hexsha stringlengths 40 40 | size int64 3 1.05M | ext stringclasses 1 value | lang stringclasses 1 value | max_stars_repo_path stringlengths 5 1.02k | max_stars_repo_name stringlengths 4 126 | max_stars_repo_head_hexsha stringlengths 40 78 | max_stars_repo_licenses list | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 5 1.02k | max_issues_repo_name stringlengths 4 114 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses list | max_issues_count float64 1 92.2k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 5 1.02k | max_forks_repo_name stringlengths 4 136 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses list | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | avg_line_length float64 2.55 99.9 | max_line_length int64 3 1k | alphanum_fraction float64 0.25 1 | index int64 0 1M | content stringlengths 3 1.05M |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
9235163f252f804621adccb6942a5f0683d918be | 2,115 | java | Java | third-integration/devCloud/src/main/java/nl/sri/devCloud/entity/VOnlinePlanDate.java | songdi676/paas-admin | cccf3c8b6a367d3d3bb96ffd9aa034dfb9abf3f7 | [
"Apache-2.0"
] | null | null | null | third-integration/devCloud/src/main/java/nl/sri/devCloud/entity/VOnlinePlanDate.java | songdi676/paas-admin | cccf3c8b6a367d3d3bb96ffd9aa034dfb9abf3f7 | [
"Apache-2.0"
] | null | null | null | third-integration/devCloud/src/main/java/nl/sri/devCloud/entity/VOnlinePlanDate.java | songdi676/paas-admin | cccf3c8b6a367d3d3bb96ffd9aa034dfb9abf3f7 | [
"Apache-2.0"
] | null | null | null | 18.552632 | 54 | 0.659574 | 997,154 | package nl.sri.devCloud.entity;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import com.baomidou.mybatisplus.annotation.TableField;
import java.io.Serializable;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* <p>
* VIEW
* </p>
*
* @author wurunxiang
* @since 2020-07-21
*/
@Data
@EqualsAndHashCode(callSuper = false)
public class VOnlinePlanDate implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 计划名称
*/
private String 上线计划;
private LocalDate 上线日期;
private String 版本状态;
private String 上线日类型;
/**
* 首次初版时的需求数
*/
private BigDecimal 首次初版需求数量;
/**
* 首次定版时的需求数
*/
private BigDecimal 首次定版需求数量;
@TableField("ONLINE_PLAN_DATE_ID")
private String onlinePlanDateId;
@TableField("ONLINE_PLAN_ID")
private String onlinePlanId;
@TableField("ONLINE_PLAN_DATE")
private LocalDate onlinePlanDate;
/**
* 基线类型1-初版 2-定版 3-正式版
*/
@TableField("BASELINE_TYPE")
private BigDecimal baselineType;
/**
* 是否正常上线 0-false 1-true
*/
@TableField("IS_NORMAL")
private BigDecimal isNormal;
/**
* 是否生效0-false,1-true
*/
@TableField("IS_VALID")
private BigDecimal isValid;
/**
* 是否开启历史变更开关0-false 1-true
*/
@TableField("IS_OPEN_HIS_CHANGE")
private BigDecimal isOpenHisChange;
/**
* 每次定版调整的变更数,上线日创建时为0,每次发送定版后更新为本次发送的变更数
*/
@TableField("CHANGE_COUNT")
private BigDecimal changeCount;
@TableField("OBJ_STATUS")
private BigDecimal objStatus;
@TableField("CREATE_TIME")
private LocalDateTime createTime;
@TableField("CREATE_USER")
private String createUser;
@TableField("UPDATE_TIME")
private LocalDateTime updateTime;
@TableField("UPDATE_USER")
private String updateUser;
/**
* 流程实例id
*/
@TableField("FLOW_INSTANCE_ID")
private String flowInstanceId;
/**
* 流程审批状态 申请状态 1-审批中 2-审批通过
*/
@TableField("FLOW_STATUS")
private BigDecimal flowStatus;
}
|
92351693d734daf0274a4e3870af4d9bda335443 | 3,001 | java | Java | endpoints/citrus-spring-integration/src/main/java/com/consol/citrus/config/annotation/ChannelEndpointConfigParser.java | citrusframework/citrus | 8bdf243e1691c591777b7c23d545a33812885ab8 | [
"Apache-2.0"
] | 177 | 2018-05-18T20:48:00.000Z | 2022-03-21T12:23:55.000Z | endpoints/citrus-spring-integration/src/main/java/com/consol/citrus/config/annotation/ChannelEndpointConfigParser.java | postfinance/citrus | e8f0f00ec16916c93686bb43dee97bd0007a8679 | [
"Apache-2.0"
] | 432 | 2018-05-16T21:56:38.000Z | 2022-03-16T13:19:45.000Z | endpoints/citrus-spring-integration/src/main/java/com/consol/citrus/config/annotation/ChannelEndpointConfigParser.java | postfinance/citrus | e8f0f00ec16916c93686bb43dee97bd0007a8679 | [
"Apache-2.0"
] | 71 | 2018-06-18T11:42:55.000Z | 2021-12-27T12:10:59.000Z | 37.987342 | 126 | 0.722759 | 997,155 | /*
* Copyright 2006-2018 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 com.consol.citrus.config.annotation;
import com.consol.citrus.TestActor;
import com.consol.citrus.channel.*;
import com.consol.citrus.spi.ReferenceResolver;
import org.springframework.integration.core.MessagingTemplate;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.core.DestinationResolver;
import org.springframework.util.StringUtils;
/**
* @author Christoph Deppisch
* @since 2.7.6
*/
public class ChannelEndpointConfigParser implements AnnotationConfigParser<ChannelEndpointConfig, ChannelEndpoint> {
@Override
public ChannelEndpoint parse(ChannelEndpointConfig annotation, ReferenceResolver referenceResolver) {
ChannelEndpointBuilder builder = new ChannelEndpointBuilder();
String channel = annotation.channel();
String channelName = annotation.channelName();
if (StringUtils.hasText(channel)) {
builder.channel(referenceResolver.resolve(annotation.channel(), MessageChannel.class));
}
if (StringUtils.hasText(channelName)) {
builder.channel(annotation.channelName());
}
if (StringUtils.hasText(annotation.messagingTemplate())) {
//messagingTemplate
String messagingTemplate = "messagingTemplate"; //default value
if (StringUtils.hasText(annotation.messagingTemplate())) {
messagingTemplate = annotation.messagingTemplate();
}
builder.messagingTemplate(referenceResolver.resolve(messagingTemplate, MessagingTemplate.class));
}
builder.useObjectMessages(annotation.useObjectMessages());
builder.filterInternalHeaders(annotation.filterInternalHeaders());
if (StringUtils.hasText(annotation.messageConverter())) {
builder.messageConverter(referenceResolver.resolve(annotation.messageConverter(), ChannelMessageConverter.class));
}
if (StringUtils.hasText(annotation.channelResolver())) {
builder.channelResolver(referenceResolver.resolve(annotation.channelResolver(), DestinationResolver.class));
}
builder.timeout(annotation.timeout());
if (StringUtils.hasText(annotation.actor())) {
builder.actor(referenceResolver.resolve(annotation.actor(), TestActor.class));
}
return builder.initialize().build();
}
}
|
9235182bba266cbd2923dd8fe53752b66a123fb0 | 384 | java | Java | JacksonMapper/src/main/java/com/springboot/jacksonmapper/annotation/exception/UserWithRoot.java | jonatanvicente/spring-boot-training | a7f6fed900df8ece0316243a10c6b98f56b2af69 | [
"MIT"
] | null | null | null | JacksonMapper/src/main/java/com/springboot/jacksonmapper/annotation/exception/UserWithRoot.java | jonatanvicente/spring-boot-training | a7f6fed900df8ece0316243a10c6b98f56b2af69 | [
"MIT"
] | null | null | null | JacksonMapper/src/main/java/com/springboot/jacksonmapper/annotation/exception/UserWithRoot.java | jonatanvicente/spring-boot-training | a7f6fed900df8ece0316243a10c6b98f56b2af69 | [
"MIT"
] | null | null | null | 20.210526 | 58 | 0.666667 | 997,156 | package com.springboot.jacksonmapper.annotation.exception;
import com.fasterxml.jackson.annotation.JsonRootName;
@JsonRootName(value = "user")
public class UserWithRoot {
public int id;
public String name;
public UserWithRoot() {
super();
}
public UserWithRoot(final int id, final String name) {
this.id = id;
this.name = name;
}
}
|
92351830fb076240e09d1d253c10f0c934b26b08 | 7,450 | java | Java | src/main/java/com/jcraft/jsch/ProxyHTTP.java | ePaul/jsch-documentation | fd8c4936defe02ccb04ae4485bcc439ca25ff988 | [
"BSD-3-Clause"
] | 52 | 2015-01-19T01:47:41.000Z | 2022-01-10T05:59:03.000Z | src/main/java/com/jcraft/jsch/ProxyHTTP.java | ePaul/jsch-documentation | fd8c4936defe02ccb04ae4485bcc439ca25ff988 | [
"BSD-3-Clause"
] | 8 | 2016-04-13T09:00:24.000Z | 2019-11-18T13:37:40.000Z | src/main/java/com/jcraft/jsch/ProxyHTTP.java | ePaul/jsch-documentation | fd8c4936defe02ccb04ae4485bcc439ca25ff988 | [
"BSD-3-Clause"
] | 16 | 2015-01-04T19:58:53.000Z | 2021-11-02T15:52:21.000Z | 31.041667 | 109 | 0.65302 | 997,157 | /* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */
/*
Copyright (c) 2002-2016 ymnk, JCraft,Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
3. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 JCRAFT,
INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE 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.
*/
package com.jcraft.jsch;
import java.io.*;
import java.net.*;
/**
* A {@link Proxy} implementation using a HTTP proxy.
*
* This uses the HTTP CONNECT method as described in Sections 5.2 and 5.3
* of RFC 2817.
* @see
* <a href="http://tools.ietf.org/html/draft-luotonen-web-proxy-tunneling-01">
* Internet Draft <em>Tunneling TCP based protocols through Web proxy
* servers</em> (Ari Luotonen, expired 1999)</a>
* @see <a href="http://tools.ietf.org/html/rfc2817#section-5">RFC 2817,
* Section 5. Upgrade across Proxies</a>
*
*/
public class ProxyHTTP implements Proxy{
private static int DEFAULTPORT=80;
private String proxy_host;
private int proxy_port;
private InputStream in;
private OutputStream out;
private Socket socket;
private String user;
private String passwd;
/**
* Creates a new ProxyHTTP object.
* @param proxy_host the proxie's host name, maybe including the port
* number separated by {@code :}. (The default port is 80.)
*/
public ProxyHTTP(String proxy_host){
int port=DEFAULTPORT;
String host=proxy_host;
// do we really need to call indexOf(':') three times? -- P.E.
if(proxy_host.indexOf(':')!=-1){
try{
host=proxy_host.substring(0, proxy_host.indexOf(':'));
port=Integer.parseInt(proxy_host.substring(proxy_host.indexOf(':')+1));
}
catch(Exception e){
}
}
this.proxy_host=host;
this.proxy_port=port;
}
/**
* Creates a new ProxyHTTP object.
* @param proxy_host the proxie's host name.
* @param proxy_port the port number of the proxy.
*/
public ProxyHTTP(String proxy_host, int proxy_port){
this.proxy_host=proxy_host;
this.proxy_port=proxy_port;
}
/**
* Sets the user name and password needed for authentication
* to the proxy. This has no relation to any authentication on
* the target server.
*<p>
* If the proxy needs authentication, this method should be called
* before calling {@link #connect} (i.e. before passing the Proxy
* object to the JSch library).
* This class supports only Basic Authentication as defined in RFC 2617,
* i.e. sending user name and password in plaintext. (Both will be
* encoded using first UTF-8 and then Base64.)
*</p>
* @param user the user name
* @param passwd the password.
* @see <a href="http://tools.ietf.org/html/rfc2617#section-2">RFC 2617,
* section 2 Basic Authentication Scheme</a>
*/
public void setUserPasswd(String user, String passwd){
this.user=user;
this.passwd=passwd;
}
// javadoc will be copied from interface. -- P.E.
public void connect(SocketFactory socket_factory, String host, int port, int timeout) throws JSchException{
try{
if(socket_factory==null){
socket=Util.createSocket(proxy_host, proxy_port, timeout);
in=socket.getInputStream();
out=socket.getOutputStream();
}
else{
socket=socket_factory.createSocket(proxy_host, proxy_port);
in=socket_factory.getInputStream(socket);
out=socket_factory.getOutputStream(socket);
}
if(timeout>0){
socket.setSoTimeout(timeout);
}
socket.setTcpNoDelay(true);
out.write(Util.str2byte("CONNECT "+host+":"+port+" HTTP/1.0\r\n"));
if(user!=null && passwd!=null){
byte[] code=Util.str2byte(user+":"+passwd);
code=Util.toBase64(code, 0, code.length);
out.write(Util.str2byte("Proxy-Authorization: Basic "));
out.write(code);
out.write(Util.str2byte("\r\n"));
}
out.write(Util.str2byte("\r\n"));
out.flush();
int foo=0;
StringBuffer sb=new StringBuffer();
while(foo>=0){
foo=in.read(); if(foo!=13){sb.append((char)foo); continue;}
foo=in.read(); if(foo!=10){continue;}
break;
}
if(foo<0){
throw new IOException();
}
String response=sb.toString();
String reason="Unknow reason";
int code=-1;
try{
foo=response.indexOf(' ');
int bar=response.indexOf(' ', foo+1);
code=Integer.parseInt(response.substring(foo+1, bar));
reason=response.substring(bar+1);
}
catch(Exception e){
}
if(code!=200){
throw new IOException("proxy error: "+reason);
}
/*
while(foo>=0){
foo=in.read(); if(foo!=13) continue;
foo=in.read(); if(foo!=10) continue;
foo=in.read(); if(foo!=13) continue;
foo=in.read(); if(foo!=10) continue;
break;
}
*/
int count=0;
while(true){
count=0;
while(foo>=0){
foo=in.read(); if(foo!=13){count++; continue;}
foo=in.read(); if(foo!=10){continue;}
break;
}
if(foo<0){
throw new IOException();
}
if(count==0)break;
}
}
catch(RuntimeException e){
throw e;
}
catch(Exception e){
try{ if(socket!=null)socket.close(); }
catch(Exception eee){
}
String message="ProxyHTTP: "+e.toString();
if(e instanceof Throwable)
throw new JSchException(message, (Throwable)e);
throw new JSchException(message);
}
}
// javadoc will be copied from interface. -- P.E.
public InputStream getInputStream(){ return in; }
// javadoc will be copied from interface. -- P.E.
public OutputStream getOutputStream(){ return out; }
// javadoc will be copied from interface. -- P.E.
public Socket getSocket(){ return socket; }
// javadoc will be copied from interface. -- P.E.
public void close(){
try{
if(in!=null)in.close();
if(out!=null)out.close();
if(socket!=null)socket.close();
}
catch(Exception e){
}
in=null;
out=null;
socket=null;
}
/**
* returns the default proxy port - this is 80 as defined for HTTP.
*/
public static int getDefaultPort(){
return DEFAULTPORT;
}
}
|
923518659b86cee17939c03b7feb615e7cea632f | 898 | java | Java | virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/int_double/Beta.java | tjake/nosqlbench | d31fbd45fe7627d681624fb94bce763bcac78feb | [
"Apache-2.0"
] | 115 | 2020-03-04T06:12:37.000Z | 2022-03-16T04:38:52.000Z | virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/int_double/Beta.java | tjake/nosqlbench | d31fbd45fe7627d681624fb94bce763bcac78feb | [
"Apache-2.0"
] | 318 | 2020-02-24T12:26:15.000Z | 2022-03-29T16:43:48.000Z | virtdata-lib-curves4/src/main/java/io/nosqlbench/virtdata/library/curves4/continuous/int_double/Beta.java | tjake/nosqlbench | d31fbd45fe7627d681624fb94bce763bcac78feb | [
"Apache-2.0"
] | 52 | 2020-03-04T06:12:59.000Z | 2022-03-21T12:23:44.000Z | 40.818182 | 213 | 0.789532 | 997,158 | package io.nosqlbench.virtdata.library.curves4.continuous.int_double;
import io.nosqlbench.virtdata.api.annotations.Categories;
import io.nosqlbench.virtdata.api.annotations.Category;
import io.nosqlbench.virtdata.api.annotations.ThreadSafeMapper;
import org.apache.commons.statistics.distribution.BetaDistribution;
/**
* @see <a href="https://en.wikipedia.org/wiki/Beta_distribution">Wikipedia: Beta distribution</a>
*
* @see <a href="https://commons.apache.org/proper/commons-statistics/commons-statistics-distribution/apidocs/org/apache/commons/statistics/distribution/BetaDistribution.html">Commons JavaDoc: BetaDistribution</a>
*
* {@inheritDoc}
*/
@Categories({Category.distributions})
@ThreadSafeMapper
public class Beta extends IntToDoubleContinuousCurve {
public Beta(double alpha, double beta, String... mods) {
super(new BetaDistribution(alpha, beta), mods);
}
}
|
9235194fdc2f31e558c11d828b2934d227eae856 | 2,667 | java | Java | src/main/java/au/lyrael/stacywolves/entity/wolf/EntityDiamondWolf.java | LyraelRayne/NeedsMoreDragons | 828c784c29ce470163d1729218827c7c65122fe4 | [
"FTL"
] | 8 | 2016-04-30T15:10:43.000Z | 2021-03-23T22:35:51.000Z | src/main/java/au/lyrael/stacywolves/entity/wolf/EntityDiamondWolf.java | LyraelRayne/NeedsMoreDragons | 828c784c29ce470163d1729218827c7c65122fe4 | [
"FTL"
] | 45 | 2016-04-22T21:01:11.000Z | 2021-10-05T06:59:11.000Z | src/main/java/au/lyrael/stacywolves/entity/wolf/EntityDiamondWolf.java | LyraelRayne/StacysWolves | 828c784c29ce470163d1729218827c7c65122fe4 | [
"FTL"
] | 4 | 2016-04-30T15:10:48.000Z | 2018-06-17T00:10:50.000Z | 44.45 | 160 | 0.689914 | 997,159 | package au.lyrael.stacywolves.entity.wolf;
import au.lyrael.stacywolves.annotation.WolfMetadata;
import au.lyrael.stacywolves.annotation.WolfSpawn;
import au.lyrael.stacywolves.annotation.WolfSpawnBiome;
import au.lyrael.stacywolves.client.render.IRenderableWolf;
import au.lyrael.stacywolves.item.WolfPeriodicItemDrop;
import au.lyrael.stacywolves.registry.ItemRegistry;
import net.minecraft.entity.EntityAgeable;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;
import static au.lyrael.stacywolves.entity.SpawnWeights.SPAWN_PROBABILITY_SUPER_RARE;
import static au.lyrael.stacywolves.entity.SpawnWeights.SPAWN_WEIGHT_SUPER_RARE;
import static au.lyrael.stacywolves.registry.WolfType.SUBTERRANEAN;
import static net.minecraftforge.common.BiomeDictionary.Type.*;
@WolfMetadata(name = "EntityDiamondWolf", primaryColour = 0x7F7F7F, secondaryColour = 0x5DECF5, type = SUBTERRANEAN, probability = SPAWN_PROBABILITY_SUPER_RARE,
spawns = {
@WolfSpawn(spawnBiomes = {
@WolfSpawnBiome(requireBiomeTypes = {PLAINS}),
@WolfSpawnBiome(requireBiomeTypes = {MESA}),
@WolfSpawnBiome(requireBiomeTypes = {FOREST}),
@WolfSpawnBiome(requireBiomeTypes = {MOUNTAIN}),
@WolfSpawnBiome(requireBiomeTypes = {HILLS}),
@WolfSpawnBiome(requireBiomeTypes = {SWAMP}),
@WolfSpawnBiome(requireBiomeTypes = {SANDY}),
@WolfSpawnBiome(requireBiomeTypes = {SNOWY}),
@WolfSpawnBiome(requireBiomeTypes = {WASTELAND}),
@WolfSpawnBiome(requireBiomeTypes = {BEACH}),
@WolfSpawnBiome(requireBiomeTypes = {JUNGLE}),
@WolfSpawnBiome(requireBiomeTypes = {RIVER}),
}, weight = SPAWN_WEIGHT_SUPER_RARE, min = 1, max = 4)
})
public class EntityDiamondWolf extends EntitySubterraneanWolfBase implements IRenderableWolf {
public EntityDiamondWolf(World worldObj) {
super(worldObj);
addLikedItem(ItemRegistry.getWolfFood("diamond_bone"));
setPeriodicDrop(new WolfPeriodicItemDrop(300, 5, new ItemStack(Items.diamond)));
}
@Override
public EntityWolfBase createChild(EntityAgeable parent) {
EntityWolfBase child = new EntityDiamondWolf(this.worldObj);
return createChild(parent, child);
}
@Override
public String getTextureFolderName() {
return "diamond";
}
@Override
public boolean getCanSpawnHere() {
return getCanSpawnHere(15);
}
}
|
923519ef5b5d2e9d2fc4e0ec13b23d7610d9608d | 1,648 | java | Java | src/main/java/com/libqa/web/domain/FeedFile.java | howlingproject/libqa | 4688caf7368c4a9607189dcaffc30cec74073107 | [
"MIT"
] | 23 | 2015-02-01T04:59:12.000Z | 2021-07-12T07:04:22.000Z | src/main/java/com/libqa/web/domain/FeedFile.java | howlingproject/libqa | 4688caf7368c4a9607189dcaffc30cec74073107 | [
"MIT"
] | 65 | 2016-03-03T23:40:40.000Z | 2016-11-05T08:58:34.000Z | src/main/java/com/libqa/web/domain/FeedFile.java | howlingproject/libqa | 4688caf7368c4a9607189dcaffc30cec74073107 | [
"MIT"
] | 9 | 2015-09-17T07:12:31.000Z | 2019-01-20T09:50:36.000Z | 22.888889 | 77 | 0.701456 | 997,160 | package com.libqa.web.domain;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.libqa.application.enums.FileType;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import javax.persistence.*;
import java.util.Date;
@Data
@Entity
@ToString
@Table(indexes = {@Index(columnList = "isDeleted")})
@EqualsAndHashCode(of = "feedFileId")
public class FeedFile {
@Id
@Column(nullable = false)
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer feedFileId;
@Column(nullable = false)
private String realName;
@Column(nullable = false)
private String savedName;
@Column(nullable = false, length = 80)
private String filePath;
@Column(nullable = false)
private Integer fileSize;
@Enumerated(EnumType.STRING)
@Column(length = 10)
private FileType fileType;
@Column
private Integer downloadCount = 0;
@Column(columnDefinition = "TINYINT(1) DEFAULT 0")
private boolean isDeleted;
@Temporal(TemporalType.TIMESTAMP)
@Column(nullable = false)
private Date insertDate;
@Column(nullable = false)
private Integer userId;
@Column(nullable = false, length = 40)
private String userNick;
@Column(nullable = false)
private Integer insertUserId;
@JsonIgnore
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "feedThreadId", referencedColumnName = "feedThreadId")
private FeedThread feedThread;
public boolean isFileType() {
return FileType.FILE == this.fileType;
}
public boolean isImageType() {
return FileType.IMAGE == this.fileType;
}
}
|
92351a280d1a1fb3789e65f01af5052b66a36959 | 368 | java | Java | src/main/java/com/bfsi/mfi/service/LoanDetailViewService.java | openMF/egalite-web-service | ac4904b323c7440a4e651e73817abf4c9e80d8a1 | [
"Apache-2.0"
] | 1 | 2016-05-13T03:09:20.000Z | 2016-05-13T03:09:20.000Z | src/main/java/com/bfsi/mfi/service/LoanDetailViewService.java | openMF/egalite-web-service | ac4904b323c7440a4e651e73817abf4c9e80d8a1 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/bfsi/mfi/service/LoanDetailViewService.java | openMF/egalite-web-service | ac4904b323c7440a4e651e73817abf4c9e80d8a1 | [
"Apache-2.0"
] | 9 | 2016-05-13T03:09:33.000Z | 2019-02-02T21:16:18.000Z | 26.285714 | 82 | 0.790761 | 997,161 | package com.bfsi.mfi.service;
import com.bfsi.mfi.entity.LoanDetailView;
import com.bfsi.mfi.exception.ServiceException;
import com.bfsi.mfi.vo.LoanDetailViewVO;
public interface LoanDetailViewService extends
ReadOnlyMaintenanceService<LoanDetailViewVO, LoanDetailView>{
LoanDetailViewVO getLoanView(String id) throws ServiceException;
}
|
92351a8d28ca420fcf0c67ff7f1b7e7d532df509 | 2,561 | java | Java | lib_permission/src/main/java/com/pinery/lib_permission/manager/OtherPermissionManager.java | gujianhesong/PermissionLibrary | 07e3c3ca8d94739f23e9dc2df07a114ae2c3890b | [
"Apache-2.0"
] | null | null | null | lib_permission/src/main/java/com/pinery/lib_permission/manager/OtherPermissionManager.java | gujianhesong/PermissionLibrary | 07e3c3ca8d94739f23e9dc2df07a114ae2c3890b | [
"Apache-2.0"
] | null | null | null | lib_permission/src/main/java/com/pinery/lib_permission/manager/OtherPermissionManager.java | gujianhesong/PermissionLibrary | 07e3c3ca8d94739f23e9dc2df07a114ae2c3890b | [
"Apache-2.0"
] | null | null | null | 26.957895 | 155 | 0.763764 | 997,162 | package com.pinery.lib_permission.manager;
import android.accessibilityservice.AccessibilityService;
import android.accessibilityservice.AccessibilityServiceInfo;
import android.content.Context;
import android.content.Intent;
import android.provider.Settings;
import android.support.v4.app.NotificationManagerCompat;
import android.support.v4.view.accessibility.AccessibilityManagerCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.accessibility.AccessibilityManager;
import com.pinery.lib_permission.dialog.GuideDialog;
import com.pinery.lib_permission.util.VersionUtil;
import java.util.List;
import java.util.Set;
import static android.provider.Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS;
/**
* 权限管理
* @author hesong
*
*/
public class OtherPermissionManager {
/**
* 通知监听功能是否开启
* @param context
* @return
*/
public static boolean isNotificationListenerEnabled(Context context) {
Set<String> packageNames = NotificationManagerCompat.getEnabledListenerPackages(context);
if (packageNames.contains(context.getPackageName())) {
return true;
}
return false;
}
/**
* 检测辅助功能是否开启
* @param context
* @param clazz
* @param <T>
* @return
*/
public static <T extends AccessibilityService> boolean isFuzhuServiceEnabled(Context context, Class<T> clazz){
boolean isEnabled = false;
AccessibilityManager manager = (AccessibilityManager) context.getSystemService(Context.ACCESSIBILITY_SERVICE);
List<AccessibilityServiceInfo> list = AccessibilityManagerCompat.getEnabledAccessibilityServiceList(manager, AccessibilityServiceInfo.FEEDBACK_ALL_MASK);
for (int i = 0; i < list.size(); i++) {
String name = context.getPackageName() + "/" + clazz.getName();
if (name.equals(list.get(i).getId())) {
isEnabled = true;
break;
}
}
return isEnabled;
}
/**
* 打开通知监听功能
*/
public static void openNotificationAccess(Context context) {
if(VersionUtil.isLowerVersionForNotification()){
return;
}
Intent intent = new Intent(ACTION_NOTIFICATION_LISTENER_SETTINGS);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
new GuideDialog(context).show();
}
/**
* 打开辅助功能
*/
public static void openFuzhuService(Context context){
try {
//打开系统设置中辅助功能
Intent intent = new Intent(android.provider.Settings.ACTION_ACCESSIBILITY_SETTINGS);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
} catch (Exception e) {
e.printStackTrace();
}
new GuideDialog(context).show();
}
}
|
92351b4ab1630d0af54df60339931df18fe7b48e | 3,302 | java | Java | app/src/main/java/com/fntj/app/manager/FileManager.java | HenryZhang1998/fntj.android2_init | 183aa0e4742d555bd54fbe17fdb56ee2a28ed53c | [
"Apache-2.0"
] | 1 | 2022-03-07T05:45:04.000Z | 2022-03-07T05:45:04.000Z | app/src/main/java/com/fntj/app/manager/FileManager.java | HenryZhang1998/fntj.android2_init | 183aa0e4742d555bd54fbe17fdb56ee2a28ed53c | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/fntj/app/manager/FileManager.java | HenryZhang1998/fntj.android2_init | 183aa0e4742d555bd54fbe17fdb56ee2a28ed53c | [
"Apache-2.0"
] | 1 | 2022-03-07T05:45:11.000Z | 2022-03-07T05:45:11.000Z | 30.293578 | 100 | 0.585706 | 997,163 | package com.fntj.app.manager;
import android.content.Context;
import android.content.res.AssetManager;
import android.os.Environment;
import android.util.Log;
import com.fntj.lib.zb.model.APIResult;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.io.Reader;
public class FileManager {
public static String read(Context context, String fileName) {
String pkg = context.getPackageName();
String filePath = null;
boolean hasSDCard = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
if (hasSDCard) {
filePath = Environment.getExternalStorageDirectory().toString();
} else {
filePath = Environment.getDownloadCacheDirectory().toString();
}
filePath += File.separator + pkg + File.separator + fileName;
try {
File file = new File(filePath);
if (!file.exists()) {
return null;
}
RandomAccessFile acc = new RandomAccessFile(file, "rwd");
String text = acc.readUTF();
acc.close();
return text;
} catch (Exception e) {
Log.e("FileManager", "Error on read File:" + e);
return null;
}
}
// 将字符串写入到文本文件中
public static void write(Context context, String fileName, String text) {
String pkg = context.getPackageName();
String filePath = null;
boolean hasSDCard = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
if (hasSDCard) {
filePath = Environment.getExternalStorageDirectory().toString();
} else {
filePath = Environment.getDownloadCacheDirectory().toString();
}
filePath += File.separator + pkg + File.separator + fileName;
try {
File file = new File(filePath);
if (!file.exists()) {
Log.d("TestFile", "Create the file:" + filePath);
file.getParentFile().mkdirs();
file.createNewFile();
}
RandomAccessFile raf = new RandomAccessFile(file, "rwd");
raf.seek(file.length());
raf.write(text.getBytes());
raf.close();
} catch (Exception e) {
Log.e("FileManager", "Error on write File:" + e);
}
}
public static APIResult<String> readAsset(Context context, String fileName) {
try {
StringBuilder stringBuilder = new StringBuilder();
//获取assets资源管理器
AssetManager assetManager = context.getAssets();
Reader reader = new InputStreamReader(assetManager.open(fileName));
//通过管理器打开文件并读取
BufferedReader bf = new BufferedReader(reader);
String line;
while ((line = bf.readLine()) != null) {
stringBuilder.append(line);
}
bf.close();
reader.close();
//assetManager.close();
String text = stringBuilder.toString();
return APIResult.Success(text);
} catch (Exception ex) {
return APIResult.Fail(ex.getMessage(), ex.getClass().getSimpleName());
}
}
}
|
92351b6d01a8dc24a721d244e2a115137e49910e | 3,577 | java | Java | starter-cli/src/main/java/io/micronaut/starter/cli/command/project/job/CreateJobCommand.java | glaforge/micronaut-starter | 9b29a7052f7a823c24a0b45475639e258db914e7 | [
"Apache-2.0"
] | 1 | 2020-05-08T14:45:27.000Z | 2020-05-08T14:45:27.000Z | starter-cli/src/main/java/io/micronaut/starter/cli/command/project/job/CreateJobCommand.java | alexismp/micronaut-starter | 17b0384dd5bba93c8a3920e719b56f73e9099998 | [
"Apache-2.0"
] | 119 | 2020-07-21T06:15:49.000Z | 2022-03-31T01:05:37.000Z | starter-cli/src/main/java/io/micronaut/starter/cli/command/project/job/CreateJobCommand.java | alexismp/micronaut-starter | 17b0384dd5bba93c8a3920e719b56f73e9099998 | [
"Apache-2.0"
] | null | null | null | 40.647727 | 163 | 0.710092 | 997,164 | /*
* Copyright 2020 original 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 io.micronaut.starter.cli.command.project.job;
import io.micronaut.context.annotation.Parameter;
import io.micronaut.context.annotation.Prototype;
import io.micronaut.core.annotation.ReflectiveAccess;
import io.micronaut.core.util.functional.ThrowingSupplier;
import io.micronaut.starter.application.Project;
import io.micronaut.starter.cli.CodeGenConfig;
import io.micronaut.starter.cli.command.CodeGenCommand;
import io.micronaut.starter.io.ConsoleOutput;
import io.micronaut.starter.io.OutputHandler;
import io.micronaut.starter.options.Language;
import io.micronaut.starter.template.RenderResult;
import io.micronaut.starter.template.RockerTemplate;
import io.micronaut.starter.template.TemplateRenderer;
import picocli.CommandLine;
import javax.inject.Inject;
import java.io.IOException;
@CommandLine.Command(name = "create-job", description = "Creates a job with scheduled method")
@Prototype
public class CreateJobCommand extends CodeGenCommand {
@ReflectiveAccess
@CommandLine.Parameters(paramLabel = "JOB-NAME", description = "The name of the job class to create")
String jobName;
@Inject
public CreateJobCommand(@Parameter CodeGenConfig config) {
super(config);
}
public CreateJobCommand(CodeGenConfig config,
ThrowingSupplier<OutputHandler, IOException> outputHandlerSupplier,
ConsoleOutput consoleOutput) {
super(config, outputHandlerSupplier, consoleOutput);
}
@Override
public boolean applies() {
return true;
}
@Override
public Integer call() throws Exception {
Project project = getProject(jobName);
TemplateRenderer templateRenderer = getTemplateRenderer(project);
RenderResult renderResult = null;
if (config.getSourceLanguage() == Language.JAVA) {
renderResult = templateRenderer.render(new RockerTemplate("src/main/java/{packagePath}/{className}.java", javaJob.template(project)), overwrite);
} else if (config.getSourceLanguage() == Language.GROOVY) {
renderResult = templateRenderer.render(new RockerTemplate("src/main/groovy/{packagePath}/{className}.groovy", groovyJob.template(project)), overwrite);
} else if (config.getSourceLanguage() == Language.KOTLIN) {
renderResult = templateRenderer.render(new RockerTemplate("src/main/kotlin/{packagePath}/{className}.kt", kotlinJob.template(project)), overwrite);
}
if (renderResult != null) {
if (renderResult.isSuccess()) {
out("@|blue ||@ Rendered job to " + renderResult.getPath());
} else if (renderResult.isSkipped()) {
warning("Rendering skipped for " + renderResult.getPath() + " because it already exists. Run again with -f to overwrite.");
} else if (renderResult.getError() != null) {
throw renderResult.getError();
}
}
return 0;
}
}
|
92351cb9102f6ebdd9a376659fafd317e12d431b | 3,367 | java | Java | cloudraider-core/src/main/java/com/intuit/cloudraider/core/interfaces/Route53Raider.java | EnzoZafra/CloudRaider | 357ed5bce432c42906a663b4a94a74dbe1d89562 | [
"Apache-2.0"
] | 29 | 2019-05-31T18:49:22.000Z | 2022-01-07T05:13:41.000Z | cloudraider-core/src/main/java/com/intuit/cloudraider/core/interfaces/Route53Raider.java | EnzoZafra/CloudRaider | 357ed5bce432c42906a663b4a94a74dbe1d89562 | [
"Apache-2.0"
] | 13 | 2019-10-01T17:12:45.000Z | 2021-10-01T17:12:09.000Z | cloudraider-core/src/main/java/com/intuit/cloudraider/core/interfaces/Route53Raider.java | EnzoZafra/CloudRaider | 357ed5bce432c42906a663b4a94a74dbe1d89562 | [
"Apache-2.0"
] | 14 | 2019-06-03T04:57:30.000Z | 2022-02-24T08:03:30.000Z | 33.336634 | 88 | 0.711613 | 997,165 | /*
* Apache 2.0 License
*
* Copyright (c) 2019 Intuit Inc.
*
* 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 com.intuit.cloudraider.core.interfaces;
import com.amazonaws.services.route53.model.HealthCheck;
import com.amazonaws.services.route53.model.HealthCheckObservation;
import com.intuit.cloudraider.model.HealthCheckStatus;
import java.util.List;
/**
* Route 53 functionality.
* <p>
*/
public interface Route53Raider {
/**
* Get all health checks.
*
* @return list of health checks
*/
public List<HealthCheck> listHealthCheckers();
/**
* Get the status of the given health check.
*
* @param healthCheckerId health check id
* @return list of HealthCheckObservation
*/
public List<HealthCheckObservation> getHealthCheckerStatus(String healthCheckerId);
/**
* Checks the health check status given id.
*
* @param healthCheckerId health checker id
* @return SUCCESS if all health checks pass; FAILURE if any health check has failed
*/
public HealthCheckStatus getSimpleHealthCheckerStatus(String healthCheckerId);
/**
* Update the traffic policy with the new version.
*
* @param trafficPolicyName traffic policy name
* @param version version
*/
public void updateTrafficPolicy(String trafficPolicyName, int version);
/**
* Get the version number of the given traffic policy.
*
* @param trafficPolicyName traffic policy name
* @return version number
*/
public int getTrafficPolicyVersion(String trafficPolicyName);
/**
* Update the health check with the provided regions.
*
* @param healthCheckId health check id
* @param regions list of health check regions
*/
public void updateHealthCheckRegions(String healthCheckId, List<String> regions);
/**
* Update the provided health check to use default regions.
*
* @param healthCheckId health check id
*/
public void updateHealthCheckToDefaultRegions(String healthCheckId);
/**
* Gets health check regions associated with the given health check.
*
* @param healthCheckId health check id
* @return list of health check regions
*/
public List<String> getHealthCheckRegions(String healthCheckId);
}
|
92351d9c715b45a2596bbeea3c01db4911cb25de | 702 | java | Java | Loader_i3b/src/main/java/es/uniovi/asw/parser/agents/PersonAgent.java | alfredofuentes9/Incii3bcodefresh | 231f05db76f41f4ea989bc3a361ed9440d8d6751 | [
"MIT"
] | null | null | null | Loader_i3b/src/main/java/es/uniovi/asw/parser/agents/PersonAgent.java | alfredofuentes9/Incii3bcodefresh | 231f05db76f41f4ea989bc3a361ed9440d8d6751 | [
"MIT"
] | 30 | 2018-03-14T19:17:21.000Z | 2018-05-10T09:50:54.000Z | Loader_i3b/src/main/java/es/uniovi/asw/parser/agents/PersonAgent.java | Arquisoft/Inci_i3b | f8b62ecf0fbb4c9639945ac93b8a59ad05bf4a41 | [
"MIT"
] | null | null | null | 23.4 | 100 | 0.662393 | 997,166 | package es.uniovi.asw.parser.agents;
/**
*
* @author Jorge Class used to represent PersonAgents and parse their data.
*
*/
public class PersonAgent extends AbstractAgent {
public PersonAgent(String name, String location, String email, String identifier, String kind) {
super(name, location, email, identifier, kind);
setKind("Person");
}
public PersonAgent(Object[] data) {
super((String)data[0],(String)data[1],(String)data[2],(String) data[3], String.valueOf(data[4]));
setKind("Person");
}
public String toString() {
return "Person Agent [Name=" + this.name
+ ", location=" + this.location
+ ", email=" + this.email
+ ", identifier=" + this.id
+"]";
}
}
|
92351df94300fe4108295a1ea82366945d7fdcf6 | 4,463 | java | Java | controller-server/src/main/java/com/yahoo/vespa/hosted/controller/versions/OsVersionStatus.java | sagiyaho/vespa | 5865b9bb80b540f6d252312fa6002300b2f1c9ee | [
"Apache-2.0"
] | 4,054 | 2017-08-11T07:58:38.000Z | 2022-03-31T22:32:15.000Z | controller-server/src/main/java/com/yahoo/vespa/hosted/controller/versions/OsVersionStatus.java | sagiyaho/vespa | 5865b9bb80b540f6d252312fa6002300b2f1c9ee | [
"Apache-2.0"
] | 4,854 | 2017-08-10T20:19:25.000Z | 2022-03-31T19:04:23.000Z | controller-server/src/main/java/com/yahoo/vespa/hosted/controller/versions/OsVersionStatus.java | sagiyaho/vespa | 5865b9bb80b540f6d252312fa6002300b2f1c9ee | [
"Apache-2.0"
] | 541 | 2017-08-10T18:51:18.000Z | 2022-03-11T03:18:56.000Z | 45.540816 | 170 | 0.637912 | 997,167 | // Copyright 2019 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.controller.versions;
import com.google.common.collect.ImmutableMap;
import com.yahoo.component.Version;
import com.yahoo.config.provision.CloudName;
import com.yahoo.config.provision.zone.ZoneApi;
import com.yahoo.vespa.hosted.controller.Controller;
import com.yahoo.vespa.hosted.controller.api.integration.configserver.NodeFilter;
import com.yahoo.vespa.hosted.controller.application.SystemApplication;
import com.yahoo.vespa.hosted.controller.maintenance.OsUpgrader;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
/**
* Information about OS versions in this system.
*
* @author mpolden
*/
public class OsVersionStatus {
public static final OsVersionStatus empty = new OsVersionStatus(ImmutableMap.of());
private final Map<OsVersion, List<NodeVersion>> versions;
/** Public for serialization purpose only. Use {@link OsVersionStatus#compute(Controller)} for an up-to-date status */
public OsVersionStatus(Map<OsVersion, List<NodeVersion>> versions) {
this.versions = ImmutableMap.copyOf(Objects.requireNonNull(versions, "versions must be non-null"));
}
/** All known OS versions and their nodes */
public Map<OsVersion, List<NodeVersion>> versions() {
return versions;
}
/** Returns nodes eligible for OS upgrades that exist in given cloud */
public List<NodeVersion> nodesIn(CloudName cloud) {
return versions.entrySet().stream()
.filter(entry -> entry.getKey().cloud().equals(cloud))
.map(Map.Entry::getValue)
.findFirst()
.orElseGet(List::of);
}
/** Returns versions that exist in given cloud */
public Set<Version> versionsIn(CloudName cloud) {
return versions.keySet().stream()
.filter(osVersion -> osVersion.cloud().equals(cloud))
.map(OsVersion::version)
.collect(Collectors.toUnmodifiableSet());
}
/** Compute the current OS versions in this system. This is expensive and should be called infrequently */
public static OsVersionStatus compute(Controller controller) {
Map<OsVersion, List<NodeVersion>> osVersions = new HashMap<>();
controller.osVersionTargets().forEach(target -> osVersions.put(target.osVersion(), new ArrayList<>()));
for (var application : SystemApplication.all()) {
for (var zone : zonesToUpgrade(controller)) {
if (!application.shouldUpgradeOs()) continue;
Version targetOsVersion = controller.serviceRegistry().configServer().nodeRepository()
.targetVersionsOf(zone.getVirtualId())
.osVersion(application.nodeType())
.orElse(Version.emptyVersion);
for (var node : controller.serviceRegistry().configServer().nodeRepository().list(zone.getVirtualId(), NodeFilter.all().applications(application.id()))) {
if (!OsUpgrader.canUpgrade(node)) continue;
Optional<Instant> suspendedAt = node.suspendedSince();
NodeVersion nodeVersion = new NodeVersion(node.hostname(), zone.getVirtualId(), node.currentOsVersion(),
targetOsVersion, suspendedAt);
OsVersion osVersion = new OsVersion(nodeVersion.currentVersion(), zone.getCloudName());
osVersions.computeIfAbsent(osVersion, (k) -> new ArrayList<>())
.add(nodeVersion);
}
}
}
return new OsVersionStatus(osVersions);
}
private static List<ZoneApi> zonesToUpgrade(Controller controller) {
return controller.zoneRegistry().osUpgradePolicies().stream()
.flatMap(upgradePolicy -> upgradePolicy.asList().stream())
.flatMap(Collection::stream)
.collect(Collectors.toUnmodifiableList());
}
}
|
92351f06c705cbadeaa596c52d6713554c37b87f | 2,749 | java | Java | jetty-core/src/test/java/com/hazelcast/session/TestServlet.java | hazelcast/hazelcast-jetty-sessionmanager | 9f7abb3794ab33af437d2cbe1760831dab975630 | [
"Apache-2.0"
] | 7 | 2016-12-08T10:59:46.000Z | 2020-11-24T01:36:50.000Z | jetty-core/src/test/java/com/hazelcast/session/TestServlet.java | hazelcast/hazelcast-jetty-sessionmanager | 9f7abb3794ab33af437d2cbe1760831dab975630 | [
"Apache-2.0"
] | 12 | 2016-07-21T12:33:38.000Z | 2021-01-26T06:06:16.000Z | jetty-core/src/test/java/com/hazelcast/session/TestServlet.java | hazelcast/hazelcast-jetty-sessionmanager | 9f7abb3794ab33af437d2cbe1760831dab975630 | [
"Apache-2.0"
] | 12 | 2016-06-02T07:15:25.000Z | 2020-08-20T09:40:30.000Z | 41.029851 | 113 | 0.625682 | 997,168 | /*
* Copyright (c) 2008-2013, Hazelcast, Inc. All Rights Reserved.
*/
package com.hazelcast.session;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
public class TestServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
HttpSession session = req.getSession();
if (req.getRequestURI().endsWith("write")) {
session.setAttribute("key", "value");
resp.getWriter().write("true");
} else if (req.getRequestURI().endsWith("read")) {
Object value = session.getAttribute("key");
resp.getWriter().write(value == null ? "null" : value.toString());
} else if (req.getRequestURI().endsWith("remove")) {
session.removeAttribute("key");
resp.getWriter().write("true");
} else if (req.getRequestURI().endsWith("invalidate")) {
session.invalidate();
resp.getWriter().write("true");
} else if (req.getRequestURI().endsWith("update")) {
session.setAttribute("key", "value-updated");
resp.getWriter().write("true");
} else if (req.getRequestURI().endsWith("names")) {
List names = Collections.list(session.getAttributeNames());
String nameList = names.toString();
//return comma separated list of attribute names
resp.getWriter().write(nameList.substring(1, nameList.length() - 1).replace(", ", ","));
} else if (req.getRequestURI().endsWith("reload")) {
session.invalidate();
session = req.getSession();
session.setAttribute("first-key", "first-value");
session.setAttribute("second-key", "second-value");
resp.getWriter().write("true");
} else if (req.getRequestURI().endsWith("isNew")) {
resp.getWriter().write(session.isNew() ? "true" : "false");
} else if (req.getRequestURI().endsWith("lastAccessTime")) {
resp.getWriter().write(String.valueOf(session.getLastAccessedTime()));
} else if (req.getRequestURI().endsWith("putnonserializable")) {
session.setAttribute("key", new Object());
session.setAttribute("key-2", "value");
resp.getWriter().write("true");
} else if (req.getRequestURI().endsWith("verifynonserializable")) {
resp.getWriter().write((String) session.getAttribute("key-2"));
}
}
}
|
92351f2080dd469de8fd9327ab654d3fafeeffd7 | 4,657 | java | Java | cellbase-core/src/main/java/org/opencb/cellbase/core/variant/annotation/ConsequenceTypeCNVGainCalculator.java | marrobi/cellbase | 70cc3d6ecff747725ade9d051438fc6bf98cae44 | [
"Apache-2.0"
] | null | null | null | cellbase-core/src/main/java/org/opencb/cellbase/core/variant/annotation/ConsequenceTypeCNVGainCalculator.java | marrobi/cellbase | 70cc3d6ecff747725ade9d051438fc6bf98cae44 | [
"Apache-2.0"
] | 1 | 2019-06-14T08:35:10.000Z | 2019-06-14T08:35:10.000Z | cellbase-core/src/main/java/org/opencb/cellbase/core/variant/annotation/ConsequenceTypeCNVGainCalculator.java | marrobi/cellbase | 70cc3d6ecff747725ade9d051438fc6bf98cae44 | [
"Apache-2.0"
] | 1 | 2020-01-23T06:52:17.000Z | 2020-01-23T06:52:17.000Z | 56.108434 | 136 | 0.627443 | 997,169 | package org.opencb.cellbase.core.variant.annotation;
import org.opencb.biodata.models.core.Gene;
import org.opencb.biodata.models.core.Transcript;
import org.opencb.biodata.models.variant.Variant;
import org.opencb.biodata.models.variant.avro.ConsequenceType;
import org.opencb.commons.datastore.core.QueryOptions;
import java.util.ArrayList;
import java.util.List;
/**
* Created by fjlopez on 31/05/16.
*/
public class ConsequenceTypeCNVGainCalculator extends ConsequenceTypeGenericRegionCalculator {
public ConsequenceTypeCNVGainCalculator() { }
public List<ConsequenceType> run(Variant inputVariant, List<Gene> geneList, boolean[] overlapsRegulatoryRegion,
QueryOptions queryOptions) {
parseQueryParam(queryOptions);
List<ConsequenceType> consequenceTypeList = new ArrayList<>();
variant = inputVariant;
variantEnd = getEnd(cnvExtraPadding);
variantStart = getStart(cnvExtraPadding);
// isBigDeletion = ((variantEnd - variantStart) > BIG_VARIANT_SIZE_THRESHOLD);
boolean isIntergenic = true;
for (Gene currentGene : geneList) {
gene = currentGene;
for (Transcript currentTranscript : gene.getTranscripts()) {
isIntergenic = isIntergenic && (variantEnd < currentTranscript.getStart() || variantStart > currentTranscript.getEnd());
transcript = currentTranscript;
consequenceType = new ConsequenceType();
consequenceType.setGeneName(gene.getName());
consequenceType.setEnsemblGeneId(gene.getId());
consequenceType.setEnsemblTranscriptId(transcript.getId());
consequenceType.setStrand(transcript.getStrand());
consequenceType.setBiotype(transcript.getBiotype());
consequenceType.setTranscriptAnnotationFlags(transcript.getAnnotationFlags() != null
? new ArrayList<>(transcript.getAnnotationFlags()) : null);
SoNames.clear();
if (transcript.getStrand().equals("+")) {
// whole transcript affected
if (variantStart <= transcript.getStart() && variantEnd >= transcript.getEnd()) {
SoNames.add(VariantAnnotationUtils.TRANSCRIPT_AMPLIFICATION);
consequenceType.setSequenceOntologyTerms(getSequenceOntologyTerms(SoNames));
consequenceTypeList.add(consequenceType);
} else if (regionsOverlap(transcript.getStart(), transcript.getEnd(), variantStart, variantEnd)) {
solvePositiveTranscript(consequenceTypeList);
} else {
solveTranscriptFlankingRegions(VariantAnnotationUtils.UPSTREAM_GENE_VARIANT,
VariantAnnotationUtils.DOWNSTREAM_GENE_VARIANT);
if (SoNames.size() > 0) { // Variant does not overlap gene region, just may have upstream/downstream annotations
consequenceType.setSequenceOntologyTerms(getSequenceOntologyTerms(SoNames));
consequenceTypeList.add(consequenceType);
}
}
} else {
if (variantStart <= transcript.getStart() && variantEnd >= transcript.getEnd()) { // whole trans. affected
SoNames.add(VariantAnnotationUtils.TRANSCRIPT_AMPLIFICATION);
consequenceType.setSequenceOntologyTerms(getSequenceOntologyTerms(SoNames));
consequenceTypeList.add(consequenceType);
} else if (regionsOverlap(transcript.getStart(), transcript.getEnd(), variantStart, variantEnd)) {
solveNegativeTranscript(consequenceTypeList);
} else {
solveTranscriptFlankingRegions(VariantAnnotationUtils.DOWNSTREAM_GENE_VARIANT,
VariantAnnotationUtils.UPSTREAM_GENE_VARIANT);
if (SoNames.size() > 0) { // Variant does not overlap gene region, just has upstream/downstream annotations
consequenceType.setSequenceOntologyTerms(getSequenceOntologyTerms(SoNames));
consequenceTypeList.add(consequenceType);
}
}
}
}
}
solveIntergenic(consequenceTypeList, isIntergenic);
solveRegulatoryRegions(overlapsRegulatoryRegion, consequenceTypeList);
return consequenceTypeList;
}
}
|
92352024429eb8e01bb2367d6805657ccd46a388 | 14,340 | java | Java | src/test/java/com/intland/codebeamer/api/client/rest/RestAdapterImplTest.java | intlandsupport/codebeamer-api-client | 972ca74c65f72bf60b3bfb0e572109a4f325180c | [
"MIT"
] | 1 | 2021-08-30T15:41:09.000Z | 2021-08-30T15:41:09.000Z | src/test/java/com/intland/codebeamer/api/client/rest/RestAdapterImplTest.java | intland/codebeamer-api-client | 972ca74c65f72bf60b3bfb0e572109a4f325180c | [
"MIT"
] | null | null | null | src/test/java/com/intland/codebeamer/api/client/rest/RestAdapterImplTest.java | intland/codebeamer-api-client | 972ca74c65f72bf60b3bfb0e572109a4f325180c | [
"MIT"
] | null | null | null | 46.710098 | 167 | 0.684798 | 997,170 | package com.intland.codebeamer.api.client.rest;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.when;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.List;
import org.apache.commons.codec.Charsets;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.intland.codebeamer.api.client.CodebeamerApiConfiguration;
import com.intland.codebeamer.api.client.Version;
import com.intland.codebeamer.api.client.dto.TrackerDto;
import com.intland.codebeamer.api.client.dto.TrackerItemDto;
import com.intland.codebeamer.api.client.dto.TrackerTypeDto;
public class RestAdapterImplTest {
private HttpClient clientMock;
private HttpResponse responseMock;
private StatusLine statusLineMock;
private ObjectMapper objectMapper = new ObjectMapper();
@BeforeMethod
public void setupMocks() {
clientMock = mock(HttpClient.class);
responseMock = mock(HttpResponse.class);
statusLineMock = mock(StatusLine.class);
CodebeamerApiConfiguration.getInstance()
.withUri("http://localhost:8080/cb")
.withUsername("bond")
.withPassword("007")
.withTestConfigurationId(10)
.withTestCaseTrackerId(20)
.withReleaseId(30)
.withTestRunTrackerId(40);
}
@Test(dataProvider = "trackerItemProvider")
public void testGetTrackerItem(int statusCode, String uri, Integer expectedItemId, Class<RequestFailed> exceptionClass) throws Exception {
TrackerItemDto expectedItemDto = new TrackerItemDto();
expectedItemDto.setUri(uri);
HttpEntity entity = new StringEntity(objectMapper.writeValueAsString(expectedItemDto));
when(statusLineMock.getStatusCode()).thenReturn(statusCode);
when(responseMock.getStatusLine()).thenReturn(statusLineMock);
when(responseMock.getEntity()).thenReturn(entity);
when(clientMock.execute(Mockito.any(HttpGet.class))).thenReturn(responseMock);
RestAdapter rest = new RestAdapterImpl(clientMock);
try {
TrackerItemDto actual = rest.getTrackerItem(1);
Assert.assertEquals(actual.getId(), expectedItemId, "id must match");
} catch (RequestFailed ex) {
checkException(ex, exceptionClass, statusCode);
}
}
@DataProvider(name = "trackerItemProvider")
public Object[][] trackerItemProvider() {
return new Object[][]{
{HttpStatus.SC_OK, "/item/1", 1, null},
{HttpStatus.SC_UNAUTHORIZED, "/item/1", 1, InvalidCredentialsException.class},
{HttpStatus.SC_NOT_FOUND, "/item/1", 1, ItemNotFoundException.class},
};
}
@Test(dataProvider = "trackerProvider")
public void testGetTracker(int statusCode, String content, Integer trackerTypeId, String trackerTypeName, Class<RequestFailed> exceptionClass) throws Exception {
HttpEntity entity = new StringEntity(content);
when(statusLineMock.getStatusCode()).thenReturn(statusCode);
when(responseMock.getStatusLine()).thenReturn(statusLineMock);
when(responseMock.getEntity()).thenReturn(entity);
when(clientMock.execute(Mockito.any(HttpGet.class))).thenReturn(responseMock);
RestAdapter rest = new RestAdapterImpl(clientMock);
try {
TrackerDto actual = rest.getTracker(1);
Assert.assertEquals(actual.getType().getTypeId(), trackerTypeId, "tracker type id");
Assert.assertEquals(actual.getType().getName(), trackerTypeName, "tracker type name");
} catch (RequestFailed ex) {
checkException(ex, exceptionClass, statusCode);
}
}
@DataProvider(name = "trackerProvider")
public Object[][] trackerProvider() {
return new Object[][]{
{HttpStatus.SC_OK, "{\"type\":{\"uri\":\"/category/type/1\", \"name\":\"Dummy Name\"}}", 1, "Dummy Name", null},
{HttpStatus.SC_UNAUTHORIZED, "{\"type\":{\"uri\":\"/category/type/1\", \"name\":\"Dummy Name\"}}", 1, "Dummy Name", InvalidCredentialsException.class},
{HttpStatus.SC_NOT_FOUND, "{\"type\":{\"uri\":\"/category/type/1\", \"name\":\"Dummy Name\"}}", 1, "Dummy Name", ItemNotFoundException.class},
};
}
@Test(dataProvider = "trackerTypeProvider")
public void testGetTrackerType(int statusCode, String uri, String name, Integer expectedId, Class<RequestFailed> exceptionClass) throws Exception {
TrackerTypeDto expectedTypeDto = new TrackerTypeDto();
expectedTypeDto.setUri(uri);
expectedTypeDto.setName(name);
HttpEntity entity = new StringEntity(objectMapper.writeValueAsString(expectedTypeDto));
TrackerDto tracker = new TrackerDto();
tracker.setType(expectedTypeDto);
when(statusLineMock.getStatusCode()).thenReturn(statusCode);
when(responseMock.getStatusLine()).thenReturn(statusLineMock);
when(responseMock.getEntity()).thenReturn(entity);
when(clientMock.execute(Mockito.any(HttpGet.class))).thenReturn(responseMock);
RestAdapter rest = new RestAdapterImpl(clientMock);
try {
TrackerTypeDto actual = rest.getTrackerType(expectedId);
Assert.assertEquals(actual.getTypeId(), expectedId, "tracker type id");
Assert.assertEquals(actual.getName(), name, "tracker type name");
} catch (RequestFailed ex) {
checkException(ex, exceptionClass, statusCode);
}
}
@DataProvider(name = "trackerTypeProvider")
public Object[][] trackerTypeProvider() {
return new Object[][]{
{HttpStatus.SC_OK, "/tracker/type/1", "Dummy Name", 1, null},
{HttpStatus.SC_UNAUTHORIZED, "/tracker/type/1", "Dummy Name", 1, InvalidCredentialsException.class},
{HttpStatus.SC_NOT_FOUND, "/tracker/type/1", "Dummy Name", 1, ItemNotFoundException.class},
};
}
private void checkException(Exception actual, Class<RequestFailed> expected, int statusCode) throws Exception {
Assert.assertEquals(actual.getClass().getSimpleName(), expected.getSimpleName(), "Statuscode " + statusCode);
}
@Test
public void testGetVersion_withCorrectEndpoint_withCorrectCredentials() throws Exception {
HttpClient client = mock(HttpClient.class);
HttpResponse response = mock(HttpResponse.class);
HttpEntity entity = new StringEntity("\"8.3.0\"");
StatusLine statusLine = mock(StatusLine.class);
when(statusLine.getStatusCode()).thenReturn(200);
when(response.getStatusLine()).thenReturn(statusLine);
when(response.getEntity()).thenReturn(entity);
when(client.execute(Mockito.any(HttpGet.class))).thenReturn(response);
RestAdapter rest = new RestAdapterImpl(client);
Assert.assertTrue(rest.getVersion() instanceof Version);
}
@Test(expectedExceptions = {RequestFailed.class, ConnectionFailedException.class})
public void testGetVersion_withIncorrectEndpoint_shouldThrowException() throws Exception {
HttpClient client = mock(HttpClient.class);
when(client.execute(Mockito.any(HttpGet.class))).thenThrow(new IOException("simulated timeout"));
RestAdapter rest = new RestAdapterImpl(client);
rest.getVersion();
}
@Test(expectedExceptions = {RequestFailed.class, InvalidCredentialsException.class})
public void testGetVersion_withCorrectEndpoint_WithIncorrectCredentials() throws Exception {
HttpClient client = mock(HttpClient.class);
HttpResponse response = mock(HttpResponse.class);
StatusLine statusLine = mock(StatusLine.class);
when(statusLine.getStatusCode()).thenReturn(HttpStatus.SC_UNAUTHORIZED);
when(response.getStatusLine()).thenReturn(statusLine);
when(client.execute(Mockito.any(HttpGet.class))).thenReturn(response);
RestAdapter rest = new RestAdapterImpl(client);
rest.getVersion();
}
@Test(dataProvider = "testConnectionProvider")
public void testTestConnection(boolean expected) throws Exception {
if (expected) {
when(statusLineMock.getStatusCode()).thenReturn(HttpStatus.SC_OK);
when(responseMock.getStatusLine()).thenReturn(statusLineMock);
when(responseMock.getEntity()).thenReturn(new StringEntity(""));
when(clientMock.execute(Mockito.any(HttpGet.class))).thenReturn(responseMock);
} else {
when(clientMock.execute(Mockito.any(HttpGet.class))).thenThrow(new IOException("simulated timeout"));
}
RestAdapter rest = new RestAdapterImpl(clientMock);
Assert.assertEquals(rest.testConnection(), expected, "test connection");
}
@DataProvider(name = "testConnectionProvider")
private Object[][] testConnectionProvider() {
return new Object[][]{
{true},
{false},
};
}
@Test(dataProvider = "testCredentialsProvider")
public void testTestCredentials(int statusCode, boolean expected) throws Exception {
when(statusLineMock.getStatusCode()).thenReturn(statusCode);
when(responseMock.getStatusLine()).thenReturn(statusLineMock);
when(responseMock.getEntity()).thenReturn(new StringEntity("\"8.3.0\""));
when(clientMock.execute(Mockito.any(HttpGet.class))).thenReturn(responseMock);
RestAdapter rest = new RestAdapterImpl(clientMock);
Assert.assertEquals(rest.testCredentials(), expected, "test credentials");
}
@DataProvider(name = "testCredentialsProvider")
private Object[][] testCredentialsProvider() {
return new Object[][]{
{HttpStatus.SC_OK, true},
{HttpStatus.SC_UNAUTHORIZED, false},
{HttpStatus.SC_NOT_FOUND, false},
};
}
@Test(dataProvider = "fileListProvider")
public void testUploadXUnitResults(File[] files, int statusCode, int numberOfRequest) throws Exception {
ArgumentCaptor<HttpPost> requestCaptor = ArgumentCaptor.forClass(HttpPost.class);
when(statusLineMock.getStatusCode()).thenReturn(statusCode);
when(responseMock.getStatusLine()).thenReturn(statusLineMock);
when(clientMock.execute(Mockito.any(HttpPost.class))).thenReturn(responseMock);
RestAdapter rest = new RestAdapterImpl(clientMock);
// check whether successful
if (statusCode >= 200 && statusCode < 300) {
rest.uploadXUnitResults(files);
Assert.assertTrue(true, "upload was successful");
} else {
try {
rest.uploadXUnitResults(files);
Assert.assertFalse(true, "upload was successful");
} catch (RequestFailed ex) {
// swallow
}
}
// check number of requests
Mockito.verify(clientMock, times(numberOfRequest)).execute(Mockito.any(HttpPost.class));
// check content of request
Mockito.verify(clientMock, times(numberOfRequest)).execute(requestCaptor.capture());
List<HttpPost> posts = requestCaptor.getAllValues();
for (HttpPost post : posts) {
checkUploadedEntity(post.getEntity(), files);
checkConfigurationIsIncluded(post.getEntity());
}
}
@DataProvider(name = "fileListProvider")
private Object[][] fileListProvider() {
File one = new File(ClassLoader.getSystemResource("test_results/AclRemotingTests.xml").getFile());
File two = new File(ClassLoader.getSystemResource("test_results/ArtifactRemotingTests.xml").getFile());
File three = new File(ClassLoader.getSystemResource("test_results/GeneralRemotingTests.xml").getFile());
return new Object[][]{
{new File[]{one}, HttpStatus.SC_CREATED, 1},
{new File[]{one}, HttpStatus.SC_UNAUTHORIZED, 1},
{new File[]{one, two, three}, HttpStatus.SC_CREATED, 1},
{new File[]{one, two, three}, HttpStatus.SC_UNAUTHORIZED, 1},
};
}
private void checkUploadedEntity(HttpEntity entity, File[] files) throws Exception {
String body = IOUtils.toString(entity.getContent(), Charsets.UTF_8);
long totalFileSize = 0;
for (File file : files) {
String fileContent = new String(Files.readAllBytes(file.toPath()));
totalFileSize += file.length();
Assert.assertTrue(body.contains(fileContent), String.format("body contains content of %s", file.getName()));
}
Assert.assertTrue(totalFileSize < entity.getContentLength(), "entity length is greater than combined file size");
}
private void checkConfigurationIsIncluded(HttpEntity entity) throws Exception {
String body = IOUtils.toString(entity.getContent(), Charsets.UTF_8);
CodebeamerApiConfiguration config = CodebeamerApiConfiguration.getInstance();
Assert.assertTrue(body.contains(String.format("\"testConfigurationId\":%s", config.getTestConfigurationId())), "testConfigurationId is included");
Assert.assertTrue(body.contains(String.format("\"testCaseId\":%s", config.getTestCaseId())), "testCaseId is included");
Assert.assertTrue(body.contains(String.format("\"releaseId\":%s", config.getReleaseId())), "releaseId is included");
Assert.assertTrue(body.contains(String.format("\"testCaseTrackerId\":%s", config.getTestCaseTrackerId())), "testCaseTrackerId is included");
Assert.assertTrue(body.contains(String.format("\"testRunTrackerId\":%s", config.getTestRunTrackerId())), "testRunTrackerId is included");
}
}
|
9235226b4255526c42cbe07e84d88ed239a2ebdc | 5,614 | java | Java | src/main/java/work/lclpnet/corebase/util/ObjectHelper.java | LCLPYT/CoreBase | 62aacdb632a5f66695951606246805e83398c71e | [
"MIT"
] | null | null | null | src/main/java/work/lclpnet/corebase/util/ObjectHelper.java | LCLPYT/CoreBase | 62aacdb632a5f66695951606246805e83398c71e | [
"MIT"
] | 1 | 2021-01-21T14:31:59.000Z | 2021-01-21T14:31:59.000Z | src/main/java/work/lclpnet/corebase/util/ObjectHelper.java | LCLPYT/CoreBase | 62aacdb632a5f66695951606246805e83398c71e | [
"MIT"
] | null | null | null | 37.932432 | 150 | 0.643035 | 997,171 | package work.lclpnet.corebase.util;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Objects;
public class ObjectHelper {
/**
* Returns the value of a field from the specified object.
* The only difference to {@link #getThrowing(Object, String)} is that this method returns null instead of throwing an exception.
*
* @param <T> The type of the object to return.
* @param obj The object whose field should be returned.
* @param fieldName The name of the field to modify.
* @return The value of the field (can be null). Also returns null if there was an error.
*/
@Nullable
public static <T> T get(@Nonnull Object obj, @Nonnull String fieldName) {
Objects.requireNonNull(obj);
Objects.requireNonNull(fieldName);
try {
return getThrowing(obj, fieldName);
} catch (ReflectiveOperationException e) {
e.printStackTrace();
return null;
}
}
/**
* Returns the value of a field from the specified object.
* The only difference to {@link #get(Object, String)} is that this method throws an exception instead of just returning null.
*
* @param obj The object whose field should be returned.
* @param fieldName The name of the field to modify.
* @return The value of the field (can be null).
* @throws ReflectiveOperationException If an error occurs.
*/
@Nullable
@SuppressWarnings("unchecked")
public static <T> T getThrowing(@Nonnull Object obj, @Nonnull String fieldName) throws ReflectiveOperationException {
Objects.requireNonNull(obj);
Objects.requireNonNull(fieldName);
Field field = getField(obj, fieldName);
if (field == null) throw new NoSuchFieldError(fieldName);
boolean accessible = field.isAccessible();
if (!accessible) field.setAccessible(true);
T value = (T) field.get(obj);
if (!accessible) field.setAccessible(false);
return value;
}
/**
* Sets the value of a field from the specified object.
* The only difference to {@link #setThrowing(Object, String, Object)} is that this method returns true or false instead of throwing an exception.
*
* @param obj The object whose field should be modified.
* @param fieldName The name of the field to modify.
* @param value The value to set the field to.
* @return true, if the value was set successfully. False on error.
*/
public static boolean set(@Nonnull Object obj, @Nonnull String fieldName, @Nullable Object value) {
Objects.requireNonNull(obj);
Objects.requireNonNull(fieldName);
try {
setThrowing(obj, fieldName, value);
return true;
} catch (ReflectiveOperationException e) {
e.printStackTrace();
return false;
}
}
/**
* Sets the value of a field from the specified object.
* The only difference to {@link #set(Object, String, Object)} is that this method throws an exception instead of returning true or false.
*
* @param obj The object whose field should be modified.
* @param fieldName The name of the field to modify.
* @param value The value to set the field to.
* @throws ReflectiveOperationException If there was an error modifying the field.
*/
public static void setThrowing(@Nonnull Object obj, @Nonnull String fieldName, @Nullable Object value) throws ReflectiveOperationException {
Objects.requireNonNull(obj);
Objects.requireNonNull(fieldName);
Field field = getField(obj, fieldName);
if (field == null) throw new NoSuchFieldError(fieldName);
boolean accessible = field.isAccessible();
if (!accessible) field.setAccessible(true);
field.set(obj, value);
if (!accessible) field.setAccessible(false);
}
/**
* Gets a field with given name recursively.
* Normally a declared field from a super class is not found when trying to get it.
* This method recursively loops through the super classes of the objects and tries to find it.
*
* @param obj The object whose field should be returned.
* @param fieldName The name of the field.
* @return The field of the object. If not found it will return null.
* @see Field
*/
@Nullable
public static Field getField(@Nonnull Object obj, @Nonnull String fieldName) {
Field field = null;
try {
field = obj.getClass().getDeclaredField(fieldName);
} catch (NoSuchFieldException e) {
try {
Class<?> superClass = obj.getClass();
while (!(superClass = superClass.getSuperclass()).equals(Object.class))
field = superClass.getDeclaredField(fieldName);
} catch (NoSuchFieldException ex) {
}
}
return field;
}
public static Method getCurrentMethod(Class<?>... parameterTypes) {
final StackTraceElement[] ste = Thread.currentThread().getStackTrace();
if (ste.length < 3) return null;
StackTraceElement current = ste[2];
try {
Class<?> cl = Class.forName(current.getClassName());
return cl.getDeclaredMethod(current.getMethodName(), parameterTypes);
} catch (ReflectiveOperationException e) {
e.printStackTrace();
return null;
}
}
}
|
923522cb626d54555d911300a8e770222f9a9156 | 2,464 | java | Java | PopcornTime_Android-src/torrent/torrent/src/main/java/com/frostwire/jlibtorrent/swig/request_dropped_alert.java | officialrafsan/POPCORNtime | b5bc452b10d7b46c2f4978e37d7fd2e9c0f75782 | [
"MIT"
] | 1 | 2015-07-11T18:16:22.000Z | 2015-07-11T18:16:22.000Z | src/main/java/com/frostwire/jlibtorrent/swig/request_dropped_alert.java | Teg79/Wave | 78142bf58252d9bb59aa80be8791bd51d666c324 | [
"MIT"
] | null | null | null | src/main/java/com/frostwire/jlibtorrent/swig/request_dropped_alert.java | Teg79/Wave | 78142bf58252d9bb59aa80be8791bd51d666c324 | [
"MIT"
] | null | null | null | 32 | 176 | 0.697646 | 997,172 | /* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 3.0.2
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package com.frostwire.jlibtorrent.swig;
public class request_dropped_alert extends peer_alert {
private long swigCPtr;
protected request_dropped_alert(long cPtr, boolean cMemoryOwn) {
super(libtorrent_jni.request_dropped_alert_SWIGUpcast(cPtr), cMemoryOwn);
swigCPtr = cPtr;
}
protected static long getCPtr(request_dropped_alert obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
protected void finalize() {
delete();
}
public synchronized void delete() {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
libtorrent_jni.delete_request_dropped_alert(swigCPtr);
}
swigCPtr = 0;
}
super.delete();
}
public request_dropped_alert(torrent_handle h, tcp_endpoint ep, sha1_hash peer_id, int block_num, int piece_num) {
this(libtorrent_jni.new_request_dropped_alert(torrent_handle.getCPtr(h), h, tcp_endpoint.getCPtr(ep), ep, sha1_hash.getCPtr(peer_id), peer_id, block_num, piece_num), true);
}
public int type() {
return libtorrent_jni.request_dropped_alert_type(swigCPtr, this);
}
public int category() {
return libtorrent_jni.request_dropped_alert_category(swigCPtr, this);
}
public String what() {
return libtorrent_jni.request_dropped_alert_what(swigCPtr, this);
}
public String message() {
return libtorrent_jni.request_dropped_alert_message(swigCPtr, this);
}
public void setBlock_index(int value) {
libtorrent_jni.request_dropped_alert_block_index_set(swigCPtr, this, value);
}
public int getBlock_index() {
return libtorrent_jni.request_dropped_alert_block_index_get(swigCPtr, this);
}
public void setPiece_index(int value) {
libtorrent_jni.request_dropped_alert_piece_index_set(swigCPtr, this, value);
}
public int getPiece_index() {
return libtorrent_jni.request_dropped_alert_piece_index_get(swigCPtr, this);
}
public final static int alert_type = libtorrent_jni.request_dropped_alert_alert_type_get();
public final static int static_category = libtorrent_jni.request_dropped_alert_static_category_get();
}
|
9235230ae1725ff0d4857ab9e00f2e951f5852a8 | 1,459 | java | Java | mirs-framework-rabbitmq/src/main/java/com/github/mirs/banxiaoxiao/framework/rabbitmq/p2p/adapter/OldP2PClient.java | git-jinlong/mirs-framework | 6bb197718926ec99144d41cc43b90cc5b3d3157e | [
"Apache-2.0"
] | 1 | 2021-07-23T08:28:32.000Z | 2021-07-23T08:28:32.000Z | mirs-framework-rabbitmq/src/main/java/com/github/mirs/banxiaoxiao/framework/rabbitmq/p2p/adapter/OldP2PClient.java | git-jinlong/mirs-framework | 6bb197718926ec99144d41cc43b90cc5b3d3157e | [
"Apache-2.0"
] | null | null | null | mirs-framework-rabbitmq/src/main/java/com/github/mirs/banxiaoxiao/framework/rabbitmq/p2p/adapter/OldP2PClient.java | git-jinlong/mirs-framework | 6bb197718926ec99144d41cc43b90cc5b3d3157e | [
"Apache-2.0"
] | null | null | null | 29.77551 | 106 | 0.702536 | 997,173 | package com.github.mirs.banxiaoxiao.framework.rabbitmq.p2p.adapter;
import com.github.mirs.banxiaoxiao.framework.rabbitmq.EventErrorCode;
import com.github.mirs.banxiaoxiao.framework.rabbitmq.mq.RmqChannel;
import com.github.mirs.banxiaoxiao.framework.rabbitmq.mq.p2p.P2PClient;
import com.github.mirs.banxiaoxiao.framework.rabbitmq.p2p.P2PMsgPublisher;
import com.github.mirs.banxiaoxiao.framework.rabbitmq.p2p.P2PRouter;
/**
* @author zcy 2019年7月19日
*/
public class OldP2PClient extends P2PClient {
private P2PMsgPublisher publisher;
private P2PRouter router;
private String eventName;
public OldP2PClient(RmqChannel connection, String eventName, P2PMsgPublisher publisher, String host) {
super(connection, eventName, host);
this.publisher = publisher;
this.eventName = eventName;
this.router = new SingleClientRouter(host);
}
public int publish(Object event) {
// 临时修复下
String routeKey = this.eventName + "_" + router.choose(event);
publisher.send(event, routeKey, null);
return EventErrorCode.SUCCEED;
}
static class SingleClientRouter implements P2PRouter {
private String targetClient;
public SingleClientRouter(String targetClient) {
super();
this.targetClient = targetClient;
}
@Override
public String choose(Object obj) {
return targetClient;
}
}
}
|
9235231aa32054a4361fd770489987779c206e0a | 1,566 | java | Java | src/main/java/io/github/ma1uta/matrix/gene/model/encryption/QueryResponse.java | ma1uta/gene | 3507be1de0b5f591c9a6f0e3f065a33a51291013 | [
"Apache-2.0"
] | 2 | 2018-07-21T09:51:51.000Z | 2019-03-13T15:07:26.000Z | src/main/java/io/github/ma1uta/matrix/gene/model/encryption/QueryResponse.java | ma1uta/gene | 3507be1de0b5f591c9a6f0e3f065a33a51291013 | [
"Apache-2.0"
] | null | null | null | src/main/java/io/github/ma1uta/matrix/gene/model/encryption/QueryResponse.java | ma1uta/gene | 3507be1de0b5f591c9a6f0e3f065a33a51291013 | [
"Apache-2.0"
] | null | null | null | 35.681818 | 129 | 0.72293 | 997,174 | /*
* Copyright anpch@example.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 io.github.ma1uta.matrix.gene.model.encryption;
import com.google.gson.annotations.SerializedName;
import java.util.Map;
/**
* Response format.
*/
public class QueryResponse {
/**
* If any remote homeservers could not be reached, they are recorded here. The names of the properties are the names of
* the unreachable servers.
* <br>
* If the homeserver could be reached, but the user or device was unknown, no failure is recorded. Instead, the corresponding
* user or device is missing from the device_keys result.
*/
public Map<String, Object> failures;
/**
* Information on the queried devices. A map from user ID, to a map from device ID to device information. For each device,
* the information returned will be the same as uploaded via /keys/upload, with the addition of an unsigned property.
*/
@SerializedName("device_keys")
public Map<String, Map<String, DeviceKeys>> deviceKeys;
}
|
923523a49bcfb4d0d233e9fd3966529d698abae6 | 648 | java | Java | fhdp/fhdp-commons/fhdp-commons-fh-lite/src/main/java/pl/fhframework/dp/commons/fh/formatters/ArrayStringFormatter.java | lukasz2029/fh | 9f2740bedaa31ee6090b176c95eb9b82a55103f6 | [
"Apache-2.0"
] | null | null | null | fhdp/fhdp-commons/fhdp-commons-fh-lite/src/main/java/pl/fhframework/dp/commons/fh/formatters/ArrayStringFormatter.java | lukasz2029/fh | 9f2740bedaa31ee6090b176c95eb9b82a55103f6 | [
"Apache-2.0"
] | null | null | null | fhdp/fhdp-commons/fhdp-commons-fh-lite/src/main/java/pl/fhframework/dp/commons/fh/formatters/ArrayStringFormatter.java | lukasz2029/fh | 9f2740bedaa31ee6090b176c95eb9b82a55103f6 | [
"Apache-2.0"
] | 1 | 2022-03-01T09:01:46.000Z | 2022-03-01T09:01:46.000Z | 27 | 82 | 0.743827 | 997,175 | package pl.fhframework.dp.commons.fh.formatters;
import org.springframework.format.Formatter;
import pl.fhframework.format.FhFormatter;
import java.text.ParseException;
import java.util.List;
import java.util.Locale;
import java.util.stream.Collectors;
@FhFormatter("arrayStringFormatter")
public class ArrayStringFormatter implements Formatter<List<String>> {
@Override
public List<String> parse(String s, Locale locale) throws ParseException {
return null;
}
@Override
public String print(List<String> s, Locale locale) {
return s.stream().map(String::valueOf).collect(Collectors.joining(", "));
}
}
|
923523a4f896c26e999f2396a64404ba54d76db6 | 2,166 | java | Java | dbus-heartbeat/src/main/java/com/creditease/dbus/heartbeat/sinker/SinkerMonitorNode.java | jasonTangxd/DBus | bfcb992fcfeac41c0376be98f927b472844f920f | [
"Apache-2.0"
] | 1,232 | 2017-09-04T11:23:08.000Z | 2022-03-25T07:01:07.000Z | dbus-heartbeat/src/main/java/com/creditease/dbus/heartbeat/sinker/SinkerMonitorNode.java | vrtch/DBus | 81dfda57dc7f6f137092edef1e834d32abb38a56 | [
"Apache-2.0"
] | 72 | 2017-10-11T04:43:17.000Z | 2022-03-01T04:48:22.000Z | dbus-heartbeat/src/main/java/com/creditease/dbus/heartbeat/sinker/SinkerMonitorNode.java | vrtch/DBus | 81dfda57dc7f6f137092edef1e834d32abb38a56 | [
"Apache-2.0"
] | 551 | 2017-09-05T06:55:14.000Z | 2022-03-19T07:24:56.000Z | 23.042553 | 75 | 0.649584 | 997,176 | /*-
* <<
* DBus
* ==
* Copyright (C) 2016 - 2019 Bridata
* ==
* 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.creditease.dbus.heartbeat.sinker;
public class SinkerMonitorNode {
//报警次数
private int alarmCount;
//超时次数
private int timeoutCnt;
//上次报警时间
private long lastAlarmTime;
//sinker心跳延时时间
private int latencyMS;
//该节点心跳延时更新时间
private long updateTime;
//实际延时时间
private long realLatencyMS;
public SinkerMonitorNode() {
this.alarmCount = 0;
this.timeoutCnt = 0;
this.lastAlarmTime = 0;
this.latencyMS = 0;
}
public int getAlarmCount() {
return alarmCount;
}
public void setAlarmCount(int alarmCount) {
this.alarmCount = alarmCount;
}
public int getTimeoutCnt() {
return timeoutCnt;
}
public void setTimeoutCnt(int timeoutCnt) {
this.timeoutCnt = timeoutCnt;
}
public long getLastAlarmTime() {
return lastAlarmTime;
}
public void setLastAlarmTime(long lastAlarmTime) {
this.lastAlarmTime = lastAlarmTime;
}
public int getLatencyMS() {
return latencyMS;
}
public boolean isRunning() {
return updateTime != 0;
}
public long getUpdateTime() {
return updateTime;
}
public void setLatencyMS(int latencyMS) {
this.latencyMS = latencyMS;
this.updateTime = System.currentTimeMillis();
}
public long getRealLatencyMS() {
return realLatencyMS;
}
public void setRealLatencyMS(long realLatencyMS) {
this.realLatencyMS = realLatencyMS;
}
}
|
923524259da6025b74cd96ffd504d99345920abf | 1,730 | java | Java | sfs-server/src/main/java/org/sfs/validate/ValidateDynamicLargeObjectHasParts.java | pitchpoint-solutions/sfs | d62387f494b369c819e03e5dc9e97b39a9fc85b0 | [
"Apache-2.0"
] | 91 | 2016-10-04T02:51:57.000Z | 2022-03-11T08:01:16.000Z | sfs-server/src/main/java/org/sfs/validate/ValidateDynamicLargeObjectHasParts.java | pitchpoint-solutions/sfs | d62387f494b369c819e03e5dc9e97b39a9fc85b0 | [
"Apache-2.0"
] | 2 | 2017-05-21T09:46:08.000Z | 2021-07-02T18:41:14.000Z | sfs-server/src/main/java/org/sfs/validate/ValidateDynamicLargeObjectHasParts.java | pitchpoint-solutions/sfs | d62387f494b369c819e03e5dc9e97b39a9fc85b0 | [
"Apache-2.0"
] | 13 | 2017-01-24T02:10:12.000Z | 2022-03-11T08:01:21.000Z | 36.808511 | 185 | 0.748555 | 997,177 | /*
* Copyright 2016 The Simple File Server Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.sfs.validate;
import io.vertx.core.json.JsonObject;
import org.sfs.util.HttpRequestValidationException;
import org.sfs.vo.TransientVersion;
import rx.functions.Func1;
import static com.google.common.collect.Iterables.isEmpty;
import static java.lang.String.format;
import static java.net.HttpURLConnection.HTTP_NOT_FOUND;
public class ValidateDynamicLargeObjectHasParts implements Func1<Iterable<TransientVersion>, Void> {
private final TransientVersion objectManifestVersion;
public ValidateDynamicLargeObjectHasParts(TransientVersion objectManifestVersion) {
this.objectManifestVersion = objectManifestVersion;
}
@Override
public Void call(Iterable<TransientVersion> parts) {
if (isEmpty(parts)) {
JsonObject jsonObject = new JsonObject()
.put("message", format("Version %d has object manifest %s but no parts were found", objectManifestVersion.getId(), objectManifestVersion.getObjectManifest().get()));
throw new HttpRequestValidationException(HTTP_NOT_FOUND, jsonObject);
}
return null;
}
} |
923524828153cab29445837a258f4ea2b56e2134 | 2,296 | java | Java | addressbook_web_tests/src/test/java/com/course_java_for_testers/addressbook/tests/ContactDeletionTests.java | nikonov1996/cours_java_for_testers | ae16badf29abafd6f1663318f1a23a21c05b7d91 | [
"Apache-2.0"
] | 1 | 2019-09-19T08:30:08.000Z | 2019-09-19T08:30:08.000Z | addressbook_web_tests/src/test/java/com/course_java_for_testers/addressbook/tests/ContactDeletionTests.java | nikonov1996/cours_java_for_testers | ae16badf29abafd6f1663318f1a23a21c05b7d91 | [
"Apache-2.0"
] | null | null | null | addressbook_web_tests/src/test/java/com/course_java_for_testers/addressbook/tests/ContactDeletionTests.java | nikonov1996/cours_java_for_testers | ae16badf29abafd6f1663318f1a23a21c05b7d91 | [
"Apache-2.0"
] | null | null | null | 41.745455 | 107 | 0.626307 | 997,178 | package com.course_java_for_testers.addressbook.tests;
import com.course_java_for_testers.addressbook.model.ContactList;
import com.course_java_for_testers.addressbook.model.NewContactData;
import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.util.HashSet;
import java.util.List;
import java.util.NoSuchElementException;
public class ContactDeletionTests extends TestBase {
public void ensurePreconditions (){
app.getNavigationHelper().gotoHomePage();
if (!app.getContactHelper().isContactPresent()){
app.getContactHelper().gotoCreateNewContact();
app.getContactHelper().createContact(new NewContactData()
.withFirstname("testname")
.withLastname("testlastname")
.withNickname("testnickname")
.withTitle("testtitle")
.withAddress("testaddress")
.withCompany("testcompany")
.withHomePhone("54872")
.withMobilePhone("89135876592")
.withEmail("test@test")
.withGroup("test1"),
true);// указываем, что это создание "контакта"
app.getNavigationHelper().gotoHomePage();}
}
@Test(enabled = true)
public void testContactDeletion() {
ensurePreconditions();
ContactList contactListBefore = app.getContactHelper().getContactList();
NewContactData deletedContact = contactListBefore.get(contactListBefore.size()-1);
app.getContactHelper().deleteContact(contactListBefore);
Assert.assertEquals(
app.getContactHelper().getContactCount(),
contactListBefore.size()-1,
"После удаления кол-во контактов должно быть меньше на единицу");
ContactList contactListAfter = app.getContactHelper().getContactList();
Assert.assertEquals(
new HashSet<>(contactListAfter),
new HashSet<>(contactListBefore.without(deletedContact)),
"Элементы списка контактов (кроме удаляемого) не должны изменятся после удаления группы.");
}
}
|
923524fe9c837d765adf95139d0762abd2922e9b | 5,841 | java | Java | netreflected/src/net5.0/windowsbase_version_5.0.10.0_culture_neutral_publickeytoken_31bf3856ad364e35/system/componentmodel/IEditableCollectionView.java | mariomastrodicasa/JCOReflector | a88b6de9d3cc607fd375ab61df8c61f44de88c93 | [
"MIT"
] | 35 | 2020-08-30T03:19:42.000Z | 2022-03-12T09:22:23.000Z | netreflected/src/net5.0/windowsbase_version_5.0.10.0_culture_neutral_publickeytoken_31bf3856ad364e35/system/componentmodel/IEditableCollectionView.java | mariomastrodicasa/JCOReflector | a88b6de9d3cc607fd375ab61df8c61f44de88c93 | [
"MIT"
] | 50 | 2020-06-22T17:03:18.000Z | 2022-03-30T21:19:05.000Z | netreflected/src/net5.0/windowsbase_version_5.0.10.0_culture_neutral_publickeytoken_31bf3856ad364e35/system/componentmodel/IEditableCollectionView.java | mariomastrodicasa/JCOReflector | a88b6de9d3cc607fd375ab61df8c61f44de88c93 | [
"MIT"
] | 12 | 2020-08-30T03:19:45.000Z | 2022-03-05T02:22:37.000Z | 37.442308 | 215 | 0.7069 | 997,179 | /*
* MIT License
*
* Copyright (c) 2021 MASES s.r.l.
*
* 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.
*/
/**************************************************************************************
* <auto-generated>
* This code was generated from a template using JCOReflector
*
* Manual changes to this file may cause unexpected behavior in your application.
* Manual changes to this file will be overwritten if the code is regenerated.
* </auto-generated>
*************************************************************************************/
package system.componentmodel;
import org.mases.jcobridge.*;
import org.mases.jcobridge.netreflection.*;
// Import section
import system.componentmodel.NewItemPlaceholderPosition;
/**
* The base .NET class managing System.ComponentModel.IEditableCollectionView, WindowsBase, Version=5.0.10.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35.
* <p>
*
* See: <a href="https://docs.microsoft.com/en-us/dotnet/api/System.ComponentModel.IEditableCollectionView" target="_top">https://docs.microsoft.com/en-us/dotnet/api/System.ComponentModel.IEditableCollectionView</a>
*/
public interface IEditableCollectionView extends IJCOBridgeReflected {
/**
* Fully assembly qualified name: WindowsBase, Version=5.0.10.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35
*/
public static final String assemblyFullName = "WindowsBase, Version=5.0.10.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";
/**
* Assembly name: WindowsBase
*/
public static final String assemblyShortName = "WindowsBase";
/**
* Qualified class name: System.ComponentModel.IEditableCollectionView
*/
public static final String className = "System.ComponentModel.IEditableCollectionView";
/**
* Try to cast the {@link IJCOBridgeReflected} instance into {@link IEditableCollectionView}, a cast assert is made to check if types are compatible.
* @param from {@link IJCOBridgeReflected} instance to be casted
* @return {@link IEditableCollectionView} instance
* @throws java.lang.Throwable in case of error during cast operation
*/
public static IEditableCollectionView ToIEditableCollectionView(IJCOBridgeReflected from) throws Throwable {
JCOBridge bridge = JCOBridgeInstance.getInstance("WindowsBase, Version=5.0.10.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35");
JCType classType = bridge.GetType(className + ", " + (JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName));
NetType.AssertCast(classType, from);
return new IEditableCollectionViewImplementation(from.getJCOInstance());
}
/**
* Returns the reflected Assembly name
*
* @return A {@link String} representing the Fullname of reflected Assembly
*/
public String getJCOAssemblyName();
/**
* Returns the reflected Class name
*
* @return A {@link String} representing the Fullname of reflected Class
*/
public String getJCOClassName();
/**
* Returns the reflected Class name used to build the object
*
* @return A {@link String} representing the name used to allocated the object
* in CLR context
*/
public String getJCOObjectName();
/**
* Returns the instantiated class
*
* @return An {@link java.lang.Object} representing the instance of the instantiated Class
*/
public java.lang.Object getJCOInstance();
/**
* Returns the instantiated class Type
*
* @return A {@link JCType} representing the Type of the instantiated Class
*/
public JCType getJCOType();
// Methods section
public NetObject AddNew() throws Throwable;
public void CancelEdit() throws Throwable;
public void CancelNew() throws Throwable;
public void CommitEdit() throws Throwable;
public void CommitNew() throws Throwable;
public void EditItem(NetObject item) throws Throwable;
public void Remove(NetObject item) throws Throwable;
public void RemoveAt(int index) throws Throwable;
// Properties section
public boolean getCanAddNew() throws Throwable;
public boolean getCanCancelEdit() throws Throwable;
public boolean getCanRemove() throws Throwable;
public boolean getIsAddingNew() throws Throwable;
public boolean getIsEditingItem() throws Throwable;
public NewItemPlaceholderPosition getNewItemPlaceholderPosition() throws Throwable;
public void setNewItemPlaceholderPosition(NewItemPlaceholderPosition NewItemPlaceholderPosition) throws Throwable;
public NetObject getCurrentAddItem() throws Throwable;
public NetObject getCurrentEditItem() throws Throwable;
// Instance Events section
} |
923525b6832db9b5c9f5e0d862ffc4f3c1ec2f38 | 4,179 | java | Java | src/main/java/com/supervisor/sdk/time/SimplePeriodicity.java | my-supervisor/my-supervisor | ba6ecc4a3373cd439586a72a8e9fc035b09a3f2b | [
"CC-BY-3.0"
] | 3 | 2022-01-31T20:40:22.000Z | 2022-02-11T04:15:44.000Z | src/main/java/com/supervisor/sdk/time/SimplePeriodicity.java | my-supervisor/my-supervisor | ba6ecc4a3373cd439586a72a8e9fc035b09a3f2b | [
"CC-BY-3.0"
] | 33 | 2022-01-31T20:40:16.000Z | 2022-02-21T01:57:51.000Z | src/main/java/com/supervisor/sdk/time/SimplePeriodicity.java | my-supervisor/my-supervisor | ba6ecc4a3373cd439586a72a8e9fc035b09a3f2b | [
"CC-BY-3.0"
] | null | null | null | 24.875 | 129 | 0.675281 | 997,180 | package com.supervisor.sdk.time;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
public final class SimplePeriodicity implements Periodicity {
final int number;
final PeriodicityUnit unit;
final LocalDate reference;
final boolean closeInterval;
public SimplePeriodicity(final int number, final PeriodicityUnit unit, final LocalDate reference, final boolean closeInterval) {
if(number <= 0)
throw new IllegalArgumentException("Vous devez saisir un entier supérieur à 0 !");
this.number = number;
this.unit = unit;
this.reference = reference;
this.closeInterval = closeInterval;
}
@Override
public int number() {
return number;
}
@Override
public PeriodicityUnit unit() {
return unit;
}
@Override
public LocalDate begin(LocalDate today) {
LocalDate date;
switch (unit) {
case DAILY:
if(number == 1)
date = today;
else {
Long days = ChronoUnit.DAYS.between(reference, today);
Long rest = days % number;
date = today.plusDays(rest);
}
break;
case WEEKLY:
date = today.with(reference.getDayOfWeek());
break;
case MONTHLY:
LocalDate referenceOfYear = LocalDate.of(today.getYear(), reference.getMonthValue(), reference.getDayOfMonth());
int numberSigned = number;
boolean isUpper = referenceOfYear.isAfter(today);
if(closeInterval)
isUpper = isUpper || referenceOfYear.isEqual(today);
if(isUpper)
numberSigned = -number;
boolean belongToPeriod = false;
LocalDate referenceOfToday = referenceOfYear;
do {
referenceOfToday = referenceOfToday.plusMonths(numberSigned);
if(numberSigned < 0) {
belongToPeriod = referenceOfToday.isBefore(today);
}
else
{
belongToPeriod = referenceOfToday.isAfter(today);
if(closeInterval)
belongToPeriod = belongToPeriod || referenceOfToday.isEqual(today);
if(belongToPeriod)
referenceOfToday = referenceOfToday.minusMonths(numberSigned);
}
}while(!belongToPeriod);
date = referenceOfToday;
break;
case YEARLY:
LocalDate referenceOfYearY = LocalDate.of(today.getYear(), reference.getMonthValue(), reference.getDayOfMonth());
int numberSignedY = number;
boolean isUpperY = referenceOfYearY.isAfter(today);
if(closeInterval)
isUpperY = isUpperY || referenceOfYearY.isEqual(today);
if(isUpperY)
numberSignedY = -number;
boolean belongToPeriodY = false;
LocalDate referenceOfTodayY = referenceOfYearY;
do {
referenceOfTodayY = referenceOfTodayY.plusYears(numberSignedY);
if(numberSignedY < 0)
belongToPeriodY = referenceOfTodayY.isBefore(today);
else {
belongToPeriodY = referenceOfTodayY.isAfter(today);
if(closeInterval)
belongToPeriodY = belongToPeriodY || referenceOfTodayY.isEqual(today);
if(belongToPeriodY)
referenceOfTodayY = referenceOfTodayY.minusYears(numberSignedY);
}
}while(!belongToPeriodY);
date = referenceOfTodayY;
break;
case FOREVER:
date = LocalDate.of(1970, 01, 01);
break;
default:
throw new IllegalArgumentException("Date de début de période : vous devez définir une unité de période !");
}
return date;
}
@Override
public LocalDate end(LocalDate today) {
LocalDate date;
LocalDate begin = begin(today);
switch (unit) {
case DAILY:
date = begin.plusDays(number).minusDays(1);
break;
case WEEKLY:
date = begin.plusDays(7L * number).minusDays(1);
break;
case MONTHLY:
date = begin.plusMonths(number).minusDays(1);
break;
case YEARLY:
date = begin.plusYears(number).minusDays(1);
break;
case FOREVER:
date = today;
break;
default:
throw new IllegalArgumentException("Date de fin de période : vous devez définir une unité de période !");
}
if(closeInterval)
date = date.plusDays(1);
return date;
}
@Override
public LocalDate reference() {
return reference;
}
@Override
public boolean closeInterval() {
return closeInterval;
}
}
|
923525eff0da80aa73d1c4a847c22a7072916a42 | 3,582 | java | Java | src/main/java/org/rumbledb/runtime/arithmetics/UnaryOperationIterator.java | alexandrumeterez/rumble | e76db97776361ab6bbd150957161c057d93245b1 | [
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"MIT",
"ECL-2.0",
"BSD-3-Clause"
] | 140 | 2019-06-03T15:23:40.000Z | 2022-03-13T14:55:08.000Z | src/main/java/org/rumbledb/runtime/arithmetics/UnaryOperationIterator.java | alexandrumeterez/rumble | e76db97776361ab6bbd150957161c057d93245b1 | [
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"MIT",
"ECL-2.0",
"BSD-3-Clause"
] | 382 | 2019-05-31T12:54:10.000Z | 2022-03-16T12:49:48.000Z | src/main/java/org/rumbledb/runtime/arithmetics/UnaryOperationIterator.java | alexandrumeterez/rumble | e76db97776361ab6bbd150957161c057d93245b1 | [
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"MIT",
"ECL-2.0",
"BSD-3-Clause"
] | 61 | 2019-08-23T14:47:40.000Z | 2022-03-14T21:09:47.000Z | 36.55102 | 97 | 0.671692 | 997,181 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Authors: Stefan Irimescu, Can Berker Cikis
*
*/
package org.rumbledb.runtime.arithmetics;
import org.rumbledb.api.Item;
import org.rumbledb.context.DynamicContext;
import org.rumbledb.exceptions.ExceptionMetadata;
import org.rumbledb.exceptions.MoreThanOneItemException;
import org.rumbledb.exceptions.UnexpectedTypeException;
import org.rumbledb.expressions.ExecutionMode;
import org.rumbledb.items.ItemFactory;
import org.rumbledb.runtime.AtMostOneItemLocalRuntimeIterator;
import org.rumbledb.runtime.RuntimeIterator;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Collections;
public class UnaryOperationIterator extends AtMostOneItemLocalRuntimeIterator {
private boolean negated;
private final RuntimeIterator child;
private Item item;
private static final long serialVersionUID = 1L;
public UnaryOperationIterator(
RuntimeIterator child,
boolean negated,
ExecutionMode executionMode,
ExceptionMetadata iteratorMetadata
) {
super(Collections.singletonList(child), executionMode, iteratorMetadata);
this.child = child;
this.negated = negated;
this.item = null;
}
@Override
public Item materializeFirstItemOrNull(DynamicContext dynamicContext) {
try {
this.item = this.child.materializeAtMostOneItemOrNull(dynamicContext);
} catch (MoreThanOneItemException e) {
throw new UnexpectedTypeException(
"Unary expression requires at most one item in its input sequence.",
getMetadata()
);
}
if (this.item == null) {
return null;
}
if (!this.negated) {
return this.item;
}
if (this.item.isInt()) {
return ItemFactory.getInstance().createIntItem(-1 * this.item.getIntValue());
}
if (this.item.isInteger()) {
return ItemFactory.getInstance()
.createIntegerItem(BigInteger.valueOf(-1).multiply(this.item.getIntegerValue()));
}
if (this.item.isFloat()) {
return ItemFactory.getInstance().createFloatItem(-1 * this.item.getFloatValue());
}
if (this.item.isDouble()) {
return ItemFactory.getInstance().createDoubleItem(-1 * this.item.getDoubleValue());
}
if (this.item.isDecimal()) {
return ItemFactory.getInstance()
.createDecimalItem(this.item.getDecimalValue().multiply(new BigDecimal(-1)));
}
throw new UnexpectedTypeException(
"Unary expression has non numeric args "
+
this.item.serialize(),
getMetadata()
);
}
}
|
923528628f41c92310aac3a0e837e2bd70406161 | 873 | java | Java | src/elias/julian/klozilla/objects/sponge/SpongeMovement.java | my-first-projects/klozilla | aefa8611f13d00d814fff4f8623f83183aeb5be7 | [
"MIT"
] | null | null | null | src/elias/julian/klozilla/objects/sponge/SpongeMovement.java | my-first-projects/klozilla | aefa8611f13d00d814fff4f8623f83183aeb5be7 | [
"MIT"
] | null | null | null | src/elias/julian/klozilla/objects/sponge/SpongeMovement.java | my-first-projects/klozilla | aefa8611f13d00d814fff4f8623f83183aeb5be7 | [
"MIT"
] | null | null | null | 20.302326 | 86 | 0.623139 | 997,182 | package elias.julian.klozilla.objects.sponge;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
import elias.julian.klozilla.gamehandler.GameState;
import elias.julian.klozilla.main.Var;
public class SpongeMovement {
private Timer movement;
private Random rnd;
public SpongeMovement() {
rnd = new Random();
movement = new Timer();
// Var.resetGame();
movement.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
if (Var.gameState == GameState.GAME) {
// If(level =1
Var.spongeY += Var.spongeSpeed;
if (Var.spongeY >= Var.screenHeight + 110) {// ----------------------------------
// startet neu oben
if (Var.spongeY >= Var.shitDistance) {
Var.spongeY = -10000 - rnd.nextInt(3000);
Var.spongeX = rnd.nextInt(600);
}
}
}
}
}, 0, 10);
}
} |
92352885a075570bac0455f0d616614448d75a1b | 512 | java | Java | week4/day1/code/LoginMvp/app/src/main/java/se/paap/loginmvp/MainActivity.java | PatrikAppelqvist/Android-C3L | 632d7e3fc5c330216a565e9884d4a1bdc3a7c1f9 | [
"MIT"
] | null | null | null | week4/day1/code/LoginMvp/app/src/main/java/se/paap/loginmvp/MainActivity.java | PatrikAppelqvist/Android-C3L | 632d7e3fc5c330216a565e9884d4a1bdc3a7c1f9 | [
"MIT"
] | null | null | null | week4/day1/code/LoginMvp/app/src/main/java/se/paap/loginmvp/MainActivity.java | PatrikAppelqvist/Android-C3L | 632d7e3fc5c330216a565e9884d4a1bdc3a7c1f9 | [
"MIT"
] | null | null | null | 25.6 | 56 | 0.751953 | 997,183 | package se.paap.loginmvp;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
public static Intent createIntent(Context context) {
return new Intent(context, MainActivity.class);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
|
923529713f89e7309cc7adade8c171fe4e8c4385 | 3,807 | java | Java | htb/fatty-10.10.10.174/fatty-client/org/springframework/web/jsf/DecoratingNavigationHandler.java | benhunter/ctf | 3de1a222ea0034ef15eb6b75585b03a6ee37ec37 | [
"MIT"
] | null | null | null | htb/fatty-10.10.10.174/fatty-client/org/springframework/web/jsf/DecoratingNavigationHandler.java | benhunter/ctf | 3de1a222ea0034ef15eb6b75585b03a6ee37ec37 | [
"MIT"
] | 1 | 2022-03-31T22:44:36.000Z | 2022-03-31T22:44:36.000Z | htb/fatty-10.10.10.174/fatty-client/org/springframework/web/jsf/DecoratingNavigationHandler.java | benhunter/ctf | 3de1a222ea0034ef15eb6b75585b03a6ee37ec37 | [
"MIT"
] | null | null | null | 23.5 | 196 | 0.452062 | 997,184 | /* */ package org.springframework.web.jsf;
/* */
/* */ import javax.faces.application.NavigationHandler;
/* */ import javax.faces.context.FacesContext;
/* */ import org.springframework.lang.Nullable;
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ public abstract class DecoratingNavigationHandler
/* */ extends NavigationHandler
/* */ {
/* */ @Nullable
/* */ private NavigationHandler decoratedNavigationHandler;
/* */
/* */ protected DecoratingNavigationHandler() {}
/* */
/* */ protected DecoratingNavigationHandler(NavigationHandler originalNavigationHandler) {
/* 57 */ this.decoratedNavigationHandler = originalNavigationHandler;
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */ @Nullable
/* */ public final NavigationHandler getDecoratedNavigationHandler() {
/* 66 */ return this.decoratedNavigationHandler;
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ public final void handleNavigation(FacesContext facesContext, String fromAction, String outcome) {
/* 78 */ handleNavigation(facesContext, fromAction, outcome, this.decoratedNavigationHandler);
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ public abstract void handleNavigation(FacesContext paramFacesContext, @Nullable String paramString1, @Nullable String paramString2, @Nullable NavigationHandler paramNavigationHandler);
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ protected final void callNextHandlerInChain(FacesContext facesContext, @Nullable String fromAction, @Nullable String outcome, @Nullable NavigationHandler originalNavigationHandler) {
/* 136 */ NavigationHandler decoratedNavigationHandler = getDecoratedNavigationHandler();
/* */
/* 138 */ if (decoratedNavigationHandler instanceof DecoratingNavigationHandler) {
/* */
/* */
/* 141 */ DecoratingNavigationHandler decHandler = (DecoratingNavigationHandler)decoratedNavigationHandler;
/* 142 */ decHandler.handleNavigation(facesContext, fromAction, outcome, originalNavigationHandler);
/* */ }
/* 144 */ else if (decoratedNavigationHandler != null) {
/* */
/* */
/* */
/* 148 */ decoratedNavigationHandler.handleNavigation(facesContext, fromAction, outcome);
/* */ }
/* 150 */ else if (originalNavigationHandler != null) {
/* */
/* */
/* 153 */ originalNavigationHandler.handleNavigation(facesContext, fromAction, outcome);
/* */ }
/* */ }
/* */ }
/* Location: /home/kali/ctf/htb/fatty-10.10.10.174/ftp/fatty-client.jar!/org/springframework/web/jsf/DecoratingNavigationHandler.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 1.1.3
*/ |
92352a978d9feb750f5f5c592c3ea4c65138bc3f | 9,256 | java | Java | src/main/java/configtools/tbconfig/entity/TbConfigEntity.java | JackietLiu/cgmlsh | 216954e054dcfcaf429b734b5f52554a2b7ba4ea | [
"Apache-2.0"
] | null | null | null | src/main/java/configtools/tbconfig/entity/TbConfigEntity.java | JackietLiu/cgmlsh | 216954e054dcfcaf429b734b5f52554a2b7ba4ea | [
"Apache-2.0"
] | 10 | 2020-03-04T22:20:02.000Z | 2022-02-01T00:58:42.000Z | src/main/java/configtools/tbconfig/entity/TbConfigEntity.java | JackietLiu/cgmlsh | 216954e054dcfcaf429b734b5f52554a2b7ba4ea | [
"Apache-2.0"
] | null | null | null | 21.830189 | 140 | 0.688959 | 997,185 | package configtools.tbconfig.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
import org.jeecgframework.poi.excel.annotation.Excel;
/**
* @Title: Entity
* @Description: 系统配置信息
* @author onlineGenerator
* @date 2017-12-28 14:01:45
* @version V1.0
*
*/
@Entity
@Table(name = "tb_config", schema = "")
@SuppressWarnings("serial")
public class TbConfigEntity implements java.io.Serializable {
/**id*/
private java.lang.String id;
/**代码*/
@Excel(name="代码",width=15)
private java.lang.String code;
/**配置名称*/
@Excel(name="配置名称",width=15)
private java.lang.String confname;
/**配置描述*/
@Excel(name="配置描述",width=15)
private java.lang.String confdescribe;
/**默认值*/
@Excel(name="默认值",width=15)
private java.lang.String defaultvalue;
/**备注*/
@Excel(name="备注",width=15)
private java.lang.String memo;
/**管理级别*/
@Excel(name="管理级别",width=15,dictTable ="tb_config where groupflag='Config_Priority' and isactive='1'",dicCode ="code",dicText ="confname")
private java.lang.String managerlevel;
/**分组代码*/
@Excel(name="分组代码",width=15)
private java.lang.String groupflag;
/**分组名称*/
@Excel(name="分组名称",width=15)
private java.lang.String groupflagname;
/**类别*/
@Excel(name="类别",width=15)
private java.lang.String category;
/**值类别*/
@Excel(name="值类别",width=15,dicCode="valuetype")
private java.lang.String valuetype;
/**值范围*/
@Excel(name="值范围",width=15)
private java.lang.String valuescope;
/**是否在用*/
@Excel(name="是否在用",width=15,dicCode="isactive")
private java.lang.Integer isactive;
/**停止日期*/
@Excel(name="停止日期",width=15,format = "yyyy-MM-dd")
private java.util.Date stopdate;
/**排序*/
@Excel(name="排序",width=15)
private java.lang.Integer sortindex;
/**是否同步本地*/
@Excel(name="是否同步本地",width=15,dicCode="sf_yn")
private java.lang.String issynclocal;
/**更新人名称*/
private java.lang.String updateName;
/**更新日期*/
private java.util.Date updateDate;
/**创建日期*/
private java.util.Date createDate;
/**创建人名称*/
private java.lang.String createName;
/**
*方法: 取得java.lang.String
*@return: java.lang.String id
*/
@Id
@GeneratedValue(generator = "paymentableGenerator")
@GenericGenerator(name = "paymentableGenerator", strategy = "uuid")
@Column(name ="ID",nullable=false,length=36)
public java.lang.String getId(){
return this.id;
}
/**
*方法: 设置java.lang.String
*@param: java.lang.String id
*/
public void setId(java.lang.String id){
this.id = id;
}
/**
*方法: 取得java.lang.String
*@return: java.lang.String 代码
*/
@Column(name ="CODE",nullable=true,length=50)
public java.lang.String getCode(){
return this.code;
}
/**
*方法: 设置java.lang.String
*@param: java.lang.String 代码
*/
public void setCode(java.lang.String code){
this.code = code;
}
/**
*方法: 取得java.lang.String
*@return: java.lang.String 配置名称
*/
@Column(name ="CONFNAME",nullable=true,length=50)
public java.lang.String getConfname(){
return this.confname;
}
/**
*方法: 设置java.lang.String
*@param: java.lang.String 配置名称
*/
public void setConfname(java.lang.String confname){
this.confname = confname;
}
/**
*方法: 取得java.lang.String
*@return: java.lang.String 配置描述
*/
@Column(name ="CONFDESCRIBE",nullable=true,length=500)
public java.lang.String getConfdescribe(){
return this.confdescribe;
}
/**
*方法: 设置java.lang.String
*@param: java.lang.String 配置描述
*/
public void setConfdescribe(java.lang.String confdescribe){
this.confdescribe = confdescribe;
}
/**
*方法: 取得java.lang.String
*@return: java.lang.String 默认值
*/
@Column(name ="DEFAULTVALUE",nullable=true,length=50)
public java.lang.String getDefaultvalue(){
return this.defaultvalue;
}
/**
*方法: 设置java.lang.String
*@param: java.lang.String 默认值
*/
public void setDefaultvalue(java.lang.String defaultvalue){
this.defaultvalue = defaultvalue;
}
/**
*方法: 取得java.lang.String
*@return: java.lang.String 备注
*/
@Column(name ="MEMO",nullable=true,length=50)
public java.lang.String getMemo(){
return this.memo;
}
/**
*方法: 设置java.lang.String
*@param: java.lang.String 备注
*/
public void setMemo(java.lang.String memo){
this.memo = memo;
}
/**
*方法: 取得java.lang.String
*@return: java.lang.String 管理级别
*/
@Column(name ="MANAGERLEVEL",nullable=true,length=50)
public java.lang.String getManagerlevel(){
return this.managerlevel;
}
/**
*方法: 设置java.lang.String
*@param: java.lang.String 管理级别
*/
public void setManagerlevel(java.lang.String managerlevel){
this.managerlevel = managerlevel;
}
/**
*方法: 取得java.lang.String
*@return: java.lang.String 分组代码
*/
@Column(name ="GROUPFLAG",nullable=true,length=50)
public java.lang.String getGroupflag(){
return this.groupflag;
}
/**
*方法: 设置java.lang.String
*@param: java.lang.String 分组代码
*/
public void setGroupflag(java.lang.String groupflag){
this.groupflag = groupflag;
}
/**
*方法: 取得java.lang.String
*@return: java.lang.String 分组名称
*/
@Column(name ="GROUPFLAGNAME",nullable=true,length=50)
public java.lang.String getGroupflagname(){
return this.groupflagname;
}
/**
*方法: 设置java.lang.String
*@param: java.lang.String 分组名称
*/
public void setGroupflagname(java.lang.String groupflagname){
this.groupflagname = groupflagname;
}
/**
*方法: 取得java.lang.String
*@return: java.lang.String 类别
*/
@Column(name ="CATEGORY",nullable=true,length=20)
public java.lang.String getCategory(){
return this.category;
}
/**
*方法: 设置java.lang.String
*@param: java.lang.String 类别
*/
public void setCategory(java.lang.String category){
this.category = category;
}
/**
*方法: 取得java.lang.String
*@return: java.lang.String 值类别
*/
@Column(name ="VALUETYPE",nullable=true,length=20)
public java.lang.String getValuetype(){
return this.valuetype;
}
/**
*方法: 设置java.lang.String
*@param: java.lang.String 值类别
*/
public void setValuetype(java.lang.String valuetype){
this.valuetype = valuetype;
}
/**
*方法: 取得java.lang.String
*@return: java.lang.String 值范围
*/
@Column(name ="VALUESCOPE",nullable=true,length=20)
public java.lang.String getValuescope(){
return this.valuescope;
}
/**
*方法: 设置java.lang.String
*@param: java.lang.String 值范围
*/
public void setValuescope(java.lang.String valuescope){
this.valuescope = valuescope;
}
/**
*方法: 取得java.lang.Integer
*@return: java.lang.Integer 是否在用
*/
@Column(name ="ISACTIVE",nullable=true,length=10)
public java.lang.Integer getIsactive(){
return this.isactive;
}
/**
*方法: 设置java.lang.Integer
*@param: java.lang.Integer 是否在用
*/
public void setIsactive(java.lang.Integer isactive){
this.isactive = isactive;
}
/**
*方法: 取得java.util.Date
*@return: java.util.Date 停止日期
*/
@Column(name ="STOPDATE",nullable=true)
public java.util.Date getStopdate(){
return this.stopdate;
}
/**
*方法: 设置java.util.Date
*@param: java.util.Date 停止日期
*/
public void setStopdate(java.util.Date stopdate){
this.stopdate = stopdate;
}
/**
*方法: 取得java.lang.Integer
*@return: java.lang.Integer 排序
*/
@Column(name ="SORTINDEX",nullable=true,length=10)
public java.lang.Integer getSortindex(){
return this.sortindex;
}
/**
*方法: 设置java.lang.Integer
*@param: java.lang.Integer 排序
*/
public void setSortindex(java.lang.Integer sortindex){
this.sortindex = sortindex;
}
/**
*方法: 取得java.lang.String
*@return: java.lang.String 是否同步本地
*/
@Column(name ="ISSYNCLOCAL",nullable=true,length=10)
public java.lang.String getIssynclocal(){
return this.issynclocal;
}
/**
*方法: 设置java.lang.String
*@param: java.lang.String 是否同步本地
*/
public void setIssynclocal(java.lang.String issynclocal){
this.issynclocal = issynclocal;
}
/**
*方法: 取得java.lang.String
*@return: java.lang.String 更新人名称
*/
@Column(name ="UPDATE_NAME",nullable=true,length=50)
public java.lang.String getUpdateName(){
return this.updateName;
}
/**
*方法: 设置java.lang.String
*@param: java.lang.String 更新人名称
*/
public void setUpdateName(java.lang.String updateName){
this.updateName = updateName;
}
/**
*方法: 取得java.util.Date
*@return: java.util.Date 更新日期
*/
@Column(name ="UPDATE_DATE",nullable=true)
public java.util.Date getUpdateDate(){
return this.updateDate;
}
/**
*方法: 设置java.util.Date
*@param: java.util.Date 更新日期
*/
public void setUpdateDate(java.util.Date updateDate){
this.updateDate = updateDate;
}
/**
*方法: 取得java.util.Date
*@return: java.util.Date 创建日期
*/
@Column(name ="CREATE_DATE",nullable=true)
public java.util.Date getCreateDate(){
return this.createDate;
}
/**
*方法: 设置java.util.Date
*@param: java.util.Date 创建日期
*/
public void setCreateDate(java.util.Date createDate){
this.createDate = createDate;
}
/**
*方法: 取得java.lang.String
*@return: java.lang.String 创建人名称
*/
@Column(name ="CREATE_NAME",nullable=true,length=50)
public java.lang.String getCreateName(){
return this.createName;
}
/**
*方法: 设置java.lang.String
*@param: java.lang.String 创建人名称
*/
public void setCreateName(java.lang.String createName){
this.createName = createName;
}
}
|
92352aab93923bc8ad351676e69ab66b4a180b83 | 1,678 | java | Java | UIConnectionFactory.java | mqadri/outsourcer | 1675cf2068b76c87d718dff6b6ce8dba38ef6f78 | [
"BSD-3-Clause"
] | null | null | null | UIConnectionFactory.java | mqadri/outsourcer | 1675cf2068b76c87d718dff6b6ce8dba38ef6f78 | [
"BSD-3-Clause"
] | null | null | null | UIConnectionFactory.java | mqadri/outsourcer | 1675cf2068b76c87d718dff6b6ce8dba38ef6f78 | [
"BSD-3-Clause"
] | null | null | null | 27.508197 | 98 | 0.727056 | 997,186 | import java.sql.*;
import org.postgresql.ds.*;
import java.io.IOException;
public class UIConnectionFactory
{
// example to use:
// Connection conn = UIConnectionFactory.getConnection();
private static PGPoolingDataSource ds;
private UIConnectionFactory()
{
}
public static synchronized PGPoolingDataSource getDataSource() throws SQLException
{
if (ds == null)
{
try
{
System.out.println("Creating new connection pool");
OSProperties.getPropValues(UI.configFile);
ds = new PGPoolingDataSource();
ds.setDataSourceName("OutsourcerUIPool");
ds.setServerName(OSProperties.gpServer);
ds.setDatabaseName(OSProperties.gpDatabase);
ds.setPortNumber(OSProperties.gpPort);
ds.setUser(OSProperties.gpUserName);
ds.setPassword(OSProperties.gpPassword);
ds.setMaxConnections(10);
}
catch (IOException iox)
{
System.out.println("Unable to load config file. Check environment variables and try again.");
throw new SQLException(iox.getMessage());
}
}
return ds;
}
public static Connection getConnection() throws SQLException
{
try
{
return getDataSource().getConnection();
}
catch (SQLException ex)
{
System.out.println(ex.getMessage());
System.out.println("gpServer from properties: " + OSProperties.gpServer);
System.out.println("gpDatabase from properties: " + OSProperties.gpDatabase);
System.out.println("gpPort from properties: " + OSProperties.gpPort);
System.out.println("gpUsername from properties: " + OSProperties.gpUserName);
System.out.println("gpPassword from properties: " + OSProperties.gpPassword);
throw new SQLException(ex.getMessage());
}
}
}
|
92352abc86a1ec3261b27439e490607882dbbce1 | 5,531 | java | Java | corpus/class/ecf/685.java | masud-technope/ACER-Replication-Package-ASE2017 | cb7318a729eb1403004d451a164c851af2d81f7a | [
"MIT"
] | null | null | null | corpus/class/ecf/685.java | masud-technope/ACER-Replication-Package-ASE2017 | cb7318a729eb1403004d451a164c851af2d81f7a | [
"MIT"
] | null | null | null | corpus/class/ecf/685.java | masud-technope/ACER-Replication-Package-ASE2017 | cb7318a729eb1403004d451a164c851af2d81f7a | [
"MIT"
] | null | null | null | 36.150327 | 135 | 0.636232 | 997,187 | /*******************************************************************************
* Copyright (c) 2004, 2007 Composent, Inc. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Composent, Inc. - initial API and implementation
******************************************************************************/
package org.eclipse.ecf.provider.generic;
import java.io.*;
import java.net.*;
import org.eclipse.ecf.core.util.Trace;
import org.eclipse.ecf.internal.provider.ECFProviderDebugOptions;
import org.eclipse.ecf.internal.provider.ProviderPlugin;
import org.eclipse.ecf.provider.comm.tcp.*;
public class TCPServerSOContainerGroup extends SOContainerGroup implements ISocketAcceptHandler {
//$NON-NLS-1$
public static final String INVALID_CONNECT = "Invalid connect request.";
public static final String DEFAULT_GROUP_NAME = TCPServerSOContainerGroup.class.getName();
private int port;
private Server listener;
private boolean isOnTheAir = false;
private final ThreadGroup threadGroup;
private int backlog = Server.DEFAULT_BACKLOG;
private InetAddress bindAddress;
/**
* @since 4.4
*/
public TCPServerSOContainerGroup(String name, ThreadGroup group, int port, int backlog, InetAddress bindAddress) {
super(name);
threadGroup = group;
this.port = port;
this.backlog = backlog;
this.bindAddress = bindAddress;
}
/**
* @since 4.4
*/
public TCPServerSOContainerGroup(String name, ThreadGroup group, int port, InetAddress bindAddress) {
this(name, group, port, Server.DEFAULT_BACKLOG, bindAddress);
}
public TCPServerSOContainerGroup(String name, ThreadGroup group, int port) {
this(name, group, port, Server.DEFAULT_BACKLOG, null);
}
public TCPServerSOContainerGroup(String name, int port) {
this(name, null, port);
}
public TCPServerSOContainerGroup(int port) {
this(DEFAULT_GROUP_NAME, port);
}
protected void trace(String msg) {
//$NON-NLS-1$
Trace.trace(ProviderPlugin.PLUGIN_ID, ECFProviderDebugOptions.DEBUG, "TRACING " + msg);
}
protected void traceStack(String msg, Throwable e) {
Trace.catching(ProviderPlugin.PLUGIN_ID, ECFProviderDebugOptions.EXCEPTIONS_CATCHING, TCPServerSOContainerGroup.class, msg, e);
}
public synchronized void putOnTheAir() throws IOException {
//$NON-NLS-1$ //$NON-NLS-2$
trace("TCPServerSOContainerGroup at port " + port + " on the air");
listener = new Server(threadGroup, port, backlog, bindAddress, this);
port = listener.getLocalPort();
isOnTheAir = true;
}
public synchronized boolean isOnTheAir() {
return isOnTheAir;
}
private void setSocketOptions(Socket aSocket) throws SocketException {
aSocket.setTcpNoDelay(true);
}
public void handleAccept(Socket aSocket) throws Exception {
// Set socket options
setSocketOptions(aSocket);
final ObjectOutputStream oStream = new ObjectOutputStream(aSocket.getOutputStream());
oStream.flush();
final ObjectInputStream iStream = new ObjectInputStream(aSocket.getInputStream());
final ConnectRequestMessage req = (ConnectRequestMessage) iStream.readObject();
if (req == null)
//$NON-NLS-1$
throw new InvalidObjectException(INVALID_CONNECT + " Connect request message cannot be null");
final URI uri = req.getTarget();
if (uri == null)
//$NON-NLS-1$
throw new InvalidObjectException(INVALID_CONNECT + " URI connect target cannot be null");
final String path = uri.getPath();
if (path == null)
//$NON-NLS-1$
throw new InvalidObjectException(INVALID_CONNECT + " Path cannot be null");
final TCPServerSOContainer srs = (TCPServerSOContainer) get(path);
if (srs == null)
//$NON-NLS-1$
throw new InvalidObjectException("Container not found for path=" + path);
// Create our local messaging interface
final Client newClient = new Client(aSocket, iStream, oStream, srs.getReceiver());
// Get output stream lock so nothing is sent until we've responded
Object outputStreamLock = newClient.getOutputStreamLock();
// connect request
synchronized (outputStreamLock) {
// Call checkConnect
final Serializable resp = srs.handleConnectRequest(aSocket, path, req.getData(), newClient);
// Create connect response wrapper and send it back
oStream.writeObject(new ConnectResultMessage(resp));
oStream.flush();
}
}
public synchronized void takeOffTheAir() {
if (listener != null) {
//$NON-NLS-1$ //$NON-NLS-2$
trace("Taking " + getName() + " off the air.");
try {
listener.close();
} catch (final IOException e) {
traceStack("Exception in closeListener", e);
}
listener = null;
}
isOnTheAir = false;
}
public int getPort() {
return port;
}
public String toString() {
//$NON-NLS-1$
return super.toString() + ";port:" + port;
}
}
|
92352b1d8463adb1ebe5b8952b7eca3535cac7ed | 1,218 | java | Java | ql/src/java/org/apache/hadoop/hive/ql/metadata/InvalidTableException.java | manbuyun/hive | cdb1052e24ca493c6486fef3dd8956dde61be834 | [
"Apache-2.0"
] | 4,140 | 2015-01-07T11:57:35.000Z | 2022-03-31T06:26:22.000Z | ql/src/java/org/apache/hadoop/hive/ql/metadata/InvalidTableException.java | manbuyun/hive | cdb1052e24ca493c6486fef3dd8956dde61be834 | [
"Apache-2.0"
] | 1,779 | 2015-05-27T04:32:42.000Z | 2022-03-31T18:53:19.000Z | ql/src/java/org/apache/hadoop/hive/ql/metadata/InvalidTableException.java | manbuyun/hive | cdb1052e24ca493c6486fef3dd8956dde61be834 | [
"Apache-2.0"
] | 3,958 | 2015-01-01T15:14:49.000Z | 2022-03-30T21:08:32.000Z | 30.45 | 75 | 0.747947 | 997,188 | /*
* 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.hadoop.hive.ql.metadata;
import org.apache.hadoop.hive.ql.ErrorMsg;
/**
* Generic exception class for Hive.
*/
public class InvalidTableException extends HiveException {
String tableName;
public InvalidTableException(String tableName) {
super(ErrorMsg.INVALID_TABLE, tableName);
this.tableName = tableName;
}
public String getTableName() {
return tableName;
}
}
|
92352b3df2e55c70f495e14b7685b7d88abefe12 | 3,199 | java | Java | app/src/main/java/com/devgmail/mitroshin/totutu/controllers/InfoFragment.java | DmitryMitroshin/ToTuTu | e1dde0c7cafff70344632bd42b98fad487134498 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/devgmail/mitroshin/totutu/controllers/InfoFragment.java | DmitryMitroshin/ToTuTu | e1dde0c7cafff70344632bd42b98fad487134498 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/devgmail/mitroshin/totutu/controllers/InfoFragment.java | DmitryMitroshin/ToTuTu | e1dde0c7cafff70344632bd42b98fad487134498 | [
"Apache-2.0"
] | null | null | null | 41.545455 | 91 | 0.737105 | 997,189 | package com.devgmail.mitroshin.totutu.controllers;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.devgmail.mitroshin.totutu.R;
import com.devgmail.mitroshin.totutu.hosts.InfoActivity;
import com.devgmail.mitroshin.totutu.model.Station;
//Контроллер для представления fragment_info.xml
public class InfoFragment extends Fragment {
private TextView mStationTitle;
private TextView mStationId;
private TextView mCityTitle;
private TextView mCityId;
private TextView mCountry;
private TextView mRegion;
private TextView mDistrict;
private TextView mStationLongitude;
private TextView mStationLatitude;
private TextView mCityLongitude;
private TextView mCityLatitude;
private Station mCurrentStation;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_info, container, false);
mStationTitle = (TextView) view.findViewById(R.id.info_text_station_title);
mStationId = (TextView) view.findViewById(R.id.info_text_station_id);
mCityTitle = (TextView) view.findViewById(R.id.info_text_city_title);
mCityId = (TextView) view.findViewById(R.id.info_text_city_id);
mCountry = (TextView) view.findViewById(R.id.info_text_country);
mRegion = (TextView) view.findViewById(R.id.info_text_region);
mDistrict = (TextView) view.findViewById(R.id.info_text_district);
mStationLongitude = (TextView) view.findViewById(R.id.info_text_longitude_station);
mStationLatitude = (TextView) view.findViewById(R.id.info_text_latitude_station);
mCityLongitude = (TextView) view.findViewById(R.id.info_text_longitude_city);
mCityLatitude = (TextView) view.findViewById(R.id.info_text_latitude_city);
return view;
}
@Override
public void onResume() {
super.onResume();
// Спасибо мне из прошлого, что сделал удобный способ для передачи объекта,
// а не через индекс и запрос в базу
mCurrentStation = getActivity().getIntent().getParcelableExtra(InfoActivity.
EXTRA_STATION_OBJECT_TO_INFO);
mStationTitle.setText(mCurrentStation.getStation());
mStationId.setText(mCurrentStation.getStationId().toString());
mCityTitle.setText(mCurrentStation.getCity());
mCityId.setText(mCurrentStation.getId().toString());
mCountry.setText(mCurrentStation.getCountry());
mRegion.setText(mCurrentStation.getRegion());
mDistrict.setText(mCurrentStation.getDistrict());
mStationLongitude.setText(mCurrentStation.getStationLongitude().toString());
mStationLatitude.setText(mCurrentStation.getStationLatitude().toString());
mCityLongitude.setText(mCurrentStation.getLongitude().toString());
mCityLatitude.setText(mCurrentStation.getLatitude().toString());
}
}
|
92352c3ae596394737fb127b23911fec0ecb396f | 1,411 | java | Java | codes/src/algo/leetcode/UniqueLetterString.java | Brucechen13/algocodes | 5385a892cce7948c067eb605314527fee7975737 | [
"MIT"
] | null | null | null | codes/src/algo/leetcode/UniqueLetterString.java | Brucechen13/algocodes | 5385a892cce7948c067eb605314527fee7975737 | [
"MIT"
] | null | null | null | codes/src/algo/leetcode/UniqueLetterString.java | Brucechen13/algocodes | 5385a892cce7948c067eb605314527fee7975737 | [
"MIT"
] | null | null | null | 30.021277 | 78 | 0.474132 | 997,190 | package algo.leetcode;
import java.util.Arrays;
public class UniqueLetterString {
public int uniqueLetterString(String S) {
int len = S.length();
final int MOD = (int)(1e9);
int[] first = new int[26];
int[] second = new int[26];
int dp = 0, res = 0;
for(int i = 0; i < len; i ++){
int ci = S.charAt(i) - 'A';
dp += (i+1 - first[ci]) - (first[ci] - second[ci]);
res = (res+dp)%MOD;
second[ci] = first[ci];
first[ci] = i+1;
}
return res;
}
public int uniqueLetterString2(String S) {
int len = S.length();
final int MOD = (int)(1e9);
int[] pre = new int[26];
int[] next = new int[26];
int[] dises = new int[len];//之前出现当前位置字符的距离
Arrays.fill(next, len);
Arrays.fill(pre, -1);
for(int i = 0; i < len; i ++){
dises[i] = i - pre[S.charAt(i) - 'A'];
pre[S.charAt(i) - 'A'] = i;
}
int res = 0;
for(int i = len-1; i >= 0; i --){
int nlen = next[S.charAt(i) - 'A'] - i;//之后出现当前字符的距离
res = (res + (dises[i] * nlen)) % MOD;//只统计该字符出现一次的字符串数
next[S.charAt(i) - 'A'] = i;
}
return res;
}
public static void main(String[] args){
System.out.print(new UniqueLetterString().uniqueLetterString2("ABC"));
}
}
|
92352e236c287ac58ca23e70cc8e17f24bdeb360 | 9,268 | java | Java | uberfire-project/uberfire-project-client/src/test/java/org/guvnor/common/services/project/client/POMEditorPanelTest.java | tomasdavidorg/appformer | 68fd82c57b224abac77ac9e5f0c56362ff981cc6 | [
"Apache-2.0"
] | 157 | 2017-09-26T17:42:08.000Z | 2022-03-11T06:48:15.000Z | uberfire-project/uberfire-project-client/src/test/java/org/guvnor/common/services/project/client/POMEditorPanelTest.java | tomasdavidorg/appformer | 68fd82c57b224abac77ac9e5f0c56362ff981cc6 | [
"Apache-2.0"
] | 940 | 2017-03-21T08:15:36.000Z | 2022-03-25T13:18:36.000Z | uberfire-project/uberfire-project-client/src/test/java/org/guvnor/common/services/project/client/POMEditorPanelTest.java | tomasdavidorg/appformer | 68fd82c57b224abac77ac9e5f0c56362ff981cc6 | [
"Apache-2.0"
] | 178 | 2017-03-14T10:44:31.000Z | 2022-03-28T23:02:29.000Z | 33.338129 | 112 | 0.581895 | 997,191 | /*
* Copyright 2012 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.guvnor.common.services.project.client;
import org.guvnor.common.services.project.client.preferences.ProjectScopedResolutionStrategySupplier;
import org.guvnor.common.services.project.model.GAV;
import org.guvnor.common.services.project.model.POM;
import org.guvnor.common.services.project.preferences.GAVPreferences;
import org.jboss.errai.ioc.client.container.SyncBeanDef;
import org.jboss.errai.ioc.client.container.SyncBeanManager;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.uberfire.client.mvp.PlaceManager;
import org.uberfire.mvp.ParameterizedCommand;
import org.uberfire.preferences.shared.impl.PreferenceScopeResolutionStrategyInfo;
import static org.mockito.Mockito.*;
@RunWith(MockitoJUnitRunner.class)
public class POMEditorPanelTest {
@Mock
private POMEditorPanelView view;
@Mock
private SyncBeanManager iocManager;
@Mock
private GAVPreferences gavPreferences;
@Mock
private ProjectScopedResolutionStrategySupplier projectScopedResolutionStrategySupplier;
private POMEditorPanel panel;
private POMEditorPanelView.Presenter presenter;
@Before
public void setUp() throws Exception {
setChildGAVEdit(false);
panel = new POMEditorPanel(view,
iocManager,
gavPreferences,
projectScopedResolutionStrategySupplier);
presenter = panel;
verify(view,
times(1)).setPresenter(presenter);
doAnswer(invocationOnMock -> {
((ParameterizedCommand<GAVPreferences>) invocationOnMock.getArguments()[1]).execute(gavPreferences);
return null;
}).when(gavPreferences).load(any(),
any(),
any());
}
@Test
public void testAddArtifactChangeHandler() {
ArtifactIdChangeHandler handler = mock(ArtifactIdChangeHandler.class);
panel.addArtifactIdChangeHandler(handler);
verify(view,
times(1)).addArtifactIdChangeHandler(handler);
}
@Test
public void testAddGroupChangeHandler() {
GroupIdChangeHandler handler = mock(GroupIdChangeHandler.class);
panel.addGroupIdChangeHandler(handler);
verify(view,
times(1)).addGroupIdChangeHandler(handler);
}
@Test
public void testAddVersionChangeHandler() {
VersionChangeHandler handler = mock(VersionChangeHandler.class);
panel.addVersionChangeHandler(handler);
verify(view,
times(1)).addVersionChangeHandler(handler);
}
@Test
public void testLoadSingleModule() throws Exception {
POM gavModel = createTestModel("pomName",
"pomDescription",
"pomUrl",
"group",
"artifact",
"1.1.1");
panel.setPOM(gavModel,
false);
verify(view).setName("pomName");
verify(view).setDescription("pomDescription");
verify(view).enableGroupID();
verify(view).enableArtifactID();
verify(view).enableVersion();
verify(view).hideParentGAV();
}
@Test
public void testLoadMultiModule() throws Exception {
POM gavModel = createTestModelWithParent("group",
"artifact",
"1.1.1");
panel.setPOM(gavModel,
false);
verify(view).setGAV(gavModel.getGav());
verify(view).setTitleText("artifact");
verify(view).setParentGAV(gavModel.getParent());
verify(view).disableGroupID("");
verify(view).enableArtifactID();
verify(view).disableVersion("");
verify(view).showParentGAV();
}
@Test
public void testProjectNameValidation() throws Exception {
panel.setValidName(true);
verify(view).setValidName(true);
panel.setValidName(false);
verify(view).setValidName(false);
}
@Test
public void testGroupIDValidation() throws Exception {
panel.setValidGroupID(true);
verify(view).setValidGroupID(true);
panel.setValidGroupID(false);
verify(view).setValidGroupID(false);
}
@Test
public void testArtifactIDValidation() throws Exception {
panel.setValidArtifactID(true);
verify(view).setValidArtifactID(true);
panel.setValidArtifactID(false);
verify(view).setValidArtifactID(false);
}
@Test
public void testVersionValidation() throws Exception {
panel.setValidVersion(true);
verify(view).setValidVersion(true);
panel.setValidVersion(false);
verify(view).setValidVersion(false);
}
@Test
public void testOpenProjectContext() throws Exception {
SyncBeanDef iocBeanDef = mock(SyncBeanDef.class);
PlaceManager placeManager = mock(PlaceManager.class);
when(iocBeanDef.getInstance()).thenReturn(placeManager);
when(iocManager.lookupBean(eq(PlaceManager.class))).thenReturn(iocBeanDef);
presenter.onOpenProjectContext();
verify(placeManager).goTo("repositoryStructureScreen");
}
@Test
public void testSetPomWhenItHasParentAndChildGAVEditIsDisabled() {
POM pom = createTestModelWithParent("group",
"artifact",
"1.1.1");
panel.setPOM(pom,
false);
verify(view).enableGroupID();
verify(view).enableArtifactID();
verify(view).enableVersion();
verify(view).showParentGAV();
verify(view).disableGroupID(anyString());
verify(view).disableVersion(anyString());
}
@Test
public void testSetPomWhenItHasParentAndChildGAVEditIsEnabled() {
POM pom = createTestModelWithParent("group",
"artifact",
"1.1.1");
setChildGAVEdit(true);
panel.setPOM(pom,
false);
verify(view).enableGroupID();
verify(view).enableArtifactID();
verify(view).enableVersion();
verify(view).showParentGAV();
verify(view,
never()).disableGroupID(anyString());
verify(view,
never()).disableVersion(anyString());
}
@Test
public void testSetPomWhenItDoesNotHaveParent() {
POM pom = createTestModel("group",
"artifact",
"1.1.1");
panel.setPOM(pom,
false);
verify(view).enableGroupID();
verify(view).enableArtifactID();
verify(view).enableVersion();
verify(view).hideParentGAV();
verify(view,
never()).disableGroupID(anyString());
verify(view,
never()).disableVersion(anyString());
}
private POM createTestModelWithParent(final String group,
final String artifact,
final String version) {
POM gavModel = createTestModel(group,
artifact,
version);
gavModel.setParent(new GAV());
return gavModel;
}
private POM createTestModel(final String group,
final String artifact,
final String version) {
return new POM(new GAV(group,
artifact,
version));
}
private POM createTestModel(final String name,
final String description,
final String url,
final String group,
final String artifact,
final String version) {
return new POM(name,
description,
url,
new GAV(group,
artifact,
version));
}
private void setChildGAVEdit(final boolean value) {
doReturn(value).when(gavPreferences).isChildGAVEditEnabled();
}
}
|
92352f0d3d833df4a8a2ff770dcd6e26f5163594 | 2,672 | java | Java | osgi-layer/integrated-tests/src/test/java/edu/northwestern/bioinformatics/studycalendar/osgi/providers/StudyConsumerIntegratedTest.java | NCIP/psc | 3f4b0be4cec4062f592ee16f059a079167e4e359 | [
"BSD-3-Clause"
] | 2 | 2015-01-22T06:14:35.000Z | 2021-09-24T20:27:40.000Z | osgi-layer/integrated-tests/src/test/java/edu/northwestern/bioinformatics/studycalendar/osgi/providers/StudyConsumerIntegratedTest.java | NCIP/psc | 3f4b0be4cec4062f592ee16f059a079167e4e359 | [
"BSD-3-Clause"
] | null | null | null | osgi-layer/integrated-tests/src/test/java/edu/northwestern/bioinformatics/studycalendar/osgi/providers/StudyConsumerIntegratedTest.java | NCIP/psc | 3f4b0be4cec4062f592ee16f059a079167e4e359 | [
"BSD-3-Clause"
] | null | null | null | 39.880597 | 118 | 0.760853 | 997,192 | /*L
* Copyright Northwestern University.
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.io/psc/LICENSE.txt for details.
*/
package edu.northwestern.bioinformatics.studycalendar.osgi.providers;
import edu.northwestern.bioinformatics.studycalendar.dataproviders.api.StudyProvider;
import edu.northwestern.bioinformatics.studycalendar.dataproviders.mock.MockDataProviderTools;
import edu.northwestern.bioinformatics.studycalendar.domain.Fixtures;
import edu.northwestern.bioinformatics.studycalendar.domain.Study;
import edu.northwestern.bioinformatics.studycalendar.osgi.OsgiLayerIntegratedTestCase;
import edu.northwestern.bioinformatics.studycalendar.service.StudyService;
import edu.northwestern.bioinformatics.studycalendar.service.dataproviders.StudyConsumer;
import gov.nih.nci.cabig.ctms.testing.MoreJUnitAssertions;
import java.util.Date;
import static edu.northwestern.bioinformatics.studycalendar.osgi.OsgiLayerIntegratedTestHelper.*;
/**
* @author Jalpa Patel
*/
public class StudyConsumerIntegratedTest extends OsgiLayerIntegratedTestCase {
private static final String MOCK_PROVIDERS_SYMBOLIC_NAME = "edu.northwestern.bioinformatics.psc-providers-mock";
private Study study;
@Override
public void setUp() throws Exception {
super.setUp();
study = Fixtures.createSingleEpochStudy("StudyName", "E", "S1", "S2");
Fixtures.addSecondaryIdentifier(study, "nct", "NCT00003641");
study.setProvider(MockDataProviderTools.PROVIDER_TOKEN);
study.setAssignedIdentifier("NCT00003641");
getStudyService().save(study);
startBundle(MOCK_PROVIDERS_SYMBOLIC_NAME, StudyProvider.class.getName());
}
@Override
public void tearDown() throws Exception {
stopBundle(MOCK_PROVIDERS_SYMBOLIC_NAME);
getStudyService().getStudyDao().delete(study);
super.tearDown();
}
public void testRefreshDoesNotFail() throws Exception {
Study refreshed = getStudyConsumer().refresh(study);
assertEquals("NCT00003641", refreshed.getAssignedIdentifier());
assertNotNull("Could not find test study", refreshed);
assertNotNull("Test study not refreshed", refreshed.getLastRefresh());
MoreJUnitAssertions.assertDatesClose("Not refreshed recently", new Date(), refreshed.getLastRefresh(), 25000);
}
////// HELPERS
private StudyService getStudyService() {
return ((StudyService) getApplicationContext().getBean("studyService"));
}
private StudyConsumer getStudyConsumer() {
return (StudyConsumer) getApplicationContext().getBean("studyConsumerBean");
}
}
|
9235307796a0c114a01dc3f7765ee9decfd532a2 | 4,188 | java | Java | app/src/main/java/com/didim99/sat/network/NetworkManager.java | didim99/SAT | 6b5598f2e04a725b74acacae04533c25909016bf | [
"MIT"
] | 1 | 2020-10-21T15:12:55.000Z | 2020-10-21T15:12:55.000Z | app/src/main/java/com/didim99/sat/network/NetworkManager.java | didim99/SAT-Android | 6b5598f2e04a725b74acacae04533c25909016bf | [
"MIT"
] | null | null | null | app/src/main/java/com/didim99/sat/network/NetworkManager.java | didim99/SAT-Android | 6b5598f2e04a725b74acacae04533c25909016bf | [
"MIT"
] | null | null | null | 30.347826 | 77 | 0.657832 | 997,193 | package com.didim99.sat.network;
import android.os.AsyncTask;
import com.didim99.sat.BuildConfig;
import com.didim99.sat.utils.MyLog;
import com.didim99.sat.utils.Utils;
import com.didim99.sat.settings.Settings;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import okhttp3.OkHttpClient;
import okhttp3.ResponseBody;
import retrofit2.Response;
import retrofit2.Retrofit;
/**
* synchronous/asynchronous network access manager
* Created by didim99 on 26.07.18.
*/
public class NetworkManager extends AsyncTask<Void, Void, Void> {
private static final String LOG_TAG = MyLog.LOG_TAG_BASE + "_NetMgr";
public static final class Status {
public static final int OK = 0;
private static final int WEB_UNAVAILABLE = -1;
}
private enum Mode { GET_DATA, SEND_LOG }
private static boolean initCompleted = false;
private static WebAPI webAPI;
private Mode mode;
private EventListener listener;
private String action, data;
private int status;
public NetworkManager(EventListener listener, String action) {
this.listener = listener;
this.action = action;
this.mode = Mode.GET_DATA;
this.status = Status.OK;
}
public NetworkManager(String logEvent) {
this.action = logEvent;
this.mode = Mode.SEND_LOG;
}
@Override
protected Void doInBackground(Void... voids) {
switch (mode) {
case GET_DATA:
try {
data = NetworkManager.getContentFromWeb(action);
} catch (IOException e) {
MyLog.e(LOG_TAG, "Can't load data from web\n " + e.toString());
status = Status.WEB_UNAVAILABLE;
}
break;
case SEND_LOG:
sendLog(action);
break;
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if (mode == Mode.GET_DATA)
listener.onDataReceived(action, status, data);
listener = null;
}
public static void init() {
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(5, TimeUnit.SECONDS)
.writeTimeout(5, TimeUnit.SECONDS).build();
webAPI = new Retrofit.Builder().baseUrl(WebAPI.URL_BASE)
.client(client).build().create(WebAPI.class);
initCompleted = true;
}
public static String getContentFromWeb(String action) throws IOException {
if (!initCompleted) init();
MyLog.d(LOG_TAG, "Trying to get data from web-server ("+ action +")...");
Response<ResponseBody> response = webAPI.getData(action).execute();
MyLog.d(LOG_TAG, response.toString());
if (response.isSuccessful()) {
ResponseBody body = response.body();
if (body != null) {
String data = body.string();
MyLog.d(LOG_TAG, "Data loaded (" + data.length() + " bytes)");
return data;
}
else throw new IOException("Response body is null");
} else {
throw new IOException("Connection error ("
+ response.code() + " " + response.message() + ")");
}
}
public static void sendLog(String event) {
try {
if (!initCompleted) init();
MyLog.d(LOG_TAG, "Sending log... ");
Settings.loadDeviceInfo();
Map<String, String> data = new HashMap<>();
data.put("vendor", Settings.getDevVendor());
data.put("model", Settings.getDevModel());
data.put("res", Settings.getDevRes());
data.put("osver", Settings.getDevOsVer());
data.put("abi", Settings.getDevAbi());
data.put("app_ver", Utils.base64Encode(BuildConfig.VERSION_NAME));
data.put("uuid", Settings.getDevId());
data.put("action", Utils.base64Encode(event));
Response<Void> response = webAPI.sendLog(data).execute();
MyLog.d(LOG_TAG, response.toString());
if (response.isSuccessful())
MyLog.d(LOG_TAG, "Log sent successful");
else {
throw new IOException("Connection error ("
+ response.code() + " " + response.message() + ")");
}
} catch (IOException e) {
MyLog.w(LOG_TAG, "can't send log\n " + e.toString());
}
}
public interface EventListener {
void onDataReceived(String action, int status, String data);
}
}
|
923530f1a39ccb23c42e16f184da2cbdbf9024fb | 3,079 | java | Java | resolver/src/main/java/io/netty/resolver/SimpleNameResolver.java | NicoK/netty | d07d7e2b9a3795139e0b6f64e55f8ed700f8ff5c | [
"Apache-2.0"
] | 12 | 2015-12-24T02:01:44.000Z | 2020-07-28T08:34:05.000Z | resolver/src/main/java/io/netty/resolver/SimpleNameResolver.java | NicoK/netty | d07d7e2b9a3795139e0b6f64e55f8ed700f8ff5c | [
"Apache-2.0"
] | 15 | 2019-11-01T08:05:01.000Z | 2022-03-31T20:29:35.000Z | resolver/src/main/java/io/netty/resolver/SimpleNameResolver.java | NicoK/netty | d07d7e2b9a3795139e0b6f64e55f8ed700f8ff5c | [
"Apache-2.0"
] | 7 | 2019-06-20T17:00:09.000Z | 2019-09-25T14:44:19.000Z | 30.485149 | 117 | 0.666775 | 997,194 | /*
* Copyright 2014 The Netty Project
*
* The Netty Project 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 io.netty.resolver;
import io.netty.util.concurrent.EventExecutor;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.Promise;
import io.netty.util.internal.UnstableApi;
import java.util.List;
import static io.netty.util.internal.ObjectUtil.*;
/**
* A skeletal {@link NameResolver} implementation.
*/
@UnstableApi
public abstract class SimpleNameResolver<T> implements NameResolver<T> {
private final EventExecutor executor;
/**
* @param executor the {@link EventExecutor} which is used to notify the listeners of the {@link Future} returned
* by {@link #resolve(String)}
*/
protected SimpleNameResolver(EventExecutor executor) {
this.executor = checkNotNull(executor, "executor");
}
/**
* Returns the {@link EventExecutor} which is used to notify the listeners of the {@link Future} returned
* by {@link #resolve(String)}.
*/
protected EventExecutor executor() {
return executor;
}
@Override
public final Future<T> resolve(String inetHost) {
final Promise<T> promise = executor().newPromise();
return resolve(inetHost, promise);
}
@Override
public Future<T> resolve(String inetHost, Promise<T> promise) {
checkNotNull(promise, "promise");
try {
doResolve(inetHost, promise);
return promise;
} catch (Exception e) {
return promise.setFailure(e);
}
}
@Override
public final Future<List<T>> resolveAll(String inetHost) {
final Promise<List<T>> promise = executor().newPromise();
return resolveAll(inetHost, promise);
}
@Override
public Future<List<T>> resolveAll(String inetHost, Promise<List<T>> promise) {
checkNotNull(promise, "promise");
try {
doResolveAll(inetHost, promise);
return promise;
} catch (Exception e) {
return promise.setFailure(e);
}
}
/**
* Invoked by {@link #resolve(String)} to perform the actual name resolution.
*/
protected abstract void doResolve(String inetHost, Promise<T> promise) throws Exception;
/**
* Invoked by {@link #resolveAll(String)} to perform the actual name resolution.
*/
protected abstract void doResolveAll(String inetHost, Promise<List<T>> promise) throws Exception;
@Override
public void close() { }
}
|
9235313ddc7d9fab72f10cdb0d51f91065684f25 | 2,502 | java | Java | user/src/main/java/com/idogs/laosiji/user/function/main/SignupActivity.java | balckban/lsj | 1a7c3470dcfe85154731c596a93ec8102cc81df4 | [
"MIT"
] | 4 | 2018-03-22T15:17:56.000Z | 2020-09-17T03:56:12.000Z | user/src/main/java/com/idogs/laosiji/user/function/main/SignupActivity.java | balckban/lsj | 1a7c3470dcfe85154731c596a93ec8102cc81df4 | [
"MIT"
] | 2 | 2020-07-23T10:01:09.000Z | 2020-07-30T01:33:22.000Z | user/src/main/java/com/idogs/laosiji/user/function/main/SignupActivity.java | balckban/lsj | 1a7c3470dcfe85154731c596a93ec8102cc81df4 | [
"MIT"
] | 2 | 2019-10-30T10:37:43.000Z | 2019-12-19T18:41:10.000Z | 32.921053 | 158 | 0.721823 | 997,195 | package com.idogs.laosiji.user.function.main;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.idogs.laosiji.basic.component.YbBasicComponent;
import com.idogs.laosiji.basic.ext.YbAbstractActivity;
import com.idogs.laosiji.basic.util.MD5Utils;
import com.idogs.laosiji.config.RouterConfig;
import com.idogs.laosiji.user.R;
import com.idogs.laosiji.user.R2;
import com.idogs.laosiji.user.function.main.componet.DaggerUserComponet;
import com.idogs.laosiji.user.function.main.contract.UserContract;
import com.idogs.laosiji.user.function.main.module.UserModule;
import com.idogs.laosiji.user.function.main.widgets.PasswordEditText;
import javax.inject.Inject;
import butterknife.BindView;
import butterknife.OnClick;
/**
* Created by Administrator on 2017/11/21 0021.
*/
@Route(path = RouterConfig.USER_SIGN)
public class SignupActivity extends YbAbstractActivity<UserContract.Presenter> implements UserContract.View {
@BindView(R2.id.signup_user)
EditText signup_user;
@BindView(R2.id.signup_pass)
PasswordEditText signup_pass;
@Inject
UserContract.Presenter mPresenter;
@Override
public int bindLayout() {
return R.layout.activity_sign_up;
}
@Override
public void afterViews() {
}
@OnClick(R2.id.btn_changetologinmode)
public void toLogin(){
ARouter.getInstance().build(RouterConfig.USER_LOGIN).navigation();
}
@OnClick(R2.id.btn_signup)
public void registerBt(){
//隐藏软键盘
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);
mPresenter.register(signup_user.getText().toString().replace(" ", ""), MD5Utils.md5Password(signup_pass.getText().toString().replace(" ", "")),this);
}
@Override
protected void injectDagger2(YbBasicComponent basicComponent) {
DaggerUserComponet.builder()
.ybBasicComponent(basicComponent)
.userModule(new UserModule(this))
.build()
.inject(this);
}
}
|
92353249adea9eaf7c16ff140b1845e77c4cf4b5 | 4,960 | java | Java | src/radlab/rain/IScoreboard.java | sguazt/rain-workload-toolkit | 90f18f77e7b21d07999512494a2a9be8a587f812 | [
"BSD-3-Clause"
] | 19 | 2015-09-23T12:59:59.000Z | 2021-12-02T08:19:26.000Z | src/radlab/rain/IScoreboard.java | itconsultore/rain-workload-toolkit | 90f18f77e7b21d07999512494a2a9be8a587f812 | [
"BSD-3-Clause"
] | 6 | 2015-11-14T18:01:12.000Z | 2016-04-14T06:45:16.000Z | src/radlab/rain/IScoreboard.java | yungsters/rain-workload-toolkit | f956999b5c2d4244a43eff656e0c0f92e32fdd2e | [
"BSD-3-Clause"
] | 12 | 2015-07-12T17:30:33.000Z | 2019-05-08T05:47:34.000Z | 30.429448 | 78 | 0.728226 | 997,196 | /*
* Copyright (c) 2010, Regents of the University of California
* 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 University of California, Berkeley
* 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.
*/
package radlab.rain;
import java.io.FileWriter;
import java.io.PrintStream;
import radlab.rain.util.MetricWriter;
/**
* The IScoreboard interface allows an implemented scoreboard to interface
* with the benchmark architecture.<br />
* <br />
* The interface requires that the scoreboard be able to start, stop, receive
* results, show statistics, and register log handles, among other things.
*/
public interface IScoreboard
{
/**
* Gets the time when this scoreboard starts recording results.
*/
long getStartTimestamp();
/**
* Sets the time when this scoreboard starts recording results.
*
* @param val The time to use as the start time.
*/
void setStartTimestamp( long val );
/**
* Gets the time when this scoreboard stops recording results.
*/
long getEndTimestamp();
/**
* Sets the time when this scoreboard stops recording results.
*
* @param val The time to use as the end time.
*/
void setEndTimestamp( long val );
/**
* Initializes the start and end times and resets the results.
*
* @param startTime The time to start receiving results.
* @param endTime The time to stop receiving results.
*/
void initialize( long startTime, long endTime );
/**
* Resets the results recorded by this scoreboard.
*/
void reset();
/**
* Starts this scoreboard for recording results.
*/
void start();
/**
* Stops this scoreboard from recording any more results.
*/
void stop();
/**
* Receives the results of an operation execution.
*
* @param result The result to record.
*/
void dropOff( OperationExecution result );
void dropOffWaitTime( long time, String opName, long waitTime );
/**
* Prints the statistics processed by this scoreboard.
*/
void printStatistics( PrintStream out );
/**
* Registers a log handler for a string identifier.
*
* @param owner The string to identify this log handler by.
* @param logHandle The log handler to register.
*/
void registerLogHandle( String owner, FileWriter logHandle );
/**
* Deregisters a log handler identified by the given string.
*
* @param owner The string identifying the log handler.
*/
void deRegisterLogHandle( String owner );
/**
* Registers an error log handler for a string identifier.
*
* @param owner The string to identify this error log handler by.
* @param logHandle The error log handler to register.
*/
void registerErrorLogHandle( String owner, FileWriter logHandle );
/**
* Deregisters an error log handler identified by the given string.
*
* @param owner The string identifying the error log handler.
*/
void deRegisterErrorLogHandle( String owner );
double getLogSamplingProbability();
void setLogSamplingProbability( double val );
long getMetricSnapshotInterval();
void setMetricSnapshotInterval( long val );
boolean getUsingMetricSnapshots();
void setUsingMetricSnapshots( boolean val );
ScenarioTrack getScenarioTrack();
void setScenarioTrack( ScenarioTrack val );
long getMeanResponseTimeSamplingInterval();
void setMeanResponseTimeSamplingInterval( long val );
String getTargetHost();
void setTargetHost( String val );
Scorecard getFinalScorecard();
MetricWriter getMetricWriter();
void setMetricWriter( MetricWriter val );
}
|
92353256580f66dc32cf09c3024e056283f903b2 | 7,781 | java | Java | audit/src/main/java/org/openhealthtools/openatna/audit/process/ProcessorChain.java | Treynis/openatna | ec1d972d133fb9536a793ff4ab7b1213e8111665 | [
"Apache-2.0"
] | null | null | null | audit/src/main/java/org/openhealthtools/openatna/audit/process/ProcessorChain.java | Treynis/openatna | ec1d972d133fb9536a793ff4ab7b1213e8111665 | [
"Apache-2.0"
] | null | null | null | audit/src/main/java/org/openhealthtools/openatna/audit/process/ProcessorChain.java | Treynis/openatna | ec1d972d133fb9536a793ff4ab7b1213e8111665 | [
"Apache-2.0"
] | null | null | null | 33.538793 | 108 | 0.614574 | 997,197 | /**
* Copyright (c) 2009-2011 University of Cardiff and others
*
* 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.
*
* Contributors:
* University of Cardiff - initial API and implementation
* -
*/
package org.openhealthtools.openatna.audit.process;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openhealthtools.openatna.audit.persistence.PersistencePolicies;
/**
* A chain for processors.
* <p/>
* The addNext() method is relative to the previous call to one of the add* methods.
* addFirst() resets the "next" counter to 1.
* addLast() resets the "next" counter to the size of the list of processors.
* addNext() increments the "next" counter.
* <p/>
* The "next" counter starts off with a value of 0.
* <p/>
* The chain will persist the atna message, if no previous processors have set the
* state of the context to PERSISTED. This means only domain/business processors
* need to be added manually.
* <p/>
* It will also validate the message before passing it to any other processors.
* To not use the built-in validator, use the constructor with the boolean set to false.
* <p/>
* If a processor throws an exception during processing, then the chain is unwound (shameless
* copy of CXF). The exception is set on the context and each
* processor that has been called gets its error(context) method called in reverse order.
*
* @author Andrew Harrison
* @version $Revision:$
* @created Sep 13, 2009: 9:07:16 PM
* @date $Date:$ modified by $Author:$
*/
public class ProcessorChain {
private static Log log = LogFactory.getLog("org.openhealthtools.openatna.audit.process.ProcessorChain");
public static enum PHASE {
PRE_VERIFY,
POST_VERIFY,
POST_PERSIST,
}
private ProvisionalProcessor prov = new ProvisionalProcessor();
private ExceptionProcessor except = new ExceptionProcessor();
private ValidationProcessor validator = new ValidationProcessor();
private PersistenceProcessor persist = new PersistenceProcessor();
private PhaseProcessor preVerify = new PhaseProcessor();
private PhaseProcessor postVerify = new PhaseProcessor();
private PhaseProcessor postPersist = new PhaseProcessor();
private boolean validate;
private Map<String, Object> contextProperties = new HashMap<String, Object>();
private PersistencePolicies policies = new PersistencePolicies();
public ProcessorChain(boolean validate) {
this.validate = validate;
}
public ProcessorChain() {
this(true);
}
public ProcessorChain addFirst(AtnaProcessor processor, PHASE phase) {
switch (phase) {
case PRE_VERIFY:
preVerify.addFirst(processor);
break;
case POST_VERIFY:
postVerify.addFirst(processor);
break;
case POST_PERSIST:
postPersist.addFirst(processor);
break;
default:
break;
}
return this;
}
public ProcessorChain addLast(AtnaProcessor processor, PHASE phase) {
switch (phase) {
case PRE_VERIFY:
preVerify.addLast(processor);
break;
case POST_VERIFY:
postVerify.addLast(processor);
break;
case POST_PERSIST:
postPersist.addLast(processor);
break;
default:
break;
}
return this;
}
public ProcessorChain addNext(AtnaProcessor processor, PHASE phase) {
switch (phase) {
case PRE_VERIFY:
preVerify.addNext(processor);
break;
case POST_VERIFY:
postVerify.addNext(processor);
break;
case POST_PERSIST:
postPersist.addNext(processor);
break;
default:
break;
}
return this;
}
public void process(ProcessContext context) throws Exception {
long before = System.currentTimeMillis();
context.addProperties(Collections.unmodifiableMap(contextProperties));
context.setPolicies(getPolicies());
List<AtnaProcessor> done = new ArrayList<AtnaProcessor>();
Exception ex = null;
try {
prov.process(context);
if (context.getState() == ProcessContext.State.ABORTED) {
log.debug("chain aborted after provisional processor");
return;
}
except.process(context);
done.add(except);
if (context.getState() == ProcessContext.State.ABORTED) {
log.debug("chain aborted after exception processor");
return;
}
preVerify.process(context);
done.add(preVerify);
if (context.getState() == ProcessContext.State.ABORTED) {
log.debug("chain aborted after preverify processors");
return;
}
if (validate) {
validator.process(context);
done.add(validator);
}
postVerify.process(context);
done.add(postVerify);
if (context.getState() == ProcessContext.State.ABORTED) {
log.debug("chain aborted after postverify processor");
return;
}
if (context.getState() != ProcessContext.State.PERSISTED) {
log.debug("about to persist message");
persist.process(context);
done.add(persist);
}
postPersist.process(context);
done.add(postPersist);
} catch (Exception e) {
ex = e;
context.setState(ProcessContext.State.ERROR);
context.setThrowable(e);
rewind(done, context);
}
long now = System.currentTimeMillis();
log.debug("message processing time:" + (now - before));
if (ex != null) {
throw ex;
}
}
private void rewind(List<AtnaProcessor> completed, ProcessContext context) {
for (int i = completed.size() - 1; i >= 0; i--) {
AtnaProcessor ap = completed.get(i);
ap.error(context);
}
}
public PersistencePolicies getPolicies() {
return policies;
}
public void setPolicies(PersistencePolicies policies) {
this.policies = policies;
}
public void putProperty(String key, Object value) {
contextProperties.put(key, value);
}
public void putProperties(Map<String, Object> props) {
contextProperties.putAll(props);
}
public Object getProperty(String key) {
return contextProperties.get(key);
}
@SuppressWarnings("unchecked")
public <T> T getProperty(String key, Class<? extends T> cls) {
Object val = contextProperties.get(key);
if (val != null && cls.isAssignableFrom(val.getClass())) {
return (T) val;
}
return null;
}
}
|
92353260ba73c608c1e4bfd5cd43b9ce1ee4aa02 | 2,738 | java | Java | src/main/java/net/reallifegames/ow/api/v1/users/get/SafeUserModel.java | agent6262/owbalancer | 546c46884644d95a4b16ef456f8596143b0c684b | [
"MIT"
] | null | null | null | src/main/java/net/reallifegames/ow/api/v1/users/get/SafeUserModel.java | agent6262/owbalancer | 546c46884644d95a4b16ef456f8596143b0c684b | [
"MIT"
] | 1 | 2021-03-19T22:06:11.000Z | 2021-03-21T05:36:14.000Z | src/main/java/net/reallifegames/ow/api/v1/users/get/SafeUserModel.java | agent6262/owbalancer | 546c46884644d95a4b16ef456f8596143b0c684b | [
"MIT"
] | 1 | 2020-08-03T03:43:52.000Z | 2020-08-03T03:43:52.000Z | 32.987952 | 156 | 0.681885 | 997,198 | /*
* The MIT License (MIT)
*
* Copyright (c) 2020 Tyler Bucher
*
* 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 net.reallifegames.ow.api.v1.users.get;
import net.reallifegames.ow.models.UserModel;
import javax.annotation.Nonnull;
import java.util.List;
/**
* An safe version of the UserModel so passwords are not exposed.
*
* @author Tyler Bucher
*/
public class SafeUserModel {
/**
* Identification filed for the account.
*/
public final String email;
/**
* Visual username for the account.
*/
public final String username;
/**
* Is this user allowed to login.
*/
public final boolean active;
/**
* The list of permissions for this user.
*/
public final List<Integer> permissions;
/**
* The amount of players this user has.
*/
public final int playerCount;
public SafeUserModel(@Nonnull final String email,
@Nonnull final String username,
final boolean active,
@Nonnull final List<Integer> permissions,
final int playerCount) {
this.email = email;
this.username = username;
this.active = active;
this.permissions = permissions;
this.playerCount = playerCount;
}
/**
* @param userModel the UserModel to convert.
* @return the converted UserModel.
*/
public static SafeUserModel fromUserModel(@Nonnull final UserModel userModel, final boolean canSeeEmail) {
return new SafeUserModel(canSeeEmail ? userModel.email : "", userModel.username, userModel.active, userModel.permissions, userModel.players.size());
}
}
|
923533e48ae824498fcf9d5efff681acdf1b5924 | 1,465 | java | Java | shardingsphere-infra/shardingsphere-infra-common/src/main/java/org/apache/shardingsphere/infra/datanode/DataNodeBuilder.java | jiangtao69039/shardingsphere | 82ff0e3dba7ca8908d6076eb1544fa215c1bc4a1 | [
"Apache-2.0"
] | 4,372 | 2019-01-16T03:07:05.000Z | 2020-04-17T11:16:15.000Z | shardingsphere-infra/shardingsphere-infra-common/src/main/java/org/apache/shardingsphere/infra/datanode/DataNodeBuilder.java | jiangtao69039/shardingsphere | 82ff0e3dba7ca8908d6076eb1544fa215c1bc4a1 | [
"Apache-2.0"
] | 3,040 | 2019-01-16T01:18:40.000Z | 2020-04-17T12:53:05.000Z | shardingsphere-infra/shardingsphere-infra-common/src/main/java/org/apache/shardingsphere/infra/datanode/DataNodeBuilder.java | jiangtao69039/shardingsphere | 82ff0e3dba7ca8908d6076eb1544fa215c1bc4a1 | [
"Apache-2.0"
] | 1,515 | 2019-01-16T08:44:17.000Z | 2020-04-17T09:07:53.000Z | 34.069767 | 86 | 0.74471 | 997,199 | /*
* 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.shardingsphere.infra.datanode;
import org.apache.shardingsphere.infra.rule.ShardingSphereRule;
import org.apache.shardingsphere.spi.annotation.SingletonSPI;
import org.apache.shardingsphere.spi.type.ordered.OrderedSPI;
import java.util.Collection;
/**
* Data node builder.
*
* @param <T> type of rule
*/
@SingletonSPI
public interface DataNodeBuilder<T extends ShardingSphereRule> extends OrderedSPI<T> {
/**
* Build data node.
*
* @param dataNodes data node collection
* @param rule rule
* @return data node collection
*/
Collection<DataNode> build(Collection<DataNode> dataNodes, T rule);
}
|
923533ec7de13b580333c316bac5b3100c7a210e | 4,604 | java | Java | lib/src/main/java/gdv/xport/satz/feld/sparte52/Feld221.java | markusneidhart/gdv.xport | 4bb4b186de05093d1d39adc6a7dc524fa4a9c1bb | [
"Apache-2.0"
] | 17 | 2016-03-24T16:04:55.000Z | 2022-01-27T10:03:34.000Z | lib/src/main/java/gdv/xport/satz/feld/sparte52/Feld221.java | markusneidhart/gdv.xport | 4bb4b186de05093d1d39adc6a7dc524fa4a9c1bb | [
"Apache-2.0"
] | 62 | 2016-08-25T16:07:18.000Z | 2022-03-21T08:31:47.000Z | lib/src/main/java/gdv/xport/satz/feld/sparte52/Feld221.java | markusneidhart/gdv.xport | 4bb4b186de05093d1d39adc6a7dc524fa4a9c1bb | [
"Apache-2.0"
] | 20 | 2015-02-16T17:35:47.000Z | 2022-01-13T11:36:15.000Z | 24.886486 | 118 | 0.560165 | 997,200 | /*
* Copyright (c) 2011, 2012 by Oli B.
*
* 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 orimplied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* (c)reated 14.04.11 by oliver
*/
package gdv.xport.satz.feld.sparte52;
import gdv.xport.annotation.FeldInfo;
import gdv.xport.annotation.FelderInfo;
import gdv.xport.feld.*;
import gdv.xport.satz.feld.common.Feld1bis7;
/**
* Diese Enum-Klasse repraesentiert die Felder fuer Satzart 221, Sparte 52.
*
* @author oliver
* @since 14.04.11
* @deprecated Enums mit Annotationen werden ab v6 nicht mehr unterstuetzt
*/
@Deprecated
public enum Feld221 {
///// Teildatensatz 1 /////////////////////////////////////////////////
/** Feld 1 - 7 sind fuer jeden (Teil-)Datensatz identisch. */
@FelderInfo(
teildatensatz = 1,
type = Feld1bis7.class
)
INTRO1,
/**
* KFV-Beitrag in Waehrungseinheiten (10,2 Stellen).
*/
@FeldInfo(
teildatensatz = 1,
nr = 8,
type = Betrag.class,
nachkommaStellen = 2,
anzahlBytes = 12,
byteAdresse = 43
)
KFV_BEITRAG_IN_WAEHRUNGSEINHEITEN,
/**
* KFV-Zuschlaege in Waehrungseinheiten (10,2 Stellen).
*/
@FeldInfo(
teildatensatz = 1,
nr = 9,
type = Betrag.class,
nachkommaStellen = 2,
anzahlBytes = 12,
byteAdresse = 55
)
KFV_ZUSCHLAEGE_IN_WAEHRUNGSEINHEITEN,
/**
* KFV-Abschlaege in Waehrungseinheiten (10,2 Stellen).
*/
@FeldInfo(
teildatensatz = 1,
nr = 10,
type = Betrag.class,
nachkommaStellen = 2,
anzahlBytes = 12,
byteAdresse = 67
)
KFV_ABSCHLAEGE_IN_WAEHRUNGSEINHEITEN,
/**
* Frei vereinbarte Selbstbeteiligung in Waehrungseinheiten fuer Vollkasko (10,2 Stellen).
*/
@FeldInfo(
teildatensatz = 1,
nr = 11,
type = Betrag.class,
nachkommaStellen = 2,
anzahlBytes = 12,
byteAdresse = 79
)
FREI_VEREINBARTE_SELBSTBETEILIGUNG_IN_WAEHRUNGSEINHEITEN_FUER_VOLLKASKO,
/**
* Tarifbeitrag 100 % fuer Kraftfahrt-Fahrzeugvoll in Waehrungseinheiten (10,2 Stellen).
*/
@FeldInfo(
teildatensatz = 1,
nr = 12,
type = Betrag.class,
nachkommaStellen = 2,
anzahlBytes = 12,
byteAdresse = 91
)
TARIFBEITRAG_100_PROZENT_FUER_KRAFTFAHRT_FAHRZEUGVOLL_IN_WAEHRUNGSEINHEITEN,
/**
* Frei vereinbarte Selbstbeteiligung in Waehrungseinheiten fuer Teilkasko im Rahmen der Vollkasko (10,2 Stellen).
*/
@FeldInfo(
teildatensatz = 1,
nr = 13,
type = Betrag.class,
nachkommaStellen = 2,
anzahlBytes = 12,
byteAdresse = 103
)
FREI_VEREINBARTE_SELBSTBETEILIGUNG_IN_WAEHRUNGSEINHEITEN_FUER_TEILKASKO,
/**
* Referenznummer.
*/
@FeldInfo(
teildatensatz = 1,
nr = 14,
type = AlphaNumFeld.class,
anzahlBytes = 7,
byteAdresse = 115
)
REFERENZNUMMER,
/**
* Lfd. Nummer.
*/
@FeldInfo(
teildatensatz = 1,
nr = 15,
type = AlphaNumFeld.class,
anzahlBytes = 4,
byteAdresse = 122
)
LFD_NUMMER,
/**
* Personennummer / lfd. Nummer.
*/
@FeldInfo(
teildatensatz = 1,
nr = 16,
type = AlphaNumFeld.class,
anzahlBytes = 17,
byteAdresse = 126
)
PERSONENNUMMER_LFD_NUMMER,
/**
* Leerstellen.
*/
@FeldInfo(
teildatensatz = 1,
nr = 17,
type = AlphaNumFeld.class,
anzahlBytes = 113,
byteAdresse = 143
)
LEERSTELLEN,
/**
* Satznummer.
*/
@FeldInfo(
teildatensatz = 1,
nr = 18,
type = Zeichen.class,
anzahlBytes = 1,
byteAdresse = 256
)
SATZNUMMER;
}
|
9235347b764f56498b201f73b7b27bf003228807 | 300 | java | Java | codeblocks-test/src/main/java/com/andyadc/codeblocks/test/encrypt/AuthenticatedEncryptionException.java | andyadc/codeblocks | f7e31f1fff839cdcfd6dcd778c8318753226262f | [
"MIT"
] | null | null | null | codeblocks-test/src/main/java/com/andyadc/codeblocks/test/encrypt/AuthenticatedEncryptionException.java | andyadc/codeblocks | f7e31f1fff839cdcfd6dcd778c8318753226262f | [
"MIT"
] | 3 | 2019-10-29T01:27:23.000Z | 2022-01-14T02:41:55.000Z | codeblocks-test/src/main/java/com/andyadc/codeblocks/test/encrypt/AuthenticatedEncryptionException.java | andyadc/codeblocks | f7e31f1fff839cdcfd6dcd778c8318753226262f | [
"MIT"
] | null | null | null | 23.076923 | 75 | 0.806667 | 997,201 | package com.andyadc.codeblocks.test.encrypt;
public class AuthenticatedEncryptionException extends Exception {
public AuthenticatedEncryptionException(String message) {
super(message);
}
public AuthenticatedEncryptionException(String message, Throwable cause) {
super(message, cause);
}
}
|
92353630da2c32f8eb5416be0235af23ee7a3a98 | 509 | java | Java | GerenciamentoNotas/src/br/com/fean/gerenciamentodenotas/service/AlunoCursoMateriaDtoService.java | BigPAB/GerenciamentoDeNotas | d23483efeb5158a5da9d3de1f7cc4129f3761d5b | [
"MIT"
] | null | null | null | GerenciamentoNotas/src/br/com/fean/gerenciamentodenotas/service/AlunoCursoMateriaDtoService.java | BigPAB/GerenciamentoDeNotas | d23483efeb5158a5da9d3de1f7cc4129f3761d5b | [
"MIT"
] | null | null | null | GerenciamentoNotas/src/br/com/fean/gerenciamentodenotas/service/AlunoCursoMateriaDtoService.java | BigPAB/GerenciamentoDeNotas | d23483efeb5158a5da9d3de1f7cc4129f3761d5b | [
"MIT"
] | null | null | null | 28.277778 | 97 | 0.850688 | 997,202 | package br.com.fean.gerenciamentodenotas.service;
import java.util.Map;
import br.com.fean.gerenciamentodenotas.dto.AlunoCursoMateriaDto;
public interface AlunoCursoMateriaDtoService {
public String salvarAlunoCursoMateriaDto( AlunoCursoMateriaDto alunoCursoMateriaDto);
public String excluirAlunoCursoMateriaDto(String id);
public String alterarAlunoCursoMateriaDto(String id, AlunoCursoMateriaDto alunoCursoMateriaDto);
public Map<String, AlunoCursoMateriaDto> listarAlunoCursoMateriaDto();
}
|
923536b99adccbb6a136e357788b70bf568cdc4c | 1,582 | java | Java | src/main/java/org/codinjutsu/tools/jenkins/view/validator/UrlValidator.java | nvdweem/jenkins-control-plugin | a2f1559857f01c9ddda061ea7b0566b418ca9891 | [
"Apache-2.0"
] | 132 | 2015-02-23T11:17:26.000Z | 2020-01-15T05:30:48.000Z | src/main/java/org/codinjutsu/tools/jenkins/view/validator/UrlValidator.java | nvdweem/jenkins-control-plugin | a2f1559857f01c9ddda061ea7b0566b418ca9891 | [
"Apache-2.0"
] | 182 | 2020-01-28T22:47:44.000Z | 2022-03-31T06:23:37.000Z | src/main/java/org/codinjutsu/tools/jenkins/view/validator/UrlValidator.java | nvdweem/jenkins-control-plugin | a2f1559857f01c9ddda061ea7b0566b418ca9891 | [
"Apache-2.0"
] | 86 | 2015-02-03T19:58:51.000Z | 2019-12-18T11:21:32.000Z | 35.155556 | 123 | 0.690265 | 997,203 | /*
* Copyright (c) 2013 David Boissier
*
* 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.codinjutsu.tools.jenkins.view.validator;
import org.apache.commons.lang.StringUtils;
import org.codinjutsu.tools.jenkins.exception.ConfigurationException;
import javax.swing.*;
import java.net.MalformedURLException;
import java.net.URL;
public class UrlValidator implements UIValidator<JTextField> {
public void validate(JTextField component) throws ConfigurationException {
String value = component.getText();
if (StringUtils.isEmpty(value)) {
return;
}
try {
URL url = new URL(value);
String userInfo = url.getUserInfo();
if (StringUtils.isEmpty(userInfo)) {
return;
}
throw new ConfigurationException("Credentials should not be embedded in the url. Use the above form instead.");
} catch (MalformedURLException ex) {
throw new ConfigurationException(String.format("URL '%s' is malformed", value));
}
}
}
|
923537cc6cf6e9c8acd974f48fd356aafe00edfd | 759 | java | Java | src/main/java/api/client/model/market/SymbolPrice.java | TomaszSiarkiewicz/Bot-For-Binance | 2c39ec07648508119b6db71551e19f60c7fd2a22 | [
"Apache-2.0"
] | null | null | null | src/main/java/api/client/model/market/SymbolPrice.java | TomaszSiarkiewicz/Bot-For-Binance | 2c39ec07648508119b6db71551e19f60c7fd2a22 | [
"Apache-2.0"
] | null | null | null | src/main/java/api/client/model/market/SymbolPrice.java | TomaszSiarkiewicz/Bot-For-Binance | 2c39ec07648508119b6db71551e19f60c7fd2a22 | [
"Apache-2.0"
] | null | null | null | 21.083333 | 110 | 0.667984 | 997,204 | package api.client.model.market;
import api.client.constant.BinanceApiConstants;
import org.apache.commons.lang3.builder.ToStringBuilder;
import java.math.BigDecimal;
public class SymbolPrice {
private String symbol;
private BigDecimal price;
public String getSymbol() {
return symbol;
}
public void setSymbol(String symbol) {
this.symbol = symbol;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
@Override
public String toString() {
return new ToStringBuilder(this, BinanceApiConstants.TO_STRING_BUILDER_STYLE).append("symbol", symbol)
.append("price", price).toString();
}
}
|
92353860aab38e77de905f84864be5720dec6dba | 5,676 | java | Java | tests/common/src/main/java/org/springframework/cloud/sleuth/otel/OtelTestTracing.java | maxxedev/spring-cloud-sleuth | 6a1495db5cd82fccda5823a84e41677bcc472e2d | [
"Apache-2.0"
] | null | null | null | tests/common/src/main/java/org/springframework/cloud/sleuth/otel/OtelTestTracing.java | maxxedev/spring-cloud-sleuth | 6a1495db5cd82fccda5823a84e41677bcc472e2d | [
"Apache-2.0"
] | null | null | null | tests/common/src/main/java/org/springframework/cloud/sleuth/otel/OtelTestTracing.java | maxxedev/spring-cloud-sleuth | 6a1495db5cd82fccda5823a84e41677bcc472e2d | [
"Apache-2.0"
] | null | null | null | 34.192771 | 112 | 0.804968 | 997,205 | /*
* Copyright 2013-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.sleuth.otel;
import java.io.Closeable;
import java.util.regex.Pattern;
import io.opentelemetry.api.OpenTelemetry;
import io.opentelemetry.context.propagation.ContextPropagators;
import io.opentelemetry.context.propagation.DefaultContextPropagators;
import io.opentelemetry.extension.trace.propagation.B3Propagator;
import io.opentelemetry.sdk.trace.TracerSdkProvider;
import io.opentelemetry.sdk.trace.config.TraceConfig;
import io.opentelemetry.sdk.trace.samplers.Sampler;
import org.springframework.cloud.sleuth.api.CurrentTraceContext;
import org.springframework.cloud.sleuth.api.SamplerFunction;
import org.springframework.cloud.sleuth.api.Tracer;
import org.springframework.cloud.sleuth.api.http.HttpClientHandler;
import org.springframework.cloud.sleuth.api.http.HttpRequestParser;
import org.springframework.cloud.sleuth.api.http.HttpServerHandler;
import org.springframework.cloud.sleuth.api.propagation.Propagator;
import org.springframework.cloud.sleuth.autoconfig.SleuthBaggageProperties;
import org.springframework.cloud.sleuth.otel.bridge.OtelBaggageManager;
import org.springframework.cloud.sleuth.otel.bridge.OtelCurrentTraceContext;
import org.springframework.cloud.sleuth.otel.bridge.OtelPropagator;
import org.springframework.cloud.sleuth.otel.bridge.OtelTracer;
import org.springframework.cloud.sleuth.otel.bridge.http.OtelHttpClientHandler;
import org.springframework.cloud.sleuth.otel.bridge.http.OtelHttpServerHandler;
import org.springframework.cloud.sleuth.otel.exporter.ArrayListSpanProcessor;
import org.springframework.cloud.sleuth.test.TestSpanHandler;
import org.springframework.cloud.sleuth.test.TestTracingAssertions;
import org.springframework.cloud.sleuth.test.TestTracingAware;
import org.springframework.cloud.sleuth.test.TestTracingAwareSupplier;
import org.springframework.cloud.sleuth.test.TracerAware;
import org.springframework.context.ApplicationEventPublisher;
public class OtelTestTracing implements TracerAware, TestTracingAware, TestTracingAwareSupplier, Closeable {
ArrayListSpanProcessor spanProcessor = new ArrayListSpanProcessor();
ContextPropagators defaultContextPropagators = OpenTelemetry.getGlobalPropagators();
ContextPropagators contextPropagators = contextPropagators();
Sampler sampler = Sampler.alwaysOn();
HttpRequestParser clientRequestParser;
io.opentelemetry.api.trace.Tracer tracer = otelTracer();
OtelCurrentTraceContext currentTraceContext = new OtelCurrentTraceContext(publisher());
OtelBaggageManager otelBaggageManager = new OtelBaggageManager(this.currentTraceContext,
new SleuthBaggageProperties(), publisher());
io.opentelemetry.api.trace.Tracer otelTracer() {
TracerSdkProvider provider = TracerSdkProvider.builder().build();
provider.addSpanProcessor(this.spanProcessor);
OpenTelemetry.setGlobalPropagators(this.contextPropagators);
provider.updateActiveTraceConfig(TraceConfig.getDefault().toBuilder().setSampler(this.sampler).build());
return provider.get("org.springframework.cloud.sleuth");
}
protected ContextPropagators contextPropagators() {
return DefaultContextPropagators.builder()
.addTextMapPropagator(B3Propagator.builder().injectMultipleHeaders().build()).build();
}
private void reset() {
this.contextPropagators = contextPropagators();
this.tracer = otelTracer();
this.currentTraceContext = new OtelCurrentTraceContext(publisher());
}
@Override
public TracerAware sampler(TraceSampler sampler) {
this.sampler = sampler == TraceSampler.ON ? Sampler.alwaysOn() : Sampler.alwaysOff();
return this;
}
@Override
public TracerAware tracing() {
return this;
}
@Override
public TestSpanHandler handler() {
return new OtelTestSpanHandler(this.spanProcessor);
}
@Override
public TestTracingAssertions assertions() {
return new OtelTestTracingAssertions();
}
@Override
public void close() {
this.spanProcessor.clear();
OpenTelemetry.setGlobalPropagators(this.defaultContextPropagators);
this.sampler = Sampler.alwaysOn();
}
@Override
public TestTracingAware tracerTest() {
return this;
}
@Override
public Tracer tracer() {
reset();
return OtelTracer.fromOtel(this.tracer, this.otelBaggageManager);
}
@Override
public CurrentTraceContext currentTraceContext() {
reset();
return new OtelCurrentTraceContext(publisher());
}
@Override
public Propagator propagator() {
reset();
return new OtelPropagator(this.contextPropagators, this.tracer);
}
@Override
public HttpServerHandler httpServerHandler() {
reset();
return new OtelHttpServerHandler(this.tracer, null, null, () -> Pattern.compile(""));
}
@Override
public TracerAware clientRequestParser(HttpRequestParser httpRequestParser) {
this.clientRequestParser = httpRequestParser;
return this;
}
@Override
public HttpClientHandler httpClientHandler() {
reset();
return new OtelHttpClientHandler(this.tracer, this.clientRequestParser, null, SamplerFunction.alwaysSample());
}
ApplicationEventPublisher publisher() {
return event -> {
};
}
}
|
923538c7a0b79fd9d1f5d10e50124ab001a75058 | 22,845 | java | Java | openfire.plugin.demeter_service_api/src/java/com/sercomm/openfire/plugin/service/api/v2/InstallationsAPI.java | Sercomm-Demeter-group/lcmdemeter | c7be2d7aee26d292deef13c5b0d6ce25bc7e2caa | [
"Apache-2.0"
] | null | null | null | openfire.plugin.demeter_service_api/src/java/com/sercomm/openfire/plugin/service/api/v2/InstallationsAPI.java | Sercomm-Demeter-group/lcmdemeter | c7be2d7aee26d292deef13c5b0d6ce25bc7e2caa | [
"Apache-2.0"
] | null | null | null | openfire.plugin.demeter_service_api/src/java/com/sercomm/openfire/plugin/service/api/v2/InstallationsAPI.java | Sercomm-Demeter-group/lcmdemeter | c7be2d7aee26d292deef13c5b0d6ce25bc7e2caa | [
"Apache-2.0"
] | 1 | 2020-11-10T08:39:03.000Z | 2020-11-10T08:39:03.000Z | 32.917867 | 142 | 0.492143 | 997,206 | package com.sercomm.openfire.plugin.service.api.v2;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
import org.jivesoftware.database.DbConnectionManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.sercomm.commons.umei.BodyPayload;
import com.sercomm.commons.umei.Meta;
import com.sercomm.commons.util.HttpUtil;
import com.sercomm.commons.util.XStringUtil;
import com.sercomm.openfire.plugin.AppManager;
import com.sercomm.openfire.plugin.data.frontend.App;
import com.sercomm.openfire.plugin.data.frontend.AppVersion;
import com.sercomm.openfire.plugin.define.EndUserRole;
import com.sercomm.openfire.plugin.service.annotation.RequireRoles;
import com.sercomm.openfire.plugin.service.api.ServiceAPIBase;
import com.sercomm.openfire.plugin.service.util.StringStreamingOutput;
@Path(InstallationsAPI.URI_PATH)
@RequireRoles({EndUserRole.ADMIN, EndUserRole.EDITOR, EndUserRole.OPERATOR})
public class InstallationsAPI extends ServiceAPIBase
{
private static final Logger log = LoggerFactory.getLogger(InstallationsAPI.class);
protected static final String URI_PATH = ServiceAPIBase.URI_PATH + "v2/";
@Context
private HttpServletRequest request;
@GET
@Path("installations")
@Produces({MediaType.APPLICATION_JSON})
public Response get(
@QueryParam("from") Integer from,
@QueryParam("size") Integer size,
@QueryParam("applicationId") String applicationId,
@QueryParam("versionId") String versionId,
@QueryParam("status") String statusValue,
@QueryParam("filter") List<String> filters)
throws UMEiException, InternalErrorException
{
Response response = null;
Response.Status status = Status.OK;
final String userId = (String) request.getAttribute("userId");
final String sessionId = (String) request.getAttribute("sessionId");
String errorMessage = XStringUtil.BLANK;
try
{
if(XStringUtil.isBlank(applicationId) || XStringUtil.isBlank(versionId) || XStringUtil.isBlank(statusValue))
{
status = Response.Status.BAD_REQUEST;
errorMessage = "MANDATORY PARAMETER(S) WAS BLANK";
throw new UMEiException(errorMessage, status);
}
App app = AppManager.getInstance().getApp(applicationId);
AppVersion version = AppManager.getInstance().getAppVersion(versionId);
InstallStatus installStatus = InstallStatus.fromString(statusValue);
if(null == installStatus)
{
status = Response.Status.BAD_REQUEST;
errorMessage = "INVALID `status` PARAMETER";
throw new UMEiException(errorMessage, status);
}
int totalCount = 0;
// query total rows count
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try
{
List<Object> arguments = new ArrayList<>();
conn = DbConnectionManager.getConnection();
stmt = conn.prepareStatement(
generateQueryTotalStatement(
applicationId,
versionId,
installStatus,
filters,
arguments));
for(int idx = 0; idx < arguments.size(); idx++)
{
stmt.setObject(idx + 1, arguments.get(idx));
}
rs = stmt.executeQuery();
rs.next();
totalCount = rs.getInt("count");
}
finally
{
DbConnectionManager.closeConnection(rs, stmt, conn);
}
// query rows data
List<GetInstallationResult> result = new ArrayList<>();
try
{
List<Object> arguments = new ArrayList<>();
conn = DbConnectionManager.getConnection();
stmt = conn.prepareStatement(
generateQueryRowsStatement(
from,
size,
applicationId,
versionId,
installStatus,
filters,
arguments));
for(int idx = 0; idx < arguments.size(); idx++)
{
stmt.setObject(idx + 1, arguments.get(idx));
}
rs = stmt.executeQuery();
while(rs.next())
{
String serial = rs.getString("serial");
String mac = rs.getString("mac");
GetInstallationResult object = new GetInstallationResult();
object.setSerial(serial);
object.setMac(mac);
object.setApplication(app.getName());
object.setVersion(version.getVersion());
object.setStatus(Integer.parseInt(statusValue));
result.add(object);
}
}
finally
{
DbConnectionManager.closeConnection(rs, stmt, conn);
}
// response
BodyPayload bodyPayload = new BodyPayload()
.withMeta(new Meta()
.withFrom(from == null ? 0 : from)
.withSize(result.size())
.withTotal(totalCount))
.withData(result);
response = Response
.status(status)
.type(MediaType.APPLICATION_JSON)
.entity(bodyPayload.toString())
.build();
}
catch(UMEiException e)
{
status = e.getErrorStatus();
errorMessage = e.getMessage();
throw e;
}
catch(Throwable t)
{
status = Response.Status.INTERNAL_SERVER_ERROR;
errorMessage = org.apache.commons.lang.exception.ExceptionUtils.getStackTrace(t);
throw new InternalErrorException(t.getMessage());
}
log.info("({},{},{},{},{},{},{},{}); {}",
userId,
sessionId,
from,
size,
applicationId,
versionId,
statusValue,
filters,
XStringUtil.isNotBlank(errorMessage) ? status.getStatusCode() + ",errors: " + errorMessage : status.getStatusCode());
return response;
}
@GET
@Path("installations/export")
@Produces({MediaType.APPLICATION_JSON})
public Response export(
@QueryParam("applicationId") String applicationId,
@QueryParam("versionId") String versionId,
@QueryParam("status") String statusValue,
@QueryParam("filter") List<String> filters)
throws UMEiException, InternalErrorException
{
Response response = null;
Response.Status status = Status.OK;
final String userId = (String) request.getAttribute("userId");
final String sessionId = (String) request.getAttribute("sessionId");
final String[] FILE_HEADER = {"Serial", "MAC"};
final String FILE_NAME = "export.csv";
final CSVFormat formatter = CSVFormat.DEFAULT.withHeader(FILE_HEADER).withSkipHeaderRecord();
final StringBuilder output = new StringBuilder();
String errorMessage = XStringUtil.BLANK;
try
{
// query rows data
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try
{
if(XStringUtil.isBlank(applicationId) || XStringUtil.isBlank(versionId) || XStringUtil.isBlank(statusValue))
{
status = Response.Status.BAD_REQUEST;
errorMessage = "MANDATORY PARAMETER(S) WAS BLANK";
throw new UMEiException(errorMessage, status);
}
// validate application ID and version ID
AppManager.getInstance().getApp(applicationId);
AppManager.getInstance().getAppVersion(versionId);
InstallStatus installStatus = InstallStatus.fromString(statusValue);
if(null == installStatus)
{
status = Response.Status.BAD_REQUEST;
errorMessage = "INVALID `status` PARAMETER";
throw new UMEiException(errorMessage, status);
}
List<Object> arguments = new ArrayList<>();
conn = DbConnectionManager.getConnection();
stmt = conn.prepareStatement(
generateQueryRowsStatement(
null,
null,
applicationId,
versionId,
installStatus,
filters,
arguments));
for(int idx = 0; idx < arguments.size(); idx++)
{
stmt.setObject(idx + 1, arguments.get(idx));
}
rs = stmt.executeQuery();
try(CSVPrinter printer = new CSVPrinter(output, formatter))
{
while(rs.next())
{
List<String> records = new ArrayList<>();
records.add(rs.getString("serial"));
records.add(rs.getString("mac"));
printer.printRecord(records);
}
}
}
finally
{
DbConnectionManager.closeConnection(rs, stmt, conn);
}
response = Response.ok(new StringStreamingOutput(output.toString()))
.type(MediaType.APPLICATION_OCTET_STREAM)
.header(HttpUtil.HEADER_CONTEXT_DISPOS, String.format("attachment; filename=\"%s\"", FILE_NAME))
.build();
}
catch(UMEiException e)
{
status = e.getErrorStatus();
errorMessage = e.getMessage();
throw e;
}
catch(Throwable t)
{
status = Response.Status.INTERNAL_SERVER_ERROR;
errorMessage = org.apache.commons.lang.exception.ExceptionUtils.getStackTrace(t);
throw new InternalErrorException(t.getMessage());
}
log.info("({},{},{}); {}",
userId,
sessionId,
filters,
XStringUtil.isNotBlank(errorMessage) ? status.getStatusCode() + ",errors: " + errorMessage : status.getStatusCode());
return response;
}
private static String generateQueryTotalStatement(
String applicationId,
String versionId,
InstallStatus installStatus,
List<String> filters,
List<Object> arguments)
throws UMEiException, InternalErrorException
{
StringBuilder builder = new StringBuilder();
builder.append("SELECT COUNT(*) AS `count` FROM (");
builder.append("SELECT `serial`,`mac` FROM `sDeviceProp` AS `t1` WHERE ");
switch(installStatus)
{
case INSTALLED:
builder.append("EXISTS ");
break;
case NOT_INSTALLED:
builder.append("NOT EXISTS ");
break;
}
builder.append("(SELECT * FROM `sAppInstallation` WHERE `serial`=`t1`.serial AND `mac`=`t1`.`mac` AND `appId`=? AND `versionId`=?) ");
arguments.add(applicationId);
arguments.add(versionId);
List<String[]> idFilters = new ArrayList<>();
List<String[]> propFilters = new ArrayList<>();
if(!filters.isEmpty())
{
builder.append("AND ");
// preprocess the filters
Iterator<String> iterator = filters.iterator();
while(iterator.hasNext())
{
final String filter = iterator.next();
String[] tokens = filter.split(":", 2);
if(2 != tokens.length)
{
throw new UMEiException(
"INVALID FILTER: " + filter,
Response.Status.BAD_REQUEST);
}
switch(tokens[0])
{
case "serial":
idFilters.add(tokens);
break;
case "mac":
idFilters.add(tokens);
break;
case "model":
propFilters.add(tokens);
break;
case "firmware":
propFilters.add(tokens);
break;
default:
throw new UMEiException(
"INVALID FILTER ATTRIBUTE: " + tokens[0],
Response.Status.BAD_REQUEST);
}
}
}
// filter serial and mac
Iterator<String[]> iterator = idFilters.iterator();
while(iterator.hasNext())
{
final String[] tokens = iterator.next();
switch(tokens[0])
{
case "serial":
builder.append("`t1`.`serial` LIKE ? ");
arguments.add(tokens[1] + "%");
break;
case "mac":
builder.append("`t1`.`mac` LIKE ? ");
arguments.add(tokens[1] + "%");
break;
}
if(iterator.hasNext())
{
builder.append("AND ");
}
else
{
if(!propFilters.isEmpty())
{
builder.append("AND ");
}
}
}
int filterPropCount = 0;
// filter properties
iterator = propFilters.iterator();
while(iterator.hasNext())
{
final String[] tokens = iterator.next();
switch(tokens[0])
{
case "model":
builder.append("(`name`='sercomm.device.model.name' AND `propValue` LIKE ?) ");
arguments.add(tokens[1] + "%");
filterPropCount++;
break;
case "firmware":
builder.append("(`name`='sercomm.device.firmware.version' AND `propValue` LIKE ?) ");
arguments.add(tokens[1] + "%");
filterPropCount++;
break;
}
if(iterator.hasNext())
{
builder.append("OR ");
}
}
builder.append("GROUP BY `t1`.`serial`,`t1`.`mac` ");
builder.append("HAVING COUNT(`t1`.`serial`) > ? AND COUNT(`t1`.`mac`) > ?");
arguments.add(filterPropCount == 0 ? 0 : filterPropCount - 1);
arguments.add(filterPropCount == 0 ? 0 : filterPropCount - 1);
builder.append(") AS `t`");
return builder.toString();
}
private static String generateQueryRowsStatement(
Integer from,
Integer size,
String applicationId,
String versionId,
InstallStatus installStatus,
List<String> filters,
List<Object> arguments)
throws UMEiException, InternalErrorException
{
StringBuilder builder = new StringBuilder();
builder.append("SELECT `serial`,`mac` FROM `sDeviceProp` AS `t1` WHERE ");
switch(installStatus)
{
case INSTALLED:
builder.append("EXISTS ");
break;
case NOT_INSTALLED:
builder.append("NOT EXISTS ");
break;
}
builder.append("(SELECT * FROM `sAppInstallation` WHERE `serial`=`t1`.serial AND `mac`=`t1`.`mac` AND `appId`=? AND `versionId`=?) ");
arguments.add(applicationId);
arguments.add(versionId);
List<String[]> idFilters = new ArrayList<>();
List<String[]> propFilters = new ArrayList<>();
if(!filters.isEmpty())
{
builder.append("AND ");
// preprocess the filters
Iterator<String> iterator = filters.iterator();
while(iterator.hasNext())
{
final String filter = iterator.next();
String[] tokens = filter.split(":", 2);
if(2 != tokens.length)
{
throw new UMEiException(
"INVALID FILTER: " + filter,
Response.Status.BAD_REQUEST);
}
switch(tokens[0])
{
case "serial":
idFilters.add(tokens);
break;
case "mac":
idFilters.add(tokens);
break;
case "model":
propFilters.add(tokens);
break;
case "firmware":
propFilters.add(tokens);
break;
default:
throw new UMEiException(
"INVALID FILTER ATTRIBUTE: " + tokens[0],
Response.Status.BAD_REQUEST);
}
}
}
// filter serial and mac
Iterator<String[]> iterator = idFilters.iterator();
while(iterator.hasNext())
{
final String[] tokens = iterator.next();
switch(tokens[0])
{
case "serial":
builder.append("`t1`.`serial` LIKE ? ");
arguments.add(tokens[1] + "%");
break;
case "mac":
builder.append("`t1`.`mac` LIKE ? ");
arguments.add(tokens[1] + "%");
break;
}
if(iterator.hasNext())
{
builder.append("AND ");
}
else
{
if(!propFilters.isEmpty())
{
builder.append("AND ");
}
}
}
int filterPropCount = 0;
// filter properties
iterator = propFilters.iterator();
while(iterator.hasNext())
{
final String[] tokens = iterator.next();
switch(tokens[0])
{
case "model":
builder.append("(`name`='sercomm.device.model.name' AND `propValue` LIKE ?) ");
arguments.add(tokens[1]);
filterPropCount++;
break;
case "firmware":
builder.append("(`name`='sercomm.device.firmware.version' AND `propValue` LIKE ?) ");
arguments.add(tokens[1]);
filterPropCount++;
break;
}
if(iterator.hasNext())
{
builder.append("OR ");
}
}
builder.append("GROUP BY `t1`.`serial`,`t1`.`mac` ");
builder.append("HAVING COUNT(`t1`.`serial`) > ? AND COUNT(`t1`.`mac`) > ? ");
arguments.add(filterPropCount == 0 ? 0 : filterPropCount - 1);
arguments.add(filterPropCount == 0 ? 0 : filterPropCount - 1);
if(null != from && null != size)
{
builder.append("LIMIT ?,?");
arguments.add(from);
arguments.add(size);
}
return builder.toString();
}
public enum InstallStatus
{
INSTALLED(1),
NOT_INSTALLED(2);
private static Map<String, InstallStatus> map =
new ConcurrentHashMap<>();
static
{
for(InstallStatus installStatus : InstallStatus.values())
{
map.put(installStatus.toString(), installStatus);
}
}
private Integer value;
private InstallStatus(Integer value)
{
this.value = value;
}
@Override
public String toString()
{
return Integer.toString(this.value);
}
public int intValue()
{
return this.value;
}
public static InstallStatus fromString(String value)
{
return map.get(value);
}
}
public static class GetInstallationResult
{
private String serial;
private String mac;
private String application;
private String version;
private Integer status;
public String getSerial()
{
return serial;
}
public void setSerial(String serial)
{
this.serial = serial;
}
public String getMac()
{
return mac;
}
public void setMac(String mac)
{
this.mac = mac;
}
public String getApplication()
{
return application;
}
public void setApplication(String application)
{
this.application = application;
}
public String getVersion()
{
return version;
}
public void setVersion(String version)
{
this.version = version;
}
public Integer getStatus()
{
return status;
}
public void setStatus(Integer status)
{
this.status = status;
}
}
}
|
923538dfde796b17a4aff402590dc23317190c54 | 2,269 | java | Java | embedded-database-spring-test/src/test/java/io/zonky/test/db/provider/ZonkyProviderWithConfigurationIntegrationTest.java | MOOM-Planet/embedded-database-spring-test | c5be9f9f95b317b1181de41765c3e9f0422b595c | [
"Apache-2.0"
] | null | null | null | embedded-database-spring-test/src/test/java/io/zonky/test/db/provider/ZonkyProviderWithConfigurationIntegrationTest.java | MOOM-Planet/embedded-database-spring-test | c5be9f9f95b317b1181de41765c3e9f0422b595c | [
"Apache-2.0"
] | null | null | null | embedded-database-spring-test/src/test/java/io/zonky/test/db/provider/ZonkyProviderWithConfigurationIntegrationTest.java | MOOM-Planet/embedded-database-spring-test | c5be9f9f95b317b1181de41765c3e9f0422b595c | [
"Apache-2.0"
] | null | null | null | 33.367647 | 102 | 0.767298 | 997,207 | /*
* Copyright 2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.zonky.test.db.provider;
import io.zonky.test.db.AutoConfigureEmbeddedDatabase;
import io.zonky.test.db.postgres.embedded.EmbeddedPostgres;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.postgresql.ds.PGSimpleDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.SocketUtils;
import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.function.Consumer;
import static io.zonky.test.db.AutoConfigureEmbeddedDatabase.DatabaseProvider.ZONKY;
import static org.assertj.core.api.Assertions.assertThat;
@RunWith(SpringRunner.class)
@AutoConfigureEmbeddedDatabase(beanName = "dataSource", provider = ZONKY)
@ContextConfiguration
public class ZonkyProviderWithConfigurationIntegrationTest {
@Configuration
static class Config {
@Bean
public Integer randomPort() {
return SocketUtils.findAvailableTcpPort();
}
@Bean
public Consumer<EmbeddedPostgres.Builder> embeddedPostgresCustomizer(Integer randomPort) {
return builder -> builder.setPort(randomPort);
}
}
@Autowired
private Integer randomPort;
@Autowired
private DataSource dataSource;
@Test
public void testDataSource() throws SQLException {
assertThat(dataSource.unwrap(PGSimpleDataSource.class).getPortNumber()).isEqualTo(randomPort);
}
}
|
92353923545c6ef6095dc6af35901262c097e23a | 406 | java | Java | deployment-web/src/main/java/io/ideploy/deployment/admin/websocket/request/CookieRequestMessage.java | kevinYin/ideploy | 0622c9641fb370422a147f04ea65476040fb56c6 | [
"Apache-2.0"
] | null | null | null | deployment-web/src/main/java/io/ideploy/deployment/admin/websocket/request/CookieRequestMessage.java | kevinYin/ideploy | 0622c9641fb370422a147f04ea65476040fb56c6 | [
"Apache-2.0"
] | null | null | null | deployment-web/src/main/java/io/ideploy/deployment/admin/websocket/request/CookieRequestMessage.java | kevinYin/ideploy | 0622c9641fb370422a147f04ea65476040fb56c6 | [
"Apache-2.0"
] | 1 | 2020-08-06T08:47:56.000Z | 2020-08-06T08:47:56.000Z | 15.615385 | 66 | 0.625616 | 997,208 | package io.ideploy.deployment.admin.websocket.request;
/**
* 功能: 发送cookie的请求
* <p>
* 详细:
*
* @author jingyesi 17/2/4
*/
public class CookieRequestMessage extends WebSocketRequestMessage{
/**
* cookie
*/
private String cookies;
public String getCookies() {
return cookies;
}
public void setCookies(String cookies) {
this.cookies = cookies;
}
}
|
92353969598c7238ce7e8fc7897adf0e7531cb5c | 1,570 | java | Java | api-gateway/image-microservice/src/test/java/com/anshul/image/microservice/ImageControllerTest.java | Ansh90/DesignProblems | 99f2edd23a7560118323fdc047bc993a7283d95a | [
"Apache-2.0"
] | 1 | 2018-09-18T15:54:52.000Z | 2018-09-18T15:54:52.000Z | api-gateway/image-microservice/src/test/java/com/anshul/image/microservice/ImageControllerTest.java | Ansh90/DesignProblems | 99f2edd23a7560118323fdc047bc993a7283d95a | [
"Apache-2.0"
] | null | null | null | api-gateway/image-microservice/src/test/java/com/anshul/image/microservice/ImageControllerTest.java | Ansh90/DesignProblems | 99f2edd23a7560118323fdc047bc993a7283d95a | [
"Apache-2.0"
] | null | null | null | 37.380952 | 80 | 0.757325 | 997,209 | /**
* The MIT License
* Copyright (c) 2018 Anshul Mohil
*
* 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 com.anshul.image.microservice;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Test for Image Rest Controller
*/
public class ImageControllerTest {
@Test
public void testGetImagePath() {
ImageController imageController = new ImageController();
String imagePath = imageController.getImagePath();
assertEquals("/product-image.png", imagePath);
}
}
|
923539d1167e841e29bdae1b08d35bda9513e578 | 3,427 | java | Java | src/me/learn/personal/month4/PalindromePairs.java | balajiboggaram/algorithms | bf09f56210c6a329914e09d94dad78c4226f524d | [
"Apache-2.0"
] | null | null | null | src/me/learn/personal/month4/PalindromePairs.java | balajiboggaram/algorithms | bf09f56210c6a329914e09d94dad78c4226f524d | [
"Apache-2.0"
] | null | null | null | src/me/learn/personal/month4/PalindromePairs.java | balajiboggaram/algorithms | bf09f56210c6a329914e09d94dad78c4226f524d | [
"Apache-2.0"
] | null | null | null | 29.8 | 106 | 0.658302 | 997,210 | package me.learn.personal.month4;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
*
* Title 336 :
*
* Given a list of unique words, find all pairs of distinct indices (i, j) in
* the given list, so that the concatenation of the two words, i.e. words[i] +
* words[j] is a palindrome.
*
* Example 1:
*
* Input: ["abcd","dcba","lls","s","sssll"] Output: [[0,1],[1,0],[3,2],[2,4]]
* Explanation: The palindromes are ["dcbaabcd","abcddcba","slls","llssssll"]
*
* Example 2:
*
* Input: ["bat","tab","cat"] Output: [[0,1],[1,0]] Explanation: The palindromes
* are ["battab","tabbat"]
*
*
*
* @author bramanarayan
* @date Aug 21, 2020
*/
public class PalindromePairs {
public static void main(String args[]) {
PalindromePairs solution = new PalindromePairs();
System.out.println(solution.palindromePairs(new String[] {"race","car"}));
System.out.println(solution.palindromePairs(new String[] {"abcd","dcba","lls","s","sssll"}));
}
// REPEAT
public List<List<String>> palindromePairs(String[] words) {
// REVERSE WORDS
Set<String> reversedWords = new HashSet<>();
for(String w : words) {
reversedWords.add(new StringBuilder(w).reverse().toString());
}
// NOW FIND PALIN BASED ON REVERSE WORDS
List<List<String>> result = new ArrayList<List<String>>();
for(String w : words) {
Set<String> palindromePairs = findPalindromeHelper(w, reversedWords);
result.add(new ArrayList<>(palindromePairs));
}
return result;
}
private Set<String> findPalindromeHelper(String w, Set<String> reversedWords) {
Set<String> palindromes = new HashSet<>();
// if same length word already exists
if(reversedWords.contains(w)) {
String reversedWord = new StringBuilder(w).reverse().toString();
if(!reversedWord.equals(w)) {
// it cannot be the same word. malayalam - we need a pairing to each other, hence this condition
palindromes.add(w + reversedWord);
}
}
// check if we can form a palindrome by concating two words with different length by appending the other
// word to the back of the given word.
for (int i = 1; i < w.length() - 1; i++) {
String takenOutString = w.substring(w.length() - 1); // right side
String remainingString = w.substring(0, w.length() - i); // left side
if (isPalindrome(takenOutString) && reversedWords.contains(remainingString)) {
String palindrome = remainingString + takenOutString
+ new StringBuilder(remainingString).reverse().toString();
palindromes.add(palindrome);
}
}
// check if we can form a palindrome by concatenating two words
// with different length by appending the other word to the front of given word
for(int i =1;i< w.length()-1;i++) {
String takenOutStr = w.substring(0,i);
String remainingStr = w.substring(i);
if (isPalindrome(takenOutStr) && reversedWords.contains(remainingStr)) {
String palindrome =
new StringBuilder(remainingStr).reverse().toString() + takenOutStr + remainingStr;
palindromes.add(palindrome);
}
}
return palindromes;
}
private boolean isPalindrome(String string) {
int left = 0;
int right = string.length() - 1;
while (left < right) {
if (string.charAt(left) != string.charAt(right)) {
return false;
}
left++;
right--;
}
return true;
}
}
|
923539e43968fac5bf9fa8294ce099cdc648baba | 410 | java | Java | grapheus-model/src/main/java/org/grapheus/client/model/graph/operation/RVerticesRemoveOperationContainer.java | black32167/grapheus | 2380fd4102b24c088e1d224077e3f7f7ad65d4f2 | [
"MIT"
] | null | null | null | grapheus-model/src/main/java/org/grapheus/client/model/graph/operation/RVerticesRemoveOperationContainer.java | black32167/grapheus | 2380fd4102b24c088e1d224077e3f7f7ad65d4f2 | [
"MIT"
] | 6 | 2019-06-12T13:24:54.000Z | 2019-09-24T03:01:13.000Z | grapheus-model/src/main/java/org/grapheus/client/model/graph/operation/RVerticesRemoveOperationContainer.java | black32167/jgraph | 2380fd4102b24c088e1d224077e3f7f7ad65d4f2 | [
"MIT"
] | null | null | null | 16.4 | 50 | 0.770732 | 997,211 | /**
*
*/
package org.grapheus.client.model.graph.operation;
import java.util.Collection;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @author black
*
*/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class RVerticesRemoveOperationContainer {
private String graphId;
private Collection<String> verticesIds;
}
|
92353b793bf63f4a7f22595d7ec31d0e934759f7 | 1,927 | java | Java | src/main/java/org/mindswap/exceptions/CastingException.java | adrianoqueiroz/owls-api | 9bf87540874adee7224df9095100ddfdf8753549 | [
"MIT"
] | 1 | 2018-10-05T19:32:40.000Z | 2018-10-05T19:32:40.000Z | src/main/java/org/mindswap/exceptions/CastingException.java | adrianoqueiroz/owls-api | 9bf87540874adee7224df9095100ddfdf8753549 | [
"MIT"
] | null | null | null | src/main/java/org/mindswap/exceptions/CastingException.java | adrianoqueiroz/owls-api | 9bf87540874adee7224df9095100ddfdf8753549 | [
"MIT"
] | null | null | null | 29.19697 | 104 | 0.697976 | 997,213 | /*
* Created on Dec 12, 2004
*/
package org.mindswap.exceptions;
import org.mindswap.owl.OWLObject;
import org.mindswap.owl.OWLType;
/**
* Used to indicate that conversion of some OWL object instance to another
* OWL type was not possible.
* <p>
* This exception can be thrown by {@link org.mindswap.owl.OWLObjectConverter}.
*
* @author unascribed
* @version $Rev: 2269 $; $Author: thorsten $; $Date: 2009-08-19 18:21:09 +0300 (Wed, 19 Aug 2009) $
*/
public class CastingException extends RuntimeException
{
private static final long serialVersionUID = 7939752388079955235L;
/**
* @see RuntimeException#RuntimeException()
*/
public CastingException()
{
super();
}
/**
* @see RuntimeException#RuntimeException(String)
*/
public CastingException(final String message)
{
super(message);
}
/**
* Create a conversion exception indicating that the source object cannot
* be viewed as an instance of the target type.
*
* @param source The source object instance whose conversion was impossible.
* @param target The target type.
* @return A new casting exception.
*/
public static CastingException create(final OWLObject source, final Class<? extends OWLObject> target)
{
return new CastingException(
String.format("Instance of %s %s cannot be viewed as %s.", source.getClass(), source, target));
}
/**
* Create a conversion exception indicating that the source object cannot
* be viewed as an instance of the target type.
*
* @param source The source object instance whose conversion was impossible.
* @param target The target type.
* @return A new casting exception.
*/
public static CastingException create(final OWLObject source, final OWLType target)
{
return new CastingException(
String.format("Instance of %s %s cannot be viewed as %s.", source.getClass(), source, target));
}
}
|
92353b8ff4c115fb7ef8f16400469a97fbd0872a | 23,915 | java | Java | src/main/java/com/binance/api/client/impl/BinanceApiService.java | aladingg/binance-java-api | 70abbf7bf8b3186e73128f9eda09079246f7ad87 | [
"MIT"
] | null | null | null | src/main/java/com/binance/api/client/impl/BinanceApiService.java | aladingg/binance-java-api | 70abbf7bf8b3186e73128f9eda09079246f7ad87 | [
"MIT"
] | null | null | null | src/main/java/com/binance/api/client/impl/BinanceApiService.java | aladingg/binance-java-api | 70abbf7bf8b3186e73128f9eda09079246f7ad87 | [
"MIT"
] | null | null | null | 55.876168 | 201 | 0.672423 | 997,214 | package com.binance.api.client.impl;
import com.binance.api.client.constant.BinanceApiConstants;
import com.binance.api.client.domain.OrderSide;
import com.binance.api.client.domain.OrderType;
import com.binance.api.client.domain.SwapRemoveType;
import com.binance.api.client.domain.TimeInForce;
import com.binance.api.client.domain.account.*;
import com.binance.api.client.domain.account.request.CancelOrderResponse;
import com.binance.api.client.domain.event.ListenKey;
import com.binance.api.client.domain.general.Coin;
import com.binance.api.client.domain.general.ExchangeInfo;
import com.binance.api.client.domain.general.ServerTime;
import com.binance.api.client.domain.market.*;
import retrofit2.Call;
import retrofit2.http.*;
import java.util.List;
/**
* Binance's REST API URL mappings and endpoint security configuration.
*/
public interface BinanceApiService {
// General endpoints
@GET("/api/v1/ping")
Call<Void> ping();
@GET("/api/v1/time")
Call<ServerTime> getServerTime();
@GET("/api/v1/exchangeInfo")
Call<ExchangeInfo> getExchangeInfo();
@Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER)
@GET("/sapi/v1/capital/config/getall")
Call<List<Coin>> getAllCoins(@Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp);
// Market data endpoints
@GET("/api/v1/depth")
Call<OrderBook> getOrderBook(@Query("symbol") String symbol, @Query("limit") Integer limit);
@GET("/api/v1/trades")
Call<List<TradeHistoryItem>> getTrades(@Query("symbol") String symbol, @Query("limit") Integer limit);
@Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER)
@GET("/api/v1/historicalTrades")
Call<List<TradeHistoryItem>> getHistoricalTrades(@Query("symbol") String symbol, @Query("limit") Integer limit, @Query("fromId") Long fromId);
@GET("/api/v1/aggTrades")
Call<List<AggTrade>> getAggTrades(@Query("symbol") String symbol, @Query("fromId") String fromId, @Query("limit") Integer limit,
@Query("startTime") Long startTime, @Query("endTime") Long endTime);
@GET("/api/v1/klines")
Call<List<Candlestick>> getCandlestickBars(@Query("symbol") String symbol, @Query("interval") String interval, @Query("limit") Integer limit,
@Query("startTime") Long startTime, @Query("endTime") Long endTime);
@GET("/api/v1/ticker/24hr")
Call<TickerStatistics> get24HrPriceStatistics(@Query("symbol") String symbol);
@GET("/api/v1/ticker/24hr")
Call<List<TickerStatistics>> getAll24HrPriceStatistics();
@GET("/api/v3/ticker/price")
Call<List<TickerPrice>> getLatestPrices();
@GET("/api/v3/ticker/price")
Call<TickerPrice> getLatestPrice(@Query("symbol") String symbol);
@GET("/api/v1/ticker/allBookTickers")
Call<List<BookTicker>> getBookTickers();
// Account endpoints
@Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER)
@POST("/api/v3/order")
Call<NewOrderResponse> newOrder(@Query("symbol") String symbol, @Query("side") OrderSide side, @Query("type") OrderType type,
@Query("timeInForce") TimeInForce timeInForce, @Query("quantity") String quantity, @Query("price") String price,
@Query("newClientOrderId") String newClientOrderId, @Query("stopPrice") String stopPrice,
@Query("icebergQty") String icebergQty, @Query("newOrderRespType") NewOrderResponseType newOrderRespType,
@Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp);
@Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER)
@POST("/api/v3/order")
Call<NewOrderResponse> newOrderQuoteQty(@Query("symbol") String symbol, @Query("side") OrderSide side, @Query("type") OrderType type,
@Query("timeInForce") TimeInForce timeInForce, @Query("quoteOrderQty") String quoteOrderQty, @Query("price") String price,
@Query("newClientOrderId") String newClientOrderId, @Query("stopPrice") String stopPrice,
@Query("icebergQty") String icebergQty, @Query("newOrderRespType") NewOrderResponseType newOrderRespType,
@Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp);
@Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER)
@POST("/api/v3/order/test")
Call<Void> newOrderTest(@Query("symbol") String symbol, @Query("side") OrderSide side, @Query("type") OrderType type,
@Query("timeInForce") TimeInForce timeInForce, @Query("quantity") String quantity, @Query("price") String price,
@Query("newClientOrderId") String newClientOrderId, @Query("stopPrice") String stopPrice,
@Query("icebergQty") String icebergQty, @Query("newOrderRespType") NewOrderResponseType newOrderRespType,
@Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp);
@Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER)
@GET("/api/v3/order")
Call<Order> getOrderStatus(@Query("symbol") String symbol, @Query("orderId") Long orderId,
@Query("origClientOrderId") String origClientOrderId, @Query("recvWindow") Long recvWindow,
@Query("timestamp") Long timestamp);
@Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER)
@DELETE("/api/v3/order")
Call<CancelOrderResponse> cancelOrder(@Query("symbol") String symbol, @Query("orderId") Long orderId,
@Query("origClientOrderId") String origClientOrderId, @Query("newClientOrderId") String newClientOrderId,
@Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp);
@Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER)
@GET("/api/v3/openOrders")
Call<List<Order>> getOpenOrders(@Query("symbol") String symbol, @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp);
@Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER)
@GET("/api/v3/allOrders")
Call<List<Order>> getAllOrders(@Query("symbol") String symbol, @Query("orderId") Long orderId,
@Query("limit") Integer limit, @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp);
@Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER)
@GET("/api/v3/allOrders")
Call<List<Order>> getAllOrders(@Query("symbol") String symbol, @Query("orderId") Long orderId, @Query("startTime") Long startTime,
@Query("endTime") Long endTime, @Query("limit") Integer limit, @Query("recvWindow") Long recvWindow,
@Query("timestamp") Long timestamp);
@Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER)
@GET("/api/v3/account")
Call<Account> getAccount(@Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp);
@Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER)
@GET("/api/v3/myTrades")
Call<List<Trade>> getMyTrades(@Query("symbol") String symbol, @Query("limit") Integer limit, @Query("fromId") Long fromId,
@Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp);
@Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER)
@GET("/api/v3/myTrades")
Call<List<Trade>> getMyTrades(@Query("symbol") String symbol, @Query("limit") Integer limit, @Query("fromId") Long fromId,
@Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp, @Query("startTime") Long startTime,
@Query("endTime") Long endTime);
// User stream endpoints
@Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER)
@POST("/api/v3/userDataStream")
Call<ListenKey> startUserDataStream();
@Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER)
@PUT("/api/v3/userDataStream")
Call<Void> keepAliveUserDataStream(@Query("listenKey") String listenKey);
@Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER)
@DELETE("/api/v3/userDataStream")
Call<Void> closeAliveUserDataStream(@Query("listenKey") String listenKey);
// Margin Account endpoints
@Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER})
@POST("/sapi/v1/margin/transfer")
Call<MarginTransaction> transfer(@Query("asset") String asset, @Query("amount") String amount, @Query("type") String type, @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp);
@Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER})
@POST("/sapi/v1/margin/loan")
Call<MarginTransaction> borrow(@Query("asset") String asset, @Query("amount") String amount, @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp);
@Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER})
@GET("/sapi/v1/margin/loan")
Call<LoanQueryResult> queryLoan(@Query("asset") String asset, @Query("txId") String txId, @Query("timestamp") Long timestamp);
@Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER})
@GET("/sapi/v1/margin/repay")
Call<RepayQueryResult> queryRepay(@Query("asset") String asset, @Query("txId") String txId, @Query("timestamp") Long timestamp);
@Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER})
@GET("/sapi/v1/margin/maxBorrowable")
Call<MaxBorrowableQueryResult> queryMaxBorrowable(@Query("asset") String asset, @Query("timestamp") Long timestamp);
@Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER})
@GET("/sapi/v1/margin/repay")
Call<RepayQueryResult> queryRepay(@Query("asset") String asset, @Query("startTime") Long starttime, @Query("timestamp") Long timestamp);
@Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER})
@POST("/sapi/v1/margin/repay")
Call<MarginTransaction> repay(@Query("asset") String asset, @Query("amount") String amount, @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp);
@Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER})
@GET("/sapi/v1/margin/account")
Call<MarginAccount> getMarginAccount(@Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp);
@Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER})
@GET("/sapi/v1/margin/openOrders")
Call<List<Order>> getOpenMarginOrders(@Query("symbol") String symbol, @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp);
@Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER)
@POST("/sapi/v1/margin/order")
Call<MarginNewOrderResponse> newMarginOrder(@Query("symbol") String symbol, @Query("side") OrderSide side, @Query("type") OrderType type,
@Query("timeInForce") TimeInForce timeInForce, @Query("quantity") String quantity,
@Query("price") String price, @Query("newClientOrderId") String newClientOrderId, @Query("stopPrice") String stopPrice,
@Query("icebergQty") String icebergQty, @Query("newOrderRespType") NewOrderResponseType newOrderRespType,
@Query("sideEffectType") SideEffectType sideEffectType, @Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp);
@Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER)
@DELETE("/sapi/v1/margin/order")
Call<CancelOrderResponse> cancelMarginOrder(@Query("symbol") String symbol, @Query("orderId") Long orderId,
@Query("origClientOrderId") String origClientOrderId, @Query("newClientOrderId") String newClientOrderId,
@Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp);
@Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER)
@GET("/sapi/v1/margin/order")
Call<Order> getMarginOrderStatus(@Query("symbol") String symbol, @Query("orderId") Long orderId,
@Query("origClientOrderId") String origClientOrderId, @Query("recvWindow") Long recvWindow,
@Query("timestamp") Long timestamp);
@Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER)
@GET("/sapi/v1/margin/myTrades")
Call<List<Trade>> getMyMarginTrades(@Query("symbol") String symbol, @Query("limit") Integer limit, @Query("fromId") Long fromId,
@Query("recvWindow") Long recvWindow, @Query("timestamp") Long timestamp);
@Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER)
@POST("/sapi/v1/userDataStream")
Call<ListenKey> startMarginUserDataStream();
@Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER)
@PUT("/sapi/v1/userDataStream")
Call<Void> keepAliveMarginUserDataStream(@Query("listenKey") String listenKey);
// Binance Liquidity Swap Pool endpoints
@Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER)
@GET("/sapi/v1/bswap/pools")
Call<List<Pool>> listAllSwapPools();
@Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER})
@GET("/sapi/v1/bswap/liquidity")
Call<List<Liquidity>> getPoolLiquidityInfo(@Query("poolId") String poolId,
@Query("recvWindow") Long recvWindow,
@Query("timestamp") Long timestamp);
@Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER})
@POST("/sapi/v1/bswap/liquidityAdd")
Call<LiquidityOperationRecord> addLiquidity(@Query("poolId") String poolId,
@Query("asset") String asset,
@Query("quantity") String quantity,
@Query("recvWindow") Long recvWindow,
@Query("timestamp") Long timestamp);
@Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER})
@POST("/sapi/v1/bswap/liquidityRemove")
Call<LiquidityOperationRecord> removeLiquidity(@Query("poolId") String poolId,
@Query("type") SwapRemoveType type,
@Query("asset") List<String> asset,
@Query("shareAmount") String shareAmount,
@Query("recvWindow") Long recvWindow,
@Query("timestamp") Long timestamp);
@Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER})
@GET("/sapi/v1/bswap/liquidityOps")
Call<List<LiquidityOperationRecord>> getPoolLiquidityOperationRecords(
@Query("poolId") String poolId,
@Query("limit") Integer limit,
@Query("recvWindow") Long recvWindow,
@Query("timestamp") Long timestamp);
@Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER})
@GET("/sapi/v1/bswap/liquidityOps")
Call<List<LiquidityOperationRecord>> getLiquidityOperationRecord(
@Query("operationId") String operationId,
@Query("recvWindow") Long recvWindow,
@Query("timestamp") Long timestamp);
@Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER})
@GET("/sapi/v1/bswap/quote")
Call<SwapQuote> requestQuote(
@Query("quoteAsset") String quoteAsset,
@Query("baseAsset") String baseAsset,
@Query("quoteQty") String quoteQty,
@Query("recvWindow") Long recvWindow,
@Query("timestamp") Long timestamp);
@Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER})
@POST("/sapi/v1/bswap/swap")
Call<SwapRecord> swap(
@Query("quoteAsset") String quoteAsset,
@Query("baseAsset") String baseAsset,
@Query("quoteQty") String quoteQty,
@Query("recvWindow") Long recvWindow,
@Query("timestamp") Long timestamp);
@Headers({BinanceApiConstants.ENDPOINT_SECURITY_TYPE_APIKEY_HEADER, BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER})
@GET("/sapi/v1/bswap/swap")
Call<List<SwapHistory>> getSwapHistory(
@Query("swapId") String swapId,
@Query("recvWindow") Long recvWindow,
@Query("timestamp") Long timestamp);
@Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER)
@POST("/sapi/v1/broker/subAccount")
Call<CreateSubAccountResult> createSubAccount(
@Query("tag") String tag,
@Query("recvWindow") Long recvWindow,
@Query("timestamp") Long timestamp);
@Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER)
@POST("/sapi/v1/broker/subAccountApi")
Call<SubAccountApiKey> createSubAccountApiKey(
@Query("subAccountId") String subAccountId,
@Query("canTrade") boolean canTrade,
@Query("recvWindow") Long recvWindow,
@Query("timestamp") Long timestamp);
@Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER)
@GET("/sapi/v1/broker/subAccountApi")
Call <List<SubAccountApiKey>> getSubAccountApiKey(
@Query("subAccountId") String subAccountId,
@Query("recvWindow") Long recvWindow,
@Query("timestamp") Long timestamp);
@Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER)
@DELETE("/sapi/v1/broker/subAccountApi")
Call<Void> deleteSubAccountApiKey(
@Query("subAccountId") String subAccountId,
@Query("subAccountApiKey") String subAccountApiKey,
@Query("recvWindow") Long recvWindow,
@Query("timestamp") Long timestamp);
@Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER)
@GET("/sapi/v1/broker/info")
Call<BrokerAccountInfo> getBrokerAccountInfo(
@Query("recvWindow") Long recvWindow,
@Query("timestamp") Long timestamp);
@Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER)
@GET("/sapi/v1/broker/subAccount")
Call<List<SubAccount>> querySubAccount(
@Query("subAccountId") String subAccountId,
@Query("page") Integer page,
@Query("size") Integer size,
@Query("recvWindow") Long recvWindow,
@Query("timestamp") Long timestamp);
@Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER)
@GET("/sapi/v1/broker/subAccount")
Call<List<SubAccount>> querySubAccounts(
@Query("page") Long page,
@Query("size") Long size,
@Query("recvWindow") Long recvWindow,
@Query("timestamp") Long timestamp);
@Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER)
@GET("/sapi/v1/broker/subAccount/depositHist")
Call<List<SubAccountDeposit>> getSubAccountDepositHistory(
@Query("subAccountId") String subAccountId,
@Query("startTime") Long startTime,
@Query("endTime") Long endTime,
@Query("recvWindow") Long recvWindow,
@Query("timestamp") Long timestamp);
@Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER)
@POST("/sapi/v1/broker/transfer")
Call<SubAccountTransferResult> subAccountTransfer(
@Query("fromId") String fromId,
@Query("toId") String toId,
@Query("clientTranId") String clientTranId,
@Query("asset") String asset,
@Query("amount") String amount,
@Query("recvWindow") Long recvWindow,
@Query("timestamp") Long timestamp);
@Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER)
@GET("/sapi/v1/broker/transfer")
Call<List<SubAccountTransferRecord>> getSubAccountTransferHistory(
@Query("fromId") String fromId,
@Query("toId") String toId,
@Query("clientTranId") String clientTranId,
@Query("showAllStatus") Boolean showAllStatus,
@Query("startTime") Long startTime,
@Query("endTime") Long endTime,
@Query("page") Integer page,
@Query("limit") Integer limit,
@Query("recvWindow") Long recvWindow,
@Query("timestamp") Long timestamp);
@Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER)
@POST("/sapi/v1/capital/withdraw/apply")
Call<WithdrawResult> withdraw(
@Query("coin") String coin,
@Query("withdrawOrderId") String withdrawOrderId,
@Query("network") String network,
@Query("address") String address,
@Query("addressTag") String addressTag,
@Query("amount") String amount,
@Query("transactionFeeFlag") boolean transactionFeeFlag,
@Query("recvWindow") Long recvWindow,
@Query("timestamp") Long timestamp);
@Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER)
@GET("/sapi/v1/capital/withdraw/history")
Call<List<Withdraw>> getWithdrawHistory(
@Query("coin") String coin,
@Query("status") Integer status,
@Query("offset") Integer offset,
@Query("limit") Integer limit,
@Query("startTime") Long startTime,
@Query("endTime") Long endTime,
@Query("recvWindow") Long recvWindow,
@Query("timestamp") Long timestamp);
@Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER)
@GET("/sapi/v1/capital/deposit/address")
Call<DepositAddress> getDepositAddress(
@Query("coin") String coin,
@Query("network") String network,
@Query("recvWindow") Long recvWindow,
@Query("timestamp") Long timestamp);
@Headers(BinanceApiConstants.ENDPOINT_SECURITY_TYPE_SIGNED_HEADER)
@GET("/sapi/v1/capital/deposit/hisrec")
Call<List<Deposit>> getDepositHistory(
@Query("coin") String coin,
@Query("status") Integer status,
@Query("startTime") Long startTime,
@Query("endTime") Long endTime,
@Query("offset") Integer offset,
@Query("limit") Integer limit,
@Query("recvWindow") Long recvWindow,
@Query("timestamp") Long timestamp);
}
|
92353badffa1a27110a0b1fe7d67b37724242247 | 577 | java | Java | Learn/src/s03/Constructor/Apple.java | silence0201/Java-Study | a912f5dfcf92f81914cea850d008301ea890eaf4 | [
"MIT"
] | null | null | null | Learn/src/s03/Constructor/Apple.java | silence0201/Java-Study | a912f5dfcf92f81914cea850d008301ea890eaf4 | [
"MIT"
] | null | null | null | Learn/src/s03/Constructor/Apple.java | silence0201/Java-Study | a912f5dfcf92f81914cea850d008301ea890eaf4 | [
"MIT"
] | null | null | null | 19.896552 | 60 | 0.601386 | 997,215 | package s03.Constructor;
/**
* Description: Apple
* Author: silence
* Update: silence(2017-04-20 20:58)
*/
public class Apple {
public String name;
public String color;
public double weight;
public Apple()
{}
//两个参数的构造器
public Apple(String name , String color)
{
this.name = name;
this.color = color;
}
//三个参数的构造器
public Apple(String name , String color , double weight)
{
//通过this调用另一个重载的构造器的初始化代码
this(name , color);
//下面this引用该构造器正在初始化的Java对象
this.weight = weight;
}
}
|
92353bc22068b81aff1f46d58f5b39427dd989d1 | 1,984 | java | Java | src/integrationTest/java/com/recursiveloop/webcommondemo/RcUnrestrictedResourceTest.java | RobJinman/rest-barebones | 1984746b23a6e4f05070fa360807d84f123c176d | [
"MIT"
] | null | null | null | src/integrationTest/java/com/recursiveloop/webcommondemo/RcUnrestrictedResourceTest.java | RobJinman/rest-barebones | 1984746b23a6e4f05070fa360807d84f123c176d | [
"MIT"
] | null | null | null | src/integrationTest/java/com/recursiveloop/webcommondemo/RcUnrestrictedResourceTest.java | RobJinman/rest-barebones | 1984746b23a6e4f05070fa360807d84f123c176d | [
"MIT"
] | null | null | null | 34.807018 | 115 | 0.770665 | 997,216 | // This file is property of Recursive Loop Ltd.
//
// Author: Rob Jinman
// Web: http://recursiveloop.org
// Copyright Recursive Loop Ltd 2015
// Copyright Rob Jinman 2015
package com.recursiveloop.webcommondemo;
import com.recursiveloop.webcommondemo.resources.RcUnrestrictedResource;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.extension.rest.client.ArquillianResteasyResource;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Test;
import org.junit.Assert;
import org.junit.runner.RunWith;
import javax.ws.rs.Consumes;
import javax.ws.rs.core.MediaType;
@RunWith(Arquillian.class)
public class RcUnrestrictedResourceTest {
@Deployment
public static WebArchive createDeployment() {
return ShrinkWrap.create(WebArchive.class, "RcUnrestrictedResourceTest.war")
.addPackage("com/recursiveloop/webcommon/test")
.addPackage("com/recursiveloop/webcommon")
.addPackage("com/recursiveloop/webcommon/config")
.addPackage("com/recursiveloop/webcommondemo")
.addPackage("com/recursiveloop/webcommondemo/models")
.addPackage("com/recursiveloop/webcommondemo/resources")
.addPackage("com/recursiveloop/webcommondemo/exceptions")
.addAsResource("config.properties")
.addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml")
.addAsWebInfResource("jboss-web.xml", "jboss-web.xml")
.setWebXML("web.xml");
}
@Test
@RunAsClient
@Consumes(MediaType.TEXT_PLAIN)
public void request_resource(@ArquillianResteasyResource("rest") RcUnrestrictedResource rcUnrestrictedResource) {
System.out.println("**((REQUEST_RESOURCE))**");
String msg = rcUnrestrictedResource.doGet();
Assert.assertNotNull(msg);
Assert.assertEquals("Hello", msg);
}
}
|
92353be178f010415afba1d9051257c2430f22b0 | 10,547 | java | Java | GoMoKu Client/src/MainWindow/Client.java | RobinNaggi/Gomoku | 3bd814380b1f688f1ab2174ab3d90b469eba7c62 | [
"MIT"
] | null | null | null | GoMoKu Client/src/MainWindow/Client.java | RobinNaggi/Gomoku | 3bd814380b1f688f1ab2174ab3d90b469eba7c62 | [
"MIT"
] | null | null | null | GoMoKu Client/src/MainWindow/Client.java | RobinNaggi/Gomoku | 3bd814380b1f688f1ab2174ab3d90b469eba7c62 | [
"MIT"
] | null | null | null | 42.01992 | 119 | 0.479188 | 997,217 | package MainWindow;
/**
* Client is a class that creates a connection with the connection class that
* is used in the server. It does all the communicating with the server for the
* client. It both receives messages and sends messages and will delegate to
* other classes when it receives a message.
*/
import java.awt.Color;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.net.Socket;
import java.util.Scanner;
import static MainWindow.Constants.correctInfo;
import static MainWindow.Constants.usernameTaken;
import static MainWindow.Constants.wrongPassword;
import static MainWindow.Constants.usernameIsNotRegistered;
import static MainWindow.Constants.alreadyLoggedIn;
import static MainWindow.Constants.goodToLogin;
import static MainWindow.Constants.stats;
import static MainWindow.Constants.onlineInfo;
import static MainWindow.Constants.inviter;
import static MainWindow.Constants.closeMessage;
import static MainWindow.Constants.decline;
import static MainWindow.Constants.accept;
import java.util.concurrent.TimeUnit;
/**
* Client is a class that creates the network framework for the messaging application.
* It creates threads and sends/receives messages.
* The constructor needs an ip number as a string and a port number as an int.
* Also, to connect the gui from the GUI.java use the method addGUI().
*
*
* @author Isaiah Scheel
*/
public class Client implements Runnable {
Thread worker;
private String server;
private int servPort;
private byte[] buf;
public Socket s;
private InputStream in;
private OutputStream out;
private DataOutputStream dos;
private Reader is;
public MainWindowController mwc;
public RegisterWindowController rwc;
public LobbyWindowController lwc;
public MasterController mc;
public User user;
/**
* This is the constructor for the client class.
* It takes a String that is the ip address in the form of
* "xxx.xxx.xxx.xxx" and an int that is the port number.
* It creates a socket, s , with the two parameters and then
* creates a few streams that can be used to read and write messages.
* @param ip - The ip address of the server you are connecting to
* @param port - The port number of the server
*
*/
public Client(String ip, int port, MasterController mc){
//Socket Initializing
this.mc = mc;
this.user = mc.user;
server = ip;
servPort = port;
try {
s = new Socket(server, servPort);
} catch (IOException e) {
e.printStackTrace();
}
//Input and Output Stream initialization
try {
in = s.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
try {
out = s.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
//InputStreamReader for the reading of messages in run()
is = new InputStreamReader(in);
dos = new DataOutputStream(out);
}
/**
* This method gets messages from the server in a manner that doesn't
* need a new line character.
* @see java.lang.Runnable#run()
*/
public void run() {
char[] buffer = new char[1024];
StringBuilder out = new StringBuilder();
while(true) {
// read a message (blocks waiting for a message)
try {
int ret = is.read(buffer, 0, buffer.length);
out.append(buffer, 0, ret);
System.out.println(mc.user.userName + " : " + out.toString());
/* list of messages that the server sends to the client.
Depending on the message, a different action is performed.
*/
//Correct info message to allow the user to log in
if(out.toString().equals(correctInfo))
{
mwc.loginButton();
}
//Error Message stating that the user name is taken
else if(out.toString().equals(usernameTaken)){
mwc.error("Username taken, Please register again.");
rwc.usernameTaken();
}
//Error Message stating that they put in the wrong password
else if(out.toString().equals(wrongPassword))
{
mwc.error("Wrong Password");
}
//Error Message stating that the username is not registered
else if(out.toString().equals(usernameIsNotRegistered))
{
mwc.error("Username is not registered");
}
else if(out.toString().equals(alreadyLoggedIn)){
mwc.error("User already logged in");
}
//Resets the error label after a good register
else if(out.toString().equals(goodToLogin)){
mwc.error("");
}
//Information for the Stats
else if(out.toString().charAt(0) == stats)
{
lwc.updateStatsLabels(out.toString());
}
//Online information when someone logs in
else if(out.toString().charAt(0) == onlineInfo){
Scanner scan = new Scanner(out.toString());
scan.nextLine();
int num = scan.nextInt();
scan.nextLine();
for (int i = 0; i < num; i++) {
String username = scan.nextLine();
if (!username.equals("null")) {
if(lwc!=null){
lwc.online(username);
}
else {
//Will sleep for 500 milliseconds
//to see if the lobby window controller is actually
//null or if it just hasn't been created yet
try {
TimeUnit.MILLISECONDS.sleep(500);
if(lwc != null){
lwc.online(username);
}
} catch (InterruptedException ex) {
}
}
}
}
}
//Invite request message
else if(out.toString().charAt(0) == inviter){
String inviter;
inviter = out.toString().substring(out.indexOf(" ")+1);
lwc.inviteRequest(inviter);
}
//Closing messsage. Will receive one for each person who signs out
else if(out.toString().substring(0, out.toString().indexOf(" ")).equals(closeMessage)){
lwc.close(out.toString().substring(out.indexOf(" ")+1));
}
//Decline message saying someone has declined your invite
else if(out.toString().charAt(0) == decline){
lwc.declined(out.toString().substring(out.indexOf(" ")+1));
}
//Accept message to tell the user that someone has accepted their invite
else if(out.toString().charAt(0) == accept){
PlayerController thisP = new PlayerController(2,Color.BLUE);
Scanner scan = new Scanner(out.toString());
scan.nextLine();
String accepter = scan.nextLine();
String ip = scan.nextLine();
int port = Integer.parseInt(scan.nextLine());
mc.openGameBoard(accepter, ip, port, thisP);
sendMessage("PlayGame " + user.userName);
lwc.lw.setVisible(false);
scan.close();
}
out.setLength(0);
} catch (IOException e) {
System.exit(0);
}
}
}
/**
* This method is called in main and creates a new thread and calls run().
*/
public void doIt() {
worker = new Thread( this ) ;
// calls run() in the new Thread
worker.start() ;
}
/**
* This method is used to send the user's message to the server by getting
* the bytes and using a DataOutputStream (dos) to write to it
* @param msg - The message from the user. Use this method in GUI.java
* in it's action listener for the textfield so when the user hits 'enter'
* the message will be sent
* @throws IOException
*/
public void sendMessage(String msg){
// send the message to the Server
buf = msg.getBytes();
try {
dos.write(buf, 0, msg.length());
} catch (IOException e) {
e.printStackTrace();
}
try {
dos.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
92353c90b650eb168fd2217037a3fa3c322bf12c | 1,175 | java | Java | app/src/main/java/com/tale/uder/ui/fragments/BaseFragment.java | talenguyen/UDer | d92fcd97321ef21fb7fcb06accbadd67f2f64225 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/tale/uder/ui/fragments/BaseFragment.java | talenguyen/UDer | d92fcd97321ef21fb7fcb06accbadd67f2f64225 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/tale/uder/ui/fragments/BaseFragment.java | talenguyen/UDer | d92fcd97321ef21fb7fcb06accbadd67f2f64225 | [
"Apache-2.0"
] | null | null | null | 29.375 | 112 | 0.676596 | 997,218 | package com.tale.uder.ui.fragments;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import com.tale.uder.UderApp;
@SuppressWarnings("PMD.AbstractClassWithoutAnyMethod") public abstract class BaseFragment
extends Fragment {
// Due to bug (https://github.com/google/dagger/issues/214) in Dagger 2 we can not inject handler here, sorry.
@NonNull private static final Handler MAIN_THREAD_HANDLER = new Handler(Looper.getMainLooper());
protected void runOnUiThreadIfFragmentAlive(@NonNull Runnable runnable) {
if (Looper.myLooper() == Looper.getMainLooper() && isFragmentAlive()) {
runnable.run();
} else {
MAIN_THREAD_HANDLER.post(() -> {
if (isFragmentAlive()) {
runnable.run();
}
});
}
}
private boolean isFragmentAlive() {
return getActivity() != null
&& isAdded()
&& !isDetached()
&& getView() != null
&& !isRemoving();
}
@Override public void onDestroy() {
UderApp.get(getContext()).applicationComponent().leakCanaryProxy().watch(this);
super.onDestroy();
}
}
|
92353caa4318552423e832a49a42b2bdc0659998 | 441 | java | Java | flowman-core/src/main/java/com/dimajix/flowman/annotation/TemplateObject.java | jackusz/flowman | 3a7ca5217ecf55734129188bc7dcb6a03d4312f2 | [
"Apache-2.0"
] | null | null | null | flowman-core/src/main/java/com/dimajix/flowman/annotation/TemplateObject.java | jackusz/flowman | 3a7ca5217ecf55734129188bc7dcb6a03d4312f2 | [
"Apache-2.0"
] | null | null | null | flowman-core/src/main/java/com/dimajix/flowman/annotation/TemplateObject.java | jackusz/flowman | 3a7ca5217ecf55734129188bc7dcb6a03d4312f2 | [
"Apache-2.0"
] | null | null | null | 25.941176 | 86 | 0.759637 | 997,219 | package com.dimajix.flowman.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
public @interface TemplateObject {
/**
* Specifies the name under which the object will be available in template scripts
* @return
*/
String name();
}
|
92353da445c26b05a83b7fde4d52d621836b3deb | 2,433 | java | Java | sli/data-access/dal/src/main/java/org/slc/sli/ingestion/model/da/BatchJobDAO.java | jstokes/secure-data-service | 94ae9df1c2a46b3555cdee5779929f48405f788d | [
"Apache-2.0"
] | null | null | null | sli/data-access/dal/src/main/java/org/slc/sli/ingestion/model/da/BatchJobDAO.java | jstokes/secure-data-service | 94ae9df1c2a46b3555cdee5779929f48405f788d | [
"Apache-2.0"
] | null | null | null | sli/data-access/dal/src/main/java/org/slc/sli/ingestion/model/da/BatchJobDAO.java | jstokes/secure-data-service | 94ae9df1c2a46b3555cdee5779929f48405f788d | [
"Apache-2.0"
] | null | null | null | 31.597403 | 105 | 0.772298 | 997,220 | /*
* Copyright 2012-2013 inBloom, Inc. and 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.slc.sli.ingestion.model.da;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.springframework.dao.DataAccessResourceFailureException;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.slc.sli.ingestion.BatchJobStageType;
import org.slc.sli.ingestion.FaultType;
import org.slc.sli.ingestion.model.Error;
import org.slc.sli.ingestion.model.NewBatchJob;
import org.slc.sli.ingestion.model.RecordHash;
import org.slc.sli.ingestion.model.Stage;
/**
* Data access object for batch job data.
*
* @author dduran
*
*/
public interface BatchJobDAO {
void saveBatchJob(NewBatchJob newBatchJob);
NewBatchJob findBatchJobById(String batchJobId);
public Iterable<Error> getBatchJobErrors(String jobId, String resourceId, FaultType type, int limit);
void saveError(Error error);
void saveBatchJobStage(String batchJobId, Stage stage);
List<Stage> getBatchJobStages(String batchJobId);
List<Stage> getBatchJobStages(String batchJobId, BatchJobStageType stageType);
void insertRecordHash(String recordId, String newHashValues)
throws DataAccessResourceFailureException;
void updateRecordHash(RecordHash rh, String newHashValues)
throws DataAccessResourceFailureException;
void removeRecordHash( RecordHash rh )
throws DataAccessResourceFailureException;
void removeRecordHashByTenant(String tenantId);
public RecordHash findRecordHash(String tenantId, String recordId);
public MongoTemplate getMongoTemplate();
boolean updateFileEntryLatch(String batchJobId, String filename);
public boolean createFileLatch(String jobId, List<String> fileEntries);
public boolean isDryRun(String jobId);
public String getDuplicateDetectionMode(String jobId);
}
|
9235409e165922043bb507ca599364e0327779a0 | 1,132 | java | Java | etrace-common/src/main/java/io/etrace/common/message/metric/MetricInTraceApi.java | blackblacksky/etrace | fb4968af0080e3cb8ee18af1790e6914751029a4 | [
"Apache-2.0"
] | 41 | 2019-12-05T03:01:17.000Z | 2022-03-24T14:35:45.000Z | etrace-common/src/main/java/io/etrace/common/message/metric/MetricInTraceApi.java | jacobke/etrace | bae5654e9a6412e444d4f519a86090af7d25d988 | [
"Apache-2.0"
] | 5 | 2020-01-12T12:21:55.000Z | 2022-01-13T03:46:23.000Z | etrace-common/src/main/java/io/etrace/common/message/metric/MetricInTraceApi.java | jacobke/etrace | bae5654e9a6412e444d4f519a86090af7d25d988 | [
"Apache-2.0"
] | 18 | 2019-11-27T07:22:31.000Z | 2022-03-08T12:48:38.000Z | 27.609756 | 75 | 0.749117 | 997,221 | /*
* Copyright 2020 etrace.io
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.etrace.common.message.metric;
import com.fasterxml.jackson.core.JsonGenerator;
import io.etrace.common.message.metric.field.MetricKey;
import io.etrace.common.message.metric.field.MetricType;
import java.io.IOException;
public interface MetricInTraceApi<M> {
String getName();
MetricType getMetricType();
MetricKey getKey();
MetricKey getTagKey();
M addTag(String key, String value);
void merge(MetricInTraceApi metricInTraceApi);
void write(JsonGenerator generator) throws IOException;
}
|
923540c11d17d5cbf9e2a345d7057dc934227726 | 999 | java | Java | src/main/java/com/github/borisskert/example/users/UsersController.java | borisskert/springboot-cucumber-wiremock-example | 38956645470af6902c087300c734e64f273e7c54 | [
"Apache-2.0"
] | 2 | 2020-03-17T15:09:48.000Z | 2020-11-05T17:14:31.000Z | src/main/java/com/github/borisskert/example/users/UsersController.java | borisskert/springboot-cucumber-wiremock-example | 38956645470af6902c087300c734e64f273e7c54 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/github/borisskert/example/users/UsersController.java | borisskert/springboot-cucumber-wiremock-example | 38956645470af6902c087300c734e64f273e7c54 | [
"Apache-2.0"
] | 1 | 2020-03-09T20:35:00.000Z | 2020-03-09T20:35:00.000Z | 30.272727 | 80 | 0.733734 | 997,222 | package com.github.borisskert.example.users;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/v1/users")
public class UsersController {
private final UserClient userClient;
@Autowired
public UsersController(UserClient userClient) {
this.userClient = userClient;
}
@GetMapping
public User[] getUsers() {
return userClient.getUsers();
}
@GetMapping(path = "/{userId}")
public ResponseEntity<User> getUser(@PathVariable("userId") String userId) {
return userClient.getUser(userId)
.map(ResponseEntity::ok)
.orElse(ResponseEntity.notFound().build());
}
}
|
923540c8ef67be4c14b8d70be24decd2349c78b9 | 534 | java | Java | flygof/src/main/java/com/hiabby/flytools/gof/state/LookState.java | ITflying/FlyTools | 36b21bbf0918c448f1784a735c04cc7c16ebe286 | [
"Apache-2.0"
] | null | null | null | flygof/src/main/java/com/hiabby/flytools/gof/state/LookState.java | ITflying/FlyTools | 36b21bbf0918c448f1784a735c04cc7c16ebe286 | [
"Apache-2.0"
] | null | null | null | flygof/src/main/java/com/hiabby/flytools/gof/state/LookState.java | ITflying/FlyTools | 36b21bbf0918c448f1784a735c04cc7c16ebe286 | [
"Apache-2.0"
] | null | null | null | 18.413793 | 64 | 0.59176 | 997,223 | package com.hiabby.flytools.gof.state;
/**
* @desc
* @date 2018/09/28
**/
public class LookState extends LeaveState {
@Override
public void apply() {
System.out.println("申请:不在当前状态中");
}
@Override
public void look() {
System.out.println(" - 提出查看中 -");
}
@Override
public void review() {
super.content.setLeaveState(LeavenContent.REVIEW_STATE);
super.content.review();
}
@Override
public void reply() {
System.out.println("回复:不在当前状态中");
}
}
|
923540ffd4a16e076a9c2c4ff9f59a4019dd5daa | 277 | java | Java | demo-command/src/main/java/es/dbiosag/command/infrasturcture/eventsourcing/events/PhoneCreatedEvent.java | alonsoir/demo-cqrs-kafka | 218bbed0b0adae009e76e4eafc5da892147818f5 | [
"MIT"
] | 2 | 2021-02-05T08:16:21.000Z | 2021-05-29T09:08:54.000Z | demo-command/src/main/java/es/dbiosag/command/infrasturcture/eventsourcing/events/PhoneCreatedEvent.java | alonsoir/demo-cqrs-kafka | 218bbed0b0adae009e76e4eafc5da892147818f5 | [
"MIT"
] | null | null | null | demo-command/src/main/java/es/dbiosag/command/infrasturcture/eventsourcing/events/PhoneCreatedEvent.java | alonsoir/demo-cqrs-kafka | 218bbed0b0adae009e76e4eafc5da892147818f5 | [
"MIT"
] | 3 | 2021-02-05T15:33:31.000Z | 2022-01-05T09:33:55.000Z | 18.466667 | 63 | 0.787004 | 997,224 | package es.dbiosag.command.infrasturcture.eventsourcing.events;
import es.dbiosag.command.domain.model.Phone;
import lombok.Builder;
import lombok.Data;
import java.util.UUID;
@Builder
@Data
public class PhoneCreatedEvent {
private UUID uuid;
private Phone phone;
}
|
9235417d1ee93f30692119ce3c87d5e82553f2f3 | 77 | java | Java | src/me/dylanmullen/agar/game/events/api/Listener.java | DylanMullen/AgarioClone | a0651024c1abc3e8f81c66af7b5e7f6f05016740 | [
"Apache-2.0"
] | 1 | 2021-02-19T09:38:19.000Z | 2021-02-19T09:38:19.000Z | src/me/dylanmullen/agar/game/events/api/Listener.java | DylanMullen/AgarioClone | a0651024c1abc3e8f81c66af7b5e7f6f05016740 | [
"Apache-2.0"
] | null | null | null | src/me/dylanmullen/agar/game/events/api/Listener.java | DylanMullen/AgarioClone | a0651024c1abc3e8f81c66af7b5e7f6f05016740 | [
"Apache-2.0"
] | null | null | null | 11 | 44 | 0.779221 | 997,225 | package me.dylanmullen.agar.game.events.api;
public interface Listener
{
}
|
9235419c79082c70c463dafa58dc94d28febf1fa | 3,859 | java | Java | test/edu/fjnu/test/dao/TestUpeoeDao.java | rush24/KnowlegeAnalyzeSystem | 24f26f0e41bce4195928eb490c40857bef71e173 | [
"MIT"
] | 1 | 2016-06-20T15:24:21.000Z | 2016-06-20T15:24:21.000Z | test/edu/fjnu/test/dao/TestUpeoeDao.java | rush24/KnowlegeAnalyzeSystem | 24f26f0e41bce4195928eb490c40857bef71e173 | [
"MIT"
] | null | null | null | test/edu/fjnu/test/dao/TestUpeoeDao.java | rush24/KnowlegeAnalyzeSystem | 24f26f0e41bce4195928eb490c40857bef71e173 | [
"MIT"
] | 1 | 2018-03-27T12:03:33.000Z | 2018-03-27T12:03:33.000Z | 36.40566 | 101 | 0.734646 | 997,226 | package edu.fjnu.test.dao;
import java.sql.SQLException;
import java.util.List;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.MapHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;
import org.junit.Test;
import cn.itcast.commons.CommonUtils;
import cn.itcast.jdbc.TxQueryRunner;
import edu.fjnu.domain.Testmain;
import edu.fjnu.domain.VGrandientScope;
import edu.fjnu.domain.VMember;
import edu.fjnu.domain.VQuestion;
import edu.fjnu.domain.VScope;
import edu.fjnu.domain.VTestDetail;
import edu.fjnu.domain.VTestMain;
public class TestUpeoeDao {
QueryRunner qr = new TxQueryRunner();
VMember member = new VMember();
VGrandientScope gs = new VGrandientScope();
VQuestion question = new VQuestion();
VScope scope = new VScope();
VTestMain testmain = new VTestMain();
VTestDetail testdetail = new VTestDetail();
String sql = "";
@Test
public void searchGrandient() throws SQLException {
sql = "select * from t_grandient_t_scope where t_grandient_grandientid = '423'";
gs = qr.query(sql, new BeanHandler<VGrandientScope>(VGrandientScope.class));
System.out.println(gs);
}
@Test
public void searchMember() throws SQLException {
sql = "select * from t_member where memberid = '100'";
member = qr.query(sql, new BeanHandler<VMember>(VMember.class));
System.out.println(member);
}
@Test
public void searchQuestion() throws SQLException {
sql = "select * from t_question where fk_question_id = '1'";
question = qr.query(sql, new BeanHandler<VQuestion>(VQuestion.class));
System.out.println(question);
}
@Test
public void searchScope() throws SQLException {
sql = "select * from t_scope where pk_scope_id = '1'";
scope = qr.query(sql, new BeanHandler<VScope>(VScope.class));
System.out.println(scope);
}
@Test
public void searchTestMain() throws SQLException {
sql = "select * from t_testmain where pk_test_main_id = '1'";
testmain = qr.query(sql, new BeanHandler<VTestMain>(VTestMain.class));
System.out.println(testmain);
}
@Test
public void searchTestDetail() throws SQLException {
sql = "select * from t_test_detail where pk_test_id = '1'";
// testdetail = qr.query(sql, new
// BeanHandler<VTestDetail>(VTestDetail.class));//查询某个表,单行多列记录
// Map map= qr.query(sql, new
// BeanListHandler<VTestMain>(VTestMain.class));//查询某个表,多行多列记录
// qr.query(sql, new MapHandler());//学生+老师+课程表 查出单行多列记录
// qr.query(sql, new MapListHandler());//学生+老师+课程表 查出多行多列记录
// CommonUtils.toBean(map, VTestMain.class);
System.out.println(testdetail);
}
@Test
public void searchVTestMain() throws SQLException {
sql = "select pk_test_main_id,subject,student_memberId from t_testmain "
+ "where subject like '语文' and student_memberId in "
+ "(select memberid from t_member where name like '陈子凡') "
+ "and grandient_grandientId in(select DISTINCT "
+ "t_grandient.grandientId as `grandientId` from t_grandient,"
+ "t_grandient_t_scope,t_scope as `chapter`,"
+ "t_scope as `unit`,"
+ "t_scope as `grade` "
+ "where t_grandient.grandientId=t_grandient_t_scope.t_grandient_grandientId "
+ "and t_grandient_t_scope.scopes_pk_scope_id=chapter.pk_scope_id "
+ "and chapter.fk_parent_id=unit.pk_scope_id and unit.fk_parent_id=grade.pk_scope_id "
+ "and grade.name like '初二(上)%')";
// String sub = "语文";
// sql ="select * from t_testmain where student_memberId = '2' and subject='语文' and realscore != 0";
// List list = qr.query(sql, new BeanListHandler<VTestMain>(VTestMain.class));
// for(int i=0; i<list.size(); i++){
// System.out.println(list.get(i));
// }
// System.out.println(sql);
System.out.println(qr.query(sql, new BeanListHandler<VTestMain>(VTestMain.class)));
}
}
|
9235427f3fc83c715a7089d570ff4ea5158473a5 | 837 | java | Java | addressbook-web-tests/src/test/java/ru/stqa/pft/addressbook/tests/GroupDeletionTests.java | DimmOn86/java-test | c8d10f0774979ebb55c1cd17236815296dd355b6 | [
"Apache-2.0"
] | null | null | null | addressbook-web-tests/src/test/java/ru/stqa/pft/addressbook/tests/GroupDeletionTests.java | DimmOn86/java-test | c8d10f0774979ebb55c1cd17236815296dd355b6 | [
"Apache-2.0"
] | null | null | null | addressbook-web-tests/src/test/java/ru/stqa/pft/addressbook/tests/GroupDeletionTests.java | DimmOn86/java-test | c8d10f0774979ebb55c1cd17236815296dd355b6 | [
"Apache-2.0"
] | null | null | null | 24.617647 | 65 | 0.698925 | 997,227 | package ru.stqa.pft.addressbook.tests;
import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import ru.stqa.pft.addressbook.model.GroupData;
import java.util.Set;
public class GroupDeletionTests extends TestBase {
@BeforeMethod
public void ensurePreconditions(){
app.goTo().groupPage();
if(app.group().all().size() == 0){
app.group().create(new GroupData().withName("FirstGroup"));
}
}
@Test
public void testGroupDeletion() {
Set<GroupData> before = app.group().all();
GroupData deletedGroup = before.iterator().next();
app.group().delete(deletedGroup);
Set<GroupData> after = app.group().all();
Assert.assertEquals(after.size(), before.size() - 1);
before.remove(deletedGroup);
Assert.assertEquals(before, after);
}
}
|
9235434a3f5bd1553d5e7757bfca9b1f8e2d8180 | 117 | java | Java | src/main/java/gui/ScalingFactor.java | januszekm3/szia | 19a25c46ac091358e78262e627505ad0971141d3 | [
"Apache-2.0"
] | null | null | null | src/main/java/gui/ScalingFactor.java | januszekm3/szia | 19a25c46ac091358e78262e627505ad0971141d3 | [
"Apache-2.0"
] | null | null | null | src/main/java/gui/ScalingFactor.java | januszekm3/szia | 19a25c46ac091358e78262e627505ad0971141d3 | [
"Apache-2.0"
] | null | null | null | 13 | 28 | 0.666667 | 997,228 | package gui;
public class ScalingFactor {
int xMargin;
int yMargin;
float xFactor;
float yFactor;
}
|
923543f1f22b00b1586da141446e9109d12e0033 | 13,874 | java | Java | modules/lwjgl/vulkan/src/generated/java/org/lwjgl/vulkan/KHRGetSurfaceCapabilities2.java | EwoutH/lwjgl3 | 1e013173094cfdacff9bf0c1e36ea35aeb8f213e | [
"BSD-3-Clause"
] | 4,054 | 2015-01-01T10:30:02.000Z | 2022-03-31T11:05:37.000Z | modules/lwjgl/vulkan/src/generated/java/org/lwjgl/vulkan/KHRGetSurfaceCapabilities2.java | EwoutH/lwjgl3 | 1e013173094cfdacff9bf0c1e36ea35aeb8f213e | [
"BSD-3-Clause"
] | 678 | 2015-01-07T15:45:25.000Z | 2022-03-28T20:09:08.000Z | modules/lwjgl/vulkan/src/generated/java/org/lwjgl/vulkan/KHRGetSurfaceCapabilities2.java | TheMrMilchmann/lwjgl3 | f88383fcdede4c575425117e184754d0afae3b52 | [
"BSD-3-Clause"
] | 892 | 2015-01-01T03:01:21.000Z | 2022-03-30T11:44:03.000Z | 54.195313 | 766 | 0.70852 | 997,229 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
* MACHINE GENERATED FILE, DO NOT EDIT
*/
package org.lwjgl.vulkan;
import javax.annotation.*;
import java.nio.*;
import org.lwjgl.system.*;
import static org.lwjgl.system.Checks.*;
import static org.lwjgl.system.JNI.*;
import static org.lwjgl.system.MemoryUtil.*;
/**
* This extension provides new entry points to query device surface capabilities in a way that can be easily extended by other extensions, without introducing any further entry points. This extension can be considered the {@link KHRSurface VK_KHR_surface} equivalent of the {@link KHRGetPhysicalDeviceProperties2 VK_KHR_get_physical_device_properties2} extension.
*
* <h5>VK_KHR_get_surface_capabilities2</h5>
*
* <dl>
* <dt><b>Name String</b></dt>
* <dd>{@code VK_KHR_get_surface_capabilities2}</dd>
* <dt><b>Extension Type</b></dt>
* <dd>Instance extension</dd>
* <dt><b>Registered Extension Number</b></dt>
* <dd>120</dd>
* <dt><b>Revision</b></dt>
* <dd>1</dd>
* <dt><b>Extension and Version Dependencies</b></dt>
* <dd><ul>
* <li>Requires Vulkan 1.0</li>
* <li>Requires {@link KHRSurface VK_KHR_surface}</li>
* </ul></dd>
* <dt><b>Contact</b></dt>
* <dd><ul>
* <li>James Jones <a target="_blank" href="https://github.com/KhronosGroup/Vulkan-Docs/issues/new?body=[VK_KHR_get_surface_capabilities2]%20@cubanismo%250A%3C%3CHere%20describe%20the%20issue%20or%20question%20you%20have%20about%20the%20VK_KHR_get_surface_capabilities2%20extension%3E%3E">cubanismo</a></li>
* </ul></dd>
* </dl>
*
* <h5>Other Extension Metadata</h5>
*
* <dl>
* <dt><b>Last Modified Date</b></dt>
* <dd>2017-02-27</dd>
* <dt><b>IP Status</b></dt>
* <dd>No known IP claims.</dd>
* <dt><b>Contributors</b></dt>
* <dd><ul>
* <li>Ian Elliott, Google</li>
* <li>James Jones, NVIDIA</li>
* <li>Alon Or-bach, Samsung</li>
* </ul></dd>
* </dl>
*/
public class KHRGetSurfaceCapabilities2 {
/** The extension specification version. */
public static final int VK_KHR_GET_SURFACE_CAPABILITIES_2_SPEC_VERSION = 1;
/** The extension name. */
public static final String VK_KHR_GET_SURFACE_CAPABILITIES_2_EXTENSION_NAME = "VK_KHR_get_surface_capabilities2";
/**
* Extends {@code VkStructureType}.
*
* <h5>Enum values:</h5>
*
* <ul>
* <li>{@link #VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SURFACE_INFO_2_KHR STRUCTURE_TYPE_PHYSICAL_DEVICE_SURFACE_INFO_2_KHR}</li>
* <li>{@link #VK_STRUCTURE_TYPE_SURFACE_CAPABILITIES_2_KHR STRUCTURE_TYPE_SURFACE_CAPABILITIES_2_KHR}</li>
* <li>{@link #VK_STRUCTURE_TYPE_SURFACE_FORMAT_2_KHR STRUCTURE_TYPE_SURFACE_FORMAT_2_KHR}</li>
* </ul>
*/
public static final int
VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SURFACE_INFO_2_KHR = 1000119000,
VK_STRUCTURE_TYPE_SURFACE_CAPABILITIES_2_KHR = 1000119001,
VK_STRUCTURE_TYPE_SURFACE_FORMAT_2_KHR = 1000119002;
protected KHRGetSurfaceCapabilities2() {
throw new UnsupportedOperationException();
}
// --- [ vkGetPhysicalDeviceSurfaceCapabilities2KHR ] ---
/** Unsafe version of: {@link #vkGetPhysicalDeviceSurfaceCapabilities2KHR GetPhysicalDeviceSurfaceCapabilities2KHR} */
public static int nvkGetPhysicalDeviceSurfaceCapabilities2KHR(VkPhysicalDevice physicalDevice, long pSurfaceInfo, long pSurfaceCapabilities) {
long __functionAddress = physicalDevice.getCapabilities().vkGetPhysicalDeviceSurfaceCapabilities2KHR;
if (CHECKS) {
check(__functionAddress);
}
return callPPPI(physicalDevice.address(), pSurfaceInfo, pSurfaceCapabilities, __functionAddress);
}
/**
* Reports capabilities of a surface on a physical device.
*
* <h5>C Specification</h5>
*
* <p>To query the basic capabilities of a surface defined by the core or extensions, call:</p>
*
* <pre><code>
* VkResult vkGetPhysicalDeviceSurfaceCapabilities2KHR(
* VkPhysicalDevice physicalDevice,
* const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
* VkSurfaceCapabilities2KHR* pSurfaceCapabilities);</code></pre>
*
* <h5>Description</h5>
*
* <p>{@code vkGetPhysicalDeviceSurfaceCapabilities2KHR} behaves similarly to {@link KHRSurface#vkGetPhysicalDeviceSurfaceCapabilitiesKHR GetPhysicalDeviceSurfaceCapabilitiesKHR}, with the ability to specify extended inputs via chained input structures, and to return extended information via chained output structures.</p>
*
* <h5>Valid Usage</h5>
*
* <ul>
* <li>{@code pSurfaceInfo→surface} <b>must</b> be supported by {@code physicalDevice}, as reported by {@link KHRSurface#vkGetPhysicalDeviceSurfaceSupportKHR GetPhysicalDeviceSurfaceSupportKHR} or an equivalent platform-specific mechanism</li>
* </ul>
*
* <ul>
* <li>If a {@link VkSurfaceCapabilitiesFullScreenExclusiveEXT} structure is included in the {@code pNext} chain of {@code pSurfaceCapabilities}, a {@link VkSurfaceFullScreenExclusiveWin32InfoEXT} structure <b>must</b> be included in the {@code pNext} chain of {@code pSurfaceInfo}</li>
* </ul>
*
* <h5>Valid Usage (Implicit)</h5>
*
* <ul>
* <li>{@code physicalDevice} <b>must</b> be a valid {@code VkPhysicalDevice} handle</li>
* <li>{@code pSurfaceInfo} <b>must</b> be a valid pointer to a valid {@link VkPhysicalDeviceSurfaceInfo2KHR} structure</li>
* <li>{@code pSurfaceCapabilities} <b>must</b> be a valid pointer to a {@link VkSurfaceCapabilities2KHR} structure</li>
* </ul>
*
* <h5>Return Codes</h5>
*
* <dl>
* <dt>On success, this command returns</dt>
* <dd><ul>
* <li>{@link VK10#VK_SUCCESS SUCCESS}</li>
* </ul></dd>
* <dt>On failure, this command returns</dt>
* <dd><ul>
* <li>{@link VK10#VK_ERROR_OUT_OF_HOST_MEMORY ERROR_OUT_OF_HOST_MEMORY}</li>
* <li>{@link VK10#VK_ERROR_OUT_OF_DEVICE_MEMORY ERROR_OUT_OF_DEVICE_MEMORY}</li>
* <li>{@link KHRSurface#VK_ERROR_SURFACE_LOST_KHR ERROR_SURFACE_LOST_KHR}</li>
* </ul></dd>
* </dl>
*
* <h5>See Also</h5>
*
* <p>{@link VkPhysicalDeviceSurfaceInfo2KHR}, {@link VkSurfaceCapabilities2KHR}</p>
*
* @param physicalDevice the physical device that will be associated with the swapchain to be created, as described for {@link KHRSwapchain#vkCreateSwapchainKHR CreateSwapchainKHR}.
* @param pSurfaceInfo a pointer to a {@link VkPhysicalDeviceSurfaceInfo2KHR} structure describing the surface and other fixed parameters that would be consumed by {@link KHRSwapchain#vkCreateSwapchainKHR CreateSwapchainKHR}.
* @param pSurfaceCapabilities a pointer to a {@link VkSurfaceCapabilities2KHR} structure in which the capabilities are returned.
*/
@NativeType("VkResult")
public static int vkGetPhysicalDeviceSurfaceCapabilities2KHR(VkPhysicalDevice physicalDevice, @NativeType("VkPhysicalDeviceSurfaceInfo2KHR const *") VkPhysicalDeviceSurfaceInfo2KHR pSurfaceInfo, @NativeType("VkSurfaceCapabilities2KHR *") VkSurfaceCapabilities2KHR pSurfaceCapabilities) {
return nvkGetPhysicalDeviceSurfaceCapabilities2KHR(physicalDevice, pSurfaceInfo.address(), pSurfaceCapabilities.address());
}
// --- [ vkGetPhysicalDeviceSurfaceFormats2KHR ] ---
/**
* Unsafe version of: {@link #vkGetPhysicalDeviceSurfaceFormats2KHR GetPhysicalDeviceSurfaceFormats2KHR}
*
* @param pSurfaceFormatCount a pointer to an integer related to the number of format tuples available or queried, as described below.
*/
public static int nvkGetPhysicalDeviceSurfaceFormats2KHR(VkPhysicalDevice physicalDevice, long pSurfaceInfo, long pSurfaceFormatCount, long pSurfaceFormats) {
long __functionAddress = physicalDevice.getCapabilities().vkGetPhysicalDeviceSurfaceFormats2KHR;
if (CHECKS) {
check(__functionAddress);
}
return callPPPPI(physicalDevice.address(), pSurfaceInfo, pSurfaceFormatCount, pSurfaceFormats, __functionAddress);
}
/**
* Query color formats supported by surface.
*
* <h5>C Specification</h5>
*
* <p>To query the supported swapchain format tuples for a surface, call:</p>
*
* <pre><code>
* VkResult vkGetPhysicalDeviceSurfaceFormats2KHR(
* VkPhysicalDevice physicalDevice,
* const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
* uint32_t* pSurfaceFormatCount,
* VkSurfaceFormat2KHR* pSurfaceFormats);</code></pre>
*
* <h5>Description</h5>
*
* <p>{@link #vkGetPhysicalDeviceSurfaceFormats2KHR GetPhysicalDeviceSurfaceFormats2KHR} behaves similarly to {@link KHRSurface#vkGetPhysicalDeviceSurfaceFormatsKHR GetPhysicalDeviceSurfaceFormatsKHR}, with the ability to be extended via {@code pNext} chains.</p>
*
* <p>If {@code pSurfaceFormats} is {@code NULL}, then the number of format tuples supported for the given {@code surface} is returned in {@code pSurfaceFormatCount}. Otherwise, {@code pSurfaceFormatCount} <b>must</b> point to a variable set by the user to the number of elements in the {@code pSurfaceFormats} array, and on return the variable is overwritten with the number of structures actually written to {@code pSurfaceFormats}. If the value of {@code pSurfaceFormatCount} is less than the number of format tuples supported, at most {@code pSurfaceFormatCount} structures will be written, and {@link VK10#VK_INCOMPLETE INCOMPLETE} will be returned instead of {@link VK10#VK_SUCCESS SUCCESS}, to indicate that not all the available values were returned.</p>
*
* <h5>Valid Usage</h5>
*
* <ul>
* <li>{@code pSurfaceInfo→surface} <b>must</b> be supported by {@code physicalDevice}, as reported by {@link KHRSurface#vkGetPhysicalDeviceSurfaceSupportKHR GetPhysicalDeviceSurfaceSupportKHR} or an equivalent platform-specific mechanism</li>
* </ul>
*
* <h5>Valid Usage (Implicit)</h5>
*
* <ul>
* <li>{@code physicalDevice} <b>must</b> be a valid {@code VkPhysicalDevice} handle</li>
* <li>{@code pSurfaceInfo} <b>must</b> be a valid pointer to a valid {@link VkPhysicalDeviceSurfaceInfo2KHR} structure</li>
* <li>{@code pSurfaceFormatCount} <b>must</b> be a valid pointer to a {@code uint32_t} value</li>
* <li>If the value referenced by {@code pSurfaceFormatCount} is not 0, and {@code pSurfaceFormats} is not {@code NULL}, {@code pSurfaceFormats} <b>must</b> be a valid pointer to an array of {@code pSurfaceFormatCount} {@link VkSurfaceFormat2KHR} structures</li>
* </ul>
*
* <h5>Return Codes</h5>
*
* <dl>
* <dt>On success, this command returns</dt>
* <dd><ul>
* <li>{@link VK10#VK_SUCCESS SUCCESS}</li>
* <li>{@link VK10#VK_INCOMPLETE INCOMPLETE}</li>
* </ul></dd>
* <dt>On failure, this command returns</dt>
* <dd><ul>
* <li>{@link VK10#VK_ERROR_OUT_OF_HOST_MEMORY ERROR_OUT_OF_HOST_MEMORY}</li>
* <li>{@link VK10#VK_ERROR_OUT_OF_DEVICE_MEMORY ERROR_OUT_OF_DEVICE_MEMORY}</li>
* <li>{@link KHRSurface#VK_ERROR_SURFACE_LOST_KHR ERROR_SURFACE_LOST_KHR}</li>
* </ul></dd>
* </dl>
*
* <h5>See Also</h5>
*
* <p>{@link VkPhysicalDeviceSurfaceInfo2KHR}, {@link VkSurfaceFormat2KHR}</p>
*
* @param physicalDevice the physical device that will be associated with the swapchain to be created, as described for {@link KHRSwapchain#vkCreateSwapchainKHR CreateSwapchainKHR}.
* @param pSurfaceInfo a pointer to a {@link VkPhysicalDeviceSurfaceInfo2KHR} structure describing the surface and other fixed parameters that would be consumed by {@link KHRSwapchain#vkCreateSwapchainKHR CreateSwapchainKHR}.
* @param pSurfaceFormatCount a pointer to an integer related to the number of format tuples available or queried, as described below.
* @param pSurfaceFormats either {@code NULL} or a pointer to an array of {@link VkSurfaceFormat2KHR} structures.
*/
@NativeType("VkResult")
public static int vkGetPhysicalDeviceSurfaceFormats2KHR(VkPhysicalDevice physicalDevice, @NativeType("VkPhysicalDeviceSurfaceInfo2KHR const *") VkPhysicalDeviceSurfaceInfo2KHR pSurfaceInfo, @NativeType("uint32_t *") IntBuffer pSurfaceFormatCount, @Nullable @NativeType("VkSurfaceFormat2KHR *") VkSurfaceFormat2KHR.Buffer pSurfaceFormats) {
if (CHECKS) {
check(pSurfaceFormatCount, 1);
checkSafe(pSurfaceFormats, pSurfaceFormatCount.get(pSurfaceFormatCount.position()));
}
return nvkGetPhysicalDeviceSurfaceFormats2KHR(physicalDevice, pSurfaceInfo.address(), memAddress(pSurfaceFormatCount), memAddressSafe(pSurfaceFormats));
}
/** Array version of: {@link #vkGetPhysicalDeviceSurfaceFormats2KHR GetPhysicalDeviceSurfaceFormats2KHR} */
@NativeType("VkResult")
public static int vkGetPhysicalDeviceSurfaceFormats2KHR(VkPhysicalDevice physicalDevice, @NativeType("VkPhysicalDeviceSurfaceInfo2KHR const *") VkPhysicalDeviceSurfaceInfo2KHR pSurfaceInfo, @NativeType("uint32_t *") int[] pSurfaceFormatCount, @Nullable @NativeType("VkSurfaceFormat2KHR *") VkSurfaceFormat2KHR.Buffer pSurfaceFormats) {
long __functionAddress = physicalDevice.getCapabilities().vkGetPhysicalDeviceSurfaceFormats2KHR;
if (CHECKS) {
check(__functionAddress);
check(pSurfaceFormatCount, 1);
checkSafe(pSurfaceFormats, pSurfaceFormatCount[0]);
}
return callPPPPI(physicalDevice.address(), pSurfaceInfo.address(), pSurfaceFormatCount, memAddressSafe(pSurfaceFormats), __functionAddress);
}
} |
9235453a76b36fc2fed302cd8ba7cdeb2f31d191 | 2,520 | java | Java | Master/src/main/java/com/domo4pi/core/mock/MockApp.java | albertoteloko/domo4pi | 8c9aa0817472c8730a31a4318ef364a1e28b1154 | [
"MIT"
] | null | null | null | Master/src/main/java/com/domo4pi/core/mock/MockApp.java | albertoteloko/domo4pi | 8c9aa0817472c8730a31a4318ef364a1e28b1154 | [
"MIT"
] | null | null | null | Master/src/main/java/com/domo4pi/core/mock/MockApp.java | albertoteloko/domo4pi | 8c9aa0817472c8730a31a4318ef364a1e28b1154 | [
"MIT"
] | null | null | null | 32.727273 | 104 | 0.656746 | 997,230 | package com.domo4pi.core.mock;
import com.domo4pi.alarm.nodes.Node;
import com.domo4pi.alarm.nodes.RemoteNode;
import com.domo4pi.core.mock.node.RemoteNodeMockController;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MockApp extends Application implements Runnable {
private static final Logger log = LoggerFactory.getLogger(MockApp.class);
@Override
public void start(Stage gpioStage) throws Exception {
ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
Parent gpioRoot = FXMLLoader.load(contextClassLoader.getResource("GPIO.fxml"));
gpioStage.setTitle("GPIO");
gpioStage.setScene(new Scene(gpioRoot, 600, 400));
gpioStage.setResizable(false);
gpioStage.show();
Stage serialStage = new Stage();
Parent serialRoot = FXMLLoader.load(contextClassLoader.getResource("Serial.fxml"));
serialStage.setTitle("Serial");
serialStage.setScene(new Scene(serialRoot, 500, 200));
serialStage.setResizable(false);
serialStage.show();
for (Node node : com.domo4pi.application.Application.getInstance().getAlarmDefinition().nodes) {
if (node instanceof RemoteNode) {
Stage remoteStage = new Stage();
FXMLLoader loader = new FXMLLoader(contextClassLoader.getResource("Remote.fxml"));
Parent remoteRoot = (Parent)loader.load();
remoteStage.setTitle(node.name);
remoteStage.setScene(new Scene(remoteRoot, 250, 300));
remoteStage.setResizable(false);
remoteStage.show();
RemoteNodeMockController controller = loader.getController();
controller.setRemoteNode(node.name);
}
}
}
@Override
public void run() {
launch();
}
private static final MockApp instance = new MockApp();
private static final Thread thread = new Thread(instance, "GUI");
public static MockApp getInstance() {
return instance;
}
public static void startGUI() {
thread.start();
}
public static void stopGUI() {
try {
getInstance().stop();
} catch (Exception e) {
log.error("Unable to stop GUI", e);
}
}
}
|
923546d92df40e00a04211da835833ad868ec74e | 6,039 | java | Java | zoj/src/main/java/open/ex/zoj/geo/p1123/Main.java | shhuan/algorithms | 2830c7e2ada8dfd3dcdda7c06846116d4f944a27 | [
"MIT"
] | null | null | null | zoj/src/main/java/open/ex/zoj/geo/p1123/Main.java | shhuan/algorithms | 2830c7e2ada8dfd3dcdda7c06846116d4f944a27 | [
"MIT"
] | null | null | null | zoj/src/main/java/open/ex/zoj/geo/p1123/Main.java | shhuan/algorithms | 2830c7e2ada8dfd3dcdda7c06846116d4f944a27 | [
"MIT"
] | 1 | 2022-03-09T04:52:55.000Z | 2022-03-09T04:52:55.000Z | 24.350806 | 99 | 0.552575 | 997,231 | package open.ex.zoj.geo.p1123;
import java.util.Scanner;
/**
* @author huash06
*
* 题意: 按照指定格式输出所有在给定三角形内部的点
*
* 分析: 計算點是否在三角形內部
*/
public class Main {
public static boolean ONLINE_JUDGE = true;
public static int MAXN = 20;
public static boolean[][] M = new boolean[MAXN][MAXN];
public static void main(String[] args) {
if (!ONLINE_JUDGE) {
System.setIn(Main.class.getClassLoader().getResourceAsStream("input_1123.txt"));
// try {
// System.setOut(new PrintStream(new
// FileOutputStream(Main.class.getClassLoader().getResource("")
// .getPath()
// + "/output_1123.txt")));
// } catch (FileNotFoundException e) {
// e.printStackTrace();
// }
}
System.out.println("Program 4 by team X");
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextInt()) {
int vx1 = scanner.nextInt();
int vy1 = scanner.nextInt();
int vx2 = scanner.nextInt();
int vy2 = scanner.nextInt();
int vx3 = scanner.nextInt();
int vy3 = scanner.nextInt();
Vector3i A = new Vector3i(vx1, vy1, 0);
Vector3i B = new Vector3i(vx2, vy2, 0);
Vector3i C = new Vector3i(vx3, vy3, 0);
int minX = Math.min(vx1, Math.min(vx2, vx3));
int maxX = Math.max(vx1, Math.max(vx2, vx3));
int minY = Math.min(vy1, Math.min(vy2, vy3));
int maxY = Math.max(vy1, Math.max(vy2, vy3));
for (int i = 0; i < MAXN; i++) {
for (int j = 0; j < MAXN; j++) {
M[i][j] = false;
}
}
int startX = MAXN;
int startY = 0;
for (int x = minX; x <= maxX; x++) {
for (int y = minY; y <= maxY; y++) {
Vector3i P = new Vector3i(x, y, 0);
if (Vector3i.pointInTriangle(A, B, C, P)) {
M[x - minX][y - minY] = true;
startX = Math.min(startX, x - minX);
startY = Math.max(startY, y - minY);
}
}
}
for (int y = startY; y >= 0; y--) {
// System.out.println("12345678901234567890123456789012345678901234567890");
boolean exists = false;
for (int x = startX; x <= maxX - minX; x++) {
if (M[x][y]) {
exists = true;
if (x > startX) {
System.out.print(" ");
}
System.out.print("(" + String.format("%2d", x + minX) + ", " + String.format("%2d", y + minY)
+ ")");
} else {
boolean hasNext = false;
for (int xi = x + 1; xi <= maxX - minX; xi++) {
if (M[xi][y]) {
hasNext = true;
break;
}
}
if (hasNext) {
if (x > startX) {
System.out.print(" ");
} else {
System.out.print(" ");
}
} else {
break;
}
}
}
if (exists || y == 0) {
System.out.println();
}
}
}
System.out.println("End of program 4 by team X");
scanner.close();
}
/**
*
* 三角形的三个点在同一个平面上,如果选中其中一个点,其他两个点不过是相对该点的位移而已,比如选择点A作为起点,
* 那么点B相当于在AB方向移动一段距离得到,而点C相当于在AC方向移动一段距离得到。
*
*
*
* 所以对于平面内任意一点,都可以由如下方程来表示
*
* P = A + u * (C – A) + v * (B - A) // 方程1
*
* 如果系数u或v为负值,那么相当于朝相反的方向移动,即BA或CA方向。那么如果想让P位于三角形ABC内部,u和v必须满足什么条件呢?有如下三个条件
*
* u >= 0
*
* v >= 0
*
* u + v <= 1
*
* 几个边界情况,当u = 0且v = 0时,就是点A,当u = 0,v = 1时,就是点B,而当u = 1, v = 0时,就是点C
*
* 整理方程1得到P – A = u(C - A) + v(B - A)
*
* 令v0 = C – A, v1 = B – A, v2 = P – A,则v2 = u * v0 + v *v1,
* 现在是一个方程,两个未知数,无法解出u和v,将等式两边分别点乘v0和v1的到两个等式
*
* (v2) • v0 = (u * v0 + v * v1) • v0
*
* (v2) • v1 = (u * v0 + v * v1) • v1
*
* 注意到这里u和v是数,而v0,v1和v2是向量,所以可以将点积展开得到下面的式子。
*
* v2 • v0 = u * (v0 • v0) + v * (v1 • v0) // 式1
*
* v2 • v1 = u * (v0 • v1) + v * (v1• v1) // 式2
*
* 解这个方程得到
*
* u = ((v1•v1)(v2•v0)-(v1•v0)(v2•v1)) / ((v0•v0)(v1•v1) - (v0•v1)(v1•v0))
*
* v = ((v0•v0)(v2•v1)-(v0•v1)(v2•v0)) / ((v0•v0)(v1•v1) - (v0•v1)(v1•v0))
*
* @param A
* @param B
* @param C
* @param P
* @return 由于精度问题, 这个方法不是非常准确 点(-6, 3) (-5, 3) (-4, 3) (-3, 3)在三角形-7 -1 -2 3
* -7 3的边上,但是返回true
*
*/
public static boolean pointInTriangle(Vector3i A, Vector3i B, Vector3i C, Vector3i P) {
Vector3i v0 = C.sub(A);
Vector3i v1 = B.sub(A);
Vector3i v2 = P.sub(A);
int dot00 = v0.dot(v0);
int dot01 = v0.dot(v1);
int dot02 = v0.dot(v2);
int dot11 = v1.dot(v1);
int dot12 = v1.dot(v2);
float inverDeno = 1.0f / (dot00 * dot11 - dot01 * dot01);
float u = (dot11 * dot02 - dot01 * dot12) * inverDeno;
if (u <= 0 || u >= 1) // if u out of range, return directly
{
return false;
}
float v = (dot00 * dot12 - dot01 * dot02) * inverDeno;
if (v <= 0 || v >= 1) // if v out of range, return directly
{
return false;
}
return u + v < 1;
}
}
class Vector3i {
public int x;
public int y;
public int z;
public Vector3i(int x, int y, int z) {
super();
this.x = x;
this.y = y;
this.z = z;
}
Vector3i sub(Vector3i v) {
return new Vector3i(x - v.x, y - v.y, z - v.z);
}
int dot(Vector3i v) {
return x * v.x + y * v.y + z * v.z;
}
Vector3i cross(Vector3i v) {
return new Vector3i(y * v.z - z * v.y, z * v.x - x * v.z, x * v.y - y * v.x);
}
/**
*
* 假设点P位于三角形内,会有这样一个规律,当我们沿着ABCA的方向在三条边上行走时,你会发现点P始终位于边AB,BC和CA的右侧。我们就利用这一点,
* 但是如何判断一个点在线段的左侧还是右侧呢?我们可以从另一个角度来思考
* ,当选定线段AB时,点C位于AB的右侧,同理选定BC时,点A位于BC的右侧,最后选定CA时
* ,点B位于CA的右侧,所以当选择某一条边时,我们只需验证点P与该边所对的点在同一侧即可
* 。问题又来了,如何判断两个点在某条线段的同一侧呢?可以通过叉积来实现
* ,连接PA,将PA和AB做叉积,再将CA和AB做叉积,如果两个叉积的结果方向一致
* ,那么两个点在同一测。判断两个向量的是否同向可以用点积实现,如果点积大于0,则两向量夹角是锐角,否则是钝角。
*
* @param A
* @param B
* @param C
* @param P
* @return
*/
public static boolean sameSide(Vector3i A, Vector3i B, Vector3i C, Vector3i P) {
Vector3i AB = B.sub(A);
Vector3i AC = C.sub(A);
Vector3i AP = P.sub(A);
Vector3i v1 = AB.cross(AC);
Vector3i v2 = AB.cross(AP);
// v1 and v2 should point to the same direction
return v1.dot(v2) > 0;
}
public static boolean pointInTriangle(Vector3i A, Vector3i B, Vector3i C, Vector3i P) {
return sameSide(A, B, C, P) && sameSide(B, C, A, P) && sameSide(C, A, B, P);
}
@Override
public String toString() {
return "Vector3i [x=" + x + ", y=" + y + ", z=" + z + "]";
}
}
|
92354798a6f2ad4daebfbcf5870b69386d8d4637 | 4,004 | java | Java | server/src/main/java/password/pwm/util/cli/commands/UserReportCommand.java | blissjoe/pwm | 38a4750448fea2ac21f2fe8b37163f194fd3747f | [
"Apache-2.0"
] | 812 | 2015-10-21T11:00:34.000Z | 2022-03-23T12:11:01.000Z | server/src/main/java/password/pwm/util/cli/commands/UserReportCommand.java | blissjoe/pwm | 38a4750448fea2ac21f2fe8b37163f194fd3747f | [
"Apache-2.0"
] | 457 | 2015-10-28T16:31:16.000Z | 2022-03-31T23:28:25.000Z | server/src/main/java/password/pwm/util/cli/commands/UserReportCommand.java | blissjoe/pwm | 38a4750448fea2ac21f2fe8b37163f194fd3747f | [
"Apache-2.0"
] | 305 | 2015-10-23T15:42:08.000Z | 2022-03-26T12:45:40.000Z | 32.819672 | 130 | 0.641858 | 997,232 | /*
* Password Management Servlets (PWM)
* http://www.pwm-project.org
*
* Copyright (c) 2006-2009 Novell, Inc.
* Copyright (c) 2009-2021 The PWM 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 password.pwm.util.cli.commands;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import password.pwm.PwmApplication;
import password.pwm.PwmConstants;
import password.pwm.health.HealthRecord;
import password.pwm.svc.PwmService;
import password.pwm.svc.report.ReportCsvUtility;
import password.pwm.svc.report.ReportService;
import password.pwm.util.cli.CliParameters;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
public class UserReportCommand extends AbstractCliCommand
{
private static final String OUTPUT_FILE_OPTIONNAME = "outputFile";
@Override
@SuppressFBWarnings( "DM_EXIT" )
void doCommand( )
throws Exception
{
final File outputFile = ( File ) cliEnvironment.getOptions().get( OUTPUT_FILE_OPTIONNAME );
try ( OutputStream outputFileStream = new BufferedOutputStream( new FileOutputStream( outputFile ) ) )
{
final PwmApplication pwmApplication = cliEnvironment.getPwmApplication();
final ReportService userReport = pwmApplication.getReportService();
if ( userReport.status() != PwmService.STATUS.OPEN )
{
out( "report service is not open or enabled" );
final List<HealthRecord> healthIssues = userReport.healthCheck();
if ( healthIssues != null )
{
for ( final HealthRecord record : healthIssues )
{
out( "report health status: " + record.toDebugString( Locale.getDefault(), pwmApplication.getConfig() ) );
}
}
return;
}
final ReportCsvUtility reportCsvUtility = new ReportCsvUtility( pwmApplication );
reportCsvUtility.outputToCsv( outputFileStream, true, PwmConstants.DEFAULT_LOCALE );
}
catch ( final IOException e )
{
out( "unable to open file '" + outputFile.getAbsolutePath() + "' for writing" );
System.exit( -1 );
throw new Exception();
}
out( "report output complete." );
}
@Override
public CliParameters getCliParameters( )
{
final CliParameters.Option outputFileOption = new CliParameters.Option()
{
@Override
public boolean isOptional( )
{
return false;
}
@Override
public Type getType( )
{
return Type.NEW_FILE;
}
@Override
public String getName( )
{
return OUTPUT_FILE_OPTIONNAME;
}
};
final CliParameters cliParameters = new CliParameters();
cliParameters.commandName = "ExportUserReportDetail";
cliParameters.description = "Output user report details to the output file (csv format)";
cliParameters.options = Collections.singletonList( outputFileOption );
cliParameters.needsPwmApplication = true;
cliParameters.readOnly = false;
return cliParameters;
}
}
|
923547c5a3d776da5e44ad97ba9b6b47497eb241 | 474 | java | Java | lab5/lab5/src/main/java/repository/BibliographyRepository.java | Amihaeseisergiu/Java-Technologies | 7071d3c9560c42dcd8980bd0e885294e3efc1cb4 | [
"MIT"
] | null | null | null | lab5/lab5/src/main/java/repository/BibliographyRepository.java | Amihaeseisergiu/Java-Technologies | 7071d3c9560c42dcd8980bd0e885294e3efc1cb4 | [
"MIT"
] | null | null | null | lab5/lab5/src/main/java/repository/BibliographyRepository.java | Amihaeseisergiu/Java-Technologies | 7071d3c9560c42dcd8980bd0e885294e3efc1cb4 | [
"MIT"
] | null | null | null | 23.7 | 104 | 0.799578 | 997,233 | package repository;
import abstraction.DataRepository;
import java.io.Serializable;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Named;
import javax.transaction.Transactional;
import model.Bibliography;
@Named
@ApplicationScoped
@Transactional
public class BibliographyRepository extends DataRepository<Bibliography, Long> implements Serializable {
public BibliographyRepository()
{
super(Bibliography.class, false);
}
}
|
92354833bf00cb0b2fb243d1d6fd2608113c7d47 | 1,172 | java | Java | src/test/java/examples/HexBytes.java | Salpadding/rlp-stream | 05d5fa3103bf5e2979954b0a4a30f9ed8563e453 | [
"MIT"
] | 2 | 2021-05-23T05:36:01.000Z | 2021-05-25T10:06:24.000Z | src/test/java/examples/HexBytes.java | Salpadding/rlp-stream | 05d5fa3103bf5e2979954b0a4a30f9ed8563e453 | [
"MIT"
] | null | null | null | src/test/java/examples/HexBytes.java | Salpadding/rlp-stream | 05d5fa3103bf5e2979954b0a4a30f9ed8563e453 | [
"MIT"
] | 1 | 2021-05-25T03:49:42.000Z | 2021-05-25T03:49:42.000Z | 27.255814 | 81 | 0.699659 | 997,234 | package examples;
import com.github.salpadding.rlpstream.Rlp;
import com.github.salpadding.rlpstream.RlpBuffer;
import com.github.salpadding.rlpstream.RlpWritable;
import com.github.salpadding.rlpstream.StreamId;
import com.github.salpadding.rlpstream.annotation.RlpCreator;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import org.spongycastle.util.encoders.Hex;
// represent bytearray in hex encoding
@RequiredArgsConstructor
@Getter
public class HexBytes implements RlpWritable {
private final byte[] data;
@RlpCreator
public static HexBytes fromRlpStream(byte[] bin, long streamId) {
return new HexBytes(StreamId.asBytes(bin, streamId));
}
@Override
public String toString() {
return Hex.toHexString(data);
}
@Override
public int writeToBuf(RlpBuffer buffer) {
return buffer.writeBytes(data);
}
public static void main(String[] args) {
System.out.println(
Hex.toHexString(Rlp.encode(new HexBytes(new byte[]{0x01, 0x01})))
);
System.out.println(
Rlp.decode(new byte[]{(byte) 0x82, 1, 1}, HexBytes.class)
);
}
}
|
9235490630e20fd59d6e796402d895995c583f8f | 5,200 | java | Java | hihope_neptune-oh_hid/00_src/v0.1/third_party/icu/ohos_icu4j/src/main/java/ohos/global/icu/impl/CharacterPropertiesImpl.java | dawmlight/vendor_oh_fun | bc9fb50920f06cd4c27399f60076f5793043c77d | [
"Apache-2.0"
] | 1 | 2022-02-15T08:51:55.000Z | 2022-02-15T08:51:55.000Z | hihope_neptune-oh_hid/00_src/v0.3/third_party/icu/ohos_icu4j/src/main/java/ohos/global/icu/impl/CharacterPropertiesImpl.java | dawmlight/vendor_oh_fun | bc9fb50920f06cd4c27399f60076f5793043c77d | [
"Apache-2.0"
] | null | null | null | hihope_neptune-oh_hid/00_src/v0.3/third_party/icu/ohos_icu4j/src/main/java/ohos/global/icu/impl/CharacterPropertiesImpl.java | dawmlight/vendor_oh_fun | bc9fb50920f06cd4c27399f60076f5793043c77d | [
"Apache-2.0"
] | null | null | null | 41.269841 | 93 | 0.618846 | 997,235 | /* GENERATED SOURCE. DO NOT MODIFY. */
// © 2018 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html#License
package ohos.global.icu.impl;
import ohos.global.icu.lang.UCharacter;
import ohos.global.icu.lang.UProperty;
import ohos.global.icu.text.UnicodeSet;
/**
* Properties functionality above class UCharacterProperty
* but below class CharacterProperties and class UnicodeSet.
* @hide exposed on OHOS
*/
public final class CharacterPropertiesImpl {
private static final int NUM_INCLUSIONS = UCharacterProperty.SRC_COUNT +
UProperty.INT_LIMIT - UProperty.INT_START;
/**
* A set of all characters _except_ the second through last characters of
* certain ranges. These ranges are ranges of characters whose
* properties are all exactly alike, e.g. CJK Ideographs from
* U+4E00 to U+9FA5.
*/
private static final UnicodeSet inclusions[] = new UnicodeSet[NUM_INCLUSIONS];
/** For {@link UnicodeSet#setDefaultXSymbolTable}. */
public static synchronized void clear() {
for (int i = 0; i < inclusions.length; ++i) {
inclusions[i] = null;
}
}
private static UnicodeSet getInclusionsForSource(int src) {
if (inclusions[src] == null) {
UnicodeSet incl = new UnicodeSet();
switch(src) {
case UCharacterProperty.SRC_CHAR:
UCharacterProperty.INSTANCE.addPropertyStarts(incl);
break;
case UCharacterProperty.SRC_PROPSVEC:
UCharacterProperty.INSTANCE.upropsvec_addPropertyStarts(incl);
break;
case UCharacterProperty.SRC_CHAR_AND_PROPSVEC:
UCharacterProperty.INSTANCE.addPropertyStarts(incl);
UCharacterProperty.INSTANCE.upropsvec_addPropertyStarts(incl);
break;
case UCharacterProperty.SRC_CASE_AND_NORM:
Norm2AllModes.getNFCInstance().impl.addPropertyStarts(incl);
UCaseProps.INSTANCE.addPropertyStarts(incl);
break;
case UCharacterProperty.SRC_NFC:
Norm2AllModes.getNFCInstance().impl.addPropertyStarts(incl);
break;
case UCharacterProperty.SRC_NFKC:
Norm2AllModes.getNFKCInstance().impl.addPropertyStarts(incl);
break;
case UCharacterProperty.SRC_NFKC_CF:
Norm2AllModes.getNFKC_CFInstance().impl.addPropertyStarts(incl);
break;
case UCharacterProperty.SRC_NFC_CANON_ITER:
Norm2AllModes.getNFCInstance().impl.addCanonIterPropertyStarts(incl);
break;
case UCharacterProperty.SRC_CASE:
UCaseProps.INSTANCE.addPropertyStarts(incl);
break;
case UCharacterProperty.SRC_BIDI:
UBiDiProps.INSTANCE.addPropertyStarts(incl);
break;
case UCharacterProperty.SRC_INPC:
case UCharacterProperty.SRC_INSC:
case UCharacterProperty.SRC_VO:
UCharacterProperty.ulayout_addPropertyStarts(src, incl);
break;
default:
throw new IllegalStateException("getInclusions(unknown src " + src + ")");
}
// We do not freeze() the set because we only iterate over it,
// rather than testing contains(),
// so the extra time and memory to optimize that are not necessary.
inclusions[src] = incl.compact();
}
return inclusions[src];
}
private static UnicodeSet getIntPropInclusions(int prop) {
assert(UProperty.INT_START <= prop && prop < UProperty.INT_LIMIT);
int inclIndex = UCharacterProperty.SRC_COUNT + prop - UProperty.INT_START;
if (inclusions[inclIndex] != null) {
return inclusions[inclIndex];
}
int src = UCharacterProperty.INSTANCE.getSource(prop);
UnicodeSet incl = getInclusionsForSource(src);
UnicodeSet intPropIncl = new UnicodeSet(0, 0);
int numRanges = incl.getRangeCount();
int prevValue = 0;
for (int i = 0; i < numRanges; ++i) {
int rangeEnd = incl.getRangeEnd(i);
for (int c = incl.getRangeStart(i); c <= rangeEnd; ++c) {
// TODO: Get a UCharacterProperty.IntProperty to avoid the property dispatch.
int value = UCharacter.getIntPropertyValue(c, prop);
if (value != prevValue) {
intPropIncl.add(c);
prevValue = value;
}
}
}
// Compact for caching.
return inclusions[inclIndex] = intPropIncl.compact();
}
/**
* Returns a mutable UnicodeSet -- do not modify!
*/
public static synchronized UnicodeSet getInclusionsForProperty(int prop) {
if (UProperty.INT_START <= prop && prop < UProperty.INT_LIMIT) {
return getIntPropInclusions(prop);
} else {
int src = UCharacterProperty.INSTANCE.getSource(prop);
return getInclusionsForSource(src);
}
}
}
|
92354980080e1a921d4e0129da0578e166d5ecd9 | 3,301 | java | Java | src/main/java/simbad/sim/DefaultKinematic.java | utarwyn/simbad-school-pong | b6b135aef0805e28efeedb135a869800a97de4c0 | [
"MIT"
] | 2 | 2021-01-13T16:10:38.000Z | 2021-11-29T09:35:21.000Z | src/main/java/simbad/sim/DefaultKinematic.java | utarwyn/simbad-school-pong | b6b135aef0805e28efeedb135a869800a97de4c0 | [
"MIT"
] | null | null | null | src/main/java/simbad/sim/DefaultKinematic.java | utarwyn/simbad-school-pong | b6b135aef0805e28efeedb135a869800a97de4c0 | [
"MIT"
] | null | null | null | 27.057377 | 123 | 0.702211 | 997,236 | /*
* Simbad - Robot Simulator
* Copyright (C) 2004 Louis Hugues
*
* 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; either version 2 of the License, or
* (at your option) any later version.
*
* 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
-----------------------------------------------------------------------------
* $Author: sioulseuguh $
* $Date: 2005/03/17 17:49:37 $
* $Revision: 1.3 $
* $Source: /cvsroot/simbad/src/simbad/sim/DefaultKinematic.java,v $
*/
package simbad.sim;
import javax.media.j3d.Transform3D;
import javax.vecmath.Vector3d;
import java.text.DecimalFormat;
/**
* This is the standard kinematic with two control parameters : translation and rotation.
* Each agent use this kinematic by default.
*/
public class DefaultKinematic extends KinematicModel {
/**
* Translational velocity in meters per second.
*/
private double translationalVelocity;
/**
* Rotational velocity in radians per second
*/
private double rotationalVelocity;
DefaultKinematic() {
reset();
}
/**
* Resets all control parameters to their initial values.
*/
protected void reset() {
rotationalVelocity = 0;
translationalVelocity = 0;
}
/**
* Compute instant translation and rotation vectors .
*
* @param elapsedSecond time elapsed
* @param rotation current rotation
* @param instantTranslation to store translation
* @param instantRotation to store rotation
*/
protected void update(double elapsedSecond, Transform3D rotation, Vector3d instantTranslation, Vector3d instantRotation) {
instantTranslation.set(translationalVelocity * elapsedSecond, 0.0, 0.0);
// apply current rotation (on y axis)
rotation.transform(instantTranslation);
// perform rotation - on y axis
instantRotation.set(0, elapsedSecond * rotationalVelocity, 0);
}
/**
* Sets rotational velocity in radians per second.
*/
public final void setRotationalVelocity(double rv) {
rotationalVelocity = rv;
}
/**
* Sets translational velocity in meter per second.
*/
public final void setTranslationalVelocity(double tv) {
translationalVelocity = tv;
}
/**
* Gets rotational velocity in radians per second
*/
public final double getRotationalVelocity() {
return rotationalVelocity;
}
/**
* Gets translational velocity in meter per second.
*/
public final double getTranslationalVelocity() {
return translationalVelocity;
}
/**
* Resets all control parameters to their initial values.
*/
protected String toString(DecimalFormat format) {
return "kinematic \t= DefaultKinematic\n" +
"rotVelocity \t= " + format.format(rotationalVelocity) + " rad/s\n" +
"transVelocity \t= " + format.format(translationalVelocity) + " m/s\n";
}
}
|
92354982083e82e289d1675cebc468ec0f2b94fa | 997 | java | Java | plugin/core/gen/com/perl5/lang/perl/psi/impl/PsiPerlForInitImpl.java | saintserge/Perl5-IDEA | 868ba3415fd179dc208c67f822cb450d2c80a8d8 | [
"Apache-2.0"
] | 1 | 2022-01-14T19:40:28.000Z | 2022-01-14T19:40:28.000Z | plugin/core/gen/com/perl5/lang/perl/psi/impl/PsiPerlForInitImpl.java | saintserge/Perl5-IDEA | 868ba3415fd179dc208c67f822cb450d2c80a8d8 | [
"Apache-2.0"
] | null | null | null | plugin/core/gen/com/perl5/lang/perl/psi/impl/PsiPerlForInitImpl.java | saintserge/Perl5-IDEA | 868ba3415fd179dc208c67f822cb450d2c80a8d8 | [
"Apache-2.0"
] | null | null | null | 27.694444 | 92 | 0.77332 | 997,237 | // This is a generated file. Not intended for manual editing.
package com.perl5.lang.perl.psi.impl;
import java.util.List;
import org.jetbrains.annotations.*;
import com.intellij.lang.ASTNode;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiElementVisitor;
import com.intellij.psi.util.PsiTreeUtil;
import static com.perl5.lang.perl.lexer.PerlElementTypesGenerated.*;
import com.perl5.lang.perl.psi.*;
public class PsiPerlForInitImpl extends PerlCompositeElementImpl implements PsiPerlForInit {
public PsiPerlForInitImpl(ASTNode node) {
super(node);
}
public void accept(@NotNull PsiPerlVisitor visitor) {
visitor.visitForInit(this);
}
@Override
public void accept(@NotNull PsiElementVisitor visitor) {
if (visitor instanceof PsiPerlVisitor) accept((PsiPerlVisitor)visitor);
else super.accept(visitor);
}
@Override
@NotNull
public PsiPerlExpr getExpr() {
return notNullChild(PsiTreeUtil.getChildOfType(this, PsiPerlExpr.class));
}
}
|
923549ed7fb24678f4c818b4a89632c29bad7393 | 19,068 | java | Java | tests/core/src/main/java/hydra/GemFirePrms.java | xyxiaoyou/snappy-store | 013ff282f888878cc99600e260ec1cde60112304 | [
"Apache-2.0"
] | 38 | 2016-01-04T01:31:40.000Z | 2020-04-07T06:35:36.000Z | tests/core/src/main/java/hydra/GemFirePrms.java | xyxiaoyou/snappy-store | 013ff282f888878cc99600e260ec1cde60112304 | [
"Apache-2.0"
] | 261 | 2016-01-07T09:14:26.000Z | 2019-12-05T10:15:56.000Z | tests/core/src/main/java/hydra/GemFirePrms.java | xyxiaoyou/snappy-store | 013ff282f888878cc99600e260ec1cde60112304 | [
"Apache-2.0"
] | 22 | 2016-03-09T05:47:09.000Z | 2020-04-02T17:55:30.000Z | 33.748673 | 128 | 0.640025 | 997,238 | /*
* Copyright (c) 2010-2015 Pivotal Software, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you
* may not use this file except in compliance with the License. You
* may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License. See accompanying
* LICENSE file.
*/
package hydra;
import java.util.*;
import com.gemstone.gemfire.cache.Cache;
/**
*
* A class used to store keys for GemFire configuration settings. The settings
* are used to create instances of {@link hydra.GemFireDescription}, which are
* used to configure and manage both gemfire systems and distributed systems.
* <p>
* The number of instances is gated by {@link #names}. The remaining parameters
* have the indicated default values. If fewer non-default values than names
* are given for these parameters, the remaining instances will use the last
* value in the list. See $JTESTS/hydra/hydra.txt for more details.
*
*/
public class GemFirePrms extends BasePrms {
public static final String GEMFIRE_NAME_PROPERTY = "gemfireName";
public static final String DISTRIBUTED_SYSTEM_NAME_PROPERTY = "distributedSystemName";
public static final String DEFAULT_DISTRIBUTED_SYSTEM_NAME = "ds";
/** Name for loner distributed systems. */
public static final String LONER = "loner";
public static final String NONE = "none";
/**
* (String(s))
* Logical names of the GemFire descriptions. Each name must be unique.
* Defaults to null. See the include files in $JTESTS/hydraconfig for
* common configurations.
*/
public static Long names;
/**
* (String(s))
* Used to group nodes into distributed systems. Defaults to {@link
* #DEFAULT_DISTRIBUTED_SYSTEM_NAME}.
* <p>
* To create a loner distributed system, use {@link #LONER}, which is
* reserved for this purpose (and is case-insensitive).
*/
public static Long distributedSystem;
/**
* (Comma-separated list of String(s))
* Remote distributed system names to use when connecting as a locator
* with {@link DistributedSystemHelper} in a WAN configuration. Defaults
* to {@link #NONE}. This is used to set the <code>remote-locators</code>
* property to the locators that have been created for each remote
* distributed system with {@link DistributedSystemHelper#createLocator}.
* <p>
* Suitable test configuration functions to use with the WAN topology
* include files in $JTESTS/hydraconfig are:
* <pre>
* <code>
* // for a ring-connected locator topology
* fcn "hydra.TestConfigFcns.generateNamesRepeatedlyShift
* (\"ds_\", ${wanSites}, ${locatorHostsPerSite}, false, true)" ncf,
* none;
*
* // for a fully-connected locator topology
* fcn "hydra.TestConfigFcns.generateNameListsRepeatedlyShift
* (\"ds_\", ${wanSites}, ${locatorHostsPerSite})" ncf,
* none;
* </code>
* </pre>
*/
public static Long remoteDistributedSystems;
/**
* (String)
* Gives the extra VM arguments passed to all master-managed locators.
* Ignored if {@link Prms#manageLocatorAgents} is false.
* Defaults to null.
*/
public static Long extraLocatorVMArgs;
protected static String getExtraLocatorVMArgs(int i) {
Long key = extraLocatorVMArgs;
String args = null;
Vector val = tab().vecAtWild( extraLocatorVMArgs, i, null );
if ( val != null ) {
args = "";
for ( Iterator it = val.iterator(); it.hasNext(); ) {
try {
String arg = (String) it.next();
if ( arg.equals( "=" ) ) {
throw new HydraConfigException( "Malformed value in " + nameForKey(key) + ", use quotes to include '='" );
} else {
args += " " + arg;
}
} catch( ClassCastException e ) {
e.printStackTrace();
throw new HydraConfigException( "Malformed value in " + nameForKey(key) + ", use single string or list of values" );
}
}
}
// Use IPv6 addresses if asked
if (TestConfig.tab().booleanAt(Prms.useIPv6)) {
if (args == null) args = "";
args += " -D" + Prms.USE_IPV6_PROPERTY + "=true";
}
return args;
}
/**
* (String(s))
* Extra classpath for master-managed locators, if used.
* Ignored if {@link Prms#manageLocatorAgents} is false.
* Default is the corresponding
* entry in {@link hydra.HostPrms#testDirs} for the target host O/S, and
* lib/gemfire.jar from the corresponding entry in
* {@link hydra.HostPrms#gemfireHomes}, if it is defined. The extra
* classpaths, if any, are prepended to the defaults. All occurrences of
* $JTESTS and $GEMFIRE in a path are expanded relative to -DJTESTS and
* -Dgemfire.home on the target host.
* Gives the extra VM arguments passed to all master-managed locators.
*/
public static Long extraLocatorClassPath;
/**
* (String(s))
* Logical names of the host descriptions to use when creating gemfire
* systems. Defaults to null.
*
* @see HostPrms#names
* @see HostDescription
*/
public static Long hostNames;
/**
* (boolean(s))
* Tells hydra whether to stop system resources at the end of the test.
* Defaults to true. The resources will not be stopped if master detects a
* hung client or system process.
*/
public static Long stopSystemsAfterTest;
/**
* @see com.gemstone.gemfire.distributed.internal.DistributionConfig#DEFAULT_ACK_WAIT_THRESHOLD
*/
public static Long ackWaitThreshold;
/**
* @see com.gemstone.gemfire.distributed.internal.DistributionConfig#DEFAULT_LOG_LEVEL
*/
public static Long logLevel;
/**
* @see com.gemstone.gemfire.distributed.internal.DistributionConfig#DEFAULT_LOG_FILE_SIZE_LIMIT
*/
public static Long logFileSizeLimit;
/**
* @see com.gemstone.gemfire.distributed.internal.DistributionConfig#DEFAULT_LOG_DISK_SPACE_LIMIT
*/
public static Long logDiskSpaceLimit;
/**
* Whether to gather statistics. Defaults to true.
*/
public static Long statisticSamplingEnabled;
/**
* @see com.gemstone.gemfire.distributed.internal.DistributionConfig#DEFAULT_STATISTIC_SAMPLE_RATE
*/
public static Long statisticSampleRate;
/**
* @see com.gemstone.gemfire.distributed.internal.DistributionConfig#DEFAULT_ENABLE_TIME_STATISTICS
*/
public static Long enableTimeStatistics;
/**
* @see com.gemstone.gemfire.distributed.internal.DistributionConfig#DEFAULT_ARCHIVE_FILE_SIZE_LIMIT
*/
public static Long archiveFileSizeLimit;
/**
* @see com.gemstone.gemfire.distributed.internal.DistributionConfig#DEFAULT_ARCHIVE_DISK_SPACE_LIMIT
*/
public static Long archiveDiskSpaceLimit;
/**
* Whether to enable multicast for the distributed system. Defaults to false.
*/
public static Long enableMcast;
/**
* Whether to use Locator(s) for the distributed system. Defaults to true.
*/
public static Long useLocator;
/**
* Whether to turn on peer locator in locator(s). Defaults to true.
* Master-managed locators are always peer locators and ignore this
* parameter.
*/
public static Long isPeerLocator;
/**
* Whether to turn on server locator in locator(s). Defaults to true.
*/
public static Long isServerLocator;
/**
* Whether to allow multicast when IPv6 is used. Defaults to false.
* <p>
* IMPORTANT: This works around issues in our network that cause
* disruptive spikes. To test multicast with IPv6, first get approval
* from I.S. and run a short-lived test with their oversight.
*/
public static Long allowMcastWithIPv6;
/**
* @see com.gemstone.gemfire.distributed.internal.DistributionConfig#DEFAULT_MCAST_ADDRESS
*/
public static Long mcastAddress;
/**
* @see com.gemstone.gemfire.distributed.internal.DistributionConfig#DEFAULT_MCAST_PORT
*/
public static Long mcastPort;
/**
* See <code>mcast-ttl</code> in {@link
* com.gemstone.gemfire.distributed.DistributedSystem}. Defaults to 0.
*/
public static Long mcastTtl;
/**
* @see com.gemstone.gemfire.distributed.internal.DistributionConfig#DEFAULT_MCAST_SEND_BUFFER_SIZE
*/
public static Long mcastSendBufferSize;
/**
* @see com.gemstone.gemfire.distributed.internal.DistributionConfig#DEFAULT_MCAST_RECV_BUFFER_SIZE
*/
public static Long mcastRecvBufferSize;
/**
* @see com.gemstone.gemfire.distributed.internal.DistributionConfig#DEFAULT_MCAST_FLOW_CONTROL
*/
public static Long mcastFlowControlByteAllowance;
/**
* @see com.gemstone.gemfire.distributed.internal.DistributionConfig#DEFAULT_MCAST_FLOW_CONTROL
*/
public static Long mcastFlowControlRechargeThreshold;
/**
* @see com.gemstone.gemfire.distributed.internal.DistributionConfig#DEFAULT_MCAST_FLOW_CONTROL
*/
public static Long mcastFlowControlRechargeBlockMs;
/**
* @see com.gemstone.gemfire.distributed.internal.DistributionConfig#DEFAULT_UDP_FRAGMENT_SIZE
*/
public static Long udpFragmentSize;
/**
* @see com.gemstone.gemfire.distributed.internal.DistributionConfig#DEFAULT_UDP_SEND_BUFFER__SIZE
*/
public static Long udpSendBufferSize;
/**
* @see com.gemstone.gemfire.distributed.internal.DistributionConfig#DEFAULT_UDP_RECV_BUFFER__SIZE
*/
public static Long udpRecvBufferSize;
/**
* @see com.gemstone.gemfire.distributed.internal.DistributionConfig#DEFAULT_TCP_PORT
*/
public static Long tcpPort;
/**
* @see com.gemstone.gemfire.distributed.internal.DistributionConfig#DEFAULT_DISABLE_TCP
*/
public static Long disableTcp;
/**
* @see com.gemstone.gemfire.distributed.internal.DistributionConfig#DEFAULT_MEMBERSHIP_PORT_RANGE
*
* For example:
*
* hydra.GemFirePrms-membershipPortRange = 60000-61000;
*/
public static Long membershipPortRange;
/**
* @see com.gemstone.gemfire.distributed.internal.DistributionConfig#DEFAULT_MEMBER_TIMEOUT
*/
public static Long memberTimeout;
/**
* (boolean)
* Should gemfire conserveSockets? Defaults to "true", the minimal number
* of sockets will be used when connecting to the distributed system.
* This conserves resources usage but can cause performance to suffer.
* If "false", then every application thread that sends
* will own its own sockets and have exclusive access to them. The
* length of time a thread can have exclusive access to a socket can
* be configured with "socketLeaseTime".
*/
public static Long conserveSockets;
/**
* (Long)
* The number of ms a thread can keep exclusive access to a socket
* that it is not actively using. Once a thread loses its lease to
* a socket it will need to re-acquire a socket the next time it
* sends a message. A value of zero causes the socket leases to
* never expire. Default = 15000. Allowed values 0 ... 600000.
*/
public static Long socketLeaseTime;
/**
* (Long)
* The size of each socket buffer, in bytes. Smaller buffers conserve
* memory. Larger buffers can improve performance; in particular if
* large messages are being sent. Default = 32768. Allowed values =
* 128 ... 20000000.
*/
public static Long socketBufferSize;
// -------------- Asynchronous Messaging Properties ------------------
/**
* (int)
* The async-distribution-timeout: the time in ms to wait on socketWrite
* before queuing begins.
* Default value = 0 (no queuing). Allowed values 0 ... 60000
*/
public static Long asyncDistributionTimeout;
/**
* (int)
* The async-queue-timeout: the time in ms to queue before declaring
* a subscriber (slow) and triggering a High Priority disconnect to
* that slow subscriber.
* Default = 60000. Allowed values = 0 ... 60000.
*/
public static Long asyncQueueTimeout;
/**
* (int)
* The async-max-queue-size: value (in MB?) of the maximum queue
* size supported. Once this max size is reached, the slow receiver
* will be sent a High Priority disconnect and the queue will be cleared
* Default = 8. Allowed values = 0 ... 1024.
*/
public static Long asyncMaxQueueSize;
/**
* (String(s))
* Roles to use when creating gemfiresystems. Defaults to null.
*/
public static Long roles;
public static Long maxWaitTimeForReconnect;
public static Long maxNumReconnectTries;
/**
* (boolean)
* Whether to configure as a durableClient. Defaults to false.
* <p>
* If true, the durable-client-id will be set to the logical VM name and
* {@link #durableClientTimeout} will be set. If false, values for
* {@link #durableClientTimeout} will be ignored.
* <p>
* If enabled, clients must invoke {@link com.gemstone.gemfire.cache.Cache#readyForEvents} for the
* client to receive any updates from the server.
*/
public static Long enableDurableClient;
/**
* (int)
* The number of seconds a disconnected durable client's queue is kept alive (and updates accumulated) by
* the server. Ignored if {@link #enableDurableClient} is false. Default = 300.
*/
public static Long durableClientTimeout;
/**
* (String(s))
* Whether to conflate events for client queues. Intended for use by bridge
* clients (edges). Valid values are "server" (use the server setting),
* "true" (conflate), "false" (do not conflate).
*/
public static Long conflateEvents;
/**
* (String(s))
* Name of logical security configuration, as found in {@link
* SecurityPrms#names}. Can be specified as {@link #NONE} (default).
* <p>
* See also {@link #sslName}.
*/
public static Long securityName;
//------------------------------------------------------------------------------
// Partition redundancy
//------------------------------------------------------------------------------
/**
* (Boolean(s))
* Whether to enforce unique hosts for this description. Defaults to false.
*/
public static Long enforceUniqueHost;
/**
* (String(s))
* The redundancy zone for this description. Defaults to null.
*/
public static Long redundancyZone;
//------------------------------------------------------------------------------
// Split brain
//------------------------------------------------------------------------------
/**
* (int(s))
* The ack severe alert threshold, in seconds, for this description.
*/
public static Long ackSevereAlertThreshold;
/**
* (boolean(s))
* Whether to enable network partition detection for this description.
*/
public static Long enableNetworkPartitionDetection;
/**
* (boolean(s))
* Whether automatic reconnect after a forced disconnect is disabled.
*/
public static Long disableAutoReconnect;
//------------------------------------------------------------------------------
/**
* (String(s))
* Name of logical SSL configuration, as found in {@link SSLPrms#names}.
* Can be specified as {@link #NONE} (default).
* <p>
* See also {@link #securityName}.
*/
public static Long sslName;
//------------------------------------------------------------------------------
// jmx
//------------------------------------------------------------------------------
/**
* (boolean(s))
* Willingness to be a JMX manager. If this is false, all other JMX manager
* parameters are disregarded by the product. The product defaults to true
* for locators and false otherwise.
*/
public static Long jmxManager;
/**
* (String(s))
* Path to JMX manager access file.
*/
public static Long jmxManagerAccessFile;
/**
* (boolean(s))
* Whether to configure an autogenerated port for the JMX manager http
* server to use so that the GemFire Pulse application can connect to the
* manager on the port. Defaults to false, which sets the port to 0 and
* disables the http server. Otherwise generates an endpoint in the {@link
* JMXManagerBlackboard}. See also {@link #jmxManagerPort}.
*/
public static Long jmxManagerHttpPort;
/**
* (String(s))
* Path to JMX manager password file.
*/
public static Long jmxManagerPasswordFile;
/**
* (boolean(s))
* Whether to configure an autogenerated port for the JMX manager to use
* so that remote tools can connect to the manager on the port. Defaults to
* false, which sets the port to 0. Otherwise generates an endpoint in the
* {@link JMXManagerBlackboard}. See also {@link #jmxManagerHttpPort}.
*/
public static Long jmxManagerPort;
/**
* (boolean(s))
* Whether the JMX manager should use SSL. When true, requires specifying
* {@link #jmxManagerPort} and {@link #sslName}. Defaults to false.
*/
public static Long jmxManagerSSL;
/**
* (boolean(s))
* Whether to start the JMX manager on cache creation. Defaults to false.
*/
public static Long jmxManagerStart;
//------------------------------------------------------------------------------
// Delta propagation
//------------------------------------------------------------------------------
/**
* (boolean(s))
* Whether to enable delta propagation.
*/
public static Long deltaPropagation;
//------------------------------------------------------------------------------
//off heap memory
//------------------------------------------------------------------------------
/**
* (String(s))
* The total size of off-heap memory in the form <n>[g|m].
* <n> is the size. [g|m] indicates whether the size should be interpreted as
* gigabytes or megabytes.
*/
public static Long offHeapMemorySize;
/**
* (boolean(s))
* The "lock-memory" property. Locks both heap and off-heap memory.
* <p>
* When set true, required jna-3.5.1.jar in the product library to be added to
* the classpath.
* <p>
* The heap memory locked is the amount the JVM is started with. Set -Xms the
* same as -Xmx to lock all heap.
*/
public static Long lockMemory;
static {
setValues( GemFirePrms.class );
}
public static void main( String args[] ) {
Log.createLogWriter( "gemfireprms", "info" );
dumpKeys();
}
}
|
923549f69c33b25a155f7c4f652c258f22ac18ab | 2,448 | java | Java | back-end/src/main/java/it/bioagri/models/Tag.java | bioagrisrls/bioagri-website | c4336e141e5831dc4db1e8018aeea28497970f7f | [
"MIT"
] | null | null | null | back-end/src/main/java/it/bioagri/models/Tag.java | bioagrisrls/bioagri-website | c4336e141e5831dc4db1e8018aeea28497970f7f | [
"MIT"
] | null | null | null | back-end/src/main/java/it/bioagri/models/Tag.java | bioagrisrls/bioagri-website | c4336e141e5831dc4db1e8018aeea28497970f7f | [
"MIT"
] | 1 | 2021-02-27T14:10:23.000Z | 2021-02-27T14:10:23.000Z | 25.768421 | 81 | 0.629902 | 997,239 | /*
* MIT License
*
* Copyright (c) 2020 BioAgri S.r.l.s.
*
* 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 it.bioagri.models;
import java.util.Objects;
public final class Tag implements Model {
private long id;
private final String hashtag;
public Tag(Long id, String hashtag) {
this.id = id;
this.hashtag = hashtag;
}
public Tag() {
this.id = 0;
this.hashtag = null;
}
public void setId(long id) {
this.id = id;
}
public Long getId() {
return id;
}
public String getHashtag() {
return hashtag;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Tag tag = (Tag) o;
return getId().equals(tag.getId());
}
@Override
public int hashCode() {
return Objects.hash(getId());
}
public static final class Builder {
private long id;
private String hashtag;
public Builder withId(long id) {
this.id = id;
return this;
}
public Builder withHashtag(String hashtag) {
this.hashtag = hashtag;
return this;
}
public Tag build() {
Tag tag = new Tag(null, hashtag);
tag.setId(id);
return tag;
}
}
}
|
92354a356f3ecc822e2b0fe74572fb313f13931e | 2,271 | java | Java | hackerrank/src/main/java/com/tsmc/problems/ProblemA.java | Shallmay14/code-training | 753c1142a19b7ce3d8f7abb19d0caccca23aa0b7 | [
"Apache-2.0"
] | null | null | null | hackerrank/src/main/java/com/tsmc/problems/ProblemA.java | Shallmay14/code-training | 753c1142a19b7ce3d8f7abb19d0caccca23aa0b7 | [
"Apache-2.0"
] | null | null | null | hackerrank/src/main/java/com/tsmc/problems/ProblemA.java | Shallmay14/code-training | 753c1142a19b7ce3d8f7abb19d0caccca23aa0b7 | [
"Apache-2.0"
] | null | null | null | 29.493506 | 66 | 0.511669 | 997,240 | package com.tsmc.problems;
public class ProblemA {
/*
* Complete the 'getSubstring' function below.
*
* The function is expected to return a STRING.
* The function accepts following parameters:
* 1. STRING input_str
* 2. INTEGER k
*/
private static final Character TAR_CHAR = '1';
private static String res = "";
private static String temp = "";
private static int tempNum = 0;
public static String getSubstring(String input_str, int k) {
// Write your code here\
System.out.println(input_str);
System.out.println(k);
for(int i=0;i<input_str.length();i++){
Character c = input_str.charAt(i);
temp += c;
// System.out.println(temp);
if(TAR_CHAR.equals(c))
tempNum++;
checkNum(k);
}
return res;
}
private static void checkNum(int k){
if(k == tempNum){
temp = removeFrontZero(temp);
// System.out.println(tempNum);
System.out.println(temp);
if(res.length()==0 || compare(temp, res))
res = temp;
tempNum--;
temp = temp.substring(1, temp.length());
// System.out.println("after:"+tempNum);
// System.out.println("after:"+temp);
}
}
private static String removeFrontZero(String temp){
// System.out.println(temp);
while(!TAR_CHAR.equals(temp.charAt(0))){
temp = temp.substring(1);
}
// System.out.println("after:"+temp);
return temp;
}
private static boolean compare(String temp, String res){
if(temp.length() < res.length()){
return true;
} else if(temp.length() > res.length()){
return false;
} else {
for(int i=0;i<res.length();i++){
if(temp.charAt(i)<res.charAt(i)){
System.out.println(i+"true:"+temp.charAt(i));
return true;
} else if(temp.charAt(i)>res.charAt(i)){
System.out.println(i+"false:"+temp.charAt(i));
return false;
}
}
return false;
}
}
}
|
92354ac4bd371126b1d2f67a3ac2868a091226df | 459 | java | Java | web/src/main/java/uk/ac/ebi/phenotype/stats/model/AdditionalInformation.java | jwgwarren/PhenotypeData | a1a36fd0efacc6515ad843ff7ce4bebc3ae98393 | [
"Apache-2.0"
] | 1 | 2018-04-03T06:44:47.000Z | 2018-04-03T06:44:47.000Z | web/src/main/java/uk/ac/ebi/phenotype/stats/model/AdditionalInformation.java | jwgwarren/PhenotypeData | a1a36fd0efacc6515ad843ff7ce4bebc3ae98393 | [
"Apache-2.0"
] | 655 | 2016-05-16T13:04:02.000Z | 2022-03-25T14:06:36.000Z | web/src/main/java/uk/ac/ebi/phenotype/stats/model/AdditionalInformation.java | jwgwarren/PhenotypeData | a1a36fd0efacc6515ad843ff7ce4bebc3ae98393 | [
"Apache-2.0"
] | 6 | 2017-06-16T13:43:37.000Z | 2020-02-27T12:57:07.000Z | 25.5 | 71 | 0.799564 | 997,241 | package uk.ac.ebi.phenotype.stats.model;
import com.fasterxml.jackson.annotation.JsonProperty;
public class AdditionalInformation {
@JsonProperty("gender_included_in_analysis")
private String genderIncludedInAnalysis;//: "Both sexes included",
@JsonProperty("multibatch_in_analysis")
private String multiBatchInAnalysis;//: "Data contains multi batches",
@JsonProperty("summary_statistics")
private SummaryStatistics summaryStatistics;//: {
}
|
92354cabdd43d983931d0cba8fbc5fc7c0abdd3b | 1,309 | java | Java | src/com/shejiaomao/core/http/config/HttpConfigFactory.java | cattong/WidgetLibrary | 11fdd576da4506bc04491eb11f691e294232af77 | [
"Apache-2.0"
] | null | null | null | src/com/shejiaomao/core/http/config/HttpConfigFactory.java | cattong/WidgetLibrary | 11fdd576da4506bc04491eb11f691e294232af77 | [
"Apache-2.0"
] | null | null | null | src/com/shejiaomao/core/http/config/HttpConfigFactory.java | cattong/WidgetLibrary | 11fdd576da4506bc04491eb11f691e294232af77 | [
"Apache-2.0"
] | 1 | 2019-04-23T03:52:29.000Z | 2019-04-23T03:52:29.000Z | 27.851064 | 119 | 0.68602 | 997,242 | package com.shejiaomao.core.http.config;
import java.util.Hashtable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.shejiaomao.core.LibConstants;
import com.shejiaomao.core.ServiceProvider;
public class HttpConfigFactory {
private static final String CLASS_NAME_FORMAT = "com.shejiaomao.core.impl.%1$s.%2$sHttpConfig";
private static final Logger logger = LoggerFactory.getLogger(HttpConfigFactory.class);
private static Hashtable<ServiceProvider, HttpConfig> spHttpConfigs =
new Hashtable<ServiceProvider, HttpConfig>();
public static synchronized HttpConfig getHttpConfiguration(ServiceProvider sp) {
HttpConfig conf = spHttpConfigs.get(sp);
if (conf != null) {
return conf;
}
try {
if (sp == ServiceProvider.None) {
conf = new HttpConfigBase();
} else {
String className = String.format(CLASS_NAME_FORMAT,
sp.toString().toLowerCase(),
sp.toString()
);
conf = (HttpConfig) Class.forName(className).newInstance();
}
} catch (Exception e) {
if (LibConstants.level <= LibConstants.VERBOSE) logger.debug("Get HttpConfig instance unfound for {}", sp, e);
conf = new HttpConfigBase();
}
spHttpConfigs.put(sp, conf);
return conf;
}
}
|
92354cb8bdccf7039fea2a6dd67e548bd9c05401 | 362 | java | Java | src/main/java/eu/erasmuswithoutpaper/registry/validators/ContentType.java | j-be/ewp-registry-service | 9d6f30b2d0ba6eb051f994e4f27ad22867224705 | [
"MIT"
] | 3 | 2017-01-18T12:48:26.000Z | 2018-06-01T11:39:19.000Z | src/main/java/eu/erasmuswithoutpaper/registry/validators/ContentType.java | j-be/ewp-registry-service | 9d6f30b2d0ba6eb051f994e4f27ad22867224705 | [
"MIT"
] | 28 | 2016-12-02T15:38:47.000Z | 2022-03-19T19:58:50.000Z | src/main/java/eu/erasmuswithoutpaper/registry/validators/ContentType.java | j-be/ewp-registry-service | 9d6f30b2d0ba6eb051f994e4f27ad22867224705 | [
"MIT"
] | 4 | 2017-01-18T12:48:28.000Z | 2022-02-22T17:45:40.000Z | 21.294118 | 68 | 0.756906 | 997,243 | package eu.erasmuswithoutpaper.registry.validators;
public enum ContentType {
ApplicationWwwFormUrlencoded("application/x-www-form-urlencoded"),
TextXml("text/xml");
private final String contentType;
ContentType(String contentType) {
this.contentType = contentType;
}
public String getContentTypeString() {
return this.contentType;
}
}
|
92354e38efce74689c9aee6a8e19492dcbbab93b | 296 | java | Java | cloud/smthit-fm/smthit-api/src/main/java/com/smthit/framework/api/handler/UserSecurity.java | yinfuquan/file-upload | b2033451836b7c2c3f58dee474c18536a1beb054 | [
"Apache-2.0"
] | null | null | null | cloud/smthit-fm/smthit-api/src/main/java/com/smthit/framework/api/handler/UserSecurity.java | yinfuquan/file-upload | b2033451836b7c2c3f58dee474c18536a1beb054 | [
"Apache-2.0"
] | null | null | null | cloud/smthit-fm/smthit-api/src/main/java/com/smthit/framework/api/handler/UserSecurity.java | yinfuquan/file-upload | b2033451836b7c2c3f58dee474c18536a1beb054 | [
"Apache-2.0"
] | null | null | null | 11.384615 | 41 | 0.581081 | 997,244 | /**
*
*/
package com.smthit.framework.api.handler;
/**
* @author Bean
*
*/
public interface UserSecurity {
/**
* 判断用户是否登陆
* @param sid
* @return
*
* @since 1.0
*/
public boolean isLogin(String sid);
/**
*
* @param sid
*/
public void initUserContext(String sid);
}
|
92354ea6a1746671e92b7e015a71c118c21b116a | 1,409 | java | Java | core/src/test/java/org/dozer/vo/SuperClass.java | piotrdytkowski/dozer | e32c04bec22ffd4b71ed402e4a5d6558be03c191 | [
"Apache-2.0"
] | null | null | null | core/src/test/java/org/dozer/vo/SuperClass.java | piotrdytkowski/dozer | e32c04bec22ffd4b71ed402e4a5d6558be03c191 | [
"Apache-2.0"
] | null | null | null | core/src/test/java/org/dozer/vo/SuperClass.java | piotrdytkowski/dozer | e32c04bec22ffd4b71ed402e4a5d6558be03c191 | [
"Apache-2.0"
] | null | null | null | 26.584906 | 75 | 0.738822 | 997,245 | /*
* Copyright 2005-2017 Dozer 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 org.dozer.vo;
/**
* @author garsombke.franz
* @author sullins.ben
* @author tierney.matt
*
*/
public class SuperClass extends SuperSuperClass {
private String superAttribute;
private java.util.List superList;
private String superFieldToExclude;
public java.util.List getSuperList() {
return superList;
}
public void setSuperList(java.util.List superList) {
this.superList = superList;
}
public String getSuperAttribute() {
return superAttribute;
}
public void setSuperAttribute(String superAttribute) {
this.superAttribute = superAttribute;
}
public String getSuperFieldToExclude() {
return superFieldToExclude;
}
public void setSuperFieldToExclude(String superFieldToExclude) {
this.superFieldToExclude = superFieldToExclude;
}
}
|
92354fb98e3a135830c40cf309842c325186b1ca | 3,215 | java | Java | app/src/main/java/com/example/yizu/demo/activity/IndexAdapter.java | WinkyZhu/AMAPNaviDemo | 13c475cf1d2dac63633dadbcbf77a068fb2c5bda | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/example/yizu/demo/activity/IndexAdapter.java | WinkyZhu/AMAPNaviDemo | 13c475cf1d2dac63633dadbcbf77a068fb2c5bda | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/example/yizu/demo/activity/IndexAdapter.java | WinkyZhu/AMAPNaviDemo | 13c475cf1d2dac63633dadbcbf77a068fb2c5bda | [
"Apache-2.0"
] | null | null | null | 36.123596 | 111 | 0.651944 | 997,246 | package com.example.yizu.demo.activity;
import android.content.Context;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.example.yizu.R;
import java.util.List;
/**
* Created by shixin on 2017/8/15.
*/
public class IndexAdapter extends BaseAdapter {
private final LayoutInflater inflater;
private List<String> list;
public IndexAdapter(Context context, List<String> list) {
inflater = LayoutInflater.from(context);
this.list = list;
}
/**
* How many items are in the data set represented by this Adapter.
*
* @return Count of items.
*/
@Override
public int getCount() {
return list.size();
}
/**
* Get the data item associated with the specified position in the data set.
*
* @param position Position of the item whose data we want within the adapter's
* data set.
* @return The data at the specified position.
*/
@Override
public Object getItem(int position) {
return list.get(position);
}
/**
* Get the row id associated with the specified position in the list.
*
* @param position The position of the item within the adapter's data set whose row id we want.
* @return The id of the item at the specified position.
*/
@Override
public long getItemId(int position) {
return position;
}
/**
* Get a View that displays the data at the specified position in the data set. You can either
* create a View manually or inflate it from an XML layout file. When the View is inflated, the
* parent View (GridView, ListView...) will apply default layout parameters unless you use
* {@link LayoutInflater#inflate(int, ViewGroup, boolean)}
* to specify a root view and to prevent attachment to the root.
*
* @param position The position of the item within the adapter's data set of the item whose view
* we want.
* @param convertView The old view to reuse, if possible. Note: You should check that this view
* is non-null and of an appropriate type before using. If it is not possible to convert
* this view to display the correct data, this method can create a new view.
* Heterogeneous lists can specify their number of view types, so that this View is
* always of the right type (see {@link #getViewTypeCount()} and
* {@link #getItemViewType(int)}).
* @param parent The parent that this view will eventually be attached to
* @return A View corresponding to the data at the specified position.
*/
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = inflater.inflate(R.layout.activity_simple_list_item, null);
final TextView text = (TextView) view.findViewById(R.id.text1);
String textStr = list.get(position);
text.setText(Html.fromHtml(textStr));
return view;
}
}
|
923550017f4fd460ce7cec8d6906c9d5d6760266 | 435 | java | Java | FacadePatron/src/patron/cliente/Cliente.java | yulagarces/facade | 84c3f8774c6ef9ca04aa61e9dc35be9a7297128b | [
"MIT"
] | null | null | null | FacadePatron/src/patron/cliente/Cliente.java | yulagarces/facade | 84c3f8774c6ef9ca04aa61e9dc35be9a7297128b | [
"MIT"
] | null | null | null | FacadePatron/src/patron/cliente/Cliente.java | yulagarces/facade | 84c3f8774c6ef9ca04aa61e9dc35be9a7297128b | [
"MIT"
] | 1 | 2020-02-22T17:57:41.000Z | 2020-02-22T17:57:41.000Z | 25.588235 | 73 | 0.602299 | 997,247 | package patron.cliente;
import patron.celular.*;
public class Cliente {
public static void main(String[] args) {
System.out.println("--------------- ENCENDER ---------------\n");
Fachada fachada = new Fachada();
DispositivoMovil dispositivo = fachada.encender();
System.out.println();
System.out.println("El dispositivo se está apagando\n");
fachada.apagar(dispositivo);
}
}
|
923550673e50469f4856ba732c8e047af66b6802 | 2,181 | java | Java | modules/platform/nuxeo-platform-publisher/src/main/java/org/nuxeo/ecm/platform/publisher/rules/DefaultValidatorsRule.java | atchertchian/nuxeo | bd28297e11151135a90a933cab6d05ce825ad539 | [
"Apache-2.0"
] | 1 | 2021-02-15T19:07:59.000Z | 2021-02-15T19:07:59.000Z | modules/platform/nuxeo-platform-publisher/src/main/java/org/nuxeo/ecm/platform/publisher/rules/DefaultValidatorsRule.java | atchertchian/nuxeo | bd28297e11151135a90a933cab6d05ce825ad539 | [
"Apache-2.0"
] | 3 | 2021-07-03T21:32:41.000Z | 2022-03-23T13:15:18.000Z | modules/platform/nuxeo-platform-publisher/src/main/java/org/nuxeo/ecm/platform/publisher/rules/DefaultValidatorsRule.java | atchertchian/nuxeo | bd28297e11151135a90a933cab6d05ce825ad539 | [
"Apache-2.0"
] | 1 | 2022-03-17T14:55:30.000Z | 2022-03-17T14:55:30.000Z | 31.608696 | 116 | 0.716644 | 997,248 | /*
* (C) Copyright 2006-2010 Nuxeo SA (http://nuxeo.com/) and others.
*
* 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.
*
* Contributors:
* Julien Anguenot
* Florent Guillaume
*/
package org.nuxeo.ecm.platform.publisher.rules;
import java.util.Arrays;
import java.util.HashSet;
import org.nuxeo.ecm.core.api.DocumentModel;
import org.nuxeo.ecm.core.api.DocumentRef;
import org.nuxeo.ecm.core.api.UnrestrictedSessionRunner;
import org.nuxeo.ecm.core.api.security.ACP;
import org.nuxeo.ecm.core.api.security.SecurityConstants;
/**
* Default NXP validator.
* <p>
* Validators here will be principals having manage everything rights in the sections where the document has been
* published.
*/
public class DefaultValidatorsRule implements ValidatorsRule {
private static final long serialVersionUID = 1L;
@Override
public String[] computesValidatorsFor(DocumentModel doc) {
UnrestrictedACPGetter acpg = new UnrestrictedACPGetter(doc);
acpg.runUnrestricted();
String[] writePermissions = doc.getCoreSession().getPermissionsToCheck(SecurityConstants.WRITE);
String[] reviewers = acpg.acp.listUsernamesForAnyPermission(new HashSet<>(Arrays.asList(writePermissions)));
return reviewers;
}
protected static class UnrestrictedACPGetter extends UnrestrictedSessionRunner {
public final DocumentRef docRef;
public ACP acp;
public UnrestrictedACPGetter(DocumentModel doc) {
super(doc.getCoreSession());
this.docRef = doc.getRef();
}
@Override
public void run() {
acp = session.getACP(docRef);
}
}
}
|
9235516da3220d2a6131b7f0335a3101a54ecad9 | 3,151 | java | Java | bundles/target/src/main/java/org/jscsi/target/util/SerialArithmeticNumber.java | YunLemon/jSCSI | 6169bfe73f0b15de7d6485453555389e782ae888 | [
"BSD-3-Clause"
] | 30 | 2015-09-08T07:07:39.000Z | 2022-03-21T01:22:02.000Z | bundles/target/src/main/java/org/jscsi/target/util/SerialArithmeticNumber.java | YunLemon/jSCSI | 6169bfe73f0b15de7d6485453555389e782ae888 | [
"BSD-3-Clause"
] | 8 | 2015-03-08T19:13:42.000Z | 2020-12-10T10:31:43.000Z | bundles/target/src/main/java/org/jscsi/target/util/SerialArithmeticNumber.java | YunLemon/jSCSI | 6169bfe73f0b15de7d6485453555389e782ae888 | [
"BSD-3-Clause"
] | 24 | 2016-02-17T20:07:06.000Z | 2021-08-18T13:56:12.000Z | 36.218391 | 121 | 0.629641 | 997,249 | package org.jscsi.target.util;
/**
* A class for serial number arithmetics, as defined in <code>[RFC 1982]</code>, with <code>SERIAL_BITS = 32</code>.
* <p>
* Unlike the original algorithm, this implementation is based on unsigned subtraction, resolving the issue of undefined
* comparisons, however introducing one additional oddity - each member of a pair of serial numbers with a wrapped
* distance of <code>2^(SERIAL_BITS - 1)</code> will be considered less than (and greater than) the other one.
*
* @author Andreas Ergenzinger
*/
public final class SerialArithmeticNumber {
/**
* The signed integer representation of the serial arithmetic number.
*/
private int value;
/**
* Creates a new {@link SerialArithmeticNumber} with a starting {@link #value} of zero.
*/
public SerialArithmeticNumber () {
this(0);
}
/**
* Creates a new {@link SerialArithmeticNumber} with the specified starting {@link #value}.
*
* @param value the initial {@link #value}
*/
public SerialArithmeticNumber (final int value) {
this.value = value;
}
/**
* Increments the {@link SerialArithmeticNumber}'s {@link #value} by one.
*/
public void increment () {
++value;
}
/**
* Returns <code>true</code> if the parameter matches the {@link #value} and <code>false</code> if it does not.
*
* @param serialArithmeticNumber the serial arithmetic number to match
* @return <code>true</code> if the parameter matches the {@link #value} and <code>false</code> if it does not
*/
public boolean equals (final int serialArithmeticNumber) {
return value == serialArithmeticNumber;
}
/**
* Returns <code>true</code> if the parameter is less than the {@link #value} in serial number arithmetics and
* <code>false</code> if it is not.
*
* @param serialArithmeticNumber the serial arithmetic number to match
* @return <code>true</code> if the parameter is less than the {@link #value} in serial number arithmetics and
* <code>false</code> if it is not
*/
public boolean lessThan (final int serialArithmeticNumber) {
if (value - serialArithmeticNumber < 0) return true;
return false;
}
/**
* Returns <code>true</code> if the parameter is greater than the {@link #value} in serial number arithmetics and
* <code>false</code> if it is not.
*
* @param serialArithmeticNumber the serial arithmetic number to match
* @return <code>true</code> if the parameter is greater than the {@link #value} in serial number arithmetics and
* <code>false</code> if it is not
*/
public boolean greaterThan (final int serialArithmeticNumber) {
if (serialArithmeticNumber - value < 0) return true;
return false;
}
/**
* Returns the {@link SerialArithmeticNumber}'s {@link #value}.
*
* @return the {@link #value}
*/
public int getValue () {
return value;
}
}
|
9235523c3b6d9df515bdcbcb11d9a0c97352c1c4 | 1,728 | java | Java | clients/service-center-client/src/main/java/org/apache/servicecomb/service/center/client/model/HeartbeatsRequest.java | MC-JY/servicecomb-java-chassis | 6c769733220a2ea7b4f2161ee4e0451d9f289cc8 | [
"Apache-2.0"
] | 1,336 | 2018-11-10T14:52:16.000Z | 2022-03-25T16:17:27.000Z | clients/service-center-client/src/main/java/org/apache/servicecomb/service/center/client/model/HeartbeatsRequest.java | MC-JY/servicecomb-java-chassis | 6c769733220a2ea7b4f2161ee4e0451d9f289cc8 | [
"Apache-2.0"
] | 1,582 | 2018-11-09T09:44:51.000Z | 2022-03-31T08:07:21.000Z | clients/service-center-client/src/main/java/org/apache/servicecomb/service/center/client/model/HeartbeatsRequest.java | MC-JY/servicecomb-java-chassis | 6c769733220a2ea7b4f2161ee4e0451d9f289cc8 | [
"Apache-2.0"
] | 485 | 2018-11-12T01:58:35.000Z | 2022-03-24T02:10:00.000Z | 35.265306 | 76 | 0.725694 | 997,250 | /*
* 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.servicecomb.service.center.client.model;
import java.util.ArrayList;
import java.util.List;
public class HeartbeatsRequest {
private List<InstancesRequest> Instances;
public HeartbeatsRequest(String serviceId, String instanceId) {
List<InstancesRequest> instances = new ArrayList<InstancesRequest>();
instances.add(new InstancesRequest(serviceId, instanceId));
this.Instances = instances;
}
public List<InstancesRequest> getInstances() {
return Instances;
}
public void setInstances(List<InstancesRequest> instances) {
this.Instances = instances;
}
public void addInstances(InstancesRequest instancesRequest) {
if (this.Instances != null) {
this.Instances.add(instancesRequest);
} else {
this.Instances = new ArrayList<InstancesRequest>();
this.Instances.add(instancesRequest);
}
}
}
|
9235526b5211fa4065403f8a304986eed32047c1 | 1,133 | java | Java | swim-java/swim-runtime-java/swim-core-java/swim.streamlet/src/main/java/swim/streamlet/StreamletScope.java | swimos/swim | b403143d89d83e24a6bf842851bab57f1a1bc035 | [
"Apache-2.0"
] | 458 | 2019-02-19T14:04:55.000Z | 2022-03-27T19:52:37.000Z | swim-java/swim-runtime-java/swim-core-java/swim.streamlet/src/main/java/swim/streamlet/StreamletScope.java | swimos/swim | b403143d89d83e24a6bf842851bab57f1a1bc035 | [
"Apache-2.0"
] | 57 | 2019-06-17T11:07:18.000Z | 2021-12-21T12:47:53.000Z | swim-java/swim-runtime-java/swim-core-java/swim.streamlet/src/main/java/swim/streamlet/StreamletScope.java | swimos/swim | b403143d89d83e24a6bf842851bab57f1a1bc035 | [
"Apache-2.0"
] | 34 | 2019-02-21T02:47:34.000Z | 2022-01-17T13:51:51.000Z | 30.621622 | 79 | 0.714916 | 997,251 | // Copyright 2015-2021 Swim Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.streamlet;
public interface StreamletScope<O> {
/**
* Returns the lexically scoped parent of this {@code StreamletScope}.
* Returns {@code null} if this {@code StreamletScope} has no lexical parent.
*/
StreamletScope<? extends O> streamletScope();
/**
* Returns the environment in which this {@code StreamletScope} operates.
*/
StreamletContext streamletContext();
/**
* Returns an {@code Outlet} that updates when the specified {@code key}
* updates.
*/
Outlet<O> outlet(String key);
}
|
9235540e88e11577e788c4a8208c78e8aa88d771 | 6,271 | java | Java | java/jdk/jdk_14/jdk_code_view/src/com/company/source/jdk.internal.vm.compiler/org/graalvm/compiler/hotspot/replacements/profiling/PluginFactory_ProfileSnippets.java | jaylinjiehong/- | 591834e6d90ec8fbfd6c1d2a0913631f9f723a0a | [
"MIT"
] | null | null | null | java/jdk/jdk_14/jdk_code_view/src/com/company/source/jdk.internal.vm.compiler/org/graalvm/compiler/hotspot/replacements/profiling/PluginFactory_ProfileSnippets.java | jaylinjiehong/- | 591834e6d90ec8fbfd6c1d2a0913631f9f723a0a | [
"MIT"
] | null | null | null | java/jdk/jdk_14/jdk_code_view/src/com/company/source/jdk.internal.vm.compiler/org/graalvm/compiler/hotspot/replacements/profiling/PluginFactory_ProfileSnippets.java | jaylinjiehong/- | 591834e6d90ec8fbfd6c1d2a0913631f9f723a0a | [
"MIT"
] | null | null | null | 61.480392 | 333 | 0.780737 | 997,252 | // CheckStyle: stop header check
// CheckStyle: stop line length check
// GENERATED CONTENT - DO NOT EDIT
// GENERATORS: org.graalvm.compiler.replacements.processor.ReplacementsAnnotationProcessor, org.graalvm.compiler.replacements.processor.PluginGenerator
package org.graalvm.compiler.hotspot.replacements.profiling;
import jdk.vm.ci.meta.ResolvedJavaMethod;
import java.lang.annotation.Annotation;
import org.graalvm.compiler.nodes.ValueNode;
import org.graalvm.compiler.nodes.graphbuilderconf.GraphBuilderContext;
import org.graalvm.compiler.nodes.graphbuilderconf.GeneratedInvocationPlugin;
import org.graalvm.compiler.nodes.graphbuilderconf.InvocationPlugin;
import org.graalvm.compiler.nodes.graphbuilderconf.InvocationPlugins;
import org.graalvm.compiler.nodes.graphbuilderconf.NodeIntrinsicPluginFactory;
// class: org.graalvm.compiler.hotspot.replacements.profiling.ProfileSnippets
// method: methodBackedgeEvent(org.graalvm.compiler.core.common.spi.ForeignCallDescriptor,org.graalvm.compiler.hotspot.word.MethodCountersPointer,int,int)
// generated-by: org.graalvm.compiler.replacements.processor.GeneratedNodeIntrinsicPlugin$CustomFactoryPlugin
final class Plugin_ProfileSnippets_methodBackedgeEvent extends GeneratedInvocationPlugin {
@Override
public boolean execute(GraphBuilderContext b, ResolvedJavaMethod targetMethod, InvocationPlugin.Receiver receiver, ValueNode[] args) {
if (!b.isPluginEnabled(this)) {
return false;
}
org.graalvm.compiler.core.common.type.Stamp arg0 = stamp;
org.graalvm.compiler.core.common.spi.ForeignCallsProvider arg1 = injectedForeignCallsProvider;
org.graalvm.compiler.core.common.spi.ForeignCallDescriptor arg2;
if (args[0].isConstant()) {
arg2 = snippetReflection.asObject(org.graalvm.compiler.core.common.spi.ForeignCallDescriptor.class, args[0].asJavaConstant());
} else {
assert b.canDeferPlugin(this) : b.getClass().toString();
return false;
}
ValueNode arg3 = args[1];
ValueNode arg4 = args[2];
ValueNode arg5 = args[3];
return org.graalvm.compiler.nodes.extended.ForeignCallNode.intrinsify(b, targetMethod, arg0, arg1, arg2, arg3, arg4, arg5);
}
@Override
public Class<? extends Annotation> getSource() {
return org.graalvm.compiler.graph.Node.NodeIntrinsic.class;
}
private final org.graalvm.compiler.core.common.spi.ForeignCallsProvider injectedForeignCallsProvider;
private final org.graalvm.compiler.api.replacements.SnippetReflectionProvider snippetReflection;
private final org.graalvm.compiler.core.common.type.Stamp stamp;
Plugin_ProfileSnippets_methodBackedgeEvent(NodeIntrinsicPluginFactory.InjectionProvider injection) {
this.injectedForeignCallsProvider = injection.getInjectedArgument(org.graalvm.compiler.core.common.spi.ForeignCallsProvider.class);
this.snippetReflection = injection.getInjectedArgument(org.graalvm.compiler.api.replacements.SnippetReflectionProvider.class);
this.stamp = injection.getInjectedStamp(void.class, false);
}
}
// class: org.graalvm.compiler.hotspot.replacements.profiling.ProfileSnippets
// method: methodInvocationEvent(org.graalvm.compiler.core.common.spi.ForeignCallDescriptor,org.graalvm.compiler.hotspot.word.MethodCountersPointer)
// generated-by: org.graalvm.compiler.replacements.processor.GeneratedNodeIntrinsicPlugin$CustomFactoryPlugin
final class Plugin_ProfileSnippets_methodInvocationEvent extends GeneratedInvocationPlugin {
@Override
public boolean execute(GraphBuilderContext b, ResolvedJavaMethod targetMethod, InvocationPlugin.Receiver receiver, ValueNode[] args) {
if (!b.isPluginEnabled(this)) {
return false;
}
org.graalvm.compiler.core.common.type.Stamp arg0 = stamp;
org.graalvm.compiler.core.common.spi.ForeignCallsProvider arg1 = injectedForeignCallsProvider;
org.graalvm.compiler.core.common.spi.ForeignCallDescriptor arg2;
if (args[0].isConstant()) {
arg2 = snippetReflection.asObject(org.graalvm.compiler.core.common.spi.ForeignCallDescriptor.class, args[0].asJavaConstant());
} else {
assert b.canDeferPlugin(this) : b.getClass().toString();
return false;
}
ValueNode arg3 = args[1];
return org.graalvm.compiler.nodes.extended.ForeignCallNode.intrinsify(b, targetMethod, arg0, arg1, arg2, arg3);
}
@Override
public Class<? extends Annotation> getSource() {
return org.graalvm.compiler.graph.Node.NodeIntrinsic.class;
}
private final org.graalvm.compiler.core.common.spi.ForeignCallsProvider injectedForeignCallsProvider;
private final org.graalvm.compiler.api.replacements.SnippetReflectionProvider snippetReflection;
private final org.graalvm.compiler.core.common.type.Stamp stamp;
Plugin_ProfileSnippets_methodInvocationEvent(NodeIntrinsicPluginFactory.InjectionProvider injection) {
this.injectedForeignCallsProvider = injection.getInjectedArgument(org.graalvm.compiler.core.common.spi.ForeignCallsProvider.class);
this.snippetReflection = injection.getInjectedArgument(org.graalvm.compiler.api.replacements.SnippetReflectionProvider.class);
this.stamp = injection.getInjectedStamp(void.class, false);
}
}
public class PluginFactory_ProfileSnippets implements NodeIntrinsicPluginFactory {
@Override
public void registerPlugins(InvocationPlugins plugins, NodeIntrinsicPluginFactory.InjectionProvider injection) {
plugins.register(new Plugin_ProfileSnippets_methodBackedgeEvent(injection), org.graalvm.compiler.hotspot.replacements.profiling.ProfileSnippets.class, "methodBackedgeEvent", org.graalvm.compiler.core.common.spi.ForeignCallDescriptor.class, org.graalvm.compiler.hotspot.word.MethodCountersPointer.class, int.class, int.class);
plugins.register(new Plugin_ProfileSnippets_methodInvocationEvent(injection), org.graalvm.compiler.hotspot.replacements.profiling.ProfileSnippets.class, "methodInvocationEvent", org.graalvm.compiler.core.common.spi.ForeignCallDescriptor.class, org.graalvm.compiler.hotspot.word.MethodCountersPointer.class);
}
}
|
923555592715c64aaa4c8146e307d2068741352e | 1,321 | java | Java | DataCore/src/umich/ms/batmass/data/core/api/AbstractUnloadable.java | chhh/batmass | 5810b9cc07a04f97f36d4ebf8d168baef73afd72 | [
"ECL-2.0",
"Apache-2.0"
] | 34 | 2015-06-04T17:16:03.000Z | 2021-09-10T03:39:22.000Z | DataCore/src/umich/ms/batmass/data/core/api/AbstractUnloadable.java | chhh/batmass | 5810b9cc07a04f97f36d4ebf8d168baef73afd72 | [
"ECL-2.0",
"Apache-2.0"
] | 20 | 2016-05-21T18:17:46.000Z | 2021-12-23T10:53:49.000Z | DataCore/src/umich/ms/batmass/data/core/api/AbstractUnloadable.java | chhh/batmass | 5810b9cc07a04f97f36d4ebf8d168baef73afd72 | [
"ECL-2.0",
"Apache-2.0"
] | 9 | 2016-10-30T15:27:49.000Z | 2021-01-12T23:44:54.000Z | 28.717391 | 80 | 0.688872 | 997,253 | /*
* Copyright 2016 Dmitry Avtonomov.
*
* 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 umich.ms.batmass.data.core.api;
/**
* Simple implementation of comparison of resources used by Unloadables by their
* references.
* @author Dmitry Avtonomov
*/
public abstract class AbstractUnloadable<T> implements Unloadable {
protected final T data;
public AbstractUnloadable(T data) {
this.data = data;
}
@Override
public T getResource() {
return data;
}
@Override
public boolean isSameResource(Unloadable other) {
// this was a bad idea, as two different objects might return
// true from .equals method
//return Objects.equals(this, other);
return this.getResource() == other.getResource();
}
}
|
92355566b3d5424cf55efcf913686e76e135771d | 1,486 | java | Java | src/main/java/kaptainwutax/featureutils/structure/generator/structure/BuriedTreasureGenerator.java | jurrejelle/FeatureUtils | 577d0a244d632778ef801b9f46e421d59822eb3f | [
"MIT"
] | null | null | null | src/main/java/kaptainwutax/featureutils/structure/generator/structure/BuriedTreasureGenerator.java | jurrejelle/FeatureUtils | 577d0a244d632778ef801b9f46e421d59822eb3f | [
"MIT"
] | null | null | null | src/main/java/kaptainwutax/featureutils/structure/generator/structure/BuriedTreasureGenerator.java | jurrejelle/FeatureUtils | 577d0a244d632778ef801b9f46e421d59822eb3f | [
"MIT"
] | null | null | null | 24.766667 | 103 | 0.781292 | 997,254 | package kaptainwutax.featureutils.structure.generator.structure;
import kaptainwutax.featureutils.loot.LootTable;
import kaptainwutax.featureutils.loot.MCLootTables;
import kaptainwutax.featureutils.structure.generator.Generator;
import kaptainwutax.mcutils.rand.ChunkRand;
import kaptainwutax.mcutils.util.data.Pair;
import kaptainwutax.mcutils.util.pos.BPos;
import kaptainwutax.mcutils.util.pos.CPos;
import kaptainwutax.mcutils.version.MCVersion;
import kaptainwutax.terrainutils.ChunkGenerator;
import java.util.Collections;
import java.util.List;
public class BuriedTreasureGenerator extends Generator {
private CPos cPos;
public BuriedTreasureGenerator(MCVersion version) {
super(version);
}
@Override
public boolean generate(ChunkGenerator generator, int chunkX, int chunkZ, ChunkRand rand) {
cPos = new CPos(chunkX, chunkZ);
return true;
}
@Override
public List<Pair<ILootType, BPos>> getLootPos() {
return getChestsPos();
}
@Override
public List<Pair<ILootType, BPos>> getChestsPos() {
return Collections.singletonList(new Pair<>(LootType.BURIED_CHEST, cPos.toBlockPos().add(9, 90, 9)));
}
@Override
public ILootType[] getLootTypes() {
return LootType.values();
}
public enum LootType implements ILootType {
BURIED_CHEST(MCLootTables.BURIED_TREASURE_CHEST),
;
public final LootTable lootTable;
LootType(LootTable lootTable) {
this.lootTable = lootTable;
}
public LootTable getLootTable() {
return lootTable;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.