code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9
values | license stringclasses 15
values | size int32 3 1.05M |
|---|---|---|---|---|---|
//hello8.cpp
#include "hello8.h"
#include <iostream>
using namespace std;
int Hello8::obj_count = 0;
int Hello8::Total() {
return obj_count;
}
void Hello8::run(int l, int c) const {
for(int i = 0; i < l; i++) {
for(int j = 0; j < c; j++)
cout<<"Hello " << id << ", ";
cout << endl;
}
}
void Hello8::operator*() const
{
run();
}
| alexbernardino/scdtr1718 | hello/hello8.cpp | C++ | unlicense | 358 |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using ImputationH31per.Modele;
using ImputationH31per.Modele.Entite;
using ImputationH31per.Vue.EditeurImputationTfs.Modele;
namespace ImputationH31per.Vue.ImputationsCourantes.Modele
{
public interface IImputationsCourantesFormModele : IEditeurImputationTfsChoixSourceModele
{
event NotifyCollectionChangedEventHandler ImputationTfssCourantesAChange;
IImputationH31perModele ImputationH31perModele { get; }
IEnumerable<IImputationTfsNotifiable> ImputationTfssCourantes { get; }
void AjouterImputationTfs(IImputationTfsNotifiable imputationTfs);
void NettoyerImputationTfs();
IImputationTfsNotifiable ObtenirDerniereImputationTfs(int numero, int? numeroComplementaire);
IInformationTacheTfsNotifiable ObtenirInformationTacheTfs(int numero);
bool SupprimerImputationTfs(IImputationTfsNotifiable imputationTfs);
}
} | blueneosky/Bag | ImputationH31per/ImputationH31per/Vue/ImputationsCourantes/Modele/IImputationsCourantesFormModele.cs | C# | unlicense | 1,033 |
/*
* Copyright (C) 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package lib.stormauthlib.com.google.gson.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* An annotation that indicates this member should be serialized to JSON with
* the provided name value as its field name.
*
* <p>This annotation will override any {@link lib.stormauthlib.com.google.gson.FieldNamingPolicy}, including
* the default field naming policy, that may have been set on the {@link lib.stormauthlib.com.google.gson.Gson}
* instance. A different naming policy can set using the {@code GsonBuilder} class. See
* {@link lib.stormauthlib.com.google.gson.GsonBuilder#setFieldNamingPolicy(lib.stormauthlib.com.google.gson.FieldNamingPolicy)}
* for more information.</p>
*
* <p>Here is an example of how this annotation is meant to be used:</p>
* <pre>
* public class SomeClassWithFields {
* @SerializedName("name") private final String someField;
* private final String someOtherField;
*
* public SomeClassWithFields(String a, String b) {
* this.someField = a;
* this.someOtherField = b;
* }
* }
* </pre>
*
* <p>The following shows the output that is generated when serializing an instance of the
* above example class:</p>
* <pre>
* SomeClassWithFields objectToSerialize = new SomeClassWithFields("a", "b");
* Gson gson = new Gson();
* String jsonRepresentation = gson.toJson(objectToSerialize);
* System.out.println(jsonRepresentation);
*
* ===== OUTPUT =====
* {"name":"a","someOtherField":"b"}
* </pre>
*
* <p>NOTE: The value you specify in this annotation must be a valid JSON field name.</p>
*
* @see lib.stormauthlib.com.google.gson.FieldNamingPolicy
*
* @author Inderjeet Singh
* @author Joel Leitch
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface SerializedName {
/**
* @return the desired name of the field when it is serialized
*/
String value();
}
| storm345dev/StormAuthLib | StormAuthLib/src/lib/stormauthlib/com/google/gson/annotations/SerializedName.java | Java | unlicense | 2,603 |
#!/usr/bin/env python
import datetime
import sys
import numpy
import math
import os
import matplotlib
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.colors import LogNorm
import data
KEYFILE = os.path.expanduser('~/.ssh/livedatakey')
WEBSPACE = 'pkienzle@webster.ncnr.nist.gov:/var/www/html/ipeek'
WORKDIR="/tmp/"
def getLiveData(datafile):
path = "/net/charlotte/var/ftp/pub/sansdata/"+datafile
sansfile="pkienzle@sparkle.ncnr.nist.gov:%s"%path
workfile=WORKDIR+"livedata."+datafile[:3].lower()
cmd = ("scp -p -i %s %s %s"
% (KEYFILE, sansfile, workfile))
#print cmd
os.system(cmd)
return workfile
def putLiveData(imgname,htmlname,rawdata=None):
files = [WORKDIR+f for f in (imgname, htmlname)]
if rawdata is not None: files.append(rawdata)
# assuming no spaces in filenames
cmd = "scp -p -i %s %s %s"% (KEYFILE, " ".join(files), WEBSPACE)
#print cmd
os.system(cmd)
def createLiveHTML(metadata,imgname,htmlname):
collen=16.258
if (metadata['sample.table'] == '1'):
offset=0.55
else:
offset=0
dataimage = imgname
outfile = open(htmlname,"w")
print >> outfile, """
<?
include("/var/www/include/utility.inc")
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>%s status</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<meta http-equiv="refresh" content="30" />
<link rel="stylesheet" href="http://www.ncnr.nist.gov/programs/sans/scripts/style.css" type="text/css">
<script src="http://www.ncnr.nist.gov/programs/sans/scripts/java_scripts.js" type="text/javascript"></script>
</head>
<body>
<div class="bannerback">
<div class="bannerleft"><a href="http://www.ncnr.nist.gov/"><img src="/images/ncnr_banner_title_2.gif" alt="NIST Center for Neutron Research Logo"></a></div>
<div class="bannerright"><a href="http://www.nist.gov/"><img src="/images/ncnr_banner_nist_name.gif" alt="NIST Logo"></a></div>
</div>
<div class="nav">
<ul>
<li><a href="http://www.ncnr.nist.gov/index.html">NCNR Home</a></li>
<li><a href="http://www.ncnr.nist.gov/instruments/index.html">Instruments</a></li>
<li><a href="http://www.ncnr.nist.gov/programs/index.html">Science</a></li>
<li><a href="http://www.ncnr.nist.gov/experiments.html">Experiments</a></li>
<li><a href="http://www.ncnr.nist.gov/sitemap.html">Sitemap</a></li>
</ul>
</div>
<div class="container">
<div align='center'><font size='Large'>%s : %s</font></div>
<div align='center'><img src="%s" alt="SANS pattern"></div>
<table align='center' border=0>
<tr valign='top'><td>
<table border=1>
<tr><td width='100px'>Date/Time</td><td>%s</td>
<tr><td>Count Time</td><td>%s s</td>
<tr><td>Elapsed Count Time</td><td>%s s</td>
<tr><td>Monitor Counts</td><td>%d</td>
<tr><td>Detector Counts</td><td>%d</td>
</table>
</td><td>
<table border=1>
<tr><td>Guides</td><td>%d</td>
<tr><td>SDD</td><td>%.1f m</td>
<tr><td>Lambda</td><td>%.1f A</td>
<tr><td>Source Aperture</td><td>%.1f cm</td>
<tr><td>Sample Aperture</td><td>%.1f cm</td>
</table>
</td><td>
<table border=1>
<tr><td>Sample Position</td><td>%.1f</td>
<tr><td>Sample Temperature</td><td>%.1f C</td>
</table>
</td></tr>
</table>
<div align='center'>The data is updated every 5 minutes and this page will refresh every 30s</div>
<div align='center'>Last data update: %s</div>
<div align='center'>Last page refresh:
<script type="text/javascript" language="JavaScript">
var date = new Date();
document.write(date.toString())
</script>
</div>
<?
include("/var/www/html/programs/sans/SANS_bottom1.inc");
?> """ % (imgname[:3],
metadata['run.defdir'],
metadata['sample.labl'],
dataimage,
metadata['run.datetime'],
metadata['run.ctime']*metadata['run.npre'],
metadata['run.rtime'],
metadata['run.moncnt'],
metadata['run.detcnt'],
round((collen-metadata['resolution.ap12dis']-offset)/1.55),
metadata['det.dis'],
metadata['resolution.lmda'],
metadata['resolution.ap1'],
metadata['resolution.ap2'],
metadata['sample.position'],
metadata['sample.temp'],
datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
outfile.close()
def generateDataImage(data,metadata,imgname):
fig = plt.figure(figsize=(8,4))
ax = fig.add_subplot(121)
ax.imshow(data,origin='lower',cmap=cm.jet)
ax2 = fig.add_subplot(122)
vmax = data.max()
if vmax < 1: vmax=1
ax2.imshow(data,origin='lower',cmap=cm.jet,norm=LogNorm(vmin=1, vmax=vmax))
#plt.colorbar(data,ax=ax2,norm=LogNorm(vmin=1))
fig.savefig(imgname)
def run_update(inst=None):
imgname = inst+"_livedata.png"
htmlname = inst+"_livedata.html"
datafile = inst[:3]+"Current/live001.sa3_ice_a001"
localfile = getLiveData(datafile)
detdata,metadata = data.readNCNRData(localfile)
generateDataImage(detdata,metadata,WORKDIR+imgname)
createLiveHTML(metadata,imgname,WORKDIR+htmlname)
putLiveData(imgname,htmlname,rawdata=localfile)
if __name__ == "__main__":
inst = sys.argv[1] if len(sys.argv) == 2 else None
run_update(inst)
| scattering/ipeek | server/sans/livesans.py | Python | unlicense | 5,262 |
#include<stdio.h>
main(){
int cake[101],i,sum,done,n,max,side[101];
char c;
for(i=-1;scanf("%d%c",&cake[++i],&c)!=EOF;i=-1){
printf("%d%c",cake[i],c);
if(c=='\n'){
printf("0\n");
continue;
}
while(1){
scanf("%d%c",&cake[++i],&c);
printf("%d%c",cake[i],c);
if(c=='\n')break;
}n=i;sum=n;
done=0;
while(!done){
for(i=1,done=1;i<=sum && done;i++)
done=(cake[i-1]<=cake[i]);
if(done)break;
for(i=n,max=n;i>=0;i--){
if(cake[i]>cake[max])
max=i;
}
if(max>0){
printf("%d ",sum-max+1);
for(i=-1;max>=0;)
side[++i]=cake[max--];
while(i>=0)
cake[i]=side[i--];
}
printf("%d ",sum-(max=n--)+1);
for(i=-1;max>=0;)
side[++i]=cake[max--];
while(i>=0)
cake[i]=side[i--];
}
printf("0\n");
}
}
| dk00/old-stuff | uva/120.cpp | C++ | unlicense | 955 |
<?php
/**
* Page d'accueil
*
* @package Kdocode.com
* @author Louis Debraine (louisdebraine@hotmail.com)
* @copyright ©Loode
* @create 29/10/2009, Loode
*/
final class Frame_Child extends Frame {
// Frame main obligatoire, c'est elle qui va gérer toute la frame.
protected function main(){
// -- Vérification des deux variables GET, si une des deux est vide, on balance un message d'erreur.
if (multi_empty(trim($_GET['id']), $_GET['code'])){
$this->setMsgPhp('Vous avez tenté d\'accéder sur cette page en n\'entrant aucun ID et aucun CODE, hors, vous ne pouvez pas.', 'index.html', 5, 1);
}
// -- Sinon, on traite les données
$this->_checkMember();
return;
}
/**
* Vérifie et envoie le formulaire
*
* @return bool
*/
private function _checkMember(){
// -- On récupére le formulaire.
$this->data = array('id' => $_GET['id'],
'code' => $_GET['code']);
// -- On vérifie tous les champs
// -- On vérifie que le code est valide.
$sql = 'SELECT COUNT(*)
FROM site_inscrits
WHERE regis_id = "'.Instances::$security->entree($this->data['id']).'" &&
regis_validation = "'.Instances::$security->entree($this->data['code']).'";';
$res = mysql_fetch_array(Instances::$db->sql_query($sql));
// -- On le dégage si ça existe déjà.
if ($res[0] != 1){
// -- On insére une ligne dans le log.
$this->setMsgPhp('Votre code n\'est pas valide, ou bien il a été déjà validé.', 'index.html', 5, 1);
}
// -- Plus de vérification, donc on passe changement de la validation.
$sql = 'UPDATE site_inscrits SET regis_validation = "" WHERE regis_id = "'.Instances::$security->entree($this->data['id']).'"';
Instances::$db->sql_query($sql);
// -- On insére une ligne dans le log.
Instances::$security->addLog('L\'id '.$this->data['id'].' a bien validé son inscription.', 'site');
// -- On finit par afficher le message qui informe le visiteur qu'il est inscrit sur le site.
$this->setMsgPhp('Votre inscription a bien été validée, vous pouvez dès maintenant commencer à jouer à KDOCode.', 'index.html', 5, 0);
}
} // end Frame_Child
?> | LouisLoode/Kdocode | pages/frames/validation.php | PHP | unlicense | 2,367 |
const types = require('recast/lib/types')
const { namedTypes: n, NodePath } = types
const ABORT_EXCEPTION = Symbol('ABORT_EXCEPTION')
/**
* Low-level pre-order (breadth-first) traversal of an AST.
* It invokes `callback` for everything in the AST, not just nodes.
*
* The callback can return false to skip the traversal of the current node's children.
* It can also call `this.abort()` to stop the whole traversal.
*/
function preOrder(ast, callback) {
preOrderTwo(ast, null, function(path1) {
return callback.call(this, path1)
})
}
/**
* Traverses two AST trees and calls `callback` on each pair of paths.
*/
function preOrderTwo(ast1, ast2, callback) {
// https://github.com/benjamn/ast-types/blob/d3b32/lib/path-visitor.js#L126
const root1 = (ast1 instanceof NodePath) ? ast1 : new NodePath({ root: ast1 }).get('root')
const root2 = (ast2 instanceof NodePath) ? ast2 : new NodePath({ root: ast2 }).get('root')
// A queue that keeps pairs of paths to be traversed.
const queue = []
queue.push([root1, root2])
let didAbort = false
const context = {
abort() {
didAbort = true
throw ABORT_EXCEPTION
},
}
while (queue.length > 0) {
const [path1, path2] = queue.shift()
let traverseChildren = true
try {
traverseChildren = callback.call(context, path1, path2)
} finally {
if (didAbort) {
return false // eslint-disable-line no-unsafe-finally
}
}
if (traverseChildren !== false) {
const usedKeys = {}
const appendChildrenPair = (key) => {
if (!usedKeys[key]) {
usedKeys[key] = true
queue.push([path1.get(key), path2.get(key)])
}
}
getChildKeys(path1.value).forEach(appendChildrenPair)
getChildKeys(path2.value).forEach(appendChildrenPair)
}
}
}
/**
* Pre-order traversal with filtering by node type.
*/
function preOrderType(ast, type, callback) {
preOrder(ast, function preOrderTypeVisitor(path) {
if (n[type].check(path.value)) {
return callback.call(this, path)
}
})
}
/**
* Pre-order (breadth-first) traversal of a subtree inside an AST.
*/
function preOrderSubtree(ast, subtree, callback) {
const path = getNodePath(ast, subtree)
preOrderType(path, 'Node', callback)
}
/**
* Get the path of a `subtree` inside an AST.
*/
function getNodePath(ast, node) {
if (node instanceof NodePath) {
return node
}
let nodePath
preOrder(ast, function findSubtreePathVisitor(path) {
if (path.value === node) {
nodePath = path
this.abort()
}
})
return nodePath
}
/**
* Get keys for children of a value in an AST. The "value" could be anything
* inside the AST (e.g. node, array, etc).
*/
function getChildKeys(value) {
if (!value || typeof value !== 'object') {
return []
}
if (Array.isArray(value)) {
return value.map((_, i) => i)
} else {
return types.getFieldNames(value)
}
}
module.exports = {
preOrder, preOrderTwo, preOrderType, preOrderSubtree,
getNodePath,
getChildKeys,
}
| mdebbar/reshift | src/ast-traverse.js | JavaScript | unlicense | 3,055 |
<div class="footer">
<div class="row footer-content">
<div class="col-md-4 col-sm-4">
<div class="footer-sobre">
<div class="row">
<div class="col-lg-4 col-md-5" >
<img src="<?php echo base_url('/assets/images/logoamarela.png'); ?>" alt="<?php echo $dadosEmpresa['nomefantasia'];?>" width="150">
</div>
<div class="col-lg-4 col-md-6 col-md-offset-1 footer-nome-fantasia" >
<strong>Metais Agrícola</strong>
</div>
</div>
<p>
<span><?php echo $dadosEmpresa['descricaoempresa'];?></span>
</p>
</div>
</div>
<div class="col-md-4 col-md-offset-1 col-sm-4">
<h3><i class="glyphicon glyphicon-user"></i> Atendimento</span></h3>
<div class="footer-atendimento">
<table>
<tr>
<td class="contato-coluna-um"><strong>Manhã:</strong></td>
<td class="contato-coluna-dois"><span>08:00 as 12:00</span></td>
</tr>
<tr>
<td class="contato-coluna-um"><strong>Tarde:</strong></td>
<td class="contato-coluna-dois"><span>13:30 as 18:00</span></td>
</tr>
<tr>
<td class="contato-coluna-um"><strong>Sábado:</strong></td>
<td class="contato-coluna-dois"><span>08:00 as 12:00</span></td>
</tr>
</table>
</div>
</div>
<div class="col-md-3 col-sm-4">
<h3><i class="glyphicon glyphicon-phone-alt"></i> Contato</h3>
<address>
<div class="footer-contato dadosEmpresaContato">
<table>
<tr>
<td rowspan="3" class="contato-coluna-um"><strong>Endereço: </strong></td>
<td><span><?php echo $dadosEmpresa['endereco'];?></span></td>
</tr>
<tr>
<td class="contato-coluna-dois"><span><?php echo $dadosEmpresa['bairro'];?></span> - <span><?php echo $dadosEmpresa['numero'];?></span></td>
</tr>
<tr>
<td class="contato-coluna-dois"><span><?php echo $dadosEmpresa['estado'];?></span> - <span><?php echo $dadosEmpresa['cidade'];?></span></td>
</tr>
<tr>
<td class="contato-coluna-um"><strong>Telefone: </strong></td>
<td><span><?php echo $dadosEmpresa['telefoneprincipal'];?></span></td>
</tr>
<tr>
<td class="contato-coluna-um"><strong>E-mail: </strong></td>
<td><span><?php echo $dadosEmpresa['emailprincipal'];?></span></td>
</tr>
</table>
</div>
</address>
</div>
</div>
</div>
<div class="row sub-footer">
<div class="sub-footer-content">
<div class="col-md-6" style="padding-top: 14px;">
<p>©2013. Tor Metais. Todos os direitos reservados.</p>
</div>
<div class="col-md-6" style="padding-top: 14px; text-align: right;">
<a href="http://www.serviti.com.br" target="_blank" title="ServiTI" style="color: #fff;" ><p>ServiTI</p></a>
</div>
</div>
</div>
</body>
</html> | DEWebSistems/tormetais | application/views/fragmentos/rodape.php | PHP | unlicense | 4,084 |
var _ = require("/lib/underscore");
function ActionBar (options, btnText) {
options = (options) ? options : {};
var title = (options.title) ? options.title : "";
btnText = btnText || "...";
options = _.extend({
backgroundColor: '#5B7663',
top: 0, left: 0, height: 45, width: Ti.UI.FILL, // fullscreen
}, _.omit(options, "title"));
var self = Ti.UI.createView(options);
self.toggleButton = Ti.UI.createButton({
title: btnText,
borderRadius: 5,
color: '#FFF',
backgroundColor: '#437653',
borderColor: '#1C2920',
style: Ti.UI.iPhone.SystemButtonStyle.PLAIN,
left: 3, top: 3, bottom: 3, width: 30,
textAlign: Ti.UI.TEXT_ALIGNMENT_CENTER,
verticalAlign: Ti.UI.TEXT_VERTICAL_ALIGNMENT_CENTER
});
self.add(self.toggleButton);
var t = Ti.UI.createLabel({
text: title,
left: 0, right: 0,
color: '#291c1c',
font: {fontSize: 24, fontFamily: 'Verdana', fontStyle: 'normal'},
textAlign: Ti.UI.TEXT_ALIGNMENT_CENTER
});
self.add(t);
return self;
}
module.exports = ActionBar; | rcelha/x360achievements2 | Resources/ui/ActionBar.js | JavaScript | unlicense | 1,018 |
<?php
/**
* The purpose of this file is to an asynchronous search on Google News for the provided term
* and parse the results into usable JSON
* @author Andrew Crites <explosion-pills@aysites.com>
* @package gn-search
*/
class GnSearchAjax {
/**
* @var WP_Error container for server-side errors
*/
private $errors;
public function __construct() {
$this->errors = new WP_Error;
}
public static function gn_search_ajax() {
$gns = new self;
$gns->run();
}
/**
* Emit the results of the search attempt as json
* When successful, this responds with a status of 'success' and a 'response'
* with the results of the search.
* If it fails on this end, it response with an error message
*/
public function run() {
if (!isset($_REQUEST['term']) || !$_REQUEST['term']) {
$this->errors->add('no_term', __METHOD__ . ': no search term was provided');
$this->error('Please provide a search term');
}
$xml = $this->retrieve('http://news.google.com/news?q=' . urlencode($_REQUEST['term']) . '&output=rss');
$this->parse_response($xml);
}
/**
* Retrieve feed data as xml from source
*/
public function retrieve($url) {
if (ini_get('allow_url_fopen')) {
$data = file_get_contents($url);
}
else if (function_exists('curl_init')) {
$ch = curl_init($url);
curl_setopt_array($ch, array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
));
$data = curl_exec($ch);
$httpst = curl_getinfo($ch, CURLINFO_HTTP_CODE);
//If a successful response was not returned, trigger the correct error below
if (!in_array($httpst, array(200, 302, 304))) {
$data = null;
}
}
else {
$this->errors->add('no_method', __METHOD__ . ': no available method for download on server side');
$this->error('This site cannot get data from Google right now');
}
if (!$data) {
$this->errors->add('no_term', __METHOD__ . ': no response from Google News');
$this->error('No results available for your search');
}
return $data;
}
/**#@+
* Emit the response and exit
*/
private function success($response) {
header('Content-Type: application/json');
echo json_encode(array(
'status' => 'success',
'response' => $response
));
exit;
}
private function error($msg) {
header('Content-Type: application/json');
echo json_encode(array(
'status' => 'error',
'msg' => $msg
));
exit;
}
/**#@-*/
/**
* Parse the xml to search for news terms and emit as JSON when successful
* If no items or found or the xml is otherwise invalid, emit an error
* @param string search result xml
*/
public function parse_response($xml) {
//SimpleXML throws the very helpful "Exception" class when it fails
try {
$dom = new SimpleXMLElement($xml);
if (!$dom->channel) {
$this->errors->add('xml_parse_error', __METHOD__ . ': no "channel" element found when parsing successful response');
$this->error('There were no results for your search');
}
if (!$dom->channel->item) {
$this->error('There is no news about ' . $_REQUEST['term'] . ' right now');
}
$limit = 0;
if (isset($_REQUEST['limit']) && ctype_digit($_REQUEST['limit'])) {
$limit = $_REQUEST['limit'];
}
$results = array();
foreach ($dom->channel->item as $elem) {
//Cast the xml elements to strings to get their values
$results[] = array(
'title' => "$elem->title"
, 'url' => "$elem->link"
);
if ($limit == 1) {
break;
}
$limit--;
}
$this->success($results);
}
catch (Exception $e) {
$this->errors->add('xml_parse_error', __METHOD__ . ': unable to parse XML with SimpleXML -- '
. $e->getMessage());
$this->error('Sorry! We were unable to get results for your search');
}
}
}
?>
| ajcrites/gn-search | src/gn-search-ajax.php | PHP | unlicense | 4,287 |
using UnityEngine;
using UnityEngine.SceneManagement;
using System.Collections;
using UnityEngine.UI;
public class gameManager : MonoBehaviour {
public GameObject player1;
public GameObject player2;
public GameObject player1Text;
public GameObject player2Text;
public GameObject playerOneScoreText;
public GameObject playerTwoScoreText;
public GameObject highScoreText;
private Text txt1;
private Text txt2;
private Text highScoreTxt;
private static int playerOneScore;
private static int playerTwoScore;
private const string PREF_HIGH_SCORE = "highScorePref";
private static int highScore = 33;
public static int HighScore
{
get
{
highScore = PlayerPrefs.GetInt(PREF_HIGH_SCORE);
return highScore;
}
set
{
if (playerOneScore > HighScore)
{
HighScore = playerOneScore;
}
if (playerTwoScore > HighScore)
{
HighScore = playerTwoScore;
}
Debug.Log("Confetti!!!");
PlayerPrefs.SetInt(PREF_HIGH_SCORE, highScore);
}
}
public static gameManager instance;
private bool incrementScore = false;
// Use this for initialization
void Start () {
player2Text.SetActive(false);
player1Text.SetActive(false);
if (instance == null)
{
instance = this;
DontDestroyOnLoad(this);
}
else
{
Destroy(gameObject);
}
txt1 = playerOneScoreText.GetComponent<Text>();
txt2 = playerTwoScoreText.GetComponent<Text>();
highScoreTxt = highScoreText.GetComponent<Text>();
txt1.text ="P1: "+playerOneScore;
txt2.text = "P2: " + playerTwoScore;
highScoreTxt.text = "HS: " + highScore;
}
// Update is called once per frame
void Update () {
txt1.text = "P1 " + playerOneScore;
txt2.text = "P2 " + playerTwoScore;
if (player1 == null)
{
player2Text.SetActive(true);
Invoke("Restart", 2);
incrementScore = true;
if(incrementScore == true)
{
playerOneScore++;
incrementScore = false;
}
}
else if(player2 == null)
{
player1Text.SetActive(true);
Invoke("Restart", 2);
incrementScore = true;
if (incrementScore == true)
{
playerTwoScore++;
incrementScore = false;
}
}
}
void Restart()
{
Scene grief = SceneManager.GetActiveScene();
SceneManager.LoadScene("level2");
}
}
| Mostopha/mmh576_CodeLab1_WK7HW | Code Lab 1 Homework/Assets/Scripts/gameManager.cs | C# | unlicense | 2,934 |
package uk.ac.ebi.phenotype.dao;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.transaction.annotation.Transactional;
import uk.ac.ebi.phenotype.pojo.ImageRecordObservation;
import uk.ac.ebi.phenotype.pojo.Parameter;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertTrue;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:test-config.xml" })
@TransactionConfiguration
@Transactional
public class ObservationDAOImplTest {
@Autowired
ObservationDAO observationDAO;
@Test
public void testGetAllParametersWithObservations() {
List<Parameter> parameters = observationDAO.getAllParametersWithObservations();
assertTrue("There must be at least 20 parameters loaded", 20 < parameters.size());
}
@Test
public void testGetAllImageObservations() {
List<ImageRecordObservation> imageObservations = observationDAO.getAllImageObservations();
for(ImageRecordObservation obs: imageObservations){
System.out.println("observation="+obs.getDownloadFilePath());
}
}
@Test
public void testGetDistinctUnidimensionalOrgPipelineParamStrainZygosityGeneAccessionAlleleAccessionMetadata() throws SQLException {
List<Map<String, String>> datasets = observationDAO.getDistinctUnidimensionalOrgPipelineParamStrainZygosityGeneAccessionAlleleAccessionMetadata();
System.out.println("number of datasets in database: " + datasets.size());
System.out.println(datasets.get(0));
}
}
| mpi2/PhenotypeArchive | src/test/java/uk/ac/ebi/phenotype/dao/ObservationDAOImplTest.java | Java | apache-2.0 | 1,802 |
package hu.androidportal.rss;
import java.util.Date;
import android.net.Uri;
public class RSSItem extends RSSObject
{
private static final String BREAK = "<!--break-->";
public final static String F_PUBDATE = "pubdate";
public final static String F_AUTHOR = "author";
public final static int MAX_SUMMARY_LENGTH = 400;
/**
* The MIME type of {@link #CONTENT_URI} providing a directory of banks.
*/
public static final String CONTENT_TYPE = "vnd.android.cursor.dir/hu.androidportal.RSSItem";
/**
* The MIME type of a {@link #CONTENT_URI} sub-directory of a single bank.
*/
public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/hu.androidportal.RSSItem";
/**
* The content:// style URL for this table.
*/
public static final Uri CONTENT_URI = Uri.parse("content://hu.androidportal.RSSItem/rssitems");
public static final String DEFAULT_SORT_ORDER = F_PUBDATE + " ASC";
public Date publishDate;
public String author;
@Override
public String toString()
{
return "RSSItem: " + super.toString() + "|" + author + "|" + publishDate;
}
public void generateSummary()
{
//remove mistic break text from the article.
//it should be removed from the original description
int breakIndex = description.indexOf(BREAK);
if ( breakIndex > 0 )
{
final StringBuilder builder = new StringBuilder(description);
while ( breakIndex >= 0 )
{
builder.delete(breakIndex, breakIndex + BREAK.length());
breakIndex = builder.indexOf(BREAK);
}
description = builder.toString();
}
final StringBuilder builder = new StringBuilder(description);
//remove HTML tags
int start = builder.indexOf("<");
int stop = builder.indexOf(">", start);
while ( start >= 0 && stop >= 0 && start < MAX_SUMMARY_LENGTH )
{
builder.delete(start, stop + 1);
start = builder.indexOf("<");
stop = builder.indexOf(">", start);
}
//normalize whitespaces
int i = 0;
start = -1;
while ( i < builder.length() && !( start == -1 && i > MAX_SUMMARY_LENGTH ) )
{
if ( start >= 0 )
{
if ( !Character.isWhitespace(builder.charAt(i)) )
{
builder.delete(start, i); //remove all white spaces
if ( start > 0 )
builder.insert(start, ' '); // insert a space instead
i = start;
start = -1;
}
}
else if ( Character.isWhitespace(builder.charAt(i)) )
{
start = i;
}
i++;
}
if ( start >= 0 )
{ // this happens only when i runs out of the length
builder.delete(start, i); //remove all white spaces at the end of the text
}
//trim to maximum length
if ( builder.length() > MAX_SUMMARY_LENGTH )
builder.delete(MAX_SUMMARY_LENGTH, builder.length());
summary = HTMLEntities.fromHtmlEntities(builder).toString();
}
}
| kuc/bankdroid | AndroidPortal.hu/src/hu/androidportal/rss/RSSItem.java | Java | apache-2.0 | 2,852 |
$('#buscador').on("input", function() {
var dInput = this.value;
console.log("res es",dInput);
}); | dsaqp1516g4/www | js/buscador.js | JavaScript | apache-2.0 | 109 |
// Copyright 2007-2011 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// 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.
namespace Burrows.Subscriptions
{
using System;
/// <summary>
/// Used to wrap an UnsubscribeAction in a disposable block
/// </summary>
public interface IUnsubscribeAction :
IDisposable
{
/// <summary>
/// Add additional actions to the unsubscribe action
/// </summary>
/// <param name="action"></param>
void Add(UnsubscribeAction action);
}
} | eswann/Burrows | src/Burrows/Subscriptions/IUnsubscribeAction.cs | C# | apache-2.0 | 1,042 |
package com.macro.mall.dao;
import com.macro.mall.model.PmsProductLadder;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* 会员阶梯价格自定义Dao
* Created by macro on 2018/4/26.
*/
public interface PmsProductLadderDao {
/**
* 批量创建
*/
int insertList(@Param("list") List<PmsProductLadder> productLadderList);
}
| macrozheng/mall | mall-admin/src/main/java/com/macro/mall/dao/PmsProductLadderDao.java | Java | apache-2.0 | 374 |
/*
* Copyright 2022 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.metaservice.service;
import com.ctrip.framework.apollo.common.condition.ConditionalOnMissingProfile;
import com.ctrip.framework.apollo.core.dto.ServiceDTO;
import com.ctrip.framework.apollo.tracer.Tracer;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.discovery.EurekaClient;
import com.netflix.discovery.shared.Application;
import java.util.Collections;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
/**
* Default discovery service for Eureka
*/
@Service
@ConditionalOnMissingProfile({"kubernetes", "nacos-discovery", "consul-discovery", "zookeeper-discovery"})
public class DefaultDiscoveryService implements DiscoveryService {
private final EurekaClient eurekaClient;
public DefaultDiscoveryService(final EurekaClient eurekaClient) {
this.eurekaClient = eurekaClient;
}
@Override
public List<ServiceDTO> getServiceInstances(String serviceId) {
Application application = eurekaClient.getApplication(serviceId);
if (application == null || CollectionUtils.isEmpty(application.getInstances())) {
Tracer.logEvent("Apollo.Discovery.NotFound", serviceId);
return Collections.emptyList();
}
return application.getInstances().stream().map(instanceInfoToServiceDTOFunc)
.collect(Collectors.toList());
}
private static final Function<InstanceInfo, ServiceDTO> instanceInfoToServiceDTOFunc = instance -> {
ServiceDTO service = new ServiceDTO();
service.setAppName(instance.getAppName());
service.setInstanceId(instance.getInstanceId());
service.setHomepageUrl(instance.getHomePageUrl());
return service;
};
}
| nobodyiam/apollo | apollo-configservice/src/main/java/com/ctrip/framework/apollo/metaservice/service/DefaultDiscoveryService.java | Java | apache-2.0 | 2,374 |
__source__ = 'https://leetcode.com/problems/knight-dialer/'
# Time: O(N)
# Space: O(1)
#
# Description: Leetcode # 935. Knight Dialer
#
# A chess knight can move as indicated in the chess diagram below:
#
# This time, we place our chess knight on any numbered key of a phone pad (indicated above),
# and the knight makes N-1 hops. Each hop must be from one key to another numbered key.
#
# Each time it lands on a key (including the initial placement of the knight),
# it presses the number of that key, pressing N digits total.
#
# How many distinct numbers can you dial in this manner?
#
# Since the answer may be large, output the answer modulo 10^9 + 7.
#
# Example 1:
#
# Input: 1
# Output: 10
# Example 2:
#
# Input: 2
# Output: 20
# Example 3:
#
# Input: 3
# Output: 46
#
# Note:
#
# 1 <= N <= 5000
#
import unittest
# 908ms 59.71%
class Solution(object):
def knightDialer(self, N):
"""
:type N: int
:rtype: int
"""
MOD = 10**9 + 7
moves = [[4,6],[6,8],[7,9],[4,8],[3,9,0],[],
[1,7,0],[2,6],[1,3],[2,4]]
dp = [1] * 10
for hops in xrange(N-1):
dp2 = [0] * 10
for node, count in enumerate(dp):
for nei in moves[node]:
dp2[nei] += count
dp2[nei] %= MOD
dp = dp2
return sum(dp) % MOD
# Time: O(longN) regarding ower matrix
# https://math.stackexchange.com/questions/1890620/finding-path-lengths-by-the-power-of-adjacency-matrix-of-an-undirected-graph
# https://leetcode.com/problems/knight-dialer/discuss/189252/O(logN)
# 64ms 98.74%
import numpy as np
class Solution2(object):
def knightDialer(self, N):
mod = 10**9 + 7
if N == 1: return 10
M = np.matrix([[0, 0, 0, 0, 1, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 0, 1, 0],
[0, 0, 0, 0, 0, 0, 0, 1, 0, 1],
[0, 0, 0, 0, 1, 0, 0, 0, 1, 0],
[1, 0, 0, 1, 0, 0, 0, 0, 0, 1],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[1, 1, 0, 0, 0, 0, 0, 1, 0, 0],
[0, 0, 1, 0, 0, 0, 1, 0, 0, 0],
[0, 1, 0, 1, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 1, 0, 0, 0, 0, 0]])
res, N = 1, N - 1
while N:
if N % 2: res = res * M % mod
M = M * M % mod
N /= 2
return int(np.sum(res)) % mod
class TestMethods(unittest.TestCase):
def test_Local(self):
self.assertEqual(1, 1)
if __name__ == '__main__':
unittest.main()
Java = '''
# Thought: https://leetcode.com/problems/knight-dialer/solution/
# Best explanation: https://leetcode.com/problems/knight-dialer/discuss/190787/How-to-solve-this-problem-explained-for-noobs!!!
Approach 1: Dynamic Programming
Complexity Analysis
Time Complexity: O(N)
Space Complexity: O(1)
DP: "the total number of unique paths to (i, j) for certain hops n
is equal to the sum of total number of unique paths to each valid position
from which (i, j) can be reached using n - 1 hops".
# 47ms 59.39%
class Solution {
public int knightDialer(int N) {
int MOD = 1_000_000_007;
int[][] moves = new int[][]{
{4,6},{6,8},{7,9},{4,8},{3,9,0},
{},{1,7,0},{2,6},{1,3},{2,4}
};
int[][] dp = new int[2][10];
Arrays.fill(dp[0], 1);
for (int hops = 0; hops < N -1; ++hops) {
Arrays.fill(dp[~hops & 1], 0);
for (int node = 0; node < 10; ++node) {
for (int nei : moves[node]) {
dp[~hops & 1][nei] += dp[hops & 1][node];
dp[~hops & 1][nei] %= MOD;
}
}
}
long ans = 0;
for (int x : dp[~N & 1]) ans += x;
return (int) (ans % MOD);
}
}
# Memorization
# 5ms 99.93%
class Solution {
private static final int MOD = 1_000_000_007;
private static final int[][] dp = new int[5001][10];
private static final int[][] moves = {{4, 6}, {6, 8}, {7, 9}, {4, 8}, {3, 9, 0}, {}, {1, 7, 0},{2, 6}, {1, 3}, {2, 4}};
public int knightDialer(int N) {
int res = 0;
for (int i = 0; i < 10; i++) {
res = (res + helper(N, i)) % MOD;
}
return res;
}
private int helper(int N, int digit) {
if (N == 1) return 1;
if (digit == 5) return 0;
if (dp[N][digit] > 0) return dp[N][digit];
for (int next : moves[digit]) {
dp[N][digit] = (dp[N][digit] + helper(N -1, next)) % MOD;
}
return dp[N][digit];
}
}
''' | JulyKikuAkita/PythonPrac | cs15211/KnightDialer.py | Python | apache-2.0 | 4,651 |
import { blue6, gold6, grey7, grey9, red6 } from "./colors";
/*
SIZES
*/
export const FONT_SIZE_DEFAULT = "14px";
export const FONT_SIZE_LARGE = "16px";
export const FONT_SIZE_SMALL = "12px";
/*
WEIGHTS
*/
export const FONT_WEIGHT_DEFAULT = 300;
export const FONT_WEIGHT_HEAVY = 500;
/*
COLOURS
*/
export const FONT_COLOR_DEFAULT = grey9;
export const FONT_COLOR_MUTED = grey7;
export const FONT_COLOR_PRIMARY = blue6;
export const FONT_COLOR_INFO = blue6;
export const FONT_COLOR_ERROR = red6;
export const FONT_COLOR_WARNING = gold6;
/*
FONT FAMILIES
*/
export const ANT_DESIGN_FONT_FAMILY = `-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,
Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif`;
| phac-nml/irida | src/main/webapp/resources/js/styles/fonts.js | JavaScript | apache-2.0 | 727 |
package algebralearning;
import org.sat4j.specs.TimeoutException;
import algebralearning.equality.EqualityAlgebraLearnerFactory;
import algebralearning.sfa.SFAAlgebraLearner;
import algebralearning.sfa.SFAEquivalenceOracle;
import algebralearning.sfa.SFAMembershipOracle;
import automata.sfa.SFA;
import theory.characters.CharPred;
import theory.intervals.UnaryCharIntervalSolver;
import utilities.SFAprovider;
/**
* This class implements the first experiment (section 6.1) from the paper
* "The Learnability of Symbolic Automata" by George Argyros and Loris D'Antoni.
*
* @author George Argyros
*
*/
public class RELearning {
public static String[] reBenchmarks = {
"\\<.*(script|xss).*?\\>",
"\\<.*(applet|b(ase|gsound|link)|embed)[^\\>]*\\>",
"(\\<[^\\<\\>]+\\>\\<[^<]+\\>\\<\\/[^\\<\\>]+\\>)",
"(<meta[/+\\t\\n ].*?http-equiv[/+\\t\\n ])",
"(<\\?import[/+\\t\\n ].*?implementation[/+\\t\\n ])",
"(alter\\s*\\w+.*character\\s+set\\s+\\w+)|(\\\";\\s*waitfor\\s+time\\s+\\\")|(\\\"\\;.*:\\s*goto)",
"(and)\\s+(\\d{1,10}|\\'[^\\=]{1,10}\\')\\s*?[\\=]|(and)\\s+(\\d{1,10}|\\'[^\\=]{1,10}\\')\\s*?[\\<\\>]|and\\s?(\\d{1,10}|[\\'\\\"][^\\=]{1,10}[\\'\\\"])\\s?[\\=\\<\\>]+|(and)\\s+(\\d{1,10}|\\'[^\\=]{1,10}\\')",
"([^a-zA-Z]\\s+as\\s*[\\\"a-z0-9A-Z]+\\s*from)|([^a-zA-Z]+\\s*(union|select|create|rename|truncate|load|alter|delete|update|insert|desc))|((select|create|rename|truncate|load|alter|delete|update|insert|desc)\\s+((group_)concat|char|load\\_file)\\s?\\(?)",
"(\\,\\s*(alert|showmodaldialog|eval)\\s*\\,)|(\\s*eval\\s*[^ ])|([^:\\s\\w\\,.\\/?+-]\\s*)?(\\<\\![a-z\\/\\_@])(\\s*return\\s*)?((document\\s*\\.)?(.+\\/)?(alert|eval|msgbox|showmod(al|eless)dialog|showhelp|prompt|write(ln)?|confirm|dialog|open))\\s*([^.a-z\\s\\-]|(\\s*[^\\s\\w\\,.@\\/+-]))|(java[ \\/]*\\.[ \\/]*lang)|(\\w\\s*\\=\\s*new\\s+\\w+)|(&\\s*\\w+\\s*\\)[^\\,])|(\\+[^a-zA-Z]*new\\s+\\w+[^a-zA-Z]*\\+)|(document\\.\\w)",
"(union\\s*(all|distinct|[(\\!\\@]*)\\s*[([]*\\s*select)|(\\w+\\s+like\\s+\\\")|(like\\s*\\\"\\\\%)|(\\\"\\s*like\\W*[\\\"0-9])|(\\\"\\s*(n?and|x?or|not[ ]|\\|\\||\\\\&\\\\&)\\s+[ a-z0-9A-Z]+\\=\\s*\\w+\\s*having)|(\\\"\\s*\\*\\s*\\w+\\W+\\\")|(\\\"\\s*[^?a-z0-9A-Z \\=.,;)(]+\\s*[(\\@\\\"]*\\s*\\w+\\W+\\w)|(select\\s*[\\[\\]\\(\\)\\s\\w\\.,\\\"-]+from)|(find_in_set\\s*\\()",
"(\\w|\\-)+\\@((\\w|\\-)+\\.)+(\\w|\\-)+",
"\\$?(\\d{1,3}\\,?(\\d{3}\\,?)*\\d{3}(\\.\\d{0,2})?|\\d{1,3}(\\.\\d{0,2})?|\\.\\d{1,2}?)",
"([A-Z]{2}|[a-z]{2}[ ]\\d{2}[ ][A-Z]{1,2}|[a-z]{1,2}[ ]\\d{1,4})?([A-Z]{3}|[a-z]{3}[ ]\\d{1,4})?",
"[A-Za-z0-9](([ \\.\\-]?[a-zA-Z0-9]+)*)\\@([A-Za-z0-9]+)(([\\.\\-]?[a-zA-Z0-9]+)*)\\.[ ]([A-Za-z][A-Za-z]+)",
"[\\+\\-]?([0-9]*\\.?[0-9]+|[0-9]+\\.?[0-9]*)([eE][\\+\\-]?[0-9]+)?"
};
public static Integer[] learnREBenchmark(Integer index) throws TimeoutException {
Integer[] results = new Integer[8];
if (index < 0 || index >= reBenchmarks.length) {
return null;
}
UnaryCharIntervalSolver solver = new UnaryCharIntervalSolver();
SFAprovider provider = new SFAprovider(reBenchmarks[index], solver);
SFA<CharPred, Character> model, sfa = provider.getSFA();
SFAMembershipOracle <CharPred, Character> memb = new SFAMembershipOracle<>(sfa, solver);
SFAEquivalenceOracle <CharPred, Character> equiv = new SFAEquivalenceOracle<>(sfa, solver);
EqualityAlgebraLearnerFactory <CharPred, Character> eqFactory = new EqualityAlgebraLearnerFactory <>(solver);
SFAAlgebraLearner <CharPred, Character> learner = new SFAAlgebraLearner<>(memb, solver, eqFactory);
model = learner.getModelFinal(equiv);
// The results are saved in the order that they are presented in the paper.
results[0] = model.stateCount();
results[1] = model.getTransitionCount();
results[2] = memb.getDistinctQueries();
results[3] = equiv.getDistinctCeNum();
results[4] = equiv.getCachedCeNum();
results[5] = learner.getNumCEGuardUpdates();
results[6] = learner.getNumDetCE();
results[7] = learner.getNumCompCE();
return results;
}
public static Integer[][] learnAllBenchmarks() throws TimeoutException {
Integer[][] results = new Integer[reBenchmarks.length][8];
for (int i = 0; i < reBenchmarks.length; i ++) {
results[i] = learnREBenchmark(i);
}
return results;
}
}
| lorisdanto/symbolicautomata | benchmarks/src/main/java/algebralearning/RELearning.java | Java | apache-2.0 | 4,269 |
/*
* Copyright 2016 OPEN TONE 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 net.java.amateras.xlsbeans.xml;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.HashMap;
import java.util.Map;
import ognl.Ognl;
import ognl.OgnlContext;
/**
* Creates {@link java.lang.annotation.Annotation} instances
* dynamically using Javassist.
*
* @author opentone
*/
public class DynamicAnnotationBuilder {
private static ClassLoader loader;
private static OgnlContext ognlContext = null;
/**
* Sets class loader that uses Annotation defined by XLSBeans.
*
* @param loader ClassLoader used to find Annotation.
*/
public static void setClassLoader(ClassLoader loader){
DynamicAnnotationBuilder.loader = loader;
DynamicAnnotationBuilder.ognlContext = null;
}
/**
* Set class loader that uses Annotation defined by XLSBeans,
* and that uses JavaBeans type in defined dynamic-annotation by users.
*
* @param loader ClassLoader used to find Annotation.
* @param propertyLoaders used to find JavaBeans type.
*/
public static void setClassLoader(ClassLoader loader,
ClassLoader[] propertyLoaders) {
DynamicAnnotationBuilder.loader = loader;
if (propertyLoaders != null && propertyLoaders.length != 0) {
Map<Integer, ClassLoader> loaderMap = new HashMap<Integer, ClassLoader>();
for (ClassLoader propertyLoader : propertyLoaders) {
loaderMap.put(propertyLoader.hashCode(), propertyLoader);
}
DynamicAnnotationBuilder.ognlContext = new OgnlContext(loaderMap);
DynamicAnnotationBuilder.ognlContext.setClassResolver(new MultipleLoaderClassResolver());
} else {
DynamicAnnotationBuilder.ognlContext = null;
}
}
/**
* Creates the annotation instance dynamically using Javaassist.
*/
public static Annotation buildAnnotation(final Class<?> ann, AnnotationInfo info) throws Exception {
final Map<String, Object> defaultValues = new HashMap<String, Object>();
for(Method method : ann.getMethods()){
Object defaultValue = method.getDefaultValue();
if(defaultValue!=null){
defaultValues.put(method.getName(), defaultValue);
}
}
final Map<String, Object> xmlValues = new HashMap<String, Object>();
for(String key : info.getAnnotationAttributeKeys()){
Object value = null;
if (ognlContext == null) {
value = Ognl.getValue(info.getAnnotationAttribute(key),new Object());
} else {
value = Ognl.getValue(info.getAnnotationAttribute(key), ognlContext, new Object());
}
xmlValues.put(key, value);
}
ClassLoader loader = DynamicAnnotationBuilder.loader;
if(loader == null){
loader = Thread.currentThread().getContextClassLoader();
}
Object obj = Proxy.newProxyInstance(loader, new Class[]{ann},
new InvocationHandler(){
public Object invoke(Object proxy, Method method,
Object[] args) throws Throwable {
String name = method.getName();
if (name.equals("annotationType")) {
return ann;
} else if(xmlValues.containsKey(name)){
return xmlValues.get(name);
} else {
return defaultValues.get(name);
}
}
});
return (Annotation)obj;
}
}
| otsecbsol/linkbinder | linkbinder-framework-core/src/main/java/net/java/amateras/xlsbeans/xml/DynamicAnnotationBuilder.java | Java | apache-2.0 | 4,346 |
/*
* Orika - simpler, better and faster Java bean mapping
*
* Copyright (C) 2011-2013 Orika authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ma.glasnost.orika;
/**
* Abstract super-class for all generated mappers and user custom mappers.
*
* @see ma.glasnost.orika.metadata.ClassMapBuilder
* @author S.M. El Aatifi
* @deprecated use {@link ma.glasnost.orika.CustomMapper} instead
*/
@Deprecated
public abstract class MapperBase<A, B> {
protected MapperFacade mapperFacade;
public void mapAtoB(A a, B b, MappingContext context) {
/* */
}
public void mapBtoA(B b, A a, MappingContext context) {
/* */
}
public void setMapperFacade(MapperFacade mapper) {
this.mapperFacade = mapper;
}
public Class<A> getAType() {
throw throwShouldNotCalledCustomMapper();
}
public Class<B> getBType() {
throw throwShouldNotCalledCustomMapper();
}
public void setUsedMappers(Mapper<Object, Object>[] mapper) {
throw throwShouldNotCalledCustomMapper();
}
private IllegalStateException throwShouldNotCalledCustomMapper() {
return new IllegalStateException("Should not be called for a user custom mapper.");
}
/**
* Provides backward-compatibility for custom mappers that extend
* the deprecated MapperBase.
*
* @author matt.deboer@gmail.com
*
* @param <A>
* @param <B>
*/
public static class MapperBaseAdapter<A, B> extends CustomMapper<A, B> {
private final MapperBase<A, B> delegate;
public MapperBaseAdapter(MapperBase<A, B> delegate) {
this.delegate = delegate;
}
public void mapAtoB(A a, B b, MappingContext context) {
delegate.mapAtoB(a, b, context);
}
public void mapBtoA(B b, A a, MappingContext context) {
delegate.mapBtoA(b, a, context);
}
public void setMapperFacade(MapperFacade mapper) {
delegate.setMapperFacade(mapper);
}
public Boolean favorsExtension() {
return false;
}
}
}
| orika-mapper/orika | core/src/main/java/ma/glasnost/orika/MapperBase.java | Java | apache-2.0 | 2,814 |
package ru.salauyou.util.collect;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Deque;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.junit.Test;
public class TestMinMaxHeapDeque {
@Test
public void testOffer() {
Deque<Integer> q = ofItems(3, 1, 0, 4, 5, 2);
assertEquals(6, q.size());
}
@Test(expected = NoSuchElementException.class)
public void testEmpty() {
Deque<Integer> q = ofItems();
assertEquals(0, q.size());
Iterator<Integer> it = q.iterator();
assertFalse(it.hasNext());
it.next();
}
@Test
public void testPeek() {
Deque<Integer> q = ofItems(6, 0, 1, 3, 4, 5, 2, 7, 8, 9);
assertEquals((Integer) 0, q.peek());
assertEquals((Integer) 9, q.peekLast());
q = new MinMaxHeapDeque<>();
int size = 100_000;
List<Integer> items = IntStream.range(0, size).boxed().collect(Collectors.toList());
Collections.shuffle(items);
q.addAll(items);
assertEquals((Integer) 0, q.peek());
assertEquals((Integer) (size - 1), q.peekLast());
}
@Test
public void testPoll() {
Deque<Integer> q = ofItems(9, 0, 1, 3, 4, 5, 2, 7, 8, 6);
List<Integer> head = new ArrayList<>();
List<Integer> tail = new ArrayList<>();
Integer h, t;
while ((h = q.poll()) != null && (t = q.pollLast()) != null) {
head.add(h);
tail.add(t);
}
assertEquals(0, q.size());
assertTrue(q.isEmpty());
assertEquals(Arrays.asList(0, 1, 2, 3, 4), head);
assertEquals(Arrays.asList(9, 8, 7, 6, 5), tail);
}
@Test
public void testPollLarge() {
int size = 50_000;
List<Integer> head = IntStream.range(0, size).boxed().collect(Collectors.toList());
List<Integer> tail = IntStream.range(size, size * 2).boxed().collect(Collectors.toList());
Collections.reverse(tail);
List<Integer> all = new ArrayList<>(head);
all.addAll(tail);
Collections.shuffle(all);
Deque<Integer> q = new MinMaxHeapDeque<>();
q.addAll(all);
Integer h, t;
Iterator<Integer> hi = head.iterator();
Iterator<Integer> ti = tail.iterator();
while ((h = q.poll()) != null && (t = q.pollLast()) != null) {
assertEquals(hi.next(), h);
assertEquals(ti.next(), t);
}
assertTrue(q.isEmpty());
}
@Test
public void testIterator() {
Deque<Integer> q = ofItems(9, 0, 1, 3, 4, 5, 2, 7, 8, 6);
List<Integer> toRemove = Arrays.asList(2, 3, 4, 9, 0);
Iterator<Integer> it = q.iterator();
while (it.hasNext()) {
if (toRemove.contains(it.next())) {
it.remove();
}
}
assertTrue(q.containsAll(Arrays.asList(1, 5, 6, 7, 8)));
}
@Test
public void testConsistentRemove() {
Deque<Integer> q = ofItems(6, 0, 1, 3, 4, 5, 2, 7, 8, 9);
q.remove(9);
q.removeLastOccurrence(3);
q.remove(0);
q.removeLastOccurrence(4);
q.remove(2);
List<Integer> head = new ArrayList<>();
Integer e;
while ((e = q.poll()) != null) {
head.add(e);
}
assertEquals(Arrays.asList(1, 5, 6, 7, 8), head);
}
@Test
public void testGenerateSequence() {
Integer[][] sequences = new Integer[][] {
{ 0 },
{ 0, 1 },
{ 0, 2, 1 },
{ 0, 3, 2, 1 },
{ 0, 3, 4, 2, 1 },
{ 0, 3, 4, 5, 2, 1 },
{ 0, 3, 4, 5, 6, 2, 1 },
{ 0, 3, 4, 5, 6, 7, 2, 1 },
{ 0, 3, 4, 5, 6, 8, 7, 2, 1 },
{ 0, 3, 4, 5, 6, 9, 8, 7, 2, 1 },
{ 0, 3, 4, 5, 6, 10, 9, 8, 7, 2, 1 },
{ 0, 3, 4, 5, 6, 11, 10, 9, 8, 7, 2, 1 },
{ 0, 3, 4, 5, 6, 12, 11, 10, 9, 8, 7, 2, 1 },
{ 0, 3, 4, 5, 6, 13, 12, 11, 10, 9, 8, 7, 2, 1 },
{ 0, 3, 4, 5, 6, 14, 13, 12, 11, 10, 9, 8, 7, 2, 1 },
{ 0, 3, 4, 5, 6, 15, 14, 13, 12, 11, 10, 9, 8, 7, 2, 1 },
{ 0, 3, 4, 5, 6, 15, 16, 14, 13, 12, 11, 10, 9, 8, 7, 2, 1 },
{ 0, 3, 4, 5, 6, 15, 16, 17, 14, 13, 12, 11, 10, 9, 8, 7, 2, 1 },
};
for (int i = 0; i < sequences.length; i++) {
int size = sequences[i].length;
int j = 0;
int p = 0;
while (j >= 0) {
assertEquals(sequences[i][p], (Integer) j);
j = MinMaxHeapDeque.nextIndex(j, size);
p++;
}
}
}
@Test
public void testSortedSetConstructor() {
SortedSet<Integer> ss = new TreeSet<>(Collections.reverseOrder());
ss.addAll(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9));
Deque<Integer> q = new MinMaxHeapDeque<>(ss);
assertEquals((Integer) 9, q.peek());
assertEquals((Integer) 1, q.peekLast());
q.offer(10);
q.offer(0);
assertEquals((Integer) 10, q.poll());
assertEquals((Integer) 9, q.poll());
assertEquals((Integer) 0, q.pollLast());
assertEquals((Integer) 1, q.pollLast());
}
@Test
public void testCollectionConstructor() {
Deque<Integer> q = new MinMaxHeapDeque<>(Arrays.asList(9, 8, 7, 6, 5, 4, 3, 2, 1, 0));
assertEquals(10, q.size());
assertEquals((Integer) 0, q.peek());
assertEquals((Integer) 9, q.peekLast());
int size = 100;
List<Integer> ordered = IntStream.range(0, size).boxed().collect(Collectors.toList());
Collections.reverse(ordered);
List<Integer> shuffled = new ArrayList<>(ordered);
Collections.shuffle(shuffled);
q = new MinMaxHeapDeque<>(shuffled, Collections.reverseOrder());
List<Integer> res = new ArrayList<>();
Integer e;
while ((e = q.poll()) != null) {
res.add(e);
}
assertTrue(q.isEmpty());
assertEquals(ordered, res);
}
@SafeVarargs
static <T extends Comparable<? super T>> MinMaxHeapDeque<T> ofItems(T... items) {
final MinMaxHeapDeque<T> q = new MinMaxHeapDeque<>();
for (T e : items) {
q.offer(e);
}
return q;
}
}
| Salauyou/Java-Utils | src/test/java/ru/salauyou/util/collect/TestMinMaxHeapDeque.java | Java | apache-2.0 | 6,052 |
/*
* Copyright 2010-2016 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.amazonaws.services.cognitosync.model;
import java.io.Serializable;
/**
* Response to a successful DescribeIdentityPoolUsage request.
*/
public class DescribeIdentityPoolUsageResult implements Serializable, Cloneable {
/** Information about the usage of the identity pool. */
private IdentityPoolUsage identityPoolUsage;
/**
* Information about the usage of the identity pool.
*
* @param identityPoolUsage
* Information about the usage of the identity pool.
*/
public void setIdentityPoolUsage(IdentityPoolUsage identityPoolUsage) {
this.identityPoolUsage = identityPoolUsage;
}
/**
* Information about the usage of the identity pool.
*
* @return Information about the usage of the identity pool.
*/
public IdentityPoolUsage getIdentityPoolUsage() {
return this.identityPoolUsage;
}
/**
* Information about the usage of the identity pool.
*
* @param identityPoolUsage
* Information about the usage of the identity pool.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public DescribeIdentityPoolUsageResult withIdentityPoolUsage(
IdentityPoolUsage identityPoolUsage) {
setIdentityPoolUsage(identityPoolUsage);
return this;
}
/**
* Returns a string representation of this object; useful for testing and
* debugging.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getIdentityPoolUsage() != null)
sb.append("IdentityPoolUsage: " + getIdentityPoolUsage());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof DescribeIdentityPoolUsageResult == false)
return false;
DescribeIdentityPoolUsageResult other = (DescribeIdentityPoolUsageResult) obj;
if (other.getIdentityPoolUsage() == null
^ this.getIdentityPoolUsage() == null)
return false;
if (other.getIdentityPoolUsage() != null
&& other.getIdentityPoolUsage().equals(
this.getIdentityPoolUsage()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime
* hashCode
+ ((getIdentityPoolUsage() == null) ? 0
: getIdentityPoolUsage().hashCode());
return hashCode;
}
@Override
public DescribeIdentityPoolUsageResult clone() {
try {
return (DescribeIdentityPoolUsageResult) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException(
"Got a CloneNotSupportedException from Object.clone() "
+ "even though we're Cloneable!", e);
}
}
} | trasa/aws-sdk-java | aws-java-sdk-cognitosync/src/main/java/com/amazonaws/services/cognitosync/model/DescribeIdentityPoolUsageResult.java | Java | apache-2.0 | 3,879 |
import '@polymer/polymer/polymer-legacy.js';
import {PolymerElement} from '@polymer/polymer/polymer-element.js';
import Dexie from 'dexie';
import EtoolsAjaxRequestMixin from '../etools-ajax-request-mixin.js';
// set logging level
window.EtoolsLogsLevel = window.EtoolsLogsLevel || 'INFO';
// custom dexie db that will be used by etoolsAjax
var etoolsCustomDexieDb = new Dexie('etoolsAjax2DexieDb');
etoolsCustomDexieDb.version(1).stores({
listsExpireMapTable: "&name, expire",
ajaxDefaultDataTable: "&cacheKey, data, expire",
countries: "&id, name"
});
// configure app dexie db to be used for caching
window.EtoolsRequestCacheDb = etoolsCustomDexieDb;
class DirectAjaxCalls extends EtoolsAjaxRequestMixin(PolymerElement) {
static get is() {
return 'direct-ajax-calls';
}
ready() {
super.ready();
// console.log(this.etoolsAjaxCacheDb);
this._setCookie();
this.get_WithNoCache();
// this.get_WithCacheToDefaultTable();
// this.get_WithCacheToSpecifiedTable();
this.post_Json();
this.patch_WithJsonContent();
this.patch_WithCsrfCheck();
this.patch_WithAdditionalHeaders();
// this.post_WithMultipartData();
}
post_Json() {
this.sendRequest({
method: 'DELETE',
endpoint: {
url: 'http://httpbin.org/delete',
},
body: {
id: "14",
firstName: "JaneTEST",
lastName: "DoeTest"
}
}).then(function (resp) {
console.log(resp);
}).catch(function (error) {
console.log(error);
});
}
patch_WithJsonContent() {
this.sendRequest({
method: 'PATCH',
endpoint: {
url: 'http://httpbin.org/patch',
},
body: {
id: "14",
firstName: "JaneTEST2"
}
}).then(function (resp) {
console.log(resp);
}).catch(function (error) {
console.log(error);
});
}
get_WithNoCache() {
this.sendRequest({
endpoint: {
url: 'http://httpbin.org/get',
},
params: {
id: 10,
name: 'Georgia'
}
}).then(function (resp) {
console.log(resp);
}).catch(function (error) {
console.log(error);
});
this.sendRequest({
endpoint: {
url: 'http://httpbin.org/status/403',
}
}).then(function (resp) {
console.log(resp);
}).catch(function (error) {
console.log(error);
});
}
get_WithCacheToDefaultTable() {
this.sendRequest({
endpoint: {
url: 'http://192.168.1.184/silex-test-app/web/index.php/countries-data',
exp: 5 * 60 * 1000, // cache set for 5m
cachingKey: 'countries',
}
}).then(function (resp) {
console.log(resp);
}).catch(function (error) {
console.log(error);
});
}
get_WithCacheToSpecifiedTable() {
this.sendRequest({
endpoint: {
url: 'http://192.168.1.184/silex-test-app/web/index.php/countries-data',
exp: 5 * 60 * 1000, // cache set for 5m
cacheTableName: 'countries'
}
}).then(function (resp) {
console.log(resp);
}).catch(function (error) {
console.log(error);
});
}
patch_WithCsrfCheck() {
this.sendRequest({
method: 'PATCH',
endpoint: {
url: 'http://httpbin.org/patch',
},
body: {
id: "14",
firstName: "JaneTEST2"
},
csrfCheck: true
}).then(function (resp) {
console.log(resp);
}).catch(function (error) {
console.log(error);
});
}
patch_WithAdditionalHeaders() {
this.sendRequest({
method: 'PATCH',
endpoint: {
url: 'http://httpbin.org/patch',
},
body: {
id: "14",
firstName: "JaneTEST2"
},
headers: {
'Authorization': 'Bearer lt8fnG9CNmLmsmRX8LTp0pVeJqkccEceXfNM8s_f624'
}
}).then(function (resp) {
console.log(resp);
}).catch(function (error) {
console.log(error);
});
}
post_WithMultipartData() {
this.sendRequest({
method: 'POST',
endpoint: {
url: 'http://192.168.1.184/silex-test-app/web/index.php/handle-post-put-delete-data',
},
body: this._getBodyWithBlobsOrFilesData(),
multiPart: true,
prepareMultipartData: true
}).then(function (resp) {
console.log(resp);
}).catch(function (error) {
console.log(error);
});
}
_setCookie() {
// set cookie
var cookieVal = 'someCookieValue123';
var d = new Date();
d.setTime(d.getTime() + (1 * 60 * 60 * 1000));
var expires = "expires=" + d.toUTCString(); // cookie will expire in 1 hour
document.cookie = "csrftoken=" + cookieVal + "; " + expires + "; path=/";
}
// just a body object that will be used by EtoolsAjaxRequestMixin to prepare multipart body data of request
// to fit etools app needs, on backend there must be a custom parser for this data
_getBodyWithBlobsOrFilesData() {
return {
id: "13",
firstName: "John",
lastName: "Doe",
testObj: {
id: 1,
name: 'testing'
},
testArr: [
{
id: 2,
name: 'testing 2',
someArray: [1, 3],
dummyData: {
test: [1, 2, 3, function () {
var content = '<a id="id1"><b id="b">hey you 1!</b></a>';
return new Blob([content], {type: "text/xml"});
}()],
dummyDataChild: {
id: 1,
id_2: [
{
file: function () {
var content = '<a id="id2"><b id="b">hey you 2!</b></a>';
return new Blob([content], {type: "text/xml"});
}()
}
],
randomObject: {
partner: 1,
agreement: 2,
assessment: function () {
var content = '<a id="id3"><b id="b">hey you 3!</b></a>';
return new Blob([content], {type: "text/xml"});
}()
}
}
}
},
1, 2, 3, 4, 5,
function () {
var content = '<a id="someId"><b id="b">hey you!</b></a>';
return new Blob([content], {type: "text/xml"});
}(),
],
testArr2: [],
someFile: function () {
var content = '<a id="a"><b id="b">hey!</b></a>';
return new Blob([content], {type: "text/xml"});
}()
};
}
}
customElements.define(DirectAjaxCalls.is, DirectAjaxCalls);
| unicef-polymer/etools-ajax | demo/direct-etools-ajax-requests.js | JavaScript | apache-2.0 | 6,501 |
/**
* Copyright (c) 2014 SQUARESPACE, 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.squarespace.less.parse;
import com.squarespace.less.core.Chars;
import com.squarespace.less.model.Node;
public class VariableCurlyParselet implements Parselet {
@Override
public Node parse(LessStream stm) {
boolean indirect = false;
int pos = 0;
if (stm.peek() != Chars.AT_SIGN) {
return null;
}
pos++;
if (stm.peek(pos) == Chars.AT_SIGN) {
indirect = true;
pos++;
}
if (stm.peek(pos) != Chars.LEFT_CURLY_BRACKET) {
return null;
}
pos++;
Mark mark = stm.mark();
stm.seek(pos);
if (!stm.matchIdentifier()) {
stm.restore(mark);
return null;
}
String token = '@' + stm.token();
if (!stm.seekIf(Chars.RIGHT_CURLY_BRACKET)) {
stm.restore(mark);
return null;
}
return stm.context().nodeBuilder().buildVariable(indirect ? '@' + token : token, true);
}
}
| phensley/less-compiler | less-core/src/main/java/com/squarespace/less/parse/VariableCurlyParselet.java | Java | apache-2.0 | 1,496 |
/* Copyright 2016 Mozilla Foundation
*
* 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 {
animationStarted,
DEFAULT_SCALE,
DEFAULT_SCALE_VALUE,
MAX_SCALE,
MIN_SCALE,
noContextMenuHandler,
} from "./ui_utils.js";
const PAGE_NUMBER_LOADING_INDICATOR = "visiblePageIsLoading";
// Keep the two values below up-to-date with the values in `web/viewer.css`:
const SCALE_SELECT_CONTAINER_WIDTH = 140; // px
const SCALE_SELECT_WIDTH = 162; // px
/**
* @typedef {Object} ToolbarOptions
* @property {HTMLDivElement} container - Container for the secondary toolbar.
* @property {HTMLSpanElement} numPages - Label that contains number of pages.
* @property {HTMLInputElement} pageNumber - Control for display and user input
* of the current page number.
* @property {HTMLSpanElement} scaleSelectContainer - Container where scale
* controls are placed. The width is adjusted on UI initialization.
* @property {HTMLSelectElement} scaleSelect - Scale selection control.
* @property {HTMLOptionElement} customScaleOption - The item used to display
* a non-predefined scale.
* @property {HTMLButtonElement} previous - Button to go to the previous page.
* @property {HTMLButtonElement} next - Button to go to the next page.
* @property {HTMLButtonElement} zoomIn - Button to zoom in the pages.
* @property {HTMLButtonElement} zoomOut - Button to zoom out the pages.
* @property {HTMLButtonElement} viewFind - Button to open find bar.
* @property {HTMLButtonElement} openFile - Button to open a new document.
* @property {HTMLButtonElement} presentationModeButton - Button to switch to
* presentation mode.
* @property {HTMLButtonElement} download - Button to download the document.
* @property {HTMLAElement} viewBookmark - Element to link current url of
* the page view.
*/
class Toolbar {
/**
* @param {ToolbarOptions} options
* @param {EventBus} eventBus
* @param {IL10n} l10n - Localization service.
*/
constructor(options, eventBus, l10n) {
this.toolbar = options.container;
this.eventBus = eventBus;
this.l10n = l10n;
this.buttons = [
{ element: options.previous, eventName: "previouspage" },
{ element: options.next, eventName: "nextpage" },
{ element: options.zoomIn, eventName: "zoomin" },
{ element: options.zoomOut, eventName: "zoomout" },
{ element: options.openFile, eventName: "openfile" },
{ element: options.print, eventName: "print" },
{
element: options.presentationModeButton,
eventName: "presentationmode",
},
{ element: options.download, eventName: "download" },
{ element: options.viewBookmark, eventName: null },
];
this.items = {
numPages: options.numPages,
pageNumber: options.pageNumber,
scaleSelectContainer: options.scaleSelectContainer,
scaleSelect: options.scaleSelect,
customScaleOption: options.customScaleOption,
previous: options.previous,
next: options.next,
zoomIn: options.zoomIn,
zoomOut: options.zoomOut,
};
this._wasLocalized = false;
this.reset();
// Bind the event listeners for click and various other actions.
this._bindListeners();
}
setPageNumber(pageNumber, pageLabel) {
this.pageNumber = pageNumber;
this.pageLabel = pageLabel;
this._updateUIState(false);
}
setPagesCount(pagesCount, hasPageLabels) {
this.pagesCount = pagesCount;
this.hasPageLabels = hasPageLabels;
this._updateUIState(true);
}
setPageScale(pageScaleValue, pageScale) {
this.pageScaleValue = (pageScaleValue || pageScale).toString();
this.pageScale = pageScale;
this._updateUIState(false);
}
reset() {
this.pageNumber = 0;
this.pageLabel = null;
this.hasPageLabels = false;
this.pagesCount = 0;
this.pageScaleValue = DEFAULT_SCALE_VALUE;
this.pageScale = DEFAULT_SCALE;
this._updateUIState(true);
this.updateLoadingIndicatorState();
}
_bindListeners() {
const { pageNumber, scaleSelect } = this.items;
const self = this;
// The buttons within the toolbar.
for (const { element, eventName } of this.buttons) {
element.addEventListener("click", evt => {
if (eventName !== null) {
this.eventBus.dispatch(eventName, { source: this });
}
});
}
// The non-button elements within the toolbar.
pageNumber.addEventListener("click", function () {
this.select();
});
pageNumber.addEventListener("change", function () {
self.eventBus.dispatch("pagenumberchanged", {
source: self,
value: this.value,
});
});
scaleSelect.addEventListener("change", function () {
if (this.value === "custom") {
return;
}
self.eventBus.dispatch("scalechanged", {
source: self,
value: this.value,
});
});
// Suppress context menus for some controls.
scaleSelect.oncontextmenu = noContextMenuHandler;
this.eventBus._on("localized", () => {
this._wasLocalized = true;
this._adjustScaleWidth();
this._updateUIState(true);
});
}
_updateUIState(resetNumPages = false) {
if (!this._wasLocalized) {
// Don't update the UI state until we localize the toolbar.
return;
}
const { pageNumber, pagesCount, pageScaleValue, pageScale, items } = this;
if (resetNumPages) {
if (this.hasPageLabels) {
items.pageNumber.type = "text";
} else {
items.pageNumber.type = "number";
this.l10n.get("of_pages", { pagesCount }).then(msg => {
items.numPages.textContent = msg;
});
}
items.pageNumber.max = pagesCount;
}
if (this.hasPageLabels) {
items.pageNumber.value = this.pageLabel;
this.l10n.get("page_of_pages", { pageNumber, pagesCount }).then(msg => {
items.numPages.textContent = msg;
});
} else {
items.pageNumber.value = pageNumber;
}
items.previous.disabled = pageNumber <= 1;
items.next.disabled = pageNumber >= pagesCount;
items.zoomOut.disabled = pageScale <= MIN_SCALE;
items.zoomIn.disabled = pageScale >= MAX_SCALE;
this.l10n
.get("page_scale_percent", { scale: Math.round(pageScale * 10000) / 100 })
.then(msg => {
let predefinedValueFound = false;
for (const option of items.scaleSelect.options) {
if (option.value !== pageScaleValue) {
option.selected = false;
continue;
}
option.selected = true;
predefinedValueFound = true;
}
if (!predefinedValueFound) {
items.customScaleOption.textContent = msg;
items.customScaleOption.selected = true;
}
});
}
updateLoadingIndicatorState(loading = false) {
const pageNumberInput = this.items.pageNumber;
pageNumberInput.classList.toggle(PAGE_NUMBER_LOADING_INDICATOR, loading);
}
/**
* Increase the width of the zoom dropdown DOM element if, and only if, it's
* too narrow to fit the *longest* of the localized strings.
* @private
*/
async _adjustScaleWidth() {
const { items, l10n } = this;
const predefinedValuesPromise = Promise.all([
l10n.get("page_scale_auto"),
l10n.get("page_scale_actual"),
l10n.get("page_scale_fit"),
l10n.get("page_scale_width"),
]);
// The temporary canvas is used to measure text length in the DOM.
let canvas = document.createElement("canvas");
if (
typeof PDFJSDev === "undefined" ||
PDFJSDev.test("MOZCENTRAL || GENERIC")
) {
canvas.mozOpaque = true;
}
let ctx = canvas.getContext("2d", { alpha: false });
await animationStarted;
const { fontSize, fontFamily } = getComputedStyle(items.scaleSelect);
ctx.font = `${fontSize} ${fontFamily}`;
let maxWidth = 0;
for (const predefinedValue of await predefinedValuesPromise) {
const { width } = ctx.measureText(predefinedValue);
if (width > maxWidth) {
maxWidth = width;
}
}
const overflow = SCALE_SELECT_WIDTH - SCALE_SELECT_CONTAINER_WIDTH;
maxWidth += 2 * overflow;
if (maxWidth > SCALE_SELECT_CONTAINER_WIDTH) {
items.scaleSelect.style.width = `${maxWidth + overflow}px`;
items.scaleSelectContainer.style.width = `${maxWidth}px`;
}
// Zeroing the width and height cause Firefox to release graphics resources
// immediately, which can greatly reduce memory consumption.
canvas.width = 0;
canvas.height = 0;
canvas = ctx = null;
}
}
export { Toolbar };
| nawawi/pdf.js | web/toolbar.js | JavaScript | apache-2.0 | 9,112 |
<?php
if ( isset($CFG->upgrading) && $CFG->upgrading === true ) require_once("upgrading.php");
if ( ! isset($CFG) ) die("Please configure this product using config.php");
if ( ! isset($CFG->staticroot) ) die('$CFG->staticroot not defined in config.php');
if ( ! isset($CFG->timezone) ) die('$CFG->timezone not defined in config.php');
if ( strpos($CFG->dbprefix, ' ') !== false ) die('$CFG->dbprefix cannot have spaces in it');
error_reporting(E_ALL & ~E_NOTICE);
error_reporting(E_ALL );
ini_set('display_errors', 1);
date_default_timezone_set($CFG->timezone);
function htmlspec_utf8($string) {
return htmlspecialchars($string,ENT_QUOTES,$encoding = 'UTF-8');
}
function htmlent_utf8($string) {
return htmlentities($string,ENT_QUOTES,$encoding = 'UTF-8');
}
// Makes sure a string is safe as an href
function safe_href($string) {
return str_replace(array('"', '<'),
array('"',''), $string);
}
// Convienence method to wrap sha256
function lti_sha256($val) {
return hash('sha256', $val);
}
function sessionize($url) {
if ( ini_get('session.use_cookies') != '0' ) return $url;
$parameter = session_name().'='.session_id();
if ( strpos($url, $parameter) !== false ) return $url;
$url = $url . (strpos($url,'?') > 0 ? "&" : "?");
$url = $url . $parameter;
return $url;
}
// No trailer
| csev/mmorps | setup.php | PHP | apache-2.0 | 1,345 |
/**
* Copyright 2005-2014 The Kuali Foundation
*
* Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php
*
* 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.kuali.rice.krad.uif.element;
import com.google.common.collect.Lists;
import org.apache.commons.lang.StringUtils;
import org.kuali.rice.krad.datadictionary.parse.BeanTag;
import org.kuali.rice.krad.datadictionary.parse.BeanTagAttribute;
import org.kuali.rice.krad.datadictionary.parse.BeanTags;
import org.kuali.rice.krad.datadictionary.validator.ValidationTrace;
import org.kuali.rice.krad.datadictionary.validator.Validator;
import org.kuali.rice.krad.uif.component.Component;
import org.kuali.rice.krad.uif.container.Group;
import org.kuali.rice.krad.uif.util.ComponentFactory;
import org.kuali.rice.krad.uif.view.View;
import org.kuali.rice.krad.util.KRADConstants;
import java.util.ArrayList;
import java.util.List;
/**
* Content element that renders a header element and optionally a <code>Group</code> to
* present along with the header text
*
* <p>
* Generally the group is used to display content to the right of the header,
* such as links for the group or other information
* </p>
*
* @author Kuali Rice Team (rice.collab@kuali.org)
*/
@BeanTags({@BeanTag(name = "header-bean", parent = "Uif-HeaderBase"), @BeanTag(name = "headerOne-bean", parent = "Uif-HeaderOne"),
@BeanTag(name = "headerTwo-bean", parent = "Uif-HeaderTwo"),
@BeanTag(name = "headerThree-bean", parent = "Uif-HeaderThree"),
@BeanTag(name = "headerFour-bean", parent = "Uif-HeaderFour"),
@BeanTag(name = "headerFive-bean", parent = "Uif-HeaderFive"),
@BeanTag(name = "headerSix-bean", parent = "Uif-HeaderSix"),
@BeanTag(name = "pageHeader-bean", parent = "Uif-PageHeader"),
@BeanTag(name = "sectionHeader-bean", parent = "Uif-SectionHeader"),
@BeanTag(name = "subSectionHeader-bean", parent = "Uif-SubSectionHeader"),
@BeanTag(name = "subCollectionHeader-bean", parent = "Uif-SubCollectionHeader"),
@BeanTag(name = "editablePageHeader-bean", parent = "Uif-EditablePageHeader"),
@BeanTag(name = "readOnlyPageHeader-bean", parent = "Uif-ReadOnlyPageHeader"),
@BeanTag(name = "imageCaptionHeader-bean", parent = "Uif-ImageCaptionHeader"),
@BeanTag(name = "documentViewHeader-bean", parent = "Uif-DocumentViewHeader"),
@BeanTag(name = "lookupPageHeader-bean", parent = "Uif-LookupPageHeader")})
public class Header extends ContentElementBase {
private static final long serialVersionUID = -6950408292923393244L;
private String headerText;
private String headerLevel;
private String headerTagStyle;
private List<String> headerTagCssClasses;
private Message richHeaderMessage;
private List<Component> inlineComponents;
private Group upperGroup;
private Group rightGroup;
private Group lowerGroup;
public Header() {
super();
headerTagCssClasses = new ArrayList<String>();
}
/**
* Sets up rich message content for the label, if any exists
*
* @see Component#performApplyModel(org.kuali.rice.krad.uif.view.View, Object,
* org.kuali.rice.krad.uif.component.Component)
*/
@Override
public void performApplyModel(View view, Object model, Component parent) {
super.performApplyModel(view, model, parent);
if (richHeaderMessage == null && headerText != null && headerText.contains(
KRADConstants.MessageParsing.LEFT_TOKEN) && headerText.contains(
KRADConstants.MessageParsing.RIGHT_TOKEN)) {
Message message = ComponentFactory.getMessage();
view.assignComponentIds(message);
message.setMessageText(headerText);
message.setInlineComponents(inlineComponents);
message.setGenerateSpan(false);
view.getViewHelperService().performComponentInitialization(view, model, message);
this.setRichHeaderMessage(message);
}
}
/**
* The following finalization is performed:
*
* <ul>
* <li>Set render on header group to false if no items are configured</li>
* </ul>
*
* @see org.kuali.rice.krad.uif.component.ComponentBase#performFinalize(org.kuali.rice.krad.uif.view.View,
* java.lang.Object, org.kuali.rice.krad.uif.component.Component)
*/
@Override
public void performFinalize(View view, Object model, Component parent) {
super.performFinalize(view, model, parent);
// don't render header groups if no items were configured
if ((getUpperGroup() != null) && (getUpperGroup().getItems().isEmpty())) {
getUpperGroup().setRender(false);
}
if ((getRightGroup() != null) && (getRightGroup().getItems().isEmpty())) {
getRightGroup().setRender(false);
}
if ((getLowerGroup() != null) && (getLowerGroup().getItems().isEmpty())) {
getLowerGroup().setRender(false);
}
//add preset styles to header groups
if (getUpperGroup() != null) {
getUpperGroup().addStyleClass("uif-header-upperGroup");
}
if (getRightGroup() != null) {
getRightGroup().addStyleClass("uif-header-rightGroup");
}
if (getLowerGroup() != null) {
getLowerGroup().addStyleClass("uif-header-lowerGroup");
}
}
/**
* @see org.kuali.rice.krad.uif.component.ComponentBase#getComponentsForLifecycle()
*/
@Override
public List<Component> getComponentsForLifecycle() {
List<Component> components = super.getComponentsForLifecycle();
components.add(richHeaderMessage);
components.add(upperGroup);
components.add(rightGroup);
components.add(lowerGroup);
return components;
}
/**
* Text that should be displayed on the header
*
* @return header text
*/
@BeanTagAttribute(name = "headerText")
public String getHeaderText() {
return this.headerText;
}
/**
* Setter for the header text
*
* @param headerText
*/
public void setHeaderText(String headerText) {
this.headerText = headerText;
}
/**
* HTML header level (h1 ... h6) that should be applied to the header text
*
* @return header level
*/
@BeanTagAttribute(name = "headerLevel")
public String getHeaderLevel() {
return this.headerLevel;
}
/**
* Setter for the header level
*
* @param headerLevel
*/
public void setHeaderLevel(String headerLevel) {
this.headerLevel = headerLevel;
}
/**
* Style classes that should be applied to the header text (h tag)
*
* <p>
* Note the style class given here applies to only the header text. The
* style class property inherited from the <code>Component</code> interface
* can be used to set the class for the whole field div (which could
* include a nested <code>Group</code>)
* </p>
*
* @return list of style classes
* @see org.kuali.rice.krad.uif.component.Component#getCssClasses()
*/
@BeanTagAttribute(name = "headerTagCssClasses", type = BeanTagAttribute.AttributeType.LISTVALUE)
public List<String> getHeaderTagCssClasses() {
return this.headerTagCssClasses;
}
/**
* Setter for the list of classes to apply to the header h tag
*
* @param headerTagCssClasses
*/
public void setHeaderTagCssClasses(List<String> headerTagCssClasses) {
this.headerTagCssClasses = headerTagCssClasses;
}
/**
* Builds the HTML class attribute string by combining the headerStyleClasses list
* with a space delimiter
*
* @return class attribute string
*/
public String getHeaderStyleClassesAsString() {
if (headerTagCssClasses != null) {
return StringUtils.join(headerTagCssClasses, " ");
}
return "";
}
/**
* Style that should be applied to the header h tag
*
* <p>
* Note the style given here applies to only the header text. The style
* property inherited from the <code>Component</code> interface can be used
* to set the style for the whole header div (which could include a nested
* <code>Group</code>)
* </p>
*
* @return header style
* @see org.kuali.rice.krad.uif.component.Component#getStyle()
*/
@BeanTagAttribute(name = "headerTagStyle")
public String getHeaderTagStyle() {
return this.headerTagStyle;
}
/**
* Setter for the header h tag style
*
* @param headerTagStyle
*/
public void setHeaderTagStyle(String headerTagStyle) {
this.headerTagStyle = headerTagStyle;
}
/**
* Nested group instance that can be used to render contents above the header text
*
* <p>
* The header group is useful for adding content such as links or actions that is presented with the header
* </p>
*
* @return Group instance
*/
@BeanTagAttribute(name = "upperGroup", type = BeanTagAttribute.AttributeType.SINGLEBEAN)
public Group getUpperGroup() {
return upperGroup;
}
/**
* Setter for the header group instance that is rendered above the header text
*
* @param upperGroup
*/
public void setUpperGroup(Group upperGroup) {
this.upperGroup = upperGroup;
}
/**
* Nested group instance that can be used to render contents to the right of the header text
*
* <p>
* The header group is useful for adding content such as links or actions that is presented with the header
* </p>
*
* @return Group instance
*/
@BeanTagAttribute(name = "rightGroup", type = BeanTagAttribute.AttributeType.SINGLEBEAN)
public Group getRightGroup() {
return rightGroup;
}
/**
* Setter for the header group instance that is rendered to the right of the header text
*
* @param rightGroup
*/
public void setRightGroup(Group rightGroup) {
this.rightGroup = rightGroup;
}
/**
* Nested group instance that can be used to render contents below the header text
*
* <p>
* The header group is useful for adding content such as links or actions that is presented with the header
* </p>
*
* @return Group instance
*/
@BeanTagAttribute(name = "lowerGroup", type = BeanTagAttribute.AttributeType.SINGLEBEAN)
public Group getLowerGroup() {
return lowerGroup;
}
/**
* Setter for the header group instance that is rendered below the header text
*
* @param lowerGroup
*/
public void setLowerGroup(Group lowerGroup) {
this.lowerGroup = lowerGroup;
}
/**
* List of <code>Component</code> instances contained in the lower header group
*
* <p>
* Convenience method for configuration to get the items List from the
* lower header group
* </p>
*
* @return List<? extends Component> items
*/
@BeanTagAttribute(name = "items", type = BeanTagAttribute.AttributeType.LISTBEAN)
public List<? extends Component> getItems() {
if (lowerGroup != null) {
return lowerGroup.getItems();
}
return null;
}
/**
* Setter for the lower group's items
*
* <p>
* Convenience method for configuration to set the items List for the
* lower header group
* </p>
*
* @param items
*/
public void setItems(List<? extends Component> items) {
if (lowerGroup != null) {
lowerGroup.setItems(items);
}
}
/**
* Gets the Message that represents the rich message content of the header if headerText is using rich message
* tags.
* <b>DO NOT set this
* property directly unless you need full control over the message structure.</b>
*
* @return rich message structure, null if no rich message structure
*/
@BeanTagAttribute(name = "richHeaderMessage", type = BeanTagAttribute.AttributeType.SINGLEBEAN)
public Message getRichHeaderMessage() {
return richHeaderMessage;
}
/**
* Sets the Message that represents the rich message content of the header if headerText is using rich message
* tags.
* <b>DO
* NOT set this
* property directly unless you need full control over the message structure.</b>
*
* @param richHeaderMessage
*/
public void setRichHeaderMessage(Message richHeaderMessage) {
this.richHeaderMessage = richHeaderMessage;
}
/**
* Gets the inlineComponents used by index in a Header that has rich message component index tags in its headerText
*
* @return the Label's inlineComponents
*/
@BeanTagAttribute(name = "inlineComponents", type = BeanTagAttribute.AttributeType.LISTBEAN)
public List<Component> getInlineComponents() {
return inlineComponents;
}
/**
* Sets the inlineComponents used by index in a Header that has rich message component index tags in its headerText
*
* @param inlineComponents
*/
public void setInlineComponents(List<Component> inlineComponents) {
this.inlineComponents = inlineComponents;
}
/**
* @see org.kuali.rice.krad.uif.component.Component#completeValidation
*/
@Override
public void completeValidation(ValidationTrace tracer) {
tracer.addBean(this);
// Checks that a correct header level is set
String headerLevel = getHeaderLevel().toUpperCase();
boolean correctHeaderLevel = false;
if (headerLevel.compareTo("H1") == 0) {
correctHeaderLevel = true;
} else if (headerLevel.compareTo("H2") == 0) {
correctHeaderLevel = true;
} else if (headerLevel.compareTo("H3") == 0) {
correctHeaderLevel = true;
} else if (headerLevel.compareTo("H4") == 0) {
correctHeaderLevel = true;
} else if (headerLevel.compareTo("H5") == 0) {
correctHeaderLevel = true;
} else if (headerLevel.compareTo("H6") == 0) {
correctHeaderLevel = true;
} else if (headerLevel.compareTo("LABEL") == 0) {
correctHeaderLevel = true;
}
if (!correctHeaderLevel) {
String currentValues[] = {"headerLevel =" + getHeaderLevel()};
tracer.createError("HeaderLevel must be of values h1, h2, h3, h4, h5, h6, or label", currentValues);
}
// Checks that header text is set
if (getHeaderText() == null) {
if (!Validator.checkExpressions(this, "headerText")) {
String currentValues[] = {"headertText =" + getHeaderText()};
tracer.createWarning("HeaderText should be set", currentValues);
}
}
super.completeValidation(tracer.getCopy());
}
/**
* @see org.kuali.rice.krad.uif.component.ComponentBase#copy()
*/
@Override
protected <T> void copyProperties(T component) {
super.copyProperties(component);
Header headerCopy = (Header) component;
headerCopy.setHeaderLevel(this.headerLevel);
if (this.headerTagCssClasses != null) {
headerCopy.setHeaderTagCssClasses(new ArrayList<String>(this.headerTagCssClasses));
}
headerCopy.setHeaderTagStyle(this.headerTagStyle);
headerCopy.setHeaderText(this.headerText);
if(inlineComponents != null) {
List<Component> inlineComponents = Lists.newArrayListWithExpectedSize(this.inlineComponents.size());
for (Component inlineComponent : this.inlineComponents) {
inlineComponents.add((Component)inlineComponent.copy());
}
headerCopy.setInlineComponents(inlineComponents);
}
if (this.lowerGroup != null) {
headerCopy.setLowerGroup((Group)this.lowerGroup.copy());
}
if (this.rightGroup != null) {
headerCopy.setRightGroup((Group)this.rightGroup.copy());
}
if (this.upperGroup != null) {
headerCopy.setUpperGroup((Group)this.upperGroup.copy());
}
if (this.richHeaderMessage != null) {
headerCopy.setRichHeaderMessage((Message)this.richHeaderMessage.copy());
}
}
}
| ua-eas/ksd-kc5.2.1-rice2.3.6-ua | rice-framework/krad-web-framework/src/main/java/org/kuali/rice/krad/uif/element/Header.java | Java | apache-2.0 | 17,458 |
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch 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.elasticsearch.snapshots;
import org.elasticsearch.ElasticsearchCorruptionException;
import org.elasticsearch.ElasticsearchParseException;
import org.elasticsearch.common.blobstore.BlobContainer;
import org.elasticsearch.common.blobstore.BlobMetadata;
import org.elasticsearch.common.blobstore.BlobPath;
import org.elasticsearch.common.blobstore.BlobStore;
import org.elasticsearch.common.blobstore.fs.FsBlobStore;
import org.elasticsearch.common.bytes.BytesArray;
import org.elasticsearch.common.io.Streams;
import org.elasticsearch.common.io.stream.BytesStreamOutput;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.ToXContentFragment;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.index.translog.BufferedChecksumStreamOutput;
import org.elasticsearch.repositories.blobstore.BlobStoreTestUtil;
import org.elasticsearch.repositories.blobstore.ChecksumBlobStoreFormat;
import org.elasticsearch.snapshots.mockstore.BlobContainerWrapper;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.greaterThan;
public class BlobStoreFormatIT extends AbstractSnapshotIntegTestCase {
public static final String BLOB_CODEC = "blob";
private static class BlobObj implements ToXContentFragment {
private final String text;
BlobObj(String text) {
this.text = text;
}
public String getText() {
return text;
}
public static BlobObj fromXContent(XContentParser parser) throws IOException {
String text = null;
XContentParser.Token token = parser.currentToken();
if (token == null) {
token = parser.nextToken();
}
if (token == XContentParser.Token.START_OBJECT) {
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token != XContentParser.Token.FIELD_NAME) {
throw new ElasticsearchParseException("unexpected token [{}]", token);
}
String currentFieldName = parser.currentName();
token = parser.nextToken();
if (token.isValue()) {
if ("text" .equals(currentFieldName)) {
text = parser.text();
} else {
throw new ElasticsearchParseException("unexpected field [{}]", currentFieldName);
}
} else {
throw new ElasticsearchParseException("unexpected token [{}]", token);
}
}
}
if (text == null) {
throw new ElasticsearchParseException("missing mandatory parameter text");
}
return new BlobObj(text);
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, ToXContent.Params params) throws IOException {
builder.field("text", getText());
return builder;
}
}
public void testBlobStoreOperations() throws IOException {
BlobStore blobStore = createTestBlobStore();
BlobContainer blobContainer = blobStore.blobContainer(BlobPath.cleanPath());
ChecksumBlobStoreFormat<BlobObj> checksumSMILE = new ChecksumBlobStoreFormat<>(BLOB_CODEC, "%s", BlobObj::fromXContent,
xContentRegistry(), false);
ChecksumBlobStoreFormat<BlobObj> checksumSMILECompressed = new ChecksumBlobStoreFormat<>(BLOB_CODEC, "%s", BlobObj::fromXContent,
xContentRegistry(), true);
// Write blobs in different formats
checksumSMILE.write(new BlobObj("checksum smile"), blobContainer, "check-smile", true);
checksumSMILECompressed.write(new BlobObj("checksum smile compressed"), blobContainer, "check-smile-comp", true);
// Assert that all checksum blobs can be read by all formats
assertEquals(checksumSMILE.read(blobContainer, "check-smile").getText(), "checksum smile");
assertEquals(checksumSMILE.read(blobContainer, "check-smile-comp").getText(), "checksum smile compressed");
}
public void testCompressionIsApplied() throws IOException {
BlobStore blobStore = createTestBlobStore();
BlobContainer blobContainer = blobStore.blobContainer(BlobPath.cleanPath());
StringBuilder veryRedundantText = new StringBuilder();
for (int i = 0; i < randomIntBetween(100, 300); i++) {
veryRedundantText.append("Blah ");
}
ChecksumBlobStoreFormat<BlobObj> checksumFormat = new ChecksumBlobStoreFormat<>(BLOB_CODEC, "%s", BlobObj::fromXContent,
xContentRegistry(), false);
ChecksumBlobStoreFormat<BlobObj> checksumFormatComp = new ChecksumBlobStoreFormat<>(BLOB_CODEC, "%s", BlobObj::fromXContent,
xContentRegistry(), true);
BlobObj blobObj = new BlobObj(veryRedundantText.toString());
checksumFormatComp.write(blobObj, blobContainer, "blob-comp", true);
checksumFormat.write(blobObj, blobContainer, "blob-not-comp", true);
Map<String, BlobMetadata> blobs = blobContainer.listBlobsByPrefix("blob-");
assertEquals(blobs.size(), 2);
assertThat(blobs.get("blob-not-comp").length(), greaterThan(blobs.get("blob-comp").length()));
}
public void testBlobCorruption() throws IOException {
BlobStore blobStore = createTestBlobStore();
BlobContainer blobContainer = blobStore.blobContainer(BlobPath.cleanPath());
String testString = randomAlphaOfLength(randomInt(10000));
BlobObj blobObj = new BlobObj(testString);
ChecksumBlobStoreFormat<BlobObj> checksumFormat = new ChecksumBlobStoreFormat<>(BLOB_CODEC, "%s", BlobObj::fromXContent,
xContentRegistry(), randomBoolean());
checksumFormat.write(blobObj, blobContainer, "test-path", true);
assertEquals(checksumFormat.read(blobContainer, "test-path").getText(), testString);
randomCorruption(blobContainer, "test-path");
try {
checksumFormat.read(blobContainer, "test-path");
fail("Should have failed due to corruption");
} catch (ElasticsearchCorruptionException ex) {
assertThat(ex.getMessage(), containsString("test-path"));
} catch (EOFException ex) {
// This can happen if corrupt the byte length
}
}
public void testAtomicWrite() throws Exception {
final BlobStore blobStore = createTestBlobStore();
final BlobContainer blobContainer = blobStore.blobContainer(BlobPath.cleanPath());
String testString = randomAlphaOfLength(randomInt(10000));
final CountDownLatch block = new CountDownLatch(1);
final CountDownLatch unblock = new CountDownLatch(1);
final BlobObj blobObj = new BlobObj(testString) {
@Override
public XContentBuilder toXContent(XContentBuilder builder, ToXContent.Params params) throws IOException {
super.toXContent(builder, params);
// Block before finishing writing
try {
block.countDown();
unblock.await(5, TimeUnit.SECONDS);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
return builder;
}
};
final ChecksumBlobStoreFormat<BlobObj> checksumFormat = new ChecksumBlobStoreFormat<>(BLOB_CODEC, "%s", BlobObj::fromXContent,
xContentRegistry(), randomBoolean());
ExecutorService threadPool = Executors.newFixedThreadPool(1);
try {
Future<Void> future = threadPool.submit(new Callable<Void>() {
@Override
public Void call() throws Exception {
checksumFormat.writeAtomic(blobObj, blobContainer, "test-blob");
return null;
}
});
// signalling
block.await(5, TimeUnit.SECONDS);
assertFalse(BlobStoreTestUtil.blobExists(blobContainer, "test-blob"));
unblock.countDown();
future.get();
assertTrue(BlobStoreTestUtil.blobExists(blobContainer, "test-blob"));
} finally {
threadPool.shutdown();
}
}
public void testAtomicWriteFailures() throws Exception {
final String name = randomAlphaOfLength(10);
final BlobObj blobObj = new BlobObj("test");
final ChecksumBlobStoreFormat<BlobObj> checksumFormat = new ChecksumBlobStoreFormat<>(BLOB_CODEC, "%s", BlobObj::fromXContent,
xContentRegistry(), randomBoolean());
final BlobStore blobStore = createTestBlobStore();
final BlobContainer blobContainer = blobStore.blobContainer(BlobPath.cleanPath());
{
IOException writeBlobException = expectThrows(IOException.class, () -> {
BlobContainer wrapper = new BlobContainerWrapper(blobContainer) {
@Override
public void writeBlobAtomic(String blobName, InputStream inputStream, long blobSize, boolean failIfAlreadyExists)
throws IOException {
throw new IOException("Exception thrown in writeBlobAtomic() for " + blobName);
}
};
checksumFormat.writeAtomic(blobObj, wrapper, name);
});
assertEquals("Exception thrown in writeBlobAtomic() for " + name, writeBlobException.getMessage());
assertEquals(0, writeBlobException.getSuppressed().length);
}
}
protected BlobStore createTestBlobStore() throws IOException {
return new FsBlobStore(Settings.EMPTY, randomRepoPath());
}
protected void randomCorruption(BlobContainer blobContainer, String blobName) throws IOException {
byte[] buffer = new byte[(int) blobContainer.listBlobsByPrefix(blobName).get(blobName).length()];
long originalChecksum = checksum(buffer);
try (InputStream inputStream = blobContainer.readBlob(blobName)) {
Streams.readFully(inputStream, buffer);
}
do {
int location = randomIntBetween(0, buffer.length - 1);
buffer[location] = (byte) (buffer[location] ^ 42);
} while (originalChecksum == checksum(buffer));
BytesArray bytesArray = new BytesArray(buffer);
try (StreamInput stream = bytesArray.streamInput()) {
blobContainer.writeBlob(blobName, stream, bytesArray.length(), false);
}
}
private long checksum(byte[] buffer) throws IOException {
try (BytesStreamOutput streamOutput = new BytesStreamOutput()) {
try (BufferedChecksumStreamOutput checksumOutput = new BufferedChecksumStreamOutput(streamOutput)) {
checksumOutput.write(buffer);
return checksumOutput.getChecksum();
}
}
}
}
| crate/crate | server/src/test/java/org/elasticsearch/snapshots/BlobStoreFormatIT.java | Java | apache-2.0 | 12,956 |
/**
* Copyright (C) 2016 - 2030 youtongluan.
*
* 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.yx.db.mapper;
import java.io.InputStream;
import java.io.StringReader;
import java.nio.charset.StandardCharsets;
import java.util.function.Supplier;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.xml.sax.InputSource;
import org.yx.exception.SumkException;
import org.yx.log.Logs;
import org.yx.util.IOUtil;
public class SqlXmlBuilderFactory implements Supplier<DocumentBuilder> {
protected final DocumentBuilderFactory dbf;
protected String sumkDTD;
public SqlXmlBuilderFactory() {
dbf = DocumentBuilderFactory.newInstance();
dbf.setIgnoringComments(true);
dbf.setIgnoringElementContentWhitespace(true);
dbf.setExpandEntityReferences(false);
dbf.setCoalescing(true);
}
private DocumentBuilder create() throws Exception {
DocumentBuilder dbd = dbf.newDocumentBuilder();
dbd.setEntityResolver((publicId, systemId) -> {
if (systemId == null) {
return null;
}
String dtd = this.sumkDTD;
if (dtd == null) {
InputStream in = SqlXmlParser.class.getClassLoader().getResourceAsStream("META-INF/sql.dtd");
if (in == null) {
return null;
}
byte[] bs = IOUtil.readAllBytes(in, true);
if (bs == null || bs.length == 0) {
return null;
}
dtd = new String(bs, StandardCharsets.UTF_8);
this.sumkDTD = dtd;
}
InputSource source = new InputSource(systemId);
source.setCharacterStream(new StringReader(dtd));
source.setEncoding("UTF-8");
return source;
});
return dbd;
}
@Override
public DocumentBuilder get() {
try {
return this.create();
} catch (Exception e) {
Logs.db().error(e.toString(), e);
throw new SumkException(-7623435, "创建XmlDocumentBuilder失败");
}
}
public DocumentBuilderFactory getDocumentBuilderFactory() {
return dbf;
}
}
| youtongluan/sumk | src/main/java/org/yx/db/mapper/SqlXmlBuilderFactory.java | Java | apache-2.0 | 2,429 |
package rds
//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 Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
// ItemsInDescribeInstanceAutoRenewalAttribute is a nested struct in rds response
type ItemsInDescribeInstanceAutoRenewalAttribute struct {
Item []Item `json:"Item" xml:"Item"`
}
| xiaozhu36/terraform-provider | vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/rds/struct_items_in_describe_instance_auto_renewal_attribute.go | GO | apache-2.0 | 879 |
/*
* Copyright 2013-2016 consulo.io
*
* 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 consulo.packaging.impl.artifacts;
import com.intellij.icons.AllIcons;
import com.intellij.packaging.artifacts.ArtifactType;
import com.intellij.packaging.elements.CompositePackagingElement;
import com.intellij.packaging.elements.PackagingElementFactory;
import com.intellij.packaging.elements.PackagingElementOutputKind;
import com.intellij.packaging.impl.artifacts.ArtifactUtil;
import consulo.packaging.impl.elements.ZipArchivePackagingElement;
import consulo.ui.image.Image;
import javax.annotation.Nonnull;
/**
* @author VISTALL
* @since 15:59/18.06.13
*/
public class ZipArtifactType extends ArtifactType {
public ZipArtifactType() {
super("zip", "Zip");
}
@Nonnull
@Override
public Image getIcon() {
return AllIcons.Nodes.Artifact;
}
@Override
public String getDefaultPathFor(@Nonnull PackagingElementOutputKind kind) {
return "/";
}
@Nonnull
@Override
public CompositePackagingElement<?> createRootElement(@Nonnull PackagingElementFactory packagingElementFactory, @Nonnull String artifactName) {
return new ZipArchivePackagingElement(ArtifactUtil.suggestArtifactFileName(artifactName) + ".zip");
}
}
| consulo/consulo | modules/base/compiler-impl/src/main/java/consulo/packaging/impl/artifacts/ZipArtifactType.java | Java | apache-2.0 | 1,761 |
package thappstudios.android.miniapps.util;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import thappstudios.android.miniapps.apps.Browser;
public class BrowserViewClient extends WebViewClient {
private Browser mBrowser;
public BrowserViewClient(Browser browser) {
// TODO Auto-generated constructor stub
mBrowser=browser;
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
@Override
public void onPageFinished(WebView view, String url) {
// TODO Auto-generated method stub
super.onPageFinished(view, url);
mBrowser.setTextUrl(url);
}
} | yannick189/Mini-Apps | src/thappstudios/android/miniapps/util/BrowserViewClient.java | Java | apache-2.0 | 682 |
/* Copyright (C) 2013-2020 TU Dortmund
* This file is part of AutomataLib, http://www.automatalib.net/.
*
* 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 net.automatalib.util.minimizer;
import net.automatalib.automata.vpda.DefaultOneSEVPA;
import net.automatalib.automata.vpda.Location;
import net.automatalib.automata.vpda.OneSEVPA;
import net.automatalib.util.partitionrefinement.Block;
import net.automatalib.util.partitionrefinement.PaigeTarjan;
import net.automatalib.util.partitionrefinement.PaigeTarjanInitializers;
import net.automatalib.words.VPDAlphabet;
import org.checkerframework.checker.nullness.qual.NonNull;
/**
* A Paige/Tarjan partition refinement based minimizer for {@link OneSEVPA}s.
*
* @author Malte Isberner
*/
public final class OneSEVPAMinimizer {
private OneSEVPAMinimizer() {}
public static <I> DefaultOneSEVPA<I> minimize(final OneSEVPA<?, I> sevpa, final VPDAlphabet<I> alphabet) {
final PaigeTarjan pt = new PaigeTarjan();
initPaigeTarjan(pt, sevpa, alphabet);
pt.initWorklist(false);
pt.computeCoarsestStablePartition();
return fromPaigeTarjan(pt, sevpa, alphabet);
}
private static <L, I> void initPaigeTarjan(PaigeTarjan pt, OneSEVPA<L, I> sevpa, VPDAlphabet<I> alphabet) {
final int numStates = sevpa.size();
final int numInputs =
alphabet.getNumInternals() + alphabet.getNumCalls() * alphabet.getNumReturns() * sevpa.size() * 2;
final int posDataLow = numStates;
final int predOfsDataLow = posDataLow + numStates;
final int numTransitions = numStates * numInputs;
final int predDataLow = predOfsDataLow + numTransitions + 1;
final int dataSize = predDataLow + numTransitions;
final int[] data = new int[dataSize];
final Block[] blockForState = new Block[numStates];
final Block[] initBlocks = new Block[2];
for (int i = 0; i < numStates; i++) {
final L loc = sevpa.getLocation(i);
final int initBlockIdx = sevpa.isAcceptingLocation(loc) ? 1 : 0;
Block block = initBlocks[initBlockIdx];
if (block == null) {
block = pt.createBlock();
block.high = 0;
initBlocks[initBlockIdx] = block;
}
block.high++;
blockForState[i] = block;
int predCountBase = predOfsDataLow;
for (I intSym : alphabet.getInternalAlphabet()) {
final L succ = sevpa.getInternalSuccessor(loc, intSym);
if (succ == null) {
throw new IllegalArgumentException("Partial OneSEVPAs are not supported");
}
final int succId = sevpa.getLocationId(succ);
data[predCountBase + succId]++;
predCountBase += numStates;
}
for (I callSym : alphabet.getCallAlphabet()) {
for (I retSym : alphabet.getReturnAlphabet()) {
for (L src : sevpa.getLocations()) {
int stackSym = sevpa.encodeStackSym(src, callSym);
L succ = sevpa.getReturnSuccessor(loc, retSym, stackSym);
if (succ == null) {
throw new IllegalArgumentException("Partial OneSEVPAs are not supported");
}
int succId = sevpa.getLocationId(succ);
data[predCountBase + succId]++;
predCountBase += numStates;
stackSym = sevpa.encodeStackSym(loc, callSym);
succ = sevpa.getReturnSuccessor(src, retSym, stackSym);
if (succ == null) {
throw new IllegalArgumentException("Partial OneSEVPAs are not supported");
}
succId = sevpa.getLocationId(succ);
data[predCountBase + succId]++;
predCountBase += numStates;
}
}
}
}
int curr = 0;
for (Block b : pt.blockList()) {
curr += b.high;
b.high = curr;
b.low = curr;
}
data[predOfsDataLow] += predDataLow;
PaigeTarjanInitializers.prefixSum(data, predOfsDataLow, predDataLow);
for (int i = 0; i < numStates; i++) {
final Block b = blockForState[i];
final int pos = --b.low;
data[pos] = i;
data[posDataLow + i] = pos;
int predOfsBase = predOfsDataLow;
final L loc = sevpa.getLocation(i);
for (I intSym : alphabet.getInternalAlphabet()) {
final L succ = sevpa.getInternalSuccessor(loc, intSym);
if (succ == null) {
throw new IllegalArgumentException("Partial OneSEVPAs are not supported");
}
final int succId = sevpa.getLocationId(succ);
data[--data[predOfsBase + succId]] = i;
predOfsBase += numStates;
}
for (I callSym : alphabet.getCallAlphabet()) {
for (I retSym : alphabet.getReturnAlphabet()) {
for (L src : sevpa.getLocations()) {
int stackSym = sevpa.encodeStackSym(src, callSym);
L succ = sevpa.getReturnSuccessor(loc, retSym, stackSym);
if (succ == null) {
throw new IllegalArgumentException("Partial OneSEVPAs are not supported");
}
int succId = sevpa.getLocationId(succ);
data[--data[predOfsBase + succId]] = i;
predOfsBase += numStates;
stackSym = sevpa.encodeStackSym(loc, callSym);
succ = sevpa.getReturnSuccessor(src, retSym, stackSym);
if (succ == null) {
throw new IllegalArgumentException("Partial OneSEVPAs are not supported");
}
succId = sevpa.getLocationId(succ);
data[--data[predOfsBase + succId]] = i;
predOfsBase += numStates;
}
}
}
}
pt.setBlockData(data);
pt.setPosData(data, posDataLow);
pt.setPredOfsData(data, predOfsDataLow);
pt.setPredData(data);
pt.setBlockForState(blockForState);
pt.setSize(numStates, numInputs);
}
private static <L, I> DefaultOneSEVPA<I> fromPaigeTarjan(final PaigeTarjan pt,
final OneSEVPA<L, I> original,
final VPDAlphabet<I> alphabet) {
final int numBlocks = pt.getNumBlocks();
final DefaultOneSEVPA<I> result = new DefaultOneSEVPA<>(alphabet, numBlocks);
final Location[] resultLocs = new Location[numBlocks];
for (int i = 0; i < resultLocs.length; i++) {
resultLocs[i] = result.addLocation(false);
}
for (Block curr : pt.blockList()) {
final int blockId = curr.id;
final int rep = pt.getRepresentative(curr);
final L repLoc = original.getLocation(rep);
final Location resultLoc = resultLocs[blockId];
resultLoc.setAccepting(original.isAcceptingLocation(repLoc));
for (I intSym : alphabet.getInternalAlphabet()) {
@SuppressWarnings("nullness") // partiality is handled during initialization
final @NonNull L origSucc = original.getInternalSuccessor(repLoc, intSym);
final int origSuccId = original.getLocationId(origSucc);
final int resSuccId = pt.getBlockForState(origSuccId).id;
final Location resSucc = resultLocs[resSuccId];
result.setInternalSuccessor(resultLoc, intSym, resSucc);
}
for (I callSym : alphabet.getCallAlphabet()) {
for (I retSym : alphabet.getReturnAlphabet()) {
for (Block b : pt.blockList()) {
final int stackRepId = pt.getRepresentative(b);
final L stackRep = original.getLocation(stackRepId);
final Location resultStackRep = resultLocs[b.id];
final int origStackSym = original.encodeStackSym(stackRep, callSym);
@SuppressWarnings("nullness") // partiality is handled during initialization
final @NonNull L origSucc = original.getReturnSuccessor(repLoc, retSym, origStackSym);
final int origSuccId = original.getLocationId(origSucc);
final int resSuccId = pt.getBlockForState(origSuccId).id;
final Location resSucc = resultLocs[resSuccId];
final int stackSym = result.encodeStackSym(resultStackRep, callSym);
result.setReturnSuccessor(resultLoc, retSym, stackSym, resSucc);
}
}
}
}
final int origInit = original.getLocationId(original.getInitialLocation());
result.setInitialLocation(resultLocs[pt.getBlockForState(origInit).id]);
return result;
}
}
| misberner/automatalib | util/src/main/java/net/automatalib/util/minimizer/OneSEVPAMinimizer.java | Java | apache-2.0 | 10,006 |
package com.porterhead.oauth2.postgres;
/**
* Created by ctg on 12/1/15.
*/
public class PostgresRepositoryTokenStore {
}
| chithanh12/oauth2 | src/main/java/com/porterhead/oauth2/postgres/PostgresRepositoryTokenStore.java | Java | apache-2.0 | 125 |
package com.github.kubatatami.richedittext.styles.binary;
import android.annotation.SuppressLint;
import android.graphics.Typeface;
import org.xml.sax.Attributes;
import java.util.Map;
public class BoldSpanController extends FontStyleSpanController {
public BoldSpanController() {
super(Typeface.BOLD, "b", "font-weight", "bold");
}
@Override
public RichStyleSpan createSpanFromTag(String tag, Map<String, String> styleMap, Attributes attributes) {
if (tag.equals("b") || tag.equals("strong") ||
(tag.equals("span") && "bold".equals(styleMap.get("font-weight")))) {
return new RichStyleSpan(typeface);
}
return null;
}
@Override
RichStyleSpan createSpan() {
return new RichBoldSpan();
}
public Class<?> spanFromEndTag(String tag) {
if (tag.equals("b") || tag.equals("strong") || tag.equals("span")) {
return clazz;
}
return null;
}
@SuppressLint("ParcelCreator")
public static class RichBoldSpan extends RichStyleSpan {
public RichBoldSpan() {
super(Typeface.BOLD);
}
}
}
| kubatatami/RichEditText | lib/src/main/java/com/github/kubatatami/richedittext/styles/binary/BoldSpanController.java | Java | apache-2.0 | 1,167 |
using System;
namespace Merlion.Utils
{
public static class HexEncoder
{
static int DigitFromHex(char c)
{
if (c >= '0' && c <= '9')
return c - '0';
if (c >= 'a' && c <= 'f')
return c - 'a' + 10;
if (c >= 'A' && c <= 'F')
return c - 'A' + 10;
throw new FormatException ("Input string contains an invalid character.");
}
static char DigitToHex(int d)
{
if (d >= 0 && d <= 9)
return (char)('0' + d);
else
return (char)('a' + d);
}
public static byte[] GetBytes(string str)
{
if (str == null)
throw new ArgumentNullException ("str");
if ((str.Length & 1) != 0)
throw new FormatException ("Length must be odd.");
byte[] ret = new byte[str.Length >> 1];
for (int i = 0; i < ret.Length; ++i) {
int d1 = DigitFromHex (str [i * 2]);
int d2 = DigitFromHex (str [i * 2 + 1]);
ret [i] = (byte)((d1 << 4) | d2);
}
return ret;
}
public static string GetString(byte[] data)
{
if (data == null)
throw new ArgumentNullException ("data");
char[] chars = new char[checked(data.Length * 2)];
for (int i = 0; i < data.Length; ++i) {
int b = data [i];
chars [i * 2] = DigitToHex(b >> 4);
chars [i * 2 + 1] = DigitToHex(b & 15);
}
return new string (chars);
}
}
}
| yvt/Merlion | Merlion/Utils/HexEncoder.cs | C# | apache-2.0 | 1,288 |
/* Copyright 2013-2014 Miguel Vicente Linares
*
* 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.miviclin.droidengine2ddemos.input.accelerometer;
import android.app.Activity;
import com.miviclin.droidengine2d.AbstractGame;
import com.miviclin.droidengine2d.graphics.GLView;
public class AccelerometerDemoGame extends AbstractGame {
public AccelerometerDemoGame(GLView glView, Activity activity) {
super(glView, activity);
}
@Override
public void initialize() {
getGameStateManager().registerGameState(0, new AccelerometerDemoGameState(this), true);
}
}
| miviclin/droidengine2d-demos | src/com/miviclin/droidengine2ddemos/input/accelerometer/AccelerometerDemoGame.java | Java | apache-2.0 | 1,102 |
package org.iotp.analytics.ruleengine.core.plugin.telemetry.cmd;
/**
*/
public interface TelemetryPluginCmd {
int getCmdId();
void setCmdId(int cmdId);
String getKeys();
}
| osswangxining/iotplatform | iot-ruleengine/ruleengine-core/src/main/java/org/iotp/analytics/ruleengine/core/plugin/telemetry/cmd/TelemetryPluginCmd.java | Java | apache-2.0 | 184 |
/*
* Copyright 2015 Tom Gibara
*
* 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.tomgibara.bits;
public class BytesBitStoreTest extends BitStoreTest {
@Override
BitStore newStore(int size) {
byte[] bytes = new byte[(size + 7) >> 3];
return Bits.asStore(bytes, 0, size);
}
@Override
BitStore randomStore(int size) {
byte[] bytes = new byte[(size + 7) >> 3];
random.nextBytes(bytes);
return Bits.asStore(bytes, 0, size);
}
}
| tomgibara/bits | src/test/java/com/tomgibara/bits/BytesBitStoreTest.java | Java | apache-2.0 | 970 |
using Talifun.Commander.Command.ConfigurationChecker.Response;
namespace Talifun.Commander.Command.BoxNetUploader.CommandTester.Response
{
public class BoxNetUploaderConfigurationTestResponseMessage : ConfigurationTestResponseMessageBase
{
}
}
| taliesins/talifun-commander | src/Talifun.Commander.Command.BoxNetUploader/CommandTester/Response/BoxNetUploaderConfigurationTestResponseMessage.cs | C# | apache-2.0 | 251 |
/*
* #%L
* GwtMaterial
* %%
* Copyright (C) 2015 - 2017 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.addins.client.iconmorph;
import com.google.gwt.core.client.GWT;
import com.google.gwt.resources.client.ClientBundle;
import com.google.gwt.resources.client.TextResource;
/**
* Client Bundle for Icon Morph component
*
* @author kevzlou7979
*/
interface MaterialIconMorphDebugClientBundle extends ClientBundle {
MaterialIconMorphDebugClientBundle INSTANCE = GWT.create(MaterialIconMorphDebugClientBundle.class);
@Source("resources/css/morph.css")
TextResource morphCssDebug();
}
| GwtMaterialDesign/gwt-material-addins | src/main/java/gwt/material/design/addins/client/iconmorph/MaterialIconMorphDebugClientBundle.java | Java | apache-2.0 | 1,178 |
/*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/domains/v1beta1/domains.proto
package com.google.cloud.domains.v1beta1;
/**
*
*
* <pre>
* Request for the `ConfigureManagementSettings` method.
* </pre>
*
* Protobuf type {@code google.cloud.domains.v1beta1.ConfigureManagementSettingsRequest}
*/
public final class ConfigureManagementSettingsRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.domains.v1beta1.ConfigureManagementSettingsRequest)
ConfigureManagementSettingsRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use ConfigureManagementSettingsRequest.newBuilder() to construct.
private ConfigureManagementSettingsRequest(
com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ConfigureManagementSettingsRequest() {
registration_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ConfigureManagementSettingsRequest();
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet getUnknownFields() {
return this.unknownFields;
}
private ConfigureManagementSettingsRequest(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
java.lang.String s = input.readStringRequireUtf8();
registration_ = s;
break;
}
case 18:
{
com.google.cloud.domains.v1beta1.ManagementSettings.Builder subBuilder = null;
if (managementSettings_ != null) {
subBuilder = managementSettings_.toBuilder();
}
managementSettings_ =
input.readMessage(
com.google.cloud.domains.v1beta1.ManagementSettings.parser(),
extensionRegistry);
if (subBuilder != null) {
subBuilder.mergeFrom(managementSettings_);
managementSettings_ = subBuilder.buildPartial();
}
break;
}
case 26:
{
com.google.protobuf.FieldMask.Builder subBuilder = null;
if (updateMask_ != null) {
subBuilder = updateMask_.toBuilder();
}
updateMask_ =
input.readMessage(com.google.protobuf.FieldMask.parser(), extensionRegistry);
if (subBuilder != null) {
subBuilder.mergeFrom(updateMask_);
updateMask_ = subBuilder.buildPartial();
}
break;
}
default:
{
if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this);
} finally {
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.domains.v1beta1.DomainsProto
.internal_static_google_cloud_domains_v1beta1_ConfigureManagementSettingsRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.domains.v1beta1.DomainsProto
.internal_static_google_cloud_domains_v1beta1_ConfigureManagementSettingsRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.domains.v1beta1.ConfigureManagementSettingsRequest.class,
com.google.cloud.domains.v1beta1.ConfigureManagementSettingsRequest.Builder.class);
}
public static final int REGISTRATION_FIELD_NUMBER = 1;
private volatile java.lang.Object registration_;
/**
*
*
* <pre>
* Required. The name of the `Registration` whose management settings are being updated,
* in the format `projects/*/locations/*/registrations/*`.
* </pre>
*
* <code>
* string registration = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The registration.
*/
@java.lang.Override
public java.lang.String getRegistration() {
java.lang.Object ref = registration_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
registration_ = s;
return s;
}
}
/**
*
*
* <pre>
* Required. The name of the `Registration` whose management settings are being updated,
* in the format `projects/*/locations/*/registrations/*`.
* </pre>
*
* <code>
* string registration = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for registration.
*/
@java.lang.Override
public com.google.protobuf.ByteString getRegistrationBytes() {
java.lang.Object ref = registration_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
registration_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int MANAGEMENT_SETTINGS_FIELD_NUMBER = 2;
private com.google.cloud.domains.v1beta1.ManagementSettings managementSettings_;
/**
*
*
* <pre>
* Fields of the `ManagementSettings` to update.
* </pre>
*
* <code>.google.cloud.domains.v1beta1.ManagementSettings management_settings = 2;</code>
*
* @return Whether the managementSettings field is set.
*/
@java.lang.Override
public boolean hasManagementSettings() {
return managementSettings_ != null;
}
/**
*
*
* <pre>
* Fields of the `ManagementSettings` to update.
* </pre>
*
* <code>.google.cloud.domains.v1beta1.ManagementSettings management_settings = 2;</code>
*
* @return The managementSettings.
*/
@java.lang.Override
public com.google.cloud.domains.v1beta1.ManagementSettings getManagementSettings() {
return managementSettings_ == null
? com.google.cloud.domains.v1beta1.ManagementSettings.getDefaultInstance()
: managementSettings_;
}
/**
*
*
* <pre>
* Fields of the `ManagementSettings` to update.
* </pre>
*
* <code>.google.cloud.domains.v1beta1.ManagementSettings management_settings = 2;</code>
*/
@java.lang.Override
public com.google.cloud.domains.v1beta1.ManagementSettingsOrBuilder
getManagementSettingsOrBuilder() {
return getManagementSettings();
}
public static final int UPDATE_MASK_FIELD_NUMBER = 3;
private com.google.protobuf.FieldMask updateMask_;
/**
*
*
* <pre>
* Required. The field mask describing which fields to update as a comma-separated list.
* For example, if only the transfer lock is being updated, the `update_mask`
* is `"transfer_lock_state"`.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the updateMask field is set.
*/
@java.lang.Override
public boolean hasUpdateMask() {
return updateMask_ != null;
}
/**
*
*
* <pre>
* Required. The field mask describing which fields to update as a comma-separated list.
* For example, if only the transfer lock is being updated, the `update_mask`
* is `"transfer_lock_state"`.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The updateMask.
*/
@java.lang.Override
public com.google.protobuf.FieldMask getUpdateMask() {
return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_;
}
/**
*
*
* <pre>
* Required. The field mask describing which fields to update as a comma-separated list.
* For example, if only the transfer lock is being updated, the `update_mask`
* is `"transfer_lock_state"`.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
@java.lang.Override
public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() {
return getUpdateMask();
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(registration_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, registration_);
}
if (managementSettings_ != null) {
output.writeMessage(2, getManagementSettings());
}
if (updateMask_ != null) {
output.writeMessage(3, getUpdateMask());
}
unknownFields.writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(registration_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, registration_);
}
if (managementSettings_ != null) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(2, getManagementSettings());
}
if (updateMask_ != null) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(3, getUpdateMask());
}
size += unknownFields.getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.domains.v1beta1.ConfigureManagementSettingsRequest)) {
return super.equals(obj);
}
com.google.cloud.domains.v1beta1.ConfigureManagementSettingsRequest other =
(com.google.cloud.domains.v1beta1.ConfigureManagementSettingsRequest) obj;
if (!getRegistration().equals(other.getRegistration())) return false;
if (hasManagementSettings() != other.hasManagementSettings()) return false;
if (hasManagementSettings()) {
if (!getManagementSettings().equals(other.getManagementSettings())) return false;
}
if (hasUpdateMask() != other.hasUpdateMask()) return false;
if (hasUpdateMask()) {
if (!getUpdateMask().equals(other.getUpdateMask())) return false;
}
if (!unknownFields.equals(other.unknownFields)) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + REGISTRATION_FIELD_NUMBER;
hash = (53 * hash) + getRegistration().hashCode();
if (hasManagementSettings()) {
hash = (37 * hash) + MANAGEMENT_SETTINGS_FIELD_NUMBER;
hash = (53 * hash) + getManagementSettings().hashCode();
}
if (hasUpdateMask()) {
hash = (37 * hash) + UPDATE_MASK_FIELD_NUMBER;
hash = (53 * hash) + getUpdateMask().hashCode();
}
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.domains.v1beta1.ConfigureManagementSettingsRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.domains.v1beta1.ConfigureManagementSettingsRequest parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.domains.v1beta1.ConfigureManagementSettingsRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.domains.v1beta1.ConfigureManagementSettingsRequest parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.domains.v1beta1.ConfigureManagementSettingsRequest parseFrom(
byte[] data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.domains.v1beta1.ConfigureManagementSettingsRequest parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.domains.v1beta1.ConfigureManagementSettingsRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.domains.v1beta1.ConfigureManagementSettingsRequest parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.domains.v1beta1.ConfigureManagementSettingsRequest
parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.domains.v1beta1.ConfigureManagementSettingsRequest
parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.domains.v1beta1.ConfigureManagementSettingsRequest parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.domains.v1beta1.ConfigureManagementSettingsRequest parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(
com.google.cloud.domains.v1beta1.ConfigureManagementSettingsRequest prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* Request for the `ConfigureManagementSettings` method.
* </pre>
*
* Protobuf type {@code google.cloud.domains.v1beta1.ConfigureManagementSettingsRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.domains.v1beta1.ConfigureManagementSettingsRequest)
com.google.cloud.domains.v1beta1.ConfigureManagementSettingsRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.domains.v1beta1.DomainsProto
.internal_static_google_cloud_domains_v1beta1_ConfigureManagementSettingsRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.domains.v1beta1.DomainsProto
.internal_static_google_cloud_domains_v1beta1_ConfigureManagementSettingsRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.domains.v1beta1.ConfigureManagementSettingsRequest.class,
com.google.cloud.domains.v1beta1.ConfigureManagementSettingsRequest.Builder.class);
}
// Construct using
// com.google.cloud.domains.v1beta1.ConfigureManagementSettingsRequest.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {}
}
@java.lang.Override
public Builder clear() {
super.clear();
registration_ = "";
if (managementSettingsBuilder_ == null) {
managementSettings_ = null;
} else {
managementSettings_ = null;
managementSettingsBuilder_ = null;
}
if (updateMaskBuilder_ == null) {
updateMask_ = null;
} else {
updateMask_ = null;
updateMaskBuilder_ = null;
}
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.domains.v1beta1.DomainsProto
.internal_static_google_cloud_domains_v1beta1_ConfigureManagementSettingsRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.domains.v1beta1.ConfigureManagementSettingsRequest
getDefaultInstanceForType() {
return com.google.cloud.domains.v1beta1.ConfigureManagementSettingsRequest
.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.domains.v1beta1.ConfigureManagementSettingsRequest build() {
com.google.cloud.domains.v1beta1.ConfigureManagementSettingsRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.domains.v1beta1.ConfigureManagementSettingsRequest buildPartial() {
com.google.cloud.domains.v1beta1.ConfigureManagementSettingsRequest result =
new com.google.cloud.domains.v1beta1.ConfigureManagementSettingsRequest(this);
result.registration_ = registration_;
if (managementSettingsBuilder_ == null) {
result.managementSettings_ = managementSettings_;
} else {
result.managementSettings_ = managementSettingsBuilder_.build();
}
if (updateMaskBuilder_ == null) {
result.updateMask_ = updateMask_;
} else {
result.updateMask_ = updateMaskBuilder_.build();
}
onBuilt();
return result;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.domains.v1beta1.ConfigureManagementSettingsRequest) {
return mergeFrom(
(com.google.cloud.domains.v1beta1.ConfigureManagementSettingsRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(
com.google.cloud.domains.v1beta1.ConfigureManagementSettingsRequest other) {
if (other
== com.google.cloud.domains.v1beta1.ConfigureManagementSettingsRequest
.getDefaultInstance()) return this;
if (!other.getRegistration().isEmpty()) {
registration_ = other.registration_;
onChanged();
}
if (other.hasManagementSettings()) {
mergeManagementSettings(other.getManagementSettings());
}
if (other.hasUpdateMask()) {
mergeUpdateMask(other.getUpdateMask());
}
this.mergeUnknownFields(other.unknownFields);
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
com.google.cloud.domains.v1beta1.ConfigureManagementSettingsRequest parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage =
(com.google.cloud.domains.v1beta1.ConfigureManagementSettingsRequest)
e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private java.lang.Object registration_ = "";
/**
*
*
* <pre>
* Required. The name of the `Registration` whose management settings are being updated,
* in the format `projects/*/locations/*/registrations/*`.
* </pre>
*
* <code>
* string registration = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The registration.
*/
public java.lang.String getRegistration() {
java.lang.Object ref = registration_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
registration_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Required. The name of the `Registration` whose management settings are being updated,
* in the format `projects/*/locations/*/registrations/*`.
* </pre>
*
* <code>
* string registration = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for registration.
*/
public com.google.protobuf.ByteString getRegistrationBytes() {
java.lang.Object ref = registration_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
registration_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Required. The name of the `Registration` whose management settings are being updated,
* in the format `projects/*/locations/*/registrations/*`.
* </pre>
*
* <code>
* string registration = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The registration to set.
* @return This builder for chaining.
*/
public Builder setRegistration(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
registration_ = value;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The name of the `Registration` whose management settings are being updated,
* in the format `projects/*/locations/*/registrations/*`.
* </pre>
*
* <code>
* string registration = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return This builder for chaining.
*/
public Builder clearRegistration() {
registration_ = getDefaultInstance().getRegistration();
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The name of the `Registration` whose management settings are being updated,
* in the format `projects/*/locations/*/registrations/*`.
* </pre>
*
* <code>
* string registration = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The bytes for registration to set.
* @return This builder for chaining.
*/
public Builder setRegistrationBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
registration_ = value;
onChanged();
return this;
}
private com.google.cloud.domains.v1beta1.ManagementSettings managementSettings_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.domains.v1beta1.ManagementSettings,
com.google.cloud.domains.v1beta1.ManagementSettings.Builder,
com.google.cloud.domains.v1beta1.ManagementSettingsOrBuilder>
managementSettingsBuilder_;
/**
*
*
* <pre>
* Fields of the `ManagementSettings` to update.
* </pre>
*
* <code>.google.cloud.domains.v1beta1.ManagementSettings management_settings = 2;</code>
*
* @return Whether the managementSettings field is set.
*/
public boolean hasManagementSettings() {
return managementSettingsBuilder_ != null || managementSettings_ != null;
}
/**
*
*
* <pre>
* Fields of the `ManagementSettings` to update.
* </pre>
*
* <code>.google.cloud.domains.v1beta1.ManagementSettings management_settings = 2;</code>
*
* @return The managementSettings.
*/
public com.google.cloud.domains.v1beta1.ManagementSettings getManagementSettings() {
if (managementSettingsBuilder_ == null) {
return managementSettings_ == null
? com.google.cloud.domains.v1beta1.ManagementSettings.getDefaultInstance()
: managementSettings_;
} else {
return managementSettingsBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Fields of the `ManagementSettings` to update.
* </pre>
*
* <code>.google.cloud.domains.v1beta1.ManagementSettings management_settings = 2;</code>
*/
public Builder setManagementSettings(
com.google.cloud.domains.v1beta1.ManagementSettings value) {
if (managementSettingsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
managementSettings_ = value;
onChanged();
} else {
managementSettingsBuilder_.setMessage(value);
}
return this;
}
/**
*
*
* <pre>
* Fields of the `ManagementSettings` to update.
* </pre>
*
* <code>.google.cloud.domains.v1beta1.ManagementSettings management_settings = 2;</code>
*/
public Builder setManagementSettings(
com.google.cloud.domains.v1beta1.ManagementSettings.Builder builderForValue) {
if (managementSettingsBuilder_ == null) {
managementSettings_ = builderForValue.build();
onChanged();
} else {
managementSettingsBuilder_.setMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* Fields of the `ManagementSettings` to update.
* </pre>
*
* <code>.google.cloud.domains.v1beta1.ManagementSettings management_settings = 2;</code>
*/
public Builder mergeManagementSettings(
com.google.cloud.domains.v1beta1.ManagementSettings value) {
if (managementSettingsBuilder_ == null) {
if (managementSettings_ != null) {
managementSettings_ =
com.google.cloud.domains.v1beta1.ManagementSettings.newBuilder(managementSettings_)
.mergeFrom(value)
.buildPartial();
} else {
managementSettings_ = value;
}
onChanged();
} else {
managementSettingsBuilder_.mergeFrom(value);
}
return this;
}
/**
*
*
* <pre>
* Fields of the `ManagementSettings` to update.
* </pre>
*
* <code>.google.cloud.domains.v1beta1.ManagementSettings management_settings = 2;</code>
*/
public Builder clearManagementSettings() {
if (managementSettingsBuilder_ == null) {
managementSettings_ = null;
onChanged();
} else {
managementSettings_ = null;
managementSettingsBuilder_ = null;
}
return this;
}
/**
*
*
* <pre>
* Fields of the `ManagementSettings` to update.
* </pre>
*
* <code>.google.cloud.domains.v1beta1.ManagementSettings management_settings = 2;</code>
*/
public com.google.cloud.domains.v1beta1.ManagementSettings.Builder
getManagementSettingsBuilder() {
onChanged();
return getManagementSettingsFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Fields of the `ManagementSettings` to update.
* </pre>
*
* <code>.google.cloud.domains.v1beta1.ManagementSettings management_settings = 2;</code>
*/
public com.google.cloud.domains.v1beta1.ManagementSettingsOrBuilder
getManagementSettingsOrBuilder() {
if (managementSettingsBuilder_ != null) {
return managementSettingsBuilder_.getMessageOrBuilder();
} else {
return managementSettings_ == null
? com.google.cloud.domains.v1beta1.ManagementSettings.getDefaultInstance()
: managementSettings_;
}
}
/**
*
*
* <pre>
* Fields of the `ManagementSettings` to update.
* </pre>
*
* <code>.google.cloud.domains.v1beta1.ManagementSettings management_settings = 2;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.domains.v1beta1.ManagementSettings,
com.google.cloud.domains.v1beta1.ManagementSettings.Builder,
com.google.cloud.domains.v1beta1.ManagementSettingsOrBuilder>
getManagementSettingsFieldBuilder() {
if (managementSettingsBuilder_ == null) {
managementSettingsBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.domains.v1beta1.ManagementSettings,
com.google.cloud.domains.v1beta1.ManagementSettings.Builder,
com.google.cloud.domains.v1beta1.ManagementSettingsOrBuilder>(
getManagementSettings(), getParentForChildren(), isClean());
managementSettings_ = null;
}
return managementSettingsBuilder_;
}
private com.google.protobuf.FieldMask updateMask_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.FieldMask,
com.google.protobuf.FieldMask.Builder,
com.google.protobuf.FieldMaskOrBuilder>
updateMaskBuilder_;
/**
*
*
* <pre>
* Required. The field mask describing which fields to update as a comma-separated list.
* For example, if only the transfer lock is being updated, the `update_mask`
* is `"transfer_lock_state"`.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the updateMask field is set.
*/
public boolean hasUpdateMask() {
return updateMaskBuilder_ != null || updateMask_ != null;
}
/**
*
*
* <pre>
* Required. The field mask describing which fields to update as a comma-separated list.
* For example, if only the transfer lock is being updated, the `update_mask`
* is `"transfer_lock_state"`.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The updateMask.
*/
public com.google.protobuf.FieldMask getUpdateMask() {
if (updateMaskBuilder_ == null) {
return updateMask_ == null
? com.google.protobuf.FieldMask.getDefaultInstance()
: updateMask_;
} else {
return updateMaskBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Required. The field mask describing which fields to update as a comma-separated list.
* For example, if only the transfer lock is being updated, the `update_mask`
* is `"transfer_lock_state"`.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setUpdateMask(com.google.protobuf.FieldMask value) {
if (updateMaskBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
updateMask_ = value;
onChanged();
} else {
updateMaskBuilder_.setMessage(value);
}
return this;
}
/**
*
*
* <pre>
* Required. The field mask describing which fields to update as a comma-separated list.
* For example, if only the transfer lock is being updated, the `update_mask`
* is `"transfer_lock_state"`.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setUpdateMask(com.google.protobuf.FieldMask.Builder builderForValue) {
if (updateMaskBuilder_ == null) {
updateMask_ = builderForValue.build();
onChanged();
} else {
updateMaskBuilder_.setMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* Required. The field mask describing which fields to update as a comma-separated list.
* For example, if only the transfer lock is being updated, the `update_mask`
* is `"transfer_lock_state"`.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder mergeUpdateMask(com.google.protobuf.FieldMask value) {
if (updateMaskBuilder_ == null) {
if (updateMask_ != null) {
updateMask_ =
com.google.protobuf.FieldMask.newBuilder(updateMask_).mergeFrom(value).buildPartial();
} else {
updateMask_ = value;
}
onChanged();
} else {
updateMaskBuilder_.mergeFrom(value);
}
return this;
}
/**
*
*
* <pre>
* Required. The field mask describing which fields to update as a comma-separated list.
* For example, if only the transfer lock is being updated, the `update_mask`
* is `"transfer_lock_state"`.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder clearUpdateMask() {
if (updateMaskBuilder_ == null) {
updateMask_ = null;
onChanged();
} else {
updateMask_ = null;
updateMaskBuilder_ = null;
}
return this;
}
/**
*
*
* <pre>
* Required. The field mask describing which fields to update as a comma-separated list.
* For example, if only the transfer lock is being updated, the `update_mask`
* is `"transfer_lock_state"`.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.protobuf.FieldMask.Builder getUpdateMaskBuilder() {
onChanged();
return getUpdateMaskFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Required. The field mask describing which fields to update as a comma-separated list.
* For example, if only the transfer lock is being updated, the `update_mask`
* is `"transfer_lock_state"`.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() {
if (updateMaskBuilder_ != null) {
return updateMaskBuilder_.getMessageOrBuilder();
} else {
return updateMask_ == null
? com.google.protobuf.FieldMask.getDefaultInstance()
: updateMask_;
}
}
/**
*
*
* <pre>
* Required. The field mask describing which fields to update as a comma-separated list.
* For example, if only the transfer lock is being updated, the `update_mask`
* is `"transfer_lock_state"`.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.FieldMask,
com.google.protobuf.FieldMask.Builder,
com.google.protobuf.FieldMaskOrBuilder>
getUpdateMaskFieldBuilder() {
if (updateMaskBuilder_ == null) {
updateMaskBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.FieldMask,
com.google.protobuf.FieldMask.Builder,
com.google.protobuf.FieldMaskOrBuilder>(
getUpdateMask(), getParentForChildren(), isClean());
updateMask_ = null;
}
return updateMaskBuilder_;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.domains.v1beta1.ConfigureManagementSettingsRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.domains.v1beta1.ConfigureManagementSettingsRequest)
private static final com.google.cloud.domains.v1beta1.ConfigureManagementSettingsRequest
DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.domains.v1beta1.ConfigureManagementSettingsRequest();
}
public static com.google.cloud.domains.v1beta1.ConfigureManagementSettingsRequest
getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ConfigureManagementSettingsRequest> PARSER =
new com.google.protobuf.AbstractParser<ConfigureManagementSettingsRequest>() {
@java.lang.Override
public ConfigureManagementSettingsRequest parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new ConfigureManagementSettingsRequest(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<ConfigureManagementSettingsRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ConfigureManagementSettingsRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.domains.v1beta1.ConfigureManagementSettingsRequest
getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
| googleapis/java-domains | proto-google-cloud-domains-v1beta1/src/main/java/com/google/cloud/domains/v1beta1/ConfigureManagementSettingsRequest.java | Java | apache-2.0 | 42,723 |
"use strict";
var utils = exports;
var emitter = require('./emitter');
/**
* @returns {window}
*/
utils.getWindow = function () {
return window;
};
/**
*
* @returns {HTMLDocument}
*/
utils.getDocument = function () {
return document;
};
/**
* Get the current x/y position crossbow
* @returns {{x: *, y: *}}
*/
utils.getBrowserScrollPosition = function () {
var $window = exports.getWindow();
var $document = exports.getDocument();
var scrollX;
var scrollY;
var dElement = $document.documentElement;
var dBody = $document.body;
if ($window.pageYOffset !== undefined) {
scrollX = $window.pageXOffset;
scrollY = $window.pageYOffset;
} else {
scrollX = dElement.scrollLeft || dBody.scrollLeft || 0;
scrollY = dElement.scrollTop || dBody.scrollTop || 0;
}
return {
x: scrollX,
y: scrollY
};
};
/**
* @returns {{x: number, y: number}}
*/
utils.getScrollSpace = function () {
var $document = exports.getDocument();
var dElement = $document.documentElement;
var dBody = $document.body;
return {
x: dBody.scrollHeight - dElement.clientWidth,
y: dBody.scrollHeight - dElement.clientHeight
};
};
/**
* Saves scroll position into cookies
*/
utils.saveScrollPosition = function () {
var pos = utils.getBrowserScrollPosition();
pos = [pos.x, pos.y];
utils.getDocument.cookie = "bs_scroll_pos=" + pos.join(",");
};
/**
* Restores scroll position from cookies
*/
utils.restoreScrollPosition = function () {
var pos = utils.getDocument().cookie.replace(/(?:(?:^|.*;\s*)bs_scroll_pos\s*\=\s*([^;]*).*$)|^.*$/, "$1").split(",");
utils.getWindow().scrollTo(pos[0], pos[1]);
};
/**
* @param tagName
* @param elem
* @returns {*|number}
*/
utils.getElementIndex = function (tagName, elem) {
var allElems = utils.getDocument().getElementsByTagName(tagName);
return Array.prototype.indexOf.call(allElems, elem);
};
/**
* Force Change event on radio & checkboxes (IE)
*/
utils.forceChange = function (elem) {
elem.blur();
elem.focus();
};
/**
* @param elem
* @returns {{tagName: (elem.tagName|*), index: *}}
*/
utils.getElementData = function (elem) {
var tagName = elem.tagName;
var index = utils.getElementIndex(tagName, elem);
return {
tagName: tagName,
index: index
};
};
/**
* @param {string} tagName
* @param {number} index
*/
utils.getSingleElement = function (tagName, index) {
var elems = utils.getDocument().getElementsByTagName(tagName);
return elems[index];
};
/**
* Get the body element
*/
utils.getBody = function () {
return utils.getDocument().getElementsByTagName("body")[0];
};
/**
* @param {{x: number, y: number}} pos
*/
utils.setScroll = function (pos) {
utils.getWindow().scrollTo(pos.x, pos.y);
};
/**
* Hard reload
*/
utils.reloadBrowser = function () {
emitter.emit("browser:hardReload");
utils.getWindow().location.reload(true);
};
/**
* Foreach polyfill
* @param coll
* @param fn
*/
utils.forEach = function (coll, fn) {
for (var i = 0, n = coll.length; i < n; i += 1) {
fn(coll[i], i, coll);
}
};
/**
* Are we dealing with old IE?
* @returns {boolean}
*/
utils.isOldIe = function () {
return typeof utils.getWindow().attachEvent !== "undefined";
};
| BrowserSync/browser-sync-core | client/lib/browser.utils.js | JavaScript | apache-2.0 | 3,359 |
<?php
/**
* Description of AlertQueries
*
* @author ben.dokter
*/
require_once('application/model/value/databaseValueConsts.inc.php');
class AlertQueries {
static function getOpenAlertsAsSender($i_employee_id)
{
$sql = 'SELECT
e.ID_E,
COUNT(*) alert_count
FROM
alerts a
INNER JOIN employees e
ON e.ID_PD = a.ID_PD
AND e.ID_E = ' . $i_employee_id . '
WHERE
e.customer_id = ' . CUSTOMER_ID . '
AND a.is_done = ' . ALERT_OPEN . '
GROUP BY
e.ID_E';
return BaseQueries::performSelectQuery($sql);
}
static function getNotificationMessages()
{
$sql = 'SELECT
*
FROM
notification_message
WHERE
customer_id = ' . CUSTOMER_ID . '
ORDER BY
ID_NM';
return BaseQueries::performSelectQuery($sql);
}
static function insertPdpActionAlert($i_employeePdpActionId,
$i_actionOwnerEmployeeId,
$i_personDataId,
$i_alertMessageId,
$s_notificationDate)
{
$sql = 'INSERT INTO
alerts
( customer_id,
action_owner,
ID_PDPEA,
ID_PD,
ID_NM,
is_level,
alert_date
) values (
' . CUSTOMER_ID . ',
' . $i_actionOwnerEmployeeId . ',
' . $i_employeePdpActionId . ',
' . $i_personDataId . ',
' . $i_alertMessageId . ',
' . ALERT_PDPACTION_EMPLOYEE . ',
"' . $s_notificationDate . '"
)';
return BaseQueries::performInsertQuery($sql);
}
static function deletePdpActionTaskAlerts($i_employee_id, $i_pdpAction_id)
{
// TODO: met inner join?
// check ook met employees_pdp_tasks?
$sql = 'DELETE
FROM
alerts
WHERE
customer_id = ' . CUSTOMER_ID . '
AND is_level = ' . ALERT_PDPACTIONTASK . '
AND ID_PDPET IN
( SELECT
ID_PDPET ept
FROM
employees_pdp_tasks ept
WHERE
ept.customer_id = ' . CUSTOMER_ID . '
AND ept.ID_E = ' . $i_employee_id . '
AND ept.ID_PDPEA = ' . $i_pdpAction_id . '
)';
$sql_result = BaseQueries::performQuery($sql);
return @mysql_affected_rows($sql_result);
}
static function deletePdpActionTaskAlert($i_pdpActionTask_id)
{
// TODO: met inner join?
// check ook met employees_pdp_tasks?
$sql = 'DELETE
FROM
alerts
WHERE
customer_id = ' . CUSTOMER_ID . '
AND is_level = ' . ALERT_PDPACTIONTASK . '
AND ID_PDPET = ' . $i_pdpActionTask_id . '
LIMIT 1';
$sql_result = BaseQueries::performQuery($sql);
return @mysql_affected_rows($sql_result);
}
static function deletePdpActionAlerts($i_pdpAction_id)
{
// TODO: met inner join op employees_pdp_actions?
$sql = 'DELETE
FROM
alerts
WHERE
customer_id = ' . CUSTOMER_ID . '
AND (is_level = ' . ALERT_PDPACTION . '
OR is_level = ' . ALERT_PDPACTION_EMPLOYEE . ')
AND ID_PDPEA = ' . $i_pdpAction_id;
$sql_result = BaseQueries::performQuery($sql);
return @mysql_affected_rows($sql_result);
}
static function activateCancelledPdpActionAlert($i_pdpAction_id)
{
$sql = 'UPDATE
alerts
SET
is_done = ' . ALERT_OPEN . '
WHERE
customer_id = ' . CUSTOMER_ID . '
AND is_done = ' . ALERT_CANCELLED . '
AND (is_level = ' . ALERT_PDPACTION . '
OR is_level = ' . ALERT_PDPACTION_EMPLOYEE . ')
AND ID_PDPEA = ' . $i_pdpAction_id .'
LIMIT 1';
BaseQueries::performQuery($sql);
return @mysql_affected_rows();
}
static function deactivateOpenPdpActionAlert($i_pdpAction_id)
{
$sql = 'UPDATE
alerts
SET
is_done = ' . ALERT_CANCELLED . '
WHERE
customer_id = ' . CUSTOMER_ID . '
AND is_done = ' . ALERT_OPEN . '
AND (is_level = ' . ALERT_PDPACTION . '
OR is_level = ' . ALERT_PDPACTION_EMPLOYEE . ')
AND ID_PDPEA = ' . $i_pdpAction_id .'
LIMIT 1';
BaseQueries::performQuery($sql);
return @mysql_affected_rows();
}
static function activateCancelledPdpActionTaskAlert($i_pdpActionTask_id)
{
$sql = 'UPDATE
alerts
SET
is_done = ' . ALERT_OPEN . '
WHERE
customer_id = ' . CUSTOMER_ID . '
AND is_done = ' . ALERT_CANCELLED . '
AND is_level = ' . ALERT_PDPACTIONTASK . '
AND ID_PDPET = ' . $i_pdpActionTask_id .'
LIMIT 1';
BaseQueries::performQuery($sql);
return @mysql_affected_rows();
}
static function deactivateOpenPdpActionTaskAlert($i_pdpActionTask_id)
{
$sql = 'UPDATE
alerts
SET
is_done = ' . ALERT_CANCELLED . '
WHERE
customer_id = ' . CUSTOMER_ID . '
AND is_done = ' . ALERT_OPEN . '
AND is_level = ' . ALERT_PDPACTIONTASK . '
AND ID_PDPET = ' . $i_pdpActionTask_id .'
LIMIT 1';
BaseQueries::performQuery($sql);
return @mysql_affected_rows();
}
}
?>
| joris520/broodjesalami | php_cm/modules/model/queries/to_refactor/AlertQueries.class.php | PHP | apache-2.0 | 6,749 |
import sys
from tasks import TaskExecutionError
from templates import TaskTemplateResolver, TemplateKeyError
from config import DatamakeConfig
import runner
import json
import utils
def parse_args(args):
try:
import argparse
return parse_args_with_argparse(args)
except ImportError:
import optparse
return parse_args_with_optparse(args)
def parse_args_with_argparse(args):
import argparse
parser = argparse.ArgumentParser(description='Run datamake task flow.')
parser.add_argument('task_id', metavar='task_id', type=str, help='target task to be run')
parser.add_argument('config_files', metavar='config_file', type=str, nargs='+',
help='task config files')
parser.add_argument('--param', dest='parameters', action='append',
help='specify KEY=VALUE parameter that will override parameters on all tasks')
parser.add_argument('--eval-param', dest='eval_parameters', action='append',
help='specify KEY=VALUE parameter that will override parameters on all tasks. VALUE will be replaced by eval(VALUE) in python. If the eval output is a list, the task flow will be executed per value.')
parser.add_argument('--showgraph', dest='showgraph', action='store_true',
help='print the task dependency graph but don\'t run tasks.')
parser.add_argument('--dryrun', dest='dryrun', action='store_true',
help='print all tasks and if they are pending but do not execute them')
parser.add_argument('--delete-artifacts', dest='delete_artifacts', action='store_true',
help='beware! deletes all artifacts in the flow!')
return parser.parse_args(args)
def parse_args_with_optparse(args):
import optparse
usage = """usage: %prog [-h] [--param PARAMETERS] [--eval-param EVAL_PARAMETERS]
[--showgraph] [--dryrun] [--delete-artifacts]
task_id config_file [config_file ...]"""
parser = optparse.OptionParser(usage=usage)
parser.add_option('--param', dest='parameters', action='append',
help='specify KEY=VALUE parameter that will override parameters on all tasks')
parser.add_option('--eval-param', dest='eval_parameters', action='append',
help='specify KEY=VALUE parameter that will override parameters on all tasks. VALUE will be replaced by eval(VALUE) in python. If the eval output is a list, the task flow will be executed per value.')
parser.add_option('--showgraph', dest='showgraph', action='store_true',
help='print the task dependency graph but don\'t run tasks')
parser.add_option('--dryrun', dest='dryrun', action='store_true',
help='print all tasks and if they are pending but do not execute them')
parser.add_option('--delete-artifacts', dest='delete_artifacts', action='store_true',
help='beware! deletes all artifacts in the flow!')
(options, remaining) = parser.parse_args()
if len(remaining) < 2:
print "Not enough arguments, need: task_id config_files | [config_file]"
options.task_id = remaining[0]
options.config_files = remaining[1:]
return options
def run_tasks(task_runner, pending_tasks):
try:
for task_id in pending_tasks:
task_runner.run_task(task_id)
return 0
except TaskExecutionError, e:
print "Error while executing task ", task_id
print e.task.tuple()
print e.message
task_runner.abort_pending_tasks()
return 1
finally:
task_runner.delete_artifacts(pending_tasks)
def dry_run_tasks(task_runner, pending_tasks):
print "Starting dry run"
for task_id in pending_tasks:
task = task_runner.get_task(task_id)
if task.command:
print "command:", task.command
if task.artifact:
print "artifact:",task.artifact.uri()
print "Dry run complete"
return 0
def get_config(config_filename):
config = DatamakeConfig()
config.load_from_file(config_filename)
return config
def get_template_resolver(configs, override_parameters={}):
task_template_sets = [config.task_templates(override_parameters) for config in configs]
flattened_task_templates = [item for sublist in task_template_sets for item in sublist]
template_resolver = TaskTemplateResolver(flattened_task_templates)
return template_resolver
def main():
args = parse_args(sys.argv[1:])
task_id = args.task_id
parameters = dict(param.split('=') for param in args.parameters) if args.parameters else {}
override_parameters_list = []
if args.eval_parameters:
evaled_parameters_list = list(utils.evalulate_parameters(dict(param.split('=') for param in args.eval_parameters)))
for evaled_parameters in evaled_parameters_list:
override_parameters = dict(evaled_parameters)
override_parameters.update(parameters)
override_parameters_list.append(override_parameters)
else:
override_parameters_list = [parameters]
if (len(args.config_files) > 1) and not ('.' in task_id):
print "task_id must be namespaced (eg. namespace.task) when multiple config files are used. You provided '%s'" % task_id
return 1
configs = [get_config(filename) for filename in args.config_files]
exit_status = 0
for override_parameters in override_parameters_list:
template_resolver = get_template_resolver(configs, override_parameters)
try:
task_graph = template_resolver.resolve_task_graph(task_id)
except TemplateKeyError, e:
print e
exit_status = 1
break
task_runner = runner.Runner(task_id, task_graph)
if args.showgraph:
print "Task graph:"
exit_status = task_runner.show_graph()
break
print "Starting Flow"
print "Override params: %s" % json.dumps(override_parameters, indent=True)
pending_tasks = task_runner.get_pending_execution_order()
print "Task status:"
task_runner.print_all_task_status()
print "Trimming tasks..."
print "Pending tasks"
task_runner.print_task_status(pending_tasks)
if args.dryrun:
exit_status += dry_run_tasks(task_runner, pending_tasks)
elif args.delete_artifacts:
print "Forcing removal of existing artifacts"
task_runner.delete_all_artifacts(force=True)
else:
exit_status += run_tasks(task_runner, pending_tasks)
print "Final status"
task_runner.print_all_task_status()
print
if exit_status:
break
print "FAILED" if exit_status else "SUCCESS"
return exit_status
if __name__ == '__main__':
main()
| tims/datamake | datamake/datamake.py | Python | apache-2.0 | 6,497 |
from setuptools import setup, find_packages
setup(
name = "scorecard",
version = "0.1",
packages = find_packages()
)
| opme/SurgeonScorecard | python/setup.py | Python | apache-2.0 | 135 |
package com.example.weather.gson;
import com.google.gson.annotations.SerializedName;
/**
* Created by johnny on 2017/8/14.
*/
public class Suggestion {
@SerializedName("comf")
public Comfort comfort;
@SerializedName("cw")
public CarWash carWash;
public Sport sport;
public class Comfort{
@SerializedName("txt")
public String info;
}
public class CarWash{
@SerializedName("txt")
public String info;
}
public class Sport{
@SerializedName("txt")
public String info;
}
}
| MrfrankyLee/Weather | app/src/main/java/com/example/weather/gson/Suggestion.java | Java | apache-2.0 | 571 |
import inspect
import typing as t
from functools import wraps
from .utils import _PassArg
from .utils import pass_eval_context
V = t.TypeVar("V")
def async_variant(normal_func): # type: ignore
def decorator(async_func): # type: ignore
pass_arg = _PassArg.from_obj(normal_func)
need_eval_context = pass_arg is None
if pass_arg is _PassArg.environment:
def is_async(args: t.Any) -> bool:
return t.cast(bool, args[0].is_async)
else:
def is_async(args: t.Any) -> bool:
return t.cast(bool, args[0].environment.is_async)
@wraps(normal_func)
def wrapper(*args, **kwargs): # type: ignore
b = is_async(args)
if need_eval_context:
args = args[1:]
if b:
return async_func(*args, **kwargs)
return normal_func(*args, **kwargs)
if need_eval_context:
wrapper = pass_eval_context(wrapper)
wrapper.jinja_async_variant = True
return wrapper
return decorator
async def auto_await(value: t.Union[t.Awaitable["V"], "V"]) -> "V":
if inspect.isawaitable(value):
return await t.cast("t.Awaitable[V]", value)
return t.cast("V", value)
async def auto_aiter(
iterable: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",
) -> "t.AsyncIterator[V]":
if hasattr(iterable, "__aiter__"):
async for item in t.cast("t.AsyncIterable[V]", iterable):
yield item
else:
for item in t.cast("t.Iterable[V]", iterable):
yield item
async def auto_to_list(
value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",
) -> t.List["V"]:
return [x async for x in auto_aiter(value)]
| sonntagsgesicht/regtest | .aux/venv/lib/python3.9/site-packages/jinja2/async_utils.py | Python | apache-2.0 | 1,751 |
<?php
use Aws\Laravel\AwsServiceProvider;
use Illuminate\Foundation\Application;
return [
/*
|--------------------------------------------------------------------------
| AWS SDK Configuration
|--------------------------------------------------------------------------
|
| The configuration options set in this file will be passed directly to the
| `Aws\Sdk` object, from which all client objects are created. The minimum
| required options are declared here, but the full set of possible options
| are documented at:
| http://docs.aws.amazon.com/aws-sdk-php/v3/guide/guide/configuration.html
|
*/
'credentials' => [
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
],
'region' => env('AWS_REGION', 'us-east-1'),
'version' => 'latest',
'ua_append' => [
'Laravel/' . Application::VERSION,
'L5MOD/' . AwsServiceProvider::VERSION,
],
];
| phazei/aws-sdk-php-laravel | config/aws.php | PHP | apache-2.0 | 972 |
package org.sunger.net.util;
import android.content.Context;
/**
* 数据转换类
* Created by xuebp on 2016/1/26.
*/
public final class ConvertUtils {
private static final float UNIT = 1000.0F;
/**
* 毫秒转秒
*
* @param time 毫秒
* @return
*/
public static float ms2s(long time) {
return time / UNIT;
}
/**
* 微秒转秒
*
* @param time 微秒
* @return
*/
public static float us2s(long time) {
return time / UNIT / UNIT;
}
/**
* 纳秒转秒
*
* @param time 纳秒
* @return
*/
public static float ns2s(long time) {
return time / UNIT / UNIT / UNIT;
}
/**
* 转换字符串为boolean
*
* @param str
* @return
*/
public static boolean toBoolean(String str) {
return toBoolean(str, false);
}
/**
* 转换字符串为boolean
*
* @param str
* @param def
* @return
*/
public static boolean toBoolean(String str, boolean def) {
if (StringUtils.isEmpty(str))
return def;
if ("false".equalsIgnoreCase(str) || "0".equals(str))
return false;
else if ("true".equalsIgnoreCase(str) || "1".equals(str))
return true;
else
return def;
}
/**
* 转换字符串为float
*
* @param str
* @return
*/
public static float toFloat(String str) {
return toFloat(str, 0F);
}
/**
* 转换字符串为float
*
* @param str
* @param def
* @return
*/
public static float toFloat(String str, float def) {
if (StringUtils.isEmpty(str))
return def;
try {
return Float.parseFloat(str);
} catch (NumberFormatException e) {
return def;
}
}
/**
* 转换字符串为long
*
* @param str
* @return
*/
public static long toLong(String str) {
return toLong(str, 0L);
}
/**
* 转换字符串为long
*
* @param str
* @param def
* @return
*/
public static long toLong(String str, long def) {
if (StringUtils.isEmpty(str))
return def;
try {
return Long.parseLong(str);
} catch (NumberFormatException e) {
return def;
}
}
/**
* 转换字符串为short
*
* @param str
* @return
*/
public static short toShort(String str) {
return toShort(str, (short) 0);
}
/**
* 转换字符串为short
*
* @param str
* @param def
* @return
*/
public static short toShort(String str, short def) {
if (StringUtils.isEmpty(str))
return def;
try {
return Short.parseShort(str);
} catch (NumberFormatException e) {
return def;
}
}
/**
* 转换字符串为int
*
* @param str
* @return
*/
public static int toInt(String str) {
return toInt(str, 0);
}
/**
* 转换字符串为int
*
* @param str
* @param def
* @return
*/
public static int toInt(String str, int def) {
if (StringUtils.isEmpty(str))
return def;
try {
return Integer.parseInt(str);
} catch (NumberFormatException e) {
return def;
}
}
public static String toString(Object o) {
return toString(o, "");
}
public static String toString(Object o, String def) {
if (o == null)
return def;
return o.toString();
}
public static int dipToPX(final Context ctx, int dip) {
float scale = ctx.getResources().getDisplayMetrics().density;
return (int) (dip / 1.5D * scale + 0.5D);
}
}
| XueBaoPeng/ningxiaVideo | app/src/main/java/org/sunger/net/util/ConvertUtils.java | Java | apache-2.0 | 3,896 |
import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import { ActivatedRoute, ParamMap } from '@angular/router';
import 'rxjs/add/operator/switchMap';
import { PhotoService } from '../../services/photo.service';
import { API } from '../../services/api.const';
@Component({
selector: 'app-generator',
templateUrl: './generator.component.html',
styleUrls: ['./generator.component.css']
})
export class GeneratorComponent implements OnInit {
private albumId: number;
photos: Array<any>;
@ViewChild('listContent')
listContent: ElementRef;
@ViewChild('listContainer')
listContainer: ElementRef;
listTransform: string = 'translate3d(0, 0, 0)';
pressing: any = null;
unpressings: Array<any>;
constructor(private route: ActivatedRoute, private photoService: PhotoService) { }
ngOnInit() {
const self = this;
this.route.paramMap.switchMap((params: ParamMap) => {
self.albumId = Number(params.get("id"));
return self.photoService.listAlbumPhotosObservable(self.albumId, 1, Number(params.get("size")));
}).subscribe(paged => self.photos = paged.Photos.map(p => ({
...p,
src: API.getAPI("domain") + p.AlbumPhotoUrl
})));
}
scroll(e) {
if (Math.abs(e.deltaY) < Math.abs(e.deltaX)) {
return;
}
let curPos = parseInt(this.listTransform.match(/translate3d\(0, (\-?\d+(?:\.\d+)?).*?, 0\)/)[1], 10);
if (e.deltaY <= 0) {
curPos = Math.min(0, curPos - e.deltaY);
} else {
curPos = Math.max(
Math.min(0, this.listContainer.nativeElement.offsetHeight - this.listContent.nativeElement.offsetHeight)
, curPos - e.deltaY);
}
this.listTransform = 'translate3d(0, ' + curPos + 'px, 0)';
}
onDrag(idx) {
this.pressing = this.photos[idx];
this.unpressings = [...this.photos.slice(0, idx), ...this.photos.slice(idx + 1)];
}
mousemove(e) {
if (this.pressing === null || e.buttons !== 1) {
return;
}
let curPos = parseInt(this.listTransform.match(/translate3d\(0, (\-?\d+(?:\.\d+)?).*?, 0\)/)[1], 10);
let on = Math.floor((e.clientY - curPos - 40) / 100);
this.photos = [
...this.unpressings.slice(0, on),
this.pressing,
...this.unpressings.slice(on)
];
}
mouseup() {
this.pressing = null;
}
}
| CaoYouXin/serveV2 | html/albumConsole/src/app/video/generator/generator.component.ts | TypeScript | apache-2.0 | 2,310 |
/*
* Copyright © 2016 EDDiscovery development team
*
* 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.
*
* EDDiscovery is not affiliated with Fronter Developments plc.
*/
using Newtonsoft.Json.Linq;
using System.Linq;
namespace EDDiscovery.EliteDangerous.JournalEvents
{
//When written: when joining up with a power
//Parameters:
//• Power
public class JournalPowerplayJoin : JournalEntry
{
public JournalPowerplayJoin(JObject evt) : base(evt, JournalTypeEnum.PowerplayJoin)
{
Power = JSONHelper.GetStringDef(evt["Power"]);
}
public string Power { get; set; }
public static System.Drawing.Bitmap Icon { get { return EDDiscovery.Properties.Resources.powerplayjoin; } }
}
}
| jeoffman/EDDiscovery | EDDiscovery/EliteDangerous/JournalEvents/JournalPowerplayJoin.cs | C# | apache-2.0 | 1,258 |
/*
* Copyright 2017-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.cloud.spring.core;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.junit.jupiter.api.Test;
/** Tests for the {@link DefaultCredentialsProvider}. */
class DefaultCredentialsProviderTests {
@Test
void testResolveScopesDefaultScopes() {
List<String> scopes = DefaultCredentialsProvider.resolveScopes(null);
assertThat(scopes.size()).isGreaterThan(1);
assertThat(scopes).contains(GcpScope.PUBSUB.getUrl());
}
@Test
void testResolveScopesOverrideScopes() {
List<String> scopes =
DefaultCredentialsProvider.resolveScopes(Collections.singletonList("myscope"));
assertThat(scopes).hasSize(1).contains("myscope");
}
@Test
void testResolveScopesStarterScopesPlaceholder() {
List<String> scopes =
DefaultCredentialsProvider.resolveScopes(Arrays.asList("DEFAULT_SCOPES", "myscope"));
assertThat(scopes)
.hasSize(GcpScope.values().length + 1)
.contains(GcpScope.PUBSUB.getUrl())
.contains("myscope");
}
}
| GoogleCloudPlatform/spring-cloud-gcp | spring-cloud-gcp-core/src/test/java/com/google/cloud/spring/core/DefaultCredentialsProviderTests.java | Java | apache-2.0 | 1,725 |
/*******************************************************************************
* Copyright 2010 Dieselpoint, 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 org.openpipeline.server.pages;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import javax.servlet.jsp.PageContext;
import org.openpipeline.scheduler.JobScanner;
import org.openpipeline.scheduler.PipelineScheduler;
import org.openpipeline.util.XMLConfig;
import org.quartz.SchedulerException;
/**
* This page populates the "trigger" part of a job.
*/
public class SetSchedulePage extends AdminPage {
/*
* The format in the job of a trigger:
* <trigger>
* <starttime>yyyy-mm-ddThh:mm:ss</starttime>
* <schedtype>periodic</schedtype>
* <period>daily</period>
* <periodinterval>2</periodinterval>
* <cronexp>some expression</cronexp>
* </trigger>
*
* The page params:
* startdate
* starthour
* startminute
* ampm
* schedtype
* period-interval
* cronexp
*
*/
private boolean redirect;
private String jobName;
public void processPage(PageContext pageContext) {
redirect = false;
super.processPage(pageContext);
try {
JobScanner jobScanner = new JobScanner();
jobName = pageContext.getRequest().getParameter("jobname");
XMLConfig conf = jobScanner.getJobFromDisk(jobName);
String next = super.getParam("next");
if (next == null || next.length() == 0) {
// we're hitting the page for the first time. populate it
if (conf != null) {
XMLConfig trig = conf.getChild("trigger");
if (trig != null) {
popParamsFromXML(trig);
}
// set some defaults here
if (super.getParam("schedtype") == null) {
super.setParam("schedtype", "ondemand");
}
}
} else {
// the user hit "next>>". save and redirect.
try {
saveJob(conf);
redirect = true;
} catch (ParseException e1) {
super.handleError("Bad date format: " + e1.toString(), e1);
} catch (Exception e) {
super.handleError("Error (see log for details): " + e.toString(), e);
}
}
} catch (Exception e) {
super.handleError("Error on set schedule page", e);
}
}
/**
* Fetch the params that define the schedule, add them to the config
* object and then write to disk.
* @throws ClassNotFoundException
* @throws SchedulerException
*/
private void saveJob(XMLConfig conf) throws IOException, ParseException, SchedulerException {
conf.removeChild("trigger");
XMLConfig trig = populateXMLFromParams();
conf.addChild(trig);
JobScanner jobScanner = new JobScanner();
jobScanner.saveAndLoadJob(conf);
}
/**
* Get params out of the config and populate the page params, so the
* controls on the page are filled in with the previous values.
* @param conf
*/
private void popParamsFromXML(XMLConfig conf) {
String fullDate = conf.getProperty("starttime");
if (fullDate != null) {
String startDate = fullDate.substring(0, 10);
String startHour = fullDate.substring(11, 13);
String startMinute = fullDate.substring(14, 16);
String ampm;
int startHourInt = Integer.parseInt(startHour);
if (startHourInt > 12) {
ampm = "pm";
startHourInt = startHourInt - 12;
startHour = startHourInt + "";
if (startHour.length() < 2)
startHour = "0" + startHour;
} else {
ampm = "am";
}
super.setParam("startdate", startDate);
super.setParam("starthour", startHour);
super.setParam("startminute", startMinute);
super.setParam("ampm", ampm);
}
super.setParam("period", conf.getProperty("period"));
super.setParam("period-interval", conf.getProperty("period-interval"));
super.setParam("schedtype", conf.getProperty("schedtype"));
super.setParam("cronexp", conf.getProperty("cronexp"));
}
/**
* Extract the params from the page and populate a config trigger.
* @return a new config object
* @throws ParseException if the date format is bad
* @throws SchedulerException
*/
private XMLConfig populateXMLFromParams() throws ParseException, SchedulerException {
String startDate = super.getParam("startdate", "");
String startHour = super.getParam("starthour", "00");
String startMinute = super.getParam("startminute", "00");
String ampm = super.getParam("ampm", "am");
if ("pm".equals(ampm)) {
int intStartHour = Integer.parseInt(startHour);
startHour = (intStartHour + 12) + "";
}
String fullDate = null;
if (startDate.length() > 0) {
fullDate = startDate + " " + startHour + ":" + startMinute + ":00 " + ampm;
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss a");
df.parse(fullDate); // just validates the date format
}
XMLConfig trig = new XMLConfig();
String cronexp = super.getParam("cronexp");
PipelineScheduler.validateCronExpression(cronexp);
addPropertyIfNotNull("period", super.getParam("period"), trig);
addPropertyIfNotNull("period-interval", super.getParam("period-interval"), trig);
addPropertyIfNotNull("schedtype", super.getParam("schedtype"), trig);
addPropertyIfNotNull("cronexp", cronexp, trig);
addPropertyIfNotNull("starttime", fullDate, trig);
trig.setName("trigger");
return trig;
}
/**
* Add property if not null.
*/
private void addPropertyIfNotNull(String name, String value, XMLConfig conf) {
if (value != null && value.length() > 0) {
conf.addProperty(name, value);
}
}
public boolean redirect() {
return redirect;
}
public String getJobName() {
return jobName;
}
}
| Spantree/openpipeline | src/main/java/org/openpipeline/server/pages/SetSchedulePage.java | Java | apache-2.0 | 6,419 |
/*
* Licensed to The Apereo Foundation under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* The Apereo Foundation 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.tle.core.connectors.equella.service;
import com.dytech.edge.queries.FreeTextQuery;
import com.google.common.base.Throwables;
import com.google.common.collect.Lists;
import com.tle.annotation.NonNullByDefault;
import com.tle.annotation.Nullable;
import com.tle.beans.item.IItem;
import com.tle.beans.item.Item;
import com.tle.beans.item.ItemId;
import com.tle.beans.item.ItemStatus;
import com.tle.beans.item.attachments.AttachmentType;
import com.tle.beans.item.attachments.CustomAttachment;
import com.tle.beans.item.attachments.ImsAttachment;
import com.tle.beans.item.attachments.UnmodifiableAttachments;
import com.tle.common.Check;
import com.tle.common.Format;
import com.tle.common.connectors.ConnectorContent;
import com.tle.common.connectors.ConnectorCourse;
import com.tle.common.connectors.ConnectorFolder;
import com.tle.common.connectors.ConnectorTerminology;
import com.tle.common.connectors.entity.Connector;
import com.tle.common.i18n.CurrentLocale;
import com.tle.common.search.DefaultSearch;
import com.tle.common.searching.SearchResults;
import com.tle.common.searching.SimpleSearchResults;
import com.tle.common.usermanagement.user.valuebean.UserBean;
import com.tle.core.connectors.exception.LmsUserNotFoundException;
import com.tle.core.connectors.service.ConnectorRepositoryImplementation;
import com.tle.core.connectors.service.ConnectorRepositoryService.ExternalContentSortType;
import com.tle.core.freetext.service.FreeTextService;
import com.tle.core.guice.Bind;
import com.tle.core.item.dao.AttachmentDao;
import com.tle.core.item.service.ItemService;
import com.tle.core.plugins.AbstractPluginService;
import com.tle.core.security.TLEAclManager;
import com.tle.core.services.item.FreetextResult;
import com.tle.core.services.item.FreetextSearchResults;
import com.tle.core.services.user.UserService;
import com.tle.web.sections.SectionInfo;
import com.tle.web.sections.SectionsController;
import com.tle.web.selection.SelectedResource;
import com.tle.web.viewable.impl.ViewableItemFactory;
import com.tle.web.viewurl.ViewItemUrl;
import com.tle.web.viewurl.ViewItemUrlFactory;
import com.tle.web.viewurl.attachments.AttachmentResourceService;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import javax.inject.Inject;
import javax.inject.Singleton;
@NonNullByDefault
@Bind
@Singleton
public class EquellaConnectorService implements ConnectorRepositoryImplementation {
private static final String KEY_PFX =
AbstractPluginService.getMyPluginId(EquellaConnectorService.class) + ".";
private static final String VIEW_ITEM = "VIEW_ITEM"; // $NON-NLS-1$
@Inject private FreeTextService freeTextService;
@Inject private UserService userService;
@Inject private TLEAclManager aclManager;
@Inject private ItemService itemService;
@Inject private ViewItemUrlFactory itemUrls;
@Inject private ViewableItemFactory viewableItemFactory;
@Inject private AttachmentResourceService attachmentResourceService;
@Inject private AttachmentDao attachmentDao;
// no!! shouldn't need this
@Inject private SectionsController sectionsController;
@Override
public boolean isRequiresAuthentication(Connector connector) {
return false;
}
@Override
public String getAuthorisationUrl(
Connector connector, String forwardUrl, @Nullable String authData) {
return null;
}
@Override
public List<ConnectorContent> findUsages(
Connector connector,
String username,
final String uuid,
int version,
boolean versionIsLatest,
boolean archived,
boolean allVersion)
throws LmsUserNotFoundException {
final DefaultSearch search = new DefaultSearch();
search.setPrivilege(VIEW_ITEM);
if (!archived) {
search.setItemStatuses(ItemStatus.LIVE);
}
if (allVersion) {
search.addMust(FreeTextQuery.FIELD_ATTACHMENT_UUID, uuid);
} else {
final List<String> values = new ArrayList<String>();
values.add(uuid + "." + version);
if (versionIsLatest) {
values.add(uuid + ".0");
}
search.addMust(FreeTextQuery.FIELD_ATTACHMENT_UUID_VERSION, values);
}
final FreetextSearchResults<FreetextResult> results = freeTextService.search(search, 0, -1);
final List<ConnectorContent> contentList = new ArrayList<ConnectorContent>();
Collection<Item> foundItems = results.getResults();
foundItems = aclManager.filterNonGrantedObjects(Collections.singleton(VIEW_ITEM), foundItems);
for (Item item : foundItems) {
final String name = CurrentLocale.get(item.getName(), item.getUuid());
final String owner = getUser(userService, item.getOwner());
final List<CustomAttachment> attachments =
new UnmodifiableAttachments(item).getCustomList("resource");
for (CustomAttachment attachment : attachments) {
final String remoteItemUuid = (String) attachment.getData("uuid");
final Integer remoteItemVersion = (Integer) attachment.getData("version");
if (remoteItemUuid != null && remoteItemUuid.equals(uuid)) {
if (allVersion
|| remoteItemVersion == version
|| (versionIsLatest && remoteItemVersion == 0)) {
contentList.add(convertAttachment(item, attachment, name, owner));
}
}
}
}
return contentList;
}
@SuppressWarnings("deprecation")
private String getUser(UserService userService, String uuid) {
if (uuid == null || uuid.length() == 0 || uuid.equals("0")) {
return CurrentLocale.get("user.nouser");
}
String user = null;
UserBean informationForUser = userService.getInformationForUser(uuid);
if (informationForUser != null) {
user = Format.format(informationForUser);
}
if (user == null) {
user = CurrentLocale.get("user.unknownuser");
}
return user;
}
@Override
public SearchResults<ConnectorContent> findAllUsages(
Connector connector,
String username,
String query,
String courseId,
String folderId,
boolean archived,
int offset,
int count,
ExternalContentSortType sortType,
boolean reverseSort)
throws LmsUserNotFoundException {
// YUK, should be no sort HQL in the service!
final String sortHql;
if (sortType != null) {
switch (sortType) {
case DATE_ADDED:
sortHql = "ORDER BY a.item.dateCreated " + (reverseSort ? "ASC" : "DESC");
break;
case NAME:
default:
sortHql = "ORDER BY a.description " + (reverseSort ? "DESC" : "ASC");
break;
}
} else {
sortHql = "ORDER BY a.description " + (reverseSort ? "DESC" : "ASC");
}
final List<CustomAttachment> resources =
attachmentDao.findResourceAttachmentsByQuery(query, !archived, sortHql);
// filter unviewable items
final List<ConnectorContent> content = Lists.newArrayList();
final Iterator<CustomAttachment> resIt = resources.iterator();
int index = 0;
while (resIt.hasNext()) {
final CustomAttachment custom = resIt.next();
final Item item = custom.getItem();
final Set<String> privs =
aclManager.filterNonGrantedPrivileges(item, Collections.singleton(VIEW_ITEM));
if (privs.isEmpty()) {
resIt.remove();
} else {
// count < 0 == ALL
if (index >= offset && (count < 0 || index < offset + count)) {
final String name = CurrentLocale.get(item.getName(), item.getUuid());
// Use user link service
final String owner = getUser(userService, item.getOwner());
content.add(convertAttachment(item, custom, name, owner));
}
index++;
if (count >= 0 && index >= offset + count) {
break;
}
}
}
return new SimpleSearchResults<ConnectorContent>(
content, content.size(), offset, resources.size());
}
@Override
public int getUnfilteredAllUsagesCount(
Connector connector, String username, String query, boolean archived) {
try {
return findAllUsages(
connector,
username,
query,
null,
null,
archived,
0,
0,
ExternalContentSortType.NAME,
false)
.getAvailable();
} catch (LmsUserNotFoundException lms) {
throw Throwables.propagate(lms);
}
}
/**
* @param item
* @param attachment
* @param name
* @param owner
* @param fakeCourseNameAndFolder This is not an ideal way to do this.
* @return
*/
private ConnectorContent convertAttachment(
Item item, CustomAttachment attachment, String name, String owner) {
final String targetItemUuid = (String) attachment.getData("uuid");
final Integer targetItemVersion = (Integer) attachment.getData("version");
// FIXME: shouldn't NEED an info. this is just DODGE-O-RAMA
final SectionInfo info = sectionsController.createForward("/viewitem/viewitem.do");
final ConnectorContent content = new ConnectorContent(attachment.getUuid());
// linking attachment
content.setFolder(attachment.getDescription());
final ViewItemUrl attachmentUrl =
attachmentResourceService
.getViewableResource(
info, viewableItemFactory.createNewViewableItem(item.getItemId() /*
* new
* ItemId (
* targetItemUuid
* ,
* targetItemVersion
* )
*/), attachment)
.createDefaultViewerUrl();
content.setFolderUrl(attachmentUrl.getHref());
// linking item
content.setCourse(name);
content.setCourseUrl(
itemUrls.createItemUrl(info, item.getItemId(), ViewItemUrl.FLAG_FULL_URL).getHref());
content.setUuid(targetItemUuid);
content.setVersion(targetItemVersion);
final String targetAttachmentUuid = attachment.getUrl();
if (!Check.isEmpty(targetAttachmentUuid)) {
if (targetAttachmentUuid.equalsIgnoreCase("viewims.jsp")) {
// load the IMS attachment and also set the attachmentUuid
List<ImsAttachment> ims =
new UnmodifiableAttachments(
itemService.getUnsecure(new ItemId(targetItemUuid, targetItemVersion)))
.getList(AttachmentType.IMS);
if (ims.size() == 1) // as it should
{
content.setAttachmentUuid(ims.get(0).getUuid());
}
content.setAttachmentUrl(targetAttachmentUuid);
} else {
content.setAttachmentUuid(targetAttachmentUuid);
}
}
content.setExternalTitle(getExternalTitle(attachment));
// content.setExternalTitle(getExternalTitle(attachment,
// selectedAttachment, targetItemUuid, targetItemVersion,
// targetAttachmentUuid));
// content.setExternalUrl(itemUrls.createItemUrl(info, item.getItemId(),
// ViewItemUrl.FLAG_FULL_URL).getHref());
content.setAttribute("owner", getKey("finduses.owner"), owner);
content.setDateModified(item.getDateModified());
content.setDateAdded(item.getDateCreated());
// if( selectedAttachment != null )
// {
// final ViewItemUrl attachmentUrl =
// attachmentResourceService.getViewableResource(
// info,
// viewableItemFactory.createNewViewableItem(new ItemId(targetItemUuid,
// targetItemVersion)), selectedAttachment).createDefaultViewerUrl();
// content.setFolderUrl(attachmentUrl.getHref());
// content.setFolder(selectedAttachment.getDescription());
// }
content.setAvailable(item.getStatus() == ItemStatus.LIVE);
return content;
}
// private String getExternalTitle(CustomAttachment attachment, Attachment
// selectedAttachment, String remoteItemUuid,
// int remoteItemVersion, String remoteAttachmentUuid)
private String getExternalTitle(CustomAttachment attachment) {
final String description = attachment.getDescription();
if (description == null) {
return attachment.getUuid();
}
return description;
// if( Check.isEmpty(description) )
// {
// Attachment sel = selectedAttachment;
// if( sel == null )
// {
// try
// {
// sel = itemService.getAttachmentForUuid(new ItemId(remoteItemUuid,
// remoteItemVersion), remoteAttachmentUuid);
// }
// catch( AttachmentNotFoundException a )
// {
// return CurrentLocale.get(getKey("finduses.attachmentnotfound"));
// }
// }
// if( sel == null )
// {
// return Utils.coalesce(description, attachment.getUrl(),
// attachment.getUuid());
// }
// //get the name of the attachment that is linked to
// return Utils.coalesce(sel.getDescription(), sel.getUrl(),
// sel.getUuid());
// }
// return description;
}
@Override
public ConnectorFolder addItemToCourse(
Connector connector,
String username,
String courseId,
String sectionId,
IItem<?> item,
SelectedResource selectedResource) {
throw new UnsupportedOperationException("Not supported yet");
}
@Override
public List<ConnectorCourse> getCourses(
Connector connector,
String username,
boolean editable,
boolean archived,
boolean management) {
throw new UnsupportedOperationException(getString("export.error.notsupported"));
}
@Override
public List<ConnectorFolder> getFoldersForCourse(
Connector connector, String username, String courseId, boolean management)
throws LmsUserNotFoundException {
throw new UnsupportedOperationException("Not supported yet");
}
@Override
public List<ConnectorFolder> getFoldersForFolder(
Connector connector, String username, String courseId, String folderId, boolean management)
throws LmsUserNotFoundException {
throw new UnsupportedOperationException("Not supported yet");
}
@Override
public String getCourseCode(Connector connector, String username, String courseId)
throws LmsUserNotFoundException {
throw new UnsupportedOperationException("Not supported yet");
}
private String getKey(String partKey) {
return KEY_PFX + partKey;
}
private String getString(String partKey, String... params) {
return CurrentLocale.get(KEY_PFX + partKey, (Object[]) params);
}
@Override
public ConnectorTerminology getConnectorTerminology() {
final ConnectorTerminology terms = new ConnectorTerminology();
terms.setShowArchived(getKey("equella.finduses.showarchived"));
terms.setCourseHeading(getKey("equella.finduses.course"));
terms.setLocationHeading(getKey("equella.finduses.location"));
return terms;
}
@Override
public boolean supportsExport() {
return false;
}
@Override
public boolean supportsEdit() {
return false;
}
@Override
public boolean supportsView() {
return true;
}
@Override
public boolean supportsDelete() {
return false;
}
@Override
public boolean supportsReverseSort() {
return true;
}
@Override
public boolean supportsEditDescription() {
return false;
}
@Override
public boolean deleteContent(Connector connector, String username, String id) {
throw new UnsupportedOperationException("Not supported yet");
}
@Override
public boolean editContent(
Connector connector, String username, String contentId, String title, String description) {
throw new UnsupportedOperationException("Not supported yet");
}
@Override
public boolean moveContent(
Connector connector, String username, String contentId, String courseId, String locationId) {
throw new UnsupportedOperationException("Not supported yet");
}
@Override
public boolean supportsCourses() {
return false;
}
@Override
public boolean supportsFindUses() {
return true;
}
}
| equella/Equella | Source/Plugins/Core/com.equella.core/src/com/tle/core/connectors/equella/service/EquellaConnectorService.java | Java | apache-2.0 | 16,829 |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class InventoryManager : MonoBehaviour
{
public List<InventoryItem> inventoryObjects = new List<InventoryItem>();
public int numCells;
public float height;
public float width;
public float yPosition;
public MissionManager missionManager;
// Use this for initialization
void Start ()
{
GameObject go = GameObject.Find ("Game");
if (go) {
missionManager = go.GetComponent<MissionManager>();
}
}
// Update is called once per frame
void Update () {
}
void onGUI() {
DisplayInventory();
}
void Insert(InteractiveObj iObj)
{
// slot into first available slot.
ObjectInteraction oi = iObj.OnCloseEnough;
InventoryItem ii = new InventoryItem();
ii.item = iObj.gameObject;
ii.quantity = 1;
ii.displayTexture = oi._texture;
ii.item.SetActive(false);
inventoryObjects.Add (ii);
// update mission manager
MissionToken mt = ii.item.GetComponent<MissionToken>();
if (mt!=null) {
_missionManager.add(mt);
}
// if there is a popinfo, instantiate it on pick up.
Instantiate (ii.item.GetComponent<CustomGameObj>().popUpInfo, Vector3.zero, Quaternion.identity);
}
void Add(InteractiveObj iObj)
{
ObjectInteraction oi = iObj.OnCloseEnough;
switch(oi.interactionType)
{
case (ObjectInteraction.InteractionType.Unique):
Insert(iObj);
break;
case (ObjectInteraction.InteractionType.Accumulate):
bool inserted = false;
// find object of same type to increase the count.
CustomGameObj cgo = iObj.gameObject.GetComponent<CustomGameObj>();
CustomGameObj.CustomGameObjectType ot = CustomGameObj.CustomGameObjectType.Invalid;
if (cgo != null) {
ot = cgo.objectType;
}
for (int i = 0; i < inventoryObjects.Count; i++) {
CustomGameObj cgoi = inventoryObjects[i].item.GetComponent<CustomGameObj>();
CustomGameObj.CustomGameObjectType io = CustomGameObj.CustomGameObjectType.Invalid;
if (cgoi != null)
{
io = cgoi.objectType;
}
if (ot == io)
{
inventoryObjects[i].quantity++;
// add token from this object to mission Manager to track it
MissionToken mt = iObj.gameObject.GetComponent<missionToken>();
if (mt != null) {
_missionMgr.add(mt);
}
iObj.gameObject.SetActive(false);
inserted = true;
break;
}
}
// if we get this far, it means a dupe was found in the inventory!
if (inserted) {
Insert(iObj);
}
break;
}
}
/**
* iterates through the inventory and display items
* also gives opportunity to click and 'use' objects (show their popup)
*/
void DisplayInventory()
{
Texture t = null;
float sw = Screen.width;
float sh = Screen.height;
int totalCellsToDisplay = inventoryObjects.Count;
for (int i = 0; i < totalCellsToDisplay; i++)
{
InventoryItem ii = inventoryObjects[i];
t = ii.displayTexture;
int quantity = ii.quantity;
float totalCellLength = sw - (numCells*width);
Rect r = new Rect(totalCellLength - (0.5f * (totalCellLength)) + (width * i),
(yPosition * sh),
width,
height);
if (GUI.Button(r, t))
{
// todo - fill in what to do when user clicks on an item
if (ii.popup == null)
{
ii.popup = (GameObject)Instantiate (ii.item.GetComponent<customGameObject>().popUpInfo, Vector3.zero, Quaternion.identity);
}
else
{
Destroy(ii.popup);
ii.popup = null;
}
}
Rect r2 = new Rect(totalCellLength - 0.5f*(totalCellLength) + (width*i), yPosition*sh, 0.5f*width, 0.5f*height);
string s = quantity.ToString();
GUI.Label(r2, s);
}
}
}
| nycynik/threecees | 3Cs/Assets/GameItems/InventoryManager.cs | C# | apache-2.0 | 3,720 |
package com.example.SimpleGoogleApp;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import ext.android.utils.AppSettings;
import ext.SimpleGoogle.SimpleGoogle;
import ext.java.threading.Callback;
/*
Before you can publish an app that retrieves an OAuth 2.0 token for Google REST APIs, you must register your
Android app with the Google Cloud Console by providing your app's package name and the SHA1 fingerprint of the
keystore with which you sign your release APK.
http://developer.android.com/google/auth/http-auth.html
*/
public class MyActivity extends Activity
{
private SimpleGoogle _simpleGoogle;
private TextView _emailInfo;
private TextView _accessTokenInfo;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button buttonLogin = (Button) findViewById(R.id.button_login);
Button buttonLogout = (Button) findViewById(R.id.button_logout);
Button buttonDisconnect = (Button) findViewById(R.id.button_disconnect);
_emailInfo = (TextView) findViewById(R.id.text_view_email_info);
_accessTokenInfo = (TextView) findViewById(R.id.text_view_access_token_info);
_simpleGoogle = new SimpleGoogle(this, new AppSettings(this));
buttonLogin.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
_simpleGoogle.logIn(new Callback<String>()
{
@Override
public void whenReady(String accessToken)
{
_accessTokenInfo.setText(accessToken);
String userEmail = _simpleGoogle.getUserEmail();
_emailInfo.setText(userEmail);
}
});
}
});
buttonLogout.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
_accessTokenInfo.setText("");
_emailInfo.setText("");
_simpleGoogle.logOut();
}
});
buttonDisconnect.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
_accessTokenInfo.setText("");
_emailInfo.setText("");
_simpleGoogle.disconnect();
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
_simpleGoogle.onActivityResult(requestCode, resultCode, data);
super.onActivityResult(requestCode, resultCode, data);
}
}
| java-extensions/android-simple-google | android-simple-google-demo/src/com/example/SimpleGoogleApp/MyActivity.java | Java | apache-2.0 | 2,919 |
import pytest
from insights.tests import context_wrap
from insights.parsers import ParseException
from insights.parsers.mongod_conf import MongodbConf
NORMAL_CONF = """
# mongodb.conf - generated from Puppet
#where to log
logpath=/var/log/mongodb/mongodb.log
logappend=true
# Set this option to configure the mongod or mongos process to bind to and
# listen for connections from applications on this address.
# You may concatenate a list of comma separated values to bind mongod to multiple IP addresses.
bind_ip = 127.0.0.1
# fork and run in background
fork=true
dbpath=/var/lib/mongodb
# location of pidfile
pidfilepath=/var/run/mongodb/mongodb.pid
# Enables journaling
journal = true
# Turn on/off security. Off is currently the default
noauth=true
abc=
""".strip()
NORMAL_CONF_V1 = """
=/var/log/mongodb/mongodb.log
logappend=true # noauth=true
""".strip()
YAML_CONF = """
# mongod.conf
# for documentation of all options, see:
# http://docs.mongodb.org/manual/reference/configuration-options/
# where to write logging data.
systemLog:
destination: file
logAppend: true
path: /var/log/mongodb/mongod.log
# Where and how to store data.
storage:
dbPath: /var/lib/mongo
journal:
enabled: true
# engine:
# mmapv1:
# wiredTiger:
# how the process runs
processManagement:
fork: true # fork and run in background
pidFilePath: /var/run/mongodb/mongod.pid # location of pidfile
# network interfaces
net:
port: 27017
#bindIp: 127.0.0.1 # Listen to local interface only, comment to listen on all interfaces.
#bindIp: 127.0.0.1 # Listen to local interface only, comment to listen on all interfaces.
#security:
#operationProfiling:
#replication:
#sharding:
## Enterprise-Only Options
#auditLog:
#snmp:
""".strip()
YAML_CONF_UNPARSABLE = """
systemLog:
destination: file
logAppend: true
port=27017
""".strip()
def test_mongodb_conf():
result = MongodbConf(context_wrap(YAML_CONF))
assert result.get("security") is None
assert result.get("processManagement") == {
'fork': True,
'pidFilePath': '/var/run/mongodb/mongod.pid'}
assert result.is_yaml is True
assert result.port == 27017
assert result.bindip is None
assert result.dbpath == '/var/lib/mongo'
assert result.fork is True
assert result.pidfilepath == '/var/run/mongodb/mongod.pid'
assert result.syslog == 'file'
assert result.logpath == '/var/log/mongodb/mongod.log'
result = MongodbConf(context_wrap(NORMAL_CONF))
assert result.is_yaml is False
assert result.port is None
assert result.bindip == '127.0.0.1'
assert result.dbpath == '/var/lib/mongodb'
assert result.fork == 'true'
assert result.pidfilepath == '/var/run/mongodb/mongodb.pid'
assert result.syslog is None
assert result.logpath == '/var/log/mongodb/mongodb.log'
assert result.get("abc") == ''
assert result.get("def") is None
result = MongodbConf(context_wrap(NORMAL_CONF_V1))
assert result.is_yaml is False
assert len(result.data) == 2
assert result.get("logappend") == 'true'
with pytest.raises(ParseException) as e:
MongodbConf(context_wrap(YAML_CONF_UNPARSABLE))
assert "mongod conf parse failed:" in str(e.value)
| wcmitchell/insights-core | insights/parsers/tests/test_mongod_conf.py | Python | apache-2.0 | 3,241 |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 OpenStack Foundation
# 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.
import datetime
import filecmp
import os
import random
import tempfile
import time
import sys
import testtools
import mock
import mox
import glanceclient.exc
from oslo.config import cfg
from nova import context
from nova import exception
from nova.image import glance
from nova import test
from nova.tests.api.openstack import fakes
from nova.tests.glance import stubs as glance_stubs
from nova.tests import matchers
from nova import utils
import nova.virt.libvirt.utils as lv_utils
CONF = cfg.CONF
class NullWriter(object):
"""Used to test ImageService.get which takes a writer object."""
def write(self, *arg, **kwargs):
pass
class TestGlanceSerializer(test.NoDBTestCase):
def test_serialize(self):
metadata = {'name': 'image1',
'is_public': True,
'foo': 'bar',
'properties': {
'prop1': 'propvalue1',
'mappings': [
{'virtual': 'aaa',
'device': 'bbb'},
{'virtual': 'xxx',
'device': 'yyy'}],
'block_device_mapping': [
{'virtual_device': 'fake',
'device_name': '/dev/fake'},
{'virtual_device': 'ephemeral0',
'device_name': '/dev/fake0'}]}}
converted_expected = {
'name': 'image1',
'is_public': True,
'foo': 'bar',
'properties': {
'prop1': 'propvalue1',
'mappings':
'[{"device": "bbb", "virtual": "aaa"}, '
'{"device": "yyy", "virtual": "xxx"}]',
'block_device_mapping':
'[{"virtual_device": "fake", "device_name": "/dev/fake"}, '
'{"virtual_device": "ephemeral0", '
'"device_name": "/dev/fake0"}]'}}
converted = glance._convert_to_string(metadata)
self.assertEqual(converted, converted_expected)
self.assertEqual(glance._convert_from_string(converted), metadata)
class TestGlanceImageService(test.NoDBTestCase):
"""
Tests the Glance image service.
At a high level, the translations involved are:
1. Glance -> ImageService - This is needed so we can support
multple ImageServices (Glance, Local, etc)
2. ImageService -> API - This is needed so we can support multple
APIs (OpenStack, EC2)
"""
NOW_GLANCE_OLD_FORMAT = "2010-10-11T10:30:22"
NOW_GLANCE_FORMAT = "2010-10-11T10:30:22.000000"
class tzinfo(datetime.tzinfo):
@staticmethod
def utcoffset(*args, **kwargs):
return datetime.timedelta()
NOW_DATETIME = datetime.datetime(2010, 10, 11, 10, 30, 22, tzinfo=tzinfo())
def setUp(self):
super(TestGlanceImageService, self).setUp()
fakes.stub_out_compute_api_snapshot(self.stubs)
self.client = glance_stubs.StubGlanceClient()
self.service = self._create_image_service(self.client)
self.context = context.RequestContext('fake', 'fake', auth_token=True)
self.mox = mox.Mox()
self.files_to_clean = []
def tearDown(self):
super(TestGlanceImageService, self).tearDown()
self.mox.UnsetStubs()
for f in self.files_to_clean:
try:
os.unlink(f)
except os.error:
pass
def _get_tempfile(self):
(outfd, config_filename) = tempfile.mkstemp(prefix='nova_glance_tests')
self.files_to_clean.append(config_filename)
return (outfd, config_filename)
def _create_image_service(self, client):
def _fake_create_glance_client(context, host, port, use_ssl, version):
return client
self.stubs.Set(glance, '_create_glance_client',
_fake_create_glance_client)
client_wrapper = glance.GlanceClientWrapper(
'fake', 'fake_host', 9292)
return glance.GlanceImageService(client=client_wrapper)
@staticmethod
def _make_fixture(**kwargs):
fixture = {'name': None,
'properties': {},
'status': None,
'is_public': None}
fixture.update(kwargs)
return fixture
def _make_datetime_fixture(self):
return self._make_fixture(created_at=self.NOW_GLANCE_FORMAT,
updated_at=self.NOW_GLANCE_FORMAT,
deleted_at=self.NOW_GLANCE_FORMAT)
def test_create_with_instance_id(self):
# Ensure instance_id is persisted as an image-property.
fixture = {'name': 'test image',
'is_public': False,
'properties': {'instance_id': '42', 'user_id': 'fake'}}
image_id = self.service.create(self.context, fixture)['id']
image_meta = self.service.show(self.context, image_id)
expected = {
'id': image_id,
'name': 'test image',
'is_public': False,
'size': None,
'min_disk': None,
'min_ram': None,
'disk_format': None,
'container_format': None,
'checksum': None,
'created_at': self.NOW_DATETIME,
'updated_at': self.NOW_DATETIME,
'deleted_at': None,
'deleted': None,
'status': None,
'properties': {'instance_id': '42', 'user_id': 'fake'},
'owner': None,
}
self.assertThat(image_meta, matchers.DictMatches(expected))
image_metas = self.service.detail(self.context)
self.assertThat(image_metas[0], matchers.DictMatches(expected))
def test_create_without_instance_id(self):
"""
Ensure we can create an image without having to specify an
instance_id. Public images are an example of an image not tied to an
instance.
"""
fixture = {'name': 'test image', 'is_public': False}
image_id = self.service.create(self.context, fixture)['id']
expected = {
'id': image_id,
'name': 'test image',
'is_public': False,
'size': None,
'min_disk': None,
'min_ram': None,
'disk_format': None,
'container_format': None,
'checksum': None,
'created_at': self.NOW_DATETIME,
'updated_at': self.NOW_DATETIME,
'deleted_at': None,
'deleted': None,
'status': None,
'properties': {},
'owner': None,
}
actual = self.service.show(self.context, image_id)
self.assertThat(actual, matchers.DictMatches(expected))
def test_create(self):
fixture = self._make_fixture(name='test image')
num_images = len(self.service.detail(self.context))
image_id = self.service.create(self.context, fixture)['id']
self.assertIsNotNone(image_id)
self.assertEqual(num_images + 1,
len(self.service.detail(self.context)))
def test_create_and_show_non_existing_image(self):
fixture = self._make_fixture(name='test image')
image_id = self.service.create(self.context, fixture)['id']
self.assertIsNotNone(image_id)
self.assertRaises(exception.ImageNotFound,
self.service.show,
self.context,
'bad image id')
def test_detail_private_image(self):
fixture = self._make_fixture(name='test image')
fixture['is_public'] = False
properties = {'owner_id': 'proj1'}
fixture['properties'] = properties
self.service.create(self.context, fixture)['id']
proj = self.context.project_id
self.context.project_id = 'proj1'
image_metas = self.service.detail(self.context)
self.context.project_id = proj
self.assertEqual(1, len(image_metas))
self.assertEqual(image_metas[0]['name'], 'test image')
self.assertEqual(image_metas[0]['is_public'], False)
def test_detail_marker(self):
fixtures = []
ids = []
for i in range(10):
fixture = self._make_fixture(name='TestImage %d' % (i))
fixtures.append(fixture)
ids.append(self.service.create(self.context, fixture)['id'])
image_metas = self.service.detail(self.context, marker=ids[1])
self.assertEqual(len(image_metas), 8)
i = 2
for meta in image_metas:
expected = {
'id': ids[i],
'status': None,
'is_public': None,
'name': 'TestImage %d' % (i),
'properties': {},
'size': None,
'min_disk': None,
'min_ram': None,
'disk_format': None,
'container_format': None,
'checksum': None,
'created_at': self.NOW_DATETIME,
'updated_at': self.NOW_DATETIME,
'deleted_at': None,
'deleted': None,
'owner': None,
}
self.assertThat(meta, matchers.DictMatches(expected))
i = i + 1
def test_detail_limit(self):
fixtures = []
ids = []
for i in range(10):
fixture = self._make_fixture(name='TestImage %d' % (i))
fixtures.append(fixture)
ids.append(self.service.create(self.context, fixture)['id'])
image_metas = self.service.detail(self.context, limit=5)
self.assertEqual(len(image_metas), 5)
def test_page_size(self):
with mock.patch.object(glance.GlanceClientWrapper, 'call') as a_mock:
self.service.detail(self.context, page_size=5)
self.assertEqual(a_mock.called, True)
a_mock.assert_called_with(self.context, 1, 'list',
filters={'is_public': 'none'},
page_size=5)
def test_detail_default_limit(self):
fixtures = []
ids = []
for i in range(10):
fixture = self._make_fixture(name='TestImage %d' % (i))
fixtures.append(fixture)
ids.append(self.service.create(self.context, fixture)['id'])
image_metas = self.service.detail(self.context)
for i, meta in enumerate(image_metas):
self.assertEqual(meta['name'], 'TestImage %d' % (i))
def test_detail_marker_and_limit(self):
fixtures = []
ids = []
for i in range(10):
fixture = self._make_fixture(name='TestImage %d' % (i))
fixtures.append(fixture)
ids.append(self.service.create(self.context, fixture)['id'])
image_metas = self.service.detail(self.context, marker=ids[3], limit=5)
self.assertEqual(len(image_metas), 5)
i = 4
for meta in image_metas:
expected = {
'id': ids[i],
'status': None,
'is_public': None,
'name': 'TestImage %d' % (i),
'properties': {},
'size': None,
'min_disk': None,
'min_ram': None,
'disk_format': None,
'container_format': None,
'checksum': None,
'created_at': self.NOW_DATETIME,
'updated_at': self.NOW_DATETIME,
'deleted_at': None,
'deleted': None,
'owner': None,
}
self.assertThat(meta, matchers.DictMatches(expected))
i = i + 1
def test_detail_invalid_marker(self):
fixtures = []
ids = []
for i in range(10):
fixture = self._make_fixture(name='TestImage %d' % (i))
fixtures.append(fixture)
ids.append(self.service.create(self.context, fixture)['id'])
self.assertRaises(exception.Invalid, self.service.detail,
self.context, marker='invalidmarker')
def test_update(self):
fixture = self._make_fixture(name='test image')
image = self.service.create(self.context, fixture)
image_id = image['id']
fixture['name'] = 'new image name'
self.service.update(self.context, image_id, fixture)
new_image_data = self.service.show(self.context, image_id)
self.assertEqual('new image name', new_image_data['name'])
def test_delete(self):
fixture1 = self._make_fixture(name='test image 1')
fixture2 = self._make_fixture(name='test image 2')
fixtures = [fixture1, fixture2]
num_images = len(self.service.detail(self.context))
self.assertEqual(0, num_images)
ids = []
for fixture in fixtures:
new_id = self.service.create(self.context, fixture)['id']
ids.append(new_id)
num_images = len(self.service.detail(self.context))
self.assertEqual(2, num_images)
self.service.delete(self.context, ids[0])
# When you delete an image from glance, it sets the status to DELETED
# and doesn't actually remove the image.
# Check the image is still there.
num_images = len(self.service.detail(self.context))
self.assertEqual(2, num_images)
# Check the image is marked as deleted.
num_images = reduce(lambda x, y: x + (0 if y['deleted'] else 1),
self.service.detail(self.context), 0)
self.assertEqual(1, num_images)
def test_show_passes_through_to_client(self):
fixture = self._make_fixture(name='image1', is_public=True)
image_id = self.service.create(self.context, fixture)['id']
image_meta = self.service.show(self.context, image_id)
expected = {
'id': image_id,
'name': 'image1',
'is_public': True,
'size': None,
'min_disk': None,
'min_ram': None,
'disk_format': None,
'container_format': None,
'checksum': None,
'created_at': self.NOW_DATETIME,
'updated_at': self.NOW_DATETIME,
'deleted_at': None,
'deleted': None,
'status': None,
'properties': {},
'owner': None,
}
self.assertEqual(image_meta, expected)
def test_show_raises_when_no_authtoken_in_the_context(self):
fixture = self._make_fixture(name='image1',
is_public=False,
properties={'one': 'two'})
image_id = self.service.create(self.context, fixture)['id']
self.context.auth_token = False
self.assertRaises(exception.ImageNotFound,
self.service.show,
self.context,
image_id)
def test_detail_passes_through_to_client(self):
fixture = self._make_fixture(name='image10', is_public=True)
image_id = self.service.create(self.context, fixture)['id']
image_metas = self.service.detail(self.context)
expected = [
{
'id': image_id,
'name': 'image10',
'is_public': True,
'size': None,
'min_disk': None,
'min_ram': None,
'disk_format': None,
'container_format': None,
'checksum': None,
'created_at': self.NOW_DATETIME,
'updated_at': self.NOW_DATETIME,
'deleted_at': None,
'deleted': None,
'status': None,
'properties': {},
'owner': None,
},
]
self.assertEqual(image_metas, expected)
def test_show_makes_datetimes(self):
fixture = self._make_datetime_fixture()
image_id = self.service.create(self.context, fixture)['id']
image_meta = self.service.show(self.context, image_id)
self.assertEqual(image_meta['created_at'], self.NOW_DATETIME)
self.assertEqual(image_meta['updated_at'], self.NOW_DATETIME)
def test_detail_makes_datetimes(self):
fixture = self._make_datetime_fixture()
self.service.create(self.context, fixture)
image_meta = self.service.detail(self.context)[0]
self.assertEqual(image_meta['created_at'], self.NOW_DATETIME)
self.assertEqual(image_meta['updated_at'], self.NOW_DATETIME)
def test_download_with_retries(self):
tries = [0]
class MyGlanceStubClient(glance_stubs.StubGlanceClient):
"""A client that fails the first time, then succeeds."""
def get(self, image_id):
if tries[0] == 0:
tries[0] = 1
raise glanceclient.exc.ServiceUnavailable('')
else:
return {}
client = MyGlanceStubClient()
service = self._create_image_service(client)
image_id = 1 # doesn't matter
writer = NullWriter()
# When retries are disabled, we should get an exception
self.flags(glance_num_retries=0)
self.assertRaises(exception.GlanceConnectionFailed,
service.download, self.context, image_id, data=writer)
# Now lets enable retries. No exception should happen now.
tries = [0]
self.flags(glance_num_retries=1)
service.download(self.context, image_id, data=writer)
def test_download_file_url(self):
self.flags(allowed_direct_url_schemes=['file'])
class MyGlanceStubClient(glance_stubs.StubGlanceClient):
"""A client that returns a file url."""
(outfd, s_tmpfname) = tempfile.mkstemp(prefix='directURLsrc')
outf = os.fdopen(outfd, 'w')
inf = open('/dev/urandom', 'r')
for i in range(10):
_data = inf.read(1024)
outf.write(_data)
outf.close()
def get(self, image_id):
return type('GlanceTestDirectUrlMeta', (object,),
{'direct_url': 'file://%s' + self.s_tmpfname})
client = MyGlanceStubClient()
(outfd, tmpfname) = tempfile.mkstemp(prefix='directURLdst')
os.close(outfd)
service = self._create_image_service(client)
image_id = 1 # doesn't matter
service.download(self.context, image_id, dst_path=tmpfname)
# compare the two files
rc = filecmp.cmp(tmpfname, client.s_tmpfname)
self.assertTrue(rc, "The file %s and %s should be the same" %
(tmpfname, client.s_tmpfname))
os.remove(client.s_tmpfname)
os.remove(tmpfname)
def test_download_module_filesystem_match(self):
mountpoint = '/'
fs_id = 'someid'
desc = {'id': fs_id, 'mountpoint': mountpoint}
class MyGlanceStubClient(glance_stubs.StubGlanceClient):
outer_test = self
def get(self, image_id):
return type('GlanceLocations', (object,),
{'locations': [
{'url': 'file:///' + os.devnull,
'metadata': desc}]})
def data(self, image_id):
self.outer_test.fail('This should not be called because the '
'transfer module should have intercepted '
'it.')
self.mox.StubOutWithMock(lv_utils, 'copy_image')
image_id = 1 # doesn't matter
client = MyGlanceStubClient()
self.flags(allowed_direct_url_schemes=['file'])
self.flags(group='image_file_url', filesystems=['gluster'])
service = self._create_image_service(client)
#NOTE(Jbresnah) The following options must be added after the module
# has added the specific groups.
self.flags(group='image_file_url:gluster', id=fs_id)
self.flags(group='image_file_url:gluster', mountpoint=mountpoint)
dest_file = os.devnull
lv_utils.copy_image(mox.IgnoreArg(), dest_file)
self.mox.ReplayAll()
service.download(self.context, image_id, dst_path=dest_file)
self.mox.VerifyAll()
def test_download_module_no_filesystem_match(self):
mountpoint = '/'
fs_id = 'someid'
desc = {'id': fs_id, 'mountpoint': mountpoint}
some_data = "sfxvdwjer"
class MyGlanceStubClient(glance_stubs.StubGlanceClient):
outer_test = self
def get(self, image_id):
return type('GlanceLocations', (object,),
{'locations': [
{'url': 'file:///' + os.devnull,
'metadata': desc}]})
def data(self, image_id):
return some_data
def _fake_copyfile(source, dest):
self.fail('This should not be called because a match should not '
'have been found.')
self.stubs.Set(lv_utils, 'copy_image', _fake_copyfile)
image_id = 1 # doesn't matter
client = MyGlanceStubClient()
self.flags(allowed_direct_url_schemes=['file'])
self.flags(group='image_file_url', filesystems=['gluster'])
service = self._create_image_service(client)
#NOTE(Jbresnah) The following options must be added after the module
# has added the specific groups.
self.flags(group='image_file_url:gluster', id='someotherid')
self.flags(group='image_file_url:gluster', mountpoint=mountpoint)
service.download(self.context, image_id,
dst_path=os.devnull,
data=None)
def test_download_module_mountpoints(self):
glance_mount = '/glance/mount/point'
_, data_filename = self._get_tempfile()
nova_mount = os.path.dirname(data_filename)
source_path = os.path.basename(data_filename)
file_url = 'file://%s' % os.path.join(glance_mount, source_path)
file_system_id = 'test_FS_ID'
file_system_desc = {'id': file_system_id, 'mountpoint': glance_mount}
class MyGlanceStubClient(glance_stubs.StubGlanceClient):
outer_test = self
def get(self, image_id):
return type('GlanceLocations', (object,),
{'locations': [{'url': file_url,
'metadata': file_system_desc}]})
def data(self, image_id):
self.outer_test.fail('This should not be called because the '
'transfer module should have intercepted '
'it.')
self.copy_called = False
def _fake_copyfile(source, dest):
self.assertEqual(source, data_filename)
self.copy_called = True
self.stubs.Set(lv_utils, 'copy_image', _fake_copyfile)
self.flags(allowed_direct_url_schemes=['file'])
self.flags(group='image_file_url', filesystems=['gluster'])
image_id = 1 # doesn't matter
client = MyGlanceStubClient()
service = self._create_image_service(client)
self.flags(group='image_file_url:gluster', id=file_system_id)
self.flags(group='image_file_url:gluster', mountpoint=nova_mount)
service.download(self.context, image_id, dst_path=os.devnull)
self.assertTrue(self.copy_called)
def test_download_module_file_bad_module(self):
_, data_filename = self._get_tempfile()
file_url = 'applesauce://%s' % data_filename
data_called = False
class MyGlanceStubClient(glance_stubs.StubGlanceClient):
data_called = False
def get(self, image_id):
return type('GlanceLocations', (object,),
{'locations': [{'url': file_url,
'metadata': {}}]})
def data(self, image_id):
self.data_called = True
return "someData"
self.flags(allowed_direct_url_schemes=['applesauce'])
self.mox.StubOutWithMock(lv_utils, 'copy_image')
self.flags(allowed_direct_url_schemes=['file'])
image_id = 1 # doesn't matter
client = MyGlanceStubClient()
service = self._create_image_service(client)
# by not calling copyfileobj in the file download module we verify
# that the requirements were not met for its use
self.mox.ReplayAll()
service.download(self.context, image_id, dst_path=os.devnull)
self.mox.VerifyAll()
self.assertTrue(client.data_called)
def test_client_forbidden_converts_to_imagenotauthed(self):
class MyGlanceStubClient(glance_stubs.StubGlanceClient):
"""A client that raises a Forbidden exception."""
def get(self, image_id):
raise glanceclient.exc.Forbidden(image_id)
client = MyGlanceStubClient()
service = self._create_image_service(client)
image_id = 1 # doesn't matter
self.assertRaises(exception.ImageNotAuthorized, service.download,
self.context, image_id, dst_path=os.devnull)
def test_client_httpforbidden_converts_to_imagenotauthed(self):
class MyGlanceStubClient(glance_stubs.StubGlanceClient):
"""A client that raises a HTTPForbidden exception."""
def get(self, image_id):
raise glanceclient.exc.HTTPForbidden(image_id)
client = MyGlanceStubClient()
service = self._create_image_service(client)
image_id = 1 # doesn't matter
self.assertRaises(exception.ImageNotAuthorized, service.download,
self.context, image_id, dst_path=os.devnull)
def test_client_notfound_converts_to_imagenotfound(self):
class MyGlanceStubClient(glance_stubs.StubGlanceClient):
"""A client that raises a NotFound exception."""
def get(self, image_id):
raise glanceclient.exc.NotFound(image_id)
client = MyGlanceStubClient()
service = self._create_image_service(client)
image_id = 1 # doesn't matter
self.assertRaises(exception.ImageNotFound, service.download,
self.context, image_id, dst_path=os.devnull)
def test_client_httpnotfound_converts_to_imagenotfound(self):
class MyGlanceStubClient(glance_stubs.StubGlanceClient):
"""A client that raises a HTTPNotFound exception."""
def get(self, image_id):
raise glanceclient.exc.HTTPNotFound(image_id)
client = MyGlanceStubClient()
service = self._create_image_service(client)
image_id = 1 # doesn't matter
self.assertRaises(exception.ImageNotFound, service.download,
self.context, image_id, dst_path=os.devnull)
def test_glance_client_image_id(self):
fixture = self._make_fixture(name='test image')
image_id = self.service.create(self.context, fixture)['id']
(service, same_id) = glance.get_remote_image_service(
self.context, image_id)
self.assertEqual(same_id, image_id)
def test_glance_client_image_ref(self):
fixture = self._make_fixture(name='test image')
image_id = self.service.create(self.context, fixture)['id']
image_url = 'http://something-less-likely/%s' % image_id
(service, same_id) = glance.get_remote_image_service(
self.context, image_url)
self.assertEqual(same_id, image_id)
self.assertEqual(service._client.host, 'something-less-likely')
def _create_failing_glance_client(info):
class MyGlanceStubClient(glance_stubs.StubGlanceClient):
"""A client that fails the first time, then succeeds."""
def get(self, image_id):
info['num_calls'] += 1
if info['num_calls'] == 1:
raise glanceclient.exc.ServiceUnavailable('')
return {}
return MyGlanceStubClient()
class TestGlanceClientWrapper(test.NoDBTestCase):
def setUp(self):
super(TestGlanceClientWrapper, self).setUp()
# host1 has no scheme, which is http by default
self.flags(glance_api_servers=['host1:9292', 'https://host2:9293',
'http://host3:9294'])
# Make the test run fast
def _fake_sleep(secs):
pass
self.stubs.Set(time, 'sleep', _fake_sleep)
def test_headers_passed_glanceclient(self):
auth_token = 'auth_token'
ctxt = context.RequestContext('fake', 'fake', auth_token=auth_token)
fake_host = 'host4'
fake_port = 9295
fake_use_ssl = False
def _get_fake_glanceclient(version, endpoint, **params):
fake_client = glance_stubs.StubGlanceClient(version,
endpoint, **params)
self.assertIsNotNone(fake_client.auth_token)
self.assertIsNotNone(fake_client.identity_headers)
self.assertEqual(fake_client.identity_header['X-Auth_Token'],
auth_token)
self.assertEqual(fake_client.identity_header['X-User-Id'], 'fake')
self.assertIsNone(fake_client.identity_header['X-Roles'])
self.assertIsNone(fake_client.identity_header['X-Tenant-Id'])
self.assertIsNone(fake_client.identity_header['X-Service-Catalog'])
self.assertEqual(fake_client.
identity_header['X-Identity-Status'],
'Confirmed')
self.stubs.Set(glanceclient.Client, '__init__',
_get_fake_glanceclient)
glance._create_glance_client(ctxt, fake_host, fake_port, fake_use_ssl)
def test_static_client_without_retries(self):
self.flags(glance_num_retries=0)
ctxt = context.RequestContext('fake', 'fake')
fake_host = 'host4'
fake_port = 9295
fake_use_ssl = False
info = {'num_calls': 0}
def _fake_create_glance_client(context, host, port, use_ssl, version):
self.assertEqual(host, fake_host)
self.assertEqual(port, fake_port)
self.assertEqual(use_ssl, fake_use_ssl)
return _create_failing_glance_client(info)
self.stubs.Set(glance, '_create_glance_client',
_fake_create_glance_client)
client = glance.GlanceClientWrapper(context=ctxt,
host=fake_host, port=fake_port, use_ssl=fake_use_ssl)
self.assertRaises(exception.GlanceConnectionFailed,
client.call, ctxt, 1, 'get', 'meow')
self.assertEqual(info['num_calls'], 1)
def test_default_client_without_retries(self):
self.flags(glance_num_retries=0)
ctxt = context.RequestContext('fake', 'fake')
info = {'num_calls': 0,
'host': 'host1',
'port': 9292,
'use_ssl': False}
# Leave the list in a known-order
def _fake_shuffle(servers):
pass
def _fake_create_glance_client(context, host, port, use_ssl, version):
self.assertEqual(host, info['host'])
self.assertEqual(port, info['port'])
self.assertEqual(use_ssl, info['use_ssl'])
return _create_failing_glance_client(info)
self.stubs.Set(random, 'shuffle', _fake_shuffle)
self.stubs.Set(glance, '_create_glance_client',
_fake_create_glance_client)
client = glance.GlanceClientWrapper()
client2 = glance.GlanceClientWrapper()
self.assertRaises(exception.GlanceConnectionFailed,
client.call, ctxt, 1, 'get', 'meow')
self.assertEqual(info['num_calls'], 1)
info = {'num_calls': 0,
'host': 'host2',
'port': 9293,
'use_ssl': True}
def _fake_shuffle2(servers):
# fake shuffle in a known manner
servers.append(servers.pop(0))
self.stubs.Set(random, 'shuffle', _fake_shuffle2)
self.assertRaises(exception.GlanceConnectionFailed,
client2.call, ctxt, 1, 'get', 'meow')
self.assertEqual(info['num_calls'], 1)
def test_static_client_with_retries(self):
self.flags(glance_num_retries=1)
ctxt = context.RequestContext('fake', 'fake')
fake_host = 'host4'
fake_port = 9295
fake_use_ssl = False
info = {'num_calls': 0}
def _fake_create_glance_client(context, host, port, use_ssl, version):
self.assertEqual(host, fake_host)
self.assertEqual(port, fake_port)
self.assertEqual(use_ssl, fake_use_ssl)
return _create_failing_glance_client(info)
self.stubs.Set(glance, '_create_glance_client',
_fake_create_glance_client)
client = glance.GlanceClientWrapper(context=ctxt,
host=fake_host, port=fake_port, use_ssl=fake_use_ssl)
client.call(ctxt, 1, 'get', 'meow')
self.assertEqual(info['num_calls'], 2)
def test_default_client_with_retries(self):
self.flags(glance_num_retries=1)
ctxt = context.RequestContext('fake', 'fake')
info = {'num_calls': 0,
'host0': 'host1',
'port0': 9292,
'use_ssl0': False,
'host1': 'host2',
'port1': 9293,
'use_ssl1': True}
# Leave the list in a known-order
def _fake_shuffle(servers):
pass
def _fake_create_glance_client(context, host, port, use_ssl, version):
attempt = info['num_calls']
self.assertEqual(host, info['host%s' % attempt])
self.assertEqual(port, info['port%s' % attempt])
self.assertEqual(use_ssl, info['use_ssl%s' % attempt])
return _create_failing_glance_client(info)
self.stubs.Set(random, 'shuffle', _fake_shuffle)
self.stubs.Set(glance, '_create_glance_client',
_fake_create_glance_client)
client = glance.GlanceClientWrapper()
client2 = glance.GlanceClientWrapper()
client.call(ctxt, 1, 'get', 'meow')
self.assertEqual(info['num_calls'], 2)
def _fake_shuffle2(servers):
# fake shuffle in a known manner
servers.append(servers.pop(0))
self.stubs.Set(random, 'shuffle', _fake_shuffle2)
info = {'num_calls': 0,
'host0': 'host2',
'port0': 9293,
'use_ssl0': True,
'host1': 'host3',
'port1': 9294,
'use_ssl1': False}
client2.call(ctxt, 1, 'get', 'meow')
self.assertEqual(info['num_calls'], 2)
class TestGlanceUrl(test.NoDBTestCase):
def test_generate_glance_http_url(self):
generated_url = glance.generate_glance_url()
glance_host = CONF.glance_host
# ipv6 address, need to wrap it with '[]'
if utils.is_valid_ipv6(glance_host):
glance_host = '[%s]' % glance_host
http_url = "http://%s:%d" % (glance_host, CONF.glance_port)
self.assertEqual(generated_url, http_url)
def test_generate_glance_https_url(self):
self.flags(glance_protocol="https")
generated_url = glance.generate_glance_url()
glance_host = CONF.glance_host
# ipv6 address, need to wrap it with '[]'
if utils.is_valid_ipv6(glance_host):
glance_host = '[%s]' % glance_host
https_url = "https://%s:%d" % (glance_host, CONF.glance_port)
self.assertEqual(generated_url, https_url)
class TestGlanceApiServers(test.TestCase):
def test_get_ipv4_api_servers(self):
self.flags(glance_api_servers=['10.0.1.1:9292',
'https://10.0.0.1:9293',
'http://10.0.2.2:9294'])
glance_host = ['10.0.1.1', '10.0.0.1',
'10.0.2.2']
api_servers = glance.get_api_servers()
i = 0
for server in api_servers:
i += 1
self.assertIn(server[0], glance_host)
if i > 2:
break
# Python 2.6 can not parse ipv6 address correctly
@testtools.skipIf(sys.version_info < (2, 7), "py27 or greater only")
def test_get_ipv6_api_servers(self):
self.flags(glance_api_servers=['[2001:2012:1:f101::1]:9292',
'https://[2010:2013:1:f122::1]:9293',
'http://[2001:2011:1:f111::1]:9294'])
glance_host = ['2001:2012:1:f101::1', '2010:2013:1:f122::1',
'2001:2011:1:f111::1']
api_servers = glance.get_api_servers()
i = 0
for server in api_servers:
i += 1
self.assertIn(server[0], glance_host)
if i > 2:
break
class TestUpdateGlanceImage(test.NoDBTestCase):
def test_start(self):
consumer = glance.UpdateGlanceImage(
'context', 'id', 'metadata', 'stream')
image_service = self.mox.CreateMock(glance.GlanceImageService)
self.mox.StubOutWithMock(glance, 'get_remote_image_service')
glance.get_remote_image_service(
'context', 'id').AndReturn((image_service, 'image_id'))
image_service.update(
'context', 'image_id', 'metadata', 'stream', purge_props=False)
self.mox.ReplayAll()
consumer.start()
| sacharya/nova | nova/tests/image/test_glance.py | Python | apache-2.0 | 38,559 |
/*
* Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH
* under one or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. Camunda licenses this file to you under the Apache License,
* Version 2.0; you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.camunda.bpm.engine.test.api.multitenancy;
import static org.camunda.bpm.engine.test.util.ActivityInstanceAssert.assertThat;
import static org.camunda.bpm.engine.test.util.ActivityInstanceAssert.describeActivityInstanceTree;
import static org.camunda.bpm.engine.test.util.ExecutionAssert.assertThat;
import static org.camunda.bpm.engine.test.util.ExecutionAssert.describeExecutionTree;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.util.List;
import org.camunda.bpm.engine.ManagementService;
import org.camunda.bpm.engine.RepositoryService;
import org.camunda.bpm.engine.RuntimeService;
import org.camunda.bpm.engine.TaskService;
import org.camunda.bpm.engine.batch.Batch;
import org.camunda.bpm.engine.impl.cfg.ProcessEngineConfigurationImpl;
import org.camunda.bpm.engine.repository.ProcessDefinition;
import org.camunda.bpm.engine.runtime.ActivityInstance;
import org.camunda.bpm.engine.runtime.Job;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.camunda.bpm.engine.task.Task;
import org.camunda.bpm.engine.test.ProcessEngineRule;
import org.camunda.bpm.engine.test.util.ExecutionTree;
import org.camunda.bpm.engine.test.util.ProcessEngineTestRule;
import org.camunda.bpm.engine.test.util.ProvidedProcessEngineRule;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.rules.RuleChain;
import junit.framework.AssertionFailedError;
public class MultiTenancySingleProcessInstanceModificationAsyncTest {
protected static final String PARALLEL_GATEWAY_PROCESS = "org/camunda/bpm/engine/test/api/runtime/ProcessInstanceModificationTest.parallelGateway.bpmn20.xml";
protected static final String TENANT_ONE = "tenant1";
protected ProcessEngineRule engineRule = new ProvidedProcessEngineRule();
protected ProcessEngineTestRule testRule = new ProcessEngineTestRule(engineRule);
@Rule
public RuleChain ruleChain = RuleChain.outerRule(engineRule).around(testRule);
@Rule
public ExpectedException thrown= ExpectedException.none();
protected ProcessEngineConfigurationImpl processEngineConfiguration;
protected RepositoryService repositoryService;
protected RuntimeService runtimeService;
protected ManagementService managementService;
protected TaskService taskService;
@Before
public void init() {
processEngineConfiguration = engineRule.getProcessEngineConfiguration();
repositoryService = engineRule.getRepositoryService();
runtimeService = engineRule.getRuntimeService();
managementService = engineRule.getManagementService();
taskService = engineRule.getTaskService();
}
@After
public void tearDown() {
List<Batch> batches = managementService.createBatchQuery().list();
for (Batch batch : batches) {
managementService.deleteBatch(batch.getId(), true);
}
List<Job> jobs = managementService.createJobQuery().list();
for (Job job : jobs) {
managementService.deleteJob(job.getId());
}
}
@Test
public void testModificationSameTenant() {
// given
testRule.deployForTenant(TENANT_ONE, PARALLEL_GATEWAY_PROCESS);
ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("parallelGateway");
String processInstanceId = processInstance.getId();
String processDefinitionId = processInstance.getProcessDefinitionId();
ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().processDefinitionId(processDefinitionId).singleResult();
ActivityInstance tree = runtimeService.getActivityInstance(processInstance.getId());
// when
Batch modificationBatch = runtimeService.createProcessInstanceModification(processInstance.getId())
.cancelActivityInstance(getInstanceIdForActivity(tree, "task1"))
.executeAsync();
assertNotNull(modificationBatch);
assertEquals(TENANT_ONE, modificationBatch.getTenantId());
Job job = managementService.createJobQuery().jobDefinitionId(modificationBatch.getSeedJobDefinitionId()).singleResult();
// seed job
assertEquals(TENANT_ONE, job.getTenantId());
managementService.executeJob(job.getId());
for (Job pending : managementService.createJobQuery().jobDefinitionId(modificationBatch.getBatchJobDefinitionId()).list()) {
managementService.executeJob(pending.getId());
assertEquals(processDefinition.getDeploymentId(), pending.getDeploymentId());
assertEquals(TENANT_ONE, pending.getTenantId());
}
// when
ActivityInstance updatedTree = runtimeService.getActivityInstance(processInstanceId);
assertNotNull(updatedTree);
assertEquals(processInstanceId, updatedTree.getProcessInstanceId());
assertThat(updatedTree).hasStructure(describeActivityInstanceTree(processInstance.getProcessDefinitionId()).activity("task2").done());
ExecutionTree executionTree = ExecutionTree.forExecution(processInstanceId, processEngineConfiguration.getProcessEngine());
assertThat(executionTree).matches(describeExecutionTree("task2").scope().done());
// complete the process
completeTasksInOrder("task2");
assertProcessEnded(processInstanceId);
}
protected String getInstanceIdForActivity(ActivityInstance activityInstance, String activityId) {
ActivityInstance instance = getChildInstanceForActivity(activityInstance, activityId);
if (instance != null) {
return instance.getId();
}
return null;
}
protected ActivityInstance getChildInstanceForActivity(ActivityInstance activityInstance, String activityId) {
if (activityId.equals(activityInstance.getActivityId())) {
return activityInstance;
}
for (ActivityInstance childInstance : activityInstance.getChildActivityInstances()) {
ActivityInstance instance = getChildInstanceForActivity(childInstance, activityId);
if (instance != null) {
return instance;
}
}
return null;
}
protected void completeTasksInOrder(String... taskNames) {
for (String taskName : taskNames) {
// complete any task with that name
List<Task> tasks = taskService.createTaskQuery().taskDefinitionKey(taskName).listPage(0, 1);
assertTrue("task for activity " + taskName + " does not exist", !tasks.isEmpty());
taskService.complete(tasks.get(0).getId());
}
}
protected void assertProcessEnded(final String processInstanceId) {
ProcessInstance processInstance = runtimeService
.createProcessInstanceQuery()
.processInstanceId(processInstanceId)
.singleResult();
if (processInstance!=null) {
throw new AssertionFailedError("Expected finished process instance '"+processInstanceId+"' but it was still in the db");
}
}
}
| falko/camunda-bpm-platform | engine/src/test/java/org/camunda/bpm/engine/test/api/multitenancy/MultiTenancySingleProcessInstanceModificationAsyncTest.java | Java | apache-2.0 | 7,828 |
/*
* Copyright (c) 2016-2018, Christoph Engelbert (aka noctarius) and
* contributors. 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.noctarius.borabora.impl;
import org.junit.Test;
import java.io.ByteArrayInputStream;
import java.io.StringReader;
import java.lang.reflect.Field;
public class QueryParserCoverageTestCase {
@Test
public void code_coverage_for_unused_but_generated_methods()
throws Exception {
ByteArrayInputStream stream = new ByteArrayInputStream(new byte[0]);
QueryParser qp = new QueryParser(stream);
qp.ReInit(stream);
qp = new QueryParser(new StringReader(""));
Field token_source = QueryParser.class.getDeclaredField("token_source");
token_source.setAccessible(true);
token_source.set(qp, null);
qp.ReInit(new StringReader(""));
QueryParserTokenManager tm = new QueryParserTokenManager(new JavaCharStream(new StringReader("")));
qp = new QueryParser(tm);
qp.ReInit(tm);
qp.enable_tracing();
qp.disable_tracing();
qp.ReInit(new StringReader("#"));
qp.getToken(0);
qp.getToken(1);
qp.ReInit(new StringReader("#"));
Token token;
while ((token = qp.getNextToken()) != null) {
if (token.next == null) {
break;
}
}
}
}
| noctarius/borabora | src/test/java/com/noctarius/borabora/impl/QueryParserCoverageTestCase.java | Java | apache-2.0 | 1,914 |
package ru.spbau.svidchenko.asteroids_project.game_logic.player;
import ru.spbau.svidchenko.asteroids_project.game_logic.world.Entity;
import ru.spbau.svidchenko.asteroids_project.game_logic.world.RelativeWorldModel;
import ru.spbau.svidchenko.asteroids_project.game_logic.world.Ship;
import java.util.List;
public abstract class Player {
protected long id;
protected RelativeWorldModel worldModel;
public Player(long id) {
this.id = id;
}
public abstract List<? extends Entity> makeAction();
public void incScore(long reward) {}
public RelativeWorldModel getWorldModel() {
return worldModel;
}
public void setRelativeWorldModel(RelativeWorldModel worldModel) {
this.worldModel = worldModel;
}
}
| ArgentumWalker/asteroids-project | game-logic/src/main/java/ru/spbau/svidchenko/asteroids_project/game_logic/player/Player.java | Java | apache-2.0 | 769 |
# Copyright 2022 Google LLC
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from google.cloud import asset_v1
from google.protobuf.json_format import MessageToDict
import click
import time
import json
def all_iam_policies(org_id, as_dict=True):
policies = []
scope = "organizations/{org_id}".format(org_id=org_id)
click.secho(
"Fetching IAM Policies from CAI API using scope {scope}".format(
scope=scope
)
)
client = asset_v1.AssetServiceClient()
response = client.search_all_iam_policies(
request={
"scope": scope,
"page_size": 500,
}
)
for policy in response:
if as_dict:
policies.append(MessageToDict(policy.__class__.pb(policy)))
else:
policies.append(policy)
return policies
def fetch_cai_file(org_id):
if not org_id:
raise SystemExit(
"ERROR: No org id provided. Set the ORG_ID environment variable or pass the --org-id parameter."
)
all_policies = all_iam_policies(org_id)
timestamp = int(time.time())
filename = "cai-iam-{timestamp}.json".format(timestamp=timestamp)
f = open(filename, "w")
json.dump(all_policies, f)
click.secho("Created inventory file {filename}.".format(filename=filename))
return filename | GoogleCloudPlatform/professional-services | tools/iam-permissions-copier/inventory/cai.py | Python | apache-2.0 | 1,851 |
/*
* Copyright 2016 Fixstars 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.
*/
#ifndef M3BP_TEST_UTIL_PROCESSORS_INPUT_DESERIALIZER_HPP
#define M3BP_TEST_UTIL_PROCESSORS_INPUT_DESERIALIZER_HPP
#include <vector>
#include <cstdint>
#include "m3bp/input_reader.hpp"
#include "m3bp/input_buffer.hpp"
#include "util/binary_util.hpp"
namespace util {
namespace processors {
template <typename T>
std::vector<T> deserialize_value_only_buffer(m3bp::InputReader &reader){
const auto buffer = reader.raw_buffer();
const auto num_records = buffer.record_count();
const auto ptr = static_cast<const uint8_t *>(buffer.key_buffer());
const auto offsets = buffer.key_offset_table();
std::vector<T> result(num_records);
for(m3bp::identifier_type i = 0; i < num_records; ++i){
result[i] = read_binary<T>(ptr + offsets[i]).first;
}
return result;
}
template <typename KeyType, typename ValueType>
std::vector<std::pair<KeyType, std::vector<ValueType>>>
deserialize_grouped_buffer(m3bp::InputReader &reader){
using GroupType = std::pair<KeyType, std::vector<ValueType>>;
const auto buffer = reader.raw_buffer();
const auto num_groups = buffer.record_count();
const auto key_ptr = static_cast<const uint8_t *>(buffer.key_buffer());
const auto key_offsets = buffer.key_offset_table();
const auto value_ptr = static_cast<const uint8_t *>(buffer.value_buffer());
const auto value_offsets = buffer.value_offset_table();
std::vector<GroupType> result;
for(m3bp::identifier_type i = 0; i < num_groups; ++i){
const auto key = read_binary<KeyType>(key_ptr + key_offsets[i]);
std::vector<ValueType> values;
const auto head = value_offsets[i], tail = value_offsets[i + 1];
for(m3bp::size_type cur = head; cur < tail; ){
const auto x = read_binary<ValueType>(value_ptr + cur);
values.push_back(x.first);
cur += x.second;
}
result.emplace_back(key.first, std::move(values));
}
return result;
}
}
}
#endif
| fixstars/m3bp | test/util/processors/input_deserializer.hpp | C++ | apache-2.0 | 2,449 |
/*
* Copyright 2012-2016 The Pkcs11Interop Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Written for the Pkcs11Interop project by:
* Jaroslav IMRICH <jimrich@jimrich.sk>
*/
using Net.Pkcs11Interop.Common;
using Net.Pkcs11Interop.HighLevelAPI81;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Net.Pkcs11Interop.Tests.HighLevelAPI81
{
/// <summary>
/// GetOperationState and SetOperationState tests.
/// </summary>
[TestClass]
public class _07_OperationStateTest
{
/// <summary>
/// Basic GetOperationState and SetOperationState test.
/// </summary>
[TestMethod]
public void _01_BasicOperationStateTest()
{
if (Platform.UnmanagedLongSize != 8 || Platform.StructPackingSize != 1)
Assert.Inconclusive("Test cannot be executed on this platform");
using (Pkcs11 pkcs11 = new Pkcs11(Settings.Pkcs11LibraryPath, Settings.UseOsLocking))
{
// Find first slot with token present
Slot slot = Helpers.GetUsableSlot(pkcs11);
// Open RO (read-only) session
using (Session session = slot.OpenSession(true))
{
// Get operation state
byte[] state = session.GetOperationState();
// Do something interesting with operation state
Assert.IsNotNull(state);
// Let's set state so the test is complete
// Note that CK_INVALID_HANDLE is passed in as encryptionKey and authenticationKey
session.SetOperationState(state, new ObjectHandle(), new ObjectHandle());
}
}
}
}
}
| thearkhelist/Pkcs11Interop | src/Pkcs11Interop/TestProject1/HighLevelAPI81/_07_OperationStateTest.cs | C# | apache-2.0 | 2,312 |
<?php
/**
* @copyright Copyright (c) 2014 X.commerce, Inc. (http://www.magentocommerce.com)
*/
namespace Magento\Backend\Model\Config\Structure\Element\Group;
class Proxy extends \Magento\Backend\Model\Config\Structure\Element\Group
{
/**
* Object manager
* @var \Magento\Framework\ObjectManagerInterface
*/
protected $_objectManager;
/**
* @var \Magento\Backend\Model\Config\Structure\Element\Group
*/
protected $_subject;
/**
* @param \Magento\Framework\ObjectManagerInterface $objectManger
*/
public function __construct(\Magento\Framework\ObjectManagerInterface $objectManger)
{
$this->_objectManager = $objectManger;
}
/**
* Retrieve subject
*
* @return \Magento\Backend\Model\Config\Structure\Element\Group
*/
protected function _getSubject()
{
if (!$this->_subject) {
$this->_subject = $this->_objectManager->create('Magento\Backend\Model\Config\Structure\Element\Group');
}
return $this->_subject;
}
/**
* Set element data
*
* @param array $data
* @param string $scope
* @return void
*/
public function setData(array $data, $scope)
{
$this->_getSubject()->setData($data, $scope);
}
/**
* Retrieve element id
*
* @return string
*/
public function getId()
{
return $this->_getSubject()->getId();
}
/**
* Retrieve element label
*
* @return string
*/
public function getLabel()
{
return $this->_getSubject()->getLabel();
}
/**
* Retrieve element label
*
* @return string
*/
public function getComment()
{
return $this->_getSubject()->getComment();
}
/**
* Retrieve frontend model class name
*
* @return string
*/
public function getFrontendModel()
{
return $this->_getSubject()->getFrontendModel();
}
/**
* Retrieve arbitrary element attribute
*
* @param string $key
* @return mixed
*/
public function getAttribute($key)
{
return $this->_getSubject()->getAttribute($key);
}
/**
* Check whether section is allowed for current user
*
* @return bool
*/
public function isAllowed()
{
return $this->_getSubject()->isAllowed();
}
/**
* Check whether element should be displayed
*
* @param string $websiteCode
* @param string $storeCode
* @return bool
*/
public function isVisible($websiteCode = '', $storeCode = '')
{
return $this->_getSubject()->isVisible($websiteCode, $storeCode);
}
/**
* Retrieve css class of a tab
*
* @return string
*/
public function getClass()
{
return $this->_getSubject()->getClass();
}
/**
* Check whether element has visible child elements
*
* @return bool
*/
public function hasChildren()
{
return $this->_getSubject()->hasChildren();
}
/**
* Retrieve children iterator
*
* @return \Magento\Backend\Model\Config\Structure\Element\Iterator
*/
public function getChildren()
{
return $this->_getSubject()->getChildren();
}
/**
* Should group fields be cloned
*
* @return bool
*/
public function shouldCloneFields()
{
return $this->_getSubject()->shouldCloneFields();
}
/**
* Retrieve clone model
*
* @return \Magento\Framework\Model\AbstractModel
*/
public function getCloneModel()
{
return $this->_getSubject()->getCloneModel();
}
/**
* Populate form fieldset with group data
*
* @param \Magento\Framework\Data\Form\Element\Fieldset $fieldset
* @return void
*/
public function populateFieldset(\Magento\Framework\Data\Form\Element\Fieldset $fieldset)
{
$this->_getSubject()->populateFieldset($fieldset);
}
/**
* Retrieve element data
*
* @return array
*/
public function getData()
{
return $this->_getSubject()->getData();
}
/**
* Retrieve element path
*
* @param string $fieldPrefix
* @return string
*/
public function getPath($fieldPrefix = '')
{
return $this->_getSubject()->getPath($fieldPrefix);
}
/**
* Check whether element should be expanded
*
* @return bool
*/
public function isExpanded()
{
return $this->_getSubject()->isExpanded();
}
/**
* Retrieve fieldset css
*
* @return string
*/
public function getFieldsetCss()
{
return $this->_getSubject()->getFieldsetCss();
}
/**
* Retrieve element dependencies
*
* @param string $storeCode
* @return array
*/
public function getDependencies($storeCode)
{
return $this->_getSubject()->getDependencies($storeCode);
}
}
| webadvancedservicescom/magento | app/code/Magento/Backend/Model/Config/Structure/Element/Group/Proxy.php | PHP | apache-2.0 | 5,046 |
/*
* Copyright 2009-2017. DigitalGlobe, 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 org.mrgeo.utils;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.RemovalListener;
import com.google.common.cache.RemovalNotification;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.SequenceFile;
import org.mrgeo.core.MrGeoProperties;
import org.mrgeo.data.DataProviderFactory;
import org.mrgeo.data.DataProviderFactory.AccessMode;
import org.mrgeo.data.ProviderProperties;
import org.mrgeo.data.image.MrsImageDataProvider;
import org.mrgeo.data.image.MrsPyramidMetadataReader;
import org.mrgeo.data.tile.TileIdWritable;
import org.mrgeo.image.MrsPyramidMetadata;
import org.mrgeo.utils.tms.Bounds;
import org.mrgeo.utils.tms.TMSUtils;
import org.mrgeo.utils.tms.Tile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileTime;
import java.time.Instant;
import java.util.*;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class S3Utils
{
private static final Logger log = LoggerFactory.getLogger(S3Utils.class);
private static S3Cache s3Cache;
private static File cacheDir;
private static boolean useFileLocker;
public interface S3CacheEntry {
void readLock() throws IOException;
void writeLock() throws IOException;
boolean tryWriteLock() throws IOException;
void releaseReadLock() throws IOException;
void releaseWriteLock() throws IOException;
Path getLocalPath();
void cleanup() throws IOException;
FileOutputStream getPrimaryFileOutputStream() throws IOException;
}
@SuppressFBWarnings(value = {"SE_BAD_FIELD", "SE_NO_SERIALVERSIONID"}, justification = "Class is never serialized")
private static class S3MemoryCacheEntry implements S3CacheEntry {
private Path localPath;
private File primaryFile;
private File secondaryFile;
private ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();
private FileOutputStream fos;
S3MemoryCacheEntry(Path localPath, File primaryFile) {
this.localPath = localPath;
this.primaryFile = primaryFile;
}
S3MemoryCacheEntry(Path localPath, File primaryFile, File secondaryFile) {
this.localPath = localPath;
this.primaryFile = primaryFile;
this.secondaryFile = secondaryFile;
}
@Override
public FileOutputStream getPrimaryFileOutputStream() throws IOException {
if (fos == null) {
org.apache.commons.io.FileUtils.forceMkdir(primaryFile.getParentFile());
fos = new FileOutputStream(primaryFile);
}
return fos;
}
@Override
public Path getLocalPath() {
return localPath;
}
@Override
public void cleanup() throws IOException {
writeLock();
try {
if (primaryFile != null) {
log.debug("Deleting cached file " + primaryFile.getAbsolutePath());
boolean file1Deleted = primaryFile.delete();
if (!file1Deleted) {
log.error("Unable to delete local cache file " + primaryFile.getAbsolutePath());
}
primaryFile = null;
}
if (secondaryFile != null) {
log.debug("Deleting cached file " + secondaryFile.getAbsolutePath());
boolean file2Deleted = secondaryFile.delete();
if (!file2Deleted) {
log.error("Unable to delete local cache file " + secondaryFile.getAbsolutePath());
}
secondaryFile = null;
}
} finally {
releaseWriteLock();
}
}
@Override
public void readLock() throws IOException {
log.debug("Lock readLock lock from thread " + Thread.currentThread().getId() +
" on cacheEntry " + toString());
rwLock.readLock().lock();
}
@Override
public void writeLock() throws IOException {
log.debug("Lock writeLock lock from thread " + Thread.currentThread().getId() +
" on cacheEntry " + toString());
rwLock.writeLock().lock();
}
@Override
public boolean tryWriteLock() throws IOException {
log.debug("Lock writeLock lock from thread " + Thread.currentThread().getId() +
" on cacheEntry " + toString());
return rwLock.writeLock().tryLock();
}
@Override
public void releaseReadLock() {
log.debug("Lock readLock unlock from thread " + Thread.currentThread().getId() +
" on cacheEntry " + toString());
rwLock.readLock().unlock();
}
@Override
public void releaseWriteLock() throws IOException {
log.debug("Lock writeLock unlock from thread " + Thread.currentThread().getId() +
" on cacheEntry " + toString());
rwLock.writeLock().unlock();
// The lock is memory-based, but we want to make sure to close the file output stream
// when we release the lock so we don't retain open files.
if (fos != null) {
fos.close();
fos = null;
}
}
}
private static class S3FileCacheEntry implements S3CacheEntry {
private Path localPath;
private File primaryFile;
private File secondaryFile;
private FileLock readFileLock;
private FileLock writeFileLock;
private FileOutputStream fos;
private FileInputStream fis;
private FileChannel readChannel;
private FileChannel writeChannel;
S3FileCacheEntry(Path localPath, File localFile) {
this.localPath = localPath;
primaryFile = localFile;
}
S3FileCacheEntry(Path localPath, File primaryFile, File secondaryFile) {
this.localPath = localPath;
this.primaryFile = primaryFile;
this.secondaryFile = secondaryFile;
}
public FileOutputStream getPrimaryFileOutputStream() throws IOException {
return fos;
}
@Override
public void readLock() throws IOException {
initReadChannel();
log.debug("readLock from thread " + Thread.currentThread().getId() + " on entry " +
primaryFile.getAbsolutePath());
readFileLock = readChannel.lock(0, Long.MAX_VALUE, true);
log.debug(" readLock from thread " + Thread.currentThread().getId() + " done ");
// Some operating systems do not support shared locks, so report that here. But
// keep the lock active - the system will just run slower.
if (!readFileLock.isShared()) {
log.warn("Unable to create a shared lock on " + getLocalPath());
}
}
@Override
public void writeLock() throws IOException {
initWriteChannel();
log.debug("writeLock from thread " + Thread.currentThread().getId() + " on entry " +
primaryFile.getAbsolutePath());
writeFileLock = writeChannel.lock(0, Long.MAX_VALUE, false);
log.debug(" done writeLock from thread " + Thread.currentThread().getId() + " on entry " +
primaryFile.getAbsolutePath());
}
@Override
public boolean tryWriteLock() throws IOException {
initWriteChannel();
log.debug("tryWriteLock from thread " + Thread.currentThread().getId() + " on entry " +
primaryFile.getAbsolutePath());
writeFileLock = writeChannel.tryLock(0, Long.MAX_VALUE, false);
log.debug(" done tryWriteLock from thread " + Thread.currentThread().getId() + " on entry " +
primaryFile.getAbsolutePath());
return (writeFileLock != null);
}
@Override
public void releaseReadLock() throws IOException {
if (readChannel != null) {
log.debug("releaseReadLock from thread " + Thread.currentThread().getId() + " on entry " +
primaryFile.getAbsolutePath());
readChannel.close();
readChannel = null;
log.debug(" done releaseReadLock from thread " + Thread.currentThread().getId() +
" on entry " + primaryFile.getAbsolutePath());
}
if (fis != null) {
fis.close();
fis = null;
}
}
@Override
public void releaseWriteLock() throws IOException {
if (writeChannel != null) {
log.debug("releaseWriteLock from thread " + Thread.currentThread().getId() + " on entry " +
primaryFile.getAbsolutePath());
writeChannel.close();
writeChannel = null;
log.debug(" done releaseWriteLock from thread " + Thread.currentThread().getId() + " on entry " + primaryFile.getAbsolutePath());
}
if (fos != null) {
fos.close();
fos = null;
}
}
@Override
public Path getLocalPath() {
return localPath;
}
@Override
public void cleanup() throws IOException {
writeLock();
try {
if (secondaryFile != null) {
log.debug("Deleting cached file " + secondaryFile.getAbsolutePath());
boolean file2Deleted = secondaryFile.delete();
if (!file2Deleted) {
log.error("Unable to delete local cache file " + secondaryFile.getAbsolutePath());
}
secondaryFile = null;
}
if (primaryFile != null) {
log.debug("Deleting cached file " + primaryFile.getAbsolutePath());
boolean file1Deleted = primaryFile.delete();
if (!file1Deleted) {
log.error("Unable to delete local cache file " + primaryFile.getAbsolutePath());
}
primaryFile = null;
}
} finally {
releaseWriteLock();
releaseReadLock();
}
}
private void initWriteChannel() throws IOException {
if (writeChannel == null) {
org.apache.commons.io.FileUtils.forceMkdir(primaryFile.getParentFile());
fos = new FileOutputStream(primaryFile);
writeChannel = fos.getChannel();
}
}
private void initReadChannel() throws IOException {
if (readChannel == null) {
fis = new FileInputStream(primaryFile);
readChannel = fis.getChannel();
}
}
@SuppressFBWarnings(value = "OS_OPEN_STREAM", justification = "stream is closed when lock is released")
public static void run(String[] args) {
Path lockPath = new Path(args[0]);
File file1 = new File(args[1]);
File file2 = new File(args[2]);
Scanner scanner = new Scanner(System.in);
System.out.print("Command (twl, wl, rwl, rl, rrl, rwlrl, wf, quit): ");
String line = scanner.nextLine();
S3FileCacheEntry entry = null;
while (!line.equalsIgnoreCase("quit")) {
if (entry == null) {
entry = new S3FileCacheEntry(lockPath, file1, file2);
}
if (line.equalsIgnoreCase("rl")) {
try {
entry.readLock();
System.out.println("result: success");
} catch (Throwable e) {
System.out.println("Error from readLock: " + e);
}
} else if (line.equalsIgnoreCase("rrl")) {
try {
entry.releaseReadLock();
entry = null;
System.out.println("result: success");
} catch (Throwable e) {
System.out.println("Error from releaseReadLock: " + e);
}
} else if (line.equalsIgnoreCase("twl")) {
try {
System.out.println("result: " + entry.tryWriteLock());
} catch (Throwable e) {
System.out.println("Error from tryWriteLock: " + e);
}
} else if (line.equalsIgnoreCase("wl")) {
try {
entry.writeLock();
System.out.println("result: success");
} catch (Throwable e) {
System.out.println("Error from writeLock: " + e);
}
} else if (line.equalsIgnoreCase("rwl")) {
try {
entry.releaseWriteLock();
entry = null;
System.out.println("result: success");
} catch (Throwable e) {
System.out.println("Error from releaseWriteLock: " + e);
}
} else if (line.equalsIgnoreCase("rwlrl")) {
try {
entry.releaseWriteLock();
System.out.println("released write lock, now getting read lock");
entry.readLock();
System.out.println("result: success");
} catch (Throwable e) {
System.out.println("Error from releaseWriteLock: " + e);
}
} else if (line.equalsIgnoreCase("wf")) {
try {
FileOutputStream fos = entry.getPrimaryFileOutputStream();
PrintWriter pw = new PrintWriter(fos);
pw.println("blah");
pw.flush();
// Do not close the stream here. That is done when the write lock is released.
} catch (Throwable e) {
System.out.println("Error writing lock file: " + e);
}
}
System.out.print("Command (twl, wl, rwl, rl, rrl, rwlrl, wf, quit): ");
line = scanner.nextLine();
}
}
}
public interface S3Cache {
void init() throws IOException;
S3CacheEntry getEntry(String key, Path localPath, File primaryFile, File secondaryFile);
void addEntry(String key, S3CacheEntry entry);
// For now, we only need an entry with either 1 or 2 local files since we only
// need support for sequence files and map files at the moment. If we ever need
// more, then change the following two methods to a single signature that takes
// a variable number of local files. For now, it avoids the overhead of storing
// an array for each entry.
S3CacheEntry createEntry(Path localPath, File primaryFile);
S3CacheEntry createEntry(Path localPath, File primaryFile, File secondaryFile);
}
private static class CacheCleanupHook extends Thread {
private File cleanupDir;
CacheCleanupHook(File cleanupDir) {
this.cleanupDir = cleanupDir;
}
@Override
public void run() {
try {
org.apache.commons.io.FileUtils.cleanDirectory(cleanupDir);
log.debug("In shutdown, deleting " + cleanupDir.getAbsolutePath());
org.apache.commons.io.FileUtils.deleteDirectory(cleanupDir);
} catch (IOException e) {
log.debug("Unable to clean MrGeo S3 cache directory " + e.getMessage());
}
}
}
private static class CacheCleanupOnElementRemoval implements RemovalListener<String, S3CacheEntry> {
@Override
public void onRemoval(RemovalNotification<String, S3CacheEntry> notification) {
log.debug("S3 cache removal key: " + notification.getKey() + " with cause " + notification.getCause() + " from thread " + Thread.currentThread().getId());
log.debug("S3 cache removal value: " + notification.getValue() + " from thread " + Thread.currentThread().getId());
try {
notification.getValue().cleanup();
} catch (IOException e) {
log.error("Got exception while cleaning up a cache entry for " + notification.getKey(), e);
}
}
}
private static class S3MemoryCache implements S3Cache {
private Cache<String, S3CacheEntry> s3FileCache;
@Override
@SuppressFBWarnings(value = "PATH_TRAVERSAL_IN", justification = "File() - name is gotten from mrgeo.conf")
public void init() throws IOException {
if (cacheDir == null) {
// For the memory-based cache approach, the locally cached S3 files
// must be cleaned up when the process exits. Also, the local cache
// dir is in a temp subdir so it does not conflict with other running
// processes that use this same cache approach (e.g. multiple instances
// of MrGeo web services running on a single machine)
String strTmpDir = MrGeoProperties.getInstance().getProperty("s3.cache.dir", "/tmp/mrgeo");
org.apache.commons.io.FileUtils.forceMkdir(new File(strTmpDir));
java.nio.file.Path tmpPath = java.nio.file.Files.createTempDirectory(java.nio.file.Paths.get(strTmpDir), "mrgeo");
cacheDir = tmpPath.toFile();
}
if (s3FileCache == null) {
long s3CacheSize = 200L;
String strCacheSize = MrGeoProperties.getInstance().getProperty("s3.cache.size.elements");
if (strCacheSize != null && !strCacheSize.isEmpty()) {
s3CacheSize = Long.parseLong(strCacheSize);
}
log.debug("cache size " + s3CacheSize);
String strLocker = MrGeoProperties.getInstance().getProperty("s3.cache.locker", "file");
useFileLocker = strLocker.equalsIgnoreCase("file");
Runtime.getRuntime().addShutdownHook(new CacheCleanupHook(cacheDir));
s3FileCache = CacheBuilder
.newBuilder().maximumSize(s3CacheSize)
.removalListener(new CacheCleanupOnElementRemoval()).build();
}
}
@Override
public S3CacheEntry getEntry(String key, Path localPath, File primaryFile,
File secondaryFile) {
return s3FileCache.getIfPresent(key);
}
@Override
public void addEntry(String key, S3CacheEntry entry) {
s3FileCache.put(key, entry);
}
@Override
public S3CacheEntry createEntry(Path localPath, File primaryFile) {
return new S3MemoryCacheEntry(localPath, primaryFile);
}
@Override
public S3CacheEntry createEntry(Path localPath, File primaryFile, File secondaryFile) {
return new S3MemoryCacheEntry(localPath, primaryFile, secondaryFile);
}
}
@SuppressFBWarnings(value = "PATH_TRAVERSAL_IN", justification = "File() - name is configured by an admin")
private static class S3FileCache implements S3Cache {
@Override
public void init() throws IOException {
if (cacheDir == null) {
// When using a file-based S3 local cache, all processes use the same
// file-based cache and file locking to coordinate access. There is no need
// the delete the cache directory when the process exits because it will
// automatically re-use the cache contents the next time it starts up.
String strTmpDir = MrGeoProperties.getInstance().getProperty("s3.cache.dir", "/tmp/mrgeo");
org.apache.commons.io.FileUtils.forceMkdir(new File(strTmpDir));
cacheDir = new File(strTmpDir);
}
}
@Override
public S3CacheEntry getEntry(String key, Path localPath, File primaryFile, File secondaryFile) {
if (primaryFile.exists()) {
log.debug("Found existing entry for " + key);
return new S3FileCacheEntry(localPath, primaryFile, secondaryFile);
}
log.debug("Did not find existing entry for " + key);
return null;
}
@Override
public void addEntry(String key, S3CacheEntry entry) {
// Nothing to do
}
@Override
public S3CacheEntry createEntry(Path localPath, File primaryFile) {
return new S3FileCacheEntry(localPath, primaryFile);
}
@Override
public S3CacheEntry createEntry(Path localPath, File primaryFile, File secondaryFile) {
return new S3FileCacheEntry(localPath, primaryFile, secondaryFile);
}
}
public static synchronized S3Cache getS3Cache() throws IOException {
if (s3Cache == null) {
String strLocker = MrGeoProperties.getInstance().getProperty("s3.cache.locker", "file");
useFileLocker = strLocker.equalsIgnoreCase("file");
s3Cache = (useFileLocker) ? new S3FileCache() : new S3MemoryCache();
s3Cache.init();
}
return s3Cache;
}
public static File getCacheDir() throws IOException
{
// Initialize the cacheDir if needed
getS3Cache();
return cacheDir;
}
private interface MrGeoImageCallback
{
void foundImage(java.nio.file.Path imagePath, long imageSize, FileTime lastAccess);
}
/**
* MrGeo images are split into partitions. Each partition is a Hadoop MapFile which
* is a directory containing two files named "index" and "data". When performing
* cache cleaning, we want to make sure that we remove both files and the parent
* directory.
*/
private static class MrGeoImageCacheFileVisitor extends SimpleFileVisitor<java.nio.file.Path>
{
private BasicFileAttributes indexAttributes;
private BasicFileAttributes dataAttributes;
private long partitionSize;
private FileTime lastAccessTime = FileTime.from(Instant.now());
private MrGeoImageCallback callback;
public MrGeoImageCacheFileVisitor(MrGeoImageCallback callback)
{
this.callback = callback;
}
@Override
public FileVisitResult preVisitDirectory(java.nio.file.Path dir, BasicFileAttributes attrs) throws IOException
{
partitionSize = 0L;
lastAccessTime = FileTime.from(Instant.now());
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(java.nio.file.Path file, BasicFileAttributes attrs) throws IOException
{
if (file != null) {
java.nio.file.Path nameOnly = file.getFileName();
if (nameOnly != null) {
String fileName = nameOnly.toString();
if (fileName.equals("index")) {
indexAttributes = attrs;
if (attrs.lastAccessTime().compareTo(lastAccessTime) < 0) {
lastAccessTime = attrs.lastAccessTime();
}
} else if (fileName.equals("data")) {
dataAttributes = attrs;
if (attrs.lastAccessTime().compareTo(lastAccessTime) < 0) {
lastAccessTime = attrs.lastAccessTime();
}
}
}
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(java.nio.file.Path dir, IOException exc) throws IOException
{
if (indexAttributes != null && dataAttributes != null) {
partitionSize = indexAttributes.size() + dataAttributes.size();
callback.foundImage(dir, partitionSize, lastAccessTime);
indexAttributes = null;
dataAttributes = null;
lastAccessTime = FileTime.from(Instant.now());
partitionSize = 0L;
}
return FileVisitResult.CONTINUE;
}
}
private static class MrGeoImageEntry
{
private java.nio.file.Path imagePath;
private long imageSize;
private FileTime lastAccess;
public MrGeoImageEntry(java.nio.file.Path imagePath, long imageSize, FileTime lastAccess)
{
this.imagePath = imagePath;
this.imageSize = imageSize;
this.lastAccess = lastAccess;
}
}
private static class MrGeoImageCollection implements MrGeoImageCallback
{
private List<MrGeoImageEntry> images;
public MrGeoImageCollection(List<MrGeoImageEntry> images)
{
this.images = images;
}
@Override
public void foundImage(java.nio.file.Path imagePath, long imageSize, FileTime lastAccess) {
images.add(new MrGeoImageEntry(imagePath, imageSize, lastAccess));
}
}
public static void cleanCache(long maxCacheSize, int age, int ageField, Bounds bbox,
int minZoom, int maxZoom, boolean dryrun,
int defaultTileSize,
Configuration conf,
ProviderProperties providerProperties) throws IOException
{
// The following call figures out the cacheDir
File useCacheDir = getCacheDir();
java.nio.file.Path startPath = Paths.get(useCacheDir.getAbsolutePath());
// Scan all entries and sort by last access time.
List<MrGeoImageEntry> imageList = new ArrayList<>(500);
MrGeoImageCollection images = new MrGeoImageCollection(imageList);
Files.walkFileTree(startPath, new MrGeoImageCacheFileVisitor(images));
// Sort in ascending order by lastAccess then descending order by size.
imageList.sort(new Comparator<MrGeoImageEntry>() {
@Override
public int compare(MrGeoImageEntry image1, MrGeoImageEntry image2) {
int result = image1.lastAccess.compareTo(image2.lastAccess);
if (result == 0) {
if (image1.imageSize > image2.imageSize) {
result = -1;
}
else if (image1.imageSize < image2.imageSize) {
result = 1;
}
}
return result;
}
});
if (imageList.size() > 0) {
long totalSize = 0L;
// Compute the total size of all images.
for (MrGeoImageEntry entry : imageList) {
totalSize += entry.imageSize;
}
if (totalSize > 0) {
long newSize = totalSize;
java.util.Calendar c = GregorianCalendar.getInstance();
if (age > 0) {
c.add(ageField, -age);
}
Iterator<MrGeoImageEntry> iter = imageList.iterator();
long deleteCount = 0L;
Map<String, Integer> tileSizes = new HashMap<>();
while (iter.hasNext()) {
MrGeoImageEntry entry = iter.next();
boolean deleteFile = false;
// Get the zoom level of the current file
int zoomLevel = -1;
java.nio.file.Path zoomPath = entry.imagePath.getParent();
if (zoomPath != null) {
java.nio.file.Path zoomName = zoomPath.getFileName();
if (zoomName != null) {
try {
zoomLevel = Integer.parseInt(zoomName.toString());
}
catch(NumberFormatException nfe) {
log.error("Unable to parse zoom level from " + zoomName);
}
}
}
try {
// System.out.println(entry.lastAccess.toString() + " " + entry.imagePath.toString() +
// " with size " + entry.imageSize +
// ". New cache size is " + newSize);
// if (newSize > maxCacheSize) {
// System.out.println(" DELETE");
// newSize -= entry.imageSize;
// }
if (maxCacheSize > 0) {
if (newSize > maxCacheSize) {
deleteFile = true;
newSize -= entry.imageSize;
}
else {
// We are below the size threshold, so bail out
break;
}
}
else if (minZoom > 0) {
deleteFile = (minZoom <= zoomLevel && zoomLevel <= maxZoom);
}
else if (age > 0) {
deleteFile = (entry.lastAccess.toMillis() < c.getTimeInMillis());
}
else if (bbox != null) {
// Have to read the tiles from the partition and see if any of them
// intersect the specified bbox.
Path indexPath = new Path("file://" + entry.imagePath, "index");
int tilesize = defaultTileSize;
try {
// Get the image name
java.nio.file.Path imagePath = zoomPath.getParent();
java.nio.file.Path cachePath = Paths.get(cacheDir.toString());
java.nio.file.Path relativeImagePath = cachePath.relativize(imagePath);
if (relativeImagePath != null) {
String strRelativeImagePath = relativeImagePath.toString();
if (tileSizes.containsKey(strRelativeImagePath)) {
tilesize = tileSizes.get(strRelativeImagePath);
}
else {
MrsImageDataProvider dp = DataProviderFactory.getMrsImageDataProvider(
"s3://" + strRelativeImagePath,
AccessMode.READ, providerProperties);
MrsPyramidMetadataReader metadataReader = dp.getMetadataReader();
if (metadataReader != null) {
MrsPyramidMetadata metadata = metadataReader.read();
tileSizes.put(strRelativeImagePath, tilesize);
tilesize = metadata.getTilesize();
}
}
}
SequenceFile.Reader indexReader = new SequenceFile.Reader(conf, SequenceFile.Reader.file(indexPath));
TileIdWritable key = (TileIdWritable)indexReader.getKeyClass().newInstance();
boolean hasKey = indexReader.next(key);
while (hasKey && !deleteFile) {
Tile tile = TMSUtils.tileid(key.get(), zoomLevel);
Bounds tb = TMSUtils.tileBounds(tile.tx, tile.ty, zoomLevel, tilesize);
deleteFile = bbox.intersects(tb);
hasKey = indexReader.next(key);
}
} catch (IllegalAccessException | InstantiationException e) {
log.error("Unable to check the bounds of " + indexPath, e);
}
}
if (deleteFile) {
deleteCount++;
if (dryrun) {
System.out.println("Would delete S3 cached file at " + entry.imagePath);
} else {
org.mrgeo.utils.FileUtils.deleteDir(entry.imagePath.toFile(), true);
System.out.println("Deleted S3 cached file at " + entry.imagePath);
}
}
}
catch(IOException e) {
log.warn("Unable to clean cached S3 image at " + entry.imagePath, e);
}
}
System.out.println(((dryrun) ? "Would have deleted " : "Deleted ") + deleteCount + " cache entries");
}
}
}
/**
* This is only meant for testing S3 caching from the command line.
* @param args
*/
// public static void main(String[] args) {
// S3FileCacheEntry.run(args);
// }
}
| ngageoint/mrgeo | mrgeo-core/src/main/java/org/mrgeo/utils/S3Utils.java | Java | apache-2.0 | 30,242 |
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
package org.elasticsearch.xpack.sql.expression.function.scalar.datetime;
import org.elasticsearch.xpack.sql.expression.Expression;
import org.elasticsearch.xpack.sql.expression.gen.pipeline.Pipe;
import org.elasticsearch.xpack.sql.expression.gen.processor.Processor;
import org.elasticsearch.xpack.sql.tree.NodeInfo;
import org.elasticsearch.xpack.sql.tree.Source;
import java.time.ZoneId;
public class DatePartPipe extends BinaryDateTimePipe {
public DatePartPipe(Source source, Expression expression, Pipe left, Pipe right, ZoneId zoneId) {
super(source, expression, left, right, zoneId);
}
@Override
protected NodeInfo<DatePartPipe> info() {
return NodeInfo.create(this, DatePartPipe::new, expression(), left(), right(), zoneId());
}
@Override
protected DatePartPipe replaceChildren(Pipe left, Pipe right) {
return new DatePartPipe(source(), expression(), left, right, zoneId());
}
@Override
protected Processor makeProcessor(Processor left, Processor right, ZoneId zoneId) {
return new DatePartProcessor(left, right, zoneId);
}
}
| coding0011/elasticsearch | x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/DatePartPipe.java | Java | apache-2.0 | 1,359 |
/*
* Rittner_Agilent7700_RawDataTemplate
*
* Copyright 2006-2015 James F. Bowring and www.Earth-Time.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.earthtime.Tripoli.rawDataFiles.templates;
import java.io.Serializable;
import java.util.TimeZone;
import org.earthtime.Tripoli.dataModels.inputParametersModels.AbstractAcquisitionModel;
import org.earthtime.Tripoli.dataModels.inputParametersModels.SingleCollectorAcquisition;
import org.earthtime.dataDictionaries.FileTypeEnum;
/**
*
* @author James F. Bowring
*/
public final class Rittner_Agilent7700_RawDataTemplate extends AbstractRawDataFileTemplate implements //
Comparable<AbstractRawDataFileTemplate>,
Serializable {
private static Rittner_Agilent7700_RawDataTemplate instance = null;
private Rittner_Agilent7700_RawDataTemplate () {
super();
this.NAME = "Rittner Agilent 7700";
this.aboutInfo = "analysis runs setup by Rittner";
this.fileType = FileTypeEnum.csv;
this.startOfFirstLine = "Sample";
this.startOfDataSectionFirstLine = "Time";
this.startOfEachBlockFirstLine = "Time";
this.blockStartOffset = 20;//4;
this.blockSize = 212;//goes with temp 106 in handler 222;//238;
this.standardIDs = new String[]//
{"stdcz"};
this.timeZone = TimeZone.getTimeZone( "GMT" );
this.defaultParsingOfFractionsBehavior = 1;
}
/**
*
* @return
*/
public static Rittner_Agilent7700_RawDataTemplate getInstance () {
if ( instance == null ) {
instance = new Rittner_Agilent7700_RawDataTemplate();
}
return instance;
}
/**
*
* @return
*/
@Override
public AbstractAcquisitionModel makeNewAcquisitionModel () {
this.acquisitionModel = new SingleCollectorAcquisition();
return acquisitionModel;
}
}
| clementparizot/ET_Redux | src/main/java/org/earthtime/Tripoli/rawDataFiles/templates/Rittner_Agilent7700_RawDataTemplate.java | Java | apache-2.0 | 2,437 |
var dynode = exports;
dynode.Client = require('./dynode/client').Client;
dynode.AmazonError = require('./dynode/amazon-error');
var defaultClient;
dynode.auth = function(config) {
defaultClient = new dynode.Client(config);
};
var methods = [
'listTables',
'describeTable',
'createTable',
'deleteTable',
'updateTable',
'putItem',
'updateItem',
'getItem',
'deleteItem',
'query',
'scan',
'batchGetItem',
'batchWriteItem',
'truncate',
'_request'
];
methods.forEach(function (method) {
dynode[method] = function () {
return defaultClient[method].apply(defaultClient, arguments);
};
}); | Wantworthy/dynode | lib/dynode.js | JavaScript | apache-2.0 | 625 |
package org.codehaus.mojo.dashboard.report.plugin.configuration;
/*
* Copyright 2007 David Vicente
*
* 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 java.util.ArrayList;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
* @author <a href="dvicente72@gmail.com">David Vicente</a>
*
*/
public class Configuration
{
private String version;
private List sections = new ArrayList();
private Map map = new Hashtable();
public Configuration()
{
}
public String getVersion()
{
return version;
}
public List getSections()
{
return sections;
}
public void setSections( List sections )
{
this.sections = sections;
}
public Section getSectionById( String artifactId)
{
if( map == null || map.isEmpty() )
{
map = new Hashtable();
Iterator iter = this.sections.iterator();
while ( iter.hasNext() )
{
Section section = (Section) iter.next();
map.put( section.getId(), section );
}
}
return (Section) map.get( artifactId );
}
}
| progosch/dashboard-maven-plugin | src/main/java/org/codehaus/mojo/dashboard/report/plugin/configuration/Configuration.java | Java | apache-2.0 | 1,745 |
/*
* 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.
*/
/**
* @author Anton Avtamonov
* @version $Revision$
*/
package javax.swing;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.plaf.SplitPaneUI;
import javax.swing.plaf.basic.BasicSplitPaneUI;
import javax.swing.plaf.metal.MetalSplitPaneUI;
public class JSplitPaneTest extends SwingTestCase {
private JSplitPane pane;
public JSplitPaneTest(final String name) {
super(name);
}
@Override
protected void setUp() throws Exception {
pane = new JSplitPane();
propertyChangeController = new PropertyChangeController();
pane.addPropertyChangeListener(propertyChangeController);
}
@Override
protected void tearDown() throws Exception {
pane = null;
}
public void testJSplitPane() throws Exception {
assertTrue(pane.getLeftComponent() instanceof JButton);
assertTrue(pane.getRightComponent() instanceof JButton);
assertFalse(pane.isContinuousLayout());
assertEquals(0, pane.getLastDividerLocation());
assertEquals(-1, pane.getDividerLocation());
assertEquals(JSplitPane.HORIZONTAL_SPLIT, pane.getOrientation());
pane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
assertNull(pane.getLeftComponent());
assertNull(pane.getRightComponent());
assertFalse(pane.isContinuousLayout());
assertEquals(0, pane.getLastDividerLocation());
assertEquals(-1, pane.getDividerLocation());
assertEquals(JSplitPane.VERTICAL_SPLIT, pane.getOrientation());
pane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
assertEquals(JSplitPane.HORIZONTAL_SPLIT, pane.getOrientation());
testExceptionalCase(new IllegalArgumentCase() {
@Override
public void exceptionalAction() throws Exception {
new JSplitPane(2);
}
});
pane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, true);
assertTrue(pane.isContinuousLayout());
assertEquals(JSplitPane.HORIZONTAL_SPLIT, pane.getOrientation());
pane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, false);
assertFalse(pane.isContinuousLayout());
assertEquals(JSplitPane.VERTICAL_SPLIT, pane.getOrientation());
testExceptionalCase(new IllegalArgumentCase() {
@Override
public void exceptionalAction() throws Exception {
new JSplitPane(-1, true);
}
});
Component left = new JButton();
Component right = new JButton();
pane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, left, right);
assertEquals(left, pane.getLeftComponent());
assertEquals(right, pane.getRightComponent());
assertFalse(pane.isContinuousLayout());
assertEquals(JSplitPane.VERTICAL_SPLIT, pane.getOrientation());
pane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, true, left, right);
assertEquals(left, pane.getLeftComponent());
assertEquals(right, pane.getRightComponent());
assertTrue(pane.isContinuousLayout());
assertEquals(JSplitPane.VERTICAL_SPLIT, pane.getOrientation());
testExceptionalCase(new IllegalArgumentCase() {
@Override
public void exceptionalAction() throws Exception {
new JSplitPane(2, true, new JButton(), new JButton());
}
});
}
public void testGetSetUpdateUI() throws Exception {
assertNotNull(pane.getUI());
SplitPaneUI ui = new MetalSplitPaneUI();
pane.setUI(ui);
assertEquals(ui, pane.getUI());
pane.updateUI();
assertNotSame(ui, pane.getUI());
}
public void testGetUIClassID() throws Exception {
assertEquals("SplitPaneUI", pane.getUIClassID());
}
public void testGetSetDividerSize() throws Exception {
assertEquals(UIManager.getInt("SplitPane.dividerSize"), pane.getDividerSize());
pane.setDividerSize(20);
assertEquals(20, pane.getDividerSize());
assertTrue(propertyChangeController.isChanged("dividerSize"));
}
public void testGetSetLeftTopComponent() throws Exception {
assertTrue(pane.getLeftComponent() instanceof JButton);
Component left = new JPanel();
pane.setLeftComponent(left);
assertEquals(left, pane.getLeftComponent());
assertEquals(left, pane.getTopComponent());
assertEquals(left, pane.getComponent(2));
Component top = new JPanel();
pane.setTopComponent(top);
assertEquals(top, pane.getLeftComponent());
assertEquals(top, pane.getTopComponent());
assertEquals(top, pane.getComponent(2));
}
public void testGetSetRightBottomComponent() throws Exception {
assertTrue(pane.getRightComponent() instanceof JButton);
Component right = new JPanel();
pane.setRightComponent(right);
assertEquals(right, pane.getRightComponent());
assertEquals(right, pane.getBottomComponent());
assertEquals(right, pane.getComponent(2));
Component bottom = new JPanel();
pane.setBottomComponent(bottom);
assertEquals(bottom, pane.getRightComponent());
assertEquals(bottom, pane.getBottomComponent());
assertEquals(bottom, pane.getComponent(2));
}
public void testIsSetOneTouchExpandable() throws Exception {
assertFalse(pane.isOneTouchExpandable());
pane.setOneTouchExpandable(true);
assertTrue(pane.isOneTouchExpandable());
assertTrue(propertyChangeController.isChanged("oneTouchExpandable"));
}
public void testGetSetLastDividerLocation() throws Exception {
assertEquals(0, pane.getLastDividerLocation());
pane.setLastDividerLocation(20);
assertEquals(20, pane.getLastDividerLocation());
assertTrue(propertyChangeController.isChanged("lastDividerLocation"));
}
public void testGetSetOrientation() throws Exception {
assertEquals(JSplitPane.HORIZONTAL_SPLIT, pane.getOrientation());
pane.setOrientation(JSplitPane.VERTICAL_SPLIT);
assertEquals(JSplitPane.VERTICAL_SPLIT, pane.getOrientation());
assertTrue(propertyChangeController.isChanged("orientation"));
}
public void testIsSetContinuousLayout() throws Exception {
assertFalse(pane.isContinuousLayout());
pane.setContinuousLayout(true);
assertTrue(pane.isContinuousLayout());
assertTrue(propertyChangeController.isChanged("continuousLayout"));
}
public void testGetSetResizeWeight() throws Exception {
assertEquals(0, 0, pane.getResizeWeight());
pane.setResizeWeight(0.4);
assertEquals(0, 0.4, pane.getResizeWeight());
assertTrue(propertyChangeController.isChanged("resizeWeight"));
testExceptionalCase(new IllegalArgumentCase() {
@Override
public void exceptionalAction() throws Exception {
pane.setResizeWeight(-1);
}
});
testExceptionalCase(new IllegalArgumentCase() {
@Override
public void exceptionalAction() throws Exception {
pane.setResizeWeight(1.5);
}
});
}
public void testResetToPreferredSizes() throws Exception {
if (isHarmony()) {
((JComponent) pane.getLeftComponent()).setPreferredSize(new Dimension(100, 50));
((JComponent) pane.getRightComponent()).setPreferredSize(new Dimension(100, 50));
pane.setSize(300, 100);
pane.setBorder(BorderFactory.createEmptyBorder(10, 20, 30, 40));
pane.setDividerLocation(40);
assertEquals(40, pane.getDividerLocation());
pane.resetToPreferredSizes();
assertEquals(120, pane.getDividerLocation());
}
}
public void testGetSetDividerLocation() throws Exception {
assertEquals(-1, pane.getDividerLocation());
((JComponent) pane.getLeftComponent()).setPreferredSize(new Dimension(100, 50));
((JComponent) pane.getRightComponent()).setPreferredSize(new Dimension(100, 50));
pane.setSize(300, 100);
pane.setBorder(BorderFactory.createEmptyBorder(10, 20, 30, 40));
pane.setDividerLocation(40);
assertTrue(propertyChangeController.isChanged("dividerLocation"));
assertTrue(propertyChangeController.isChanged("lastDividerLocation"));
assertEquals(40, pane.getDividerLocation());
assertEquals(0, pane.getUI().getDividerLocation(pane));
pane.getUI().setDividerLocation(pane, 50);
assertEquals(0, pane.getUI().getDividerLocation(pane));
assertEquals(40, pane.getDividerLocation());
pane.getLayout().layoutContainer(pane);
assertEquals(40, pane.getDividerLocation());
assertEquals(40, pane.getUI().getDividerLocation(pane));
pane.setDividerLocation(0.3);
assertEquals((300 - 10) * 0.3, pane.getDividerLocation(), 0);
pane.setDividerLocation(0.5);
assertEquals((300 - 10) * 0.5, pane.getDividerLocation(), 0);
pane.setDividerLocation(0.6);
assertEquals((300 - 10) * 0.6, pane.getDividerLocation(), 0);
}
public void testGetMinimumMaximumDividerLocation() throws Exception {
SplitPaneUI ui = new BasicSplitPaneUI() {
@Override
public int getMinimumDividerLocation(final JSplitPane sp) {
return 20;
}
@Override
public int getMaximumDividerLocation(final JSplitPane sp) {
return 40;
}
};
pane.setUI(ui);
assertEquals(20, pane.getMinimumDividerLocation());
assertEquals(40, pane.getMaximumDividerLocation());
}
public void testRemove() throws Exception {
assertNotNull(pane.getLeftComponent());
pane.remove(pane.getLeftComponent());
assertNull(pane.getLeftComponent());
assertNotNull(pane.getRightComponent());
pane.remove(pane.getRightComponent());
assertNull(pane.getRightComponent());
pane = new JSplitPane();
assertNotNull(pane.getRightComponent());
pane.remove(1);
assertNull(pane.getRightComponent());
assertNotNull(pane.getLeftComponent());
pane.remove(0);
assertNull(pane.getLeftComponent());
pane = new JSplitPane();
assertNotNull(pane.getLeftComponent());
assertNotNull(pane.getRightComponent());
pane.removeAll();
assertNull(pane.getLeftComponent());
assertNull(pane.getRightComponent());
}
public void testIsValidateRoot() throws Exception {
assertTrue(pane.isValidateRoot());
}
public void testAddImpl() throws Exception {
pane.removeAll();
assertEquals(0, pane.getComponentCount());
Component left = new JButton();
pane.add(left, JSplitPane.LEFT);
assertEquals(1, pane.getComponentCount());
assertEquals(left, pane.getLeftComponent());
assertEquals(left, pane.getTopComponent());
Component top = new JButton();
pane.add(top, JSplitPane.TOP);
assertEquals(1, pane.getComponentCount());
assertEquals(top, pane.getLeftComponent());
assertEquals(top, pane.getTopComponent());
Component right = new JButton();
pane.add(right, JSplitPane.RIGHT);
assertEquals(2, pane.getComponentCount());
assertEquals(right, pane.getRightComponent());
assertEquals(right, pane.getBottomComponent());
Component bottom = new JButton();
pane.add(bottom, JSplitPane.BOTTOM);
assertEquals(2, pane.getComponentCount());
assertEquals(bottom, pane.getRightComponent());
assertEquals(bottom, pane.getBottomComponent());
Component divider = new JButton();
pane.add(divider, JSplitPane.DIVIDER);
assertEquals(3, pane.getComponentCount());
pane.removeAll();
left = new JButton();
right = new JButton();
pane.addImpl(right, JSplitPane.RIGHT, 1);
pane.addImpl(left, JSplitPane.LEFT, 0);
assertSame(right, pane.getComponent(0));
assertSame(left, pane.getComponent(1));
pane.removeAll();
left = new JButton();
pane.add(left);
assertEquals(left, pane.getLeftComponent());
right = new JButton();
pane.add(right);
assertEquals(right, pane.getRightComponent());
testExceptionalCase(new IllegalArgumentCase() {
@Override
public void exceptionalAction() throws Exception {
pane.add(new JButton());
}
});
testExceptionalCase(new IllegalArgumentCase() {
@Override
public void exceptionalAction() throws Exception {
pane.add(new JButton(), "wrong");
}
});
}
public void testPaintChildren() throws Exception {
final Marker m = new Marker();
SplitPaneUI ui = new BasicSplitPaneUI() {
@Override
public void finishedPaintingChildren(final JSplitPane sp, final Graphics g) {
m.mark();
}
};
pane.setUI(ui);
pane.paintChildren(createTestGraphics());
assertTrue(m.isMarked());
}
public void testGetAccessibleContext() throws Exception {
assertTrue(pane.getAccessibleContext() instanceof JSplitPane.AccessibleJSplitPane);
}
public void testIsOpaque() throws Exception {
assertTrue(pane.isOpaque());
}
private class Marker {
private boolean marked;
public void mark() {
marked = true;
}
public boolean isMarked() {
return marked;
}
}
}
| freeVM/freeVM | enhanced/archive/classlib/java6/modules/swing/src/test/api/java/common/javax/swing/JSplitPaneTest.java | Java | apache-2.0 | 14,634 |
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.Runtime.Serialization;
namespace InstaSharp.Models
{
[JsonConverter(typeof(StringEnumConverter))]
public enum IncomingStatus
{
[EnumMember(Value = "followed_by")]
FollowedBy,
[EnumMember(Value = "requested_by")]
RequestedBy,
[EnumMember(Value = "blocked_by_you")]
BlockedbyYou,
[EnumMember(Value = "none")]
None
}
} | InstaSharp/InstaSharp | src/InstaSharp/Models/IncomingStatus.cs | C# | apache-2.0 | 469 |
package at.ac.tuwien.dsg.sanalytics.meta;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MetaApp {
public static void main(String[] args) {
SpringApplication.run(MetaApp.class, args);
}
}
| SINCConcept/sanalytics | monitoring-metadata/src/main/java/at/ac/tuwien/dsg/sanalytics/meta/MetaApp.java | Java | apache-2.0 | 306 |
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
namespace ListMetricsExample
{
// snippet-start:[CloudWatch.dotnetv3.ListMetricsExample]
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Amazon.CloudWatch;
using Amazon.CloudWatch.Model;
/// <summary>
/// This example demonstrates how to list metrics for Amazon CloudWatch.
/// The example was created using the AWS SDK for .NET version 3.7 and
/// .NET Core 5.0.
/// </summary>
public class ListMetrics
{
public static async Task Main()
{
IAmazonCloudWatch cwClient = new AmazonCloudWatchClient();
var filter = new DimensionFilter
{
Name = "InstanceType",
Value = "t1.micro",
};
string metricName = "CPUUtilization";
string namespaceName = "AWS/EC2";
await ListMetricsAsync(cwClient, filter, metricName, namespaceName);
}
/// <summary>
/// Retrieve CloudWatch metrics using the supplied filter, metrics name,
/// and namespace.
/// </summary>
/// <param name="client">An initialized CloudWatch client.</param>
/// <param name="filter">The filter to apply in retrieving metrics.</param>
/// <param name="metricName">The metric name for which to retrieve
/// information.</param>
/// <param name="nameSpaceName">The name of the namespace from which
/// to retrieve metric information.</param>
public static async Task ListMetricsAsync(
IAmazonCloudWatch client,
DimensionFilter filter,
string metricName,
string nameSpaceName)
{
var request = new ListMetricsRequest
{
Dimensions = new List<DimensionFilter>() { filter },
MetricName = metricName,
Namespace = nameSpaceName,
};
var response = new ListMetricsResponse();
do
{
response = await client.ListMetricsAsync(request);
if (response.Metrics.Count > 0)
{
foreach (var metric in response.Metrics)
{
Console.WriteLine(metric.MetricName +
" (" + metric.Namespace + ")");
foreach (var dimension in metric.Dimensions)
{
Console.WriteLine(" " + dimension.Name + ": "
+ dimension.Value);
}
}
}
else
{
Console.WriteLine("No metrics found.");
}
request.NextToken = response.NextToken;
}
while (!string.IsNullOrEmpty(response.NextToken));
}
}
// snippet-end:[CloudWatch.dotnetv3.ListMetricsExample]
}
| awsdocs/aws-doc-sdk-examples | dotnetv3/CloudWatch/ListMetricsExample/ListMetricsExample/ListMetrics.cs | C# | apache-2.0 | 3,087 |
package com.elastisys.scale.commons.rest.auth;
import org.jose4j.jwk.RsaJsonWebKey;
import org.jose4j.jwt.JwtClaims;
import org.jose4j.jwt.NumericDate;
import org.jose4j.jwt.consumer.InvalidJwtException;
import org.jose4j.jwt.consumer.JwtConsumer;
import org.jose4j.jwt.consumer.JwtConsumerBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.elastisys.scale.commons.security.jwt.AuthTokenValidator;
import com.elastisys.scale.commons.util.time.UtcTime;
/**
* A simple {@link AuthTokenRequestFilter} that uses the public key of a
* public/private key pair to validate the signature of an authentication token.
*/
public class AsymmetricKeyAuthTokenValidator implements AuthTokenValidator {
private static final Logger LOG = LoggerFactory.getLogger(AsymmetricKeyAuthTokenValidator.class);
/**
* The public/private key pair used to sign and validate a signature.
*/
private final RsaJsonWebKey signatureKeyPair;
/**
* an expected issuer that must be present (in a token's {@code iss} claim)
* in order for validation to succeed. Can be <code>null</code>.
*/
private String expectedIssuer = null;
/**
* Creates an {@link AsymmetricKeyAuthTokenValidator} with a given signature
* key pair.
*
* @param signatureKeyPair
*/
public AsymmetricKeyAuthTokenValidator(RsaJsonWebKey signatureKeyPair) {
this.signatureKeyPair = signatureKeyPair;
}
/**
* Sets an expected issuer that must be present (in a token's {@code iss}
* claim) in order for validation to succeed.
*
* @param expectedIssuer
* @return
*/
public AsymmetricKeyAuthTokenValidator withExpectedIssuer(String expectedIssuer) {
this.expectedIssuer = expectedIssuer;
return this;
}
@Override
public JwtClaims validate(String signedToken) throws InvalidJwtException {
JwtConsumerBuilder jwtConsumerBuilder = new JwtConsumerBuilder()
// verify the signature with the public key
.setVerificationKey(this.signatureKeyPair.getKey());
if (this.expectedIssuer != null) {
jwtConsumerBuilder.setExpectedIssuer(this.expectedIssuer);
}
jwtConsumerBuilder.setRequireExpirationTime();
// evaluate expiration time against current time
NumericDate now = NumericDate.fromMilliseconds(UtcTime.now().getMillis());
jwtConsumerBuilder.setEvaluationTime(now);
JwtConsumer jwtConsumer = jwtConsumerBuilder.build();
// Deserialize and validate the JWT and process it to the Claims
return jwtConsumer.processToClaims(signedToken);
}
}
| elastisys/scale.commons | rest/src/test/java/com/elastisys/scale/commons/rest/auth/AsymmetricKeyAuthTokenValidator.java | Java | apache-2.0 | 2,679 |
/*
* Copyright 2000-2011 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.application.options;
import com.intellij.application.options.codeStyle.CodeStyleBlankLinesPanel;
import com.intellij.application.options.codeStyle.CodeStyleSchemesModel;
import com.intellij.application.options.codeStyle.CodeStyleSpacesPanel;
import com.intellij.application.options.codeStyle.WrappingAndBracesPanel;
import com.intellij.lang.Language;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.application.ApplicationBundle;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.colors.EditorColorsScheme;
import com.intellij.openapi.editor.highlighter.EditorHighlighter;
import com.intellij.openapi.editor.highlighter.EditorHighlighterFactory;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.fileTypes.FileTypes;
import com.intellij.openapi.options.Configurable;
import com.intellij.openapi.options.ConfigurationException;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectUtil;
import com.intellij.openapi.ui.JBMenuItem;
import com.intellij.openapi.ui.JBPopupMenu;
import com.intellij.openapi.util.Disposer;
import com.intellij.psi.codeStyle.*;
import com.intellij.ui.ScrollPaneFactory;
import com.intellij.ui.TabbedPaneWrapper;
import com.intellij.util.containers.hash.HashSet;
import com.intellij.util.ui.GraphicsUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
/**
* @author Rustam Vishnyakov
*/
public abstract class TabbedLanguageCodeStylePanel extends CodeStyleAbstractPanel {
private static final Logger LOG = Logger.getInstance(TabbedLanguageCodeStylePanel.class);
private CodeStyleAbstractPanel myActiveTab;
private List<CodeStyleAbstractPanel> myTabs;
private JPanel myPanel;
private TabbedPaneWrapper myTabbedPane;
private final PredefinedCodeStyle[] myPredefinedCodeStyles;
private JPopupMenu myCopyFromMenu;
private @Nullable TabChangeListener myListener;
protected TabbedLanguageCodeStylePanel(@Nullable Language language, CodeStyleSettings currentSettings, CodeStyleSettings settings) {
super(language, currentSettings, settings);
myPredefinedCodeStyles = getPredefinedStyles();
}
/**
* Initializes all standard tabs: "Tabs and Indents", "Spaces", "Blank Lines" and "Wrapping and Braces" if relevant.
* For "Tabs and Indents" LanguageCodeStyleSettingsProvider must instantiate its own indent options, for other standard tabs it
* must return false in usesSharedPreview() method. You can override this method to add your own tabs by calling super.initTabs() and
* then addTab() methods or selectively add needed tabs with your own implementation.
* @param settings Code style settings to be used with initialized panels.
* @see LanguageCodeStyleSettingsProvider
* @see #addIndentOptionsTab(CodeStyleSettings)
* @see #addSpacesTab(CodeStyleSettings)
* @see #addBlankLinesTab(CodeStyleSettings)
* @see #addWrappingAndBracesTab(CodeStyleSettings)
*/
protected void initTabs(CodeStyleSettings settings) {
LanguageCodeStyleSettingsProvider provider = LanguageCodeStyleSettingsProvider.forLanguage(getDefaultLanguage());
addIndentOptionsTab(settings);
if (provider != null) {
addSpacesTab(settings);
addWrappingAndBracesTab(settings);
addBlankLinesTab(settings);
}
}
/**
* Adds "Tabs and Indents" tab if the language has its own LanguageCodeStyleSettings provider and instantiates indent options in
* getDefaultSettings() method.
* @param settings CodeStyleSettings to be used with "Tabs and Indents" panel.
*/
protected void addIndentOptionsTab(CodeStyleSettings settings) {
LanguageCodeStyleSettingsProvider provider = LanguageCodeStyleSettingsProvider.forLanguage(getDefaultLanguage());
if (provider != null) {
IndentOptionsEditor indentOptionsEditor = provider.getIndentOptionsEditor();
if (indentOptionsEditor != null) {
MyIndentOptionsWrapper indentOptionsWrapper = new MyIndentOptionsWrapper(settings, provider, indentOptionsEditor);
addTab(indentOptionsWrapper);
}
}
}
protected void addSpacesTab(CodeStyleSettings settings) {
addTab(new MySpacesPanel(settings));
}
protected void addBlankLinesTab(CodeStyleSettings settings) {
addTab(new MyBlankLinesPanel(settings));
}
protected void addWrappingAndBracesTab(CodeStyleSettings settings) {
addTab(new MyWrappingAndBracesPanel(settings));
}
protected void ensureTabs() {
if (myTabs == null) {
myPanel = new JPanel();
myPanel.setLayout(new BorderLayout());
myTabbedPane = new TabbedPaneWrapper(this);
myTabbedPane.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
if (myListener != null) {
String title = myTabbedPane.getSelectedTitle();
if (title != null) {
myListener.tabChanged(TabbedLanguageCodeStylePanel.this, title);
}
}
}
});
myTabs = new ArrayList<>();
myPanel.add(myTabbedPane.getComponent());
initTabs(getSettings());
}
assert !myTabs.isEmpty();
}
public void showSetFrom(Component component) {
initCopyFromMenu();
myCopyFromMenu.show(component, 0, component.getHeight());
}
private void initCopyFromMenu() {
if (myCopyFromMenu == null) {
myCopyFromMenu = new JBPopupMenu();
setupCopyFromMenu(myCopyFromMenu);
}
}
/**
* Adds a tab with the given CodeStyleAbstractPanel. Tab title is taken from getTabTitle() method.
* @param tab The panel to use in a tab.
*/
protected final void addTab(CodeStyleAbstractPanel tab) {
myTabs.add(tab);
tab.setShouldUpdatePreview(true);
addPanelToWatch(tab.getPanel());
myTabbedPane.addTab(tab.getTabTitle(), tab.getPanel());
if (myActiveTab == null) {
myActiveTab = tab;
}
}
private void addTab(Configurable configurable) {
ConfigurableWrapper wrapper = new ConfigurableWrapper(configurable, getSettings());
addTab(wrapper);
}
/**
* Creates and adds a tab from CodeStyleSettingsProvider. The provider may return false in hasSettingsPage() method in order not to be
* shown at top level of code style settings.
* @param provider The provider used to create a settings page.
*/
protected final void createTab(CodeStyleSettingsProvider provider) {
if (provider.hasSettingsPage()) return;
Configurable configurable = provider.createSettingsPage(getCurrentSettings(), getSettings());
addTab(configurable);
}
@Override
public final void setModel(CodeStyleSchemesModel model) {
super.setModel(model);
ensureTabs();
for (CodeStyleAbstractPanel tab : myTabs) {
tab.setModel(model);
}
}
@Override
protected int getRightMargin() {
ensureTabs();
return myActiveTab.getRightMargin();
}
@Override
protected EditorHighlighter createHighlighter(EditorColorsScheme scheme) {
ensureTabs();
return myActiveTab.createHighlighter(scheme);
}
@NotNull
@Override
protected FileType getFileType() {
ensureTabs();
return myActiveTab.getFileType();
}
@Override
protected String getPreviewText() {
ensureTabs();
return myActiveTab.getPreviewText();
}
@Override
protected void updatePreview(boolean useDefaultSample) {
ensureTabs();
for (CodeStyleAbstractPanel tab : myTabs) {
tab.updatePreview(useDefaultSample);
}
}
@Override
public void onSomethingChanged() {
ensureTabs();
for (CodeStyleAbstractPanel tab : myTabs) {
tab.setShouldUpdatePreview(true);
tab.onSomethingChanged();
}
}
@Override
public void apply(CodeStyleSettings settings) throws ConfigurationException {
ensureTabs();
for (CodeStyleAbstractPanel tab : myTabs) {
tab.apply(settings);
}
}
@Override
public void dispose() {
for (CodeStyleAbstractPanel tab : myTabs) {
Disposer.dispose(tab);
}
super.dispose();
}
@Override
public boolean isModified(CodeStyleSettings settings) {
ensureTabs();
for (CodeStyleAbstractPanel tab : myTabs) {
if (tab.isModified(settings)) {
return true;
}
}
return false;
}
@Override
public JComponent getPanel() {
return myPanel;
}
@Override
protected void resetImpl(CodeStyleSettings settings) {
ensureTabs();
for (CodeStyleAbstractPanel tab : myTabs) {
tab.resetImpl(settings);
}
}
@Override
public void setupCopyFromMenu(JPopupMenu copyMenu) {
super.setupCopyFromMenu(copyMenu);
if (myPredefinedCodeStyles.length > 0) {
JMenu langs = new JMenu("Language") {
@Override
public void paint(Graphics g) {
GraphicsUtil.setupAntialiasing(g);
super.paint(g);
}
}; //TODO<rv>: Move to resource bundle
copyMenu.add(langs);
fillLanguages(langs);
JMenu predefined = new JMenu("Predefined Style") {
@Override
public void paint(Graphics g) {
GraphicsUtil.setupAntialiasing(g);
super.paint(g);
}
}; //TODO<rv>: Move to resource bundle
copyMenu.add(predefined);
fillPredefined(predefined);
}
else {
fillLanguages(copyMenu);
}
}
private void fillLanguages(JComponent parentMenu) {
Language[] languages = LanguageCodeStyleSettingsProvider.getLanguagesWithCodeStyleSettings();
@SuppressWarnings("UnnecessaryFullyQualifiedName")
java.util.List<JMenuItem> langItems = new ArrayList<>();
for (final Language lang : languages) {
if (!lang.equals(getDefaultLanguage())) {
final String langName = LanguageCodeStyleSettingsProvider.getLanguageName(lang);
JMenuItem langItem = new JBMenuItem(langName);
langItem.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
applyLanguageSettings(lang);
}
});
langItems.add(langItem);
}
}
Collections.sort(langItems, (item1, item2) -> item1.getText().compareToIgnoreCase(item2.getText()));
for (JMenuItem langItem : langItems) {
parentMenu.add(langItem);
}
}
private void fillPredefined(JMenuItem parentMenu) {
for (final PredefinedCodeStyle predefinedCodeStyle : myPredefinedCodeStyles) {
JMenuItem predefinedItem = new JBMenuItem(predefinedCodeStyle.getName());
parentMenu.add(predefinedItem);
predefinedItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
applyPredefinedStyle(predefinedCodeStyle.getName());
}
});
}
}
private PredefinedCodeStyle[] getPredefinedStyles() {
final Language language = getDefaultLanguage();
final List<PredefinedCodeStyle> result = new ArrayList<>();
for (PredefinedCodeStyle codeStyle : PredefinedCodeStyle.EP_NAME.getExtensions()) {
if (codeStyle.getLanguage().equals(language)) {
result.add(codeStyle);
}
}
return result.toArray(new PredefinedCodeStyle[0]);
}
private void applyLanguageSettings(Language lang) {
final Project currProject = ProjectUtil.guessCurrentProject(getPanel());
CodeStyleSettings rootSettings = CodeStyleSettingsManager.getSettings(currProject);
CodeStyleSettings targetSettings = getSettings();
if (rootSettings.getCommonSettings(lang) == null || targetSettings.getCommonSettings(getDefaultLanguage()) == null)
return;
applyLanguageSettings(lang, rootSettings, targetSettings);
reset(targetSettings);
onSomethingChanged();
}
protected void applyLanguageSettings(Language lang, CodeStyleSettings rootSettings, CodeStyleSettings targetSettings) {
CommonCodeStyleSettings sourceCommonSettings = rootSettings.getCommonSettings(lang);
CommonCodeStyleSettings targetCommonSettings = targetSettings.getCommonSettings(getDefaultLanguage());
CommonCodeStyleSettingsManager.copy(sourceCommonSettings, targetCommonSettings);
}
private void applyPredefinedStyle(String styleName) {
for (PredefinedCodeStyle style : myPredefinedCodeStyles) {
if (style.getName().equals(styleName)) {
applyPredefinedSettings(style);
}
}
}
//========================================================================================================================================
protected class MySpacesPanel extends CodeStyleSpacesPanel {
public MySpacesPanel(CodeStyleSettings settings) {
super(settings);
}
@Override
protected boolean shouldHideOptions() {
return true;
}
@Override
public Language getDefaultLanguage() {
return TabbedLanguageCodeStylePanel.this.getDefaultLanguage();
}
}
protected class MyBlankLinesPanel extends CodeStyleBlankLinesPanel {
public MyBlankLinesPanel(CodeStyleSettings settings) {
super(settings);
}
@Override
public Language getDefaultLanguage() {
return TabbedLanguageCodeStylePanel.this.getDefaultLanguage();
}
}
protected class MyWrappingAndBracesPanel extends WrappingAndBracesPanel {
public MyWrappingAndBracesPanel(CodeStyleSettings settings) {
super(settings);
}
@Override
public Language getDefaultLanguage() {
return TabbedLanguageCodeStylePanel.this.getDefaultLanguage();
}
}
//========================================================================================================================================
private class ConfigurableWrapper extends CodeStyleAbstractPanel {
private final Configurable myConfigurable;
private JComponent myComponent;
public ConfigurableWrapper(@NotNull Configurable configurable, CodeStyleSettings settings) {
super(settings);
myConfigurable = configurable;
Disposer.register(this, new Disposable() {
@Override
public void dispose() {
myConfigurable.disposeUIResources();
}
});
}
@Override
protected int getRightMargin() {
return 0;
}
@Nullable
@Override
protected EditorHighlighter createHighlighter(EditorColorsScheme scheme) {
return null;
}
@SuppressWarnings("ConstantConditions")
@NotNull
@Override
protected FileType getFileType() {
Language language = getDefaultLanguage();
return language != null ? language.getAssociatedFileType() : FileTypes.PLAIN_TEXT;
}
@Override
public Language getDefaultLanguage() {
return TabbedLanguageCodeStylePanel.this.getDefaultLanguage();
}
@Override
protected String getTabTitle() {
return myConfigurable.getDisplayName();
}
@Override
protected String getPreviewText() {
return null;
}
@Override
public void apply(CodeStyleSettings settings) throws ConfigurationException {
if (myConfigurable instanceof CodeStyleConfigurable) {
((CodeStyleConfigurable)myConfigurable).apply(settings);
}
else {
myConfigurable.apply();
}
}
@Override
public boolean isModified(CodeStyleSettings settings) {
return myConfigurable.isModified();
}
@Nullable
@Override
public JComponent getPanel() {
if (myComponent == null) {
myComponent = myConfigurable.createComponent();
}
return myComponent;
}
@Override
protected void resetImpl(CodeStyleSettings settings) {
if (myConfigurable instanceof CodeStyleConfigurable) {
((CodeStyleConfigurable)myConfigurable).reset(settings);
}
else {
myConfigurable.reset();
}
}
}
@Override
public Set<String> processListOptions() {
final Set<String> result = new HashSet<>();
for (CodeStyleAbstractPanel tab : myTabs) {
result.addAll(tab.processListOptions());
}
return result;
}
//========================================================================================================================================
protected class MyIndentOptionsWrapper extends CodeStyleAbstractPanel {
private final IndentOptionsEditor myEditor;
private final LanguageCodeStyleSettingsProvider myProvider;
private final JPanel myTopPanel = new JPanel(new BorderLayout());
private final JPanel myLeftPanel = new JPanel(new BorderLayout());
private final JPanel myRightPanel;
protected MyIndentOptionsWrapper(CodeStyleSettings settings, LanguageCodeStyleSettingsProvider provider, IndentOptionsEditor editor) {
super(settings);
myProvider = provider;
myTopPanel.add(myLeftPanel, BorderLayout.WEST);
myRightPanel = new JPanel();
installPreviewPanel(myRightPanel);
myEditor = editor;
if (myEditor != null) {
JPanel panel = myEditor.createPanel();
panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
JScrollPane scroll = ScrollPaneFactory.createScrollPane(panel, true);
scroll.setPreferredSize(new Dimension(panel.getPreferredSize().width + scroll.getVerticalScrollBar().getPreferredSize().width + 5, -1));
myLeftPanel.add(scroll, BorderLayout.CENTER);
}
myTopPanel.add(myRightPanel, BorderLayout.CENTER);
}
@Override
protected int getRightMargin() {
return myProvider.getRightMargin(LanguageCodeStyleSettingsProvider.SettingsType.INDENT_SETTINGS);
}
@Override
protected EditorHighlighter createHighlighter(EditorColorsScheme scheme) {
//noinspection NullableProblems
return EditorHighlighterFactory.getInstance().createEditorHighlighter(getFileType(), scheme, null);
}
@SuppressWarnings("ConstantConditions")
@NotNull
@Override
protected FileType getFileType() {
Language language = TabbedLanguageCodeStylePanel.this.getDefaultLanguage();
return language != null ? language.getAssociatedFileType() : FileTypes.PLAIN_TEXT;
}
@Override
protected String getPreviewText() {
return myProvider != null ? myProvider.getCodeSample(LanguageCodeStyleSettingsProvider.SettingsType.INDENT_SETTINGS) : "Loading...";
}
@Override
protected String getFileExt() {
if (myProvider != null) {
String ext = myProvider.getFileExt();
if (ext != null) return ext;
}
return super.getFileExt();
}
@Override
public void apply(CodeStyleSettings settings) {
CommonCodeStyleSettings.IndentOptions indentOptions = getIndentOptions(settings);
if (indentOptions == null) return;
myEditor.apply(settings, indentOptions);
}
@Override
public boolean isModified(CodeStyleSettings settings) {
CommonCodeStyleSettings.IndentOptions indentOptions = getIndentOptions(settings);
if (indentOptions == null) return false;
return myEditor.isModified(settings, indentOptions);
}
@Override
public JComponent getPanel() {
return myTopPanel;
}
@Override
protected void resetImpl(CodeStyleSettings settings) {
CommonCodeStyleSettings.IndentOptions indentOptions = getIndentOptions(settings);
if (indentOptions == null) {
myEditor.setEnabled(false);
indentOptions = settings.getIndentOptions(myProvider.getLanguage().getAssociatedFileType());
}
myEditor.reset(settings, indentOptions);
}
@Nullable
private CommonCodeStyleSettings.IndentOptions getIndentOptions(CodeStyleSettings settings) {
return settings.getCommonSettings(getDefaultLanguage()).getIndentOptions();
}
@Override
public Language getDefaultLanguage() {
return TabbedLanguageCodeStylePanel.this.getDefaultLanguage();
}
@Override
protected String getTabTitle() {
return ApplicationBundle.message("title.tabs.and.indents");
}
@Override
public void onSomethingChanged() {
super.onSomethingChanged();
myEditor.setEnabled(true);
}
}
public interface TabChangeListener {
void tabChanged(@NotNull TabbedLanguageCodeStylePanel source, @NotNull String tabTitle);
}
public void setListener(@Nullable TabChangeListener listener) {
myListener = listener;
}
public void changeTab(@NotNull String tabTitle) {
myTabbedPane.setSelectedTitle(tabTitle);
}
}
| mglukhikh/intellij-community | platform/lang-impl/src/com/intellij/application/options/TabbedLanguageCodeStylePanel.java | Java | apache-2.0 | 21,316 |
/* Copyright 2014 Rick Warren
*
* 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 crud.voldemort;
import java.util.Objects;
import crud.ReadableResourceProvider;
import crud.WritableResourceProvider;
import voldemort.client.StoreClient;
import voldemort.versioning.Version;
import voldemort.versioning.Versioned;
public class VoldemortResourceProvider<K, V>
implements ReadableResourceProvider<K, Versioned<V>>,
WritableResourceProvider<K, Versioned<V>, Version> {
private final StoreClient<K, V> store;
public VoldemortResourceProvider(final StoreClient<K, V> store) {
this.store = Objects.requireNonNull(store);
}
@Override
public VoldemortResource<V> get(final K key) {
return VoldemortResource.create(this.store, key);
}
}
| rickbw/crud-voldemort | src/main/java/crud/voldemort/VoldemortResourceProvider.java | Java | apache-2.0 | 1,302 |
/*
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. 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.wso2.msf4j.internal.websocket;
import org.wso2.msf4j.websocket.exception.WebSocketEndpointAnnotationException;
import org.wso2.msf4j.websocket.exception.WebSocketEndpointMethodReturnTypeException;
import org.wso2.msf4j.websocket.exception.WebSocketMethodParameterException;
import org.wso2.transport.http.netty.contract.websocket.WebSocketConnection;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.nio.ByteBuffer;
import javax.websocket.CloseReason;
import javax.websocket.PongMessage;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
/**
* This validates all the methods which are relevant to WebSocket Server endpoint using JSR-356 specification.
*/
public class EndpointValidator {
/**
* Validate the whole WebSocket endpoint.
*
* @return true if validation is completed without any error.
* @throws WebSocketEndpointAnnotationException if error on an annotation declaration occurred.
* @throws WebSocketMethodParameterException if the method parameters are invalid for a given method according
* to JSR-356 specification.
*/
public boolean validate(Object webSocketEndpoint) throws WebSocketEndpointAnnotationException,
WebSocketMethodParameterException,
WebSocketEndpointMethodReturnTypeException {
if (webSocketEndpoint == null) {
return false;
}
return validateURI(webSocketEndpoint) && validateOnStringMethod(webSocketEndpoint) &&
validateOnBinaryMethod(webSocketEndpoint) && validateOnPongMethod(webSocketEndpoint) &&
validateOnOpenMethod(webSocketEndpoint) && validateOnCloseMethod(webSocketEndpoint) &&
validateOnErrorMethod(webSocketEndpoint);
}
private boolean validateURI(Object webSocketEndpoint) throws WebSocketEndpointAnnotationException {
if (webSocketEndpoint.getClass().isAnnotationPresent(ServerEndpoint.class)) {
return true;
}
throw new WebSocketEndpointAnnotationException("Server Endpoint is not defined.");
}
private boolean validateOnStringMethod(Object webSocketEndpoint)
throws WebSocketMethodParameterException, WebSocketEndpointMethodReturnTypeException {
EndpointDispatcher dispatcher = new EndpointDispatcher();
Method method;
if (dispatcher.getOnStringMessageMethod(webSocketEndpoint).isPresent()) {
method = dispatcher.getOnStringMessageMethod(webSocketEndpoint).get();
} else {
return true;
}
validateReturnType(method);
boolean foundPrimaryString = false;
for (Parameter parameter: method.getParameters()) {
Class<?> paraType = parameter.getType();
if (paraType == String.class) {
if (parameter.getAnnotation(PathParam.class) == null) {
if (foundPrimaryString) {
throw new WebSocketMethodParameterException("Invalid parameter found on text message method: " +
"More than one string parameter without " +
"@PathParam annotation.");
}
foundPrimaryString = true;
}
} else if (paraType != WebSocketConnection.class) {
throw new WebSocketMethodParameterException("Invalid parameter found on text message method: " +
paraType);
}
}
return foundPrimaryString;
}
private boolean validateOnBinaryMethod(Object webSocketEndpoint)
throws WebSocketMethodParameterException, WebSocketEndpointMethodReturnTypeException {
EndpointDispatcher dispatcher = new EndpointDispatcher();
Method method;
if (dispatcher.getOnBinaryMessageMethod(webSocketEndpoint).isPresent()) {
method = dispatcher.getOnBinaryMessageMethod(webSocketEndpoint).get();
} else {
return true;
}
validateReturnType(method);
boolean foundPrimaryBuffer = false;
boolean foundIsFinal = false;
for (Parameter parameter: method.getParameters()) {
Class<?> paraType = parameter.getType();
if (paraType == String.class) {
if (parameter.getAnnotation(PathParam.class) == null) {
throw new WebSocketMethodParameterException("Invalid parameter found on binary message method: " +
"string parameter without " +
"@PathParam annotation.");
}
} else if (paraType == ByteBuffer.class || paraType == byte[].class) {
if (foundPrimaryBuffer) {
throw new WebSocketMethodParameterException("Invalid parameter found on binary message method: " +
"only one ByteBuffer/byte[] " +
"should be declared.");
}
foundPrimaryBuffer = true;
} else if (paraType == boolean.class) {
if (foundIsFinal) {
throw new WebSocketMethodParameterException("Invalid parameter found on binary message method: " +
"only one boolean should be declared and " +
"found more than one.");
}
foundIsFinal = true;
} else if (paraType != WebSocketConnection.class) {
throw new WebSocketMethodParameterException("Invalid parameter found on binary message method: " +
paraType);
}
}
return foundPrimaryBuffer;
}
private boolean validateOnPongMethod(Object webSocketEndpoint)
throws WebSocketMethodParameterException, WebSocketEndpointMethodReturnTypeException {
EndpointDispatcher dispatcher = new EndpointDispatcher();
Method method;
if (dispatcher.getOnPongMessageMethod(webSocketEndpoint).isPresent()) {
method = dispatcher.getOnPongMessageMethod(webSocketEndpoint).get();
} else {
return true;
}
validateReturnType(method);
boolean foundPrimaryPong = false;
for (Parameter parameter: method.getParameters()) {
Class<?> paraType = parameter.getType();
if (paraType == String.class) {
if (parameter.getAnnotation(PathParam.class) == null) {
throw new WebSocketMethodParameterException("Invalid parameter found on pong message method: " +
"string parameter without " +
"@PathParam annotation.");
}
} else if (paraType == PongMessage.class) {
if (foundPrimaryPong) {
throw new WebSocketMethodParameterException("Invalid parameter found on pong message method: " +
"only one PongMessage should be declared.");
}
foundPrimaryPong = true;
} else if (paraType != WebSocketConnection.class) {
throw new WebSocketMethodParameterException("Invalid parameter found on pong message method: " +
paraType);
}
}
return foundPrimaryPong;
}
private boolean validateOnOpenMethod(Object webSocketEndpoint)
throws WebSocketMethodParameterException, WebSocketEndpointMethodReturnTypeException {
EndpointDispatcher dispatcher = new EndpointDispatcher();
Method method;
if (dispatcher.getOnOpenMethod(webSocketEndpoint).isPresent()) {
method = dispatcher.getOnOpenMethod(webSocketEndpoint).get();
} else {
return true;
}
validateReturnType(method);
for (Parameter parameter: method.getParameters()) {
Class<?> paraType = parameter.getType();
if (paraType == String.class) {
if (parameter.getAnnotation(PathParam.class) == null) {
throw new WebSocketMethodParameterException("Invalid parameter found on open message method: " +
"string parameter without " +
"@PathParam annotation.");
}
} else if (paraType != WebSocketConnection.class) {
throw new WebSocketMethodParameterException("Invalid parameter found on open message method: " +
paraType);
}
}
return true;
}
private boolean validateOnCloseMethod(Object webSocketEndpoint)
throws WebSocketMethodParameterException, WebSocketEndpointMethodReturnTypeException {
EndpointDispatcher dispatcher = new EndpointDispatcher();
Method method;
if (dispatcher.getOnCloseMethod(webSocketEndpoint).isPresent()) {
method = dispatcher.getOnCloseMethod(webSocketEndpoint).get();
} else {
return true;
}
validateReturnType(method);
for (Parameter parameter: method.getParameters()) {
Class<?> paraType = parameter.getType();
if (paraType == String.class) {
if (parameter.getAnnotation(PathParam.class) == null) {
throw new WebSocketMethodParameterException("Invalid parameter found on close message method: " +
"string parameter without " +
"@PathParam annotation.");
}
} else if (paraType != CloseReason.class && paraType != WebSocketConnection.class) {
throw new WebSocketMethodParameterException("Invalid parameter found on close message method: " +
paraType);
}
}
return true;
}
private boolean validateOnErrorMethod(Object webSocketEndpoint)
throws WebSocketMethodParameterException, WebSocketEndpointMethodReturnTypeException {
EndpointDispatcher dispatcher = new EndpointDispatcher();
Method method;
if (dispatcher.getOnErrorMethod(webSocketEndpoint).isPresent()) {
method = dispatcher.getOnErrorMethod(webSocketEndpoint).get();
} else {
return true;
}
validateReturnType(method);
boolean foundPrimaryThrowable = false;
for (Parameter parameter: method.getParameters()) {
Class<?> paraType = parameter.getType();
if (paraType == String.class) {
if (parameter.getAnnotation(PathParam.class) == null) {
throw new WebSocketMethodParameterException("Invalid parameter found on error message method: " +
"string parameter without " +
"@PathParam annotation.");
}
} else if (paraType == Throwable.class) {
if (foundPrimaryThrowable) {
throw new WebSocketMethodParameterException("Invalid parameter found on pong message method: " +
"only one Throwable should be declared.");
}
foundPrimaryThrowable = true;
} else if (paraType != WebSocketConnection.class) {
throw new WebSocketMethodParameterException("Invalid parameter found on error message method: " +
paraType);
}
}
if (!foundPrimaryThrowable) {
throw new WebSocketMethodParameterException("Mandatory parameter for on error method " + Throwable.class +
" not found.");
}
return foundPrimaryThrowable;
}
private boolean validateReturnType(Method method) throws WebSocketEndpointMethodReturnTypeException {
Class<?> returnType = method.getReturnType();
boolean foundCorrectReturnType = returnType == String.class || returnType == ByteBuffer.class ||
returnType == byte[].class || returnType == PongMessage.class || returnType == void.class;
if (!foundCorrectReturnType) {
throw new WebSocketEndpointMethodReturnTypeException("Unexpected method return type: " + returnType);
}
return foundCorrectReturnType;
}
}
| wso2/product-mss | core/src/main/java/org/wso2/msf4j/internal/websocket/EndpointValidator.java | Java | apache-2.0 | 14,197 |
package com.monospace.framework;
import com.monospace.framework.Graphics.ImageFormat;
import android.graphics.Paint;
public interface Graphics {
public static enum ImageFormat {
ARGB8888, ARGB4444, RGB565
}
public Image newImage(String fileName, ImageFormat format);
public void clearScreen(int color);
public void drawLine(int x, int y, int x2, int y2, int color);
public void drawRect(int x, int y, int width, int height, int color);
public void drawImage(Image image, int x, int y, int srcX, int srcY,
int srcWidth, int srcHeight);
public void drawImage(Image Image, int x, int y);
public void drawScaledImage(Image Image, int x, int y, int width, int height, int srcX, int srcY, int srcWidth, int srcHeight);
public void drawString(String text, int x, int y, Paint paint);
public int getWidth();
public int getHeight();
public void drawARGB(int i, int j, int k, int l);
void drawRectHollow(int x, int y, int width, int height, int color);
void drawCircle(float cx, float cy, float radius, Paint paint);
Image newRotateImage(String fileName, ImageFormat format, int degrees);
}
| TaintedWind/MonospaceAndroidEdition | src/com/monospace/framework/Graphics.java | Java | apache-2.0 | 1,122 |
package api
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"net/url"
"os"
"strconv"
)
type DocumentResponse struct {
Id string `json:"id,omitempty"`
Title string `json:"title,omitempty"`
Content string `json:"content,omitempty"`
ContentType string `json:"contentType,omitempty"`
Origin string `json:"origin,omitempty"`
Date string `json:"date,omitempty"`
Owner string `json:"owner,omitempty"`
Ghost bool `json:"ghost,omitempty"`
}
type DocumentsResponse struct {
Documents []DocumentResponse `json:"hits"`
}
func (k *Client) GetDocuments(query string, order string, size int, from int) ([]DocumentResponse, error) {
q := make(url.Values)
q.Add("size", strconv.Itoa(size))
q.Add("from", strconv.Itoa(from))
q.Add("order", order)
if query != "" {
q.Add("q", query)
}
res, err := k.Get("/v2/documents", &q)
if err != nil {
return nil, err
}
defer res.Body.Close()
if res.StatusCode >= 400 {
io.Copy(os.Stderr, res.Body)
return nil, errors.New(res.Status)
}
var result DocumentsResponse
err = json.NewDecoder(res.Body).Decode(&result)
return result.Documents, err
}
func (k *Client) GetDocument(docid string) (*DocumentResponse, error) {
res, err := k.Get("/v2/documents/"+docid, nil)
if err != nil {
return nil, err
}
defer res.Body.Close()
if res.StatusCode >= 400 {
io.Copy(os.Stderr, res.Body)
return nil, errors.New(res.Status)
}
var result DocumentResponse
err = json.NewDecoder(res.Body).Decode(&result)
return &result, err
}
func (k *Client) CreateDocument(doc *DocumentResponse) (*DocumentResponse, error) {
b := new(bytes.Buffer)
json.NewEncoder(b).Encode(doc)
fmt.Fprintf(os.Stdout, "Posting: %s", b)
res, err := k.Post("/v2/documents", nil, b)
if err != nil {
return nil, err
}
defer res.Body.Close()
if res.StatusCode >= 400 {
io.Copy(os.Stderr, res.Body)
return nil, errors.New(res.Status)
}
var result DocumentResponse
err = json.NewDecoder(res.Body).Decode(&result)
return &result, err
}
func (k *Client) RemoveDocument(docid string) error {
res, err := k.Delete("/v2/documents/"+docid, nil)
if err != nil {
return err
}
defer res.Body.Close()
if res.StatusCode >= 400 {
io.Copy(os.Stderr, res.Body)
return errors.New(res.Status)
}
return nil
}
func (k *Client) RestoreDocument(docid string) (*DocumentResponse, error) {
res, err := k.Put("/v2/graveyard/documents/"+docid, nil, nil)
if err != nil {
return nil, err
}
defer res.Body.Close()
if res.StatusCode >= 400 {
io.Copy(os.Stderr, res.Body)
return nil, errors.New(res.Status)
}
var result DocumentResponse
err = json.NewDecoder(res.Body).Decode(&result)
return &result, err
}
| ncarlier/keeper-cli | api/document.go | GO | apache-2.0 | 2,709 |
/*
* Copyright (c) 2005-2013 Clark & Parsia, LLC. <http://www.clarkparsia.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 com.complexible.common.io;
import java.io.DataInput;
import java.io.IOException;
import com.google.common.collect.ForwardingObject;
/**
* <p>Base class for creating a {@link DataInput} decorator</p>
*
* @author Michael Grove
* @since 1.0
* @version 1.0
*/
public class ForwardingDataInput extends ForwardingObject implements DataInput {
private final DataInput mInput;
public ForwardingDataInput(final DataInput theInput) {
mInput = theInput;
}
/**
* @inheritDoc
*/
@Override
protected DataInput delegate() {
return mInput;
}
/**
* @inheritDoc
*/
@Override
public boolean readBoolean() throws IOException {
return mInput.readBoolean();
}
/**
* @inheritDoc
*/
@Override
public byte readByte() throws IOException {
return mInput.readByte();
}
/**
* @inheritDoc
*/
@Override
public char readChar() throws IOException {
return mInput.readChar();
}
/**
* @inheritDoc
*/
@Override
public double readDouble() throws IOException {
return mInput.readDouble();
}
/**
* @inheritDoc
*/
@Override
public float readFloat() throws IOException {
return mInput.readFloat();
}
/**
* @inheritDoc
*/
@Override
public void readFully(final byte[] theBytes) throws IOException {
mInput.readFully(theBytes);
}
/**
* @inheritDoc
*/
@Override
public void readFully(final byte[] theBytes, final int i, final int i2) throws IOException {
mInput.readFully(theBytes, i, i2);
}
/**
* @inheritDoc
*/
@Override
public int readInt() throws IOException {
return mInput.readInt();
}
/**
* @inheritDoc
*/
@Override
public String readLine() throws IOException {
return mInput.readLine();
}
/**
* @inheritDoc
*/
@Override
public long readLong() throws IOException {
return mInput.readLong();
}
/**
* @inheritDoc
*/
@Override
public short readShort() throws IOException {
return mInput.readShort();
}
/**
* @inheritDoc
*/
@Override
public int readUnsignedByte() throws IOException {
return mInput.readUnsignedByte();
}
/**
* @inheritDoc
*/
@Override
public int readUnsignedShort() throws IOException {
return mInput.readUnsignedShort();
}
/**
* @inheritDoc
*/
@Override
public String readUTF() throws IOException {
return mInput.readUTF();
}
/**
* @inheritDoc
*/
@Override
public int skipBytes(final int i) throws IOException {
return mInput.skipBytes(i);
}
}
| schwarzmx/cp-common-utils | core/main/src/com/complexible/common/io/ForwardingDataInput.java | Java | apache-2.0 | 3,457 |
/*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.amazonaws.services.opsworks.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.Request;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.opsworks.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.protocol.*;
import com.amazonaws.protocol.Protocol;
import com.amazonaws.annotation.SdkInternalApi;
/**
* UnassignVolumeRequest Marshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class UnassignVolumeRequestProtocolMarshaller implements Marshaller<Request<UnassignVolumeRequest>, UnassignVolumeRequest> {
private static final OperationInfo SDK_OPERATION_BINDING = OperationInfo.builder().protocol(Protocol.AWS_JSON).requestUri("/")
.httpMethodName(HttpMethodName.POST).hasExplicitPayloadMember(false).hasPayloadMembers(true)
.operationIdentifier("OpsWorks_20130218.UnassignVolume").serviceName("AWSOpsWorks").build();
private final com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory;
public UnassignVolumeRequestProtocolMarshaller(com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory) {
this.protocolFactory = protocolFactory;
}
public Request<UnassignVolumeRequest> marshall(UnassignVolumeRequest unassignVolumeRequest) {
if (unassignVolumeRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
final ProtocolRequestMarshaller<UnassignVolumeRequest> protocolMarshaller = protocolFactory.createProtocolMarshaller(SDK_OPERATION_BINDING,
unassignVolumeRequest);
protocolMarshaller.startMarshalling();
UnassignVolumeRequestMarshaller.getInstance().marshall(unassignVolumeRequest, protocolMarshaller);
return protocolMarshaller.finishMarshalling();
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
| aws/aws-sdk-java | aws-java-sdk-opsworks/src/main/java/com/amazonaws/services/opsworks/model/transform/UnassignVolumeRequestProtocolMarshaller.java | Java | apache-2.0 | 2,683 |
/*
* Copyright 2017 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.keycloak.testsuite.util.saml;
import org.keycloak.testsuite.util.SamlClientBuilder;
import org.keycloak.dom.saml.v2.assertion.NameIDType;
import org.keycloak.dom.saml.v2.protocol.LogoutRequestType;
import org.keycloak.saml.SAML2LogoutRequestBuilder;
import org.keycloak.saml.common.util.DocumentUtil;
import org.keycloak.testsuite.util.SamlClient.Binding;
import java.net.URI;
import java.util.function.Supplier;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.client.CloseableHttpClient;
/**
*
* @author hmlnarik
*/
public class CreateLogoutRequestStepBuilder extends SamlDocumentStepBuilder<LogoutRequestType, CreateLogoutRequestStepBuilder> {
private final URI authServerSamlUrl;
private final String issuer;
private final Binding requestBinding;
private Supplier<String> sessionIndex = () -> null;
private Supplier<NameIDType> nameId = () -> null;
private Supplier<String> relayState = () -> null;
public CreateLogoutRequestStepBuilder(URI authServerSamlUrl, String issuer, Binding requestBinding, SamlClientBuilder clientBuilder) {
super(clientBuilder);
this.authServerSamlUrl = authServerSamlUrl;
this.issuer = issuer;
this.requestBinding = requestBinding;
}
public String sessionIndex() {
return sessionIndex.get();
}
public CreateLogoutRequestStepBuilder sessionIndex(String sessionIndex) {
this.sessionIndex = () -> sessionIndex;
return this;
}
public CreateLogoutRequestStepBuilder sessionIndex(Supplier<String> sessionIndex) {
this.sessionIndex = sessionIndex;
return this;
}
public String relayState() {
return relayState.get();
}
public CreateLogoutRequestStepBuilder relayState(String relayState) {
this.relayState = () -> relayState;
return this;
}
public CreateLogoutRequestStepBuilder relayState(Supplier<String> relayState) {
this.relayState = relayState;
return this;
}
public NameIDType nameId() {
return nameId.get();
}
public CreateLogoutRequestStepBuilder nameId(NameIDType nameId) {
this.nameId = () -> nameId;
return this;
}
public CreateLogoutRequestStepBuilder nameId(Supplier<NameIDType> nameId) {
this.nameId = nameId;
return this;
}
@Override
public HttpUriRequest perform(CloseableHttpClient client, URI currentURI, CloseableHttpResponse currentResponse, HttpClientContext context) throws Exception {
SAML2LogoutRequestBuilder builder = new SAML2LogoutRequestBuilder()
.destination(authServerSamlUrl.toString())
.issuer(issuer)
.sessionIndex(sessionIndex());
if (nameId() != null) {
builder = builder.userPrincipal(nameId().getValue(), nameId().getFormat().toString());
}
String documentAsString = DocumentUtil.getDocumentAsString(builder.buildDocument());
String transformed = getTransformer().transform(documentAsString);
if (transformed == null) {
return null;
}
return requestBinding.createSamlUnsignedRequest(authServerSamlUrl, relayState(), DocumentUtil.getDocument(transformed));
}
}
| agolPL/keycloak | testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/util/saml/CreateLogoutRequestStepBuilder.java | Java | apache-2.0 | 4,074 |
<?php $TRANSLATIONS = array(
"Contacts" => "Kontaktai",
"Save" => "Išsaugoti",
"Uploading..." => "Įkeliama...",
"Importing..." => "Importuojama...",
"Preparing..." => "Ruošiama...",
"Imported {count} of {total} contacts" => "Importuota {count} iš {total} kontaktų",
"Imported {imported} contacts. {failed} failed." => "Importuota {imported} kontaktų. {failed} nepavyko.",
"An address book called {name} already exists" => "Adresų knyga pavadinimu {group} jau egzistuoja",
"Failed adding address book: {error}" => "Nepavyko pridėti adresų knygos: {error}",
"Failed loading address books: {error}" => "Nepavyko įkelti adresų knygų: {error}",
"Indexing contacts" => "Indeksuojami kontaktai",
"Error." => "Klaida.",
"Add to..." => "Pridėti į...",
"Remove from..." => "Pašalinti iš...",
"Add group..." => "Pridėti grupę...",
"Invalid URL: \"{url}\"" => "Netinkamas URL\" „{url}“",
"There was an error opening a mail composer." => "Buvo klaida atveriant el. laiško redaktorių.",
"Invalid email: \"{url}\"" => "Netinkamas el. paštas",
"Merge failed. Cannot find contact: {id}" => "Suliejimas nepavyko. Nepavyksta rasti kontakto: {id}",
"Merge failed." => "Sulieti nepavyko.",
"Merge failed. Error saving contact." => "Suliejimas nepavyko. Klaida saugant kontaktą.",
"Select photo" => "Nurodykite nuotrauką",
"Network or server error. Please inform administrator." => "Tinklo arba serverio klaida. Prašome informuoti administratorių.",
"Error adding to group." => "Klaida pridedant į grupę.",
"Error removing from group." => "Klaida pašalinant iš grupės.",
"Error setting {name} as favorite." => "Klaida nustatant {name} mėgstamu.",
"Merge contacts" => "Sulieti kontaktus",
"Cancel" => "Atšaukti",
"Add group" => "Pridėti grupę",
"OK" => "Gerai",
"Could not find contact: {id}" => "Nepavyko rasti kontakto: {id}",
"No files selected for upload." => "Nepažymėta jokių failų įkėlimui.",
"The file you are trying to upload exceed the maximum size for file uploads on this server." => "Įkeliamo failo dydis viršijo šio serverio maksimalų leistiną dydį.",
"Edit profile picture" => "Redaguoti profilio paveikslėlį",
"Crop photo" => "Apkirpti nuotrauką",
"Is this correct?" => "Teisinga?",
"Error parsing date: {date}" => "Klaida apdorojant datą: {date}",
"# groups" => "# grupės",
"Error parsing birthday {bday}: {error}" => "Klaida nagrinėjant gimtadienį {bday}: {error}",
"Some contacts are marked for deletion, but not deleted yet. Please wait for them to be deleted." => "Keletas kontaktų buvo pažymėti ištrinimui, bet dar neištrinti. Prašome palaukti kol jie bus ištrinti.",
"Click to undo deletion of {num} contacts" => "Spauskite, kad atstatyti trynimą {num} kontaktų",
"Cancelled deletion of {num} contacts" => "Atšauktas {num} kontaktų trynimas",
"Add" => "Pridėti",
"Contact is already in this group." => "Kontaktas jau yra grupėje.",
"Contacts are already in this group." => "Kontaktai jau yra grupėje.",
"Couldn't get contact list." => "Nepavyko gauti kontaktų sąrašo.",
"Contact is not in this group." => "Kontaktas nėra šioje grupėje.",
"Contacts are not in this group." => "KontaktaI nėra šioje grupėje.",
"Failed renaming group: {error}" => "Nepavyko pervadinti grupės: {error}",
"A group named {group} already exists" => "Grupė pavadinimu {group} jau egzistuoja",
"You can drag groups to\narrange them as you like." => "Galite tempti grupes, kad\nišrikiuoti jas kaip Jums reikia.",
"Failed adding group: {error}" => "Nepavyko pridėti grupės: {error}",
"All" => "Viskas",
"Favorites" => "Mėgstamiausi",
"Shared by {owner}" => "Bendrina {owner}",
"Not grouped" => "Nesugrupuotas",
"Failed loading groups: {error}" => "Nepavyko įkelti grupių: {error}",
"Please choose the addressbook" => "Prašome pasirinkti adresų knygą",
"Import into..." => "Importuoti į...",
"Error loading import template" => "Klaida įkeliant importavimo ruošinį",
"Import contacts" => "Importuoti kontaktus",
"Import" => "Importuoti",
"Import done" => "Importas baigas",
"Close" => "Užverti",
"Error" => "Klaida",
"Displayname cannot be empty." => "Rodomas vardas negali būti tuščias.",
"Show CardDav link" => "Rodyti CardDAV nuorodą",
"Show read-only VCF link" => "Rodyti tik skaitymui VCF nuorodą",
"Download" => "Atsisiųsti",
"Edit" => "Redaguoti",
"Delete" => "Ištrinti",
"More..." => "Daugiau...",
"Less..." => "Mažiau...",
"Server error! Please inform system administator" => "Serverio klaida! Prašome informuoti administratorių",
"Failed loading photo: {error}" => "Nepavyko įkelti nuotraukos: {error}",
"You do not have permissions to see this contacts" => "Jūs neturite leidimo matyti šių kontaktų",
"Contact not found" => "Kontaktas nerastas",
"You do not have permissions to see these contacts" => "Jūs neturite leidimo matyti šiuos kontaktus",
"You do not have permissions add contacts to the address book" => "Jūs neturite leidimų pridėti kontaktų į šią adresų knygutę",
"You do not have permissions to delete this contact" => "Jūs neturite leidimų ištrinti šį kontaktą",
"Unknown error" => "Neatpažinta klaida",
"You don't have permissions to update the address book." => "Jūs neturite leidimo atnaujinti šią adresų knygutę.",
"You don't have permissions to delete the address book." => "Jūs neturite leidimo ištrinti šią adresų knygutę.",
"Address book not found" => "Adresų knygutė nerasta",
"You do not have permissions to see this contact" => "Jūs neturite leidimo matyti šį kontaktą",
"You do not have permissions to update this contact" => "Jūs neturite leidimo atnaujinti šį kontaktą",
"Property not found" => "Savybė nerasta",
"Unknown IM: " => "Nežinomas IM:",
"{name}'s Birthday" => "{name} gimtadienis",
"Error creating address book" => "Klaida kuriant adresų knygutę",
"Error updating address book" => "Klaida atnaujinant adresų knygutę",
"You do not have permissions to delete the \"%s\" address book" => "Jūs neturite leidimo ištrinti „%s“ adresų knygos",
"Error deleting address book" => "Klaida trinant adresų knygutę",
"Error creating contact." => "Klaida kuriant kontaktą.",
"Error deleting contact." => "Klaida trinant kontaktą.",
"Error retrieving contact." => "Klaida gaunant kontaktą.",
"Error saving contact." => "Klaida išsaugant kontaktą.",
"Error removing contact from other address book." => "Klaida paralinant kontaktą iš kitos adresų knygutės.",
"Couldn't find contact." => "Nepavyko rasti kontakto.",
"Property name is not set." => "Nenustatytas savybės pavadinimas.",
"Property checksum is not set." => "Nenustatyta savybės kontrolinė suma.",
"Information about vCard is incorrect. Please reload the page." => "Informacija apie vCard yra neteisinga. ",
"Error updating contact" => "Klaida atnaujinant kontaktą",
"Error getting user photo" => "Klaida gaunant naudotojo nuotrauką",
"No file was uploaded. Unknown error" => "Failai nebuvo įkelti dėl nežinomos priežasties",
"There is no error, the file uploaded with success" => "Failas įkeltas sėkmingai, be klaidų",
"The uploaded file exceeds the upload_max_filesize directive in php.ini" => "Įkeliamo failo dydis viršija upload_max_filesize nustatymą php.ini",
"The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form" => "Įkeliamo failo dydis viršija MAX_FILE_SIZE nustatymą, kuris naudojamas HTML formoje.",
"The uploaded file was only partially uploaded" => "Failas buvo įkeltas tik dalinai",
"No file was uploaded" => "Nebuvo įkeltas joks failas",
"Missing a temporary folder" => "Nėra laikinojo katalogo",
"Couldn't load temporary image: " => "Nepavyko įkelti laikiną paveikslėlį:",
"Couldn't save temporary image: " => "Nepavyko išsaugoti laikiną paveikslėlį:",
"No photo path was submitted." => "Nenurodytas nuotraukos kelias. ",
"File doesn't exist:" => "Failas neegzistuoja:",
"Error loading image." => "Klaida įkeliant nuotrauką.",
"Image has been removed from cache" => "Paveikslėlis pašalintas iš talpyklos",
"Error creating temporary image" => "Klaida kuriant laikiną paveikslėlį",
"Error cropping image" => "Klaida apkerpant paveikslėlį",
"Error resizing image" => "Klaida keičiant paveikslėlio dydį",
"Error getting PHOTO property." => "Klaida gaunant nuotraukos savybes.",
"No group name given." => "Nepateiktas grupės pavadinimas.",
"Error adding group." => "Klaida pridedant grupę.",
"Error renaming group." => "Klaida pervadinant grupę.",
"Failed to write to disk" => "Nepavyko įrašyti į diską",
"Not enough storage available" => "Nepakanka vietos serveryje",
"Attempt to upload blacklisted file:" => "Bandymas įkelti draudžiamą failą:",
"Error uploading contacts to storage." => "Klaida siunčiant kontaktus į saugyklą.",
"Error moving file to imports folder." => "Klaida perkeliant failą į importavimų aplanką.",
"You do not have permissions to import into this address book." => "Jūs neturite leidimo importuoti į šią adresų knygutę.",
"File name missing from request." => "Užklausoje trūksta failo pavadinimo.",
"Attempt to access blacklisted file:" => "bandymas pasiekti draudžiamą failą:",
"No contacts found in: " => "Kontaktų nerasta:",
"No key is given." => "Nepateiktas raktas.",
"No value is given." => "Nepateikta vertė.",
"Could not set preference: " => "Nepavyko nustatyti:",
"Contact" => "Kontaktas",
"Other" => "Kita",
"HomePage" => "Namų puslapis",
"Jabber" => "Jabber",
"Internet call" => "Internetinis skambutis",
"AIM" => "AIM",
"MSN" => "MSN",
"Twitter" => "Twitter",
"GoogleTalk" => "GoogleTalk",
"Facebook" => "Facebook",
"XMPP" => "XMPP",
"ICQ" => "ICQ",
"Yahoo" => "Yahoo",
"Skype" => "Skype",
"QQ" => "QQ",
"GaduGadu" => "GaduGadu",
"Work" => "Darbas",
"Home" => "Namų",
"Mobile" => "Mobilusis",
"Text" => "Žinučių",
"Voice" => "Balso",
"Message" => "Žinutė",
"Fax" => "Faksas",
"Video" => "Vaizdo",
"Pager" => "Pranešimų gaviklis",
"Internet" => "Internetas",
"Friends" => "Draugai",
"Family" => "Šeima",
"New Contact" => "Naujas kontaktas",
"Group name" => "Grupės pavadinimas",
"New Group" => "Nauja grupė",
"Address books" => "Adresų knygos",
"Display name" => "Rodyti vardą",
"Add Address Book" => "Pridėti adresų knygą",
"Select file..." => "Pasirinkti failą...",
"(De-)select all" => "Nuimti pažymėjimą",
"Sort order" => "Išdėstymo tvarka",
"First- Lastname" => "Vardas- Pavardė",
"Last-, Firstname" => "Pavardė-, Vardas",
"Groups" => "Grupės",
"Favorite" => "Mėgiamas",
"Merge selected" => "Suliejimas pažymėtas",
"Keyboard shortcuts" => "Klaviatūros spartieji klavišai",
"Navigation" => "Navigacija",
"Next contact in list" => "Kitas kontaktas sąraše",
"Previous contact in list" => "Ankstesnis kontaktas sąraše",
"Expand/collapse current addressbook" => "Išskleisti/sutraukti šią adresų knygutę",
"Next addressbook" => "Kita adresų knygutė",
"Previous addressbook" => "Ankstesnė adresų knygutė",
"Actions" => "Veiksmai",
"Refresh contacts list" => "Atnaujinti kontaktų sąrašą",
"Add new contact" => "Pridėti naują kontaktą",
"Add new addressbook" => "Pridėti naują adresų knygą",
"Delete current contact" => "Ištrinti šį kontaktą",
"<h3>You have no contacts in your address book or your address book is disabled.</h3><p>Add a new contact or import existing contacts from a VCF file.</p>" => "<h3>Jūs neturite kontaktų savo adresų knygoje, arba adresų knyga yra išjungta.</h3><p>Pridėkite naują kontaktą, arba importuokite turimus kontaktus iš VCF failo.</p>",
"Add contact" => "Pridėti kontaktą",
"Delete group" => "Trinti grupę",
"Rename group" => "Pervadinti grupę",
"Compose mail" => "Sukurti el. laišką",
"Delete current photo" => "Ištrinti šią nuotrauką",
"Edit current photo" => "Redaguoti šią nuotrauką",
"Upload new photo" => "Įkelti naują foto",
"Select photo from ownCloud" => "Pasirinkite nuotrauką iš ownCloud",
"Name" => "Pavadinimas",
"First name" => "Vardas",
"Additional names" => "Papildomi vardai",
"Last name" => "Pavardė",
"Select groups" => "Pasirinkti grupes",
"Select address book" => "Parinkti adresų knygą",
"Nickname" => "Slapyvardis",
"Enter nickname" => "Įveskite slapyvardį",
"Title" => "Pavadinimas",
"Enter title" => "Įveskite pavadinimą",
"Organization" => "Organizacija",
"Enter organization" => "Įveskite organizaciją",
"Birthday" => "Gimtadienis",
"Notes go here..." => "Pastabos rašomo čia...",
"Export as VCF" => "Eksportuoti kaip VCF",
"Add field..." => "Pridėti lauką...",
"Phone" => "Telefonas",
"Email" => "El. Paštas",
"Instant Messaging" => "Tikralaikiai pokalbiai",
"Address" => "Adresas",
"Note" => "Pastaba",
"Web site" => "Svetainė",
"Delete contact" => "Ištrinti kontaktą",
"Preferred" => "Pageidautinas",
"Please specify a valid email address." => "Prašome nurodyti tinkamą el. pašto adresą.",
"someone@example.com" => "kasnors@pavyzdys.lt",
"Mail to address" => "Gavėjo el. pašto adresas",
"Delete email address" => "Ištrinti el. pašto adresus",
"Enter phone number" => "Įveskite telefono numerį",
"Delete phone number" => "Ištrinti telefono numerį",
"Go to web site" => "Eiti į svetainę",
"Delete URL" => "Ištrinti URL",
"View on map" => "Žiūrėti žemėlapyje",
"Delete address" => "Pašalinti adresą",
"Street address" => "Gatvės adresas",
"Postal code" => "Pašto kodas",
"Washington, DC" => "Vašingtono apygarda",
"City" => "Miestas",
"State or province" => "Šalis ar provincija",
"USA" => "JAV",
"Country" => "Šalis",
"Instant Messenger" => "Momentinių žinučių klientas",
"Delete IM" => "Ištrinti IM",
"Active" => "Aktyvus",
"Share" => "Dalintis",
"Export" => "Eksportuoti",
"CardDAV link" => "CardDAV nuoroda",
"CardDAV syncing addresses" => "CardDAV sinchronizavimo adresai",
"more info" => "daugiau informacijos",
"Primary address (Kontact et al)" => "Pirminis adresas",
"iOS/OS X" => "iOS/OS X",
"Addressbooks" => "Adresų knygos",
"New Address Book" => "Nauja adresų knyga",
"Description" => "Aprašymas"
);
| ArcherCraftStore/ArcherVMPeridot | apps/owncloud/htdocs/apps/contacts/l10n/lt_LT.php | PHP | apache-2.0 | 14,004 |
/* Copyright 2002-2014 CS Systèmes d'Information
* Licensed to CS Systèmes d'Information (CS) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* CS 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.orekit.forces.gravity;
import org.apache.commons.math3.dfp.Dfp;
import org.apache.commons.math3.geometry.euclidean.threed.Rotation;
import org.apache.commons.math3.geometry.euclidean.threed.Vector3D;
import org.apache.commons.math3.ode.AbstractIntegrator;
import org.apache.commons.math3.ode.nonstiff.AdaptiveStepsizeIntegrator;
import org.apache.commons.math3.ode.nonstiff.ClassicalRungeKuttaIntegrator;
import org.apache.commons.math3.ode.nonstiff.DormandPrince853Integrator;
import org.apache.commons.math3.util.FastMath;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.orekit.Utils;
import org.orekit.bodies.CelestialBodyFactory;
import org.orekit.errors.OrekitException;
import org.orekit.errors.PropagationException;
import org.orekit.forces.AbstractForceModelTest;
import org.orekit.forces.ForceModel;
import org.orekit.forces.gravity.potential.GRGSFormatReader;
import org.orekit.forces.gravity.potential.GravityFieldFactory;
import org.orekit.forces.gravity.potential.ICGEMFormatReader;
import org.orekit.forces.gravity.potential.NormalizedSphericalHarmonicsProvider;
import org.orekit.forces.gravity.potential.TideSystem;
import org.orekit.frames.Frame;
import org.orekit.frames.FramesFactory;
import org.orekit.frames.Transform;
import org.orekit.orbits.CartesianOrbit;
import org.orekit.orbits.EquinoctialOrbit;
import org.orekit.orbits.KeplerianOrbit;
import org.orekit.orbits.Orbit;
import org.orekit.orbits.OrbitType;
import org.orekit.orbits.PositionAngle;
import org.orekit.propagation.BoundedPropagator;
import org.orekit.propagation.SpacecraftState;
import org.orekit.propagation.analytical.EcksteinHechlerPropagator;
import org.orekit.propagation.numerical.NumericalPropagator;
import org.orekit.propagation.sampling.OrekitFixedStepHandler;
import org.orekit.time.AbsoluteDate;
import org.orekit.time.DateComponents;
import org.orekit.time.TimeComponents;
import org.orekit.time.TimeScalesFactory;
import org.orekit.utils.Constants;
import org.orekit.utils.IERSConventions;
import org.orekit.utils.PVCoordinates;
import org.orekit.utils.PVCoordinatesProvider;
public class HolmesFeatherstoneAttractionModelTest extends AbstractForceModelTest {
@Test
public void testRelativeNumericPrecision() throws OrekitException {
// this test is similar in spirit to section 4.2 of Holmes and Featherstone paper,
// but reduced to lower degree since our reference implementation is MUCH slower
// than the one used in the paper (Clenshaw method)
int max = 50;
NormalizedSphericalHarmonicsProvider provider = new GleasonProvider(max, max);
HolmesFeatherstoneAttractionModel model =
new HolmesFeatherstoneAttractionModel(itrf, provider);
// Note that despite it uses adjustable high accuracy, the reference model
// uses unstable formulas and hence loses lots of digits near poles.
// This implies that if we still want about 16 digits near the poles, we
// need to ask for at least 30 digits in computation. Setting for example
// the following to 28 digits makes the test fail as the relative errors
// raise to about 10^-12 near North pole and near 10^-11 near South pole.
// The reason for this is that the reference becomes less accurate than
// the model we are testing!
int digits = 30;
ReferenceFieldModel refModel = new ReferenceFieldModel(provider, digits);
double r = 1.25;
for (double theta = 0.01; theta < 3.14; theta += 0.1) {
Vector3D position = new Vector3D(r * FastMath.sin(theta), 0.0, r * FastMath.cos(theta));
Dfp refValue = refModel.nonCentralPart(null, position);
double value = model.nonCentralPart(null, position);
double relativeError = error(refValue, value).divide(refValue).toDouble();
Assert.assertEquals(0, relativeError, 7.0e-15);
}
}
@Test
public void testValue() throws OrekitException {
int max = 50;
NormalizedSphericalHarmonicsProvider provider = new GleasonProvider(max, max);
HolmesFeatherstoneAttractionModel model =
new HolmesFeatherstoneAttractionModel(itrf, provider);
double r = 1.25;
for (double lambda = 0; lambda < 2 * FastMath.PI; lambda += 0.5) {
for (double theta = 0.05; theta < 3.11; theta += 0.03) {
Vector3D position = new Vector3D(r * FastMath.sin(theta) * FastMath.cos(lambda),
r * FastMath.sin(theta) * FastMath.sin(lambda),
r * FastMath.cos(theta));
double refValue = provider.getMu() / position.getNorm() +
model.nonCentralPart(AbsoluteDate.GPS_EPOCH, position);
double value = model.value(AbsoluteDate.GPS_EPOCH, position);
Assert.assertEquals(refValue, value, 1.0e-15 * FastMath.abs(refValue));
}
}
}
@Test
public void testGradient() throws OrekitException {
int max = 50;
NormalizedSphericalHarmonicsProvider provider = new GleasonProvider(max, max);
HolmesFeatherstoneAttractionModel model =
new HolmesFeatherstoneAttractionModel(itrf, provider);
double r = 1.25;
for (double lambda = 0; lambda < 2 * FastMath.PI; lambda += 0.5) {
for (double theta = 0.05; theta < 3.11; theta += 0.03) {
Vector3D position = new Vector3D(r * FastMath.sin(theta) * FastMath.cos(lambda),
r * FastMath.sin(theta) * FastMath.sin(lambda),
r * FastMath.cos(theta));
double[] refGradient = gradient(model, null, position, 1.0e-3);
double norm = FastMath.sqrt(refGradient[0] * refGradient[0] +
refGradient[1] * refGradient[1] +
refGradient[2] * refGradient[2]);
double[] gradient = model.gradient(null, position);
double errorX = refGradient[0] - gradient[0];
double errorY = refGradient[1] - gradient[1];
double errorZ = refGradient[2] - gradient[2];
double relativeError = FastMath.sqrt(errorX * errorX + errorY * errorY + errorZ * errorZ) /
norm;
Assert.assertEquals(0, relativeError, 3.0e-12);
}
}
}
@Test
public void testHessian() throws OrekitException {
int max = 50;
NormalizedSphericalHarmonicsProvider provider = new GleasonProvider(max, max);
HolmesFeatherstoneAttractionModel model =
new HolmesFeatherstoneAttractionModel(itrf, provider);
double r = 1.25;
for (double lambda = 0; lambda < 2 * FastMath.PI; lambda += 0.5) {
for (double theta = 0.05; theta < 3.11; theta += 0.03) {
Vector3D position = new Vector3D(r * FastMath.sin(theta) * FastMath.cos(lambda),
r * FastMath.sin(theta) * FastMath.sin(lambda),
r * FastMath.cos(theta));
double[][] refHessian = hessian(model, null, position, 1.0e-3);
double[][] hessian = model.gradientHessian(null, position).getHessian();
double normH2 = 0;
double normE2 = 0;
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) {
double error = refHessian[i][j] - hessian[i][j];
normH2 += refHessian[i][j] * refHessian[i][j];
normE2 += error * error;
}
}
Assert.assertEquals(0, FastMath.sqrt(normE2 / normH2), 5.0e-12);
}
}
}
private Dfp error(Dfp refValue, double value) {
return refValue.getField().newDfp(value).subtract(refValue);
}
private double[] gradient(final HolmesFeatherstoneAttractionModel model,
final AbsoluteDate date, final Vector3D position, final double h)
throws OrekitException {
return new double[] {
differential8(model.nonCentralPart(date, position.add(new Vector3D(-4 * h, Vector3D.PLUS_I))),
model.nonCentralPart(date, position.add(new Vector3D(-3 * h, Vector3D.PLUS_I))),
model.nonCentralPart(date, position.add(new Vector3D(-2 * h, Vector3D.PLUS_I))),
model.nonCentralPart(date, position.add(new Vector3D(-1 * h, Vector3D.PLUS_I))),
model.nonCentralPart(date, position.add(new Vector3D(+1 * h, Vector3D.PLUS_I))),
model.nonCentralPart(date, position.add(new Vector3D(+2 * h, Vector3D.PLUS_I))),
model.nonCentralPart(date, position.add(new Vector3D(+3 * h, Vector3D.PLUS_I))),
model.nonCentralPart(date, position.add(new Vector3D(+4 * h, Vector3D.PLUS_I))),
h),
differential8(model.nonCentralPart(date, position.add(new Vector3D(-4 * h, Vector3D.PLUS_J))),
model.nonCentralPart(date, position.add(new Vector3D(-3 * h, Vector3D.PLUS_J))),
model.nonCentralPart(date, position.add(new Vector3D(-2 * h, Vector3D.PLUS_J))),
model.nonCentralPart(date, position.add(new Vector3D(-1 * h, Vector3D.PLUS_J))),
model.nonCentralPart(date, position.add(new Vector3D(+1 * h, Vector3D.PLUS_J))),
model.nonCentralPart(date, position.add(new Vector3D(+2 * h, Vector3D.PLUS_J))),
model.nonCentralPart(date, position.add(new Vector3D(+3 * h, Vector3D.PLUS_J))),
model.nonCentralPart(date, position.add(new Vector3D(+4 * h, Vector3D.PLUS_J))),
h),
differential8(model.nonCentralPart(date, position.add(new Vector3D(-4 * h, Vector3D.PLUS_K))),
model.nonCentralPart(date, position.add(new Vector3D(-3 * h, Vector3D.PLUS_K))),
model.nonCentralPart(date, position.add(new Vector3D(-2 * h, Vector3D.PLUS_K))),
model.nonCentralPart(date, position.add(new Vector3D(-1 * h, Vector3D.PLUS_K))),
model.nonCentralPart(date, position.add(new Vector3D(+1 * h, Vector3D.PLUS_K))),
model.nonCentralPart(date, position.add(new Vector3D(+2 * h, Vector3D.PLUS_K))),
model.nonCentralPart(date, position.add(new Vector3D(+3 * h, Vector3D.PLUS_K))),
model.nonCentralPart(date, position.add(new Vector3D(+4 * h, Vector3D.PLUS_K))),
h)
};
}
private double[][] hessian(final HolmesFeatherstoneAttractionModel model,
final AbsoluteDate date, final Vector3D position, final double h)
throws OrekitException {
return new double[][] {
differential8(model.gradient(date, position.add(new Vector3D(-4 * h, Vector3D.PLUS_I))),
model.gradient(date, position.add(new Vector3D(-3 * h, Vector3D.PLUS_I))),
model.gradient(date, position.add(new Vector3D(-2 * h, Vector3D.PLUS_I))),
model.gradient(date, position.add(new Vector3D(-1 * h, Vector3D.PLUS_I))),
model.gradient(date, position.add(new Vector3D(+1 * h, Vector3D.PLUS_I))),
model.gradient(date, position.add(new Vector3D(+2 * h, Vector3D.PLUS_I))),
model.gradient(date, position.add(new Vector3D(+3 * h, Vector3D.PLUS_I))),
model.gradient(date, position.add(new Vector3D(+4 * h, Vector3D.PLUS_I))),
h),
differential8(model.gradient(date, position.add(new Vector3D(-4 * h, Vector3D.PLUS_J))),
model.gradient(date, position.add(new Vector3D(-3 * h, Vector3D.PLUS_J))),
model.gradient(date, position.add(new Vector3D(-2 * h, Vector3D.PLUS_J))),
model.gradient(date, position.add(new Vector3D(-1 * h, Vector3D.PLUS_J))),
model.gradient(date, position.add(new Vector3D(+1 * h, Vector3D.PLUS_J))),
model.gradient(date, position.add(new Vector3D(+2 * h, Vector3D.PLUS_J))),
model.gradient(date, position.add(new Vector3D(+3 * h, Vector3D.PLUS_J))),
model.gradient(date, position.add(new Vector3D(+4 * h, Vector3D.PLUS_J))),
h),
differential8(model.gradient(date, position.add(new Vector3D(-4 * h, Vector3D.PLUS_K))),
model.gradient(date, position.add(new Vector3D(-3 * h, Vector3D.PLUS_K))),
model.gradient(date, position.add(new Vector3D(-2 * h, Vector3D.PLUS_K))),
model.gradient(date, position.add(new Vector3D(-1 * h, Vector3D.PLUS_K))),
model.gradient(date, position.add(new Vector3D(+1 * h, Vector3D.PLUS_K))),
model.gradient(date, position.add(new Vector3D(+2 * h, Vector3D.PLUS_K))),
model.gradient(date, position.add(new Vector3D(+3 * h, Vector3D.PLUS_K))),
model.gradient(date, position.add(new Vector3D(+4 * h, Vector3D.PLUS_K))),
h)
};
}
/** Dummy provider for testing purposes.
* <p>
* This providers correspond to the testing regime used in the
* Holmes and Featherstone paper, who credit it to D. M. Gleason.
* </p>
*/
private static class GleasonProvider implements NormalizedSphericalHarmonicsProvider {
private final int degree;
private final int order;
public GleasonProvider(int degree, int order) {
this.degree = degree;
this.order = order;
}
public int getMaxDegree() {
return degree;
}
public int getMaxOrder() {
return order;
}
public double getMu() {
return 1;
}
public double getAe() {
return 1;
}
public AbsoluteDate getReferenceDate() {
return null;
}
public double getOffset(AbsoluteDate date) {
return 0;
}
public TideSystem getTideSystem() {
return TideSystem.UNKNOWN;
}
@Override
public NormalizedSphericalHarmonics onDate(final AbsoluteDate date) throws OrekitException {
return new NormalizedSphericalHarmonics() {
@Override
public double getNormalizedCnm(int n, int m) throws OrekitException {
return 1;
}
@Override
public double getNormalizedSnm(int n, int m) throws OrekitException {
return 1;
}
@Override
public AbsoluteDate getDate() {
return date;
}
};
}
}
// rough test to determine if J2 alone creates heliosynchronism
@Test
public void testHelioSynchronous()
throws OrekitException {
// initialization
AbsoluteDate date = new AbsoluteDate(new DateComponents(1970, 07, 01),
new TimeComponents(13, 59, 27.816),
TimeScalesFactory.getUTC());
Transform itrfToEME2000 = itrf.getTransformTo(FramesFactory.getEME2000(), date);
Vector3D pole = itrfToEME2000.transformVector(Vector3D.PLUS_K);
Frame poleAligned = new Frame(FramesFactory.getEME2000(),
new Transform(date, new Rotation(pole, Vector3D.PLUS_K)),
"pole aligned", true);
double i = FastMath.toRadians(98.7);
double omega = FastMath.toRadians(93.0);
double OMEGA = FastMath.toRadians(15.0 * 22.5);
Orbit orbit = new KeplerianOrbit(7201009.7124401, 1e-3, i , omega, OMEGA,
0, PositionAngle.MEAN, poleAligned, date, mu);
double[][] c = new double[3][1];
c[0][0] = 0.0;
c[2][0] = normalizedC20;
double[][] s = new double[3][1];
propagator.addForceModel(new HolmesFeatherstoneAttractionModel(itrf,
GravityFieldFactory.getNormalizedProvider(6378136.460, mu,
TideSystem.UNKNOWN,
c, s)));
// let the step handler perform the test
propagator.setMasterMode(Constants.JULIAN_DAY, new SpotStepHandler(date, mu));
propagator.setInitialState(new SpacecraftState(orbit));
propagator.propagate(date.shiftedBy(7 * Constants.JULIAN_DAY));
Assert.assertTrue(propagator.getCalls() < 9200);
}
private static class SpotStepHandler implements OrekitFixedStepHandler {
public SpotStepHandler(AbsoluteDate date, double mu) throws OrekitException {
sun = CelestialBodyFactory.getSun();
previous = Double.NaN;
}
private PVCoordinatesProvider sun;
private double previous;
public void init(SpacecraftState s0, AbsoluteDate t) {
}
public void handleStep(SpacecraftState currentState, boolean isLast)
throws PropagationException {
AbsoluteDate current = currentState.getDate();
Vector3D sunPos;
try {
sunPos = sun.getPVCoordinates(current , FramesFactory.getEME2000()).getPosition();
} catch (OrekitException e) {
throw new PropagationException(e);
}
Vector3D normal = currentState.getPVCoordinates().getMomentum();
double angle = Vector3D.angle(sunPos , normal);
if (! Double.isNaN(previous)) {
Assert.assertEquals(previous, angle, 0.0013);
}
previous = angle;
}
}
// test the difference with the analytical extrapolator Eckstein Hechler
@Test
public void testEcksteinHechlerReference()
throws OrekitException {
// Definition of initial conditions with position and velocity
AbsoluteDate date = AbsoluteDate.J2000_EPOCH.shiftedBy(584.);
Vector3D position = new Vector3D(3220103., 69623., 6449822.);
Vector3D velocity = new Vector3D(6414.7, -2006., -3180.);
Transform itrfToEME2000 = itrf.getTransformTo(FramesFactory.getEME2000(), date);
Vector3D pole = itrfToEME2000.transformVector(Vector3D.PLUS_K);
Frame poleAligned = new Frame(FramesFactory.getEME2000(),
new Transform(date, new Rotation(pole, Vector3D.PLUS_K)),
"pole aligned", true);
Orbit initialOrbit = new EquinoctialOrbit(new PVCoordinates(position, velocity),
poleAligned, date, mu);
propagator.addForceModel(new HolmesFeatherstoneAttractionModel(itrf,
GravityFieldFactory.getNormalizedProvider(ae, mu,
TideSystem.UNKNOWN,
new double[][] {
{ 0.0 }, { 0.0 }, { normalizedC20 }, { normalizedC30 },
{ normalizedC40 }, { normalizedC50 }, { normalizedC60 },
},
new double[][] {
{ 0.0 }, { 0.0 }, { 0.0 }, { 0.0 },
{ 0.0 }, { 0.0 }, { 0.0 },
})));
// let the step handler perform the test
propagator.setInitialState(new SpacecraftState(initialOrbit));
propagator.setMasterMode(20, new EckStepHandler(initialOrbit, ae,
unnormalizedC20, unnormalizedC30, unnormalizedC40,
unnormalizedC50, unnormalizedC60));
propagator.propagate(date.shiftedBy(50000));
Assert.assertTrue(propagator.getCalls() < 1100);
}
private static class EckStepHandler implements OrekitFixedStepHandler {
/** Body mu */
private static final double mu = 3.986004415e+14;
private EckStepHandler(Orbit initialOrbit, double ae,
double c20, double c30, double c40, double c50, double c60)
throws OrekitException {
referencePropagator =
new EcksteinHechlerPropagator(initialOrbit,
ae, mu, c20, c30, c40, c50, c60);
}
private EcksteinHechlerPropagator referencePropagator;
public void init(SpacecraftState s0, AbsoluteDate t) {
}
public void handleStep(SpacecraftState currentState, boolean isLast) {
try {
SpacecraftState EHPOrbit = referencePropagator.propagate(currentState.getDate());
Vector3D posEHP = EHPOrbit.getPVCoordinates().getPosition();
Vector3D posDROZ = currentState.getPVCoordinates().getPosition();
Vector3D velEHP = EHPOrbit.getPVCoordinates().getVelocity();
Vector3D dif = posEHP.subtract(posDROZ);
Vector3D T = new Vector3D(1 / velEHP.getNorm(), velEHP);
Vector3D W = EHPOrbit.getPVCoordinates().getMomentum().normalize();
Vector3D N = Vector3D.crossProduct(W, T);
Assert.assertTrue(dif.getNorm() < 111);
Assert.assertTrue(FastMath.abs(Vector3D.dotProduct(dif, T)) < 111);
Assert.assertTrue(FastMath.abs(Vector3D.dotProduct(dif, N)) < 54);
Assert.assertTrue(FastMath.abs(Vector3D.dotProduct(dif, W)) < 12);
} catch (PropagationException e) {
e.printStackTrace();
}
}
}
// test the difference with the Cunningham model
@Test
public void testZonalWithCunninghamReference()
throws OrekitException {
// initialization
AbsoluteDate date = new AbsoluteDate(new DateComponents(2000, 07, 01),
new TimeComponents(13, 59, 27.816),
TimeScalesFactory.getUTC());
double i = FastMath.toRadians(98.7);
double omega = FastMath.toRadians(93.0);
double OMEGA = FastMath.toRadians(15.0 * 22.5);
Orbit orbit = new KeplerianOrbit(7201009.7124401, 1e-3, i , omega, OMEGA,
0, PositionAngle.MEAN, FramesFactory.getEME2000(), date, mu);
propagator = new NumericalPropagator(new ClassicalRungeKuttaIntegrator(1000));
propagator.addForceModel(new HolmesFeatherstoneAttractionModel(itrf,
GravityFieldFactory.getNormalizedProvider(ae, mu,
TideSystem.UNKNOWN,
new double[][] {
{ 0.0 }, { 0.0 }, { normalizedC20 }, { normalizedC30 },
{ normalizedC40 }, { normalizedC50 }, { normalizedC60 },
},
new double[][] {
{ 0.0 }, { 0.0 }, { 0.0 }, { 0.0 },
{ 0.0 }, { 0.0 }, { 0.0 },
})));
propagator.setInitialState(new SpacecraftState(orbit));
SpacecraftState hfOrb = propagator.propagate(date.shiftedBy(Constants.JULIAN_DAY));
propagator.removeForceModels();
propagator.addForceModel(new CunninghamAttractionModel(itrf,
GravityFieldFactory.getUnnormalizedProvider(ae, mu,
TideSystem.UNKNOWN,
new double[][] {
{ 0.0 }, { 0.0 }, { unnormalizedC20 }, { unnormalizedC30 },
{ unnormalizedC40 }, { unnormalizedC50 }, { unnormalizedC60 },
},
new double[][] {
{ 0.0 }, { 0.0 }, { 0.0 }, { 0.0 },
{ 0.0 }, { 0.0 }, { 0.0 },
})));
propagator.setInitialState(new SpacecraftState(orbit));
SpacecraftState cOrb = propagator.propagate(date.shiftedBy(Constants.JULIAN_DAY));
Vector3D dif = hfOrb.getPVCoordinates().getPosition().subtract(cOrb.getPVCoordinates().getPosition());
Assert.assertEquals(0, dif.getNorm(), 2e-9);
Assert.assertTrue(propagator.getCalls() < 400);
}
@Test
public void testCompleteWithCunninghamReference()
throws OrekitException {
Utils.setDataRoot("regular-data:potential/grgs-format");
GravityFieldFactory.addPotentialCoefficientsReader(new GRGSFormatReader("grim4s4_gr", true));
// initialization
AbsoluteDate date = new AbsoluteDate(new DateComponents(2000, 07, 01),
new TimeComponents(13, 59, 27.816),
TimeScalesFactory.getUTC());
double i = FastMath.toRadians(98.7);
double omega = FastMath.toRadians(93.0);
double OMEGA = FastMath.toRadians(15.0 * 22.5);
Orbit orbit = new KeplerianOrbit(7201009.7124401, 1e-3, i , omega, OMEGA,
0, PositionAngle.MEAN, FramesFactory.getEME2000(), date, mu);
double[][] tolerances = NumericalPropagator.tolerances(0.01, orbit, OrbitType.CARTESIAN);
AbsoluteDate targetDate = date.shiftedBy(3 * Constants.JULIAN_DAY);
propagator = new NumericalPropagator(new DormandPrince853Integrator(1.0e-3, 120,
tolerances[0], tolerances[1]));
propagator.setOrbitType(OrbitType.CARTESIAN);
propagator.addForceModel(new HolmesFeatherstoneAttractionModel(itrf,
GravityFieldFactory.getNormalizedProvider(69, 69)));
propagator.setInitialState(new SpacecraftState(orbit));
SpacecraftState hfOrb = propagator.propagate(targetDate);
propagator.removeForceModels();
propagator.addForceModel(new CunninghamAttractionModel(itrf,
GravityFieldFactory.getUnnormalizedProvider(69, 69)));
propagator.setInitialState(new SpacecraftState(orbit));
SpacecraftState cOrb = propagator.propagate(targetDate);
Vector3D dif = hfOrb.getPVCoordinates().getPosition().subtract(cOrb.getPVCoordinates().getPosition());
Assert.assertEquals(0, dif.getNorm(), 4e-5);
}
@Test
public void testIssue97() throws OrekitException {
Utils.setDataRoot("regular-data:potential/grgs-format");
GravityFieldFactory.addPotentialCoefficientsReader(new GRGSFormatReader("grim4s4_gr", true));
// pos-vel (from a ZOOM ephemeris reference)
final Vector3D pos = new Vector3D(6.46885878304673824e+06, -1.88050918456274318e+06, -1.32931592294715829e+04);
final Vector3D vel = new Vector3D(2.14718074509906819e+03, 7.38239351251748485e+03, -1.14097953925384523e+01);
final SpacecraftState state =
new SpacecraftState(new CartesianOrbit(new PVCoordinates(pos, vel),
FramesFactory.getGCRF(),
new AbsoluteDate(2005, 3, 5, 0, 24, 0.0, TimeScalesFactory.getTAI()),
GravityFieldFactory.getUnnormalizedProvider(1, 1).getMu()));
for (int i = 2; i <= 69; i++) {
final ForceModel holmesFeatherstoneModel =
new HolmesFeatherstoneAttractionModel(FramesFactory.getITRF(IERSConventions.IERS_2010, true),
GravityFieldFactory.getNormalizedProvider(i, i));
final ForceModel cunninghamModel =
new CunninghamAttractionModel(FramesFactory.getITRF(IERSConventions.IERS_2010, true),
GravityFieldFactory.getUnnormalizedProvider(i, i));
double relativeError = accelerationRelativeError(holmesFeatherstoneModel, cunninghamModel, state);
Assert.assertEquals(0.0, relativeError, 8.0e-15);
}
}
@Test
public void testParameterDerivative() throws OrekitException {
Utils.setDataRoot("regular-data:potential/grgs-format");
GravityFieldFactory.addPotentialCoefficientsReader(new GRGSFormatReader("grim4s4_gr", true));
// pos-vel (from a ZOOM ephemeris reference)
final Vector3D pos = new Vector3D(6.46885878304673824e+06, -1.88050918456274318e+06, -1.32931592294715829e+04);
final Vector3D vel = new Vector3D(2.14718074509906819e+03, 7.38239351251748485e+03, -1.14097953925384523e+01);
final SpacecraftState state =
new SpacecraftState(new CartesianOrbit(new PVCoordinates(pos, vel),
FramesFactory.getGCRF(),
new AbsoluteDate(2005, 3, 5, 0, 24, 0.0, TimeScalesFactory.getTAI()),
GravityFieldFactory.getUnnormalizedProvider(1, 1).getMu()));
final HolmesFeatherstoneAttractionModel holmesFeatherstoneModel =
new HolmesFeatherstoneAttractionModel(FramesFactory.getITRF(IERSConventions.IERS_2010, true),
GravityFieldFactory.getNormalizedProvider(20, 20));
final String name = NewtonianAttraction.CENTRAL_ATTRACTION_COEFFICIENT;
checkParameterDerivative(state, holmesFeatherstoneModel, name, 1.0e-5, 5.0e-12);
}
private double accelerationRelativeError(ForceModel testModel, ForceModel referenceModel,
SpacecraftState state)
throws OrekitException {
AccelerationRetriever accelerationRetriever = new AccelerationRetriever();
testModel.addContribution(state, accelerationRetriever);
final Vector3D testAcceleration = accelerationRetriever.getAcceleration();
referenceModel.addContribution(state, accelerationRetriever);
final Vector3D referenceAcceleration = accelerationRetriever.getAcceleration();
return testAcceleration.subtract(referenceAcceleration).getNorm() /
referenceAcceleration.getNorm();
}
@Test
public void testTimeDependentField() throws OrekitException {
Utils.setDataRoot("regular-data:potential/icgem-format");
GravityFieldFactory.addPotentialCoefficientsReader(new ICGEMFormatReader("eigen-6s-truncated", true));
final Vector3D pos = new Vector3D(6.46885878304673824e+06, -1.88050918456274318e+06, -1.32931592294715829e+04);
final Vector3D vel = new Vector3D(2.14718074509906819e+03, 7.38239351251748485e+03, -1.14097953925384523e+01);
final SpacecraftState spacecraftState =
new SpacecraftState(new CartesianOrbit(new PVCoordinates(pos, vel),
FramesFactory.getGCRF(),
new AbsoluteDate(2005, 3, 5, 0, 24, 0.0, TimeScalesFactory.getTAI()),
GravityFieldFactory.getUnnormalizedProvider(1, 1).getMu()));
double dP = 0.1;
double duration = 3 * Constants.JULIAN_DAY;
BoundedPropagator fixedFieldEphemeris = createEphemeris(dP, spacecraftState, duration,
GravityFieldFactory.getConstantNormalizedProvider(8, 8));
BoundedPropagator varyingFieldEphemeris = createEphemeris(dP, spacecraftState, duration,
GravityFieldFactory.getNormalizedProvider(8, 8));
double step = 60.0;
double maxDeltaT = 0;
double maxDeltaN = 0;
double maxDeltaW = 0;
for (AbsoluteDate date = fixedFieldEphemeris.getMinDate();
date.compareTo(fixedFieldEphemeris.getMaxDate()) < 0;
date = date.shiftedBy(step)) {
PVCoordinates pvFixedField = fixedFieldEphemeris.getPVCoordinates(date, FramesFactory.getGCRF());
PVCoordinates pvVaryingField = varyingFieldEphemeris.getPVCoordinates(date, FramesFactory.getGCRF());
Vector3D t = pvFixedField.getVelocity().normalize();
Vector3D w = pvFixedField.getMomentum().normalize();
Vector3D n = Vector3D.crossProduct(w, t);
Vector3D delta = pvVaryingField.getPosition().subtract(pvFixedField.getPosition());
maxDeltaT = FastMath.max(maxDeltaT, FastMath.abs(Vector3D.dotProduct(delta, t)));
maxDeltaN = FastMath.max(maxDeltaN, FastMath.abs(Vector3D.dotProduct(delta, n)));
maxDeltaW = FastMath.max(maxDeltaW, FastMath.abs(Vector3D.dotProduct(delta, w)));
}
Assert.assertTrue(maxDeltaT > 0.15);
Assert.assertTrue(maxDeltaT < 0.25);
Assert.assertTrue(maxDeltaN > 0.01);
Assert.assertTrue(maxDeltaN < 0.02);
Assert.assertTrue(maxDeltaW > 0.05);
Assert.assertTrue(maxDeltaW < 0.10);
}
private BoundedPropagator createEphemeris(double dP, SpacecraftState initialState, double duration,
NormalizedSphericalHarmonicsProvider provider)
throws OrekitException {
double[][] tol = NumericalPropagator.tolerances(dP, initialState.getOrbit(), OrbitType.CARTESIAN);
AbstractIntegrator integrator =
new DormandPrince853Integrator(0.001, 120.0, tol[0], tol[1]);
NumericalPropagator propagator = new NumericalPropagator(integrator);
propagator.setEphemerisMode();
propagator.setOrbitType(OrbitType.CARTESIAN);
propagator.addForceModel(new HolmesFeatherstoneAttractionModel(FramesFactory.getITRF(IERSConventions.IERS_2010, true), provider));
propagator.setInitialState(initialState);
propagator.propagate(initialState.getDate().shiftedBy(duration));
return propagator.getGeneratedEphemeris();
}
@Test
public void testStateJacobian()
throws OrekitException {
Utils.setDataRoot("regular-data:potential/grgs-format");
GravityFieldFactory.addPotentialCoefficientsReader(new GRGSFormatReader("grim4s4_gr", true));
// initialization
AbsoluteDate date = new AbsoluteDate(new DateComponents(2000, 07, 01),
new TimeComponents(13, 59, 27.816),
TimeScalesFactory.getUTC());
double i = FastMath.toRadians(98.7);
double omega = FastMath.toRadians(93.0);
double OMEGA = FastMath.toRadians(15.0 * 22.5);
Orbit orbit = new KeplerianOrbit(7201009.7124401, 1e-3, i , omega, OMEGA,
0, PositionAngle.MEAN, FramesFactory.getEME2000(), date, mu);
OrbitType integrationType = OrbitType.CARTESIAN;
double[][] tolerances = NumericalPropagator.tolerances(0.01, orbit, integrationType);
propagator = new NumericalPropagator(new DormandPrince853Integrator(1.0e-3, 120,
tolerances[0], tolerances[1]));
propagator.setOrbitType(integrationType);
HolmesFeatherstoneAttractionModel hfModel =
new HolmesFeatherstoneAttractionModel(itrf, GravityFieldFactory.getNormalizedProvider(50, 50));
Assert.assertEquals(TideSystem.UNKNOWN, hfModel.getTideSystem());
propagator.addForceModel(hfModel);
SpacecraftState state0 = new SpacecraftState(orbit);
propagator.setInitialState(state0);
checkStateJacobian(propagator, state0, date.shiftedBy(3.5 * 3600.0),
50000, tolerances[0], 7.0e-10);
}
@Before
public void setUp() {
itrf = null;
propagator = null;
Utils.setDataRoot("regular-data");
try {
// Eigen 6s model truncated to degree 6
mu = 3.986004415e+14;
ae = 6378136.460;
normalizedC20 = -4.84165299820e-04;
normalizedC30 = 9.57211326674e-07;
normalizedC40 = 5.39990167207e-07;
normalizedC50 = 6.86846073356e-08 ;
normalizedC60 = -1.49953256913e-07;
unnormalizedC20 = FastMath.sqrt( 5) * normalizedC20;
unnormalizedC30 = FastMath.sqrt( 7) * normalizedC30;
unnormalizedC40 = FastMath.sqrt( 9) * normalizedC40;
unnormalizedC50 = FastMath.sqrt(11) * normalizedC50;
unnormalizedC60 = FastMath.sqrt(13) * normalizedC60;
itrf = FramesFactory.getITRF(IERSConventions.IERS_2010, true);
double[] absTolerance = {
0.001, 1.0e-9, 1.0e-9, 1.0e-6, 1.0e-6, 1.0e-6, 0.001
};
double[] relTolerance = {
1.0e-7, 1.0e-4, 1.0e-4, 1.0e-7, 1.0e-7, 1.0e-7, 1.0e-7
};
AdaptiveStepsizeIntegrator integrator =
new DormandPrince853Integrator(0.001, 1000, absTolerance, relTolerance);
integrator.setInitialStepSize(60);
propagator = new NumericalPropagator(integrator);
} catch (OrekitException oe) {
Assert.fail(oe.getMessage());
}
}
@After
public void tearDown() {
itrf = null;
propagator = null;
}
private double unnormalizedC20;
private double unnormalizedC30;
private double unnormalizedC40;
private double unnormalizedC50;
private double unnormalizedC60;
private double normalizedC20;
private double normalizedC30;
private double normalizedC40;
private double normalizedC50;
private double normalizedC60;
private double mu;
private double ae;
private Frame itrf;
private NumericalPropagator propagator;
}
| wardev/orekit | src/test/java/org/orekit/forces/gravity/HolmesFeatherstoneAttractionModelTest.java | Java | apache-2.0 | 40,238 |
// Copyright 2013, 2014 MongoDB, 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 rolling_file_appender provides a slogger Appender that
// supports log rotation.
package rolling_file_appender
import (
"fmt"
"github.com/tolsen/slogger/v2/slogger"
"os"
"path/filepath"
"regexp"
"sort"
"strconv"
"sync"
"time"
)
type RollingFileAppender struct {
MaxFileSize int64
MaxRotatedLogs int
file *os.File
absPath string
curFileSize int64
headerGenerator func() []string
stringWriterCallback func(*os.File) slogger.StringWriter
lock sync.Mutex
}
// New creates a new RollingFileAppender. filename is path to the
// file to log to. It can be a relative path (with respect to the
// current working directory) or an absolute path. maxFileSize is the
// approximate file size that will be allowed before the log file is
// rotated. Rotated log files will have suffix of the form
// .YYYY-MM-DDTHH-MM-SS or .YYYY-MM-DDTHH-MM-SS-N (where N is an
// incrementing serial number used to resolve conflicts) appended to
// them. Set maxFileSize to a non-positive number if you wish there
// to be no limit. maxRotatedLogs specifies the maximum number of
// rotated logs allowed before old logs are deleted. If
// rotateIfExists is set to true and a log file with the same filename
// already exists, then the current one will be rotated. If
// rotateIfExists is set to false and a log file with the same
// filename already exists, then the current log file will be appended
// to. If a log file with the same filename does not exist, then a
// new log file is created regardless of the value of rotateIfExists.
// As RotatingFileAppender might be wrapped by an AsyncAppender, an
// errHandler can be provided that will be called when an error
// occurs. It can set to nil if you do not want to provide one. The
// return value headerGenerator, if not nil, is logged at the
// beginning of every log file.
//
// Note that after creating a RollingFileAppender with New(), you will
// probably want to defer a call to RollingFileAppender's Close() (or
// at least Flush()). This ensures that in case of program exit
// (normal or panicking) that any pending logs are logged.
func New(filename string, maxFileSize int64, maxRotatedLogs int, rotateIfExists bool, headerGenerator func() []string) (*RollingFileAppender, error) {
return NewWithStringWriter(filename, maxFileSize, maxRotatedLogs, rotateIfExists, headerGenerator, nil)
}
func NewWithStringWriter(filename string, maxFileSize int64, maxRotatedLogs int, rotateIfExists bool, headerGenerator func() []string, stringWriterCallback func(*os.File) slogger.StringWriter) (*RollingFileAppender, error) {
if headerGenerator == nil {
headerGenerator = func() []string {
return []string{}
}
}
if stringWriterCallback == nil {
stringWriterCallback = func(f *os.File) slogger.StringWriter {
return f
}
}
absPath, err := filepath.Abs(filename)
if err != nil {
return nil, err
}
appender := &RollingFileAppender{
MaxFileSize: maxFileSize,
MaxRotatedLogs: maxRotatedLogs,
absPath: absPath,
headerGenerator: headerGenerator,
stringWriterCallback: stringWriterCallback,
}
fileInfo, err := os.Stat(absPath)
if err == nil && rotateIfExists { // err == nil means file exists
return appender, appender.rotate()
} else {
// we're either creating a new log file or appending to the current one
appender.file, err = os.OpenFile(
absPath,
os.O_WRONLY|os.O_APPEND|os.O_CREATE,
0666,
)
if err != nil {
return nil, err
}
if fileInfo != nil {
appender.curFileSize = fileInfo.Size()
}
return appender, appender.logHeader()
}
}
func (self *RollingFileAppender) Append(log *slogger.Log) error {
self.lock.Lock()
defer self.lock.Unlock()
n, err := self.appendSansSizeTracking(log)
self.curFileSize += int64(n)
if err != nil {
return err
}
if self.MaxFileSize > 0 && self.curFileSize > self.MaxFileSize {
return self.rotate()
}
return nil
}
func (self *RollingFileAppender) Close() error {
err := self.Flush()
if err != nil {
return err
}
return self.file.Close()
}
func (self *RollingFileAppender) Flush() error {
return self.file.Sync()
}
func rotatedFilename(baseFilename string, t time.Time, serial int) string {
filename := fmt.Sprintf(
"%s.%d-%02d-%02dT%02d-%02d-%02d",
baseFilename,
t.Year(),
t.Month(),
t.Day(),
t.Hour(),
t.Minute(),
t.Second(),
)
if serial > 0 {
filename = fmt.Sprintf("%s-%d", filename, serial)
}
return filename
}
func (self *RollingFileAppender) appendSansSizeTracking(log *slogger.Log) (bytesWritten int, err error) {
if self.file == nil {
return 0, NoFileError{}
}
msg := slogger.FormatLog(log)
bytesWritten, err = self.stringWriterCallback(self.file).WriteString(msg)
if err != nil {
err = WriteError{self.absPath, err}
}
return
}
func (self *RollingFileAppender) logHeader() error {
header := self.headerGenerator()
for _, line := range header {
log := &slogger.Log{
Prefix: "header",
Level: slogger.INFO,
Filename: "",
Line: 0,
Timestamp: time.Now(),
MessageFmt: line,
Args: []interface{}{},
}
// do not count header as part of size towards rotation in
// order to prevent infinite rotation when max size is smaller
// than header
_, err := self.appendSansSizeTracking(log)
if err != nil {
return err
}
}
return nil
}
func (self *RollingFileAppender) removeMaxRotatedLogs() error {
rotationTimes, err := self.rotationTimeSlice()
if err != nil {
return MinorRotationError{err}
}
numLogsToDelete := len(rotationTimes) - self.MaxRotatedLogs
// return if we're under the limit
if numLogsToDelete <= 0 {
return nil
}
// otherwise remove enough of the oldest logfiles to bring us
// under the limit
sort.Sort(rotationTimes)
for _, rotationTime := range rotationTimes[:numLogsToDelete] {
if err = os.Remove(rotationTime.Filename); err != nil {
return MinorRotationError{err}
}
}
return nil
}
const MAX_ROTATE_SERIAL_NUM = 1000000000
func (self *RollingFileAppender) renameLogFile(oldFilename string) error {
now := time.Now()
var newFilename string
var err error
for serial := 0; err == nil; serial++ { // err == nil means file exists
if serial > MAX_ROTATE_SERIAL_NUM {
return RenameError{
oldFilename,
newFilename,
fmt.Errorf("Reached max serial number: %d", MAX_ROTATE_SERIAL_NUM),
}
}
newFilename = rotatedFilename(self.absPath, now, serial)
_, err = os.Stat(newFilename)
}
err = os.Rename(oldFilename, newFilename)
if err != nil {
return RenameError{oldFilename, newFilename, err}
}
return nil
}
func (self *RollingFileAppender) rotate() error {
// close current log if we have one open
if self.file != nil {
if err := self.file.Close(); err != nil {
return CloseError{self.absPath, err}
}
}
self.curFileSize = 0
// rename old log
if err := self.renameLogFile(self.absPath); err != nil {
return err
}
// create new log
file, err := os.Create(self.absPath)
if err != nil {
self.file = nil
return OpenError{self.absPath, err}
}
self.file = file
self.logHeader()
// remove really old logs
self.removeMaxRotatedLogs()
return nil
}
func (self *RollingFileAppender) rotationTimeSlice() (RotationTimeSlice, error) {
candidateFilenames, err := filepath.Glob(self.absPath + ".*")
if err != nil {
return nil, err
}
rotationTimes := make(RotationTimeSlice, 0, len(candidateFilenames))
for _, candidateFilename := range candidateFilenames {
rotationTime, err := extractRotationTimeFromFilename(candidateFilename)
if err == nil {
rotationTimes = append(rotationTimes, rotationTime)
}
}
return rotationTimes, nil
}
type CloseError struct {
Filename string
Err error
}
func (self CloseError) Error() string {
return fmt.Sprintf(
"rolling_file_appender: Failed to close %s: %s",
self.Filename,
self.Err.Error(),
)
}
func IsCloseError(err error) bool {
_, ok := err.(CloseError)
return ok
}
type MinorRotationError struct {
Err error
}
func (self MinorRotationError) Error() string {
return ("rolling_file_appender: minor error while rotating logs: " + self.Err.Error())
}
func IsMinorRotationError(err error) bool {
_, ok := err.(MinorRotationError)
return ok
}
type NoFileError struct{}
func (NoFileError) Error() string {
return "rolling_file_appender: No log file to write to"
}
func IsNoFileError(err error) bool {
_, ok := err.(NoFileError)
return ok
}
type OpenError struct {
Filename string
Err error
}
func (self OpenError) Error() string {
return fmt.Sprintf(
"rolling_file_appender: Failed to open %s: %s",
self.Filename,
self.Err.Error(),
)
}
func IsOpenError(err error) bool {
_, ok := err.(OpenError)
return ok
}
type RenameError struct {
OldFilename string
NewFilename string
Err error
}
func (self RenameError) Error() string {
return fmt.Sprintf(
"rolling_file_appender: Failed to rename %s to %s: %s",
self.OldFilename,
self.NewFilename,
self.Err.Error(),
)
}
func IsRenameError(err error) bool {
_, ok := err.(RenameError)
return ok
}
type WriteError struct {
Filename string
Err error
}
func (self WriteError) Error() string {
return fmt.Sprintf(
"rolling_file_appender: Failed to write to %s: %s",
self.Filename,
self.Err.Error(),
)
}
func IsWriteError(err error) bool {
_, ok := err.(WriteError)
return ok
}
type RotationTime struct {
Time time.Time
Serial int
Filename string
}
type RotationTimeSlice [](*RotationTime)
func (self RotationTimeSlice) Len() int {
return len(self)
}
func (self RotationTimeSlice) Less(i, j int) bool {
if self[i].Time == self[j].Time {
return self[i].Serial < self[j].Serial
}
return self[i].Time.Before(self[j].Time)
}
func (self RotationTimeSlice) Swap(i, j int) {
self[i], self[j] = self[j], self[i]
}
var rotatedTimeRegExp = regexp.MustCompile(`\.(\d+-\d\d-\d\dT\d\d-\d\d-\d\d)(-(\d+))?$`)
func extractRotationTimeFromFilename(filename string) (*RotationTime, error) {
match := rotatedTimeRegExp.FindStringSubmatch(filename)
if match == nil {
return nil, fmt.Errorf("Filename does not match rotation time format: %s", filename)
}
rotatedTime, err := time.Parse("2006-01-02T15-04-05", match[1])
if err != nil {
return nil, fmt.Errorf(
"Time %s in filename %s did not parse: %v",
match[1],
filename,
err,
)
}
serial := 0
if match[3] != "" {
serial, err = strconv.Atoi(match[3])
if err != nil {
return nil, fmt.Errorf(
"Could not parse serial number in filename %s: %v",
filename,
err,
)
}
}
return &RotationTime{rotatedTime, serial, filename}, nil
}
| tolsen/slogger | v2/slogger/rolling_file_appender/rolling_file_appender.go | GO | apache-2.0 | 11,316 |
/*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.ide.impl.dataRules;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.actionSystem.DataProvider;
import com.intellij.openapi.actionSystem.LangDataKeys;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ModuleRootManager;
import com.intellij.openapi.roots.ProjectRootManager;
import consulo.util.dataholder.Key;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiDirectory;
import com.intellij.psi.PsiDirectoryContainer;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.usages.Usage;
import com.intellij.usages.UsageDataUtil;
import com.intellij.usages.UsageTarget;
import com.intellij.usages.UsageView;
import com.intellij.util.containers.ContainerUtil;
import javax.annotation.Nonnull;
import java.util.ArrayList;
import java.util.HashSet;
public class VirtualFileArrayRule implements GetDataRule<VirtualFile[]> {
@Nonnull
@Override
public Key<VirtualFile[]> getKey() {
return CommonDataKeys.VIRTUAL_FILE_ARRAY;
}
@Override
public VirtualFile[] getData(@Nonnull final DataProvider dataProvider) {
// Try to detect multiselection.
Project project = dataProvider.getDataUnchecked(PlatformDataKeys.PROJECT_CONTEXT);
if (project != null && !project.isDisposed()) {
return ProjectRootManager.getInstance(project).getContentRoots();
}
Module[] selectedModules = dataProvider.getDataUnchecked(LangDataKeys.MODULE_CONTEXT_ARRAY);
if (selectedModules != null && selectedModules.length > 0) {
return getFilesFromModules(selectedModules);
}
Module selectedModule = dataProvider.getDataUnchecked(LangDataKeys.MODULE_CONTEXT);
if (selectedModule != null && !selectedModule.isDisposed()) {
return ModuleRootManager.getInstance(selectedModule).getContentRoots();
}
PsiElement[] psiElements = dataProvider.getDataUnchecked(LangDataKeys.PSI_ELEMENT_ARRAY);
if (psiElements != null && psiElements.length != 0) {
return getFilesFromPsiElements(psiElements);
}
// VirtualFile -> VirtualFile[]
VirtualFile vFile = dataProvider.getDataUnchecked(PlatformDataKeys.VIRTUAL_FILE);
if (vFile != null) {
return new VirtualFile[]{vFile};
}
//
PsiFile psiFile = dataProvider.getDataUnchecked(LangDataKeys.PSI_FILE);
if (psiFile != null && psiFile.getVirtualFile() != null) {
return new VirtualFile[]{psiFile.getVirtualFile()};
}
PsiElement elem = dataProvider.getDataUnchecked(LangDataKeys.PSI_ELEMENT);
if (elem != null) {
return getFilesFromPsiElement(elem);
}
Usage[] usages = dataProvider.getDataUnchecked(UsageView.USAGES_KEY);
UsageTarget[] usageTargets = dataProvider.getDataUnchecked(UsageView.USAGE_TARGETS_KEY);
if (usages != null || usageTargets != null) {
return UsageDataUtil.provideVirtualFileArray(usages, usageTargets);
}
return null;
}
private static VirtualFile[] getFilesFromPsiElement(PsiElement elem) {
if (elem instanceof PsiFile) {
VirtualFile virtualFile = ((PsiFile)elem).getVirtualFile();
return virtualFile != null ? new VirtualFile[]{virtualFile} : null;
}
else if (elem instanceof PsiDirectory) {
return new VirtualFile[]{((PsiDirectory)elem).getVirtualFile()};
}
else {
PsiFile file = elem.getContainingFile();
return file != null && file.getVirtualFile() != null ? new VirtualFile[]{file.getVirtualFile()} : null;
}
}
private static VirtualFile[] getFilesFromPsiElements(PsiElement[] psiElements) {
HashSet<VirtualFile> files = new HashSet<>();
for (PsiElement elem : psiElements) {
if (elem instanceof PsiDirectory) {
files.add(((PsiDirectory)elem).getVirtualFile());
}
else if (elem instanceof PsiFile) {
VirtualFile virtualFile = ((PsiFile)elem).getVirtualFile();
if (virtualFile != null) {
files.add(virtualFile);
}
}
else if (elem instanceof PsiDirectoryContainer) {
PsiDirectory[] dirs = ((PsiDirectoryContainer)elem).getDirectories();
for (PsiDirectory dir : dirs) {
files.add(dir.getVirtualFile());
}
}
else {
PsiFile file = elem.getContainingFile();
if (file != null) {
VirtualFile virtualFile = file.getVirtualFile();
if (virtualFile != null) {
files.add(virtualFile);
}
}
}
}
VirtualFile[] result = VfsUtil.toVirtualFileArray(files);
files.clear();
return result;
}
private static VirtualFile[] getFilesFromModules(Module[] selectedModules) {
ArrayList<VirtualFile> result = new ArrayList<>();
for (Module selectedModule : selectedModules) {
ContainerUtil.addAll(result, ModuleRootManager.getInstance(selectedModule).getContentRoots());
}
return VfsUtil.toVirtualFileArray(result);
}
}
| consulo/consulo | modules/base/lang-impl/src/main/java/com/intellij/ide/impl/dataRules/VirtualFileArrayRule.java | Java | apache-2.0 | 5,692 |
package com.nollec.myservice;
<<<<<<< HEAD
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import com.android.volley.toolbox.Volley;
import com.example.myservice.R;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;
import java.io.StringReader;
=======
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
>>>>>>> e6f4ad129e697f8250d2c5c6acb69c625aa5827e
public class MainActivity extends AppCompatActivity {
private Button startService;
private Button stopService;
private Button bindServier;
private Button unbindService;
private MyService.DownloadBinder downloadBinder;
private ServiceConnection connection=new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
downloadBinder=(MyService.DownloadBinder)service;//向下转型
downloadBinder.startDownload();
downloadBinder.getProgress();
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
<<<<<<< HEAD
Volley volley=new Volley();
}
private void parseXMLWithPull(String xmlData){
try {
XmlPullParserFactory factory=XmlPullParserFactory.newInstance();
XmlPullParser xmlPullParser=factory.newPullParser();
xmlPullParser.setInput(new StringReader(xmlData));
int eventType=xmlPullParser.getEventType();
String id=null;
String name=null;
String version=null;
while(eventType!=XmlPullParser.END_DOCUMENT){
String nodeName=xmlPullParser.getName();
switch (eventType){
case XmlPullParser.START_TAG:
if("id".equals(nodeName)){
id=xmlPullParser.nextText();
}else if ("name".equals(nodeName)){
name=xmlPullParser.nextText();
}else if ("version".equals(nodeName)){
version=xmlPullParser.nextText();
}
break;
case XmlPullParser.END_TAG:
if ("app".equals(nodeName)){
Log.d("MainActivity","id is"+id);
Log.d("MainActivity","name is"+name);
Log.d("MainActivity","version is"+version);
}
break;
default:
break;
}
eventType=xmlPullParser.next();
}
} catch (Exception e) {
e.printStackTrace();
=======
startService = (Button) findViewById(R.id.start_service);
stopService = (Button) findViewById(R.id.stop_service);
bindServier= (Button) findViewById(R.id.bind_service);
unbindService= (Button) findViewById(R.id.unbind_service);
}
public void onClick(View v){
switch (v.getId()){
case R.id.start_service:
Intent startIntent=new Intent(this,MyService.class);
startService(startIntent);//启动服务
break;
case R.id.stop_service:
Intent stopIntent=new Intent(this,MyService.class);
stopService(stopIntent);//停止服务
break;
case R.id.bind_service:
Intent bindIntent=new Intent(this,MyService.class);
bindService(bindIntent,connection,BIND_AUTO_CREATE);
//BIND_AUTO_CREATE 表示在活动和服务进行绑定后自动创建服务
break;
case R.id.unbind_service:
unbindService(connection);
default:
break;
>>>>>>> e6f4ad129e697f8250d2c5c6acb69c625aa5827e
}
}
}
| songyang2088/A-week-to-develop-android-app-plan | 001_FeatureGuide/myservice/src/main/java/com/nollec/myservice/MainActivity.java | Java | apache-2.0 | 4,334 |
/**
* Copyright 2013 DuraSpace, 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 org.fcrepo.kernel;
import static com.hp.hpl.jena.graph.NodeFactory.createAnon;
import static com.hp.hpl.jena.graph.Triple.create;
import static com.hp.hpl.jena.rdf.model.ModelFactory.createDefaultModel;
import static com.hp.hpl.jena.rdf.model.ResourceFactory.createResource;
import static java.util.Calendar.JULY;
import static org.apache.commons.codec.digest.DigestUtils.shaHex;
import static org.fcrepo.jcr.FedoraJcrTypes.FEDORA_RESOURCE;
import static org.fcrepo.jcr.FedoraJcrTypes.JCR_CREATED;
import static org.fcrepo.jcr.FedoraJcrTypes.JCR_LASTMODIFIED;
import static org.fcrepo.kernel.FedoraResource.hasMixin;
import static org.fcrepo.kernel.rdf.JcrRdfTools.getProblemsModel;
import static org.fcrepo.kernel.utils.FedoraTypesUtils.getBaseVersion;
import static org.fcrepo.kernel.utils.FedoraTypesUtils.getVersionHistory;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.mockito.MockitoAnnotations.initMocks;
import static org.modeshape.jcr.api.JcrConstants.JCR_CONTENT;
import static org.powermock.api.mockito.PowerMockito.mockStatic;
import java.util.Calendar;
import java.util.Date;
import javax.jcr.Node;
import javax.jcr.Property;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.nodetype.NodeType;
import javax.jcr.version.Version;
import javax.jcr.version.VersionHistory;
import org.fcrepo.kernel.rdf.GraphSubjects;
import org.fcrepo.kernel.rdf.JcrRdfTools;
import org.fcrepo.kernel.rdf.impl.DefaultGraphSubjects;
import org.fcrepo.kernel.utils.FedoraTypesUtils;
import org.fcrepo.kernel.utils.iterators.RdfStream;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import com.hp.hpl.jena.graph.Triple;
import com.hp.hpl.jena.query.Dataset;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.sparql.util.Symbol;
@RunWith(PowerMockRunner.class)
//PowerMock needs to ignore some packages to prevent class-cast errors
//PowerMock needs to ignore unnecessary packages to keep from running out of heap
@PowerMockIgnore({
"org.slf4j.*",
"org.apache.xerces.*",
"javax.xml.*",
"org.xml.sax.*",
"javax.management.*",
"com.google.common.*",
"com.hp.hpl.jena.*",
"com.codahale.metrics.*"
})
@PrepareForTest({JcrRdfTools.class, FedoraTypesUtils.class})
public class FedoraResourceTest {
private FedoraResource testObj;
@Mock
private Node mockNode;
@Mock
private Node mockRoot;
@Mock
private Session mockSession;
private Resource mockResource = createResource();
@Mock
private Property mockProp;
private Triple mockTriple =
create(createAnon(), createAnon(), createAnon());
@Mock
private JcrRdfTools mockJcrRdfTools;
@Before
public void setUp() throws RepositoryException {
initMocks(this);
when(mockNode.getSession()).thenReturn(mockSession);
NodeType mockNodeType = mock(NodeType.class);
when(mockNodeType.getName()).thenReturn("nt:folder");
when(mockNode.getPrimaryNodeType()).thenReturn(mockNodeType);
testObj = new FedoraResource(mockNode);
assertEquals(mockNode, testObj.getNode());
}
@Test
public void testPathConstructor() throws RepositoryException {
when(mockSession.getRootNode()).thenReturn(mockRoot);
when(mockRoot.getNode("foo/bar")).thenReturn(mockNode);
when(mockNode.isNew()).thenReturn(true);
when(mockNode.getMixinNodeTypes()).thenReturn(new NodeType[] {});
new FedoraResource(mockSession, "/foo/bar", null);
}
@Test
public void testHasMixin() throws RepositoryException {
boolean actual;
final NodeType mockType = mock(NodeType.class);
final NodeType[] mockTypes = new NodeType[] {mockType};
when(mockNode.getMixinNodeTypes()).thenReturn(mockTypes);
actual = hasMixin(mockNode);
assertEquals(false, actual);
when(mockType.getName()).thenReturn(FEDORA_RESOURCE);
actual = hasMixin(mockNode);
assertEquals(true, actual);
}
@Test
public void testGetPath() throws RepositoryException {
testObj.getPath();
verify(mockNode).getPath();
}
@Test
public void testHasContent() throws RepositoryException {
testObj.hasContent();
verify(mockNode).hasNode(JCR_CONTENT);
}
@Test
public void testGetCreatedDate() throws RepositoryException {
final Calendar someDate = Calendar.getInstance();
when(mockProp.getDate()).thenReturn(someDate);
when(mockNode.hasProperty(JCR_CREATED)).thenReturn(true);
when(mockNode.getProperty(JCR_CREATED)).thenReturn(mockProp);
assertEquals(someDate.getTimeInMillis(), testObj.getCreatedDate()
.getTime());
}
@Test
public void testGetLastModifiedDateDefault() throws RepositoryException {
// test missing JCR_LASTMODIFIED
final Calendar someDate = Calendar.getInstance();
someDate.add(Calendar.DATE, -1);
try {
when(mockNode.hasProperty(JCR_LASTMODIFIED)).thenReturn(false);
when(mockProp.getDate()).thenReturn(someDate);
when(mockNode.hasProperty(JCR_CREATED)).thenReturn(true);
when(mockNode.getProperty(JCR_CREATED)).thenReturn(mockProp);
when(mockNode.getSession()).thenReturn(mockSession);
} catch (final RepositoryException e) {
e.printStackTrace();
}
final Date actual = testObj.getLastModifiedDate();
assertEquals(someDate.getTimeInMillis(), actual.getTime());
// this is a read operation, it must not persist the session
verify(mockSession, never()).save();
}
@Test
public void testGetLastModifiedDate() throws RepositoryException {
// test existing JCR_LASTMODIFIED
final Calendar someDate = Calendar.getInstance();
someDate.add(Calendar.DATE, -1);
try {
when(mockProp.getDate()).thenReturn(someDate);
when(mockNode.hasProperty(JCR_CREATED)).thenReturn(true);
when(mockNode.getProperty(JCR_CREATED)).thenReturn(mockProp);
when(mockNode.getSession()).thenReturn(mockSession);
} catch (final RepositoryException e) {
e.printStackTrace();
}
final Property mockMod = mock(Property.class);
final Calendar modDate = Calendar.getInstance();
try {
when(mockNode.hasProperty(JCR_LASTMODIFIED)).thenReturn(true);
when(mockNode.getProperty(JCR_LASTMODIFIED)).thenReturn(mockMod);
when(mockMod.getDate()).thenReturn(modDate);
} catch (final RepositoryException e) {
System.err.println("What are we doing in the second test?");
e.printStackTrace();
}
final Date actual = testObj.getLastModifiedDate();
assertEquals(modDate.getTimeInMillis(), actual.getTime());
}
@Test
public void testGetPropertiesDataset() throws Exception {
mockStatic(JcrRdfTools.class);
final GraphSubjects mockSubjects = mock(GraphSubjects.class);
when(JcrRdfTools.withContext(mockSubjects, mockSession)).thenReturn(mockJcrRdfTools);
when(mockSubjects.getGraphSubject(mockNode)).thenReturn(mockResource);
final RdfStream propertiesStream = new RdfStream(mockTriple);
when(mockJcrRdfTools.getJcrTriples(mockNode)).thenReturn(
propertiesStream);
final RdfStream treeStream = new RdfStream(mockTriple);
when(mockJcrRdfTools.getTreeTriples(mockNode)).thenReturn(
treeStream);
final Model problemsModel = new RdfStream().asModel();
when(getProblemsModel()).thenReturn(problemsModel);
final Dataset dataset =
testObj.getPropertiesDataset(mockSubjects, 0, -1);
assertTrue(dataset.getDefaultModel().containsAll(
propertiesStream.asModel()));
assertTrue(dataset.getDefaultModel().containsAll(
propertiesStream.asModel()));
assertEquals(mockResource, dataset.getContext().get(
Symbol.create("uri")));
}
@Test
public void testGetPropertiesDatasetDefaultLimits()
throws Exception {
mockStatic(JcrRdfTools.class);
final GraphSubjects mockSubjects = mock(GraphSubjects.class);
when(JcrRdfTools.withContext(mockSubjects, mockSession)).thenReturn(mockJcrRdfTools);
when(mockSubjects.getGraphSubject(mockNode)).thenReturn(mockResource);
final RdfStream propertiesStream = new RdfStream(mockTriple);
when(mockJcrRdfTools.getJcrTriples(mockNode)).thenReturn(propertiesStream);
final RdfStream treeStream = new RdfStream(mockTriple);
when(mockJcrRdfTools.getTreeTriples(mockNode)).thenReturn(treeStream);
final Model problemsModel = createDefaultModel();
when(getProblemsModel()).thenReturn(problemsModel);
final Dataset dataset = testObj.getPropertiesDataset(mockSubjects);
assertTrue(dataset.getDefaultModel().containsAll(treeStream.asModel()));
assertTrue(dataset.getDefaultModel().containsAll(
propertiesStream.asModel()));
assertEquals(mockResource, dataset.getContext().get(Symbol.create("uri")));
}
@Test
public void testGetVersionDataset() throws Exception {
mockStatic(FedoraTypesUtils.class);
when(getVersionHistory(mockNode)).thenReturn(mock(VersionHistory.class));
mockStatic(JcrRdfTools.class);
final GraphSubjects mockSubjects = mock(GraphSubjects.class);
when(JcrRdfTools.withContext(mockSubjects, mockSession)).thenReturn(mockJcrRdfTools);
when(mockSubjects.getGraphSubject(mockNode)).thenReturn(mockResource);
final RdfStream versionsStream = new RdfStream();
when(mockJcrRdfTools.getVersionTriples(any(Node.class)))
.thenReturn(versionsStream);
final RdfStream result = testObj.getVersionTriples(mockSubjects);
assertEquals(versionsStream, result);
}
@Test
public void testAddVersionLabel() throws RepositoryException {
mockStatic(FedoraTypesUtils.class);
final VersionHistory mockVersionHistory = mock(VersionHistory.class);
final Version mockVersion = mock(Version.class);
when(mockVersion.getName()).thenReturn("uuid");
when(getBaseVersion(mockNode)).thenReturn(mockVersion);
when(getVersionHistory(mockNode)).thenReturn(mockVersionHistory);
testObj.addVersionLabel("v1.0.0");
verify(mockVersionHistory).addVersionLabel("uuid", "v1.0.0", true);
}
@Test
public void testIsNew() throws RepositoryException {
when(mockNode.isNew()).thenReturn(true);
assertTrue("resource state should be the same as the node state",
testObj.isNew());
}
@Test
public void testIsNotNew() throws RepositoryException {
when(mockNode.isNew()).thenReturn(false);
assertFalse("resource state should be the same as the node state",
testObj.isNew());
}
@Test
public void testReplacePropertiesDataset() throws Exception {
mockStatic(JcrRdfTools.class);
final DefaultGraphSubjects defaultGraphSubjects = new DefaultGraphSubjects(mockSession);
when(JcrRdfTools.withContext(defaultGraphSubjects, mockSession)).thenReturn(mockJcrRdfTools);
when(mockNode.getPath()).thenReturn("/xyz");
final Model propertiesModel = createDefaultModel();
propertiesModel.add(propertiesModel.createResource("a"),
propertiesModel.createProperty("b"),
"c");
propertiesModel.add(propertiesModel.createResource("i"),
propertiesModel.createProperty("j"),
"k");
propertiesModel.add(propertiesModel.createResource("x"),
propertiesModel.createProperty("y"),
"z");
final RdfStream propertiesStream = RdfStream.fromModel(propertiesModel);
when(mockJcrRdfTools.getJcrTriples(mockNode)).thenReturn(propertiesStream);
final RdfStream treeStream = new RdfStream();
when(mockJcrRdfTools.getTreeTriples(mockNode)).thenReturn(treeStream);
final Model problemsModel = createDefaultModel();
when(getProblemsModel()).thenReturn(problemsModel);
final Model replacementModel = createDefaultModel();
replacementModel.add(replacementModel.createResource("a"),
replacementModel.createProperty("b"),
"n");
replacementModel.add(replacementModel.createResource("i"),
replacementModel.createProperty("j"),
"k");
final Model replacements = testObj.replaceProperties(defaultGraphSubjects, replacementModel).asModel();
assertTrue(replacements.containsAll(replacementModel));
assertFalse(problemsModel.contains(propertiesModel.createResource("x"),
propertiesModel.createProperty("y"),
"z"));
}
@Test
public void shouldGetEtagForAnObject() throws RepositoryException {
final Property mockMod = mock(Property.class);
final Calendar modDate = Calendar.getInstance();
modDate.set(2013, JULY, 30, 0, 0, 0);
when(mockNode.getPath()).thenReturn("some-path");
when(mockNode.hasProperty(JCR_LASTMODIFIED)).thenReturn(true);
when(mockNode.getProperty(JCR_LASTMODIFIED)).thenReturn(mockMod);
when(mockMod.getDate()).thenReturn(modDate);
assertEquals(shaHex("some-path"
+ testObj.getLastModifiedDate().toString()), testObj
.getEtagValue());
}
}
| barmintor/fcrepo4 | fcrepo-kernel/src/test/java/org/fcrepo/kernel/FedoraResourceTest.java | Java | apache-2.0 | 15,120 |
/*
* Copyright 2014-2019 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.amazonaws.services.codecommit.model.transform;
import java.math.*;
import javax.annotation.Generated;
import com.amazonaws.services.codecommit.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;
import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;
/**
* GetMergeCommitResult JSON Unmarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class GetMergeCommitResultJsonUnmarshaller implements Unmarshaller<GetMergeCommitResult, JsonUnmarshallerContext> {
public GetMergeCommitResult unmarshall(JsonUnmarshallerContext context) throws Exception {
GetMergeCommitResult getMergeCommitResult = new GetMergeCommitResult();
int originalDepth = context.getCurrentDepth();
String currentParentElement = context.getCurrentParentElement();
int targetDepth = originalDepth + 1;
JsonToken token = context.getCurrentToken();
if (token == null)
token = context.nextToken();
if (token == VALUE_NULL) {
return getMergeCommitResult;
}
while (true) {
if (token == null)
break;
if (token == FIELD_NAME || token == START_OBJECT) {
if (context.testExpression("sourceCommitId", targetDepth)) {
context.nextToken();
getMergeCommitResult.setSourceCommitId(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("destinationCommitId", targetDepth)) {
context.nextToken();
getMergeCommitResult.setDestinationCommitId(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("baseCommitId", targetDepth)) {
context.nextToken();
getMergeCommitResult.setBaseCommitId(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("mergedCommitId", targetDepth)) {
context.nextToken();
getMergeCommitResult.setMergedCommitId(context.getUnmarshaller(String.class).unmarshall(context));
}
} else if (token == END_ARRAY || token == END_OBJECT) {
if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
if (context.getCurrentDepth() <= originalDepth)
break;
}
}
token = context.nextToken();
}
return getMergeCommitResult;
}
private static GetMergeCommitResultJsonUnmarshaller instance;
public static GetMergeCommitResultJsonUnmarshaller getInstance() {
if (instance == null)
instance = new GetMergeCommitResultJsonUnmarshaller();
return instance;
}
}
| jentfoo/aws-sdk-java | aws-java-sdk-codecommit/src/main/java/com/amazonaws/services/codecommit/model/transform/GetMergeCommitResultJsonUnmarshaller.java | Java | apache-2.0 | 3,601 |
using Nest;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace _1_RabbitMq_Mapping_ElasticSearch.Mapping
{
public static class GeoUtil
{
public static Dictionary<string, GeoLocation> Memory = new Dictionary<string, GeoLocation>();
public static GeoLocation GetByUrl(string url) {
Uri myUri = new Uri(url);
var ip = Dns.GetHostAddresses(myUri.Host).FirstOrDefault();
if(ip == null) {
return new GeoLocation(0, 0);
}
return GetByIp(ip.ToString());
}
public static GeoLocation GetByIp(string ip) {
if(Memory.ContainsKey(ip)) {
return Memory[ip];
}
var result = new WebClient().DownloadString(string.Format("http://ws.cdyne.com/ip2geo/ip2geo.asmx/ResolveIP?ipAddress={0}&licenseKey=1", ip.ToString()));
var xDoc = XDocument.Parse(result).Root.DescendantNodes().Where(x => x is XElement);
var lat = xDoc.FirstOrDefault(x => ((XElement)x).Name.LocalName == "Latitude");
var lng = xDoc.Where(x => x is XElement).FirstOrDefault(x => ((XElement)x).Name.LocalName == "Longitude");
var res = new GeoLocation(
double.Parse((lat as XElement).Value, CultureInfo.InvariantCulture),
double.Parse((lng as XElement).Value, CultureInfo.InvariantCulture)
);
Memory.Add(ip, res);
return res;
}
}
}
| AlexanderMykulych/InterflowFramework | InterflowFramework/1_RabbitMq-Mapping-ElasticSearch/Mapping/GeoUtil.cs | C# | apache-2.0 | 1,399 |
//
// Diese Datei wurde mit der JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.5-2 generiert
// Siehe <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Änderungen an dieser Datei gehen bei einer Neukompilierung des Quellschemas verloren.
// Generiert: 2016.03.16 um 01:52:47 PM CET
//
package org.onvif.ver10.events.wsdl;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAnyElement;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import org.oasis_open.docs.wsn.t_1.TopicSetType;
/**
* <p>Java-Klasse für anonymous complex type.
*
* <p>Das folgende Schemafragment gibt den erwarteten Content an, der in dieser Klasse enthalten ist.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="TopicNamespaceLocation" type="{http://www.w3.org/2001/XMLSchema}anyURI" maxOccurs="unbounded"/>
* <element ref="{http://docs.oasis-open.org/wsn/b-2}FixedTopicSet"/>
* <element ref="{http://docs.oasis-open.org/wsn/t-1}TopicSet"/>
* <element ref="{http://docs.oasis-open.org/wsn/b-2}TopicExpressionDialect" maxOccurs="unbounded"/>
* <element name="MessageContentFilterDialect" type="{http://www.w3.org/2001/XMLSchema}anyURI" maxOccurs="unbounded"/>
* <element name="ProducerPropertiesFilterDialect" type="{http://www.w3.org/2001/XMLSchema}anyURI" maxOccurs="unbounded" minOccurs="0"/>
* <element name="MessageContentSchemaLocation" type="{http://www.w3.org/2001/XMLSchema}anyURI" maxOccurs="unbounded"/>
* <any namespace='##other' maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"topicNamespaceLocation",
"fixedTopicSet",
"topicSet",
"topicExpressionDialect",
"messageContentFilterDialect",
"producerPropertiesFilterDialect",
"messageContentSchemaLocation",
"any"
})
@XmlRootElement(name = "GetEventPropertiesResponse")
public class GetEventPropertiesResponse {
@XmlElement(name = "TopicNamespaceLocation", required = true)
@XmlSchemaType(name = "anyURI")
protected List<String> topicNamespaceLocation;
@XmlElement(name = "FixedTopicSet", namespace = "http://docs.oasis-open.org/wsn/b-2", defaultValue = "true")
protected boolean fixedTopicSet;
@XmlElement(name = "TopicSet", namespace = "http://docs.oasis-open.org/wsn/t-1", required = true)
protected TopicSetType topicSet;
@XmlElement(name = "TopicExpressionDialect", namespace = "http://docs.oasis-open.org/wsn/b-2", required = true)
@XmlSchemaType(name = "anyURI")
protected List<String> topicExpressionDialect;
@XmlElement(name = "MessageContentFilterDialect", required = true)
@XmlSchemaType(name = "anyURI")
protected List<String> messageContentFilterDialect;
@XmlElement(name = "ProducerPropertiesFilterDialect")
@XmlSchemaType(name = "anyURI")
protected List<String> producerPropertiesFilterDialect;
@XmlElement(name = "MessageContentSchemaLocation", required = true)
@XmlSchemaType(name = "anyURI")
protected List<String> messageContentSchemaLocation;
@XmlAnyElement(lax = true)
protected List<Object> any;
/**
* Gets the value of the topicNamespaceLocation property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the topicNamespaceLocation property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getTopicNamespaceLocation().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
*
*
*/
public List<String> getTopicNamespaceLocation() {
if (topicNamespaceLocation == null) {
topicNamespaceLocation = new ArrayList<String>();
}
return this.topicNamespaceLocation;
}
/**
* True when topicset is fixed for all times.
*
*/
public boolean isFixedTopicSet() {
return fixedTopicSet;
}
/**
* Legt den Wert der fixedTopicSet-Eigenschaft fest.
*
*/
public void setFixedTopicSet(boolean value) {
this.fixedTopicSet = value;
}
/**
* Set of topics supported.
*
* @return
* possible object is
* {@link TopicSetType }
*
*/
public TopicSetType getTopicSet() {
return topicSet;
}
/**
* Legt den Wert der topicSet-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link TopicSetType }
*
*/
public void setTopicSet(TopicSetType value) {
this.topicSet = value;
}
/**
*
* Defines the XPath expression syntax supported for matching topic expressions.
* <pre>
* <?xml version="1.0" encoding="UTF-8"?><br xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap12/" xmlns:tev="http://www.onvif.org/ver10/events/wsdl" xmlns:wsa="http://www.w3.org/2005/08/addressing" xmlns:wsaw="http://www.w3.org/2006/05/addressing/wsdl" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:wsnt="http://docs.oasis-open.org/wsn/b-2" xmlns:wsntw="http://docs.oasis-open.org/wsn/bw-2" xmlns:wsrf-rw="http://docs.oasis-open.org/wsrf/rw-2" xmlns:wstop="http://docs.oasis-open.org/wsn/t-1" xmlns:xs="http://www.w3.org/2001/XMLSchema"/>
* </pre>
*
* The following TopicExpressionDialects are mandatory for an ONVIF compliant device :
*
* <pre>
* <?xml version="1.0" encoding="UTF-8"?><ul xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap12/" xmlns:tev="http://www.onvif.org/ver10/events/wsdl" xmlns:wsa="http://www.w3.org/2005/08/addressing" xmlns:wsaw="http://www.w3.org/2006/05/addressing/wsdl" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:wsnt="http://docs.oasis-open.org/wsn/b-2" xmlns:wsntw="http://docs.oasis-open.org/wsn/bw-2" xmlns:wsrf-rw="http://docs.oasis-open.org/wsrf/rw-2" xmlns:wstop="http://docs.oasis-open.org/wsn/t-1" xmlns:xs="http://www.w3.org/2001/XMLSchema" type="disc"><li>http://docs.oasis-open.org/wsn/t-1/TopicExpression/Concrete</li><li>http://www.onvif.org/ver10/tev/topicExpression/ConcreteSet.</li></ul>
* </pre>
* Gets the value of the topicExpressionDialect property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the topicExpressionDialect property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getTopicExpressionDialect().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
*
*
*/
public List<String> getTopicExpressionDialect() {
if (topicExpressionDialect == null) {
topicExpressionDialect = new ArrayList<String>();
}
return this.topicExpressionDialect;
}
/**
* Gets the value of the messageContentFilterDialect property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the messageContentFilterDialect property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getMessageContentFilterDialect().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
*
*
*/
public List<String> getMessageContentFilterDialect() {
if (messageContentFilterDialect == null) {
messageContentFilterDialect = new ArrayList<String>();
}
return this.messageContentFilterDialect;
}
/**
* Gets the value of the producerPropertiesFilterDialect property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the producerPropertiesFilterDialect property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getProducerPropertiesFilterDialect().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
*
*
*/
public List<String> getProducerPropertiesFilterDialect() {
if (producerPropertiesFilterDialect == null) {
producerPropertiesFilterDialect = new ArrayList<String>();
}
return this.producerPropertiesFilterDialect;
}
/**
* Gets the value of the messageContentSchemaLocation property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the messageContentSchemaLocation property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getMessageContentSchemaLocation().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
*
*
*/
public List<String> getMessageContentSchemaLocation() {
if (messageContentSchemaLocation == null) {
messageContentSchemaLocation = new ArrayList<String>();
}
return this.messageContentSchemaLocation;
}
/**
* Gets the value of the any property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the any property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getAny().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link Object }
*
*
*/
public List<Object> getAny() {
if (any == null) {
any = new ArrayList<Object>();
}
return this.any;
}
}
| milg0/onvif-java-lib | src/org/onvif/ver10/events/wsdl/GetEventPropertiesResponse.java | Java | apache-2.0 | 11,762 |
package com.crawljax.condition;
import net.jcip.annotations.Immutable;
import com.crawljax.browser.EmbeddedBrowser;
/**
* Conditions that returns true iff the browser's current url contains url. Note: Case insesitive
*
* @author dannyroest@gmail.com (Danny Roest)
*/
@Immutable
public class UrlCondition extends AbstractCondition {
private final String url;
/**
* @param url
* the URL.
*/
public UrlCondition(String url) {
this.url = url;
}
@Override
public boolean check(EmbeddedBrowser browser) {
return browser.getCurrentUrl().toLowerCase().contains(url);
}
}
| saltlab/crawljax-graphdb | core/src/main/java/com/crawljax/condition/UrlCondition.java | Java | apache-2.0 | 603 |
'use strict';
// Convenient Node cluster setup, which monitors and restarts child processes
// as needed. Creates workers, monitors them, restarts them as needed, and
// manages the flow of event messages between the cluster master and the
// workers.
// We use process.exit() intentionally here
/* eslint no-process-exit: 1 */
const _ = require('underscore');
const cluster = require('cluster');
const events = require('abacus-events');
const vcapenv = require('abacus-vcapenv');
const map = _.map;
const clone = _.clone;
const range = _.range;
// Setup debug log
const debuglog = require('abacus-debug');
const debug = debuglog('abacus-cluster');
const xdebug = debuglog('@x-abacus/cluster');
// Set up an event emitter allowing a cluster to listen to messages from other
// modules and propagate them to the entire cluster
const emitter = events.emitter('abacus-cluster/emitter');
const on = (e, l) => {
emitter.on(e, l);
};
// We're monitoring the health of cluster workers by requiring them to send
// heartbeat messages and monitoring these heartbeats in the cluster master.
// We terminate a worker if it stops sending heartbeats, resulting in a new
// worker getting forked to replace it. The following two times (in ms)
// are used to configure the expected worker heart rate and our monitoring
// interval.
const heartbeatInterval = parseInt(process.env.CLUSTER_HEARTBEAT) || 30000;
const heartMonitorInterval = heartbeatInterval * 2;
// Return true if we're in a cluster master process
const isMaster = () => cluster.isMaster;
// Return true if we're in a cluster worker process
const isWorker = () => cluster.noCluster || cluster.isWorker;
// Return the current worker id
const wid = () => cluster.worker ? cluster.worker.id : 0;
// Configure the number of workers to use in the cluster
// Warning: workers is a mutable variable
let workers = parseInt(process.env.CLUSTER_WORKERS) || 1;
const scale = (w) => {
// Broadcast workers event to all instances of this module
workers = w || parseInt(process.env.CLUSTER_WORKERS) || 1;
debug('Requesting cluster update to %d workers', workers);
emitter.emit('workers', workers);
return workers;
};
// Return the number of workers in the cluster
const size = () => {
return workers;
};
// Configure the cluster to run a single worker
const singleton = () => scale(1);
// Handle event requesting configuration of the number of workers to use
emitter.on('workers', (w) => {
// Warning: mutating variable workers
debug('Updating cluster to %d workers', w);
workers = w;
});
// Monitor a worker process and emit its messages to the emitter listeners
const monitor = (worker) => {
// Give the worker an initial heartbeat, as we don't want to erroneously
// terminate it just after we've forked it if we hit our heart monitoring
// cutoff before that worker gets a chance to report its heartbeat
worker.heartbeat = Date.now();
worker.on('message', (m) => {
const msg = clone(m);
// Record a worker heartbeat message in the worker, we're monitoring
// these messages in our worker heart monitor function
// Warning: mutating variable worker, but that's the simplest thing to
// do here
if(msg.heartbeat)
worker.heartbeat = msg.heartbeat;
// Store worker information in the message so any listener that's interested
// can determine which worker the message is coming from
msg.worker = {
id: worker.id,
process: {
pid: worker.process.pid
}
};
xdebug('Cluster master got message from worker %o', msg);
emitter.emit('message', msg);
});
};
// Fork a number of workers, configurable with a default of 1
const fork = () => {
debug('Forking %d cluster workers', workers);
map(range(workers), () => monitor(cluster.fork()));
};
// Handle process signals
const signals = (t, cleanupcb) => {
process.on('SIGINT', () => {
debug('%s interrupted', t);
cleanupcb(() => process.exit(0));
});
process.on('SIGTERM', () => {
debug('%s terminated', t);
cleanupcb(() => process.exit(0));
process.exit(0);
});
if(process.env.HEAPDUMP) {
// Trigger heapdumps
process.on('SIGWINCH', () => {
if(global.gc) {
debug('%s gc\'ing');
global.gc();
}
});
// Save heapdumps
require('heapdump');
}
process.on('exit', (code) => {
if(code !== 0)
debug('Cluster %s exiting with code %d', t, code);
else
debug('Cluster %s exiting', t);
emitter.emit('log', {
category: 'cluster',
event: 'exiting',
type: t,
pid: process.pid,
code: code
});
});
};
// A simple worker heart monitor, which regularly checks if workers have
// reported a heartbeat and terminates them if they haven't
const heartMonitor = () => {
const cutoff = Date.now() - heartMonitorInterval;
map(cluster.workers, (worker) => {
// Disconnect worker if it failed to report a heartbeat within the
// last monitoring interval
if(worker.heartbeat < cutoff) {
debug('Cluster worker %d didn\'t report heartbeat, disconnecting it',
worker.process.pid);
worker.disconnect();
}
});
};
// Setup a Node cluster master process
const master = () => {
debug('Cluster master started');
emitter.emit('log', {
category: 'cluster',
event: 'started',
type: 'master',
pid: process.pid
});
// Monitor the heartbeats of our workers at regular intervals
const i = setInterval(heartMonitor, heartMonitorInterval);
if(i.unref) i.unref();
// Set the master process title
process.title = 'node ' +
(process.env.TITLE || [vcapenv.appname(), vcapenv.appindex()].join('-')) +
' master';
// Handle process signals
signals('master', (exitcb) => {
// Terminate the workers
// Let the master process exit
exitcb();
});
// Restart worker on disconnect unless it's marked with a noretry flag
cluster.on('disconnect', (worker) => {
debug('Cluster worker %d disconnected', worker.process.pid);
if(!worker.noretry)
monitor(cluster.fork());
});
cluster.on('exit', (worker, code, signal) => {
debug('Cluster worker %d exited with code %d', worker.process.pid, code);
});
// Handle messages from worker servers
emitter.on('message', (msg) => {
if(msg.server) {
if(msg.server.noretry) {
debug('Cluster worker %d reported fatal error', msg.worker.process
.pid);
// Mark worker with a noretry flag if it requested it, typically to
// avoid infinite retries when the worker has determined that retrying
// would fail again anyway
// Warning: mutating worker variable here
cluster.workers[msg.worker.id].noretry = true;
}
if(msg.server.listening)
debug('Cluster worker %d listening on %d',
msg.worker.process.pid, msg.server.listening);
if(msg.server.exiting) debug('Cluster worker %d exiting', msg.worker
.process.pid);
}
});
};
// Setup a Node cluster worker process
const worker = () => {
debug('Cluster worker started');
emitter.emit('log', {
category: 'cluster',
event: 'started',
type: 'worker',
pid: process.pid
});
// Set the worker process title
process.title = 'node ' +
(process.env.TITLE || [vcapenv.appname(), vcapenv.appindex()].join('-')) +
' worker';
// Handle process signals
signals('worker', (exitcb) => {
// Let the process exit
exitcb();
});
// Send a heartbeat message to the master at regular intervals
// If the worker fails to send a heartbeat, well, we know it's not going
// well and the master will terminate it
const heartbeatReporter = setInterval(() => {
process.send({
heartbeat: Date.now()
});
}, heartbeatInterval);
// Shutdown the heartbeat reporter when the worker is getting disconnected
process.on('disconnect', () => {
clearInterval(heartbeatReporter);
});
// Emit messages from the master to the emitter listeners
process.on('message', (msg) => {
emitter.emit('message', msg);
});
};
// Configure a server for clustering
const clusterify = (server) => {
// Optionally disable clustering to help debugging and profiling
if(process.env.CLUSTER === 'false') {
cluster.noCluster = true;
// Handle process signals
signals('worker', (exitcb) => {
// Let the process exit
exitcb();
});
return server;
}
if(cluster.isMaster) {
// Setup the master process
master();
// Monkey patch the listen function, as in the master we want to fork
// worker processes instead of actually listening
if(server.listen)
server.listen = fork;
}
// Setup a worker process
else worker();
return server;
};
// Process messages from other modules
const onMessage = (msg) => {
xdebug('Got message in onMessage %o', msg);
if(cluster.isWorker) {
// In a worker process, send message to the master
xdebug('Cluster worker sending message to master %o', msg);
process.send(msg);
}
else {
// In the master process, send message to all the workers
const mmsg = clone(msg);
mmsg.master = process.pid;
map(cluster.workers, (worker) => {
xdebug('Cluster master sending message to worker %d %o', worker.process
.pid, mmsg);
worker.send(mmsg);
});
}
};
// Stitch the debug and cluster emitters and listeners together to make debug
// config messages flow from workers to master and back to workers and
// broadcast the log config across the cluster
// Let the debug module send messages to the cluster master
debuglog.on('message', onMessage);
// Pass cluster messages to the debug module
emitter.on('message', debuglog.onMessage);
// Export our public functions
module.exports = clusterify;
module.exports.onMessage = onMessage;
module.exports.on = on;
module.exports.isWorker = isWorker;
module.exports.isMaster = isMaster;
module.exports.scale = scale;
module.exports.singleton = singleton;
module.exports.size = size;
module.exports.wid = wid;
| sasrin/cf-abacus | lib/utils/cluster/src/index.js | JavaScript | apache-2.0 | 10,064 |
/*
* Copyright 2012-2014 MarkLogic 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.marklogic.client.impl;
import com.marklogic.client.io.Format;
import com.marklogic.client.document.TextDocumentManager;
import com.marklogic.client.io.marker.TextReadHandle;
import com.marklogic.client.io.marker.TextWriteHandle;
class TextDocumentImpl
extends DocumentManagerImpl<TextReadHandle, TextWriteHandle>
implements TextDocumentManager
{
TextDocumentImpl(RESTServices services) {
super(services, Format.TEXT);
}
}
| grechaw/java-client-api | src/main/java/com/marklogic/client/impl/TextDocumentImpl.java | Java | apache-2.0 | 1,051 |
/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=======================================================================*/
// This class has been generated, DO NOT EDIT!
package org.tensorflow.op.core;
import java.util.Arrays;
import org.tensorflow.GraphOperation;
import org.tensorflow.Operand;
import org.tensorflow.Operation;
import org.tensorflow.OperationBuilder;
import org.tensorflow.Output;
import org.tensorflow.op.RawOp;
import org.tensorflow.op.RawOpInputs;
import org.tensorflow.op.Scope;
import org.tensorflow.op.annotation.Endpoint;
import org.tensorflow.op.annotation.OpInputsMetadata;
import org.tensorflow.op.annotation.OpMetadata;
import org.tensorflow.op.annotation.Operator;
import org.tensorflow.types.family.TType;
/**
* Creates and returns an empty tensor map.
* handle: an empty tensor map
*/
@OpMetadata(
opType = EmptyTensorMap.OP_NAME,
inputsClass = EmptyTensorMap.Inputs.class
)
@Operator
public final class EmptyTensorMap extends RawOp implements Operand<TType> {
/**
* The name of this op, as known by TensorFlow core engine
*/
public static final String OP_NAME = "EmptyTensorMap";
private Output<? extends TType> handle;
@SuppressWarnings("unchecked")
public EmptyTensorMap(Operation operation) {
super(operation, OP_NAME);
int outputIdx = 0;
handle = operation.output(outputIdx++);
}
/**
* Factory method to create a class wrapping a new EmptyTensorMap operation.
*
* @param scope current scope
* @return a new instance of EmptyTensorMap
*/
@Endpoint(
describeByClass = true
)
public static EmptyTensorMap create(Scope scope) {
OperationBuilder opBuilder = scope.opBuilder(OP_NAME, "EmptyTensorMap");
return new EmptyTensorMap(opBuilder.build());
}
/**
* Gets handle.
*
* @return handle.
*/
public Output<? extends TType> handle() {
return handle;
}
@Override
@SuppressWarnings("unchecked")
public Output<TType> asOutput() {
return (Output<TType>) handle;
}
@OpInputsMetadata(
outputsClass = EmptyTensorMap.class
)
public static class Inputs extends RawOpInputs<EmptyTensorMap> {
public Inputs(GraphOperation op) {
super(new EmptyTensorMap(op), op, Arrays.asList());
int inputIndex = 0;
}
}
}
| tensorflow/java | tensorflow-core/tensorflow-core-api/src/gen/java/org/tensorflow/op/core/EmptyTensorMap.java | Java | apache-2.0 | 2,823 |
/*
Copyright 2014 Google Inc. 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.cloud.genomics.localrepo.dto;
import com.google.cloud.genomics.localrepo.DataTransferObject;
import org.codehaus.jackson.annotate.JsonCreator;
import org.codehaus.jackson.annotate.JsonProperty;
import java.util.List;
public class SearchReadsetsRequest extends DataTransferObject {
private static final ReflectiveHashCodeAndEquals<SearchReadsetsRequest> HASH_CODE_AND_EQUALS =
ReflectiveHashCodeAndEquals.create(SearchReadsetsRequest.class);
@JsonCreator public static SearchReadsetsRequest create(
@JsonProperty("datasetIds") List<String> datasetIds,
@JsonProperty("pageToken") String pageToken) {
return new SearchReadsetsRequest(datasetIds, pageToken);
}
private final List<String> datasetIds;
private final String pageToken;
private SearchReadsetsRequest(
List<String> datasetIds,
String pageToken) {
this.datasetIds = datasetIds;
this.pageToken = pageToken;
}
@Override public boolean equals(Object obj) {
return HASH_CODE_AND_EQUALS.equals(this, obj);
}
public List<String> getDatasetIds() {
return datasetIds;
}
public String getPageToken() {
return pageToken;
}
@Override public int hashCode() {
return HASH_CODE_AND_EQUALS.hashCode(this);
}
}
| Tong-Chen/genomics-tools | readstore-local-java/src/main/java/com/google/cloud/genomics/localrepo/dto/SearchReadsetsRequest.java | Java | apache-2.0 | 1,849 |