repo_name stringlengths 6 101 | path stringlengths 4 300 | text stringlengths 7 1.31M |
|---|---|---|
ichbinfrog/vulnerability-assessment-tool | rest-backend/src/main/java/com/sap/psr/vulas/backend/util/DigestVerifierEnumerator.java | package com.sap.psr.vulas.backend.util;
import java.util.HashSet;
import java.util.ServiceLoader;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.sap.psr.vulas.backend.model.Library;
import com.sap.psr.vulas.shared.enums.DigestAlgorithm;
import com.sap.psr.vulas.shared.enums.ProgrammingLanguage;
import com.sap.psr.vulas.shared.util.CollectionUtil;
/**
* Loops over available implementations of {@link DigestVerifier} in order to verify the digest of a given {@link Library}.
*/
public class DigestVerifierEnumerator implements DigestVerifier {
private static Logger log = LoggerFactory.getLogger(DigestVerifierEnumerator.class);
private String url = null;
/** Release timestamp of the given digest (null if unknown). */
private java.util.Calendar timestamp;
/** {@inheritDoc} */
@Override
public Set<ProgrammingLanguage> getSupportedLanguages() {
final Set<ProgrammingLanguage> l = new HashSet<ProgrammingLanguage>();
final ServiceLoader<DigestVerifier> loader = ServiceLoader.load(DigestVerifier.class);
for(DigestVerifier dv: loader) {
l.addAll(dv.getSupportedLanguages());
}
return l;
}
/** {@inheritDoc} */
@Override
public Set<DigestAlgorithm> getSupportedDigestAlgorithms() {
final Set<DigestAlgorithm> l = new HashSet<DigestAlgorithm>();
final ServiceLoader<DigestVerifier> loader = ServiceLoader.load(DigestVerifier.class);
for(DigestVerifier dv: loader) {
l.addAll(dv.getSupportedDigestAlgorithms());
}
return l;
}
/** {@inheritDoc} */
@Override
public String getVerificationUrl() { return url; }
/** {@inheritDoc} */
@Override
public java.util.Calendar getReleaseTimestamp() { return this.timestamp; }
/**
* {@inheritDoc}
*
* Loops over available implementations of {@link DigestVerifier} in order to verify the digest of a given {@link Library}.
*/
public Boolean verify(Library _lib) throws VerificationException {
if(_lib==null || _lib.getDigest()==null)
throw new IllegalArgumentException("No library or digest provided: [" + _lib + "]");
// Will only have a true or false value if either one verifier returns true, or all returned false (thus, no exception happened)
Boolean verified = null;
int exception_count = 0;
// Perform the loop
final ServiceLoader<DigestVerifier> loader = ServiceLoader.load(DigestVerifier.class);
for(DigestVerifier l: loader) {
// Check that programming language and digest alg match (in order to avoid a couple of queries)
final CollectionUtil<ProgrammingLanguage> u = new CollectionUtil<ProgrammingLanguage>();
final Set<ProgrammingLanguage> developed_in = _lib.getDevelopedIn();
if( (developed_in.isEmpty() || u.haveIntersection(developed_in, l.getSupportedLanguages())) &&
l.getSupportedDigestAlgorithms().contains(_lib.getDigestAlgorithm())) {
try {
verified = l.verify(_lib);
if(verified!=null && verified) {
this.url = l.getVerificationUrl();
this.timestamp = l.getReleaseTimestamp();
break;
}
} catch (VerificationException e) {
exception_count++;
log.error(e.getMessage());
}
}
}
// Return null if an exception happened, verified otherwise
return ( exception_count==0 ? verified : null);
}
}
|
theGreenJedi/neon | examples/cifar10.py | #!/usr/bin/env python
# ----------------------------------------------------------------------------
# Copyright 2015-2016 Nervana Systems Inc.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ----------------------------------------------------------------------------
"""
Small MLP with fully connected layers trained on CIFAR10 data.
Usage:
python examples/cifar10.py
"""
from neon import logger as neon_logger
from neon.data import ArrayIterator, load_cifar10
from neon.initializers import Uniform
from neon.layers import GeneralizedCost, Affine
from neon.models import Model
from neon.optimizers import GradientDescentMomentum
from neon.transforms import Misclassification, CrossEntropyBinary, Logistic, Rectlin
from neon.callbacks.callbacks import Callbacks
from neon.util.argparser import NeonArgparser
# parse the command line arguments
parser = NeonArgparser(__doc__)
args = parser.parse_args()
(X_train, y_train), (X_test, y_test), nclass = load_cifar10(path=args.data_dir)
train = ArrayIterator(X_train, y_train, nclass=nclass, lshape=(3, 32, 32))
test = ArrayIterator(X_test, y_test, nclass=nclass, lshape=(3, 32, 32))
init_uni = Uniform(low=-0.1, high=0.1)
opt_gdm = GradientDescentMomentum(learning_rate=0.01, momentum_coef=0.9)
# set up the model layers
layers = [Affine(nout=200, init=init_uni, activation=Rectlin()),
Affine(nout=10, init=init_uni, activation=Logistic(shortcut=True))]
cost = GeneralizedCost(costfunc=CrossEntropyBinary())
mlp = Model(layers=layers)
# configure callbacks
callbacks = Callbacks(mlp, eval_set=test, **args.callback_args)
mlp.fit(train, optimizer=opt_gdm, num_epochs=args.epochs,
cost=cost, callbacks=callbacks)
neon_logger.display('Misclassification error = %.1f%%' %
(mlp.eval(test, metric=Misclassification()) * 100))
|
VU-libtech/OLE-INST | ole-app/olefs/src/main/java/org/kuali/ole/fp/businessobject/CapitalAccountingLines.java | /*
* Copyright 2006 The Kuali Foundation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl2.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kuali.ole.fp.businessobject;
import java.util.LinkedHashMap;
import org.kuali.ole.sys.OLEPropertyConstants;
import org.kuali.rice.core.api.util.type.KualiDecimal;
import org.kuali.rice.krad.bo.TransientBusinessObjectBase;
/**
* This transient business object represents the Capital Accounting Lines
* business object that is used by the FP documents.
*/
public class CapitalAccountingLines extends TransientBusinessObjectBase {
protected String documentNumber;
protected Integer sequenceNumber; // relative to the grouping of accounting lines
protected String lineType; //tells where source or target line
protected String chartOfAccountsCode;
protected String accountNumber;
protected String financialObjectCode;
protected String subAccountNumber;
protected String financialSubObjectCode;
protected String projectCode;
protected String organizationReferenceId;
protected String financialDocumentLineDescription;
protected KualiDecimal amount;
protected boolean selectLine;
protected String distributionAmountCode;
protected boolean amountDistributed;
//need to show the percentage of the accounts.
protected KualiDecimal accountLinePercent;
/**
* Default constructor.
*/
public CapitalAccountingLines() {
}
/**
* Gets the documentNumber attribute.
*
* @return Returns the documentNumber
*/
public String getDocumentNumber() {
return documentNumber;
}
/**
* Sets the documentNumber attribute.
*
* @param documentNumber The documentNumber to set.
*/
public void setDocumentNumber(String documentNumber) {
this.documentNumber = documentNumber;
}
/**
* Gets the sequenceNumber attribute.
*
* @return Returns the sequenceNumber
*/
public Integer getSequenceNumber() {
return sequenceNumber;
}
/**
* Sets the sequenceNumber attribute.
*
* @param sequenceNumber The sequenceNumber to set.
*/
public void setSequenceNumber(Integer sequenceNumber) {
this.sequenceNumber = sequenceNumber;
}
/**
* Gets the lineType attribute.
*
* @return Returns the lineType
*/
public String getLineType() {
return lineType;
}
/**
* Sets the lineType attribute.
*
* @param lineType The lineType to set.
*/
public void setLineType(String lineType) {
this.lineType = lineType;
}
/**
* Gets the chartOfAccountsCode attribute.
*
* @return Returns the chartOfAccountsCode
*/
public String getChartOfAccountsCode() {
return chartOfAccountsCode;
}
/**
* Sets the chartOfAccountsCode attribute.
*
* @param chartOfAccountsCode The chartOfAccountsCode to set.
*/
public void setChartOfAccountsCode(String chartOfAccountsCode) {
this.chartOfAccountsCode = chartOfAccountsCode;
}
/**
* Gets the accountNumber attribute.
*
* @return Returns the accountNumber
*/
public String getAccountNumber() {
return accountNumber;
}
/**
* Sets the accountNumber attribute.
*
* @param accountNumber The accountNumber to set.
*/
public void setAccountNumber(String accountNumber) {
this.accountNumber = accountNumber;
}
/**
* Gets the financialObjectCode attribute.
*
* @return Returns the financialObjectCode
*/
public String getFinancialObjectCode() {
return financialObjectCode;
}
/**
* Sets the financialObjectCode attribute.
*
* @param financialObjectCode The financialObjectCode to set.
*/
public void setFinancialObjectCode(String financialObjectCode) {
this.financialObjectCode = financialObjectCode;
}
/**
* Gets the subAccountNumber attribute.
*
* @return Returns the subAccountNumber
*/
public String getSubAccountNumber() {
return subAccountNumber;
}
/**
* Sets the subAccountNumber attribute.
*
* @param subAccountNumber The subAccountNumber to set.
*/
public void setSubAccountNumber(String subAccountNumber) {
this.subAccountNumber = subAccountNumber;
}
/**
* Gets the financialSubObjectCode attribute.
*
* @return Returns the financialSubObjectCode
*/
public String getFinancialSubObjectCode() {
return financialSubObjectCode;
}
/**
* Sets the financialSubObjectCode attribute.
*
* @param financialSubObjectCode The financialSubObjectCode to set.
*/
public void setFinancialSubObjectCode(String financialSubObjectCode) {
this.financialSubObjectCode = financialSubObjectCode;
}
/**
* Gets the projectCode attribute.
*
* @return Returns the projectCode
*/
public String getProjectCode() {
return projectCode;
}
/**
* Sets the projectCode attribute.
*
* @param projectCode The projectCode to set.
*/
public void setProjectCode(String projectCode) {
this.projectCode = projectCode;
}
public String getOrganizationReferenceId() {
return organizationReferenceId;
}
public void setOrganizationReferenceId(String organizationReferenceId) {
this.organizationReferenceId = organizationReferenceId;
}
/**
* Gets the financialDocumentLineDescription attribute.
*
* @return Returns the financialDocumentLineDescription
*/
public String getFinancialDocumentLineDescription() {
return financialDocumentLineDescription;
}
/**
* Sets the financialDocumentLineDescription attribute.
*
* @param financialDocumentLineDescription The financialDocumentLineDescription to set.
*/
public void setFinancialDocumentLineDescription(String financialDocumentLineDescription) {
this.financialDocumentLineDescription = financialDocumentLineDescription;
}
/**
* Gets the amount attribute.
*
* @return Returns the amount
*/
public KualiDecimal getAmount() {
return amount;
}
/**
* Sets the amount attribute.
*
* @param amount The amount to set.
*/
public void setAmount(KualiDecimal amount) {
this.amount = amount;
}
/**
* Gets the selectLine attribute.
*
* @return Returns the selectLine
*/
public boolean isSelectLine() {
return selectLine;
}
/**
* Sets the selectLine attribute.
*
* @param selectLine The selectLine to set.
*/
public void setSelectLine(boolean selectLine) {
this.selectLine = selectLine;
}
/**
* Gets the distributionAmountCode attribute.
*
* @return Returns the distributionAmountCode
*/
public String getDistributionAmountCode() {
return distributionAmountCode;
}
/**
* Sets the distributionAmountCode attribute.
*
* @param distributionAmountCode The distributionAmountCode to set.
*/
public void setDistributionAmountCode(String distributionAmountCode) {
this.distributionAmountCode = distributionAmountCode;
}
/**
* Gets the amountDistributed attribute.
*
* @return Returns the amountDistributed
*/
public boolean isAmountDistributed() {
return amountDistributed;
}
/**
* Sets the amountDistributed attribute.
*
* @param amountDistributed The amountDistributed to set.
*/
public void setAmountDistributed(boolean amountDistributed) {
this.amountDistributed = amountDistributed;
}
/**
* Gets the accountLinePercent attribute.
*
* @return Returns the accountLinePercent
*/
public KualiDecimal getAccountLinePercent() {
return accountLinePercent;
}
/**
* Sets the accountLinePercent attribute.
*
* @param accountLinePercent The accountLinePercent to set.
*/
public void setAccountLinePercent(KualiDecimal accountLinePercent) {
this.accountLinePercent = accountLinePercent;
}
/**
* @see org.kuali.rice.kns.bo.BusinessObjectBase#toStringMapper()
*/
public LinkedHashMap toStringMapper_RICE20_REFACTORME() {
LinkedHashMap m = new LinkedHashMap();
m.put(OLEPropertyConstants.DOCUMENT_NUMBER, this.getDocumentNumber());
m.put(OLEPropertyConstants.SEQUENCE_NUMBER, this.getSequenceNumber());
m.put(OLEPropertyConstants.LINE_TYPE, this.getLineType());
m.put(OLEPropertyConstants.CHART_OF_ACCOUNTS_CODE, this.getChartOfAccountsCode());
m.put(OLEPropertyConstants.ACCOUNT_NUMBER, this.getAccountNumber());
m.put(OLEPropertyConstants.FINANCIAL_OBJECT_CODE, this.getFinancialObjectCode());
m.put(OLEPropertyConstants.SUB_ACCOUNT_NUMBER, this.getSubAccountNumber());
m.put(OLEPropertyConstants.FINANCIAL_SUB_OBJECT_CODE, this.getFinancialSubObjectCode());
m.put(OLEPropertyConstants.PROJECT_CODE, this.getProjectCode());
// m.put(OLEPropertyConstants.FINANCIAL_DOCUMENT_LINE_DESCRIPTION, this.getFinancialDocumentLineDescription());
// m.put(OLEPropertyConstants.AMOUNT, this.getAmount());
// m.put(OLEPropertyConstants.SELECT_LINE, this.isSelectLine());
// m.put(OLEPropertyConstants.DISTRIBUTION_AMOUNT_CODE, this.getDistributionAmountCode());
// m.put(OLEPropertyConstants.AMOUNT_DISTRIBUTED, this.isAmountDistributed());
// m.put(OLEPropertyConstants.ACCOUNT_LINE_PERCENT, this.getAccountLinePercent());
return m;
}
}
|
guillempg/spring-boot-oracleXE | src/main/java/com/example/springjpaoracle/model/Teacher.java | package com.example.springjpaoracle.model;
import lombok.*;
import lombok.experimental.Accessors;
import javax.persistence.*;
import java.util.List;
@Entity
@EqualsAndHashCode(onlyExplicitlyIncluded = true, callSuper = true)
@Getter
@Setter
@RequiredArgsConstructor
@ToString(callSuper = true)
@Accessors(chain = true)
@DiscriminatorValue("Teacher")
public class Teacher extends Person
{
@ManyToMany(cascade = CascadeType.REMOVE)
@JoinTable(
name = "TEACHER_COURSE_ASSIGNATIONS",
joinColumns = @JoinColumn(name = "TEACHER_ID", referencedColumnName = "ID"),
inverseJoinColumns = @JoinColumn(name = "COURSE_ID", referencedColumnName = "ID")
)
private List<Course> courses;
@OneToMany(mappedBy = "teacher", cascade = {CascadeType.REMOVE, CascadeType.PERSIST})
private List<TeacherAssignation> assignations;
}
|
devlights/try-python | trypython/stdlib/weakref_/weakref02.py | <reponame>devlights/try-python<gh_stars>1-10
# coding: utf-8
"""
weakref モジュールについてのサンプルです。
弱参照がオブジェクトの __weakref__ に設定されることを確認するサンプルです。
"""
import weakref
from trypython.common.commoncls import SampleBase
from trypython.common.commonfunc import pr
# noinspection PyUnusedLocal,SpellCheckingInspection,PyUnresolvedReferences
class Sample(SampleBase):
def exec(self):
# ------------------------------------------------
# 弱参照は、オブジェクトの
# __weakref__
# に設定される。
#
# ただし、この属性が存在するのは
# ユーザ定義クラス
# の場合のみ。
# ------------------------------------------------
set01 = {1, 2}
wref = weakref.ref(set01)
pr('__weakref__ exists?', hasattr(set01, '__weakref__'))
a = A()
wref = weakref.ref(a)
pr('__weakref__ exists?', hasattr(a, '__weakref__'))
pr('a.__weakref__ is wref', a.__weakref__ is wref)
# ------------------------------------------------
# ユーザ定義クラスで弱参照をサポートするためには
# __weakref__ 属性が必要となる。__slots__ 属性を
# つかって、オブジェクトのメモリサイズを最適化している
# 場合、この属性を含めていないと弱参照が作れない。
# ------------------------------------------------
b = NotContainsWeakrefAttr(100)
try:
bref = weakref.ref(b)
except TypeError as e:
pr('NotContainsWeakrefAttr', e)
c = ContainsWeakrefAttr(100)
cref = weakref.ref(c)
print(cref)
class A:
pass
class NotContainsWeakrefAttr:
__slots__ = ('val',)
def __init__(self, val):
self.val = val
class ContainsWeakrefAttr:
__slots__ = ('val', '__weakref__',)
def __init__(self, val):
self.val = val
def go():
obj = Sample()
obj.exec()
|
slife518/Giantbaby_sv | node_modules/sugar/dist/locales/pl.js | /*
* Polish locale definition.
* See the readme for customization and more information.
* To set this locale globally:
*
* Sugar.Date.setLocale('pl')
*
*/
Sugar.Date.addLocale('pl', {
'plural': true,
'units': 'milisekund:a|y|,sekund:a|y|,minut:a|y|,godzin:a|y|,dzień|dni|dni,tydzień|tygodnie|tygodni,miesiąc|miesiące|miesięcy,rok|lata|lat',
'months': 'sty:cznia||czeń,lut:ego||y,mar:ca||zec,kwi:etnia||ecień,maj:a|,cze:rwca||rwiec,lip:ca||iec,sie:rpnia||rpień,wrz:eśnia||esień,paź:dziernika||dziernik,lis:topada||topad,gru:dnia||dzień',
'weekdays': 'nie:dziela||dzielę,pon:iedziałek|,wt:orek|,śr:oda||odę,czw:artek|,piątek|pt,sobota|sb|sobotę',
'numerals': 'zero,jeden|jedną,dwa|dwie,trzy,cztery,pięć,sześć,siedem,osiem,dziewięć,dziesięć',
'tokens': 'w|we,roku',
'short': '{dd}.{MM}.{yyyy}',
'medium': '{d} {month} {yyyy}',
'long': '{d} {month} {yyyy} {time}',
'full' : '{weekday}, {d} {month} {yyyy} {time}',
'stamp': '{dow} {d} {mon} {yyyy} {time}',
'time': '{H}:{mm}',
'timeMarkers': 'o',
'ampm': 'am,pm',
'modifiers': [
{ 'name': 'day', 'src': 'przedwczoraj', 'value': -2 },
{ 'name': 'day', 'src': 'wczoraj', 'value': -1 },
{ 'name': 'day', 'src': 'dzisiaj|dziś', 'value': 0 },
{ 'name': 'day', 'src': 'jutro', 'value': 1 },
{ 'name': 'day', 'src': 'pojutrze', 'value': 2 },
{ 'name': 'sign', 'src': 'temu|przed', 'value': -1 },
{ 'name': 'sign', 'src': 'za', 'value': 1 },
{ 'name': 'shift', 'src': 'zeszły|zeszła|ostatni|ostatnia', 'value': -1 },
{ 'name': 'shift', 'src': 'następny|następna|następnego|przyszły|przyszła|przyszłego', 'value': 1 }
],
'relative': function (num, unit, ms, format) {
// special cases for relative days
var DAY = 4;
if (unit === DAY) {
if (num === 1 && format === 'past') return 'wczoraj';
if (num === 1 && format === 'future') return 'jutro';
if (num === 2 && format === 'past') return 'przedwczoraj';
if (num === 2 && format === 'future') return 'pojutrze';
}
var mult;
var last = +num.toFixed(0).slice(-1);
var last2 = +num.toFixed(0).slice(-2);
switch (true) {
case num === 1: mult = 0; break;
case last2 >= 12 && last2 <= 14: mult = 2; break;
case last >= 2 && last <= 4: mult = 1; break;
default: mult = 2;
}
var text = this['units'][(mult * 8) + unit];
var prefix = num + ' ';
// changing to accusative case for 'past' and 'future' formats
// (only singular feminine unit words are different in accusative, each of which ends with 'a')
if ((format === 'past' || format === 'future') && num === 1) {
text = text.replace(/a$/, 'ę');
}
text = prefix + text;
switch (format) {
case 'duration': return text;
case 'past': return text + ' temu';
case 'future': return 'za ' + text;
}
},
'parse': [
'{num} {unit} {sign}',
'{sign} {num} {unit}',
'{months} {year?}',
'{shift} {unit:5-7}',
'{0} {shift?} {weekday}'
],
'timeFrontParse': [
'{day|weekday}',
'{date} {months} {year?} {1?}',
'{0?} {shift?} {weekday}'
]
});
|
Biolunar/linux_syscall | src/timer_gettime.c | <filename>src/timer_gettime.c
#include <liblinux/linux.h>
extern inline linux_error_t linux_timer_gettime(linux_timer_t timer_id, struct linux_itimerspec* setting);
|
FYPYTHON/WBMSBT | database/tbl_browsing_history.py | <gh_stars>1-10
# coding=utf-8
from sqlalchemy import Column, String, Integer , DateTime
from database import table_base
from database.db_config import ModelBase
# web访问历史记录
class TblBrowsingHistory(ModelBase, table_base.TableBase):
__tablename__ = 'tbl_browsing_history'
id = Column(Integer, unique=True, primary_key=True)
user_ip = Column(String(100)) # 访问ip
user_account = Column(String(100)) # 登录用户
uri = Column(String(255)) # 访问地址
request_method = Column(String(100)) # post/get
status = Column(String(100)) # 访问状态码
browsing_date = Column(String(20)) # 访问日期
browsing_time = Column(String(20)) # 访问时间
user_agent = Column(String(200)) # 用户代理
def __repr__(self):
return "%s<id=%s, ip=%s>" % (self.__class__.__name__, self.id, self.ip)
|
jmaya371/Boot-usb | apps/usb_device_hid_bootloader/bootloader/firmware/src/config/sam_l22_xpro/usb/usb_device_hid.h | <filename>apps/usb_device_hid_bootloader/bootloader/firmware/src/config/sam_l22_xpro/usb/usb_device_hid.h<gh_stars>1-10
/*******************************************************************************
USB HID Function Driver
Company:
Microchip Technology Inc.
File Name:
usb_hid_function_driver.h
Summary:
USB HID Function Driver
Description:
This file contains the API definitions for the USB Device HID Function
Driver. The application should include this file if it needs to use the HID
Function Driver API.
*******************************************************************************/
//DOM-IGNORE-BEGIN
/*******************************************************************************
* Copyright (C) 2018 Microchip Technology Inc. and its subsidiaries.
*
* Subject to your compliance with these terms, you may use Microchip software
* and any derivatives exclusively with Microchip products. It is your
* responsibility to comply with third party license terms applicable to your
* use of third party software (including open source software) that may
* accompany Microchip software.
*
* THIS SOFTWARE IS SUPPLIED BY MICROCHIP "AS IS". NO WARRANTIES, WHETHER
* EXPRESS, IMPLIED OR STATUTORY, APPLY TO THIS SOFTWARE, INCLUDING ANY IMPLIED
* WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY, AND FITNESS FOR A
* PARTICULAR PURPOSE.
*
* IN NO EVENT WILL MICROCHIP BE LIABLE FOR ANY INDIRECT, SPECIAL, PUNITIVE,
* INCIDENTAL OR CONSEQUENTIAL LOSS, DAMAGE, COST OR EXPENSE OF ANY KIND
* WHATSOEVER RELATED TO THE SOFTWARE, HOWEVER CAUSED, EVEN IF MICROCHIP HAS
* BEEN ADVISED OF THE POSSIBILITY OR THE DAMAGES ARE FORESEEABLE. TO THE
* FULLEST EXTENT ALLOWED BY LAW, MICROCHIP'S TOTAL LIABILITY ON ALL CLAIMS IN
* ANY WAY RELATED TO THIS SOFTWARE WILL NOT EXCEED THE AMOUNT OF FEES, IF ANY,
* THAT YOU HAVE PAID DIRECTLY TO MICROCHIP FOR THIS SOFTWARE.
*******************************************************************************/
//DOM-IGNORE-END
#ifndef _USB_DEVICE_HID_H_
#define _USB_DEVICE_HID_H_
// *****************************************************************************
// *****************************************************************************
// Section: Included Files
// *****************************************************************************
// *****************************************************************************
/* This section lists the other files that are included in this file.
*/
#include <stdint.h>
#include <stdbool.h>
#include "configuration.h"
#include "system/system_common.h"
#include "usb_common.h"
#include "usb_chapter_9.h"
#include "usb_device.h"
#include "usb/src/usb_device_function_driver.h"
#include "usb_hid.h"
// DOM-IGNORE-BEGIN
#ifdef __cplusplus // Provide C++ Compatibility
extern "C" {
#endif
// DOM-IGNORE-END
// *****************************************************************************
// *****************************************************************************
// Section: Data Types
// *****************************************************************************
// *****************************************************************************
// *****************************************************************************
/* USB Device HID Function Driver Index Constants
Summary:
USB Device HID Function Driver Index Constants
Description:
This constants can be used by the application to specify HID function
driver instance indexes.
Remarks:
None.
*/
#define USB_DEVICE_HID_INDEX_0 0
#define USB_DEVICE_HID_INDEX_1 1
#define USB_DEVICE_HID_INDEX_2 2
#define USB_DEVICE_HID_INDEX_3 3
#define USB_DEVICE_HID_INDEX_4 4
#define USB_DEVICE_HID_INDEX_5 5
#define USB_DEVICE_HID_INDEX_6 6
#define USB_DEVICE_HID_INDEX_7 7
// *****************************************************************************
/* USB Device HID Driver Index Numbers
Summary:
USB device HID Function Driver Index.
Description:
This uniquely identifies a HID Function Driver instance.
Remarks:
None.
*/
typedef uintptr_t USB_DEVICE_HID_INDEX;
// *****************************************************************************
/* USB Device HID Function Driver Transfer Handle Definition
Summary:
USB Device HID Function Driver Transfer Handle Definition.
Description:
This definition defines a USB Device HID Function Driver Transfer Handle. A
Transfer Handle is owned by the application but its value is modified by the
USB_DEVICE_HID_ReportSend and USB_DEVICE_HID_ReportReceive functions. The
transfer handle is valid for the life time of the transfer and expires when
the transfer related event has occurred.
Remarks:
None.
*/
typedef uintptr_t USB_DEVICE_HID_TRANSFER_HANDLE;
// *****************************************************************************
/* USB Device HID Function Driver Invalid Transfer Handle Definition
Summary:
USB Device HID Function Driver Invalid Transfer Handle Definition.
Description:
This definition defines a USB Device HID Function Driver Invalid Transfer
Handle. A Invalid Transfer Handle is returned by the
USB_DEVICE_HID_ReportReceive and USB_DEVICE_HID_ReportSend functions
when the request was not successful.
Remarks:
None.
*/
#define USB_DEVICE_HID_TRANSFER_HANDLE_INVALID /*DOM-IGNORE-BEGIN*/((USB_DEVICE_HID_TRANSFER_HANDLE)(-1))/*DOM-IGNORE-END*/
// *****************************************************************************
/* USB Device HID Function Driver USB Device HID Result enumeration.
Summary:
USB Device HID Function Driver USB Device HID Result enumeration.
Description:
This enumeration lists the possible USB Device HID Function Driver operation
results. These values USB Device HID Library functions.
Remarks:
None.
*/
typedef enum
{
/* The operation was successful */
USB_DEVICE_HID_RESULT_OK
/*DOM-IGNORE-BEGIN*/ = USB_ERROR_NONE /*DOM-IGNORE-END*/,
/* The transfer queue is full. No new transfers can be
* scheduled */
USB_DEVICE_HID_RESULT_ERROR_TRANSFER_QUEUE_FULL
/*DOM-IGNORE-BEGIN*/ = USB_ERROR_IRP_QUEUE_FULL /*DOM-IGNORE-END*/,
/* The specified instance is not configured yet */
USB_DEVICE_HID_RESULT_ERROR_INSTANCE_NOT_CONFIGURED
/*DOM-IGNORE-BEGIN*/ = USB_ERROR_ENDPOINT_NOT_CONFIGURED /*DOM-IGNORE-END*/,
/* The specified instance is not provisioned in the system */
USB_DEVICE_HID_RESULT_ERROR_INSTANCE_INVALID
/* DOM-IGNORE-BEGIN */ = USB_ERROR_DEVICE_FUNCTION_INSTANCE_INVALID /* DOM-IGNORE-END */,
/* One or more parameter/s of the function is invalid */
USB_DEVICE_HID_RESULT_ERROR_PARAMETER_INVALID =
/*DOM-IGNORE-BEGIN*/ USB_ERROR_PARAMETER_INVALID /*DOM-IGNORE-END*/,
/* Transfer terminated because host halted the endpoint */
USB_DEVICE_HID_RESULT_ERROR_ENDPOINT_HALTED
/* DOM-IGNORE-BEGIN */ = USB_ERROR_ENDPOINT_HALTED /* DOM-IGNORE-END */,
/* Transfer terminated by host because of a stall clear */
USB_DEVICE_HID_RESULT_ERROR_TERMINATED_BY_HOST
/* DOM-IGNORE-BEGIN */ = USB_ERROR_TRANSFER_TERMINATED_BY_HOST /* DOM-IGNORE-END */,
/* General Error */
USB_DEVICE_HID_RESULT_ERROR
} USB_DEVICE_HID_RESULT;
// *****************************************************************************
/* USB Device HID Function Driver Events
Summary:
USB Device HID Function Driver Events
Description:
These events are specific to the USB Device HID Function Driver instance.
Each event description contains details about the parameters passed with
event. The contents of pData depends on the generated event.
Events that are associated with the HID Function Driver Specific Control
Transfers require application response. The application should respond to
these events by using the USB_DEVICE_ControlReceive,
USB_DEVICE_ControlSend and USB_DEVICE_ControlStatus functions.
Calling the USB_DEVICE_ControlStatus function with a
USB_DEVICE_CONTROL_STATUS_ERROR will stall the control transfer request.
The application would do this if the control transfer request is not
supported. Calling the USB_DEVICE_ControlStatus function with a
USB_DEVICE_CONTROL_STATUS_OK will complete the status stage of the control
transfer request. The application would do this if the control transfer
request is supported
The following code snippet shows an example of a possible event handling
scheme.
<code>
// This code example shows all HID Function Driver events and a possible
// scheme for handling these events. In this example event responses are not
// deferred.
USB_DEVICE_HID_EVENT_RESPONSE USB_AppHIDEventHandler
(
USB_DEVICE_HID_INDEX instanceIndex,
USB_DEVICE_HID_EVENT event,
void * pData,
uintptr_t userData
)
{
uint8_t currentIdleRate;
uint8_t someHIDReport[128];
uint8_t someHIDDescriptor[128];
USB_DEVICE_HANDLE usbDeviceHandle;
USB_HID_PROTOCOL_CODE currentProtocol;
USB_DEVICE_HID_EVENT_DATA_GET_REPORT * getReportEventData;
USB_DEVICE_HID_EVENT_DATA_SET_IDLE * setIdleEventData;
USB_DEVICE_HID_EVENT_DATA_SET_DESCRIPTOR * setDescriptorEventData;
USB_DEVICE_HID_EVENT_DATA_SET_REPORT * setReportEventData;
switch(event)
{
case USB_DEVICE_HID_EVENT_GET_REPORT:
// In this case, pData should be interpreted as a
// USB_DEVICE_HID_EVENT_DATA_GET_REPORT pointer. The application
// must send the requested report by using the
// USB_DEVICE_ControlSend() function.
getReportEventData = (USB_DEVICE_HID_EVENT_DATA_GET_REPORT *)pData;
USB_DEVICE_ControlSend(usbDeviceHandle, someHIDReport, getReportEventData->reportLength);
break;
case USB_DEVICE_HID_EVENT_GET_PROTOCOL:
// In this case, pData will be NULL. The application
// must send the current protocol to the host by using
// the USB_DEVICE_ControlSend() function.
USB_DEVICE_ControlSend(usbDeviceHandle, ¤tProtocol, sizeof(USB_HID_PROTOCOL_CODE));
break;
case USB_DEVICE_HID_EVENT_GET_IDLE:
// In this case, pData will be a
// USB_DEVICE_HID_EVENT_DATA_GET_IDLE pointer type containing the
// ID of the report for which the idle rate is being requested.
// The application must send the current idle rate to the host
// by using the USB_DEVICE_ControlSend() function.
USB_DEVICE_ControlSend(usbDeviceHandle, ¤tIdleRate, 1);
break;
case USB_DEVICE_HID_EVENT_SET_REPORT:
// In this case, pData should be interpreted as a
// USB_DEVICE_HID_EVENT_DATA_SET_REPORT type pointer. The
// application can analyze the request and then obtain the
// report by using the USB_DEVICE_ControlReceive() function.
setReportEventData = (USB_DEVICE_HID_EVENT_DATA_SET_REPORT *)pData;
USB_DEVICE_ControlReceive(deviceHandle, someHIDReport, setReportEventData->reportLength);
break;
case USB_DEVICE_HID_EVENT_SET_PROTOCOL:
// In this case, pData should be interpreted as a
// USB_DEVICE_HID_EVENT_DATA_SET_PROTOCOL type pointer. The application can
// analyze the data and decide to stall or accept the setting.
// This shows an example of accepting the protocol setting.
USB_DEVICE_ControlStatus(deviceHandle, USB_DEVICE_CONTROL_STATUS_OK);
break;
case USB_DEVICE_HID_EVENT_SET_IDLE:
// In this case, pData should be interpreted as a
// USB_DEVICE_HID_EVENT_DATA_SET_IDLE type pointer. The
// application can analyze the data and decide to stall
// or accept the setting. This shows an example of accepting
// the protocol setting.
setIdleEventData = (USB_DEVICE_HID_EVENT_DATA_SET_IDLE *)pData;
USB_DEVICE_ControlStatus(deviceHandle, USB_DEVICE_CONTROL_STATUS_OK);
break;
case USB_DEVICE_HID_EVENT_CONTROL_TRANSFER_DATA_RECEIVED:
// In this case, control transfer data was received. The
// application can inspect that data and then stall the
// handshake stage of the control transfer or accept it
// (as shown here).
USB_DEVICE_ControlStatus(deviceHandle, USB_DEVICE_CONTROL_STATUS_OK);
break;
case USB_DEVICE_HID_EVENT_CONTROL_TRANSFER_DATA_SENT:
// This means that control transfer data was sent. The
// application would typically acknowledge the handshake
// stage of the control transfer.
break;
case USB_DEVICE_HID_EVENT_CONTROL_TRANSFER_ABORTED:
// This is an indication only event. The application must
// reset any HID control transfer related tasks when it receives
// this event.
break;
case USB_DEVICE_HID_EVENT_REPORT_RECEIVED:
// This means a HID report receive request has completed.
// The pData member should be interpreted as a
// USB_DEVICE_HID_EVENT_DATA_REPORT_RECEIVED pointer type.
break;
case USB_DEVICE_HID_EVENT_REPORT_SENT:
// This means a HID report send request has completed.
// The pData member should be interpreted as a
// USB_DEVICE_HID_EVENT_DATA_REPORT_SENT pointer type.
break;
}
return(USB_DEVICE_HID_EVENT_RESPONSE_NONE);
}
</code>
Remarks:
Some of the events allow the application to defer responses. This allows the
application some time to obtain the response data rather than having to
respond to the event immediately. Note that a USB host will typically wait
for event response for a finite time duration before timing out and
canceling the event and associated transactions. Even when deferring
response, the application must respond promptly if such timeouts have to be
avoided.
*/
typedef enum
{
/* This event occurs when the host issues a GET REPORT command. This is a
HID class specific control transfer related event. The application must
interpret the pData parameter as USB_DEVICE_HID_EVENT_DATA_GET_REPORT
pointer type. If the report request is supported, the application must
send the report to the host by using the USB_DEVICE_ControlSend
function either in the event handler or after the event handler routine
has returned. The application can track the completion of the request by
using the USB_DEVICE_HID_EVENT_CONTROL_TRANSFER_DATA_SENT event. If the
report request is not supported, the application must stall the request
by calling the USB_DEVICE_ControlStatus function with a
USB_DEVICE_CONTROL_STATUS_ERROR flag. */
USB_DEVICE_HID_EVENT_GET_REPORT,
/* This event occurs when the host issues a GET IDLE command. This is a HID
class specific control transfer related event. The pData parameter will
be a USB_DEVICE_HID_EVENT_DATA_GET_IDLE pointer type containing the ID of
the report for which the idle parameter is requested. If the request is
supported, the application must send the idle rate to the host by calling
the USB_DEVICE_ControlSend function. This function can be called either
in the event handler or after the event handler routine has returned. The
application can track the completion of the request by using the
USB_DEVICE_HID_EVENT_CONTROL_TRANSFER_DATA_SENT event. If the request is
not supported, the application must stall the request by calling the
USB_DEVICE_ControlStatus function with a
USB_DEVICE_CONTROL_STATUS_ERROR flag. */
USB_DEVICE_HID_EVENT_GET_IDLE,
/* This event occurs when the host issues a GET PROTOCOL command. This is a
HID class specific control transfer related event. The pData parameter
will be NULL. If the request is supported, the application must send a
USB_HID_PROTOCOL_CODE data type object, containing the current protocol,
to the host by calling the USB_DEVICE_ControlSend function. This
function can be called either in the event handler or after the event
handler routine has returned. The application can track the completion of
the request by using the USB_DEVICE_HID_EVENT_CONTROL_TRANSFER_DATA_SENT
event. If the request is not supported, the application must stall the
request by calling the USB_DEVICE_ControlStatus function with a
USB_DEVICE_CONTROL_STATUS_ERROR flag. */
USB_DEVICE_HID_EVENT_GET_PROTOCOL,
/* This event occurs when the host issues a SET REPORT command. This is a
HID class specific control transfer related event. The application must
interpret the pData parameter as a USB_DEVICE_HID_EVENT_DATA_SET_REPORT
pointer type. If the report request is supported, the application must
provide a buffer, to receive the report, to the host by calling the
USB_DEVICE_ControlReceive function either in the event handler or after
the event handler routine has returned. The application can track the
completion of the request by using the
USB_DEVICE_HID_EVENT_CONTROL_TRANSFER_DATA_RECEIVED event. If the report
request is not supported, the application must stall the request by
calling the USB_DEVICE_ControlStatus function with a
USB_DEVICE_CONTROL_STATUS_ERROR flag. */
USB_DEVICE_HID_EVENT_SET_REPORT,
/* This event occurs when the host issues a SET IDLE command. This is a
HID class specific control transfer related event. The pData parameter
will be USB_DEVICE_HID_EVENT_DATA_SET_IDLE pointer type. The application
can analyze the idle duration and acknowledge or reject the setting by
calling the USB_DEVICE_ControlStatus function. This function can be
called in the event handler or after the event handler exits. If
application can reject the request by calling the
USB_DEVICE_ControlStatus function with a
USB_DEVICE_CONTROL_STATUS_ERROR flag. It can accept the request by
calling this function with USB_DEVICE_CONTROL_STATUS_OK flag. */
USB_DEVICE_HID_EVENT_SET_IDLE,
/* This event occurs when the host issues a SET PROTOCOL command. This is a
HID class specific control transfer related event. The pData parameter
will be a pointer to a USB_DEVICE_HID_EVENT_DATA_SET_PROTOCOL data type.
If the request is supported, the application must acknowledge the request
by calling the USB_DEVICE_ControlStatus function with a
USB_DEVICE_CONTROL_STATUS_OK flag. If the request is not supported, the
application must stall the request by calling the
USB_DEVICE_ControlStatus function with a
USB_DEVICE_CONTROL_STATUS_ERROR flag. */
USB_DEVICE_HID_EVENT_SET_PROTOCOL,
/* This event indicates that USB_DEVICE_HID_ReportSend function
completed a report transfer on interrupt endpoint from host to device.
The pData parameter will be a USB_DEVICE_HID_EVENT_DATA_REPORT_SENT type.
*/
USB_DEVICE_HID_EVENT_REPORT_SENT,
/* This event indicates that USB_DEVICE_HID_ReportReceive function
completed a report transfer on interrupt endpoint from device to host.
The pData parameter will be a USB_DEVICE_HID_EVENT_DATA_REPORT_RECEIVED
type */
USB_DEVICE_HID_EVENT_REPORT_RECEIVED,
/* This event occurs when the data stage of a control write transfer has
completed. This happens after the application uses the
USB_DEVICE_ControlReceive function to respond to a HID Function Driver
Control Transfer Event that requires data to be received from the host.
The pData parameter will be NULL. The application should call the
USB_DEVICE_ControlStatus function with the USB_DEVICE_CONTROL_STATUS_OK
flag if the received data is acceptable or should call this function with
USB_DEVICE_CONTROL_STATUS_ERROR flag if the received data needs to be
rejected.*/
USB_DEVICE_HID_EVENT_CONTROL_TRANSFER_DATA_RECEIVED
/*DOM-IGNORE-BEGIN*/ = USB_DEVICE_EVENT_CONTROL_TRANSFER_DATA_RECEIVED /*DOM-IGNORE-END*/,
/* This event occurs when the data stage of a control read transfer has
completed. This happens after the application uses the
USB_DEVICE_ControlSend function to respond to a HID Function Driver
Control Transfer Event that requires data to be sent to the host. The
pData parameter will be NULL */
USB_DEVICE_HID_EVENT_CONTROL_TRANSFER_DATA_SENT
/*DOM-IGNORE-BEGIN*/ = USB_DEVICE_EVENT_CONTROL_TRANSFER_DATA_SENT /*DOM-IGNORE-END*/,
/* This event occurs when an ongoing control transfer was aborted.
The application must stop any pending control transfer related
activities.
*/
USB_DEVICE_HID_EVENT_CONTROL_TRANSFER_ABORTED
/*DOM-IGNORE-BEGIN*/ = USB_DEVICE_EVENT_CONTROL_TRANSFER_ABORTED /*DOM-IGNORE-END*/,
} USB_DEVICE_HID_EVENT;
// *****************************************************************************
/* USB Device HID Get Idle Event Data
Summary:
USB Device HID Get Idle Event Data Type.
Description:
This defines the data type of the data generated to the HID event
handler on a USB_DEVICE_HID_EVENT_GET_IDLE event.
Remarks:
None.
*/
typedef struct
{
/* The protocol code */
uint8_t reportID;
} USB_DEVICE_HID_EVENT_DATA_GET_IDLE;
// *****************************************************************************
/* USB Device HID Set Protocol Event Data
Summary:
USB Device HID Set Protocol Event Data Type.
Description:
This defines the data type of the data generated to the HID event
handler on a USB_DEVICE_HID_EVENT_SET_PROTOCOL event.
Remarks:
None.
*/
typedef struct
{
/* The protocol code */
USB_HID_PROTOCOL_CODE protocolCode;
} USB_DEVICE_HID_EVENT_DATA_SET_PROTOCOL;
// *****************************************************************************
/* USB Device HID Report Sent Event Data Type.
Summary:
USB Device HID Report Sent Event Data Type.
Description:
This defines the data type of the data generated to the HID event
handler on a USB_DEVICE_HID_EVENT_REPORT_SENT event.
Remarks:
None.
*/
typedef struct
{
/* Transfer handle */
USB_DEVICE_HID_TRANSFER_HANDLE handle;
/* Report size transmitted */
size_t length;
/* Completion status of the transfer */
USB_DEVICE_HID_RESULT status;
} USB_DEVICE_HID_EVENT_DATA_REPORT_SENT;
// *****************************************************************************
/* USB Device HID Report Received Event Data Type.
Summary:
USB Device HID Report Received Event Data Type.
Description:
This defines the data type of the data generated to the HID event
handler on a USB_DEVICE_HID_EVENT_REPORT_RECEIVED event.
Remarks:
None.
*/
typedef struct
{
/* Transfer handle */
USB_DEVICE_HID_TRANSFER_HANDLE handle;
/* Report size received */
size_t length;
/* Completion status of the transfer */
USB_DEVICE_HID_RESULT status;
} USB_DEVICE_HID_EVENT_DATA_REPORT_RECEIVED;
// *****************************************************************************
/* USB Device HID Set Idle Event Data Type.
Summary:
USB Device HID Set Idle Event Data Type.
Description:
This defines the data type of the data generated to the HID event
handler on a USB_DEVICE_HID_EVENT_SET_IDLE event.
Remarks:
None.
*/
typedef struct
{
/* Idle duration */
uint8_t duration;
/* Report ID*/
uint8_t reportID;
} USB_DEVICE_HID_EVENT_DATA_SET_IDLE;
// *****************************************************************************
/* USB Device HID Get Report Event Data Type.
Summary:
USB Device HID Get Report Event Data Type.
Description:
This defines the data type of the data generated to the HID event
handler on a USB_DEVICE_HID_EVENT_GET_REPORT event.
Remarks:
None.
*/
typedef struct
{
/* Report type */
uint8_t reportType;
/* Report ID */
uint8_t reportID;
/* Report Length*/
uint16_t reportLength;
} USB_DEVICE_HID_EVENT_DATA_GET_REPORT;
// *****************************************************************************
/* USB Device HID Set Report Event Data Type.
Summary:
USB Device HID Set Report Event Data Type.
Description:
This defines the data type of the data generated to the HID event
handler on a USB_DEVICE_HID_EVENT_SET_REPORT event.
Remarks:
None.
*/
typedef struct
{
/* Report type */
uint8_t reportType;
/* Report ID */
uint8_t reportID;
/* Report Length */
uint16_t reportLength;
} USB_DEVICE_HID_EVENT_DATA_SET_REPORT;
// *****************************************************************************
/* USB Device HID Function Driver Event Handler Response Type
Summary:
USB Device HID Function Driver Event Callback Response Type
Description:
This is the return type of the HID Function Driver event handler.
Remarks:
None.
*/
typedef void USB_DEVICE_HID_EVENT_RESPONSE;
// *****************************************************************************
/* USB Device HID Event Handler Function Pointer Type.
Summary:
USB Device HID Event Handler Function Pointer Type.
Description:
This data type defines the required function signature of the USB Device HID
Function Driver event handling callback function. The application must
register a pointer to a HID Function Driver events handling function whose
function signature (parameter and return value types) match the types
specified by this function pointer in order to receive event call backs from
the HID Function Driver. The function driver will invoke this function with
event relevant parameters. The description of the event handler function
parameters is given here.
instanceIndex - Instance index of the HID Function Driver that
generated the event.
event - Type of event generated.
pData - This parameter should be type casted to a event
specific pointer type based on the event that has
occurred. Refer to the USB_DEVICE_HID_EVENT
enumeration description for more details.
context - Value identifying the context of the application
that registered the event handling function.
Remarks:
None.
*/
typedef USB_DEVICE_HID_EVENT_RESPONSE (*USB_DEVICE_HID_EVENT_HANDLER)
(
USB_DEVICE_HID_INDEX instanceIndex,
USB_DEVICE_HID_EVENT event,
void * pData,
uintptr_t context
);
// *****************************************************************************
// *****************************************************************************
// Section: Constants
// *****************************************************************************
// *****************************************************************************
// *****************************************************************************
/* USB Device HID Function Driver Event Handler Response None
Summary:
USB Device HID Function Driver Event Handler Response Type None.
Description:
This is the definition of the HID Function Driver Event Handler Response
Type none.
Remarks:
Intentionally defined to be empty.
*/
#define USB_DEVICE_HID_EVENT_RESPONSE_NONE
// *****************************************************************************
// *****************************************************************************
// Section: API definitions
// *****************************************************************************
// *****************************************************************************
// *****************************************************************************
/* Function:
USB_DEVICE_HID_RESULT USB_DEVICE_HID_EventHandlerSet
(
USB_DEVICE_HID_INDEX instance
USB_DEVICE_HID_EVENT_HANDLER eventHandler
uintptr_t context
);
Summary:
This function registers a event handler for the specified HID function
driver instance.
Description:
This function registers a event handler for the specified HID function
driver instance. This function should be called by the client when it
receives a SET CONFIGURATION event from the device layer. A event handler
must be registered for function driver to respond to function driver
specific commands. If the event handler is not registered, the device
layer will stall function driver specific commands and the USB device
may not function.
Precondition:
This function should be called when the function driver has been initialized
as a result of a set configuration.
Parameters:
instance - Instance of the HID Function Driver.
eventHandler - A pointer to event handler function.
context - Application specific context that is returned in the
event handler.
Returns:
USB_DEVICE_HID_RESULT_OK - The operation was successful
USB_DEVICE_HID_RESULT_ERROR_INSTANCE_INVALID - The specified instance does
not exist.
USB_DEVICE_HID_RESULT_ERROR_PARAMETER_INVALID - The eventHandler parameter is
NULL
Example:
<code>
// This code snippet shows an example registering an event handler. Here
// the application specifies the context parameter as a pointer to an
// application object (appObject) that should be associated with this
// instance of the HID function driver.
USB_DEVICE_HID_RESULT result;
USB_DEVICE_HID_EVENT_RESPONSE APP_USBDeviceHIDEventHandler
(
USB_DEVICE_HID_INDEX instanceIndex,
USB_DEVICE_HID_EVENT event,
void * pData,
uintptr_t context
)
{
// Event Handling comes here
switch(event)
{
...
}
return(USB_DEVICE_HID_EVENT_RESPONSE_NONE);
}
result = USB_DEVICE_HID_EventHandlerSet (0, &APP_EventHandler, (uintptr_t) &appObject);
if(USB_DEVICE_HID_RESULT_OK != result)
{
SYS_ASSERT ( false , "Error while registering event handler" );
}
</code>
Remarks:
None.
*/
USB_DEVICE_HID_RESULT USB_DEVICE_HID_EventHandlerSet
(
USB_DEVICE_HID_INDEX instanceIndex ,
USB_DEVICE_HID_EVENT_HANDLER eventHandler,
uintptr_t context
);
//******************************************************************************
/* Function:
USB_DEVICE_HID_RESULT USB_DEVICE_HID_ReportSend
(
USB_DEVICE_HID_INDEX instanceIndex,
USB_DEVICE_HID_TRANSFER_HANDLE * transferHandle,
void * buffer,
size_t size
)
Summary:
This function submits the buffer to HID function driver library to
send a report from device to host.
Description:
This function places a request to send a HID report with the USB Device HID
Function Driver Layer. The function places a requests with driver, the
request will get serviced when report is requested by the USB Host. A handle
to the request is returned in the transferHandle parameter. The termination
of the request is indicated by the USB_DEVICE_HID_EVENT_REPORT_SENT event.
The amount of data sent, a pointer to the report and the transfer handle
associated with the request is returned along with the event in the pData
parameter of the event handler. The transfer handle expires when event
handler for the USB_DEVICE_HID_EVENT_REPORT_SENT exits. If the send request
could not be accepted, the function returns an error code and transferHandle
will contain the value USB_DEVICE_HID_TRANSFER_HANDLE_INVALID.
Precondition:
USB device layer must be initialized.
Parameters:
instance - USB Device HID Function Driver instance.
transferHandle - Pointer to a USB_DEVICE_HID_TRANSFER_HANDLE type of
variable. This variable will contain the transfer handle
in case the send request was successful.
data - pointer to the data buffer containing the report to be sent.
size - Size (in bytes) of the report to be sent.
Returns:
USB_DEVICE_HID_RESULT_OK - The send request was successful. transferHandle
contains a valid transfer handle.
USB_DEVICE_HID_RESULT_ERROR_TRANSFER_QUEUE_FULL - Internal request queue
is full. The send request could not be added.
USB_DEVICE_HID_RESULT_ERROR_INSTANCE_NOT_CONFIGURED - The specified
instance is not configured yet.
USB_DEVICE_HID_RESULT_ERROR_INSTANCE_INVALID - The specified instance
was not provisioned in the application and is invalid.
Example:
<code>
USB_DEVICE_HID_TRANSFER_HANDLE hidTransferHandle;
USB_DEVICE_HID_RESULT result;
// Register APP_HIDEventHandler function
USB_DEVICE_HID_EventHandlerSet( USB_DEVICE_HID_INDEX_0 ,
APP_HIDEventHandler );
// Prepare report and request HID to send the report.
result = USB_DEVICE_HID_ReportSend( USB_DEVICE_HID_INDEX_0,
&hidTransferHandle ,
&appReport[0], sizeof(appReport));
if( result != USB_DEVICE_HID_RESULT_OK)
{
//Handle error.
}
//Implementation of APP_HIDEventHandler
USB_DEVICE_HIDE_EVENT_RESPONSE APP_HIDEventHandler
{
USB_DEVICE_HID_INDEX instanceIndex,
USB_DEVICE_HID_EVENT event,
void * pData,
uintptr_t context
}
{
USB_DEVICE_HID_EVENT_DATA_REPORT_SENT * reportSentEventData;
// Handle HID events here.
switch (event)
{
case USB_DEVICE_HID_EVENT_REPORT_SENT:
reportSentEventData = (USB_DEVICE_HID_EVENT_REPORT_SENT *)pData;
if(reportSentEventData->reportSize == sizeof(appReport))
{
// The report was sent completely.
}
break;
....
}
return(USB_DEVICE_HID_EVENT_RESPONSE_NONE);
}
</code>
Remarks:
While the using the HID Function Driver with the PIC32MZ USB module, the
report data buffer provided to the USB_DEVICE_HID_ReportSend function should
be placed in coherent memory and aligned at a 16 byte boundary. This can be
done by declaring the buffer using the __attribute__((coherent, aligned(16)))
attribute. An example is shown here
<code>
uint8_t data[256] __attribute__((coherent, aligned(16)));
</code>
*/
USB_DEVICE_HID_RESULT USB_DEVICE_HID_ReportSend
(
USB_DEVICE_HID_INDEX instanceIndex,
USB_DEVICE_HID_TRANSFER_HANDLE * handle,
void * buffer,
size_t size
);
//******************************************************************************
/* Function:
USB_DEVICE_HID_RESULT USB_DEVICE_HID_ReportReceive
(
USB_DEVICE_HID_INDEX instanceIndex,
USB_DEVICE_HID_TRANSFER_HANDLE * transferHandle,
void * buffer,
size_t size
);
Summary:
This function submits the buffer to HID function driver library to
receive a report from host to device.
Description:
This function submits the buffer to HID function driver library to receive a
report from host to device. On completion of the transfer the library
generates USB_DEVICE_HID_EVENT_REPORT_RECEIVED event to the application. A
handle to the request is passed in the transferHandle parameter. The
transfer handle expires when event handler for the
USB_DEVICE_HID_EVENT_REPORT_RECEIVED exits. If the receive request could
not be accepted, the function returns an error code and transferHandle
will contain the value USB_DEVICE_HID_TRANSFER_HANDLE_INVALID.
Precondition:
USB device layer must be initialized.
Parameters:
instanceIndex - HID instance index.
transferHandle - HID transfer handle.
buffer - Pointer to buffer where the received report has to be
received stored.
size - Buffer size.
Returns:
USB_DEVICE_HID_RESULT_OK - The receive request was successful. transferHandle
contains a valid transfer handle.
USB_DEVICE_HID_RESULT_ERROR_TRANSFER_QUEUE_FULL - internal request queue
is full. The receive request could not be added.
USB_DEVICE_HID_RESULT_ERROR_INSTANCE_NOT_CONFIGURED - The specified
instance is not configured yet.
USB_DEVICE_HID_RESULT_ERROR_INSTANCE_INVALID - The specified instance
was not provisioned in the application and is invalid.
Example:
<code>
USB_DEVICE_HID_TRANSFER_HANDLE hidTransferHandle;
USB_DEVICE_HID_RESULT result;
// Register APP_HIDEventHandler function
USB_DEVICE_HID_EventHandlerSet( USB_DEVICE_HID_INDEX_0 ,
APP_HIDEventHandler );
// Prepare report and request HID to send the report.
result = USB_DEVICE_HID_ReportReceive( USB_DEVICE_HID_INDEX_0,
&hidTransferHandle ,
&appReport[0], sizeof(appReport));
if( result != USB_DEVICE_HID_RESULT_OK)
{
//Handle error.
}
//Implementation of APP_HIDEventHandler
USB_DEVICE_HIDE_EVENT_RESPONSE APP_HIDEventHandler
{
USB_DEVICE_HID_INDEX instanceIndex,
USB_DEVICE_HID_EVENT event,
void * pData,
uintptr_t context
}
{
USB_DEVICE_HID_EVENT_DATA_REPORT_RECEIVED reportReceivedEventData;
// Handle HID events here.
switch (event)
{
case USB_DEVICE_HID_EVENT_REPORT_RECEIVED:
if( (reportReceivedEventData->reportSize == sizeof(appReport)
&& reportReceivedEventData->report == &appReport[0])
{
// Previous transfer was complete.
}
break;
....
}
}
</code>
Remarks:
While the using the HID Function Driver with the PIC32MZ USB module, the
report data buffer provided to the USB_DEVICE_HID_ReportReceive function should
be placed in coherent memory and aligned at a 16 byte boundary. This can be
done by declaring the buffer using the __attribute__((coherent, aligned(16)))
attribute. An example is shown here
<code>
uint8_t data[256] __attribute__((coherent, aligned(16)));
</code>
*/
USB_DEVICE_HID_RESULT USB_DEVICE_HID_ReportReceive
(
USB_DEVICE_HID_INDEX instanceIndex,
USB_DEVICE_HID_TRANSFER_HANDLE * handle,
void * buffer,
size_t size
);
//******************************************************************************
/* Function:
USB_DEVICE_HID_RESULT USB_DEVICE_HID_TransferCancel
(
USB_DEVICE_HID_INDEX instanceIndex,
USB_DEVICE_HID_TRANSFER_HANDLE transferHandle
);
Summary:
This function cancels a scheduled HID Device data transfer.
Description:
This function cancels a scheduled HID Device data transfer. The transfer
could have been scheduled using the USB_DEVICE_HID_ReportReceive,
USB_DEVICE_HID_ReportSend function. If a transfer is still in the queue
and its processing has not started, then the transfer is canceled
completely. A transfer that is in progress may or may not get canceled
depending on the transaction that is presently in progress. If the last
transaction of the transfer is in progress, then the transfer will not be
canceled. If it is not the last transaction in progress, the in-progress
will be allowed to complete. Pending transactions will be canceled. The
first transaction of an in progress transfer cannot be canceled.
Precondition:
The USB Device should be in a configured state.
Parameters:
instanceIndex - HID Function Driver instance index.
transferHandle - Transfer handle of the transfer to be canceled.
Returns:
USB_DEVICE_HID_RESULT_OK - The transfer will be canceled completely or
partially.
USB_DEVICE_HID_RESULT_ERROR_PARAMETER_INVALID - Invalid transfer handle
USB_DEVICE_HID_RESULT_ERROR_INSTANCE_INVALID - Invalid HID instance index
USB_DEVICE_HID_RESULT_ERROR - The transfer could not be canceled because it
has either completed, the transfer handle is
invalid or the last transaction is in progress.
Example:
<code>
// The following code snippet cancels a HID transfer.
USB_DEVICE_HID_TRANSFER_HANDLE transferHandle;
USB_DEVICE_HID_RESULT result;
result = USB_DEVICE_HID_TransferCancel(instanceIndex, transferHandle);
if(USB_DEVICE_HID_RESULT_OK == result)
{
// The transfer cancellation was either completely or
// partially successful.
}
</code>
Remarks:
The buffer specific to the transfer handle should not be released unless
the transfer abort event is notified through callback.
*/
USB_DEVICE_HID_RESULT USB_DEVICE_HID_TransferCancel
(
USB_DEVICE_HID_INDEX usbDeviceHandle,
USB_DEVICE_HID_TRANSFER_HANDLE transferHandle
);
// *****************************************************************************
// *****************************************************************************
// Section: Data Types and constants specific to PIC32 implementation of the
// USB Device Stack.
// *****************************************************************************
// *****************************************************************************
// *****************************************************************************
/* USB Device HID Function Driver Device Layer callback function pointer group
Summary:
This is a pointer to a group of HID Function Driver callback function
pointers.
Description:
This is a pointer to a group of HID Function Driver callback function
pointers. The application must use this pointer while registering an
instance of the HID function driver with the Device Layer via the function
driver registration table i.e. the driver member of the function driver
registration object in the device layer function driver registration table
should be set to this value.
Remarks:
None.
*/
/*DOM-IGNORE-BEGIN*/extern const USB_DEVICE_FUNCTION_DRIVER hidFuncDriver; /*DOM-IGNORE-END*/
#define USB_DEVICE_HID_FUNCTION_DRIVER /*DOM-IGNORE-BEGIN*/&hidFuncDriver/*DOM-IGNORE-END*/
// *****************************************************************************
/* USB Device HID Function Driver Initialization Data Structure
Summary:
USB Device HID Function Driver Initialization Data Structure
Description:
This data structure must be defined for every instance of the HID function
driver. It is passed to the HID function driver, by the Device Layer, at the
time of initialization. The funcDriverInit member of the Device Layer
Function Driver registration table entry must point to this data structure
for an instance of the HID function driver.
Remarks:
None.
*/
typedef struct
{
/* Size of the HID report descriptor */
size_t hidReportDescriptorSize;
/* Pointer to HID report descriptor */
void * hidReportDescriptor;
/* Report send queue size */
size_t queueSizeReportSend;
/* Report receive queue size */
size_t queueSizeReportReceive;
} USB_DEVICE_HID_INIT;
//DOM-IGNORE-BEGIN
#ifdef __cplusplus
}
#endif
//DOM-IGNORE-END
#endif
/*******************************************************************************
End of File
*/
|
yildiz-online/module-graphic-ogre | src/main/java/jni/JniBillboardSet.java | <reponame>yildiz-online/module-graphic-ogre<gh_stars>0
/*
* This file is part of the Yildiz-Engine project, licenced under the MIT License (MIT)
*
* Copyright (c) 2019 <NAME>
*
* More infos available: https://engine.yildiz-games.be
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this
* software and associated documentation files (the "Software"), to deal in the Software
* without restriction, including without limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
* to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package jni;
/**
* @author <NAME>
*/
public class JniBillboardSet {
/**
* Create a new Billboard in native code.
*
* @param pointer The billboard set native object pointer address.
* @return The newly built billboard native object pointer address.
*/
public native long createBillboard(final long pointer);
/**
* Set the default size in native code.
*
* @param address The Ogre::BillboardSet pointer address.
* @param width New default width in pixel.
* @param height New default height in pixels.
*/
public native void setSize(final long address, final float width, final float height);
/**
* Remove a billboard from the set.
*
* @param pointer The Ogre::BillboardSet pointer address.
* @param billboardPointer The Ogre::Billboard to remove pointer address.
*/
public native void remove(final long pointer, final long billboardPointer);
/**
* Attach the set to a node.
*
* @param pointer Set pointer address.
* @param nodePointer Node address.
*/
public native void attachToNode(final long pointer, final long nodePointer);
/**
* Set the set visible.
*
* @param pointerAddress Set pointer address.
*/
public native void show(final long pointerAddress);
/**
* Set the set invisible.
*
* @param pointerAddress Set pointer address.
*/
public native void hide(final long pointerAddress);
}
|
jhonatasrm/chromium-android | app/src/main/java/org/chromium/chrome/browser/preferences/privacy/ClearBrowsingDataTabsFragment.java | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.preferences.privacy;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Context;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.graphics.drawable.VectorDrawableCompat;
import android.support.v13.app.FragmentPagerAdapter;
import android.support.v4.text.TextUtilsCompat;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import org.chromium.base.metrics.RecordUserAction;
import org.chromium.chrome.R;
import org.chromium.chrome.browser.browsing_data.ClearBrowsingDataTab;
import org.chromium.chrome.browser.help.HelpAndFeedback;
import org.chromium.chrome.browser.preferences.PrefServiceBridge;
import org.chromium.chrome.browser.preferences.Preferences;
import org.chromium.chrome.browser.profiles.Profile;
import java.util.Locale;
/**
* Fragment with a {@link TabLayout} containing a basic and an advanced version of the CBD dialog.
*/
public class ClearBrowsingDataTabsFragment extends Fragment {
public static final int CBD_TAB_COUNT = 2;
private ClearBrowsingDataFetcher mFetcher;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
if (savedInstanceState == null) {
mFetcher = new ClearBrowsingDataFetcher();
mFetcher.fetchImportantSites();
mFetcher.requestInfoAboutOtherFormsOfBrowsingHistory();
} else {
mFetcher = savedInstanceState.getParcelable(
ClearBrowsingDataPreferences.CLEAR_BROWSING_DATA_FETCHER);
}
RecordUserAction.record("ClearBrowsingData_DialogCreated");
}
/*
* RTL is broken for ViewPager: https://code.google.com/p/android/issues/detail?id=56831
* This class works around this issue by inserting the tabs in inverse order if RTL is active.
* The TabLayout needs to be set to LTR for this to work.
* TODO(dullweber): Extract the RTL code into a wrapper class if other places in Chromium need
* it as well.
*/
private static int adjustIndexForDirectionality(int index) {
if (TextUtilsCompat.getLayoutDirectionFromLocale(Locale.getDefault())
== ViewCompat.LAYOUT_DIRECTION_RTL) {
return CBD_TAB_COUNT - 1 - index;
}
return index;
}
@Override
public View onCreateView(
LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment.
View view = inflater.inflate(R.layout.clear_browsing_data_tabs, container, false);
// Get the ViewPager and set its PagerAdapter so that it can display items.
ViewPager viewPager = view.findViewById(R.id.clear_browsing_data_viewpager);
viewPager.setAdapter(
new ClearBrowsingDataPagerAdapter(mFetcher, getFragmentManager(), getActivity()));
// Give the TabLayout the ViewPager.
TabLayout tabLayout = view.findViewById(R.id.clear_browsing_data_tabs);
tabLayout.setupWithViewPager(viewPager);
int tabIndex = adjustIndexForDirectionality(
PrefServiceBridge.getInstance().getLastSelectedClearBrowsingDataTab());
TabLayout.Tab tab = tabLayout.getTabAt(tabIndex);
if (tab != null) {
tab.select();
}
tabLayout.addOnTabSelectedListener(new TabSelectListener());
// Remove elevation to avoid shadow between title and tabs.
Preferences activity = (Preferences) getActivity();
activity.getSupportActionBar().setElevation(0.0f);
return view;
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// mFetcher acts as a cache for important sites and history data. If the activity gets
// suspended, we can save the cached data and reuse it when we are activated again.
outState.putParcelable(ClearBrowsingDataPreferences.CLEAR_BROWSING_DATA_FETCHER, mFetcher);
}
private static class ClearBrowsingDataPagerAdapter extends FragmentPagerAdapter {
private final ClearBrowsingDataFetcher mFetcher;
private final Context mContext;
ClearBrowsingDataPagerAdapter(
ClearBrowsingDataFetcher fetcher, FragmentManager fm, Context context) {
super(fm);
mFetcher = fetcher;
mContext = context;
}
@Override
public int getCount() {
return CBD_TAB_COUNT;
}
@Override
public Fragment getItem(int position) {
position = adjustIndexForDirectionality(position);
ClearBrowsingDataPreferences fragment;
switch (position) {
case 0:
fragment = new ClearBrowsingDataPreferencesBasic();
break;
case 1:
fragment = new ClearBrowsingDataPreferencesAdvanced();
break;
default:
throw new RuntimeException("invalid position: " + position);
}
fragment.setClearBrowsingDataFetcher(mFetcher);
return fragment;
}
@Override
public CharSequence getPageTitle(int position) {
position = adjustIndexForDirectionality(position);
switch (position) {
case 0:
return mContext.getString(R.string.clear_browsing_data_basic_tab_title);
case 1:
return mContext.getString(R.string.prefs_section_advanced);
default:
throw new RuntimeException("invalid position: " + position);
}
}
}
private static class TabSelectListener implements TabLayout.OnTabSelectedListener {
@Override
public void onTabSelected(TabLayout.Tab tab) {
int tabIndex = adjustIndexForDirectionality(tab.getPosition());
PrefServiceBridge.getInstance().setLastSelectedClearBrowsingDataTab(tabIndex);
if (tabIndex == ClearBrowsingDataTab.BASIC) {
RecordUserAction.record("ClearBrowsingData_SwitchTo_BasicTab");
} else {
RecordUserAction.record("ClearBrowsingData_SwitchTo_AdvancedTab");
}
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {}
@Override
public void onTabReselected(TabLayout.Tab tab) {}
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
menu.clear();
MenuItem help =
menu.add(Menu.NONE, R.id.menu_id_targeted_help, Menu.NONE, R.string.menu_help);
help.setIcon(VectorDrawableCompat.create(
getResources(), R.drawable.ic_help_and_feedback, getActivity().getTheme()));
help.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.menu_id_targeted_help) {
HelpAndFeedback.getInstance(getActivity())
.show(getActivity(), getString(R.string.help_context_clear_browsing_data),
Profile.getLastUsedProfile(), null);
return true;
}
return false;
}
}
|
antonmedv/year | packages/2032/11/09/index.js | module.exports = new Date(2032, 10, 9)
|
HeyLey/catboost | util/system/atomic_gcc.h | #pragma once
#define ATOMIC_COMPILER_BARRIER() __asm__ __volatile__("" \
: \
: \
: "memory")
static inline TAtomicBase AtomicGet(const TAtomic& a) {
TAtomicBase tmp;
#if defined(_arm64_)
__asm__ __volatile__(
"ldar %x[value], %[ptr] \n\t"
: [value] "=r"(tmp)
: [ptr] "Q"(a)
: "memory");
#else
__atomic_load(&a, &tmp, __ATOMIC_ACQUIRE);
#endif
return tmp;
}
static inline void AtomicSet(TAtomic& a, TAtomicBase v) {
#if defined(_arm64_)
__asm__ __volatile__(
"stlr %x[value], %[ptr] \n\t"
: [ptr] "=Q"(a)
: [value] "r"(v)
: "memory");
#else
__atomic_store(&a, &v, __ATOMIC_RELEASE);
#endif
}
static inline intptr_t AtomicIncrement(TAtomic& p) {
return __atomic_add_fetch(&p, 1, __ATOMIC_SEQ_CST);
}
static inline intptr_t AtomicGetAndIncrement(TAtomic& p) {
return __atomic_fetch_add(&p, 1, __ATOMIC_SEQ_CST);
}
static inline intptr_t AtomicDecrement(TAtomic& p) {
return __atomic_sub_fetch(&p, 1, __ATOMIC_SEQ_CST);
}
static inline intptr_t AtomicGetAndDecrement(TAtomic& p) {
return __atomic_fetch_sub(&p, 1, __ATOMIC_SEQ_CST);
}
static inline intptr_t AtomicAdd(TAtomic& p, intptr_t v) {
return __atomic_add_fetch(&p, v, __ATOMIC_SEQ_CST);
}
static inline intptr_t AtomicGetAndAdd(TAtomic& p, intptr_t v) {
return __atomic_fetch_add(&p, v, __ATOMIC_SEQ_CST);
}
static inline intptr_t AtomicSwap(TAtomic* p, intptr_t v) {
(void)p; // disable strange 'parameter set but not used' warning on gcc
intptr_t ret;
__atomic_exchange(p, &v, &ret, __ATOMIC_SEQ_CST);
return ret;
}
static inline bool AtomicCas(TAtomic* a, intptr_t exchange, intptr_t compare) {
(void)a; // disable strange 'parameter set but not used' warning on gcc
return __atomic_compare_exchange(a, &compare, &exchange, false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST);
}
static inline intptr_t AtomicGetAndCas(TAtomic* a, intptr_t exchange, intptr_t compare) {
(void)a; // disable strange 'parameter set but not used' warning on gcc
__atomic_compare_exchange(a, &compare, &exchange, false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST);
return compare;
}
static inline intptr_t AtomicOr(TAtomic& a, intptr_t b) {
return __atomic_or_fetch(&a, b, __ATOMIC_SEQ_CST);
}
static inline intptr_t AtomicXor(TAtomic& a, intptr_t b) {
return __atomic_xor_fetch(&a, b, __ATOMIC_SEQ_CST);
}
static inline intptr_t AtomicAnd(TAtomic& a, intptr_t b) {
return __atomic_and_fetch(&a, b, __ATOMIC_SEQ_CST);
}
static inline void AtomicBarrier() {
__sync_synchronize();
}
|
lanzhu259X/mywork | account/account-api/src/main/java/com/lanzhu/mywork/account/vo/user/request/RegisterArg.java | <reponame>lanzhu259X/mywork
package com.lanzhu.mywork.account.vo.user.request;
import com.lanzhu.mywork.account.common.enums.UserAuthType;
import com.lanzhu.mywork.master.commons.ToString;
import lombok.Getter;
import lombok.Setter;
import javax.validation.constraints.NotNull;
/**
* description:
*
* @author lanzhu259X
* @date 2018-12-31
*/
@Setter
@Getter
public class RegisterArg extends ToString {
private static final long serialVersionUID = 841116202577681850L;
/**
* 认证类型
*/
@NotNull
private UserAuthType userAuthType;
/**
* 身份标识
*/
@NotNull
private String identifier;
/**
* 验证码
*/
private String verifyCode;
/**
* 密码
*/
private String password;
/**
* 邀请码
*/
private String inviteCode;
}
|
bobdoah/garmin-connect | connect/sleep.go | <reponame>bobdoah/garmin-connect
package main
import (
"fmt"
"os"
connect "github.com/abrander/garmin-connect"
"github.com/spf13/cobra"
)
func init() {
sleepCmd := &cobra.Command{
Use: "sleep",
}
rootCmd.AddCommand(sleepCmd)
sleepSummaryCmd := &cobra.Command{
Use: "summary <date> [displayName]",
Short: "Show sleep summary for date",
Run: sleepSummary,
Args: cobra.RangeArgs(1, 2),
}
sleepCmd.AddCommand(sleepSummaryCmd)
}
func sleepSummary(_ *cobra.Command, args []string) {
date, err := connect.ParseDate(args[0])
bail(err)
displayName := ""
if len(args) > 1 {
displayName = args[1]
}
summary, _, levels, err := client.SleepData(displayName, date.Time())
bail(err)
t := NewTabular()
t.AddValue("Start", summary.StartGMT)
t.AddValue("End", summary.EndGMT)
t.AddValue("Sleep", hoursAndMinutes(summary.Sleep))
t.AddValue("Nap", hoursAndMinutes(summary.Nap))
t.AddValue("Unmeasurable", hoursAndMinutes(summary.Unmeasurable))
t.AddValue("Deep", hoursAndMinutes(summary.Deep))
t.AddValue("Light", hoursAndMinutes(summary.Light))
t.AddValue("REM", hoursAndMinutes(summary.REM))
t.AddValue("Awake", hoursAndMinutes(summary.Awake))
t.AddValue("Confirmed", summary.Confirmed)
t.AddValue("Confirmation Type", summary.Confirmation)
t.AddValue("REM Data", summary.REMData)
t.Output(os.Stdout)
fmt.Fprintf(os.Stdout, "\n")
t2 := NewTable()
t2.AddHeader("Start", "End", "State", "Duration")
for _, l := range levels {
t2.AddRow(l.Start, l.End, l.State, hoursAndMinutes(l.End.Sub(l.Start.Time)))
}
t2.Output(os.Stdout)
}
|
consorzio-rfx/mdsplus | javadevices/NI6368AISetup.java | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* NI6368AISetup.java
*
* Created on Dec 22, 2011, 9:59:13 AM
*/
/**
*
* @author manduchi
*/
public class NI6368AISetup extends DeviceSetup {
/** Creates new form NI6368AISetup */
public NI6368AISetup() {
initComponents();
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
deviceButtons1 = new DeviceButtons();
jPanel1 = new javax.swing.JPanel();
jPanel2 = new javax.swing.JPanel();
deviceField2 = new DeviceField();
deviceField1 = new DeviceField();
deviceDispatch1 = new DeviceDispatch();
jPanel3 = new javax.swing.JPanel();
deviceChoice51 = new DeviceChoice();
deviceField3 = new DeviceField();
deviceField4 = new DeviceField();
jPanel4 = new javax.swing.JPanel();
deviceChoice4 = new DeviceChoice();
deviceField5 = new DeviceField();
deviceField6 = new DeviceField();
jPanel5 = new javax.swing.JPanel();
deviceChoice2 = new DeviceChoice();
deviceField11 = new DeviceField();
jPanel6 = new javax.swing.JPanel();
deviceChoice52 = new DeviceChoice();
deviceField7 = new DeviceField();
deviceField8 = new DeviceField();
deviceField9 = new DeviceField();
deviceField10 = new DeviceField();
jScrollPane1 = new javax.swing.JScrollPane();
jPanel39 = new javax.swing.JPanel();
jPanel7 = new javax.swing.JPanel();
deviceChoice3 = new DeviceChoice();
deviceChoice5 = new DeviceChoice();
jLabel1 = new javax.swing.JLabel();
jPanel8 = new javax.swing.JPanel();
deviceChoice6 = new DeviceChoice();
deviceChoice17 = new DeviceChoice();
jLabel9 = new javax.swing.JLabel();
jPanel9 = new javax.swing.JPanel();
deviceChoice9 = new DeviceChoice();
deviceChoice7 = new DeviceChoice();
jLabel2 = new javax.swing.JLabel();
jPanel10 = new javax.swing.JPanel();
deviceChoice12 = new DeviceChoice();
deviceChoice19 = new DeviceChoice();
jLabel10 = new javax.swing.JLabel();
jPanel11 = new javax.swing.JPanel();
deviceChoice15 = new DeviceChoice();
deviceChoice8 = new DeviceChoice();
jLabel3 = new javax.swing.JLabel();
jPanel12 = new javax.swing.JPanel();
deviceChoice18 = new DeviceChoice();
deviceChoice20 = new DeviceChoice();
jLabel11 = new javax.swing.JLabel();
jPanel13 = new javax.swing.JPanel();
deviceChoice21 = new DeviceChoice();
deviceChoice10 = new DeviceChoice();
jLabel4 = new javax.swing.JLabel();
jPanel14 = new javax.swing.JPanel();
deviceChoice24 = new DeviceChoice();
deviceChoice22 = new DeviceChoice();
jLabel12 = new javax.swing.JLabel();
jPanel15 = new javax.swing.JPanel();
deviceChoice27 = new DeviceChoice();
deviceChoice11 = new DeviceChoice();
jLabel5 = new javax.swing.JLabel();
jPanel16 = new javax.swing.JPanel();
deviceChoice30 = new DeviceChoice();
deviceChoice23 = new DeviceChoice();
jLabel13 = new javax.swing.JLabel();
jPanel17 = new javax.swing.JPanel();
deviceChoice33 = new DeviceChoice();
deviceChoice13 = new DeviceChoice();
jLabel6 = new javax.swing.JLabel();
jPanel18 = new javax.swing.JPanel();
deviceChoice36 = new DeviceChoice();
deviceChoice25 = new DeviceChoice();
jLabel14 = new javax.swing.JLabel();
jPanel19 = new javax.swing.JPanel();
deviceChoice39 = new DeviceChoice();
deviceChoice14 = new DeviceChoice();
jLabel7 = new javax.swing.JLabel();
jPanel20 = new javax.swing.JPanel();
deviceChoice42 = new DeviceChoice();
deviceChoice26 = new DeviceChoice();
jLabel15 = new javax.swing.JLabel();
jPanel21 = new javax.swing.JPanel();
deviceChoice45 = new DeviceChoice();
deviceChoice16 = new DeviceChoice();
jLabel8 = new javax.swing.JLabel();
jPanel22 = new javax.swing.JPanel();
deviceChoice48 = new DeviceChoice();
deviceChoice28 = new DeviceChoice();
jLabel16 = new javax.swing.JLabel();
setDeviceProvider("localhost");
setDeviceTitle("National Instruments PXIe 6368 16 ch 2MS/s ADC");
setDeviceType("NI6368AI");
setHeight(900);
setWidth(900);
deviceButtons1.setCheckExpressions(new String[] {});
deviceButtons1.setCheckMessages(new String[] {});
deviceButtons1.setMethods(new String[] {"init", "start_store", "stop_store"});
getContentPane().add(deviceButtons1, java.awt.BorderLayout.PAGE_END);
jPanel1.setLayout(new java.awt.GridLayout(5, 1));
deviceField2.setIdentifier("");
deviceField2.setLabelString("Comment: ");
deviceField2.setNumCols(40);
deviceField2.setOffsetNid(2);
deviceField2.setTextOnly(true);
jPanel2.add(deviceField2);
deviceField1.setIdentifier("");
deviceField1.setLabelString("Board Id: ");
deviceField1.setNumCols(4);
deviceField1.setOffsetNid(1);
jPanel2.add(deviceField1);
jPanel2.add(deviceDispatch1);
jPanel1.add(jPanel2);
deviceChoice51.setChoiceItems(new String[] {"TRANSIENT REC.", "CONTINUOUS"});
deviceChoice51.setIdentifier("");
deviceChoice51.setLabelString("Acq. Mode: ");
deviceChoice51.setOffsetNid(9);
deviceChoice51.setUpdateIdentifier("");
jPanel3.add(deviceChoice51);
deviceField3.setIdentifier("");
deviceField3.setLabelString("Buf. Size (Bytes): ");
deviceField3.setOffsetNid(6);
jPanel3.add(deviceField3);
deviceField4.setIdentifier("");
deviceField4.setLabelString("Segment Size (Bytes): ");
deviceField4.setOffsetNid(7);
jPanel3.add(deviceField4);
jPanel1.add(jPanel3);
deviceChoice4.setChoiceItems(new String[] {"INTERNAL", "EXTERNAL"});
deviceChoice4.setIdentifier("");
deviceChoice4.setLabelString("Clock Mode: ");
deviceChoice4.setOffsetNid(4);
deviceChoice4.setUpdateIdentifier("");
jPanel4.add(deviceChoice4);
deviceField5.setIdentifier("");
deviceField5.setLabelString("Frequency (Hz): ");
deviceField5.setOffsetNid(5);
jPanel4.add(deviceField5);
deviceField6.setIdentifier("");
deviceField6.setLabelString("Ext. Clock: ");
deviceField6.setNumCols(30);
deviceField6.setOffsetNid(8);
jPanel4.add(deviceField6);
jPanel1.add(jPanel4);
deviceChoice2.setChoiceItems(new String[] {"INTERNAL", "EXTERNAL"});
deviceChoice2.setIdentifier("");
deviceChoice2.setLabelString("Trigger Mode: ");
deviceChoice2.setOffsetNid(10);
deviceChoice2.setUpdateIdentifier("");
jPanel5.add(deviceChoice2);
deviceField11.setIdentifier("");
deviceField11.setLabelString("Ext. Trigger: ");
deviceField11.setNumCols(30);
deviceField11.setOffsetNid(11);
jPanel5.add(deviceField11);
jPanel1.add(jPanel5);
deviceChoice52.setChoiceItems(new String[] {"YES", "NO"});
deviceChoice52.setIdentifier("");
deviceChoice52.setLabelString("Use Time: ");
deviceChoice52.setOffsetNid(12);
deviceChoice52.setUpdateIdentifier("");
jPanel6.add(deviceChoice52);
deviceField7.setIdentifier("");
deviceField7.setLabelString("Start Time (s): ");
deviceField7.setNumCols(8);
deviceField7.setOffsetNid(13);
jPanel6.add(deviceField7);
deviceField8.setIdentifier("");
deviceField8.setLabelString("End Time (s): ");
deviceField8.setNumCols(8);
deviceField8.setOffsetNid(14);
jPanel6.add(deviceField8);
deviceField9.setIdentifier("");
deviceField9.setLabelString("Start Idx: ");
deviceField9.setNumCols(8);
deviceField9.setOffsetNid(15);
jPanel6.add(deviceField9);
deviceField10.setIdentifier("");
deviceField10.setLabelString("End Idx:");
deviceField10.setNumCols(8);
deviceField10.setOffsetNid(16);
jPanel6.add(deviceField10);
jPanel1.add(jPanel6);
getContentPane().add(jPanel1, java.awt.BorderLayout.PAGE_START);
jPanel39.setLayout(new java.awt.GridLayout(8, 2));
jPanel7.setBorder(javax.swing.BorderFactory.createTitledBorder("Channel 1"));
jPanel7.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.CENTER, 0, 0));
deviceChoice3.setChoiceItems(new String[] {"ENABLED", "DISABLED"});
deviceChoice3.setIdentifier("");
deviceChoice3.setLabelString("State: ");
deviceChoice3.setOffsetNid(18);
deviceChoice3.setUpdateIdentifier("");
jPanel7.add(deviceChoice3);
deviceChoice5.setChoiceFloatValues(new float[] {10.0f, 5.0f, 2.0f, 1.0f});
deviceChoice5.setChoiceItems(new String[] {"10.", "5.", "2.", "1."});
deviceChoice5.setIdentifier("");
deviceChoice5.setLabelString("Range: +/-");
deviceChoice5.setOffsetNid(19);
deviceChoice5.setUpdateIdentifier("");
jPanel7.add(deviceChoice5);
jLabel1.setText("V");
jPanel7.add(jLabel1);
jPanel39.add(jPanel7);
jPanel8.setBorder(javax.swing.BorderFactory.createTitledBorder("Channel 2"));
jPanel8.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.CENTER, 0, 0));
deviceChoice6.setChoiceItems(new String[] {"ENABLED", "DISABLED"});
deviceChoice6.setIdentifier("");
deviceChoice6.setLabelString("State: ");
deviceChoice6.setOffsetNid(24);
deviceChoice6.setUpdateIdentifier("");
jPanel8.add(deviceChoice6);
deviceChoice17.setChoiceFloatValues(new float[] {10.0f, 5.0f, 2.0f, 1.0f});
deviceChoice17.setChoiceItems(new String[] {"10.", "5.", "2.", "1."});
deviceChoice17.setIdentifier("");
deviceChoice17.setLabelString("Range: +/-");
deviceChoice17.setOffsetNid(25);
deviceChoice17.setUpdateIdentifier("");
jPanel8.add(deviceChoice17);
jLabel9.setText("V");
jPanel8.add(jLabel9);
jPanel39.add(jPanel8);
jPanel9.setBorder(javax.swing.BorderFactory.createTitledBorder("Channel 3"));
deviceChoice9.setChoiceItems(new String[] {"ENABLED", "DISABLED"});
deviceChoice9.setIdentifier("");
deviceChoice9.setLabelString("State: ");
deviceChoice9.setOffsetNid(30);
deviceChoice9.setUpdateIdentifier("");
jPanel9.add(deviceChoice9);
deviceChoice7.setChoiceFloatValues(new float[] {10.0f, 5.0f, 2.0f, 1.0f});
deviceChoice7.setChoiceItems(new String[] {"10.", "5.", "2.", "1."});
deviceChoice7.setIdentifier("");
deviceChoice7.setLabelString("Range: +/-");
deviceChoice7.setOffsetNid(31);
deviceChoice7.setUpdateIdentifier("");
jPanel9.add(deviceChoice7);
jLabel2.setText("V");
jPanel9.add(jLabel2);
jPanel39.add(jPanel9);
jPanel10.setBorder(javax.swing.BorderFactory.createTitledBorder("Channel 4"));
deviceChoice12.setChoiceItems(new String[] {"ENABLED", "DISABLED"});
deviceChoice12.setIdentifier("");
deviceChoice12.setLabelString("State: ");
deviceChoice12.setOffsetNid(36);
deviceChoice12.setUpdateIdentifier("");
jPanel10.add(deviceChoice12);
deviceChoice19.setChoiceFloatValues(new float[] {10.0f, 5.0f, 2.0f, 1.0f});
deviceChoice19.setChoiceItems(new String[] {"10.", "5.", "2.", "1."});
deviceChoice19.setIdentifier("");
deviceChoice19.setLabelString("Range: +/-");
deviceChoice19.setOffsetNid(37);
deviceChoice19.setUpdateIdentifier("");
jPanel10.add(deviceChoice19);
jLabel10.setText("V");
jPanel10.add(jLabel10);
jPanel39.add(jPanel10);
jPanel11.setBorder(javax.swing.BorderFactory.createTitledBorder("Channel 5"));
deviceChoice15.setChoiceItems(new String[] {"ENABLED", "DISABLED"});
deviceChoice15.setIdentifier("");
deviceChoice15.setLabelString("State: ");
deviceChoice15.setOffsetNid(42);
deviceChoice15.setUpdateIdentifier("");
jPanel11.add(deviceChoice15);
deviceChoice8.setChoiceFloatValues(new float[] {10.0f, 5.0f, 2.0f, 1.0f});
deviceChoice8.setChoiceItems(new String[] {"10.", "5.", "2.", "1."});
deviceChoice8.setIdentifier("");
deviceChoice8.setLabelString("Range: +/-");
deviceChoice8.setOffsetNid(43);
deviceChoice8.setUpdateIdentifier("");
jPanel11.add(deviceChoice8);
jLabel3.setText("V");
jPanel11.add(jLabel3);
jPanel39.add(jPanel11);
jPanel12.setBorder(javax.swing.BorderFactory.createTitledBorder("Channel 6"));
deviceChoice18.setChoiceItems(new String[] {"ENABLED", "DISABLED"});
deviceChoice18.setIdentifier("");
deviceChoice18.setLabelString("State: ");
deviceChoice18.setOffsetNid(48);
deviceChoice18.setUpdateIdentifier("");
jPanel12.add(deviceChoice18);
deviceChoice20.setChoiceFloatValues(new float[] {10.0f, 5.0f, 2.0f, 1.0f});
deviceChoice20.setChoiceItems(new String[] {"10.", "5.", "2.", "1."});
deviceChoice20.setIdentifier("");
deviceChoice20.setLabelString("Range: +/-");
deviceChoice20.setOffsetNid(49);
deviceChoice20.setUpdateIdentifier("");
jPanel12.add(deviceChoice20);
jLabel11.setText("V");
jPanel12.add(jLabel11);
jPanel39.add(jPanel12);
jPanel13.setBorder(javax.swing.BorderFactory.createTitledBorder("Channel 7"));
deviceChoice21.setChoiceItems(new String[] {"ENABLED", "DISABLED"});
deviceChoice21.setIdentifier("");
deviceChoice21.setLabelString("State: ");
deviceChoice21.setOffsetNid(54);
deviceChoice21.setUpdateIdentifier("");
jPanel13.add(deviceChoice21);
deviceChoice10.setChoiceFloatValues(new float[] {10.0f, 5.0f, 2.0f, 1.0f});
deviceChoice10.setChoiceItems(new String[] {"10.", "5.", "2.", "1."});
deviceChoice10.setIdentifier("");
deviceChoice10.setLabelString("Range: +/-");
deviceChoice10.setOffsetNid(55);
deviceChoice10.setUpdateIdentifier("");
jPanel13.add(deviceChoice10);
jLabel4.setText("V");
jPanel13.add(jLabel4);
jPanel39.add(jPanel13);
jPanel14.setBorder(javax.swing.BorderFactory.createTitledBorder("Channel 8"));
deviceChoice24.setChoiceItems(new String[] {"ENABLED", "DISABLED"});
deviceChoice24.setIdentifier("");
deviceChoice24.setLabelString("State: ");
deviceChoice24.setOffsetNid(60);
deviceChoice24.setUpdateIdentifier("");
jPanel14.add(deviceChoice24);
deviceChoice22.setChoiceFloatValues(new float[] {10.0f, 5.0f, 2.0f, 1.0f});
deviceChoice22.setChoiceItems(new String[] {"10.", "5.", "2.", "1."});
deviceChoice22.setIdentifier("");
deviceChoice22.setLabelString("Range: +/-");
deviceChoice22.setOffsetNid(51);
deviceChoice22.setUpdateIdentifier("");
jPanel14.add(deviceChoice22);
jLabel12.setText("V");
jPanel14.add(jLabel12);
jPanel39.add(jPanel14);
jPanel15.setBorder(javax.swing.BorderFactory.createTitledBorder("Channel 9"));
deviceChoice27.setChoiceItems(new String[] {"ENABLED", "DISABLED"});
deviceChoice27.setIdentifier("");
deviceChoice27.setLabelString("State: ");
deviceChoice27.setOffsetNid(66);
deviceChoice27.setUpdateIdentifier("");
jPanel15.add(deviceChoice27);
deviceChoice11.setChoiceFloatValues(new float[] {10.0f, 5.0f, 2.0f, 1.0f});
deviceChoice11.setChoiceItems(new String[] {"10.", "5.", "2.", "1."});
deviceChoice11.setIdentifier("");
deviceChoice11.setLabelString("Range: +/-");
deviceChoice11.setOffsetNid(67);
deviceChoice11.setUpdateIdentifier("");
jPanel15.add(deviceChoice11);
jLabel5.setText("V");
jPanel15.add(jLabel5);
jPanel39.add(jPanel15);
jPanel16.setBorder(javax.swing.BorderFactory.createTitledBorder("Channel 10"));
deviceChoice30.setChoiceItems(new String[] {"ENABLED", "DISABLED"});
deviceChoice30.setIdentifier("");
deviceChoice30.setLabelString("State: ");
deviceChoice30.setOffsetNid(72);
deviceChoice30.setUpdateIdentifier("");
jPanel16.add(deviceChoice30);
deviceChoice23.setChoiceFloatValues(new float[] {10.0f, 5.0f, 2.0f, 1.0f});
deviceChoice23.setChoiceItems(new String[] {"10.", "5.", "2.", "1."});
deviceChoice23.setIdentifier("");
deviceChoice23.setLabelString("Range: +/-");
deviceChoice23.setOffsetNid(73);
deviceChoice23.setUpdateIdentifier("");
jPanel16.add(deviceChoice23);
jLabel13.setText("V");
jPanel16.add(jLabel13);
jPanel39.add(jPanel16);
jPanel17.setBorder(javax.swing.BorderFactory.createTitledBorder("Channel 11"));
deviceChoice33.setChoiceItems(new String[] {"ENABLED", "DISABLED"});
deviceChoice33.setIdentifier("");
deviceChoice33.setLabelString("State: ");
deviceChoice33.setOffsetNid(78);
deviceChoice33.setUpdateIdentifier("");
jPanel17.add(deviceChoice33);
deviceChoice13.setChoiceFloatValues(new float[] {10.0f, 5.0f, 2.0f, 1.0f});
deviceChoice13.setChoiceItems(new String[] {"10.", "5.", "2.", "1."});
deviceChoice13.setIdentifier("");
deviceChoice13.setLabelString("Range: +/-");
deviceChoice13.setOffsetNid(79);
deviceChoice13.setUpdateIdentifier("");
jPanel17.add(deviceChoice13);
jLabel6.setText("V");
jPanel17.add(jLabel6);
jPanel39.add(jPanel17);
jPanel18.setBorder(javax.swing.BorderFactory.createTitledBorder("Channel 12"));
deviceChoice36.setChoiceItems(new String[] {"ENABLED", "DISABLED"});
deviceChoice36.setIdentifier("");
deviceChoice36.setLabelString("State: ");
deviceChoice36.setOffsetNid(84);
deviceChoice36.setUpdateIdentifier("");
jPanel18.add(deviceChoice36);
deviceChoice25.setChoiceFloatValues(new float[] {10.0f, 5.0f, 2.0f, 1.0f});
deviceChoice25.setChoiceItems(new String[] {"10.", "5.", "2.", "1."});
deviceChoice25.setIdentifier("");
deviceChoice25.setLabelString("Range: +/-");
deviceChoice25.setOffsetNid(85);
deviceChoice25.setUpdateIdentifier("");
jPanel18.add(deviceChoice25);
jLabel14.setText("V");
jPanel18.add(jLabel14);
jPanel39.add(jPanel18);
jPanel19.setBorder(javax.swing.BorderFactory.createTitledBorder("Channel 13"));
deviceChoice39.setChoiceItems(new String[] {"ENABLED", "DISABLED"});
deviceChoice39.setIdentifier("");
deviceChoice39.setLabelString("State: ");
deviceChoice39.setOffsetNid(90);
deviceChoice39.setUpdateIdentifier("");
jPanel19.add(deviceChoice39);
deviceChoice14.setChoiceFloatValues(new float[] {10.0f, 5.0f, 2.0f, 1.0f});
deviceChoice14.setChoiceItems(new String[] {"10.", "5.", "2.", "1."});
deviceChoice14.setIdentifier("");
deviceChoice14.setLabelString("Range: +/-");
deviceChoice14.setOffsetNid(91);
deviceChoice14.setUpdateIdentifier("");
jPanel19.add(deviceChoice14);
jLabel7.setText("V");
jPanel19.add(jLabel7);
jPanel39.add(jPanel19);
jPanel20.setBorder(javax.swing.BorderFactory.createTitledBorder("Channel 14"));
deviceChoice42.setChoiceItems(new String[] {"ENABLED", "DISABLED"});
deviceChoice42.setIdentifier("");
deviceChoice42.setLabelString("State: ");
deviceChoice42.setOffsetNid(96);
deviceChoice42.setUpdateIdentifier("");
jPanel20.add(deviceChoice42);
deviceChoice26.setChoiceFloatValues(new float[] {10.0f, 5.0f, 2.0f, 1.0f});
deviceChoice26.setChoiceItems(new String[] {"10.", "5.", "2.", "1."});
deviceChoice26.setIdentifier("");
deviceChoice26.setLabelString("Range: +/-");
deviceChoice26.setOffsetNid(97);
deviceChoice26.setUpdateIdentifier("");
jPanel20.add(deviceChoice26);
jLabel15.setText("V");
jPanel20.add(jLabel15);
jPanel39.add(jPanel20);
jPanel21.setBorder(javax.swing.BorderFactory.createTitledBorder("Channel 15"));
deviceChoice45.setChoiceItems(new String[] {"ENABLED", "DISABLED"});
deviceChoice45.setIdentifier("");
deviceChoice45.setLabelString("State: ");
deviceChoice45.setOffsetNid(102);
deviceChoice45.setUpdateIdentifier("");
jPanel21.add(deviceChoice45);
deviceChoice16.setChoiceFloatValues(new float[] {10.0f, 5.0f, 2.0f, 1.0f});
deviceChoice16.setChoiceItems(new String[] {"10.", "5.", "2.", "1."});
deviceChoice16.setIdentifier("");
deviceChoice16.setLabelString("Range: +/-");
deviceChoice16.setOffsetNid(103);
deviceChoice16.setUpdateIdentifier("");
jPanel21.add(deviceChoice16);
jLabel8.setText("V");
jPanel21.add(jLabel8);
jPanel39.add(jPanel21);
jPanel22.setBorder(javax.swing.BorderFactory.createTitledBorder("Channel 16"));
deviceChoice48.setChoiceItems(new String[] {"ENABLED", "DISABLED"});
deviceChoice48.setIdentifier("");
deviceChoice48.setLabelString("State: ");
deviceChoice48.setOffsetNid(108);
deviceChoice48.setUpdateIdentifier("");
jPanel22.add(deviceChoice48);
deviceChoice28.setChoiceFloatValues(new float[] {10.0f, 5.0f, 2.0f, 1.0f});
deviceChoice28.setChoiceItems(new String[] {"10.", "5.", "2.", "1."});
deviceChoice28.setIdentifier("");
deviceChoice28.setLabelString("Range: +/-");
deviceChoice28.setOffsetNid(109);
deviceChoice28.setUpdateIdentifier("");
jPanel22.add(deviceChoice28);
jLabel16.setText("V");
jPanel22.add(jLabel16);
jPanel39.add(jPanel22);
jScrollPane1.setViewportView(jPanel39);
getContentPane().add(jScrollPane1, java.awt.BorderLayout.CENTER);
}// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
private DeviceButtons deviceButtons1;
private DeviceChoice deviceChoice10;
private DeviceChoice deviceChoice11;
private DeviceChoice deviceChoice12;
private DeviceChoice deviceChoice13;
private DeviceChoice deviceChoice14;
private DeviceChoice deviceChoice15;
private DeviceChoice deviceChoice16;
private DeviceChoice deviceChoice17;
private DeviceChoice deviceChoice18;
private DeviceChoice deviceChoice19;
private DeviceChoice deviceChoice2;
private DeviceChoice deviceChoice20;
private DeviceChoice deviceChoice21;
private DeviceChoice deviceChoice22;
private DeviceChoice deviceChoice23;
private DeviceChoice deviceChoice24;
private DeviceChoice deviceChoice25;
private DeviceChoice deviceChoice26;
private DeviceChoice deviceChoice27;
private DeviceChoice deviceChoice28;
private DeviceChoice deviceChoice3;
private DeviceChoice deviceChoice30;
private DeviceChoice deviceChoice33;
private DeviceChoice deviceChoice36;
private DeviceChoice deviceChoice39;
private DeviceChoice deviceChoice4;
private DeviceChoice deviceChoice42;
private DeviceChoice deviceChoice45;
private DeviceChoice deviceChoice48;
private DeviceChoice deviceChoice5;
private DeviceChoice deviceChoice51;
private DeviceChoice deviceChoice52;
private DeviceChoice deviceChoice6;
private DeviceChoice deviceChoice7;
private DeviceChoice deviceChoice8;
private DeviceChoice deviceChoice9;
private DeviceDispatch deviceDispatch1;
private DeviceField deviceField1;
private DeviceField deviceField10;
private DeviceField deviceField11;
private DeviceField deviceField2;
private DeviceField deviceField3;
private DeviceField deviceField4;
private DeviceField deviceField5;
private DeviceField deviceField6;
private DeviceField deviceField7;
private DeviceField deviceField8;
private DeviceField deviceField9;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel11;
private javax.swing.JLabel jLabel12;
private javax.swing.JLabel jLabel13;
private javax.swing.JLabel jLabel14;
private javax.swing.JLabel jLabel15;
private javax.swing.JLabel jLabel16;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel10;
private javax.swing.JPanel jPanel11;
private javax.swing.JPanel jPanel12;
private javax.swing.JPanel jPanel13;
private javax.swing.JPanel jPanel14;
private javax.swing.JPanel jPanel15;
private javax.swing.JPanel jPanel16;
private javax.swing.JPanel jPanel17;
private javax.swing.JPanel jPanel18;
private javax.swing.JPanel jPanel19;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel20;
private javax.swing.JPanel jPanel21;
private javax.swing.JPanel jPanel22;
private javax.swing.JPanel jPanel3;
private javax.swing.JPanel jPanel39;
private javax.swing.JPanel jPanel4;
private javax.swing.JPanel jPanel5;
private javax.swing.JPanel jPanel6;
private javax.swing.JPanel jPanel7;
private javax.swing.JPanel jPanel8;
private javax.swing.JPanel jPanel9;
private javax.swing.JScrollPane jScrollPane1;
// End of variables declaration//GEN-END:variables
}
|
myGrid/methodbox | lib/tasks/fix_value_domains.rake | # Value domains pulled from ccsr metadata were recorded twice
require 'rubygems'
require 'rake'
require 'model_execution'
require 'active_record/fixtures'
namespace :obesity do
desc "fix value domains pulled from ccsr metadata"
task :fix_ccsr_value_domain => :environment do
Variable.all.each do |variable|
if variable.info != nil && !variable.info.include?("SPSS")
value_domains = variable.value_domains
if !value_domains.empty?
info = String.new
hash = Hash.new
value_domains.each do |value_domain|
hash[value_domain.value] = value_domain.label
end
hash.sort.reverse.each do |value, label|
info << "value " + value + " label " + label + "\r\n"
end
variable.update_attributes(:info => info)
puts "update for " + variable.name + variable.dataset.name
end
end
end
end
end |
Corpus-2021/sablecc | src/org/sablecc/objectmacro/codegeneration/scala/macro/MTextInsertPart.java | /* This file was generated by SableCC's ObjectMacro. */
package org.sablecc.objectmacro.codegeneration.scala.macro;
import java.util.*;
public class MTextInsertPart {
private final List<Object> eTextInsert = new LinkedList<>();
public MTextInsertPart() {
}
public MTextInsert newTextInsert(
String pName) {
MTextInsert lTextInsert = new MTextInsert(pName);
this.eTextInsert.add(lTextInsert);
return lTextInsert;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(" sb.append(");
for (Object oTextInsert : this.eTextInsert) {
sb.append(oTextInsert.toString());
}
sb.append(")");
sb.append(System.getProperty("line.separator"));
return sb.toString();
}
}
|
danielma/react-trello-multiboard | src/components/trello-card/card.js | <gh_stars>10-100
// https://codepen.io/natterstefan/pen/QxJZzW?editors=0110
import React from 'react'
import PropTypes from 'prop-types'
import classNames from 'classnames'
import { get, map, includes } from 'lodash'
import FontAwesomeIcon from '@fortawesome/react-fontawesome'
// clicks on the label should not open a new tab with the TrelloCard
const onClick = (event, callback = () => {}) => {
const classes = get(event, 'target.classList.value') || ''
if (includes(classes, 'labels')) {
event.preventDefault()
callback()
}
}
// TODO
// - handle case when avatarHash is null, use `initials` on user instead
const TrelloCardUI = ({
badges,
boardName,
labels,
members,
minimizeLabels,
name,
shortUrl,
listName,
toggleMinimizeLabels,
}) => (
<a
className="trello-card-wrapper"
href={shortUrl}
onClick={event => onClick(event, toggleMinimizeLabels)}
target="_blank"
>
<div className="trello-card">
<div className="trello-card__content">
<div className="trello-card--labels">
{map(labels, label => (
<span
key={label.id}
className={classNames(
`trello-card--labels-text trello-card--labels-text__${label.color}`,
{
'trello-card--labels-text__minimize': minimizeLabels,
},
)}
title={label.name}
>
{label.name}
</span>
))}
</div>
<div className="trello-card__title">{name}</div>
<div className="trello-card__badges">
{badges &&
badges.description && (
<div>
<FontAwesomeIcon icon={['fa', 'align-left']} size="sm" />
</div>
)}
{badges &&
badges.comments > 0 && (
<div>
<FontAwesomeIcon icon={['fa', 'comment-dots']} size="sm" /> {badges.comments}
</div>
)}
{badges &&
badges.attachments > 0 && (
<div>
<FontAwesomeIcon icon={['fa', 'paperclip']} size="sm" /> {badges.attachments}
</div>
)}
{badges &&
badges.checkItems > 0 && (
<div>
<FontAwesomeIcon icon={['fa', 'check-square']} size="sm" />{' '}
{badges.checkItemsChecked}/{badges.checkItems}
</div>
)}
</div>
<div className="trello-card__members">
<ul>
{map(members, ({ avatarHash, fullName, initials }) => (
<li key={`${shortUrl}-${avatarHash}`}>
<div className="trello-card__member">
{avatarHash ? (
<img
className="trello-card__member--image"
src={`https://trello-avatars.s3.amazonaws.com/${avatarHash}/50.png`}
alt={fullName}
/>
) : (
<span className="trello-card__member--intials">{initials}</span>
)}
</div>
</li>
))}
</ul>
</div>
</div>
<div className="trello-card__board-details">
<div className="trello-card__board-name">{boardName}:</div>
<div className="trello-card__list-name">{listName}</div>
</div>
</div>
</a>
)
TrelloCardUI.displayName = 'TrelloCardUI'
TrelloCardUI.propTypes = {
badges: PropTypes.shape({
description: PropTypes.bool,
comments: PropTypes.number,
attachments: PropTypes.number,
checkItems: PropTypes.number,
checkItemsChecked: PropTypes.number,
}).isRequired,
boardName: PropTypes.string.isRequired,
labels: PropTypes.arrayOf(
PropTypes.shape({
id: PropTypes.string,
name: PropTypes.string,
}),
).isRequired,
listName: PropTypes.string.isRequired,
members: PropTypes.arrayOf(
PropTypes.shape({
avatarHash: PropTypes.string,
fullName: PropTypes.string,
initials: PropTypes.string,
}),
).isRequired,
minimizeLabels: PropTypes.bool,
name: PropTypes.string.isRequired,
shortUrl: PropTypes.string.isRequired,
toggleMinimizeLabels: PropTypes.func,
}
TrelloCardUI.defaultProps = {
minimizeLabels: false,
toggleMinimizeLabels: () => {},
}
export default TrelloCardUI
|
foolite/panda | panda-nets/src/main/java/panda/net/DefaultDatagramSocketFactory.java | package panda.net;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
/***
* DefaultDatagramSocketFactory implements the DatagramSocketFactory interface by simply wrapping
* the java.net.DatagramSocket constructors. It is the default DatagramSocketFactory used by
* {@link panda.net.DatagramSocketClient} implementations.
*
* @see DatagramSocketFactory
* @see DatagramSocketClient
* @see DatagramSocketClient#setDatagramSocketFactory
***/
public class DefaultDatagramSocketFactory implements DatagramSocketFactory {
/***
* Creates a DatagramSocket on the local host at the first available port.
*
* @return a new DatagramSocket
* @exception SocketException If the socket could not be created.
***/
// @Override
public DatagramSocket createDatagramSocket() throws SocketException {
return new DatagramSocket();
}
/***
* Creates a DatagramSocket on the local host at a specified port.
*
* @param port The port to use for the socket.
* @return a new DatagramSocket
* @exception SocketException If the socket could not be created.
***/
// @Override
public DatagramSocket createDatagramSocket(int port) throws SocketException {
return new DatagramSocket(port);
}
/***
* Creates a DatagramSocket at the specified address on the local host at a specified port.
*
* @param port The port to use for the socket.
* @param laddr The local address to use.
* @return a new DatagramSocket
* @exception SocketException If the socket could not be created.
***/
// @Override
public DatagramSocket createDatagramSocket(int port, InetAddress laddr) throws SocketException {
return new DatagramSocket(port, laddr);
}
}
|
StephenTunAung/jTracker | src/main/java/info/jtrac/wicket/yui/YuiPanel.java | <reponame>StephenTunAung/jTracker<filename>src/main/java/info/jtrac/wicket/yui/YuiPanel.java
/*
* Copyright 2002-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package info.jtrac.wicket.yui;
import java.util.HashMap;
import java.util.Map;
import org.apache.wicket.Component;
import org.apache.wicket.behavior.HeaderContributor;
import org.apache.wicket.markup.html.IHeaderContributor;
import org.apache.wicket.markup.html.IHeaderResponse;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.panel.Panel;
/**
* custom wicketized yahoo ui panel widget
*/
public class YuiPanel extends Panel {
public static final String CONTENT_ID = "content";
private WebMarkupContainer dialog;
private Map<String, Object> getDefaultConfig() {
Map<String, Object> map = new HashMap<String, Object>();
map.put("constraintoviewport", true);
map.put("visible", false);
return map;
}
public YuiPanel(String id, String heading, Component content, Map<String, Object> customConfig) {
super(id);
final Map<String, Object> config = getDefaultConfig();
if(customConfig != null) {
config.putAll(customConfig);
}
add(HeaderContributor.forJavaScript("resources/yui/yahoo/yahoo-min.js"));
add(HeaderContributor.forJavaScript("resources/yui/event/event-min.js"));
add(HeaderContributor.forJavaScript("resources/yui/dom/dom-min.js"));
add(HeaderContributor.forJavaScript("resources/yui/dragdrop/dragdrop-min.js"));
add(HeaderContributor.forJavaScript("resources/yui/container/container-min.js"));
add(HeaderContributor.forCss("resources/yui/container/assets/container.css"));
dialog = new WebMarkupContainer("dialog");
dialog.setOutputMarkupId(true);
add(dialog);
dialog.add(new Label("heading", heading));
dialog.add(content);
add(new HeaderContributor(new IHeaderContributor() {
public void renderHead(IHeaderResponse response) {
String markupId = dialog.getMarkupId();
response.renderJavascript("var " + markupId + ";", null);
response.renderOnDomReadyJavascript(markupId + " = new YAHOO.widget.Panel('" + markupId + "',"
+ " " + YuiUtils.getJson(config) + "); " + markupId + ".render()");
}
}));
}
public String getShowScript() {
return dialog.getMarkupId() + ".show();";
}
public String getHideScript() {
return dialog.getMarkupId() + ".hide();";
}
}
|
jaylinhong/jdk14-learn | src/jdk14-source/jdk.internal.vm.compiler/org.graalvm.compiler.hotspot/src/org/graalvm/compiler/hotspot/nodes/MonitorCounterNode.java | /*
* Copyright (c) 2012, 2019, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*/
package org.graalvm.compiler.hotspot.nodes;
import static org.graalvm.compiler.nodeinfo.NodeSize.SIZE_1;
import org.graalvm.compiler.core.common.type.StampFactory;
import org.graalvm.compiler.graph.Node;
import org.graalvm.compiler.graph.NodeClass;
import org.graalvm.compiler.lir.VirtualStackSlot;
import org.graalvm.compiler.nodeinfo.NodeCycles;
import org.graalvm.compiler.nodeinfo.NodeInfo;
import org.graalvm.compiler.nodes.calc.FloatingNode;
import org.graalvm.compiler.nodes.spi.LIRLowerable;
import org.graalvm.compiler.nodes.spi.NodeLIRBuilderTool;
import org.graalvm.compiler.word.Word;
import org.graalvm.compiler.word.WordTypes;
import jdk.vm.ci.meta.Value;
/**
* Node that is used to maintain a stack based counter of how many locks are currently held.
*/
@NodeInfo(cycles = NodeCycles.CYCLES_2, size = SIZE_1)
public final class MonitorCounterNode extends FloatingNode implements LIRLowerable, Node.ValueNumberable {
public static final NodeClass<MonitorCounterNode> TYPE = NodeClass.create(MonitorCounterNode.class);
public MonitorCounterNode(@InjectedNodeParameter WordTypes wordTypes) {
super(TYPE, StampFactory.forKind(wordTypes.getWordKind()));
}
@Override
public void generate(NodeLIRBuilderTool gen) {
assert graph().getNodes().filter(MonitorCounterNode.class).count() == 1 : "monitor counters not canonicalized to single instance";
VirtualStackSlot counter = gen.getLIRGeneratorTool().getResult().getFrameMapBuilder().allocateStackSlots(1);
Value result = gen.getLIRGeneratorTool().emitAddress(counter);
gen.setResult(this, result);
}
@NodeIntrinsic
public static native Word counter();
}
|
jmapi/cdmi-core-monitor | src/main/java/pw/cdmi/om/protocol/smi/quantum/SoftwareIdentity.java | <filename>src/main/java/pw/cdmi/om/protocol/smi/quantum/SoftwareIdentity.java
package pw.cdmi.om.protocol.smi.quantum;
public class SoftwareIdentity {
}
|
aherbert/MFL | mfl-core/src/main/java/us/hebi/matlab/mat/types/AbstractSink.java | /*-
* #%L
* MAT File Library
* %%
* Copyright (C) 2018 HEBI Robotics
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package us.hebi.matlab.mat.types;
import us.hebi.matlab.mat.util.ByteConverter;
import us.hebi.matlab.mat.util.ByteConverters;
import us.hebi.matlab.mat.util.Bytes;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.zip.Deflater;
import java.util.zip.DeflaterOutputStream;
import static us.hebi.matlab.mat.util.Bytes.*;
import static us.hebi.matlab.mat.util.Preconditions.*;
/**
* @author <NAME>
* @since 06 May 2018
*/
public abstract class AbstractSink implements Sink {
@Override
public AbstractSink nativeOrder() {
return order(ByteOrder.nativeOrder());
}
@Override
public AbstractSink order(ByteOrder byteOrder) {
this.byteOrder = checkNotNull(byteOrder);
return this;
}
@Override
public ByteOrder order() {
return byteOrder;
}
@Override
public void writeByte(byte value) throws IOException {
bytes[0] = value;
writeBytes(bytes, 0, 1);
}
@Override
public void writeShort(short value) throws IOException {
byteConverter.putShort(value, order(), bytes, 0);
writeBytes(bytes, 0, SIZEOF_SHORT);
}
@Override
public void writeInt(int value) throws IOException {
byteConverter.putInt(value, order(), bytes, 0);
writeBytes(bytes, 0, SIZEOF_INT);
}
@Override
public void writeLong(long value) throws IOException {
byteConverter.putLong(value, order(), bytes, 0);
writeBytes(bytes, 0, SIZEOF_LONG);
}
@Override
public void writeFloat(float value) throws IOException {
byteConverter.putFloat(value, order(), bytes, 0);
writeBytes(bytes, 0, SIZEOF_FLOAT);
}
@Override
public void writeDouble(double value) throws IOException {
byteConverter.putDouble(value, order(), bytes, 0);
writeBytes(bytes, 0, SIZEOF_DOUBLE);
}
@Override
public void writeByteBuffer(ByteBuffer buffer) throws IOException {
if (buffer.hasArray()) {
// Fast path
int offset = buffer.arrayOffset() + buffer.position();
int length = buffer.remaining();
writeBytes(buffer.array(), offset, length);
buffer.position(buffer.limit());
} else {
// Slow path
while (buffer.hasRemaining()) {
int length = Math.min(buffer.remaining(), bytes.length);
buffer.get(bytes, 0, length);
writeBytes(bytes, 0, length);
}
}
}
@Override
public void writeInputStream(InputStream input, long length) throws IOException {
for (long i = 0; i < length; ) {
int maxN = (int) Math.min((length - i), bytes.length);
int n = input.read(bytes, 0, maxN);
if (n < 0) throw new EOFException();
writeBytes(bytes, 0, n);
i += n;
}
}
@Override
public void writeDataInput(DataInput input, long length) throws IOException {
for (long i = 0; i < length; ) {
int n = (int) Math.min((length - i), bytes.length);
input.readFully(bytes, 0, n);
writeBytes(bytes, 0, n);
i += n;
}
}
@Override
public void writeShorts(short[] buffer, int offset, int length) throws IOException {
for (int i = 0; i < length; ) {
int n = Math.min((length - i) * SIZEOF_SHORT, bytes.length);
for (int j = 0; j < n; j += SIZEOF_SHORT, i++) {
byteConverter.putShort(buffer[offset + i], order(), bytes, j);
}
writeBytes(bytes, 0, n);
}
}
@Override
public void writeInts(int[] buffer, int offset, int length) throws IOException {
for (int i = 0; i < length; ) {
int n = Math.min((length - i) * SIZEOF_INT, bytes.length);
for (int j = 0; j < n; j += SIZEOF_INT, i++) {
byteConverter.putInt(buffer[offset + i], order(), bytes, j);
}
writeBytes(bytes, 0, n);
}
}
@Override
public void writeLongs(long[] buffer, int offset, int length) throws IOException {
for (int i = 0; i < length; ) {
int n = Math.min((length - i) * SIZEOF_LONG, bytes.length);
for (int j = 0; j < n; j += SIZEOF_LONG, i++) {
byteConverter.putLong(buffer[offset + i], order(), bytes, j);
}
writeBytes(bytes, 0, n);
}
}
@Override
public void writeFloats(float[] buffer, int offset, int length) throws IOException {
for (int i = 0; i < length; ) {
int n = Math.min((length - i) * SIZEOF_FLOAT, bytes.length);
for (int j = 0; j < n; j += SIZEOF_FLOAT, i++) {
byteConverter.putFloat(buffer[offset + i], order(), bytes, j);
}
writeBytes(bytes, 0, n);
}
}
@Override
public void writeDoubles(double[] buffer, int offset, int length) throws IOException {
for (int i = 0; i < length; ) {
int n = Math.min((length - i) * SIZEOF_DOUBLE, bytes.length);
for (int j = 0; j < n; j += SIZEOF_DOUBLE, i++) {
byteConverter.putDouble(buffer[offset + i], order(), bytes, j);
}
writeBytes(bytes, 0, n);
}
}
@Override
public Sink writeDeflated(Deflater deflater) {
DeflaterOutputStream deflateStream = new DeflaterOutputStream(streamWrapper, deflater, bytes.length);
int deflateBufferSize = Math.max(1024, bytes.length);
return Sinks.wrapNonSeeking(deflateStream, deflateBufferSize).order(order());
}
private OutputStream streamWrapper = new Sinks.SinkOutputStream(this);
protected AbstractSink(int copyBufferSize) {
// Make sure size is always a multiple of 8, and that it can hold the 116 byte description
int size = Math.max(Bytes.nextPowerOfTwo(copyBufferSize), 256);
this.bytes = new byte[size];
}
private ByteOrder byteOrder = ByteOrder.nativeOrder(); // default to native, same as MATLAB
private final byte[] bytes;
private static final ByteConverter byteConverter = ByteConverters.getFastest();
}
|
ThingIng-projects/ThingIng_M | ThingingCore/thinging-core/src/main/java/com/thinging/project/errors/JobNotExistsException.java | package com.thinging.project.errors;
import com.thinging.project.errors.utils.ErrorCode;
public class JobNotExistsException extends RecordConflictException {
public JobNotExistsException(String message) {
super(ErrorCode.JOB_NOT_EXISTS, message);
}
}
|
TanJay/stratos | extensions/load-balancer/modules/aws-extension/src/main/java/org/apache/stratos/aws/extension/AWSExtensionContext.java | <gh_stars>100-1000
/*
* 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.stratos.aws.extension;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* AWS Load Balancer context to read and store system properties.
*/
public class AWSExtensionContext {
private static final Log log = LogFactory.getLog(AWSExtensionContext.class);
private static volatile AWSExtensionContext context;
private boolean cepStatsPublisherEnabled;
private String thriftReceiverIp;
private String thriftReceiverPort;
private String networkPartitionId;
private String clusterId;
private String serviceName;
private boolean terminateLBsOnExtensionStop;
private boolean terminateLBOnClusterRemoval;
private boolean operatingInVPC;
private boolean enableCrossZoneLoadBalancing;
private AWSExtensionContext() {
this.cepStatsPublisherEnabled = Boolean.getBoolean(Constants.CEP_STATS_PUBLISHER_ENABLED);
this.thriftReceiverIp = System.getProperty(Constants.THRIFT_RECEIVER_IP);
this.thriftReceiverPort = System.getProperty(Constants.THRIFT_RECEIVER_PORT);
this.networkPartitionId = System.getProperty(Constants.NETWORK_PARTITION_ID);
this.clusterId = System.getProperty(Constants.CLUSTER_ID);
this.serviceName = System.getProperty(Constants.SERVICE_NAME);
this.terminateLBsOnExtensionStop = Boolean.getBoolean(Constants.TERMINATE_LBS_ON_EXTENSION_STOP);
this.terminateLBOnClusterRemoval = Boolean.getBoolean(Constants.TERMINATE_LB_ON_CLUSTER_REMOVAL);
this.operatingInVPC = Boolean.getBoolean(Constants.OPERATIMG_IN_VPC);
this.enableCrossZoneLoadBalancing = Boolean.getBoolean(Constants.ENABLE_CROSS_ZONE_LOADBALANCING);
if (log.isDebugEnabled()) {
log.debug(Constants.CEP_STATS_PUBLISHER_ENABLED + " = " + cepStatsPublisherEnabled);
log.debug(Constants.THRIFT_RECEIVER_IP + " = " + thriftReceiverIp);
log.debug(Constants.THRIFT_RECEIVER_PORT + " = " + thriftReceiverPort);
log.debug(Constants.NETWORK_PARTITION_ID + " = " + networkPartitionId);
log.debug(Constants.CLUSTER_ID + " = " + clusterId);
log.debug(Constants.TERMINATE_LBS_ON_EXTENSION_STOP + "=" + terminateLBsOnExtensionStop);
log.debug(Constants.TERMINATE_LB_ON_CLUSTER_REMOVAL + "=" + terminateLBOnClusterRemoval);
log.debug(Constants.OPERATIMG_IN_VPC + "=" + operatingInVPC);
log.debug(Constants.ENABLE_CROSS_ZONE_LOADBALANCING + "=" + enableCrossZoneLoadBalancing);
}
}
public static AWSExtensionContext getInstance() {
if (context == null) {
synchronized (AWSExtensionContext.class) {
if (context == null) {
context = new AWSExtensionContext();
}
}
}
return context;
}
public void validate() {
validateSystemProperty(Constants.CEP_STATS_PUBLISHER_ENABLED);
validateSystemProperty(Constants.CLUSTER_ID);
if (cepStatsPublisherEnabled) {
validateSystemProperty(Constants.THRIFT_RECEIVER_IP);
validateSystemProperty(Constants.THRIFT_RECEIVER_PORT);
validateSystemProperty(Constants.NETWORK_PARTITION_ID);
}
}
private void validateSystemProperty(String propertyName) {
String value = System.getProperty(propertyName);
if (StringUtils.isEmpty(value)) {
throw new RuntimeException("System property was not found: " + propertyName);
}
}
public boolean isCEPStatsPublisherEnabled() {
return cepStatsPublisherEnabled;
}
public String getNetworkPartitionId() {
return networkPartitionId;
}
public String getClusterId() {
return clusterId;
}
public String getServiceName() {
return serviceName;
}
public boolean terminateLBsOnExtensionStop() {
return terminateLBsOnExtensionStop;
}
public boolean terminateLBOnClusterRemoval() {
return terminateLBOnClusterRemoval;
}
public boolean isOperatingInVPC() {
return operatingInVPC;
}
public boolean isCrossZoneLoadBalancingEnabled () {
return enableCrossZoneLoadBalancing;
}
}
|
tylerchen/springmvc-mybatis-v1.0-project | src/main/java/org/iff/infra/util/moduler/TCActionHelper.java | /*******************************************************************************
* Copyright (c) Aug 9, 2015 @author <a href="mailto:<EMAIL>"><NAME></a>.
* All rights reserved.
*
* Contributors:
* <a href="mailto:<EMAIL>"><NAME></a> - initial API and implementation
******************************************************************************/
package org.iff.infra.util.moduler;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.iff.infra.util.HttpHelper;
import org.iff.infra.util.ThreadLocalHelper;
/**
* @author <a href="mailto:<EMAIL>"><NAME></a>
* @since Aug 9, 2015
*/
public class TCActionHelper {
private static final String urlCharset = "UTF-8";
private HttpServletRequest request = null;
private HttpServletResponse response = null;
private Map<String, Object> userAgent = new HashMap<String, Object>();
private Map<String, Object> requestParams = new LinkedHashMap<String, Object>();
public static TCActionHelper create(HttpServletRequest request, HttpServletResponse response) {
TCActionHelper actionHelper = new TCActionHelper();
{
actionHelper.setRequest(request);
actionHelper.setResponse(response);
}
ThreadLocalHelper.set("actionHelper", actionHelper);
return actionHelper;
}
public static TCActionHelper get() {
TCActionHelper actionHelper = ThreadLocalHelper.get("actionHelper");
if (actionHelper == null) {
Map params = ThreadLocalHelper.get("params");
actionHelper = create((HttpServletRequest) params.get("request"),
(HttpServletResponse) params.get("response"));
ThreadLocalHelper.set("actionHelper", actionHelper);
}
return actionHelper;
}
public String urlEncode(String url) {
if (url != null && url.length() > 0) {
try {
return URLEncoder.encode(url, urlCharset);
} catch (Exception e) {
e.printStackTrace();
}
}
return "";
}
public String urlDecode(String url) {
if (url != null && url.length() > 0) {
try {
return URLDecoder.decode(url, urlCharset);
} catch (Exception e) {
e.printStackTrace();
}
}
return "";
}
public TCActionHelper addUrlParam(String key, Object value) {
requestParams.put(key, urlEncode(value == null ? null : String.valueOf(value)));
return this;
}
public TCActionHelper forward(String url) {
if (url != null && url.length() > 0 && requestParams.size() > 0) {
StringBuilder sb = new StringBuilder(512).append(url);
if (url.endsWith("?") || url.endsWith("&")) {
} else if (url.indexOf('?') > -1) {
sb.append('&');
} else {
sb.append('?');
}
for (Entry<String, Object> entry : requestParams.entrySet()) {
sb.append(entry.getKey()).append('=').append(entry.getValue()).append('&');
}
sb.setLength(sb.length() - 1);
url = sb.toString();
}
try {
request.getRequestDispatcher(url == null ? "" : url).forward(request, response);
} catch (Exception e) {
e.printStackTrace();
}
return this;
}
public TCActionHelper redirect(String url) {
if (url != null && url.length() > 0 && requestParams.size() > 0) {
StringBuilder sb = new StringBuilder(512).append(url);
if (url.endsWith("?") || url.endsWith("&")) {
} else if (url.indexOf('?') > -1) {
sb.append('&');
} else {
sb.append('?');
}
for (Entry<String, Object> entry : requestParams.entrySet()) {
sb.append(entry.getKey()).append('=').append(entry.getValue()).append('&');
}
sb.setLength(sb.length() - 1);
url = sb.toString();
}
try {
response.sendRedirect(url == null ? "" : url);
} catch (Exception e) {
e.printStackTrace();
}
return this;
}
public Map<String, Object> userAgent() {
if (userAgent.isEmpty()) {
userAgent.putAll(HttpHelper.userAgent(request.getHeader("User-Agent")));
}
return userAgent;
}
public HttpServletRequest getRequest() {
return request;
}
public void setRequest(HttpServletRequest request) {
this.request = request;
}
public HttpServletResponse getResponse() {
return response;
}
public void setResponse(HttpServletResponse response) {
this.response = response;
}
}
|
zhanzju/bsl | groups/bsl/bslstl/bslstl_sstream.t.cpp | // bslstl_sstream.t.cpp -*-C++-*-
#include <bslstl_sstream.h>
#include <bsls_bsltestutil.h>
#include <stdio.h>
#include <stdlib.h>
//=============================================================================
// TEST PLAN
//-----------------------------------------------------------------------------
// Overview
// --------
// The component under test provides no functionality per se. Its sole purpose
// is to include, in its own header file (for the convenience of
// 'bsl_sstream.h' in package 'bsl+bslhdrs'), the header files of the four
// 'bslstl' components that implement string-based streams. Therefore, it is
// sufficient to verify, via appropriate declarations, that the four header
// files are included as expected.
//-----------------------------------------------------------------------------
// [ 1] BREATHING TEST
//=============================================================================
// STANDARD BDE ASSERT TEST MACRO
//-----------------------------------------------------------------------------
// NOTE: THIS IS A LOW-LEVEL COMPONENT AND MAY NOT USE ANY C++ LIBRARY
// FUNCTIONS, INCLUDING IOSTREAMS.
static int testStatus = 0;
namespace {
void aSsErT(bool b, const char *s, int i) {
if (b) {
printf("Error " __FILE__ "(%d): %s (failed)\n", i, s);
if (testStatus >= 0 && testStatus <= 100) ++testStatus;
}
}
} // close unnamed namespace
//=============================================================================
// STANDARD BDE TEST DRIVER MACROS
//-----------------------------------------------------------------------------
#define ASSERT BSLS_BSLTESTUTIL_ASSERT
#define LOOP_ASSERT BSLS_BSLTESTUTIL_LOOP_ASSERT
#define LOOP0_ASSERT BSLS_BSLTESTUTIL_LOOP0_ASSERT
#define LOOP1_ASSERT BSLS_BSLTESTUTIL_LOOP1_ASSERT
#define LOOP2_ASSERT BSLS_BSLTESTUTIL_LOOP2_ASSERT
#define LOOP3_ASSERT BSLS_BSLTESTUTIL_LOOP3_ASSERT
#define LOOP4_ASSERT BSLS_BSLTESTUTIL_LOOP4_ASSERT
#define LOOP5_ASSERT BSLS_BSLTESTUTIL_LOOP5_ASSERT
#define LOOP6_ASSERT BSLS_BSLTESTUTIL_LOOP6_ASSERT
#define ASSERTV BSLS_BSLTESTUTIL_ASSERTV
#define Q BSLS_BSLTESTUTIL_Q // Quote identifier literally.
#define P BSLS_BSLTESTUTIL_P // Print identifier and value.
#define P_ BSLS_BSLTESTUTIL_P_ // P(X) without '\n'.
#define T_ BSLS_BSLTESTUTIL_T_ // Print a tab (w/o newline).
#define L_ BSLS_BSLTESTUTIL_L_ // current Line number
#define RUN_EACH_TYPE BSLTF_TEMPLATETESTFACILITY_RUN_EACH_TYPE
// ============================================================================
// NEGATIVE-TEST MACRO ABBREVIATIONS
// ----------------------------------------------------------------------------
#define ASSERT_SAFE_PASS(EXPR) BSLS_ASSERTTEST_ASSERT_SAFE_PASS(EXPR)
#define ASSERT_SAFE_FAIL(EXPR) BSLS_ASSERTTEST_ASSERT_SAFE_FAIL(EXPR)
#define ASSERT_PASS(EXPR) BSLS_ASSERTTEST_ASSERT_PASS(EXPR)
#define ASSERT_FAIL(EXPR) BSLS_ASSERTTEST_ASSERT_FAIL(EXPR)
#define ASSERT_OPT_PASS(EXPR) BSLS_ASSERTTEST_ASSERT_OPT_PASS(EXPR)
#define ASSERT_OPT_FAIL(EXPR) BSLS_ASSERTTEST_ASSERT_OPT_FAIL(EXPR)
// ============================================================================
// GLOBAL TEST VALUES
// ----------------------------------------------------------------------------
static bool verbose;
static bool veryVerbose;
static bool veryVeryVerbose;
static bool veryVeryVeryVerbose;
//=============================================================================
// GLOBAL TYPEDEFS/CONSTANTS FOR TESTING
//-----------------------------------------------------------------------------
//=============================================================================
// TEST FACILITIES
//-----------------------------------------------------------------------------
//=============================================================================
// USAGE EXAMPLE
//-----------------------------------------------------------------------------
//=============================================================================
// MAIN PROGRAM
//-----------------------------------------------------------------------------
int main(int argc, char *argv[])
{
int test = argc > 1 ? atoi(argv[1]) : 0;
verbose = argc > 2;
veryVerbose = argc > 3;
veryVeryVerbose = argc > 4;
veryVeryVeryVerbose = argc > 5;
printf("TEST " __FILE__ " CASE %d\n", test);
switch (test) { case 0:
case 1: {
// --------------------------------------------------------------------
// BREATHING TEST:
// Developers' Sandbox.
//
// Plan:
// Define an instance of each of the standard types declared in the
// header files of the four 'bslstl' components that implement
// string-based streams.
//
// Testing:
// This "test" *exercises* basic functionality, but *tests* nothing.
// --------------------------------------------------------------------
if (verbose) printf("\nBREATHING TEST"
"\n==============\n");
bsl::stringbuf stringBuf; (void)stringBuf;
bsl::wstringbuf wstringBuf; (void)wstringBuf;
bsl::istringstream inputStream; (void)inputStream;
bsl::wistringstream winputStream; (void)winputStream;
bsl::ostringstream outputStream; (void)outputStream;
bsl::wostringstream woutputStream; (void)woutputStream;
bsl::stringstream inoutStream; (void)inoutStream;
bsl::wstringstream winoutStream; (void)winoutStream;
} break;
default: {
fprintf(stderr, "WARNING: CASE `%d' NOT FOUND.\n", test);
testStatus = -1;
}
}
if (testStatus > 0) {
fprintf(stderr, "Error, non-zero test status = %d.\n", testStatus);
}
return testStatus;
}
// ----------------------------------------------------------------------------
// Copyright (C) 2013 <NAME>.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
// ----------------------------- END-OF-FILE ----------------------------------
|
kingces95/kingjs | .trash/@kingjs-reflect-define/define-field/construct.js | function createField(target, name, value) {
return { target, name, descriptor: { value } };
}
module.exports = createField;
|
ArboreusSystems/arboreus_examples | objective-c/DetectPermissions/DetectPermissions/DetectPermissions/ViewControllers/MainViewController.h | //
// MainViewController.h
// DetectPermissions
//
// Created by <NAME> on 21.05.2021.
//
#import <UIKit/UIKit.h>
#import "../Definitions/ColorDefinitions.h"
NS_ASSUME_NONNULL_BEGIN
@interface MainViewController : UIViewController
@end
NS_ASSUME_NONNULL_END
|
1446554749/jdk_11_src_read | jdk11/openj9.dtfj/com/ibm/j9ddr/vm29/tools/ddrinteractive/gccheck/ScanFormatter.java | <filename>jdk11/openj9.dtfj/com/ibm/j9ddr/vm29/tools/ddrinteractive/gccheck/ScanFormatter.java
/*******************************************************************************
* Copyright (c) 2001, 2014 IBM Corp. and others
*
* This program and the accompanying materials are made available under
* the terms of the Eclipse Public License 2.0 which accompanies this
* distribution and is available at https://www.eclipse.org/legal/epl-2.0/
* or the Apache License, Version 2.0 which accompanies this distribution and
* is available at https://www.apache.org/licenses/LICENSE-2.0.
*
* This Source Code may also be made available under the following
* Secondary Licenses when the conditions for such availability set
* forth in the Eclipse Public License, v. 2.0 are satisfied: GNU
* General Public License, version 2 with the GNU Classpath
* Exception [1] and GNU General Public License, version 2 with the
* OpenJDK Assembly Exception [2].
*
* [1] https://www.gnu.org/software/classpath/license.html
* [2] http://openjdk.java.net/legal/assembly-exception.html
*
* SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 OR LicenseRef-GPL-2.0 WITH Assembly-exception
*******************************************************************************/
package com.ibm.j9ddr.vm29.tools.ddrinteractive.gccheck;
import com.ibm.j9ddr.vm29.pointer.AbstractPointer;
import com.ibm.j9ddr.vm29.pointer.generated.J9BuildFlags;
class ScanFormatter
{
protected static final int NUMBER_ELEMENTS_DISPLAYED_PER_LINE = 8;
protected long _currentCount = 0;
protected boolean _displayedData = false;
protected CheckReporter _reporter;
public ScanFormatter(Check check, String title, AbstractPointer pointer)
{
_reporter = check.getReporter();
_reporter.println(String.format("<gc check: Start scan %s (%s)>", title, formatPointer(pointer)));
}
public ScanFormatter(Check check, String title)
{
_reporter = check.getReporter();
_reporter.println(String.format("<gc check: Start scan %s>", title));
}
static String formatPointer(AbstractPointer pointer)
{
if(J9BuildFlags.env_data64) {
return String.format("%016X", pointer.getAddress());
} else {
return String.format("%08X", pointer.getAddress());
}
}
public void section(String type)
{
_reporter.println(String.format(" <%s>", type));
_currentCount = 0;
}
public void section(String type, AbstractPointer pointer)
{
_reporter.println(String.format(" <%s (%s)>", type, formatPointer(pointer)));
_currentCount = 0;
}
public void endSection()
{
if((0 != _currentCount) && _displayedData) {
_reporter.println(">");
_currentCount = 0;
}
}
public void entry(AbstractPointer pointer)
{
if(0 == _currentCount) {
_reporter.print(" <");
_displayedData = true;
}
_reporter.print(formatPointer(pointer) + " ");
_currentCount += 1;
if(NUMBER_ELEMENTS_DISPLAYED_PER_LINE == _currentCount) {
_reporter.println(">");
_currentCount = 0;
}
}
public void end(String type, AbstractPointer pointer)
{
if((0 != _currentCount) && _displayedData) {
_reporter.println(">");
}
_reporter.println(String.format("<gc check: End scan %s (%s)>", type, formatPointer(pointer)));
}
public void end(String type)
{
if((0 != _currentCount) && _displayedData) {
_reporter.println(">");
}
_reporter.println(String.format("<gc check: End scan %s>", type));
}
}
|
dwijpr/islam | storage/app/Al-QuranIndonesia_com.andi.alquran.id_source_from_JADX/com/google/android/gms/internal/ka.java | <reponame>dwijpr/islam
package com.google.android.gms.internal;
import com.google.android.gms.ads.formats.NativeCustomTemplateAd.OnCustomTemplateAdLoadedListener;
import com.google.android.gms.internal.jv.C1700a;
@op
public class ka extends C1700a {
private final OnCustomTemplateAdLoadedListener f4589a;
public ka(OnCustomTemplateAdLoadedListener onCustomTemplateAdLoadedListener) {
this.f4589a = onCustomTemplateAdLoadedListener;
}
public void m7064a(jq jqVar) {
this.f4589a.onCustomTemplateAdLoaded(new jr(jqVar));
}
}
|
noeleont/renku-ui | client/src/project/datasets/ProjectDatasets.test.js |
/*!
* Copyright 2020 - Swiss Data Science Center (SDSC)
* A partnership between École Polytechnique Fédérale de Lausanne (EPFL) and
* Eidgenössische Technische Hochschule Zürich (ETHZ).
*
* 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.
*/
/**
* renku-ui
*
* ProjectDatasets.test.js
* Tests for datasets inside projects.
*/
import React from "react";
import ReactDOM from "react-dom";
import { createMemoryHistory } from "history";
import { MemoryRouter } from "react-router-dom";
import { ACCESS_LEVELS, testClient as client } from "../../api-client";
import { StateModel, globalSchema } from "../../model";
import ChangeDataset from "./change/index";
import DatasetImport from "./import/index";
import DatasetsListView from "./DatasetsListView";
import { generateFakeUser } from "../../user/User.test";
describe("rendering", () => {
const model = new StateModel(globalSchema);
let spy = null;
const loggedUser = generateFakeUser();
const fakeHistory = createMemoryHistory({
initialEntries: ["/"],
initialIndex: 0,
});
const migration = { core: { versionUrl: "" } };
fakeHistory.push({
pathname: "/projects/namespace/project-name/datasets/new"
});
beforeEach(() => {
// ckeditor dumps some junk to the console.error. Ignore it.
spy = jest.spyOn(console, "error").mockImplementation(() => { });
});
afterEach(() => {
spy.mockRestore();
});
it("renders datasets list without crashing", () => {
const props = {
client: client,
datasets_kg: [],
datasets: [{
"title": "Test dataset title",
"identifier": "79215657-4319-4fcf-82b9-58267f2a1db8",
"name": "test-dataset-name",
"created_at": "2021-06-04 04:20:24.287936+00:00",
"creators": [{
"name": "<NAME>",
"email": null,
"affiliation": "Some Affiliation",
}]
}],
graphStatus: false,
migration,
user: loggedUser,
visibility: { accessLevel: ACCESS_LEVELS.MAINTAINER }
};
const div = document.createElement("div");
ReactDOM.render(
<MemoryRouter>
<DatasetsListView
{...props}
/>
</MemoryRouter>
, div);
});
it("renders NewDataset form without crashing", () => {
const div = document.createElement("div");
document.body.appendChild(div);
ReactDOM.render(
<MemoryRouter>
<ChangeDataset
client={client}
edit={false}
location={fakeHistory}
maintainer={ACCESS_LEVELS.maintainer}
migration={migration}
model={model}
params={{ UPLOAD_THRESHOLD: { soft: 104857600 } }}
user={loggedUser}
/>
</MemoryRouter>
, div);
});
it("renders DatasetImport form without crashing", () => {
const div = document.createElement("div");
document.body.appendChild(div);
ReactDOM.render(
<MemoryRouter>
<DatasetImport
client={client}
edit={false}
location={fakeHistory}
maintainer={ACCESS_LEVELS.maintainer}
migration={migration}
model={model}
user={loggedUser}
/>
</MemoryRouter>
, div);
});
});
|
bingoohuang/blackcat-server | src/main/java/com/github/bingoohuang/blackcat/server/job/HttpCheckerJob.java | <reponame>bingoohuang/blackcat-server<gh_stars>0
package com.github.bingoohuang.blackcat.server.job;
import com.github.bingoohuang.blackcat.server.base.BlackcatJob;
import com.github.bingoohuang.blackcat.server.base.MsgService;
import com.github.bingoohuang.blackcat.server.base.QuartzScheduler;
import com.github.bingoohuang.utils.net.HttpReq;
import com.google.common.base.Charsets;
import com.google.common.base.Splitter;
import com.google.common.io.Files;
import lombok.SneakyThrows;
import lombok.val;
import org.apache.commons.lang3.StringUtils;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.File;
import java.util.List;
import static org.apache.commons.lang3.StringUtils.INDEX_NOT_FOUND;
import static org.quartz.DateBuilder.futureDate;
import static org.quartz.JobBuilder.newJob;
import static org.quartz.SimpleScheduleBuilder.simpleSchedule;
import static org.quartz.TriggerBuilder.newTrigger;
@Component
public class HttpCheckerJob implements BlackcatJob {
@Autowired MsgService msgService;
@SneakyThrows
public void scheduleJob(QuartzScheduler scheduler) {
val heartbeatJob = createHeartbeatJobDetail();
val heartbeatTrigger = createHeartbeatTrigger();
scheduler.scheduleJob(heartbeatJob, heartbeatTrigger);
}
private JobDetail createHeartbeatJobDetail() {
val job = newJob(HttpCheckerQuartzJob.class).build();
job.getJobDataMap().put("handler", this);
return job;
}
private Trigger createHeartbeatTrigger() {
return newTrigger().withSchedule(
simpleSchedule()
.withIntervalInMinutes(10) // 先写死10分钟
.repeatForever())
.startAt(futureDate(70, DateBuilder.IntervalUnit.SECOND))
.build();
}
public static class HttpCheckerQuartzJob implements Job {
@Override @SneakyThrows
public void execute(JobExecutionContext context) {
val jobDataMap = context.getJobDetail().getJobDataMap();
val handler = (HttpCheckerJob) jobDataMap.get("handler");
handler.checkAllHttps();
}
}
@SneakyThrows
private void checkAllHttps() {
File urlFile = new File("httpchecker.urls");
if (urlFile.exists() && urlFile.isFile()) {
val lines = Files.readLines(urlFile, Charsets.UTF_8);
for (String line : lines) {
checkHttp(line);
}
}
}
Splitter splitter = Splitter.on(",").trimResults();
private void checkHttp(String line) {
if (StringUtils.isEmpty(line)) return;
// name,url
List<String> parts = splitter.splitToList(line);
val name = parts.get(0);
val url = parts.get(1);
val result = new HttpReq(url).get();
if (StringUtils.indexOf(result, name) != INDEX_NOT_FOUND) return;
msgService.sendMsg("HTTP巡检异常", name);
}
}
|
njam/puppet-packages | modules/earlyoom/spec/spec.rb | require 'spec_helper'
describe 'earlyoom' do
describe command('earlyoom -h') do
its(:exit_status) { should eq 1 }
end
describe service('earlyoom') do
it { should be_running }
end
end
|
yeastrc/proxl-gen-import-xml-kojak | src/org/yeastrc/proxl/proxl_gen_import_xml_kojak/kojak_and_percolator/percolator/constants/PercolatorGenImportXML_AnnotationNames_Constants.java | package org.yeastrc.proxl.proxl_gen_import_xml_kojak.kojak_and_percolator.percolator.constants;
/**
* Update DefaultVisibleAnnotationsConstants as needed when change this class
*
*/
public class PercolatorGenImportXML_AnnotationNames_Constants {
// Update DefaultVisibleAnnotationsConstants as needed when change this class
// Peptide and PSM
// Filterable
public static final String ANNOTATION_NAME_Q_VALUE = "q-value";
public static final String ANNOTATION_DESCRIPTION_Q_VALUE = "The minimum false discovery among all predictions with this score or better.";
public static final String ANNOTATION_NAME_P_VALUE = "p-value";
public static final String ANNOTATION_DESCRIPTION_P_VALUE = "The computed p-value.";
public static final String ANNOTATION_NAME_SVM_SCORE = "SVM Score";
public static final String ANNOTATION_DESCRIPTION_SVM_SCORE = "Support vector machine score. The signed distance from x to the decision boundary. More strongly positive scores indicate a more confident prediction.";
public static final String ANNOTATION_NAME_PEP = "PEP";
public static final String ANNOTATION_DESCRIPTION_PEP = "Posterior error probability. The probability that this identification is incorrect.";
// Descriptive
// public static final String ANNOTATION_NAME_CALC_MASS = "Calc Mass";
public static final String ANNOTATION_NAME_SCAN_NUMBER = "Scan Number";
}
|
itonov/Java-Advanced | 01_IntroExercises/src/TriangleArea.java | import java.util.Scanner;
public class TriangleArea {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int x1 = scanner.nextInt();
int y1 = scanner.nextInt();
scanner.nextLine();
int x2 = scanner.nextInt();
int y2 = scanner.nextInt();
scanner.nextLine();
int x3 = scanner.nextInt();
int y3 = scanner.nextInt();
int triangleArea = x1 * (y3 - y2) + x3 * (y2 - y1) + x2 * (y1 - y3);
System.out.println(Math.abs(triangleArea / 2));
}
}
|
andrewsgoetz/Orekit | src/main/java/org/orekit/forces/radiation/KnockeRediffusedForceModel.java | <filename>src/main/java/org/orekit/forces/radiation/KnockeRediffusedForceModel.java
/* Copyright 2002-2021 CS GROUP
* Licensed to CS GROUP (CS) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* CS licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.orekit.forces.radiation;
import java.util.stream.Stream;
import org.hipparchus.Field;
import org.hipparchus.RealFieldElement;
import org.hipparchus.analysis.polynomials.PolynomialFunction;
import org.hipparchus.analysis.polynomials.PolynomialsUtils;
import org.hipparchus.geometry.euclidean.threed.FieldRotation;
import org.hipparchus.geometry.euclidean.threed.FieldVector3D;
import org.hipparchus.geometry.euclidean.threed.Rotation;
import org.hipparchus.geometry.euclidean.threed.RotationConvention;
import org.hipparchus.geometry.euclidean.threed.Vector3D;
import org.hipparchus.util.FastMath;
import org.hipparchus.util.FieldSinCos;
import org.hipparchus.util.SinCos;
import org.orekit.annotation.DefaultDataContext;
import org.orekit.bodies.OneAxisEllipsoid;
import org.orekit.data.DataContext;
import org.orekit.forces.AbstractForceModel;
import org.orekit.frames.FieldTransform;
import org.orekit.frames.Frame;
import org.orekit.frames.Transform;
import org.orekit.propagation.FieldSpacecraftState;
import org.orekit.propagation.SpacecraftState;
import org.orekit.propagation.events.EventDetector;
import org.orekit.propagation.events.FieldEventDetector;
import org.orekit.time.AbsoluteDate;
import org.orekit.time.FieldAbsoluteDate;
import org.orekit.time.TimeScale;
import org.orekit.utils.Constants;
import org.orekit.utils.ExtendedPVCoordinatesProvider;
import org.orekit.utils.ParameterDriver;
/** The Knocke Earth Albedo and IR emission force model.
* <p>
* This model is based on "EARTH RADIATION PRESSURE EFFECTS ON SATELLITES", 1988, by <NAME>, <NAME>, and <NAME>.
* </p> <p>
* This model represents the effects of radiation pressure coming from the Earth.
* It considers Solar radiation which has been reflected by Earth (albedo) and Earth infrared emissions.
* The planet is considered as a sphere and is divided into elementary areas.
* Each elementary area is considered as a plane and emits radiation according to Lambert's law.
* The flux the satellite receives is then equal to the sum of the elementary fluxes coming from Earth.
* </p> <p>
* The radiative model of the satellite, and its ability to diffuse, reflect or absorb radiation is handled
* by a {@link RadiationSensitive radiation sensitive model}.
* </p> <p>
* <b>Caution:</b> The spacecraft state must be defined in an Earth centered frame.
* </p>
*
* @author <NAME>
* @since 10.3
*/
public class KnockeRediffusedForceModel extends AbstractForceModel {
/** Two PI. */
private static final double TWO_PI = 2.0 * FastMath.PI;
/** PI over 2. */
private static final double PI_OVER_2 = 0.5 * FastMath.PI;
/** Earth rotation around Sun pulsation in rad/sec. */
private static final double EARTH_AROUND_SUN_PULSATION = TWO_PI / Constants.JULIAN_YEAR;
/** Coefficient for solar irradiance computation. */
private static final double ES_COEFF = 4.5606E-6;
/** First coefficient for albedo computation. */
private static final double A0 = 0.34;
/** Second coefficient for albedo computation. */
private static final double C0 = 0.;
/** Third coefficient for albedo computation. */
private static final double C1 = 0.10;
/** Fourth coefficient for albedo computation. */
private static final double C2 = 0.;
/** Fifth coefficient for albedo computation. */
private static final double A2 = 0.29;
/** First coefficient for Earth emissivity computation. */
private static final double E0 = 0.68;
/** Second coefficient for Earth emissivity computation. */
private static final double K0 = 0.;
/** Third coefficient for Earth emissivity computation. */
private static final double K1 = -0.07;
/** Fourth coefficient for Earth emissivity computation. */
private static final double K2 = 0.;
/** Fifth coefficient for Earth emissivity computation. */
private static final double E2 = -0.18;
/** Sun model. */
private final ExtendedPVCoordinatesProvider sun;
/** Spacecraft. */
private final RadiationSensitive spacecraft;
/** Angular resolution for emissivity and albedo computation in rad. */
private final double angularResolution;
/** Earth equatorial radius in m. */
private double equatorialRadius;
/** Reference date for periodic terms: December 22nd 1981.
* Without more precision, the choice is to set it at midnight, UTC. */
private final AbsoluteDate referenceEpoch;
/** Default Constructor.
* <p>This constructor uses the {@link DataContext#getDefault() default data context}</p>.
* @param sun Sun model
* @param spacecraft the object physical and geometrical information
* @param equatorialRadius the Earth equatorial radius in m
* @param angularResolution angular resolution in rad
*/
@DefaultDataContext
public KnockeRediffusedForceModel (final ExtendedPVCoordinatesProvider sun,
final RadiationSensitive spacecraft,
final double equatorialRadius,
final double angularResolution) {
this(sun, spacecraft, equatorialRadius, angularResolution, DataContext.getDefault().getTimeScales().getUTC());
}
/** General constructor.
* @param sun Sun model
* @param spacecraft the object physical and geometrical information
* @param equatorialRadius the Earth equatorial radius in m
* @param angularResolution angular resolution in rad
* @param utc the UTC time scale to define reference epoch
*/
public KnockeRediffusedForceModel (final ExtendedPVCoordinatesProvider sun,
final RadiationSensitive spacecraft,
final double equatorialRadius,
final double angularResolution,
final TimeScale utc) {
this.sun = sun;
this.spacecraft = spacecraft;
this.equatorialRadius = equatorialRadius;
this.angularResolution = angularResolution;
this.referenceEpoch = new AbsoluteDate(1981, 12, 22, 0, 0, 0.0, utc);
}
/** {@inheritDoc} */
@Override
public boolean dependsOnPositionOnly() {
return false;
}
/** {@inheritDoc} */
@Override
public Stream<EventDetector> getEventsDetectors() {
return Stream.of();
}
/** {@inheritDoc} */
@Override
public <T extends RealFieldElement<T>> Stream<FieldEventDetector<T>> getFieldEventsDetectors(final Field<T> field) {
return Stream.of();
}
/** {@inheritDoc} */
@Override
public Vector3D acceleration(final SpacecraftState s,
final double[] parameters) {
// Get date
final AbsoluteDate date = s.getDate();
// Get frame
final Frame frame = s.getFrame();
// Get satellite position
final Vector3D satellitePosition = s.getPVCoordinates().getPosition();
// Get Sun position
final Vector3D sunPosition = sun.getPVCoordinates(date, frame).getPosition();
// Get spherical Earth model
final OneAxisEllipsoid earth = new OneAxisEllipsoid(equatorialRadius, 0.0, frame);
// Project satellite on Earth as vector
final Vector3D projectedToGround = satellitePosition.normalize().scalarMultiply(equatorialRadius);
// Get elementary vector east for Earth browsing using rotations
final Vector3D east = earth.transform(satellitePosition, frame, date).getEast();
// Initialize rediffused flux with elementary flux coming from the circular area around the projected satellite
final double centerArea = TWO_PI * equatorialRadius * equatorialRadius *
(1.0 - FastMath.cos(angularResolution));
Vector3D rediffusedFlux = computeElementaryFlux(s, projectedToGround, sunPosition, earth, centerArea);
// Sectorize the part of Earth which is seen by the satellite into crown sectors with constant angular resolution
for (double eastAxisOffset = 1.5 * angularResolution;
eastAxisOffset < FastMath.asin(equatorialRadius / satellitePosition.getNorm());
eastAxisOffset = eastAxisOffset + angularResolution) {
// Build rotation transformations to get first crown elementary sector center
final Transform eastRotation = new Transform(date,
new Rotation(east, eastAxisOffset, RotationConvention.VECTOR_OPERATOR));
// Get first elementary crown sector center
final Vector3D firstCrownSectorCenter = eastRotation.transformPosition(projectedToGround);
// Browse the entire crown
for (double radialAxisOffset = 0.5 * angularResolution;
radialAxisOffset < TWO_PI;
radialAxisOffset = radialAxisOffset + angularResolution) {
// Build rotation transformations to get elementary area center
final Transform radialRotation = new Transform(date,
new Rotation(projectedToGround, radialAxisOffset, RotationConvention.VECTOR_OPERATOR));
// Get current elementary crown sector center
final Vector3D currentCenter = radialRotation.transformPosition(firstCrownSectorCenter);
// Compute current elementary crown sector area, it results of the integration of an elementary crown sector
// over the angular resolution
final double sectorArea = equatorialRadius * equatorialRadius *
2.0 * angularResolution * FastMath.sin(0.5 * angularResolution) * FastMath.sin(eastAxisOffset);
// Add current sector contribution to total rediffused flux
rediffusedFlux = rediffusedFlux.add(computeElementaryFlux(s, currentCenter, sunPosition, earth, sectorArea));
}
}
return spacecraft.radiationPressureAcceleration(date, frame, satellitePosition, s.getAttitude().getRotation(),
s.getMass(), rediffusedFlux, parameters);
}
/** {@inheritDoc} */
@Override
public <T extends RealFieldElement<T>> FieldVector3D<T> acceleration(final FieldSpacecraftState<T> s,
final T[] parameters) {
// Get date
final FieldAbsoluteDate<T> date = s.getDate();
// Get frame
final Frame frame = s.getFrame();
// Get zero
final T zero = date.getField().getZero();
// Get satellite position
final FieldVector3D<T> satellitePosition = s.getPVCoordinates().getPosition();
// Get Sun position
final FieldVector3D<T> sunPosition = sun.getPVCoordinates(date, frame).getPosition();
// Get spherical Earth model
final OneAxisEllipsoid earth = new OneAxisEllipsoid(equatorialRadius, 0.0, frame);
// Project satellite on Earth as vector
final FieldVector3D<T> projectedToGround = satellitePosition.normalize().scalarMultiply(equatorialRadius);
// Get elementary vector east for Earth browsing using rotations
final FieldVector3D<T> east = earth.transform(satellitePosition, frame, date).getEast();
// Initialize rediffused flux with elementary flux coming from the circular area around the projected satellite
final T centerArea = zero.add(TWO_PI * equatorialRadius * equatorialRadius *
(1.0 - FastMath.cos(angularResolution)));
FieldVector3D<T> rediffusedFlux = computeElementaryFlux(s, projectedToGround, sunPosition, earth, centerArea);
// Sectorize the part of Earth which is seen by the satellite into crown sectors with constant angular resolution
for (double eastAxisOffset = 1.5 * angularResolution;
eastAxisOffset < FastMath.asin(equatorialRadius / satellitePosition.getNorm().getReal());
eastAxisOffset = eastAxisOffset + angularResolution) {
// Build rotation transformations to get first crown elementary sector center
final FieldTransform<T> eastRotation = new FieldTransform<>(date,
new FieldRotation<>(east,
zero.add(eastAxisOffset),
RotationConvention.VECTOR_OPERATOR));
// Get first elementary crown sector center
final FieldVector3D<T> firstCrownSectorCenter = eastRotation.transformPosition(projectedToGround);
// Browse the entire crown
for (double radialAxisOffset = 0.5 * angularResolution;
radialAxisOffset < TWO_PI;
radialAxisOffset = radialAxisOffset + angularResolution) {
// Build rotation transformations to get elementary area center
final FieldTransform<T> radialRotation = new FieldTransform<>(date,
new FieldRotation<>(projectedToGround,
zero.add(radialAxisOffset),
RotationConvention.VECTOR_OPERATOR));
// Get current elementary crown sector center
final FieldVector3D<T> currentCenter = radialRotation.transformPosition(firstCrownSectorCenter);
// Compute current elementary crown sector area, it results of the integration of an elementary crown sector
// over the angular resolution
final T sectorArea = zero.add(equatorialRadius * equatorialRadius *
2.0 * angularResolution * FastMath.sin(0.5 * angularResolution) * FastMath.sin(eastAxisOffset));
// Add current sector contribution to total rediffused flux
rediffusedFlux = rediffusedFlux.add(computeElementaryFlux(s, currentCenter, sunPosition, earth, sectorArea));
}
}
return spacecraft.radiationPressureAcceleration(date, frame, satellitePosition, s.getAttitude().getRotation(),
s.getMass(), rediffusedFlux, parameters);
}
/** {@inheritDoc} */
@Override
public ParameterDriver[] getParametersDrivers() {
return spacecraft.getRadiationParametersDrivers();
}
/** Compute Earth albedo.
* Albedo value represents the fraction of solar radiative flux that is reflected by Earth.
* Its value is in [0;1].
* @param date the date
* @param phi the equatorial latitude in rad
* @return the albedo in [0;1]
*/
private double computeAlbedo(final AbsoluteDate date, final double phi) {
// Get duration since coefficient reference epoch
final double deltaT = date.durationFrom(referenceEpoch);
// Compute 1rst Legendre polynomial coeficient
final SinCos sc = FastMath.sinCos(EARTH_AROUND_SUN_PULSATION * deltaT);
final double A1 = C0 +
C1 * sc.cos() +
C2 * sc.sin();
// Get 1rst and 2nd order Legendre polynomials
final PolynomialFunction firstLegendrePolynomial = PolynomialsUtils.createLegendrePolynomial(1);
final PolynomialFunction secondLegendrePolynomial = PolynomialsUtils.createLegendrePolynomial(2);
// Get latitude sinus
final double sinPhi = FastMath.sin(phi);
// Compute albedo
return A0 +
A1 * firstLegendrePolynomial.value(sinPhi) +
A2 * secondLegendrePolynomial.value(sinPhi);
}
/** Compute Earth albedo.
* Albedo value represents the fraction of solar radiative flux that is reflected by Earth.
* Its value is in [0;1].
* @param date the date
* @param phi the equatorial latitude in rad
* @param <T> extends RealFieldElement
* @return the albedo in [0;1]
*/
private <T extends RealFieldElement<T>> T computeAlbedo(final FieldAbsoluteDate<T> date, final T phi) {
// Get duration since coefficient reference epoch
final T deltaT = date.durationFrom(referenceEpoch);
// Compute 1rst Legendre polynomial coeficient
final FieldSinCos<T> sc = FastMath.sinCos(deltaT.multiply(EARTH_AROUND_SUN_PULSATION));
final T A1 = sc.cos().multiply(C1).add(
sc.sin().multiply(C2)).add(C0);
// Get 1rst and 2nd order Legendre polynomials
final PolynomialFunction firstLegendrePolynomial = PolynomialsUtils.createLegendrePolynomial(1);
final PolynomialFunction secondLegendrePolynomial = PolynomialsUtils.createLegendrePolynomial(2);
// Get latitude sinus
final T sinPhi = FastMath.sin(phi);
// Compute albedo
return firstLegendrePolynomial.value(sinPhi).multiply(A1).add(
secondLegendrePolynomial.value(sinPhi).multiply(A2)).add(A0);
}
/** Compute Earth emisivity.
* Emissivity is used to compute the infrared flux that is emitted by Earth.
* Its value is in [0;1].
* @param date the date
* @param phi the equatorial latitude in rad
* @return the emissivity in [0;1]
*/
private double computeEmissivity(final AbsoluteDate date, final double phi) {
// Get duration since coefficient reference epoch
final double deltaT = date.durationFrom(referenceEpoch);
// Compute 1rst Legendre polynomial coefficient
final SinCos sc = FastMath.sinCos(EARTH_AROUND_SUN_PULSATION * deltaT);
final double E1 = K0 +
K1 * sc.cos() +
K2 * sc.sin();
// Get 1rst and 2nd order Legendre polynomials
final PolynomialFunction firstLegendrePolynomial = PolynomialsUtils.createLegendrePolynomial(1);
final PolynomialFunction secondLegendrePolynomial = PolynomialsUtils.createLegendrePolynomial(2);
// Get latitude sinus
final double sinPhi = FastMath.sin(phi);
// Compute albedo
return E0 +
E1 * firstLegendrePolynomial.value(sinPhi) +
E2 * secondLegendrePolynomial.value(sinPhi);
}
/** Compute Earth emisivity.
* Emissivity is used to compute the infrared flux that is emitted by Earth.
* Its value is in [0;1].
* @param date the date
* @param phi the equatorial latitude in rad
* @param <T> extends RealFieldElement
* @return the emissivity in [0;1]
*/
private <T extends RealFieldElement<T>> T computeEmissivity(final FieldAbsoluteDate<T> date, final T phi) {
// Get duration since coefficient reference epoch
final T deltaT = date.durationFrom(referenceEpoch);
// Compute 1rst Legendre polynomial coeficient
final FieldSinCos<T> sc = FastMath.sinCos(deltaT.multiply(EARTH_AROUND_SUN_PULSATION));
final T E1 = sc.cos().multiply(K1).add(
sc.sin().multiply(K2)).add(K0);
// Get 1rst and 2nd order Legendre polynomials
final PolynomialFunction firstLegendrePolynomial = PolynomialsUtils.createLegendrePolynomial(1);
final PolynomialFunction secondLegendrePolynomial = PolynomialsUtils.createLegendrePolynomial(2);
// Get latitude sinus
final T sinPhi = FastMath.sin(phi);
// Compute albedo
return firstLegendrePolynomial.value(sinPhi).multiply(E1).add(
secondLegendrePolynomial.value(sinPhi).multiply(E2)).add(E0);
}
/** Compute total solar flux impacting Earth.
* @param sunPosition the Sun position in an Earth centered frame
* @return the total solar flux impacting Earth in J/m^3
*/
private double computeSolarFlux(final Vector3D sunPosition) {
// Compute Earth - Sun distance in UA
final double earthSunDistance = sunPosition.getNorm() / Constants.JPL_SSD_ASTRONOMICAL_UNIT;
// Compute Solar flux
return ES_COEFF * Constants.SPEED_OF_LIGHT / (earthSunDistance * earthSunDistance);
}
/** Compute total solar flux impacting Earth.
* @param sunPosition the Sun position in an Earth centered frame
* @param <T> extends RealFieldElement
* @return the total solar flux impacting Earth in J/m^3
*/
private <T extends RealFieldElement<T>> T computeSolarFlux(final FieldVector3D<T> sunPosition) {
// Compute Earth - Sun distance in UA
final T earthSunDistance = sunPosition.getNorm().divide(Constants.JPL_SSD_ASTRONOMICAL_UNIT);
// Compute Solar flux
return earthSunDistance.multiply(earthSunDistance).reciprocal().multiply(ES_COEFF * Constants.SPEED_OF_LIGHT);
}
/** Compute elementary rediffused flux on satellite.
* @param state the current spacecraft state
* @param elementCenter the position of the considered area center
* @param sunPosition the position of the Sun in the spacecraft frame
* @param earth the Earth model
* @param elementArea the area of the current element
* @return the rediffused flux from considered element on the spacecraft
*/
private Vector3D computeElementaryFlux(final SpacecraftState state,
final Vector3D elementCenter,
final Vector3D sunPosition,
final OneAxisEllipsoid earth,
final double elementArea) {
// Get satellite position
final Vector3D satellitePosition = state.getPVCoordinates().getPosition();
// Get current date
final AbsoluteDate date = state.getDate();
// Get frame
final Frame frame = state.getFrame();
// Get solar flux impacting Earth
final double solarFlux = computeSolarFlux(sunPosition);
// Get satellite viewing angle as seen from current elementary area
final double alpha = Vector3D.angle(elementCenter, satellitePosition);
// Check that satellite sees the current area
if (FastMath.abs(alpha) < PI_OVER_2) {
// Get current elementary area center latitude
final double currentLatitude = earth.transform(elementCenter, frame, date).getLatitude();
// Compute Earth emissivity value
final double e = computeEmissivity(date, currentLatitude);
// Initialize albedo
double a = 0.0;
// Check if elementary area is in day light
final double sunAngle = Vector3D.angle(elementCenter, sunPosition);
if (FastMath.abs(sunAngle) < PI_OVER_2) {
// Elementary area is in day light, compute albedo value
a = computeAlbedo(date, currentLatitude);
}
// Compute elementary area contribution to rediffused flux
final double albedoAndIR = a * solarFlux * FastMath.cos(sunAngle) +
e * solarFlux * 0.25;
// Compute elementary area - satellite vector and distance
final Vector3D r = satellitePosition.subtract(elementCenter);
final double rNorm = r.getNorm();
// Compute attenuated projected elemetary area vector
final Vector3D projectedAreaVector = r.scalarMultiply(elementArea * FastMath.cos(alpha) /
(FastMath.PI * rNorm * rNorm * rNorm));
// Compute elementary radiation flux from current elementary area
return projectedAreaVector.scalarMultiply(albedoAndIR / Constants.SPEED_OF_LIGHT);
} else {
// Spacecraft does not see the elementary area
return new Vector3D(0.0, 0.0, 0.0);
}
}
/** Compute elementary rediffused flux on satellite.
* @param state the current spacecraft state
* @param elementCenter the position of the considered area center
* @param sunPosition the position of the Sun in the spacecraft frame
* @param earth the Earth model
* @param elementArea the area of the current element
* @param <T> extends RealFieldElement
* @return the rediffused flux from considered element on the spacecraft
*/
private <T extends RealFieldElement<T>> FieldVector3D<T> computeElementaryFlux(final FieldSpacecraftState<T> state,
final FieldVector3D<T> elementCenter,
final FieldVector3D<T> sunPosition,
final OneAxisEllipsoid earth,
final T elementArea) {
// Get satellite position
final FieldVector3D<T> satellitePosition = state.getPVCoordinates().getPosition();
// Get current date
final FieldAbsoluteDate<T> date = state.getDate();
// Get frame
final Frame frame = state.getFrame();
// Get zero
final T zero = date.getField().getZero();
// Get solar flux impacting Earth
final T solarFlux = computeSolarFlux(sunPosition);
// Get satellite viewing angle as seen from current elementary area
final T alpha = FieldVector3D.angle(elementCenter, satellitePosition);
// Check that satellite sees the current area
if (FastMath.abs(alpha).getReal() < PI_OVER_2) {
// Get current elementary area center latitude
final T currentLatitude = earth.transform(elementCenter, frame, date).getLatitude();
// Compute Earth emissivity value
final T e = computeEmissivity(date, currentLatitude);
// Initialize albedo
T a = zero;
// Check if elementary area is in day light
final T sunAngle = FieldVector3D.angle(elementCenter, sunPosition);
if (FastMath.abs(sunAngle).getReal() < PI_OVER_2) {
// Elementary area is in day light, compute albedo value
a = computeAlbedo(date, currentLatitude);
}
// Compute elementary area contribution to rediffused flux
final T albedoAndIR = a.multiply(solarFlux).multiply(FastMath.cos(sunAngle)).add(
e.multiply(solarFlux).multiply(0.25));
// Compute elementary area - satellite vector and distance
final FieldVector3D<T> r = satellitePosition.subtract(elementCenter);
final T rNorm = r.getNorm();
// Compute attenuated projected elemetary area vector
final FieldVector3D<T> projectedAreaVector = r.scalarMultiply(elementArea.multiply(FastMath.cos(alpha)).divide(
rNorm.multiply(rNorm).multiply(rNorm).multiply(FastMath.PI)));
// Compute elementary radiation flux from current elementary area
return projectedAreaVector.scalarMultiply(albedoAndIR.divide(Constants.SPEED_OF_LIGHT));
} else {
// Spacecraft does not see the elementary area
return new FieldVector3D<T>(zero, zero, zero);
}
}
}
|
mangarme/mads-todolist | app/models/Proyecto.java | package models;
import play.data.validation.Constraints;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
@Entity
public class Proyecto {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
public Integer id;
@Constraints.Required
public String nombre;
public String descripcion;
@ManyToOne
@JoinColumn(name = "usuarioId")
public Usuario usuario;
@OneToMany(mappedBy = "proyecto")
public List<Tarea> tareas = new ArrayList<Tarea>();
@OneToMany(mappedBy="proyecto")
public List<Comentario> comentarios = new ArrayList<Comentario>();
@ManyToMany(mappedBy="colaboraciones")
public List<Usuario> colaboradores = new ArrayList<Usuario>();
// Un constructor vacío necesario para JPA
public Proyecto() {
}
// Un constructor a partir del nombre
public Proyecto( String nombre ) {
this.nombre = nombre;
}
public Boolean propietario( int idUsuario ) {
return usuario.id == idUsuario;
}
public Boolean colaborador( int idUsuario ) {
for( Usuario colaborador: colaboradores ) {
if( colaborador.id == idUsuario ) {
return true;
}
}
return false;
}
public Proyecto copy() {
Proyecto nuevo = new Proyecto( this.nombre );
nuevo.id = this.id;
nuevo.usuario = this.usuario;
nuevo.tareas = this.tareas;
nuevo.comentarios = this.comentarios;
nuevo.colaboradores = this.colaboradores;
return nuevo;
}
@Override
public int hashCode() {
final int prime = 31;
int result = prime + ((nombre == null) ? 0 : nombre.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (getClass() != obj.getClass()) return false;
Proyecto other = (Proyecto) obj;
// Si tenemos los ID, comparamos por ID
if (id != null && other.id != null)
return (id == other.id);
// sino comparamos por campos obligatorios
else {
if (nombre == null) {
if (other.nombre != null) return false;
} else if (!nombre.equals(other.nombre)) return false;
}
return true;
}
public String toString() {
return String.format("Proyecto id: %s nombre: %s", id, nombre);
}
}
|
williamweber2/apidoc | lib/parsers/api_example.js | <filename>lib/parsers/api_example.js
function parse(content, source)
{
// Trim
source = source.replace(/^\s+|\s+$/g, "");
var title = "";
var text = "";
var type;
// Search for [@apiexample title] and content
var parseRegExp = /^(@\w*)?\s?(?:(?:\{(.+?)\})\s*)?(.*)$/gm;
var matches;
while(matches = parseRegExp.exec(source))
{
if(matches[1] && matches[3]) title += matches[3]; // @apiExample and title in the same line
if(matches[2]) type = matches[2];
else if(matches[3]) text += matches[3] + "\n";
} // while
if(text.length === 0) return null;
return {
title: title,
content: text,
type: type || "json"
};
} // parse
function pushTo()
{
return "local.examples";
}
/**
* Exports.
*/
module.exports = {
parse: parse,
pushTo: pushTo
}; |
MiguelJG/TFG | jgrapht-1.3.0/source/jgrapht-core/src/main/java/org/jgrapht/alg/color/GreedyColoring.java | /*
* (C) Copyright 2017-2018, by <NAME> and Contributors.
*
* JGraphT : a free Java graph-theory library
*
* See the CONTRIBUTORS.md file distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0, or the
* GNU Lesser General Public License v2.1 or later
* which is available at
* http://www.gnu.org/licenses/old-licenses/lgpl-2.1-standalone.html.
*
* SPDX-License-Identifier: EPL-2.0 OR LGPL-2.1-or-later
*/
package org.jgrapht.alg.color;
import org.jgrapht.*;
import org.jgrapht.alg.interfaces.*;
import java.util.*;
/**
* The greedy coloring algorithm.
*
* <p>
* The algorithm iterates over all vertices and assigns the smallest possible color that is not used
* by any neighbors. Subclasses may provide a different vertex ordering.
*
* @param <V> the graph vertex type
* @param <E> the graph edge type
*
* @author <NAME>
*/
public class GreedyColoring<V, E>
implements
VertexColoringAlgorithm<V>
{
/**
* Error message if the input graph contains self-loops.
*/
protected static final String SELF_LOOPS_NOT_ALLOWED = "Self-loops not allowed";
/**
* The input graph
*/
protected final Graph<V, E> graph;
/**
* Construct a new coloring algorithm.
*
* @param graph the input graph
*/
public GreedyColoring(Graph<V, E> graph)
{
this.graph = Objects.requireNonNull(graph, "Graph cannot be null");
}
/**
* Get the ordering of the vertices used by the algorithm.
*
* @return the ordering of the vertices used by the algorithm
*/
protected Iterable<V> getVertexOrdering()
{
return graph.vertexSet();
}
/**
* {@inheritDoc}
*/
@Override
public Coloring<V> getColoring()
{
int maxColor = -1;
Map<V, Integer> colors = new HashMap<>();
Set<Integer> used = new HashSet<>();
for (V v : getVertexOrdering()) {
// find used colors
for (E e : graph.edgesOf(v)) {
V u = Graphs.getOppositeVertex(graph, e, v);
if (v.equals(u)) {
throw new IllegalArgumentException(SELF_LOOPS_NOT_ALLOWED);
}
if (colors.containsKey(u)) {
used.add(colors.get(u));
}
}
// find first free
int candidate = 0;
while (used.contains(candidate)) {
candidate++;
}
used.clear();
// set color
colors.put(v, candidate);
maxColor = Math.max(maxColor, candidate);
}
return new ColoringImpl<>(colors, maxColor + 1);
}
}
|
murdinc/awsm | models/bucket.go | package models
import "time"
// Bucket represents an S3 Bucket
type Bucket struct {
Name string `json:"name" awsmTable:"Name"`
CreationDate time.Time `json:"createDate" awsmTable:"Created"`
}
|
fieldenms/ | platform-web-ui/src/main/java/ua/com/fielden/platform/web/layout/api/impl/ContainerCellConfig.java | package ua.com.fielden.platform.web.layout.api.impl;
import java.util.ArrayList;
import ua.com.fielden.platform.dom.DomElement;
import ua.com.fielden.platform.web.layout.api.ILayoutCell;
public class ContainerCellConfig extends ContainerConfig implements ILayoutCell {
ContainerCellConfig() {
super(new ArrayList<>(), 0);
}
@Override
public ContainerRepeatConfig cell(final ContainerConfig container, final FlexLayoutConfig layout) {
cells.add(new CellConfig(container, layout));
return new ContainerRepeatConfig(cells);
}
@Override
public ContainerRepeatConfig cell(final ContainerConfig container) {
cells.add(new CellConfig(container));
return new ContainerRepeatConfig(cells);
}
@Override
public ContainerRepeatConfig cell(final FlexLayoutConfig layout) {
cells.add(new CellConfig(layout));
return new ContainerRepeatConfig(cells);
}
@Override
public ContainerRepeatConfig cell() {
cells.add(new CellConfig());
return new ContainerRepeatConfig(cells);
}
@Override
public ContainerRepeatConfig skip(final FlexLayoutConfig layout) {
cells.add(new CellConfig(layout, "skip"));
return new ContainerRepeatConfig(cells);
}
@Override
public ContainerRepeatConfig skip() {
cells.add(new CellConfig("skip"));
return new ContainerRepeatConfig(cells);
}
@Override
public ContainerRepeatConfig select(final String attribute, final String value, final FlexLayoutConfig layout) {
cells.add(new CellConfig(layout, "select:" + attribute + "=" + value));
return new ContainerRepeatConfig(cells);
}
@Override
public ContainerRepeatConfig select(final String attribute, final String value) {
cells.add(new CellConfig("select:" + attribute + "=" + value));
return new ContainerRepeatConfig(cells);
}
@Override
public ContainerRepeatConfig html(final DomElement dom, final FlexLayoutConfig layout) {
cells.add(new CellConfig(dom, layout));
return new ContainerRepeatConfig(cells);
}
@Override
public ContainerRepeatConfig html(final DomElement dom) {
cells.add(new CellConfig(dom));
return new ContainerRepeatConfig(cells);
}
@Override
public ContainerRepeatConfig html(final String html, final FlexLayoutConfig layout) {
cells.add(new CellConfig(layout, "html:" + html));
return new ContainerRepeatConfig(cells);
}
@Override
public ContainerRepeatConfig html(final String html) {
cells.add(new CellConfig("html:" + html));
return new ContainerRepeatConfig(cells);
}
@Override
public ContainerRepeatConfig subheader(final String title, final FlexLayoutConfig layout) {
cells.add(new CellConfig(layout, "subheader:" + title));
return new ContainerRepeatConfig(cells);
}
@Override
public ContainerRepeatConfig subheader(final String title) {
cells.add(new CellConfig("subheader:" + title));
return new ContainerRepeatConfig(cells);
}
@Override
public ContainerRepeatConfig subheaderOpen(final String title, final FlexLayoutConfig layout) {
cells.add(new CellConfig(layout, "subheader-open:" + title));
return new ContainerRepeatConfig(cells);
}
@Override
public ContainerRepeatConfig subheaderOpen(final String title) {
cells.add(new CellConfig("subheader-open:" + title));
return new ContainerRepeatConfig(cells);
}
@Override
public ContainerRepeatConfig subheaderClosed(final String title, final FlexLayoutConfig layout) {
cells.add(new CellConfig(layout, "subheader-closed:" + title));
return new ContainerRepeatConfig(cells);
}
@Override
public ContainerRepeatConfig subheaderClosed(final String title) {
cells.add(new CellConfig("subheader-closed:" + title));
return new ContainerRepeatConfig(cells);
}
}
|
pupper68k/arcusplatform | platform/arcus-lib/src/main/java/com/iris/core/protocol/ipcd/IpcdDeviceDao.java | <reponame>pupper68k/arcusplatform
/*
* Copyright 2019 Arcus Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.iris.core.protocol.ipcd;
import java.util.UUID;
import java.util.stream.Stream;
import com.iris.core.protocol.ipcd.exceptions.IpcdDaoException;
import com.iris.messages.address.Address;
import com.iris.platform.partition.PlatformPartition;
import com.iris.protocol.ipcd.IpcdDevice;
import com.iris.protocol.ipcd.message.model.Device;
public interface IpcdDeviceDao {
IpcdDevice findByProtocolAddress(String address);
IpcdDevice findByProtocolAddress(Address address);
IpcdDevice save(IpcdDevice ipcdDevice);
void delete(IpcdDevice ipcdDevice);
/**
* Returns a stream of IpcdDevice objects, the entries in this stream may be loaded
* lazily as the stream is processed.
* @param partitionId
* @return
*/
Stream<IpcdDevice> streamByPartitionId(int partitionId);
default Stream<IpcdDevice> streamByPartition(PlatformPartition partition) { return streamByPartitionId(partition.getId()); }
String claimAndGetProtocolAddress(Device d, UUID accountId, UUID placeId) throws IpcdDaoException;
void completeRegistration(String protocolAddress, UUID placeId, String driverAddress) throws IpcdDaoException;
void clearRegistration(String protocolAddress, UUID placeId) throws IpcdDaoException;
void forceRegistration(String protocolAddress, UUID accountId, UUID placeId, String driverAddress);
void delete(String protocolAddress, UUID placeId);
void offline(String protocolAddress);
}
|
Robert-Stackflow/HUST-Courses | 07_Java_Experiment/SearchEngineForStudent/src/hust/cs/javacourse/search/index/impl/Document.java | <gh_stars>1-10
/**
* @Author Ruida
* @date 2022/4/20
*/
package hust.cs.javacourse.search.index.impl;
import hust.cs.javacourse.search.index.AbstractDocument;
import hust.cs.javacourse.search.index.AbstractTermTuple;
import java.util.List;
/**
* <pre>
* Document是AbstractDocument的具体子类.
* 功能: 存储某个文档的文档编号、文档路径、文档中的三元组对象列表.
* </pre>
*/
public class Document extends AbstractDocument {
public Document() {
}
public Document(int docId, String docPath, List<AbstractTermTuple> tuples) {
super(docId, docPath, tuples);
}
public Document(int docId, String docPath) {
super(docId, docPath);
}
@Override
public int getDocId() {
return docId;
}
@Override
public void setDocId(int docId) {
this.docId = docId;
}
@Override
public String getDocPath() {
return docPath;
}
@Override
public void setDocPath(String docPath) {
this.docPath = docPath;
}
@Override
public List<AbstractTermTuple> getTuples() {
return tuples;
}
@Override
public void addTuple(AbstractTermTuple tuple) {
if (!contains(tuple)) {
tuples.add(tuple);
}
}
@Override
public boolean contains(AbstractTermTuple tuple) {
return tuples.contains(tuple);
}
@Override
public AbstractTermTuple getTuple(int index) {
return tuples.get(index);
}
@Override
public int getTupleSize() {
return tuples.size();
}
@Override
public String toString() {
StringBuilder str = new StringBuilder();
str.append("docId ").append(docId).append(", docPath ").append(docPath).append("\nTuples \n");
for (AbstractTermTuple tuple : tuples)
str.append(tuple.toString());
return String.valueOf(str);
}
}
|
soma115/wikikracja | article/migrations/0012_auto_20210821_2050.py | # Generated by Django 3.1.12 on 2021-08-21 18:50
from django.db import migrations
import tinymce.models
class Migration(migrations.Migration):
dependencies = [
('article', '0011_auto_20210821_2049'),
]
operations = [
migrations.AlterField(
model_name='article',
name='body',
field=tinymce.models.HTMLField(null=True, verbose_name='Body'),
),
]
|
cfuerst/aws-doc-sdk-examples | javav2/example_code/ssm/src/main/java/com/example/ssm/DescribeOpsItems.java | // snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.]
// snippet-sourcedescription:[DescribeOpsItems.java demonstrates how to describe an OpsItem for Amazon Simple Systems Management (Amazon SSM).]
//snippet-keyword:[AWS SDK for Java v2]
// snippet-keyword:[Amazon Simple Systems Management]
// snippet-keyword:[Code Sample]
// snippet-sourcetype:[full-example]
// snippet-sourcedate:[11/06/2020]
// snippet-sourceauthor:[AWS - scmacdon]
/*
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package com.example.ssm;
//snippet-start:[ssm.java2.describe_ops.import]
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.ssm.SsmClient;
import software.amazon.awssdk.services.ssm.model.DescribeOpsItemsRequest;
import software.amazon.awssdk.services.ssm.model.DescribeOpsItemsResponse;
import software.amazon.awssdk.services.ssm.model.OpsItemSummary;
import software.amazon.awssdk.services.ssm.model.SsmException;
import java.util.List;
//snippet-end:[ssm.java2.describe_ops.import]
/**
* To run this Java V2 code example, ensure that you have setup your development environment, including your credentials.
*
* For information, see this documentation topic:
*
* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
*/
public class DescribeOpsItems {
public static void main(String[] args) {
Region region = Region.US_EAST_1;
SsmClient ssmClient = SsmClient.builder()
.region(region)
.build();
describeItems(ssmClient);
ssmClient.close();
}
//snippet-start:[ssm.java2.describe_ops.main]
public static void describeItems(SsmClient ssmClient) {
try {
DescribeOpsItemsRequest itemsRequest = DescribeOpsItemsRequest.builder()
.maxResults(10)
.build();
DescribeOpsItemsResponse itemsResponse = ssmClient.describeOpsItems(itemsRequest);
List<OpsItemSummary> items = itemsResponse.opsItemSummaries();
for (OpsItemSummary item: items) {
System.out.println("The item title is "+item.title());
}
} catch (SsmException e) {
System.err.println(e.getMessage());
System.exit(1);
}
}
//snippet-end:[ssm.java2.describe_ops.main]
}
|
teeeeeegz/DuckDuckGo-Android | app/src/main/java/au/com/michaeltigas/duckduckdefine/injection/component/ApplicationComponent.java | package au.com.michaeltigas.duckduckdefine.injection.component;
import android.app.Application;
import android.content.Context;
import com.squareup.moshi.Moshi;
import com.squareup.picasso.Picasso;
import javax.inject.Singleton;
import au.com.michaeltigas.duckduckdefine.app.DuckDuckDefineApplication;
import au.com.michaeltigas.duckduckdefine.data.DataManager;
import au.com.michaeltigas.duckduckdefine.data.local.PreferencesHelper;
import au.com.michaeltigas.duckduckdefine.data.remote.DuckDuckGoApiService;
import au.com.michaeltigas.duckduckdefine.injection.context.ApplicationContext;
import au.com.michaeltigas.duckduckdefine.injection.module.ApplicationModule;
import au.com.michaeltigas.duckduckdefine.injection.module.NetworkModule;
import dagger.Component;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
/**
* Created by <NAME> on 15/3/17.
*
* Provide references to dependencies that have been defined in the component modules, to enable
* access via @Inject field annotation injection, or class constructor injection
*/
@Singleton
@Component( modules = {
ApplicationModule.class,
NetworkModule.class
})
public interface ApplicationComponent {
void inject(DuckDuckDefineApplication duckDuckDefineApplication);
@ApplicationContext Context context();
Application application();
// Architecture-based helpers
DataManager dataManager();
PreferencesHelper preferencesHelper();
// Network related
Moshi moshi();
HttpUrl httpUrl();
Retrofit retrofit();
OkHttpClient okHttpClient();
DuckDuckGoApiService duckDuckGoApiService();
// Custom services
Picasso picasso();
}
|
USEPA/Water-Security-Toolkit | tpl/acro/packages/utilib/src/libs/Ereal.cpp | /* _________________________________________________________________________
*
* UTILIB: A utility library for developing portable C++ codes.
* Copyright (c) 2008 Sandia Corporation.
* This software is distributed under the BSD License.
* Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
* the U.S. Government retains certain rights in this software.
* For more information, see the README file in the top UTILIB directory.
* _________________________________________________________________________
*/
//
// Ereal.cpp
//
#include <utilib_config.h>
#include <utilib/Ereal.h>
#include <utilib/_math.h>
namespace utilib {
#ifndef _MSC_VER
// For everything other than MSVS, we (correctly) define specific static
// member definitions here in a single location (compilation unit).
template<>
const long double Ereal<long double>::positive_infinity_val = MAXLONGDOUBLE;
template<>
const long double Ereal<long double>::negative_infinity_val = -MAXLONGDOUBLE;
template<>
const double Ereal<double>::positive_infinity_val = MAXDOUBLE;
template<>
const double Ereal<double>::negative_infinity_val = -MAXDOUBLE;
#endif
} // namespace utilib
|
iFindTA/PBJ2Objc | include/java/security/spec/RSAOtherPrimeInfo.h | <gh_stars>0
//
// Generated by the J2ObjC translator. DO NOT EDIT!
// source: android/libcore/luni/src/main/java/java/security/spec/RSAOtherPrimeInfo.java
//
#ifndef _JavaSecuritySpecRSAOtherPrimeInfo_H_
#define _JavaSecuritySpecRSAOtherPrimeInfo_H_
#include "J2ObjC_header.h"
@class JavaMathBigInteger;
@interface JavaSecuritySpecRSAOtherPrimeInfo : NSObject
#pragma mark Public
- (instancetype)initWithJavaMathBigInteger:(JavaMathBigInteger *)prime
withJavaMathBigInteger:(JavaMathBigInteger *)primeExponent
withJavaMathBigInteger:(JavaMathBigInteger *)crtCoefficient;
- (JavaMathBigInteger *)getCrtCoefficient;
- (JavaMathBigInteger *)getExponent;
- (JavaMathBigInteger *)getPrime;
@end
J2OBJC_EMPTY_STATIC_INIT(JavaSecuritySpecRSAOtherPrimeInfo)
FOUNDATION_EXPORT void JavaSecuritySpecRSAOtherPrimeInfo_initWithJavaMathBigInteger_withJavaMathBigInteger_withJavaMathBigInteger_(JavaSecuritySpecRSAOtherPrimeInfo *self, JavaMathBigInteger *prime, JavaMathBigInteger *primeExponent, JavaMathBigInteger *crtCoefficient);
FOUNDATION_EXPORT JavaSecuritySpecRSAOtherPrimeInfo *new_JavaSecuritySpecRSAOtherPrimeInfo_initWithJavaMathBigInteger_withJavaMathBigInteger_withJavaMathBigInteger_(JavaMathBigInteger *prime, JavaMathBigInteger *primeExponent, JavaMathBigInteger *crtCoefficient) NS_RETURNS_RETAINED;
J2OBJC_TYPE_LITERAL_HEADER(JavaSecuritySpecRSAOtherPrimeInfo)
#endif // _JavaSecuritySpecRSAOtherPrimeInfo_H_
|
dbcls/togodb | app/helpers/application_helper.rb | module ApplicationHelper
def nl2br(str)
str.gsub(/\r\n|\r|\n/, '<br />')
end
def format_float(value, column)
if value.nil?
value = ''
else
if column.num_decimal_places.blank?
value_s = value.to_s
if value == 0
value = value_s
elsif value_s.downcase.include?('e')
value = value_s
elsif value.abs < 0.00001
/([1-9]+)\z/ =~ value_s
if $1 && $1.size > 1
p = $1.size - 1
else
p = 0
end
value = "%.#{p}e" % value
elsif value.abs > 1000000
/\A\-?([0-9]+)\.?([0-9]*)\z/ =~ value_s
if $1 && $1.size > 0
p = $1.size
else
p = 0
end
if $2 && $2 != '0' && $2.size > 0
p += $2.size
end
if p > 0
p -= 1
end
value = "%.#{p}e" % value
else
value = value_s
end
else
value = sprintf("%.#{column.num_decimal_places}f", value)
end
end
value
end
def convert_url_link(str)
begin
unless str.blank?
if str.to_s =~ /(https?:\/\/[\w\-\.\!\~\*\(\)\;\/\?\:\@\&\=\+\$\,\%\#]+)/
%Q(<a href="#{$1}" target="_blank">#{$1}</a>)
else
str
end
#str.to_s.gsub(/(https?:\/\/[\w\-\.\!\~\*\(\)\;\/\?\:\@\&\=\+\$\,\%\#]+)/) {
# '<a href="' + $1 + '" target="_blank">' + $1 + '</a>'
#}
end
rescue => e
str
end
end
def checkbox_tag_with_hidden(name, checked_value='1', unchecked_value='0', checked=false, options = {})
html = %Q(<input type="hidden" name="#{name}" value="#{unchecked_value}" />)
html << check_box_tag(name, checked_value, checked, options)
html
end
def advanced_search_input_elem_name(column)
"search[#{column.internal_name}]"
end
def advanced_search_text_form_element(column, search_params, value = nil)
text_field_tag(advanced_search_input_elem_name(column), value,
{ autocomplete: 'off', size: 30, class: 'bgWhite', id: "search_#{column.internal_name}" })
end
def advanced_search_form_element(column, search_params, value = nil)
name = advanced_search_input_elem_name(column)
if column.has_data_type?
advanced_search_text_form_element(column, search_params, value)
else
case column.data_type
when 'integer', 'bigint', 'float', 'decimal'
text_field_size = column.data_type == 'bigint' ? 20 : 10
if value.kind_of?(Hash)
from = value['from']
to = value['to']
else
from = ''
to = ''
end
'from ' +
text_field_tag(name+'[from]', from, { size: text_field_size, class: 'bgWhite' }) +
' to ' +
text_field_tag(name+'[to]', to, { size: text_field_size, class: 'bgWhite' })
when 'date'
if value.kind_of?(Hash)
if value['from'].kind_of?(Hash)
from_year = value['from']['year']
from_month = value['from']['month']
from_day = value['from']['day']
else
from_year = ''
from_month = ''
from_day = ''
end
if value['to'].kind_of?(Hash)
to_year = value['to']['year']
to_month = value['to']['month']
to_day = value['to']['day']
else
to_year = ''
to_month = ''
to_day = ''
end
else
from_year = ''
from_month = ''
from_day = ''
to_year = ''
to_month = ''
to_day = ''
end
'from ' +
text_field_tag(name+'[from][year]', from_year, { size: 4, class: 'bgWhite' }) +
text_field_tag(name+'[from][month]', from_month, { size: 2, class: 'bgWhite' }) +
text_field_tag(name+'[from][day]', from_day, { size: 2, class: 'bgWhite' }) +
' to ' +
text_field_tag(name+'[to][year]', to_year, { size: 4, class: 'bgWhite' }) +
text_field_tag(name+'[to][month]', to_month, { size: 2, class: 'bgWhite' }) +
text_field_tag(name+'[to][day]', to_day, { size: 2, class: 'bgWhite' })
when 'time'
if value.kind_of?(Hash)
if value['from'].kind_of?(Hash)
from_hour = value['from']['hour']
from_min = value['from']['min']
from_sec = value['from']['sec']
else
to_year = ''
to_month = ''
to_day = ''
end
if value['to'].kind_of?(Hash)
to_hour = value['to']['hour']
to_min = value['to']['min']
to_sec = value['to']['sec']
else
to_hour = ''
to_min = ''
to_sec = ''
end
else
from_hour = ''
from_min = ''
from_sec = ''
to_hour = ''
to_min = ''
to_sec = ''
end
'from ' +
text_field_tag(name+'[from][hour]', from_hour, { size: 2, class: 'bgWhite' }) +
text_field_tag(name+'[from][min]', from_min, { size: 2, class: 'bgWhite' }) +
text_field_tag(name+'[from][sec]', from_sec, { size: 2, class: 'bgWhite' }) +
' to ' +
text_field_tag(name+'[to][hour]', to_hour, { size: 2, class: 'bgWhite' }) +
text_field_tag(name+'[to][min]', to_min, { size: 2, class: 'bgWhite' }) +
text_field_tag(name+'[to][sec]', to_sec, { size: 2, class: 'bgWhite' })
when 'boolean'
options = [['', ''],
['True', '1'],
['False', '0']
]
select_tag name, options_for_select(options, value)
when 'string'
if column.other_type == 'list'
list_column_values_select_tag(column, value)
else
advanced_search_text_form_element(column, search_params, value)
end
else
advanced_search_text_form_element(column, search_params, value)
end
end
end
def list_column_values_select_tag(column, value = nil)
values = TogodbColumnValue.where(column_id: column.id).order('value')
select_tag "search[#{column.internal_name}]",
options_from_collection_for_select(values, :value, :value, value),
include_blank: true
end
end
|
elcorto/pwtools | setup.py | <filename>setup.py<gh_stars>10-100
"""
Notes on building extensions
----------------------------
Since we build extensions using f2py, we need numpy during the build phase.
We use
setup(setup_requires=['numpy'],...)
which, if no numpy install is found, downloads smth like
.eggs/numpy-1.17.2-py3.7-linux-x86_64.egg/
and used its f2py to compile extensions.
We build the extensions using src/Makefile (see doc/source/written/install.rst)
instead of setuptools.extension.Extension or
numpy.distutils.extension.Extension, so we sneak a call to "make" into the
setup.py build_py phase using build_extensions() and make_cmd_class() below.
pip install seems to trigger setup.py build_py and setup.py install, so adding
build_extensions() to build_py is sufficient.
"""
import os
import subprocess
from setuptools import setup, find_packages
from setuptools.command.build_py import build_py
here = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(here, 'README.rst')) as fd:
long_description = fd.read()
def build_extensions():
"""
Instead of fighting with numpy.distutils (see
https://stackoverflow.com/a/41896134), we use our Makefile which we know
works well (OpenMP etc, see "make help") and copy the *.so files using the
package_data trick below. Makefile will copy the *.so files to pwtools/, so
we just need to tell setuptools that these are "data files" that we wish to
copy when installing, along with all *.py files.
"""
subprocess.run(r"cd src; make clean; make", shell=True, check=True)
def make_cmd_class(base):
"""
Call build_extensions() in "python setup.py <base>" prior to anything else.
base = build_py, install, develop, ..., i.e. a setup.py command. Use in
setup(cmdclass={'<base>': make_cmd_class(<base>)}, ...).
Parameters
----------
base : setuptools.command.<base>.<base> instance
Notes
-----
https://stackoverflow.com/a/36902139
"""
class CmdClass(base):
def run(self):
build_extensions()
super().run()
return CmdClass
setup(
name='pwtools',
version='1.2.2',
description='pre- and postprocessing of atomistic calculations',
long_description=long_description,
url='https://github.com/elcorto/pwtools',
author='<NAME>',
author_email='<EMAIL>',
license='BSD 3-Clause',
keywords='ase scipy atoms simulation database postprocessing qha',
packages=find_packages(),
install_requires=open('requirements.txt').read().splitlines(),
setup_requires=['numpy'],
python_requires='>=3',
package_data={'pwtools': ['*.so']},
cmdclass={
'build_py': make_cmd_class(build_py),
},
)
|
triffon/oop-2019-20 | labs/6/Practice_15 - Iterator and STL/Factory Method & Proxy pattern/Proxy.cpp | #include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <Windows.h>
#include "IBook.hpp"
#include "IBookFileFactory.hpp"
#include "BookFileFactory.hpp"
#include "Library.h"
#include "BookProxyFileFactory.hpp"
void testLibraryWithBook();
void testLibraryWithBookProxy();
int main()
{
testLibraryWithBook();
Sleep(1000);
std::cout << std::endl << std::endl;
testLibraryWithBookProxy();
}
void testLibraryWithBook()
{
std::cout << "Starting test for library with books. Loading 4 books..." << std::endl;
IBookFileFactory* bookFactory = new BookFileFactory({ "test01.txt","test01.txt" ,"test01.txt" ,"test01.txt" });
Library simpleLibrary = Library::loadFromFiles(bookFactory);
simpleLibrary.add(new Book("test01.txt"));
std::cout << "Simple Library pages for index 4: " << simpleLibrary.getNumberOfPages(4) << std::endl;
std::cout << "Library test with books finished." << std::endl;
}
void testLibraryWithBookProxy()
{
std::cout << "Starting test for library with proxy. Loading 500 books..." << std::endl;
std::vector<std::string> filenames;
for (size_t i = 0; i < 500; i++)
{
filenames.push_back("test01.txt");
}
IBookFileFactory* proxyFactory = new BookProxyFileFactory(filenames);
Library library = Library::loadFromFiles(proxyFactory);
std::cout << library.getNumberOfChapters(4) << std::endl;
// Initialize library using BookProxy.
std::cout << "Library test with proxy finished." << std::endl;
}
|
ostdotcom/ost-wallet-sdk-android | ostsdk/src/test/java/com/ost/walletsdk/utils/GnosisSafeTest.java | /*
* Copyright 2019 OST.com 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
*/
package com.ost.walletsdk.utils;
import org.json.JSONObject;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class GnosisSafeTest {
@Test
public void testAddOwnerWithThreshold() {
String expectedOutput = "0x0d582f1300000000000000000000000098443ba43e5a55ff9c0ebeddfd1db32d7b1a" +
"949a0000000000000000000000000000000000000000000000000000000000000001";
String encodeMessage = new GnosisSafe().getAddOwnerWithThresholdExecutableData(
"0x98443bA43e5a55fF9c0EbeDdfd1db32d7b1A949A", "1");
assertEquals(expectedOutput, encodeMessage);
}
@Test
public void testGetSafeTxData() {
String expectedOutput = "0x4fd9d0aed661d3993b562981a1cc2f5670723bab7bb45e3ff0c42fc021fa30b4";
String addOwnerExecutableData = "0x0d582f1300000000000000000000000098443ba43e5a55ff9c0ebeddfd" +
"1db32d7b1a949a0000000000000000000000000000000000000000000000000000000000000001";
String NULL_ADDRESS = "0x0000000000000000000000000000000000000000";
JSONObject safeTxData = new GnosisSafe().getSafeTxData("0x98443bA43e5a55fF9c0EbeDdfd1db32d7b1A949A",
"0x98443bA43e5a55fF9c0EbeDdfd1db32d7b1A949A"
,
"0", addOwnerExecutableData, "0", "0", "0", "0",
NULL_ADDRESS, NULL_ADDRESS, "0");
String hashString = null;
try {
hashString = new EIP712(safeTxData).toEIP712TransactionHash();
} catch (Exception e) {
e.printStackTrace();
}
assertEquals(expectedOutput, hashString);
}
@Test
public void testAddSessionHash() {
String expectedOutput = "0x204e19fb7d8f765c487d67f0e77460a24804ef10a12d0fbfa668bb9dc036d83b";
String addOwnerExecutableData = "0x028c979d00000000000000000000000099dbad5becad9eb32eb12a709aaf" +
"831d1be3b25500000000000000000000000000000000000000000000000000000000000f424000000000" +
"0000000000000000000000000000000000000000000000174876e800";
String tokenHolder = "0x59aAF1528a3538752B165EB2D6e0293C86bbCa4F";
String deviceManager = "0xA5936b94619E1f76349B27879c8B54A118c15A82";
JSONObject safeTxData = new GnosisSafe.SafeTxnBuilder()
.setCallData(addOwnerExecutableData)
.setNonce("4")
.setToAddress(tokenHolder)
.setVerifyingContract(deviceManager)
.build();
String hashString = null;
try {
hashString = new EIP712(safeTxData).toEIP712TransactionHash();
} catch (Exception e) {
e.printStackTrace();
}
assertEquals(expectedOutput, hashString);
}
} |
movermeyer/madrona | madrona/installer/files/_project/_app/models.py | from django.contrib.gis.db import models
from madrona.features.models import PolygonFeature, PointFeature, LineFeature, FeatureCollection
from madrona.features import register
|
vitobasso/scala-torrent | src/main/scala/com/dominikgruber/scalatorrent/tracker/udp/UdpTracker.scala | package com.dominikgruber.scalatorrent.tracker.udp
import java.net.InetSocketAddress
import java.nio.charset.StandardCharsets.ISO_8859_1
import akka.actor.{Actor, ActorLogging, ActorRef, Props}
import akka.io.{IO, UdpConnected}
import akka.util.ByteString
import com.dominikgruber.scalatorrent.PeerFinder.TrackerConfig
import com.dominikgruber.scalatorrent.metainfo.FileMetaInfo
import com.dominikgruber.scalatorrent.tracker.Peer
import com.dominikgruber.scalatorrent.tracker.http.HttpTracker.SendEventStarted
import com.dominikgruber.scalatorrent.tracker.http.TrackerResponseWithSuccess
import com.dominikgruber.scalatorrent.tracker.udp.UdpEncoding._
import scala.util.{Failure, Random, Success}
case class UdpTracker(meta: FileMetaInfo, remote: InetSocketAddress, config: TrackerConfig) extends Actor with ActorLogging {
val udpManager: ActorRef = IO(UdpConnected)(context.system)
override def preStart(): Unit = {
udpManager ! UdpConnected.Connect(self, remote)
}
override def receive: Receive = {
case UdpConnected.Connected =>
context become ready(sender)
}
def ready(udpConn: ActorRef): Receive = {
case SendEventStarted(dl, ul) => // from Torrent
val transactionId = TransactionId(Random.nextInt())
val connReq = ConnectRequest(transactionId)
val connReqBytes = ByteString(encode(connReq))
log.debug(s"Sending $connReq")
udpConn ! UdpConnected.Send(connReqBytes)
context become expectingConnectResponse(sender, udpConn, transactionId, dl, ul)
case UdpConnected.Disconnect =>
udpConn ! UdpConnected.Disconnect
context.become(disconnecting)
}
def expectingConnectResponse(requester: ActorRef, udpConn: ActorRef, trans: TransactionId, dl: Long, ul: Long): Receive = {
case UdpConnected.Received(data) =>
val torrentHash = InfoHash.validate(meta.infoHash.toArray)
val peerId = PeerId.validate(config.peerId.getBytes(ISO_8859_1))
val left: Long = meta.totalBytes //TODO get progress
val key = 123L //TODO
decode(data.toArray) match {
case Success(c: ConnectResponse) =>
log.debug(s"Received $c")
val announceReq = AnnounceRequest(
c.conn, trans, torrentHash, peerId, dl, left, ul, AnnounceEvent.Started, key = key, port = config.portIn)
val announceReqBytes = ByteString(encode(announceReq))
log.debug(s"Sending $announceReq")
udpConn ! UdpConnected.Send(announceReqBytes)
case Success(a: AnnounceResponse) =>
log.debug(s"Received $a")
//TODO validate transaction
val peers: List[Peer] = a.peers.map(p => Peer(None, p.ip, p.port)).toList
requester ! TrackerResponseWithSuccess(a.interval, None, None, a.seeders, a.leechers, peers, None)
case Failure(t) =>
log.error(t, "Request to tracker failed")
}
}
def disconnecting: Receive = {
case UdpConnected.Disconnected => context.stop(self)
}
}
object UdpTracker {
def props(meta: FileMetaInfo, remote: InetSocketAddress, config: TrackerConfig) =
Props(classOf[UdpTracker], meta, remote, config)
} |
cardforcoin/raas-v2-sdk-python | setup.py | from setuptools import setup, find_packages
# Try to convert markdown README to rst format for PyPI.
try:
import pypandoc
long_description = pypandoc.convert('README.md', 'rst')
except(IOError, ImportError):
long_description = open('README.md').read()
setup(
name='tangocard-raasv2',
version='1.0.0b2',
description='With this RESTful API you can integrate a global reward or incentive program into your app or platform. If you have any questions or if you\'d like to receive your own credentials, please contact us at <EMAIL>.',
long_description=long_description,
author='<NAME>.',
author_email='<EMAIL>',
url='https://github.com/tangocard/raas-v2-sdk-python',
download_url='https://github.com/tangocard/raas-v2-sdk-python/archive/1.0.0b2.tar.gz',
packages=find_packages(),
install_requires=[
'requests>=2.9.1, <3.0',
'jsonpickle>=0.7.1, <1.0',
'cachecontrol>=0.11.7, <1.0',
'python-dateutil>=2.5.3, <3.0'
],
tests_require=[
'nose>=1.3.7'
],
test_suite = 'nose.collector'
)
|
lel352/Curso-Python | aulaspythonbasico/aula16/aula16.py | # Índices e fatiamento de strings em Python
'''
Manipulando String
* String Indices
* Fatiamento de String [Inicio:Fim:Passo]
* Funções built-in len, abs, type, print, etc...
'''
# [012345678] Positivos
texto = 'Python S2'
# -[987654321] Negativos
print(texto[2])
print(texto[-7])
print(texto[-1]) # pega o último caracter
url = 'www.google.com.br/'
print(url[:-1])
# pegando trechos
nova_string = texto[2:6] # vai pegar do indice 2 ao 5 (6 não é incluido, fim não é incluido)
print(nova_string)
nova_string = texto[:6] # Sem valor entende que é zero [:6] = [0:6]
print(nova_string)
nova_string = texto[7:] # Sem valor entende que é final [7:] = [7:9]
print(nova_string)
nova_string = texto[-9:-3]
print(nova_string)
nova_string = texto[:-1] # pegando do indice zero e excluindo o último caracter
print(nova_string)
# Passo Step
nova_string = texto[::2] # do inicio até o último caracter, pulando de 2 em 2
print(nova_string)
nova_string = texto[0:6:2] # do inicio até o 5 caracter, pulando de 2 em 2
print(nova_string)
nova_string = texto[0::3] # do inicio até o último caracter, pulando de 3 em 3
print(nova_string)
|
themoffster/openlayers | examples/navigation-controls.js | import Map from '../src/ol/Map.js';
import OSM from '../src/ol/source/OSM.js';
import TileLayer from '../src/ol/layer/Tile.js';
import View from '../src/ol/View.js';
import {ZoomToExtent, defaults as defaultControls} from '../src/ol/control.js';
const map = new Map({
controls: defaultControls().extend([
new ZoomToExtent({
extent: [
813079.7791264898, 5929220.284081122, 848966.9639063801,
5936863.986909639,
],
}),
]),
layers: [
new TileLayer({
source: new OSM(),
}),
],
target: 'map',
view: new View({
center: [0, 0],
zoom: 2,
}),
});
|
yvanlebras/galaxy | lib/galaxy/model/migrate/versions/0097_add_ctx_rev_column.py | <reponame>yvanlebras/galaxy<filename>lib/galaxy/model/migrate/versions/0097_add_ctx_rev_column.py
"""
Migration script to add the ctx_rev column to the tool_shed_repository table.
"""
import logging
from sqlalchemy import (
Column,
MetaData,
)
from galaxy.model.custom_types import TrimmedString
from galaxy.model.migrate.versions.util import (
add_column,
drop_column,
)
log = logging.getLogger(__name__)
metadata = MetaData()
def upgrade(migrate_engine):
print(__doc__)
metadata.bind = migrate_engine
metadata.reflect()
col = Column("ctx_rev", TrimmedString(10))
add_column(col, "tool_shed_repository", metadata)
def downgrade(migrate_engine):
metadata.bind = migrate_engine
metadata.reflect()
drop_column("ctx_rev", "tool_shed_repository", metadata)
|
879479119/gitto-android | app/src/main/java/com/stormphoenix/ogit/mvp/view/base/ProgressView.java | <filename>app/src/main/java/com/stormphoenix/ogit/mvp/view/base/ProgressView.java<gh_stars>0
package com.stormphoenix.ogit.mvp.view.base;
import com.stormphoenix.ogit.mvp.contract.BaseContract;
/**
* Created by wanlei on 18-3-10.
*/
public interface ProgressView extends BaseContract.View {
void showProgress();
void hideProgress();
}
|
maandree/liberror-gpgme | data_new_from_estream.c | <gh_stars>1-10
/* See LICENSE file for copyright and license details. */
#include "internal.h"
gpgme_error_t
liberror_gpgme_data_new_from_estream(gpgme_data_t *r_dh, gpgrt_stream_t stream)
{
gpgme_error_t ret = gpgme_data_new_from_estream(r_dh, stream);
if (ret)
liberror_gpgme_set_error("gpgme_data_new_from_estream", ret);
return ret;
}
|
hussam-aldarwish/kodluyoruz-k127-js-react-bootcamp | homeworks/chat-app/src/components/Input/input.js | <reponame>hussam-aldarwish/kodluyoruz-k127-js-react-bootcamp
import React, { forwardRef } from "react";
import PropTypes from "prop-types";
import "./input.css";
const Input = forwardRef(({ error, text, value, ...props }, ref) => {
return (
<div className="input-container">
<input ref={ref} className={`input ${error ? "error" : ""}`} {...props} />
{error ? <span className="error">{hadndleError(error.type)}</span> : null}
</div>
);
});
Input.propsTypes = {
error: PropTypes.shape({
type: PropTypes.string,
message: PropTypes.string,
ref: PropTypes.node,
}),
};
const hadndleError = (errorType) => {
switch (errorType) {
case "required":
return "You must fill this input!";
default:
return `Error: ${errorType}`;
}
};
export default Input;
|
diegolovison/radargun-plugin | src/main/java/org/jenkinsci/plugins/radargun/model/Option.java | package org.jenkinsci.plugins.radargun.model;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
/**
* Represents a switch in RG shell scripts. Used in classes which describe these script, e.g. {@link MasterScriptConfig}
* or {@link SlaveScriptConfig}.
*
* @author vjuranek
*
*/
public class Option {
public static final String MULTI_VALUE_SEPARATOR = " ";
private String optionSwitch;
private String getterName;
private boolean hasOptionValue;
private boolean isMultiValue;
public Option(String optionSwitch, String getterName, boolean hasOptionValue, boolean isMultiValue) {
this.optionSwitch = optionSwitch;
this.getterName = getterName;
this.hasOptionValue = hasOptionValue;
this.isMultiValue = isMultiValue;
}
public String getOptionSwitch() {
return optionSwitch;
}
public String getGetterName() {
return getterName;
}
public boolean hasOptionValue() {
return hasOptionValue;
}
public boolean isMultiValue() {
return isMultiValue;
}
public List<String> getCmdOption(RgScriptConfig cfg) throws IllegalArgumentException {
List<String> options = new ArrayList<String>();
try {
Method m = cfg.getClass().getMethod(getGetterName());
Object val = m.invoke(cfg);
if (val != null) {
if (hasOptionValue()) {
if (isMultiValue()) {
String[] values = val.toString().split(MULTI_VALUE_SEPARATOR);
for (String value : values) {
options.add(getOptionSwitch());
options.add(value);
}
} else {
options.add(getOptionSwitch());
options.add(val.toString());
}
} else { // no value for this switch, getter should be boolean
if (((Boolean) val).booleanValue())
options.add(getOptionSwitch());
}
}
} catch (NoSuchMethodException e) {
throw new IllegalArgumentException(String.format("Cannot obtain value for switch %s", getOptionSwitch()),
e.getCause());
} catch (IllegalAccessException e) {
throw new IllegalArgumentException(String.format("Cannot resolve value for switch %s", getOptionSwitch()),
e.getCause());
} catch (InvocationTargetException e) {
throw new IllegalArgumentException(String.format("Some issue when resoling value for switch %s",
getOptionSwitch()), e.getCause());
}
return options;
}
}
|
Bots-United/whichbot | bot/src/cpp/strategy/BuilderStrategy.cpp | //
// $Id: BuilderStrategy.cpp,v 1.63 2005/02/28 05:20:14 clamatius Exp $
// Copyright (c) 2003, WhichBot Project
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of the WhichBot Project nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "BotManager.h"
#include "config/Config.h"
#include "config/TranslationManager.h"
#include "engine/Reward.h"
#include "strategy/BuilderStrategy.h"
#include "strategy/HiveMind.h"
#include "navigation/BuildNavMethod.h"
#include "worldstate/HiveManager.h"
#include "worldstate/WorldStateUtil.h"
#include "extern/metamod/meta_api.h"
static double DISTANCE_SCALING_FACTOR = 0.03;
static double TIME_SCALING_FACTOR = 0.008;
// TODO - config file?
static int MIN_RES_FOR_DEFENSE_CHAMBER = 10;
static int MIN_RES_FOR_MOVEMENT_CHAMBER = 10;
static int MIN_RES_FOR_SENSORY_CHAMBER = 10;
static int MIN_RES_FOR_OFFENSE_CHAMBER = 10;
static int MIN_RES_FOR_RESOURCE_TOWER = 15;
static int MIN_RES_FOR_HIVE = 40;
const float REWARD_TIMEOUT = 300.0f;
static float RESNODE_REWARD = 100.0f;
static float UNBUILT_HIVE_REWARD = 100.0f;
static float HIVE_REWARD = 100.0f;
static float HIVE_DEFENSE_RANGE = 1000.0f;
static float HIVE_DEFENSE_TIMEOUT = 10.0f;
const float RES_WAIT_TIMEOUT = 120.0f;
static float MIN_OC_DISTANCE = 200.0f;
static float MIN_SC_DISTANCE = 500.0f;
static float HIVE_DESIRE = 30.0f;
static float HIVE_DEFENSE_DESIRE = 30.0f;
static float SCALING_FACTOR = 10.0f;
static float MIN_BUILD_WAIT = 10.0f;
const float ARTIFICIAL_DISTANCE_BOOST_THRESHOLD = 20.0;
const float ARTIFICIAL_DISTANCE_BOOST = 10.0;
BuilderStrategy::BuilderStrategy(Bot& bot) :
_bot(bot),
_plan(kNoBuildPlan),
_targetRes(0),
_timeLastBuildingDropped(0),
_waitStartTime(-1),
_hiveDefenseRange(HIVE_DEFENSE_RANGE)
{
MIN_RES_FOR_DEFENSE_CHAMBER =
Config::getInstance().getTweak("game/resources/defensechamber", MIN_RES_FOR_DEFENSE_CHAMBER);
MIN_RES_FOR_SENSORY_CHAMBER =
Config::getInstance().getTweak("game/resources/sensorychamber", MIN_RES_FOR_SENSORY_CHAMBER);
MIN_RES_FOR_MOVEMENT_CHAMBER =
Config::getInstance().getTweak("game/resources/movementchamber", MIN_RES_FOR_MOVEMENT_CHAMBER);
MIN_RES_FOR_OFFENSE_CHAMBER =
Config::getInstance().getTweak("game/resources/offensechamber", MIN_RES_FOR_OFFENSE_CHAMBER);
MIN_RES_FOR_RESOURCE_TOWER =
Config::getInstance().getTweak("game/resources/alienresourcetower", MIN_RES_FOR_RESOURCE_TOWER);
MIN_RES_FOR_HIVE =
Config::getInstance().getTweak("game/resources/team_hive", MIN_RES_FOR_HIVE);
MIN_OC_DISTANCE =
Config::getInstance().getTweak("strategy/builder/min_oc_distance", MIN_OC_DISTANCE);
MIN_SC_DISTANCE =
Config::getInstance().getTweak("strategy/builder/min_sc_distance", MIN_OC_DISTANCE);
SCALING_FACTOR =
Config::getInstance().getTweak("strategy/builder/scale_factor", SCALING_FACTOR);
DISTANCE_SCALING_FACTOR =
Config::getInstance().getTweak("strategy/builder/distance_scale", DISTANCE_SCALING_FACTOR);
RESNODE_REWARD =
Config::getInstance().getTweak("strategy/builder/resnode_reward", RESNODE_REWARD);
UNBUILT_HIVE_REWARD =
Config::getInstance().getTweak("strategy/builder/unbuilt_hive_reward", UNBUILT_HIVE_REWARD);
HIVE_REWARD =
Config::getInstance().getTweak("strategy/builder/hive_reward", HIVE_REWARD);
HIVE_DEFENSE_RANGE =
Config::getInstance().getTweak("strategy/builder/hive_defense_range", HIVE_DEFENSE_RANGE);
HIVE_DEFENSE_TIMEOUT =
Config::getInstance().getTweak("strategy/builder/hive_defense_timeout", HIVE_DEFENSE_TIMEOUT);
HIVE_DESIRE =
Config::getInstance().getTweak("strategy/builder/hive_desire", HIVE_DESIRE);
HIVE_DEFENSE_DESIRE =
Config::getInstance().getTweak("strategy/builder/hive_defense_desire", HIVE_DEFENSE_DESIRE);
for (int ii = 0; ii < 3; ii++) {
_chambers[ii] = (eBuildPlan)(int)Config::getInstance().getArrayTweak("strategy/roles/builder/chamber_order", ii, 0.0);
}
if (_chambers[0] == kNoBuildPlan) {
LOG_CONSOLE(PLID, "Warning: chamber order config incorrect. Gorge bots will not function correctly.");
}
}
void BuilderStrategy::countChambers()
{
_numDefenseChambers = WorldStateUtil::countEntities("defensechamber");
_numMovementChambers = WorldStateUtil::countEntities("movementchamber");
_numSensoryChambers = WorldStateUtil::countEntities("sensorychamber");
}
void BuilderStrategy::getRewards(vector<Reward>& rewards, tEvolution evolution)
{
_buildableLocations.clear();
countChambers();
switch (_plan) {
case kNoBuildPlan:
selectBuildPlan();
if (_plan != kNoBuildPlan) {
getRewards(rewards, evolution);
}
break;
case kBuildResTower:
getResTowerRewards(rewards);
break;
case kBuildHive:
rewardHiveLocations(rewards, kEmptyHive);
break;
case kBuildOffenseChamber:
rewardHiveLocations(rewards, kAnyHive);
rewardResTowerLocations(rewards, ALIEN_NODE_MASK, false);
break;
case kBuildDefenseChamber:
case kBuildMovementChamber:
case kBuildSensoryChamber:
tHiveFillState desiredHiveState = kAnyHive;
if (_numDefenseChambers < 3) {
desiredHiveState = kFilledHive;
}
rewardHiveLocations(rewards, desiredHiveState);
break;
}
}
void BuilderStrategy::getResTowerRewards(vector<Reward>& rewards)
{
bool emptyNodeFound = rewardResTowerLocations(rewards, OCCUPIED_NODE_MASK, true);
if (!emptyNodeFound) {
if (HiveManager::getActiveHiveCount() > 1) {
// if we have more than 1 hive, we have bilebomb so let's go kill the marine nodes
bool marineNodeFound = rewardResTowerLocations(rewards, MARINE_NODE_MASK, false);
if (!marineNodeFound) {
// if there aren't any marine nodes
selectHiveDefensePlan();
rewardHiveLocations(rewards, kAnyHive);
}
} else {
_plan = kBuildHive;
rewardHiveLocations(rewards, kEmptyHive);
}
}
}
void BuilderStrategy::visitedWaypoint(tNodeId wptId, tEvolution evolution)
{
if (evolution == kGorge) {
switch (_plan) {
case kBuildResTower:
checkForBuildStart(wptId, MIN_RES_FOR_RESOURCE_TOWER, kAlienResourceTower);
break;
case kBuildHive:
checkForBuildStart(wptId, MIN_RES_FOR_HIVE, kHive);
break;
case kBuildDefenseChamber:
checkForBuildStart(wptId, MIN_RES_FOR_DEFENSE_CHAMBER, kDefenseChamber);
break;
case kBuildOffenseChamber:
checkForBuildStart(wptId, MIN_RES_FOR_OFFENSE_CHAMBER, kOffenseChamber);
break;
case kBuildMovementChamber:
checkForBuildStart(wptId, MIN_RES_FOR_MOVEMENT_CHAMBER, kMovementChamber);
break;
case kBuildSensoryChamber:
checkForBuildStart(wptId, MIN_RES_FOR_SENSORY_CHAMBER, kSensoryChamber);
break;
}
}
}
void BuilderStrategy::waitedAtWaypoint(tNodeId wptId, tEvolution evolution)
{
if (evolution == kGorge && locationIsBuildable(wptId)) {
checkBuildStatus();
} else {
if (_bot.getNavigationEngine() != NULL) {
_bot.getNavigationEngine()->resume();
}
_waitStartTime = -1;
}
}
int getResTowerCount()
{
int resTowerCount = 0;
CBaseEntity* pEntity = NULL;
do {
pEntity = UTIL_FindEntityByClassname(pEntity, "alienresourcetower");
if ((pEntity != NULL) && !FNullEnt(pEntity->edict())) {
resTowerCount++;
}
} while (pEntity != NULL);
return resTowerCount;
}
int BuilderStrategy::getChamberCount(int hiveNum)
{
switch (_chambers[hiveNum]) {
case kBuildDefenseChamber:
return _numDefenseChambers;
case kBuildMovementChamber:
return _numMovementChambers;
case kBuildSensoryChamber:
return _numSensoryChambers;
default:
return 0;
}
}
void BuilderStrategy::selectHiveDefensePlan()
{
int die = RANDOM_LONG(0, 100);
int chance = 10;
_plan = kBuildOffenseChamber;
int hiveCount = HiveManager::getActiveHiveCount();
switch (hiveCount) {
case 0:
// shouldn't be building hive defense at 0 hives, we can't build anything anyway
break;
case 1:
if (getChamberCount(0) < 3) {
_plan = _chambers[0];
}
break;
case 2:
if (getChamberCount(1) < 3) {
_plan = _chambers[1];
}
break;
case 3:
if (getChamberCount(0) < 3) {
_plan = _chambers[0];
} else if (getChamberCount(1) < 3) {
_plan = _chambers[1];
} else if (getChamberCount(2) < 3) {
_plan = _chambers[2];
}
break;
}
if (_plan == kBuildOffenseChamber) {
_hiveDefenseRange = HIVE_DEFENSE_RANGE * RANDOM_FLOAT(0.3, 1.0);
} else {
_hiveDefenseRange = HIVE_DEFENSE_RANGE * RANDOM_FLOAT(0.3, 0.6);
}
}
void BuilderStrategy::selectBuildPlan()
{
// TODO - better algorithm than this chimpy one
int hiveCount = HiveManager::getActiveHiveCount();
int resTowerCount = getResTowerCount();
int die = RANDOM_LONG(0, 100);
int totalTraitCount = _numMovementChambers + _numDefenseChambers + _numSensoryChambers;
switch (hiveCount) {
case 0:
_log.Debug("No hives! Selecting hive build plan.");
_plan = kBuildHive;
break;
case 1:
if (_bot.getResources() > 80 && resTowerCount > 1 && totalTraitCount == 3 && !gpBotManager->areCheatsEnabled())
{
_plan = kBuildHive;
} else {
if (resTowerCount < 3) {
_plan = kBuildResTower;
} else if ((getChamberCount(0) < 3) &&
(getChamberCount(1) == 0) &&
(getChamberCount(2) == 0))
{
selectHiveDefensePlan();
} else {
if (resTowerCount < 4) {
_plan = kBuildResTower;
} else {
_plan = kBuildHive;
}
}
}
break;
case 2:
if (_bot.getResources() > 80 && resTowerCount > 1 && totalTraitCount == 6 && !gpBotManager->areCheatsEnabled()) {
_plan = kBuildHive;
} else {
if ((getChamberCount(2) == 0) &&
((getChamberCount(0) < 3) ||
(getChamberCount(1) < 3)))
{
selectHiveDefensePlan();
} else {
if (resTowerCount < 2) {
_plan = kBuildResTower;
} else if (die < HIVE_DESIRE) {
_plan = kBuildHive;
} else {
selectHiveDefensePlan();
}
}
}
break;
case 3:
if (die > 20 * resTowerCount || die > 95) {
_plan = kBuildResTower;
} else {
selectHiveDefensePlan();
}
break;
}
switch (_plan) {
case kBuildResTower:
_log.Debug("Selected res tower build plan");
break;
case kBuildHive:
_log.Debug("Selected hive build plan");
break;
case kBuildDefenseChamber:
_log.Debug("Selected defense chamber build plan");
break;
case kBuildMovementChamber:
_log.Debug("Selected movement chamber build build plan");
break;
case kBuildSensoryChamber:
_log.Debug("Selected sensory chamber build build plan");
break;
case kBuildOffenseChamber:
_log.Debug("Selected offense chamber build plan");
break;
}
}
bool BuilderStrategy::rewardResTowerLocations(vector<Reward>& rewards, int nodeMask, bool rewardEmpty)
{
const char* resLocClassname = "func_resource";
bool locationFound = false;
CBaseEntity* pEntity = NULL;
do {
pEntity = UTIL_FindEntityByClassname(pEntity, resLocClassname);
if (pEntity != NULL) {
edict_t* pEdict = pEntity->edict();
bool resNodeTaken = HiveMind::resourceNodeIsTaken(pEdict->v.origin, nodeMask);
if ((rewardEmpty && !resNodeTaken) || (!rewardEmpty && resNodeTaken)) {
tNodeId wptId = HiveMind::getNearestWaypoint(kGorge, pEdict);
if (_bot.getPathManager().nodeIdValid(wptId)) {
addReward(rewards, wptId, RESNODE_REWARD);
locationFound = true;
}
}
}
} while (pEntity != NULL);
return locationFound;
}
void BuilderStrategy::rewardHiveLocations(vector<Reward>& rewards, tHiveFillState desiredHiveState)
{
int numRewardsGiven = 0;
for (int ii = 0; ii < HiveManager::getHiveCount(); ii++) {
HiveInfo* pHiveInfo = HiveManager::getHive(ii);
if (pHiveInfo->getWaypointId() >= 0) {
if ((desiredHiveState == kAnyHive) ||
(desiredHiveState == pHiveInfo->getHiveFillState()))
{
addReward(rewards, pHiveInfo->getWaypointId(), HIVE_REWARD);
numRewardsGiven++;
}
}
}
if (numRewardsGiven == 0) {
_log.Debug("Wanted to reward hive locations, but no empty hives found!");
_plan = kNoBuildPlan;
}
}
void BuilderStrategy::checkForBuildStart(tNodeId wptId, int targetRes, eEntityType entityType)
{
if (locationIsBuildable(wptId)) {
_targetRes = targetRes;
if (_bot.getResources() < _targetRes) {
_log.Debug("Reached buildable wpt %d, waiting for more res", wptId);
if (_bot.getNavigationEngine() != NULL) {
_bot.getNavigationEngine()->pause();
}
_waitStartTime = gpGlobals->time;
} else {
// Don't switch to build mode too often, it can cause some pathological sticking issues where the
// bot can't actually build but thinks it can and continuously switches in and out of build mode
if (gpGlobals->time > _bot.getProperty(Bot::kLastBuildTime) + MIN_BUILD_WAIT) {
_log.Debug("Reached buildable wpt %d, switching to build mode", wptId);
_bot.setProperty(Bot::kLastBuildTime);
if (_bot.getNavigationEngine() != NULL) {
_bot.getNavigationEngine()->setNextMethod(new BuildNavMethod(_bot, entityType));
}
_timeLastBuildingDropped = gpGlobals->time;
_plan = kNoBuildPlan;
}
}
}
}
void BuilderStrategy::checkBuildStatus()
{
if (_bot.getNavigationEngine() != NULL) {
if (_bot.getResources() >= _targetRes) {
_log.Debug("Resources have reached target, switching to build mode");
_bot.getNavigationEngine()->resume();
_waitStartTime = -1;
} else if (gpGlobals->time > _waitStartTime + RES_WAIT_TIMEOUT) {
_log.Debug("Moving around to keep our feet warm");
_bot.getNavigationEngine()->resume();
_waitStartTime = -1;
}
}
}
void BuilderStrategy::addReward(vector<Reward>& rewards, tNodeId wptId, float rewardVal)
{
if (_bot.getPathManager().nodeIdValid(wptId)) {
float distance = _bot.getPathManager().getDistance(wptId);
// let's not add it if it's not in the optimised tree search space
if (!_bot.hasFailedToBuildAt(wptId) && distance < MAX_DISTANCE_ESTIMATE) {
float timeDiff = gpGlobals->time - HiveMind::getVisitTime(wptId);
float scale = (REWARD_TIMEOUT + timeDiff) / REWARD_TIMEOUT;
// let's add an exponentially increasing desire to build so that we always keep building and don't
// camp in a hive (e.g. if we're overly scared of marine buildings)
float lastBuildTimeDiff = gpGlobals->time - _timeLastBuildingDropped;
if (lastBuildTimeDiff > 0) {
scale *= (1 + exp(TIME_SCALING_FACTOR * (lastBuildTimeDiff * - 60)));
}
float scaledRewardVal = SCALING_FACTOR * rewardVal * exp((-DISTANCE_SCALING_FACTOR) * distance) * scale * scale;
// Add a strong imperative to go to things that are very close to us
if (distance < ARTIFICIAL_DISTANCE_BOOST_THRESHOLD) {
scaledRewardVal *= ARTIFICIAL_DISTANCE_BOOST;
}
Reward reward(wptId, scaledRewardVal, TranslationManager::getTranslation(getBuildPlanName()));
rewards.push_back(reward);
//_log.Debug("Rewarding waypoint %d with reward %f", wptId, scaledRewardVal);
_buildableLocations.push_back(wptId);
//WaypointDebugger::drawDebugBeam(_bot.getEdict()->v.origin, gpBotManager->getWaypointManager().getOrigin(wptId), 255, 0, 0);
}
}
}
string BuilderStrategy::getBuildPlanName() const
{
switch (_plan) {
case kNoBuildPlan: return "BuildNothing";
case kBuildResTower: return "BuildResTower";
case kBuildHive: return "BuildHive";
case kBuildOffenseChamber: return "BuildOffenseChamber";
case kBuildDefenseChamber: return "BuildDefenseChamber";
case kBuildMovementChamber: return "BuildMovementChamber";
case kBuildSensoryChamber: return "BuildSensoryChamber";
default: return "BuildUnknown";
}
}
bool BuilderStrategy::locationIsBuildable(tNodeId wptId)
{
if (_bot.hasFailedToBuildAt(wptId)) {
return false;
}
switch (_plan) {
case kBuildHive:
case kBuildResTower:
return find(_buildableLocations.begin(), _buildableLocations.end(), wptId) != _buildableLocations.end();
case kBuildDefenseChamber:
case kBuildSensoryChamber:
case kBuildMovementChamber:
case kBuildOffenseChamber:
bool locationOk = false;
if ((gpGlobals->time > _timeLastBuildingDropped + HIVE_DEFENSE_TIMEOUT) &&
((find(_buildableLocations.begin(), _buildableLocations.end(), wptId) != _buildableLocations.end()) ||
(HiveManager::distanceToNearestHive(_bot.getEdict()->v.origin) < _hiveDefenseRange)))
{
// Let's not build underwater
if (UTIL_PointContents(_bot.getEdict()->v.origin) == CONTENTS_WATER) {
return false;
}
// Let's not block ladders
edict_t* pLadder = WorldStateUtil::findClosestEntity("func_ladder", _bot.getEdict()->v.origin);
if (!FNullEnt(pLadder)) {
float range = (_bot.getEdict()->v.origin.Make2D() - pLadder->v.origin.Make2D()).Length();
return (range > 200);
} else {
return true;
}
}
}
return false;
}
bool BuilderStrategy::otherChamberTooClose(tNodeId wptId)
{
edict_t* pClosestChamber = NULL;
float allowedRange = 10000.0;
switch (_plan) {
case kBuildOffenseChamber:
pClosestChamber = WorldStateUtil::findClosestEntity("offensechamber", _bot.getEdict()->v.origin);
allowedRange = MIN_OC_DISTANCE;
break;
case kBuildSensoryChamber:
pClosestChamber = WorldStateUtil::findClosestEntity("sensorychamber", _bot.getEdict()->v.origin);
allowedRange = MIN_SC_DISTANCE;
break;
}
if (pClosestChamber != NULL) {
float range = (_bot.getEdict()->v.origin - pClosestChamber->v.origin).Length();
if (range < allowedRange) {
return true;
}
}
return false;
}
Log BuilderStrategy::_log("strategy/BuilderStrategy");
|
UbuntuEvangelist/OG-Platform | projects/OG-Analytics/src/test/java/com/opengamma/analytics/financial/interestrate/capletstripping/FlatSurfaceFitTest.java | <filename>projects/OG-Analytics/src/test/java/com/opengamma/analytics/financial/interestrate/capletstripping/FlatSurfaceFitTest.java<gh_stars>10-100
/**
* Copyright (C) 2014 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.analytics.financial.interestrate.capletstripping;
import static org.testng.AssertJUnit.assertEquals;
import java.util.ArrayList;
import java.util.List;
import org.testng.annotations.Test;
import com.opengamma.analytics.financial.model.volatility.discrete.DiscreteVolatilityFunction;
import com.opengamma.analytics.financial.model.volatility.discrete.DiscreteVolatilityFunctionProvider;
import com.opengamma.analytics.financial.model.volatility.surface.ParameterizedVolatilitySurfaceProvider;
import com.opengamma.analytics.financial.model.volatility.surface.VolatilitySurfaceProvider;
import com.opengamma.analytics.math.differentiation.VectorFieldFirstOrderDifferentiator;
import com.opengamma.analytics.math.function.Function1D;
import com.opengamma.analytics.math.function.ParameterizedSurface;
import com.opengamma.analytics.math.matrix.DoubleMatrix1D;
import com.opengamma.analytics.math.matrix.DoubleMatrix2D;
import com.opengamma.util.test.TestGroup;
import com.opengamma.util.tuple.DoublesPair;
/**
* Fit a flat (caplet) volatility surface to the cap market values. Clearly, having only one parameter, this will not be
* a good fit in terms of recovering the market values, however this does test a lot of the functionality of the caplet
* stripper.
*/
@Test(groups = TestGroup.UNIT)
public class FlatSurfaceFitTest extends CapletStrippingSetup {
private final static DiscreteVolatilityFunctionProvider DISCRETE_FLAT_SURFACE;
private final static VolatilitySurfaceProvider FLAT_SURFACE;
static {
DISCRETE_FLAT_SURFACE = new DiscreteVolatilityFunctionProvider() {
@Override
public DiscreteVolatilityFunction from(final DoublesPair[] expiryStrikePoints) {
final int size = expiryStrikePoints.length;
final DoubleMatrix2D one = new DoubleMatrix2D(size, 1);
for (int i = 0; i < size; i++) {
one.getData()[i][0] = 1.0;
}
return new DiscreteVolatilityFunction() {
@Override
public DoubleMatrix2D calculateJacobian(final DoubleMatrix1D x) {
return one;
}
@Override
public DoubleMatrix1D evaluate(final DoubleMatrix1D x) {
return new DoubleMatrix1D(size, x.getEntry(0));
}
@Override
public int getLengthOfDomain() {
return 1;
}
@Override
public int getLengthOfRange() {
return size;
}
};
}
};
ParameterizedSurface fs = new ParameterizedSurface() {
@Override
public int getNumberOfParameters() {
return 1;
}
@Override
public Double evaluate(DoublesPair x, DoubleMatrix1D parameters) {
return parameters.getEntry(0);
}
};
FLAT_SURFACE = new ParameterizedVolatilitySurfaceProvider(fs);
}
@Test
public void solveSinglePrice() {
double vol = 0.5;
CapFloor cap = getATMCaps().get(0);
List<CapFloor> caps = new ArrayList<>();
caps.add(cap);
MultiCapFloorPricer pricer = new MultiCapFloorPricer(caps, getYieldCurves());
double price = pricer.price(new double[] {vol })[0];
final CapletStrippingCore imp = new CapletStrippingCore(pricer, FLAT_SURFACE);
CapletStrippingResult res = imp.rootFindForCapPrices(new double[] {price }, new DoubleMatrix1D(1, 0.3));
DoubleMatrix1D fitParms = res.getFitParameters();
assertEquals(1, fitParms.getNumberOfElements());
assertEquals(0.5, fitParms.getEntry(0), 1e-8);
}
@Test
public void priceFitTest() {
final MultiCapFloorPricer pricer = new MultiCapFloorPricer(getAllCaps(), getYieldCurves());
final CapletStrippingCore imp = new CapletStrippingCore(pricer, DISCRETE_FLAT_SURFACE);
final CapletStrippingResult res = imp.leastSqrSolveForCapPrices(getAllCapPrices(), new DoubleMatrix1D(0.4));
// since this is an unbiased LS fit to price it is skewed to fitting the long (10 year caps)
assertEquals(0.3654148224492559, res.getFitParameters().getEntry(0), 1e-15);
}
@Test
public void priceVegaFitTest() {
final MultiCapFloorPricer pricer = new MultiCapFloorPricer(getAllCaps(), getYieldCurves());
final CapletStrippingCore imp = new CapletStrippingCore(pricer, DISCRETE_FLAT_SURFACE);
final double[] capVols = getAllCapVols();
final double[] vega = pricer.vega(capVols);
final double[] prices = pricer.price(capVols);
final CapletStrippingResult res = imp.solveForCapPrices(prices, vega, new DoubleMatrix1D(0.4));
// since this is a vega weighted LS fit to price it looks more like the average cap volatility
assertEquals(0.49945534507287803, res.getFitParameters().getEntry(0), 1e-15);
}
@Test
public void volFitTest() {
final double[] vols = getAllCapVols();
final int n = vols.length;
double sum = 0;
for (int i = 0; i < n; i++) {
sum += vols[i];
}
sum /= n;
final MultiCapFloorPricer pricer = new MultiCapFloorPricer(getAllCaps(), getYieldCurves());
final CapletStrippingCore imp = new CapletStrippingCore(pricer, DISCRETE_FLAT_SURFACE);
final CapletStrippingResult res = imp.leastSqrSolveForCapVols(vols, new DoubleMatrix1D(0.4));
// since this is an unbiased LS fit to cap volatilities, the fit is very close to the average cap volatility
assertEquals(sum, res.getFitParameters().getEntry(0), 1e-7);
assertEquals(0.6051342199655784, res.getFitParameters().getEntry(0), 1e-8);
}
/**
* This tests the cap-vol Jacobian function
*/
@Test
public void functionTest() {
final double vol = 0.4;
final MultiCapFloorPricer pricer = new MultiCapFloorPricer(getAllCaps(), getYieldCurves());
final CapletStrippingCore imp = new CapletStrippingCore(pricer, DISCRETE_FLAT_SURFACE);
final Function1D<DoubleMatrix1D, DoubleMatrix1D> func = imp.getCapVolFunction();
final VectorFieldFirstOrderDifferentiator diff = new VectorFieldFirstOrderDifferentiator();
final Function1D<DoubleMatrix1D, DoubleMatrix2D> jacFDFunc = diff.differentiate(func);
final Function1D<DoubleMatrix1D, DoubleMatrix2D> jacFunc = imp.getCapVolJacobianFunction();
final DoubleMatrix1D pos = new DoubleMatrix1D(vol);
final DoubleMatrix1D capVols = func.evaluate(pos);
final DoubleMatrix2D jac = jacFunc.evaluate(pos);
final DoubleMatrix2D jacFD = jacFDFunc.evaluate(pos);
final int n = capVols.getNumberOfElements();
for (int i = 0; i < n; i++) {
assertEquals(vol, capVols.getEntry(i), 1e-9);
assertEquals(1.0, jac.getEntry(i, 0), 5e-8);
assertEquals(1.0, jacFD.getEntry(i, 0), 1e-6);
}
}
}
|
miko3k/hardcode | hardcode-guava/src/test/java/org/deletethis/hardcode/guava/SplitTest.java | <gh_stars>0
package org.deletethis.hardcode.guava;
import com.google.common.collect.*;
import org.deletethis.hardcode.Hardcode;
import org.deletethis.hardcode.testing.HardcodeTesting;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestName;
public class SplitTest {
@Rule
public TestName name = new TestName();
void testSplit(Object o) {
SplitWrapper1000 mm = new SplitWrapper1000(o);
SplitWrapper1000 mm2 = HardcodeTesting.supply(Hardcode.defaultConfig().createClass("Split" + name.getMethodName(), mm));
Assert.assertEquals(mm, mm2);
}
@Test
public void multimap() {
ImmutableListMultimap.Builder<Integer,Integer> bld = ImmutableListMultimap.builder();
for(int i=0;i<100;++i) {
for(int j=0;j<100;j++) {
bld.put(i, j);
}
}
testSplit(bld.build());
}
@Test
public void multimap2() {
ImmutableSetMultimap.Builder<Integer,Integer> bld = ImmutableSetMultimap.builder();
for(int i=0;i<100;++i) {
for(int j=0;j<100;j++) {
bld.put(i, j);
}
}
testSplit(bld.build());
}
@Test
public void map() {
ImmutableMap.Builder<Integer,Integer> bld = ImmutableMap.builder();
for (int i = 0; i < 20000; ++i) {
bld.put(i, i);
}
testSplit(bld.build());
}
@Test
public void list() {
ImmutableList.Builder<Integer> bld = ImmutableList.builder();
for(int i=0;i<20000;++i) {
bld.add(i);
}
testSplit(bld.build());
}
@Test
public void set() {
ImmutableSet.Builder<Integer> bld = ImmutableSet.builder();
for(int i=0;i<20000;++i) {
bld.add(i);
}
testSplit(bld.build());
}
}
|
Wesley1808/ServerCore | src/main/java/me/wesley1808/servercore/mixin/features/misc/ChunkMapMixin.java | <filename>src/main/java/me/wesley1808/servercore/mixin/features/misc/ChunkMapMixin.java
package me.wesley1808.servercore.mixin.features.misc;
import it.unimi.dsi.fastutil.objects.ObjectIterator;
import me.wesley1808.servercore.common.config.tables.FeatureConfig;
import me.wesley1808.servercore.common.utils.DynamicManager;
import net.minecraft.server.level.ChunkHolder;
import net.minecraft.server.level.ChunkMap;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Redirect;
@Mixin(ChunkMap.class)
public abstract class ChunkMapMixin {
@Redirect(
method = "processUnloads",
require = 0,
at = @At(
value = "INVOKE",
target = "Lit/unimi/dsi/fastutil/objects/ObjectIterator;hasNext()Z",
ordinal = 0
)
)
private boolean limitChunkSaves(ObjectIterator<ChunkHolder> iterator) {
final int threshold = FeatureConfig.CHUNK_SAVE_THRESHOLD.get();
if (threshold < 0) return iterator.hasNext();
return DynamicManager.getAverageTickTime() < threshold && iterator.hasNext();
}
} |
loupipalien/java | src/main/java/com/ltchen/java/util/RandomList.java | <reponame>loupipalien/java
package com.ltchen.java.util;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
/**
* @file : RandomList.java
* @date : 2017年7月18日
* @author : ltchen
* @email : <EMAIL>
* @desc : 简单泛型练习
* @param <T>
*/
public class RandomList<T> {
private List<T> list = new ArrayList<T>();
private Random random = new Random(47);
public void add(T item){
list.add(item);
}
public T select(){
return list.get(random.nextInt(list.size()));
}
public static void main(String[] args) {
RandomList<String> rs = new RandomList<String>();
for (String str : "The quick brown fox jumped over the lazy brown dog".split(" ")) {
rs.add(str);
}
for (int i = 0; i < 10; i++) {
System.out.println(rs.select());
}
}
}
|
caponetto/kogito-editors-java | kie-wb-common-stunner/kie-wb-common-stunner-core/kie-wb-common-stunner-commons/kie-wb-common-stunner-client-common/src/main/java/org/kie/workbench/common/stunner/core/client/command/RequestCommands.java | /*
* Copyright 2019 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kie.workbench.common.stunner.core.client.command;
import java.util.ArrayList;
import java.util.Stack;
import java.util.function.Consumer;
import org.kie.workbench.common.stunner.core.client.canvas.AbstractCanvasHandler;
import org.kie.workbench.common.stunner.core.command.Command;
import org.kie.workbench.common.stunner.core.command.impl.CompositeCommand;
public class RequestCommands implements CommandRequestLifecycle {
private final Consumer<Command<AbstractCanvasHandler, CanvasViolation>> completedCommand;
private final Consumer<Command<AbstractCanvasHandler, CanvasViolation>> rollbackCommand;
private Stack<Command<AbstractCanvasHandler, CanvasViolation>> commands;
private boolean rollback;
public static class Builder {
private Consumer<Command<AbstractCanvasHandler, CanvasViolation>> completedCommand;
private Consumer<Command<AbstractCanvasHandler, CanvasViolation>> rollbackCommand;
public Builder onComplete(Consumer<Command<AbstractCanvasHandler, CanvasViolation>> consumer) {
this.completedCommand = consumer;
return this;
}
public Builder onRollback(Consumer<Command<AbstractCanvasHandler, CanvasViolation>> consumer) {
this.rollbackCommand = consumer;
return this;
}
public RequestCommands build() {
return new RequestCommands(completedCommand, rollbackCommand);
}
}
RequestCommands(final Consumer<Command<AbstractCanvasHandler, CanvasViolation>> completedCommand,
final Consumer<Command<AbstractCanvasHandler, CanvasViolation>> rollbackCommand) {
this.completedCommand = completedCommand;
this.rollbackCommand = rollbackCommand;
}
@Override
public void start() {
commands = new Stack<>();
rollback = false;
}
public void push(Command<AbstractCanvasHandler, CanvasViolation> command) {
commands.push(command);
}
boolean isStarted() {
return null != commands;
}
@Override
public void rollback() {
rollback = true;
}
@Override
public void complete() {
if (null != commands && !commands.isEmpty()) {
final CompositeCommand<AbstractCanvasHandler, CanvasViolation> composite =
new CompositeCommand.Builder<AbstractCanvasHandler, CanvasViolation>()
.reverse()
.addCommands(new ArrayList<>(commands))
.build();
if (rollback) {
rollbackCommand.accept(composite);
} else {
completedCommand.accept(composite);
}
}
clear();
}
void clear() {
if (null != commands) {
commands.clear();
commands = null;
}
rollback = false;
}
}
|
jokimina/aliyunpy | tests/test_client_cs.py | <reponame>jokimina/aliyunpy
import json
import httpretty
from .base import BaseAliyunTestCase
from .config import auto_load_fixture, suppress_warnings
class AliyunClientCsTestCase(BaseAliyunTestCase):
@suppress_warnings
@httpretty.activate
@auto_load_fixture
def test_list_cluster(self):
self.assertEqual(3, len(self.client.cs.list_cluster()))
self.assertEqual('aliyun', self.client.cs.list_cluster(cs_type='aliyun')[0].get('cluster_type'))
self.assertEqual('Kubernetes', self.client.cs.list_cluster(cs_type='Kubernetes')[0].get('cluster_type'))
self.assertEqual('ManagedKubernetes', self.client.cs.list_cluster(cs_type='ManagedKubernetes')[0]
.get('cluster_type'))
def test_list_cluster_real(self):
r = self.client.cs.list_cluster()
# r = [x['cluster_type'] for x in r]
print(json.dumps(r, indent=2, ensure_ascii=False))
@suppress_warnings
def test_list_service(self):
r = self.client.cs.list_service(cs_id='c3f555f50caf14faeb0b380eb3621e09f')
# r = self.client.cs.list_service(cs_id='c9001581cfd71416a88e3d69534439052', cs_type='Kubernetes')
# d = list(set([x['project'] for x in r]))
d = list(set([s["project"] for s in r]))
print("\n".join(d))
# d = r[0]
# d.sort()
# print(f'Total count: {len(d)}')
# print('\n'.join(d))
# d = r[0]
# print(json.dumps(d, indent=2, ensure_ascii=False))
# print(d.get('metadata', {}).get('labels', {}).get('app', ''))
def test_list_ingress(self):
r = self.client.cs.list_ingress(cs_id='c9001581cfd71416a88e3d69534439052')
d = r[0]
print(json.dumps(d, indent=2, ensure_ascii=False))
|
gunpowder78/google-research | nopad_inception_v3_fcn/eval_inception_v3_fcn.py | # coding=utf-8
# Copyright 2022 The Google Research 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.
# Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Generic evaluation script that evaluates a model using a given dataset."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import math
import tensorflow.compat.v1 as tf
import tf_slim as slim
from nopad_inception_v3_fcn import inception_v3_fcn
from nopad_inception_v3_fcn import network_params
from tensorflow_models.slim.datasets import dataset_factory
from tensorflow_models.slim.preprocessing import preprocessing_factory
tf.app.flags.DEFINE_integer(
'batch_size', 16, 'The number of samples in each batch.')
tf.app.flags.DEFINE_string(
'checkpoint_path', '/tmp/tfmodel/',
'The directory where the model was written to or an absolute path to a '
'checkpoint file.')
tf.app.flags.DEFINE_string(
'eval_dir', '/tmp/tfmodel/', 'Directory where the results are saved to.')
tf.app.flags.DEFINE_string(
'dataset_name', 'imagenet', 'The name of the dataset to load.')
tf.app.flags.DEFINE_string(
'dataset_split_name', 'test', 'The name of the train/test split.')
tf.app.flags.DEFINE_string(
'dataset_dir', None, 'The directory where the dataset files are stored.')
tf.app.flags.DEFINE_integer('receptive_field_size', None,
'Model receptive field size')
FLAGS = tf.app.flags.FLAGS
# Number of threads used for preprocessing input data into batches.
PREPROCESSING_THREADS = 4
def main(_):
if not FLAGS.dataset_dir:
raise ValueError('You must supply the dataset directory with --dataset_dir')
tf.logging.set_verbosity(tf.logging.INFO)
with tf.Graph().as_default():
_ = slim.get_or_create_global_step() # Required when creating the session.
######################
# Select the dataset #
######################
dataset = dataset_factory.get_dataset(
FLAGS.dataset_name, FLAGS.dataset_split_name, FLAGS.dataset_dir)
#########################
# Configure the network #
#########################
inception_params = network_params.InceptionV3FCNParams(
receptive_field_size=FLAGS.receptive_field_size,
prelogit_dropout_keep_prob=0.8,
depth_multiplier=0.1,
min_depth=16,
inception_fcn_stride=16,
)
conv_params = network_params.ConvScopeParams(
dropout=False,
dropout_keep_prob=0.8,
batch_norm=True,
batch_norm_decay=0.99,
l2_weight_decay=4e-05,
)
network_fn = inception_v3_fcn.get_inception_v3_fcn_network_fn(
inception_params,
conv_params,
num_classes=dataset.num_classes,
is_training=False,
)
##############################################################
# Create a dataset provider that loads data from the dataset #
##############################################################
provider = slim.dataset_data_provider.DatasetDataProvider(
dataset,
shuffle=False,
common_queue_capacity=2 * FLAGS.batch_size,
common_queue_min=FLAGS.batch_size)
[image, label] = provider.get(['image', 'label'])
#####################################
# Select the preprocessing function #
#####################################
image_preprocessing_fn = preprocessing_factory.get_preprocessing(
'inception_v3', is_training=False)
eval_image_size = FLAGS.receptive_field_size
image = image_preprocessing_fn(image, eval_image_size, eval_image_size)
images, labels = tf.train.batch(
[image, label],
batch_size=FLAGS.batch_size,
num_threads=PREPROCESSING_THREADS,
capacity=5 * FLAGS.batch_size)
####################
# Define the model #
####################
logits, _ = network_fn(images)
variables_to_restore = slim.get_variables_to_restore()
predictions = tf.argmax(logits, 1)
labels = tf.squeeze(labels)
# Define the metrics:
names_to_values, names_to_updates = slim.metrics.aggregate_metric_map({
'Accuracy': slim.metrics.streaming_accuracy(predictions, labels),
'Recall_2': slim.metrics.streaming_recall_at_k(
logits, labels, 2),
})
# Print the summaries to screen.
for name, value in names_to_values.items():
summary_name = 'eval/%s' % name
op = tf.summary.scalar(summary_name, value, collections=[])
op = tf.Print(op, [value], summary_name)
tf.add_to_collection(tf.GraphKeys.SUMMARIES, op)
# This ensures that we make a single pass over all of the data.
num_batches = math.ceil(dataset.num_samples / float(FLAGS.batch_size))
if tf.gfile.IsDirectory(FLAGS.checkpoint_path):
checkpoint_path = tf.train.latest_checkpoint(FLAGS.checkpoint_path)
else:
checkpoint_path = FLAGS.checkpoint_path
tf.logging.info('Evaluating %s', checkpoint_path)
slim.evaluation.evaluate_once(
master='',
checkpoint_path=checkpoint_path,
logdir=FLAGS.eval_dir,
num_evals=num_batches,
eval_op=list(names_to_updates.values()),
session_config=tf.ConfigProto(allow_soft_placement=True),
variables_to_restore=variables_to_restore)
if __name__ == '__main__':
tf.app.run()
|
whatmk/new | api/beginBalance.js | <reponame>whatmk/new<filename>api/beginBalance.js
/**
* 会计期初余额api接口
*/
/**
* 查询期初余额
* @param currentYear 查询年度
* @param accountTypeId 科目类型id(可选)
* @param isQuantityCalc 是否数量核算(可选)
* @param isMultiCalc 是否外币核算(可选)
* @returns {*}
*/
export function init(post, accountTypeId, currentYear, isQuantityCalc, isMultiCalc){
return post('/v1/accountPeriodBegin/init',
{
accountTypeId: accountTypeId,
currentYear: currentYear,
isQuantityCalc: isQuantityCalc,
isMultiCalc: isMultiCalc
})
}
/**
* 查询期初余额
* @param orgId 组织机构id
* @param accountTypeId 科目类型id(可选)
* @returns {*}
*/
export function query(post, currentYear, accountTypeId){
return post('/v1/accountPeriodBegin/query', {currentYear:currentYear, accountTypeId:accountTypeId})
}
/**
* 新增期初余额
* @param list 科目余额列表
* @returns {*}
*/
export function addBatch(post, list){
return post('/v1/accountPeriodBegin/createBatch', list)
}
/**
* 更新期初余额
* @param list 科目余额列表
* @returns {*}
*/
export function updateBatch(post, list){
return post('/v1/accountPeriodBegin/updateBatch', list)
}
/**
* 删除期初余额
* @param id 期初余额id
* @param selectedYear 界面选中年度
* @returns {*}
*/
export function deleteBalance(post, id, selectedYear){
return post('/v1/accountPeriodBegin/delete', {id: id, currentYear: selectedYear})
}
/**
* 保存期初余额 通过id判判断,有id的进行更新,无id进行新增
* @param list 科目余额列表
* @returns {*}
*/
export function createAndUpdateBatch(post, list){
return post('/v1/accountPeriodBegin/createAndUpdateBatch', list)
}
/**
* 期初余额试算平衡
* @param currentYear 当前年度
* @returns {*}
*/
export function getAccountBeginBalanceDrCr(post, currentYear){
return post('/v1/accountPeriodBegin/getAccountBeginBalanceDrCr', {currentYear: currentYear})
}
/**
* 查询当前组织是否存在期初
* @returns {*}
*/
export function haveAccountPeriodBegin(post){
return post('/v1/accountPeriodBegin/haveAccountPeriodBegin')
}
/**
* 期初余额中的[调整]按钮是否可见
* @returns {*}
*/
export function isResetButtonVisible(post){
return post('/v1/accountPeriodBegin/isResetButtonVisible')
}
/**
* 期初余额下载导入模板
* @returns {*}
*/
export function exportTemplate(post,filename){
return post('/v1/accountPeriodBegin/exporttemplate', {filename:filename})
}
/**
* 期初余额 待抵扣进项税额期初 查询接口
* @returns {*}
*/
export function periodBeginQuery(post){
return post('/v1/InputTaxDeduct/periodBeginQuery')
}
/**
* 期初余额 待抵扣进项税额期初 增删改接口
* @param
{ "rowStatus":1, --行状态 0未改变,1新增,2修改,3删除
"voucherDate":"2017-06-01", --入账日期
"code":"001", --凭证号
"summary":"期初进行税额", --摘要
"amount":1000.32, --待抵扣进项税额
"isPeriodBeginDeduct":0 --是否启用前已转出(2017年1月至2017年4月已转出)
}
* @returns {*}
*/
export function save(post,list){
return post('/v1/InputTaxDeduct/save',list)
} |
AtteKoivukangas/sanajahti-ratkaisin | src/App/SolutionList/SolutionList.js | import { useContext } from 'react';
import { groupSolutions } from './utils/solutionHelper';
import { storeContext } from 'shared/store';
import './SolutionList.css';
const SolutionList = () => {
const { state } = useContext(storeContext);
return (
<div>
{groupSolutions(state.solutions).map(({ length, words }) =>
<div key={length}>
<h3 className='word-container-title'>{length} kirjaimiset sanat</h3>
<p className='word-container'>
{words.map(word => word.charAt(0)+word.slice(1).toLowerCase()).join(', ')}
</p>
</div>
)}
</div>
);
};
export default SolutionList; |
ghuntley/COVIDSafe_1.0.11.apk | src/sources/io/reactivex/MaybeTransformer.java | package io.reactivex;
public interface MaybeTransformer<Upstream, Downstream> {
MaybeSource<Downstream> apply(Maybe<Upstream> maybe);
}
|
bvfalcon/apache-camel | components/camel-digitalocean/src/test/java/org/apache/camel/component/digitalocean/DigitalOceanComponentTest.java | /*
* 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.camel.component.digitalocean;
import com.myjeeva.digitalocean.impl.DigitalOceanClient;
import com.myjeeva.digitalocean.pojo.Account;
import org.apache.camel.BindToRegistry;
import org.apache.camel.EndpointInject;
import org.apache.camel.Exchange;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.digitalocean.constants.DigitalOceanHeaders;
import org.apache.camel.component.digitalocean.constants.DigitalOceanOperations;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.test.junit5.CamelTestSupport;
import org.junit.jupiter.api.Test;
import static org.apache.camel.test.junit5.TestSupport.assertIsInstanceOf;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class DigitalOceanComponentTest extends CamelTestSupport {
@EndpointInject("mock:result")
protected MockEndpoint mockResultEndpoint;
@BindToRegistry("digitalOceanClient")
DigitalOceanClient digitalOceanClient = new DigitalOceanClientMock();
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
public void configure() {
from("direct:getAccountInfo")
.setHeader(DigitalOceanHeaders.OPERATION, constant(DigitalOceanOperations.get))
.to("digitalocean:account?digitalOceanClient=#digitalOceanClient")
.to("mock:result");
}
};
}
@Test
public void testGetAccountInfo() throws Exception {
mockResultEndpoint.expectedMinimumMessageCount(1);
Exchange exchange = template.request("direct:getAccountInfo", null);
assertMockEndpointsSatisfied();
assertIsInstanceOf(Account.class, exchange.getMessage().getBody());
assertEquals("<EMAIL>", exchange.getMessage().getBody(Account.class).getEmail());
}
}
|
mousepawmedia/libdeps | cpgf/src/metadata/irrlicht/meta_irrlicht_IMaterialRendererServices.cpp | <filename>cpgf/src/metadata/irrlicht/meta_irrlicht_IMaterialRendererServices.cpp
// Auto generated file, don't modify.
#include "irrlicht.h"
#include "IMaterialRendererServices.h"
#include "cpgf/metadata/irrlicht/meta_irrlicht_IMaterialRendererServices.h"
using namespace cpgf;
namespace meta_irrlicht {
GDefineMetaInfo createMetaClass_IMaterialRendererServices()
{
GDefineMetaGlobalDangle _d = GDefineMetaGlobalDangle::dangle();
{
GDefineMetaClass<irr::video::IMaterialRendererServices> _nd = GDefineMetaClass<irr::video::IMaterialRendererServices>::Policy<MakePolicy<GMetaRuleDefaultConstructorAbsent, GMetaRuleCopyConstructorAbsent> >::declare("IMaterialRendererServices");
buildMetaClass_IMaterialRendererServices(0, _nd);
_d._class(_nd);
}
return _d.getMetaInfo();
}
} // namespace meta_irrlicht
|
mikehelmick/CascadeLMS | vendor/plugins/oauth-plugin/lib/generators/oauth_consumer/templates/controller.rb | require 'oauth/controllers/consumer_controller'
class OauthConsumersController < ApplicationController
include Oauth::Controllers::ConsumerController
# Replace this with the equivalent for your authentication framework
# Eg. for devise
#
# before_filter :authenticate_user!, :only=>:index
before_filter :ensure_login, :only=>:index
def index
@consumer_tokens=ConsumerToken.all :conditions=>{:user_id=>current_user.id}
@services=OAUTH_CREDENTIALS.keys-@consumer_tokens.collect{|c| c.class.service_name}
end
def callback
super
end
def client
super
end
protected
# Change this to decide where you want to redirect user to after callback is finished.
# params[:id] holds the service name so you could use this to redirect to various parts
# of your application depending on what service you're connecting to.
def go_back
redirect_to root_url
end
# The plugin requires logged_in? to return true or false if the user is logged in. Uncomment and
# call your auth frameworks equivalent below if different. eg. for devise:
#
# def logged_in?
# user_signed_in?
# end
# The plugin requires current_user to return the current logged in user. Uncomment and
# call your auth frameworks equivalent below if different.
# def current_user
# current_person
# end
# The plugin requires a way to log a user in. Call your auth frameworks equivalent below
# if different. eg. for devise:
#
# def current_user=(user)
# sign_in(user)
# end
# Override this to deny the user or redirect to a login screen depending on your framework and app
# if different. eg. for devise:
#
# def deny_access!
# raise Acl9::AccessDenied
# end
end
|
purepanic/AutoRuneLite | src/org/osrs/api/wrappers/GameShell.java | package org.osrs.api.wrappers;
public interface GameShell{
public java.awt.Canvas canvas();
public MouseWheelListener mouseWheelListener();
} |
PyXRD/pyxrd | pyxrd/probabilities/controllers.py | # coding=UTF-8
# ex:ts=4:sw=4:et=on
# Copyright (c) 2013, <NAME>
# All rights reserved.
# Complete license can be found in the LICENSE file.
from mvc import Controller
from pyxrd.generic.controllers import BaseController
from pyxrd.probabilities.views import get_correct_probability_views
from pyxrd.probabilities.models import RGbounds
def get_correct_probability_controllers(probability, parent_controller, independents_view, dependents_view):
if probability is not None:
G = probability.G
R = probability.R
if (RGbounds[R, G - 1] > 0):
return BaseController(model=probability, parent=parent_controller, view=independents_view), \
MatrixController(current=R, model=probability, parent=parent_controller, view=dependents_view)
else:
raise ValueError("Cannot (yet) handle R%d for %d layer structures!" % (R, G))
class EditProbabilitiesController(BaseController):
independents_view = None
matrix_view = None
auto_adapt = False
def __init__(self, *args, **kwargs):
BaseController.__init__(self, *args, **kwargs)
self._init_views(kwargs["view"])
self.update_views()
def _init_views(self, view):
self.independents_view, self.dependents_view = get_correct_probability_views(self.model, view)
self.independents_controller, self.dependents_controller = get_correct_probability_controllers(self.model, self, self.independents_view, self.dependents_view)
view.set_views(self.independents_view, self.dependents_view)
@BaseController.model.setter
def model(self, model):
if self.view is not None:
self.independents_controller.model = None # model
self.dependents_controller.model = None # model
super(EditProbabilitiesController, self)._set_model(model)
if self.view is not None:
self.independents_controller.model = model
self.dependents_controller.model = model
self.update_views()
def update_views(self): # needs to be called whenever an independent value changes
with self.model.data_changed.hold():
self.dependents_view.update_matrices(self.model)
self.independents_view.update_matrices(self.model)
def register_adapters(self):
return
# ------------------------------------------------------------
# Notifications of observable properties
# ------------------------------------------------------------
@Controller.observe("data_changed", signal=True)
def notif_updated(self, model, prop_name, info):
self.update_views()
return
pass # end of class
class MatrixController(BaseController):
auto_adapt = False
def __init__(self, current, *args, **kwargs):
BaseController.__init__(self, *args, **kwargs)
self.current_W = current
self.current_P = current
def register_adapters(self):
return
def on_w_prev_clicked(self, widget, *args):
self.current_W = self.view.show_w_matrix(self.current_W - 1)
def on_w_next_clicked(self, widget, *args):
self.current_W = self.view.show_w_matrix(self.current_W + 1)
def on_p_prev_clicked(self, widget, *args):
self.current_P = self.view.show_p_matrix(self.current_P - 1)
def on_p_next_clicked(self, widget, *args):
self.current_P = self.view.show_p_matrix(self.current_P + 1)
pass # end of class
|
King0987654/windows2000 | private/shell/ext/ftp/encoding.cpp | /*****************************************************************************\
FILE: encoding.cpp
DESCRIPTION:
Handle taking internet strings by detecting if they are UTF-8 encoded
or DBCS and finding out what code page was used.
\*****************************************************************************/
#include "priv.h"
#include "util.h"
#include "ftpurl.h"
#include "statusbr.h"
#include <commctrl.h>
#include <shdocvw.h>
/*****************************************************************************\
CLASS: CMultiLanguageCache
\*****************************************************************************/
HRESULT CMultiLanguageCache::_Init(void)
{
if (m_pml2)
return S_OK;
return CoCreateInstance(CLSID_CMultiLanguage, NULL, CLSCTX_INPROC_SERVER, IID_IMultiLanguage2, (void **) &m_pml2);
}
/*****************************************************************************\
CLASS: CWireEncoding
\*****************************************************************************/
CWireEncoding::CWireEncoding(void)
{
// We can go on the stack, so we may not be zero inited.
m_nConfidence = 0;
m_uiCodePage = CP_ACP; //
m_dwMode = 0;
m_fUseUTF8 = FALSE;
}
CWireEncoding::~CWireEncoding(void)
{
}
void CWireEncoding::_ImproveAccuracy(CMultiLanguageCache * pmlc, LPCWIRESTR pwStr, BOOL fUpdateCP, UINT * puiCodePath)
{
DetectEncodingInfo dei = {0};
INT nStructs = 1;
INT cchSize = lstrlenA(pwStr);
IMultiLanguage2 * pml2 = pmlc->GetIMultiLanguage2();
// Assume we will use the normal code page.
*puiCodePath = m_uiCodePage;
if (S_OK == pml2->DetectInputCodepage(MLDETECTCP_8BIT, CP_AUTO, (LPWIRESTR)pwStr, &cchSize, &dei, (INT *)&nStructs))
{
// Is it UTF8 or just plain ansi(CP_20127)?
if (((CP_UTF_8 == dei.nCodePage) || (CP_20127 == dei.nCodePage)) &&
(dei.nConfidence > 70))
{
// Yes, so make sure the caller uses UTF8 to decode but don't update
// the codepage.
*puiCodePath = CP_UTF_8;
}
else
{
if (fUpdateCP && (dei.nConfidence > m_nConfidence))
{
m_uiCodePage = dei.nCodePage;
m_nConfidence = dei.nConfidence;
}
}
}
}
HRESULT CWireEncoding::WireBytesToUnicode(CMultiLanguageCache * pmlc, LPCWIRESTR pwStr, DWORD dwFlags, LPWSTR pwzDest, DWORD cchSize)
{
HRESULT hr;
// Optimize for the fast common case.
if (Is7BitAnsi(pwStr))
{
pwzDest[0] = 0;
SHAnsiToUnicodeCP(CP_UTF_8, pwStr, pwzDest, cchSize);
hr = S_OK;
}
else
{
#ifdef FEATURE_CP_AUTODETECT
if (this)
{
CMultiLanguageCache mlcTemp;
UINT cchSizeTemp = cchSize;
UINT uiCodePageToUse;
if (!pmlc)
pmlc = &mlcTemp;
if (!pmlc || !pmlc->GetIMultiLanguage2())
return E_FAIL;
IMultiLanguage2 * pml2 = pmlc->GetIMultiLanguage2();
_ImproveAccuracy(pmlc, pwStr, (WIREENC_IMPROVE_ACCURACY & dwFlags), &uiCodePageToUse);
if (CP_ACP == uiCodePageToUse)
uiCodePageToUse = GetACP();
UINT cchSrcSize = lstrlenA(pwStr) + 1; // The need to do the terminator also.
hr = pml2->ConvertStringToUnicode(&m_dwMode, uiCodePageToUse, (LPWIRESTR)pwStr, &cchSrcSize, pwzDest, &cchSizeTemp);
if (!(EVAL(S_OK == hr)))
SHAnsiToUnicode(pwStr, pwzDest, cchSize);
}
else
#endif // FEATURE_CP_AUTODETECT
{
UINT uiCodePage = ((WIREENC_USE_UTF8 & dwFlags) ? CP_UTF_8 : CP_ACP);
SHAnsiToUnicodeCP(uiCodePage, pwStr, pwzDest, cchSize);
}
}
return hr;
}
HRESULT CWireEncoding::UnicodeToWireBytes(CMultiLanguageCache * pmlc, LPCWSTR pwzStr, DWORD dwFlags, LPWIRESTR pwDest, DWORD cchSize)
{
HRESULT hr = S_OK;
#ifdef FEATURE_CP_AUTODETECT
CMultiLanguageCache mlcTemp;
DWORD dwCodePage = CP_UTF_8;
DWORD dwModeTemp = 0;
DWORD * pdwMode = &dwModeTemp;
UINT cchSizeTemp = cchSize;
// In some cases, we don't know the site, so we use this.
// BUGBUG: Come back and force this to be set.
if (this)
{
dwCodePage = m_uiCodePage;
pdwMode = &m_dwMode;
}
if (!pmlc)
pmlc = &mlcTemp;
if (!pmlc)
return E_FAIL;
IMultiLanguage2 * pml2 = pmlc->GetIMultiLanguage2();
// if (WIREENC_USE_UTF8 & dwFlags)
// dwCodePage = CP_UTF_8;
UINT cchSrcSize = lstrlenW(pwzStr) + 1; // The need to do the terminator also.
if (CP_ACP == dwCodePage)
dwCodePage = GetACP();
hr = pml2->ConvertStringFromUnicode(pdwMode, dwCodePage, (LPWSTR) pwzStr, &cchSrcSize, pwDest, &cchSizeTemp);
if (!(EVAL(S_OK == hr)))
SHUnicodeToAnsi(pwzStr, pwDest, cchSize);
#else // FEATURE_CP_AUTODETECT
UINT nCodePage = ((WIREENC_USE_UTF8 & dwFlags) ? CP_UTF_8 : CP_ACP);
SHUnicodeToAnsiCP(nCodePage, pwzStr, pwDest, cchSize);
#endif // FEATURE_CP_AUTODETECT
return hr;
}
HRESULT CWireEncoding::ReSetCodePages(CMultiLanguageCache * pmlc, CFtpPidlList * pFtpPidlList)
{
CMultiLanguageCache mlcTemp;
if (!pmlc)
pmlc = &mlcTemp;
if (!pmlc)
return E_FAIL;
// BUGBUG/TODO:
return S_OK;
}
HRESULT CWireEncoding::CreateFtpItemID(CMultiLanguageCache * pmlc, LPFTP_FIND_DATA pwfd, LPITEMIDLIST * ppidl)
{
CMultiLanguageCache mlcTemp;
WCHAR wzDisplayName[MAX_PATH];
if (!pmlc)
pmlc = &mlcTemp;
WireBytesToUnicode(pmlc, pwfd->cFileName, (m_fUseUTF8 ? WIREENC_USE_UTF8 : WIREENC_NONE), wzDisplayName, ARRAYSIZE(wzDisplayName));
return FtpItemID_CreateReal(pwfd, wzDisplayName, ppidl);
}
HRESULT CWireEncoding::ChangeFtpItemIDName(CMultiLanguageCache * pmlc, LPCITEMIDLIST pidlBefore, LPCWSTR pwzNewName, BOOL fUTF8, LPITEMIDLIST * ppidlAfter)
{
CMultiLanguageCache mlcTemp;
WIRECHAR wWireName[MAX_PATH];
HRESULT hr;
if (!pmlc)
pmlc = &mlcTemp;
hr = UnicodeToWireBytes(pmlc, pwzNewName, (fUTF8 ? WIREENC_USE_UTF8 : WIREENC_NONE), wWireName, ARRAYSIZE(wWireName));
if (EVAL(SUCCEEDED(hr)))
hr = FtpItemID_CreateWithNewName(pidlBefore, pwzNewName, wWireName, ppidlAfter);
return hr;
}
BOOL SHIsUTF8Encoded(LPCWIRESTR pszIsUTF8)
{
unsigned int len = lstrlenA(pszIsUTF8);
LPCWIRESTR endbuf = pszIsUTF8 + len;
unsigned char byte2mask = 0x00;
unsigned char c;
int trailing = 0; // trailing (continuation) bytes to follow
while (pszIsUTF8 != endbuf)
{
c = *pszIsUTF8++;
if (trailing)
{
if ((c & 0xC0) == 0x80) // Does trailing byte follow UTF-8 format?
{
if (byte2mask) // Need to check 2nd byte for proper range?
{
if (c & byte2mask) // Are appropriate bits set?
byte2mask=0x00;
else
return 0;
trailing--;
}
}
else
return FALSE;
}
else
{
if ((c & 0x80) == 0x00)
continue; // valid 1 byte UTF-8
else
{
if ((c & 0xE0) == 0xC0) // valid 2 byte UTF-8
{
if (c & 0x1E) // Is UTF-8 byte in proper range?
{
trailing =1;
}
else
return FALSE;
}
else
{
if ((c & 0xF0) == 0xE0) // valid 3 byte UTF-8
{
if (!(c & 0x0F)) // Is UTF-8 byte in proper range?
byte2mask=0x20; // If not set mask to check next byte
trailing = 2;
}
else
{
if ((c & 0xF8) == 0xF0) // valid 4 byte UTF-8
{
if (!(c & 0x07)) // Is UTF-8 byte in proper range?
byte2mask=0x30; // If not set mask to check next byte
trailing = 3;
}
else
{
if ((c & 0xFC) == 0xF8) // valid 5 byte UTF-8
{
if (!(c & 0x03)) // Is UTF-8 byte in proper range?
byte2mask=0x38; // If not set mask to check next byte
trailing = 4;
}
else
{
if ((c & 0xFE) == 0xFC) // valid 6 byte UTF-8
{
if (!(c & 0x01)) // Is UTF-8 byte in proper range?
byte2mask=0x3C; // If not set mask to check next byte
trailing = 5;
}
else
return FALSE;
}
}
}
}
}
}
}
return (trailing == 0);
}
|
thunderbird/pungwecms | core/src/main/java/com/pungwe/cms/core/form/element/FieldsetElement.java | package com.pungwe.cms.core.form.element;
import com.pungwe.cms.core.annotations.ui.ThemeInfo;
import com.pungwe.cms.core.element.AbstractContentElement;
import com.pungwe.cms.core.element.AbstractRenderedElement;
import com.pungwe.cms.core.element.RenderedElement;
import com.pungwe.cms.core.element.basic.PlainTextElement;
import org.springframework.web.bind.annotation.ModelAttribute;
import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
/**
* Created by ian on 09/01/2016.
*/
@ThemeInfo("form/fieldset")
public class FieldsetElement extends AbstractContentElement {
protected RenderedElement legend;
@ModelAttribute("legend")
public RenderedElement getLegend() {
return legend;
}
public void setLegend(RenderedElement legend) {
this.legend = legend;
}
public void setLegend(String legend) {
setLegend(new PlainTextElement(legend));
}
@Override
protected Collection<String> excludedAttributes() {
return new LinkedList<>();
}
}
|
huangboju/Alpha | Alpha/Model/Conversion/ALPHADataConverterSource.h | <filename>Alpha/Model/Conversion/ALPHADataConverterSource.h
//
// ALPHADataConverterSource.h
// Alpha
//
// Created by <NAME> on 02/06/15.
// Copyright © 2015 Unified Sense. All rights reserved.
//
#import "ALPHAModel.h"
#import "ALPHAScreenModel.h"
/*!
* Data Converter source takes Alpha model and converts it to screen model
*/
@protocol ALPHADataConverterSource <NSObject>
/*!
* Each source is asked if object can be converted, no other calls are made if this call returns NO, to save
* the resources required to convert some objects.
*
* @param object of data
*
* @return YES if conversion is possible
*/
- (BOOL)canConvertObject:(id)object;
/*!
* Method converts data model into screen model to be rendered
*
* @param object of data
*
* @return screen model if successful, nil otherwise
*/
- (ALPHAScreenModel *)screenModelForObject:(id)object;
@optional
/*!
* Returns renderer class for an object. If class is returned, object will be rendered using that class.
*
* @param object to be rendered
*
* @return class that can render the object
*/
- (Class)renderClassForObject:(id)object;
@end
|
martinfengshenxiang/atom_game | src/Asset/Component/Header/Store/Action/preview.js | import React from 'react';
import { Button } from 'antd';
const Preview = () => (
<div style={{ width: '30%', height: '100%' }}>
<div style={{ width: '100%', height: '90%' }}>
</div>
<div style={{ width: '100%', height: '10%', display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
<Button>使用</Button>
</div>
</div>
);
export default Preview;
|
gregory-vovchok/YEngine | Editor/BoolSpinBox/BoolSpinBox.cpp | <reponame>gregory-vovchok/YEngine
#include "BoolSpinBox.h"
BoolSpinBox::BoolSpinBox(void)
{}
BoolSpinBox::BoolSpinBox(QWidget *_parent): QSpinBox(_parent)
{
setRange(0, 1);
}
QString BoolSpinBox::textFromValue(int _value)const
{
if(_value) { return "true"; } else { return "false"; }
}
|
steroin/DocManager | src/main/java/pl/docmanager/domain/user/UserSettings.java | <reponame>steroin/DocManager<filename>src/main/java/pl/docmanager/domain/user/UserSettings.java
package pl.docmanager.domain.user;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
@Entity
@Table(name = "usersettings")
public class UserSettings {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@ManyToOne
@JoinColumn(name = "userid", nullable = false)
private User user;
@Column(name = "name", length = 256, nullable = false)
private String name;
@Column(name = "value", length = 1024, nullable = false)
private String value;
@Column(name = "domain", length = 2048)
private String domain;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getDomain() {
return domain;
}
public void setDomain(String domain) {
this.domain = domain;
}
}
|
jsfit/frontend-loket | app/components/mandatenbeheer/persoon-search-result.js | import Component from '@ember/component';
export default Component.extend({
showDetails: false,
actions: {
select(){
this.onSelect(this.persoon);
},
toggleDetails(){
this.set('showDetails', !this.showDetails);
}
}
});
|
topiolli/into | core/PiiException.h | /* This file is part of Into.
* Copyright (C) Intopii 2013.
* All rights reserved.
*
* Licensees holding a commercial Into license may use this file in
* accordance with the commercial license agreement. Please see
* LICENSE.commercial for commercial licensing terms.
*
* Alternatively, this file may be used under the terms of the GNU
* Affero General Public License version 3 as published by the Free
* Software Foundation. In addition, Intopii gives you special rights
* to use Into as a part of open source software projects. Please
* refer to LICENSE.AGPL3 for details.
*/
#ifndef _PIIEXCEPTION_H
#define _PIIEXCEPTION_H
#include "PiiGlobal.h"
#include <QString>
#ifndef _DEBUG
// Release builds save memory by not storing error location.
# define PII_MAKE_EXCEPTION(EXCEPTION, MESSAGE) EXCEPTION(MESSAGE)
#else
/**
* Constructs an instance of `EXCEPTION` with the given `MESSAGE`.
* This macro automatically fills in file and line number information
* in debug builds. Error location will be omitted in release builds.
*/
# define PII_MAKE_EXCEPTION(EXCEPTION, MESSAGE) EXCEPTION(MESSAGE, QString(__FILE__ ":%1").arg(__LINE__))
#endif
/**
* A macro for throwing an exception with error location information.
* With this macro, the file name and line number of the current code
* line are automatically stored as the error location. If you don't
* need the location information, just throw the exception as in `throw
* PiiException("Everything just went kablooie.")`. An example:
*
* ~~~(c++)
* PII_THROW(PiiException, tr("The software just failed spectacularly."));
* ~~~
*
* @param EXCEPTION the class name of the exception to be thrown, e.g.
* PiiException.
*
* @param MESSAGE the error message
*/
#define PII_THROW(EXCEPTION, MESSAGE) throw PII_MAKE_EXCEPTION(EXCEPTION, MESSAGE)
namespace PiiSerialization
{
struct Accessor;
}
class PiiMetaObject;
/**
* PiiException is the base class of all exceptions. Usually, one
* does not throw an PiiException directly but creates a sub-class
* whose type identifies the exception more precisely.
*
* To support exceptions in remote function calls, all exception
* classes should be made serializable.
*/
class PII_CORE_EXPORT PiiException
{
#ifndef PII_NO_QT
friend struct PiiSerialization::Accessor;
template <class Archive> void serialize(Archive& archive, const unsigned version);
virtual const PiiMetaObject* piiMetaObject() const;
#endif
public:
/**
* Constructs an empty exception.
*/
PiiException();
/**
* Constructs a new exception with the given *message*.
*
* @param message the error message. The message should be a
* user-readable explation of the error, and it is typically
* translatable.
*/
PiiException(const QString& message);
/**
* Constructs a new exception with the given *message* and error
* location.
*
* @param message the error message. The message should be a
* user-readable explation of the error, and it is typically
* translatable.
*
* @param location the location of the code this error occured at.
* The standard, official, God-given format is "%file:line", e.g.
* "PiiException.h:30". The reason is that such a string works as a
* hyperlink to source code when debugging applications with
* (X)Emacs (which is the standard editor).
*/
PiiException(const QString& message, const QString& location);
/**
* Copy another exception.
*/
PiiException(const PiiException& other);
PiiException& operator= (const PiiException& other);
virtual ~PiiException();
/**
* Get the message stored in this exception.
*/
QString message() const;
/**
* Set the message stored in this exception.
*
* @param message the new exception message
*/
void setMessage(const QString& message);
/**
* Returns the error location, for example
* "PiiException.h:106". Note that if you use the [PII_THROW]
* macro, location will not be included in release builds.
*/
QString location() const;
/**
* Returns *prefix* + [location()] + *suffix*, if location is
* non-empty. Otherwise returns an empty string.
*/
QString location(const QString& prefix, const QString& suffix) const;
/**
* Set the error location.
*/
void setLocation(const QString& location);
/**
* Returns a textual representation of the exception, including its
* type, location (if known), and message.
*/
QString toString() const;
/**
* Throws the exception as a value and deletes the this pointer.
* This function is used to throw exceptions whose type is not known
* at compile time.
*
* @internal
*/
void throwIt();
protected:
/// @hide
class PII_CORE_EXPORT Data
{
public:
Data();
Data(const QString& message, const QString& location);
Data(const Data& other);
virtual ~Data();
QString strMessage;
QString strLocation;
} *d;
PiiException(Data* data);
// Throws *this (as a value).
virtual void throwThis();
/// @endhide
};
#ifndef PII_NO_QT
#include <PiiVirtualMetaObject.h>
#include <PiiSerializationUtil.h>
#include <PiiNameValuePair.h>
template <class Archive> void PiiException::serialize(Archive& archive, const unsigned)
{
archive & PII_NVP("message", d->strMessage);
archive & PII_NVP("location", d->strLocation);
}
#define PII_SERIALIZABLE_CLASS PiiException
#define PII_VIRTUAL_METAOBJECT
#define PII_BUILDING_LIBRARY PII_BUILDING_CORE
#include "PiiSerializableRegistration.h"
#endif
#endif //_PIIEXCEPTION_H
|
cssl-unist/tweezer | Docker/gperftools/benchmark/binary_trees.cc | <reponame>cssl-unist/tweezer
// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*-
//
// Copied from
// http://benchmarksgame.alioth.debian.org/u64q/program.php?test=binarytrees&lang=gpp&id=2
// and slightly modified (particularly by adding multi-threaded
// operation to hit malloc harder).
//
// This version of binary trees is mostly new/delete benchmark
//
// NOTE: copyright of this code is unclear, but we only distribute
// source.
/* The Computer Language Benchmarks Game
* http://benchmarksgame.alioth.debian.org/
*
* Contributed by <NAME>
* Modified by <NAME>
* Adapted for gperftools and added threads by <NAME>
*/
#include <algorithm>
#include <errno.h>
#include <iostream>
#include <pthread.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <vector>
struct Node {
Node *l, *r;
int i;
Node(int i2) : l(0), r(0), i(i2) {}
Node(Node *l2, int i2, Node *r2) : l(l2), r(r2), i(i2) {}
~Node() { delete l; delete r; }
int check() const {
if (l) {
return l->check() + i - r->check();
} else {
return i;
}
}
};
Node *make(int i, int d) {
if (d == 0) return new Node(i);
return new Node(make(2*i-1, d-1), i, make(2*i, d-1));
}
void run(int given_depth) {
int min_depth = 4,
max_depth = std::max(min_depth+2,
given_depth),
stretch_depth = max_depth+1;
{
Node *c = make(0, stretch_depth);
std::cout << "stretch tree of depth " << stretch_depth << "\t "
<< "check: " << c->check() << std::endl;
delete c;
}
Node *long_lived_tree=make(0, max_depth);
for (int d=min_depth; d<=max_depth; d+=2) {
int iterations = 1 << (max_depth - d + min_depth), c=0;
for (int i=1; i<=iterations; ++i) {
Node *a = make(i, d), *b = make(-i, d);
c += a->check() + b->check();
delete a;
delete b;
}
std::cout << (2*iterations) << "\t trees of depth " << d << "\t "
<< "check: " << c << std::endl;
}
std::cout << "long lived tree of depth " << max_depth << "\t "
<< "check: " << (long_lived_tree->check()) << "\n";
delete long_lived_tree;
}
static void *run_tramp(void *_a) {
intptr_t a = reinterpret_cast<intptr_t>(_a);
run(a);
return 0;
}
int main(int argc, char *argv[]) {
int given_depth = argc >= 2 ? atoi(argv[1]) : 20;
int thread_count = std::max(1, argc >= 3 ? atoi(argv[2]) : 1) - 1;
std::vector<pthread_t> threads(thread_count);
for (int i = 0; i < thread_count; i++) {
int rv = pthread_create(&threads[i], NULL,
run_tramp,
reinterpret_cast<void *>(given_depth));
if (rv) {
errno = rv;
perror("pthread_create");
}
}
run_tramp(reinterpret_cast<void *>(given_depth));
for (int i = 0; i < thread_count; i++) {
pthread_join(threads[i], NULL);
}
return 0;
}
|
jokofa/JAMPR_plus | lib/model/baselines/pg_baselines.py | <gh_stars>0
#
import copy
import logging
from typing import Dict, Optional, OrderedDict, List, Union
from torch import Tensor
from scipy.stats import ttest_rel
import torch
import torch.nn.functional as F
from lib.model.baselines.base_class import Baseline, BaselineDataset
from lib.routing import RPInstance, RPDataset, RPEnv
from lib.model.policy import Policy
from lib.model.training import rollout, eval_episode
__all__ = [
"NoBaseline",
"ExponentialBaseline",
"WarmupBaseline",
"RolloutBaseline",
"CriticBaseline",
"POMOBaseline",
]
logger = logging.getLogger(__name__)
class NoBaseline(Baseline):
"""Dummy baseline doing nothing."""
def eval(self, batch: List[RPInstance], cost: Union[float, Tensor]):
return 0, 0 # No baseline, no loss
class ExponentialBaseline(Baseline):
"""Exponential moving average baseline."""
def __init__(self, beta: float, **kwargs):
super(Baseline, self).__init__()
self.beta = beta
self.v = None
@torch.no_grad()
def eval(self, batch: List[RPInstance], cost: Tensor):
if self.v is None:
v = cost.mean()
else:
v = self.beta * self.v + (1. - self.beta) * cost.mean()
self.v = v.detach()
return self.v, 0 # No loss
def state_dict(self):
return {'v': self.v}
def load_state_dict(self, state_dict: Union[Dict, OrderedDict]):
self.v = state_dict['v']
class WarmupBaseline(Baseline):
"""Wrapper implementing exponential warmup phase
for rollout and critic baselines."""
def __init__(self,
baseline: Baseline,
n_epochs: int = 1,
warmup_exp_beta: float = 0.8,
verbose: bool = False,
**kwargs):
super(Baseline, self).__init__()
self.baseline = baseline
self.n_epochs = n_epochs
self.verbose = verbose
assert n_epochs > 0, "n_epochs must be positive."
self.warmup_baseline = ExponentialBaseline(warmup_exp_beta, **kwargs)
self.alpha = 0
def wrap_dataset(self, dataset: RPDataset):
if self.alpha > 0:
return self.baseline.wrap_dataset(dataset)
return self.warmup_baseline.wrap_dataset(dataset)
def unwrap_batch(self, batch: List):
if self.alpha > 0:
return self.baseline.unwrap_batch(batch)
return self.warmup_baseline.unwrap_batch(batch)
@torch.no_grad()
def eval(self, batch: List[RPInstance], cost: Union[float, Tensor]):
if self.alpha >= 1:
return self.baseline.eval(batch, cost)
elif self.alpha == 0:
return self.warmup_baseline.eval(batch, cost)
else:
# Return convex combination of baselines
v, l = self.baseline.eval(batch, cost)
vw, lw = self.warmup_baseline.eval(batch, cost)
return (
self.alpha * v + (1 - self.alpha) * vw,
self.alpha * l + (1 - self.alpha * (lw if lw is not None else 0))
)
def epoch_callback(self, policy: Policy, epoch: int):
# Need to call epoch callback of inner model (also after first epoch if we have not used it)
self.baseline.epoch_callback(policy, epoch)
self.alpha = (epoch + 1) / float(self.n_epochs)
if self.verbose and epoch < self.n_epochs:
logger.info(f"Set warmup alpha = {self.alpha}")
def state_dict(self):
# Checkpointing within warmup stage makes no sense, only save inner baseline
return self.baseline.state_dict()
def load_state_dict(self, state_dict):
# Checkpointing within warmup stage makes no sense, only load inner baseline
self.baseline.load_state_dict(state_dict)
class RolloutBaseline(Baseline):
"""Greedy rollout baseline.
Args:
dataset: baseline val dataset
env: baseline val env
policy: policy model
sample_size: size of baseline val dataset
graph_size: size of graphs in baseline val dataset
batch_size: batch size for baseline evaluations
check_significance: flag to use ttest to check significance of baseline improvement
alpha: confidence level for p-value
resample_interval: resample the baseline validation data every 'resample_interval' epochs
to prevent over-fitting (disabled for interval=0)
num_workers: number of workers to load data
verbose: flag to log additional info
"""
def __init__(self,
dataset: RPDataset,
env: RPEnv,
policy: Policy,
sample_size: int,
graph_size: int,
batch_size: int,
check_significance: bool = True,
alpha: float = 0.05,
resample_interval: int = 0,
num_workers: int = 4,
verbose: bool = False,
**kwargs):
super(Baseline, self).__init__()
self.dataset = dataset
self.env = env
self.sample_size = sample_size
self.graph_size = graph_size
self.batch_size = batch_size
self.check_significance = check_significance
assert alpha > 0
self.alpha = alpha
self.resample_interval = resample_interval
self.num_workers = num_workers
self.verbose = verbose
self.policy = None
self.bl_vals = None
self.bl_epoch = 0
self._cpu = torch.device("cpu")
self._device = None
self._last_sample_epoch = 0
self._update_model(policy, 0)
self._clear()
def _update_model(self, policy: Policy, epoch: int):
self.bl_epoch = epoch
self._device = policy.device
self.policy = copy.deepcopy(policy)
resample = self.check_significance and (
self._last_sample_epoch == 0 or
(self.resample_interval > 0 and epoch - self._last_sample_epoch >= self.resample_interval)
)
if resample:
# (re)sample val dataset
self.dataset = self.dataset.sample(sample_size=self.sample_size,
graph_size=self.graph_size)
self._last_sample_epoch = epoch
# (re)evaluate in case of new data
if self.verbose:
logger.info("Evaluating baseline model on evaluation dataset")
self.bl_vals = rollout(
dataset=self.dataset,
env=self.env,
policy=self.policy.to(self._device), # move to GPU for fast process
batch_size=self.batch_size,
num_workers=self.num_workers,
disable_progress_bar=True, # always disable
)[0].cpu()
def _clear(self):
# move model to CPU and clear env cache, since is not needed the whole remaining epoch
self.policy.to(device=self._cpu)
self.env.clear_cache()
def wrap_dataset(self, dataset: RPDataset) -> BaselineDataset:
if self.verbose:
logger.info(f"Precomputing baseline on dataset ({len(dataset)} instances)...")
bl = rollout(
dataset=dataset,
env=self.env,
policy=self.policy.to(self._device), # move to GPU for fast pre-computing
batch_size=self.batch_size,
num_workers=self.num_workers,
disable_progress_bar=True, # always disable
)[0].cpu()
self._clear()
return BaselineDataset(dataset, bl)
def unwrap_batch(self, batch):
return (
[b[0] for b in batch],
torch.stack([b[1] for b in batch], dim=0).to(self._device)
)
@torch.no_grad()
def eval(self, batch: List[RPInstance], cost: Union[float, Tensor]):
# single batch so we do not need rollout function
cost, _ = eval_episode(batch, self.env, self.policy)
return cost, 0 # no loss
def epoch_callback(self, policy: Policy, epoch: int):
"""
Challenge the current baseline with the new model and
replace the baseline model if the new model is significantly better.
Args:
policy: policy to challenge the baseline by
epoch: current epoch
Returns:
"""
if not self.check_significance:
self._update_model(policy, epoch)
else:
if self.verbose:
logger.info("Evaluating candidate model on baseline val dataset")
candidate_vals = rollout(
dataset=self.dataset,
env=self.env,
policy=policy,
batch_size=self.batch_size,
num_workers=self.num_workers,
disable_progress_bar=True, # always disable
)[0].cpu()
candidate_mean = candidate_vals.mean()
cur_mean = self.bl_vals.mean()
diff = candidate_mean - cur_mean
p_val_str = ""
if diff < 0:
# Calc p value
t, p = ttest_rel(candidate_vals.numpy(), self.bl_vals)
assert t < 0, "T-statistic should be negative"
p_val = p / 2 # one-sided
p_val_str = f", p-value: {p_val: .6f}"
if p_val < self.alpha:
if self.verbose:
logger.info('Update baseline')
self.bl_vals = candidate_vals
self._update_model(policy, epoch)
if self.verbose:
logger.info(f"Epoch {epoch} / Baseline epoch {self.bl_epoch}"
f"\n candidate mean {candidate_mean: .6f}, "
f"\n baseline mean {cur_mean: .6f}, "
f"\n difference {diff: .6f}{p_val_str}")
def state_dict(self):
return {
'bl_policy': self.policy,
'bl_dataset': self.dataset,
'bl_epoch': self.bl_epoch
}
def load_state_dict(self, state_dict):
# We make it such that it works whether model was saved as data parallel or not
policy_ = copy.deepcopy(self.policy)
policy_.load_state_dict(state_dict['bl_policy'].state_dict())
self._update_model(policy_, state_dict['bl_epoch'])
class CriticBaseline(Baseline):
def __init__(self, critic: torch.nn.Module):
super(Baseline, self).__init__()
self.critic = critic
def eval(self, batch: List[RPInstance], cost: Union[float, Tensor]):
v = self.critic(batch)
# Detach v since actor should not backprop through baseline, only for loss
return v.detach(), F.mse_loss(v, cost.detach())
def get_learnable_parameters(self):
return list(self.critic.parameters())
def epoch_callback(self, policy: Policy, epoch):
pass
def state_dict(self):
return {
'critic': self.critic.state_dict()
}
def load_state_dict(self, state_dict):
critic_state_dict = state_dict.get('critic', {})
if not isinstance(critic_state_dict, dict): # backwards compatibility
critic_state_dict = critic_state_dict.state_dict()
self.critic.load_state_dict({**self.critic.state_dict(), **critic_state_dict})
class POMOBaseline(Baseline):
"""Uses the average cost over the POMO rollouts as baseline."""
def __init__(self, num_samples: int, **kwargs):
super(Baseline, self).__init__()
self.num_samples = num_samples
@torch.no_grad()
def eval(self, batch: List[RPInstance], cost: Tensor):
# cost has shape (BS*num_samples, ) where num samples is the number of POMO rollout trajectories
bs = len(batch)
v = cost.view(bs, self.num_samples).mean(dim=-1)[:, None].expand(-1, self.num_samples).reshape(-1)
return v.detach(), 0 # No loss
|
difi/minid-notification-server | src/main/java/no/digdir/minidnotificationserver/api/internal/authorization/RequestAuthorizationEntity.java | <reponame>difi/minid-notification-server
package no.digdir.minidnotificationserver.api.internal.authorization;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import no.idporten.validators.identifier.PersonIdentifier;
import javax.validation.constraints.NotBlank;
import java.time.ZonedDateTime;
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
public class RequestAuthorizationEntity {
@NotBlank
@Schema(description = "Person identifier - 11 digits.", example = "26079490775")
@PersonIdentifier(message = "invalid person identifier")
String person_identifier;
@Schema(description = "The ID of the server - used in routing. Optional.", example = "2")
String server_id;
@Schema(description = "The login attempt id", example = "[uuid-4]")
String login_attempt_id;
@Schema(description = "The login attempt counter", example = "1")
Integer login_attempt_counter;
@Schema(description = "The expiry time of the login attempt in ISO-8601 format.", example = "2021-02-18T10:15:30Z")
ZonedDateTime login_attempt_expiry;
@NotBlank
@Schema(description = "The title of the notification", example = "Test notification")
String title;
@NotBlank
@Schema(description = "The body of the notification", example = "Lengre tekst")
String body;
@NotBlank
@Schema(description = "The service provider for the login", example = "NAV")
String service_provider;
}
|
palmurugan/ptracker | report-builder/src/main/java/com/hts/report/service/impl/ConnectionManager.java | package com.hts.report.service.impl;
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import com.hts.report.domain.Resource;
/**
*
* @author PalMurugan
*
*/
public abstract class ConnectionManager {
private static final String MYSQL_DRIVER = "com.mysql.jdbc.Driver";
protected JdbcTemplate getJDBCTemplate(Resource resource) {
return new JdbcTemplate(getDataSource(resource));
}
private DataSource getDataSource(Resource resource) {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(ConnectionManager.MYSQL_DRIVER);
dataSource.setUrl(resource.getDatasource().getConnectionURL());
dataSource.setUsername("root");
dataSource.setPassword("<PASSWORD>");
return dataSource;
}
}
|
andela/andela-societies-backend | src/api/endpoints/cohorts/marshmallow_schemas.py | from marshmallow import fields, validate
from api.utils.marshmallow_schemas import BaseSchema
class CohortSchema(BaseSchema):
"""Validation Schema for Cohort."""
center_id = fields.String(dump_only=True, dump_to='centerId',
validate=[validate.Length(max=36)])
society_id = fields.String(dump_only=True, dump_to='societyId',
validate=[validate.Length(max=36)])
cohort_schema = CohortSchema()
|
ghiloufibelgacem/jornaldev | CoreJavaProjects/CoreJavaExamples/src/com/journaldev/string/IntToString.java | package com.journaldev.string;
public class IntToString {
/**
* This class shows how to convert int to String
* @param args
*/
public static void main(String[] args) {
int i = 10;
int j = 0xEF;
int k = 0123;
int l = 0b111;
String str = "" +i;
String str1 = String.valueOf(j);
String str2 = String.format("%d", k);
String str3 = "" +l;
System.out.println(i+" decimal int to String "+str);
System.out.println(j+" hexadecimal int to String "+str1);
System.out.println(k+" octal int to String "+str2);
System.out.println(l+" binary int to String "+str3);
}
}
|
rtluu/personalsite | src/cases/Fastrope/fastrope.js | import React, { useState } from "react";
import { Link } from "gatsby";
import HeroFastrope from "./images/HeroFastrope";
import FastropeContact from "./images/FastropeContact";
import FastropePortfolio from "./images/FastropePortfolio";
import FastropeServices from "./images/FastropeServices";
import FastropeTeam from "./images/FastropeTeam";
import FastropeAnchors from "./anchorsFastrope";
import ArrowIcon from "../../icons/arrow-icon.inline.svg";
import CaseArrowIcon from "../../icons/case-arrow-icon.inline.svg";
import Popup from "../../components/Popup/popup";
import Caption from "../../components/Caption/caption";
import { setImageNumber, setImageGallery, useGlobalState } from '../../state';
const Fastrope = () => {
//Lightbox - About
const [value, update] = useGlobalState('lightboxActive');
const [imageNumber] = useGlobalState('imageNumber');
setImageGallery(5);
function openLightbox1() { setImageNumber(1); update(!value); }
function openLightbox2() { setImageNumber(2); update(!value); }
function openLightbox3() { setImageNumber(3); update(!value); }
function openLightbox4() { setImageNumber(4); update(!value); }
function openLightbox5() { setImageNumber(5); update(!value); }
//Collapse - Fastrope
const [objectiveCollapsed, setObjectiveCollapsed] = useState(false);
const [requirementsCollapsed, setRequirementsCollapsed] = useState(false);
const [processCollapsed, setProcessCollapsed] = useState(false);
const [developmentCollapsed, setDevelopmentCollapsed] = useState(false);
const [reflectionCollapsed, setReflectionCollapsed] = useState(false);
return (
<div className="template-content">
<FastropeAnchors />
<h1 id="fastrope">Fastrope Labs</h1>
<div className="template-section">
<div className="hero">
<button onClick={openLightbox1} key={1} className="image-button" type="button">
<HeroFastrope />
</button>
</div>
<div className="template-text-block">
<div className="template-text-body">
<p><span className="bold-italic">Client: </span>Fastrope Labs</p>
<p><span className="bold-italic">Role: </span>Frontend</p>
<p><span className="bold-italic">Tools: </span>React, SCSS, Git</p>
<p><span className="bold-italic">Timeline: </span>2017</p>
</div>
</div>
</div>
<div className="template-section">
<div className={`template-text-block ${objectiveCollapsed ? "collapsed" : ""}`}>
<div className="template-text-header" onClick={() => setObjectiveCollapsed(!objectiveCollapsed)}>
<button className="collapse-expand"><ArrowIcon /></button>
<h2 id="objective">Objective</h2>
</div>
<div className="template-text-body">
<p>Develop a website for the creative agency based in Washington DC.</p>
</div>
</div>
</div>
<div className="template-section">
<div className={`template-text-block ${requirementsCollapsed ? "collapsed" : ""}`}>
<div className="template-text-header" onClick={() => setRequirementsCollapsed(!requirementsCollapsed)}>
<button className="collapse-expand"><ArrowIcon /></button>
<h2 id="requirements">Requirements</h2>
</div>
<div className="template-text-body">
<ul className="listtype-bullet listindent1" >
<li><p>Create a website in a modern framework</p></li>
<li><p>Work with the design and marketing team translate mocks into experience</p></li>
<li><p>Pages to include: Work, Team, Contact</p></li>
</ul>
</div>
</div>
</div>
<div className="template-section">
<div className={`template-text-block ${processCollapsed ? "collapsed" : ""}`}>
<div className="template-text-header" onClick={() => setProcessCollapsed(!processCollapsed)}>
<button className="collapse-expand"><ArrowIcon /></button>
<h2 id="process">Process</h2>
</div>
<div className="template-text-body">
<ol className="listtype-numbered" >
<li><p>Client interview and requirements gathering</p></li>
<li><p>Design synthesis and technical discovery</p></li>
<li><p>Develop, deploy, feedback, adjust</p></li>
<li><p>Final delivery and asset transfer</p></li>
</ol>
</div>
</div>
</div>
<div className="template-section">
<div className={`template-text-block ${developmentCollapsed ? "collapsed" : ""}`}>
<div className="template-text-header" onClick={() => setDevelopmentCollapsed(!developmentCollapsed)}>
<button className="collapse-expand"><ArrowIcon /></button>
<h2 id="development">Development</h2>
</div>
<div className="template-text-body">
<p>The focus for my development was creating a snappy, efficient site while meeting the design requirements laid out by the Fastrope design team. I made it a point to build the components in a modular format for reusability and ease in adjustment.</p>
<span className="gallery">
<div className="gallery-outer-wrapper">
<div className="gallery-wrapper">
<div className="gallery-item-wrapper ">
<button onClick={openLightbox2} className="image-button" type="button">
<FastropeTeam />
</button>
<Caption caption="team" />
</div>
<div className="gallery-item-wrapper">
<button onClick={openLightbox3} className="image-button" type="button">
<FastropeContact />
</button>
<Caption caption="contact page" />
</div>
</div>
</div>
</span>
<span className="gallery">
<div className="gallery-outer-wrapper second-gallery-row">
<div className="gallery-wrapper">
<div className="gallery-item-wrapper flex-neat-services">
<button onClick={openLightbox4} className="image-button" type="button">
<FastropeServices />
</button>
<Caption caption="services" />
</div>
<div className="gallery-item-wrapper flex-neat-portfolio">
<button onClick={openLightbox5} className="image-button" type="button">
<FastropePortfolio />
</button>
<Caption caption="client work" />
</div>
</div>
</div>
</span>
</div>
</div>
</div>
<div className="template-section">
<div className={`template-text-block ${reflectionCollapsed ? "collapsed" : ""}`}>
<div className="template-text-header" onClick={() => setReflectionCollapsed(!reflectionCollapsed)}>
<button className="collapse-expand"><ArrowIcon /></button>
<h2 id="reflection" >Reflection</h2>
</div>
<div className="template-text-body">
<p>Working with the Fastrope team was very smooth, with a clear vision for what they wanted to build along with a stellar team that was easy to communicate with. Working on this project gave me another opportunity to refine my development in React and control the full development pipeline from first commit through deployment.</p>
</div>
</div>
</div>
<div className="template-section">
<div className="template-text-body">
<div className="case-end-links">
<Link to="/humblevc/" className="case-item">
<div className="case-popup"><Popup text="Case Study: Humble Venture Capital" imgsrc="HumblePopup" /></div>
<span className="case-arrow previous"><CaseArrowIcon /></span>
<p>+Humble Venture Capital</p>
</Link>
<Link to="/ourluubeginning/" className="case-item next">
<div className="case-popup"><Popup text="Case Study: OurLuuBeginning" imgsrc="OLBPopup" /></div>
<span className="case-arrow"><CaseArrowIcon /></span>
<p>+OurLuuBeginning</p>
</Link>
</div>
</div>
</div>
</div>
)
}
export default Fastrope |
developedbyme/dbm | javascripts/dbm/classes/dbm/constants/fileformats/midi/MidiChannelEventTypes.js | <reponame>developedbyme/dbm
/* Copyright (C) 2011-2014 <NAME>. Used under MIT license, see full details at https://github.com/developedbyme/dbm/blob/master/LICENSE.txt */
dbm.registerClass("dbm.constants.fileformats.midi.MidiChannelEventTypes", null, function(objectFunctions, staticFunctions, ClassReference) {
//console.log("dbm.constants.fileformats.midi.MidiChannelEventTypes");
//"use strict";
var MidiChannelEventTypes = dbm.importClass("dbm.constants.fileformats.midi.MidiChannelEventTypes");
staticFunctions.NOTE_OFF = 0x80;
staticFunctions.NOTE_ON = 0x90;
staticFunctions.NOTE_AFTER_TOUCH = 0xA0;
staticFunctions.CONTROLLER_MODE_CHANGE = 0xB0;
staticFunctions.PROGRAM_CHANGE = 0xC0;
staticFunctions.CHANNEL_AFTER_TOUCH = 0xD0;
staticFunctions.PITCH_BEND = 0xE0;
}); |
hephzaron/Hello-Books | server/migrations/20170904030813-create-borrowed.js | <gh_stars>0
'use strict';
module.exports = {
up: function(queryInterface, Sequelize) {
return queryInterface.createTable('Borroweds', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
bookId: {
type: Sequelize.INTEGER,
allowNull: false,
onUpdate: 'CASCADE',
onDelete: 'CASCADE'
},
userId: {
type: Sequelize.INTEGER,
allowNull: false,
onUpdate: 'CASCADE',
onDelete: 'CASCADE'
},
returned: {
type: Sequelize.BOOLEAN,
allowNull: false
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
});
},
down: function(queryInterface /*, Sequelize*/ ) {
return queryInterface.dropTable('Borroweds');
}
}; |
freedesktop/mesa-crucible | src/util/cru_image.c | // Copyright 2015 Intel Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice (including the next
// paragraph) shall be included in all copies or substantial portions of the
// Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "util/log.h"
#include "util/misc.h"
#include "util/string.h"
#include "util/xalloc.h"
#include "cru_image.h"
typedef bool (*pixel_copy_func_t)(
uint32_t width, uint32_t height,
void *src, uint32_t src_x, uint32_t src_y, uint32_t src_stride,
void *dest, uint32_t dest_x, uint32_t dest_y, uint32_t dest_stride);
/// Caller must free the returned string.
char *
cru_image_get_abspath(const char *filename)
{
string_t abspath = STRING_INIT;
const char *env = getenv("CRU_DATA_DIR");
if (env && env[0]) {
path_append_cstr(&abspath, env);
path_append_cstr(&abspath, filename);
} else {
path_append(&abspath, cru_prefix_path());
path_append_cstr(&abspath, "data");
path_append_cstr(&abspath, filename);
}
return string_detach(&abspath);
}
void
cru_image_reference(cru_image_t *image)
{
cru_refcount_get(&image->refcount);
}
void
cru_image_release(cru_image_t *image)
{
if (cru_refcount_put(&image->refcount) > 0)
return;
image->destroy(image);
}
uint32_t
cru_image_get_width(cru_image_t *image)
{
return image->width;
}
uint32_t
cru_image_get_height(cru_image_t *image)
{
return image->height;
}
uint32_t
cru_image_get_pitch_bytes(cru_image_t *image)
{
return image->pitch_bytes ? image->pitch_bytes : image->width * image->format_info->cpp;
}
VkFormat
cru_image_get_format(cru_image_t *image)
{
return image->format_info->format;
}
bool
cru_image_init(cru_image_t *image, enum cru_image_type type,
VkFormat format, uint32_t width, uint32_t height,
bool read_only)
{
cru_refcount_init(&image->refcount);
image->format_info = cru_format_get_info(format);
if (!image->format_info) {
loge("cannot crucible image with VkFormat %d", format);
return false;
}
if (width == 0) {
loge("cannot create crucible image with zero width");
return false;
}
if (height == 0) {
loge("cannot create crucible image with zero width");
return false;
}
image->width = width;
image->height = height;
image->type = type;
image->read_only = read_only;
image->pitch_bytes = 0;
return true;
}
void
cru_image_set_pitch_bytes(cru_image_t *image, uint32_t pitch_bytes)
{
image->pitch_bytes = pitch_bytes;
}
static bool
cru_image_check_compatible(const char *func,
cru_image_t *a, cru_image_t *b)
{
if (a == b) {
loge("%s: images are same", func);
return false;
}
if (a->format_info->num_channels != b->format_info->num_channels) {
loge("%s: image formats differ in number of channels", func);
return false;
}
// FIXME: Reject images whose channel order differs.
if (a->width != b->width) {
loge("%s: image widths differ", func);
return false;
}
if (a->height != b->height) {
loge("%s: image heights differ", func);
return false;
}
return true;
}
cru_image_t *
cru_image_from_filename(const char *_filename)
{
string_t filename = STRING_INIT;
cru_image_t *image = NULL;
string_copy_cstr(&filename, _filename);
if (string_endswith_cstr(&filename, ".png")) {
image = cru_png_image_load_file(_filename);
} else if (string_endswith_cstr(&filename, ".ktx")) {
loge("loading ktx requires array in %s", _filename);
} else {
loge("unknown file extension in %s", _filename);
}
string_finish(&filename);
return image;
}
bool
cru_image_write_file(cru_image_t *image, const char *_filename)
{
string_t filename = STRING_INIT;
bool res;
string_copy_cstr(&filename, _filename);
if (string_endswith_cstr(&filename, ".png")) {
res = cru_png_image_write_file(image, &filename);
} else {
loge("unknown file extension in %s", _filename);
res = false;
}
string_finish(&filename);
return res;
}
static bool
copy_unorm8_to_uint8(
uint32_t width, uint32_t height,
void *src, uint32_t src_x, uint32_t src_y, uint32_t src_stride,
void *dest, uint32_t dest_x, uint32_t dest_y, uint32_t dest_stride)
{
const uint32_t cpp = 1;
for (uint32_t y = 0; y < height; ++y) {
void *src_row = src + ((src_y + y) * src_stride + src_x * cpp);
void *dest_row = dest + ((dest_y + y) * dest_stride + dest_x * cpp);
memcpy(dest_row, src_row, width * cpp);
}
return true;
}
static bool
copy_uint8_to_unorm8(
uint32_t width, uint32_t height,
void *src, uint32_t src_x, uint32_t src_y, uint32_t src_stride,
void *dest, uint32_t dest_x, uint32_t dest_y, uint32_t dest_stride)
{
return copy_unorm8_to_uint8(width, height,
src, src_x, src_y, src_stride,
dest, dest_x, dest_y, dest_stride);
}
static bool
copy_unorm8_to_f32(
uint32_t width, uint32_t height,
void *src, uint32_t src_x, uint32_t src_y, uint32_t src_stride,
void *dest, uint32_t dest_x, uint32_t dest_y, uint32_t dest_stride)
{
const uint32_t src_cpp = 1;
const uint32_t dest_cpp = 4;
for (uint32_t y = 0; y < height; ++y) {
void *src_row = src + ((src_y + y) * src_stride +
src_x * src_cpp);
void *dest_row = dest + ((dest_y + y) * dest_stride +
dest_x * dest_cpp);
for (uint32_t x = 0; x < width; ++x) {
uint8_t *src_pix = src_row + (x * src_cpp);
float *dest_pix = dest_row + (x * dest_cpp);
dest_pix[0] = (float) src_pix[0] / UINT8_MAX;
}
}
return true;
}
static bool
copy_f32_to_unorm8(
uint32_t width, uint32_t height,
void *src, uint32_t src_x, uint32_t src_y, uint32_t src_stride,
void *dest, uint32_t dest_x, uint32_t dest_y, uint32_t dest_stride)
{
const uint32_t src_cpp = 4;
const uint32_t dest_cpp = 1;
for (uint32_t y = 0; y < height; ++y) {
void *src_row = src + ((src_y + y) * src_stride +
src_x * src_cpp);
void *dest_row = dest + ((dest_y + y) * dest_stride +
dest_x * dest_cpp);
for (uint32_t x = 0; x < width; ++x) {
float *src_pix = src_row + (x * src_cpp);
uint8_t *dest_pix = dest_row + (x * dest_cpp);
dest_pix[0] = UINT8_MAX * src_pix[0];
}
}
return true;
}
static bool
copy_oneshot_memcpy(
uint32_t width, uint32_t height,
void *src, uint32_t src_x, uint32_t src_y, uint32_t src_stride,
void *dest, uint32_t dest_x, uint32_t dest_y, uint32_t dest_stride)
{
assert(src_x == 0);
assert(src_y == 0);
assert(dest_x == 0);
assert(dest_y == 0);
assert(src_stride == dest_stride);
memcpy(dest, src, height * src_stride);
return true;
}
static bool
cru_image_copy_pixels_to_pixels(cru_image_t *dest, cru_image_t *src)
{
bool result = false;
uint8_t *src_pixels = NULL;
uint8_t *dest_pixels = NULL;
pixel_copy_func_t copy_func;
const VkFormat src_format = src->format_info->format;
const VkFormat dest_format = dest->format_info->format;
const uint32_t width = src->width;
const uint32_t height = src->height;
const uint32_t src_stride = cru_image_get_pitch_bytes(src);
const uint32_t dest_stride = cru_image_get_pitch_bytes(dest);
assert(!dest->read_only);
// Extent equality is enforced by cru_image_check_compatible().
assert(src->width == dest->width);
assert(src->height == dest->height);
src_pixels = src->map_pixels(src, CRU_IMAGE_MAP_ACCESS_READ);
if (!src_pixels)
goto fail_map_src_pixels;
dest_pixels = dest->map_pixels(dest, CRU_IMAGE_MAP_ACCESS_WRITE);
if (!dest_pixels)
goto fail_map_dest_pixels;
if (src->format_info == dest->format_info
&& src_stride == dest_stride) {
copy_func = copy_oneshot_memcpy;
} else if (src_format == VK_FORMAT_R8_UNORM &&
dest_format == VK_FORMAT_D32_SFLOAT) {
copy_func = copy_unorm8_to_f32;
} else if (src_format == VK_FORMAT_D32_SFLOAT &&
dest_format == VK_FORMAT_R8_UNORM) {
copy_func = copy_f32_to_unorm8;
} else if (src_format == VK_FORMAT_R8_UNORM &&
dest_format == VK_FORMAT_S8_UINT) {
copy_func = copy_unorm8_to_uint8;
} else if (src_format == VK_FORMAT_S8_UINT &&
dest_format == VK_FORMAT_R8_UNORM) {
copy_func = copy_uint8_to_unorm8;
} else {
loge("%s: unsupported format combination", __func__);
goto fail_no_copy_func;
}
result = copy_func(width, height,
src_pixels, 0, 0, src_stride,
dest_pixels, 0, 0, dest_stride);
fail_no_copy_func:
// Check the result of unmapping the destination image because writeback
// can fail during unmap.
result &= dest->unmap_pixels(dest);
fail_map_dest_pixels:
// Ignore the result of unmapping the source image because no writeback
// occurs when unmapping a read-only map.
src->unmap_pixels(src);
fail_map_src_pixels:
return result;
}
bool
cru_image_copy(cru_image_t *dest, cru_image_t *src)
{
if (!cru_image_check_compatible(__func__, dest, src))
return false;
if (dest->read_only) {
loge("%s: dest is read only", __func__);
return false;
}
// PNG images are always read-only.
assert(dest->type != CRU_IMAGE_TYPE_PNG);
if (src->type == CRU_IMAGE_TYPE_PNG)
return cru_png_image_copy_to_pixels(src, dest);
else
return cru_image_copy_pixels_to_pixels(dest, src);
}
bool
cru_image_compare(cru_image_t *a, cru_image_t *b)
{
if (a->width != b->width || a->height != b->height) {
loge("%s: image dimensions differ", __func__);
return false;
}
return cru_image_compare_rect(a, 0, 0, b, 0, 0, a->width, a->height);
}
bool
cru_image_compare_rect(cru_image_t *a, uint32_t a_x, uint32_t a_y,
cru_image_t *b, uint32_t b_x, uint32_t b_y,
uint32_t width, uint32_t height)
{
bool result = false;
void *a_map = NULL;
void *b_map = NULL;
if (a == b)
return true;
if (a->format_info != b->format_info &&
!((a->format_info->format == VK_FORMAT_S8_UINT &&
b->format_info->format == VK_FORMAT_R8_UNORM) ||
(a->format_info->format == VK_FORMAT_R8_UNORM &&
b->format_info->format == VK_FORMAT_S8_UINT))) {
// Maybe one day we'll want to support more formats.
loge("%s: image formats are incompatible", __func__);
goto cleanup;
}
if (a_x + width > a->width || a_y + height > a->height ||
b_x + width > b->width || b_y + height > b->height) {
loge("%s: rect exceeds image dimensions", __func__);
goto cleanup;
}
const uint32_t cpp = a->format_info->cpp;
const uint32_t row_size = cpp * width;
const uint32_t a_stride = cru_image_get_pitch_bytes(a);
const uint32_t b_stride = cru_image_get_pitch_bytes(b);
a_map = a->map_pixels(a, CRU_IMAGE_MAP_ACCESS_READ);
if (!a_map)
goto cleanup;
b_map = b->map_pixels(b, CRU_IMAGE_MAP_ACCESS_READ);
if (!b_map)
goto cleanup;
// FINISHME: Support a configurable tolerance.
// FINISHME: Support dumping the diff to file.
for (uint32_t y = 0; y < height; ++y) {
const void *a_row = a_map + ((a_y + y) * a_stride + a_x * cpp);
const void *b_row = b_map + ((b_y + y) * b_stride + b_x * cpp);
if (memcmp(a_row, b_row, row_size) != 0) {
loge("%s: diff found in row %u of rect", __func__, y);
result = false;
goto cleanup;
}
}
result = true;
cleanup:
if (a_map)
a->unmap_pixels(a);
if (b_map)
b->unmap_pixels(b);
return result;
}
void *
cru_image_map(cru_image_t *image, uint32_t access_mask)
{
return image->map_pixels(image, access_mask);
}
bool
cru_image_unmap(cru_image_t *image)
{
return image->unmap_pixels(image);
}
void
cru_image_array_reference(cru_image_array_t *ia)
{
cru_refcount_get(&ia->refcount);
}
static void
cru_image_array_destroy(cru_image_array_t *ia)
{
for (int i = 0; i < ia->num_images; i++)
cru_image_release(ia->images[i]);
free(ia->images);
free(ia);
}
void
cru_image_array_release(cru_image_array_t *ia)
{
if (cru_refcount_put(&ia->refcount) > 0)
return;
cru_image_array_destroy(ia);
}
cru_image_t *
cru_image_array_get_image(cru_image_array_t *ia, int index)
{
return ia->images[index];
}
cru_image_array_t *
cru_image_array_from_filename(const char *_filename)
{
string_t filename = STRING_INIT;
cru_image_array_t *ia = NULL;
string_copy_cstr(&filename, _filename);
if (string_endswith_cstr(&filename, ".png")) {
ia = calloc(1, sizeof(*ia));
if (!ia)
return NULL;
cru_refcount_init(&ia->refcount);
ia->num_images = 1;
ia->images = calloc(1, sizeof(struct cru_image *));
if (!ia->images) {
free(ia);
return NULL;
}
ia->images[0] = cru_png_image_load_file(_filename);
if (!ia->images[0]) {
free(ia->images);
free(ia);
return NULL;
}
} else if (string_endswith_cstr(&filename, ".ktx")) {
ia = cru_ktx_image_array_load_file(_filename);
}
string_finish(&filename);
return ia;
}
|
athenagroup/brxm | channel-manager/content-service/src/test/java/org/onehippo/cms/channelmanager/content/documenttype/util/NamespaceUtilsTest.java | <gh_stars>0
/*
* Copyright 2016-2019 <NAME>.V. (http://www.onehippo.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onehippo.cms.channelmanager.content.documenttype.util;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import javax.jcr.Node;
import javax.jcr.Property;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import org.hippoecm.repository.api.HippoNodeType;
import org.hippoecm.repository.util.JcrUtils;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.onehippo.cms.channelmanager.content.documenttype.ContentTypeContext;
import org.onehippo.cms.channelmanager.content.documenttype.field.FieldTypeContext;
import org.onehippo.cms.channelmanager.content.documenttype.field.sort.NodeOrderFieldSorter;
import org.onehippo.cms.channelmanager.content.documenttype.field.sort.TwoColumnFieldSorter;
import org.onehippo.repository.mock.MockNode;
import org.powermock.api.easymock.PowerMock;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import static org.easymock.EasyMock.expect;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertFalse;
import static org.powermock.api.easymock.PowerMock.createMock;
import static org.powermock.api.easymock.PowerMock.replayAll;
import static org.powermock.api.easymock.PowerMock.verifyAll;
@RunWith(PowerMockRunner.class)
@PowerMockIgnore({"javax.management.*", "com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "org.w3c.dom.*", "com.sun.org.apache.xalan.*", "javax.activation.*", "javax.net.ssl.*"})
@PrepareForTest({NamespaceUtils.class, JcrUtils.class})
public class NamespaceUtilsTest {
@Before
public void setup() {
PowerMock.mockStatic(JcrUtils.class);
}
@Test
public void getDocumentRootNode() throws Exception {
final Session session = createMock(Session.class);
final Node rootNode = createMock(Node.class);
expect(session.getNode("/hippo:namespaces/ns/testdocument")).andReturn(rootNode);
replayAll();
assertThat(NamespaceUtils.getContentTypeRootNode("ns:testdocument", session).get(), equalTo(rootNode));
}
@Test
public void getSystemTypeRootNode() throws Exception {
final Session session = createMock(Session.class);
final Node rootNode = createMock(Node.class);
expect(session.getNode("/hippo:namespaces/system/String")).andReturn(rootNode);
replayAll();
assertThat(NamespaceUtils.getContentTypeRootNode("String", session).get(), equalTo(rootNode));
}
@Test
public void getRootNodeWithInvalidId() {
final Session session = createMock(Session.class);
assertFalse(NamespaceUtils.getContentTypeRootNode("bla:bla:bla", session).isPresent());
}
@Test
public void getRootNodeWithRepositoryException() throws Exception {
final Session session = createMock(Session.class);
expect(session.getNode("/hippo:namespaces/ns/testdocument")).andThrow(new RepositoryException());
replayAll();
assertFalse(NamespaceUtils.getContentTypeRootNode("ns:testdocument", session).isPresent());
}
@Test
public void getNodeTypeNodeWithRepositoryException() throws Exception {
final Node contentTypeRootNode = createMock(Node.class);
expect(JcrUtils.getNodePathQuietly(contentTypeRootNode)).andReturn("/bla");
expect(contentTypeRootNode.hasNode(NamespaceUtils.NODE_TYPE_PATH)).andThrow(new RepositoryException());
replayAll();
assertFalse(NamespaceUtils.getNodeTypeNode(contentTypeRootNode, false).isPresent());
verifyAll();
}
@Test
public void getNodeTypeNodeWithoutNode() throws Exception {
final Node contentTypeRootNode = createMock(Node.class);
expect(contentTypeRootNode.hasNode(NamespaceUtils.NODE_TYPE_PATH)).andReturn(false);
replayAll();
assertFalse(NamespaceUtils.getNodeTypeNode(contentTypeRootNode, false).isPresent());
verifyAll();
}
@Test
public void getNodeTypeNodeIgnoreChildren() throws Exception {
final Node contentTypeRootNode = createMock(Node.class);
final Node nodeTypeNode = createMock(Node.class);
expect(contentTypeRootNode.hasNode(NamespaceUtils.NODE_TYPE_PATH)).andReturn(true);
expect(contentTypeRootNode.getNode(NamespaceUtils.NODE_TYPE_PATH)).andReturn(nodeTypeNode);
replayAll();
assertThat(NamespaceUtils.getNodeTypeNode(contentTypeRootNode, true).get(), equalTo(nodeTypeNode));
verifyAll();
}
@Test
public void getNodeTypeNodeWithoutChildren() throws Exception {
final Node contentTypeRootNode = createMock(Node.class);
final Node nodeTypeNode = createMock(Node.class);
expect(contentTypeRootNode.hasNode(NamespaceUtils.NODE_TYPE_PATH)).andReturn(true);
expect(contentTypeRootNode.getNode(NamespaceUtils.NODE_TYPE_PATH)).andReturn(nodeTypeNode);
expect(nodeTypeNode.hasNodes()).andReturn(false);
replayAll();
assertFalse(NamespaceUtils.getNodeTypeNode(contentTypeRootNode, false).isPresent());
verifyAll();
}
@Test
public void getNodeTypeNodeWithChildren() throws Exception {
final Node contentTypeRootNode = createMock(Node.class);
final Node nodeTypeNode = createMock(Node.class);
expect(contentTypeRootNode.hasNode(NamespaceUtils.NODE_TYPE_PATH)).andReturn(true);
expect(contentTypeRootNode.getNode(NamespaceUtils.NODE_TYPE_PATH)).andReturn(nodeTypeNode);
expect(nodeTypeNode.hasNodes()).andReturn(true);
replayAll();
assertThat(NamespaceUtils.getNodeTypeNode(contentTypeRootNode, false).get(), equalTo(nodeTypeNode));
verifyAll();
}
@Test
public void getEditorFieldConfigNodesWithRepositoryException() throws Exception {
final Node contentTypeRootNode = createMock(Node.class);
expect(contentTypeRootNode.hasNode(NamespaceUtils.EDITOR_CONFIG_PATH)).andThrow(new RepositoryException());
expect(JcrUtils.getNodePathQuietly(contentTypeRootNode)).andReturn("/bla");
replayAll();
assertThat(NamespaceUtils.getEditorFieldConfigNodes(contentTypeRootNode), empty());
verifyAll();
}
@Test
public void getEditorFieldConfigNodesWithoutEditorConfig() throws Exception {
final Node contentTypeRootNode = createMock(Node.class);
expect(contentTypeRootNode.hasNode(NamespaceUtils.EDITOR_CONFIG_PATH)).andReturn(false);
replayAll();
assertThat(NamespaceUtils.getEditorFieldConfigNodes(contentTypeRootNode), empty());
verifyAll();
}
@Test
public void getEditorFieldConfigNodesWithEditorConfig() throws Exception {
final Node contentTypeRootNode = MockNode.root();
final Node editorConfigNode = contentTypeRootNode.addNode("editor:templates", "bla").addNode("_default_", "bla");
final Node fieldNode1 = editorConfigNode.addNode("field1", "bla");
final Node fieldNode2 = editorConfigNode.addNode("field2", "bla");
final Node fieldNode3 = editorConfigNode.addNode("field3", "bla");
final List<Node> editorFieldConfigNodes = NamespaceUtils.getEditorFieldConfigNodes(contentTypeRootNode);
assertThat(editorFieldConfigNodes.size(), equalTo(3));
assertThat(editorFieldConfigNodes.get(0), equalTo(fieldNode1));
assertThat(editorFieldConfigNodes.get(1), equalTo(fieldNode2));
assertThat(editorFieldConfigNodes.get(2), equalTo(fieldNode3));
}
@Test
public void getPathForNodeTypeFieldWithRepositoryException() throws Exception {
final Node nodeTypeNode = createMock(Node.class);
expect(nodeTypeNode.hasNode("fieldName")).andThrow(new RepositoryException());
expect(JcrUtils.getNodePathQuietly(nodeTypeNode)).andReturn("/bla");
replayAll();
assertFalse(NamespaceUtils.getPathForNodeTypeField(nodeTypeNode, "fieldName").isPresent());
verifyAll();
}
@Test
public void getPathForNodeTypeFieldWithoutFieldNode() throws Exception {
final Node nodeTypeNode = createMock(Node.class);
expect(nodeTypeNode.hasNode("fieldName")).andReturn(false);
replayAll();
assertFalse(NamespaceUtils.getPathForNodeTypeField(nodeTypeNode, "fieldName").isPresent());
verifyAll();
}
@Test
public void getPathForNodeTypeFieldWithFieldNode() throws Exception {
final Node nodeTypeNode = createMock(Node.class);
final Node fieldNode = createMock(Node.class);
final Property property = createMock(Property.class);
expect(nodeTypeNode.hasNode("fieldName")).andReturn(true);
expect(nodeTypeNode.getNode("fieldName")).andReturn(fieldNode);
expect(fieldNode.hasProperty(HippoNodeType.HIPPO_PATH)).andReturn(true);
expect(fieldNode.getProperty(HippoNodeType.HIPPO_PATH)).andReturn(property);
expect(property.getString()).andReturn("/path");
replayAll();
assertThat(NamespaceUtils.getPathForNodeTypeField(nodeTypeNode, "fieldName").get(), equalTo("/path"));
verifyAll();
}
@Test
public void getConfigPropertyFromClusterOptions() throws Exception {
final Node editorFieldConfigNode = MockNode.root();
final Node clusterOptionsNode = editorFieldConfigNode.addNode(NamespaceUtils.CLUSTER_OPTIONS, null);
clusterOptionsNode.setProperty("maxlength", "256");
final FieldTypeContext fieldContext = new FieldTypeContext(null, null, null, false, false, null, null, editorFieldConfigNode);
assertThat(NamespaceUtils.getConfigProperty(fieldContext, "maxlength", JcrStringReader.get()).get(), equalTo("256"));
}
@Test
public void getConfigPropertyNotInClusterOptionsFromType() throws Exception {
final String propertyName = "maxlength";
final ContentTypeContext parentContext = createMock(ContentTypeContext.class);
final Node editorFieldConfigNode = createMock(Node.class);
final Node clusterOptionsNode = createMock(Node.class);
final Node contentTypeRootNode = createMock(Node.class);
final Node contentTypeEditorConfigNode = createMock(Node.class);
final Property property = createMock(Property.class);
final Session session = createMock(Session.class);
final FieldTypeContext fieldContext = new FieldTypeContext("fieldName", "hippo:fieldtype", "hippo:fieldtype",
true, false, Collections.emptyList(), parentContext, editorFieldConfigNode);
expect(editorFieldConfigNode.hasNode(NamespaceUtils.CLUSTER_OPTIONS)).andReturn(true);
expect(editorFieldConfigNode.getNode(NamespaceUtils.CLUSTER_OPTIONS)).andReturn(clusterOptionsNode);
expect(clusterOptionsNode.hasProperty(propertyName)).andReturn(false);
expect(parentContext.getSession()).andReturn(session);
expect(session.getNode("/hippo:namespaces/hippo/fieldtype")).andReturn(contentTypeRootNode);
expect(contentTypeRootNode.hasNode("editor:templates/_default_")).andReturn(true);
expect(contentTypeRootNode.getNode("editor:templates/_default_")).andReturn(contentTypeEditorConfigNode);
expect(contentTypeEditorConfigNode.hasProperty(propertyName)).andReturn(true);
expect(contentTypeEditorConfigNode.getProperty(propertyName)).andReturn(property);
expect(property.getString()).andReturn("256");
replayAll();
assertThat(NamespaceUtils.getConfigProperty(fieldContext, propertyName, JcrStringReader.get()).get(),
equalTo("256"));
verifyAll();
}
@Test
public void getConfigPropertyNoClusterOptionsFromType() throws Exception {
final String propertyName = "maxlength";
final ContentTypeContext parentContext = createMock(ContentTypeContext.class);
final Node editorFieldConfigNode = createMock(Node.class);
final Node contentTypeRootNode = createMock(Node.class);
final Node contentTypeEditorConfigNode = createMock(Node.class);
final Property property = createMock(Property.class);
final Session session = createMock(Session.class);
final FieldTypeContext fieldContext = new FieldTypeContext("fieldName", "hippo:fieldtype", "hippo:fieldtype",
true, false, Collections.emptyList(), parentContext, editorFieldConfigNode);
expect(editorFieldConfigNode.hasNode(NamespaceUtils.CLUSTER_OPTIONS)).andReturn(false);
expect(parentContext.getSession()).andReturn(session);
expect(session.getNode("/hippo:namespaces/hippo/fieldtype")).andReturn(contentTypeRootNode);
expect(contentTypeRootNode.hasNode("editor:templates/_default_")).andReturn(true);
expect(contentTypeRootNode.getNode("editor:templates/_default_")).andReturn(contentTypeEditorConfigNode);
expect(contentTypeEditorConfigNode.hasProperty(propertyName)).andReturn(true);
expect(contentTypeEditorConfigNode.getProperty(propertyName)).andReturn(property);
expect(property.getString()).andReturn("256");
replayAll();
assertThat(NamespaceUtils.getConfigProperty(fieldContext, propertyName, JcrStringReader.get()).get(),
equalTo("256"));
verifyAll();
}
@Test
public void getConfigPropertyNoClusterOptionsNotInType() throws Exception {
final String propertyName = "maxlength";
final ContentTypeContext parentContext = createMock(ContentTypeContext.class);
final Node editorFieldConfigNode = createMock(Node.class);
final Node contentTypeRootNode = createMock(Node.class);
final Node contentTypeEditorConfigNode = createMock(Node.class);
final Session session = createMock(Session.class);
final FieldTypeContext fieldContext = new FieldTypeContext("fieldName", "hippo:fieldtype", "hippo:fieldtype",
true, false, Collections.emptyList(), parentContext, editorFieldConfigNode);
expect(editorFieldConfigNode.hasNode(NamespaceUtils.CLUSTER_OPTIONS)).andReturn(false);
expect(parentContext.getSession()).andReturn(session);
expect(session.getNode("/hippo:namespaces/hippo/fieldtype")).andReturn(contentTypeRootNode);
expect(contentTypeRootNode.hasNode("editor:templates/_default_")).andReturn(true);
expect(contentTypeRootNode.getNode("editor:templates/_default_")).andReturn(contentTypeEditorConfigNode);
expect(contentTypeEditorConfigNode.hasProperty(propertyName)).andReturn(false);
replayAll();
assertFalse(NamespaceUtils.getConfigProperty(fieldContext, propertyName, JcrStringReader.get()).isPresent());
verifyAll();
}
@Test
public void getPluginClass() throws Exception {
final String pluginClass = "pluginClass";
final Property property = createMock(Property.class);
final Node editorFieldNode = createMock(Node.class);
expect(editorFieldNode.hasProperty("plugin.class")).andReturn(true);
expect(editorFieldNode.getProperty("plugin.class")).andReturn(property);
expect(property.getString()).andReturn(pluginClass);
replayAll();
assertThat(NamespaceUtils.getPluginClassForField(editorFieldNode).get(), equalTo(pluginClass));
}
@Test
public void getPluginClassForFieldWithoutProperty() throws Exception {
final Node editorFieldNode = createMock(Node.class);
expect(editorFieldNode.hasProperty("plugin.class")).andReturn(false);
replayAll();
assertFalse(NamespaceUtils.getPluginClassForField(editorFieldNode).isPresent());
}
@Test
public void getPluginClassWithRepositoryException() throws Exception {
final Node editorFieldNode = createMock(Node.class);
expect(editorFieldNode.hasProperty("plugin.class")).andThrow(new RepositoryException());
expect(JcrUtils.getNodePathQuietly(editorFieldNode)).andReturn("/bla");
replayAll(editorFieldNode);
assertFalse(NamespaceUtils.getPluginClassForField(editorFieldNode).isPresent());
}
@Test
public void getWicketIdForField() throws Exception {
final Property property = createMock(Property.class);
final Node editorFieldNode = createMock(Node.class);
expect(editorFieldNode.hasProperty("wicket.id")).andReturn(true);
expect(editorFieldNode.getProperty("wicket.id")).andReturn(property);
expect(property.getString()).andReturn("WicketID");
replayAll();
assertThat(NamespaceUtils.getWicketIdForField(editorFieldNode).get(), equalTo("WicketID"));
verifyAll();
}
@Test
public void getFieldProperty() throws Exception {
final Property property = createMock(Property.class);
final Node editorFieldNode = createMock(Node.class);
expect(editorFieldNode.hasProperty("field")).andReturn(true);
expect(editorFieldNode.getProperty("field")).andReturn(property);
expect(property.getString()).andReturn("fieldName");
replayAll();
assertThat(NamespaceUtils.getFieldProperty(editorFieldNode).get(), equalTo("fieldName"));
verifyAll();
}
@Test
public void retrieveFieldSorterTwoColumns() throws Exception {
final Node root = createMock(Node.class);
final Node editorNode = createMock(Node.class);
final Node layout = createMock(Node.class);
PowerMock.mockStaticPartial(NamespaceUtils.class, "getPluginClassForField");
expect(root.hasNode(NamespaceUtils.EDITOR_CONFIG_PATH)).andReturn(true);
expect(root.getNode(NamespaceUtils.EDITOR_CONFIG_PATH)).andReturn(editorNode);
expect(editorNode.hasNode("root")).andReturn(true);
expect(editorNode.getNode("root")).andReturn(layout);
expect(NamespaceUtils.getPluginClassForField(layout)).andReturn(Optional.of("org.hippoecm.frontend.editor.layout.TwoColumn"));
replayAll(root, editorNode);
assertThat("2-col sorter is retrieved", NamespaceUtils.retrieveFieldSorter(root).get() instanceof TwoColumnFieldSorter);
}
@Test
public void retrieveFieldSorterUnknownLayout() throws Exception {
final Node root = createMock(Node.class);
final Node editorNode = createMock(Node.class);
final Node layout = createMock(Node.class);
PowerMock.mockStaticPartial(NamespaceUtils.class, "getPluginClassForField");
expect(root.hasNode(NamespaceUtils.EDITOR_CONFIG_PATH)).andReturn(true);
expect(root.getNode(NamespaceUtils.EDITOR_CONFIG_PATH)).andReturn(editorNode);
expect(editorNode.hasNode("root")).andReturn(true);
expect(editorNode.getNode("root")).andReturn(layout);
expect(NamespaceUtils.getPluginClassForField(layout)).andReturn(Optional.of("unknown"));
replayAll(root, editorNode);
assertThat("default sorter is retrieved", NamespaceUtils.retrieveFieldSorter(root).get() instanceof NodeOrderFieldSorter);
}
@Test
public void retrieveFieldSorterNoPluginClass() throws Exception {
final Node root = createMock(Node.class);
final Node editorNode = createMock(Node.class);
final Node layout = createMock(Node.class);
PowerMock.mockStaticPartial(NamespaceUtils.class, "getPluginClassForField");
expect(root.hasNode(NamespaceUtils.EDITOR_CONFIG_PATH)).andReturn(true);
expect(root.getNode(NamespaceUtils.EDITOR_CONFIG_PATH)).andReturn(editorNode);
expect(editorNode.hasNode("root")).andReturn(true);
expect(editorNode.getNode("root")).andReturn(layout);
expect(NamespaceUtils.getPluginClassForField(layout)).andReturn(Optional.empty());
replayAll(root, editorNode);
assertThat("default sorter is retrieved", NamespaceUtils.retrieveFieldSorter(root).get() instanceof NodeOrderFieldSorter);
}
@Test
public void retrieveFieldSorterNoLayoutNode() throws Exception {
final Node root = createMock(Node.class);
final Node editorNode = createMock(Node.class);
expect(root.hasNode(NamespaceUtils.EDITOR_CONFIG_PATH)).andReturn(true);
expect(root.getNode(NamespaceUtils.EDITOR_CONFIG_PATH)).andReturn(editorNode);
expect(editorNode.hasNode("root")).andReturn(false);
replayAll();
assertThat("default sorter is retrieved", NamespaceUtils.retrieveFieldSorter(root).get() instanceof NodeOrderFieldSorter);
}
@Test
public void retrieveFieldSorterNoEditorNode() throws Exception {
final Node root = createMock(Node.class);
expect(root.hasNode(NamespaceUtils.EDITOR_CONFIG_PATH)).andReturn(false);
replayAll();
assertFalse(NamespaceUtils.retrieveFieldSorter(root).isPresent());
}
@Test
public void retrieveFieldSorterRepositoryException() throws Exception {
final Node root = createMock(Node.class);
expect(root.hasNode(NamespaceUtils.EDITOR_CONFIG_PATH)).andThrow(new RepositoryException());
expect(JcrUtils.getNodePathQuietly(root)).andReturn("/bla");
replayAll(root);
assertFalse(NamespaceUtils.retrieveFieldSorter(root).isPresent());
}
}
|
huhong789/shortcut | linux-lts-quantal-3.5.0/drivers/usb/host/ohci-sh.c | <reponame>huhong789/shortcut<filename>linux-lts-quantal-3.5.0/drivers/usb/host/ohci-sh.c
/*
* OHCI HCD (Host Controller Driver) for USB.
*
* Copyright (C) 2008 Renesas Solutions Corp.
*
* Author : <NAME> <<EMAIL>>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 2 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#include <linux/platform_device.h>
static int ohci_sh_start(struct usb_hcd *hcd)
{
struct ohci_hcd *ohci = hcd_to_ohci(hcd);
ohci_hcd_init(ohci);
ohci_init(ohci);
ohci_run(ohci);
return 0;
}
static const struct hc_driver ohci_sh_hc_driver = {
.description = hcd_name,
.product_desc = "SuperH OHCI",
.hcd_priv_size = sizeof(struct ohci_hcd),
/*
* generic hardware linkage
*/
.irq = ohci_irq,
.flags = HCD_USB11 | HCD_MEMORY,
/*
* basic lifecycle operations
*/
.start = ohci_sh_start,
.stop = ohci_stop,
.shutdown = ohci_shutdown,
/*
* managing i/o requests and associated device resources
*/
.urb_enqueue = ohci_urb_enqueue,
.urb_dequeue = ohci_urb_dequeue,
.endpoint_disable = ohci_endpoint_disable,
/*
* scheduling support
*/
.get_frame_number = ohci_get_frame,
/*
* root hub support
*/
.hub_status_data = ohci_hub_status_data,
.hub_control = ohci_hub_control,
#ifdef CONFIG_PM
.bus_suspend = ohci_bus_suspend,
.bus_resume = ohci_bus_resume,
#endif
.start_port_reset = ohci_start_port_reset,
};
/*-------------------------------------------------------------------------*/
static int ohci_hcd_sh_probe(struct platform_device *pdev)
{
struct resource *res = NULL;
struct usb_hcd *hcd = NULL;
int irq = -1;
int ret;
if (usb_disabled())
return -ENODEV;
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!res) {
dev_err(&pdev->dev, "platform_get_resource error.\n");
return -ENODEV;
}
irq = platform_get_irq(pdev, 0);
if (irq < 0) {
dev_err(&pdev->dev, "platform_get_irq error.\n");
return -ENODEV;
}
/* initialize hcd */
hcd = usb_create_hcd(&ohci_sh_hc_driver, &pdev->dev, (char *)hcd_name);
if (!hcd) {
dev_err(&pdev->dev, "Failed to create hcd\n");
return -ENOMEM;
}
hcd->regs = (void __iomem *)res->start;
hcd->rsrc_start = res->start;
hcd->rsrc_len = resource_size(res);
ret = usb_add_hcd(hcd, irq, IRQF_SHARED);
if (ret != 0) {
dev_err(&pdev->dev, "Failed to add hcd\n");
usb_put_hcd(hcd);
return ret;
}
return ret;
}
static int ohci_hcd_sh_remove(struct platform_device *pdev)
{
struct usb_hcd *hcd = platform_get_drvdata(pdev);
usb_remove_hcd(hcd);
usb_put_hcd(hcd);
return 0;
}
static struct platform_driver ohci_hcd_sh_driver = {
.probe = ohci_hcd_sh_probe,
.remove = ohci_hcd_sh_remove,
.shutdown = usb_hcd_platform_shutdown,
.driver = {
.name = "sh_ohci",
.owner = THIS_MODULE,
},
};
MODULE_ALIAS("platform:sh_ohci");
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.