code
stringlengths 3
1.01M
| repo_name
stringlengths 5
116
| path
stringlengths 3
311
| language
stringclasses 30
values | license
stringclasses 15
values | size
int64 3
1.01M
|
|---|---|---|---|---|---|
<?php
class User{
public $userId=0;
public $userCName='';
public $userPass='';
public $userEmail='';
public $userRealName='';
public function setUserId($userId){
$this->userId=$userId;
}
public function getUserId(){
return $this->userId;
}
public function setUserCName($userCName){
$this->userCName=userCName;
}
public function getUserCName(){
return $this->userCName;
}
public function setUserPass($userPass){
$this->userPass=$userPass;
}
public function getUserPass(){
return $this->userPass;
}
public function setUserEmail($userEmail){
$this->userEmail=$userEmail;
}
public function getUserEmail(){
return $this->userEmail;
}
public function setUserRealName($userRealName){
$this->userRealName=$userRealName;
}
public function getUserRealName(){
return $this->userRealName;
}
}
?>
|
gemineses/gfg
|
mvc/model/obj/user.php
|
PHP
|
apache-2.0
| 867
|
<?php
/**
* Created by JetBrains PhpStorm.
* User: nmeegama
* Date: 2/3/14
* Time: 10:58 AM
* To change this template use File | Settings | File Templates.
*/
namespace RedLink;
interface IData {
const URI = "uri";
const PATH = "data";
const RESOURCE = "resource";
const SPARQL = "sparql";
const SELECT = "select";
const QUERY = "query";
const UPDATE = "update";
const LDPATH = "ldpath";
/**
* @param $data
* @param string $format
* @param string $dataset
* @param bool $cleanBefore
* @return mixed
*/
public function importDataset($data, $format = '', $dataset = '', $cleanBefore = FALSE);
/**
* @param $dataset
* @return mixed
*/
public function exportDataset($dataset);
/**
* @param $dataset
* @return mixed
*/
public function cleanDataset($dataset);
/**
* @param $resource
* @param string $dataset
* @return mixed
*/
public function getRescouce($resource, $dataset = '');
/**
* @param $resource
* @param $data
* @param $dataset
* @param bool $cleanBefore
* @return mixed
*/
public function importResource($resource, $data, $dataset, $cleanBefore = FALSE);
/**
* @param $resouce
* @param $dataset
* @return mixed
*/
public function deleteResource($resouce, $dataset);
/**
* @param $query
* @param string $dataset
* @return mixed
*/
public function sparqlSelect($query, $dataset = '');
/**
* @param $query
* @param $dataset
* @return mixed
*/
public function sparqlUpdate($query, $dataset);
/**
* @param $uri
* @param $program
* @param string $dataset
* @return mixed
*/
public function ldpath($uri, $program, $dataset = '');
}
|
redlink-gmbh/redlink-php-sdk
|
src/RedLink/IData.php
|
PHP
|
apache-2.0
| 1,720
|
class Solution {
public:
int getSum(int a, int b) {
while(b) {
int x=a^b; // 位异或实现不进位的位加
int y=(a&b)<<1; // 位与 右移1 实现进位
a=x,b=y;
}
return a;
}
};
|
jlygit/leetcode-oj
|
algorithms/sum-of-two-integers.cpp
|
C++
|
apache-2.0
| 262
|
import tests from "../../support/accessibility/a11y-utils";
tests(0, 150);
|
Sage/carbon
|
cypress/integration/accessibility/a11y-first-part.test.js
|
JavaScript
|
apache-2.0
| 76
|
package com.baidu.unbiz.dsp.config;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* @author zhangxu
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath*:applicationContext.xml"})
public class YamlTest implements ApplicationContextAware {
@Autowired
@Qualifier("yamlProperties")
private Properties yamlProperties;
private ApplicationContext ctx;
@Test
public void testConfig() {
//Map(不能直接注入@Autowired Map)
//请参考 Map依赖注入(http://jinnianshilongnian.iteye.com/blog/1989379)
Map<String, Object> yamlMap = ctx.getBean("yamlMap", Map.class);
//需要snakeyaml 该功能是从spring-boot引入的
Map<String, Object> env = (Map<String, Object>) yamlMap.get("env");
Map<String, Object> one = (Map<String, Object>) env.get("one");
Assert.assertEquals("neo", one.get("name"));
List<Map<String, Object>> two = (List) env.get("two");
Assert.assertEquals(1, two.get(0).get("a"));
Assert.assertEquals("3", two.get(1).get("c"));
Assert.assertEquals(null, env.get("three"));
//Properties
Assert.assertEquals("neo", yamlProperties.getProperty("env.one.name"));
//getProperty如果返回的数据时非String的则返回null
Assert.assertEquals(1, yamlProperties.get("env.two[0].a"));
Assert.assertEquals("3", yamlProperties.getProperty("env.two[1].c"));
Assert.assertEquals("", yamlProperties.getProperty("env.three"));
}
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.ctx = applicationContext;
}
}
|
neoremind/spring4-project-archetype
|
src/test/java/com/baidu/unbiz/dsp/config/YamlTest.java
|
Java
|
apache-2.0
| 2,236
|
#
# Copyright 2021 Centreon (http://www.centreon.com/)
#
# Centreon is a full-fledged industry-strength solution that meets
# the needs in IT infrastructure and application monitoring for
# service performance.
#
# 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 network::citrix::netscaler::snmp::mode::vserverstatus;
use base qw(centreon::plugins::templates::counter);
use strict;
use warnings;
use Digest::MD5 qw(md5_hex);
sub set_counters {
my ($self, %options) = @_;
$self->{maps_counters_type} = [
{ name => 'vservers', type => 1, cb_prefix_output => 'prefix_vservers_output', message_multiple => 'All Virtual Servers are ok' }
];
$self->{maps_counters}->{vservers} = [
{ label => 'status', threshold => 0, set => {
key_values => [ { name => 'state' } ],
closure_custom_output => $self->can('custom_status_output'),
closure_custom_perfdata => sub { return 0; },
closure_custom_threshold_check => $self->can('custom_threshold_output')
}
},
{ label => 'health', nlabel => 'vserver.health.percentage', set => {
key_values => [ { name => 'health' }, { name => 'display' } ],
output_template => 'Health: %.2f %%', output_error_template => 'Health: %s',
perfdatas => [
{ label => 'health', template => '%.2f',
unit => '%', min => 0, max => 100, label_extra_instance => 1, instance_use => 'display' }
]
}
},
{ label => 'in-traffic', nlabel => 'vserver.traffic.in.bitspersecond', set => {
key_values => [ { name => 'in', per_second => 1 }, { name => 'display' } ],
output_template => 'Traffic In: %s %s/s',
output_change_bytes => 2,
perfdatas => [
{ label => 'traffic_in', template => '%.2f',
min => 0, unit => 'b/s', label_extra_instance => 1, instance_use => 'display' }
]
}
},
{ label => 'out-traffic', nlabel => 'vserver.traffic.out.bitspersecond', set => {
key_values => [ { name => 'out', per_second => 1 }, { name => 'display' } ],
output_template => 'Traffic Out: %s %s/s',
output_change_bytes => 2,
perfdatas => [
{ label => 'traffic_out', template => '%.2f',
min => 0, unit => 'b/s', label_extra_instance => 1, instance_use => 'display' }
]
}
},
{ label => 'clients', nlabel => 'vserver.connections.client.count', set => {
key_values => [ { name => 'clients', diff => 1 }, { name => 'display' } ],
output_template => 'Total Client Connections : %s',
perfdatas => [
{ label => 'clients', template => '%s',
min => 0, label_extra_instance => 1, instance_use => 'display' }
]
}
},
{ label => 'servers', nlabel => 'vserver.connections.server.count', set => {
key_values => [ { name => 'servers', diff => 1 }, { name => 'display' } ],
output_template => 'Total Server Connections : %s',
perfdatas => [
{ label => 'servers', template => '%s',
min => 0, label_extra_instance => 1, instance_use => 'display' }
]
}
}
];
}
sub prefix_vservers_output {
my ($self, %options) = @_;
return "Virtual Server '" . $options{instance_value}->{display} . "' ";
}
my $overload_th = {};
my $thresholds = {
vs => [
['unknown', 'UNKNOWN'],
['down|outOfService|transitionToOutOfService|transitionToOutOfServiceDown', 'CRITICAL'],
['up', 'OK'],
],
};
sub get_severity {
my (%options) = @_;
my $status = 'UNKNOWN'; # default
if (defined($overload_th->{$options{section}})) {
foreach (@{$overload_th->{$options{section}}}) {
if ($options{value} =~ /$_->{filter}/i) {
$status = $_->{status};
return $status;
}
}
}
foreach (@{$thresholds->{$options{section}}}) {
if ($options{value} =~ /$$_[0]/i) {
$status = $$_[1];
return $status;
}
}
return $status;
}
sub custom_threshold_output {
my ($self, %options) = @_;
return get_severity(section => 'vs', value => $self->{result_values}->{state});
}
sub custom_status_output {
my ($self, %options) = @_;
return 'State : ' . $self->{result_values}->{state};
}
sub new {
my ($class, %options) = @_;
my $self = $class->SUPER::new(package => __PACKAGE__, %options, statefile => 1);
bless $self, $class;
$options{options}->add_options(arguments => {
'filter-name:s' => { name => 'filter_name' },
'filter-type:s' => { name => 'filter_type' },
'force-counters64' => { name => 'force_counters64' },
'threshold-overload:s@' => { name => 'threshold_overload' }
});
return $self;
}
sub check_options {
my ($self, %options) = @_;
$self->SUPER::check_options(%options);
foreach my $val (@{$self->{option_results}->{threshold_overload}}) {
if ($val !~ /^(.*?),(.*)$/) {
$self->{output}->add_option_msg(short_msg => "Wrong threshold-overload option '" . $val . "'.");
$self->{output}->option_exit();
}
my ($section, $status, $filter) = ('vs', $1, $2);
if ($self->{output}->is_litteral_status(status => $status) == 0) {
$self->{output}->add_option_msg(short_msg => "Wrong threshold-overload status '" . $val . "'.");
$self->{output}->option_exit();
}
$overload_th->{$section} = [] if (!defined($overload_th->{$section}));
push @{$overload_th->{$section}}, {filter => $filter, status => $status};
}
}
my %map_vs_type = (
0 => 'unknown',
1 => 'loadbalancing',
2 => 'loadbalancinggroup',
3 => 'sslvpn',
4 => 'contentswitching',
5 => 'cacheredirection',
);
my %map_vs_status = (
1 => 'down',
2 => 'unknown',
3 => 'busy',
4 => 'outOfService',
5 => 'transitionToOutOfService',
7 => 'up',
8 => 'transitionToOutOfServiceDown',
);
my $mapping = {
vsvrState => { oid => '.1.3.6.1.4.1.5951.4.1.3.1.1.5', map => \%map_vs_status },
vsvrFullName => { oid => '.1.3.6.1.4.1.5951.4.1.3.1.1.59' },
vsvrEntityType => { oid => '.1.3.6.1.4.1.5951.4.1.3.1.1.64', map => \%map_vs_type },
};
my $mapping2 = {
vsvrTotalRequestBytesLow => { oid => '.1.3.6.1.4.1.5951.4.1.3.1.1.13' },
vsvrTotalRequestBytesHigh => { oid => '.1.3.6.1.4.1.5951.4.1.3.1.1.14' },
vsvrTotalResponseBytesLow => { oid => '.1.3.6.1.4.1.5951.4.1.3.1.1.17' },
vsvrTotalResponseBytesHigh => { oid => '.1.3.6.1.4.1.5951.4.1.3.1.1.18' },
vsvrTotalRequestBytes => { oid => '.1.3.6.1.4.1.5951.4.1.3.1.1.31' },
vsvrTotalResponseBytes => { oid => '.1.3.6.1.4.1.5951.4.1.3.1.1.33' },
vsvrTotalClients => { oid => '.1.3.6.1.4.1.5951.4.1.3.1.1.56' },
vsvrHealth => { oid => '.1.3.6.1.4.1.5951.4.1.3.1.1.62' },
vsvrTotalServers => { oid => '.1.3.6.1.4.1.5951.4.1.3.1.1.65' },
};
sub manage_selection {
my ($self, %options) = @_;
my $snmp_result = $options{snmp}->get_multiple_table(
oids => [
{ oid => $mapping->{vsvrFullName}->{oid} },
{ oid => $mapping->{vsvrState}->{oid} },
{ oid => $mapping->{vsvrEntityType}->{oid} }
],
return_type => 1,
nothing_quit => 1
);
$self->{vservers} = {};
foreach my $oid (keys %{$snmp_result}) {
next if ($oid !~ /^$mapping->{vsvrFullName}->{oid}\.(.*)$/);
my $instance = $1;
my $result = $options{snmp}->map_instance(mapping => $mapping, results => $snmp_result, instance => $instance);
if (defined($self->{option_results}->{filter_type}) && $self->{option_results}->{filter_type} ne '' &&
$result->{vsvrEntityType} !~ /$self->{option_results}->{filter_type}/) {
$self->{output}->output_add(long_msg => "skipping Virtual Server '" . $result->{vsvrFullName} . "'.", debug => 1);
next;
}
if (defined($self->{option_results}->{filter_name}) && $self->{option_results}->{filter_name} ne '' &&
$result->{vsvrFullName} !~ /$self->{option_results}->{filter_name}/) {
$self->{output}->output_add(long_msg => "skipping Virtual Server '" . $result->{vsvrFullName} . "'.", debug => 1);
next;
}
$self->{vservers}->{$instance} = { display => $result->{vsvrFullName}, state => $result->{vsvrState} };
}
if (scalar(keys %{$self->{vservers}}) <= 0) {
$self->{output}->add_option_msg(short_msg => "No virtual server found.");
$self->{output}->option_exit();
}
$options{snmp}->load(
oids => defined($self->{option_results}->{force_counters64}) ? [
$mapping2->{vsvrTotalRequestBytes}->{oid}, $mapping2->{vsvrTotalResponseBytes}->{oid},
$mapping2->{vsvrTotalClients}->{oid}, $mapping2->{vsvrHealth}->{oid}, $mapping2->{vsvrTotalServers}->{oid}
] : [
$mapping2->{vsvrTotalRequestBytesLow}->{oid}, $mapping2->{vsvrTotalRequestBytesHigh}->{oid},
$mapping2->{vsvrTotalResponseBytesLow}->{oid}, $mapping2->{vsvrTotalResponseBytesHigh}->{oid},
$mapping2->{vsvrTotalRequestBytes}->{oid}, $mapping2->{vsvrTotalResponseBytes}->{oid},
$mapping2->{vsvrTotalClients}->{oid}, $mapping2->{vsvrHealth}->{oid}, $mapping2->{vsvrTotalServers}->{oid}
],
instances => [keys %{$self->{vservers}}], instance_regexp => '^(.*)$'
);
$snmp_result = $options{snmp}->get_leef(nothing_quit => 1);
foreach (keys %{$self->{vservers}}) {
my $result = $options{snmp}->map_instance(mapping => $mapping2, results => $snmp_result, instance => $_);
$self->{vservers}->{$_}->{out} = defined($result->{vsvrTotalResponseBytes}) ? $result->{vsvrTotalResponseBytes} * 8 :
(($result->{vsvrTotalResponseBytesHigh} << 32) + $result->{vsvrTotalResponseBytesLow}) * 8;
$self->{vservers}->{$_}->{in} = defined($result->{vsvrTotalRequestBytes}) ? $result->{vsvrTotalRequestBytes} * 8 :
(($result->{vsvrTotalRequestBytesHigh} << 32) + $result->{vsvrTotalRequestBytesLow}) * 8;
$self->{vservers}->{$_}->{health} = $result->{vsvrHealth};
$self->{vservers}->{$_}->{clients} = $result->{vsvrTotalClients};
$self->{vservers}->{$_}->{servers} = $result->{vsvrTotalServers};
}
$self->{cache_name} = "citrix_netscaler_" . $self->{mode} . '_' . $options{snmp}->get_hostname() . '_' . $options{snmp}->get_port() . '_' .
(defined($self->{option_results}->{filter_counters}) ? md5_hex($self->{option_results}->{filter_counters}) : md5_hex('all')) . '_' .
(defined($self->{option_results}->{filter_name}) ? md5_hex($self->{option_results}->{filter_name}) : md5_hex('all')) . '_' .
(defined($self->{option_results}->{filter_type}) ? md5_hex($self->{option_results}->{filter_type}) : md5_hex('all'));
}
1;
__END__
=head1 MODE
Check vservers status and health.
=over 8
=item B<--warning-*>
Threshold warning.
Can be: 'in-traffic', 'out-traffic', 'health' (%),
'clients', 'servers'.
=item B<--critical-*>
Threshold critical.
Can be: 'in-traffic', 'out-traffic', 'health' (%),
'clients', 'servers'.
=item B<--filter-name>
Filter by virtual server name (can be a regexp).
=item B<--filter-type>
Filter which type of vserver (can be a regexp).
=item B<--force-counters64>
Force to use 64 bits counters only. Can be used to improve performance,
or to solve a missing counters bug.
=item B<--threshold-overload>
Set to overload default threshold values (syntax: status,regexp)
It used before default thresholds (order stays).
Example: --threshold-overload='CRITICAL,^(?!(green)$)'
=back
=cut
|
Tpo76/centreon-plugins
|
network/citrix/netscaler/snmp/mode/vserverstatus.pm
|
Perl
|
apache-2.0
| 12,826
|
/*
* Copyright 2015-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.docksidestage.remote.maihama.showbase.wx.remogen.method.onbodyform;
import org.lastaflute.core.util.Lato;
/**
* The bean class as param for remote API of DELETE /wx/remogen/method/onbodyform.
* @author FreeGen
*/
public class RemoteWxRemogenMethodOnbodyformDeleteParam {
/** The property of sea. (NullAllowed) */
public String sea;
/** The property of land. (NullAllowed) */
public Integer land;
/** The property of iamForm. (NullAllowed) */
public String iamForm;
@Override
public String toString() {
return Lato.string(this);
}
}
|
lastaflute/lastaflute-test-fortress
|
src/main/java/org/docksidestage/remote/maihama/showbase/wx/remogen/method/onbodyform/RemoteWxRemogenMethodOnbodyformDeleteParam.java
|
Java
|
apache-2.0
| 1,217
|
package br.com.caelum.parsac.parser;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import br.com.caelum.parsac.modelo.Alternativa;
import br.com.caelum.parsac.modelo.Curso;
import br.com.caelum.parsac.modelo.Exercicio;
import br.com.caelum.parsac.modelo.ExercicioMultiplaEscolha;
import br.com.caelum.parsac.modelo.Secao;
public class ParserAfc {
private List<String> links = new ArrayList<String>();
private List<String> respostas = new ArrayList<String>();
public String parseiaTagsOnline(String string) throws IOException {
string = string.replaceAll("class=\"linked-list\"", "");
// Itálico precisa ser parseado antes do negrito, para a ~gambiarra~
// funcionar
string = parseiaItalico(string);
string = parseiaNegrito(string);
string = parseiaTagCode(string);
string = parseiaCode(string);
// string = parseiaLista(string);
// string = parseiaItemLista(string);
string = removeTagHr(string);
// string = removeLinksDeixandoSomenteOTexto(string);
string = parseiaImagens(string);
return string;
}
private String removeTagHr(String string) {
string = string.replaceAll("<[ ]*hr[ ]*>", "");
string = string.replaceAll("<[ ]*hr[ ]*/[ ]*>", "");
return string;
}
private String parseiaImagens(String string) {
string = string.replaceAll("src=\"http(s)*://[a-z A-Z_0-9./-]*/", "");
string = string.replaceAll("\"[ ]*alt=\"[a-z A-Z_0-9./-]*", "");
string = string.replaceAll("\"[ ]*width=\"[a-z A-Z_0-9./-]*", "");
string = string.replaceAll("img ", "img images/");
string = string.replaceAll("<[ ]*([a-z A-Z_0-9./-]*)\"(|/| | /)>",
"[$1]");
return string;
}
private String removeLinksDeixandoSomenteOTexto(String string) {
string = string
.replaceAll(
"<[ ]*a[ ]*href[ ]*=[ ]*\"http(s)*://[a-z A-Z_0-9./-]*\"[ ]*(target=\"_blank\")*>",
"");
string = string.replaceAll("<[ ]*/[ ]*a[ ]*>", "");
return string;
}
private String parseiaItemLista(String string) {
string = string.replaceAll("<[ ]*li[ ]*>", "* ");
string = string.replaceAll("<[ ]*/[ ]*li[ ]*>", "");
return string;
}
private String parseiaLista(String string) {
string = string.replaceAll("<[ ]*(ul|ol)[ ]*>", "[list]");
string = string.replaceAll("<[ ]*/[ ]*(ul|ol)[ ]*>", "[/list]");
return string;
}
private String parseiaItalico(String string) {
string = string.replaceAll("<[ ]*(em|i)[ ]*>", "::");
string = string.replaceAll("<[ ]*/[ ]*(em|i)[ ]*>", "::");
string = string.replaceAll("\\*([^*]+)\\*", "::$1::");
return string;
}
private String parseiaNegrito(String string) {
string = string.replaceAll("<[ ]*(b|strong|u)[ ]*>", "**");
string = string.replaceAll("<[ ]*/[ ]*(b|strong|u)[ ]*>", "**");
string = string.replaceAll("::::", "**");
return string;
}
private String parseiaCode(String string) {
string = string.replaceAll("<[ ]*code[ ]*>", "%%");
string = string.replaceAll("<[ ]*/[ ]*code[ ]*>", "%%");
string = string.replaceAll("`", "%%");
return string;
}
private String parseiaTagCode(String string) {
for (int i = 0; i < string.length(); i++) {
string = string.replaceFirst("```", "[code]");
string = string.replaceFirst("```", "[/code]");
}
return string;
}
public List<String> pegaLinksDasImagens(String string) {
Scanner scanner = new Scanner(string);
while (scanner.hasNext()) {
String token = scanner.next();
if (token
.matches("src=\"http(s)*://[a-z A-Z_0-9./-]*\"((|/)>)*[ ,.]*")) {
String link = (token.split("\"", 3)[1]);
links.add(link);
}
}
scanner.close();
return links;
}
public String parseiaCurso(Curso curso, int numeroDaSecao)
throws IOException {
Secao secao = curso.getSecoes().get(numeroDaSecao);
String texto = "[chapter " + secao.getTitulo() + "]";
System.out.println(">>\tParseando tags da explicação...");
texto += "\n" + parseiaTagsOnline(secao.getExplicacao());
System.out.println(">>\tParseando exercicios...");
texto += "\n\n[section Exercícios]\n\n[exercise]";
for (Exercicio exercicio : secao.getExercicios().getExercicios()) {
texto += "\n\t[question]";
texto += parseiaTagsOnline(exercicio.getEnunciado());
if (exercicio instanceof ExercicioMultiplaEscolha) {
texto += "[list]";
for (Alternativa alternativa : exercicio.getAlternativas()) {
texto += "\n* " + parseiaTagsOnline(alternativa.getTexto());
}
texto += "[/list]";
}
texto += "\n[/question]";
respostas.add(parseiaTagsOnline(exercicio.getResposta()));
}
texto += "\n[/exercise]\n[note]\n**Respostas:**\n\n";
for (int i = 0; i < respostas.size(); i++) {
texto += i + 1 + ") " + respostas.get(i) + "\n\n";
}
texto += "[/note]";
respostas.clear();
return texto;
}
}
|
vmattos/parsac
|
src/br/com/caelum/parsac/parser/ParserAfc.java
|
Java
|
apache-2.0
| 4,815
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.treasuredata.client;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableMultimap;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Protocol;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import org.exparity.hamcrest.date.DateMatchers;
import org.hamcrest.Matcher;
import org.hamcrest.Matchers;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import static com.google.common.net.HttpHeaders.USER_AGENT;
import static com.treasuredata.client.TDHttpRequestHandlers.stringContentHandler;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.exparity.hamcrest.date.DateMatchers.within;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
/**
*
*/
public class TestTDHttpClient
{
private static Logger logger = LoggerFactory.getLogger(TestTDHttpClient.class);
private TDHttpClient client;
@Before
public void setUp()
throws Exception
{
client = TDClient.newClient().httpClient;
}
@After
public void tearDown()
throws Exception
{
client.close();
}
@Test
public void addHttpRequestHeader()
{
TDApiRequest req = TDApiRequest.Builder.GET("/v3/system/server_status").addHeader("TEST_HEADER", "hello td-client-java").build();
String resp = client.submitRequest(req, Optional.<String>absent(), stringContentHandler);
}
@Test
public void addUserAgentHeader()
{
TDApiRequest apiRequest = TDApiRequest.Builder.GET("/v3/system/server_status").build();
// Without specifying User-Agent header
Request request1 = client.prepareRequest(apiRequest, Optional.<String>absent());
assertEquals("td-client-java unknown", request1.header(USER_AGENT));
// With specifying User-Agent header
TDHttpClient newClient = client.withHeaders(ImmutableMultimap.of(USER_AGENT, "td-sample-client 1.0"));
Request request2 = newClient.prepareRequest(apiRequest, Optional.<String>absent());
assertEquals("td-client-java unknown,td-sample-client 1.0", request2.header(USER_AGENT));
}
@Test
public void deleteMethodTest()
{
try {
TDApiRequest req = TDApiRequest.Builder.DELETE("/v3/dummy_endpoint").build();
String resp = client.submitRequest(req, Optional.<String>absent(), stringContentHandler);
fail();
}
catch (TDClientHttpException e) {
}
}
@Test
public void retryOn429()
throws Exception
{
// Configure an artificially low retry interval so we can measure with some confidence that Retry-After is respected
client = TDClient.newBuilder()
.setRetryMaxIntervalMillis(100)
.setRetryLimit(1000)
.build()
.httpClient;
final AtomicLong firstRequestNanos = new AtomicLong();
final AtomicLong secondRequestNanos = new AtomicLong();
final AtomicInteger requests = new AtomicInteger();
final TDApiRequest req = TDApiRequest.Builder.GET("/v3/system/server_status").build();
final byte[] body = "foobar".getBytes("UTF-8");
final long retryAfterSeconds = 5;
byte[] result = client.submitRequest(req, Optional.<String>absent(), new TDHttpRequestHandler<byte[]>()
{
@Override
public Response send(OkHttpClient httpClient, Request request)
throws IOException
{
switch (requests.incrementAndGet()) {
case 1: {
firstRequestNanos.set(System.nanoTime());
return new Response.Builder()
.request(request)
.protocol(Protocol.HTTP_1_1)
.message("")
.code(429)
.header("Retry-After", Long.toString(retryAfterSeconds))
.body(ResponseBody.create(null, ""))
.build();
}
case 2: {
secondRequestNanos.set(System.nanoTime());
return new Response.Builder()
.request(request)
.protocol(Protocol.HTTP_1_1)
.message("")
.code(200)
.body(ResponseBody.create(MediaType.parse("plain/text"), body))
.build();
}
default:
throw new AssertionError();
}
}
public byte[] onSuccess(Response response)
throws Exception
{
assertThat(response.code(), is(200));
return response.body().bytes();
}
});
assertThat(requests.get(), is(2));
assertThat(result, is(body));
long delayNanos = secondRequestNanos.get() - firstRequestNanos.get();
assertThat(delayNanos, Matchers.greaterThanOrEqualTo(SECONDS.toNanos(retryAfterSeconds)));
}
@Test
public void retryOn429WithoutRetryAfter()
throws Exception
{
client = TDClient.newBuilder()
.setRetryMaxIntervalMillis(100)
.setRetryLimit(3)
.build()
.httpClient;
int requests = failWith429(Optional.<String>absent(), Optional.<Matcher<Date>>absent());
assertThat(requests, is(4));
}
@Test
public void retryOn429WithInvalidRetryAfter()
throws Exception
{
client = TDClient.newBuilder()
.setRetryMaxIntervalMillis(100)
.setRetryLimit(3)
.build()
.httpClient;
int requests = failWith429(Optional.of("foobar"), Optional.<Matcher<Date>>absent());
assertThat(requests, is(4));
}
@Test
public void failOn429_TimeLimitExceeded_Seconds()
throws Exception
{
client = TDClient.newBuilder()
.setRetryMaxIntervalMillis(1000)
.setRetryLimit(3)
.build()
.httpClient;
// A high Retry-After value to verify that the exception is propagated without any retries when
// the Retry-After value exceeds the configured retryLimit * retryMaxInterval
long retryAfterSeconds = 4711;
Date expectedRetryAfter = new Date(System.currentTimeMillis() + SECONDS.toMillis(retryAfterSeconds));
int requests = failWith429(
Optional.of(Long.toString(retryAfterSeconds)),
Optional.of(within(5, SECONDS, expectedRetryAfter)));
// Verify that only one attempt was made
assertThat(requests, is(1));
}
@Test
public void failOn429_TimeLimitExceeded_Date()
throws Exception
{
client = TDClient.newBuilder()
.setRetryMaxIntervalMillis(1000)
.setRetryLimit(3)
.build()
.httpClient;
// A late Retry-After value to verify that the exception is propagated without any retries when
// the Retry-After value exceeds the configured retryLimit * retryMaxInterval
DateTime retryAfter = new DateTime().plusSeconds(4711);
DateTimeFormatter httpDateFormatter = DateTimeFormat.forPattern("EEE, dd MMM yyyy HH:mm:ss zzz");
String retryAfterString = retryAfter.toString(httpDateFormatter);
int requests = failWith429(
Optional.of(retryAfterString),
Optional.of(DateMatchers.within(30, SECONDS, retryAfter.toDate())));
// Verify that only one attempt was made
assertThat(requests, is(1));
}
@Test
public void failOn429_RetryLimitExceededUsingExponentialBackOff()
throws Exception
{
client = TDClient.newBuilder()
.setRetryMaxIntervalMillis(Integer.MAX_VALUE)
.setRetryStrategy(BackOffStrategy.Exponential)
.setRetryLimit(3)
.build()
.httpClient;
long retryAfterSeconds = 1;
Date expectedRetryAfter = new Date(System.currentTimeMillis() + SECONDS.toMillis(retryAfterSeconds));
int requests = failWith429(
Optional.of(Long.toString(retryAfterSeconds)),
Optional.of(within(5, SECONDS, expectedRetryAfter)));
// Verify that 4 attempts were made (original request + three retries)
assertThat(requests, is(4));
}
@Test
public void readBodyAsBytes()
throws Exception
{
final TDApiRequest req = TDApiRequest.Builder.GET("/v3/system/server_status").build();
final byte[] body = new byte[3 * 1024 * 1024];
Arrays.fill(body, (byte) 100);
byte[] res = client.submitRequest(req, Optional.<String>absent(), new TestDefaultHandler(body));
assertThat(res, is(body));
}
private static class TestDefaultHandler
implements TDHttpRequestHandler<byte[]>
{
private final byte[] body;
public TestDefaultHandler(byte[] body)
{
this.body = body;
}
@Override
public Response send(OkHttpClient httpClient, Request request)
throws IOException
{
// Return a dummy response
return new Response.Builder()
.request(request)
.code(200)
.message("")
.protocol(Protocol.HTTP_1_1)
.header("Content-Length", String.valueOf(body.length))
.body(ResponseBody.create(MediaType.parse("plain/text"), body))
.build();
}
@Override
public byte[] onSuccess(Response response)
throws Exception
{
return response.body().bytes();
}
}
private int failWith429(final Optional<String> retryAfterValue, final Optional<Matcher<Date>> retryAfterMatcher)
{
final AtomicInteger requests = new AtomicInteger();
final TDApiRequest req = TDApiRequest.Builder.GET("/v3/system/server_status").build();
try {
client.submitRequest(req, Optional.<String>absent(), new TDHttpRequestHandler<byte[]>()
{
@Override
public Response send(OkHttpClient httpClient, Request request)
throws IOException
{
requests.incrementAndGet();
Response.Builder builder = new Response.Builder()
.request(request)
.protocol(Protocol.HTTP_1_1)
.message("")
.body(ResponseBody.create(null, ""))
.code(429);
if (retryAfterValue.isPresent()) {
builder = builder.header("Retry-After", retryAfterValue.get());
}
return builder.build();
}
@Override
public byte[] onSuccess(Response response)
throws Exception
{
return response.body().bytes();
}
});
fail();
}
catch (TDClientException e) {
if (!(e instanceof TDClientHttpTooManyRequestsException)) {
fail("Expected " + TDClientHttpTooManyRequestsException.class + ", got " + e.getClass() + ": " + e.getMessage());
}
TDClientHttpTooManyRequestsException tooManyRequestsException = (TDClientHttpTooManyRequestsException) e;
if (retryAfterMatcher.isPresent()) {
assertThat(tooManyRequestsException.getRetryAfter().orNull(), retryAfterMatcher.get());
}
}
return requests.get();
}
}
|
treasure-data/td-client-java
|
src/test/java/com/treasuredata/client/TestTDHttpClient.java
|
Java
|
apache-2.0
| 13,473
|
FROM python:3.8-alpine
ENV PUPPETBOARD_PORT 80
EXPOSE 80
ENV PUPPETBOARD_SETTINGS docker_settings.py
RUN mkdir -p /usr/src/app/
WORKDIR /usr/src/app/
# Workaround for https://github.com/benoitc/gunicorn/issues/2160
RUN apk --update --no-cache add libc-dev binutils
COPY requirements*.txt /usr/src/app/
RUN pip install --no-cache-dir -r requirements-docker.txt
COPY . /usr/src/app
CMD gunicorn -b 0.0.0.0:${PUPPETBOARD_PORT} -e SCRIPT_NAME="${PUPPETBOARD_URL_PREFIX:-}" --access-logfile=- puppetboard.app:app --timeout=240 --workers=8 --threads=8
|
grandich/puppetboard
|
Dockerfile
|
Dockerfile
|
apache-2.0
| 552
|
# Copyright 2013-2015 ARM Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# pylint: disable=W0613,no-member,attribute-defined-outside-init
"""
Some "standard" instruments to collect additional info about workload execution.
.. note:: The run() method of a Workload may perform some "boilerplate" as well as
the actual execution of the workload (e.g. it may contain UI automation
needed to start the workload). This "boilerplate" execution will also
be measured by these instruments. As such, they are not suitable for collected
precise data about specific operations.
"""
import os
import re
import logging
import time
import tarfile
from itertools import izip, izip_longest
from subprocess import CalledProcessError
from wlauto import Instrument, Parameter
from wlauto.core import signal
from wlauto.exceptions import DeviceError, ConfigError
from wlauto.utils.misc import diff_tokens, write_table, check_output, as_relative
from wlauto.utils.misc import ensure_file_directory_exists as _f
from wlauto.utils.misc import ensure_directory_exists as _d
from wlauto.utils.android import ApkInfo
from wlauto.utils.types import list_of_strings
logger = logging.getLogger(__name__)
class SysfsExtractor(Instrument):
name = 'sysfs_extractor'
description = """
Collects the contest of a set of directories, before and after workload execution
and diffs the result.
"""
mount_command = 'mount -t tmpfs -o size={} tmpfs {}'
extract_timeout = 30
tarname = 'sysfs.tar'
DEVICE_PATH = 0
BEFORE_PATH = 1
AFTER_PATH = 2
DIFF_PATH = 3
parameters = [
Parameter('paths', kind=list_of_strings, mandatory=True,
description="""A list of paths to be pulled from the device. These could be directories
as well as files.""",
global_alias='sysfs_extract_dirs'),
Parameter('use_tmpfs', kind=bool, default=None,
description="""
Specifies whether tmpfs should be used to cache sysfile trees and then pull them down
as a tarball. This is significantly faster then just copying the directory trees from
the device directly, bur requres root and may not work on all devices. Defaults to
``True`` if the device is rooted and ``False`` if it is not.
"""),
Parameter('tmpfs_mount_point', default=None,
description="""Mount point for tmpfs partition used to store snapshots of paths."""),
Parameter('tmpfs_size', default='32m',
description="""Size of the tempfs partition."""),
]
def initialize(self, context):
if not self.device.is_rooted and self.use_tmpfs: # pylint: disable=access-member-before-definition
raise ConfigError('use_tempfs must be False for an unrooted device.')
elif self.use_tmpfs is None: # pylint: disable=access-member-before-definition
self.use_tmpfs = self.device.is_rooted
if self.use_tmpfs:
self.on_device_before = self.device.path.join(self.tmpfs_mount_point, 'before')
self.on_device_after = self.device.path.join(self.tmpfs_mount_point, 'after')
if not self.device.file_exists(self.tmpfs_mount_point):
self.device.execute('mkdir -p {}'.format(self.tmpfs_mount_point), as_root=True)
self.device.execute(self.mount_command.format(self.tmpfs_size, self.tmpfs_mount_point),
as_root=True)
def setup(self, context):
before_dirs = [
_d(os.path.join(context.output_directory, 'before', self._local_dir(d)))
for d in self.paths
]
after_dirs = [
_d(os.path.join(context.output_directory, 'after', self._local_dir(d)))
for d in self.paths
]
diff_dirs = [
_d(os.path.join(context.output_directory, 'diff', self._local_dir(d)))
for d in self.paths
]
self.device_and_host_paths = zip(self.paths, before_dirs, after_dirs, diff_dirs)
if self.use_tmpfs:
for d in self.paths:
before_dir = self.device.path.join(self.on_device_before,
self.device.path.dirname(as_relative(d)))
after_dir = self.device.path.join(self.on_device_after,
self.device.path.dirname(as_relative(d)))
if self.device.file_exists(before_dir):
self.device.execute('rm -rf {}'.format(before_dir), as_root=True)
self.device.execute('mkdir -p {}'.format(before_dir), as_root=True)
if self.device.file_exists(after_dir):
self.device.execute('rm -rf {}'.format(after_dir), as_root=True)
self.device.execute('mkdir -p {}'.format(after_dir), as_root=True)
def slow_start(self, context):
if self.use_tmpfs:
for d in self.paths:
dest_dir = self.device.path.join(self.on_device_before, as_relative(d))
if '*' in dest_dir:
dest_dir = self.device.path.dirname(dest_dir)
self.device.execute('{} cp -Hr {} {}'.format(self.device.busybox, d, dest_dir),
as_root=True, check_exit_code=False)
else: # not rooted
for dev_dir, before_dir, _, _ in self.device_and_host_paths:
self.device.pull_file(dev_dir, before_dir)
def slow_stop(self, context):
if self.use_tmpfs:
for d in self.paths:
dest_dir = self.device.path.join(self.on_device_after, as_relative(d))
if '*' in dest_dir:
dest_dir = self.device.path.dirname(dest_dir)
self.device.execute('{} cp -Hr {} {}'.format(self.device.busybox, d, dest_dir),
as_root=True, check_exit_code=False)
else: # not using tmpfs
for dev_dir, _, after_dir, _ in self.device_and_host_paths:
self.device.pull_file(dev_dir, after_dir)
def update_result(self, context):
if self.use_tmpfs:
on_device_tarball = self.device.path.join(self.device.working_directory, self.tarname)
on_host_tarball = self.device.path.join(context.output_directory, self.tarname + ".gz")
self.device.execute('{} tar cf {} -C {} .'.format(self.device.busybox,
on_device_tarball,
self.tmpfs_mount_point),
as_root=True)
self.device.execute('chmod 0777 {}'.format(on_device_tarball), as_root=True)
self.device.execute('{} gzip {}'.format(self.device.busybox,
on_device_tarball))
self.device.pull_file(on_device_tarball + ".gz", on_host_tarball)
with tarfile.open(on_host_tarball, 'r:gz') as tf:
tf.extractall(context.output_directory)
self.device.delete_file(on_device_tarball + ".gz")
os.remove(on_host_tarball)
for paths in self.device_and_host_paths:
after_dir = paths[self.AFTER_PATH]
dev_dir = paths[self.DEVICE_PATH].strip('*') # remove potential trailing '*'
if (not os.listdir(after_dir) and
self.device.file_exists(dev_dir) and
self.device.listdir(dev_dir)):
self.logger.error('sysfs files were not pulled from the device.')
self.device_and_host_paths.remove(paths) # Path is removed to skip diffing it
for _, before_dir, after_dir, diff_dir in self.device_and_host_paths:
_diff_sysfs_dirs(before_dir, after_dir, diff_dir)
def teardown(self, context):
self._one_time_setup_done = []
def finalize(self, context):
if self.use_tmpfs:
try:
self.device.execute('umount {}'.format(self.tmpfs_mount_point), as_root=True)
except (DeviceError, CalledProcessError):
# assume a directory but not mount point
pass
self.device.execute('rm -rf {}'.format(self.tmpfs_mount_point),
as_root=True, check_exit_code=False)
def validate(self):
if not self.tmpfs_mount_point: # pylint: disable=access-member-before-definition
self.tmpfs_mount_point = self.device.path.join(self.device.working_directory, 'temp-fs')
def _local_dir(self, directory):
return os.path.dirname(as_relative(directory).replace(self.device.path.sep, os.sep))
class ExecutionTimeInstrument(Instrument):
name = 'execution_time'
description = """
Measure how long it took to execute the run() methods of a Workload.
"""
priority = 15
def __init__(self, device, **kwargs):
super(ExecutionTimeInstrument, self).__init__(device, **kwargs)
self.start_time = None
self.end_time = None
def on_run_start(self, context):
signal.connect(self.get_start_time, signal.BEFORE_WORKLOAD_EXECUTION, priority=self.priority)
signal.connect(self.get_stop_time, signal.AFTER_WORKLOAD_EXECUTION, priority=self.priority)
def get_start_time(self, context):
self.start_time = time.time()
def get_stop_time(self, context):
self.end_time = time.time()
def update_result(self, context):
execution_time = self.end_time - self.start_time
context.result.add_metric('execution_time', execution_time, 'seconds')
class ApkVersion(Instrument):
name = 'apk_version'
description = """
(DEPRECATED) Extracts APK versions for workloads that have them.
This instrument is deprecated and should not be used. It will be removed in
future versions of Workload Automation.
Versions of Android packages are now automatically attached to the results as
"apk_version" classfiers.
"""
def __init__(self, device, **kwargs):
super(ApkVersion, self).__init__(device, **kwargs)
self.apk_info = None
def setup(self, context):
if hasattr(context.workload, 'apk_file'):
self.apk_info = ApkInfo(context.workload.apk_file)
else:
self.apk_info = None
def update_result(self, context):
if self.apk_info:
context.result.add_metric(self.name, self.apk_info.version_name)
class InterruptStatsInstrument(Instrument):
name = 'interrupts'
description = """
Pulls the ``/proc/interrupts`` file before and after workload execution and diffs them
to show what interrupts occurred during that time.
"""
def __init__(self, device, **kwargs):
super(InterruptStatsInstrument, self).__init__(device, **kwargs)
self.before_file = None
self.after_file = None
self.diff_file = None
def setup(self, context):
self.before_file = os.path.join(context.output_directory, 'before', 'proc', 'interrupts')
self.after_file = os.path.join(context.output_directory, 'after', 'proc', 'interrupts')
self.diff_file = os.path.join(context.output_directory, 'diff', 'proc', 'interrupts')
def start(self, context):
with open(_f(self.before_file), 'w') as wfh:
wfh.write(self.device.execute('cat /proc/interrupts'))
def stop(self, context):
with open(_f(self.after_file), 'w') as wfh:
wfh.write(self.device.execute('cat /proc/interrupts'))
def update_result(self, context):
# If workload execution failed, the after_file may not have been created.
if os.path.isfile(self.after_file):
_diff_interrupt_files(self.before_file, self.after_file, _f(self.diff_file))
class DynamicFrequencyInstrument(SysfsExtractor):
name = 'cpufreq'
description = """
Collects dynamic frequency (DVFS) settings before and after workload execution.
"""
tarname = 'cpufreq.tar'
parameters = [
Parameter('paths', mandatory=False, override=True),
]
def setup(self, context):
self.paths = ['/sys/devices/system/cpu']
if self.use_tmpfs:
self.paths.append('/sys/class/devfreq/*') # the '*' would cause problems for adb pull.
super(DynamicFrequencyInstrument, self).setup(context)
def validate(self):
# temp-fs would have been set in super's validate, if not explicitly specified.
if not self.tmpfs_mount_point.endswith('-cpufreq'): # pylint: disable=access-member-before-definition
self.tmpfs_mount_point += '-cpufreq'
def _diff_interrupt_files(before, after, result): # pylint: disable=R0914
output_lines = []
with open(before) as bfh:
with open(after) as ofh:
for bline, aline in izip(bfh, ofh):
bchunks = bline.strip().split()
while True:
achunks = aline.strip().split()
if achunks[0] == bchunks[0]:
diffchunks = ['']
diffchunks.append(achunks[0])
diffchunks.extend([diff_tokens(b, a) for b, a
in zip(bchunks[1:], achunks[1:])])
output_lines.append(diffchunks)
break
else: # new category appeared in the after file
diffchunks = ['>'] + achunks
output_lines.append(diffchunks)
try:
aline = ofh.next()
except StopIteration:
break
# Offset heading columns by one to allow for row labels on subsequent
# lines.
output_lines[0].insert(0, '')
# Any "columns" that do not have headings in the first row are not actually
# columns -- they are a single column where space-spearated words got
# split. Merge them back together to prevent them from being
# column-aligned by write_table.
table_rows = [output_lines[0]]
num_cols = len(output_lines[0])
for row in output_lines[1:]:
table_row = row[:num_cols]
table_row.append(' '.join(row[num_cols:]))
table_rows.append(table_row)
with open(result, 'w') as wfh:
write_table(table_rows, wfh)
def _diff_sysfs_dirs(before, after, result): # pylint: disable=R0914
before_files = []
os.path.walk(before,
lambda arg, dirname, names: arg.extend([os.path.join(dirname, f) for f in names]),
before_files
)
before_files = filter(os.path.isfile, before_files)
files = [os.path.relpath(f, before) for f in before_files]
after_files = [os.path.join(after, f) for f in files]
diff_files = [os.path.join(result, f) for f in files]
for bfile, afile, dfile in zip(before_files, after_files, diff_files):
if not os.path.isfile(afile):
logger.debug('sysfs_diff: {} does not exist or is not a file'.format(afile))
continue
with open(bfile) as bfh, open(afile) as afh: # pylint: disable=C0321
with open(_f(dfile), 'w') as dfh:
for i, (bline, aline) in enumerate(izip_longest(bfh, afh), 1):
if aline is None:
logger.debug('Lines missing from {}'.format(afile))
break
bchunks = re.split(r'(\W+)', bline)
achunks = re.split(r'(\W+)', aline)
if len(bchunks) != len(achunks):
logger.debug('Token length mismatch in {} on line {}'.format(bfile, i))
dfh.write('xxx ' + bline)
continue
if ((len([c for c in bchunks if c.strip()]) == len([c for c in achunks if c.strip()]) == 2) and
(bchunks[0] == achunks[0])):
# if there are only two columns and the first column is the
# same, assume it's a "header" column and do not diff it.
dchunks = [bchunks[0]] + [diff_tokens(b, a) for b, a in zip(bchunks[1:], achunks[1:])]
else:
dchunks = [diff_tokens(b, a) for b, a in zip(bchunks, achunks)]
dfh.write(''.join(dchunks))
|
chase-qi/workload-automation
|
wlauto/instrumentation/misc/__init__.py
|
Python
|
apache-2.0
| 17,103
|
'use strict';
const common = require('../common');
const assert = require('assert');
const cluster = require('cluster');
const net = require('net');
if (cluster.isMaster) {
cluster.fork().on('message', function(msg) {
if (msg === 'done') this.kill();
});
} else {
const server = net.createServer(common.fail);
server.listen(common.PORT, function() {
server.unref();
server.ref();
server.close(function() {
process.send('done');
});
});
}
|
dreamllq/node
|
test/parallel/test-cluster-rr-ref.js
|
JavaScript
|
apache-2.0
| 476
|
/**
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import './node_modules/@google-pay/save-button-element/dist/index.js';
const button = document.querySelector('save-to-google-pay-button');
[...document.querySelectorAll('select')].forEach(select => {
select.addEventListener('change', event => {
const { name, value } = event.target;
button.setAttribute(name, value);
});
});
button.addEventListener('success', () => {
console.log('success');
});
button.addEventListener('failure', event => {
console.log('failure', event.detail);
});
// button.onProvideJwt = () => {
// console.log('provide jwt');
// return button.jwt;
// };
|
google-pay/save-to-google-pay-button
|
examples/html/example.js
|
JavaScript
|
apache-2.0
| 1,199
|
/*
* Copyright 2008-2019 by Emeric Vernat
*
* This file is part of the Monitoring plugin.
*
* 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.jvnet.hudson.plugins.monitoring;
import java.io.File;
import java.util.Arrays;
import java.util.logging.LogRecord;
import javax.servlet.ServletContext;
import hudson.Plugin;
import hudson.init.InitMilestone;
import hudson.util.PluginServletFilter;
import jenkins.model.Jenkins;
import net.bull.javamelody.Parameter;
import net.bull.javamelody.internal.common.Parameters;
/**
* Entry point of the plugin.
* <p>
* There must be one {@link Plugin} class in each plugin. See javadoc of
* {@link Plugin} for more about what can be done on this class.
* @author Emeric Vernat
*/
@SuppressWarnings("deprecation")
public class PluginImpl extends Plugin {
private ServletContext context;
private HudsonMonitoringFilter filter;
private static class CsrfThread extends Thread {
CsrfThread() {
super();
}
@Override
public void run() {
final Jenkins jenkins = Jenkins.getInstance();
while (jenkins.getInitLevel() != InitMilestone.COMPLETED) {
try {
Thread.sleep(1000);
} catch (final InterruptedException e) {
// RAS
}
}
if (jenkins.isUseCrumbs()) {
Parameter.CSRF_PROTECTION_ENABLED.setValue("true");
}
}
}
/** {@inheritDoc} */
@Override
public void start() throws Exception {
super.start();
// get the servletContext in Jenkins instead of overriding Plugin.setServletContext
final Jenkins jenkins = Jenkins.getInstance();
this.context = jenkins.servletContext;
// jenkins.isUseCrumbs() is always false here because it's too early
// and we can't use @Initializer(after = InitMilestone.COMPLETED)
// because of https://issues.jenkins-ci.org/browse/JENKINS-37807
// so check when jenkins is initialized
final Thread thread = new CsrfThread();
thread.setName("javamelody-initializer");
thread.setDaemon(true);
thread.start();
// on active les actions systemes (gc, heap dump, histogramme memoire,
// processus...), sauf si l'administrateur a dit differemment
if (isParameterUndefined(Parameter.SYSTEM_ACTIONS_ENABLED)) {
Parameter.SYSTEM_ACTIONS_ENABLED.setValue("true");
}
// on desactive les graphiques jdbc et statistiques sql puisqu'il n'y en
// aura pas
if (isParameterUndefined(Parameter.NO_DATABASE)) {
Parameter.NO_DATABASE.setValue("true");
}
// le repertoire de stockage est dans le repertoire de Hudson/Jenkins au lieu
// d'etre dans le repertoire temporaire
// ("/" initial necessaire sous windows pour javamelody v1.8.1)
if (isParameterUndefined(Parameter.STORAGE_DIRECTORY)) {
Parameter.STORAGE_DIRECTORY
.setValue("/" + new File(jenkins.getRootDir(), "monitoring").getAbsolutePath());
}
// http-transform-pattern pour agreger les requetes contenant des
// parties "dynamiques" comme des numeros des builds,
// les fichiers dans job/<name>/site/, javadoc/, ws/, cobertura/,
// testReport/, violations/file/
// ou les utilisateurs dans user/
// ou les fichiers dans /static/abcdef123/ et dans /adjuncts/abcdef123/
// ou les renders ajax lors de l'ajout de build step dans /$stapler/bound/c285ac3d-39c1-4515-86aa-0b42d75212b3/render
if (isParameterUndefined(Parameter.HTTP_TRANSFORM_PATTERN)) {
Parameter.HTTP_TRANSFORM_PATTERN.setValue(
"/\\d+/|(?<=/static/|/adjuncts/|/bound/)[\\w\\-]+|(?<=/ws/|/user/|/testReport/|/javadoc/|/site/|/violations/file/|/cobertura/).+|(?<=/job/).+(?=/descriptorByName/)");
}
// custom reports (v1.50+)
if (isParameterUndefined(Parameter.CUSTOM_REPORTS)) {
Parameter.CUSTOM_REPORTS.setValue("Jenkins Info,About Monitoring");
System.setProperty("javamelody.Jenkins Info", "/systemInfo");
System.setProperty("javamelody.About Monitoring",
"https://plugins.jenkins.io/monitoring/");
}
// fix for JENKINS-14050: Unreadable HTML response for the monitoring reports
if (isParameterUndefined(Parameter.GZIP_COMPRESSION_DISABLED)) {
Parameter.GZIP_COMPRESSION_DISABLED.setValue("true");
}
if (isParameterUndefined(Parameter.MAVEN_REPOSITORIES)) {
// add jenkins maven public repository for jenkins and plugins sources
final String mavenRepositories = System.getProperty("user.home")
+ "/.m2/repository,http://repo1.maven.org/maven2,http://repo.jenkins-ci.org/public";
Parameter.MAVEN_REPOSITORIES.setValue(mavenRepositories);
}
// we could set "javamelody.admin-emails" with
// ((Mailer.DescriptorImpl) Jenkins.getInstance().getDescriptorByType(
// hudson.tasks.Mailer.DescriptorImpl.class)).getAdminAddress();
// but the admin-emails property is better next to the mail session
// try to fix https://issues.jenkins-ci.org/browse/JENKINS-23442 (ClassCircularityError: java/util/logging/LogRecord)
// by preloading the java.util.logging.LogRecord class
Arrays.hashCode(new Class<?>[] { LogRecord.class });
this.filter = new HudsonMonitoringFilter();
PluginServletFilter.addFilter(filter);
}
private boolean isParameterUndefined(Parameter parameter) {
final String key = Parameters.PARAMETER_SYSTEM_PREFIX + parameter.getCode();
return isParameterUndefined(key);
}
private boolean isParameterUndefined(String key) {
return System.getProperty(key) == null && context != null
&& context.getInitParameter(key) == null;
}
HudsonMonitoringFilter getFilter() {
return filter;
}
/** {@inheritDoc} */
@Override
public void postInitialize() throws Exception {
super.postInitialize();
if (filter == null) {
throw new Exception("Post-initialization hook has been called before the plugin start. "
+ "Filters are not available");
}
filter.getNodesCollector().init();
// replaced by @Extension in NodesListener: new NodesListener(filter.getNodesCollector()).register();
// replaced by @Extension in CounterRunListener: new CounterRunListener().register();
}
/** {@inheritDoc} */
@Override
public void stop() throws Exception {
if (filter != null && filter.getNodesCollector() != null) {
filter.getNodesCollector().stop();
}
super.stop();
}
}
|
jenkinsci/monitoring-plugin
|
src/main/java/org/jvnet/hudson/plugins/monitoring/PluginImpl.java
|
Java
|
apache-2.0
| 6,620
|
all: libnss_etcd.so.2
libnss_etcd.so.2: nssrc.c
gcc -shared -fPIC -o libnss_etcd.so.2 -Wl,-soname,libnss_etcd.so.2 nssrc.c
|
tingar/libnss_etcd
|
Makefile
|
Makefile
|
apache-2.0
| 125
|
/* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.flowable.cmmn.engine.impl.persistence.entity;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import org.flowable.cmmn.api.runtime.CaseInstance;
import org.flowable.cmmn.api.runtime.CaseInstanceQuery;
import org.flowable.cmmn.engine.CmmnEngineConfiguration;
import org.flowable.cmmn.engine.impl.persistence.entity.data.CaseInstanceDataManager;
import org.flowable.cmmn.engine.impl.runtime.CaseInstanceQueryImpl;
import org.flowable.cmmn.engine.impl.task.TaskHelper;
import org.flowable.engine.common.impl.persistence.entity.data.DataManager;
import org.flowable.job.api.Job;
import org.flowable.job.service.impl.DeadLetterJobQueryImpl;
import org.flowable.job.service.impl.JobQueryImpl;
import org.flowable.job.service.impl.SuspendedJobQueryImpl;
import org.flowable.job.service.impl.TimerJobQueryImpl;
import org.flowable.job.service.impl.persistence.entity.DeadLetterJobEntityManager;
import org.flowable.job.service.impl.persistence.entity.JobEntityManager;
import org.flowable.job.service.impl.persistence.entity.SuspendedJobEntityManager;
import org.flowable.job.service.impl.persistence.entity.TimerJobEntityManager;
import org.flowable.task.service.impl.persistence.entity.TaskEntity;
import org.flowable.task.service.impl.persistence.entity.TaskEntityManager;
import org.flowable.variable.api.type.VariableScopeType;
/**
* @author Joram Barrez
*/
public class CaseInstanceEntityManagerImpl extends AbstractCmmnEntityManager<CaseInstanceEntity> implements CaseInstanceEntityManager {
protected CaseInstanceDataManager caseInstanceDataManager;
public CaseInstanceEntityManagerImpl(CmmnEngineConfiguration cmmnEngineConfiguration, CaseInstanceDataManager caseInstanceDataManager) {
super(cmmnEngineConfiguration);
this.caseInstanceDataManager = caseInstanceDataManager;
}
@Override
protected DataManager<CaseInstanceEntity> getDataManager() {
return caseInstanceDataManager;
}
@Override
public CaseInstanceQuery createCaseInstanceQuery() {
return new CaseInstanceQueryImpl(cmmnEngineConfiguration.getCommandExecutor());
}
@Override
public List<CaseInstanceEntity> findCaseInstancesByCaseDefinitionId(String caseDefinitionId) {
return caseInstanceDataManager.findCaseInstancesByCaseDefinitionId(caseDefinitionId);
}
@Override
public List<CaseInstance> findByCriteria(CaseInstanceQuery query) {
return caseInstanceDataManager.findByCriteria((CaseInstanceQueryImpl) query);
}
@Override
public List<CaseInstance> findWithVariablesByCriteria(CaseInstanceQuery query) {
return caseInstanceDataManager.findWithVariablesByCriteria((CaseInstanceQueryImpl) query);
}
@Override
public long countByCriteria(CaseInstanceQuery query) {
return caseInstanceDataManager.countByCriteria((CaseInstanceQueryImpl) query);
}
@Override
public void delete(String caseInstanceId, String deleteReason) {
CaseInstanceEntity caseInstanceEntity = caseInstanceDataManager.findById(caseInstanceId);
// Variables
getVariableInstanceEntityManager().deleteByScopeIdAndScopeType(caseInstanceId, VariableScopeType.CMMN);
// Tasks
TaskEntityManager taskEntityManager = getTaskEntityManager();
List<TaskEntity> taskEntities = taskEntityManager.findTasksByScopeIdAndScopeType(caseInstanceId, VariableScopeType.CMMN);
for (TaskEntity taskEntity : taskEntities) {
TaskHelper.deleteTask(taskEntity, deleteReason, false, true);
}
// Sentry part instances
getSentryPartInstanceEntityManager().deleteByCaseInstanceId(caseInstanceId);
// Runtime milestones
getMilestoneInstanceEntityManager().deleteByCaseInstanceId(caseInstanceId);
// Plan item instances
PlanItemInstanceEntityManager planItemInstanceEntityManager = getPlanItemInstanceEntityManager();
// Plan item instances are removed per stage, in reversed order
ArrayList<PlanItemInstanceEntity> stagePlanItemInstances = new ArrayList<>();
collectStagePlanItemInstances(caseInstanceEntity, stagePlanItemInstances);
for (int i = stagePlanItemInstances.size() - 1; i>=0; i--) {
planItemInstanceEntityManager.deleteByStageInstanceId(stagePlanItemInstances.get(i).getId());
}
planItemInstanceEntityManager.deleteByCaseInstanceId(caseInstanceId); // root plan item instances
// Jobs have dependencies (byte array refs that need to be deleted, so no immediate delete for the moment)
JobEntityManager jobEntityManager = cmmnEngineConfiguration.getJobServiceConfiguration().getJobEntityManager();
List<Job> jobs = jobEntityManager.findJobsByQueryCriteria(new JobQueryImpl().scopeId(caseInstanceId).scopeType(VariableScopeType.CMMN));
for (Job job : jobs) {
jobEntityManager.delete(job.getId());
}
TimerJobEntityManager timerJobEntityManager = cmmnEngineConfiguration.getJobServiceConfiguration().getTimerJobEntityManager();
List<Job> timerJobs = timerJobEntityManager.findJobsByQueryCriteria(new TimerJobQueryImpl().scopeId(caseInstanceId).scopeType(VariableScopeType.CMMN));
for (Job timerJob : timerJobs) {
timerJobEntityManager.delete(timerJob.getId());
}
SuspendedJobEntityManager suspendedJobEntityManager = cmmnEngineConfiguration.getJobServiceConfiguration().getSuspendedJobEntityManager();
List<Job> suspendedJobs = suspendedJobEntityManager.findJobsByQueryCriteria(new SuspendedJobQueryImpl().scopeId(caseInstanceId).scopeType(VariableScopeType.CMMN));
for (Job suspendedJob : suspendedJobs) {
suspendedJobEntityManager.delete(suspendedJob.getId());
}
DeadLetterJobEntityManager deadLetterJobEntityManager = cmmnEngineConfiguration.getJobServiceConfiguration().getDeadLetterJobEntityManager();
List<Job> deadLetterJobs = deadLetterJobEntityManager.findJobsByQueryCriteria(new DeadLetterJobQueryImpl().scopeId(caseInstanceId).scopeType(VariableScopeType.CMMN));
for (Job deadLetterJob : deadLetterJobs) {
deadLetterJobEntityManager.delete(deadLetterJob.getId());
}
// Actual case instance
delete(caseInstanceEntity);
}
protected void collectStagePlanItemInstances(PlanItemInstanceContainer planItemInstanceContainer, ArrayList<PlanItemInstanceEntity> stagePlanItemInstanceEntities) {
for (PlanItemInstanceEntity planItemInstanceEntity : planItemInstanceContainer.getChildPlanItemInstances()) {
if (planItemInstanceEntity.isStage()) {
stagePlanItemInstanceEntities.add(planItemInstanceEntity);
collectStagePlanItemInstances(planItemInstanceEntity, stagePlanItemInstanceEntities);
}
}
}
@Override
public void updateLockTime(String caseInstanceId) {
Date expirationTime = getCmmnEngineConfiguration().getClock().getCurrentTime();
int lockMillis = getCmmnEngineConfiguration().getAsyncExecutor().getAsyncJobLockTimeInMillis();
GregorianCalendar lockCal = new GregorianCalendar();
lockCal.setTime(expirationTime);
lockCal.add(Calendar.MILLISECOND, lockMillis);
Date lockDate = lockCal.getTime();
caseInstanceDataManager.updateLockTime(caseInstanceId, lockDate, expirationTime);
}
@Override
public void clearLockTime(String caseInstanceId) {
caseInstanceDataManager.clearLockTime(caseInstanceId);
}
}
|
marcus-nl/flowable-engine
|
modules/flowable-cmmn-engine/src/main/java/org/flowable/cmmn/engine/impl/persistence/entity/CaseInstanceEntityManagerImpl.java
|
Java
|
apache-2.0
| 8,211
|
/*
* Copyright 2000-2022 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jetbrains.buildServer.clouds.base.tasks;
import com.intellij.openapi.diagnostic.Logger;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import jetbrains.buildServer.Used;
import jetbrains.buildServer.clouds.InstanceStatus;
import jetbrains.buildServer.clouds.base.AbstractCloudClient;
import jetbrains.buildServer.clouds.base.AbstractCloudImage;
import jetbrains.buildServer.clouds.base.AbstractCloudInstance;
import jetbrains.buildServer.clouds.base.connector.AbstractInstance;
import jetbrains.buildServer.clouds.base.connector.CloudApiConnector;
import jetbrains.buildServer.clouds.base.errors.CheckedCloudException;
import jetbrains.buildServer.clouds.base.errors.TypedCloudErrorInfo;
import jetbrains.buildServer.util.Disposable;
import org.jetbrains.annotations.NotNull;
/**
* @author Sergey.Pak
* Date: 7/22/2014
* Time: 1:52 PM
*/
public class UpdateInstancesTask< G extends AbstractCloudInstance<T>,
T extends AbstractCloudImage<G,?>,
F extends AbstractCloudClient<G, T, ?>
> implements Runnable {
private static final Logger LOG = Logger.getInstance(UpdateInstancesTask.class.getName());
private static final long STUCK_STATUS_TIME = 10*60*1000l; // 2 minutes;
@NotNull protected final CloudApiConnector<T, G> myConnector;
@NotNull protected final F myClient;
@Used("Tests")
private final long myStuckTime;
@Used("Tests")
private final boolean myRethrowException;
public UpdateInstancesTask(@NotNull final CloudApiConnector<T, G> connector,
@NotNull final F client) {
this(connector, client, STUCK_STATUS_TIME, false);
}
@Used("Tests")
public UpdateInstancesTask(@NotNull final CloudApiConnector<T, G> connector,
@NotNull final F client,
@Used("Tests")
final long stuckTimeMillis,
@Used("Tests")
final boolean rethrowException) {
myConnector = connector;
myClient = client;
myStuckTime = stuckTimeMillis;
myRethrowException = rethrowException;
}
public void run() {
final Map<InstanceStatus, List<String>> instancesByStatus = new HashMap<InstanceStatus, List<String>>();
try {
List<T> goodImages = new ArrayList<>();
myConnector.checkImages(getImages()).forEach((img, errors)->{
img.updateErrors(errors);
if (img.getErrorInfo() == null)
goodImages.add(img);
});
final Map<T, Map<String, AbstractInstance>> groupedInstances = myConnector.fetchInstances(goodImages);
if (LOG.isDebugEnabled()) {
groupedInstances.forEach((img, instMap) -> {
LOG.debug(String.format("Instances for [%s]:[%s]", img.getId(), String.join(",", instMap.keySet())));
});
}
for (T image : goodImages) {
Map<String, AbstractInstance> realInstances = groupedInstances.get(image);
if (realInstances == null){
realInstances = Collections.emptyMap();
}
for (String realInstanceName : realInstances.keySet()) {
final G instance = image.findInstanceById(realInstanceName);
final AbstractInstance realInstance = realInstances.get(realInstanceName);
if (instance == null) {
continue;
}
final InstanceStatus realInstanceStatus = realInstance.getInstanceStatus();
if (!instancesByStatus.containsKey(realInstanceStatus)){
instancesByStatus.put(realInstanceStatus, new ArrayList<String>());
}
instancesByStatus.get(realInstanceStatus).add(realInstanceName);
if ((isStatusPermanent(instance.getStatus()) || isStuck(instance))
&& isStatusPermanent(realInstanceStatus)
&& realInstanceStatus != instance.getStatus()) {
LOG.info(String.format("Updated instance '%s' status to %s based on API information", realInstanceName, realInstanceStatus));
instance.setStatus(realInstanceStatus);
}
}
final Collection<G> instances = image.getInstances();
final Set<String> instancesToRemove = new HashSet<>();
for (final G cloudInstance : instances) {
try {
final String instanceName = cloudInstance.getName();
final AbstractInstance instance = realInstances.get(instanceName);
if (instance == null) {
if (cloudInstance.getStatus() != InstanceStatus.SCHEDULED_TO_START && cloudInstance.getStatus() != InstanceStatus.STARTING) {
instancesToRemove.add(instanceName);
}
continue;
}
cloudInstance.updateErrors(myConnector.checkInstance(cloudInstance));
if (instance.getStartDate() != null) {
cloudInstance.setStartDate(instance.getStartDate());
}
if (instance.getIpAddress() != null) {
cloudInstance.setNetworkIdentify(instance.getIpAddress());
}
} catch (Exception ex){
LOG.warnAndDebugDetails("Error processing VM " + cloudInstance.getName(), ex);
}
}
for (String instanceName : instancesToRemove) {
AbstractInstance realInstanceNullable = realInstances.get(instanceName);
final InstanceStatus currentStatus = realInstanceNullable==null ? null : realInstanceNullable.getInstanceStatus();
if (currentStatus == null) {
image.removeInstance(instanceName);
}
}
image.detectNewInstances(realInstances);
}
myClient.updateErrors();
} catch (CheckedCloudException e) {
LOG.warnAndDebugDetails("An error occurred during updateInstanceTask", e);
if (myRethrowException){
// for tests
throw new RuntimeException(e);
}
} finally {
//logging here:
if (LOG.isDebugEnabled()) {
for (InstanceStatus instanceStatus : instancesByStatus.keySet()) {
LOG.debug(String.format("Instances in '%s' status: %s", instanceStatus.getText(), Arrays.toString(instancesByStatus.get(instanceStatus).toArray())));
}
}
}
}
@NotNull
protected Collection<T> getImages() {
return myClient.getImages();
}
private static boolean isStatusPermanent(InstanceStatus status){
return status == InstanceStatus.STOPPED || status == InstanceStatus.RUNNING;
}
private boolean isStuck(G instance){
return (System.currentTimeMillis() - instance.getStatusUpdateTime().getTime()) > myStuckTime &&
(instance.getStatus() == InstanceStatus.STOPPING
|| instance.getStatus() == InstanceStatus.STARTING
|| instance.getStatus() == InstanceStatus.SCHEDULED_TO_STOP
|| instance.getStatus() == InstanceStatus.SCHEDULED_TO_START
);
}
}
|
JetBrains/teamcity-vmware-plugin
|
cloud-vmware-server/src/main/java/jetbrains/buildServer/clouds/base/tasks/UpdateInstancesTask.java
|
Java
|
apache-2.0
| 7,634
|
package com.weygo.weygophone.pages.order.commit.model;
import com.weygo.weygophone.base.WGObject;
/**
* Created by muma on 2017/8/19.
*/
public class WGCommitOrderUpdateTimeData extends WGObject {
public WGOrderExpireGood expireGood;
}
|
mumabinggan/WeygoPhone
|
app/src/main/java/com/weygo/weygophone/pages/order/commit/model/WGCommitOrderUpdateTimeData.java
|
Java
|
apache-2.0
| 245
|
** Note: the ftdi driver installation has stopped working as of version 10556.0 **
# FTDI sample for Windows Universal (UWP)
A sample application showcasing the FTDI D2XX driver use in Windows Universal projects (UWP). This sample is tested on the Raspberry PI 2 with Windows IOT installed and a FTDI FT232R usb-to-serial adapter.
This project uses the D2XX Windows RT driver from FTDI, see http://www.ftdichip.com/Drivers/D2XX.htm for the licensing and liability terms.
## Screenshots


## Installing the FTDI D2XX drivers on the Raspberry PI
1. go to `\\[device-name]\c$\windows\system32`, login with username: `[device-name]\administrator` and the administrator password
2. copy [ftdi.d2xx.winrt.cat](lib/D2xx WinRT 1.0.2/driver/ftdi.d2xx.winrt.cat) and [FTDI.D2xx.WinRT.inf](lib/D2xx WinRT 1.0.2/driver/FTDI.D2xx.WinRT.inf) from [lib\D2xx WinRT 1.0.2\driver](lib/D2xx WinRT 1.0.2/driver) to the folder above
3. start a remote powershell (as administrator) session to the Raspberry PI:
- start the remote service: `net start WinRM`
- add the Raspberry PI to the TrustedHosts if you haven't already: `set-Item WSMan:\localhost\Client\TrustedHosts -Value [device-name]`
- start the session with: `enter-pssession -computername [device-name] -credential [device-name]\administrator` this can take up to 30 seconds or more, so be patient
5. type `cd c:\windows\system32` to go to the folder where the drivers are located
4. install the FTDI D2XX driver using the following command: `devcon.exe dp_add FTDI.D2xx.WinRT.inf`
5. reboot the device: `shutdown /r /t 0`
6. when rebooted reconnect again using last part of step 3
5. test the driver is working with: `devcon status "USB\VID_0403&PID_6001"`, it should say something along the lines of:
```
USB\VID_0403&PID_6001\AH02A2KS
Name: FT232R USB UART
Driver is running.
1 matching device(s) found.
```
**Note: the VID and PID need to match the model you are using, if you see `0 matching device(s) found.` your FTDI device might use a different VID/PID . For an overview of the default VIDs/PIDS per model see the `DeviceCapability` section in: [Package.appxmanifest](src/FTDISample/Package.appxmanifest) or look up the Hardware Id in the device manager on Windows.**
## Limitations
- if you pull the usb adapter from the Raspberry PI the app will crash
- Toggling ASCII / hex output mode doesn't immediately switch but only after the next change to the read buffer
- there is no cancellation support in the read task, so if the device errors the device will most likely lock up
## Setting up a new Windows Universal project using the D2XX
**Note: you don't need to execute these instructions if you want to try the sample, this is just for a *new* project.**
1. download the ARM Windows RT drivers http://www.ftdichip.com/Drivers/D2XX.htm (or look in the lib folder of this repository)
2. copy `FTDI.D2xx.WinRT.USB.winmd`, `FTDI.D2xx.WinRT.winmd`, `FTDI.D2xx.WinRT.XML` to your lib folder
3. in your new project add references to the files above
4. open the `Package.appxmanifest` file and make sure the `Capabilities` node has the following sub node:
```xml
<DeviceCapability Name="usb">
<!--FT232AM, FT232BM, FT232R and FT245R Devices-->
<Device Id="vidpid:0403 6001">
<Function Type="name:vendorSpecific" />
</Device>
<!--FT2232D and FT2232H Devices-->
<Device Id="vidpid:0403 6010">
<Function Type="name:vendorSpecific" />
</Device>
<!--FT4232H Device-->
<Device Id="vidpid:0403 6011">
<Function Type="name:vendorSpecific" />
</Device>
<!--FT232H Device-->
<Device Id="vidpid:0403 6014">
<Function Type="name:vendorSpecific" />
</Device>
<!--FT-X-Series Devices-->
<Device Id="vidpid:0403 6015">
<Function Type="name:vendorSpecific" />
</Device>
<!--My Custom Device-->
<!--<Device Id="vidpid:1234 4321">
<Function Type="name:vendorSpecific" />
</Device>-->
</DeviceCapability>
```
See the sample for how to use the library, more sample code can be found in the download from the FTDI site: http://www.ftdichip.com/Drivers/D2XX.htm
|
Jark/FTDISample
|
README.md
|
Markdown
|
apache-2.0
| 4,160
|
/*
* 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.
*/
/**
*
* @author Usuario
*/
public class Verciones {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
System.out.println("suse");
System.out.println("mandriva");
}
}
|
sebastianhernandezs96/Ejercicio-5
|
Linux/src/Verciones.java
|
Java
|
apache-2.0
| 470
|
package st.domain.quitanda.client.view.adapters.vholders;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.View;
import st.domain.support.android.adapter.BaseRecyclerAdapter;
import st.domain.support.android.adapter.SupportRecyclerAdapter;
import st.domain.quitanda.client.R;
import java.util.List;
/**
* Created by Daniel Costa at 8/27/16.
* Using user computer xdata
*/
public class ListItemSellPayment extends BaseRecyclerAdapter.ItemViewHolder implements SupportRecyclerAdapter.OnCreateViewHolder
{
private final RecyclerView recyclerViewProduct;
private SupportRecyclerAdapter productSelectedAdapters;
public ListItemSellPayment(View itemView)
{
super(itemView);
this.recyclerViewProduct = (RecyclerView) this.itemView.findViewById(R.id.rv_selected_products);
}
@Override
public BaseRecyclerAdapter.ItemViewHolder onCreateViewHolder(View view, int viewType, int onRecyclerViewId)
{
switch (viewType)
{
case R.layout.item_sell:
ListItemView.ItemViewHolder viewHolder = new ListItemView.ItemViewHolder(view, R.id.tv_item_sell_product);
viewHolder.setTextSecond1dId(R.id.tv_item_sell_quantity);
viewHolder.setTextSecond2Id(R.id.tv_item_sell_amount);
view.findViewById(R.id.bt_remove).setVisibility(View.INVISIBLE);
return viewHolder;
}
return null;
}
@Override
public boolean bind(BaseRecyclerAdapter.ItemDataSet dataSet, int position)
{
super.bind(dataSet, position);
if(productSelectedAdapters == null)
{
this.productSelectedAdapters = new SupportRecyclerAdapter(getContext());
List l = productSelectedAdapters.getListDataSet();
ListItemView.TextTreeLineDataSet selected;
l.add(selected = new ListItemView.TextTreeLineDataSet(R.layout.item_sell));
selected.setTextPrimary("Produto 2");
selected.setTextSecond1("30 Kg.");
selected.setTextSecond2("1 788 000,00");
l.add(selected = new ListItemView.TextTreeLineDataSet(R.layout.item_sell));
selected.setTextPrimary("Produto 3");
selected.setTextSecond1("73 Kg.");
selected.setTextSecond2("1 893 000,00");
l.add(selected = new ListItemView.TextTreeLineDataSet(R.layout.item_sell));
selected.setTextPrimary("Produto 18");
selected.setTextSecond1("672 Kg.");
selected.setTextSecond2("1 892 000,00");
StaggeredGridLayoutManager llm = new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL);
this.recyclerViewProduct.setLayoutManager(llm);
this.recyclerViewProduct.setAdapter(this.productSelectedAdapters);
productSelectedAdapters.useTypeViewAsReferenceLayout(true);
productSelectedAdapters.setOnCreateViewHolder(this);
}
return true;
}
}
|
danie555costa/Quitanda
|
app/src/main/java/st/domain/quitanda/client/view/adapters/vholders/ListItemSellPayment.java
|
Java
|
apache-2.0
| 3,071
|
# Meniscium cuspidatum Blume SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Pteridophyta/Polypodiopsida/Polypodiales/Thelypteridaceae/Pronephrium/Pronephrium cuspidatum/ Syn. Meniscium cuspidatum/README.md
|
Markdown
|
apache-2.0
| 183
|
// Copyright 2016-2021 The Libsacloud 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 localrouter
import (
"context"
localrouterBuilder "github.com/sacloud/libsacloud/v2/helper/builder/localrouter"
"github.com/sacloud/libsacloud/v2/sacloud"
"github.com/sacloud/libsacloud/v2/sacloud/types"
)
// Builder ローカルルータの構築を行う
type Builder struct {
ID types.ID
Name string
Description string
Tags types.Tags
IconID types.ID
Switch *sacloud.LocalRouterSwitch
Interface *sacloud.LocalRouterInterface
Peers []*sacloud.LocalRouterPeer
StaticRoutes []*sacloud.LocalRouterStaticRoute
SettingsHash string
Caller sacloud.APICaller
}
func BuilderFromResource(ctx context.Context, caller sacloud.APICaller, id types.ID) (*Builder, error) {
client := sacloud.NewLocalRouterOp(caller)
current, err := client.Read(ctx, id)
if err != nil {
return nil, err
}
return &Builder{
Name: current.Name,
Description: current.Description,
Tags: current.Tags,
IconID: current.IconID,
Switch: current.Switch,
Interface: current.Interface,
Peers: current.Peers,
StaticRoutes: current.StaticRoutes,
Caller: caller,
}, nil
}
func (b *Builder) Build(ctx context.Context) (*sacloud.LocalRouter, error) {
builder := &localrouterBuilder.Builder{
Name: b.Name,
Description: b.Description,
Tags: b.Tags,
IconID: b.IconID,
Switch: b.Switch,
Interface: b.Interface,
Peers: b.Peers,
StaticRoutes: b.StaticRoutes,
SettingsHash: b.SettingsHash,
Client: localrouterBuilder.NewAPIClient(b.Caller),
}
if b.ID.IsEmpty() {
return builder.Build(ctx)
}
return builder.Update(ctx, b.ID)
}
|
yamamoto-febc/usacloud
|
vendor/github.com/sacloud/libsacloud/v2/helper/service/localrouter/builder.go
|
GO
|
apache-2.0
| 2,297
|
# Stencila Node.js
## 👋 Introduction
This is the `stencila` package for Node.js. It uses [`Neon`](https://neon-bindings.com/) to expose functionality implemented in the Stencila [Rust library](../rust) to Node.js. The main use of this package is to provide core functionality to the [Electron](https://www.electronjs.org/)-based [Stencila Desktop](../desktop) application.
## 📦 Install
```sh
npm install stencila
```
## 🚀 Use
```ts
import * as stencila from 'stencila'
```
See the in-code doc comment and the tests for more examples of usage. See the Neon docs for advice on using in [Electron apps](https://neon-bindings.com/docs/electron-apps).
## 🛠️ Develop
### Getting started
Given this package is a set of bindings to the Stencila [Rust library](../rust) you'll need to have [Rust installed](https://rustup.rs) to build it. Then, get started by cloning this repository, installing dependencies and building the package:
```sh
git clone git@github.com:stencila/stencila
cd stencila/node
make setup build
```
Please run formatting, linting and testing before contributing code e.g.
```sh
make format lint test
```
### Testing
There are tests in `src/*.test.ts` files. Note that most of these tests are aimed at picking up regressions in the API of this package, and not of the correctness of the wrapped Rust code for which tests exists in `../rust`.
### Project Layout
This project was bootstrapped by [create-neon](https://www.npmjs.com/package/create-neon). Its directory structure is something like:
```
node/
├── Cargo.toml
├── README.md
├── index.node
├── package.json
├── src/
| └── lib.rs
| └── index.ts
| └── *.rs
| └── *.ts
| └── *.test.ts
```
The `index.node` file is a Node addon—i.e., a binary Node module—generated by building the project. Under the hood, a [Node addon](https://nodejs.org/api/addons.html) is a [dynamically-linked shared object](<https://en.wikipedia.org/wiki/Library_(computing)#Shared_libraries>). The `"build"` script produces this file by copying it from within the `../target/` directory, which is where the Rust build produces the shared object.
### Learn More
To learn more about Neon, see the [Neon documentation](https://neon-bindings.com).
To learn more about Rust, see the [Rust documentation](https://www.rust-lang.org).
To learn more about Node, see the [Node documentation](https://nodejs.org).
|
stencila/stencila
|
node/README.md
|
Markdown
|
apache-2.0
| 2,454
|
function loadNavBar() {'use strict';
var navBarView = Ti.UI.createView({
backgroundImage : '/assets/navBar/backgroundGrey.png',
backgroundColor : '#ffffff',
height : '44dp',
width : '100%',
top : 0
});
// The title
var navBarTitle = Ti.UI.createLabel({
left : 10,
right : 10,
height : 'auto',
textAlign : 'center',
color : '#ffffff',
font : {
fontSize : '22dp',
fontWeight : 'bold'
},
text : "navBarTitle"
});
navBarView.add(navBarTitle);
// The back button
var navBarBack = Ti.UI.createView({
left : '10dp',
height : '28dp',
width : '57dp',
backgroundImage : '/assets/buttons/backButtonGreyOff.png',
zIndex:2
});
navBarBack.addEventListener('click', function() {
navBarView.fireEvent('ratingChanged',{
currentValue:"back"
});
});
var navBarBackText = Ti.UI.createLabel({
top : 0,
left : 10,
right : 0,
bottom : 0,
text : "Back",
textAlign : 'center',
color : '#ffffff',
font : {
fontSize : '16dp',
fontWeight : 'bold'
}
});
// Same trick as the menu to identify the area with a plain view over the top
var navBarButtonView = Ti.UI.createView({
top : 0,
left : 0,
right : 0,
bottom : 0,
backgroundColor : 'transparent',
//OPTION : settingsGlobal.value.OPTIONS.BACK,
TEXT : navBarBackText,
IMAGE : navBarBack
});
var navBarMenu = Ti.UI.createView({
right : '10dp',
height : '28dp',
width : '57dp',
backgroundImage : '/assets/menuBar/menuIconOffGrey.png',
zIndex:2
});
// working ok
navBarMenu.addEventListener('click', function() {
navBarView.fireEvent('ratingChanged',{
currentValue:"home"
});
});
var navBarMenuText = Ti.UI.createLabel({
top : 0,
left : 10,
right : 0,
bottom : 0,
text : "Menu",
textAlign : 'center',
color : '#ffffff',
font : {
fontSize : '16dp',
fontWeight : 'bold'
}
});
var navBarMenuView = Ti.UI.createView({
top : 0,
left : 0,
right : 0,
bottom : 0,
backgroundColor : 'transparent',
TEXT : navBarMenuText,
IMAGE : navBarMenu
});
navBarBack.add(navBarBackText);
navBarView.add(navBarBack);
navBarView.add(navBarButtonView);
navBarMenu.add(navBarMenuText);
navBarView.add(navBarMenu);
navBarView.add(navBarMenuView);
// Always return the view object to the calling window
return navBarView;
}
/*
* EXPORTS SECTION
*/
exports.loadNavBar= loadNavBar;
/*
* END OF FILE
*/
|
andi2/02_singleWindow
|
Resources/ui/customWidgets/navigationBar.js
|
JavaScript
|
apache-2.0
| 3,563
|
package com.example.fw;
import static org.junit.Assert.fail;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import com.opera.core.systems.OperaDriver;
public class WebDriverHelper {
private static WebDriver driver;
private StringBuffer verificationErrors = new StringBuffer();
private final ApplicationManager manager;
public WebDriverHelper(ApplicationManager manager) {
this.manager = manager;
String browser = manager.getProperty("browser");
if ("firefox".equals(browser)) {
driver = new FirefoxDriver();
} else if ("ie".equals(browser)) {
driver = new InternetExplorerDriver();
} else if ("chrome".equals(browser)) {
driver = new ChromeDriver();
} else {
driver = new OperaDriver();
}
driver.manage().timeouts().implicitlyWait(
Integer.parseInt(manager.getProperty("implicitWait", "10")),
TimeUnit.SECONDS);
driver.get(manager.getProperty("baseUrl"));
}
public void stop() {
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
public WebDriver getDriver() {
return driver;
}
}
|
Angy1/mantis-tests
|
src/com/example/fw/WebDriverHelper.java
|
Java
|
apache-2.0
| 1,392
|
/*
ChibiOS/HAL - Copyright (C) 2006-2014 Giovanni Di Sirio
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.
*/
/**
* @file STM32L1xx/stm32_registry.h
* @brief STM32L1xx capabilities registry.
*
* @addtogroup HAL
* @{
*/
#ifndef _STM32_REGISTRY_H_
#define _STM32_REGISTRY_H_
/*===========================================================================*/
/* Platform capabilities. */
/*===========================================================================*/
/**
* @name STM32L1xx capabilities
* @{
*/
#if defined(STM32L1XX_MD) || defined(STM32L1XX_MDP) || defined(__DOXYGEN__)
/* ADC attributes.*/
#define STM32_HAS_ADC1 TRUE
#define STM32_HAS_ADC2 FALSE
#define STM32_HAS_ADC3 FALSE
#define STM32_HAS_ADC4 FALSE
/* CAN attributes.*/
#define STM32_HAS_CAN1 FALSE
#define STM32_HAS_CAN2 FALSE
#define STM32_CAN_MAX_FILTERS 0
/* DAC attributes.*/
#define STM32_HAS_DAC1 TRUE
#define STM32_HAS_DAC2 FALSE
/* DMA attributes.*/
#define STM32_ADVANCED_DMA FALSE
#define STM32_HAS_DMA1 TRUE
#define STM32_HAS_DMA2 FALSE
/* ETH attributes.*/
#define STM32_HAS_ETH FALSE
/* EXTI attributes.*/
#define STM32_EXTI_NUM_CHANNELS 23
/* GPIO attributes.*/
#define STM32_HAS_GPIOA TRUE
#define STM32_HAS_GPIOB TRUE
#define STM32_HAS_GPIOC TRUE
#define STM32_HAS_GPIOD TRUE
#define STM32_HAS_GPIOE TRUE
#define STM32_HAS_GPIOF FALSE
#define STM32_HAS_GPIOG FALSE
#define STM32_HAS_GPIOH TRUE
#define STM32_HAS_GPIOI FALSE
/* I2C attributes.*/
#define STM32_HAS_I2C1 TRUE
#define STM32_I2C_I2C1_RX_DMA_STREAM STM32_DMA_STREAM_ID(1, 7)
#define STM32_I2C_I2C1_TX_DMA_STREAM STM32_DMA_STREAM_ID(1, 6)
#define STM32_HAS_I2C2 TRUE
#define STM32_I2C_I2C2_RX_DMA_STREAM STM32_DMA_STREAM_ID(1, 5)
#define STM32_I2C_I2C2_TX_DMA_STREAM STM32_DMA_STREAM_ID(1, 4)
#define STM32_HAS_I2C3 FALSE
/* RTC attributes.*/
#define STM32_HAS_RTC TRUE
#if defined(STM32L1XX_MDP)
#define STM32_RTC_HAS_SUBSECONDS TRUE
#else
#define STM32_RTC_HAS_SUBSECONDS FALSE
#endif
#define STM32_HAS_RTC TRUE
#define STM32_RTC_HAS_PERIODIC_WAKEUPS TRUE
#define STM32_RTC_NUM_ALARMS 2
#define STM32_RTC_HAS_INTERRUPTS FALSE
/* SDIO attributes.*/
#define STM32_HAS_SDIO TRUE
/* SPI attributes.*/
#define STM32_HAS_SPI1 TRUE
#define STM32_SPI_SPI1_RX_DMA_STREAM STM32_DMA_STREAM_ID(1, 2)
#define STM32_SPI_SPI1_TX_DMA_STREAM STM32_DMA_STREAM_ID(1, 3)
#define STM32_HAS_SPI2 TRUE
#define STM32_SPI_SPI2_RX_DMA_STREAM STM32_DMA_STREAM_ID(1, 4)
#define STM32_SPI_SPI2_TX_DMA_STREAM STM32_DMA_STREAM_ID(1, 5)
#define STM32_HAS_SPI3 FALSE
#define STM32_HAS_SPI4 FALSE
#define STM32_HAS_SPI5 FALSE
#define STM32_HAS_SPI6 FALSE
/* TIM attributes.*/
#define STM32_TIM_MAX_CHANNELS 4
#define STM32_HAS_TIM2 TRUE
#define STM32_TIM2_IS_32BITS FALSE
#define STM32_TIM2_CHANNELS 4
#define STM32_HAS_TIM3 TRUE
#define STM32_TIM3_IS_32BITS FALSE
#define STM32_TIM3_CHANNELS 4
#define STM32_HAS_TIM4 TRUE
#define STM32_TIM4_IS_32BITS FALSE
#define STM32_TIM4_CHANNELS 4
#define STM32_HAS_TIM6 TRUE
#define STM32_TIM6_IS_32BITS FALSE
#define STM32_TIM6_CHANNELS 0
#define STM32_HAS_TIM7 TRUE
#define STM32_TIM7_IS_32BITS FALSE
#define STM32_TIM7_CHANNELS 0
#define STM32_HAS_TIM9 TRUE
#define STM32_TIM9_IS_32BITS FALSE
#define STM32_TIM9_CHANNELS 2
#define STM32_HAS_TIM10 TRUE
#define STM32_TIM10_IS_32BITS FALSE
#define STM32_TIM10_CHANNELS 2
#define STM32_HAS_TIM11 TRUE
#define STM32_TIM11_IS_32BITS FALSE
#define STM32_TIM11_CHANNELS 2
#define STM32_HAS_TIM1 FALSE
#define STM32_HAS_TIM5 FALSE
#define STM32_HAS_TIM8 FALSE
#define STM32_HAS_TIM12 FALSE
#define STM32_HAS_TIM13 FALSE
#define STM32_HAS_TIM14 FALSE
#define STM32_HAS_TIM15 FALSE
#define STM32_HAS_TIM16 FALSE
#define STM32_HAS_TIM17 FALSE
#define STM32_HAS_TIM18 FALSE
#define STM32_HAS_TIM19 FALSE
/* USART attributes.*/
#define STM32_HAS_USART1 TRUE
#define STM32_UART_USART1_RX_DMA_STREAM STM32_DMA_STREAM_ID(1, 5)
#define STM32_UART_USART1_TX_DMA_STREAM STM32_DMA_STREAM_ID(1, 4)
#define STM32_HAS_USART2 TRUE
#define STM32_UART_USART2_RX_DMA_STREAM STM32_DMA_STREAM_ID(1, 6)
#define STM32_UART_USART2_TX_DMA_STREAM STM32_DMA_STREAM_ID(1, 7)
#define STM32_HAS_USART3 TRUE
#define STM32_UART_USART3_RX_DMA_STREAM STM32_DMA_STREAM_ID(1, 3)
#define STM32_UART_USART3_TX_DMA_STREAM STM32_DMA_STREAM_ID(1, 2)
#define STM32_HAS_UART4 FALSE
#define STM32_HAS_UART5 FALSE
#define STM32_HAS_USART6 FALSE
/* USB attributes.*/
#define STM32_HAS_USB TRUE
#define STM32_HAS_OTG1 FALSE
#define STM32_HAS_OTG2 FALSE
#else /* STM32L1XX_HD */
/* ADC attributes.*/
#define STM32_HAS_ADC1 TRUE
#define STM32_HAS_ADC2 FALSE
#define STM32_HAS_ADC3 FALSE
#define STM32_HAS_ADC4 FALSE
/* CAN attributes.*/
#define STM32_HAS_CAN1 FALSE
#define STM32_HAS_CAN2 FALSE
#define STM32_CAN_MAX_FILTERS 0
/* DAC attributes.*/
#define STM32_HAS_DAC1 TRUE
#define STM32_HAS_DAC2 FALSE
/* DMA attributes.*/
#define STM32_ADVANCED_DMA FALSE
#define STM32_HAS_DMA1 TRUE
#define STM32_HAS_DMA2 TRUE
/* ETH attributes.*/
#define STM32_HAS_ETH FALSE
/* EXTI attributes.*/
#define STM32_EXTI_NUM_CHANNELS 24
/* GPIO attributes.*/
#define STM32_HAS_GPIOA TRUE
#define STM32_HAS_GPIOB TRUE
#define STM32_HAS_GPIOC TRUE
#define STM32_HAS_GPIOD TRUE
#define STM32_HAS_GPIOE TRUE
#define STM32_HAS_GPIOF TRUE
#define STM32_HAS_GPIOG TRUE
#define STM32_HAS_GPIOH TRUE
#define STM32_HAS_GPIOI FALSE
/* I2C attributes.*/
#define STM32_HAS_I2C1 TRUE
#define STM32_I2C_I2C1_RX_DMA_STREAM STM32_DMA_STREAM_ID(1, 7)
#define STM32_I2C_I2C1_TX_DMA_STREAM STM32_DMA_STREAM_ID(1, 6)
#define STM32_HAS_I2C2 TRUE
#define STM32_I2C_I2C2_RX_DMA_STREAM STM32_DMA_STREAM_ID(1, 5)
#define STM32_I2C_I2C2_TX_DMA_STREAM STM32_DMA_STREAM_ID(1, 4)
#define STM32_HAS_I2C3 FALSE
/* RTC attributes.*/
#define STM32_HAS_RTC TRUE
#define STM32_RTC_HAS_SUBSECONDS TRUE
#define STM32_RTC_HAS_PERIODIC_WAKEUPS TRUE
#define STM32_RTC_NUM_ALARMS 2
#define STM32_RTC_HAS_INTERRUPTS FALSE
/* SDIO attributes.*/
#define STM32_HAS_SDIO TRUE
/* SPI attributes.*/
#define STM32_HAS_SPI1 TRUE
#define STM32_SPI_SPI1_RX_DMA_STREAM STM32_DMA_STREAM_ID(1, 2)
#define STM32_SPI_SPI1_TX_DMA_STREAM STM32_DMA_STREAM_ID(1, 3)
#define STM32_HAS_SPI2 TRUE
#define STM32_SPI_SPI2_RX_DMA_STREAM STM32_DMA_STREAM_ID(1, 4)
#define STM32_SPI_SPI2_TX_DMA_STREAM STM32_DMA_STREAM_ID(1, 5)
#define STM32_HAS_SPI3 TRUE
#define STM32_SPI_SPI3_RX_DMA_STREAM STM32_DMA_STREAM_ID(2, 1)
#define STM32_SPI_SPI3_TX_DMA_STREAM STM32_DMA_STREAM_ID(2, 2)
#define STM32_HAS_SPI4 FALSE
#define STM32_HAS_SPI5 FALSE
#define STM32_HAS_SPI6 FALSE
/* TIM attributes.*/
#define STM32_TIM_MAX_CHANNELS 4
#define STM32_HAS_TIM2 TRUE
#define STM32_TIM2_IS_32BITS FALSE
#define STM32_TIM2_CHANNELS 4
#define STM32_HAS_TIM3 TRUE
#define STM32_TIM3_IS_32BITS FALSE
#define STM32_TIM3_CHANNELS 4
#define STM32_HAS_TIM4 TRUE
#define STM32_TIM4_IS_32BITS FALSE
#define STM32_TIM4_CHANNELS 4
#define STM32_HAS_TIM5 TRUE
#define STM32_TIM5_IS_32BITS TRUE
#define STM32_TIM5_CHANNELS 4
#define STM32_HAS_TIM6 TRUE
#define STM32_TIM6_IS_32BITS FALSE
#define STM32_TIM6_CHANNELS 0
#define STM32_HAS_TIM7 TRUE
#define STM32_TIM7_IS_32BITS FALSE
#define STM32_TIM7_CHANNELS 0
#define STM32_HAS_TIM9 TRUE
#define STM32_TIM9_IS_32BITS FALSE
#define STM32_TIM9_CHANNELS 2
#define STM32_HAS_TIM10 TRUE
#define STM32_TIM10_IS_32BITS FALSE
#define STM32_TIM10_CHANNELS 2
#define STM32_HAS_TIM11 TRUE
#define STM32_TIM11_IS_32BITS FALSE
#define STM32_TIM11_CHANNELS 2
#define STM32_HAS_TIM1 FALSE
#define STM32_HAS_TIM8 FALSE
#define STM32_HAS_TIM12 FALSE
#define STM32_HAS_TIM13 FALSE
#define STM32_HAS_TIM14 FALSE
#define STM32_HAS_TIM15 FALSE
#define STM32_HAS_TIM16 FALSE
#define STM32_HAS_TIM17 FALSE
#define STM32_HAS_TIM18 FALSE
#define STM32_HAS_TIM19 FALSE
/* USART attributes.*/
#define STM32_HAS_USART1 TRUE
#define STM32_UART_USART1_RX_DMA_STREAM STM32_DMA_STREAM_ID(1, 5)
#define STM32_UART_USART1_TX_DMA_STREAM STM32_DMA_STREAM_ID(1, 4)
#define STM32_HAS_USART2 TRUE
#define STM32_UART_USART2_RX_DMA_STREAM STM32_DMA_STREAM_ID(1, 6)
#define STM32_UART_USART2_TX_DMA_STREAM STM32_DMA_STREAM_ID(1, 7)
#define STM32_HAS_USART3 TRUE
#define STM32_UART_USART3_RX_DMA_STREAM STM32_DMA_STREAM_ID(1, 3)
#define STM32_UART_USART3_TX_DMA_STREAM STM32_DMA_STREAM_ID(1, 2)
#define STM32_HAS_UART4 TRUE
#define STM32_UART_UART4_RX_DMA_STREAM STM32_DMA_STREAM_ID(2, 3)
#define STM32_UART_UART4_TX_DMA_STREAM STM32_DMA_STREAM_ID(2, 5)
#define STM32_HAS_UART5 TRUE
#define STM32_UART_UART5_RX_DMA_STREAM STM32_DMA_STREAM_ID(2, 2)
#define STM32_UART_UART5_TX_DMA_STREAM STM32_DMA_STREAM_ID(2, 1)
#define STM32_HAS_USART6 FALSE
/* USB attributes.*/
#define STM32_HAS_USB TRUE
#define STM32_HAS_OTG1 FALSE
#define STM32_HAS_OTG2 FALSE
#endif /* STM32L1XX_HD */
/** @} */
#endif /* _STM32_REGISTRY_H_ */
/** @} */
|
marcoveeneman/ChibiOS-Tiva
|
os/hal/ports/STM32/STM32L1xx/stm32_registry.h
|
C
|
apache-2.0
| 12,695
|
/*!
* jQuery UI 1.8.1
*
* Copyright (c) 2010 AUTHORS.txt (http://jqueryui.com/about)
* Dual licensed under the MIT (MIT-LICENSE.txt)
* and GPL (GPL-LICENSE.txt) licenses.
*
* http://docs.jquery.com/UI
*/
jQuery.ui||function(c){c.ui={version:"1.8.1",plugin:{add:function(a,b,d){a=c.ui[a].prototype;for(var e in d){a.plugins[e]=a.plugins[e]||[];a.plugins[e].push([b,d[e]])}},call:function(a,b,d){if((b=a.plugins[b])&&a.element[0].parentNode)for(var e=0;e<b.length;e++)a.options[b[e][0]]&&b[e][1].apply(a.element,d)}},contains:function(a,b){return document.compareDocumentPosition?a.compareDocumentPosition(b)&16:a!==b&&a.contains(b)},hasScroll:function(a,b){if(c(a).css("overflow")=="hidden")return false;
b=b&&b=="left"?"scrollLeft":"scrollTop";var d=false;if(a[b]>0)return true;a[b]=1;d=a[b]>0;a[b]=0;return d},isOverAxis:function(a,b,d){return a>b&&a<b+d},isOver:function(a,b,d,e,f,g){return c.ui.isOverAxis(a,d,f)&&c.ui.isOverAxis(b,e,g)},keyCode:{ALT:18,BACKSPACE:8,CAPS_LOCK:20,COMMA:188,CONTROL:17,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,INSERT:45,LEFT:37,NUMPAD_ADD:107,NUMPAD_DECIMAL:110,NUMPAD_DIVIDE:111,NUMPAD_ENTER:108,NUMPAD_MULTIPLY:106,NUMPAD_SUBTRACT:109,PAGE_DOWN:34,PAGE_UP:33,
PERIOD:190,RIGHT:39,SHIFT:16,SPACE:32,TAB:9,UP:38}};c.fn.extend({_focus:c.fn.focus,focus:function(a,b){return typeof a==="number"?this.each(function(){var d=this;setTimeout(function(){c(d).focus();b&&b.call(d)},a)}):this._focus.apply(this,arguments)},enableSelection:function(){return this.attr("unselectable","off").css("MozUserSelect","")},disableSelection:function(){return this.attr("unselectable","on").css("MozUserSelect","none")},scrollParent:function(){var a;a=c.browser.msie&&/(static|relative)/.test(this.css("position"))||
/absolute/.test(this.css("position"))?this.parents().filter(function(){return/(relative|absolute|fixed)/.test(c.curCSS(this,"position",1))&&/(auto|scroll)/.test(c.curCSS(this,"overflow",1)+c.curCSS(this,"overflow-y",1)+c.curCSS(this,"overflow-x",1))}).eq(0):this.parents().filter(function(){return/(auto|scroll)/.test(c.curCSS(this,"overflow",1)+c.curCSS(this,"overflow-y",1)+c.curCSS(this,"overflow-x",1))}).eq(0);return/fixed/.test(this.css("position"))||!a.length?c(document):a},zIndex:function(a){if(a!==
undefined)return this.css("zIndex",a);if(this.length){a=c(this[0]);for(var b;a.length&&a[0]!==document;){b=a.css("position");if(b=="absolute"||b=="relative"||b=="fixed"){b=parseInt(a.css("zIndex"));if(!isNaN(b)&&b!=0)return b}a=a.parent()}}return 0}});c.extend(c.expr[":"],{data:function(a,b,d){return!!c.data(a,d[3])},focusable:function(a){var b=a.nodeName.toLowerCase(),d=c.attr(a,"tabindex");return(/input|select|textarea|button|object/.test(b)?!a.disabled:"a"==b||"area"==b?a.href||!isNaN(d):!isNaN(d))&&
!c(a)["area"==b?"parents":"closest"](":hidden").length},tabbable:function(a){var b=c.attr(a,"tabindex");return(isNaN(b)||b>=0)&&c(a).is(":focusable")}})}(jQuery);
;/*!
* jQuery UI Widget 1.8.1
*
* Copyright (c) 2010 AUTHORS.txt (http://jqueryui.com/about)
* Dual licensed under the MIT (MIT-LICENSE.txt)
* and GPL (GPL-LICENSE.txt) licenses.
*
* http://docs.jquery.com/UI/Widget
*/
(function(b){var j=b.fn.remove;b.fn.remove=function(a,c){return this.each(function(){if(!c)if(!a||b.filter(a,[this]).length)b("*",this).add(this).each(function(){b(this).triggerHandler("remove")});return j.call(b(this),a,c)})};b.widget=function(a,c,d){var e=a.split(".")[0],f;a=a.split(".")[1];f=e+"-"+a;if(!d){d=c;c=b.Widget}b.expr[":"][f]=function(h){return!!b.data(h,a)};b[e]=b[e]||{};b[e][a]=function(h,g){arguments.length&&this._createWidget(h,g)};c=new c;c.options=b.extend({},c.options);b[e][a].prototype=
b.extend(true,c,{namespace:e,widgetName:a,widgetEventPrefix:b[e][a].prototype.widgetEventPrefix||a,widgetBaseClass:f},d);b.widget.bridge(a,b[e][a])};b.widget.bridge=function(a,c){b.fn[a]=function(d){var e=typeof d==="string",f=Array.prototype.slice.call(arguments,1),h=this;d=!e&&f.length?b.extend.apply(null,[true,d].concat(f)):d;if(e&&d.substring(0,1)==="_")return h;e?this.each(function(){var g=b.data(this,a),i=g&&b.isFunction(g[d])?g[d].apply(g,f):g;if(i!==g&&i!==undefined){h=i;return false}}):this.each(function(){var g=
b.data(this,a);if(g){d&&g.option(d);g._init()}else b.data(this,a,new c(d,this))});return h}};b.Widget=function(a,c){arguments.length&&this._createWidget(a,c)};b.Widget.prototype={widgetName:"widget",widgetEventPrefix:"",options:{disabled:false},_createWidget:function(a,c){this.element=b(c).data(this.widgetName,this);this.options=b.extend(true,{},this.options,b.metadata&&b.metadata.get(c)[this.widgetName],a);var d=this;this.element.bind("remove."+this.widgetName,function(){d.destroy()});this._create();
this._init()},_create:function(){},_init:function(){},destroy:function(){this.element.unbind("."+this.widgetName).removeData(this.widgetName);this.widget().unbind("."+this.widgetName).removeAttr("aria-disabled").removeClass(this.widgetBaseClass+"-disabled ui-state-disabled")},widget:function(){return this.element},option:function(a,c){var d=a,e=this;if(arguments.length===0)return b.extend({},e.options);if(typeof a==="string"){if(c===undefined)return this.options[a];d={};d[a]=c}b.each(d,function(f,
h){e._setOption(f,h)});return e},_setOption:function(a,c){this.options[a]=c;if(a==="disabled")this.widget()[c?"addClass":"removeClass"](this.widgetBaseClass+"-disabled ui-state-disabled").attr("aria-disabled",c);return this},enable:function(){return this._setOption("disabled",false)},disable:function(){return this._setOption("disabled",true)},_trigger:function(a,c,d){var e=this.options[a];c=b.Event(c);c.type=(a===this.widgetEventPrefix?a:this.widgetEventPrefix+a).toLowerCase();d=d||{};if(c.originalEvent){a=
b.event.props.length;for(var f;a;){f=b.event.props[--a];c[f]=c.originalEvent[f]}}this.element.trigger(c,d);return!(b.isFunction(e)&&e.call(this.element[0],c,d)===false||c.isDefaultPrevented())}}})(jQuery);
;/*
* jQuery UI Position 1.8.1
*
* Copyright (c) 2010 AUTHORS.txt (http://jqueryui.com/about)
* Dual licensed under the MIT (MIT-LICENSE.txt)
* and GPL (GPL-LICENSE.txt) licenses.
*
* http://docs.jquery.com/UI/Position
*/
(function(c){c.ui=c.ui||{};var m=/left|center|right/,n=/top|center|bottom/,p=c.fn.position,q=c.fn.offset;c.fn.position=function(a){if(!a||!a.of)return p.apply(this,arguments);a=c.extend({},a);var b=c(a.of),d=(a.collision||"flip").split(" "),e=a.offset?a.offset.split(" "):[0,0],g,h,i;if(a.of.nodeType===9){g=b.width();h=b.height();i={top:0,left:0}}else if(a.of.scrollTo&&a.of.document){g=b.width();h=b.height();i={top:b.scrollTop(),left:b.scrollLeft()}}else if(a.of.preventDefault){a.at="left top";g=h=
0;i={top:a.of.pageY,left:a.of.pageX}}else{g=b.outerWidth();h=b.outerHeight();i=b.offset()}c.each(["my","at"],function(){var f=(a[this]||"").split(" ");if(f.length===1)f=m.test(f[0])?f.concat(["center"]):n.test(f[0])?["center"].concat(f):["center","center"];f[0]=m.test(f[0])?f[0]:"center";f[1]=n.test(f[1])?f[1]:"center";a[this]=f});if(d.length===1)d[1]=d[0];e[0]=parseInt(e[0],10)||0;if(e.length===1)e[1]=e[0];e[1]=parseInt(e[1],10)||0;if(a.at[0]==="right")i.left+=g;else if(a.at[0]==="center")i.left+=
g/2;if(a.at[1]==="bottom")i.top+=h;else if(a.at[1]==="center")i.top+=h/2;i.left+=e[0];i.top+=e[1];return this.each(function(){var f=c(this),k=f.outerWidth(),l=f.outerHeight(),j=c.extend({},i);if(a.my[0]==="right")j.left-=k;else if(a.my[0]==="center")j.left-=k/2;if(a.my[1]==="bottom")j.top-=l;else if(a.my[1]==="center")j.top-=l/2;j.left=parseInt(j.left);j.top=parseInt(j.top);c.each(["left","top"],function(o,r){c.ui.position[d[o]]&&c.ui.position[d[o]][r](j,{targetWidth:g,targetHeight:h,elemWidth:k,
elemHeight:l,offset:e,my:a.my,at:a.at})});c.fn.bgiframe&&f.bgiframe();f.offset(c.extend(j,{using:a.using}))})};c.ui.position={fit:{left:function(a,b){var d=c(window);b=a.left+b.elemWidth-d.width()-d.scrollLeft();a.left=b>0?a.left-b:Math.max(0,a.left)},top:function(a,b){var d=c(window);b=a.top+b.elemHeight-d.height()-d.scrollTop();a.top=b>0?a.top-b:Math.max(0,a.top)}},flip:{left:function(a,b){if(b.at[0]!=="center"){var d=c(window);d=a.left+b.elemWidth-d.width()-d.scrollLeft();var e=b.my[0]==="left"?
-b.elemWidth:b.my[0]==="right"?b.elemWidth:0,g=-2*b.offset[0];a.left+=a.left<0?e+b.targetWidth+g:d>0?e-b.targetWidth+g:0}},top:function(a,b){if(b.at[1]!=="center"){var d=c(window);d=a.top+b.elemHeight-d.height()-d.scrollTop();var e=b.my[1]==="top"?-b.elemHeight:b.my[1]==="bottom"?b.elemHeight:0,g=b.at[1]==="top"?b.targetHeight:-b.targetHeight,h=-2*b.offset[1];a.top+=a.top<0?e+b.targetHeight+h:d>0?e+g+h:0}}}};if(!c.offset.setOffset){c.offset.setOffset=function(a,b){if(/static/.test(c.curCSS(a,"position")))a.style.position=
"relative";var d=c(a),e=d.offset(),g=parseInt(c.curCSS(a,"top",true),10)||0,h=parseInt(c.curCSS(a,"left",true),10)||0;e={top:b.top-e.top+g,left:b.left-e.left+h};"using"in b?b.using.call(a,e):d.css(e)};c.fn.offset=function(a){var b=this[0];if(!b||!b.ownerDocument)return null;if(a)return this.each(function(){c.offset.setOffset(this,a)});return q.call(this)}}})(jQuery);
;/*
* jQuery UI Dialog 1.8.1
*
* Copyright (c) 2010 AUTHORS.txt (http://jqueryui.com/about)
* Dual licensed under the MIT (MIT-LICENSE.txt)
* and GPL (GPL-LICENSE.txt) licenses.
*
* http://docs.jquery.com/UI/Dialog
*
* Depends:
* jquery.ui.core.js
* jquery.ui.widget.js
* jquery.ui.button.js
* jquery.ui.draggable.js
* jquery.ui.mouse.js
* jquery.ui.position.js
* jquery.ui.resizable.js
*/
(function(c){c.widget("ui.dialog",{options:{autoOpen:true,buttons:{},closeOnEscape:true,closeText:"close",dialogClass:"",draggable:true,hide:null,height:"auto",maxHeight:false,maxWidth:false,minHeight:150,minWidth:150,modal:false,position:"center",resizable:true,show:null,stack:true,title:"",width:300,zIndex:1E3},_create:function(){this.originalTitle=this.element.attr("title");var a=this,b=a.options,d=b.title||a.originalTitle||" ",e=c.ui.dialog.getTitleId(a.element),g=(a.uiDialog=c("<div></div>")).appendTo(document.body).hide().addClass("ui-dialog ui-widget ui-widget-content ui-corner-all "+
b.dialogClass).css({zIndex:b.zIndex}).attr("tabIndex",-1).css("outline",0).keydown(function(i){if(b.closeOnEscape&&i.keyCode&&i.keyCode===c.ui.keyCode.ESCAPE){a.close(i);i.preventDefault()}}).attr({role:"dialog","aria-labelledby":e}).mousedown(function(i){a.moveToTop(false,i)});a.element.show().removeAttr("title").addClass("ui-dialog-content ui-widget-content").appendTo(g);var f=(a.uiDialogTitlebar=c("<div></div>")).addClass("ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix").prependTo(g),
h=c('<a href="#"></a>').addClass("ui-dialog-titlebar-close ui-corner-all").attr("role","button").hover(function(){h.addClass("ui-state-hover")},function(){h.removeClass("ui-state-hover")}).focus(function(){h.addClass("ui-state-focus")}).blur(function(){h.removeClass("ui-state-focus")}).click(function(i){a.close(i);return false}).appendTo(f);(a.uiDialogTitlebarCloseText=c("<span></span>")).addClass("ui-icon ui-icon-closethick").text(b.closeText).appendTo(h);c("<span></span>").addClass("ui-dialog-title").attr("id",
e).html(d).prependTo(f);if(c.isFunction(b.beforeclose)&&!c.isFunction(b.beforeClose))b.beforeClose=b.beforeclose;f.find("*").add(f).disableSelection();b.draggable&&c.fn.draggable&&a._makeDraggable();b.resizable&&c.fn.resizable&&a._makeResizable();a._createButtons(b.buttons);a._isOpen=false;c.fn.bgiframe&&g.bgiframe()},_init:function(){this.options.autoOpen&&this.open()},destroy:function(){var a=this;a.overlay&&a.overlay.destroy();a.uiDialog.hide();a.element.unbind(".dialog").removeData("dialog").removeClass("ui-dialog-content ui-widget-content").hide().appendTo("body");
a.uiDialog.remove();a.originalTitle&&a.element.attr("title",a.originalTitle);return a},widget:function(){return this.uiDialog},close:function(a){var b=this,d;if(false!==b._trigger("beforeClose",a)){b.overlay&&b.overlay.destroy();b.uiDialog.unbind("keypress.ui-dialog");b._isOpen=false;if(b.options.hide)b.uiDialog.hide(b.options.hide,function(){b._trigger("close",a)});else{b.uiDialog.hide();b._trigger("close",a)}c.ui.dialog.overlay.resize();if(b.options.modal){d=0;c(".ui-dialog").each(function(){if(this!==
b.uiDialog[0])d=Math.max(d,c(this).css("z-index"))});c.ui.dialog.maxZ=d}return b}},isOpen:function(){return this._isOpen},moveToTop:function(a,b){var d=this,e=d.options;if(e.modal&&!a||!e.stack&&!e.modal)return d._trigger("focus",b);if(e.zIndex>c.ui.dialog.maxZ)c.ui.dialog.maxZ=e.zIndex;if(d.overlay){c.ui.dialog.maxZ+=1;d.overlay.$el.css("z-index",c.ui.dialog.overlay.maxZ=c.ui.dialog.maxZ)}a={scrollTop:d.element.attr("scrollTop"),scrollLeft:d.element.attr("scrollLeft")};c.ui.dialog.maxZ+=1;d.uiDialog.css("z-index",
c.ui.dialog.maxZ);d.element.attr(a);d._trigger("focus",b);return d},open:function(){if(!this._isOpen){var a=this,b=a.options,d=a.uiDialog;a.overlay=b.modal?new c.ui.dialog.overlay(a):null;d.next().length&&d.appendTo("body");a._size();a._position(b.position);d.show(b.show);a.moveToTop(true);b.modal&&d.bind("keypress.ui-dialog",function(e){if(e.keyCode===c.ui.keyCode.TAB){var g=c(":tabbable",this),f=g.filter(":first");g=g.filter(":last");if(e.target===g[0]&&!e.shiftKey){f.focus(1);return false}else if(e.target===
f[0]&&e.shiftKey){g.focus(1);return false}}});c([]).add(d.find(".ui-dialog-content :tabbable:first")).add(d.find(".ui-dialog-buttonpane :tabbable:first")).add(d).filter(":first").focus();a._trigger("open");a._isOpen=true;return a}},_createButtons:function(a){var b=this,d=false,e=c("<div></div>").addClass("ui-dialog-buttonpane ui-widget-content ui-helper-clearfix");b.uiDialog.find(".ui-dialog-buttonpane").remove();typeof a==="object"&&a!==null&&c.each(a,function(){return!(d=true)});if(d){c.each(a,
function(g,f){g=c('<button type="button"></button>').text(g).click(function(){f.apply(b.element[0],arguments)}).appendTo(e);c.fn.button&&g.button()});e.appendTo(b.uiDialog)}},_makeDraggable:function(){function a(f){return{position:f.position,offset:f.offset}}var b=this,d=b.options,e=c(document),g;b.uiDialog.draggable({cancel:".ui-dialog-content, .ui-dialog-titlebar-close",handle:".ui-dialog-titlebar",containment:"document",start:function(f,h){g=d.height==="auto"?"auto":c(this).height();c(this).height(c(this).height()).addClass("ui-dialog-dragging");
b._trigger("dragStart",f,a(h))},drag:function(f,h){b._trigger("drag",f,a(h))},stop:function(f,h){d.position=[h.position.left-e.scrollLeft(),h.position.top-e.scrollTop()];c(this).removeClass("ui-dialog-dragging").height(g);b._trigger("dragStop",f,a(h));c.ui.dialog.overlay.resize()}})},_makeResizable:function(a){function b(f){return{originalPosition:f.originalPosition,originalSize:f.originalSize,position:f.position,size:f.size}}a=a===undefined?this.options.resizable:a;var d=this,e=d.options,g=d.uiDialog.css("position");
a=typeof a==="string"?a:"n,e,s,w,se,sw,ne,nw";d.uiDialog.resizable({cancel:".ui-dialog-content",containment:"document",alsoResize:d.element,maxWidth:e.maxWidth,maxHeight:e.maxHeight,minWidth:e.minWidth,minHeight:d._minHeight(),handles:a,start:function(f,h){c(this).addClass("ui-dialog-resizing");d._trigger("resizeStart",f,b(h))},resize:function(f,h){d._trigger("resize",f,b(h))},stop:function(f,h){c(this).removeClass("ui-dialog-resizing");e.height=c(this).height();e.width=c(this).width();d._trigger("resizeStop",
f,b(h));c.ui.dialog.overlay.resize()}}).css("position",g).find(".ui-resizable-se").addClass("ui-icon ui-icon-grip-diagonal-se")},_minHeight:function(){var a=this.options;return a.height==="auto"?a.minHeight:Math.min(a.minHeight,a.height)},_position:function(a){var b=[],d=[0,0];a=a||c.ui.dialog.prototype.options.position;if(typeof a==="string"||typeof a==="object"&&"0"in a){b=a.split?a.split(" "):[a[0],a[1]];if(b.length===1)b[1]=b[0];c.each(["left","top"],function(e,g){if(+b[e]===b[e]){d[e]=b[e];b[e]=
g}})}else if(typeof a==="object"){if("left"in a){b[0]="left";d[0]=a.left}else if("right"in a){b[0]="right";d[0]=-a.right}if("top"in a){b[1]="top";d[1]=a.top}else if("bottom"in a){b[1]="bottom";d[1]=-a.bottom}}(a=this.uiDialog.is(":visible"))||this.uiDialog.show();this.uiDialog.css({top:0,left:0}).position({my:b.join(" "),at:b.join(" "),offset:d.join(" "),of:window,collision:"fit",using:function(e){var g=c(this).css(e).offset().top;g<0&&c(this).css("top",e.top-g)}});a||this.uiDialog.hide()},_setOption:function(a,
b){var d=this,e=d.uiDialog,g=e.is(":data(resizable)"),f=false;switch(a){case "beforeclose":a="beforeClose";break;case "buttons":d._createButtons(b);break;case "closeText":d.uiDialogTitlebarCloseText.text(""+b);break;case "dialogClass":e.removeClass(d.options.dialogClass).addClass("ui-dialog ui-widget ui-widget-content ui-corner-all "+b);break;case "disabled":b?e.addClass("ui-dialog-disabled"):e.removeClass("ui-dialog-disabled");break;case "draggable":b?d._makeDraggable():e.draggable("destroy");break;
case "height":f=true;break;case "maxHeight":g&&e.resizable("option","maxHeight",b);f=true;break;case "maxWidth":g&&e.resizable("option","maxWidth",b);f=true;break;case "minHeight":g&&e.resizable("option","minHeight",b);f=true;break;case "minWidth":g&&e.resizable("option","minWidth",b);f=true;break;case "position":d._position(b);break;case "resizable":g&&!b&&e.resizable("destroy");g&&typeof b==="string"&&e.resizable("option","handles",b);!g&&b!==false&&d._makeResizable(b);break;case "title":c(".ui-dialog-title",
d.uiDialogTitlebar).html(""+(b||" "));break;case "width":f=true;break}c.Widget.prototype._setOption.apply(d,arguments);f&&d._size()},_size:function(){var a=this.options,b;this.element.css({width:"auto",minHeight:0,height:0});b=this.uiDialog.css({height:"auto",width:a.width}).height();this.element.css(a.height==="auto"?{minHeight:Math.max(a.minHeight-b,0),height:"auto"}:{minHeight:0,height:Math.max(a.height-b,0)}).show();this.uiDialog.is(":data(resizable)")&&this.uiDialog.resizable("option","minHeight",
this._minHeight())}});c.extend(c.ui.dialog,{version:"1.8.1",uuid:0,maxZ:0,getTitleId:function(a){a=a.attr("id");if(!a){this.uuid+=1;a=this.uuid}return"ui-dialog-title-"+a},overlay:function(a){this.$el=c.ui.dialog.overlay.create(a)}});c.extend(c.ui.dialog.overlay,{instances:[],oldInstances:[],maxZ:0,events:c.map("focus,mousedown,mouseup,keydown,keypress,click".split(","),function(a){return a+".dialog-overlay"}).join(" "),create:function(a){if(this.instances.length===0){setTimeout(function(){c.ui.dialog.overlay.instances.length&&
c(document).bind(c.ui.dialog.overlay.events,function(d){return c(d.target).zIndex()>=c.ui.dialog.overlay.maxZ})},1);c(document).bind("keydown.dialog-overlay",function(d){if(a.options.closeOnEscape&&d.keyCode&&d.keyCode===c.ui.keyCode.ESCAPE){a.close(d);d.preventDefault()}});c(window).bind("resize.dialog-overlay",c.ui.dialog.overlay.resize)}var b=(this.oldInstances.pop()||c("<div></div>").addClass("ui-widget-overlay")).appendTo(document.body).css({width:this.width(),height:this.height()});c.fn.bgiframe&&
b.bgiframe();this.instances.push(b);return b},destroy:function(a){this.oldInstances.push(this.instances.splice(c.inArray(a,this.instances),1)[0]);this.instances.length===0&&c([document,window]).unbind(".dialog-overlay");a.remove();var b=0;c.each(this.instances,function(){b=Math.max(b,this.css("z-index"))});this.maxZ=b},height:function(){var a,b;if(c.browser.msie&&c.browser.version<7){a=Math.max(document.documentElement.scrollHeight,document.body.scrollHeight);b=Math.max(document.documentElement.offsetHeight,
document.body.offsetHeight);return a<b?c(window).height()+"px":a+"px"}else return c(document).height()+"px"},width:function(){var a,b;if(c.browser.msie&&c.browser.version<7){a=Math.max(document.documentElement.scrollWidth,document.body.scrollWidth);b=Math.max(document.documentElement.offsetWidth,document.body.offsetWidth);return a<b?c(window).width()+"px":a+"px"}else return c(document).width()+"px"},resize:function(){var a=c([]);c.each(c.ui.dialog.overlay.instances,function(){a=a.add(this)});a.css({width:0,
height:0}).css({width:c.ui.dialog.overlay.width(),height:c.ui.dialog.overlay.height()})}});c.extend(c.ui.dialog.overlay.prototype,{destroy:function(){c.ui.dialog.overlay.destroy(this.$el)}})})(jQuery);
;/*
* jQuery UI Tabs 1.8.1
*
* Copyright (c) 2010 AUTHORS.txt (http://jqueryui.com/about)
* Dual licensed under the MIT (MIT-LICENSE.txt)
* and GPL (GPL-LICENSE.txt) licenses.
*
* http://docs.jquery.com/UI/Tabs
*
* Depends:
* jquery.ui.core.js
* jquery.ui.widget.js
*/
(function(d){var s=0,u=0;d.widget("ui.tabs",{options:{add:null,ajaxOptions:null,cache:false,cookie:null,collapsible:false,disable:null,disabled:[],enable:null,event:"click",fx:null,idPrefix:"ui-tabs-",load:null,panelTemplate:"<div></div>",remove:null,select:null,show:null,spinner:"<em>Loading…</em>",tabTemplate:'<li><a href="#{href}"><span>#{label}</span></a></li>'},_create:function(){this._tabify(true)},_setOption:function(c,e){if(c=="selected")this.options.collapsible&&e==this.options.selected||
this.select(e);else{this.options[c]=e;this._tabify()}},_tabId:function(c){return c.title&&c.title.replace(/\s/g,"_").replace(/[^A-Za-z0-9\-_:\.]/g,"")||this.options.idPrefix+ ++s},_sanitizeSelector:function(c){return c.replace(/:/g,"\\:")},_cookie:function(){var c=this.cookie||(this.cookie=this.options.cookie.name||"ui-tabs-"+ ++u);return d.cookie.apply(null,[c].concat(d.makeArray(arguments)))},_ui:function(c,e){return{tab:c,panel:e,index:this.anchors.index(c)}},_cleanup:function(){this.lis.filter(".ui-state-processing").removeClass("ui-state-processing").find("span:data(label.tabs)").each(function(){var c=
d(this);c.html(c.data("label.tabs")).removeData("label.tabs")})},_tabify:function(c){function e(g,f){g.css({display:""});!d.support.opacity&&f.opacity&&g[0].style.removeAttribute("filter")}this.list=this.element.find("ol,ul").eq(0);this.lis=d("li:has(a[href])",this.list);this.anchors=this.lis.map(function(){return d("a",this)[0]});this.panels=d([]);var a=this,b=this.options,h=/^#.+/;this.anchors.each(function(g,f){var j=d(f).attr("href"),l=j.split("#")[0],p;if(l&&(l===location.toString().split("#")[0]||
(p=d("base")[0])&&l===p.href)){j=f.hash;f.href=j}if(h.test(j))a.panels=a.panels.add(a._sanitizeSelector(j));else if(j!="#"){d.data(f,"href.tabs",j);d.data(f,"load.tabs",j.replace(/#.*$/,""));j=a._tabId(f);f.href="#"+j;f=d("#"+j);if(!f.length){f=d(b.panelTemplate).attr("id",j).addClass("ui-tabs-panel ui-widget-content ui-corner-bottom").insertAfter(a.panels[g-1]||a.list);f.data("destroy.tabs",true)}a.panels=a.panels.add(f)}else b.disabled.push(g)});if(c){this.element.addClass("ui-tabs ui-widget ui-widget-content ui-corner-all");
this.list.addClass("ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all");this.lis.addClass("ui-state-default ui-corner-top");this.panels.addClass("ui-tabs-panel ui-widget-content ui-corner-bottom");if(b.selected===undefined){location.hash&&this.anchors.each(function(g,f){if(f.hash==location.hash){b.selected=g;return false}});if(typeof b.selected!="number"&&b.cookie)b.selected=parseInt(a._cookie(),10);if(typeof b.selected!="number"&&this.lis.filter(".ui-tabs-selected").length)b.selected=
this.lis.index(this.lis.filter(".ui-tabs-selected"));b.selected=b.selected||(this.lis.length?0:-1)}else if(b.selected===null)b.selected=-1;b.selected=b.selected>=0&&this.anchors[b.selected]||b.selected<0?b.selected:0;b.disabled=d.unique(b.disabled.concat(d.map(this.lis.filter(".ui-state-disabled"),function(g){return a.lis.index(g)}))).sort();d.inArray(b.selected,b.disabled)!=-1&&b.disabled.splice(d.inArray(b.selected,b.disabled),1);this.panels.addClass("ui-tabs-hide");this.lis.removeClass("ui-tabs-selected ui-state-active");
if(b.selected>=0&&this.anchors.length){this.panels.eq(b.selected).removeClass("ui-tabs-hide");this.lis.eq(b.selected).addClass("ui-tabs-selected ui-state-active");a.element.queue("tabs",function(){a._trigger("show",null,a._ui(a.anchors[b.selected],a.panels[b.selected]))});this.load(b.selected)}d(window).bind("unload",function(){a.lis.add(a.anchors).unbind(".tabs");a.lis=a.anchors=a.panels=null})}else b.selected=this.lis.index(this.lis.filter(".ui-tabs-selected"));this.element[b.collapsible?"addClass":
"removeClass"]("ui-tabs-collapsible");b.cookie&&this._cookie(b.selected,b.cookie);c=0;for(var i;i=this.lis[c];c++)d(i)[d.inArray(c,b.disabled)!=-1&&!d(i).hasClass("ui-tabs-selected")?"addClass":"removeClass"]("ui-state-disabled");b.cache===false&&this.anchors.removeData("cache.tabs");this.lis.add(this.anchors).unbind(".tabs");if(b.event!="mouseover"){var k=function(g,f){f.is(":not(.ui-state-disabled)")&&f.addClass("ui-state-"+g)},n=function(g,f){f.removeClass("ui-state-"+g)};this.lis.bind("mouseover.tabs",
function(){k("hover",d(this))});this.lis.bind("mouseout.tabs",function(){n("hover",d(this))});this.anchors.bind("focus.tabs",function(){k("focus",d(this).closest("li"))});this.anchors.bind("blur.tabs",function(){n("focus",d(this).closest("li"))})}var m,o;if(b.fx)if(d.isArray(b.fx)){m=b.fx[0];o=b.fx[1]}else m=o=b.fx;var q=o?function(g,f){d(g).closest("li").addClass("ui-tabs-selected ui-state-active");f.hide().removeClass("ui-tabs-hide").animate(o,o.duration||"normal",function(){e(f,o);a._trigger("show",
null,a._ui(g,f[0]))})}:function(g,f){d(g).closest("li").addClass("ui-tabs-selected ui-state-active");f.removeClass("ui-tabs-hide");a._trigger("show",null,a._ui(g,f[0]))},r=m?function(g,f){f.animate(m,m.duration||"normal",function(){a.lis.removeClass("ui-tabs-selected ui-state-active");f.addClass("ui-tabs-hide");e(f,m);a.element.dequeue("tabs")})}:function(g,f){a.lis.removeClass("ui-tabs-selected ui-state-active");f.addClass("ui-tabs-hide");a.element.dequeue("tabs")};this.anchors.bind(b.event+".tabs",
function(){var g=this,f=d(this).closest("li"),j=a.panels.filter(":not(.ui-tabs-hide)"),l=d(a._sanitizeSelector(this.hash));if(f.hasClass("ui-tabs-selected")&&!b.collapsible||f.hasClass("ui-state-disabled")||f.hasClass("ui-state-processing")||a._trigger("select",null,a._ui(this,l[0]))===false){this.blur();return false}b.selected=a.anchors.index(this);a.abort();if(b.collapsible)if(f.hasClass("ui-tabs-selected")){b.selected=-1;b.cookie&&a._cookie(b.selected,b.cookie);a.element.queue("tabs",function(){r(g,
j)}).dequeue("tabs");this.blur();return false}else if(!j.length){b.cookie&&a._cookie(b.selected,b.cookie);a.element.queue("tabs",function(){q(g,l)});a.load(a.anchors.index(this));this.blur();return false}b.cookie&&a._cookie(b.selected,b.cookie);if(l.length){j.length&&a.element.queue("tabs",function(){r(g,j)});a.element.queue("tabs",function(){q(g,l)});a.load(a.anchors.index(this))}else throw"jQuery UI Tabs: Mismatching fragment identifier.";d.browser.msie&&this.blur()});this.anchors.bind("click.tabs",
function(){return false})},destroy:function(){var c=this.options;this.abort();this.element.unbind(".tabs").removeClass("ui-tabs ui-widget ui-widget-content ui-corner-all ui-tabs-collapsible").removeData("tabs");this.list.removeClass("ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all");this.anchors.each(function(){var e=d.data(this,"href.tabs");if(e)this.href=e;var a=d(this).unbind(".tabs");d.each(["href","load","cache"],function(b,h){a.removeData(h+".tabs")})});this.lis.unbind(".tabs").add(this.panels).each(function(){d.data(this,
"destroy.tabs")?d(this).remove():d(this).removeClass("ui-state-default ui-corner-top ui-tabs-selected ui-state-active ui-state-hover ui-state-focus ui-state-disabled ui-tabs-panel ui-widget-content ui-corner-bottom ui-tabs-hide")});c.cookie&&this._cookie(null,c.cookie);return this},add:function(c,e,a){if(a===undefined)a=this.anchors.length;var b=this,h=this.options;e=d(h.tabTemplate.replace(/#\{href\}/g,c).replace(/#\{label\}/g,e));c=!c.indexOf("#")?c.replace("#",""):this._tabId(d("a",e)[0]);e.addClass("ui-state-default ui-corner-top").data("destroy.tabs",
true);var i=d("#"+c);i.length||(i=d(h.panelTemplate).attr("id",c).data("destroy.tabs",true));i.addClass("ui-tabs-panel ui-widget-content ui-corner-bottom ui-tabs-hide");if(a>=this.lis.length){e.appendTo(this.list);i.appendTo(this.list[0].parentNode)}else{e.insertBefore(this.lis[a]);i.insertBefore(this.panels[a])}h.disabled=d.map(h.disabled,function(k){return k>=a?++k:k});this._tabify();if(this.anchors.length==1){h.selected=0;e.addClass("ui-tabs-selected ui-state-active");i.removeClass("ui-tabs-hide");
this.element.queue("tabs",function(){b._trigger("show",null,b._ui(b.anchors[0],b.panels[0]))});this.load(0)}this._trigger("add",null,this._ui(this.anchors[a],this.panels[a]));return this},remove:function(c){var e=this.options,a=this.lis.eq(c).remove(),b=this.panels.eq(c).remove();if(a.hasClass("ui-tabs-selected")&&this.anchors.length>1)this.select(c+(c+1<this.anchors.length?1:-1));e.disabled=d.map(d.grep(e.disabled,function(h){return h!=c}),function(h){return h>=c?--h:h});this._tabify();this._trigger("remove",
null,this._ui(a.find("a")[0],b[0]));return this},enable:function(c){var e=this.options;if(d.inArray(c,e.disabled)!=-1){this.lis.eq(c).removeClass("ui-state-disabled");e.disabled=d.grep(e.disabled,function(a){return a!=c});this._trigger("enable",null,this._ui(this.anchors[c],this.panels[c]));return this}},disable:function(c){var e=this.options;if(c!=e.selected){this.lis.eq(c).addClass("ui-state-disabled");e.disabled.push(c);e.disabled.sort();this._trigger("disable",null,this._ui(this.anchors[c],this.panels[c]))}return this},
select:function(c){if(typeof c=="string")c=this.anchors.index(this.anchors.filter("[href$="+c+"]"));else if(c===null)c=-1;if(c==-1&&this.options.collapsible)c=this.options.selected;this.anchors.eq(c).trigger(this.options.event+".tabs");return this},load:function(c){var e=this,a=this.options,b=this.anchors.eq(c)[0],h=d.data(b,"load.tabs");this.abort();if(!h||this.element.queue("tabs").length!==0&&d.data(b,"cache.tabs"))this.element.dequeue("tabs");else{this.lis.eq(c).addClass("ui-state-processing");
if(a.spinner){var i=d("span",b);i.data("label.tabs",i.html()).html(a.spinner)}this.xhr=d.ajax(d.extend({},a.ajaxOptions,{url:h,success:function(k,n){d(e._sanitizeSelector(b.hash)).html(k);e._cleanup();a.cache&&d.data(b,"cache.tabs",true);e._trigger("load",null,e._ui(e.anchors[c],e.panels[c]));try{a.ajaxOptions.success(k,n)}catch(m){}},error:function(k,n){e._cleanup();e._trigger("load",null,e._ui(e.anchors[c],e.panels[c]));try{a.ajaxOptions.error(k,n,c,b)}catch(m){}}}));e.element.dequeue("tabs");return this}},
abort:function(){this.element.queue([]);this.panels.stop(false,true);this.element.queue("tabs",this.element.queue("tabs").splice(-2,2));if(this.xhr){this.xhr.abort();delete this.xhr}this._cleanup();return this},url:function(c,e){this.anchors.eq(c).removeData("cache.tabs").data("load.tabs",e);return this},length:function(){return this.anchors.length}});d.extend(d.ui.tabs,{version:"1.8.1"});d.extend(d.ui.tabs.prototype,{rotation:null,rotate:function(c,e){var a=this,b=this.options,h=a._rotate||(a._rotate=
function(i){clearTimeout(a.rotation);a.rotation=setTimeout(function(){var k=b.selected;a.select(++k<a.anchors.length?k:0)},c);i&&i.stopPropagation()});e=a._unrotate||(a._unrotate=!e?function(i){i.clientX&&a.rotate(null)}:function(){t=b.selected;h()});if(c){this.element.bind("tabsshow",h);this.anchors.bind(b.event+".tabs",e);h()}else{clearTimeout(a.rotation);this.element.unbind("tabsshow",h);this.anchors.unbind(b.event+".tabs",e);delete this._rotate;delete this._unrotate}return this}})})(jQuery);
;
|
aeolusproject/conductor
|
src/vendor/assets/javascripts/jquery.ui-1.8.1/jquery-ui-1.8.1.custom.min.js
|
JavaScript
|
apache-2.0
| 31,425
|
# Copyright 2021 The TensorFlow Probability 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.
# ============================================================================
"""Tests for no_pivot_ldl."""
import numpy as np
import tensorflow.compat.v2 as tf
from tensorflow_probability.python.experimental.linalg.no_pivot_ldl import no_pivot_ldl
from tensorflow_probability.python.experimental.linalg.no_pivot_ldl import simple_robustified_cholesky
from tensorflow_probability.python.internal import test_util
@test_util.test_all_tf_execution_regimes
class NoPivotLDLTest(test_util.TestCase):
def _randomDiag(self, n, batch_shape, low, high, forcemin=None, seed=42):
np.random.seed(seed)
shape = batch_shape + [n]
diag = np.random.uniform(low, high, size=shape)
if forcemin:
assert forcemin < low
diag = np.where(diag == np.min(diag, axis=-1)[..., np.newaxis],
forcemin, diag)
return diag
def _randomTril(self, n, batch_shape, seed=42):
np.random.seed(seed)
unit_tril = np.random.standard_normal(batch_shape + [n, n])
unit_tril = np.tril(unit_tril)
unit_tril[..., range(n), range(n)] = 1.
return unit_tril
def _randomSymmetricMatrix(self, n, batch_shape, low, high,
forcemin=None, seed=42):
diag = self._randomDiag(n, batch_shape, low, high, forcemin, seed)
unit_tril = self._randomTril(n, batch_shape, seed)
return np.einsum('...ij,...j,...kj->...ik', unit_tril, diag, unit_tril)
def testLDLRandomPSD(self):
matrix = self._randomSymmetricMatrix(
10, [2, 1, 3], 1e-6, 10., forcemin=0., seed=42)
left, diag = self.evaluate(no_pivot_ldl(matrix))
reconstruct = np.einsum('...ij,...j,...kj->...ik', left, diag, left)
self.assertAllClose(matrix, reconstruct)
def testLDLIndefinite(self):
matrix = [[1., 2.], [2., 1.]]
left, diag = self.evaluate(no_pivot_ldl(matrix))
reconstruct = np.einsum('...ij,...j,...kj->...ik', left, diag, left)
self.assertAllClose(matrix, reconstruct)
def testSimpleIsCholeskyRandomPD(self):
matrix = self._randomSymmetricMatrix(10, [2, 1, 3], 1e-6, 10., seed=42)
chol, left = self.evaluate(
(tf.linalg.cholesky(matrix),
simple_robustified_cholesky(matrix)))
self.assertAllClose(chol, left)
def testSimpleIndefinite(self):
matrix = [[1., 2.], [2., 1.]]
left = self.evaluate(
simple_robustified_cholesky(matrix, tol=.1))
reconstruct = np.einsum('...ij,...kj->...ik', left, left)
eigv, _ = self.evaluate(tf.linalg.eigh(reconstruct))
self.assertAllTrue(eigv > 0.)
def testXlaCompileBug(self):
inp = tf.Variable([[2., 1.], [1., 2.]])
self.evaluate(inp.initializer)
alt_chol = simple_robustified_cholesky
alt_chol_nojit = tf.function(alt_chol, autograph=False, jit_compile=False)
alt_chol_jit = tf.function(alt_chol, autograph=False, jit_compile=True)
answer = np.array([[1.4142135, 0.], [0.70710677, 1.2247449]])
self.assertAllClose(self.evaluate(alt_chol(inp)), answer)
self.assertAllClose(self.evaluate(alt_chol_nojit(inp)), answer)
self.assertAllClose(self.evaluate(alt_chol_jit(inp)), answer)
with tf.GradientTape():
chol_with_grad = alt_chol(inp)
chol_nojit_with_grad = alt_chol_nojit(inp)
# Not supported by TF-XLA (WAI), see b/193584244
# chol_jit_with_grad = alt_chol_jit(inp)
self.assertAllClose(self.evaluate(chol_with_grad), answer)
self.assertAllClose(self.evaluate(chol_nojit_with_grad), answer)
# But wrapping the tape in tf.function should work.
@tf.function(autograph=False, jit_compile=True)
def jit_with_grad(mat):
with tf.GradientTape():
return alt_chol_jit(mat)
self.assertAllClose(self.evaluate(jit_with_grad(inp)), answer)
if __name__ == '__main__':
test_util.main()
|
tensorflow/probability
|
tensorflow_probability/python/experimental/linalg/no_pivot_ldl_test.py
|
Python
|
apache-2.0
| 4,358
|
// Code generated by msgraph.go/gen DO NOT EDIT.
package msgraph
// HealthState undocumented
type HealthState string
const (
// HealthStateVUnknown undocumented
HealthStateVUnknown HealthState = "unknown"
// HealthStateVHealthy undocumented
HealthStateVHealthy HealthState = "healthy"
// HealthStateVUnhealthy undocumented
HealthStateVUnhealthy HealthState = "unhealthy"
)
var (
// HealthStatePUnknown is a pointer to HealthStateVUnknown
HealthStatePUnknown = &_HealthStatePUnknown
// HealthStatePHealthy is a pointer to HealthStateVHealthy
HealthStatePHealthy = &_HealthStatePHealthy
// HealthStatePUnhealthy is a pointer to HealthStateVUnhealthy
HealthStatePUnhealthy = &_HealthStatePUnhealthy
)
var (
_HealthStatePUnknown = HealthStateVUnknown
_HealthStatePHealthy = HealthStateVHealthy
_HealthStatePUnhealthy = HealthStateVUnhealthy
)
|
42wim/matterbridge
|
vendor/github.com/yaegashi/msgraph.go/beta/EnumHealth.go
|
GO
|
apache-2.0
| 863
|
/**
* Copyright (C) 2018 - present McLeod Moores Software Limited. All rights reserved.
*/
package com.opengamma.core.change;
import org.testng.annotations.Test;
import com.opengamma.util.test.TestGroup;
/**
* Tests for {@link AggregatingChangeManager}.
*/
@Test(groups = TestGroup.UNIT)
public class AggregatingChangeManagerTest {
private static final BasicChangeManager BCM1 = new BasicChangeManager();
private static final BasicChangeManager BCM2 = new BasicChangeManager();
private static final BasicChangeManager BCM3 = new BasicChangeManager();
private static final BasicChangeManager BCM4 = new BasicChangeManager();
/**
* Tests that the change providers cannot be null.
*/
@Test(expectedExceptions = IllegalArgumentException.class)
public void testNullChangeProviders() {
new AggregatingChangeManager(null);
}
/**
*
*/
}
|
McLeodMoores/starling
|
projects/core/src/test/java/com/opengamma/core/change/AggregatingChangeManagerTest.java
|
Java
|
apache-2.0
| 873
|
package ua.anironglass.boilerplate.injection.components;
import javax.inject.Singleton;
import dagger.Component;
import ua.anironglass.boilerplate.injection.modules.TestApplicationModule;
@Singleton
@Component(modules = TestApplicationModule.class)
public interface TestApplicationComponent extends ApplicationComponent {
}
|
AnironGlass/MVP-Boilerplate
|
app/src/androidTest/java/ua/anironglass/boilerplate/injection/components/TestApplicationComponent.java
|
Java
|
apache-2.0
| 327
|
/*
* Copyright (C) 2008 Jive Software. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.openfire.reporting.stats;
import org.jivesoftware.openfire.cluster.ClusterManager;
import org.jivesoftware.openfire.stats.Statistic;
import org.jrobin.core.RrdDb;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class DefaultStatsViewer implements StatsViewer {
private static final Logger Log = LoggerFactory.getLogger(DefaultStatsViewer.class);
private StatsEngine engine;
/**
* Default constructor used by the plugin container to create this class.
*
* @param engine The stats engine used to retrieve the stats.
*/
public DefaultStatsViewer(StatsEngine engine) {
this.engine = engine;
}
public String [] getAllHighLevelStatKeys() {
return engine.getAllHighLevelNames();
}
public Statistic[] getStatistic(String statKey) {
StatDefinition[] definitions = engine.getDefinition(statKey);
if(definitions == null) {
throw new IllegalArgumentException("Illegal stat key: " + statKey);
}
Statistic[] statistics = new Statistic[definitions.length];
int i = 0;
for(StatDefinition def : definitions) {
statistics[i++] = def.getStatistic();
}
return statistics;
}
public long getLastSampleTime(String key) {
return engine.getDefinition(key)[0].getLastSampleTime() * 1000;
}
public double[][] getData(String key, long startTime, long endTime) {
return engine.getDefinition(key)[0].getData(parseTime(startTime), parseTime(endTime));
}
/**
* Converts milliseconds to seconds.
*
* @param time the time to convert
* @return the converted time
*/
private long parseTime(long time) {
return time / 1000;
}
public double[][] getData(String key, long startTime, long endTime, int dataPoints) {
return engine.getDefinition(key)[0].getData(parseTime(startTime), parseTime(endTime), dataPoints);
}
public StatView getData(String key, TimePeriod timePeriod) {
StatDefinition def = engine.getDefinition(key)[0];
long endTime = def.getLastSampleTime();
long startTime = timePeriod.getStartTime(endTime);
double [][] data = def.getData(startTime, endTime, timePeriod.getDataPoints());
return new StatView(startTime, endTime, data);
}
public double[] getMax(String key, long startTime, long endTime) {
return engine.getDefinition(key)[0].getMax(parseTime(startTime), parseTime(endTime));
}
public double[] getMax(String key, long startTime, long endTime, int dataPoints) {
return engine.getDefinition(key)[0].getMax(parseTime(startTime), parseTime(endTime), dataPoints);
}
public double[] getMax(String key, TimePeriod timePeriod) {
StatDefinition def = engine.getDefinition(key)[0];
long lastTime = def.getLastSampleTime();
return def.getMax(timePeriod.getStartTime(lastTime), lastTime);
}
public double[] getMin(String key, long startTime, long endTime) {
return engine.getDefinition(key)[0].getMin(parseTime(startTime), parseTime(endTime));
}
public double[] getMin(String key, long startTime, long endTime, int dataPoints) {
return engine.getDefinition(key)[0].getMin(parseTime(startTime), parseTime(endTime), dataPoints);
}
public double[] getMin(String key, TimePeriod timePeriod) {
StatDefinition def = engine.getDefinition(key)[0];
long lastTime = def.getLastSampleTime();
return def.getMin(timePeriod.getStartTime(lastTime), lastTime);
}
public double[] getCurrentValue(String key) {
if (ClusterManager.isSeniorClusterMember()) {
return new double[] { engine.getDefinition(key)[0].getLastSample() };
}
else {
try {
if (RrdSqlBackend.exists(key)) {
RrdDb db = new RrdDb(key, true);
return new double[] { db.getLastDatasourceValues()[0] };
}
} catch (Exception e) {
Log.error("Error retrieving last sample value for: " + key, e);
}
return new double[] { 0 };
}
}
}
|
Gugli/Openfire
|
src/plugins/monitoring/src/java/org/jivesoftware/openfire/reporting/stats/DefaultStatsViewer.java
|
Java
|
apache-2.0
| 4,857
|
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<link rel="SHORTCUT ICON" href="../../../../../img/clover.ico" />
<link rel="stylesheet" href="../../../../../aui/css/aui.min.css" media="all"/>
<link rel="stylesheet" href="../../../../../aui/css/aui-experimental.min.css" media="all"/>
<!--[if IE 9]><link rel="stylesheet" href="../../../../../aui/css/aui-ie9.min.css" media="all"/><![endif]-->
<style type="text/css" media="all">
@import url('../../../../../style.css');
@import url('../../../../../tree.css');
</style>
<script src="../../../../../jquery-1.8.3.min.js" type="text/javascript"></script>
<script src="../../../../../aui/js/aui.min.js" type="text/javascript"></script>
<script src="../../../../../aui/js/aui-experimental.min.js" type="text/javascript"></script>
<script src="../../../../../aui/js/aui-soy.min.js" type="text/javascript"></script>
<script src="../../../../../package-nodes-tree.js" type="text/javascript"></script>
<script src="../../../../../clover-tree.js" type="text/javascript"></script>
<script src="../../../../../clover.js" type="text/javascript"></script>
<script src="../../../../../clover-descriptions.js" type="text/javascript"></script>
<script src="../../../../../cloud.js" type="text/javascript"></script>
<title>ABA Route Transit Number Validator 1.0.1-SNAPSHOT</title>
</head>
<body>
<div id="page">
<header id="header" role="banner">
<nav class="aui-header aui-dropdown2-trigger-group" role="navigation">
<div class="aui-header-inner">
<div class="aui-header-primary">
<h1 id="logo" class="aui-header-logo aui-header-logo-clover">
<a href="http://openclover.org" title="Visit OpenClover home page"><span class="aui-header-logo-device">OpenClover</span></a>
</h1>
</div>
<div class="aui-header-secondary">
<ul class="aui-nav">
<li id="system-help-menu">
<a class="aui-nav-link" title="Open online documentation" target="_blank"
href="http://openclover.org/documentation">
<span class="aui-icon aui-icon-small aui-iconfont-help"> Help</span>
</a>
</li>
</ul>
</div>
</div>
</nav>
</header>
<div class="aui-page-panel">
<div class="aui-page-panel-inner">
<div class="aui-page-panel-nav aui-page-panel-nav-clover">
<div class="aui-page-header-inner" style="margin-bottom: 20px;">
<div class="aui-page-header-image">
<a href="http://cardatechnologies.com" target="_top">
<div class="aui-avatar aui-avatar-large aui-avatar-project">
<div class="aui-avatar-inner">
<img src="../../../../../img/clover_logo_large.png" alt="Clover icon"/>
</div>
</div>
</a>
</div>
<div class="aui-page-header-main" >
<h1>
<a href="http://cardatechnologies.com" target="_top">
ABA Route Transit Number Validator 1.0.1-SNAPSHOT
</a>
</h1>
</div>
</div>
<nav class="aui-navgroup aui-navgroup-vertical">
<div class="aui-navgroup-inner">
<ul class="aui-nav">
<li class="">
<a href="../../../../../dashboard.html">Project overview</a>
</li>
</ul>
<div class="aui-nav-heading packages-nav-heading">
<strong>Packages</strong>
</div>
<div class="aui-nav project-packages">
<form method="get" action="#" class="aui package-filter-container">
<input type="text" autocomplete="off" class="package-filter text"
placeholder="Type to filter packages..." name="package-filter" id="package-filter"
title="Start typing package name (or part of the name) to search through the tree. Use arrow keys and the Enter key to navigate."/>
</form>
<p class="package-filter-no-results-message hidden">
<small>No results found.</small>
</p>
<div class="packages-tree-wrapper" data-root-relative="../../../../../" data-package-name="com.cardatechnologies.utils.validators.abaroutevalidator">
<div class="packages-tree-container"></div>
<div class="clover-packages-lozenges"></div>
</div>
</div>
</div>
</nav> </div>
<section class="aui-page-panel-content">
<div class="aui-page-panel-content-clover">
<div class="aui-page-header-main"><ol class="aui-nav aui-nav-breadcrumbs">
<li><a href="../../../../../dashboard.html"> Project Clover database Sat Aug 7 2021 12:29:33 MDT</a></li>
<li><a href="test-pkg-summary.html">Package com.cardatechnologies.utils.validators.abaroutevalidator</a></li>
<li><a href="test-Test_AbaRouteValidator_17a.html">Class Test_AbaRouteValidator_17a</a></li>
</ol></div>
<h1 class="aui-h2-clover">
Test testAbaNumberCheck_36867_good
</h1>
<table class="aui">
<thead>
<tr>
<th>Test</th>
<th><label title="The test result. Either a Pass, Fail or Error.">Status</label></th>
<th><label title="When the test execution was started">Start time</label></th>
<th><label title="The total time in seconds taken to run this test.">Time (seconds)</label></th>
<th><label title="A failure or error message if the test is not successful.">Message</label></th>
</tr>
</thead>
<tbody>
<tr>
<td>
<a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/Test_AbaRouteValidator_17a.html?line=42825#src-42825" >testAbaNumberCheck_36867_good</a>
</td>
<td>
<span class="sortValue">1</span><span class="aui-lozenge aui-lozenge-success">PASS</span>
</td>
<td>
7 Aug 12:45:56
</td>
<td>
0.0 </td>
<td>
<div></div>
<div class="errorMessage"></div>
</td>
</tr>
</tbody>
</table>
<div> </div>
<table class="aui aui-table-sortable">
<thead>
<tr>
<th style="white-space:nowrap;"><label title="A class that was directly hit by this test.">Target Class</label></th>
<th colspan="4"><label title="The percentage of coverage contributed by each single test.">Coverage contributed by</label> testAbaNumberCheck_36867_good</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<span class="sortValue">com.cardatechnologies.utils.validators.abaroutevalidator.AbaRouteValidator</span>
  <a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/AbaRouteValidator.html?id=32609#AbaRouteValidator" title="AbaRouteValidator" name="sl-47">com.cardatechnologies.utils.validators.abaroutevalidator.AbaRouteValidator</a>
</td>
<td>
<span class="sortValue">0.7352941</span>73.5%
</td>
<td class="align-middle" style="width: 100%" colspan="3">
<div>
<div title="73.5% Covered" style="min-width:40px;" class="barNegative contribBarNegative contribBarNegative"><div class="barPositive contribBarPositive contribBarPositive" style="width:73.5%"></div></div></div> </td>
</tr>
</tbody>
</table>
</div> <!-- class="aui-page-panel-content-clover" -->
<footer id="footer" role="contentinfo">
<section class="footer-body">
<ul>
<li>
Report generated by <a target="_new" href="http://openclover.org">OpenClover</a> v 4.4.1
on Sat Aug 7 2021 12:49:26 MDT using coverage data from Sat Aug 7 2021 12:47:23 MDT.
</li>
</ul>
<ul>
<li>OpenClover is free and open-source software. </li>
</ul>
</section>
</footer> </section> <!-- class="aui-page-panel-content" -->
</div> <!-- class="aui-page-panel-inner" -->
</div> <!-- class="aui-page-panel" -->
</div> <!-- id="page" -->
</body>
</html>
|
dcarda/aba.route.validator
|
target13/site/clover/com/cardatechnologies/utils/validators/abaroutevalidator/Test_AbaRouteValidator_17a_testAbaNumberCheck_36867_good_p5t.html
|
HTML
|
apache-2.0
| 9,184
|
# Cephalaria attenuata Roem. & Schult. SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Dipsacales/Dipsacaceae/Cephalaria/Cephalaria attenuata/README.md
|
Markdown
|
apache-2.0
| 186
|
# Copyright 2014 Open Source Robotics Foundation, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import print_function
import sys
import time
from catkin_pkg.package import InvalidPackage
from catkin_tools.argument_parsing import add_context_args
from catkin_tools.argument_parsing import add_cmake_and_make_and_catkin_make_args
from catkin_tools.common import format_time_delta
from catkin_tools.common import is_tty
from catkin_tools.common import log
from catkin_tools.common import find_enclosing_package
from catkin_tools.context import Context
from catkin_tools.terminal_color import set_color
from catkin_tools.metadata import get_metadata
from catkin_tools.metadata import update_metadata
from catkin_tools.resultspace import load_resultspace_environment
from .color import clr
from .common import get_build_type
from .build import build_isolated_workspace
from .build import determine_packages_to_be_built
from .build import topological_order_packages
from .build import verify_start_with_option
def prepare_arguments(parser):
parser.description = "Build one or more packages in a catkin workspace.\
This invokes `CMake`, `make`, and optionally `make install` for either all\
or the specified packages in a catkin workspace.\
\
Arguments passed to this verb can temporarily override persistent options\
stored in the catkin profile config. If you want to save these options, use\
the --save-config argument. To see the current config, use the\
`catkin config` command."
# Workspace / profile args
add_context_args(parser)
# Sub-commands
add = parser.add_argument
add('--dry-run', '-d', action='store_true', default=False,
help='List the packages which will be built with the given arguments without building them.')
# What packages to build
pkg_group = parser.add_argument_group('Packages', 'Control which packages get built.')
add = pkg_group.add_argument
add('packages', metavar='PKGNAME', nargs='*',
help='Workspace packages to build, package dependencies are built as well unless --no-deps is used. '
'If no packages are given, then all the packages are built.')
add('--this', dest='build_this', action='store_true', default=False,
help='Build the package containing the current working directory.')
add('--no-deps', action='store_true', default=False,
help='Only build specified packages, not their dependencies.')
start_with_group = pkg_group.add_mutually_exclusive_group()
add = start_with_group.add_argument
add('--start-with', metavar='PKGNAME', type=str,
help='Build a given package and those which depend on it, skipping any before it.')
add('--start-with-this', action='store_true', default=False,
help='Similar to --start-with, starting with the package containing the current directory.')
# Build options
build_group = parser.add_argument_group('Build', 'Control the build behaiovr.')
add = build_group.add_argument
add('--force-cmake', action='store_true', default=None,
help='Runs cmake explicitly for each catkin package.')
add('--no-install-lock', action='store_true', default=None,
help='Prevents serialization of the install steps, which is on by default to prevent file install collisions')
config_group = parser.add_argument_group('Config', 'Parameters for the underlying buildsystem.')
add = config_group.add_argument
add('--save-config', action='store_true', default=False,
help='Save any configuration options in this section for the next build invocation.')
add_cmake_and_make_and_catkin_make_args(config_group)
# Behavior
behavior_group = parser.add_argument_group('Interface', 'The behavior of the command-line interface.')
add = behavior_group.add_argument
add('--force-color', action='store_true', default=False,
help='Forces catkin build to ouput in color, even when the terminal does not appear to support it.')
add('--verbose', '-v', action='store_true', default=False,
help='Print output from commands in ordered blocks once the command finishes.')
add('--interleave-output', '-i', action='store_true', default=False,
help='Prevents ordering of command output when multiple commands are running at the same time.')
add('--no-status', action='store_true', default=False,
help='Suppresses status line, useful in situations where carriage return is not properly supported.')
add('--no-notify', action='store_true', default=False,
help='Suppresses system popup notification.')
return parser
def dry_run(context, packages, no_deps, start_with):
# Print Summary
log(context.summary())
# Find list of packages in the workspace
packages_to_be_built, packages_to_be_built_deps, all_packages = determine_packages_to_be_built(packages, context)
# Assert start_with package is in the workspace
verify_start_with_option(start_with, packages, all_packages, packages_to_be_built + packages_to_be_built_deps)
if not no_deps:
# Extend packages to be built to include their deps
packages_to_be_built.extend(packages_to_be_built_deps)
# Also resort
packages_to_be_built = topological_order_packages(dict(packages_to_be_built))
# Print packages
log("Packages to be built:")
max_name_len = str(max([len(pkg.name) for pth, pkg in packages_to_be_built]))
prefix = clr('@{pf}' + ('------ ' if start_with else '- ') + '@|')
for pkg_path, pkg in packages_to_be_built:
build_type = get_build_type(pkg)
if build_type == 'catkin' and 'metapackage' in [e.tagname for e in pkg.exports]:
build_type = 'metapackage'
if start_with and pkg.name == start_with:
start_with = None
log(clr("{prefix}@{cf}{name:<" + max_name_len + "}@| (@{yf}{build_type}@|)")
.format(prefix=clr('@!@{kf}(skip)@| ') if start_with else prefix, name=pkg.name, build_type=build_type))
log("Total packages: " + str(len(packages_to_be_built)))
def main(opts):
# Context-aware args
if opts.build_this or opts.start_with_this:
# Determine the enclosing package
try:
this_package = find_enclosing_package()
except InvalidPackage:
pass
# Handle context-based package building
if opts.build_this:
if this_package:
opts.packages += [this_package]
else:
sys.exit("catkin build: --this was specified, but this directory is not contained by a catkin package.")
# If --start--with was used without any packages and --this was specified, start with this package
if opts.start_with_this:
if this_package:
opts.start_with = this_package
else:
sys.exit("catkin build: --this was specified, but this directory is not contained by a catkin package.")
if opts.no_deps and not opts.packages:
sys.exit("With --no-deps, you must specify packages to build.")
if not opts.force_color and not is_tty(sys.stdout):
set_color(False)
# Load the context
ctx = Context.Load(opts.workspace, opts.profile, opts)
# Load the environment of the workspace to extend
if ctx.extend_path is not None:
try:
load_resultspace_environment(ctx.extend_path)
except IOError as exc:
log(clr("@!@{rf}Error:@| Unable to extend workspace from \"%s\": %s" %
(ctx.extend_path, exc.message)))
return 1
# Display list and leave the filesystem untouched
if opts.dry_run:
dry_run(ctx, opts.packages, opts.no_deps, opts.start_with)
return
# Check if the context is valid before writing any metadata
if not ctx.source_space_exists():
print("catkin build: error: Unable to find source space `%s`" % ctx.source_space_abs)
return 1
# Always save the last context under the build verb
update_metadata(ctx.workspace, ctx.profile, 'build', ctx.get_stored_dict())
build_metadata = get_metadata(ctx.workspace, ctx.profile, 'build')
if build_metadata.get('needs_force', False):
opts.force_cmake = True
update_metadata(ctx.workspace, ctx.profile, 'build', {'needs_force': False})
# Save the context as the configuration
if opts.save_config:
Context.Save(ctx)
start = time.time()
try:
return build_isolated_workspace(
ctx,
packages=opts.packages,
start_with=opts.start_with,
no_deps=opts.no_deps,
jobs=opts.parallel_jobs,
force_cmake=opts.force_cmake,
force_color=opts.force_color,
quiet=not opts.verbose,
interleave_output=opts.interleave_output,
no_status=opts.no_status,
lock_install=not opts.no_install_lock,
no_notify=opts.no_notify
)
finally:
log("[build] Runtime: {0}".format(format_time_delta(time.time() - start)))
|
xqms/catkin_tools
|
catkin_tools/verbs/catkin_build/cli.py
|
Python
|
apache-2.0
| 9,623
|
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="google-site-verification" content="xBT4GhYoi5qRD5tr338pgPM5OWHHIDR6mNg1a3euekI" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="{{ site.description }}">
<meta name="keywords" content="{{ site.keyword }}">
<meta name="theme-color" content="{{ site.chrome-tab-theme-color }}">
<meta name="baidu-site-verification" content="h9febHTgVU" />
<title>{% if page.title %}{{ page.title }} - {{ site.SEOTitle }}{% else %}{{ site.SEOTitle }}{% endif %}</title>
<!-- Web App Manifest -->
<link rel="manifest" href="{{ site.baseurl }}/pwa/manifest.json">
<!-- Favicon -->
<link rel="shortcut icon" href="{{ site.baseurl }}/img/favicon.ico">
<!-- Canonical URL -->
<link rel="canonical" href="{{ page.url | replace:'index.html','' | prepend: site.baseurl | prepend: site.url }}">
<!-- Bootstrap Core CSS -->
<link rel="stylesheet" href="{{ "/css/bootstrap.min.css" | prepend: site.baseurl }}">
<!-- Custom CSS -->
<link rel="stylesheet" href="{{ "/css/hux-blog.min.css" | prepend: site.baseurl }}">
<!-- Pygments Github CSS -->
<link rel="stylesheet" href="{{ "/css/syntax.css" | prepend: site.baseurl }}">
<!-- Custom Fonts -->
<!-- <link href="http://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet" type="text/css"> -->
<!-- Hux change font-awesome CDN to qiniu -->
<link href="//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet" type="text/css">
<!-- Hux Delete, sad but pending in China
<link href='http://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/
css'>
-->
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
<!-- Gittalk -->
<link rel="stylesheet" href="{{ site.baseurl }}/css/gitalk.css">
<script src="{{ site.baseurl }}/js/gitalk.min.js"></script>
<script src="{{ site.baseurl }}/js/md5.min.js"></script>
<!-- advertisement -->
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<script>
(adsbygoogle = window.adsbygoogle || []).push({
google_ad_client: "ca-pub-6317521302109017",
enable_page_level_ads: true
});
</script>
<!-- ga & ba script hoook -->
<script>
var _hmt = _hmt || [];
(function() {
var hm = document.createElement("script");
hm.src = "https://hm.baidu.com/hm.js?a7b90dba0b51a40180988f710992ac76";
var s = document.getElementsByTagName("script")[0];
s.parentNode.insertBefore(hm, s);
})();
</script>
<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','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-103224542-1', 'auto');
ga('send', 'pageview');
</script>
<script>
(function(){
var bp = document.createElement('script');
var curProtocol = window.location.protocol.split(':')[0];
if (curProtocol === 'https') {
bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
}
else {
bp.src = 'http://push.zhanzhang.baidu.com/push.js';
}
var s = document.getElementsByTagName("script")[0];
s.parentNode.insertBefore(bp, s);
})();
</script>
</head>
|
chenwenhang/chenwenhang.github.io
|
_includes/head.html
|
HTML
|
apache-2.0
| 4,314
|
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from oslo_utils import uuidutils
from nova import context
from nova import exception
from nova.objects import cell_mapping
from nova.objects import instance_mapping
from nova import test
from nova.tests import fixtures
sample_mapping = {'instance_uuid': '',
'cell_id': 3,
'project_id': 'fake-project'}
sample_cell_mapping = {'id': 3,
'uuid': '',
'name': 'fake-cell',
'transport_url': 'rabbit:///',
'database_connection': 'mysql:///'}
def create_cell_mapping(**kwargs):
args = sample_cell_mapping.copy()
if 'uuid' not in kwargs:
args['uuid'] = uuidutils.generate_uuid()
args.update(kwargs)
ctxt = context.RequestContext('fake-user', 'fake-project')
return cell_mapping.CellMapping._create_in_db(ctxt, args)
def create_mapping(**kwargs):
args = sample_mapping.copy()
if 'instance_uuid' not in kwargs:
args['instance_uuid'] = uuidutils.generate_uuid()
args.update(kwargs)
ctxt = context.RequestContext('fake-user', 'fake-project')
return instance_mapping.InstanceMapping._create_in_db(ctxt, args)
class InstanceMappingTestCase(test.NoDBTestCase):
USES_DB_SELF = True
def setUp(self):
super(InstanceMappingTestCase, self).setUp()
self.useFixture(fixtures.Database(database='api'))
self.context = context.RequestContext('fake-user', 'fake-project')
self.mapping_obj = instance_mapping.InstanceMapping()
def test_get_by_instance_uuid(self):
cell_mapping = create_cell_mapping()
mapping = create_mapping()
db_mapping = self.mapping_obj._get_by_instance_uuid_from_db(
self.context, mapping['instance_uuid'])
for key in [key for key in self.mapping_obj.fields.keys()
if key != 'cell_mapping']:
self.assertEqual(db_mapping[key], mapping[key])
self.assertEqual(db_mapping['cell_mapping']['id'], cell_mapping['id'])
def test_get_by_instance_uuid_not_found(self):
self.assertRaises(exception.InstanceMappingNotFound,
self.mapping_obj._get_by_instance_uuid_from_db, self.context,
uuidutils.generate_uuid())
def test_save_in_db(self):
mapping = create_mapping()
cell_mapping = create_cell_mapping()
self.mapping_obj._save_in_db(self.context, mapping['instance_uuid'],
{'cell_id': cell_mapping['id']})
db_mapping = self.mapping_obj._get_by_instance_uuid_from_db(
self.context, mapping['instance_uuid'])
for key in [key for key in self.mapping_obj.fields.keys()
if key not in ['cell_id', 'cell_mapping', 'updated_at']]:
self.assertEqual(db_mapping[key], mapping[key])
self.assertEqual(db_mapping['cell_id'], cell_mapping['id'])
def test_destroy_in_db(self):
mapping = create_mapping()
self.mapping_obj._get_by_instance_uuid_from_db(self.context,
mapping['instance_uuid'])
self.mapping_obj._destroy_in_db(self.context, mapping['instance_uuid'])
self.assertRaises(exception.InstanceMappingNotFound,
self.mapping_obj._get_by_instance_uuid_from_db, self.context,
mapping['instance_uuid'])
def test_cell_id_nullable(self):
# Just ensure this doesn't raise
create_mapping(cell_id=None)
def test_modify_cell_mapping(self):
inst_mapping = instance_mapping.InstanceMapping(context=self.context)
inst_mapping.instance_uuid = uuidutils.generate_uuid()
inst_mapping.project_id = self.context.project_id
inst_mapping.cell_mapping = None
inst_mapping.create()
c_mapping = cell_mapping.CellMapping(
self.context,
uuid=uuidutils.generate_uuid(),
name="cell0",
transport_url="none:///",
database_connection="fake:///")
c_mapping.create()
inst_mapping.cell_mapping = c_mapping
inst_mapping.save()
result_mapping = instance_mapping.InstanceMapping.get_by_instance_uuid(
self.context, inst_mapping.instance_uuid)
self.assertEqual(result_mapping.cell_mapping.id,
c_mapping.id)
class InstanceMappingListTestCase(test.NoDBTestCase):
USES_DB_SELF = True
def setUp(self):
super(InstanceMappingListTestCase, self).setUp()
self.useFixture(fixtures.Database(database='api'))
self.context = context.RequestContext('fake-user', 'fake-project')
self.list_obj = instance_mapping.InstanceMappingList()
def test_get_by_project_id_from_db(self):
project_id = 'fake-project'
mappings = {}
mapping = create_mapping(project_id=project_id)
mappings[mapping['instance_uuid']] = mapping
mapping = create_mapping(project_id=project_id)
mappings[mapping['instance_uuid']] = mapping
db_mappings = self.list_obj._get_by_project_id_from_db(
self.context, project_id)
for db_mapping in db_mappings:
mapping = mappings[db_mapping.instance_uuid]
for key in instance_mapping.InstanceMapping.fields.keys():
self.assertEqual(db_mapping[key], mapping[key])
def test_instance_mapping_list_get_by_cell_id(self):
"""Tests getting all of the InstanceMappings for a given CellMapping id
"""
# we shouldn't have any instance mappings yet
inst_mapping_list = (
instance_mapping.InstanceMappingList.get_by_cell_id(
self.context, sample_cell_mapping['id'])
)
self.assertEqual(0, len(inst_mapping_list))
# now create an instance mapping in a cell
db_inst_mapping1 = create_mapping()
# let's also create an instance mapping that's not in a cell to make
# sure our filtering is working
db_inst_mapping2 = create_mapping(cell_id=None)
self.assertIsNone(db_inst_mapping2['cell_id'])
# now we should list out one instance mapping for the cell
inst_mapping_list = (
instance_mapping.InstanceMappingList.get_by_cell_id(
self.context, db_inst_mapping1['cell_id'])
)
self.assertEqual(1, len(inst_mapping_list))
self.assertEqual(db_inst_mapping1['id'], inst_mapping_list[0].id)
|
vmturbo/nova
|
nova/tests/functional/db/test_instance_mapping.py
|
Python
|
apache-2.0
| 7,062
|
.type_16_content .vc_row {
margin-left: -15px;
margin-right: -15px;
margin-bottom: 0;
}
.type_16_content .vc_row .parallax-image {
border-radius: 2px;
box-shadow: 0 1px 3px rgba(0,0,0,0.15), 0 7px 15px rgba(0,0,0,0.42);
border: 7px solid #fff;
background-color: #fff;
max-width: 260px;
height: auto;
}
.type_16_content .vc_row .parallax-image:nth-of-type(1) {
-webkit-transform: rotate(-10deg);
transform: rotate(-10deg);
}
.type_16_content .vc_row .pt1 {
position: absolute;
top: -80.959px;
left: 12%;
z-index: 1;
}
.type_16_content .vc_row .pt2 {
position: absolute;
top: 140.038px;
left: 24%;
}
.type_16_content .vc_row .pt3 {
left: 17%;
top: 57px;
z-index: 1;
}
.type_16_content .vc_row a {
text-decoration: none;
}
.type_16_content .vc_row .parallax-image:nth-of-type(2) {
-webkit-transform: rotate(7deg);
transform: rotate(7deg);
}
.type_16_content .vc_row .parallax-image:nth-of-type(3) {
-webkit-transform: rotate(16deg);
transform: rotate(16deg);
}
.type_16_content .vc_row .vc_column-inner {
padding-top: 0;
}
.type_16_content .vc_row h2 {
line-height: 1.2;
margin: 2.8rem 0 1.4rem;
position: relative;
font-family: 'Domine';
font-weight: normal;
font-style: normal;
text-transform: none;
font-size: 3rem;
color: #363d40;
}
.type_16_content .vc_row h2 small {
color: inherit;
font-size: 50%;
font-weight: normal;
display: block;
opacity: 0.8;
line-height: 1.2;
}
.type_16_content .vc_row p {
margin: 2.8rem 0 1.4rem;
font-family: 'Roboto';
font-weight: 300;
text-transform: none;
font-size: 1.4rem;
margin-top: 0;
}
.type_16_content .vc_custom_1456180226251 {
background-image: url(../../images/home/bg-parallax-3.jpg) !important;
background-position: center;
background-repeat: no-repeat !important;
background-size: cover !important;
width: 100%;
margin: 0px;
}
|
InfinitePW/Laravel5_GroupL
|
Laravel-group_L/public/css/home/type_16_content.css
|
CSS
|
apache-2.0
| 1,882
|
package Physics;
import org.joml.Vector2f;
public abstract class CollideArea {
public abstract boolean inArea(Vector2f dot);
public abstract CollideArea copy();
}
|
dmromanov98/GameProject
|
Engine/src/Physics/CollideArea.java
|
Java
|
apache-2.0
| 174
|
//---------------------------------------------------------------------------
// Greenplum Database
// Copyright (C) 2010 Greenplum, Inc.
//
// @filename:
// CParseHandlerScalarConstValue.cpp
//
// @doc:
//
// Implementation of the SAX parse handler class for parsing scalar ConstVal.
//---------------------------------------------------------------------------
#include "naucrates/dxl/parser/CParseHandlerScalarConstValue.h"
#include "naucrates/dxl/parser/CParseHandlerScalarOp.h"
#include "naucrates/dxl/parser/CParseHandlerFactory.h"
#include "naucrates/dxl/operators/CDXLOperatorFactory.h"
using namespace gpdxl;
XERCES_CPP_NAMESPACE_USE
//---------------------------------------------------------------------------
// @function:
// CParseHandlerScalarConstValue::CParseHandlerScalarConstValue
//
// @doc:
// Constructor
//
//---------------------------------------------------------------------------
CParseHandlerScalarConstValue::CParseHandlerScalarConstValue
(
IMemoryPool *pmp,
CParseHandlerManager *pphm,
CParseHandlerBase *pphRoot
)
:
CParseHandlerScalarOp(pmp, pphm, pphRoot)
{
}
//---------------------------------------------------------------------------
// @function:
// CParseHandlerScalarConstValue::StartElement
//
// @doc:
// Invoked by Xerces to process an opening tag
//
//---------------------------------------------------------------------------
void
CParseHandlerScalarConstValue::StartElement
(
const XMLCh* const, // xmlszUri,
const XMLCh* const xmlszLocalname,
const XMLCh* const, // xmlszQname
const Attributes& attrs
)
{
if(0 != XMLString::compareString(CDXLTokens::XmlstrToken(EdxltokenScalarConstValue), xmlszLocalname))
{
CWStringDynamic *pstr = CDXLUtils::PstrFromXMLCh(m_pphm->Pmm(), xmlszLocalname);
GPOS_RAISE(gpdxl::ExmaDXL, gpdxl::ExmiDXLUnexpectedTag, pstr->Wsz());
}
// parse and create scalar const operator
CDXLScalarConstValue *pdxlop = (CDXLScalarConstValue*) CDXLOperatorFactory::PdxlopConstValue(m_pphm->Pmm(), attrs);
// construct scalar Const node
GPOS_ASSERT(NULL != pdxlop);
m_pdxln = GPOS_NEW(m_pmp) CDXLNode(m_pmp);
m_pdxln->SetOperator(pdxlop);
}
//---------------------------------------------------------------------------
// @function:
// CParseHandlerScalarConstValue::EndElement
//
// @doc:
// Invoked by Xerces to process a closing tag
//
//---------------------------------------------------------------------------
void
CParseHandlerScalarConstValue::EndElement
(
const XMLCh* const, // xmlszUri,
const XMLCh* const xmlszLocalname,
const XMLCh* const // xmlszQname
)
{
if(0 != XMLString::compareString(CDXLTokens::XmlstrToken(EdxltokenScalarConstValue), xmlszLocalname))
{
CWStringDynamic *pstr = CDXLUtils::PstrFromXMLCh(m_pphm->Pmm(), xmlszLocalname);
GPOS_RAISE(gpdxl::ExmaDXL, gpdxl::ExmiDXLUnexpectedTag, pstr->Wsz());
}
// deactivate handler
m_pphm->DeactivateHandler();
}
// EOF
|
PengJi/gporca-comments
|
libnaucrates/src/parser/CParseHandlerScalarConstValue.cpp
|
C++
|
apache-2.0
| 2,914
|
package org.springframework.social.kakao.api.impl;
import org.springframework.social.kakao.api.KakaoApi;
import org.springframework.social.kakao.api.TalkOperations;
public class TalkTemplate extends AbstractKakaoOperations implements TalkOperations {
private final KakaoApi kakaoApi;
public TalkTemplate(KakaoApi kakaoApi, boolean isAuthorizedForUser) {
super(isAuthorizedForUser);
this.kakaoApi = kakaoApi;
}
}
|
Hongchae/spring-social-kakao
|
src/main/java/org/springframework/social/kakao/api/impl/TalkTemplate.java
|
Java
|
apache-2.0
| 445
|
# Listonella damsela (Love et al., 1982) MacDonell & Colwell, 1986 SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Bacteria/Proteobacteria/Gammaproteobacteria/Vibrionales/Vibrionaceae/Photobacterium/Photobacterium damselae/ Syn. Listonella damsela/README.md
|
Markdown
|
apache-2.0
| 221
|
package org.insightech.er.editor.controller.editpolicy.not_element.tablespace;
import org.eclipse.gef.commands.Command;
import org.insightech.er.editor.controller.command.diagram_contents.not_element.tablespace.DeleteTablespaceCommand;
import org.insightech.er.editor.controller.editpolicy.not_element.NotElementComponentEditPolicy;
import org.insightech.er.editor.model.ERDiagram;
import org.insightech.er.editor.model.diagram_contents.not_element.tablespace.Tablespace;
public class TablespaceComponentEditPolicy extends NotElementComponentEditPolicy {
@Override
protected Command createDeleteCommand(ERDiagram diagram, Object model) {
return new DeleteTablespaceCommand(diagram, (Tablespace) model);
}
}
|
crow-misia/ermaster.old
|
org.insightech.er/src/org/insightech/er/editor/controller/editpolicy/not_element/tablespace/TablespaceComponentEditPolicy.java
|
Java
|
apache-2.0
| 732
|
package org.swtk.commons.dict.wordnet.indexbyname.instance.u.n.l; import java.util.ArrayList; import java.util.Collection; import java.util.Map; import java.util.TreeMap; import org.swtk.common.dict.dto.wordnet.IndexNoun; import com.trimc.blogger.commons.utils.GsonUtils; public final class WordnetNounIndexNameInstanceUNL { private static Map<String, Collection<IndexNoun>> map = new TreeMap<String, Collection<IndexNoun>>(); static { add("{\"term\":\"unlawful carnal knowledge\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"00849728\"]}");
add("{\"term\":\"unlawfulness\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"04818117\"]}");
add("{\"term\":\"unleaded gasoline\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"15108386\"]}");
add("{\"term\":\"unleaded petrol\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"15108386\"]}");
add("{\"term\":\"unleavened bread\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"07699909\"]}");
add("{\"term\":\"unlikelihood\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"04766031\"]}");
add("{\"term\":\"unlikeliness\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"04766031\"]}");
add("{\"term\":\"unlikeness\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"04758019\"]}");
add("{\"term\":\"unlisted security\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13442268\"]}");
add("{\"term\":\"unlisted stock\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"13442459\"]}");
add("{\"term\":\"unloading\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"00715425\"]}");
} private static void add(final String JSON) { IndexNoun indexNoun = GsonUtils.toObject(JSON, IndexNoun.class); Collection<IndexNoun> list = (map.containsKey(indexNoun.getTerm())) ? map.get(indexNoun.getTerm()) : new ArrayList<IndexNoun>(); list.add(indexNoun); map.put(indexNoun.getTerm(), list); } public static Collection<IndexNoun> get(final String TERM) { return map.get(TERM); } public static boolean has(final String TERM) { return map.containsKey(TERM); } public static Collection<String> terms() { return map.keySet(); } }
|
torrances/swtk-commons
|
commons-dict-wordnet-indexbyname/src/main/java/org/swtk/commons/dict/wordnet/indexbyname/instance/u/n/l/WordnetNounIndexNameInstanceUNL.java
|
Java
|
apache-2.0
| 2,178
|
# -*- coding: utf-8; -*-
#
# Licensed to CRATE Technology GmbH ("Crate") under one or more contributor
# license agreements. See the NOTICE file distributed with this work for
# additional information regarding copyright ownership. Crate 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.
#
# However, if you have executed another commercial license agreement
# with Crate these terms will supersede the license and you may use the
# software solely pursuant to the terms of the relevant commercial agreement.
import sqlalchemy as sa
from sqlalchemy.ext.declarative import declarative_base
from crate.client.sqlalchemy.types import Object, ObjectArray
from crate.client.cursor import Cursor
from unittest import TestCase
from unittest.mock import patch, MagicMock
fake_cursor = MagicMock(name='fake_cursor')
FakeCursor = MagicMock(name='FakeCursor', spec=Cursor)
FakeCursor.return_value = fake_cursor
@patch('crate.client.connection.Cursor', FakeCursor)
class CreateTableTest(TestCase):
def setUp(self):
self.engine = sa.create_engine('crate://')
self.Base = declarative_base(bind=self.engine)
def test_create_table_with_basic_types(self):
class User(self.Base):
__tablename__ = 'users'
string_col = sa.Column(sa.String, primary_key=True)
unicode_col = sa.Column(sa.Unicode)
text_col = sa.Column(sa.Text)
int_col = sa.Column(sa.Integer)
long_col1 = sa.Column(sa.BigInteger)
long_col2 = sa.Column(sa.NUMERIC)
bool_col = sa.Column(sa.Boolean)
short_col = sa.Column(sa.SmallInteger)
datetime_col = sa.Column(sa.DateTime)
date_col = sa.Column(sa.Date)
float_col = sa.Column(sa.Float)
double_col = sa.Column(sa.DECIMAL)
self.Base.metadata.create_all()
fake_cursor.execute.assert_called_with(
('\nCREATE TABLE users (\n\tstring_col STRING, '
'\n\tunicode_col STRING, \n\ttext_col STRING, \n\tint_col INT, '
'\n\tlong_col1 LONG, \n\tlong_col2 LONG, '
'\n\tbool_col BOOLEAN, '
'\n\tshort_col SHORT, '
'\n\tdatetime_col TIMESTAMP, \n\tdate_col TIMESTAMP, '
'\n\tfloat_col FLOAT, \n\tdouble_col DOUBLE, '
'\n\tPRIMARY KEY (string_col)\n)\n\n'),
())
def test_with_obj_column(self):
class DummyTable(self.Base):
__tablename__ = 'dummy'
pk = sa.Column(sa.String, primary_key=True)
obj_col = sa.Column(Object)
self.Base.metadata.create_all()
fake_cursor.execute.assert_called_with(
('\nCREATE TABLE dummy (\n\tpk STRING, \n\tobj_col OBJECT, '
'\n\tPRIMARY KEY (pk)\n)\n\n'),
())
def test_with_clustered_by(self):
class DummyTable(self.Base):
__tablename__ = 't'
__table_args__ = {
'crate_clustered_by': 'p'
}
pk = sa.Column(sa.String, primary_key=True)
p = sa.Column(sa.String)
self.Base.metadata.create_all()
fake_cursor.execute.assert_called_with(
('\nCREATE TABLE t (\n\t'
'pk STRING, \n\t'
'p STRING, \n\t'
'PRIMARY KEY (pk)\n'
') CLUSTERED BY (p)\n\n'),
())
def test_with_partitioned_by(self):
class DummyTable(self.Base):
__tablename__ = 't'
__table_args__ = {
'crate_partitioned_by': 'p',
'invalid_option': 1
}
pk = sa.Column(sa.String, primary_key=True)
p = sa.Column(sa.String)
self.Base.metadata.create_all()
fake_cursor.execute.assert_called_with(
('\nCREATE TABLE t (\n\t'
'pk STRING, \n\t'
'p STRING, \n\t'
'PRIMARY KEY (pk)\n'
') PARTITIONED BY (p)\n\n'),
())
def test_with_number_of_shards_and_replicas(self):
class DummyTable(self.Base):
__tablename__ = 't'
__table_args__ = {
'crate_number_of_replicas': '2',
'crate_number_of_shards': 3
}
pk = sa.Column(sa.String, primary_key=True)
self.Base.metadata.create_all()
fake_cursor.execute.assert_called_with(
('\nCREATE TABLE t (\n\t'
'pk STRING, \n\t'
'PRIMARY KEY (pk)\n'
') CLUSTERED INTO 3 SHARDS WITH (NUMBER_OF_REPLICAS = 2)\n\n'),
())
def test_with_clustered_by_and_number_of_shards(self):
class DummyTable(self.Base):
__tablename__ = 't'
__table_args__ = {
'crate_clustered_by': 'p',
'crate_number_of_shards': 3
}
pk = sa.Column(sa.String, primary_key=True)
p = sa.Column(sa.String, primary_key=True)
self.Base.metadata.create_all()
fake_cursor.execute.assert_called_with(
('\nCREATE TABLE t (\n\t'
'pk STRING, \n\t'
'p STRING, \n\t'
'PRIMARY KEY (pk, p)\n'
') CLUSTERED BY (p) INTO 3 SHARDS\n\n'),
())
def test_table_with_object_array(self):
class DummyTable(self.Base):
__tablename__ = 't'
pk = sa.Column(sa.String, primary_key=True)
tags = sa.Column(ObjectArray)
self.Base.metadata.create_all()
fake_cursor.execute.assert_called_with(
('\nCREATE TABLE t (\n\t'
'pk STRING, \n\t'
'tags ARRAY(OBJECT), \n\t'
'PRIMARY KEY (pk)\n)\n\n'), ())
|
crate/crate-python
|
src/crate/client/sqlalchemy/tests/create_table_test.py
|
Python
|
apache-2.0
| 6,206
|
# Cheirinia altissima Link SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Brassicales/Brassicaceae/Cheirinia/Cheirinia altissima/README.md
|
Markdown
|
apache-2.0
| 174
|
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/** */
package com.google.mystery.assets.cvs;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVRecord;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.common.base.Charsets;
import com.google.common.collect.Lists;
import com.google.mystery.assets.IImportDataSource;
/** @author Ilya Platonov */
public class CSVDataSource implements IImportDataSource {
@Override
public List<List<Object>> getData(HttpRequestInitializer credential, String id, String range)
throws IOException {
String[] split = range.split("!");
if (split.length == 0) {
throw new IllegalArgumentException("Invalid range " + range);
}
String sheet = split[0];
Iterable<CSVRecord> records =
CSVFormat.DEFAULT.parse(
new InputStreamReader(
this.getClass().getResourceAsStream(String.format("/%s/%s.csv", id, sheet)),
Charsets.UTF_8));
List<List<Object>> result = new ArrayList<>();
for (CSVRecord record : records) {
List<String> row = Lists.newArrayList(record.iterator());
for (ListIterator<String> i = row.listIterator(row.size()); i.hasPrevious(); ) {
String prev = i.previous();
if (prev == null || prev.isEmpty()) {
i.remove();
} else {
break;
}
}
result.add((List) row);
}
return result;
}
}
|
actions-on-google-labs/sherlock-mysteries-java
|
sherlock-web/src/main/java/com/google/mystery/assets/cvs/CSVDataSource.java
|
Java
|
apache-2.0
| 2,134
|
/*
* Copyright 2018 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.river.api.io;
import java.io.StreamCorruptedException;
/**
*
* @author peter
*/
public class CircularReferenceException extends StreamCorruptedException {
CircularReferenceException(String message){
super(message);
}
}
|
pfirmstone/JGDMS
|
JGDMS/jgdms-platform/src/main/java/org/apache/river/api/io/CircularReferenceException.java
|
Java
|
apache-2.0
| 878
|
package com.rightutils.gcm.services.gcm;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.os.AsyncTask;
import android.util.Log;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.rightutils.rightutils.utils.RightUtils;
import java.io.IOException;
/**
* Created by Anton Maniskevich on 5/7/15.
*/
public class RegGCMReceiver extends BroadcastReceiver {
private static final String TAG = RegGCMReceiver.class.getSimpleName();
public static final String PROPERTY_REG_ID = "registration_id";
public static final String PROPERTY_APP_VERSION = "appVersion";
public static final int REG_GCM_INTERVAL = 20 * 1000;
private GoogleCloudMessaging gcm;
//NB your id from google api console
public static final String SENDER_ID = "559174343034";
@Override
public void onReceive(final Context context, Intent intent) {
Log.i(TAG, "REG ID receiver running = " + RightUtils.isOnline(context));
if (RightUtils.isOnline(context)) {
if (checkPlayServices(context)) {
gcm = GoogleCloudMessaging.getInstance(context);
final String redId = getRegistrationId(context);
if (redId.isEmpty()) {
registerInBackground(context);
} else {
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
sendRegistrationIdToBackend(context, redId);
return null;
}
@Override
protected void onPostExecute(Void param) {
}
}.execute();
}
} else {
Log.i(TAG, "No valid Google Play Services APK found.");
}
}
}
private boolean checkPlayServices(Context context) {
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(context);
if (resultCode != ConnectionResult.SUCCESS) {
if (!GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
Log.i(TAG, "This device is not supported.");
cancelLoop(context);
}
return false;
}
return true;
}
private String getRegistrationId(Context context) {
final SharedPreferences prefs = getGCMPreferences(context);
String registrationId = prefs.getString(PROPERTY_REG_ID, "");
if (registrationId == null || registrationId.isEmpty()) {
Log.i(TAG, "Registration not found.");
return "";
}
int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE);
int currentVersion = getAppVersion(context);
if (registeredVersion != currentVersion) {
Log.i(TAG, "App version changed.");
return "";
}
return registrationId;
}
private SharedPreferences getGCMPreferences(Context context) {
return context.getSharedPreferences(TAG, Context.MODE_PRIVATE);
}
private static int getAppVersion(Context context) {
try {
PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
return packageInfo.versionCode;
} catch (Exception e) {
throw new RuntimeException("Could not get package name: " + e);
}
}
private void registerInBackground(final Context context) {
new AsyncTask<Void, Void, String>() {
@Override
protected String doInBackground(Void... params) {
String msg;
try {
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(context);
}
final String pushId = gcm.register(SENDER_ID);
msg = "Device registered, registration ID=" + pushId;
sendRegistrationIdToBackend(context, pushId);
storeRegistrationId(context, pushId);
} catch (IOException ex) {
msg = "Error :" + ex.getMessage();
}
return msg;
}
@Override
protected void onPostExecute(String msg) {
Log.i(TAG, msg);
}
}.execute();
}
private void storeRegistrationId(Context context, String regId) {
final SharedPreferences prefs = getGCMPreferences(context);
int appVersion = getAppVersion(context);
Log.i(TAG, "Saving regId on app version " + appVersion);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(PROPERTY_REG_ID, regId);
editor.putInt(PROPERTY_APP_VERSION, appVersion);
editor.apply();
}
private void cancelLoop(Context context) {
Intent alarmIntent = new Intent(context, RegGCMReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, alarmIntent, 0);
AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
manager.cancel(pendingIntent);
}
private void sendRegistrationIdToBackend(Context context, String redId) {
//TODO send regid to server
Log.i(TAG, redId);
cancelLoop(context);
}
}
|
manfenixhome/GCM
|
app/src/main/java/com/rightutils/gcm/services/gcm/RegGCMReceiver.java
|
Java
|
apache-2.0
| 4,802
|
package com.s4game.server.io.action;
import javax.annotation.Resource;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.s4game.core.action.annotation.ActionMapping;
import com.s4game.core.action.annotation.ActionWorker;
import com.s4game.protocol.Message.Response;
import com.s4game.server.io.IoConstants;
import com.s4game.server.io.global.ChannelManager;
import com.s4game.server.io.message.IoMessage;
import io.netty.channel.Channel;
/**
*
* @Author zeusgooogle@gmail.com
* @sine 2015年5月19日 下午5:02:38
*
*/
@ActionWorker
public class IoMsgOutAction {
private Logger LOG = LoggerFactory.getLogger(getClass());
@Resource
private ChannelManager channelManager;
@ActionMapping(mapping = IoMessage.IO_MSG_OUT_CMD)
public void out(IoMessage message) {
LOG.info("message out: {}", message.toString());
Response.Builder builder = Response.newBuilder();
builder.setCommand(message.getRealCommand()).setData(message.toData());
int route = message.getRoute();
switch (route) {
case IoConstants.SEND_TO_ONE: // one player
Channel channel = null;
String sessionId = message.getSessionId();
if (null != sessionId) {
channel = channelManager.getChannel(sessionId);
}
String roleId = message.getRoleId();
if (!StringUtils.isEmpty(roleId)) {
channel = channelManager.getChannel(roleId);
}
if (null != channel) {
channel.writeAndFlush(builder);
}
break;
case IoConstants.SEND_TO_MANY: // mutile player
for (String id : message.getRoleIds()) {
channel = channelManager.getChannel(id);
channel.writeAndFlush(builder);
}
break;
case IoConstants.SEND_TO_ALL: // all player
break;
}
}
}
|
zuesgooogle/HappyMj
|
mj-game/src/main/java/com/s4game/server/io/action/IoMsgOutAction.java
|
Java
|
apache-2.0
| 2,043
|
<?php
/**
* DRAIWIKI
* Open source wiki software
*
* @version 1.0 Alpha 1
* @author Robert Monden
* @copyright 2017-2018 DraiWiki
* @license Apache 2.0
*/
namespace DraiWiki\src\admin\models;
if (!defined('DraiWiki')) {
header('Location: ../index.php');
die('You\'re really not supposed to be here.');
}
use DraiWiki\src\core\controllers\QueryFactory;
use DraiWiki\src\main\models\{ModelHeader, Table};
class UploadManagement extends ModelHeader {
private $_table, $_request;
private const MAX_UPLOADS_PER_PAGE = 20;
public function generateTable() : void {
$columns = [
'preview',
'filename',
'poster',
'upload_date',
'file_type'
];
$table = new Table('management', $columns, []);
$table->setID('user_list');
$table->create();
$this->_table = $table->returnTable();
}
public function prepareData() : array {
$this->generateTable();
return [
'table' => $this->_table
];
}
public function getPageDescription() : string {
return _localized('management.upload_management_description');
}
public function getTitle() : string {
return _localized('management.upload_management');
}
private function getUploads(int $start = 0) : array {
$uploads = [];
$query = QueryFactory::produce('select', '
SELECT f.original_name, f.type, f.upload_date, u.username
FROM {db_prefix}upload f
INNER JOIN {db_prefix}user u ON (f.user_id = u.id)
ORDER BY f.upload_date DESC
LIMIT ' . $start . ', ' . self::MAX_UPLOADS_PER_PAGE);
foreach ($query->execute() as $record) {
$uploads[] = [
'preview' => $this->getPreview($record['original_name'], $record['type']),
'filename' => $record['original_name'],
'poster' => $record['username'],
'upload_date' => $record['upload_date'],
'file_type' => _localized('management.file_' . $record['type'])
];
}
return $uploads;
}
public function getUploadCount() : int {
$query = QueryFactory::produce('select', '
SELECT COUNT(id) AS num
FROM {db_prefix}upload
');
foreach ($query->execute() as $record)
return (int) $record['num'];
return 0;
}
private function getStart(int $recordCount) : int {
if (!empty($_REQUEST['start']) && is_numeric($_REQUEST['start']) && ((int) $_REQUEST['start']) <= $recordCount) {
return (int) $_REQUEST['start'];
}
else
return 0;
}
public function generateJSON() : string {
switch ($this->_request) {
case 'getlist':
$recordCount = $this->getUploadCount();
$start = $this->getStart($recordCount);
$end = $start + self::MAX_UPLOADS_PER_PAGE;
if ($end > $recordCount)
$end = $start + ($recordCount % self::MAX_UPLOADS_PER_PAGE);
$uploads = [];
foreach ($this->getUploads($start) as $record) {
$uploads[] = [
'preview' => $record['preview'],
'filename' => $record['filename'],
'poster' => $record['poster'],
'upload_date' => $record['upload_date'],
'file_type' => $record['file_type']
];
}
return json_encode([
'start' => $start,
'end' => $end,
'total_records' => $recordCount,
'displayed_records' => self::MAX_UPLOADS_PER_PAGE,
'data' => $uploads
]);
default:
return '';
}
}
public function setRequest(string $request) : void {
$this->_request = $request;
}
private function getPreview(string $filename, string $type) : string {
switch ($type) {
case 'avatar':
case 'uploaded_image':
return '<img src="' . self::$config->read('url') . '/public/ImageDispatch.php?filename=' . $filename . '" alt="*" class="image_preview" />';
default:
return '';
}
}
}
|
Chistaen/DraiWiki
|
src/admin/models/UploadManagement.class.php
|
PHP
|
apache-2.0
| 4,507
|
package app.apphub.devon.walkingquest.Helper;
import android.util.Log;
import app.apphub.devon.walkingquest.database.DatabaseHandler;
import app.apphub.devon.walkingquest.database.objects.Quest;
import app.apphub.devon.walkingquest.database.objects.Reward;
/**
* Created by Devon on 4/1/2017.
*/
public class StringUtils {
/*
* Takes a CSV string of questIds as an input and a database handler. Finds the quests related to the questIds and constructs an array of Quests and
* returns them
*
* Author: Devon Rimmington & Jonathan McDavit
**/
public static Quest[] getQuestByCSV(DatabaseHandler databaseHandler, String csv){
String[] ids = csv.split(",");
Log.i("STRING UTILS", csv.toString());
if(!csv.equals("")) {
int length = ids.length;
Quest[] quests = new Quest[length];
for (int i = 0; i < length; i++) {
Quest quest = databaseHandler.getQuestByID(Integer.parseInt(ids[i]));
if (quest == null)
throw new NullPointerException();
if (quest.isCompleted())
quests[i] = quest;
}
return quests;
}
return new Quest[0];
}
/*
* Adds a new questId to the end of the list of questIds
*
* Author: Devon Rimmington
**/
public static String addCompletedQuestToCharacter(String csv, int newlyCompletedQuest){
if(!csv.equals("")) {
csv += "," + newlyCompletedQuest;
}else{
csv += newlyCompletedQuest;
}
return csv;
}
/*
* Returns the number of questIds in the string
*
* Author: Devon Rimmington
**/
public static int getNumberOfQuestRewards(String csv){
if(csv.equals(""))
return 0;
return csv.split(",").length;
}
}
|
ipettigrew/WalkingQuest
|
WalkingQuest/app/src/main/java/app/apphub/devon/walkingquest/Helper/StringUtils.java
|
Java
|
apache-2.0
| 1,891
|
/*
* Copyright (C) 2015 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.moshi.recipes;
import com.squareup.moshi.JsonAdapter;
import com.squareup.moshi.Moshi;
import com.squareup.moshi.adapters.Rfc3339DateJsonAdapter;
import com.squareup.moshi.recipes.models.Tournament;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;
public final class ReadAndWriteRfc3339Dates {
public void run() throws Exception {
Moshi moshi = new Moshi.Builder().add(Date.class, new Rfc3339DateJsonAdapter()).build();
JsonAdapter<Tournament> jsonAdapter = moshi.adapter(Tournament.class);
// The RFC3339 JSON adapter can read dates with a timezone offset like '-05:00'.
String lastTournament =
""
+ "{"
+ " \"location\":\"Chainsaw\","
+ " \"name\":\"21 for 21\","
+ " \"start\":\"2015-09-01T20:00:00-05:00\""
+ "}";
System.out.println("Last tournament: " + jsonAdapter.fromJson(lastTournament));
// The RFC3339 JSON adapter always writes dates with UTC, using a 'Z' suffix.
Tournament nextTournament =
new Tournament("Waterloo Classic", "Bauer Kitchen", newDate(2015, 10, 1, 20, -5));
System.out.println("Next tournament JSON: " + jsonAdapter.toJson(nextTournament));
}
public static void main(String[] args) throws Exception {
new ReadAndWriteRfc3339Dates().run();
}
private Date newDate(int year, int month, int day, int hour, int offset) {
Calendar calendar = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
calendar.set(year, month - 1, day, hour, 0, 0);
calendar.set(Calendar.MILLISECOND, 0);
return new Date(calendar.getTimeInMillis() - TimeUnit.HOURS.toMillis(offset));
}
}
|
square/moshi
|
examples/src/main/java/com/squareup/moshi/recipes/ReadAndWriteRfc3339Dates.java
|
Java
|
apache-2.0
| 2,359
|
sap.ui.define(['sap/ui/core/UIComponent'],
function(UIComponent) {
"use strict";
var Component = UIComponent.extend("sap.m.sample.ListDeletion.Component", {
metadata : {
manifest: "json"
}
});
return Component;
});
|
SAP/openui5
|
src/sap.m/test/sap/m/demokit/sample/ListDeletion/Component.js
|
JavaScript
|
apache-2.0
| 232
|
# Acacia rutaefolia auct. non Link 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/Acacia/Acacia leioderma/ Syn. Acacia rutaefolia/README.md
|
Markdown
|
apache-2.0
| 189
|
# Cassia reticulata Willd. SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
Enum. pl. 1:443. 1809
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Fabales/Fabaceae/Senna/Senna reticulata/ Syn. Cassia reticulata/README.md
|
Markdown
|
apache-2.0
| 198
|
# Caryospermum alpestre Kuntze SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Celastrales/Celastraceae/Caryospermum/Caryospermum alpestre/README.md
|
Markdown
|
apache-2.0
| 178
|
# Cyclotella glomerata-stelligera Bachmann-Cleve & Grunow SPECIES
#### Status
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Chromista/Ochrophyta/Coscinodiscophyceae/Thalassiosirales/Stephanodiscaceae/Cyclotella/Cyclotella glomerata-stelligera/README.md
|
Markdown
|
apache-2.0
| 213
|
# Pogonanthera squamulata Korth. ex Blume 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/Myrtales/Melastomataceae/Pachycentria/Pachycentria pulverulenta/ Syn. Pogonanthera squamulata/README.md
|
Markdown
|
apache-2.0
| 196
|
# Erucaria hypognea Viv. SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Brassicales/Brassicaceae/Erucaria/Erucaria hypognea/README.md
|
Markdown
|
apache-2.0
| 172
|
# Heterolepis conyzoides Bertero ex DC. 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/Senecio adenotrichius/ Syn. Heterolepis conyzoides/README.md
|
Markdown
|
apache-2.0
| 194
|
# Codiolum nordenskjoldianum Kjellman SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Chlorophyta/Ulvophyceae/Codiolales/Acrosiphoniaceae/Urospora/Urospora wormskioldii/ Syn. Codiolum nordenskjoldianum/README.md
|
Markdown
|
apache-2.0
| 192
|
# Ixeris dentata subsp. kitayamensis Murata SUBSPECIES
#### 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/ Syn. Ixeris dentata kitayamensis/README.md
|
Markdown
|
apache-2.0
| 201
|
# Salsola globulifera Fenzl SPECIES
#### 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/Caryophyllales/Chenopodiaceae/Salsola/Salsola globulifera/README.md
|
Markdown
|
apache-2.0
| 183
|
# Ormosia obscurinervia Tanaka & Odash. 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/Ormosia/Ormosia simplicifolia/ Syn. Ormosia obscurinervia/README.md
|
Markdown
|
apache-2.0
| 194
|
/*
* 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.flink.streaming.runtime.tasks;
import org.apache.flink.core.fs.FileSystemSafetyNet;
import org.apache.flink.runtime.checkpoint.CheckpointException;
import org.apache.flink.runtime.checkpoint.CheckpointFailureReason;
import org.apache.flink.runtime.checkpoint.CheckpointMetaData;
import org.apache.flink.runtime.checkpoint.CheckpointMetrics;
import org.apache.flink.runtime.checkpoint.CheckpointMetricsBuilder;
import org.apache.flink.runtime.checkpoint.TaskStateSnapshot;
import org.apache.flink.runtime.execution.Environment;
import org.apache.flink.runtime.jobgraph.OperatorID;
import org.apache.flink.streaming.api.operators.OperatorSnapshotFinalizer;
import org.apache.flink.streaming.api.operators.OperatorSnapshotFutures;
import org.apache.flink.util.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.Closeable;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
import java.util.function.Supplier;
import static org.apache.flink.util.Preconditions.checkNotNull;
import static org.apache.flink.util.Preconditions.checkState;
/**
* This runnable executes the asynchronous parts of all involved backend snapshots for the subtask.
*/
final class AsyncCheckpointRunnable implements Runnable, Closeable {
public static final Logger LOG = LoggerFactory.getLogger(AsyncCheckpointRunnable.class);
private final String taskName;
private final Consumer<AsyncCheckpointRunnable> registerConsumer;
private final Consumer<AsyncCheckpointRunnable> unregisterConsumer;
private final Supplier<Boolean> isTaskRunning;
private final Environment taskEnvironment;
public boolean isRunning() {
return asyncCheckpointState.get() == AsyncCheckpointState.RUNNING;
}
enum AsyncCheckpointState {
RUNNING,
DISCARDED,
COMPLETED
}
private final AsyncExceptionHandler asyncExceptionHandler;
private final Map<OperatorID, OperatorSnapshotFutures> operatorSnapshotsInProgress;
private final CheckpointMetaData checkpointMetaData;
private final CheckpointMetricsBuilder checkpointMetrics;
private final long asyncConstructionNanos;
private final AtomicReference<AsyncCheckpointState> asyncCheckpointState =
new AtomicReference<>(AsyncCheckpointState.RUNNING);
AsyncCheckpointRunnable(
Map<OperatorID, OperatorSnapshotFutures> operatorSnapshotsInProgress,
CheckpointMetaData checkpointMetaData,
CheckpointMetricsBuilder checkpointMetrics,
long asyncConstructionNanos,
String taskName,
Consumer<AsyncCheckpointRunnable> register,
Consumer<AsyncCheckpointRunnable> unregister,
Environment taskEnvironment,
AsyncExceptionHandler asyncExceptionHandler,
Supplier<Boolean> isTaskRunning) {
this.operatorSnapshotsInProgress = checkNotNull(operatorSnapshotsInProgress);
this.checkpointMetaData = checkNotNull(checkpointMetaData);
this.checkpointMetrics = checkNotNull(checkpointMetrics);
this.asyncConstructionNanos = asyncConstructionNanos;
this.taskName = checkNotNull(taskName);
this.registerConsumer = register;
this.unregisterConsumer = unregister;
this.taskEnvironment = checkNotNull(taskEnvironment);
this.asyncExceptionHandler = checkNotNull(asyncExceptionHandler);
this.isTaskRunning = isTaskRunning;
}
@Override
public void run() {
final long asyncStartNanos = System.nanoTime();
final long asyncStartDelayMillis = (asyncStartNanos - asyncConstructionNanos) / 1_000_000L;
LOG.debug(
"{} - started executing asynchronous part of checkpoint {}. Asynchronous start delay: {} ms",
taskName,
checkpointMetaData.getCheckpointId(),
asyncStartDelayMillis);
FileSystemSafetyNet.initializeSafetyNetForThread();
try {
registerConsumer.accept(this);
TaskStateSnapshot jobManagerTaskOperatorSubtaskStates =
new TaskStateSnapshot(operatorSnapshotsInProgress.size());
TaskStateSnapshot localTaskOperatorSubtaskStates =
new TaskStateSnapshot(operatorSnapshotsInProgress.size());
long bytesPersistedDuringAlignment = 0;
for (Map.Entry<OperatorID, OperatorSnapshotFutures> entry :
operatorSnapshotsInProgress.entrySet()) {
OperatorID operatorID = entry.getKey();
OperatorSnapshotFutures snapshotInProgress = entry.getValue();
// finalize the async part of all by executing all snapshot runnables
OperatorSnapshotFinalizer finalizedSnapshots =
new OperatorSnapshotFinalizer(snapshotInProgress);
jobManagerTaskOperatorSubtaskStates.putSubtaskStateByOperatorID(
operatorID, finalizedSnapshots.getJobManagerOwnedState());
localTaskOperatorSubtaskStates.putSubtaskStateByOperatorID(
operatorID, finalizedSnapshots.getTaskLocalState());
bytesPersistedDuringAlignment +=
finalizedSnapshots
.getJobManagerOwnedState()
.getResultSubpartitionState()
.getStateSize();
bytesPersistedDuringAlignment +=
finalizedSnapshots
.getJobManagerOwnedState()
.getInputChannelState()
.getStateSize();
}
final long asyncEndNanos = System.nanoTime();
final long asyncDurationMillis = (asyncEndNanos - asyncConstructionNanos) / 1_000_000L;
checkpointMetrics.setBytesPersistedDuringAlignment(bytesPersistedDuringAlignment);
checkpointMetrics.setAsyncDurationMillis(asyncDurationMillis);
if (asyncCheckpointState.compareAndSet(
AsyncCheckpointState.RUNNING, AsyncCheckpointState.COMPLETED)) {
reportCompletedSnapshotStates(
jobManagerTaskOperatorSubtaskStates,
localTaskOperatorSubtaskStates,
asyncDurationMillis);
} else {
LOG.debug(
"{} - asynchronous part of checkpoint {} could not be completed because it was closed before.",
taskName,
checkpointMetaData.getCheckpointId());
}
} catch (Exception e) {
LOG.info(
"{} - asynchronous part of checkpoint {} could not be completed.",
taskName,
checkpointMetaData.getCheckpointId(),
e);
handleExecutionException(e);
} finally {
unregisterConsumer.accept(this);
FileSystemSafetyNet.closeSafetyNetAndGuardedResourcesForThread();
}
}
private void reportCompletedSnapshotStates(
TaskStateSnapshot acknowledgedTaskStateSnapshot,
TaskStateSnapshot localTaskStateSnapshot,
long asyncDurationMillis) {
boolean hasAckState = acknowledgedTaskStateSnapshot.hasState();
boolean hasLocalState = localTaskStateSnapshot.hasState();
checkState(
hasAckState || !hasLocalState,
"Found cached state but no corresponding primary state is reported to the job "
+ "manager. This indicates a problem.");
// we signal stateless tasks by reporting null, so that there are no attempts to assign
// empty state
// to stateless tasks on restore. This enables simple job modifications that only concern
// stateless without the need to assign them uids to match their (always empty) states.
taskEnvironment
.getTaskStateManager()
.reportTaskStateSnapshots(
checkpointMetaData,
checkpointMetrics
.setTotalBytesPersisted(
acknowledgedTaskStateSnapshot.getStateSize())
.build(),
hasAckState ? acknowledgedTaskStateSnapshot : null,
hasLocalState ? localTaskStateSnapshot : null);
LOG.debug(
"{} - finished asynchronous part of checkpoint {}. Asynchronous duration: {} ms",
taskName,
checkpointMetaData.getCheckpointId(),
asyncDurationMillis);
LOG.trace(
"{} - reported the following states in snapshot for checkpoint {}: {}.",
taskName,
checkpointMetaData.getCheckpointId(),
acknowledgedTaskStateSnapshot);
}
private void reportAbortedSnapshotStats(long stateSize) {
CheckpointMetrics metrics =
checkpointMetrics.setTotalBytesPersisted(stateSize).buildIncomplete();
LOG.trace(
"{} - report failed checkpoint stats: {} {}",
taskName,
checkpointMetaData.getCheckpointId(),
metrics);
taskEnvironment
.getTaskStateManager()
.reportIncompleteTaskStateSnapshots(checkpointMetaData, metrics);
}
private void handleExecutionException(Exception e) {
boolean didCleanup = false;
AsyncCheckpointState currentState = asyncCheckpointState.get();
while (AsyncCheckpointState.DISCARDED != currentState) {
if (asyncCheckpointState.compareAndSet(currentState, AsyncCheckpointState.DISCARDED)) {
didCleanup = true;
try {
cleanup();
} catch (Exception cleanupException) {
e.addSuppressed(cleanupException);
}
Exception checkpointException =
new Exception(
"Could not materialize checkpoint "
+ checkpointMetaData.getCheckpointId()
+ " for operator "
+ taskName
+ '.',
e);
if (isTaskRunning.get()) {
// We only report the exception for the original cause of fail and cleanup.
// Otherwise this followup exception could race the original exception in
// failing the task.
try {
Optional<CheckpointException> underlyingCheckpointException =
ExceptionUtils.findThrowable(
checkpointException, CheckpointException.class);
// If this failure is already a CheckpointException, do not overwrite the
// original CheckpointFailureReason
CheckpointFailureReason reportedFailureReason =
underlyingCheckpointException
.map(exception -> exception.getCheckpointFailureReason())
.orElse(CheckpointFailureReason.CHECKPOINT_ASYNC_EXCEPTION);
taskEnvironment.declineCheckpoint(
checkpointMetaData.getCheckpointId(),
new CheckpointException(
reportedFailureReason, checkpointException));
} catch (Exception unhandled) {
AsynchronousException asyncException = new AsynchronousException(unhandled);
asyncExceptionHandler.handleAsyncException(
"Failure in asynchronous checkpoint materialization",
asyncException);
}
} else {
// We never decline checkpoint after task is not running to avoid unexpected job
// failover, which caused by exceeding checkpoint tolerable failure threshold.
LOG.warn(
"As task is already not running, no longer decline checkpoint {}.",
checkpointMetaData.getCheckpointId(),
checkpointException);
}
currentState = AsyncCheckpointState.DISCARDED;
} else {
currentState = asyncCheckpointState.get();
}
}
if (!didCleanup) {
LOG.trace(
"Caught followup exception from a failed checkpoint thread. This can be ignored.",
e);
}
}
@Override
public void close() {
if (asyncCheckpointState.compareAndSet(
AsyncCheckpointState.RUNNING, AsyncCheckpointState.DISCARDED)) {
try {
final long stateSize = cleanup();
reportAbortedSnapshotStats(stateSize);
} catch (Exception cleanupException) {
LOG.warn(
"Could not properly clean up the async checkpoint runnable.",
cleanupException);
}
} else {
logFailedCleanupAttempt();
}
}
long getCheckpointId() {
return checkpointMetaData.getCheckpointId();
}
/** @return discarded state size (if available). */
private long cleanup() throws Exception {
LOG.debug(
"Cleanup AsyncCheckpointRunnable for checkpoint {} of {}.",
checkpointMetaData.getCheckpointId(),
taskName);
Exception exception = null;
// clean up ongoing operator snapshot results and non partitioned state handles
long stateSize = 0;
for (OperatorSnapshotFutures operatorSnapshotResult :
operatorSnapshotsInProgress.values()) {
if (operatorSnapshotResult != null) {
try {
stateSize += operatorSnapshotResult.cancel();
} catch (Exception cancelException) {
exception = ExceptionUtils.firstOrSuppressed(cancelException, exception);
}
}
}
if (null != exception) {
throw exception;
}
return stateSize;
}
private void logFailedCleanupAttempt() {
LOG.debug(
"{} - asynchronous checkpointing operation for checkpoint {} has "
+ "already been completed. Thus, the state handles are not cleaned up.",
taskName,
checkpointMetaData.getCheckpointId());
}
}
|
kl0u/flink
|
flink-streaming-java/src/main/java/org/apache/flink/streaming/runtime/tasks/AsyncCheckpointRunnable.java
|
Java
|
apache-2.0
| 15,931
|
#include "DA2TextWin.h"
bool cTextWin::SetWindow(int x, int y, char *txt){
xPos=x;
yPos=y;
//text.Init(ddGfx);
strcpy(str,txt);
return true;
}
bool cTextWin::Render(){
SDL_Rect r;
Uint8 R, G, B, A;
r.x=xPos;
r.y=yPos;
r.w=545;
r.h=175;
//translucent background
SDL_GetRenderDrawColor(display->renderer, &R, &G, &B, &A);
SDL_SetRenderDrawColor(display->renderer, 0, 0, 0, 200);
SDL_RenderFillRect(display->renderer, &r);
SDL_SetRenderDrawColor(display->renderer, R, G, B, A);
SDL_RenderCopy(display->renderer, ddGfx->Windows->texture, &ddGfx->aWindows[0], &r);
text.drawText(display->renderer,xPos+21,yPos+16,63,str);
return true;
}
//This function checks to see if space or mouse button was pressed. If so, close the window.
bool cTextWin::Logic(){
diObj->pollEvents();
//Make sure keys and buttons aren't locked
if( diObj->CheckLockMouse(0) || diObj->CheckLockMouse(1) || diObj->CheckLock(KEY_SPACE)) return true;
if( diObj->MousePress(0) ){
diObj->LockMouse(0);
return false;
}
if( diObj->KeyPress(KEY_SPACE) ) {
diObj->LockKey(KEY_SPACE);
return false;
}
return true;
}
|
DungMunkey/Dark-Ages-2
|
DA2TextWin.cpp
|
C++
|
apache-2.0
| 1,136
|
<!DOCTYPE html>
<html lang="en">
<head>
<title>BabylonJS - tools</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="author" href="humans.txt" />
<!-- FB -->
<meta property="og:title" content="Babylon.js: Powerful, Beautiful, Simple, Open - Web-Based 3D At Its Best" />
<meta property="og:site_name" content="Babylon.js" />
<meta property="og:url" content="https://www.babylonjs.com" />
<meta property="og:description"
content="Babylon.js is one of the world's leading WebGL-based graphics engines. From a new visual scene inspector, best-in-class physically-based rendering, countless performance optimizations, and much more, Babylon.js brings powerful, beautiful, simple, and open 3D to everyone on the web." />
<meta property="og:type" content="website" />
<meta property="og:image" content="https://www.babylonjs.com/assets/logo-babylonjs-social-twitter.png" />
<meta property="og:locale" content="en_US" />
<!-- Twitter -->
<meta name="twitter:card" content="summary" />
<meta name="twitter:url" content="https://www.babylonjs.com" />
<meta name="twitter:title" content="Babylon.js: Powerful, Beautiful, Simple, Open - Web-Based 3D At Its Best" />
<meta name="twitter:description"
content="Babylon.js is one of the world's leading WebGL-based graphics engines. From a new visual scene inspector, best-in-class physically-based rendering, countless performance optimizations, and much more, Babylon.js brings powerful, beautiful, simple, and open 3D to everyone on the web." />
<meta name="twitter:image" content="https://www.babylonjs.com/assets/logo-babylonjs-social-twitter.png" />
<meta name="description" property="" content="BabylonJS - tools" />
<meta name="" property="og:title" content="BabylonJS - tools" />
<link rel="shortcut icon" href="/assets/favicon.ico">
<link rel="icon" type="image/png" href="/assets/favicon.ico">
<link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">
<link rel="stylesheet" href="https://use.typekit.net/cta4xsb.css">
<link rel="stylesheet" href="/assets/styles/variables.css">
<link rel="stylesheet" href="/assets/styles/upTriangleBlock.css">
<link rel="stylesheet" href="/assets/styles/downTriangleBlock.css">
<link rel="stylesheet" href="/assets/styles/header.css">
<link rel="stylesheet" href="/assets/styles/footer.css">
<link rel="stylesheet" href="/assets/styles/gallery.css">
<link rel="stylesheet" href="/assets/styles/topBlock.css">
<link rel="stylesheet" href="/assets/styles/carousel.css">
<link rel="stylesheet" href="/assets/styles/textBlock.css">
<link rel="stylesheet" href="/assets/styles/imageBlock.css">
<link rel="stylesheet" href="/assets/styles/twoColumns.css">
<link rel="stylesheet" href="/assets/styles/imageAndTextBlock.css">
<link rel="stylesheet" href="/assets/styles/linkList.css">
<link rel="stylesheet" href="/assets/styles/imageList.css">
<link rel="stylesheet" href="/assets/styles/styles.css">
<link rel="stylesheet" href="/assets/styles/mediaQueries.css">
<link rel="author" href="humans.txt">
</head>
<body>
<div class="container-header-background"></div>
<div class="header">
<div class="container-header">
<div class="menu-btn">
<img src="/assets/img/HamburgerIcon.svg">
</div>
<div class="babylon-logo hidden">
<a href="/">
<img src="/assets/img/BabylonIdentity.svg">
</a>
</div>
<a class="download" href="https://github.com/BabylonJS/Babylon.js"><img src="/assets/img/GithubIcon.svg"></a>
<div class="header-top-wrapper overflow">
<div class="header-top">
<div class="menu">
<div class="header-ul-wrapper">
<ul>
<li class="TOOLS user-select"><a class="TOOLS">TOOLS</a>
<li class="COMMUNITY user-select"><a class="COMMUNITY">COMMUNITY</a>
<li class="GAMES user-select"><a class="GAMES"
href="/games">GAMES</a>
<li class="E-COMMERCE user-select"><a class="E-COMMERCE"
href="/ecommerce">E-COMMERCE</a>
<li class="BABYLON NATIVE user-select"><a class="BABYLON NATIVE">BABYLON NATIVE</a>
<li class="LEARN user-select"><a class="LEARN">LEARN</a>
<li class="SPECIFICATIONS user-select"><a class="SPECIFICATIONS"
href="/specifications">SPECIFICATIONS</a>
<li class="RELEASE NOTES user-select"><a class="RELEASE NOTES"
href="https://doc.babylonjs.com/whats-new">RELEASE NOTES</a>
<li class="GET user-select"><a class="GET"
href="https://doc.babylonjs.com/babylon101/how_to_get">GET</a>
</ul>
</div>
<div class="sub-menu">
<ul class="TOOLS hidden">
<li class="user-select"><a href="https://playground.babylonjs.com/" target="_blank">PLAYGROUND</a></li>
<li class="user-select"><a href="https://sandbox.babylonjs.com/" target="_blank">SANDBOX</a></li>
<li class="user-select"><a href="https://nme.babylonjs.com/" target="_blank">NODE MATERIAL EDITOR</a></li>
<li class="user-select"><a href="https://doc.babylonjs.com/" target="_blank">DOCUMENTATION</a></li>
<li class="user-select"><a href="https://github.com/BabylonJS/Exporters/" target="_blank">EXPORTERS</a></li>
<li class="user-select"><a href="https://spector.babylonjs.com/" target="_blank">SPECTOR.JS</a></li>
</ul>
<ul class="COMMUNITY hidden">
<li class="user-select"><a href="https://forum.babylonjs.com" target="_blank">FORUM</a></li>
<li class="user-select"><a href="/community" target="">DEMOS</a></li>
</ul>
<ul class="BABYLON NATIVE hidden">
<li class="user-select"><a href="/native" target="">BABYLON NATIVE RUNTIME</a></li>
<li class="user-select"><a href="/reactnative" target="">BABYLON REACT NATIVE</a></li>
</ul>
<ul class="LEARN hidden">
<li class="user-select"><a href="https://doc.babylonjs.com/" target="_blank">DOCUMENTATION</a></li>
<li class="user-select"><a href="https://www.youtube.com/channel/UCyOemMa5EJkIgVavJjSCLKQ" target="_blank">VIDEOS</a></li>
<li class="user-select"><a href="https://medium.com/@babylonjs" target="_blank">BLOG</a></li>
</ul>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="content-container">
<div class="text-block">
<div class="inner-container" style="margin-left:;margin-right:">
<h2>WHY CHOOSE BABYLON.JS?</h2>
<p>Babylon.js is a fully-featured 3D framework built on the WebGL platform. The engine works seamlessly and transparently on both WebGL 1.0 and WebGL 2.0 platforms. And Babylon.js is available on the devices your users frequent:</p>
</div>
</div>
<section class="image-and-text-block "
style="background-color: #5C5C5C;">
<div class="inner-container" style="max-height:;padding-top:;padding-bottom:;">
<div>
<img src="completeSceneGraph" alt="Complete scene graph" style="width:">
</div>
<div class="text-block"
style="text-align:;width:;margin-left:;margin-right:;">
<h2>COMPLETE SCENE GRAPH</h2>
<p style="color:">Babylon.js offers a fully-featured scene graph with nodes available for lights, cameras, materials, meshes, sprites, layers, animations, audio clips, GUI elements and actions.</p>
</div>
</div>
</section>
<section class="image-and-text-block right "
style="background-color: #00000000;">
<div class="inner-container" style="max-height:;padding-top:;padding-bottom:;">
<div class="text-block"
style="text-align:;width:;margin-left:;margin-right:;">
<h2>SCENE INTERACTION</h2>
<p style="color:">Interactions with elements in the 3D scene are made easy through the integration or ray casting, behaviors and mesh picking in Babylon.js. Give your users full control over your 3D environment.</p>
</div>
<div>
<img src="sceneInteraction" alt="Scene interaction" style="width:">
</div>
</div>
</section>
<section class="image-and-text-block "
style="background-color: #282828;">
<div class="inner-container" style="max-height:;padding-top:;padding-bottom:;">
<div>
<img src="guiSystem" alt="GUI system" style="width:">
</div>
<div class="text-block"
style="text-align:;width:;margin-left:;margin-right:;">
<h2>GUI SYSTEM</h2>
<p style="color:">Your user interface needs are covered with the full-fledged GUI engine that provides a complete set of controls like buttons, grid, stack panels, lists and so on.</p>
</div>
</div>
</section>
<section class="image-and-text-block right "
style="background-color: #00000000;">
<div class="inner-container" style="max-height:;padding-top:;padding-bottom:;">
<div class="text-block"
style="text-align:;width:;margin-left:;margin-right:;">
<h2>IMPORT AND EXPORT</h2>
<p style="color:">Work with existing file formats with our gITFm OBJ and STL importers. Export your entire scene to OBJ or gITL, SImply load all your scene assets with a few lines of code thanks to the AssetsManager</p>
</div>
<div>
<img src="importAndExport" alt="Import and export" style="width:">
</div>
</div>
</section>
<section class="image-and-text-block right "
style="background-color: #333333;">
<div class="inner-container" style="max-height:;padding-top:;padding-bottom:;">
<div class="text-block"
style="text-align:;width:;margin-left:;margin-right:;">
<h2>EASILY INSPECT AND SETUP YOUR SCENE</h2>
<p style="color:">Interactions with elements in the 3D scene are made easy through the integration or ray casting, behaviors and mesh picking in Babylon.js. Give your users full control over your 3D environment.</p>
</div>
<div>
<img src="inspectAndSetupScene" alt="EASILY INSPECT AND SETUP YOUR SCENE" style="width:">
</div>
</div>
</section>
<div class="middle-block">
<div class="container">
<div class="middle-background">
<h2>FEATURED DEMOS</h2>
<div class="container-info">
<ul id="hexGrid">
<li class="hex">
<div class="hexIn">
<a class="hexLink" href="https://google.com">
<img src="featuredDemo1" alt="Demo 1 description" />
<div class="desc">
<div class="hexDesc"></div>
<div class="hexDesc author"></div>
</div>
<img src="/assets/img/hoverFrame.svg" class="hoverFrame" />
<img src="/assets/img/defaultFrame.svg" class="defaultFrame" />
</a>
</div>
</li>
<li class="hex">
<div class="hexIn">
<a class="hexLink" href="https://google.ua">
<img src="featuredDemo2" alt="Demo 2 description" />
<div class="desc">
<div class="hexDesc"></div>
<div class="hexDesc author"></div>
</div>
<img src="/assets/img/hoverFrame.svg" class="hoverFrame" />
<img src="/assets/img/defaultFrame.svg" class="defaultFrame" />
</a>
</div>
</li>
<li class="hex">
<div class="hexIn">
<a class="hexLink" href="https://google.nl">
<img src="featuredDemo3" alt="Demo 3 description" />
<div class="desc">
<div class="hexDesc"></div>
<div class="hexDesc author"></div>
</div>
<img src="/assets/img/hoverFrame.svg" class="hoverFrame" />
<img src="/assets/img/defaultFrame.svg" class="defaultFrame" />
</a>
</div>
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
<footer class="footer">
<div class="footer-container">
<div class="footer-left">
<div class="social-icons">
<a href="https://www.twitter.com/babylonjs" target="_blank"><img src="/assets/img/TwitterIcon.svg" alt="Twitter"></a>
<a href="https://github.com/BabylonJS/Babylon.js" target="_blank"><img src="/assets/img/GithubIcon.svg" alt="Github"></a>
<a href="https://forum.babylonjs.com/" target="_blank"><img src="/assets/img/DiscourseIcon.svg" alt="Forum"></a>
<a href="https://medium.com/@babylonjs" target="_blank"><img src="/assets/img/MediumIcon.svg" alt="Blog"></a>
<a href="https://www.youtube.com/channel/UCyOemMa5EJkIgVavJjSCLKQ" target="_blank"><img src="/assets/img/YouTubeIcon.svg" alt="YouTube channel"></a>
<a href="https://www.netlify.com" target="_blank"><img src="/assets/img/netlify.svg" alt="Hosted by Netlify"></a>
</div>
</div>
<div class="footer-right">
<a href="https://forum.babylonjs.com" target="_blank">Forum</a>
<a href="https://doc.babylonjs.com/how_to/how_to_start" target="_blank">Contribute</a>
<a href="https://doc.babylonjs.com/babylon101" target="_blank">Tutorials</a>
<a href="https://github.com/BabylonJS/Brand-Toolkit" target="_blank">Branding</a>
</div>
</div>
</footer>
<script src="/assets/js/animation.js"></script>
<script src="/assets/js/scripts.js"></script>
<script src="/assets/js/pullRefresh.js"></script>
</body>
</html>
|
BabylonJS/Samples
|
build/learn/index.html
|
HTML
|
apache-2.0
| 16,236
|
/* Generic definitions */
#define PACKAGE it.unimi.dsi.fastutil.ints
#define VALUE_PACKAGE it.unimi.dsi.fastutil.bytes
/* Assertions (useful to generate conditional code) */
#unassert keyclass
#assert keyclass(Integer)
#unassert keys
#assert keys(primitive)
#unassert valueclass
#assert valueclass(Byte)
#unassert values
#assert values(primitive)
/* Current type and class (and size, if applicable) */
#define KEY_TYPE int
#define VALUE_TYPE byte
#define KEY_CLASS Integer
#define VALUE_CLASS Byte
#if #keyclass(Object) || #keyclass(Reference)
#define KEY_GENERIC_CLASS K
#define KEY_GENERIC_TYPE K
#define KEY_GENERIC <K>
#define KEY_GENERIC_WILDCARD <?>
#define KEY_EXTENDS_GENERIC <? extends K>
#define KEY_SUPER_GENERIC <? super K>
#define KEY_GENERIC_CAST (K)
#define KEY_GENERIC_ARRAY_CAST (K[])
#define KEY_GENERIC_BIG_ARRAY_CAST (K[][])
#else
#define KEY_GENERIC_CLASS KEY_CLASS
#define KEY_GENERIC_TYPE KEY_TYPE
#define KEY_GENERIC
#define KEY_GENERIC_WILDCARD
#define KEY_EXTENDS_GENERIC
#define KEY_SUPER_GENERIC
#define KEY_GENERIC_CAST
#define KEY_GENERIC_ARRAY_CAST
#define KEY_GENERIC_BIG_ARRAY_CAST
#endif
#if #valueclass(Object) || #valueclass(Reference)
#define VALUE_GENERIC_CLASS V
#define VALUE_GENERIC_TYPE V
#define VALUE_GENERIC <V>
#define VALUE_EXTENDS_GENERIC <? extends V>
#define VALUE_GENERIC_CAST (V)
#define VALUE_GENERIC_ARRAY_CAST (V[])
#else
#define VALUE_GENERIC_CLASS VALUE_CLASS
#define VALUE_GENERIC_TYPE VALUE_TYPE
#define VALUE_GENERIC
#define VALUE_EXTENDS_GENERIC
#define VALUE_GENERIC_CAST
#define VALUE_GENERIC_ARRAY_CAST
#endif
#if #keyclass(Object) || #keyclass(Reference)
#if #valueclass(Object) || #valueclass(Reference)
#define KEY_VALUE_GENERIC <K,V>
#define KEY_VALUE_EXTENDS_GENERIC <? extends K, ? extends V>
#else
#define KEY_VALUE_GENERIC <K>
#define KEY_VALUE_EXTENDS_GENERIC <? extends K>
#endif
#else
#if #valueclass(Object) || #valueclass(Reference)
#define KEY_VALUE_GENERIC <V>
#define KEY_VALUE_EXTENDS_GENERIC <? extends V>
#else
#define KEY_VALUE_GENERIC
#define KEY_VALUE_EXTENDS_GENERIC
#endif
#endif
/* Value methods */
#define KEY_VALUE intValue
#define VALUE_VALUE byteValue
/* Interfaces (keys) */
#define COLLECTION IntCollection
#define SET IntSet
#define HASH IntHash
#define SORTED_SET IntSortedSet
#define STD_SORTED_SET IntSortedSet
#define FUNCTION Int2ByteFunction
#define MAP Int2ByteMap
#define SORTED_MAP Int2ByteSortedMap
#if #keyclass(Object) || #keyclass(Reference)
#define STD_SORTED_MAP SortedMap
#define STRATEGY Strategy
#else
#define STD_SORTED_MAP Int2ByteSortedMap
#define STRATEGY PACKAGE.IntHash.Strategy
#endif
#define LIST IntList
#define BIG_LIST IntBigList
#define STACK IntStack
#define PRIORITY_QUEUE IntPriorityQueue
#define INDIRECT_PRIORITY_QUEUE IntIndirectPriorityQueue
#define INDIRECT_DOUBLE_PRIORITY_QUEUE IntIndirectDoublePriorityQueue
#define KEY_ITERATOR IntIterator
#define KEY_ITERABLE IntIterable
#define KEY_BIDI_ITERATOR IntBidirectionalIterator
#define KEY_LIST_ITERATOR IntListIterator
#define KEY_BIG_LIST_ITERATOR IntBigListIterator
#define STD_KEY_ITERATOR IntIterator
#define KEY_COMPARATOR IntComparator
/* Interfaces (values) */
#define VALUE_COLLECTION ByteCollection
#define VALUE_ARRAY_SET ByteArraySet
#define VALUE_ITERATOR ByteIterator
#define VALUE_LIST_ITERATOR ByteListIterator
/* Abstract implementations (keys) */
#define ABSTRACT_COLLECTION AbstractIntCollection
#define ABSTRACT_SET AbstractIntSet
#define ABSTRACT_SORTED_SET AbstractIntSortedSet
#define ABSTRACT_FUNCTION AbstractInt2ByteFunction
#define ABSTRACT_MAP AbstractInt2ByteMap
#define ABSTRACT_FUNCTION AbstractInt2ByteFunction
#define ABSTRACT_SORTED_MAP AbstractInt2ByteSortedMap
#define ABSTRACT_LIST AbstractIntList
#define ABSTRACT_BIG_LIST AbstractIntBigList
#define SUBLIST IntSubList
#define ABSTRACT_PRIORITY_QUEUE AbstractIntPriorityQueue
#define ABSTRACT_STACK AbstractIntStack
#define KEY_ABSTRACT_ITERATOR AbstractIntIterator
#define KEY_ABSTRACT_BIDI_ITERATOR AbstractIntBidirectionalIterator
#define KEY_ABSTRACT_LIST_ITERATOR AbstractIntListIterator
#define KEY_ABSTRACT_BIG_LIST_ITERATOR AbstractIntBigListIterator
#if #keyclass(Object)
#define KEY_ABSTRACT_COMPARATOR Comparator
#else
#define KEY_ABSTRACT_COMPARATOR AbstractIntComparator
#endif
/* Abstract implementations (values) */
#define VALUE_ABSTRACT_COLLECTION AbstractByteCollection
#define VALUE_ABSTRACT_ITERATOR AbstractByteIterator
#define VALUE_ABSTRACT_BIDI_ITERATOR AbstractByteBidirectionalIterator
/* Static containers (keys) */
#define COLLECTIONS IntCollections
#define SETS IntSets
#define SORTED_SETS IntSortedSets
#define LISTS IntLists
#define BIG_LISTS IntBigLists
#define MAPS Int2ByteMaps
#define FUNCTIONS Int2ByteFunctions
#define SORTED_MAPS Int2ByteSortedMaps
#define PRIORITY_QUEUES IntPriorityQueues
#define HEAPS IntHeaps
#define SEMI_INDIRECT_HEAPS IntSemiIndirectHeaps
#define INDIRECT_HEAPS IntIndirectHeaps
#define ARRAYS IntArrays
#define BIG_ARRAYS IntBigArrays
#define ITERATORS IntIterators
#define BIG_LIST_ITERATORS IntBigListIterators
#define COMPARATORS IntComparators
/* Static containers (values) */
#define VALUE_COLLECTIONS ByteCollections
#define VALUE_SETS ByteSets
#define VALUE_ARRAYS ByteArrays
/* Implementations */
#define OPEN_HASH_SET IntOpenHashSet
#define OPEN_HASH_BIG_SET IntOpenHashBigSet
#define OPEN_DOUBLE_HASH_SET IntOpenDoubleHashSet
#define OPEN_HASH_MAP Int2ByteOpenHashMap
#define STRIPED_OPEN_HASH_MAP StripedInt2ByteOpenHashMap
#define OPEN_DOUBLE_HASH_MAP Int2ByteOpenDoubleHashMap
#define ARRAY_SET IntArraySet
#define ARRAY_MAP Int2ByteArrayMap
#define LINKED_OPEN_HASH_SET IntLinkedOpenHashSet
#define AVL_TREE_SET IntAVLTreeSet
#define RB_TREE_SET IntRBTreeSet
#define AVL_TREE_MAP Int2ByteAVLTreeMap
#define RB_TREE_MAP Int2ByteRBTreeMap
#define ARRAY_LIST IntArrayList
#define BIG_ARRAY_BIG_LIST IntBigArrayBigList
#define ARRAY_FRONT_CODED_LIST IntArrayFrontCodedList
#define HEAP_PRIORITY_QUEUE IntHeapPriorityQueue
#define HEAP_SEMI_INDIRECT_PRIORITY_QUEUE IntHeapSemiIndirectPriorityQueue
#define HEAP_INDIRECT_PRIORITY_QUEUE IntHeapIndirectPriorityQueue
#define HEAP_SESQUI_INDIRECT_DOUBLE_PRIORITY_QUEUE IntHeapSesquiIndirectDoublePriorityQueue
#define HEAP_INDIRECT_DOUBLE_PRIORITY_QUEUE IntHeapIndirectDoublePriorityQueue
#define ARRAY_FIFO_QUEUE IntArrayFIFOQueue
#define ARRAY_PRIORITY_QUEUE IntArrayPriorityQueue
#define ARRAY_INDIRECT_PRIORITY_QUEUE IntArrayIndirectPriorityQueue
#define ARRAY_INDIRECT_DOUBLE_PRIORITY_QUEUE IntArrayIndirectDoublePriorityQueue
/* Synchronized wrappers */
#define SYNCHRONIZED_COLLECTION SynchronizedIntCollection
#define SYNCHRONIZED_SET SynchronizedIntSet
#define SYNCHRONIZED_SORTED_SET SynchronizedIntSortedSet
#define SYNCHRONIZED_FUNCTION SynchronizedInt2ByteFunction
#define SYNCHRONIZED_MAP SynchronizedInt2ByteMap
#define SYNCHRONIZED_LIST SynchronizedIntList
/* Unmodifiable wrappers */
#define UNMODIFIABLE_COLLECTION UnmodifiableIntCollection
#define UNMODIFIABLE_SET UnmodifiableIntSet
#define UNMODIFIABLE_SORTED_SET UnmodifiableIntSortedSet
#define UNMODIFIABLE_FUNCTION UnmodifiableInt2ByteFunction
#define UNMODIFIABLE_MAP UnmodifiableInt2ByteMap
#define UNMODIFIABLE_LIST UnmodifiableIntList
#define UNMODIFIABLE_KEY_ITERATOR UnmodifiableIntIterator
#define UNMODIFIABLE_KEY_BIDI_ITERATOR UnmodifiableIntBidirectionalIterator
#define UNMODIFIABLE_KEY_LIST_ITERATOR UnmodifiableIntListIterator
/* Other wrappers */
#define KEY_READER_WRAPPER IntReaderWrapper
#define KEY_DATA_INPUT_WRAPPER IntDataInputWrapper
/* Methods (keys) */
#define NEXT_KEY nextInt
#define PREV_KEY previousInt
#define FIRST_KEY firstIntKey
#define LAST_KEY lastIntKey
#define GET_KEY getInt
#define REMOVE_KEY removeInt
#define READ_KEY readInt
#define WRITE_KEY writeInt
#define DEQUEUE dequeueInt
#define DEQUEUE_LAST dequeueLastInt
#define SUBLIST_METHOD intSubList
#define SINGLETON_METHOD intSingleton
#define FIRST firstInt
#define LAST lastInt
#define TOP topInt
#define PEEK peekInt
#define POP popInt
#define KEY_ITERATOR_METHOD intIterator
#define KEY_LIST_ITERATOR_METHOD intListIterator
#define KEY_EMPTY_ITERATOR_METHOD emptyIntIterator
#define AS_KEY_ITERATOR asIntIterator
#define TO_KEY_ARRAY toIntArray
#define ENTRY_GET_KEY getIntKey
#define REMOVE_FIRST_KEY removeFirstInt
#define REMOVE_LAST_KEY removeLastInt
#define PARSE_KEY parseInt
#define LOAD_KEYS loadInts
#define LOAD_KEYS_BIG loadIntsBig
#define STORE_KEYS storeInts
/* Methods (values) */
#define NEXT_VALUE nextByte
#define PREV_VALUE previousByte
#define READ_VALUE readByte
#define WRITE_VALUE writeByte
#define VALUE_ITERATOR_METHOD byteIterator
#define ENTRY_GET_VALUE getByteValue
#define REMOVE_FIRST_VALUE removeFirstByte
#define REMOVE_LAST_VALUE removeLastByte
/* Methods (keys/values) */
#define ENTRYSET int2ByteEntrySet
/* Methods that have special names depending on keys (but the special names depend on values) */
#if #keyclass(Object) || #keyclass(Reference)
#define GET_VALUE getByte
#define REMOVE_VALUE removeByte
#else
#define GET_VALUE get
#define REMOVE_VALUE remove
#endif
/* Equality */
#ifdef Custom
#define KEY_EQUALS(x,y) ( strategy.equals( (x), KEY_GENERIC_CAST (y) ) )
#else
#if #keyclass(Object)
#define KEY_EQUALS(x,y) ( (x) == null ? (y) == null : (x).equals(y) )
#define KEY_EQUALS_NOT_NULL(x,y) ( (x).equals(y) )
#else
#define KEY_EQUALS(x,y) ( (x) == (y) )
#define KEY_EQUALS_NOT_NULL(x,y) ( (x) == (y) )
#endif
#endif
#if #valueclass(Object)
#define VALUE_EQUALS(x,y) ( (x) == null ? (y) == null : (x).equals(y) )
#else
#define VALUE_EQUALS(x,y) ( (x) == (y) )
#endif
/* Object/Reference-only definitions (keys) */
#if #keyclass(Object) || #keyclass(Reference)
#define REMOVE remove
#define KEY_OBJ2TYPE(x) (x)
#define KEY_CLASS2TYPE(x) (x)
#define KEY2OBJ(x) (x)
#if #keyclass(Object)
#ifdef Custom
#define KEY2JAVAHASH(x) ( strategy.hashCode( KEY_GENERIC_CAST (x)) )
#define KEY2INTHASH(x) ( it.unimi.dsi.fastutil.HashCommon.murmurHash3( strategy.hashCode( KEY_GENERIC_CAST (x)) ) )
#define KEY2LONGHASH(x) ( it.unimi.dsi.fastutil.HashCommon.murmurHash3( (long)strategy.hashCode( KEY_GENERIC_CAST (x)) ) )
#else
#define KEY2JAVAHASH(x) ( (x) == null ? 0 : (x).hashCode() )
#define KEY2INTHASH(x) ( (x) == null ? 0x87fcd5c : it.unimi.dsi.fastutil.HashCommon.murmurHash3( (x).hashCode() ) )
#define KEY2LONGHASH(x) ( (x) == null ? 0x810879608e4259ccL : it.unimi.dsi.fastutil.HashCommon.murmurHash3( (long)(x).hashCode() ) )
#endif
#else
#define KEY2JAVAHASH(x) ( (x) == null ? 0 : System.identityHashCode(x) )
#define KEY2INTHASH(x) ( (x) == null ? 0x87fcd5c : it.unimi.dsi.fastutil.HashCommon.murmurHash3( System.identityHashCode(x) ) )
#define KEY2LONGHASH(x) ( (x) == null ? 0x810879608e4259ccL : it.unimi.dsi.fastutil.HashCommon.murmurHash3( (long)System.identityHashCode(x) ) )
#endif
#define KEY_CMP(x,y) ( ((Comparable<KEY_GENERIC_CLASS>)(x)).compareTo(y) )
#define KEY_CMP_EQ(x,y) ( ((Comparable<KEY_GENERIC_CLASS>)(x)).compareTo(y) == 0 )
#define KEY_LESS(x,y) ( ((Comparable<KEY_GENERIC_CLASS>)(x)).compareTo(y) < 0 )
#define KEY_LESSEQ(x,y) ( ((Comparable<KEY_GENERIC_CLASS>)(x)).compareTo(y) <= 0 )
#define KEY_NULL (null)
#else
/* Primitive-type-only definitions (keys) */
#define REMOVE rem
#define KEY_CLASS2TYPE(x) ((x).KEY_VALUE())
#define KEY_OBJ2TYPE(x) (KEY_CLASS2TYPE((KEY_CLASS)(x)))
#define KEY2OBJ(x) (KEY_CLASS.valueOf(x))
#if #keyclass(Boolean)
#define KEY_CMP_EQ(x,y) ( (x) == (y) )
#define KEY_NULL (false)
#define KEY_CMP(x,y) ( !(x) && (y) ? -1 : ( (x) == (y) ? 0 : 1 ) )
#define KEY_LESS(x,y) ( !(x) && (y) )
#define KEY_LESSEQ(x,y) ( !(x) || (y) )
#else
#define KEY_NULL ((KEY_TYPE)0)
#if #keyclass(Float) || #keyclass(Double)
#define KEY_CMP_EQ(x,y) ( KEY_CLASS.compare((x),(y)) == 0 )
#define KEY_CMP(x,y) ( KEY_CLASS.compare((x),(y)) )
#define KEY_LESS(x,y) ( KEY_CLASS.compare((x),(y)) < 0 )
#define KEY_LESSEQ(x,y) ( KEY_CLASS.compare((x),(y)) <= 0 )
#else
#define KEY_CMP_EQ(x,y) ( (x) == (y) )
#define KEY_CMP(x,y) ( (x) < (y) ? -1 : ( (x) == (y) ? 0 : 1 ) )
#define KEY_LESS(x,y) ( (x) < (y) )
#define KEY_LESSEQ(x,y) ( (x) <= (y) )
#endif
#if #keyclass(Float)
#define KEY2LEXINT(x) fixFloat(x)
#elif #keyclass(Double)
#define KEY2LEXINT(x) fixDouble(x)
#else
#define KEY2LEXINT(x) (x)
#endif
#endif
#ifdef Custom
#define KEY2JAVAHASH(x) ( strategy.hashCode(x) )
#define KEY2INTHASH(x) ( it.unimi.dsi.fastutil.HashCommon.murmurHash3( strategy.hashCode(x) ) )
#define KEY2LONGHASH(x) ( it.unimi.dsi.fastutil.HashCommon.murmurHash3( (long)strategy.hashCode(x) ) )
#else
#if #keyclass(Float)
#define KEY2JAVAHASH(x) it.unimi.dsi.fastutil.HashCommon.float2int(x)
#define KEY2INTHASH(x) it.unimi.dsi.fastutil.HashCommon.murmurHash3( it.unimi.dsi.fastutil.HashCommon.float2int(x) )
#define KEY2LONGHASH(x) it.unimi.dsi.fastutil.HashCommon.murmurHash3( (long)it.unimi.dsi.fastutil.HashCommon.float2int(x) )
#elif #keyclass(Double)
#define KEY2JAVAHASH(x) it.unimi.dsi.fastutil.HashCommon.double2int(x)
#define KEY2INTHASH(x) (int)it.unimi.dsi.fastutil.HashCommon.murmurHash3(Double.doubleToRawLongBits(x))
#define KEY2LONGHASH(x) it.unimi.dsi.fastutil.HashCommon.murmurHash3(Double.doubleToRawLongBits(x))
#elif #keyclass(Long)
#define KEY2JAVAHASH(x) it.unimi.dsi.fastutil.HashCommon.long2int(x)
#define KEY2INTHASH(x) (int)it.unimi.dsi.fastutil.HashCommon.murmurHash3(x)
#define KEY2LONGHASH(x) it.unimi.dsi.fastutil.HashCommon.murmurHash3(x)
#elif #keyclass(Boolean)
#define KEY2JAVAHASH(x) ((x) ? 1231 : 1237)
#define KEY2INTHASH(x) ((x) ? 0xfab5368 : 0xcba05e7b)
#define KEY2LONGHASH(x) ((x) ? 0x74a19fc8b6428188L : 0xbaeca2031a4fd9ecL)
#else
#define KEY2JAVAHASH(x) (x)
#define KEY2INTHASH(x) ( it.unimi.dsi.fastutil.HashCommon.murmurHash3( (x) ) )
#define KEY2LONGHASH(x) ( it.unimi.dsi.fastutil.HashCommon.murmurHash3( (long)(x) ) )
#endif
#endif
#endif
/* Object/Reference-only definitions (values) */
#if #valueclass(Object) || #valueclass(Reference)
#define VALUE_OBJ2TYPE(x) (x)
#define VALUE_CLASS2TYPE(x) (x)
#define VALUE2OBJ(x) (x)
#if #valueclass(Object)
#define VALUE2JAVAHASH(x) ( (x) == null ? 0 : (x).hashCode() )
#else
#define VALUE2JAVAHASH(x) ( (x) == null ? 0 : System.identityHashCode(x) )
#endif
#define VALUE_NULL (null)
#define OBJECT_DEFAULT_RETURN_VALUE (this.defRetValue)
#else
/* Primitive-type-only definitions (values) */
#define VALUE_CLASS2TYPE(x) ((x).VALUE_VALUE())
#define VALUE_OBJ2TYPE(x) (VALUE_CLASS2TYPE((VALUE_CLASS)(x)))
#define VALUE2OBJ(x) (VALUE_CLASS.valueOf(x))
#if #valueclass(Float) || #valueclass(Double) || #valueclass(Long)
#define VALUE_NULL (0)
#define VALUE2JAVAHASH(x) it.unimi.dsi.fastutil.HashCommon.byte2int(x)
#elif #valueclass(Boolean)
#define VALUE_NULL (false)
#define VALUE2JAVAHASH(x) (x ? 1231 : 1237)
#else
#if #valueclass(Integer)
#define VALUE_NULL (0)
#else
#define VALUE_NULL ((VALUE_TYPE)0)
#endif
#define VALUE2JAVAHASH(x) (x)
#endif
#define OBJECT_DEFAULT_RETURN_VALUE (null)
#endif
#include "drv/Function.drv"
|
karussell/fastutil
|
src/it/unimi/dsi/fastutil/ints/Int2ByteFunction.c
|
C
|
apache-2.0
| 15,042
|
/*
* Copyright (C) 2017 Renat Sarymsakov.
*
* 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 io.reist.sandbox.weather.model.local;
import com.google.gson.annotations.SerializedName;
/**
* Created on 25.07.16.
*
* @author Timofey Plotnikov <timofey.plot@gmail.com>
*/
public class WeatherEntity {
@SerializedName("location")
private LocationData location;
@SerializedName("current")
private WeatherData weatherData;
public void setLocation(LocationData location) {
this.location = location;
}
public void setWeatherData(WeatherData weatherData) {
this.weatherData = weatherData;
}
public String getAddress() {
return String.format("%s, %s, %s", location.country, location.region, location.name);
}
public double getTemperature() {
return weatherData.tempC;
}
public double getPressure() {
return weatherData.pressure;
}
public class LocationData {
@SerializedName("name")
private String name;
@SerializedName("region")
private String region;
@SerializedName("country")
private String country;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRegion() {
return region;
}
public void setRegion(String region) {
this.region = region;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
}
public class WeatherData {
@SerializedName("temp_c")
private double tempC;
@SerializedName("pressure_mb")
private double pressure;
public double getTempC() {
return tempC;
}
public void setTempC(double tempC) {
this.tempC = tempC;
}
public double getPressure() {
return pressure;
}
public void setPressure(double pressure) {
this.pressure = pressure;
}
}
}
|
ragnor-rs/visum
|
demo/src/main/java/io/reist/sandbox/weather/model/local/WeatherEntity.java
|
Java
|
apache-2.0
| 2,691
|
# Amphilothaceae FAMILY
#### Status
ACCEPTED
#### According to
Integrated Taxonomic Information System
#### Published in
null
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Protozoa/Dinophyta/Dinophyceae/Peridiniales/Amphilothaceae/README.md
|
Markdown
|
apache-2.0
| 171
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_07) on Fri Dec 19 15:11:14 CET 2008 -->
<TITLE>
Uses of Interface gameframework.game.Game
</TITLE>
<META NAME="date" CONTENT="2008-12-19">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Interface gameframework.game.Game";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../gameframework/game/Game.html" title="interface in gameframework.game"><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-files/index-1.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?gameframework/game//class-useGame.html" target="_top"><B>FRAMES</B></A>
<A HREF="Game.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>gameframework.game.Game</B></H2>
</CENTER>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Packages that use <A HREF="../../../gameframework/game/Game.html" title="interface in gameframework.game">Game</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#gameframework.game"><B>gameframework.game</B></A></TD>
<TD> </TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#pacman"><B>pacman</B></A></TD>
<TD> </TD>
</TR>
</TABLE>
<P>
<A NAME="gameframework.game"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Uses of <A HREF="../../../gameframework/game/Game.html" title="interface in gameframework.game">Game</A> in <A HREF="../../../gameframework/game/package-summary.html">gameframework.game</A></FONT></TH>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Classes in <A HREF="../../../gameframework/game/package-summary.html">gameframework.game</A> that implement <A HREF="../../../gameframework/game/Game.html" title="interface in gameframework.game">Game</A></FONT></TH>
</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="../../../gameframework/game/GameDefaultImpl.html" title="class in gameframework.game">GameDefaultImpl</A></B></CODE>
<BR>
Create a basic game application with menus and displays of lives and score</TD>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Constructors in <A HREF="../../../gameframework/game/package-summary.html">gameframework.game</A> with parameters of type <A HREF="../../../gameframework/game/Game.html" title="interface in gameframework.game">Game</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><B><A HREF="../../../gameframework/game/GameLevelDefaultImpl.html#GameLevelDefaultImpl(gameframework.game.Game)">GameLevelDefaultImpl</A></B>(<A HREF="../../../gameframework/game/Game.html" title="interface in gameframework.game">Game</A> g)</CODE>
<BR>
</TD>
</TR>
</TABLE>
<P>
<A NAME="pacman"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Uses of <A HREF="../../../gameframework/game/Game.html" title="interface in gameframework.game">Game</A> in <A HREF="../../../pacman/package-summary.html">pacman</A></FONT></TH>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Constructors in <A HREF="../../../pacman/package-summary.html">pacman</A> with parameters of type <A HREF="../../../gameframework/game/Game.html" title="interface in gameframework.game">Game</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><B><A HREF="../../../pacman/PacmanGameLevel.html#PacmanGameLevel(gameframework.game.Game)">PacmanGameLevel</A></B>(<A HREF="../../../gameframework/game/Game.html" title="interface in gameframework.game">Game</A> g)</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=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../gameframework/game/Game.html" title="interface in gameframework.game"><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-files/index-1.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?gameframework/game//class-useGame.html" target="_top"><B>FRAMES</B></A>
<A HREF="Game.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>
|
elyas-bhy/octolink
|
source/doc/gameframework/game/class-use/Game.html
|
HTML
|
apache-2.0
| 9,465
|
<!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 -->
<title>com.centurylink.mdw.adapter (MDW 6 API JavaDocs)</title>
<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="com.centurylink.mdw.adapter (MDW 6 API JavaDocs)";
}
}
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-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../com/centurylink/mdw/activity/types/package-summary.html">Prev Package</a></li>
<li><a href="../../../../com/centurylink/mdw/annotations/package-summary.html">Next Package</a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?com/centurylink/mdw/adapter/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 com.centurylink.mdw.adapter</h1>
</div>
<div class="contentContainer">
<ul class="blockList">
<li class="blockList">
<table class="typeSummary" border="0" cellpadding="3" cellspacing="0" summary="Interface Summary table, listing interfaces, and an explanation">
<caption><span>Interface Summary</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Interface</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="../../../../com/centurylink/mdw/adapter/AdapterInvocationError.html" title="interface in com.centurylink.mdw.adapter">AdapterInvocationError</a></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../com/centurylink/mdw/adapter/HeaderAwareAdapter.html" title="interface in com.centurylink.mdw.adapter">HeaderAwareAdapter</a></td>
<td class="colLast"> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../../com/centurylink/mdw/adapter/TextAdapter.html" title="interface in com.centurylink.mdw.adapter">TextAdapter</a></td>
<td class="colLast">
<div class="block">Interface for text-based adapter activities.</div>
</td>
</tr>
</tbody>
</table>
</li>
<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="../../../../com/centurylink/mdw/adapter/AdapterStubRequest.html" title="class in com.centurylink.mdw.adapter">AdapterStubRequest</a></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../com/centurylink/mdw/adapter/AdapterStubResponse.html" title="class in com.centurylink.mdw.adapter">AdapterStubResponse</a></td>
<td class="colLast"> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../../com/centurylink/mdw/adapter/SimulationResponse.html" title="class in com.centurylink.mdw.adapter">SimulationResponse</a></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<table class="typeSummary" border="0" cellpadding="3" cellspacing="0" summary="Exception Summary table, listing exceptions, and an explanation">
<caption><span>Exception Summary</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Exception</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="../../../../com/centurylink/mdw/adapter/AdapterException.html" title="class in com.centurylink.mdw.adapter">AdapterException</a></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../com/centurylink/mdw/adapter/ConnectionException.html" title="class in com.centurylink.mdw.adapter">ConnectionException</a></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-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../com/centurylink/mdw/activity/types/package-summary.html">Prev Package</a></li>
<li><a href="../../../../com/centurylink/mdw/annotations/package-summary.html">Next Package</a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?com/centurylink/mdw/adapter/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 ======= -->
<p class="legalCopy"><small><i>Copyright © 2019 CenturyLink, Inc.</i></small></p>
</body>
</html>
|
CenturyLinkCloud/mdw
|
docs/_docs/javadoc/com/centurylink/mdw/adapter/package-summary.html
|
HTML
|
apache-2.0
| 7,337
|
# junior
Начальный проект для курса Junior
http://job4j.ru
|
MrBlackBear/ashalobasov
|
README.md
|
Markdown
|
apache-2.0
| 83
|
package org.intellij.ibatis.dom.configuration;
import com.intellij.javaee.model.xml.CommonDomModelElement;
import com.intellij.psi.PsiFile;
import com.intellij.util.xml.Convert;
import com.intellij.util.xml.GenericAttributeValue;
import org.intellij.ibatis.dom.converters.SqlMapFileConverter;
import org.jetbrains.annotations.NotNull;
/**
* properties element in iBATIS configuration xml file
*/
public interface SqlMap extends CommonDomModelElement {
@Convert(SqlMapFileConverter.class) @NotNull
public GenericAttributeValue<PsiFile> getResource();
}
|
code4craft/ibatis-plugin
|
src/org/intellij/ibatis/dom/configuration/SqlMap.java
|
Java
|
apache-2.0
| 582
|
package nyla.solutions.core.patterns.creational.generator;
import nyla.solutions.core.patterns.expression.IsEmailExpression;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertTrue;
class EmailCreatorTest
{
@Test
public void test_create()
{
EmailCreator subject = new EmailCreator();
String actual;
IsEmailExpression isEmail = new IsEmailExpression();
for (int i = 0; i < 10; i++)
{
actual = subject.create();
System.out.println(actual);
assertTrue(isEmail.apply(actual));
}
}
}
|
nyla-solutions/nyla
|
src/test/java/nyla/solutions/core/patterns/creational/generator/EmailCreatorTest.java
|
Java
|
apache-2.0
| 625
|
/**
* Copyright 2012 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @author benvanik@google.com (Ben Vanik)
*/
goog.provide('blk.sim.Inventory');
goog.require('blk.sim');
goog.require('blk.sim.EntityType');
goog.require('blk.sim.commands.SetHeldToolCommand');
goog.require('gf');
goog.require('gf.sim');
goog.require('gf.sim.Entity');
goog.require('goog.events.KeyCodes');
goog.require('goog.math');
/**
* Abstract actor controller entity.
* Can be parented to an actor and assigned as a controller.
*
* @constructor
* @extends {gf.sim.Entity}
* @param {!gf.sim.Simulator} simulator Owning simulator.
* @param {!gf.sim.EntityFactory} entityFactory Entity factory.
* @param {number} entityId Entity ID.
* @param {number} entityFlags Bitmask of {@see gf.sim.EntityFlag} values.
*/
blk.sim.Inventory = function(
simulator, entityFactory, entityId, entityFlags) {
goog.base(this, simulator, entityFactory, entityId, entityFlags);
if (goog.DEBUG) {
this.debugName = 'Inventory';
}
};
goog.inherits(blk.sim.Inventory, gf.sim.Entity);
/**
* Entity ID.
* @const
* @type {number}
*/
blk.sim.Inventory.ID = gf.sim.createTypeId(
blk.sim.BLK_MODULE_ID, blk.sim.EntityType.INVENTORY);
/**
* Gets the target actor of the controller, if any.
* @return {blk.sim.Actor} Target actor.
*/
blk.sim.Inventory.prototype.getTarget = function() {
return /** @type {blk.sim.Actor} */ (this.getParent());
};
/**
* @override
*/
blk.sim.Inventory.prototype.childAdded = function(entity) {
goog.base(this, 'childAdded', entity);
// Item was added to the inventory
};
/**
* @override
*/
blk.sim.Inventory.prototype.childRemoved = function(entity) {
goog.base(this, 'childRemoved', entity);
// Item was removed from the inventory
};
/**
* @override
*/
blk.sim.Inventory.prototype.executeCommand = function(command) {
goog.base(this, 'executeCommand', command);
if (command instanceof blk.sim.commands.SetHeldToolCommand) {
var target = this.getTarget();
var newTool = this.getChild(command.toolId);
if (newTool) {
target.setHeldTool(newTool);
}
}
};
if (gf.CLIENT) {
/**
* Processes the input control for a single frame.
* @param {!gf.RenderFrame} frame Current frame.
* @param {!gf.input.Data} inputData Current input data.
* @return {boolean} True if input is valid, false if input has failed.
*/
blk.sim.Inventory.prototype.processInput = function(frame, inputData) {
var keyboardData = inputData.keyboard;
var mouseData = inputData.mouse;
var target = this.getTarget();
var heldTool = target.getHeldTool();
var count = this.getChildCount();
var oldHeldIndex = heldTool ? this.getIndexOfChild(heldTool) : 0;
var newHeldIndex = oldHeldIndex;
if (mouseData.dz) {
// TODO(benvanik): mac touchpad scroll
var dz = mouseData.dz > 0 ? 1 : -1;
newHeldIndex = (oldHeldIndex + dz) % count;
if (newHeldIndex < 0) {
newHeldIndex = count - 1;
}
}
if (keyboardData.didKeyGoDown(goog.events.KeyCodes.ONE)) {
newHeldIndex = 0;
} else if (keyboardData.didKeyGoDown(goog.events.KeyCodes.TWO)) {
newHeldIndex = 1;
} else if (keyboardData.didKeyGoDown(goog.events.KeyCodes.THREE)) {
newHeldIndex = 2;
} else if (keyboardData.didKeyGoDown(goog.events.KeyCodes.FOUR)) {
newHeldIndex = 3;
} else if (keyboardData.didKeyGoDown(goog.events.KeyCodes.FIVE)) {
newHeldIndex = 4;
} else if (keyboardData.didKeyGoDown(goog.events.KeyCodes.SIX)) {
newHeldIndex = 5;
} else if (keyboardData.didKeyGoDown(goog.events.KeyCodes.SEVEN)) {
newHeldIndex = 6;
} else if (keyboardData.didKeyGoDown(goog.events.KeyCodes.EIGHT)) {
newHeldIndex = 7;
} else if (keyboardData.didKeyGoDown(goog.events.KeyCodes.NINE)) {
newHeldIndex = 8;
} else if (keyboardData.didKeyGoDown(goog.events.KeyCodes.ZERO)) {
newHeldIndex = 9;
}
newHeldIndex = goog.math.clamp(newHeldIndex, 0, count - 1);
if (newHeldIndex != oldHeldIndex) {
// Create command
var cmd = /** @type {!blk.sim.commands.SetHeldToolCommand} */ (
this.createCommand(blk.sim.commands.SetHeldToolCommand.ID));
var newTool = this.getChildAtIndex(newHeldIndex);
cmd.toolId = newTool.getId();
this.simulator.sendCommand(cmd);
if (gf.CLIENT) {
var controller = blk.sim.getClientController(this);
controller.playClick();
}
}
return true;
};
}
|
gamebytes/blk-game
|
src/blk/sim/inventory.js
|
JavaScript
|
apache-2.0
| 5,067
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<HTML>
<HEAD>
<META HTTP-EQUIV="Content-Type" Content="text/html; charset=Windows-1252">
<TITLE>Automatic analysis of twofish encryption algorithm</TITLE>
<link rel="stylesheet" type="text/css" href="CrypTool_Help.css">
</HEAD>
<!-- multiple keywords for CrypTool HTML help index -->
<OBJECT TYPE="application/x-oleobject" CLASSID="clsid:1e2a7bd0-dab9-11d0-b93a-00c04fc99f9e">
<PARAM NAME="Keyword" VALUE="Analysis">
<PARAM NAME="Keyword" VALUE="Twofish encryption algorithm">
</OBJECT>
<BODY>
<h3>Twofish (Menu <A href="menu_analyze.html">Analyze</A> \ Symmetric Encryption (modern) \ Further Algorithms)</h3>
<P>A <!--ZZZPOPUP--><A href="bruteforce.html">brute-force attack</A> is available for <A href="hid_crypt_aes_twofish.html">encryption with the Twofish encryption algorithm</A>.</P>
<P>The key space to be searched through is entered in the <A href="hidd_bruteforce.html">brute-force</A> dialog. After the <!--ZZZPOPUP--><A href="dokument.html">document</A> has been <!--ZZZPOPUP--><A href="entschluesselung.html">decrypted</A> with all the possible <!--ZZZPOPUP--><A href="schluessel.html">keys</A>, the <!--ZZZPOPUP--><A href="klartext.html">plaintext</A> version of the document is assumed to be that which has the smallest <!--ZZZPOPUP--><A href="entropie.html">entropy</A> in the first thousand characters.</P>
<P>In the <A href="hid_hilfe_szenarien.html">examples</A> chapter there is an <A href="szenarien_tripledescbc.html">example</A> of an <A href="angriffe.html">attack</A> on the <A href="hid_crypt_3des_cbc.html">triple-DES encryption algorithm in CBC mode</A>. This example can be worked through for each of the symmetric <!--ZZZPOPUP--><A href="verschluesselung.html">encryption algorithms</A>; however, the <!--ZZZPOPUP--><A href="verschluesselung.html">encrypted</A> documents are always different.</P>
<P>Conditions which the document must satisfy for a successful attack: see <a href="bruteforce.html">brute-force attack</a>.</P>
</BODY>
</HTML>
|
flomar/CrypTool-VS2015
|
trunk/CrypTool/hlp_en/hid_analyse_aes_twofish.html
|
HTML
|
apache-2.0
| 2,039
|
package io.github.ketao1989.rpc;
import scala.tools.cmd.gen.AnyVals;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
* @author: tao.ke Date: 2016/12/5 Time: 下午9:06
* @version: \$Id$
*/
public class ServiceProcessor {
public static final ServiceProcessor processor = new ServiceProcessor();
private static final ConcurrentMap<String, Object> PROCESSOR_INSTANCE_MAP = new ConcurrentHashMap<String, Object>();
public boolean publish(Class clazz, Object obj) {
return PROCESSOR_INSTANCE_MAP.putIfAbsent(clazz.getName(), obj) != null;
}
public Object process(ServiceProtocol.ProtocolModel model) {
try {
Class clazz = Class.forName(model.getClazz());
Class[] types = new Class[model.getArgTypes().length];
for (int i = 0; i < types.length; i++) {
types[i] = Class.forName(model.getArgTypes()[i]);
}
Method method = clazz.getMethod(model.getMethod(), types);
Object obj = PROCESSOR_INSTANCE_MAP.get(model.getClazz());
if (obj == null) {
return null;
}
return method.invoke(obj, model.getArgs());
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
|
ketao1989/tools
|
src/main/java/io/github/ketao1989/rpc/ServiceProcessor.java
|
Java
|
apache-2.0
| 1,394
|
# Univiscidiatus elegans (Rchb.f.) Szlach. 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/Acianthus/Acianthus elegans/ Syn. Univiscidiatus elegans/README.md
|
Markdown
|
apache-2.0
| 197
|
/**
* @author Oleg Cherednik
* @since 11.12.2017
*/
public class Solution {
static class Node {
int val; //Value
int ht; //Height
Node left; //Left child
Node right; //Right child
}
private static Node createNode(int val) {
Node node = new Node();
node.val = val;
return node;
}
private static int height(Node node) {
return node != null ? node.ht : -1;
}
private static int balanceFactor(Node node) {
return node != null ? height(node.right) - height(node.left) : 0;
}
private static void fixHeight(Node node) {
if (node != null)
node.ht = Math.max(height(node.left), height(node.right)) + 1;
}
private static Node rotateRight(Node node) {
Node root = node.left;
node.left = root.right;
root.right = node;
fixHeight(node);
fixHeight(root);
return root;
}
private static Node rotateLeft(Node node) {
Node root = node.right;
node.right = root.left;
root.left = node;
fixHeight(node);
fixHeight(root);
return root;
}
private static Node balance(Node node) {
fixHeight(node);
if (balanceFactor(node) == 2) {
if (balanceFactor(node.right) < 0)
node.right = rotateRight(node.right);
return rotateLeft(node);
}
if (balanceFactor(node) == -2) {
if (balanceFactor(node.left) > 0)
node.left = rotateLeft(node.left);
return rotateRight(node);
}
return node;
}
static Node insert(Node root, int val) {
if (root == null)
return createNode(val);
if (val < root.val)
root.left = insert(root.left, val);
else
root.right = insert(root.right, val);
return balance(root);
}
}
|
oleg-cherednik/hackerrank
|
Data Structures/Balanced Trees/Self Balancing Tree/Solution.java
|
Java
|
apache-2.0
| 1,944
|
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<link rel="SHORTCUT ICON" href="../../../../../img/clover.ico" />
<link rel="stylesheet" href="../../../../../aui/css/aui.min.css" media="all"/>
<link rel="stylesheet" href="../../../../../aui/css/aui-experimental.min.css" media="all"/>
<!--[if IE 9]><link rel="stylesheet" href="../../../../../aui/css/aui-ie9.min.css" media="all"/><![endif]-->
<style type="text/css" media="all">
@import url('../../../../../style.css');
@import url('../../../../../tree.css');
</style>
<script src="../../../../../jquery-1.8.3.min.js" type="text/javascript"></script>
<script src="../../../../../aui/js/aui.min.js" type="text/javascript"></script>
<script src="../../../../../aui/js/aui-experimental.min.js" type="text/javascript"></script>
<script src="../../../../../aui/js/aui-soy.min.js" type="text/javascript"></script>
<script src="../../../../../package-nodes-tree.js" type="text/javascript"></script>
<script src="../../../../../clover-tree.js" type="text/javascript"></script>
<script src="../../../../../clover.js" type="text/javascript"></script>
<script src="../../../../../clover-descriptions.js" type="text/javascript"></script>
<script src="../../../../../cloud.js" type="text/javascript"></script>
<title>ABA Route Transit Number Validator 1.0.1-SNAPSHOT</title>
</head>
<body>
<div id="page">
<header id="header" role="banner">
<nav class="aui-header aui-dropdown2-trigger-group" role="navigation">
<div class="aui-header-inner">
<div class="aui-header-primary">
<h1 id="logo" class="aui-header-logo aui-header-logo-clover">
<a href="http://openclover.org" title="Visit OpenClover home page"><span class="aui-header-logo-device">OpenClover</span></a>
</h1>
</div>
<div class="aui-header-secondary">
<ul class="aui-nav">
<li id="system-help-menu">
<a class="aui-nav-link" title="Open online documentation" target="_blank"
href="http://openclover.org/documentation">
<span class="aui-icon aui-icon-small aui-iconfont-help"> Help</span>
</a>
</li>
</ul>
</div>
</div>
</nav>
</header>
<div class="aui-page-panel">
<div class="aui-page-panel-inner">
<div class="aui-page-panel-nav aui-page-panel-nav-clover">
<div class="aui-page-header-inner" style="margin-bottom: 20px;">
<div class="aui-page-header-image">
<a href="http://cardatechnologies.com" target="_top">
<div class="aui-avatar aui-avatar-large aui-avatar-project">
<div class="aui-avatar-inner">
<img src="../../../../../img/clover_logo_large.png" alt="Clover icon"/>
</div>
</div>
</a>
</div>
<div class="aui-page-header-main" >
<h1>
<a href="http://cardatechnologies.com" target="_top">
ABA Route Transit Number Validator 1.0.1-SNAPSHOT
</a>
</h1>
</div>
</div>
<nav class="aui-navgroup aui-navgroup-vertical">
<div class="aui-navgroup-inner">
<ul class="aui-nav">
<li class="">
<a href="../../../../../dashboard.html">Project overview</a>
</li>
</ul>
<div class="aui-nav-heading packages-nav-heading">
<strong>Packages</strong>
</div>
<div class="aui-nav project-packages">
<form method="get" action="#" class="aui package-filter-container">
<input type="text" autocomplete="off" class="package-filter text"
placeholder="Type to filter packages..." name="package-filter" id="package-filter"
title="Start typing package name (or part of the name) to search through the tree. Use arrow keys and the Enter key to navigate."/>
</form>
<p class="package-filter-no-results-message hidden">
<small>No results found.</small>
</p>
<div class="packages-tree-wrapper" data-root-relative="../../../../../" data-package-name="com.cardatechnologies.utils.validators.abaroutevalidator">
<div class="packages-tree-container"></div>
<div class="clover-packages-lozenges"></div>
</div>
</div>
</div>
</nav> </div>
<section class="aui-page-panel-content">
<div class="aui-page-panel-content-clover">
<div class="aui-page-header-main"><ol class="aui-nav aui-nav-breadcrumbs">
<li><a href="../../../../../dashboard.html"> Project Clover database Sat Aug 7 2021 12:29:33 MDT</a></li>
<li><a href="test-pkg-summary.html">Package com.cardatechnologies.utils.validators.abaroutevalidator</a></li>
<li><a href="test-Test_AbaRouteValidator_11.html">Class Test_AbaRouteValidator_11</a></li>
</ol></div>
<h1 class="aui-h2-clover">
Test testAbaNumberCheck_23162_bad
</h1>
<table class="aui">
<thead>
<tr>
<th>Test</th>
<th><label title="The test result. Either a Pass, Fail or Error.">Status</label></th>
<th><label title="When the test execution was started">Start time</label></th>
<th><label title="The total time in seconds taken to run this test.">Time (seconds)</label></th>
<th><label title="A failure or error message if the test is not successful.">Message</label></th>
</tr>
</thead>
<tbody>
<tr>
<td>
<a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/Test_AbaRouteValidator_11.html?line=17152#src-17152" >testAbaNumberCheck_23162_bad</a>
</td>
<td>
<span class="sortValue">1</span><span class="aui-lozenge aui-lozenge-success">PASS</span>
</td>
<td>
7 Aug 12:40:30
</td>
<td>
0.0 </td>
<td>
<div></div>
<div class="errorMessage"></div>
</td>
</tr>
</tbody>
</table>
<div> </div>
<table class="aui aui-table-sortable">
<thead>
<tr>
<th style="white-space:nowrap;"><label title="A class that was directly hit by this test.">Target Class</label></th>
<th colspan="4"><label title="The percentage of coverage contributed by each single test.">Coverage contributed by</label> testAbaNumberCheck_23162_bad</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<span class="sortValue">com.cardatechnologies.utils.validators.abaroutevalidator.exceptions.AbaRouteValidationException</span>
  <a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/exceptions/AbaRouteValidationException.html?id=8987#AbaRouteValidationException" title="AbaRouteValidationException" name="sl-43">com.cardatechnologies.utils.validators.abaroutevalidator.exceptions.AbaRouteValidationException</a>
</td>
<td>
<span class="sortValue">0.5714286</span>57.1%
</td>
<td class="align-middle" style="width: 100%" colspan="3">
<div>
<div title="57.1% Covered" style="min-width:40px;" class="barNegative contribBarNegative contribBarNegative"><div class="barPositive contribBarPositive contribBarPositive" style="width:57.1%"></div></div></div> </td>
</tr>
<tr>
<td>
<span class="sortValue">com.cardatechnologies.utils.validators.abaroutevalidator.ErrorCodes</span>
  <a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/ErrorCodes.html?id=8987#ErrorCodes" title="ErrorCodes" name="sl-42">com.cardatechnologies.utils.validators.abaroutevalidator.ErrorCodes</a>
</td>
<td>
<span class="sortValue">0.5714286</span>57.1%
</td>
<td class="align-middle" style="width: 100%" colspan="3">
<div>
<div title="57.1% Covered" style="min-width:40px;" class="barNegative contribBarNegative contribBarNegative"><div class="barPositive contribBarPositive contribBarPositive" style="width:57.1%"></div></div></div> </td>
</tr>
<tr>
<td>
<span class="sortValue">com.cardatechnologies.utils.validators.abaroutevalidator.AbaRouteValidator</span>
  <a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/AbaRouteValidator.html?id=8987#AbaRouteValidator" title="AbaRouteValidator" name="sl-47">com.cardatechnologies.utils.validators.abaroutevalidator.AbaRouteValidator</a>
</td>
<td>
<span class="sortValue">0.29411766</span>29.4%
</td>
<td class="align-middle" style="width: 100%" colspan="3">
<div>
<div title="29.4% Covered" style="min-width:40px;" class="barNegative contribBarNegative contribBarNegative"><div class="barPositive contribBarPositive contribBarPositive" style="width:29.4%"></div></div></div> </td>
</tr>
</tbody>
</table>
</div> <!-- class="aui-page-panel-content-clover" -->
<footer id="footer" role="contentinfo">
<section class="footer-body">
<ul>
<li>
Report generated by <a target="_new" href="http://openclover.org">OpenClover</a> v 4.4.1
on Sat Aug 7 2021 12:49:26 MDT using coverage data from Sat Aug 7 2021 12:47:23 MDT.
</li>
</ul>
<ul>
<li>OpenClover is free and open-source software. </li>
</ul>
</section>
</footer> </section> <!-- class="aui-page-panel-content" -->
</div> <!-- class="aui-page-panel-inner" -->
</div> <!-- class="aui-page-panel" -->
</div> <!-- id="page" -->
</body>
</html>
|
dcarda/aba.route.validator
|
target13/site/clover/com/cardatechnologies/utils/validators/abaroutevalidator/Test_AbaRouteValidator_11_testAbaNumberCheck_23162_bad_6xn.html
|
HTML
|
apache-2.0
| 10,984
|
// ImGui SDL2 binding with OpenGL3
// In this binding, ImTextureID is used to store an OpenGL 'GLuint' texture identifier. Read the FAQ about ImTextureID in imgui.cpp.
// You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this.
// If you use this binding you'll need to call 4 functions: ImGui_ImplXXXX_Init(), ImGui_ImplXXXX_NewFrame(), ImGui::Render() and ImGui_ImplXXXX_Shutdown().
// If you are new to ImGui, see examples/README.txt and documentation at the top of imgui.cpp.
// https://github.com/ocornut/imgui
#include "imgui.h"
#include "imgui_impl_sdl_gl3.h"
// SDL,GL3W
#include <SDL2/SDL.h>
#include <SDL2/SDL_syswm.h>
#include <GL/glew.h>
// Data
static double g_Time = 0.0f;
static bool g_MousePressed[3] = { false, false, false };
static float g_MouseWheel = 0.0f;
static GLuint g_FontTexture = 0;
static int g_ShaderHandle = 0, g_VertHandle = 0, g_FragHandle = 0;
static int g_AttribLocationTex = 0, g_AttribLocationProjMtx = 0;
static int g_AttribLocationPosition = 0, g_AttribLocationUV = 0, g_AttribLocationColor = 0;
static unsigned int g_VboHandle = 0, g_VaoHandle = 0, g_ElementsHandle = 0;
// This is the main rendering function that you have to implement and provide to ImGui (via setting up 'RenderDrawListsFn' in the ImGuiIO structure)
// If text or lines are blurry when integrating ImGui in your engine:
// - in your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f)
void ImGui_ImplSdlGL3_RenderDrawLists(ImDrawData* draw_data)
{
// Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates)
ImGuiIO& io = ImGui::GetIO();
int fb_width = (int)(io.DisplaySize.x * io.DisplayFramebufferScale.x);
int fb_height = (int)(io.DisplaySize.y * io.DisplayFramebufferScale.y);
if (fb_width == 0 || fb_height == 0)
return;
draw_data->ScaleClipRects(io.DisplayFramebufferScale);
// Backup GL state
GLint last_program; glGetIntegerv(GL_CURRENT_PROGRAM, &last_program);
GLint last_texture; glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture);
GLint last_active_texture; glGetIntegerv(GL_ACTIVE_TEXTURE, &last_active_texture);
GLint last_array_buffer; glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &last_array_buffer);
GLint last_element_array_buffer; glGetIntegerv(GL_ELEMENT_ARRAY_BUFFER_BINDING, &last_element_array_buffer);
GLint last_vertex_array; glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &last_vertex_array);
GLint last_blend_src; glGetIntegerv(GL_BLEND_SRC, &last_blend_src);
GLint last_blend_dst; glGetIntegerv(GL_BLEND_DST, &last_blend_dst);
GLint last_blend_equation_rgb; glGetIntegerv(GL_BLEND_EQUATION_RGB, &last_blend_equation_rgb);
GLint last_blend_equation_alpha; glGetIntegerv(GL_BLEND_EQUATION_ALPHA, &last_blend_equation_alpha);
GLint last_viewport[4]; glGetIntegerv(GL_VIEWPORT, last_viewport);
GLint last_scissor_box[4]; glGetIntegerv(GL_SCISSOR_BOX, last_scissor_box);
GLboolean last_enable_blend = glIsEnabled(GL_BLEND);
GLboolean last_enable_cull_face = glIsEnabled(GL_CULL_FACE);
GLboolean last_enable_depth_test = glIsEnabled(GL_DEPTH_TEST);
GLboolean last_enable_scissor_test = glIsEnabled(GL_SCISSOR_TEST);
// Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled
glEnable(GL_BLEND);
glBlendEquation(GL_FUNC_ADD);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glDisable(GL_CULL_FACE);
glDisable(GL_DEPTH_TEST);
glEnable(GL_SCISSOR_TEST);
glActiveTexture(GL_TEXTURE0);
// Setup orthographic projection matrix
glViewport(0, 0, (GLsizei)fb_width, (GLsizei)fb_height);
const float ortho_projection[4][4] =
{
{ 2.0f/io.DisplaySize.x, 0.0f, 0.0f, 0.0f },
{ 0.0f, 2.0f/-io.DisplaySize.y, 0.0f, 0.0f },
{ 0.0f, 0.0f, -1.0f, 0.0f },
{-1.0f, 1.0f, 0.0f, 1.0f },
};
glUseProgram(g_ShaderHandle);
glUniform1i(g_AttribLocationTex, 0);
glUniformMatrix4fv(g_AttribLocationProjMtx, 1, GL_FALSE, &ortho_projection[0][0]);
glBindVertexArray(g_VaoHandle);
for (int n = 0; n < draw_data->CmdListsCount; n++)
{
const ImDrawList* cmd_list = draw_data->CmdLists[n];
const ImDrawIdx* idx_buffer_offset = 0;
glBindBuffer(GL_ARRAY_BUFFER, g_VboHandle);
glBufferData(GL_ARRAY_BUFFER, (GLsizeiptr)cmd_list->VtxBuffer.Size * sizeof(ImDrawVert), (GLvoid*)cmd_list->VtxBuffer.Data, GL_STREAM_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, g_ElementsHandle);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, (GLsizeiptr)cmd_list->IdxBuffer.Size * sizeof(ImDrawIdx), (GLvoid*)cmd_list->IdxBuffer.Data, GL_STREAM_DRAW);
for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
{
const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
if (pcmd->UserCallback)
{
pcmd->UserCallback(cmd_list, pcmd);
}
else
{
glBindTexture(GL_TEXTURE_2D, (GLuint)(intptr_t)pcmd->TextureId);
glScissor((int)pcmd->ClipRect.x, (int)(fb_height - pcmd->ClipRect.w), (int)(pcmd->ClipRect.z - pcmd->ClipRect.x), (int)(pcmd->ClipRect.w - pcmd->ClipRect.y));
glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer_offset);
}
idx_buffer_offset += pcmd->ElemCount;
}
}
// Restore modified GL state
glUseProgram(last_program);
glActiveTexture(last_active_texture);
glBindTexture(GL_TEXTURE_2D, last_texture);
glBindVertexArray(last_vertex_array);
glBindBuffer(GL_ARRAY_BUFFER, last_array_buffer);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, last_element_array_buffer);
glBlendEquationSeparate(last_blend_equation_rgb, last_blend_equation_alpha);
glBlendFunc(last_blend_src, last_blend_dst);
if (last_enable_blend) glEnable(GL_BLEND); else glDisable(GL_BLEND);
if (last_enable_cull_face) glEnable(GL_CULL_FACE); else glDisable(GL_CULL_FACE);
if (last_enable_depth_test) glEnable(GL_DEPTH_TEST); else glDisable(GL_DEPTH_TEST);
if (last_enable_scissor_test) glEnable(GL_SCISSOR_TEST); else glDisable(GL_SCISSOR_TEST);
glViewport(last_viewport[0], last_viewport[1], (GLsizei)last_viewport[2], (GLsizei)last_viewport[3]);
glScissor(last_scissor_box[0], last_scissor_box[1], (GLsizei)last_scissor_box[2], (GLsizei)last_scissor_box[3]);
}
static const char* ImGui_ImplSdlGL3_GetClipboardText(void*)
{
return SDL_GetClipboardText();
}
static void ImGui_ImplSdlGL3_SetClipboardText(void*, const char* text)
{
SDL_SetClipboardText(text);
}
bool ImGui_ImplSdlGL3_ProcessEvent(SDL_Event* event)
{
ImGuiIO& io = ImGui::GetIO();
switch (event->type)
{
case SDL_MOUSEWHEEL:
{
if (event->wheel.y > 0)
g_MouseWheel = 1;
if (event->wheel.y < 0)
g_MouseWheel = -1;
return true;
}
case SDL_MOUSEBUTTONDOWN:
{
if (event->button.button == SDL_BUTTON_LEFT) g_MousePressed[0] = true;
if (event->button.button == SDL_BUTTON_RIGHT) g_MousePressed[1] = true;
if (event->button.button == SDL_BUTTON_MIDDLE) g_MousePressed[2] = true;
return true;
}
case SDL_TEXTINPUT:
{
io.AddInputCharactersUTF8(event->text.text);
return true;
}
case SDL_KEYDOWN:
case SDL_KEYUP:
{
int key = event->key.keysym.sym & ~SDLK_SCANCODE_MASK;
io.KeysDown[key] = (event->type == SDL_KEYDOWN);
io.KeyShift = ((SDL_GetModState() & KMOD_SHIFT) != 0);
io.KeyCtrl = ((SDL_GetModState() & KMOD_CTRL) != 0);
io.KeyAlt = ((SDL_GetModState() & KMOD_ALT) != 0);
io.KeySuper = ((SDL_GetModState() & KMOD_GUI) != 0);
return true;
}
}
return false;
}
void ImGui_ImplSdlGL3_CreateFontsTexture()
{
// Build texture atlas
ImGuiIO& io = ImGui::GetIO();
unsigned char* pixels;
int width, height;
io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); // Load as RGBA 32-bits for OpenGL3 demo because it is more likely to be compatible with user's existing shader.
// Upload texture to graphics system
GLint last_texture;
glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture);
glGenTextures(1, &g_FontTexture);
glBindTexture(GL_TEXTURE_2D, g_FontTexture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
// Store our identifier
io.Fonts->TexID = (void *)(intptr_t)g_FontTexture;
// Restore state
glBindTexture(GL_TEXTURE_2D, last_texture);
}
bool ImGui_ImplSdlGL3_CreateDeviceObjects()
{
// Backup GL state
GLint last_texture, last_array_buffer, last_vertex_array;
glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture);
glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &last_array_buffer);
glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &last_vertex_array);
const GLchar *vertex_shader =
"#version 330\n"
"uniform mat4 ProjMtx;\n"
"in vec2 Position;\n"
"in vec2 UV;\n"
"in vec4 Color;\n"
"out vec2 Frag_UV;\n"
"out vec4 Frag_Color;\n"
"void main()\n"
"{\n"
" Frag_UV = UV;\n"
" Frag_Color = Color;\n"
" gl_Position = ProjMtx * vec4(Position.xy,0,1);\n"
"}\n";
const GLchar* fragment_shader =
"#version 330\n"
"uniform sampler2D Texture;\n"
"in vec2 Frag_UV;\n"
"in vec4 Frag_Color;\n"
"out vec4 Out_Color;\n"
"void main()\n"
"{\n"
" Out_Color = Frag_Color * texture( Texture, Frag_UV.st);\n"
"}\n";
g_ShaderHandle = glCreateProgram();
g_VertHandle = glCreateShader(GL_VERTEX_SHADER);
g_FragHandle = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(g_VertHandle, 1, &vertex_shader, 0);
glShaderSource(g_FragHandle, 1, &fragment_shader, 0);
glCompileShader(g_VertHandle);
glCompileShader(g_FragHandle);
glAttachShader(g_ShaderHandle, g_VertHandle);
glAttachShader(g_ShaderHandle, g_FragHandle);
glLinkProgram(g_ShaderHandle);
g_AttribLocationTex = glGetUniformLocation(g_ShaderHandle, "Texture");
g_AttribLocationProjMtx = glGetUniformLocation(g_ShaderHandle, "ProjMtx");
g_AttribLocationPosition = glGetAttribLocation(g_ShaderHandle, "Position");
g_AttribLocationUV = glGetAttribLocation(g_ShaderHandle, "UV");
g_AttribLocationColor = glGetAttribLocation(g_ShaderHandle, "Color");
glGenBuffers(1, &g_VboHandle);
glGenBuffers(1, &g_ElementsHandle);
glGenVertexArrays(1, &g_VaoHandle);
glBindVertexArray(g_VaoHandle);
glBindBuffer(GL_ARRAY_BUFFER, g_VboHandle);
glEnableVertexAttribArray(g_AttribLocationPosition);
glEnableVertexAttribArray(g_AttribLocationUV);
glEnableVertexAttribArray(g_AttribLocationColor);
#define OFFSETOF(TYPE, ELEMENT) ((size_t)&(((TYPE *)0)->ELEMENT))
glVertexAttribPointer(g_AttribLocationPosition, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)OFFSETOF(ImDrawVert, pos));
glVertexAttribPointer(g_AttribLocationUV, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)OFFSETOF(ImDrawVert, uv));
glVertexAttribPointer(g_AttribLocationColor, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(ImDrawVert), (GLvoid*)OFFSETOF(ImDrawVert, col));
#undef OFFSETOF
ImGui_ImplSdlGL3_CreateFontsTexture();
// Restore modified GL state
glBindTexture(GL_TEXTURE_2D, last_texture);
glBindBuffer(GL_ARRAY_BUFFER, last_array_buffer);
glBindVertexArray(last_vertex_array);
return true;
}
void ImGui_ImplSdlGL3_InvalidateDeviceObjects()
{
if (g_VaoHandle) glDeleteVertexArrays(1, &g_VaoHandle);
if (g_VboHandle) glDeleteBuffers(1, &g_VboHandle);
if (g_ElementsHandle) glDeleteBuffers(1, &g_ElementsHandle);
g_VaoHandle = g_VboHandle = g_ElementsHandle = 0;
if (g_ShaderHandle && g_VertHandle) glDetachShader(g_ShaderHandle, g_VertHandle);
if (g_VertHandle) glDeleteShader(g_VertHandle);
g_VertHandle = 0;
if (g_ShaderHandle && g_FragHandle) glDetachShader(g_ShaderHandle, g_FragHandle);
if (g_FragHandle) glDeleteShader(g_FragHandle);
g_FragHandle = 0;
if (g_ShaderHandle) glDeleteProgram(g_ShaderHandle);
g_ShaderHandle = 0;
if (g_FontTexture)
{
glDeleteTextures(1, &g_FontTexture);
ImGui::GetIO().Fonts->TexID = 0;
g_FontTexture = 0;
}
}
bool ImGui_ImplSdlGL3_Init(SDL_Window* window)
{
ImGuiIO& io = ImGui::GetIO();
io.KeyMap[ImGuiKey_Tab] = SDLK_TAB; // Keyboard mapping. ImGui will use those indices to peek into the io.KeyDown[] array.
io.KeyMap[ImGuiKey_LeftArrow] = SDL_SCANCODE_LEFT;
io.KeyMap[ImGuiKey_RightArrow] = SDL_SCANCODE_RIGHT;
io.KeyMap[ImGuiKey_UpArrow] = SDL_SCANCODE_UP;
io.KeyMap[ImGuiKey_DownArrow] = SDL_SCANCODE_DOWN;
io.KeyMap[ImGuiKey_PageUp] = SDL_SCANCODE_PAGEUP;
io.KeyMap[ImGuiKey_PageDown] = SDL_SCANCODE_PAGEDOWN;
io.KeyMap[ImGuiKey_Home] = SDL_SCANCODE_HOME;
io.KeyMap[ImGuiKey_End] = SDL_SCANCODE_END;
io.KeyMap[ImGuiKey_Delete] = SDLK_DELETE;
io.KeyMap[ImGuiKey_Backspace] = SDLK_BACKSPACE;
io.KeyMap[ImGuiKey_Enter] = SDLK_RETURN;
io.KeyMap[ImGuiKey_Escape] = SDLK_ESCAPE;
io.KeyMap[ImGuiKey_A] = SDLK_a;
io.KeyMap[ImGuiKey_C] = SDLK_c;
io.KeyMap[ImGuiKey_V] = SDLK_v;
io.KeyMap[ImGuiKey_X] = SDLK_x;
io.KeyMap[ImGuiKey_Y] = SDLK_y;
io.KeyMap[ImGuiKey_Z] = SDLK_z;
io.RenderDrawListsFn = ImGui_ImplSdlGL3_RenderDrawLists; // Alternatively you can set this to NULL and call ImGui::GetDrawData() after ImGui::Render() to get the same ImDrawData pointer.
io.SetClipboardTextFn = ImGui_ImplSdlGL3_SetClipboardText;
io.GetClipboardTextFn = ImGui_ImplSdlGL3_GetClipboardText;
io.ClipboardUserData = NULL;
#ifdef _WIN32
SDL_SysWMinfo wmInfo;
SDL_VERSION(&wmInfo.version);
SDL_GetWindowWMInfo(window, &wmInfo);
io.ImeWindowHandle = wmInfo.info.win.window;
#else
(void)window;
#endif
return true;
}
void ImGui_ImplSdlGL3_Shutdown()
{
ImGui_ImplSdlGL3_InvalidateDeviceObjects();
ImGui::Shutdown();
}
void ImGui_ImplSdlGL3_NewFrame(SDL_Window* window)
{
if (!g_FontTexture)
ImGui_ImplSdlGL3_CreateDeviceObjects();
ImGuiIO& io = ImGui::GetIO();
// Setup display size (every frame to accommodate for window resizing)
int w, h;
int display_w, display_h;
SDL_GetWindowSize(window, &w, &h);
SDL_GL_GetDrawableSize(window, &display_w, &display_h);
io.DisplaySize = ImVec2((float)w, (float)h);
io.DisplayFramebufferScale = ImVec2(w > 0 ? ((float)display_w / w) : 0, h > 0 ? ((float)display_h / h) : 0);
// Setup time step
Uint32 time = SDL_GetTicks();
double current_time = time / 1000.0;
io.DeltaTime = g_Time > 0.0 ? (float)(current_time - g_Time) : (float)(1.0f / 60.0f);
g_Time = current_time;
// Setup inputs
// (we already got mouse wheel, keyboard keys & characters from SDL_PollEvent())
int mx, my;
Uint32 mouseMask = SDL_GetMouseState(&mx, &my);
if (SDL_GetWindowFlags(window) & SDL_WINDOW_MOUSE_FOCUS)
io.MousePos = ImVec2((float)mx, (float)my); // Mouse position, in pixels (set to -1,-1 if no mouse / on another screen, etc.)
else
io.MousePos = ImVec2(-1, -1);
io.MouseDown[0] = g_MousePressed[0] || (mouseMask & SDL_BUTTON(SDL_BUTTON_LEFT)) != 0; // If a mouse press event came, always pass it as "mouse held this frame", so we don't miss click-release events that are shorter than 1 frame.
io.MouseDown[1] = g_MousePressed[1] || (mouseMask & SDL_BUTTON(SDL_BUTTON_RIGHT)) != 0;
io.MouseDown[2] = g_MousePressed[2] || (mouseMask & SDL_BUTTON(SDL_BUTTON_MIDDLE)) != 0;
g_MousePressed[0] = g_MousePressed[1] = g_MousePressed[2] = false;
io.MouseWheel = g_MouseWheel;
g_MouseWheel = 0.0f;
// Hide OS mouse cursor if ImGui is drawing it
SDL_ShowCursor(io.MouseDrawCursor ? 0 : 1);
// Start the frame
ImGui::NewFrame();
}
|
texel-sensei/eversim
|
external/imgui/src/imgui_impl_sdl_gl3.cpp
|
C++
|
apache-2.0
| 16,636
|
// ========================================================================
// Copyright (c) 2004-2009 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
package org.eclipse.jetty.servlets;
import java.io.IOException;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.eclipse.jetty.continuation.Continuation;
import org.eclipse.jetty.continuation.ContinuationListener;
import org.eclipse.jetty.continuation.ContinuationSupport;
import org.eclipse.jetty.server.handler.ContextHandler;
/**
* Quality of Service Filter.
*
* This filter limits the number of active requests to the number set by the "maxRequests" init parameter (default 10).
* If more requests are received, they are suspended and placed on priority queues. Priorities are determined by
* the {@link #getPriority(ServletRequest)} method and are a value between 0 and the value given by the "maxPriority"
* init parameter (default 10), with higher values having higher priority.
* </p><p>
* This filter is ideal to prevent wasting threads waiting for slow/limited
* resources such as a JDBC connection pool. It avoids the situation where all of a
* containers thread pool may be consumed blocking on such a slow resource.
* By limiting the number of active threads, a smaller thread pool may be used as
* the threads are not wasted waiting. Thus more memory may be available for use by
* the active threads.
* </p><p>
* Furthermore, this filter uses a priority when resuming waiting requests. So that if
* a container is under load, and there are many requests waiting for resources,
* the {@link #getPriority(ServletRequest)} method is used, so that more important
* requests are serviced first. For example, this filter could be deployed with a
* maxRequest limit slightly smaller than the containers thread pool and a high priority
* allocated to admin users. Thus regardless of load, admin users would always be
* able to access the web application.
* </p><p>
* The maxRequest limit is policed by a {@link Semaphore} and the filter will wait a short while attempting to acquire
* the semaphore. This wait is controlled by the "waitMs" init parameter and allows the expense of a suspend to be
* avoided if the semaphore is shortly available. If the semaphore cannot be obtained, the request will be suspended
* for the default suspend period of the container or the valued set as the "suspendMs" init parameter.
* </p><p>
* If the "managedAttr" init parameter is set to true, then this servlet is set as a {@link ServletContext} attribute with the
* filter name as the attribute name. This allows context external mechanism (eg JMX via {@link ContextHandler#MANAGED_ATTRIBUTES}) to
* manage the configuration of the filter.
* </p>
*
*
*/
public class QoSFilter implements Filter
{
final static int __DEFAULT_MAX_PRIORITY=10;
final static int __DEFAULT_PASSES=10;
final static int __DEFAULT_WAIT_MS=50;
final static long __DEFAULT_TIMEOUT_MS = -1;
final static String MANAGED_ATTR_INIT_PARAM="managedAttr";
final static String MAX_REQUESTS_INIT_PARAM="maxRequests";
final static String MAX_PRIORITY_INIT_PARAM="maxPriority";
final static String MAX_WAIT_INIT_PARAM="waitMs";
final static String SUSPEND_INIT_PARAM="suspendMs";
ServletContext _context;
protected long _waitMs;
protected long _suspendMs;
protected int _maxRequests;
private Semaphore _passes;
private Queue<Continuation>[] _queue;
private ContinuationListener[] _listener;
private String _suspended="QoSFilter@"+this.hashCode();
/* ------------------------------------------------------------ */
/**
* @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
*/
public void init(FilterConfig filterConfig)
{
_context=filterConfig.getServletContext();
int max_priority=__DEFAULT_MAX_PRIORITY;
if (filterConfig.getInitParameter(MAX_PRIORITY_INIT_PARAM)!=null)
max_priority=Integer.parseInt(filterConfig.getInitParameter(MAX_PRIORITY_INIT_PARAM));
_queue=new Queue[max_priority+1];
_listener = new ContinuationListener[max_priority + 1];
for (int p=0;p<_queue.length;p++)
{
_queue[p]=new ConcurrentLinkedQueue<Continuation>();
final int priority=p;
_listener[p] = new ContinuationListener()
{
public void onComplete(Continuation continuation)
{}
public void onTimeout(Continuation continuation)
{
_queue[priority].remove(continuation);
}
};
}
int maxRequests=__DEFAULT_PASSES;
if (filterConfig.getInitParameter(MAX_REQUESTS_INIT_PARAM)!=null)
maxRequests=Integer.parseInt(filterConfig.getInitParameter(MAX_REQUESTS_INIT_PARAM));
_passes=new Semaphore(maxRequests,true);
_maxRequests = maxRequests;
long wait = __DEFAULT_WAIT_MS;
if (filterConfig.getInitParameter(MAX_WAIT_INIT_PARAM)!=null)
wait=Integer.parseInt(filterConfig.getInitParameter(MAX_WAIT_INIT_PARAM));
_waitMs=wait;
long suspend = __DEFAULT_TIMEOUT_MS;
if (filterConfig.getInitParameter(SUSPEND_INIT_PARAM)!=null)
suspend=Integer.parseInt(filterConfig.getInitParameter(SUSPEND_INIT_PARAM));
_suspendMs=suspend;
if (_context!=null && Boolean.parseBoolean(filterConfig.getInitParameter(MANAGED_ATTR_INIT_PARAM)))
_context.setAttribute(filterConfig.getFilterName(),this);
}
/* ------------------------------------------------------------ */
/**
* @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
*/
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException
{
boolean accepted=false;
try
{
if (request.getAttribute(_suspended)==null)
{
accepted=_passes.tryAcquire(_waitMs,TimeUnit.MILLISECONDS);
if (accepted)
{
request.setAttribute(_suspended,Boolean.FALSE);
}
else
{
request.setAttribute(_suspended,Boolean.TRUE);
int priority = getPriority(request);
Continuation continuation = ContinuationSupport.getContinuation(request);
if (_suspendMs>0)
continuation.setTimeout(_suspendMs);
continuation.suspend();
continuation.addContinuationListener(_listener[priority]);
_queue[priority].add(continuation);
return;
}
}
else
{
Boolean suspended=(Boolean)request.getAttribute(_suspended);
if (suspended.booleanValue())
{
request.setAttribute(_suspended,Boolean.FALSE);
if (request.getAttribute("javax.servlet.resumed")==Boolean.TRUE)
{
_passes.acquire();
accepted=true;
}
else
{
// Timeout! try 1 more time.
accepted = _passes.tryAcquire(_waitMs,TimeUnit.MILLISECONDS);
}
}
else
{
// pass through resume of previously accepted request
_passes.acquire();
accepted = true;
}
}
if (accepted)
{
chain.doFilter(request,response);
}
else
{
((HttpServletResponse)response).sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
}
}
catch(InterruptedException e)
{
_context.log("QoS",e);
((HttpServletResponse)response).sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
}
finally
{
if (accepted)
{
for (int p=_queue.length;p-->0;)
{
Continuation continutaion=_queue[p].poll();
if (continutaion!=null && continutaion.isSuspended())
{
continutaion.resume();
break;
}
}
_passes.release();
}
}
}
/**
* Get the request Priority.
* <p> The default implementation assigns the following priorities:<ul>
* <li> 2 - for a authenticated request
* <li> 1 - for a request with valid /non new session
* <li> 0 - for all other requests.
* </ul>
* This method may be specialised to provide application specific priorities.
*
* @param request
* @return the request priority
*/
protected int getPriority(ServletRequest request)
{
HttpServletRequest baseRequest = (HttpServletRequest)request;
if (baseRequest.getUserPrincipal() != null )
return 2;
else
{
HttpSession session = baseRequest.getSession(false);
if (session!=null && !session.isNew())
return 1;
else
return 0;
}
}
/* ------------------------------------------------------------ */
/**
* @see javax.servlet.Filter#destroy()
*/
public void destroy(){}
/* ------------------------------------------------------------ */
/**
* Get the (short) amount of time (in milliseconds) that the filter would wait
* for the semaphore to become available before suspending a request.
*
* @return wait time (in milliseconds)
*/
public long getWaitMs()
{
return _waitMs;
}
/* ------------------------------------------------------------ */
/**
* Set the (short) amount of time (in milliseconds) that the filter would wait
* for the semaphore to become available before suspending a request.
*
* @param value wait time (in milliseconds)
*/
public void setWaitMs(long value)
{
_waitMs = value;
}
/* ------------------------------------------------------------ */
/**
* Get the amount of time (in milliseconds) that the filter would suspend
* a request for while waiting for the semaphore to become available.
*
* @return suspend time (in milliseconds)
*/
public long getSuspendMs()
{
return _suspendMs;
}
/* ------------------------------------------------------------ */
/**
* Set the amount of time (in milliseconds) that the filter would suspend
* a request for while waiting for the semaphore to become available.
*
* @param value suspend time (in milliseconds)
*/
public void setSuspendMs(long value)
{
_suspendMs = value;
}
/* ------------------------------------------------------------ */
/**
* Get the maximum number of requests allowed to be processed
* at the same time.
*
* @return maximum number of requests
*/
public int getMaxRequests()
{
return _maxRequests;
}
/* ------------------------------------------------------------ */
/**
* Set the maximum number of requests allowed to be processed
* at the same time.
*
* @param value the number of requests
*/
public void setMaxRequests(int value)
{
_passes = new Semaphore((value-_maxRequests+_passes.availablePermits()), true);
_maxRequests = value;
}
}
|
wang88/jetty
|
jetty-servlets/src/main/java/org/eclipse/jetty/servlets/QoSFilter.java
|
Java
|
apache-2.0
| 13,432
|
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Threading.Tasks;
using Ku.Core.CMS.Domain.Dto.DataCenter;
using Ku.Core.CMS.Domain.Entity.DataCenter;
using Ku.Core.CMS.IService.DataCenter;
using Ku.Core.CMS.Web.Base;
using Ku.Core.CMS.Web.Security;
namespace Ku.Core.CMS.Web.Backend.Pages.DataCenter.App
{
/// <summary>
/// 应用 列表页面
/// </summary>
[Auth("datacenter.app")]
[IgnoreAntiforgeryToken(Order = 1001)]
public class IndexModel : BasePage
{
private readonly IAppService _service;
public IndexModel(IAppService service)
{
this._service = service;
}
[Auth("view")]
public void OnGet()
{
}
/// <summary>
/// 取得列表数据
/// </summary>
[Auth("view")]
public async Task<IActionResult> OnPostDataAsync(int page, int rows, AppSearch where)
{
var data = await _service.GetListAsync(page, rows, where, null);
return PagerData(data.items, page, rows, data.count);
}
/// <summary>
/// 删除
/// </summary>
[Auth("delete")]
public async Task<IActionResult> OnPostDeleteAsync(params long[] id)
{
await _service.DeleteAsync(id);
return JsonData(true);
}
/// <summary>
/// 恢复
/// </summary>
[Auth("restore")]
public async Task<IActionResult> OnPostRestoreAsync(params long[] id)
{
await _service.RestoreAsync(id);
return JsonData(true);
}
}
}
|
kulend/Vino.Core.CMS
|
source/Ku.Core.CMS.Web.Backend/Pages/DataCenter/App/Index.cshtml.cs
|
C#
|
apache-2.0
| 1,644
|
package dk.lessismore.nojpa.masterworker.bean;
/**
* Created : by IntelliJ IDEA.
* User: seb
* Date: 22-10-2010
* Time: 16:04:19
* To change this template use File | Settings | File Templates.
*/
public interface RemoteBeanInterface {
public void closeDownRemoteBean();
public double getProgress();
}
|
NoJPA-LESS-IS-MORE/NoJPA
|
nojpa_common/src/main/java/dk/lessismore/nojpa/masterworker/bean/RemoteBeanInterface.java
|
Java
|
apache-2.0
| 321
|
# vericredClient.PlanDeleted
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
|
vericred/vericred-javascript
|
docs/PlanDeleted.md
|
Markdown
|
apache-2.0
| 141
|
package com.khs.microservice.whirlpool.common;
public class Command {
// type is for JSON
private String type;
private String id;
private String command;
private String subscription;
public String getType() { return type; }
public void setType(String type) { this.type = type; }
public String getId() { return id; }
public void setId(String id) { this.id = id; }
public String getCommand() {
return command;
}
public void setCommand(String command) {
this.command = command;
}
public String getSubscription() {
return subscription;
}
public void setSubscription(String subscription) { this.subscription = subscription; }
@Override
public boolean equals(Object o) {
if (this == o) { return true; }
if (o == null || getClass() != o.getClass()) { return false; }
Command that = (Command) o;
if (id != null ? !id.equals(that.id) : that.id != null) { return false; }
if (command != null ? !command.equals(that.command) : that.command != null) { return false; }
if (subscription != null ? !subscription.equals(that.subscription) : that.subscription != null) { return false; }
return true;
}
@Override
public int hashCode() {
int result = this.id != null ? this.id.hashCode() : 0;
result = 31 * result + (command != null ? command.hashCode() : 0);
result = 31 * result + (subscription != null ? subscription.hashCode() : 0);
return result;
}
@Override
public String toString() {
return type + "{" +
"id='" + id + "'" +
", command='" + command + "'" +
", subscription='" + subscription + "'" +
"}";
}
}
|
jwboardman/whirlpool
|
common/src/main/java/com/khs/microservice/whirlpool/common/Command.java
|
Java
|
apache-2.0
| 1,771
|
#include <zk/server/server_tests.hpp>
#include <algorithm>
#include <chrono>
#include <cstring>
#include <iostream>
#include <thread>
#include "client.hpp"
#include "error.hpp"
#include "multi.hpp"
#include "string_view.hpp"
namespace zk
{
static buffer buffer_from(string_view str)
{
return buffer(str.data(), str.data() + str.size());
}
class client_tests :
public server::single_server_fixture
{ };
GTEST_TEST_F(client_tests, get_root)
{
client c = get_connected_client();
auto res = c.get("/").get();
std::cerr << res << std::endl;
c.close();
}
GTEST_TEST_F(client_tests, exists)
{
client c = get_connected_client();
CHECK_TRUE(c.exists("/").get());
CHECK_FALSE(c.exists("/some/bogus/path").get());
}
GTEST_TEST_F(client_tests, create)
{
client c = get_connected_client();
const char local_buf[10] = { 0 };
auto f_create = c.create("/test-node", buffer(local_buf, local_buf + sizeof local_buf));
auto name = f_create.get().name();
CHECK_EQ("/test-node", name);
}
GTEST_TEST_F(client_tests, create_seq_and_set)
{
client c = get_connected_client();
auto f_create = c.create("/test-node-", buffer_from("Hello!"), create_mode::sequential);
auto name = f_create.get().name();
auto orig_stat = c.get(name).get().stat();
auto expected_version = orig_stat.data_version;
++expected_version;
c.set(name, buffer_from("WORLD")).get();
auto contents = c.get(name).get();
CHECK_EQ(contents.stat().data_version, expected_version);
CHECK_TRUE(contents.data() == buffer_from("WORLD"));
}
GTEST_TEST_F(client_tests, create_seq_and_erase)
{
client c = get_connected_client();
auto f_create = c.create("/test-node-", buffer_from("Hello!"), create_mode::sequential);
auto name = f_create.get().name();
auto orig_stat = c.get(name).get().stat();
c.erase(name, orig_stat.data_version).get();
CHECK_THROWS(no_entry)
{
c.get(name).get();
};
}
GTEST_TEST_F(client_tests, create_seq_and_get_children)
{
client c = get_connected_client();
auto f_create = c.create("/test-node-", buffer_from("Hello!"), create_mode::sequential);
auto name = f_create.get().name();
auto orig_stat = c.get(name).get().stat();
c.create(name + "/a", buffer()).get();
c.create(name + "/b", buffer()).get();
c.create(name + "/c", buffer()).get();
auto result = c.get_children(name).get();
CHECK_EQ(orig_stat.data_version, result.parent_stat().data_version);
CHECK_LT(orig_stat.child_version, result.parent_stat().child_version);
std::vector<std::string> expected_children = { "a", "b", "c" };
std::sort(result.children().begin(), result.children().end());
CHECK_TRUE(expected_children == result.children());
}
GTEST_TEST_F(client_tests, acl)
{
client c = get_connected_client();
auto name = c.create("/test-node-", buffer_from("Hello!"), create_mode::sequential).get().name();
// set the data of the node a few times to make sure the data_version is different value from acl_version
for (std::size_t changes = 0; changes < 5; ++changes)
c.set(name, buffer_from("data change")).get();
auto orig_result = c.get_acl(name).get();
CHECK_EQ(acls::open_unsafe(), orig_result.acl());
std::cerr << "HEY: " << orig_result << std::endl;
c.set_acl(name, acls::read_unsafe(), orig_result.stat().acl_version).get();
auto new_result = c.get_acl(name).get();
CHECK_EQ(acls::read_unsafe(), new_result.acl());
}
GTEST_TEST_F(client_tests, watch_change)
{
client c = get_connected_client();
auto name = c.create("/test-node-", buffer_from("Hello!"), create_mode::sequential).get().name();
auto watch = c.watch(name).get();
CHECK_TRUE(watch.initial().data() == buffer_from("Hello!"));
c.set(name, buffer_from("world")); // don't wait -- the watch won't trigger until the operation completes
auto ev = watch.next().get();
CHECK_EQ(ev.type(), event_type::changed);
CHECK_EQ(ev.state(), state::connected);
}
GTEST_TEST_F(client_tests, watch_children)
{
client c = get_connected_client();
auto root_name = c.create("/test-node-", buffer_from("Hello!"), create_mode::sequential).get().name();
c.commit({
op::create(root_name + "/a", buffer_from("a")),
op::create(root_name + "/b", buffer_from("b")),
op::create(root_name + "/c", buffer_from("c")),
op::create(root_name + "/d", buffer_from("d")),
}).get();
auto watch_child_creation = c.watch_children(root_name).get();
CHECK_EQ(4U, watch_child_creation.initial().children().size());
c.create(root_name + "/e", buffer_from("e"));
auto ev = watch_child_creation.next().get();
CHECK_EQ(ev.type(), event_type::child);
CHECK_EQ(ev.state(), state::connected);
auto watch_child_erase = c.watch_children(root_name).get();
CHECK_EQ(5U, watch_child_erase.initial().children().size());
c.erase(root_name + "/a");
auto ev2 = watch_child_erase.next().get();
CHECK_EQ(ev2.type(), event_type::child);
CHECK_EQ(ev2.state(), state::connected);
}
GTEST_TEST_F(client_tests, watch_exists)
{
client c = get_connected_client();
auto root_name = c.create("/test-node-", buffer_from("Hello!"), create_mode::sequential).get().name();
auto watch_creation = c.watch_exists(root_name + "/sub").get();
CHECK_FALSE(watch_creation.initial());
c.create(root_name + "/sub", buffer_from("Blah"));
auto ev = watch_creation.next().get();
CHECK_EQ(ev.type(), event_type::created);
CHECK_EQ(ev.state(), state::connected);
auto watch_erase = c.watch_exists(root_name + "/sub").get();
CHECK_TRUE(watch_erase.initial());
c.erase(root_name + "/sub");
auto ev2 = watch_erase.next().get();
CHECK_EQ(ev2.type(), event_type::erased);
CHECK_EQ(ev2.state(), state::connected);
}
GTEST_TEST_F(client_tests, load_fence)
{
client c = get_connected_client();
// There does not appear to be a good way to actually test this -- so just make sure we don't segfault
c.load_fence().get();
}
GTEST_TEST_F(client_tests, watch_close)
{
client c = get_connected_client();
auto watch = c.watch("/").get();
c.close();
// watch should be triggered with session closed
auto ev = watch.next().get();
CHECK_EQ(ev.type(), event_type::session);
CHECK_EQ(ev.state(), state::closed);
}
class stopping_client_tests :
public server::server_fixture
{ };
GTEST_TEST_F(stopping_client_tests, watch_server_stop)
{
client c = get_connected_client();
auto watch = c.watch("/").get();
this->stop_server(true);
auto ev = watch.next().get();
CHECK_EQ(ev.type(), event_type::session);
}
}
|
tgockel/zookeeper-cpp
|
src/zk/client_tests.cpp
|
C++
|
apache-2.0
| 6,726
|
import numpy as np
import matplotlib.pyplot as plt #Used for graphing audio tests
import pyaudio as pa
import wave
from time import sleep
#Constants used for sampling audio
CHUNK = 1024
FORMAT = pa.paInt16
CHANNELS = 1
RATE = 44100 # Must match rate at which mic actually samples sound
RECORD_TIMEFRAME = 1.0 #Time in seconds
OUTPUT_FILE = "sample.wav"
#Flag for plotting sound input waves for debugging and implementation purposes
TESTING_GRAPHS = True
def sampleAudio(wav_name=OUTPUT_FILE):
"""Samples audio from the microphone for a given period of time.
The output file is saved as [wav_name]
Code here taken from the front page of:
< https://people.csail.mit.edu/hubert/pyaudio/ > """
# Open the recording session
rec_session = pa.PyAudio()
stream = rec_session.open(format=FORMAT,
channels=CHANNELS,rate=RATE,input=True,frames_per_buffer=CHUNK)
print("Start recording")
frames = []
# Sample audio frames for given time period
for i in range(0, int(RATE/CHUNK*RECORD_TIMEFRAME)):
data = stream.read(CHUNK)
frames.append(data)
# Close the recording session
stream.stop_stream()
stream.close()
rec_session.terminate()
#Create the wav file for analysis
output_wav = wave.open(wav_name,"wb")
output_wav.setnchannels(CHANNELS)
output_wav.setsampwidth(rec_session.get_sample_size(FORMAT))
output_wav.setframerate(RATE)
output_wav.writeframes(b''.join(frames))
output_wav.close()
def getAvgFreq(wav_file=OUTPUT_FILE):
"""Analyzes the audio sample [wav_file] (must be a 16-bit WAV file with
one channel) and returns maximum magnitude of the most prominent sound
and the frequency thresholds it falls between.
Basic procedure of processing audio taken from:
< http://samcarcagno.altervista.org/blog/basic-sound-processing-python/ >"""
#Open wav file for analysis
sound_sample = wave.open(wav_file, "rb")
#Get sampling frequency
sample_freq = sound_sample.getframerate()
#Extract audio frames to be analyzed
# audio_frames = sound_sample.readframes(sound_sample.getnframes())
audio_frames = sound_sample.readframes(1024)
converted_val = []
#COnvert byte objects into frequency values per frame
for i in range(0,len(audio_frames),2):
if ord(audio_frames[i+1])>127:
converted_val.append(-(ord(audio_frames[i])+(256*(255-ord(audio_frames[i+1])))))
else:
converted_val.append(ord(audio_frames[i])+(256*ord(audio_frames[i+1])))
#Fit into numpy array for FFT analysis
freq_per_frame = np.array(converted_val)
# Get amplitude of soundwave section
freq = np.fft.fft(freq_per_frame)
amplitude = np.abs(freq)
amplitude = amplitude/float(len(freq_per_frame))
amplitude = amplitude**2
#Get bins/thresholds for frequencies
freqbins = np.fft.fftfreq(CHUNK,1.0/sample_freq)
x = np.linspace(0.0,1.0,1024)
# Plot data if need visualization
if(TESTING_GRAPHS):
#Plot raw data
plt.plot(converted_val)
plt.title("Raw Data")
plt.xlabel("Time (ms)")
plt.ylabel("Frequency (Hz)")
plt.show()
#Plot frequency histogram
plt.plot(freqbins[:16],amplitude[:16])
plt.title("Processed Data")
plt.xlabel("Frequency Bins")
plt.ylabel("Magnitude")
plt.show()
#Get the range that the max amplitude falls in. This represents the loudest noise
magnitude = np.amax(amplitude)
loudest = np.argmax(amplitude)
lower_thres = freqbins[loudest]
upper_thres = (freqbins[1]-freqbins[0])+lower_thres
#Close wav file
sound_sample.close()
#Return the magnitude of the sound wave and its frequency threshold for analysis
return magnitude, lower_thres, upper_thres
#Use for testing microphone input
if __name__ == "__main__":
# print("Wait 3 seconds to start...")
# sleep(3)
print("Recording!")
sampleAudio(OUTPUT_FILE)
print("Stop recording!")
print("Analyzing...")
mag, lower, upper = getAvgFreq(OUTPUT_FILE)
print("Magnitude is "+str(mag))
print("Lower bin threshold is "+str(lower))
print("Upper bin threshold is "+str(upper))
|
cornell-cup/cs-minibot-platform
|
python-interface/src/MiniBotFramework/Sound/live_audio_sample.py
|
Python
|
apache-2.0
| 3,940
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Appacitive.Sdk.Wcf
{
public class SessionCleanupProxy : ISession, IDisposable
{
public SessionCleanupProxy(ISession internalSession, TimeSpan heartbeat, TimeSpan expiryDuration)
{
this.Session = internalSession;
_collector = new Timer( OnHeartbeat, null, TimeSpan.Zero, heartbeat);
_expiryLimit = expiryDuration;
}
public ISession Session { get; private set; }
private Timer _collector;
private TimeSpan _expiryLimit;
public object this[string key]
{
get
{
NotifyKeyActivity(key);
return this.Session[key];
}
set
{
NotifyKeyActivity(key);
this.Session[key] = value;
}
}
public void Remove(string key)
{
this.Session.Remove(key);
RemoveKey(key);
}
private void NotifyKeyActivity(string key)
{
TouchKey(key);
}
private void OnHeartbeat(object state)
{
// If busy then return.
if (Interlocked.CompareExchange(ref _isBusy, YES, NO) != NO)
return;
try
{
// Iterate through all keys in the keys collection and expiry those with lifetime > expiry time.
var existing = CloneKeys();
var toBeCleaned = existing.Where(x => DateTime.Now - x.Value > _expiryLimit).ToList();
toBeCleaned.ForEach(x => RemoveKey(x.Key));
}
finally
{
_isBusy = NO;
}
}
private static readonly int YES = 1;
private static readonly int NO = 0;
private int _isBusy = NO;
private readonly object _keyLock = new object();
private Dictionary<string, DateTime> _keys = new Dictionary<string, DateTime>();
private KeyValuePair<string, DateTime>[] CloneKeys()
{
lock (_keyLock)
{
return _keys.ToArray();
}
}
private void TouchKey(string key)
{
lock (_keyLock)
{
_keys[key] = DateTime.Now;
}
}
private void RemoveKey(string key)
{
lock (_keyLock)
{
if (_keys.ContainsKey(key) == true)
_keys.Remove(key);
}
}
public void Dispose()
{
if (_collector != null)
{
_collector.Change(-1, Timeout.Infinite);
_collector.Dispose();
_collector = null;
}
}
}
}
|
appacitive/appacitive-dotnet-sdk
|
src/Appacitive.Sdk.Net45/Wcf/SessionCleanupProxy.cs
|
C#
|
apache-2.0
| 2,920
|
# CHANGELOG
This file is used to list changes made in each version of the unfi cookbook.
## v2.0.0 (2020-02-01)
- Get InSpec tests passing
- Bump minimum Chef Infra Client version to 13+ for `apt_update` resource
- Add dependency on the `java` cookbook and remove obsolete Java 6 support
- Removed support for Debian 8 as openjdk is not easily available
- Removed unused long_description from metadata.rb
- Simplify platforms depends statements in the metadata
- Migrate to Github Actions for testing
## v1.2.0 (2016-09-23)
- Add an attribute for setting the repo components so you can use unstable releases
- Require at least Chef 12.1
- Add chef_version metadata
- Misc testing improvements
## v1.1.0 (2016-05-24)
- Ownership has been transferred from Orion Labs. Thanks for all the original work folks.
- Updated the PPA resource to work with the Apt 3.0 cookbook
- Added Debian as a supported platform
- Added contributing and testing docs
- Added Debian and Ubuntu 16.04 to the Test Kitchen config
- Added testing in Travis including Kitchen-Dokken integration testing
- Updated the metadata with issues_url and source_url metadata
- Resolved all cookstyle (rubocop) warnings
- Updated the Berksfile to point to the supermarket
- Added maintainers files with contact information
- Added a Rakefile for simplified testing
- Added Github templates for PRs and Issues
- Updated testing deps to the latest versions
- Changed from Rubocop to Cookstyle to bring in a set of sale defaults
- Existing build / CI files have been removed (Makefile, .ruby-version, Thorfile, Vagrantfile)
|
tas50/unifi
|
CHANGELOG.md
|
Markdown
|
apache-2.0
| 1,589
|
/*
* Copyright 2019, EnMasse authors.
* License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html).
*/
package io.enmasse.address.model;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import com.fasterxml.jackson.annotation.JsonInclude;
import io.fabric8.kubernetes.api.model.Doneable;
import io.sundr.builder.annotations.Buildable;
import io.sundr.builder.annotations.Inline;
/**
* A reduced, info only, view on the {@link AddressType} object.
*/
@Buildable(
editableEnabled = false,
generateBuilderPackage = false,
builderPackage = "io.fabric8.kubernetes.api.builder",
inline = @Inline(
type = Doneable.class,
prefix = "Doneable",
value = "done"))
@JsonInclude(JsonInclude.Include.NON_NULL)
public class AddressTypeInformation {
@NotNull
private String name;
private String description;
private List<@Valid AddressPlanDescription> plans = new ArrayList<>();
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public void setPlans(final List<AddressPlanDescription> plans) {
this.plans = plans;
}
public List<AddressPlanDescription> getPlans() {
return plans;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
AddressTypeInformation that = (AddressTypeInformation) o;
return Objects.equals(name, that.name) &&
Objects.equals(description, that.description) &&
Objects.equals(plans, that.plans);
}
@Override
public int hashCode() {
return Objects.hash(name, description, plans);
}
@Override
public String toString() {
return "AddressTypeInformation{" +
"name='" + name + '\'' +
", description='" + description + '\'' +
", plans=" + plans +
'}';
}
public static AddressTypeInformation fromAddressType(final AddressType addressType) {
if (addressType == null) {
return null;
}
return new AddressTypeInformationBuilder()
.withName(addressType.getName())
.withDescription(addressType.getDescription())
.withPlans(addressType.getPlans().stream()
.map(plan -> new AddressPlanDescription(plan.getMetadata().getName(), plan.getShortDescription(), plan.getResources()))
.collect(Collectors.toList()))
.build();
}
}
|
jenmalloy/enmasse
|
api-model/src/main/java/io/enmasse/address/model/AddressTypeInformation.java
|
Java
|
apache-2.0
| 3,004
|
/**
* Users collection.
* Initializes Users collection and provides methods
* for accessing the collection.
* */
users = "Users";
Users = new Mongo.Collection(users);
/**
* Schema for Users
*/
Users.attachSchema(new SimpleSchema({
userName:{
label: "Username",
type: String,
optional: false,
autoform:{
group: users,
placeholder: "Username"
}
},
firstName:{
label: "First Name",
type: String,
optional: true,
autoform:{
group: users,
placeholder: "First Name"
}
},
lastName:{
label: "Last Name",
type: String,
optional: true,
autoform:{
group: users,
placeholder: "Last Name"
}
},
email:{
label: "Email",
type: String,
optional: false,
unique: true,
autoform:{
group: users,
placeholder: "Email"
}
},
roles: {
type: Object,
optional: true,
blackbox: true
}
}));
|
CutieOranges/FarmersMarket
|
app/lib/collections/Users.js
|
JavaScript
|
apache-2.0
| 942
|
package com.dangdang.ddframe.job.plugin.sharding.strategy;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.dangdang.ddframe.job.internal.sharding.strategy.JobShardingStrategy;
import com.dangdang.ddframe.job.internal.sharding.strategy.JobShardingStrategyOption;
/**
* 根据作业名的哈希值对服务器列表进行轮转的分片策略.
*
* @author weishubin
* @author xiong.j support jdk1.6
*/
public class RotateServerByNameJobShardingStrategy implements JobShardingStrategy {
private AverageAllocationJobShardingStrategy averageAllocationJobShardingStrategy = new AverageAllocationJobShardingStrategy();
@Override
public Map<String, List<Integer>> sharding(final List<String> serversList, final JobShardingStrategyOption option) {
return averageAllocationJobShardingStrategy.sharding(rotateServerList(serversList, option.getJobName()), option);
}
private List<String> rotateServerList(final List<String> serversList, final String jobName) {
int serverSize = serversList.size();
int offset = Math.abs(jobName.hashCode()) % serverSize;
if (0 == offset) {
return serversList;
}
List<String> result = new ArrayList<String>(serverSize);
for (int i = 0; i < serverSize; i++) {
int index = (i + offset) % serverSize;
result.add(serversList.get(index));
}
return result;
}
}
|
artoderk/elastic-jobx
|
elastic-jobx-core/src/main/java/com/dangdang/ddframe/job/plugin/sharding/strategy/RotateServerByNameJobShardingStrategy.java
|
Java
|
apache-2.0
| 1,467
|
# Lachnea abundans P. Karst., 1869 SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
Not. Sällsk. Fauna et Fl. Fenn. Förh. 10: 124 (1869)
#### Original name
Lachnea abundans P. Karst., 1869
### Remarks
null
|
mdoering/backbone
|
life/Fungi/Ascomycota/Pezizomycetes/Pezizales/Pyronemataceae/Trichophaea/Trichophaea abundans/ Syn. Lachnea abundans/README.md
|
Markdown
|
apache-2.0
| 267
|
// ======================================================================== //
// Copyright 2009-2017 Intel Corporation //
// //
// Licensed under the Apache License, Version 2.0 (the "License"); //
// you may not use this file except in compliance with the License. //
// You may obtain a copy of the License at //
// //
// http://www.apache.org/licenses/LICENSE-2.0 //
// //
// Unless required by applicable law or agreed to in writing, software //
// distributed under the License is distributed on an "AS IS" BASIS, //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and //
// limitations under the License. //
// ======================================================================== //
#pragma once
#include "../sys/alloc.h"
#include "math.h"
#include "../simd/sse.h"
namespace embree
{
////////////////////////////////////////////////////////////////////////////////
/// SSE Vec3ba Type
////////////////////////////////////////////////////////////////////////////////
struct __aligned(16) Vec3ba
{
ALIGNED_STRUCT;
union {
__m128 m128;
struct { int x,y,z; int a; };
};
typedef int Scalar;
enum { N = 3 };
////////////////////////////////////////////////////////////////////////////////
/// Constructors, Assignment & Cast Operators
////////////////////////////////////////////////////////////////////////////////
__forceinline Vec3ba( ) {}
__forceinline Vec3ba( const __m128 input ) : m128(input) {}
__forceinline Vec3ba( const Vec3ba& other ) : m128(other.m128) {}
__forceinline Vec3ba& operator =(const Vec3ba& other) { m128 = other.m128; return *this; }
__forceinline explicit Vec3ba( bool a )
: m128(_mm_lookupmask_ps[(size_t(a) << 3) | (size_t(a) << 2) | (size_t(a) << 1) | size_t(a)]) {}
__forceinline Vec3ba( bool a, bool b, bool c)
: m128(_mm_lookupmask_ps[(size_t(c) << 2) | (size_t(b) << 1) | size_t(a)]) {}
__forceinline operator const __m128&( void ) const { return m128; }
__forceinline operator __m128&( void ) { return m128; }
////////////////////////////////////////////////////////////////////////////////
/// Constants
////////////////////////////////////////////////////////////////////////////////
__forceinline Vec3ba( FalseTy ) : m128(_mm_setzero_ps()) {}
__forceinline Vec3ba( TrueTy ) : m128(_mm_castsi128_ps(_mm_cmpeq_epi32(_mm_setzero_si128(), _mm_setzero_si128()))) {}
////////////////////////////////////////////////////////////////////////////////
/// Array Access
////////////////////////////////////////////////////////////////////////////////
__forceinline const int& operator []( const size_t index ) const { assert(index < 3); return (&x)[index]; }
__forceinline int& operator []( const size_t index ) { assert(index < 3); return (&x)[index]; }
};
////////////////////////////////////////////////////////////////////////////////
/// Unary Operators
////////////////////////////////////////////////////////////////////////////////
__forceinline const Vec3ba operator !( const Vec3ba& a ) { return _mm_xor_ps(a.m128, Vec3ba(embree::True)); }
////////////////////////////////////////////////////////////////////////////////
/// Binary Operators
////////////////////////////////////////////////////////////////////////////////
__forceinline const Vec3ba operator &( const Vec3ba& a, const Vec3ba& b ) { return _mm_and_ps(a.m128, b.m128); }
__forceinline const Vec3ba operator |( const Vec3ba& a, const Vec3ba& b ) { return _mm_or_ps (a.m128, b.m128); }
__forceinline const Vec3ba operator ^( const Vec3ba& a, const Vec3ba& b ) { return _mm_xor_ps(a.m128, b.m128); }
////////////////////////////////////////////////////////////////////////////////
/// Assignment Operators
////////////////////////////////////////////////////////////////////////////////
__forceinline const Vec3ba operator &=( Vec3ba& a, const Vec3ba& b ) { return a = a & b; }
__forceinline const Vec3ba operator |=( Vec3ba& a, const Vec3ba& b ) { return a = a | b; }
__forceinline const Vec3ba operator ^=( Vec3ba& a, const Vec3ba& b ) { return a = a ^ b; }
////////////////////////////////////////////////////////////////////////////////
/// Comparison Operators + Select
////////////////////////////////////////////////////////////////////////////////
__forceinline bool operator ==( const Vec3ba& a, const Vec3ba& b ) {
return (_mm_movemask_ps(_mm_castsi128_ps(_mm_cmpeq_epi32(_mm_castps_si128(a.m128), _mm_castps_si128(b.m128)))) & 7) == 7;
}
__forceinline bool operator !=( const Vec3ba& a, const Vec3ba& b ) {
return (_mm_movemask_ps(_mm_castsi128_ps(_mm_cmpeq_epi32(_mm_castps_si128(a.m128), _mm_castps_si128(b.m128)))) & 7) != 7;
}
__forceinline bool operator < ( const Vec3ba& a, const Vec3ba& b ) {
if (a.x != b.x) return a.x < b.x;
if (a.y != b.y) return a.y < b.y;
if (a.z != b.z) return a.z < b.z;
return false;
}
////////////////////////////////////////////////////////////////////////////////
/// Reduction Operations
////////////////////////////////////////////////////////////////////////////////
__forceinline bool reduce_and( const Vec3ba& a ) { return (_mm_movemask_ps(a) & 0x7) == 0x7; }
__forceinline bool reduce_or ( const Vec3ba& a ) { return (_mm_movemask_ps(a) & 0x7) != 0x0; }
__forceinline bool all ( const Vec3ba& b ) { return (_mm_movemask_ps(b) & 0x7) == 0x7; }
__forceinline bool any ( const Vec3ba& b ) { return (_mm_movemask_ps(b) & 0x7) != 0x0; }
__forceinline bool none ( const Vec3ba& b ) { return (_mm_movemask_ps(b) & 0x7) == 0x0; }
////////////////////////////////////////////////////////////////////////////////
/// Output Operators
////////////////////////////////////////////////////////////////////////////////
inline std::ostream& operator<<(std::ostream& cout, const Vec3ba& a) {
return cout << "(" << (a.x ? "1" : "0") << ", " << (a.y ? "1" : "0") << ", " << (a.z ? "1" : "0") << ")";
}
}
|
Sjoerdie/embree
|
common/math/vec3ba.h
|
C
|
apache-2.0
| 6,568
|
package com.coolweather.app.activity;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.coolweather.app.R;
import com.coolweather.app.db.CoolWeatherDB;
import com.coolweather.app.model.City;
import com.coolweather.app.model.County;
import com.coolweather.app.model.Province;
import com.coolweather.app.util.HttpCallbackListener;
import com.coolweather.app.util.HttpUtil;
import com.coolweather.app.util.Utility;
public class ChooseAreaActivity extends Activity{
public static final int LEVEL_PROVINCE = 0;
public static final int LEVEL_CITY = 1;
public static final int LEVEL_COUNTY = 2;
private ProgressDialog progressDialog;
private TextView titleText;
private ListView listView;
private ArrayAdapter<String> adapter;
private CoolWeatherDB coolWeatherDB;
private List<String> dataList=new ArrayList<String>();
/**
*Ê¡Áбí
*/
private List<Province> provinceList;
/**
*ÊÐÁбí
*/
private List<City> cityList;
/**
*ÏØÁбí
*/
private List<County> countyList;
/**
* Ñ¡ÖеÄÊ¡·Ý
*/
private Province selectedProvince;
/**
*Ñ¡ÖеijÇÊÐ
*/
private City selectedCity;
/**
*µ±Ç°Ñ¡Öеļ¶±ð
*/
private int currentLevel;
/**
*ÊÇ·ñ´ÓWeatherActivityÖÐÌø×ª¹ýÀ´¡£
*/
private boolean isFromWeatherActivity;
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
isFromWeatherActivity=getIntent().getBooleanExtra(
"from_weather_activity", false);
SharedPreferences prefs = PreferenceManager.
getDefaultSharedPreferences(this);
//ÒѾѡÔñÁ˳ÇÊÐÇÒ²»ÊÇ´ÓWeatherActivityÌø×ª¹ýÀ´£¬²Å»áÖ±½ÓÌø×ªµ½WeatherActivity
if(prefs.getBoolean("city_selected", false) && !isFromWeatherActivity){
Intent intent = new Intent(this,WeatherActivity.class);
startActivity(intent);
finish();
return;
}
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.choose_area);
listView = (ListView)findViewById(R.id.list_view);
titleText = (TextView)findViewById(R.id.title_text);
adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,
dataList);
listView.setAdapter(adapter);
coolWeatherDB = CoolWeatherDB.getInstance(this);
listView.setOnItemClickListener(new OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> arg0, View view, int index,
long arg3) {
if(currentLevel == LEVEL_PROVINCE){
selectedProvince = provinceList.get(index);
queryCities();
}else if(currentLevel == LEVEL_CITY){
selectedCity=cityList.get(index);
queryCounties();
}else if(currentLevel == LEVEL_COUNTY){
String countyCode = countyList.get(index).getCountyCode();
Intent intent = new Intent(ChooseAreaActivity.this,
WeatherActivity.class);
intent.putExtra("county_code", countyCode);
startActivity(intent);
finish();
}
}
});
queryProvinces(); //¼ÓÔØÊ¡¼¶Êý¾Ý
}
/**
* ²éѯȫ¹úËùÓеÄÊ¡·Ý£¬ÓÅÏÈ´ÓÊý¾Ý¿â²éѯ£¬Èç¹ûûÓвéѯµ½ÔÙÈ¥·þÎñÆ÷Éϲéѯ¡£
*/
private void queryProvinces(){
provinceList = coolWeatherDB.loadProvinces();
if(provinceList.size() > 0){
dataList.clear();
for(Province province : provinceList){
dataList.add(province.getProvinceName());
}
adapter.notifyDataSetChanged();
listView.setSelection(0);
titleText.setText("Öйú");
currentLevel=LEVEL_PROVINCE;
}else{
queryFromServer(null, "province");
}
}
/**
*²éѯѡÖÐÊ¡ÄÚËùÓеÄÊУ¬ÓÅÏÈ´ÓÊý¾Ý¿â²éѯ£¬Èç¹ûûÓвéѯµ½ÔÙÈ¥·þÎñÆ÷Éϲéѯ¡£
*/
private void queryCities(){
cityList=coolWeatherDB.loadCities(selectedProvince.getId());
if(cityList.size() > 0){
dataList.clear();
for(City city : cityList){
dataList.add(city.getCityName());
}
adapter.notifyDataSetChanged();
listView.setSelection(0);
titleText.setText(selectedProvince.getProvinceName());
currentLevel=LEVEL_CITY;
}else{
queryFromServer(selectedProvince.getProvinceCode(),"city");
}
}
/**
* ²éѯѡÖÐÊÐÄÚµÄËùÓÐÏØ£¬ÓÅÏÈ´ÓÊý¾Ý¿â²éѯ£¬Èç¹ûûÓвéѯµ½ÔÙµ½·þÎñÆ÷ÉÏÈ¥²éѯ¡£
*/
private void queryCounties(){
countyList=coolWeatherDB.loadCounties(selectedCity.getId());
if(countyList.size() > 0){
dataList.clear();
for(County county : countyList){
dataList.add(county.getCountyName());
}
adapter.notifyDataSetChanged();
listView.setSelection(0);
titleText.setText(selectedCity.getCityName());
currentLevel=LEVEL_COUNTY;
}else{
queryFromServer(selectedCity.getCityCode(),"county");
}
}
/**
*¸ù¾Ý´«ÈëµÄ´úºÅºÍÊý¾ÝÀàÐÍ´Ó·þÎñÆ÷ÉϲéѯʡÊÐÏØÊý¾Ý¡£
*/
private void queryFromServer(final String code,final String type){
String address;
if(!TextUtils.isEmpty(code)){
address="http://www.weather.com.cn/data/list3/city"+code+".xml";
}else{
address="http://www.weather.com.cn/data/list3/city.xml";
}
showProgressDialog();
HttpUtil.sendHttpRequest(address, new HttpCallbackListener(){
@Override
public void onFinish(String response){
boolean result=false;
if("province".equals(type)){
result=Utility.handleProvincesResponse(coolWeatherDB,
response);
}else if("city".equals(type)){
result=Utility.handleCitiesResponse(coolWeatherDB,
response,selectedProvince.getId());
}else if("county".equals(type)){
result=Utility.handleCountiesResponse(coolWeatherDB,
response, selectedCity.getId());
}
if(result){
//ͨ¹ýrunOnThread()·½·¨»Øµ½Ö÷Ï̴߳¦ÀíÂß¼
runOnUiThread(new Runnable(){
@Override
public void run(){
closeProgressDialog();
if("province".equals(type)){
queryProvinces();
} else if("city".equals(type)){
queryCities();
} else if("county".equals(type)){
queryCounties();
}
}
});
}
}
@Override
public void onError(Exception e){
//ͨ¹ýrunOnUiThread()·½·¨»Øµ½Ö÷Ï̴߳¦ÀíÂß¼
runOnUiThread(new Runnable(){
@Override
public void run(){
closeProgressDialog();
Toast.makeText(ChooseAreaActivity.this,
"¼ÓÔØÊ§°Ü",Toast.LENGTH_SHORT).show();
}
});
}
});
}
/**
*ÏÔʾ½ø¶È¶Ô»°¿ò
*/
private void showProgressDialog(){
if(progressDialog == null){
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("ÕýÔÚ¼ÓÔØÖÐ...");
progressDialog.setCanceledOnTouchOutside(false);
}
progressDialog.show();
}
/**
*¹Ø±Õ½ø¶È¶Ô»°¿ò
*/
private void closeProgressDialog(){
if(progressDialog!=null){
progressDialog.dismiss();
}
}
/**
* ²¶»ñBack°´¼ü£¬¸ù¾Ýµ±Ç°¼¶±ðÀ´Åжϣ¬´ËʱӦ¸Ã·µ»ØÊÐÁÐ±í£¬Ê¡ÁÐ±í£¬»¹ÊÇÖ±½ÓÍ˳ö
*/
@Override
public void onBackPressed(){
if(currentLevel == LEVEL_COUNTY){
queryCities();
} else if(currentLevel == LEVEL_CITY){
queryProvinces();
}else{
if(isFromWeatherActivity){
Intent intent=new Intent(this,WeatherActivity.class);
startActivity(intent);
}
finish();
}
}
}
|
tony-blue/coolweather
|
src/com/coolweather/app/activity/ChooseAreaActivity.java
|
Java
|
apache-2.0
| 7,411
|
if (typeof PATH_TO_THE_REPO_PATH_UTILS_FILE === 'undefined') {
PATH_TO_THE_REPO_PATH_UTILS_FILE = "https://raw.githubusercontent.com/highfidelity/hifi_tests/master/tests/utils/branchUtils.js";
Script.include(PATH_TO_THE_REPO_PATH_UTILS_FILE);
nitpick = createNitpick(Script.resolvePath("."));
}
nitpick.perform("Image Entity keepAspectRatio", Script.resolvePath("."), "secondary", undefined, function(testType) {
Script.include(nitpick.getUtilsRootPath() + "test_stage.js");
var LIFETIME = 200;
// Add the test Cases
var initData = {
flags: {
hasKeyLight: true,
hasAmbientLight: true
},
lifetime: LIFETIME,
originFrame: nitpick.getOriginFrame()
};
var createdEntities = setupStage(initData);
var posOri = getStagePosOriAt(0, 0, 0);
var assetsRootPath = nitpick.getAssetsRootPath();
function getPos(col, row) {
var center = posOri.pos;
return Vec3.sum(Vec3.sum(center, Vec3.multiply(Quat.getRight(MyAvatar.orientation), col)),
Vec3.multiply(Quat.getUp(MyAvatar.orientation), row));
}
createdEntities.push(Entities.addEntity({
type: "Image",
imageURL: assetsRootPath + "textures/redArrow.jpg",
position: getPos(-0.5, 1),
dimensions: 1.0,
keepAspectRatio: false,
lifetime: LIFETIME
}));
createdEntities.push(Entities.addEntity({
type: "Image",
imageURL: assetsRootPath + "textures/redArrow.jpg",
position: getPos(0.5, 1),
dimensions: 1.0,
keepAspectRatio: true,
lifetime: LIFETIME
}));
nitpick.addStepSnapshot("Take snapshot");
nitpick.addStep("Clean up after test", function () {
for (var i = 0; i < createdEntities.length; i++) {
Entities.deleteEntity(createdEntities[i]);
}
});
var result = nitpick.runTest(testType);
});
|
highfidelity/hifi_tests
|
tests/content/entity/image/keepAspectRatio/test.js
|
JavaScript
|
apache-2.0
| 2,006
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.