code
stringlengths 3
1.05M
| repo_name
stringlengths 4
116
| path
stringlengths 3
942
| language
stringclasses 30
values | license
stringclasses 15
values | size
int32 3
1.05M
|
---|---|---|---|---|---|
/*
* Copyright © 2016 - 2017 Dominik Szalai ([email protected])
*
* 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 cz.muni.fi.editor.support;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.core.annotation.AliasFor;
import org.springframework.security.test.context.support.WithSecurityContext;
/**
* @author Dominik Szalai - emptulik at gmail.com on 10.8.2016.
*/
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
@WithSecurityContext(
factory = TestSecurityContextFactory.class
)
public @interface WithEditorUser {
// the owner is always user with ID 1
@AliasFor("value")
long id() default 1L;
@AliasFor("id")
long value() default 1L;
boolean mock() default false;
}
| empt-ak/meditor | editor-backend/src/test/java/cz/muni/fi/editor/support/WithEditorUser.java | Java | apache-2.0 | 1,489 |
# Ceratium buceros (Zacharias) Schiller SPECIES
#### Status
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Protozoa/Dinophyta/Dinophyceae/Peridiniales/Ceratiaceae/Ceratium/Ceratium buceros/README.md | Markdown | apache-2.0 | 195 |
# Dactylis glomerata var. hispanica VARIETY
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
Cat. Bot. 1:8. 1797
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Liliopsida/Poales/Poaceae/Dactylis/Dactylis glomerata/ Syn. Dactylis glomerata hispanica/README.md | Markdown | apache-2.0 | 205 |
# Andropogon exaltatus var. ambiguus VARIETY
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Liliopsida/Poales/Poaceae/Cymbopogon/Cymbopogon ambiguus/ Syn. Andropogon exaltatus ambiguus/README.md | Markdown | apache-2.0 | 191 |
# Sida decumbens f. suberecta Chodat & Hassl. FORM
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Malvales/Malvaceae/Sida/Sida decumbens/Sida decumbens suberecta/README.md | Markdown | apache-2.0 | 190 |
# Cereus sublanatus Salm-Dyck SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Caryophyllales/Cactaceae/Cereus/Cereus sublanatus/README.md | Markdown | apache-2.0 | 177 |
# Acianthera carinata (C.Schweinf.) Luer SPECIES
#### Status
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
Pleurothallis carinata C.Schweinf.
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Liliopsida/Asparagales/Orchidaceae/Acianthera/Acianthera carinata/README.md | Markdown | apache-2.0 | 226 |
# Ramariopsis kunzei var. subasperata Corner, 1950 VARIETY
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
Monograph of Clavaria and allied Genera (Annals of Botany Memoirs No. 1) 700 (1950)
#### Original name
Ramariopsis kunzei var. subasperata Corner, 1950
### Remarks
null | mdoering/backbone | life/Fungi/Basidiomycota/Agaricomycetes/Agaricales/Clavariaceae/Ramariopsis/Ramariopsis kunzei/ Syn. Ramariopsis kunzei subasperata/README.md | Markdown | apache-2.0 | 328 |
# Colpoda colpoda SPECIES
#### Status
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Protozoa/Ciliophora/Colpodea/Colpodida/Colpodidae/Colpoda/Colpoda colpoda/README.md | Markdown | apache-2.0 | 173 |
# Cornus acuminata Hort. ex Lavallée SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Cornales/Cornaceae/Cornus/Cornus acuminata/README.md | Markdown | apache-2.0 | 185 |
/*
* Copyright (C) 2014-2015 Vy Nguyen
* Github https://github.com/vy-nguyen/tvntd
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#ifndef _CRYPTO_USER_CACHE_H_
#define _CRYPTO_USER_CACHE_H_
#include <crypto/user.h>
class AsyncKeyClient;
class KeyServiceClient;
class UserLruCache : public LruTable
{
public:
UserLruCache(int max_elm, Crypto::ptr m) : LruTable(max_elm), cryp_mod(m) {}
inline UserCrypto::ptr get_user(uint64_t uuid) {
return object_cast<UserCrypto>(lookup(uuid));
}
inline UserCrypto::ptr get_user(uint64_t uuid, uint64_t key_ver) {
return object_cast<UserCrypto>(lookup(uuid));
}
void get_user(uint64_t uuid, uint64_t key_ver, lru_str_cb cb);
bool get_public_key(uint64_t uuid, uint64_t ver, std::string *key);
void get_public_key(uint64_t uuid, uint64_t ver, lru_str_cb cb);
bool get_all_pub_keys(uint64_t uuid, std::vector<Crypto::KeyVer::ptr> *krec);
LruObj::ptr lookup_missed(uint64_t uuid) override;
LruObj::ptr lookup_missed(const std::string &key) override;
void lookup_missed(uint64_t uuid, lru_u64_cb cb) override;
void lookup_missed(const std::string &key, lru_str_cb cb) override;
protected:
Crypto::ptr cryp_mod;
};
#endif /* _CRYPTO_USER_CACHE_H_ */
| vy-nguyen/tvntd | crypto/user-cache.h | C | apache-2.0 | 2,523 |
/**
* Licensed to the Austrian Association for Software Tool Integration (AASTI)
* under one or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. The AASTI 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.openengsb.ui.admin.tree.editablePanel;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.IModel;
@SuppressWarnings("serial")
public class EditablePanel extends Panel {
public EditablePanel(String id, IModel<String> inputModel) {
super(id);
TextField<String> field = new TextField<String>("textfield", inputModel);
add(field);
field.add(new AjaxFormComponentUpdatingBehavior("onblur") {
@Override
protected void onUpdate(AjaxRequestTarget target) {
}
});
}
}
| openengsb/openengsb | ui/admin/src/main/java/org/openengsb/ui/admin/tree/editablePanel/EditablePanel.java | Java | apache-2.0 | 1,593 |
# Sopubia kacondensis S.Moore SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Lamiales/Orobanchaceae/Sopubia/Sopubia kacondensis/README.md | Markdown | apache-2.0 | 177 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="de">
<head>
<!-- Generated by javadoc (1.8.0_101) on Mon Aug 22 00:07:21 CEST 2016 -->
<title>de.dhbw.wi13c.jguicreator.data.validator</title>
<meta name="date" content="2016-08-22">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="de.dhbw.wi13c.jguicreator.data.validator";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li class="navBarCell1Rev">Package</li>
<li>Class</li>
<li><a href="package-use.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../../de/dhbw/wi13c/jguicreator/data/util/package-summary.html">Prev Package</a></li>
<li><a href="../../../../../../de/dhbw/wi13c/jguicreator/elemente/package-summary.html">Next Package</a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?de/dhbw/wi13c/jguicreator/data/validator/package-summary.html" target="_top">Frames</a></li>
<li><a href="package-summary.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h1 title="Package" class="title">Package de.dhbw.wi13c.jguicreator.data.validator</h1>
</div>
<div class="contentContainer">
<ul class="blockList">
<li class="blockList">
<table class="typeSummary" border="0" cellpadding="3" cellspacing="0" summary="Class Summary table, listing classes, and an explanation">
<caption><span>Class Summary</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Class</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="../../../../../../de/dhbw/wi13c/jguicreator/data/validator/NotNullValidator.html" title="class in de.dhbw.wi13c.jguicreator.data.validator">NotNullValidator</a></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../../../de/dhbw/wi13c/jguicreator/data/validator/PatternValidator.html" title="class in de.dhbw.wi13c.jguicreator.data.validator">PatternValidator</a></td>
<td class="colLast"> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../../../../de/dhbw/wi13c/jguicreator/data/validator/SizeValidator.html" title="class in de.dhbw.wi13c.jguicreator.data.validator">SizeValidator</a></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../../../de/dhbw/wi13c/jguicreator/data/validator/Validator.html" title="class in de.dhbw.wi13c.jguicreator.data.validator">Validator</a><T></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li class="navBarCell1Rev">Package</li>
<li>Class</li>
<li><a href="package-use.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../../de/dhbw/wi13c/jguicreator/data/util/package-summary.html">Prev Package</a></li>
<li><a href="../../../../../../de/dhbw/wi13c/jguicreator/elemente/package-summary.html">Next Package</a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?de/dhbw/wi13c/jguicreator/data/validator/package-summary.html" target="_top">Frames</a></li>
<li><a href="package-summary.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| WI13C/Jgui-creator | code/framework/doc/de/dhbw/wi13c/jguicreator/data/validator/package-summary.html | HTML | apache-2.0 | 5,916 |
<?php
namespace Test\Webmail;
use Magium\AbstractTestCase;
use Magium\Mail\Webmail\Messages;
class WebmailTest extends AbstractTestCase
{
protected $subjectContains = '<subject contains something>';
protected $recipient = '<magium mail recipient';
protected $subjectEquals = '<full subject >';
public function setUp()
{
self::markTestSkipped('This test requires individual configuration');
parent::setUp();
}
public function testNavigateByNumber()
{
$messages = $this->get(Messages::LOCATOR);
/* @var $messages Messages */
$messages->open();
$message = $messages->getMessage();
self::assertNotNull($message->getSubject());
$message = $messages->getMessage(2);
self::assertNotNull($message->getSubject());
}
public function testNavigateSubjectContains()
{
$messages = $this->get(Messages::LOCATOR);
/* @var $messages Messages */
$messages->open();
$message = $messages->getMessageWithSubjectContains($this->subjectContains);
self::assertNotNull($message->getSubject());
}
public function testNavigateSubjectEquals()
{
$messages = $this->get(Messages::LOCATOR);
/* @var $messages Messages */
$messages->open();
$message = $messages->getMessageWithSubject($this->subjectEquals);
self::assertNotNull($message->getSubject());
}
public function testNavigateSubjectContainsAndRecipient()
{
$messages = $this->get(Messages::LOCATOR);
/* @var $messages Messages */
$messages->open();
$message = $messages->getMessageWithSubjectContains($this->subjectContains, 1, $this->recipient);
self::assertNotNull($message->getSubject());
}
public function testNavigateSubjectEqualsAndRecipient()
{
$messages = $this->get(Messages::LOCATOR);
/* @var $messages Messages */
$messages->open();
$message = $messages->getMessageWithSubject($this->subjectEquals, 1, $this->recipient);
self::assertNotNull($message->getSubject());
}
public function testNavigateSubjectContainsAndInvalidRecipientDoesNotDisplay()
{
$messages = $this->get(Messages::LOCATOR);
/* @var $messages Messages */
$messages->open();
$message = $messages->getMessageWithSubjectContains($this->subjectContains, 1, 'nobody');
self::assertNull($message);
}
} | magium/MagiumMail | tests/Webmail/WebmailTest.php | PHP | apache-2.0 | 2,480 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# File: common.py
# Author: Yuxin Wu <[email protected]>
import random
import time
import threading
import multiprocessing
import numpy as np
from tqdm import tqdm
from six.moves import queue
from tensorpack import *
from tensorpack.utils.concurrency import *
from tensorpack.utils.stats import *
def play_one_episode(player, func, verbose=False):
def f(s):
spc = player.get_action_space()
act = func([[s]])[0][0].argmax()
if random.random() < 0.001:
act = spc.sample()
if verbose:
print(act)
return act
return np.mean(player.play_one_episode(f))
def play_model(cfg, player):
predfunc = OfflinePredictor(cfg)
while True:
score = play_one_episode(player, predfunc)
print("Total:", score)
def eval_with_funcs(predictors, nr_eval, get_player_fn):
class Worker(StoppableThread, ShareSessionThread):
def __init__(self, func, queue):
super(Worker, self).__init__()
self._func = func
self.q = queue
def func(self, *args, **kwargs):
if self.stopped():
raise RuntimeError("stopped!")
return self._func(*args, **kwargs)
def run(self):
with self.default_sess():
player = get_player_fn(train=False)
while not self.stopped():
try:
score = play_one_episode(player, self.func)
# print("Score, ", score)
except RuntimeError:
return
self.queue_put_stoppable(self.q, score)
q = queue.Queue()
threads = [Worker(f, q) for f in predictors]
for k in threads:
k.start()
time.sleep(0.1) # avoid simulator bugs
stat = StatCounter()
try:
for _ in tqdm(range(nr_eval), **get_tqdm_kwargs()):
r = q.get()
stat.feed(r)
logger.info("Waiting for all the workers to finish the last run...")
for k in threads:
k.stop()
for k in threads:
k.join()
while q.qsize():
r = q.get()
stat.feed(r)
except:
logger.exception("Eval")
finally:
if stat.count > 0:
return (stat.average, stat.max)
return (0, 0)
def eval_model_multithread(cfg, nr_eval, get_player_fn):
func = OfflinePredictor(cfg)
NR_PROC = min(multiprocessing.cpu_count() // 2, 8)
mean, max = eval_with_funcs([func] * NR_PROC, nr_eval, get_player_fn)
logger.info("Average Score: {}; Max Score: {}".format(mean, max))
class Evaluator(Triggerable):
def __init__(self, nr_eval, input_names, output_names, get_player_fn):
self.eval_episode = nr_eval
self.input_names = input_names
self.output_names = output_names
self.get_player_fn = get_player_fn
def _setup_graph(self):
NR_PROC = min(multiprocessing.cpu_count() // 2, 20)
self.pred_funcs = [self.trainer.get_predictor(
self.input_names, self.output_names)] * NR_PROC
def _trigger(self):
t = time.time()
mean, max = eval_with_funcs(
self.pred_funcs, self.eval_episode, self.get_player_fn)
t = time.time() - t
if t > 10 * 60: # eval takes too long
self.eval_episode = int(self.eval_episode * 0.94)
self.trainer.monitors.put_scalar('mean_score', mean)
self.trainer.monitors.put_scalar('max_score', max)
def play_n_episodes(player, predfunc, nr):
logger.info("Start evaluation: ")
for k in range(nr):
if k != 0:
player.restart_episode()
score = play_one_episode(player, predfunc)
print("{}/{}, score={}".format(k, nr, score))
| haamoon/tensorpack | examples/DeepQNetwork/common.py | Python | apache-2.0 | 3,829 |
#ifndef dynamic_array_h
#define dynamic_array_h
#include <stdlib.h>
#include "dynamic_array.c"
struct dynamic_array {
uint32_t size;
uint32_t expansion_factor;
void ** array;
};
int da_precise_create (struct dynamic_array * ar, uint32_t init_size, uint32_t expansion_factor);
int da_create (struct dynamic_array * ar);
int64_t da_add(struct dynamic_array * ar, void * val);
void da_delete(struct dynamic_array * ar);
#endif | TelluIoT/ThingML | compilers/c/src/main/resources/cutilities/dynamic_array.h | C | apache-2.0 | 434 |
package org.devocative.demeter.service.template;
import groovy.lang.Binding;
import groovy.lang.Script;
import org.devocative.demeter.iservice.template.BaseStringTemplate;
import java.util.Map;
public class GroovyScript extends BaseStringTemplate<Script> {
private Script script;
public GroovyScript(Script script) {
this.script = script;
}
@Override
public Object process(Map<String, Object> params) {
Binding binding = new Binding();
for (Map.Entry<String, Object> entry : params.entrySet()) {
binding.setVariable(entry.getKey(), entry.getValue());
}
script.setBinding(binding);
return script.run();
}
@Override
public Script unwrap() {
return script;
}
}
| mbizhani/Demeter | service/src/main/java/org/devocative/demeter/service/template/GroovyScript.java | Java | apache-2.0 | 690 |
/**
*
* ThingBench - Things and Devices Simulator
*
* http://github.com/frapu78/thingbench
*
* @author Frank Puhlmann
*
*/
package thingbench;
import java.util.HashMap;
import net.frapu.code.visualization.ProcessNode;
/**
* This class provides an operation on a thing.
*
* @author fpu
*/
public abstract class ThingOperation {
private ProcessNode thingNode;
private String operationName;
public ThingOperation(ProcessNode thingNode, String operationName) {
this.thingNode = thingNode;
this.operationName = operationName;
}
public ProcessNode getThingNode() {
return thingNode;
}
public String getOperationName() {
return operationName;
}
/**
* This class executes the Operation. Each operation has a set of properties
* of the type <String, String> as input and output. What the operation
* does with it remains to the operation.
* @param properties
* @return
* @throws thingbench.ThingExecutionException
*/
public abstract HashMap<String, String> execute(HashMap<String, String> properties) throws ThingExecutionException;
}
| frapu78/thingbench | src/thingbench/ThingOperation.java | Java | apache-2.0 | 1,167 |
package lan.dk.podcastserver.manager.worker.selector;
import lan.dk.podcastserver.manager.worker.selector.update.*;
import lan.dk.podcastserver.manager.worker.updater.*;
import org.junit.Before;
import org.junit.Test;
import java.util.HashSet;
import java.util.Set;
import static org.assertj.core.api.Assertions.assertThat;
public class UpdaterSelectorTest {
Set<UpdaterCompatibility> updaterSelectors = new HashSet<>();
@Before
public void setUp() throws Exception {
updaterSelectors.add(new YoutubeUpdaterCompatibility());
updaterSelectors.add(new RssUpdaterCompatibility());
updaterSelectors.add(new BeInSportUpdaterCompatibility());
updaterSelectors.add(new CanalPlusUpdaterCompatibility());
updaterSelectors.add(new JeuxVideoFrCompatibility());
updaterSelectors.add(new JeuxVideoComCompatibility());
updaterSelectors.add(new ParleysCompatibility());
updaterSelectors.add(new PluzzCompatibility());
}
@Test
public void should_return_an_RssUpdater () {
/* Given */ UpdaterSelector updaterSelector = new UpdaterSelector().setUpdaterCompatibilities(updaterSelectors);
/* When */ Class updaterClass = updaterSelector.of("www.link.to.rss/feeds");
/* Then */ assertThat(updaterClass).isEqualTo(RSSUpdater.class);
}
@Test
public void should_return_a_YoutubeUpdater () {
/* Given */ UpdaterSelector updaterSelector = new UpdaterSelector().setUpdaterCompatibilities(updaterSelectors);
/* When */ Class updaterClass = updaterSelector.of("http://www.youtube.com/user/fakeUser");
/* Then */ assertThat(updaterClass).isEqualTo(YoutubeUpdater.class);
}
@Test
public void should_return_a_BeInSportUpdater () {
/* Given */ UpdaterSelector updaterSelector = new UpdaterSelector().setUpdaterCompatibilities(updaterSelectors);
/* When */ Class updaterClass = updaterSelector.of("http://www.beinsports.fr/replay/category/3361/name/lexpresso");
/* Then */ assertThat(updaterClass).isEqualTo(BeInSportsUpdater.class);
}
@Test
public void should_return_a_CanalPlusUpdater() {
/* Given */ UpdaterSelector updaterSelector = new UpdaterSelector().setUpdaterCompatibilities(updaterSelectors);
/* When */ Class updaterClass = updaterSelector.of("http://www.canalplus.fr/show/for/dummies");
/* Then */ assertThat(updaterClass).isEqualTo(CanalPlusUpdater.class);
}
@Test
public void should_return_a_JeuxVideoFrUpdater() {
/* Given */ UpdaterSelector updaterSelector = new UpdaterSelector().setUpdaterCompatibilities(updaterSelectors);
/* When */ Class updaterClass = updaterSelector.of("http://www.jeuxvideo.fr/show/for/dummies");
/* Then */ assertThat(updaterClass).isEqualTo(JeuxVideoFRUpdater.class);
}
@Test
public void should_return_a_JeuxVideoComUpdater() {
/* Given */ UpdaterSelector updaterSelector = new UpdaterSelector().setUpdaterCompatibilities(updaterSelectors);
/* When */ Class updaterClass = updaterSelector.of("http://www.jeuxvideo.com/show/for/dummies");
/* Then */ assertThat(updaterClass).isEqualTo(JeuxVideoComUpdater.class);
}
@Test
public void should_return_a_ParleysUpdater() {
/* Given */ UpdaterSelector updaterSelector = new UpdaterSelector().setUpdaterCompatibilities(updaterSelectors);
/* When */ Class updaterClass = updaterSelector.of("http://www.parleys.com/show/for/dummies");
/* Then */ assertThat(updaterClass).isEqualTo(ParleysUpdater.class);
}
@Test
public void should_return_a_PluzzUpdater() {
/* Given */ UpdaterSelector updaterSelector = new UpdaterSelector().setUpdaterCompatibilities(updaterSelectors);
/* When */ Class updaterClass = updaterSelector.of("http://www.pluzz.francetv.fr/show/for/dummies");
/* Then */ assertThat(updaterClass).isEqualTo(PluzzUpdater.class);
}
@Test(expected = RuntimeException.class)
public void should_reject_empty_url() {
/* Given */ UpdaterSelector updaterSelector = new UpdaterSelector().setUpdaterCompatibilities(updaterSelectors);
/* When */ updaterSelector.of("");
}
} | radut/Podcast-Server | src/test/java/lan/dk/podcastserver/manager/worker/selector/UpdaterSelectorTest.java | Java | apache-2.0 | 4,263 |
// Code generated by msgraph.go/gen DO NOT EDIT.
package msgraph
import "context"
//
type WorkbookFunctionsTanRequestBuilder struct{ BaseRequestBuilder }
// Tan action undocumented
func (b *WorkbookFunctionsRequestBuilder) Tan(reqObj *WorkbookFunctionsTanRequestParameter) *WorkbookFunctionsTanRequestBuilder {
bb := &WorkbookFunctionsTanRequestBuilder{BaseRequestBuilder: b.BaseRequestBuilder}
bb.BaseRequestBuilder.baseURL += "/tan"
bb.BaseRequestBuilder.requestObject = reqObj
return bb
}
//
type WorkbookFunctionsTanRequest struct{ BaseRequest }
//
func (b *WorkbookFunctionsTanRequestBuilder) Request() *WorkbookFunctionsTanRequest {
return &WorkbookFunctionsTanRequest{
BaseRequest: BaseRequest{baseURL: b.baseURL, client: b.client, requestObject: b.requestObject},
}
}
//
func (r *WorkbookFunctionsTanRequest) Post(ctx context.Context) (resObj *WorkbookFunctionResult, err error) {
err = r.JSONRequest(ctx, "POST", "", r.requestObject, &resObj)
return
}
| 42wim/matterbridge | vendor/github.com/yaegashi/msgraph.go/beta/RequestWorkbookFunctionsTan.go | GO | apache-2.0 | 978 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.4.2_11) on Sun Oct 15 22:02:30 CDT 2006 -->
<TITLE>
Overview (Hibernate API Documentation)
</TITLE>
<META NAME="keywords" CONTENT="Overview, Hibernate API Documentation (3.2.0.ga)">
<LINK REL ="stylesheet" TYPE="text/css" HREF="jdstyle.css" TITLE="Style">
</HEAD>
<BODY BGCOLOR="white">
<TABLE BORDER="0" WIDTH="100%" SUMMARY="">
<TR>
<TD NOWRAP><FONT size="+1" CLASS="FrameTitleFont">
<B></B></FONT></TD>
</TR>
</TABLE>
<TABLE BORDER="0" WIDTH="100%" SUMMARY="">
<TR>
<TD NOWRAP><FONT CLASS="FrameItemFont"><A HREF="allclasses-frame.html" target="packageFrame">All Classes</A></FONT>
<P>
<FONT size="+1" CLASS="FrameHeadingFont">
Packages</FONT>
<BR>
<FONT CLASS="FrameItemFont"><A HREF="org/hibernate/package-frame.html" target="packageFrame">org.hibernate</A></FONT>
<BR>
<FONT CLASS="FrameItemFont"><A HREF="org/hibernate/action/package-frame.html" target="packageFrame">org.hibernate.action</A></FONT>
<BR>
<FONT CLASS="FrameItemFont"><A HREF="org/hibernate/bytecode/package-frame.html" target="packageFrame">org.hibernate.bytecode</A></FONT>
<BR>
<FONT CLASS="FrameItemFont"><A HREF="org/hibernate/bytecode/cglib/package-frame.html" target="packageFrame">org.hibernate.bytecode.cglib</A></FONT>
<BR>
<FONT CLASS="FrameItemFont"><A HREF="org/hibernate/bytecode/javassist/package-frame.html" target="packageFrame">org.hibernate.bytecode.javassist</A></FONT>
<BR>
<FONT CLASS="FrameItemFont"><A HREF="org/hibernate/bytecode/util/package-frame.html" target="packageFrame">org.hibernate.bytecode.util</A></FONT>
<BR>
<FONT CLASS="FrameItemFont"><A HREF="org/hibernate/cache/package-frame.html" target="packageFrame">org.hibernate.cache</A></FONT>
<BR>
<FONT CLASS="FrameItemFont"><A HREF="org/hibernate/cache/entry/package-frame.html" target="packageFrame">org.hibernate.cache.entry</A></FONT>
<BR>
<FONT CLASS="FrameItemFont"><A HREF="org/hibernate/cfg/package-frame.html" target="packageFrame">org.hibernate.cfg</A></FONT>
<BR>
<FONT CLASS="FrameItemFont"><A HREF="org/hibernate/classic/package-frame.html" target="packageFrame">org.hibernate.classic</A></FONT>
<BR>
<FONT CLASS="FrameItemFont"><A HREF="org/hibernate/collection/package-frame.html" target="packageFrame">org.hibernate.collection</A></FONT>
<BR>
<FONT CLASS="FrameItemFont"><A HREF="org/hibernate/connection/package-frame.html" target="packageFrame">org.hibernate.connection</A></FONT>
<BR>
<FONT CLASS="FrameItemFont"><A HREF="org/hibernate/context/package-frame.html" target="packageFrame">org.hibernate.context</A></FONT>
<BR>
<FONT CLASS="FrameItemFont"><A HREF="org/hibernate/criterion/package-frame.html" target="packageFrame">org.hibernate.criterion</A></FONT>
<BR>
<FONT CLASS="FrameItemFont"><A HREF="org/hibernate/dialect/package-frame.html" target="packageFrame">org.hibernate.dialect</A></FONT>
<BR>
<FONT CLASS="FrameItemFont"><A HREF="org/hibernate/dialect/function/package-frame.html" target="packageFrame">org.hibernate.dialect.function</A></FONT>
<BR>
<FONT CLASS="FrameItemFont"><A HREF="org/hibernate/dialect/lock/package-frame.html" target="packageFrame">org.hibernate.dialect.lock</A></FONT>
<BR>
<FONT CLASS="FrameItemFont"><A HREF="org/hibernate/engine/package-frame.html" target="packageFrame">org.hibernate.engine</A></FONT>
<BR>
<FONT CLASS="FrameItemFont"><A HREF="org/hibernate/engine/query/package-frame.html" target="packageFrame">org.hibernate.engine.query</A></FONT>
<BR>
<FONT CLASS="FrameItemFont"><A HREF="org/hibernate/engine/query/sql/package-frame.html" target="packageFrame">org.hibernate.engine.query.sql</A></FONT>
<BR>
<FONT CLASS="FrameItemFont"><A HREF="org/hibernate/engine/transaction/package-frame.html" target="packageFrame">org.hibernate.engine.transaction</A></FONT>
<BR>
<FONT CLASS="FrameItemFont"><A HREF="org/hibernate/event/package-frame.html" target="packageFrame">org.hibernate.event</A></FONT>
<BR>
<FONT CLASS="FrameItemFont"><A HREF="org/hibernate/event/def/package-frame.html" target="packageFrame">org.hibernate.event.def</A></FONT>
<BR>
<FONT CLASS="FrameItemFont"><A HREF="org/hibernate/exception/package-frame.html" target="packageFrame">org.hibernate.exception</A></FONT>
<BR>
<FONT CLASS="FrameItemFont"><A HREF="org/hibernate/hql/package-frame.html" target="packageFrame">org.hibernate.hql</A></FONT>
<BR>
<FONT CLASS="FrameItemFont"><A HREF="org/hibernate/hql/antlr/package-frame.html" target="packageFrame">org.hibernate.hql.antlr</A></FONT>
<BR>
<FONT CLASS="FrameItemFont"><A HREF="org/hibernate/hql/ast/package-frame.html" target="packageFrame">org.hibernate.hql.ast</A></FONT>
<BR>
<FONT CLASS="FrameItemFont"><A HREF="org/hibernate/hql/ast/exec/package-frame.html" target="packageFrame">org.hibernate.hql.ast.exec</A></FONT>
<BR>
<FONT CLASS="FrameItemFont"><A HREF="org/hibernate/hql/ast/tree/package-frame.html" target="packageFrame">org.hibernate.hql.ast.tree</A></FONT>
<BR>
<FONT CLASS="FrameItemFont"><A HREF="org/hibernate/hql/ast/util/package-frame.html" target="packageFrame">org.hibernate.hql.ast.util</A></FONT>
<BR>
<FONT CLASS="FrameItemFont"><A HREF="org/hibernate/hql/classic/package-frame.html" target="packageFrame">org.hibernate.hql.classic</A></FONT>
<BR>
<FONT CLASS="FrameItemFont"><A HREF="org/hibernate/id/package-frame.html" target="packageFrame">org.hibernate.id</A></FONT>
<BR>
<FONT CLASS="FrameItemFont"><A HREF="org/hibernate/id/insert/package-frame.html" target="packageFrame">org.hibernate.id.insert</A></FONT>
<BR>
<FONT CLASS="FrameItemFont"><A HREF="org/hibernate/impl/package-frame.html" target="packageFrame">org.hibernate.impl</A></FONT>
<BR>
<FONT CLASS="FrameItemFont"><A HREF="org/hibernate/intercept/package-frame.html" target="packageFrame">org.hibernate.intercept</A></FONT>
<BR>
<FONT CLASS="FrameItemFont"><A HREF="org/hibernate/intercept/cglib/package-frame.html" target="packageFrame">org.hibernate.intercept.cglib</A></FONT>
<BR>
<FONT CLASS="FrameItemFont"><A HREF="org/hibernate/intercept/javassist/package-frame.html" target="packageFrame">org.hibernate.intercept.javassist</A></FONT>
<BR>
<FONT CLASS="FrameItemFont"><A HREF="org/hibernate/jdbc/package-frame.html" target="packageFrame">org.hibernate.jdbc</A></FONT>
<BR>
<FONT CLASS="FrameItemFont"><A HREF="org/hibernate/jmx/package-frame.html" target="packageFrame">org.hibernate.jmx</A></FONT>
<BR>
<FONT CLASS="FrameItemFont"><A HREF="org/hibernate/loader/package-frame.html" target="packageFrame">org.hibernate.loader</A></FONT>
<BR>
<FONT CLASS="FrameItemFont"><A HREF="org/hibernate/loader/collection/package-frame.html" target="packageFrame">org.hibernate.loader.collection</A></FONT>
<BR>
<FONT CLASS="FrameItemFont"><A HREF="org/hibernate/loader/criteria/package-frame.html" target="packageFrame">org.hibernate.loader.criteria</A></FONT>
<BR>
<FONT CLASS="FrameItemFont"><A HREF="org/hibernate/loader/custom/package-frame.html" target="packageFrame">org.hibernate.loader.custom</A></FONT>
<BR>
<FONT CLASS="FrameItemFont"><A HREF="org/hibernate/loader/custom/sql/package-frame.html" target="packageFrame">org.hibernate.loader.custom.sql</A></FONT>
<BR>
<FONT CLASS="FrameItemFont"><A HREF="org/hibernate/loader/entity/package-frame.html" target="packageFrame">org.hibernate.loader.entity</A></FONT>
<BR>
<FONT CLASS="FrameItemFont"><A HREF="org/hibernate/loader/hql/package-frame.html" target="packageFrame">org.hibernate.loader.hql</A></FONT>
<BR>
<FONT CLASS="FrameItemFont"><A HREF="org/hibernate/lob/package-frame.html" target="packageFrame">org.hibernate.lob</A></FONT>
<BR>
<FONT CLASS="FrameItemFont"><A HREF="org/hibernate/mapping/package-frame.html" target="packageFrame">org.hibernate.mapping</A></FONT>
<BR>
<FONT CLASS="FrameItemFont"><A HREF="org/hibernate/metadata/package-frame.html" target="packageFrame">org.hibernate.metadata</A></FONT>
<BR>
<FONT CLASS="FrameItemFont"><A HREF="org/hibernate/param/package-frame.html" target="packageFrame">org.hibernate.param</A></FONT>
<BR>
<FONT CLASS="FrameItemFont"><A HREF="org/hibernate/persister/package-frame.html" target="packageFrame">org.hibernate.persister</A></FONT>
<BR>
<FONT CLASS="FrameItemFont"><A HREF="org/hibernate/persister/collection/package-frame.html" target="packageFrame">org.hibernate.persister.collection</A></FONT>
<BR>
<FONT CLASS="FrameItemFont"><A HREF="org/hibernate/persister/entity/package-frame.html" target="packageFrame">org.hibernate.persister.entity</A></FONT>
<BR>
<FONT CLASS="FrameItemFont"><A HREF="org/hibernate/pretty/package-frame.html" target="packageFrame">org.hibernate.pretty</A></FONT>
<BR>
<FONT CLASS="FrameItemFont"><A HREF="org/hibernate/property/package-frame.html" target="packageFrame">org.hibernate.property</A></FONT>
<BR>
<FONT CLASS="FrameItemFont"><A HREF="org/hibernate/proxy/package-frame.html" target="packageFrame">org.hibernate.proxy</A></FONT>
<BR>
<FONT CLASS="FrameItemFont"><A HREF="org/hibernate/proxy/dom4j/package-frame.html" target="packageFrame">org.hibernate.proxy.dom4j</A></FONT>
<BR>
<FONT CLASS="FrameItemFont"><A HREF="org/hibernate/proxy/map/package-frame.html" target="packageFrame">org.hibernate.proxy.map</A></FONT>
<BR>
<FONT CLASS="FrameItemFont"><A HREF="org/hibernate/proxy/pojo/package-frame.html" target="packageFrame">org.hibernate.proxy.pojo</A></FONT>
<BR>
<FONT CLASS="FrameItemFont"><A HREF="org/hibernate/proxy/pojo/cglib/package-frame.html" target="packageFrame">org.hibernate.proxy.pojo.cglib</A></FONT>
<BR>
<FONT CLASS="FrameItemFont"><A HREF="org/hibernate/proxy/pojo/javassist/package-frame.html" target="packageFrame">org.hibernate.proxy.pojo.javassist</A></FONT>
<BR>
<FONT CLASS="FrameItemFont"><A HREF="org/hibernate/secure/package-frame.html" target="packageFrame">org.hibernate.secure</A></FONT>
<BR>
<FONT CLASS="FrameItemFont"><A HREF="org/hibernate/sql/package-frame.html" target="packageFrame">org.hibernate.sql</A></FONT>
<BR>
<FONT CLASS="FrameItemFont"><A HREF="org/hibernate/stat/package-frame.html" target="packageFrame">org.hibernate.stat</A></FONT>
<BR>
<FONT CLASS="FrameItemFont"><A HREF="org/hibernate/tool/hbm2ddl/package-frame.html" target="packageFrame">org.hibernate.tool.hbm2ddl</A></FONT>
<BR>
<FONT CLASS="FrameItemFont"><A HREF="org/hibernate/tool/instrument/package-frame.html" target="packageFrame">org.hibernate.tool.instrument</A></FONT>
<BR>
<FONT CLASS="FrameItemFont"><A HREF="org/hibernate/tool/instrument/cglib/package-frame.html" target="packageFrame">org.hibernate.tool.instrument.cglib</A></FONT>
<BR>
<FONT CLASS="FrameItemFont"><A HREF="org/hibernate/tool/instrument/javassist/package-frame.html" target="packageFrame">org.hibernate.tool.instrument.javassist</A></FONT>
<BR>
<FONT CLASS="FrameItemFont"><A HREF="org/hibernate/transaction/package-frame.html" target="packageFrame">org.hibernate.transaction</A></FONT>
<BR>
<FONT CLASS="FrameItemFont"><A HREF="org/hibernate/transform/package-frame.html" target="packageFrame">org.hibernate.transform</A></FONT>
<BR>
<FONT CLASS="FrameItemFont"><A HREF="org/hibernate/tuple/package-frame.html" target="packageFrame">org.hibernate.tuple</A></FONT>
<BR>
<FONT CLASS="FrameItemFont"><A HREF="org/hibernate/tuple/component/package-frame.html" target="packageFrame">org.hibernate.tuple.component</A></FONT>
<BR>
<FONT CLASS="FrameItemFont"><A HREF="org/hibernate/tuple/entity/package-frame.html" target="packageFrame">org.hibernate.tuple.entity</A></FONT>
<BR>
<FONT CLASS="FrameItemFont"><A HREF="org/hibernate/type/package-frame.html" target="packageFrame">org.hibernate.type</A></FONT>
<BR>
<FONT CLASS="FrameItemFont"><A HREF="org/hibernate/usertype/package-frame.html" target="packageFrame">org.hibernate.usertype</A></FONT>
<BR>
<FONT CLASS="FrameItemFont"><A HREF="org/hibernate/util/package-frame.html" target="packageFrame">org.hibernate.util</A></FONT>
<BR>
</TD>
</TR>
</TABLE>
<P>
</BODY>
</HTML>
| renmeng8875/projects | Hibernate-source/源代码及重要说明/Hibernate相关资料/hibernate-3.2.0.ga/hibernate-3.2/doc/api/overview-frame.html | HTML | apache-2.0 | 11,893 |
import optparse
import pickle
#converts urls to wiki_id
parser = optparse.OptionParser()
parser.add_option('-i','--input', dest = 'input_file', help = 'input_file')
parser.add_option('-o','--output', dest = 'output_file', help = 'output_file')
(options, args) = parser.parse_args()
if options.input_file is None:
options.input_file = raw_input('Enter input file:')
if options.output_file is None:
options.output_file = raw_input('Enter output file:')
input_file = options.input_file
output_file = options.output_file
#define the dictionary url:wiki_id
wiki_from_url_dict = {}
with open('../../datasets/dbpedia/page_ids_en_2016.ttl','r') as f:
for line in f:
line = line.split(' ')
if line[0] == '#':
continue
url = line[0]
wiki_id_list = line[2].split('\"')
wiki_id = wiki_id_list[1]
print(url, wiki_id)
wiki_from_url_dict[url] = int(wiki_id)
output_file_write = open(output_file,'w')
#iterate through the page links and turn urls into wiki_ids
max_wiki_id = max(wiki_from_url_dict.values()) + 1
local_id = {}
count = 0
with open(input_file) as page_links:
for line in page_links:
line = line.split(' ')
if line[0] == '#':
continue
url_1 = line[0]
url_2 = line[2]
#if wiki_id not found, assign an id = max_wiki_id and increment max_wiki_id
try:
wiki_id1 = wiki_from_url_dict[url_1] #first entity has wiki_id
try:
wiki_id2 = wiki_from_url_dict[url_2] #first and second entities have wiki_ids
except (KeyError, IndexError): #first entity has wiki_id, second entity doesn't
try: #check if a local id has already been assigned
wiki_id2 = local_id[url_2]
except (KeyError, IndexError):
wiki_id2 = max_wiki_id
local_id[url_2] = wiki_id2
max_wiki_id +=1
except (KeyError, IndexError): #first entity doesn't have wiki_id
try:
wiki_id1 = local_id[url_1]
except (KeyError, IndexError):
wiki_id1 = max_wiki_id
local_id[url_1] = wiki_id1
max_wiki_id += 1
try: #first entity doesn't have wiki_id, second entity has it
wiki_id2 = wiki_from_url_dict[url_2]
except (KeyError, IndexError): #neither first nor second entity have wiki_ids
try: #check if a local id has already been assigned
wiki_id2 = local_id[url_2]
except (KeyError, IndexError):
wiki_id2 = max_wiki_id
local_id[url_2] = wiki_id2
max_wiki_id +=1
output_file_write.write('%d %d\n' %(wiki_id1,wiki_id2))
print count
count += 1
output_file_write.close()
pickle.dump(local_id,open('../../datasets/dbpedia/local_id_to_url_full_mapping_based.p','wb'))
| MultimediaSemantics/entity2vec | scripts/old/page_links_to_edge_list_wiki.py | Python | apache-2.0 | 3,039 |
/*
* #%L
* fujion
* %%
* Copyright (C) 2021 Fujion Framework
* %%
* 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 org.fujion.highcharts;
import org.fujion.ancillary.OptionMap;
import org.fujion.ancillary.Options;
import org.fujion.annotation.Option;
import java.util.ArrayList;
import java.util.List;
/**
* Base class for all plot types.
* <p>
* PlotOptions is a wrapper for config objects for each series type. The config objects for each
* series can also be overridden for each series item as given in the series array. Configuration
* options for the series are given in three levels. Options for all series in a chart are given in
* the plotOptions.series object. Then options for all series of a specific type are given in the
* plotOptions of that type, for example plotOptions.line. Next, options for one single series are
* given in the series array.
*/
public abstract class PlotOptions extends Options {
/**
* The text identifier of the plot type.
*/
@Option(ignore = true)
protected String type;
/**
* Allow this series' points to be selected by clicking on the markers, bars or pie slices.
* Defaults to false.
*/
@Option
public Boolean allowPointSelect;
/**
* Enable or disable the initial animation when a series is displayed. Since version 2.1, the
* animation can be set as a configuration object. Please note that this option only applies to
* the initial animation of the series itself. For other animations, see #chart.animation and
* the animation parameter under the API methods.
*/
@Option
public final AnimationOptions animation = new AnimationOptions();
/**
* For some series, there is a limit that shuts down initial animation by default when the total
* number of points in the chart is too high. For example, for a column chart and its
* derivatives, animation doesn't run if there is more than 250 points totally. To disable this
* cap, set animationLimit to Infinity.
*/
@Option
public Integer animationLimit;
/**
* Set the point threshold for when a series should enter boost mode. Setting it to e.g. 2000
* will cause the series to enter boost mode when there are 2000 or more points in the series.
* To disable boosting on the series, set the boostThreshold to 0. Setting it to 1 will force
* boosting. Requires modules/boost.js.
*/
@Option
public Integer boostThreshold;
/**
* A CSS class name to apply to the series' graphical elements.
*/
@Option
public String className;
/**
* The main color or the series. In line type series it applies to the line and the point
* markers unless otherwise specified. In bar type series it applies to the bars unless a color
* is specified per point. The default value is pulled from the options.colors array.
*/
@Option
public String color;
/**
* Styled mode only. A specific color index to use for the series, so its graphic
* representations are given the class name highcharts-color-{n}. Defaults to undefined.
*/
@Option
public Integer colorIndex;
/**
* When using automatic point colors pulled from the options.colors collection, this option
* determines whether the chart should receive one color per series or one color per point.
* Defaults to false.
*/
@Option
public Boolean colorByPoint;
/**
* A series specific or series type specific color set to apply instead of the global colors
* when colorByPoint is true.
*/
@Option
public List<String> colors = new ArrayList<>();
/**
* Polar charts only. Whether to connect the ends of a line series plot across the extremes.
* Defaults to true.
*/
@Option
public Boolean connectEnds;
/**
* Whether to connect a graph line across null points. Defaults to false.
*/
@Option
public Boolean connectNulls;
/**
* When the series contains less points than the crop threshold, all points are drawn, event if
* the points fall outside the visible plot area at the current zoom. The advantage of drawing
* all points (including markers and columns), is that animation is performed on updates. On the
* other hand, when the series contains more points than the crop threshold, the series data is
* cropped to only contain points that fall within the plot area. The advantage of cropping away
* invisible points is to increase performance on large series. . Defaults to 300.
*/
@Option
public Double cropThreshold;
/**
* You can set the cursor to "pointer" if you have click events attached to the series, to
* signal to the user that the points and lines can be clicked. Defaults to ''.
*/
@Option
public String cursor;
/**
* A name for the dash style to use for the graph. Applies only to series type having a graph,
* like line, spline, area and scatter in case it has a lineWidth. The value for the dashStyle
* include:
* <ul>
* <li>Solid</li>
* <li>ShortDash</li>
* <li>ShortDot</li>
* <li>ShortDashDot</li>
* <li>ShortDashDotDot</li>
* <li>Dot</li>
* <li>Dash</li>
* <li>LongDash</li>
* <li>DashDot</li>
* <li>LongDashDot</li>
* <li>LongDashDotDot</li>
* </ul>
* Defaults to null.
*/
@Option
public DashStyle dashStyle;
/**
* Options for data labels.
*
* @see DataLabelOptions
*/
@Option
public final DataLabelOptions dataLabels = new DataLabelOptions();
/**
* Requires the Accessibility module. A description of the series to add to the screen reader
* information about the series. Defaults to undefined.
*/
@Option
public String description;
/**
* Enable or disable the mouse tracking for a specific series. This includes point tooltips and
* click events on graphs and points. For large datasets it improves performance. Defaults to
* true.
*/
@Option
public Boolean enableMouseTracking;
/**
* Requires the Accessibility module. By default, series are exposed to screen readers as
* regions. By enabling this option, the series element itself will be exposed in the same way
* as the data points. This is useful if the series is not used as a grouping entity in the
* chart, but you still want to attach a description to the series. Defaults to undefined.
*/
@Option
public Boolean exposeElementToA11y;
/**
* Determines whether the series should look for the nearest point in both dimensions or just
* the x-dimension when hovering the series. Defaults to 'xy' for scatter series and 'x' for
* most other series. If the data has duplicate x-values, it is recommended to set this to 'xy'
* to allow hovering over all points. Applies only to series types using nearest neighbor search
* (not direct hover) for tooltip. Defaults to x.
*/
@Option
public String findNearestPointBy;
/**
* Whether to use the Y extremes of the total chart width or only the zoomed area when zooming
* in on parts of the X axis. By default, the Y axis adjusts to the min and max of the visible
* data. Cartesian series only. Defaults to false.
*/
@Option
public Boolean getExtremesFromAll;
/**
* An id for the series. Defaults to null.
*/
@Option
public String id;
/**
* An array specifying which option maps to which key in the data point array. This makes it
* convenient to work with unstructured data arrays from different sources. Defaults to
* undefined.
*/
@Option
public final List<String> keys = new ArrayList<>();
/**
* Text labels for the plot bands.
*/
@Option
public final PlotLabelOptions label = new PlotLabelOptions();
/**
* The line cap used for line ends and line joins on the graph. Defaults to round.
*/
@Option
public String linecap;
/**
* Pixel with of the graph line. Defaults to 2.
*/
@Option
public Integer lineWidth;
/**
* The id of another series to link to. Additionally, the value can be ":previous" to link to
* the previous series. When two series are linked, only the first one appears in the legend.
* Toggling the visibility of this also toggles the linked series.
*/
@Option
public String linkedTo;
/**
* Options for point markers.
*
* @see MarkerOptions
*/
@Option
public final MarkerOptions marker = new MarkerOptions();
/**
* The color for the parts of the graph or points that are below the threshold. Defaults to
* null.
*/
@Option
public String negativeColor;
/**
* If no x values are given for the points in a series, pointInterval defines the interval of
* the x values. For example, if a series contains one value every decade starting from year 0,
* set pointInterval to 10. Defaults to 1.
*/
@Option
public Double pointInterval;
/**
* On datetime series, this allows for setting the pointInterval to irregular time units, day,
* month and year. A day is usually the same as 24 hours, but pointIntervalUnit also takes the
* DST crossover into consideration when dealing with local time. Combine this option with
* pointInterval to draw weeks, quarters, 6 months, 10 years etc. Please note that this options
* applies to the series data, not the interval of the axis ticks, which is independent.
* Defaults to undefined.
*/
@Option
public String pointIntervalUnit;
/**
* Possible values: null, "on", "between". In a column chart, when pointPlacement is "on", the
* point will not create any padding of the X axis. In a polar column chart this means that the
* first column points directly north. If the pointPlacement is "between", the columns will be
* laid out between ticks. This is useful for example for visualising an amount between two
* points in time or in a certain sector of a polar chart. Defaults to null in cartesian charts,
* "between" in polar charts.
*/
@Option
public String pointPlacement;
/**
* If no x values are given for the points in a series, pointStart defines on what value to
* start. For example, if a series contains one yearly value starting from 1945, set pointStart
* to 1945. Defaults to 0.
*/
@Option
public Double pointStart;
/**
* Whether to select the series initially. If showCheckbox is true, the checkbox next to the
* series name will be checked for a selected series. Defaults to false.
*/
@Option
public Boolean selected;
/**
* Boolean value whether to apply a drop shadow to the graph line. Optionally can be a
* ShadowOptions object. Defaults to true.
*
* @see ShadowOptions
*/
@Option
public Object shadow;
/**
* If true, a checkbox is displayed next to the legend item to allow selecting the series. The
* state of the checkbox is determined by the selected option. Defaults to false.
*/
@Option
public Boolean showCheckbox;
/**
* Whether to display this particular series or series type in the legend. Defaults to true.
*/
@Option
public Boolean showInLegend;
/**
* If set to True, the accessibility module will skip past the points in this series for
* keyboard navigation. Defaults to undefined.
*/
@Option
public Boolean skipKeyboardNavigation;
/**
* When this is true, the series will not cause the Y axis to cross the zero plane (or threshold
* option) unless the data actually crosses the plane. For example, if softThreshold is false, a
* series of 0, 1, 2, 3 will make the Y axis show negative values according to the minPadding
* option. If softThreshold is true, the Y axis starts at 0. Defaults to true.
*/
@Option
public Boolean softThreshold;
/**
* Whether to stack the values of each series on top of each other. Possible values are null to
* disable, "normal" to stack by value or "percent". Defaults to null.
*/
@Option
public String stacking;
/**
* Whether to apply steps to the line. Possible values are left, center and right. Defaults to
* undefined.
*/
@Option
public AlignHorizontal step;
/**
* Sticky tracking of mouse events. When true, the mouseOut event on a series isn't triggered
* until the mouse moves over another series, or out of the plot area. When false, the mouseOut
* event on a series is triggered when the mouse leaves the area around the series' graph or
* markers. This also implies the tooltip. When stickyTracking is false and tooltip.shared is
* false, the tooltip will be hidden when moving the mouse between series. Defaults to true.
*/
@Option
public Boolean stickyTracking;
/**
* The threshold, also called zero level or base level. For line type series this is only used
* in conjunction with negativeColor. Defaults to 0.
*/
@Option
public Double threshold;
/**
* A configuration object for the tooltip rendering of each single series.
*/
@Option
public final TooltipOptions tooltip = new TooltipOptions();
/**
* When a series contains a data array that is longer than this, only one dimensional arrays of
* numbers, or two dimensional arrays with x and y values are allowed. Also, only the first
* point is tested, and the rest are assumed to be the same format. This saves expensive data
* checking and indexing in long series. Defaults to 1000.
*/
@Option
public Integer turboThreshold;
/**
* Set the initial visibility of the series. Defaults to true.
*/
@Option
public Boolean visible;
/**
* Defines the axis on which the zones are applied. Defaults to y.
*/
@Option
public String zoneAxis;
/**
* An array defining zones within a series. Zones can be applied to the X axis, Y axis or Z axis
* for bubbles, according to the zoneAxis option. In styled mode, the color zones are styled
* with the .highcharts-zone-{n} class, or custom classed from the className option.
*/
@Option
public final List<Zone> zones = new ArrayList<>();
/**
* If type is not null, place options under a submap indexed by the type id.
*/
@Override
public OptionMap toMap() {
OptionMap map = super.toMap();
if (type != null) {
OptionMap newMap = new OptionMap();
newMap.put(type, map);
map = newMap;
}
return map;
}
}
| fujion/fujion-framework | fujion-highcharts/src/main/java/org/fujion/highcharts/PlotOptions.java | Java | apache-2.0 | 15,646 |
describe('app.components.SaveProfileModal', function() {
beforeEach(function () {
module('app.components', 'ui.bootstrap', 'gettext');
});
describe('service', function () {
var callbackObject;
var saveSpy;
var doNotSaveSpy;
var cancelSpy;
beforeEach(function () {
bard.inject('SaveProfileModal', '$rootScope', '$document');
callbackObject = {
save: function () {},
doNotSave: function () {},
cancel: function () {},
}
saveSpy = sinon.spy(callbackObject, "save");
doNotSaveSpy = sinon.spy(callbackObject, "doNotSave");
cancelSpy = sinon.spy(callbackObject, "cancel");
});
xit('should show the modal', function () {
var modal = SaveProfileModal.showModal(callbackObject.save, callbackObject.doNotSave, callbackObject.cancel);
$rootScope.$digest();
var saveDialog = $document.find('.save-profile-modal');
expect(saveDialog.length).to.eq(1);
var saveButton = $document.find('.save-profile-modal .btn.btn-primary');
expect(saveButton.length).to.eq(1);
eventFire(saveButton[0], 'click');
$rootScope.$digest();
expect(saveSpy).to.have.been.called;
var closeButtons = $document.find('.save-profile-modal .btn.btn-default');
expect(closeButtons.length).to.eq(2);
eventFire(closeButtons[0], 'click');
$rootScope.$digest();
expect(cancelSpy).to.have.been.called;
eventFire(closeButtons[1], 'click');
$rootScope.$digest();
expect(doNotSaveSpy).to.have.been.called;
});
});
});
| dtaylor113/manageiq-ui-self_service | tests/profiles/save-profile-modal-service.spec.js | JavaScript | apache-2.0 | 1,584 |
package grok.core;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.auto.value.AutoValue;
@AutoValue
public abstract class Image {
@JsonCreator
public static Image of(@JsonProperty("id") String id,
@JsonProperty("title") String title,
@JsonProperty("url") String url) {
return builder().id(id)
.title(title)
.url(url)
.build();
}
public static Builder builder() {
return new AutoValue_Image.Builder();
}
Image() {}
@JsonProperty
public abstract String id();
@JsonProperty
public abstract String title();
@JsonProperty
public abstract String url();
@AutoValue.Builder
public abstract static class Builder {
Builder() {}
public abstract Builder id(String value);
@JsonProperty
public abstract Builder title(String value);
@JsonProperty
public abstract Builder url(String value);
public abstract Image build();
}
}
| achaphiv/grok-core | grok-core-api/src/main/java/grok/core/Image.java | Java | apache-2.0 | 1,076 |
package com.mgaetan89.showsrage.fragment;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.util.Arrays;
import java.util.Collection;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
@RunWith(Parameterized.class)
public class ShowsFragment_OnQueryTextChangeTest {
@Parameterized.Parameter(0)
public String newText;
private ShowsFragment fragment;
@Before
public void before() {
this.fragment = spy(new ShowsFragment());
}
@Test
public void onQueryTextChange() {
try {
assertTrue(this.fragment.onQueryTextChange(this.newText));
} catch (NullPointerException exception) {
// LocalBroadcastManager.getInstance(Context) returns null in tests
}
verify(this.fragment).sendFilterMessage();
}
@After
public void after() {
this.fragment = null;
}
@Parameterized.Parameters
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][]{
{null},
{""},
{" "},
{"Search Query"},
});
}
}
| phaseburn/ShowsRage | app/src/test/java/com/mgaetan89/showsrage/fragment/ShowsFragment_OnQueryTextChangeTest.java | Java | apache-2.0 | 1,137 |
# frozen_string_literal: true
class CreateSnapshotAttributeValues < ActiveRecord::Migration[4.2]
def change
create_table :snapshot_attribute_values do |t|
t.integer :snapshot_id, null: false
t.integer :attribute_value_id, null: false
t.timestamps null: false
end
end
end
| ausaccessfed/validator-service | db/migrate/20160508233712_create_snapshot_attribute_values.rb | Ruby | apache-2.0 | 302 |
/***************************************************************
*
* Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,
* University of Wisconsin-Madison, WI.
*
* 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.
*
***************************************************************/
#include "condor_common.h"
#include "condor_config.h"
#include "condor_state.h"
#include "condor_api.h"
#include "status_types.h"
#include "totals.h"
#include "get_daemon_name.h"
#include "daemon.h"
#include "dc_collector.h"
#include "extArray.h"
#include "sig_install.h"
#include "string_list.h"
#include "condor_string.h" // for strnewp()
#include "match_prefix.h" // is_arg_colon_prefix
#include "print_wrapped_text.h"
#include "error_utils.h"
#include "condor_distribution.h"
#include "condor_version.h"
#include <vector>
#include <sstream>
#include <iostream>
using std::vector;
using std::string;
using std::stringstream;
struct SortSpec {
string arg;
string keyAttr;
string keyExprAttr;
ExprTree* expr;
ExprTree* exprLT;
ExprTree* exprEQ;
SortSpec(): arg(), keyAttr(), keyExprAttr(), expr(NULL), exprLT(NULL), exprEQ(NULL) {}
~SortSpec() {
if (NULL != expr) delete expr;
if (NULL != exprLT) delete exprLT;
if (NULL != exprEQ) delete exprEQ;
}
SortSpec(const SortSpec& src): expr(NULL), exprLT(NULL), exprEQ(NULL) { *this = src; }
SortSpec& operator=(const SortSpec& src) {
if (this == &src) return *this;
arg = src.arg;
keyAttr = src.keyAttr;
keyExprAttr = src.keyExprAttr;
if (NULL != expr) delete expr;
expr = src.expr->Copy();
if (NULL != exprLT) delete exprLT;
exprLT = src.exprLT->Copy();
if (NULL != exprEQ) delete exprEQ;
exprEQ = src.exprEQ->Copy();
return *this;
}
};
// global variables
AttrListPrintMask pm;
printmask_headerfooter_t pmHeadFoot = STD_HEADFOOT;
List<const char> pm_head; // The list of headings for the mask entries
std::vector<GroupByKeyInfo> group_by_keys; // TJ 8.1.5 for future use, ignored for now.
bool explicit_format = false;
bool using_print_format = false; // hack for now so we can get standard totals when using -print-format
bool disable_user_print_files = false; // allow command line to defeat use of default user print files.
const char *DEFAULT= "<default>";
DCCollector* pool = NULL;
AdTypes type = (AdTypes) -1;
ppOption ppStyle = PP_NOTSET;
ppOption ppTotalStyle = PP_NOTSET; // used when setting PP_CUSTOM to keep track of how to do totals.
int wantOnlyTotals = 0;
int summarySize = -1;
bool expert = false;
bool wide_display = false; // when true, don't truncate field data
bool invalid_fields_empty = false; // when true, print "" instead of "[?]" for missing data
Mode mode = MODE_NOTSET;
const char * mode_constraint = NULL; // constraint set by mode
int diagnose = 0;
char* direct = NULL;
char* statistics = NULL;
char* genericType = NULL;
CondorQuery *query;
char buffer[1024];
char *myName;
vector<SortSpec> sortSpecs;
bool noSort = false; // set to true to disable sorting entirely
bool javaMode = false;
bool vmMode = false;
bool absentMode = false;
char *target = NULL;
const char * ads_file = NULL; // read classads from this file instead of querying them from the collector
ClassAd *targetAd = NULL;
ArgList projList; // Attributes that we want the server to send us
// instantiate templates
// function declarations
void usage ();
void firstPass (int, char *[]);
void secondPass (int, char *[]);
void prettyPrint(ClassAdList &, TrackTotals *);
int matchPrefix(const char *, const char *, int min_len);
int lessThanFunc(AttrList*,AttrList*,void*);
int customLessThanFunc(AttrList*,AttrList*,void*);
static bool read_classad_file(const char *filename, ClassAdList &classads, const char * constr);
extern "C" int SetSyscalls (int) {return 0;}
extern void setPPstyle (ppOption, int, const char *);
extern void setType (const char *, int, const char *);
extern void setMode (Mode, int, const char *);
int
main (int argc, char *argv[])
{
#if !defined(WIN32)
install_sig_handler(SIGPIPE, (SIG_HANDLER)SIG_IGN );
#endif
// initialize to read from config file
myDistro->Init( argc, argv );
myName = argv[0];
config();
dprintf_config_tool_on_error(0);
// The arguments take two passes to process --- the first pass
// figures out the mode, after which we can instantiate the required
// query object. We add implied constraints from the command line in
// the second pass.
firstPass (argc, argv);
// if the mode has not been set, it is STARTD_NORMAL
if (mode == MODE_NOTSET) {
setMode (MODE_STARTD_NORMAL, 0, DEFAULT);
}
// instantiate query object
if (!(query = new CondorQuery (type))) {
dprintf_WriteOnErrorBuffer(stderr, true);
fprintf (stderr, "Error: Out of memory\n");
exit (1);
}
// if a first-pass setMode set a mode_constraint, apply it now to the query object
if (mode_constraint && ! explicit_format) {
query->addANDConstraint(mode_constraint);
}
// set pretty print style implied by the type of entity being queried
// but do it with default priority, so that explicitly requested options
// can override it
switch (type)
{
#ifdef HAVE_EXT_POSTGRESQL
case QUILL_AD:
setPPstyle(PP_QUILL_NORMAL, 0, DEFAULT);
break;
#endif /* HAVE_EXT_POSTGRESQL */
case DEFRAG_AD:
setPPstyle(PP_GENERIC_NORMAL, 0, DEFAULT);
break;
case STARTD_AD:
setPPstyle(PP_STARTD_NORMAL, 0, DEFAULT);
break;
case SCHEDD_AD:
setPPstyle(PP_SCHEDD_NORMAL, 0, DEFAULT);
break;
case MASTER_AD:
setPPstyle(PP_MASTER_NORMAL, 0, DEFAULT);
break;
case CKPT_SRVR_AD:
setPPstyle(PP_CKPT_SRVR_NORMAL, 0, DEFAULT);
break;
case COLLECTOR_AD:
setPPstyle(PP_COLLECTOR_NORMAL, 0, DEFAULT);
break;
case STORAGE_AD:
setPPstyle(PP_STORAGE_NORMAL, 0, DEFAULT);
break;
case NEGOTIATOR_AD:
setPPstyle(PP_NEGOTIATOR_NORMAL, 0, DEFAULT);
break;
case GRID_AD:
setPPstyle(PP_GRID_NORMAL, 0, DEFAULT);
break;
case GENERIC_AD:
setPPstyle(PP_GENERIC, 0, DEFAULT);
break;
case ANY_AD:
setPPstyle(PP_ANY_NORMAL, 0, DEFAULT);
break;
default:
setPPstyle(PP_VERBOSE, 0, DEFAULT);
}
// set the constraints implied by the mode
switch (mode) {
#ifdef HAVE_EXT_POSTGRESQL
case MODE_QUILL_NORMAL:
#endif /* HAVE_EXT_POSTGRESQL */
case MODE_DEFRAG_NORMAL:
case MODE_STARTD_NORMAL:
case MODE_MASTER_NORMAL:
case MODE_CKPT_SRVR_NORMAL:
case MODE_SCHEDD_NORMAL:
case MODE_SCHEDD_SUBMITTORS:
case MODE_COLLECTOR_NORMAL:
case MODE_NEGOTIATOR_NORMAL:
case MODE_STORAGE_NORMAL:
case MODE_GENERIC_NORMAL:
case MODE_ANY_NORMAL:
case MODE_GRID_NORMAL:
case MODE_HAD_NORMAL:
break;
case MODE_OTHER:
// tell the query object what the type we're querying is
query->setGenericQueryType(genericType);
free(genericType);
genericType = NULL;
break;
case MODE_STARTD_AVAIL:
// For now, -avail shows you machines avail to anyone.
sprintf (buffer, "%s == \"%s\"", ATTR_STATE,
state_to_string(unclaimed_state));
if (diagnose) {
printf ("Adding constraint [%s]\n", buffer);
}
query->addORConstraint (buffer);
break;
case MODE_STARTD_RUN:
sprintf (buffer, "%s == \"%s\"", ATTR_STATE,
state_to_string(claimed_state));
if (diagnose) {
printf ("Adding constraint [%s]\n", buffer);
}
query->addORConstraint (buffer);
break;
case MODE_STARTD_COD:
sprintf (buffer, "%s > 0", ATTR_NUM_COD_CLAIMS );
if (diagnose) {
printf ("Adding constraint [%s]\n", buffer);
}
query->addORConstraint (buffer);
break;
default:
break;
}
if(javaMode) {
sprintf( buffer, "%s == TRUE", ATTR_HAS_JAVA );
if (diagnose) {
printf ("Adding constraint [%s]\n", buffer);
}
query->addANDConstraint (buffer);
projList.AppendArg(ATTR_HAS_JAVA);
projList.AppendArg(ATTR_JAVA_MFLOPS);
projList.AppendArg(ATTR_JAVA_VENDOR);
projList.AppendArg(ATTR_JAVA_VERSION);
}
if(absentMode) {
sprintf( buffer, "%s == TRUE", ATTR_ABSENT );
if (diagnose) {
printf( "Adding constraint %s\n", buffer );
}
query->addANDConstraint( buffer );
projList.AppendArg( ATTR_ABSENT );
projList.AppendArg( ATTR_LAST_HEARD_FROM );
projList.AppendArg( ATTR_CLASSAD_LIFETIME );
}
if(vmMode) {
sprintf( buffer, "%s == TRUE", ATTR_HAS_VM);
if (diagnose) {
printf ("Adding constraint [%s]\n", buffer);
}
query->addANDConstraint (buffer);
projList.AppendArg(ATTR_VM_TYPE);
projList.AppendArg(ATTR_VM_MEMORY);
projList.AppendArg(ATTR_VM_NETWORKING);
projList.AppendArg(ATTR_VM_NETWORKING_TYPES);
projList.AppendArg(ATTR_VM_HARDWARE_VT);
projList.AppendArg(ATTR_VM_AVAIL_NUM);
projList.AppendArg(ATTR_VM_ALL_GUEST_MACS);
projList.AppendArg(ATTR_VM_ALL_GUEST_IPS);
projList.AppendArg(ATTR_VM_GUEST_MAC);
projList.AppendArg(ATTR_VM_GUEST_IP);
}
// second pass: add regular parameters and constraints
if (diagnose) {
printf ("----------\n");
}
secondPass (argc, argv);
// initialize the totals object
if (ppStyle == PP_CUSTOM && using_print_format) {
if (pmHeadFoot & HF_NOSUMMARY) ppTotalStyle = PP_CUSTOM;
} else {
ppTotalStyle = ppStyle;
}
TrackTotals totals(ppTotalStyle);
// fetch the query
QueryResult q;
if ((mode == MODE_STARTD_NORMAL) && (ppStyle == PP_STARTD_NORMAL)) {
projList.AppendArg("Name");
projList.AppendArg("Machine");
projList.AppendArg("Opsys");
projList.AppendArg("Arch");
projList.AppendArg("State");
projList.AppendArg("Activity");
projList.AppendArg("LoadAvg");
projList.AppendArg("Memory");
projList.AppendArg("ActvtyTime");
projList.AppendArg("MyCurrentTime");
projList.AppendArg("EnteredCurrentActivity");
} else if( ppStyle == PP_VERBOSE ) {
// Remove everything from the projection list if we're displaying
// the "long form" of the ads.
projList.Clear();
}
if( projList.Count() > 0 ) {
char **attr_list = projList.GetStringArray();
query->setDesiredAttrs(attr_list);
deleteStringArray(attr_list);
}
// if diagnose was requested, just print the query ad
if (diagnose) {
ClassAd queryAd;
// print diagnostic information about inferred internal state
setMode ((Mode) 0, 0, NULL);
setType (NULL, 0, NULL);
setPPstyle ((ppOption) 0, 0, DEFAULT);
printf ("----------\n");
q = query->getQueryAd (queryAd);
fPrintAd (stdout, queryAd);
printf ("----------\n");
fprintf (stderr, "Result of making query ad was: %d\n", q);
exit (1);
}
// Address (host:port) is taken from requested pool, if given.
char* addr = (NULL != pool) ? pool->addr() : NULL;
Daemon* requested_daemon = pool;
// If we're in "direct" mode, then we attempt to locate the daemon
// associated with the requested subsystem (here encoded by value of mode)
// In this case the host:port of pool (if given) denotes which
// pool is being consulted
if( direct ) {
Daemon *d = NULL;
switch( mode ) {
case MODE_MASTER_NORMAL:
d = new Daemon( DT_MASTER, direct, addr );
break;
case MODE_STARTD_NORMAL:
case MODE_STARTD_AVAIL:
case MODE_STARTD_RUN:
case MODE_STARTD_COD:
d = new Daemon( DT_STARTD, direct, addr );
break;
#ifdef HAVE_EXT_POSTGRESQL
case MODE_QUILL_NORMAL:
d = new Daemon( DT_QUILL, direct, addr );
break;
#endif /* HAVE_EXT_POSTGRESQL */
case MODE_SCHEDD_NORMAL:
case MODE_SCHEDD_SUBMITTORS:
d = new Daemon( DT_SCHEDD, direct, addr );
break;
case MODE_NEGOTIATOR_NORMAL:
d = new Daemon( DT_NEGOTIATOR, direct, addr );
break;
case MODE_CKPT_SRVR_NORMAL:
case MODE_COLLECTOR_NORMAL:
case MODE_LICENSE_NORMAL:
case MODE_STORAGE_NORMAL:
case MODE_GENERIC_NORMAL:
case MODE_ANY_NORMAL:
case MODE_OTHER:
case MODE_GRID_NORMAL:
case MODE_HAD_NORMAL:
// These have to go to the collector, anyway.
break;
default:
fprintf( stderr, "Error: Illegal mode %d\n", mode );
exit( 1 );
break;
}
// Here is where we actually override 'addr', if we can obtain
// address of the requested daemon/subsys. If it can't be
// located, then fail with error msg.
// 'd' will be null (unset) if mode is one of above that must go to
// collector (MODE_ANY_NORMAL, MODE_COLLECTOR_NORMAL, etc)
if (NULL != d) {
if( d->locate() ) {
addr = d->addr();
requested_daemon = d;
} else {
const char* id = d->idStr();
if (NULL == id) id = d->name();
dprintf_WriteOnErrorBuffer(stderr, true);
if (NULL == id) id = "daemon";
fprintf(stderr, "Error: Failed to locate %s\n", id);
fprintf(stderr, "%s\n", d->error());
exit( 1 );
}
}
}
ClassAdList result;
CondorError errstack;
if (NULL != ads_file) {
MyString req; // query requirements
q = query->getRequirements(req);
const char * constraint = req.empty() ? NULL : req.c_str();
if (read_classad_file(ads_file, result, constraint)) {
q = Q_OK;
}
} else if (NULL != addr) {
// this case executes if pool was provided, or if in "direct" mode with
// subsystem that corresponds to a daemon (above).
// Here 'addr' represents either the host:port of requested pool, or
// alternatively the host:port of daemon associated with requested subsystem (direct mode)
q = query->fetchAds (result, addr, &errstack);
} else {
// otherwise obtain list of collectors and submit query that way
CollectorList * collectors = CollectorList::create();
q = collectors->query (*query, result, &errstack);
delete collectors;
}
// if any error was encountered during the query, report it and exit
if (Q_OK != q) {
dprintf_WriteOnErrorBuffer(stderr, true);
// we can always provide these messages:
fprintf( stderr, "Error: %s\n", getStrQueryResult(q) );
fprintf( stderr, "%s\n", errstack.getFullText(true).c_str() );
if ((NULL != requested_daemon) && ((Q_NO_COLLECTOR_HOST == q) ||
(requested_daemon->type() == DT_COLLECTOR)))
{
// Specific long message if connection to collector failed.
const char* fullhost = requested_daemon->fullHostname();
if (NULL == fullhost) fullhost = "<unknown_host>";
const char* daddr = requested_daemon->addr();
if (NULL == daddr) daddr = "<unknown>";
char info[1000];
sprintf(info, "%s (%s)", fullhost, daddr);
printNoCollectorContact( stderr, info, !expert );
} else if ((NULL != requested_daemon) && (Q_COMMUNICATION_ERROR == q)) {
// more helpful message for failure to connect to some daemon/subsys
const char* id = requested_daemon->idStr();
if (NULL == id) id = requested_daemon->name();
if (NULL == id) id = "daemon";
const char* daddr = requested_daemon->addr();
if (NULL == daddr) daddr = "<unknown>";
fprintf(stderr, "Error: Failed to contact %s at %s\n", id, daddr);
}
// fail
exit (1);
}
if (noSort) {
// do nothing
} else if (sortSpecs.empty()) {
// default classad sorting
result.Sort((SortFunctionType)lessThanFunc);
} else {
// User requested custom sorting expressions:
// insert attributes related to custom sorting
result.Open();
while (ClassAd* ad = result.Next()) {
for (vector<SortSpec>::iterator ss(sortSpecs.begin()); ss != sortSpecs.end(); ++ss) {
ss->expr->SetParentScope(ad);
classad::Value v;
ss->expr->Evaluate(v);
stringstream vs;
// This will properly render all supported value types,
// including undefined and error, although current semantic
// pre-filters classads where sort expressions are undef/err:
vs << ((v.IsStringValue())?"\"":"") << v << ((v.IsStringValue())?"\"":"");
ad->AssignExpr(ss->keyAttr.c_str(), vs.str().c_str());
// Save the full expr in case user wants to examine on output:
ad->AssignExpr(ss->keyExprAttr.c_str(), ss->arg.c_str());
}
}
result.Open();
result.Sort((SortFunctionType)customLessThanFunc);
}
// output result
prettyPrint (result, &totals);
delete query;
return 0;
}
const CustomFormatFnTable * getCondorStatusPrintFormats();
int set_status_print_mask_from_stream (
const char * streamid,
bool is_filename,
const char ** pconstraint)
{
std::string where_expr;
std::string messages;
StringList attrs;
SimpleInputStream * pstream = NULL;
*pconstraint = NULL;
FILE *file = NULL;
if (MATCH == strcmp("-", streamid)) {
pstream = new SimpleFileInputStream(stdin, false);
} else if (is_filename) {
file = safe_fopen_wrapper_follow(streamid, "r");
if (file == NULL) {
fprintf(stderr, "Can't open select file: %s\n", streamid);
return -1;
}
pstream = new SimpleFileInputStream(file, true);
} else {
pstream = new StringLiteralInputStream(streamid);
}
ASSERT(pstream);
int err = SetAttrListPrintMaskFromStream(
*pstream,
*getCondorStatusPrintFormats(),
pm,
pmHeadFoot,
group_by_keys,
where_expr,
attrs,
messages);
delete pstream; pstream = NULL;
if ( ! err) {
if ( ! where_expr.empty()) {
*pconstraint = pm.store(where_expr.c_str());
//if ( ! validate_constraint(*pconstraint)) {
// formatstr_cat(messages, "WHERE expression is not valid: %s\n", *pconstraint);
//}
}
// convert projection list into the format that condor status likes. because programmers.
attrs.rewind();
const char * attr;
while ((attr = attrs.next())) { projList.AppendArg(attr); }
}
if ( ! messages.empty()) { fprintf(stderr, "%s", messages.c_str()); }
return err;
}
static bool read_classad_file(const char *filename, ClassAdList &classads, const char * constr)
{
bool success = false;
FILE* file = safe_fopen_wrapper_follow(filename, "r");
if (file == NULL) {
fprintf(stderr, "Can't open file of job ads: %s\n", filename);
return false;
} else {
CondorClassAdFileParseHelper parse_helper("\n");
for (;;) {
ClassAd* classad = new ClassAd();
int error;
bool is_eof;
int cAttrs = classad->InsertFromFile(file, is_eof, error, &parse_helper);
bool include_classad = cAttrs > 0 && error >= 0;
if (include_classad && constr) {
classad::Value val;
if (classad->EvaluateExpr(constr,val)) {
if ( ! val.IsBooleanValueEquiv(include_classad)) {
include_classad = false;
}
}
}
if (include_classad) {
classads.Insert(classad);
} else {
delete classad;
}
if (is_eof) {
success = true;
break;
}
if (error < 0) {
success = false;
break;
}
}
fclose(file);
}
return success;
}
void
usage ()
{
fprintf (stderr,"Usage: %s [help-opt] [query-opt] [display-opt] "
"[custom-opts ...] [name ...]\n"
" where [help-opt] is one of\n"
"\t-help\t\t\tPrint this screen and exit\n"
"\t-version\t\tPrint HTCondor version and exit\n"
"\t-diagnose\t\tPrint out query ad without performing query\n"
" and [query-opt] is one of\n"
"\t-absent\t\t\tPrint information about absent resources\n"
"\t-avail\t\t\tPrint information about available resources\n"
"\t-ckptsrvr\t\tDisplay checkpoint server attributes\n"
"\t-claimed\t\tPrint information about claimed resources\n"
"\t-cod\t\t\tDisplay Computing On Demand (COD) jobs\n"
"\t-collector\t\tDisplay collector daemon attributes\n"
"\t-debug\t\t\tDisplay debugging info to console\n"
"\t-defrag\t\t\tDisplay status of defrag daemon\n"
"\t-direct <host>\t\tGet attributes directly from the given daemon\n"
"\t-java\t\t\tDisplay Java-capable hosts\n"
"\t-vm\t\t\tDisplay VM-capable hosts\n"
"\t-license\t\tDisplay attributes of licenses\n"
"\t-master\t\t\tDisplay daemon master attributes\n"
"\t-pool <name>\t\tGet information from collector <name>\n"
"\t-ads <file>\t\tGet information from <file>\n"
"\t-grid\t\t\tDisplay grid resources\n"
"\t-run\t\t\tSame as -claimed [deprecated]\n"
#ifdef HAVE_EXT_POSTGRESQL
"\t-quill\t\t\tDisplay attributes of quills\n"
#endif /* HAVE_EXT_POSTGRESQL */
"\t-schedd\t\t\tDisplay attributes of schedds\n"
"\t-server\t\t\tDisplay important attributes of resources\n"
"\t-startd\t\t\tDisplay resource attributes\n"
"\t-generic\t\tDisplay attributes of 'generic' ads\n"
"\t-subsystem <type>\tDisplay classads of the given type\n"
"\t-negotiator\t\tDisplay negotiator attributes\n"
"\t-storage\t\tDisplay network storage resources\n"
"\t-any\t\t\tDisplay any resources\n"
"\t-state\t\t\tDisplay state of resources\n"
"\t-submitters\t\tDisplay information about request submitters\n"
// "\t-statistics <set>:<n>\tDisplay statistics for <set> at level <n>\n"
// "\t\t\t\tsee STATISTICS_TO_PUBLISH for valid <set> and level values\n"
// "\t-world\t\t\tDisplay all pools reporting to UW collector\n"
" and [display-opt] is one of\n"
"\t-long\t\t\tDisplay entire classads\n"
"\t-sort <expr>\t\tSort entries by expressions. 'no' disables sorting\n"
"\t-total\t\t\tDisplay totals only\n"
"\t-verbose\t\tSame as -long\n"
"\t-wide\t\t\tdon't truncate data to fit in 80 columns.\n"
"\t-xml\t\t\tDisplay entire classads, but in XML\n"
"\t-attributes X,Y,...\tAttributes to show in -xml or -long \n"
"\t-expert\t\t\tDisplay shorter error messages\n"
" and [custom-opts ...] are one or more of\n"
"\t-constraint <const>\tAdd constraint on classads\n"
"\t-format <fmt> <attr>\tRegister display format and attribute\n"
"\t-autoformat:[V,ntlh] <attr> [attr2 [attr3 ...]]\t Print attr(s) with automatic formatting\n"
"\t\tV\tUse %%V formatting\n"
"\t\t,\tComma separated (default is space separated)\n"
"\t\tt\tTab separated\n"
"\t\tn\tNewline after each attribute\n"
"\t\tl\tLabel each value\n"
"\t\th\tHeadings\n"
"\t-target filename\tIf -format or -af is used, the option target classad\n",
myName);
}
void
firstPass (int argc, char *argv[])
{
int had_pool_error = 0;
int had_direct_error = 0;
int had_statistics_error = 0;
//bool explicit_mode = false;
const char * pcolon = NULL;
// Process arguments: there are dependencies between them
// o -l/v and -serv are mutually exclusive
// o -sub, -avail and -run are mutually exclusive
// o -pool and -entity may be used at most once
// o since -c can be processed only after the query has been instantiated,
// constraints are added on the second pass
for (int i = 1; i < argc; i++) {
if (matchPrefix (argv[i], "-avail", 3)) {
setMode (MODE_STARTD_AVAIL, i, argv[i]);
} else
if (matchPrefix (argv[i], "-pool", 2)) {
if( pool ) {
delete pool;
had_pool_error = 1;
}
i++;
if( ! argv[i] ) {
fprintf( stderr, "%s: -pool requires a hostname as an argument.\n",
myName );
if (!expert) {
printf("\n");
print_wrapped_text("Extra Info: The hostname should be the central "
"manager of the Condor pool you wish to work with.",
stderr);
printf("\n");
}
fprintf( stderr, "Use \"%s -help\" for details\n", myName );
exit( 1 );
}
pool = new DCCollector( argv[i] );
if( !pool->addr() ) {
dprintf_WriteOnErrorBuffer(stderr, true);
fprintf( stderr, "Error: %s\n", pool->error() );
if (!expert) {
printf("\n");
print_wrapped_text("Extra Info: You specified a hostname for a pool "
"(the -pool argument). That should be the Internet "
"host name for the central manager of the pool, "
"but it does not seem to "
"be a valid hostname. (The DNS lookup failed.)",
stderr);
}
exit( 1 );
}
} else
if (is_dash_arg_prefix (argv[i], "ads", 2)) {
if( !argv[i+1] ) {
fprintf( stderr, "%s: -ads requires a filename argument\n",
myName );
fprintf( stderr, "Use \"%s -help\" for details\n", myName );
exit( 1 );
}
i += 1;
ads_file = argv[i];
} else
if (matchPrefix (argv[i], "-format", 2)) {
setPPstyle (PP_CUSTOM, i, argv[i]);
if( !argv[i+1] || !argv[i+2] ) {
fprintf( stderr, "%s: -format requires two other arguments\n",
myName );
fprintf( stderr, "Use \"%s -help\" for details\n", myName );
exit( 1 );
}
i += 2;
explicit_format = true;
} else
if (*argv[i] == '-' &&
(is_arg_colon_prefix(argv[i]+1, "autoformat", &pcolon, 5) ||
is_arg_colon_prefix(argv[i]+1, "af", &pcolon, 2)) ) {
// make sure we have at least one more argument
if ( !argv[i+1] || *(argv[i+1]) == '-') {
fprintf( stderr, "Error: Argument %s requires "
"at last one attribute parameter\n", argv[i] );
fprintf( stderr, "Use \"%s -help\" for details\n", myName );
exit( 1 );
}
explicit_format = true;
setPPstyle (PP_CUSTOM, i, argv[i]);
while (argv[i+1] && *(argv[i+1]) != '-') {
++i;
}
// if autoformat list ends in a '-' without any characters after it, just eat the arg and keep going.
if (i+1 < argc && '-' == (argv[i+1])[0] && 0 == (argv[i+1])[1]) {
++i;
}
} else
if (is_dash_arg_colon_prefix(argv[i], "print-format", &pcolon, 2)) {
if ( (i+1 >= argc) || (*(argv[i+1]) == '-' && (argv[i+1])[1] != 0)) {
fprintf( stderr, "Error: Argument -print-format requires a filename argument\n");
exit( 1 );
}
explicit_format = true;
++i; // eat the next argument.
// we can't fully parse the print format argument until the second pass, so we are done for now.
} else
if (matchPrefix (argv[i], "-wide", 3)) {
wide_display = true; // when true, don't truncate field data
//invalid_fields_empty = true;
} else
if (matchPrefix (argv[i], "-target", 5)) {
if( !argv[i+1] ) {
fprintf( stderr, "%s: -target requires one additional argument\n",
myName );
fprintf( stderr, "Use \"%s -help\" for details\n", myName );
exit( 1 );
}
i += 1;
target = argv[i];
FILE *targetFile = safe_fopen_wrapper_follow(target, "r");
int iseof, iserror, empty;
targetAd = new ClassAd(targetFile, "\n\n", iseof, iserror, empty);
fclose(targetFile);
} else
if (matchPrefix (argv[i], "-constraint", 4)) {
// can add constraints on second pass only
i++;
if( ! argv[i] ) {
fprintf( stderr, "%s: -constraint requires another argument\n",
myName );
fprintf( stderr, "Use \"%s -help\" for details\n", myName );
exit( 1 );
}
} else
if (matchPrefix (argv[i], "-direct", 4)) {
if( direct ) {
free( direct );
had_direct_error = 1;
}
i++;
if( ! argv[i] ) {
fprintf( stderr, "%s: -direct requires another argument\n",
myName );
fprintf( stderr, "Use \"%s -help\" for details\n", myName );
exit( 1 );
}
direct = strdup( argv[i] );
} else
if (matchPrefix (argv[i], "-diagnose", 4)) {
diagnose = 1;
} else
if (matchPrefix (argv[i], "-debug", 3)) {
// dprintf to console
dprintf_set_tool_debug("TOOL", 0);
} else
if (matchPrefix (argv[i], "-defrag", 4)) {
setMode (MODE_DEFRAG_NORMAL, i, argv[i]);
} else
if (matchPrefix (argv[i], "-help", 2)) {
usage ();
exit (0);
} else
if (matchPrefix (argv[i], "-long", 2) || matchPrefix (argv[i],"-verbose", 3)) {
setPPstyle (PP_VERBOSE, i, argv[i]);
} else
if (matchPrefix (argv[i],"-xml", 2)){
setPPstyle (PP_XML, i, argv[i]);
} else
if (matchPrefix (argv[i],"-attributes", 3)){
if( !argv[i+1] ) {
fprintf( stderr, "%s: -attributes requires one additional argument\n",
myName );
fprintf( stderr, "Use \"%s -help\" for details\n", myName );
exit( 1 );
}
i++;
} else
if (matchPrefix (argv[i], "-run", 2) || matchPrefix(argv[i], "-claimed", 3)) {
setMode (MODE_STARTD_RUN, i, argv[i]);
} else
if( matchPrefix (argv[i], "-cod", 4) ) {
setMode (MODE_STARTD_COD, i, argv[i]);
} else
if (matchPrefix (argv[i], "-java", 2)) {
/*explicit_mode =*/ javaMode = true;
} else
if (matchPrefix (argv[i], "-absent", 3)) {
/*explicit_mode =*/ absentMode = true;
} else
if (matchPrefix (argv[i], "-vm", 3)) {
/*explicit_mode =*/ vmMode = true;
} else
if (matchPrefix (argv[i], "-server", 3)) {
setPPstyle (PP_STARTD_SERVER, i, argv[i]);
} else
if (matchPrefix (argv[i], "-state", 5)) {
setPPstyle (PP_STARTD_STATE, i, argv[i]);
} else
if (matchPrefix (argv[i], "-statistics", 6)) {
if( statistics ) {
free( statistics );
had_statistics_error = 1;
}
i++;
if( ! argv[i] ) {
fprintf( stderr, "%s: -statistics requires another argument\n",
myName );
fprintf( stderr, "Use \"%s -help\" for details\n", myName );
exit( 1 );
}
statistics = strdup( argv[i] );
} else
if (matchPrefix (argv[i], "-startd", 5)) {
setMode (MODE_STARTD_NORMAL,i, argv[i]);
} else
if (matchPrefix (argv[i], "-schedd", 3)) {
setMode (MODE_SCHEDD_NORMAL, i, argv[i]);
} else
if (matchPrefix (argv[i], "-grid", 2)) {
setMode (MODE_GRID_NORMAL, i, argv[i]);
} else
if (matchPrefix (argv[i], "-subsystem", 5)) {
i++;
if( !argv[i] ) {
fprintf( stderr, "%s: -subsystem requires another argument\n",
myName );
fprintf( stderr, "Use \"%s -help\" for details\n", myName );
exit( 1 );
}
if (matchPrefix (argv[i], "schedd", 6)) {
setMode (MODE_SCHEDD_NORMAL, i, argv[i]);
} else
if (matchPrefix (argv[i], "startd", 6)) {
setMode (MODE_STARTD_NORMAL, i, argv[i]);
} else
if (matchPrefix (argv[i], "quill", 5)) {
setMode (MODE_QUILL_NORMAL, i, argv[i]);
} else
if (matchPrefix (argv[i], "negotiator", 10)) {
setMode (MODE_NEGOTIATOR_NORMAL, i, argv[i]);
} else
if (matchPrefix (argv[i], "master", 6)) {
setMode (MODE_MASTER_NORMAL, i, argv[i]);
} else
if (matchPrefix (argv[i], "collector", 9)) {
setMode (MODE_COLLECTOR_NORMAL, i, argv[i]);
} else
if (matchPrefix (argv[i], "generic", 7)) {
setMode (MODE_GENERIC_NORMAL, i, argv[i]);
} else
if (matchPrefix (argv[i], "had", 3)) {
setMode (MODE_HAD_NORMAL, i, argv[i]);
} else
if (*argv[i] == '-') {
fprintf(stderr, "%s: -subsystem requires another argument\n",
myName);
fprintf( stderr, "Use \"%s -help\" for details\n", myName );
exit(1);
} else {
genericType = strdup(argv[i]);
setMode (MODE_OTHER, i, argv[i]);
}
} else
#ifdef HAVE_EXT_POSTGRESQL
if (matchPrefix (argv[i], "-quill", 2)) {
setMode (MODE_QUILL_NORMAL, i, argv[i]);
} else
#endif /* HAVE_EXT_POSTGRESQL */
if (matchPrefix (argv[i], "-license", 3)) {
setMode (MODE_LICENSE_NORMAL, i, argv[i]);
} else
if (matchPrefix (argv[i], "-storage", 4)) {
setMode (MODE_STORAGE_NORMAL, i, argv[i]);
} else
if (matchPrefix (argv[i], "-negotiator", 2)) {
setMode (MODE_NEGOTIATOR_NORMAL, i, argv[i]);
} else
if (matchPrefix (argv[i], "-generic", 3)) {
setMode (MODE_GENERIC_NORMAL, i, argv[i]);
} else
if (matchPrefix (argv[i], "-any", 3)) {
setMode (MODE_ANY_NORMAL, i, argv[i]);
} else
if (matchPrefix (argv[i], "-sort", 3)) {
i++;
if( ! argv[i] ) {
fprintf( stderr, "%s: -sort requires another argument\n",
myName );
fprintf( stderr, "Use \"%s -help\" for details\n", myName );
exit( 1 );
}
if (MATCH == strcasecmp(argv[i], "false") ||
MATCH == strcasecmp(argv[i], "0") ||
MATCH == strcasecmp(argv[i], "no") ||
MATCH == strcasecmp(argv[i], "none"))
{
noSort = true;
continue;
}
int jsort = sortSpecs.size();
SortSpec ss;
ExprTree* sortExpr = NULL;
if (ParseClassAdRvalExpr(argv[i], sortExpr)) {
fprintf(stderr, "Error: Parse error of: %s\n", argv[i]);
exit(1);
}
ss.expr = sortExpr;
ss.arg = argv[i];
formatstr(ss.keyAttr, "CondorStatusSortKey%d", jsort);
formatstr(ss.keyExprAttr, "CondorStatusSortKeyExpr%d", jsort);
string exprString;
formatstr(exprString, "MY.%s < TARGET.%s", ss.keyAttr.c_str(), ss.keyAttr.c_str());
if (ParseClassAdRvalExpr(exprString.c_str(), sortExpr)) {
fprintf(stderr, "Error: Parse error of: %s\n", exprString.c_str());
exit(1);
}
ss.exprLT = sortExpr;
formatstr(exprString, "MY.%s == TARGET.%s", ss.keyAttr.c_str(), ss.keyAttr.c_str());
if (ParseClassAdRvalExpr(exprString.c_str(), sortExpr)) {
fprintf(stderr, "Error: Parse error of: %s\n", exprString.c_str());
exit(1);
}
ss.exprEQ = sortExpr;
sortSpecs.push_back(ss);
// the silent constraint TARGET.%s =!= UNDEFINED is added
// as a customAND constraint on the second pass
} else
if (matchPrefix (argv[i], "-submitters", 5)) {
setMode (MODE_SCHEDD_SUBMITTORS, i, argv[i]);
} else
if (matchPrefix (argv[i], "-master", 2)) {
setMode (MODE_MASTER_NORMAL, i, argv[i]);
} else
if (matchPrefix (argv[i], "-collector", 4)) {
setMode (MODE_COLLECTOR_NORMAL, i, argv[i]);
} else
if (matchPrefix (argv[i], "-world", 2)) {
setMode (MODE_COLLECTOR_NORMAL, i, argv[i]);
} else
if (matchPrefix (argv[i], "-ckptsrvr", 3)) {
setMode (MODE_CKPT_SRVR_NORMAL, i, argv[i]);
} else
if (matchPrefix (argv[i], "-total", 2)) {
wantOnlyTotals = 1;
explicit_format = true;
} else
if (matchPrefix(argv[i], "-expert", 2)) {
expert = true;
} else
if (matchPrefix(argv[i], "-version", 4)) {
printf( "%s\n%s\n", CondorVersion(), CondorPlatform() );
exit(0);
} else
if (*argv[i] == '-') {
fprintf (stderr, "Error: Unknown option %s\n", argv[i]);
usage ();
exit (1);
}
}
if( had_pool_error ) {
fprintf( stderr,
"Warning: Multiple -pool arguments given, using \"%s\"\n",
pool->name() );
}
if( had_direct_error ) {
fprintf( stderr,
"Warning: Multiple -direct arguments given, using \"%s\"\n",
direct );
}
if( had_statistics_error ) {
fprintf( stderr,
"Warning: Multiple -statistics arguments given, using \"%s\"\n",
statistics );
}
}
void
secondPass (int argc, char *argv[])
{
const char * pcolon = NULL;
char *daemonname;
for (int i = 1; i < argc; i++) {
// omit parameters which qualify switches
if( matchPrefix(argv[i],"-pool", 2) || matchPrefix(argv[i],"-direct", 4) ) {
i++;
continue;
}
if( matchPrefix(argv[i],"-subsystem", 5) ) {
i++;
continue;
}
if (matchPrefix (argv[i], "-format", 2)) {
pm.registerFormat (argv[i+1], argv[i+2]);
StringList attributes;
ClassAd ad;
if(!ad.GetExprReferences(argv[i+2],attributes,attributes)){
fprintf( stderr, "Error: Parse error of: %s\n", argv[i+2]);
exit(1);
}
attributes.rewind();
char const *s;
while( (s=attributes.next()) ) {
projList.AppendArg(s);
}
if (diagnose) {
printf ("Arg %d --- register format [%s] for [%s]\n",
i, argv[i+1], argv[i+2]);
}
i += 2;
continue;
}
if (*argv[i] == '-' &&
(is_arg_colon_prefix(argv[i]+1, "autoformat", &pcolon, 5) ||
is_arg_colon_prefix(argv[i]+1, "af", &pcolon, 2)) ) {
// make sure we have at least one more argument
if ( !argv[i+1] || *(argv[i+1]) == '-') {
fprintf( stderr, "Error: Argument %s requires "
"at last one attribute parameter\n", argv[i] );
fprintf( stderr, "Use \"%s -help\" for details\n", myName );
exit( 1 );
}
bool flabel = false;
bool fCapV = false;
bool fheadings = false;
const char * pcolpre = " ";
const char * pcolsux = NULL;
if (pcolon) {
++pcolon;
while (*pcolon) {
switch (*pcolon)
{
case ',': pcolsux = ","; break;
case 'n': pcolsux = "\n"; break;
case 't': pcolpre = "\t"; break;
case 'l': flabel = true; break;
case 'V': fCapV = true; break;
case 'h': fheadings = true; break;
}
++pcolon;
}
}
pm.SetAutoSep(NULL, pcolpre, pcolsux, "\n");
while (argv[i+1] && *(argv[i+1]) != '-') {
++i;
ClassAd ad;
StringList attributes;
if(!ad.GetExprReferences(argv[i],attributes,attributes)){
fprintf( stderr, "Error: Parse error of: %s\n", argv[i]);
exit(1);
}
attributes.rewind();
char const *s;
while ((s = attributes.next())) {
projList.AppendArg(s);
}
MyString lbl = "";
int wid = 0;
int opts = FormatOptionNoTruncate;
if (fheadings || pm_head.Length() > 0) {
const char * hd = fheadings ? argv[i] : "(expr)";
wid = 0 - (int)strlen(hd);
opts = FormatOptionAutoWidth | FormatOptionNoTruncate;
pm_head.Append(hd);
}
else if (flabel) { lbl.formatstr("%s = ", argv[i]); wid = 0; opts = 0; }
lbl += fCapV ? "%V" : "%v";
if (diagnose) {
printf ("Arg %d --- register format [%s] width=%d, opt=0x%x for [%s]\n",
i, lbl.Value(), wid, opts, argv[i]);
}
pm.registerFormat(lbl.Value(), wid, opts, argv[i]);
}
// if autoformat list ends in a '-' without any characters after it, just eat the arg and keep going.
if (i+1 < argc && '-' == (argv[i+1])[0] && 0 == (argv[i+1])[1]) {
++i;
}
continue;
}
if (is_dash_arg_colon_prefix(argv[i], "print-format", &pcolon, 2)) {
if ( (i+1 >= argc) || (*(argv[i+1]) == '-' && (argv[i+1])[1] != 0)) {
fprintf( stderr, "Error: Argument -print-format requires a filename argument\n");
exit( 1 );
}
// hack allow -pr ! to disable use of user-default print format files.
if (MATCH == strcmp(argv[i+1], "!")) {
++i;
disable_user_print_files = true;
continue;
}
ppTotalStyle = ppStyle;
setPPstyle (PP_CUSTOM, i, argv[i]);
++i; // skip to the next argument.
if (set_status_print_mask_from_stream(argv[i], true, &mode_constraint) < 0) {
fprintf(stderr, "Error: invalid select file %s\n", argv[i]);
exit (1);
}
if (mode_constraint) {
query->addANDConstraint(mode_constraint);
}
using_print_format = true; // so we can hack totals.
continue;
}
if (matchPrefix (argv[i], "-target", 5)) {
i++;
continue;
}
if (is_dash_arg_prefix(argv[i], "ads", 2)) {
++i;
continue;
}
if( matchPrefix(argv[i], "-sort", 3) ) {
i++;
if ( ! noSort) {
sprintf( buffer, "%s =!= UNDEFINED", argv[i] );
query->addANDConstraint( buffer );
}
continue;
}
if (matchPrefix (argv[i], "-statistics", 6)) {
i += 2;
sprintf(buffer,"STATISTICS_TO_PUBLISH = \"%s\"", statistics);
if (diagnose) {
printf ("[%s]\n", buffer);
}
query->addExtraAttribute(buffer);
continue;
}
if (matchPrefix (argv[i], "-attributes", 3) ) {
// parse attributes to be selected and split them along ","
StringList more_attrs(argv[i+1],",");
char const *s;
more_attrs.rewind();
while( (s=more_attrs.next()) ) {
projList.AppendArg(s);
}
i++;
continue;
}
// figure out what the other parameters should do
if (*argv[i] != '-') {
// display extra information for diagnosis
if (diagnose) {
printf ("Arg %d (%s) --- adding constraint", i, argv[i]);
}
if( !(daemonname = get_daemon_name(argv[i])) ) {
if ( (mode==MODE_SCHEDD_SUBMITTORS) && strchr(argv[i],'@') ) {
// For a submittor query, it is possible that the
// hostname is really a UID_DOMAIN. And there is
// no requirement that UID_DOMAIN actually have
// an inverse lookup in DNS... so if get_daemon_name()
// fails with a fully qualified submittor lookup, just
// use what we are given and do not flag an error.
daemonname = strnewp(argv[i]);
} else {
dprintf_WriteOnErrorBuffer(stderr, true);
fprintf( stderr, "%s: unknown host %s\n",
argv[0], get_host_part(argv[i]) );
exit(1);
}
}
switch (mode) {
case MODE_DEFRAG_NORMAL:
case MODE_STARTD_NORMAL:
case MODE_STARTD_COD:
#ifdef HAVE_EXT_POSTGRESQL
case MODE_QUILL_NORMAL:
#endif /* HAVE_EXT_POSTGRESQL */
case MODE_SCHEDD_NORMAL:
case MODE_SCHEDD_SUBMITTORS:
case MODE_MASTER_NORMAL:
case MODE_COLLECTOR_NORMAL:
case MODE_CKPT_SRVR_NORMAL:
case MODE_NEGOTIATOR_NORMAL:
case MODE_STORAGE_NORMAL:
case MODE_ANY_NORMAL:
case MODE_GENERIC_NORMAL:
case MODE_STARTD_AVAIL:
case MODE_OTHER:
case MODE_GRID_NORMAL:
case MODE_HAD_NORMAL:
sprintf(buffer,"(%s==\"%s\") || (%s==\"%s\")",
ATTR_NAME, daemonname, ATTR_MACHINE, daemonname );
if (diagnose) {
printf ("[%s]\n", buffer);
}
query->addORConstraint (buffer);
break;
case MODE_STARTD_RUN:
sprintf (buffer,"%s == \"%s\"",ATTR_REMOTE_USER,argv[i]);
if (diagnose) {
printf ("[%s]\n", buffer);
}
query->addORConstraint (buffer);
break;
default:
fprintf(stderr,"Error: Don't know how to process %s\n",argv[i]);
}
delete [] daemonname;
daemonname = NULL;
} else
if (matchPrefix (argv[i], "-constraint", 4)) {
if (diagnose) {
printf ("[%s]\n", argv[i+1]);
}
query->addANDConstraint (argv[i+1]);
i++;
}
}
}
int
matchPrefix (const char *s1, const char *s2, int min_len)
{
int lenS1 = strlen (s1);
int lenS2 = strlen (s2);
int len = (lenS1 < lenS2) ? lenS1 : lenS2;
if(len < min_len) {
return 0;
}
return (strncmp (s1, s2, len) == 0);
}
int
lessThanFunc(AttrList *ad1, AttrList *ad2, void *)
{
MyString buf1;
MyString buf2;
int val;
if( !ad1->LookupString(ATTR_OPSYS, buf1) ||
!ad2->LookupString(ATTR_OPSYS, buf2) ) {
buf1 = "";
buf2 = "";
}
val = strcmp( buf1.Value(), buf2.Value() );
if( val ) {
return (val < 0);
}
if( !ad1->LookupString(ATTR_ARCH, buf1) ||
!ad2->LookupString(ATTR_ARCH, buf2) ) {
buf1 = "";
buf2 = "";
}
val = strcmp( buf1.Value(), buf2.Value() );
if( val ) {
return (val < 0);
}
if( !ad1->LookupString(ATTR_MACHINE, buf1) ||
!ad2->LookupString(ATTR_MACHINE, buf2) ) {
buf1 = "";
buf2 = "";
}
val = strcmp( buf1.Value(), buf2.Value() );
if( val ) {
return (val < 0);
}
if (!ad1->LookupString(ATTR_NAME, buf1) ||
!ad2->LookupString(ATTR_NAME, buf2))
return 0;
return ( strcmp( buf1.Value(), buf2.Value() ) < 0 );
}
int
customLessThanFunc( AttrList *ad1, AttrList *ad2, void *)
{
classad::Value lt_result;
bool val;
for (unsigned i = 0; i < sortSpecs.size(); ++i) {
if (EvalExprTree(sortSpecs[i].exprLT, ad1, ad2, lt_result)
&& lt_result.IsBooleanValue(val) ) {
if( val ) {
return 1;
} else {
if (EvalExprTree( sortSpecs[i].exprEQ, ad1,
ad2, lt_result ) &&
( !lt_result.IsBooleanValue(val) || !val )){
return 0;
}
}
} else {
return 0;
}
}
return 0;
}
| zhangzhehust/htcondor | src/condor_status.V6/status.cpp | C++ | apache-2.0 | 43,130 |
#
# Copyright (C) 2007-2011 OpenWrt.org
#
# This is free software, licensed under the GNU General Public License v2.
# See /LICENSE for more information.
#
include $(TOPDIR)/rules.mk
PKG_NAME:=tcpdump
PKG_VERSION:=4.2.1
PKG_RELEASE:=3
PKG_SOURCE:=$(PKG_NAME)-$(PKG_VERSION).tar.gz
PKG_SOURCE_URL:=http://www.tcpdump.org/release/ \
http://ftp.gwdg.de/pub/misc/tcpdump/ \
http://www.at.tcpdump.org/ \
http://www.br.tcpdump.org/
PKG_MD5SUM:=c202878c6db054767b52651041b9e60e
PKG_BUILD_DIR:=$(BUILD_DIR)/$(PKG_NAME)-$(BUILD_VARIANT)/$(PKG_NAME)-$(PKG_VERSION)
PKG_BUILD_PARALLEL:=1
PKG_MAINTAINER:=Felix Fietkau <[email protected]>
PKG_INSTALL:=1
include $(INCLUDE_DIR)/package.mk
define Package/tcpdump/default
SECTION:=net
CATEGORY:=Network
DEPENDS:=+libpcap
TITLE:=Network monitoring and data acquisition tool
URL:=http://www.tcpdump.org/
endef
define Package/tcpdump
$(Package/tcpdump/default)
VARIANT:=full
endef
define Package/tcpdump-mini
$(Package/tcpdump/default)
TITLE+= (minimal version)
VARIANT:=mini
endef
CONFIGURE_ARGS += \
--without-crypto
ifeq ($(CONFIG_IPV6),y)
CONFIGURE_ARGS += \
--enable-ipv6
endif
TARGET_CFLAGS += -ffunction-sections -fdata-sections
TARGET_LDFLAGS += -Wl,--gc-sections
CONFIGURE_VARS += \
BUILD_CC="$(TARGET_CC)" \
HOSTCC="$(HOSTCC)" \
td_cv_buggygetaddrinfo="no" \
ac_cv_linux_vers=$(LINUX_VERSION) \
ac_cv_header_rpc_rpcent_h=no \
ac_cv_lib_rpc_main=no \
ac_cv_path_PCAP_CONFIG=""
MAKE_FLAGS :=
ifeq ($(BUILD_VARIANT),mini)
TARGET_CFLAGS += -DTCPDUMP_MINI
CONFIGURE_ARGS += --disable-smb
MAKE_FLAGS += TCPDUMP_MINI=1
endif
MAKE_FLAGS += \
CCOPT="$(TARGET_CFLAGS)" INCLS="-I. $(TARGET_CPPFLAGS)"
define Package/tcpdump/install
$(INSTALL_DIR) $(1)/usr/sbin
$(INSTALL_BIN) $(PKG_INSTALL_DIR)/usr/sbin/tcpdump $(1)/usr/sbin/
endef
Package/tcpdump-mini/install = $(Package/tcpdump/install)
$(eval $(call BuildPackage,tcpdump))
$(eval $(call BuildPackage,tcpdump-mini))
| whble/trunk | package/network/utils/tcpdump/Makefile | Makefile | apache-2.0 | 2,050 |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package entities;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.Lob;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* @author Maarten De Weerdt
*/
@Entity
@Table(name = "Product")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "Product.findAll", query = "SELECT p FROM Product p")
, @NamedQuery(name = "Product.findById", query = "SELECT p FROM Product p WHERE p.id = :id")
, @NamedQuery(name = "Product.findByPrijs", query = "SELECT p FROM Product p WHERE p.prijs = :prijs")
, @NamedQuery(name = "Product.findByCategorie", query = "SELECT p FROM Product p WHERE p.categorieNaam = :categorieNaam")
})
public class Product implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "ID")
private Integer id;
@Basic(optional = false)
@NotNull
@Lob
@Size(min = 1, max = 65535)
@Column(name = "Naam")
private String naam;
@Basic(optional = false)
@NotNull
@Lob
@Size(min = 1, max = 65535)
@Column(name = "Omschrijving")
private String omschrijving;
@Basic(optional = false)
@NotNull
@Column(name = "Prijs")
private double prijs;
@Basic(optional = false)
@NotNull
@Lob
@Size(min = 1, max = 65535)
@Column(name = "Afbeelding")
private String afbeelding;
@Lob
@Size(max = 65535)
@Column(name = "Informatie")
private String informatie;
@JoinColumn(name = "CategorieNaam", referencedColumnName = "CategorieNaam")
@ManyToOne(optional = false)
private Categorie categorieNaam;
public Product() {
}
public Product(Integer id) {
this.id = id;
}
public Product(Integer id, String naam, String omschrijving, double prijs, String afbeelding) {
this.id = id;
this.naam = naam;
this.omschrijving = omschrijving;
this.prijs = prijs;
this.afbeelding = afbeelding;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getNaam() {
return naam;
}
public void setNaam(String naam) {
this.naam = naam;
}
public String getOmschrijving() {
return omschrijving;
}
public void setOmschrijving(String omschrijving) {
this.omschrijving = omschrijving;
}
public double getPrijs() {
return prijs;
}
public void setPrijs(double prijs) {
this.prijs = prijs;
}
public String getAfbeelding() {
return afbeelding;
}
public void setAfbeelding(String afbeelding) {
this.afbeelding = afbeelding;
}
public String getInformatie() {
return informatie;
}
public void setInformatie(String informatie) {
this.informatie = informatie;
}
public Categorie getCategorieNaam() {
return categorieNaam;
}
public void setCategorieNaam(Categorie categorieNaam) {
this.categorieNaam = categorieNaam;
}
@Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Product)) {
return false;
}
Product other = (Product) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
@Override
public String toString() {
return "entities.Product[ id=" + id + " ]";
}
}
| MaartenDeWeerdt/TomEnJerry | TomEnJerry-ejb/src/java/entities/Product.java | Java | apache-2.0 | 4,620 |
/*
* Copyright (C) 2018 The Dagger 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 dagger.internal.codegen.validation;
import static com.google.auto.common.MoreTypes.asDeclared;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Predicates.in;
import static com.google.common.collect.Collections2.transform;
import static com.google.common.collect.Iterables.getOnlyElement;
import static dagger.internal.codegen.base.ComponentAnnotation.rootComponentAnnotation;
import static dagger.internal.codegen.base.DiagnosticFormatting.stripCommonTypePrefixes;
import static dagger.internal.codegen.base.Formatter.INDENT;
import static dagger.internal.codegen.base.Scopes.getReadableSource;
import static dagger.internal.codegen.base.Scopes.scopesOf;
import static dagger.internal.codegen.base.Scopes.singletonScope;
import static dagger.internal.codegen.base.Util.reentrantComputeIfAbsent;
import static dagger.internal.codegen.extension.DaggerStreams.toImmutableSet;
import static dagger.internal.codegen.extension.DaggerStreams.toImmutableSetMultimap;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;
import static javax.tools.Diagnostic.Kind.ERROR;
import com.google.auto.common.MoreElements;
import com.google.auto.common.MoreTypes;
import com.google.common.base.Equivalence.Wrapper;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSetMultimap;
import com.google.common.collect.Multimaps;
import com.google.common.collect.Sets;
import dagger.internal.codegen.binding.ComponentCreatorDescriptor;
import dagger.internal.codegen.binding.ComponentDescriptor;
import dagger.internal.codegen.binding.ComponentRequirement;
import dagger.internal.codegen.binding.ComponentRequirement.NullPolicy;
import dagger.internal.codegen.binding.ContributionBinding;
import dagger.internal.codegen.binding.ErrorMessages;
import dagger.internal.codegen.binding.ErrorMessages.ComponentCreatorMessages;
import dagger.internal.codegen.binding.MethodSignatureFormatter;
import dagger.internal.codegen.binding.ModuleDescriptor;
import dagger.internal.codegen.compileroption.CompilerOptions;
import dagger.internal.codegen.compileroption.ValidationType;
import dagger.internal.codegen.langmodel.DaggerElements;
import dagger.internal.codegen.langmodel.DaggerTypes;
import dagger.model.Scope;
import java.util.ArrayDeque;
import java.util.Collection;
import java.util.Deque;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.Set;
import java.util.StringJoiner;
import javax.inject.Inject;
import javax.lang.model.element.Element;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.ExecutableType;
import javax.lang.model.type.TypeMirror;
import javax.tools.Diagnostic;
/**
* Reports errors in the component hierarchy.
*
* <ul>
* <li>Validates scope hierarchy of component dependencies and subcomponents.
* <li>Reports errors if there are component dependency cycles.
* <li>Reports errors if any abstract modules have non-abstract instance binding methods.
* <li>Validates component creator types.
* </ul>
*/
// TODO(dpb): Combine with ComponentHierarchyValidator.
public final class ComponentDescriptorValidator {
private final DaggerElements elements;
private final DaggerTypes types;
private final CompilerOptions compilerOptions;
private final MethodSignatureFormatter methodSignatureFormatter;
private final ComponentHierarchyValidator componentHierarchyValidator;
@Inject
ComponentDescriptorValidator(
DaggerElements elements,
DaggerTypes types,
CompilerOptions compilerOptions,
MethodSignatureFormatter methodSignatureFormatter,
ComponentHierarchyValidator componentHierarchyValidator) {
this.elements = elements;
this.types = types;
this.compilerOptions = compilerOptions;
this.methodSignatureFormatter = methodSignatureFormatter;
this.componentHierarchyValidator = componentHierarchyValidator;
}
public ValidationReport<TypeElement> validate(ComponentDescriptor component) {
ComponentValidation validation = new ComponentValidation(component);
validation.visitComponent(component);
validation.report(component).addSubreport(componentHierarchyValidator.validate(component));
return validation.buildReport();
}
private final class ComponentValidation {
final ComponentDescriptor rootComponent;
final Map<ComponentDescriptor, ValidationReport.Builder<TypeElement>> reports =
new LinkedHashMap<>();
ComponentValidation(ComponentDescriptor rootComponent) {
this.rootComponent = checkNotNull(rootComponent);
}
/** Returns a report that contains all validation messages found during traversal. */
ValidationReport<TypeElement> buildReport() {
ValidationReport.Builder<TypeElement> report =
ValidationReport.about(rootComponent.typeElement());
reports.values().forEach(subreport -> report.addSubreport(subreport.build()));
return report.build();
}
/** Returns the report builder for a (sub)component. */
private ValidationReport.Builder<TypeElement> report(ComponentDescriptor component) {
return reentrantComputeIfAbsent(
reports, component, descriptor -> ValidationReport.about(descriptor.typeElement()));
}
private void reportComponentItem(
Diagnostic.Kind kind, ComponentDescriptor component, String message) {
report(component)
.addItem(message, kind, component.typeElement(), component.annotation().annotation());
}
private void reportComponentError(ComponentDescriptor component, String error) {
reportComponentItem(ERROR, component, error);
}
void visitComponent(ComponentDescriptor component) {
validateDependencyScopes(component);
validateComponentDependencyHierarchy(component);
validateModules(component);
validateCreators(component);
component.childComponents().forEach(this::visitComponent);
}
/** Validates that component dependencies do not form a cycle. */
private void validateComponentDependencyHierarchy(ComponentDescriptor component) {
validateComponentDependencyHierarchy(component, component.typeElement(), new ArrayDeque<>());
}
/** Recursive method to validate that component dependencies do not form a cycle. */
private void validateComponentDependencyHierarchy(
ComponentDescriptor component, TypeElement dependency, Deque<TypeElement> dependencyStack) {
if (dependencyStack.contains(dependency)) {
// Current component has already appeared in the component chain.
StringBuilder message = new StringBuilder();
message.append(component.typeElement().getQualifiedName());
message.append(" contains a cycle in its component dependencies:\n");
dependencyStack.push(dependency);
appendIndentedComponentsList(message, dependencyStack);
dependencyStack.pop();
reportComponentItem(
compilerOptions.scopeCycleValidationType().diagnosticKind().get(),
component,
message.toString());
} else {
rootComponentAnnotation(dependency)
.ifPresent(
componentAnnotation -> {
dependencyStack.push(dependency);
for (TypeElement nextDependency : componentAnnotation.dependencies()) {
validateComponentDependencyHierarchy(
component, nextDependency, dependencyStack);
}
dependencyStack.pop();
});
}
}
/**
* Validates that among the dependencies are at most one scoped dependency, that there are no
* cycles within the scoping chain, and that singleton components have no scoped dependencies.
*/
private void validateDependencyScopes(ComponentDescriptor component) {
ImmutableSet<Scope> scopes = component.scopes();
ImmutableSet<TypeElement> scopedDependencies =
scopedTypesIn(
component
.dependencies()
.stream()
.map(ComponentRequirement::typeElement)
.collect(toImmutableSet()));
if (!scopes.isEmpty()) {
Scope singletonScope = singletonScope(elements);
// Dagger 1.x scope compatibility requires this be suppress-able.
if (compilerOptions.scopeCycleValidationType().diagnosticKind().isPresent()
&& scopes.contains(singletonScope)) {
// Singleton is a special-case representing the longest lifetime, and therefore
// @Singleton components may not depend on scoped components
if (!scopedDependencies.isEmpty()) {
StringBuilder message =
new StringBuilder(
"This @Singleton component cannot depend on scoped components:\n");
appendIndentedComponentsList(message, scopedDependencies);
reportComponentItem(
compilerOptions.scopeCycleValidationType().diagnosticKind().get(),
component,
message.toString());
}
} else if (scopedDependencies.size() > 1) {
// Scoped components may depend on at most one scoped component.
StringBuilder message = new StringBuilder();
for (Scope scope : scopes) {
message.append(getReadableSource(scope)).append(' ');
}
message
.append(component.typeElement().getQualifiedName())
.append(" depends on more than one scoped component:\n");
appendIndentedComponentsList(message, scopedDependencies);
reportComponentError(component, message.toString());
} else {
// Dagger 1.x scope compatibility requires this be suppress-able.
if (!compilerOptions.scopeCycleValidationType().equals(ValidationType.NONE)) {
validateDependencyScopeHierarchy(
component, component.typeElement(), new ArrayDeque<>(), new ArrayDeque<>());
}
}
} else {
// Scopeless components may not depend on scoped components.
if (!scopedDependencies.isEmpty()) {
StringBuilder message =
new StringBuilder(component.typeElement().getQualifiedName())
.append(" (unscoped) cannot depend on scoped components:\n");
appendIndentedComponentsList(message, scopedDependencies);
reportComponentError(component, message.toString());
}
}
}
private void validateModules(ComponentDescriptor component) {
for (ModuleDescriptor module : component.modules()) {
if (module.moduleElement().getModifiers().contains(Modifier.ABSTRACT)) {
for (ContributionBinding binding : module.bindings()) {
if (binding.requiresModuleInstance()) {
report(component).addError(abstractModuleHasInstanceBindingMethodsError(module));
break;
}
}
}
}
}
private String abstractModuleHasInstanceBindingMethodsError(ModuleDescriptor module) {
String methodAnnotations;
switch (module.kind()) {
case MODULE:
methodAnnotations = "@Provides";
break;
case PRODUCER_MODULE:
methodAnnotations = "@Provides or @Produces";
break;
default:
throw new AssertionError(module.kind());
}
return String.format(
"%s is abstract and has instance %s methods. Consider making the methods static or "
+ "including a non-abstract subclass of the module instead.",
module.moduleElement(), methodAnnotations);
}
private void validateCreators(ComponentDescriptor component) {
if (!component.creatorDescriptor().isPresent()) {
// If no builder, nothing to validate.
return;
}
ComponentCreatorDescriptor creator = component.creatorDescriptor().get();
ComponentCreatorMessages messages = ErrorMessages.creatorMessagesFor(creator.annotation());
// Requirements for modules and dependencies that the creator can set
Set<ComponentRequirement> creatorModuleAndDependencyRequirements =
creator.moduleAndDependencyRequirements();
// Modules and dependencies the component requires
Set<ComponentRequirement> componentModuleAndDependencyRequirements =
component.dependenciesAndConcreteModules();
// Requirements that the creator can set that don't match any requirements that the component
// actually has.
Set<ComponentRequirement> inapplicableRequirementsOnCreator =
Sets.difference(
creatorModuleAndDependencyRequirements, componentModuleAndDependencyRequirements);
DeclaredType container = asDeclared(creator.typeElement().asType());
if (!inapplicableRequirementsOnCreator.isEmpty()) {
Collection<Element> excessElements =
Multimaps.filterKeys(
creator.unvalidatedRequirementElements(), in(inapplicableRequirementsOnCreator))
.values();
String formatted =
excessElements.stream()
.map(element -> formatElement(element, container))
.collect(joining(", ", "[", "]"));
report(component)
.addError(String.format(messages.extraSetters(), formatted), creator.typeElement());
}
// Component requirements that the creator must be able to set
Set<ComponentRequirement> mustBePassed =
Sets.filter(
componentModuleAndDependencyRequirements,
input -> input.nullPolicy(elements, types).equals(NullPolicy.THROW));
// Component requirements that the creator must be able to set, but can't
Set<ComponentRequirement> missingRequirements =
Sets.difference(mustBePassed, creatorModuleAndDependencyRequirements);
if (!missingRequirements.isEmpty()) {
report(component)
.addError(
String.format(
messages.missingSetters(),
missingRequirements.stream().map(ComponentRequirement::type).collect(toList())),
creator.typeElement());
}
// Validate that declared creator requirements (modules, dependencies) have unique types.
ImmutableSetMultimap<Wrapper<TypeMirror>, Element> declaredRequirementsByType =
Multimaps.filterKeys(
creator.unvalidatedRequirementElements(),
creatorModuleAndDependencyRequirements::contains)
.entries().stream()
.collect(
toImmutableSetMultimap(entry -> entry.getKey().wrappedType(), Entry::getValue));
declaredRequirementsByType
.asMap()
.forEach(
(typeWrapper, elementsForType) -> {
if (elementsForType.size() > 1) {
TypeMirror type = typeWrapper.get();
// TODO(cgdecker): Attach this error message to the factory method rather than
// the component type if the elements are factory method parameters AND the
// factory method is defined by the factory type itself and not by a supertype.
report(component)
.addError(
String.format(
messages.multipleSettersForModuleOrDependencyType(),
type,
transform(
elementsForType, element -> formatElement(element, container))),
creator.typeElement());
}
});
// TODO(cgdecker): Duplicate binding validation should handle the case of multiple elements
// that set the same bound-instance Key, but validating that here would make it fail faster
// for subcomponents.
}
private String formatElement(Element element, DeclaredType container) {
// TODO(cgdecker): Extract some or all of this to another class?
// But note that it does different formatting for parameters than
// DaggerElements.elementToString(Element).
switch (element.getKind()) {
case METHOD:
return methodSignatureFormatter.format(
MoreElements.asExecutable(element), Optional.of(container));
case PARAMETER:
return formatParameter(MoreElements.asVariable(element), container);
default:
// This method shouldn't be called with any other type of element.
throw new AssertionError();
}
}
private String formatParameter(VariableElement parameter, DeclaredType container) {
// TODO(cgdecker): Possibly leave the type (and annotations?) off of the parameters here and
// just use their names, since the type will be redundant in the context of the error message.
StringJoiner joiner = new StringJoiner(" ");
parameter.getAnnotationMirrors().stream().map(Object::toString).forEach(joiner::add);
TypeMirror parameterType = resolveParameterType(parameter, container);
return joiner
.add(stripCommonTypePrefixes(parameterType.toString()))
.add(parameter.getSimpleName())
.toString();
}
private TypeMirror resolveParameterType(VariableElement parameter, DeclaredType container) {
ExecutableElement method =
MoreElements.asExecutable(parameter.getEnclosingElement());
int parameterIndex = method.getParameters().indexOf(parameter);
ExecutableType methodType = MoreTypes.asExecutable(types.asMemberOf(container, method));
return methodType.getParameterTypes().get(parameterIndex);
}
/**
* Validates that scopes do not participate in a scoping cycle - that is to say, scoped
* components are in a hierarchical relationship terminating with Singleton.
*
* <p>As a side-effect, this means scoped components cannot have a dependency cycle between
* themselves, since a component's presence within its own dependency path implies a cyclical
* relationship between scopes. However, cycles in component dependencies are explicitly checked
* in {@link #validateComponentDependencyHierarchy(ComponentDescriptor)}.
*/
private void validateDependencyScopeHierarchy(
ComponentDescriptor component,
TypeElement dependency,
Deque<ImmutableSet<Scope>> scopeStack,
Deque<TypeElement> scopedDependencyStack) {
ImmutableSet<Scope> scopes = scopesOf(dependency);
if (stackOverlaps(scopeStack, scopes)) {
scopedDependencyStack.push(dependency);
// Current scope has already appeared in the component chain.
StringBuilder message = new StringBuilder();
message.append(component.typeElement().getQualifiedName());
message.append(" depends on scoped components in a non-hierarchical scope ordering:\n");
appendIndentedComponentsList(message, scopedDependencyStack);
if (compilerOptions.scopeCycleValidationType().diagnosticKind().isPresent()) {
reportComponentItem(
compilerOptions.scopeCycleValidationType().diagnosticKind().get(),
component,
message.toString());
}
scopedDependencyStack.pop();
} else {
// TODO(beder): transitively check scopes of production components too.
rootComponentAnnotation(dependency)
.filter(componentAnnotation -> !componentAnnotation.isProduction())
.ifPresent(
componentAnnotation -> {
ImmutableSet<TypeElement> scopedDependencies =
scopedTypesIn(componentAnnotation.dependencies());
if (scopedDependencies.size() == 1) {
// empty can be ignored (base-case), and > 1 is a separately-reported error.
scopeStack.push(scopes);
scopedDependencyStack.push(dependency);
validateDependencyScopeHierarchy(
component,
getOnlyElement(scopedDependencies),
scopeStack,
scopedDependencyStack);
scopedDependencyStack.pop();
scopeStack.pop();
}
}); // else: we skip component dependencies which are not components
}
}
private <T> boolean stackOverlaps(Deque<ImmutableSet<T>> stack, ImmutableSet<T> set) {
for (ImmutableSet<T> entry : stack) {
if (!Sets.intersection(entry, set).isEmpty()) {
return true;
}
}
return false;
}
/** Appends and formats a list of indented component types (with their scope annotations). */
private void appendIndentedComponentsList(StringBuilder message, Iterable<TypeElement> types) {
for (TypeElement scopedComponent : types) {
message.append(INDENT);
for (Scope scope : scopesOf(scopedComponent)) {
message.append(getReadableSource(scope)).append(' ');
}
message
.append(stripCommonTypePrefixes(scopedComponent.getQualifiedName().toString()))
.append('\n');
}
}
/**
* Returns a set of type elements containing only those found in the input set that have a
* scoping annotation.
*/
private ImmutableSet<TypeElement> scopedTypesIn(Collection<TypeElement> types) {
return types.stream().filter(type -> !scopesOf(type).isEmpty()).collect(toImmutableSet());
}
}
}
| cgruber/dagger | java/dagger/internal/codegen/validation/ComponentDescriptorValidator.java | Java | apache-2.0 | 22,500 |
.home {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
padding-top: 5rem;
text-align: center;
color: $colorTheme;
}
.link {
margin-bottom: $s1;
}
| tribou/react-template | src/components/routes/examples/Home/Home.style.css | CSS | apache-2.0 | 201 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ungarc0r
{
static class Program
{
/// <summary>
/// Der Haupteinstiegspunkt für die Anwendung.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
| manuth/ungarc0r | GameArchiver/Program.cs | C# | apache-2.0 | 511 |
import errno
import os
import pwd
import shutil
import sys
from jinja2 import Environment, FileSystemLoader
class TutorialEnv:
LOCAL_MACHINE = ("Local Machine Condor Pool", "submit-host")
USC_HPCC_CLUSTER = ("USC HPCC Cluster", "usc-hpcc")
OSG_FROM_ISI = ("OSG from ISI submit node", "osg")
XSEDE_BOSCO = ("XSEDE, with Bosco", "xsede-bosco")
BLUEWATERS_GLITE = ("Bluewaters, with Glite", "bw-glite")
TACC_WRANGLER = ("TACC Wrangler with Glite", "wrangler-glite")
OLCF_TITAN = ("OLCF TITAN with Glite", "titan-glite")
OLCF_SUMMIT_KUBERNETES_BOSCO = (
"OLCF Summit from Kubernetes using BOSCO",
"summit-kub-bosco",
)
class TutorialExample:
PROCESS = ("Process", "process")
PIPELINE = ("Pipeline", "pipeline")
SPLIT = ("Split", "split")
MERGE = ("Merge", "merge")
EPA = ("EPA (requires R)", "r-epa")
DIAMOND = ("Diamond", "diamond")
CONTAINER = ("Population Modeling using Containers", "population")
MPI = ("MPI Hello World", "mpi-hw")
def choice(question, options, default):
"Ask the user to choose from a short list of named options"
while True:
sys.stdout.write("{} ({}) [{}]: ".format(question, "/".join(options), default))
answer = sys.stdin.readline().strip()
if len(answer) == 0:
return default
for opt in options:
if answer == opt:
return answer
def yesno(question, default="y"):
"Ask the user a yes/no question"
while True:
sys.stdout.write("{} (y/n) [{}]: ".format(question, default))
answer = sys.stdin.readline().strip().lower()
if len(answer) == 0:
answer = default
if answer == "y":
return True
elif answer == "n":
return False
def query(question, default=None):
"Ask the user a question and return the response"
while True:
if default:
sys.stdout.write("{} [{}]: ".format(question, default))
else:
sys.stdout.write("%s: " % question)
answer = sys.stdin.readline().strip().replace(" ", "_")
if answer == "":
if default:
return default
else:
return answer
def optionlist(question, options, default=0):
"Ask the user to choose from a list of options"
for i, option in enumerate(options):
print("%d: %s" % (i + 1, option[0]))
while True:
sys.stdout.write("%s (1-%d) [%d]: " % (question, len(options), default + 1))
answer = sys.stdin.readline().strip()
if len(answer) == 0:
return options[default][1]
try:
optno = int(answer)
if optno > 0 and optno <= len(options):
return options[optno - 1][1]
except Exception:
pass
class Workflow:
def __init__(self, workflowdir, sharedir):
self.jinja = Environment(loader=FileSystemLoader(sharedir), trim_blocks=True)
self.name = os.path.basename(workflowdir)
self.workflowdir = workflowdir
self.sharedir = sharedir
self.properties = {}
self.home = os.environ["HOME"]
self.user = pwd.getpwuid(os.getuid())[0]
self.tutorial = None
self.generate_tutorial = False
self.tutorial_setup = None
self.compute_queue = "default"
self.project = "MYPROJ123"
sysname, _, _, _, machine = os.uname()
if sysname == "Darwin":
self.os = "MACOSX"
else:
# Probably Linux
self.os = sysname.upper()
self.arch = machine
def copy_template(self, template, dest, mode=0o644):
"Copy template to dest in workflowdir with mode"
path = os.path.join(self.workflowdir, dest)
t = self.jinja.get_template(template)
t.stream(**self.__dict__).dump(path)
os.chmod(path, mode)
def copy_dir(self, src, dest):
# self.mkdir(dest)
if not src.startswith("/"):
src = os.path.join(self.sharedir, src)
try:
dest = os.path.join(self.workflowdir, dest)
shutil.copytree(src, dest)
except OSError as exc: # python >2.5
if exc.errno == errno.ENOTDIR:
shutil.copy(src, dest)
else:
raise
def mkdir(self, path):
"Make relative directory in workflowdir"
path = os.path.join(self.workflowdir, path)
if not os.path.exists(path):
os.makedirs(path)
def configure(self):
# The tutorial is a special case
if yesno("Do you want to generate a tutorial workflow?", "n"):
self.config = "tutorial"
self.daxgen = "tutorial"
self.generate_tutorial = True
# determine the environment to setup tutorial for
self.tutorial_setup = optionlist(
"What environment is tutorial to be setup for?",
[
TutorialEnv.LOCAL_MACHINE,
TutorialEnv.USC_HPCC_CLUSTER,
TutorialEnv.OSG_FROM_ISI,
TutorialEnv.XSEDE_BOSCO,
TutorialEnv.BLUEWATERS_GLITE,
TutorialEnv.TACC_WRANGLER,
TutorialEnv.OLCF_TITAN,
TutorialEnv.OLCF_SUMMIT_KUBERNETES_BOSCO,
],
)
# figure out what example options to provide
examples = [
TutorialExample.PROCESS,
TutorialExample.PIPELINE,
TutorialExample.SPLIT,
TutorialExample.MERGE,
TutorialExample.EPA,
TutorialExample.CONTAINER,
]
if self.tutorial_setup != "osg":
examples.append(TutorialExample.DIAMOND)
if self.tutorial_setup in [
"bw-glite",
"wrangler-glite",
"titan-glite",
"summit-kub-bosco",
]:
examples.append(TutorialExample.MPI)
self.project = query(
"What project your jobs should run under. For example on TACC there are like : TG-DDM160003 ?"
)
self.tutorial = optionlist("What tutorial workflow do you want?", examples)
self.setup_tutorial()
return
# Determine which DAX generator API to use
self.daxgen = choice(
"What DAX generator API do you want to use?",
["python", "perl", "java", "r"],
"python",
)
# Determine what kind of site catalog we need to generate
self.config = optionlist(
"What does your computing infrastructure look like?",
[
("Local Machine Condor Pool", "condorpool"),
("Remote Cluster using Globus GRAM", "globus"),
("Remote Cluster using CREAMCE", "creamce"),
("Local PBS Cluster with Glite", "glite"),
("Remote PBS Cluster with BOSCO and SSH", "bosco"),
],
)
# Find out some information about the site
self.sitename = query("What do you want to call your compute site?", "compute")
self.os = choice(
"What OS does your compute site have?", ["LINUX", "MACOSX"], self.os
)
self.arch = choice(
"What architecture does your compute site have?",
["x86_64", "x86"],
self.arch,
)
def setup_tutorial(self):
"""
Set up tutorial for pre-defined computing environments
:return:
"""
if self.tutorial_setup is None:
self.tutorial_setup = "submit-host"
if self.tutorial_setup == "submit-host":
self.sitename = "condorpool"
elif self.tutorial_setup == "usc-hpcc":
self.sitename = "usc-hpcc"
self.config = "glite"
self.compute_queue = "quick"
# for running the whole workflow as mpi job
self.properties["pegasus.job.aggregator"] = "mpiexec"
elif self.tutorial_setup == "osg":
self.sitename = "osg"
self.os = "linux"
if not yesno("Do you want to use Condor file transfers", "y"):
self.staging_site = "isi_workflow"
elif self.tutorial_setup == "xsede-bosco":
self.sitename = "condorpool"
elif self.tutorial_setup == "bw-glite":
self.sitename = "bluewaters"
self.config = "glite"
self.compute_queue = "normal"
elif self.tutorial_setup == "wrangler-glite":
self.sitename = "wrangler"
self.config = "glite"
self.compute_queue = "normal"
elif self.tutorial_setup == "titan-glite":
self.sitename = "titan"
self.config = "glite"
self.compute_queue = "titan"
elif self.tutorial_setup == "summit-kub-bosco":
self.sitename = "summit"
self.config = "bosco"
self.compute_queue = "batch"
return
def generate(self):
os.makedirs(self.workflowdir)
if self.tutorial != "population":
self.mkdir("input")
self.mkdir("output")
if self.generate_tutorial:
self.copy_template("%s/tc.txt" % self.tutorial, "tc.txt")
if self.tutorial == "r-epa":
self.copy_template("%s/daxgen.R" % self.tutorial, "daxgen.R")
elif self.tutorial != "mpi-hw":
self.copy_template("%s/daxgen.py" % self.tutorial, "daxgen.py")
if self.tutorial == "diamond":
# Executables used by the diamond workflow
self.mkdir("bin")
self.copy_template(
"diamond/transformation.py", "bin/preprocess", mode=0o755
)
self.copy_template(
"diamond/transformation.py", "bin/findrange", mode=0o755
)
self.copy_template(
"diamond/transformation.py", "bin/analyze", mode=0o755
)
# Diamond input file
self.copy_template("diamond/f.a", "input/f.a")
elif self.tutorial == "split":
# Split workflow input file
self.mkdir("bin")
self.copy_template("split/pegasus.html", "input/pegasus.html")
elif self.tutorial == "r-epa":
# Executables used by the R-EPA workflow
self.mkdir("bin")
self.copy_template(
"r-epa/epa-wrapper.sh", "bin/epa-wrapper.sh", mode=0o755
)
self.copy_template("r-epa/setupvar.R", "bin/setupvar.R", mode=0o755)
self.copy_template(
"r-epa/weighted.average.R", "bin/weighted.average.R", mode=0o755
)
self.copy_template(
"r-epa/cumulative.percentiles.R",
"bin/cumulative.percentiles.R",
mode=0o755,
)
elif self.tutorial == "population":
self.copy_template("%s/Dockerfile" % self.tutorial, "Dockerfile")
self.copy_template("%s/Singularity" % self.tutorial, "Singularity")
self.copy_template(
"%s/tc.txt.containers" % self.tutorial, "tc.txt.containers"
)
self.copy_dir("%s/scripts" % self.tutorial, "scripts")
self.copy_dir("%s/data" % self.tutorial, "input")
# copy the mpi wrapper, c code and mpi
elif self.tutorial == "mpi-hw":
# copy the mpi wrapper, c code and mpi example
# Executables used by the mpi-hw workflow
self.mkdir("bin")
self.copy_template(
"%s/pegasus-mpi-hw.c" % self.tutorial, "pegasus-mpi-hw.c"
)
self.copy_template("%s/Makefile" % self.tutorial, "Makefile")
self.copy_template("%s/daxgen.py.template" % self.tutorial, "daxgen.py")
self.copy_template(
"%s/mpi-hello-world-wrapper" % self.tutorial,
"bin/mpi-hello-world-wrapper",
mode=0o755,
)
self.copy_template("split/pegasus.html", "input/f.in")
else:
self.copy_template("tc.txt", "tc.txt")
if self.daxgen == "python":
self.copy_template("daxgen/daxgen.py", "daxgen.py")
elif self.daxgen == "perl":
self.copy_template("daxgen/daxgen.pl", "daxgen.pl")
elif self.daxgen == "java":
self.copy_template("daxgen/DAXGen.java", "DAXGen.java")
elif self.daxgen == "r":
self.copy_template("daxgen/daxgen.R", "daxgen.R")
else:
assert False
self.copy_template("sites.xml", "sites.xml")
self.copy_template("plan_dax.sh", "plan_dax.sh", mode=0o755)
self.copy_template("plan_cluster_dax.sh", "plan_cluster_dax.sh", mode=0o755)
self.copy_template("generate_dax.sh", "generate_dax.sh", mode=0o755)
self.copy_template("README.md", "README.md")
self.copy_template("rc.txt", "rc.txt")
self.copy_template("pegasus.properties", "pegasus.properties")
if self.tutorial == "diamond":
if self.tutorial_setup == "wrangler-glite":
self.copy_template(
"pmc-wrapper.wrangler", "bin/pmc-wrapper", mode=0o755
)
elif self.tutorial_setup == "titan-glite":
self.copy_template("pmc-wrapper.titan", "bin/pmc-wrapper", mode=0o755)
elif self.tutorial_setup == "wrangler-glite":
self.copy_template(
"pmc-wrapper.wrangler", "bin/pmc-wrapper", mode=0o755
)
elif self.tutorial_setup == "summit-kub-bosco":
self.copy_template("pmc-wrapper.summit", "bin/pmc-wrapper", mode=0o755)
if self.generate_tutorial:
sys.stdout.write(
"Pegasus Tutorial setup for example workflow - %s for execution on %s in directory %s\n"
% (self.tutorial, self.tutorial_setup, self.workflowdir)
)
def usage():
print("Usage: %s WORKFLOW_DIR" % sys.argv[0])
def main(pegasus_share_dir):
if len(sys.argv) != 2:
usage()
exit(1)
if "-h" in sys.argv:
usage()
exit(1)
workflowdir = sys.argv[1]
if os.path.exists(workflowdir):
print("ERROR: WORKFLOW_DIR '%s' already exists" % workflowdir)
exit(1)
workflowdir = os.path.abspath(workflowdir)
sharedir = os.path.join(pegasus_share_dir, "init")
w = Workflow(workflowdir, sharedir)
w.configure()
w.generate()
| pegasus-isi/pegasus | packages/pegasus-python/src/Pegasus/init-old.py | Python | apache-2.0 | 14,973 |
// 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
//
// 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 code. DO NOT EDIT!
using gagvr = Google.Ads.GoogleAds.V10.Resources;
namespace Google.Ads.GoogleAds.V10.Services
{
public partial class BiddingDataExclusionOperation
{
/// <summary>
/// <see cref="gagvr::BiddingDataExclusionName"/>-typed view over the <see cref="Remove"/> resource name
/// property.
/// </summary>
public gagvr::BiddingDataExclusionName RemoveAsBiddingDataExclusionName
{
get => string.IsNullOrEmpty(Remove) ? null : gagvr::BiddingDataExclusionName.Parse(Remove, allowUnparsed: true);
set => Remove = value?.ToString() ?? "";
}
}
public partial class MutateBiddingDataExclusionsResult
{
/// <summary>
/// <see cref="gagvr::BiddingDataExclusionName"/>-typed view over the <see cref="ResourceName"/> resource name
/// property.
/// </summary>
public gagvr::BiddingDataExclusionName ResourceNameAsBiddingDataExclusionName
{
get => string.IsNullOrEmpty(ResourceName) ? null : gagvr::BiddingDataExclusionName.Parse(ResourceName, allowUnparsed: true);
set => ResourceName = value?.ToString() ?? "";
}
}
}
| googleads/google-ads-dotnet | src/V10/Services/BiddingDataExclusionServiceResourceNames.g.cs | C# | apache-2.0 | 1,806 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.7"/>
<title>FlatBuffers: Use in C++</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="navtree.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="resize.js"></script>
<script type="text/javascript" src="navtree.js"></script>
<script type="text/javascript">
$(document).ready(initResizable);
$(window).load(resizeHeight);
</script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td style="padding-left: 0.5em;">
<div id="projectname">FlatBuffers
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.7 -->
</div><!-- top -->
<div id="side-nav" class="ui-resizable side-nav-resizable">
<div id="nav-tree">
<div id="nav-tree-contents">
<div id="nav-sync" class="sync"></div>
</div>
</div>
<div id="splitbar" style="-moz-user-select:none;"
class="ui-resizable-handle">
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){initNavTree('md__cpp_usage.html','');});
</script>
<div id="doc-content">
<div class="header">
<div class="headertitle">
<div class="title">Use in C++ </div> </div>
</div><!--header-->
<div class="contents">
<div class="textblock"><p>Assuming you have written a schema using the above language in say <code>mygame.fbs</code> (FlatBuffer Schema, though the extension doesn't matter), you've generated a C++ header called <code>mygame_generated.h</code> using the compiler (e.g. <code>flatc -c mygame.fbs</code>), you can now start using this in your program by including the header. As noted, this header relies on <code>flatbuffers/flatbuffers.h</code>, which should be in your include path.</p>
<h3>Writing in C++</h3>
<p>To start creating a buffer, create an instance of <code>FlatBufferBuilder</code> which will contain the buffer as it grows:</p>
<div class="fragment"><div class="line">FlatBufferBuilder fbb;</div>
</div><!-- fragment --><p>Before we serialize a Monster, we need to first serialize any objects that are contained there-in, i.e. we serialize the data tree using depth first, pre-order traversal. This is generally easy to do on any tree structures. For example:</p>
<div class="fragment"><div class="line"><span class="keyword">auto</span> name = fbb.CreateString(<span class="stringliteral">"MyMonster"</span>);</div>
<div class="line"></div>
<div class="line"><span class="keywordtype">unsigned</span> <span class="keywordtype">char</span> inv[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };</div>
<div class="line"><span class="keyword">auto</span> inventory = fbb.CreateVector(inv, 10);</div>
</div><!-- fragment --><p><code>CreateString</code> and <code>CreateVector</code> serialize these two built-in datatypes, and return offsets into the serialized data indicating where they are stored, such that <code>Monster</code> below can refer to them.</p>
<p><code>CreateString</code> can also take an <code>std::string</code>, or a <code>const char *</code> with an explicit length, and is suitable for holding UTF-8 and binary data if needed.</p>
<p><code>CreateVector</code> can also take an <code>std::vector</code>. The offset it returns is typed, i.e. can only be used to set fields of the correct type below. To create a vector of struct objects (which will be stored as contiguous memory in the buffer, use <code>CreateVectorOfStructs</code> instead.</p>
<p>To create a vector of nested objects (e.g. tables, strings or other vectors) collect their offsets in a temporary array/vector, then call <code>CreateVector</code> on that (see e.g. the array of strings example in <code>test.cpp</code> <code>CreateFlatBufferTest</code>).</p>
<div class="fragment"><div class="line">Vec3 vec(1, 2, 3);</div>
</div><!-- fragment --><p><code>Vec3</code> is the first example of code from our generated header. Structs (unlike tables) translate to simple structs in C++, so we can construct them in a familiar way.</p>
<p>We have now serialized the non-scalar components of of the monster example, so we could create the monster something like this:</p>
<div class="fragment"><div class="line"><span class="keyword">auto</span> mloc = CreateMonster(fbb, &vec, 150, 80, name, inventory, Color_Red, 0, Any_NONE);</div>
</div><!-- fragment --><p>Note that we're passing <code>150</code> for the <code>mana</code> field, which happens to be the default value: this means the field will not actually be written to the buffer, since we'll get that value anyway when we query it. This is a nice space savings, since it is very common for fields to be at their default. It means we also don't need to be scared to add fields only used in a minority of cases, since they won't bloat up the buffer sizes if they're not actually used.</p>
<p>We do something similarly for the union field <code>test</code> by specifying a <code>0</code> offset and the <code>NONE</code> enum value (part of every union) to indicate we don't actually want to write this field. You can use <code>0</code> also as a default for other non-scalar types, such as strings, vectors and tables.</p>
<p>Tables (like <code>Monster</code>) give you full flexibility on what fields you write (unlike <code>Vec3</code>, which always has all fields set because it is a <code>struct</code>). If you want even more control over this (i.e. skip fields even when they are not default), instead of the convenient <code>CreateMonster</code> call we can also build the object field-by-field manually:</p>
<div class="fragment"><div class="line">MonsterBuilder mb(fbb);</div>
<div class="line">mb.add_pos(&vec);</div>
<div class="line">mb.add_hp(80);</div>
<div class="line">mb.add_name(name);</div>
<div class="line">mb.add_inventory(inventory);</div>
<div class="line"><span class="keyword">auto</span> mloc = mb.Finish();</div>
</div><!-- fragment --><p>We start with a temporary helper class <code>MonsterBuilder</code> (which is defined in our generated code also), then call the various <code>add_</code> methods to set fields, and <code>Finish</code> to complete the object. This is pretty much the same code as you find inside <code>CreateMonster</code>, except we're leaving out a few fields. Fields may also be added in any order, though orderings with fields of the same size adjacent to each other most efficient in size, due to alignment. You should not nest these Builder classes (serialize your data in pre-order).</p>
<p>Regardless of whether you used <code>CreateMonster</code> or <code>MonsterBuilder</code>, you now have an offset to the root of your data, and you can finish the buffer using:</p>
<div class="fragment"><div class="line">FinishMonsterBuffer(fbb, mloc);</div>
</div><!-- fragment --><p>The buffer is now ready to be stored somewhere, sent over the network, be compressed, or whatever you'd like to do with it. You can access the start of the buffer with <code>fbb.GetBufferPointer()</code>, and it's size from <code>fbb.GetSize()</code>.</p>
<p><code>samples/sample_binary.cpp</code> is a complete code sample similar to the code above, that also includes the reading code below.</p>
<h3>Reading in C++</h3>
<p>If you've received a buffer from somewhere (disk, network, etc.) you can directly start traversing it using:</p>
<div class="fragment"><div class="line"><span class="keyword">auto</span> monster = GetMonster(buffer_pointer);</div>
</div><!-- fragment --><p><code>monster</code> is of type <code>Monster *</code>, and points to somewhere <em>inside</em> your buffer (root object pointers are not the same as <code>buffer_pointer</code> !). If you look in your generated header, you'll see it has convenient accessors for all fields, e.g.</p>
<div class="fragment"><div class="line">assert(monster->hp() == 80);</div>
<div class="line">assert(monster->mana() == 150); <span class="comment">// default</span></div>
<div class="line">assert(strcmp(monster->name()->c_str(), <span class="stringliteral">"MyMonster"</span>) == 0);</div>
</div><!-- fragment --><p>These should all be true. Note that we never stored a <code>mana</code> value, so it will return the default.</p>
<p>To access sub-objects, in this case the <code>Vec3</code>:</p>
<div class="fragment"><div class="line"><span class="keyword">auto</span> pos = monster->pos();</div>
<div class="line">assert(pos);</div>
<div class="line">assert(pos->z() == 3);</div>
</div><!-- fragment --><p>If we had not set the <code>pos</code> field during serialization, it would be <code>NULL</code>.</p>
<p>Similarly, we can access elements of the inventory array:</p>
<div class="fragment"><div class="line"><span class="keyword">auto</span> inv = monster->inventory();</div>
<div class="line">assert(inv);</div>
<div class="line">assert(inv->Get(9) == 9);</div>
</div><!-- fragment --><h3>Storing maps / dictionaries in a FlatBuffer</h3>
<p>FlatBuffers doesn't support maps natively, but there is support to emulate their behavior with vectors and binary search, which means you can have fast lookups directly from a FlatBuffer without having to unpack your data into a <code>std::map</code> or similar.</p>
<p>To use it:</p><ul>
<li>Designate one of the fields in a table as they "key" field. You do this by setting the <code>key</code> attribute on this field, e.g. <code>name:string (key)</code>. You may only have one key field, and it must be of string or scalar type.</li>
<li>Write out tables of this type as usual, collect their offsets in an array or vector.</li>
<li>Instead of <code>CreateVector</code>, call <code>CreateVectorOfSortedTables</code>, which will first sort all offsets such that the tables they refer to are sorted by the key field, then serialize it.</li>
<li>Now when you're accessing the FlatBuffer, you can use <code>Vector::LookupByKey</code> instead of just <code>Vector::Get</code> to access elements of the vector, e.g.: <code>myvector->LookupByKey("Fred")</code>, which returns a pointer to the corresponding table type, or <code>nullptr</code> if not found. <code>LookupByKey</code> performs a binary search, so should have a similar speed to <code>std::map</code>, though may be faster because of better caching. <code>LookupByKey</code> only works if the vector has been sorted, it will likely not find elements if it hasn't been sorted.</li>
</ul>
<h3>Direct memory access</h3>
<p>As you can see from the above examples, all elements in a buffer are accessed through generated accessors. This is because everything is stored in little endian format on all platforms (the accessor performs a swap operation on big endian machines), and also because the layout of things is generally not known to the user.</p>
<p>For structs, layout is deterministic and guaranteed to be the same accross platforms (scalars are aligned to their own size, and structs themselves to their largest member), and you are allowed to access this memory directly by using <code>sizeof()</code> and <code>memcpy</code> on the pointer to a struct, or even an array of structs.</p>
<p>To compute offsets to sub-elements of a struct, make sure they are a structs themselves, as then you can use the pointers to figure out the offset without having to hardcode it. This is handy for use of arrays of structs with calls like <code>glVertexAttribPointer</code> in OpenGL or similar APIs.</p>
<p>It is important to note is that structs are still little endian on all machines, so only use tricks like this if you can guarantee you're not shipping on a big endian machine (an <code>assert(FLATBUFFERS_LITTLEENDIAN)</code> would be wise).</p>
<h3>Access of untrusted buffers</h3>
<p>The generated accessor functions access fields over offsets, which is very quick. These offsets are not verified at run-time, so a malformed buffer could cause a program to crash by accessing random memory.</p>
<p>When you're processing large amounts of data from a source you know (e.g. your own generated data on disk), this is acceptable, but when reading data from the network that can potentially have been modified by an attacker, this is undesirable.</p>
<p>For this reason, you can optionally use a buffer verifier before you access the data. This verifier will check all offsets, all sizes of fields, and null termination of strings to ensure that when a buffer is accessed, all reads will end up inside the buffer.</p>
<p>Each root type will have a verification function generated for it, e.g. for <code>Monster</code>, you can call:</p>
<div class="fragment"><div class="line"><span class="keywordtype">bool</span> ok = VerifyMonsterBuffer(Verifier(buf, len));</div>
</div><!-- fragment --><p>if <code>ok</code> is true, the buffer is safe to read.</p>
<p>Besides untrusted data, this function may be useful to call in debug mode, as extra insurance against data being corrupted somewhere along the way.</p>
<p>While verifying a buffer isn't "free", it is typically faster than a full traversal (since any scalar data is not actually touched), and since it may cause the buffer to be brought into cache before reading, the actual overhead may be even lower than expected.</p>
<p>In specialized cases where a denial of service attack is possible, the verifier has two additional constructor arguments that allow you to limit the nesting depth and total amount of tables the verifier may encounter before declaring the buffer malformed.</p>
<h2>Text & schema parsing</h2>
<p>Using binary buffers with the generated header provides a super low overhead use of FlatBuffer data. There are, however, times when you want to use text formats, for example because it interacts better with source control, or you want to give your users easy access to data.</p>
<p>Another reason might be that you already have a lot of data in JSON format, or a tool that generates JSON, and if you can write a schema for it, this will provide you an easy way to use that data directly.</p>
<p>(see the schema documentation for some specifics on the JSON format accepted).</p>
<p>There are two ways to use text formats:</p>
<h3>Using the compiler as a conversion tool</h3>
<p>This is the preferred path, as it doesn't require you to add any new code to your program, and is maximally efficient since you can ship with binary data. The disadvantage is that it is an extra step for your users/developers to perform, though you might be able to automate it. </p><pre class="fragment">flatc -b myschema.fbs mydata.json
</pre><p>This will generate the binary file <code>mydata_wire.bin</code> which can be loaded as before.</p>
<h3>Making your program capable of loading text directly</h3>
<p>This gives you maximum flexibility. You could even opt to support both, i.e. check for both files, and regenerate the binary from text when required, otherwise just load the binary.</p>
<p>This option is currently only available for C++, or Java through JNI.</p>
<p>As mentioned in the section "Building" above, this technique requires you to link a few more files into your program, and you'll want to include <code>flatbuffers/idl.h</code>.</p>
<p>Load text (either a schema or json) into an in-memory buffer (there is a convenient <code>LoadFile()</code> utility function in <code>flatbuffers/util.h</code> if you wish). Construct a parser:</p>
<div class="fragment"><div class="line">flatbuffers::Parser parser;</div>
</div><!-- fragment --><p>Now you can parse any number of text files in sequence:</p>
<div class="fragment"><div class="line">parser.Parse(text_file.c_str());</div>
</div><!-- fragment --><p>This works similarly to how the command-line compiler works: a sequence of files parsed by the same <code>Parser</code> object allow later files to reference definitions in earlier files. Typically this means you first load a schema file (which populates <code>Parser</code> with definitions), followed by one or more JSON files.</p>
<p>As optional argument to <code>Parse</code>, you may specify a null-terminated list of include paths. If not specified, any include statements try to resolve from the current directory.</p>
<p>If there were any parsing errors, <code>Parse</code> will return <code>false</code>, and <code>Parser::err</code> contains a human readable error string with a line number etc, which you should present to the creator of that file.</p>
<p>After each JSON file, the <code>Parser::fbb</code> member variable is the <code>FlatBufferBuilder</code> that contains the binary buffer version of that file, that you can access as described above.</p>
<p><code>samples/sample_text.cpp</code> is a code sample showing the above operations.</p>
<h3>Threading</h3>
<p>Reading a FlatBuffer does not touch any memory outside the original buffer, and is entirely read-only (all const), so is safe to access from multiple threads even without synchronisation primitives.</p>
<p>Creating a FlatBuffer is not thread safe. All state related to building a FlatBuffer is contained in a FlatBufferBuilder instance, and no memory outside of it is touched. To make this thread safe, either do not share instances of FlatBufferBuilder between threads (recommended), or manually wrap it in synchronisation primites. There's no automatic way to accomplish this, by design, as we feel multithreaded construction of a single buffer will be rare, and synchronisation overhead would be costly. </p>
</div></div><!-- contents -->
</div><!-- doc-content -->
<!-- Google Analytics -->
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-49880327-7', 'auto');
ga('send', 'pageview');
</script>
</body>
</html>
| radent/flatbuffers | docs/html/md__cpp_usage.html | HTML | apache-2.0 | 18,427 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head><!-- start favicons snippet, use https://realfavicongenerator.net/ --><link rel="apple-touch-icon" sizes="180x180" href="/assets/apple-touch-icon.png"><link rel="icon" type="image/png" sizes="32x32" href="/assets/favicon-32x32.png"><link rel="icon" type="image/png" sizes="16x16" href="/assets/favicon-16x16.png"><link rel="manifest" href="/assets/site.webmanifest"><link rel="mask-icon" href="/assets/safari-pinned-tab.svg" color="#fc4d50"><link rel="shortcut icon" href="/assets/favicon.ico"><meta name="msapplication-TileColor" content="#ffc40d"><meta name="msapplication-config" content="/assets/browserconfig.xml"><meta name="theme-color" content="#ffffff"><!-- end favicons snippet -->
<title>com.google.android.exoplayer2.source.ads (ExoPlayer library)</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">
<link rel="stylesheet" type="text/css" href="../../../../../../jquery/jquery-ui.css" title="Style">
<script type="text/javascript" src="../../../../../../script.js"></script>
<script type="text/javascript" src="../../../../../../jquery/jszip/dist/jszip.min.js"></script>
<script type="text/javascript" src="../../../../../../jquery/jszip-utils/dist/jszip-utils.min.js"></script>
<!--[if IE]>
<script type="text/javascript" src="../../../../../../jquery/jszip-utils/dist/jszip-utils-ie.min.js"></script>
<![endif]-->
<script type="text/javascript" src="../../../../../../jquery/jquery-1.10.2.js"></script>
<script type="text/javascript" src="../../../../../../jquery/jquery-ui.js"></script>
</head>
<body>
<h1 class="bar"><a href="../../../../../../com/google/android/exoplayer2/source/ads/package-summary.html" target="classFrame">com.google.android.exoplayer2.source.ads</a></h1>
<div class="indexContainer">
<h2 title="Interfaces">Interfaces</h2>
<ul title="Interfaces">
<li><a href="AdsLoader.html" title="interface in com.google.android.exoplayer2.source.ads" target="classFrame"><span class="interfaceName">AdsLoader</span></a></li>
<li><a href="AdsLoader.AdViewProvider.html" title="interface in com.google.android.exoplayer2.source.ads" target="classFrame"><span class="interfaceName">AdsLoader.AdViewProvider</span></a></li>
<li><a href="AdsLoader.EventListener.html" title="interface in com.google.android.exoplayer2.source.ads" target="classFrame"><span class="interfaceName">AdsLoader.EventListener</span></a></li>
</ul>
<h2 title="Classes">Classes</h2>
<ul title="Classes">
<li><a href="AdPlaybackState.html" title="class in com.google.android.exoplayer2.source.ads" target="classFrame">AdPlaybackState</a></li>
<li><a href="AdPlaybackState.AdGroup.html" title="class in com.google.android.exoplayer2.source.ads" target="classFrame">AdPlaybackState.AdGroup</a></li>
<li><a href="AdsLoader.OverlayInfo.html" title="class in com.google.android.exoplayer2.source.ads" target="classFrame">AdsLoader.OverlayInfo</a></li>
<li><a href="AdsMediaSource.html" title="class in com.google.android.exoplayer2.source.ads" target="classFrame">AdsMediaSource</a></li>
<li><a href="SinglePeriodAdTimeline.html" title="class in com.google.android.exoplayer2.source.ads" target="classFrame">SinglePeriodAdTimeline</a></li>
</ul>
<h2 title="Exceptions">Exceptions</h2>
<ul title="Exceptions">
<li><a href="AdsMediaSource.AdLoadException.html" title="class in com.google.android.exoplayer2.source.ads" target="classFrame">AdsMediaSource.AdLoadException</a></li>
</ul>
<h2 title="Annotation Types">Annotation Types</h2>
<ul title="Annotation Types">
<li><a href="AdPlaybackState.AdState.html" title="annotation in com.google.android.exoplayer2.source.ads" target="classFrame">AdPlaybackState.AdState</a></li>
<li><a href="AdsLoader.OverlayInfo.Purpose.html" title="annotation in com.google.android.exoplayer2.source.ads" target="classFrame">AdsLoader.OverlayInfo.Purpose</a></li>
<li><a href="AdsMediaSource.AdLoadException.Type.html" title="annotation in com.google.android.exoplayer2.source.ads" target="classFrame">AdsMediaSource.AdLoadException.Type</a></li>
</ul>
</div>
</body>
</html>
| amzn/exoplayer-amazon-port | docs/doc/reference/com/google/android/exoplayer2/source/ads/package-frame.html | HTML | apache-2.0 | 4,255 |
/*
* 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.route53.model.transform;
import java.util.ArrayList;
import javax.xml.stream.events.XMLEvent;
import javax.annotation.Generated;
import com.amazonaws.services.route53.model.*;
import com.amazonaws.transform.Unmarshaller;
import com.amazonaws.transform.StaxUnmarshallerContext;
import com.amazonaws.transform.SimpleTypeStaxUnmarshallers.*;
/**
* GetHealthCheckLastFailureReasonResult StAX Unmarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class GetHealthCheckLastFailureReasonResultStaxUnmarshaller implements Unmarshaller<GetHealthCheckLastFailureReasonResult, StaxUnmarshallerContext> {
public GetHealthCheckLastFailureReasonResult unmarshall(StaxUnmarshallerContext context) throws Exception {
GetHealthCheckLastFailureReasonResult getHealthCheckLastFailureReasonResult = new GetHealthCheckLastFailureReasonResult();
int originalDepth = context.getCurrentDepth();
int targetDepth = originalDepth + 1;
if (context.isStartOfDocument())
targetDepth += 1;
while (true) {
XMLEvent xmlEvent = context.nextEvent();
if (xmlEvent.isEndDocument())
return getHealthCheckLastFailureReasonResult;
if (xmlEvent.isAttribute() || xmlEvent.isStartElement()) {
if (context.testExpression("HealthCheckObservations", targetDepth)) {
getHealthCheckLastFailureReasonResult.withHealthCheckObservations(new ArrayList<HealthCheckObservation>());
continue;
}
if (context.testExpression("HealthCheckObservations/HealthCheckObservation", targetDepth)) {
getHealthCheckLastFailureReasonResult.withHealthCheckObservations(HealthCheckObservationStaxUnmarshaller.getInstance().unmarshall(context));
continue;
}
} else if (xmlEvent.isEndElement()) {
if (context.getCurrentDepth() < originalDepth) {
return getHealthCheckLastFailureReasonResult;
}
}
}
}
private static GetHealthCheckLastFailureReasonResultStaxUnmarshaller instance;
public static GetHealthCheckLastFailureReasonResultStaxUnmarshaller getInstance() {
if (instance == null)
instance = new GetHealthCheckLastFailureReasonResultStaxUnmarshaller();
return instance;
}
}
| jentfoo/aws-sdk-java | aws-java-sdk-route53/src/main/java/com/amazonaws/services/route53/model/transform/GetHealthCheckLastFailureReasonResultStaxUnmarshaller.java | Java | apache-2.0 | 3,038 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ignite.cache.store.jdbc;
import java.nio.ByteBuffer;
import java.sql.BatchUpdateException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import javax.cache.Cache;
import javax.cache.CacheException;
import javax.cache.integration.CacheLoaderException;
import javax.cache.integration.CacheWriterException;
import javax.sql.DataSource;
import org.apache.ignite.Ignite;
import org.apache.ignite.IgniteCheckedException;
import org.apache.ignite.IgniteException;
import org.apache.ignite.IgniteLogger;
import org.apache.ignite.cache.CacheTypeFieldMetadata;
import org.apache.ignite.cache.CacheTypeMetadata;
import org.apache.ignite.cache.store.CacheStore;
import org.apache.ignite.cache.store.CacheStoreSession;
import org.apache.ignite.cache.store.jdbc.dialect.BasicJdbcDialect;
import org.apache.ignite.cache.store.jdbc.dialect.DB2Dialect;
import org.apache.ignite.cache.store.jdbc.dialect.H2Dialect;
import org.apache.ignite.cache.store.jdbc.dialect.JdbcDialect;
import org.apache.ignite.cache.store.jdbc.dialect.MySQLDialect;
import org.apache.ignite.cache.store.jdbc.dialect.OracleDialect;
import org.apache.ignite.cache.store.jdbc.dialect.SQLServerDialect;
import org.apache.ignite.configuration.CacheConfiguration;
import org.apache.ignite.internal.util.tostring.GridToStringExclude;
import org.apache.ignite.internal.util.typedef.C1;
import org.apache.ignite.internal.util.typedef.F;
import org.apache.ignite.internal.util.typedef.internal.U;
import org.apache.ignite.lang.IgniteBiInClosure;
import org.apache.ignite.lang.IgnitePredicate;
import org.apache.ignite.lifecycle.LifecycleAware;
import org.apache.ignite.resources.CacheStoreSessionResource;
import org.apache.ignite.resources.IgniteInstanceResource;
import org.apache.ignite.resources.LoggerResource;
import org.apache.ignite.transactions.Transaction;
import org.jetbrains.annotations.Nullable;
import static java.sql.Statement.EXECUTE_FAILED;
import static java.sql.Statement.SUCCESS_NO_INFO;
/**
* Implementation of {@link CacheStore} backed by JDBC.
* <p>
* Store works with database via SQL dialect. Ignite ships with dialects for most popular databases:
* <ul>
* <li>{@link DB2Dialect} - dialect for IBM DB2 database.</li>
* <li>{@link OracleDialect} - dialect for Oracle database.</li>
* <li>{@link SQLServerDialect} - dialect for Microsoft SQL Server database.</li>
* <li>{@link MySQLDialect} - dialect for Oracle MySQL database.</li>
* <li>{@link H2Dialect} - dialect for H2 database.</li>
* <li>{@link BasicJdbcDialect} - dialect for any database via plain JDBC.</li>
* </ul>
* <p>
* <h2 class="header">Configuration</h2>
* <ul>
* <li>Data source (see {@link #setDataSource(DataSource)}</li>
* <li>Dialect (see {@link #setDialect(JdbcDialect)}</li>
* <li>Maximum batch size for writeAll and deleteAll operations. (see {@link #setBatchSize(int)})</li>
* <li>Max workers thread count. These threads are responsible for load cache. (see {@link #setMaximumPoolSize(int)})</li>
* <li>Parallel load cache minimum threshold. (see {@link #setParallelLoadCacheMinimumThreshold(int)})</li>
* </ul>
* <h2 class="header">Java Example</h2>
* <pre name="code" class="java">
* ...
* CacheConfiguration ccfg = new CacheConfiguration<>();
*
* // Configure cache store.
* ccfg.setCacheStoreFactory(new FactoryBuilder.SingletonFactory(ConfigurationSnippet.store()));
* ccfg.setReadThrough(true);
* ccfg.setWriteThrough(true);
*
* // Configure cache types metadata.
* ccfg.setTypeMetadata(ConfigurationSnippet.typeMetadata());
*
* cfg.setCacheConfiguration(ccfg);
* ...
* </pre>
*/
public abstract class CacheAbstractJdbcStore<K, V> implements CacheStore<K, V>, LifecycleAware {
/** Max attempt write count. */
protected static final int MAX_ATTEMPT_WRITE_COUNT = 2;
/** Default batch size for put and remove operations. */
protected static final int DFLT_BATCH_SIZE = 512;
/** Default batch size for put and remove operations. */
protected static final int DFLT_PARALLEL_LOAD_CACHE_MINIMUM_THRESHOLD = 512;
/** Connection attribute property name. */
protected static final String ATTR_CONN_PROP = "JDBC_STORE_CONNECTION";
/** Empty column value. */
protected static final Object[] EMPTY_COLUMN_VALUE = new Object[] { null };
/** Auto-injected store session. */
@CacheStoreSessionResource
private CacheStoreSession ses;
/** Auto injected ignite instance. */
@IgniteInstanceResource
private Ignite ignite;
/** Auto-injected logger instance. */
@LoggerResource
protected IgniteLogger log;
/** Lock for metadata cache. */
@GridToStringExclude
private final Lock cacheMappingsLock = new ReentrantLock();
/** Data source. */
protected DataSource dataSrc;
/** Cache with entry mapping description. (cache name, (key id, mapping description)). */
protected volatile Map<String, Map<Object, EntryMapping>> cacheMappings = Collections.emptyMap();
/** Database dialect. */
protected JdbcDialect dialect;
/** Max workers thread count. These threads are responsible for load cache. */
private int maxPoolSz = Runtime.getRuntime().availableProcessors();
/** Maximum batch size for writeAll and deleteAll operations. */
private int batchSz = DFLT_BATCH_SIZE;
/** Parallel load cache minimum threshold. If {@code 0} then load sequentially. */
private int parallelLoadCacheMinThreshold = DFLT_PARALLEL_LOAD_CACHE_MINIMUM_THRESHOLD;
/**
* Get field value from object for use as query parameter.
*
* @param cacheName Cache name.
* @param typeName Type name.
* @param fieldName Field name.
* @param obj Cache object.
* @return Field value from object.
* @throws CacheException in case of error.
*/
@Nullable protected abstract Object extractParameter(@Nullable String cacheName, String typeName, String fieldName,
Object obj) throws CacheException;
/**
* Construct object from query result.
*
* @param <R> Type of result object.
* @param cacheName Cache name.
* @param typeName Type name.
* @param fields Fields descriptors.
* @param loadColIdxs Select query columns index.
* @param rs ResultSet.
* @return Constructed object.
* @throws CacheLoaderException If failed to construct cache object.
*/
protected abstract <R> R buildObject(@Nullable String cacheName, String typeName,
Collection<CacheTypeFieldMetadata> fields, Map<String, Integer> loadColIdxs, ResultSet rs)
throws CacheLoaderException;
/**
* Extract key type id from key object.
*
* @param key Key object.
* @return Key type id.
* @throws CacheException If failed to get type key id from object.
*/
protected abstract Object keyTypeId(Object key) throws CacheException;
/**
* Extract key type id from key class name.
*
* @param type String description of key type.
* @return Key type id.
* @throws CacheException If failed to get type key id from object.
*/
protected abstract Object keyTypeId(String type) throws CacheException;
/**
* Prepare internal store specific builders for provided types metadata.
*
* @param cacheName Cache name to prepare builders for.
* @param types Collection of types.
* @throws CacheException If failed to prepare internal builders for types.
*/
protected abstract void prepareBuilders(@Nullable String cacheName, Collection<CacheTypeMetadata> types)
throws CacheException;
/**
* Perform dialect resolution.
*
* @return The resolved dialect.
* @throws CacheException Indicates problems accessing the metadata.
*/
protected JdbcDialect resolveDialect() throws CacheException {
Connection conn = null;
String dbProductName = null;
try {
conn = openConnection(false);
dbProductName = conn.getMetaData().getDatabaseProductName();
}
catch (SQLException e) {
throw new CacheException("Failed access to metadata for detect database dialect.", e);
}
finally {
U.closeQuiet(conn);
}
if ("H2".equals(dbProductName))
return new H2Dialect();
if ("MySQL".equals(dbProductName))
return new MySQLDialect();
if (dbProductName.startsWith("Microsoft SQL Server"))
return new SQLServerDialect();
if ("Oracle".equals(dbProductName))
return new OracleDialect();
if (dbProductName.startsWith("DB2/"))
return new DB2Dialect();
U.warn(log, "Failed to resolve dialect (BasicJdbcDialect will be used): " + dbProductName);
return new BasicJdbcDialect();
}
/** {@inheritDoc} */
@Override public void start() throws IgniteException {
if (dataSrc == null)
throw new IgniteException("Failed to initialize cache store (data source is not provided).");
if (dialect == null) {
dialect = resolveDialect();
if (log.isDebugEnabled() && dialect.getClass() != BasicJdbcDialect.class)
log.debug("Resolved database dialect: " + U.getSimpleName(dialect.getClass()));
}
}
/** {@inheritDoc} */
@Override public void stop() throws IgniteException {
// No-op.
}
/**
* Gets connection from a pool.
*
* @param autocommit {@code true} If connection should use autocommit mode.
* @return Pooled connection.
* @throws SQLException In case of error.
*/
protected Connection openConnection(boolean autocommit) throws SQLException {
Connection conn = dataSrc.getConnection();
conn.setAutoCommit(autocommit);
return conn;
}
/**
* @return Connection.
* @throws SQLException In case of error.
*/
protected Connection connection() throws SQLException {
CacheStoreSession ses = session();
if (ses.transaction() != null) {
Map<String, Connection> prop = ses.properties();
Connection conn = prop.get(ATTR_CONN_PROP);
if (conn == null) {
conn = openConnection(false);
// Store connection in session to used it for other operations in the same session.
prop.put(ATTR_CONN_PROP, conn);
}
return conn;
}
// Transaction can be null in case of simple load operation.
else
return openConnection(true);
}
/**
* Closes connection.
*
* @param conn Connection to close.
*/
protected void closeConnection(@Nullable Connection conn) {
CacheStoreSession ses = session();
// Close connection right away if there is no transaction.
if (ses.transaction() == null)
U.closeQuiet(conn);
}
/**
* Closes allocated resources depending on transaction status.
*
* @param conn Allocated connection.
* @param st Created statement,
*/
protected void end(@Nullable Connection conn, @Nullable Statement st) {
U.closeQuiet(st);
closeConnection(conn);
}
/** {@inheritDoc} */
@Override public void sessionEnd(boolean commit) throws CacheWriterException {
CacheStoreSession ses = session();
Transaction tx = ses.transaction();
if (tx != null) {
Map<String, Connection> sesProps = ses.properties();
Connection conn = sesProps.get(ATTR_CONN_PROP);
if (conn != null) {
sesProps.remove(ATTR_CONN_PROP);
try {
if (commit)
conn.commit();
else
conn.rollback();
}
catch (SQLException e) {
throw new CacheWriterException(
"Failed to end transaction [xid=" + tx.xid() + ", commit=" + commit + ']', e);
}
finally {
U.closeQuiet(conn);
}
}
if (log.isDebugEnabled())
log.debug("Transaction ended [xid=" + tx.xid() + ", commit=" + commit + ']');
}
}
/**
* Retrieves the value of the designated column in the current row of this <code>ResultSet</code> object and
* will convert to the requested Java data type.
*
* @param rs Result set.
* @param colIdx Column index in result set.
* @param type Class representing the Java data type to convert the designated column to.
* @return Value in column.
* @throws SQLException If a database access error occurs or this method is called.
*/
protected Object getColumnValue(ResultSet rs, int colIdx, Class<?> type) throws SQLException {
Object val = rs.getObject(colIdx);
if (val == null)
return null;
if (type == int.class)
return rs.getInt(colIdx);
if (type == long.class)
return rs.getLong(colIdx);
if (type == double.class)
return rs.getDouble(colIdx);
if (type == boolean.class || type == Boolean.class)
return rs.getBoolean(colIdx);
if (type == byte.class)
return rs.getByte(colIdx);
if (type == short.class)
return rs.getShort(colIdx);
if (type == float.class)
return rs.getFloat(colIdx);
if (type == Integer.class || type == Long.class || type == Double.class ||
type == Byte.class || type == Short.class || type == Float.class) {
Number num = (Number)val;
if (type == Integer.class)
return num.intValue();
else if (type == Long.class)
return num.longValue();
else if (type == Double.class)
return num.doubleValue();
else if (type == Byte.class)
return num.byteValue();
else if (type == Short.class)
return num.shortValue();
else if (type == Float.class)
return num.floatValue();
}
if (type == UUID.class) {
if (val instanceof UUID)
return val;
if (val instanceof byte[]) {
ByteBuffer bb = ByteBuffer.wrap((byte[])val);
long most = bb.getLong();
long least = bb.getLong();
return new UUID(most, least);
}
if (val instanceof String)
return UUID.fromString((String)val);
}
return val;
}
/**
* Construct load cache from range.
*
* @param em Type mapping description.
* @param clo Closure that will be applied to loaded values.
* @param lowerBound Lower bound for range.
* @param upperBound Upper bound for range.
* @return Callable for pool submit.
*/
private Callable<Void> loadCacheRange(final EntryMapping em, final IgniteBiInClosure<K, V> clo,
@Nullable final Object[] lowerBound, @Nullable final Object[] upperBound) {
return new Callable<Void>() {
@Override public Void call() throws Exception {
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = openConnection(true);
stmt = conn.prepareStatement(lowerBound == null && upperBound == null
? em.loadCacheQry
: em.loadCacheRangeQuery(lowerBound != null, upperBound != null));
int ix = 1;
if (lowerBound != null)
for (int i = lowerBound.length; i > 0; i--)
for (int j = 0; j < i; j++)
stmt.setObject(ix++, lowerBound[j]);
if (upperBound != null)
for (int i = upperBound.length; i > 0; i--)
for (int j = 0; j < i; j++)
stmt.setObject(ix++, upperBound[j]);
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
K key = buildObject(em.cacheName, em.keyType(), em.keyColumns(), em.loadColIdxs, rs);
V val = buildObject(em.cacheName, em.valueType(), em.valueColumns(), em.loadColIdxs, rs);
clo.apply(key, val);
}
}
catch (SQLException e) {
throw new IgniteCheckedException("Failed to load cache", e);
}
finally {
U.closeQuiet(stmt);
U.closeQuiet(conn);
}
return null;
}
};
}
/**
* Construct load cache in one select.
*
* @param m Type mapping description.
* @param clo Closure for loaded values.
* @return Callable for pool submit.
*/
private Callable<Void> loadCacheFull(EntryMapping m, IgniteBiInClosure<K, V> clo) {
return loadCacheRange(m, clo, null, null);
}
/**
* Object is a simple type.
*
* @param cls Class.
* @return {@code True} if object is a simple type.
*/
protected static boolean simpleType(Class<?> cls) {
return (Number.class.isAssignableFrom(cls) || String.class.isAssignableFrom(cls) ||
java.util.Date.class.isAssignableFrom(cls) || Boolean.class.isAssignableFrom(cls) ||
UUID.class.isAssignableFrom(cls));
}
/**
* @param cacheName Cache name to check mapping for.
* @param clsName Class name.
* @param fields Fields descriptors.
* @throws CacheException If failed to check type metadata.
*/
private static void checkMapping(@Nullable String cacheName, String clsName,
Collection<CacheTypeFieldMetadata> fields) throws CacheException {
try {
Class<?> cls = Class.forName(clsName);
if (simpleType(cls)) {
if (fields.size() != 1)
throw new CacheException("More than one field for simple type [cache name=" + cacheName
+ ", type=" + clsName + " ]");
CacheTypeFieldMetadata field = F.first(fields);
if (field.getDatabaseName() == null)
throw new CacheException("Missing database name in mapping description [cache name=" + cacheName
+ ", type=" + clsName + " ]");
field.setJavaType(cls);
}
else
for (CacheTypeFieldMetadata field : fields) {
if (field.getDatabaseName() == null)
throw new CacheException("Missing database name in mapping description [cache name=" + cacheName
+ ", type=" + clsName + " ]");
if (field.getJavaName() == null)
throw new CacheException("Missing field name in mapping description [cache name=" + cacheName
+ ", type=" + clsName + " ]");
if (field.getJavaType() == null)
throw new CacheException("Missing field type in mapping description [cache name=" + cacheName
+ ", type=" + clsName + " ]");
}
}
catch (ClassNotFoundException e) {
throw new CacheException("Failed to find class: " + clsName, e);
}
}
/**
* @param cacheName Cache name to check mappings for.
* @return Type mappings for specified cache name.
* @throws CacheException If failed to initialize cache mappings.
*/
private Map<Object, EntryMapping> cacheMappings(@Nullable String cacheName) throws CacheException {
Map<Object, EntryMapping> entryMappings = cacheMappings.get(cacheName);
if (entryMappings != null)
return entryMappings;
cacheMappingsLock.lock();
try {
entryMappings = cacheMappings.get(cacheName);
if (entryMappings != null)
return entryMappings;
CacheConfiguration ccfg = ignite().cache(cacheName).getConfiguration(CacheConfiguration.class);
Collection<CacheTypeMetadata> types = ccfg.getTypeMetadata();
entryMappings = U.newHashMap(types.size());
for (CacheTypeMetadata type : types) {
Object keyTypeId = keyTypeId(type.getKeyType());
if (entryMappings.containsKey(keyTypeId))
throw new CacheException("Key type must be unique in type metadata [cache name=" + cacheName +
", key type=" + type.getKeyType() + "]");
checkMapping(cacheName, type.getKeyType(), type.getKeyFields());
checkMapping(cacheName, type.getValueType(), type.getValueFields());
entryMappings.put(keyTypeId(type.getKeyType()), new EntryMapping(cacheName, dialect, type));
}
Map<String, Map<Object, EntryMapping>> mappings = new HashMap<>(cacheMappings);
mappings.put(cacheName, entryMappings);
prepareBuilders(cacheName, types);
cacheMappings = mappings;
return entryMappings;
}
finally {
cacheMappingsLock.unlock();
}
}
/**
* @param cacheName Cache name.
* @param keyTypeId Key type id.
* @param key Key object.
* @return Entry mapping.
* @throws CacheException If mapping for key was not found.
*/
private EntryMapping entryMapping(String cacheName, Object keyTypeId, Object key) throws CacheException {
EntryMapping em = cacheMappings(cacheName).get(keyTypeId);
if (em == null) {
String maskedCacheName = U.maskName(cacheName);
throw new CacheException("Failed to find mapping description [key=" + key +
", cache=" + maskedCacheName + "]. Please configure CacheTypeMetadata to associate '" + maskedCacheName + "' with JdbcPojoStore.");
}
return em;
}
/** {@inheritDoc} */
@Override public void loadCache(final IgniteBiInClosure<K, V> clo, @Nullable Object... args)
throws CacheLoaderException {
ExecutorService pool = null;
String cacheName = session().cacheName();
try {
pool = Executors.newFixedThreadPool(maxPoolSz);
Collection<Future<?>> futs = new ArrayList<>();
if (args != null && args.length > 0) {
if (args.length % 2 != 0)
throw new CacheLoaderException("Expected even number of arguments, but found: " + args.length);
if (log.isDebugEnabled())
log.debug("Start loading entries from db using user queries from arguments");
for (int i = 0; i < args.length; i += 2) {
String keyType = args[i].toString();
String selQry = args[i + 1].toString();
EntryMapping em = entryMapping(cacheName, keyTypeId(keyType), keyType);
futs.add(pool.submit(new LoadCacheCustomQueryWorker<>(em, selQry, clo)));
}
}
else {
Collection<EntryMapping> entryMappings = cacheMappings(session().cacheName()).values();
for (EntryMapping em : entryMappings) {
if (parallelLoadCacheMinThreshold > 0) {
log.debug("Multithread loading entries from db [cache name=" + cacheName +
", key type=" + em.keyType() + " ]");
Connection conn = null;
try {
conn = connection();
PreparedStatement stmt = conn.prepareStatement(em.loadCacheSelRangeQry);
stmt.setInt(1, parallelLoadCacheMinThreshold);
ResultSet rs = stmt.executeQuery();
if (rs.next()) {
int keyCnt = em.keyCols.size();
Object[] upperBound = new Object[keyCnt];
for (int i = 0; i < keyCnt; i++)
upperBound[i] = rs.getObject(i + 1);
futs.add(pool.submit(loadCacheRange(em, clo, null, upperBound)));
while (rs.next()) {
Object[] lowerBound = upperBound;
upperBound = new Object[keyCnt];
for (int i = 0; i < keyCnt; i++)
upperBound[i] = rs.getObject(i + 1);
futs.add(pool.submit(loadCacheRange(em, clo, lowerBound, upperBound)));
}
futs.add(pool.submit(loadCacheRange(em, clo, upperBound, null)));
}
else
futs.add(pool.submit(loadCacheFull(em, clo)));
}
catch (SQLException ignored) {
futs.add(pool.submit(loadCacheFull(em, clo)));
}
finally {
U.closeQuiet(conn);
}
}
else {
if (log.isDebugEnabled())
log.debug("Single thread loading entries from db [cache name=" + cacheName +
", key type=" + em.keyType() + " ]");
futs.add(pool.submit(loadCacheFull(em, clo)));
}
}
}
for (Future<?> fut : futs)
U.get(fut);
if (log.isDebugEnabled())
log.debug("Cache loaded from db: " + cacheName);
}
catch (IgniteCheckedException e) {
throw new CacheLoaderException("Failed to load cache: " + cacheName, e.getCause());
}
finally {
U.shutdownNow(getClass(), pool, log);
}
}
/** {@inheritDoc} */
@Nullable @Override public V load(K key) throws CacheLoaderException {
assert key != null;
EntryMapping em = entryMapping(session().cacheName(), keyTypeId(key), key);
if (log.isDebugEnabled())
log.debug("Load value from db [table= " + em.fullTableName() + ", key=" + key + "]");
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = connection();
stmt = conn.prepareStatement(em.loadQrySingle);
fillKeyParameters(stmt, em, key);
ResultSet rs = stmt.executeQuery();
if (rs.next())
return buildObject(em.cacheName, em.valueType(), em.valueColumns(), em.loadColIdxs, rs);
}
catch (SQLException e) {
throw new CacheLoaderException("Failed to load object [table=" + em.fullTableName() +
", key=" + key + "]", e);
}
finally {
end(conn, stmt);
}
return null;
}
/** {@inheritDoc} */
@Override public Map<K, V> loadAll(Iterable<? extends K> keys) throws CacheLoaderException {
assert keys != null;
Connection conn = null;
try {
conn = connection();
String cacheName = session().cacheName();
Map<Object, LoadWorker<K, V>> workers = U.newHashMap(cacheMappings(cacheName).size());
Map<K, V> res = new HashMap<>();
for (K key : keys) {
Object keyTypeId = keyTypeId(key);
EntryMapping em = entryMapping(cacheName, keyTypeId, key);
LoadWorker<K, V> worker = workers.get(keyTypeId);
if (worker == null)
workers.put(keyTypeId, worker = new LoadWorker<>(conn, em));
worker.keys.add(key);
if (worker.keys.size() == em.maxKeysPerStmt)
res.putAll(workers.remove(keyTypeId).call());
}
for (LoadWorker<K, V> worker : workers.values())
res.putAll(worker.call());
return res;
}
catch (Exception e) {
throw new CacheWriterException("Failed to load entries from database", e);
}
finally {
closeConnection(conn);
}
}
/**
* @param insStmt Insert statement.
* @param updStmt Update statement.
* @param em Entry mapping.
* @param entry Cache entry.
* @throws CacheWriterException If failed to update record in database.
*/
private void writeUpsert(PreparedStatement insStmt, PreparedStatement updStmt,
EntryMapping em, Cache.Entry<? extends K, ? extends V> entry) throws CacheWriterException {
try {
CacheWriterException we = null;
for (int attempt = 0; attempt < MAX_ATTEMPT_WRITE_COUNT; attempt++) {
int paramIdx = fillValueParameters(updStmt, 1, em, entry.getValue());
fillKeyParameters(updStmt, paramIdx, em, entry.getKey());
if (updStmt.executeUpdate() == 0) {
paramIdx = fillKeyParameters(insStmt, em, entry.getKey());
fillValueParameters(insStmt, paramIdx, em, entry.getValue());
try {
insStmt.executeUpdate();
if (attempt > 0)
U.warn(log, "Entry was inserted in database on second try [table=" + em.fullTableName() +
", entry=" + entry + "]");
}
catch (SQLException e) {
String sqlState = e.getSQLState();
SQLException nested = e.getNextException();
while (sqlState == null && nested != null) {
sqlState = nested.getSQLState();
nested = nested.getNextException();
}
// The error with code 23505 or 23000 is thrown when trying to insert a row that
// would violate a unique index or primary key.
if ("23505".equals(sqlState) || "23000".equals(sqlState)) {
if (we == null)
we = new CacheWriterException("Failed insert entry in database, violate a unique" +
" index or primary key [table=" + em.fullTableName() + ", entry=" + entry + "]");
we.addSuppressed(e);
U.warn(log, "Failed insert entry in database, violate a unique index or primary key" +
" [table=" + em.fullTableName() + ", entry=" + entry + "]");
continue;
}
throw new CacheWriterException("Failed insert entry in database [table=" + em.fullTableName() +
", entry=" + entry, e);
}
}
if (attempt > 0)
U.warn(log, "Entry was updated in database on second try [table=" + em.fullTableName() +
", entry=" + entry + "]");
return;
}
throw we;
}
catch (SQLException e) {
throw new CacheWriterException("Failed update entry in database [table=" + em.fullTableName() +
", entry=" + entry + "]", e);
}
}
/** {@inheritDoc} */
@Override public void write(Cache.Entry<? extends K, ? extends V> entry) throws CacheWriterException {
assert entry != null;
K key = entry.getKey();
EntryMapping em = entryMapping(session().cacheName(), keyTypeId(key), key);
if (log.isDebugEnabled())
log.debug("Start write entry to database [table=" + em.fullTableName() + ", entry=" + entry + "]");
Connection conn = null;
try {
conn = connection();
if (dialect.hasMerge()) {
PreparedStatement stmt = null;
try {
stmt = conn.prepareStatement(em.mergeQry);
int i = fillKeyParameters(stmt, em, key);
fillValueParameters(stmt, i, em, entry.getValue());
int updCnt = stmt.executeUpdate();
if (updCnt != 1)
U.warn(log, "Unexpected number of updated entries [table=" + em.fullTableName() +
", entry=" + entry + "expected=1, actual=" + updCnt + "]");
}
finally {
U.closeQuiet(stmt);
}
}
else {
PreparedStatement insStmt = null;
PreparedStatement updStmt = null;
try {
insStmt = conn.prepareStatement(em.insQry);
updStmt = conn.prepareStatement(em.updQry);
writeUpsert(insStmt, updStmt, em, entry);
}
finally {
U.closeQuiet(insStmt);
U.closeQuiet(updStmt);
}
}
}
catch (SQLException e) {
throw new CacheWriterException("Failed to write entry to database [table=" + em.fullTableName() +
", entry=" + entry + "]", e);
}
finally {
closeConnection(conn);
}
}
/** {@inheritDoc} */
@Override public void writeAll(final Collection<Cache.Entry<? extends K, ? extends V>> entries)
throws CacheWriterException {
assert entries != null;
Connection conn = null;
try {
conn = connection();
String cacheName = session().cacheName();
Object currKeyTypeId = null;
if (dialect.hasMerge()) {
PreparedStatement mergeStmt = null;
try {
EntryMapping em = null;
LazyValue<Object[]> lazyEntries = new LazyValue<Object[]>() {
@Override public Object[] create() {
return entries.toArray();
}
};
int fromIdx = 0, prepared = 0;
for (Cache.Entry<? extends K, ? extends V> entry : entries) {
K key = entry.getKey();
Object keyTypeId = keyTypeId(key);
em = entryMapping(cacheName, keyTypeId, key);
if (currKeyTypeId == null || !currKeyTypeId.equals(keyTypeId)) {
if (mergeStmt != null) {
if (log.isDebugEnabled())
log.debug("Write entries to db [cache name=" + cacheName +
", key type=" + em.keyType() + ", count=" + prepared + "]");
executeBatch(em, mergeStmt, "writeAll", fromIdx, prepared, lazyEntries);
U.closeQuiet(mergeStmt);
}
mergeStmt = conn.prepareStatement(em.mergeQry);
currKeyTypeId = keyTypeId;
fromIdx += prepared;
prepared = 0;
}
int i = fillKeyParameters(mergeStmt, em, key);
fillValueParameters(mergeStmt, i, em, entry.getValue());
mergeStmt.addBatch();
if (++prepared % batchSz == 0) {
if (log.isDebugEnabled())
log.debug("Write entries to db [cache name=" + cacheName +
", key type=" + em.keyType() + ", count=" + prepared + "]");
executeBatch(em, mergeStmt, "writeAll", fromIdx, prepared, lazyEntries);
fromIdx += prepared;
prepared = 0;
}
}
if (mergeStmt != null && prepared % batchSz != 0) {
if (log.isDebugEnabled())
log.debug("Write entries to db [cache name=" + cacheName +
", key type=" + em.keyType() + ", count=" + prepared + "]");
executeBatch(em, mergeStmt, "writeAll", fromIdx, prepared, lazyEntries);
}
}
finally {
U.closeQuiet(mergeStmt);
}
}
else {
log.debug("Write entries to db one by one using update and insert statements [cache name=" +
cacheName + ", count=" + entries.size() + "]");
PreparedStatement insStmt = null;
PreparedStatement updStmt = null;
try {
for (Cache.Entry<? extends K, ? extends V> entry : entries) {
K key = entry.getKey();
Object keyTypeId = keyTypeId(key);
EntryMapping em = entryMapping(cacheName, keyTypeId, key);
if (currKeyTypeId == null || !currKeyTypeId.equals(keyTypeId)) {
U.closeQuiet(insStmt);
insStmt = conn.prepareStatement(em.insQry);
U.closeQuiet(updStmt);
updStmt = conn.prepareStatement(em.updQry);
currKeyTypeId = keyTypeId;
}
writeUpsert(insStmt, updStmt, em, entry);
}
}
finally {
U.closeQuiet(insStmt);
U.closeQuiet(updStmt);
}
}
}
catch (SQLException e) {
throw new CacheWriterException("Failed to write entries in database", e);
}
finally {
closeConnection(conn);
}
}
/** {@inheritDoc} */
@Override public void delete(Object key) throws CacheWriterException {
assert key != null;
EntryMapping em = entryMapping(session().cacheName(), keyTypeId(key), key);
if (log.isDebugEnabled())
log.debug("Remove value from db [table=" + em.fullTableName() + ", key=" + key + "]");
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = connection();
stmt = conn.prepareStatement(em.remQry);
fillKeyParameters(stmt, em, key);
int delCnt = stmt.executeUpdate();
if (delCnt != 1)
U.warn(log, "Unexpected number of deleted entries [table=" + em.fullTableName() + ", key=" + key +
", expected=1, actual=" + delCnt + "]");
}
catch (SQLException e) {
throw new CacheWriterException("Failed to remove value from database [table=" + em.fullTableName() +
", key=" + key + "]", e);
}
finally {
end(conn, stmt);
}
}
/**
* @param em Entry mapping.
* @param stmt Statement.
* @param desc Statement description for error message.
* @param fromIdx Objects in batch start from index.
* @param prepared Expected objects in batch.
* @param lazyObjs All objects used in batch statement as array.
* @throws SQLException If failed to execute batch statement.
*/
private void executeBatch(EntryMapping em, Statement stmt, String desc, int fromIdx, int prepared,
LazyValue<Object[]> lazyObjs) throws SQLException {
try {
int[] rowCounts = stmt.executeBatch();
int numOfRowCnt = rowCounts.length;
if (numOfRowCnt != prepared)
U.warn(log, "Unexpected number of updated rows [table=" + em.fullTableName() + ", expected=" + prepared +
", actual=" + numOfRowCnt + "]");
for (int i = 0; i < numOfRowCnt; i++) {
int cnt = rowCounts[i];
if (cnt != 1 && cnt != SUCCESS_NO_INFO) {
Object[] objs = lazyObjs.value();
U.warn(log, "Batch " + desc + " returned unexpected updated row count [table=" + em.fullTableName() +
", entry=" + objs[fromIdx + i] + ", expected=1, actual=" + cnt + "]");
}
}
}
catch (BatchUpdateException be) {
int[] rowCounts = be.getUpdateCounts();
for (int i = 0; i < rowCounts.length; i++) {
if (rowCounts[i] == EXECUTE_FAILED) {
Object[] objs = lazyObjs.value();
U.warn(log, "Batch " + desc + " failed on execution [table=" + em.fullTableName() +
", entry=" + objs[fromIdx + i] + "]");
}
}
throw be;
}
}
/** {@inheritDoc} */
@Override public void deleteAll(final Collection<?> keys) throws CacheWriterException {
assert keys != null;
Connection conn = null;
try {
conn = connection();
LazyValue<Object[]> lazyKeys = new LazyValue<Object[]>() {
@Override public Object[] create() {
return keys.toArray();
}
};
String cacheName = session().cacheName();
Object currKeyTypeId = null;
EntryMapping em = null;
PreparedStatement delStmt = null;
int fromIdx = 0, prepared = 0;
for (Object key : keys) {
Object keyTypeId = keyTypeId(key);
em = entryMapping(cacheName, keyTypeId, key);
if (delStmt == null) {
delStmt = conn.prepareStatement(em.remQry);
currKeyTypeId = keyTypeId;
}
if (!currKeyTypeId.equals(keyTypeId)) {
if (log.isDebugEnabled())
log.debug("Delete entries from db [cache name=" + cacheName +
", key type=" + em.keyType() + ", count=" + prepared + "]");
executeBatch(em, delStmt, "deleteAll", fromIdx, prepared, lazyKeys);
fromIdx += prepared;
prepared = 0;
currKeyTypeId = keyTypeId;
}
fillKeyParameters(delStmt, em, key);
delStmt.addBatch();
if (++prepared % batchSz == 0) {
if (log.isDebugEnabled())
log.debug("Delete entries from db [cache name=" + cacheName +
", key type=" + em.keyType() + ", count=" + prepared + "]");
executeBatch(em, delStmt, "deleteAll", fromIdx, prepared, lazyKeys);
fromIdx += prepared;
prepared = 0;
}
}
if (delStmt != null && prepared % batchSz != 0) {
if (log.isDebugEnabled())
log.debug("Delete entries from db [cache name=" + cacheName +
", key type=" + em.keyType() + ", count=" + prepared + "]");
executeBatch(em, delStmt, "deleteAll", fromIdx, prepared, lazyKeys);
}
}
catch (SQLException e) {
throw new CacheWriterException("Failed to remove values from database", e);
}
finally {
closeConnection(conn);
}
}
/**
* Sets the value of the designated parameter using the given object.
*
* @param stmt Prepare statement.
* @param i Index for parameters.
* @param field Field descriptor.
* @param fieldVal Field value.
* @throws CacheException If failed to set statement parameter.
*/
protected void fillParameter(PreparedStatement stmt, int i, CacheTypeFieldMetadata field, @Nullable Object fieldVal)
throws CacheException {
try {
if (fieldVal != null) {
if (field.getJavaType() == UUID.class) {
switch (field.getDatabaseType()) {
case Types.BINARY:
fieldVal = U.uuidToBytes((UUID)fieldVal);
break;
case Types.CHAR:
case Types.VARCHAR:
fieldVal = fieldVal.toString();
break;
}
}
stmt.setObject(i, fieldVal);
}
else
stmt.setNull(i, field.getDatabaseType());
}
catch (SQLException e) {
throw new CacheException("Failed to set statement parameter name: " + field.getDatabaseName(), e);
}
}
/**
* @param stmt Prepare statement.
* @param idx Start index for parameters.
* @param em Entry mapping.
* @param key Key object.
* @return Next index for parameters.
* @throws CacheException If failed to set statement parameters.
*/
protected int fillKeyParameters(PreparedStatement stmt, int idx, EntryMapping em,
Object key) throws CacheException {
for (CacheTypeFieldMetadata field : em.keyColumns()) {
Object fieldVal = extractParameter(em.cacheName, em.keyType(), field.getJavaName(), key);
fillParameter(stmt, idx++, field, fieldVal);
}
return idx;
}
/**
* @param stmt Prepare statement.
* @param m Type mapping description.
* @param key Key object.
* @return Next index for parameters.
* @throws CacheException If failed to set statement parameters.
*/
protected int fillKeyParameters(PreparedStatement stmt, EntryMapping m, Object key) throws CacheException {
return fillKeyParameters(stmt, 1, m, key);
}
/**
* @param stmt Prepare statement.
* @param idx Start index for parameters.
* @param em Type mapping description.
* @param val Value object.
* @return Next index for parameters.
* @throws CacheException If failed to set statement parameters.
*/
protected int fillValueParameters(PreparedStatement stmt, int idx, EntryMapping em, Object val)
throws CacheWriterException {
for (CacheTypeFieldMetadata field : em.uniqValFields) {
Object fieldVal = extractParameter(em.cacheName, em.valueType(), field.getJavaName(), val);
fillParameter(stmt, idx++, field, fieldVal);
}
return idx;
}
/**
* @return Data source.
*/
public DataSource getDataSource() {
return dataSrc;
}
/**
* @param dataSrc Data source.
*/
public void setDataSource(DataSource dataSrc) {
this.dataSrc = dataSrc;
}
/**
* Get database dialect.
*
* @return Database dialect.
*/
public JdbcDialect getDialect() {
return dialect;
}
/**
* Set database dialect.
*
* @param dialect Database dialect.
*/
public void setDialect(JdbcDialect dialect) {
this.dialect = dialect;
}
/**
* Get Max workers thread count. These threads are responsible for execute query.
*
* @return Max workers thread count.
*/
public int getMaximumPoolSize() {
return maxPoolSz;
}
/**
* Set Max workers thread count. These threads are responsible for execute query.
*
* @param maxPoolSz Max workers thread count.
*/
public void setMaximumPoolSize(int maxPoolSz) {
this.maxPoolSz = maxPoolSz;
}
/**
* Get maximum batch size for delete and delete operations.
*
* @return Maximum batch size.
*/
public int getBatchSize() {
return batchSz;
}
/**
* Set maximum batch size for write and delete operations.
*
* @param batchSz Maximum batch size.
*/
public void setBatchSize(int batchSz) {
this.batchSz = batchSz;
}
/**
* Parallel load cache minimum row count threshold.
*
* @return If {@code 0} then load sequentially.
*/
public int getParallelLoadCacheMinimumThreshold() {
return parallelLoadCacheMinThreshold;
}
/**
* Parallel load cache minimum row count threshold.
*
* @param parallelLoadCacheMinThreshold Minimum row count threshold. If {@code 0} then load sequentially.
*/
public void setParallelLoadCacheMinimumThreshold(int parallelLoadCacheMinThreshold) {
this.parallelLoadCacheMinThreshold = parallelLoadCacheMinThreshold;
}
/**
* @return Ignite instance.
*/
protected Ignite ignite() {
return ignite;
}
/**
* @return Store session.
*/
protected CacheStoreSession session() {
return ses;
}
/**
* Entry mapping description.
*/
protected static class EntryMapping {
/** Cache name. */
private final String cacheName;
/** Database dialect. */
private final JdbcDialect dialect;
/** Select border for range queries. */
private final String loadCacheSelRangeQry;
/** Select all items query. */
private final String loadCacheQry;
/** Select item query. */
private final String loadQrySingle;
/** Select items query. */
private final String loadQry;
/** Merge item(s) query. */
private final String mergeQry;
/** Update item query. */
private final String insQry;
/** Update item query. */
private final String updQry;
/** Remove item(s) query. */
private final String remQry;
/** Max key count for load query per statement. */
private final int maxKeysPerStmt;
/** Database key columns. */
private final Collection<String> keyCols;
/** Database unique value columns. */
private final Collection<String> cols;
/** Select query columns index. */
private final Map<String, Integer> loadColIdxs;
/** Unique value fields. */
private final Collection<CacheTypeFieldMetadata> uniqValFields;
/** Type metadata. */
private final CacheTypeMetadata typeMeta;
/** Full table name. */
private final String fullTblName;
/**
* @param cacheName Cache name.
* @param dialect JDBC dialect.
* @param typeMeta Type metadata.
*/
public EntryMapping(@Nullable String cacheName, JdbcDialect dialect, CacheTypeMetadata typeMeta) {
this.cacheName = cacheName;
this.dialect = dialect;
this.typeMeta = typeMeta;
Collection<CacheTypeFieldMetadata> keyFields = typeMeta.getKeyFields();
Collection<CacheTypeFieldMetadata> valFields = typeMeta.getValueFields();
keyCols = databaseColumns(keyFields);
uniqValFields = F.view(valFields, new IgnitePredicate<CacheTypeFieldMetadata>() {
@Override public boolean apply(CacheTypeFieldMetadata col) {
return !keyCols.contains(col.getDatabaseName());
}
});
String schema = typeMeta.getDatabaseSchema();
String tblName = typeMeta.getDatabaseTable();
fullTblName = F.isEmpty(schema) ? tblName : schema + "." + tblName;
Collection<String> uniqValCols = databaseColumns(uniqValFields);
cols = F.concat(false, keyCols, uniqValCols);
loadColIdxs = U.newHashMap(cols.size());
int idx = 1;
for (String col : cols)
loadColIdxs.put(col, idx++);
loadCacheQry = dialect.loadCacheQuery(fullTblName, cols);
loadCacheSelRangeQry = dialect.loadCacheSelectRangeQuery(fullTblName, keyCols);
loadQrySingle = dialect.loadQuery(fullTblName, keyCols, cols, 1);
maxKeysPerStmt = dialect.getMaxParameterCount() / keyCols.size();
loadQry = dialect.loadQuery(fullTblName, keyCols, cols, maxKeysPerStmt);
insQry = dialect.insertQuery(fullTblName, keyCols, uniqValCols);
updQry = dialect.updateQuery(fullTblName, keyCols, uniqValCols);
mergeQry = dialect.mergeQuery(fullTblName, keyCols, uniqValCols);
remQry = dialect.removeQuery(fullTblName, keyCols);
}
/**
* Extract database column names from {@link CacheTypeFieldMetadata}.
*
* @param dsc collection of {@link CacheTypeFieldMetadata}.
* @return Collection with database column names.
*/
private static Collection<String> databaseColumns(Collection<CacheTypeFieldMetadata> dsc) {
return F.transform(dsc, new C1<CacheTypeFieldMetadata, String>() {
/** {@inheritDoc} */
@Override public String apply(CacheTypeFieldMetadata col) {
return col.getDatabaseName();
}
});
}
/**
* Construct query for select values with key count less or equal {@code maxKeysPerStmt}
*
* @param keyCnt Key count.
* @return Load query statement text.
*/
protected String loadQuery(int keyCnt) {
assert keyCnt <= maxKeysPerStmt;
if (keyCnt == maxKeysPerStmt)
return loadQry;
if (keyCnt == 1)
return loadQrySingle;
return dialect.loadQuery(fullTblName, keyCols, cols, keyCnt);
}
/**
* Construct query for select values in range.
*
* @param appendLowerBound Need add lower bound for range.
* @param appendUpperBound Need add upper bound for range.
* @return Query with range.
*/
protected String loadCacheRangeQuery(boolean appendLowerBound, boolean appendUpperBound) {
return dialect.loadCacheRangeQuery(fullTblName, keyCols, cols, appendLowerBound, appendUpperBound);
}
/**
* @return Key type.
*/
protected String keyType() {
return typeMeta.getKeyType();
}
/**
* @return Value type.
*/
protected String valueType() {
return typeMeta.getValueType();
}
/**
* Gets key columns.
*
* @return Key columns.
*/
protected Collection<CacheTypeFieldMetadata> keyColumns() {
return typeMeta.getKeyFields();
}
/**
* Gets value columns.
*
* @return Value columns.
*/
protected Collection<CacheTypeFieldMetadata> valueColumns() {
return typeMeta.getValueFields();
}
/**
* Get full table name.
*
* @return <schema>.<table name>
*/
protected String fullTableName() {
return fullTblName;
}
}
/**
* Worker for load cache using custom user query.
*
* @param <K1> Key type.
* @param <V1> Value type.
*/
private class LoadCacheCustomQueryWorker<K1, V1> implements Callable<Void> {
/** Entry mapping description. */
private final EntryMapping em;
/** User query. */
private final String qry;
/** Closure for loaded values. */
private final IgniteBiInClosure<K1, V1> clo;
/**
* @param em Entry mapping description.
* @param qry User query.
* @param clo Closure for loaded values.
*/
private LoadCacheCustomQueryWorker(EntryMapping em, String qry, IgniteBiInClosure<K1, V1> clo) {
this.em = em;
this.qry = qry;
this.clo = clo;
}
/** {@inheritDoc} */
@Override public Void call() throws Exception {
if (log.isDebugEnabled())
log.debug("Load cache using custom query [cache name= " + em.cacheName +
", key type=" + em.keyType() + ", query=" + qry + "]");
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = openConnection(true);
stmt = conn.prepareStatement(qry);
ResultSet rs = stmt.executeQuery();
ResultSetMetaData meta = rs.getMetaData();
Map<String, Integer> colIdxs = U.newHashMap(meta.getColumnCount());
for (int i = 1; i <= meta.getColumnCount(); i++)
colIdxs.put(meta.getColumnLabel(i), i);
while (rs.next()) {
K1 key = buildObject(em.cacheName, em.keyType(), em.keyColumns(), colIdxs, rs);
V1 val = buildObject(em.cacheName, em.valueType(), em.valueColumns(), colIdxs, rs);
clo.apply(key, val);
}
return null;
}
catch (SQLException e) {
throw new CacheLoaderException("Failed to execute custom query for load cache", e);
}
finally {
U.closeQuiet(stmt);
U.closeQuiet(conn);
}
}
}
/**
* Lazy initialization of value.
*
* @param <T> Cached object type
*/
private abstract static class LazyValue<T> {
/** Cached value. */
private T val;
/**
* @return Construct value.
*/
protected abstract T create();
/**
* @return Value.
*/
public T value() {
if (val == null)
val = create();
return val;
}
}
/**
* Worker for load by keys.
*
* @param <K1> Key type.
* @param <V1> Value type.
*/
private class LoadWorker<K1, V1> implements Callable<Map<K1, V1>> {
/** Connection. */
private final Connection conn;
/** Keys for load. */
private final Collection<K1> keys;
/** Entry mapping description. */
private final EntryMapping em;
/**
* @param conn Connection.
* @param em Entry mapping description.
*/
private LoadWorker(Connection conn, EntryMapping em) {
this.conn = conn;
this.em = em;
keys = new ArrayList<>(em.maxKeysPerStmt);
}
/** {@inheritDoc} */
@Override public Map<K1, V1> call() throws Exception {
if (log.isDebugEnabled())
log.debug("Load values from db [table= " + em.fullTableName() +
", key count=" + keys.size() + "]");
PreparedStatement stmt = null;
try {
stmt = conn.prepareStatement(em.loadQuery(keys.size()));
int idx = 1;
for (Object key : keys)
for (CacheTypeFieldMetadata field : em.keyColumns()) {
Object fieldVal = extractParameter(em.cacheName, em.keyType(), field.getJavaName(), key);
fillParameter(stmt, idx++, field, fieldVal);
}
ResultSet rs = stmt.executeQuery();
Map<K1, V1> entries = U.newHashMap(keys.size());
while (rs.next()) {
K1 key = buildObject(em.cacheName, em.keyType(), em.keyColumns(), em.loadColIdxs, rs);
V1 val = buildObject(em.cacheName, em.valueType(), em.valueColumns(), em.loadColIdxs, rs);
entries.put(key, val);
}
return entries;
}
finally {
U.closeQuiet(stmt);
}
}
}
}
| vsisko/incubator-ignite | modules/core/src/main/java/org/apache/ignite/cache/store/jdbc/CacheAbstractJdbcStore.java | Java | apache-2.0 | 62,015 |
connection = ActiveRecord::Base.connection
puts 'adding govt data'
%w[states districts zip_codes districts_zip_codes legislators].each do |table|
puts "loading #{table}"
connection.execute(IO.read("db/seed_data/#{table}.sql"))
end
%w[states districts zip_codes legislators].each do |table|
puts "updating table IDs for #{table}"
result = connection.execute("SELECT id FROM #{table} ORDER BY id DESC LIMIT 1")
connection.execute(
"ALTER SEQUENCE #{table}_id_seq RESTART WITH #{result.first['id'].to_i + 1}"
)
end
| MayOneUS/mayday-2.0-backend | db/seeds.rb | Ruby | apache-2.0 | 532 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_111) on Wed Jan 04 22:31:31 EST 2017 -->
<title>Uses of Class org.drip.sample.stochasticvolatility.HestonAMSTPayoffTransform</title>
<meta name="date" content="2017-01-04">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.drip.sample.stochasticvolatility.HestonAMSTPayoffTransform";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../org/drip/sample/stochasticvolatility/HestonAMSTPayoffTransform.html" title="class in org.drip.sample.stochasticvolatility">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/drip/sample/stochasticvolatility/class-use/HestonAMSTPayoffTransform.html" target="_top">Frames</a></li>
<li><a href="HestonAMSTPayoffTransform.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class org.drip.sample.stochasticvolatility.HestonAMSTPayoffTransform" class="title">Uses of Class<br>org.drip.sample.stochasticvolatility.HestonAMSTPayoffTransform</h2>
</div>
<div class="classUseContainer">No usage of org.drip.sample.stochasticvolatility.HestonAMSTPayoffTransform</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../org/drip/sample/stochasticvolatility/HestonAMSTPayoffTransform.html" title="class in org.drip.sample.stochasticvolatility">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/drip/sample/stochasticvolatility/class-use/HestonAMSTPayoffTransform.html" target="_top">Frames</a></li>
<li><a href="HestonAMSTPayoffTransform.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| lakshmiDRIP/DRIP | Javadoc/org/drip/sample/stochasticvolatility/class-use/HestonAMSTPayoffTransform.html | HTML | apache-2.0 | 4,663 |
<?php
/**
* Activity
*
* PHP version 5
*
* @category Class
* @package ultracart\v2
* @author Swagger Codegen team
* @link https://github.com/swagger-api/swagger-codegen
*/
/**
* UltraCart Rest API V2
*
* UltraCart REST API Version 2
*
* OpenAPI spec version: 2.0.0
* Contact: [email protected]
* Generated by: https://github.com/swagger-api/swagger-codegen.git
* Swagger Codegen version: 2.4.15-SNAPSHOT
*/
/**
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen
* Do not edit the class manually.
*/
namespace ultracart\v2\models;
use \ArrayAccess;
use \ultracart\v2\ObjectSerializer;
/**
* Activity Class Doc Comment
*
* @category Class
* @package ultracart\v2
* @author Swagger Codegen team
* @link https://github.com/swagger-api/swagger-codegen
*/
class Activity implements ModelInterface, ArrayAccess
{
const DISCRIMINATOR = null;
/**
* The original name of the model.
*
* @var string
*/
protected static $swaggerModelName = 'Activity';
/**
* Array of property to type mappings. Used for (de)serialization
*
* @var string[]
*/
protected static $swaggerTypes = [
'action' => 'string',
'metric' => 'string',
'subject' => 'string',
'ts' => 'int',
'type' => 'string',
'uuid' => 'string'
];
/**
* Array of property to format mappings. Used for (de)serialization
*
* @var string[]
*/
protected static $swaggerFormats = [
'action' => null,
'metric' => null,
'subject' => null,
'ts' => 'int64',
'type' => null,
'uuid' => null
];
/**
* Array of property to type mappings. Used for (de)serialization
*
* @return array
*/
public static function swaggerTypes()
{
return self::$swaggerTypes;
}
/**
* Array of property to format mappings. Used for (de)serialization
*
* @return array
*/
public static function swaggerFormats()
{
return self::$swaggerFormats;
}
/**
* Array of attributes where the key is the local name,
* and the value is the original name
*
* @var string[]
*/
protected static $attributeMap = [
'action' => 'action',
'metric' => 'metric',
'subject' => 'subject',
'ts' => 'ts',
'type' => 'type',
'uuid' => 'uuid'
];
/**
* Array of attributes to setter functions (for deserialization of responses)
*
* @var string[]
*/
protected static $setters = [
'action' => 'setAction',
'metric' => 'setMetric',
'subject' => 'setSubject',
'ts' => 'setTs',
'type' => 'setType',
'uuid' => 'setUuid'
];
/**
* Array of attributes to getter functions (for serialization of requests)
*
* @var string[]
*/
protected static $getters = [
'action' => 'getAction',
'metric' => 'getMetric',
'subject' => 'getSubject',
'ts' => 'getTs',
'type' => 'getType',
'uuid' => 'getUuid'
];
/**
* Array of attributes where the key is the local name,
* and the value is the original name
*
* @return array
*/
public static function attributeMap()
{
return self::$attributeMap;
}
/**
* Array of attributes to setter functions (for deserialization of responses)
*
* @return array
*/
public static function setters()
{
return self::$setters;
}
/**
* Array of attributes to getter functions (for serialization of requests)
*
* @return array
*/
public static function getters()
{
return self::$getters;
}
/**
* The original name of the model.
*
* @return string
*/
public function getModelName()
{
return self::$swaggerModelName;
}
/**
* Associative array for storing property values
*
* @var mixed[]
*/
protected $container = [];
/**
* Constructor
*
* @param mixed[] $data Associated array of property values
* initializing the model
*/
public function __construct(array $data = null)
{
$this->container['action'] = isset($data['action']) ? $data['action'] : null;
$this->container['metric'] = isset($data['metric']) ? $data['metric'] : null;
$this->container['subject'] = isset($data['subject']) ? $data['subject'] : null;
$this->container['ts'] = isset($data['ts']) ? $data['ts'] : null;
$this->container['type'] = isset($data['type']) ? $data['type'] : null;
$this->container['uuid'] = isset($data['uuid']) ? $data['uuid'] : null;
}
/**
* Show all the invalid properties with reasons.
*
* @return array invalid properties with reasons
*/
public function listInvalidProperties()
{
$invalidProperties = [];
return $invalidProperties;
}
/**
* Validate all the properties in the model
* return true if all passed
*
* @return bool True if all properties are valid
*/
public function valid()
{
return count($this->listInvalidProperties()) === 0;
}
/**
* Gets action
*
* @return string
*/
public function getAction()
{
return $this->container['action'];
}
/**
* Sets action
*
* @param string $action action
*
* @return $this
*/
public function setAction($action)
{
$this->container['action'] = $action;
return $this;
}
/**
* Gets metric
*
* @return string
*/
public function getMetric()
{
return $this->container['metric'];
}
/**
* Sets metric
*
* @param string $metric metric
*
* @return $this
*/
public function setMetric($metric)
{
$this->container['metric'] = $metric;
return $this;
}
/**
* Gets subject
*
* @return string
*/
public function getSubject()
{
return $this->container['subject'];
}
/**
* Sets subject
*
* @param string $subject subject
*
* @return $this
*/
public function setSubject($subject)
{
$this->container['subject'] = $subject;
return $this;
}
/**
* Gets ts
*
* @return int
*/
public function getTs()
{
return $this->container['ts'];
}
/**
* Sets ts
*
* @param int $ts ts
*
* @return $this
*/
public function setTs($ts)
{
$this->container['ts'] = $ts;
return $this;
}
/**
* Gets type
*
* @return string
*/
public function getType()
{
return $this->container['type'];
}
/**
* Sets type
*
* @param string $type type
*
* @return $this
*/
public function setType($type)
{
$this->container['type'] = $type;
return $this;
}
/**
* Gets uuid
*
* @return string
*/
public function getUuid()
{
return $this->container['uuid'];
}
/**
* Sets uuid
*
* @param string $uuid uuid
*
* @return $this
*/
public function setUuid($uuid)
{
$this->container['uuid'] = $uuid;
return $this;
}
/**
* Returns true if offset exists. False otherwise.
*
* @param integer $offset Offset
*
* @return boolean
*/
public function offsetExists($offset)
{
return isset($this->container[$offset]);
}
/**
* Gets offset.
*
* @param integer $offset Offset
*
* @return mixed
*/
public function offsetGet($offset)
{
return isset($this->container[$offset]) ? $this->container[$offset] : null;
}
/**
* Sets value based on offset.
*
* @param integer $offset Offset
* @param mixed $value Value to be set
*
* @return void
*/
public function offsetSet($offset, $value)
{
if (is_null($offset)) {
$this->container[] = $value;
} else {
$this->container[$offset] = $value;
}
}
/**
* Unsets offset.
*
* @param integer $offset Offset
*
* @return void
*/
public function offsetUnset($offset)
{
unset($this->container[$offset]);
}
/**
* Gets the string presentation of the object
*
* @return string
*/
public function __toString()
{
if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print
return json_encode(
ObjectSerializer::sanitizeForSerialization($this),
JSON_PRETTY_PRINT
);
}
return json_encode(ObjectSerializer::sanitizeForSerialization($this));
}
}
| UltraCart/rest_api_v2_sdk_php | lib/models/Activity.php | PHP | apache-2.0 | 9,144 |
# Evelyna oligantha Poepp. & Endl. SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Liliopsida/Asparagales/Orchidaceae/Elleanthus/Elleanthus oliganthus/ Syn. Evelyna oligantha/README.md | Markdown | apache-2.0 | 189 |
using System;
using System.Linq.Expressions;
namespace storagecore.EntityFrameworkCore.Query
{
public class Filter<TEntity>
{
public Filter(Expression<Func<TEntity, bool>> expression)
{
Expression = expression;
}
public Expression<Func<TEntity, bool>> Expression { get; private set; }
public void AddExpression(Expression<Func<TEntity, bool>> newExpression)
{
if (newExpression == null) throw new ArgumentNullException(nameof(newExpression), $"{nameof(newExpression)} is null.");
if (Expression == null) Expression = newExpression;
var parameter = System.Linq.Expressions.Expression.Parameter(typeof(TEntity));
var leftVisitor = new ReplaceExpressionVisitor(newExpression.Parameters[0], parameter);
var left = leftVisitor.Visit(newExpression.Body);
var rightVisitor = new ReplaceExpressionVisitor(Expression.Parameters[0], parameter);
var right = rightVisitor.Visit(Expression.Body);
Expression = System.Linq.Expressions.Expression.Lambda<Func<TEntity, bool>>(System.Linq.Expressions.Expression.AndAlso(left, right), parameter);
}
}
}
| FlorinskiyDI/coremanage | coremanage/storagecore.EntityFrameworkCore/Query/Filter.cs | C# | apache-2.0 | 1,222 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# OPTIONS_GHC -Wall #-}
-- TODO: Complex Numbers
{-|
Embeds Fortran's type system in Haskell via the 'D' GADT.
== Note: Phantom Types and GADTs
Lots of the data types in this module are parameterised by phantom types. These
are types which appear at the type-level, but not at the value level. They are
there to make things more type-safe.
In addition, a lot of the data types are GADTs. In a phantom-type-indexed GADT,
the phantom type often restricts which GADT constructors a particular value may
be an instance of. This is very useful for restricting value-level terms based
on type-level information.
-}
module Language.Fortran.Model.Types where
import Data.Int (Int16, Int32, Int64,
Int8)
import Data.List (intersperse)
import Data.Monoid (Endo (..))
import Data.Typeable (Typeable)
import Data.Word (Word8)
import Data.Singletons.TypeLits
import Data.Vinyl hiding (Field)
import Data.Vinyl.Functor
import Language.Expression.Pretty
import Language.Fortran.Model.Singletons
--------------------------------------------------------------------------------
-- * Fortran Types
{-|
This is the main embedding of Fortran types. A value of type @D a@ represents
the Fortran type which corresponds to the Haskell type @a@. @a@ is a phantom
type parameter. There is at most one instance of @D a@ for each @a@. This means
that a value of type @D a@ acts as a kind of proof that it possible to have a
Fortran type corresponding to the Haskell type @a@ -- and that when you match on
@D a@ knowing the particular @a@ you have, you know which constructor you will
get. This is a nice property because it means that GHC (with
@-fwarn-incomplete-patterns@) will not warn when you match on an impossible
case. It eliminates situations where you'd otherwise write @error "impossible:
..."@.
* @'DPrim' p :: D ('PrimS' a)@ is for primitive types. It contains a value @p@
of type @'Prim' p k a@ for some @p@, @k@, @a@. When matching on something of
type @D ('PrimS' a)@, you know it can only contain a primitive type.
* @'DArray' i v :: D ('Array' i v)@ is for arrays. It contains instances of @'Index'
i@ and @'ArrValue' a@. @'Index' i@ is a proof that @i@ can be used as an index,
and @'ArrValue' a@ is a proof that @a@ can be stored in arrays.
* @'DData' s xs :: D ('Record' name fs)@ is for user-defined data types. The
type has a name, represented at the type level by the type parameter @name@ of
kind 'Symbol'. The constructor contains @s :: 'SSymbol' name@, which acts as a
sort of value-level representation of the name. 'SSymbol' is from the
@singletons@ library. It also contains @xs :: 'Rec' ('Field' D) fs@. @fs@ is a
type-level list of pairs, pairing field names with field types. @'Field' D
'(fname, b)@ is a value-level pair of @'SSymbol' fname@ and @D b@. The vinyl
record is a list of fields, one for each pair in @fs@.
-}
data D a where
DPrim :: Prim p k a -> D (PrimS a)
DArray :: Index i -> ArrValue a -> D (Array i a)
DData :: SSymbol name -> Rec (Field D) fs -> D (Record name fs)
--------------------------------------------------------------------------------
-- * Semantic Types
newtype Bool8 = Bool8 { getBool8 :: Int8 } deriving (Show, Num, Eq, Typeable)
newtype Bool16 = Bool16 { getBool16 :: Int16 } deriving (Show, Num, Eq, Typeable)
newtype Bool32 = Bool32 { getBool32 :: Int32 } deriving (Show, Num, Eq, Typeable)
newtype Bool64 = Bool64 { getBool64 :: Int64 } deriving (Show, Num, Eq, Typeable)
newtype Char8 = Char8 { getChar8 :: Word8 } deriving (Show, Num, Eq, Typeable)
{-|
This newtype wrapper is used in 'DPrim' for semantic primitive types. This means
that when matching on something of type @'D' ('PrimS' a)@, we know it can't be
an array or a record.
-}
newtype PrimS a = PrimS { getPrimS :: a }
deriving (Show, Eq, Typeable)
--------------------------------------------------------------------------------
-- * Primitive Types
{-|
Lists the allowed primitive Fortran types. For example, @'PInt8' :: 'Prim' 'P8
''BTInt' 'Int8'@ represents 8-bit integers. 'Prim' has three phantom type
parameters: precision, base type and semantic Haskell type. Precision is the
number of bits used to store values of that type. The base type represents the
corresponding Fortran base type, e.g. @integer@ or @real@. Constructors are only
provided for those Fortran types which are semantically valid, so for example no
constructor is provided for a 16-bit real. A value of type @'Prim' p k a@ can be
seen as a proof that there is some Fortran primitive type with those parameters.
-}
data Prim p k a where
PInt8 :: Prim 'P8 'BTInt Int8
PInt16 :: Prim 'P16 'BTInt Int16
PInt32 :: Prim 'P32 'BTInt Int32
PInt64 :: Prim 'P64 'BTInt Int64
PBool8 :: Prim 'P8 'BTLogical Bool8
PBool16 :: Prim 'P16 'BTLogical Bool16
PBool32 :: Prim 'P32 'BTLogical Bool32
PBool64 :: Prim 'P64 'BTLogical Bool64
PFloat :: Prim 'P32 'BTReal Float
PDouble :: Prim 'P64 'BTReal Double
PChar :: Prim 'P8 'BTChar Char8
--------------------------------------------------------------------------------
-- * Arrays
-- | Specifies which types can be used as array indices.
data Index a where
Index :: Prim p 'BTInt a -> Index (PrimS a)
-- | Specifies which types can be stored in arrays. Currently arrays of arrays
-- are not supported.
data ArrValue a where
ArrPrim :: Prim p k a -> ArrValue (PrimS a)
ArrData :: SSymbol name -> Rec (Field ArrValue) fs -> ArrValue (Record name fs)
-- | An array with a phantom index type. Mostly used at the type-level to
-- constrain instances of @'D' (Array i a)@ etc.
newtype Array i a = Array [a]
--------------------------------------------------------------------------------
-- * Records
-- | A field over a pair of name and value type.
data Field f field where
Field :: SSymbol name -> f a -> Field f '(name, a)
-- | A type of records with the given @name@ and @fields@. Mostly used at the
-- type level to constrain instances of @'D' (Record name fields)@ etc.
data Record name fields where
Record :: SSymbol name -> Rec (Field Identity) fields -> Record name fields
--------------------------------------------------------------------------------
-- * Combinators
-- | Any Fortran index type is a valid Fortran type.
dIndex :: Index i -> D i
dIndex (Index p) = DPrim p
-- | Anything that can be stored in Fortran arrays is a valid Fortran type.
dArrValue :: ArrValue a -> D a
dArrValue (ArrPrim p) = DPrim p
dArrValue (ArrData nameSym fieldArrValues) =
DData nameSym (rmap (overField' dArrValue) fieldArrValues)
-- | Given a field with known contents, we can change the functor and value
-- type.
overField :: (f a -> g b) -> Field f '(name, a) -> Field g '(name, b)
overField f (Field n x) = Field n (f x)
-- | Given a field with unknown contents, we can change the functor but not the
-- value type.
overField' :: (forall a. f a -> g a) -> Field f nv -> Field g nv
overField' f (Field n x) = Field n (f x)
traverseField' :: (Functor t) => (forall a. f a -> t (g a)) -> Field f nv -> t (Field g nv)
traverseField' f (Field n x) = Field n <$> f x
-- | Combine two fields over the same name-value pair but (potentially)
-- different functors.
zipFieldsWith :: (forall a. f a -> g a -> h a) -> Field f nv -> Field g nv -> Field h nv
zipFieldsWith f (Field _ x) (Field n y) = Field n (f x y)
zip3FieldsWith
:: (forall a. f a -> g a -> h a -> i a)
-> Field f nv
-> Field g nv
-> Field h nv
-> Field i nv
zip3FieldsWith f (Field _ x) (Field _ y) (Field n z) = Field n (f x y z)
--------------------------------------------------------------------------------
-- Pretty Printing
instance Pretty1 (Prim p k) where
prettys1Prec p = \case
PInt8 -> showString "integer8"
PInt16 -> showString "integer16"
PInt32 -> showString "integer32"
PInt64 -> showString "integer64"
PFloat -> showString "real"
PDouble -> showParen (p > 8) $ showString "double precision"
PBool8 -> showString "logical8"
PBool16 -> showString "logical16"
PBool32 -> showString "logical32"
PBool64 -> showString "logical64"
PChar -> showString "character"
instance Pretty1 ArrValue where
prettys1Prec p = prettys1Prec p . dArrValue
instance (Pretty1 f) => Pretty1 (Field f) where
prettys1Prec _ = \case
Field fname x ->
prettys1Prec 0 x .
showString " " .
withKnownSymbol fname (showString (symbolVal fname))
-- | e.g. "type custom_type { character a, integer array b }"
instance Pretty1 D where
prettys1Prec p = \case
DPrim px -> prettys1Prec p px
DArray _ pv -> prettys1Prec p pv . showString " array"
DData rname fields ->
showParen (p > 8)
$ showString "type "
. withKnownSymbol rname (showString (symbolVal rname))
. showString "{ "
. appEndo ( mconcat
. intersperse (Endo $ showString ", ")
. recordToList
. rmap (Const . Endo . prettys1Prec 0)
$ fields)
. showString " }"
| dorchard/camfort | src/Language/Fortran/Model/Types.hs | Haskell | apache-2.0 | 9,913 |
# Euosma callosa (F.Muell.) Kuntze SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
Logania callosa F.Muell.
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Gentianales/Rubiaceae/Euosma/Euosma callosa/README.md | Markdown | apache-2.0 | 202 |
## toast-with-duration-headref
#### Toast with duration


*Syntax*
{% codetabs name="React Native", type="js" -%}
import React, { Component } from "react";
import { Container, Header, Content, Text, Button, Toast } from "native-base";
export default class ToastDuration extends Component {
constructor(props) {
super(props);
this.state = {
showToast: false
};
}
render() {
return (
<Container>
<Header />
<Content padder>
<Button
onPress={() =>
Toast.show({
text: "Wrong password!",
buttonText: "Okay",
duration: 3000
})}
>
<Text>Toast</Text>
</Button>
</Content>
</Container>
);
}
}
{%- language name="Vue Native", type="vue" -%}
<template>
<nb-container>
<nb-header />
<nb-content padder>
<nb-button :onPress="handleBtnPress">
<nb-text>Toast</nb-text>
</nb-button>
</nb-content>
</nb-container>
</template>
<script>
import React from "react";
import { Toast } from "native-base";
export default {
methods: {
handleBtnPress: function() {
Toast.show({
text: "Wrong password!",
buttonText: "Okay",
duration: 3000
});
}
}
};
</script>
{%- endcodetabs %}
<p>
<div id="" class="mobileDevice" style="background: url("https://docs-v2.nativebase.io/docs/assets/iosphone.png") no-repeat; padding: 63px 20px 100px 15px; width: 292px; height: 600px;margin:0 auto;float:none;">
<img src="https://github.com/GeekyAnts/NativeBase-KitchenSink/raw/v2.6.1/screenshots/ios/toast-duration.gif" alt="" style="display:block !important" />
</div>
</p>
<br />
| GeekyAnts/native-base-docs | _book/docs/components/toast/Toast-with-duration.md | Markdown | apache-2.0 | 2,043 |
package de.jungblut.math.squashing;
import de.jungblut.math.DoubleMatrix;
import de.jungblut.math.MathUtils;
/**
* Logistic error function implementation.
*
* @author thomas.jungblut
*
*/
public final class LogisticErrorFunction implements ErrorFunction {
@Override
public double calculateError(DoubleMatrix y, DoubleMatrix hypothesis) {
return (y.multiply(-1d)
.multiplyElementWise(MathUtils.logMatrix(hypothesis)).subtract((y
.subtractBy(1.0d)).multiplyElementWise(MathUtils.logMatrix(hypothesis
.subtractBy(1d))))).sum();
}
}
| sourcewarehouse/thomasjungblut | src/de/jungblut/math/squashing/LogisticErrorFunction.java | Java | apache-2.0 | 574 |
"""
Django settings for sparta project.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = ')mg$xo^v*2mmwidr0ak6%9&!@e18v8t#7@+vd+wqg8kydb48k7'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'blog',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'sparta.urls'
WSGI_APPLICATION = 'sparta.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.6/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'USER':'root',
'NAME':'fordjango',
'PASSWORD':'123456',
'HOST':'localhost',
'PORT':''
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.6/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
STATIC_ROOT = os.path.join('/home/dexter/weaponx/Django/sparta/sparta/static')
STATIC_URL = '/assets/'
STATICFILES_DIRS = (
'/home/dexter/weaponx/Django/sparta/sparta/assets',
)
TEMPLATE_DIRS=('/home/dexter/weaponx/Django/sparta/sparta/template',) | sureshprasanna70/the-spartan-blog | sparta/settings.py | Python | apache-2.0 | 2,223 |
namespace CJia.PIVAS.App.UI
{
partial class BatchIllfieldLabelCollectReport
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.Detail = new DevExpress.XtraReports.UI.DetailBand();
this.xrTable1 = new DevExpress.XtraReports.UI.XRTable();
this.xrTableRow1 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrIllfield = new DevExpress.XtraReports.UI.XRTableCell();
this.xrBatchZ = new DevExpress.XtraReports.UI.XRTableCell();
this.xrBatch1 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrBatch2 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrBatch3 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrBatch4 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrBatch5 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrBatch6 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrBatchB = new DevExpress.XtraReports.UI.XRTableCell();
this.xrBatchW = new DevExpress.XtraReports.UI.XRTableCell();
this.xrBatchL = new DevExpress.XtraReports.UI.XRTableCell();
this.xrAllBatch = new DevExpress.XtraReports.UI.XRTableCell();
this.TopMargin = new DevExpress.XtraReports.UI.TopMarginBand();
this.BottomMargin = new DevExpress.XtraReports.UI.BottomMarginBand();
this.ReportHeader = new DevExpress.XtraReports.UI.ReportHeaderBand();
this.xlZX = new DevExpress.XtraReports.UI.XRLabel();
this.xlZXDate = new DevExpress.XtraReports.UI.XRLabel();
this.xlKDDate = new DevExpress.XtraReports.UI.XRLabel();
this.xlKD1 = new DevExpress.XtraReports.UI.XRLabel();
this.xrDY1 = new DevExpress.XtraReports.UI.XRLabel();
this.xlDYstart = new DevExpress.XtraReports.UI.XRLabel();
this.xrDY2 = new DevExpress.XtraReports.UI.XRLabel();
this.xlDYEnd = new DevExpress.XtraReports.UI.XRLabel();
this.xrRepertHeader = new DevExpress.XtraReports.UI.XRLabel();
this.ReportFooter = new DevExpress.XtraReports.UI.ReportFooterBand();
this.xrLabel8 = new DevExpress.XtraReports.UI.XRLabel();
this.xrPrintBy = new DevExpress.XtraReports.UI.XRLabel();
this.lblPrintDate = new DevExpress.XtraReports.UI.XRLabel();
this.xrLabel6 = new DevExpress.XtraReports.UI.XRLabel();
this.xrPageInfo1 = new DevExpress.XtraReports.UI.XRPageInfo();
this.xr = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell3 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell2 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell4 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow3 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell1 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell8 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell9 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell10 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell11 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell5 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell6 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell7 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTable3 = new DevExpress.XtraReports.UI.XRTable();
this.GroupHeader1 = new DevExpress.XtraReports.UI.GroupHeaderBand();
((System.ComponentModel.ISupportInitialize)(this.xrTable1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable3)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this)).BeginInit();
//
// Detail
//
this.Detail.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.xrTable1});
this.Detail.HeightF = 25.95833F;
this.Detail.Name = "Detail";
this.Detail.Padding = new DevExpress.XtraPrinting.PaddingInfo(0, 0, 0, 0, 100F);
this.Detail.TextAlignment = DevExpress.XtraPrinting.TextAlignment.TopLeft;
//
// xrTable1
//
this.xrTable1.LocationFloat = new DevExpress.Utils.PointFloat(16.49996F, 0F);
this.xrTable1.Name = "xrTable1";
this.xrTable1.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow1});
this.xrTable1.SizeF = new System.Drawing.SizeF(823.5001F, 25F);
//
// xrTableRow1
//
this.xrTableRow1.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrIllfield,
this.xrBatchZ,
this.xrBatch1,
this.xrBatch2,
this.xrBatch3,
this.xrBatch4,
this.xrBatch5,
this.xrBatch6,
this.xrBatchB,
this.xrBatchW,
this.xrBatchL,
this.xrAllBatch});
this.xrTableRow1.Name = "xrTableRow1";
this.xrTableRow1.Weight = 1D;
//
// xrIllfield
//
this.xrIllfield.Borders = ((DevExpress.XtraPrinting.BorderSide)((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Bottom)));
this.xrIllfield.Name = "xrIllfield";
this.xrIllfield.StylePriority.UseBorders = false;
this.xrIllfield.StylePriority.UseTextAlignment = false;
this.xrIllfield.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleCenter;
this.xrIllfield.Weight = 0.56262541342602934D;
//
// xrBatchZ
//
this.xrBatchZ.Borders = ((DevExpress.XtraPrinting.BorderSide)((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Bottom)));
this.xrBatchZ.Name = "xrBatchZ";
this.xrBatchZ.StylePriority.UseBorders = false;
this.xrBatchZ.StylePriority.UseTextAlignment = false;
this.xrBatchZ.Text = "xrBatchZ";
this.xrBatchZ.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleCenter;
this.xrBatchZ.Weight = 0.21932980514517925D;
//
// xrBatch1
//
this.xrBatch1.Borders = ((DevExpress.XtraPrinting.BorderSide)((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Bottom)));
this.xrBatch1.Name = "xrBatch1";
this.xrBatch1.StylePriority.UseBorders = false;
this.xrBatch1.StylePriority.UseTextAlignment = false;
this.xrBatch1.Text = "xrBatch1";
this.xrBatch1.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleCenter;
this.xrBatch1.Weight = 0.21932980955029355D;
//
// xrBatch2
//
this.xrBatch2.Borders = ((DevExpress.XtraPrinting.BorderSide)((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Bottom)));
this.xrBatch2.Name = "xrBatch2";
this.xrBatch2.StylePriority.UseBorders = false;
this.xrBatch2.StylePriority.UseTextAlignment = false;
this.xrBatch2.Text = "xrBatch2";
this.xrBatch2.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleCenter;
this.xrBatch2.Weight = 0.21932981924775033D;
//
// xrBatch3
//
this.xrBatch3.Borders = ((DevExpress.XtraPrinting.BorderSide)((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Bottom)));
this.xrBatch3.Name = "xrBatch3";
this.xrBatch3.Padding = new DevExpress.XtraPrinting.PaddingInfo(5, 0, 0, 0, 100F);
this.xrBatch3.StylePriority.UseBorders = false;
this.xrBatch3.StylePriority.UsePadding = false;
this.xrBatch3.StylePriority.UseTextAlignment = false;
this.xrBatch3.Text = "xrBatch3";
this.xrBatch3.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleCenter;
this.xrBatch3.Weight = 0.21932982002991075D;
//
// xrBatch4
//
this.xrBatch4.Borders = ((DevExpress.XtraPrinting.BorderSide)((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Bottom)));
this.xrBatch4.Name = "xrBatch4";
this.xrBatch4.StylePriority.UseBorders = false;
this.xrBatch4.StylePriority.UseTextAlignment = false;
this.xrBatch4.Text = "xrBatch4";
this.xrBatch4.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleCenter;
this.xrBatch4.Weight = 0.21932980591515972D;
//
// xrBatch5
//
this.xrBatch5.Borders = ((DevExpress.XtraPrinting.BorderSide)((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Bottom)));
this.xrBatch5.Name = "xrBatch5";
this.xrBatch5.StylePriority.UseBorders = false;
this.xrBatch5.StylePriority.UseTextAlignment = false;
this.xrBatch5.Text = "xrBatch5";
this.xrBatch5.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleCenter;
this.xrBatch5.Weight = 0.21932981354501713D;
//
// xrBatch6
//
this.xrBatch6.Borders = ((DevExpress.XtraPrinting.BorderSide)((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Bottom)));
this.xrBatch6.Name = "xrBatch6";
this.xrBatch6.StylePriority.UseBorders = false;
this.xrBatch6.StylePriority.UseTextAlignment = false;
this.xrBatch6.Text = "xrBatch6";
this.xrBatch6.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleCenter;
this.xrBatch6.Weight = 0.21932980797892387D;
//
// xrBatchB
//
this.xrBatchB.Borders = ((DevExpress.XtraPrinting.BorderSide)((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Bottom)));
this.xrBatchB.Name = "xrBatchB";
this.xrBatchB.StylePriority.UseBorders = false;
this.xrBatchB.StylePriority.UseTextAlignment = false;
this.xrBatchB.Text = "xrBatchB";
this.xrBatchB.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleCenter;
this.xrBatchB.Weight = 0.2193298025618684D;
//
// xrBatchW
//
this.xrBatchW.Borders = ((DevExpress.XtraPrinting.BorderSide)((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Bottom)));
this.xrBatchW.Name = "xrBatchW";
this.xrBatchW.StylePriority.UseBorders = false;
this.xrBatchW.StylePriority.UseTextAlignment = false;
this.xrBatchW.Text = "xrBatchW";
this.xrBatchW.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleCenter;
this.xrBatchW.Weight = 0.21932980514517925D;
//
// xrBatchL
//
this.xrBatchL.Borders = ((DevExpress.XtraPrinting.BorderSide)((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Bottom)));
this.xrBatchL.Name = "xrBatchL";
this.xrBatchL.StylePriority.UseBorders = false;
this.xrBatchL.StylePriority.UseTextAlignment = false;
this.xrBatchL.Text = "xrBatchL";
this.xrBatchL.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleCenter;
this.xrBatchL.Weight = 0.21932980436755359D;
//
// xrAllBatch
//
this.xrAllBatch.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
this.xrAllBatch.Name = "xrAllBatch";
this.xrAllBatch.StylePriority.UseBorders = false;
this.xrAllBatch.StylePriority.UseTextAlignment = false;
this.xrAllBatch.Text = "xrAllBatch";
this.xrAllBatch.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleCenter;
this.xrAllBatch.Weight = 0.25437855038829715D;
//
// TopMargin
//
this.TopMargin.HeightF = 42F;
this.TopMargin.Name = "TopMargin";
this.TopMargin.Padding = new DevExpress.XtraPrinting.PaddingInfo(0, 0, 0, 0, 100F);
this.TopMargin.TextAlignment = DevExpress.XtraPrinting.TextAlignment.TopLeft;
//
// BottomMargin
//
this.BottomMargin.HeightF = 34.24994F;
this.BottomMargin.Name = "BottomMargin";
this.BottomMargin.Padding = new DevExpress.XtraPrinting.PaddingInfo(0, 0, 0, 0, 100F);
this.BottomMargin.TextAlignment = DevExpress.XtraPrinting.TextAlignment.TopLeft;
//
// ReportHeader
//
this.ReportHeader.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.xlZX,
this.xlZXDate,
this.xlKDDate,
this.xlKD1,
this.xrDY1,
this.xlDYstart,
this.xrDY2,
this.xlDYEnd,
this.xrRepertHeader});
this.ReportHeader.HeightF = 111.1667F;
this.ReportHeader.Name = "ReportHeader";
//
// xlZX
//
this.xlZX.Font = new System.Drawing.Font("Times New Roman", 9.75F);
this.xlZX.LocationFloat = new DevExpress.Utils.PointFloat(633.5764F, 78.16674F);
this.xlZX.Name = "xlZX";
this.xlZX.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
this.xlZX.SizeF = new System.Drawing.SizeF(82.59384F, 23.00001F);
this.xlZX.StylePriority.UseFont = false;
this.xlZX.StylePriority.UseTextAlignment = false;
this.xlZX.Text = "执行日期:";
this.xlZX.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleCenter;
this.xlZX.Visible = false;
//
// xlZXDate
//
this.xlZXDate.Font = new System.Drawing.Font("Times New Roman", 12F, System.Drawing.FontStyle.Bold);
this.xlZXDate.LocationFloat = new DevExpress.Utils.PointFloat(716.1702F, 78.16674F);
this.xlZXDate.Name = "xlZXDate";
this.xlZXDate.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
this.xlZXDate.SizeF = new System.Drawing.SizeF(108.3733F, 23.00002F);
this.xlZXDate.StylePriority.UseFont = false;
this.xlZXDate.StylePriority.UseTextAlignment = false;
this.xlZXDate.Text = "2222/22/22";
this.xlZXDate.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleCenter;
this.xlZXDate.Visible = false;
//
// xlKDDate
//
this.xlKDDate.Font = new System.Drawing.Font("Times New Roman", 12F, System.Drawing.FontStyle.Bold);
this.xlKDDate.LocationFloat = new DevExpress.Utils.PointFloat(525.2031F, 78.16674F);
this.xlKDDate.Name = "xlKDDate";
this.xlKDDate.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
this.xlKDDate.SizeF = new System.Drawing.SizeF(108.3733F, 23.00002F);
this.xlKDDate.StylePriority.UseFont = false;
this.xlKDDate.StylePriority.UseTextAlignment = false;
this.xlKDDate.Text = "2222/22/22";
this.xlKDDate.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleCenter;
this.xlKDDate.Visible = false;
//
// xlKD1
//
this.xlKD1.Font = new System.Drawing.Font("Times New Roman", 9.75F);
this.xlKD1.LocationFloat = new DevExpress.Utils.PointFloat(442.6093F, 78.16674F);
this.xlKD1.Name = "xlKD1";
this.xlKD1.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
this.xlKD1.SizeF = new System.Drawing.SizeF(82.59384F, 23.00001F);
this.xlKD1.StylePriority.UseFont = false;
this.xlKD1.StylePriority.UseTextAlignment = false;
this.xlKD1.Text = "开单日期:";
this.xlKD1.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleCenter;
this.xlKD1.Visible = false;
//
// xrDY1
//
this.xrDY1.Font = new System.Drawing.Font("Times New Roman", 9.75F);
this.xrDY1.LocationFloat = new DevExpress.Utils.PointFloat(18.99999F, 78.16671F);
this.xrDY1.Name = "xrDY1";
this.xrDY1.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
this.xrDY1.SizeF = new System.Drawing.SizeF(82.59384F, 23.00001F);
this.xrDY1.StylePriority.UseFont = false;
this.xrDY1.StylePriority.UseTextAlignment = false;
this.xrDY1.Text = "打印时间:";
this.xrDY1.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleCenter;
this.xrDY1.Visible = false;
//
// xlDYstart
//
this.xlDYstart.Font = new System.Drawing.Font("Times New Roman", 12F, System.Drawing.FontStyle.Bold);
this.xlDYstart.LocationFloat = new DevExpress.Utils.PointFloat(101.5938F, 78.16671F);
this.xlDYstart.Name = "xlDYstart";
this.xlDYstart.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
this.xlDYstart.SizeF = new System.Drawing.SizeF(156.8757F, 23.00002F);
this.xlDYstart.StylePriority.UseFont = false;
this.xlDYstart.StylePriority.UseTextAlignment = false;
this.xlDYstart.Text = "2222/22/22 22:33:33";
this.xlDYstart.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleCenter;
this.xlDYstart.Visible = false;
//
// xrDY2
//
this.xrDY2.Font = new System.Drawing.Font("Times New Roman", 9.75F);
this.xrDY2.LocationFloat = new DevExpress.Utils.PointFloat(258.4695F, 78.16671F);
this.xrDY2.Name = "xrDY2";
this.xrDY2.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
this.xrDY2.SizeF = new System.Drawing.SizeF(27.2641F, 23.00001F);
this.xrDY2.StylePriority.UseFont = false;
this.xrDY2.StylePriority.UseTextAlignment = false;
this.xrDY2.Text = "~";
this.xrDY2.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleCenter;
this.xrDY2.Visible = false;
//
// xlDYEnd
//
this.xlDYEnd.Font = new System.Drawing.Font("Times New Roman", 12F, System.Drawing.FontStyle.Bold);
this.xlDYEnd.LocationFloat = new DevExpress.Utils.PointFloat(285.7336F, 78.16671F);
this.xlDYEnd.Name = "xlDYEnd";
this.xlDYEnd.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
this.xlDYEnd.SizeF = new System.Drawing.SizeF(156.8757F, 22.99998F);
this.xlDYEnd.StylePriority.UseFont = false;
this.xlDYEnd.StylePriority.UseTextAlignment = false;
this.xlDYEnd.Text = "2222/22/22 22:33:33";
this.xlDYEnd.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleCenter;
this.xlDYEnd.Visible = false;
//
// xrRepertHeader
//
this.xrRepertHeader.Font = new System.Drawing.Font("Times New Roman", 24F, System.Drawing.FontStyle.Bold);
this.xrRepertHeader.LocationFloat = new DevExpress.Utils.PointFloat(16.5F, 10.00001F);
this.xrRepertHeader.Name = "xrRepertHeader";
this.xrRepertHeader.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
this.xrRepertHeader.SizeF = new System.Drawing.SizeF(823.4999F, 45.91666F);
this.xrRepertHeader.StylePriority.UseFont = false;
this.xrRepertHeader.StylePriority.UseTextAlignment = false;
this.xrRepertHeader.Text = "瓶贴汇总";
this.xrRepertHeader.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleCenter;
//
// ReportFooter
//
this.ReportFooter.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.xrLabel8,
this.xrPrintBy,
this.lblPrintDate,
this.xrLabel6,
this.xrPageInfo1});
this.ReportFooter.HeightF = 60.66672F;
this.ReportFooter.Name = "ReportFooter";
//
// xrLabel8
//
this.xrLabel8.Font = new System.Drawing.Font("Times New Roman", 9F);
this.xrLabel8.LocationFloat = new DevExpress.Utils.PointFloat(18.99999F, 10.00001F);
this.xrLabel8.Multiline = true;
this.xrLabel8.Name = "xrLabel8";
this.xrLabel8.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
this.xrLabel8.SizeF = new System.Drawing.SizeF(67.70834F, 23F);
this.xrLabel8.StylePriority.UseFont = false;
this.xrLabel8.StylePriority.UseTextAlignment = false;
this.xrLabel8.Text = "打印人:\r\n";
this.xrLabel8.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleLeft;
//
// xrPrintBy
//
this.xrPrintBy.Font = new System.Drawing.Font("Times New Roman", 9F);
this.xrPrintBy.LocationFloat = new DevExpress.Utils.PointFloat(86.70836F, 10.00001F);
this.xrPrintBy.Name = "xrPrintBy";
this.xrPrintBy.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
this.xrPrintBy.SizeF = new System.Drawing.SizeF(134.375F, 22.99999F);
this.xrPrintBy.StylePriority.UseFont = false;
this.xrPrintBy.StylePriority.UseTextAlignment = false;
this.xrPrintBy.Text = "xrPrintBy";
this.xrPrintBy.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleLeft;
//
// lblPrintDate
//
this.lblPrintDate.Font = new System.Drawing.Font("Times New Roman", 9.75F);
this.lblPrintDate.LocationFloat = new DevExpress.Utils.PointFloat(699.4152F, 10.00001F);
this.lblPrintDate.Name = "lblPrintDate";
this.lblPrintDate.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
this.lblPrintDate.SizeF = new System.Drawing.SizeF(145.4509F, 23.00002F);
this.lblPrintDate.StylePriority.UseFont = false;
this.lblPrintDate.StylePriority.UseTextAlignment = false;
this.lblPrintDate.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleLeft;
//
// xrLabel6
//
this.xrLabel6.Font = new System.Drawing.Font("Times New Roman", 9.75F);
this.xrLabel6.LocationFloat = new DevExpress.Utils.PointFloat(602.238F, 10.00001F);
this.xrLabel6.Name = "xrLabel6";
this.xrLabel6.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
this.xrLabel6.SizeF = new System.Drawing.SizeF(97.17715F, 23.00001F);
this.xrLabel6.StylePriority.UseFont = false;
this.xrLabel6.StylePriority.UseTextAlignment = false;
this.xrLabel6.Text = "打印时间:";
this.xrLabel6.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleRight;
//
// xrPageInfo1
//
this.xrPageInfo1.LocationFloat = new DevExpress.Utils.PointFloat(770.4121F, 33.00002F);
this.xrPageInfo1.Name = "xrPageInfo1";
this.xrPageInfo1.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
this.xrPageInfo1.SizeF = new System.Drawing.SizeF(50F, 23F);
//
// xr
//
this.xr.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
this.xr.Name = "xr";
this.xr.Padding = new DevExpress.XtraPrinting.PaddingInfo(5, 0, 0, 0, 100F);
this.xr.StylePriority.UseBorders = false;
this.xr.StylePriority.UsePadding = false;
this.xr.StylePriority.UseTextAlignment = false;
this.xr.Text = "第2批";
this.xr.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleCenter;
this.xr.Weight = 0.21635782812123941D;
//
// xrTableCell3
//
this.xrTableCell3.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
this.xrTableCell3.Name = "xrTableCell3";
this.xrTableCell3.StylePriority.UseBorders = false;
this.xrTableCell3.StylePriority.UseTextAlignment = false;
this.xrTableCell3.Text = "第1批";
this.xrTableCell3.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleCenter;
this.xrTableCell3.Weight = 0.21635782165233986D;
//
// xrTableCell2
//
this.xrTableCell2.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
this.xrTableCell2.Name = "xrTableCell2";
this.xrTableCell2.StylePriority.UseBorders = false;
this.xrTableCell2.StylePriority.UseTextAlignment = false;
this.xrTableCell2.Text = "早上批";
this.xrTableCell2.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleCenter;
this.xrTableCell2.Weight = 0.21635782739762832D;
//
// xrTableCell4
//
this.xrTableCell4.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
this.xrTableCell4.Name = "xrTableCell4";
this.xrTableCell4.StylePriority.UseBorders = false;
this.xrTableCell4.StylePriority.UseTextAlignment = false;
this.xrTableCell4.Text = "病区\\批次";
this.xrTableCell4.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleCenter;
this.xrTableCell4.Weight = 0.55500149632994178D;
//
// xrTableRow3
//
this.xrTableRow3.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell4,
this.xrTableCell2,
this.xrTableCell3,
this.xr,
this.xrTableCell1,
this.xrTableCell8,
this.xrTableCell9,
this.xrTableCell10,
this.xrTableCell11,
this.xrTableCell5,
this.xrTableCell6,
this.xrTableCell7});
this.xrTableRow3.Name = "xrTableRow3";
this.xrTableRow3.Weight = 1D;
//
// xrTableCell1
//
this.xrTableCell1.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
this.xrTableCell1.Name = "xrTableCell1";
this.xrTableCell1.StylePriority.UseBorders = false;
this.xrTableCell1.StylePriority.UseTextAlignment = false;
this.xrTableCell1.Text = "第3批";
this.xrTableCell1.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleCenter;
this.xrTableCell1.Weight = 0.21635793591515309D;
//
// xrTableCell8
//
this.xrTableCell8.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
this.xrTableCell8.Name = "xrTableCell8";
this.xrTableCell8.StylePriority.UseBorders = false;
this.xrTableCell8.Text = "第4批";
this.xrTableCell8.Weight = 0.21635784117031898D;
//
// xrTableCell9
//
this.xrTableCell9.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
this.xrTableCell9.Name = "xrTableCell9";
this.xrTableCell9.StylePriority.UseBorders = false;
this.xrTableCell9.Text = "第5批";
this.xrTableCell9.Weight = 0.21635794209431053D;
//
// xrTableCell10
//
this.xrTableCell10.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
this.xrTableCell10.Name = "xrTableCell10";
this.xrTableCell10.StylePriority.UseBorders = false;
this.xrTableCell10.Text = "第6批";
this.xrTableCell10.Weight = 0.21635761118606367D;
//
// xrTableCell11
//
this.xrTableCell11.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
this.xrTableCell11.Name = "xrTableCell11";
this.xrTableCell11.StylePriority.UseBorders = false;
this.xrTableCell11.Text = "打包";
this.xrTableCell11.Weight = 0.21635761118606367D;
//
// xrTableCell5
//
this.xrTableCell5.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
this.xrTableCell5.Name = "xrTableCell5";
this.xrTableCell5.StylePriority.UseBorders = false;
this.xrTableCell5.StylePriority.UseTextAlignment = false;
this.xrTableCell5.Text = "打包2";
this.xrTableCell5.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleCenter;
this.xrTableCell5.Weight = 0.2163580562136298D;
//
// xrTableCell6
//
this.xrTableCell6.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
this.xrTableCell6.Name = "xrTableCell6";
this.xrTableCell6.StylePriority.UseBorders = false;
this.xrTableCell6.StylePriority.UseTextAlignment = false;
this.xrTableCell6.Text = "临时";
this.xrTableCell6.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleCenter;
this.xrTableCell6.Weight = 0.21635783261726718D;
//
// xrTableCell7
//
this.xrTableCell7.Borders = ((DevExpress.XtraPrinting.BorderSide)((((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Right)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
this.xrTableCell7.Name = "xrTableCell7";
this.xrTableCell7.StylePriority.UseBorders = false;
this.xrTableCell7.StylePriority.UseTextAlignment = false;
this.xrTableCell7.Text = "全部批次";
this.xrTableCell7.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleCenter;
this.xrTableCell7.Weight = 0.25093144098893139D;
//
// xrTable3
//
this.xrTable3.LocationFloat = new DevExpress.Utils.PointFloat(16.5F, 0F);
this.xrTable3.Name = "xrTable3";
this.xrTable3.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow3});
this.xrTable3.SizeF = new System.Drawing.SizeF(823.5F, 25F);
this.xrTable3.StylePriority.UseTextAlignment = false;
this.xrTable3.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleCenter;
//
// GroupHeader1
//
this.GroupHeader1.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.xrTable3});
this.GroupHeader1.HeightF = 25F;
this.GroupHeader1.Name = "GroupHeader1";
//
// BatchIllfieldLabelCollectReport
//
this.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] {
this.ReportHeader,
this.ReportFooter,
this.BottomMargin,
this.Detail,
this.TopMargin,
this.GroupHeader1});
this.Margins = new System.Drawing.Printing.Margins(0, 0, 42, 34);
this.Version = "12.1";
((System.ComponentModel.ISupportInitialize)(this.xrTable1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable3)).EndInit();
((System.ComponentModel.ISupportInitialize)(this)).EndInit();
}
#endregion
private DevExpress.XtraReports.UI.DetailBand Detail;
private DevExpress.XtraReports.UI.TopMarginBand TopMargin;
private DevExpress.XtraReports.UI.BottomMarginBand BottomMargin;
private DevExpress.XtraReports.UI.ReportHeaderBand ReportHeader;
private DevExpress.XtraReports.UI.ReportFooterBand ReportFooter;
private DevExpress.XtraReports.UI.XRLabel lblPrintDate;
private DevExpress.XtraReports.UI.XRLabel xrLabel6;
private DevExpress.XtraReports.UI.XRLabel xrRepertHeader;
private DevExpress.XtraReports.UI.XRPageInfo xrPageInfo1;
private DevExpress.XtraReports.UI.XRTable xrTable1;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow1;
private DevExpress.XtraReports.UI.XRTableCell xrIllfield;
private DevExpress.XtraReports.UI.XRTableCell xrBatch1;
private DevExpress.XtraReports.UI.XRTableCell xrBatch2;
private DevExpress.XtraReports.UI.XRTableCell xrBatch3;
private DevExpress.XtraReports.UI.XRLabel xrLabel8;
private DevExpress.XtraReports.UI.XRLabel xrPrintBy;
private DevExpress.XtraReports.UI.XRTableCell xr;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell3;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell2;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell4;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow3;
private DevExpress.XtraReports.UI.XRTable xrTable3;
private DevExpress.XtraReports.UI.GroupHeaderBand GroupHeader1;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell1;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell5;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell6;
private DevExpress.XtraReports.UI.XRTableCell xrBatch4;
private DevExpress.XtraReports.UI.XRTableCell xrBatch5;
private DevExpress.XtraReports.UI.XRTableCell xrBatch6;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell7;
private DevExpress.XtraReports.UI.XRTableCell xrAllBatch;
private DevExpress.XtraReports.UI.XRTableCell xrBatchZ;
private DevExpress.XtraReports.UI.XRTableCell xrBatchB;
private DevExpress.XtraReports.UI.XRTableCell xrBatchL;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell8;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell9;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell10;
private DevExpress.XtraReports.UI.XRLabel xrDY1;
private DevExpress.XtraReports.UI.XRLabel xlDYstart;
private DevExpress.XtraReports.UI.XRLabel xrDY2;
private DevExpress.XtraReports.UI.XRLabel xlDYEnd;
private DevExpress.XtraReports.UI.XRLabel xlKDDate;
private DevExpress.XtraReports.UI.XRLabel xlKD1;
private DevExpress.XtraReports.UI.XRTableCell xrBatchW;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell11;
private DevExpress.XtraReports.UI.XRLabel xlZX;
private DevExpress.XtraReports.UI.XRLabel xlZXDate;
}
}
| leborety/CJia | CJia.PIVAS.JiuJiang/CJia.PIVAS.App/UI/BatchIllfieldLabelCollectReport.designer.cs | C# | apache-2.0 | 37,992 |
{% include header_product.html%}
<div class="company-section">
<div class="container">
<div class="company-text">
<h1 class="company-title">Company</h1>
<div class="client-text-section">
{{ content }}
</div>
</div>
</div>
</div>
{% include contact_info.html %}
{% include footer.html %}
| tribbloid/tribbloid.github.io | _layouts/company.html | HTML | apache-2.0 | 366 |
/**
* Appcelerator Titanium Mobile
* Copyright (c) 2009-2016 by Appcelerator, Inc. All Rights Reserved.
* Licensed under the terms of the Apache Public License
* Please see the LICENSE included with this distribution for details.
*/
package ti.modules.titanium.geolocation;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import org.appcelerator.kroll.KrollDict;
import org.appcelerator.kroll.KrollFunction;
import org.appcelerator.kroll.KrollModule;
import org.appcelerator.kroll.KrollProxy;
import org.appcelerator.kroll.KrollRuntime;
import org.appcelerator.kroll.annotations.Kroll;
import org.appcelerator.kroll.common.Log;
import org.appcelerator.titanium.TiApplication;
import org.appcelerator.titanium.TiBaseActivity;
import org.appcelerator.titanium.TiC;
import org.appcelerator.titanium.analytics.TiAnalyticsEventFactory;
import org.appcelerator.titanium.util.TiConvert;
import ti.modules.titanium.geolocation.TiLocation.GeocodeResponseHandler;
import ti.modules.titanium.geolocation.android.AndroidModule;
import ti.modules.titanium.geolocation.android.LocationProviderProxy;
import ti.modules.titanium.geolocation.android.LocationProviderProxy.LocationProviderListener;
import ti.modules.titanium.geolocation.android.LocationRuleProxy;
import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
/**
* GeolocationModule exposes all common methods and properties relating to geolocation behavior
* associated with Ti.Geolocation to the Titanium developer. Only cross platform API points should
* be exposed through this class as Android-only API points or types should be put in a Android module
* under this module.
*
* The GeolocationModule provides management for 3 different location behavior modes (detailed
* descriptions will follow below):
* <ul>
* <li>legacy - existing behavior found in Titanium Mobile 1.7 and 1.8. <b>DEPRECATED</b></li>
* <li>simple - replacement for the old legacy mode that allows for better parity across platforms</li>
* <li>manual - Android-specific mode that exposes full control over the providers and rules</li>
* </ul>
*
* <p>
* <b>Legacy location mode</b>:<br>
* This mode operates on receiving location updates from a single active provider at a time. Settings
* used to pick and register a provider with the OS are pulled from the PROPERTY_ACCURACY, PROPERTY_FREQUENCY
* and PROPERTY_PREFERRED_PROVIDER properties on the module.
* <p>
* The valid accuracy properties for this location mode are ACCURACY_BEST, ACCURACY_NEAREST_TEN_METERS,
* ACCURACY_HUNDRED_METERS, ACCURACY_KILOMETER and ACCURACY_THREE_KILOMETERS. The accuracy property is a
* double value that will be used by the OS as a way to determine how many meters should change in location
* before a new update is sent. Accuracy properties other than this will either be ignored or change the
* current location behavior mode. The frequency property is a double value that is used by the OS to determine
* how much time in milliseconds should pass before a new update is sent.
* <p>
* The OS uses some fuzzy logic to determine the update frequency and these values are treated as no more than
* suggestions. For example: setting the frequency to 0 milliseconds and the accuracy to 10 meters may not
* result in a update being sent as fast as possible which is what frequency of 0 ms indicates. This is due to
* the OS not sending updates till the accuracy property is satisfied. If the desired behavior is to get updates
* purely based on time then the suggested mechanism would be to set the accuracy to 0 meters and then set the
* frequency to the desired update interval in milliseconds.
*
* <p>
* <b>Simple location mode</b>:<br>
* This mode operates on receiving location updates from multiple sources. The simple mode has two states - high
* accuracy and low accuracy. The difference in these two modes is that low accuracy has the passive and network
* providers registered by default where the high accuracy state enables the gps provider in addition to the passive
* and network providers. The simple mode utilizes location rules for filtering location updates to try and fall back
* gracefully (when in high accuracy state) to the network and passive providers if a gps update has not been received
* recently.
* <p>
* No specific controls for time or distance (better terminology in line with native Android docs but these
* are called frequency and accuracy in legacy mode) are exposed to the Titanium developer as the details of this mode
* are supposed to be driven by Appcelerator based on our observations. If greater control on the part of the Titanium
* developer is needed then the manual behavior mode can and should be used.
*
* <p>
* <b>Manual location mode</b>:<br>
* This mode puts full control over providers and rules in the hands of the Titanium developer. The developer will be
* responsible for registering location providers, setting time and distance settings per provider and defining the rule
* set if any rules are desired.
* <p>
* In this mode, the developer would create a Ti.Geolocation.Android.LocationProvider object for each provider they want
* to use and add this to the list of manual providers via addLocationProvider(LocationProviderProxy). In order to set
* rules, the developer will have to create a Ti.Geolocation.Android.LocationRule object per rule and then add those
* rules via addLocationRule(LocationRuleProxy). These rules will be applied to any location updates that come from the
* registered providers. Further information on the LocationProvider and LocationRule objects can be found by looking at
* those specific classes.
*
* <p>
* <b>General location behavior</b>:<br>
* The GeolocationModule is capable of switching modes at any time and keeping settings per mode separated. Changing modes
* is done by updating the Ti.Geolocation.accuracy property. Based on the new value of the accuracy property, the
* legacy or simple modes may be enabled (and the previous mode may be turned off). Enabling or disabling the manual mode
* is done by setting the AndroidModule.manualMode (Ti.Geolocation.Android.manualMode) value. NOTE: updating the location
* rules will not update the mode. Simply setting the Ti.Geolocation.accuracy property will not enable the legacy/simple
* modes if you are currently in the manual mode - you must disable the manual mode before the simple/legacy modes are used
* <p>
* In regards to actually "turning on" the providers by registering them with the OS - this is triggered by the presence of
* "location" event listeners on the GeolocationModule. When the first listener is added, providers start being registered
* with the OS. When there are no listeners then all the providers are de-registered. Changes made to location providers or
* accuracy, frequency properties or even changing modes are respected and kept but don't actually get applied on the OS until
* the listener count is greater than 0.
*/
// TODO deprecate the frequency and preferredProvider property
@Kroll.module(propertyAccessors={
TiC.PROPERTY_ACCURACY,
TiC.PROPERTY_FREQUENCY,
TiC.PROPERTY_PREFERRED_PROVIDER
})
public class GeolocationModule extends KrollModule
implements Handler.Callback, LocationProviderListener
{
// TODO move these to the AndroidModule namespace since they will only be used when creating
// manual location providers
@Kroll.constant @Deprecated public static final String PROVIDER_PASSIVE = LocationManager.PASSIVE_PROVIDER;
@Kroll.constant @Deprecated public static final String PROVIDER_NETWORK = LocationManager.NETWORK_PROVIDER;
@Kroll.constant @Deprecated public static final String PROVIDER_GPS = LocationManager.GPS_PROVIDER;
@Kroll.constant public static final int ACCURACY_LOW = 0;
@Kroll.constant public static final int ACCURACY_HIGH = 1;
@Kroll.constant @Deprecated public static final int ACCURACY_BEST = 2;
@Kroll.constant @Deprecated public static final int ACCURACY_NEAREST_TEN_METERS = 3;
@Kroll.constant @Deprecated public static final int ACCURACY_HUNDRED_METERS = 4;
@Kroll.constant @Deprecated public static final int ACCURACY_KILOMETER = 5;
@Kroll.constant @Deprecated public static final int ACCURACY_THREE_KILOMETERS = 6;
public TiLocation tiLocation;
public AndroidModule androidModule;
public int numLocationListeners = 0;
public HashMap<String, LocationProviderProxy> simpleLocationProviders = new HashMap<String, LocationProviderProxy>();
@Deprecated public HashMap<String, LocationProviderProxy> legacyLocationProviders = new HashMap<String, LocationProviderProxy>();
public boolean legacyModeActive = true;
protected static final int MSG_ENABLE_LOCATION_PROVIDERS = KrollModule.MSG_LAST_ID + 100;
protected static final int MSG_LAST_ID = MSG_ENABLE_LOCATION_PROVIDERS;
private static final String TAG = "GeolocationModule";
private static final double SIMPLE_LOCATION_PASSIVE_DISTANCE = 0.0;
private static final double SIMPLE_LOCATION_PASSIVE_TIME = 0;
private static final double SIMPLE_LOCATION_NETWORK_DISTANCE = 10.0;
private static final double SIMPLE_LOCATION_NETWORK_TIME = 10000;
private static final double SIMPLE_LOCATION_GPS_DISTANCE = 3.0;
private static final double SIMPLE_LOCATION_GPS_TIME = 3000;
private static final double SIMPLE_LOCATION_NETWORK_DISTANCE_RULE = 200;
private static final double SIMPLE_LOCATION_NETWORK_MIN_AGE_RULE = 60000;
private static final double SIMPLE_LOCATION_GPS_MIN_AGE_RULE = 30000;
private TiCompass tiCompass;
private boolean compassListenersRegistered = false;
private boolean sentAnalytics = false;
private ArrayList<LocationRuleProxy> simpleLocationRules = new ArrayList<LocationRuleProxy>();
private LocationRuleProxy simpleLocationGpsRule;
private LocationRuleProxy simpleLocationNetworkRule;
private int simpleLocationAccuracyProperty = ACCURACY_LOW;
private Location currentLocation;
//currentLocation is conditionally updated. lastLocation is unconditionally updated
//since currentLocation determines when to send out updates, and lastLocation is passive
private Location lastLocation;
@Deprecated private HashMap<Integer, Double> legacyLocationAccuracyMap = new HashMap<Integer, Double>();
@Deprecated private int legacyLocationAccuracyProperty = ACCURACY_NEAREST_TEN_METERS;
@Deprecated private double legacyLocationFrequency = 5000;
@Deprecated private String legacyLocationPreferredProvider = PROVIDER_NETWORK;
/**
* Constructor
*/
public GeolocationModule()
{
super("geolocation");
tiLocation = new TiLocation();
tiCompass = new TiCompass(this, tiLocation);
// initialize the legacy location accuracy map
legacyLocationAccuracyMap.put(ACCURACY_BEST, 0.0); // this needs to be 0.0 to work for only time based updates
legacyLocationAccuracyMap.put(ACCURACY_NEAREST_TEN_METERS, 10.0);
legacyLocationAccuracyMap.put(ACCURACY_HUNDRED_METERS, 100.0);
legacyLocationAccuracyMap.put(ACCURACY_KILOMETER, 1000.0);
legacyLocationAccuracyMap.put(ACCURACY_THREE_KILOMETERS, 3000.0);
legacyLocationProviders.put(PROVIDER_NETWORK, new LocationProviderProxy(PROVIDER_NETWORK, 10.0f, legacyLocationFrequency, this));
simpleLocationProviders.put(PROVIDER_NETWORK, new LocationProviderProxy(PROVIDER_NETWORK, SIMPLE_LOCATION_NETWORK_DISTANCE, SIMPLE_LOCATION_NETWORK_TIME, this));
simpleLocationProviders.put(PROVIDER_PASSIVE, new LocationProviderProxy(PROVIDER_PASSIVE, SIMPLE_LOCATION_PASSIVE_DISTANCE, SIMPLE_LOCATION_PASSIVE_TIME, this));
// create these now but we don't want to include these in the rule set unless the simple GPS provider is enabled
simpleLocationGpsRule = new LocationRuleProxy(PROVIDER_GPS, null, SIMPLE_LOCATION_GPS_MIN_AGE_RULE, null);
simpleLocationNetworkRule = new LocationRuleProxy(PROVIDER_NETWORK, SIMPLE_LOCATION_NETWORK_DISTANCE_RULE, SIMPLE_LOCATION_NETWORK_MIN_AGE_RULE, null);
}
/**
* @see org.appcelerator.kroll.KrollProxy#handleMessage(android.os.Message)
*/
@Override
public boolean handleMessage(Message message)
{
switch (message.what) {
case MSG_ENABLE_LOCATION_PROVIDERS: {
Object locationProviders = message.obj;
doEnableLocationProviders((HashMap<String, LocationProviderProxy>) locationProviders);
return true;
}
}
return super.handleMessage(message);
}
private void doAnalytics(Location location)
{
if (!sentAnalytics) {
tiLocation.doAnalytics(location);
sentAnalytics = true;
}
}
/**
* Called by a registered location provider when a location update is received
*
* @param location location update that was received
*
* @see ti.modules.titanium.geolocation.android.LocationProviderProxy.LocationProviderListener#onLocationChanged(android.location.Location)
*/
public void onLocationChanged(Location location)
{
lastLocation = location;
if (shouldUseUpdate(location)) {
fireEvent(TiC.EVENT_LOCATION, buildLocationEvent(location, tiLocation.locationManager.getProvider(location.getProvider())));
currentLocation = location;
doAnalytics(location);
}
}
/**
* Called by a registered location provider when its state changes
*
* @param providerName name of the provider whose state has changed
* @param state new state of the provider
*
* @see ti.modules.titanium.geolocation.android.LocationProviderProxy.LocationProviderListener#onProviderStateChanged(java.lang.String, int)
*/
public void onProviderStateChanged(String providerName, int state)
{
String message = providerName;
// TODO this is trash. deprecate the existing mechanism of bundling status updates with the
// location event and create a new "locationState" (or whatever) event. for the time being,
// this solution kills my soul slightly less than the previous one
switch (state) {
case LocationProviderProxy.STATE_DISABLED:
message += " is disabled";
Log.i(TAG, message, Log.DEBUG_MODE);
fireEvent(TiC.EVENT_LOCATION, buildLocationErrorEvent(state, message));
break;
case LocationProviderProxy.STATE_ENABLED:
message += " is enabled";
Log.d(TAG, message, Log.DEBUG_MODE);
break;
case LocationProviderProxy.STATE_OUT_OF_SERVICE:
message += " is out of service";
Log.d(TAG, message, Log.DEBUG_MODE);
fireEvent(TiC.EVENT_LOCATION, buildLocationErrorEvent(state, message));
break;
case LocationProviderProxy.STATE_UNAVAILABLE:
message += " is unavailable";
Log.d(TAG, message, Log.DEBUG_MODE);
fireEvent(TiC.EVENT_LOCATION, buildLocationErrorEvent(state, message));
break;
case LocationProviderProxy.STATE_AVAILABLE:
message += " is available";
Log.d(TAG, message, Log.DEBUG_MODE);
break;
case LocationProviderProxy.STATE_UNKNOWN:
message += " is in a unknown state [" + state + "]";
Log.d(TAG, message, Log.DEBUG_MODE);
fireEvent(TiC.EVENT_LOCATION, buildLocationErrorEvent(state, message));
break;
default:
message += " is in a unknown state [" + state + "]";
Log.d(TAG, message, Log.DEBUG_MODE);
fireEvent(TiC.EVENT_LOCATION, buildLocationErrorEvent(state, message));
break;
}
}
/**
* Called when the location provider has had one of it's properties updated and thus needs to be re-registered with the OS
*
* @param locationProvider the location provider that needs to be re-registered
*
* @see ti.modules.titanium.geolocation.android.LocationProviderProxy.LocationProviderListener#onProviderUpdated(ti.modules.titanium.geolocation.android.LocationProviderProxy)
*/
public void onProviderUpdated(LocationProviderProxy locationProvider)
{
if (getManualMode() && (numLocationListeners > 0)) {
tiLocation.locationManager.removeUpdates(locationProvider);
registerLocationProvider(locationProvider);
}
}
/**
* @see org.appcelerator.kroll.KrollModule#propertyChanged(java.lang.String, java.lang.Object, java.lang.Object, org.appcelerator.kroll.KrollProxy)
*/
@Override
public void propertyChanged(String key, Object oldValue, Object newValue, KrollProxy proxy)
{
if (key.equals(TiC.PROPERTY_ACCURACY)) {
// accuracy property is what triggers a shift between simple and legacy modes. the
// android only manual mode is indicated by the AndroidModule.manualMode value which
// has no impact on the legacyModeActive flag. IE: when determining the current mode,
// both flags must be checked
propertyChangedAccuracy(newValue);
} else if (key.equals(TiC.PROPERTY_FREQUENCY)) {
propertyChangedFrequency(newValue);
} else if (key.equals(TiC.PROPERTY_PREFERRED_PROVIDER)) {
propertyChangedPreferredProvider(newValue);
}
}
/**
* Handles property change for Ti.Geolocation.accuracy
*
* @param newValue new accuracy value
*/
private void propertyChangedAccuracy(Object newValue)
{
// is legacy mode enabled (registered with OS, not just selected via the accuracy property)
boolean legacyModeEnabled = false;
if (legacyModeActive && (!getManualMode()) && (numLocationListeners > 0)) {
legacyModeEnabled = true;
}
// is simple mode enabled (registered with OS, not just selected via the accuracy property)
boolean simpleModeEnabled = false;
if (!legacyModeActive && !(getManualMode()) && (numLocationListeners > 0)) {
simpleModeEnabled = true;
}
int accuracyProperty = TiConvert.toInt(newValue);
// is this a legacy accuracy property?
Double accuracyLookupResult = legacyLocationAccuracyMap.get(accuracyProperty);
if (accuracyLookupResult != null) {
// has the value changed from the last known good value?
if (accuracyProperty != legacyLocationAccuracyProperty) {
legacyLocationAccuracyProperty = accuracyProperty;
for (String providerKey : legacyLocationProviders.keySet()) {
LocationProviderProxy locationProvider = legacyLocationProviders.get(providerKey);
locationProvider.setProperty(TiC.PROPERTY_MIN_UPDATE_DISTANCE, accuracyLookupResult);
}
if (legacyModeEnabled) {
enableLocationProviders(legacyLocationProviders);
}
}
if (simpleModeEnabled) {
enableLocationProviders(legacyLocationProviders);
}
legacyModeActive = true;
// is this a simple accuracy property?
} else if ((accuracyProperty == ACCURACY_HIGH) || (accuracyProperty == ACCURACY_LOW)) {
// has the value changed from the last known good value?
if (accuracyProperty != simpleLocationAccuracyProperty) {
simpleLocationAccuracyProperty = accuracyProperty;
LocationProviderProxy gpsProvider = simpleLocationProviders.get(PROVIDER_GPS);
if ((accuracyProperty == ACCURACY_HIGH) && (gpsProvider == null)) {
gpsProvider = new LocationProviderProxy(PROVIDER_GPS, SIMPLE_LOCATION_GPS_DISTANCE, SIMPLE_LOCATION_GPS_TIME, this);
simpleLocationProviders.put(PROVIDER_GPS, gpsProvider);
simpleLocationRules.add(simpleLocationNetworkRule);
simpleLocationRules.add(simpleLocationGpsRule);
if (simpleModeEnabled) {
registerLocationProvider(gpsProvider);
}
} else if ((accuracyProperty == ACCURACY_LOW) && (gpsProvider != null)) {
simpleLocationProviders.remove(PROVIDER_GPS);
simpleLocationRules.remove(simpleLocationNetworkRule);
simpleLocationRules.remove(simpleLocationGpsRule);
if (simpleModeEnabled) {
tiLocation.locationManager.removeUpdates(gpsProvider);
}
}
}
if (legacyModeEnabled) {
enableLocationProviders(simpleLocationProviders);
}
legacyModeActive = false;
}
}
/**
* Handles property change for Ti.Geolocation.frequency
*
* @param newValue new frequency value
*/
private void propertyChangedFrequency(Object newValue)
{
// is legacy mode enabled (registered with OS, not just selected via the accuracy property)
boolean legacyModeEnabled = false;
if (legacyModeActive && !getManualMode() && (numLocationListeners > 0)) {
legacyModeEnabled = true;
}
double frequencyProperty = TiConvert.toDouble(newValue) * 1000;
if (frequencyProperty != legacyLocationFrequency) {
legacyLocationFrequency = frequencyProperty;
Iterator<String> iterator = legacyLocationProviders.keySet().iterator();
while(iterator.hasNext()) {
LocationProviderProxy locationProvider = legacyLocationProviders.get(iterator.next());
locationProvider.setProperty(TiC.PROPERTY_MIN_UPDATE_TIME, legacyLocationFrequency);
}
if (legacyModeEnabled) {
enableLocationProviders(legacyLocationProviders);
}
}
}
/**
* Handles property change for Ti.Geolocation.preferredProvider
*
* @param newValue new preferredProvider value
*/
private void propertyChangedPreferredProvider(Object newValue)
{
// is legacy mode enabled (registered with OS, not just selected via the accuracy property)
boolean legacyModeEnabled = false;
if (legacyModeActive && !getManualMode() && (numLocationListeners > 0)) {
legacyModeEnabled = true;
}
String preferredProviderProperty = TiConvert.toString(newValue);
if (!(preferredProviderProperty.equals(PROVIDER_NETWORK)) && (!(preferredProviderProperty.equals(PROVIDER_GPS)))) {
return;
}
if (!(preferredProviderProperty.equals(legacyLocationPreferredProvider))) {
LocationProviderProxy oldProvider = legacyLocationProviders.get(legacyLocationPreferredProvider);
LocationProviderProxy newProvider = legacyLocationProviders.get(preferredProviderProperty);
if (oldProvider != null) {
legacyLocationProviders.remove(legacyLocationPreferredProvider);
if (legacyModeEnabled) {
tiLocation.locationManager.removeUpdates(oldProvider);
}
}
if (newProvider == null) {
newProvider = new LocationProviderProxy(preferredProviderProperty, legacyLocationAccuracyMap.get(legacyLocationAccuracyProperty), legacyLocationFrequency, this);
legacyLocationProviders.put(preferredProviderProperty, newProvider);
if (legacyModeEnabled) {
registerLocationProvider(newProvider);
}
}
legacyLocationPreferredProvider = preferredProviderProperty;
}
}
/**
* @see org.appcelerator.kroll.KrollProxy#eventListenerAdded(java.lang.String, int, org.appcelerator.kroll.KrollProxy)
*/
@Override
protected void eventListenerAdded(String event, int count, KrollProxy proxy)
{
if (TiC.EVENT_HEADING.equals(event)) {
if (!compassListenersRegistered) {
tiCompass.registerListener();
compassListenersRegistered = true;
}
} else if (TiC.EVENT_LOCATION.equals(event)) {
numLocationListeners++;
if (numLocationListeners == 1) {
HashMap<String, LocationProviderProxy> locationProviders = legacyLocationProviders;
if (getManualMode()) {
locationProviders = androidModule.manualLocationProviders;
} else if (!legacyModeActive) {
locationProviders = simpleLocationProviders;
}
enableLocationProviders(locationProviders);
// fire off an initial location fix if one is available
if (!hasLocationPermissions()) {
Log.e(TAG, "Location permissions missing");
return;
}
lastLocation = tiLocation.getLastKnownLocation();
if (lastLocation != null) {
fireEvent(TiC.EVENT_LOCATION, buildLocationEvent(lastLocation, tiLocation.locationManager.getProvider(lastLocation.getProvider())));
doAnalytics(lastLocation);
}
}
}
super.eventListenerAdded(event, count, proxy);
}
/**
* @see org.appcelerator.kroll.KrollProxy#eventListenerRemoved(java.lang.String, int, org.appcelerator.kroll.KrollProxy)
*/
@Override
protected void eventListenerRemoved(String event, int count, KrollProxy proxy)
{
if (TiC.EVENT_HEADING.equals(event)) {
if (compassListenersRegistered) {
tiCompass.unregisterListener();
compassListenersRegistered = false;
}
} else if (TiC.EVENT_LOCATION.equals(event)) {
numLocationListeners--;
if (numLocationListeners == 0) {
disableLocationProviders();
}
}
super.eventListenerRemoved(event, count, proxy);
}
/**
* Checks if the device has a compass sensor
*
* @return <code>true</code> if the device has a compass, <code>false</code> if not
*/
@Kroll.method @Kroll.getProperty
public boolean getHasCompass()
{
return tiCompass.getHasCompass();
}
/**
* Retrieves the current compass heading and returns it to the specified Javascript function
*
* @param listener Javascript function that will be invoked with the compass heading
*/
@Kroll.method
public void getCurrentHeading(final KrollFunction listener)
{
tiCompass.getCurrentHeading(listener);
}
/**
* Retrieves the last obtained location and returns it as JSON.
*
* @return String representing the last geolocation event
*/
@Kroll.method @Kroll.getProperty
public String getLastGeolocation()
{
return TiAnalyticsEventFactory.locationToJSONString(lastLocation);
}
/**
* Checks if the Android manual location behavior mode is currently enabled
*
* @return <code>true</code> if currently in manual mode, <code>
* false</code> if the Android module has not been registered
* yet with the OS or manual mode is not enabled
*/
private boolean getManualMode()
{
if (androidModule == null) {
return false;
} else {
return androidModule.manualMode;
}
}
@Kroll.method
public boolean hasLocationPermissions()
{
if (Build.VERSION.SDK_INT < 23) {
return true;
}
Activity currentActivity = TiApplication.getInstance().getCurrentActivity();
if (currentActivity.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
return true;
}
return false;
}
@Kroll.method
public void requestLocationPermissions(@Kroll.argument(optional=true) Object type, @Kroll.argument(optional=true) KrollFunction permissionCallback)
{
if (hasLocationPermissions()) {
return;
}
KrollFunction permissionCB;
if (type instanceof KrollFunction && permissionCallback == null) {
permissionCB = (KrollFunction) type;
} else {
permissionCB = permissionCallback;
}
TiBaseActivity.registerPermissionRequestCallback(TiC.PERMISSION_CODE_LOCATION, permissionCB, getKrollObject());
Activity currentActivity = TiApplication.getInstance().getCurrentActivity();
currentActivity.requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, TiC.PERMISSION_CODE_LOCATION);
}
/**
* Registers the specified location provider with the OS. Once the provider is registered, the OS
* will begin to provider location updates as they are available
*
* @param locationProvider location provider to be registered
*/
public void registerLocationProvider(LocationProviderProxy locationProvider)
{
if (!hasLocationPermissions()) {
Log.e(TAG, "Location permissions missing", Log.DEBUG_MODE);
return;
}
String provider = TiConvert.toString(locationProvider.getProperty(TiC.PROPERTY_NAME));
try {
tiLocation.locationManager.requestLocationUpdates(
provider,
(long) locationProvider.getMinUpdateTime(),
(float) locationProvider.getMinUpdateDistance(),
locationProvider);
} catch (IllegalArgumentException e) {
Log.e(TAG, "Unable to register [" + provider + "], provider is null");
} catch (SecurityException e) {
Log.e(TAG, "Unable to register [" + provider + "], permission denied");
}
}
/**
* Wrapper to ensure task executes on the runtime thread
*
* @param locationProviders list of location providers to enable by registering
* the providers with the OS
*/
public void enableLocationProviders(HashMap<String, LocationProviderProxy> locationProviders)
{
if (KrollRuntime.getInstance().isRuntimeThread()) {
doEnableLocationProviders(locationProviders);
} else {
Message message = getRuntimeHandler().obtainMessage(MSG_ENABLE_LOCATION_PROVIDERS, locationProviders);
message.sendToTarget();
}
}
/**
* Enables the specified location behavior mode by registering the associated
* providers with the OS. Even if the specified mode is currently active, the
* current mode will be disabled by de-registering all the associated providers
* for that mode with the OS and then registering
* them again. This can be useful in cases where the properties for all the
* providers have been updated and they need to be re-registered in order for the
* change to take effect. Modification of the list of providers for any mode
* should occur on the runtime thread in order to make sure threading issues are
* avoiding
*
* @param locationProviders
*/
private void doEnableLocationProviders(HashMap<String, LocationProviderProxy> locationProviders)
{
if (numLocationListeners > 0) {
disableLocationProviders();
Iterator<String> iterator = locationProviders.keySet().iterator();
while(iterator.hasNext()) {
LocationProviderProxy locationProvider = locationProviders.get(iterator.next());
registerLocationProvider(locationProvider);
}
}
}
/**
* Disables the current mode by de-registering all the associated providers
* for that mode with the OS. Providers are just de-registered with the OS,
* not removed from the list of providers we associate with the behavior mode.
*/
private void disableLocationProviders()
{
for (LocationProviderProxy locationProvider : legacyLocationProviders.values()) {
tiLocation.locationManager.removeUpdates(locationProvider);
}
for (LocationProviderProxy locationProvider : simpleLocationProviders.values()) {
tiLocation.locationManager.removeUpdates(locationProvider);
}
if (androidModule != null) {
for (LocationProviderProxy locationProvider : androidModule.manualLocationProviders.values()) {
tiLocation.locationManager.removeUpdates(locationProvider);
}
}
}
/**
* Checks if the device has a valid location service present. The passive location service
* is not counted.
*
* @return <code>true</code> if a valid location service is available on the device,
* <code>false</code> if not
*/
@Kroll.getProperty @Kroll.method
public boolean getLocationServicesEnabled()
{
return tiLocation.getLocationServicesEnabled();
}
/**
* Retrieves the last known location and returns it to the specified Javascript function
*
* @param callback Javascript function that will be invoked with the last known location
*/
@Kroll.method
public void getCurrentPosition(KrollFunction callback)
{
if (!hasLocationPermissions()) {
Log.e(TAG, "Location permissions missing");
return;
}
if (callback != null) {
Location latestKnownLocation = tiLocation.getLastKnownLocation();
if (latestKnownLocation != null) {
callback.call(this.getKrollObject(), new Object[] {
buildLocationEvent(latestKnownLocation, tiLocation.locationManager.getProvider(latestKnownLocation.getProvider()))
});
} else {
Log.e(TAG, "Unable to get current position, location is null");
callback.call(this.getKrollObject(), new Object[] {
buildLocationErrorEvent(TiLocation.ERR_POSITION_UNAVAILABLE, "location is currently unavailable.")
});
}
}
}
/**
* Converts the specified address to coordinates and returns the value to the specified
* Javascript function
*
* @param address address to be converted
* @param callback Javascript function that will be invoked with the coordinates
* for the specified address if available
*/
@Kroll.method
public void forwardGeocoder(String address, KrollFunction callback)
{
tiLocation.forwardGeocode(address, createGeocodeResponseHandler(callback));
}
/**
* Converts the specified latitude and longitude to a human readable address and returns
* the value to the specified Javascript function
*
* @param latitude latitude to be used in looking up the associated address
* @param longitude longitude to be used in looking up the associated address
* @param callback Javascript function that will be invoked with the address
* for the specified latitude and longitude if available
*/
@Kroll.method
public void reverseGeocoder(double latitude, double longitude, KrollFunction callback)
{
tiLocation.reverseGeocode(latitude, longitude, createGeocodeResponseHandler(callback));
}
/**
* Convenience method for creating a response handler that is used when doing a
* geocode lookup.
*
* @param callback Javascript function that the response handler will invoke
* once the geocode response is ready
* @return the geocode response handler
*/
private GeocodeResponseHandler createGeocodeResponseHandler(final KrollFunction callback)
{
final GeolocationModule geolocationModule = this;
return new GeocodeResponseHandler() {
@Override
public void handleGeocodeResponse(KrollDict geocodeResponse)
{
geocodeResponse.put(TiC.EVENT_PROPERTY_SOURCE, geolocationModule);
callback.call(getKrollObject(), new Object[] { geocodeResponse });
}
};
}
/**
* Called to determine if the specified location is "better" than the current location.
* This is determined by comparing the new location to the current location according
* to the location rules (if any are set) for the current behavior mode. If no rules
* are set for the current behavior mode, the new location is always accepted.
*
* @param newLocation location to evaluate
* @return <code>true</code> if the location has been deemed better than
* the current location based on the existing rules set for the
* current behavior mode, <code>false</code> if not
*/
private boolean shouldUseUpdate(Location newLocation)
{
boolean passed = false;
if (getManualMode()) {
if (androidModule.manualLocationRules.size() > 0) {
for(LocationRuleProxy rule : androidModule.manualLocationRules) {
if (rule.check(currentLocation, newLocation)) {
passed = true;
break;
}
}
} else {
passed = true; // no rules set, always accept
}
} else if (!legacyModeActive) {
for(LocationRuleProxy rule : simpleLocationRules) {
if (rule.check(currentLocation, newLocation)) {
passed = true;
break;
}
}
// TODO remove this block when legacy mode is removed
} else {
// the legacy mode will fall here, don't filter the results
passed = true;
}
return passed;
}
/**
* Convenience method used to package a location from a location provider into a
* consumable form for the Titanium developer before it is fire back to Javascript.
*
* @param location location that needs to be packaged into consumable form
* @param locationProvider location provider that provided the location update
* @return map of property names and values that contain information
* pulled from the specified location
*/
private KrollDict buildLocationEvent(Location location, LocationProvider locationProvider)
{
KrollDict coordinates = new KrollDict();
coordinates.put(TiC.PROPERTY_LATITUDE, location.getLatitude());
coordinates.put(TiC.PROPERTY_LONGITUDE, location.getLongitude());
coordinates.put(TiC.PROPERTY_ALTITUDE, location.getAltitude());
coordinates.put(TiC.PROPERTY_ACCURACY, location.getAccuracy());
coordinates.put(TiC.PROPERTY_ALTITUDE_ACCURACY, null); // Not provided
coordinates.put(TiC.PROPERTY_HEADING, location.getBearing());
coordinates.put(TiC.PROPERTY_SPEED, location.getSpeed());
coordinates.put(TiC.PROPERTY_TIMESTAMP, location.getTime());
KrollDict event = new KrollDict();
event.putCodeAndMessage(TiC.ERROR_CODE_NO_ERROR, null);
event.put(TiC.PROPERTY_COORDS, coordinates);
if (locationProvider != null) {
KrollDict provider = new KrollDict();
provider.put(TiC.PROPERTY_NAME, locationProvider.getName());
provider.put(TiC.PROPERTY_ACCURACY, locationProvider.getAccuracy());
provider.put(TiC.PROPERTY_POWER, locationProvider.getPowerRequirement());
event.put(TiC.PROPERTY_PROVIDER, provider);
}
return event;
}
/**
* Convenience method used to package a error into a consumable form
* for the Titanium developer before it is fired back to Javascript.
*
* @param code Error code identifying the error
* @param msg Error message describing the event
* @return map of property names and values that contain information
* regarding the error
*/
private KrollDict buildLocationErrorEvent(int code, String msg)
{
KrollDict d = new KrollDict(3);
d.putCodeAndMessage(code, msg);
return d;
}
@Override
public String getApiName()
{
return "Ti.Geolocation";
}
@Override
public void onDestroy(Activity activity) {
//clean up event listeners
if (compassListenersRegistered) {
tiCompass.unregisterListener();
compassListenersRegistered = false;
}
disableLocationProviders();
super.onDestroy(activity);
}
}
| ashcoding/titanium_mobile | android/modules/geolocation/src/java/ti/modules/titanium/geolocation/GeolocationModule.java | Java | apache-2.0 | 36,967 |
package repomodel
import (
"github.com/kopia/kopia/repo/content"
"github.com/kopia/kopia/repo/manifest"
)
// RepositorySession models the behavior of a single session in an repository.
type RepositorySession struct {
OpenRepo *OpenRepository
WrittenContents ContentSet
WrittenManifests ManifestSet
}
// WriteContent adds the provided content ID to the model.
func (s *RepositorySession) WriteContent(cid content.ID) {
s.WrittenContents.Add(cid)
}
// WriteManifest adds the provided manifest ID to the model.
func (s *RepositorySession) WriteManifest(mid manifest.ID) {
s.WrittenManifests.Add(mid)
}
// Refresh refreshes the set of committed contents and manifest from repositor.
func (s *RepositorySession) Refresh() {
s.OpenRepo.Refresh()
}
// Flush flushes the changes written in this RepositorySession and makes them available
// to other RepositoryData model.
func (s *RepositorySession) Flush(wc *ContentSet, wm *ManifestSet) {
s.OpenRepo.mu.Lock()
defer s.OpenRepo.mu.Unlock()
// data flushed is visible to other sessions in the same open repository.
s.OpenRepo.Contents.Add(wc.ids...)
s.OpenRepo.Manifests.Add(wm.ids...)
// data flushed is visible to other sessions in other open repositories.
s.OpenRepo.RepoData.Contents.Add(wc.ids...)
s.OpenRepo.RepoData.Manifests.Add(wm.ids...)
s.WrittenContents.RemoveAll(wc.ids...)
s.WrittenManifests.RemoveAll(wm.ids...)
}
| kopia/kopia | tests/repository_stress_test/repomodel/repository_session_model.go | GO | apache-2.0 | 1,400 |
using EPiServer.Core;
namespace EPiServer.SocialAlloy.Web.Social.Models
{
/// <summary>
/// The LikeButtonBlockViewModel class represents the model that will be used to
/// provide data to the Like button block frontend view.
/// </summary>
public class LikeButtonBlockViewModel
{
/// <summary>
/// Parameterless constructor
/// </summary>
public LikeButtonBlockViewModel()
{
}
/// <summary>
/// Gets or sets the current page link.
/// </summary>
public PageReference PageLink { get; set; }
/// <summary>
/// Gets or sets the total number of Liked ratings found for the current page.
/// </summary>
public long TotalCount { get; set; }
/// <summary>
/// Gets or sets the existing Liked rating, if any, submitted by current user for the current page.
/// </summary>
public int? CurrentRating { get; set; }
}
} | episerver/SocialAlloy | src/EPiServer.SocialAlloy.Web/Social/Models/Ratings/LikeButtonBlockViewModel.cs | C# | apache-2.0 | 987 |
# Adactylus ellipticus (J.J.Sm.) Cretz. SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Liliopsida/Asparagales/Orchidaceae/Apostasia/Apostasia elliptica/ Syn. Adactylus ellipticus/README.md | Markdown | apache-2.0 | 194 |
package org.xmlcml.ami.visitor;
import java.io.File;
import java.util.List;
import org.apache.commons.io.FilenameUtils;
import org.apache.log4j.Logger;
import org.xmlcml.ami.util.AMIUtil;
import org.xmlcml.ami.visitable.VisitableInput;
/** manages the output.
*
* Decides whether to create files or directories. May map the structure onto the input structure.
*
* @author pm286
*
*/
public class VisitorOutput {
private static final Logger LOG = Logger.getLogger(VisitorOutput.class);
private static final String DEFAULT_OUTPUT_LOCATION = "target/";
private static final String DEFAULT_BASENAME = "dummy";
private static final String DEFAULT_OUTPUT_SUFFIX = ".xml";
private String outputLocation;
// private VisitableInput visitableInput;
private List<VisitableInput> visitableInputList;
private String extension;
private boolean isDirectory;
private File outputDirectory;
/** reads outputLocation and ducktypes the type (File, Directory, etc.).
*
* @param outputLocation
*/
public VisitorOutput(String outputLocation) {
setDefaults();
this.outputLocation = outputLocation;
generateOutputDirectoryName();
}
/** this creates a default outputLocation
*
*/
public VisitorOutput() {
setDefaults();
}
private void setDefaults() {
outputLocation = DEFAULT_OUTPUT_LOCATION;
extension = DEFAULT_OUTPUT_SUFFIX;
outputDirectory = new File(DEFAULT_OUTPUT_LOCATION);
}
/** not yet used
*
* @param visitableInput
*/
public void setVisitableInputList(List<VisitableInput> visitableInputList) {
this.visitableInputList = visitableInputList;
}
private void generateOutputDirectoryName() {
if (outputLocation.startsWith(AMIUtil.HTTP)) {
throw new RuntimeException("Cannot output to URL: "+outputLocation);
}
if (outputLocation.startsWith(AMIUtil.DOI)) {
throw new RuntimeException("Cannot output to DOI: "+outputLocation);
}
if (outputLocation == null) {
LOG.info("No explicit output location");
} else {
outputLocation = FilenameUtils.normalize(new File(outputLocation).getAbsolutePath());
extension = FilenameUtils.getExtension(outputLocation);
isDirectory = AMIUtil.endsWithSeparator(outputLocation) || extension == null || extension.equals("");
outputDirectory = new File(outputLocation);
}
}
protected String getOutputLocation() {
return outputLocation;
}
protected String getExtension() {
return extension;
}
protected boolean isDirectory() {
return isDirectory;
}
public File getOutputDirectoryFile() {
if (outputDirectory != null) {
LOG.trace("outputDirectory: "+outputDirectory);
if (outputDirectory.exists() && !outputDirectory.isDirectory()) {
LOG.info("existing file is not a directory: "+outputDirectory);
} else {
ifNotEndsWithSlashUseParentAsOutputDirectory();
outputDirectory.mkdirs();
String baseName = (visitableInputList == null || visitableInputList.size() == 0) ? DEFAULT_BASENAME
: visitableInputList.get(0).getBaseName();
LOG.trace("basename "+baseName);
outputDirectory = new File(outputDirectory, baseName+"."+extension);
}
} else {
throw new RuntimeException("Null output directory");
}
return outputDirectory;
}
private void ifNotEndsWithSlashUseParentAsOutputDirectory() {
if (!outputDirectory.toString().endsWith("/")) {
File parent = outputDirectory.getParentFile();
outputDirectory = (parent == null) ? outputDirectory : parent;
}
}
public void setExtension(String extension) {
this.extension = extension;
}
}
| tarrow/ami | src/main/java/org/xmlcml/ami/visitor/VisitorOutput.java | Java | apache-2.0 | 3,654 |
/*
Copyright 2006 Jerry Huxtable
Copyright 2009 Martin Davis
Copyright 2012 Antoine Gourlay
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.jproj;
import java.text.DecimalFormat;
/**
* Stores a the coordinates for a position
* defined relative to some {@link CoordinateReferenceSystem}.
* The coordinate is defined via X, Y, and optional Z ordinates.
* Provides utility methods for comparing the ordinates of two positions and
* for creating positions from Strings/storing positions as strings.
* <p>
* The primary use of this class is to represent coordinate
* values which are to be transformed
* by a {@link CoordinateTransform}.
*/
public class ProjCoordinate {
private static final String DECIMAL_FORMAT_PATTERN = "0.0###############";
// a DecimalFormat is not ThreadSafe, hence the ThreadLocal variable.
private static final ThreadLocal<DecimalFormat> DECIMAL_FORMAT = new ThreadLocal<DecimalFormat>() {
@Override
protected DecimalFormat initialValue() {
return new DecimalFormat(DECIMAL_FORMAT_PATTERN);
}
};
/**
* The X ordinate for this point.
* <p>
* Note: This member variable
* can be accessed directly. In the future this direct access should
* be replaced with getter and setter methods. This will require
* refactoring of the Proj4J code base.
*/
public double x;
/**
* The Y ordinate for this point.
* <p>
* Note: This member variable
* can be accessed directly. In the future this direct access should
* be replaced with getter and setter methods. This will require
* refactoring of the Proj4J code base.
*/
public double y;
/**
* The Z ordinate for this point.
* If this variable has the value <tt>Double.NaN</tt>
* then this coordinate does not have a Z value.
* <p>
* Note: This member variable
* can be accessed directly. In the future this direct access should
* be replaced with getter and setter methods. This will require
* refactoring of the Proj4J code base.
*/
public double z;
/**
* Creates a ProjCoordinate with default ordinate values.
*
*/
public ProjCoordinate() {
this(0.0, 0.0);
}
/**
* Creates a ProjCoordinate with values copied from the given coordinate object.
* @param pt a ProjCoordinate to copy
*/
public ProjCoordinate(ProjCoordinate pt) {
this(pt.x, pt.y, pt.z);
}
/**
* Creates a ProjCoordinate using the provided double parameters.
* The first double parameter is the x ordinate (or easting),
* the second double parameter is the y ordinate (or northing),
* and the third double parameter is the z ordinate (elevation or height).
*
* Valid values should be passed for all three (3) double parameters. If
* you want to create a horizontal-only point without a valid Z value, use
* the constructor defined in this class that only accepts two (2) double
* parameters.
*
* @param argX
* @param argY
* @param argZ
* @see #ProjCoordinate(double argX, double argY)
*/
public ProjCoordinate(double argX, double argY, double argZ) {
this.x = argX;
this.y = argY;
this.z = argZ;
}
/**
* Creates a ProjCoordinate using the provided double parameters.
* The first double parameter is the x ordinate (or easting),
* the second double parameter is the y ordinate (or northing).
* This constructor is used to create a "2D" point, so the Z ordinate
* is automatically set to Double.NaN.
* @param argX
* @param argY
*/
public ProjCoordinate(double argX, double argY) {
this.x = argX;
this.y = argY;
this.z = Double.NaN;
}
/**
* Create a ProjCoordinate by parsing a String in the same format as returned
* by the toString method defined by this class.
*
* @param argToParse the string to parse
*/
public ProjCoordinate(String argToParse) {
// Make sure the String starts with "ProjCoordinate: ".
if (!argToParse.startsWith("ProjCoordinate: ")) {
throw new IllegalArgumentException("The input string was not in the proper format.");
}
// 15 characters should cut out "ProjCoordinate: ".
String chomped = argToParse.substring(16);
// Get rid of the starting and ending square brackets.
String withoutFrontBracket = chomped.substring(1);
// Calc the position of the last bracket.
int length = withoutFrontBracket.length();
int positionOfCharBeforeLast = length - 2;
String withoutBackBracket = withoutFrontBracket.substring(0,
positionOfCharBeforeLast);
// We should be left with just the ordinate values as strings,
// separated by spaces. Split them into an array of Strings.
String[] parts = withoutBackBracket.split(" ");
// Get number of elements in Array. There should be two (2) elements
// or three (3) elements.
// If we don't have an array with two (2) or three (3) elements,
// then we need to throw an exception.
if (parts.length != 2 && parts.length != 3) {
throw new IllegalArgumentException("The input string was not in the proper format.");
}
// Convert strings to doubles.
this.x = "NaN".equals(parts[0]) ? Double.NaN : Double.parseDouble(parts[0]);
this.y = "NaN".equals(parts[1]) ? Double.NaN : Double.parseDouble(parts[1]);
// You might not always have a Z ordinate. If you do, set it.
if (parts.length == 3) {
this.z = "NaN".equals(parts[2]) ? Double.NaN : Double.parseDouble(parts[2]);
} else {
this.z = Double.NaN;
}
}
/**
* Sets the value of this coordinate to
* be equal to the given coordinate's ordinates.
*
* @param p the coordinate to copy
*/
public void setValue(ProjCoordinate p) {
this.x = p.x;
this.y = p.y;
this.z = p.z;
}
/**
* Returns a boolean indicating if the X ordinate value of the
* ProjCoordinate provided as an ordinate is equal to the X ordinate
* value of this ProjCoordinate. Because we are working with floating
* point numbers the ordinates are considered equal if the difference
* between them is less than the specified tolerance.
* @param argToCompare
* @param argTolerance
* @return
*/
public boolean areXOrdinatesEqual(ProjCoordinate argToCompare, double argTolerance) {
// Subtract the x ordinate values and then see if the difference
// between them is less than the specified tolerance. If the difference
// is less, return true.
return argToCompare.x - this.x <= argTolerance;
}
/**
* Returns a boolean indicating if the Y ordinate value of the
* ProjCoordinate provided as an ordinate is equal to the Y ordinate
* value of this ProjCoordinate. Because we are working with floating
* point numbers the ordinates are considered equal if the difference
* between them is less than the specified tolerance.
* @param argToCompare
* @param argTolerance
* @return
*/
public boolean areYOrdinatesEqual(ProjCoordinate argToCompare, double argTolerance) {
// Subtract the y ordinate values and then see if the difference
// between them is less than the specified tolerance. If the difference
// is less, return true.
return argToCompare.y - this.y <= argTolerance;
}
/**
* Returns a boolean indicating if the Z ordinate value of the
* ProjCoordinate provided as an ordinate is equal to the Z ordinate
* value of this ProjCoordinate. Because we are working with floating
* point numbers the ordinates are considered equal if the difference
* between them is less than the specified tolerance.
*
* If both Z ordinate values are Double.NaN this method will return
* true. If one Z ordinate value is a valid double value and one is
* Double.Nan, this method will return false.
* @param argToCompare
* @param argTolerance
* @return
*/
public boolean areZOrdinatesEqual(ProjCoordinate argToCompare, double argTolerance) {
// We have to handle Double.NaN values here, because not every
// ProjCoordinate will have a valid Z Value.
if (Double.isNaN(z)) {
return Double.isNaN(argToCompare.z);
// if true, both the z ordinate values are Double.Nan.
// else, We've got one z ordinate with a valid value and one with
// a Double.NaN value.
} // We have a valid z ordinate value in this ProjCoordinate object.
else {
if (Double.isNaN(argToCompare.z)) {
// We've got one z ordinate with a valid value and one with
// a Double.NaN value. Return false.
return false;
}
// If we get to this point in the method execution, we have to
// z ordinates with valid values, and we need to do a regular
// comparison. This is done in the remainder of the method.
}
// Subtract the z ordinate values and then see if the difference
// between them is less than the specified tolerance. If the difference
// is less, return true.
return argToCompare.z - this.z <= argTolerance;
}
/**
* Returns a string representing the ProjPoint in the format:
* <tt>ProjCoordinate[X Y Z]</tt>.
* <p>
* Example:
* <pre>
* ProjCoordinate[6241.11 5218.25 12.3]
* </pre>
*/
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("ProjCoordinate[");
if (Double.isNaN(x)) {
builder.append("NaN");
} else {
builder.append(x);
}
builder.append(" ");
if (Double.isNaN(x)) {
builder.append("NaN");
} else {
builder.append(y);
}
builder.append(" ");
if (Double.isNaN(x)) {
builder.append("NaN");
} else {
builder.append(z);
}
builder.append("]");
return builder.toString();
}
/**
* Returns a string representing the ProjPoint in the format:
* <tt>[X Y]</tt>
* or <tt>[X, Y, Z]</tt>.
* Z is not displayed if it is NaN.
* <p>
* Example:
* <pre>
* [6241.11, 5218.25, 12.3]
* </pre>
* @return
*/
public String toShortString() {
StringBuilder builder = new StringBuilder();
builder.append("[");
if (Double.isNaN(x)) {
builder.append("NaN");
} else {
builder.append(DECIMAL_FORMAT.get().format(x));
}
builder.append(", ");
if (Double.isNaN(y)) {
builder.append("NaN");
} else {
builder.append(DECIMAL_FORMAT.get().format(y));
}
if (!Double.isNaN(z)) {
builder.append(", ");
builder.append(this.z);
}
builder.append("]");
return builder.toString();
}
public boolean hasValidZOrdinate() {
return !Double.isNaN(z);
}
/**
* Indicates if this ProjCoordinate has valid X ordinate and Y ordinate
* values. Values are considered invalid if they are Double.NaN or
* positive/negative infinity.
* @return
*/
public boolean hasValidXandYOrdinates() {
return !Double.isNaN(x) && !Double.isInfinite(x) && !Double.isNaN(y) && !Double.isInfinite(y);
}
}
| ebocher/jproj | src/main/java/org/jproj/ProjCoordinate.java | Java | apache-2.0 | 14,438 |
package interviews;
public class Yahoo {
}
Run Length Encoding for byte array
Input byte array [10, 10, 10, 255, 255, 0, 10] ==> output byte array [3, 10, 2, 255, 1, 0, 1, 10]
Class ByteArrayEncodeDecode {
public byte[] encodeByteArray(byte[] input) {
int n = input.length;
if (n == 0) return new byte[];
Arraylist<Byte> out = Arraylist<Byte>();
byte prevByte = input[0];
byte prevCount = 1;
for (int i = 1; i < n; i++) {
if(prevByte == input[i] && prevCount != 255){ //
prevCount++;
} else {
out.add(prevCount);
out.add(prevByte);
prevByte = input[i];
prevCount = 1;
}
}
out.add(prevCount);
out.add(prevByte);
return out.toArray();
}
public static void main() {
}
}
// [] ==> []
// [1] ==> [1, 1]
// [1, 1, 1, 2, 2, 3] ==> [3, 1, 2, 2, 1, 3]
// [1 ... 300.....1] ==> [255, 1, 45, 1]
| rezaur86/Coding-competitions | Java/interviews/Yahoo.java | Java | apache-2.0 | 1,011 |
/*******************************************************************\
Module: Type Naming for C
Author: Daniel Kroening, [email protected]
\*******************************************************************/
#include <ctype.h>
#include <i2string.h>
#include <std_types.h>
#include "type2name.h"
/*******************************************************************\
Function: type2name
Inputs:
Outputs:
Purpose:
\*******************************************************************/
std::string type2name(const typet &type)
{
std::string result;
if(type.id()=="")
throw "Empty type encountered.";
else if(type.id()=="empty")
result+="V";
else if(type.id()=="signedbv")
result+="S" + type.width().as_string();
else if(type.id()=="unsignedbv")
result+="U" + type.width().as_string();
else if(type.is_bool())
result+="B";
else if(type.id()=="integer")
result+="I";
else if(type.id()=="real")
result+="R";
else if(type.id()=="complex")
result+="C";
else if(type.id()=="float")
result+="F";
else if(type.id()=="floatbv")
result+="F" + type.width().as_string();
else if(type.id()=="fixed")
result+="X";
else if(type.id()=="fixedbv")
result+="X" + type.width().as_string();
else if(type.id()=="natural")
result+="N";
else if(type.id()=="pointer")
result+="*";
else if(type.id()=="reference")
result+="&";
else if(type.is_code())
{
const code_typet &t = to_code_type(type);
const code_typet::argumentst arguments = t.arguments();
result+="P(";
for (code_typet::argumentst::const_iterator it = arguments.begin();
it!=arguments.end();
it++)
{
result+=type2name(it->type());
result+="'" + it->get_identifier().as_string() + "'|";
}
result.resize(result.size()-1);
result+=")";
}
else if(type.is_array())
{
const array_typet &t = to_array_type(type);
result+="ARR" + t.size().value().as_string();
}
else if(type.id()=="incomplete_array")
{
result+="ARR?";
}
else if(type.id()=="symbol")
{
result+="SYM#" + type.identifier().as_string() + "#";
}
else if(type.id()=="struct" ||
type.id()=="union")
{
if(type.id()=="struct") result +="ST";
if(type.id()=="union") result +="UN";
const struct_typet &t = to_struct_type(type);
const struct_typet::componentst &components = t.components();
result+="[";
for(struct_typet::componentst::const_iterator it = components.begin();
it!=components.end();
it++)
{
result+=type2name(it->type());
result+="'" + it->name().as_string() + "'|";
}
result.resize(result.size()-1);
result+="]";
}
else if(type.id()=="incomplete_struct")
result +="ST?";
else if(type.id()=="incomplete_union")
result +="UN?";
else if(type.id()=="c_enum")
result +="EN" + type.width().as_string();
else if(type.id()=="incomplete_c_enum")
result +="EN?";
else if(type.id()=="c_bitfield")
{
result+="BF" + type.size().as_string();
}
else
{
throw (std::string("Unknown type '") +
type.id().as_string() +
"' encountered.");
}
if(type.has_subtype())
{
result+="{";
result+=type2name(type.subtype());
result+="}";
}
if(type.has_subtypes())
{
result+="$";
forall_subtypes(it, type)
{
result+=type2name(*it);
result+="|";
}
result.resize(result.size()-1);
result+="$";
}
return result;
}
| ssvlab/esbmc-gpu | ansi-c/type2name.cpp | C++ | apache-2.0 | 3,566 |
# Hemimycena guanacastensis Singer SPECIES
#### Status
ACCEPTED
#### According to
Index Fungorum
#### Published in
Fieldiana, Bot. 21: 68 (1989)
#### Original name
Hemimycena guanacastensis Singer
### Remarks
null | mdoering/backbone | life/Fungi/Basidiomycota/Agaricomycetes/Agaricales/Mycenaceae/Hemimycena/Hemimycena guanacastensis/README.md | Markdown | apache-2.0 | 218 |
using System;
namespace ProSecuritiesTrading.MOEX.FIX.Base.Field
{
public class PartyID
{
public const int Tag = 448;
public static readonly byte[] TagBytes;
static PartyID()
{
TagBytes = new byte[3];
TagBytes[0] = 52;
TagBytes[1] = 52;
TagBytes[2] = 56;
}
}
}
| AlexeyLA0509/PSTTrader | src/ProSecuritiesTrading.MOEX.FIX/Base/Field/PartyID.cs | C# | apache-2.0 | 366 |
/*
* Copyright 2013-2017 Grzegorz Ligas <[email protected]> and other contributors
* (see the CONTRIBUTORS file).
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// This is a generated file. Not intended for manual editing.
package org.intellij.xquery.psi;
import java.util.List;
import org.jetbrains.annotations.*;
import com.intellij.psi.PsiElement;
public interface XQueryContextItemDecl extends XQueryPsiElement {
@Nullable
XQueryItemType getItemType();
@Nullable
XQuerySeparator getSeparator();
@Nullable
XQueryVarDefaultValue getVarDefaultValue();
@Nullable
XQueryVarValue getVarValue();
}
| ligasgr/intellij-xquery | gen/org/intellij/xquery/psi/XQueryContextItemDecl.java | Java | apache-2.0 | 1,132 |
using GoBuddies.Server.Data;
using GoBuddies.Server.Data.DbModels;
using GoBuddies.Services;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.AspNetCore.OData.Extensions;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Swashbuckle.Swagger.Model;
using System;
using System.IO;
namespace GoBuddies.Server.WebApi
{
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
if (env.IsEnvironment("Development"))
{
// This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately.
//builder.AddApplicationInsightsSettings(developerMode: true);
}
builder.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
////services.AddApplicationInsightsTelemetry(Configuration);
// add ef
services.AddDbContext<ApplicationDbContext>(options => options.UseInMemoryDatabase());
// add swagger
services.AddSwaggerGen();
services.ConfigureSwaggerGen(options =>
{
options.SingleApiVersion(new Info
{
Version = "v1",
Title = "Geo Search API",
Description = "A simple api to search using geo location in Elasticsearch",
TermsOfService = "None"
});
string pathToDoc = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "GoBuddies.Server.WebApi.XML");
options.IncludeXmlComments(pathToDoc);
options.DescribeAllEnumsAsStrings();
});
// config identity
services.AddIdentity<ApplicationUser, IdentityRole>(options =>
{
options.Cookies.ApplicationCookie.AuthenticationScheme = "ApplicationCookie";
options.Cookies.ApplicationCookie.CookieName = "Interop";
options.Cookies.ApplicationCookie.DataProtectionProvider = DataProtectionProvider.Create(new DirectoryInfo(@"C:\Identities"));
})
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.AddMvc();
// Add application services.
services.AddTransient<IEmailSender, AuthMessageSender>();
services.AddTransient<ISmsSender, AuthMessageSender>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
////app.UseApplicationInsightsRequestTelemetry();
////app.UseApplicationInsightsExceptionTelemetry();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller}/{action}/{id?}");
});
app.UseIdentity();
app.UseOData("odata");
app.UseSwagger();
app.UseSwaggerUi();
}
}
}
| dot-connect/GoBuddies | GoBuddies/GoBuddies.Server.WebApi/StartUp.cs | C# | apache-2.0 | 4,126 |
/*
* Copyright (c) 2008-2016 Computer Network Information Center (CNIC), Chinese Academy of Sciences.
*
* This file is part of Duckling project.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package net.duckling.vmt.domain;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import org.apache.log4j.Logger;
public class HttpGet {
private static final Logger LOG=Logger.getLogger(HttpGet.class);
private String path;
private String encode="UTF-8";
public HttpGet(String url,String encode){
this.path=url;
this.encode=encode;
}
public HttpGet(String url){
this.path=url;
}
public String connect(){
URL url = null;
try {
url = new URL(path);
} catch (MalformedURLException e) {
LOG.error(e.getMessage()+",can't touch this url="+path, e);
return null;
}
try (InputStream ins = url.openConnection().getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(ins, encode));) {
String line;
StringBuffer sb = new StringBuffer();
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
return sb.toString();
} catch (IOException e) {
LOG.error(e.getMessage(), e);
return null;
}
}
}
| duckling-falcon/vmt | src/main/java/net/duckling/vmt/domain/HttpGet.java | Java | apache-2.0 | 1,845 |
/*
* Copyright 2011 Jon S Akhtar (Sylvanaar)
*
* 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.sylvanaar.idea.Lua.lang.psi.impl.symbols;
import com.intellij.lang.ASTNode;
import com.sylvanaar.idea.Lua.lang.psi.symbols.LuaParameter;
import com.sylvanaar.idea.Lua.lang.psi.symbols.LuaSymbol;
import com.sylvanaar.idea.Lua.lang.psi.symbols.LuaUpvalueIdentifier;
/**
* Created by IntelliJ IDEA.
* User: Jon S Akhtar
* Date: 1/26/11
* Time: 9:23 PM
*/
public class LuaUpvalueIdentifierImpl extends LuaLocalIdentifierImpl implements LuaUpvalueIdentifier {
public LuaUpvalueIdentifierImpl(ASTNode node) {
super(node);
}
@Override
public boolean isSameKind(LuaSymbol symbol) {
return symbol instanceof LuaLocalDeclarationImpl || symbol instanceof LuaParameter;
}
@Override
public String toString() {
return "Upvalue: " + getText();
}
}
| consulo/consulo-lua | src/main/java/com/sylvanaar/idea/Lua/lang/psi/impl/symbols/LuaUpvalueIdentifierImpl.java | Java | apache-2.0 | 1,415 |
<?php
namespace ContainerFelbUiK;
use Symfony\Component\DependencyInjection\Argument\RewindableGenerator;
use Symfony\Component\DependencyInjection\Exception\RuntimeException;
/**
* @internal This class has been auto-generated by the Symfony Dependency Injection Component.
*/
class getForm_TypeExtension_Form_ValidatorService extends App_KernelDevDebugContainer
{
/**
* Gets the private 'form.type_extension.form.validator' shared service.
*
* @return \Symfony\Component\Form\Extension\Validator\Type\FormTypeValidatorExtension
*/
public static function do($container, $lazyLoad = true)
{
include_once \dirname(__DIR__, 4).'/vendor/symfony/form/FormTypeExtensionInterface.php';
include_once \dirname(__DIR__, 4).'/vendor/symfony/form/AbstractTypeExtension.php';
include_once \dirname(__DIR__, 4).'/vendor/symfony/form/Extension/Validator/Type/BaseValidatorExtension.php';
include_once \dirname(__DIR__, 4).'/vendor/symfony/form/Extension/Validator/Type/FormTypeValidatorExtension.php';
return $container->privates['form.type_extension.form.validator'] = new \Symfony\Component\Form\Extension\Validator\Type\FormTypeValidatorExtension(($container->services['validator'] ?? $container->getValidatorService()));
}
}
| cloudfoundry/php-buildpack | fixtures/symfony_5_local_deps/var/cache/dev/ContainerFelbUiK/getForm_TypeExtension_Form_ValidatorService.php | PHP | apache-2.0 | 1,296 |
# Trachycaryon hookeri var. hookeri F.Muell. VARIETY
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Malpighiales/Euphorbiaceae/Adriana/Adriana urticoides/Adriana urticoides hookeri/Trachycaryon hookeri hookeri/README.md | Markdown | apache-2.0 | 192 |
# Sphaeria corticola Fuckel, 1870 SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
Jb. nassau. Ver. Naturk. 23-24: (1870)
#### Original name
Sphaeria corticola Fuckel, 1870
### Remarks
null | mdoering/backbone | life/Fungi/Ascomycota/Sordariomycetes/Xylariales/Amphisphaeriaceae/Discostroma/Discostroma corticola/ Syn. Sphaeria corticola/README.md | Markdown | apache-2.0 | 249 |
# Hutchinsia stricta (Roth) Lyngbye SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Rhodophyta/Florideophyceae/Ceramiales/Rhodomelaceae/Polysiphonia/Polysiphonia fibrillosa/ Syn. Hutchinsia stricta/README.md | Markdown | apache-2.0 | 190 |
# Issatchenkia Kudrjanzev GENUS
#### Status
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
Bot. Mater. Otd. Sporov. Rast. Bot. Inst. Komarova Akad. Nauk S. S. S. R. 13: 143 (1960)
#### Original name
Issatchenkia Kudrjanzev
### Remarks
null | mdoering/backbone | life/Fungi/Ascomycota/Saccharomycetes/Saccharomycetales/Pichiaceae/Issatchenkia/README.md | Markdown | apache-2.0 | 282 |
# Alpinia corneri (Holttum) R.M.Sm. SPECIES
#### Status
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
Cenolophon corneri Holttum
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Liliopsida/Zingiberales/Zingiberaceae/Alpinia/Alpinia corneri/README.md | Markdown | apache-2.0 | 213 |
package com.buschmais.xo.neo4j.test.id;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import java.util.Collection;
import com.buschmais.xo.api.XOManager;
import com.buschmais.xo.api.bootstrap.XOUnit;
import com.buschmais.xo.neo4j.test.AbstractNeo4JXOManagerIT;
import com.buschmais.xo.neo4j.test.id.composite.A;
import com.buschmais.xo.neo4j.test.id.composite.A2B;
import com.buschmais.xo.neo4j.test.id.composite.B;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
@RunWith(Parameterized.class)
public class EqualsHashcodeIT extends AbstractNeo4JXOManagerIT {
public EqualsHashcodeIT(XOUnit xoUnit) {
super(xoUnit);
}
@Parameterized.Parameters
public static Collection<Object[]> getXOUnits() {
return xoUnits(A.class, B.class, A2B.class);
}
@Test
public void equalsHashcode() {
XOManager xoManager = getXOManager();
xoManager.currentTransaction().begin();
A a = xoManager.create(A.class);
int aHashCode = a.hashCode();
B b = xoManager.create(B.class);
int bHashCode = b.hashCode();
A2B a2b = xoManager.create(a, A2B.class, b);
int a2bHashCode = a2b.hashCode();
xoManager.currentTransaction().commit();
xoManager.currentTransaction().begin();
assertThat(a.equals(a), equalTo(true));
assertThat(b.equals(b), equalTo(true));
assertThat(a2b.equals(a2b), equalTo(true));
assertThat(a.hashCode(), equalTo(aHashCode));
assertThat(b.hashCode(), equalTo(bHashCode));
assertThat(a2b.hashCode(), equalTo(a2bHashCode));
xoManager.currentTransaction().commit();
}
}
| buschmais/extended-objects | neo4j/test/src/test/java/com/buschmais/xo/neo4j/test/id/EqualsHashcodeIT.java | Java | apache-2.0 | 1,744 |
package com.tle.configmanager;
import com.dytech.gui.ComponentHelper;
import com.thoughtworks.xstream.XStream;
import com.tle.common.Check;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JSeparator;
import net.miginfocom.swing.MigLayout;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.io.FileUtils;
// Author: Andrew Gibb
@SuppressWarnings({"serial", "nls"})
public class ConfigLauncherGUI extends JFrame implements ActionListener {
public static final String MANDATORY_CONFIG = "mandatory-config.properties";
public static final String OPTIONAL_CONFIG = "optional-config.properties";
public static final String HIBERNATE_CONFIG = "hibernate.properties";
public static final String LOGGING_CONFIG = "learningedge-log4j.properties";
public static final String IMAGEMAGICK_CONFIG =
"plugins/com.tle.core.imagemagick/config.properties.unresolved";
public static final String HIKARI_CONFIG = "hikari.properties";
private final String TITLE = "TLE Configuration Manager";
private final String PATH = "./configs/";
private final String ORACLE = "oracle";
private final String POSTGRESQL = "postgresql";
private final String MSSQL = "ms sql";
private final String source;
private final String destination;
private JLabel lblConfig;
private JComboBox<ConfigProfile> cmbConfigs;
private JButton btnNew, btnEdit, btnApply, btnDelete;
private JSeparator sep;
private List<ConfigProfile> configs;
public ConfigLauncherGUI(String source, String destination) {
setTitle(TITLE);
setupGUI();
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
this.source = source;
this.destination = destination;
// Set a minimum width...leave the height to the pack...
setMinimumSize(new Dimension(300, 0));
pack();
ComponentHelper.centreOnScreen(this);
// Updated combo box containing profiles
updateConfigs();
}
// Sets up the GUI for managing/loading the configuration profiles
private void setupGUI() {
Container contents = getContentPane();
contents.setLayout(new MigLayout("wrap 3", "[grow][grow][grow]"));
configs = new ArrayList<ConfigProfile>();
lblConfig = new JLabel("Configurations: ");
cmbConfigs = new JComboBox<ConfigProfile>();
btnNew = new JButton("New");
btnNew.addActionListener(this);
btnApply = new JButton("Apply Configuration");
btnApply.addActionListener(this);
btnEdit = new JButton("Edit");
btnEdit.addActionListener(this);
sep = new JSeparator();
btnDelete = new JButton("Delete");
btnDelete.addActionListener(this);
contents.add(lblConfig, "growx, spanx 3");
contents.add(cmbConfigs, "growx, spanx 3");
contents.add(btnNew, "growx, center");
contents.add(btnEdit, "growx, center");
contents.add(btnDelete, "growx, center");
contents.add(sep, "growx, spanx 3");
contents.add(btnApply, "center, growx, spanx 3");
}
// Updates the available configuration profiles
public void updateConfigs() {
File srcDir = new File(PATH);
File[] configFiles = srcDir.listFiles();
Reader rdr;
cmbConfigs.removeAllItems();
configs.clear();
if (configFiles != null) {
for (File f : configFiles) {
if (f.isFile()) {
XStream xstream = new XStream();
try {
rdr = new BufferedReader(new FileReader(f));
ConfigProfile prof = (ConfigProfile) xstream.fromXML(rdr);
configs.add(prof);
rdr.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
Collections.sort(
configs,
new Comparator<ConfigProfile>() {
@Override
public int compare(ConfigProfile o1, ConfigProfile o2) {
return o1.getProfName().compareToIgnoreCase(o2.getProfName());
}
});
for (ConfigProfile prof : configs) {
cmbConfigs.addItem(prof);
}
}
if (configs.isEmpty()) {
btnEdit.setEnabled(false);
btnApply.setEnabled(false);
btnDelete.setEnabled(false);
} else {
btnEdit.setEnabled(true);
btnApply.setEnabled(true);
btnDelete.setEnabled(true);
}
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btnNew) {
addProfile();
} else if (e.getSource() == btnEdit) {
editProfile();
} else if (e.getSource() == btnDelete) {
deleteProfile();
} else if (e.getSource() == btnApply) {
try {
loadProfile();
} catch (Exception ex) {
JOptionPane.showMessageDialog(
null,
"Error loading configuration: \n" + ex.getMessage(),
"Load Failed",
JOptionPane.ERROR_MESSAGE);
}
}
}
// Adds a new profile which is either a clone of an existing profile or is
// blank
private void addProfile() {
ConfigEditorGUI confEd = null;
if (configs != null && cmbConfigs.getSelectedItem() != null) {
ConfigProfile selectedProf = (ConfigProfile) cmbConfigs.getSelectedItem();
int result =
JOptionPane.showConfirmDialog(
null,
"Do you want to clone the currently selected configuration?: "
+ selectedProf.getProfName(),
"Clone Confirmation",
JOptionPane.YES_NO_OPTION);
if (result == JOptionPane.YES_OPTION) {
confEd = new ConfigEditorGUI(selectedProf, "copy");
} else {
confEd = new ConfigEditorGUI();
}
} else {
confEd = new ConfigEditorGUI();
}
confEd.setModal(true);
confEd.setVisible(true);
if (confEd.getResult() == ConfigEditorGUI.RESULT_SAVE) {
updateConfigs();
}
}
// Edits and existing profile
private void editProfile() {
int index = cmbConfigs.getSelectedIndex();
ConfigProfile selectedProf = (ConfigProfile) cmbConfigs.getSelectedItem();
ConfigEditorGUI confEd = new ConfigEditorGUI(selectedProf);
confEd.setModal(true);
confEd.setVisible(true);
if (confEd.getResult() == ConfigEditorGUI.RESULT_SAVE) {
updateConfigs();
cmbConfigs.setSelectedIndex(index);
}
}
// Deletes a configuration profile
private void deleteProfile() {
ConfigProfile selectedProf = (ConfigProfile) cmbConfigs.getSelectedItem();
File toDel = new File(PATH + selectedProf.getProfName() + ".xml");
int result =
JOptionPane.showConfirmDialog(
null,
"Are you sure you want to delete this configuration?: " + selectedProf.getProfName(),
"Delete Confirmation",
JOptionPane.YES_NO_OPTION);
if (result == JOptionPane.YES_OPTION) {
boolean success = toDel.delete();
if (!success) {
JOptionPane.showMessageDialog(
null,
"Unable to delete configuration: " + selectedProf.getProfName(),
"Delete Failed",
JOptionPane.ERROR_MESSAGE);
}
}
updateConfigs();
}
// Loads a profile (SUPER HACKISH)
private void loadProfile() throws FileNotFoundException, IOException, ConfigurationException {
ConfigProfile selectedProf = (ConfigProfile) cmbConfigs.getSelectedItem();
File srcDir = new File(source);
// Remove Current Configuration Files
File destDir = new File(destination);
FileUtils.deleteDirectory(destDir);
// Create Destination
destDir.mkdir();
// Copy Required Files (Database Specific)
boolean oracleSelected = selectedProf.getDbtype().equalsIgnoreCase(ORACLE);
if (oracleSelected) {
org.apache.commons.io.FileUtils.copyFile(
new File(srcDir + "/hibernate.properties.oracle"),
new File(destDir + "/hibernate.properties"));
} else if (selectedProf.getDbtype().equalsIgnoreCase(POSTGRESQL)) {
FileUtils.copyFile(
new File(srcDir + "/hibernate.properties.postgresql"),
new File(destDir + "/hibernate.properties"));
} else if (selectedProf.getDbtype().equalsIgnoreCase(MSSQL)) {
FileUtils.copyFile(
new File(srcDir + "/hibernate.properties.sqlserver"),
new File(destDir + "/hibernate.properties"));
}
// Mandatory / Optional / Logging
FileUtils.copyFile(
new File(srcDir + "/mandatory-config.properties"),
new File(destDir + "/mandatory-config.properties"));
FileUtils.copyFile(
new File(srcDir + "/optional-config.properties"),
new File(destDir + "/optional-config.properties"));
// Copy custom development logging file
FileUtils.copyFile(
new File("./learningedge-log4j.properties"),
new File(destDir + "/learningedge-log4j.properties"));
// Other Miscellaneous Files
FileUtils.copyFile(
new File(srcDir + "/en-stopWords.txt"), new File(destDir + "/en-stopWords.txt"));
FileUtils.copyFile(
new File(srcDir + "/" + HIKARI_CONFIG), new File(destDir + "/" + HIKARI_CONFIG));
// Plugins Folder
FileUtils.copyDirectoryToDirectory(new File(srcDir + "/plugins"), destDir);
// Edit Hibernate Properties
String hibProp = readFile(destination + "/" + HIBERNATE_CONFIG);
hibProp = hibProp.replace("${datasource/host}", selectedProf.getHost());
hibProp = hibProp.replace("${datasource/port}", selectedProf.getPort());
hibProp = hibProp.replace("${datasource/database}", selectedProf.getDatabase());
hibProp = hibProp.replace("${datasource/username}", selectedProf.getUsername());
hibProp = hibProp.replace("${datasource/password}", selectedProf.getPassword());
hibProp =
hibProp.replace(
"${datasource/schema}",
oracleSelected ? "hibernate.default_schema = " + selectedProf.getUsername() : "");
writeFile(destination + "/hibernate.properties", hibProp);
// Edit Mandatory Properties
PropertyEditor mandProps = new PropertyEditor();
mandProps.load(new File(destination + "/" + MANDATORY_CONFIG));
String http = selectedProf.getHttp();
String portFromUrl = selectedProf.getAdminurl().split(":")[1];
mandProps.setProperty(
"http.port",
!Check.isEmpty(http) ? http : !Check.isEmpty(portFromUrl) ? portFromUrl : "80");
String https = selectedProf.getHttps();
if (!Check.isEmpty(https)) {
mandProps.setProperty("https.port", https);
}
String ajp = selectedProf.getAjp();
if (!Check.isEmpty(https)) {
mandProps.setProperty("ajp.port", ajp);
}
mandProps.setProperty("filestore.root", selectedProf.getFilestore());
mandProps.setProperty("java.home", selectedProf.getJavahome());
mandProps.setProperty("admin.url", selectedProf.getAdminurl());
mandProps.setProperty("freetext.index.location", selectedProf.getFreetext());
mandProps.setProperty("freetext.stopwords.file", selectedProf.getStopwords());
String reporting = selectedProf.getReporting();
if (!Check.isEmpty(reporting)) {
mandProps.setProperty("reporting.workspace.location", reporting);
}
mandProps.setProperty("plugins.location", selectedProf.getPlugins());
mandProps.save(new File(destination + "/" + MANDATORY_CONFIG));
// Edit Optional Properties
String optProp = readFile(destination + "/" + OPTIONAL_CONFIG);
if (selectedProf.isDevinst()) {
optProp =
optProp.replace(
"#conversionService.disableConversion = false",
"conversionService.disableConversion = true");
optProp =
optProp.replace(
"conversionService.conversionServicePath = ${install.path#t\\/}/conversion/conversion-service.jar",
"#conversionService.conversionServicePath =");
optProp =
optProp.replace("#pluginPathResolver.wrappedClass", "pluginPathResolver.wrappedClass");
} else {
optProp =
optProp.replace(
"${install.path#t\\/}/conversion/conversion-service.jar",
selectedProf.getConversion());
}
writeFile(destination + "/optional-config.properties", optProp);
// Edit ImageMagik Properties (MORE HAX...)
File imgmgk = new File(destination + "/" + IMAGEMAGICK_CONFIG);
PropertyEditor magickProps = new PropertyEditor();
magickProps.load(imgmgk);
magickProps.setProperty("imageMagick.path", selectedProf.getImagemagick());
magickProps.save(new File((destination + "/" + IMAGEMAGICK_CONFIG).replace(".unresolved", "")));
imgmgk.delete();
JOptionPane.showMessageDialog(
null,
"The configuration: " + selectedProf.getProfName() + " has been successfully loaded.",
"Load Success",
JOptionPane.INFORMATION_MESSAGE);
}
// Reads a file into a string
private String readFile(String path) throws IOException {
StringBuilder contents = new StringBuilder();
BufferedReader br = new BufferedReader(new FileReader(path));
String line = null;
while ((line = br.readLine()) != null) {
contents.append(line);
contents.append(System.getProperty("line.separator"));
}
br.close();
return contents.toString();
}
// Writes a file from String
private void writeFile(String path, String contents) throws IOException {
BufferedWriter output = null;
output = new BufferedWriter(new FileWriter(new File(path)));
output.write(contents);
output.close();
}
}
| equella/Equella | Source/Tools/ConfigManager/src/com/tle/configmanager/ConfigLauncherGUI.java | Java | apache-2.0 | 13,989 |
<?php
final class DrydockLeaseViewController extends DrydockLeaseController {
public function handleRequest(AphrontRequest $request) {
$viewer = $request->getViewer();
$id = $request->getURIData('id');
$lease = id(new DrydockLeaseQuery())
->setViewer($viewer)
->withIDs(array($id))
->needUnconsumedCommands(true)
->executeOne();
if (!$lease) {
return new Aphront404Response();
}
$lease_uri = $this->getApplicationURI('lease/'.$lease->getID().'/');
$title = pht('Lease %d', $lease->getID());
$header = id(new PHUIHeaderView())
->setHeader($title);
if ($lease->isReleasing()) {
$header->setStatus('fa-exclamation-triangle', 'red', pht('Releasing'));
}
$actions = $this->buildActionListView($lease);
$properties = $this->buildPropertyListView($lease, $actions);
$pager = new PHUIPagerView();
$pager->setURI(new PhutilURI($lease_uri), 'offset');
$pager->setOffset($request->getInt('offset'));
$logs = id(new DrydockLogQuery())
->setViewer($viewer)
->withLeaseIDs(array($lease->getID()))
->executeWithOffsetPager($pager);
$log_table = id(new DrydockLogListView())
->setUser($viewer)
->setLogs($logs)
->render();
$log_table->appendChild($pager);
$crumbs = $this->buildApplicationCrumbs();
$crumbs->addTextCrumb($title, $lease_uri);
$locks = $this->buildLocksTab($lease->getPHID());
$commands = $this->buildCommandsTab($lease->getPHID());
$object_box = id(new PHUIObjectBoxView())
->setHeader($header)
->addPropertyList($properties, pht('Properties'))
->addPropertyList($locks, pht('Slot Locks'))
->addPropertyList($commands, pht('Commands'));
$log_box = id(new PHUIObjectBoxView())
->setHeaderText(pht('Lease Logs'))
->setTable($log_table);
return $this->buildApplicationPage(
array(
$crumbs,
$object_box,
$log_box,
),
array(
'title' => $title,
));
}
private function buildActionListView(DrydockLease $lease) {
$viewer = $this->getViewer();
$view = id(new PhabricatorActionListView())
->setUser($viewer)
->setObjectURI($this->getRequest()->getRequestURI())
->setObject($lease);
$id = $lease->getID();
$can_release = $lease->canRelease();
if ($lease->isReleasing()) {
$can_release = false;
}
$can_edit = PhabricatorPolicyFilter::hasCapability(
$viewer,
$lease,
PhabricatorPolicyCapability::CAN_EDIT);
$view->addAction(
id(new PhabricatorActionView())
->setName(pht('Release Lease'))
->setIcon('fa-times')
->setHref($this->getApplicationURI("/lease/{$id}/release/"))
->setWorkflow(true)
->setDisabled(!$can_release || !$can_edit));
return $view;
}
private function buildPropertyListView(
DrydockLease $lease,
PhabricatorActionListView $actions) {
$viewer = $this->getViewer();
$view = new PHUIPropertyListView();
$view->setActionList($actions);
$view->addProperty(
pht('Status'),
DrydockLeaseStatus::getNameForStatus($lease->getStatus()));
$view->addProperty(
pht('Resource Type'),
$lease->getResourceType());
$owner_phid = $lease->getOwnerPHID();
if ($owner_phid) {
$owner_display = $viewer->renderHandle($owner_phid);
} else {
$owner_display = phutil_tag('em', array(), pht('No Owner'));
}
$view->addProperty(pht('Owner'), $owner_display);
$resource_phid = $lease->getResourcePHID();
if ($resource_phid) {
$resource_display = $viewer->renderHandle($resource_phid);
} else {
$resource_display = phutil_tag('em', array(), pht('No Resource'));
}
$view->addProperty(pht('Resource'), $resource_display);
$until = $lease->getUntil();
if ($until) {
$until_display = phabricator_datetime($until, $viewer);
} else {
$until_display = phutil_tag('em', array(), pht('Never'));
}
$view->addProperty(pht('Expires'), $until_display);
$attributes = $lease->getAttributes();
if ($attributes) {
$view->addSectionHeader(
pht('Attributes'), 'fa-list-ul');
foreach ($attributes as $key => $value) {
$view->addProperty($key, $value);
}
}
return $view;
}
}
| librewiki/phabricator | src/applications/drydock/controller/DrydockLeaseViewController.php | PHP | apache-2.0 | 4,366 |
# Lecanactis opponens (Nyl.) H. Olivier SPECIES
#### Status
ACCEPTED
#### According to
Index Fungorum
#### Published in
null
#### Original name
Lecidea opponens Nyl.
### Remarks
null | mdoering/backbone | life/Fungi/Ascomycota/Arthoniomycetes/Arthoniales/Roccellaceae/Lecanactis/Lecanactis opponens/README.md | Markdown | apache-2.0 | 187 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
using System;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using System.Text;
namespace Microsoft.Web.Utility.PInvoke.Fusion
{
[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("CD193BC0-B4BC-11d2-9833-00C04FC31D2E")]
internal interface IAssemblyName
{
[PreserveSig()]
int SetProperty(
int PropertyId,
IntPtr pvProperty,
int cbProperty);
[PreserveSig()]
int GetProperty(
int PropertyId,
IntPtr pvProperty,
ref int pcbProperty);
[PreserveSig()]
int Finalize();
[PreserveSig()]
int GetDisplayName(
StringBuilder pDisplayName,
ref int pccDisplayName,
int displayFlags);
[PreserveSig()]
int Reserved(ref Guid guid,
Object obj1,
Object obj2,
String string1,
Int64 llFlags,
IntPtr pvReserved,
int cbReserved,
out IntPtr ppv);
[PreserveSig()]
int GetName(
ref int pccBuffer,
StringBuilder pwzName);
[PreserveSig()]
int GetVersion(
out int versionHi,
out int versionLow);
[PreserveSig()]
int IsEqual(
IAssemblyName pAsmName,
int cmpFlags);
[PreserveSig()]
int Clone(out IAssemblyName pAsmName);
}// IAssemblyName
[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("e707dcde-d1cd-11d2-bab9-00c04f8eceae")]
internal interface IAssemblyCache
{
[PreserveSig()]
int UninstallAssembly(
int flags,
[MarshalAs(UnmanagedType.LPWStr)]
string assemblyName,
IntPtr refData,
out int disposition);
[PreserveSig()]
int QueryAssemblyInfo(
int flags,
[MarshalAs(UnmanagedType.LPWStr)]
string assemblyName,
ref AssemblyInfo assemblyInfo);
[PreserveSig()]
int Reserved(
int flags,
IntPtr pvReserved,
out object ppAsmItem,
[MarshalAs(UnmanagedType.LPWStr)]
string assemblyName);
[PreserveSig()]
int Reserved(out object ppAsmScavenger);
[PreserveSig()]
int InstallAssembly(
int flags,
[MarshalAs(UnmanagedType.LPWStr)]
string assemblyFilePath,
IntPtr refData);
}// IAssemblyCache
[StructLayout(LayoutKind.Sequential)]
internal struct AssemblyInfo
{
public int cbAssemblyInfo; // size of this structure for future expansion
public int assemblyFlags;
public long assemblySizeInKB;
[MarshalAs(UnmanagedType.LPWStr)]
public string currentAssemblyPath;
public int cchBuf; // size of path buf.
}
[Flags]
internal enum AssemblyCacheFlags
{
GAC = 2,
}
[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("21b8916c-f28e-11d2-a473-00c04f8ef448")]
internal interface IAssemblyEnum
{
[PreserveSig()]
int GetNextAssembly(
IntPtr pvReserved,
out IAssemblyName ppName,
int flags);
[PreserveSig()]
int Reset();
[PreserveSig()]
int Clone(out IAssemblyEnum ppEnum);
}
[Flags]
internal enum AssemblyNameDisplayFlags
{
VERSION = 0x01,
CULTURE = 0x02,
PUBLIC_KEY_TOKEN = 0x04,
PROCESSORARCHITECTURE = 0x20,
RETARGETABLE = 0x80,
// This enum might change in the future to include
// more attributes.
ALL =
VERSION
| CULTURE
| PUBLIC_KEY_TOKEN
| PROCESSORARCHITECTURE
| RETARGETABLE
}
internal enum CreateAssemblyNameObjectFlags
{
CANOF_DEFAULT = 0,
CANOF_PARSE_DISPLAY_NAME = 1,
}
internal static class NativeMethods
{
[DllImport("fusion.dll")]
public static extern int CreateAssemblyCache(
out IAssemblyCache ppAsmCache,
int reserved);
[DllImport("fusion.dll")]
public static extern int CreateAssemblyEnum(
out IAssemblyEnum ppEnum,
IntPtr pUnkReserved,
IAssemblyName pName,
AssemblyCacheFlags flags,
IntPtr pvReserved);
[DllImport("fusion.dll")]
public static extern int CreateAssemblyNameObject(
out IAssemblyName ppAssemblyNameObj,
[MarshalAs(UnmanagedType.LPWStr)]
String szAssemblyName,
CreateAssemblyNameObjectFlags flags,
IntPtr pvReserved);
}
}
| aspnet/AspNetCore | src/Installers/Windows/AspNetCoreModule-Setup/IIS-Setup/IIS-Common/Managed/NativeMethods/Fusion.cs | C# | apache-2.0 | 4,421 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.4.2_11) on Sun Oct 15 22:02:21 CDT 2006 -->
<TITLE>
Uses of Interface org.hibernate.dialect.lock.LockingStrategy (Hibernate API Documentation)
</TITLE>
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../jdstyle.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
parent.document.title="Uses of Interface org.hibernate.dialect.lock.LockingStrategy (Hibernate API Documentation)";
}
</SCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=3 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../org/hibernate/dialect/lock/LockingStrategy.html" title="interface in org.hibernate.dialect.lock"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html" target="_top"><B>FRAMES</B></A>
<A HREF="LockingStrategy.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<CENTER>
<H2>
<B>Uses of Interface<br>org.hibernate.dialect.lock.LockingStrategy</B></H2>
</CENTER>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TD COLSPAN=2><FONT SIZE="+2">
Packages that use <A HREF="../../../../../org/hibernate/dialect/lock/LockingStrategy.html" title="interface in org.hibernate.dialect.lock">LockingStrategy</A></FONT></TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#org.hibernate.dialect"><B>org.hibernate.dialect</B></A></TD>
<TD>
This package abstracts the SQL dialect of the underlying database. </TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#org.hibernate.dialect.lock"><B>org.hibernate.dialect.lock</B></A></TD>
<TD> </TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#org.hibernate.persister.entity"><B>org.hibernate.persister.entity</B></A></TD>
<TD>
This package abstracts persistence mechanisms for
entities, and defines the Hibernate runtime
metamodel. </TD>
</TR>
</TABLE>
<P>
<A NAME="org.hibernate.dialect"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TD COLSPAN=2><FONT SIZE="+2">
Uses of <A HREF="../../../../../org/hibernate/dialect/lock/LockingStrategy.html" title="interface in org.hibernate.dialect.lock">LockingStrategy</A> in <A HREF="../../../../../org/hibernate/dialect/package-summary.html">org.hibernate.dialect</A></FONT></TD>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TD COLSPAN=2>Classes in <A HREF="../../../../../org/hibernate/dialect/package-summary.html">org.hibernate.dialect</A> that implement <A HREF="../../../../../org/hibernate/dialect/lock/LockingStrategy.html" title="interface in org.hibernate.dialect.lock">LockingStrategy</A></FONT></TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>static class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../org/hibernate/dialect/HSQLDialect.ReadUncommittedLockingStrategy.html" title="class in org.hibernate.dialect">HSQLDialect.ReadUncommittedLockingStrategy</A></B></CODE>
<BR>
</TD>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TD COLSPAN=2>Methods in <A HREF="../../../../../org/hibernate/dialect/package-summary.html">org.hibernate.dialect</A> that return <A HREF="../../../../../org/hibernate/dialect/lock/LockingStrategy.html" title="interface in org.hibernate.dialect.lock">LockingStrategy</A></FONT></TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../../org/hibernate/dialect/lock/LockingStrategy.html" title="interface in org.hibernate.dialect.lock">LockingStrategy</A></CODE></FONT></TD>
<TD><CODE><B>TimesTenDialect.</B><B><A HREF="../../../../../org/hibernate/dialect/TimesTenDialect.html#getLockingStrategy(org.hibernate.persister.entity.Lockable, org.hibernate.LockMode)">getLockingStrategy</A></B>(<A HREF="../../../../../org/hibernate/persister/entity/Lockable.html" title="interface in org.hibernate.persister.entity">Lockable</A> lockable,
<A HREF="../../../../../org/hibernate/LockMode.html" title="class in org.hibernate">LockMode</A> lockMode)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../../org/hibernate/dialect/lock/LockingStrategy.html" title="interface in org.hibernate.dialect.lock">LockingStrategy</A></CODE></FONT></TD>
<TD><CODE><B>RDMSOS2200Dialect.</B><B><A HREF="../../../../../org/hibernate/dialect/RDMSOS2200Dialect.html#getLockingStrategy(org.hibernate.persister.entity.Lockable, org.hibernate.LockMode)">getLockingStrategy</A></B>(<A HREF="../../../../../org/hibernate/persister/entity/Lockable.html" title="interface in org.hibernate.persister.entity">Lockable</A> lockable,
<A HREF="../../../../../org/hibernate/LockMode.html" title="class in org.hibernate">LockMode</A> lockMode)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../../org/hibernate/dialect/lock/LockingStrategy.html" title="interface in org.hibernate.dialect.lock">LockingStrategy</A></CODE></FONT></TD>
<TD><CODE><B>PointbaseDialect.</B><B><A HREF="../../../../../org/hibernate/dialect/PointbaseDialect.html#getLockingStrategy(org.hibernate.persister.entity.Lockable, org.hibernate.LockMode)">getLockingStrategy</A></B>(<A HREF="../../../../../org/hibernate/persister/entity/Lockable.html" title="interface in org.hibernate.persister.entity">Lockable</A> lockable,
<A HREF="../../../../../org/hibernate/LockMode.html" title="class in org.hibernate">LockMode</A> lockMode)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../../org/hibernate/dialect/lock/LockingStrategy.html" title="interface in org.hibernate.dialect.lock">LockingStrategy</A></CODE></FONT></TD>
<TD><CODE><B>MckoiDialect.</B><B><A HREF="../../../../../org/hibernate/dialect/MckoiDialect.html#getLockingStrategy(org.hibernate.persister.entity.Lockable, org.hibernate.LockMode)">getLockingStrategy</A></B>(<A HREF="../../../../../org/hibernate/persister/entity/Lockable.html" title="interface in org.hibernate.persister.entity">Lockable</A> lockable,
<A HREF="../../../../../org/hibernate/LockMode.html" title="class in org.hibernate">LockMode</A> lockMode)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../../org/hibernate/dialect/lock/LockingStrategy.html" title="interface in org.hibernate.dialect.lock">LockingStrategy</A></CODE></FONT></TD>
<TD><CODE><B>HSQLDialect.</B><B><A HREF="../../../../../org/hibernate/dialect/HSQLDialect.html#getLockingStrategy(org.hibernate.persister.entity.Lockable, org.hibernate.LockMode)">getLockingStrategy</A></B>(<A HREF="../../../../../org/hibernate/persister/entity/Lockable.html" title="interface in org.hibernate.persister.entity">Lockable</A> lockable,
<A HREF="../../../../../org/hibernate/LockMode.html" title="class in org.hibernate">LockMode</A> lockMode)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../../org/hibernate/dialect/lock/LockingStrategy.html" title="interface in org.hibernate.dialect.lock">LockingStrategy</A></CODE></FONT></TD>
<TD><CODE><B>FrontBaseDialect.</B><B><A HREF="../../../../../org/hibernate/dialect/FrontBaseDialect.html#getLockingStrategy(org.hibernate.persister.entity.Lockable, org.hibernate.LockMode)">getLockingStrategy</A></B>(<A HREF="../../../../../org/hibernate/persister/entity/Lockable.html" title="interface in org.hibernate.persister.entity">Lockable</A> lockable,
<A HREF="../../../../../org/hibernate/LockMode.html" title="class in org.hibernate">LockMode</A> lockMode)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../../org/hibernate/dialect/lock/LockingStrategy.html" title="interface in org.hibernate.dialect.lock">LockingStrategy</A></CODE></FONT></TD>
<TD><CODE><B>Dialect.</B><B><A HREF="../../../../../org/hibernate/dialect/Dialect.html#getLockingStrategy(org.hibernate.persister.entity.Lockable, org.hibernate.LockMode)">getLockingStrategy</A></B>(<A HREF="../../../../../org/hibernate/persister/entity/Lockable.html" title="interface in org.hibernate.persister.entity">Lockable</A> lockable,
<A HREF="../../../../../org/hibernate/LockMode.html" title="class in org.hibernate">LockMode</A> lockMode)</CODE>
<BR>
Get a strategy instance which knows how to acquire a database-level lock
of the specified mode for this dialect.</TD>
</TR>
</TABLE>
<P>
<A NAME="org.hibernate.dialect.lock"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TD COLSPAN=2><FONT SIZE="+2">
Uses of <A HREF="../../../../../org/hibernate/dialect/lock/LockingStrategy.html" title="interface in org.hibernate.dialect.lock">LockingStrategy</A> in <A HREF="../../../../../org/hibernate/dialect/lock/package-summary.html">org.hibernate.dialect.lock</A></FONT></TD>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TD COLSPAN=2>Classes in <A HREF="../../../../../org/hibernate/dialect/lock/package-summary.html">org.hibernate.dialect.lock</A> that implement <A HREF="../../../../../org/hibernate/dialect/lock/LockingStrategy.html" title="interface in org.hibernate.dialect.lock">LockingStrategy</A></FONT></TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../org/hibernate/dialect/lock/SelectLockingStrategy.html" title="class in org.hibernate.dialect.lock">SelectLockingStrategy</A></B></CODE>
<BR>
A locking strategy where the locks are obtained through select statements.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../org/hibernate/dialect/lock/UpdateLockingStrategy.html" title="class in org.hibernate.dialect.lock">UpdateLockingStrategy</A></B></CODE>
<BR>
A locking strategy where the locks are obtained through update statements.</TD>
</TR>
</TABLE>
<P>
<A NAME="org.hibernate.persister.entity"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TD COLSPAN=2><FONT SIZE="+2">
Uses of <A HREF="../../../../../org/hibernate/dialect/lock/LockingStrategy.html" title="interface in org.hibernate.dialect.lock">LockingStrategy</A> in <A HREF="../../../../../org/hibernate/persister/entity/package-summary.html">org.hibernate.persister.entity</A></FONT></TD>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TD COLSPAN=2>Methods in <A HREF="../../../../../org/hibernate/persister/entity/package-summary.html">org.hibernate.persister.entity</A> that return <A HREF="../../../../../org/hibernate/dialect/lock/LockingStrategy.html" title="interface in org.hibernate.dialect.lock">LockingStrategy</A></FONT></TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>protected <A HREF="../../../../../org/hibernate/dialect/lock/LockingStrategy.html" title="interface in org.hibernate.dialect.lock">LockingStrategy</A></CODE></FONT></TD>
<TD><CODE><B>AbstractEntityPersister.</B><B><A HREF="../../../../../org/hibernate/persister/entity/AbstractEntityPersister.html#generateLocker(org.hibernate.LockMode)">generateLocker</A></B>(<A HREF="../../../../../org/hibernate/LockMode.html" title="class in org.hibernate">LockMode</A> lockMode)</CODE>
<BR>
</TD>
</TR>
</TABLE>
<P>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=3 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../org/hibernate/dialect/lock/LockingStrategy.html" title="interface in org.hibernate.dialect.lock"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html" target="_top"><B>FRAMES</B></A>
<A HREF="LockingStrategy.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
</BODY>
</HTML>
| renmeng8875/projects | Hibernate-source/源代码及重要说明/Hibernate相关资料/hibernate-3.2.0.ga/hibernate-3.2/doc/api/org/hibernate/dialect/lock/class-use/LockingStrategy.html | HTML | apache-2.0 | 18,122 |
# Russula decolorans var. albida A. Blytt VARIETY
#### Status
ACCEPTED
#### According to
Index Fungorum
#### Published in
null
#### Original name
Russula decolorans var. albida A. Blytt
### Remarks
null | mdoering/backbone | life/Fungi/Basidiomycota/Agaricomycetes/Russulales/Russulaceae/Russula/Russula decolorans/Russula decolorans albida/README.md | Markdown | apache-2.0 | 207 |
# Meibomia megaphylla (Zoll.) Kuntze SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Fabales/Fabaceae/Desmodium/Desmodium megaphyllum/ Syn. Meibomia megaphylla/README.md | Markdown | apache-2.0 | 191 |
# Artanthe poeppigii var. glabrior Miq. VARIETY
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Piperales/Piperaceae/Artanthe/Artanthe poeppigii/Artanthe poeppigii glabrior/README.md | Markdown | apache-2.0 | 187 |
# Teucrium polium subsp. carthaginense (Lange) O.Bolòs & Vigo SUBSPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
Teucrium carthaginense Lange
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Lamiales/Lamiaceae/Teucrium/Teucrium polium/Teucrium polium carthaginense/README.md | Markdown | apache-2.0 | 237 |
# Ficus virgata Reinw. ex Blume SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
Bijdr. 454. 1825
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Rosales/Moraceae/Ficus/Ficus virgata/README.md | Markdown | apache-2.0 | 191 |
# Scorzonera tau-saghyz Lipsch. & G.G.Bosse SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
Trans. rubber & cuttap. Inst. 1:7. 1930 (Trans. rubber & Cuttap. Inst. 4:27. 1931)
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Scorzonera/Scorzonera tau-saghyz/README.md | Markdown | apache-2.0 | 269 |
# Conyza macrorrhiza Sch.Bip. ex A.Rich. SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Erigeron/Erigeron karvinskianus/ Syn. Conyza macrorrhiza/README.md | Markdown | apache-2.0 | 195 |
# Zanthoxylum L. GENUS
#### Status
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Sapindales/Rutaceae/Zanthoxylum/README.md | Markdown | apache-2.0 | 170 |
package com.krealid.starter.adapters;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import com.krealid.starter.R;
import butterknife.ButterKnife;
/**
* Created by Maxime on 26/08/2015.
*/
public class ActuExpendedAdapter extends RecyclerView.Adapter<ActuExpendedAdapter.ViewHolder> {
private String text;
private Context context;
private View view;
public ActuExpendedAdapter(String text, Context context){
this.text = text;
this.context = context;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
view = LayoutInflater
.from(parent.getContext())
.inflate(R.layout.actu_text, parent,false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
String iframeLink;
if(this.text.contains("<iframe")){
String iframeStart = "<iframe src=\"";
String iframeEnd = "\" width=";
int indexToStartIframe = this.text.indexOf(iframeStart);
int indexToEndIframe = (this.text.substring(indexToStartIframe)).indexOf(iframeEnd);
String iframeHeight = "height=\"";
int indexToStartHeightIframe= this.text.indexOf(iframeHeight);
String iframeHeightValue = this.text.substring(indexToStartHeightIframe + iframeHeight.length(),
this.text.indexOf('"', indexToStartHeightIframe + iframeHeight.length()));
iframeLink = this.text.substring(indexToStartIframe + iframeStart.length(),
indexToStartIframe + indexToEndIframe);
String articleText = this.text.substring(0, indexToStartIframe);
holder.text.loadData("<font style=\"text-align:justify;text-justify:inter-word;\">" +
articleText + "</font>", "text/html; charset=UTF-8", null);
final RelativeLayout layout = new RelativeLayout(this.context);
RelativeLayout.LayoutParams lprams = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.MATCH_PARENT);
layout.setLayoutParams(lprams);
WebView web1 = new WebView(this.context);
web1.setWebChromeClient(new WebChromeClient());
web1.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
web1.getSettings().setJavaScriptEnabled(true);
web1.getSettings().setPluginState(WebSettings.PluginState.ON);
web1.loadUrl(iframeLink);
web1.setId(R.id.myWebView);
int height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
Integer.parseInt(iframeHeightValue),
this.context.getResources().getDisplayMetrics());
final RelativeLayout.LayoutParams webViewParams = new RelativeLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, height);
layout.addView(web1, webViewParams);
holder.articleContainer.addView(layout);
} else {
holder.text.loadData("<font style=\"text-align:justify;text-justify:inter-word;\">" +
this.text + "</font>", "text/html; charset=UTF-8", null);
}
}
@Override
public int getItemCount() {
return 1;
}
public void stopVideo(){
ViewHolder holder = new ViewHolder(view);
WebView mWebView = (WebView) holder.articleContainer.findViewById(R.id.myWebView);
if(mWebView != null)
mWebView.loadUrl("about:blank");
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public WebView text;
public LinearLayout articleContainer;
public ViewHolder(View itemView) {
super(itemView);
text = ButterKnife.findById(itemView, R.id.articleContent);
articleContainer = ButterKnife.findById(itemView, R.id.article_container);
}
}
}
| max02100/paroisse | ParseStarterProject/src/main/java/com/krealid/starter/adapters/ActuExpendedAdapter.java | Java | apache-2.0 | 4,384 |
//
// PBObjcWrapper.h
// AppBootstrap
//
// Created by Yaming on 10/31/14.
// Copyright (c) 2014 whosbean.com. All rights reserved.
//
#import <Foundation/Foundation.h>
#ifdef __cplusplus
#import <google/protobuf/message.h>
#endif
@protocol PBObjcWrapper <NSObject>
-(instancetype) initWithProtocolData:(NSData*) data;
#ifdef __cplusplus
-(instancetype) initWithProtocolObj:(google::protobuf::Message *)pbobj;
#endif
-(NSData*) getProtocolData;
-(NSMutableDictionary*) asDict;
@end
| yamingd/AppBootstrap-iOS | AppBootstrap/Protobuf/PBObjcWrapper.hh | C++ | apache-2.0 | 493 |
# AUTOGENERATED FILE
FROM balenalib/beagleboard-xm-ubuntu:cosmic-build
ENV NODE_VERSION 12.20.1
ENV YARN_VERSION 1.22.4
RUN for key in \
6A010C5166006599AA17F08146C2130DFD2497F5 \
; do \
gpg --keyserver pgp.mit.edu --recv-keys "$key" || \
gpg --keyserver keyserver.pgp.com --recv-keys "$key" || \
gpg --keyserver ha.pool.sks-keyservers.net --recv-keys "$key" ; \
done \
&& curl -SLO "http://nodejs.org/dist/v$NODE_VERSION/node-v$NODE_VERSION-linux-armv7l.tar.gz" \
&& echo "7283ced5d7c0cc036a35bc2e64b23e7d4b348848170567880edabcf5279f4f8a node-v$NODE_VERSION-linux-armv7l.tar.gz" | sha256sum -c - \
&& tar -xzf "node-v$NODE_VERSION-linux-armv7l.tar.gz" -C /usr/local --strip-components=1 \
&& rm "node-v$NODE_VERSION-linux-armv7l.tar.gz" \
&& curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz" \
&& curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz.asc" \
&& gpg --batch --verify yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \
&& mkdir -p /opt/yarn \
&& tar -xzf yarn-v$YARN_VERSION.tar.gz -C /opt/yarn --strip-components=1 \
&& ln -s /opt/yarn/bin/yarn /usr/local/bin/yarn \
&& ln -s /opt/yarn/bin/yarn /usr/local/bin/yarnpkg \
&& rm yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \
&& npm config set unsafe-perm true -g --unsafe-perm \
&& rm -rf /tmp/*
CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"]
RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/[email protected]" \
&& echo "Running test-stack@node" \
&& chmod +x [email protected] \
&& bash [email protected] \
&& rm -rf [email protected]
RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v7 \nOS: Ubuntu cosmic \nVariant: build variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nNode.js v12.20.1, Yarn v1.22.4 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info
RUN echo '#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \
&& chmod +x /bin/sh-shim \
&& cp /bin/sh /bin/sh.real \
&& mv /bin/sh-shim /bin/sh | nghiant2710/base-images | balena-base-images/node/beagleboard-xm/ubuntu/cosmic/12.20.1/build/Dockerfile | Dockerfile | apache-2.0 | 2,767 |
package storage
import (
"io/ioutil"
"log"
"os"
"path/filepath"
"testing"
)
func TestSetBinlogPosition(t *testing.T) {
dir, err := ioutil.TempDir("", "example")
if err != nil {
log.Fatal(err)
}
defer os.RemoveAll(dir)
file := filepath.Join(dir, "temp.db")
store := &BoltDBStore{}
store.Open(file)
store.SetBinlogPosition(&BinlogInformation{File: "binlog001.log", Position: 1234567890})
binlogInfo, err := store.GetBinlogPosition()
if err != nil || binlogInfo.File != "binlog001.log" || binlogInfo.Position != 1234567890 {
t.Error("failed")
}
}
| simongui/fastlane | storage/boltdb_store_test.go | GO | apache-2.0 | 568 |
/*
* Copyright 2005-2017 ECMWF.
*
* This software is licensed under the terms of the Apache Licence Version 2.0
* which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
*
* In applying this licence, ECMWF does not waive the privileges and immunities granted to it by
* virtue of its status as an intergovernmental organisation nor does it submit to any jurisdiction.
*/
/*****************************
* Enrico Fucile
****************************/
#include "grib_api_internal.h"
/*
This is used by make_class.pl
START_CLASS_DEF
CLASS = accessor
SUPER = grib_accessor_class_long
IMPLEMENTS = unpack_long
IMPLEMENTS = init
MEMBERS = const char* numberOfValues
MEMBERS = const char* bitsPerValue
MEMBERS = const char* offsetBeforeData
MEMBERS = const char* offsetAfterData
MEMBERS = const char* unusedBits
END_CLASS_DEF
*/
/* START_CLASS_IMP */
/*
Don't edit anything between START_CLASS_IMP and END_CLASS_IMP
Instead edit values between START_CLASS_DEF and END_CLASS_DEF
or edit "accessor.class" and rerun ./make_class.pl
*/
static int unpack_long(grib_accessor*, long* val,size_t *len);
static void init(grib_accessor*,const long, grib_arguments* );
static void init_class(grib_accessor_class*);
typedef struct grib_accessor_number_of_coded_values {
grib_accessor att;
/* Members defined in gen */
/* Members defined in long */
/* Members defined in number_of_coded_values */
const char* numberOfValues;
const char* bitsPerValue;
const char* offsetBeforeData;
const char* offsetAfterData;
const char* unusedBits;
} grib_accessor_number_of_coded_values;
extern grib_accessor_class* grib_accessor_class_long;
static grib_accessor_class _grib_accessor_class_number_of_coded_values = {
&grib_accessor_class_long, /* super */
"number_of_coded_values", /* name */
sizeof(grib_accessor_number_of_coded_values), /* size */
0, /* inited */
&init_class, /* init_class */
&init, /* init */
0, /* post_init */
0, /* free mem */
0, /* describes himself */
0, /* get length of section */
0, /* get length of string */
0, /* get number of values */
0, /* get number of bytes */
0, /* get offset to bytes */
0, /* get native type */
0, /* get sub_section */
0, /* grib_pack procedures long */
0, /* grib_pack procedures long */
0, /* grib_pack procedures long */
&unpack_long, /* grib_unpack procedures long */
0, /* grib_pack procedures double */
0, /* grib_unpack procedures double */
0, /* grib_pack procedures string */
0, /* grib_unpack procedures string */
0, /* grib_pack procedures bytes */
0, /* grib_unpack procedures bytes */
0, /* pack_expression */
0, /* notify_change */
0, /* update_size */
0, /* preferred_size */
0, /* resize */
0, /* nearest_smaller_value */
0, /* next accessor */
0, /* compare vs. another accessor */
0, /* unpack only ith value */
0, /* unpack a subarray */
0, /* clear */
};
grib_accessor_class* grib_accessor_class_number_of_coded_values = &_grib_accessor_class_number_of_coded_values;
static void init_class(grib_accessor_class* c)
{
c->dump = (*(c->super))->dump;
c->next_offset = (*(c->super))->next_offset;
c->string_length = (*(c->super))->string_length;
c->value_count = (*(c->super))->value_count;
c->byte_count = (*(c->super))->byte_count;
c->byte_offset = (*(c->super))->byte_offset;
c->get_native_type = (*(c->super))->get_native_type;
c->sub_section = (*(c->super))->sub_section;
c->pack_missing = (*(c->super))->pack_missing;
c->is_missing = (*(c->super))->is_missing;
c->pack_long = (*(c->super))->pack_long;
c->pack_double = (*(c->super))->pack_double;
c->unpack_double = (*(c->super))->unpack_double;
c->pack_string = (*(c->super))->pack_string;
c->unpack_string = (*(c->super))->unpack_string;
c->pack_bytes = (*(c->super))->pack_bytes;
c->unpack_bytes = (*(c->super))->unpack_bytes;
c->pack_expression = (*(c->super))->pack_expression;
c->notify_change = (*(c->super))->notify_change;
c->update_size = (*(c->super))->update_size;
c->preferred_size = (*(c->super))->preferred_size;
c->resize = (*(c->super))->resize;
c->nearest_smaller_value = (*(c->super))->nearest_smaller_value;
c->next = (*(c->super))->next;
c->compare = (*(c->super))->compare;
c->unpack_double_element = (*(c->super))->unpack_double_element;
c->unpack_double_subarray = (*(c->super))->unpack_double_subarray;
c->clear = (*(c->super))->clear;
}
/* END_CLASS_IMP */
static void init(grib_accessor* a,const long l, grib_arguments* c)
{
int n=0;
grib_accessor_number_of_coded_values* self = (grib_accessor_number_of_coded_values*)a;
self->bitsPerValue = grib_arguments_get_name(a->parent->h,c,n++);
self->offsetBeforeData = grib_arguments_get_name(a->parent->h,c,n++);
self->offsetAfterData = grib_arguments_get_name(a->parent->h,c,n++);
self->unusedBits = grib_arguments_get_name(a->parent->h,c,n++);
self->numberOfValues = grib_arguments_get_name(a->parent->h,c,n++);
a->flags |= GRIB_ACCESSOR_FLAG_READ_ONLY;
a->flags |= GRIB_ACCESSOR_FLAG_FUNCTION;
a->length=0;
}
static int unpack_long(grib_accessor* a, long* val, size_t *len)
{
int ret=GRIB_SUCCESS;
long bpv=0;
long offsetBeforeData=0,offsetAfterData=0,unusedBits=0,numberOfValues;
grib_accessor_number_of_coded_values* self = (grib_accessor_number_of_coded_values*)a;
if((ret = grib_get_long_internal(a->parent->h, self->bitsPerValue,&bpv)) != GRIB_SUCCESS)
return ret;
if((ret = grib_get_long_internal(a->parent->h, self->offsetBeforeData,&offsetBeforeData)) != GRIB_SUCCESS)
return ret;
if((ret = grib_get_long_internal(a->parent->h, self->offsetAfterData,&offsetAfterData)) != GRIB_SUCCESS)
return ret;
if((ret = grib_get_long_internal(a->parent->h, self->unusedBits,&unusedBits)) != GRIB_SUCCESS)
return ret;
if ( bpv != 0 ) {
grib_context_log(a->parent->h->context,GRIB_LOG_DEBUG,"grib_accessor_number_of_coded_values: offsetAfterData=%ld offsetBeforeData=%ld unusedBits=%ld bpv=%ld\n",
offsetAfterData,offsetBeforeData,unusedBits,bpv);
*val=((offsetAfterData-offsetBeforeData)*8-unusedBits)/bpv;
} else {
if((ret = grib_get_long_internal(a->parent->h, self->numberOfValues,&numberOfValues)) != GRIB_SUCCESS)
return ret;
*val=numberOfValues;
}
return ret;
}
| weathersource/grib_api | src/grib_accessor_class_number_of_coded_values.c | C | apache-2.0 | 7,223 |
/*
* Copyright 2014 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkBigPicture.h"
#include "SkData.h"
#include "SkDrawable.h"
#include "SkLayerInfo.h"
#include "SkPictureRecorder.h"
#include "SkPictureUtils.h"
#include "SkRecord.h"
#include "SkRecordDraw.h"
#include "SkRecordOpts.h"
#include "SkRecorder.h"
#include "SkTypes.h"
SkPictureRecorder::SkPictureRecorder() {
fActivelyRecording = false;
fRecorder.reset(new SkRecorder(nullptr, SkRect::MakeWH(0, 0), &fMiniRecorder));
}
SkPictureRecorder::~SkPictureRecorder() {}
SkCanvas* SkPictureRecorder::beginRecording(const SkRect& cullRect,
SkBBHFactory* bbhFactory /* = nullptr */,
uint32_t recordFlags /* = 0 */) {
fCullRect = cullRect;
fFlags = recordFlags;
if (bbhFactory) {
fBBH.reset((*bbhFactory)(cullRect));
SkASSERT(fBBH.get());
}
if (!fRecord) {
fRecord.reset(new SkRecord);
}
SkRecorder::DrawPictureMode dpm = (recordFlags & kPlaybackDrawPicture_RecordFlag)
? SkRecorder::Playback_DrawPictureMode
: SkRecorder::Record_DrawPictureMode;
fRecorder->reset(fRecord.get(), cullRect, dpm, &fMiniRecorder);
fActivelyRecording = true;
return this->getRecordingCanvas();
}
SkCanvas* SkPictureRecorder::getRecordingCanvas() {
return fActivelyRecording ? fRecorder.get() : nullptr;
}
sk_sp<SkPicture> SkPictureRecorder::finishRecordingAsPicture() {
fActivelyRecording = false;
fRecorder->restoreToCount(1); // If we were missing any restores, add them now.
if (fRecord->count() == 0) {
return fMiniRecorder.detachAsPicture(fCullRect);
}
// TODO: delay as much of this work until just before first playback?
SkRecordOptimize(fRecord);
SkAutoTUnref<SkLayerInfo> saveLayerData;
if (fBBH && (fFlags & kComputeSaveLayerInfo_RecordFlag)) {
saveLayerData.reset(new SkLayerInfo);
}
SkDrawableList* drawableList = fRecorder->getDrawableList();
SkBigPicture::SnapshotArray* pictList =
drawableList ? drawableList->newDrawableSnapshot() : nullptr;
if (fBBH.get()) {
SkAutoTMalloc<SkRect> bounds(fRecord->count());
if (saveLayerData) {
SkRecordComputeLayers(fCullRect, *fRecord, bounds, pictList, saveLayerData);
} else {
SkRecordFillBounds(fCullRect, *fRecord, bounds);
}
fBBH->insert(bounds, fRecord->count());
// Now that we've calculated content bounds, we can update fCullRect, often trimming it.
// TODO: get updated fCullRect from bounds instead of forcing the BBH to return it?
SkRect bbhBound = fBBH->getRootBound();
SkASSERT((bbhBound.isEmpty() || fCullRect.contains(bbhBound))
|| (bbhBound.isEmpty() && fCullRect.isEmpty()));
fCullRect = bbhBound;
}
size_t subPictureBytes = fRecorder->approxBytesUsedBySubPictures();
for (int i = 0; pictList && i < pictList->count(); i++) {
subPictureBytes += SkPictureUtils::ApproximateBytesUsed(pictList->begin()[i]);
}
return sk_make_sp<SkBigPicture>(fCullRect, fRecord.release(), pictList, fBBH.release(),
saveLayerData.release(), subPictureBytes);
}
sk_sp<SkPicture> SkPictureRecorder::finishRecordingAsPictureWithCull(const SkRect& cullRect) {
fCullRect = cullRect;
return this->finishRecordingAsPicture();
}
void SkPictureRecorder::partialReplay(SkCanvas* canvas) const {
if (nullptr == canvas) {
return;
}
int drawableCount = 0;
SkDrawable* const* drawables = nullptr;
SkDrawableList* drawableList = fRecorder->getDrawableList();
if (drawableList) {
drawableCount = drawableList->count();
drawables = drawableList->begin();
}
SkRecordDraw(*fRecord, canvas, nullptr, drawables, drawableCount, nullptr/*bbh*/, nullptr/*callback*/);
}
///////////////////////////////////////////////////////////////////////////////////////////////////
class SkRecordedDrawable : public SkDrawable {
SkAutoTUnref<SkRecord> fRecord;
SkAutoTUnref<SkBBoxHierarchy> fBBH;
SkAutoTDelete<SkDrawableList> fDrawableList;
const SkRect fBounds;
const bool fDoSaveLayerInfo;
public:
SkRecordedDrawable(SkRecord* record, SkBBoxHierarchy* bbh, SkDrawableList* drawableList,
const SkRect& bounds, bool doSaveLayerInfo)
: fRecord(SkRef(record))
, fBBH(SkSafeRef(bbh))
, fDrawableList(drawableList) // we take ownership
, fBounds(bounds)
, fDoSaveLayerInfo(doSaveLayerInfo)
{}
protected:
SkRect onGetBounds() override { return fBounds; }
void onDraw(SkCanvas* canvas) override {
SkDrawable* const* drawables = nullptr;
int drawableCount = 0;
if (fDrawableList) {
drawables = fDrawableList->begin();
drawableCount = fDrawableList->count();
}
SkRecordDraw(*fRecord, canvas, nullptr, drawables, drawableCount, fBBH, nullptr/*callback*/);
}
SkPicture* onNewPictureSnapshot() override {
SkBigPicture::SnapshotArray* pictList = nullptr;
if (fDrawableList) {
// TODO: should we plumb-down the BBHFactory and recordFlags from our host
// PictureRecorder?
pictList = fDrawableList->newDrawableSnapshot();
}
SkAutoTUnref<SkLayerInfo> saveLayerData;
if (fBBH && fDoSaveLayerInfo) {
// TODO: can we avoid work by not allocating / filling these bounds?
SkAutoTMalloc<SkRect> scratchBounds(fRecord->count());
saveLayerData.reset(new SkLayerInfo);
SkRecordComputeLayers(fBounds, *fRecord, scratchBounds, pictList, saveLayerData);
}
size_t subPictureBytes = 0;
for (int i = 0; pictList && i < pictList->count(); i++) {
subPictureBytes += SkPictureUtils::ApproximateBytesUsed(pictList->begin()[i]);
}
// SkBigPicture will take ownership of a ref on both fRecord and fBBH.
// We're not willing to give up our ownership, so we must ref them for SkPicture.
return new SkBigPicture(fBounds, SkRef(fRecord.get()), pictList, SkSafeRef(fBBH.get()),
saveLayerData.release(), subPictureBytes);
}
};
sk_sp<SkDrawable> SkPictureRecorder::finishRecordingAsDrawable() {
fActivelyRecording = false;
fRecorder->flushMiniRecorder();
fRecorder->restoreToCount(1); // If we were missing any restores, add them now.
// TODO: delay as much of this work until just before first playback?
SkRecordOptimize(fRecord);
if (fBBH.get()) {
SkAutoTMalloc<SkRect> bounds(fRecord->count());
SkRecordFillBounds(fCullRect, *fRecord, bounds);
fBBH->insert(bounds, fRecord->count());
}
sk_sp<SkDrawable> drawable =
sk_make_sp<SkRecordedDrawable>(fRecord, fBBH, fRecorder->detachDrawableList(), fCullRect,
SkToBool(fFlags & kComputeSaveLayerInfo_RecordFlag));
// release our refs now, so only the drawable will be the owner.
fRecord.reset(nullptr);
fBBH.reset(nullptr);
return drawable;
}
| qrealka/skia-hc | src/core/SkPictureRecorder.cpp | C++ | apache-2.0 | 7,381 |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Text;
namespace gov.va.medora.mdo.dao
{
public interface IEncounterDao
{
Appointment[] getAppointments();
Appointment[] getAppointments(string pid);
Appointment[] getFutureAppointments();
Appointment[] getFutureAppointments(string pid);
Appointment[] getAppointments(int pastDays, int futureDays);
Appointment[] getAppointments(string pid, int pastDays, int futureDays);
Appointment[] getMentalHealthAppointments();
string getAppointmentText(string apptId);
string getAppointmentText(string pid, string apptId);
Adt[] getInpatientMoves(string fromDate, string toDate);
Adt[] getInpatientMovesByCheckinId(string checkinId);
Adt[] getInpatientMoves();
Adt[] getInpatientMoves(string pid);
Adt[] getInpatientMoves(string fromDate, string toDate, string iterLength);
// Depreciate to lookupHospitalLocations
HospitalLocation[] lookupLocations(string target, string direction);
StringDictionary lookupHospitalLocations(string target);
string getLocationId(string locationName);
HospitalLocation[] getWards();
HospitalLocation[] getClinics(string target, string direction);
InpatientStay[] getStaysForWard(string wardId);
Drg[] getDRGRecords();
Visit[] getOutpatientVisits();
Visit[] getOutpatientVisits(string pid);
Visit[] getVisits(string fromDate, string toDate);
Visit[] getVisits(string pid, string fromDate, string toDate);
Visit[] getVisitsForDay(string theDate);
Visit[] getMentalHealthVisits();
InpatientStay[] getAdmissions();
InpatientStay[] getAdmissions(string pid);
string getServiceConnectedCategory(string initialCategory, string locationIen, bool outpatient);
string getOutpatientEncounterReport(string fromDate, string toDate, int nrpts);
string getOutpatientEncounterReport(string pid, string fromDate, string toDate, int nrpts);
string getAdmissionsReport(string fromDate, string toDate, int nrpts);
string getAdmissionsReport(string pid, string fromDate, string toDate, int nrpts);
string getExpandedAdtReport(string fromDate, string toDate, int nrpts);
string getExpandedAdtReport(string pid, string fromDate, string toDate, int nrpts);
string getDischargesReport(string fromDate, string toDate, int nrpts);
string getDischargesReport(string pid, string fromDate, string toDate, int nrpts);
string getTransfersReport(string fromDate, string toDate, int nrpts);
string getTransfersReport(string pid, string fromDate, string toDate, int nrpts);
string getFutureClinicVisitsReport(string fromDate, string toDate, int nrpts);
string getFutureClinicVisitsReport(string pid, string fromDate, string toDate, int nrpts);
string getPastClinicVisitsReport(string fromDate, string toDate, int nrpts);
string getPastClinicVisitsReport(string pid, string fromDate, string toDate, int nrpts);
string getTreatingSpecialtyReport(string fromDate, string toDate, int nrpts);
string getTreatingSpecialtyReport(string pid, string fromDate, string toDate, int nrpts);
string getCareTeamReport();
string getCareTeamReport(string pid);
string getDischargeDiagnosisReport(string fromDate, string toDate, int nrpts);
string getDischargeDiagnosisReport(string pid, string fromDate, string toDate, int nrpts);
IcdReport[] getIcdProceduresReport(string fromDate, string toDate, int nrpts);
IcdReport[] getIcdProceduresReport(string pid, string fromDate, string toDate, int nrpts);
IcdReport[] getIcdSurgeryReport(string fromDate, string toDate, int nrpts);
IcdReport[] getIcdSurgeryReport(string pid, string fromDate, string toDate, int nrpts);
string getCompAndPenReport(string fromDate, string toDate, int nrpts);
string getCompAndPenReport(string pid, string fromDate, string toDate, int nrpts);
DictionaryHashList getSpecialties();
DictionaryHashList getTeams();
Adt[] getInpatientDischarges(string pid);
InpatientStay[] getStayMovementsByDateRange(string fromDate, string toDate);
InpatientStay getStayMovements(string checkinId);
Site[] getSiteDivisions(string siteId);
PatientCareTeam getPatientCareTeamMembers(string station);
}
}
| VHAINNOVATIONS/RAPTOR | OtherComponents/MDWSvistalayer/MDWS Source/mdo/mdo/src/mdo/dao/IEncounterDao.cs | C# | apache-2.0 | 4,557 |
/*
* Copyright (c) 2017 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
package org.webrtc;
@JNINamespace("webrtc::jni")
class VP8Decoder extends WrappedNativeVideoDecoder {
@Override
long createNativeDecoder() {
return nativeCreateDecoder();
}
static native long nativeCreateDecoder();
}
| wangcy6/storm_app | frame/c++/webrtc-master/sdk/android/src/java/org/webrtc/VP8Decoder.java | Java | apache-2.0 | 645 |
/*
* Copyright (C) 2013 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.inputmethod.keyboard.internal;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.os.Message;
import android.util.SparseArray;
import android.view.View;
import com.android.inputmethod.keyboard.PointerTracker;
import com.android.inputmethod.keyboard.internal.GestureTrail.Params;
import com.android.inputmethod.latin.CollectionUtils;
import com.android.inputmethod.latin.StaticInnerHandlerWrapper;
/**
* Draw gesture trail preview graphics during gesture.
*/
public final class GestureTrailsPreview extends AbstractDrawingPreview {
private final SparseArray<GestureTrail> mGestureTrails = CollectionUtils.newSparseArray();
private final Params mGestureTrailParams;
private final Paint mGesturePaint;
private int mOffscreenWidth;
private int mOffscreenHeight;
private int mOffscreenOffsetY;
private Bitmap mOffscreenBuffer;
private final Canvas mOffscreenCanvas = new Canvas();
private final Rect mOffscreenSrcRect = new Rect();
private final Rect mDirtyRect = new Rect();
private final Rect mGestureTrailBoundsRect = new Rect(); // per trail
private final DrawingHandler mDrawingHandler;
private static final class DrawingHandler
extends StaticInnerHandlerWrapper<GestureTrailsPreview> {
private static final int MSG_UPDATE_GESTURE_TRAIL = 0;
private final Params mGestureTrailParams;
public DrawingHandler(final GestureTrailsPreview outerInstance,
final Params gestureTrailParams) {
super(outerInstance);
mGestureTrailParams = gestureTrailParams;
}
@Override
public void handleMessage(final Message msg) {
final GestureTrailsPreview preview = getOuterInstance();
if (preview == null) return;
switch (msg.what) {
case MSG_UPDATE_GESTURE_TRAIL:
preview.getDrawingView().invalidate();
break;
}
}
public void postUpdateGestureTrailPreview() {
removeMessages(MSG_UPDATE_GESTURE_TRAIL);
sendMessageDelayed(obtainMessage(MSG_UPDATE_GESTURE_TRAIL),
mGestureTrailParams.mUpdateInterval);
}
}
public GestureTrailsPreview(final View drawingView, final TypedArray mainKeyboardViewAttr) {
super(drawingView);
mGestureTrailParams = new Params(mainKeyboardViewAttr);
mDrawingHandler = new DrawingHandler(this, mGestureTrailParams);
final Paint gesturePaint = new Paint();
gesturePaint.setAntiAlias(true);
gesturePaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC));
mGesturePaint = gesturePaint;
}
@Override
public void setKeyboardGeometry(final int[] originCoords, final int width, final int height) {
mOffscreenOffsetY = (int)(
height * GestureStroke.EXTRA_GESTURE_TRAIL_AREA_ABOVE_KEYBOARD_RATIO);
mOffscreenWidth = width;
mOffscreenHeight = mOffscreenOffsetY + height;
}
@Override
public void onDetachFromWindow() {
freeOffscreenBuffer();
}
private void freeOffscreenBuffer() {
if (mOffscreenBuffer != null) {
mOffscreenBuffer.recycle();
mOffscreenBuffer = null;
}
}
private void mayAllocateOffscreenBuffer() {
if (mOffscreenBuffer != null && mOffscreenBuffer.getWidth() == mOffscreenWidth
&& mOffscreenBuffer.getHeight() == mOffscreenHeight) {
return;
}
freeOffscreenBuffer();
mOffscreenBuffer = Bitmap.createBitmap(
mOffscreenWidth, mOffscreenHeight, Bitmap.Config.ARGB_8888);
mOffscreenCanvas.setBitmap(mOffscreenBuffer);
mOffscreenCanvas.translate(0, mOffscreenOffsetY);
}
private boolean drawGestureTrails(final Canvas offscreenCanvas, final Paint paint,
final Rect dirtyRect) {
// Clear previous dirty rectangle.
if (!dirtyRect.isEmpty()) {
paint.setColor(Color.TRANSPARENT);
paint.setStyle(Paint.Style.FILL);
offscreenCanvas.drawRect(dirtyRect, paint);
}
dirtyRect.setEmpty();
boolean needsUpdatingGestureTrail = false;
// Draw gesture trails to offscreen buffer.
synchronized (mGestureTrails) {
// Trails count == fingers count that have ever been active.
final int trailsCount = mGestureTrails.size();
for (int index = 0; index < trailsCount; index++) {
final GestureTrail trail = mGestureTrails.valueAt(index);
needsUpdatingGestureTrail |= trail.drawGestureTrail(offscreenCanvas, paint,
mGestureTrailBoundsRect, mGestureTrailParams);
// {@link #mGestureTrailBoundsRect} has bounding box of the trail.
dirtyRect.union(mGestureTrailBoundsRect);
}
}
return needsUpdatingGestureTrail;
}
/**
* Draws the preview
* @param canvas The canvas where the preview is drawn.
*/
@Override
public void drawPreview(final Canvas canvas) {
if (!isPreviewEnabled()) {
return;
}
mayAllocateOffscreenBuffer();
// Draw gesture trails to offscreen buffer.
final boolean needsUpdatingGestureTrail = drawGestureTrails(
mOffscreenCanvas, mGesturePaint, mDirtyRect);
if (needsUpdatingGestureTrail) {
mDrawingHandler.postUpdateGestureTrailPreview();
}
// Transfer offscreen buffer to screen.
if (!mDirtyRect.isEmpty()) {
mOffscreenSrcRect.set(mDirtyRect);
mOffscreenSrcRect.offset(0, mOffscreenOffsetY);
canvas.drawBitmap(mOffscreenBuffer, mOffscreenSrcRect, mDirtyRect, null);
// Note: Defer clearing the dirty rectangle here because we will get cleared
// rectangle on the canvas.
}
}
/**
* Set the position of the preview.
* @param tracker The new location of the preview is based on the points in PointerTracker.
*/
@Override
public void setPreviewPosition(final PointerTracker tracker) {
if (!isPreviewEnabled()) {
return;
}
GestureTrail trail;
synchronized (mGestureTrails) {
trail = mGestureTrails.get(tracker.mPointerId);
if (trail == null) {
trail = new GestureTrail();
mGestureTrails.put(tracker.mPointerId, trail);
}
}
trail.addStroke(tracker.getGestureStrokeWithPreviewPoints(), tracker.getDownTime());
// TODO: Should narrow the invalidate region.
getDrawingView().invalidate();
}
}
| slightfoot/android-kioskime | src/com/android/inputmethod/keyboard/internal/GestureTrailsPreview.java | Java | apache-2.0 | 7,627 |
using System.Collections.Generic;
using Amazon.DynamoDBv2.Model;
using AwsTools;
using IndexBackend;
namespace SlideshowCreator.AwsAccess
{
class DynamoDbInsert
{
public const int BATCH_SIZE = 25;
public static Dictionary<string, List<WriteRequest>> GetBatchInserts<T>(List<T> pocoModels) where T : IModel, new()
{
var batchWrite = new Dictionary<string, List<WriteRequest>> { [new T().GetTable()] = new List<WriteRequest>() };
foreach (var pocoModel in pocoModels)
{
var dyamoDbModel = Conversion<T>.ConvertToDynamoDb(pocoModel);
var putRequest = new PutRequest(dyamoDbModel);
var writeRequest = new WriteRequest(putRequest);
batchWrite[new T().GetTable()].Add(writeRequest);
}
return batchWrite;
}
}
}
| timg456789/SlideshowCreator | SlideshowCreator/SlideshowCreator/AwsAccess/DynamoDbInsert.cs | C# | apache-2.0 | 879 |
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright (c) 2013 Oracle and/or its affiliates. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License"). You
* may not use this file except in compliance with the License. You can
* obtain a copy of the License at
* https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html
* or packager/legal/LICENSE.txt. See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file at packager/legal/LICENSE.txt.
*
* GPL Classpath Exception:
* Oracle designates this particular file as subject to the "Classpath"
* exception as provided by Oracle in the GPL Version 2 section of the License
* file that accompanied this code.
*
* Modifications:
* If applicable, add the following below the License Header, with the fields
* enclosed by brackets [] replaced by your own identifying information:
* "Portions Copyright [year] [name of copyright owner]"
*
* Contributor(s):
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
* Version 2] license." If you don't indicate a single choice of license, a
* recipient has the option to distribute your version of this file under
* either the CDDL, the GPL Version 2 or to extend the choice of license to
* its licensees as provided above. However, if you add GPL Version 2 code
* and therefore, elected the GPL Version 2 license, then the option applies
* only if the new code is made subject to such option by the copyright
* holder.
*/
package org.glassfish.admingui.devtests;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.support.ui.Select;
public class JavaMessageServiceTest extends BaseSeleniumTestClass {
public static final String DEFAULT_JMS_HOST = "default_JMS_host";
@Test
public void testJmsService() {
gotoDasPage();
final String timeout = Integer.toString(generateRandomNumber(90));
final String interval = Integer.toString(generateRandomNumber(10));
final String attempts = Integer.toString(generateRandomNumber(10));
clickAndWait("treeForm:tree:configurations:server-config:jmsConfiguration:jmsConfiguration_link");
setFieldValue("propertyForm:propertyContentPage:propertySheet:propertSectionTextField:timeoutProp:Timeout", timeout);
setFieldValue("propertyForm:propertyContentPage:propertySheet:propertSectionTextField:intervalProp:Interval", interval);
setFieldValue("propertyForm:propertyContentPage:propertySheet:propertSectionTextField:attemptsProp:Attempts", attempts);
Select select = new Select(driver.findElement(By.id("propertyForm:propertyContentPage:propertySheet:propertSectionTextField:behaviorProp:Behavior")));
select.selectByVisibleText("priority");
int count = addTableRow("propertyForm:propertyContentPage:basicTable", "propertyForm:propertyContentPage:basicTable:topActionsGroup1:addSharedTableButton");
sleep(500);
setFieldValue("propertyForm:propertyContentPage:basicTable:rowGroup1:0:col2:col1St", "property" + generateRandomString());
sleep(500);
setFieldValue("propertyForm:propertyContentPage:basicTable:rowGroup1:0:col3:col1St", "value");
clickAndWait("propertyForm:propertyContentPage:topButtons:saveButton");
assertTrue(isElementSaveSuccessful("label_sun4","New values successfully saved."));
gotoDasPage();
clickAndWait("treeForm:tree:configurations:server-config:jmsConfiguration:jmsConfiguration_link");
assertEquals(timeout, getValue("propertyForm:propertyContentPage:propertySheet:propertSectionTextField:timeoutProp:Timeout", "value"));
assertEquals(interval, getValue("propertyForm:propertyContentPage:propertySheet:propertSectionTextField:intervalProp:Interval", "value"));
assertEquals(attempts, getValue("propertyForm:propertyContentPage:propertySheet:propertSectionTextField:attemptsProp:Attempts", "value"));
assertTableRowCount("propertyForm:propertyContentPage:basicTable", count);
//delete the property used to test
clickByIdAction("propertyForm:propertyContentPage:basicTable:_tableActionsTop:_selectMultipleButton:_selectMultipleButton_image");
clickByIdAction("propertyForm:propertyContentPage:basicTable:topActionsGroup1:button1");
waitforBtnDisable("propertyForm:propertyContentPage:basicTable:topActionsGroup1:button1");
clickAndWait("propertyForm:propertyContentPage:topButtons:saveButton");
assertTrue(isElementSaveSuccessful("label_sun4","New values successfully saved."));
}
@Test
public void testJmsHosts() {
gotoDasPage();
String hostText = "host" + generateRandomString();
String host = "somemachine" + generateRandomNumber(1000);
String port = Integer.toString(generateRandomNumber(32768));
clickAndWait("treeForm:tree:configurations:server-config:jmsConfiguration:jmsHosts:jmsHosts_link");
clickAndWait("propertyForm:configs:topActionsGroup1:newButton");
setFieldValue("propertyForm:propertySheet:propertSectionTextField:JmsHostTextProp:JmsHostText", hostText);
setFieldValue("propertyForm:propertySheet:propertSectionTextField:HostProp:Host", host);
setFieldValue("propertyForm:propertySheet:propertSectionTextField:PortProp:Port", port);
setFieldValue("propertyForm:propertySheet:propertSectionTextField:AdminUserProp:AdminUser", "admin");
setFieldValue("propertyForm:propertySheet:propertSectionTextField:newPasswordProp:NewPassword", "admin");
setFieldValue("propertyForm:propertySheet:propertSectionTextField:confirmPasswordProp:ConfirmPassword", "admin");
clickAndWait("propertyForm:propertyContentPage:topButtons:newButton");
String prefix = getTableRowByValue("propertyForm:configs", hostText, "colName");
assertEquals(hostText, getText(prefix + "colName:link"));
String clickId = prefix + "colName:link";
clickByIdAction(clickId);
assertEquals(host, getValue("propertyForm:propertySheet:propertSectionTextField:HostProp:Host", "value"));
clickAndWait("propertyForm:propertyContentPage:topButtons:cancelButton");
//delete related jms host
String deleteRow = prefix + "col0:select";
clickByIdAction(deleteRow);
clickByIdAction("propertyForm:configs:topActionsGroup1:button1");
closeAlertAndGetItsText();
waitForAlertProcess("modalBody");
}
@Test
public void testJmsHostInNonServerConfig() {
String hostText = "host" + generateRandomString();
String instanceName = "in" + generateRandomString();
final String LINK_HOSTS = "treeForm:tree:configurations:" + instanceName + "-config:jmsConfiguration:jmsHosts:jmsHosts_link";
StandaloneTest sat = new StandaloneTest();
sat.createStandAloneInstance(instanceName);
sat.startInstance(instanceName);
// Create new JMS Host for the standalone instance's config
clickAndWait(LINK_HOSTS);
clickAndWait("propertyForm:configs:topActionsGroup1:newButton");
setFieldValue("propertyForm:propertySheet:propertSectionTextField:JmsHostTextProp:JmsHostText", hostText);
setFieldValue("propertyForm:propertySheet:propertSectionTextField:HostProp:Host", "localhost");
clickAndWait("propertyForm:propertyContentPage:topButtons:newButton");
// Delete the default host for the SA instance
gotoDasPage();
clickAndWait(LINK_HOSTS);
String prefix = getTableRowByValue("propertyForm:configs", DEFAULT_JMS_HOST, "colName");
String deleteRow = prefix + "col0:select";
clickByIdAction(deleteRow);
clickByIdAction("propertyForm:configs:topActionsGroup1:button1");
closeAlertAndGetItsText();
waitForAlertProcess("modalBody");
// Verify that the DAS still has the default JMS Host
gotoDasPage();
clickAndWait("treeForm:tree:configurations:server-config:jmsConfiguration:jmsHosts:jmsHosts_link");
assertEquals(DEFAULT_JMS_HOST, getText(prefix + "colName:link"));
// Delete SA config's new host
gotoDasPage();
clickAndWait(LINK_HOSTS);
String prefix1 = getTableRowByValue("propertyForm:configs", hostText, "colName");
String deleteRow1 = prefix1 + "col0:select";
clickByIdAction(deleteRow1);
clickByIdAction("propertyForm:configs:topActionsGroup1:button1");
closeAlertAndGetItsText();
waitForAlertProcess("modalBody");
sat.deleteAllStandaloneInstances();
}
// //This tests need to be rewrite and retested after the issue has been resolved
// @Test
// public void testJmsPhysicalDestinations() {
// gotoDasPage();
// final String name = "dest" + generateRandomString();
// final String maxUnconsumed = Integer.toString(generateRandomNumber(100));
// final String maxMessageSize = Integer.toString(generateRandomNumber(100));
// final String maxTotalMemory = Integer.toString(generateRandomNumber(100));
// final String maxProducers = Integer.toString(generateRandomNumber(500));
// final String consumerFlowLimit = Integer.toString(generateRandomNumber(5000));
//
// clickAndWait("treeForm:tree:applicationServer:applicationServer_link");
// clickAndWait("propertyForm:serverInstTabs:jmsPhysDest");
// clickAndWait("propertyForm:configs:topActionsGroup1:newButton");
//
// setFieldValue("jmsPhysDestForm:propertySheet:propertSectionTextField:NameTextProp:NameText", name);
// setFieldValue("jmsPhysDestForm:propertySheet:propertSectionTextField:maxNumMsgsProp:maxNumMsgs", maxUnconsumed);
// setFieldValue("jmsPhysDestForm:propertySheet:propertSectionTextField:maxBytesPerMsgProp:maxBytesPerMsg", maxMessageSize);
// setFieldValue("jmsPhysDestForm:propertySheet:propertSectionTextField:maxTotalMsgBytesProp:maxTotalMsgBytes", maxTotalMemory);
// Select select = new Select(driver.findElement(By.id("jmsPhysDestForm:propertySheet:propertSectionTextField:typeProp:type")));
// select.selectByVisibleText("javax.jms.Queue");
// setFieldValue("jmsPhysDestForm:propertySheet:propertSectionTextField:maxNumProducersProp:maxNumProducers", maxProducers);
// setFieldValue("jmsPhysDestForm:propertySheet:propertSectionTextField:consumerFlowLimitProp:consumerFlowLimit", consumerFlowLimit);
// Select select1 = new Select(driver.findElement(By.id("jmsPhysDestForm:propertySheet:propertSectionTextField:useDmqProp:useDmq")));
// select1.selectByVisibleText("false");
// Select select2 = new Select(driver.findElement(By.id("jmsPhysDestForm:propertySheet:propertSectionTextField:validateSchemaProp:validateXMLSchemaEnabled")));
// select2.selectByVisibleText("true");
// clickAndWait("jmsPhysDestForm:propertyContentPage:topButtons:newButton");
//
// String prefix = getTableRowByValue("propertyForm:configs", name, "col1");
// assertEquals(name, getText(prefix + "col1:nameCol"));
//
// String clickId = prefix + "col1:nameCol";
// clickByIdAction(clickId);
//
// assertEquals(maxUnconsumed, getValue("jmsPhysDestForm:propertySheet:propertSectionTextField:maxNumMsgsProp:maxNumMsgs", "value"));
// assertEquals(maxMessageSize, getValue("jmsPhysDestForm:propertySheet:propertSectionTextField:maxBytesPerMsgProp:maxBytesPerMsg", "value"));
// assertEquals(maxTotalMemory, getValue("jmsPhysDestForm:propertySheet:propertSectionTextField:maxTotalMsgBytesProp:maxTotalMsgBytes", "value"));
//
// assertEquals(consumerFlowLimit, getValue("jmsPhysDestForm:propertySheet:propertSectionTextField:consumerFlowLimitProp:consumerFlowLimit", "value"));
// assertEquals("true", getValue("jmsPhysDestForm:propertySheet:propertSectionTextField:validateSchemaProp:validateXMLSchemaEnabled", "value"));
// clickAndWait("jmsPhysDestForm:propertyContentPage:topButtons:cancelButton");
//
// String selectId = prefix + "col0:select";
// clickByIdAction(selectId);;
// clickAndWait("propertyForm:configs:topActionsGroup1:flushButton");
//
// gotoDasPage();
// clickAndWait("treeForm:tree:applicationServer:applicationServer_link");
// clickAndWait("propertyForm:serverInstTabs:jmsPhysDest");
// deleteRow("propertyForm:configs:topActionsGroup1:deleteButton", "propertyForm:configs", name);
// }
@Test
public void testMasterBroker() {
ClusterTest ct = new ClusterTest();
try {
final String FIELD_MASTER_BROKER = "propertyForm:propertyContentPage:propertySheet:propertSectionTextField:maseterBrokerProp:MasterBroker";
String clusterName = "clusterName" + generateRandomString();
ct.deleteAllCluster();
final String instance1 = clusterName + generateRandomString();
final String instance2 = clusterName + generateRandomString();
ct.createCluster(clusterName, instance1, instance2);
final String ELEMENT_JMS_LINK = "treeForm:tree:configurations:" + clusterName + "-config:jmsConfiguration:jmsConfiguration_link";
clickAndWait(ELEMENT_JMS_LINK);
Select select = new Select(driver.findElement(By.id(FIELD_MASTER_BROKER)));
select.selectByVisibleText(instance2);
clickAndWait("propertyForm:propertyContentPage:topButtons:saveButton");
clickAndWait(ELEMENT_JMS_LINK);
assertEquals(instance2, getValue(FIELD_MASTER_BROKER, "value"));
} finally {
ct.deleteAllCluster();
}
}
}
| LvSongping/GLASSFISH_ADMIN_CONSOLE_DEVTESTS | auto-test/src/test/java/org/glassfish/admingui/devtests/JavaMessageServiceTest.java | Java | apache-2.0 | 14,315 |
/** @file
Provide Boot Manager related library APIs.
Copyright (c) 2011 - 2019, Intel Corporation. All rights reserved.<BR>
(C) Copyright 2015-2016 Hewlett Packard Enterprise Development LP<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
**/
#ifndef _UEFI_BOOT_MANAGER_LIB_H_
#define _UEFI_BOOT_MANAGER_LIB_H_
#include <Protocol/DriverHealth.h>
#include <Library/SortLib.h>
//
// Boot Manager load option library functions.
//
//
// Load Option Type
//
typedef enum {
LoadOptionTypeDriver,
LoadOptionTypeSysPrep,
LoadOptionTypeBoot,
LoadOptionTypePlatformRecovery,
LoadOptionTypeMax
} EFI_BOOT_MANAGER_LOAD_OPTION_TYPE;
typedef enum {
LoadOptionNumberMax = 0x10000,
LoadOptionNumberUnassigned = LoadOptionNumberMax
} EFI_BOOT_MANAGER_LOAD_OPTION_NUMBER;
//
// Common structure definition for DriverOption and BootOption
//
typedef struct {
//
// Data read from UEFI NV variables
//
UINTN OptionNumber; // #### numerical value, could be LoadOptionNumberUnassigned
EFI_BOOT_MANAGER_LOAD_OPTION_TYPE OptionType; // LoadOptionTypeBoot or LoadOptionTypeDriver
UINT32 Attributes; // Load Option Attributes
CHAR16 *Description; // Load Option Description
EFI_DEVICE_PATH_PROTOCOL *FilePath; // Load Option Device Path
UINT8 *OptionalData; // Load Option optional data to pass into image
UINT32 OptionalDataSize; // Load Option size of OptionalData
EFI_GUID VendorGuid;
//
// Used at runtime
//
EFI_STATUS Status; // Status returned from boot attempt gBS->StartImage ()
CHAR16 *ExitData; // Exit data returned from gBS->StartImage ()
UINTN ExitDataSize; // Size of ExitData
} EFI_BOOT_MANAGER_LOAD_OPTION;
/**
Returns an array of load options based on the EFI variable
L"BootOrder"/L"DriverOrder" and the L"Boot####"/L"Driver####" variables impled by it.
#### is the hex value of the UINT16 in each BootOrder/DriverOrder entry.
@param LoadOptionCount Returns number of entries in the array.
@param LoadOptionType The type of the load option.
@retval NULL No load options exist.
@retval !NULL Array of load option entries.
**/
EFI_BOOT_MANAGER_LOAD_OPTION *
EFIAPI
EfiBootManagerGetLoadOptions (
OUT UINTN *LoadOptionCount,
IN EFI_BOOT_MANAGER_LOAD_OPTION_TYPE LoadOptionType
);
/**
Free an array of load options returned from EfiBootManagerGetLoadOptions().
@param LoadOptions Pointer to the array of load options to free.
@param LoadOptionCount Number of array entries in LoadOptions.
@return EFI_SUCCESS LoadOptions was freed.
@return EFI_INVALID_PARAMETER LoadOptions is NULL.
**/
EFI_STATUS
EFIAPI
EfiBootManagerFreeLoadOptions (
IN EFI_BOOT_MANAGER_LOAD_OPTION *LoadOptions,
IN UINTN LoadOptionCount
);
/**
Initialize a load option.
@param Option Pointer to the load option to be initialized.
@param OptionNumber Option number of the load option.
@param OptionType Type of the load option.
@param Attributes Attributes of the load option.
@param Description Description of the load option.
@param FilePath Device path of the load option.
@param OptionalData Optional data of the load option.
@param OptionalDataSize Size of the optional data of the load option.
@retval EFI_SUCCESS The load option was initialized successfully.
@retval EFI_INVALID_PARAMETER Option, Description or FilePath is NULL.
**/
EFI_STATUS
EFIAPI
EfiBootManagerInitializeLoadOption (
IN OUT EFI_BOOT_MANAGER_LOAD_OPTION *Option,
IN UINTN OptionNumber,
IN EFI_BOOT_MANAGER_LOAD_OPTION_TYPE OptionType,
IN UINT32 Attributes,
IN CHAR16 *Description,
IN EFI_DEVICE_PATH_PROTOCOL *FilePath,
IN UINT8 *OptionalData,
IN UINT32 OptionalDataSize
);
/**
Free a load option created by EfiBootManagerInitializeLoadOption()
or EfiBootManagerVariableToLoadOption().
@param LoadOption Pointer to the load option to free.
CONCERN: Check Boot#### instead of BootOrder, optimize, spec clarify
@return EFI_SUCCESS LoadOption was freed.
@return EFI_INVALID_PARAMETER LoadOption is NULL.
**/
EFI_STATUS
EFIAPI
EfiBootManagerFreeLoadOption (
IN EFI_BOOT_MANAGER_LOAD_OPTION *LoadOption
);
/**
Initialize the load option from the VariableName.
@param VariableName EFI Variable name which could be Boot#### or
Driver####
@param LoadOption Pointer to the load option to be initialized
@retval EFI_SUCCESS The option was created
@retval EFI_INVALID_PARAMETER VariableName or LoadOption is NULL.
@retval EFI_NOT_FOUND The variable specified by VariableName cannot be found.
**/
EFI_STATUS
EFIAPI
EfiBootManagerVariableToLoadOption (
IN CHAR16 *VariableName,
IN OUT EFI_BOOT_MANAGER_LOAD_OPTION *LoadOption
);
/**
Create the Boot#### or Driver#### variable from the load option.
@param LoadOption Pointer to the load option.
@retval EFI_SUCCESS The variable was created.
@retval Others Error status returned by RT->SetVariable.
**/
EFI_STATUS
EFIAPI
EfiBootManagerLoadOptionToVariable (
IN CONST EFI_BOOT_MANAGER_LOAD_OPTION *LoadOption
);
/**
This function will register the new Boot####, Driver#### or SysPrep#### option.
After the *#### is updated, the *Order will also be updated.
@param Option Pointer to load option to add. If on input
Option->OptionNumber is LoadOptionNumberUnassigned,
then on output Option->OptionNumber is updated to
the number of the new Boot####,
Driver#### or SysPrep#### option.
@param Position Position of the new load option to put in the ****Order variable.
@retval EFI_SUCCESS The *#### have been successfully registered.
@retval EFI_INVALID_PARAMETER The option number exceeds 0xFFFF.
@retval EFI_ALREADY_STARTED The option number of Option is being used already.
Note: this API only adds new load option, no replacement support.
@retval EFI_OUT_OF_RESOURCES There is no free option number that can be used when the
option number specified in the Option is LoadOptionNumberUnassigned.
@return Status codes of gRT->SetVariable ().
**/
EFI_STATUS
EFIAPI
EfiBootManagerAddLoadOptionVariable (
IN OUT EFI_BOOT_MANAGER_LOAD_OPTION *Option,
IN UINTN Position
);
/**
Delete the load option according to the OptionNumber and OptionType.
Only the BootOrder/DriverOrder is updated to remove the reference of the OptionNumber.
@param OptionNumber Option number of the load option.
@param OptionType Type of the load option.
@retval EFI_NOT_FOUND The load option cannot be found.
@retval EFI_SUCCESS The load option was deleted.
**/
EFI_STATUS
EFIAPI
EfiBootManagerDeleteLoadOptionVariable (
IN UINTN OptionNumber,
IN EFI_BOOT_MANAGER_LOAD_OPTION_TYPE OptionType
);
/**
Sort the load options. The DriverOrder/BootOrder variables will be re-created to
reflect the new order.
@param OptionType The type of the load option.
@param CompareFunction The comparator function pointer.
**/
VOID
EFIAPI
EfiBootManagerSortLoadOptionVariable (
IN EFI_BOOT_MANAGER_LOAD_OPTION_TYPE OptionType,
IN SORT_COMPARE CompareFunction
);
/**
Return the index of the load option in the load option array.
The function consider two load options are equal when the
OptionType, Attributes, Description, FilePath and OptionalData are equal.
@param Key Pointer to the load option to be found.
@param Array Pointer to the array of load options to be found.
@param Count Number of entries in the Array.
@retval -1 Key wasn't found in the Array.
@retval 0 ~ Count-1 The index of the Key in the Array.
**/
INTN
EFIAPI
EfiBootManagerFindLoadOption (
IN CONST EFI_BOOT_MANAGER_LOAD_OPTION *Key,
IN CONST EFI_BOOT_MANAGER_LOAD_OPTION *Array,
IN UINTN Count
);
//
// Boot Manager hot key library functions.
//
#pragma pack(1)
///
/// EFI Key Option.
///
typedef struct {
///
/// Specifies options about how the key will be processed.
///
EFI_BOOT_KEY_DATA KeyData;
///
/// The CRC-32 which should match the CRC-32 of the entire EFI_LOAD_OPTION to
/// which BootOption refers. If the CRC-32s do not match this value, then this key
/// option is ignored.
///
UINT32 BootOptionCrc;
///
/// The Boot#### option which will be invoked if this key is pressed and the boot option
/// is active (LOAD_OPTION_ACTIVE is set).
///
UINT16 BootOption;
///
/// The key codes to compare against those returned by the
/// EFI_SIMPLE_TEXT_INPUT and EFI_SIMPLE_TEXT_INPUT_EX protocols.
/// The number of key codes (0-3) is specified by the EFI_KEY_CODE_COUNT field in KeyOptions.
///
EFI_INPUT_KEY Keys[3];
UINT16 OptionNumber;
} EFI_BOOT_MANAGER_KEY_OPTION;
#pragma pack()
/**
Start the hot key service so that the key press can trigger the boot option.
@param HotkeyTriggered Return the waitable event and it will be signaled
when a valid hot key is pressed.
@retval EFI_SUCCESS The hot key service is started.
**/
EFI_STATUS
EFIAPI
EfiBootManagerStartHotkeyService (
IN EFI_EVENT *HotkeyTriggered
);
//
// Modifier for EfiBootManagerAddKeyOptionVariable and EfiBootManagerDeleteKeyOptionVariable
//
#define EFI_BOOT_MANAGER_SHIFT_PRESSED 0x00000001
#define EFI_BOOT_MANAGER_CONTROL_PRESSED 0x00000002
#define EFI_BOOT_MANAGER_ALT_PRESSED 0x00000004
#define EFI_BOOT_MANAGER_LOGO_PRESSED 0x00000008
#define EFI_BOOT_MANAGER_MENU_KEY_PRESSED 0x00000010
#define EFI_BOOT_MANAGER_SYS_REQ_PRESSED 0x00000020
/**
Add the key option.
It adds the key option variable and the key option takes affect immediately.
@param AddedOption Return the added key option.
@param BootOptionNumber The boot option number for the key option.
@param Modifier Key shift state.
@param ... Parameter list of pointer of EFI_INPUT_KEY.
@retval EFI_SUCCESS The key option is added.
@retval EFI_ALREADY_STARTED The hot key is already used by certain key option.
**/
EFI_STATUS
EFIAPI
EfiBootManagerAddKeyOptionVariable (
OUT EFI_BOOT_MANAGER_KEY_OPTION *AddedOption, OPTIONAL
IN UINT16 BootOptionNumber,
IN UINT32 Modifier,
...
);
/**
Delete the Key Option variable and unregister the hot key
@param DeletedOption Return the deleted key options.
@param Modifier Key shift state.
@param ... Parameter list of pointer of EFI_INPUT_KEY.
@retval EFI_SUCCESS The key option is deleted.
@retval EFI_NOT_FOUND The key option cannot be found.
**/
EFI_STATUS
EFIAPI
EfiBootManagerDeleteKeyOptionVariable (
IN EFI_BOOT_MANAGER_KEY_OPTION *DeletedOption, OPTIONAL
IN UINT32 Modifier,
...
);
/**
Register the key option to exit the waiting of the Boot Manager timeout.
Platform should ensure that the continue key option isn't conflict with
other boot key options.
@param Modifier Key shift state.
@param ... Parameter list of pointer of EFI_INPUT_KEY.
@retval EFI_SUCCESS Successfully register the continue key option.
@retval EFI_ALREADY_STARTED The continue key option is already registered.
**/
EFI_STATUS
EFIAPI
EfiBootManagerRegisterContinueKeyOption (
IN UINT32 Modifier,
...
);
/**
Try to boot the boot option triggered by hot key.
**/
VOID
EFIAPI
EfiBootManagerHotkeyBoot (
VOID
);
//
// Boot Manager boot library functions.
//
/**
The function creates boot options for all possible bootable medias in the following order:
1. Removable BlockIo - The boot option only points to the removable media
device, like USB key, DVD, Floppy etc.
2. Fixed BlockIo - The boot option only points to a Fixed blockIo device,
like HardDisk.
3. Non-BlockIo SimpleFileSystem - The boot option points to a device supporting
SimpleFileSystem Protocol, but not supporting BlockIo
protocol.
4. LoadFile - The boot option points to the media supporting
LoadFile protocol.
Reference: UEFI Spec chapter 3.3 Boot Option Variables Default Boot Behavior
The function won't delete the boot option not added by itself.
**/
VOID
EFIAPI
EfiBootManagerRefreshAllBootOption (
VOID
);
/**
Attempt to boot the EFI boot option. This routine sets L"BootCurent" and
signals the EFI ready to boot event. If the device path for the option starts
with a BBS device path a legacy boot is attempted. Short form device paths are
also supported via this rountine. A device path starting with
MEDIA_HARDDRIVE_DP, MSG_USB_WWID_DP, MSG_USB_CLASS_DP gets expaned out
to find the first device that matches. If the BootOption Device Path
fails the removable media boot algorithm is attempted (\EFI\BOOTIA32.EFI,
\EFI\BOOTX64.EFI,... only one file type is tried per processor type)
@param BootOption Boot Option to try and boot.
On return, BootOption->Status contains the boot status:
EFI_SUCCESS BootOption was booted
EFI_UNSUPPORTED BootOption isn't supported.
EFI_NOT_FOUND The BootOption was not found on the system
Others BootOption failed with this error status
**/
VOID
EFIAPI
EfiBootManagerBoot (
IN EFI_BOOT_MANAGER_LOAD_OPTION *BootOption
);
/**
Return the boot option corresponding to the Boot Manager Menu.
It may automatically create one if the boot option hasn't been created yet.
@param BootOption Return the Boot Manager Menu.
@retval EFI_SUCCESS The Boot Manager Menu is successfully returned.
@retval EFI_NOT_FOUND The Boot Manager Menu cannot be found.
@retval others Return status of gRT->SetVariable (). BootOption still points
to the Boot Manager Menu even the Status is not EFI_SUCCESS
and EFI_NOT_FOUND.
**/
EFI_STATUS
EFIAPI
EfiBootManagerGetBootManagerMenu (
EFI_BOOT_MANAGER_LOAD_OPTION *BootOption
);
/**
Get the next possible full path pointing to the load option.
The routine doesn't guarantee the returned full path points to an existing
file, and it also doesn't guarantee the existing file is a valid load option.
BmGetNextLoadOptionBuffer() guarantees.
@param FilePath The device path pointing to a load option.
It could be a short-form device path.
@param FullPath The full path returned by the routine in last call.
Set to NULL in first call.
@return The next possible full path pointing to the load option.
Caller is responsible to free the memory.
**/
EFI_DEVICE_PATH_PROTOCOL *
EFIAPI
EfiBootManagerGetNextLoadOptionDevicePath (
IN EFI_DEVICE_PATH_PROTOCOL *FilePath,
IN EFI_DEVICE_PATH_PROTOCOL *FullPath
);
/**
Get the load option by its device path.
@param FilePath The device path pointing to a load option.
It could be a short-form device path.
@param FullPath Return the full device path of the load option after
short-form device path expanding.
Caller is responsible to free it.
@param FileSize Return the load option size.
@return The load option buffer. Caller is responsible to free the memory.
**/
VOID *
EFIAPI
EfiBootManagerGetLoadOptionBuffer (
IN EFI_DEVICE_PATH_PROTOCOL *FilePath,
OUT EFI_DEVICE_PATH_PROTOCOL **FullPath,
OUT UINTN *FileSize
);
/**
The function enumerates all the legacy boot options, creates them and
registers them in the BootOrder variable.
**/
typedef
VOID
(EFIAPI *EFI_BOOT_MANAGER_REFRESH_LEGACY_BOOT_OPTION) (
VOID
);
/**
The function boots a legacy boot option.
**/
typedef
VOID
(EFIAPI *EFI_BOOT_MANAGER_LEGACY_BOOT) (
IN EFI_BOOT_MANAGER_LOAD_OPTION *BootOption
);
/**
The function registers the legacy boot support capabilities.
@param RefreshLegacyBootOption The function pointer to create all the legacy boot options.
@param LegacyBoot The function pointer to boot the legacy boot option.
**/
VOID
EFIAPI
EfiBootManagerRegisterLegacyBootSupport (
EFI_BOOT_MANAGER_REFRESH_LEGACY_BOOT_OPTION RefreshLegacyBootOption,
EFI_BOOT_MANAGER_LEGACY_BOOT LegacyBoot
);
/**
Return the platform provided boot option description for the controller.
@param Handle Controller handle.
@param DefaultDescription Default boot description provided by core.
@return The callee allocated description string
or NULL if the handler wants to use DefaultDescription.
**/
typedef
CHAR16 *
(EFIAPI *EFI_BOOT_MANAGER_BOOT_DESCRIPTION_HANDLER) (
IN EFI_HANDLE Handle,
IN CONST CHAR16 *DefaultDescription
);
/**
Register the platform provided boot description handler.
@param Handler The platform provided boot description handler
@retval EFI_SUCCESS The handler was registered successfully.
@retval EFI_ALREADY_STARTED The handler was already registered.
@retval EFI_OUT_OF_RESOURCES There is not enough resource to perform the registration.
**/
EFI_STATUS
EFIAPI
EfiBootManagerRegisterBootDescriptionHandler (
IN EFI_BOOT_MANAGER_BOOT_DESCRIPTION_HANDLER Handler
);
//
// Boot Manager connect and disconnect library functions
//
/**
This function will connect all the system driver to controller
first, and then special connect the default console, this make
sure all the system controller available and the platform default
console connected.
**/
VOID
EFIAPI
EfiBootManagerConnectAll (
VOID
);
/**
This function will create all handles associate with every device
path node. If the handle associate with one device path node can not
be created successfully, then still give chance to do the dispatch,
which load the missing drivers if possible.
@param DevicePathToConnect The device path which will be connected, it can be
a multi-instance device path
@param MatchingHandle Return the controller handle closest to the DevicePathToConnect
@retval EFI_SUCCESS All handles associate with every device path node
have been created.
@retval EFI_OUT_OF_RESOURCES There is no resource to create new handles.
@retval EFI_NOT_FOUND Create the handle associate with one device path
node failed.
@retval EFI_SECURITY_VIOLATION The user has no permission to start UEFI device
drivers on the DevicePath.
**/
EFI_STATUS
EFIAPI
EfiBootManagerConnectDevicePath (
IN EFI_DEVICE_PATH_PROTOCOL *DevicePathToConnect,
OUT EFI_HANDLE *MatchingHandle OPTIONAL
);
/**
This function will disconnect all current system handles.
gBS->DisconnectController() is invoked for each handle exists in system handle buffer.
If handle is a bus type handle, all childrens also are disconnected recursively by
gBS->DisconnectController().
**/
VOID
EFIAPI
EfiBootManagerDisconnectAll (
VOID
);
//
// Boot Manager console library functions
//
typedef enum {
ConIn,
ConOut,
ErrOut,
ConInDev,
ConOutDev,
ErrOutDev,
ConsoleTypeMax
} CONSOLE_TYPE;
/**
This function will connect all the console devices base on the console
device variable ConIn, ConOut and ErrOut.
@retval EFI_DEVICE_ERROR All the consoles were not connected due to an error.
@retval EFI_SUCCESS Success connect any one instance of the console
device path base on the variable ConVarName.
**/
EFI_STATUS
EFIAPI
EfiBootManagerConnectAllDefaultConsoles (
VOID
);
/**
This function updates the console variable based on ConVarName. It can
add or remove one specific console device path from the variable
@param ConsoleType ConIn, ConOut, ErrOut, ConInDev, ConOutDev or ErrOutDev.
@param CustomizedConDevicePath The console device path to be added to
the console variable. Cannot be multi-instance.
@param ExclusiveDevicePath The console device path to be removed
from the console variable. Cannot be multi-instance.
@retval EFI_UNSUPPORTED The added device path is the same as a removed one.
@retval EFI_SUCCESS Successfully added or removed the device path from the
console variable.
**/
EFI_STATUS
EFIAPI
EfiBootManagerUpdateConsoleVariable (
IN CONSOLE_TYPE ConsoleType,
IN EFI_DEVICE_PATH_PROTOCOL *CustomizedConDevicePath,
IN EFI_DEVICE_PATH_PROTOCOL *ExclusiveDevicePath
);
/**
Connect the console device base on the variable ConVarName, if
device path of the ConVarName is multi-instance device path, if
anyone of the instances is connected success, then this function
will return success.
@param ConsoleType ConIn, ConOut or ErrOut.
@retval EFI_NOT_FOUND There is not any console devices connected
success
@retval EFI_SUCCESS Success connect any one instance of the console
device path base on the variable ConVarName.
**/
EFI_STATUS
EFIAPI
EfiBootManagerConnectConsoleVariable (
IN CONSOLE_TYPE ConsoleType
);
/**
Query all the children of VideoController and return the device paths of all the
children that support GraphicsOutput protocol.
@param VideoController PCI handle of video controller.
@return Device paths of all the children that support GraphicsOutput protocol.
**/
EFI_DEVICE_PATH_PROTOCOL *
EFIAPI
EfiBootManagerGetGopDevicePath (
IN EFI_HANDLE VideoController
);
/**
Connect the platform active active video controller.
@param VideoController PCI handle of video controller.
@retval EFI_NOT_FOUND There is no active video controller.
@retval EFI_SUCCESS The video controller is connected.
**/
EFI_STATUS
EFIAPI
EfiBootManagerConnectVideoController (
EFI_HANDLE VideoController OPTIONAL
);
//
// Boot Manager driver health library functions.
//
typedef struct {
EFI_DRIVER_HEALTH_PROTOCOL *DriverHealth;
///
/// Driver relative handles
///
EFI_HANDLE DriverHealthHandle;
EFI_HANDLE ControllerHandle;
EFI_HANDLE ChildHandle;
///
/// Driver health messages of the specify Driver
///
EFI_DRIVER_HEALTH_HII_MESSAGE *MessageList;
///
/// HII relative handles
///
EFI_HII_HANDLE HiiHandle;
///
/// Driver Health status
///
EFI_DRIVER_HEALTH_STATUS HealthStatus;
} EFI_BOOT_MANAGER_DRIVER_HEALTH_INFO;
/**
Return all the Driver Health information.
When the cumulative health status of all the controllers managed by the
driver who produces the EFI_DRIVER_HEALTH_PROTOCOL is healthy, only one
EFI_BOOT_MANAGER_DRIVER_HEALTH_INFO entry is created for such
EFI_DRIVER_HEALTH_PROTOCOL instance.
Otherwise, every controller creates one EFI_BOOT_MANAGER_DRIVER_HEALTH_INFO
entry. Additionally every child controller creates one
EFI_BOOT_MANAGER_DRIVER_HEALTH_INFO entry if the driver is a bus driver.
@param Count Return the count of the Driver Health information.
@retval NULL No Driver Health information is returned.
@retval !NULL Pointer to the Driver Health information array.
**/
EFI_BOOT_MANAGER_DRIVER_HEALTH_INFO *
EFIAPI
EfiBootManagerGetDriverHealthInfo (
UINTN *Count
);
/**
Free the Driver Health information array.
@param DriverHealthInfo Pointer to array of the Driver Health information.
@param Count Count of the array.
@retval EFI_SUCCESS The array is freed.
@retval EFI_INVALID_PARAMETER The array is NULL.
**/
EFI_STATUS
EFIAPI
EfiBootManagerFreeDriverHealthInfo (
EFI_BOOT_MANAGER_DRIVER_HEALTH_INFO *DriverHealthInfo,
UINTN Count
);
/**
Process (load and execute) the load option.
@param LoadOption Pointer to the load option.
@retval EFI_INVALID_PARAMETER The load option type is invalid,
or the load option file path doesn't point to a valid file.
@retval EFI_UNSUPPORTED The load option type is of LoadOptionTypeBoot.
@retval EFI_SUCCESS The load option is inactive, or successfully loaded and executed.
**/
EFI_STATUS
EFIAPI
EfiBootManagerProcessLoadOption (
EFI_BOOT_MANAGER_LOAD_OPTION *LoadOption
);
/**
Check whether the VariableName is a valid load option variable name
and return the load option type and option number.
@param VariableName The name of the load option variable.
@param OptionType Return the load option type.
@param OptionNumber Return the load option number.
@retval TRUE The variable name is valid; The load option type and
load option number are returned.
@retval FALSE The variable name is NOT valid.
**/
BOOLEAN
EFIAPI
EfiBootManagerIsValidLoadOptionVariableName (
IN CHAR16 *VariableName,
OUT EFI_BOOT_MANAGER_LOAD_OPTION_TYPE *OptionType OPTIONAL,
OUT UINT16 *OptionNumber OPTIONAL
);
/**
Dispatch the deferred images that are returned from all DeferredImageLoad instances.
@retval EFI_SUCCESS At least one deferred image is loaded successfully and started.
@retval EFI_NOT_FOUND There is no deferred image.
@retval EFI_ACCESS_DENIED There are deferred images but all of them are failed to load.
**/
EFI_STATUS
EFIAPI
EfiBootManagerDispatchDeferredImages (
VOID
);
#endif
| google/google-ctf | third_party/edk2/MdeModulePkg/Include/Library/UefiBootManagerLib.h | C | apache-2.0 | 28,153 |
---
layout: post
title: "java GC 学习(四)"
subtitle: "\"分代垃圾回收\""
date: 2017-2-21 08:00:00
author: "Jht"
header-img: "img/java-bg.jpg"
catalog: true
tags:
- java
- jvm
- GC
---
## stop-the-world
选择哪种GC算法,stop-the-world都是不可避免的。一旦Stop-the-world发生,
除了GC所需的线程外,其他线程都将停止工作GC调优通常就是为了改善stop-the-world的时间。
## 基于的分代理论的垃圾回收
垃圾回收器的创建基于以下两个前提:
- 大多数对象的很快就会变得不可达
- 只有极少数情况会出现旧对象持有新对象的引用
这两条被称为”弱分代假设“。为了证明此假设,在HotSpot VM中物理内存空间被划分为两部分:
新生代(young generate)和老年代(old generation)。
### 新生代
大部分的新创建对象分配在新生代。因为大部分对象很快就会变得不可达,所以它们被分配在新生代,
然后消失不再。当对象从新生代移除时,我们称之为”minor GC“
### 老年代
存活在新生代中但未变为不可达的对象会被复制到老年代。一般来说老年代的内存空间比新生代大,
所以在老年代GC发生的频率较新生代低一些。当对象从老年代被移除时,我们称之为”major GC“(或者full GC)。
#### 方法区
其中存储着类和接口的元信息以及interned的字符串信息。所以这一区域并不是为老年代中存活下来的对象所定义的持久区。
方法区中也会发生GC,这里的GC同样也被称为major GC
#### 如果老年代的对象需要持有新生代对象的引用怎么办?
在老年代中设计了”索引表(card table)“,是一个512字节的数据块。不管何时老年代需要持有新生代对象的引用时,
都会记录到此表中。当新生代中需要执行GC时,通过搜索此表决定新生代的对象是否为GC的目标对象,
从而降低遍历所有老年代对象进行检查的代价。该索引表使用写栅栏(write barrier)进行管理。
wite barrier是一个允许高性能执行minor GC的设备。尽管它会引入一个数据位的开销,
却能带来总体GC时间的大幅降低。
### 新生代的结构
新生代又可分为三个部分:
- 一个Eden区
- 两个Survivor区
对象在三个区域中的存活过程如下:
- 大多数新生对象都被分配在Eden区
- 第一次GC过后Eden中还存活的对象被移到其中一个Survivor区
- 再次GC过程中,Eden中还存活的对象会被移到之前已移入对象的Survivor区
- 一旦该Survivor区域无空间可用时,还存活的对象会从当前Survivor区移到另一个空的Survivor区。而当前Survivor区就会再次置为空状态
- 经过数次在两个Survivor区域移动后还存活的对象最后会被移动到老年代
下图是`Java VisualVm`的`Visual GC`监控图,Spaces包含新生代和老年代。

#### 注意
两个Survivor区域在任何时候必定有一个保持空白。如果同时有数据存在于两个Survivor区或者两个区域的的使用量都是0(空闲的时候有可能),
则意味着你的系统`可能`出现了运行错误。
### 更快的内存分配
在HotSpot VM中,使用了两项技术来实现更快的内存分配:
- 指针碰撞(bump-the-pointer)
- TLABs(Thread-Local Allocation Buffers)
Bump-the-pointer技术会跟踪在Eden上新创建的对象。由于新对象被分配在Eden空间的最上面,
所以后续如果有新对象创建,只需要判断新创建对象的大小是否满足剩余的Eden空间。
如果新对象满足要求,则其会被分配到Eden空间,同样位于Eden的最上面。所以当有新对象创建时,
只需要判断此新对象的大小即可,因此具有更快的内存分配速度。然而,在多线程环境下,
将会有别样的状况。为了满足多个线程在Eden空间上创建对象时的线程安全,不可避免的会引入锁,
因此随着锁竞争的开销,创建对象的性能也大打折扣。在HotSpot中正是通过TLABs解决了多线程问题。
TLABs允许每个线程在Eden上有自己的小片空间,线程只能访问其自己的TLAB区域,
因此bump-the-pointer能通过TLAB在不加锁的情况下完成快速的内存分配。
### 老年代垃圾回收
当老年代数据满时,便会执行老年代垃圾回收。根据GC算法的不同其执行过程也会有所区别,所以当你了解了每种GC的特点后再来理解老年代的垃圾回收就会容易很多。
7种GC类型:


#### Serial GC
参数控制:
- -XX:+UseSerialGC 串行收集器
Serial GC会损耗应用的性能,这种GC是为单核CPU上的桌面应用设计的。
Serial GC适用于CPU核数较少且使用的内存空间较小的场景。
只使用一个线程去回收。新生代、老年代使用串行回收;新生代复制算法、老年代标记-压缩
在老年代,则使用了一种称之为`mark-sweep-compact`的算法。
- 首先该算法需要在老年代中标记出存活着的对象
- 然后从前到后检查堆空间中存活的对象,并保持位置不变(把不再存活的对象清理出堆空间,称为`空间清理`)
- 最后,把存活的对象移到堆空间的前面部分以保持已使用的堆空间的连续性,从而把堆空间分为两部分:有对象的和无对象的(称为`空间压缩`)

#### ParNew GC
参数控制:
- -XX:+UseParNewGC ParNew收集器
- -XX:ParallelGCThreads 限制线程数量
ParNew收集器其实就是Serial收集器的多线程版本。新生代并行,老年代串行;新生代复制算法、老年代标记-压缩

#### Parallel GC
参数控制:
- -XX:+UseParallelGC 使用Parallel收集器
Parallel Scavenge收集器类似ParNew收集器,Parallel收集器更关注系统的吞吐量。
可以通过参数来打开自适应调节策略,虚拟机会根据当前系统的运行情况收集性能监控信息,
动态调整这些参数以提供最合适的停顿时间或最大的吞吐量;也可以通过参数控制GC的时间不大于多少毫秒或者比例;
新生代并行,老年代串行;新生代复制算法、老年代标记-压缩,Parallel GC又被称为`高吞吐GC(throughput GC)`
#### Parallel Old GC
- 参数控制: -XX:+UseParallelOldGC 使用Parallel收集器+ 老年代并行
Parallel Old是Parallel Scavenge收集器的老年代版本,使用多线程和标记-压缩算法。
#### CMS GC
- 参数控制:
- -XX:+UseConcMarkSweepGC 使用CMS收集器
- -XX:+ UseCMSCompactAtFullCollection Full GC后,进行一次碎片整理;整理过程是独占的,会引起停顿时间变长
- -XX:+CMSFullGCsBeforeCompaction 设置进行几次Full GC后,进行一次碎片整理
- -XX:ParallelCMSThreads 设定CMS的线程数量(一般情况约等于可用CPU数量)
CMS(Concurrent Mark Sweep)收集器是一种以获取最短回收停顿时间为目标的收集器。
目前很大一部分的Java应用都集中在互联网站或B/S系统的服务端上,这类应用尤其重视服务的响应速度,
希望系统停顿时间最短,以给用户带来较好的体验。
从名字(包含“Mark Sweep”)上就可以看出CMS收集器是基于“标记-清除”算法实现的,
它的运作过程相对于前面几种收集器来说要更复杂一些,整个过程分为4个步骤,包括:
- 初始标记(CMS initial mark)
- 并发标记(CMS concurrent mark)
- 重新标记(CMS remark)
- 并发清除(CMS concurrent sweep)
其中初始标记、重新标记这两个步骤仍然需要“Stop The World”。初始标记仅仅只是标记一下GC Roots能直接关联到的对象,
速度很快,并发标记阶段就是进行GC Roots Tracing的过程,而重新标记阶段则是为了修正并发标记期间,
因用户程序继续运作而导致标记产生变动的那一部分对象的标记记录,这个阶段的停顿时间一般会比初始标记阶段稍长一些,
但远比并发标记的时间短。
由于整个过程中耗时最长的并发标记和并发清除过程中,收集器线程都可以与用户线程一起工作,
所以总体上来说,CMS收集器的内存回收过程是与用户线程一起并发地执行。老年代收集器(新生代使用ParNew)

#### G1 GC
G1是目前技术发展的最前沿成果之一,HotSpot开发团队赋予它的使命是未来可以替换掉CMS收集器。
与CMS收集器相比G1收集器有以下特点:
- 1. 空间整合,G1收集器采用标记整理算法,不会产生内存空间碎片。分配大对象时不会因为无法找到连续空间而提前触发下一次GC。
- 2. 可预测停顿,这是G1的另一大优势,降低停顿时间是G1和CMS的共同关注点,但G1除了追求低停顿外,还能建立可预测的停顿时间模型,能让使用者明确指定在一个长度为N毫秒的时间片段内,消耗在垃圾收集上的时间不得超过N毫秒,这几乎已经是实时Java(RTSJ)的垃圾收集器的特征了。
上面提到的垃圾收集器,收集的范围都是整个新生代或者老年代,而G1不再是这样。使用G1收集器时,
Java堆的内存布局与其他收集器有很大差别,它将整个Java堆划分为多个大小相等的独立区域(Region),
虽然还保留有新生代和老年代的概念,但新生代和老年代不再是物理隔阂了,它们都是一部分(可以不连续)Region的集合。
##### 新生代收集步骤
- 1、G1的新生代收集跟ParNew类似,当新生代占用达到一定比例的时候,开始出发收集。

- 2、下图被圈起的绿色部分为新生代的区域(region),经过Young GC后存活的对象被复制到一个或者多个区域空闲中,这些被填充的区域将是新的新生代;当新生代对象的年龄(逃逸过一次Young GC年龄增加1)已经达到某个阈值(ParNew默认15),被复制到老年代的区域中。
回收过程是停顿的(STW,Stop-The-Word);回收完成之后根据Young GC的统计信息调整Eden和Survivor的大小,有助于合理利用内存,提高回收效率。回收的过程多个回收线程并发收集。

##### 老年代收集步骤
和CMS类似,G1收集器收集老年代对象会有短暂停顿。
- 1、标记阶段,首先初始标记(Initial-Mark),这个阶段是停顿的(Stop the World Event),并且会触发一次普通Mintor GC。对应GC log:GC pause (young) (inital-mark)
- 2、Root Region Scanning,程序运行过程中会回收survivor区(存活到老年代),这一过程必须在young GC之前完成。
- 3、Concurrent Marking,在整个堆中进行并发标记(和应用程序并发执行),此过程可能被young GC中断。在并发标记阶段,若发现区域对象中的所有对象都是垃圾,那个这个区域会被立即回收(图中打X)。同时,并发标记过程中,会计算每个区域的对象活性(区域中存活对象的比例)。

- 4、Remark, 再标记,会有短暂停顿(STW)。再标记阶段是用来收集 并发标记阶段 产生新的垃圾(并发阶段和应用程序一同运行);G1中采用了比CMS更快的初始快照算法:snapshot-at-the-beginning (SATB)。
- 5、Copy/Clean up,多线程清除失活对象,会有STW。G1将回收区域的存活对象拷贝到新区域,清除Remember Sets,并发清空回收区域并把它返回到空闲区域链表中。

- 6、复制/清除过程后。回收区域的活性对象已经被集中回收到深蓝色和深绿色区域。

### 常用GC组合
| 新生代GC | 老年代GC | 描述 |
| ------------- |:-------------:| -----:|
|Serial | Serial Old |Serial和Serial Old都是单线程进行GC,GC时暂停所有应用线程。|
| ParNew | CMS | 使用-XX:+UseParNewGC选项来开启。ParNew是Serial的并行版本,可以指定GC线程数,默认GC线程数为CPU的数量。可以使用-XX:ParallelGCThreads选项指定GC的线程数。
如果指定了选项-XX:+UseConcMarkSweepGC选项,则新生代默认使用ParNew GC策略。 |
|ParNew| Serial Old | 使用-XX:+UseParNewGC选项来开启。新生代使用ParNew GC策略,年老代默认使用Serial Old GC策略。 |
|Parallel Scavenge| Serial Old | Parallel Scavenge策略主要是关注一个可控的吞吐量:应用程序运行时间 / (应用程序运行时间 + GC时间),可见这会使得CPU的利用率尽可能的高,适用于后台持久运行的应用程序,而不适用于交互较多的应用程序。 |
|Parallel Scavenge| Parallel Old | Parallel Old是Serial Old的并行版本 |
|G1GC| G1GC | XX:+UnlockExperimentalVMOptions -XX:+UseG1GC #开启<br> -XX:MaxGCPauseMillis =50 #暂停时间目标<br> -XX:GCPauseIntervalMillis =200 #暂停间隔目标<br> -XX:+G1YoungGenSize=512m #年轻代大小<br> -XX:SurvivorRatio=6 #幸存区比例 |
### 参考资料
[理解Java垃圾回收](http://www.codeceo.com/article/java-gc-1.html)
[GC算法 垃圾收集器](http://www.cnblogs.com/ityouknow/p/5614961.html) | jianghaitao1221/jianghaitao1221.github.com | _posts/2017-2-21-jvm-4.md | Markdown | apache-2.0 | 14,046 |
/*
* 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 code was generated by https://github.com/googleapis/google-api-java-client-services/
* Modify at your own risk.
*/
package com.google.api.services.dialogflow.v3beta1.model;
/**
* Metadata for a ConversationDatasets.ImportConversationData operation.
*
* <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is
* transmitted over HTTP when working with the Dialogflow API. For a detailed explanation see:
* <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a>
* </p>
*
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public final class GoogleCloudDialogflowV2ImportConversationDataOperationMetadata extends com.google.api.client.json.GenericJson {
/**
* The resource name of the imported conversation dataset. Format:
* `projects//locations//conversationDatasets/`
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String conversationDataset;
/**
* Timestamp when import conversation data request was created. The time is measured on server
* side.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private String createTime;
/**
* Partial failures are failures that don't fail the whole long running operation, e.g. single
* files that couldn't be read.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<GoogleRpcStatus> partialFailures;
/**
* The resource name of the imported conversation dataset. Format:
* `projects//locations//conversationDatasets/`
* @return value or {@code null} for none
*/
public java.lang.String getConversationDataset() {
return conversationDataset;
}
/**
* The resource name of the imported conversation dataset. Format:
* `projects//locations//conversationDatasets/`
* @param conversationDataset conversationDataset or {@code null} for none
*/
public GoogleCloudDialogflowV2ImportConversationDataOperationMetadata setConversationDataset(java.lang.String conversationDataset) {
this.conversationDataset = conversationDataset;
return this;
}
/**
* Timestamp when import conversation data request was created. The time is measured on server
* side.
* @return value or {@code null} for none
*/
public String getCreateTime() {
return createTime;
}
/**
* Timestamp when import conversation data request was created. The time is measured on server
* side.
* @param createTime createTime or {@code null} for none
*/
public GoogleCloudDialogflowV2ImportConversationDataOperationMetadata setCreateTime(String createTime) {
this.createTime = createTime;
return this;
}
/**
* Partial failures are failures that don't fail the whole long running operation, e.g. single
* files that couldn't be read.
* @return value or {@code null} for none
*/
public java.util.List<GoogleRpcStatus> getPartialFailures() {
return partialFailures;
}
/**
* Partial failures are failures that don't fail the whole long running operation, e.g. single
* files that couldn't be read.
* @param partialFailures partialFailures or {@code null} for none
*/
public GoogleCloudDialogflowV2ImportConversationDataOperationMetadata setPartialFailures(java.util.List<GoogleRpcStatus> partialFailures) {
this.partialFailures = partialFailures;
return this;
}
@Override
public GoogleCloudDialogflowV2ImportConversationDataOperationMetadata set(String fieldName, Object value) {
return (GoogleCloudDialogflowV2ImportConversationDataOperationMetadata) super.set(fieldName, value);
}
@Override
public GoogleCloudDialogflowV2ImportConversationDataOperationMetadata clone() {
return (GoogleCloudDialogflowV2ImportConversationDataOperationMetadata) super.clone();
}
}
| googleapis/google-api-java-client-services | clients/google-api-services-dialogflow/v3beta1/1.31.0/com/google/api/services/dialogflow/v3beta1/model/GoogleCloudDialogflowV2ImportConversationDataOperationMetadata.java | Java | apache-2.0 | 4,520 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.