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
|
|---|---|---|---|---|---|
// Задание 11
// Войти на главную страницу http://localhost/litecart
// Зарегистрировать нового пользователя
// Выйти - Logout
// Авторизоваться пользователем и выйти
var webdriver = require('selenium-webdriver');
var chrome = require('selenium-webdriver/chrome');
var By = webdriver.By;
var until = webdriver.until;
var test = require('selenium-webdriver/testing');
var assert = require('assert');
var Key = webdriver.Key;
var $q=require('q');
test.describe('Регистрация пользователя', function() {
var driver; var email; var password;
var getRandomNumber = function () {
var n=100; var m=1000;
return Math.floor(Math.random( ) * (n - m + 1)) + m
};
test.before(function() {
driver = new webdriver.Builder()
.withCapabilities({'unexpectedAlertBehaviour': 'dismiss'})
.forBrowser('chrome')
.build();
driver.get('http://localhost/litecart/');
driver.manage().timeouts().implicitlyWait(10000/*ms*/);
});
test.after(function() {
driver.quit();
});
test.it('Регистрируемся', function() {
var inputField;
var number =getRandomNumber();
var firstname = "Marina";
var lastname = "Tolmacheva" + number;
email = "emailUser"+number+"@list.ru";
password = lastname;
driver.findElement(By.linkText("New customers click here")).click().then(
(click)=> {
driver.findElement(By.name("firstname")).sendKeys(firstname + Key.TAB
+ lastname + Key.TAB + "100 let Vladivostoky" + Key.TAB + "Davydova" + Key.TAB
+ "69006" + Key.TAB + "Vladivostok" + Key.TAB + "United States"
+ Key.TAB + email + Key.TAB + "+7 914 123 98 70" + Key.TAB
+ password + Key.TAB + password).then(()=>
driver.findElement(By.css("select[name = 'country_code']")).getAttribute("value")
.then((text) =>{
if (text == "US") {
var selectElem = driver.findElement(By.css("select[name = 'zone_code']"));
selectElem.click();
selectElem.findElement(By.css("option[value='AK']")).click();
}
})).then(()=>
driver.findElement(By.css("input[name='newsletter']")).getAttribute("value")
.then((text) =>{
if (text == "1") {
driver.findElement(By.css("input[name='newsletter']")).click();
}
})).then(()=>
driver.findElement(By.css("button[name='create_account']")).click()).then(()=>
driver.wait(driver.findElement(By.linkText("Logout")).click(),1000));
}
);
});
test.it('Авторизация', function () {
driver.findElement(By.name("email")).sendKeys(email).then(()=>
driver.findElement(By.name("password")).sendKeys(password)).then(()=>
driver.wait(driver.findElement(By.css("button[name = 'login'")).click(), 1000)).then(()=>
driver.wait(driver.findElement(By.linkText("Logout")).click(), 1000));
});
});
|
tolmacheva/ST_project
|
LAB/Less6_Lab11.js
|
JavaScript
|
apache-2.0
| 3,414
|
#!/bin/sh
ruby analysis.rb data/data_2015Q1.csv projects/projects_2015Q1.csv map/hints.csv map/urls.csv map/defmaps.csv map/skip.csv map/ranges.csv
ruby analysis.rb data/data_2015Q2.csv projects/projects_2015Q2.csv map/hints.csv map/urls.csv map/defmaps.csv map/skip.csv map/ranges.csv
ruby analysis.rb data/data_2015Q3.csv projects/projects_2015Q3.csv map/hints.csv map/urls.csv map/defmaps.csv map/skip.csv map/ranges.csv
ruby analysis.rb data/data_2015Q4.csv projects/projects_2015Q4.csv map/hints.csv map/urls.csv map/defmaps.csv map/skip.csv map/ranges.csv
ruby analysis.rb data/data_2016Q1.csv projects/projects_2016Q1.csv map/hints.csv map/urls.csv map/defmaps.csv map/skip.csv map/ranges.csv
ruby analysis.rb data/data_2016Q2.csv projects/projects_2016Q2.csv map/hints.csv map/urls.csv map/defmaps.csv map/skip.csv map/ranges.csv
ruby analysis.rb data/data_2016Q3.csv projects/projects_2016Q3.csv map/hints.csv map/urls.csv map/defmaps.csv map/skip.csv map/ranges.csv
ruby analysis.rb data/data_2016Q4.csv projects/projects_2016Q4.csv map/hints.csv map/urls.csv map/defmaps.csv map/skip.csv map/ranges.csv
ruby analysis.rb data/data_2017Q1.csv projects/projects_2017Q1.csv map/hints.csv map/urls.csv map/defmaps.csv map/skip.csv map/ranges.csv
|
cncf/velocity
|
shells/quarters.sh
|
Shell
|
apache-2.0
| 1,252
|
package AST;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.io.File;
import java.util.*;
import beaver.*;
import java.util.ArrayList;
import java.util.zip.*;
import java.io.*;
import java.util.Stack;
import java.util.regex.Pattern;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.Transformer;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Element;
import org.w3c.dom.Document;
import java.util.HashMap;
import java.util.Map.Entry;
import javax.xml.transform.TransformerException;
import javax.xml.parsers.ParserConfigurationException;
import java.util.Collection;
/**
* @ast interface
* @declaredat :0
*/
public interface FinallyHost {
//public Block getFinally();
//public Block getFinally();
public boolean isDUafterFinally(Variable v);
public boolean isDAafterFinally(Variable v);
/**
* @attribute syn
* @aspect CreateBCode
* @declaredat D:\zhh\JastAddJ\Java1.4Backend\CreateBCode.jrag:2061
*/
@SuppressWarnings({"unchecked", "cast"})
public int label_finally_block();
}
|
xjtu3c/GranuleJ
|
GOP/GranuleJIDE/src/AST/FinallyHost.java
|
Java
|
apache-2.0
| 1,447
|
<?xml version="1.0" encoding="utf-8"?>
<OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/"><ShortName>National Water Supply and Drainage Board</ShortName><Description>National Water Supply and Drainage Board</Description><InputEncoding>UTF-8</InputEncoding><Image type="image/vnd.microsoft.icon" width="16" height="16">http://waterboard.lk/web/templates/poora_temp/favicon.ico</Image><Url type="application/opensearchdescription+xml" rel="self" template="http://waterboard.lk/web/index.php?option=com_search&view=article&id=219&Itemid=106&lang=ta&format=opensearch"/><Url type="text/html" template="http://waterboard.lk/web/index.php?option=com_search&searchword={searchTerms}&Itemid=188"/></OpenSearchDescription>
|
cmaere/lwb
|
templates/protostar/indexd882.php
|
PHP
|
apache-2.0
| 759
|
// Copyright 2017 PingCAP, 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,
// See the License for the specific language governing permissions and
// limitations under the License.
package plan
import (
"github.com/pingcap/tidb/expression"
)
// pushDownTopNOptimizer pushes down the topN or limit. In the future we will remove the limit from `requiredProperty` in CBO phase.
type pushDownTopNOptimizer struct {
}
func (s *pushDownTopNOptimizer) optimize(p LogicalPlan) (LogicalPlan, error) {
return p.pushDownTopN(nil), nil
}
func (s *baseLogicalPlan) pushDownTopN(topN *LogicalTopN) LogicalPlan {
p := s.self
for i, child := range p.Children() {
p.Children()[i] = child.pushDownTopN(nil)
}
if topN != nil {
return topN.setChild(p, false)
}
return p
}
// setChild set p as topn's child. If eliminable is true, this topn plan can be removed.
func (lt *LogicalTopN) setChild(p LogicalPlan, eliminable bool) LogicalPlan {
if lt.partial && eliminable {
return p
}
if lt.isLimit() {
limit := LogicalLimit{
Count: lt.Count,
Offset: lt.Offset,
partial: lt.partial,
}.init(lt.ctx)
limit.SetChildren(p)
return limit
}
// Then lt must be topN.
lt.SetChildren(p)
return lt
}
func (ls *LogicalSort) pushDownTopN(topN *LogicalTopN) LogicalPlan {
if topN == nil {
return ls.baseLogicalPlan.pushDownTopN(nil)
} else if topN.isLimit() {
topN.ByItems = ls.ByItems
// If a Limit is pushed down, the LogicalSort should be converted to topN and be pushed again.
return ls.children[0].pushDownTopN(topN)
}
// If a TopN is pushed down, this sort is useless.
return ls.children[0].pushDownTopN(topN)
}
func (p *LogicalLimit) convertToTopN() *LogicalTopN {
return LogicalTopN{Offset: p.Offset, Count: p.Count}.init(p.ctx)
}
func (p *LogicalLimit) pushDownTopN(topN *LogicalTopN) LogicalPlan {
child := p.children[0].pushDownTopN(p.convertToTopN())
if topN != nil {
return topN.setChild(child, false)
}
return child
}
func (p *LogicalUnionAll) pushDownTopN(topN *LogicalTopN) LogicalPlan {
for i, child := range p.children {
var newTopN *LogicalTopN
if topN != nil {
newTopN = LogicalTopN{Count: topN.Count + topN.Offset, partial: true}.init(p.ctx)
for _, by := range topN.ByItems {
newTopN.ByItems = append(newTopN.ByItems, &ByItems{by.Expr.Clone(), by.Desc})
}
}
p.children[i] = child.pushDownTopN(newTopN)
}
if topN != nil {
return topN.setChild(p, true)
}
return p
}
func (p *LogicalProjection) pushDownTopN(topN *LogicalTopN) LogicalPlan {
if topN != nil {
for _, by := range topN.ByItems {
by.Expr = expression.ColumnSubstitute(by.Expr, p.schema, p.Exprs)
}
}
p.children[0] = p.children[0].pushDownTopN(topN)
return p
}
// pushDownTopNToChild will push a topN to one child of join. The idx stands for join child index. 0 is for left child.
func (p *LogicalJoin) pushDownTopNToChild(topN *LogicalTopN, idx int) LogicalPlan {
var newTopN *LogicalTopN
if topN != nil {
canPush := true
for _, by := range topN.ByItems {
cols := expression.ExtractColumns(by.Expr)
if len(p.children[1-idx].Schema().ColumnsIndices(cols)) != 0 {
canPush = false
break
}
}
if canPush {
newTopN = LogicalTopN{
Count: topN.Count + topN.Offset,
ByItems: make([]*ByItems, len(topN.ByItems)),
partial: true,
}.init(topN.ctx)
// The old topN should be maintained upon Join,
// so we clone TopN here and push down a newTopN.
for i := range topN.ByItems {
newTopN.ByItems[i] = topN.ByItems[i].Clone()
}
}
}
return p.children[idx].pushDownTopN(newTopN)
}
func (p *LogicalJoin) pushDownTopN(topN *LogicalTopN) LogicalPlan {
switch p.JoinType {
case LeftOuterJoin, LeftOuterSemiJoin, AntiLeftOuterSemiJoin:
p.children[0] = p.pushDownTopNToChild(topN, 0)
p.children[1] = p.children[1].pushDownTopN(nil)
case RightOuterJoin:
p.children[0] = p.children[0].pushDownTopN(nil)
p.children[1] = p.pushDownTopNToChild(topN, 1)
default:
return p.baseLogicalPlan.pushDownTopN(topN)
}
// The LogicalJoin may be also a LogicalApply. So we must use self to set parents.
if topN != nil {
return topN.setChild(p.self, true)
}
return p.self
}
|
yangwenmai/tidb
|
plan/topn_push_down.go
|
GO
|
apache-2.0
| 4,505
|
# Voyria primuloides Baker SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Gentianales/Gentianaceae/Voyria/Voyria primuloides/README.md
|
Markdown
|
apache-2.0
| 174
|
CREATE PROCEDURE rb_GetModulesInRecycler
(
@PortalID int,
@SortField VarChar(50)
)
AS
SELECT
rb_Recycler.DateDeleted,
rb_Recycler.DeletedBy,
rb_Recycler.OriginalTab,
rb_Recycler.ModuleID,
rb_Modules.ModuleTitle,
rb_Pages.PageName as 'OriginalPageName'
FROM rb_Recycler INNER JOIN
rb_Modules ON rb_Recycler.ModuleID = rb_Modules.ModuleID INNER JOIN
rb_Pages ON rb_Recycler.OriginalTab = rb_Pages.PageID
WHERE PortalID = @PortalID
ORDER BY
CASE
WHEN @SortField = 'DateDeleted' THEN CAST(DateDeleted AS VarChar(50))
WHEN @SortField = 'DeletedBy' THEN CAST(DeletedBy AS VarChar(50))
WHEN @SortField = 'OriginalTab' THEN CAST(OriginalTab AS VarChar(50))
WHEN @SortField = 'ModuleID' THEN CAST(rb_Recycler.ModuleID AS VarChar(50))
WHEN @SortField = 'ModuleTitle' THEN CAST(ModuleTitle AS VarChar(50))
WHEN @SortField = 'PageName' THEN CAST(rb_Pages.PageName AS VarChar(50))
ELSE ModuleTitle
END
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE rb_GetAuthViewRolesRecycler
(
@PortalID int,
@ModuleID int,
@AccessRoles nvarchar (256) OUTPUT,
@ViewRoles nvarchar (256) OUTPUT
)
AS
SELECT
@AccessRoles = rb_Pages.AuthorizedRoles,
@ViewRoles = rb_Modules.AuthorizedViewRoles
FROM
rb_Modules
INNER JOIN
rb_Recycler ON rb_Modules.ModuleID = rb_Recycler.ModuleID
INNER join
rb_Pages ON rb_Recycler.OriginalTab = rb_Pages.PageID
WHERE
rb_Modules.ModuleID = @ModuleID
AND
rb_Pages.PortalID = @PortalID
GO
CREATE PROCEDURE rb_GetAuthDeleteRolesRecycler
(
@PortalID int,
@ModuleID int,
@AccessRoles nvarchar (256) OUTPUT,
@DeleteRoles nvarchar (256) OUTPUT
)
AS
SELECT
@AccessRoles = rb_Pages.AuthorizedRoles,
@DeleteRoles = rb_Modules.AuthorizedDeleteRoles
FROM
rb_Modules
INNER JOIN
rb_Recycler ON rb_Modules.ModuleID = rb_Recycler.ModuleID
INNER join
rb_Pages ON rb_Recycler.OriginalTab = rb_Pages.PageID
WHERE
rb_Modules.ModuleID = @ModuleID
AND
rb_Pages.PortalID = @PortalID
GO
|
Appleseed/portal
|
Master/Appleseed/WebSites/Appleseed/Setup/Scripts/2.0.0.1892.sql
|
SQL
|
apache-2.0
| 2,158
|
using System;
using System.Threading;
using System.Threading.Tasks;
using Lime.Protocol;
namespace Takenet.MessagingHub.Client.Listener
{
public class LambdaMessageReceiver : IMessageReceiver
{
private Func<Message, CancellationToken, Task> OnMessageReceived { get; }
public LambdaMessageReceiver(Func<Message, CancellationToken, Task> onMessageReceived)
{
if (onMessageReceived == null) throw new ArgumentNullException(nameof(onMessageReceived));
OnMessageReceived = onMessageReceived;
}
public Task ReceiveAsync(Message message, CancellationToken cancellationToken = default(CancellationToken))
{
return OnMessageReceived?.Invoke(message, cancellationToken);
}
}
}
|
takenet/messaginghub-client-csharp
|
src/Takenet.MessagingHub.Client/Listener/LambdaMessageReceiver.cs
|
C#
|
apache-2.0
| 773
|
/*
* 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.
*
* =========================================================================================================
*
* This software consists of voluntary contributions made by many individuals on behalf of the
* Apache Software Foundation. For more information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
* +-------------------------------------------------------------------------------------------------------+
* | License: http://www.apache.org/licenses/LICENSE-2.0.txt |
* | Author: Yong.Teng <webmaster@buession.com> |
* | Copyright @ 2013-2018 Buession.com Inc. |
* +-------------------------------------------------------------------------------------------------------+
*/
package com.buession.core;
/**
* @author Yong.Teng
*/
public class Geo {
private double longitude;
private double latitude;
public Geo(){
}
public Geo(double longitude, double latitude){
this.longitude = longitude;
this.latitude = latitude;
}
public double getLongitude(){
return longitude;
}
public void setLongitude(double longitude){
this.longitude = longitude;
}
public double getLatitude(){
return latitude;
}
public void setLatitude(double latitude){
this.latitude = latitude;
}
@Override
public boolean equals(Object object){
if(object == null || object instanceof Geo){
return false;
}
Geo that = (Geo) object;
return that.getLongitude() == longitude && that.getLatitude() == latitude;
}
@Override
public String toString(){
return "Geo{" + "longitude=" + longitude + ", latitude=" + latitude + '}';
}
}
|
eduosi/buessionframework
|
buession-core/src/main/java/com/buession/core/Geo.java
|
Java
|
apache-2.0
| 2,558
|
---
layout: post
title: "数位 DP 问题"
subtitle: "走在 OJ 的路上"
date: 2016-11-17
author: "sabertazimi"
header-img: "img/home-bg.jpg"
tags:
- Algorithm
- OJ
- ACM
- C++
---
在刷 CCF 的真题中遇到了一道数位 DP 问题(201312-4), 于是对数位 DP 问题进行了一番学习, 现将学习笔记记录于下:
## 题目模式
* 给定区间 [a, b], 求满足特定要求的数, 要求一般与大小无关, 与数位的组成相关
* 规模巨大, 无法枚举
> 递增数: 1234, 2579; 双峰数: 19280, 26193; 含49: 49, 149, 1492; 整除13: 26, 39 ...
## 解题模式
f(a, b) = f(b, 0) - f(a - 1, 0)
暴力 + 存储 = 记忆化搜索:
* 暴力枚举每一位的 (0, ...,9)
* 利用 dp[pos][state] 与 dfs(pos, state, k, flag) 进行存储
```cpp
/// \brief 数字处理函数
/// \param num 原始数据
/// \param digit 保存每个数位的值
/// \param state 初始状态
int f(int num){
int ans;
int pos = 0;
while(num){
digit[++pos]=num%10;
num=num/10;
}
return dfs( pos, state , true);
}
/// \brief dfs 函数, 从高位开始遍历
/// \param f 记忆化数组
/// \param pos 当前数位下标
/// \param state 之前数字的状态
/// \param flag 上限标志
int dfs(int pos, int state, bool flag) {
if (pos == -1) {
return state == target_state;
}
if (!exception && ~f[pos][state]) {
return f[pos][state]
}
int ans = 0;
// 对于每一个数位, 求出枚举界限
// 一般从 0 枚举至 9, 当到达特殊位置时, 枚举上限可能改变
int next = exception ? digit[i] : 9;
for (int digit = 0; digit <= next; digit++) {
ans += dfs(pos - 1, new_state(state, digit), exception && digit == next);
}
return flag ? ans : f[pos][state] = ans;
}
```
```cpp
typedef long long ll;
int a[20];
ll dp[20][state]; //不同题目状态不同
ll dfs(int pos, int state, bool lead, bool limit) {
// 递归边界, 按位枚举最低位是0, pos == -1 表示枚举结束
if (pos == -1) {
// 若可以保证每一位都合法, 则 return 1; 否则 return 0
return 1;
}
// 记忆化
if (!limit && !lead && dp[pos][state] != -1) {
return dp[pos][state];
}
// 根据 limit 判断枚举的上界 up
int up = limit ? a[pos] : 9;
// 开始计数
ll ans=0;
// 枚举: 把不同情况的个数加到ans
for(int i = 0;i <= up; i++)
{
// 当前数位枚举的数是i,根据题目的约束条件分类讨论
// 计算不同情况下的个数, 根据 state 变量来保证 i 的合法性
// 一定要保证枚举数的合法性
// 比如要求数位上不能有 62 连续出现, 那么state 就要保存前一位 pre
// 前一位如果是 6 那么位不能是 2
// 当不合法时, 直接 continue
if() ...
else if()...
ans += dfs(pos-1, new_state(pos, state) /*状态转移*/, lead && i==0, limit && i == a[pos])
}
// 计算结束, 记录状态
if (!limit && !lead) {
dp[pos][state] = ans;
}
return ans;
}
ll solve(ll x) {
int pos=0;
// 数位分解
while(x) {
a[pos++] = x % 10;
x /= 10;
}
// 从最高位开始枚举
// 最高位前导为 0, 且受上限限制(无法枚举至 9)
return dfs(pos-1, state /*一系列状态 */, true, true);
}
int main(void) {
ll le,ri;
while (~scanf("%lld %lld", &le, &ri)) {
// 初始化dp数组为-1
printf("%lld\n", solve(ri)-solve(le-1));
}
return 0;
}
```
|
sabertazimi/sabertazimi.github.io
|
_posts/2016-11-17-数位DP问题.markdown
|
Markdown
|
apache-2.0
| 3,655
|
{{ partial "head.html" . }}
{{ partial "nav-front.html" . }}
<div class="page">
<div class="main">
<section>
{{ range $index, $element := (.Paginate .Site.Taxonomies.tags.featured.Pages).Pages }}
{{ $.Scratch.SetInMap "exclude" (string $index) .Title }}
{{ .Render "li" }}
{{ end }}
{{ partial "pagination.html" . }}
</section>
{{ partial "sidebar.html" . }}
</div>
</div>
{{ partial "foot.html" . }}
|
blackhole12/ponion
|
themes/ponion/layouts/index.html
|
HTML
|
apache-2.0
| 447
|
<?php
require 'functions.php';
licTest();
require 'settings.php';
include 'header.inc';
if ($mls_pass == $admin_password) {
print "<br><center><b>Update Item</b></center>\n";
if($uploads <= 1)
{
$uploads = 10;
}
$fields = $uploads + $uploads;
for($n = 0; $n < $uploads; $n++)
{
if($uploadedFile[$n] != "" && $uploadedFile[$n] != "none")
{
copy("$uploadedFile[$n]", "$path$uname/$uploadedFile_name[$n]");
if(file_exists("$path$fileName[$n]"))
{
//
}
else
{
print("error: upload failed<br>\n");
}
}
}
if ($uploadedFile_name[0] != "") {
$image1 = $uploadedFile_name[0];
}
if ($uploadedFile_name[1] != "") {
$image2 = $uploadedFile_name[1];
}
if ($uploadedFile_name[2] != "") {
$image3 = $uploadedFile_name[2];
}
if ($uploadedFile_name[3] != "") {
$image4 = $uploadedFile_name[3];
}
if ($uploadedFile_name[4] != "") {
$image5 = $uploadedFile_name[4];
}
if ($uploadedFile_name[5] != "") {
$image6 = $uploadedFile_name[5];
}
if ($uploadedFile_name[6] != "") {
$image7 = $uploadedFile_name[6];
}
if ($uploadedFile_name[7] != "") {
$image8 = $uploadedFile_name[7];
}
if ($uploadedFile_name[8] != "") {
$image9 = $uploadedFile_name[8];
}
if ($uploadedFile_name[9] != "") {
$image10 = $uploadedFile_name[9];
}
$linkID = @mysql_connect("$server", "$username", "$password");
mysql_select_db("$database", $linkID);
$result = mysql_query("UPDATE mls SET realtor_name = '$realtor_name', realtor_phone = '$realtor_phone',realtor_email = '$realtor_email',
title = '$title', short_description = '$short_description', detailed_description = '$detailed_description', price = '$price',
bedrooms = '$bedrooms', baths = '$baths', half_baths = '$half_baths', sqf = '$sqf', acres = '$acres', house_type = '$house_type',
image1 = '$image1', image2 = '$image2', image3 = '$image3', image4 = '$image4', image5 = '$image5',image6 = '$image6',
image7 = '$image7', image8 = '$image8', image9 = '$image9', image10 = '$image10', url = '$url', virtual_tour = '$virtual_tour',
map = '$map', property_address = '$property_address', property_city = '$property_city', property_state = '$property_state',
property_zip = '$property_zip', property_county = '$property_county', property_school_zone = '$property_school_zone',
feature1 = '$feature1', feature2 = '$feature2', feature3 = '$feature3' , feature4 = '$feature4' , feature5 = '$feature5',
feature6 = '$feature6' , feature7 = '$feature7' , feature8 = '$feature8' , feature9 = '$feature9' , feature10 = '$feature10',
feature11 = '$feature11', feature12 = '$feature12' , feature13 = '$feature13' , feature14 = '$feature14',
feature15 = '$feature15' , feature16 = '$feature16' , feature17 = '$feature17' , feature18 = '$feature18' ,
feature19 = '$feature19' , feature20 = '$feature20' , feature21 = '$feature21' , feature22 = '$feature22' ,
feature23 = '$feature23' , feature24 = '$feature24' , feature25 = '$feature25' , feature26 = '$feature26' ,
feature27 = '$feature27' , feature28 = '$feature28' , feature29 = '$feature29' , feature30 = '$feature30' ,
feature31 = '$feature31' , feature32 = '$feature32' , feature33 = '$feature33' , feature34 = '$feature34' ,
feature35 = '$feature35' , feature36 = '$feature36' , feature37 = '$feature37' , feature38 = '$feature38' ,
feature39 = '$feature39' , feature40 = '$feature40'
WHERE mls = '$mls'" , $linkID);
if ($result == TRUE) {
print "<br><br><b><center>MLS number $mls was updated.</center></b><br><br></center>\n";
print "<center><a href=admin.php>Home</a></center><br>\n";
} else {
print "<center><font color=red><b>The server was unable to write to the MySQL DataBase.<br><br></b></font></center>\n";
}
} else {
print "<center><h2>MLS Lister Administrator Login</h2></center><br><br>\n";
print "
<form action=admin.php method=post>
<div align=center><table border=1 width=600>
<tr><td>Administration Password:</td><td><input type=password name=pass></td></tr>
</table></div>
<center><input type=submit value=Login></center>
<br><br>
\n";
}
include 'footer.inc';
?>
|
drlouie/public-views
|
_client-workareas/MARK-STRATEGY/mlsopen/admin_edit3.php
|
PHP
|
apache-2.0
| 4,059
|
# Hibiscus jatrophifolius A.Rich. SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Malvales/Malvaceae/Hibiscus/Hibiscus jatrophifolius/README.md
|
Markdown
|
apache-2.0
| 181
|
/*
* 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.cassandra.service;
import java.io.DataInput;
import java.io.IOException;
import java.net.InetAddress;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.*;
import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.cassandra.concurrent.ScheduledExecutors;
import org.apache.cassandra.concurrent.Stage;
import org.apache.cassandra.concurrent.StageManager;
import org.apache.cassandra.config.CFMetaData;
import org.apache.cassandra.config.KSMetaData;
import org.apache.cassandra.config.Schema;
import org.apache.cassandra.cql3.functions.UDAggregate;
import org.apache.cassandra.cql3.functions.UDFunction;
import org.apache.cassandra.db.*;
import org.apache.cassandra.db.marshal.UserType;
import org.apache.cassandra.exceptions.AlreadyExistsException;
import org.apache.cassandra.exceptions.ConfigurationException;
import org.apache.cassandra.gms.*;
import org.apache.cassandra.io.IVersionedSerializer;
import org.apache.cassandra.io.util.DataOutputPlus;
import org.apache.cassandra.net.MessageOut;
import org.apache.cassandra.net.MessagingService;
import org.apache.cassandra.schema.LegacySchemaTables;
import org.apache.cassandra.utils.FBUtilities;
import org.apache.cassandra.utils.WrappedRunnable;
public class MigrationManager
{
private static final Logger logger = LoggerFactory.getLogger(MigrationManager.class);
public static final MigrationManager instance = new MigrationManager();
private static final RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
public static final int MIGRATION_DELAY_IN_MS = 60000;
private final List<MigrationListener> listeners = new CopyOnWriteArrayList<>();
private MigrationManager() {}
public void register(MigrationListener listener)
{
listeners.add(listener);
}
public void unregister(MigrationListener listener)
{
listeners.remove(listener);
}
public void scheduleSchemaPull(InetAddress endpoint, EndpointState state)
{
VersionedValue value = state.getApplicationState(ApplicationState.SCHEMA);
if (!endpoint.equals(FBUtilities.getBroadcastAddress()) && value != null)
maybeScheduleSchemaPull(UUID.fromString(value.value), endpoint);
}
/**
* If versions differ this node sends request with local migration list to the endpoint
* and expecting to receive a list of migrations to apply locally.
*/
private static void maybeScheduleSchemaPull(final UUID theirVersion, final InetAddress endpoint)
{
if ((Schema.instance.getVersion() != null && Schema.instance.getVersion().equals(theirVersion)) || !shouldPullSchemaFrom(endpoint))
{
logger.debug("Not pulling schema because versions match or shouldPullSchemaFrom returned false");
return;
}
if (Schema.emptyVersion.equals(Schema.instance.getVersion()) || runtimeMXBean.getUptime() < MIGRATION_DELAY_IN_MS)
{
// If we think we may be bootstrapping or have recently started, submit MigrationTask immediately
logger.debug("Submitting migration task for {}", endpoint);
submitMigrationTask(endpoint);
}
else
{
// Include a delay to make sure we have a chance to apply any changes being
// pushed out simultaneously. See CASSANDRA-5025
Runnable runnable = new Runnable()
{
public void run()
{
// grab the latest version of the schema since it may have changed again since the initial scheduling
EndpointState epState = Gossiper.instance.getEndpointStateForEndpoint(endpoint);
if (epState == null)
{
logger.debug("epState vanished for {}, not submitting migration task", endpoint);
return;
}
VersionedValue value = epState.getApplicationState(ApplicationState.SCHEMA);
UUID currentVersion = UUID.fromString(value.value);
if (Schema.instance.getVersion().equals(currentVersion))
{
logger.debug("not submitting migration task for {} because our versions match", endpoint);
return;
}
logger.debug("submitting migration task for {}", endpoint);
submitMigrationTask(endpoint);
}
};
ScheduledExecutors.optionalTasks.schedule(runnable, MIGRATION_DELAY_IN_MS, TimeUnit.MILLISECONDS);
}
}
private static Future<?> submitMigrationTask(InetAddress endpoint)
{
/*
* Do not de-ref the future because that causes distributed deadlock (CASSANDRA-3832) because we are
* running in the gossip stage.
*/
return StageManager.getStage(Stage.MIGRATION).submit(new MigrationTask(endpoint));
}
public static boolean shouldPullSchemaFrom(InetAddress endpoint)
{
/*
* Don't request schema from nodes with a differnt or unknonw major version (may have incompatible schema)
* Don't request schema from fat clients
*/
return MessagingService.instance().knowsVersion(endpoint)
&& MessagingService.instance().getRawVersion(endpoint) == MessagingService.current_version
&& !Gossiper.instance.isGossipOnlyMember(endpoint);
}
public static boolean isReadyForBootstrap()
{
return ((ThreadPoolExecutor) StageManager.getStage(Stage.MIGRATION)).getActiveCount() == 0;
}
public void notifyCreateKeyspace(KSMetaData ksm)
{
for (MigrationListener listener : listeners)
listener.onCreateKeyspace(ksm.name);
}
public void notifyCreateColumnFamily(CFMetaData cfm)
{
for (MigrationListener listener : listeners)
listener.onCreateColumnFamily(cfm.ksName, cfm.cfName);
}
public void notifyCreateUserType(UserType ut)
{
for (MigrationListener listener : listeners)
listener.onCreateUserType(ut.keyspace, ut.getNameAsString());
}
public void notifyCreateFunction(UDFunction udf)
{
for (MigrationListener listener : listeners)
listener.onCreateFunction(udf.name().keyspace, udf.name().name, udf.argTypes());
}
public void notifyCreateAggregate(UDAggregate udf)
{
for (MigrationListener listener : listeners)
listener.onCreateAggregate(udf.name().keyspace, udf.name().name, udf.argTypes());
}
public void notifyUpdateKeyspace(KSMetaData ksm)
{
for (MigrationListener listener : listeners)
listener.onUpdateKeyspace(ksm.name);
}
public void notifyUpdateColumnFamily(CFMetaData cfm, boolean columnsDidChange)
{
for (MigrationListener listener : listeners)
listener.onUpdateColumnFamily(cfm.ksName, cfm.cfName, columnsDidChange);
}
public void notifyUpdateUserType(UserType ut)
{
for (MigrationListener listener : listeners)
listener.onUpdateUserType(ut.keyspace, ut.getNameAsString());
// FIXME: remove when we get rid of AbstractType in metadata. Doesn't really belong anywhere.
Schema.instance.getKSMetaData(ut.keyspace).functions.udfs().forEach(f -> f.userTypeUpdated(ut.keyspace, ut.getNameAsString()));
}
public void notifyUpdateFunction(UDFunction udf)
{
for (MigrationListener listener : listeners)
listener.onUpdateFunction(udf.name().keyspace, udf.name().name, udf.argTypes());
}
public void notifyUpdateAggregate(UDAggregate udf)
{
for (MigrationListener listener : listeners)
listener.onUpdateAggregate(udf.name().keyspace, udf.name().name, udf.argTypes());
}
public void notifyDropKeyspace(KSMetaData ksm)
{
for (MigrationListener listener : listeners)
listener.onDropKeyspace(ksm.name);
}
public void notifyDropColumnFamily(CFMetaData cfm)
{
for (MigrationListener listener : listeners)
listener.onDropColumnFamily(cfm.ksName, cfm.cfName);
}
public void notifyDropUserType(UserType ut)
{
for (MigrationListener listener : listeners)
listener.onDropUserType(ut.keyspace, ut.getNameAsString());
}
public void notifyDropFunction(UDFunction udf)
{
for (MigrationListener listener : listeners)
listener.onDropFunction(udf.name().keyspace, udf.name().name, udf.argTypes());
}
public void notifyDropAggregate(UDAggregate udf)
{
for (MigrationListener listener : listeners)
listener.onDropAggregate(udf.name().keyspace, udf.name().name, udf.argTypes());
}
public static void announceNewKeyspace(KSMetaData ksm) throws ConfigurationException
{
announceNewKeyspace(ksm, false);
}
public static void announceNewKeyspace(KSMetaData ksm, boolean announceLocally) throws ConfigurationException
{
announceNewKeyspace(ksm, FBUtilities.timestampMicros(), announceLocally);
}
public static void announceNewKeyspace(KSMetaData ksm, long timestamp, boolean announceLocally) throws ConfigurationException
{
ksm.validate();
if (Schema.instance.getKSMetaData(ksm.name) != null)
throw new AlreadyExistsException(ksm.name);
logger.info(String.format("Create new Keyspace: %s", ksm));
announce(LegacySchemaTables.makeCreateKeyspaceMutation(ksm, timestamp), announceLocally);
}
public static void announceNewColumnFamily(CFMetaData cfm) throws ConfigurationException
{
announceNewColumnFamily(cfm, false);
}
public static void announceNewColumnFamily(CFMetaData cfm, boolean announceLocally) throws ConfigurationException
{
cfm.validate();
KSMetaData ksm = Schema.instance.getKSMetaData(cfm.ksName);
if (ksm == null)
throw new ConfigurationException(String.format("Cannot add table '%s' to non existing keyspace '%s'.", cfm.cfName, cfm.ksName));
else if (ksm.tables.get(cfm.cfName).isPresent())
throw new AlreadyExistsException(cfm.ksName, cfm.cfName);
logger.info(String.format("Create new table: %s", cfm));
announce(LegacySchemaTables.makeCreateTableMutation(ksm, cfm, FBUtilities.timestampMicros()), announceLocally);
}
public static void announceNewType(UserType newType, boolean announceLocally)
{
KSMetaData ksm = Schema.instance.getKSMetaData(newType.keyspace);
announce(LegacySchemaTables.makeCreateTypeMutation(ksm, newType, FBUtilities.timestampMicros()), announceLocally);
}
public static void announceNewFunction(UDFunction udf, boolean announceLocally)
{
logger.info(String.format("Create scalar function '%s'", udf.name()));
KSMetaData ksm = Schema.instance.getKSMetaData(udf.name().keyspace);
announce(LegacySchemaTables.makeCreateFunctionMutation(ksm, udf, FBUtilities.timestampMicros()), announceLocally);
}
public static void announceNewAggregate(UDAggregate udf, boolean announceLocally)
{
logger.info(String.format("Create aggregate function '%s'", udf.name()));
KSMetaData ksm = Schema.instance.getKSMetaData(udf.name().keyspace);
announce(LegacySchemaTables.makeCreateAggregateMutation(ksm, udf, FBUtilities.timestampMicros()), announceLocally);
}
public static void announceKeyspaceUpdate(KSMetaData ksm) throws ConfigurationException
{
announceKeyspaceUpdate(ksm, false);
}
public static void announceKeyspaceUpdate(KSMetaData ksm, boolean announceLocally) throws ConfigurationException
{
ksm.validate();
KSMetaData oldKsm = Schema.instance.getKSMetaData(ksm.name);
if (oldKsm == null)
throw new ConfigurationException(String.format("Cannot update non existing keyspace '%s'.", ksm.name));
logger.info(String.format("Update Keyspace '%s' From %s To %s", ksm.name, oldKsm, ksm));
announce(LegacySchemaTables.makeCreateKeyspaceMutation(ksm, FBUtilities.timestampMicros(), false), announceLocally);
}
public static void announceColumnFamilyUpdate(CFMetaData cfm, boolean fromThrift) throws ConfigurationException
{
announceColumnFamilyUpdate(cfm, fromThrift, false);
}
public static void announceColumnFamilyUpdate(CFMetaData cfm, boolean fromThrift, boolean announceLocally) throws ConfigurationException
{
cfm.validate();
CFMetaData oldCfm = Schema.instance.getCFMetaData(cfm.ksName, cfm.cfName);
if (oldCfm == null)
throw new ConfigurationException(String.format("Cannot update non existing table '%s' in keyspace '%s'.", cfm.cfName, cfm.ksName));
KSMetaData ksm = Schema.instance.getKSMetaData(cfm.ksName);
oldCfm.validateCompatility(cfm);
logger.info(String.format("Update table '%s/%s' From %s To %s", cfm.ksName, cfm.cfName, oldCfm, cfm));
announce(LegacySchemaTables.makeUpdateTableMutation(ksm, oldCfm, cfm, FBUtilities.timestampMicros(), fromThrift), announceLocally);
}
public static void announceTypeUpdate(UserType updatedType, boolean announceLocally)
{
announceNewType(updatedType, announceLocally);
}
public static void announceKeyspaceDrop(String ksName) throws ConfigurationException
{
announceKeyspaceDrop(ksName, false);
}
public static void announceKeyspaceDrop(String ksName, boolean announceLocally) throws ConfigurationException
{
KSMetaData oldKsm = Schema.instance.getKSMetaData(ksName);
if (oldKsm == null)
throw new ConfigurationException(String.format("Cannot drop non existing keyspace '%s'.", ksName));
logger.info(String.format("Drop Keyspace '%s'", oldKsm.name));
announce(LegacySchemaTables.makeDropKeyspaceMutation(oldKsm, FBUtilities.timestampMicros()), announceLocally);
}
public static void announceColumnFamilyDrop(String ksName, String cfName) throws ConfigurationException
{
announceColumnFamilyDrop(ksName, cfName, false);
}
public static void announceColumnFamilyDrop(String ksName, String cfName, boolean announceLocally) throws ConfigurationException
{
CFMetaData oldCfm = Schema.instance.getCFMetaData(ksName, cfName);
if (oldCfm == null)
throw new ConfigurationException(String.format("Cannot drop non existing table '%s' in keyspace '%s'.", cfName, ksName));
KSMetaData ksm = Schema.instance.getKSMetaData(ksName);
logger.info(String.format("Drop table '%s/%s'", oldCfm.ksName, oldCfm.cfName));
announce(LegacySchemaTables.makeDropTableMutation(ksm, oldCfm, FBUtilities.timestampMicros()), announceLocally);
}
public static void announceTypeDrop(UserType droppedType)
{
announceTypeDrop(droppedType, false);
}
public static void announceTypeDrop(UserType droppedType, boolean announceLocally)
{
KSMetaData ksm = Schema.instance.getKSMetaData(droppedType.keyspace);
announce(LegacySchemaTables.dropTypeFromSchemaMutation(ksm, droppedType, FBUtilities.timestampMicros()), announceLocally);
}
public static void announceFunctionDrop(UDFunction udf, boolean announceLocally)
{
logger.info(String.format("Drop scalar function overload '%s' args '%s'", udf.name(), udf.argTypes()));
KSMetaData ksm = Schema.instance.getKSMetaData(udf.name().keyspace);
announce(LegacySchemaTables.makeDropFunctionMutation(ksm, udf, FBUtilities.timestampMicros()), announceLocally);
}
public static void announceAggregateDrop(UDAggregate udf, boolean announceLocally)
{
logger.info(String.format("Drop aggregate function overload '%s' args '%s'", udf.name(), udf.argTypes()));
KSMetaData ksm = Schema.instance.getKSMetaData(udf.name().keyspace);
announce(LegacySchemaTables.makeDropAggregateMutation(ksm, udf, FBUtilities.timestampMicros()), announceLocally);
}
/**
* actively announce a new version to active hosts via rpc
* @param schema The schema mutation to be applied
*/
private static void announce(Mutation schema, boolean announceLocally)
{
if (announceLocally)
{
try
{
LegacySchemaTables.mergeSchema(Collections.singletonList(schema), false);
}
catch (IOException e)
{
throw new RuntimeException(e);
}
}
else
{
FBUtilities.waitOnFuture(announce(Collections.singletonList(schema)));
}
}
private static void pushSchemaMutation(InetAddress endpoint, Collection<Mutation> schema)
{
MessageOut<Collection<Mutation>> msg = new MessageOut<>(MessagingService.Verb.DEFINITIONS_UPDATE,
schema,
MigrationsSerializer.instance);
MessagingService.instance().sendOneWay(msg, endpoint);
}
// Returns a future on the local application of the schema
private static Future<?> announce(final Collection<Mutation> schema)
{
Future<?> f = StageManager.getStage(Stage.MIGRATION).submit(new WrappedRunnable()
{
protected void runMayThrow() throws IOException, ConfigurationException
{
LegacySchemaTables.mergeSchema(schema);
}
});
for (InetAddress endpoint : Gossiper.instance.getLiveMembers())
{
// only push schema to nodes with known and equal versions
if (!endpoint.equals(FBUtilities.getBroadcastAddress()) &&
MessagingService.instance().knowsVersion(endpoint) &&
MessagingService.instance().getRawVersion(endpoint) == MessagingService.current_version)
pushSchemaMutation(endpoint, schema);
}
return f;
}
/**
* Announce my version passively over gossip.
* Used to notify nodes as they arrive in the cluster.
*
* @param version The schema version to announce
*/
public static void passiveAnnounce(UUID version)
{
Gossiper.instance.addLocalApplicationState(ApplicationState.SCHEMA, StorageService.instance.valueFactory.schema(version));
logger.debug("Gossiping my schema version {}", version);
}
/**
* Clear all locally stored schema information and reset schema to initial state.
* Called by user (via JMX) who wants to get rid of schema disagreement.
*
* @throws IOException if schema tables truncation fails
*/
public static void resetLocalSchema() throws IOException
{
logger.info("Starting local schema reset...");
logger.debug("Truncating schema tables...");
LegacySchemaTables.truncateSchemaTables();
logger.debug("Clearing local schema keyspace definitions...");
Schema.instance.clear();
Set<InetAddress> liveEndpoints = Gossiper.instance.getLiveMembers();
liveEndpoints.remove(FBUtilities.getBroadcastAddress());
// force migration if there are nodes around
for (InetAddress node : liveEndpoints)
{
if (shouldPullSchemaFrom(node))
{
logger.debug("Requesting schema from {}", node);
FBUtilities.waitOnFuture(submitMigrationTask(node));
break;
}
}
logger.info("Local schema reset is complete.");
}
public static class MigrationsSerializer implements IVersionedSerializer<Collection<Mutation>>
{
public static MigrationsSerializer instance = new MigrationsSerializer();
public void serialize(Collection<Mutation> schema, DataOutputPlus out, int version) throws IOException
{
out.writeInt(schema.size());
for (Mutation mutation : schema)
Mutation.serializer.serialize(mutation, out, version);
}
public Collection<Mutation> deserialize(DataInput in, int version) throws IOException
{
int count = in.readInt();
Collection<Mutation> schema = new ArrayList<>(count);
for (int i = 0; i < count; i++)
schema.add(Mutation.serializer.deserialize(in, version));
return schema;
}
public long serializedSize(Collection<Mutation> schema, int version)
{
int size = TypeSizes.NATIVE.sizeof(schema.size());
for (Mutation mutation : schema)
size += Mutation.serializer.serializedSize(mutation, version);
return size;
}
}
}
|
DICL/cassandra
|
src/java/org/apache/cassandra/service/MigrationManager.java
|
Java
|
apache-2.0
| 21,970
|
package junit.org.rapidpm.vaadin.jumpstart.charts.microservice.bootstrap.v001;
import java.util.Optional;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.core.Response;
import org.junit.Assert;
import org.junit.Test;
import org.rapidpm.microservice.Main;
import org.rapidpm.microservice.optionals.metrics.health.rest.SessionHealth;
import org.rapidpm.microservice.optionals.metrics.health.rest.api.SessionHealthInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.gson.Gson;
import junit.org.rapidpm.vaadin.jumpstart.charts.microservice.MicroserviceBaseTest;
/**
* Created by svenruppert on 04.04.17.
*/
public class StartupActionTest extends MicroserviceBaseTest {
private static final Logger LOGGER = LoggerFactory
.getLogger(StartupTestAction.class);
public static final String START_UP_ACTION = "StartUpAction";
@Test
public void test001()
throws Exception {
// Testrequest to see if MicroService is up and running
final String generateBasicReqURL = generateBasicReqURL(
SessionHealth.class);
Client client = ClientBuilder.newClient();
LOGGER.info("generateBasicReqURL = " + generateBasicReqURL);
final Invocation.Builder authcode = client.target(generateBasicReqURL)
.request();
String response = authcode.get(String.class);
Gson gson = new Gson();
SessionHealthInfo[] sessionHealthInfo = gson
.fromJson(response, SessionHealthInfo[].class);
Assert.assertEquals(0L, sessionHealthInfo[0].activeSessionCount);
client.close();
}
@Test
public void test002()
throws Exception {
final String basicReqURL = generateBasicReqURL(TestRessource.class);
final Response response = ClientBuilder.newClient().target(basicReqURL)
.request().get();
Assert.assertEquals(Response.Status.OK, response.getStatusInfo());
Assert.assertEquals(StartupTestAction.class.getSimpleName(),
response.readEntity(String.class));
}
@Path("/OverviewTest")
public static class TestRessource {
@GET()
public String doWork() {
return System.getProperty(START_UP_ACTION);
}
}
public static class StartupTestAction implements Main.MainStartupAction {
private static final Logger LOGGER = LoggerFactory
.getLogger(StartupTestAction.class);
@Override
public void execute(Optional<String[]> args) {
// Start here the MicroService bootstraping stuff
LOGGER.debug("Started with MicroService bootstrapping");
System
.setProperty(START_UP_ACTION, this.getClass().getSimpleName());
LOGGER.debug("Stopped with MicroService bootstrapping");
}
}
}
|
Java-Publications/vaadin-001-charts-jumpstart
|
modules/microservice/src/test/java/junit/org/rapidpm/vaadin/jumpstart/charts/microservice/bootstrap/v001/StartupActionTest.java
|
Java
|
apache-2.0
| 2,978
|
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link type="text/css" rel="stylesheet" href="style1.css"/>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap-theme.min.css">
<link href="http://netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
<script src="http://cameronspear.com/downloads/bootstrap-hover-dropdown/bootstrap-hover-dropdown.js"></script>
<script src="script1.js" type="text/javascript"></script>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<title>
DSS Home Page
</title>
</head>
<body>
<div class="container">
<nav class="navbar navbar-inverse navbar-fixed-top" >
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="#">Doctor Shift Scheduler</a>
</div>
<ul class="nav navbar-nav">
<li class="active"><a href="#"><span class="glyphicon glyphicon-home"> Home</span></a></li>
<li class="dropdown" id="dd">
<a class="dropdown-toggle" data-toggle="dropdown" href="#"><span class="glyphicon glyphicon-stats"></span> Statistics</a>
<ul class="dropdown-menu">
<li><a href="IndividualStats.html"> Individual Statistics </a></li>
<li><a href="groupstats.php"> Group Statistics </a></li>
</ul>
</li>
<li><a href="vacation.php"><span class="glyphicon glyphicon-plane"></span> Vacations </a></li>
<li><a href="addDoc.php"><span class="fa fa-user-md"></span> Doctors </a></li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li><a href="logout.html"><span class="glyphicon glyphicon-log-out"></span> Logout</a></li>
</ul>
</div>
</nav>
</div>
<div class="container">
<div class="jumbotron">
<h2>Doctor Shift Scheduler</h2>
</div>
<form name="form1" class="display" method="POST" action="adminhome2.php">
<div class="dropdown display">
<button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" name="dropdownMenu1" data-toggle="dropdown">
Select Term
<span id="MenuText" class="caret"> </span>
</button>
<ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu1" id="TermSelect">
<li role="presentation"><a role="menuitem" tabindex="-1" href="#">January - June</a></li>
<li role="presentation"><a role="menuitem" tabindex="-1" href="#">July - December</a></li>
</ul>
</div>
<div class="dropdown display">
<button class="btn btn-default dropdown-toggle" type="button" name="dropdownMenu2" id="dropdownMenu2" data-toggle="dropdown">
Select Month
<span id="MenuText" class="caret"> </span>
</button>
<ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu2" id="MonthSelect">
<?php
require("config.php");
$sql = "SELECT distinct(monthName) from calendar_table";
$result = mysql_query($sql);
while(!(empty($row = mysql_fetch_array($result))))
{
?>
<li role="presentation"><a role="menuitem" tabindex="-1" href="#" ><?php echo $row['monthName'] ?></a></li>
<?php } ?>
</ul>
</div>
<div class="dropdown display">
<button class="btn btn-default dropdown-toggle" type="button" name="dropdownMenu3" id="dropdownMenu3" data-toggle="dropdown">
Select Year
<span id="MenuText" class="caret"> </span>
</button>
<ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu3" id="YearSelect">
<?php require("config.php");
$sql = "SELECT distinct(y) from calendar_table";
$result = mysql_query($sql);
while(!(empty($row = mysql_fetch_array($result))))
{
?>
<li role="presentation"><a role="menuitem" tabindex="-1" href="#" ><?php echo $row['y'] ?></a></li>
<?php } ?>
</ul>
</div>
<input type="hidden" id="hidden" name="hidden" value="">
<input type="submit" id="submit" name="submit" value="submit" style="display:none;">
</form>
<br/>
<?php
require('config.php');
/* draws a calendar */
function draw_calendar($month,$year){
/* draw table */
$calendar = '<table cellpadding="0" cellspacing="0" class="calendar">';
$calendar.= '<col class="weekend">
<col class="weekday" span="5">
<col class="weekend">';
/* table headings */
$headings = array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday');
$calendar.= '<tr class="calendar-row"><td class="calendar-day-head">'.implode('</td><td class="calendar-day-head">',$headings).'</td></tr>';
/* days and weeks vars now ... */
$running_day = date('w',mktime(0,0,0,$month,1,$year));
$days_in_month = date('t',mktime(0,0,0,$month,1,$year));
$days_in_this_week = 1;
$day_counter = 0;
$dates_array = array();
$today=date("d");
$tomonth=date("m");
$toyear=date("y");
/* row for week one */
$calendar.= '<tr class="calendar-row">';
/* print "blank" days until the first of the current week */
for($x = 0; $x < $running_day; $x++):
$calendar.= '<td class="calendar-day-np"> </td>';
$days_in_this_week++;
endfor;
/* keep going with days.... */
for($list_day = 1; $list_day <= $days_in_month; $list_day++):
if($list_day==$today && $month==$tomonth && $year==$toyear)
{
$calendar.= '<td class="calendar-day" style="background: #ffffcc">';
}
else
{
$calendar.= '<td class="calendar-day">';
}
/* add in the day number */
$calendar.= '<div class="day-number">'.$list_day.'</div>';
$calendar.= '<div class="sc">SC: ';
$calendar.= '<a class="dropdown-toggle" data-toggle="dropdown">??? </a>
<div class="dropdown-menu">';
$sql2 = "SELECT initials from doctors where sc='YES'";
$r2 = mysql_query($sql2);
$i=1;
while($row2 = mysql_fetch_array($r2))
{
$calendar.=' <div><a class="t'.$i.'" href="#">';
$calendar.=$row2['initials'];
$calendar.='</a></div>';
$i = $i + 1;
}
$calendar.='</div><p id="value2" name="value2" value=""> </p> <form action="" METHOD="POST"><input type="hidden" name="hidden2" id="hidden2" value=""></form>';
$sql2 = "insert into schedule values ('','KA','$list_day','$month','$year','YES','NO')";
$r2 = mysql_query($sql2);
$calendar.='</div>';
$calendar.= '<div class="pc">PC: ';
$calendar.= '<a class="dropdown-toggle" data-toggle="dropdown">??? </a>
<div class="dropdown-menu">';
$sql3 = "SELECT initials from doctors where pc='YES'";
$r3 = mysql_query($sql3);
$i=1;
while($row3 = mysql_fetch_array($r3))
{
$calendar.=' <div><a class="t'.$i.'" href="#">';
$calendar.=$row3['initials'];
$calendar.='</a></div>';
$i = $i + 1;
}
$calendar.='</div><p id="value2" name="value2" value=""> </p> <form action="" METHOD="POST"><input type="hidden" name="hidden2" id="hidden2" value=""></form>';
$sql4 = "insert into schedule values ('','KA','$list_day','$month','$year','NO','YES')";
$r4 = mysql_query($sql4);
$calendar.='</div>';
/** QUERY THE DATABASE FOR AN ENTRY FOR THIS DAY !! IF MATCHES FOUND, PRINT THEM !! **/
$calendar.= '</td>';
if($running_day == 6):
$calendar.= '</tr>';
if(($day_counter+1) != $days_in_month):
$calendar.= '<tr class="calendar-row">';
endif;
$running_day = -1;
$days_in_this_week = 0;
endif;
$days_in_this_week++; $running_day++; $day_counter++;
endfor;
/* finish the rest of the days in the week */
if($days_in_this_week < 8):
for($x = 1; $x <= (8 - $days_in_this_week); $x++):
$calendar.= '<td class="calendar-day-np"> </td>';
endfor;
endif;
/* final row */
$calendar.= '</tr>';
/* end the table */
$calendar.= '</table> ';
/* all done, return result */
return $calendar;
}
echo draw_calendar(date("m"),date("y"));
?>
<br/>
<br/>
<form class="publish">
<div class="btn-group">
<button type="button" class="btn btn-default" id="pub"><span class="glyphicon glyphicon-print"></span> PUBLISH</button>
</div>
</form>
<br/>
<br/>
</div>
<nav class="navbar navbar-default navbar-bottom">
<div class="container-fluid">
<div>
<ul class="nav navbar-nav">
<li><a href="about.html">About</a></li>
<li><a href="contact.html">Contact</a></li>
</ul>
</div>
</div>
</nav>
</body>
</html>
|
kpcorda/CS-422-Doctor-Shift-Scheduler
|
Code/Alpha Release/adminhome.php
|
PHP
|
apache-2.0
| 9,527
|
# Contributing Guidelines
Welcome to Kubernetes. We are excited about the prospect of you joining our [community](https://github.com/kubernetes/community)! The Kubernetes community abides by the CNCF [code of conduct](code-of-conduct.md). Here is an excerpt:
_As contributors and maintainers of this project, and in the interest of fostering an open and welcoming community, we pledge to respect all people who contribute through reporting issues, posting feature requests, updating documentation, submitting pull requests or patches, and other activities._
## Getting Started
We have full documentation on how to get started contributing here:
- [Contributor License Agreement](https://git.k8s.io/community/CLA.md) Kubernetes projects require that you sign a Contributor License Agreement (CLA) before we can accept your pull requests
- [Kubernetes Contributor Guide](http://git.k8s.io/community/contributors/guide) - Main contributor documentation, or you can just jump directly to the [contributing section](http://git.k8s.io/community/contributors/guide#contributing)
- [Contributor Cheat Sheet](https://git.k8s.io/community/contributors/guide/contributor-cheatsheet.md) - Common resources for existing developers
## Mentorship
- [Mentoring Initiatives](https://git.k8s.io/community/mentoring) - We have a diverse set of mentorship programs available that are always looking for volunteers!
## Contact Information
- [Slack channel](https://kubernetes.slack.com/messages/sig-storage)
- [Mailing list](https://groups.google.com/forum/#!forum/kubernetes-sig-storage)
|
opensds/nbp
|
csi-plug-n-play/sidecars/soda-csi-provisioner/external-provisioner/CONTRIBUTING.md
|
Markdown
|
apache-2.0
| 1,577
|
<label>
<input type="radio" name="" value="">
</label>
|
hawtio/hawtio-integration
|
plugins/components/forms2/html/radio-group-member.html
|
HTML
|
apache-2.0
| 57
|
package com.puresoltechnologies.ductiledb.xo.impl.metadata;
import com.buschmais.xo.spi.datastore.DatastoreEntityMetadata;
import com.buschmais.xo.spi.metadata.method.IndexedPropertyMethodMetadata;
public class DuctileVertexMetadata implements DatastoreEntityMetadata<String> {
private final String discriminator;
private final IndexedPropertyMethodMetadata<?> indexedProperty;
public DuctileVertexMetadata(String discriminator,
IndexedPropertyMethodMetadata<?> indexedProperty) {
super();
this.discriminator = discriminator;
this.indexedProperty = indexedProperty;
}
@Override
public String getDiscriminator() {
return discriminator;
}
public IndexedPropertyMethodMetadata<?> getIndexedProperty() {
return indexedProperty;
}
}
|
PureSolTechnologies/DuctileDB
|
xo/src/main/java/com/puresoltechnologies/ductiledb/xo/impl/metadata/DuctileVertexMetadata.java
|
Java
|
apache-2.0
| 757
|
# AUTOGENERATED FILE
FROM balenalib/jetson-xavier-fedora:36-build
# http://bugs.python.org/issue19846
# > At the moment, setting "LANG=C" on a Linux system *fundamentally breaks Python 3*, and that's not OK.
ENV LANG C.UTF-8
RUN dnf install -y \
python3-pip \
python3-dbus \
&& dnf clean all
# install "virtualenv", since the vast majority of users of this image will want it
RUN pip3 install -U --no-cache-dir --ignore-installed pip setuptools \
&& pip3 install --no-cache-dir virtualenv
RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo $'As of January 1st, 2020, Python 2 was end-of-life, we will change the latest tag for Balenalib Python base image to Python 3.x and drop support for Python 2 soon. So after 1st July, 2020, all the balenalib Python latest tag will point to the latest Python 3 version and no changes, or fixes will be made to balenalib Python 2 base image. If you are using Python 2 for your application, please upgrade to Python 3 before 1st July.' > /.balena/messages/python-deprecation-warning
CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"]
RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/test-stack@python.sh" \
&& echo "Running test-stack@python" \
&& chmod +x test-stack@python.sh \
&& bash test-stack@python.sh \
&& rm -rf test-stack@python.sh
RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo $'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v8 \nOS: Fedora 36 \nVariant: build variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nPython v3.10.0, Pip v21.2.4, Setuptools v58.0.0 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info
RUN echo $'#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \
&& chmod +x /bin/sh-shim \
&& cp /bin/sh /bin/sh.real \
&& mv /bin/sh-shim /bin/sh
|
resin-io-library/base-images
|
balena-base-images/python/jetson-xavier/fedora/36/3.10.0/build/Dockerfile
|
Dockerfile
|
apache-2.0
| 2,441
|
---
layout: base
title: 'Statistics of Case in UD_Guajajara-TuDeT'
udver: '2'
---
## Treebank Statistics: UD_Guajajara-TuDeT: Features: `Case`
This feature is universal.
It occurs with 5 different values: `All`, `Dat`, `Loc`, `Tem`, `Tra`.
72 tokens (4%) have a non-empty value of `Case`.
20 types (5%) occur at least once with a non-empty value of `Case`.
14 lemmas (5%) occur at least once with a non-empty value of `Case`.
The feature is used with 3 part-of-speech tags: <tt><a href="gub_tudet-pos-ADP.html">ADP</a></tt> (63; 3% instances), <tt><a href="gub_tudet-pos-NOUN.html">NOUN</a></tt> (5; 0% instances), <tt><a href="gub_tudet-pos-PRON.html">PRON</a></tt> (4; 0% instances).
### `ADP`
63 <tt><a href="gub_tudet-pos-ADP.html">ADP</a></tt> tokens (23% of all `ADP` tokens) have a non-empty value of `Case`.
The most frequent other feature values with which `ADP` and `Case` co-occurred: <tt><a href="gub_tudet-feat-Rel.html">Rel</a></tt><tt>=EMPTY</tt> (44; 70%).
`ADP` tokens may have the following values of `Case`:
* `All` (10; 16% of non-empty `Case`): <em>pe</em>
* `Dat` (29; 46% of non-empty `Case`): <em>pe, izupe, newe, wanehe, uzeupe, wanuwi, hehe, ihewe, wanupe</em>
* `Loc` (24; 38% of non-empty `Case`): <em>pe, ihe, izuwi</em>
* `EMPTY` (208): <em>pe, rehe, rupi, romo, pa, pupe, izupe, mehe, wi, hehe</em>
<table>
<tr><th>Paradigm <i>pe</i></th><th><tt>Dat</tt></th><th><tt>Loc</tt></th><th><tt>All</tt></th></tr>
<tr><td><tt></tt></td><td><em>pe</em></td><td><em>pe</em></td><td><em>pe</em></td></tr>
</table>
### `NOUN`
5 <tt><a href="gub_tudet-pos-NOUN.html">NOUN</a></tt> tokens (1% of all `NOUN` tokens) have a non-empty value of `Case`.
The most frequent other feature values with which `NOUN` and `Case` co-occurred: <tt><a href="gub_tudet-feat-Rel.html">Rel</a></tt><tt>=EMPTY</tt> (3; 60%).
`NOUN` tokens may have the following values of `Case`:
* `Dat` (3; 60% of non-empty `Case`): <em>upe, aʔepehar, izupehar</em>
* `Tra` (2; 40% of non-empty `Case`): <em>xixigaturumu, xixirogaturumu</em>
* `EMPTY` (502): <em>maʔe, kaʔa, ko, awa, awaxi, ipira, ɨrɨhu, ʔɨ, hoko, kara</em>
### `PRON`
4 <tt><a href="gub_tudet-pos-PRON.html">PRON</a></tt> tokens (6% of all `PRON` tokens) have a non-empty value of `Case`.
The most frequent other feature values with which `PRON` and `Case` co-occurred: <tt><a href="gub_tudet-feat-Person.html">Person</a></tt><tt>=EMPTY</tt> (4; 100%), <tt><a href="gub_tudet-feat-PronType.html">PronType</a></tt><tt>=Dem</tt> (3; 75%).
`PRON` tokens may have the following values of `Case`:
* `Loc` (2; 50% of non-empty `Case`): <em>Aʔepe, parupi</em>
* `Tem` (2; 50% of non-empty `Case`): <em>aʔere</em>
* `EMPTY` (61): <em>aʔe, Maʔe, ihe, ne, Mon, Agwer, Mo, aipo, akwez, ere</em>
<table>
<tr><th>Paradigm <i>aʔe</i></th><th><tt>Loc</tt></th><th><tt>Tem</tt></th></tr>
<tr><td><tt></tt></td><td><em>Aʔepe</em></td><td><em>aʔere</em></td></tr>
</table>
|
UniversalDependencies/docs
|
treebanks/gub_tudet/gub_tudet-feat-Case.md
|
Markdown
|
apache-2.0
| 2,951
|
$packageName = 'dolphin'
$url = 'http://dl.dolphin-emu.org/builds/dolphin-master-5.0-3427-x64.7z'
$checksum = 'a8780e30b808db2951056e378998a6ea6e66cdc93ffcf1fdc7c84b3da66db806'
$checksumType = 'sha256'
$url64 = $url
$checksum64 = $checksum
$checksumType64 = $checksumType
$toolsDir = "$(Split-Path -parent $MyInvocation.MyCommand.Definition)"
Install-ChocolateyZipPackage -PackageName "$packageName" `
-Url "$url" `
-UnzipLocation "$toolsDir" `
-Url64bit "$url64" `
-Checksum "$checksum" `
-ChecksumType "$checksumType" `
-Checksum64 "$checksum64" `
-ChecksumType64 "$checksumType64"
|
dtgm/chocolatey-packages
|
automatic/_output/dolphin/5.0.3427/tools/chocolateyInstall.ps1
|
PowerShell
|
apache-2.0
| 790
|
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
var async_1 = require("../scheduler/async");
var isDate_1 = require("../util/isDate");
var Subscriber_1 = require("../Subscriber");
var TimeoutError_1 = require("../util/TimeoutError");
/**
*
* Errors if Observable does not emit a value in given time span.
*
* <span class="informal">Timeouts on Observable that doesn't emit values fast enough.</span>
*
* <img src="./img/timeout.png" width="100%">
*
* `timeout` operator accepts as an argument either a number or a Date.
*
* If number was provided, it returns an Observable that behaves like a source
* Observable, unless there is a period of time where there is no value emitted.
* So if you provide `100` as argument and first value comes after 50ms from
* the moment of subscription, this value will be simply re-emitted by the resulting
* Observable. If however after that 100ms passes without a second value being emitted,
* stream will end with an error and source Observable will be unsubscribed.
* These checks are performed throughout whole lifecycle of Observable - from the moment
* it was subscribed to, until it completes or errors itself. Thus every value must be
* emitted within specified period since previous value.
*
* If provided argument was Date, returned Observable behaves differently. It throws
* if Observable did not complete before provided Date. This means that periods between
* emission of particular values do not matter in this case. If Observable did not complete
* before provided Date, source Observable will be unsubscribed. Other than that, resulting
* stream behaves just as source Observable.
*
* `timeout` accepts also a Scheduler as a second parameter. It is used to schedule moment (or moments)
* when returned Observable will check if source stream emitted value or completed.
*
* @example <caption>Check if ticks are emitted within certain timespan</caption>
* const seconds = Rx.Observable.interval(1000);
*
* seconds.timeout(1100) // Let's use bigger timespan to be safe,
* // since `interval` might fire a bit later then scheduled.
* .subscribe(
* value => console.log(value), // Will emit numbers just as regular `interval` would.
* err => console.log(err) // Will never be called.
* );
*
* seconds.timeout(900).subscribe(
* value => console.log(value), // Will never be called.
* err => console.log(err) // Will emit error before even first value is emitted,
* // since it did not arrive within 900ms period.
* );
*
* @example <caption>Use Date to check if Observable completed</caption>
* const seconds = Rx.Observable.interval(1000);
*
* seconds.timeout(new Date("December 17, 2020 03:24:00"))
* .subscribe(
* value => console.log(value), // Will emit values as regular `interval` would
* // until December 17, 2020 at 03:24:00.
* err => console.log(err) // On December 17, 2020 at 03:24:00 it will emit an error,
* // since Observable did not complete by then.
* );
*
* @see {@link timeoutWith}
*
* @param {number|Date} due Number specifying period within which Observable must emit values
* or Date specifying before when Observable should complete
* @param {Scheduler} [scheduler] Scheduler controlling when timeout checks occur.
* @return {Observable<T>} Observable that mirrors behaviour of source, unless timeout checks fail.
* @method timeout
* @owner Observable
*/
function timeout(due, scheduler) {
if (scheduler === void 0) { scheduler = async_1.async; }
var absoluteTimeout = isDate_1.isDate(due);
var waitFor = absoluteTimeout ? (+due - scheduler.now()) : Math.abs(due);
return function (source) { return source.lift(new TimeoutOperator(waitFor, absoluteTimeout, scheduler, new TimeoutError_1.TimeoutError())); };
}
exports.timeout = timeout;
var TimeoutOperator = /** @class */ (function () {
function TimeoutOperator(waitFor, absoluteTimeout, scheduler, errorInstance) {
this.waitFor = waitFor;
this.absoluteTimeout = absoluteTimeout;
this.scheduler = scheduler;
this.errorInstance = errorInstance;
}
TimeoutOperator.prototype.call = function (subscriber, source) {
return source.subscribe(new TimeoutSubscriber(subscriber, this.absoluteTimeout, this.waitFor, this.scheduler, this.errorInstance));
};
return TimeoutOperator;
}());
/**
* We need this JSDoc comment for affecting ESDoc.
* @ignore
* @extends {Ignored}
*/
var TimeoutSubscriber = /** @class */ (function (_super) {
__extends(TimeoutSubscriber, _super);
function TimeoutSubscriber(destination, absoluteTimeout, waitFor, scheduler, errorInstance) {
var _this = _super.call(this, destination) || this;
_this.absoluteTimeout = absoluteTimeout;
_this.waitFor = waitFor;
_this.scheduler = scheduler;
_this.errorInstance = errorInstance;
_this.action = null;
_this.scheduleTimeout();
return _this;
}
TimeoutSubscriber.dispatchTimeout = function (subscriber) {
subscriber.error(subscriber.errorInstance);
};
TimeoutSubscriber.prototype.scheduleTimeout = function () {
var action = this.action;
if (action) {
// Recycle the action if we've already scheduled one. All the production
// Scheduler Actions mutate their state/delay time and return themeselves.
// VirtualActions are immutable, so they create and return a clone. In this
// case, we need to set the action reference to the most recent VirtualAction,
// to ensure that's the one we clone from next time.
this.action = action.schedule(this, this.waitFor);
}
else {
this.add(this.action = this.scheduler.schedule(TimeoutSubscriber.dispatchTimeout, this.waitFor, this));
}
};
TimeoutSubscriber.prototype._next = function (value) {
if (!this.absoluteTimeout) {
this.scheduleTimeout();
}
_super.prototype._next.call(this, value);
};
TimeoutSubscriber.prototype._unsubscribe = function () {
this.action = null;
this.scheduler = null;
this.errorInstance = null;
};
return TimeoutSubscriber;
}(Subscriber_1.Subscriber));
//# sourceMappingURL=timeout.js.map
|
HeH-Projects/team-agozzino
|
frontend/node_modules/rxjs/operators/timeout.js
|
JavaScript
|
apache-2.0
| 6,958
|
<?php
/**
* Created by PhpStorm.
* User: dom
* Date: 2/26/16
* Time: 11:22 AM
*/
require_once dirname(dirname(__DIR__)) . "/classes/autoload.php";
require_once dirname(dirname(__DIR__)) . "/lib/xsrf.php";
require_once("/etc/apache2/capstone-mysql/encrypted-config.php");
require_once(dirname(dirname(dirname(dirname(__DIR__)))) . "/vendor/autoload");
//verify the xsrf challenge
if(session_status() !== PHP_SESSION_ACTIVE) {
session_start();
}
// prepare an empty reply
$reply = new stdClass();
$reply->status = 200;
$reply->data = null;
try {
// grab the MySQL connection
$pdo = connectToEncryptedMySQL("/etc/apache2/capstone-mysql/sprots.ini");
//determine which HTTP method was used
$method = array_key_exists("HTTP_X_HTTP_METHOD", $_SERVER) ? $_SERVER["HTTP_X_HTTP_METHOD"] : $SERVER["REQUEST_METHOD"];
//sanitize inputs
$id = filter_input(INPUT_GET, "id", FILTER_VALIDATE_INT);
//make sure the id is valid for methods that require it
if(($method === "DELETE" || $method === "PUT") && (empty($id) === true || $id < 0)) {
throw(new InvalidArgumentException("id can not be empty or negative", 405));
}
//sanitize and trim other fields
$favoriteTeamProfileId= filter_input(INPUT_GET, "profileId", FILTER_VALIDATE_INT);
$favoriteTeamTeamId= filter_input(INPUT_GET, "teamId", FILTER_VALIDATE_INT);
//get the team based on the given field
if(empty($id) === false) {
$favoriteTeam = FavoriteTeam::getFavoriteTeamByFavoriteTeamProfileIdAndFavoriteTeamTeamId($pdo, $id);
$reply->data = $favoriteTeam;
} elseif(empty($favoriteTeamTeamId) === false) {
$favoriteTeam = FavoriteTeam::getFavoriteTeamsByFavoriteTeamProfileId($pdo, $teamId);
$reply->date = $favoriteTeam;
}
} catch(Exception $exception) {
$reply->status = $exception->getCode();
$reply->message = $exception->getMessage();
} catch(TypeError $typeError) {
$reply->status = $typeError->getCode();
$reply->message = $typeError->getMessage();
}
header("Content-type: application/json");
if($reply->data === null) {
unset($reply->data);
}
echo json_encode($reply);
?>
|
chrispaul3625/sprots
|
public_html/php/api/FavoriteTeam/index.php
|
PHP
|
apache-2.0
| 2,075
|
#sidebar {
float: left;
overflow: hidden;
margin-right: 20px;
}
#appImage {
width: 300px;
}
#right_content {
line-height:1.8em;
}
|
sihrc/HFID-website
|
assets/css/index.css
|
CSS
|
apache-2.0
| 136
|
package org.mcavallo.opencloud.filters;
import org.mcavallo.opencloud.Tag;
/**
* Filters tags with length not contained between a minimum and a maximum value
*/
public class LengthFilter extends TagFilter {
private static final long serialVersionUID = 1L;
private int minLength = 0;
private int maxLength = Integer.MAX_VALUE;
public LengthFilter(int minLength, int maxLength) {
setMinLength(minLength);
setMaxLength(maxLength);
}
@Override
public boolean accept(Tag tag) {
if (tag == null || tag.getName() == null)
return false;
if (tag.getName().length() < getMinLength() || tag.getName().length() > getMaxLength())
return false;
else
return true;
}
public int getMinLength() {
return minLength;
}
public void setMinLength(int minLength) {
this.minLength = minLength;
}
public int getMaxLength() {
return maxLength;
}
public void setMaxLength(int minLength) {
this.maxLength = minLength;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + maxLength;
result = prime * result + minLength;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final LengthFilter other = (LengthFilter) obj;
if (maxLength != other.maxLength)
return false;
if (minLength != other.minLength)
return false;
return true;
}
}
|
alessandro-vincelli/youeat
|
src/main/java/org/mcavallo/opencloud/filters/LengthFilter.java
|
Java
|
apache-2.0
| 1,547
|
/*
* ====================================================================
* 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.impl.nio.conn;
import java.io.IOException;
import java.nio.channels.ReadableByteChannel;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.Header;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseFactory;
import org.apache.http.impl.nio.DefaultNHttpClientConnection;
import org.apache.http.impl.nio.reactor.SSLIOSession;
import org.apache.http.nio.NHttpMessageParser;
import org.apache.http.nio.NHttpMessageWriter;
import org.apache.http.nio.conn.OperatedClientConnection;
import org.apache.http.nio.reactor.IOSession;
import org.apache.http.nio.reactor.SessionInputBuffer;
import org.apache.http.nio.reactor.SessionOutputBuffer;
import org.apache.http.nio.util.ByteBufferAllocator;
import org.apache.http.params.HttpParams;
public class DefaultClientConnection
extends DefaultNHttpClientConnection implements OperatedClientConnection {
private final Log headerlog = LogFactory.getLog("org.apache.http.headers");
private final Log wirelog = LogFactory.getLog("org.apache.http.wire");
private final Log log;
private SSLIOSession ssliosession;
public DefaultClientConnection(
final IOSession iosession,
final HttpResponseFactory responseFactory,
final ByteBufferAllocator allocator,
final HttpParams params) {
super(iosession, responseFactory, allocator, params);
this.log = LogFactory.getLog(iosession.getClass());
if (this.log.isDebugEnabled() || this.wirelog.isDebugEnabled()) {
this.session = new LoggingIOSession(iosession, this.log, this.wirelog);
}
if (iosession instanceof SSLIOSession) {
this.ssliosession = (SSLIOSession) iosession;
} else {
this.ssliosession = null;
}
}
public void upgrade(final IOSession iosession) {
this.session.setBufferStatus(null);
if (this.log.isDebugEnabled() || this.wirelog.isDebugEnabled()) {
this.session = new LoggingIOSession(iosession, this.headerlog, this.wirelog);
} else {
this.session = iosession;
}
this.session.setBufferStatus(this);
if (iosession instanceof SSLIOSession) {
this.ssliosession = (SSLIOSession) iosession;
} else {
this.ssliosession = null;
}
}
public SSLIOSession getSSLIOSession() {
return this.ssliosession;
}
@Override
protected NHttpMessageWriter<HttpRequest> createRequestWriter(
final SessionOutputBuffer buffer,
final HttpParams params) {
return new LoggingNHttpMessageWriter(
super.createRequestWriter(buffer, params));
}
@Override
protected NHttpMessageParser<HttpResponse> createResponseParser(
final SessionInputBuffer buffer,
final HttpResponseFactory responseFactory,
final HttpParams params) {
return new LoggingNHttpMessageParser(
super.createResponseParser(buffer, responseFactory, params));
}
class LoggingNHttpMessageWriter implements NHttpMessageWriter<HttpRequest> {
private final NHttpMessageWriter<HttpRequest> writer;
public LoggingNHttpMessageWriter(final NHttpMessageWriter<HttpRequest> writer) {
super();
this.writer = writer;
}
public void reset() {
this.writer.reset();
}
public void write(final HttpRequest request) throws IOException, HttpException {
if (request != null && headerlog.isDebugEnabled()) {
headerlog.debug(">> " + request.getRequestLine().toString());
Header[] headers = request.getAllHeaders();
for (int i = 0; i < headers.length; i++) {
headerlog.debug(">> " + headers[i].toString());
}
}
this.writer.write(request);
}
}
class LoggingNHttpMessageParser implements NHttpMessageParser<HttpResponse> {
private final NHttpMessageParser<HttpResponse> parser;
public LoggingNHttpMessageParser(final NHttpMessageParser<HttpResponse> parser) {
super();
this.parser = parser;
}
public void reset() {
this.parser.reset();
}
public int fillBuffer(final ReadableByteChannel channel) throws IOException {
return this.parser.fillBuffer(channel);
}
public HttpResponse parse() throws IOException, HttpException {
HttpResponse response = this.parser.parse();
if (headerlog.isDebugEnabled()) {
if (response != null && headerlog.isDebugEnabled()) {
headerlog.debug("<< " + response.getStatusLine().toString());
Header[] headers = response.getAllHeaders();
for (int i = 0; i < headers.length; i++) {
headerlog.debug("<< " + headers[i].toString());
}
}
}
return response;
}
}
}
|
henry4j/httpasyncclient
|
httpasyncclient/src/main/java/org/apache/http/impl/nio/conn/DefaultClientConnection.java
|
Java
|
apache-2.0
| 6,445
|
<!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.5.0_13) on Sun Jun 29 16:47:10 MSD 2008 -->
<TITLE>
Uses of Class org.apache.poi.contrib.poibrowser.DocumentDescriptorRenderer (POI API Documentation)
</TITLE>
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
parent.document.title="Uses of Class org.apache.poi.contrib.poibrowser.DocumentDescriptorRenderer (POI API Documentation)";
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../org/apache/poi/contrib/poibrowser/DocumentDescriptorRenderer.html" title="class in org.apache.poi.contrib.poibrowser"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../index.html?org/apache/poi/contrib/poibrowser/\class-useDocumentDescriptorRenderer.html" target="_top"><B>FRAMES</B></A>
<A HREF="DocumentDescriptorRenderer.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<CENTER>
<H2>
<B>Uses of Class<br>org.apache.poi.contrib.poibrowser.DocumentDescriptorRenderer</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="../../../../../../org/apache/poi/contrib/poibrowser/DocumentDescriptorRenderer.html" title="class in org.apache.poi.contrib.poibrowser">DocumentDescriptorRenderer</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#org.apache.poi.contrib.poibrowser"><B>org.apache.poi.contrib.poibrowser</B></A></TD>
<TD><div> </TD>
</TR>
</TABLE>
<P>
<A NAME="org.apache.poi.contrib.poibrowser"><!-- --></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="../../../../../../org/apache/poi/contrib/poibrowser/DocumentDescriptorRenderer.html" title="class in org.apache.poi.contrib.poibrowser">DocumentDescriptorRenderer</A> in <A HREF="../../../../../../org/apache/poi/contrib/poibrowser/package-summary.html">org.apache.poi.contrib.poibrowser</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">Subclasses of <A HREF="../../../../../../org/apache/poi/contrib/poibrowser/DocumentDescriptorRenderer.html" title="class in org.apache.poi.contrib.poibrowser">DocumentDescriptorRenderer</A> in <A HREF="../../../../../../org/apache/poi/contrib/poibrowser/package-summary.html">org.apache.poi.contrib.poibrowser</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="../../../../../../org/apache/poi/contrib/poibrowser/PropertySetDescriptorRenderer.html" title="class in org.apache.poi.contrib.poibrowser">PropertySetDescriptorRenderer</A></B></CODE>
<BR>
Renders a <A HREF="../../../../../../org/apache/poi/contrib/poibrowser/PropertySetDescriptor.html" title="class in org.apache.poi.contrib.poibrowser"><CODE>PropertySetDescriptor</CODE></A> by more or less dumping
the stuff into a <CODE>JTextArea</CODE>.</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="../../../../../../org/apache/poi/contrib/poibrowser/DocumentDescriptorRenderer.html" title="class in org.apache.poi.contrib.poibrowser"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../index.html?org/apache/poi/contrib/poibrowser/\class-useDocumentDescriptorRenderer.html" target="_top"><B>FRAMES</B></A>
<A HREF="DocumentDescriptorRenderer.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>
<i>Copyright 2008 The Apache Software Foundation or
its licensors, as applicable.</i>
</BODY>
</HTML>
|
stumoodie/MetabolicNotationSubsystem
|
lib/poi-3.1-FINAL/docs/apidocs/org/apache/poi/contrib/poibrowser/class-use/DocumentDescriptorRenderer.html
|
HTML
|
apache-2.0
| 8,648
|
#region Copyright and License
// Copyright 2010..11 Alexander Reinert
//
// 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.
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ARSoft.Tools.Net.Dns
{
public class DsRecord : DnsRecordBase
{
public ushort KeyTag { get; private set; }
public DnsSecAlgorithm Algorithm { get; private set; }
public DnsSecDigestType DigestType { get; private set; }
public byte[] Digest { get; private set; }
internal DsRecord() {}
public DsRecord(string name, RecordClass recordClass, int timeToLive, ushort keyTag, DnsSecAlgorithm algorithm, DnsSecDigestType digestType, byte[] digest)
: base(name, RecordType.Ds, recordClass, timeToLive)
{
KeyTag = keyTag;
Algorithm = algorithm;
DigestType = digestType;
Digest = digest ?? new byte[] { };
}
internal override void ParseRecordData(byte[] resultData, int startPosition, int length)
{
KeyTag = DnsMessageBase.ParseUShort(resultData, ref startPosition);
Algorithm = (DnsSecAlgorithm) resultData[startPosition++];
DigestType = (DnsSecDigestType) resultData[startPosition++];
Digest = DnsMessageBase.ParseByteData(resultData, ref startPosition, length - 4);
}
internal override string RecordDataToString()
{
return KeyTag
+ " " + (byte) Algorithm
+ " " + (byte) DigestType
+ " " + Digest.ToBase64String();
}
protected internal override int MaximumRecordDataLength
{
get { return 4 + Digest.Length; }
}
protected internal override void EncodeRecordData(byte[] messageData, int offset, ref int currentPosition, Dictionary<string, ushort> domainNames)
{
DnsMessageBase.EncodeUShort(messageData, ref currentPosition, KeyTag);
messageData[currentPosition++] = (byte) Algorithm;
messageData[currentPosition++] = (byte) DigestType;
DnsMessageBase.EncodeByteArray(messageData, ref currentPosition, Digest);
}
}
}
|
LETO-R/ARSoft.Tools.Net
|
ARSoft.Tools.Net/Dns/DnsSec/DsRecord.cs
|
C#
|
apache-2.0
| 2,469
|
// Copyright 2019 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.query2.cquery;
import static com.google.common.truth.Truth.assertThat;
import static com.google.devtools.build.lib.packages.Attribute.attr;
import static com.google.devtools.build.lib.packages.BuildType.LABEL;
import static com.google.devtools.build.lib.packages.BuildType.LABEL_LIST;
import com.google.common.eventbus.EventBus;
import com.google.devtools.build.lib.analysis.ConfiguredRuleClassProvider;
import com.google.devtools.build.lib.analysis.ConfiguredTarget;
import com.google.devtools.build.lib.analysis.config.TransitionFactories;
import com.google.devtools.build.lib.analysis.config.transitions.NoTransition;
import com.google.devtools.build.lib.analysis.config.transitions.TransitionFactory;
import com.google.devtools.build.lib.analysis.util.MockRule;
import com.google.devtools.build.lib.events.Event;
import com.google.devtools.build.lib.events.Reporter;
import com.google.devtools.build.lib.packages.Rule;
import com.google.devtools.build.lib.query2.PostAnalysisQueryEnvironment;
import com.google.devtools.build.lib.query2.cquery.CqueryOptions.Transitions;
import com.google.devtools.build.lib.query2.engine.QueryEnvironment.Setting;
import com.google.devtools.build.lib.query2.engine.QueryExpression;
import com.google.devtools.build.lib.query2.engine.QueryParser;
import com.google.devtools.build.lib.util.FileTypeSet;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import javax.annotation.Nullable;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Tests for the transitions output format. */
@RunWith(JUnit4.class)
public class TransitionsOutputFormatterTest extends ConfiguredTargetQueryTest {
private CqueryOptions options;
private Reporter reporter;
private final List<Event> events = new ArrayList<>();
@Nullable private TransitionFactory<Rule> trimmingTransitionFactory;
@Before
public final void setUpCqueryOptions() {
this.options = new CqueryOptions();
helper.setQuerySettings(Setting.INCLUDE_ASPECTS);
this.reporter = new Reporter(new EventBus(), events::add);
}
@Test
public void testTransitions_full() throws Exception {
setUpRules();
writeFile(
"test/BUILD",
"my_rule(name = 'rule_with_patch',",
" patched = [':foo', ':foo2', ':trimmed_foo'],",
")",
"my_rule(name = 'rule_with_split',",
" split = ':bar',",
")",
"simple_rule(name = 'foo')",
"simple_rule(name = 'foo2')",
"simple_rule(name = 'trimmed_foo')",
"simple_rule(name = 'bar')");
List<String> result = getOutput("deps(//test:rule_with_patch)", Transitions.FULL);
assertThat(result.get(0)).startsWith("TestArgPatchTransition -> //test:rule_with_patch");
assertThat(result.get(1)).startsWith(" patched#//test:foo#TestArgPatch");
assertThat(result.get(2))
.isEqualTo(" test_arg:[SET BY RULE CLASS PATCH] -> [[SET BY PATCH]]");
assertThat(result.get(3)).startsWith(" patched#//test:foo2#TestArgPatch");
assertThat(result.get(4)).isEqualTo(result.get(2));
assertThat(result.get(5))
.startsWith(
" patched#//test:trimmed_foo#(TestArgPatchTransition + TestArgPatchTransition(trim))");
assertThat(result.get(6))
.isEqualTo(" test_arg:[SET BY RULE CLASS PATCH] -> [[SET BY TRIM]]");
result = getOutput("deps(//test:rule_with_split)", Transitions.FULL);
assertThat(result.get(1)).startsWith(" split#//test:bar#TestArgSplitTransition");
assertThat(result.get(2))
.isEqualTo(
" test_arg:[SET BY RULE CLASS PATCH] -> [[SET BY SPLIT 1], [SET BY SPLIT 2]]");
}
@Test
public void testTransitions_lite() throws Exception {
setUpRules();
writeFile(
"test/BUILD",
"my_rule(name = 'rule_with_patch',",
" patched = [':foo', ':foo2'],",
")",
"my_rule(name = 'rule_with_split',",
" split = ':bar',",
")",
"simple_rule(name = 'foo')",
"simple_rule(name = 'foo2')",
"simple_rule(name = 'bar')");
List<String> result = getOutput("deps(//test:rule_with_patch)", Transitions.LITE);
assertThat(result.get(0)).startsWith("TestArgPatchTransition -> //test:rule_with_patch");
assertThat(result.get(1)).startsWith(" patched#//test:foo#TestArgPatchTransition");
assertThat(result.get(2)).startsWith(" patched#//test:foo2#TestArgPatchTransition");
result = getOutput("deps(//test:rule_with_split)", Transitions.LITE);
assertThat(result.get(0)).startsWith("TestArgPatchTransition -> //test:rule_with_split");
assertThat(result.get(1)).startsWith(" split#//test:bar#TestArgSplitTransition");
}
@Test
public void testTransitions_getRightConfigurations() throws Exception {
setUpRules();
writeFile(
"test/BUILD",
"my_rule(name = 'rule_with_patch',",
" patched = [':foo'],",
")",
"simple_rule(name = 'foo')");
List<String> result = getOutput("deps(//test:rule_with_patch)", Transitions.LITE);
String postPatchConfig = result.get(2).substring("//test:foo (".length());
assertThat(result.get(1)).endsWith(postPatchConfig);
}
@Test
public void testTransitions_noTransitions() throws Exception {
setUpRules();
writeFile(
"test/BUILD",
"simple_rule(name = 'foo')");
List<String> result = getOutput("//test:foo", Transitions.NONE);
assertThat(result).isEmpty();
assertThat(events).hasSize(1);
assertThat(events.get(0).getMessage())
.isEqualTo(
"Instead of using --output=transitions, set the --transitions flag explicitly to 'lite'"
+ " or 'full'");
}
private void setUpRules() throws Exception {
TransitionFactory<Rule> infixTrimmingTransitionFactory =
(rule) -> {
if (!rule.getName().contains("trimmed")) {
return NoTransition.INSTANCE;
}
// rename the transition so it's distinguishable from the others in tests
return new TestArgPatchTransition("SET BY TRIM", "TestArgPatchTransition(trim)");
};
TestArgPatchTransition ruleClassTransition =
new TestArgPatchTransition("SET BY RULE CLASS PATCH");
TestArgPatchTransition attributePatchTransition = new TestArgPatchTransition("SET BY PATCH");
TestArgSplitTransition attributeSplitTransitions =
new TestArgSplitTransition("SET BY SPLIT 1", "SET BY SPLIT 2");
MockRule ruleWithTransitions =
() ->
MockRule.define(
"my_rule",
(builder, env) ->
builder
.cfg(ruleClassTransition)
.add(
attr("patched", LABEL_LIST)
.allowedFileTypes(FileTypeSet.ANY_FILE)
.cfg(TransitionFactories.of(attributePatchTransition)))
.add(
attr("split", LABEL)
.allowedFileTypes(FileTypeSet.ANY_FILE)
.cfg(TransitionFactories.of(attributeSplitTransitions))));
MockRule simpleRule =
() ->
MockRule.define(
"simple_rule",
(builder, env) ->
builder
.add(attr("deps", LABEL_LIST).allowedFileTypes(FileTypeSet.ANY_FILE)));
ConfiguredRuleClassProvider ruleClassProvider =
setRuleClassProviders(ruleWithTransitions, simpleRule)
.overrideTrimmingTransitionFactoryForTesting(infixTrimmingTransitionFactory)
.build();
this.trimmingTransitionFactory = ruleClassProvider.getTrimmingTransitionFactory();
helper.useRuleClassProvider(ruleClassProvider);
}
private List<String> getOutput(String queryExpression, CqueryOptions.Transitions verbosity)
throws Exception {
QueryExpression expression = QueryParser.parse(queryExpression, getDefaultFunctions());
Set<String> targetPatternSet = new LinkedHashSet<>();
expression.collectTargetPatterns(targetPatternSet);
helper.setQuerySettings(Setting.NO_IMPLICIT_DEPS);
PostAnalysisQueryEnvironment<ConfiguredTarget> env =
((ConfiguredTargetQueryHelper) helper).getPostAnalysisQueryEnvironment(targetPatternSet);
options.transitions = verbosity;
// TODO(juliexxia): Test late-bound attributes.
TransitionsOutputFormatterCallback callback =
new TransitionsOutputFormatterCallback(
reporter,
options,
/*out=*/ null,
getHelper().getSkyframeExecutor(),
env.getAccessor(),
env.getHostConfiguration(),
trimmingTransitionFactory);
env.evaluateQuery(env.transformParsedQuery(QueryParser.parse(queryExpression, env)), callback);
return callback.getResult();
}
}
|
werkt/bazel
|
src/test/java/com/google/devtools/build/lib/query2/cquery/TransitionsOutputFormatterTest.java
|
Java
|
apache-2.0
| 9,600
|
/*
* Copyright 2013 Gunnar Kappei.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.opengis.gml;
/**
* A document containing one conversionRef(@http://www.opengis.net/gml) element.
*
* This is a complex type.
*/
public interface ConversionRefDocument extends org.apache.xmlbeans.XmlObject
{
public static final org.apache.xmlbeans.SchemaType type = (org.apache.xmlbeans.SchemaType)
org.apache.xmlbeans.XmlBeans.typeSystemForClassLoader(ConversionRefDocument.class.getClassLoader(), "schemaorg_apache_xmlbeans.system.s6E28D279B6C224D74769DB8B98AF1665").resolveHandle("conversionrefc380doctype");
/**
* Gets the "conversionRef" element
*/
net.opengis.gml.ConversionRefType getConversionRef();
/**
* Sets the "conversionRef" element
*/
void setConversionRef(net.opengis.gml.ConversionRefType conversionRef);
/**
* Appends and returns a new empty "conversionRef" element
*/
net.opengis.gml.ConversionRefType addNewConversionRef();
/**
* A factory class with static methods for creating instances
* of this type.
*/
public static final class Factory
{
public static net.opengis.gml.ConversionRefDocument newInstance() {
return (net.opengis.gml.ConversionRefDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newInstance( type, null ); }
public static net.opengis.gml.ConversionRefDocument newInstance(org.apache.xmlbeans.XmlOptions options) {
return (net.opengis.gml.ConversionRefDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newInstance( type, options ); }
/** @param xmlAsString the string value to parse */
public static net.opengis.gml.ConversionRefDocument parse(java.lang.String xmlAsString) throws org.apache.xmlbeans.XmlException {
return (net.opengis.gml.ConversionRefDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( xmlAsString, type, null ); }
public static net.opengis.gml.ConversionRefDocument parse(java.lang.String xmlAsString, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException {
return (net.opengis.gml.ConversionRefDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( xmlAsString, type, options ); }
/** @param file the file from which to load an xml document */
public static net.opengis.gml.ConversionRefDocument parse(java.io.File file) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (net.opengis.gml.ConversionRefDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( file, type, null ); }
public static net.opengis.gml.ConversionRefDocument parse(java.io.File file, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (net.opengis.gml.ConversionRefDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( file, type, options ); }
public static net.opengis.gml.ConversionRefDocument parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (net.opengis.gml.ConversionRefDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( u, type, null ); }
public static net.opengis.gml.ConversionRefDocument parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (net.opengis.gml.ConversionRefDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( u, type, options ); }
public static net.opengis.gml.ConversionRefDocument parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (net.opengis.gml.ConversionRefDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( is, type, null ); }
public static net.opengis.gml.ConversionRefDocument parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (net.opengis.gml.ConversionRefDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( is, type, options ); }
public static net.opengis.gml.ConversionRefDocument parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (net.opengis.gml.ConversionRefDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( r, type, null ); }
public static net.opengis.gml.ConversionRefDocument parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (net.opengis.gml.ConversionRefDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( r, type, options ); }
public static net.opengis.gml.ConversionRefDocument parse(javax.xml.stream.XMLStreamReader sr) throws org.apache.xmlbeans.XmlException {
return (net.opengis.gml.ConversionRefDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( sr, type, null ); }
public static net.opengis.gml.ConversionRefDocument parse(javax.xml.stream.XMLStreamReader sr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException {
return (net.opengis.gml.ConversionRefDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( sr, type, options ); }
public static net.opengis.gml.ConversionRefDocument parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException {
return (net.opengis.gml.ConversionRefDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( node, type, null ); }
public static net.opengis.gml.ConversionRefDocument parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException {
return (net.opengis.gml.ConversionRefDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( node, type, options ); }
/** @deprecated {@link org.apache.xmlbeans.xml.stream.XMLInputStream} */
@Deprecated
public static net.opengis.gml.ConversionRefDocument parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException {
return (net.opengis.gml.ConversionRefDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( xis, type, null ); }
/** @deprecated {@link org.apache.xmlbeans.xml.stream.XMLInputStream} */
@Deprecated
public static net.opengis.gml.ConversionRefDocument parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException {
return (net.opengis.gml.ConversionRefDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( xis, type, options ); }
/** @deprecated {@link org.apache.xmlbeans.xml.stream.XMLInputStream} */
@Deprecated
public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException {
return org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, null ); }
/** @deprecated {@link org.apache.xmlbeans.xml.stream.XMLInputStream} */
@Deprecated
public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException {
return org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, options ); }
private Factory() { } // No instance of this class allowed
}
}
|
moosbusch/xbLIDO
|
src/net/opengis/gml/ConversionRefDocument.java
|
Java
|
apache-2.0
| 8,712
|
package view;
import java.util.Random;
import java.util.Scanner;
public class Employee extends Member {
protected String department; int yearHired;
static Random rnd=new Random();
public Employee(){generate();}
public void generate(){
super.generate();
department=Names.department[rnd.nextInt(Names.department.length)];
yearHired=Names.yearHired[rnd.nextInt(Names.yearHired.length)];
}
public String toString(){return toString(true);}
public String toString(boolean lab){
return (lab?"Emp.":"")+String.format("%s %20s %-10s", super.toString(false),
department,yearHired);}
public String htmlRow(){ return "<TR>"+htmlColumns()+"</TR>";}
public String htmlColumns(){
return String.format("%s <TD>%20s</TD> <TD>%-10s</TD> ",super.htmlColumns(),department,yearHired);
}
}
|
zengboming/JAVA
|
q/src/view/Employee.java
|
Java
|
apache-2.0
| 798
|
package com.silen.android.preferences;
import android.app.ActionBar;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceFragment;
import android.view.MenuItem;
import android.widget.Toast;
import com.silen.android.MainActivity;
import com.silen.android.R;
import com.silen.android.Webview;
import java.io.File;
public class MyPreferencesActivity extends PreferenceActivity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActionBar ac = getActionBar();
ac.setDisplayHomeAsUpEnabled(true); //激活返回键
getFragmentManager().beginTransaction().replace(android.R.id.content, new MyPreferenceFragment()).commit();
}
@Override
public boolean onOptionsItemSelected(MenuItem item){
switch(item.getItemId()){
case android.R.id.home:
this.finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public static class MyPreferenceFragment extends PreferenceFragment
{
@Override
public void onCreate(final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
Preference cachebutton = (Preference)findPreference("clearCache");
cachebutton.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
String sDir = Environment.getExternalStorageDirectory().getPath() + "/FastImgSearch/temp/";
File temp = new File(sDir);
File[] tempfiles = temp.listFiles();
if(tempfiles.length != 0){
for(int i = 0; i<tempfiles.length; i++) tempfiles[i].delete();
Toast.makeText(MainActivity.mainActivity, "缓存清除完毕!", Toast.LENGTH_SHORT).show();
}
else Toast.makeText(MainActivity.mainActivity, "无缓存文件哦~", Toast.LENGTH_SHORT).show();
return true;
}
});
}
}
}
|
silencender/FastImgSearch
|
android/src/main/java/com/silen/android/preferences/MyPreferencesActivity.java
|
Java
|
apache-2.0
| 2,420
|
# Summarize all the SNPs in 1,000 Genomes also found in ClinVar by clinical significance.
SELECT
clinicalsignificance,
COUNT(1) AS num_variants
FROM
FLATTEN([google.com:biggene:1000genomes.variants1kG],
alternate_bases) AS var
JOIN (
SELECT
chromosome,
start,
clinicalsignificance,
REGEXP_EXTRACT(hgvs_c,
r'(\w)>\w') AS ref,
REGEXP_EXTRACT(hgvs_c,
r'\w>(\w)') AS alt,
REGEXP_EXTRACT(phenotypeids,
r'MedGen:(\w+)') AS disease_id,
FROM
[google.com:biggene:1000genomes.clinvar]
WHERE
type='single nucleotide variant'
) AS clin
ON
var.contig = clin.chromosome
AND var.position = clin.start
AND reference_bases = ref
AND alternate_bases = alt
WHERE
var.vt='SNP'
GROUP BY
clinicalsignificance,
ORDER BY
num_variants DESC;
|
PersonalGenomesOrg/bigquery-examples
|
1000genomes/sql/snp-clinical-significance.sql
|
SQL
|
apache-2.0
| 800
|
[%
page.import({
title => 'Site Information',
section => 'about',
description
=> 'Information about this website',
});
%]
<p>
<a name="SiteInformation" id="SiteInformation"></a>
</p>
<h4>
Contact Information
</h4>
<p>
You can email us at <tt>webmaster at perl.org</tt>.
Please open an <a href="https://github.com/perlorg/perlweb/issues">issue</a>
or better yet a pull request on our <a href="https://github.com/perlorg/perlweb/">github</a> account.
</p>
<h4>
Questions? Comments? Suggestions?
</h4>
<p>
Please use the email address above to send us questions, suggestions, new links, or accessibility problems.
</p>
<h4>
About the website
</h4>
<p>
The current look of www.perl.org was designed by Leo Lapworth.
Robert Spier and Ask Bjørn Hansen are the webmasters and sysadmins.
We believe in browser independence and accessibility, but <a
href="http://www.ie6nomore.com/">not IE6</a>. Our center of operations
is <a href="http://noc.perl.org">The Perl NOC</a>. You
can track our progress at <a
href="http://log.perl.org">the Perl NOC Log</a>.
The source for the site is stored in <a href="https://github.com/perlorg/perlweb/">github</a>.
</p>
<p>
When you need to link to Perl, we want you to think <tt>perl.org</tt>
</p>
<h4>
Mantra
</h4>
<p>
<em>Genius is 1 percent inspiration and 99 percent perspiration.</em>
- <a href="http://en.wikipedia.org/wiki/Thomas_Edison">T.E.</a>
</p>
<h4>
Privacy Policy
</h4>
<p>
We do not collect any personal data at this time, but if we do, you'll find the privacy policy here.
</p>
<h4>
Copyrights
</h4>
<p>
Copyright © 2002-[% USE date; date.format(date.now, '%Y') %] Perl.org unless otherwise specified.
</p>
<h4>
Intellectual Property
</h4>
<p>
The use of the camel image in association with the Perl language is a trademark of <a href="http://www.ora.com">O'Reilly Media, Inc.</a> <a href="http://www.onlamp.com/pub/a/oreilly/perl/usage/">Used with permission</a>.
</p>
<h4>
License
</h4>
<p>
<a style="float: left; padding-right: 1em;" rel="license" href="http://creativecommons.org/licenses/by-nc-nd/3.0/us/"><img alt="Creative Commons License" style="border-width:0" src="https://licensebuttons.net/l/by-nc-nd/3.0/us/88x31.png" /></a> <span xmlns:dc="http://purl.org/dc/elements/1.1/" property="dc:title">www.perl.org</span> is licensed under a <a rel="license" href="http://creativecommons.org/licenses/by-nc-nd/3.0/us/">Creative Commons Attribution-Noncommercial-No Derivative Works 3.0 United States License</a>.
</p>
<p>
<a name="Sponsors" id="Sponsors"></a>
</p>
<h4>
Sponsors
</h4>
<p>
<a name="sponsors" id="sponsors"></a>
</p>
<p>
The following companies have donated valuable resources to Perl.org. We encourage you to support them.
</p>
<table border="0" width="100%">
<tr>
<td valign="top" align="center">
<a href="http://www.phyber.com/"><img border="0" src="[% combust.static_url("/images/friends/phyber.png") %]" height="54" width="150" alt="Phyber Communications" /></a>
</td>
<td>
<p>
Phyber Communications are providing us delicious <a href="http://www.phyber.com/services/network/#ip-transit">IP transit</a> in both IPv4 and IPv6 flavors
and power, rackspace, occasional hardware and other infrastructure resources.
</p>
</td>
</tr>
<tr>
<td valign="top" align="center">
<a href="http://www.maxcdn.com/"><img border="0" src="[% combust.static_url("/images/friends/maxcdn.svg") %]" height="51" width="110" alt="MaxCDN" /></a>
</td>
<td>
<p>
www.perl.org is TLS-terminated and cached with MaxCDN for maximum performance around
the world. They have incredibly quick and easy setup including enabling TLS.
</p>
</td>
</tr>
<tr>
<td valign="top" align="center">
<a href="http://www.fastly.com/"><img border="0" src="[% combust.static_url("/images/friends/fastly.png") %]" height="51" width="110" alt="Fastly CDN" /></a>
</td>
<td>
<p>
Fastly provides us CDN services
for <a href="http://www.cpan.org/">CPAN</a> and other
sites. They have <a href="http://www.fastly.com/docs">fantastic
features</a> and an API including a
<a href="https://metacpan.org/release/Net-Fastly/">Perl
interface</a>.
</p>
</td>
</tr>
<tr>
<td valign="top" align="center">
<a href="http://www.activestate.com/"><img border="0" src="[% combust.static_url("/images/friends/activestate.png") %]" height="34" width="160" alt="ActiveState" /></a>
</td>
<td>
<p>
ActiveState Perl: ActiveState offers both a free
community version and a commercially supported binary
distribution of Perl for Win32 and Perl for Win64.
</p>
</td>
</tr>
<tr>
<td valign="top" align="center">
<a href="https://advancesystemsinc.com/">
<img class="border" border="0" src="[% combust.static_url("/images/friends/advancesystemsinc.com.png") %]" height="56" width="133" alt="Advance Systems Inc" />
</a>
</td>
<td>
<p>
Advance Systems Inc is a premier provider of workforce
management software and supports open source.
</p>
</td>
</tr>
<tr>
<td valign="top" align="center">
<a href="http://digitalcraftsmen.net/"><img border="0" src="[% combust.static_url("/images/friends/digital_craftsmen.png") %]" height="56" width="142" alt="Digital Craftsmen" /></a>
</td>
<td>
<p>
The London based hosting
company <a href="http://digitalcraftsmen.net/">Digital
Craftsmen</a> have generously and competently hosted
our European mirror
of <a href="http://search.cpan.org/">Search CPAN</a> for years.
</p>
</td>
</tr>
<tr>
<td align="center">
<a href="http://www.redhat.com/"><img border="0" src="[% combust.static_url("/images/friends/rhn.png") %]" width="139" height="48" alt="Powered By Red Hat" /></a>
</td>
<td>
<p>
Most of our systems are running <a href="http://www.redhat.com/">Red Hat Linux</a>. With <a href="http://www.redhat.com/software/rhn/offerings/">Red Hat Network Enterprise</a> it's almost too easy to manage them.
</p>
</td>
</tr>
<tr>
<td align="center">
<a href="http://develooper.com/"><img border="0" src="[% combust.static_url("/images/friends/develooperlogo-160t.png") %]" height="36" width="160" alt="Develooper" /></a>
</td>
<td>
<p>
For custom development, logistics and coordination.
</p>
</td>
</tr>
<tr>
<td align="center">
<a href="http://www.bestpractical.com/"><img border="0" src="[% combust.static_url("/images/friends/bestpractical.png") %]" width="160" height="34" alt="Best Practical Solutions" /></a>
</td>
<td>
<p>
We couldn't keep track of anything without <a href="http://www.bestpractical.com/rt/">Request Tracker</a>.
</p>
</td>
</tr>
<tr>
<td align="center">
<a href="http://oreilly.com/"><img border="0" src="[% combust.static_url("/images/friends/oreilly-160.png") %]" width="160" height="48" alt="O'Reilly Media" /></a>
</td>
<td>
<p>
O'Reilly publishes great Perl books, and associated the <a href="/camel.html">camel</a> with Perl.
</p>
</td>
</tr>
</table>
<h4>
Wishlist
</h4>
<p>
<a name="donate" id="donate"></a> We have a <a href="wishlist.html">wishlist</a> if you want to help us. You can also <a href="http://donate.perlfoundation.org/">donate money</a> to <a href="http://www.perlfoundation.org/">The Perl Foundation</a>. Please add a comment to your donation about supporting the Perl.org infrastructure. Your donation (money or hardware) is tax deductible. TPF is a non-profit, 501(c)(3) organization. If you are outside the US, please check with your accountant.
</p>
<p>
<a name="Technology" id="Technology"></a>
</p>
<h4>
Technology
</h4>
<table width="476" border="0">
<tr>
<td>
<a href="http://www.perl.org/"><img border="0" src="[% combust.static_url("/images/buttons/perlpowered.png") %]" alt="Powered By Perl" /></a>
</td>
<td>
<p>
We use Perl. (Duh!)
</p>
</td>
</tr>
<tr>
<td>
<a href="http://combust.develooper.com/"><img border="0" src="/simages/combust-powered.png" alt="Powered by Combust" /></a>
</td>
<td>
<p>
This site is powered
by <a href="http://git.develooper.com/combust.git">Combust!</a>
</p>
</td>
</tr>
<tr>
<td>
<a href="http://www.template-toolkit.org"><img border="0" src="[% combust.static_url("/images/friends/template-toolkit.gif") %]" alt="[Template Toolkit Logo]" /></a>
</td>
<td>
<p>
Built with <a href="http://www.template-toolkit.org">Template Toolkit</a>
</p>
</td>
</tr>
</table>
|
Abigail/perlweb
|
docs/www/siteinfo.html
|
HTML
|
apache-2.0
| 9,712
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Corex.CodingTools.CSharp
{
public class Attribute
{
public Attribute()
{
Parameters = new List<string>();
NamedParamters = new Dictionary<string, string>();
}
public Attribute Clone()
{
return new Attribute { Name = Name, Parameters = new List<string>(Parameters), NamedParamters = new Dictionary<string, string>(NamedParamters) };
}
public string Name { get; set; }
public List<string> Parameters { get; set; }
public Dictionary<string, string> NamedParamters { get; set; }
}
public class Assembly
{
public Assembly()
{
Classes = new List<Class>();
Usings = new List<string>();
}
public List<Class> Classes { get; set; }
public string Namespace { get; set; }
public List<string> Usings { get; set; }
}
public class Member
{
public Member()
{
Attributes = new List<Attribute>();
}
public List<Attribute> Attributes { get; set; }
public string Summary { get; set; }
public string Remarks { get; set; }
public string Name { get; set; }
public Class Type { get; set; }
public override string ToString()
{
return String.Format("{0} {1} {2}", GetType().Name, Type, Name); ;
}
public virtual Member Clone2()
{
var me = Activator.CreateInstance(GetType()) as Member;
me.Name = Name;
me.Type = Type;
return me;
}
}
public class Class : Member
{
public Class()
{
Methods = new List<Method>();
Properties = new List<Property>();
GenericArguments = new List<Class>();
GenericClasses = new List<Class>();
}
public Class BaseClass { get; set; }
public Class MakeGenericClass(Class[] args)
{
foreach (var ce in GenericClasses)
{
for (var i = 0; i < args.Length; i++)
{
var arg = args[i];
var arg2 = ce.GenericArguments[i];
if (arg != arg2)
break;
}
return ce;
}
var ce2 = new Class { Name = Name };
ce2.GenericArguments.AddRange(args);
GenericClasses.Add(ce2);
return ce2;
}
public List<Class> GenericClasses { get; set; }
public List<Class> GenericArguments { get; set; }
public List<Method> Methods { get; set; }
public List<Property> Properties { get; set; }
public IEnumerable<Member> Members
{
get
{
return Methods.Concat<Member>(Properties);
}
}
public void AddMember(Member me)
{
if (me is Property)
Properties.Add((Property)me);
else if (me is Method)
Methods.Add((Method)me);
}
public void RemoveMember(Member me)
{
if (me is Property)
Properties.Remove((Property)me);
else if (me is Method)
Methods.Remove((Method)me);
}
public override Member Clone2()
{
var x = base.Clone2() as Class;
x.Properties.AddRange(Properties.Select(t => t.Clone()));
x.Methods.AddRange(Methods.Select(t => t.Clone()));
return x;
}
}
public class Method : Member
{
public Method()
{
Parameters = new List<Parameter>();
}
public List<Parameter> Parameters { get; set; }
public override Member Clone2()
{
var x = base.Clone2() as Method;
x.IsStatic = IsStatic;
x.Attributes.AddRange(Attributes.Select(t => t.Clone()));
x.Parameters.AddRange(Parameters.Select(t => t.Clone()));
x.Summary = Summary;
x.Remarks = Remarks;
x.ReturnsSummary = ReturnsSummary;
return x;
}
public string ReturnsSummary { get; set; }
public bool IsStatic { get; set; }
}
public class Parameter : Member
{
public bool IsOptional { get; set; }
public override Member Clone2()
{
var x = base.Clone2() as Parameter;
x.IsOptional = IsOptional;
return x;
}
}
public class Property : Member
{
public bool IsStatic { get; set; }
}
}
|
danelkhen/corex
|
src/Corex.Coding/CSharp/CodeModel.cs
|
C#
|
apache-2.0
| 4,926
|
/**
* Copyright 2014 Open Connectome Project (http://openconnecto.me)
* Written by Da Zheng (zhengda1936@gmail.com)
*
* This file is part of FlashGraph.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "messaging.h"
int multicast_msg_sender::flush()
{
if (buf.is_empty()) {
assert(mmsg == NULL);
return 0;
}
this->mmsg = NULL;
this->num_dests = 0;
dest_list.clear();
queue->add(&buf, 1);
if (buf.get_num_objs() > 1)
printf("there are %d objs in the msg\n", buf.get_num_objs());
// We have to make sure all messages have been sent to the queue.
assert(buf.is_empty());
message tmp(alloc.get());
buf = tmp;
return 1;
}
bool multicast_msg_sender::add_dest(local_vid_t id)
{
int ret = buf.inc_msg_size(sizeof(id.id));
if (ret == 0) {
flush();
multicast_message *mmsg_template
= (multicast_message *) mmsg_temp_buf;
vertex_message *p = (vertex_message *) buf.add(*mmsg_template);
// We just add the buffer. We should be able to add the new message.
assert(p);
this->mmsg = multicast_message::convert2multicast(p);
dest_list = this->mmsg->get_dest_list();
buf.inc_msg_size(sizeof(id.id));
}
num_dests++;
dest_list.add_dest(id);
return true;
}
int multicast_msg_sender::add_dests(local_vid_t ids[], int num)
{
int orig_num = num;
while (num > 0) {
int num_allowed = min(buf.get_remaining_size(),
num * sizeof(ids[0].id)) / sizeof(ids[0].id);
if (num_allowed == 0) {
flush();
multicast_message *mmsg_template
= (multicast_message *) mmsg_temp_buf;
vertex_message *p = (vertex_message *) buf.add(*mmsg_template);
// We just add the buffer. We should be able to add the new message.
assert(p);
this->mmsg = multicast_message::convert2multicast(p);
dest_list = this->mmsg->get_dest_list();
num_allowed = min(buf.get_remaining_size(),
num * sizeof(ids[0].id)) / sizeof(ids[0].id);
assert(num_allowed > 0);
}
buf.inc_msg_size(num_allowed * sizeof(ids[0].id));
num_dests += num_allowed;
dest_list.add_dests(ids, num_allowed);
ids += num_allowed;
num -= num_allowed;
assert(num >= 0);
}
return orig_num;
}
|
silky/FlashGraph
|
flash-graph/messaging.cpp
|
C++
|
apache-2.0
| 2,629
|
# -*- coding: utf-8 -*-
# Copyright Tom SF Haines
#
# 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 posixpath
import random
import math
from bin.shared import ray_cast
from bin.shared import csp
from direct.actor.Actor import Actor
from direct.interval.IntervalGlobal import *
from direct.interval.ActorInterval import ActorInterval
from panda3d.core import *
from panda3d.ode import *
class SimpleWeapon:
"""Provides a simple weapon system - not very sophisticaed, but good enough to test shooting things."""
def __init__(self,manager,xml):
self.gunView = render.attachNewNode('gun-view')
self.ray = None
self.reload(manager,xml)
def destroy(self):
self.gunView.removeNode()
if self.ray!=None:
self.ray.destroy()
def reload(self,manager,xml):
# Get the path to load weapons from...
basePath = manager.get('paths').getConfig().find('weapons').get('path')
# Variables to manage the firing state (Used G36 as reference for defaults.)...
bullet = xml.find('bullet')
if bullet!=None:
self.bulletRate = float(bullet.get('rate',1.0/12.5))
self.bulletSpeed = float(bullet.get('speed',920.0))
self.bulletWeight = float(bullet.get('mass',0.004))
else:
self.bulletRate = 1.0/12.5
self.bulletSpeed = 920.0
self.bulletWeight = 0.004
# Determine the weapon meshes path...
self.meshPath = posixpath.join(basePath, xml.find('egg').get('file'))
# Get the camera interface, so we can zoom in when the player aims...
self.camera = manager.get(xml.find('camera').get('plugin'))
# Create our gun node - both the gun and the ray used for shooting track this - allows for gun jitter, kick back etc...
parent = xml.find('parent')
self.gunView.reparentTo(manager.get(parent.get('plugin')).getNode(parent.get('node')))
# Create a ray cast to detect what the player is looking at... and what will be shot...
self.space = manager.get('ode').getSpace()
if self.ray!=None:
self.ray.destroy()
self.ray = OdeRayGeom(100.0)
self.ray.setCategoryBits(BitMask32(0xfffffffe))
self.ray.setCollideBits(BitMask32(0xfffffffe))
# Get all the stuff we need to do the muzzle flash particle effect...
flash = xml.find('muzzle_flash')
self.flashManager = manager.get(flash.get('plugin'))
self.flashEffect = flash.get('effect')
self.flashBone = flash.get('bone') # Will be swapped out for the actual node latter.
self.flashPos = csp.getPos(flash.get('pos'))
# Get all the stuff we need to do the bullet hit sparks effect...
sparks = xml.find('sparks')
self.sparksManager = manager.get(sparks.get('plugin'))
self.sparksEffect = sparks.get('effect')
# Create a quaternion that rotates +ve z to +ve y - used to point it in the weapon direction rather than up...
self.zToY = Quat()
self.zToY.setFromAxisAngle(-90.0,Vec3(1.0,0.0,0.0))
# State for the animation...
self.state = False # False==casual, True==aim.
self.nextState = False
# Firing state...
self.firing = False # True if the trigger is being held.
self.triggerTime = 0.0 # How long the trigger has been held for, so we know when to eject ammo.
# For bullet holes
bh = xml.find('bullet_holes')
if bh != None:
self.bulletHoles = manager.get(bh.get('plugin'))
else:
self.bulletHoles = None
def postInit(self):
for i in self.postReload():
yield i
def postReload(self):
# Load the actor...
self.mesh = Actor(self.meshPath)
yield
# Shader generator makes it shiny, plus we need it in the right places in the render graph...
self.mesh.setShaderAuto()
self.mesh.reparentTo(self.gunView)
self.mesh.hide()
yield
# Set its animation going... except we pause it until needed...
self.nextAni()
self.interval.pause()
# Gun flash requires an exposed bone...
self.flashBone = self.mesh.exposeJoint(None,"modelRoot",self.flashBone)
yield
def gunControl(self,task):
# Update the gun direction ray to follow the players view...
self.ray.setPosition(self.gunView.getPos(render))
self.ray.setQuaternion(self.zToY.multiply(self.gunView.getQuat(render)))
# If the gun is firing update the trigger time, if a bullet is ejected do the maths...
if self.firing:
dt = globalClock.getDt()
self.triggerTime += dt
while self.triggerTime>self.bulletRate:
self.triggerTime -= self.bulletRate
hit,pos,norm = ray_cast.nearestHit(self.space,self.ray)
# Create a muzzle flash effect...
self.flashManager.doEffect(self.flashEffect, self.flashBone, True, self.flashPos)
if hit:
# Create an impact sparks effect...
# Calculate the reflection direction...
rd = self.ray.getDirection()
sparkDir = (norm * (2.0*norm.dot(rd))) - rd
# Convert the reflection direction into a quaternion that will rotate +ve z to the required direction...
try:
ang = -math.acos(sparkDir[2])
except:
print 'Angle problem', sparkDir
ang = 0.0
axis = Vec3(0.0,0.0,1.0).cross(sparkDir)
axis.normalize()
sparkQuat = Quat()
sparkQuat.setFromAxisAngleRad(ang,axis)
# Set it going...
self.sparksManager.doEffect(self.sparksEffect, render, False, pos, sparkQuat)
# Make a bullet hole
if hit.hasBody() and isinstance(hit.getBody().getData(), NodePath):
self.bulletHoles.makeNew(pos, norm, hit.getBody().getData())
else:
self.bulletHoles.makeNew(pos, norm, None)
# Impart some energy on the object...
if hit and hit.hasBody():
body = hit.getBody()
# Calculate the force required to supply the energy the bullet contains to the body...
force = self.bulletWeight*self.bulletSpeed/0.05
# Get the direction of travel of the bullet, multiply by force...
d = self.ray.getDirection()
d *= force
# If the object is asleep awaken it...
if not body.isEnabled():
body.enable()
# Add the force to the object...
body.addForceAtPos(d,pos)
return task.cont
def start(self):
# Make the gun visible...
self.mesh.show()
# Set the gun animation going...
self.interval.finish()
# Weapon task - this primarily makes it shoot...
self.task = taskMgr.add(self.gunControl,'GunControl')
def stop(self):
self.interval.pause()
self.mesh.hide()
taskMgr.remove(self.task)
def nextAni(self):
self.state = self.nextState
if self.state:
ani = random.choice(('aim_wiggle_a','aim_wiggle_b','aim_wiggle_c'))
else:
ani = random.choice(('casual_wiggle_a','casual_wiggle_b','casual_wiggle_c'))
self.mesh.pose(ani,0)
self.interval = Sequence(self.mesh.actorInterval(ani),Func(self.nextAni))
self.interval.start()
def setAiming(self,s):
if self.nextState!=s:
self.interval.pause()
self.nextState = s
self.camera.setZoomed(s)
def wib():
self.interval.finish()
if s: ani = 'casual_aim'
else: ani = 'aim_casual'
transition = Sequence(self.mesh.actorInterval(ani),Func(wib))
transition.start()
def setFiring(self,s):
self.firing = s
if self.firing:
self.triggerTime = 0.0
|
Panda3D-google-code-repositories/naith
|
game/plugins/simpleweapon/simpleweapon.py
|
Python
|
apache-2.0
| 7,962
|
#include "sympl_utils.h"
void sympl_calculateDelta(DVector *delta, Matrix *A, DVector *C, IVector *basis) {
for (int j = 0; j < A->w; j++) {
delta->data[j] = 0;
for (int i = 0; i < A->h; i++) {
delta->data[j] += A->data[i][j] * C->data[basis->data[i]];
}
delta->data[j] -= C->data[j];
}
}
int sympl_is_good_delta(DVector *delta, int delta_flag) {
if (delta_flag == DELTA_BEFORE_ZERO) {
for (int i = 0; i < delta->size; i++) {
if (delta->data[i] > 0) return DELTA_BAD;
}
} else {
for (int i = 0; i < delta->size; i++) {
if (delta->data[i] < 0) return DELTA_BAD;
}
}
return DELTA_GOOD;
}
void sympl_print(FILE *out, Matrix *A, DVector *C, DVector *delta,
IVector *basis) {
printf("\n\n| ");
for (int i = 0; i < A->w; i++) {
printf("| A%i ", i);
}
printf("| C |\n");
for (int i = 0; i < basis->size; i++) {
printf("|A%i", basis->data[i]);
for (int j = 0; j < A->w; j++) {
printf("|%.2lf", A->data[i][j]);
}
printf("|%0.2lf\n", C->data[basis->data[i]]);
}
printf("|dl");
for (int i = 0; i < delta->size; i++) {
printf("|%.2lf", delta->data[i]);
}
printf("\n\n");
}
void sympl_find_p_k(Matrix *A, DVector *delta, int *p, int *k) {
*p = 1;
double p_val = delta->data[*p];
for (int i = *p + 1; i < delta->size; i++) {
if (delta->data[i] < p_val) {
p_val = delta->data[i];
*p = i;
}
}
*k = 0;
double k_val = A->data[*k][0] / A->data[*k][*p];
for (int i = 1; i < A->h; i++) {
if (A->data[i][*p] < 0) continue;
double newValue = A->data[i][0] / A->data[i][*p];
if (newValue < k_val) {
k_val = newValue;
*k = i;
}
}
}
void sympl_process_table(Matrix *A, DVector *delta, IVector *basis) {
int p,k;
sympl_find_p_k(A, delta, &p, &k);
basis->data[k] = p;
Matrix *A_tmp = matrix_allocate(A->h, A->w);
for (int i = 0; i < A_tmp->h; i++) {
for (int j = 0; j < A_tmp->w; j++) {
if (i == k) {
A_tmp->data[i][j] = A->data[k][j] / A->data[k][p];
} else {
A_tmp->data[i][j] = (A->data[i][j] * A->data[k][p]
- A->data[i][p] * A->data[k][j]) / A->data[k][p];
}
}
}
matrix_fill(A_tmp, A);
matrix_free(A_tmp);
}
#define CORRECT 0
#define INCORRECT 1
#define POSITION_NOT_SET -1
IVector * sympl_add_basis_vars(Matrix *A) {
IVector *counter = IVector_allocate(A->h);
for (int i = 0 ; i < counter->size; i++) {
counter->data[i] = 0;
}
IVector *basis = IVector_allocate(A->h);
int basis_pos = 0;
for (int j = 0; j < A->w; j++) {
int is_correct = CORRECT;
int one_position = POSITION_NOT_SET;
int one_col;
for (int i = 0; i < A->h; i++) {
if (A->data[i][j] != 0 && A->data[i][j] != 1) {
is_correct = INCORRECT;
break;
}
if (A->data[i][j] == 1) {
if (one_position == POSITION_NOT_SET) {
one_position = i;
one_col = j;
} else {
is_correct = INCORRECT;
break;
}
}
}
if (is_correct == CORRECT) {
counter->data[one_position]++;
basis->data[basis_pos++] = one_col;
}
}
for (int i = 0; i < counter->size; i++) {
if (counter->data[i] == 0) {
// add new col
matrix_add_col(A, A->w);
A->data[i][A->w - 1] = 1;
counter->data[i] = 1;
basis->data[basis_pos++] = A->w - 1;
}
}
return basis;
}
void sympl_add_artificial_vars(Matrix *A, CVector *operators) {
for (int i = 0; i < operators->size; i++) {
char operator = operators->data[i];
if (operator == '=')
continue;
matrix_add_col(A, A->w);
A->data[i][A->w - 1] = operator == '>' ? -1 : 1;
}
}
void sympl_print_result(FILE *out, IVector *basis, Matrix *A) {
for (int i = 0 ;i < basis->size; i++) {
fprintf(out, "x%i = %lf\n", basis->data[i], A->data[i][0]);
}
}
|
gutachok/lnu_mmoi
|
sympl_utils/sympl_utils.c
|
C
|
apache-2.0
| 3,903
|
/*
* 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.nifi.controller;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.nifi.admin.service.AuditService;
import org.apache.nifi.annotation.behavior.Stateful;
import org.apache.nifi.authorization.AbstractPolicyBasedAuthorizer;
import org.apache.nifi.authorization.AccessPolicy;
import org.apache.nifi.authorization.Group;
import org.apache.nifi.authorization.MockPolicyBasedAuthorizer;
import org.apache.nifi.authorization.RequestAction;
import org.apache.nifi.authorization.User;
import org.apache.nifi.bundle.Bundle;
import org.apache.nifi.bundle.BundleCoordinate;
import org.apache.nifi.cluster.protocol.DataFlow;
import org.apache.nifi.components.PropertyDescriptor;
import org.apache.nifi.controller.exception.ProcessorInstantiationException;
import org.apache.nifi.controller.flow.FlowManager;
import org.apache.nifi.controller.reporting.ReportingTaskInstantiationException;
import org.apache.nifi.controller.repository.FlowFileEventRepository;
import org.apache.nifi.controller.serialization.FlowSynchronizer;
import org.apache.nifi.controller.service.ControllerServiceNode;
import org.apache.nifi.controller.service.mock.DummyProcessor;
import org.apache.nifi.controller.service.mock.DummyReportingTask;
import org.apache.nifi.controller.service.mock.ServiceA;
import org.apache.nifi.controller.service.mock.ServiceB;
import org.apache.nifi.encrypt.StringEncryptor;
import org.apache.nifi.groups.ProcessGroup;
import org.apache.nifi.logging.LogLevel;
import org.apache.nifi.logging.LogRepository;
import org.apache.nifi.logging.LogRepositoryFactory;
import org.apache.nifi.nar.ExtensionDiscoveringManager;
import org.apache.nifi.nar.InstanceClassLoader;
import org.apache.nifi.nar.StandardExtensionDiscoveringManager;
import org.apache.nifi.nar.SystemBundle;
import org.apache.nifi.processor.Relationship;
import org.apache.nifi.provenance.MockProvenanceRepository;
import org.apache.nifi.registry.VariableRegistry;
import org.apache.nifi.registry.flow.FlowRegistryClient;
import org.apache.nifi.registry.variable.FileBasedVariableRegistry;
import org.apache.nifi.reporting.BulletinRepository;
import org.apache.nifi.scheduling.ExecutionNode;
import org.apache.nifi.scheduling.SchedulingStrategy;
import org.apache.nifi.util.NiFiProperties;
import org.apache.nifi.web.api.dto.BundleDTO;
import org.apache.nifi.web.api.dto.ControllerServiceDTO;
import org.apache.nifi.web.api.dto.FlowSnippetDTO;
import org.apache.nifi.web.api.dto.PositionDTO;
import org.apache.nifi.web.api.dto.ProcessorConfigDTO;
import org.apache.nifi.web.api.dto.ProcessorDTO;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class TestFlowController {
private FlowController controller;
private AbstractPolicyBasedAuthorizer authorizer;
private FlowFileEventRepository flowFileEventRepo;
private AuditService auditService;
private StringEncryptor encryptor;
private NiFiProperties nifiProperties;
private Bundle systemBundle;
private BulletinRepository bulletinRepo;
private VariableRegistry variableRegistry;
private volatile String propsFile = "src/test/resources/flowcontrollertest.nifi.properties";
private ExtensionDiscoveringManager extensionManager;
/**
* Utility method which accepts {@link NiFiProperties} object but calls {@link StringEncryptor#createEncryptor(String, String, String)} with extracted properties.
*
* @param nifiProperties the NiFiProperties object
* @return the StringEncryptor
*/
private StringEncryptor createEncryptorFromProperties(NiFiProperties nifiProperties) {
final String algorithm = nifiProperties.getProperty(NiFiProperties.SENSITIVE_PROPS_ALGORITHM);
final String provider = nifiProperties.getProperty(NiFiProperties.SENSITIVE_PROPS_PROVIDER);
final String password = nifiProperties.getProperty(NiFiProperties.SENSITIVE_PROPS_KEY);
return StringEncryptor.createEncryptor(algorithm, provider, password);
}
@Before
public void setup() {
flowFileEventRepo = Mockito.mock(FlowFileEventRepository.class);
auditService = Mockito.mock(AuditService.class);
final Map<String, String> otherProps = new HashMap<>();
otherProps.put(NiFiProperties.PROVENANCE_REPO_IMPLEMENTATION_CLASS, MockProvenanceRepository.class.getName());
otherProps.put("nifi.remote.input.socket.port", "");
otherProps.put("nifi.remote.input.secure", "");
nifiProperties = NiFiProperties.createBasicNiFiProperties(propsFile, otherProps);
encryptor = createEncryptorFromProperties(nifiProperties);
// use the system bundle
systemBundle = SystemBundle.create(nifiProperties);
extensionManager = new StandardExtensionDiscoveringManager();
extensionManager.discoverExtensions(systemBundle, Collections.emptySet());
User user1 = new User.Builder().identifier("user-id-1").identity("user-1").build();
User user2 = new User.Builder().identifier("user-id-2").identity("user-2").build();
Group group1 = new Group.Builder().identifier("group-id-1").name("group-1").addUser(user1.getIdentifier()).build();
Group group2 = new Group.Builder().identifier("group-id-2").name("group-2").build();
AccessPolicy policy1 = new AccessPolicy.Builder()
.identifier("policy-id-1")
.resource("resource1")
.action(RequestAction.READ)
.addUser(user1.getIdentifier())
.addUser(user2.getIdentifier())
.build();
AccessPolicy policy2 = new AccessPolicy.Builder()
.identifier("policy-id-2")
.resource("resource2")
.action(RequestAction.READ)
.addGroup(group1.getIdentifier())
.addGroup(group2.getIdentifier())
.addUser(user1.getIdentifier())
.addUser(user2.getIdentifier())
.build();
Set<Group> groups1 = new LinkedHashSet<>();
groups1.add(group1);
groups1.add(group2);
Set<User> users1 = new LinkedHashSet<>();
users1.add(user1);
users1.add(user2);
Set<AccessPolicy> policies1 = new LinkedHashSet<>();
policies1.add(policy1);
policies1.add(policy2);
authorizer = new MockPolicyBasedAuthorizer(groups1, users1, policies1);
variableRegistry = new FileBasedVariableRegistry(nifiProperties.getVariableRegistryPropertiesPaths());
bulletinRepo = Mockito.mock(BulletinRepository.class);
controller = FlowController.createStandaloneInstance(flowFileEventRepo, nifiProperties, authorizer,
auditService, encryptor, bulletinRepo, variableRegistry, Mockito.mock(FlowRegistryClient.class), extensionManager);
}
@After
public void cleanup() throws Exception {
controller.shutdown(true);
FileUtils.deleteDirectory(new File("./target/flowcontrollertest"));
}
@Test
public void testSynchronizeFlowWithReportingTaskAndProcessorReferencingControllerService() throws IOException {
final FlowSynchronizer standardFlowSynchronizer = new StandardFlowSynchronizer(
createEncryptorFromProperties(nifiProperties), nifiProperties, extensionManager);
// create a mock proposed data flow with the same auth fingerprint as the current authorizer
final String authFingerprint = authorizer.getFingerprint();
final DataFlow proposedDataFlow = Mockito.mock(DataFlow.class);
when(proposedDataFlow.getAuthorizerFingerprint()).thenReturn(authFingerprint.getBytes(StandardCharsets.UTF_8));
final File flowFile = new File("src/test/resources/conf/reporting-task-with-cs-flow-0.7.0.xml");
final String flow = IOUtils.toString(new FileInputStream(flowFile), StandardCharsets.UTF_8);
when(proposedDataFlow.getFlow()).thenReturn(flow.getBytes(StandardCharsets.UTF_8));
controller.synchronize(standardFlowSynchronizer, proposedDataFlow);
// should be two controller services
final Set<ControllerServiceNode> controllerServiceNodes = controller.getFlowManager().getAllControllerServices();
assertNotNull(controllerServiceNodes);
assertEquals(2, controllerServiceNodes.size());
// find the controller service that was moved to the root group
final ControllerServiceNode rootGroupCs = controllerServiceNodes.stream().filter(c -> c.getProcessGroup() != null).findFirst().get();
assertNotNull(rootGroupCs);
// find the controller service that was not moved to the root group
final ControllerServiceNode controllerCs = controllerServiceNodes.stream().filter(c -> c.getProcessGroup() == null).findFirst().get();
assertNotNull(controllerCs);
// should be same class (not Ghost), different ids, and same properties
assertEquals(rootGroupCs.getCanonicalClassName(), controllerCs.getCanonicalClassName());
assertFalse(rootGroupCs.getCanonicalClassName().contains("Ghost"));
assertNotEquals(rootGroupCs.getIdentifier(), controllerCs.getIdentifier());
assertEquals(rootGroupCs.getProperties(), controllerCs.getProperties());
// should be one processor
final Collection<ProcessorNode> processorNodes = controller.getFlowManager().getGroup(controller.getFlowManager().getRootGroupId()).getProcessors();
assertNotNull(processorNodes);
assertEquals(1, processorNodes.size());
// verify the processor is still pointing at the controller service that got moved to the root group
final ProcessorNode processorNode = processorNodes.stream().findFirst().get();
final PropertyDescriptor procControllerServiceProp = processorNode.getProperties().entrySet().stream()
.filter(e -> e.getValue().equals(rootGroupCs.getIdentifier()))
.map(e -> e.getKey())
.findFirst()
.get();
assertNotNull(procControllerServiceProp);
// should be one reporting task
final Set<ReportingTaskNode> reportingTaskNodes = controller.getAllReportingTasks();
assertNotNull(reportingTaskNodes);
assertEquals(1, reportingTaskNodes.size());
// verify that the reporting task is pointing at the controller service at the controller level
final ReportingTaskNode reportingTaskNode = reportingTaskNodes.stream().findFirst().get();
final PropertyDescriptor reportingTaskControllerServiceProp = reportingTaskNode.getProperties().entrySet().stream()
.filter(e -> e.getValue().equals(controllerCs.getIdentifier()))
.map(e -> e.getKey())
.findFirst()
.get();
assertNotNull(reportingTaskControllerServiceProp);
}
@Test
public void testSynchronizeFlowWithProcessorReferencingControllerService() throws IOException {
final FlowSynchronizer standardFlowSynchronizer = new StandardFlowSynchronizer(
createEncryptorFromProperties(nifiProperties), nifiProperties, extensionManager);
// create a mock proposed data flow with the same auth fingerprint as the current authorizer
final String authFingerprint = authorizer.getFingerprint();
final DataFlow proposedDataFlow = Mockito.mock(DataFlow.class);
when(proposedDataFlow.getAuthorizerFingerprint()).thenReturn(authFingerprint.getBytes(StandardCharsets.UTF_8));
final File flowFile = new File("src/test/resources/conf/processor-with-cs-flow-0.7.0.xml");
final String flow = IOUtils.toString(new FileInputStream(flowFile), StandardCharsets.UTF_8);
when(proposedDataFlow.getFlow()).thenReturn(flow.getBytes(StandardCharsets.UTF_8));
controller.synchronize(standardFlowSynchronizer, proposedDataFlow);
// should be two controller services
final Set<ControllerServiceNode> controllerServiceNodes = controller.getFlowManager().getAllControllerServices();
assertNotNull(controllerServiceNodes);
assertEquals(1, controllerServiceNodes.size());
// find the controller service that was moved to the root group
final ControllerServiceNode rootGroupCs = controllerServiceNodes.stream().filter(c -> c.getProcessGroup() != null).findFirst().get();
assertNotNull(rootGroupCs);
// should be one processor
final Collection<ProcessorNode> processorNodes = controller.getFlowManager().getRootGroup().getProcessors();
assertNotNull(processorNodes);
assertEquals(1, processorNodes.size());
// verify the processor is still pointing at the controller service that got moved to the root group
final ProcessorNode processorNode = processorNodes.stream().findFirst().get();
final PropertyDescriptor procControllerServiceProp = processorNode.getProperties().entrySet().stream()
.filter(e -> e.getValue().equals(rootGroupCs.getIdentifier()))
.map(e -> e.getKey())
.findFirst()
.get();
assertNotNull(procControllerServiceProp);
}
@Test
public void testSynchronizeFlowWhenAuthorizationsAreEqual() {
final FlowSynchronizer standardFlowSynchronizer = new StandardFlowSynchronizer(
createEncryptorFromProperties(nifiProperties), nifiProperties, extensionManager);
// create a mock proposed data flow with the same auth fingerprint as the current authorizer
final String authFingerprint = authorizer.getFingerprint();
final DataFlow proposedDataFlow = Mockito.mock(DataFlow.class);
when(proposedDataFlow.getAuthorizerFingerprint()).thenReturn(authFingerprint.getBytes(StandardCharsets.UTF_8));
controller.synchronize(standardFlowSynchronizer, proposedDataFlow);
assertEquals(authFingerprint, authorizer.getFingerprint());
}
@Test(expected = UninheritableFlowException.class)
public void testSynchronizeFlowWhenAuthorizationsAreDifferent() {
final FlowSynchronizer standardFlowSynchronizer = new StandardFlowSynchronizer(
createEncryptorFromProperties(nifiProperties), nifiProperties, extensionManager);
// create a mock proposed data flow with different auth fingerprint as the current authorizer
final String authFingerprint = "<authorizations></authorizations>";
final DataFlow proposedDataFlow = Mockito.mock(DataFlow.class);
when(proposedDataFlow.getAuthorizerFingerprint()).thenReturn(authFingerprint.getBytes(StandardCharsets.UTF_8));
controller.synchronize(standardFlowSynchronizer, proposedDataFlow);
assertNotEquals(authFingerprint, authorizer.getFingerprint());
}
@Test(expected = UninheritableFlowException.class)
public void testSynchronizeFlowWhenProposedAuthorizationsAreNull() {
final FlowSynchronizer standardFlowSynchronizer = new StandardFlowSynchronizer(
createEncryptorFromProperties(nifiProperties), nifiProperties, extensionManager);
final DataFlow proposedDataFlow = Mockito.mock(DataFlow.class);
when(proposedDataFlow.getAuthorizerFingerprint()).thenReturn(null);
controller.synchronize(standardFlowSynchronizer, proposedDataFlow);
}
@Test
public void testSynchronizeFlowWhenCurrentAuthorizationsAreEmptyAndProposedAreNot() {
final FlowSynchronizer standardFlowSynchronizer = new StandardFlowSynchronizer(
createEncryptorFromProperties(nifiProperties), nifiProperties, extensionManager);
// create a mock proposed data flow with the same auth fingerprint as the current authorizer
final String authFingerprint = authorizer.getFingerprint();
final DataFlow proposedDataFlow = Mockito.mock(DataFlow.class);
when(proposedDataFlow.getAuthorizerFingerprint()).thenReturn(authFingerprint.getBytes(StandardCharsets.UTF_8));
authorizer = new MockPolicyBasedAuthorizer();
assertNotEquals(authFingerprint, authorizer.getFingerprint());
controller.shutdown(true);
controller = FlowController.createStandaloneInstance(flowFileEventRepo, nifiProperties, authorizer,
auditService, encryptor, bulletinRepo, variableRegistry, Mockito.mock(FlowRegistryClient.class), extensionManager);
controller.synchronize(standardFlowSynchronizer, proposedDataFlow);
assertEquals(authFingerprint, authorizer.getFingerprint());
}
@Test
public void testSynchronizeFlowWhenProposedMissingComponentsAreDifferent() {
final FlowSynchronizer standardFlowSynchronizer = new StandardFlowSynchronizer(
createEncryptorFromProperties(nifiProperties), nifiProperties, extensionManager);
final Set<String> missingComponents = new HashSet<>();
missingComponents.add("1");
missingComponents.add("2");
final DataFlow proposedDataFlow = Mockito.mock(DataFlow.class);
when(proposedDataFlow.getMissingComponents()).thenReturn(missingComponents);
try {
controller.synchronize(standardFlowSynchronizer, proposedDataFlow);
Assert.fail("Should have thrown exception");
} catch (UninheritableFlowException e) {
assertTrue(e.getMessage().contains("Proposed flow has missing components that are not considered missing in the current flow (1,2)"));
}
}
@Test
public void testSynchronizeFlowWhenExistingMissingComponentsAreDifferent() throws IOException {
final StringEncryptor stringEncryptor = createEncryptorFromProperties(nifiProperties);
final FlowSynchronizer standardFlowSynchronizer = new StandardFlowSynchronizer(stringEncryptor, nifiProperties, extensionManager);
final ProcessorNode mockProcessorNode = mock(ProcessorNode.class);
when(mockProcessorNode.getIdentifier()).thenReturn("1");
when(mockProcessorNode.isExtensionMissing()).thenReturn(true);
final ControllerServiceNode mockControllerServiceNode = mock(ControllerServiceNode.class);
when(mockControllerServiceNode.getIdentifier()).thenReturn("2");
when(mockControllerServiceNode.isExtensionMissing()).thenReturn(true);
final ReportingTaskNode mockReportingTaskNode = mock(ReportingTaskNode.class);
when(mockReportingTaskNode.getIdentifier()).thenReturn("3");
when(mockReportingTaskNode.isExtensionMissing()).thenReturn(true);
final ProcessGroup mockRootGroup = mock(ProcessGroup.class);
when(mockRootGroup.findAllProcessors()).thenReturn(Collections.singletonList(mockProcessorNode));
final SnippetManager mockSnippetManager = mock(SnippetManager.class);
when(mockSnippetManager.export()).thenReturn(new byte[0]);
final FlowManager flowManager = Mockito.mock(FlowManager.class);
final FlowController mockFlowController = mock(FlowController.class);
when(mockFlowController.getFlowManager()).thenReturn(flowManager);
when(flowManager.getRootGroup()).thenReturn(mockRootGroup);
when(flowManager.getAllControllerServices()).thenReturn(new HashSet<>(Arrays.asList(mockControllerServiceNode)));
when(flowManager.getAllReportingTasks()).thenReturn(new HashSet<>(Arrays.asList(mockReportingTaskNode)));
when(mockFlowController.getAuthorizer()).thenReturn(authorizer);
when(mockFlowController.getSnippetManager()).thenReturn(mockSnippetManager);
final DataFlow proposedDataFlow = Mockito.mock(DataFlow.class);
when(proposedDataFlow.getMissingComponents()).thenReturn(new HashSet<>());
try {
standardFlowSynchronizer.sync(mockFlowController, proposedDataFlow, stringEncryptor);
Assert.fail("Should have thrown exception");
} catch (UninheritableFlowException e) {
assertTrue(e.getMessage(), e.getMessage().contains("Current flow has missing components that are not considered missing in the proposed flow (1,2,3)"));
}
}
@Test
public void testSynchronizeFlowWhenBundlesAreSame() throws IOException {
final FlowSynchronizer standardFlowSynchronizer = new StandardFlowSynchronizer(
createEncryptorFromProperties(nifiProperties), nifiProperties, extensionManager);
final LogRepository logRepository = LogRepositoryFactory.getRepository("d89ada5d-35fb-44ff-83f1-4cc00b48b2df");
logRepository.removeAllObservers();
syncFlow("src/test/resources/nifi/fingerprint/flow4.xml", standardFlowSynchronizer);
syncFlow("src/test/resources/nifi/fingerprint/flow4.xml", standardFlowSynchronizer);
}
@Test
public void testSynchronizeFlowWhenBundlesAreDifferent() throws IOException {
final FlowSynchronizer standardFlowSynchronizer = new StandardFlowSynchronizer(
createEncryptorFromProperties(nifiProperties), nifiProperties, extensionManager);
final LogRepository logRepository = LogRepositoryFactory.getRepository("d89ada5d-35fb-44ff-83f1-4cc00b48b2df");
logRepository.removeAllObservers();
// first sync should work because we are syncing to an empty flow controller
syncFlow("src/test/resources/nifi/fingerprint/flow4.xml", standardFlowSynchronizer);
// second sync should fail because the bundle of the processor is different
try {
syncFlow("src/test/resources/nifi/fingerprint/flow4-with-different-bundle.xml", standardFlowSynchronizer);
Assert.fail("Should have thrown UninheritableFlowException");
} catch (UninheritableFlowException e) {
//e.printStackTrace();
}
}
private void syncFlow(String flowXmlFile, FlowSynchronizer standardFlowSynchronizer) throws IOException {
String flowString = null;
try (final InputStream in = new FileInputStream(flowXmlFile)) {
flowString = IOUtils.toString(in, StandardCharsets.UTF_8);
}
assertNotNull(flowString);
final DataFlow proposedDataFlow1 = Mockito.mock(DataFlow.class);
when(proposedDataFlow1.getFlow()).thenReturn(flowString.getBytes(StandardCharsets.UTF_8));
final String authFingerprint = authorizer.getFingerprint();
when(proposedDataFlow1.getAuthorizerFingerprint()).thenReturn(authFingerprint.getBytes(StandardCharsets.UTF_8));
controller.synchronize(standardFlowSynchronizer, proposedDataFlow1);
}
@Test
public void testCreateMissingProcessor() throws ProcessorInstantiationException {
final ProcessorNode procNode = controller.getFlowManager().createProcessor("org.apache.nifi.NonExistingProcessor", "1234-Processor",
systemBundle.getBundleDetails().getCoordinate());
assertNotNull(procNode);
assertEquals("org.apache.nifi.NonExistingProcessor", procNode.getCanonicalClassName());
assertEquals("(Missing) NonExistingProcessor", procNode.getComponentType());
final PropertyDescriptor descriptor = procNode.getPropertyDescriptor("my descriptor");
assertNotNull(descriptor);
assertEquals("my descriptor", descriptor.getName());
assertTrue(descriptor.isRequired());
assertTrue(descriptor.isSensitive());
final Relationship relationship = procNode.getRelationship("my relationship");
assertEquals("my relationship", relationship.getName());
}
@Test
public void testCreateMissingReportingTask() throws ReportingTaskInstantiationException {
final ReportingTaskNode taskNode = controller.createReportingTask("org.apache.nifi.NonExistingReportingTask", "1234-Reporting-Task",
systemBundle.getBundleDetails().getCoordinate(), true);
assertNotNull(taskNode);
assertEquals("org.apache.nifi.NonExistingReportingTask", taskNode.getCanonicalClassName());
assertEquals("(Missing) NonExistingReportingTask", taskNode.getComponentType());
final PropertyDescriptor descriptor = taskNode.getReportingTask().getPropertyDescriptor("my descriptor");
assertNotNull(descriptor);
assertEquals("my descriptor", descriptor.getName());
assertTrue(descriptor.isRequired());
assertTrue(descriptor.isSensitive());
}
@Test
public void testCreateMissingControllerService() throws ProcessorInstantiationException {
final ControllerServiceNode serviceNode = controller.getFlowManager().createControllerService("org.apache.nifi.NonExistingControllerService", "1234-Controller-Service",
systemBundle.getBundleDetails().getCoordinate(), null, false, true);
assertNotNull(serviceNode);
assertEquals("org.apache.nifi.NonExistingControllerService", serviceNode.getCanonicalClassName());
assertEquals("(Missing) NonExistingControllerService", serviceNode.getComponentType());
final ControllerService service = serviceNode.getControllerServiceImplementation();
final PropertyDescriptor descriptor = service.getPropertyDescriptor("my descriptor");
assertNotNull(descriptor);
assertEquals("my descriptor", descriptor.getName());
assertTrue(descriptor.isRequired());
assertTrue(descriptor.isSensitive());
assertEquals("GhostControllerService[id=1234-Controller-Service, type=org.apache.nifi.NonExistingControllerService]", service.toString());
service.hashCode(); // just make sure that an Exception is not thrown
assertTrue(service.equals(service));
assertFalse(service.equals(serviceNode));
}
@Test
public void testProcessorDefaultScheduleAnnotation() throws ProcessorInstantiationException, ClassNotFoundException, InstantiationException, IllegalAccessException {
ProcessorNode p_scheduled = controller.getFlowManager().createProcessor(DummyScheduledProcessor.class.getName(), "1234-ScheduledProcessor",
systemBundle.getBundleDetails().getCoordinate());
assertEquals(5, p_scheduled.getMaxConcurrentTasks());
assertEquals(SchedulingStrategy.CRON_DRIVEN, p_scheduled.getSchedulingStrategy());
assertEquals("0 0 0 1/1 * ?", p_scheduled.getSchedulingPeriod());
assertEquals("1 sec", p_scheduled.getYieldPeriod());
assertEquals("30 sec", p_scheduled.getPenalizationPeriod());
assertEquals(LogLevel.WARN, p_scheduled.getBulletinLevel());
}
@Test
public void testReportingTaskDefaultScheduleAnnotation() throws ReportingTaskInstantiationException {
ReportingTaskNode p_scheduled = controller.getFlowManager().createReportingTask(DummyScheduledReportingTask.class.getName(), systemBundle.getBundleDetails().getCoordinate());
assertEquals(SchedulingStrategy.CRON_DRIVEN, p_scheduled.getSchedulingStrategy());
assertEquals("0 0 0 1/1 * ?", p_scheduled.getSchedulingPeriod());
}
@Test
public void testProcessorDefaultSettingsAnnotation() throws ProcessorInstantiationException, ClassNotFoundException {
ProcessorNode p_settings = controller.getFlowManager().createProcessor(DummySettingsProcessor.class.getName(), "1234-SettingsProcessor", systemBundle.getBundleDetails().getCoordinate());
assertEquals("5 sec", p_settings.getYieldPeriod());
assertEquals("1 min", p_settings.getPenalizationPeriod());
assertEquals(LogLevel.DEBUG, p_settings.getBulletinLevel());
assertEquals(1, p_settings.getMaxConcurrentTasks());
assertEquals(SchedulingStrategy.TIMER_DRIVEN, p_settings.getSchedulingStrategy());
assertEquals("0 sec", p_settings.getSchedulingPeriod());
}
@Test
public void testPrimaryNodeOnlyAnnotation() throws ProcessorInstantiationException {
String id = UUID.randomUUID().toString();
ProcessorNode processorNode = controller.getFlowManager().createProcessor(DummyPrimaryNodeOnlyProcessor.class.getName(), id, systemBundle.getBundleDetails().getCoordinate());
assertEquals(ExecutionNode.PRIMARY, processorNode.getExecutionNode());
}
@Test
public void testDeleteProcessGroup() {
ProcessGroup pg = controller.getFlowManager().createProcessGroup("my-process-group");
pg.setName("my-process-group");
ControllerServiceNode cs = controller.getFlowManager().createControllerService("org.apache.nifi.NonExistingControllerService", "my-controller-service",
systemBundle.getBundleDetails().getCoordinate(), null, false, true);
pg.addControllerService(cs);
controller.getFlowManager().getRootGroup().addProcessGroup(pg);
controller.getFlowManager().getRootGroup().removeProcessGroup(pg);
pg.getControllerServices(true);
assertTrue(pg.getControllerServices(true).isEmpty());
}
@Test
public void testReloadProcessor() throws ProcessorInstantiationException {
final String id = "1234-ScheduledProcessor" + System.currentTimeMillis();
final BundleCoordinate coordinate = systemBundle.getBundleDetails().getCoordinate();
final ProcessorNode processorNode = controller.getFlowManager().createProcessor(DummyScheduledProcessor.class.getName(), id, coordinate);
final String originalName = processorNode.getName();
assertEquals(id, processorNode.getIdentifier());
assertEquals(id, processorNode.getComponent().getIdentifier());
assertEquals(coordinate.getCoordinate(), processorNode.getBundleCoordinate().getCoordinate());
assertEquals(DummyScheduledProcessor.class.getCanonicalName(), processorNode.getCanonicalClassName());
assertEquals(DummyScheduledProcessor.class.getSimpleName(), processorNode.getComponentType());
assertEquals(DummyScheduledProcessor.class.getCanonicalName(), processorNode.getComponent().getClass().getCanonicalName());
assertEquals(5, processorNode.getMaxConcurrentTasks());
assertEquals(SchedulingStrategy.CRON_DRIVEN, processorNode.getSchedulingStrategy());
assertEquals("0 0 0 1/1 * ?", processorNode.getSchedulingPeriod());
assertEquals("1 sec", processorNode.getYieldPeriod());
assertEquals("30 sec", processorNode.getPenalizationPeriod());
assertEquals(LogLevel.WARN, processorNode.getBulletinLevel());
// now change the type of the processor from DummyScheduledProcessor to DummySettingsProcessor
controller.getReloadComponent().reload(processorNode, DummySettingsProcessor.class.getName(), coordinate, Collections.emptySet());
// ids and coordinate should stay the same
assertEquals(id, processorNode.getIdentifier());
assertEquals(id, processorNode.getComponent().getIdentifier());
assertEquals(coordinate.getCoordinate(), processorNode.getBundleCoordinate().getCoordinate());
// in this test we happened to change between two processors that have different canonical class names
// but in the running application the DAO layer would call verifyCanUpdateBundle and would prevent this so
// for the sake of this test it is ok that the canonical class name hasn't changed
assertEquals(originalName, processorNode.getName());
assertEquals(DummyScheduledProcessor.class.getCanonicalName(), processorNode.getCanonicalClassName());
assertEquals(DummyScheduledProcessor.class.getSimpleName(), processorNode.getComponentType());
assertEquals(DummySettingsProcessor.class.getCanonicalName(), processorNode.getComponent().getClass().getCanonicalName());
// all these settings should have stayed the same
assertEquals(5, processorNode.getMaxConcurrentTasks());
assertEquals(SchedulingStrategy.CRON_DRIVEN, processorNode.getSchedulingStrategy());
assertEquals("0 0 0 1/1 * ?", processorNode.getSchedulingPeriod());
assertEquals("1 sec", processorNode.getYieldPeriod());
assertEquals("30 sec", processorNode.getPenalizationPeriod());
assertEquals(LogLevel.WARN, processorNode.getBulletinLevel());
}
@Test
public void testReloadProcessorWithAdditionalResources() throws ProcessorInstantiationException, MalformedURLException {
final URL resource1 = new File("src/test/resources/TestClasspathResources/resource1.txt").toURI().toURL();
final URL resource2 = new File("src/test/resources/TestClasspathResources/resource2.txt").toURI().toURL();
final URL resource3 = new File("src/test/resources/TestClasspathResources/resource3.txt").toURI().toURL();
final Set<URL> additionalUrls = new LinkedHashSet<>(Arrays.asList(resource1, resource2, resource3));
final String id = "1234-ScheduledProcessor" + System.currentTimeMillis();
final BundleCoordinate coordinate = systemBundle.getBundleDetails().getCoordinate();
final ProcessorNode processorNode = controller.getFlowManager().createProcessor(DummyScheduledProcessor.class.getName(), id, coordinate);
final String originalName = processorNode.getName();
// the instance class loader shouldn't have any of the resources yet
InstanceClassLoader instanceClassLoader = extensionManager.getInstanceClassLoader(id);
assertNotNull(instanceClassLoader);
assertFalse(containsResource(instanceClassLoader.getURLs(), resource1));
assertFalse(containsResource(instanceClassLoader.getURLs(), resource2));
assertFalse(containsResource(instanceClassLoader.getURLs(), resource3));
assertTrue(instanceClassLoader.getAdditionalResourceUrls().isEmpty());
// now change the type of the processor from DummyScheduledProcessor to DummySettingsProcessor
controller.getReloadComponent().reload(processorNode, DummySettingsProcessor.class.getName(), coordinate, additionalUrls);
// the instance class loader shouldn't have any of the resources yet
instanceClassLoader = extensionManager.getInstanceClassLoader(id);
assertNotNull(instanceClassLoader);
assertTrue(containsResource(instanceClassLoader.getURLs(), resource1));
assertTrue(containsResource(instanceClassLoader.getURLs(), resource2));
assertTrue(containsResource(instanceClassLoader.getURLs(), resource3));
assertEquals(3, instanceClassLoader.getAdditionalResourceUrls().size());
}
@Test
public void testReloadControllerService() {
final String id = "ServiceA" + System.currentTimeMillis();
final BundleCoordinate coordinate = systemBundle.getBundleDetails().getCoordinate();
final ControllerServiceNode controllerServiceNode = controller.getFlowManager().createControllerService(ServiceA.class.getName(), id, coordinate, null, true, true);
final String originalName = controllerServiceNode.getName();
assertEquals(id, controllerServiceNode.getIdentifier());
assertEquals(id, controllerServiceNode.getComponent().getIdentifier());
assertEquals(coordinate.getCoordinate(), controllerServiceNode.getBundleCoordinate().getCoordinate());
assertEquals(ServiceA.class.getCanonicalName(), controllerServiceNode.getCanonicalClassName());
assertEquals(ServiceA.class.getSimpleName(), controllerServiceNode.getComponentType());
assertEquals(ServiceA.class.getCanonicalName(), controllerServiceNode.getComponent().getClass().getCanonicalName());
controller.getReloadComponent().reload(controllerServiceNode, ServiceB.class.getName(), coordinate, Collections.emptySet());
// ids and coordinate should stay the same
assertEquals(id, controllerServiceNode.getIdentifier());
assertEquals(id, controllerServiceNode.getComponent().getIdentifier());
assertEquals(coordinate.getCoordinate(), controllerServiceNode.getBundleCoordinate().getCoordinate());
// in this test we happened to change between two services that have different canonical class names
// but in the running application the DAO layer would call verifyCanUpdateBundle and would prevent this so
// for the sake of this test it is ok that the canonical class name hasn't changed
assertEquals(originalName, controllerServiceNode.getName());
assertEquals(ServiceA.class.getCanonicalName(), controllerServiceNode.getCanonicalClassName());
assertEquals(ServiceA.class.getSimpleName(), controllerServiceNode.getComponentType());
assertEquals(ServiceB.class.getCanonicalName(), controllerServiceNode.getComponent().getClass().getCanonicalName());
}
@Test
public void testReloadControllerServiceWithAdditionalResources() throws MalformedURLException {
final URL resource1 = new File("src/test/resources/TestClasspathResources/resource1.txt").toURI().toURL();
final URL resource2 = new File("src/test/resources/TestClasspathResources/resource2.txt").toURI().toURL();
final URL resource3 = new File("src/test/resources/TestClasspathResources/resource3.txt").toURI().toURL();
final Set<URL> additionalUrls = new LinkedHashSet<>(Arrays.asList(resource1, resource2, resource3));
final String id = "ServiceA" + System.currentTimeMillis();
final BundleCoordinate coordinate = systemBundle.getBundleDetails().getCoordinate();
final ControllerServiceNode controllerServiceNode = controller.getFlowManager().createControllerService(ServiceA.class.getName(), id, coordinate, null, true, true);
// the instance class loader shouldn't have any of the resources yet
URLClassLoader instanceClassLoader = extensionManager.getInstanceClassLoader(id);
assertNotNull(instanceClassLoader);
assertFalse(containsResource(instanceClassLoader.getURLs(), resource1));
assertFalse(containsResource(instanceClassLoader.getURLs(), resource2));
assertFalse(containsResource(instanceClassLoader.getURLs(), resource3));
assertTrue(instanceClassLoader instanceof InstanceClassLoader);
assertTrue(((InstanceClassLoader) instanceClassLoader).getAdditionalResourceUrls().isEmpty());
controller.getReloadComponent().reload(controllerServiceNode, ServiceB.class.getName(), coordinate, additionalUrls);
// the instance class loader shouldn't have any of the resources yet
instanceClassLoader = extensionManager.getInstanceClassLoader(id);
assertNotNull(instanceClassLoader);
assertTrue(containsResource(instanceClassLoader.getURLs(), resource1));
assertTrue(containsResource(instanceClassLoader.getURLs(), resource2));
assertTrue(containsResource(instanceClassLoader.getURLs(), resource3));
assertTrue(instanceClassLoader instanceof InstanceClassLoader);
assertEquals(3, ((InstanceClassLoader) instanceClassLoader).getAdditionalResourceUrls().size());
}
@Test
public void testReloadReportingTask() throws ReportingTaskInstantiationException {
final String id = "ReportingTask" + System.currentTimeMillis();
final BundleCoordinate coordinate = systemBundle.getBundleDetails().getCoordinate();
final ReportingTaskNode node = controller.createReportingTask(DummyReportingTask.class.getName(), id, coordinate, true);
final String originalName = node.getName();
assertEquals(id, node.getIdentifier());
assertEquals(id, node.getComponent().getIdentifier());
assertEquals(coordinate.getCoordinate(), node.getBundleCoordinate().getCoordinate());
assertEquals(DummyReportingTask.class.getCanonicalName(), node.getCanonicalClassName());
assertEquals(DummyReportingTask.class.getSimpleName(), node.getComponentType());
assertEquals(DummyReportingTask.class.getCanonicalName(), node.getComponent().getClass().getCanonicalName());
controller.getReloadComponent().reload(node, DummyScheduledReportingTask.class.getName(), coordinate, Collections.emptySet());
// ids and coordinate should stay the same
assertEquals(id, node.getIdentifier());
assertEquals(id, node.getComponent().getIdentifier());
assertEquals(coordinate.getCoordinate(), node.getBundleCoordinate().getCoordinate());
// in this test we happened to change between two services that have different canonical class names
// but in the running application the DAO layer would call verifyCanUpdateBundle and would prevent this so
// for the sake of this test it is ok that the canonical class name hasn't changed
assertEquals(originalName, node.getName());
assertEquals(DummyReportingTask.class.getCanonicalName(), node.getCanonicalClassName());
assertEquals(DummyReportingTask.class.getSimpleName(), node.getComponentType());
assertEquals(DummyScheduledReportingTask.class.getCanonicalName(), node.getComponent().getClass().getCanonicalName());
}
@Test
public void testReloadReportingTaskWithAdditionalResources() throws ReportingTaskInstantiationException, MalformedURLException {
final URL resource1 = new File("src/test/resources/TestClasspathResources/resource1.txt").toURI().toURL();
final URL resource2 = new File("src/test/resources/TestClasspathResources/resource2.txt").toURI().toURL();
final URL resource3 = new File("src/test/resources/TestClasspathResources/resource3.txt").toURI().toURL();
final Set<URL> additionalUrls = new LinkedHashSet<>(Arrays.asList(resource1, resource2, resource3));
final String id = "ReportingTask" + System.currentTimeMillis();
final BundleCoordinate coordinate = systemBundle.getBundleDetails().getCoordinate();
final ReportingTaskNode node = controller.createReportingTask(DummyReportingTask.class.getName(), id, coordinate, true);
// the instance class loader shouldn't have any of the resources yet
InstanceClassLoader instanceClassLoader = extensionManager.getInstanceClassLoader(id);
assertNotNull(instanceClassLoader);
assertFalse(containsResource(instanceClassLoader.getURLs(), resource1));
assertFalse(containsResource(instanceClassLoader.getURLs(), resource2));
assertFalse(containsResource(instanceClassLoader.getURLs(), resource3));
assertTrue(instanceClassLoader.getAdditionalResourceUrls().isEmpty());
controller.getReloadComponent().reload(node, DummyScheduledReportingTask.class.getName(), coordinate, additionalUrls);
// the instance class loader shouldn't have any of the resources yet
instanceClassLoader = extensionManager.getInstanceClassLoader(id);
assertNotNull(instanceClassLoader);
assertTrue(containsResource(instanceClassLoader.getURLs(), resource1));
assertTrue(containsResource(instanceClassLoader.getURLs(), resource2));
assertTrue(containsResource(instanceClassLoader.getURLs(), resource3));
assertEquals(3, instanceClassLoader.getAdditionalResourceUrls().size());
}
private boolean containsResource(URL[] resources, URL resourceToFind) {
for (URL resource : resources) {
if (resourceToFind.getPath().equals(resource.getPath())) {
return true;
}
}
return false;
}
@Test(expected = IllegalArgumentException.class)
public void testInstantiateSnippetWhenProcessorMissingBundle() throws Exception {
final String id = UUID.randomUUID().toString();
final BundleCoordinate coordinate = systemBundle.getBundleDetails().getCoordinate();
final ProcessorNode processorNode = controller.getFlowManager().createProcessor(DummyProcessor.class.getName(), id, coordinate);
// create a processor dto
final ProcessorDTO processorDTO = new ProcessorDTO();
processorDTO.setId(UUID.randomUUID().toString()); // use a different id here
processorDTO.setPosition(new PositionDTO(new Double(0), new Double(0)));
processorDTO.setStyle(processorNode.getStyle());
processorDTO.setParentGroupId("1234");
processorDTO.setInputRequirement(processorNode.getInputRequirement().name());
processorDTO.setPersistsState(processorNode.getProcessor().getClass().isAnnotationPresent(Stateful.class));
processorDTO.setRestricted(processorNode.isRestricted());
processorDTO.setExecutionNodeRestricted(processorNode.isExecutionNodeRestricted());
processorDTO.setExtensionMissing(processorNode.isExtensionMissing());
processorDTO.setType(processorNode.getCanonicalClassName());
processorDTO.setBundle(null); // missing bundle
processorDTO.setName(processorNode.getName());
processorDTO.setState(processorNode.getScheduledState().toString());
processorDTO.setRelationships(new ArrayList<>());
processorDTO.setDescription("description");
processorDTO.setSupportsParallelProcessing(!processorNode.isTriggeredSerially());
processorDTO.setSupportsEventDriven(processorNode.isEventDrivenSupported());
processorDTO.setSupportsBatching(processorNode.isSessionBatchingSupported());
ProcessorConfigDTO configDTO = new ProcessorConfigDTO();
configDTO.setSchedulingPeriod(processorNode.getSchedulingPeriod());
configDTO.setPenaltyDuration(processorNode.getPenalizationPeriod());
configDTO.setYieldDuration(processorNode.getYieldPeriod());
configDTO.setRunDurationMillis(processorNode.getRunDuration(TimeUnit.MILLISECONDS));
configDTO.setConcurrentlySchedulableTaskCount(processorNode.getMaxConcurrentTasks());
configDTO.setLossTolerant(processorNode.isLossTolerant());
configDTO.setComments(processorNode.getComments());
configDTO.setBulletinLevel(processorNode.getBulletinLevel().name());
configDTO.setSchedulingStrategy(processorNode.getSchedulingStrategy().name());
configDTO.setExecutionNode(processorNode.getExecutionNode().name());
configDTO.setAnnotationData(processorNode.getAnnotationData());
processorDTO.setConfig(configDTO);
// create the snippet with the processor
final FlowSnippetDTO flowSnippetDTO = new FlowSnippetDTO();
flowSnippetDTO.setProcessors(Collections.singleton(processorDTO));
// instantiate the snippet
assertEquals(0, controller.getFlowManager().getRootGroup().getProcessors().size());
controller.getFlowManager().instantiateSnippet(controller.getFlowManager().getRootGroup(), flowSnippetDTO);
}
@Test
public void testInstantiateSnippetWithProcessor() throws ProcessorInstantiationException {
final String id = UUID.randomUUID().toString();
final BundleCoordinate coordinate = systemBundle.getBundleDetails().getCoordinate();
final ProcessorNode processorNode = controller.getFlowManager().createProcessor(DummyProcessor.class.getName(), id, coordinate);
// create a processor dto
final ProcessorDTO processorDTO = new ProcessorDTO();
processorDTO.setId(UUID.randomUUID().toString()); // use a different id here
processorDTO.setPosition(new PositionDTO(new Double(0), new Double(0)));
processorDTO.setStyle(processorNode.getStyle());
processorDTO.setParentGroupId("1234");
processorDTO.setInputRequirement(processorNode.getInputRequirement().name());
processorDTO.setPersistsState(processorNode.getProcessor().getClass().isAnnotationPresent(Stateful.class));
processorDTO.setRestricted(processorNode.isRestricted());
processorDTO.setExecutionNodeRestricted(processorNode.isExecutionNodeRestricted());
processorDTO.setExtensionMissing(processorNode.isExtensionMissing());
processorDTO.setType(processorNode.getCanonicalClassName());
processorDTO.setBundle(new BundleDTO(coordinate.getGroup(), coordinate.getId(), coordinate.getVersion()));
processorDTO.setName(processorNode.getName());
processorDTO.setState(processorNode.getScheduledState().toString());
processorDTO.setRelationships(new ArrayList<>());
processorDTO.setDescription("description");
processorDTO.setSupportsParallelProcessing(!processorNode.isTriggeredSerially());
processorDTO.setSupportsEventDriven(processorNode.isEventDrivenSupported());
processorDTO.setSupportsBatching(processorNode.isSessionBatchingSupported());
ProcessorConfigDTO configDTO = new ProcessorConfigDTO();
configDTO.setSchedulingPeriod(processorNode.getSchedulingPeriod());
configDTO.setPenaltyDuration(processorNode.getPenalizationPeriod());
configDTO.setYieldDuration(processorNode.getYieldPeriod());
configDTO.setRunDurationMillis(processorNode.getRunDuration(TimeUnit.MILLISECONDS));
configDTO.setConcurrentlySchedulableTaskCount(processorNode.getMaxConcurrentTasks());
configDTO.setLossTolerant(processorNode.isLossTolerant());
configDTO.setComments(processorNode.getComments());
configDTO.setBulletinLevel(processorNode.getBulletinLevel().name());
configDTO.setSchedulingStrategy(processorNode.getSchedulingStrategy().name());
configDTO.setExecutionNode(processorNode.getExecutionNode().name());
configDTO.setAnnotationData(processorNode.getAnnotationData());
processorDTO.setConfig(configDTO);
// create the snippet with the processor
final FlowSnippetDTO flowSnippetDTO = new FlowSnippetDTO();
flowSnippetDTO.setProcessors(Collections.singleton(processorDTO));
// instantiate the snippet
assertEquals(0, controller.getFlowManager().getRootGroup().getProcessors().size());
controller.getFlowManager().instantiateSnippet(controller.getFlowManager().getRootGroup(), flowSnippetDTO);
assertEquals(1, controller.getFlowManager().getRootGroup().getProcessors().size());
}
@Test
public void testInstantiateSnippetWithDisabledProcessor() throws ProcessorInstantiationException {
final String id = UUID.randomUUID().toString();
final BundleCoordinate coordinate = systemBundle.getBundleDetails().getCoordinate();
final ProcessorNode processorNode = controller.getFlowManager().createProcessor(DummyProcessor.class.getName(), id, coordinate);
processorNode.disable();
// create a processor dto
final ProcessorDTO processorDTO = new ProcessorDTO();
processorDTO.setId(UUID.randomUUID().toString()); // use a different id here
processorDTO.setPosition(new PositionDTO(new Double(0), new Double(0)));
processorDTO.setStyle(processorNode.getStyle());
processorDTO.setParentGroupId("1234");
processorDTO.setInputRequirement(processorNode.getInputRequirement().name());
processorDTO.setPersistsState(processorNode.getProcessor().getClass().isAnnotationPresent(Stateful.class));
processorDTO.setRestricted(processorNode.isRestricted());
processorDTO.setExecutionNodeRestricted(processorNode.isExecutionNodeRestricted());
processorDTO.setExtensionMissing(processorNode.isExtensionMissing());
processorDTO.setType(processorNode.getCanonicalClassName());
processorDTO.setBundle(new BundleDTO(coordinate.getGroup(), coordinate.getId(), coordinate.getVersion()));
processorDTO.setName(processorNode.getName());
processorDTO.setState(processorNode.getScheduledState().toString());
processorDTO.setRelationships(new ArrayList<>());
processorDTO.setDescription("description");
processorDTO.setSupportsParallelProcessing(!processorNode.isTriggeredSerially());
processorDTO.setSupportsEventDriven(processorNode.isEventDrivenSupported());
processorDTO.setSupportsBatching(processorNode.isSessionBatchingSupported());
ProcessorConfigDTO configDTO = new ProcessorConfigDTO();
configDTO.setSchedulingPeriod(processorNode.getSchedulingPeriod());
configDTO.setPenaltyDuration(processorNode.getPenalizationPeriod());
configDTO.setYieldDuration(processorNode.getYieldPeriod());
configDTO.setRunDurationMillis(processorNode.getRunDuration(TimeUnit.MILLISECONDS));
configDTO.setConcurrentlySchedulableTaskCount(processorNode.getMaxConcurrentTasks());
configDTO.setLossTolerant(processorNode.isLossTolerant());
configDTO.setComments(processorNode.getComments());
configDTO.setBulletinLevel(processorNode.getBulletinLevel().name());
configDTO.setSchedulingStrategy(processorNode.getSchedulingStrategy().name());
configDTO.setExecutionNode(processorNode.getExecutionNode().name());
configDTO.setAnnotationData(processorNode.getAnnotationData());
processorDTO.setConfig(configDTO);
// create the snippet with the processor
final FlowSnippetDTO flowSnippetDTO = new FlowSnippetDTO();
flowSnippetDTO.setProcessors(Collections.singleton(processorDTO));
// instantiate the snippet
assertEquals(0, controller.getFlowManager().getRootGroup().getProcessors().size());
controller.getFlowManager().instantiateSnippet(controller.getFlowManager().getRootGroup(), flowSnippetDTO);
assertEquals(1, controller.getFlowManager().getRootGroup().getProcessors().size());
assertTrue(controller.getFlowManager().getRootGroup().getProcessors().iterator().next().getScheduledState().equals(ScheduledState.DISABLED));
}
@Test(expected = IllegalArgumentException.class)
public void testInstantiateSnippetWhenControllerServiceMissingBundle() throws ProcessorInstantiationException {
final String id = UUID.randomUUID().toString();
final BundleCoordinate coordinate = systemBundle.getBundleDetails().getCoordinate();
final ControllerServiceNode controllerServiceNode = controller.getFlowManager().createControllerService(ServiceA.class.getName(), id, coordinate, null, true, true);
// create the controller service dto
final ControllerServiceDTO csDto = new ControllerServiceDTO();
csDto.setId(UUID.randomUUID().toString()); // use a different id
csDto.setParentGroupId(controllerServiceNode.getProcessGroup() == null ? null : controllerServiceNode.getProcessGroup().getIdentifier());
csDto.setName(controllerServiceNode.getName());
csDto.setType(controllerServiceNode.getCanonicalClassName());
csDto.setBundle(null); // missing bundle
csDto.setState(controllerServiceNode.getState().name());
csDto.setAnnotationData(controllerServiceNode.getAnnotationData());
csDto.setComments(controllerServiceNode.getComments());
csDto.setPersistsState(controllerServiceNode.getControllerServiceImplementation().getClass().isAnnotationPresent(Stateful.class));
csDto.setRestricted(controllerServiceNode.isRestricted());
csDto.setExtensionMissing(controllerServiceNode.isExtensionMissing());
csDto.setDescriptors(new LinkedHashMap<>());
csDto.setProperties(new LinkedHashMap<>());
// create the snippet with the controller service
final FlowSnippetDTO flowSnippetDTO = new FlowSnippetDTO();
flowSnippetDTO.setControllerServices(Collections.singleton(csDto));
// instantiate the snippet
assertEquals(0, controller.getFlowManager().getRootGroup().getControllerServices(false).size());
controller.getFlowManager().instantiateSnippet(controller.getFlowManager().getRootGroup(), flowSnippetDTO);
}
@Test
public void testInstantiateSnippetWithControllerService() throws ProcessorInstantiationException {
final String id = UUID.randomUUID().toString();
final BundleCoordinate coordinate = systemBundle.getBundleDetails().getCoordinate();
final ControllerServiceNode controllerServiceNode = controller.getFlowManager().createControllerService(ServiceA.class.getName(), id, coordinate, null, true, true);
// create the controller service dto
final ControllerServiceDTO csDto = new ControllerServiceDTO();
csDto.setId(UUID.randomUUID().toString()); // use a different id
csDto.setParentGroupId(controllerServiceNode.getProcessGroup() == null ? null : controllerServiceNode.getProcessGroup().getIdentifier());
csDto.setName(controllerServiceNode.getName());
csDto.setType(controllerServiceNode.getCanonicalClassName());
csDto.setBundle(new BundleDTO(coordinate.getGroup(), coordinate.getId(), coordinate.getVersion()));
csDto.setState(controllerServiceNode.getState().name());
csDto.setAnnotationData(controllerServiceNode.getAnnotationData());
csDto.setComments(controllerServiceNode.getComments());
csDto.setPersistsState(controllerServiceNode.getControllerServiceImplementation().getClass().isAnnotationPresent(Stateful.class));
csDto.setRestricted(controllerServiceNode.isRestricted());
csDto.setExtensionMissing(controllerServiceNode.isExtensionMissing());
csDto.setDescriptors(new LinkedHashMap<>());
csDto.setProperties(new LinkedHashMap<>());
// create the snippet with the controller service
final FlowSnippetDTO flowSnippetDTO = new FlowSnippetDTO();
flowSnippetDTO.setControllerServices(Collections.singleton(csDto));
// instantiate the snippet
assertEquals(0, controller.getFlowManager().getRootGroup().getControllerServices(false).size());
controller.getFlowManager().instantiateSnippet(controller.getFlowManager().getRootGroup(), flowSnippetDTO);
assertEquals(1, controller.getFlowManager().getRootGroup().getControllerServices(false).size());
}
}
|
peter-gergely-horvath/nifi
|
nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/controller/TestFlowController.java
|
Java
|
apache-2.0
| 59,415
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Tyvj.ViewModels;
using Tyvj.DataModels;
namespace Tyvj.Controllers
{
public class TopicController : BaseController
{
//
// GET: /Topic/
public ActionResult Index(int id)
{
var topic = DbContext.Topics.Find(id);
return View(topic);
}
[HttpGet]
public ActionResult GetTopics(int page, int? ForumID)
{
List<DataModels.Topic> _topics;
if (ForumID == null)
{
_topics = (from t in DbContext.Topics
orderby t.LastReply descending
select t).Skip(page * 10).Take(10).ToList();
}
else
{
_topics = (from t in DbContext.Topics
where t.ForumID == ForumID
orderby t.LastReply descending
select t).Skip(page * 10).Take(10).ToList();
}
List<ViewModels.vTopic> topics = new List<ViewModels.vTopic>();
foreach (var topic in _topics)
topics.Add(new ViewModels.vTopic(topic));
return Json(topics, JsonRequestBehavior.AllowGet);
}
[Authorize]
public ActionResult Create(int id)
{
if ((from f in DbContext.Forums where f.ID == id && f.FatherID != null select f).Count() == 0)
return Message("没有找到这个论坛版块!" );
return View();
}
[Authorize]
[HttpPost]
[ValidateInput(false)]
[ValidateAntiForgeryToken]
public ActionResult Create(ViewModels.vPost model)
{
if ((from f in DbContext.Forums where f.ID == model.ForumID && f.FatherID != null select f).Count() == 0)
return Message("没有找到这个论坛版块!");
if (string.IsNullOrEmpty(model.Content))
return Message("内容不能为空!" );
if (string.IsNullOrEmpty(model.Title))
return Message("标题不能为空!");
if (model.Reward > 0)
{
if (CurrentUser.Coins < model.Reward)
return Message("您的金币不足,无法发出悬赏。");
else
{
var user = DbContext.Users.Find(CurrentUser.ID);
user.Coins -= model.Reward;
}
}
var topic = new DataModels.Topic
{
ForumID = model.ForumID,
Title = model.Title,
Content = model.Content,
UserID = CurrentUser.ID,
Time = DateTime.Now,
Top = false,
LastReply = DateTime.Now,
Reward = model.Reward
};
DbContext.Topics.Add(topic);
DbContext.SaveChanges();
HomeController.RefreshHomeTopicsCache();
return RedirectToAction("Index", "Topic", new { id = topic.ID });
}
[Authorize]
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Delete(int id)
{
var topic = DbContext.Topics.Find(id);
if (topic.UserID == ViewBag.CurrentUser.ID || ((DataModels.User)ViewBag.CurrentUser).Role >= UserRole.Master)
{
var forum_id = topic.ForumID;
DbContext.Topics.Remove(topic);
DbContext.SaveChanges();
return RedirectToAction("Index", "Forum", new { id = forum_id });
}
else
{
return Message("您无权删除这个主题!");
}
}
[Authorize]
[HttpPost]
[ValidateInput(false)]
[ValidateAntiForgeryToken]
public ActionResult Edit(int id, string content)
{
var topic = DbContext.Topics.Find(id);
if (topic.UserID == ViewBag.CurrentUser.ID || ((DataModels.User)ViewBag.CurrentUser).Role >= UserRole.Master)
{
topic.Content = content;
DbContext.SaveChanges();
return Content("OK");
}
else
{
return Content("NO");
}
}
[Authorize]
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult UnSetTop(int id)
{
if (((DataModels.User)ViewBag.CurrentUser).Role >= UserRole.Master)
{
var topic = DbContext.Topics.Find(id);
topic.Top = false;
DbContext.SaveChanges();
return Content("OK");
}
else
{
return Content("NO");
}
}
[Authorize]
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult SetTop(int id)
{
if (((DataModels.User)ViewBag.CurrentUser).Role >= UserRole.Master)
{
var topic = DbContext.Topics.Find(id);
topic.Top = true;
DbContext.SaveChanges();
return Content("OK");
}
else
{
return Content("NO");
}
}
[Authorize]
[HttpGet]
public ActionResult Reward(int id)
{
var reply = DbContext.Replies.Find(id);
if (reply.Topic.UserID != CurrentUser.ID)
return Message("您无权执行本操作!");
if (reply.UserID == CurrentUser.ID)
return Message("您不能采纳自己的回答!");
reply.User.Coins += reply.Topic.Reward;
reply.Awarded = true;
DbContext.SaveChanges();
return Message("采纳成功!");
}
}
}
|
Kagamine/Tyvj
|
Tyvj/Controllers/TopicController.cs
|
C#
|
apache-2.0
| 6,167
|
$basePath = (Get-Item $ScriptRoot/../../../).FullName
$buildPath = $basePath + "Build\" + $targetSystem
New-Item -ItemType Directory -Force -Path $buildPath | Out-Null
echo "Base Path: $basePath"
echo "Build Path: $buildPath"
|
mlomb/OrbitEngine
|
Tools/Build/Windows/common.ps1
|
PowerShell
|
apache-2.0
| 227
|
package com.mygdx.hiddenmarble.entities;
/** A moving ball. */
public interface Marble extends DynamicEntity {
}
|
js42721/hiddenmarble
|
core/src/com/mygdx/hiddenmarble/entities/Marble.java
|
Java
|
apache-2.0
| 114
|
<div class="row">
<div class="col-md-8">
<!--<iframe class="video" src="https://www.youtube.com/embed/DU6UV2GPzIk?"></iframe>
<iframe class="video" src="https://www.youtube.com/embed/DU6UV2GPzIk?rel=0&autoplay=1"></iframe>-->
<div class="embed-responsive embed-responsive-16by9">
<!--<iframe class="embed-responsive-item" ng-src="{{trustSrc(srcVideo)}}" id="player">-->
<!--</iframe>-->
<youtube width="640" height="390" videoid="{{video.video_id}}" on-change="videoTerminou()" id="player"></youtube>
</div>
</div>
<div class="col-md-4 list-container">
<div class="title">
<!-- se quiser colocar um titulo na play -->
</div>
<nav>
<ul class="list-group">
<li class="list-group-item item" ng-repeat="musica in playlist">
<div ng-click="setVideo(musica)">
<h4>{{musica.song}}</h4>
{{musica.artist}}
</div>
</li>
</ul>
</nav>
</div>
</div>
<div class="row">
<div class="col-md-7s">
<h3>
<span class="titulo">{{video.song}}</span>
<span class="artista">{{video.artist}}</span>
</h3>
<h4>
{{video.year}}
</h4>
</div>
</div>
|
talitalobo/radiola
|
web/angular/directive/playlist.html
|
HTML
|
apache-2.0
| 1,337
|
package main
func test() error { return nil }
func main() {
if err := test(); nil == err {
println("err is nil")
}
}
// Output:
// err is nil
|
containous/yaegi
|
_test/nil2.go
|
GO
|
apache-2.0
| 149
|
__source__ = 'https://leetcode.com/problems/balanced-binary-tree/#/description'
# https://github.com/kamyu104/LeetCode/blob/master/Python/balanced-binary-tree.py
# Time: O(n)
# Space: O(h), h is height of binary tree
# divide and conquer
#
# Description: Leetcode # 110. Balanced Binary Tree
#
# Given a binary tree, determine if it is height-balanced.
#
# For this problem, a height-balanced binary tree is defined as a binary tree
# in which the depth of the two subtrees of every node never differ by more than 1.
#
# Companies
# Bloomberg
# Related Topics
# Tree Depth-first Search
# Similar Questions
# Maximum Depth of Binary Tree
#
import unittest
# Definition for a binary tree node
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# @param root, a tree node
# @return a boolean
def isBalanced(self, root):
return (self.getHeight(root) >= 0)
def getHeight(self, root):
if root is None:
return 0
left_height = self.getHeight(root.left)
right_height = self.getHeight(root.right)
if left_height < 0 or right_height < 0 or abs(left_height - right_height) > 1:
return -1
return max(left_height, right_height) + 1
#http://www.programcreek.com/2013/02/leetcode-balanced-binary-tree-java/
class javaSolution:
# @param root, a tree node
# @return a boolean
def isBalanced(self, root):
if not root:
return None
if self.getHeight(root) == -1:
return False
return True
def getHeight(self, root):
if not root:
return 0
left = self.getHeight(root.left)
right = self.getHeight(root.right)
if left == -1 or right == -1:
return -1
if abs(left - right) > 1:
return -1
return max(left, right) + 1
class SolutionOther:
# @param root, a tree node
# @return a boolean
# http://www.cnblogs.com/zuoyuan/p/3720169.html
def isBalanced(self, root):
if root == None:
return True
if abs(self.Height(root.left) - self.Height(root.right)) <= 1:
return self.isBalanced(root.left) and self.isBalanced(root.right)
else:
return False
def Height(self, root) :
if root == None:
return 0
return max(self.Height(root.left), self.Height(root.right)) +1
#############test
#creating BST tree ####
root0=TreeNode(0)
tree1=TreeNode(1)
tree2=TreeNode(2)
tree3=TreeNode(3)
tree4=TreeNode(4)
tree5=TreeNode(5)
tree6=TreeNode(6)
root0.left=tree1
#root0.right=tree2
tree1.left=tree3
tree1.right=tree4
tree2.left=tree5
#tree2.right=tree6
#end of creating BST tree ####
#test
test = SolutionOther()
print test.isBalanced(root0)
#print test.isBalanced3(root0)
#print test.isBalanced2(root0)
class TestMethods(unittest.TestCase):
def test_Local(self):
self.assertEqual(1, 1)
root = TreeNode(0)
root.left = TreeNode(1)
result = Solution().isBalanced(root)
print result
root.left.left = TreeNode(2)
result = javaSolution().isBalanced(root)
print result
if __name__ == '__main__':
unittest.main()
Java = '''
#Thought: https://leetcode.com/problems/contains-duplicate/solution/
Thought: This problem is generally believed to have two solutions:
the top down approach and the bottom up way.
DFS 1) The first method checks whether the tree is balanced strictly according to the definition
of balanced binary tree: the difference between the heights of the two sub trees are not bigger than 1,
and both the left sub tree and right sub tree are also balanced. With the helper function depth(),
we could easily write the code;
For the current node root, calling depth() for its left and right children actually has to access all of its children,
thus the complexity is O(N). We do this for each node in the tree,
so the overall complexity of isBalanced will be O(N^2). This is a top down approach.
DFS 2)The second method is based on DFS. Instead of calling depth() explicitly for each child node,
we return the height of the current node in DFS recursion.
When the sub tree of the current node (inclusive) is balanced, the function dfsHeight()
returns a non-negative value as the height.
Otherwise -1 is returned. According to the leftHeight and rightHeight of the two children,
the parent node could check if the sub tree is balanced, and decides its return value.
# DFS
# 87.89% 1ms
class Solution {
public boolean isBalanced(TreeNode root) {
return dfsHeight(root) != -1;
}
public int dfsHeight(TreeNode root) {
if (root == null) return 0;
int left = dfsHeight(root.left);
int right = dfsHeight(root.right);
if (left == -1 || right == -1 || Math.abs(left - right) > 1) return -1;
return Math.max(left, right) + 1;
}
}
# DFS
# 87.89% 1ms
class Solution {
public boolean isBalanced(TreeNode root) {
if (root == null) return true;
int left = getDpeth(root.left);
int right = getDpeth(root.right);
return Math.abs(left - right) <= 1 && isBalanced(root.left) && isBalanced(root.right);
}
public int getDpeth(TreeNode root) {
if (root == null) return 0;
return Math.max(getDpeth(root.left), getDpeth(root.right)) + 1;
}
}
'''
|
JulyKikuAkita/PythonPrac
|
cs15211/BalancedBinaryTree.py
|
Python
|
apache-2.0
| 5,434
|
<!DOCTYPE html>
<html ng-app="oppia" itemscope itemtype="http://schema.org/Organization">
<head>
@load('base-components/header.template.html', {"title": "Oppia"})
<style>
@media(max-width: 500px) {
.oppia-exploration-header {
max-width: 180px;
}
}
@media(max-width: 400px) {
.oppia-exploration-header {
max-width: 130px;
}
}
</style>
</head>
<body>
<oppia-root>
<div ng-controller="Base">
<base-content>
<navbar-breadcrumb>
<learner-view-info></learner-view-info>
</navbar-breadcrumb>
<nav-options>
<learner-local-nav></learner-local-nav>
</nav-options>
<content>
<exploration-player-page></exploration-player-page>
</content>
<page-footer>
<exploration-footer></exploration-footer>
</page-footer>
</base-content>
</div>
</oppia-root>
@load('pages/footer_js_libs.html')
@loadExtensions('interactions/dependency_html.html')
</body>
</html>
|
prasanna08/oppia
|
core/templates/pages/exploration-player-page/exploration-player-page.mainpage.html
|
HTML
|
apache-2.0
| 1,110
|
# AUTOGENERATED FILE
FROM balenalib/vab820-quad-alpine:3.13-build
ENV NODE_VERSION 15.6.0
ENV YARN_VERSION 1.22.4
# Install dependencies
RUN apk add --no-cache libgcc libstdc++ libuv \
&& apk add --no-cache libssl1.0 || apk add --no-cache libssl1.1
RUN for key in \
6A010C5166006599AA17F08146C2130DFD2497F5 \
; do \
gpg --keyserver pgp.mit.edu --recv-keys "$key" || \
gpg --keyserver keyserver.pgp.com --recv-keys "$key" || \
gpg --keyserver ha.pool.sks-keyservers.net --recv-keys "$key" ; \
done \
&& curl -SLO "http://resin-packages.s3.amazonaws.com/node/v$NODE_VERSION/node-v$NODE_VERSION-linux-alpine-armv7hf.tar.gz" \
&& echo "084ad9e36676f5c65d932546623ba9cf5d7a329902e40f77a3b5b7e3485be841 node-v$NODE_VERSION-linux-alpine-armv7hf.tar.gz" | sha256sum -c - \
&& tar -xzf "node-v$NODE_VERSION-linux-alpine-armv7hf.tar.gz" -C /usr/local --strip-components=1 \
&& rm "node-v$NODE_VERSION-linux-alpine-armv7hf.tar.gz" \
&& curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz" \
&& curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz.asc" \
&& gpg --batch --verify yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \
&& mkdir -p /opt/yarn \
&& tar -xzf yarn-v$YARN_VERSION.tar.gz -C /opt/yarn --strip-components=1 \
&& ln -s /opt/yarn/bin/yarn /usr/local/bin/yarn \
&& ln -s /opt/yarn/bin/yarn /usr/local/bin/yarnpkg \
&& rm yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \
&& npm config set unsafe-perm true -g --unsafe-perm \
&& rm -rf /tmp/*
CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"]
RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/test-stack@node.sh" \
&& echo "Running test-stack@node" \
&& chmod +x test-stack@node.sh \
&& bash test-stack@node.sh \
&& rm -rf test-stack@node.sh
RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo $'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v7 \nOS: Alpine Linux 3.13 \nVariant: build variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nNode.js v15.6.0, Yarn v1.22.4 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info
RUN echo $'#!/bin/bash\nbalena-info\nbusybox ln -sf /bin/busybox /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \
&& chmod +x /bin/sh-shim \
&& ln -f /bin/sh /bin/sh.real \
&& ln -f /bin/sh-shim /bin/sh
|
nghiant2710/base-images
|
balena-base-images/node/vab820-quad/alpine/3.13/15.6.0/build/Dockerfile
|
Dockerfile
|
apache-2.0
| 2,956
|
package org.apereo.cas.web.flow.resolver.impl.mfa;
import org.apereo.cas.CentralAuthenticationService;
import org.apereo.cas.authentication.AuthenticationServiceSelectionPlan;
import org.apereo.cas.authentication.AuthenticationSystemSupport;
import org.apereo.cas.authentication.MultifactorAuthenticationProviderSelector;
import org.apereo.cas.authentication.principal.Principal;
import org.apereo.cas.services.RegisteredService;
import org.apereo.cas.services.ServicesManager;
import org.apereo.cas.ticket.registry.TicketRegistrySupport;
import org.apereo.cas.util.CollectionUtils;
import org.apereo.cas.web.flow.authentication.BaseMultifactorAuthenticationProviderEventResolver;
import org.apereo.cas.web.support.WebUtils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.apache.commons.lang3.StringUtils;
import org.apereo.inspektr.audit.annotation.Audit;
import org.springframework.web.util.CookieGenerator;
import org.springframework.webflow.execution.Event;
import org.springframework.webflow.execution.RequestContext;
import java.util.Optional;
import java.util.Set;
/**
* This is {@link RegisteredServiceMultifactorAuthenticationPolicyEventResolver}
* that attempts to resolve the next event based on the authentication providers of this service.
*
* @author Misagh Moayyed
* @since 5.0.0
*/
@Slf4j
public class RegisteredServiceMultifactorAuthenticationPolicyEventResolver extends BaseMultifactorAuthenticationProviderEventResolver {
public RegisteredServiceMultifactorAuthenticationPolicyEventResolver(final AuthenticationSystemSupport authenticationSystemSupport,
final CentralAuthenticationService centralAuthenticationService,
final ServicesManager servicesManager,
final TicketRegistrySupport ticketRegistrySupport,
final CookieGenerator warnCookieGenerator,
final AuthenticationServiceSelectionPlan authSelectionStrategies,
final MultifactorAuthenticationProviderSelector selector) {
super(authenticationSystemSupport, centralAuthenticationService, servicesManager,
ticketRegistrySupport, warnCookieGenerator, authSelectionStrategies, selector);
}
@Override
public Set<Event> resolveInternal(final RequestContext context) {
val service = resolveRegisteredServiceInRequestContext(context);
val authentication = WebUtils.getAuthentication(context);
if (service == null || authentication == null) {
LOGGER.debug("No service or authentication is available to determine event for principal");
return null;
}
val policy = service.getMultifactorPolicy();
if (policy == null || policy.getMultifactorAuthenticationProviders().isEmpty()) {
LOGGER.debug("Authentication policy does not contain any multifactor authentication providers");
return null;
}
if (StringUtils.isNotBlank(policy.getPrincipalAttributeNameTrigger()) || StringUtils.isNotBlank(policy.getPrincipalAttributeValueToMatch())) {
LOGGER.debug("Authentication policy for [{}] has defined principal attribute triggers. Skipping...", service.getServiceId());
return null;
}
return resolveEventPerAuthenticationProvider(authentication.getPrincipal(), context, service);
}
/**
* Resolve event per authentication provider event.
*
* @param principal the principal
* @param context the context
* @param service the service
* @return the event
*/
@SneakyThrows
protected Set<Event> resolveEventPerAuthenticationProvider(final Principal principal,
final RequestContext context,
final RegisteredService service) {
val providers = getAuthenticationProviderForService(service);
if (providers != null && !providers.isEmpty()) {
val provider = this.multifactorAuthenticationProviderSelector.resolve(providers, service, principal);
LOGGER.debug("Selected multifactor authentication provider for this transaction is [{}]", provider);
val identifier = provider.getId();
LOGGER.debug("Attempting to build an event based on the authentication provider [{}] and service [{}]", provider, service.getName());
val event = validateEventIdForMatchingTransitionInContext(identifier, context, buildEventAttributeMap(principal, Optional.of(service), provider));
return CollectionUtils.wrapSet(event);
}
LOGGER.debug("No multifactor authentication providers could be located for [{}]", service);
return null;
}
@Audit(action = "AUTHENTICATION_EVENT",
actionResolverName = "AUTHENTICATION_EVENT_ACTION_RESOLVER",
resourceResolverName = "AUTHENTICATION_EVENT_RESOURCE_RESOLVER")
@Override
public Event resolveSingle(final RequestContext context) {
return super.resolveSingle(context);
}
}
|
frett/cas
|
core/cas-server-core-webflow-mfa-api/src/main/java/org/apereo/cas/web/flow/resolver/impl/mfa/RegisteredServiceMultifactorAuthenticationPolicyEventResolver.java
|
Java
|
apache-2.0
| 5,457
|
/*
* 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.
*
* $Header:$
*/
package org.apache.beehive.netui.tags.rendering;
import org.apache.beehive.netui.tags.html.HtmlConstants;
import java.util.HashMap;
/**
* Render the HTML <button> element. In HTML 4.01 the start and end tags are required.
*
* <p>This renderer is just used by the NetUI Button as an alternative to the <input>
* HTML element rendered by the InputSubmitTag.
* </p>
*/
public abstract class ButtonTag extends TagHtmlBase implements HtmlConstants
{
public static void add(HashMap html, HashMap htmlQuirks, HashMap xhtml)
{
html.put(BUTTON_TAG, new HtmlRendering());
htmlQuirks.put(BUTTON_TAG, new HtmlRendering());
xhtml.put(BUTTON_TAG, new XhtmlRendering());
}
public static class State extends InputSubmitTag.State
{
}
public void doStartTag(AbstractRenderAppender writer, AbstractTagState renderState)
{
assert(writer != null) : "Parameter 'writer' must not be null";
assert(renderState != null) : "Parameter 'renderState' must not be null";
assert(renderState instanceof ButtonTag.State) : "Paramater 'renderState' must be an instance of ButtonTag.State";
State state = (State) renderState;
// Generate an HTML element
renderTag(writer, BUTTON);
if (state.type == null)
state.type = INPUT_SUBMIT;
renderAttribute(writer, TYPE, state.type);
renderAttribute(writer, NAME, state.name);
renderAttribute(writer, ID, state.id);
renderAttribute(writer, CLASS, state.styleClass);
renderAttribute(writer, VALUE, state.value);
renderDisabled(writer, state.disabled);
renderAttributes(AbstractHtmlState.ATTR_GENERAL, writer, state);
renderAttribute(writer, STYLE, state.style);
renderAttributes(AbstractHtmlState.ATTR_JAVASCRIPT, writer, state);
writer.append(">");
}
public void doEndTag(AbstractRenderAppender writer)
{
renderEndTag(writer, BUTTON);
}
abstract protected void renderDisabled(AbstractRenderAppender writer, boolean disabled);
private static class HtmlRendering extends ButtonTag
{
protected void renderDisabled(AbstractRenderAppender writer, boolean disabled)
{
if (disabled)
writer.append(" disabled");
}
}
private static class XhtmlRendering extends ButtonTag
{
protected void renderDisabled(AbstractRenderAppender writer, boolean disabled)
{
if (disabled)
renderAttribute(writer, "disabled", "disabled");
}
}
}
|
moparisthebest/beehive
|
beehive-netui-tags/src/main/java/org/apache/beehive/netui/tags/rendering/ButtonTag.java
|
Java
|
apache-2.0
| 3,426
|
const fs = require('fs');
const path = require('path');
const { COPYFILE_EXCL } = fs.constants;
function isConflict(origStat, stat)
{
return stat != null && origStat != null && stat.mtimeMs != origStat.mtimeMs;
};
function saveFile(fileObject, data, origStat, overwrite, defEnc, reqId)
{
var retryCount = 0;
var backupCreated = false;
var writeFile = function()
{
if (data == null || data.length == 0)
{
postMessage({error: true, msg: 'empty data', reqId: reqId});
}
else
{
var writeEnc = defEnc || fileObject.encoding;
fs.writeFile(fileObject.path, data, writeEnc,
function (e)
{
if (e)
{
postMessage({error: true, msg: 'saving failed', e: e, reqId: reqId});
}
else
{
fs.stat(fileObject.path, function(e2, stat2)
{
if (e2)
{
postMessage({error: true, msg: 'stat failed', e: e2, reqId: reqId});
}
else
{
// Workaround for possible writing errors is to check the written
// contents of the file and retry 3 times before showing an error
fs.readFile(fileObject.path, writeEnc, (err, writtenData) =>
{
if (data != writtenData)
{
retryCount++;
if (retryCount < 3)
{
writeFile();
}
else
{
postMessage({error: true, msg: 'all saving trials failed', e: e, reqId: reqId});
}
}
else
{
postMessage({success: true, data: {stat: stat2}, reqId: reqId});
if (backupCreated)
{
fs.unlink(fileObject.bkpPath, (err) => {}); //Ignore errors!
}
}
});
}
});
}
});
}
};
function doSaveFile()
{
//Copy file to backup file (after conflict and stat is checked)
fs.copyFile(fileObject.path, fileObject.bkpPath, COPYFILE_EXCL, (err) =>
{
if (!err)
{
backupCreated = true;
}
writeFile();
});
};
if (overwrite)
{
doSaveFile();
}
else
{
//TODO Using stat before write is not recommended, we can check the error code from writeFile
fs.stat(fileObject.path, function(err, stat)
{
if (isConflict(origStat, stat))
{
postMessage({error: true, msg: 'conflict', e: {isConflicted: true}, reqId: reqId});
}
else if (err != null && err.code !== 'ENOENT')
{
postMessage({error: true, msg: 'stat failed', e: err, reqId: reqId});
}
else
{
doSaveFile();
}
});
}
};
//TODO handle reqId better
onmessage = function(e)
{
switch(e.data.action)
{
case 'saveFile':
saveFile(e.data.fileObject, e.data.data, e.data.origStat, e.data.overwrite, e.data.defEnc, e.data.reqId);
break;
};
};
|
jgraph/draw.io
|
src/main/webapp/electronFilesWorker.js
|
JavaScript
|
apache-2.0
| 2,829
|
//
// SecondIntroductionView.h
// Inneract
//
// Created by Jim Liu on 3/5/15.
// Copyright (c) 2015 Emmanuel Texier. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface SecondIntroductionView : UIView
@end
|
etexier/inneract
|
Inneract/SecondIntroductionView.h
|
C
|
apache-2.0
| 221
|
package id.bizdir.ui.activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.internal.view.ContextThemeWrapper;
import android.support.v7.widget.Toolbar;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;
import com.afollestad.materialdialogs.MaterialDialog;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import id.bizdir.App;
import id.bizdir.R;
import id.bizdir.modelhelper.ForumPostHelper;
import id.bizdir.modelhelper.MemberBizdirHelper;
import id.bizdir.model.ForumPost;
import id.bizdir.model.MemberBizdir;
import id.bizdir.model.ResultObject;
import id.bizdir.model.ResultObjectHelper;
import id.bizdir.service.AllSync;
import id.bizdir.service.ForumPostService;
import id.bizdir.ui.adapter.ForumPostAdapter;
import id.bizdir.util.Const;
import id.bizdir.util.Helpers;
public class ForumPostActivity extends AppCompatActivity {
private TextView textNoData;
private TextView title;
private ListView list;
private List<ForumPost> listObject;
private ForumPostAdapter adapter;
private ForumPostHelper forumPostHelper;
private SwipeRefreshLayout mSwipeRefreshLayout;
private int progressInterval = 700;
private int threadId;
private MemberBizdir memberBizdir;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_forum_post);
Helpers.setLockOrientation(ForumPostActivity.this);
LayoutInflater inflater = LayoutInflater.from(ForumPostActivity.this);
View headerLayout = inflater.inflate(R.layout.item_header_forum_post, null);
title = (TextView) headerLayout.findViewById(R.id.title);
getDataFromPreviousPage();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
textNoData = (TextView) findViewById(R.id.textNoData);
list = (ListView) findViewById(R.id.list);
list.addHeaderView(headerLayout);
forumPostHelper = new ForumPostHelper();
mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.activity_main_swipe_refresh_layout);
mSwipeRefreshLayout.setColorSchemeResources(R.color.orange, R.color.green, R.color.blue, R.color.red);
mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
new Handler().post(new Runnable() {
@Override
public void run() {
refreshDataSync();
}
});
}
});
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
Helpers.setMainActionBarNoShadow(actionBar);
}
showProgress();
RefreshData();
}
private void refreshDataSync() {
class GetAllSyncTask extends AsyncTask<String, Void, String> {
String response = "";
@Override
protected String doInBackground(String... param) {
response = "";
try {
response = AllSync.syncForum();
} catch (IOException e) {
response = e.getMessage();
e.printStackTrace();
}
return response;
}
@Override
protected void onPostExecute(String resultJson) {
ResultObject resultObject = ResultObjectHelper.getResult(resultJson);
int status = resultObject.getStatus();
if (status == 1) {
String jsonString = resultObject.getResult();
AllSync.insertForumSync(jsonString);
}
RefreshData();
}
}
GetAllSyncTask task = new GetAllSyncTask();
task.execute();
}
private void RefreshData() {
new GetDataAndBindList().execute();
}
private void showProgress() {
mSwipeRefreshLayout.post(new Runnable() {
@Override
public void run() {
mSwipeRefreshLayout.setRefreshing(true);
}
});
}
private void hideProgress() {
mSwipeRefreshLayout.postDelayed(new Runnable() {
@Override
public void run() {
mSwipeRefreshLayout.setRefreshing(false);
}
}, progressInterval);
}
private class GetDataAndBindList extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
//showProgress();
}
@Override
protected Void doInBackground(Void... params) {
getData();
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
bindData();
hideProgress();
}
}
@Override
public void onResume() {
boolean isDataChange = App.getDataMemberIsChanged();
if (isDataChange) {
showProgress();
RefreshData();
}
super.onResume();
}
private void getData() {
listObject = forumPostHelper.getAll(threadId);
}
private void bindData() {
adapter = new ForumPostAdapter(this,
R.layout.item_cardview_forum_post, listObject);
list.setAdapter(adapter);
if (listObject.size() > 0) {
textNoData.setVisibility(View.GONE);
} else {
textNoData.setVisibility(View.VISIBLE);
}
}
private void showReplyPostDialog() {
new MaterialDialog.Builder(new ContextThemeWrapper(this, R.style.MaterialDrawerTheme_Light_DarkToolbar))
.title(R.string.action_reply_forum)
.content(R.string.action_post_message_forum)
.inputType(InputType.TYPE_CLASS_TEXT)
//InputType.TYPE_TEXT_VARIATION_PERSON_NAME |
// InputType.TYPE_TEXT_FLAG_CAP_WORDS)
.inputMaxLength(Const.MAX_CHAR_POST_MESSAGE)
.positiveText(R.string.action_submit)
.input(R.string.action_message, 0,
false, new MaterialDialog.InputCallback() {
@Override
public void onInput(MaterialDialog dialog, CharSequence input) {
//showToast("Hello, " + input.toString() + "!");
int userId = 0;
if (memberBizdir != null) {
userId = memberBizdir.getId();
}
boolean isavailable = Helpers.isInternetConnected(ForumPostActivity.this);
if (isavailable) {
postForumWs(userId, threadId, input.toString());
} else {
new MaterialDialog.Builder(new ContextThemeWrapper(ForumPostActivity.this,
R.style.MaterialDrawerTheme_Light_DarkToolbar))
.title(R.string.dialog_forum_post_failed)
.content(R.string.no_internet_connection)
.positiveText(R.string.button_ok)
.show();
}
}
}).show();
}
private void postForumWs(Integer userId, Integer topicId, String message) {
class PostAsyncTask extends AsyncTask<String, Void, String> {
String response = "";
final MaterialDialog progressDialog = new MaterialDialog.Builder(
new ContextThemeWrapper(ForumPostActivity.this, R.style.MaterialDrawerTheme_Light_DarkToolbar))
.title("Loading")
.content("Please wait...")
.progress(true, 0)
.cancelable(false)
.show();
@Override
protected String doInBackground(String... param) {
String userId = param[0];
String topicId = param[1];
String message = param[2];
response = "";
try {
ForumPostService service = new ForumPostService();
response = service.postForum(userId, topicId, message);
} catch (IOException e) {
response = e.getMessage();
e.printStackTrace();
}
return response;
}
@Override
protected void onPostExecute(String resultJson) {
progressDialog.dismiss();
ResultObject resultObject = ResultObjectHelper.getResult(resultJson);
if (resultObject != null) {
int status = resultObject.getStatus();
if (status == 1) {
String resultJsonString = resultObject.getResult();
ForumPost forumPost = App.getGson().fromJson(resultJsonString,
ForumPost.class);
if (forumPost != null) {
forumPost.setCreateDate(new Date());
ForumPostHelper helper = new ForumPostHelper();
helper.add(forumPost);
showProgress();
RefreshData();
}
} else {
String title = getResources().getString(R.string.dialog_forum_post_failed);
String content = getResources().getString(R.string.dialog_forum_post_failed_message);
Helpers.showDialog(ForumPostActivity.this, title, content);
}
}
}
}
String[] myTaskParams = {userId.toString(), topicId.toString(), message};
PostAsyncTask task = new PostAsyncTask();
task.execute(myTaskParams);
}
private void postViewCountWs(Integer topicId) {
class PostAsyncTask extends AsyncTask<String, Void, String> {
String response = "";
@Override
protected String doInBackground(String... param) {
String topicId = param[0];
response = "";
try {
ForumPostService service = new ForumPostService();
response = service.postViewCount(topicId);
} catch (IOException e) {
response = e.getMessage();
e.printStackTrace();
}
return response;
}
@Override
protected void onPostExecute(String resultJson) {
ResultObject resultObject = ResultObjectHelper.getResult(resultJson);
if (resultObject != null) {
int status = resultObject.getStatus();
if (status == 1) {
String resultJsonString = resultObject.getResult();
Log.i("View Count Success:", resultJsonString);
} else {
Log.i("View Count Failed:", resultObject.getMessage());
}
}
}
}
String[] myTaskParams = {topicId.toString()};
PostAsyncTask task = new PostAsyncTask();
task.execute(myTaskParams);
}
private void getDataFromPreviousPage() {
Intent intent = this.getIntent();
int objectIndex = intent.getIntExtra(Const.OBJECT_INDEX, 0);
String toolbarTitle = intent.getStringExtra(Const.TOOLBAR_TITLE);
if (objectIndex != 0) {
threadId = objectIndex;
}
if (!TextUtils.isEmpty(toolbarTitle)) {
title.setText(toolbarTitle);
}
MemberBizdirHelper memberBizdirHelper = new MemberBizdirHelper();
memberBizdir = memberBizdirHelper.get();
postViewCountWs(threadId);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
if (menu.size() > 0) {
menu.clear();
}
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.activity_forum_post, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
case R.id.action_favorite_refresh:
showProgress();
refreshDataSync();
return true;
case R.id.action_post_forum:
showReplyPostDialog();
return true;
case R.id.action_home:
Intent intent = new Intent(ForumPostActivity.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
this.finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
@Override
public void onBackPressed() {
super.onBackPressed();
}
}
|
niqmk/BizDir-Android
|
BizDir-app/src/main/java/id/bizdir/ui/activity/ForumPostActivity.java
|
Java
|
apache-2.0
| 14,325
|
# AUTOGENERATED FILE
FROM balenalib/photon-nano-ubuntu:disco-run
# remove several traces of debian python
RUN apt-get purge -y python.*
# http://bugs.python.org/issue19846
# > At the moment, setting "LANG=C" on a Linux system *fundamentally breaks Python 3*, and that's not OK.
ENV LANG C.UTF-8
# install python dependencies
RUN apt-get update && apt-get install -y --no-install-recommends \
ca-certificates \
netbase \
&& rm -rf /var/lib/apt/lists/*
# key 63C7CC90: public key "Simon McVittie <smcv@pseudorandom.co.uk>" imported
# key 3372DCFA: public key "Donald Stufft (dstufft) <donald@stufft.io>" imported
RUN gpg --keyserver keyring.debian.org --recv-keys 4DE8FF2A63C7CC90 \
&& gpg --keyserver keyserver.ubuntu.com --recv-key 6E3CBCE93372DCFA \
&& gpg --keyserver keyserver.ubuntu.com --recv-keys 0x52a43a1e4b77b059
ENV PYTHON_VERSION 3.9.1
# if this is called "PIP_VERSION", pip explodes with "ValueError: invalid truth value '<VERSION>'"
ENV PYTHON_PIP_VERSION 20.3.1
ENV SETUPTOOLS_VERSION 51.0.0
RUN set -x \
&& buildDeps=' \
curl \
' \
&& apt-get update && apt-get install -y $buildDeps --no-install-recommends && rm -rf /var/lib/apt/lists/* \
&& curl -SLO "http://resin-packages.s3.amazonaws.com/python/v$PYTHON_VERSION/Python-$PYTHON_VERSION.linux-aarch64-openssl1.1.tar.gz" \
&& echo "833cd79bb2ec9c2a587ce8e9119d96d2f727713911570e410a4b0b758df6017f Python-$PYTHON_VERSION.linux-aarch64-openssl1.1.tar.gz" | sha256sum -c - \
&& tar -xzf "Python-$PYTHON_VERSION.linux-aarch64-openssl1.1.tar.gz" --strip-components=1 \
&& rm -rf "Python-$PYTHON_VERSION.linux-aarch64-openssl1.1.tar.gz" \
&& ldconfig \
&& if [ ! -e /usr/local/bin/pip3 ]; then : \
&& curl -SLO "https://raw.githubusercontent.com/pypa/get-pip/430ba37776ae2ad89f794c7a43b90dc23bac334c/get-pip.py" \
&& echo "19dae841a150c86e2a09d475b5eb0602861f2a5b7761ec268049a662dbd2bd0c get-pip.py" | sha256sum -c - \
&& python3 get-pip.py \
&& rm get-pip.py \
; fi \
&& pip3 install --no-cache-dir --upgrade --force-reinstall pip=="$PYTHON_PIP_VERSION" setuptools=="$SETUPTOOLS_VERSION" \
&& find /usr/local \
\( -type d -a -name test -o -name tests \) \
-o \( -type f -a -name '*.pyc' -o -name '*.pyo' \) \
-exec rm -rf '{}' + \
&& cd / \
&& rm -rf /usr/src/python ~/.cache
# make some useful symlinks that are expected to exist
RUN cd /usr/local/bin \
&& ln -sf pip3 pip \
&& { [ -e easy_install ] || ln -s easy_install-* easy_install; } \
&& ln -sf idle3 idle \
&& ln -sf pydoc3 pydoc \
&& ln -sf python3 python \
&& ln -sf python3-config python-config
# set PYTHONPATH to point to dist-packages
ENV PYTHONPATH /usr/lib/python3/dist-packages:$PYTHONPATH
CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"]
RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/test-stack@python.sh" \
&& echo "Running test-stack@python" \
&& chmod +x test-stack@python.sh \
&& bash test-stack@python.sh \
&& rm -rf test-stack@python.sh
RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v8 \nOS: Ubuntu disco \nVariant: run variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nPython v3.9.1, Pip v20.3.1, Setuptools v51.0.0 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info
RUN echo '#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \
&& chmod +x /bin/sh-shim \
&& cp /bin/sh /bin/sh.real \
&& mv /bin/sh-shim /bin/sh
|
nghiant2710/base-images
|
balena-base-images/python/photon-nano/ubuntu/disco/3.9.1/run/Dockerfile
|
Dockerfile
|
apache-2.0
| 4,068
|
# AUTOGENERATED FILE
FROM balenalib/genericx86-64-ext-ubuntu:focal-build
ENV NODE_VERSION 15.6.0
ENV YARN_VERSION 1.22.4
RUN for key in \
6A010C5166006599AA17F08146C2130DFD2497F5 \
; do \
gpg --keyserver pgp.mit.edu --recv-keys "$key" || \
gpg --keyserver keyserver.pgp.com --recv-keys "$key" || \
gpg --keyserver ha.pool.sks-keyservers.net --recv-keys "$key" ; \
done \
&& curl -SLO "http://nodejs.org/dist/v$NODE_VERSION/node-v$NODE_VERSION-linux-x64.tar.gz" \
&& echo "a8b42f6f174f857b9369858b63ff136ed5b9072336e6df9f0208eddde13897dc node-v$NODE_VERSION-linux-x64.tar.gz" | sha256sum -c - \
&& tar -xzf "node-v$NODE_VERSION-linux-x64.tar.gz" -C /usr/local --strip-components=1 \
&& rm "node-v$NODE_VERSION-linux-x64.tar.gz" \
&& curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz" \
&& curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz.asc" \
&& gpg --batch --verify yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \
&& mkdir -p /opt/yarn \
&& tar -xzf yarn-v$YARN_VERSION.tar.gz -C /opt/yarn --strip-components=1 \
&& ln -s /opt/yarn/bin/yarn /usr/local/bin/yarn \
&& ln -s /opt/yarn/bin/yarn /usr/local/bin/yarnpkg \
&& rm yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \
&& npm config set unsafe-perm true -g --unsafe-perm \
&& rm -rf /tmp/*
CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"]
RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/test-stack@node.sh" \
&& echo "Running test-stack@node" \
&& chmod +x test-stack@node.sh \
&& bash test-stack@node.sh \
&& rm -rf test-stack@node.sh
RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: Intel 64-bit (x86-64) \nOS: Ubuntu focal \nVariant: build variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nNode.js v15.6.0, Yarn v1.22.4 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info
RUN echo '#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \
&& chmod +x /bin/sh-shim \
&& cp /bin/sh /bin/sh.real \
&& mv /bin/sh-shim /bin/sh
|
nghiant2710/base-images
|
balena-base-images/node/genericx86-64-ext/ubuntu/focal/15.6.0/build/Dockerfile
|
Dockerfile
|
apache-2.0
| 2,769
|
#region License
/*
* Copyright 2002-2010 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.
*/
#endregion
using System.Collections.Generic;
using System.Globalization;
namespace Spring.Globalization
{
/// <summary>
/// Defines an interface that resource cache adapters have to implement.
/// </summary>
/// <author>Aleksandar Seovic</author>
public interface IResourceCache
{
/// <summary>
/// Gets the list of resources from cache.
/// </summary>
/// <param name="target">Target to get a list of resources for.</param>
/// <param name="culture">Resource culture.</param>
/// <returns>A list of cached resources for the specified target object and culture.</returns>
IList<Resource> GetResources(object target, CultureInfo culture);
/// <summary>
/// Puts the list of resources in the cache.
/// </summary>
/// <param name="target">Target to cache a list of resources for.</param>
/// <param name="culture">Resource culture.</param>
/// <param name="resources">A list of resources to cache.</param>
/// <returns>A list of cached resources for the specified target object and culture.</returns>
void PutResources(object target, CultureInfo culture, IList<Resource> resources);
}
}
|
spring-projects/spring-net
|
src/Spring/Spring.Core/Globalization/IResourceCache.cs
|
C#
|
apache-2.0
| 1,874
|
//=============================================================================
/**
* @file Network_Events.cpp
*
* $Id: Network_Events.cpp 95488 2012-01-24 13:32:10Z johnnyw $
*
*
* This application tests Reactor to make sure that it responds
* correctly to different kinds of network events.
*
* The test starts off by creating a Network_Listener, that listens
* for connections at ACE_DEFAULT_SERVER_PORT. When a client
* connects, a Network_Handler is created. Network_Handler reads
* messages off the socket and prints them out. This is done until
* the remote side shuts down. Multiple clients can connect at the
* same time.
*
* Events tested in this example includes ACCEPT, READ, and CLOSE masks.
*
* To run this example, start an instance of this example and
* connect to it using telnet (to port
* ACE_DEFAULT_SERVER_PORT(20002)).
*
*
* @author Irfan Pyarali
*/
//=============================================================================
#include "ace/Reactor.h"
#include "ace/WFMO_Reactor.h"
#include "ace/INET_Addr.h"
#include "ace/SOCK_Stream.h"
#include "ace/SOCK_Acceptor.h"
#include "ace/OS_main.h"
class Network_Handler : public ACE_Event_Handler
{
public:
/// Default constructor
Network_Handler (ACE_SOCK_Stream &s);
virtual int handle_input (ACE_HANDLE handle);
virtual int handle_close (ACE_HANDLE handle,
ACE_Reactor_Mask close_mask);
virtual ACE_HANDLE get_handle (void) const;
ACE_SOCK_Stream stream_;
};
Network_Handler::Network_Handler (ACE_SOCK_Stream &s)
: stream_ (s)
{
this->reactor (ACE_Reactor::instance ());
int result = this->reactor ()->register_handler (this, READ_MASK);
ACE_TEST_ASSERT (result == 0);
}
ACE_HANDLE
Network_Handler::get_handle (void) const
{
return this->stream_.get_handle ();
}
int
Network_Handler::handle_input (ACE_HANDLE handle)
{
ACE_DEBUG ((LM_DEBUG, "Network_Handler::handle_input handle = %d\n", handle));
while (1)
{
char message[BUFSIZ];
int result = this->stream_.recv (message, sizeof message);
if (result > 0)
{
message[result] = 0;
ACE_DEBUG ((LM_DEBUG, "Remote message: %s\n", message));
}
else if (result == 0)
{
ACE_DEBUG ((LM_DEBUG, "Connection closed\n"));
return -1;
}
else if (errno == EWOULDBLOCK)
{
return 0;
}
else
{
ACE_DEBUG ((LM_DEBUG, "Problems in receiving data, result = %d", result));
return -1;
}
}
}
int
Network_Handler::handle_close (ACE_HANDLE handle,
ACE_Reactor_Mask)
{
ACE_DEBUG ((LM_DEBUG, "Network_Handler::handle_close handle = %d\n", handle));
this->stream_.close ();
delete this;
ACE_Reactor::end_event_loop ();
return 0;
}
class Network_Listener : public ACE_Event_Handler
{
public:
/// Default constructor
/// Default constructor
Network_Listener (void);
~Network_Listener (void);
virtual int handle_input (ACE_HANDLE handle);
virtual int handle_close (ACE_HANDLE handle,
ACE_Reactor_Mask close_mask);
ACE_HANDLE get_handle (void) const;
ACE_INET_Addr local_address_;
ACE_SOCK_Acceptor acceptor_;
};
Network_Listener::Network_Listener (void)
: local_address_ (ACE_DEFAULT_SERVER_PORT),
acceptor_ (local_address_, 1)
{
this->reactor (ACE_Reactor::instance ());
int result = this->reactor ()->register_handler (this,
ACE_Event_Handler::ACCEPT_MASK);
ACE_TEST_ASSERT (result == 0);
}
Network_Listener::~Network_Listener (void)
{
}
ACE_HANDLE
Network_Listener::get_handle (void) const
{
return this->acceptor_.get_handle ();
}
int
Network_Listener::handle_input (ACE_HANDLE handle)
{
ACE_DEBUG ((LM_DEBUG, "Network_Listener::handle_input handle = %d\n", handle));
ACE_INET_Addr remote_address;
ACE_SOCK_Stream stream;
// Try to find out if the implementation of the reactor that we are
// using requires us to reset the event association for the newly
// created handle. This is because the newly created handle will
// inherit the properties of the listen handle, including its event
// associations.
int reset_new_handle = this->reactor ()->uses_event_associations ();
int result = this->acceptor_.accept (stream, // stream
&remote_address, // remote address
0, // timeout
1, // restart
reset_new_handle); // reset new handler
ACE_TEST_ASSERT (result == 0);
ACE_DEBUG ((LM_DEBUG, "Remote connection from: "));
remote_address.dump ();
Network_Handler *handler = 0;
ACE_NEW_RETURN (handler, Network_Handler (stream), -1);
return 0;
}
int
Network_Listener::handle_close (ACE_HANDLE handle,
ACE_Reactor_Mask)
{
ACE_DEBUG ((LM_DEBUG, "Network_Listener::handle_close handle = %d\n", handle));
this->acceptor_.close ();
delete this;
return 0;
}
int
ACE_TMAIN (int, ACE_TCHAR *[])
{
Network_Listener *listener = 0;
listener = new Network_Listener;
ACE_UNUSED_ARG (listener);
ACE_Reactor::run_event_loop ();
return 0;
};
|
batmancn/TinySDNController
|
ACE_wrappers/examples/Reactor/WFMO_Reactor/Network_Events.cpp
|
C++
|
apache-2.0
| 5,316
|
# Phoma punctispora McAlpine SPECIES
#### Status
ACCEPTED
#### According to
Index Fungorum
#### Published in
null
#### Original name
Phoma punctispora McAlpine
### Remarks
null
|
mdoering/backbone
|
life/Fungi/Ascomycota/Dothideomycetes/Pleosporales/Phoma/Phoma punctispora/README.md
|
Markdown
|
apache-2.0
| 181
|
package carbon.internal;
import android.content.Context;
import android.graphics.Typeface;
import java.util.HashMap;
public class TypefaceUtils {
public static HashMap<Roboto, Typeface> robotoCache = new HashMap<>();
public static HashMap<String, Typeface> pathCache = new HashMap<>();
public static HashMap[] familyStyleCache = new HashMap[4];
static {
familyStyleCache[Typeface.NORMAL] = new HashMap();
familyStyleCache[Typeface.ITALIC] = new HashMap();
familyStyleCache[Typeface.BOLD] = new HashMap();
familyStyleCache[Typeface.BOLD_ITALIC] = new HashMap();
}
public static Typeface getTypeface(Context context, String path) {
// get from cache
Typeface t = pathCache.get(path);
if (t != null)
return t;
// Roboto?
for (Roboto style : Roboto.values()) {
if (style.getPath().equals(path)) {
t = loadRoboto(context, style);
if (t != null)
return t;
}
}
// load from asset
t = Typeface.createFromAsset(context.getAssets(), path);
if (t != null) {
pathCache.put(path, t);
return t;
}
return Typeface.DEFAULT;
}
public static Typeface getTypeface(Context context, String fontFamily, int textStyle) {
// get from cache
Typeface t = (Typeface) familyStyleCache[textStyle].get(fontFamily);
if (t != null)
return t;
// Roboto?
for (Roboto style : Roboto.values()) {
if (style.getFontFamily().equals(fontFamily) && style.getTextStyle() == textStyle) {
t = loadRoboto(context, style);
if (t != null)
return t;
}
}
// load from system res
t = Typeface.create(fontFamily, textStyle);
if (t != null) {
familyStyleCache[textStyle].put(fontFamily, t);
return t;
}
return Typeface.DEFAULT;
}
public static Typeface getTypeface(Context context, Roboto roboto) {
// get from cache
Typeface t = robotoCache.get(roboto);
if (t != null)
return t;
t = loadRoboto(context, roboto);
if (t != null)
return t;
return Typeface.DEFAULT;
}
private static Typeface loadRoboto(Context context, Roboto roboto) {
// try to load asset
try {
Typeface t = Typeface.createFromAsset(context.getAssets(), roboto.getPath());
robotoCache.put(roboto, t);
pathCache.put(roboto.getPath(), t);
familyStyleCache[roboto.getTextStyle()].put(roboto.getFontFamily(), t);
return t;
} catch (Exception e) {
}
// try system font
Typeface t = Typeface.create(roboto.getFontFamily(), roboto.getTextStyle());
if (t != null) {
robotoCache.put(roboto, t);
pathCache.put(roboto.getPath(), t);
familyStyleCache[roboto.getTextStyle()].put(roboto.getFontFamily(), t);
return t;
}
return null;
}
}
|
Sai-Teja/Carbon
|
carbon/src/main/java/carbon/internal/TypefaceUtils.java
|
Java
|
apache-2.0
| 3,191
|
# Cylindrolobus soronensis (Schltr.) Brieger 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/Eria/Eria aporoides/ Syn. Cylindrolobus soronensis/README.md
|
Markdown
|
apache-2.0
| 199
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_172) on Wed Jul 25 07:27:33 CEST 2018 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>org.togglz.core.logging Class Hierarchy (Togglz 2.6.1.Final API)</title>
<meta name="date" content="2018-07-25">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="org.togglz.core.logging Class Hierarchy (Togglz 2.6.1.Final API)";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li>Class</li>
<li>Use</li>
<li class="navBarCell1Rev">Tree</li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../org/togglz/core/jndi/package-tree.html">Prev</a></li>
<li><a href="../../../../org/togglz/core/manager/package-tree.html">Next</a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?org/togglz/core/logging/package-tree.html" target="_top">Frames</a></li>
<li><a href="package-tree.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h1 class="title">Hierarchy For Package org.togglz.core.logging</h1>
<span class="packageHierarchyLabel">Package Hierarchies:</span>
<ul class="horizontal">
<li><a href="../../../../overview-tree.html">All Packages</a></li>
</ul>
</div>
<div class="contentContainer">
<h2 title="Class Hierarchy">Class Hierarchy</h2>
<ul>
<li type="circle">java.lang.<a href="http://download.oracle.com/javase/7/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang"><span class="typeNameLink">Object</span></a>
<ul>
<li type="circle">org.togglz.core.logging.<a href="../../../../org/togglz/core/logging/Jdk14LogProvider.html" title="class in org.togglz.core.logging"><span class="typeNameLink">Jdk14LogProvider</span></a> (implements org.togglz.core.spi.<a href="../../../../org/togglz/core/spi/LogProvider.html" title="interface in org.togglz.core.spi">LogProvider</a>)</li>
<li type="circle">org.togglz.core.logging.<a href="../../../../org/togglz/core/logging/Jdk14LogProvider.Jdk14Log.html" title="class in org.togglz.core.logging"><span class="typeNameLink">Jdk14LogProvider.Jdk14Log</span></a> (implements org.togglz.core.logging.<a href="../../../../org/togglz/core/logging/Log.html" title="interface in org.togglz.core.logging">Log</a>)</li>
<li type="circle">org.togglz.core.logging.<a href="../../../../org/togglz/core/logging/LogFactory.html" title="class in org.togglz.core.logging"><span class="typeNameLink">LogFactory</span></a></li>
<li type="circle">org.togglz.core.logging.<a href="../../../../org/togglz/core/logging/LoggingStateRepository.html" title="class in org.togglz.core.logging"><span class="typeNameLink">LoggingStateRepository</span></a> (implements org.togglz.core.repository.<a href="../../../../org/togglz/core/repository/StateRepository.html" title="interface in org.togglz.core.repository">StateRepository</a>)</li>
</ul>
</li>
</ul>
<h2 title="Interface Hierarchy">Interface Hierarchy</h2>
<ul>
<li type="circle">org.togglz.core.logging.<a href="../../../../org/togglz/core/logging/Log.html" title="interface in org.togglz.core.logging"><span class="typeNameLink">Log</span></a></li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li>Class</li>
<li>Use</li>
<li class="navBarCell1Rev">Tree</li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../org/togglz/core/jndi/package-tree.html">Prev</a></li>
<li><a href="../../../../org/togglz/core/manager/package-tree.html">Next</a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?org/togglz/core/logging/package-tree.html" target="_top">Frames</a></li>
<li><a href="package-tree.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2018. All Rights Reserved.</small></p>
</body>
</html>
|
togglz/togglz-site
|
apidocs/2.6.1.Final/org/togglz/core/logging/package-tree.html
|
HTML
|
apache-2.0
| 6,363
|
// Copyright 2018 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.api.ads.adwords.jaxws.v201809.cm;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
/**
*
* Error due to user not accepting the AdWords terms of service.
*
*
* <p>Java class for ClientTermsError complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="ClientTermsError">
* <complexContent>
* <extension base="{https://adwords.google.com/api/adwords/cm/v201809}ApiError">
* <sequence>
* <element name="reason" type="{https://adwords.google.com/api/adwords/cm/v201809}ClientTermsError.Reason" minOccurs="0"/>
* </sequence>
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "ClientTermsError", propOrder = {
"reason"
})
public class ClientTermsError
extends ApiError
{
@XmlSchemaType(name = "string")
protected ClientTermsErrorReason reason;
/**
* Gets the value of the reason property.
*
* @return
* possible object is
* {@link ClientTermsErrorReason }
*
*/
public ClientTermsErrorReason getReason() {
return reason;
}
/**
* Sets the value of the reason property.
*
* @param value
* allowed object is
* {@link ClientTermsErrorReason }
*
*/
public void setReason(ClientTermsErrorReason value) {
this.reason = value;
}
}
|
googleads/googleads-java-lib
|
modules/adwords_appengine/src/main/java/com/google/api/ads/adwords/jaxws/v201809/cm/ClientTermsError.java
|
Java
|
apache-2.0
| 2,287
|
package com.dinglian.server.chuqulang.utils;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.TimeZone;
import org.apache.commons.lang.StringUtils;
public class DateUtils {
private static final SimpleDateFormat dataFormat = new SimpleDateFormat("dd/MM/yyyy");
private static final SimpleDateFormat sqlDataFormat = new SimpleDateFormat("yyyy-MM-dd");
private static final SimpleDateFormat dataFormatWithTime = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
private static final SimpleDateFormat dataFormatWithTimeNoSecond = new SimpleDateFormat("dd/MM/yyyy HH:mm");
private static final SimpleDateFormat testFormatWithTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
private static final SimpleDateFormat millSecondFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss-SSS");
private static final SimpleDateFormat sqlDateFormatWithTime = new SimpleDateFormat("yyyy-MM-dd HH:mm");
private static final SimpleDateFormat dataFormatString = new SimpleDateFormat("yyMMdd");
private static final SimpleDateFormat dataFormatExtJs = new SimpleDateFormat("MMM dd yyyy");
private static final SimpleDateFormat dataFormatUS = new SimpleDateFormat("MM/dd/yy");
private static final SimpleDateFormat dataFormatToUS = new SimpleDateFormat("MMM-dd-yyyy", Locale.US);
private static final SimpleDateFormat dataFormatCombo = new SimpleDateFormat("yy/mm/dd HH:mm");
public static final SimpleDateFormat dateFormatString = new SimpleDateFormat("yyMMddHHmmss");
public static final SimpleDateFormat dateFormatYear = new SimpleDateFormat("yy");
public final static String defaultFormatStr = "dd/MM/yyyy";
public final static String dMyHm = "dd/MM/yyyy HH:mm";
public final static String dMyHms = "dd/MM/yyyy HH:mm:ss";
public final static String dMy = "dd/MM/yyyy";
public final static String yMdHms = "yyyy-MM-dd HH:mm:ss";
public final static String yMd = "yyyy-MM-dd";
public final static String yyyyMMddHM = "yyyyMMdd HH:mm";
public final static String yyyyMMddHmsMs = "yyyyMMdd HHmmssSSS";
public final static String yyyyMMddHmsMsWithNoSpace = "yyyyMMdd:HHmmssSSS";
public final static String SUNDAY = "sun";
public final static String MONDAY = "mon";
public final static String TUESDAY = "tue";
public final static String WEDNESDAY = "wed";
public final static String THURSDAY = "thu";
public final static String FRIDAY = "fri";
public final static String SATURDAY = "sat";
public final static String JANUARY = "January";
public final static String FEBRUARY = "February";
public final static String MARCH = "March";
public final static String APRIL = "April";
public final static String MAY = "May";
public final static String JUNE = "June";
public final static String JULY = "July";
public final static String AUGUST = "August";
public final static String SEPTEMBER = "September";
public final static String OCTOBER = "October";
public final static String NOVEMBER = "November";
public final static String DECEMBER = "December";
public final static String extDateFormat = "yyyy/MM/dd";
public static final String[] MONTH = { "January", "February", "March", "April", "May", "June", "July", "August",
"September", "October", "November", "December" };
/** Creates a new instance of DateUtils */
public DateUtils() {
}
public static String format(Date date, String format) {
if (date == null) {
return "";
}
SimpleDateFormat dataFormat = new SimpleDateFormat(format);
return dataFormat.format(date);
}
public static String format(Calendar calendar, String format) {
if (calendar == null) {
return "";
}
SimpleDateFormat dataFormat = new SimpleDateFormat(format);
return dataFormat.format(calendar.getTime());
}
public static Date parse(String dateStr, String format) {
if (StringUtils.isBlank(dateStr)) {
return null;
}
Date date = null;
SimpleDateFormat dataFormat = new SimpleDateFormat(format);
try {
date = dataFormat.parse(dateStr);
} catch (Exception ex) {
ex.printStackTrace();
}
return date;
}
public static String transeferFormat(String dateStr, String fromFormat, String toFormat) {
if (StringUtils.isBlank(dateStr)) {
return "";
}
Date date = parse(dateStr, fromFormat);
return format(date, toFormat);
}
public static Date parse(String dateStr, SimpleDateFormat format) {
if (StringUtils.isBlank(dateStr)) {
return null;
}
Date date = null;
try {
date = format.parse(dateStr);
} catch (Exception ex) {
ex.printStackTrace();
}
return date;
}
public static Calendar parseCalendar(String dateStr, String format) {
Date date = parse(dateStr, format);
if (date == null) {
return null;
}
Calendar calendar = GregorianCalendar.getInstance();
calendar.setTime(date);
return calendar;
}
public static String format(Date date) {
return dataFormat.format(date);
}
public static String simpleFormat(Date date) {
return dataFormatString.format(date);
}
public static String sqlDataFormat(Date date) {
return sqlDataFormat.format(date);
}
public static Date dataFormat(String date) throws ParseException {
return dataFormatCombo.parse(date);
}
public static Date sqlDataFormat(String date) throws ParseException {
return sqlDataFormat.parse(date);
}
public static String sqlDataStringFormat(String date) {
return sqlDataFormat.format(date);
}
public static String formatSqlWithTime(Date date) {
return sqlDateFormatWithTime.format(date);
}
public static String formatWithTime(Date date) {
return dataFormatWithTime.format(date);
}
public static String format(Calendar calendar) {
if (calendar == null) {
return "";
}
return format(calendar.getTime());
}
public static String formatSql(Calendar calendar) {
if (calendar == null) {
return "";
}
return sqlDataFormat(calendar.getTime());
}
public static String formatSqlWithTime(Calendar calendar) {
if (calendar == null) {
return "";
}
return formatSqlWithTime(calendar.getTime());
}
public static String formatSqlDataFormat(Calendar calendar) {
if (calendar == null) {
return "";
}
return sqlDataFormat(calendar.getTime());
}
public static String formatWithTime(Calendar calendar) {
if (calendar == null) {
return "";
}
return formatWithTime(calendar.getTime());
}
public static Date parse(String dateInStr) throws ParseException {
return dataFormat.parse(dateInStr);
}
public static Date parseWithTime(String dateInStr) throws ParseException {
return dataFormatWithTime.parse(dateInStr);
}
public static Date parseForExtJs(String dateInStr) throws ParseException {
return dataFormatExtJs.parse(dateInStr);
}
public static Date parseForUS(String dateInStr) throws ParseException {
return dataFormatUS.parse(dateInStr);
}
public static Calendar parseCalendar(String dateInStr, TimeZone timeZone) throws ParseException {
if (StringUtils.isBlank(dateInStr)) {
return null;
}
Date date = parse(dateInStr);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar;
}
public static Calendar parseCalendarWithTime(String dateInStr, TimeZone timeZone) throws ParseException {
if (StringUtils.isBlank(dateInStr)) {
return null;
}
Date date = parseWithTime(dateInStr);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar;
}
public static Calendar parseCalendarForExtJs(String dateInStr, TimeZone timeZone) throws ParseException {
if (StringUtils.isBlank(dateInStr)) {
return null;
}
Date date = parseForExtJs(dateInStr);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar;
}
public static Calendar parseCalendarUS(String dateInStr, TimeZone timeZone) throws ParseException {
if (StringUtils.isBlank(dateInStr)) {
return null;
}
Date date = parseForUS(dateInStr);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar;
}
public static Calendar getCalendar() throws ParseException {
Calendar calendar = Calendar.getInstance();
return calendar;
}
public static Date getSystemDate() throws ParseException {
// return DateUtils.sqlDataFormat(DateUtils.sqlDataFormat(new Date()));
String dateInStr = testFormatWithTime.format(new Date().getTime());
return sqlDateFormatWithTime.parse(dateInStr);
}
public static Date getSystemTime() throws ParseException {
Date systemTime = new Date();
String dateInStr = sqlDateFormatWithTime.format(new Date().getTime());
systemTime = sqlDateFormatWithTime.parse(dateInStr);
return systemTime;
}
public static String getSystemTimeStr() throws ParseException {
String dateInStr = sqlDateFormatWithTime.format(new Date().getTime());
return dateInStr;
}
public static String getCurrentTimeWithSecond() throws ParseException {
String dateInStr = testFormatWithTime.format(new Date().getTime());
return dateInStr;
}
public static long getDiffTimeWithSecond(String startTime, String endTime) throws ParseException {
Date startDate = testFormatWithTime.parse(startTime);
Date endDate = testFormatWithTime.parse(endTime);
long between = (endDate.getTime() - startDate.getTime()) / 1000;// return
// second
return between;
}
public static String getYearMonth(Date date) {
return dataFormatString.format(date).substring(0, 4);
}
public static String getDataFormatToUS(String date) {
return dataFormatToUS.format(date);
}
public static String getDataFormatToUS(Date date) throws ParseException {
return dataFormatToUS.format(date);
}
public static String getDataFormatWithTimeNoSecond(Date date) throws ParseException {
return dataFormatWithTimeNoSecond.format(date);
}
public static String getTimeStr() {
Calendar date = GregorianCalendar.getInstance();
String timeStr = dataFormatWithTime.format(date.getTime());
return timeStr;
}
public static String getTomorrowDateStr() {
Calendar tomorrowCalendar = GregorianCalendar.getInstance();
tomorrowCalendar.add(Calendar.DATE, 1);
String tomorrowDateStr = dataFormat.format(tomorrowCalendar.getTime());
return tomorrowDateStr;
}
public static String getCurrentDateStr() {
Calendar currentCalendar = GregorianCalendar.getInstance();
String currentDateStr = dataFormat.format(currentCalendar.getTime());
return currentDateStr;
}
public static String getDefaultCreateOrderDateFrom() {
Calendar nowDate = GregorianCalendar.getInstance();
nowDate.add(Calendar.MONTH, -1);
nowDate.set(Calendar.DAY_OF_MONTH, 1);
return dataFormat.format(nowDate.getTime());
}
public static String getDefaultCreateOrderDateTo() {
Calendar nowDate = GregorianCalendar.getInstance();
return dataFormat.format(nowDate.getTime());
}
public static String getPreviousSixMonthDate() {
Calendar nowDate = GregorianCalendar.getInstance();
nowDate.add(Calendar.MONTH, -6);
nowDate.set(Calendar.DAY_OF_MONTH, 1);
String date = dataFormat.format(nowDate.getTime());
return date;
}
public static String getPreviousThreeMonthDate() {
Calendar nowDate = GregorianCalendar.getInstance();
nowDate.add(Calendar.MONTH, -3);
nowDate.set(Calendar.DAY_OF_MONTH, 1);
String date = dataFormat.format(nowDate.getTime());
return date;
}
public static String getPreviousMonthDate(int beforeMonth) {
Calendar nowDate = GregorianCalendar.getInstance();
nowDate.add(Calendar.MONTH, beforeMonth);
nowDate.set(Calendar.DAY_OF_MONTH, 1);
String date = dataFormat.format(nowDate.getTime());
return date;
}
public static int getYearsSoFar() {
Calendar nowTime = GregorianCalendar.getInstance();
return nowTime.get(Calendar.YEAR);
}
public static Calendar getRequestShipDate(int day) {
Calendar currentCalendar = GregorianCalendar.getInstance();
currentCalendar.add(Calendar.DAY_OF_YEAR, day);
return currentCalendar;
}
public static Date getRangeDate(int day) {
Calendar currentCalendar = GregorianCalendar.getInstance();
currentCalendar.add(Calendar.DAY_OF_YEAR, day);
Date date = currentCalendar.getTime();
return date;
}
public static String millSecondFormat(Calendar calendar) {
if (calendar == null) {
return "";
}
return millSecondFormat.format(calendar.getTime());
}
public static boolean isDateField(String value) {
boolean isDateField = false;
SimpleDateFormat dMyDateFormat = new SimpleDateFormat(DateUtils.dMy);
dMyDateFormat.setLenient(false);
try {
dMyDateFormat.parse(value);
isDateField = true;
} catch (Exception e) {
isDateField = false;
}
return isDateField;
}
public static boolean isInTime(String periodTime) {
if (StringUtils.isBlank(periodTime)) {
return false;
}
String[] periodTimeArray = periodTime.split("-");
if (periodTimeArray == null || periodTimeArray.length < 2) {
return false;
}
String[] beginTimeArray = periodTimeArray[0].split(":");
String[] endTimeArray = periodTimeArray[1].split(":");
if (beginTimeArray == null || endTimeArray == null || beginTimeArray.length < 2 || endTimeArray.length < 2) {
return false;
}
int beginTime = Integer.parseInt(beginTimeArray[0]) * 60 + Integer.parseInt(beginTimeArray[1]);
int endTime = Integer.parseInt(endTimeArray[0]) * 60 + Integer.parseInt(endTimeArray[1]);
Calendar currentDateTime = Calendar.getInstance();
int hour = currentDateTime.get(Calendar.HOUR_OF_DAY);
int minute = currentDateTime.get(Calendar.MINUTE);
int currentTime = hour * 60 + minute;
if (currentTime >= beginTime && currentTime <= endTime) {
return true;
}
return false;
}
// format of periodTime must is Time-Time,Time is HH:mm or H:m or HH:m or
// H:mm, example : 07:16-18:22
// return value unit minute
public static int getDiffTime(String periodTime) {
if (StringUtils.isBlank(periodTime)) {
return -1;
}
String[] periodTimeArray = periodTime.split("-");
if (periodTimeArray == null || periodTimeArray.length < 2) {
return -1;
}
String[] beginTimeArray = periodTimeArray[0].split(":");
String[] endTimeArray = periodTimeArray[1].split(":");
if (beginTimeArray == null || endTimeArray == null || beginTimeArray.length < 2 || endTimeArray.length < 2) {
return -1;
}
int beginTime = Integer.parseInt(beginTimeArray[0]) * 60 + Integer.parseInt(beginTimeArray[1]);
int endTime = Integer.parseInt(endTimeArray[0]) * 60 + Integer.parseInt(endTimeArray[1]);
return endTime - beginTime;
}
public static String getCurrentYearDigits() {
Date nowDate = new Date(System.currentTimeMillis());
SimpleDateFormat bartDateFormat = dateFormatYear;
String year = bartDateFormat.format(nowDate);
return year;
}
public static String getWeekDay(int dayOfWeek) {
switch (dayOfWeek) {
case 1:
return SUNDAY;
case 2:
return MONDAY;
case 3:
return TUESDAY;
case 4:
return WEDNESDAY;
case 5:
return THURSDAY;
case 6:
return FRIDAY;
case 7:
return SATURDAY;
default:
return "Non";
}
}
public static String getMonth(int monthOfYear) {
switch (monthOfYear) {
case 0:
return JANUARY;
case 1:
return FEBRUARY;
case 2:
return MARCH;
case 3:
return APRIL;
case 4:
return MAY;
case 5:
return JUNE;
case 6:
return JULY;
case 7:
return AUGUST;
case 8:
return SEPTEMBER;
case 9:
return OCTOBER;
case 10:
return NOVEMBER;
case 11:
return DECEMBER;
default:
return "Non";
}
}
public static boolean isIncludeCurrentDay(String exeDays) {
Calendar currentDate = Calendar.getInstance();
int dayOfWeek = currentDate.get(Calendar.DAY_OF_WEEK);
return exeDays.contains(getWeekDay(dayOfWeek));
}
public static int transerWeekDay(int weekDay) throws Exception {
if (weekDay < 1 || weekDay > 7) {
throw new Exception("week day only 1-7");
}
if (weekDay == 7) {
return 1;
} else {
return weekDay + 1;
}
}
}
|
fyunxu/chuqulang
|
src/main/java/com/dinglian/server/chuqulang/utils/DateUtils.java
|
Java
|
apache-2.0
| 16,528
|
package com.github.mkopylec.charon.configuration;
import java.util.function.Consumer;
import com.github.mkopylec.charon.forwarding.RestTemplateConfigurer;
import com.github.mkopylec.charon.forwarding.interceptors.RequestForwardingInterceptorConfigurer;
import com.github.mkopylec.charon.forwarding.interceptors.RequestForwardingInterceptorType;
import static org.springframework.util.Assert.notNull;
public class CharonConfigurer extends Configurer<CharonConfiguration> {
private CharonConfigurer() {
super(new CharonConfiguration());
}
public static CharonConfigurer charonConfiguration() {
return new CharonConfigurer();
}
public CharonConfigurer filterOrder(int filterOrder) {
configuredObject.setFilterOrder(filterOrder);
return this;
}
public CharonConfigurer set(RestTemplateConfigurer restTemplateConfigurer) {
configuredObject.setRestTemplateConfiguration(restTemplateConfigurer.configure());
return this;
}
public CharonConfigurer set(RequestForwardingInterceptorConfigurer<?> requestForwardingInterceptorConfigurer) {
configuredObject.addRequestForwardingInterceptor(requestForwardingInterceptorConfigurer.configure());
return this;
}
public CharonConfigurer unset(RequestForwardingInterceptorType requestForwardingInterceptorType) {
configuredObject.removeRequestForwardingInterceptor(requestForwardingInterceptorType);
return this;
}
public CharonConfigurer add(RequestMappingConfigurer requestMappingConfigurer) {
configuredObject.addRequestMappingConfiguration(requestMappingConfigurer.configure());
return this;
}
public CharonConfigurer update(String requestMappingName, Consumer<RequestMappingConfigurer> requestMappingConfigurerUpdate) {
RequestMappingConfigurer requestMappingConfigurer = configuredObject.getRequestMappingConfigurer(requestMappingName);
notNull(requestMappingConfigurer, "Request mapping '" + requestMappingName + "' not found");
requestMappingConfigurerUpdate.accept(requestMappingConfigurer);
configuredObject.addRequestMappingConfiguration(requestMappingConfigurer.configure());
return this;
}
@Override
protected CharonConfiguration configure() {
configuredObject.mergeWithRequestMappingConfigurations();
return super.configure();
}
}
|
mkopylec/charon-spring-boot-starter
|
charon-spring-webmvc/src/main/java/com/github/mkopylec/charon/configuration/CharonConfigurer.java
|
Java
|
apache-2.0
| 2,417
|
# java-mongodb
Just simples tests with JAVA and MongoDB
|
albertocerqueira/java-mongodb
|
README.md
|
Markdown
|
apache-2.0
| 56
|
# 14. Practice Project - 94%


[:scroll: Solution](solutions/13. Practice Project - 94%25)
|
joan38/Learn-Programming-Scala
|
course/14. Practice Project - 94%.md
|
Markdown
|
apache-2.0
| 148
|
/*
* Copyright 2010 ZXing 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.
*/
using System;
using System.Collections.Generic;
using System.Text;
using ZXing.Common;
namespace ZXing.OneD
{
/// <summary>
/// <p>Decodes Code 93 barcodes.</p>
/// <author>Sean Owen</author>
/// <see cref="Code39Reader" />
/// </summary>
public sealed class Code93Reader : OneDReader
{
// Note that 'abcd' are dummy characters in place of control characters.
internal const String ALPHABET_STRING = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. $/+%abcd*";
private static readonly char[] ALPHABET = ALPHABET_STRING.ToCharArray();
/// <summary>
/// These represent the encodings of characters, as patterns of wide and narrow bars.
/// The 9 least-significant bits of each int correspond to the pattern of wide and narrow.
/// </summary>
internal static readonly int[] CHARACTER_ENCODINGS = {
0x114, 0x148, 0x144, 0x142, 0x128, 0x124, 0x122, 0x150, 0x112, 0x10A, // 0-9
0x1A8, 0x1A4, 0x1A2, 0x194, 0x192, 0x18A, 0x168, 0x164, 0x162, 0x134, // A-J
0x11A, 0x158, 0x14C, 0x146, 0x12C, 0x116, 0x1B4, 0x1B2, 0x1AC, 0x1A6, // K-T
0x196, 0x19A, 0x16C, 0x166, 0x136, 0x13A, // U-Z
0x12E, 0x1D4, 0x1D2, 0x1CA, 0x16E, 0x176, 0x1AE, // - - %
0x126, 0x1DA, 0x1D6, 0x132, 0x15E, // Control chars? $-*
};
private static readonly int ASTERISK_ENCODING = CHARACTER_ENCODINGS[47];
private readonly StringBuilder decodeRowResult;
private readonly int[] counters;
/// <summary>
/// Initializes a new instance of the <see cref="Code93Reader"/> class.
/// </summary>
public Code93Reader()
{
decodeRowResult = new StringBuilder(20);
counters = new int[6];
}
/// <summary>
/// <p>Attempts to decode a one-dimensional barcode format given a single row of
/// an image.</p>
/// </summary>
/// <param name="rowNumber">row number from top of the row</param>
/// <param name="row">the black/white pixel data of the row</param>
/// <param name="hints">decode hints</param>
/// <returns><see cref="Result"/>containing encoded string and start/end of barcode</returns>
override public Result decodeRow(int rowNumber, BitArray row, IDictionary<DecodeHintType, object> hints)
{
for (var index = 0; index < counters.Length; index++)
counters[index] = 0;
decodeRowResult.Length = 0;
int[] start = findAsteriskPattern(row);
if (start == null)
return null;
// Read off white space
int nextStart = row.getNextSet(start[1]);
int end = row.Size;
char decodedChar;
int lastStart;
do
{
if (!recordPattern(row, nextStart, counters))
return null;
int pattern = toPattern(counters);
if (pattern < 0)
{
return null;
}
if (!patternToChar(pattern, out decodedChar))
return null;
decodeRowResult.Append(decodedChar);
lastStart = nextStart;
foreach (int counter in counters)
{
nextStart += counter;
}
// Read off white space
nextStart = row.getNextSet(nextStart);
} while (decodedChar != '*');
decodeRowResult.Remove(decodeRowResult.Length - 1, 1); // remove asterisk
int lastPatternSize = 0;
foreach (int counter in counters)
{
lastPatternSize += counter;
}
// Should be at least one more black module
if (nextStart == end || !row[nextStart])
{
return null;
}
if (decodeRowResult.Length < 2)
{
// false positive -- need at least 2 checksum digits
return null;
}
if (!checkChecksums(decodeRowResult))
return null;
// Remove checksum digits
decodeRowResult.Length = decodeRowResult.Length - 2;
String resultString = decodeExtended(decodeRowResult);
if (resultString == null)
return null;
float left = (start[1] + start[0])/2.0f;
float right = lastStart + lastPatternSize / 2.0f;
var resultPointCallback = hints == null || !hints.ContainsKey(DecodeHintType.NEED_RESULT_POINT_CALLBACK)
? null
: (ResultPointCallback) hints[DecodeHintType.NEED_RESULT_POINT_CALLBACK];
if (resultPointCallback != null)
{
resultPointCallback(new ResultPoint(left, rowNumber));
resultPointCallback(new ResultPoint(right, rowNumber));
}
return new Result(
resultString,
null,
new[]
{
new ResultPoint(left, rowNumber),
new ResultPoint(right, rowNumber)
},
BarcodeFormat.CODE_93);
}
private int[] findAsteriskPattern(BitArray row)
{
int width = row.Size;
int rowOffset = row.getNextSet(0);
for (var index = 0; index < counters.Length; index++)
counters[index] = 0;
int counterPosition = 0;
int patternStart = rowOffset;
bool isWhite = false;
int patternLength = counters.Length;
for (int i = rowOffset; i < width; i++)
{
if (row[i] != isWhite)
{
counters[counterPosition]++;
}
else
{
if (counterPosition == patternLength - 1)
{
if (toPattern(counters) == ASTERISK_ENCODING)
{
return new int[] { patternStart, i };
}
patternStart += counters[0] + counters[1];
Array.Copy(counters, 2, counters, 0, counterPosition - 1);
counters[counterPosition - 1] = 0;
counters[counterPosition] = 0;
counterPosition--;
}
else
{
counterPosition++;
}
counters[counterPosition] = 1;
isWhite = !isWhite;
}
}
return null;
}
private static int toPattern(int[] counters)
{
int max = counters.Length;
int sum = 0;
foreach (var counter in counters)
{
sum += counter;
}
int pattern = 0;
for (int i = 0; i < max; i++)
{
int scaledShifted = (counters[i] << INTEGER_MATH_SHIFT) * 9 / sum;
int scaledUnshifted = scaledShifted >> INTEGER_MATH_SHIFT;
if ((scaledShifted & 0xFF) > 0x7F)
{
scaledUnshifted++;
}
if (scaledUnshifted < 1 || scaledUnshifted > 4)
{
return -1;
}
if ((i & 0x01) == 0)
{
for (int j = 0; j < scaledUnshifted; j++)
{
pattern = (pattern << 1) | 0x01;
}
}
else
{
pattern <<= scaledUnshifted;
}
}
return pattern;
}
private static bool patternToChar(int pattern, out char c)
{
for (int i = 0; i < CHARACTER_ENCODINGS.Length; i++)
{
if (CHARACTER_ENCODINGS[i] == pattern)
{
c = ALPHABET[i];
return true;
}
}
c = '*';
return false;
}
private static String decodeExtended(StringBuilder encoded)
{
int length = encoded.Length;
StringBuilder decoded = new StringBuilder(length);
for (int i = 0; i < length; i++)
{
char c = encoded[i];
if (c >= 'a' && c <= 'd')
{
if (i >= length - 1)
{
return null;
}
char next = encoded[i + 1];
char decodedChar = '\0';
switch (c)
{
case 'd':
// +A to +Z map to a to z
if (next >= 'A' && next <= 'Z')
{
decodedChar = (char)(next + 32);
}
else
{
return null;
}
break;
case 'a':
// $A to $Z map to control codes SH to SB
if (next >= 'A' && next <= 'Z')
{
decodedChar = (char)(next - 64);
}
else
{
return null;
}
break;
case 'b':
if (next >= 'A' && next <= 'E')
{
// %A to %E map to control codes ESC to USep
decodedChar = (char)(next - 38);
}
else if (next >= 'F' && next <= 'J') {
// %F to %J map to ; < = > ?
decodedChar = (char) (next - 11);
}
else if (next >= 'K' && next <= 'O') {
// %K to %O map to [ \ ] ^ _
decodedChar = (char) (next + 16);
}
else if (next >= 'P' && next <= 'S') {
// %P to %S map to { | } ~
decodedChar = (char) (next + 43);
}
else if (next >= 'T' && next <= 'Z')
{
// %T to %Z all map to DEL (127)
decodedChar = (char)127;
}
else
{
return null;
}
break;
case 'c':
// /A to /O map to ! to , and /Z maps to :
if (next >= 'A' && next <= 'O')
{
decodedChar = (char)(next - 32);
}
else if (next == 'Z')
{
decodedChar = ':';
}
else
{
return null;
}
break;
}
decoded.Append(decodedChar);
// bump up i again since we read two characters
i++;
}
else
{
decoded.Append(c);
}
}
return decoded.ToString();
}
private static bool checkChecksums(StringBuilder result)
{
int length = result.Length;
if (!checkOneChecksum(result, length - 2, 20))
return false;
if (!checkOneChecksum(result, length - 1, 15))
return false;
return true;
}
private static bool checkOneChecksum(StringBuilder result, int checkPosition, int weightMax)
{
int weight = 1;
int total = 0;
for (int i = checkPosition - 1; i >= 0; i--)
{
total += weight * ALPHABET_STRING.IndexOf(result[i]);
if (++weight > weightMax)
{
weight = 1;
}
}
if (result[checkPosition] != ALPHABET[total % 47])
{
return false;
}
return true;
}
}
}
|
bsoja/ZXing.Net
|
Source/lib/oned/Code93Reader.cs
|
C#
|
apache-2.0
| 13,124
|
/*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.ssmcontacts.model.transform;
import java.math.*;
import javax.annotation.Generated;
import com.amazonaws.services.ssmcontacts.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;
import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;
/**
* InternalServerException JSON Unmarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class InternalServerExceptionUnmarshaller extends EnhancedJsonErrorUnmarshaller {
private InternalServerExceptionUnmarshaller() {
super(com.amazonaws.services.ssmcontacts.model.InternalServerException.class, "InternalServerException");
}
@Override
public com.amazonaws.services.ssmcontacts.model.InternalServerException unmarshallFromContext(JsonUnmarshallerContext context) throws Exception {
com.amazonaws.services.ssmcontacts.model.InternalServerException internalServerException = new com.amazonaws.services.ssmcontacts.model.InternalServerException(
null);
int originalDepth = context.getCurrentDepth();
String currentParentElement = context.getCurrentParentElement();
int targetDepth = originalDepth + 1;
JsonToken token = context.getCurrentToken();
if (token == null)
token = context.nextToken();
if (token == VALUE_NULL) {
return null;
}
while (true) {
if (token == null)
break;
if (token == FIELD_NAME || token == START_OBJECT) {
if (context.testExpression("RetryAfterSeconds", targetDepth)) {
context.nextToken();
internalServerException.setRetryAfterSeconds(context.getUnmarshaller(Integer.class).unmarshall(context));
}
} else if (token == END_ARRAY || token == END_OBJECT) {
if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
if (context.getCurrentDepth() <= originalDepth)
break;
}
}
token = context.nextToken();
}
return internalServerException;
}
private static InternalServerExceptionUnmarshaller instance;
public static InternalServerExceptionUnmarshaller getInstance() {
if (instance == null)
instance = new InternalServerExceptionUnmarshaller();
return instance;
}
}
|
aws/aws-sdk-java
|
aws-java-sdk-ssmcontacts/src/main/java/com/amazonaws/services/ssmcontacts/model/transform/InternalServerExceptionUnmarshaller.java
|
Java
|
apache-2.0
| 3,147
|
//------------------------------------------------------------------------------
// <auto-generated>
// 此代码由工具生成。
// 运行时版本:4.0.30319.1
//
// 对此文件的更改可能会导致不正确的行为,并且如果
// 重新生成代码,这些更改将会丢失。
// </auto-generated>
//------------------------------------------------------------------------------
namespace dp2Circulation.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "10.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default {
get {
return defaultInstance;
}
}
}
}
|
renyh1013/dp2
|
dp2Circulation/Properties/Settings.Designer.cs
|
C#
|
apache-2.0
| 1,084
|
package org.codehaus.plexus.archiver.diags;
/*
* Copyright 2014 The Codehaus Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import org.codehaus.plexus.archiver.ArchiveEntry;
import org.codehaus.plexus.archiver.ArchivedFileSet;
import org.codehaus.plexus.archiver.Archiver;
import org.codehaus.plexus.archiver.ArchiverException;
import org.codehaus.plexus.archiver.FileSet;
import org.codehaus.plexus.archiver.ResourceIterator;
import org.codehaus.plexus.components.io.resources.PlexusIoResource;
import org.codehaus.plexus.components.io.resources.PlexusIoResourceCollection;
import javax.annotation.Nonnull;
import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.Map;
/**
* An archiver that does nothing. Really.
*/
@SuppressWarnings( "UnusedDeclaration" )
public class NoOpArchiver implements Archiver
{
boolean useJvmChmod;
private boolean ignorePermissions;
public void createArchive()
throws ArchiverException, IOException
{
}
public void addDirectory( @Nonnull File directory )
throws ArchiverException
{
}
public void addDirectory( @Nonnull File directory, String prefix )
throws ArchiverException
{
}
public void addDirectory( @Nonnull File directory, String[] includes, String[] excludes )
throws ArchiverException
{
}
public void addDirectory( @Nonnull File directory, String prefix, String[] includes, String[] excludes )
throws ArchiverException
{
}
public void addFileSet( @Nonnull FileSet fileSet )
throws ArchiverException
{
}
public void addSymlink( String symlinkName, String symlinkDestination )
throws ArchiverException
{
}
public void addSymlink( String symlinkName, int permissions, String symlinkDestination )
throws ArchiverException
{
}
public void addFile( @Nonnull File inputFile, @Nonnull String destFileName )
throws ArchiverException
{
}
public void addFile( @Nonnull File inputFile, @Nonnull String destFileName, int permissions )
throws ArchiverException
{
}
public void addArchivedFileSet( @Nonnull File archiveFile )
throws ArchiverException
{
}
public void addArchivedFileSet( @Nonnull File archiveFile, String prefix )
throws ArchiverException
{
}
public void addArchivedFileSet( File archiveFile, String[] includes, String[] excludes )
throws ArchiverException
{
}
public void addArchivedFileSet( @Nonnull File archiveFile, String prefix, String[] includes, String[] excludes )
throws ArchiverException
{
}
public void addArchivedFileSet( ArchivedFileSet fileSet )
throws ArchiverException
{
}
public void addResource( PlexusIoResource resource, String destFileName, int permissions )
throws ArchiverException
{
}
public void addResources( PlexusIoResourceCollection resources )
throws ArchiverException
{
}
public File getDestFile()
{
return null;
}
public void setDestFile( File destFile )
{
}
public void setFileMode( int mode )
{
}
public int getFileMode()
{
return 0;
}
public int getOverrideFileMode()
{
return 0;
}
public void setDefaultFileMode( int mode )
{
}
public int getDefaultFileMode()
{
return 0;
}
public void setDirectoryMode( int mode )
{
}
public int getDirectoryMode()
{
return 0;
}
public int getOverrideDirectoryMode()
{
return 0;
}
public void setDefaultDirectoryMode( int mode )
{
}
public int getDefaultDirectoryMode()
{
return 0;
}
public boolean getIncludeEmptyDirs()
{
return false;
}
public void setIncludeEmptyDirs( boolean includeEmptyDirs )
{
}
public void setDotFileDirectory( File dotFileDirectory )
{
}
@Nonnull
public ResourceIterator getResources()
throws ArchiverException
{
return new ResourceIterator()
{
public boolean hasNext()
{
return false;
}
public ArchiveEntry next()
{
return null;
}
public void remove() {
throw new UnsupportedOperationException("remove");
}
};
}
public Map<String, ArchiveEntry> getFiles()
{
return Collections.emptyMap();
}
public boolean isForced()
{
return false;
}
public void setForced( boolean forced )
{
}
public boolean isSupportingForced()
{
return false;
}
public String getDuplicateBehavior()
{
return null;
}
public void setDuplicateBehavior( String duplicate )
{
}
public void setUseJvmChmod( boolean useJvmChmod )
{
this.useJvmChmod = useJvmChmod;
}
public boolean isUseJvmChmod()
{
return useJvmChmod;
}
public boolean isIgnorePermissions()
{
return ignorePermissions;
}
public void setIgnorePermissions( boolean ignorePermissions )
{
this.ignorePermissions = ignorePermissions;
}
}
|
sonatype/plexus-archiver
|
src/main/java/org/codehaus/plexus/archiver/diags/NoOpArchiver.java
|
Java
|
apache-2.0
| 5,917
|
// Generated from /POI/java/org/apache/poi/ss/formula/functions/Sumx2my2.java
#pragma once
#include <fwd-POI.hpp>
#include <org/apache/poi/ss/formula/functions/fwd-POI.hpp>
#include <java/lang/Object.hpp>
#include <org/apache/poi/ss/formula/functions/XYNumericFunction_Accumulator.hpp>
struct default_init_tag;
class poi::ss::formula::functions::Sumx2my2_1
: public virtual ::java::lang::Object
, public virtual XYNumericFunction_Accumulator
{
public:
typedef ::java::lang::Object super;
double accumulate(double x, double y) override;
// Generated
Sumx2my2_1();
static ::java::lang::Class *class_();
private:
virtual ::java::lang::Class* getClass0();
friend class Sumx2my2;
};
|
pebble2015/cpoi
|
src/org/apache/poi/ss/formula/functions/Sumx2my2_1.hpp
|
C++
|
apache-2.0
| 721
|
package co.edu.usbcali.modelo;
// Generated 16/03/2015 02:47:53 PM by Hibernate Tools 4.0.0
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
/**
* Usuarios generated by hbm2java
*/
public class Usuarios implements java.io.Serializable {
private Long codigoUsua;
private Roles roles;
private String nombre;
private String clave;
private String email;
private Date fechaCreacion;
private Date fechaModifcacion;
private String usuCrea;
private String usuModifica;
private String estadoRegistro;
private Set<Colecciones> coleccioneses = new HashSet<Colecciones>(0);
private Set<Articulos> articuloses = new HashSet<Articulos>(0);
private Set<EventosArticulos> eventosArticuloses = new HashSet<EventosArticulos>(0);
public Usuarios() {
}
public Usuarios(Long codigoUsua, Roles roles, String nombre, String clave, String email, Date fechaCreacion, String usuCrea, String estadoRegistro) {
this.codigoUsua = codigoUsua;
this.roles = roles;
this.nombre = nombre;
this.clave = clave;
this.email = email;
this.fechaCreacion = fechaCreacion;
this.usuCrea = usuCrea;
this.estadoRegistro = estadoRegistro;
}
public Usuarios(Long codigoUsua, Roles roles, String nombre, String clave, String email, Date fechaCreacion, Date fechaModifcacion, String usuCrea, String usuModifica, String estadoRegistro, Set<Colecciones> coleccioneses, Set<Articulos> articuloses, Set<EventosArticulos> eventosArticuloses) {
this.codigoUsua = codigoUsua;
this.roles = roles;
this.nombre = nombre;
this.clave = clave;
this.email = email;
this.fechaCreacion = fechaCreacion;
this.fechaModifcacion = fechaModifcacion;
this.usuCrea = usuCrea;
this.usuModifica = usuModifica;
this.estadoRegistro = estadoRegistro;
this.coleccioneses = coleccioneses;
this.articuloses = articuloses;
this.eventosArticuloses = eventosArticuloses;
}
public Long getCodigoUsua() {
return this.codigoUsua;
}
public void setCodigoUsua(Long codigoUsua) {
this.codigoUsua = codigoUsua;
}
public Roles getRoles() {
return this.roles;
}
public void setRoles(Roles roles) {
this.roles = roles;
}
public String getNombre() {
return this.nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getClave() {
return this.clave;
}
public void setClave(String clave) {
this.clave = clave;
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
public Date getFechaCreacion() {
return this.fechaCreacion;
}
public void setFechaCreacion(Date fechaCreacion) {
this.fechaCreacion = fechaCreacion;
}
public Date getFechaModifcacion() {
return this.fechaModifcacion;
}
public void setFechaModifcacion(Date fechaModifcacion) {
this.fechaModifcacion = fechaModifcacion;
}
public String getUsuCrea() {
return this.usuCrea;
}
public void setUsuCrea(String usuCrea) {
this.usuCrea = usuCrea;
}
public String getUsuModifica() {
return this.usuModifica;
}
public void setUsuModifica(String usuModifica) {
this.usuModifica = usuModifica;
}
public String getEstadoRegistro() {
return this.estadoRegistro;
}
public void setEstadoRegistro(String estadoRegistro) {
this.estadoRegistro = estadoRegistro;
}
public Set<Colecciones> getColeccioneses() {
return this.coleccioneses;
}
public void setColeccioneses(Set<Colecciones> coleccioneses) {
this.coleccioneses = coleccioneses;
}
public Set<Articulos> getArticuloses() {
return this.articuloses;
}
public void setArticuloses(Set<Articulos> articuloses) {
this.articuloses = articuloses;
}
public Set<EventosArticulos> getEventosArticuloses() {
return this.eventosArticuloses;
}
public void setEventosArticuloses(Set<EventosArticulos> eventosArticuloses) {
this.eventosArticuloses = eventosArticuloses;
}
}
|
cesarvarela04/IntegradorVaoiFeed
|
IntegradorVaoiFeeds/src/co/edu/usbcali/modelo/Usuarios.java
|
Java
|
apache-2.0
| 4,421
|
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Aritmath.Entities
{
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
public partial class ClientsEntities : DbContext
{
public ClientsEntities()
: base("name=ClientsEntities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public virtual DbSet<User> Users { get; set; }
}
}
|
pirumpi/WCF_App
|
Aritmath/Entities/Clients.Context.cs
|
C#
|
apache-2.0
| 937
|
package com.jakewharton.trakt.services;
import com.google.myjson.JsonArray;
import com.google.myjson.JsonObject;
import com.google.myjson.reflect.TypeToken;
import com.jakewharton.trakt.TraktApiBuilder;
import com.jakewharton.trakt.TraktApiService;
import com.jakewharton.trakt.entities.Response;
import com.jakewharton.trakt.entities.Shout;
import com.jakewharton.trakt.entities.TvEntity;
import com.jakewharton.trakt.entities.TvShow;
import com.jakewharton.trakt.entities.TvShowEpisode;
import com.jakewharton.trakt.entities.TvShowSeason;
import com.jakewharton.trakt.entities.UserProfile;
import java.util.List;
public class ShowService extends TraktApiService {
/**
* <p>Notify Trakt that a user has stopped watching a show.</p>
*
* <p><em>Warning</em>: This method requires a developer API key.</p>
*
* @return Builder instance.
*/
public CancelWatchingBuilder cancelWatching() {
return new CancelWatchingBuilder(this);
}
/**
* Add unwatched episodes to your library.
*
* @param imdbId Show IMDB ID.
* @return Builder instance.
*/
public EpisodeLibraryBuilder episodeLibrary(String imdbId) {
return new EpisodeLibraryBuilder(this).imdbId(imdbId);
}
/**
* Add unwatched episodes to your library.
*
* @param tvdbId Show TVDB ID.
* @return Builder instance.
*/
public EpisodeLibraryBuilder episodeLibrary(int tvdbId) {
return new EpisodeLibraryBuilder(this).tvdbId(tvdbId);
}
/**
* Add unwatched episodes to your library.
*
* @param title Show title.
* @param year Show year.
* @return Builder instance.
*/
public EpisodeLibraryBuilder episodeLibrary(String title, int year) {
return new EpisodeLibraryBuilder(this).title(title).year(year);
}
/**
* Add episodes watched outside of trakt to your library.
*
* @param imdbId Show IMDB ID.
* @return Builder instance.
*/
public EpisodeSeenBuilder episodeSeen(String imdbId) {
return new EpisodeSeenBuilder(this).imdbId(imdbId);
}
/**
* Add episodes watched outside of trakt to your library.
*
* @param tvdbId Show TVDB ID.
* @return Builder instance.
*/
public EpisodeSeenBuilder episodeSeen(int tvdbId) {
return new EpisodeSeenBuilder(this).tvdbId(tvdbId);
}
/**
* Add episodes watched outside of trakt to your library.
*
* @param title Show title.
* @param year Show year.
* @return Builder instance.
*/
public EpisodeSeenBuilder episodeSeen(String title, int year) {
return new EpisodeSeenBuilder(this).title(title).year(year);
}
/**
* Returns information for an episode including ratings.
*
* @param tvdbId The TVDB ID.
* @param season The season number. Use 0 if you want the specials.
* @param episode The episode number.
* @return Builder instance.
*/
public EpisodeSummaryBuilder episodeSummary(int tvdbId, int season, int episode) {
return (new EpisodeSummaryBuilder(this)).tvdbId(tvdbId).season(season).episode(episode);
}
/**
* Returns information for an episode including ratings.
*
* @param title Either the slug (i.e. the-walking-dead) or TVDB ID. You can
* get a show's slug by browsing the website and looking at the URL when on
* a show summary page.
* @param season The season number. Use 0 if you want the specials.
* @param episode The episode number.
* @return Builder instance.
*/
public EpisodeSummaryBuilder episodeSummary(String title, int season, int episode) {
return (new EpisodeSummaryBuilder(this)).title(title).season(season).episode(episode);
}
/**
* Remove episodes from your library collection.
*
* @param imdbId Show IMDB ID.
* @return Builder instance.
*/
public EpisodeUnlibraryBuilder episodeUnlibrary(String imdbId) {
return new EpisodeUnlibraryBuilder(this).imdbId(imdbId);
}
/**
* Remove episodes from your library collection.
*
* @param tvdbId Show TVDB ID.
* @return Builder instance.
*/
public EpisodeUnlibraryBuilder episodeUnlibrary(int tvdbId) {
return new EpisodeUnlibraryBuilder(this).tvdbId(tvdbId);
}
/**
* Remove episodes from your library collection.
*
* @param title Show title.
* @param year Show year.
* @return Builder instance.
*/
public EpisodeUnlibraryBuilder episodeUnlibrary(String title, int year) {
return new EpisodeUnlibraryBuilder(this).title(title).year(year);
}
/**
* Remove episodes watched outside of trakt from your library.
*
* @param imdbId Show IMDB ID.
* @return Builder instance.
*/
public EpisodeUnseenBuilder episodeUnseen(String imdbId) {
return new EpisodeUnseenBuilder(this).imdbId(imdbId);
}
/**
* Remove episodes watched outside of trakt from your library.
*
* @param tvdbId Show TVDB ID.
* @return Builder instance.
*/
public EpisodeUnseenBuilder episodeUnseen(int tvdbId) {
return new EpisodeUnseenBuilder(this).tvdbId(tvdbId);
}
/**
* Remove episodes watched outside of trakt from your library.
*
* @param title Show title.
* @param year Show year.
* @return Builder instance.
*/
public EpisodeUnseenBuilder episodeUnseen(String title, int year) {
return new EpisodeUnseenBuilder(this).title(title).year(year);
}
/**
* Remove one or more episodes for a specific show from your watchlist.
*
* @param imdbId Show IMDB ID.
* @return Builder instance.
*/
public EpisodeUnwatchlistBuilder episodeUnwatchlist(String imdbId) {
return new EpisodeUnwatchlistBuilder(this).imdbId(imdbId);
}
/**
* Remove one or more episodes for a specific show from your watchlist.
*
* @param tvdbId Show TVDB ID.
* @return Builder instance.
*/
public EpisodeUnwatchlistBuilder episodeUnwatchlist(int tvdbId) {
return new EpisodeUnwatchlistBuilder(this).tvdbId(tvdbId);
}
/**
* Remove one or more episodes for a specific show from your watchlist.
*
* @param title Show title.
* @param year Show year.
* @return Builder instance.
*/
public EpisodeUnwatchlistBuilder episodeUnwatchlist(String title, int year) {
return new EpisodeUnwatchlistBuilder(this).title(title).year(year);
}
/**
* Returns a array of all users watching an episode.
*
* @param title Either the slug (i.e. the-walking-dead) or TVDB ID. You can
* get a show's slug by browsing the website and looking at the URL when on
* a show summary page.
* @param season The season number. Use 0 if you want the specials.
* @param episode The episode number.
* @return Builder instance.
*/
public EpisodeWatchingNowBuilder episodeWatchingNow(String title, int season, int episode) {
return new EpisodeWatchingNowBuilder(this).title(title).season(season).episode(episode);
}
/**
* Add one or more episodes for a specific show to your watchlist.
*
* @param imdbId Show IMDB ID.
* @return Builder instance.
*/
public EpisodeWatchlistBuilder episodeWatchlist(String imdbId) {
return new EpisodeWatchlistBuilder(this).imdbId(imdbId);
}
/**
* Add one or more episodes for a specific show to your watchlist.
*
* @param tvdbId Show TVDB ID.
* @return Builder instance.
*/
public EpisodeWatchlistBuilder episodeWatchlist(int tvdbId) {
return new EpisodeWatchlistBuilder(this).tvdbId(tvdbId);
}
/**
* Add one or more episodes for a specific show to your watchlist.
*
* @param title Show title.
* @param year Show year.
* @return Builder instance.
*/
public EpisodeWatchlistBuilder episodeWatchlist(String title, int year) {
return new EpisodeWatchlistBuilder(this).title(title).year(year);
}
/**
* <p>Notify Trakt that a user has finished watching a show. This commits
* the show to the users profile. You should use show/watching prior to
* calling this method.</p>
*
* <p><em>Warning</em>: This method requires a developer API key.</p>
*
* @param imdbId IMDB ID for the show.
* @return Builder instance.
*/
public ScrobbleBuilder scrobble(String imdbId) {
return new ScrobbleBuilder(this).imdbId(imdbId);
}
/**
* <p>Notify Trakt that a user has finished watching a show. This commits
* the show to the users profile. You should use show/watching prior to
* calling this method.</p>
*
* <p><em>Warning</em>: This method requires a developer API key.</p>
*
* @param tvdbId TVDB ID for the show.
* @return Builder instance.
*/
public ScrobbleBuilder scrobble(int tvdbId) {
return new ScrobbleBuilder(this).tvdbId(tvdbId);
}
/**
* <p>Notify Trakt that a user has finished watching a show. This commits
* the show to the users profile. You should use show/watching prior to
* calling this method.</p>
*
* <p><em>Warning</em>: This method requires a developer API key.</p>
*
* @param title Show title.
* @param year Show year.
* @return Builder instance.
*/
public ScrobbleBuilder scrobble(String title, int year) {
return new ScrobbleBuilder(this).title(title).year(year);
}
/**
* Returns detailed episode info for a specific season of a show.
*
* @param query Either the slug (i.e. the-walking-dead) or TVDB ID. You can
* get a show's slug by browsing the website and looking at the URL when on
* a show summary page.
* @param season The season number. Use 0 if you want the specials.
* @return Builder instance.
*/
public SeasonBuilder season(String query, int season) {
return new SeasonBuilder(this, query, season);
}
/**
* Returns basic season info for a show.
*
* @param query Either the slug (i.e. the-walking-dead) or TVDB ID. You can
* get a show's slug by browsing the website and looking at the URL when on
* a show summary page.
* @return Builder instance.
*/
public SeasonsBuilder seasons(String query) {
return new SeasonsBuilder(this, query);
}
/**
* Returns information for a TV show including ratings, top watchers, and
* most watched episodes.
*
* @param title Either the slug (i.e. the-walking-dead) or TVDB ID. You can
* get a show's slug by browsing the website and looking at the URL when on
* a show summary page.
* @return Builder instance.
*/
public SummaryBuilder summary(String title) {
return (new SummaryBuilder(this)).title(title);
}
/**
* Returns all shows being watched right now.
*
* @return Builder instance.
*/
public TrendingBuilder trending() {
return new TrendingBuilder(this);
}
/**
* Remove an entire show (including all episodes) from your library collection.
*
* @param imdbId IMDB ID for the show.
* @return Builder instance.
*/
public UnlibraryBuilder unlibrary(String imdbId) {
return new UnlibraryBuilder(this).imdbId(imdbId);
}
/**
* Remove an entire show (including all episodes) from your library collection.
*
* @param tvdbId TVDB ID for the show.
* @return Builder instance.
*/
public UnlibraryBuilder unlibrary(int tvdbId) {
return new UnlibraryBuilder(this).tvdbId(tvdbId);
}
/**
* Remove an entire show (including all episodes) from your library collection.
*
* @param title Show title.
* @param year Show year.
* @return Builder instance.
*/
public UnlibraryBuilder unlibrary(String title, int year) {
return new UnlibraryBuilder(this).title(title).year(year);
}
/**
* Remove one or more shows from your watchlist.
*
* @return Builder instance.
*/
public UnwatchlistBuilder unwatchlist() {
return new UnwatchlistBuilder(this);
}
/**
* <p>Notify Trakt that a user has started watching a show.</p>
*
* <p><em>Warning</em>: This method requires a developer API key.</p>
*
* @param imdbId IMDB ID for the show.
* @return Builder instance.
*/
public WatchingBuilder watching(String imdbId) {
return new WatchingBuilder(this).imdbId(imdbId);
}
/**
* <p>Notify Trakt that a user has started watching a show.</p>
*
* <p><em>Warning</em>: This method requires a developer API key.</p>
*
* @param tvdbId TVDB ID for the show.
* @return Builder instance.
*/
public WatchingBuilder watching(int tvdbId) {
return new WatchingBuilder(this).tvdbId(tvdbId);
}
/**
* <p>Notify Trakt that a user has started watching a show.</p>
*
* <p><em>Warning</em>: This method requires a developer API key.</p>
*
* @param title Show title.
* @param year Show year.
* @return Builder instance.
*/
public WatchingBuilder watching(String title, int year) {
return new WatchingBuilder(this).title(title).year(year);
}
/**
* Returns a array of all users watching a show.
*
* @param query Either the slug (i.e. the-walking-dead) or TVDB ID. You can
* get a show's slug by browsing the website and looking at the URL when on
* a show summary page.
* @return Builder instance.
*/
public WatchingNowBuilder watchingNow(String query) {
return new WatchingNowBuilder(this).query(query);
}
/**
* Add one or more shows to your watchlist.
*
* @return Builder instance.
*/
public WatchlistBuilder watchlist() {
return new WatchlistBuilder(this);
}
/**
* Returns all shouts for a show. Most recent shouts returned first.
*
* @param title Show title.
* @return Builder instance.
*/
public ShoutsBuilder shouts(String title) {
return new ShoutsBuilder(this).title(title);
}
/**
* Returns all shouts for a show. Most recent shouts returned first.
*
* @param tvdbId TVDB ID.
* @return Builder instance.
*/
public ShoutsBuilder shouts(int tvdbId) {
return new ShoutsBuilder(this).title(tvdbId);
}
/**
* Returns all shouts for an episode. Most recent shouts returned first.
*
* @param title Show title.
* @param season The season number. Use 0 if you want the specials.
* @param episode The episode number.
* @return Builder instance.
*/
public EpisodeShoutsBuilder episodeShouts(String title, int season, int episode) {
return new EpisodeShoutsBuilder(this).title(title).season(season).episode(episode);
}
/**
* Returns all shouts for an episode. Most recent shouts returned first.
*
* @param tvdbId TMDB ID.
* @param season The season number. Use 0 if you want the specials.
* @param episode The episode number.
* @return Builder instance.
*/
public EpisodeShoutsBuilder episodeShouts(int tvdbId, int season, int episode) {
return new EpisodeShoutsBuilder(this).title(tvdbId).season(season).episode(episode);
}
/**
* Get the top 10 related shows.
*
* @param slug Show title slug.
* @return Builder instance.
*/
public RelatedBuilder related(String slug) {
return new RelatedBuilder(this).title(slug);
}
/**
* Get the top 10 related shows.
*
* @param tvdbId TVDB ID.
* @return Builder instance.
*/
public RelatedBuilder related(int tvdbId) {
return new RelatedBuilder(this).title(tvdbId);
}
/**
* <p>Check into a show on trakt. Think of this method as in between a seen
* and a scrobble. After checking in, the trakt will automatically display
* it as watching then switch over to watched status once the duration has
* elapsed.</p>
*
* <p><em>Warning</em>: This method requires a developer API key.</p>
*
* @param tvdbId TVDB ID for the show.
* @return Builder instance.
*/
public CheckinBuilder checkin(int tvdbId) {
return new CheckinBuilder(this).tvdbId(tvdbId);
}
/**
* <p>Check into a show on trakt. Think of this method as in between a seen
* and a scrobble. After checking in, the trakt will automatically display
* it as watching then switch over to watched status once the duration has
* elapsed.</p>
*
* <p><em>Warning</em>: This method requires a developer API key.</p>
*
* @param title Show title.
* @param year Show year.
* @return Builder instance.
*/
public CheckinBuilder checkin(String title, int year) {
return new CheckinBuilder(this).title(title).year(year);
}
/**
* <p>Notify trakt that a user wants to cancel their current check in.</p>
*
* <p><em>Warning</em>: This method requires a developer API key.</p>
*
* @return Builder instance.
*/
public CancelCheckinBuilder cancelCheckin() {
return new CancelCheckinBuilder(this);
}
public static final class CancelWatchingBuilder extends TraktApiBuilder<Response> {
private static final String URI = "/show/cancelwatching/" + FIELD_API_KEY;
private CancelWatchingBuilder(ShowService service) {
super(service, new TypeToken<Response>() {}, URI, HttpMethod.Post);
}
}
public static final class EpisodeLibraryBuilder extends TraktApiBuilder<Void> {
private static final String POST_IMDB_ID = "imdb_id";
private static final String POST_TVDB_ID = "tvdb_id";
private static final String POST_TITLE = "title";
private static final String POST_YEAR = "year";
private static final String POST_EPISODES = "episodes";
private static final String POST_SEASON = "season";
private static final String POST_EPISODE = "episode";
private static final String URI = "/show/episode/library/" + FIELD_API_KEY;
private JsonArray episodeList;
private EpisodeLibraryBuilder(ShowService service) {
super(service, new TypeToken<Void>() {}, URI, HttpMethod.Post);
this.episodeList = new JsonArray();
}
/**
* Show IMDB ID.
*
* @param imdbId Value.
* @return Builder instance.
*/
public EpisodeLibraryBuilder imdbId(String imdbId) {
this.postParameter(POST_IMDB_ID, imdbId);
return this;
}
/**
* Show TVDB ID.
*
* @param tvdbId Value.
* @return Builder instance.
*/
public EpisodeLibraryBuilder tvdbId(int tvdbId) {
this.postParameter(POST_TVDB_ID, tvdbId);
return this;
}
/**
* Show title.
*
* @param title Value.
* @return Builder instance.
*/
public EpisodeLibraryBuilder title(String title) {
this.postParameter(POST_TITLE, title);
return this;
}
/**
* Show year.
*
* @param year Value.
* @return Builder instance.
*/
public EpisodeLibraryBuilder year(int year) {
this.postParameter(POST_YEAR, year);
return this;
}
/**
* Add an episode to the list.
*
* @param season Episode's season number.
* @param episode Episode's number.
* @return Builder instance.
*/
public EpisodeLibraryBuilder episode(int season, int episode) {
JsonObject ep = new JsonObject();
ep.addProperty(POST_SEASON, season);
ep.addProperty(POST_EPISODE, episode);
this.episodeList.add(ep);
return this;
}
@Override
protected void preFireCallback() {
//Add the assembled movie list to the JSON post body.
this.postParameter(POST_EPISODES, this.episodeList);
}
}
public static final class EpisodeSeenBuilder extends TraktApiBuilder<Void> {
private static final String POST_IMDB_ID = "imdb_id";
private static final String POST_TVDB_ID = "tvdb_id";
private static final String POST_TITLE = "title";
private static final String POST_YEAR = "year";
private static final String POST_EPISODES = "episodes";
private static final String POST_SEASON = "season";
private static final String POST_EPISODE = "episode";
private static final String URI = "/show/episode/seen/" + FIELD_API_KEY;
private JsonArray episodeList;
private EpisodeSeenBuilder(ShowService service) {
super(service, new TypeToken<Void>() {}, URI, HttpMethod.Post);
this.episodeList = new JsonArray();
}
/**
* Show IMDB ID.
*
* @param imdbId Value.
* @return Builder instance.
*/
public EpisodeSeenBuilder imdbId(String imdbId) {
this.postParameter(POST_IMDB_ID, imdbId);
return this;
}
/**
* Show TVDB ID.
*
* @param tvdbId Value.
* @return Builder instance.
*/
public EpisodeSeenBuilder tvdbId(int tvdbId) {
this.postParameter(POST_TVDB_ID, tvdbId);
return this;
}
/**
* Show title.
*
* @param title Value.
* @return Builder instance.
*/
public EpisodeSeenBuilder title(String title) {
this.postParameter(POST_TITLE, title);
return this;
}
/**
* Show year.
*
* @param year Value.
* @return Builder instance.
*/
public EpisodeSeenBuilder year(int year) {
this.postParameter(POST_YEAR, year);
return this;
}
/**
* Add an episode to the list.
*
* @param season Episode's season number.
* @param episode Episode's number.
* @return Builder instance.
*/
public EpisodeSeenBuilder episode(int season, int episode) {
JsonObject ep = new JsonObject();
ep.addProperty(POST_SEASON, season);
ep.addProperty(POST_EPISODE, episode);
this.episodeList.add(ep);
return this;
}
@Override
protected void preFireCallback() {
//Add the assembled movie list to the JSON post body.
this.postParameter(POST_EPISODES, this.episodeList);
}
}
public static final class EpisodeSummaryBuilder extends TraktApiBuilder<TvEntity> {
private static final String URI = "/show/episode/summary.json/" + FIELD_API_KEY + "/" + FIELD_TITLE + "/" + FIELD_SEASON + "/" + FIELD_EPISODE;
private EpisodeSummaryBuilder(ShowService service) {
super(service, new TypeToken<TvEntity>() {}, URI);
}
/**
* Show title.
*
* @param title Value.
* @return Builder instance.
*/
public EpisodeSummaryBuilder title(String title) {
this.field(FIELD_TITLE, title);
return this;
}
/**
* Show TVDB ID.
*
* @param tvdbId Value.
* @return Builder instance.
*/
public EpisodeSummaryBuilder tvdbId(int tvdbId) {
this.field(FIELD_TITLE, tvdbId);
return this;
}
/**
* Show season.
*
* @param season Value.
* @return Builder instance.
*/
public EpisodeSummaryBuilder season(int season) {
this.field(FIELD_SEASON, season);
return this;
}
/**
* Show episode.
*
* @param episode Value.
* @return Builder instance.
*/
public EpisodeSummaryBuilder episode(int episode) {
this.field(FIELD_EPISODE, episode);
return this;
}
}
public static final class EpisodeUnlibraryBuilder extends TraktApiBuilder<Void> {
private static final String POST_IMDB_ID = "imdb_id";
private static final String POST_TVDB_ID = "tvdb_id";
private static final String POST_TITLE = "title";
private static final String POST_YEAR = "year";
private static final String POST_EPISODES = "episodes";
private static final String POST_SEASON = "season";
private static final String POST_EPISODE = "episode";
private static final String URI = "/show/episode/unlibrary/" + FIELD_API_KEY;
private JsonArray episodeList;
private EpisodeUnlibraryBuilder(ShowService service) {
super(service, new TypeToken<Void>() {}, URI, HttpMethod.Post);
this.episodeList = new JsonArray();
}
/**
* Show IMDB ID.
*
* @param imdbId Value.
* @return Builder instance.
*/
public EpisodeUnlibraryBuilder imdbId(String imdbId) {
this.postParameter(POST_IMDB_ID, imdbId);
return this;
}
/**
* Show TVDB ID.
*
* @param tvdbId Value.
* @return Builder instance.
*/
public EpisodeUnlibraryBuilder tvdbId(int tvdbId) {
this.postParameter(POST_TVDB_ID, tvdbId);
return this;
}
/**
* Show title.
*
* @param title Value.
* @return Builder instance.
*/
public EpisodeUnlibraryBuilder title(String title) {
this.postParameter(POST_TITLE, title);
return this;
}
/**
* Show year.
*
* @param year Value.
* @return Builder instance.
*/
public EpisodeUnlibraryBuilder year(int year) {
this.postParameter(POST_YEAR, year);
return this;
}
/**
* Add an episode to the list.
*
* @param season Episode's season number.
* @param episode Episode's number.
* @return Builder instance.
*/
public EpisodeUnlibraryBuilder episode(int season, int episode) {
JsonObject ep = new JsonObject();
ep.addProperty(POST_SEASON, season);
ep.addProperty(POST_EPISODE, episode);
this.episodeList.add(ep);
return this;
}
@Override
protected void preFireCallback() {
//Add the assembled movie list to the JSON post body.
this.postParameter(POST_EPISODES, this.episodeList);
}
}
public static final class EpisodeUnseenBuilder extends TraktApiBuilder<Void> {
private static final String POST_IMDB_ID = "imdb_id";
private static final String POST_TVDB_ID = "tvdb_id";
private static final String POST_TITLE = "title";
private static final String POST_YEAR = "year";
private static final String POST_EPISODES = "episodes";
private static final String POST_SEASON = "season";
private static final String POST_EPISODE = "episode";
private static final String URI = "/show/episode/unseen/" + FIELD_API_KEY;
private JsonArray episodeList;
private EpisodeUnseenBuilder(ShowService service) {
super(service, new TypeToken<Void>() {}, URI, HttpMethod.Post);
this.episodeList = new JsonArray();
}
/**
* Show IMDB ID.
*
* @param imdbId Value.
* @return Builder instance.
*/
public EpisodeUnseenBuilder imdbId(String imdbId) {
this.postParameter(POST_IMDB_ID, imdbId);
return this;
}
/**
* Show TVDB ID.
*
* @param tvdbId Value.
* @return Builder instance.
*/
public EpisodeUnseenBuilder tvdbId(int tvdbId) {
this.postParameter(POST_TVDB_ID, tvdbId);
return this;
}
/**
* Show title.
*
* @param title Value.
* @return Builder instance.
*/
public EpisodeUnseenBuilder title(String title) {
this.postParameter(POST_TITLE, title);
return this;
}
/**
* Show year.
*
* @param year Value.
* @return Builder instance.
*/
public EpisodeUnseenBuilder year(int year) {
this.postParameter(POST_YEAR, year);
return this;
}
/**
* Add an episode to the list.
*
* @param season Episode's season number.
* @param episode Episode's number.
* @return Builder instance.
*/
public EpisodeUnseenBuilder episode(int season, int episode) {
JsonObject ep = new JsonObject();
ep.addProperty(POST_SEASON, season);
ep.addProperty(POST_EPISODE, episode);
this.episodeList.add(ep);
return this;
}
@Override
protected void preFireCallback() {
//Add the assembled movie list to the JSON post body.
this.postParameter(POST_EPISODES, this.episodeList);
}
}
public static final class EpisodeUnwatchlistBuilder extends TraktApiBuilder<Void> {
private static final String POST_IMDB_ID = "imdb_id";
private static final String POST_TVDB_ID = "tvdb_id";
private static final String POST_TITLE = "title";
private static final String POST_YEAR = "year";
private static final String POST_EPISODES = "episodes";
private static final String POST_SEASON = "season";
private static final String POST_EPISODE = "episode";
private static final String URI = "/show/episode/unwatchlist/" + FIELD_API_KEY;
private JsonArray episodeList;
private EpisodeUnwatchlistBuilder(ShowService service) {
super(service, new TypeToken<Void>() {}, URI, HttpMethod.Post);
this.episodeList = new JsonArray();
}
/**
* Show IMDB ID.
*
* @param imdbId Value.
* @return Builder instance.
*/
public EpisodeUnwatchlistBuilder imdbId(String imdbId) {
this.postParameter(POST_IMDB_ID, imdbId);
return this;
}
/**
* Show TVDB ID.
*
* @param tvdbId Value.
* @return Builder instance.
*/
public EpisodeUnwatchlistBuilder tvdbId(int tvdbId) {
this.postParameter(POST_TVDB_ID, tvdbId);
return this;
}
/**
* Show title.
*
* @param title Value.
* @return Builder instance.
*/
public EpisodeUnwatchlistBuilder title(String title) {
this.postParameter(POST_TITLE, title);
return this;
}
/**
* Show year.
*
* @param year Value.
* @return Builder instance.
*/
public EpisodeUnwatchlistBuilder year(int year) {
this.postParameter(POST_YEAR, year);
return this;
}
/**
* Add an episode to the list.
*
* @param season Episode's season number.
* @param episode Episode's number.
* @return Builder instance.
*/
public EpisodeUnwatchlistBuilder episode(int season, int episode) {
JsonObject ep = new JsonObject();
ep.addProperty(POST_SEASON, season);
ep.addProperty(POST_EPISODE, episode);
this.episodeList.add(ep);
return this;
}
@Override
protected void preFireCallback() {
//Add the assembled movie list to the JSON post body.
this.postParameter(POST_EPISODES, this.episodeList);
}
}
public static final class EpisodeWatchingNowBuilder extends TraktApiBuilder<List<UserProfile>> {
private static final String URI = "/show/episode/watchingnow.json/" + FIELD_API_KEY + "/" + FIELD_TITLE + "/" + FIELD_SEASON + "/" + FIELD_EPISODE;
private EpisodeWatchingNowBuilder(ShowService service) {
super(service, new TypeToken<List<UserProfile>>() {}, URI);
}
/**
* Either the slug (i.e. the-walking-dead) or TVDB ID. You can get a
* show's slug by browsing the website and looking at the URL when on a
* show summary page.
*
* @param title Value.
* @return Builder instance.
*/
public EpisodeWatchingNowBuilder title(String title) {
this.field(FIELD_TITLE, title);
return this;
}
/**
* The season number. Use 0 if you want the specials.
*
* @param season Value.
* @return Builder instance.
*/
public EpisodeWatchingNowBuilder season(int season) {
this.field(FIELD_SEASON, season);
return this;
}
/**
* The episode number.
*
* @param episode Value
* @return Builder instance.
*/
public EpisodeWatchingNowBuilder episode(int episode) {
this.field(FIELD_EPISODE, episode);
return this;
}
}
public static final class EpisodeWatchlistBuilder extends TraktApiBuilder<Void> {
private static final String POST_IMDB_ID = "imdb_id";
private static final String POST_TVDB_ID = "tvdb_id";
private static final String POST_TITLE = "title";
private static final String POST_YEAR = "year";
private static final String POST_EPISODES = "episodes";
private static final String POST_SEASON = "season";
private static final String POST_EPISODE = "episode";
private static final String URI = "/show/episode/watchlist/" + FIELD_API_KEY;
private JsonArray episodeList;
private EpisodeWatchlistBuilder(ShowService service) {
super(service, new TypeToken<Void>() {}, URI, HttpMethod.Post);
this.episodeList = new JsonArray();
}
/**
* Show IMDB ID.
*
* @param imdbId Value.
* @return Builder instance.
*/
public EpisodeWatchlistBuilder imdbId(String imdbId) {
this.postParameter(POST_IMDB_ID, imdbId);
return this;
}
/**
* Show TVDB ID.
*
* @param tvdbId Value.
* @return Builder instance.
*/
public EpisodeWatchlistBuilder tvdbId(int tvdbId) {
this.postParameter(POST_TVDB_ID, tvdbId);
return this;
}
/**
* Show title.
*
* @param title Value.
* @return Builder instance.
*/
public EpisodeWatchlistBuilder title(String title) {
this.postParameter(POST_TITLE, title);
return this;
}
/**
* Show year.
*
* @param year Value.
* @return Builder instance.
*/
public EpisodeWatchlistBuilder year(int year) {
this.postParameter(POST_YEAR, year);
return this;
}
/**
* Add an episode to the list.
*
* @param season Episode's season number.
* @param episode Episode's number.
* @return Builder instance.
*/
public EpisodeWatchlistBuilder episode(int season, int episode) {
JsonObject ep = new JsonObject();
ep.addProperty(POST_SEASON, season);
ep.addProperty(POST_EPISODE, episode);
this.episodeList.add(ep);
return this;
}
@Override
protected void preFireCallback() {
//Add the assembled movie list to the JSON post body.
this.postParameter(POST_EPISODES, this.episodeList);
}
}
public static final class ScrobbleBuilder extends TraktApiBuilder<Response> {
private static final String POST_IMDB_ID = "imdb_id";
private static final String POST_TVDB_ID = "tvdb_id";
private static final String POST_TITLE = "title";
private static final String POST_YEAR = "year";
private static final String POST_SEASON = "season";
private static final String POST_EPISODE = "episode";
private static final String POST_DURATION = "duration";
private static final String POST_PROGRESS = "progress";
private static final String URI = "/show/scrobble/" + FIELD_API_KEY;
private ScrobbleBuilder(ShowService service) {
super(service, new TypeToken<Response>() {}, URI, HttpMethod.Post);
this.includeScrobbleDebugStrings();
}
/**
* IMDB ID for the show.
*
* @param imdbId Value.
* @return Builder instance.
*/
public ScrobbleBuilder imdbId(String imdbId) {
this.postParameter(POST_IMDB_ID, imdbId);
return this;
}
/**
* TVDB ID for the show.
*
* @param tmdbId Value.
* @return Builder instance.
*/
public ScrobbleBuilder tvdbId(int tmdbId) {
this.postParameter(POST_TVDB_ID, tmdbId);
return this;
}
/**
* Movie title.
*
* @param title Value.
* @return Builder instance.
*/
public ScrobbleBuilder title(String title) {
this.postParameter(POST_TITLE, title);
return this;
}
/**
* Movie year.
*
* @param year Value.
* @return Builder instance.
*/
public ScrobbleBuilder year(int year) {
this.postParameter(POST_YEAR, year);
return this;
}
/**
* Show season. Send 0 if watching a special.
*
* @param season Value.
* @return Builder instance.
*/
public ScrobbleBuilder season(int season) {
this.postParameter(POST_SEASON, season);
return this;
}
/**
* Show episode.
*
* @param episode Value.
* @return Builder instance.
*/
public ScrobbleBuilder episode(int episode) {
this.postParameter(POST_EPISODE, episode);
return this;
}
/**
* Duration (in minutes).
*
* @param duration Value.
* @return Builder instance.
*/
public ScrobbleBuilder duration(int duration) {
this.postParameter(POST_DURATION, duration);
return this;
}
/**
* Percent progress (0-100). It is recommended to call the watching API
* every 15 minutes, then call the scrobble API near the end of the
* movie to lock it in.
*
* @param progress Value.
* @return Builder instance.
*/
public ScrobbleBuilder progress(int progress) {
this.postParameter(POST_PROGRESS, progress);
return this;
}
@Override
protected void performValidation() {
assert this.hasPostParameter(POST_TVDB_ID)
|| (this.hasPostParameter(POST_TITLE) && this.hasPostParameter(POST_YEAR))
: "Either IMDB ID, TMDB ID, or both title and year is required.";
assert this.hasPostParameter(POST_SEASON) : "Season is required.";
assert this.hasPostParameter(POST_EPISODE) : "Episode is required.";
assert this.hasPostParameter(POST_DURATION) : "Duration is required.";
assert this.hasPostParameter(POST_PROGRESS) : "Progress is required.";
}
}
public static final class SeasonBuilder extends TraktApiBuilder<List<TvShowEpisode>> {
private static final String URI = "/show/season.json/" + FIELD_API_KEY + "/" + FIELD_QUERY + "/" + FIELD_SEASON;
private SeasonBuilder(ShowService service, String query, int season) {
super(service, new TypeToken<List<TvShowEpisode>>() {}, URI);
this.field(FIELD_QUERY, query);
this.field(FIELD_SEASON, season);
}
}
public static final class SeasonsBuilder extends TraktApiBuilder<List<TvShowSeason>> {
private static final String URI = "/show/seasons.json/" + FIELD_API_KEY + "/" + FIELD_QUERY;
private SeasonsBuilder(ShowService service, String query) {
super(service, new TypeToken<List<TvShowSeason>>() {}, URI);
this.field(FIELD_QUERY, query);
}
}
public static final class SummaryBuilder extends TraktApiBuilder<TvShow> {
private static final String EXTENDED = "extended";
private static final String URI = "/show/summary.json/" + FIELD_API_KEY + "/" + FIELD_TITLE + "/" + FIELD_EXTENDED;
private SummaryBuilder(ShowService service) {
super(service, new TypeToken<TvShow>() {}, URI);
}
/**
* Either the slug (i.e. the-walking-dead) or TVDB ID. You can get a
* show's slug by browsing the website and looking at the URL when on a
* show summary page.
*
* @param title Value.
* @return Builder instance.
*/
public SummaryBuilder title(String title) {
this.field(FIELD_TITLE, title);
return this;
}
/**
* Returns complete season and episode info. Only send this if you
* really need the full dump. Use the show/seasons and show/season
* methods if you only need some of the season or episode info.
*
* @return Builder instance.
*/
public SummaryBuilder extended() {
this.field(FIELD_EXTENDED, EXTENDED);
return this;
}
}
public static final class TrendingBuilder extends TraktApiBuilder<List<TvShow>> {
private static final String URI = "/shows/trending.json/" + FIELD_API_KEY;
private TrendingBuilder(ShowService service) {
super(service, new TypeToken<List<TvShow>>() {}, URI);
}
}
public static final class UnlibraryBuilder extends TraktApiBuilder<Void> {
private static final String POST_IMDB_ID = "imdb_id";
private static final String POST_TVDB_ID = "tvdb_id";
private static final String POST_TITLE = "title";
private static final String POST_YEAR = "year";
private static final String URI = "/show/unlibrary/" + FIELD_API_KEY;
private UnlibraryBuilder(ShowService service) {
super(service, new TypeToken<Void>() {}, URI, HttpMethod.Post);
}
/**
* IMDB ID for the show.
*
* @param imdbId Value.
* @return Builder instance.
*/
public UnlibraryBuilder imdbId(String imdbId) {
this.postParameter(POST_IMDB_ID, imdbId);
return this;
}
/**
* TVDB ID for the show.
*
* @param tmdbId Value.
* @return Builder instance.
*/
public UnlibraryBuilder tvdbId(int tmdbId) {
this.postParameter(POST_TVDB_ID, tmdbId);
return this;
}
/**
* Movie title.
*
* @param title Value.
* @return Builder instance.
*/
public UnlibraryBuilder title(String title) {
this.postParameter(POST_TITLE, title);
return this;
}
/**
* Movie year.
*
* @param year Value.
* @return Builder instance.
*/
public UnlibraryBuilder year(int year) {
this.postParameter(POST_YEAR, year);
return this;
}
}
public static final class UnwatchlistBuilder extends TraktApiBuilder<Void> {
private static final String POST_IMDB_ID = "imdb_id";
private static final String POST_TVDB_ID = "tvdb_id";
private static final String POST_TITLE = "title";
private static final String POST_YEAR = "year";
private static final String POST_SHOWS = "shows";
private static final String URI = "/show/unwatchlist/" + FIELD_API_KEY;
private JsonArray showList;
private UnwatchlistBuilder(ShowService service) {
super(service, new TypeToken<Void>() {}, URI, HttpMethod.Post);
this.showList = new JsonArray();
}
/**
* Add a show to be removed.
*
* @param imdbId IMDB ID for the show.
* @return Builder instance.
*/
public UnwatchlistBuilder imdbId(String imdbId) {
JsonObject show = new JsonObject();
show.addProperty(POST_IMDB_ID, imdbId);
this.showList.add(show);
return this;
}
/**
* Add a show to be removed.
*
* @param tvdbId TVDB ID for the show.
* @return Builder instance.
*/
public UnwatchlistBuilder tvdbId(int tvdbId) {
JsonObject show = new JsonObject();
show.addProperty(POST_TVDB_ID, tvdbId);
this.showList.add(show);
return this;
}
/**
* Add a show to be removed.
*
* @param title Title for the show.
* @param year Year of the show.
* @return Builder instance.
*/
public UnwatchlistBuilder title(String title, int year) {
JsonObject show = new JsonObject();
show.addProperty(POST_TITLE, title);
show.addProperty(POST_YEAR, year);
this.showList.add(show);
return this;
}
@Override
protected void preFireCallback() {
this.postParameter(POST_SHOWS, this.showList);
}
}
public static final class WatchingBuilder extends TraktApiBuilder<Response> {
private static final String POST_IMDB_ID = "imdb_id";
private static final String POST_TVDB_ID = "tvdb_id";
private static final String POST_TITLE = "title";
private static final String POST_YEAR = "year";
private static final String POST_SEASON = "season";
private static final String POST_EPISODE = "episode";
private static final String POST_DURATION = "duration";
private static final String POST_PROGRESS = "progress";
private static final String URI = "/show/watching/" + FIELD_API_KEY;
private WatchingBuilder(ShowService service) {
super(service, new TypeToken<Response>() {}, URI, HttpMethod.Post);
this.includeScrobbleDebugStrings();
}
/**
* IMDB ID for the show.
*
* @param imdbId Value.
* @return Builder instance.
*/
public WatchingBuilder imdbId(String imdbId) {
this.postParameter(POST_IMDB_ID, imdbId);
return this;
}
/**
* TVDB ID for the show.
*
* @param tmdbId Value.
* @return Builder instance.
*/
public WatchingBuilder tvdbId(int tmdbId) {
this.postParameter(POST_TVDB_ID, tmdbId);
return this;
}
/**
* Movie title.
*
* @param title Value.
* @return Builder instance.
*/
public WatchingBuilder title(String title) {
this.postParameter(POST_TITLE, title);
return this;
}
/**
* Movie year.
*
* @param year Value.
* @return Builder instance.
*/
public WatchingBuilder year(int year) {
this.postParameter(POST_YEAR, year);
return this;
}
/**
* Show season. Send 0 if watching a special.
*
* @param season Value.
* @return Builder instance.
*/
public WatchingBuilder season(int season) {
this.postParameter(POST_SEASON, season);
return this;
}
/**
* Show episode.
*
* @param episode Value.
* @return Builder instance.
*/
public WatchingBuilder episode(int episode) {
this.postParameter(POST_EPISODE, episode);
return this;
}
/**
* Duration (in minutes).
*
* @param duration Value.
* @return Builder instance.
*/
public WatchingBuilder duration(int duration) {
this.postParameter(POST_DURATION, duration);
return this;
}
/**
* Percent progress (0-100). It is recommended to call the watching API
* every 15 minutes, then call the scrobble API near the end of the
* movie to lock it in.
*
* @param progress Value.
* @return Builder instance.
*/
public WatchingBuilder progress(int progress) {
this.postParameter(POST_PROGRESS, progress);
return this;
}
@Override
protected void performValidation() {
assert this.hasPostParameter(POST_TVDB_ID)
|| (this.hasPostParameter(POST_TITLE) && this.hasPostParameter(POST_YEAR))
: "Either IMDB ID, TMDB ID, or both title and year is required.";
assert this.hasPostParameter(POST_SEASON) : "Season is required.";
assert this.hasPostParameter(POST_EPISODE) : "Episode is required.";
assert this.hasPostParameter(POST_DURATION) : "Duration is required.";
assert this.hasPostParameter(POST_PROGRESS) : "Progress is required.";
}
}
public static final class WatchingNowBuilder extends TraktApiBuilder<List<UserProfile>> {
private static final String URI = "/show/watchingnow.json/" + FIELD_API_KEY + "/" + FIELD_QUERY;
private WatchingNowBuilder(ShowService service) {
super(service, new TypeToken<List<UserProfile>>() {}, URI);
}
/**
* Either the slug (i.e. the-walking-dead) or TVDB ID. You can get a
* show's slug by browsing the website and looking at the URL when on
* a show summary page.
*
* @param query Value.
* @return Builder instance.
*/
public WatchingNowBuilder query(String query) {
this.field(FIELD_QUERY, query);
return this;
}
}
public static final class WatchlistBuilder extends TraktApiBuilder<Void> {
private static final String POST_IMDB_ID = "imdb_id";
private static final String POST_TVDB_ID = "tvdb_id";
private static final String POST_TITLE = "title";
private static final String POST_YEAR = "year";
private static final String POST_SHOWS = "shows";
private static final String URI = "/show/watchlist/" + FIELD_API_KEY;
private JsonArray showList;
private WatchlistBuilder(ShowService service) {
super(service, new TypeToken<Void>() {}, URI, HttpMethod.Post);
this.showList = new JsonArray();
}
/**
* Add a show to be added.
*
* @param imdbId IMDB ID for the show.
* @return Builder instance.
*/
public WatchlistBuilder imdbId(String imdbId) {
JsonObject show = new JsonObject();
show.addProperty(POST_IMDB_ID, imdbId);
this.showList.add(show);
return this;
}
/**
* Add a show to be added.
*
* @param tvdbId TVDB ID for the show.
* @return Builder instance.
*/
public WatchlistBuilder tvdbId(int tvdbId) {
JsonObject show = new JsonObject();
show.addProperty(POST_TVDB_ID, tvdbId);
this.showList.add(show);
return this;
}
/**
* Add a show to be added.
*
* @param title Title for the show.
* @param year Year of the show.
* @return Builder instance.
*/
public WatchlistBuilder title(String title, int year) {
JsonObject show = new JsonObject();
show.addProperty(POST_TITLE, title);
show.addProperty(POST_YEAR, year);
this.showList.add(show);
return this;
}
@Override
protected void preFireCallback() {
this.postParameter(POST_SHOWS, this.showList);
}
}
public static final class ShoutsBuilder extends TraktApiBuilder<List<Shout>> {
private static final String URI = "/show/shouts.json/" + FIELD_API_KEY + "/" + FIELD_TITLE;
private ShoutsBuilder(ShowService service) {
super(service, new TypeToken<List<Shout>>() {}, URI);
}
/**
* Set show title.
*
* @param title Value.
* @return Builder instance.
*/
public ShoutsBuilder title(String title) {
this.field(FIELD_TITLE, title);
return this;
}
/**
* Set show TVDB ID
*
* @param tvdbId Value.
* @return Builder instance.
*/
public ShoutsBuilder title(int tvdbId) {
this.field(FIELD_TITLE, tvdbId);
return this;
}
}
public static final class EpisodeShoutsBuilder extends TraktApiBuilder<List<Shout>> {
private static final String URI = "/show/episode/shouts.json/" + FIELD_API_KEY + "/" + FIELD_TITLE + "/" + FIELD_SEASON + "/" + FIELD_EPISODE;
private EpisodeShoutsBuilder(ShowService service) {
super(service, new TypeToken<List<Shout>>() {}, URI);
}
/**
* Set show title or IMDB ID.
*
* @param titleOrImdbId Value.
* @return Builder instance.
*/
public EpisodeShoutsBuilder title(String titleOrImdbId) {
this.field(FIELD_TITLE, titleOrImdbId);
return this;
}
/**
* Set show TMDB ID.
*
* @param tmdbId Value.
* @return Builder instance.
*/
public EpisodeShoutsBuilder title(int tmdbId) {
this.field(FIELD_TITLE, tmdbId);
return this;
}
/**
* Set episode season.
*
* @param season Value.
* @return Builder instance.
*/
public EpisodeShoutsBuilder season(int season) {
this.field(FIELD_SEASON, season);
return this;
}
/**
* Set episode number.
*
* @param episode Value.
* @return Builder instance.
*/
public EpisodeShoutsBuilder episode(int episode) {
this.field(FIELD_EPISODE, episode);
return this;
}
}
public static final class RelatedBuilder extends TraktApiBuilder<List<TvShow>> {
private static final String EXTENDED = "extended";
private static final String HIDE_WATCHED = "hidewatched";
private static final String URI = "/show/related.json/" + FIELD_API_KEY + "/" + FIELD_TITLE + "/" + FIELD_EXTENDED + "/" + FIELD_HIDE_WATCHED;
private RelatedBuilder(ShowService service) {
super(service, new TypeToken<List<TvShow>>() {}, URI);
}
/**
* Show title.
*
* @param slug Show title slug.
* @return Builder instance.
*/
public RelatedBuilder title(String slug) {
this.field(FIELD_TITLE, slug);
return this;
}
/**
* Show ID.
*
* @param tvdbId TVDB ID.
* @return Builder instance.
*/
public RelatedBuilder title(int tvdbId) {
this.field(FIELD_TITLE, tvdbId);
return this;
}
/**
* Returns complete season and episode info. Only send this if you
* really need the full dump. Use the show/seasons and show/season
* methods if you only need some of the season or episode info.
*
* @return Builder instance.
*/
public RelatedBuilder extended() {
this.field(FIELD_EXTENDED, EXTENDED);
return this;
}
/**
* If this parameter is set and valid auth is sent, shows with at least one play will be filtered out.
*
* @param hideWatched Value.
* @return Builder instance.
*/
public RelatedBuilder hideWatched(boolean hideWatched) {
if (hideWatched) {
this.field(FIELD_HIDE_WATCHED, HIDE_WATCHED);
}
return this;
}
}
public static final class CheckinBuilder extends TraktApiBuilder<Response> {
private static final String POST_TVDB_ID = "tvdb_id";
private static final String POST_TITLE = "title";
private static final String POST_YEAR = "year";
private static final String POST_SEASON = "season";
private static final String POST_EPISODE = "episode";
private static final String POST_DURATION = "duration";
private static final String POST_VENUE_ID = "venue_id";
private static final String POST_VENUE_NAME = "venue_name";
private static final String POST_MESSAGE = "message";
private static final String URI = "/show/checkin/" + FIELD_API_KEY;
private CheckinBuilder(ShowService service) {
super(service, new TypeToken<Response>() {}, URI, HttpMethod.Post);
this.includeCheckinDebugStrings();
}
/** TVDB ID for the show. */
public CheckinBuilder tvdbId(int tvdbId) {
this.postParameter(POST_TVDB_ID, tvdbId);
return this;
}
/** Show title. */
public CheckinBuilder title(String title) {
this.postParameter(POST_TITLE, title);
return this;
}
/** Show year. */
public CheckinBuilder year(int year) {
this.postParameter(POST_YEAR, year);
return this;
}
/** Show season. Send '0' if watching a special. */
public CheckinBuilder season(int season) {
this.postParameter(POST_SEASON, season);
return this;
}
/** Show episode. */
public CheckinBuilder episode(int episode) {
this.postParameter(POST_EPISODE, episode);
return this;
}
/** Duration in minutes. */
public CheckinBuilder duration(int duration) {
this.postParameter(POST_DURATION, duration);
return this;
}
/** Foursquare venue ID. */
public CheckinBuilder venueId(int venueId) {
this.postParameter(POST_VENUE_ID, venueId);
return this;
}
/** Custom venue name for display purposes. */
public CheckinBuilder venueName(String venueName) {
this.postParameter(POST_VENUE_NAME, venueName);
return this;
}
/**
* The message to use for sharing. If not sent, it will use the
* localized watching string set on the connections page. The message
* will be truncated to 100 characters to make sure it fits in the tweet
* with the url and hashtag.
*/
public CheckinBuilder message(String message) {
this.postParameter(POST_MESSAGE, message);
return this;
}
}
public static final class CancelCheckinBuilder extends TraktApiBuilder<Response> {
private static final String URI = "/show/cancelcheckin/" + FIELD_API_KEY;
private CancelCheckinBuilder(ShowService service) {
super(service, new TypeToken<Response>() {}, URI, HttpMethod.Post);
}
}
}
|
UweTrottmann/MovieTracker
|
SeriesGuideMovies/src/com/jakewharton/trakt/services/ShowService.java
|
Java
|
apache-2.0
| 60,531
|
import { FormControl } from '../../form-control';
import { RequiredValidator } from './required';
describe('Required validator', () => {
let formControl: FormControl<any>;
beforeEach(() => {
formControl = new FormControl<any>(
[RequiredValidator()]
);
});
it('if value is undefined, it should be invalid', () => {
formControl.validate();
expect(formControl.valid).toBe(false);
});
it('if value is empty array, it should be invalid', () => {
formControl.value = [];
formControl.validate();
expect(formControl.valid).toBe(false);
});
it('is value is empty string, it should be invalid', () => {
formControl.value = '';
formControl.validate();
expect(formControl.valid).toBe(false);
});
it('if value is 0, it should be valid', () => {
formControl.value = 0;
formControl.validate();
expect(formControl.valid).toBe(true);
});
it('if value is set, it should be valid', () => {
formControl.value = 'test';
formControl.validate();
expect(formControl.valid).toBe(true);
});
});
|
ulaval/modul-components
|
src/utils/form/validators/required/required.spec.ts
|
TypeScript
|
apache-2.0
| 1,178
|
<?php
return [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=sistema_votacao',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
];
|
rydiorc/sistema-de-votacao
|
config/db.php
|
PHP
|
apache-2.0
| 188
|
package a4336.a0.practise.james.mvppractise.Presenter;
import a4336.a0.practise.james.mvppractise.DTO.IDTO;
/**
* Created by james on 13/12/16.
*/
public interface PresenterInterface<E> {
void onStart();
void onRestart();
void onStop();
void onDestroy();
void onPause();
void onResume();
IDTO retrieveModel();
void doAction(IDTO<E> dao);
}
|
JamesAlexander1/AndroidNotes
|
java/a4336/a0/practise/james/mvppractise/Presenter/PresenterInterface.java
|
Java
|
apache-2.0
| 380
|
#ifndef _ZZIP__CONFIG_H
#define _ZZIP__CONFIG_H 1
/* zzip/_config.h. Generated automatically at end of configure. */
/* config.h. Generated from config.h.in by configure. */
/* config.h.in. Generated from configure.ac by autoheader. */
/* Define if pointers to integers require aligned access */
/* #undef HAVE_ALIGNED_ACCESS_REQUIRED */
/* Define to 1 if you have the <byteswap.h> header file. */
#ifndef ZZIP_HAVE_BYTESWAP_H
#define ZZIP_HAVE_BYTESWAP_H 1
#endif
/* Define to 1 if you have the <direct.h> header file. */
/* #undef HAVE_DIRECT_H */
/* Define to 1 if you have the <dirent.h> header file, and it defines `DIR'.
*/
#ifndef ZZIP_HAVE_DIRENT_H
#define ZZIP_HAVE_DIRENT_H 1
#endif
/* Define to 1 if you have the <dlfcn.h> header file. */
#ifndef ZZIP_HAVE_DLFCN_H
#define ZZIP_HAVE_DLFCN_H 1
#endif
/* Define to 1 if you have the <fnmatch.h> header file. */
#ifndef ZZIP_HAVE_FNMATCH_H
#define ZZIP_HAVE_FNMATCH_H 1
#endif
/* Define to 1 if you have the <inttypes.h> header file. */
#ifndef ZZIP_HAVE_INTTYPES_H
#define ZZIP_HAVE_INTTYPES_H 1
#endif
/* Define to 1 if you have the <io.h> header file. */
/* #undef HAVE_IO_H */
/* Define to 1 if you have the <memory.h> header file. */
#ifndef ZZIP_HAVE_MEMORY_H
#define ZZIP_HAVE_MEMORY_H 1
#endif
/* Define to 1 if you have the <ndir.h> header file, and it defines `DIR'. */
/* #undef HAVE_NDIR_H */
/* Define to 1 if you have the <stdint.h> header file. */
#ifndef ZZIP_HAVE_STDINT_H
#define ZZIP_HAVE_STDINT_H 1
#endif
/* Define to 1 if you have the <stdlib.h> header file. */
#ifndef ZZIP_HAVE_STDLIB_H
#define ZZIP_HAVE_STDLIB_H 1
#endif
/* Define to 1 if you have the `strcasecmp' function. */
#ifndef ZZIP_HAVE_STRCASECMP
#define ZZIP_HAVE_STRCASECMP 1
#endif
/* Define to 1 if you have the <strings.h> header file. */
#ifndef ZZIP_HAVE_STRINGS_H
#define ZZIP_HAVE_STRINGS_H 1
#endif
/* Define to 1 if you have the <string.h> header file. */
#ifndef ZZIP_HAVE_STRING_H
#define ZZIP_HAVE_STRING_H 1
#endif
/* Define to 1 if you have the `strndup' function. */
#ifndef ZZIP_HAVE_STRNDUP
#define ZZIP_HAVE_STRNDUP 1
#endif
/* Define to 1 if you have the <sys/dir.h> header file, and it defines `DIR'.
*/
/* #undef HAVE_SYS_DIR_H */
/* Define to 1 if you have the <sys/int_types.h> header file. */
/* #undef HAVE_SYS_INT_TYPES_H */
/* Define to 1 if you have the <sys/mman.h> header file. */
#ifndef ZZIP_HAVE_SYS_MMAN_H
#define ZZIP_HAVE_SYS_MMAN_H 1
#endif
/* Define to 1 if you have the <sys/ndir.h> header file, and it defines `DIR'.
*/
/* #undef HAVE_SYS_NDIR_H */
/* Define to 1 if you have the <sys/param.h> header file. */
#ifndef ZZIP_HAVE_SYS_PARAM_H
#define ZZIP_HAVE_SYS_PARAM_H 1
#endif
/* Define to 1 if you have the <sys/stat.h> header file. */
#ifndef ZZIP_HAVE_SYS_STAT_H
#define ZZIP_HAVE_SYS_STAT_H 1
#endif
/* Define to 1 if you have the <sys/types.h> header file. */
#ifndef ZZIP_HAVE_SYS_TYPES_H
#define ZZIP_HAVE_SYS_TYPES_H 1
#endif
/* Define to 1 if you have the <unistd.h> header file. */
#ifndef ZZIP_HAVE_UNISTD_H
#define ZZIP_HAVE_UNISTD_H 1
#endif
/* Define to 1 if you have the <winbase.h> header file. */
/* #undef HAVE_WINBASE_H */
/* Define to 1 if you have the <windows.h> header file. */
/* #undef HAVE_WINDOWS_H */
/* Define to 1 if you have the <winnt.h> header file. */
/* #undef HAVE_WINNT_H */
/* Define to 1 if you have the <zlib.h> header file. */
#ifndef ZZIP_HAVE_ZLIB_H
#define ZZIP_HAVE_ZLIB_H 1
#endif
/* whether the system defaults to 32bit off_t but can do 64bit when requested
*/
#ifndef ZZIP_LARGEFILE_SENSITIVE
#define ZZIP_LARGEFILE_SENSITIVE 1
#endif
/* Name of package */
#ifndef ZZIP_PACKAGE
#define ZZIP_PACKAGE "zziplib"
#endif
/* Define to the address where bug reports for this package should be sent. */
#ifndef ZZIP_PACKAGE_BUGREPORT
#define ZZIP_PACKAGE_BUGREPORT ""
#endif
/* Define to the full name of this package. */
#ifndef ZZIP_PACKAGE_NAME
#define ZZIP_PACKAGE_NAME ""
#endif
/* Define to the full name and version of this package. */
#ifndef ZZIP_PACKAGE_STRING
#define ZZIP_PACKAGE_STRING ""
#endif
/* Define to the one symbol short name of this package. */
#ifndef ZZIP_PACKAGE_TARNAME
#define ZZIP_PACKAGE_TARNAME ""
#endif
/* Define to the version of this package. */
#ifndef ZZIP_PACKAGE_VERSION
#define ZZIP_PACKAGE_VERSION ""
#endif
/* The number of bytes in type int */
#ifndef ZZIP_SIZEOF_INT
#define ZZIP_SIZEOF_INT 4
#endif
/* The number of bytes in type long */
#ifndef ZZIP_SIZEOF_LONG
#define ZZIP_SIZEOF_LONG 4
#endif
/* The number of bytes in type short */
#ifndef ZZIP_SIZEOF_SHORT
#define ZZIP_SIZEOF_SHORT 2
#endif
/* Define to 1 if you have the ANSI C header files. */
#ifndef ZZIP_STDC_HEADERS
#define ZZIP_STDC_HEADERS 1
#endif
/* Version number of package */
#ifndef ZZIP_VERSION
#define ZZIP_VERSION "0.13.49"
#endif
/* Define to 1 if your processor stores words with the most significant byte
first (like Motorola and SPARC, unlike Intel and VAX). */
/* #undef WORDS_BIGENDIAN */
/* Number of bits in a file offset, on hosts where this is settable. */
#ifndef ZZIP__FILE_OFFSET_BITS
#define ZZIP__FILE_OFFSET_BITS 64
#endif
/* Define for large files, on AIX-style hosts. */
/* #undef _LARGE_FILES */
/* Define to `long long' if <sys/types.h> does not define. */
#ifndef ZZIP___int64
#define ZZIP___int64 long long
#endif
/* Define to empty if `const' does not conform to ANSI C. */
/* #undef const */
/* Define to `__inline__' or `__inline' if that's what the C compiler
calls it, or to nothing if 'inline' is not supported under any name. */
#ifndef __cplusplus
/* #undef inline */
#endif
/* Define to `_zzip_off_t' if <sys/types.h> does not define. */
#ifndef _zzip_off64_t
#define _zzip_off64_t _zzip_off_t
#endif
/* Define to `long int' if <sys/types.h> does not define. */
/* #undef off_t */
/* Define to equivalent of C99 restrict keyword, or to nothing if this is not
supported. Do not define if restrict is supported directly. */
#ifndef _zzip_restrict
#define _zzip_restrict __restrict__
#endif
/* Define to `unsigned int' if <sys/types.h> does not define. */
/* #undef size_t */
/* Define to `int' if <sys/types.h> does not define. */
/* #undef ssize_t */
/* once: _ZZIP__CONFIG_H */
#endif
|
LiberatorUSA/GUCEF
|
dependencies/zziplib/zzip/_config.h
|
C
|
apache-2.0
| 6,346
|
/*
* Copyright 2015 Ben Manes. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.benmanes.caffeine.jcache.configuration;
import java.util.Map;
import javax.cache.integration.CacheLoader;
/**
* @author ben.manes@gmail.com (Ben Manes)
*/
public final class TestCacheLoader implements CacheLoader<Integer, Integer> {
@Override public Integer load(Integer key) {
return null;
}
@SuppressWarnings("ReturnsNullCollection")
@Override public Map<Integer, Integer> loadAll(Iterable<? extends Integer> keys) {
return null;
}
}
|
ben-manes/caffeine
|
jcache/src/test/java/com/github/benmanes/caffeine/jcache/configuration/TestCacheLoader.java
|
Java
|
apache-2.0
| 1,093
|
require 'spec_helper'
describe 'merging users', :type => :request do
let(:user) { threadable.users.find_by_email_address!('bethany@ucsd.example.com') }
let(:destination_user) { threadable.users.find_by_email_address!('alice@ucsd.example.com') }
let(:user_record) { user.user_record }
let(:destination_user_record){ destination_user.user_record }
before do
@event = Event.create!(
event_type: 'task_added_doer',
organization: user_record.organizations.first,
user_id: user.id,
content: {doer_id: user.id}
)
end
it 'should copy all the relationships from user to the destination user and delete the user' do
email_addresses = user_record.email_addresses.to_set
organization_memberships = user_record.organization_memberships.map(&:organization_id).to_set
group_memberships = user_record.group_memberships.map(&:group_id).to_set
messages = user_record.messages.to_set
events = user_record.events.to_set
external_authorizations = user_record.external_authorizations.to_set
task_doers = user_record.task_doers.map(&:task_id).to_set
user.merge_into! destination_user
expect(User.where(id: user.id)).to_not exist
destination_user_record.reload
expect( destination_user_record.email_addresses.to_set ).to be_a_superset email_addresses
expect( destination_user_record.organization_memberships.map(&:organization_id).to_set ).to be_a_superset organization_memberships
expect( destination_user_record.group_memberships.map(&:group_id).to_set ).to be_a_superset group_memberships
expect( destination_user_record.messages.to_set ).to be_a_superset messages
expect( destination_user_record.events.to_set ).to be_a_superset events
expect( destination_user_record.external_authorizations.to_set ).to be_a_superset external_authorizations
expect( destination_user_record.task_doers.map(&:task_id).to_set ).to be_a_superset task_doers
expect( EmailAddress .where(user_id: user.id) ).to be_empty
expect( OrganizationMembership .where(user_id: user.id) ).to be_empty
expect( GroupMembership .where(user_id: user.id) ).to be_empty
expect( Message .where(user_id: user.id) ).to be_empty
expect( Event .where(user_id: user.id) ).to be_empty
expect( ExternalAuthorization .where(user_id: user.id) ).to be_empty
expect( TaskDoer .where(user_id: user.id) ).to be_empty
@event.reload
expect( @event.user_id ).to eq destination_user.id
expect( @event.content[:doer_id] ).to eq destination_user.id
end
end
|
otherio/threadable.com
|
spec/integration/merging_users_spec.rb
|
Ruby
|
apache-2.0
| 2,881
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Simple [DEFLATE][def]-based compression. This is a wrapper around the
//! [`miniz`][mz] library, which is a one-file pure-C implementation of zlib.
//!
//! [def]: https://en.wikipedia.org/wiki/DEFLATE
//! [mz]: https://code.google.com/p/miniz/
#![crate_name = "flate"]
#![experimental]
#![staged_api]
#![crate_type = "rlib"]
#![crate_type = "dylib"]
#![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "http://www.rust-lang.org/favicon.ico",
html_root_url = "http://doc.rust-lang.org/nightly/")]
#[cfg(test)] #[macro_use] extern crate log;
extern crate libc;
use libc::{c_void, size_t, c_int};
use std::ops::Deref;
use std::ptr::Unique;
use std::slice;
pub struct Bytes {
ptr: Unique<u8>,
len: uint,
}
impl Deref for Bytes {
type Target = [u8];
fn deref(&self) -> &[u8] {
unsafe { slice::from_raw_mut_buf(&self.ptr.0, self.len) }
}
}
impl Drop for Bytes {
fn drop(&mut self) {
unsafe { libc::free(self.ptr.0 as *mut _); }
}
}
#[link(name = "miniz", kind = "static")]
extern {
/// Raw miniz compression function.
fn tdefl_compress_mem_to_heap(psrc_buf: *const c_void,
src_buf_len: size_t,
pout_len: *mut size_t,
flags: c_int)
-> *mut c_void;
/// Raw miniz decompression function.
fn tinfl_decompress_mem_to_heap(psrc_buf: *const c_void,
src_buf_len: size_t,
pout_len: *mut size_t,
flags: c_int)
-> *mut c_void;
}
static LZ_NORM : c_int = 0x80; // LZ with 128 probes, "normal"
static TINFL_FLAG_PARSE_ZLIB_HEADER : c_int = 0x1; // parse zlib header and adler32 checksum
static TDEFL_WRITE_ZLIB_HEADER : c_int = 0x01000; // write zlib header and adler32 checksum
fn deflate_bytes_internal(bytes: &[u8], flags: c_int) -> Option<Bytes> {
unsafe {
let mut outsz : size_t = 0;
let res = tdefl_compress_mem_to_heap(bytes.as_ptr() as *const _,
bytes.len() as size_t,
&mut outsz,
flags);
if !res.is_null() {
let res = Unique(res as *mut u8);
Some(Bytes { ptr: res, len: outsz as uint })
} else {
None
}
}
}
/// Compress a buffer, without writing any sort of header on the output.
pub fn deflate_bytes(bytes: &[u8]) -> Option<Bytes> {
deflate_bytes_internal(bytes, LZ_NORM)
}
/// Compress a buffer, using a header that zlib can understand.
pub fn deflate_bytes_zlib(bytes: &[u8]) -> Option<Bytes> {
deflate_bytes_internal(bytes, LZ_NORM | TDEFL_WRITE_ZLIB_HEADER)
}
fn inflate_bytes_internal(bytes: &[u8], flags: c_int) -> Option<Bytes> {
unsafe {
let mut outsz : size_t = 0;
let res = tinfl_decompress_mem_to_heap(bytes.as_ptr() as *const _,
bytes.len() as size_t,
&mut outsz,
flags);
if !res.is_null() {
let res = Unique(res as *mut u8);
Some(Bytes { ptr: res, len: outsz as uint })
} else {
None
}
}
}
/// Decompress a buffer, without parsing any sort of header on the input.
pub fn inflate_bytes(bytes: &[u8]) -> Option<Bytes> {
inflate_bytes_internal(bytes, 0)
}
/// Decompress a buffer that starts with a zlib header.
pub fn inflate_bytes_zlib(bytes: &[u8]) -> Option<Bytes> {
inflate_bytes_internal(bytes, TINFL_FLAG_PARSE_ZLIB_HEADER)
}
#[cfg(test)]
mod tests {
use super::{inflate_bytes, deflate_bytes};
use std::rand;
use std::rand::Rng;
#[test]
fn test_flate_round_trip() {
let mut r = rand::thread_rng();
let mut words = vec!();
for _ in range(0u, 20) {
let range = r.gen_range(1u, 10);
let v = r.gen_iter::<u8>().take(range).collect::<Vec<u8>>();
words.push(v);
}
for _ in range(0u, 20) {
let mut input = vec![];
for _ in range(0u, 2000) {
input.push_all(r.choose(words.as_slice()).unwrap().as_slice());
}
debug!("de/inflate of {} bytes of random word-sequences",
input.len());
let cmp = deflate_bytes(input.as_slice()).expect("deflation failed");
let out = inflate_bytes(cmp.as_slice()).expect("inflation failed");
debug!("{} bytes deflated to {} ({:.1}% size)",
input.len(), cmp.len(),
100.0 * ((cmp.len() as f64) / (input.len() as f64)));
assert_eq!(input, out.as_slice());
}
}
#[test]
fn test_zlib_flate() {
let bytes = vec!(1, 2, 3, 4, 5);
let deflated = deflate_bytes(bytes.as_slice()).expect("deflation failed");
let inflated = inflate_bytes(deflated.as_slice()).expect("inflation failed");
assert_eq!(inflated.as_slice(), bytes);
}
}
|
ktossell/rust
|
src/libflate/lib.rs
|
Rust
|
apache-2.0
| 5,723
|
package com.jersey.resources;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import javax.xml.bind.JAXBElement;
import com.jersey.model.Car;
import com.jersey.singleton.CarDao;
public class CarResource {
@Context
UriInfo uriInfo;
@Context
Request request;
String id;
public CarResource(UriInfo uriInfo, Request request, String id) {
this.uriInfo = uriInfo;
this.request = request;
this.id = id;
}
//Application integration
@GET
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public Car getCar() {
Car car = CarDao.instance.getModel().get(id);
if(car==null)
throw new RuntimeException("Get: Car with " + id + " not found - Type APP_XML/APP_JSON");
return car;
}
// for the browser
@GET
@Produces(MediaType.TEXT_XML)
public Car getCarHTML() {
Car car = CarDao.instance.getModel().get(id);
if(car==null)
throw new RuntimeException("Get: Car with " + id + " not found - Type TEXT_XML");
return car;
}
@PUT
@Consumes(MediaType.APPLICATION_XML)
public Response putCar(JAXBElement<Car> car) {
Car c = car.getValue();
return putAndGetResponse(c);
}
@DELETE
public void deleteCar() {
Car c = CarDao.instance.getModel().remove(id);
if(c==null)
throw new RuntimeException("Delete: Car with " + id + " not found");
}
private Response putAndGetResponse(Car car) {
Response res;
if(CarDao.instance.getModel().containsKey(car.getRegistrationNumber())) {
res = Response.noContent().build();
} else {
res = Response.created(uriInfo.getAbsolutePath()).build();
}
CarDao.instance.getModel().put(car.getRegistrationNumber(), car);
return res;
}
}
|
jmanday/Master
|
DSS/Practicas/Practica3/GarciaMandayJesus-p3/com.jersey/src/com/jersey/resources/CarResource.java
|
Java
|
apache-2.0
| 2,097
|
/*
* (C) Copyright IBM Corp. 2014
*
* 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.ibm.portal.samples.mvc;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.GenericPortlet;
import javax.portlet.MimeResponse;
import javax.portlet.PortletException;
import javax.portlet.PortletRequest;
import javax.portlet.PortletResponse;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import javax.portlet.ResourceRequest;
import javax.portlet.ResourceResponse;
import com.ibm.portal.samples.common.Marshaller;
import com.ibm.portal.samples.common.PrivateParameterMarshaller;
import com.ibm.portal.samples.mvc.controller.TemplateController;
import com.ibm.portal.samples.mvc.model.TemplateActions;
import com.ibm.portal.samples.mvc.model.TemplateModel;
import com.ibm.portal.samples.mvc.view.TemplateView;
/**
* Implementation of the actual portlet class. The portlet initializes and
* manages the lifecycle of the model, view and controller beans. During
* rendering it dispatches to a JSP that can then make use of the beans via
* request attributes. The JSP is located inside a subdirectory of the "WEB-INF"
* directory. The subdirectory follows the package structure of the portlet
* class. The name of the JSP is the name of the portlet mode, followed by
* ".jsp".
*
* The JSP is located inside the "WEB-INF" directory, because it is not supposed
* to be accessed directly via a servlet entry point. Using the package name as
* the directory structure makes it easier to maintain multiple portlets in one
* project.
*
* @author cleue
*/
public class TemplatePortlet extends GenericPortlet {
/**
* Representation to dependencies on external services. Note that this
* interface inherits all dependencies from the components it aggregates.
* You should use a naming convention such that common dependencies use the
* same getters.
*/
public interface Dependencies extends TemplateModel.Dependencies,
TemplateActions.Dependencies, TemplateController.Dependencies,
TemplateView.Dependencies {
/**
* TODO add dependencies via parameterless getter methods
*/
}
/**
* Name of the request attribute for the controller
*/
private static final String KEY_CONTROLLER = "controller";
/**
* Name of the request attribute for the model
*/
private static final String KEY_MODEL = "model";
/**
* Name of the request attribute for the view
*/
private static final String KEY_VIEW = "view";
/** class name for the logger */
private static final String LOG_CLASS = TemplatePortlet.class.getName();
/** logging level */
private static final Level LOG_LEVEL = Level.FINER;
/** class logger */
private static final Logger LOGGER = Logger.getLogger(LOG_CLASS);
/**
* reference to external services
*/
private Dependencies dependencies;
/**
* root path for JSPs. Per default we use the package name of the portlet
* inside the WEB-INF directory.
*/
private String jspRoot;
/**
* Constructs the action handler
*
* @param aModel
* model the actions will work on
* @param aRequest
* the action request
* @param aResponse
* the action response
* @return the model
*
* @throws PortletException
* @throws IOException
*/
private final TemplateActions createActions(final TemplateModel aModel,
final ActionRequest aRequest, final ActionResponse aResponse)
throws PortletException, IOException {
// sanity check
assert aModel != null;
assert aRequest != null;
assert aResponse != null;
/**
* Decodes the action.This method normally does not have to be changed.
* Rather change the implementation of the action.
*/
return new TemplateActions(aModel, aRequest, aResponse, dependencies);
}
/**
* Constructs a new controller
*
* @param aModel
* the model
* @param aRequest
* the request
* @param aResponse
* the response
* @return the controller
*/
private final TemplateController createController(
final TemplateModel aModel, final PortletRequest aRequest,
final MimeResponse aResponse) {
// sanity check
assert aModel != null;
assert aRequest != null;
assert aResponse != null;
/**
* Constructs the controller. This method normally does not have to be
* changed. Rather change the implementation of the controller.
*/
return new TemplateController(aModel, aRequest, aResponse, dependencies);
}
/**
* Decodes the model used during rendering
*
* @param aRequest
* the portlet request
* @param aResponse
* the portlet response
* @return the model
*
* @throws PortletException
* @throws IOException
*/
private final TemplateModel decodeModel(final PortletRequest aRequest,
final PortletResponse aResponse) throws PortletException,
IOException {
// sanity check
assert aRequest != null;
assert aResponse != null;
/**
* Decodes the model.This method normally does not have to be changed.
* Rather change the implementation of the model.
*/
return new TemplateModel(aRequest, aResponse, getPortletConfig(),
dependencies);
}
/*
* (non-Javadoc)
*
* @see javax.portlet.GenericPortlet#destroy()
*/
@Override
public void destroy() {
// logging support
final String LOG_METHOD = "destroy()";
final boolean bIsLogging = LOGGER.isLoggable(LOG_LEVEL);
if (bIsLogging) {
LOGGER.entering(LOG_CLASS, LOG_METHOD);
}
// TODO reset all other instance fields to null
// reset the dependencies
dependencies = null;
jspRoot = null;
// default
super.destroy();
// exit trace
if (bIsLogging) {
LOGGER.exiting(LOG_CLASS, LOG_METHOD);
}
}
/*
* (non-Javadoc)
*
* @see javax.portlet.GenericPortlet#doDispatch(javax.portlet.RenderRequest,
* javax.portlet.RenderResponse)
*/
@Override
protected void doDispatch(final RenderRequest request,
final RenderResponse response) throws PortletException, IOException {
// logging support
final String LOG_METHOD = "doDispatch(request, response)";
final boolean bIsLogging = LOGGER.isLoggable(LOG_LEVEL);
if (bIsLogging) {
LOGGER.entering(LOG_CLASS, LOG_METHOD);
}
// initialize the content type
response.setContentType(request.getResponseContentType());
// render the JSP
final String jspName = jspRoot + request.getPortletMode() + ".jsp";
getPortletContext().getRequestDispatcher(jspName).include(request,
response);
// exit trace
if (bIsLogging) {
LOGGER.exiting(LOG_CLASS, LOG_METHOD);
}
}
/*
* (non-Javadoc)
*
* @see com.ibm.portal.portlet.base.portal.WebSpherePortalPortlet#init()
*/
@Override
public void init() throws PortletException {
// logging support
final String LOG_METHOD = "init()";
final boolean bIsLogging = LOGGER.isLoggable(LOG_LEVEL);
if (bIsLogging) {
LOGGER.entering(LOG_CLASS, LOG_METHOD);
}
// default
super.init();
// initialize the JSP root path
jspRoot = "/WEB-INF/"
+ TemplatePortlet.class.getPackage().getName()
.replace('.', '/') + "/";
// log this
if (bIsLogging) {
LOGGER.logp(LOG_LEVEL, LOG_CLASS, LOG_METHOD, "Root path [{0}].",
jspRoot);
}
/**
* Note that our dependency interface extends the dependency interfaces
* of multiple other components. Thanks to a naming convention however
* the methods all collapse into one single method that we have to
* implement.
*/
dependencies = new Dependencies() {
/*
* (non-Javadoc)
*
* @see com.ibm.portal.samples.portlettemplate.model.TemplateModel.
* Dependencies#getPrivateParameterMarshaller()
*/
@Override
public Marshaller getPrivateParameterMarshaller() {
// decide how to marshal private parameters
return PrivateParameterMarshaller.SINGLETON;
}
// implement your getters here
};
// exit trace
if (bIsLogging) {
LOGGER.exiting(LOG_CLASS, LOG_METHOD);
}
}
/*
* (non-Javadoc)
*
* @see
* javax.portlet.GenericPortlet#processAction(javax.portlet.ActionRequest,
* javax.portlet.ActionResponse)
*/
@Override
public void processAction(final ActionRequest request,
final ActionResponse response) throws PortletException, IOException {
// logging support
final String LOG_METHOD = "processAction(request, response)";
final boolean bIsLogging = LOGGER.isLoggable(LOG_LEVEL);
if (bIsLogging) {
LOGGER.entering(LOG_CLASS, LOG_METHOD);
}
// decode the model
final TemplateModel model = decodeModel(request, response);
// construct the action handler
final TemplateActions actions = createActions(model, request, response);
try {
// process the model
if (actions.processActions()) {
// log this
if (bIsLogging) {
LOGGER.logp(LOG_LEVEL, LOG_CLASS, LOG_METHOD,
"Committing the model ...");
}
// commit persistent modifications
actions.commit();
}
} catch (final Throwable ex) {
// handle the exception
} finally {
/**
* Encodes the model. This is an important step, without it the
* navigational state would be lost after the action.
*/
model.encode(response);
// dispose
actions.dispose();
model.dispose();
}
// exit trace
if (bIsLogging) {
LOGGER.exiting(LOG_CLASS, LOG_METHOD);
}
}
/*
* (non-Javadoc)
*
* @see javax.portlet.GenericPortlet#render(javax.portlet.RenderRequest,
* javax.portlet.RenderResponse)
*/
@Override
public void render(final RenderRequest request,
final RenderResponse response) throws PortletException, IOException {
// logging support
final String LOG_METHOD = "doDispatch(request, response)";
final boolean bIsLogging = LOGGER.isLoggable(LOG_LEVEL);
if (bIsLogging) {
LOGGER.entering(LOG_CLASS, LOG_METHOD);
}
// construct the view bean
final TemplateView view = new TemplateView(getPortletConfig(), request,
response, dependencies);
// decode the model
final TemplateModel model = decodeModel(request, response);
// get the controller
final TemplateController controller = createController(model, request,
response);
// set the beans, so we can access them in the JSP
request.setAttribute(KEY_VIEW, view);
request.setAttribute(KEY_MODEL, model);
request.setAttribute(KEY_CONTROLLER, controller);
try {
// default handling
super.render(request, response);
} finally {
// release model and controller
request.removeAttribute(KEY_CONTROLLER);
request.removeAttribute(KEY_MODEL);
request.removeAttribute(KEY_VIEW);
// dispose
controller.dispose();
model.dispose();
view.dispose();
}
// exit trace
if (bIsLogging) {
LOGGER.exiting(LOG_CLASS, LOG_METHOD);
}
}
/*
* (non-Javadoc)
*
* @see
* javax.portlet.GenericPortlet#serveResource(javax.portlet.ResourceRequest,
* javax.portlet.ResourceResponse)
*/
@Override
public void serveResource(final ResourceRequest request,
final ResourceResponse response) throws PortletException,
IOException {
/**
* Method not required at the moment. Make sure to override the default
* implementation, because it exposes a security issue.
*/
}
}
|
OpenNTF/WebSpherePortalPortletSamples
|
TemplatePortlet/src/main/java/com/ibm/portal/samples/mvc/TemplatePortlet.java
|
Java
|
apache-2.0
| 12,188
|
# Rhizocarpon geographicum var. alandica (Räsänen) Räsänen VARIETY
#### Status
ACCEPTED
#### According to
Index Fungorum
#### Published in
null
#### Original name
Rhizocarpon geographicum f. alandicum Räsänen
### Remarks
null
|
mdoering/backbone
|
life/Fungi/Ascomycota/Lecanoromycetes/Lecanorales/Rhizocarpaceae/Rhizocarpon/Rhizocarpon geographicum/Rhizocarpon geographicum alandica/README.md
|
Markdown
|
apache-2.0
| 236
|
# Skyttea elachistophora (Nyl.) Sherwood & D. Hawksw. SPECIES
#### Status
ACCEPTED
#### According to
Index Fungorum
#### Published in
in Sherwood, Hawksworth & Coppins, Trans. Br. mycol. Soc. 75(3): 484 (1981)
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Fungi/Ascomycota/Lecanoromycetes/Ostropales/Odontotremataceae/Skyttea/Skyttea elachistophora/README.md
|
Markdown
|
apache-2.0
| 255
|
# Mesanthemum albidum Lecomte 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/Liliopsida/Poales/Eriocaulaceae/Mesanthemum/Mesanthemum albidum/README.md
|
Markdown
|
apache-2.0
| 185
|
# Chomelia apodantha (Standl.) Steyerm. 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/Gentianales/Rubiaceae/Chomelia/Chomelia apodantha/README.md
|
Markdown
|
apache-2.0
| 195
|
# Staurastrum tohopekaligense var. trifurcatum West & G.S. West VARIETY
#### Status
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Chlorophyta/Zygnematophyceae/Zygnematales/Desmidiaceae/Staurastrum/Staurastrum tohopekaligense/Staurastrum tohopekaligense trifurcatum/README.md
|
Markdown
|
apache-2.0
| 219
|
# Hymenocallis choctawensis Traub 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/Liliopsida/Asparagales/Amaryllidaceae/Hymenocallis/Hymenocallis choctawensis/README.md
|
Markdown
|
apache-2.0
| 189
|
/*
*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.wso2.carbon.apimgt.rest.api.common.interceptors;
import io.swagger.models.Swagger;
import io.swagger.parser.SwaggerParser;
import io.swagger.util.Json;
import org.osgi.service.component.annotations.Component;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.wso2.carbon.apimgt.core.exception.APIManagementException;
import org.wso2.carbon.apimgt.core.exception.ErrorHandler;
import org.wso2.carbon.apimgt.core.exception.ExceptionCodes;
import org.wso2.carbon.apimgt.rest.api.common.RestApiConstants;
import org.wso2.carbon.apimgt.rest.api.common.api.RESTAPIAuthenticator;
import org.wso2.carbon.apimgt.rest.api.common.dto.ErrorDTO;
import org.wso2.carbon.apimgt.rest.api.common.exception.APIMgtSecurityException;
import org.wso2.carbon.apimgt.rest.api.common.util.RestApiUtil;
import org.wso2.msf4j.Interceptor;
import org.wso2.msf4j.Request;
import org.wso2.msf4j.Response;
import org.wso2.msf4j.ServiceMethodInfo;
import java.util.HashMap;
import java.util.Locale;
import javax.ws.rs.core.MediaType;
import static org.wso2.carbon.messaging.Constants.PROTOCOL;
/**
* Security Interceptor that does basic authentication for REST ApI requests.
*
*/
@Component(
name = "org.wso2.carbon.apimgt.rest.api.common.interceptors.RESTAPISecurityInterceptor",
service = Interceptor.class,
immediate = true
)
public class RESTAPISecurityInterceptor implements Interceptor {
private static final Logger log = LoggerFactory.getLogger(RESTAPISecurityInterceptor.class);
//todo authenticatorName should be read from a configuration
private static String authenticatorName = "org.wso2.carbon.apimgt.rest.api.common.impl.OAuth2Authenticator";
private RESTAPIAuthenticator authenticatorImplClass = null;
/**
* preCall is run before a handler method call is made. If any of the preCalls throw exception or return false then
* no other subsequent preCalls will be called and the request processing will be terminated,
* also no postCall interceptors will be called.
*
* @param request HttpRequest being processed.
* @param response HttpResponder to send response.
* @param serviceMethodInfo Info on handler method that will be called.
* @return true if the request processing can continue, otherwise the hook should send response and return false to
* stop further processing.
* @throws APIMgtSecurityException if error occurs while executing the preCall
*/
@Override
public boolean preCall(Request request, Response response, ServiceMethodInfo serviceMethodInfo) throws
APIMgtSecurityException {
ErrorHandler errorHandler = null;
boolean isAuthenticated = false;
/* TODO: Following string contains check is done to avoid checking security headers in non API requests.
* Consider this as a tempory fix until MSF4J support context based interceptor registration */
String requestURI = request.getUri().toLowerCase(Locale.ENGLISH);
if (!requestURI.contains("/api/am/")) {
return true;
}
String yamlContent = null;
String protocol = (String) request.getProperty(PROTOCOL);
Swagger swagger = null;
if (requestURI.contains("/publisher")) {
if (requestURI.contains("swagger.json")) {
try {
yamlContent = RestApiUtil.getPublisherRestAPIResource();
swagger = new SwaggerParser().parse(yamlContent);
swagger.setBasePath(RestApiUtil.getContext(RestApiConstants.APPType.PUBLISHER));
swagger.setHost(RestApiUtil.getHost(protocol.toLowerCase(Locale.ENGLISH)));
} catch (APIManagementException e) {
log.error("Couldn't find swagger.json for publisher", e);
}
response.setStatus(javax.ws.rs.core.Response.Status.OK.getStatusCode()).setEntity(Json.pretty
(swagger)).setMediaType(MediaType.APPLICATION_JSON).send();
return false;
}
} else if (requestURI.contains("/store")) {
if (requestURI.contains("swagger.json")) {
try {
yamlContent = RestApiUtil.getStoreRestAPIResource();
swagger = new SwaggerParser().parse(yamlContent);
swagger.setBasePath(RestApiUtil.getContext(RestApiConstants.APPType.STORE));
swagger.setHost(RestApiUtil.getHost(protocol.toLowerCase(Locale.ENGLISH)));
} catch (APIManagementException e) {
log.error("Couldn't find swagger.json for store", e);
}
response.setStatus(javax.ws.rs.core.Response.Status.OK.getStatusCode()).setEntity(Json.pretty
(swagger)).setMediaType(MediaType.APPLICATION_JSON).send();
return false;
}
} else if (requestURI.contains("/editor") || requestURI.contains("keyserver") || requestURI.contains("core")) {
return true;
} else if (requestURI.contains("/admin")) {
if (requestURI.contains("swagger.json")) {
try {
yamlContent = RestApiUtil.getAdminRestAPIResource();
swagger = new SwaggerParser().parse(yamlContent);
swagger.setBasePath(RestApiUtil.getContext(RestApiConstants.APPType.ADMIN));
swagger.setHost(RestApiUtil.getHost(protocol.toLowerCase(Locale.ENGLISH)));
} catch (APIManagementException e) {
log.error("Couldn't find swagger.json for admin", e);
}
response.setStatus(javax.ws.rs.core.Response.Status.OK.getStatusCode()).setEntity(Json.pretty
(swagger)).setMediaType(MediaType.APPLICATION_JSON).send();
return false;
}
}
try {
if (authenticatorImplClass == null) {
Class<?> implClass = null;
try {
implClass = Class.forName(authenticatorName);
} catch (ClassNotFoundException e) {
throw new APIMgtSecurityException("Error while loading class " + authenticatorName, e);
}
authenticatorImplClass = (RESTAPIAuthenticator) implClass.newInstance();
}
isAuthenticated = authenticatorImplClass.authenticate(request, response, serviceMethodInfo);
} catch (APIMgtSecurityException e) {
errorHandler = e.getErrorHandler();
log.error(e.getMessage() + " Requested Path: " + request.getUri());
} catch (InstantiationException e) {
log.error(e.getMessage() + " Error while instantiating authenticator: " + authenticatorName);
isAuthenticated = false;
errorHandler = ExceptionCodes.AUTH_GENERAL_ERROR;
} catch (IllegalAccessException e) {
log.error(e.getMessage() + " Error while accessing resource : " + authenticatorName);
isAuthenticated = false;
errorHandler = ExceptionCodes.AUTH_GENERAL_ERROR;
}
if (!isAuthenticated) {
handleSecurityError(errorHandler, response);
}
return isAuthenticated;
}
/**
* postCall is run after a handler method call is made. If any of the postCalls throw and exception then the
* remaining postCalls will still be called. If the handler method was not called then postCall interceptors will
* not be called.
*
* @param request HttpRequest being processed.
* @param status Http status returned to the client.
* @param serviceMethodInfo Info on handler method that was called.
* @throws Exception if error occurs while executing the postCall
*/
@Override
public void postCall(Request request, int status, ServiceMethodInfo serviceMethodInfo) throws Exception {
}
/**
* Handles error condition
* @param errorHandler Security error code
* @param responder HttpResponder instance which is used send error messages back to the client
*/
private void handleSecurityError(ErrorHandler errorHandler, Response responder) {
HashMap<String, String> paramList = new HashMap<String, String>();
ErrorDTO errorDTO = RestApiUtil.getErrorDTO(errorHandler, paramList);
responder.setStatus(errorHandler.getHttpStatusCode());
responder.setHeader(javax.ws.rs.core.HttpHeaders.WWW_AUTHENTICATE, RestApiConstants.AUTH_TYPE_OAUTH2);
responder.setEntity(errorDTO);
responder.send();
}
}
|
lalaji/carbon-apimgt
|
components/apimgt/org.wso2.carbon.apimgt.rest.api.commons/src/main/java/org/wso2/carbon/apimgt/rest/api/common/interceptors/RESTAPISecurityInterceptor.java
|
Java
|
apache-2.0
| 9,415
|
#include "AppDelegate.h"
#include <vector>
#include <string>
#include "HelloWorldScene.h"
#include "AppMacros.h"
#include "audio/include/SimpleAudioEngine.h"
USING_NS_CC;
using namespace std;
using namespace CocosDenshion;
AppDelegate::AppDelegate() {
}
AppDelegate::~AppDelegate()
{
}
void AppDelegate::initGLContextAttrs()
{
GLContextAttrs glContextAttrs = {8, 8, 8, 8, 24, 8};
GLView::setGLContextAttrs(glContextAttrs);
}
bool AppDelegate::applicationDidFinishLaunching() {
// initialize director
auto director = Director::getInstance();
auto glview = director->getOpenGLView();
if(!glview) {
glview = GLViewImpl::create("Cpp Empty Test");
director->setOpenGLView(glview);
}
// glview->setFrameSize(1024/2, 576/2);//改变参数测试屏幕适配
director->setOpenGLView(glview);
// Set the design resolution
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WP8)
// a bug in DirectX 11 level9-x on the device prevents ResolutionPolicy::NO_BORDER from working correctly
glview->setDesignResolutionSize(designResolutionSize.width, designResolutionSize.height, ResolutionPolicy::EXACT_FIT);
#else
glview->setDesignResolutionSize(designResolutionSize.width, designResolutionSize.height, ResolutionPolicy::EXACT_FIT);
#endif
// Size frameSize = glview->getFrameSize();
vector<string> searchPath;
// In this demo, we select resource according to the frame's height.
// If the resource size is different from design resolution size, you need to set contentScaleFactor.
// We use the ratio of resource's height to the height of design resolution,
// this can make sure that the resource's height could fit for the height of design resolution.
// if the frame's height is larger than the height of medium resource size, select large resource.
// if (frameSize.height > mediumResource.size.height)
// {
// searchPath.push_back(largeResource.directory);
//
// director->setContentScaleFactor(MIN(largeResource.size.height/designResolutionSize.height, largeResource.size.width/designResolutionSize.width));
// }
// // if the frame's height is larger than the height of small resource size, select medium resource.
// else if (frameSize.height > smallResource.size.height)
// {
// searchPath.push_back(mediumResource.directory);
//
// director->setContentScaleFactor(MIN(mediumResource.size.height/designResolutionSize.height, mediumResource.size.width/designResolutionSize.width));
// }
// // if the frame's height is smaller than the height of medium resource size, select small resource.
// else
{
searchPath.push_back(smallResource.directory);
director->setContentScaleFactor(MIN(smallResource.size.height/designResolutionSize.height, smallResource.size.width/designResolutionSize.width));
}
// set searching path
FileUtils::getInstance()->setSearchPaths(searchPath);
// turn on display FPS
// director->setDisplayStats(true);
// set FPS. the default value is 1.0/60 if you don't call this
director->setAnimationInterval(1.0 / 60);
// create a scene. it's an autorelease object
auto scene = HelloWorld::scene();
// run
director->runWithScene(scene);
// play the bg music
SimpleAudioEngine::getInstance()->playBackgroundMusic("The Last Goodbye.mp3", true);
return true;
}
// This function will be called when the app is inactive. When comes a phone call,it's be invoked too
void AppDelegate::applicationDidEnterBackground() {
Director::getInstance()->stopAnimation();
// if you use SimpleAudioEngine, it must be pause
SimpleAudioEngine::getInstance()->pauseBackgroundMusic();
}
// this function will be called when the app is active again
void AppDelegate::applicationWillEnterForeground() {
Director::getInstance()->startAnimation();
// if you use SimpleAudioEngine, it must resume here
SimpleAudioEngine::getInstance()->resumeBackgroundMusic();
}
|
cheyiliu/Cocos2d-x-scene-transition
|
Classes/AppDelegate.cpp
|
C++
|
apache-2.0
| 4,000
|
# Caryopteris tangutica Maxim. SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
Bull. Acad. Imp. Sci. Saint-Pétersbourg 27:525; Mélanges Biol. Bull. Phys. -Math. Acad. Imp. Sci. Saint-Pétersbourg 11:301. 1882 (Diagn. pl. nov. asiat. )
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Lamiales/Lamiaceae/Caryopteris/Caryopteris tangutica/README.md
|
Markdown
|
apache-2.0
| 331
|
/*
* Copyright (C) 2020 MapRoulette contributors (see CONTRIBUTORS.md).
* Licensed under the Apache License, Version 2.0 (see LICENSE).
*/
package org.maproulette.framework.model
import org.joda.time.DateTime
import org.maproulette.framework.psql.CommonField
import org.maproulette.framework.model.Task
import play.api.libs.json.{Json, Reads, Writes}
import play.api.libs.json.JodaWrites._
import play.api.libs.json.JodaReads._
case class TaskReview(
id: Long,
taskId: Long,
reviewStatus: Option[Int],
challengeName: Option[String],
reviewRequestedBy: Option[Long],
reviewRequestedByUsername: Option[String],
reviewedBy: Option[Long],
reviewedByUsername: Option[String],
reviewedAt: Option[DateTime],
metaReviewedBy: Option[Long],
metaReviewStatus: Option[Int],
metaReviewedAt: Option[DateTime],
reviewStartedAt: Option[DateTime],
additionalReviewers: Option[List[Long]],
reviewClaimedBy: Option[Long],
reviewClaimedByUsername: Option[String],
reviewClaimedAt: Option[DateTime]
)
object TaskReview extends CommonField {
implicit val writes: Writes[TaskReview] = Json.writes[TaskReview]
implicit val reads: Reads[TaskReview] = Json.reads[TaskReview]
val TABLE = "task_review"
val FIELD_TASK_ID = "task_id"
val FIELD_REVIEW_STATUS = "review_status"
val FIELD_REVIEW_REQUESTED_BY = "review_requested_by"
val FIELD_REVIEWED_BY = "reviewed_by"
val FIELD_REVIEWED_AT = "reviewed_at"
val FIELD_META_REVIEWED_BY = "meta_reviewed_by"
val FIELD_META_REVIEWED_AT = "meta_reviewed_at"
val FIELD_META_REVIEW_STATUS = "meta_review_status"
val FIELD_REVIEW_CLAIMED_AT = "review_claimed_at"
val FIELD_REVIEW_CLAIMED_BY = "review_claimed_by"
val FIELD_REVIEW_STARTED_AT = "review_started_at"
}
case class TaskWithReview(task: Task, review: TaskReview)
object TaskWithReview {
implicit val taskWithReviewWrites: Writes[TaskWithReview] = Json.writes[TaskWithReview]
implicit val taskWithReviewReads: Reads[TaskWithReview] = Json.reads[TaskWithReview]
}
case class ReviewMetrics(
total: Int,
reviewRequested: Int,
reviewApproved: Int,
reviewRejected: Int,
reviewAssisted: Int,
reviewDisputed: Int,
metaReviewRequested: Int,
metaReviewApproved: Int,
metaReviewRejected: Int,
metaReviewAssisted: Int,
fixed: Int,
falsePositive: Int,
skipped: Int,
alreadyFixed: Int,
tooHard: Int,
avgReviewTime: Double,
userId: Option[Long] = None, // If these metrics apply to a particular user
tagName: Option[String] = None, // If these metrics apply for a particular tag
tagType: Option[String] = None // If these metrics apply for a particular tag with tag type
)
object ReviewMetrics {
implicit val reviewMetricsWrites = Json.writes[ReviewMetrics]
}
|
mgcuthbert/maproulette2
|
app/org/maproulette/framework/model/TaskReview.scala
|
Scala
|
apache-2.0
| 2,878
|
/*
* Licensed to The Apereo Foundation under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* The Apereo Foundation licenses this file to you under the Apache License,
* Version 2.0, (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tle.web.connectors.service;
import com.tle.common.security.SettingsTarget;
import com.tle.core.guice.Bind;
import com.tle.core.settings.security.AbstractSettingsPrivilegeTreeProvider;
import com.tle.web.resources.ResourcesService;
import javax.inject.Singleton;
@Bind
@Singleton
@SuppressWarnings("nls")
public class ConnectorManagementPrivilegeTreeProvider
extends AbstractSettingsPrivilegeTreeProvider {
public ConnectorManagementPrivilegeTreeProvider() {
super(
Type.MANAGEMENT_PAGE,
ResourcesService.getResourceHelper(ConnectorManagementPrivilegeTreeProvider.class)
.key("securitytree.manageconnectors"),
new SettingsTarget("connectors"));
}
}
|
equella/Equella
|
Source/Plugins/Core/com.equella.core/src/com/tle/web/connectors/service/ConnectorManagementPrivilegeTreeProvider.java
|
Java
|
apache-2.0
| 1,515
|
package spet.sbwo.api.service.base;
public interface IPrivate {
}
|
serban-petrescu/sbwo
|
src/main/java/spet/sbwo/api/service/base/IPrivate.java
|
Java
|
apache-2.0
| 68
|
# Conostylis prolifera Benth. 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/Liliopsida/Commelinales/Haemodoraceae/Conostylis/Conostylis prolifera/README.md
|
Markdown
|
apache-2.0
| 185
|
/*
* Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#pragma once
#include <aws/cloudformation/CloudFormation_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSStreamFwd.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/cloudformation/model/ParameterConstraints.h>
namespace Aws
{
namespace Utils
{
namespace Xml
{
class XmlNode;
} // namespace Xml
} // namespace Utils
namespace CloudFormation
{
namespace Model
{
/**
* <p>The ParameterDeclaration data type.</p>
*/
class AWS_CLOUDFORMATION_API ParameterDeclaration
{
public:
ParameterDeclaration();
ParameterDeclaration(const Aws::Utils::Xml::XmlNode& xmlNode);
ParameterDeclaration& operator=(const Aws::Utils::Xml::XmlNode& xmlNode);
void OutputToStream(Aws::OStream& ostream, const char* location, unsigned index, const char* locationValue) const;
void OutputToStream(Aws::OStream& oStream, const char* location) const;
/**
* <p>The name that is associated with the parameter.</p>
*/
inline const Aws::String& GetParameterKey() const{ return m_parameterKey; }
/**
* <p>The name that is associated with the parameter.</p>
*/
inline void SetParameterKey(const Aws::String& value) { m_parameterKeyHasBeenSet = true; m_parameterKey = value; }
/**
* <p>The name that is associated with the parameter.</p>
*/
inline void SetParameterKey(Aws::String&& value) { m_parameterKeyHasBeenSet = true; m_parameterKey = value; }
/**
* <p>The name that is associated with the parameter.</p>
*/
inline void SetParameterKey(const char* value) { m_parameterKeyHasBeenSet = true; m_parameterKey.assign(value); }
/**
* <p>The name that is associated with the parameter.</p>
*/
inline ParameterDeclaration& WithParameterKey(const Aws::String& value) { SetParameterKey(value); return *this;}
/**
* <p>The name that is associated with the parameter.</p>
*/
inline ParameterDeclaration& WithParameterKey(Aws::String&& value) { SetParameterKey(value); return *this;}
/**
* <p>The name that is associated with the parameter.</p>
*/
inline ParameterDeclaration& WithParameterKey(const char* value) { SetParameterKey(value); return *this;}
/**
* <p>The default value of the parameter.</p>
*/
inline const Aws::String& GetDefaultValue() const{ return m_defaultValue; }
/**
* <p>The default value of the parameter.</p>
*/
inline void SetDefaultValue(const Aws::String& value) { m_defaultValueHasBeenSet = true; m_defaultValue = value; }
/**
* <p>The default value of the parameter.</p>
*/
inline void SetDefaultValue(Aws::String&& value) { m_defaultValueHasBeenSet = true; m_defaultValue = value; }
/**
* <p>The default value of the parameter.</p>
*/
inline void SetDefaultValue(const char* value) { m_defaultValueHasBeenSet = true; m_defaultValue.assign(value); }
/**
* <p>The default value of the parameter.</p>
*/
inline ParameterDeclaration& WithDefaultValue(const Aws::String& value) { SetDefaultValue(value); return *this;}
/**
* <p>The default value of the parameter.</p>
*/
inline ParameterDeclaration& WithDefaultValue(Aws::String&& value) { SetDefaultValue(value); return *this;}
/**
* <p>The default value of the parameter.</p>
*/
inline ParameterDeclaration& WithDefaultValue(const char* value) { SetDefaultValue(value); return *this;}
/**
* <p>The type of parameter.</p>
*/
inline const Aws::String& GetParameterType() const{ return m_parameterType; }
/**
* <p>The type of parameter.</p>
*/
inline void SetParameterType(const Aws::String& value) { m_parameterTypeHasBeenSet = true; m_parameterType = value; }
/**
* <p>The type of parameter.</p>
*/
inline void SetParameterType(Aws::String&& value) { m_parameterTypeHasBeenSet = true; m_parameterType = value; }
/**
* <p>The type of parameter.</p>
*/
inline void SetParameterType(const char* value) { m_parameterTypeHasBeenSet = true; m_parameterType.assign(value); }
/**
* <p>The type of parameter.</p>
*/
inline ParameterDeclaration& WithParameterType(const Aws::String& value) { SetParameterType(value); return *this;}
/**
* <p>The type of parameter.</p>
*/
inline ParameterDeclaration& WithParameterType(Aws::String&& value) { SetParameterType(value); return *this;}
/**
* <p>The type of parameter.</p>
*/
inline ParameterDeclaration& WithParameterType(const char* value) { SetParameterType(value); return *this;}
/**
* <p>Flag that indicates whether the parameter value is shown as plain text in
* logs and in the AWS Management Console.</p>
*/
inline bool GetNoEcho() const{ return m_noEcho; }
/**
* <p>Flag that indicates whether the parameter value is shown as plain text in
* logs and in the AWS Management Console.</p>
*/
inline void SetNoEcho(bool value) { m_noEchoHasBeenSet = true; m_noEcho = value; }
/**
* <p>Flag that indicates whether the parameter value is shown as plain text in
* logs and in the AWS Management Console.</p>
*/
inline ParameterDeclaration& WithNoEcho(bool value) { SetNoEcho(value); return *this;}
/**
* <p>The description that is associate with the parameter.</p>
*/
inline const Aws::String& GetDescription() const{ return m_description; }
/**
* <p>The description that is associate with the parameter.</p>
*/
inline void SetDescription(const Aws::String& value) { m_descriptionHasBeenSet = true; m_description = value; }
/**
* <p>The description that is associate with the parameter.</p>
*/
inline void SetDescription(Aws::String&& value) { m_descriptionHasBeenSet = true; m_description = value; }
/**
* <p>The description that is associate with the parameter.</p>
*/
inline void SetDescription(const char* value) { m_descriptionHasBeenSet = true; m_description.assign(value); }
/**
* <p>The description that is associate with the parameter.</p>
*/
inline ParameterDeclaration& WithDescription(const Aws::String& value) { SetDescription(value); return *this;}
/**
* <p>The description that is associate with the parameter.</p>
*/
inline ParameterDeclaration& WithDescription(Aws::String&& value) { SetDescription(value); return *this;}
/**
* <p>The description that is associate with the parameter.</p>
*/
inline ParameterDeclaration& WithDescription(const char* value) { SetDescription(value); return *this;}
/**
* <p>The criteria that AWS CloudFormation uses to validate parameter values.</p>
*/
inline const ParameterConstraints& GetParameterConstraints() const{ return m_parameterConstraints; }
/**
* <p>The criteria that AWS CloudFormation uses to validate parameter values.</p>
*/
inline void SetParameterConstraints(const ParameterConstraints& value) { m_parameterConstraintsHasBeenSet = true; m_parameterConstraints = value; }
/**
* <p>The criteria that AWS CloudFormation uses to validate parameter values.</p>
*/
inline void SetParameterConstraints(ParameterConstraints&& value) { m_parameterConstraintsHasBeenSet = true; m_parameterConstraints = value; }
/**
* <p>The criteria that AWS CloudFormation uses to validate parameter values.</p>
*/
inline ParameterDeclaration& WithParameterConstraints(const ParameterConstraints& value) { SetParameterConstraints(value); return *this;}
/**
* <p>The criteria that AWS CloudFormation uses to validate parameter values.</p>
*/
inline ParameterDeclaration& WithParameterConstraints(ParameterConstraints&& value) { SetParameterConstraints(value); return *this;}
private:
Aws::String m_parameterKey;
bool m_parameterKeyHasBeenSet;
Aws::String m_defaultValue;
bool m_defaultValueHasBeenSet;
Aws::String m_parameterType;
bool m_parameterTypeHasBeenSet;
bool m_noEcho;
bool m_noEchoHasBeenSet;
Aws::String m_description;
bool m_descriptionHasBeenSet;
ParameterConstraints m_parameterConstraints;
bool m_parameterConstraintsHasBeenSet;
};
} // namespace Model
} // namespace CloudFormation
} // namespace Aws
|
ambasta/aws-sdk-cpp
|
aws-cpp-sdk-cloudformation/include/aws/cloudformation/model/ParameterDeclaration.h
|
C
|
apache-2.0
| 8,909
|
# Rhodophyllus simplex Romagn. SPECIES
#### Status
ACCEPTED
#### According to
Index Fungorum
#### Published in
Les Rhodophylles de Madagascar 152 (1941)
#### Original name
Rhodophyllus simplex Romagn.
### Remarks
null
|
mdoering/backbone
|
life/Fungi/Basidiomycota/Agaricomycetes/Agaricales/Entolomataceae/Rhodophyllus/Rhodophyllus simplex/README.md
|
Markdown
|
apache-2.0
| 222
|
templates
=========
templates for various projects
|
kburger/templates
|
README.md
|
Markdown
|
apache-2.0
| 52
|
/*
* Copyright 2018. AppDynamics LLC and its affiliates.
* All Rights Reserved.
* This is unpublished proprietary source code of AppDynamics LLC and its affiliates.
* The copyright notice above does not evidence any actual or intended publication of such source code.
*
*/
package com.appdynamics.connectors.vcd.VdcParams;
import javax.xml.bind.annotation.XmlElement;
public class Cpu {
private String Units;
private String Allocated;
private String Limit;
@XmlElement(name="Units")
public void setUnits(String units) {
Units = units;
}
public String getUnits() {
return Units;
}
@XmlElement(name="Allocated")
public void setAllocated(String allocated) {
Allocated = allocated;
}
public String getAllocated() {
return Allocated;
}
@XmlElement(name="Limit")
public void setLimit(String limit) {
Limit = limit;
}
public String getLimit() {
return Limit;
}
}
|
Appdynamics/vcloud-director-connector-extension
|
src/main/java/com/appdynamics/connectors/vcd/VdcParams/Cpu.java
|
Java
|
apache-2.0
| 913
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.