code stringlengths 3 1.01M | repo_name stringlengths 5 116 | path stringlengths 3 311 | language stringclasses 30 values | license stringclasses 15 values | size int64 3 1.01M |
|---|---|---|---|---|---|
using eCommerceSoa.DataAccess.Contract;
namespace eCommerceSoa.DataAccess
{
public class Repository<T> : IRepository<T> where T : IEntity
{
private readonly ICommandHandler _requestHandler;
private readonly IUnitOfWork _unitOfWork;
public Repository(ICommandHandler requestHandler, IUnitOfWork unitOfWork)
{
_requestHandler = requestHandler;
_unitOfWork = unitOfWork;
}
public void Create(T obj)
{
_unitOfWork.NewEntities.Add(obj);
}
public void Update(T obj)
{
_unitOfWork.ChangedEntities.Add(obj);
}
public void Delete(T obj)
{
_unitOfWork.RemovedEntities.Add(obj);
}
public T GetById(long id)
{
return _requestHandler.Execute<long, T>(id);
}
public void Save()
{
if(_unitOfWork.Commit())
_unitOfWork.Rollback();
}
}
}
| nazeemkhan77/eCommerceSoa | eCommerceSoa/DataAccess/Repository.cs | C# | apache-2.0 | 1,045 |
# Copyright 2016-2018 Michael Peters
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import cProfile
from scipy.stats import norm
# annotate a function with @profile to see where it's spending the most time
def profile(func):
def profiled_func(*args, **kwargs):
p = cProfile.Profile()
try:
p.enable()
result = func(*args, **kwargs)
p.disable()
return result
finally:
p.print_stats()
return profiled_func
# annotate a function with @print_models
def print_models(func):
def printed_func(*args, **kwargs):
model = func(*args, **kwargs)
cv_keys = ('mean_test_score', 'std_test_score', 'params')
for r, _ in enumerate(model.cv_results_['mean_test_score']):
print("%0.3f +/- %0.2f %r" % (model.cv_results_[cv_keys[0]][r],
model.cv_results_[cv_keys[1]][r] / 2.0,
model.cv_results_[cv_keys[2]][r]))
print('Best parameters: %s' % model.best_params_)
print('Best accuracy: %.2f' % model.best_score_)
return model
return printed_func
# https://www.pro-football-reference.com/about/win_prob.htm
def mov_to_win_percent(u, m=11, offset=0):
u = u + offset
return 1 - norm.cdf(0.5, loc=u, scale=m) + .5 * (norm.cdf(0.5, loc=u, scale=m) - norm.cdf(-0.5, loc=u, scale=m))
| opiethehokie/march-madness-predictions | ml/util.py | Python | apache-2.0 | 1,932 |
/*
* Copyright 2013 Monoscape
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* History:
* 2011/11/10 Imesh Gunaratne <imesh@monoscape.org> Created.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
using Monoscape.Common.Model;
namespace Monoscape.NodeController.Api.Services.ApplicationGrid.Model
{
[DataContract]
public class NcAddApplicationRequest : AbstractApplicationRequest
{
[DataMember]
public Application Application { get; set; }
public NcAddApplicationRequest(MonoscapeCredentials credentials)
: base(credentials)
{
}
}
}
| monoscape/monoscape | Monoscape.NodeController.Api/Services/ApplicationGrid/Model/NcAddApplicationRequest.cs | C# | apache-2.0 | 1,212 |
package heng.shi.controller;
import heng.shi.entity.User;
import heng.shi.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* Created by shihe on 2016/12/21.
*/
@RestController
@RequestMapping(value = "/user")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping(value = "/{userId}")
public User findOne(@PathVariable(value = "userId") Long id) {
return userService.findOne(id);
}
@RequestMapping(value = "/create")
public User create(User user) {
return userService.save(user);
}
@RequestMapping(value = "/delete")
public void delete(Long id) {
userService.delete(id);
}
}
| Pabears/happy-reading-happy-writing | src/main/java/heng/shi/controller/UserController.java | Java | apache-2.0 | 911 |
<!doctype html public "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html>
<head>
<title>PHPXRef 0.7.1 : Unnamed Project : Variable Reference: $step</title>
<link rel="stylesheet" href="../sample.css" type="text/css">
<link rel="stylesheet" href="../sample-print.css" type="text/css" media="print">
<style id="hilight" type="text/css"></style>
<meta http-equiv="content-type" content="text/html;charset=iso-8859-1">
</head>
<body bgcolor="#ffffff" text="#000000" link="#801800" vlink="#300540" alink="#ffffff">
<table class="pagetitle" width="100%">
<tr>
<td valign="top" class="pagetitle">
[ <a href="../index.html">Index</a> ]
</td>
<td align="right" class="pagetitle">
<h2 style="margin-bottom: 0px">PHP Cross Reference of Unnamed Project</h2>
</td>
</tr>
</table>
<!-- Generated by PHPXref 0.7.1 at Thu Oct 23 19:15:14 2014 -->
<!-- PHPXref (c) 2000-2010 Gareth Watts - gareth@omnipotent.net -->
<!-- http://phpxref.sourceforge.net/ -->
<script src="../phpxref.js" type="text/javascript"></script>
<script language="JavaScript" type="text/javascript">
<!--
ext='.html';
relbase='../';
subdir='_variables';
filename='index.html';
cookiekey='phpxref';
handleNavFrame(relbase, subdir, filename);
logVariable('step');
// -->
</script>
<script language="JavaScript" type="text/javascript">
if (gwGetCookie('xrefnav')=='off')
document.write('<p class="navlinks">[ <a href="javascript:navOn()">Show Explorer<\/a> ]<\/p>');
else
document.write('<p class="navlinks">[ <a href="javascript:navOff()">Hide Explorer<\/a> ]<\/p>');
</script>
<noscript>
<p class="navlinks">
[ <a href="../nav.html" target="_top">Show Explorer</a> ]
[ <a href="index.html" target="_top">Hide Navbar</a> ]
</p>
</noscript>
[<a href="../index.html">Top level directory</a>]<br>
<script language="JavaScript" type="text/javascript">
<!--
document.writeln('<table align="right" class="searchbox-link"><tr><td><a class="searchbox-link" href="javascript:void(0)" onMouseOver="showSearchBox()">Search</a><br>');
document.writeln('<table border="0" cellspacing="0" cellpadding="0" class="searchbox" id="searchbox">');
document.writeln('<tr><td class="searchbox-title">');
document.writeln('<a class="searchbox-title" href="javascript:showSearchPopup()">Search History +</a>');
document.writeln('<\/td><\/tr>');
document.writeln('<tr><td class="searchbox-body" id="searchbox-body">');
document.writeln('<form name="search" style="margin:0px; padding:0px" onSubmit=\'return jump()\'>');
document.writeln('<a class="searchbox-body" href="../_classes/index.html">Class<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="classname"><br>');
document.writeln('<a id="funcsearchlink" class="searchbox-body" href="../_functions/index.html">Function<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="funcname"><br>');
document.writeln('<a class="searchbox-body" href="../_variables/index.html">Variable<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="varname"><br>');
document.writeln('<a class="searchbox-body" href="../_constants/index.html">Constant<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="constname"><br>');
document.writeln('<a class="searchbox-body" href="../_tables/index.html">Table<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="tablename"><br>');
document.writeln('<input type="submit" class="searchbox-button" value="Search">');
document.writeln('<\/form>');
document.writeln('<\/td><\/tr><\/table>');
document.writeln('<\/td><\/tr><\/table>');
// -->
</script>
<div id="search-popup" class="searchpopup"><p id="searchpopup-title" class="searchpopup-title">title</p><div id="searchpopup-body" class="searchpopup-body">Body</div><p class="searchpopup-close"><a href="javascript:gwCloseActive()">[close]</a></p></div>
<h3>Variable Cross Reference</h3>
<h2><a href="index.html#step">$step</a></h2>
<b>Defined at:</b><ul>
<li><a href="../bonfire/codeigniter/libraries/Migration.php.html">/bonfire/codeigniter/libraries/Migration.php</A> -> <a href="../bonfire/codeigniter/libraries/Migration.php.source.html#l105"> line 105</A></li>
<li><a href="../bonfire/codeigniter/libraries/Migration.php.html">/bonfire/codeigniter/libraries/Migration.php</A> -> <a href="../bonfire/codeigniter/libraries/Migration.php.source.html#l110"> line 110</A></li>
<li><a href="../tests/simpletest/mock_objects.php.html">/tests/simpletest/mock_objects.php</A> -> <a href="../tests/simpletest/mock_objects.php.source.html#l1110"> line 1110</A></li>
<li><a href="../bonfire/modules/migrations/libraries/Migrations.php.html">/bonfire/modules/migrations/libraries/Migrations.php</A> -> <a href="../bonfire/modules/migrations/libraries/Migrations.php.source.html#l239"> line 239</A></li>
<li><a href="../bonfire/modules/migrations/libraries/Migrations.php.html">/bonfire/modules/migrations/libraries/Migrations.php</A> -> <a href="../bonfire/modules/migrations/libraries/Migrations.php.source.html#l244"> line 244</A></li>
<li><a href="../tests/simpletest/dumper.php.html">/tests/simpletest/dumper.php</A> -> <a href="../tests/simpletest/dumper.php.source.html#l383"> line 383</A></li>
<li><a href="../tests/simpletest/dumper.php.html">/tests/simpletest/dumper.php</A> -> <a href="../tests/simpletest/dumper.php.source.html#l385"> line 385</A></li>
</ul>
<br><b>Referenced 33 times:</b><ul>
<li><a href="../bonfire/codeigniter/libraries/Migration.php.html">/bonfire/codeigniter/libraries/Migration.php</a> -> <a href="../bonfire/codeigniter/libraries/Migration.php.source.html#l105"> line 105</a></li>
<li><a href="../bonfire/codeigniter/libraries/Migration.php.html">/bonfire/codeigniter/libraries/Migration.php</a> -> <a href="../bonfire/codeigniter/libraries/Migration.php.source.html#l110"> line 110</a></li>
<li><a href="../bonfire/codeigniter/libraries/Migration.php.html">/bonfire/codeigniter/libraries/Migration.php</a> -> <a href="../bonfire/codeigniter/libraries/Migration.php.source.html#l113"> line 113</a></li>
<li><a href="../bonfire/codeigniter/libraries/Migration.php.html">/bonfire/codeigniter/libraries/Migration.php</a> -> <a href="../bonfire/codeigniter/libraries/Migration.php.source.html#l118"> line 118</a></li>
<li><a href="../bonfire/codeigniter/libraries/Migration.php.html">/bonfire/codeigniter/libraries/Migration.php</a> -> <a href="../bonfire/codeigniter/libraries/Migration.php.source.html#l134"> line 134</a></li>
<li><a href="../bonfire/codeigniter/libraries/Migration.php.html">/bonfire/codeigniter/libraries/Migration.php</a> -> <a href="../bonfire/codeigniter/libraries/Migration.php.source.html#l186"> line 186</a></li>
<li><a href="../bonfire/codeigniter/libraries/Migration.php.html">/bonfire/codeigniter/libraries/Migration.php</a> -> <a href="../bonfire/codeigniter/libraries/Migration.php.source.html#l203"> line 203</a></li>
<li><a href="../tests/simpletest/mock_objects.php.html">/tests/simpletest/mock_objects.php</a> -> <a href="../tests/simpletest/mock_objects.php.source.html#l413"> line 413</a></li>
<li><a href="../tests/simpletest/mock_objects.php.html">/tests/simpletest/mock_objects.php</a> -> <a href="../tests/simpletest/mock_objects.php.source.html#l419"> line 419</a></li>
<li><a href="../tests/simpletest/mock_objects.php.html">/tests/simpletest/mock_objects.php</a> -> <a href="../tests/simpletest/mock_objects.php.source.html#l420"> line 420</a></li>
<li><a href="../tests/simpletest/mock_objects.php.html">/tests/simpletest/mock_objects.php</a> -> <a href="../tests/simpletest/mock_objects.php.source.html#l422"> line 422</a></li>
<li><a href="../tests/simpletest/mock_objects.php.html">/tests/simpletest/mock_objects.php</a> -> <a href="../tests/simpletest/mock_objects.php.source.html#l449"> line 449</a></li>
<li><a href="../tests/simpletest/mock_objects.php.html">/tests/simpletest/mock_objects.php</a> -> <a href="../tests/simpletest/mock_objects.php.source.html#l451"> line 451</a></li>
<li><a href="../tests/simpletest/mock_objects.php.html">/tests/simpletest/mock_objects.php</a> -> <a href="../tests/simpletest/mock_objects.php.source.html#l452"> line 452</a></li>
<li><a href="../tests/simpletest/mock_objects.php.html">/tests/simpletest/mock_objects.php</a> -> <a href="../tests/simpletest/mock_objects.php.source.html#l453"> line 453</a></li>
<li><a href="../tests/simpletest/mock_objects.php.html">/tests/simpletest/mock_objects.php</a> -> <a href="../tests/simpletest/mock_objects.php.source.html#l1110"> line 1110</a></li>
<li><a href="../tests/simpletest/mock_objects.php.html">/tests/simpletest/mock_objects.php</a> -> <a href="../tests/simpletest/mock_objects.php.source.html#l1112"> line 1112</a></li>
<li><a href="../tests/simpletest/mock_objects.php.html">/tests/simpletest/mock_objects.php</a> -> <a href="../tests/simpletest/mock_objects.php.source.html#l1115"> line 1115</a></li>
<li><a href="../tests/simpletest/mock_objects.php.html">/tests/simpletest/mock_objects.php</a> -> <a href="../tests/simpletest/mock_objects.php.source.html#l1134"> line 1134</a></li>
<li><a href="../tests/simpletest/mock_objects.php.html">/tests/simpletest/mock_objects.php</a> -> <a href="../tests/simpletest/mock_objects.php.source.html#l1135"> line 1135</a></li>
<li><a href="../bonfire/modules/migrations/libraries/Migrations.php.html">/bonfire/modules/migrations/libraries/Migrations.php</a> -> <a href="../bonfire/modules/migrations/libraries/Migrations.php.source.html#l239"> line 239</a></li>
<li><a href="../bonfire/modules/migrations/libraries/Migrations.php.html">/bonfire/modules/migrations/libraries/Migrations.php</a> -> <a href="../bonfire/modules/migrations/libraries/Migrations.php.source.html#l244"> line 244</a></li>
<li><a href="../bonfire/modules/migrations/libraries/Migrations.php.html">/bonfire/modules/migrations/libraries/Migrations.php</a> -> <a href="../bonfire/modules/migrations/libraries/Migrations.php.source.html#l247"> line 247</a></li>
<li><a href="../bonfire/modules/migrations/libraries/Migrations.php.html">/bonfire/modules/migrations/libraries/Migrations.php</a> -> <a href="../bonfire/modules/migrations/libraries/Migrations.php.source.html#l253"> line 253</a></li>
<li><a href="../bonfire/modules/migrations/libraries/Migrations.php.html">/bonfire/modules/migrations/libraries/Migrations.php</a> -> <a href="../bonfire/modules/migrations/libraries/Migrations.php.source.html#l268"> line 268</a></li>
<li><a href="../bonfire/modules/migrations/libraries/Migrations.php.html">/bonfire/modules/migrations/libraries/Migrations.php</a> -> <a href="../bonfire/modules/migrations/libraries/Migrations.php.source.html#l317"> line 317</a></li>
<li><a href="../bonfire/modules/migrations/libraries/Migrations.php.html">/bonfire/modules/migrations/libraries/Migrations.php</a> -> <a href="../bonfire/modules/migrations/libraries/Migrations.php.source.html#l367"> line 367</a></li>
<li><a href="../tests/simpletest/dumper.php.html">/tests/simpletest/dumper.php</a> -> <a href="../tests/simpletest/dumper.php.source.html#l383"> line 383</a></li>
<li><a href="../tests/simpletest/dumper.php.html">/tests/simpletest/dumper.php</a> -> <a href="../tests/simpletest/dumper.php.source.html#l384"> line 384</a></li>
<li><a href="../tests/simpletest/dumper.php.html">/tests/simpletest/dumper.php</a> -> <a href="../tests/simpletest/dumper.php.source.html#l385"> line 385</a></li>
<li><a href="../tests/simpletest/dumper.php.html">/tests/simpletest/dumper.php</a> -> <a href="../tests/simpletest/dumper.php.source.html#l385"> line 385</a></li>
<li><a href="../tests/simpletest/dumper.php.html">/tests/simpletest/dumper.php</a> -> <a href="../tests/simpletest/dumper.php.source.html#l386"> line 386</a></li>
<li><a href="../tests/simpletest/dumper.php.html">/tests/simpletest/dumper.php</a> -> <a href="../tests/simpletest/dumper.php.source.html#l387"> line 387</a></li>
</ul>
<!-- A link to the phpxref site in your customized footer file is appreciated ;-) -->
<br><hr>
<table width="100%">
<tr><td>Generated: Thu Oct 23 19:15:14 2014</td>
<td align="right"><i>Cross-referenced by <a href="http://phpxref.sourceforge.net/">PHPXref 0.7.1</a></i></td>
</tr>
</table>
</body></html>
| inputx/code-ref-doc | rebbit/_variables/step.html | HTML | apache-2.0 | 12,278 |
<!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"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.13"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>Neodroid: /home/heider/Projects/Neodroid/Unity/Examples/Assets/droid/Runtime/Interfaces/IHasByteArray.cs File Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="navtree.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="resize.js"></script>
<script type="text/javascript" src="navtreedata.js"></script>
<script type="text/javascript" src="navtree.js"></script>
<script type="text/javascript">
$(document).ready(initResizable);
</script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/searchdata.js"></script>
<script type="text/javascript" src="search/search.js"></script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td id="projectlogo"><img alt="Logo" src="neodroidcropped124.png"/></td>
<td id="projectalign" style="padding-left: 0.5em;">
<div id="projectname">Neodroid
 <span id="projectnumber">0.2.0</span>
</div>
<div id="projectbrief">Machine Learning Environment Prototyping Tool</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.13 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "search",false,'Search');
</script>
<script type="text/javascript" src="menudata.js"></script>
<script type="text/javascript" src="menu.js"></script>
<script type="text/javascript">
$(function() {
initMenu('',true,false,'search.php','Search');
$(document).ready(function() { init_search(); });
});
</script>
<div id="main-nav"></div>
</div><!-- top -->
<div id="side-nav" class="ui-resizable side-nav-resizable">
<div id="nav-tree">
<div id="nav-tree-contents">
<div id="nav-sync" class="sync"></div>
</div>
</div>
<div id="splitbar" style="-moz-user-select:none;"
class="ui-resizable-handle">
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){initNavTree('_i_has_byte_array_8cs.html','');});
</script>
<div id="doc-content">
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<div class="header">
<div class="summary">
<a href="#nested-classes">Classes</a> |
<a href="#namespaces">Namespaces</a> </div>
<div class="headertitle">
<div class="title">IHasByteArray.cs File Reference</div> </div>
</div><!--header-->
<div class="contents">
<p><a href="_i_has_byte_array_8cs_source.html">Go to the source code of this file.</a></p>
<table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="nested-classes"></a>
Classes</h2></td></tr>
<tr class="memitem:"><td class="memItemLeft" align="right" valign="top">interface  </td><td class="memItemRight" valign="bottom"><a class="el" href="interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_has_byte_array.html">droid.Runtime.Interfaces.IHasByteArray</a></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
</table><table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="namespaces"></a>
Namespaces</h2></td></tr>
<tr class="memitem:namespacedroid_1_1_runtime_1_1_interfaces"><td class="memItemLeft" align="right" valign="top">namespace  </td><td class="memItemRight" valign="bottom"><a class="el" href="namespacedroid_1_1_runtime_1_1_interfaces.html">droid.Runtime.Interfaces</a></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
</table>
</div><!-- contents -->
</div><!-- doc-content -->
<!-- start footer part -->
<div id="nav-path" class="navpath"><!-- id is needed for treeview function! -->
<ul>
<li class="navelem"><a class="el" href="dir_4f6666a8f2ab10bc970eb7559668f031.html">Runtime</a></li><li class="navelem"><a class="el" href="dir_72e30cb13ec7f0b6aa475169ab72c9f9.html">Interfaces</a></li><li class="navelem"><a class="el" href="_i_has_byte_array_8cs.html">IHasByteArray.cs</a></li>
<li class="footer">Generated by
<a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.8.13 </li>
</ul>
</div>
</body>
</html>
| sintefneodroid/droid | docs/cvs/_i_has_byte_array_8cs.html | HTML | apache-2.0 | 5,241 |
package org.jetbrains.plugins.scala.traceLogViewer.selection
import java.util.concurrent.atomic.AtomicReference
import java.util.{Timer, TimerTask}
import scala.concurrent.duration.Duration
/**
* Executes scheduled tasks.
*
* If a task is scheduled while there is another scheduled task,
* the earlier task will NOT be executed.
*/
class LastTaskTimer {
private val timer = new Timer
private val currentTask = new AtomicReference[TimerTask](null)
def schedule(time: Duration)(body: => Unit): Unit = {
val task: TimerTask = new TimerTask {
override def run(): Unit = {
if (currentTask.get() == this) {
body
}
}
}
currentTask.set(task)
timer.schedule(task, time.toMillis)
}
}
| JetBrains/intellij-scala | scala/traceLogViewer/src/org/jetbrains/plugins/scala/traceLogViewer/selection/LastTaskTimer.scala | Scala | apache-2.0 | 744 |
---
layout: "docs_api"
version: "1.3.3"
versionHref: "/docs/v1"
path: "api/directive/ionPane/"
title: "ion-pane"
header_sub_title: "Directive in module ionic"
doc: "ionPane"
docType: "directive"
---
<div class="improve-docs">
<a href='https://github.com/ionic-team/ionic-v1/blob/master/js/angular/directive/pane.js#L2'>
View Source
</a>
<a href='http://github.com/ionic-team/ionic/edit/1.x/js/angular/directive/pane.js#L2'>
Improve this doc
</a>
</div>
<h1 class="api-title">
ion-pane
</h1>
A simple container that fits content, with no side effects. Adds the 'pane' class to the element.
<h2 id="usage">Usage</h2>
```html
<ion-pane>
...
</ion-pane>
```
| driftyco/ionic-site | content/docs/v1/api/directive/ionPane/index.md | Markdown | apache-2.0 | 698 |
// Copyright 2015 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.worker;
import static java.nio.charset.StandardCharsets.UTF_8;
import com.google.common.base.Charsets;
import com.google.common.base.MoreObjects;
import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import com.google.common.collect.Multimap;
import com.google.common.eventbus.EventBus;
import com.google.common.hash.HashCode;
import com.google.devtools.build.lib.actions.ActionExecutionContext;
import com.google.devtools.build.lib.actions.ActionExecutionMetadata;
import com.google.devtools.build.lib.actions.ActionInput;
import com.google.devtools.build.lib.actions.ActionInputFileCache;
import com.google.devtools.build.lib.actions.ActionInputHelper;
import com.google.devtools.build.lib.actions.ActionStatusMessage;
import com.google.devtools.build.lib.actions.ExecException;
import com.google.devtools.build.lib.actions.ExecutionStrategy;
import com.google.devtools.build.lib.actions.Executor;
import com.google.devtools.build.lib.actions.ResourceManager;
import com.google.devtools.build.lib.actions.ResourceManager.ResourceHandle;
import com.google.devtools.build.lib.actions.SandboxedSpawnActionContext;
import com.google.devtools.build.lib.actions.Spawn;
import com.google.devtools.build.lib.actions.SpawnActionContext;
import com.google.devtools.build.lib.actions.UserExecException;
import com.google.devtools.build.lib.analysis.BlazeDirectories;
import com.google.devtools.build.lib.events.Event;
import com.google.devtools.build.lib.events.EventHandler;
import com.google.devtools.build.lib.sandbox.SandboxHelpers;
import com.google.devtools.build.lib.sandbox.SpawnHelpers;
import com.google.devtools.build.lib.standalone.StandaloneSpawnStrategy;
import com.google.devtools.build.lib.util.CommandFailureUtils;
import com.google.devtools.build.lib.util.Preconditions;
import com.google.devtools.build.lib.util.io.FileOutErr;
import com.google.devtools.build.lib.vfs.Path;
import com.google.devtools.build.lib.vfs.PathFragment;
import com.google.devtools.build.lib.worker.WorkerProtocol.WorkRequest;
import com.google.devtools.build.lib.worker.WorkerProtocol.WorkResponse;
import com.google.protobuf.ByteString;
import java.io.ByteArrayOutputStream;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;
import java.util.regex.Pattern;
/**
* A spawn action context that launches Spawns the first time they are used in a persistent mode and
* then shards work over all the processes.
*/
@ExecutionStrategy(
name = {"worker"},
contextType = SpawnActionContext.class
)
public final class WorkerSpawnStrategy implements SandboxedSpawnActionContext {
/**
* An input stream filter that records the first X bytes read from its wrapped stream.
*
* <p>The number bytes to record can be set via {@link #startRecording(int)}}, which also discards
* any already recorded data. The recorded data can be retrieved via {@link
* #getRecordedDataAsString(Charset)}.
*/
private static final class RecordingInputStream extends FilterInputStream {
private static final Pattern NON_PRINTABLE_CHARS =
Pattern.compile("[^\\p{Print}\\t\\r\\n]", Pattern.UNICODE_CHARACTER_CLASS);
private ByteArrayOutputStream recordedData;
private int maxRecordedSize;
protected RecordingInputStream(InputStream in) {
super(in);
}
/**
* Returns the maximum number of bytes that can still be recorded in our buffer (but not more
* than {@code size}).
*/
private int getRecordableBytes(int size) {
if (recordedData == null) {
return 0;
}
return Math.min(maxRecordedSize - recordedData.size(), size);
}
@Override
public int read() throws IOException {
int bytesRead = super.read();
if (getRecordableBytes(bytesRead) > 0) {
recordedData.write(bytesRead);
}
return bytesRead;
}
@Override
public int read(byte[] b) throws IOException {
int bytesRead = super.read(b);
int recordableBytes = getRecordableBytes(bytesRead);
if (recordableBytes > 0) {
recordedData.write(b, 0, recordableBytes);
}
return bytesRead;
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
int bytesRead = super.read(b, off, len);
int recordableBytes = getRecordableBytes(bytesRead);
if (recordableBytes > 0) {
recordedData.write(b, off, recordableBytes);
}
return bytesRead;
}
public void startRecording(int maxSize) {
recordedData = new ByteArrayOutputStream(maxSize);
maxRecordedSize = maxSize;
}
/**
* Reads whatever remaining data is available on the input stream if we still have space left in
* the recording buffer, in order to maximize the usefulness of the recorded data for the
* caller.
*/
public void readRemaining() {
try {
byte[] dummy = new byte[getRecordableBytes(available())];
read(dummy);
} catch (IOException e) {
// Ignore.
}
}
/**
* Returns the recorded data as a string, where non-printable characters are replaced with a '?'
* symbol.
*/
public String getRecordedDataAsString(Charset charsetName) throws UnsupportedEncodingException {
String recordedString = recordedData.toString(charsetName.name());
return NON_PRINTABLE_CHARS.matcher(recordedString).replaceAll("?").trim();
}
}
public static final String ERROR_MESSAGE_PREFIX =
"Worker strategy cannot execute this %s action, ";
public static final String REASON_NO_FLAGFILE =
"because the command-line arguments do not contain at least one @flagfile or --flagfile=";
public static final String REASON_NO_TOOLS = "because the action has no tools";
public static final String REASON_NO_EXECUTION_INFO =
"because the action's execution info does not contain 'supports-workers=1'";
/** Pattern for @flagfile.txt and --flagfile=flagfile.txt */
private static final Pattern FLAG_FILE_PATTERN = Pattern.compile("(?:@|--?flagfile=)(.+)");
private final WorkerPool workers;
private final Path execRoot;
private final boolean verboseFailures;
private final int maxRetries;
private final Multimap<String, String> extraFlags;
private final boolean workerVerbose;
public WorkerSpawnStrategy(
BlazeDirectories blazeDirs,
WorkerPool workers,
boolean verboseFailures,
int maxRetries,
boolean workerVerbose,
Multimap<String, String> extraFlags) {
Preconditions.checkNotNull(workers);
this.workers = Preconditions.checkNotNull(workers);
this.execRoot = blazeDirs.getExecRoot();
this.verboseFailures = verboseFailures;
this.maxRetries = maxRetries;
this.workerVerbose = workerVerbose;
this.extraFlags = extraFlags;
}
@Override
public void exec(Spawn spawn, ActionExecutionContext actionExecutionContext)
throws ExecException, InterruptedException {
exec(spawn, actionExecutionContext, null);
}
@Override
public void exec(
Spawn spawn,
ActionExecutionContext actionExecutionContext,
AtomicReference<Class<? extends SpawnActionContext>> writeOutputFiles)
throws ExecException, InterruptedException {
Executor executor = actionExecutionContext.getExecutor();
if (!spawn.getExecutionInfo().containsKey("supports-workers")
|| !spawn.getExecutionInfo().get("supports-workers").equals("1")) {
StandaloneSpawnStrategy standaloneStrategy =
Preconditions.checkNotNull(executor.getContext(StandaloneSpawnStrategy.class));
executor.getEventHandler().handle(
Event.warn(
String.format(ERROR_MESSAGE_PREFIX + REASON_NO_EXECUTION_INFO, spawn.getMnemonic())));
standaloneStrategy.exec(spawn, actionExecutionContext);
return;
}
EventBus eventBus = actionExecutionContext.getExecutor().getEventBus();
ActionExecutionMetadata owner = spawn.getResourceOwner();
eventBus.post(ActionStatusMessage.schedulingStrategy(owner));
try (ResourceHandle handle =
ResourceManager.instance().acquireResources(owner, spawn.getLocalResources())) {
eventBus.post(ActionStatusMessage.runningStrategy(spawn.getResourceOwner(), "worker"));
actuallyExec(spawn, actionExecutionContext, writeOutputFiles);
}
}
private void actuallyExec(
Spawn spawn,
ActionExecutionContext actionExecutionContext,
AtomicReference<Class<? extends SpawnActionContext>> writeOutputFiles)
throws ExecException, InterruptedException {
Executor executor = actionExecutionContext.getExecutor();
EventHandler eventHandler = executor.getEventHandler();
if (executor.reportsSubcommands()) {
executor.reportSubcommand(spawn);
}
// We assume that the spawn to be executed always gets at least one @flagfile.txt or
// --flagfile=flagfile.txt argument, which contains the flags related to the work itself (as
// opposed to start-up options for the executed tool). Thus, we can extract those elements from
// its args and put them into the WorkRequest instead.
List<String> flagfiles = new ArrayList<>();
List<String> startupArgs = new ArrayList<>();
for (String arg : spawn.getArguments()) {
if (FLAG_FILE_PATTERN.matcher(arg).matches()) {
flagfiles.add(arg);
} else {
startupArgs.add(arg);
}
}
if (flagfiles.isEmpty()) {
throw new UserExecException(
String.format(ERROR_MESSAGE_PREFIX + REASON_NO_FLAGFILE, spawn.getMnemonic()));
}
if (Iterables.isEmpty(spawn.getToolFiles())) {
throw new UserExecException(
String.format(ERROR_MESSAGE_PREFIX + REASON_NO_TOOLS, spawn.getMnemonic()));
}
FileOutErr outErr = actionExecutionContext.getFileOutErr();
ImmutableList<String> args =
ImmutableList.<String>builder()
.addAll(startupArgs)
.add("--persistent_worker")
.addAll(
MoreObjects.firstNonNull(
extraFlags.get(spawn.getMnemonic()), ImmutableList.<String>of()))
.build();
ImmutableMap<String, String> env = spawn.getEnvironment();
try {
ActionInputFileCache inputFileCache = actionExecutionContext.getActionInputFileCache();
HashCode workerFilesHash = WorkerFilesHash.getWorkerFilesHash(
spawn.getToolFiles(), actionExecutionContext);
Map<PathFragment, Path> inputFiles =
new SpawnHelpers(execRoot).getMounts(spawn, actionExecutionContext);
Set<PathFragment> outputFiles = SandboxHelpers.getOutputFiles(spawn);
WorkerKey key =
new WorkerKey(
args,
env,
execRoot,
spawn.getMnemonic(),
workerFilesHash,
inputFiles,
outputFiles,
writeOutputFiles != null);
WorkRequest.Builder requestBuilder = WorkRequest.newBuilder();
for (String flagfile : flagfiles) {
expandArgument(requestBuilder, flagfile);
}
List<ActionInput> inputs =
ActionInputHelper.expandArtifacts(
spawn.getInputFiles(), actionExecutionContext.getArtifactExpander());
for (ActionInput input : inputs) {
byte[] digestBytes = inputFileCache.getDigest(input);
ByteString digest;
if (digestBytes == null) {
digest = ByteString.EMPTY;
} else {
digest = ByteString.copyFromUtf8(HashCode.fromBytes(digestBytes).toString());
}
requestBuilder
.addInputsBuilder()
.setPath(input.getExecPathString())
.setDigest(digest)
.build();
}
WorkResponse response =
execInWorker(eventHandler, key, requestBuilder.build(), maxRetries, writeOutputFiles);
outErr.getErrorStream().write(response.getOutputBytes().toByteArray());
if (response.getExitCode() != 0) {
throw new UserExecException(
String.format(
"Worker process sent response with exit code: %d.", response.getExitCode()));
}
} catch (IOException e) {
String message =
CommandFailureUtils.describeCommandFailure(
verboseFailures, spawn.getArguments(), env, execRoot.getPathString());
throw new UserExecException(message, e);
}
}
/**
* Recursively expands arguments by replacing @filename args with the contents of the referenced
* files. The @ itself can be escaped with @@. This deliberately does not expand --flagfile= style
* arguments, because we want to get rid of the expansion entirely at some point in time.
*
* @param requestBuilder the WorkRequest.Builder that the arguments should be added to.
* @param arg the argument to expand.
* @throws java.io.IOException if one of the files containing options cannot be read.
*/
private void expandArgument(WorkRequest.Builder requestBuilder, String arg) throws IOException {
if (arg.startsWith("@") && !arg.startsWith("@@")) {
for (String line : Files.readAllLines(
Paths.get(execRoot.getRelative(arg.substring(1)).getPathString()), UTF_8)) {
if (line.length() > 0) {
expandArgument(requestBuilder, line);
}
}
} else {
requestBuilder.addArguments(arg);
}
}
private WorkResponse execInWorker(
EventHandler eventHandler,
WorkerKey key,
WorkRequest request,
int retriesLeft,
AtomicReference<Class<? extends SpawnActionContext>> writeOutputFiles)
throws IOException, InterruptedException, UserExecException {
Worker worker = null;
WorkResponse response = null;
try {
worker = workers.borrowObject(key);
worker.prepareExecution(key);
request.writeDelimitedTo(worker.getOutputStream());
worker.getOutputStream().flush();
RecordingInputStream recordingStream = new RecordingInputStream(worker.getInputStream());
recordingStream.startRecording(4096);
try {
response = WorkResponse.parseDelimitedFrom(recordingStream);
} catch (IOException e2) {
// If protobuf couldn't parse the response, try to print whatever the failing worker wrote
// to stdout - it's probably a stack trace or some kind of error message that will help the
// user figure out why the compiler is failing.
recordingStream.readRemaining();
String data = recordingStream.getRecordedDataAsString(Charsets.UTF_8);
eventHandler.handle(
Event.warn("Worker process returned an unparseable WorkResponse:\n" + data));
throw e2;
}
if (writeOutputFiles != null
&& !writeOutputFiles.compareAndSet(null, WorkerSpawnStrategy.class)) {
throw new InterruptedException();
}
worker.finishExecution(key);
if (response == null) {
throw new UserExecException(
"Worker process did not return a WorkResponse. This is probably caused by a "
+ "bug in the worker, writing unexpected other data to stdout.");
}
} catch (IOException e) {
if (worker != null) {
workers.invalidateObject(key, worker);
worker = null;
}
if (retriesLeft > 0) {
// The worker process failed, but we still have some retries left. Let's retry with a fresh
// worker.
if (workerVerbose) {
eventHandler.handle(
Event.warn(
key.getMnemonic()
+ " worker failed ("
+ Throwables.getStackTraceAsString(e)
+ "), invalidating and retrying with new worker..."));
} else {
eventHandler.handle(
Event.warn(
key.getMnemonic()
+ " worker failed, invalidating and retrying with new worker..."));
}
return execInWorker(eventHandler, key, request, retriesLeft - 1, writeOutputFiles);
} else {
throw e;
}
} finally {
if (worker != null) {
workers.returnObject(key, worker);
}
}
return response;
}
@Override
public String toString() {
return "worker";
}
@Override
public boolean shouldPropagateExecException() {
return false;
}
}
| Asana/bazel | src/main/java/com/google/devtools/build/lib/worker/WorkerSpawnStrategy.java | Java | apache-2.0 | 17,363 |
class PostsController < ApplicationController
before_action :set_post, only: [:show, :edit, :update, :destroy]
load_and_authorize_resource
# GET /posts
# GET /posts.json
def index
if params[:user_id]== nil and params[:project_id]==nil and current_user.admin?
@posts = Post.all
elsif params[:user_id]!=nil
user = User.find(params[:user_id])
@posts = user.posts
elsif params[:project_id] != nil
project = Project.find(params[:project_id])
@posts = project.posts
end
end
# GET /posts/1
# GET /posts/1.json
def show
end
# GET /posts/new
def new
@post = Post.new
end
# GET /posts/1/edit
def edit
end
# POST /posts
# POST /posts.json
def create
@post = Post.new(post_params)
respond_to do |format|
if @post.save
format.html { redirect_to @post, notice: 'Post was successfully created.' }
format.json { render :show, status: :created, location: @post }
else
format.html { render :new }
format.json { render json: @post.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /posts/1
# PATCH/PUT /posts/1.json
def update
respond_to do |format|
if @post.update(post_params)
format.html { redirect_to @post, notice: 'Post was successfully updated.' }
format.json { render :show, status: :ok, location: @post }
else
format.html { render :edit }
format.json { render json: @post.errors, status: :unprocessable_entity }
end
end
end
# DELETE /posts/1
# DELETE /posts/1.json
def destroy
@post.destroy
respond_to do |format|
format.html { redirect_to posts_url, notice: 'Post was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_post
@post = Post.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def post_params
params.require(:post).permit(:content, :project_id, :user_id)
end
end
| Someluck/ProjectAccountingSystem | accounting_system/app/controllers/posts_controller.rb | Ruby | apache-2.0 | 2,237 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_45) on Thu Mar 26 16:48:33 UTC 2015 -->
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
com.hazelcast.ascii Class Hierarchy (Hazelcast Root 3.4.2 API)
</TITLE>
<META NAME="date" CONTENT="2015-03-26">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="com.hazelcast.ascii Class Hierarchy (Hazelcast Root 3.4.2 API)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Use</FONT> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Tree</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../com/hazelcast/package-tree.html"><B>PREV</B></A>
<A HREF="../../../com/hazelcast/ascii/memcache/package-tree.html"><B>NEXT</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../index.html?com/hazelcast/ascii/package-tree.html" target="_top"><B>FRAMES</B></A>
<A HREF="package-tree.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<CENTER>
<H2>
Hierarchy For Package com.hazelcast.ascii
</H2>
</CENTER>
<DL>
<DT><B>Package Hierarchies:</B><DD><A HREF="../../../overview-tree.html">All Packages</A></DL>
<HR>
<H2>
Class Hierarchy
</H2>
<UL>
<LI TYPE="circle">java.lang.<A HREF="http://download.oracle.com/javase/1.6.0/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang"><B>Object</B></A><UL>
<LI TYPE="circle">com.hazelcast.ascii.<A HREF="../../../com/hazelcast/ascii/AbstractTextCommand.html" title="class in com.hazelcast.ascii"><B>AbstractTextCommand</B></A> (implements com.hazelcast.ascii.<A HREF="../../../com/hazelcast/ascii/TextCommand.html" title="interface in com.hazelcast.ascii">TextCommand</A>)
<UL>
<LI TYPE="circle">com.hazelcast.ascii.<A HREF="../../../com/hazelcast/ascii/NoOpCommand.html" title="class in com.hazelcast.ascii"><B>NoOpCommand</B></A></UL>
<LI TYPE="circle">com.hazelcast.ascii.<A HREF="../../../com/hazelcast/ascii/AbstractTextCommandProcessor.html" title="class in com.hazelcast.ascii"><B>AbstractTextCommandProcessor</B></A><T> (implements com.hazelcast.ascii.<A HREF="../../../com/hazelcast/ascii/TextCommandProcessor.html" title="interface in com.hazelcast.ascii">TextCommandProcessor</A><T>)
<UL>
<LI TYPE="circle">com.hazelcast.ascii.<A HREF="../../../com/hazelcast/ascii/NoOpCommandProcessor.html" title="class in com.hazelcast.ascii"><B>NoOpCommandProcessor</B></A></UL>
<LI TYPE="circle">com.hazelcast.ascii.<A HREF="../../../com/hazelcast/ascii/TextCommandConstants.html" title="class in com.hazelcast.ascii"><B>TextCommandConstants</B></A><LI TYPE="circle">com.hazelcast.ascii.<A HREF="../../../com/hazelcast/ascii/TextCommandServiceImpl.html" title="class in com.hazelcast.ascii"><B>TextCommandServiceImpl</B></A> (implements com.hazelcast.ascii.<A HREF="../../../com/hazelcast/ascii/TextCommandService.html" title="interface in com.hazelcast.ascii">TextCommandService</A>)
<LI TYPE="circle">com.hazelcast.ascii.<A HREF="../../../com/hazelcast/ascii/TypeAwareCommandParser.html" title="class in com.hazelcast.ascii"><B>TypeAwareCommandParser</B></A> (implements com.hazelcast.ascii.<A HREF="../../../com/hazelcast/ascii/CommandParser.html" title="interface in com.hazelcast.ascii">CommandParser</A>)
</UL>
</UL>
<H2>
Interface Hierarchy
</H2>
<UL>
<LI TYPE="circle">com.hazelcast.ascii.<A HREF="../../../com/hazelcast/ascii/CommandParser.html" title="interface in com.hazelcast.ascii"><B>CommandParser</B></A><LI TYPE="circle">com.hazelcast.nio.<A HREF="../../../com/hazelcast/nio/SocketReadable.html" title="interface in com.hazelcast.nio"><B>SocketReadable</B></A><UL>
<LI TYPE="circle">com.hazelcast.ascii.<A HREF="../../../com/hazelcast/ascii/TextCommand.html" title="interface in com.hazelcast.ascii"><B>TextCommand</B></A> (also extends com.hazelcast.nio.<A HREF="../../../com/hazelcast/nio/SocketWritable.html" title="interface in com.hazelcast.nio">SocketWritable</A>)
</UL>
<LI TYPE="circle">com.hazelcast.nio.<A HREF="../../../com/hazelcast/nio/SocketWritable.html" title="interface in com.hazelcast.nio"><B>SocketWritable</B></A><UL>
<LI TYPE="circle">com.hazelcast.ascii.<A HREF="../../../com/hazelcast/ascii/TextCommand.html" title="interface in com.hazelcast.ascii"><B>TextCommand</B></A> (also extends com.hazelcast.nio.<A HREF="../../../com/hazelcast/nio/SocketReadable.html" title="interface in com.hazelcast.nio">SocketReadable</A>)
</UL>
<LI TYPE="circle">com.hazelcast.ascii.<A HREF="../../../com/hazelcast/ascii/TextCommandProcessor.html" title="interface in com.hazelcast.ascii"><B>TextCommandProcessor</B></A><T><LI TYPE="circle">com.hazelcast.ascii.<A HREF="../../../com/hazelcast/ascii/TextCommandService.html" title="interface in com.hazelcast.ascii"><B>TextCommandService</B></A></UL>
<H2>
Enum Hierarchy
</H2>
<UL>
<LI TYPE="circle">java.lang.<A HREF="http://download.oracle.com/javase/1.6.0/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang"><B>Object</B></A><UL>
<LI TYPE="circle">java.lang.<A HREF="http://download.oracle.com/javase/1.6.0/docs/api/java/lang/Enum.html?is-external=true" title="class or interface in java.lang"><B>Enum</B></A><E> (implements java.lang.<A HREF="http://download.oracle.com/javase/1.6.0/docs/api/java/lang/Comparable.html?is-external=true" title="class or interface in java.lang">Comparable</A><T>, java.io.<A HREF="http://download.oracle.com/javase/1.6.0/docs/api/java/io/Serializable.html?is-external=true" title="class or interface in java.io">Serializable</A>)
<UL>
<LI TYPE="circle">com.hazelcast.ascii.<A HREF="../../../com/hazelcast/ascii/TextCommandConstants.TextCommandType.html" title="enum in com.hazelcast.ascii"><B>TextCommandConstants.TextCommandType</B></A></UL>
</UL>
</UL>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Use</FONT> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Tree</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../com/hazelcast/package-tree.html"><B>PREV</B></A>
<A HREF="../../../com/hazelcast/ascii/memcache/package-tree.html"><B>NEXT</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../index.html?com/hazelcast/ascii/package-tree.html" target="_top"><B>FRAMES</B></A>
<A HREF="package-tree.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
Copyright © 2015 <a href="http://www.hazelcast.com/">Hazelcast, Inc.</a>. All Rights Reserved.
</BODY>
</HTML>
| akiskip/KoDeMat-Collaboration-Platform-Application | KoDeMat_TouchScreen/lib/hazelcast-3.4.2/hazelcast-3.4.2/docs/javadoc/com/hazelcast/ascii/package-tree.html | HTML | apache-2.0 | 10,532 |
package dao
import (
"context"
"crypto/hmac"
"crypto/sha1"
"encoding/base64"
"errors"
"fmt"
"hash"
"net/http"
"strconv"
"strings"
"time"
"go-common/library/log"
"go-common/library/net/trace"
)
const (
_uploadURL = "/%s"
_family = "http_client"
_template = "%s\n%s\n\n%d\n"
_method = "PUT"
_fileType = "txt"
)
var (
errUpload = errors.New("Upload failed")
)
// Upload upload picture or log file to bfs
func (d *Dao) Upload(c context.Context, content string, expire int64) (location string, err error) {
var (
url string
req *http.Request
resp *http.Response
header http.Header
code string
)
bfsConf := d.c.Bfs
url = fmt.Sprintf(bfsConf.Addr+_uploadURL, bfsConf.Bucket)
if req, err = http.NewRequest(_method, url, strings.NewReader(content)); err != nil {
log.Error("http.NewRequest() Upload(%v) error(%v)", url, err)
return
}
authorization := authorize(bfsConf.Key, bfsConf.Secret, _method, bfsConf.Bucket, expire)
req.Header.Set("Host", bfsConf.Addr)
req.Header.Add("Date", fmt.Sprint(expire))
req.Header.Add("Authorization", authorization)
req.Header.Add("Content-Type", _fileType)
if t, ok := trace.FromContext(c); ok {
t = t.Fork(_family, req.URL.Path)
defer t.Finish(&err)
}
c, cancel := context.WithTimeout(c, time.Duration(d.c.Bfs.Timeout))
req = req.WithContext(c)
defer cancel()
resp, err = d.bfsClient.Do(req)
if err != nil {
log.Error("bfsClient.Do(%s) error(%v)", url, err)
return
}
if resp.StatusCode != http.StatusOK {
log.Error("Upload url(%s) http.statuscode:%d", url, resp.StatusCode)
err = errUpload
return
}
header = resp.Header
code = header.Get("Code")
if code != strconv.Itoa(http.StatusOK) {
log.Error("Upload url(%s) code:%s", url, code)
err = errUpload
return
}
location = header.Get("Location")
return
}
// authorize returns authorization for upload file to bfs
func authorize(key, secret, method, bucket string, expire int64) (authorization string) {
var (
content string
mac hash.Hash
signature string
)
content = fmt.Sprintf(_template, method, bucket, expire)
mac = hmac.New(sha1.New, []byte(secret))
mac.Write([]byte(content))
signature = base64.StdEncoding.EncodeToString(mac.Sum(nil))
authorization = fmt.Sprintf("%s:%s:%d", key, signature, expire)
return
}
| LQJJ/demo | 126-go-common-master/app/interface/main/web/dao/bfs.go | GO | apache-2.0 | 2,315 |
/* Yukon Admin all functions
*
* Content:
*
* 1. Helpers
* 2. Common functions
* 3. Plugins
*
* */
$(function () {
// bootstrap custom functions
yukon_bs_custom.accordion_active_class();
yukon_bs_custom.dropdown_click();
yukon_bs_custom.tooltips_init();
yukon_bs_custom.popover_init();
// switchery
yukon_switchery.init();
// side menu
yukon_main_menu.init();
// style switcher
yukon_style_switcher.init();
// typeahead (header)
yukon_typeahead.init();
// fastclick (eliminate the 300ms delay between a physical tap and the firing of a click event on mobile browsers)
FastClick.attach(document.body);
});
/* Helpers */
/* Detect touch devices */
function is_touch_device() {
return !!('ontouchstart' in window);
}
/* Detect hi-res devices */
function isHighDensity() {
return ((window.matchMedia && (window.matchMedia('only screen and (min-resolution: 124dpi), only screen and (min-resolution: 1.3dppx), only screen and (min-resolution: 48.8dpcm)').matches || window.matchMedia('only screen and (-webkit-min-device-pixel-ratio: 1.3), only screen and (-o-min-device-pixel-ratio: 2.6/2), only screen and (min--moz-device-pixel-ratio: 1.3), only screen and (min-device-pixel-ratio: 1.3)').matches)) || (window.devicePixelRatio && window.devicePixelRatio > 1.3));
}
/*
* debouncedresize: special jQuery event that happens once after a window resize
* throttledresize: special jQuery event that happens at a reduced rate compared to "resize"
*
* latest version and complete README available on Github:
* https://github.com/louisremi/jquery-smartresize
*
* Copyright 2012 @louis_remi
* Licensed under the MIT license.
*
*/
(function(a){var d=a.event,b,c;b=d.special.debouncedresize={setup:function(){a(this).on("resize",b.handler)},teardown:function(){a(this).off("resize",b.handler)},handler:function(a,f){var g=this,h=arguments,e=function(){a.type="debouncedresize";d.dispatch.apply(g,h)};c&&clearTimeout(c);f?e():c=setTimeout(e,b.threshold)},threshold:150}})(jQuery);
(function(b){var f=b.event,c,g={_:0},a=0,d,e;c=f.special.throttledresize={setup:function(){b(this).on("resize",c.handler)},teardown:function(){b(this).off("resize",c.handler)},handler:function(h,k){var l=this,m=arguments;d=!0;e||(setInterval(function(){a++;if(a>c.threshold&&d||k)h.type="throttledresize",f.dispatch.apply(l,m),d=!1,a=0;9<a&&(b(g).stop(),e=!1,a=0)},30),e=!0)},threshold:0}})(jQuery);
/* common functions */
/* main menu */
yukon_main_menu = {
init: function () {
// add '.has_submenu' class if section has childrens
$('#main_menu ul > li').each(function () {
if ($(this).children('ul').length) {
$(this).addClass('has_submenu');
}
});
// accordion menu
$(document).off('click', '.side_menu_expanded #main_menu .has_submenu > a').on('click', '.side_menu_expanded #main_menu .has_submenu > a', function () {
if($(this).parent('.has_submenu').hasClass('first_level')) {
var $this_parent = $(this).parent('.has_submenu'),
panel_active = $this_parent.hasClass('section_active');
if (!panel_active) {
$this_parent.siblings().removeClass('section_active').children('ul').slideUp('200');
$this_parent.addClass('section_active').children('ul').slideDown('200');
} else {
$this_parent.removeClass('section_active').children('ul').slideUp('200');
}
} else {
var $submenu_parent = $(this).parent('.has_submenu'),
submenu_active = $submenu_parent.hasClass('submenu_active');
if (!submenu_active) {
$submenu_parent.siblings().removeClass('submenu_active').children('ul').slideUp('200');
$submenu_parent.addClass('submenu_active').children('ul').slideDown('200');
} else {
$submenu_parent.removeClass('submenu_active').children('ul').slideUp('200');
}
}
});
// side menu initialization
if(!$('#main_menu .has_submenu').hasClass('section_active')) {
$('#main_menu .has_submenu .act_nav').closest('.has_submenu').children('a').click();
} else {
$('#main_menu .has_submenu.section_active').children('ul').show();
}
$('.menu_toggle').click(function() {
if($('body').hasClass('side_menu_expanded')) {
yukon_main_menu.menu_collapse();
} else if($('body').hasClass('side_menu_collapsed')) {
yukon_main_menu.menu_expand();
}
$(window).off("debouncedresize").trigger('resize').on("debouncedresize");
});
// collapse navigation on mobile devices
if($('body').hasClass('side_menu_expanded') && $(window).width() <= 992 ) {
yukon_main_menu.menu_collapse();
}
// create scrollbar if menu is expanded
if($('body').hasClass('side_menu_expanded')) {
yukon_main_menu.menu_scrollbar_create();
}
// uncomment function bellow to activate saving side menu states
//yukon_main_menu.menu_cookie();
},
menu_expand: function() {
$('body').addClass('side_menu_expanded').removeClass('side_menu_collapsed');
$('.menu_toggle').find('.toggle_left').show();
$('.menu_toggle').find('.toggle_right').hide();
yukon_main_menu.menu_scrollbar_create();
},
menu_collapse: function() {
$('body').removeClass('side_menu_expanded').addClass('side_menu_collapsed');
$('.menu_toggle').find('.toggle_left').hide();
$('.menu_toggle').find('.toggle_right').show();
yukon_main_menu.menu_scrollbar_destroy();
},
menu_cookie: function() {
$('.menu_toggle').on('click',function() {
if($('body').hasClass('side_menu_expanded')) {
$.cookie('side_menu', '1');
} else if($('body').hasClass('side_menu_collapsed')) {
$.cookie('side_menu', '0');
}
});
var $side_menu_cookie = $.cookie('side_menu');
if($side_menu_cookie != undefined) {
if($side_menu_cookie == '1') {
yukon_main_menu.menu_expand();
} else if($side_menu_cookie == '0') {
yukon_main_menu.menu_collapse();
}
}
},
position_top: function() {
$('body')
.removeClass('side_menu_active side_menu_expanded side_menu_collapsed')
.addClass('top_menu_active');
},
position_side: function() {
$('body')
.removeClass('top_menu_active')
.addClass('side_menu_active');
yukon_main_menu.menu_collapse();
},
menu_scrollbar_create: function() {
$("#main_menu .menu_wrapper").mCustomScrollbar({
theme: "minimal-dark",
scrollbarPosition: "outside"
});
},
menu_scrollbar_destroy: function() {
$("#main_menu .menu_wrapper").mCustomScrollbar('destroy');
}
};
// style switcher
yukon_style_switcher = {
init: function() {
var $styleSwitcher = $('#style_switcher');
// toggle style switcher
$('.switcher_toggle').on('click', function(e) {
if(!$styleSwitcher.hasClass('switcher_open')) {
$styleSwitcher.addClass('switcher_open')
} else {
$styleSwitcher.removeClass('switcher_open')
}
e.preventDefault();
})
// layout switch
$('#fixed_layout_switch').attr('checked',false).on('change', function () {
if( $('#fixed_layout_switch').prop('checked') ) {
$('body').addClass('fixed_layout');
$('#fixed_layout_bg_switch').show();
} else {
$('body').removeClass('fixed_layout');
$('#fixed_layout_bg_switch').hide();
};
$(window).resize();
});
// menu position
$('#top_menu_switch').attr('checked',false).on('change', function () {
if( $('#top_menu_switch').prop('checked') ) {
yukon_main_menu.position_top();
yukon_main_menu.menu_scrollbar_destroy();
} else {
yukon_main_menu.position_side();
yukon_main_menu.menu_scrollbar_create();
};
$(window).resize();
});
// hide breadcumbs
$('#breadcrumbs_hide').attr('checked',false).on('change', function () {
if( $('#breadcrumbs_hide').prop('checked') ) {
$('body').addClass('hide_breadcrumbs');
} else {
$('body').removeClass('hide_breadcrumbs');
};
});
// top bar style
$('#topBar_style_switch li').on('click',function() {
var topBarStyle = $(this).attr('title');
$('#topBar_style_switch li').removeClass('style_active');
$(this).addClass('style_active');
$('#main_header').removeClass('topBar_style_1 topBar_style_2 topBar_style_3 topBar_style_4 topBar_style_5 topBar_style_6 topBar_style_7 topBar_style_8 topBar_style_9 topBar_style_10 topBar_style_11 topBar_style_12 topBar_style_13 topBar_style_14').addClass(topBarStyle);
});
// fixed layout background
if( !$('body').hasClass('fixed_layout') ) {
$('#fixed_layout_bg_switch').hide();
}
$('#fixed_layout_bg_switch ul li').on('click',function() {
var fixedLayBg = $(this).attr('title');
$('#fixed_layout_bg_switch ul li').removeClass('style_active');
$(this).addClass('style_active');
$('body').removeClass('bg_0 bg_1 bg_2 bg_3 bg_4 bg_5 bg_6 bg_7').addClass(fixedLayBg);
});
// show CSS
$('#showCSSModal').on('show.bs.modal', function (e) {
$bodyClasses = $('body').attr('class');
$headerClasses = $('#main_header').attr('class');
$bodyClassesStr =
'// <body> classes'
+ '<br><body class="'+ $bodyClasses + '">...</body>';
if(typeof $headerClasses !== "undefined" && $headerClasses != '') {
$headerClassesStr =
'<br><br>'
+ '// <header> classes'
+ '<br><header id="main_header" class="' + $headerClasses + '">...</header>';
} else {
$headerClassesStr = '';
}
$('#showCSSPre').html($bodyClassesStr + '' + $headerClassesStr);
})
}
}
// bootstrap custom functions
yukon_bs_custom = {
accordion_active_class: function() {
if($('.panel-collapse').length) {
$('.panel-collapse.in').closest('.panel').addClass('panel-active');
$('.panel-collapse').on('hide.bs.collapse', function () {
$(this).closest('.panel').removeClass('panel-active');
}).on('show.bs.collapse', function () {
$(this).closest('.panel').addClass('panel-active');
})
}
},
dropdown_click: function() {
// prevent closing notification dropdown on content click
if($('.header_notifications .dropdown-menu').length) {
$('.header_notifications .dropdown-menu').click(function(e) {
e.stopPropagation();
});
}
},
tooltips_init: function() {
$('.bs_ttip').tooltip({
container: 'body'
});
},
popover_init: function() {
$('.bs_popup').popover({
container: 'body'
});
}
};
/* page specific functions */
// chat
yukon_chat = {
init: function() {
if($('.chat_message_send button').length) {
var msg_date_unix;
$('.chat_message_send button').on('click', function() {
var msg_date = moment().format('MMM D YYYY, h:mm A'),
chat_msg = $('.chat_message_send textarea').val();
if(chat_msg != '') {
if( msg_date != $('.chat_messages').data('lastMessageUnix') ) {
$('.chat_messages').prepend('<div class="message_date">'+ msg_date +'</div><ul></ul>').data('lastMessageUnix', msg_date);
}
$('.chat_messages ul:first').prepend('<li class="msg_left"><p class="msg_user">Carrol Clark</p>' + chat_msg + '</li>');
$('.chat_message_send textarea').val('');
}
})
}
}
};
// mailbox
yukon_mailbox = {
init: function() {
var $mailbox_table = $('#mailbox_table');
$mailbox_table.find('.mbox_star span').on('click', function(){
var $this = $(this),
$this_parent = $this.parent('.mbox_star');
$this.hasClass('icon_star') ? $this_parent.removeClass('marked') : $this_parent.addClass('marked');
$this.toggleClass('icon_star icon_star_alt');
});
$('input.msgSelect').on('click',function() {
$(this).is(':checked') ? $(this).closest('tr').addClass('selected') : $(this).closest('tr').removeClass('selected');
});
$mailbox_table.on('click', '#msgSelectAll', function () {
var $this = $(this);
$mailbox_table.find('input.msgSelect').filter(':visible').each(function() {
$this.is(':checked') ? $(this).prop('checked',true).closest('tr').addClass('selected') : $(this).prop('checked',false).closest('tr').removeClass('selected');
})
})
}
};
// user list
yukon_user_list = {
init: function() {
$('.countUsers').text($('#user_list > li').length);
}
};
// icons
yukon_icons = {
search_icons: function() {
$('#icon_search').val('').keyup(function(){
var sValue = $(this).val().toLowerCase();
$('.icon_list > li > span').each(function () {
if ($(this).attr('class').toLowerCase().indexOf(sValue) === -1) {
$(this).parent('li').hide();
} else {
$(this).parent('li').show();
}
});
});
}
};
// gallery
yukon_gallery = {
search_gallery: function() {
$('#gallery_search').val('').keyup(function(){
var sValue = $(this).val().toLowerCase();
$('.gallery_grid > li > a').each(function () {
if( $(this).text().search(new RegExp(sValue, "i")) < 0 && $(this).attr('title').toLowerCase().indexOf(sValue) === -1 ) {
$(this).closest('li').hide();
} else {
$(this).closest('li').show();
}
});
});
}
};
// contact list
yukon_contact_list = {
init: function() {
var $grid = $('.contact_list');
$grid.shuffle({
itemSelector: '.contact_item'
});
$('#contactList_sort').prop('selectedIndex',0).on('change', function() {
var sort = this.value,
opts = {};
if (sort === 'company') {
opts = {
by: function ($el) {
return $el.data('company');
}
};
} else if (sort === 'company_desc') {
opts = {
reverse: true,
by: function ($el) {
return $el.data('company').toLowerCase();
}
};
} else if (sort === 'name') {
opts = {
by: function ($el) {
return $el.data('name').toLowerCase();
}
};
} else if (sort === 'name_desc') {
opts = {
reverse: true,
by: function ($el) {
return $el.data('name').toLowerCase();
}
};
}
// Sort elements
$grid.shuffle('sort', opts);
});
$('#contactList_filter').prop('selectedIndex',0).on('change', function() {
var group = this.value;
// Filter elements
$grid.shuffle( 'shuffle', group );
$('#contactList_sort').prop('selectedIndex',0);
$('#contactList_search').val('');
});
$('#contactList_search').val('').on('keyup', function() {
var uName = this.value;
if(uName.length > 1) {
$('#contactList_filter, #contactList_sort').prop('selectedIndex',0);
// Filter elements
$grid.shuffle('shuffle', function ($el, shuffle) {
return $el.data('name').toLowerCase().indexOf(uName.toLowerCase()) >= 0;
});
} else {
$grid.shuffle( 'shuffle', $('#contactList_filter').val() );
}
});
}
}
/* plugins */
// 2col multiselect
yukon_2col_multiselect = {
init: function() {
if($('#2col_ms_default').length) {
var $msListDefault = $('#2col_ms_default');
$msListDefault.multiSelect({
keepOrder: true,
selectableHeader: '<div class="ms-header">Selectable items</div>',
selectionHeader: '<div class="ms-header">Selection items</div>',
selectableFooter: '<div class="ms-footer">Selectable footer</div>',
selectionFooter: '<div class="ms-footer">Selection footer</div>'
});
$msListDefault.closest('.ms-wrapper').find('.ms_select_all').click(function (e) {
e.preventDefault();
$msListDefault.multiSelect('select_all');
});
$msListDefault.closest('.ms-wrapper').find('.ms_deselect_all').click(function (e) {
e.preventDefault();
$msListDefault.multiSelect('deselect_all');
});
}
if($('#2col_ms_search').length) {
var $msListSearch = $('#2col_ms_search');
$('#2col_ms_search').multiSelect({
keepOrder: true,
selectableHeader: '<div class="ms-header-search"><input class="form-control input-sm" type="text" placeholder="Search in selectable..."/></div>',
selectionHeader: '<div class="ms-header-search"><input class="form-control input-sm" type="text" placeholder="Search in selection..."/></div>',
afterInit: function(ms){
ms.find('.ms-list li').each(function() {
var thisText = $(this).children('span').text(),
flag = thisText.substr(2, 2),
flag_remove = thisText.substr(0, 6);
$(this).children('span').html( '<i class="flag-'+ flag +'"></i>'+ thisText.replace(flag_remove,'') );
});
var that = this,
$selectableSearch = that.$selectableUl.prev().children(),
$selectionSearch = that.$selectionUl.prev().children(),
selectableSearchString = '#' + that.$container.attr('id') + ' .ms-elem-selectable:not(.ms-selected)',
selectionSearchString = '#' + that.$container.attr('id') + ' .ms-elem-selection.ms-selected';
that.qs1 = $selectableSearch.quicksearch(selectableSearchString).on('keydown', function (e) {
if (e.which === 40) {
that.$selectableUl.focus();
return false;
}
});
that.qs2 = $selectionSearch.quicksearch(selectionSearchString).on('keydown', function (e) {
if (e.which == 40) {
that.$selectionUl.focus();
return false;
}
});
},
afterSelect: function () {
this.qs1.cache();
this.qs2.cache();
},
afterDeselect: function () {
this.qs1.cache();
this.qs2.cache();
}
});
$msListSearch.closest('.ms-wrapper').find('.ms_select_all').click(function (e) {
e.preventDefault();
$msListSearch.multiSelect('select_all');
});
$msListSearch.closest('.ms-wrapper').find('.ms_deselect_all').click(function (e) {
e.preventDefault();
$msListSearch.multiSelect('deselect_all');
});
}
}
}
// ace editor
yukon_ace_editor = {
init: function () {
var editor = ace.edit("aceEditor");
$('#aceEditor').data('editor', editor);
editor.setTheme("ace/theme/monokai");
document.getElementById('aceEditor').style.fontSize='14px';
editor.getSession().setMode("ace/mode/javascript");
editor.setShowPrintMargin(false);
editor.setOptions({maxLines: 32});
editor.setAutoScrollEditorIntoView(true);
// change theme
$('#editor_theme').val('monokai').on('change',function() {
$('#aceEditor').data('editor').setTheme("ace/theme/"+$(this).val());
})
// change font size
$('#editor_font_size').val('14').on('change',function() {
document.getElementById('aceEditor').style.fontSize=$(this).val()+'px';
})
}
}
// full calendar
yukon_fullCalendar = {
p_plugins_calendar: function() {
if($('#calendar').length) {
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
$('#calendar').fullCalendar({
header: {
center: 'title',
left: 'month,agendaWeek,agendaDay today',
right: 'prev,next'
},
buttonIcons: {
prev: ' el-icon-chevron-left',
next: ' el-icon-chevron-right'
},
editable: true,
aspectRatio: 2.2,
events: [
{
title: 'All Day Event',
start: new Date(y, m, 1)
},
{
title: 'Long Event',
start: new Date(y, m, d - 5),
end: new Date(y, m, d - 2)
},
{
id: 999,
title: 'Repeating Event',
start: new Date(y, m, d - 3, 16, 0)
},
{
id: 999,
title: 'Repeating Event',
start: new Date(y, m, d + 4, 16, 0)
},
{
title: 'Meeting',
start: new Date(y, m, d + 1, 19, 0),
end: new Date(y, m, d + 1, 22, 30)
},
{
title: 'Lunch',
start: new Date(y, m, d - 7)
},
{
title: 'Birthday Party',
start: new Date(y, m, d + 10)
},
{
title: 'Click for Google',
url: 'http://google.com/',
start: new Date(y, m, d + 12)
}
],
eventAfterAllRender: function() {
$('.fc-header .fc-button-prev').html('<span class="el-icon-chevron-left"></span>');
$('.fc-header .fc-button-next').html('<span class="el-icon-chevron-right"></span>');
}
});
}
if($('#calendar_phases').length) {
$('#calendar_phases').fullCalendar({
header: {
center: 'title',
left: 'month,agendaWeek,agendaDay today',
right: 'prev,next'
},
buttonIcons: false,
aspectRatio: 2.2,
// Phases of the Moon
events: 'https://www.google.com/calendar/feeds/ht3jlfaac5lfd6263ulfh4tql8%40group.calendar.google.com/public/basic',
eventClick: function(event) {
// opens events in a popup window
window.open(event.url, 'gcalevent', 'width=700,height=600');
return false;
},
eventAfterAllRender: function() {
$('.fc-header .fc-button-prev').html('<span class="el-icon-chevron-left"></span>');
$('.fc-header .fc-button-next').html('<span class="el-icon-chevron-right"></span>');
}
});
}
}
};
// chained selects
yukon_chained_selects = {
init: function() {
$("#chs_button").hide();
$("#chs_series").chained("#chs_mark");
$("#chs_model").chained("#chs_series");
$("#chs_engine").chained("#chs_series, #chs_model").on("change", function() {
if ("" != $("option:selected", this).val() && "" != $("option:selected", $("#chs_model")).val()) {
$("#chs_button").fadeIn();
} else {
$("#chs_button").hide();
}
});
}
};
// c3 charts
yukon_charts = {
p_dashboard: function() {
if($('#c3_7_days').length) {
var c3_7_days_chart = c3.generate({
bindto: '#c3_7_days',
data: {
x: 'x',
columns: [
['x', '2013-01-01', '2013-02-01', '2013-03-01', '2013-04-01', '2013-05-01', '2013-06-01', '2013-07-01', '2013-08-01', '2013-09-01', '2013-10-01', '2013-11-01', '2013-12-01'],
['2013', 14512, 10736, 18342, 14582, 16304, 22799, 18833, 21973, 23643, 22488, 24752, 28722],
['2014', 23732, 22904, 23643, 26887, 32629, 30512, 31658, 35782, 36724, 38947, 42426, 37439]
],
types: {
'2013': 'area',
'2014': 'line'
}
},
axis: {
x: {
type: 'timeseries',
tick: {
culling: false,
fit: true,
format: "%b"
}
},
y : {
tick: {
format: d3.format("$,")
}
}
},
point: {
r: '4',
focus: {
expand: {
r: '5'
}
}
},
bar: {
width: {
ratio: 0.4 // this makes bar width 50% of length between ticks
}
},
grid: {
x: {
show: true
},
y: {
show: true
}
},
color: {
pattern: ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf']
}
});
$('.chart_switch').on('click', function() {
if($(this).data('chart') == 'line') {
c3_7_days_chart.transform('area', '2013');
c3_7_days_chart.transform('line', '2014');
} else if($(this).data('chart') == 'bar') {
c3_7_days_chart.transform('bar');
}
$('.chart_switch').toggleClass('btn-default btn-link');
});
$(window).on("debouncedresize", function() {
c3_7_days_chart.resize();
});
}
if($('#c3_orders').length) {
var c3_orders_chart = c3.generate({
bindto: '#c3_orders',
data: {
columns: [
['New', 64],
['In Progrees', 36]
],
type : 'pie'
},
pie: {
//onclick: function (d, i) { console.log(d, i); },
//onmouseover: function (d, i) { console.log(d, i); },
//onmouseout: function (d, i) { console.log(d, i); }
}
});
$(window).on("debouncedresize", function() {
c3_orders_chart.resize();
});
}
if($('#c3_users_age').length) {
var c3_users_age = c3.generate({
bindto: '#c3_users_age',
data: {
columns: [
['18-24', 18],
['25-32', 42],
['33-40', 31],
['41-57', 9]
],
type : 'donut'
},
donut: {
//onclick: function (d, i) { console.log(d, i); },
//onmouseover: function (d, i) { console.log(d, i); },
//onmouseout: function (d, i) { console.log(d, i); }
}
});
$(window).on("debouncedresize", function() {
c3_users_age.resize();
});
}
},
p_plugins_charts: function() {
// combined chart
var c3_combined_chart = c3.generate({
bindto: '#c3_combined',
data: {
columns: [
['data1', 30, 20, 50, 40, 60, 50],
['data2', 200, 130, 90, 240, 130, 220],
['data3', 200, 130, 90, 240, 130, 220],
['data4', 130, 120, 150, 140, 160, 150],
['data5', 90, 70, 20, 50, 60, 120]
],
type: 'bar',
types: {
data3: 'line',
data5: 'area'
},
groups: [
['data1','data2']
]
},
point: {
r: '4',
focus: {
expand: {
r: '5'
}
}
},
bar: {
width: {
ratio: 0.4 // this makes bar width 50% of length between ticks
}
},
grid: {
x: {
show: true
},
y: {
show: true
}
},
color: {
pattern: ['#ff7f0e', '#2ca02c', '#9467bd', '#1f77b4', '#d62728']
}
});
// gauge chart
var chart_gauge = c3.generate({
bindto: '#c3_gauge',
data: {
columns: [
['data', 91.4]
],
type: 'gauge'
//onclick: function (d, i) { console.log("onclick", d, i); },
//onmouseover: function (d, i) { console.log("onmouseover", d, i); },
//onmouseout: function (d, i) { console.log("onmouseout", d, i); }
},
gauge: {
width: 39
},
color: {
pattern: ['#ff0000', '#f97600', '#f6c600', '#60b044'],
threshold: {
values: [30, 60, 90, 100]
}
}
});
setTimeout(function () {
chart_gauge.load({
columns: [['data', 10]]
});
}, 2000);
setTimeout(function () {
chart_gauge.load({
columns: [['data', 50]]
});
}, 3000);
setTimeout(function () {
chart_gauge.load({
columns: [['data', 70]]
});
}, 4000);
setTimeout(function () {
chart_gauge.load({
columns: [['data', 0]]
});
}, 5000);
setTimeout(function () {
chart_gauge.load({
columns: [['data', 100]]
});
}, 6000);
// donut chart
var chart_donut = c3.generate({
bindto: '#c3_donut',
data: {
columns: [
['data1', 30],
['data2', 120]
],
type : 'donut',
onclick: function (d, i) { console.log("onclick", d, i); },
onmouseover: function (d, i) { console.log("onmouseover", d, i); },
onmouseout: function (d, i) { console.log("onmouseout", d, i); }
},
donut: {
title: "Iris Petal Width"
}
});
setTimeout(function () {
chart_donut.load({
columns: [
["setosa", 0.2, 0.2, 0.2, 0.2, 0.2, 0.4, 0.3, 0.2, 0.2, 0.1, 0.2, 0.2, 0.1, 0.1, 0.2, 0.4, 0.4, 0.3, 0.3, 0.3, 0.2, 0.4, 0.2, 0.5, 0.2, 0.2, 0.4, 0.2, 0.2, 0.2, 0.2, 0.4, 0.1, 0.2, 0.2, 0.2, 0.2, 0.1, 0.2, 0.2, 0.3, 0.3, 0.2, 0.6, 0.4, 0.3, 0.2, 0.2, 0.2, 0.2],
["versicolor", 1.4, 1.5, 1.5, 1.3, 1.5, 1.3, 1.6, 1.0, 1.3, 1.4, 1.0, 1.5, 1.0, 1.4, 1.3, 1.4, 1.5, 1.0, 1.5, 1.1, 1.8, 1.3, 1.5, 1.2, 1.3, 1.4, 1.4, 1.7, 1.5, 1.0, 1.1, 1.0, 1.2, 1.6, 1.5, 1.6, 1.5, 1.3, 1.3, 1.3, 1.2, 1.4, 1.2, 1.0, 1.3, 1.2, 1.3, 1.3, 1.1, 1.3],
["virginica", 2.5, 1.9, 2.1, 1.8, 2.2, 2.1, 1.7, 1.8, 1.8, 2.5, 2.0, 1.9, 2.1, 2.0, 2.4, 2.3, 1.8, 2.2, 2.3, 1.5, 2.3, 2.0, 2.0, 1.8, 2.1, 1.8, 1.8, 1.8, 2.1, 1.6, 1.9, 2.0, 2.2, 1.5, 1.4, 2.3, 2.4, 1.8, 1.8, 2.1, 2.4, 2.3, 1.9, 2.3, 2.5, 2.3, 1.9, 2.0, 2.3, 1.8]
]
});
}, 2500);
setTimeout(function () {
chart_donut.unload({
ids: 'data1'
});
chart_donut.unload({
ids: 'data2'
});
}, 4500);
// grid lines
var chart_grid_lines = c3.generate({
bindto: '#c3_grid_lines',
data: {
columns: [
['sample', 30, 200, 100, 400, 150, 250],
['sample2', 1300, 1200, 1100, 1400, 1500, 1250]
],
axes: {
sample2: 'y2'
}
},
axis: {
y2: {
show: true
}
},
grid: {
y: {
lines: [{value: 50, text: 'Label 50'}, {value: 1300, text: 'Label 1300', axis: 'y2'}]
}
}
});
// scatter plot
var chart_scatter = c3.generate({
bindto: '#c3_scatter',
data: {
xs: {
setosa: 'setosa_x',
versicolor: 'versicolor_x'
},
// iris data from R
columns: [
["setosa_x", 3.5, 3.0, 3.2, 3.1, 3.6, 3.9, 3.4, 3.4, 2.9, 3.1, 3.7, 3.4, 3.0, 3.0, 4.0, 4.4, 3.9, 3.5, 3.8, 3.8, 3.4, 3.7, 3.6, 3.3, 3.4, 3.0, 3.4, 3.5, 3.4, 3.2, 3.1, 3.4, 4.1, 4.2, 3.1, 3.2, 3.5, 3.6, 3.0, 3.4, 3.5, 2.3, 3.2, 3.5, 3.8, 3.0, 3.8, 3.2, 3.7, 3.3],
["versicolor_x", 3.2, 3.2, 3.1, 2.3, 2.8, 2.8, 3.3, 2.4, 2.9, 2.7, 2.0, 3.0, 2.2, 2.9, 2.9, 3.1, 3.0, 2.7, 2.2, 2.5, 3.2, 2.8, 2.5, 2.8, 2.9, 3.0, 2.8, 3.0, 2.9, 2.6, 2.4, 2.4, 2.7, 2.7, 3.0, 3.4, 3.1, 2.3, 3.0, 2.5, 2.6, 3.0, 2.6, 2.3, 2.7, 3.0, 2.9, 2.9, 2.5, 2.8],
["setosa", 0.2, 0.2, 0.2, 0.2, 0.2, 0.4, 0.3, 0.2, 0.2, 0.1, 0.2, 0.2, 0.1, 0.1, 0.2, 0.4, 0.4, 0.3, 0.3, 0.3, 0.2, 0.4, 0.2, 0.5, 0.2, 0.2, 0.4, 0.2, 0.2, 0.2, 0.2, 0.4, 0.1, 0.2, 0.2, 0.2, 0.2, 0.1, 0.2, 0.2, 0.3, 0.3, 0.2, 0.6, 0.4, 0.3, 0.2, 0.2, 0.2, 0.2],
["versicolor", 1.4, 1.5, 1.5, 1.3, 1.5, 1.3, 1.6, 1.0, 1.3, 1.4, 1.0, 1.5, 1.0, 1.4, 1.3, 1.4, 1.5, 1.0, 1.5, 1.1, 1.8, 1.3, 1.5, 1.2, 1.3, 1.4, 1.4, 1.7, 1.5, 1.0, 1.1, 1.0, 1.2, 1.6, 1.5, 1.6, 1.5, 1.3, 1.3, 1.3, 1.2, 1.4, 1.2, 1.0, 1.3, 1.2, 1.3, 1.3, 1.1, 1.3]
],
type: 'scatter'
},
axis: {
x: {
label: 'Sepal.Width',
tick: {
fit: false
}
},
y: {
label: 'Petal.Width'
}
}
});
setTimeout(function () {
chart_scatter.load({
xs: {
virginica: 'virginica_x'
},
columns: [
["virginica_x", 3.3, 2.7, 3.0, 2.9, 3.0, 3.0, 2.5, 2.9, 2.5, 3.6, 3.2, 2.7, 3.0, 2.5, 2.8, 3.2, 3.0, 3.8, 2.6, 2.2, 3.2, 2.8, 2.8, 2.7, 3.3, 3.2, 2.8, 3.0, 2.8, 3.0, 2.8, 3.8, 2.8, 2.8, 2.6, 3.0, 3.4, 3.1, 3.0, 3.1, 3.1, 3.1, 2.7, 3.2, 3.3, 3.0, 2.5, 3.0, 3.4, 3.0],
["virginica", 2.5, 1.9, 2.1, 1.8, 2.2, 2.1, 1.7, 1.8, 1.8, 2.5, 2.0, 1.9, 2.1, 2.0, 2.4, 2.3, 1.8, 2.2, 2.3, 1.5, 2.3, 2.0, 2.0, 1.8, 2.1, 1.8, 1.8, 1.8, 2.1, 1.6, 1.9, 2.0, 2.2, 1.5, 1.4, 2.3, 2.4, 1.8, 1.8, 2.1, 2.4, 2.3, 1.9, 2.3, 2.5, 2.3, 1.9, 2.0, 2.3, 1.8]
]
});
}, 1000);
setTimeout(function () {
chart_scatter.unload({
ids: 'setosa'
});
}, 2000);
setTimeout(function () {
chart_scatter.load({
columns: [
["virginica", 0.2, 0.2, 0.2, 0.2, 0.2, 0.4, 0.3, 0.2, 0.2, 0.1, 0.2, 0.2, 0.1, 0.1, 0.2, 0.4, 0.4, 0.3, 0.3, 0.3, 0.2, 0.4, 0.2, 0.5, 0.2, 0.2, 0.4, 0.2, 0.2, 0.2, 0.2, 0.4, 0.1, 0.2, 0.2, 0.2, 0.2, 0.1, 0.2, 0.2, 0.3, 0.3, 0.2, 0.6, 0.4, 0.3, 0.2, 0.2, 0.2, 0.2]
]
});
}, 3000);
// resize charts
$(window).on("debouncedresize", function() {
c3_combined_chart.resize();
chart_gauge.resize();
chart_donut.resize();
chart_grid_lines.resize();
chart_scatter.resize();
});
}
};
// gantt chart
yukon_gantt_chart = {
init: function() {
var ganttData = [
{
id: 1,
name: "Concept",
color: '#006064',
series: [
{
name: "Brainstorm<span>1 Jan - 3 Jan</span>",
start: new Date('01/01/2015'),
end: new Date('01/03/2015'),
color: "#0097a7"
},
{
name: "Wireframes<span>4 Jan - 7 Jan</span>",
start: new Date('01/04/2015'),
end: new Date('01/07/2015'),
color: "#00bcd4"
},
{
name: "Concept description<span>6 Jan - 10 Jan</span>",
start: new Date('01/06/2015'),
end: new Date('01/10/2015'),
color: "#4dd0e1"
}
]
},
{
id: 2,
name: "Design",
series: [
{
name: "Sketching<span>8 Jan - 16 Jan</span>",
start: new Date('01/08/2015'),
end: new Date('01/16/2015'),
color: "#f57c00"
},
{
name: "Photography<span>10 Jan - 16 Jan</span>",
start: new Date('01/10/2015'),
end: new Date('01/16/2015'),
color: "#fb8c00"
},
{
name: "Feedback<span>19 Jan - 21 Jan</span>",
start: new Date('01/19/2015'),
end: new Date('01/21/2015'),
color: "#ff9800"
},
{
name: "Final Design<span>21 Jan - 27 Jan</span>",
start: new Date('01/21/2015'),
end: new Date('01/27/2015'),
color: "#ffa726"
}
]
},
{
id: 3,
name: "Implementation",
series: [
{
name: "Specifications<span>26 Jan - 2 Feb</span>",
start: new Date('01/26/2015'),
end: new Date('02/06/2015'),
color: "#689f38"
},
{
name: "Templates<span>4 Feb - 10 Feb</span>",
start: new Date('02/04/2015'),
end: new Date('02/10/2015'),
color: "#7cb342"
},
{
name: "Database<span>5 Feb - 13 Feb</span>",
start: new Date('02/05/2015'),
end: new Date('02/13/2015'),
color: "#8bc34a"
},
{
name: "Integration<span>16 Feb - 10 Mar</span>",
start: new Date('02/16/2015'),
end: new Date('03/10/2015'),
color: "#9ccc65"
}
]
},
{
id: 4,
name: "Testing & Delivery",
series: [
{
name: "Focus Group<span>17 Mar - 27 Mar</span>",
start: new Date('03/17/2015'),
end: new Date('03/27/2015'),
color: "#1976d2"
},
{
name: "Stress Test<span>25 Mar - 6 Apr</span>",
start: new Date('03/25/2015'),
end: new Date('04/06/2015'),
color: "#2196f3"
},
{
name: "Delivery<span>7 Apr - 8 Apr</span>",
start: new Date('04/07/2015'),
end: new Date('04/08/2015'),
color: "#64b5f6"
}
]
}
];
$("#ganttChart").ganttView({
data: ganttData,
behavior: {
onClick: function (data) {
var msg = "You clicked on an event: { start: " + data.start.toString("M/d/yyyy") + ", end: " + data.end.toString("M/d/yyyy") + " }";
console.log(msg);
},
onResize: function (data) {
var msg = "You resized an event: { start: " + data.start.toString("M/d/yyyy") + ", end: " + data.end.toString("M/d/yyyy") + " }";
console.log(msg);
},
onDrag: function (data) {
var msg = "You dragged an event: { start: " + data.start.toString("M/d/yyyy") + ", end: " + data.end.toString("M/d/yyyy") + " }";
console.log(msg);
}
}
});
}
};
// clock picker
yukon_clock_picker = {
init: function() {
if($('.clockpicker').length) {
$('.clockpicker').clockpicker()
.find('input').change(function () {
console.log(this.value);
});
}
}
};
// countUp animation
yukon_count_up = {
init: function() {
if($('.countUpMe').length) {
$('.countUpMe').each(function() {
var target = this;
var endVal = parseInt($(this).attr('data-endVal'));
theAnimation = new countUp(target, 0, endVal, 0, 2.6, { useEasing : true, useGrouping : true, separator: ' ' });
theAnimation.start();
});
}
}
};
// datepicker
yukon_datepicker = {
p_forms_extended: function() {
if ( $.isFunction($.fn.datepicker) ) {
// replace datepicker arrow
$.fn.datepicker.DPGlobal.template = $.fn.datepicker.DPGlobal.template
.replace(/\«/g, '<i class="arrow_carrot-left"></i>')
.replace(/\»/g, '<i class="arrow_carrot-right"></i>');
}
if ($("#dp_basic").length) {
$("#dp_basic").datepicker({
autoclose: true
});
}
if ($("#dp_component").length) {
$("#dp_component").datepicker({
autoclose: true
});
}
if ($("#dp_range").length) {
$("#dp_range").datepicker({
autoclose: true
});
}
if ($("#dp_inline").length) {
$("#dp_inline").datepicker();
}
}
};
// date range picker
yukon_date_range_picker = {
p_forms_extended: function() {
if ($("#drp_time").length) {
$('#drp_time').daterangepicker({
timePicker: true,
timePickerIncrement: 30,
format: 'MM/DD/YYYY h:mm A',
buttonClasses: 'btn btn-sm'
});
}
if ($("#drp_predefined").length) {
$('#drp_predefined').daterangepicker(
{
ranges: {
'Today': [moment(), moment()],
'Yesterday': [moment().subtract('days', 1), moment().subtract('days', 1)],
'Last 7 Days': [moment().subtract('days', 6), moment()],
'Last 30 Days': [moment().subtract('days', 29), moment()],
'This Month': [moment().startOf('month'), moment().endOf('month')],
'Last Month': [moment().subtract('month', 1).startOf('month'), moment().subtract('month', 1).endOf('month')]
},
startDate: moment().subtract('days', 29),
endDate: moment()
},
function(start, end) {
$('#drp_predefined span').html(start.format('MMMM D, YYYY') + ' - ' + end.format('MMMM D, YYYY'));
}
);
}
}
};
// datatables
yukon_datatables = {
p_plugins_tables_datatable: function() {
var table = $('#datatable_demo').dataTable({
"iDisplayLength": 25
});
// fixed header
var oFH = new $.fn.dataTable.FixedHeader(table, {
"offsetTop": 48
});
oFH.fnUpdate();
// update fixed headers on window resize
$(window).on("throttledresize", function( event ) {
oFH._fnUpdateClones( true );
oFH._fnUpdatePositions();
})
}
};
// easyPie chart
yukon_easyPie_chart = {
p_dashboard: function() {
if($('.easy_chart_a').length) {
$('.easy_chart_a').easyPieChart({
animate: 2000,
size: 90,
lineWidth: 4,
scaleColor: false,
barColor: '#48ac2e',
trackColor: '#eee',
easing: 'easeOutBounce',
onStep: function(from, to, percent) {
$(this.el).children('.easy_chart_percent').text(Math.round(percent) + '%');
}
});
}
if($('.easy_chart_b').length) {
$('.easy_chart_b').easyPieChart({
animate: 2000,
size: 90,
lineWidth: 4,
scaleColor: false,
barColor: '#c0392b',
trackColor: '#eee',
easing: 'easeOutBounce',
onStep: function(from, to, percent) {
}
});
}
if($('.easy_chart_c').length) {
$('.easy_chart_c').easyPieChart({
animate: 2000,
size: 90,
lineWidth: 4,
scaleColor: false,
barColor: '#4a89dc',
trackColor: '#eee',
easing: 'easeOutBounce',
onStep: function(from, to, percent) {
}
});
}
},
p_pages_user_profile: function() {
if($('.easy_chart_user_tasks').length) {
$('.easy_chart_user_tasks').easyPieChart({
animate: 2000,
size: 60,
lineWidth: 3,
scaleColor: false,
barColor: '#48ac2e',
trackColor: '#ddd',
easing: 'easeOutBounce'
});
}
if($('.easy_chart_user_mails').length) {
$('.easy_chart_user_mails').easyPieChart({
animate: 2000,
size: 60,
lineWidth: 3,
scaleColor: false,
barColor: '#c0392b',
trackColor: '#ddd',
easing: 'easeOutBounce',
onStep: function(from, to, percent) {
$(this.el).children('.easy_chart_percent_text').html(Math.round(percent) + '%<small>Mails</small>');
}
});
}
if($('.easy_chart_user_sale').length) {
$('.easy_chart_user_sale').easyPieChart({
animate: 2000,
size: 60,
lineWidth: 3,
scaleColor: false,
barColor: '#4a89dc',
trackColor: '#ddd',
easing: 'easeOutBounce',
onStep: function(from, to, percent) {
$(this.el).children('.easy_chart_percent').html(Math.round(percent) + '%');
}
});
}
}
};
// footable
yukon_footable = {
p_pages_mailbox: function() {
$('#mailbox_table').footable({
toggleSelector: " > tbody > tr > td > span.footable-toggle"
});
},
p_plugins_tables_footable: function() {
$('#footable_demo').footable({
toggleSelector: " > tbody > tr > td > span.footable-toggle"
}).on({
'footable_filtering': function (e) {
var selected = $('#userStatus').find(':selected').text();
if (selected && selected.length > 0) {
e.filter += (e.filter && e.filter.length > 0) ? ' ' + selected : selected;
e.clear = !e.filter;
}
}
});
$('#clearFilters').click(function(e) {
e.preventDefault();
$('#userStatus').val('');
$('#footable_demo').trigger('footable_clear_filter');
});
$('#userStatus').change(function (e) {
e.preventDefault();
$('#footable_demo').data('footable-filter').filter( $('#textFilter').val() );
});
// clear filters on page load
$('#textFilter, #userStatus').val('');
}
};
// gmaps
yukon_gmaps = {
init: function() {
// basic google maps
new GMaps({
div: '#gmap_basic',
lat: -12.043333,
lng: -77.028333
});
// with markers
map_markers = new GMaps({
el: '#gmap_markers',
lat: 51.500902,
lng: -0.124531
});
map_markers.addMarker({
lat: 51.497714,
lng: -0.12991,
title: 'Westminster',
details: {
// You can attach additional information, which will be passed to Event object (e) in the events previously defined.
},
click: function(e){
alert('You clicked in this marker');
},
mouseover: function(e){
if(console.log) console.log(e);
}
});
map_markers.addMarker({
lat: 51.500891,
lng: -0.123347,
title: 'Westminster Bridge',
infoWindow: {
content: '<div class="infoWindow_content"><p>Westminster Bridge is a road and foot traffic bridge over the River Thames...</p><a href="http://en.wikipedia.org/wiki/Westminster_Bridge" target="_blank">wikipedia</a></div>'
}
});
// static map
var img_scale = window.devicePixelRatio >= 2 ? '&scale=2' : '';
var background_size = window.devicePixelRatio >= 2 ? 'background-size: 640px 640px;' : '';
url = GMaps.staticMapURL({
size: [640, 640],
lat: -37.824972,
lng: 144.958735,
zoom: 10
});
$('#gmap_static').append('<span class="gmap-static" style="height:100%;display:block;background: url('+url+img_scale+') no-repeat 50% 50%;'+background_size+'"><img src="'+url+'" style="visibility:hidden" alt="" /></span>');
// geocoding
map_geocode = new GMaps({
el: '#gmap_geocoding',
lat: 55.478853,
lng: 15.117188,
zoom: 3
});
$('#geocoding_form').submit(function (e) {
e.preventDefault();
GMaps.geocode({
address: $('#gmaps_address').val().trim(),
callback: function (results, status) {
if (status == 'OK') {
var latlng = results[0].geometry.location;
map_geocode.setCenter(latlng.lat(), latlng.lng());
map_geocode.addMarker({
lat: latlng.lat(),
lng: latlng.lng()
});
map_geocode.map.setZoom(15);
$('#gmaps_address').val('');
}
}
});
});
}
};
// checkboxes & radio buttons
yukon_icheck = {
init: function() {
if($('.icheck').length) {
$('.icheck').iCheck({
checkboxClass: 'icheckbox_minimal-blue',
radioClass: 'iradio_minimal-blue'
});
}
}
};
// jBox
yukon_jBox = {
p_components_notifications_popups: function() {
new jBox('Modal', {
width: 340,
height: 180,
attach: $('#jbox_modal_drag'),
draggable: 'title',
closeButton: 'title',
title: 'Click here to drag me around',
content: 'You can move this modal window'
});
new jBox('Confirm', {
closeButton: false,
confirmButton: 'Yes',
cancelButton: 'No',
_onOpen: function() {
// Set the new action for the submit button
this.submitButton
.off('click.jBox-Confirm' + this.id)
.on('click.jBox-Confirm' + this.id, function() {
new jBox('Notice', {
offset: {
y: 36
},
content: 'Comment deleted: id=34'
});
this.close();
}.bind(this));
}
});
$('#jbox_n_default').click(function() {
new jBox('Notice', {
offset: {
y: 36
},
stack: false,
autoClose: 30000,
animation: {
open: 'slide:top',
close: 'slide:right'
},
onInit: function () {
this.options.content = 'Default notification';
}
});
});
$('#jbox_n_audio').click(function() {
new jBox('Notice', {
attributes: {
x: 'right',
y: 'bottom'
},
theme: 'NoticeBorder',
color: 'green',
audio: 'assets/lib/jBox-0.3.0/Source/audio/bling2',
volume: '100',
stack: false,
autoClose: 3000,
animation: {
open: 'slide:bottom',
close: 'slide:left'
},
onInit: function () {
this.options.title = 'Title';
this.options.content = 'Notification with audio effect';
}
});
});
$('#jbox_n_audio50').click(function() {
new jBox('Notice', {
attributes: {
x: 'right',
y: 'top'
},
offset: {
y: 36
},
theme: 'NoticeBorder',
color: 'blue',
audio: 'assets/lib/jBox-0.3.0/Source/audio/beep2',
volume: '60',
stack: false,
autoClose: 3000,
animation: {
open: 'slide:top',
close: 'slide:right'
},
onInit: function () {
this.options.title = 'Title';
this.options.content = 'Volume set to 60%';
}
})
});
}
};
// listNav
yukon_listNav = {
p_pages_user_list: function() {
$('#user_list').listnav({
filterSelector: '.ul_lastName',
includeNums: false,
removeDisabled: true,
showCounts: false,
onClick: function(letter) {
$('.countUsers').text($(".listNavShow").length);
}
});
}
};
// magnific lightbox
yukon_magnific = {
p_components_gallery: function() {
$('.gallery_grid .img_wrapper').magnificPopup({
type: 'image',
gallery:{
enabled: true,
arrowMarkup: '<i title="%title%" class="el-icon-chevron-%dir% mfp-nav"></i>'
},
image: {
titleSrc: function(item) {
return item.el.attr('title') + '<small>' + item.el.children(".gallery_image_tags").text() + '</small>';
}
},
removalDelay: 500, //delay removal by X to allow out-animation
callbacks: {
beforeOpen: function() {
$('html').addClass('magnific-popup-open');
// just a hack that adds mfp-anim class to markup
this.st.image.markup = this.st.image.markup.replace('mfp-figure', 'mfp-figure mfp-with-anim');
this.st.mainClass = 'mfp-zoom-in';
},
close: function() {
$('html').removeClass('magnific-popup-open');
}
},
retina: {
ratio: 2
},
closeOnContentClick: true,
midClick: true // allow opening popup on middle mouse click. Always set it to true if you don't provide alternative source.
});
}
};
// masked inputs
yukon_maskedInputs = {
p_forms_extended: function() {
$("#mask_date").inputmask("dd/mm/yyyy",{ "placeholder": "dd/mm/yyyy", showMaskOnHover: false });
$("#mask_phone").inputmask("mask", {"mask": "(999) 999-9999"});
$("#mask_plate").inputmask({"mask": "[9-]AAA-999"});
$("#mask_numeric").inputmask('€ 999.999,99', { numericInput: false });
$("#mask_mac").inputmask({"mask": "**:**:**:**:**:**"});
$("#mask_callback").inputmask("mm/dd/yyyy",{ "placeholder": "mm/dd/yyyy", "oncomplete": function(){ alert('Date entered: '+$(this).val()); } });
$('[data-inputmask]').inputmask();
}
};
// match height
yukon_matchHeight = {
p_dashboard: function() {
$('.mHeight').each(function() {
$(this).find('.mHeight-item').matchHeight(true);
});
$(window).on("debouncedresize", function() {
$.fn.matchHeight._update();
});
}
}
// validation (parsley.js)
yukon_parsley_validation = {
p_forms_validation: function() {
$('#form_validation').parsley();
},
p_forms_wizard: function() {
$('#wizard_validation').parsley();
var thisIndex = 0;
$.listen('parsley:field:validate', function(e) {
yukon_steps.setContentHeight('#'+e.$element.closest('div.wizard').attr('id'));
});
}
};
// password show/hide
yukon_pwd_show_hide = {
init: function() {
if($('#pwdSt_password').length) {
$('#pwdSt_password').hidePassword(true);
}
}
};
// password strength metter
yukon_pwd_strength_metter = {
init: function() {
if($('#pwdSt_password').length) {
var options = {};
options.ui = {
verdicts: ["Weak", "Normal", "Medium", "Strong", "Very Strong"],
container: "#pwd-container",
showVerdictsInsideProgressBar: true,
viewports: {
progress: ".pwstrength_viewport_progress"
}
};
$('#pwdSt_password').pwstrength(options);
}
}
};
// qrcode
yukon_qrcode = {
p_pages_invoices: function() {
$('#invoice_qrcode').css({'width': gr_code_data.baseSize / 2, 'height': gr_code_data.baseSize / 2}).qrcode({
render: 'canvas',
size: gr_code_data.baseSize,
text: gr_code_data.qrText
}).children('img').prop('title', gr_code_data.qrText);
}
};
// rangeSlider
yukon_rangeSlider = {
p_forms_extended: function() {
if ($("#rS_exm_1").length) {
$("#rS_exm_1").ionRangeSlider({
min: 0,
max: 5000,
from: 1200,
to: 2450,
type: 'double',
prefix: "$",
maxPostfix: "+",
prettify: false,
hasGrid: true
});
}
if ($("#rS_exm_2").length) {
$("#rS_exm_2").ionRangeSlider({
min: 1000,
max: 100000,
from: 30000,
to: 90000,
type: 'double',
step: 500,
postfix: " €",
hasGrid: true
});
}
if ($("#rS_exm_3").length) {
$("#rS_exm_3").ionRangeSlider({
min: 0,
max: 10,
type: 'single',
step: 0.1,
postfix: " carats",
prettify: false,
hasGrid: true
});
}
if ($("#rS_exm_4").length) {
$("#rS_exm_4").ionRangeSlider({
min: -50,
max: 50,
from: 0,
postfix: "°",
prettify: false,
hasGrid: true
});
}
if ($("#rS_exm_5").length) {
$("#rS_exm_5").ionRangeSlider({
min: 10000,
max: 100000,
step: 100,
postfix: " km",
from: 55000,
hideMinMax: true,
hideFromTo: false
});
}
}
};
// select2
yukon_select2 = {
p_forms_extended: function() {
if ($("#s2_basic").length) {
$("#s2_basic").select2({
allowClear: true,
placeholder: "Select..."
});
}
if ($("#s2_multi").length) {
$("#s2_multi").select2({
placeholder: "Select..."
});
}
if($('#s2_tokenization').length) {
$('#s2_tokenization').select2({
placeholder: "Select...",
tags:["red", "green", "blue", "black", "orange", "white"],
tokenSeparators: [",", " "]
});
}
if($('#s2_ext_value').length) {
function format(state) {
if (!state.id) return state.text;
return '<i class="flag-' + state.id + '"></i>' + state.text;
}
$('#s2_ext_value').select2({
placeholder: "Select Country",
formatResult: format,
formatSelection: format,
escapeMarkup: function(markup) { return markup; }
}).val("AU").trigger("change");
$("#s2_ext_us").click(function(e) { e.preventDefault(); $("#s2_ext_value").val("US").trigger("change"); });
$("#s2_ext_br_gb").click(function(e) { e.preventDefault(); $("#s2_ext_value").val(["JP","PL"]).trigger("change"); });
}
if($('#s2_load_data').length) {
$("#s2_load_data").select2({
data:[
{id:0,text:'enhancement'},
{id:1,text:'bug'},
{id:2,text:'duplicate'},
{id:3,text:'invalid'},
{id:4,text:'wontfix'}
]
});
}
},
p_forms_validation: function() {
if($('#val_select').length) {
$('#val_select').select2({
allowClear: true,
placeholder: "Select..."
});
}
},
p_forms_wizard: function() {
if($('#s2_country').length) {
function format(state) {
if (!state.id) return state.text;
return '<i class="flag-' + state.id + '"></i>' + state.text;
}
$('#s2_country').select2({
placeholder: "Select Country",
formatResult: format,
formatSelection: format,
escapeMarkup: function(markup) { return markup; }
});
}
if($('#s2_languages').length) {
$('#s2_languages').select2({
placeholder: "Select language",
tags:["Mandarin", "Spanish", "English", "Hindi", "Arabic", "Portuguese"],
tokenSeparators: [",", " "]
});
}
}
};
// selectize.js
yukon_selectize = {
p_forms_extended: function() {
if($('#slz_optgroups').length) {
$('#slz_optgroups').selectize({
sortField: 'text'
});
}
if($('#slz_contacts').length) {
var REGEX_EMAIL = '([a-z0-9!#$%&\'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&\'*+/=?^_`{|}~-]+)*@' +
'(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)';
var formatName = function(item) {
return $.trim((item.first_name || '') + ' ' + (item.last_name || ''));
};
$('#slz_contacts').selectize({
persist: false,
maxItems: null,
valueField: 'email',
labelField: 'name',
searchField: ['first_name', 'last_name', 'email'],
sortField: [
{field: 'first_name', direction: 'asc'},
{field: 'last_name', direction: 'asc'}
],
options: [
{email: 'nikola@tesla.com', first_name: 'Nikola', last_name: 'Tesla'},
{email: 'brian@thirdroute.com', first_name: 'Brian', last_name: 'Reavis'},
{email: 'someone@gmail.com'}
],
render: {
item: function(item, escape) {
var name = formatName(item);
return '<div>' +
(name ? '<span class="name">' + escape(name) + '</span>' : '') +
(item.email ? '<span class="email">' + escape(item.email) + '</span>' : '') +
'</div>';
},
option: function(item, escape) {
var name = formatName(item);
var label = name || item.email;
var caption = name ? item.email : null;
return '<div>' +
'<span class="label">' + escape(label) + '</span>' +
(caption ? '<span class="caption">' + escape(caption) + '</span>' : '') +
'</div>';
}
},
createFilter: function(input) {
var regexpA = new RegExp('^' + REGEX_EMAIL + '$', 'i');
var regexpB = new RegExp('^([^<]*)\<' + REGEX_EMAIL + '\>$', 'i');
return regexpA.test(input) || regexpB.test(input);
},
create: function(input) {
if ((new RegExp('^' + REGEX_EMAIL + '$', 'i')).test(input)) {
return {email: input};
}
var match = input.match(new RegExp('^([^<]*)\<' + REGEX_EMAIL + '\>$', 'i'));
if (match) {
var name = $.trim(match[1]);
var pos_space = name.indexOf(' ');
var first_name = name.substring(0, pos_space);
var last_name = name.substring(pos_space + 1);
return {
email: match[2],
first_name: first_name,
last_name: last_name
};
}
alert('Invalid email address.');
return false;
}
});
}
if($('#slz_remove_btn').length) {
$('#slz_remove_btn').selectize({
plugins: ['remove_button'],
persist: false,
create: true,
render: {
item: function(data, escape) {
return '<div>"' + escape(data.text) + '"</div>';
}
},
onDelete: function(values) {
return confirm(values.length > 1 ? 'Are you sure you want to remove these ' + values.length + ' items?' : 'Are you sure you want to remove "' + values[0] + '"?');
}
});
}
}
};
// wizard
yukon_steps = {
init: function() {
if ($("#wizard_101").length) {
// initialize wizard
$("#wizard_101").steps({
headerTag: 'h3',
bodyTag: "section",
titleTemplate: "<span class=\"title\">#title#</span>",
enableAllSteps: true,
enableFinishButton: false,
transitionEffect: "slideLeft",
labels: {
next: "Next <i class=\"fa fa-angle-right\"></i>",
previous: "<i class=\"fa fa-angle-left\"></i> Previous",
current: "",
finish: "Agree"
},
onStepChanged: function (event, currentIndex, priorIndex) {
// adjust wizard height
yukon_steps.setContentHeight('#wizard_101')
}
});
// set initial wizard height
yukon_steps.setContentHeight('#wizard_101');
// rezie wizard on window resize
$(window).on('resize',function() {
yukon_steps.setContentHeight('#wizard_101');
})
}
if ($("#wizard_form").length) {
var wizard_form = $('#wizard_form');
// initialize wizard
wizard_form.steps({
headerTag: 'h3',
bodyTag: "section",
enableAllSteps: true,
titleTemplate: "<span class=\"title\">#title#</span>",
transitionEffect: "slideLeft",
labels: {
next: "Next Step <i class=\"fa fa-angle-right\"></i>",
previous: "<i class=\"fa fa-angle-left\"></i> Previous Step",
current: "",
finish: "<i class=\"fa fa-check\"></i> Register"
},
onStepChanging: function (event, currentIndex, newIndex) {
var cursentStep = wizard_form.find('.content > .body').eq(currentIndex);
// check input fields for errors
cursentStep.find('[data-parsley-id]').each(function() {
$(this).parsley().validate();
});
return cursentStep.find('.parsley-error').length ? false : true;
},
onStepChanged: function (event, currentIndex, priorIndex) {
// adjust wizard height
yukon_steps.setContentHeight('#wizard_form');
},
onFinishing: function (event, currentIndex) {
var cursentStep = wizard_form.find('.content > .body').eq(currentIndex);
// check input fields for errors
cursentStep.find('[data-parsley-id]').each(function() {
$(this).parsley().validate();
});
return cursentStep.find('.parsley-error').length ? false : true;
},
onFinished: function(event, currentIndex) {
alert("Submitted!");
// uncomment the following line to submit form
//wizard_form.submit();
}
});
// set initial wizard height
yukon_steps.setContentHeight('#wizard_form');
// rezie wizard on window resize
$(window).on('resize',function() {
yukon_steps.setContentHeight('#wizard_form');
})
}
},
setContentHeight: function($wizard) {
setTimeout(function() {
var cur_height = $($wizard).children('.content').children('.body.current').outerHeight();
$($wizard).find('.content').height(cur_height);
},0);
}
};
// switchery
yukon_switchery = {
init: function() {
if($('.js-switch').length) {
$('.js-switch').each(function() {
new Switchery(this);
})
}
if($('.js-switch-blue').length) {
$('.js-switch-blue').each(function() {
new Switchery(this, { color: '#41b7f1' });
})
}
if($('.js-switch-success').length) {
$('.js-switch-success').each(function() {
new Switchery(this, { color: '#8cc152' });
})
}
if($('.js-switch-warning').length) {
$('.js-switch-warning').each(function() {
new Switchery(this, { color: '#f6bb42' });
})
}
if($('.js-switch-danger').length) {
$('.js-switch-danger').each(function() {
new Switchery(this, { color: '#da4453' });
})
}
if($('.js-switch-info').length) {
$('.js-switch-info').each(function() {
new Switchery(this, { color: '#37bc9b' });
})
}
}
};
// textarea autosize
yukon_textarea_autosize = {
init: function() {
if($('.textarea_auto').length) {
$('.textarea_auto').autosize();
}
}
};
// maxLength for textareas
yukon_textarea_maxlength = {
p_forms_extended: function() {
if($('#ml_default').length) {
$('#ml_default').stopVerbosity({
limit: 20,
existingIndicator: $('#ml_default_indicator')
});
}
if($('#ml_custom').length) {
$('#ml_custom').stopVerbosity({
limit: 32,
existingIndicator: $('#ml_custom_indicator'),
indicatorPhrase: [
'This is a custom indicator phrase.',
'This one only counts down. Only', '<span class="label label-primary">[countdown]</span>', 'characters', 'left.'
]
})
}
}
};
// typeahead
yukon_typeahead = {
init: function() {
var substringMatcher = function (strs) {
return function findMatches(q, cb) {
var matches, substrRegex;
// an array that will be populated with substring matches
matches = [];
// regex used to determine if a string contains the substring `q`
substrRegex = new RegExp(q, 'i');
// iterate through the pool of strings and for any string that
// contains the substring `q`, add it to the `matches` array
$.each(strs, function (i, str) {
if (substrRegex.test(str)) {
// the typeahead jQuery plugin expects suggestions to a
// JavaScript object, refer to typeahead docs for more info
matches.push({value: str});
}
});
cb(matches);
};
};
var states = ['Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California', 'Colorado', 'Connecticut', 'Delaware', 'Florida', 'Georgia', 'Hawaii', 'Idaho', 'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky', 'Louisiana', 'Maine', 'Maryland', 'Massachusetts', 'Michigan', 'Minnesota', 'Mississippi', 'Missouri', 'Montana', 'Nebraska', 'Nevada', 'New Hampshire', 'New Jersey', 'New Mexico', 'New York', 'North Carolina', 'North Dakota', 'Ohio', 'Oklahoma', 'Oregon', 'Pennsylvania', 'Rhode Island', 'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah', 'Vermont', 'Virginia', 'Washington', 'West Virginia', 'Wisconsin', 'Wyoming'];
$('#main_header .search_section > input').val('').typeahead({
hint: true,
highlight: true,
minLength: 1
},
{
name: 'states',
displayKey: 'value',
source: substringMatcher(states)
});
}
}
// multiuploader
yukon_uploader = {
p_forms_extended: function() {
if($('#uploader').length) {
$("#uploader").pluploadQueue({
// General settings
runtimes : 'html5,flash,silverlight,html4',
url : "/upload",
chunk_size : '1mb',
rename : true,
dragdrop: true,
filters : {
// Maximum file size
max_file_size : '10mb',
// Specify what files to browse for
mime_types: [
{title : "Image files", extensions : "jpg,gif,png"},
{title : "Zip files", extensions : "zip"}
]
},
// Resize images on clientside if we can
resize: {
width : 200,
height : 200,
quality : 90,
crop: true // crop to exact dimensions
},
// Flash settings
flash_swf_url : 'assets/lib/plupload/js/Moxie.swf',
// Silverlight settings
silverlight_xap_url : 'assets/lib/plupload/js/Moxie.xap'
});
}
}
};
// vector maps
yukon_vector_maps = {
p_dashboard: function() {
if($('#world_map_vector').length) {
$('#world_map_vector').vectorMap({
map: 'world_mill_en',
backgroundColor: 'transparent',
regionStyle: {
initial: {
fill: '#c8c8c8'
},
hover: {
"fill-opacity": 1
}
},
series: {
regions: [{
values: countries_data,
scale: ['#58bbdf', '#1c7393'],
normalizeFunction: 'polynomial'
}]
},
onRegionLabelShow: function(e, el, code){
if(typeof countries_data[code] == 'undefined') {
e.preventDefault();
} else {
var countryLabel = countries_data[code];
el.html(el.html()+': '+countryLabel+' visits');
}
}
});
}
},
p_plugins_vector_maps: function() {
// random colors
var palette = ['#1f77b4', '#3a9add', '#888'];
function generateColors() {
var colors = {},
key;
for (key in map_ca.regions) {
colors[key] = palette[Math.floor(Math.random() * palette.length)];
}
return colors;
};
function updateColors() {
map_ca.series.regions[0].setValues(generateColors());
};
$('#updateColors').click(function(e) {
e.preventDefault();
updateColors();
})
map_ca = new jvm.WorldMap({
map: 'ca_mill_en',
container: $('#vmap_canada'),
backgroundColor: 'transparent',
series: {
regions: [
{
attribute: 'fill'
}
]
}
});
map_ca.series.regions[0].setValues(generateColors());
// markers on the map
$('#vmap_markers').vectorMap({
map: 'world_mill_en',
backgroundColor: 'transparent',
scaleColors: ['#c8eeff', '#0071a4'],
normalizeFunction: 'polynomial',
hoverColor: false,
regionStyle: {
initial: {
fill: '#888'
},
hover: {
"fill-opacity": 1
}
},
markerStyle: {
initial: {
fill: '#fff',
stroke: '#1f77b4'
},
hover: {
fill: '#13476c',
stroke: '#13476c'
}
},
markers: [
{latLng: [41.90, 12.45], name: 'Vatican City'},
{latLng: [43.73, 7.41], name: 'Monaco'},
{latLng: [-0.52, 166.93], name: 'Nauru'},
{latLng: [-8.51, 179.21], name: 'Tuvalu'},
{latLng: [43.93, 12.46], name: 'San Marino'},
{latLng: [47.14, 9.52], name: 'Liechtenstein'},
{latLng: [7.11, 171.06], name: 'Marshall Islands'},
{latLng: [17.3, -62.73], name: 'Saint Kitts and Nevis'},
{latLng: [3.2, 73.22], name: 'Maldives'},
{latLng: [35.88, 14.5], name: 'Malta'},
{latLng: [12.05, -61.75], name: 'Grenada'},
{latLng: [13.16, -61.23], name: 'Saint Vincent and the Grenadines'},
{latLng: [13.16, -59.55], name: 'Barbados'},
{latLng: [17.11, -61.85], name: 'Antigua and Barbuda'},
{latLng: [-4.61, 55.45], name: 'Seychelles'},
{latLng: [7.35, 134.46], name: 'Palau'},
{latLng: [42.5, 1.51], name: 'Andorra'},
{latLng: [14.01, -60.98], name: 'Saint Lucia'},
{latLng: [6.91, 158.18], name: 'Federated States of Micronesia'},
{latLng: [1.3, 103.8], name: 'Singapore'},
{latLng: [1.46, 173.03], name: 'Kiribati'},
{latLng: [-21.13, -175.2], name: 'Tonga'},
{latLng: [15.3, -61.38], name: 'Dominica'},
{latLng: [-20.2, 57.5], name: 'Mauritius'},
{latLng: [26.02, 50.55], name: 'Bahrain'},
{latLng: [0.33, 6.73], name: 'São Tomé and Príncipe'}
]
});
}
};
// wysiwg editor
yukon_wysiwg = {
p_forms_validation: function() {
if ($('#val_textarea_message').length) {
var editor_validate = $('textarea#val_textarea_message').ckeditor();
}
},
p_forms_extended: function() {
if ($('#wysiwg_editor').length) {
$('#wysiwg_editor').ckeditor();
}
}
};
| ubiquitous-computing-lab/Mining-Minds | supporting-layer/descriptive-analytics/src/assets/js/yukon_all.js | JavaScript | apache-2.0 | 89,162 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_151) on Mon Jun 22 05:15:26 MST 2020 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>org.wildfly.swarm.config.messaging.activemq.server.ha_policy.replication_colocated Class Hierarchy (BOM: * : All 2.7.1.Final-SNAPSHOT API)</title>
<meta name="date" content="2020-06-22">
<link rel="stylesheet" type="text/css" href="../../../../../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="org.wildfly.swarm.config.messaging.activemq.server.ha_policy.replication_colocated Class Hierarchy (BOM: * : All 2.7.1.Final-SNAPSHOT API)";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li>Class</li>
<li>Use</li>
<li class="navBarCell1Rev">Tree</li>
<li><a href="../../../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage">Thorntail API, 2.7.1.Final-SNAPSHOT</div>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/package-tree.html">Prev</a></li>
<li><a href="../../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/ha_policy/shared_store_colocated/package-tree.html">Next</a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../../../index.html?org/wildfly/swarm/config/messaging/activemq/server/ha_policy/replication_colocated/package-tree.html" target="_top">Frames</a></li>
<li><a href="package-tree.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h1 class="title">Hierarchy For Package org.wildfly.swarm.config.messaging.activemq.server.ha_policy.replication_colocated</h1>
<span class="packageHierarchyLabel">Package Hierarchies:</span>
<ul class="horizontal">
<li><a href="../../../../../../../../../overview-tree.html">All Packages</a></li>
</ul>
</div>
<div class="contentContainer">
<h2 title="Class Hierarchy">Class Hierarchy</h2>
<ul>
<li type="circle">java.lang.<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang"><span class="typeNameLink">Object</span></a>
<ul>
<li type="circle">org.wildfly.swarm.config.messaging.activemq.server.ha_policy.replication_colocated.<a href="../../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/ha_policy/replication_colocated/MasterConfiguration.html" title="class in org.wildfly.swarm.config.messaging.activemq.server.ha_policy.replication_colocated"><span class="typeNameLink">MasterConfiguration</span></a><T></li>
<li type="circle">org.wildfly.swarm.config.messaging.activemq.server.ha_policy.replication_colocated.<a href="../../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/ha_policy/replication_colocated/SlaveConfiguration.html" title="class in org.wildfly.swarm.config.messaging.activemq.server.ha_policy.replication_colocated"><span class="typeNameLink">SlaveConfiguration</span></a><T></li>
</ul>
</li>
</ul>
<h2 title="Interface Hierarchy">Interface Hierarchy</h2>
<ul>
<li type="circle">org.wildfly.swarm.config.messaging.activemq.server.ha_policy.replication_colocated.<a href="../../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/ha_policy/replication_colocated/MasterConfigurationConsumer.html" title="interface in org.wildfly.swarm.config.messaging.activemq.server.ha_policy.replication_colocated"><span class="typeNameLink">MasterConfigurationConsumer</span></a><T></li>
<li type="circle">org.wildfly.swarm.config.messaging.activemq.server.ha_policy.replication_colocated.<a href="../../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/ha_policy/replication_colocated/MasterConfigurationSupplier.html" title="interface in org.wildfly.swarm.config.messaging.activemq.server.ha_policy.replication_colocated"><span class="typeNameLink">MasterConfigurationSupplier</span></a><T></li>
<li type="circle">org.wildfly.swarm.config.messaging.activemq.server.ha_policy.replication_colocated.<a href="../../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/ha_policy/replication_colocated/SlaveConfigurationConsumer.html" title="interface in org.wildfly.swarm.config.messaging.activemq.server.ha_policy.replication_colocated"><span class="typeNameLink">SlaveConfigurationConsumer</span></a><T></li>
<li type="circle">org.wildfly.swarm.config.messaging.activemq.server.ha_policy.replication_colocated.<a href="../../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/ha_policy/replication_colocated/SlaveConfigurationSupplier.html" title="interface in org.wildfly.swarm.config.messaging.activemq.server.ha_policy.replication_colocated"><span class="typeNameLink">SlaveConfigurationSupplier</span></a><T></li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li>Class</li>
<li>Use</li>
<li class="navBarCell1Rev">Tree</li>
<li><a href="../../../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage">Thorntail API, 2.7.1.Final-SNAPSHOT</div>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/package-tree.html">Prev</a></li>
<li><a href="../../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/ha_policy/shared_store_colocated/package-tree.html">Next</a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../../../index.html?org/wildfly/swarm/config/messaging/activemq/server/ha_policy/replication_colocated/package-tree.html" target="_top">Frames</a></li>
<li><a href="package-tree.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2020 <a href="http://www.jboss.org">JBoss by Red Hat</a>. All rights reserved.</small></p>
</body>
</html>
| wildfly-swarm/wildfly-swarm-javadocs | 2.7.1.Final-SNAPSHOT/apidocs/org/wildfly/swarm/config/messaging/activemq/server/ha_policy/replication_colocated/package-tree.html | HTML | apache-2.0 | 8,400 |
// Copyright 2009-2017 Brad Sokol
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// MainViewController.h
// FieldTools
//
// Created by Brad on 2008/11/29.
//
#import <UIKit/UIKit.h>
#import "FlipsideViewController.h"
#import "SubjectDistanceSliderPolicy.h"
@class DistanceFormatter;
@class ResultView;
@protocol AnalyticsPolicy;
@interface MainViewController : UIViewController <FlipsideViewControllerDelegate, UIActionSheetDelegate>
{
IBOutlet UIButton *cameraAndLensDescription;
IBOutlet UIButton *infoButton;
IBOutlet UILabel* apertureLabel;
IBOutlet UISlider* apertureSlider;
IBOutlet UILabel* apertureText;
IBOutlet UILabel* apertureMinimum;
IBOutlet UILabel* apertureMaximum;
IBOutlet UISegmentedControl* distanceType;
IBOutlet UISlider* focalLengthSlider;
IBOutlet UILabel* focalLengthText;
IBOutlet UILabel* focalLengthMinimum;
IBOutlet UILabel* focalLengthMaximum;
__weak IBOutlet NSLayoutConstraint*apertureToFocalLengthConstraint;
IBOutlet UISlider* subjectDistanceSlider;
IBOutlet UILabel* subjectDistanceLabel;
IBOutlet UILabel* subjectDistanceText;
IBOutlet UILabel* subjectDistanceMinimum;
IBOutlet UILabel* subjectDistanceMaximum;
IBOutlet UIButton* subjectDistanceRangeText;
IBOutlet ResultView* resultView;
DistanceFormatter* distanceFormatter;
NSInteger apertureIndex;
float circleOfLeastConfusion;
float focalLength;
float subjectDistance;
NSMutableArray* apertures;
SubjectDistanceSliderPolicy* subjectDistanceSliderPolicy;
}
- (IBAction)subjectDistanceRangeTextWasTouched:(id)sender;
- (IBAction)apertureDidChange:(id)sender;
- (IBAction)distanceTypeDidChange:(id)sender;
- (IBAction)focalLengthDidChange:(id)sender;
- (IBAction)subjectDistanceDidChange:(id)sender;
- (float)aperture;
- (IBAction)toggleView;
@property (nonatomic, strong) UIButton* cameraAndLensDescription;
@property (nonatomic, strong) UIButton *infoButton;
@property(assign) float circleOfLeastConfusion;
@property(assign) float focalLength;
@property(assign) float subjectDistance;
@property(nonatomic, strong) id<AnalyticsPolicy> analyticsPolicy;
@end
| bradsokol/iphonefieldtools | src/Classes/MainViewController.h | C | apache-2.0 | 2,625 |
<!-- Do not edit this file. It is automatically generated by API Documenter. -->
[Home](./index.md) > [puppeteer](./puppeteer.md) > [Protocol](./puppeteer.protocol.md) > [Input](./puppeteer.protocol.input.md) > [SynthesizePinchGestureRequest](./puppeteer.protocol.input.synthesizepinchgesturerequest.md) > [y](./puppeteer.protocol.input.synthesizepinchgesturerequest.y.md)
## Protocol.Input.SynthesizePinchGestureRequest.y property
Y coordinate of the start of the gesture in CSS pixels.
<b>Signature:</b>
```typescript
y: number;
```
| GoogleChrome/puppeteer | new-docs/puppeteer.protocol.input.synthesizepinchgesturerequest.y.md | Markdown | apache-2.0 | 568 |
package org.wordcounthbase;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public class DirectoryScanner {
public static List<File> getFileList(String directoryPath) {
List<File> fileList = new ArrayList<File>();
addTree(new File(directoryPath), fileList);
return fileList;
}
private static void addTree(File file, Collection<File> all) {
File[] children = file.listFiles();
if (children != null) {
for (File child : children) {
all.add(child);
addTree(child, all);
}
}
}
} | arks-api/arks-api | modules-samples/wordcount-hbase/src/org/wordcounthbase/DirectoryScanner.java | Java | apache-2.0 | 651 |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev;
import java.util.ArrayList ;
import java.util.List ;
import org.apache.jena.sparql.syntax.* ;
import org.apache.jena.sparql.syntax.syntaxtransform.ElementTransformCopyBase ;
/**
* Clean a SPARQL and ARQ syntax. This applies after using OpAsQuery.
* <ul>
* <li>Unwrap groups of one where they do not matter.
* <li>Merge adjacent ElementPathBlock</li>
* </ul>
* Groups of one do matter for <code>OPTIONAL { { ?s ?p ?o FILTER(?foo) } }</code>.
*/
public class ElementTransformCleanGroups extends ElementTransformCopyBase {
// ElementTransformCleanGroupsOfOne -> ElementTransformCleanGroups
private ElementTransformCleanGroups() {}
@Override
public Element transform(ElementGroup eltGroup, List<Element> elts) {
if ( elts.size() != 1 ) {
List<Element> elts2 = mergeAdjacent(elts) ;
return super.transform(eltGroup, elts2) ;
}
Element elt = elts.get(0) ;
// These ones may clash with an adjacent one in the group above.
if ( ( elt instanceof ElementTriplesBlock ) ||
( elt instanceof ElementPathBlock ) ||
( elt instanceof ElementFilter ) )
return super.transform(eltGroup, elts) ; // No transformation.
return elt ;
}
// Merge adjacent if safe.
// ** Currently copy always.
private List<Element> mergeAdjacent(List<Element> elts) {
boolean changed = true ;
List<Element> elts2 = new ArrayList<>() ;
Element lastElt = null ;
for ( Element elt : elts ) {
if ( lastElt == null ) {
lastElt = elt ;
continue ;
}
Element eltNew = null ;
if ( ( elt instanceof ElementTriplesBlock ) && ( lastElt instanceof ElementTriplesBlock ) )
{
ElementTriplesBlock blk1 = (ElementTriplesBlock)lastElt ;
ElementTriplesBlock blk2 = (ElementTriplesBlock)elt ;
ElementTriplesBlock blk3 = new ElementTriplesBlock() ;
blk3.getPattern().addAll(blk1.getPattern());
blk3.getPattern().addAll(blk2.getPattern());
lastElt = blk3 ;
changed = true ;
}
else if ( ( elt instanceof ElementPathBlock ) && ( lastElt instanceof ElementPathBlock ) )
{
ElementPathBlock blk1 = (ElementPathBlock)lastElt ;
ElementPathBlock blk2 = (ElementPathBlock)elt ;
ElementPathBlock blk3 = new ElementPathBlock() ;
blk3.getPattern().addAll(blk1.getPattern());
blk3.getPattern().addAll(blk2.getPattern());
lastElt = blk3 ;
changed = true ;
} else {
elts2.add(lastElt) ;
lastElt = elt ;
}
}
if ( lastElt != null ) {
elts2.add(lastElt) ;
}
if ( ! changed )
return elts ;
return elts2 ;
}
// Special case: If Optional, and the original had a {{}} protected filter, keep {{}}
// transform/ElementGroup has already run so undo if necessary.
@Override
public Element transform(ElementOptional eltOptional, Element transformedElt) {
// RHS of optional is always an ElementGroup in a normal syntax tree.
if ( ! ( transformedElt instanceof ElementGroup ) ) {
ElementGroup protectedElt = new ElementGroup() ;
protectedElt.addElement(transformedElt);
transformedElt = protectedElt ;
}
// Does the original eltOptional have a {{}} RHS?
Element x = eltOptional.getOptionalElement() ;
if ( ! ( x instanceof ElementGroup ) )
// No. But it is not possible in written query syntax to have a nongroup as the RHS.
return super.transform(eltOptional, transformedElt) ;
// So far - {}-RHS.
ElementGroup eGroup = (ElementGroup)x ;
// Is it {{}}?
//ElementGroup inner = getGroupInGroup(x) ;
if ( eGroup.size() != 1 )
return super.transform(eltOptional, transformedElt) ;
Element inner = eGroup.get(0) ;
if ( ! ( inner instanceof ElementGroup ) )
return super.transform(eltOptional, transformedElt) ;
// Yes - {{}}
ElementGroup innerGroup = (ElementGroup)inner ;
// Unbundle multiple levels.
innerGroup = unwrap(innerGroup) ;
boolean mustProtect = containsFilter(innerGroup) ;
if ( mustProtect ) {
// No need to check for {{}} in elt1 as the transform(ElementGroup) will have processed it.
ElementGroup protectedElt = new ElementGroup() ;
protectedElt.addElement(transformedElt);
return new ElementOptional(protectedElt) ;
}
// No need to protect - process as usual.
return super.transform(eltOptional, transformedElt) ;
}
private boolean containsFilter(ElementGroup eltGroup) {
return eltGroup.getElements().stream().anyMatch(el2 ->( el2 instanceof ElementFilter ) ) ;
}
// Removed layers of groups of one. Return inner most group.
private ElementGroup unwrap(ElementGroup eltGroup) {
if ( eltGroup.size() != 1 )
return eltGroup ;
Element el = eltGroup.get(0) ;
if ( ! ( el instanceof ElementGroup ) )
return eltGroup ;
ElementGroup eltGroup2 = (ElementGroup)el ;
return unwrap(eltGroup2) ;
}
}
| afs/jena-reports | src/dev/ElementTransformCleanGroups.java | Java | apache-2.0 | 6,396 |
#include<iostream>
#include<cstdlib>
using namespace std;
class MyType
{
public :
int value;
MyType(int i);
int compare(MyType y);
};
MyType::MyType(int i)//¹¹Ô캯Êý
{
this->value = i ;
}
int MyType::compare(MyType y)
{
if(value > y.value)
return 1;
else
return -1;
}
MyType max(MyType x, MyType y)
{
if(x.compare(y) > 0)
return x;
else
return y;
}
template<class Type>
Type max(Type x, Type y)
{
return (x > y ? x : y);
}
void Swap(MyType &x, MyType &y)
{
MyType temp = x;
x = y;
y = temp;
}
void sort(MyType *MyArray, int size)
{
for(int i = 0; i < size; i++){
for(int j = 0; j < size- i -1; j++){
if(max(MyArray[j], MyArray[j + 1]).value == MyArray[j].value){
Swap(MyArray[j], MyArray[j + 1]);
}
}
}
}
void Disp(MyType *MyArray, int size)
{
for(int i = 0;i < size; i++)
cout<<MyArray[i].value<<" ";
cout<<endl;
}
int main()
{
int a, b;
a= rand();
b= rand();
MyType A(a), B(b);
cout<<"a= "<<a<<endl;
cout<<"b= "<<b<<endl;
MyType myarray[] = {MyType(82), MyType(34), MyType(26), MyType(77), MyType(68)};
sort(myarray, 5);
Disp(myarray, 5);
return 0;
} | WeAreChampion/notes | c/template/类模板.cpp | C++ | apache-2.0 | 1,106 |
<?php
namespace app\user\controller;
use cmf\controller\UserBaseController;
use think\Db;
class IndexController extends UserBaseController
{
// 前台用户首页 (公开)
public function index()
{
$id = input("get.id", 0, 'intval');
$users_model = Db::name("User");
$user = $users_model->where('id', $id)->find();
if (empty($user)) {
session('user', null);
$this->error("查无此人!");
}
$this->assign($user);
$this->display(":index");
}
// 前台ajax 判断用户登录状态接口
function is_login()
{
if (sp_is_user_login()) {
$this->ajaxReturn(["status" => 1, "user" => sp_get_current_user()]);
} else {
$this->ajaxReturn(["status" => 0, "info" => "此用户未登录!"]);
}
}
//退出
public function logout()
{
$ucenter_syn = C("UCENTER_ENABLED");
$login_success = false;
if ($ucenter_syn) {
include UC_CLIENT_ROOT . "client.php";
echo uc_user_synlogout();
}
session("user", null);//只有前台用户退出
redirect(__ROOT__ . "/");
}
}
| txterm/txsprider | app/user/controller/IndexController.php | PHP | apache-2.0 | 1,212 |
package egovframework.com.sts.bst.service;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
/**
* 게시물 통계 집계를 위한 스케줄링 클래스
* @author 공통서비스 개발팀 박지욱
* @since 2009.04.16
* @version 1.0
* @see
*
* <pre>
* << 개정이력(Modification Information) >>
*
* 수정일 수정자 수정내용
* ------- -------- ---------------------------
* 2009.04.16 박지욱 최초 생성
* 2011.06.30 이기하 패키지 분리(sts -> sts.bst)
*
* </pre>
*/
@Service("egovBbsStatsScheduling")
public class EgovBbsStatsScheduling {
/** EgovBbsStatsService */
@Resource(name = "bbsStatsService")
private EgovBbsStatsService bbsStatsService;
/**
* 게시물 통계를 위한 집계를 하루단위로 작업하는 배치 프로그램
* @exception Exception
*/
public void summaryBbsStats() throws Exception {
bbsStatsService.summaryBbsStats();
}
}
| dasomel/egovframework | common-component/v2.3.2/src/main/java/egovframework/com/sts/bst/service/EgovBbsStatsScheduling.java | Java | apache-2.0 | 1,036 |
<!DOCTYPE html>
<html>
<head>
<link href="js/bootstrap.min.css" rel="stylesheet"type="text/css">
<link href="css/moncss.css" rel="stylesheet"type="text/css">
<script type="text/javascript" src="js/jquery-3.1.1.min.js"> </script>
<script type="text/javascript" src="js/typeahead.min.js"></script>
<script type="text/javascript" src="js/bootstrap.min.js"></script>
<script type="text/javascript" src="js/formulaire.js"></script>
<title>List of AMD graphics processing units - IGP (X12xx, 21xx) </title>
<meta charset="utf-8">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-2"> </div>
<div class="col-md-8">
<h1>List of AMD graphics processing units - IGP (X12xx, 21xx) </h1>
</div>
<div class="col-md-2"> </div>
</div>
<div class="row">
<fieldset>
<div class="col-md-2"> </div>
<div class="col-md-8">
<form action="" method="post">
<legend style="color:red;font-weight: bold;font-style:italic;text-align: center;" >Formulaire</legend>
</br>
<label>Memory clock (MHz) : </label></br> <input id="0" type="text" name="Feature"></br>
</br>
<label>Core clock (MHz) : </label></br> <input style="display:block;" id="id1Core clock (MHz)" type="number" name="Feature">
<input style="display:none;" id="id2Core clock (MHz)" type="text"/>
<button class="btn btn-primary btn-xs" type="button" onClick="switchFunction('id1Core clock (MHz)','id2Core clock (MHz)');">Changer type</button></br> </br>
<label>Launch :</label></br>
<input type="checkbox" name="Feature" >Aug. 29</br>
<input type="checkbox" name="Feature" >2006 (Intel)</br>
<input type="checkbox" name="Feature" >Feb. 28</br>
<input type="checkbox" name="Feature" >2007 (AMD)</br>
<input type="checkbox" name="Feature" >March 4</br>
<input type="checkbox" name="Feature" >2008</br>
<input type='checkbox'><label>autre:</label></br><input type="text"/> </br>
</br>
<label>Fillrate - MTexels/s : </label></br> <input style="display:block;" id="id1Fillrate - MTexels/s" type="number" name="Feature">
<input style="display:none;" id="id2Fillrate - MTexels/s" type="text"/>
<button class="btn btn-primary btn-xs" type="button" onClick="switchFunction('id1Fillrate - MTexels/s','id2Fillrate - MTexels/s');">Changer type</button></br> </br>
<label>Fillrate - MPixels/s : </label></br> <input style="display:block;" id="id1Fillrate - MPixels/s" type="number" name="Feature">
<input style="display:none;" id="id2Fillrate - MPixels/s" type="text"/>
<button class="btn btn-primary btn-xs" type="button" onClick="switchFunction('id1Fillrate - MPixels/s','id2Fillrate - MPixels/s');">Changer type</button></br> </br>
<label>Fillrate - MOperations/s : </label></br> <input style="display:block;" id="id1Fillrate - MOperations/s" type="number" name="Feature">
<input style="display:none;" id="id2Fillrate - MOperations/s" type="text"/>
<button class="btn btn-primary btn-xs" type="button" onClick="switchFunction('id1Fillrate - MOperations/s','id2Fillrate - MOperations/s');">Changer type</button></br> </br>
<label>Fillrate - MVertices/s : </label></br> <input style="display:block;" id="id1Fillrate - MVertices/s" type="number" name="Feature">
<input style="display:none;" id="id2Fillrate - MVertices/s" type="text"/>
<button class="btn btn-primary btn-xs" type="button" onClick="switchFunction('id1Fillrate - MVertices/s','id2Fillrate - MVertices/s');">Changer type</button></br> </br>
<label>Config core : </label></br> <input id="1" type="text" name="Feature"></br>
</br>
<label>Bus interface : </label></br> <input id="2" type="text" name="Feature"></br>
</br>
<label>Fab (nm) : </label></br> <input style="display:block;" id="id1Fab (nm)" type="number" name="Feature">
<input style="display:none;" id="id2Fab (nm)" type="text"/>
<button class="btn btn-primary btn-xs" type="button" onClick="switchFunction('id1Fab (nm)','id2Fab (nm)');">Changer type</button></br> </br>
<label>Memory (MB) : </label></br> <input id="3" type="text" name="Feature"></br>
</br>
<label>Model : </label></br> <input id="4" type="text" name="Feature"></br>
</br>
<label>Code name : </label></br> <input id="5" type="text" name="Feature"></br>
</br>
<label>Memory - Bandwidth (GB/s) : </label></br> <input id="6" type="text" name="Feature"></br>
</br>
<label>Memory - Bus width (bit) : </label></br> <input style="display:block;" id="id1Memory - Bus width (bit)" type="number" name="Feature">
<input style="display:none;" id="id2Memory - Bus width (bit)" type="text"/>
<button class="btn btn-primary btn-xs" type="button" onClick="switchFunction('id1Memory - Bus width (bit)','id2Memory - Bus width (bit)');">Changer type</button></br> </br>
<label>Memory - Bus type : </label></br> <input id="7" type="text" name="Feature"></br>
<script>
$("#0").typeahead({
name:"list0",
local : ['400 - 800','']
});
$("#1").typeahead({
name:"list1",
local : ['4:2:4:4','']
});
$("#2").typeahead({
name:"list2",
local : ['FSB, HT 2.0','HT 2.0','']
});
$("#3").typeahead({
name:"list3",
local : ['256 - 512','']
});
$("#4").typeahead({
name:"list4",
local : ['Radeon Xpress X1200','Radeon Xpress X1250','Radeon Xpress 2100','']
});
$("#5").typeahead({
name:"list5",
local : ['RS740 (titan)','RS600, RS690 (zeus)','RS690C (zeus)','']
});
</script>
</br><input type="submit" class="btn btn-info" value="Ajouter un produit" />
</form>
</div>
</fieldset>
<div class="col-md-2"> </div>
</div>
</div>
</body>
</html> | Ophelle/PDL | pcms/List_of_AMD_graphics_processing_units_12.pcm.html | HTML | apache-2.0 | 6,183 |
<?php
namespace lb\components;
use lb\BaseClass;
class Pagination extends BaseClass
{
public static function getParams($total, $page_size, $page = 1)
{
$pageTotal = ceil($total / $page_size);
$offset = ($page - 1) * $page_size;
if ($page != $pageTotal) {
$limit = $page_size;
} else {
$limit = $total % $page_size ? : $page_size;
}
return [$offset, $limit];
}
}
| luoxiaojun1992/lb_framework | components/Pagination.php | PHP | apache-2.0 | 449 |
package com.bq.corbel.iam.service;
import java.util.List;
import org.springframework.dao.DataIntegrityViolationException;
import com.bq.corbel.iam.exception.DuplicatedOauthServiceIdentityException;
import com.bq.corbel.iam.exception.IdentityAlreadyExistsException;
import com.bq.corbel.iam.model.Identity;
import com.bq.corbel.iam.model.User;
import com.bq.corbel.iam.repository.IdentityRepository;
/**
* @author Rubén Carrasco
*
*/
public class DefaultIdentityService implements IdentityService {
private final IdentityRepository identityRepository;
public DefaultIdentityService(IdentityRepository identityRepository) {
this.identityRepository = identityRepository;
}
@Override
public Identity addIdentity(Identity identity) throws DuplicatedOauthServiceIdentityException, IdentityAlreadyExistsException {
if (identityRepository.existsByDomainAndUserIdAndOauthService(identity.getDomain(), identity.getUserId(),
identity.getOauthService())) {
throw new DuplicatedOauthServiceIdentityException();
}
try {
return identityRepository.save(identity);
} catch (DataIntegrityViolationException e) {
throw new IdentityAlreadyExistsException();
}
}
@Override
public void deleteUserIdentities(User user) {
identityRepository.deleteByUserIdAndDomain(user.getId(), user.getDomain());
}
@Override
public List<Identity> findUserIdentities(User user) {
return identityRepository.findByUserIdAndDomain(user.getId(), user.getDomain());
}
}
| bq/corbel | iam/src/main/java/com/bq/corbel/iam/service/DefaultIdentityService.java | Java | apache-2.0 | 1,605 |
package apycazo.codex.testing.spring;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
@Slf4j
@Service
public class SpringService {
private final SpringComponent component;
public SpringService(SpringComponent component) {
this.component = component;
}
public void init() {
component.addValues(1,2,3,4,5);
}
public int sum() {
return component.sum();
}
public void addValue(int v) {
component.addValues(v);
}
public void clear() {
component.clear();
}
}
| apycazo/codex | codex-testing/src/main/java/apycazo/codex/testing/spring/SpringService.java | Java | apache-2.0 | 537 |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
// Generated from: GetCacheBindingResponse.proto
namespace Alachisoft.NCache.Common.Protobuf
{
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"GetCacheBindingResponse")]
public partial class GetCacheBindingResponse : global::ProtoBuf.IExtensible
{
public GetCacheBindingResponse() {}
private string _server = "";
[global::ProtoBuf.ProtoMember(1, IsRequired = false, Name=@"server", DataFormat = global::ProtoBuf.DataFormat.Default)]
[global::System.ComponentModel.DefaultValue("")]
public string server
{
get { return _server; }
set { _server = value; }
}
private int _port = default(int);
[global::ProtoBuf.ProtoMember(2, IsRequired = false, Name=@"port", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
[global::System.ComponentModel.DefaultValue(default(int))]
public int port
{
get { return _port; }
set { _port = value; }
}
private bool _isRunning = default(bool);
[global::ProtoBuf.ProtoMember(3, IsRequired = false, Name=@"isRunning", DataFormat = global::ProtoBuf.DataFormat.Default)]
[global::System.ComponentModel.DefaultValue(default(bool))]
public bool isRunning
{
get { return _isRunning; }
set { _isRunning = value; }
}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}
}
| Alachisoft/NCache | Src/NCCommon/Protobuf/GetCacheBindingResponse.cs | C# | apache-2.0 | 1,919 |
import sys
import numpy as np
from normalization import tokenize
from helpers import ahash
class KerasVectorizer():
'''
Convert list of documents to numpy array for input into Keras model
'''
def __init__(self, n_features=100000, maxlen=None, maxper=100, hash_function=ahash):
self.maxlen = maxlen
self.maxper = maxper
self.n_features = n_features
self.hash_function = hash_function
def _exact_hash(self, word, n_features):
return self.token_lookup.get(word, 0)
def fit_transform(self, raw_documents, y=None, suffix='', verbose=True):
if verbose:
print >> sys.stderr, 'splitting raw documents'
# Some way to print progress?
tokens = map(self._split_function, raw_documents)
if self.maxlen:
maxlen = self.maxlen
else:
maxlen = int(np.percentile(map(len, tokens), self.maxper))
self.maxlen = maxlen
X = np.zeros((len(tokens), maxlen))
for i,t in enumerate(tokens):
if verbose:
if not i % 10000:
print >> sys.stderr, 'processed %d tokens' % i
if len(t) > 0:
X[i,-len(t):] = map(lambda x: self.hash_function(x + suffix, self.n_features), t[:maxlen])
return X
class KerasCharacterVectorizer(KerasVectorizer):
'''
Split a string into characters
'''
def _split_function(self, doc):
return list(doc)
class KerasTokenVectorizer(KerasVectorizer):
'''
Split a string into words,
'''
def _split_function(self, doc):
return tokenize(doc, keep_punctuation=True)
class KerasPretokenizedVectorizer(KerasVectorizer):
def _split_function(self, doc):
return doc
'''
from keras_vectorizer import KerasTokenVectorizer, KerasCharacterVectorizer
ktv = KerasTokenVectorizer()
ktv.fit_transform(['this is a test'])
ktv.fit_transform(['this is a test', 'this is a another test'])
ktv = KerasTokenVectorizer(maxlen=2)
ktv.fit_transform(['this is a test', 'this is a another test'])
kcv = KerasCharacterVectorizer()
kcv.fit_transform(['something', 'else'])
'''
| gophronesis/smlib | smlib/keras_vectorizer.py | Python | apache-2.0 | 2,229 |
/*
* Copyright (C) 2017-2019 Dremio Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.dremio.exec.store;
import org.apache.hadoop.fs.BlockLocation;
import org.junit.Test;
import com.dremio.exec.ExecTest;
import com.google.common.collect.ImmutableRangeMap;
import com.google.common.collect.Range;
public class TestAffinityCalculator extends ExecTest {
static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(TestAffinityCalculator.class);
String port = "1234";
public BlockLocation[] buildBlockLocations(String[] hosts, long blockSize) {
String[] names = new String[hosts.length];
for (int i = 0; i < hosts.length; i++) {
hosts[i] = "host" + i;
names[i] = "host:" + port;
}
BlockLocation[] blockLocations = new BlockLocation[3];
blockLocations[0] = new BlockLocation(new String[]{names[0], names[1], names[2]}, new String[]{hosts[0], hosts[1], hosts[2]}, 0, blockSize);
blockLocations[1] = new BlockLocation(new String[]{names[0], names[2], names[3]}, new String[]{hosts[0], hosts[2], hosts[3]}, blockSize, blockSize);
blockLocations[2] = new BlockLocation(new String[]{names[0], names[1], names[3]}, new String[]{hosts[0], hosts[1], hosts[3]}, blockSize*2, blockSize);
return blockLocations;
}
@Test
public void testBuildRangeMap() {
BlockLocation[] blocks = buildBlockLocations(new String[4], 256*1024*1024);
long tA = System.nanoTime();
ImmutableRangeMap.Builder<Long, BlockLocation> blockMapBuilder = new ImmutableRangeMap.Builder<>();
for (BlockLocation block : blocks) {
long start = block.getOffset();
long end = start + block.getLength();
Range<Long> range = Range.closedOpen(start, end);
blockMapBuilder = blockMapBuilder.put(range, block);
}
ImmutableRangeMap<Long,BlockLocation> map = blockMapBuilder.build();
long tB = System.nanoTime();
System.out.println(String.format("Took %f ms to build range map", (tB - tA) / 1e6));
}
}
| dremio/dremio-oss | sabot/kernel/src/test/java/com/dremio/exec/store/TestAffinityCalculator.java | Java | apache-2.0 | 2,516 |
#
# Cookbook Name:: my-company
# Recipe:: default
#
# Copyright 2014, YOUR_COMPANY_NAME
#
# All rights reserved - Do Not Redistribute
#
| gd1e/chef-repo | cookbooks/my-company/recipes/default.rb | Ruby | apache-2.0 | 136 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_45) on Fri Nov 14 23:56:06 UTC 2014 -->
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
Uses of Class org.apache.hadoop.lib.service.hadoop.FileSystemAccessService (Apache Hadoop HttpFS 2.5.2 API)
</TITLE>
<META NAME="date" CONTENT="2014-11-14">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.apache.hadoop.lib.service.hadoop.FileSystemAccessService (Apache Hadoop HttpFS 2.5.2 API)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../org/apache/hadoop/lib/service/hadoop/FileSystemAccessService.html" title="class in org.apache.hadoop.lib.service.hadoop"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../../index.html?org/apache/hadoop/lib/service/hadoop//class-useFileSystemAccessService.html" target="_top"><B>FRAMES</B></A>
<A HREF="FileSystemAccessService.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<CENTER>
<H2>
<B>Uses of Class<br>org.apache.hadoop.lib.service.hadoop.FileSystemAccessService</B></H2>
</CENTER>
No usage of org.apache.hadoop.lib.service.hadoop.FileSystemAccessService
<P>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../org/apache/hadoop/lib/service/hadoop/FileSystemAccessService.html" title="class in org.apache.hadoop.lib.service.hadoop"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../../index.html?org/apache/hadoop/lib/service/hadoop//class-useFileSystemAccessService.html" target="_top"><B>FRAMES</B></A>
<A HREF="FileSystemAccessService.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
Copyright © 2014 <a href="http://www.apache.org">Apache Software Foundation</a>. All Rights Reserved.
</BODY>
</HTML>
| hsh075623201/hadoop | share/doc/hadoop/hadoop-hdfs-httpfs/apidocs/org/apache/hadoop/lib/service/hadoop/class-use/FileSystemAccessService.html | HTML | apache-2.0 | 6,466 |
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.27.1
// protoc v3.15.8
// source: third_party/tink/proto/jwt_hmac.proto
package jwt_hmac_go_proto
import (
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
sync "sync"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
type JwtHmacAlgorithm int32
const (
JwtHmacAlgorithm_HS_UNKNOWN JwtHmacAlgorithm = 0
JwtHmacAlgorithm_HS256 JwtHmacAlgorithm = 1
JwtHmacAlgorithm_HS384 JwtHmacAlgorithm = 2
JwtHmacAlgorithm_HS512 JwtHmacAlgorithm = 3
)
// Enum value maps for JwtHmacAlgorithm.
var (
JwtHmacAlgorithm_name = map[int32]string{
0: "HS_UNKNOWN",
1: "HS256",
2: "HS384",
3: "HS512",
}
JwtHmacAlgorithm_value = map[string]int32{
"HS_UNKNOWN": 0,
"HS256": 1,
"HS384": 2,
"HS512": 3,
}
)
func (x JwtHmacAlgorithm) Enum() *JwtHmacAlgorithm {
p := new(JwtHmacAlgorithm)
*p = x
return p
}
func (x JwtHmacAlgorithm) String() string {
return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x))
}
func (JwtHmacAlgorithm) Descriptor() protoreflect.EnumDescriptor {
return file_third_party_tink_proto_jwt_hmac_proto_enumTypes[0].Descriptor()
}
func (JwtHmacAlgorithm) Type() protoreflect.EnumType {
return &file_third_party_tink_proto_jwt_hmac_proto_enumTypes[0]
}
func (x JwtHmacAlgorithm) Number() protoreflect.EnumNumber {
return protoreflect.EnumNumber(x)
}
// Deprecated: Use JwtHmacAlgorithm.Descriptor instead.
func (JwtHmacAlgorithm) EnumDescriptor() ([]byte, []int) {
return file_third_party_tink_proto_jwt_hmac_proto_rawDescGZIP(), []int{0}
}
// key_type: type.googleapis.com/google.crypto.tink.JwtHmacKey
type JwtHmacKey struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Version uint32 `protobuf:"varint,1,opt,name=version,proto3" json:"version,omitempty"`
Algorithm JwtHmacAlgorithm `protobuf:"varint,2,opt,name=algorithm,proto3,enum=google.crypto.tink.JwtHmacAlgorithm" json:"algorithm,omitempty"`
KeyValue []byte `protobuf:"bytes,3,opt,name=key_value,json=keyValue,proto3" json:"key_value,omitempty"`
CustomKid *JwtHmacKey_CustomKid `protobuf:"bytes,4,opt,name=custom_kid,json=customKid,proto3" json:"custom_kid,omitempty"`
}
func (x *JwtHmacKey) Reset() {
*x = JwtHmacKey{}
if protoimpl.UnsafeEnabled {
mi := &file_third_party_tink_proto_jwt_hmac_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *JwtHmacKey) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*JwtHmacKey) ProtoMessage() {}
func (x *JwtHmacKey) ProtoReflect() protoreflect.Message {
mi := &file_third_party_tink_proto_jwt_hmac_proto_msgTypes[0]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use JwtHmacKey.ProtoReflect.Descriptor instead.
func (*JwtHmacKey) Descriptor() ([]byte, []int) {
return file_third_party_tink_proto_jwt_hmac_proto_rawDescGZIP(), []int{0}
}
func (x *JwtHmacKey) GetVersion() uint32 {
if x != nil {
return x.Version
}
return 0
}
func (x *JwtHmacKey) GetAlgorithm() JwtHmacAlgorithm {
if x != nil {
return x.Algorithm
}
return JwtHmacAlgorithm_HS_UNKNOWN
}
func (x *JwtHmacKey) GetKeyValue() []byte {
if x != nil {
return x.KeyValue
}
return nil
}
func (x *JwtHmacKey) GetCustomKid() *JwtHmacKey_CustomKid {
if x != nil {
return x.CustomKid
}
return nil
}
type JwtHmacKeyFormat struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Version uint32 `protobuf:"varint,1,opt,name=version,proto3" json:"version,omitempty"`
Algorithm JwtHmacAlgorithm `protobuf:"varint,2,opt,name=algorithm,proto3,enum=google.crypto.tink.JwtHmacAlgorithm" json:"algorithm,omitempty"`
KeySize uint32 `protobuf:"varint,3,opt,name=key_size,json=keySize,proto3" json:"key_size,omitempty"`
}
func (x *JwtHmacKeyFormat) Reset() {
*x = JwtHmacKeyFormat{}
if protoimpl.UnsafeEnabled {
mi := &file_third_party_tink_proto_jwt_hmac_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *JwtHmacKeyFormat) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*JwtHmacKeyFormat) ProtoMessage() {}
func (x *JwtHmacKeyFormat) ProtoReflect() protoreflect.Message {
mi := &file_third_party_tink_proto_jwt_hmac_proto_msgTypes[1]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use JwtHmacKeyFormat.ProtoReflect.Descriptor instead.
func (*JwtHmacKeyFormat) Descriptor() ([]byte, []int) {
return file_third_party_tink_proto_jwt_hmac_proto_rawDescGZIP(), []int{1}
}
func (x *JwtHmacKeyFormat) GetVersion() uint32 {
if x != nil {
return x.Version
}
return 0
}
func (x *JwtHmacKeyFormat) GetAlgorithm() JwtHmacAlgorithm {
if x != nil {
return x.Algorithm
}
return JwtHmacAlgorithm_HS_UNKNOWN
}
func (x *JwtHmacKeyFormat) GetKeySize() uint32 {
if x != nil {
return x.KeySize
}
return 0
}
// Optional, custom kid header value to be used with "RAW" keys.
// "TINK" keys with this value set will be rejected.
type JwtHmacKey_CustomKid struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Value string `protobuf:"bytes,1,opt,name=value,proto3" json:"value,omitempty"`
}
func (x *JwtHmacKey_CustomKid) Reset() {
*x = JwtHmacKey_CustomKid{}
if protoimpl.UnsafeEnabled {
mi := &file_third_party_tink_proto_jwt_hmac_proto_msgTypes[2]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *JwtHmacKey_CustomKid) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*JwtHmacKey_CustomKid) ProtoMessage() {}
func (x *JwtHmacKey_CustomKid) ProtoReflect() protoreflect.Message {
mi := &file_third_party_tink_proto_jwt_hmac_proto_msgTypes[2]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use JwtHmacKey_CustomKid.ProtoReflect.Descriptor instead.
func (*JwtHmacKey_CustomKid) Descriptor() ([]byte, []int) {
return file_third_party_tink_proto_jwt_hmac_proto_rawDescGZIP(), []int{0, 0}
}
func (x *JwtHmacKey_CustomKid) GetValue() string {
if x != nil {
return x.Value
}
return ""
}
var File_third_party_tink_proto_jwt_hmac_proto protoreflect.FileDescriptor
var file_third_party_tink_proto_jwt_hmac_proto_rawDesc = []byte{
0x0a, 0x25, 0x74, 0x68, 0x69, 0x72, 0x64, 0x5f, 0x70, 0x61, 0x72, 0x74, 0x79, 0x2f, 0x74, 0x69,
0x6e, 0x6b, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x6a, 0x77, 0x74, 0x5f, 0x68, 0x6d, 0x61,
0x63, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x12, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e,
0x63, 0x72, 0x79, 0x70, 0x74, 0x6f, 0x2e, 0x74, 0x69, 0x6e, 0x6b, 0x22, 0xf3, 0x01, 0x0a, 0x0a,
0x4a, 0x77, 0x74, 0x48, 0x6d, 0x61, 0x63, 0x4b, 0x65, 0x79, 0x12, 0x18, 0x0a, 0x07, 0x76, 0x65,
0x72, 0x73, 0x69, 0x6f, 0x6e, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x07, 0x76, 0x65, 0x72,
0x73, 0x69, 0x6f, 0x6e, 0x12, 0x42, 0x0a, 0x09, 0x61, 0x6c, 0x67, 0x6f, 0x72, 0x69, 0x74, 0x68,
0x6d, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x24, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65,
0x2e, 0x63, 0x72, 0x79, 0x70, 0x74, 0x6f, 0x2e, 0x74, 0x69, 0x6e, 0x6b, 0x2e, 0x4a, 0x77, 0x74,
0x48, 0x6d, 0x61, 0x63, 0x41, 0x6c, 0x67, 0x6f, 0x72, 0x69, 0x74, 0x68, 0x6d, 0x52, 0x09, 0x61,
0x6c, 0x67, 0x6f, 0x72, 0x69, 0x74, 0x68, 0x6d, 0x12, 0x1b, 0x0a, 0x09, 0x6b, 0x65, 0x79, 0x5f,
0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x08, 0x6b, 0x65, 0x79,
0x56, 0x61, 0x6c, 0x75, 0x65, 0x12, 0x47, 0x0a, 0x0a, 0x63, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x5f,
0x6b, 0x69, 0x64, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x28, 0x2e, 0x67, 0x6f, 0x6f, 0x67,
0x6c, 0x65, 0x2e, 0x63, 0x72, 0x79, 0x70, 0x74, 0x6f, 0x2e, 0x74, 0x69, 0x6e, 0x6b, 0x2e, 0x4a,
0x77, 0x74, 0x48, 0x6d, 0x61, 0x63, 0x4b, 0x65, 0x79, 0x2e, 0x43, 0x75, 0x73, 0x74, 0x6f, 0x6d,
0x4b, 0x69, 0x64, 0x52, 0x09, 0x63, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x4b, 0x69, 0x64, 0x1a, 0x21,
0x0a, 0x09, 0x43, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x4b, 0x69, 0x64, 0x12, 0x14, 0x0a, 0x05, 0x76,
0x61, 0x6c, 0x75, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75,
0x65, 0x22, 0x8b, 0x01, 0x0a, 0x10, 0x4a, 0x77, 0x74, 0x48, 0x6d, 0x61, 0x63, 0x4b, 0x65, 0x79,
0x46, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x12, 0x18, 0x0a, 0x07, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f,
0x6e, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x07, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e,
0x12, 0x42, 0x0a, 0x09, 0x61, 0x6c, 0x67, 0x6f, 0x72, 0x69, 0x74, 0x68, 0x6d, 0x18, 0x02, 0x20,
0x01, 0x28, 0x0e, 0x32, 0x24, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x72, 0x79,
0x70, 0x74, 0x6f, 0x2e, 0x74, 0x69, 0x6e, 0x6b, 0x2e, 0x4a, 0x77, 0x74, 0x48, 0x6d, 0x61, 0x63,
0x41, 0x6c, 0x67, 0x6f, 0x72, 0x69, 0x74, 0x68, 0x6d, 0x52, 0x09, 0x61, 0x6c, 0x67, 0x6f, 0x72,
0x69, 0x74, 0x68, 0x6d, 0x12, 0x19, 0x0a, 0x08, 0x6b, 0x65, 0x79, 0x5f, 0x73, 0x69, 0x7a, 0x65,
0x18, 0x03, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x07, 0x6b, 0x65, 0x79, 0x53, 0x69, 0x7a, 0x65, 0x2a,
0x43, 0x0a, 0x10, 0x4a, 0x77, 0x74, 0x48, 0x6d, 0x61, 0x63, 0x41, 0x6c, 0x67, 0x6f, 0x72, 0x69,
0x74, 0x68, 0x6d, 0x12, 0x0e, 0x0a, 0x0a, 0x48, 0x53, 0x5f, 0x55, 0x4e, 0x4b, 0x4e, 0x4f, 0x57,
0x4e, 0x10, 0x00, 0x12, 0x09, 0x0a, 0x05, 0x48, 0x53, 0x32, 0x35, 0x36, 0x10, 0x01, 0x12, 0x09,
0x0a, 0x05, 0x48, 0x53, 0x33, 0x38, 0x34, 0x10, 0x02, 0x12, 0x09, 0x0a, 0x05, 0x48, 0x53, 0x35,
0x31, 0x32, 0x10, 0x03, 0x42, 0x50, 0x0a, 0x1c, 0x63, 0x6f, 0x6d, 0x2e, 0x67, 0x6f, 0x6f, 0x67,
0x6c, 0x65, 0x2e, 0x63, 0x72, 0x79, 0x70, 0x74, 0x6f, 0x2e, 0x74, 0x69, 0x6e, 0x6b, 0x2e, 0x70,
0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x2e, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63,
0x6f, 0x6d, 0x2f, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x74, 0x69, 0x6e, 0x6b, 0x2f, 0x70,
0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x6a, 0x77, 0x74, 0x5f, 0x68, 0x6d, 0x61, 0x63, 0x5f, 0x67, 0x6f,
0x5f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
}
var (
file_third_party_tink_proto_jwt_hmac_proto_rawDescOnce sync.Once
file_third_party_tink_proto_jwt_hmac_proto_rawDescData = file_third_party_tink_proto_jwt_hmac_proto_rawDesc
)
func file_third_party_tink_proto_jwt_hmac_proto_rawDescGZIP() []byte {
file_third_party_tink_proto_jwt_hmac_proto_rawDescOnce.Do(func() {
file_third_party_tink_proto_jwt_hmac_proto_rawDescData = protoimpl.X.CompressGZIP(file_third_party_tink_proto_jwt_hmac_proto_rawDescData)
})
return file_third_party_tink_proto_jwt_hmac_proto_rawDescData
}
var file_third_party_tink_proto_jwt_hmac_proto_enumTypes = make([]protoimpl.EnumInfo, 1)
var file_third_party_tink_proto_jwt_hmac_proto_msgTypes = make([]protoimpl.MessageInfo, 3)
var file_third_party_tink_proto_jwt_hmac_proto_goTypes = []interface{}{
(JwtHmacAlgorithm)(0), // 0: google.crypto.tink.JwtHmacAlgorithm
(*JwtHmacKey)(nil), // 1: google.crypto.tink.JwtHmacKey
(*JwtHmacKeyFormat)(nil), // 2: google.crypto.tink.JwtHmacKeyFormat
(*JwtHmacKey_CustomKid)(nil), // 3: google.crypto.tink.JwtHmacKey.CustomKid
}
var file_third_party_tink_proto_jwt_hmac_proto_depIdxs = []int32{
0, // 0: google.crypto.tink.JwtHmacKey.algorithm:type_name -> google.crypto.tink.JwtHmacAlgorithm
3, // 1: google.crypto.tink.JwtHmacKey.custom_kid:type_name -> google.crypto.tink.JwtHmacKey.CustomKid
0, // 2: google.crypto.tink.JwtHmacKeyFormat.algorithm:type_name -> google.crypto.tink.JwtHmacAlgorithm
3, // [3:3] is the sub-list for method output_type
3, // [3:3] is the sub-list for method input_type
3, // [3:3] is the sub-list for extension type_name
3, // [3:3] is the sub-list for extension extendee
0, // [0:3] is the sub-list for field type_name
}
func init() { file_third_party_tink_proto_jwt_hmac_proto_init() }
func file_third_party_tink_proto_jwt_hmac_proto_init() {
if File_third_party_tink_proto_jwt_hmac_proto != nil {
return
}
if !protoimpl.UnsafeEnabled {
file_third_party_tink_proto_jwt_hmac_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*JwtHmacKey); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_third_party_tink_proto_jwt_hmac_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*JwtHmacKeyFormat); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_third_party_tink_proto_jwt_hmac_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*JwtHmacKey_CustomKid); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: file_third_party_tink_proto_jwt_hmac_proto_rawDesc,
NumEnums: 1,
NumMessages: 3,
NumExtensions: 0,
NumServices: 0,
},
GoTypes: file_third_party_tink_proto_jwt_hmac_proto_goTypes,
DependencyIndexes: file_third_party_tink_proto_jwt_hmac_proto_depIdxs,
EnumInfos: file_third_party_tink_proto_jwt_hmac_proto_enumTypes,
MessageInfos: file_third_party_tink_proto_jwt_hmac_proto_msgTypes,
}.Build()
File_third_party_tink_proto_jwt_hmac_proto = out.File
file_third_party_tink_proto_jwt_hmac_proto_rawDesc = nil
file_third_party_tink_proto_jwt_hmac_proto_goTypes = nil
file_third_party_tink_proto_jwt_hmac_proto_depIdxs = nil
}
| google/tink | go/proto/jwt_hmac_go_proto/jwt_hmac.pb.go | GO | apache-2.0 | 15,201 |
using org.ohdsi.cdm.framework.common.Builder;
using org.ohdsi.cdm.framework.common.Omop;
using System;
using System.Collections.Generic;
using System.Data;
namespace org.ohdsi.cdm.framework.common.DataReaders.v6
{
public class DeviceExposureDataReader : IDataReader
{
private readonly IEnumerator<DeviceExposure> _enumerator;
private readonly KeyMasterOffsetManager _offset;
// A custom DataReader is implemented to prevent the need for the HashSet to be transformed to a DataTable for loading by SqlBulkCopy
public DeviceExposureDataReader(List<DeviceExposure> batch, KeyMasterOffsetManager o)
{
_enumerator = batch?.GetEnumerator();
_offset = o;
}
public bool Read()
{
return _enumerator.MoveNext();
}
public int FieldCount
{
get { return 15; }
}
// is this called only because the datatype specific methods are not implemented?
// probably performance to be gained by not passing object back?
public object GetValue(int i)
{
switch (i)
{
case 0:
return _offset.GetId(_enumerator.Current.PersonId, _enumerator.Current.Id);
case 1:
return _enumerator.Current.PersonId;
case 2:
return _enumerator.Current.ConceptId;
case 3:
return _enumerator.Current.StartDate;
case 4:
return _enumerator.Current.StartDate.TimeOfDay;
case 5:
return _enumerator.Current.EndDate;
case 6:
return _enumerator.Current.EndDate?.TimeOfDay;
case 7:
return _enumerator.Current.TypeConceptId;
case 8:
return _enumerator.Current.UniqueDeviceId;
case 9:
return _enumerator.Current.Quantity;
case 10:
return _enumerator.Current.ProviderId == 0 ? null : _enumerator.Current.ProviderId;
case 11:
if (_enumerator.Current.VisitOccurrenceId.HasValue)
{
if (_offset.GetKeyOffset(_enumerator.Current.PersonId).VisitOccurrenceIdChanged)
return _offset.GetId(_enumerator.Current.PersonId,
_enumerator.Current.VisitOccurrenceId.Value);
return _enumerator.Current.VisitOccurrenceId.Value;
}
return null;
case 12:
if (_enumerator.Current.VisitDetailId.HasValue)
{
if (_offset.GetKeyOffset(_enumerator.Current.PersonId).VisitDetailIdChanged)
return _offset.GetId(_enumerator.Current.PersonId,
_enumerator.Current.VisitDetailId.Value);
return _enumerator.Current.VisitDetailId;
}
return null;
case 13:
return _enumerator.Current.SourceValue;
case 14:
return _enumerator.Current.SourceConceptId;
default:
throw new NotImplementedException();
}
}
public string GetName(int i)
{
switch (i)
{
case 0: return "device_exposure_id";
case 1: return "person_id";
case 2: return "device_concept_id";
case 3: return "device_exposure_start_date";
case 4: return "device_exposure_start_datetime";
case 5: return "device_exposure_end_date";
case 6: return "device_exposure_end_datetime";
case 7: return "device_type_concept_id";
case 8: return "unique_device_id";
case 9: return "quantity";
case 10: return "provider_id";
case 11: return "visit_occurrence_id";
case 12: return "visit_detail_id";
case 13: return "device_source_value";
case 14: return "device_source_concept_id";
default:
throw new NotImplementedException();
}
}
#region implementationn not required for SqlBulkCopy
public bool NextResult()
{
throw new NotImplementedException();
}
public void Close()
{
throw new NotImplementedException();
}
public bool IsClosed
{
get { throw new NotImplementedException(); }
}
public int Depth
{
get { throw new NotImplementedException(); }
}
public DataTable GetSchemaTable()
{
throw new NotImplementedException();
}
public int RecordsAffected
{
get { throw new NotImplementedException(); }
}
public void Dispose()
{
throw new NotImplementedException();
}
public bool GetBoolean(int i)
{
return (bool)GetValue(i);
}
public byte GetByte(int i)
{
return (byte)GetValue(i);
}
public long GetBytes(int i, long fieldOffset, byte[] buffer, int bufferoffset, int length)
{
throw new NotImplementedException();
}
public char GetChar(int i)
{
return (char)GetValue(i);
}
public long GetChars(int i, long fieldoffset, char[] buffer, int bufferoffset, int length)
{
throw new NotImplementedException();
}
public IDataReader GetData(int i)
{
throw new NotImplementedException();
}
public string GetDataTypeName(int i)
{
throw new NotImplementedException();
}
public DateTime GetDateTime(int i)
{
return (DateTime)GetValue(i);
}
public decimal GetDecimal(int i)
{
return (decimal)GetValue(i);
}
public double GetDouble(int i)
{
return Convert.ToDouble(GetValue(i));
}
public Type GetFieldType(int i)
{
switch (i)
{
case 0: return typeof(long);
case 1: return typeof(long);
case 2: return typeof(int);
case 3: return typeof(DateTime?);
case 4: return typeof(TimeSpan);
case 5: return typeof(DateTime?);
case 6: return typeof(TimeSpan?);
case 7: return typeof(int);
case 8: return typeof(string);
case 9: return typeof(int?);
case 10: return typeof(long?);
case 11: return typeof(long?);
case 12: return typeof(long?);
case 13: return typeof(string);
case 14: return typeof(int);
default:
throw new NotImplementedException();
}
}
public float GetFloat(int i)
{
return (float)GetValue(i);
}
public Guid GetGuid(int i)
{
return (Guid)GetValue(i);
}
public short GetInt16(int i)
{
return (short)GetValue(i);
}
public int GetInt32(int i)
{
return (int)GetValue(i);
}
public long GetInt64(int i)
{
return Convert.ToInt64(GetValue(i));
}
public int GetOrdinal(string name)
{
throw new NotImplementedException();
}
public string GetString(int i)
{
return (string)GetValue(i);
}
public int GetValues(object[] values)
{
var cnt = 0;
for (var i = 0; i < FieldCount; i++)
{
values[i] = GetValue(i);
cnt++;
}
return cnt;
}
public bool IsDBNull(int i)
{
return GetValue(i) == null;
}
public object this[string name]
{
get { throw new NotImplementedException(); }
}
public object this[int i]
{
get { throw new NotImplementedException(); }
}
#endregion
}
}
| OHDSI/ETL-CDMBuilder | source/org.ohdsi.cdm.framework.common/DataReaders/v6/DeviceExposureDataReader.cs | C# | apache-2.0 | 8,642 |
/* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.flowable.rest.service.api.runtime;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.engine.test.Deployment;
import org.flowable.rest.service.BaseSpringRestTestCase;
import org.flowable.rest.service.api.RestUrls;
import org.junit.Test;
/**
* @author Frederik Heremans
*/
public class ProcessInstanceDiagramResourceTest extends BaseSpringRestTestCase {
@Test
@Deployment
public void testGetProcessDiagram() throws Exception {
ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("simpleProcess");
CloseableHttpResponse response = executeRequest(new HttpGet(SERVER_URL_PREFIX + RestUrls.createRelativeResourceUrl(RestUrls.URL_PROCESS_INSTANCE_DIAGRAM, processInstance.getId())),
HttpStatus.SC_OK);
assertNotNull(response.getEntity().getContent());
assertEquals("image/png", response.getEntity().getContentType().getValue());
closeResponse(response);
}
@Test
@Deployment
public void testGetProcessDiagramWithoutDiagram() throws Exception {
ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess");
closeResponse(executeRequest(new HttpGet(SERVER_URL_PREFIX + RestUrls.createRelativeResourceUrl(RestUrls.URL_PROCESS_INSTANCE_DIAGRAM, processInstance.getId())), HttpStatus.SC_BAD_REQUEST));
}
/**
* Test getting an unexisting process instance.
*/
@Test
public void testGetUnexistingProcessInstance() {
closeResponse(executeRequest(new HttpGet(SERVER_URL_PREFIX + RestUrls.createRelativeResourceUrl(RestUrls.URL_PROCESS_INSTANCE_DIAGRAM, "unexistingpi")), HttpStatus.SC_NOT_FOUND));
}
}
| yvoswillens/flowable-engine | modules/flowable-rest/src/test/java/org/flowable/rest/service/api/runtime/ProcessInstanceDiagramResourceTest.java | Java | apache-2.0 | 2,517 |
# Changelog
[npm history][1]
[1]: https://www.npmjs.com/package/@justinbeckwith/sloth?activeTab=versions
## [6.6.0](https://github.com/googleapis/sloth/compare/v6.5.1...v6.6.0) (2022-02-16)
### Features
* update in scope services ([#1038](https://github.com/googleapis/sloth/issues/1038)) ([f24f064](https://github.com/googleapis/sloth/commit/f24f06467d557592b6984d438ea12e2e25c223ed))
### [6.5.1](https://www.github.com/googleapis/sloth/compare/v6.5.0...v6.5.1) (2022-01-05)
### Bug Fixes
* add anthos-edge-usecases ([#1023](https://www.github.com/googleapis/sloth/issues/1023)) ([a68a96d](https://www.github.com/googleapis/sloth/commit/a68a96d7936532b1d8ddcab5dd3a80d4dcbb4277))
## [6.5.0](https://www.github.com/googleapis/sloth/compare/v6.4.4...v6.5.0) (2021-12-09)
### Features
* add elixir to core repos ([#1020](https://www.github.com/googleapis/sloth/issues/1020)) ([e9407ac](https://www.github.com/googleapis/sloth/commit/e9407ac2337633bb492cfab8a8fd10955209d99b))
### [6.4.4](https://www.github.com/googleapis/sloth/compare/v6.4.3...v6.4.4) (2021-11-09)
### Bug Fixes
* add anthos/gke dpe repos to the repos.json ([#1017](https://www.github.com/googleapis/sloth/issues/1017)) ([efc359c](https://www.github.com/googleapis/sloth/commit/efc359c1b090a634b48dbb91315818bf2d56c0d1))
* use replace instead of replaceAll ([#1014](https://www.github.com/googleapis/sloth/issues/1014)) ([c9cd971](https://www.github.com/googleapis/sloth/commit/c9cd971e8538dd832112b4909ff6a38fd46c004b))
### [6.4.3](https://www.github.com/googleapis/sloth/compare/v6.4.2...v6.4.3) (2021-09-29)
### Bug Fixes
* **deps:** update dependency truncate to v3 ([#1003](https://www.github.com/googleapis/sloth/issues/1003)) ([24eaed2](https://www.github.com/googleapis/sloth/commit/24eaed26eedf969adda12ab0ae4d1496eab59fdb))
### [6.4.2](https://www.github.com/googleapis/sloth/compare/v6.4.1...v6.4.2) (2021-09-08)
### Bug Fixes
* ACTools owns gapic_rules ([#998](https://www.github.com/googleapis/sloth/issues/998)) ([f576d88](https://www.github.com/googleapis/sloth/commit/f576d88cfb1970548ac550a1b675cc1aa2eb366c))
### [6.4.1](https://www.github.com/googleapis/sloth/compare/v6.4.0...v6.4.1) (2021-08-26)
### Bug Fixes
* **deps:** update dependency @google-cloud/service-management to ^0.3.0 ([#992](https://www.github.com/googleapis/sloth/issues/992)) ([efb27e6](https://www.github.com/googleapis/sloth/commit/efb27e680cfb1410c767e2c81a31d8576f944812))
## [6.4.0](https://www.github.com/googleapis/sloth/compare/v6.3.1...v6.4.0) (2021-08-16)
### Features
* assign google-cloud-python-happybase to cloud-native-databases ([#986](https://www.github.com/googleapis/sloth/issues/986)) ([70bfcb3](https://www.github.com/googleapis/sloth/commit/70bfcb3406df14307d3c6fed678c17b48064a3e4))
### Bug Fixes
* use Cloud Run for bigquery exports ([#989](https://www.github.com/googleapis/sloth/issues/989)) ([3d6fd5c](https://www.github.com/googleapis/sloth/commit/3d6fd5ca9b6a854edb58544697bc5164dae0222f))
### [6.3.1](https://www.github.com/googleapis/sloth/compare/v6.3.0...v6.3.1) (2021-08-09)
### Bug Fixes
* **build:** migrate to using main branch ([#983](https://www.github.com/googleapis/sloth/issues/983)) ([849120d](https://www.github.com/googleapis/sloth/commit/849120d752f26710bfb1dd0e46999f0c05662265))
## [6.3.0](https://www.github.com/googleapis/sloth/compare/v6.2.1...v6.3.0) (2021-07-30)
### Features
* add env-tests-logging repo under operations team ([#976](https://www.github.com/googleapis/sloth/issues/976)) ([0b0bed1](https://www.github.com/googleapis/sloth/commit/0b0bed16c1dd7a59b1e6f0cf44b85232af059b22))
* add protoc-docs-plugin repo under actools team ([#978](https://www.github.com/googleapis/sloth/issues/978)) ([e9e5411](https://www.github.com/googleapis/sloth/commit/e9e5411adac2e2c68474ad348ad10fa64728e016))
### [6.2.1](https://www.github.com/googleapis/sloth/compare/v6.2.0...v6.2.1) (2021-07-09)
### Bug Fixes
* send experimental headers to github to fix experimental filtering ([#971](https://www.github.com/googleapis/sloth/issues/971)) ([63c5ffa](https://www.github.com/googleapis/sloth/commit/63c5ffafd3dbd8ea5229c980b66e56ed10b129ca))
## [6.2.0](https://www.github.com/googleapis/sloth/compare/v6.1.0...v6.2.0) (2021-07-08)
### Features
* add google-cloud-datastore repo under cloud-native-databases team ([#967](https://www.github.com/googleapis/sloth/issues/967)) ([3170dca](https://www.github.com/googleapis/sloth/commit/3170dca8f55fc2cab2dd43122373fbfa5bfb73ee))
## [6.1.0](https://www.github.com/googleapis/sloth/compare/v6.0.3...v6.1.0) (2021-06-25)
### Features
* add sphinx-docfx-yaml repo under CXE team ([#963](https://www.github.com/googleapis/sloth/issues/963)) ([6db5d1a](https://www.github.com/googleapis/sloth/commit/6db5d1ac367cab8d460fe7c7581fb82a4e868dcf))
### [6.0.3](https://www.github.com/googleapis/sloth/compare/v6.0.2...v6.0.3) (2021-06-15)
### Bug Fixes
* remove onramp specific assignment for samples ([#961](https://www.github.com/googleapis/sloth/issues/961)) ([f5ed3b9](https://www.github.com/googleapis/sloth/commit/f5ed3b985287ab813c33643b7249971d0449b2c9))
* samples to yoshi ([#959](https://www.github.com/googleapis/sloth/issues/959)) ([a643371](https://www.github.com/googleapis/sloth/commit/a6433714155ea30f3257704b73f9b9f3de63795d))
### [6.0.2](https://www.github.com/googleapis/sloth/compare/v6.0.1...v6.0.2) (2021-06-08)
### Bug Fixes
* use the service management module ([#936](https://www.github.com/googleapis/sloth/issues/936)) ([b5fd186](https://www.github.com/googleapis/sloth/commit/b5fd18694875865e0c64065162194063e430babd))
### [6.0.1](https://www.github.com/googleapis/sloth/compare/v6.0.0...v6.0.1) (2021-05-27)
### Bug Fixes
* correct spelling of baremetalsolution ([#938](https://www.github.com/googleapis/sloth/issues/938)) ([f0a2838](https://www.github.com/googleapis/sloth/commit/f0a28385c0aebd7a5464714479133315fcffa7b0))
## [6.0.0](https://www.github.com/googleapis/sloth/compare/v5.42.0...v6.0.0) (2021-05-25)
### ⚠ BREAKING CHANGES
* remove policy tools (#934)
### Bug Fixes
* **deps:** update dependency googleapis to v74 ([#931](https://www.github.com/googleapis/sloth/issues/931)) ([f5ce271](https://www.github.com/googleapis/sloth/commit/f5ce271414bd6da68f68d357149363350e206f68))
* remove policy tools ([#934](https://www.github.com/googleapis/sloth/issues/934)) ([d935f09](https://www.github.com/googleapis/sloth/commit/d935f097ee6aca3485a2092c193d41dcdd8286ac))
## [5.42.0](https://www.github.com/googleapis/sloth/compare/v5.41.1...v5.42.0) (2021-05-22)
### Features
* adds inScope classification and other details ([#888](https://www.github.com/googleapis/sloth/issues/888)) ([6c34dce](https://www.github.com/googleapis/sloth/commit/6c34dce0b80830ec66c615ca73f4f66d25e5efb1))
### [5.41.1](https://www.github.com/googleapis/sloth/compare/v5.41.0...v5.41.1) (2021-05-05)
### Bug Fixes
* **deps:** update dependency googleapis to v73 ([#920](https://www.github.com/googleapis/sloth/issues/920)) ([f425e12](https://www.github.com/googleapis/sloth/commit/f425e12a55196475639be7231621945a891be962))
## [5.41.0](https://www.github.com/googleapis/sloth/compare/v5.40.0...v5.41.0) (2021-04-23)
### Features
* split workflows out to a new team ([#915](https://www.github.com/googleapis/sloth/issues/915)) ([f0038a1](https://www.github.com/googleapis/sloth/commit/f0038a1548f64385b708f8f204e4d363a056c8c8))
* update repos.json and teams.json to include anthos-samples ([#913](https://www.github.com/googleapis/sloth/issues/913)) ([bfd801c](https://www.github.com/googleapis/sloth/commit/bfd801c3899ef91080bf6bf9d3eb06ae563705b1))
### Bug Fixes
* **deps:** update dependency googleapis to v72 ([#917](https://www.github.com/googleapis/sloth/issues/917)) ([49aa49e](https://www.github.com/googleapis/sloth/commit/49aa49e136210240ed4a4a6618f60cc27652a40e))
## [5.40.0](https://www.github.com/googleapis/sloth/compare/v5.39.1...v5.40.0) (2021-04-19)
### Features
* add GoogleCloudPlatform/workflows-samples to tracked repositories ([#905](https://www.github.com/googleapis/sloth/issues/905)) ([f3aea79](https://www.github.com/googleapis/sloth/commit/f3aea79e4e33c2b3395693d854b83e102aadb611))
### [5.39.1](https://www.github.com/googleapis/sloth/compare/v5.39.0...v5.39.1) (2021-04-08)
### Bug Fixes
* **deps:** update dependency googleapis to v70 ([#902](https://www.github.com/googleapis/sloth/issues/902)) ([486f2e1](https://www.github.com/googleapis/sloth/commit/486f2e157cbf82fd44f33665e8a8c17b6ddcf40f))
* **deps:** update dependency googleapis to v71 ([#904](https://www.github.com/googleapis/sloth/issues/904)) ([35a7b6e](https://www.github.com/googleapis/sloth/commit/35a7b6eb26ae8d482d06c9ebf10cbda49f0bbf98))
## [5.39.0](https://www.github.com/googleapis/sloth/compare/v5.38.0...v5.39.0) (2021-03-31)
### Features
* adds discrete team for Cloud IoT ([#900](https://www.github.com/googleapis/sloth/issues/900)) ([808df93](https://www.github.com/googleapis/sloth/commit/808df932e90376d338a07fd795998f63096af599))
## [5.38.0](https://www.github.com/googleapis/sloth/compare/v5.37.0...v5.38.0) (2021-03-25)
### Features
* adds microservices-demo repo to DevPlat team ([#898](https://www.github.com/googleapis/sloth/issues/898)) ([b27c68e](https://www.github.com/googleapis/sloth/commit/b27c68e3578a00e9335d1a0eb1ddf43d907a0863))
## [5.37.0](https://www.github.com/googleapis/sloth/compare/v5.36.5...v5.37.0) (2021-03-22)
### Features
* add policy check for SECURITY.md ([#892](https://www.github.com/googleapis/sloth/issues/892)) ([e8c75df](https://www.github.com/googleapis/sloth/commit/e8c75dfbbb75d0702718d2ddc7ae218567927828))
* add policy tracking ([#876](https://www.github.com/googleapis/sloth/issues/876)) ([7fa16a8](https://www.github.com/googleapis/sloth/commit/7fa16a8964b3df5f57f1f7e5d7420f5792ea5aaf))
* add pubsublite python and java repos ([#849](https://www.github.com/googleapis/sloth/issues/849)) ([b38ee61](https://www.github.com/googleapis/sloth/commit/b38ee61c51a24913a7d24cfaf2846a94cfe92039))
* add storage and database teams ([#854](https://www.github.com/googleapis/sloth/issues/854)) ([4542728](https://www.github.com/googleapis/sloth/commit/45427289cd0587065e4b2b3570c1d1e4a10e9269))
* adds export of Cloud API classification ([#884](https://www.github.com/googleapis/sloth/issues/884)) ([4ddf13d](https://www.github.com/googleapis/sloth/commit/4ddf13de4efe1ef0556a275adee6ca02e4672d29))
* adds usage/ToS to Cloud APIs export ([#887](https://www.github.com/googleapis/sloth/issues/887)) ([feb4fc0](https://www.github.com/googleapis/sloth/commit/feb4fc0de11424719b49c1b5f0cb2529bed45c47))
* new c++ repository ([#883](https://www.github.com/googleapis/sloth/issues/883)) ([430e05c](https://www.github.com/googleapis/sloth/commit/430e05ce551f12abe2838aac692408fb71503e0d))
* **node:** add nodejs-video-transcoder ([#838](https://www.github.com/googleapis/sloth/issues/838)) ([f154fd7](https://www.github.com/googleapis/sloth/commit/f154fd77ff671b7b58224e10300af0d6a6fcf101))
* **nodejs:** add API Gateway ([#893](https://www.github.com/googleapis/sloth/issues/893)) ([eb8c992](https://www.github.com/googleapis/sloth/commit/eb8c992e67b9fd0cf283d110577dc12d1f3c19fa))
* **python:** add data-qna repo ([#853](https://www.github.com/googleapis/sloth/issues/853)) ([28f96ce](https://www.github.com/googleapis/sloth/commit/28f96ce24de0518b3acb25c175678142abe019dc))
* **python:** add python-channel and python-retail ([#866](https://www.github.com/googleapis/sloth/issues/866)) ([d2e24e3](https://www.github.com/googleapis/sloth/commit/d2e24e3a230223fdb193768082788538eb87e70e))
* **python:** add python-compute and python-binary-authorzation ([#865](https://www.github.com/googleapis/sloth/issues/865)) ([1d5f753](https://www.github.com/googleapis/sloth/commit/1d5f753e74d50077a59be3dab6869b21c655286f))
* **python:** add python-network-connectivity and python-domains ([#868](https://www.github.com/googleapis/sloth/issues/868)) ([e0c86e8](https://www.github.com/googleapis/sloth/commit/e0c86e83c73f2729c5e96ff3c3a760bad12210f4))
* scan entire googleapis org ([#873](https://www.github.com/googleapis/sloth/issues/873)) ([03eca08](https://www.github.com/googleapis/sloth/commit/03eca081b16a4ed2d47a33aaca4fe8d5d9662904))
* update SoDa repos ([#877](https://www.github.com/googleapis/sloth/issues/877)) ([61bedc4](https://www.github.com/googleapis/sloth/commit/61bedc421b1632f9f7119c16670bd4d7c4c35cd5))
### Bug Fixes
* add nodejs-data-qna to repos ([#859](https://www.github.com/googleapis/sloth/issues/859)) ([f1ecd56](https://www.github.com/googleapis/sloth/commit/f1ecd56996d5b3b548831dabcb5a9ecb441936e5))
* assign ownership of repos to actools ([#889](https://www.github.com/googleapis/sloth/issues/889)) ([770af7e](https://www.github.com/googleapis/sloth/commit/770af7e5d8883e38a4e93ce8cb0730db3efc43eb))
* **deps:** update dependency gaxios to v4 ([#826](https://www.github.com/googleapis/sloth/issues/826)) ([c16fc0e](https://www.github.com/googleapis/sloth/commit/c16fc0ec7f2144099c126ab39ebfa9bce76bf746))
* **deps:** update dependency googleapis to v62 ([#835](https://www.github.com/googleapis/sloth/issues/835)) ([930e94e](https://www.github.com/googleapis/sloth/commit/930e94ec229bb3fe98e40264b8edea43833184fe))
* **deps:** update dependency googleapis to v63 ([#842](https://www.github.com/googleapis/sloth/issues/842)) ([c5f19cd](https://www.github.com/googleapis/sloth/commit/c5f19cdccf5d342d7787b937f0d4c435fc7445df))
* **deps:** update dependency googleapis to v64 ([#847](https://www.github.com/googleapis/sloth/issues/847)) ([5b1aaec](https://www.github.com/googleapis/sloth/commit/5b1aaec81e1074f523d77c3d9b82097aa853910b))
* **deps:** update dependency googleapis to v65 ([#851](https://www.github.com/googleapis/sloth/issues/851)) ([f95e58f](https://www.github.com/googleapis/sloth/commit/f95e58f0d8dff84ce7f8174b31459da4deb761d2))
* **deps:** update dependency googleapis to v66 ([#855](https://www.github.com/googleapis/sloth/issues/855)) ([ec7703f](https://www.github.com/googleapis/sloth/commit/ec7703f339fbb5719075bfcbc1cfbe718959aee1))
* **deps:** update dependency googleapis to v67 ([#862](https://www.github.com/googleapis/sloth/issues/862)) ([f1e7a5d](https://www.github.com/googleapis/sloth/commit/f1e7a5d15389e68c22b000c63c58ad4e7e6aa334))
* **deps:** update dependency googleapis to v68 ([#894](https://www.github.com/googleapis/sloth/issues/894)) ([14f5739](https://www.github.com/googleapis/sloth/commit/14f5739b7683e111dd5bfb8c0b7a4f4bf8c5096c))
* **deps:** update dependency meow to v8 ([#836](https://www.github.com/googleapis/sloth/issues/836)) ([0e65442](https://www.github.com/googleapis/sloth/commit/0e6544259fa3295cf2fb0d0761c522f3767e52f7))
* **deps:** update dependency meow to v9 ([#861](https://www.github.com/googleapis/sloth/issues/861)) ([6d186ff](https://www.github.com/googleapis/sloth/commit/6d186ff9e1a729c80bc181a0e3ae51c77be266da))
* do not use preview CoC API ([#882](https://www.github.com/googleapis/sloth/issues/882)) ([40dc4f9](https://www.github.com/googleapis/sloth/commit/40dc4f9b113cd6a2fd20d4bbb80116f370fa3ff0))
* ignore experimental repos ([#890](https://www.github.com/googleapis/sloth/issues/890)) ([d5e2026](https://www.github.com/googleapis/sloth/commit/d5e20265a798cd6e647c94b096f5f9467a688457))
* include cpp functions framework for cxx team ([#885](https://www.github.com/googleapis/sloth/issues/885)) ([8d0e0dd](https://www.github.com/googleapis/sloth/commit/8d0e0dd841eb056983f2ba45ec10a8cdd74fca7e))
* renovate.json can be in the .github directory ([#879](https://www.github.com/googleapis/sloth/issues/879)) ([16a2e91](https://www.github.com/googleapis/sloth/commit/16a2e91da81598f2ed1f3db7b4bd782936d3321b))
* separate databases team into infra and cloud native ([#881](https://www.github.com/googleapis/sloth/issues/881)) ([3fa0d0f](https://www.github.com/googleapis/sloth/commit/3fa0d0f8f24ae656b98da639702affa38bdeef45))
* use GitHub API to fetch code of conduct ([#880](https://www.github.com/googleapis/sloth/issues/880)) ([16cdc60](https://www.github.com/googleapis/sloth/commit/16cdc6078955838bf6b1e3257b179019e00c2a82))
### [5.36.5](https://www.github.com/googleapis/sloth/compare/v5.36.4...v5.36.5) (2020-10-16)
### Bug Fixes
* remove trailing comma ([#820](https://www.github.com/googleapis/sloth/issues/820)) ([8432ccd](https://www.github.com/googleapis/sloth/commit/8432ccdc4d5330da15632099cadc45b013fe11e0))
### [5.36.4](https://www.github.com/googleapis/sloth/compare/v5.36.3...v5.36.4) (2020-10-15)
### Bug Fixes
* update teams.json ([#818](https://www.github.com/googleapis/sloth/issues/818)) ([a0c69ac](https://www.github.com/googleapis/sloth/commit/a0c69ac3e899d681b7d3fce17c3e3687109c9340))
### [5.36.3](https://www.github.com/googleapis/sloth/compare/v5.36.2...v5.36.3) (2020-10-13)
### Bug Fixes
* CAKE team sloth reorg ([#810](https://www.github.com/googleapis/sloth/issues/810)) ([5d2e381](https://www.github.com/googleapis/sloth/commit/5d2e381dd5f412468d36fd75a0e8b57ad9cdae76))
### [5.36.2](https://www.github.com/googleapis/sloth/compare/v5.36.1...v5.36.2) (2020-10-07)
### ⚠ BREAKING CHANGES
* update build configuration enable engines strict (#797)
### Bug Fixes
* **build:** switch to trampoline 2 (release as patch rather than major) ([#813](https://www.github.com/googleapis/sloth/issues/813)) ([ee3a1bd](https://www.github.com/googleapis/sloth/commit/ee3a1bd4f0174d9b5fc9b187d1e185abdc5c71e2))
### Build System
* update build configuration enable engines strict ([#797](https://www.github.com/googleapis/sloth/issues/797)) ([6e8458a](https://www.github.com/googleapis/sloth/commit/6e8458a1299a2f5b7deec810b586138528cb0786))
### [5.36.1](https://www.github.com/googleapis/sloth/compare/v5.36.0...v5.36.1) (2020-10-03)
### Bug Fixes
* **deps:** update dependency update-notifier to v5 ([#806](https://www.github.com/googleapis/sloth/issues/806)) ([300a472](https://www.github.com/googleapis/sloth/commit/300a472f326942de85719fd4fd067c0dac61551d))
## [5.36.0](https://www.github.com/googleapis/sloth/compare/v5.35.0...v5.36.0) (2020-09-23)
### Features
* **repos:** adds nodejs-ai-platform repo ([#804](https://www.github.com/googleapis/sloth/issues/804)) ([b754a29](https://www.github.com/googleapis/sloth/commit/b754a29d59501a8234ef70640e29398abe11a1df))
### Bug Fixes
* add nodejs-security-private-ca to repos.json ([#803](https://www.github.com/googleapis/sloth/issues/803)) ([88aaa91](https://www.github.com/googleapis/sloth/commit/88aaa91726f51f3cfae27ed9b03e306b0b411d2c))
## [5.35.0](https://www.github.com/googleapis/sloth/compare/v5.34.0...v5.35.0) (2020-09-15)
### Features
* new node.js libraries ([#801](https://www.github.com/googleapis/sloth/issues/801)) ([e29a531](https://www.github.com/googleapis/sloth/commit/e29a531793ead588dbeeef81907c9798a33a7f9b))
### Bug Fixes
* add python-analytics-data and python-area120-tables ([#798](https://www.github.com/googleapis/sloth/issues/798)) ([ae12158](https://www.github.com/googleapis/sloth/commit/ae121583252d5311d62e60078057f1087cce9c10))
## [5.34.0](https://www.github.com/googleapis/sloth/compare/v5.33.0...v5.34.0) (2020-09-12)
### Features
* add retry logic with backoff ([#793](https://www.github.com/googleapis/sloth/issues/793)) ([f86ee6f](https://www.github.com/googleapis/sloth/commit/f86ee6f994fe02abcdfdf3532ff6297d324f9a9b))
## [5.33.0](https://www.github.com/googleapis/sloth/compare/v5.32.4...v5.33.0) (2020-09-03)
### Features
* **repos:** adds nodejs-notebooks repo ([#791](https://www.github.com/googleapis/sloth/issues/791)) ([95e59e1](https://www.github.com/googleapis/sloth/commit/95e59e1dacd42283054fe39311199d2848163c87))
### [5.32.4](https://www.github.com/googleapis/sloth/compare/v5.32.3...v5.32.4) (2020-09-02)
### Bug Fixes
* catch-all samples issues go to onramp ([#789](https://www.github.com/googleapis/sloth/issues/789)) ([1e6672f](https://www.github.com/googleapis/sloth/commit/1e6672ffc848cefdf1b881f5aa9ff5b907f4ce56))
### [5.32.3](https://www.github.com/googleapis/sloth/compare/v5.32.2...v5.32.3) (2020-09-02)
### Bug Fixes
* add nodejs-analytics-data library ([#787](https://www.github.com/googleapis/sloth/issues/787)) ([020662e](https://www.github.com/googleapis/sloth/commit/020662e4bec9cad646b0889340e2c93c74a6f14f))
### [5.32.2](https://www.github.com/googleapis/sloth/compare/v5.32.1...v5.32.2) (2020-08-28)
### Bug Fixes
* drop java-bigtable-emulator from repos ([#785](https://www.github.com/googleapis/sloth/issues/785)) ([f69f046](https://www.github.com/googleapis/sloth/commit/f69f046dd97800fcb7ac17c1f15f6c2f46a175fc))
### [5.32.1](https://www.github.com/googleapis/sloth/compare/v5.32.0...v5.32.1) (2020-08-26)
### Bug Fixes
* update teams.json to fix ownership of "notebooks" API ([#782](https://www.github.com/googleapis/sloth/issues/782)) ([4fb6373](https://www.github.com/googleapis/sloth/commit/4fb6373c5bd8ed105753ed7fbeef363b8c14e16b))
## [5.32.0](https://www.github.com/googleapis/sloth/compare/v5.31.4...v5.32.0) (2020-08-25)
### Features
* **node:** add dialogflow-cx ([#779](https://www.github.com/googleapis/sloth/issues/779)) ([5a5ea7c](https://www.github.com/googleapis/sloth/commit/5a5ea7c9efcf572855b963476608349842477a02))
### Bug Fixes
* add python dialogflow-cx and transcoder repos ([#777](https://www.github.com/googleapis/sloth/issues/777)) ([82470e0](https://www.github.com/googleapis/sloth/commit/82470e00cd237770e9991a5d03faac97506b89c9))
### [5.31.4](https://www.github.com/googleapis/sloth/compare/v5.31.3...v5.31.4) (2020-08-20)
### Bug Fixes
* updating list of APIs owned by code-build-run team ([#769](https://www.github.com/googleapis/sloth/issues/769)) ([bad516b](https://www.github.com/googleapis/sloth/commit/bad516beef1370a3db78054068a0e8fc377350f2))
### [5.31.3](https://www.github.com/googleapis/sloth/compare/v5.31.2...v5.31.3) (2020-07-31)
### Bug Fixes
* **deps:** roll back dependency @justinbeckwith/sloth to ^5.31.1 ([#763](https://www.github.com/googleapis/sloth/issues/763)) ([161f2b7](https://www.github.com/googleapis/sloth/commit/161f2b79fc38942d016a00faa925d2a383d11852))
### [5.31.2](https://www.github.com/googleapis/sloth/compare/v5.31.1...v5.31.2) (2020-07-31)
### Bug Fixes
* add python-audit-log to repos ([#761](https://www.github.com/googleapis/sloth/issues/761)) ([67e7f39](https://www.github.com/googleapis/sloth/commit/67e7f39507513b38998f1d4105accada8f1c102f))
### [5.31.1](https://www.github.com/googleapis/sloth/compare/v5.31.0...v5.31.1) (2020-07-28)
### Bug Fixes
* add proto-plus-python to actools ([#756](https://www.github.com/googleapis/sloth/issues/756)) ([ea4412b](https://www.github.com/googleapis/sloth/commit/ea4412bb107c15ec097d1342c2fbe2775c67b258))
* makes proto-plus-python issues team managed ([#759](https://www.github.com/googleapis/sloth/issues/759)) ([4913bd6](https://www.github.com/googleapis/sloth/commit/4913bd6bfda738cdfa24a7dd8afd259b677668cb))
## [5.31.0](https://www.github.com/googleapis/sloth/compare/v5.30.1...v5.31.0) (2020-07-27)
### Features
* add doc repos and teams ([#753](https://www.github.com/googleapis/sloth/issues/753)) ([3ec5996](https://www.github.com/googleapis/sloth/commit/3ec5996213f1f638dbb3c20d483764a2d2c03a12))
* add nodejs-analytics-admin and nodejs-functions ([#752](https://www.github.com/googleapis/sloth/issues/752)) ([ac7725f](https://www.github.com/googleapis/sloth/commit/ac7725fa2dad3c8d7d75327c4b130fb7fa15ad85))
### [5.30.1](https://www.github.com/googleapis/sloth/compare/v5.30.0...v5.30.1) (2020-07-24)
### Bug Fixes
* add jsdoc-region-tag repository ([#749](https://www.github.com/googleapis/sloth/issues/749)) ([96fbfc2](https://www.github.com/googleapis/sloth/commit/96fbfc2ac036f7bf3ba5fbdc71fb3bde57cf9ff9))
## [5.30.0](https://www.github.com/googleapis/sloth/compare/v5.29.2...v5.30.0) (2020-07-23)
### Features
* add python-functions and python-analytics-admin ([#747](https://www.github.com/googleapis/sloth/issues/747)) ([fabb641](https://www.github.com/googleapis/sloth/commit/fabb641f5b65c572b46ac6068e6854a08b5744db))
### [5.29.2](https://www.github.com/googleapis/sloth/compare/v5.29.1...v5.29.2) (2020-07-16)
### Bug Fixes
* add ability to set language via label ([#741](https://www.github.com/googleapis/sloth/issues/741)) ([a8c07a3](https://www.github.com/googleapis/sloth/commit/a8c07a3313d39b0db0a9e963f95333f9893dd286))
### [5.29.1](https://www.github.com/googleapis/sloth/compare/v5.29.0...v5.29.1) (2020-07-08)
### Bug Fixes
* add BigQuery Reservation ([#736](https://www.github.com/googleapis/sloth/issues/736)) ([6610d78](https://www.github.com/googleapis/sloth/commit/6610d7840e22e8db2f85f5d97fc0b1648969f3cf))
## [5.29.0](https://www.github.com/googleapis/sloth/compare/v5.28.2...v5.29.0) (2020-06-25)
### Features
* data-analytics is its own team ([#731](https://www.github.com/googleapis/sloth/issues/731)) ([294486a](https://www.github.com/googleapis/sloth/commit/294486a97f81fc0afd1cb1e92d2fb84ba421fc55))
### Bug Fixes
* **deps:** update dependency @google-cloud/bigquery to v5 ([#724](https://www.github.com/googleapis/sloth/issues/724)) ([2bbf2df](https://www.github.com/googleapis/sloth/commit/2bbf2df8bba00e585170b00d07489419f1fe3f7e))
### [5.28.2](https://www.github.com/googleapis/sloth/compare/v5.28.1...v5.28.2) (2020-06-19)
### Bug Fixes
* update node issue template ([#722](https://www.github.com/googleapis/sloth/issues/722)) ([660f5fd](https://www.github.com/googleapis/sloth/commit/660f5fd91cbe5fbdfc71c5bea81153d2fda38730))
### [5.28.1](https://www.github.com/googleapis/sloth/compare/v5.28.0...v5.28.1) (2020-06-15)
### Bug Fixes
* include new CAKE repos in teams ([#719](https://www.github.com/googleapis/sloth/issues/719)) ([fcd569d](https://www.github.com/googleapis/sloth/commit/fcd569dcc260bd442b9ce7fb030151f27e56e8c0))
* update APM team attribution ([#717](https://www.github.com/googleapis/sloth/issues/717)) ([5dd9702](https://www.github.com/googleapis/sloth/commit/5dd97024dd399fe7070279c08d20dbf16ea78835))
## [5.28.0](https://www.github.com/googleapis/sloth/compare/v5.27.0...v5.28.0) (2020-06-12)
### Features
* **secrets:** begin migration to secret manager from keystore ([#705](https://www.github.com/googleapis/sloth/issues/705)) ([4befa68](https://www.github.com/googleapis/sloth/commit/4befa6892b812207670d9fa9516368f6fe6030d3))
### Bug Fixes
* Adding stackdriver-sandbox and cloud-code-samples ([#708](https://www.github.com/googleapis/sloth/issues/708)) ([91f753e](https://www.github.com/googleapis/sloth/commit/91f753ea08a53c7bf82c4c246f6bfe8fd48b489e))
* corrects shortname for Cloud Translation API ([#711](https://www.github.com/googleapis/sloth/issues/711)) ([a980e00](https://www.github.com/googleapis/sloth/commit/a980e0015156489b9c50eaf19c33addb35b87577))
## [5.27.0](https://www.github.com/googleapis/sloth/compare/v5.26.2...v5.27.0) (2020-06-10)
### Features
* add xiaozhenliu to yoshi-python ([#701](https://www.github.com/googleapis/sloth/issues/701)) ([c64c761](https://www.github.com/googleapis/sloth/commit/c64c76125bce7d7ef8281f8dafa58e86277ed8e6))
### Bug Fixes
* **deps:** update dependency @octokit/rest to v17.11.0 ([#700](https://www.github.com/googleapis/sloth/issues/700)) ([b834404](https://www.github.com/googleapis/sloth/commit/b834404f1b8b615cf98ed7026570a8904a403d53))
* add APIs to AnIML teams ([#703](https://www.github.com/googleapis/sloth/issues/703)) ([e096274](https://www.github.com/googleapis/sloth/commit/e0962743aba8b18d107c3fef2bca3c0f80bc87ca))
* add python-os-config repo ([#704](https://www.github.com/googleapis/sloth/issues/704)) ([813df10](https://www.github.com/googleapis/sloth/commit/813df106c4564a124269fa32e13d39eda97e94bb))
### [5.26.2](https://www.github.com/googleapis/sloth/compare/v5.26.1...v5.26.2) (2020-06-05)
### Bug Fixes
* add meredithslota to teams they triage/assign ([#695](https://www.github.com/googleapis/sloth/issues/695)) ([455eae7](https://www.github.com/googleapis/sloth/commit/455eae723e3de5c469a088f631f076ef9231eb70))
* **deps:** update dependency @octokit/rest to v17.10.0 ([#698](https://www.github.com/googleapis/sloth/issues/698)) ([a697b7f](https://www.github.com/googleapis/sloth/commit/a697b7fd35df040ff03cb25e4a62f8cf879f3b62))
* **deps:** update dependency @octokit/rest to v17.9.3 ([#697](https://www.github.com/googleapis/sloth/issues/697)) ([3eef942](https://www.github.com/googleapis/sloth/commit/3eef9420226e1e21086eed5765610a0e715d8eec))
### [5.26.1](https://www.github.com/googleapis/sloth/compare/v5.26.0...v5.26.1) (2020-05-29)
### Bug Fixes
* assign more APIs to cake ([#692](https://www.github.com/googleapis/sloth/issues/692)) ([c6a5e0e](https://www.github.com/googleapis/sloth/commit/c6a5e0e8cf7ffa396568c7a2251e292cf77a1843))
## [5.26.0](https://www.github.com/googleapis/sloth/compare/v5.25.2...v5.26.0) (2020-05-20)
### Features
* add python-bigquery-connection repo ([#685](https://www.github.com/googleapis/sloth/issues/685)) ([796b8b1](https://www.github.com/googleapis/sloth/commit/796b8b1198de9ac70797ba64e07053600154fe86))
### Bug Fixes
* add jsdoc-fresh repos ([#687](https://www.github.com/googleapis/sloth/issues/687)) ([0c2b306](https://www.github.com/googleapis/sloth/commit/0c2b30612c4caaeeb67b1a8b9c987daf17355a91))
* remove bcoe from teams they're not contributing to ([#688](https://www.github.com/googleapis/sloth/issues/688)) ([b9e17cc](https://www.github.com/googleapis/sloth/commit/b9e17ccc5a824735f849da15cbc23958cb271420))
### [5.25.2](https://www.github.com/googleapis/sloth/compare/v5.25.1...v5.25.2) (2020-05-19)
### Bug Fixes
* **deps:** update dependency @octokit/rest to v17.9.2 ([#682](https://www.github.com/googleapis/sloth/issues/682)) ([f51967b](https://www.github.com/googleapis/sloth/commit/f51967b5c06231b87881f8f2ee25d92750b31bfa))
* add java-pubsublite repository ([#684](https://www.github.com/googleapis/sloth/issues/684)) ([ba95d59](https://www.github.com/googleapis/sloth/commit/ba95d59e39439050ad1d64786e1431e19b107df4))
### [5.25.1](https://www.github.com/googleapis/sloth/compare/v5.25.0...v5.25.1) (2020-05-18)
### Bug Fixes
* **deps:** update dependency @octokit/rest to v17.9.1 ([#680](https://www.github.com/googleapis/sloth/issues/680)) ([b452bd8](https://www.github.com/googleapis/sloth/commit/b452bd8526c292efd0d6abc424d0fa7eefe7ffd1))
## [5.25.0](https://www.github.com/googleapis/sloth/compare/v5.24.0...v5.25.0) (2020-05-13)
### Features
* adding missing repos and update teams ([#676](https://www.github.com/googleapis/sloth/issues/676)) ([89b9b2e](https://www.github.com/googleapis/sloth/commit/89b9b2eb77c14b5e18585eb499bf6edd62ec4e60))
### Bug Fixes
* **deps:** update dependency @octokit/rest to v17.9.0 ([#672](https://www.github.com/googleapis/sloth/issues/672)) ([85f9fc4](https://www.github.com/googleapis/sloth/commit/85f9fc4799162fa0bc0b5a26566c253ad3052816))
* adds intern to python ([#674](https://www.github.com/googleapis/sloth/issues/674)) ([7dfc5d5](https://www.github.com/googleapis/sloth/commit/7dfc5d560f376024c026e07360c0bba2928ac90e)), closes [#673](https://www.github.com/googleapis/sloth/issues/673)
## [5.24.0](https://www.github.com/googleapis/sloth/compare/v5.23.0...v5.24.0) (2020-05-11)
### Features
* **java:** add java-iam repo ([#665](https://www.github.com/googleapis/sloth/issues/665)) ([c23e8ad](https://www.github.com/googleapis/sloth/commit/c23e8ad348e4a8d3f9638e1a8f2642b2cd6187c8))
* add os-config ([#671](https://www.github.com/googleapis/sloth/issues/671)) ([3dbf7f2](https://www.github.com/googleapis/sloth/commit/3dbf7f288138e667f27842b5c56ad94d94623d8b))
* add python orgpolicy and accesscontextmanager ([#669](https://www.github.com/googleapis/sloth/issues/669)) ([0889093](https://www.github.com/googleapis/sloth/commit/0889093189001d888233c2158d04deb470bf3378))
### Bug Fixes
* **deps:** update dependency @octokit/rest to v17.7.0 ([#664](https://www.github.com/googleapis/sloth/issues/664)) ([e606eed](https://www.github.com/googleapis/sloth/commit/e606eed707762be08d36da9b8289c1f2f16e39aa))
* **deps:** update dependency @octokit/rest to v17.8.0 ([#667](https://www.github.com/googleapis/sloth/issues/667)) ([e967305](https://www.github.com/googleapis/sloth/commit/e9673058f5e6a43ad9a6dbbd0acf3a72210b150a))
* **deps:** upgrade to meow 7.x ([#670](https://www.github.com/googleapis/sloth/issues/670)) ([d5849af](https://www.github.com/googleapis/sloth/commit/d5849af7a9c1046d646e41dac0a901b36610e519))
## [5.23.0](https://www.github.com/googleapis/sloth/compare/v5.22.0...v5.23.0) (2020-05-04)
### Features
* **java:** add java-common-protos repo ([#661](https://www.github.com/googleapis/sloth/issues/661)) ([ad27652](https://www.github.com/googleapis/sloth/commit/ad27652b575af1782d8c46a05b16edcd4d077bef))
## [5.22.0](https://www.github.com/googleapis/sloth/compare/v5.21.0...v5.22.0) (2020-04-27)
### Features
* add BigQuery Connections, BigQuery Reservations repos. ([#649](https://www.github.com/googleapis/sloth/issues/649)) ([1f5ab3a](https://www.github.com/googleapis/sloth/commit/1f5ab3a468784e5d9b9f46a892905c08772180e0))
* add python-test-utils ([#648](https://www.github.com/googleapis/sloth/issues/648)) ([c4ab444](https://www.github.com/googleapis/sloth/commit/c4ab444aeadf756492562aff6f744631f7db3e61))
### Bug Fixes
* **deps:** update dependency @octokit/rest to v17.5.2 ([#642](https://www.github.com/googleapis/sloth/issues/642)) ([74233cf](https://www.github.com/googleapis/sloth/commit/74233cf3021c6a2c12d26fc8207d328ed50a0c4c))
* add nodejs-local-auth ([#647](https://www.github.com/googleapis/sloth/issues/647)) ([1d0c173](https://www.github.com/googleapis/sloth/commit/1d0c1738b62aef335d7d4944b9463ccc6848638f))
* **deps:** update dependency @octokit/rest to v17.6.0 ([#646](https://www.github.com/googleapis/sloth/issues/646)) ([ea1ed79](https://www.github.com/googleapis/sloth/commit/ea1ed792122b3e14d46a36a0d0a7380008a2d278))
* add storagetransfer to SoDa ([#654](https://www.github.com/googleapis/sloth/issues/654)) ([179e19b](https://www.github.com/googleapis/sloth/commit/179e19b4000220caa506b19640d6e633349db2ac))
## [5.21.0](https://www.github.com/googleapis/sloth/compare/v5.20.2...v5.21.0) (2020-04-23)
### Features
* add python-recaptcha-enterprise ([#639](https://www.github.com/googleapis/sloth/issues/639)) ([2238bb5](https://www.github.com/googleapis/sloth/commit/2238bb51097ff552028e1f270abcdaadc0b46ede))
* **python:** add python-api-common-protos ([#641](https://www.github.com/googleapis/sloth/issues/641)) ([411d170](https://www.github.com/googleapis/sloth/commit/411d170bf1cb37ad01ab574334091d8db109fe80))
### Bug Fixes
* remove the google-cloud-cpp-pubsub repo ([#643](https://www.github.com/googleapis/sloth/issues/643)) ([7337f41](https://www.github.com/googleapis/sloth/commit/7337f41f47f9e7b0bb4465ed5caf35aa46f8b8c3))
### [5.20.2](https://www.github.com/googleapis/sloth/compare/v5.20.1...v5.20.2) (2020-04-20)
### Bug Fixes
* **deps:** update dependency @octokit/rest to v17.5.1 ([#636](https://www.github.com/googleapis/sloth/issues/636)) ([e221dc5](https://www.github.com/googleapis/sloth/commit/e221dc539280bbe6d0643d1e9442ab9aa32b3ca1))
* **deps:** update dependency csv-string to v4 ([#634](https://www.github.com/googleapis/sloth/issues/634)) ([b4a2b69](https://www.github.com/googleapis/sloth/commit/b4a2b69bdc5a3fb33cc54bfa8d948ed7e3d71659))
* re-enable the field mask ([#638](https://www.github.com/googleapis/sloth/issues/638)) ([11451bc](https://www.github.com/googleapis/sloth/commit/11451bc72793e911fa48b505850926929112eef2))
### [5.20.1](https://www.github.com/googleapis/sloth/compare/v5.20.0...v5.20.1) (2020-04-17)
### Bug Fixes
* remove field mask due to closed issues being returned ([#632](https://www.github.com/googleapis/sloth/issues/632)) ([1b0f29f](https://www.github.com/googleapis/sloth/commit/1b0f29f71a6d5c17b19976ad39c5410232c5e6b9))
## [5.20.0](https://www.github.com/googleapis/sloth/compare/v5.19.0...v5.20.0) (2020-04-17)
### Features
* add bradmiro to java and python ([#627](https://www.github.com/googleapis/sloth/issues/627)) ([6ca8be7](https://www.github.com/googleapis/sloth/commit/6ca8be73826dfc3640963327f677c6a8a423bb67))
* add suraj-qlogic to java team ([#578](https://www.github.com/googleapis/sloth/issues/578)) ([75adb24](https://www.github.com/googleapis/sloth/commit/75adb24d8a996ca03dcfd8b940647af152a97287))
* Use field_mask for faster retrieval of issues ([#573](https://www.github.com/googleapis/sloth/issues/573)) ([15e88d9](https://www.github.com/googleapis/sloth/commit/15e88d9abe4b007b7128987f4e6eceeaa432816e))
### Bug Fixes
* apache license URL ([#468](https://www.github.com/googleapis/sloth/issues/468)) ([#626](https://www.github.com/googleapis/sloth/issues/626)) ([25ecc34](https://www.github.com/googleapis/sloth/commit/25ecc34fdabfc64abe7026eaf9b287402bab8196))
* **deps:** update dependency @octokit/rest to v17.2.1 ([#625](https://www.github.com/googleapis/sloth/issues/625)) ([52a8f8d](https://www.github.com/googleapis/sloth/commit/52a8f8da6b814643f81f21a08a88d676c00c8b65))
* **deps:** update dependency @octokit/rest to v17.3.0 ([#630](https://www.github.com/googleapis/sloth/issues/630)) ([e42eecb](https://www.github.com/googleapis/sloth/commit/e42eecb92a63f20a51a3cb614a3773acdfaa37c1))
* remove the google-cloud-cpp-bigquery repo ([#631](https://www.github.com/googleapis/sloth/issues/631)) ([369db83](https://www.github.com/googleapis/sloth/commit/369db83b07463e027111afd70febf729e0144104))
## [5.19.0](https://www.github.com/googleapis/sloth/compare/v5.18.0...v5.19.0) (2020-04-03)
### Features
* add dwsupplee to yoshi-go ([#616](https://www.github.com/googleapis/sloth/issues/616)) ([d0fcacf](https://www.github.com/googleapis/sloth/commit/d0fcacf25fee0f05bec6bd3ff6dc5f1fda698e56))
* **deps:** drop node8 & update dependencies ([#617](https://www.github.com/googleapis/sloth/issues/617)) ([1706df9](https://www.github.com/googleapis/sloth/commit/1706df9838713a9a4e1ab3d7cc6ea44305d9dc83))
* **java:** add java-shared-dependencies repo ([#615](https://www.github.com/googleapis/sloth/issues/615)) ([be31169](https://www.github.com/googleapis/sloth/commit/be31169d83e4ed6262ac397df1e15e211cb6fa29))
* add java-accesscontextmanager, java-os-config ([#622](https://www.github.com/googleapis/sloth/issues/622)) ([ef9583a](https://www.github.com/googleapis/sloth/commit/ef9583a6de8d3eb425bfc04264396f59f15db6e6))
* add java-orgpolicy repo ([#612](https://www.github.com/googleapis/sloth/issues/612)) ([4fa7ec9](https://www.github.com/googleapis/sloth/commit/4fa7ec942cabd86946c6933005c32e1d913325d8))
* add nodejs-memcache ([#621](https://www.github.com/googleapis/sloth/issues/621)) ([039a6da](https://www.github.com/googleapis/sloth/commit/039a6da5ba87f23a72273d7cc92b81e6de3d55b5))
### Bug Fixes
* add python-spanner-django repo ([#618](https://www.github.com/googleapis/sloth/issues/618)) ([52347e8](https://www.github.com/googleapis/sloth/commit/52347e89cd336127071db078546842b2589b5f4d))
## [5.18.0](https://www.github.com/googleapis/sloth/compare/v5.17.1...v5.18.0) (2020-03-25)
### Features
* **java:** add java-recommendations-ai and java-securitycenter-settings repos ([#606](https://www.github.com/googleapis/sloth/issues/606)) ([1a0a6e7](https://www.github.com/googleapis/sloth/commit/1a0a6e75d5e1e5c685650d720d49ae1a4cfa1474))
### Bug Fixes
* limit yoshi team membership ([#589](https://www.github.com/googleapis/sloth/issues/589)) ([a34ff01](https://www.github.com/googleapis/sloth/commit/a34ff01ca175fddd5cb81955e5ac33053fbe40ad))
* **deps:** update dependency gaxios to v3 ([#608](https://www.github.com/googleapis/sloth/issues/608)) ([e072e16](https://www.github.com/googleapis/sloth/commit/e072e1668826524707b2c53c1e8cb9759f8a9583))
### [5.17.1](https://www.github.com/googleapis/sloth/compare/v5.17.0...v5.17.1) (2020-03-21)
### Bug Fixes
* attributes to team before api, when appropriate ([#600](https://www.github.com/googleapis/sloth/issues/600)) ([b56fe5b](https://www.github.com/googleapis/sloth/commit/b56fe5b797bfb580d9d24ca96f92ce73ac73b616)), closes [#562](https://www.github.com/googleapis/sloth/issues/562) [#562](https://www.github.com/googleapis/sloth/issues/562)
* correct typo in python-media-translation repo name ([#599](https://www.github.com/googleapis/sloth/issues/599)) ([8fdf0f5](https://www.github.com/googleapis/sloth/commit/8fdf0f5567a19911e60949ad0a39aa01a15462c8)), closes [#562](https://www.github.com/googleapis/sloth/issues/562)
* revert attributes team by repo before api ([#563](https://www.github.com/googleapis/sloth/issues/563)) ([#596](https://www.github.com/googleapis/sloth/issues/596)) ([213c428](https://www.github.com/googleapis/sloth/commit/213c428574bc84ad8c68e042685f5d286801303e))
## [5.17.0](https://www.github.com/googleapis/sloth/compare/v5.16.0...v5.17.0) (2020-03-19)
### Features
* add nodejs-media-translation ([#592](https://www.github.com/googleapis/sloth/issues/592)) ([7c58eda](https://www.github.com/googleapis/sloth/commit/7c58edaff18ea4907ab3e2cf64308ea46048d9e7))
## [5.16.0](https://www.github.com/googleapis/sloth/compare/v5.15.0...v5.16.0) (2020-03-17)
### Features
* **java:** add java-mediatranslation repo ([#590](https://www.github.com/googleapis/sloth/issues/590)) ([b8fd3d1](https://www.github.com/googleapis/sloth/commit/b8fd3d1c7511379a6aabfaa63d599186d8401387))
### Bug Fixes
* adds Alex to python-docs-samples ([#587](https://www.github.com/googleapis/sloth/issues/587)) ([d8cb329](https://www.github.com/googleapis/sloth/commit/d8cb3291b66526af8f4ce4dd71a0d8ad5929b448))
## [5.15.0](https://www.github.com/googleapis/sloth/compare/v5.14.0...v5.15.0) (2020-03-13)
### Features
* **java:** add java-document-ai repo ([#584](https://www.github.com/googleapis/sloth/issues/584)) ([8115009](https://www.github.com/googleapis/sloth/commit/8115009199adea1336ac1fdfcb0ec259ea6d42c4))
* add python-service-directory and python-recommendations-ai ([#586](https://www.github.com/googleapis/sloth/issues/586)) ([85ba7e4](https://www.github.com/googleapis/sloth/commit/85ba7e479b357f55c2bddaab68aec419df9fd0e4))
* adds Document AI to repos.json ([#582](https://www.github.com/googleapis/sloth/issues/582)) ([df82f91](https://www.github.com/googleapis/sloth/commit/df82f9175733e1136c37715047eb0971b18fffa9))
## [5.14.0](https://www.github.com/googleapis/sloth/compare/v5.13.0...v5.14.0) (2020-03-13)
### Features
* add java-memcache repo ([#575](https://www.github.com/googleapis/sloth/issues/575)) ([4e2cb1a](https://www.github.com/googleapis/sloth/commit/4e2cb1aee0350ad50714af7295daa11ff70f8b85))
* add java-servicedirectory repo ([#580](https://www.github.com/googleapis/sloth/issues/580)) ([55abdf1](https://www.github.com/googleapis/sloth/commit/55abdf1ecc9aabcf19b0da1c2be14c4522f23b04))
### Bug Fixes
* do not require API hints ([#583](https://www.github.com/googleapis/sloth/issues/583)) ([990b2f5](https://www.github.com/googleapis/sloth/commit/990b2f59592d313f9a257460f5f55ce939b2256c))
## [5.13.0](https://www.github.com/googleapis/sloth/compare/v5.12.0...v5.13.0) (2020-03-06)
### Features
* update SLO calculation to match policy ([#568](https://www.github.com/googleapis/sloth/issues/568)) ([7d88ffc](https://www.github.com/googleapis/sloth/commit/7d88ffcd47d3fba2325ed81edd758c6929092e0c))
### Bug Fixes
* repo issue fetch needs to be serial ([#571](https://www.github.com/googleapis/sloth/issues/571)) ([9ab9cb6](https://www.github.com/googleapis/sloth/commit/9ab9cb6b93744158e83d39ffaa84038c86d7f1c8))
## [5.12.0](https://www.github.com/googleapis/sloth/compare/v5.11.1...v5.12.0) (2020-03-05)
### Features
* add meredithslota to yoshi ([#566](https://www.github.com/googleapis/sloth/issues/566)) ([0f8951a](https://www.github.com/googleapis/sloth/commit/0f8951a28d3ca1c9a11c66fe5f2aa6b88596cb40))
### Bug Fixes
* add samples/docs repos, and remove jskeet from Ruby team ([#564](https://www.github.com/googleapis/sloth/issues/564)) ([a8d72b9](https://www.github.com/googleapis/sloth/commit/a8d72b9977dfce4f80765475e1bf1f0d0cf1809e))
* **drghs:** add pagination support ([#506](https://www.github.com/googleapis/sloth/issues/506)) ([6cd9b22](https://www.github.com/googleapis/sloth/commit/6cd9b22cf2eee790d9a2b67c6adeb33dc1eed310))
### [5.11.1](https://www.github.com/googleapis/sloth/compare/v5.11.0...v5.11.1) (2020-03-04)
### Bug Fixes
* attributes team by repo before api ([#563](https://www.github.com/googleapis/sloth/issues/563)) ([02b4a3b](https://www.github.com/googleapis/sloth/commit/02b4a3b0a7096992fa70e2a25aae8ae4b2c836f5)), closes [#562](https://www.github.com/googleapis/sloth/issues/562)
* cbr owns tasks ([#560](https://www.github.com/googleapis/sloth/issues/560)) ([ccc5eb4](https://www.github.com/googleapis/sloth/commit/ccc5eb47b58dbac91eeab58705455557b1bb98f0))
* remove python 3.5 kokoro requirement ([#561](https://www.github.com/googleapis/sloth/issues/561)) ([a77add2](https://www.github.com/googleapis/sloth/commit/a77add2fcdf5ab8c1c8393cdab772efbed75dbf8))
* remove tswast from yoshi teams ([#558](https://www.github.com/googleapis/sloth/issues/558)) ([5795e58](https://www.github.com/googleapis/sloth/commit/5795e585f2d781a2ab0e48bb44beb2cb13b5cafa))
## [5.11.0](https://www.github.com/googleapis/sloth/compare/v5.10.0...v5.11.0) (2020-03-03)
### Features
* **python:** add python-billing repo ([#554](https://www.github.com/googleapis/sloth/issues/554)) ([edbc344](https://www.github.com/googleapis/sloth/commit/edbc344e18460fd6719849fa3200d531f5a33a3a))
* **python:** add python-memcache repo ([#557](https://www.github.com/googleapis/sloth/issues/557)) ([2d5c6c3](https://www.github.com/googleapis/sloth/commit/2d5c6c33087aead27d82e1be41b2fc8f39b51cce))
### Bug Fixes
* cloud-trace-nodejs has different requirements for tests ([#552](https://www.github.com/googleapis/sloth/issues/552)) ([933e19b](https://www.github.com/googleapis/sloth/commit/933e19b70cf2e3a1e622b0d2fc8191ec128f7c65))
## [5.10.0](https://www.github.com/googleapis/sloth/compare/v5.9.0...v5.10.0) (2020-02-28)
### Features
* add bigquery-storage ([#542](https://www.github.com/googleapis/sloth/issues/542)) ([f945488](https://www.github.com/googleapis/sloth/commit/f9454884fbcf57277d071667cb1a5abb7e81111d))
* add nodejs-billing to sloth ([#549](https://www.github.com/googleapis/sloth/issues/549)) ([7becffe](https://www.github.com/googleapis/sloth/commit/7becffe066ce9ef33fe47fb0f38f161cea3c40a7))
* updates users.json to include Game Servers ([#540](https://www.github.com/googleapis/sloth/issues/540)) ([c115aa4](https://www.github.com/googleapis/sloth/commit/c115aa470e39b5fcc7c2caeba5a5b3406f3e94e2))
### Bug Fixes
* add dsymonds to yoshi-go ([#548](https://www.github.com/googleapis/sloth/issues/548)) ([6a413c3](https://www.github.com/googleapis/sloth/commit/6a413c39d359e670596ac11ea6753c792cb941b2))
* add support for Node Support ([#543](https://www.github.com/googleapis/sloth/issues/543)) ([50d7c9d](https://www.github.com/googleapis/sloth/commit/50d7c9d6346f23ec265b1a994f6829ad0939cf38))
* add support for Python Samples Docs ([#544](https://www.github.com/googleapis/sloth/issues/544)) ([37a6dc6](https://www.github.com/googleapis/sloth/commit/37a6dc626c6fce9bb692e4913e25fd5722f2d03d))
## [5.9.0](https://www.github.com/googleapis/sloth/compare/v5.8.0...v5.9.0) (2020-02-24)
### Features
* add arithmetic1728 to yoshi-python ([#531](https://www.github.com/googleapis/sloth/issues/531)) ([ef9db71](https://www.github.com/googleapis/sloth/commit/ef9db7122f92bffafa8ad140512ffdf16cdbe418))
* add nightly snapshot job ([#524](https://www.github.com/googleapis/sloth/issues/524)) ([ba17d5c](https://www.github.com/googleapis/sloth/commit/ba17d5c00ff43738a72b85bfd292d68f94f2a8ce))
* add paul1319 to python ([#522](https://www.github.com/googleapis/sloth/issues/522)) ([8028668](https://www.github.com/googleapis/sloth/commit/8028668e3ddc88ceaead50db41ffd4494b74c20d))
* add repo support to getting started with java and java docs samples ([#534](https://www.github.com/googleapis/sloth/issues/534)) ([5f47d73](https://www.github.com/googleapis/sloth/commit/5f47d738455bd4e56e8d1594039aa9bd26d58ddd))
* add required checks for google-api-ruby-client ([#533](https://www.github.com/googleapis/sloth/issues/533)) ([ce5c6bc](https://www.github.com/googleapis/sloth/commit/ce5c6bce273dd7a04714d6944c38545575d37d11))
* updates repos.json ([#537](https://www.github.com/googleapis/sloth/issues/537)) ([7ef1d3d](https://www.github.com/googleapis/sloth/commit/7ef1d3ddec885ca2abfba8f8553a60e6171d0297))
### Bug Fixes
* drop nodejs-common-grpc module ([#521](https://www.github.com/googleapis/sloth/issues/521)) ([6a65c0a](https://www.github.com/googleapis/sloth/commit/6a65c0ad776d7f4a6b5d4a81491473733d7aac61))
* **java:** add required-checks override for googleapis/google-api-java-client-services ([#525](https://www.github.com/googleapis/sloth/issues/525)) ([5f047ee](https://www.github.com/googleapis/sloth/commit/5f047eedb4e3024874f663a93c64d77537589913))
* no required status checks for google-cloud-node ([#536](https://www.github.com/googleapis/sloth/issues/536)) ([9d8bd93](https://www.github.com/googleapis/sloth/commit/9d8bd933b37e28a1b37f88970012559e8e1dce3d))
* require node13, repo-automation-bots is a snowflake ([#539](https://www.github.com/googleapis/sloth/issues/539)) ([5aa9b62](https://www.github.com/googleapis/sloth/commit/5aa9b6225bd471ae530aa47339c297c469e30321))
## [5.8.0](https://www.github.com/googleapis/sloth/compare/v5.7.0...v5.8.0) (2020-02-12)
### Features
* track java-datastore repo ([#519](https://www.github.com/googleapis/sloth/issues/519)) ([d326cd2](https://www.github.com/googleapis/sloth/commit/d326cd2a8ae5649d4d458a9595a52fbaf69e5e7e))
## [5.7.0](https://www.github.com/googleapis/sloth/compare/v5.6.1...v5.7.0) (2020-02-12)
### Features
* Add Andrew Zammit (zamnuts) to yoshi-nodejs team. ([#513](https://www.github.com/googleapis/sloth/issues/513)) ([09ce1b7](https://www.github.com/googleapis/sloth/commit/09ce1b7425d8c8a190e1b2ae8045b39c06641935))
* add kolea2 to yoshi-nodejs ([#515](https://www.github.com/googleapis/sloth/issues/515)) ([4790f26](https://www.github.com/googleapis/sloth/commit/4790f26cf0241d3debed98cdf3d29c42467da16b))
* break out required checks into JSON file; update Node.js required checks ([#518](https://www.github.com/googleapis/sloth/issues/518)) ([1d19029](https://www.github.com/googleapis/sloth/commit/1d19029abd3474a50fc763ca5a1482dff4835b11))
### [5.6.1](https://www.github.com/googleapis/sloth/compare/v5.6.0...v5.6.1) (2020-02-11)
### Bug Fixes
* add run API to code-build-run team ([#510](https://www.github.com/googleapis/sloth/issues/510)) ([c75093f](https://www.github.com/googleapis/sloth/commit/c75093fcdfbff54719285916fa637ebfc81e813f))
## [5.6.0](https://www.github.com/googleapis/sloth/compare/v5.5.0...v5.6.0) (2020-02-08)
### Features
* add java-accessapproval repository ([#502](https://www.github.com/googleapis/sloth/issues/502)) ([89d4998](https://www.github.com/googleapis/sloth/commit/89d49982f416ae77a5401642e128222f9ab8eb55))
### Bug Fixes
* P1s have a 7 day window ([#507](https://www.github.com/googleapis/sloth/issues/507)) ([3739d5f](https://www.github.com/googleapis/sloth/commit/3739d5f362c070027d01be7a9380a71faaf0e504))
## [5.5.0](https://www.github.com/googleapis/sloth/compare/v5.4.0...v5.5.0) (2020-02-05)
### Features
* add GCS DPEs to Yoshi Python team ([#497](https://www.github.com/googleapis/sloth/issues/497)) ([83d2d39](https://www.github.com/googleapis/sloth/commit/83d2d39f54e71a2fba78d9f7f6a438fa6e2270fb))
### Bug Fixes
* frankyn github handle ([#499](https://www.github.com/googleapis/sloth/issues/499)) ([f027481](https://www.github.com/googleapis/sloth/commit/f02748111aa23353c3f98340bf92385e376b6449))
* **deps:** upgrade to the next octokit ([#501](https://www.github.com/googleapis/sloth/issues/501)) ([98b51a8](https://www.github.com/googleapis/sloth/commit/98b51a80f37210b8ab4034a88a5adedecd182f12))
## [5.4.0](https://www.github.com/googleapis/sloth/compare/v5.3.1...v5.4.0) (2020-02-03)
### Features
* **drghs:** updates drghs API to use new casing ([#474](https://www.github.com/googleapis/sloth/issues/474)) ([121bc66](https://www.github.com/googleapis/sloth/commit/121bc66ac244820231d3a0f655a3db8a1e84389c))
* add java to repo settings sync ([#495](https://www.github.com/googleapis/sloth/issues/495)) ([6664343](https://www.github.com/googleapis/sloth/commit/666434374b12999d1b0f4190ad4c1c038d81c9c8))
* add recommender for PHP to users/repos.json ([#487](https://www.github.com/googleapis/sloth/issues/487)) ([3d5e3f5](https://www.github.com/googleapis/sloth/commit/3d5e3f57c589b8e2f2ded01af96ea3aa25729d86))
* add sync-repo-settings ([#492](https://www.github.com/googleapis/sloth/issues/492)) ([bef1225](https://www.github.com/googleapis/sloth/commit/bef12257be9de02692d2ed47f5f7530a07bfc09f))
* add viacheslav-rostovtsev to a ruby team in users.json ([#484](https://www.github.com/googleapis/sloth/issues/484)) ([bb1756c](https://www.github.com/googleapis/sloth/commit/bb1756cd90cad9fdee9be7df397213427b82a2e8))
* support python for repo-settings-sync ([#493](https://www.github.com/googleapis/sloth/issues/493)) ([59a6d93](https://www.github.com/googleapis/sloth/commit/59a6d93f7995d29eb2c5d341c76895808e5817ad))
### Bug Fixes
* **deps:** update dependency @octokit/rest to v16.43.0 ([#491](https://www.github.com/googleapis/sloth/issues/491)) ([d83cea0](https://www.github.com/googleapis/sloth/commit/d83cea00200c880adc7432e01dc610dfd02b1c27))
* lesv is a javasaur ([#494](https://www.github.com/googleapis/sloth/issues/494)) ([438bb9f](https://www.github.com/googleapis/sloth/commit/438bb9fae0964dc30aff25e6f31db8ee342c8a15))
### [5.3.1](https://www.github.com/googleapis/sloth/compare/v5.3.0...v5.3.1) (2020-01-31)
### Bug Fixes
* bigquerystorage belongs to the animl team ([#481](https://www.github.com/googleapis/sloth/issues/481)) ([d414b61](https://www.github.com/googleapis/sloth/commit/d414b61d9c2be3a082219c21df1265c3b06d0873))
* python-bigquery-storage should be bigquerystorage ([#482](https://www.github.com/googleapis/sloth/issues/482)) ([aa3b79a](https://www.github.com/googleapis/sloth/commit/aa3b79a72ed551b7820df74b5a91514d03dd07d7))
* **deps:** update dependency @octokit/rest to v16.41.0 ([#485](https://www.github.com/googleapis/sloth/issues/485)) ([88bd88d](https://www.github.com/googleapis/sloth/commit/88bd88dee53403e5919bb431418a560c2f2c129f))
## [5.3.0](https://www.github.com/googleapis/sloth/compare/v5.2.0...v5.3.0) (2020-01-30)
### Features
* add java-billing repo ([#480](https://www.github.com/googleapis/sloth/issues/480)) ([119155d](https://www.github.com/googleapis/sloth/commit/119155d858407e6440e5a7347b51d299005dccdb))
* add summer in users.json ([#478](https://www.github.com/googleapis/sloth/issues/478)) ([8cb4e26](https://www.github.com/googleapis/sloth/commit/8cb4e26976d7ba24838bba45cbe0462eb3d90ebc))
* adds me to Node.Js and .NET users ([#460](https://www.github.com/googleapis/sloth/issues/460)) ([aae4d68](https://www.github.com/googleapis/sloth/commit/aae4d6852a057ef507019d0b6adebd2fe4d2add8))
### Bug Fixes
* **deps:** upgrade to latest version of octokit ([#476](https://www.github.com/googleapis/sloth/issues/476)) ([dbd7a9d](https://www.github.com/googleapis/sloth/commit/dbd7a9decb14cba2e03eea2269aed35fb2794c63))
## [5.2.0](https://www.github.com/googleapis/sloth/compare/v5.1.0...v5.2.0) (2020-01-27)
### Features
* add ava12 php ([#470](https://www.github.com/googleapis/sloth/issues/470)) ([2798dc7](https://www.github.com/googleapis/sloth/commit/2798dc7c193ccc12424e84ca8b46a33549b942b5))
* add google-cloud-cpp-pubsub repository ([#465](https://www.github.com/googleapis/sloth/issues/465)) ([e6027d8](https://www.github.com/googleapis/sloth/commit/e6027d8799284f541bbbe6a4d4520c617de8c42b))
* add split python repos to users and repos ([#473](https://www.github.com/googleapis/sloth/issues/473)) ([4c3e836](https://www.github.com/googleapis/sloth/commit/4c3e836826864bcd2e88b43338d4783351e3ff8d))
### Bug Fixes
* add fhinkel to yoshi-nodejs team ([#468](https://www.github.com/googleapis/sloth/issues/468)) ([c5a7bb4](https://www.github.com/googleapis/sloth/commit/c5a7bb420c5defa6de481e6394fe29c6fb8b19ef))
* add hongalex to yoshi group ([#463](https://www.github.com/googleapis/sloth/issues/463)) ([57a72af](https://www.github.com/googleapis/sloth/commit/57a72af28e275f291db583024f0a3a6181d79dc5))
* add secret manager repo for php ([#461](https://www.github.com/googleapis/sloth/issues/461)) ([dc64f29](https://www.github.com/googleapis/sloth/commit/dc64f29b4e3a06c7d87a795b3695f42134088f10))
## [5.1.0](https://www.github.com/googleapis/sloth/compare/v5.0.0...v5.1.0) (2020-01-15)
### Features
* add dmitry-fa to java and node teams ([#429](https://www.github.com/googleapis/sloth/issues/429)) ([6154b3a](https://www.github.com/googleapis/sloth/commit/6154b3ad84f25bc9021eadab968dcf5e1398c64a))
* add new googleapis/nodejs-recommender repo ([#454](https://www.github.com/googleapis/sloth/issues/454)) ([422483a](https://www.github.com/googleapis/sloth/commit/422483aa2bf3fd2caa1ba6780bfa408d02ca7da6))
* adds cloudsql as a monitored label for soda ([#459](https://www.github.com/googleapis/sloth/issues/459)) ([537af78](https://www.github.com/googleapis/sloth/commit/537af78280671e2920bc5453a51c011e03b25b83))
### Bug Fixes
* Add crwilcox to java repos ([#458](https://www.github.com/googleapis/sloth/issues/458)) ([5383ab7](https://www.github.com/googleapis/sloth/commit/5383ab774abee0f269c9fd5ccadb9297e5c18887))
* add python-monitoring-dashboards repo ([#457](https://www.github.com/googleapis/sloth/issues/457)) ([5a3c75e](https://www.github.com/googleapis/sloth/commit/5a3c75e71d1c65677bda4519a9d36f328b43fb9e))
* remove callmehiphop ([#453](https://www.github.com/googleapis/sloth/issues/453)) ([5eec574](https://www.github.com/googleapis/sloth/commit/5eec5746eb90bf42ce69c01f16f7886298b5d7bd))
## [5.0.0](https://www.github.com/googleapis/sloth/compare/v4.30.0...v5.0.0) (2020-01-13)
### ⚠ BREAKING CHANGES
* remove labels command (#427)
### Features
* add nodejs-monitoring-dashboards, nodejs-secret-manager ([#450](https://www.github.com/googleapis/sloth/issues/450)) ([3184da0](https://www.github.com/googleapis/sloth/commit/3184da0eaf2769c951fe2dffefaaeda42dfc751b))
* remove labels command ([#427](https://www.github.com/googleapis/sloth/issues/427)) ([d688509](https://www.github.com/googleapis/sloth/commit/d688509eaeae83a6217cb779c39f172cfa7a160e))
### Bug Fixes
* cbr owns functions ([#448](https://www.github.com/googleapis/sloth/issues/448)) ([ce7e30a](https://www.github.com/googleapis/sloth/commit/ce7e30a07bdac84a4bbb3656b8dc8788c05e7d32))
* ml is owned by animl ([#451](https://www.github.com/googleapis/sloth/issues/451)) ([e1cac61](https://www.github.com/googleapis/sloth/commit/e1cac6133b28ba518e97fd543acb6974e0db33fd))
* remove emar-kar ([#446](https://www.github.com/googleapis/sloth/issues/446)) ([4b31d22](https://www.github.com/googleapis/sloth/commit/4b31d220d9659942f18c05ff89363a4e5d852471))
## [4.30.0](https://www.github.com/googleapis/sloth/compare/v4.29.2...v4.30.0) (2020-01-09)
### Features
* add frankyn to yoshi-java team ([#441](https://www.github.com/googleapis/sloth/issues/441)) ([b54bd64](https://www.github.com/googleapis/sloth/commit/b54bd64bad91f1f9b32d1c230398d26d2f6f0305))
* add java-monitoring-dashboards repo ([#444](https://www.github.com/googleapis/sloth/issues/444)) ([815010a](https://www.github.com/googleapis/sloth/commit/815010a374a819023d70894202908b3dbf44bda2))
### Bug Fixes
* remove jadekler from yoshi groups ([#442](https://www.github.com/googleapis/sloth/issues/442)) ([5e9e5a1](https://www.github.com/googleapis/sloth/commit/5e9e5a139db4820741b30d4b84f51bedb429dd8b))
### [4.29.2](https://www.github.com/googleapis/sloth/compare/v4.29.1...v4.29.2) (2020-01-07)
### Bug Fixes
* appengine belongs to cbr ([#439](https://www.github.com/googleapis/sloth/issues/439)) ([7f889dc](https://www.github.com/googleapis/sloth/commit/7f889dc757a5dc8e44661953ca54004bfaecf093))
### [4.29.1](https://www.github.com/googleapis/sloth/compare/v4.29.0...v4.29.1) (2020-01-04)
### Bug Fixes
* rename to java-bigtable-hbase ([#431](https://www.github.com/googleapis/sloth/issues/431)) ([5721094](https://www.github.com/googleapis/sloth/commit/5721094b972faef23ee1353b9a8fbf67ad8f929e))
* **deps:** update dependency @octokit/rest to v16.36.0 ([#435](https://www.github.com/googleapis/sloth/issues/435)) ([fc91600](https://www.github.com/googleapis/sloth/commit/fc91600776483c655bec866daf164cdbbd139ceb))
## [4.29.0](https://www.github.com/googleapis/sloth/compare/v4.28.0...v4.29.0) (2019-12-18)
### Features
* add irm and secretmanager java repos ([#428](https://www.github.com/googleapis/sloth/issues/428)) ([0891882](https://www.github.com/googleapis/sloth/commit/0891882bffd40680d8a0ada67767f311479bf460))
* add sample-tester repo ([#415](https://www.github.com/googleapis/sloth/issues/415)) ([679b614](https://www.github.com/googleapis/sloth/commit/679b61487e24314f15c477cbfb535964cabca075))
* add user to yoshi-nodejs ([#418](https://www.github.com/googleapis/sloth/issues/418)) ([f50d779](https://www.github.com/googleapis/sloth/commit/f50d7798dad87baf9bfb72bb1e7b12c2f60a1683))
### Bug Fixes
* **deps:** pin TypeScript below 3.7.0 ([50cd2bd](https://www.github.com/googleapis/sloth/commit/50cd2bdd42a0a65a46f7656290ac11e40a0fbc61))
* add nnegrey to yoshi-java ([#421](https://www.github.com/googleapis/sloth/issues/421)) ([44bf74e](https://www.github.com/googleapis/sloth/commit/44bf74e069344b96bad6cd085f3c0b5914420c1e))
* **deps:** update dependency @octokit/rest to v16.35.2 ([#426](https://www.github.com/googleapis/sloth/issues/426)) ([018440e](https://www.github.com/googleapis/sloth/commit/018440e8029d75b7a1387ffe854a7dfac7beeac7))
* **deps:** update dependency update-notifier to v4 ([#424](https://www.github.com/googleapis/sloth/issues/424)) ([56979e9](https://www.github.com/googleapis/sloth/commit/56979e99223ce44f793442e1f9f9918c8a7c4f55))
## [4.28.0](https://www.github.com/googleapis/sloth/compare/v4.27.0...v4.28.0) (2019-11-21)
### Features
* add speech to list of php repos ([#412](https://www.github.com/googleapis/sloth/issues/412)) ([267eabb](https://www.github.com/googleapis/sloth/commit/267eabb70bd4b8b6cb13b5903edd7b6b8fd4bb89))
## [4.27.0](https://www.github.com/googleapis/sloth/compare/v4.26.0...v4.27.0) (2019-11-20)
### Features
* add missing PHP repos to users.json ([#401](https://www.github.com/googleapis/sloth/issues/401)) ([7e7c769](https://www.github.com/googleapis/sloth/commit/7e7c769f59c5c4401033ec18afa9beabdf0abbae))
### Bug Fixes
* correct repo name for nodejs-datastore-kvstore ([#409](https://www.github.com/googleapis/sloth/issues/409)) ([493a085](https://www.github.com/googleapis/sloth/commit/493a08563676a9827791b8ced3e355481490ad56))
* gce-images should now be nodejs-gce-images ([#406](https://www.github.com/googleapis/sloth/issues/406)) ([5e98534](https://www.github.com/googleapis/sloth/commit/5e98534f0ec94586a2dd3e328abfb3a5e8e47db0))
## [4.26.0](https://www.github.com/googleapis/sloth/compare/v4.25.2...v4.26.0) (2019-11-13)
### Features
* add java billing budgets repo ([#395](https://www.github.com/googleapis/sloth/issues/395)) ([f77813f](https://www.github.com/googleapis/sloth/commit/f77813f6757a4d970c8146cb18de15622c51c10c))
* add missing PHP repos ([#400](https://www.github.com/googleapis/sloth/issues/400)) ([e6e47f5](https://www.github.com/googleapis/sloth/commit/e6e47f5bddef307fd8e5a46c843528d6f378a5e9))
### Bug Fixes
* **docs:** add jsdoc-region-tag plugin ([#399](https://www.github.com/googleapis/sloth/issues/399)) ([5aba550](https://www.github.com/googleapis/sloth/commit/5aba55008ab2d0ddaa505accbbf901be9076618e))
### [4.25.2](https://www.github.com/googleapis/sloth/compare/v4.25.1...v4.25.2) (2019-11-11)
### Bug Fixes
* **deps:** update dependency @octokit/rest to v16.35.0 ([#393](https://www.github.com/googleapis/sloth/issues/393)) ([ce3dd35](https://www.github.com/googleapis/sloth/commit/ce3dd359c812c1054f4938e2c9400b32221e4673))
### [4.25.1](https://www.github.com/googleapis/sloth/compare/v4.25.0...v4.25.1) (2019-11-06)
### Bug Fixes
* add bigtable hbase java repo ([#389](https://www.github.com/googleapis/sloth/issues/389)) ([a398d95](https://www.github.com/googleapis/sloth/commit/a398d950ebf0357df77a6d9d22d4cd46cbe8dffe))
## [4.25.0](https://www.github.com/googleapis/sloth/compare/v4.24.0...v4.25.0) (2019-11-04)
### Features
* stop tracking googleapis/oauth2client ([#386](https://www.github.com/googleapis/sloth/issues/386)) ([7e0c39b](https://www.github.com/googleapis/sloth/commit/7e0c39b74be39a2fea6612440f7ef3fc5397a7ed))
## [4.24.0](https://www.github.com/googleapis/sloth/compare/v4.23.1...v4.24.0) (2019-10-31)
### Features
* add nodejs-cloudbuild ([#382](https://www.github.com/googleapis/sloth/issues/382)) ([3aa217e](https://www.github.com/googleapis/sloth/commit/3aa217efbfe2efbb0624207f8073a97f48e6af68))
* adding sofia to sloth users.json ([#378](https://www.github.com/googleapis/sloth/issues/378)) ([2ccff70](https://www.github.com/googleapis/sloth/commit/2ccff7059c917143d5e8c2cc151a29d0c1ec0150))
### Bug Fixes
* **deps:** update dependency @octokit/rest to v16.34.1 ([#384](https://www.github.com/googleapis/sloth/issues/384)) ([8bba2e6](https://www.github.com/googleapis/sloth/commit/8bba2e6dd1f3dcf1a46995938e1ce069f0c543c0))
### [4.23.1](https://www.github.com/googleapis/sloth/compare/v4.23.0...v4.23.1) (2019-10-24)
### Bug Fixes
* **deps:** update dependency @octokit/rest to v16.34.0 ([#374](https://www.github.com/googleapis/sloth/issues/374)) ([09f20a5](https://www.github.com/googleapis/sloth/commit/09f20a53aa9de2c448a3a5087d73154cba25b676))
* cpp issues to cpp team ([#376](https://www.github.com/googleapis/sloth/issues/376)) ([f0705d5](https://www.github.com/googleapis/sloth/commit/f0705d505dc12b6cbeac2421ad0be4a494c84bf0))
## [4.23.0](https://www.github.com/googleapis/sloth/compare/v4.22.0...v4.23.0) (2019-10-23)
### Features
* add cpp-docs-samples repo ([#372](https://www.github.com/googleapis/sloth/issues/372)) ([2831893](https://www.github.com/googleapis/sloth/commit/2831893b8ddaac57d125320dafaf607bcac9b295))
## [4.22.0](https://www.github.com/googleapis/sloth/compare/v4.21.0...v4.22.0) (2019-10-21)
### Features
* Add Chris, Frank to ruby repo ([#367](https://www.github.com/googleapis/sloth/issues/367)) ([0ca4b21](https://www.github.com/googleapis/sloth/commit/0ca4b21a13060891b02a963a69525f6df3911e9e))
## [4.21.0](https://www.github.com/googleapis/sloth/compare/v4.20.0...v4.21.0) (2019-10-17)
### Features
* add kokoro:run label ([#364](https://www.github.com/googleapis/sloth/issues/364)) ([a6545db](https://www.github.com/googleapis/sloth/commit/a6545dbb4297728bea6e595424a9cac16ac7857e))
## [4.20.0](https://www.github.com/googleapis/sloth/compare/v4.19.0...v4.20.0) (2019-10-16)
### Features
* move spanner to the spanner team ([#362](https://www.github.com/googleapis/sloth/issues/362)) ([9f740a5](https://www.github.com/googleapis/sloth/commit/9f740a579006aa374dde35e47bbf3d60d7bb3eb6))
## [4.19.0](https://www.github.com/googleapis/sloth/compare/v4.18.0...v4.19.0) (2019-10-14)
### Features
* add surferjeffatgoogle to Node.js and yoshi ([#359](https://www.github.com/googleapis/sloth/issues/359)) ([499a256](https://www.github.com/googleapis/sloth/commit/499a2562037f8f3dc87a6aed23bbef8bbb47db86))
## [4.18.0](https://www.github.com/googleapis/sloth/compare/v4.17.2...v4.18.0) (2019-10-12)
### Features
* Add new google-cloud-cpp-bigquery repository ([#356](https://www.github.com/googleapis/sloth/issues/356)) ([3efbe2c](https://www.github.com/googleapis/sloth/commit/3efbe2c72b38756e7d9faa915446108e343a043d))
### Bug Fixes
* add sneakybueno (esbueno@) - 20%er on Go ([#353](https://www.github.com/googleapis/sloth/issues/353)) ([ecb2834](https://www.github.com/googleapis/sloth/commit/ecb28343c3ee715004e78987d8c0dca0ff8ba914))
* **deps:** update dependency @octokit/rest to v16.33.1 ([#358](https://www.github.com/googleapis/sloth/issues/358)) ([8c939d9](https://www.github.com/googleapis/sloth/commit/8c939d91ba1aab9167c264804320cfbbb0989dee))
### [4.17.2](https://www.github.com/googleapis/sloth/compare/v4.17.1...v4.17.2) (2019-10-04)
### Bug Fixes
* assigned is not related to SLO ([#347](https://www.github.com/googleapis/sloth/issues/347)) ([e13c621](https://www.github.com/googleapis/sloth/commit/e13c621))
### [4.17.1](https://www.github.com/googleapis/sloth/compare/v4.17.0...v4.17.1) (2019-10-03)
### Bug Fixes
* use issue_number with octokit ([#345](https://www.github.com/googleapis/sloth/issues/345)) ([cf01397](https://www.github.com/googleapis/sloth/commit/cf01397))
## [4.17.0](https://www.github.com/googleapis/sloth/compare/v4.16.1...v4.17.0) (2019-10-03)
### Bug Fixes
* remove abhinav and paras ([#327](https://www.github.com/googleapis/sloth/issues/327)) ([1e1dfb3](https://www.github.com/googleapis/sloth/commit/1e1dfb3))
* update name of gapic csharp generator ([#329](https://www.github.com/googleapis/sloth/issues/329)) ([42431cc](https://www.github.com/googleapis/sloth/commit/42431cc))
* update users.json to include bradmiro ([#336](https://www.github.com/googleapis/sloth/issues/336)) ([7211409](https://www.github.com/googleapis/sloth/commit/7211409))
### Features
* add cloudbuild/recommender Java repos ([#337](https://www.github.com/googleapis/sloth/issues/337)) ([971a6b3](https://www.github.com/googleapis/sloth/commit/971a6b3))
* add new google-cloud-cpp-common repository ([#339](https://www.github.com/googleapis/sloth/issues/339)) ([3f47c14](https://www.github.com/googleapis/sloth/commit/3f47c14))
* add the onramp repos and team ([#343](https://www.github.com/googleapis/sloth/issues/343)) ([b993ec3](https://www.github.com/googleapis/sloth/commit/b993ec3))
### [4.16.1](https://www.github.com/googleapis/sloth/compare/v4.16.0...v4.16.1) (2019-09-16)
### Bug Fixes
* nodejs-proto-files belongs to actools ([#322](https://www.github.com/googleapis/sloth/issues/322)) ([beca95b](https://www.github.com/googleapis/sloth/commit/beca95b))
## [4.16.0](https://www.github.com/googleapis/sloth/compare/v4.15.0...v4.16.0) (2019-09-06)
### Features
* add codyoss to yoshi-java ([#317](https://www.github.com/googleapis/sloth/issues/317)) ([f07aae3](https://www.github.com/googleapis/sloth/commit/f07aae3))
* add Ilya, Cody, Aleksandra, and Chris to Go ([#319](https://www.github.com/googleapis/sloth/issues/319)) ([24f364e](https://www.github.com/googleapis/sloth/commit/24f364e))
* tweak SLO logic for customer issues ([#307](https://www.github.com/googleapis/sloth/issues/307)) ([a10014a](https://www.github.com/googleapis/sloth/commit/a10014a))
## [4.15.0](https://www.github.com/googleapis/sloth/compare/v4.14.1...v4.15.0) (2019-08-26)
### Bug Fixes
* clean up sloth repos ([#313](https://www.github.com/googleapis/sloth/issues/313)) ([f694f40](https://www.github.com/googleapis/sloth/commit/f694f40))
### Features
* add googleapis/cpp-cmakefiles repository ([#308](https://www.github.com/googleapis/sloth/issues/308)) ([f3d5ca2](https://www.github.com/googleapis/sloth/commit/f3d5ca2))
* add java split repos ([#312](https://www.github.com/googleapis/sloth/issues/312)) ([9a1f83d](https://www.github.com/googleapis/sloth/commit/9a1f83d))
### [4.14.1](https://www.github.com/googleapis/sloth/compare/v4.14.0...v4.14.1) (2019-08-01)
### Bug Fixes
* Add sirtorry to yoshi-python ([#305](https://www.github.com/googleapis/sloth/issues/305)) ([5515933](https://www.github.com/googleapis/sloth/commit/5515933))
## [4.14.0](https://www.github.com/googleapis/sloth/compare/v4.13.0...v4.14.0) (2019-07-29)
### Bug Fixes
* do not crash on error obtaining repo issues ([#300](https://www.github.com/googleapis/sloth/issues/300)) ([95f13ec](https://www.github.com/googleapis/sloth/commit/95f13ec))
### Features
* Add C++ team ([#282](https://www.github.com/googleapis/sloth/issues/282)) ([af1f0bf](https://www.github.com/googleapis/sloth/commit/af1f0bf))
## [4.13.0](https://www.github.com/googleapis/sloth/compare/v4.12.0...v4.13.0) (2019-07-26)
### Features
* add repo-automation-bots repo ([#297](https://www.github.com/googleapis/sloth/issues/297)) ([4adc5cb](https://www.github.com/googleapis/sloth/commit/4adc5cb))
## [4.12.0](https://www.github.com/googleapis/sloth/compare/v4.11.0...v4.12.0) (2019-07-17)
### Features
* Add [@elharo](https://www.github.com/elharo) to yoshi-java ([#295](https://www.github.com/googleapis/sloth/issues/295)) ([68ef46e](https://www.github.com/googleapis/sloth/commit/68ef46e))
## [4.11.0](https://www.github.com/googleapis/sloth/compare/v4.10.0...v4.11.0) (2019-07-10)
### Features
* ignore external issues from SLO ([#293](https://www.github.com/googleapis/sloth/issues/293)) ([dbfa009](https://www.github.com/googleapis/sloth/commit/dbfa009))
## [4.10.0](https://www.github.com/googleapis/sloth/compare/v4.9.0...v4.10.0) (2019-07-08)
### Features
* Add Storage and DB team members ([#288](https://www.github.com/googleapis/sloth/issues/288)) ([8d80017](https://www.github.com/googleapis/sloth/commit/8d80017))
## [4.9.0](https://www.github.com/googleapis/sloth/compare/v4.8.0...v4.9.0) (2019-07-08)
### Features
* update Qlogic users ([#286](https://www.github.com/googleapis/sloth/issues/286)) ([44e5f24](https://www.github.com/googleapis/sloth/commit/44e5f24))
## [4.8.0](https://www.github.com/googleapis/sloth/compare/v4.7.1...v4.8.0) (2019-07-03)
### Features
* remove SLO for PRs ([#283](https://www.github.com/googleapis/sloth/issues/283)) ([ab900a7](https://www.github.com/googleapis/sloth/commit/ab900a7))
### [4.7.1](https://www.github.com/googleapis/sloth/compare/v4.7.0...v4.7.1) (2019-06-28)
### Bug Fixes
* move ndb api to cbr team ([#277](https://www.github.com/googleapis/sloth/issues/277)) ([c8b362c](https://www.github.com/googleapis/sloth/commit/c8b362c))
## [4.7.0](https://www.github.com/googleapis/sloth/compare/v4.6.1...v4.7.0) (2019-06-27)
### Features
* add actools generator repos ([#272](https://www.github.com/googleapis/sloth/issues/272)) ([bdc4c7f](https://www.github.com/googleapis/sloth/commit/bdc4c7f))
### [4.6.1](https://www.github.com/googleapis/sloth/compare/v4.6.0...v4.6.1) (2019-06-26)
### Bug Fixes
* **docs:** make anchors work in jsdoc ([#270](https://www.github.com/googleapis/sloth/issues/270)) ([8daf382](https://www.github.com/googleapis/sloth/commit/8daf382))
## [4.6.0](https://www.github.com/googleapis/sloth/compare/v4.5.0...v4.6.0) (2019-06-17)
### Features
* add more team splitting ([#266](https://www.github.com/googleapis/sloth/issues/266)) ([fe124d5](https://www.github.com/googleapis/sloth/commit/fe124d5))
## [4.5.0](https://www.github.com/googleapis/sloth/compare/v4.4.0...v4.5.0) (2019-06-13)
### Features
* add datacatalog ([#264](https://www.github.com/googleapis/sloth/issues/264)) ([8331eda](https://www.github.com/googleapis/sloth/commit/8331eda))
## [4.4.0](https://www.github.com/googleapis/sloth/compare/v4.3.0...v4.4.0) (2019-06-10)
### Features
* include assignees in returned issue data ([#261](https://www.github.com/googleapis/sloth/issues/261)) ([66faa21](https://www.github.com/googleapis/sloth/commit/66faa21))
## [4.3.0](https://www.github.com/googleapis/sloth/compare/v4.2.1...v4.3.0) (2019-06-09)
### Bug Fixes
* update ownership of translation and ndb ([#260](https://www.github.com/googleapis/sloth/issues/260)) ([7e535ac](https://www.github.com/googleapis/sloth/commit/7e535ac))
### Features
* provide improved api mapping and teams ([#258](https://www.github.com/googleapis/sloth/issues/258)) ([d84e921](https://www.github.com/googleapis/sloth/commit/d84e921))
### [4.2.1](https://www.github.com/googleapis/sloth/compare/v4.2.0...v4.2.1) (2019-06-05)
### Bug Fixes
* check for assignees ([#253](https://www.github.com/googleapis/sloth/issues/253)) ([07d4bdb](https://www.github.com/googleapis/sloth/commit/07d4bdb))
## [4.2.0](https://www.github.com/googleapis/sloth/compare/v4.1.0...v4.2.0) (2019-05-29)
### Bug Fixes
* bump minimim version ([#244](https://www.github.com/googleapis/sloth/issues/244)) ([401aefa](https://www.github.com/googleapis/sloth/commit/401aefa))
### Features
* remove labels we do not want ([#245](https://www.github.com/googleapis/sloth/issues/245)) ([3b9c046](https://www.github.com/googleapis/sloth/commit/3b9c046))
## [4.1.0](https://www.github.com/googleapis/sloth/compare/v4.0.1...v4.1.0) (2019-05-23)
### Features
* add phishing protection ([#238](https://www.github.com/googleapis/sloth/issues/238)) ([e50481e](https://www.github.com/googleapis/sloth/commit/e50481e))
### [4.0.1](https://www.github.com/googleapis/sloth/compare/v4.0.0...v4.0.1) (2019-05-20)
### Bug Fixes
* **deps:** update dependency update-notifier to v3 ([#227](https://www.github.com/googleapis/sloth/issues/227)) ([34fb1a6](https://www.github.com/googleapis/sloth/commit/34fb1a6))
* check for unknown priority ([#233](https://www.github.com/googleapis/sloth/issues/233)) ([956d2f7](https://www.github.com/googleapis/sloth/commit/956d2f7))
* remove suprious log ([#230](https://www.github.com/googleapis/sloth/issues/230)) ([cf361b0](https://www.github.com/googleapis/sloth/commit/cf361b0))
* use issue_number for tag issues ([#236](https://www.github.com/googleapis/sloth/issues/236)) ([2fcb920](https://www.github.com/googleapis/sloth/commit/2fcb920))
* use the drift prod enpoint ([#229](https://www.github.com/googleapis/sloth/issues/229)) ([e20e160](https://www.github.com/googleapis/sloth/commit/e20e160))
## [4.0.0](https://www.github.com/googleapis/sloth/compare/v3.0.0...v4.0.0) (2019-05-03)
### Build System
* upgrade engines field to >=8.10.0 ([#216](https://www.github.com/googleapis/sloth/issues/216)) ([3135d04](https://www.github.com/googleapis/sloth/commit/3135d04))
### BREAKING CHANGES
* upgrade engines field to >=8.10.0 (#216)
## v3.0.0
03-28-2019 12:40 PDT
- Add alixhami to python ([#200](https://github.com/googleapis/sloth/pull/200))
- Adding Seth and Tim ([#199](https://github.com/googleapis/sloth/pull/199))
- Add Peter Lamut to yoshi-python ([#197](https://github.com/googleapis/sloth/pull/197))
- Add andreamlin to yoshi-java ([#196](https://github.com/googleapis/sloth/pull/196))
- add Emmanuel to Go ([#194](https://github.com/googleapis/sloth/pull/194))
- chore: publish to npm using wombat ([#192](https://github.com/googleapis/sloth/pull/192))
- build: use per-repo publish token ([#189](https://github.com/googleapis/sloth/pull/189))
- Added andrei-semeniuk to yoshi team ([#190](https://github.com/googleapis/sloth/pull/190))
- Add googleapis/google-auth-library-python-oauthlib to repos ([#188](https://github.com/googleapis/sloth/pull/188))
- chore: add bcoe to ruby, python, node.js, cpp ([#187](https://github.com/googleapis/sloth/pull/187))
- chore: remove GoogleCloudPlatform org ([#186](https://github.com/googleapis/sloth/pull/186))
- Adding olavloite to the java team ([#185](https://github.com/googleapis/sloth/pull/185))
- Fix users.json ([#184](https://github.com/googleapis/sloth/pull/184))
- Moving cloud-bigtable-client to googleapis ([#182](https://github.com/googleapis/sloth/pull/182))
- build: Add docuploader credentials to node publish jobs ([#181](https://github.com/googleapis/sloth/pull/181))
- build: update release config ([#178](https://github.com/googleapis/sloth/pull/178))
- build: use node10 to run samples-test, system-test etc ([#180](https://github.com/googleapis/sloth/pull/180))
- Add docuploader repository. ([#179](https://github.com/googleapis/sloth/pull/179))
- fix: update changed username and fix json
- update users ([#176](https://github.com/googleapis/sloth/pull/176))
- Adding dpcollins, removing dhermes ([#175](https://github.com/googleapis/sloth/pull/175))
- chore(deps): update dependency mocha to v6 ([#173](https://github.com/googleapis/sloth/pull/173))
- Add the GoogleCloudPlatform/cloud-bigtable-client repo ([#172](https://github.com/googleapis/sloth/pull/172))
- build: use linkinator for docs test ([#169](https://github.com/googleapis/sloth/pull/169))
- docs: update links in contrib guide ([#171](https://github.com/googleapis/sloth/pull/171))
- Update yoshi-cpp members. ([#170](https://github.com/googleapis/sloth/pull/170))
- Add the nodejs-precise-date repo ([#168](https://github.com/googleapis/sloth/pull/168))
- feat: add nodejs-irm and -talent to repos.json ([#167](https://github.com/googleapis/sloth/pull/167))
- build: create docs test npm scripts ([#166](https://github.com/googleapis/sloth/pull/166))
- build: test using @grpc/grpc-js in CI ([#165](https://github.com/googleapis/sloth/pull/165))
- fix: exclude blocked PRs from SLO ([#164](https://github.com/googleapis/sloth/pull/164))
- docs: update contributing guide ([#163](https://github.com/googleapis/sloth/pull/163))
- feat: add an SLO for PRs ([#161](https://github.com/googleapis/sloth/pull/161))
- Remove the profiler-go team and use api-profiler ([#160](https://github.com/googleapis/sloth/pull/160))
- docs: add lint/fix example to contributing guide ([#157](https://github.com/googleapis/sloth/pull/157))
- add new team for profiler folks working on Go ([#156](https://github.com/googleapis/sloth/pull/156))
- Update users and urls for cpp ([#155](https://github.com/googleapis/sloth/pull/155))
- Add irm and talent PHP repos ([#154](https://github.com/googleapis/sloth/pull/154))
- Add autoML PHP repo ([#153](https://github.com/googleapis/sloth/pull/153))
- remove enocom@ ([#152](https://github.com/googleapis/sloth/pull/152))
- Removing dups from users.json ([#151](https://github.com/googleapis/sloth/pull/151))
- Sorting values in repos.json and users.json ([#150](https://github.com/googleapis/sloth/pull/150))
- Add google-cloud-cpp project ([#148](https://github.com/googleapis/sloth/pull/148))
- build: ignore googleapis.com in doc link check ([#147](https://github.com/googleapis/sloth/pull/147))
- fix: use latest auth method for octokit ([#146](https://github.com/googleapis/sloth/pull/146))
- Add Kokoro job to tag issues ([#144](https://github.com/googleapis/sloth/pull/144))
- Syncing repos.json and users.json ([#143](https://github.com/googleapis/sloth/pull/143))
- Removing mattwhisenhunt from users.json ([#142](https://github.com/googleapis/sloth/pull/142))
- build: check for 404s in the docs. ([#139](https://github.com/googleapis/sloth/pull/139))
- docs: generate some docs ([#140](https://github.com/googleapis/sloth/pull/140))
- Add scheduler to list of PHP repos ([#138](https://github.com/googleapis/sloth/pull/138))
- add cguardia to the python team ([#135](https://github.com/googleapis/sloth/pull/135))
- add billy jacobson ([#136](https://github.com/googleapis/sloth/pull/136))
- add Daniel Sims to yoshi-php ([#133](https://github.com/googleapis/sloth/pull/133))
- fix: fix the build ([#134](https://github.com/googleapis/sloth/pull/134))
- Allow yoshi-php access to PHP sub-repos ([#131](https://github.com/googleapis/sloth/pull/131))
- add seth and noah for Go reviews and issues ([#130](https://github.com/googleapis/sloth/pull/130))
- feat: add ability to search for many apis ([#129](https://github.com/googleapis/sloth/pull/129))
- chore: update users ([#121](https://github.com/googleapis/sloth/pull/121))
- chore(build): inject yoshi automation key ([#128](https://github.com/googleapis/sloth/pull/128))
- chore: update nyc and eslint configs ([#127](https://github.com/googleapis/sloth/pull/127))
- chore: fix publish.sh permission +x ([#125](https://github.com/googleapis/sloth/pull/125))
- fix(build): fix Kokoro release script ([#124](https://github.com/googleapis/sloth/pull/124))
- build: add Kokoro configs for autorelease ([#123](https://github.com/googleapis/sloth/pull/123))
## v2.1.2
12-07-2018 11:20 PST
- Add googleapis/google-resumable-media-python repository ([#118](https://github.com/googleapis/sloth/pull/118))
- add frankyn to yoshi-go ([#115](https://github.com/googleapis/sloth/pull/115))
- chore: always nyc report before calling codecov ([#114](https://github.com/googleapis/sloth/pull/114))
- chore: nyc ignore build/test by default ([#113](https://github.com/googleapis/sloth/pull/113))
- Add bshaffer to yoshi-php ([#112](https://github.com/googleapis/sloth/pull/112))
- chore(build): update common templates ([#110](https://github.com/googleapis/sloth/pull/110))
- Add andrey-qlogic to yoshi-java ([#109](https://github.com/googleapis/sloth/pull/109))
- Adding andrewsg to yoshi-python ([#108](https://github.com/googleapis/sloth/pull/108))
- chore: update license file ([#106](https://github.com/googleapis/sloth/pull/106))
- fix: update the repository location in package.json ([#102](https://github.com/googleapis/sloth/pull/102))
- Add kolea2 to yoshi and yoshi-java. ([#103](https://github.com/googleapis/sloth/pull/103))
## v2.1.1
12-03-2018 08:52 PST
- fix: fix the linter ([#100](https://github.com/googleapis/sloth/pull/100))
- fix: allow passing multiple types ([#98](https://github.com/googleapis/sloth/pull/98))
- fix(build): fix system key decryption ([#96](https://github.com/googleapis/sloth/pull/96))
- Update list of repos
- Add extended Go devrel community to yoshi-go, so that they can do reviews ([#95](https://github.com/googleapis/sloth/pull/95))
- Add yoshi-kokoro as admin ([#94](https://github.com/googleapis/sloth/pull/94))
- add help wanted, good first issue labels ([#93](https://github.com/googleapis/sloth/pull/93))
- test: add tests to verify json configs are valid ([#92](https://github.com/googleapis/sloth/pull/92))
- Remove jba, dpebot, update nodejs repos ([#90](https://github.com/googleapis/sloth/pull/90))
- Add nodejs-security-center and nodejs-scheduler to repos.json ([#89](https://github.com/googleapis/sloth/pull/89))
- fix(deps): update dependency @octokit/rest to v16 ([#87](https://github.com/googleapis/sloth/pull/87))
- chore: add a synth.metadata
## v2.2.0
12-03-2018 08:44 PST
- fix: allow passing multiple types ([#98](https://github.com/googleapis/sloth/pull/98))
- fix(build): fix system key decryption ([#96](https://github.com/googleapis/sloth/pull/96))
- Update list of repos
- Add extended Go devrel community to yoshi-go, so that they can do reviews ([#95](https://github.com/googleapis/sloth/pull/95))
- Add yoshi-kokoro as admin ([#94](https://github.com/googleapis/sloth/pull/94))
- add help wanted, good first issue labels ([#93](https://github.com/googleapis/sloth/pull/93))
- test: add tests to verify json configs are valid ([#92](https://github.com/googleapis/sloth/pull/92))
- Remove jba, dpebot, update nodejs repos ([#90](https://github.com/googleapis/sloth/pull/90))
- Add nodejs-security-center and nodejs-scheduler to repos.json ([#89](https://github.com/googleapis/sloth/pull/89))
- fix(deps): update dependency @octokit/rest to v16 ([#87](https://github.com/googleapis/sloth/pull/87))
- chore: add a synth.metadata
## v2.1.0
### Implementation Changes
- add Q-Logic folks to the java team ([#84](https://github.com/GoogleCloudPlatform/sloth/pull/84))
- chore(deps): update dependency gts to ^0.9.0 ([#83](https://github.com/GoogleCloudPlatform/sloth/pull/83))
- chore: update eslintignore config ([#81](https://github.com/GoogleCloudPlatform/sloth/pull/81))
- feat: add ability to filter by type ([#77](https://github.com/GoogleCloudPlatform/sloth/pull/77))
- chore: use latest npm on Windows ([#80](https://github.com/GoogleCloudPlatform/sloth/pull/80))
- Add yoshi-automation to yoshi-admins ([#79](https://github.com/GoogleCloudPlatform/sloth/pull/79))
- Remove beckwith from most teams ([#78](https://github.com/GoogleCloudPlatform/sloth/pull/78))
- chore(build): ignore build/ in eslint config ([#74](https://github.com/GoogleCloudPlatform/sloth/pull/74))
- fix: repair busted users.json ([#75](https://github.com/GoogleCloudPlatform/sloth/pull/75))
- Adding QLogic java and node devs ([#71](https://github.com/GoogleCloudPlatform/sloth/pull/71))
- chore: update CircleCI config ([#73](https://github.com/GoogleCloudPlatform/sloth/pull/73))
- fix: use csv-string package to format --csv output ([#69](https://github.com/GoogleCloudPlatform/sloth/pull/69))
- chore: update issue templates ([#64](https://github.com/GoogleCloudPlatform/sloth/pull/64))
- chore: remove old issue template ([#62](https://github.com/GoogleCloudPlatform/sloth/pull/62))
- chore(deps): update dependency typescript to v3 ([#59](https://github.com/GoogleCloudPlatform/sloth/pull/59))
- build: run tests on node11 ([#61](https://github.com/GoogleCloudPlatform/sloth/pull/61))
- chore(deps): update dependency @types/meow to v5 ([#58](https://github.com/GoogleCloudPlatform/sloth/pull/58))
- chores(build): run codecov on continuous builds ([#54](https://github.com/GoogleCloudPlatform/sloth/pull/54))
| googleapis/sloth | CHANGELOG.md | Markdown | apache-2.0 | 89,212 |
package org.slc.sli.context;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import org.springframework.context.ApplicationContext;
/**
* HTTPRequestFilter.java
*
* Purpose: This filter intercepts all the request coming from url
* /api/secure/jsonws/* and stores the httprequest object to the
* HTTPRequestHolder class. since the url of the server which is firing the
* webservice cannot be found in the implementation classs. this filter is used
* to get the server url
*
* @author
* @version 1.0
*/
public class HTTPRequestFilter implements Filter {
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
ApplicationContext ctx = AppContext.getApplicationContext();
HTTPRequestHolder httpRequestHolder = (HTTPRequestHolder) ctx
.getBean("httpRequestHolder");
httpRequestHolder.setHttpServletRequest(request);
chain.doFilter(req, res);
}
public void init(FilterConfig config) throws ServletException {
// Get init parameter
String testParam = config.getInitParameter("test-param");
}
public void destroy() {
// add code to release any resource
}
} | inbloom/datastore-portal | portlets/headerfooter-portlet/docroot/WEB-INF/src/org/slc/sli/context/HTTPRequestFilter.java | Java | apache-2.0 | 1,461 |
package dh.algorithms.classification.kmeans;
import dh.algorithms.classification.ClassificationModel;
import dh.data.column.special.NominalDataColumn;
import dh.repository.Table;
public class KMeansModel extends ClassificationModel {
private static final long serialVersionUID = 1L;
String[] columnNames;
boolean[] targets;
String[][] centerLabels;
public KMeansModel(NominalDataColumn[] columns, int[][] centers, boolean[] targets) {
columnNames = new String[columns.length];
for (int i = 0; i < columns.length; ++i) {
columnNames[i] = columns[i].getName();
}
centerLabels = new String[centers.length][];
for (int i = 0; i < centerLabels.length; ++i) {
centerLabels[i] = new String[centers[i].length];
for (int j = 0; j < centers[i].length; ++j) {
centerLabels[i][j] = columns[j].getReverseMapping().get(centers[i][j]);
}
}
this.targets = new boolean[targets.length];
for (int i = 0; i < targets.length; ++i) {
this.targets[i] = targets[i];
}
}
@Override
public void apply(Table table) {
boolean[] prediction = getPredictionData(table);
double[] numericPrediction = getNumericPredictionData(table);
int[][] centers = new int[centerLabels.length][];
int[][] data = new int[columnNames.length][];
for (int i = 0; i < centers.length; ++i) {
centers[i] = new int[columnNames.length];
}
for (int i = 0; i < columnNames.length; ++i) {
NominalDataColumn column = table.getColumn(columnNames[i]);
data[i] = column.getData();
for (int j = 0; j < centers.length; ++j) {
centers[j][i] = column.getMapping().get(centerLabels[j][i]);
}
}
int[] row = new int[columnNames.length];
for (int i = 0; i < table.getSize(); ++i) {
for (int j = 0; j < data.length; ++j) {
row[j] = data[j][i];
}
int maxSimilarity = Integer.MIN_VALUE;
int group = -1;
for (int j = 0; j < centers.length; ++j) {
int sim = calculateSimilarity(centers[j], row);
if (sim > maxSimilarity) {
maxSimilarity = sim;
group = j;
}
}
if (targets[group]) {
prediction[i] = true;
numericPrediction[i] = 1.0;
} else {
prediction[i] = false;
numericPrediction[i] = 0.0;
}
}
}
private int calculateSimilarity(int[] e1, int[] e2) {
int sim = 0;
for (int i = 0; i < e1.length; ++i) {
if (e1[i] == e2[i]) {
++sim;
}
}
return sim;
}
}
| gabormakrai/datahammer | src/dh/algorithms/classification/kmeans/KMeansModel.java | Java | apache-2.0 | 2,368 |
#noti_Container {
position:relative;
}
/* A CIRCLE LIKE BUTTON IN THE TOP MENU. */
#noti_Button {
width:43px;
height:43px;
line-height:77px;
-moz-border-radius:50%;
-webkit-border-radius:50%;
/*background:#FFF;*/
background-image:url('/img/vslow.gif');
border-style:none;
background-color:transparent !important;
margin:5px 10px 0 10px;
cursor:pointer;
}
/* THE POPULAR RED NOTIFICATIONS COUNTER. */
#noti_Counter {
display:block;
position:absolute;
background:#E1141E;
color:#FFF;
font-size:12px;
font-weight:normal;
padding:3px 3px;
margin:20px 0 0 24px;
border-radius:2px;
-moz-border-radius:2px;
-webkit-border-radius:2px;
z-index:1;
}
/* THE NOTIFICAIONS WINDOW. THIS REMAINS HIDDEN WHEN THE PAGE LOADS. */
#notifications1 {
display:none;
width:430px;
height:200px;
position:absolute;
top:45px;
left:-170px;
background:#FFF;
border:solid 1px rgba(100, 100, 100, .20);
-webkit-box-shadow:0 3px 8px rgba(0, 0, 0, .20);
z-index: 0;
}
/* AN ARROW LIKE STRUCTURE JUST OVER THE NOTIFICATIONS WINDOW */
#notifications1:before {
content: '';
display:block;
width:0;
height:0;
color:transparent;
border:10px solid #CCC;
border-color:transparent transparent #FFF;
margin-top:-18px;
margin-left:180px;
}
@media screen and (Max-width: 770px) {
#notifications1 {
display:none;
width:200px;
height:200px;
position:absolute;
top:55px;
left:25px;
background:#FFF;
border:solid 1px rgba(100, 100, 100, .20);
-webkit-box-shadow:0 3px 8px rgba(0, 0, 0, .20);
z-index: 0;
}
#notifications1:before {
content: '';
display:block;
width:0;
height:0;
color:transparent;
border:10px solid #CCC;
border-color:transparent transparent #FFF;
margin-top:-20px;
margin-left:5px;
}
}
/*h3 {
display:block;
color:#333;
background:#FFF;
font-weight:bold;
font-size:13px;
padding:8px;
margin:0;
border-bottom:solid 1px rgba(100, 100, 100, .30);
}*/
.seeAll {
background:#F6F7F8;
padding:8px;
font-size:12px;
font-weight:bold;
border-top:solid 1px rgba(100, 100, 100, .30);
text-align:center;
}
.seeAll a {
color:#3b5998;
}
.seeAll a:hover {
background:#F6F7F8;
color:#3b5998;
text-decoration:underline;
} | Ruke45/DManagement | DSCMS/DSCMS/css/notification.css | CSS | apache-2.0 | 2,893 |
/**
* Copyright 2017 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
const glob = require('glob');
const fs = require('fs');
const path = require('path');
const mkdirp = require('mkdirp');
const ampOptimizer = require('amp-toolbox-optimizer');
const runtimeVersion = require('amp-toolbox-runtime-version');
// Transformers are easy to implement and integrate
class CustomTransformer {
transform(tree /* optional: ', params' */) {
const html = tree.root.firstChildByTag('html');
if (!html) return;
const head = html.firstChildByTag('head');
if (!head) return;
const desc = tree.createElement('meta', {
name: 'description',
content: 'this is just a demo'
});
head.appendChild(desc);
}
}
// Configure the transformers to be used.
// otherwise a default configuration is used.
ampOptimizer.setConfig({
transformers: [
new CustomTransformer(),
'AddAmpLink',
'ServerSideRendering',
'RemoveAmpAttribute',
// needs to run after ServerSideRendering
'AmpBoilerplateTransformer',
// needs to run after ServerSideRendering
'ReorderHeadTransformer',
// needs to run after ReorderHeadTransformer
'RewriteAmpUrls'
]
});
const SRC_DIR = 'src';
const DIST_DIR = 'dist';
runAmpOptimizerTransformations();
async function runAmpOptimizerTransformations() {
// This is optional in case AMP runtime URLs should be versioned
const ampRuntimeVersion = await runtimeVersion.currentVersion();
console.log('amp version: ', ampRuntimeVersion);
// Collect input files and invoke the transformers
const files = await collectInputFiles('/**/*.html');
files.forEach(file => copyAndTransform(file, ampRuntimeVersion));
}
// Collect all files in the src dir.
function collectInputFiles(pattern) {
return new Promise((resolve, reject) => {
glob(pattern, {root: SRC_DIR, nomount: true}, (err, files) => {
if (err) {
return reject(err);
}
resolve(files);
});
});
}
// Copy original and transformed AMP file into the dist dir.
async function copyAndTransform(file, ampRuntimeVersion) {
const originalHtml = await readFile(file);
const ampFile = file.substring(1, file.length)
.replace('.html', '.amp.html');
// The transformer needs the path to the original AMP document
// to correctly setup AMP to canonical linking
const optimizedHtml = await ampOptimizer.transformHtml(originalHtml, {
ampUrl: ampFile,
ampRuntimeVersion: ampRuntimeVersion
});
// We change the path of the original AMP file to match the new
// amphtml link and make the canonical link point to the transformed version.
writeFile(ampFile, originalHtml);
writeFile(file, optimizedHtml);
}
function readFile(fileName) {
return new Promise((resolve, reject) => {
fs.readFile(path.join(SRC_DIR, fileName), 'utf8', (err, contents) => {
if (err) {
return reject(err);
}
resolve(contents);
});
});
}
function writeFile(filePath, content) {
filePath = path.join(DIST_DIR, filePath);
mkdirp(path.dirname(filePath), err => {
if (err) {
throw err;
}
fs.writeFile(filePath, content, err => {
if (err) {
throw err;
}
});
});
}
| google/amp-toolbox | optimizer/demo/simple/index.js | JavaScript | apache-2.0 | 3,789 |
import * as utils from 'src/utils';
import * as url from 'src/url';
import {registerBidder} from 'src/adapters/bidderFactory';
import {NATIVE, VIDEO} from 'src/mediaTypes';
/**
* Adapter for requesting bids from adxcg.net
* updated to latest prebid repo on 2017.10.20
*/
const BIDDER_CODE = 'adxcg';
const SUPPORTED_AD_TYPES = [VIDEO, NATIVE];
const SOURCE = 'pbjs10';
export const spec = {
code: BIDDER_CODE,
supportedMediaTypes: SUPPORTED_AD_TYPES,
/**
* Determines whether or not the given bid request is valid.
*
* @param {object} bid The bid params to validate.
* @return boolean True if this is a valid bid, and false otherwise.
*/
isBidRequestValid: function (bid) {
return !!(bid.params.adzoneid);
},
/**
* Make a server request from the list of BidRequests.
*
* an array of validBidRequests
* Info describing the request to the server.
*/
buildRequests: function (validBidRequests, bidderRequest) {
utils.logMessage(`buildRequests: ${JSON.stringify(validBidRequests)}`);
let adZoneIds = [];
let prebidBidIds = [];
let sizes = [];
validBidRequests.forEach(bid => {
adZoneIds.push(utils.getBidIdParameter('adzoneid', bid.params));
prebidBidIds.push(bid.bidId);
sizes.push(utils.parseSizesInput(bid.sizes).join('|'));
});
let location = utils.getTopWindowLocation();
let secure = location.protocol === 'https:';
let requestUrl = url.parse(location.href);
requestUrl.search = null;
requestUrl.hash = null;
let adxcgRequestUrl = url.format({
protocol: secure ? 'https' : 'http',
hostname: secure ? 'hbps.adxcg.net' : 'hbp.adxcg.net',
pathname: '/get/adi',
search: {
renderformat: 'javascript',
ver: 'r20171102PB10',
adzoneid: adZoneIds.join(','),
format: sizes.join(','),
prebidBidIds: prebidBidIds.join(','),
url: encodeURIComponent(url.format(requestUrl)),
secure: secure ? '1' : '0',
source: SOURCE,
pbjs: '$prebid.version$'
}
});
return {
method: 'GET',
url: adxcgRequestUrl,
};
},
/**
* Unpack the response from the server into a list of bids.
*
* @param {*} serverResponse A successful response from the server.
* @return {bidRequests[]} An array of bids which were nested inside the server.
*/
interpretResponse: function (serverResponse, bidRequests) {
let bids = [];
serverResponse = serverResponse.body;
if (serverResponse) {
serverResponse.forEach(serverResponseOneItem => {
let bid = {};
bid.requestId = serverResponseOneItem.bidId;
bid.cpm = serverResponseOneItem.cpm;
bid.creativeId = parseInt(serverResponseOneItem.creativeId);
bid.currency = serverResponseOneItem.currency ? serverResponseOneItem.currency : 'USD';
bid.netRevenue = serverResponseOneItem.netRevenue ? serverResponseOneItem.netRevenue : true;
bid.ttl = serverResponseOneItem.ttl ? serverResponseOneItem.ttl : 300;
if (serverResponseOneItem.deal_id != null && serverResponseOneItem.deal_id.trim().length > 0) {
bid.dealId = serverResponseOneItem.deal_id;
}
if (serverResponseOneItem.ad) {
bid.ad = serverResponseOneItem.ad;
} else if (serverResponseOneItem.vastUrl) {
bid.vastUrl = serverResponseOneItem.vastUrl;
bid.mediaType = 'video';
} else if (serverResponseOneItem.nativeResponse) {
bid.mediaType = 'native';
let nativeResponse = serverResponseOneItem.nativeResponse;
bid['native'] = {
clickUrl: encodeURIComponent(nativeResponse.link.url),
impressionTrackers: nativeResponse.imptrackers
};
nativeResponse.assets.forEach(asset => {
if (asset.title && asset.title.text) {
bid['native'].title = asset.title.text;
}
if (asset.img && asset.img.url) {
bid['native'].image = asset.img.url;
}
if (asset.data && asset.data.label === 'DESC' && asset.data.value) {
bid['native'].body = asset.data.value;
}
if (asset.data && asset.data.label === 'SPONSORED' && asset.data.value) {
bid['native'].sponsoredBy = asset.data.value;
}
});
}
bid.width = serverResponseOneItem.width;
bid.height = serverResponseOneItem.height;
utils.logMessage(`submitting bid[${serverResponseOneItem.bidId}]: ${JSON.stringify(bid)}`);
bids.push(bid);
});
} else {
utils.logMessage(`empty bid response`);
}
return bids;
},
getUserSyncs: function (syncOptions) {
if (syncOptions.iframeEnabled) {
return [{
type: 'iframe',
url: '//cdn.adxcg.net/pb-sync.html'
}];
}
}
};
registerBidder(spec);
| atomx/Prebid.js | modules/adxcgBidAdapter.js | JavaScript | apache-2.0 | 4,925 |
var nearby = function(){
navigator.geolocation.getCurrentPosition(
// success
highlight
// error
,function(position){
console.log('Error occurred. Error code: ' + error.code);
}
);
}
var highlight = function(currentPosition, types){
if (!types)
types = ['car_dealer', 'car_rental', 'car_repair', 'car_wash', 'gas_station'];
var request = {
location: new google.maps.LatLng(currentPosition.coords.latitude, currentPosition.coords.longitude)
,rankBy: google.maps.places.RankBy.DISTANCE
,types: types
}
placesService.nearbySearch(request, onNearbyFound);
}
var onNearbyFound = function(results, status){
setAllMap(null);
if (status == google.maps.places.PlacesServiceStatus.OK){
for (var i=0; i<results.length; i++){
var place = results[i];
createMarker(results[i]);
}
}
}
var createMarker = function(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function(){
new google.maps.InfoWindow({
content: place.name
}).open(map, marker);
});
markers.push(marker);
};
var getDetails = function(result){
placesService.getDetails({reference: result.reference});
} | tiefenauer/dudewheresmycar | app/scripts/nearby.js | JavaScript | apache-2.0 | 1,280 |
# encoding: UTF-8
#
# Cookbook Name:: system
# Resource:: environment
#
# Copyright 2012-2015, Chris Fordham
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
actions [:configure]
default_action :configure
attribute :filename,
name_attribute: true,
kind_of: String,
default: '/etc/environment'
attribute :extra,
kind_of: Hash,
default: nil
| crossroads/system | resources/environment.rb | Ruby | apache-2.0 | 889 |
package mesosphere.marathon
package api.v2
import javax.inject.Inject
import javax.servlet.http.HttpServletRequest
import javax.ws.rs._
import javax.ws.rs.container.{AsyncResponse, Suspended}
import javax.ws.rs.core.{Context, MediaType}
import mesosphere.marathon.api.EndpointsHelper.ListTasks
import mesosphere.marathon.api._
import mesosphere.marathon.core.appinfo.EnrichedTask
import scala.concurrent.ExecutionContext
import mesosphere.marathon.core.group.GroupManager
import mesosphere.marathon.core.health.HealthCheckManager
import mesosphere.marathon.core.instance.Instance
import mesosphere.marathon.core.task.Task
import mesosphere.marathon.core.task.tracker.InstanceTracker
import mesosphere.marathon.core.task.tracker.InstanceTracker.InstancesBySpec
import mesosphere.marathon.plugin.auth._
import mesosphere.marathon.raml.AnyToRaml
import mesosphere.marathon.raml.Task._
import mesosphere.marathon.raml.TaskConversion._
import mesosphere.marathon.state.PathId
import mesosphere.marathon.state.PathId._
import mesosphere.marathon.util.toRichFuture
import scala.async.Async._
import scala.concurrent.Future
import scala.util.{Failure, Success}
@Consumes(Array(MediaType.APPLICATION_JSON))
@Produces(Array(MediaType.APPLICATION_JSON))
class AppTasksResource @Inject() (
instanceTracker: InstanceTracker,
taskKiller: TaskKiller,
healthCheckManager: HealthCheckManager,
val config: MarathonConf,
groupManager: GroupManager,
val authorizer: Authorizer,
val authenticator: Authenticator)(implicit val executionContext: ExecutionContext) extends AuthResource {
val GroupTasks = """^((?:.+/)|)\*$""".r
@GET
def indexJson(
@PathParam("appId") id: String,
@Context req: HttpServletRequest, @Suspended asyncResponse: AsyncResponse): Unit = sendResponse(asyncResponse) {
async {
implicit val identity = await(authenticatedAsync(req))
val instancesBySpec = await(instanceTracker.instancesBySpec)
id match {
case GroupTasks(gid) =>
val groupPath = gid.toRootPath
val maybeGroup = groupManager.group(groupPath)
await(withAuthorization(ViewGroup, maybeGroup, Future.successful(unknownGroup(groupPath))) { group =>
async {
val tasks = await(runningTasks(group.transitiveAppIds, instancesBySpec)).toRaml
ok(jsonObjString("tasks" -> tasks))
}
})
case _ =>
val appId = id.toRootPath
val maybeApp = groupManager.app(appId)
val tasks = await(runningTasks(Set(appId), instancesBySpec)).toRaml
withAuthorization(ViewRunSpec, maybeApp, unknownApp(appId)) { _ =>
ok(jsonObjString("tasks" -> tasks))
}
}
}
}
def runningTasks(appIds: Iterable[PathId], instancesBySpec: InstancesBySpec): Future[Vector[EnrichedTask]] = {
Future.sequence(appIds.withFilter(instancesBySpec.hasSpecInstances).map { id =>
async {
val health = await(healthCheckManager.statuses(id))
instancesBySpec.specInstances(id).flatMap { i =>
EnrichedTask.fromInstance(i, healthCheckResults = health.getOrElse(i.instanceId, Nil))
}
}
}).map(_.iterator.flatten.toVector)
}
@GET
@Produces(Array(RestResource.TEXT_PLAIN_LOW))
def indexTxt(
@PathParam("appId") appId: String,
@Context req: HttpServletRequest, @Suspended asyncResponse: AsyncResponse): Unit = sendResponse(asyncResponse) {
async {
implicit val identity = await(authenticatedAsync(req))
val id = appId.toRootPath
val instancesBySpec = await(instanceTracker.instancesBySpec)
withAuthorization(ViewRunSpec, groupManager.app(id), unknownApp(id)) { app =>
ok(EndpointsHelper.appsToEndpointString(ListTasks(instancesBySpec, Seq(app))))
}
}
}
@DELETE
def deleteMany(
@PathParam("appId") appId: String,
@QueryParam("host") host: String,
@QueryParam("scale")@DefaultValue("false") scale: Boolean = false,
@QueryParam("force")@DefaultValue("false") force: Boolean = false,
@QueryParam("wipe")@DefaultValue("false") wipe: Boolean = false,
@Context req: HttpServletRequest, @Suspended asyncResponse: AsyncResponse): Unit = sendResponse(asyncResponse) {
async {
implicit val identity = await(authenticatedAsync(req))
val pathId = appId.toRootPath
def findToKill(appTasks: Seq[Instance]): Seq[Instance] = {
Option(host).fold(appTasks) { hostname =>
appTasks.filter(_.hostname.contains(hostname) || hostname == "*")
}
}
if (scale && wipe) throw new BadRequestException("You cannot use scale and wipe at the same time.")
if (scale) {
val deploymentF = taskKiller.killAndScale(pathId, findToKill, force)
deploymentResult(await(deploymentF))
} else {
await(taskKiller.kill(pathId, findToKill, wipe).asTry) match {
case Success(instances) =>
val healthStatuses = await(healthCheckManager.statuses(pathId))
val enrichedTasks: Seq[EnrichedTask] = instances.flatMap { i =>
EnrichedTask.singleFromInstance(i, healthCheckResults = healthStatuses.getOrElse(i.instanceId, Nil))
}
ok(jsonObjString("tasks" -> enrichedTasks.toRaml))
case Failure(PathNotFoundException(appId, version)) => unknownApp(appId, version)
}
}
}
}
@DELETE
@Path("{taskId}")
def deleteOne(
@PathParam("appId") appId: String,
@PathParam("taskId") id: String,
@QueryParam("scale")@DefaultValue("false") scale: Boolean = false,
@QueryParam("force")@DefaultValue("false") force: Boolean = false,
@QueryParam("wipe")@DefaultValue("false") wipe: Boolean = false,
@Context req: HttpServletRequest, @Suspended asyncResponse: AsyncResponse): Unit = sendResponse(asyncResponse) {
async {
implicit val identity = await(authenticatedAsync(req))
val pathId = appId.toRootPath
def findToKill(appTasks: Seq[Instance]): Seq[Instance] = {
try {
val instanceId = Task.Id.parse(id).instanceId
appTasks.filter(_.instanceId == instanceId)
} catch {
// the id can not be translated to an instanceId
case _: MatchError => Seq.empty
}
}
if (scale && wipe) throw new BadRequestException("You cannot use scale and wipe at the same time.")
if (scale) {
val deploymentF = taskKiller.killAndScale(pathId, findToKill, force)
deploymentResult(await(deploymentF))
} else {
await(taskKiller.kill(pathId, findToKill, wipe).asTry) match {
case Success(instances) =>
val healthStatuses = await(healthCheckManager.statuses(pathId))
instances.headOption match {
case None =>
unknownTask(id)
case Some(i) =>
val killedTask = EnrichedTask.singleFromInstance(i).get
val enrichedTask = killedTask.copy(healthCheckResults = healthStatuses.getOrElse(i.instanceId, Nil))
ok(jsonObjString("task" -> enrichedTask.toRaml))
}
case Failure(PathNotFoundException(appId, version)) => unknownApp(appId, version)
}
}
}
}
}
| gsantovena/marathon | src/main/scala/mesosphere/marathon/api/v2/AppTasksResource.scala | Scala | apache-2.0 | 7,265 |
/*
* Copyright (c) 2017 by the original author
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.powertac.genco;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
import java.util.ArrayList;
import java.util.List;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.Instant;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.powertac.common.Competition;
import org.powertac.common.RandomSeed;
import org.powertac.common.TimeService;
import org.powertac.common.WeatherForecast;
import org.powertac.common.WeatherForecastPrediction;
import org.powertac.common.WeatherReport;
import org.powertac.common.interfaces.BrokerProxy;
import org.powertac.common.interfaces.ContextService;
import org.powertac.common.repo.RandomSeedRepo;
import org.powertac.common.repo.TimeslotRepo;
import org.powertac.common.repo.WeatherForecastRepo;
import org.powertac.common.repo.WeatherReportRepo;
import org.springframework.test.util.ReflectionTestUtils;
/**
* @author John Collins
*/
public class MisoBuyerTest
{
private BrokerProxy mockProxy;
private TimeslotRepo timeslotRepo;
private WeatherReportRepo mockReportRepo;
private WeatherForecastRepo mockForecastRepo;
private MisoBuyer buyer;
private Instant start;
private RandomSeedRepo mockSeedRepo;
private RandomSeed seed;
private TimeService timeService;
/**
*
*/
@BeforeEach
public void setUp () throws Exception
{
// Start Thursday 9:00
Instant start = new DateTime(2017, 1, 12, 9, 0, DateTimeZone.UTC).toInstant();
Competition comp =
Competition.newInstance("MisoBuyer test").withTimeslotsOpen(24)
.withSimulationBaseTime(start);
Competition.setCurrent(comp);
mockProxy = mock(BrokerProxy.class);
mockSeedRepo = mock(RandomSeedRepo.class);
mockReportRepo = mock(WeatherReportRepo.class);
mockForecastRepo = mock(WeatherForecastRepo.class);
seed = mock(RandomSeed.class);
when(mockSeedRepo.getRandomSeed(eq(MisoBuyer.class.getName()),
anyLong(),
anyString())).thenReturn(seed);
when(seed.nextLong()).thenReturn(1l);
timeslotRepo = new TimeslotRepo();
buyer = new MisoBuyer("Test");
timeService = new TimeService();
timeService.setCurrentTime(start);
ReflectionTestUtils.setField(timeslotRepo, "timeService", timeService);
}
private void init ()
{
ContextService svc = mock(ContextService.class);
when(svc.getBean("timeslotRepo")).thenReturn(timeslotRepo);
when(svc.getBean("randomSeedRepo")).thenReturn(mockSeedRepo);
when(svc.getBean("weatherReportRepo")).thenReturn(mockReportRepo);
when(svc.getBean("weatherForecastRepo")).thenReturn(mockForecastRepo);
buyer.init(mockProxy, 0, svc);
}
/**
* Test method for {@link org.powertac.genco.CpGenco#CpGenco(java.lang.String)}.
*/
@Test
public void testMisoBuyer()
{
assertNotNull(buyer, "created something");
assertEquals(buyer.getUsername(), "Test", "correct name");
}
/**
* Test method for {@link org.powertac.genco.CpGenco#init(org.powertac.common.interfaces.BrokerProxy, int, org.powertac.common.repo.RandomSeedRepo, org.powertac.common.repo.TimeslotRepo)}.
*/
@Test
public void testInitBoot ()
{
init();
verify(mockSeedRepo).getRandomSeed(eq(MisoBuyer.class.getName()),
anyLong(), eq("ts"));
assertEquals(0, buyer.getTimeslotOffset(), "timeslotOffset is zero");
}
// Check timeslotOffset in sim mode
@Test
public void testInitSim ()
{
Competition comp = Competition.currentCompetition();
Instant start = comp.getSimulationBaseTime();
timeService.setCurrentTime(comp.getSimulationBaseTime()
.plus(24 * comp.getTimeslotDuration()));
init();
assertEquals(24, buyer.getTimeslotOffset(), "timeslotOffset non-zero");
}
// Check timeslotOffset in sim mode
@Test
public void testInitSim_360 ()
{
Competition comp = Competition.currentCompetition();
Instant start = comp.getSimulationBaseTime();
timeService.setCurrentTime(comp.getSimulationBaseTime()
.plus(360 * comp.getTimeslotDuration()));
init();
assertEquals(360, buyer.getTimeslotOffset(), "timeslotOffset non-zero");
}
// Runs the timeseries for a few steps without randomness
@Test
public void testTS_nr ()
{
// make normal distro return 0.0
when(seed.nextGaussian()).thenReturn(0.0);
init();
buyer.withScaleFactor(1.0);
int len = 10;
double [] ts = new double[len];
for (int i = 0; i < len; i += 1) {
ts[i] = buyer.computeScaledValue(i, 0.0);
}
// daily numbers starting at 9:00
assertEquals(9, buyer.getDailyOffset(), "daily offset");
assertEquals(3*24 + 9, buyer.getWeeklyOffset(), "weeklyOffset");
for (int i = 0; i < len; i += 1) {
double d = buyer.getDailyValue(i);
double w = buyer.getWeeklyValue(i);
assertEquals((d + w + buyer.getMean()), buyer.computeScaledValue(i, 0.0), 1e-5, "correct ts value");
}
}
// Runs the timeseries for a few steps without randomness
@Test
public void testTS_nr_360 ()
{
// make normal distro return 0.0
when(seed.nextGaussian()).thenReturn(0.0);
Competition comp = Competition.currentCompetition();
Instant start = comp.getSimulationBaseTime();
timeService.setCurrentTime(comp.getSimulationBaseTime()
.plus(360 * comp.getTimeslotDuration()));
init();
buyer.withScaleFactor(1.0);
int len = 10;
double [] ts = new double[len];
int first = 360;
for (int i = first; i < len + first; i += 1) {
int idx = i - first;
ts[idx] = buyer.computeScaledValue(i, 0.0);
}
// daily numbers starting at 9:00
assertEquals(9, buyer.getDailyOffset(), "daily offset");
assertEquals((18*24 + 9) % 168, buyer.getWeeklyOffset(), "weeklyOffset");
for (int i = 360; i < len+ 360; i += 1) {
double d = buyer.getDailyValue(i);
double w = buyer.getWeeklyValue(i);
assertEquals((d + w + buyer.getMean()), buyer.computeScaledValue(i, 0.0), 1e-5, "correct ts value");
}
}
@Test
public void testWeatherCorrection_z ()
{
Competition comp = Competition.currentCompetition();
comp.withTimeslotsOpen(4);
WeatherReport wr = new WeatherReport(0, 18.0, 0.0, 0.0, 0.0);
when(mockReportRepo.currentWeatherReport()).thenReturn(wr);
List<WeatherForecastPrediction> wfs = new ArrayList<>();
for (int i = 0; i < comp.getTimeslotsOpen(); i += 1) {
WeatherForecastPrediction wfp =
new WeatherForecastPrediction(i + 1, 17.0 + i, 0.0, 0.0, 0.0);
wfs.add(wfp);
}
WeatherForecast wf = new WeatherForecast(0, wfs);
when(mockReportRepo.currentWeatherReport()).thenReturn(wr);
when(mockForecastRepo.currentWeatherForecast()).thenReturn(wf);
init();
double[] corrections = buyer.computeWeatherCorrections();
for (int i = 0; i < comp.getTimeslotsOpen(); i += 1) {
assertEquals(0.0, corrections[i], 1e-6, "zero correction");
}
}
@Test
public void testForecastSmooth ()
{
init();
buyer.withTempAlpha(0.2);
WeatherForecastPrediction[] wfpa=
new WeatherForecastPrediction[4];
for (int i = 0; i < 4; i += 1)
wfpa[i] = new WeatherForecastPrediction(1, 10.0, 0.0, 0.0, 0.0);
// cooling, temps below threshold
double[] s1 = buyer.smoothForecasts(0, 11.0, 1.0, wfpa);
assertNotNull(s1, "non-null result");
assertEquals(0.0, s1[0], 1e-6, "first zero");
assertEquals(0.0, s1[3], 1e-6, "last zero");
// cooling, temps 10 deg over theshold
s1 = buyer.smoothForecasts(0.0, 0.0, 1.0, wfpa);
double exp = 10.0 * 0.2;
assertEquals(exp, s1[0], 1e-6, "first cs");
exp = 10.0 * 0.2 + exp * 0.8;
assertEquals(exp, s1[1], 1e-6, "second cs");
exp = 10.0 * 0.2 + exp * 0.8;
assertEquals(exp, s1[2], 1e-6, "third cs");
// heating, temps above threshold
s1 = buyer.smoothForecasts(0.0, 0.0, -1.0, wfpa);
assertEquals(0.0, s1[0], 1e-6, "first zero");
assertEquals(0.0, s1[3], 1e-6, "last zero");
// heating, temps below threshold
s1 = buyer.smoothForecasts(0.0, 20.0, -1.0, wfpa);
exp = -10 * 0.2;
assertEquals(exp, s1[0], 1e-6, "first hs");
exp = -10.0 * 0.2 + exp * 0.8;
assertEquals(exp, s1[1], 1e-6, "second cs");
exp = -10.0 * 0.2 + exp * 0.8;
assertEquals(exp, s1[2], 1e-6, "third cs");
exp = -10.0 * 0.2 + exp * 0.8;
assertEquals(exp, s1[3], 1e-6, "fourth cs");
}
@Test
public void testWeatherCorrection_heat ()
{
Competition comp = Competition.currentCompetition();
comp.withTimeslotsOpen(4);
WeatherReport wr = new WeatherReport(0, 8.0, 0.0, 0.0, 0.0);
when(mockReportRepo.currentWeatherReport()).thenReturn(wr);
List<WeatherForecastPrediction> wfs = new ArrayList<>();
for (int i = 0; i < comp.getTimeslotsOpen(); i += 1) {
WeatherForecastPrediction wfp =
new WeatherForecastPrediction(i + 1, 7.0 - i, 0.0, 0.0, 0.0);
wfs.add(wfp);
}
WeatherForecast wf = new WeatherForecast(0, wfs);
when(mockReportRepo.currentWeatherReport()).thenReturn(wr);
when(mockForecastRepo.currentWeatherForecast()).thenReturn(wf);
init();
buyer.withHeatThreshold(10.0);
double[] smoothedTemps = new double[comp.getTimeslotsOpen()];
double exp = 0.1 * -2.0;
for (int i = 0; i < smoothedTemps.length; i += 1) {
exp = 0.1 * (-3.0 - i) + 0.9 * exp;
smoothedTemps[i] = exp;
}
double[] corrections = buyer.computeWeatherCorrections();
for (int i = 0; i < comp.getTimeslotsOpen(); i += 1) {
assertEquals(smoothedTemps[i] * buyer.getHeatCoef(), corrections[i], 1e-6, "correction");
}
}
// Generates a long demand sequence, without weather mod,
// for statistical testing
// @Test
// public void testTS ()
// {
// init();
// java.util.Random gen = new java.util.Random();
// when(seed.nextDouble()).thenReturn(gen.nextDouble());
// // set up ts
// for (int i = 0; i < 18000; i += 1) {
// double val = buyer.computeScaledValue(i, 0.0);
// //System.out.println(String.format("Value %d: %.2f", i, val));
// }
}
| powertac/powertac-server | genco/src/test/java/org/powertac/genco/MisoBuyerTest.java | Java | apache-2.0 | 10,945 |
/*jslint node:true, browser:true */
'use strict';
/*
Copyright 2015 Enigma Marketing Services Limited
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
module.exports = require('lackey-make-title'); | getlackey/framework | make-title.js | JavaScript | apache-2.0 | 715 |
# Exception View Strategy
The base Cornerstone module registers the "View\Http\ExceptionStrategy" for handling
the unhandled Exceptions before Zend gets its grubby paws on it and swallows it
whole. It uses the "Default\Logger" service to write those exceptions to Syslog
by default, but the service can be replaced for other means as well. | web-masons/Cornerstone | doc/view-strategies/exception-view-strategy.md | Markdown | apache-2.0 | 339 |
<?php
/*
* Copyright (C) 2015 Alefe Souza <contato@alefesouza.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Última modificação em: 04/10/2015 23:40
include("../connect_db.php");
include("../values/other.php");
include("pode_nao_pode.php");
if($_GET['data'] == "true") {
$data = "active"; $recente = "backbutton";
$result = mysqli_query($dbi, "SELECT * FROM eventos WHERE sala NOT IN ('gestao','biblioteca','cantina','cartazprecosdacantina') AND sala NOT like ('%cartaz%') ORDER BY date");
} else {
$data = "backbutton"; $recente = "active";
$result = mysqli_query($dbi, "SELECT * FROM eventos WHERE sala NOT IN ('gestao','biblioteca','cantina','cartazprecosdacantina') AND sala NOT like ('%cartaz%') ORDER BY id DESC");
}
?>
<html>
<head>
<?
$title = "Gerenciar eventos";
include("../values/head.php");
toTitle($title); ?>
</head>
<body>
<? toTitle2($title); ?>
<section class="margin card center" style="padding: 0; margin-top: 10px;"><div class="<? echo $recente; ?>" style="width: 50%; float: left; border-left: none;" onclick="window.open('agenda.php', '_self');">Mais recentes</div><div class="<? echo $data; ?>" style="width: 50%;" onclick="window.open('agenda.php?data=true', '_self');">Ordenar por data</div></section>
<?
while ($row = mysqli_fetch_array($result)) {
if(strpos($row['sala'], 'clube') !== false) {
$sala = "Clube de ".getAll($row['sala']);
} else if(strpos($row['sala'], 'eletiva') !== false) {
$sala = "Eletiva de ".getAll($row['sala']);
} else if (getAll($row['sala']) != "") {
$sala = "".getAll($row['sala']);
} else {
$sala = $row['sala'];
} ?>
<section class="margin card">
<p><b>Sala:</b> <? echo $sala; ?></p>
<p><b>Data:</b> <? echo $row['data']; ?></p>
<p><b>Título:</b> <? echo $row['titulo']; ?></p>
<p><b>Descrição:</b> <? if($row['tipo'] == "1") { $tipo = "true"; echo $row['descricao']; } else { $tipo = "false"; echo str_replace("\n", "<br>", $row['descricao']); } ?></p>
<? if($row['historico'] != "") { ?>
<p id="<? echo $row['id']; ?>" style="display: none;"><b>Histórico:</b><br><br><?
$history = json_decode($row['historico']);
foreach($history as $h) {
echo $h;
} }
?></p>
<a class="btn btn-flat" onclick="window.open('editar_evento.php?id=<? echo $row['id']; ?>&aloogleapp=needinternet&editor=<? echo $tipo; ?>', '_self')"><b>Editar</b></a> <a class="btn btn-flat" onclick="window.open('apagar_evento.php?id=<? echo $row['id']; ?>&aloogleapp=needinternet&url=<? echo urlencode($_SERVER[REQUEST_URI]); ?>', '_self');"><b>Apagar</b></a><? if($row['historico'] != "") { ?><a class="btn btn-flat" id="history<? echo $row['id']; ?>" onclick="historyShow(<? echo $row['id']; ?>)"><b>Histórico de edições</b></a><? } ?>
</section>
<? }
if(mysqli_num_rows($result) == 0) { ?>
<section class="margin card">
Não há eventos
</section>
<? }
include("../values/materialinit.php"); ?>
<script>
function historyShow(qual) {
$('#' + qual).show();
$('#history' + qual).hide();
}
</script>
</body>
</html> | alefesouza/schoolapp-backend | backend/schoolapp/rebua/painel/corrigir/agenda.php | PHP | apache-2.0 | 3,516 |
/*
* =============================================================================
*
* Copyright (c) 2011-2016, The THYMELEAF team (http://www.thymeleaf.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* =============================================================================
*/
package org.thymeleaf.templateengine.conversion.conversion1;
import org.thymeleaf.context.IExpressionContext;
import org.thymeleaf.standard.expression.AbstractStandardConversionService;
public class TestStandardConversionService1 extends AbstractStandardConversionService {
public TestStandardConversionService1() {
super();
}
@Override
protected String convertToString(
final IExpressionContext context, final Object object) {
return "[" + super.convertToString(context, object) + "]";
}
}
| thymeleaf/thymeleaf-tests | src/test/java/org/thymeleaf/templateengine/conversion/conversion1/TestStandardConversionService1.java | Java | apache-2.0 | 1,379 |
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
int __attribute__((naked)) sub(int a, int b) {
__asm__("sub r0, r0, r1 \n"
"bx lr \n");
}
int add(int a, int b) { return a + b; }
int sum(int count, ...) {
int ret = 0;
va_list args;
va_start(args, count);
while (count--) {
int e = va_arg(args, int);
ret = add(ret, e);
}
va_end(args);
return ret;
}
int main(int argc, char * argv[]) {
printf("%d\n", sum(5, 1, 2, 3, 4, 5));
} | Samsung/ADBI | idk/tests/args.c | C | apache-2.0 | 554 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from ansible.module_utils.basic import AnsibleModule
import git
import itertools
import multiprocessing
import os
import signal
import time
DOCUMENTATION = """
---
module: git_requirements
short_description: Module to run a multithreaded git clone
options:
repo_info:
description:
- List of repo information dictionaries containing at
a minimum a key entry "src" with the source git URL
to clone for each repo. In these dictionaries, one
can further specify:
"path" - destination clone location
"version" - git version to checkout
"refspec" - git refspec to checkout
"depth" - clone depth level
"force" - require git clone uses "--force"
default_path:
description:
Default git clone path (str) in case not
specified on an individual repo basis in
repo_info. Defaults to "master". Not
required.
default_version:
description:
Default git version (str) in case not
specified on an individual repo basis in
repo_info. Defaults to "master". Not
required.
default_refspec:
description:
Default git repo refspec (str) in case not
specified on an individual repo basis in
repo_info. Defaults to "". Not required.
default_depth:
description:
Default clone depth (int) in case not specified
on an individual repo basis. Defaults to 10.
Not required.
retries:
description:
Integer number of retries allowed in case of git
clone failure. Defaults to 1. Not required.
delay:
description:
Integer time delay (seconds) between git clone
retries in case of failure. Defaults to 0. Not
required.
force:
description:
Boolean. Apply --force flags to git clones wherever
possible. Defaults to False. Not required.
core_multiplier:
description:
Integer multiplier on the number of cores
present on the machine to use for
multithreading. For example, on a 2 core
machine, a multiplier of 4 would use 8
threads. Defaults to 4. Not required.
"""
EXAMPLES = r"""
- name: Clone repos
git_requirements:
repo_info: "[{'src':'https://github.com/ansible/',
'name': 'ansible'
'dest': '/etc/opt/ansible'}]"
"""
def init_signal():
signal.signal(signal.SIGINT, signal.SIG_IGN)
def check_out_version(repo, version, pull=False, force=False,
refspec=None, tag=False, depth=10):
try:
repo.git.fetch(tags=tag, force=force, refspec=refspec, depth=depth)
except Exception as e:
return ["Failed to fetch %s\n%s" % (repo.working_dir, str(e))]
try:
repo.git.checkout(version, force=force)
except Exception as e:
return [
"Failed to check out version %s for %s\n%s" %
(version, repo.working_dir, str(e))]
if repo.is_dirty(untracked_files=True) and force:
try:
repo.git.clean(force=force)
except Exception as e:
return [
"Failed to clean up repository% s\n%s" %
(repo.working_dir, str(e))]
if pull:
try:
repo.git.pull(force=force, refspec=refspec, depth=depth)
except Exception as e:
return ["Failed to pull repo %s\n%s" % (repo.working_dir, str(e))]
return []
def pull_wrapper(info):
role_info = info
retries = info[1]["retries"]
delay = info[1]["delay"]
for i in range(retries):
success = pull_role(role_info)
if success:
return True
else:
time.sleep(delay)
info[2].append(["Role {0} failed after {1} retries\n".format(role_info[0],
retries)])
return False
def pull_role(info):
role, config, failures = info
required_version = role["version"]
version_hash = False
if 'version' in role:
# If the version is the length of a hash then treat is as one
if len(required_version) == 40:
version_hash = True
def get_repo(dest):
try:
return git.Repo(dest)
except Exception:
failtxt = "Role in {0} is broken/not a git repo.".format(
role["dest"])
failtxt += "Please delete or fix it manually"
failures.append(failtxt)
return False
# if repo exists
if os.path.exists(role["dest"]):
repo = get_repo(role["dest"])
if not repo:
return False # go to next role
repo_url = list(repo.remote().urls)[0]
if repo_url != role["src"]:
repo.remote().set_url(role["src"])
# if they want master then fetch, checkout and pull to stay at latest
# master
if required_version == "master":
fail = check_out_version(repo, required_version, pull=True,
force=config["force"],
refspec=role["refspec"],
depth=role["depth"])
# If we have a hash then reset it to
elif version_hash:
fail = check_out_version(repo, required_version,
force=config["force"],
refspec=role["refspec"],
depth=role["depth"])
else:
# describe can fail in some cases so be careful:
try:
current_version = repo.git.describe(tags=True)
except Exception:
current_version = ""
if current_version == required_version and not config["force"]:
fail = []
pass
else:
fail = check_out_version(repo, required_version,
force=config["force"],
refspec=role["refspec"],
depth=role["depth"],
tag=True)
else:
try:
# If we have a hash id then treat this a little differently
if version_hash:
git.Repo.clone_from(role["src"], role["dest"],
branch='master',
no_single_branch=True,
depth=role["depth"])
repo = get_repo(role["dest"])
if not repo:
return False # go to next role
fail = check_out_version(repo, required_version,
force=config["force"],
refspec=role["refspec"],
depth=role["depth"])
else:
git.Repo.clone_from(role["src"], role["dest"],
branch=required_version,
depth=role["depth"],
no_single_branch=True)
fail = []
except Exception as e:
fail = ('Failed cloning repo %s\n%s' % (role["dest"], str(e)))
if fail == []:
return True
else:
failures.append(fail)
return False
def set_default(dictionary, key, defaults):
if key not in dictionary.keys():
dictionary[key] = defaults[key]
def main():
# Define variables
failures = multiprocessing.Manager().list()
# Data we can pass in to the module
fields = {
"repo_info": {"required": True, "type": "list"},
"default_path": {"required": True,
"type": "str"},
"default_version": {"required": False,
"type": "str",
"default": "master"},
"default_refspec": {"required": False,
"type": "str",
"default": None},
"default_depth": {"required": False,
"type": "int",
"default": 10},
"retries": {"required": False,
"type": "int",
"default": 1},
"delay": {"required": False,
"type": "int",
"default": 0},
"force": {"required": False,
"type": "bool",
"default": False},
"core_multiplier": {"required": False,
"type": "int",
"default": 4},
}
# Pull in module fields and pass into variables
module = AnsibleModule(argument_spec=fields)
git_repos = module.params['repo_info']
defaults = {
"path": module.params["default_path"],
"depth": module.params["default_depth"],
"version": module.params["default_version"],
"refspec": module.params["default_refspec"]
}
config = {
"retries": module.params["retries"],
"delay": module.params["delay"],
"force": module.params["force"],
"core_multiplier": module.params["core_multiplier"]
}
# Set up defaults
for repo in git_repos:
for key in ["path", "refspec", "version", "depth"]:
set_default(repo, key, defaults)
if "name" not in repo.keys():
repo["name"] = os.path.basename(repo["src"])
repo["dest"] = os.path.join(repo["path"], repo["name"])
# Define varibles
failures = multiprocessing.Manager().list()
core_count = multiprocessing.cpu_count() * config["core_multiplier"]
# Load up process and pass in interrupt and core process count
p = multiprocessing.Pool(core_count, init_signal)
clone_success = p.map(pull_wrapper, zip(git_repos,
itertools.repeat(config),
itertools.repeat(failures)),
chunksize=1)
p.close()
success = all(i for i in clone_success)
if success:
module.exit_json(msg=str(git_repos), changed=True)
else:
module.fail_json(msg=("Module failed"), meta=failures)
if __name__ == '__main__':
main()
| stackforge/os-ansible-deployment | playbooks/library/git_requirements.py | Python | apache-2.0 | 10,270 |
/* global error:false */
/* global done:false */
/* global PaymentRequest:false */
/**
* Updates details based on shipping address.
* @param {object} details - The details to update.
* @param {ShippingAddress} addr - The shipping address.
* @return {object} The updated details.
*/
function updateDetails(details, addr) {
if (addr.regionCode === 'US') {
var shippingOption = {
id: '',
label: '',
amount: {
currency: 'USD',
value: '0.00'
}
};
if (addr.administrativeArea === 'CA') {
shippingOption.id = 'ca';
shippingOption.label = 'Free shipping in California';
details.items[details.items.length - 1].amount.value = '55.00';
} else {
shippingOption.id = 'us';
shippingOption.label = 'Standard shipping in US';
shippingOption.amount.value = '5.00';
details.items[details.items.length - 1].amount.value = '60.00';
}
if (details.items.length === 3) {
details.items.splice(-1, 0, shippingOption);
} else {
details.items.splice(-2, 1, shippingOption);
}
details.shippingOptions = [shippingOption];
} else {
delete details.shippingOptions;
}
return details;
}
/**
* Starts PaymentRequest with shipping options that depend on the shipping
* address.
*/
function onBuyClicked() { // eslint-disable-line no-unused-vars
var supportedInstruments = [
'https://android.com/pay', 'visa', 'mastercard', 'amex', 'discover',
'maestro', 'diners', 'jcb', 'unionpay'
];
var details = {
items: [{
id: 'original',
label: 'Original donation amount',
amount: {
currency: 'USD',
value: '65.00'
}
},
{
id: 'discount',
label: 'Friends and family discount',
amount: {
currency: 'USD',
value: '-10.00'
}
},
{
id: 'total',
label: 'Donation',
amount: {
currency: 'USD',
value: '55.00'
}
}
]
};
var options = {
requestShipping: true
};
var schemeData = {
'https://android.com/pay': {
'gateway': 'stripe',
'stripe:publishableKey': 'pk_test_VKUbaXb3LHE7GdxyOBMNwXqa',
'stripe:version': '2015-10-16 (latest)'
}
};
if (!window.PaymentRequest) {
error('PaymentRequest API is not supported.');
return;
}
try {
var request =
new PaymentRequest(supportedInstruments, details, options, schemeData);
request.addEventListener('shippingaddresschange', e => {
e.updateWith(new Promise(resolve => {
resolve(updateDetails(details, request.shippingAddress));
}));
});
request.show()
.then(instrumentResponse => {
instrumentResponse.complete(true)
.then(() => {
done(
'This is a demo website. No payment will be processed.', request.shippingAddress,
request.shippingOption, instrumentResponse.methodName,
instrumentResponse.details);
})
.catch(err => {
error(err.message);
});
})
.catch(err => {
error(err.message);
});
} catch (e) {
error('Developer mistake: \'' + e.message + '\'');
}
}
| rsolomakhin/rsolomakhin.github.io | 52/pr/us/pr.js | JavaScript | apache-2.0 | 3,278 |
package guetzli_patapon
// kDCTMatrix[8*u+x] = 0.5*alpha(u)*cos((2*x+1)*u*M_PI/16),
// where alpha(0) = 1/sqrt(2) and alpha(u) = 1 for u > 0.
var kDCTMatrix = [64]float64{
0.3535533906, 0.3535533906, 0.3535533906, 0.3535533906,
0.3535533906, 0.3535533906, 0.3535533906, 0.3535533906,
0.4903926402, 0.4157348062, 0.2777851165, 0.0975451610,
-0.0975451610, -0.2777851165, -0.4157348062, -0.4903926402,
0.4619397663, 0.1913417162, -0.1913417162, -0.4619397663,
-0.4619397663, -0.1913417162, 0.1913417162, 0.4619397663,
0.4157348062, -0.0975451610, -0.4903926402, -0.2777851165,
0.2777851165, 0.4903926402, 0.0975451610, -0.4157348062,
0.3535533906, -0.3535533906, -0.3535533906, 0.3535533906,
0.3535533906, -0.3535533906, -0.3535533906, 0.3535533906,
0.2777851165, -0.4903926402, 0.0975451610, 0.4157348062,
-0.4157348062, -0.0975451610, 0.4903926402, -0.2777851165,
0.1913417162, -0.4619397663, 0.4619397663, -0.1913417162,
-0.1913417162, 0.4619397663, -0.4619397663, 0.1913417162,
0.0975451610, -0.2777851165, 0.4157348062, -0.4903926402,
0.4903926402, -0.4157348062, 0.2777851165, -0.0975451610,
}
func DCT1d(in []float64, stride int, out []float64) {
for x := 0; x < 8; x++ {
out[x*stride] = 0.0
for u := 0; u < 8; u++ {
out[x*stride] += kDCTMatrix[8*x+u] * in[u*stride]
}
}
}
func IDCT1d(in []float64, stride int, out []float64) {
for x := 0; x < 8; x++ {
out[x*stride] = 0.0
for u := 0; u < 8; u++ {
out[x*stride] += kDCTMatrix[8*u+x] * in[u*stride]
}
}
}
type Transform1d func(in []float64, stride int, out []float64)
func TransformBlock(block []float64, f Transform1d) {
var tmp [64]float64
for x := 0; x < 8; x++ {
f(block[x:], 8, tmp[x:])
}
for y := 0; y < 8; y++ {
f(tmp[8*y:], 1, block[8*y:])
}
}
func ComputeBlockDCTDouble(block []float64) {
TransformBlock(block, DCT1d)
}
func ComputeBlockIDCTDouble(block []float64) {
TransformBlock(block, IDCT1d)
}
| Ripounet/guetzli-patapon | dct_double.go | GO | apache-2.0 | 1,918 |
package com.jongsoft.harvester.query.neo4j;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeName;
import com.jongsoft.harvester.query.NotOperator;
import com.jongsoft.harvester.query.Operation;
/**
*
* @author gerben
*/
@JsonTypeName(value = "not")
public class Neo4jNotOperator extends NotOperator {
public Neo4jNotOperator(@JsonProperty("operator") Operation operation) {
super(operation);
}
@Override
public String toString(String ... fields) {
return " NOT (" + super.getOperation().toString(fields) + ") ";
}
@Override
public String toString() {
return " NOT (" + super.getOperation().toString() + ") ";
}
}
| gjong/web-harvester | repository/src/main/java/com/jongsoft/harvester/query/neo4j/Neo4jNotOperator.java | Java | apache-2.0 | 736 |
////////////////////////////////////////////////////////////////////////////
// Module : script_fmatrix_script.cpp
// Created : 28.06.2004
// Modified : 28.06.2004
// Author : Dmitriy Iassenev
// Description : Script float matrix script export
////////////////////////////////////////////////////////////////////////////
#include "pch_script.h"
#include "script_fmatrix.h"
#include "xrServer_Space.h"
using namespace luabind;
void get_matrix_hpb(Fmatrix* self, float* h, float* p, float* b)
{
self->getHPB (*h, *p, *b);
}
void matrix_transform (Fmatrix* self, Fvector* v)
{
self->transform (*v);
}
SRotation get_matrix_rotation(Fmatrix *self)
{
SRotation result;
self->getHPB(result.yaw, result.pitch, result.roll);
return result;
}
void set_matrix_rotation(Fmatrix *self, SRotation *R)
{
self->setHPB(R->yaw, R->pitch, R->roll);
}
#pragma optimize("s",on)
void CScriptFmatrix::script_register(lua_State *L)
{
module(L)
[
class_<Fmatrix>("matrix")
.def_readwrite("i", &Fmatrix::i)
.def_readwrite("_14_", &Fmatrix::_14_)
.def_readwrite("j", &Fmatrix::j)
.def_readwrite("_24_", &Fmatrix::_24_)
.def_readwrite("k", &Fmatrix::k)
.def_readwrite("_34_", &Fmatrix::_34_)
.def_readwrite("c", &Fmatrix::c)
.def_readwrite("_44_", &Fmatrix::_44_)
.def( constructor<>())
.def("set", (Fmatrix & (Fmatrix::*)(const Fmatrix &))(&Fmatrix::set), return_reference_to(_1))
.def("set", (Fmatrix & (Fmatrix::*)(const Fvector &, const Fvector &, const Fvector &, const Fvector &))(&Fmatrix::set), return_reference_to(_1))
.def("identity", &Fmatrix::identity, return_reference_to(_1))
.def("mk_xform", &Fmatrix::mk_xform, return_reference_to(_1))
.def("mul", (Fmatrix & (Fmatrix::*)(const Fmatrix &, const Fmatrix &))(&Fmatrix::mul), return_reference_to(_1))
.def("mul", (Fmatrix & (Fmatrix::*)(const Fmatrix &, float))(&Fmatrix::mul), return_reference_to(_1))
.def("mul", (Fmatrix & (Fmatrix::*)(float))(&Fmatrix::mul), return_reference_to(_1))
.def("mul_43", (Fmatrix & (Fmatrix::*)(const Fmatrix &, const Fmatrix &))(&Fmatrix::mul_43), return_reference_to(_1))
.def("div", (Fmatrix & (Fmatrix::*)(const Fmatrix &, float))(&Fmatrix::div), return_reference_to(_1))
.def("div", (Fmatrix & (Fmatrix::*)(float))(&Fmatrix::div), return_reference_to(_1))
// .def("invert", (Fmatrix & (Fmatrix::*)())(&Fmatrix::invert), return_reference_to(_1))
// .def("invert", (Fmatrix & (Fmatrix::*)(const Fmatrix &))(&Fmatrix::invert), return_reference_to(_1))
.def("transpose", (Fmatrix & (Fmatrix::*)())(&Fmatrix::transpose), return_reference_to(_1))
.def("transpose", (Fmatrix & (Fmatrix::*)(const Fmatrix &))(&Fmatrix::transpose), return_reference_to(_1))
// .def("translate", (Fmatrix & (Fmatrix::*)(const Fvector &))(&Fmatrix::translate), return_reference_to(_1))
// .def("translate", (Fmatrix & (Fmatrix::*)(float, float, float))(&Fmatrix::translate), return_reference_to(_1))
// .def("translate_over", (Fmatrix & (Fmatrix::*)(const Fvector &))(&Fmatrix::translate_over), return_reference_to(_1))
// .def("translate_over", (Fmatrix & (Fmatrix::*)(float, float, float))(&Fmatrix::translate_over), return_reference_to(_1))
// .def("translate_add", &Fmatrix::translate_add, return_reference_to(_1))
// .def("scale", (Fmatrix & (Fmatrix::*)(const Fvector &))(&Fmatrix::scale), return_reference_to(_1))
// .def("scale", (Fmatrix & (Fmatrix::*)(float, float, float))(&Fmatrix::scale), return_reference_to(_1))
// .def("rotateX", &Fmatrix::rotateX, return_reference_to(_1))
// .def("rotateY", &Fmatrix::rotateY, return_reference_to(_1))
// .def("rotateZ", &Fmatrix::rotateZ, return_reference_to(_1))
// .def("rotation", (Fmatrix & (Fmatrix::*)(const Fvector &, const Fvector &))(&Fmatrix::rotation), return_reference_to(_1))
// .def("rotation", (Fmatrix & (Fmatrix::*)(const Fvector &, float))(&Fmatrix::rotation), return_reference_to(_1))
// .def("rotation", &Fmatrix::rotation, return_reference_to(_1))
/*
.def("mapXYZ", &Fmatrix::mapXYZ, return_reference_to(_1))
.def("mapXZY", &Fmatrix::mapXZY, return_reference_to(_1))
.def("mapYXZ", &Fmatrix::mapYXZ, return_reference_to(_1))
.def("mapYZX", &Fmatrix::mapYZX, return_reference_to(_1))
.def("mapZXY", &Fmatrix::mapZXY, return_reference_to(_1))
.def("mapZYX", &Fmatrix::mapZYX, return_reference_to(_1))
.def("mirrorX", &Fmatrix::mirrorX, return_reference_to(_1))
.def("mirrorX_over", &Fmatrix::mirrorX_over, return_reference_to(_1))
.def("mirrorX_add ", &Fmatrix::mirrorX_add, return_reference_to(_1))
.def("mirrorY", &Fmatrix::mirrorY, return_reference_to(_1))
.def("mirrorY_over", &Fmatrix::mirrorY_over, return_reference_to(_1))
.def("mirrorY_add ", &Fmatrix::mirrorY_add, return_reference_to(_1))
.def("mirrorZ", &Fmatrix::mirrorZ, return_reference_to(_1))
.def("mirrorZ_over", &Fmatrix::mirrorZ_over, return_reference_to(_1))
.def("mirrorZ_add ", &Fmatrix::mirrorZ_add, return_reference_to(_1))
*/
// .def("build_projection", &Fmatrix::build_projection, return_reference_to(_1))
// .def("build_projection_HAT", &Fmatrix::build_projection_HAT, return_reference_to(_1))
// .def("build_projection_ortho", &Fmatrix::build_projection_ortho, return_reference_to(_1))
// .def("build_camera", &Fmatrix::build_camera, return_reference_to(_1))
// .def("build_camera_dir", &Fmatrix::build_camera_dir, return_reference_to(_1))
// .def("inertion", &Fmatrix::inertion, return_reference_to(_1))
// .def("transform_tiny32", &Fmatrix::transform_tiny32)
// .def("transform_tiny23", &Fmatrix::transform_tiny23)
.def("transform_tiny", (void (Fmatrix::*)(Fvector &) const)(&Fmatrix::transform_tiny), out_value(_2))
.def("transform_tiny", (void (Fmatrix::*)(Fvector &, const Fvector &) const)(&Fmatrix::transform_tiny), out_value(_2))
// .def("transform_dir", (void (Fmatrix::*)(Fvector &) const)(&Fmatrix::transform_dir), out_value(_2))
// .def("transform_dir", (void (Fmatrix::*)(Fvector &, const Fvector &) const)(&Fmatrix::transform_dir), out_value(_2))
// .def("transform", (void (Fmatrix::*)(Fvector &) const)(&Fmatrix::transform), out_value(_2))
// .def("transform", &matrix_transform)
.def("setHPB", &Fmatrix::setHPB, return_reference_to(_1))
// .def("setXYZ", (Fmatrix & (Fmatrix::*)(Fvector &))(&Fmatrix::setXYZ), return_reference_to(_1) + out_value(_2))
.def("setXYZ", (Fmatrix & (Fmatrix::*)(float, float, float))(&Fmatrix::setXYZ), return_reference_to(_1))
// .def("setXYZi", (Fmatrix & (Fmatrix::*)(Fvector &))(&Fmatrix::setXYZi), return_reference_to(_1) + out_value(_2))
.def("setXYZi", (Fmatrix & (Fmatrix::*)(float, float, float))(&Fmatrix::setXYZi), return_reference_to(_1))
// .def("getHPB", (void (Fmatrix::*)(Fvector &) const)(&Fmatrix::getHPB), out_value(_2))
.def("getHPB", &get_matrix_hpb)
.def("getRotation", &get_matrix_rotation)
.def("setRotation", &set_matrix_rotation)
// .def("getXYZ", (void (Fmatrix::*)(Fvector &) const)(&Fmatrix::getXYZ), out_value(_2))
// .def("getXYZ", (void (Fmatrix::*)(float &, float &, float &) const)(&Fmatrix::getXYZ))
// .def("getXYZi", (void (Fmatrix::*)(Fvector &) const)(&Fmatrix::getXYZi), out_value(_2))
// .def("getXYZi", (void (Fmatrix::*)(float &, float &, float &) const)(&Fmatrix::getXYZi))
];
}
| OLR-xray/OLR-3.0 | src/xray/xr_3da/xrGame/script_fmatrix_script.cpp | C++ | apache-2.0 | 8,832 |
# AUTOGENERATED FILE
FROM balenalib/hummingboard-debian:buster-build
RUN apt-get update \
&& apt-get install -y --no-install-recommends \
ca-certificates \
curl \
\
# .NET Core dependencies
libc6 \
libgcc1 \
libgssapi-krb5-2 \
libicu63 \
libssl1.1 \
libstdc++6 \
zlib1g \
&& rm -rf /var/lib/apt/lists/*
# Configure web servers to bind to port 80 when present
ENV ASPNETCORE_URLS=http://+:80 \
# Enable detection of running in a container
DOTNET_RUNNING_IN_CONTAINER=true
# Install .NET Core
ENV DOTNET_VERSION 3.1.12
RUN curl -SL --output dotnet.tar.gz "https://dotnetcli.blob.core.windows.net/dotnet/Runtime/$DOTNET_VERSION/dotnet-runtime-$DOTNET_VERSION-linux-arm.tar.gz" \
&& dotnet_sha512='5d241663ef78720dacd4073f06150e0b1e085cda542436a9319beb3c14fb6dc19ade72caa738ce50d2bdd31e2936858d9f080a2f9ae43856587b165407b47314' \
&& echo "$dotnet_sha512 dotnet.tar.gz" | sha512sum -c - \
&& mkdir -p /usr/share/dotnet \
&& tar -zxf dotnet.tar.gz -C /usr/share/dotnet \
&& rm dotnet.tar.gz \
&& ln -s /usr/share/dotnet/dotnet /usr/bin/dotnet
CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"]
RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/test-stack@dotnet.sh" \
&& echo "Running test-stack@dotnet" \
&& chmod +x test-stack@dotnet.sh \
&& bash test-stack@dotnet.sh \
&& rm -rf test-stack@dotnet.sh
RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v7 \nOS: Debian Buster \nVariant: build variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \ndotnet 3.1-runtime \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info
RUN echo '#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \
&& chmod +x /bin/sh-shim \
&& cp /bin/sh /bin/sh.real \
&& mv /bin/sh-shim /bin/sh | nghiant2710/base-images | balena-base-images/dotnet/hummingboard/debian/buster/3.1-runtime/build/Dockerfile | Dockerfile | apache-2.0 | 2,529 |
package org.immutables.samples.json.immutables;
import org.immutables.moshi.Json;
import com.google.common.base.Optional;
import java.util.List;
import java.util.Set;
import javax.annotation.Nullable;
import org.immutables.gson.Gson;
import org.immutables.value.Value;
@Value.Immutable
@Value.Enclosing
@Gson.TypeAdapters
@Json.Adapters
public interface Gocument {
List<Item> items();
@Value.Immutable
public interface Item {
int id();
@Json.Named("name")
String name();
@Nullable
String description();
List<Evaluation> evaluation();
int foo();
boolean bar();
Optional<Integer> tid();
Optional<String> gname();
@Nullable
String bdescription();
List<Evaluation> nevaluation();
Optional<Integer> hfoo();
boolean ybar();
Set<Item> recitems();
}
@Value.Immutable
public static abstract class Evaluation {
public abstract String comment();
@Value.Default
public Stars stars() {
return Stars.NONE;
}
public enum Stars {
NONE, ONE, TWO, THREE, FOUR, FIVE
}
}
}
| immutables/samples | json/src/org/immutables/samples/json/immutables/Gocument.java | Java | apache-2.0 | 1,088 |
#!/bin/sh
set -e
mkdir -p "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}"
RESOURCES_TO_COPY=${PODS_ROOT}/resources-to-copy-${TARGETNAME}.txt
> "$RESOURCES_TO_COPY"
XCASSET_FILES=()
case "${TARGETED_DEVICE_FAMILY}" in
1,2)
TARGET_DEVICE_ARGS="--target-device ipad --target-device iphone"
;;
1)
TARGET_DEVICE_ARGS="--target-device iphone"
;;
2)
TARGET_DEVICE_ARGS="--target-device ipad"
;;
*)
TARGET_DEVICE_ARGS="--target-device mac"
;;
esac
install_resource()
{
if [[ "$1" = /* ]] ; then
RESOURCE_PATH="$1"
else
RESOURCE_PATH="${PODS_ROOT}/$1"
fi
if [[ ! -e "$RESOURCE_PATH" ]] ; then
cat << EOM
error: Resource "$RESOURCE_PATH" not found. Run 'pod install' to update the copy resources script.
EOM
exit 1
fi
case $RESOURCE_PATH in
*.storyboard)
echo "ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile ${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .storyboard`.storyboardc $RESOURCE_PATH --sdk ${SDKROOT} ${TARGET_DEVICE_ARGS}"
ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .storyboard`.storyboardc" "$RESOURCE_PATH" --sdk "${SDKROOT}" ${TARGET_DEVICE_ARGS}
;;
*.xib)
echo "ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile ${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib $RESOURCE_PATH --sdk ${SDKROOT} ${TARGET_DEVICE_ARGS}"
ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib" "$RESOURCE_PATH" --sdk "${SDKROOT}" ${TARGET_DEVICE_ARGS}
;;
*.framework)
echo "mkdir -p ${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}"
mkdir -p "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}"
echo "rsync -av $RESOURCE_PATH ${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}"
rsync -av "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}"
;;
*.xcdatamodel)
echo "xcrun momc \"$RESOURCE_PATH\" \"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH"`.mom\""
xcrun momc "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcdatamodel`.mom"
;;
*.xcdatamodeld)
echo "xcrun momc \"$RESOURCE_PATH\" \"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcdatamodeld`.momd\""
xcrun momc "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcdatamodeld`.momd"
;;
*.xcmappingmodel)
echo "xcrun mapc \"$RESOURCE_PATH\" \"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcmappingmodel`.cdm\""
xcrun mapc "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcmappingmodel`.cdm"
;;
*.xcassets)
ABSOLUTE_XCASSET_FILE="$RESOURCE_PATH"
XCASSET_FILES+=("$ABSOLUTE_XCASSET_FILE")
;;
*)
echo "$RESOURCE_PATH"
echo "$RESOURCE_PATH" >> "$RESOURCES_TO_COPY"
;;
esac
}
if [[ "$CONFIGURATION" == "Debug" ]]; then
install_resource "WeiboSDK/libWeiboSDK/WeiboSDK.bundle"
fi
if [[ "$CONFIGURATION" == "Release" ]]; then
install_resource "WeiboSDK/libWeiboSDK/WeiboSDK.bundle"
fi
mkdir -p "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}"
rsync -avr --copy-links --no-relative --exclude '*/.svn/*' --files-from="$RESOURCES_TO_COPY" / "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}"
if [[ "${ACTION}" == "install" ]] && [[ "${SKIP_INSTALL}" == "NO" ]]; then
mkdir -p "${INSTALL_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}"
rsync -avr --copy-links --no-relative --exclude '*/.svn/*' --files-from="$RESOURCES_TO_COPY" / "${INSTALL_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}"
fi
rm -f "$RESOURCES_TO_COPY"
if [[ -n "${WRAPPER_EXTENSION}" ]] && [ "`xcrun --find actool`" ] && [ -n "$XCASSET_FILES" ]
then
# Find all other xcassets (this unfortunately includes those of path pods and other targets).
OTHER_XCASSETS=$(find "$PWD" -iname "*.xcassets" -type d)
while read line; do
if [[ $line != "${PODS_ROOT}*" ]]; then
XCASSET_FILES+=("$line")
fi
done <<<"$OTHER_XCASSETS"
printf "%s\0" "${XCASSET_FILES[@]}" | xargs -0 xcrun actool --output-format human-readable-text --notices --warnings --platform "${PLATFORM_NAME}" --minimum-deployment-target "${!DEPLOYMENT_TARGET_SETTING_NAME}" ${TARGET_DEVICE_ARGS} --compress-pngs --compile "${BUILT_PRODUCTS_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}"
fi
| Faceunity/FUQiniuDemo | Example/Pods/Target Support Files/Pods-PLMediaStreamingKitDemo/Pods-PLMediaStreamingKitDemo-resources.sh | Shell | apache-2.0 | 5,221 |
package ru.job4j.cartrade.controller.main;
import com.google.gson.Gson;
import ru.job4j.cartrade.controller.authorization.UserIdentification;
import ru.job4j.cartrade.model.advertisement.Advertisement;
import ru.job4j.cartrade.model.user.User;
import ru.job4j.cartrade.storage.Storage;
import ru.job4j.cartrade.storage.dao.IAdvertisementDAO;
import ru.job4j.cartrade.storage.dao.IUserDAO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
/**
* Class MainPage описывает контроллер изменения состояния объявления.
* @author Timur Kapkaev (timur.kap@yandex.ru)
* @version $ID$
* @since 25.01.2018
* */
public class ChangeStatus extends HttpServlet {
/**
* Изменяет состояние объявления.
* @param req - запрос пользователя
* @param resp - ответ
* @throws ServletException - сервлет исключение
* @throws IOException - ошибка ввода/вывода
* */
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
HttpSession session = req.getSession();
UserIdentification identification = (UserIdentification) session.getAttribute("identification");
Storage storage = Storage.getInstance();
storage.open();
IUserDAO userDAO = storage.getUserDAO();
User user = userDAO.get(identification.getId());
Gson gson = new Gson();
Advertisement advertisement = gson.fromJson(req.getReader(), Advertisement.class);
IAdvertisementDAO advertisementDAO = storage.getAdvertisementDAO();
Advertisement tmpAdv = advertisementDAO.get(advertisement.getId());
User tmpUser = tmpAdv.getSeller();
if (user.equals(tmpUser)) {
tmpAdv.setSold(advertisement.getSold());
}
advertisement.setSold(tmpAdv.getSold());
storage.submit();
String json = gson.toJson(advertisement);
PrintWriter writer = resp.getWriter();
writer.append(json);
writer.flush();
}
}
| TimKap/tkapkaev | chapter_008/src/main/java/ru/job4j/cartrade/controller/main/ChangeStatus.java | Java | apache-2.0 | 2,344 |
/**
* Copyright (c) 2015 - Andrew C. Pacifico - All Rights Reserved.
* @author Andrew C. Pacifico <andrewcpacifico@gmail.com>
*/
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int n, i, j;
scanf("%d", &n);
for (i = 0; i < n; ++i) {
for (j = 0; j < n - (i + 1); ++j) {
printf(" ");
}
for (; j < n; ++j) {
printf("#");
}
printf("\n");
}
return 0;
}
| andrewcpacifico/programming | hackerrank/algorithms/warmup/0007_staircase.cc | C++ | apache-2.0 | 467 |
package info.u250.c2d.accessors;
import info.u250.c2d.engine.Flip3DCamera;
import aurelienribon.tweenengine.TweenAccessor;
/** change some attributes of the camera
* @author lycying@gmail.com*/
public class Flip3DCameraAccessor implements TweenAccessor<Flip3DCamera>{
public final static int Zoom = 1;
public final static int XY = 2;
public final static int ROTATION_Z = 3;
public final static int ROTATION_X = 4;
public final static int ROTATION_Y = 5;
@Override
public int getValues(Flip3DCamera target, int tweenType, float[] returnValues) {
switch(tweenType){
case Zoom:
returnValues[0] = target.getZoom();
return 1;
case XY:
returnValues[0] = target.position.x ;
returnValues[1] = target.position.y ;
return 2;
case ROTATION_Z:
returnValues[0] = target.getAngleZ();
return 1;
case ROTATION_X:
returnValues[0] = target.getAngleX();
return 1;
case ROTATION_Y:
returnValues[0] = target.getAngleY();
return 1;
default: assert false; return -1;
}
}
@Override
public void setValues(Flip3DCamera target, int tweenType, float[] newValues) {
switch(tweenType){
case Zoom:
target.setZoom(newValues[0]);
break;
case XY:
target.position.x = newValues[0];
target.position.y = newValues[1];
break;
case ROTATION_Z:
target.setAngleZ(newValues[0]);
break;
case ROTATION_X:
target.setAngleX(newValues[0]);
break;
case ROTATION_Y:
target.setAngleY(newValues[0]);
break;
default: assert false;
}
}
} | shiguang1120/c2d-engine | c2d/src/info/u250/c2d/accessors/Flip3DCameraAccessor.java | Java | apache-2.0 | 1,502 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional information regarding
* copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License. You may obtain a
* copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.apache.geode.rest.internal.web;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Properties;
import org.apache.http.HttpResponse;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.apache.geode.cache.execute.Function;
import org.apache.geode.distributed.ConfigurationProperties;
import org.apache.geode.examples.SimpleSecurityManager;
import org.apache.geode.test.compiler.JarBuilder;
import org.apache.geode.test.dunit.rules.ClusterStartupRule;
import org.apache.geode.test.dunit.rules.MemberVM;
import org.apache.geode.test.junit.categories.DistributedTest;
import org.apache.geode.test.junit.rules.GfshCommandRule;
@Category(DistributedTest.class)
public class RestFunctionExecuteDUnitTest {
@ClassRule
public static ClusterStartupRule cluster = new ClusterStartupRule();
@ClassRule
public static GfshCommandRule gfsh = new GfshCommandRule();
private static JarBuilder jarBuilder = new JarBuilder();
private static MemberVM locator, server1, server2;
private GeodeRestClient client;
@BeforeClass
public static void beforeClass() throws Exception {
// prepare the jar to deploy
File jarsToDeploy = new File(gfsh.getWorkingDir(), "function.jar");
jarBuilder.buildJar(jarsToDeploy, loadClassToFile());
Properties locatorProps = new Properties();
locatorProps.put(ConfigurationProperties.SECURITY_MANAGER,
SimpleSecurityManager.class.getName());
locator = cluster.startLocatorVM(0, locatorProps);
Properties props = new Properties();
props.put(ConfigurationProperties.START_DEV_REST_API, "true");
props.put("security-username", "cluster");
props.put("security-password", "cluster");
props.put(ConfigurationProperties.GROUPS, "group1");
server1 = cluster.startServerVM(1, props, locator.getPort());
props.put(ConfigurationProperties.GROUPS, "group2");
server2 = cluster.startServerVM(2, props, locator.getPort());
gfsh.connectAndVerify(locator);
// deploy the function only to server1
gfsh.executeAndAssertThat("deploy --jar=" + jarsToDeploy.getAbsolutePath() + " --group=group1")
.statusIsSuccess();
}
@Test
public void connectToServer1() throws Exception {
client = new GeodeRestClient("localhost", server1.getHttpPort());
HttpResponse response = client.doPost("/functions/myTestFunction", "dataRead", "dataRead", "");
assertThat(GeodeRestClient.getCode(response)).isEqualTo(403);
// function can't be executed on all members since it's only deployed on server1
response = client.doPost("/functions/myTestFunction", "dataManage", "dataManage", "");
assertThat(GeodeRestClient.getCode(response)).isEqualTo(500);
// function can't be executed on server2
response = client.doPost("/functions/myTestFunction?onMembers=server-2", "dataManage",
"dataManage", "");
assertThat(GeodeRestClient.getCode(response)).isEqualTo(500);
// function can only be executed on server1 only
response = client.doPost("/functions/myTestFunction?onMembers=server-1", "dataManage",
"dataManage", "");
assertThat(GeodeRestClient.getCode(response)).isEqualTo(200);
}
@Test
public void connectToServer2() throws Exception {
// function is deployed on server1
client = new GeodeRestClient("localhost", server2.getHttpPort());
HttpResponse response = client.doPost("/functions/myTestFunction", "dataRead", "dataRead", "");
assertThat(GeodeRestClient.getCode(response)).isEqualTo(404);
}
// find ImplementsFunction.java in the geode-core resource
private static File loadClassToFile() throws URISyntaxException {
URL resourceFileURL = Function.class.getClassLoader()
.getResource("org/apache/geode/management/internal/deployment/ImplementsFunction.java");
assertThat(resourceFileURL).isNotNull();
URI resourceUri = resourceFileURL.toURI();
return new File(resourceUri);
}
}
| smanvi-pivotal/geode | geode-assembly/src/test/java/org/apache/geode/rest/internal/web/RestFunctionExecuteDUnitTest.java | Java | apache-2.0 | 4,913 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_45) on Mon Mar 03 10:44:37 EST 2014 -->
<title>Uses of Class org.hibernate.annotations.CollectionId (Hibernate JavaDocs)</title>
<meta name="date" content="2014-03-03">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.hibernate.annotations.CollectionId (Hibernate JavaDocs)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../org/hibernate/annotations/CollectionId.html" title="annotation in org.hibernate.annotations">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../../../../overview-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?org/hibernate/annotations/class-use/CollectionId.html" target="_top">Frames</a></li>
<li><a href="CollectionId.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class org.hibernate.annotations.CollectionId" class="title">Uses of Class<br>org.hibernate.annotations.CollectionId</h2>
</div>
<div class="classUseContainer">No usage of org.hibernate.annotations.CollectionId</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../org/hibernate/annotations/CollectionId.html" title="annotation in org.hibernate.annotations">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../../../../overview-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?org/hibernate/annotations/class-use/CollectionId.html" target="_top">Frames</a></li>
<li><a href="CollectionId.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2001-2014 <a href="http://redhat.com">Red Hat, Inc.</a> All Rights Reserved.</small></p>
</body>
</html>
| serious6/HibernateSimpleProject | javadoc/hibernate_Doc/org/hibernate/annotations/class-use/CollectionId.html | HTML | apache-2.0 | 4,305 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="refresh" content="0;URL=../../ocl_core/fn.verify_context.html">
</head>
<body>
<p>Redirecting to <a href="../../ocl_core/fn.verify_context.html">../../ocl_core/fn.verify_context.html</a>...</p>
<script>location.replace("../../ocl_core/fn.verify_context.html" + location.search + location.hash);</script>
</body>
</html> | liebharc/clFFT | docs/bindings/ocl_core/functions/fn.verify_context.html | HTML | apache-2.0 | 389 |
/*
*
* * Copyright (C) 2016 Singular Studios (a.k.a Atom Tecnologia) - www.opensingular.com
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
*
*/
package org.opensingular.lib.wicket.util.util;
import static org.opensingular.lib.wicket.util.util.Shortcuts.*;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.IModel;
import org.junit.Assert;
import org.junit.Test;
import org.opensingular.lib.commons.lambda.IFunction;
import org.opensingular.lib.commons.lambda.ISupplier;
public class IModelsMixinTest {
@Test
public void compound() {
CompoundPropertyModel<TestTO> model = $m.compound($m.ofValue(new TestTO()));
Assert.assertEquals("A", model.bind("a").getObject());
Assert.assertEquals("B", model.bind("b").getObject());
Assert.assertEquals("C", model.bind("c").getObject());
}
@Test
public void compoundOf() {
CompoundPropertyModel<TestTO> model = $m.compoundOf(new TestTO());
Assert.assertEquals("A", model.bind("a").getObject());
Assert.assertEquals("B", model.bind("b").getObject());
Assert.assertEquals("C", model.bind("c").getObject());
}
@Test
public void conditional() {
IModel<Boolean> condition = $m.ofValue(true);
IModel<Integer> model = $m.conditional(condition, $m.ofValue(1), $m.ofValue(0));
condition.setObject(true);
Assert.assertEquals(1, model.getObject().intValue());
condition.setObject(false);
Assert.assertEquals(0, model.getObject().intValue());
model.detach();
}
@Test
public void get() {
TestTO to = new TestTO();
IModel<String> model = $m.get(() -> to.a);
Assert.assertEquals("A", model.getObject());
to.a = "AA";
Assert.assertEquals("AA", model.getObject());
}
@Test
public void getSet() {
TestTO to = new TestTO();
IModel<String> model = $m.getSet(() -> to.a, v -> to.a = v);
Assert.assertEquals("A", model.getObject());
model.setObject("AA");
Assert.assertEquals("AA", model.getObject());
Assert.assertEquals("AA", to.a);
}
@Test
public void isGt() {
IModel<Integer> m1 = $m.ofValue(1);
IModel<Integer> m2 = $m.ofValue(2);
IModel<Integer> mn = $m.ofValue();
Assert.assertFalse($m.isGt(m1, m2).getObject());
Assert.assertTrue($m.isGt(m2, m1).getObject());
Assert.assertFalse($m.isGt(mn, m1).getObject());
Assert.assertTrue($m.isGt(m1, mn).getObject());
$m.isGt(m1, m2).detach();
}
@Test
public void isNot() {
Assert.assertFalse($m.isNot($m.ofValue(true)).getObject());
Assert.assertTrue($m.isNot($m.ofValue(false)).getObject());
$m.isNot($m.ofValue(false)).detach();
}
@Test
public void isNotNullOrEmpty() {
Assert.assertFalse($m.isNotNullOrEmpty($m.ofValue()).getObject());
Assert.assertFalse($m.isNotNullOrEmpty(null).getObject());
Assert.assertTrue($m.isNotNullOrEmpty($m.ofValue(1)).getObject());
Assert.assertTrue($m.isNotNullOrEmpty(1).getObject());
}
@Test
public void isNullOrEmpty() {
Assert.assertTrue($m.isNullOrEmpty($m.ofValue()).getObject());
Assert.assertTrue($m.isNullOrEmpty(null).getObject());
Assert.assertFalse($m.isNullOrEmpty($m.ofValue(1)).getObject());
Assert.assertFalse($m.isNullOrEmpty(1).getObject());
}
@Test
public void loadable() {
List<Integer> list = new ArrayList<>();
IFunction<List<Integer>, List<Integer>> populator = it -> {
it.addAll(Arrays.asList(1, 2));
return it;
};
ISupplier<List<Integer>> supplier = () -> populator.apply(list);
IModel<List<Integer>> model = $m.loadable(supplier);
Assert.assertEquals(2, model.getObject().size());
Assert.assertEquals(2, model.getObject().size());
Assert.assertEquals(4, supplier.get().size());
Assert.assertEquals(6, supplier.get().size());
Assert.assertEquals(6, model.getObject().size());
}
@Test
public void loadableInitial() {
IModel<List<Integer>> model = $m.loadable(Arrays.asList(1, 2), () -> Arrays.asList(3));
Assert.assertEquals(2, model.getObject().size());
model.detach();
Assert.assertEquals(1, model.getObject().size());
}
@Test
public void map() {
IModel<String> model = $m.map($m.ofValue(new TestTO("S")), it -> it.a);
Assert.assertEquals("S", model.getObject());
model.detach();
}
@Test
public void ofValue() {
Assert.assertNull($m.ofValue().getObject());
Assert.assertEquals(1, $m.ofValue(1).getObject().intValue());
Assert.assertEquals(
$m.ofValue(new TestTO("A", "B", "C"), it -> it.a),
$m.ofValue(new TestTO("A", "X", "Y"), it -> it.a));
}
@Test
public void property() {
Assert.assertEquals("X", $m.property(new TestTO("X"), "a").getObject());
Assert.assertEquals("Y", $m.property(new TestTO("Y"), "a", String.class).getObject());
}
@Test
public void wrapValue() {
Assert.assertEquals("X", $m.wrapValue("X").getObject());
Assert.assertEquals("X", $m.wrapValue($m.ofValue("X")).getObject());
}
static class TestTO implements Serializable {
private String a, b, c;
public TestTO(String s) {
this(s, s, s);
}
public TestTO() {
this("A", "B", "C");
}
public TestTO(String a, String b, String c) {
this.a = a;
this.b = b;
this.c = c;
}
//@formatter:off
public String getA() { return a; }
public String getB() { return b; }
public String getC() { return c; }
public TestTO setA(String a) { this.a = a; return this; }
public TestTO setB(String b) { this.b = b; return this; }
public TestTO setC(String c) { this.c = c; return this; }
//@formatter:on
}
}
| opensingular/singular-core | lib/wicket-utils/src/test/java/org/opensingular/lib/wicket/util/util/IModelsMixinTest.java | Java | apache-2.0 | 6,764 |
package com.example.webehave;
import static org.jbehave.core.io.CodeLocations.codeLocationFromClass;
import java.util.List;
import java.util.Properties;
import org.jbehave.core.configuration.Configuration;
import org.jbehave.core.configuration.MostUsefulConfiguration;
import org.jbehave.core.io.StoryFinder;
import org.jbehave.core.junit.JUnitStories;
import org.jbehave.core.reporters.FilePrintStreamFactory.ResolveToPackagedName;
import org.jbehave.core.reporters.Format;
import org.jbehave.core.reporters.StoryReporterBuilder;
import org.jbehave.core.steps.InjectableStepsFactory;
import org.jbehave.core.steps.InstanceStepsFactory;
import org.jbehave.core.steps.ParameterControls;
import org.jbehave.web.selenium.PropertyWebDriverProvider;
import de.codecentric.jbehave.junit.monitoring.JUnitReportingRunner;
@SuppressWarnings({"javadoc","nls"})
abstract public class AllStories extends JUnitStories {
public AllStories() {
super();
configuredEmbedder().embedderControls()
.doGenerateViewAfterStories(true)
.doIgnoreFailureInStories(true)
.doIgnoreFailureInView(true)
.useThreads(2)
.useStoryTimeoutInSecs(60)
.useStoryTimeoutInSecs(Long.MAX_VALUE);
JUnitReportingRunner.recommandedControls(configuredEmbedder());
}
@Override
public Configuration configuration() {
final Properties viewResources = new Properties();
viewResources.put("decorateNonHtml", "true");
return new MostUsefulConfiguration()
.useParameterControls(
new ParameterControls()
.useDelimiterNamedParameters(true))
.useStoryReporterBuilder(
new StoryReporterBuilder()
.withDefaultFormats()
.withPathResolver(new ResolveToPackagedName())
.withViewResources(viewResources)
.withFormats(Format.HTML)
.withFailureTrace(true)
.withFailureTraceCompression(true));
}
@Override
public InjectableStepsFactory stepsFactory() {
return new InstanceStepsFactory(
configuration(),
new SimpleSteps(new PropertyWebDriverProvider()));
}
@Override
protected List<String> storyPaths() {
return new StoryFinder()
.findPaths(
codeLocationFromClass(this.getClass()),
Utils.includePattern,
Utils.excludePattern);
}
}
| adrian-herscu/experiments | frameworks/jbehave/webehave/src/main/java/com/example/webehave/AllStories.java | Java | apache-2.0 | 2,704 |
---
layout: post
title: "Set up Waterline ORM with ExpressJS"
subtitle: "Easily set up an ORM for relational databases in ExpressJS."
date: 2015-03-1 8:59:00
author: "Ganesh Datta"
header-img: "img/waterline.png"
description: "Setting up the Waterline ORM in express is easy if you put everything in one file, but I like to keep my apps organized. Here's how I setup Waterline in a clean, readable manner for ExpressJS."
ogimage: "img/waterline.png"
comments: true
---
I've been working with Node.js and the ExpressJS framework recently for a project of mine, and I wanted to use Postgres as my database due to the relational nature of my data. I looked for an ORM to speed up my development, and came across multiple, including Sequelize and Bookshelf, among others. Looking at their docs, I found that Waterline, the default ORM in SailsJS, was much friendlier to use from my last encounter with Sails. So, I decided to figure out how to use Waterline in an Express application in a more modular format.
*Disclaimer: I'm in no way an expert at this stuff, so please do correct me in the comment section if I'm wrong!*
#Folder Setup
I like to keep my project organized, so my folder layout for a REST API looks like the following (a modification of the built in express-generator):
~~~
myapp
- bin
+ www
- models
+ index.js
+ all other models
- router
+ routes (containing all routes)
+ index.js
- services
~~~
Setting up Waterline with Express is quite simple if you have all the models in the same file. However, keeping things modular makes it a little more complicated. First off is my models folder. In my models folder, I have an index.js file, along with a file for each individual model. For example, `models/User.js` would look like:
{% highlight javascript %}
var Waterline = require('Waterline');
var bcrypt = require('bcrypt');
var User = Waterline.Collection.extend({
identity: 'user',
connection: 'myPostgres',
attributes: {
email: {
type: 'string',
email: true,
required: true,
unique: true
},
name: {
type: 'string',
required: true,
},
password: {
type: 'string',
required: true
},
classes: {
type: 'array',
required: true
},
toJSON: function() {
var obj = this.toObject();
delete obj.password;
return obj;
}
},
beforeCreate: function(values, next){
var bcrypt = require('bcrypt');
bcrypt.genSalt(10, function(err, salt) {
if (err) return next(err);
bcrypt.hash(values.password, salt, function(err, hash) {
if (err) return next(err);
values.password = hash;
next();
});
});
}
});
module.exports = User;
{% endhighlight %}
Notice the connection field in the model. This will be defined in the index.js file. Speaking of which, let's move on to that file now!
#index.js - Why?
Waterline needs to be told about all models so that it can create the correct tables, etc. in your database, and allow you to access these models elsewhere in your app. However, we've defined all these models in different files, and we want to make it easy for these models to be added to the ORM automatically. So, I use an index.js file to automate this process for me.
Additionally, I use it to set up the actual connection to the database (though this should probably be in an external config file).
{% highlight javascript %}
var postgresAdapter = require('sails-postgresql');
var Waterline = require('waterline');
var orm = new Waterline();
var config = {
adapters: {
postgresql: postgresAdapter
},
connections: {
myPostgres: {
adapter: 'postgresql',
host: 'localhost',
user: 'ganeshdatta',
database: 'studygroup-express'
}
}
};
var fs = require('fs');
var path = require("path");
fs
.readdirSync(__dirname)
.filter(function(file) {
return (file.indexOf(".") !== 0) && (file !== "index.js");
})
.forEach(function(file) {
var model = require(path.join(__dirname, file));
orm.loadCollection(model);
});
module.exports = {waterline: orm, config: config};
{% endhighlight %}
There are two things going on here. First, we create a waterline object, which will be used to access models throughout the application.
Second, we're going through all the files in the models folder, and added them to waterline with the `loadCollection()` method. The best part about doing it this way is that we can continue adding model files to the models directory, and they'll automatically be added to Waterline!
Also, notice how the module exports two things - the orm object itself, and the config we defined here. This will be used in our application startup file (`bin/www` in my case), so that we can get the orm running correctly when the server is started.
#Server Startup
Wherever you're starting your server, you would now need to add this little snippet of code:
~~~
var models = require('../models');
models.waterline.initialize(models.config, function(err, models) {
if(err) throw err;
// console.log(models.collections);
app.models = models.collections;
app.connections = models.connections;
// Start Server
server.listen(port);
});
~~~
What this does is initializes the server with the defined config in index.js, and then start the server only if waterline is up and running correctly. Additionally, it adds the collections (models) to your app object (assuming your app is called `app`, obviously), so you can access them around the application by calling it like `app.models.user.findOne({})`.
With this, waterline is set up in a modular way in express! Shoutout to the guys at SailsJS and Waterline working on this awesome ORM! | gsdatta/gsdatta.github.io | _posts/2015-3-1-waterline-orm-in-express-the-correct-way.md | Markdown | apache-2.0 | 5,814 |
<?php
/**
* Class Google\Site_Kit\Core\Util\Entity
*
* @package Google\Site_Kit
* @copyright 2021 Google LLC
* @license https://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0
* @link https://sitekit.withgoogle.com
*/
namespace Google\Site_Kit\Core\Util;
/**
* Class representing an entity.
*
* An entity in Site Kit terminology is based on a canonical URL, i.e. every
* canonical frontend URL has an associated entity.
*
* An entity may also have a type, if it can be determined.
* Possible types are e.g. 'post' for a WordPress post (of any post type!),
* 'term' for a WordPress term (of any taxonomy!), 'blog' for the blog archive,
* 'date' for a date-based archive etc.
*
* For specific entity types, the entity will also have a title, and it may
* even have an ID. For example:
* * For a type of 'post', the entity ID will be the post ID and the entity
* title will be the post title.
* * For a type of 'term', the entity ID will be the term ID and the entity
* title will be the term title.
* * For a type of 'date', there will be no entity ID, but the entity title
* will be the title of the date-based archive.
*
* @since 1.7.0
* @access private
* @ignore
*/
final class Entity {
/**
* The entity URL.
*
* @since 1.7.0
* @var string
*/
private $url;
/**
* The entity type.
*
* @since 1.7.0
* @var string
*/
private $type;
/**
* The entity title.
*
* @since 1.7.0
* @var string
*/
private $title;
/**
* The entity ID.
*
* @since 1.7.0
* @var int
*/
private $id;
/**
* Entity URL sub-variant.
*
* @since 1.42.0
* @var string
*/
private $mode;
/**
* Constructor.
*
* @since 1.7.0
*
* @param string $url The entity URL.
* @param array $args {
* Optional. Additional entity arguments.
*
* @type string $type The entity type.
* @type string $title The entity title.
* @type int $id The entity ID.
* @type string $mode Entity URL sub-variant.
* }
*/
public function __construct( $url, array $args = array() ) {
$args = array_merge(
array(
'type' => '',
'title' => '',
'id' => 0,
'mode' => '',
),
$args
);
$this->url = $url;
$this->type = (string) $args['type'];
$this->title = (string) $args['title'];
$this->id = (int) $args['id'];
$this->mode = (string) $args['mode'];
}
/**
* Gets the entity URL.
*
* @since 1.7.0
*
* @return string The entity URL.
*/
public function get_url() {
return $this->url;
}
/**
* Gets the entity type.
*
* @since 1.7.0
*
* @return string The entity type, or empty string if unknown.
*/
public function get_type() {
return $this->type;
}
/**
* Gets the entity title.
*
* @since 1.7.0
*
* @return string The entity title, or empty string if unknown.
*/
public function get_title() {
return $this->title;
}
/**
* Gets the entity ID.
*
* @since 1.7.0
*
* @return int The entity ID, or 0 if unknown.
*/
public function get_id() {
return $this->id;
}
/**
* Gets the entity URL sub-variant.
*
* @since 1.42.0
*
* @return string The entity title, or empty string if unknown.
*/
public function get_mode() {
return $this->mode;
}
}
| google/site-kit-wp | includes/Core/Util/Entity.php | PHP | apache-2.0 | 3,278 |
/*
* Copyright (C) 2014 Philippine Android Developers Community
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ph.devcon.android.profile.event;
/**
* Created by lope on 10/29/14.
*/
public class UpdatedProfileFailedEvent {
public String message;
public UpdatedProfileFailedEvent(String message) {
this.message = message;
}
}
| padc/DevConSummit | app/src/main/java/ph/devcon/android/profile/event/UpdatedProfileFailedEvent.java | Java | apache-2.0 | 871 |
CRICTL User Guide
=================
This document presumes you already have `containerd` and `cri-containerd`
installed and running.
This document is for developers who wish to debug, inspect, and manage their pods,
containers, and container images.
Before generating issues against this document, `containerd`, `cri-containerd`,
or `crictl` please make sure the issue has not already been submitted.
## Install crictl
If you have not already installed crictl please install the version compatible
with the `cri-containerd` you are using. If you are a user, your deployment
should have installed crictl for you. If not, get it from your release tarball.
If you are a developer the current version of crictl is specified [here](../hack/utils.sh).
A helper command has been included to install the dependencies at the right version:
```console
$ make install.deps
```
* Note: The file named `/etc/crictl.yaml` is used to configure crictl
so you don't have to repeatedly specify the runtime sock used to connect crictl
to the container runtime:
```console
$ cat /etc/crictl.yaml
runtime-endpoint: /var/run/cri-containerd.sock
image-endpoint: /var/run/cri-containerd.sock
timeout: 10
debug: true
```
## Download and Inspect a Container Image
The pull command tells the container runtime to download a container image from
a container registry.
```console
$ crictl pull busybox
...
$ crictl inspecti busybox
... displays information about the image.
```
## Directly Load a Container Image
Another way to load an image into the container runtime is with the load
command. With the load command you inject a container image into the container
runtime from a file. First you need to create a container image tarball. For
example to create an image tarball for a pause container using Docker:
```console
$ docker pull k8s.gcr.io/pause-amd64:3.1
3.1: Pulling from pause-amd64
67ddbfb20a22: Pull complete
Digest: sha256:59eec8837a4d942cc19a52b8c09ea75121acc38114a2c68b98983ce9356b8610
Status: Downloaded newer image for k8s.gcr.io/pause-amd64:3.1
$ docker save k8s.gcr.io/pause-amd64:3.1 -o pause.tar
```
Then load the container image into the container runtime:
```console
$ sudo ctrcri load pause.tar
Loaded image: k8s.gcr.io/pause-amd64:3.1
```
List images and inspect the pause image:
```console
$ sudo crictl images
IMAGE TAG IMAGE ID SIZE
docker.io/library/busybox latest f6e427c148a76 728kB
k8s.gcr.io/pause-amd64 3.1 da86e6ba6ca19 746kB
$ sudo crictl inspecti da86e6ba6ca19
... displays information about the pause image.
$ sudo crictl inspecti k8s.gcr.io/pause-amd64:3.1
... displays information about the pause image.
```
## Run a pod sandbox (using a config file)
```console
$ cat sandbox-config.json
{
"metadata": {
"name": "nginx-sandbox",
"namespace": "default",
"attempt": 1,
"uid": "hdishd83djaidwnduwk28bcsb"
},
"linux": {
}
}
$ crictl runp sandbox-config.json
e1c83b0b8d481d4af8ba98d5f7812577fc175a37b10dc824335951f52addbb4e
$ crictl pods
PODSANDBOX ID CREATED STATE NAME NAMESPACE ATTEMPT
e1c83b0b8d481 2 hours ago SANDBOX_READY nginx-sandbox default 1
$ crictl inspectp e1c8
... displays information about the pod and the pod sandbox pause container.
```
* Note: As shown above, you may use truncated IDs if they are unique.
* Other commands to manage the pod include `stops ID` to stop a running pod and
`rmp ID` to remove a pod sandbox.
## Create and Run a Container in a Pod Sandbox (using a config file)
```console
$ cat sandbox-config.json
{
"metadata": {
"name": "nginx-sandbox",
"namespace": "default",
"attempt": 1,
"uid": "hdishd83djaidwnduwk28bcsb"
},
"linux": {
}
}
$ cat container-config.json
{
"metadata": {
"name": "busybox"
},
"image":{
"image": "busybox"
},
"command": [
"top"
],
"linux": {
}
}
$ crictl create e1c83 container-config.json sandbox-config.json
0a2c761303163f2acaaeaee07d2ba143ee4cea7e3bde3d32190e2a36525c8a05
$ crictl ps
CONTAINER ID IMAGE CREATED STATE NAME ATTEMPT
0a2c761303163 docker.io/busybox 2 hours ago CONTAINER_CREATED busybox 0
$ crictl start 0a2c
0a2c761303163f2acaaeaee07d2ba143ee4cea7e3bde3d32190e2a36525c8a05
$ crictl ps
CONTAINER ID IMAGE CREATED STATE NAME ATTEMPT
0a2c761303163 docker.io/busybox 2 hours ago CONTAINER_RUNNING busybox 0
$ crictl inspect 0a2c7
... show detailed information about the container
```
## Exec a Command in the Container
```console
$ crictl exec -i -t 0a2c ls
bin dev etc home proc root sys tmp usr var
```
## Display Stats for the Container
```console
$ crictl stats
CONTAINER CPU % MEM DISK INODES
0a2c761303163f 0.00 991.2kB 16.38kB 6
```
* Other commands to manage the container include `stop ID` to stop a running
container and `rm ID` to remove a container.
## Display Version Information
```console
$ crictl version
Version: 0.1.0
RuntimeName: cri-containerd
RuntimeVersion: 1.0.0-alpha.1-167-g737efe7-dirty
RuntimeApiVersion: 0.0.0
```
## Display Status & Configuration Information about Containerd & CRI-Containerd
```console
$ crictl info
{
"status": {
"conditions": [
{
"type": "RuntimeReady",
"status": true,
"reason": "",
"message": ""
},
{
"type": "NetworkReady",
"status": true,
"reason": "",
"message": ""
}
]
},
"config": {
"containerd": {
"rootDir": "/var/lib/containerd",
"snapshotter": "overlayfs",
"endpoint": "/run/containerd/containerd.sock",
"runtime": "io.containerd.runtime.v1.linux"
},
"cni": {
"binDir": "/opt/cni/bin",
"confDir": "/etc/cni/net.d"
},
"socketPath": "/var/run/cri-containerd.sock",
"rootDir": "/var/lib/cri-containerd",
"streamServerPort": "10010",
"sandboxImage": "gcr.io/google_containers/pause:3.0",
"statsCollectPeriod": 10,
"oomScore": -999,
"enableProfiling": true,
"profilingPort": "10011",
"profilingAddress": "127.0.0.1"
}
}
```
## More Information
See [here](https://github.com/kubernetes-incubator/cri-tools/blob/master/docs/crictl.md)
for information about crictl.
| mikebrow/cri-containerd | docs/crictl.md | Markdown | apache-2.0 | 6,649 |
# Quick instruction:
# To build against an OpenSSL built in the source tree, do this:
#
# make OPENSSL_INCS_LOCATION=-I../../include OPENSSL_LIBS_LOCATION=-L../..
#
# To run the demos when linked with a shared library (default):
#
# LD_LIBRARY_PATH=../.. ./gmac
# LD_LIBRARY_PATH=../.. ./poly1305
CFLAGS = $(OPENSSL_INCS_LOCATION) -Wall
LDFLAGS = $(OPENSSL_LIBS_LOCATION) -lssl -lcrypto
all: gmac poly1305
gmac: gmac.o
poly1305: poly1305.o
gmac poly1305:
$(CC) $(CFLAGS) -o $@ $< $(LDFLAGS)
clean:
$(RM) gmac poly1305 *.o
| openssl/openssl | demos/mac/Makefile | Makefile | apache-2.0 | 538 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
public partial class EditPost : System.Web.UI.Page
{
public int nid;
protected void Page_Load(object sender, EventArgs e)
{
Master.pageTitle = "New Blog Post";
Master.bgImg = "blogpost-bg.jpg";
//reference site http://www.tinymce.com/wiki.php
Master.formatContent = @"
<script type='text/javascript' src='/js/tinymce/tinymce.min.js'></script>
<script type='text/javascript' src='/js/tinymce/jquery.tinymce.min.js'></script>
<script src='/js/tinymceEditor.js'></script>";
if (Request.QueryString["id"] != null)
{
nid = Convert.ToInt32(Request.QueryString["id"]);
}
/**
* Executes the following block of code only when
* the page is not posted back. If IsPostBack is true
* or no PostBack methed declared here, then update command on btnUpdate_Click event won't work. No information will be updated.
* Because the Page_Load method resets the changed values with the old values again.
*/
if (IsPostBack == false)
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = Master.con;
cmd.CommandText = @"SELECT *
FROM Blog
WHERE id = @nid";
cmd.Parameters.AddWithValue("@nid", nid);
SqlDataReader reader;
reader = cmd.ExecuteReader();
while (reader.Read())
{
txtpostTitle.Text = reader["postTitle"].ToString();
txtpostSubTitle.Text = reader["postSubTitle"].ToString();
txtUserId.Text = reader["userId"].ToString();
txtcreatedAt.Text = reader["createdAt"].ToString();
txtcontent.Text = reader["content"].ToString();
}
}
}
protected void btnUpdate_Click(object sender, EventArgs e)
{
if (Request.QueryString["id"] != null)
{
nid = Convert.ToInt32(Request.QueryString["id"]);
}
SqlCommand cmd = new SqlCommand();
cmd.Connection = Master.con;
cmd.CommandText = @"UPDATE Blog
SET postTitle=@postTitle, postSubTitle=@postSubTitle, userId=@userId, createdAt=@createdAt, content=@content
WHERE id=@nid";
cmd.Parameters.Add("@nid", SqlDbType.Int).Value = nid;
cmd.Parameters.Add("@postTitle", SqlDbType.NVarChar).Value = txtpostTitle.Text;
cmd.Parameters.Add("@postSubTitle", SqlDbType.NVarChar).Value = txtpostSubTitle.Text;
cmd.Parameters.Add("@userId", SqlDbType.Int).Value = txtUserId.Text;
cmd.Parameters.Add("@createdAt", SqlDbType.DateTime).Value = txtcreatedAt.Text;
cmd.Parameters.Add("@content", SqlDbType.NVarChar).Value = txtcontent.Text;
cmd.ExecuteNonQuery();
cmd.Dispose();
Clear_Rec();
successPost.Text = "<div class='alert alert-success'>You post has been updated!</div>";
}
private void Clear_Rec()
{
txtUserId.Text = "";
txtpostTitle.Text = "";
txtpostSubTitle.Text = "";
txtcreatedAt.Text = "";
txtcontent.Text = "";
}
} | IqbalKaur/iqbalkaur | EditPost.aspx.cs | C# | apache-2.0 | 3,468 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* \file coproc_sync.cc
*/
#include <tvm/runtime/registry.h>
#include <tvm/tir/builtin.h>
#include <tvm/tir/expr.h>
#include <tvm/tir/stmt_functor.h>
#include <tvm/tir/transform.h>
#include <unordered_map>
#include <unordered_set>
#include "ir_utils.h"
#include "storage_access.h"
namespace tvm {
namespace tir {
// Visitor to find touched set by co-processor scope.
class CoProcTouchedBuffer : public StmtExprVisitor {
public:
void VisitExpr_(const LoadNode* op) final {
if (in_scope_) {
touched_[op->buffer_var.get()].coproc = true;
} else {
touched_[op->buffer_var.get()].normal = true;
}
StmtExprVisitor::VisitExpr_(op);
}
void VisitStmt_(const StoreNode* op) final {
if (in_scope_) {
touched_[op->buffer_var.get()].coproc = true;
} else {
touched_[op->buffer_var.get()].normal = true;
}
StmtExprVisitor::VisitStmt_(op);
}
void VisitExpr_(const CallNode* op) final {
if (op->op.same_as(builtin::tvm_access_ptr())) {
const VarNode* buffer = op->args[1].as<VarNode>();
if (in_scope_) {
touched_[buffer].coproc = true;
} else {
touched_[buffer].normal = true;
}
}
StmtExprVisitor::VisitExpr_(op);
}
void VisitStmt_(const AttrStmtNode* op) final {
if (op->attr_key == attr::coproc_scope && !in_scope_) {
in_scope_ = true;
IterVar iv = Downcast<IterVar>(op->node);
coproc_.insert(iv);
StmtExprVisitor::VisitStmt_(op);
in_scope_ = false;
} else {
StmtExprVisitor::VisitStmt_(op);
}
}
// Touch Entry
struct TouchEntry {
bool normal{false};
bool coproc{false};
};
std::unordered_map<const VarNode*, TouchEntry> touched_;
std::unordered_set<IterVar> coproc_;
private:
bool in_scope_{false};
};
// Synchronization planning with co-processor.
class CoProcSyncPlanner : public StorageAccessVisitor {
public:
explicit CoProcSyncPlanner(const std::unordered_set<const VarNode*>& touched,
const std::string& coproc_name)
: touched_(touched), coproc_name_(coproc_name) {}
void Plan(const Stmt& stmt) {
this->VisitStmt(stmt);
PlanSync(scope_.back(), nullptr, true);
if (sync_.size() == 0) {
sync_[stmt.get()] = GetSync(coproc_name_ + ".coproc_sync");
}
}
// Write synchronization to be inserted before or after stmt.
std::unordered_map<const Object*, std::vector<Stmt> > sync_;
protected:
bool Enabled(const VarNode* buf, const StorageScope& scope) const final {
return touched_.count(buf);
}
// Plan the sync
std::vector<AccessEntry> Summarize(std::vector<StmtEntry> seq, const ForNode* loop) final {
return PlanSync(seq, loop, false);
}
private:
// Plan write synchronization if write is not coherent
std::vector<AccessEntry> PlanSync(std::vector<StmtEntry> seq, const ForNode* loop,
bool force_sync_at_end) {
// detect write barriers
// access by the co-processor.
std::vector<AccessEntry> co_access;
bool contain_sync = false;
auto find_conflict = [&](const AccessEntry& acc) {
for (const AccessEntry& x : co_access) {
if (x.buffer.same_as(acc.buffer) &&
((acc.type == kRead && x.type == kWrite) || acc.type == kWrite)) {
return true;
}
}
return false;
};
for (size_t i = 0; i < seq.size(); ++i) {
const StmtEntry& s = seq[i];
bool sync_write = false;
for (const AccessEntry& acc : s.access) {
if (acc.threads.size() == 0 && find_conflict(acc)) {
sync_write = true;
break;
}
if (acc.type == kSync) {
co_access.clear();
contain_sync = true;
}
}
if (sync_write) {
ICHECK_NE(i, 0U);
sync_[seq[i - 1].stmt] = GetSync(co_access);
co_access.clear();
contain_sync = true;
}
for (const AccessEntry& acc : s.access) {
if (acc.threads.size() != 0) {
co_access.push_back(acc);
}
}
}
bool sync_at_end = force_sync_at_end;
if (loop != nullptr && !sync_at_end) {
// loop carray dependency
for (size_t i = 0; i < seq.size(); ++i) {
const StmtEntry& s = seq[i];
for (const AccessEntry& acc : s.access) {
if (acc.threads.size() == 0 && find_conflict(acc)) {
sync_at_end = true;
break;
}
}
if (sync_.count(s.stmt) || sync_at_end) break;
}
}
if (sync_at_end && co_access.size() != 0) {
ICHECK_NE(seq.size(), 0);
contain_sync = true;
sync_[seq.back().stmt] = GetSync(co_access);
co_access.clear();
}
if (contain_sync) {
AccessEntry e;
e.type = kSync;
co_access.insert(co_access.begin(), e);
}
return co_access;
}
// Add write Synchronization
std::vector<Stmt> GetSync(const std::vector<AccessEntry>& co_access) {
// Does not consider memory coherence, need runtime.
ICHECK_NE(co_access.size(), 0U);
ICHECK_EQ(co_access[0].threads.size(), 1U);
return GetSync(coproc_name_ + ".coproc_sync");
}
std::vector<Stmt> GetSync(std::string sync_name) {
return {Evaluate(Call(DataType::Int(32), Op::Get("tir." + sync_name), {}))};
}
const std::unordered_set<const VarNode*>& touched_;
std::string coproc_name_;
};
// Detect memory barriers when coproc read/write memory
class CoProcBarrierDetector : public StorageAccessVisitor {
public:
explicit CoProcBarrierDetector(const std::unordered_set<const VarNode*>& touched,
const std::string& coproc_name)
: touched_(touched) {
read_barrier_name_ = "tir." + coproc_name + ".coproc_read_barrier";
write_barrier_name_ = "tir." + coproc_name + ".coproc_write_barrier";
}
void PlanReadBarrier(const Stmt& stmt) {
read_barrier_ = true;
this->VisitStmt(stmt);
PlanReadBarrier(scope_.back(), nullptr);
}
void PlanWriteBarrier(const Stmt& stmt) {
read_barrier_ = false;
this->VisitStmt(stmt);
PlanWriteBarrier(scope_.back(), nullptr);
}
std::unordered_map<const Object*, std::vector<Stmt> > barrier_before_;
std::unordered_map<const Object*, std::vector<Stmt> > barrier_after_;
protected:
bool Enabled(const VarNode* buf, const StorageScope& scope) const final {
return touched_.count(buf);
}
// Plan the sync
std::vector<AccessEntry> Summarize(std::vector<StmtEntry> seq, const ForNode* loop) final {
if (read_barrier_) {
return PlanReadBarrier(seq, loop);
} else {
return PlanWriteBarrier(seq, loop);
}
}
private:
// Plan write barrier at Read after write point.
std::vector<AccessEntry> PlanWriteBarrier(std::vector<StmtEntry> seq, const ForNode* loop) {
std::vector<AccessEntry> read_seq;
std::unordered_map<const VarNode*, std::vector<AccessEntry> > write_set;
auto fupdate = [&](size_t i, const AccessEntry& acc) {
auto it = write_set.find(acc.buffer.get());
if (it != write_set.end()) {
ICHECK_NE(i, 0U);
barrier_after_[seq[i - 1].stmt].push_back(MakeBarrier(write_barrier_name_, it->second));
write_set.erase(it);
}
};
for (size_t i = 0; i < seq.size(); ++i) {
const StmtEntry& s = seq[i];
for (const AccessEntry& acc : s.access) {
if (acc.threads.size() == 0 && acc.type == kRead) {
fupdate(i, acc);
read_seq.push_back(acc);
}
}
for (const AccessEntry& acc : s.access) {
if (acc.threads.size() != 0 && acc.type == kWrite) {
write_set[acc.buffer.get()].push_back(acc);
}
}
}
// loop carry
if (loop != nullptr) {
for (const AccessEntry& acc : read_seq) {
fupdate(seq.size(), acc);
}
}
for (const auto& kv : write_set) {
read_seq.insert(read_seq.end(), kv.second.begin(), kv.second.end());
}
return read_seq;
}
std::vector<AccessEntry> PlanReadBarrier(std::vector<StmtEntry> seq, const ForNode* loop) {
std::vector<AccessEntry> write_seq;
std::unordered_map<const VarNode*, std::vector<AccessEntry> > read_set;
auto fupdate = [&](size_t i, const AccessEntry& acc) {
auto it = read_set.find(acc.buffer.get());
if (it != read_set.end()) {
ICHECK_NE(i, seq.size());
barrier_before_[seq[i].stmt].push_back(MakeBarrier(read_barrier_name_, it->second));
read_set.erase(it);
}
};
for (size_t i = seq.size(); i != 0; --i) {
const StmtEntry& s = seq[i - 1];
for (const AccessEntry& acc : s.access) {
if (acc.threads.size() == 0 && acc.type == kWrite) {
fupdate(i, acc);
write_seq.push_back(acc);
}
}
for (const AccessEntry& acc : s.access) {
if (acc.threads.size() != 0 && acc.type == kRead) {
read_set[acc.buffer.get()].push_back(acc);
}
}
}
// loop carry
if (loop != nullptr) {
for (const AccessEntry& acc : write_seq) {
fupdate(0, acc);
}
}
for (const auto& kv : read_set) {
write_seq.insert(write_seq.end(), kv.second.begin(), kv.second.end());
}
return write_seq;
}
Stmt MakeBarrier(const std::string& func, const std::vector<AccessEntry>& wvec) {
// insert write point
Array<arith::IntSet> wset;
for (const AccessEntry& acc : wvec) {
ICHECK(acc.dtype == wvec[0].dtype);
wset.push_back(acc.touched);
}
Range none;
Range r = arith::Union(wset).CoverRange(none);
ICHECK(r.defined()) << "Cannot deduce write range of " << wvec[0].buffer;
PrimExpr min = r->min;
PrimExpr extent = r->extent;
return Evaluate(Call(DataType::Int(32), Op::Get(func),
{wvec[0].buffer, wvec[0].dtype.bits(), r->min, r->extent}));
}
// Write barrier name
bool read_barrier_{false};
std::string read_barrier_name_;
std::string write_barrier_name_;
const std::unordered_set<const VarNode*>& touched_;
};
class CoProcInstDepDetector : public StmtVisitor {
public:
explicit CoProcInstDepDetector(const IterVar& coproc_axis, const std::string& coproc_name)
: coproc_axis_(coproc_axis) {
sync_push_op_ = Op::Get("tir." + coproc_name + ".coproc_dep_push");
sync_pop_op_ = Op::Get("tir." + coproc_name + ".coproc_dep_pop");
}
void Plan(const Stmt& stmt) {
this->VisitStmt(stmt);
if (last_state_.node != nullptr) {
MatchFixEnterPop(first_state_);
MatchFixExitPush(last_state_);
}
}
void VisitStmt_(const AttrStmtNode* op) final {
if (op->attr_key == attr::coproc_scope && op->node.same_as(coproc_axis_)) {
const IntImmNode* ctx_id = op->value.as<IntImmNode>();
ICHECK(ctx_id != nullptr);
curr_state_.clear();
curr_state_.node = op->body.get();
curr_state_.enter_ctx.insert(ctx_id->value);
curr_state_.exit_ctx.insert(ctx_id->value);
UpdateState();
} else {
StmtVisitor::VisitStmt_(op);
}
}
void VisitStmt_(const ForNode* op) final {
SyncState temp_first, temp_last;
std::swap(first_state_, temp_first);
std::swap(last_state_, temp_last);
this->VisitStmt(op->body);
curr_state_.clear();
if (last_state_.node != nullptr) {
curr_state_.node = op;
ICHECK(first_state_.node != nullptr);
// loop carry dependency
InjectSync(last_state_, first_state_, &(curr_state_.exit_push), &(curr_state_.enter_pop));
curr_state_.enter_ctx = first_state_.enter_ctx;
curr_state_.exit_ctx = last_state_.exit_ctx;
}
std::swap(first_state_, temp_first);
std::swap(last_state_, temp_last);
if (curr_state_.node != nullptr) {
UpdateState();
}
}
void VisitStmt_(const IfThenElseNode* op) final {
SyncState temp_first, temp_last, curr_state;
std::swap(first_state_, temp_first);
std::swap(last_state_, temp_last);
{
// then stmt
this->VisitStmt(op->then_case);
if (last_state_.node != nullptr) {
curr_state.node = op;
MatchFixEnterPop(first_state_);
MatchFixExitPush(last_state_);
curr_state.enter_ctx.insert(first_state_.enter_ctx.begin(), first_state_.enter_ctx.end());
curr_state.exit_ctx.insert(last_state_.exit_ctx.begin(), last_state_.exit_ctx.end());
}
first_state_.clear();
last_state_.clear();
}
if (op->else_case.defined()) {
this->VisitStmt(op->else_case);
if (last_state_.node != nullptr) {
curr_state.node = op;
MatchFixEnterPop(first_state_);
MatchFixExitPush(last_state_);
curr_state.enter_ctx.insert(first_state_.enter_ctx.begin(), first_state_.enter_ctx.end());
curr_state.exit_ctx.insert(last_state_.exit_ctx.begin(), last_state_.exit_ctx.end());
}
}
// update in the trace.
std::swap(first_state_, temp_first);
std::swap(last_state_, temp_last);
std::swap(curr_state_, curr_state);
if (curr_state_.node != nullptr) {
UpdateState();
}
}
void VisitStmt_(const WhileNode* op) final {
// TODO(masahi): Do we need a special handling for While nodes?
LOG(FATAL) << "WhileNode not supported in CoProcSync.";
}
// insert before is stored in reverse order
// the first element is closest to the node.
std::unordered_map<const Object*, std::vector<Stmt> > insert_before_;
std::unordered_map<const Object*, std::vector<Stmt> > insert_after_;
private:
// state in the sync entry
struct SyncState {
// The statement of the state.
const Object* node{nullptr};
// Set of all possible contexts in the entering moment.
std::unordered_set<int> enter_ctx;
// Set of all possible contexts in the exit moment.
std::unordered_set<int> exit_ctx;
// existing pop performed at enter
std::vector<std::pair<int, int> > enter_pop;
// existing push peformed at exit
std::vector<std::pair<int, int> > exit_push;
// clear the state
void clear() {
node = nullptr;
enter_ctx.clear();
exit_ctx.clear();
enter_pop.clear();
exit_push.clear();
}
};
// inject proper sync into the pair
// record the push/pop sequence that could be possibly un-matched.
// return the push/pop message at enter/exit of the Block
// after considering the existing unmatcheded events and added events
void InjectSync(const SyncState& prev, const SyncState& next,
std::vector<std::pair<int, int> >* prev_exit_push,
std::vector<std::pair<int, int> >* next_enter_pop) {
prev_exit_push->clear();
next_enter_pop->clear();
// quick path
if (prev.exit_push.size() == 0 && next.enter_pop.size() == 0 && prev.exit_ctx.size() == 1 &&
next.enter_ctx.size() == 1) {
int from = *prev.exit_ctx.begin();
int to = *next.enter_ctx.begin();
if (from != to) {
insert_after_[prev.node].emplace_back(MakePush(from, to));
insert_before_[next.node].emplace_back(MakePop(from, to));
prev_exit_push->emplace_back(std::make_pair(from, to));
next_enter_pop->emplace_back(std::make_pair(from, to));
}
return;
}
// complicate path.
std::vector<std::pair<int, int> > vpush = prev.exit_push;
std::vector<std::pair<int, int> > vpop = next.enter_pop;
std::vector<std::pair<int, int> > pending;
for (int from : prev.exit_ctx) {
for (int to : next.enter_ctx) {
if (from != to) {
pending.emplace_back(std::make_pair(from, to));
}
}
}
// policy 1
std::vector<Stmt> prev_after, next_before;
for (const std::pair<int, int>& p : pending) {
if (std::find(prev.exit_push.begin(), prev.exit_push.end(), p) == prev.exit_push.end()) {
vpush.push_back(p);
prev_after.emplace_back(MakePush(p.first, p.second));
}
if (std::find(next.enter_pop.begin(), next.enter_pop.end(), p) == next.enter_pop.end()) {
vpop.push_back(p);
next_before.emplace_back(MakePop(p.first, p.second));
}
}
// fix pending
for (const std::pair<int, int>& p : vpush) {
if (std::find(vpop.begin(), vpop.end(), p) == vpop.end()) {
prev_after.emplace_back(MakePop(p.first, p.second));
} else {
prev_exit_push->push_back(p);
}
}
for (const std::pair<int, int>& p : vpop) {
if (std::find(vpush.begin(), vpush.end(), p) == vpush.end()) {
next_before.emplace_back(MakePush(p.first, p.second));
} else {
next_enter_pop->push_back(p);
}
}
if (prev_after.size() != 0) {
auto& v1 = insert_after_[prev.node];
v1.insert(v1.end(), prev_after.begin(), prev_after.end());
}
if (next_before.size() != 0) {
auto& v2 = insert_before_[next.node];
v2.insert(v2.end(), next_before.begin(), next_before.end());
}
}
void MatchFixEnterPop(const SyncState& state) {
if (state.enter_pop.size() == 0) return;
auto& vec = insert_before_[state.node];
for (const std::pair<int, int>& p : state.enter_pop) {
vec.push_back(MakePush(p.first, p.second));
}
}
void MatchFixExitPush(const SyncState& state) {
if (state.exit_push.size() == 0) return;
auto& vec = insert_after_[state.node];
for (const std::pair<int, int>& p : state.exit_push) {
vec.push_back(MakePop(p.first, p.second));
}
}
void UpdateState() {
if (last_state_.node != nullptr) {
std::vector<std::pair<int, int> > t1, t2;
InjectSync(last_state_, curr_state_, &t1, &t2);
std::swap(last_state_, curr_state_);
} else {
ICHECK(first_state_.node == nullptr);
first_state_ = curr_state_;
last_state_ = curr_state_;
}
}
Stmt MakePush(int from, int to) {
return Evaluate(Call(DataType::Int(32), sync_push_op_,
{make_const(DataType::Int(32), from), make_const(DataType::Int(32), to)}));
}
Stmt MakePop(int from, int to) {
return Evaluate(Call(DataType::Int(32), sync_pop_op_,
{make_const(DataType::Int(32), from), make_const(DataType::Int(32), to)}));
}
// sync states.
SyncState first_state_, last_state_, curr_state_;
// Variables
IterVar coproc_axis_;
Op sync_push_op_, sync_pop_op_;
};
class CoProcSyncInserter : public StmtMutator {
public:
Stmt Insert(Stmt stmt) {
CoProcTouchedBuffer visitor;
visitor(stmt);
if (visitor.coproc_.size() == 0) return stmt;
std::unordered_set<const VarNode*> touched;
for (const auto& kv : visitor.touched_) {
if (kv.second.normal && kv.second.coproc) {
touched.insert(kv.first);
}
}
ICHECK_EQ(visitor.coproc_.size(), 1U);
std::string coproc_name = (*visitor.coproc_.begin())->var->name_hint;
// plan sync.
CoProcSyncPlanner sync_planner(touched, coproc_name);
sync_planner.Plan(stmt);
for (const auto& kv : sync_planner.sync_) {
auto& vec = insert_after_[kv.first];
vec.insert(vec.end(), kv.second.begin(), kv.second.end());
}
// Detect barrier
CoProcBarrierDetector barrier_detector(touched, coproc_name);
barrier_detector.PlanReadBarrier(stmt);
barrier_detector.PlanWriteBarrier(stmt);
for (const auto& kv : barrier_detector.barrier_before_) {
auto& vec = insert_before_[kv.first];
vec.insert(vec.end(), kv.second.begin(), kv.second.end());
}
for (const auto& kv : barrier_detector.barrier_after_) {
auto& vec = insert_after_[kv.first];
vec.insert(vec.end(), kv.second.begin(), kv.second.end());
}
// Detect barrier
CoProcInstDepDetector sync_detector(*visitor.coproc_.begin(), coproc_name);
sync_detector.Plan(stmt);
for (const auto& kv : sync_detector.insert_before_) {
auto& vec = insert_before_[kv.first];
vec.insert(vec.end(), kv.second.begin(), kv.second.end());
}
for (const auto& kv : sync_detector.insert_after_) {
auto& vec = insert_after_[kv.first];
vec.insert(vec.end(), kv.second.begin(), kv.second.end());
}
return operator()(std::move(stmt));
}
Stmt VisitStmt(const Stmt& stmt) final {
auto it_before = insert_before_.find(stmt.get());
auto it_after = insert_after_.find(stmt.get());
Stmt new_stmt = StmtMutator::VisitStmt(stmt);
return SeqStmt::Flatten(
it_before != insert_before_.end() ? it_before->second : std::vector<Stmt>(), new_stmt,
it_after != insert_after_.end() ? it_after->second : std::vector<Stmt>());
}
private:
// insert before is stored in reverse order
// the first element is closest to the node.
std::unordered_map<const Object*, std::vector<Stmt> > insert_before_;
std::unordered_map<const Object*, std::vector<Stmt> > insert_after_;
};
Stmt CoProcSync(Stmt stmt) { return CoProcSyncInserter().Insert(std::move(stmt)); }
namespace transform {
Pass CoProcSync() {
auto pass_func = [](PrimFunc f, IRModule m, PassContext ctx) {
auto* n = f.CopyOnWrite();
n->body = CoProcSyncInserter().Insert(std::move(n->body));
return f;
};
return CreatePrimFuncPass(pass_func, 0, "tir.CoProcSync", {});
}
TVM_REGISTER_GLOBAL("tir.transform.CoProcSync").set_body_typed(CoProcSync);
} // namespace transform
} // namespace tir
} // namespace tvm
| Laurawly/tvm-1 | src/tir/transforms/coproc_sync.cc | C++ | apache-2.0 | 22,100 |
<div
class="wrapper"
[is-dirty]="swapping || (swapForm && swapForm.dirty)"
[is-dirty-message]="swapping ? operationInProgressWarning : swapForm && swapForm.dirty ? unsavedChangesWarning : null"
>
<div *ngIf="showHeader" class="header">
<div class="header-icon-container">
<span class="header-icon" load-image="image/swap.svg"></span>
</div>
{{ 'swapSlotsHeading' | translate }}
<div
class="header-close-button"
role="button"
title="'close' | translate"
aria-label="'close' | translate"
load-image="image/close.svg"
tabindex="0"
(click)="closePanel()"
[activate-with-keys]
>
<span class="header-close-button-icon"> </span>
</div>
</div>
<div class="body" [formGroup]="swapForm" novalidate>
<div class="body-liner">
<div class="controls-container">
<info-box *ngIf="loadingFailure" typeClass="error" [infoText]="loadingFailure"> </info-box>
<info-box *ngIf="swapPermissionsMessage" typeClass="warn" [infoText]="swapPermissionsMessage"> </info-box>
<info-box *ngIf="readOnlyLockMessage" typeClass="warn" [infoText]="readOnlyLockMessage"> </info-box>
</div>
<div class="controls-container">
<div class="control-container src">
<div class="control-label">
<div class="bullet src"></div>
{{ 'source' | translate }}
<div *ngIf="(swapForm?.controls)['srcId']?.value === siteResourceId" class="pill">{{ 'production' | translate }}</div>
</div>
<div>
<drop-down
[ariaLabel]="'source' | translate"
ariaErrorId="src-validation"
[control]="!!swapForm ? swapForm.controls['srcId'] : null"
[options]="srcDropDownOptions"
[highlightDirty]="false"
(value)="onSlotIdChange()"
>
</drop-down>
<div *ngIf="(swapForm?.controls)['srcId']" id="src-validation" class="validation-container">
<div
*ngIf="!swapForm.pending && swapForm.invalid && swapForm.errors && swapForm.errors['slotsNotUnique']"
class="error-message"
>
{{ swapForm.errors['slotsNotUnique'] }}
</div>
<ng-container
*ngIf="!swapForm.controls['srcId'].pending && swapForm.controls['srcId'].invalid && swapForm.controls['srcId'].errors"
>
<div *ngIf="swapForm.controls['srcId'].errors['noSwapPermission']" class="error-message">
{{ swapForm.controls['srcId'].errors['noSwapPermission'] }}
</div>
<div *ngIf="swapForm.controls['srcId'].errors['noWritePermission']" class="error-message">
{{ swapForm.controls['srcId'].errors['noWritePermission'] }}
</div>
<div *ngIf="swapForm.controls['srcId'].errors['readOnlyLock']" class="error-message">
{{ swapForm.controls['srcId'].errors['readOnlyLock'] }}
</div>
</ng-container>
<div [style.display]="swapForm.controls['srcId'].pending ? 'inherit' : 'none'">
<span load-image="image/spinner.svg" class="icon-small"></span>
<p class="centered-validating-text">{{ 'validating' | translate }}</p>
</div>
</div>
</div>
</div>
<div class="control-container dest">
<div class="control-label">
<div class="bullet dest"></div>
{{ 'target' | translate }}
<div *ngIf="(swapForm?.controls)['destId']?.value === siteResourceId" class="pill">{{ 'production' | translate }}</div>
</div>
<div>
<drop-down
[ariaLabel]="'target' | translate"
ariaErrorId="dest-validation"
[control]="!!swapForm ? swapForm.controls['destId'] : null"
[options]="destDropDownOptions"
[highlightDirty]="false"
(value)="onSlotIdChange()"
>
</drop-down>
<div *ngIf="(swapForm?.controls)['destId']" id="dest-validation" class="validation-container">
<div
*ngIf="!swapForm.pending && swapForm.invalid && swapForm.errors && swapForm.errors['slotsNotUnique']"
class="error-message"
>
{{ swapForm.errors['slotsNotUnique'] }}
</div>
<ng-container
*ngIf="!swapForm.controls['destId'].pending && swapForm.controls['destId'].invalid && swapForm.controls['destId'].errors"
>
<div *ngIf="swapForm.controls['destId'].errors['noSwapPermission']" class="error-message">
{{ swapForm.controls['destId'].errors['noSwapPermission'] }}
</div>
<div *ngIf="swapForm.controls['destId'].errors['noWritePermission']" class="error-message">
{{ swapForm.controls['destId'].errors['noWritePermission'] }}
</div>
<div *ngIf="swapForm.controls['destId'].errors['readOnlyLock']" class="error-message">
{{ swapForm.controls['destId'].errors['readOnlyLock'] }}
</div>
</ng-container>
<div [style.display]="swapForm.controls['destId'].pending ? 'inherit' : 'none'">
<span load-image="image/spinner.svg" class="icon-small"></span>
<p class="centered-validating-text">{{ 'validating' | translate }}</p>
</div>
</div>
</div>
</div>
</div>
<div class="controls-container">
<info-box *ngIf="noStickySettings" typeClass="info" [infoText]="'swapMultiPhaseNoStickySettings' | translate"> </info-box>
<div>
<label>
<input [formControl]="swapForm ? swapForm.controls['multiPhase'] : null" type="checkbox" />
{{ 'swapWithPreviewLabel' | translate }}
</label>
<info-box
*ngIf="swapForm && swapForm.errors !== null && swapForm.errors['authMultiPhaseConflict']"
typeClass="warning"
[infoText]="swapForm.errors['authMultiPhaseConflict'] | translate"
>
</info-box>
</div>
</div>
<div *ngIf="(swapForm?.controls)['multiPhase']?.value" class="phase-container">
<progress-bar [steps]="phases" class="NavSymbols"></progress-bar>
<div class="help-text-container">
{{ 'swapWithPreviewInfoText' | translate }}
</div>
<info-box *ngIf="showPreviewLink" typeClass="info" [infoText]="'swapMultiPhasePreviewMessage' | translate" [infoLink]="previewLink">
</info-box>
</div>
<div *ngIf="showPreviewChanges && (swapForm?.controls)['multiPhase']?.value">
<h1 class="preview-changes-header">{{ 'phaseOneChangesHeading' | translate }}</h1>
<div class="help-text-container">
{{ 'phaseOneChangesInfoText' | translate }}
</div>
<swap-diff-table
[loading]="swapForm?.pending || (swapForm?.valid && loadingDiffs)"
[invalid]="!swapForm?.pending && !swapForm?.valid"
[loadedOrFailed]="!swapForm?.pending && swapForm?.valid && !loadingDiffs"
[diffs]="stickySettingDiffs"
[showToggle]="false"
oldValueHeading="slotsDiff_currentValueHeader"
newValueHeading="slotsDiff_tempValueHeader"
>
</swap-diff-table>
</div>
<div>
<h1 *ngIf="!(swapForm?.controls)['multiPhase']?.value" class="preview-changes-header">
{{ 'swapDiffHeading' | translate }}
</h1>
<h1 *ngIf="(swapForm?.controls)['multiPhase']?.value" class="preview-changes-header">
{{ 'phaseTwoChangesHeading' | translate }}
</h1>
<div class="help-text-container">
{{ 'swapChangesInfoText' | translate }}
</div>
<swap-diff-table
[loading]="swapForm?.pending || (swapForm?.valid && loadingDiffs)"
[invalid]="!swapForm?.pending && !swapForm?.valid"
[loadedOrFailed]="!swapForm?.pending && swapForm?.valid && !loadingDiffs"
[diffs]="slotsDiffs"
[showToggle]="true"
oldValueHeading="slotsDiff_oldValueHeader"
newValueHeading="slotsDiff_newValueHeader"
>
</swap-diff-table>
</div>
<div *ngIf="showPhase2Controls" class="controls-container revert-dropdown-container">
<div class="control-container">
<div class="control-label">
{{ 'swapActionLabel' | translate }}
</div>
<div>
<drop-down
[ariaLabel]="'swapActionLabel' | translate"
[control]="!!swapForm ? swapForm.controls['revertSwap'] : null"
[options]="phase2DropDownOptions"
[highlightDirty]="false"
>
</drop-down>
</div>
</div>
</div>
</div>
</div>
<div class="footer">
<div *ngIf="progressMessage" class="progress-container">
<info-box [typeClass]="progressMessageClass" [infoText]="progressMessage"> </info-box>
</div>
<div class="buttons-container">
<button
*ngIf="!showPhase2Controls"
class="custom-button"
(click)="executePhase1()"
[disabled]="executeButtonDisabled || !swapForm || swapForm.pending || !swapForm.valid"
>
{{ (swapForm && swapForm.controls['multiPhase'].value ? 'startSwap' : 'swap') | translate }}
</button>
<button
*ngIf="showPhase2Controls"
class="custom-button"
[disabled]="executeButtonDisabled || !swapForm || swapForm.pending || !swapForm.valid"
(click)="executePhase2()"
>
{{
(swapForm && swapForm.controls['revertSwap'].value === stage2OptionData.CancelSwap ? 'cancelSwap' : 'completeSwap') | translate
}}
</button>
<button class="custom-button" [disabled]="swapping" (click)="closePanel()">
{{ 'close' | translate }}
</button>
</div>
</div>
</div>
| projectkudu/AzureFunctions | client/src/app/site/slots/swap-slots/swap-slots.component.html | HTML | apache-2.0 | 10,192 |
package com.indeed.util.mmap;
import junit.framework.TestCase;
import java.io.File;
import java.nio.ByteOrder;
import java.nio.channels.FileChannel;
/** @author goodwin */
public class CharArrayTest extends TestCase {
int length = 10240;
int size = 4; // bytes
int maxValue = (int) Math.pow(2, size * 8);
CharArray[] charArrays;
public void setUp() throws Exception {
File file = File.createTempFile("tmp", "", new File("."));
// noinspection ResultOfMethodCallIgnored
file.deleteOnExit();
charArrays = new CharArray[3];
charArrays[0] = new HeapMemory(length * size, ByteOrder.LITTLE_ENDIAN).charArray(0, length);
charArrays[1] =
new MMapBuffer(
file,
0,
length * size,
FileChannel.MapMode.READ_WRITE,
ByteOrder.LITTLE_ENDIAN)
.memory()
.charArray(0L, length);
charArrays[2] =
new NativeBuffer(length * size, ByteOrder.LITTLE_ENDIAN)
.memory()
.charArray(0L, length);
}
public void testByteArray() throws Exception {
for (CharArray charArray : charArrays) {
assertEquals(length, charArray.length());
charArray.set(0, (char) 0);
charArray.set(1, (char) 1);
charArray.set(2, (char) 2);
assertEquals(0, charArray.get(0));
assertEquals(1, charArray.get(1));
assertEquals(2, charArray.get(2));
assertEquals(length, charArray.length());
charArray.set(3, new char[] {3, 4});
assertEquals(3, charArray.get(3));
charArray.set(5, new char[] {0, 1, 2, 3, 4, 5, 6}, 5, 2);
for (int i = 7; i < length; i++) {
charArray.set(i, (char) i);
}
for (int i = 0; i < length; i++) {
int value = i % maxValue;
if (value >= maxValue / 2) {
value = value - maxValue;
}
assertEquals(value, charArray.get(i));
}
for (int i = 0; i < length - 8; i++) {
char[] bytes = new char[8];
charArray.get(i, bytes);
for (int j = 0; j < 8; j++) {
int value = (i + j) % maxValue;
if (value >= maxValue / 2) {
value = value - maxValue;
}
assertEquals(value, bytes[j]);
}
}
CharArray second = charArray.slice(2, length - 2);
assertEquals(2, second.get(0));
}
}
public void testThrownExceptions() {
for (CharArray charArray : charArrays) {
try {
charArray.set(-1, (char) 1);
fail();
} catch (IndexOutOfBoundsException success) {
}
try {
charArray.set(-1, new char[4], 0, 2);
fail();
} catch (IndexOutOfBoundsException success) {
}
try {
charArray.set(-1, new char[2]);
fail();
} catch (IndexOutOfBoundsException success) {
}
try {
charArray.get(-1);
fail();
} catch (IndexOutOfBoundsException success) {
}
try {
charArray.get(-1, new char[4], 0, 2);
fail();
} catch (IndexOutOfBoundsException success) {
}
try {
charArray.get(-1, new char[4], 0, 2);
fail();
} catch (IndexOutOfBoundsException success) {
}
try {
charArray.slice(-1, length);
fail();
} catch (IndexOutOfBoundsException success) {
}
}
}
}
| indeedeng/util | mmap/src/test/java/com/indeed/util/mmap/CharArrayTest.java | Java | apache-2.0 | 4,059 |
/*
* Copyright 2000-2016 Vaadin Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.vaadin.shared.ui.ui;
import com.vaadin.shared.communication.ClientRpc;
public interface PageClientRpc extends ClientRpc {
public void reload();
}
| Legioth/vaadin | shared/src/main/java/com/vaadin/shared/ui/ui/PageClientRpc.java | Java | apache-2.0 | 763 |
/*
* Copyright 2015 Adaptris Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.adaptris.core.jms.activemq;
import static com.adaptris.core.jms.MessageTypeTranslatorCase.addMetadata;
import static com.adaptris.core.jms.MessageTypeTranslatorCase.addProperties;
import static com.adaptris.core.jms.MessageTypeTranslatorCase.assertJmsProperties;
import static com.adaptris.core.jms.MessageTypeTranslatorCase.assertMetadata;
import java.io.ByteArrayInputStream;
import java.util.ArrayList;
import java.util.List;
import javax.jms.Message;
import javax.jms.Session;
import org.apache.activemq.ActiveMQSession;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.adaptris.core.AdaptrisMessage;
import com.adaptris.core.AdaptrisMessageFactory;
import com.adaptris.core.ConfiguredProduceDestination;
import com.adaptris.core.DefaultMessageFactory;
import com.adaptris.core.StandaloneProducer;
import com.adaptris.core.jms.JmsConnection;
import com.adaptris.core.jms.JmsConstants;
import com.adaptris.core.jms.JmsProducer;
import com.adaptris.core.jms.JmsProducerExample;
import com.adaptris.core.jms.JmsProducerImpl;
import com.adaptris.core.jms.MessageTypeTranslatorImp;
@SuppressWarnings("deprecation")
public class BlobMessageTranslatorTest extends JmsProducerExample {
private transient Log log = LogFactory.getLog(this.getClass());
private static final String INPUT = "Quick zephyrs blow, vexing daft Jim";
public BlobMessageTranslatorTest(String name) {
super(name);
}
@Override
protected void setUp() throws Exception {
super.setUp();
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
}
private Message createMessage(Session session) throws Exception {
return ((ActiveMQSession) session).createBlobMessage(new ByteArrayInputStream(INPUT.getBytes()));
}
public void testMoveMetadataJmsMessageToAdaptrisMessage() throws Exception {
MessageTypeTranslatorImp trans = new BlobMessageTranslator();
EmbeddedActiveMq activeMqBroker = new EmbeddedActiveMq();
JmsConnection conn = null;
try {
activeMqBroker.start();
conn = activeMqBroker.getJmsConnection(new BasicActiveMqImplementation());
start(conn);
Session session = conn.createSession(false, Session.CLIENT_ACKNOWLEDGE);
Message jmsMsg = createMessage(session);
addProperties(jmsMsg);
trans.registerSession(session);
trans.registerMessageFactory(new DefaultMessageFactory());
start(trans);
AdaptrisMessage msg = trans.translate(jmsMsg);
assertMetadata(msg);
}
finally {
stop(trans);
stop(conn);
activeMqBroker.destroy();
}
}
public void testMoveJmsHeadersJmsMessageToAdaptrisMessage() throws Exception {
MessageTypeTranslatorImp trans = new BlobMessageTranslator();
EmbeddedActiveMq activeMqBroker = new EmbeddedActiveMq();
JmsConnection conn = null;
try {
activeMqBroker.start();
conn = activeMqBroker.getJmsConnection(new BasicActiveMqImplementation());
start(conn);
Session session = conn.createSession(false, Session.CLIENT_ACKNOWLEDGE);
Message jmsMsg = createMessage(session);
jmsMsg.setJMSCorrelationID("ABC");
jmsMsg.setJMSDeliveryMode(1);
jmsMsg.setJMSPriority(4);
addProperties(jmsMsg);
long timestamp = System.currentTimeMillis();
jmsMsg.setJMSTimestamp(timestamp);
trans.registerSession(session);
trans.registerMessageFactory(new DefaultMessageFactory());
trans.setMoveJmsHeaders(true);
start(trans);
AdaptrisMessage msg = trans.translate(jmsMsg);
assertMetadata(msg);
assertEquals("ABC", msg.getMetadataValue(JmsConstants.JMS_CORRELATION_ID));
assertEquals("1", msg.getMetadataValue(JmsConstants.JMS_DELIVERY_MODE));
assertEquals("4", msg.getMetadataValue(JmsConstants.JMS_PRIORITY));
assertEquals(String.valueOf(timestamp), msg.getMetadataValue(JmsConstants.JMS_TIMESTAMP));
}
finally {
stop(trans);
stop(conn);
activeMqBroker.destroy();
}
}
public void testMoveMetadataAdaptrisMessageToJmsMessage() throws Exception {
MessageTypeTranslatorImp trans = new BlobMessageTranslator();
EmbeddedActiveMq activeMqBroker = new EmbeddedActiveMq();
JmsConnection conn = null;
try {
activeMqBroker.start();
conn = activeMqBroker.getJmsConnection(new BasicActiveMqImplementation());
start(conn);
AdaptrisMessage msg = AdaptrisMessageFactory.getDefaultInstance().newMessage();
addMetadata(msg);
Session session = conn.createSession(false, Session.CLIENT_ACKNOWLEDGE);
trans.registerSession(session);
trans.registerMessageFactory(new DefaultMessageFactory());
start(trans);
Message jmsMsg = trans.translate(msg);
assertJmsProperties(jmsMsg);
}
finally {
stop(trans);
stop(conn);
activeMqBroker.destroy();
}
}
public void testBug895() throws Exception {
MessageTypeTranslatorImp trans = new BlobMessageTranslator();
EmbeddedActiveMq activeMqBroker = new EmbeddedActiveMq();
JmsConnection conn = null;
try {
activeMqBroker.start();
conn = activeMqBroker.getJmsConnection(new BasicActiveMqImplementation());
start(conn);
AdaptrisMessage msg = AdaptrisMessageFactory.getDefaultInstance().newMessage();
msg.addMetadata(JmsConstants.JMS_PRIORITY, "9");
msg.addMetadata(JmsConstants.JMS_TYPE, "idaho");
Session session = conn.createSession(false, Session.CLIENT_ACKNOWLEDGE);
trans.setMoveJmsHeaders(true);
trans.registerSession(session);
trans.registerMessageFactory(new DefaultMessageFactory());
start(trans);
Message jmsMsg = trans.translate(msg);
assertNotSame("JMS Priorities should be different", jmsMsg.getJMSPriority(), 9);
assertEquals("JMSType should be equal", "idaho", jmsMsg.getJMSType());
}
finally {
stop(trans);
stop(conn);
activeMqBroker.destroy();
}
}
private static StandaloneProducer buildStandaloneProducer(JmsConnection c, JmsProducer p) {
p.setDestination(new ConfiguredProduceDestination("jms:queue:MyQueueName?priority=4"));
p.setMessageTranslator(new BlobMessageTranslator("metadataKeyContainingTheUrlReference"));
c.setUserName("BrokerUsername");
c.setPassword("BrokerPassword");
c.setVendorImplementation(new BasicActiveMqImplementation(BasicActiveMqImplementationTest.PRIMARY));
return new StandaloneProducer(c, p);
}
@Override
protected List retrieveObjectsForSampleConfig() {
ArrayList result = new ArrayList();
result.add(buildStandaloneProducer(new JmsConnection(), new JmsProducer()));
return result;
}
/**
* @see com.adaptris.core.ExampleConfigCase#retrieveObjectForSampleConfig()
*/
@Override
protected Object retrieveObjectForSampleConfig() {
return null;
}
@Override
protected String createBaseFileName(Object object) {
JmsProducerImpl p = (JmsProducerImpl) ((StandaloneProducer) object).getProducer();
return super.createBaseFileName(object) + "-" + p.getMessageTranslator().getClass().getSimpleName();
}
}
| mcwarman/interlok | adapter/src/test/java/com/adaptris/core/jms/activemq/BlobMessageTranslatorTest.java | Java | apache-2.0 | 7,785 |
Chrome extension: served locally, run in browser UI, observe pages / integrate with browsing (or separate window).
Chrome packaged app (a.k.a. "Chrome App"): served locally, run in own window.
Firefox addon: served locally, run in browser UI, observe pages / integrate with browsing (or separate window).
Firefox packaged app (a.k.a. "Open Web App"): served locally, run in own window.
| graydon/stxt | pkg/README.md | Markdown | apache-2.0 | 387 |
package main.service;
import java.util.Arrays;
import java.util.List;
import org.javokapi;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import main.factory.OkapiFactory;
/**
* Sadra
* Created by Sadra on 1/18/16.
*/
@Service
public class OkapiService {
javokapi okapiInterface = null;
Utils okapiUtils = null;
public OkapiService () {
OkapiFactory okapiFactory = new OkapiFactory ();
okapiInterface = okapiFactory.getInstance();
okapiUtils = new Utils();
}
public List<String> listDatabase() {
//System.out.println("in list Database...");
String dbList = okapiInterface.infoDB();
System.out.println(dbList);
String[] response = dbList.split("name");
return Arrays.asList(response);
}
public String setDatabase(String dbName) {
//System.out.println("DB name: " + dbName);
System.out.println(okapiInterface.displayStemFunctions());
okapiInterface.chooseDB(dbName); //CHOOSE THE DATABASE UESR INPUTTED
okapiInterface.deleteAllSets(); //CLEAR ALL EXISTING DATASETS IF ANY
return "database name successfully set to " + dbName;
}
public String parseTerms(String parseTerms) {
String okapiParsedTerms = okapiInterface.superParse("", parseTerms);
System.out.println("Parsed term(s): " + okapiParsedTerms); //OUTPUT THE PARSED TERMS
return "parsed terms: " + okapiParsedTerms;
}
public String stemTerm(String term) {
String stemmedWord = okapiInterface.stem("psstem", term); //FINDS THE ROOT OF THE WORD (i.e. 'running' becomes 'run')
System.out.println("Stemmed word: " + stemmedWord);
return stemmedWord.replace("t=", ""); //Trims the t= produced from the stem() function
}
public String searchTerm(String term) {
String searchResult = okapiInterface.find("1", "0", "DEFAULT", term); //QUERIES OKAPI WITH THE SEARCH WORD ENTERED BY USER
System.out.println("search result: " + searchResult);
return searchResult;
}
public String displayResultSet(String searchWord) {
System.out.println("Your query returned the following results");
String results = "";
String stemmedSearchWord=okapiInterface.stem("psstem",searchWord); //FINDS THE ROOT OF THE WORD (i.e. 'running' becomes 'run')
String trimString = stemmedSearchWord.replace( "t=", ""); //Trims the t= produced from the stem() function
stemmedSearchWord = trimString;
System.out.println("Stemmed Search Word: " + stemmedSearchWord);
String found = null;
String np = null;
found = okapiInterface.find("1","0","DEFAULT", stemmedSearchWord); //QUERIES OKAPI WITH THE SEARCH WORD ENTERED BY USER
System.out.println("Results: "+ found);
String splitFound = null;
np = okapiUtils.findNP(found,stemmedSearchWord); //SEE METHOD findNP() BELOW
int npInt = Integer.parseInt(np);
String weight = okapiInterface.weight("2",np,"0","0","4","5");
System.out.println("weight()= "+ weight); //OUTPUT THE WEIGHT FOUND BY THE weight() FUNCTION
System.out.println("setFind()= " + okapiInterface.setFind("0", weight,"")); //OUTPUT THE SET
System.out.println(okapiInterface.displayStemFunctions());
//DISPLAYS ALL THE RECORDS FOUND
System.out.println("\n\nYour query returned the following results");
//for (int i=0; i<npInt; i++){
for (int i=0; i<99; i++) {
//System.out.println("Record #" + i + ": "+okapiInterface.showSetRecord("100", "1", Integer.toString(i),"0"));
System.out.println("Record #" + i + ": "+okapiInterface.showSetRecord("1", "1", Integer.toString(i),"0"));
results += "Record #" + i + ": " +okapiInterface.showSetRecord("1", "1", Integer.toString(i),"0") + "\n";
}
System.out.println("Record #" + results);
return results;
}
public String getWeigh(String term) {
String results = "";
String stemmedSearchWord=okapiInterface.stem("psstem",term); //FINDS THE ROOT OF THE WORD (i.e. 'running' becomes 'run')
String trimString = stemmedSearchWord.replace( "t=", ""); //Trims the t= produced from the stem() function
stemmedSearchWord = trimString;
System.out.println("Stemmed Search Word: " + stemmedSearchWord);
String found = null;
String np = null;
found = okapiInterface.find("1","0","DEFAULT", stemmedSearchWord); //QUERIES OKAPI WITH THE SEARCH WORD ENTERED BY USER
System.out.println("Results: "+ found);
String splitFound = null;
np = okapiUtils.findNP(found,stemmedSearchWord); //SEE METHOD findNP() BELOW
int npInt = Integer.parseInt(np);
String weight = okapiInterface.weight("2",np,"0","0","4","5");
System.out.println("weight()= "+ weight); //OUTPUT THE WEIGHT FOUND BY THE weight() FUNCTION
System.out.println("setFind()= " + okapiInterface.setFind("0", weight,"")); //OUTPUT THE SET
System.out.println(okapiInterface.displayStemFunctions());
return weight;
}
}
| YorkUIRLab/okapi-web-service | src/main/java/main/service/OkapiService.java | Java | apache-2.0 | 5,236 |
package iam
import (
"fmt"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/iam"
// "github.com/quintilesims/layer0/api/config"
"strings"
"github.com/quintilesims/layer0/common/aws/provider"
)
type Provider interface {
UploadServerCertificate(string, string, string, string, *string) (*ServerCertificateMetadata, error)
ListCertificates() ([]*ServerCertificateMetadata, error)
GetUser(username *string) (*User, error)
DeleteServerCertificate(certName string) error
CreateRole(roleName, servicePrincipal string) (*Role, error)
GetRole(roleName string) (*Role, error)
PutRolePolicy(roleName, policy string) error
GetAccountId() (string, error)
DeleteRole(roleName string) error
DeleteRolePolicy(roleName, policyName string) error
ListRolePolicies(roleName string) ([]*string, error)
ListRoles() ([]*string, error)
}
type iamInternal interface {
UploadServerCertificate(input *iam.UploadServerCertificateInput) (output *iam.UploadServerCertificateOutput, err error)
ListServerCertificates(*iam.ListServerCertificatesInput) (*iam.ListServerCertificatesOutput, error)
DeleteServerCertificate(input *iam.DeleteServerCertificateInput) (*iam.DeleteServerCertificateOutput, error)
GetUser(input *iam.GetUserInput) (*iam.GetUserOutput, error)
PutRolePolicy(*iam.PutRolePolicyInput) (*iam.PutRolePolicyOutput, error)
CreateRole(*iam.CreateRoleInput) (*iam.CreateRoleOutput, error)
GetRole(*iam.GetRoleInput) (*iam.GetRoleOutput, error)
DeleteRole(*iam.DeleteRoleInput) (*iam.DeleteRoleOutput, error)
DeleteRolePolicy(*iam.DeleteRolePolicyInput) (*iam.DeleteRolePolicyOutput, error)
ListRolePolicies(*iam.ListRolePoliciesInput) (*iam.ListRolePoliciesOutput, error)
ListRoles(*iam.ListRolesInput) (*iam.ListRolesOutput, error)
}
type IAM struct {
credProvider provider.CredProvider
region string
Connect func() (iamInternal, error)
}
type ServerCertificateMetadata struct {
*iam.ServerCertificateMetadata
}
func NewServerCertificateMetadata(name, arn string) *ServerCertificateMetadata {
return &ServerCertificateMetadata{
&iam.ServerCertificateMetadata{
ServerCertificateName: aws.String(name),
Arn: aws.String(arn),
},
}
}
type User struct {
*iam.User
}
func NewUser() *User {
return &User{&iam.User{}}
}
type Role struct {
*iam.Role
}
func Connect(credProvider provider.CredProvider, region string) (iamInternal, error) {
connection, err := provider.GetIAMConnection(credProvider, region)
if err != nil {
return nil, err
}
return connection, nil
}
func NewIAM(credProvider provider.CredProvider, region string) (Provider, error) {
iam := IAM{
credProvider: credProvider,
region: region,
Connect: func() (iamInternal, error) { return Connect(credProvider, region) },
}
_, err := iam.Connect()
if err != nil {
return nil, err
}
return &iam, nil
}
func (this *IAM) UploadServerCertificate(name, path, body, pk string, optionalChain *string) (*ServerCertificateMetadata, error) {
input := &iam.UploadServerCertificateInput{
ServerCertificateName: aws.String(name),
CertificateBody: aws.String(body),
CertificateChain: optionalChain,
PrivateKey: aws.String(pk),
Path: aws.String(path),
}
connection, err := this.Connect()
if err != nil {
return nil, err
}
output, err := connection.UploadServerCertificate(input)
if err != nil {
return nil, err
}
metadata := output.ServerCertificateMetadata
return &ServerCertificateMetadata{metadata}, nil
}
func (this *IAM) ListCertificates() ([]*ServerCertificateMetadata, error) {
connection, err := this.Connect()
if err != nil {
return nil, err
}
output, err := connection.ListServerCertificates(&iam.ListServerCertificatesInput{})
if err != nil {
return nil, err
}
certs := []*ServerCertificateMetadata{}
for _, metadata := range output.ServerCertificateMetadataList {
certs = append(certs, &ServerCertificateMetadata{metadata})
}
return certs, nil
}
func (this *IAM) GetUser(username *string) (*User, error) {
input := &iam.GetUserInput{
UserName: username,
}
connection, err := this.Connect()
if err != nil {
return nil, err
}
output, err := connection.GetUser(input)
if err != nil {
return nil, err
}
var user *User
if output.User != nil {
user = &User{output.User}
}
return user, nil
}
func (this *IAM) DeleteServerCertificate(certName string) error {
input := &iam.DeleteServerCertificateInput{
ServerCertificateName: aws.String(certName),
}
connection, err := this.Connect()
if err != nil {
return err
}
_, err = connection.DeleteServerCertificate(input)
return err
}
func (this *IAM) CreateRole(roleName, servicePrincipal string) (*Role, error) {
input := &iam.CreateRoleInput{
AssumeRolePolicyDocument: aws.String(fmt.Sprintf(`{"Version":"2008-10-17","Statement":[{"Sid":"","Effect":"Allow","Principal":{"Service":["%s"]},"Action":["sts:AssumeRole"]}]}`, servicePrincipal)),
RoleName: &roleName,
}
connection, err := this.Connect()
if err != nil {
return nil, err
}
out, err := connection.CreateRole(input)
if err != nil {
return nil, err
}
return &Role{out.Role}, nil
}
func (this *IAM) GetRole(roleName string) (*Role, error) {
input := &iam.GetRoleInput{
RoleName: &roleName,
}
connection, err := this.Connect()
if err != nil {
return nil, err
}
output, err := connection.GetRole(input)
if err != nil {
return nil, err
}
return &Role{output.Role}, nil
}
func (this *IAM) DeleteRole(roleName string) error {
input := &iam.DeleteRoleInput{
RoleName: &roleName,
}
connection, err := this.Connect()
if err != nil {
return err
}
_, err = connection.DeleteRole(input)
return err
}
func (this *IAM) DeleteRolePolicy(roleName, policyName string) error {
input := &iam.DeleteRolePolicyInput{
RoleName: &roleName,
PolicyName: &policyName,
}
connection, err := this.Connect()
if err != nil {
return err
}
_, err = connection.DeleteRolePolicy(input)
return err
}
func (this *IAM) ListRolePolicies(roleName string) ([]*string, error) {
input := &iam.ListRolePoliciesInput{
RoleName: &roleName,
}
connection, err := this.Connect()
if err != nil {
return nil, err
}
output, err := connection.ListRolePolicies(input)
if err != nil {
return nil, err
}
return output.PolicyNames, nil
}
func (this *IAM) ListRoles() ([]*string, error) {
input := &iam.ListRolesInput{}
connection, err := this.Connect()
if err != nil {
return nil, err
}
output, err := connection.ListRoles(input)
if err != nil {
return nil, err
}
roles := []*string{}
for _, role := range output.Roles {
roles = append(roles, role.RoleName)
}
return roles, nil
}
func (this *IAM) PutRolePolicy(roleName, policy string) error {
input := &iam.PutRolePolicyInput{
PolicyName: &roleName,
PolicyDocument: &policy,
RoleName: &roleName,
}
connection, err := this.Connect()
if err != nil {
return err
}
_, err = connection.PutRolePolicy(input)
return err
}
func (this *IAM) GetAccountId() (string, error) {
connection, err := this.Connect()
if err != nil {
return "", err
}
out, err := connection.GetUser(nil)
if err != nil {
return "", fmt.Errorf("[ERROR] Failed to get current IAM user: %s", err.Error())
}
// Sample ARN: "arn:aws:iam::123456789012:user/layer0/l0/bootstrap-user-user-ABCDEFGHIJKL"
return strings.Split(*out.User.Arn, ":")[4], nil
}
| quintilesims/layer0 | common/aws/iam/iam.go | GO | apache-2.0 | 7,447 |
package ddevapp_test
import (
"fmt"
"github.com/drud/ddev/pkg/ddevapp"
"github.com/drud/ddev/pkg/nodeps"
"github.com/drud/ddev/pkg/testcommon"
"github.com/drud/ddev/pkg/util"
asrt "github.com/stretchr/testify/assert"
"strings"
"testing"
"time"
)
//TestSetInstrumentationAppTags checks to see that tags are properly set
//and tries to make sure no leakage happens with URLs or other
//tags that we don't want to see.
func TestSetInstrumentationAppTags(t *testing.T) {
assert := asrt.New(t)
site := TestSites[0]
runTime := util.TimeTrack(time.Now(), fmt.Sprintf("%s %s", site.Name, t.Name()))
testcommon.ClearDockerEnv()
app := new(ddevapp.DdevApp)
err := app.Init(site.Dir)
assert.NoError(err)
t.Cleanup(func() {
_ = app.Stop(true, false)
})
app.SetInstrumentationAppTags()
// Make sure that none of the "url" items in app.desc are being reported
for k := range nodeps.InstrumentationTags {
assert.NotContains(strings.ToLower(k), "url")
}
for _, unwanted := range []string{"approot", "hostname", "hostnames", "name", "router_status_log", "shortroot"} {
assert.Empty(nodeps.InstrumentationTags[unwanted])
}
// Make sure that expected attributes come through
for _, wanted := range []string{"database_type", "dbimg", "dbaimg", "nfs_mount_enabled", "ProjectID", "php_version", "router_http_port", "router_https_port", "router_status", "ssh_agent_status", "status", "type", "webimg", "webserver_type"} {
assert.NotEmpty(nodeps.InstrumentationTags[wanted], "tag '%s' was not found and it should have been", wanted)
}
runTime()
}
| rfay/ddev | pkg/ddevapp/instrumentation_test.go | GO | apache-2.0 | 1,567 |
/*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat, Inc., and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.weld.tests.enterprise;
import jakarta.inject.Qualifier;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.ElementType.TYPE;
@Qualifier
@Retention(RetentionPolicy.RUNTIME)
@Target({FIELD, METHOD, TYPE, PARAMETER})
public @interface DAO {
}
| weld/core | tests-arquillian/src/test/java/org/jboss/weld/tests/enterprise/DAO.java | Java | apache-2.0 | 1,309 |
package com.climate.mirage.app;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import com.climate.mirage.Mirage;
public class SimpleLoadActivity extends AppCompatActivity {
private ImageView iv;
private Button button1, button2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.row);
iv = (ImageView)findViewById(R.id.imageView);
button1 = (Button)findViewById(R.id.button1);
button2 = (Button)findViewById(R.id.button2);
button1.setText("Load Puppy");
button2.setText("Load Cat");
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Mirage.get(SimpleLoadActivity.this)
.load(Images.PUPPY)
.into(iv)
.placeHolder(R.drawable.mirage_ic_launcher)
.error(R.drawable.ic_error)
.fade()
.go();
}
});
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Mirage.get(SimpleLoadActivity.this)
.load(Images.CAT)
.into(iv)
.placeHolder(R.drawable.mirage_ic_launcher)
.error(R.drawable.ic_error)
.fade()
.go();
}
});
}
} | TheClimateCorporation/mirage | samples/src/main/java/com/climate/mirage/app/SimpleLoadActivity.java | Java | apache-2.0 | 1,315 |
use rayon::par_iter::*;
use self::page::Page;
use super::{ReportMemory, PAGE_SIZE, PAGE_WIDTH};
pub use self::page::{Cell, CellType};
mod cell;
mod page;
mod zorder;
pub struct Grid {
pages: Vec<Page>,
dimension: u32,
pages_per_side: u32,
}
impl ReportMemory for Grid {
fn memory(&self) -> u32 {
self.pages
.into_par_iter()
.map(|page| page.memory())
.sum()
}
}
impl Grid {
pub fn new(size: u32, density: f32, seed: &[usize]) -> Grid {
// todo assert size
let num_pages = size * size;
info!("Creating grid with {} pages per side ({} pages total), each with {} cells ({} \
total cells)",
size,
num_pages,
PAGE_SIZE,
num_pages * PAGE_SIZE);
let mut pages = Vec::with_capacity(num_pages as usize);
for i in 0..num_pages {
let offset_x = (i as u32 % size) * PAGE_WIDTH;
let offset_y = (i as u32 / size) * PAGE_WIDTH;
debug!("Offsets: ({},{})", offset_x, offset_y);
pages.push(Page::new(density, offset_x, offset_y, seed));
}
Grid {
pages: pages,
dimension: size * PAGE_WIDTH,
pages_per_side: size,
}
}
pub fn grow(&mut self) {
loop {
let active_cells = self.grow_step();
if active_cells == 0 {
break;
}
}
}
pub fn grow_step(&mut self) -> u32 {
debug!("Growing Pages...");
self.pages
.par_iter_mut()
.weight_max()
.for_each(|page| page.grow());;
let active_cells = self.pages
.iter()
.map(|page| page.get_active_cell_count())
.fold(0u32, |acc, x| acc + x);
for i in 0..self.pages.len() {
let changes = self.pages[i].get_remote_changes().clone();
if changes.is_empty() {
continue;
}
debug!("Remote changes to process: {}", changes.len());
for c in changes {
debug!("Absolute change position: ({},{})", c.x, c.y);
if !(c.x > 0 && c.x < self.dimension && c.y > 0 && c.y < self.dimension) {
debug!("x > 1 {}", c.x > 0);
debug!("x < dimension - 1{}", c.x < self.dimension);
debug!("y > 1 {}", c.y > 0);
debug!("y < dimension - 1 {}", c.y < self.dimension);
continue;
}
self.get_mut_page(c.x, c.y)
.add_change(c.x % PAGE_WIDTH,
c.y % PAGE_WIDTH,
c.cell,
c.travel_direction,
c.stim);
}
}
debug!("Active cells after growth: {}", active_cells);
debug!("Updating Pages...");
self.pages
.par_iter_mut()
.weight_max()
.for_each(|page| page.update());
active_cells
}
pub fn signal(&mut self) {
loop {
let active_cells = self.signal_step();
if active_cells == 0 {
break;
}
}
}
pub fn signal_step(&mut self) -> u32 {
debug!("Processing signals...");
self.pages
.par_iter_mut()
.weight_max()
.for_each(|page| page.signal());
for i in 0..self.pages.len() {
let signals = self.pages[i].get_remote_signal().clone();
if signals.is_empty() {
continue;
}
debug!("Remote signal to process: {}", signals.len());
for s in signals {
debug!("Absolute signal position: ({},{})", s.x, s.y);
if !(s.x > 0 && s.x < self.dimension && s.y > 0 && s.y < self.dimension) {
debug!("x > 1 {}", s.x > 0);
debug!("x < dimension - 1{}", s.x < self.dimension);
debug!("y > 1 {}", s.y > 0);
debug!("y < dimension - 1 {}", s.y < self.dimension);
continue;
}
self.get_mut_page(s.x, s.y)
.add_signal(s.x % PAGE_WIDTH, s.y % PAGE_WIDTH, s.strength, s.stim);
}
}
debug!("Updating Pages...");
self.pages
.par_iter_mut()
.weight_max()
.map(|page| page.update_signal())
.sum()
}
fn get_mut_page(&mut self, x: u32, y: u32) -> &mut Page {
let i = x / PAGE_WIDTH + ((y / PAGE_WIDTH) * self.pages_per_side);
debug!("get_mut_page: ({},{}) -> {}", x, y, i);
&mut self.pages[i as usize]
}
pub fn get_cell(&self, x: u32, y: u32) -> &Cell {
let i = x / PAGE_WIDTH + ((y / PAGE_WIDTH) * self.pages_per_side);
self.pages[i as usize].get_cell(x % PAGE_WIDTH, y % PAGE_WIDTH)
}
fn get_mut_cell(&mut self, x: u32, y: u32) -> &mut Cell {
let i = x / PAGE_WIDTH + ((y / PAGE_WIDTH) * self.pages_per_side);
self.pages[i as usize].get_mut_cell(x % PAGE_WIDTH, y % PAGE_WIDTH)
}
pub fn set_input(&mut self, x: u32, y: u32, sig: u8) {
self.get_mut_page(x, y).set_input(x % PAGE_WIDTH, y % PAGE_WIDTH, sig);
}
}
impl Default for Grid {
fn default() -> Grid {
Grid::new(10, 0.05, &[1, 2, 3, 4])
}
}
#[cfg(test)]
mod test {
use super::Grid;
#[test]
fn grid_default_params() {
let _ = Grid::default();
}
}
| polyfractal/cajal | src/grid/mod.rs | Rust | apache-2.0 | 5,709 |
## How to reduce CPU usage in VB.NET using ByteScout BarCode Reader SDK
### How to reduce CPU usage in VB.NET
Source code documentation samples provide quick and easy way to add a required functionality into your application. What is ByteScout BarCode Reader SDK? It is the SDK for reading of barcodes from PDF, images and live camera or video. Almost every common type like Code 39, Code 128, GS1, UPC, QR Code, Datamatrix, PDF417 and many others are supported. Supports noisy and defective images and docs. Includes optional documents splitter and merger for pdf and tiff based on found barcodess. Batch mode is supported for superior performance using multiple threads. Decoded values are easily exported to JSON, CSV, XML and to custom format. It can help you to reduce CPU usage in your VB.NET application.
VB.NET code samples for VB.NET developers help to speed up coding of your application when using ByteScout BarCode Reader SDK. In your VB.NET project or application you may simply copy & paste the code and then run your app! This basic programming language sample code for VB.NET will do the whole work for you to reduce CPU usage.
ByteScout free trial version is available for download from our website. It includes all these programming tutorials along with source code samples.
## REQUEST FREE TECH SUPPORT
[Click here to get in touch](https://bytescout.zendesk.com/hc/en-us/requests/new?subject=ByteScout%20BarCode%20Reader%20SDK%20Question)
or just send email to [support@bytescout.com](mailto:support@bytescout.com?subject=ByteScout%20BarCode%20Reader%20SDK%20Question)
## ON-PREMISE OFFLINE SDK
[Get Your 60 Day Free Trial](https://bytescout.com/download/web-installer?utm_source=github-readme)
[Explore SDK Docs](https://bytescout.com/documentation/index.html?utm_source=github-readme)
[Sign Up For Online Training](https://academy.bytescout.com/)
## ON-DEMAND REST WEB API
[Get your API key](https://pdf.co/documentation/api?utm_source=github-readme)
[Explore Web API Documentation](https://pdf.co/documentation/api?utm_source=github-readme)
[Explore Web API Samples](https://github.com/bytescout/ByteScout-SDK-SourceCode/tree/master/PDF.co%20Web%20API)
## VIDEO REVIEW
[https://www.youtube.com/watch?v=EARSPJFIJMU](https://www.youtube.com/watch?v=EARSPJFIJMU)
<!-- code block begin -->
##### ****Program.vb:**
```
Imports Bytescout.BarCodeReader
Class Program
Friend Shared Sub Main(args As String())
' Barcode reader instance
Dim reader As New Reader()
reader.RegistrationName = "demo"
reader.RegistrationKey = "demo"
'If you are reading barcodes from PDF Then you may reduce CPU And RAM load Using the following approach:
'- instead of using All1D Or All2D barcode types, set it to the specific types you have in your documents Like PDF417 Or Code 39. You may set multiple barcode types if you need to
'- reduce PDF rendering resolution to 200-150 dpi (depends on your document)
'- set specific pages to read barcodes from. If you have barcodes on 2 first pages only then change the code to read barcodes from first 2 pages only.
'- if barcodes are always located / printed in the same corner then also specify the area to read from instead of whole page for scanning
' Input filename
Dim inputFileName As String = "barcode_multipage.pdf"
' Set specific barcode type to read
reader.BarcodeTypesToFind.Code128 = True
' Reduce PDF rendering resolution
reader.PDFRenderingResolution = 150
' Set specific area to read from
reader.CustomAreaLeft = 407
reader.CustomAreaTop = 494
reader.CustomAreaHeight = 605
reader.CustomAreaWidth = 999
' Set specific page to read from along with filename
reader.ReadFromPdfFilePage(inputFileName, 1, 1)
' Get all found barcodes
Dim barcodes As FoundBarcode() = reader.FoundBarcodes
' Display found barcodes
Console.WriteLine("Reading barcode(s) from PDF file...")
For Each barcode As FoundBarcode In barcodes
Console.WriteLine("Found Barcode - Type: '{0}', Value: '{1}'", barcode.Type, barcode.Value)
Next
' Cleanup
reader.Dispose()
Console.WriteLine()
Console.WriteLine("Press any key to continue.")
Console.ReadKey()
End Sub
End Class
```
<!-- code block end -->
<!-- code block begin -->
##### ****ReduceCPUUsage.VS2005.vbproj:**
```
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>8.0.50727</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{5F17DE51-EC94-4A5A-AF58-C4876D4BA652}</ProjectGuid>
<OutputType>Exe</OutputType>
<RootNamespace>ReduceCPUUsage</RootNamespace>
<AssemblyName>ReduceCPUUsage</AssemblyName>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG,TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.VisualBasic.Targets" />
<ItemGroup>
<Import Include="Microsoft.VisualBasic" />
<Import Include="System" />
<Reference Include="Bytescout.BarCodeReader, Version=8.20.0.1340, Culture=neutral, PublicKeyToken=f7dd1bd9d40a50eb, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>C:\Program Files\Bytescout BarCode Reader SDK\net2.00\Bytescout.BarCodeReader.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Data" />
<Reference Include="System.Drawing" />
<Reference Include="System.Xml" />
<Compile Include="Program.vb" />
<Content Include="barcode_multipage.pdf">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
</ItemGroup>
</Project>
```
<!-- code block end -->
<!-- code block begin -->
##### ****ReduceCPUUsage.VS2008.vbproj:**
```
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="3.5">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>9.0.30729</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{5F17DE51-EC94-4A5A-AF58-C4876D4BA652}</ProjectGuid>
<OutputType>Exe</OutputType>
<RootNamespace>ReduceCPUUsage</RootNamespace>
<AssemblyName>ReduceCPUUsage</AssemblyName>
<OldToolsVersion>2.0</OldToolsVersion>
<TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG,TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.VisualBasic.Targets" />
<ItemGroup>
<Import Include="Microsoft.VisualBasic" />
<Import Include="System" />
<Reference Include="Bytescout.BarCodeReader, Version=8.20.0.1340, Culture=neutral, PublicKeyToken=f7dd1bd9d40a50eb, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>C:\Program Files\Bytescout BarCode Reader SDK\net3.50\Bytescout.BarCodeReader.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Data" />
<Reference Include="System.Drawing" />
<Reference Include="System.Xml" />
<Compile Include="Program.vb" />
<Content Include="barcode_multipage.pdf">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
</ItemGroup>
</Project>
```
<!-- code block end -->
<!-- code block begin -->
##### ****ReduceCPUUsage.VS2010.vbproj:**
```
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>
</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{5F17DE51-EC94-4A5A-AF58-C4876D4BA652}</ProjectGuid>
<OutputType>Exe</OutputType>
<RootNamespace>ReduceCPUUsage</RootNamespace>
<AssemblyName>ReduceCPUUsage</AssemblyName>
<OldToolsVersion>3.5</OldToolsVersion>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG,TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.VisualBasic.Targets" />
<ItemGroup>
<Import Include="Microsoft.VisualBasic" />
<Import Include="System" />
<Reference Include="Bytescout.BarCodeReader, Version=8.20.0.1340, Culture=neutral, PublicKeyToken=f7dd1bd9d40a50eb, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>C:\Program Files\Bytescout BarCode Reader SDK\net4.00\Bytescout.BarCodeReader.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Data" />
<Reference Include="System.Drawing" />
<Reference Include="System.Xml" />
<Compile Include="Program.vb" />
<Content Include="barcode_multipage.pdf">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
</ItemGroup>
</Project>
```
<!-- code block end --> | bytescout/ByteScout-SDK-SourceCode | BarCode Reader SDK/VB.NET/Reduce CPU Usage/README.md | Markdown | apache-2.0 | 11,299 |
/*
* #%L
* GwtMaterial
* %%
* Copyright (C) 2015 - 2021 GwtMaterialDesign
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package gwt.material.design.client;
import com.google.gwt.core.client.EntryPoint;
public class MaterialWithoutResources implements EntryPoint {
@Override
public void onModuleLoad() {
}
}
| GwtMaterialDesign/gwt-material | gwt-material/src/main/java/gwt/material/design/client/MaterialWithoutResources.java | Java | apache-2.0 | 856 |
/*
* Copyright 2015 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hawkular.agent.monitor.log;
import java.util.List;
import org.hawkular.agent.monitor.scheduler.config.MonitoredEndpoint;
import org.jboss.logging.Logger;
import org.jboss.logging.Logger.Level;
import org.jboss.logging.annotations.Cause;
import org.jboss.logging.annotations.LogMessage;
import org.jboss.logging.annotations.Message;
import org.jboss.logging.annotations.MessageLogger;
import org.jboss.logging.annotations.ValidIdRange;
@MessageLogger(projectCode = "HAWKMONITOR")
@ValidIdRange(min = 10000, max = 19999)
public interface MsgLogger {
MsgLogger LOG = Logger.getMessageLogger(MsgLogger.class, "org.hawkular.agent.monitor");
@LogMessage(level = Level.INFO)
@Message(id = 10000, value = "Starting Hawkular Monitor service")
void infoStarting();
@LogMessage(level = Level.INFO)
@Message(id = 10001, value = "Stopping Hawkular Monitor service")
void infoStopping();
@LogMessage(level = Level.INFO)
@Message(id = 10002, value = "Hawkular Monitor subsystem is disabled; service will not be started")
void infoSubsystemDisabled();
@LogMessage(level = Level.INFO)
@Message(id = 10003, value = "JNDI binding [%s]: bound to object of type [%s]")
void infoBindJndiResource(String jndiName, String objectTypeName);
@LogMessage(level = Level.INFO)
@Message(id = 10004, value = "JNDI binding [%s]: unbound")
void infoUnbindJndiResource(String jndiName);
@LogMessage(level = Level.INFO)
@Message(id = 10005, value = "No diagnostics configuration - diagnostics will be disabled")
void infoNoDiagnosticsConfig();
@LogMessage(level = Level.INFO)
@Message(id = 10006, value = "There are no enabled metric sets")
void infoNoEnabledMetricsConfigured();
@LogMessage(level = Level.INFO)
@Message(id = 10007, value = "There are no enabled availability check sets")
void infoNoEnabledAvailsConfigured();
@LogMessage(level = Level.ERROR)
@Message(id = 10008, value = "A metric collection failed")
void errorMetricCollectionFailed(@Cause Throwable t);
@LogMessage(level = Level.ERROR)
@Message(id = 10009, value = "An availability check failed")
void errorAvailCheckFailed(@Cause Throwable t);
@LogMessage(level = Level.ERROR)
@Message(id = 10010, value = "Failed to store metric data: %s")
void errorFailedToStoreMetricData(@Cause Throwable t, String data);
@LogMessage(level = Level.ERROR)
@Message(id = 10011, value = "Failed to store avail data: %s")
void errorFailedToStoreAvailData(@Cause Throwable t, String data);
@LogMessage(level = Level.INFO)
@Message(id = 10012, value = "Starting scheduler")
void infoStartingScheduler();
@LogMessage(level = Level.INFO)
@Message(id = 10013, value = "Stopping scheduler")
void infoStoppingScheduler();
@LogMessage(level = Level.WARN)
@Message(id = 10014, value = "Batch operation requested [%d] values but received [%d]")
void warnBatchResultsDoNotMatchRequests(int expectedCound, int actualCount);
@LogMessage(level = Level.WARN)
@Message(id = 10015, value = "Comma in name! This will interfere with comma-separators in lists. [%s]")
void warnCommaInName(String name);
@LogMessage(level = Level.WARN)
@Message(id = 10016, value = "The resource type [%s] wants to use an unknown metric set [%s]")
void warnMetricSetDoesNotExist(String resourceTypeName, String metricSetName);
@LogMessage(level = Level.WARN)
@Message(id = 10017, value = "The resource type [%s] wants to use an unknown avail set [%s]")
void warnAvailSetDoesNotExist(String resourceTypeName, String availSetName);
@LogMessage(level = Level.WARN)
@Message(id = 10018, value = "Cannot obtain server identifiers for [%s]: %s")
void warnCannotObtainServerIdentifiersForDMREndpoint(String endpoint, String errorString);
@LogMessage(level = Level.INFO)
@Message(id = 10019, value = "Managed server [%s] is disabled. It will not be monitored.")
void infoManagedServerDisabled(String name);
@LogMessage(level = Level.WARN)
@Message(id = 10020, value = "The managed server [%s] wants to use an unknown resource type set [%s]")
void warnResourceTypeSetDoesNotExist(String managedServerName, String resourceTypeSetName);
@LogMessage(level = Level.INFO)
@Message(id = 10021, value = "There are no enabled resource type sets")
void infoNoEnabledResourceTypesConfigured();
@LogMessage(level = Level.INFO)
@Message(id = 10022, value = "Resource type [%s] is disabled - all if its child types will also be disabled: %s")
void infoDisablingResourceTypes(Object disabledType, List<?> toBeDisabled);
@LogMessage(level = Level.ERROR)
@Message(id = 10023, value = "Discovery failed while probing endpoint [%s]")
void errorDiscoveryFailed(@Cause Exception e, MonitoredEndpoint endpoint);
@LogMessage(level = Level.ERROR)
@Message(id = 10024, value = "Failed to store inventory data")
void errorFailedToStoreInventoryData(@Cause Throwable t);
@LogMessage(level = Level.INFO)
@Message(id = 10025, value = "Will talk to Hawkular at URL [%s]")
void infoUsingServerSideUrl(String url);
@LogMessage(level = Level.ERROR)
@Message(id = 10026, value = "Can't do anything without a feed; aborting startup")
void errorCannotDoAnythingWithoutFeed(@Cause Throwable t);
@LogMessage(level = Level.ERROR)
@Message(id = 10027, value = "To use standalone Hawkular Metrics, you must configure a tenant ID")
void errorMustHaveTenantIdConfigured();
@LogMessage(level = Level.ERROR)
@Message(id = 10028, value = "Cannot start storage adapter; aborting startup")
void errorCannotStartStorageAdapter(@Cause Throwable t);
@LogMessage(level = Level.ERROR)
@Message(id = 10029, value = "Scheduler failed to initialize; aborting startup")
void errorCannotInitializeScheduler(@Cause Throwable t);
}
| jsanda/hawkular-agent | hawkular-wildfly-monitor/src/main/java/org/hawkular/agent/monitor/log/MsgLogger.java | Java | apache-2.0 | 6,632 |
/*
* Copyright 2017 ThoughtWorks, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.thoughtworks.go.domain;
import com.thoughtworks.go.config.*;
import com.thoughtworks.go.config.materials.AbstractMaterialConfig;
import com.thoughtworks.go.config.materials.MaterialConfigs;
import com.thoughtworks.go.config.materials.PackageMaterialConfig;
import com.thoughtworks.go.config.materials.PluggableSCMMaterialConfig;
import com.thoughtworks.go.config.materials.dependency.DependencyMaterialConfig;
import com.thoughtworks.go.config.materials.git.GitMaterialConfig;
import com.thoughtworks.go.config.materials.svn.SvnMaterialConfig;
import com.thoughtworks.go.config.remote.ConfigRepoConfig;
import com.thoughtworks.go.config.remote.FileConfigOrigin;
import com.thoughtworks.go.config.remote.RepoConfigOrigin;
import com.thoughtworks.go.domain.label.PipelineLabel;
import com.thoughtworks.go.domain.materials.MaterialConfig;
import com.thoughtworks.go.helper.MaterialConfigsMother;
import com.thoughtworks.go.helper.PipelineConfigMother;
import com.thoughtworks.go.helper.StageConfigMother;
import com.thoughtworks.go.security.GoCipher;
import com.thoughtworks.go.util.Node;
import org.bouncycastle.crypto.InvalidCipherTextException;
import org.junit.Test;
import java.util.*;
import static com.thoughtworks.go.util.DataStructureUtils.a;
import static com.thoughtworks.go.util.DataStructureUtils.m;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.*;
import static org.hamcrest.Matchers.startsWith;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsNot.not;
import static org.hamcrest.core.IsNull.nullValue;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.*;
public class PipelineConfigTest {
private static final String BUILDING_PLAN_NAME = "building";
EnvironmentVariablesConfig mockEnvironmentVariablesConfig = mock(EnvironmentVariablesConfig.class);
ParamsConfig mockParamsConfig = mock(ParamsConfig.class);
public enum Foo {
Bar, Baz;
}
@Test
public void shouldFindByName() {
PipelineConfig pipelineConfig = new PipelineConfig(new CaseInsensitiveString("pipeline"), null, completedStage(), buildingStage());
assertThat(pipelineConfig.findBy(new CaseInsensitiveString("completed stage")).name(), is(new CaseInsensitiveString("completed stage")));
}
@Test
public void shouldReturnDuplicateWithoutName() {
PipelineConfig pipelineConfig = PipelineConfigMother.pipelineConfig("somePipeline");
PipelineConfig clonedPipelineConfig = pipelineConfig.duplicate();
assertThat(clonedPipelineConfig.name(), is(new CaseInsensitiveString("")));
assertThat(clonedPipelineConfig.materialConfigs(), is(pipelineConfig.materialConfigs()));
assertThat(clonedPipelineConfig.getFirstStageConfig(), is(pipelineConfig.getFirstStageConfig()));
}
@Test
public void shouldReturnDuplicateWithPipelineNameEmptyIfFetchArtifactTaskIsFetchingFromSamePipeline() {
PipelineConfig pipelineConfig = PipelineConfigMother.createPipelineConfig("somePipeline", "stage", "job");
StageConfig stageConfig = pipelineConfig.get(0);
JobConfig jobConfig = stageConfig.getJobs().get(0);
Tasks originalTasks = jobConfig.getTasks();
originalTasks.add(new FetchTask(pipelineConfig.name(), stageConfig.name(), jobConfig.name(), "src", "dest"));
originalTasks.add(new FetchTask(new CaseInsensitiveString("some_other_pipeline"), stageConfig.name(), jobConfig.name(), "src", "dest"));
PipelineConfig clone = pipelineConfig.duplicate();
Tasks clonedTasks = clone.get(0).getJobs().get(0).getTasks();
assertThat(((FetchTask) clonedTasks.get(0)).getTargetPipelineName(), is(new CaseInsensitiveString("")));
assertThat(((FetchTask) clonedTasks.get(1)).getTargetPipelineName(), is(new CaseInsensitiveString("some_other_pipeline")));
assertThat(((FetchTask) originalTasks.get(0)).getTargetPipelineName(), is(pipelineConfig.name()));
}
@Test //#6821
public void shouldCopyOverAllEnvironmentVariablesWhileCloningAPipeline() throws InvalidCipherTextException {
PipelineConfig source = PipelineConfigMother.createPipelineConfig("somePipeline", "stage", "job");
source.addEnvironmentVariable("k1", "v1");
source.addEnvironmentVariable("k2", "v2");
GoCipher goCipher = mock(GoCipher.class);
when(goCipher.encrypt("secret")).thenReturn("encrypted");
source.addEnvironmentVariable(new EnvironmentVariableConfig(goCipher, "secret_key", "secret", true));
PipelineConfig cloned = source.duplicate();
EnvironmentVariablesConfig clonedEnvVariables = cloned.getPlainTextVariables();
EnvironmentVariablesConfig sourceEnvVariables = source.getPlainTextVariables();
assertThat(clonedEnvVariables.size(), is(sourceEnvVariables.size()));
clonedEnvVariables.getPlainTextVariables().containsAll(sourceEnvVariables.getPlainTextVariables());
assertThat(cloned.getSecureVariables().size(), is(source.getSecureVariables().size()));
assertThat(cloned.getSecureVariables().containsAll(source.getSecureVariables()), is(true));
}
@Test
public void shouldGetStageByName() {
PipelineConfig pipelineConfig = new PipelineConfig(new CaseInsensitiveString("pipeline"), null, completedStage(), buildingStage());
assertThat(pipelineConfig.getStage(new CaseInsensitiveString("COMpleTEd stage")).name(), is(new CaseInsensitiveString("completed stage")));
assertThat(pipelineConfig.getStage(new CaseInsensitiveString("Does-not-exist")), is(nullValue()));
}
@Test
public void shouldReturnFalseIfThereIsNoNextStage() {
PipelineConfig pipelineConfig = new PipelineConfig(new CaseInsensitiveString("pipeline"), null, completedStage(), buildingStage());
assertThat(pipelineConfig.hasNextStage(buildingStage().name()), is(false));
}
@Test
public void shouldReturnFalseIfThereIsNextStage() {
PipelineConfig pipelineConfig = new PipelineConfig(new CaseInsensitiveString("pipeline"), null, completedStage(), buildingStage());
assertThat(pipelineConfig.hasNextStage(completedStage().name()), is(true));
}
@Test
public void shouldReturnFalseThePassInStageDoesNotExist() {
PipelineConfig pipelineConfig = new PipelineConfig(new CaseInsensitiveString("pipeline"), null, completedStage(), buildingStage());
assertThat(pipelineConfig.hasNextStage(new CaseInsensitiveString("notExist")), is(false));
}
@Test
public void shouldReturnTrueIfThereNoStagesDefined() {
PipelineConfig pipelineConfig = new PipelineConfig(new CaseInsensitiveString("pipeline"), null);
assertThat(pipelineConfig.hasNextStage(completedStage().name()), is(false));
}
@Test
public void shouldGetDependenciesAsNode() throws Exception {
PipelineConfig pipelineConfig = new PipelineConfig();
pipelineConfig.addMaterialConfig(new DependencyMaterialConfig(new CaseInsensitiveString("framework"), new CaseInsensitiveString("dev")));
pipelineConfig.addMaterialConfig(new DependencyMaterialConfig(new CaseInsensitiveString("middleware"), new CaseInsensitiveString("dev")));
assertThat(pipelineConfig.getDependenciesAsNode(),
is(new Node(
new Node.DependencyNode(new CaseInsensitiveString("framework"), new CaseInsensitiveString("dev")),
new Node.DependencyNode(new CaseInsensitiveString("middleware"), new CaseInsensitiveString("dev")))));
}
@Test
public void shouldReturnTrueIfFirstStageIsManualApproved() {
PipelineConfig pipelineConfig = PipelineConfigMother.createPipelineConfig("pipeline", "stage", "build");
pipelineConfig.getFirstStageConfig().updateApproval(Approval.manualApproval());
assertThat("First stage should be manual approved", pipelineConfig.isFirstStageManualApproval(), is(true));
}
@Test
public void shouldThrowExceptionForEmptyPipeline() {
PipelineConfig pipelineConfig = new PipelineConfig(new CaseInsensitiveString("cruise"), new MaterialConfigs());
try {
pipelineConfig.isFirstStageManualApproval();
fail("Should throw exception if pipeline has no pipeline");
} catch (IllegalStateException e) {
assertThat(e.getMessage(),
containsString("Pipeline [" + pipelineConfig.name() + "] doesn't have any stage"));
}
}
@Test
public void shouldThrowExceptionOnAddingTemplatesIfItAlreadyHasStages() {
PipelineConfig pipelineConfig = PipelineConfigMother.createPipelineConfig("pipeline", "stage", "build");
try {
PipelineTemplateConfig template = new PipelineTemplateConfig();
template.add(StageConfigMother.stageConfig("first"));
pipelineConfig.setTemplateName(new CaseInsensitiveString("some-template"));
fail("Should throw exception because the pipeline has stages already");
} catch (RuntimeException e) {
assertThat(e.getMessage(), containsString("Cannot set template 'some-template' on pipeline 'pipeline' because it already has stages defined"));
}
}
@Test
public void shouldBombWhenAddingStagesIfItAlreadyHasATemplate() {
PipelineConfig pipelineConfig = new PipelineConfig(new CaseInsensitiveString("mingle"), null);
try {
pipelineConfig.setTemplateName(new CaseInsensitiveString("some-template"));
pipelineConfig.add(StageConfigMother.stageConfig("second"));
fail("Should throw exception because pipeline already has a template");
} catch (RuntimeException e) {
assertThat(e.getMessage(), containsString("Cannot add stage 'second' to pipeline 'mingle', which already references template 'some-template'."));
}
}
@Test
public void shouldKnowIfATemplateWasApplied() {
PipelineConfig pipelineConfig = PipelineConfigMother.createPipelineConfig("pipeline", "stage", "build");
assertThat(pipelineConfig.hasTemplateApplied(), is(false));
pipelineConfig.clear();
PipelineTemplateConfig template = new PipelineTemplateConfig();
template.add(StageConfigMother.stageConfig("first"));
pipelineConfig.usingTemplate(template);
assertThat(pipelineConfig.hasTemplateApplied(), is(true));
}
@Test
public void shouldGetAllTemplateVariableNames() {
PipelineConfig pipelineConfig = new PipelineConfig(new CaseInsensitiveString("cruise"), new MaterialConfigs());
pipelineConfig.setLabelTemplate("pipeline-${COUNT}-${mymaterial}${hi}");
Set<String> variables = pipelineConfig.getTemplateVariables();
assertThat(variables.contains("COUNT"), is(true));
assertThat(variables.contains("mymaterial"), is(true));
assertThat(variables.contains("hi"), is(true));
}
@Test
public void shouldValidateCorrectPipelineLabelWithoutAnyMaterial() {
PipelineConfig pipelineConfig = new PipelineConfig(new CaseInsensitiveString("cruise"), new MaterialConfigs(),new StageConfig(new CaseInsensitiveString("first"), new JobConfigs()));
pipelineConfig.setLabelTemplate("pipeline-${COUNT}-alpha");
pipelineConfig.validate(null);
assertThat(pipelineConfig.errors().isEmpty(), is(true));
assertThat(pipelineConfig.errors().on(PipelineConfig.LABEL_TEMPLATE), is(nullValue()));
}
@Test
public void shouldValidateMissingLabel() {
PipelineConfig pipelineConfig = createAndValidatePipelineLabel(null);
assertThat(pipelineConfig.errors().on(PipelineConfig.LABEL_TEMPLATE), is(PipelineConfig.BLANK_LABEL_TEMPLATE_ERROR_MESSAGE));
pipelineConfig = createAndValidatePipelineLabel("");
assertThat(pipelineConfig.errors().on(PipelineConfig.LABEL_TEMPLATE), is(PipelineConfig.BLANK_LABEL_TEMPLATE_ERROR_MESSAGE));
}
@Test
public void shouldValidateCorrectPipelineLabelWithoutTruncationSyntax() {
String labelFormat = "pipeline-${COUNT}-${git}-454";
PipelineConfig pipelineConfig = createAndValidatePipelineLabel(labelFormat);
assertThat(pipelineConfig.errors().on(PipelineConfig.LABEL_TEMPLATE), is(nullValue()));
}
@Test
public void shouldValidatePipelineLabelWithNonExistingMaterial() {
String labelFormat = "pipeline-${COUNT}-${NoSuchMaterial}";
PipelineConfig pipelineConfig = createAndValidatePipelineLabel(labelFormat);
assertThat(pipelineConfig.errors().on(PipelineConfig.LABEL_TEMPLATE), startsWith("You have defined a label template in pipeline"));
}
@Test
public void shouldValidateCorrectPipelineLabelWithTruncationSyntax() {
String labelFormat = "pipeline-${COUNT}-${git[:7]}-alpha";
PipelineConfig pipelineConfig = createAndValidatePipelineLabel(labelFormat);
assertThat(pipelineConfig.errors().on(PipelineConfig.LABEL_TEMPLATE), is(nullValue()));
}
@Test
public void shouldValidatePipelineLabelWithBrokenTruncationSyntax1() {
String labelFormat = "pipeline-${COUNT}-${git[:7}-alpha";
PipelineConfig pipelineConfig = createAndValidatePipelineLabel(labelFormat);
String expectedLabelTemplate = "Invalid label 'pipeline-${COUNT}-${git[:7}-alpha'.";
assertThat(pipelineConfig.errors().on(PipelineConfig.LABEL_TEMPLATE), startsWith(expectedLabelTemplate));
}
@Test
public void shouldValidatePipelineLabelWithBrokenTruncationSyntax2() {
String labelFormat = "pipeline-${COUNT}-${git[7]}-alpha";
PipelineConfig pipelineConfig = createAndValidatePipelineLabel(labelFormat);
String expectedLabelTemplate = "Invalid label 'pipeline-${COUNT}-${git[7]}-alpha'.";
assertThat(pipelineConfig.errors().on(PipelineConfig.LABEL_TEMPLATE), startsWith(expectedLabelTemplate));
}
@Test
public void shouldValidateIncorrectPipelineLabelWithTruncationSyntax() {
String labelFormat = "pipeline-${COUNT}-${noSuch[:7]}-alpha";
PipelineConfig pipelineConfig = createAndValidatePipelineLabel(labelFormat);
assertThat(pipelineConfig.errors().on(PipelineConfig.LABEL_TEMPLATE), startsWith("You have defined a label template in pipeline"));
}
@Test
public void shouldNotAllowLabelTemplateWithLengthOfZeroInTruncationSyntax() throws Exception {
String labelFormat = "pipeline-${COUNT}-${git[:0]}-alpha";
PipelineConfig pipelineConfig = createAndValidatePipelineLabel(labelFormat);
assertThat(pipelineConfig.errors().on(PipelineConfig.LABEL_TEMPLATE), is(String.format("Length of zero not allowed on label %s defined on pipeline %s.", labelFormat, pipelineConfig.name())));
}
@Test
public void shouldNotAllowLabelTemplateWithLengthOfZeroInTruncationSyntax2() throws Exception {
String labelFormat = "pipeline-${COUNT}-${git[:0]}${one[:00]}-alpha";
PipelineConfig pipelineConfig = createAndValidatePipelineLabel(labelFormat);
assertThat(pipelineConfig.errors().on(PipelineConfig.LABEL_TEMPLATE), is(String.format("Length of zero not allowed on label %s defined on pipeline %s.",labelFormat,pipelineConfig.name())));
}
@Test
public void shouldSupportTruncationSyntax() {
PipelineConfig pipelineConfig = new PipelineConfig(new CaseInsensitiveString("cruise"), new MaterialConfigs());
pipelineConfig.setLabelTemplate("pipeline-${COUNT}-${git[:7]}-alpha");
Set<String> variables = pipelineConfig.getTemplateVariables();
assertThat(variables, contains("COUNT", "git"));
assertThat(variables.size(), is(2));
}
@Test
public void shouldSupportSpecialCharacters() {
PipelineConfig pipelineConfig = new PipelineConfig(new CaseInsensitiveString("cruise"), new MaterialConfigs());
pipelineConfig.setLabelTemplate("pipeline-${COUN_T}-${my-material}${h.i}${**}");
Set<String> variables = pipelineConfig.getTemplateVariables();
assertThat(variables, contains("COUN_T", "my-material", "h.i", "**"));
}
@Test
public void shouldAllowColonInLabelTemplateVariable() throws Exception {
PipelineConfig pipelineConfig = new PipelineConfig(new CaseInsensitiveString("cruise"), new MaterialConfigs());
pipelineConfig.setLabelTemplate("pipeline-${COUN_T}:${repo:package}");
Set<String> variables = pipelineConfig.getTemplateVariables();
assertThat(variables.contains("repo:package"), is(true));
}
@Test
public void shouldSetPipelineConfigFromConfigAttributes() {
PipelineConfig pipelineConfig = new PipelineConfig();
HashMap mingleConfigMap = new HashMap();
mingleConfigMap.put("mingleconfig", "mingleconfig");
HashMap trackingToolMap = new HashMap();
trackingToolMap.put("trackingtool", "trackingtool");
HashMap timerConfigMap = new HashMap();
String cronSpec = "0 0 11 * * ?";
timerConfigMap.put(TimerConfig.TIMER_SPEC, cronSpec);
Map configMap = new HashMap();
configMap.put(PipelineConfig.LABEL_TEMPLATE, "LABEL123-${COUNT}");
configMap.put(PipelineConfig.MINGLE_CONFIG, mingleConfigMap);
configMap.put(PipelineConfig.TRACKING_TOOL, trackingToolMap);
configMap.put(PipelineConfig.TIMER_CONFIG, timerConfigMap);
pipelineConfig.setConfigAttributes(configMap);
assertThat(pipelineConfig.getLabelTemplate(), is("LABEL123-${COUNT}"));
assertThat(pipelineConfig.getTimer().getTimerSpec(), is(cronSpec));
assertThat(pipelineConfig.getTimer().shouldTriggerOnlyOnChanges(), is(false));
}
@Test
public void shouldSetPipelineConfigFromConfigAttributesForTimerConfig() {
PipelineConfig pipelineConfig = new PipelineConfig();
HashMap timerConfigMap = new HashMap();
String cronSpec = "0 0 11 * * ?";
timerConfigMap.put(TimerConfig.TIMER_SPEC, cronSpec);
timerConfigMap.put(TimerConfig.TIMER_ONLY_ON_CHANGES, "1");
Map configMap = new HashMap();
configMap.put(PipelineConfig.LABEL_TEMPLATE, "LABEL123-${COUNT}");
configMap.put(PipelineConfig.TIMER_CONFIG, timerConfigMap);
pipelineConfig.setConfigAttributes(configMap);
assertThat(pipelineConfig.getLabelTemplate(), is("LABEL123-${COUNT}"));
assertThat(pipelineConfig.getTimer().getTimerSpec(), is(cronSpec));
assertThat(pipelineConfig.getTimer().shouldTriggerOnlyOnChanges(), is(true));
}
@Test
public void shouldSetLabelTemplateToDefaultValueIfBlankIsEnteredWhileSettingConfigAttributes() {
PipelineConfig pipelineConfig = new PipelineConfig();
Map configMap = new HashMap();
configMap.put(PipelineConfig.LABEL_TEMPLATE, "");
pipelineConfig.setConfigAttributes(configMap);
assertThat(pipelineConfig.getLabelTemplate(), is(PipelineLabel.COUNT_TEMPLATE));
}
@Test
public void shouldNotSetLockStatusOnPipelineConfigWhenValueIsNone() {
Map configMap = new HashMap();
configMap.put(PipelineConfig.LOCK_BEHAVIOR, PipelineConfig.LOCK_VALUE_NONE);
PipelineConfig pipelineConfig = new PipelineConfig();
pipelineConfig.setConfigAttributes(configMap);
assertThat(pipelineConfig.isLockable(), is(false));
}
@Test
public void shouldSetLockStatusOnPipelineConfigWhenValueIsLockOnFailure() {
Map configMap = new HashMap();
configMap.put(PipelineConfig.LOCK_BEHAVIOR, PipelineConfig.LOCK_VALUE_LOCK_ON_FAILURE);
PipelineConfig pipelineConfig = new PipelineConfig();
pipelineConfig.setConfigAttributes(configMap);
assertThat(pipelineConfig.isLockable(), is(true));
}
@Test
public void shouldSetLockStatusOnPipelineConfigWhenValueIsUnlockWhenFinished() {
Map configMap = new HashMap();
configMap.put(PipelineConfig.LOCK_BEHAVIOR, PipelineConfig.LOCK_VALUE_UNLOCK_WHEN_FINISHED);
PipelineConfig pipelineConfig = new PipelineConfig();
pipelineConfig.setConfigAttributes(configMap);
assertThat(pipelineConfig.isPipelineUnlockableWhenFinished(), is(true));
}
@Test
public void isNotLockableWhenLockValueHasNotBeenSet() {
PipelineConfig pipelineConfig = new PipelineConfig();
assertThat(pipelineConfig.hasExplicitLock(), is(false));
assertThat(pipelineConfig.isLockable(), is(false));
}
@Test
public void shouldValidateLockBehaviorValues() throws Exception {
Map configMap = new HashMap();
configMap.put(PipelineConfig.LOCK_BEHAVIOR, "someRandomValue");
PipelineConfig pipelineConfig = PipelineConfigMother.pipelineConfig("pipeline1");
pipelineConfig.setConfigAttributes(configMap);
pipelineConfig.validate(null);
assertThat(pipelineConfig.errors().isEmpty(), is(false));
assertThat(pipelineConfig.errors().on(PipelineConfig.LOCK_BEHAVIOR),
containsString("Lock behavior has an invalid value (someRandomValue). Valid values are: "));
}
@Test
public void shouldAllowNullForLockBehavior() throws Exception {
PipelineConfig pipelineConfig = PipelineConfigMother.pipelineConfig("pipeline1");
pipelineConfig.setLockBehaviorIfNecessary(null);
pipelineConfig.validate(null);
assertThat(pipelineConfig.errors().toString(), pipelineConfig.errors().isEmpty(), is(true));
}
@Test
public void shouldPopulateEnvironmentVariablesFromAttributeMap() {
PipelineConfig pipelineConfig = new PipelineConfig();
HashMap map = new HashMap();
HashMap valueHashMap = new HashMap();
valueHashMap.put("name", "FOO");
valueHashMap.put("value", "BAR");
map.put(PipelineConfig.ENVIRONMENT_VARIABLES, valueHashMap);
pipelineConfig.setVariables(mockEnvironmentVariablesConfig);
pipelineConfig.setConfigAttributes(map);
verify(mockEnvironmentVariablesConfig).setConfigAttributes(valueHashMap);
}
@Test
public void shouldPopulateParamsFromAttributeMapWhenConfigurationTypeIsNotSet() {
PipelineConfig pipelineConfig = new PipelineConfig();
final HashMap map = new HashMap();
final HashMap valueHashMap = new HashMap();
valueHashMap.put("param-name", "FOO");
valueHashMap.put("param-value", "BAR");
map.put(PipelineConfig.PARAMS, valueHashMap);
pipelineConfig.setParams(mockParamsConfig);
pipelineConfig.setConfigAttributes(map);
verify(mockParamsConfig).setConfigAttributes(valueHashMap);
}
@Test
public void shouldPopulateParamsFromAttributeMapIfConfigurationTypeIsTemplate() {
PipelineConfig pipelineConfig = new PipelineConfig();
HashMap map = new HashMap();
HashMap valueHashMap = new HashMap();
valueHashMap.put("param-name", "FOO");
valueHashMap.put("param-value", "BAR");
map.put(PipelineConfig.PARAMS, valueHashMap);
map.put(PipelineConfig.CONFIGURATION_TYPE, PipelineConfig.CONFIGURATION_TYPE_TEMPLATE);
map.put(PipelineConfig.TEMPLATE_NAME, "template");
pipelineConfig.setParams(mockParamsConfig);
pipelineConfig.setConfigAttributes(map);
verify(mockParamsConfig).setConfigAttributes(valueHashMap);
}
@Test
public void shouldNotPopulateParamsFromAttributeMapIfConfigurationTypeIsStages() {
PipelineConfig pipelineConfig = new PipelineConfig();
HashMap map = new HashMap();
HashMap valueHashMap = new HashMap();
valueHashMap.put("param-name", "FOO");
valueHashMap.put("param-value", "BAR");
map.put(PipelineConfig.PARAMS, valueHashMap);
map.put(PipelineConfig.CONFIGURATION_TYPE, PipelineConfig.CONFIGURATION_TYPE_STAGES);
pipelineConfig.setParams(mockParamsConfig);
pipelineConfig.setConfigAttributes(map);
verify(mockParamsConfig, never()).setConfigAttributes(valueHashMap);
}
@Test
public void shouldSetTheCorrectIntegrationType() {
PipelineConfig pipelineConfig = new PipelineConfig();
assertThat(pipelineConfig.getIntegrationType(), is(PipelineConfig.INTEGRATION_TYPE_NONE));
pipelineConfig = new PipelineConfig();
pipelineConfig.setTrackingTool(new TrackingTool("link", "regex"));
assertThat(pipelineConfig.getIntegrationType(), is(PipelineConfig.INTEGRATION_TYPE_TRACKING_TOOL));
pipelineConfig = new PipelineConfig();
pipelineConfig.setMingleConfig(new MingleConfig("baseUri", "projId"));
assertThat(pipelineConfig.getIntegrationType(), is(PipelineConfig.INTEGRATION_TYPE_MINGLE));
}
@Test
public void shouldSetIntegrationTypeToMingleInCaseAnEmptyMingleConfigIsSubmitted() {
PipelineConfig pipelineConfig = new PipelineConfig();
MingleConfig mingleConfig = new MingleConfig();
mingleConfig.addError(MingleConfig.BASE_URL, "some error");
pipelineConfig.setMingleConfig(mingleConfig);
String integrationType = pipelineConfig.getIntegrationType();
assertThat(integrationType, is(PipelineConfig.INTEGRATION_TYPE_MINGLE));
}
@Test
public void shouldPopulateTrackingToolWhenIntegrationTypeIsTrackingToolAndLinkAndRegexAreDefined() {
PipelineConfig pipelineConfig = new PipelineConfig();
pipelineConfig.setMingleConfig(new MingleConfig("baseUri", "go"));
HashMap map = new HashMap();
HashMap valueHashMap = new HashMap();
valueHashMap.put("link", "GoleyLink");
valueHashMap.put("regex", "GoleyRegex");
map.put(PipelineConfig.TRACKING_TOOL, valueHashMap);
map.put(PipelineConfig.INTEGRATION_TYPE, PipelineConfig.INTEGRATION_TYPE_TRACKING_TOOL);
pipelineConfig.setConfigAttributes(map);
assertThat(pipelineConfig.getTrackingTool(), is(new TrackingTool("GoleyLink", "GoleyRegex")));
assertThat(pipelineConfig.getMingleConfig(), is(new MingleConfig()));
assertThat(pipelineConfig.getIntegrationType(), is(PipelineConfig.INTEGRATION_TYPE_TRACKING_TOOL));
}
@Test
public void shouldPopulateMingleConfigWhenIntegrationTypeIsMingle() {
PipelineConfig pipelineConfig = new PipelineConfig();
pipelineConfig.setTrackingTool(new TrackingTool("link", "regex"));
Map map = new HashMap();
HashMap valueHashMap = new HashMap();
valueHashMap.put(MingleConfig.BASE_URL, "url");
valueHashMap.put(MingleConfig.PROJECT_IDENTIFIER, "identifier");
valueHashMap.put(MqlCriteria.MQL, "criteria");
valueHashMap.put(MingleConfig.MQL_GROUPING_CONDITIONS, valueHashMap);
map.put(PipelineConfig.MINGLE_CONFIG, valueHashMap);
map.put(PipelineConfig.INTEGRATION_TYPE, PipelineConfig.INTEGRATION_TYPE_MINGLE);
pipelineConfig.setConfigAttributes(map);
assertThat(pipelineConfig.getMingleConfig(), is(new MingleConfig("url", "identifier", "criteria")));
assertThat(pipelineConfig.getTrackingTool(), is(nullValue()));
assertThat(pipelineConfig.getIntegrationType(), is(PipelineConfig.INTEGRATION_TYPE_MINGLE));
}
@Test
public void shouldResetMingleConfigWhenIntegrationTypeIsNone() {
PipelineConfig pipelineConfig = new PipelineConfig();
pipelineConfig.setMingleConfig(new MingleConfig("baseUri", "go"));
Map map = new HashMap();
map.put(PipelineConfig.INTEGRATION_TYPE, PipelineConfig.INTEGRATION_TYPE_NONE);
pipelineConfig.setConfigAttributes(map);
assertThat(pipelineConfig.getMingleConfig(), is(new MingleConfig()));
assertThat(pipelineConfig.getIntegrationType(), is(PipelineConfig.INTEGRATION_TYPE_NONE));
}
@Test
public void shouldResetTrackingToolWhenIntegrationTypeIsNone() {
PipelineConfig pipelineConfig = new PipelineConfig();
pipelineConfig.setTrackingTool(new TrackingTool("link", "regex"));
Map map = new HashMap();
map.put(PipelineConfig.INTEGRATION_TYPE, PipelineConfig.INTEGRATION_TYPE_NONE);
pipelineConfig.setConfigAttributes(map);
assertThat(pipelineConfig.getTrackingTool(), is(nullValue()));
assertThat(pipelineConfig.getIntegrationType(), is(PipelineConfig.INTEGRATION_TYPE_NONE));
}
@Test
public void shouldGetIntegratedTrackingToolWhenGenericTrackingToolIsDefined() {
PipelineConfig pipelineConfig = PipelineConfigMother.pipelineConfig("pipeline");
TrackingTool trackingTool = new TrackingTool("http://example.com/${ID}", "Foo-(\\d+)");
pipelineConfig.setTrackingTool(trackingTool);
pipelineConfig.setMingleConfig(new MingleConfig());
assertThat(pipelineConfig.getIntegratedTrackingTool(), is(Optional.of(trackingTool)));
}
@Test
public void shouldGetIntegratedTrackingToolWhenMingleTrackingToolIsDefined() {
PipelineConfig pipelineConfig = PipelineConfigMother.pipelineConfig("pipeline");
MingleConfig mingleConfig = new MingleConfig("http://example.com", "go-project");
pipelineConfig.setTrackingTool(null);
pipelineConfig.setMingleConfig(mingleConfig);
assertThat(pipelineConfig.getIntegratedTrackingTool(), is(Optional.of(mingleConfig.asTrackingTool())));
}
@Test
public void shouldGetIntegratedTrackingToolWhenNoneIsDefined() {
PipelineConfig pipelineConfig = PipelineConfigMother.pipelineConfig("pipeline");
pipelineConfig.setTrackingTool(null);
pipelineConfig.setMingleConfig(new MingleConfig());
assertThat(pipelineConfig.getIntegratedTrackingTool(), is(Optional.empty()));
}
@Test
public void shouldGetTheCorrectConfigurationType() {
PipelineConfig pipelineConfigWithTemplate = PipelineConfigMother.pipelineConfigWithTemplate("pipeline", "template");
assertThat(pipelineConfigWithTemplate.getConfigurationType(), is(PipelineConfig.CONFIGURATION_TYPE_TEMPLATE));
PipelineConfig pipelineConfig = PipelineConfigMother.pipelineConfig("pipeline");
assertThat(pipelineConfig.getConfigurationType(), is(PipelineConfig.CONFIGURATION_TYPE_STAGES));
}
@Test
public void shouldUseTemplateWhenSetConfigAttributesContainsTemplateName() {
PipelineConfig pipelineConfig = PipelineConfigMother.pipelineConfig("pipeline");
assertThat(pipelineConfig.hasTemplate(), is(false));
Map map = new HashMap();
map.put(PipelineConfig.CONFIGURATION_TYPE, PipelineConfig.CONFIGURATION_TYPE_TEMPLATE);
map.put(PipelineConfig.TEMPLATE_NAME, "foo-template");
pipelineConfig.setConfigAttributes(map);
assertThat(pipelineConfig.getConfigurationType(), is(PipelineConfig.CONFIGURATION_TYPE_TEMPLATE));
assertThat(pipelineConfig.getTemplateName(), is(new CaseInsensitiveString("foo-template")));
}
@Test
public void shouldIncrementIndexBy1OfGivenStage() {
StageConfig moveMeStage = StageConfigMother.stageConfig("move-me");
StageConfig dontMoveMeStage = StageConfigMother.stageConfig("dont-move-me");
PipelineConfig pipelineConfig = PipelineConfigMother.pipelineConfig("pipeline", moveMeStage, dontMoveMeStage);
pipelineConfig.incrementIndex(moveMeStage);
assertThat(pipelineConfig.indexOf(moveMeStage), is(1));
assertThat(pipelineConfig.indexOf(dontMoveMeStage), is(0));
}
@Test
public void shouldDecrementIndexBy1OfGivenStage() {
StageConfig moveMeStage = StageConfigMother.stageConfig("move-me");
StageConfig dontMoveMeStage = StageConfigMother.stageConfig("dont-move-me");
PipelineConfig pipelineConfig = PipelineConfigMother.pipelineConfig("pipeline", dontMoveMeStage, moveMeStage);
pipelineConfig.decrementIndex(moveMeStage);
assertThat(pipelineConfig.indexOf(moveMeStage), is(0));
assertThat(pipelineConfig.indexOf(dontMoveMeStage), is(1));
}
@Test
public void shouldThrowExceptionWhenTheStageIsNotFound() {
StageConfig moveMeStage = StageConfigMother.stageConfig("move-me");
StageConfig dontMoveMeStage = StageConfigMother.stageConfig("dont-move-me");
PipelineConfig pipelineConfig = PipelineConfigMother.pipelineConfig("pipeline", dontMoveMeStage);
try {
pipelineConfig.incrementIndex(moveMeStage);
fail("Should fail to increment the index of a stage that is not found");
} catch (RuntimeException expected) {
assertThat(expected.getMessage(), is("Cannot find the stage 'move-me' in pipeline 'pipeline'"));
}
try {
pipelineConfig.decrementIndex(moveMeStage);
fail("Should fail to increment the index of a stage that is not found");
} catch (RuntimeException expected) {
assertThat(expected.getMessage(), is("Cannot find the stage 'move-me' in pipeline 'pipeline'"));
}
}
@Test
public void shouldReturnListOfStageConfigWhichIsApplicableForFetchArtifact() {
PipelineConfig superUpstream = PipelineConfigMother.createPipelineConfigWithStages("superUpstream", "s1", "s2", "s3");
PipelineConfig upstream = PipelineConfigMother.createPipelineConfigWithStages("upstream", "s4", "s5", "s6");
upstream.addMaterialConfig(new DependencyMaterialConfig(superUpstream.name(), new CaseInsensitiveString("s2")));
PipelineConfig downstream = PipelineConfigMother.createPipelineConfigWithStages("downstream", "s7");
downstream.addMaterialConfig(new DependencyMaterialConfig(upstream.name(), new CaseInsensitiveString("s5")));
List<StageConfig> fetchableStages = upstream.validStagesForFetchArtifact(downstream, new CaseInsensitiveString("s7"));
assertThat(fetchableStages.size(), is(2));
assertThat(fetchableStages, hasItem(upstream.get(0)));
assertThat(fetchableStages, hasItem(upstream.get(1)));
}
@Test
public void shouldReturnStagesBeforeCurrentForSelectedPipeline() {
PipelineConfig downstream = PipelineConfigMother.createPipelineConfigWithStages("downstream", "s1", "s2");
List<StageConfig> fetchableStages = downstream.validStagesForFetchArtifact(downstream, new CaseInsensitiveString("s2"));
assertThat(fetchableStages.size(), is(1));
assertThat(fetchableStages, hasItem(downstream.get(0)));
}
@Test
public void shouldUpdateNameAndMaterialsOnAttributes() {
PipelineConfig pipelineConfig = new PipelineConfig();
HashMap svnMaterialConfigMap = new HashMap();
svnMaterialConfigMap.put(SvnMaterialConfig.URL, "http://url");
svnMaterialConfigMap.put(SvnMaterialConfig.USERNAME, "loser");
svnMaterialConfigMap.put(SvnMaterialConfig.PASSWORD, "passwd");
svnMaterialConfigMap.put(SvnMaterialConfig.CHECK_EXTERNALS, false);
HashMap materialConfigsMap = new HashMap();
materialConfigsMap.put(AbstractMaterialConfig.MATERIAL_TYPE, SvnMaterialConfig.TYPE);
materialConfigsMap.put(SvnMaterialConfig.TYPE, svnMaterialConfigMap);
HashMap attributeMap = new HashMap();
attributeMap.put(PipelineConfig.NAME, "startup");
attributeMap.put(PipelineConfig.MATERIALS, materialConfigsMap);
pipelineConfig.setConfigAttributes(attributeMap);
assertThat(pipelineConfig.name(), is(new CaseInsensitiveString("startup")));
assertThat(pipelineConfig.materialConfigs().get(0), is(new SvnMaterialConfig("http://url", "loser", "passwd", false)));
}
@Test
public void shouldUpdateStageOnAttributes() {
PipelineConfig pipelineConfig = new PipelineConfig();
HashMap stageMap = new HashMap();
List jobList = a(m(JobConfig.NAME, "JobName"));
stageMap.put(StageConfig.NAME, "someStage");
stageMap.put(StageConfig.JOBS, jobList);
HashMap attributeMap = new HashMap();
attributeMap.put(PipelineConfig.NAME, "startup");
attributeMap.put(PipelineConfig.STAGE, stageMap);
pipelineConfig.setConfigAttributes(attributeMap);
assertThat(pipelineConfig.name(), is(new CaseInsensitiveString("startup")));
assertThat(pipelineConfig.get(0).name(), is(new CaseInsensitiveString("someStage")));
assertThat(pipelineConfig.get(0).getJobs().first().name(), is(new CaseInsensitiveString("JobName")));
}
@Test
public void shouldValidatePipelineName() {
PipelineConfig pipelineConfig = PipelineConfigMother.createPipelineConfig("foo bar", "stage1", "job1");
pipelineConfig.validate(null);
assertThat(pipelineConfig.errors().isEmpty(), is(false));
assertThat(pipelineConfig.errors().on(PipelineConfig.NAME),
is("Invalid pipeline name 'foo bar'. This must be alphanumeric and can contain underscores and periods (however, it cannot start with a period). The maximum allowed length is 255 characters."));
}
@Test
public void shouldRemoveExistingStagesWhileDoingAStageUpdate() {
PipelineConfig pipelineConfig = new PipelineConfig(new CaseInsensitiveString("foo"), new MaterialConfigs(), new StageConfig(new CaseInsensitiveString("first"), new JobConfigs()),
new StageConfig(
new CaseInsensitiveString("second"), new JobConfigs()));
HashMap stageMap = new HashMap();
List jobList = a(m(JobConfig.NAME, "JobName"));
stageMap.put(StageConfig.NAME, "someStage");
stageMap.put(StageConfig.JOBS, jobList);
HashMap attributeMap = new HashMap();
attributeMap.put(PipelineConfig.NAME, "startup");
attributeMap.put(PipelineConfig.STAGE, stageMap);
pipelineConfig.setConfigAttributes(attributeMap);
assertThat(pipelineConfig.name(), is(new CaseInsensitiveString("startup")));
assertThat(pipelineConfig.size(), is(1));
assertThat(pipelineConfig.get(0).name(), is(new CaseInsensitiveString("someStage")));
assertThat(pipelineConfig.get(0).getJobs().first().name(), is(new CaseInsensitiveString("JobName")));
}
@Test
public void shouldGetAllFetchTasks() {
PipelineConfig pipelineConfig = PipelineConfigMother.createPipelineConfig("foo bar", "stage1", "job1");
FetchTask firstFetch = new FetchTask();
JobConfig firstJob = pipelineConfig.getFirstStageConfig().getJobs().get(0);
firstJob.addTask(firstFetch);
firstJob.addTask(new AntTask());
JobConfig secondJob = new JobConfig();
secondJob.addTask(new ExecTask());
FetchTask secondFetch = new FetchTask();
secondJob.addTask(secondFetch);
pipelineConfig.add(new StageConfig(new CaseInsensitiveString("stage-2"), new JobConfigs(secondJob)));
List<FetchTask> fetchTasks = pipelineConfig.getFetchTasks();
assertThat(fetchTasks.size(), is(2));
assertThat(fetchTasks.contains(firstFetch), is(true));
assertThat(fetchTasks.contains(secondFetch), is(true));
}
@Test
public void shouldGetOnlyPlainTextVariables() throws InvalidCipherTextException {
PipelineConfig pipelineConfig = new PipelineConfig();
EnvironmentVariableConfig username = new EnvironmentVariableConfig("username", "ram");
pipelineConfig.addEnvironmentVariable(username);
GoCipher goCipher = mock(GoCipher.class);
when(goCipher.encrypt("=%HG*^&*&^")).thenReturn("encrypted");
EnvironmentVariableConfig password = new EnvironmentVariableConfig(goCipher, "password", "=%HG*^&*&^", true);
pipelineConfig.addEnvironmentVariable(password);
EnvironmentVariablesConfig plainTextVariables = pipelineConfig.getPlainTextVariables();
assertThat(plainTextVariables, not(hasItem(password)));
assertThat(plainTextVariables, hasItem(username));
}
@Test
public void shouldGetOnlySecureVariables() throws InvalidCipherTextException {
PipelineConfig pipelineConfig = new PipelineConfig();
EnvironmentVariableConfig username = new EnvironmentVariableConfig("username", "ram");
pipelineConfig.addEnvironmentVariable(username);
GoCipher goCipher = mock(GoCipher.class);
when(goCipher.encrypt("=%HG*^&*&^")).thenReturn("encrypted");
EnvironmentVariableConfig password = new EnvironmentVariableConfig(goCipher, "password", "=%HG*^&*&^", true);
pipelineConfig.addEnvironmentVariable(password);
List<EnvironmentVariableConfig> plainTextVariables = pipelineConfig.getSecureVariables();
assertThat(plainTextVariables, hasItem(password));
assertThat(plainTextVariables, not(hasItem(username)));
}
@Test
public void shouldTemplatizeAPipeline() {
PipelineConfig config = PipelineConfigMother.createPipelineConfigWithStages("pipeline", "stage1", "stage2");
config.templatize(new CaseInsensitiveString("template"));
assertThat(config.hasTemplate(), is(true));
assertThat(config.hasTemplateApplied(), is(false));
assertThat(config.getTemplateName(), is(new CaseInsensitiveString("template")));
assertThat(config.isEmpty(), is(true));
config.templatize(new CaseInsensitiveString(""));
assertThat(config.hasTemplate(), is(false));
config.templatize(null);
assertThat(config.hasTemplate(), is(false));
}
@Test
public void shouldAssignApprovalTypeOnFirstStageAsAuto() throws Exception {
Map approvalAttributes = Collections.singletonMap(Approval.TYPE, Approval.SUCCESS);
Map<String, Map> map = Collections.singletonMap(StageConfig.APPROVAL, approvalAttributes);
PipelineConfig pipelineConfig = PipelineConfigMother.createPipelineConfig("p1", "s1", "j1");
pipelineConfig.get(0).updateApproval(Approval.manualApproval());
pipelineConfig.setConfigAttributes(map);
assertThat(pipelineConfig.get(0).getApproval().getType(), is(Approval.SUCCESS));
}
@Test
public void shouldAssignApprovalTypeOnFirstStageAsManual() throws Exception {
Map approvalAttributes = Collections.singletonMap(Approval.TYPE, Approval.MANUAL);
Map<String, Map> map = Collections.singletonMap(StageConfig.APPROVAL, approvalAttributes);
PipelineConfig pipelineConfig = PipelineConfigMother.createPipelineConfig("p1", "s1", "j1");
pipelineConfig.get(0).updateApproval(Approval.manualApproval());
pipelineConfig.setConfigAttributes(map);
assertThat(pipelineConfig.get(0).getApproval().getType(), is(Approval.MANUAL));
}
@Test
public void shouldAssignApprovalTypeOnFirstStageAsManualAndRestOfStagesAsUntouched() throws Exception {
Map approvalAttributes = Collections.singletonMap(Approval.TYPE, Approval.MANUAL);
Map<String, Map> map = Collections.singletonMap(StageConfig.APPROVAL, approvalAttributes);
PipelineConfig pipelineConfig = PipelineConfigMother.pipelineConfig("p1", StageConfigMother.custom("s1", Approval.automaticApproval()),
StageConfigMother.custom("s2", Approval.automaticApproval()));
pipelineConfig.setConfigAttributes(map);
assertThat(pipelineConfig.get(0).getApproval().getType(), is(Approval.MANUAL));
assertThat(pipelineConfig.get(1).getApproval().getType(), is(Approval.SUCCESS));
}
@Test
public void shouldGetPackageMaterialConfigs() throws Exception {
SvnMaterialConfig svn = new SvnMaterialConfig("svn", false);
PackageMaterialConfig packageMaterialOne = new PackageMaterialConfig();
PackageMaterialConfig packageMaterialTwo = new PackageMaterialConfig();
PipelineConfig pipelineConfig = PipelineConfigMother.pipelineConfig("p1", new MaterialConfigs(svn, packageMaterialOne, packageMaterialTwo));
List<PackageMaterialConfig> packageMaterialConfigs = pipelineConfig.packageMaterialConfigs();
assertThat(packageMaterialConfigs.size(), is(2));
assertThat(packageMaterialConfigs, hasItems(packageMaterialOne, packageMaterialTwo));
}
@Test
public void shouldGetPluggableSCMMaterialConfigs() throws Exception {
SvnMaterialConfig svn = new SvnMaterialConfig("svn", false);
PluggableSCMMaterialConfig pluggableSCMMaterialOne = new PluggableSCMMaterialConfig("scm-id-1");
PluggableSCMMaterialConfig pluggableSCMMaterialTwo = new PluggableSCMMaterialConfig("scm-id-2");
PipelineConfig pipelineConfig = PipelineConfigMother.pipelineConfig("p1", new MaterialConfigs(svn, pluggableSCMMaterialOne, pluggableSCMMaterialTwo));
List<PluggableSCMMaterialConfig> pluggableSCMMaterialConfigs = pipelineConfig.pluggableSCMMaterialConfigs();
assertThat(pluggableSCMMaterialConfigs.size(), is(2));
assertThat(pluggableSCMMaterialConfigs, hasItems(pluggableSCMMaterialOne, pluggableSCMMaterialTwo));
}
@Test
public void shouldReturnTrueWhenOneOfPipelineMaterialsIsTheSameAsConfigOrigin()
{
PipelineConfig pipelineConfig = PipelineConfigMother.createPipelineConfig("pipeline", "stage", "build");
MaterialConfig material = pipelineConfig.materialConfigs().first();
pipelineConfig.setOrigin(new RepoConfigOrigin(new ConfigRepoConfig(material, "plugin"), "1233"));
assertThat(pipelineConfig.isConfigOriginSameAsOneOfMaterials(),is(true));
}
@Test
public void shouldReturnTrueWhenOneOfPipelineMaterialsIsTheSameAsConfigOriginButDestinationIsDifferent()
{
PipelineConfig pipelineConfig = PipelineConfigMother.createPipelineConfig("pipeline", "stage", "build");
pipelineConfig.materialConfigs().clear();
GitMaterialConfig pipeMaterialConfig = new GitMaterialConfig("http://git");
pipeMaterialConfig.setFolder("dest1");
pipelineConfig.materialConfigs().add(pipeMaterialConfig);
GitMaterialConfig repoMaterialConfig = new GitMaterialConfig("http://git");
pipelineConfig.setOrigin(new RepoConfigOrigin(new ConfigRepoConfig(repoMaterialConfig,"plugin"),"1233"));
assertThat(pipelineConfig.isConfigOriginSameAsOneOfMaterials(),is(true));
}
@Test
public void shouldReturnFalseWhenOneOfPipelineMaterialsIsNotTheSameAsConfigOrigin()
{
PipelineConfig pipelineConfig = PipelineConfigMother.createPipelineConfig("pipeline", "stage", "build");
MaterialConfig material = new GitMaterialConfig("http://git");
pipelineConfig.setOrigin(new RepoConfigOrigin(new ConfigRepoConfig(material, "plugin"), "1233"));
assertThat(pipelineConfig.isConfigOriginSameAsOneOfMaterials(),is(false));
}
@Test
public void shouldReturnFalseIfOneOfPipelineMaterialsIsTheSameAsConfigOrigin_WhenOriginIsFile()
{
PipelineConfig pipelineConfig = PipelineConfigMother.createPipelineConfig("pipeline", "stage", "build");
pipelineConfig.setOrigin(new FileConfigOrigin());
assertThat(pipelineConfig.isConfigOriginSameAsOneOfMaterials(),is(false));
}
@Test
public void shouldReturnTrueWhenConfigRevisionIsEqualToQuery()
{
PipelineConfig pipelineConfig = PipelineConfigMother.createPipelineConfig("pipeline", "stage", "build");
MaterialConfig material = pipelineConfig.materialConfigs().first();
pipelineConfig.setOrigin(new RepoConfigOrigin(new ConfigRepoConfig(material, "plugin"), "1233"));
assertThat(pipelineConfig.isConfigOriginFromRevision("1233"),is(true));
}
@Test
public void shouldReturnFalseWhenConfigRevisionIsNotEqualToQuery()
{
PipelineConfig pipelineConfig = PipelineConfigMother.createPipelineConfig("pipeline", "stage", "build");
MaterialConfig material = pipelineConfig.materialConfigs().first();
pipelineConfig.setOrigin(new RepoConfigOrigin(new ConfigRepoConfig(material, "plugin"), "1233"));
assertThat(pipelineConfig.isConfigOriginFromRevision("32"),is(false));
}
@Test
public void shouldReturnConfigRepoOriginDisplayNameWhenOriginIsRemote() {
PipelineConfig pipelineConfig = new PipelineConfig();
pipelineConfig.setOrigin(new RepoConfigOrigin(new ConfigRepoConfig(MaterialConfigsMother.gitMaterialConfig(), "plugin"), "revision1"));
assertThat(pipelineConfig.getOriginDisplayName(), is("AwesomeGitMaterial at revision1"));
}
@Test
public void shouldReturnConfigRepoOriginDisplayNameWhenOriginIsFile() {
PipelineConfig pipelineConfig = new PipelineConfig();
pipelineConfig.setOrigin(new FileConfigOrigin());
assertThat(pipelineConfig.getOriginDisplayName(), is("cruise-config.xml"));
}
@Test
public void shouldReturnConfigRepoOriginDisplayNameWhenOriginIsNotSet() {
PipelineConfig pipelineConfig = new PipelineConfig();
assertThat(pipelineConfig.getOriginDisplayName(), is("cruise-config.xml"));
}
private StageConfig completedStage() {
JobConfigs plans = new JobConfigs();
plans.add(new JobConfig("completed"));
return new StageConfig(new CaseInsensitiveString("completed stage"), plans);
}
private StageConfig buildingStage() {
JobConfigs plans = new JobConfigs();
plans.add(new JobConfig(BUILDING_PLAN_NAME));
return new StageConfig(new CaseInsensitiveString("building stage"), plans);
}
private PipelineConfig createAndValidatePipelineLabel(String labelFormat) {
GitMaterialConfig git = new GitMaterialConfig("git@github.com:gocd/gocd.git");
git.setName(new CaseInsensitiveString("git"));
PipelineConfig pipelineConfig = new PipelineConfig(new CaseInsensitiveString("cruise"), new MaterialConfigs(git));
pipelineConfig.setLabelTemplate(labelFormat);
pipelineConfig.validate(null);
return pipelineConfig;
}
}
| stevem999/gocd | common/src/test/java/com/thoughtworks/go/domain/PipelineConfigTest.java | Java | apache-2.0 | 50,610 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_151) on Wed Jan 16 11:48:25 MST 2019 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Class org.wildfly.swarm.config.security.security_domain.authentication.LoginModule (BOM: * : All 2.3.0.Final API)</title>
<meta name="date" content="2019-01-16">
<link rel="stylesheet" type="text/css" href="../../../../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.wildfly.swarm.config.security.security_domain.authentication.LoginModule (BOM: * : All 2.3.0.Final API)";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../../../org/wildfly/swarm/config/security/security_domain/authentication/LoginModule.html" title="class in org.wildfly.swarm.config.security.security_domain.authentication">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../../../../../../../../overview-tree.html">Tree</a></li>
<li><a href="../../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage">Thorntail API, 2.3.0.Final</div>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../../index.html?org/wildfly/swarm/config/security/security_domain/authentication/class-use/LoginModule.html" target="_top">Frames</a></li>
<li><a href="LoginModule.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class org.wildfly.swarm.config.security.security_domain.authentication.LoginModule" class="title">Uses of Class<br>org.wildfly.swarm.config.security.security_domain.authentication.LoginModule</h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../../../../../org/wildfly/swarm/config/security/security_domain/authentication/LoginModule.html" title="class in org.wildfly.swarm.config.security.security_domain.authentication">LoginModule</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#org.wildfly.swarm.config.security.security_domain">org.wildfly.swarm.config.security.security_domain</a></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="#org.wildfly.swarm.config.security.security_domain.authentication">org.wildfly.swarm.config.security.security_domain.authentication</a></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="org.wildfly.swarm.config.security.security_domain">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../../../../org/wildfly/swarm/config/security/security_domain/authentication/LoginModule.html" title="class in org.wildfly.swarm.config.security.security_domain.authentication">LoginModule</a> in <a href="../../../../../../../../org/wildfly/swarm/config/security/security_domain/package-summary.html">org.wildfly.swarm.config.security.security_domain</a></h3>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../../../../org/wildfly/swarm/config/security/security_domain/package-summary.html">org.wildfly.swarm.config.security.security_domain</a> that return <a href="../../../../../../../../org/wildfly/swarm/config/security/security_domain/authentication/LoginModule.html" title="class in org.wildfly.swarm.config.security.security_domain.authentication">LoginModule</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../../../../org/wildfly/swarm/config/security/security_domain/authentication/LoginModule.html" title="class in org.wildfly.swarm.config.security.security_domain.authentication">LoginModule</a></code></td>
<td class="colLast"><span class="typeNameLabel">ClassicAuthentication.ClassicAuthenticationResources.</span><code><span class="memberNameLink"><a href="../../../../../../../../org/wildfly/swarm/config/security/security_domain/ClassicAuthentication.ClassicAuthenticationResources.html#loginModule-java.lang.String-">loginModule</a></span>(<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a> key)</code> </td>
</tr>
</tbody>
</table>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../../../../org/wildfly/swarm/config/security/security_domain/package-summary.html">org.wildfly.swarm.config.security.security_domain</a> that return types with arguments of type <a href="../../../../../../../../org/wildfly/swarm/config/security/security_domain/authentication/LoginModule.html" title="class in org.wildfly.swarm.config.security.security_domain.authentication">LoginModule</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="https://docs.oracle.com/javase/8/docs/api/java/util/List.html?is-external=true" title="class or interface in java.util">List</a><<a href="../../../../../../../../org/wildfly/swarm/config/security/security_domain/authentication/LoginModule.html" title="class in org.wildfly.swarm.config.security.security_domain.authentication">LoginModule</a>></code></td>
<td class="colLast"><span class="typeNameLabel">ClassicAuthentication.ClassicAuthenticationResources.</span><code><span class="memberNameLink"><a href="../../../../../../../../org/wildfly/swarm/config/security/security_domain/ClassicAuthentication.ClassicAuthenticationResources.html#loginModules--">loginModules</a></span>()</code>
<div class="block">Get the list of LoginModule resources</div>
</td>
</tr>
</tbody>
</table>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../../../../org/wildfly/swarm/config/security/security_domain/package-summary.html">org.wildfly.swarm.config.security.security_domain</a> with parameters of type <a href="../../../../../../../../org/wildfly/swarm/config/security/security_domain/authentication/LoginModule.html" title="class in org.wildfly.swarm.config.security.security_domain.authentication">LoginModule</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../../../../org/wildfly/swarm/config/security/security_domain/ClassicAuthentication.html" title="type parameter in ClassicAuthentication">T</a></code></td>
<td class="colLast"><span class="typeNameLabel">ClassicAuthentication.</span><code><span class="memberNameLink"><a href="../../../../../../../../org/wildfly/swarm/config/security/security_domain/ClassicAuthentication.html#loginModule-org.wildfly.swarm.config.security.security_domain.authentication.LoginModule-">loginModule</a></span>(<a href="../../../../../../../../org/wildfly/swarm/config/security/security_domain/authentication/LoginModule.html" title="class in org.wildfly.swarm.config.security.security_domain.authentication">LoginModule</a> value)</code>
<div class="block">Add the LoginModule object to the list of subresources</div>
</td>
</tr>
</tbody>
</table>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Method parameters in <a href="../../../../../../../../org/wildfly/swarm/config/security/security_domain/package-summary.html">org.wildfly.swarm.config.security.security_domain</a> with type arguments of type <a href="../../../../../../../../org/wildfly/swarm/config/security/security_domain/authentication/LoginModule.html" title="class in org.wildfly.swarm.config.security.security_domain.authentication">LoginModule</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../../../../org/wildfly/swarm/config/security/security_domain/ClassicAuthentication.html" title="type parameter in ClassicAuthentication">T</a></code></td>
<td class="colLast"><span class="typeNameLabel">ClassicAuthentication.</span><code><span class="memberNameLink"><a href="../../../../../../../../org/wildfly/swarm/config/security/security_domain/ClassicAuthentication.html#loginModules-java.util.List-">loginModules</a></span>(<a href="https://docs.oracle.com/javase/8/docs/api/java/util/List.html?is-external=true" title="class or interface in java.util">List</a><<a href="../../../../../../../../org/wildfly/swarm/config/security/security_domain/authentication/LoginModule.html" title="class in org.wildfly.swarm.config.security.security_domain.authentication">LoginModule</a>> value)</code>
<div class="block">Add all LoginModule objects to this subresource</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="org.wildfly.swarm.config.security.security_domain.authentication">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../../../../org/wildfly/swarm/config/security/security_domain/authentication/LoginModule.html" title="class in org.wildfly.swarm.config.security.security_domain.authentication">LoginModule</a> in <a href="../../../../../../../../org/wildfly/swarm/config/security/security_domain/authentication/package-summary.html">org.wildfly.swarm.config.security.security_domain.authentication</a></h3>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation">
<caption><span>Classes in <a href="../../../../../../../../org/wildfly/swarm/config/security/security_domain/authentication/package-summary.html">org.wildfly.swarm.config.security.security_domain.authentication</a> with type parameters of type <a href="../../../../../../../../org/wildfly/swarm/config/security/security_domain/authentication/LoginModule.html" title="class in org.wildfly.swarm.config.security.security_domain.authentication">LoginModule</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Class and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../../../org/wildfly/swarm/config/security/security_domain/authentication/LoginModule.html" title="class in org.wildfly.swarm.config.security.security_domain.authentication">LoginModule</a><T extends <a href="../../../../../../../../org/wildfly/swarm/config/security/security_domain/authentication/LoginModule.html" title="class in org.wildfly.swarm.config.security.security_domain.authentication">LoginModule</a><T>></span></code>
<div class="block">List of authentication modules</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>interface </code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../../../org/wildfly/swarm/config/security/security_domain/authentication/LoginModuleConsumer.html" title="interface in org.wildfly.swarm.config.security.security_domain.authentication">LoginModuleConsumer</a><T extends <a href="../../../../../../../../org/wildfly/swarm/config/security/security_domain/authentication/LoginModule.html" title="class in org.wildfly.swarm.config.security.security_domain.authentication">LoginModule</a><T>></span></code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>interface </code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../../../org/wildfly/swarm/config/security/security_domain/authentication/LoginModuleSupplier.html" title="interface in org.wildfly.swarm.config.security.security_domain.authentication">LoginModuleSupplier</a><T extends <a href="../../../../../../../../org/wildfly/swarm/config/security/security_domain/authentication/LoginModule.html" title="class in org.wildfly.swarm.config.security.security_domain.authentication">LoginModule</a>></span></code> </td>
</tr>
</tbody>
</table>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../../../../org/wildfly/swarm/config/security/security_domain/authentication/package-summary.html">org.wildfly.swarm.config.security.security_domain.authentication</a> that return <a href="../../../../../../../../org/wildfly/swarm/config/security/security_domain/authentication/LoginModule.html" title="class in org.wildfly.swarm.config.security.security_domain.authentication">LoginModule</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../../../../org/wildfly/swarm/config/security/security_domain/authentication/LoginModule.html" title="class in org.wildfly.swarm.config.security.security_domain.authentication">LoginModule</a></code></td>
<td class="colLast"><span class="typeNameLabel">LoginModuleSupplier.</span><code><span class="memberNameLink"><a href="../../../../../../../../org/wildfly/swarm/config/security/security_domain/authentication/LoginModuleSupplier.html#get--">get</a></span>()</code>
<div class="block">Constructed instance of LoginModule resource</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code><a href="../../../../../../../../org/wildfly/swarm/config/security/security_domain/authentication/LoginModule.html" title="class in org.wildfly.swarm.config.security.security_domain.authentication">LoginModule</a></code></td>
<td class="colLast"><span class="typeNameLabel">LoginModuleStack.LoginModuleStackResources.</span><code><span class="memberNameLink"><a href="../../../../../../../../org/wildfly/swarm/config/security/security_domain/authentication/LoginModuleStack.LoginModuleStackResources.html#loginModule-java.lang.String-">loginModule</a></span>(<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a> key)</code> </td>
</tr>
</tbody>
</table>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../../../../org/wildfly/swarm/config/security/security_domain/authentication/package-summary.html">org.wildfly.swarm.config.security.security_domain.authentication</a> that return types with arguments of type <a href="../../../../../../../../org/wildfly/swarm/config/security/security_domain/authentication/LoginModule.html" title="class in org.wildfly.swarm.config.security.security_domain.authentication">LoginModule</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="https://docs.oracle.com/javase/8/docs/api/java/util/List.html?is-external=true" title="class or interface in java.util">List</a><<a href="../../../../../../../../org/wildfly/swarm/config/security/security_domain/authentication/LoginModule.html" title="class in org.wildfly.swarm.config.security.security_domain.authentication">LoginModule</a>></code></td>
<td class="colLast"><span class="typeNameLabel">LoginModuleStack.LoginModuleStackResources.</span><code><span class="memberNameLink"><a href="../../../../../../../../org/wildfly/swarm/config/security/security_domain/authentication/LoginModuleStack.LoginModuleStackResources.html#loginModules--">loginModules</a></span>()</code>
<div class="block">Get the list of LoginModule resources</div>
</td>
</tr>
</tbody>
</table>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../../../../org/wildfly/swarm/config/security/security_domain/authentication/package-summary.html">org.wildfly.swarm.config.security.security_domain.authentication</a> with parameters of type <a href="../../../../../../../../org/wildfly/swarm/config/security/security_domain/authentication/LoginModule.html" title="class in org.wildfly.swarm.config.security.security_domain.authentication">LoginModule</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../../../../org/wildfly/swarm/config/security/security_domain/authentication/LoginModuleStack.html" title="type parameter in LoginModuleStack">T</a></code></td>
<td class="colLast"><span class="typeNameLabel">LoginModuleStack.</span><code><span class="memberNameLink"><a href="../../../../../../../../org/wildfly/swarm/config/security/security_domain/authentication/LoginModuleStack.html#loginModule-org.wildfly.swarm.config.security.security_domain.authentication.LoginModule-">loginModule</a></span>(<a href="../../../../../../../../org/wildfly/swarm/config/security/security_domain/authentication/LoginModule.html" title="class in org.wildfly.swarm.config.security.security_domain.authentication">LoginModule</a> value)</code>
<div class="block">Add the LoginModule object to the list of subresources</div>
</td>
</tr>
</tbody>
</table>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Method parameters in <a href="../../../../../../../../org/wildfly/swarm/config/security/security_domain/authentication/package-summary.html">org.wildfly.swarm.config.security.security_domain.authentication</a> with type arguments of type <a href="../../../../../../../../org/wildfly/swarm/config/security/security_domain/authentication/LoginModule.html" title="class in org.wildfly.swarm.config.security.security_domain.authentication">LoginModule</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../../../../org/wildfly/swarm/config/security/security_domain/authentication/LoginModuleStack.html" title="type parameter in LoginModuleStack">T</a></code></td>
<td class="colLast"><span class="typeNameLabel">LoginModuleStack.</span><code><span class="memberNameLink"><a href="../../../../../../../../org/wildfly/swarm/config/security/security_domain/authentication/LoginModuleStack.html#loginModules-java.util.List-">loginModules</a></span>(<a href="https://docs.oracle.com/javase/8/docs/api/java/util/List.html?is-external=true" title="class or interface in java.util">List</a><<a href="../../../../../../../../org/wildfly/swarm/config/security/security_domain/authentication/LoginModule.html" title="class in org.wildfly.swarm.config.security.security_domain.authentication">LoginModule</a>> value)</code>
<div class="block">Add all LoginModule objects to this subresource</div>
</td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../../../org/wildfly/swarm/config/security/security_domain/authentication/LoginModule.html" title="class in org.wildfly.swarm.config.security.security_domain.authentication">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../../../../../../../../overview-tree.html">Tree</a></li>
<li><a href="../../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage">Thorntail API, 2.3.0.Final</div>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../../index.html?org/wildfly/swarm/config/security/security_domain/authentication/class-use/LoginModule.html" target="_top">Frames</a></li>
<li><a href="LoginModule.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2019 <a href="http://www.jboss.org">JBoss by Red Hat</a>. All rights reserved.</small></p>
</body>
</html>
| wildfly-swarm/wildfly-swarm-javadocs | 2.3.0.Final/apidocs/org/wildfly/swarm/config/security/security_domain/authentication/class-use/LoginModule.html | HTML | apache-2.0 | 23,909 |
package com.babarehner.android.pycolib;
import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.TextView;
import com.babarehner.android.pycolib.data.LibraryContract;
/**
* Created by mike on 12/23/16.
*/
public class PythonistaCursorAdapter extends CursorAdapter {
public PythonistaCursorAdapter(Context context, Cursor c) {
super(context, c /* flags*/);
}
/**
* creates a new blank list item with no data
* @param context app context
* @param c cursor
* @param parent parent to which view is attached to
* @return the newly created list item view
*/
@Override
public View newView(Context context, Cursor c, ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.list_pythonista, parent, false);
}
/**
* Binds data to the empty lsit item
* @param v
* @param context
* @param c
*/
@Override
public void bindView(View v, Context context, Cursor c) {
// find the id of the views to modify
TextView firstNameTV = (TextView) v.findViewById(R.id.first_name);
TextView lastNameTV = (TextView) v.findViewById(R.id.last_name);
int fNameColIndex = c.getColumnIndex(LibraryContract.LibraryEntry.COL_F_NAME);
int lNameColIndex = c.getColumnIndex(LibraryContract.LibraryEntry.COL_L_NAME);
String firstName = c.getString(fNameColIndex);
String lastName = c.getString(lNameColIndex);
firstNameTV.setText(firstName);
lastNameTV.setText(lastName + ", ");
}
}
| babarehner/Android-PyCoLib | app/src/main/java/com/babarehner/android/pycolib/PythonistaCursorAdapter.java | Java | apache-2.0 | 1,740 |
package com.netflix.evcache.config;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.netflix.archaius.config.PollingDynamicConfig;
import com.netflix.archaius.config.polling.FixedPollingStrategy;
import com.netflix.archaius.persisted2.DefaultPersisted2ClientConfig;
import com.netflix.archaius.persisted2.JsonPersistedV2Reader;
import com.netflix.archaius.persisted2.Persisted2ClientConfig;
import com.netflix.archaius.persisted2.ScopePredicates;
import com.netflix.archaius.persisted2.loader.HTTPStreamLoader;
public class EVCachePersistedProperties {
private static Logger log = LoggerFactory.getLogger(EVCachePersistedProperties.class);
private static final String SCOPE_CLUSTER = "cluster";
private static final String SCOPE_AMI = "ami";
private static final String SCOPE_ZONE = "zone";
private static final String SCOPE_ASG = "asg";
private static final String SCOPE_SERVER_ID = "serverId";
private static final String SCOPE_REGION = "region";
private static final String SCOPE_STACK = "stack";
private static final String SCOPE_ENV = "env";
private static final String SCOPE_APP_ID = "appId";
private PollingDynamicConfig config;
public EVCachePersistedProperties() {
}
private Persisted2ClientConfig getConfig() {
final String region = System.getProperty("netflix.region", getSystemEnvValue("NETFLIX_REGION", "us-east-1"));
final String env = System.getProperty("netflix.environment", getSystemEnvValue("NETFLIX_ENVIRONMENT", "test"));
String url = System.getProperty("platformserviceurl", "http://platformservice."+region+".dyn" + env +".netflix.net:7001/platformservice/REST/v2/properties/jsonFilterprops");
return new DefaultPersisted2ClientConfig()
.setEnabled(true)
.withServiceUrl(url)
.withQueryScope(SCOPE_APP_ID, System.getProperty("netflix.appId", getSystemEnvValue("NETFLIX_APP", "")), "")
.withQueryScope(SCOPE_ENV, env, "")
.withQueryScope(SCOPE_STACK, System.getProperty("netflix.stack", getSystemEnvValue("NETFLIX_STACK", "")), "")
.withQueryScope(SCOPE_REGION, region, "")
.withScope(SCOPE_APP_ID, System.getProperty("netflix.appId", getSystemEnvValue("NETFLIX_APP", "")))
.withScope(SCOPE_ENV, env)
.withScope(SCOPE_STACK, System.getProperty("netflix.stack", getSystemEnvValue("NETFLIX_STACK", "")))
.withScope(SCOPE_REGION, region)
.withScope(SCOPE_SERVER_ID, System.getProperty("netflix.serverId", getSystemEnvValue("NETFLIX_INSTANCE_ID", "")))
.withScope(SCOPE_ASG, System.getProperty("netflix.appinfo.asgName", getSystemEnvValue("NETFLIX_AUTO_SCALE_GROUP", "")))
.withScope(SCOPE_ZONE, getSystemEnvValue("EC2_AVAILABILITY_ZONE", ""))
.withScope(SCOPE_AMI, getSystemEnvValue("EC2_AMI_ID", ""))
.withScope(SCOPE_CLUSTER, getSystemEnvValue("NETFLIX_CLUSTER", ""))
.withPrioritizedScopes(SCOPE_SERVER_ID, SCOPE_ASG, SCOPE_AMI, SCOPE_CLUSTER, SCOPE_APP_ID, SCOPE_ENV, SCOPE_STACK, SCOPE_ZONE, SCOPE_REGION)
;
}
private String getSystemEnvValue(String key, String def) {
final String val = System.getenv(key);
return val == null ? def : val;
}
private String getFilterString(Map<String, Set<String>> scopes) {
StringBuilder sb = new StringBuilder();
for (Entry<String, Set<String>> scope : scopes.entrySet()) {
if (scope.getValue().isEmpty())
continue;
if (sb.length() > 0) {
sb.append(" and ");
}
sb.append("(");
boolean first = true;
for (String value : scope.getValue()) {
if (!first) {
sb.append(" or ");
}
else {
first = false;
}
sb.append(scope.getKey());
if (null == value) {
sb.append(" is null");
}
else if (value.isEmpty()) {
sb.append("=''");
}
else {
sb.append("='").append(value).append("'");
}
}
sb.append(")");
}
return sb.toString();
}
public PollingDynamicConfig getPollingDynamicConfig() {
try {
Persisted2ClientConfig clientConfig = getConfig();
log.info("Remote config : " + clientConfig);
String url = new StringBuilder()
.append(clientConfig.getServiceUrl())
.append("?skipPropsWithExtraScopes=").append(clientConfig.getSkipPropsWithExtraScopes())
.append("&filter=").append(URLEncoder.encode(getFilterString(clientConfig.getQueryScopes()), "UTF-8"))
.toString();
if (clientConfig.isEnabled()) {
JsonPersistedV2Reader reader = JsonPersistedV2Reader.builder(new HTTPStreamLoader(new URL(url)))
.withPath("propertiesList")
.withScopes(clientConfig.getPrioritizedScopes())
.withPredicate(ScopePredicates.fromMap(clientConfig.getScopes()))
.build();
config = new PollingDynamicConfig(reader, new FixedPollingStrategy(clientConfig.getRefreshRate(), TimeUnit.SECONDS));
return config;
}
} catch (Exception e1) {
throw new RuntimeException(e1);
}
return null;
}
}
| Netflix/EVCache | evcache-core/src/main/java/com/netflix/evcache/config/EVCachePersistedProperties.java | Java | apache-2.0 | 6,075 |
import { Injectable } from '@angular/core';
@Injectable()
export class ProgressbarConfig {
/** if `true` changing value of progress bar will be animated (note: not supported by Bootstrap 4) */
public animate: Boolean = true;
/** maximum total value of progress element */
public max: number = 100;
} | mayuranjan/the-hawker-front-end | src/app/typescripts/angular-bootstrap-md/pro/progress-bars/progressbarConfig.ts | TypeScript | apache-2.0 | 308 |
/*
* Copyright (c) 2020, Peter Abeles. All Rights Reserved.
*
* This file is part of BoofCV (http://boofcv.org).
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package boofcv.struct.image;
/**
* <p>
* An image where the primitive type is a signed byte.
* </p>
*
* @author Peter Abeles
*/
public class InterleavedS8 extends InterleavedI8<InterleavedS8> {
/**
* Creates a new image with an arbitrary number of bands/colors.
*
* @param width number of columns in the image.
* @param height number of rows in the image.
* @param numBands number of bands/colors in the image.
*/
public InterleavedS8( int width, int height, int numBands ) {
super(width, height, numBands);
}
public InterleavedS8() {}
@Override
public ImageDataType getDataType() {
return ImageDataType.S8;
}
/**
* Returns the value of the specified band in the specified pixel.
*
* @param x pixel coordinate.
* @param y pixel coordinate.
* @param band which color band in the pixel
* @return an intensity value.
*/
@Override
public int getBand( int x, int y, int band ) {
if (!isInBounds(x, y))
throw new ImageAccessException("Requested pixel is out of bounds.");
if (band < 0 || band >= numBands)
throw new ImageAccessException("Invalid band requested.");
return data[getIndex(x, y, band)];
}
@Override
public void unsafe_get( int x, int y, int[] storage ) {
int index = getIndex(x, y, 0);
for (int i = 0; i < numBands; i++, index++) {
storage[i] = data[index];
}
}
@Override
public InterleavedS8 createNew( int imgWidth, int imgHeight ) {
if (imgWidth == -1 || imgHeight == -1)
return new InterleavedS8();
return new InterleavedS8(imgWidth, imgHeight, numBands);
}
}
| lessthanoptimal/BoofCV | main/boofcv-types/src/noauto/java/boofcv/struct/image/InterleavedS8.java | Java | apache-2.0 | 2,237 |
/*
* Copyright 2015 West Coast Informatics, LLC
*/
package org.ihtsdo.otf.refset.rest.impl;
import java.util.HashSet;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
import org.apache.log4j.Logger;
import org.glassfish.jersey.jackson.JacksonFeature;
import org.glassfish.jersey.jsonp.JsonProcessingFeature;
import org.ihtsdo.otf.refset.helpers.ConfigUtility;
import com.ibm.icu.util.Calendar;
import com.wordnik.swagger.jaxrs.config.BeanConfig;
/**
* The application (for jersey). Also serves the role of the initialization
* listener.
*/
@ApplicationPath("/")
public class RefsetServerApplication extends Application {
/** The API_VERSION - also used in "swagger.htmL" */
public final static String API_VERSION = "1.0.0";
/** The timer. */
Timer timer;
/**
* Instantiates an empty {@link RefsetServerApplication}.
*
* @throws Exception the exception
*/
public RefsetServerApplication() throws Exception {
Logger.getLogger(getClass()).info("IHTSDO refset management service APPLICATION START");
BeanConfig beanConfig = new BeanConfig();
beanConfig.setTitle("IHTSDO refset management service API");
beanConfig.setDescription("RESTful calls for IHTSDO refset management service");
beanConfig.setVersion(API_VERSION);
beanConfig.setBasePath(ConfigUtility.getConfigProperties().getProperty(
"base.url"));
beanConfig.setResourcePackage("org.ihtsdo.otf.refset.rest.impl");
beanConfig.setScan(true);
// Set up a timer task to run at 2AM every day
TimerTask task = new InitializationTask();
timer = new Timer();
Calendar today = Calendar.getInstance();
today.set(Calendar.HOUR_OF_DAY, 2);
today.set(Calendar.MINUTE, 0);
today.set(Calendar.SECOND, 0);
timer.scheduleAtFixedRate(task, today.getTime(), 6 * 60 * 60 * 1000);
// Cache the "guest" user.
// SecurityService service;
// try {
// service = new SecurityServiceJpa();
// Properties config = ConfigUtility.getConfigProperties();
// if (config.getProperty("security.handler").equals("DEFAULT")) {
// service.authenticate("guest", "guest");
// }
// } catch (Exception e) {
// try {
// ExceptionHandler.handleException(e, "Cacheing guest user info");
// } catch (Exception e1) {
// // do nothing
// e1.printStackTrace();
// }
// }
}
/**
* Initialization task.
*/
class InitializationTask extends TimerTask {
/* see superclass */
@Override
public void run() {
// TODO:
}
}
/* see superclass */
@Override
public Set<Class<?>> getClasses() {
final Set<Class<?>> classes = new HashSet<Class<?>>();
// TODO: need to list services here
classes.add(SecurityServiceRestImpl.class);
classes.add(ProjectServiceRestImpl.class);
classes
.add(com.wordnik.swagger.jersey.listing.ApiListingResourceJSON.class);
classes
.add(com.wordnik.swagger.jersey.listing.JerseyApiDeclarationProvider.class);
classes
.add(com.wordnik.swagger.jersey.listing.JerseyResourceListingProvider.class);
return classes;
}
/* see superclass */
@Override
public Set<Object> getSingletons() {
final Set<Object> instances = new HashSet<Object>();
instances.add(new JacksonFeature());
instances.add(new JsonProcessingFeature());
// Enable for LOTS of logging of HTTP requests
// instances.add(new LoggingFilter());
return instances;
}
}
| WestCoastInformatics/ihtsdo-refset-tool | rest/src/main/java/org/ihtsdo/otf/refset/rest/impl/RefsetServerApplication.java | Java | apache-2.0 | 3,554 |
namespace Stumps.Server
{
using System.Collections.Generic;
/// <summary>
/// A class that represents a contract for a rule.
/// </summary>
public class RuleContract
{
private readonly List<RuleSetting> _ruleSettings;
/// <summary>
/// Initializes a new instance of the <see cref="RuleContract"/> class.
/// </summary>
public RuleContract()
{
_ruleSettings = new List<RuleSetting>();
}
/// <summary>
/// Initializes a new instance of the <see cref="RuleContract"/> class.
/// </summary>
/// <param name="rule">The <see cref="IStumpRule"/> used to create the instance.</param>
public RuleContract(IStumpRule rule) : this()
{
if (rule == null)
{
return;
}
this.RuleName = rule.GetType().Name;
var settings = rule.GetRuleSettings();
foreach (var setting in settings)
{
_ruleSettings.Add(setting);
}
}
/// <summary>
/// Gets or sets the name of the rule.
/// </summary>
/// <value>
/// The name of the rule.
/// </value>
public string RuleName
{
get;
set;
}
/// <summary>
/// Appends a <see cref="RuleSetting"/> to the contract.
/// </summary>
/// <param name="setting">The <see cref="RuleSetting"/> to add to the contract.</param>
public void AppendRuleSetting(RuleSetting setting)
{
if (setting == null || string.IsNullOrWhiteSpace(setting.Name) || setting.Value == null)
{
return;
}
_ruleSettings.Add(setting);
}
/// <summary>
/// Gets an array of the <see cref="RuleSetting" /> objects for the contract.
/// </summary>
/// <returns>An array of <see cref="RuleSetting"/> objects.</returns>
public RuleSetting[] GetRuleSettings() => _ruleSettings.ToArray();
}
}
| merchantwarehouse/stumps | src/main/dot-net/Stumps.Server/RuleContract.cs | C# | apache-2.0 | 2,133 |
package com.psc.vote.vote.dao;
import com.psc.vote.common.dao.ConnectionDao;
import com.psc.vote.vote.domain.Campaign;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
public class CampaignDao extends ConnectionDao {
public List<Campaign> getCampaignsByAnchor(String anchorName) {
System.out.println("AnchorName:" + anchorName);
StringBuilder selectStmt = new StringBuilder();
selectStmt.append("select c.campaign_id ");
selectStmt.append(" ,c.question ");
selectStmt.append(" ,c.start_date ");
selectStmt.append(" ,c.end_date ");
selectStmt.append(" ,c.region_country ");
selectStmt.append(" ,c.reward_info ");
selectStmt.append(" ,c.price ");
selectStmt.append(" ,c.status ");
selectStmt.append(" from campaigns c ");
selectStmt.append(" where c.anchor_id = ? ");
selectStmt.append(" and (c.status <> 'DELETED' OR c.status IS NULL) ");
selectStmt.append(" order by c.creation_date desc ");
System.out.println("selectStmt:" + selectStmt.toString());
return this.getJdbcTemplate().query(selectStmt.toString(), new Object[]{anchorName}, new CampaignRowMapper());
}
public Campaign getCampaign(String campaignId) {
StringBuilder selectStmt = new StringBuilder();
selectStmt.append("select c.campaign_id ");
selectStmt.append(" ,c.question ");
selectStmt.append(" ,c.start_date ");
selectStmt.append(" ,c.end_date ");
selectStmt.append(" ,c.region_country ");
selectStmt.append(" ,c.reward_info ");
selectStmt.append(" ,c.price ");
selectStmt.append(" ,c.status ");
selectStmt.append(" from campaigns c ");
selectStmt.append(" where c.campaign_id = ? ");
return this.getJdbcTemplate().queryForObject(selectStmt.toString(), new Object[]{campaignId}, new CampaignRowMapper());
}
public void createCampaign(Campaign campaign) throws Exception {
String insertStmt = "INSERT INTO campaigns(campaign_id, anchor_id, question, start_date, end_date, region_country, reward_info, creation_date) " +
" VALUES (:campaignId, :anchorId, :question, :startDate, :endDate, :regionCountry, :rewardInfo, sysdate());";
SqlParameterSource sqlParams = new BeanPropertySqlParameterSource(campaign);
try {
this.getNamedParameterJdbcTemplate().update(insertStmt, sqlParams);
} catch (Exception ex) {
System.out.println("failed to create campaign : " + campaign + ex.getMessage());
}
}
public void modifyCampaign(Campaign campaign) throws Exception {
String updateStmt = "UPDATE campaigns " +
" SET start_date = :startDate " +
" ,end_date = :endDate " +
" ,region_country = :regionCountry " +
" ,reward_info = :rewardInfo " +
" WHERE campaign_id = :campaignId ";
SqlParameterSource sqlParams = new BeanPropertySqlParameterSource(campaign);
try {
this.getNamedParameterJdbcTemplate().update(updateStmt, sqlParams);
} catch (Exception ex) {
System.out.println("failed to update campaign : " + campaign + ex.getMessage());
}
}
public void updateCampaignStatus(String campaignId, String status) throws Exception {
String updateStmt = "UPDATE campaigns SET status = ? WHERE campaign_id = ? ";
try {
this.getJdbcTemplate().update(updateStmt, new Object[]{status, campaignId});
} catch (Exception ex) {
System.out.println("failed to update status of campaign : " + campaignId + ex.getMessage());
throw ex;
}
}
private static final class CampaignRowMapper implements RowMapper<Campaign> {
@Override
public Campaign mapRow(ResultSet rs, int rowNum) throws SQLException {
Campaign campaign = new Campaign();
campaign.setCampaignId(rs.getString("CAMPAIGN_ID"));
campaign.setQuestion(rs.getString("QUESTION"));
campaign.setStartDate(rs.getDate("START_DATE"));
campaign.setEndDate(rs.getDate("END_DATE"));
campaign.setRegionCountry(rs.getString("REGION_COUNTRY"));
campaign.setRewardInfo(rs.getString("REWARD_INFO"));
campaign.setCampaignPrice(rs.getBigDecimal("PRICE"));
campaign.setStatus(rs.getString("STATUS"));
return campaign;
}
}
} | sgudupat/psc-vote-server | src/main/java/com/psc/vote/vote/dao/CampaignDao.java | Java | apache-2.0 | 4,923 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="pl">
<head>
<!-- Generated by javadoc -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>All Classes (Play! 2.x Provider for Play! 2.1.x 1.0.0-beta7 API)</title>
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style">
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<h1 class="bar">All Classes</h1>
<div class="indexContainer">
<ul>
<li><a href="com/google/code/play2/provider/play21/Play21CoffeescriptCompiler.html" title="class in com.google.code.play2.provider.play21">Play21CoffeescriptCompiler</a></li>
<li><a href="com/google/code/play2/provider/play21/Play21CoffeescriptCompiler.CompileResult.html" title="class in com.google.code.play2.provider.play21">Play21CoffeescriptCompiler.CompileResult</a></li>
<li><a href="com/google/code/play2/provider/play21/Play21EbeanEnhancer.html" title="class in com.google.code.play2.provider.play21">Play21EbeanEnhancer</a></li>
<li><a href="com/google/code/play2/provider/play21/Play21JavaEnhancer.html" title="class in com.google.code.play2.provider.play21">Play21JavaEnhancer</a></li>
<li><a href="com/google/code/play2/provider/play21/Play21JavascriptCompiler.html" title="class in com.google.code.play2.provider.play21">Play21JavascriptCompiler</a></li>
<li><a href="com/google/code/play2/provider/play21/Play21JavascriptCompiler.CompileResult.html" title="class in com.google.code.play2.provider.play21">Play21JavascriptCompiler.CompileResult</a></li>
<li><a href="com/google/code/play2/provider/play21/Play21LessCompiler.html" title="class in com.google.code.play2.provider.play21">Play21LessCompiler</a></li>
<li><a href="com/google/code/play2/provider/play21/Play21LessCompiler.CompileResult.html" title="class in com.google.code.play2.provider.play21">Play21LessCompiler.CompileResult</a></li>
<li><a href="com/google/code/play2/provider/play21/Play21Provider.html" title="class in com.google.code.play2.provider.play21">Play21Provider</a></li>
<li><a href="com/google/code/play2/provider/play21/Play21RoutesCompiler.html" title="class in com.google.code.play2.provider.play21">Play21RoutesCompiler</a></li>
<li><a href="com/google/code/play2/provider/play21/Play21Runner.html" title="class in com.google.code.play2.provider.play21">Play21Runner</a></li>
<li><a href="com/google/code/play2/provider/play21/Play21TemplateCompiler.html" title="class in com.google.code.play2.provider.play21">Play21TemplateCompiler</a></li>
</ul>
</div>
</body>
</html>
| play2-maven-plugin/play2-maven-plugin.github.io | play2-maven-plugin/1.0.0-beta7/play2-providers/play2-provider-play21/apidocs/allclasses-noframe.html | HTML | apache-2.0 | 2,613 |
# AUTOGENERATED FILE
FROM balenalib/jetson-xavier-nx-devkit-emmc-alpine:edge-build
# remove several traces of python
RUN apk del python*
# http://bugs.python.org/issue19846
# > At the moment, setting "LANG=C" on a Linux system *fundamentally breaks Python 3*, and that's not OK.
ENV LANG C.UTF-8
# key 63C7CC90: public key "Simon McVittie <smcv@pseudorandom.co.uk>" imported
# key 3372DCFA: public key "Donald Stufft (dstufft) <donald@stufft.io>" imported
RUN gpg --keyserver keyring.debian.org --recv-keys 4DE8FF2A63C7CC90 \
&& gpg --keyserver keyserver.ubuntu.com --recv-key 6E3CBCE93372DCFA \
&& gpg --keyserver keyserver.ubuntu.com --recv-keys 0x52a43a1e4b77b059
# point Python at a system-provided certificate database. Otherwise, we might hit CERTIFICATE_VERIFY_FAILED.
# https://www.python.org/dev/peps/pep-0476/#trust-database
ENV SSL_CERT_FILE /etc/ssl/certs/ca-certificates.crt
ENV PYTHON_VERSION 3.8.6
# if this is called "PIP_VERSION", pip explodes with "ValueError: invalid truth value '<VERSION>'"
ENV PYTHON_PIP_VERSION 20.3.1
ENV SETUPTOOLS_VERSION 51.0.0
RUN set -x \
&& curl -SLO "http://resin-packages.s3.amazonaws.com/python/v$PYTHON_VERSION/Python-$PYTHON_VERSION.linux-alpine-aarch64-openssl1.1.tar.gz" \
&& echo "e1c61b20b9e3c35cc6fe765b4d49426ebfef188580592da1bdcd9ed40564e612 Python-$PYTHON_VERSION.linux-alpine-aarch64-openssl1.1.tar.gz" | sha256sum -c - \
&& tar -xzf "Python-$PYTHON_VERSION.linux-alpine-aarch64-openssl1.1.tar.gz" --strip-components=1 \
&& rm -rf "Python-$PYTHON_VERSION.linux-alpine-aarch64-openssl1.1.tar.gz" \
&& if [ ! -e /usr/local/bin/pip3 ]; then : \
&& curl -SLO "https://raw.githubusercontent.com/pypa/get-pip/430ba37776ae2ad89f794c7a43b90dc23bac334c/get-pip.py" \
&& echo "19dae841a150c86e2a09d475b5eb0602861f2a5b7761ec268049a662dbd2bd0c get-pip.py" | sha256sum -c - \
&& python3 get-pip.py \
&& rm get-pip.py \
; fi \
&& pip3 install --no-cache-dir --upgrade --force-reinstall pip=="$PYTHON_PIP_VERSION" setuptools=="$SETUPTOOLS_VERSION" \
&& find /usr/local \
\( -type d -a -name test -o -name tests \) \
-o \( -type f -a -name '*.pyc' -o -name '*.pyo' \) \
-exec rm -rf '{}' + \
&& cd / \
&& rm -rf /usr/src/python ~/.cache
# install "virtualenv", since the vast majority of users of this image will want it
RUN pip3 install --no-cache-dir virtualenv
ENV PYTHON_DBUS_VERSION 1.2.8
# install dbus-python dependencies
RUN apk add --no-cache \
dbus-dev \
dbus-glib-dev
# install dbus-python
RUN set -x \
&& mkdir -p /usr/src/dbus-python \
&& curl -SL "http://dbus.freedesktop.org/releases/dbus-python/dbus-python-$PYTHON_DBUS_VERSION.tar.gz" -o dbus-python.tar.gz \
&& curl -SL "http://dbus.freedesktop.org/releases/dbus-python/dbus-python-$PYTHON_DBUS_VERSION.tar.gz.asc" -o dbus-python.tar.gz.asc \
&& gpg --verify dbus-python.tar.gz.asc \
&& tar -xzC /usr/src/dbus-python --strip-components=1 -f dbus-python.tar.gz \
&& rm dbus-python.tar.gz* \
&& cd /usr/src/dbus-python \
&& PYTHON_VERSION=$(expr match "$PYTHON_VERSION" '\([0-9]*\.[0-9]*\)') ./configure \
&& make -j$(nproc) \
&& make install -j$(nproc) \
&& cd / \
&& rm -rf /usr/src/dbus-python
# make some useful symlinks that are expected to exist
RUN cd /usr/local/bin \
&& ln -sf pip3 pip \
&& { [ -e easy_install ] || ln -s easy_install-* easy_install; } \
&& ln -sf idle3 idle \
&& ln -sf pydoc3 pydoc \
&& ln -sf python3 python \
&& ln -sf python3-config python-config
CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"]
RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/test-stack@python.sh" \
&& echo "Running test-stack@python" \
&& chmod +x test-stack@python.sh \
&& bash test-stack@python.sh \
&& rm -rf test-stack@python.sh
RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo $'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v8 \nOS: Alpine Linux edge \nVariant: build variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nPython v3.8.6, Pip v20.3.1, Setuptools v51.0.0 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info
RUN echo $'#!/bin/bash\nbalena-info\nbusybox ln -sf /bin/busybox /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \
&& chmod +x /bin/sh-shim \
&& ln -f /bin/sh /bin/sh.real \
&& ln -f /bin/sh-shim /bin/sh | nghiant2710/base-images | balena-base-images/python/jetson-xavier-nx-devkit-emmc/alpine/edge/3.8.6/build/Dockerfile | Dockerfile | apache-2.0 | 4,855 |
# [Start Bootstrap](http://startbootstrap.com/) - [Freelancer](http://startbootstrap.com/template-overviews/freelancer/)
[Freelancer](http://startbootstrap.com/template-overviews/freelancer/) is a one page freelancer portfolio theme for [Bootstrap](http://getbootstrap.com/) created by [Start Bootstrap](http://startbootstrap.com/). This theme features several content sections, a responsive portfolio grid with hover effects, full page portfolio item modals, and a working PHP contact form.
## Getting Started
To use this theme, choose one of the following options to get started:
* Download the latest release on Start Bootstrap
* Fork this repository on GitHub
## Bugs and Issues
Have a bug or an issue with this theme? [Open a new issue](https://github.com/IronSummitMedia/startbootstrap-freelancer/issues) here on GitHub or leave a comment on the [template overview page at Start Bootstrap](http://startbootstrap.com/template-overviews/freelancer/).
## Creator
Start Bootstrap was created by and is maintained by **David Miller**, Managing Parter at [Iron Summit Media Strategies](http://www.ironsummitmedia.com/).
* https://twitter.com/davidmillerskt
* https://github.com/davidtmiller
Start Bootstrap is based on the [Bootstrap](http://getbootstrap.com/) framework created by [Mark Otto](https://twitter.com/mdo) and [Jacob Thorton](https://twitter.com/fat).
## Copyright and License
Copyright 2013-2015 Iron Summit Media Strategies, LLC. Code released under the [Apache 2.0](https://github.com/IronSummitMedia/startbootstrap-freelancer/blob/gh-pages/LICENSE) license.# JeffYourmanFullStackWebsite
| jeffreyyourman/JeffYourmanFullStackWebsite | README.md | Markdown | apache-2.0 | 1,615 |
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using MediatR.Pipeline;
namespace MediatR.Examples;
public class GenericRequestPostProcessor<TRequest, TResponse> : IRequestPostProcessor<TRequest, TResponse>
where TRequest : IRequest<TResponse>
{
private readonly TextWriter _writer;
public GenericRequestPostProcessor(TextWriter writer)
{
_writer = writer;
}
public Task Process(TRequest request, TResponse response, CancellationToken cancellationToken)
{
return _writer.WriteLineAsync("- All Done");
}
} | jbogard/MediatR | samples/MediatR.Examples/GenericRequestPostProcessor.cs | C# | apache-2.0 | 579 |
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package com.cloud.storage;
import java.math.BigDecimal;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.UnknownHostException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import javax.inject.Inject;
import javax.naming.ConfigurationException;
import com.cloud.hypervisor.Hypervisor;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import org.apache.cloudstack.api.command.admin.storage.CancelPrimaryStorageMaintenanceCmd;
import org.apache.cloudstack.api.command.admin.storage.CreateSecondaryStagingStoreCmd;
import org.apache.cloudstack.api.command.admin.storage.CreateStoragePoolCmd;
import org.apache.cloudstack.api.command.admin.storage.DeleteImageStoreCmd;
import org.apache.cloudstack.api.command.admin.storage.DeletePoolCmd;
import org.apache.cloudstack.api.command.admin.storage.DeleteSecondaryStagingStoreCmd;
import org.apache.cloudstack.api.command.admin.storage.UpdateStoragePoolCmd;
import org.apache.cloudstack.context.CallContext;
import org.apache.cloudstack.engine.subsystem.api.storage.ClusterScope;
import org.apache.cloudstack.engine.subsystem.api.storage.DataStore;
import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreDriver;
import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreLifeCycle;
import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreManager;
import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreProvider;
import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreProviderManager;
import org.apache.cloudstack.engine.subsystem.api.storage.EndPoint;
import org.apache.cloudstack.engine.subsystem.api.storage.EndPointSelector;
import org.apache.cloudstack.engine.subsystem.api.storage.HostScope;
import org.apache.cloudstack.engine.subsystem.api.storage.HypervisorHostListener;
import org.apache.cloudstack.engine.subsystem.api.storage.ImageStoreProvider;
import org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStoreDriver;
import org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStoreInfo;
import org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStoreLifeCycle;
import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotDataFactory;
import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotInfo;
import org.apache.cloudstack.engine.subsystem.api.storage.TemplateDataFactory;
import org.apache.cloudstack.engine.subsystem.api.storage.TemplateInfo;
import org.apache.cloudstack.engine.subsystem.api.storage.TemplateService;
import org.apache.cloudstack.engine.subsystem.api.storage.TemplateService.TemplateApiResult;
import org.apache.cloudstack.engine.subsystem.api.storage.VolumeDataFactory;
import org.apache.cloudstack.engine.subsystem.api.storage.VolumeInfo;
import org.apache.cloudstack.engine.subsystem.api.storage.VolumeService;
import org.apache.cloudstack.engine.subsystem.api.storage.VolumeService.VolumeApiResult;
import org.apache.cloudstack.engine.subsystem.api.storage.ZoneScope;
import org.apache.cloudstack.framework.async.AsyncCallFuture;
import org.apache.cloudstack.framework.config.ConfigKey;
import org.apache.cloudstack.framework.config.Configurable;
import org.apache.cloudstack.framework.config.dao.ConfigurationDao;
import org.apache.cloudstack.storage.command.DettachCommand;
import org.apache.cloudstack.managed.context.ManagedContextRunnable;
import org.apache.cloudstack.storage.datastore.db.ImageStoreDao;
import org.apache.cloudstack.storage.datastore.db.ImageStoreDetailsDao;
import org.apache.cloudstack.storage.datastore.db.ImageStoreVO;
import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao;
import org.apache.cloudstack.storage.datastore.db.SnapshotDataStoreDao;
import org.apache.cloudstack.storage.datastore.db.SnapshotDataStoreVO;
import org.apache.cloudstack.storage.datastore.db.StoragePoolDetailsDao;
import org.apache.cloudstack.storage.datastore.db.StoragePoolVO;
import org.apache.cloudstack.storage.datastore.db.TemplateDataStoreDao;
import org.apache.cloudstack.storage.datastore.db.TemplateDataStoreVO;
import org.apache.cloudstack.storage.datastore.db.VolumeDataStoreDao;
import org.apache.cloudstack.storage.datastore.db.VolumeDataStoreVO;
import org.apache.cloudstack.storage.image.datastore.ImageStoreEntity;
import org.apache.cloudstack.storage.to.VolumeObjectTO;
import com.cloud.agent.AgentManager;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.Command;
import com.cloud.agent.api.StoragePoolInfo;
import com.cloud.agent.api.to.DataTO;
import com.cloud.agent.api.to.DiskTO;
import com.cloud.agent.manager.Commands;
import com.cloud.api.ApiDBUtils;
import com.cloud.api.query.dao.TemplateJoinDao;
import com.cloud.api.query.vo.TemplateJoinVO;
import com.cloud.capacity.Capacity;
import com.cloud.capacity.CapacityManager;
import com.cloud.capacity.CapacityState;
import com.cloud.capacity.CapacityVO;
import com.cloud.capacity.dao.CapacityDao;
import com.cloud.cluster.ClusterManagerListener;
import com.cloud.cluster.ManagementServerHost;
import com.cloud.configuration.Config;
import com.cloud.configuration.ConfigurationManager;
import com.cloud.configuration.ConfigurationManagerImpl;
import com.cloud.configuration.Resource.ResourceType;
import com.cloud.dc.ClusterVO;
import com.cloud.dc.DataCenterVO;
import com.cloud.dc.dao.ClusterDao;
import com.cloud.dc.dao.DataCenterDao;
import com.cloud.event.ActionEvent;
import com.cloud.event.EventTypes;
import com.cloud.exception.AgentUnavailableException;
import com.cloud.exception.ConnectionException;
import com.cloud.exception.DiscoveryException;
import com.cloud.exception.InsufficientCapacityException;
import com.cloud.exception.InvalidParameterValueException;
import com.cloud.exception.OperationTimedoutException;
import com.cloud.exception.PermissionDeniedException;
import com.cloud.exception.ResourceInUseException;
import com.cloud.exception.ResourceUnavailableException;
import com.cloud.exception.StorageConflictException;
import com.cloud.exception.StorageUnavailableException;
import com.cloud.host.Host;
import com.cloud.host.HostVO;
import com.cloud.host.Status;
import com.cloud.host.dao.HostDao;
import com.cloud.hypervisor.Hypervisor.HypervisorType;
import com.cloud.hypervisor.HypervisorGuruManager;
import com.cloud.offering.DiskOffering;
import com.cloud.offering.ServiceOffering;
import com.cloud.org.Grouping;
import com.cloud.org.Grouping.AllocationState;
import com.cloud.resource.ResourceState;
import com.cloud.server.ConfigurationServer;
import com.cloud.server.ManagementServer;
import com.cloud.server.StatsCollector;
import com.cloud.storage.Storage.ImageFormat;
import com.cloud.storage.Storage.StoragePoolType;
import com.cloud.storage.Volume.Type;
import com.cloud.storage.dao.DiskOfferingDao;
import com.cloud.storage.dao.SnapshotDao;
import com.cloud.storage.dao.StoragePoolHostDao;
import com.cloud.storage.dao.StoragePoolTagsDao;
import com.cloud.storage.dao.StoragePoolWorkDao;
import com.cloud.storage.dao.VMTemplateDao;
import com.cloud.storage.dao.VMTemplatePoolDao;
import com.cloud.storage.dao.VMTemplateZoneDao;
import com.cloud.storage.dao.VolumeDao;
import com.cloud.storage.listener.StoragePoolMonitor;
import com.cloud.storage.listener.VolumeStateListener;
import com.cloud.template.TemplateManager;
import com.cloud.template.VirtualMachineTemplate;
import com.cloud.user.Account;
import com.cloud.user.AccountManager;
import com.cloud.user.ResourceLimitService;
import com.cloud.user.dao.UserDao;
import com.cloud.utils.DateUtil;
import com.cloud.utils.NumbersUtil;
import com.cloud.utils.Pair;
import com.cloud.utils.StringUtils;
import com.cloud.utils.UriUtils;
import com.cloud.utils.component.ComponentContext;
import com.cloud.utils.component.ManagerBase;
import com.cloud.utils.concurrency.NamedThreadFactory;
import com.cloud.utils.db.DB;
import com.cloud.utils.db.EntityManager;
import com.cloud.utils.db.GenericSearchBuilder;
import com.cloud.utils.db.GlobalLock;
import com.cloud.utils.db.JoinBuilder;
import com.cloud.utils.db.JoinBuilder.JoinType;
import com.cloud.utils.db.SearchBuilder;
import com.cloud.utils.db.SearchCriteria;
import com.cloud.utils.db.SearchCriteria.Op;
import com.cloud.utils.db.Transaction;
import com.cloud.utils.db.TransactionCallbackNoReturn;
import com.cloud.utils.db.TransactionLegacy;
import com.cloud.utils.db.TransactionStatus;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.vm.DiskProfile;
import com.cloud.vm.VMInstanceVO;
import com.cloud.vm.VirtualMachine.State;
import com.cloud.vm.dao.VMInstanceDao;
@Component
public class StorageManagerImpl extends ManagerBase implements StorageManager, ClusterManagerListener, Configurable {
private static final Logger s_logger = Logger.getLogger(StorageManagerImpl.class);
protected String _name;
@Inject
protected AgentManager _agentMgr;
@Inject
protected TemplateManager _tmpltMgr;
@Inject
protected AccountManager _accountMgr;
@Inject
protected ConfigurationManager _configMgr;
@Inject
protected VolumeDao _volsDao;
@Inject
private VolumeDataStoreDao _volumeDataStoreDao;
@Inject
protected HostDao _hostDao;
@Inject
protected SnapshotDao _snapshotDao;
@Inject
protected StoragePoolHostDao _storagePoolHostDao;
@Inject
protected VMTemplatePoolDao _vmTemplatePoolDao = null;
@Inject
protected VMTemplateZoneDao _vmTemplateZoneDao;
@Inject
protected VMTemplateDao _vmTemplateDao = null;
@Inject
protected VMInstanceDao _vmInstanceDao;
@Inject
protected PrimaryDataStoreDao _storagePoolDao = null;
@Inject
protected StoragePoolDetailsDao _storagePoolDetailsDao;
@Inject
protected ImageStoreDao _imageStoreDao = null;
@Inject
protected ImageStoreDetailsDao _imageStoreDetailsDao = null;
@Inject
protected SnapshotDataStoreDao _snapshotStoreDao = null;
@Inject
protected TemplateDataStoreDao _templateStoreDao = null;
@Inject
protected TemplateJoinDao _templateViewDao = null;
@Inject
protected VolumeDataStoreDao _volumeStoreDao = null;
@Inject
protected CapacityDao _capacityDao;
@Inject
protected CapacityManager _capacityMgr;
@Inject
protected DataCenterDao _dcDao = null;
@Inject
protected VMTemplateDao _templateDao;
@Inject
protected UserDao _userDao;
@Inject
protected ClusterDao _clusterDao;
@Inject
protected StoragePoolWorkDao _storagePoolWorkDao;
@Inject
protected HypervisorGuruManager _hvGuruMgr;
@Inject
protected VolumeDao _volumeDao;
@Inject
ConfigurationDao _configDao;
@Inject
ManagementServer _msServer;
@Inject
VolumeService volService;
@Inject
VolumeDataFactory volFactory;
@Inject
TemplateDataFactory tmplFactory;
@Inject
SnapshotDataFactory snapshotFactory;
@Inject
ConfigurationServer _configServer;
@Inject
DataStoreManager _dataStoreMgr;
@Inject
DataStoreProviderManager _dataStoreProviderMgr;
@Inject
private TemplateService _imageSrv;
@Inject
EndPointSelector _epSelector;
@Inject
private DiskOfferingDao _diskOfferingDao;
@Inject
ResourceLimitService _resourceLimitMgr;
@Inject
EntityManager _entityMgr;
@Inject
StoragePoolTagsDao _storagePoolTagsDao;
protected List<StoragePoolDiscoverer> _discoverers;
public List<StoragePoolDiscoverer> getDiscoverers() {
return _discoverers;
}
public void setDiscoverers(List<StoragePoolDiscoverer> discoverers) {
_discoverers = discoverers;
}
protected SearchBuilder<VMTemplateHostVO> HostTemplateStatesSearch;
protected GenericSearchBuilder<StoragePoolHostVO, Long> UpHostsInPoolSearch;
protected SearchBuilder<VMInstanceVO> StoragePoolSearch;
protected SearchBuilder<StoragePoolVO> LocalStorageSearch;
ScheduledExecutorService _executor = null;
boolean _templateCleanupEnabled = true;
int _storagePoolAcquisitionWaitSeconds = 1800; // 30 minutes
int _downloadUrlCleanupInterval;
int _downloadUrlExpirationInterval;
// protected BigDecimal _overProvisioningFactor = new BigDecimal(1);
private long _serverId;
private final Map<String, HypervisorHostListener> hostListeners = new HashMap<String, HypervisorHostListener>();
public boolean share(VMInstanceVO vm, List<VolumeVO> vols, HostVO host, boolean cancelPreviousShare) throws StorageUnavailableException {
// if pool is in maintenance and it is the ONLY pool available; reject
List<VolumeVO> rootVolForGivenVm = _volsDao.findByInstanceAndType(vm.getId(), Type.ROOT);
if (rootVolForGivenVm != null && rootVolForGivenVm.size() > 0) {
boolean isPoolAvailable = isPoolAvailable(rootVolForGivenVm.get(0).getPoolId());
if (!isPoolAvailable) {
throw new StorageUnavailableException("Can not share " + vm, rootVolForGivenVm.get(0).getPoolId());
}
}
// this check is done for maintenance mode for primary storage
// if any one of the volume is unusable, we return false
// if we return false, the allocator will try to switch to another PS if
// available
for (VolumeVO vol : vols) {
if (vol.getRemoved() != null) {
s_logger.warn("Volume id:" + vol.getId() + " is removed, cannot share on this instance");
// not ok to share
return false;
}
}
// ok to share
return true;
}
private boolean isPoolAvailable(Long poolId) {
// get list of all pools
List<StoragePoolVO> pools = _storagePoolDao.listAll();
// if no pools or 1 pool which is in maintenance
if (pools == null || pools.size() == 0 || (pools.size() == 1 && pools.get(0).getStatus().equals(StoragePoolStatus.Maintenance))) {
return false;
} else {
return true;
}
}
@Override
public List<StoragePoolVO> ListByDataCenterHypervisor(long datacenterId, HypervisorType type) {
List<StoragePoolVO> pools = _storagePoolDao.listByDataCenterId(datacenterId);
List<StoragePoolVO> retPools = new ArrayList<StoragePoolVO>();
for (StoragePoolVO pool : pools) {
if (pool.getStatus() != StoragePoolStatus.Up) {
continue;
}
if (pool.getScope() == ScopeType.ZONE) {
if (pool.getHypervisor() != null && pool.getHypervisor() == type) {
retPools.add(pool);
}
} else {
ClusterVO cluster = _clusterDao.findById(pool.getClusterId());
if (type == cluster.getHypervisorType()) {
retPools.add(pool);
}
}
}
Collections.shuffle(retPools);
return retPools;
}
@Override
public boolean isLocalStorageActiveOnHost(Long hostId) {
List<StoragePoolHostVO> storagePoolHostRefs = _storagePoolHostDao.listByHostId(hostId);
for (StoragePoolHostVO storagePoolHostRef : storagePoolHostRefs) {
StoragePoolVO PrimaryDataStoreVO = _storagePoolDao.findById(storagePoolHostRef.getPoolId());
if (PrimaryDataStoreVO.getPoolType() == StoragePoolType.LVM || PrimaryDataStoreVO.getPoolType() == StoragePoolType.EXT) {
SearchBuilder<VolumeVO> volumeSB = _volsDao.createSearchBuilder();
volumeSB.and("poolId", volumeSB.entity().getPoolId(), SearchCriteria.Op.EQ);
volumeSB.and("removed", volumeSB.entity().getRemoved(), SearchCriteria.Op.NULL);
volumeSB.and("state", volumeSB.entity().getState(), SearchCriteria.Op.NIN);
SearchBuilder<VMInstanceVO> activeVmSB = _vmInstanceDao.createSearchBuilder();
activeVmSB.and("state", activeVmSB.entity().getState(), SearchCriteria.Op.IN);
volumeSB.join("activeVmSB", activeVmSB, volumeSB.entity().getInstanceId(), activeVmSB.entity().getId(), JoinBuilder.JoinType.INNER);
SearchCriteria<VolumeVO> volumeSC = volumeSB.create();
volumeSC.setParameters("poolId", PrimaryDataStoreVO.getId());
volumeSC.setParameters("state", Volume.State.Expunging, Volume.State.Destroy);
volumeSC.setJoinParameters("activeVmSB", "state", State.Starting, State.Running, State.Stopping, State.Migrating);
List<VolumeVO> volumes = _volsDao.search(volumeSC, null);
if (volumes.size() > 0) {
return true;
}
}
}
return false;
}
@Override
public Answer[] sendToPool(StoragePool pool, Commands cmds) throws StorageUnavailableException {
return sendToPool(pool, null, null, cmds).second();
}
@Override
public Answer sendToPool(StoragePool pool, long[] hostIdsToTryFirst, Command cmd) throws StorageUnavailableException {
Answer[] answers = sendToPool(pool, hostIdsToTryFirst, null, new Commands(cmd)).second();
if (answers == null) {
return null;
}
return answers[0];
}
@Override
public Answer sendToPool(StoragePool pool, Command cmd) throws StorageUnavailableException {
Answer[] answers = sendToPool(pool, new Commands(cmd));
if (answers == null) {
return null;
}
return answers[0];
}
public Long chooseHostForStoragePool(StoragePoolVO poolVO, List<Long> avoidHosts, boolean sendToVmResidesOn, Long vmId) {
if (sendToVmResidesOn) {
if (vmId != null) {
VMInstanceVO vmInstance = _vmInstanceDao.findById(vmId);
if (vmInstance != null) {
Long hostId = vmInstance.getHostId();
if (hostId != null && !avoidHosts.contains(vmInstance.getHostId())) {
return hostId;
}
}
}
/*
* Can't find the vm where host resides on(vm is destroyed? or
* volume is detached from vm), randomly choose a host to send the
* cmd
*/
}
List<StoragePoolHostVO> poolHosts = _storagePoolHostDao.listByHostStatus(poolVO.getId(), Status.Up);
Collections.shuffle(poolHosts);
if (poolHosts != null && poolHosts.size() > 0) {
for (StoragePoolHostVO sphvo : poolHosts) {
if (!avoidHosts.contains(sphvo.getHostId())) {
return sphvo.getHostId();
}
}
}
return null;
}
@Override
public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
Map<String, String> configs = _configDao.getConfiguration("management-server", params);
_storagePoolAcquisitionWaitSeconds = NumbersUtil.parseInt(configs.get("pool.acquisition.wait.seconds"), 1800);
s_logger.info("pool.acquisition.wait.seconds is configured as " + _storagePoolAcquisitionWaitSeconds + " seconds");
_agentMgr.registerForHostEvents(new StoragePoolMonitor(this, _storagePoolDao, _dataStoreProviderMgr), true, false, true);
String value = _configDao.getValue(Config.StorageTemplateCleanupEnabled.key());
_templateCleanupEnabled = (value == null ? true : Boolean.parseBoolean(value));
s_logger.info("Storage cleanup enabled: " + StorageCleanupEnabled.value() + ", interval: " + StorageCleanupInterval.value() + ", delay: " + StorageCleanupDelay.value() +
", template cleanup enabled: " + _templateCleanupEnabled);
String cleanupInterval = configs.get("extract.url.cleanup.interval");
_downloadUrlCleanupInterval = NumbersUtil.parseInt(cleanupInterval, 7200);
String urlExpirationInterval = configs.get("extract.url.expiration.interval");
_downloadUrlExpirationInterval = NumbersUtil.parseInt(urlExpirationInterval, 14400);
String workers = configs.get("expunge.workers");
int wrks = NumbersUtil.parseInt(workers, 10);
_executor = Executors.newScheduledThreadPool(wrks, new NamedThreadFactory("StorageManager-Scavenger"));
_agentMgr.registerForHostEvents(ComponentContext.inject(LocalStoragePoolListener.class), true, false, false);
_serverId = _msServer.getId();
UpHostsInPoolSearch = _storagePoolHostDao.createSearchBuilder(Long.class);
UpHostsInPoolSearch.selectFields(UpHostsInPoolSearch.entity().getHostId());
SearchBuilder<HostVO> hostSearch = _hostDao.createSearchBuilder();
hostSearch.and("status", hostSearch.entity().getStatus(), Op.EQ);
hostSearch.and("resourceState", hostSearch.entity().getResourceState(), Op.EQ);
UpHostsInPoolSearch.join("hosts", hostSearch, hostSearch.entity().getId(), UpHostsInPoolSearch.entity().getHostId(), JoinType.INNER);
UpHostsInPoolSearch.and("pool", UpHostsInPoolSearch.entity().getPoolId(), Op.EQ);
UpHostsInPoolSearch.done();
StoragePoolSearch = _vmInstanceDao.createSearchBuilder();
SearchBuilder<VolumeVO> volumeSearch = _volumeDao.createSearchBuilder();
volumeSearch.and("volumeType", volumeSearch.entity().getVolumeType(), SearchCriteria.Op.EQ);
volumeSearch.and("poolId", volumeSearch.entity().getPoolId(), SearchCriteria.Op.EQ);
volumeSearch.and("state", volumeSearch.entity().getState(), SearchCriteria.Op.EQ);
StoragePoolSearch.join("vmVolume", volumeSearch, volumeSearch.entity().getInstanceId(), StoragePoolSearch.entity().getId(), JoinBuilder.JoinType.INNER);
StoragePoolSearch.done();
LocalStorageSearch = _storagePoolDao.createSearchBuilder();
SearchBuilder<StoragePoolHostVO> storageHostSearch = _storagePoolHostDao.createSearchBuilder();
storageHostSearch.and("hostId", storageHostSearch.entity().getHostId(), SearchCriteria.Op.EQ);
LocalStorageSearch.join("poolHost", storageHostSearch, storageHostSearch.entity().getPoolId(), LocalStorageSearch.entity().getId(), JoinBuilder.JoinType.INNER);
LocalStorageSearch.and("type", LocalStorageSearch.entity().getPoolType(), SearchCriteria.Op.IN);
LocalStorageSearch.done();
Volume.State.getStateMachine().registerListener(new VolumeStateListener(_configDao, _vmInstanceDao));
return true;
}
@Override
public String getStoragePoolTags(long poolId) {
return StringUtils.listToCsvTags(_storagePoolDao.searchForStoragePoolTags(poolId));
}
@Override
public boolean start() {
if (StorageCleanupEnabled.value()) {
Random generator = new Random();
int initialDelay = generator.nextInt(StorageCleanupInterval.value());
_executor.scheduleWithFixedDelay(new StorageGarbageCollector(), initialDelay, StorageCleanupInterval.value(), TimeUnit.SECONDS);
} else {
s_logger.debug("Storage cleanup is not enabled, so the storage cleanup thread is not being scheduled.");
}
_executor.scheduleWithFixedDelay(new DownloadURLGarbageCollector(), _downloadUrlCleanupInterval, _downloadUrlCleanupInterval, TimeUnit.SECONDS);
return true;
}
@Override
public boolean stop() {
if (StorageCleanupEnabled.value()) {
_executor.shutdown();
}
return true;
}
@DB
@Override
public DataStore createLocalStorage(Host host, StoragePoolInfo pInfo) throws ConnectionException {
DataCenterVO dc = _dcDao.findById(host.getDataCenterId());
if (dc == null) {
return null;
}
boolean useLocalStorageForSystemVM = false;
Boolean isLocal = ConfigurationManagerImpl.SystemVMUseLocalStorage.valueIn(dc.getId());
if (isLocal != null) {
useLocalStorageForSystemVM = isLocal.booleanValue();
}
if (!(dc.isLocalStorageEnabled() || useLocalStorageForSystemVM)) {
return null;
}
DataStore store;
try {
String hostAddress = pInfo.getHost();
if (host.getHypervisorType() == Hypervisor.HypervisorType.VMware) {
hostAddress = "VMFS datastore: " + pInfo.getHostPath();
}
StoragePoolVO pool = _storagePoolDao.findPoolByHostPath(host.getDataCenterId(), host.getPodId(), hostAddress, pInfo.getHostPath(), pInfo.getUuid());
if (pool == null && host.getHypervisorType() == HypervisorType.VMware) {
// perform run-time upgrade. In versions prior to 2.2.12, there
// is a bug that we don't save local datastore info (host path
// is empty), this will cause us
// not able to distinguish multiple local datastores that may be
// available on the host, to support smooth migration, we
// need to perform runtime upgrade here
if (pInfo.getHostPath().length() > 0) {
pool = _storagePoolDao.findPoolByHostPath(host.getDataCenterId(), host.getPodId(), hostAddress, "", pInfo.getUuid());
}
}
if (pool == null) {
//the path can be different, but if they have the same uuid, assume they are the same storage
pool = _storagePoolDao.findPoolByHostPath(host.getDataCenterId(), host.getPodId(), hostAddress, null,
pInfo.getUuid());
if (pool != null) {
s_logger.debug("Found a storage pool: " + pInfo.getUuid() + ", but with different hostpath " + pInfo.getHostPath() + ", still treat it as the same pool");
}
}
DataStoreProvider provider = _dataStoreProviderMgr.getDefaultPrimaryDataStoreProvider();
DataStoreLifeCycle lifeCycle = provider.getDataStoreLifeCycle();
if (pool == null) {
Map<String, Object> params = new HashMap<String, Object>();
String name = (host.getName() + " Local Storage");
params.put("zoneId", host.getDataCenterId());
params.put("clusterId", host.getClusterId());
params.put("podId", host.getPodId());
params.put("url", pInfo.getPoolType().toString() + "://" + pInfo.getHost() + "/" + pInfo.getHostPath());
params.put("name", name);
params.put("localStorage", true);
params.put("details", pInfo.getDetails());
params.put("uuid", pInfo.getUuid());
params.put("providerName", provider.getName());
store = lifeCycle.initialize(params);
} else {
store = _dataStoreMgr.getDataStore(pool.getId(), DataStoreRole.Primary);
}
pool = _storagePoolDao.findById(store.getId());
if (pool.getStatus() != StoragePoolStatus.Maintenance && pool.getStatus() != StoragePoolStatus.Removed) {
HostScope scope = new HostScope(host.getId(), host.getClusterId(), host.getDataCenterId());
lifeCycle.attachHost(store, scope, pInfo);
}
} catch (Exception e) {
s_logger.warn("Unable to setup the local storage pool for " + host, e);
throw new ConnectionException(true, "Unable to setup the local storage pool for " + host, e);
}
return _dataStoreMgr.getDataStore(store.getId(), DataStoreRole.Primary);
}
@Override
public PrimaryDataStoreInfo createPool(CreateStoragePoolCmd cmd) throws ResourceInUseException, IllegalArgumentException, UnknownHostException,
ResourceUnavailableException {
String providerName = cmd.getStorageProviderName();
DataStoreProvider storeProvider = _dataStoreProviderMgr.getDataStoreProvider(providerName);
if (storeProvider == null) {
storeProvider = _dataStoreProviderMgr.getDefaultPrimaryDataStoreProvider();
if (storeProvider == null) {
throw new InvalidParameterValueException("can't find storage provider: " + providerName);
}
}
Long clusterId = cmd.getClusterId();
Long podId = cmd.getPodId();
Long zoneId = cmd.getZoneId();
ScopeType scopeType = ScopeType.CLUSTER;
String scope = cmd.getScope();
if (scope != null) {
try {
scopeType = Enum.valueOf(ScopeType.class, scope.toUpperCase());
} catch (Exception e) {
throw new InvalidParameterValueException("invalid scope for pool " + scope);
}
}
if (scopeType == ScopeType.CLUSTER && clusterId == null) {
throw new InvalidParameterValueException("cluster id can't be null, if scope is cluster");
} else if (scopeType == ScopeType.ZONE && zoneId == null) {
throw new InvalidParameterValueException("zone id can't be null, if scope is zone");
}
HypervisorType hypervisorType = HypervisorType.KVM;
if (scopeType == ScopeType.ZONE) {
// ignore passed clusterId and podId
clusterId = null;
podId = null;
String hypervisor = cmd.getHypervisor();
if (hypervisor != null) {
try {
hypervisorType = HypervisorType.getType(hypervisor);
} catch (Exception e) {
throw new InvalidParameterValueException("invalid hypervisor type " + hypervisor);
}
} else {
throw new InvalidParameterValueException("Missing parameter hypervisor. Hypervisor type is required to create zone wide primary storage.");
}
if (hypervisorType != HypervisorType.KVM && hypervisorType != HypervisorType.VMware && hypervisorType != HypervisorType.Hyperv && hypervisorType != HypervisorType.LXC && hypervisorType != HypervisorType.Any) {
throw new InvalidParameterValueException("zone wide storage pool is not supported for hypervisor type " + hypervisor);
}
}
Map<String, String> details = extractApiParamAsMap(cmd.getDetails());
DataCenterVO zone = _dcDao.findById(cmd.getZoneId());
if (zone == null) {
throw new InvalidParameterValueException("unable to find zone by id " + zoneId);
}
// Check if zone is disabled
Account account = CallContext.current().getCallingAccount();
if (Grouping.AllocationState.Disabled == zone.getAllocationState() && !_accountMgr.isRootAdmin(account.getId())) {
throw new PermissionDeniedException("Cannot perform this operation, Zone is currently disabled: " + zoneId);
}
Map<String, Object> params = new HashMap<String, Object>();
params.put("zoneId", zone.getId());
params.put("clusterId", clusterId);
params.put("podId", podId);
params.put("url", cmd.getUrl());
params.put("tags", cmd.getTags());
params.put("name", cmd.getStoragePoolName());
params.put("details", details);
params.put("providerName", storeProvider.getName());
params.put("managed", cmd.isManaged());
params.put("capacityBytes", cmd.getCapacityBytes());
params.put("capacityIops", cmd.getCapacityIops());
DataStoreLifeCycle lifeCycle = storeProvider.getDataStoreLifeCycle();
DataStore store = null;
try {
store = lifeCycle.initialize(params);
if (scopeType == ScopeType.CLUSTER) {
ClusterScope clusterScope = new ClusterScope(clusterId, podId, zoneId);
lifeCycle.attachCluster(store, clusterScope);
} else if (scopeType == ScopeType.ZONE) {
ZoneScope zoneScope = new ZoneScope(zoneId);
lifeCycle.attachZone(store, zoneScope, hypervisorType);
}
} catch (Exception e) {
s_logger.debug("Failed to add data store: "+e.getMessage(), e);
try {
// clean up the db, just absorb the exception thrown in deletion with error logged, so that user can get error for adding data store
// not deleting data store.
if (store != null) {
lifeCycle.deleteDataStore(store);
}
} catch (Exception ex) {
s_logger.debug("Failed to clean up storage pool: " + ex.getMessage());
}
throw new CloudRuntimeException("Failed to add data store: "+e.getMessage(), e);
}
return (PrimaryDataStoreInfo)_dataStoreMgr.getDataStore(store.getId(), DataStoreRole.Primary);
}
private Map<String, String> extractApiParamAsMap(Map ds) {
Map<String, String> details = new HashMap<String, String>();
if (ds != null) {
Collection detailsCollection = ds.values();
Iterator it = detailsCollection.iterator();
while (it.hasNext()) {
HashMap d = (HashMap)it.next();
Iterator it2 = d.entrySet().iterator();
while (it2.hasNext()) {
Map.Entry entry = (Map.Entry)it2.next();
details.put((String)entry.getKey(), (String)entry.getValue());
}
}
}
return details;
}
@ActionEvent(eventType = EventTypes.EVENT_DISABLE_PRIMARY_STORAGE, eventDescription = "disable storage pool")
private void disablePrimaryStoragePool(StoragePoolVO primaryStorage) {
if (!primaryStorage.getStatus().equals(StoragePoolStatus.Up)) {
throw new InvalidParameterValueException("Primary storage with id " + primaryStorage.getId() + " cannot be disabled. Storage pool state : " +
primaryStorage.getStatus().toString());
}
DataStoreProvider provider = _dataStoreProviderMgr.getDataStoreProvider(primaryStorage.getStorageProviderName());
DataStoreLifeCycle dataStoreLifeCycle = provider.getDataStoreLifeCycle();
DataStore store = _dataStoreMgr.getDataStore(primaryStorage.getId(), DataStoreRole.Primary);
((PrimaryDataStoreLifeCycle)dataStoreLifeCycle).disableStoragePool(store);
}
@ActionEvent(eventType = EventTypes.EVENT_ENABLE_PRIMARY_STORAGE, eventDescription = "enable storage pool")
private void enablePrimaryStoragePool(StoragePoolVO primaryStorage) {
if (!primaryStorage.getStatus().equals(StoragePoolStatus.Disabled)) {
throw new InvalidParameterValueException("Primary storage with id " + primaryStorage.getId() + " cannot be enabled. Storage pool state : " +
primaryStorage.getStatus().toString());
}
DataStoreProvider provider = _dataStoreProviderMgr.getDataStoreProvider(primaryStorage.getStorageProviderName());
DataStoreLifeCycle dataStoreLifeCycle = provider.getDataStoreLifeCycle();
DataStore store = _dataStoreMgr.getDataStore(primaryStorage.getId(), DataStoreRole.Primary);
((PrimaryDataStoreLifeCycle)dataStoreLifeCycle).enableStoragePool(store);
}
@Override
public PrimaryDataStoreInfo updateStoragePool(UpdateStoragePoolCmd cmd) throws IllegalArgumentException {
// Input validation
Long id = cmd.getId();
StoragePoolVO pool = _storagePoolDao.findById(id);
if (pool == null) {
throw new IllegalArgumentException("Unable to find storage pool with ID: " + id);
}
final List<String> storagePoolTags = cmd.getTags();
if (storagePoolTags != null) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Updating Storage Pool Tags to :" + storagePoolTags);
}
_storagePoolTagsDao.persist(pool.getId(), storagePoolTags);
}
Long updatedCapacityBytes = null;
Long capacityBytes = cmd.getCapacityBytes();
if (capacityBytes != null) {
if (capacityBytes != pool.getCapacityBytes()) {
updatedCapacityBytes = capacityBytes;
}
}
Long updatedCapacityIops = null;
Long capacityIops = cmd.getCapacityIops();
if (capacityIops != null) {
if (!capacityIops.equals(pool.getCapacityIops())) {
updatedCapacityIops = capacityIops;
}
}
if (updatedCapacityBytes != null || updatedCapacityIops != null) {
StoragePoolVO storagePool = _storagePoolDao.findById(id);
DataStoreProvider dataStoreProvider = _dataStoreProviderMgr.getDataStoreProvider(storagePool.getStorageProviderName());
DataStoreLifeCycle dataStoreLifeCycle = dataStoreProvider.getDataStoreLifeCycle();
if (dataStoreLifeCycle instanceof PrimaryDataStoreLifeCycle) {
Map<String, String> details = new HashMap<String, String>();
details.put(PrimaryDataStoreLifeCycle.CAPACITY_BYTES, updatedCapacityBytes != null ? String.valueOf(updatedCapacityBytes) : null);
details.put(PrimaryDataStoreLifeCycle.CAPACITY_IOPS, updatedCapacityIops != null ? String.valueOf(updatedCapacityIops) : null);
((PrimaryDataStoreLifeCycle)dataStoreLifeCycle).updateStoragePool(storagePool, details);
}
}
Boolean enabled = cmd.getEnabled();
if (enabled != null) {
if (enabled) {
enablePrimaryStoragePool(pool);
} else {
disablePrimaryStoragePool(pool);
}
}
if (updatedCapacityBytes != null) {
_storagePoolDao.updateCapacityBytes(id, capacityBytes);
}
if (updatedCapacityIops != null) {
_storagePoolDao.updateCapacityIops(id, capacityIops);
}
return (PrimaryDataStoreInfo)_dataStoreMgr.getDataStore(pool.getId(), DataStoreRole.Primary);
}
@Override
@DB
public boolean deletePool(DeletePoolCmd cmd) {
Long id = cmd.getId();
boolean forced = cmd.isForced();
StoragePoolVO sPool = _storagePoolDao.findById(id);
if (sPool == null) {
s_logger.warn("Unable to find pool:" + id);
throw new InvalidParameterValueException("Unable to find pool by id " + id);
}
if (sPool.getStatus() != StoragePoolStatus.Maintenance) {
s_logger.warn("Unable to delete storage id: " + id + " due to it is not in Maintenance state");
throw new InvalidParameterValueException("Unable to delete storage due to it is not in Maintenance state, id: " + id);
}
if (sPool.isLocal()) {
s_logger.warn("Unable to delete local storage id:" + id);
throw new InvalidParameterValueException("Unable to delete local storage id: " + id);
}
Pair<Long, Long> vlms = _volsDao.getCountAndTotalByPool(id);
if (forced) {
if (vlms.first() > 0) {
Pair<Long, Long> nonDstrdVlms = _volsDao.getNonDestroyedCountAndTotalByPool(id);
if (nonDstrdVlms.first() > 0) {
throw new CloudRuntimeException("Cannot delete pool " + sPool.getName() + " as there are associated " + "non-destroyed vols for this pool");
}
// force expunge non-destroyed volumes
List<VolumeVO> vols = _volsDao.listVolumesToBeDestroyed();
for (VolumeVO vol : vols) {
AsyncCallFuture<VolumeApiResult> future = volService.expungeVolumeAsync(volFactory.getVolume(vol.getId()));
try {
future.get();
} catch (InterruptedException e) {
s_logger.debug("expunge volume failed:" + vol.getId(), e);
} catch (ExecutionException e) {
s_logger.debug("expunge volume failed:" + vol.getId(), e);
}
}
}
} else {
// Check if the pool has associated volumes in the volumes table
// If it does , then you cannot delete the pool
if (vlms.first() > 0) {
throw new CloudRuntimeException("Cannot delete pool " + sPool.getName() + " as there are associated volumes for this pool");
}
}
// First get the host_id from storage_pool_host_ref for given pool id
StoragePoolVO lock = _storagePoolDao.acquireInLockTable(sPool.getId());
if (lock == null) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Failed to acquire lock when deleting PrimaryDataStoreVO with ID: " + sPool.getId());
}
return false;
}
_storagePoolDao.releaseFromLockTable(lock.getId());
s_logger.trace("Released lock for storage pool " + id);
DataStoreProvider storeProvider = _dataStoreProviderMgr.getDataStoreProvider(sPool.getStorageProviderName());
DataStoreLifeCycle lifeCycle = storeProvider.getDataStoreLifeCycle();
DataStore store = _dataStoreMgr.getDataStore(sPool.getId(), DataStoreRole.Primary);
return lifeCycle.deleteDataStore(store);
}
@Override
public void connectHostToSharedPool(long hostId, long poolId) throws StorageUnavailableException, StorageConflictException {
StoragePool pool = (StoragePool)_dataStoreMgr.getDataStore(poolId, DataStoreRole.Primary);
assert (pool.isShared()) : "Now, did you actually read the name of this method?";
s_logger.debug("Adding pool " + pool.getName() + " to host " + hostId);
DataStoreProvider provider = _dataStoreProviderMgr.getDataStoreProvider(pool.getStorageProviderName());
HypervisorHostListener listener = hostListeners.get(provider.getName());
listener.hostConnect(hostId, pool.getId());
}
@Override
public BigDecimal getStorageOverProvisioningFactor(Long poolId) {
return new BigDecimal(CapacityManager.StorageOverprovisioningFactor.valueIn(poolId));
}
@Override
public void createCapacityEntry(StoragePoolVO storagePool, short capacityType, long allocated) {
SearchCriteria<CapacityVO> capacitySC = _capacityDao.createSearchCriteria();
capacitySC.addAnd("hostOrPoolId", SearchCriteria.Op.EQ, storagePool.getId());
capacitySC.addAnd("dataCenterId", SearchCriteria.Op.EQ, storagePool.getDataCenterId());
capacitySC.addAnd("capacityType", SearchCriteria.Op.EQ, capacityType);
List<CapacityVO> capacities = _capacityDao.search(capacitySC, null);
long totalOverProvCapacity;
if (storagePool.getPoolType().supportsOverProvisioning()) {
// All this is for the inaccuracy of floats for big number multiplication.
BigDecimal overProvFactor = getStorageOverProvisioningFactor(storagePool.getId());
totalOverProvCapacity = overProvFactor.multiply(new BigDecimal(storagePool.getCapacityBytes())).longValue();
s_logger.debug("Found storage pool " + storagePool.getName() + " of type " + storagePool.getPoolType().toString() + " with overprovisioning factor "
+ overProvFactor.toString());
s_logger.debug("Total over provisioned capacity calculated is " + overProvFactor + " * " + storagePool.getCapacityBytes());
} else {
s_logger.debug("Found storage pool " + storagePool.getName() + " of type " + storagePool.getPoolType().toString());
totalOverProvCapacity = storagePool.getCapacityBytes();
}
s_logger.debug("Total over provisioned capacity of the pool " + storagePool.getName() + " id: " + storagePool.getId() + " is " + totalOverProvCapacity);
CapacityState capacityState = CapacityState.Enabled;
if (storagePool.getScope() == ScopeType.ZONE) {
DataCenterVO dc = ApiDBUtils.findZoneById(storagePool.getDataCenterId());
AllocationState allocationState = dc.getAllocationState();
capacityState = (allocationState == AllocationState.Disabled) ? CapacityState.Disabled : CapacityState.Enabled;
} else {
if (storagePool.getClusterId() != null) {
ClusterVO cluster = ApiDBUtils.findClusterById(storagePool.getClusterId());
if (cluster != null) {
AllocationState allocationState = _configMgr.findClusterAllocationState(cluster);
capacityState = (allocationState == AllocationState.Disabled) ? CapacityState.Disabled : CapacityState.Enabled;
}
}
}
if (capacities.size() == 0) {
CapacityVO capacity =
new CapacityVO(storagePool.getId(), storagePool.getDataCenterId(), storagePool.getPodId(), storagePool.getClusterId(), allocated, totalOverProvCapacity,
capacityType);
capacity.setCapacityState(capacityState);
_capacityDao.persist(capacity);
} else {
CapacityVO capacity = capacities.get(0);
if (capacity.getTotalCapacity() != totalOverProvCapacity || allocated != 0L || capacity.getCapacityState() != capacityState) {
capacity.setTotalCapacity(totalOverProvCapacity);
capacity.setUsedCapacity(allocated);
capacity.setCapacityState(capacityState);
_capacityDao.update(capacity.getId(), capacity);
}
}
s_logger.debug("Successfully set Capacity - " + totalOverProvCapacity + " for capacity type - " + capacityType + " , DataCenterId - " +
storagePool.getDataCenterId() + ", HostOrPoolId - " + storagePool.getId() + ", PodId " + storagePool.getPodId());
}
@Override
public List<Long> getUpHostsInPool(long poolId) {
SearchCriteria<Long> sc = UpHostsInPoolSearch.create();
sc.setParameters("pool", poolId);
sc.setJoinParameters("hosts", "status", Status.Up);
sc.setJoinParameters("hosts", "resourceState", ResourceState.Enabled);
return _storagePoolHostDao.customSearch(sc, null);
}
@Override
public Pair<Long, Answer[]> sendToPool(StoragePool pool, long[] hostIdsToTryFirst, List<Long> hostIdsToAvoid, Commands cmds) throws StorageUnavailableException {
List<Long> hostIds = getUpHostsInPool(pool.getId());
Collections.shuffle(hostIds);
if (hostIdsToTryFirst != null) {
for (int i = hostIdsToTryFirst.length - 1; i >= 0; i--) {
if (hostIds.remove(hostIdsToTryFirst[i])) {
hostIds.add(0, hostIdsToTryFirst[i]);
}
}
}
if (hostIdsToAvoid != null) {
hostIds.removeAll(hostIdsToAvoid);
}
if (hostIds == null || hostIds.isEmpty()) {
throw new StorageUnavailableException("Unable to send command to the pool " + pool.getId() + " due to there is no enabled hosts up in this cluster",
pool.getId());
}
for (Long hostId : hostIds) {
try {
List<Answer> answers = new ArrayList<Answer>();
Command[] cmdArray = cmds.toCommands();
for (Command cmd : cmdArray) {
long targetHostId = _hvGuruMgr.getGuruProcessedCommandTargetHost(hostId, cmd);
answers.add(_agentMgr.send(targetHostId, cmd));
}
return new Pair<Long, Answer[]>(hostId, answers.toArray(new Answer[answers.size()]));
} catch (AgentUnavailableException e) {
s_logger.debug("Unable to send storage pool command to " + pool + " via " + hostId, e);
} catch (OperationTimedoutException e) {
s_logger.debug("Unable to send storage pool command to " + pool + " via " + hostId, e);
}
}
throw new StorageUnavailableException("Unable to send command to the pool ", pool.getId());
}
@Override
public Pair<Long, Answer> sendToPool(StoragePool pool, long[] hostIdsToTryFirst, List<Long> hostIdsToAvoid, Command cmd) throws StorageUnavailableException {
Commands cmds = new Commands(cmd);
Pair<Long, Answer[]> result = sendToPool(pool, hostIdsToTryFirst, hostIdsToAvoid, cmds);
return new Pair<Long, Answer>(result.first(), result.second()[0]);
}
@Override
public void cleanupStorage(boolean recurring) {
GlobalLock scanLock = GlobalLock.getInternLock("storagemgr.cleanup");
try {
if (scanLock.lock(3)) {
try {
// Cleanup primary storage pools
if (_templateCleanupEnabled) {
List<StoragePoolVO> storagePools = _storagePoolDao.listAll();
for (StoragePoolVO pool : storagePools) {
try {
List<VMTemplateStoragePoolVO> unusedTemplatesInPool = _tmpltMgr.getUnusedTemplatesInPool(pool);
s_logger.debug("Storage pool garbage collector found " + unusedTemplatesInPool.size() + " templates to clean up in storage pool: " +
pool.getName());
for (VMTemplateStoragePoolVO templatePoolVO : unusedTemplatesInPool) {
if (templatePoolVO.getDownloadState() != VMTemplateStorageResourceAssoc.Status.DOWNLOADED) {
s_logger.debug("Storage pool garbage collector is skipping template with ID: " + templatePoolVO.getTemplateId() +
" on pool " + templatePoolVO.getPoolId() + " because it is not completely downloaded.");
continue;
}
if (!templatePoolVO.getMarkedForGC()) {
templatePoolVO.setMarkedForGC(true);
_vmTemplatePoolDao.update(templatePoolVO.getId(), templatePoolVO);
s_logger.debug("Storage pool garbage collector has marked template with ID: " + templatePoolVO.getTemplateId() +
" on pool " + templatePoolVO.getPoolId() + " for garbage collection.");
continue;
}
_tmpltMgr.evictTemplateFromStoragePool(templatePoolVO);
}
} catch (Exception e) {
s_logger.warn("Problem cleaning up primary storage pool " + pool, e);
}
}
}
cleanupSecondaryStorage(recurring);
// ROOT volumes will be destroyed as part of VM cleanup
List<VolumeVO> vols = _volsDao.listNonRootVolumesToBeDestroyed(new Date(System.currentTimeMillis() - ((long) StorageCleanupDelay.value() << 10)));
for (VolumeVO vol : vols) {
try {
// If this fails, just log a warning. It's ideal if we clean up the host-side clustered file
// system, but not necessary.
handleManagedStorage(vol);
} catch (Exception e) {
s_logger.warn("Unable to destroy host-side clustered file system " + vol.getUuid(), e);
}
try {
VolumeInfo volumeInfo = volFactory.getVolume(vol.getId());
if (volumeInfo != null) {
volService.expungeVolumeAsync(volumeInfo);
} else {
s_logger.debug("Volume " + vol.getUuid() + " is already destroyed");
}
} catch (Exception e) {
s_logger.warn("Unable to destroy volume " + vol.getUuid(), e);
}
}
// remove snapshots in Error state
List<SnapshotVO> snapshots = _snapshotDao.listAllByStatus(Snapshot.State.Error);
for (SnapshotVO snapshotVO : snapshots) {
try {
List<SnapshotDataStoreVO> storeRefs = _snapshotStoreDao.findBySnapshotId(snapshotVO.getId());
for (SnapshotDataStoreVO ref : storeRefs) {
_snapshotStoreDao.expunge(ref.getId());
}
_snapshotDao.expunge(snapshotVO.getId());
} catch (Exception e) {
s_logger.warn("Unable to destroy snapshot " + snapshotVO.getUuid(), e);
}
}
// destroy uploaded volumes in abandoned/error state
List<VolumeDataStoreVO> volumeDataStores = _volumeDataStoreDao.listByVolumeState(Volume.State.UploadError, Volume.State.UploadAbandoned);
for (VolumeDataStoreVO volumeDataStore : volumeDataStores) {
VolumeVO volume = _volumeDao.findById(volumeDataStore.getVolumeId());
if (volume == null) {
s_logger.warn("Uploaded volume with id " + volumeDataStore.getVolumeId() + " not found, so cannot be destroyed");
continue;
}
try {
DataStore dataStore = _dataStoreMgr.getDataStore(volumeDataStore.getDataStoreId(), DataStoreRole.Image);
EndPoint ep = _epSelector.select(dataStore, volumeDataStore.getExtractUrl());
if (ep == null) {
s_logger.warn("There is no secondary storage VM for image store " + dataStore.getName() + ", cannot destroy uploaded volume " + volume.getUuid());
continue;
}
Host host = _hostDao.findById(ep.getId());
if (host != null && host.getManagementServerId() != null) {
if (_serverId == host.getManagementServerId().longValue()) {
if (!volService.destroyVolume(volume.getId())) {
s_logger.warn("Unable to destroy uploaded volume " + volume.getUuid());
continue;
}
// decrement volume resource count
_resourceLimitMgr.decrementResourceCount(volume.getAccountId(), ResourceType.volume, volume.isDisplayVolume());
// expunge volume from secondary if volume is on image store
VolumeInfo volOnSecondary = volFactory.getVolume(volume.getId(), DataStoreRole.Image);
if (volOnSecondary != null) {
s_logger.info("Expunging volume " + volume.getUuid() + " uploaded using HTTP POST from secondary data store");
AsyncCallFuture<VolumeApiResult> future = volService.expungeVolumeAsync(volOnSecondary);
VolumeApiResult result = future.get();
if (!result.isSuccess()) {
s_logger.warn("Failed to expunge volume " + volume.getUuid() + " from the image store " + dataStore.getName() + " due to: " + result.getResult());
}
}
}
}
} catch (Throwable th) {
s_logger.warn("Unable to destroy uploaded volume " + volume.getUuid() + ". Error details: " + th.getMessage());
}
}
// destroy uploaded templates in abandoned/error state
List<TemplateDataStoreVO> templateDataStores = _templateStoreDao.listByTemplateState(VirtualMachineTemplate.State.UploadError, VirtualMachineTemplate.State.UploadAbandoned);
for (TemplateDataStoreVO templateDataStore : templateDataStores) {
VMTemplateVO template = _templateDao.findById(templateDataStore.getTemplateId());
if (template == null) {
s_logger.warn("Uploaded template with id " + templateDataStore.getTemplateId() + " not found, so cannot be destroyed");
continue;
}
try {
DataStore dataStore = _dataStoreMgr.getDataStore(templateDataStore.getDataStoreId(), DataStoreRole.Image);
EndPoint ep = _epSelector.select(dataStore, templateDataStore.getExtractUrl());
if (ep == null) {
s_logger.warn("There is no secondary storage VM for image store " + dataStore.getName() + ", cannot destroy uploaded template " + template.getUuid());
continue;
}
Host host = _hostDao.findById(ep.getId());
if (host != null && host.getManagementServerId() != null) {
if (_serverId == host.getManagementServerId().longValue()) {
AsyncCallFuture<TemplateApiResult> future = _imageSrv.deleteTemplateAsync(tmplFactory.getTemplate(template.getId(), dataStore));
TemplateApiResult result = future.get();
if (!result.isSuccess()) {
s_logger.warn("Failed to delete template " + template.getUuid() + " from the image store " + dataStore.getName() + " due to: " + result.getResult());
continue;
}
// remove from template_zone_ref
List<VMTemplateZoneVO> templateZones = _vmTemplateZoneDao.listByZoneTemplate(((ImageStoreEntity)dataStore).getDataCenterId(), template.getId());
if (templateZones != null) {
for (VMTemplateZoneVO templateZone : templateZones) {
_vmTemplateZoneDao.remove(templateZone.getId());
}
}
// mark all the occurrences of this template in the given store as destroyed
_templateStoreDao.removeByTemplateStore(template.getId(), dataStore.getId());
// find all eligible image stores for this template
List<DataStore> imageStores = _tmpltMgr.getImageStoreByTemplate(template.getId(), null);
if (imageStores == null || imageStores.size() == 0) {
template.setState(VirtualMachineTemplate.State.Inactive);
_templateDao.update(template.getId(), template);
// decrement template resource count
_resourceLimitMgr.decrementResourceCount(template.getAccountId(), ResourceType.template);
}
}
}
} catch (Throwable th) {
s_logger.warn("Unable to destroy uploaded template " + template.getUuid() + ". Error details: " + th.getMessage());
}
}
} finally {
scanLock.unlock();
}
}
} finally {
scanLock.releaseRef();
}
}
private void handleManagedStorage(Volume volume) {
Long instanceId = volume.getInstanceId();
// The idea of this "if" statement is to see if we need to remove an SR/datastore before
// deleting the volume that supports it on a SAN. This only applies for managed storage.
if (instanceId != null) {
StoragePoolVO storagePool = _storagePoolDao.findById(volume.getPoolId());
if (storagePool != null && storagePool.isManaged()) {
DataTO volTO = volFactory.getVolume(volume.getId()).getTO();
DiskTO disk = new DiskTO(volTO, volume.getDeviceId(), volume.getPath(), volume.getVolumeType());
DettachCommand cmd = new DettachCommand(disk, null);
cmd.setManaged(true);
cmd.setStorageHost(storagePool.getHostAddress());
cmd.setStoragePort(storagePool.getPort());
cmd.set_iScsiName(volume.get_iScsiName());
VMInstanceVO vmInstanceVO = _vmInstanceDao.findById(instanceId);
Long lastHostId = vmInstanceVO.getLastHostId();
if (lastHostId != null) {
Answer answer = _agentMgr.easySend(lastHostId, cmd);
if (answer != null && answer.getResult()) {
VolumeInfo volumeInfo = volFactory.getVolume(volume.getId());
HostVO host = _hostDao.findById(lastHostId);
volService.revokeAccess(volumeInfo, host, volumeInfo.getDataStore());
} else {
s_logger.warn("Unable to remove host-side clustered file system for the following volume: " + volume.getUuid());
}
}
}
}
}
@DB
List<Long> findAllVolumeIdInSnapshotTable(Long storeId) {
String sql = "SELECT volume_id from snapshots, snapshot_store_ref WHERE snapshots.id = snapshot_store_ref.snapshot_id and store_id=? GROUP BY volume_id";
List<Long> list = new ArrayList<Long>();
try {
TransactionLegacy txn = TransactionLegacy.currentTxn();
ResultSet rs = null;
PreparedStatement pstmt = null;
pstmt = txn.prepareAutoCloseStatement(sql);
pstmt.setLong(1, storeId);
rs = pstmt.executeQuery();
while (rs.next()) {
list.add(rs.getLong(1));
}
return list;
} catch (Exception e) {
s_logger.debug("failed to get all volumes who has snapshots in secondary storage " + storeId + " due to " + e.getMessage());
return null;
}
}
List<String> findAllSnapshotForVolume(Long volumeId) {
String sql = "SELECT backup_snap_id FROM snapshots WHERE volume_id=? and backup_snap_id is not NULL";
try {
TransactionLegacy txn = TransactionLegacy.currentTxn();
ResultSet rs = null;
PreparedStatement pstmt = null;
pstmt = txn.prepareAutoCloseStatement(sql);
pstmt.setLong(1, volumeId);
rs = pstmt.executeQuery();
List<String> list = new ArrayList<String>();
while (rs.next()) {
list.add(rs.getString(1));
}
return list;
} catch (Exception e) {
s_logger.debug("failed to get all snapshots for a volume " + volumeId + " due to " + e.getMessage());
return null;
}
}
@Override
@DB
public void cleanupSecondaryStorage(boolean recurring) {
// NOTE that object_store refactor will immediately delete the object from secondary storage when deleteTemplate etc api is issued.
// so here we don't need to issue DeleteCommand to resource anymore, only need to remove db entry.
try {
// Cleanup templates in template_store_ref
List<DataStore> imageStores = _dataStoreMgr.getImageStoresByScope(new ZoneScope(null));
for (DataStore store : imageStores) {
try {
long storeId = store.getId();
List<TemplateDataStoreVO> destroyedTemplateStoreVOs = _templateStoreDao.listDestroyed(storeId);
s_logger.debug("Secondary storage garbage collector found " + destroyedTemplateStoreVOs.size() +
" templates to cleanup on template_store_ref for store: " + store.getName());
for (TemplateDataStoreVO destroyedTemplateStoreVO : destroyedTemplateStoreVOs) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Deleting template store DB entry: " + destroyedTemplateStoreVO);
}
_templateStoreDao.remove(destroyedTemplateStoreVO.getId());
}
} catch (Exception e) {
s_logger.warn("problem cleaning up templates in template_store_ref for store: " + store.getName(), e);
}
}
// CleanUp snapshots on snapshot_store_ref
for (DataStore store : imageStores) {
try {
List<SnapshotDataStoreVO> destroyedSnapshotStoreVOs = _snapshotStoreDao.listDestroyed(store.getId());
s_logger.debug("Secondary storage garbage collector found " + destroyedSnapshotStoreVOs.size() +
" snapshots to cleanup on snapshot_store_ref for store: " + store.getName());
for (SnapshotDataStoreVO destroyedSnapshotStoreVO : destroyedSnapshotStoreVOs) {
// check if this snapshot has child
SnapshotInfo snap = snapshotFactory.getSnapshot(destroyedSnapshotStoreVO.getSnapshotId(), store);
if (snap.getChild() != null) {
s_logger.debug("Skip snapshot on store: " + destroyedSnapshotStoreVO + " , because it has child");
continue;
}
if (s_logger.isDebugEnabled()) {
s_logger.debug("Deleting snapshot store DB entry: " + destroyedSnapshotStoreVO);
}
_snapshotDao.remove(destroyedSnapshotStoreVO.getSnapshotId());
SnapshotDataStoreVO snapshotOnPrimary = _snapshotStoreDao.findBySnapshot(destroyedSnapshotStoreVO.getSnapshotId(), DataStoreRole.Primary);
if (snapshotOnPrimary != null) {
_snapshotStoreDao.remove(snapshotOnPrimary.getId());
}
_snapshotStoreDao.remove(destroyedSnapshotStoreVO.getId());
}
} catch (Exception e2) {
s_logger.warn("problem cleaning up snapshots in snapshot_store_ref for store: " + store.getName(), e2);
}
}
// CleanUp volumes on volume_store_ref
for (DataStore store : imageStores) {
try {
List<VolumeDataStoreVO> destroyedStoreVOs = _volumeStoreDao.listDestroyed(store.getId());
s_logger.debug("Secondary storage garbage collector found " + destroyedStoreVOs.size() + " volumes to cleanup on volume_store_ref for store: " +
store.getName());
for (VolumeDataStoreVO destroyedStoreVO : destroyedStoreVOs) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Deleting volume store DB entry: " + destroyedStoreVO);
}
_volumeStoreDao.remove(destroyedStoreVO.getId());
}
} catch (Exception e2) {
s_logger.warn("problem cleaning up volumes in volume_store_ref for store: " + store.getName(), e2);
}
}
} catch (Exception e3) {
s_logger.warn("problem cleaning up secondary storage DB entries. ", e3);
}
}
@Override
public String getPrimaryStorageNameLabel(VolumeVO volume) {
Long poolId = volume.getPoolId();
// poolId is null only if volume is destroyed, which has been checked
// before.
assert poolId != null;
StoragePoolVO PrimaryDataStoreVO = _storagePoolDao.findById(poolId);
assert PrimaryDataStoreVO != null;
return PrimaryDataStoreVO.getUuid();
}
@Override
@DB
public PrimaryDataStoreInfo preparePrimaryStorageForMaintenance(Long primaryStorageId) throws ResourceUnavailableException, InsufficientCapacityException {
StoragePoolVO primaryStorage = null;
primaryStorage = _storagePoolDao.findById(primaryStorageId);
if (primaryStorage == null) {
String msg = "Unable to obtain lock on the storage pool record in preparePrimaryStorageForMaintenance()";
s_logger.error(msg);
throw new InvalidParameterValueException(msg);
}
if (!primaryStorage.getStatus().equals(StoragePoolStatus.Up) && !primaryStorage.getStatus().equals(StoragePoolStatus.ErrorInMaintenance)) {
throw new InvalidParameterValueException("Primary storage with id " + primaryStorageId + " is not ready for migration, as the status is:" +
primaryStorage.getStatus().toString());
}
DataStoreProvider provider = _dataStoreProviderMgr.getDataStoreProvider(primaryStorage.getStorageProviderName());
DataStoreLifeCycle lifeCycle = provider.getDataStoreLifeCycle();
DataStore store = _dataStoreMgr.getDataStore(primaryStorage.getId(), DataStoreRole.Primary);
lifeCycle.maintain(store);
return (PrimaryDataStoreInfo)_dataStoreMgr.getDataStore(primaryStorage.getId(), DataStoreRole.Primary);
}
@Override
@DB
public PrimaryDataStoreInfo cancelPrimaryStorageForMaintenance(CancelPrimaryStorageMaintenanceCmd cmd) throws ResourceUnavailableException {
Long primaryStorageId = cmd.getId();
StoragePoolVO primaryStorage = null;
primaryStorage = _storagePoolDao.findById(primaryStorageId);
if (primaryStorage == null) {
String msg = "Unable to obtain lock on the storage pool in cancelPrimaryStorageForMaintenance()";
s_logger.error(msg);
throw new InvalidParameterValueException(msg);
}
if (primaryStorage.getStatus().equals(StoragePoolStatus.Up) || primaryStorage.getStatus().equals(StoragePoolStatus.PrepareForMaintenance)) {
throw new StorageUnavailableException("Primary storage with id " + primaryStorageId + " is not ready to complete migration, as the status is:" +
primaryStorage.getStatus().toString(), primaryStorageId);
}
DataStoreProvider provider = _dataStoreProviderMgr.getDataStoreProvider(primaryStorage.getStorageProviderName());
DataStoreLifeCycle lifeCycle = provider.getDataStoreLifeCycle();
DataStore store = _dataStoreMgr.getDataStore(primaryStorage.getId(), DataStoreRole.Primary);
lifeCycle.cancelMaintain(store);
return (PrimaryDataStoreInfo)_dataStoreMgr.getDataStore(primaryStorage.getId(), DataStoreRole.Primary);
}
protected class StorageGarbageCollector extends ManagedContextRunnable {
public StorageGarbageCollector() {
}
@Override
protected void runInContext() {
try {
s_logger.trace("Storage Garbage Collection Thread is running.");
cleanupStorage(true);
} catch (Exception e) {
s_logger.error("Caught the following Exception", e);
}
}
}
@Override
public void onManagementNodeJoined(List<? extends ManagementServerHost> nodeList, long selfNodeId) {
// TODO Auto-generated method stub
}
@Override
public void onManagementNodeLeft(List<? extends ManagementServerHost> nodeList, long selfNodeId) {
for (ManagementServerHost vo : nodeList) {
if (vo.getMsid() == _serverId) {
s_logger.info("Cleaning up storage maintenance jobs associated with Management server: " + vo.getMsid());
List<Long> poolIds = _storagePoolWorkDao.searchForPoolIdsForPendingWorkJobs(vo.getMsid());
if (poolIds.size() > 0) {
for (Long poolId : poolIds) {
StoragePoolVO pool = _storagePoolDao.findById(poolId);
// check if pool is in an inconsistent state
if (pool != null &&
(pool.getStatus().equals(StoragePoolStatus.ErrorInMaintenance) || pool.getStatus().equals(StoragePoolStatus.PrepareForMaintenance) || pool.getStatus()
.equals(StoragePoolStatus.CancelMaintenance))) {
_storagePoolWorkDao.removePendingJobsOnMsRestart(vo.getMsid(), poolId);
pool.setStatus(StoragePoolStatus.ErrorInMaintenance);
_storagePoolDao.update(poolId, pool);
}
}
}
}
}
}
@Override
public void onManagementNodeIsolated() {
}
@Override
public CapacityVO getSecondaryStorageUsedStats(Long hostId, Long zoneId) {
SearchCriteria<HostVO> sc = _hostDao.createSearchCriteria();
if (zoneId != null) {
sc.addAnd("dataCenterId", SearchCriteria.Op.EQ, zoneId);
}
List<Long> hosts = new ArrayList<Long>();
if (hostId != null) {
hosts.add(hostId);
} else {
List<DataStore> stores = _dataStoreMgr.getImageStoresByScope(new ZoneScope(zoneId));
if (stores != null) {
for (DataStore store : stores) {
hosts.add(store.getId());
}
}
}
CapacityVO capacity = new CapacityVO(hostId, zoneId, null, null, 0, 0, Capacity.CAPACITY_TYPE_SECONDARY_STORAGE);
for (Long id : hosts) {
StorageStats stats = ApiDBUtils.getSecondaryStorageStatistics(id);
if (stats == null) {
continue;
}
capacity.setUsedCapacity(stats.getByteUsed() + capacity.getUsedCapacity());
capacity.setTotalCapacity(stats.getCapacityBytes() + capacity.getTotalCapacity());
}
return capacity;
}
@Override
public CapacityVO getStoragePoolUsedStats(Long poolId, Long clusterId, Long podId, Long zoneId) {
SearchCriteria<StoragePoolVO> sc = _storagePoolDao.createSearchCriteria();
List<StoragePoolVO> pools = new ArrayList<StoragePoolVO>();
if (zoneId != null) {
sc.addAnd("dataCenterId", SearchCriteria.Op.EQ, zoneId);
}
if (podId != null) {
sc.addAnd("podId", SearchCriteria.Op.EQ, podId);
}
if (clusterId != null) {
sc.addAnd("clusterId", SearchCriteria.Op.EQ, clusterId);
}
if (poolId != null) {
sc.addAnd("hostOrPoolId", SearchCriteria.Op.EQ, poolId);
}
if (poolId != null) {
pools.add(_storagePoolDao.findById(poolId));
} else {
pools = _storagePoolDao.search(sc, null);
}
CapacityVO capacity = new CapacityVO(poolId, zoneId, podId, clusterId, 0, 0, Capacity.CAPACITY_TYPE_STORAGE);
for (StoragePoolVO PrimaryDataStoreVO : pools) {
StorageStats stats = ApiDBUtils.getStoragePoolStatistics(PrimaryDataStoreVO.getId());
if (stats == null) {
continue;
}
capacity.setUsedCapacity(stats.getByteUsed() + capacity.getUsedCapacity());
capacity.setTotalCapacity(stats.getCapacityBytes() + capacity.getTotalCapacity());
}
return capacity;
}
@Override
public PrimaryDataStoreInfo getStoragePool(long id) {
return (PrimaryDataStoreInfo)_dataStoreMgr.getDataStore(id, DataStoreRole.Primary);
}
@Override
@DB
public List<VMInstanceVO> listByStoragePool(long storagePoolId) {
SearchCriteria<VMInstanceVO> sc = StoragePoolSearch.create();
sc.setJoinParameters("vmVolume", "volumeType", Volume.Type.ROOT);
sc.setJoinParameters("vmVolume", "poolId", storagePoolId);
sc.setJoinParameters("vmVolume", "state", Volume.State.Ready);
return _vmInstanceDao.search(sc, null);
}
@Override
@DB
public StoragePoolVO findLocalStorageOnHost(long hostId) {
SearchCriteria<StoragePoolVO> sc = LocalStorageSearch.create();
sc.setParameters("type", new Object[] {StoragePoolType.Filesystem, StoragePoolType.LVM});
sc.setJoinParameters("poolHost", "hostId", hostId);
List<StoragePoolVO> storagePools = _storagePoolDao.search(sc, null);
if (!storagePools.isEmpty()) {
return storagePools.get(0);
} else {
return null;
}
}
@Override
public Host updateSecondaryStorage(long secStorageId, String newUrl) {
HostVO secHost = _hostDao.findById(secStorageId);
if (secHost == null) {
throw new InvalidParameterValueException("Can not find out the secondary storage id: " + secStorageId);
}
if (secHost.getType() != Host.Type.SecondaryStorage) {
throw new InvalidParameterValueException("host: " + secStorageId + " is not a secondary storage");
}
URI uri = null;
try {
uri = new URI(UriUtils.encodeURIComponent(newUrl));
if (uri.getScheme() == null) {
throw new InvalidParameterValueException("uri.scheme is null " + newUrl + ", add nfs:// (or cifs://) as a prefix");
} else if (uri.getScheme().equalsIgnoreCase("nfs")) {
if (uri.getHost() == null || uri.getHost().equalsIgnoreCase("") || uri.getPath() == null || uri.getPath().equalsIgnoreCase("")) {
throw new InvalidParameterValueException("Your host and/or path is wrong. Make sure it's of the format nfs://hostname/path");
}
} else if (uri.getScheme().equalsIgnoreCase("cifs")) {
// Don't validate against a URI encoded URI.
URI cifsUri = new URI(newUrl);
String warnMsg = UriUtils.getCifsUriParametersProblems(cifsUri);
if (warnMsg != null) {
throw new InvalidParameterValueException(warnMsg);
}
}
} catch (URISyntaxException e) {
throw new InvalidParameterValueException(newUrl + " is not a valid uri");
}
String oldUrl = secHost.getStorageUrl();
URI oldUri = null;
try {
oldUri = new URI(UriUtils.encodeURIComponent(oldUrl));
if (!oldUri.getScheme().equalsIgnoreCase(uri.getScheme())) {
throw new InvalidParameterValueException("can not change old scheme:" + oldUri.getScheme() + " to " + uri.getScheme());
}
} catch (URISyntaxException e) {
s_logger.debug("Failed to get uri from " + oldUrl);
}
secHost.setStorageUrl(newUrl);
secHost.setGuid(newUrl);
secHost.setName(newUrl);
_hostDao.update(secHost.getId(), secHost);
return secHost;
}
@Override
public HypervisorType getHypervisorTypeFromFormat(ImageFormat format) {
if (format == null) {
return HypervisorType.None;
}
if (format == ImageFormat.VHD) {
return HypervisorType.XenServer;
} else if (format == ImageFormat.OVA) {
return HypervisorType.VMware;
} else if (format == ImageFormat.QCOW2) {
return HypervisorType.KVM;
} else if (format == ImageFormat.RAW) {
return HypervisorType.Ovm;
} else if (format == ImageFormat.VHDX) {
return HypervisorType.Hyperv;
} else {
return HypervisorType.None;
}
}
private boolean checkUsagedSpace(StoragePool pool) {
StatsCollector sc = StatsCollector.getInstance();
double storageUsedThreshold = CapacityManager.StorageCapacityDisableThreshold.valueIn(pool.getDataCenterId());
if (sc != null) {
long totalSize = pool.getCapacityBytes();
StorageStats stats = sc.getStoragePoolStats(pool.getId());
if (stats == null) {
stats = sc.getStorageStats(pool.getId());
}
if (stats != null) {
double usedPercentage = ((double)stats.getByteUsed() / (double)totalSize);
if (s_logger.isDebugEnabled()) {
s_logger.debug("Checking pool " + pool.getId() + " for storage, totalSize: " + pool.getCapacityBytes() + ", usedBytes: " + stats.getByteUsed() +
", usedPct: " + usedPercentage + ", disable threshold: " + storageUsedThreshold);
}
if (usedPercentage >= storageUsedThreshold) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Insufficient space on pool: " + pool.getId() + " since its usage percentage: " + usedPercentage +
" has crossed the pool.storage.capacity.disablethreshold: " + storageUsedThreshold);
}
return false;
}
}
return true;
}
return false;
}
@Override
public boolean storagePoolHasEnoughIops(List<Volume> requestedVolumes, StoragePool pool) {
if (requestedVolumes == null || requestedVolumes.isEmpty() || pool == null) {
return false;
}
// Only IOPS-guaranteed primary storage like SolidFire is using/setting IOPS.
// This check returns true for storage that does not specify IOPS.
if (pool.getCapacityIops() == null) {
s_logger.info("Storage pool " + pool.getName() + " (" + pool.getId() + ") does not supply IOPS capacity, assuming enough capacity");
return true;
}
StoragePoolVO storagePoolVo = _storagePoolDao.findById(pool.getId());
long currentIops = _capacityMgr.getUsedIops(storagePoolVo);
long requestedIops = 0;
for (Volume requestedVolume : requestedVolumes) {
Long minIops = requestedVolume.getMinIops();
if (minIops != null && minIops > 0) {
requestedIops += minIops;
}
}
long futureIops = currentIops + requestedIops;
return futureIops <= pool.getCapacityIops();
}
@Override
public boolean storagePoolHasEnoughSpace(List<Volume> volumes, StoragePool pool) {
return storagePoolHasEnoughSpace(volumes, pool, null);
}
@Override
public boolean storagePoolHasEnoughSpace(List<Volume> volumes, StoragePool pool, Long clusterId) {
if (volumes == null || volumes.isEmpty()) {
return false;
}
if (!checkUsagedSpace(pool)) {
return false;
}
// allocated space includes templates
if(s_logger.isDebugEnabled()) {
s_logger.debug("Destination pool id: " + pool.getId());
}
StoragePoolVO poolVO = _storagePoolDao.findById(pool.getId());
long allocatedSizeWithTemplate = _capacityMgr.getAllocatedPoolCapacity(poolVO, null);
long totalAskingSize = 0;
for (Volume volume : volumes) {
// refreshing the volume from the DB to get latest hv_ss_reserve (hypervisor snapshot reserve) field
// I could have just assigned this to "volume", but decided to make a new variable for it so that it
// might be clearer that this "volume" in "volumes" still might have an old value for hv_ss_reverse.
VolumeVO volumeVO = _volumeDao.findById(volume.getId());
if (volumeVO.getHypervisorSnapshotReserve() == null) {
// update the volume's hv_ss_reserve (hypervisor snapshot reserve) from a disk offering (used for managed storage)
volService.updateHypervisorSnapshotReserveForVolume(getDiskOfferingVO(volumeVO), volumeVO.getId(), getHypervisorType(volumeVO));
// hv_ss_reserve field might have been updated; refresh from DB to make use of it in getDataObjectSizeIncludingHypervisorSnapshotReserve
volumeVO = _volumeDao.findById(volume.getId());
}
// this if statement should resolve to true at most once per execution of the for loop its contained within (for a root disk that is
// to leverage a template)
if (volume.getTemplateId() != null) {
VMTemplateVO tmpl = _templateDao.findByIdIncludingRemoved(volume.getTemplateId());
if (tmpl != null && !ImageFormat.ISO.equals(tmpl.getFormat())) {
allocatedSizeWithTemplate = _capacityMgr.getAllocatedPoolCapacity(poolVO, tmpl);
}
}
// A ready state volume is already allocated in a pool. so the asking size is zero for it.
// In case the volume is moving across pools or is not ready yet, the asking size has to be computed
if (s_logger.isDebugEnabled()) {
s_logger.debug("pool id for the volume with id: " + volumeVO.getId() + " is " + volumeVO.getPoolId());
}
if ((volumeVO.getState() != Volume.State.Ready) || (volumeVO.getPoolId() != pool.getId())) {
if (ScopeType.ZONE.equals(poolVO.getScope()) && volumeVO.getTemplateId() != null) {
VMTemplateVO tmpl = _templateDao.findByIdIncludingRemoved(volumeVO.getTemplateId());
if (tmpl != null && !ImageFormat.ISO.equals(tmpl.getFormat())) {
// Storage plug-ins for zone-wide primary storage can be designed in such a way as to store a template on the
// primary storage once and make use of it in different clusters (via cloning).
// This next call leads to CloudStack asking how many more bytes it will need for the template (if the template is
// already stored on the primary storage, then the answer is 0).
if (clusterId != null && _clusterDao.getSupportsResigning(clusterId)) {
totalAskingSize += getBytesRequiredForTemplate(tmpl, pool);
}
}
}
}
}
long totalOverProvCapacity;
if (pool.getPoolType().supportsOverProvisioning()) {
BigDecimal overProvFactor = getStorageOverProvisioningFactor(pool.getId());
totalOverProvCapacity = overProvFactor.multiply(new BigDecimal(pool.getCapacityBytes())).longValue();
s_logger.debug("Found storage pool " + poolVO.getName() + " of type " + pool.getPoolType().toString() + " with overprovisioning factor "
+ overProvFactor.toString());
s_logger.debug("Total over provisioned capacity calculated is " + overProvFactor + " * " + pool.getCapacityBytes());
} else {
totalOverProvCapacity = pool.getCapacityBytes();
s_logger.debug("Found storage pool " + poolVO.getName() + " of type " + pool.getPoolType().toString());
}
s_logger.debug("Total capacity of the pool " + poolVO.getName() + " id: " + pool.getId() + " is " + totalOverProvCapacity);
double storageAllocatedThreshold = CapacityManager.StorageAllocatedCapacityDisableThreshold.valueIn(pool.getDataCenterId());
if (s_logger.isDebugEnabled()) {
s_logger.debug("Checking pool: " + pool.getId() + " for volume allocation " + volumes.toString() + ", maxSize : " + totalOverProvCapacity +
", totalAllocatedSize : " + allocatedSizeWithTemplate + ", askingSize : " + totalAskingSize + ", allocated disable threshold: " +
storageAllocatedThreshold);
}
double usedPercentage = (allocatedSizeWithTemplate + totalAskingSize) / (double)(totalOverProvCapacity);
if (usedPercentage > storageAllocatedThreshold) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Insufficient un-allocated capacity on: " + pool.getId() + " for volume allocation: " + volumes.toString() +
" since its allocated percentage: " + usedPercentage + " has crossed the allocated pool.storage.allocated.capacity.disablethreshold: " +
storageAllocatedThreshold + ", skipping this pool");
}
return false;
}
if (totalOverProvCapacity < (allocatedSizeWithTemplate + totalAskingSize)) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Insufficient un-allocated capacity on: " + pool.getId() + " for volume allocation: " + volumes.toString() +
", not enough storage, maxSize : " + totalOverProvCapacity + ", totalAllocatedSize : " + allocatedSizeWithTemplate + ", askingSize : " +
totalAskingSize);
}
return false;
}
return true;
}
private DiskOfferingVO getDiskOfferingVO(Volume volume) {
Long diskOfferingId = volume.getDiskOfferingId();
return _diskOfferingDao.findById(diskOfferingId);
}
private HypervisorType getHypervisorType(Volume volume) {
Long instanceId = volume.getInstanceId();
VMInstanceVO vmInstance = _vmInstanceDao.findById(instanceId);
if (vmInstance != null) {
return vmInstance.getHypervisorType();
}
return null;
}
private long getDataObjectSizeIncludingHypervisorSnapshotReserve(Volume volume, StoragePool pool) {
DataStoreProvider storeProvider = _dataStoreProviderMgr.getDataStoreProvider(pool.getStorageProviderName());
DataStoreDriver storeDriver = storeProvider.getDataStoreDriver();
if (storeDriver instanceof PrimaryDataStoreDriver) {
PrimaryDataStoreDriver primaryStoreDriver = (PrimaryDataStoreDriver)storeDriver;
VolumeInfo volumeInfo = volFactory.getVolume(volume.getId());
return primaryStoreDriver.getDataObjectSizeIncludingHypervisorSnapshotReserve(volumeInfo, pool);
}
return volume.getSize();
}
private long getBytesRequiredForTemplate(VMTemplateVO tmpl, StoragePool pool) {
DataStoreProvider storeProvider = _dataStoreProviderMgr.getDataStoreProvider(pool.getStorageProviderName());
DataStoreDriver storeDriver = storeProvider.getDataStoreDriver();
if (storeDriver instanceof PrimaryDataStoreDriver) {
PrimaryDataStoreDriver primaryStoreDriver = (PrimaryDataStoreDriver)storeDriver;
TemplateInfo templateInfo = tmplFactory.getReadyTemplateOnImageStore(tmpl.getId(), pool.getDataCenterId());
return primaryStoreDriver.getBytesRequiredForTemplate(templateInfo, pool);
}
return tmpl.getSize();
}
@Override
public void createCapacityEntry(long poolId) {
StoragePoolVO storage = _storagePoolDao.findById(poolId);
createCapacityEntry(storage, Capacity.CAPACITY_TYPE_STORAGE_ALLOCATED, 0);
}
@Override
public synchronized boolean registerHostListener(String providerName, HypervisorHostListener listener) {
hostListeners.put(providerName, listener);
return true;
}
@Override
public Answer sendToPool(long poolId, Command cmd) throws StorageUnavailableException {
// TODO Auto-generated method stub
return null;
}
@Override
public Answer[] sendToPool(long poolId, Commands cmd) throws StorageUnavailableException {
// TODO Auto-generated method stub
return null;
}
@Override
public String getName() {
// TODO Auto-generated method stub
return null;
}
@Override
public ImageStore discoverImageStore(String name, String url, String providerName, Long zoneId, Map details) throws IllegalArgumentException, DiscoveryException,
InvalidParameterValueException {
DataStoreProvider storeProvider = _dataStoreProviderMgr.getDataStoreProvider(providerName);
if (storeProvider == null) {
storeProvider = _dataStoreProviderMgr.getDefaultImageDataStoreProvider();
if (storeProvider == null) {
throw new InvalidParameterValueException("can't find image store provider: " + providerName);
}
providerName = storeProvider.getName(); // ignored passed provider name and use default image store provider name
}
ScopeType scopeType = ScopeType.ZONE;
if (zoneId == null) {
scopeType = ScopeType.REGION;
}
if (name == null) {
name = url;
}
ImageStoreVO imageStore = _imageStoreDao.findByName(name);
if (imageStore != null) {
throw new InvalidParameterValueException("The image store with name " + name + " already exists, try creating with another name");
}
// check if scope is supported by store provider
if (!((ImageStoreProvider)storeProvider).isScopeSupported(scopeType)) {
throw new InvalidParameterValueException("Image store provider " + providerName + " does not support scope " + scopeType);
}
// check if we have already image stores from other different providers,
// we currently are not supporting image stores from different
// providers co-existing
List<ImageStoreVO> imageStores = _imageStoreDao.listImageStores();
for (ImageStoreVO store : imageStores) {
if (!store.getProviderName().equalsIgnoreCase(providerName)) {
throw new InvalidParameterValueException("You can only add new image stores from the same provider " + store.getProviderName() + " already added");
}
}
if (zoneId != null) {
// Check if the zone exists in the system
DataCenterVO zone = _dcDao.findById(zoneId);
if (zone == null) {
throw new InvalidParameterValueException("Can't find zone by id " + zoneId);
}
Account account = CallContext.current().getCallingAccount();
if (Grouping.AllocationState.Disabled == zone.getAllocationState()
&& !_accountMgr.isRootAdmin(account.getId())) {
PermissionDeniedException ex = new PermissionDeniedException(
"Cannot perform this operation, Zone with specified id is currently disabled");
ex.addProxyObject(zone.getUuid(), "dcId");
throw ex;
}
}
Map<String, Object> params = new HashMap();
params.put("zoneId", zoneId);
params.put("url", url);
params.put("name", name);
params.put("details", details);
params.put("scope", scopeType);
params.put("providerName", storeProvider.getName());
params.put("role", DataStoreRole.Image);
DataStoreLifeCycle lifeCycle = storeProvider.getDataStoreLifeCycle();
DataStore store;
try {
store = lifeCycle.initialize(params);
} catch (Exception e) {
if(s_logger.isDebugEnabled()) {
s_logger.debug("Failed to add data store: " + e.getMessage(), e);
}
throw new CloudRuntimeException("Failed to add data store: " + e.getMessage(), e);
}
if (((ImageStoreProvider)storeProvider).needDownloadSysTemplate()) {
// trigger system vm template download
_imageSrv.downloadBootstrapSysTemplate(store);
} else {
// populate template_store_ref table
_imageSrv.addSystemVMTemplatesToSecondary(store);
}
// associate builtin template with zones associated with this image store
associateCrosszoneTemplatesToZone(zoneId);
// duplicate cache store records to region wide storage
if (scopeType == ScopeType.REGION) {
duplicateCacheStoreRecordsToRegionStore(store.getId());
}
return (ImageStore)_dataStoreMgr.getDataStore(store.getId(), DataStoreRole.Image);
}
@Override
public ImageStore migrateToObjectStore(String name, String url, String providerName, Map details) throws IllegalArgumentException, DiscoveryException,
InvalidParameterValueException {
// check if current cloud is ready to migrate, we only support cloud with only NFS secondary storages
List<ImageStoreVO> imgStores = _imageStoreDao.listImageStores();
List<ImageStoreVO> nfsStores = new ArrayList<ImageStoreVO>();
if (imgStores != null && imgStores.size() > 0) {
for (ImageStoreVO store : imgStores) {
if (!store.getProviderName().equals(DataStoreProvider.NFS_IMAGE)) {
throw new InvalidParameterValueException("We only support migrate NFS secondary storage to use object store!");
} else {
nfsStores.add(store);
}
}
}
// convert all NFS secondary storage to staging store
if (nfsStores != null && nfsStores.size() > 0) {
for (ImageStoreVO store : nfsStores) {
long storeId = store.getId();
_accountMgr.checkAccessAndSpecifyAuthority(CallContext.current().getCallingAccount(), store.getDataCenterId());
DataStoreProvider provider = _dataStoreProviderMgr.getDataStoreProvider(store.getProviderName());
DataStoreLifeCycle lifeCycle = provider.getDataStoreLifeCycle();
DataStore secStore = _dataStoreMgr.getDataStore(storeId, DataStoreRole.Image);
lifeCycle.migrateToObjectStore(secStore);
// update store_role in template_store_ref and snapshot_store_ref to ImageCache
_templateStoreDao.updateStoreRoleToCachce(storeId);
_snapshotStoreDao.updateStoreRoleToCache(storeId);
}
}
// add object store
return discoverImageStore(name, url, providerName, null, details);
}
private void duplicateCacheStoreRecordsToRegionStore(long storeId) {
_templateStoreDao.duplicateCacheRecordsOnRegionStore(storeId);
_snapshotStoreDao.duplicateCacheRecordsOnRegionStore(storeId);
_volumeStoreDao.duplicateCacheRecordsOnRegionStore(storeId);
}
private void associateCrosszoneTemplatesToZone(Long zoneId) {
VMTemplateZoneVO tmpltZone;
List<VMTemplateVO> allTemplates = _vmTemplateDao.listAll();
List<Long> dcIds = new ArrayList<Long>();
if (zoneId != null) {
dcIds.add(zoneId);
} else {
List<DataCenterVO> dcs = _dcDao.listAll();
if (dcs != null) {
for (DataCenterVO dc : dcs) {
dcIds.add(dc.getId());
}
}
}
for (VMTemplateVO vt : allTemplates) {
if (vt.isCrossZones()) {
for (Long dcId : dcIds) {
tmpltZone = _vmTemplateZoneDao.findByZoneTemplate(dcId, vt.getId());
if (tmpltZone == null) {
VMTemplateZoneVO vmTemplateZone = new VMTemplateZoneVO(dcId, vt.getId(), new Date());
_vmTemplateZoneDao.persist(vmTemplateZone);
}
}
}
}
}
@Override
public boolean deleteImageStore(DeleteImageStoreCmd cmd) {
final long storeId = cmd.getId();
// Verify that image store exists
ImageStoreVO store = _imageStoreDao.findById(storeId);
if (store == null) {
throw new InvalidParameterValueException("Image store with id " + storeId + " doesn't exist");
}
_accountMgr.checkAccessAndSpecifyAuthority(CallContext.current().getCallingAccount(), store.getDataCenterId());
// Verify that there are no live snapshot, template, volume on the image
// store to be deleted
List<SnapshotDataStoreVO> snapshots = _snapshotStoreDao.listByStoreId(storeId, DataStoreRole.Image);
if (snapshots != null && snapshots.size() > 0) {
throw new InvalidParameterValueException("Cannot delete image store with active snapshots backup!");
}
List<VolumeDataStoreVO> volumes = _volumeStoreDao.listByStoreId(storeId);
if (volumes != null && volumes.size() > 0) {
throw new InvalidParameterValueException("Cannot delete image store with active volumes backup!");
}
// search if there are user templates stored on this image store, excluding system, builtin templates
List<TemplateJoinVO> templates = _templateViewDao.listActiveTemplates(storeId);
if (templates != null && templates.size() > 0) {
throw new InvalidParameterValueException("Cannot delete image store with active templates backup!");
}
// ready to delete
Transaction.execute(new TransactionCallbackNoReturn() {
@Override
public void doInTransactionWithoutResult(TransactionStatus status) {
// first delete from image_store_details table, we need to do that since
// we are not actually deleting record from main
// image_data_store table, so delete cascade will not work
_imageStoreDetailsDao.deleteDetails(storeId);
_snapshotStoreDao.deletePrimaryRecordsForStore(storeId, DataStoreRole.Image);
_volumeStoreDao.deletePrimaryRecordsForStore(storeId);
_templateStoreDao.deletePrimaryRecordsForStore(storeId);
_imageStoreDao.remove(storeId);
}
});
return true;
}
@Override
public ImageStore createSecondaryStagingStore(CreateSecondaryStagingStoreCmd cmd) {
String providerName = cmd.getProviderName();
DataStoreProvider storeProvider = _dataStoreProviderMgr.getDataStoreProvider(providerName);
if (storeProvider == null) {
storeProvider = _dataStoreProviderMgr.getDefaultCacheDataStoreProvider();
if (storeProvider == null) {
throw new InvalidParameterValueException("can't find cache store provider: " + providerName);
}
}
Long dcId = cmd.getZoneId();
ScopeType scopeType = null;
String scope = cmd.getScope();
if (scope != null) {
try {
scopeType = Enum.valueOf(ScopeType.class, scope.toUpperCase());
} catch (Exception e) {
throw new InvalidParameterValueException("invalid scope for cache store " + scope);
}
if (scopeType != ScopeType.ZONE) {
throw new InvalidParameterValueException("Only zone wide cache storage is supported");
}
}
if (scopeType == ScopeType.ZONE && dcId == null) {
throw new InvalidParameterValueException("zone id can't be null, if scope is zone");
}
// Check if the zone exists in the system
DataCenterVO zone = _dcDao.findById(dcId);
if (zone == null) {
throw new InvalidParameterValueException("Can't find zone by id " + dcId);
}
Account account = CallContext.current().getCallingAccount();
if (Grouping.AllocationState.Disabled == zone.getAllocationState() && !_accountMgr.isRootAdmin(account.getId())) {
PermissionDeniedException ex = new PermissionDeniedException(
"Cannot perform this operation, Zone with specified id is currently disabled");
ex.addProxyObject(zone.getUuid(), "dcId");
throw ex;
}
Map<String, Object> params = new HashMap<String, Object>();
params.put("zoneId", dcId);
params.put("url", cmd.getUrl());
params.put("name", cmd.getUrl());
params.put("details", cmd.getDetails());
params.put("scope", scopeType);
params.put("providerName", storeProvider.getName());
params.put("role", DataStoreRole.ImageCache);
DataStoreLifeCycle lifeCycle = storeProvider.getDataStoreLifeCycle();
DataStore store = null;
try {
store = lifeCycle.initialize(params);
} catch (Exception e) {
s_logger.debug("Failed to add data store: "+e.getMessage(), e);
throw new CloudRuntimeException("Failed to add data store: "+e.getMessage(), e);
}
return (ImageStore)_dataStoreMgr.getDataStore(store.getId(), DataStoreRole.ImageCache);
}
@Override
public boolean deleteSecondaryStagingStore(DeleteSecondaryStagingStoreCmd cmd) {
final long storeId = cmd.getId();
// Verify that cache store exists
ImageStoreVO store = _imageStoreDao.findById(storeId);
if (store == null) {
throw new InvalidParameterValueException("Cache store with id " + storeId + " doesn't exist");
}
_accountMgr.checkAccessAndSpecifyAuthority(CallContext.current().getCallingAccount(), store.getDataCenterId());
// Verify that there are no live snapshot, template, volume on the cache
// store that is currently referenced
List<SnapshotDataStoreVO> snapshots = _snapshotStoreDao.listActiveOnCache(storeId);
if (snapshots != null && snapshots.size() > 0) {
throw new InvalidParameterValueException("Cannot delete cache store with staging snapshots currently in use!");
}
List<VolumeDataStoreVO> volumes = _volumeStoreDao.listActiveOnCache(storeId);
if (volumes != null && volumes.size() > 0) {
throw new InvalidParameterValueException("Cannot delete cache store with staging volumes currently in use!");
}
List<TemplateDataStoreVO> templates = _templateStoreDao.listActiveOnCache(storeId);
if (templates != null && templates.size() > 0) {
throw new InvalidParameterValueException("Cannot delete cache store with staging templates currently in use!");
}
// ready to delete
Transaction.execute(new TransactionCallbackNoReturn() {
@Override
public void doInTransactionWithoutResult(TransactionStatus status) {
// first delete from image_store_details table, we need to do that since
// we are not actually deleting record from main
// image_data_store table, so delete cascade will not work
_imageStoreDetailsDao.deleteDetails(storeId);
_snapshotStoreDao.deletePrimaryRecordsForStore(storeId, DataStoreRole.ImageCache);
_volumeStoreDao.deletePrimaryRecordsForStore(storeId);
_templateStoreDao.deletePrimaryRecordsForStore(storeId);
_imageStoreDao.remove(storeId);
}
});
return true;
}
protected class DownloadURLGarbageCollector implements Runnable {
public DownloadURLGarbageCollector() {
}
@Override
public void run() {
try {
s_logger.trace("Download URL Garbage Collection Thread is running.");
cleanupDownloadUrls();
} catch (Exception e) {
s_logger.error("Caught the following Exception", e);
}
}
}
@Override
public void cleanupDownloadUrls(){
// Cleanup expired volume URLs
List<VolumeDataStoreVO> volumesOnImageStoreList = _volumeStoreDao.listVolumeDownloadUrls();
for(VolumeDataStoreVO volumeOnImageStore : volumesOnImageStoreList){
try {
long downloadUrlCurrentAgeInSecs = DateUtil.getTimeDifference(DateUtil.now(), volumeOnImageStore.getExtractUrlCreated());
if(downloadUrlCurrentAgeInSecs < _downloadUrlExpirationInterval){ // URL hasnt expired yet
continue;
}
s_logger.debug("Removing download url " + volumeOnImageStore.getExtractUrl() + " for volume id " + volumeOnImageStore.getVolumeId());
// Remove it from image store
ImageStoreEntity secStore = (ImageStoreEntity) _dataStoreMgr.getDataStore(volumeOnImageStore.getDataStoreId(), DataStoreRole.Image);
secStore.deleteExtractUrl(volumeOnImageStore.getInstallPath(), volumeOnImageStore.getExtractUrl(), Upload.Type.VOLUME);
// Now expunge it from DB since this entry was created only for download purpose
_volumeStoreDao.expunge(volumeOnImageStore.getId());
}catch(Throwable th){
s_logger.warn("Caught exception while deleting download url " +volumeOnImageStore.getExtractUrl() +
" for volume id " + volumeOnImageStore.getVolumeId(), th);
}
}
// Cleanup expired template URLs
List<TemplateDataStoreVO> templatesOnImageStoreList = _templateStoreDao.listTemplateDownloadUrls();
for(TemplateDataStoreVO templateOnImageStore : templatesOnImageStoreList){
try {
long downloadUrlCurrentAgeInSecs = DateUtil.getTimeDifference(DateUtil.now(), templateOnImageStore.getExtractUrlCreated());
if(downloadUrlCurrentAgeInSecs < _downloadUrlExpirationInterval){ // URL hasnt expired yet
continue;
}
s_logger.debug("Removing download url " + templateOnImageStore.getExtractUrl() + " for template id " + templateOnImageStore.getTemplateId());
// Remove it from image store
ImageStoreEntity secStore = (ImageStoreEntity) _dataStoreMgr.getDataStore(templateOnImageStore.getDataStoreId(), DataStoreRole.Image);
secStore.deleteExtractUrl(templateOnImageStore.getInstallPath(), templateOnImageStore.getExtractUrl(), Upload.Type.TEMPLATE);
// Now remove download details from DB.
templateOnImageStore.setExtractUrl(null);
templateOnImageStore.setExtractUrlCreated(null);
_templateStoreDao.update(templateOnImageStore.getId(), templateOnImageStore);
}catch(Throwable th){
s_logger.warn("caught exception while deleting download url " +templateOnImageStore.getExtractUrl() +
" for template id " +templateOnImageStore.getTemplateId(), th);
}
}
}
// get bytesReadRate from service_offering, disk_offering and vm.disk.throttling.bytes_read_rate
@Override
public Long getDiskBytesReadRate(final ServiceOffering offering, final DiskOffering diskOffering) {
if ((offering != null) && (offering.getBytesReadRate() != null) && (offering.getBytesReadRate() > 0)) {
return offering.getBytesReadRate();
} else if ((diskOffering != null) && (diskOffering.getBytesReadRate() != null) && (diskOffering.getBytesReadRate() > 0)) {
return diskOffering.getBytesReadRate();
} else {
Long bytesReadRate = Long.parseLong(_configDao.getValue(Config.VmDiskThrottlingBytesReadRate.key()));
if ((bytesReadRate > 0) && ((offering == null) || (!offering.getSystemUse()))) {
return bytesReadRate;
}
}
return 0L;
}
// get bytesWriteRate from service_offering, disk_offering and vm.disk.throttling.bytes_write_rate
@Override
public Long getDiskBytesWriteRate(final ServiceOffering offering, final DiskOffering diskOffering) {
if ((offering != null) && (offering.getBytesWriteRate() != null) && (offering.getBytesWriteRate() > 0)) {
return offering.getBytesWriteRate();
} else if ((diskOffering != null) && (diskOffering.getBytesWriteRate() != null) && (diskOffering.getBytesWriteRate() > 0)) {
return diskOffering.getBytesWriteRate();
} else {
Long bytesWriteRate = Long.parseLong(_configDao.getValue(Config.VmDiskThrottlingBytesWriteRate.key()));
if ((bytesWriteRate > 0) && ((offering == null) || (!offering.getSystemUse()))) {
return bytesWriteRate;
}
}
return 0L;
}
// get iopsReadRate from service_offering, disk_offering and vm.disk.throttling.iops_read_rate
@Override
public Long getDiskIopsReadRate(final ServiceOffering offering, final DiskOffering diskOffering) {
if ((offering != null) && (offering.getIopsReadRate() != null) && (offering.getIopsReadRate() > 0)) {
return offering.getIopsReadRate();
} else if ((diskOffering != null) && (diskOffering.getIopsReadRate() != null) && (diskOffering.getIopsReadRate() > 0)) {
return diskOffering.getIopsReadRate();
} else {
Long iopsReadRate = Long.parseLong(_configDao.getValue(Config.VmDiskThrottlingIopsReadRate.key()));
if ((iopsReadRate > 0) && ((offering == null) || (!offering.getSystemUse()))) {
return iopsReadRate;
}
}
return 0L;
}
// get iopsWriteRate from service_offering, disk_offering and vm.disk.throttling.iops_write_rate
@Override
public Long getDiskIopsWriteRate(final ServiceOffering offering, final DiskOffering diskOffering) {
if ((offering != null) && (offering.getIopsWriteRate() != null) && (offering.getIopsWriteRate() > 0)) {
return offering.getIopsWriteRate();
} else if ((diskOffering != null) && (diskOffering.getIopsWriteRate() != null) && (diskOffering.getIopsWriteRate() > 0)) {
return diskOffering.getIopsWriteRate();
} else {
Long iopsWriteRate = Long.parseLong(_configDao.getValue(Config.VmDiskThrottlingIopsWriteRate.key()));
if ((iopsWriteRate > 0) && ((offering == null) || (!offering.getSystemUse()))) {
return iopsWriteRate;
}
}
return 0L;
}
@Override
public String getConfigComponentName() {
return StorageManager.class.getSimpleName();
}
@Override
public ConfigKey<?>[] getConfigKeys() {
return new ConfigKey<?>[] {StorageCleanupInterval, StorageCleanupDelay, StorageCleanupEnabled};
}
@Override
public void setDiskProfileThrottling(DiskProfile dskCh, final ServiceOffering offering, final DiskOffering diskOffering) {
dskCh.setBytesReadRate(getDiskBytesReadRate(offering, diskOffering));
dskCh.setBytesWriteRate(getDiskBytesWriteRate(offering, diskOffering));
dskCh.setIopsReadRate(getDiskIopsReadRate(offering, diskOffering));
dskCh.setIopsWriteRate(getDiskIopsWriteRate(offering, diskOffering));
}
@Override
public DiskTO getDiskWithThrottling(final DataTO volTO, final Volume.Type volumeType, final long deviceId, final String path, final long offeringId, final long diskOfferingId) {
DiskTO disk = null;
if (volTO != null && volTO instanceof VolumeObjectTO) {
VolumeObjectTO volumeTO = (VolumeObjectTO) volTO;
ServiceOffering offering = _entityMgr.findById(ServiceOffering.class, offeringId);
DiskOffering diskOffering = _entityMgr.findById(DiskOffering.class, diskOfferingId);
if (volumeType == Volume.Type.ROOT) {
setVolumeObjectTOThrottling(volumeTO, offering, diskOffering);
} else {
setVolumeObjectTOThrottling(volumeTO, null, diskOffering);
}
disk = new DiskTO(volumeTO, deviceId, path, volumeType);
} else {
disk = new DiskTO(volTO, deviceId, path, volumeType);
}
return disk;
}
private void setVolumeObjectTOThrottling(VolumeObjectTO volumeTO, final ServiceOffering offering, final DiskOffering diskOffering) {
volumeTO.setBytesReadRate(getDiskBytesReadRate(offering, diskOffering));
volumeTO.setBytesWriteRate(getDiskBytesWriteRate(offering, diskOffering));
volumeTO.setIopsReadRate(getDiskIopsReadRate(offering, diskOffering));
volumeTO.setIopsWriteRate(getDiskIopsWriteRate(offering, diskOffering));
}
}
| jcshen007/cloudstack | server/src/com/cloud/storage/StorageManagerImpl.java | Java | apache-2.0 | 118,418 |
import * as fromShoppingList from '../shopping-list/store/shopping-list.reducers';
import * as fromAuth from '../auth/store/auth.reducers';
import {ActionReducerMap} from '@ngrx/store';
export interface AppState {
shoppingList: fromShoppingList.State;
auth: fromAuth.State;
}
export const reducers: ActionReducerMap<AppState> = {
shoppingList: fromShoppingList.shoppingListReducers,
auth: fromAuth.authReducer
};
| davidokun/Angular-js | ng4-complete-app/src/app/store/app.reducers.ts | TypeScript | apache-2.0 | 423 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.