blob_id stringlengths 40 40 | language stringclasses 1
value | repo_name stringlengths 5 132 | path stringlengths 2 382 | src_encoding stringclasses 34
values | length_bytes int64 9 3.8M | score float64 1.5 4.94 | int_score int64 2 5 | detected_licenses listlengths 0 142 | license_type stringclasses 2
values | text stringlengths 9 3.8M | download_success bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|
d58e0b69d4e4382800ffc7de13863096a31fd060 | Java | bulison/test | /ops-domain/src/main/java/cn/fooltech/fool_ops/domain/fiscal/vo/FiscalInitBalanceVo.java | UTF-8 | 13,963 | 2.0625 | 2 | [] | no_license | package cn.fooltech.fool_ops.domain.fiscal.vo;
import com.google.common.collect.Lists;
import javax.validation.constraints.Max;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.List;
/**
* <p>表单传输对象 - 财务-科目初始数据</p>
*
* @author xjh
* @version 1.0
* @date 2015-11-24 10:08:19
*/
public class FiscalInitBalanceVo implements Serializable {
private static final long serialVersionUID = -6597735583510461623L;
/**
* 科目
*/
private String subjectId;
private String subjectName;
private String subjectCode;
private Integer subjectType;
private String subjectCategory;
/**
* 节点标识 1为子节点,0为父节点
*/
private Short subjectFlag;
/**
* 余额方向
*/
private Integer direction;
/**
* 金额
*/
@Max(value = Integer.MAX_VALUE, message = "金额不能大于{value}")
private BigDecimal amount;
/**
* 单位
*/
private String unitId;
private String unitName;
private String unitCode;
/**
* 数量
*/
private BigDecimal quantity;
/**
* 外币金额
*/
private BigDecimal currencyAmount;
/**
* 币别
*/
private String currencyId;
private String currencyName;
private String currencyCode;
/**
* 供应商
*/
private String supplierId;
private String supplierName;
private String supplierCode;
/**
* 销售商
*/
private String customerId;
private String customerName;
private String customerCode;
/**
* 部门
*/
private String departmentId;
private String departmentName;
private String departmentCode;
/**
* 职员
*/
private String memberId;
private String memberName;
private String memberCode;
/**
* 仓库
*/
private String warehouseId;
private String warehouseName;
private String warehouseCode;
/**
* 项目
*/
private String projectId;
private String projectName;
private String projectCode;
/**
* 货品
*/
private String goodsId;
private String goodsName;
private String goodsCode;
/**
* 创建人
*/
private String creatorId;
private String creatorName;
/**
* 账套
*/
private String fiscalAccountId;
private String fiscalAccountName;
private String fiscalAccountCode;
/**
* 描述
*/
private String describe;
private String createTime;
private String updateTime;
private String fid;
/**
* 核算现金流量
*/
private Short cashSign;
/**
* 核算外币
*/
private Short currencySign;
/**
* 核算往来帐
*/
private Short cussentAccountSign;
/**
* 核算供应商
*/
private Short supplierSign;
/**
* 核算销售商
*/
private Short customerSign;
/**
* 核算部门
*/
private Short departmentSign;
/**
* 核算职员
*/
private Short memberSign;
/**
* 核算仓库
*/
private Short warehouseSign;
/**
* 核算项目
*/
private Short projectSign;
/**
* 核算货品
*/
private Short goodsSign;
/**
* 核算数量
*/
private Short quantitySign;
/**
* 是否核算数据
*/
private Short isCheck;
/**
* 是否核算科目
*/
private Short isCheckSubject;
private List<FiscalInitBalanceVo> children = Lists.newArrayList();
public Integer getDirection() {
return this.direction;
}
public void setDirection(Integer direction) {
this.direction = direction;
}
public BigDecimal getAmount() {
return this.amount;
}
public void setAmount(BigDecimal amount) {
this.amount = amount;
}
public BigDecimal getQuantity() {
return this.quantity;
}
public void setQuantity(BigDecimal quantity) {
this.quantity = quantity;
}
public BigDecimal getCurrencyAmount() {
return this.currencyAmount;
}
public void setCurrencyAmount(BigDecimal currencyAmount) {
this.currencyAmount = currencyAmount;
}
public String getDescribe() {
return this.describe;
}
public void setDescribe(String describe) {
this.describe = describe;
}
public String getCreateTime() {
return this.createTime;
}
public void setCreateTime(String createTime) {
this.createTime = createTime;
}
public String getUpdateTime() {
return this.updateTime;
}
public void setUpdateTime(String updateTime) {
this.updateTime = updateTime;
}
public String getFid() {
return this.fid;
}
public void setFid(String fid) {
this.fid = fid;
}
public String getSubjectId() {
return subjectId;
}
public void setSubjectId(String subjectId) {
this.subjectId = subjectId;
}
public String getSubjectName() {
return subjectName;
}
public void setSubjectName(String subjectName) {
this.subjectName = subjectName;
}
public String getSubjectCode() {
return subjectCode;
}
public void setSubjectCode(String subjectCode) {
this.subjectCode = subjectCode;
}
public String getUnitId() {
return unitId;
}
public void setUnitId(String unitId) {
this.unitId = unitId;
}
public String getUnitName() {
return unitName;
}
public void setUnitName(String unitName) {
this.unitName = unitName;
}
public String getUnitCode() {
return unitCode;
}
public void setUnitCode(String unitCode) {
this.unitCode = unitCode;
}
public String getCurrencyId() {
return currencyId;
}
public void setCurrencyId(String currencyId) {
this.currencyId = currencyId;
}
public String getCurrencyName() {
return currencyName;
}
public void setCurrencyName(String currencyName) {
this.currencyName = currencyName;
}
public String getCurrencyCode() {
return currencyCode;
}
public void setCurrencyCode(String currencyCode) {
this.currencyCode = currencyCode;
}
public String getSupplierId() {
return supplierId;
}
public void setSupplierId(String supplierId) {
this.supplierId = supplierId;
}
public String getSupplierName() {
return supplierName;
}
public void setSupplierName(String supplierName) {
this.supplierName = supplierName;
}
public String getSupplierCode() {
return supplierCode;
}
public void setSupplierCode(String supplierCode) {
this.supplierCode = supplierCode;
}
public String getCustomerId() {
return customerId;
}
public void setCustomerId(String customerId) {
this.customerId = customerId;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public String getCustomerCode() {
return customerCode;
}
public void setCustomerCode(String customerCode) {
this.customerCode = customerCode;
}
public String getDepartmentId() {
return departmentId;
}
public void setDepartmentId(String departmentId) {
this.departmentId = departmentId;
}
public String getDepartmentName() {
return departmentName;
}
public void setDepartmentName(String departmentName) {
this.departmentName = departmentName;
}
public String getDepartmentCode() {
return departmentCode;
}
public void setDepartmentCode(String departmentCode) {
this.departmentCode = departmentCode;
}
public String getMemberId() {
return memberId;
}
public void setMemberId(String memberId) {
this.memberId = memberId;
}
public String getMemberName() {
return memberName;
}
public void setMemberName(String memberName) {
this.memberName = memberName;
}
public String getMemberCode() {
return memberCode;
}
public void setMemberCode(String memberCode) {
this.memberCode = memberCode;
}
public String getWarehouseId() {
return warehouseId;
}
public void setWarehouseId(String warehouseId) {
this.warehouseId = warehouseId;
}
public String getWarehouseName() {
return warehouseName;
}
public void setWarehouseName(String warehouseName) {
this.warehouseName = warehouseName;
}
public String getWarehouseCode() {
return warehouseCode;
}
public void setWarehouseCode(String warehouseCode) {
this.warehouseCode = warehouseCode;
}
public String getProjectId() {
return projectId;
}
public void setProjectId(String projectId) {
this.projectId = projectId;
}
public String getProjectName() {
return projectName;
}
public void setProjectName(String projectName) {
this.projectName = projectName;
}
public String getProjectCode() {
return projectCode;
}
public void setProjectCode(String projectCode) {
this.projectCode = projectCode;
}
public String getGoodsId() {
return goodsId;
}
public void setGoodsId(String goodsId) {
this.goodsId = goodsId;
}
public String getGoodsName() {
return goodsName;
}
public void setGoodsName(String goodsName) {
this.goodsName = goodsName;
}
public String getGoodsCode() {
return goodsCode;
}
public void setGoodsCode(String goodsCode) {
this.goodsCode = goodsCode;
}
public String getCreatorId() {
return creatorId;
}
public void setCreatorId(String creatorId) {
this.creatorId = creatorId;
}
public String getCreatorName() {
return creatorName;
}
public void setCreatorName(String creatorName) {
this.creatorName = creatorName;
}
public String getFiscalAccountId() {
return fiscalAccountId;
}
public void setFiscalAccountId(String fiscalAccountId) {
this.fiscalAccountId = fiscalAccountId;
}
public String getFiscalAccountName() {
return fiscalAccountName;
}
public void setFiscalAccountName(String fiscalAccountName) {
this.fiscalAccountName = fiscalAccountName;
}
public String getFiscalAccountCode() {
return fiscalAccountCode;
}
public void setFiscalAccountCode(String fiscalAccountCode) {
this.fiscalAccountCode = fiscalAccountCode;
}
public Integer getSubjectType() {
return subjectType;
}
public void setSubjectType(Integer subjectType) {
this.subjectType = subjectType;
}
public List<FiscalInitBalanceVo> getChildren() {
return children;
}
public void setChildren(List<FiscalInitBalanceVo> children) {
this.children = children;
}
public Short getCashSign() {
return cashSign;
}
public void setCashSign(Short cashSign) {
this.cashSign = cashSign;
}
public Short getCurrencySign() {
return currencySign;
}
public void setCurrencySign(Short currencySign) {
this.currencySign = currencySign;
}
public Short getCussentAccountSign() {
return cussentAccountSign;
}
public void setCussentAccountSign(Short cussentAccountSign) {
this.cussentAccountSign = cussentAccountSign;
}
public Short getSupplierSign() {
return supplierSign;
}
public void setSupplierSign(Short supplierSign) {
this.supplierSign = supplierSign;
}
public Short getCustomerSign() {
return customerSign;
}
public void setCustomerSign(Short customerSign) {
this.customerSign = customerSign;
}
public Short getDepartmentSign() {
return departmentSign;
}
public void setDepartmentSign(Short departmentSign) {
this.departmentSign = departmentSign;
}
public Short getMemberSign() {
return memberSign;
}
public void setMemberSign(Short memberSign) {
this.memberSign = memberSign;
}
public Short getWarehouseSign() {
return warehouseSign;
}
public void setWarehouseSign(Short warehouseSign) {
this.warehouseSign = warehouseSign;
}
public Short getProjectSign() {
return projectSign;
}
public void setProjectSign(Short projectSign) {
this.projectSign = projectSign;
}
public Short getGoodsSign() {
return goodsSign;
}
public void setGoodsSign(Short goodsSign) {
this.goodsSign = goodsSign;
}
public Short getQuantitySign() {
return quantitySign;
}
public void setQuantitySign(Short quantitySign) {
this.quantitySign = quantitySign;
}
public String getSubjectCategory() {
return subjectCategory;
}
public void setSubjectCategory(String subjectCategory) {
this.subjectCategory = subjectCategory;
}
public Short getIsCheck() {
return isCheck;
}
public void setIsCheck(Short isCheck) {
this.isCheck = isCheck;
}
public Short getIsCheckSubject() {
return isCheckSubject;
}
public void setIsCheckSubject(Short isCheckSubject) {
this.isCheckSubject = isCheckSubject;
}
public Short getSubjectFlag() {
return subjectFlag;
}
public void setSubjectFlag(Short subjectFlag) {
this.subjectFlag = subjectFlag;
}
}
| true |
42f19c4a1df9451dad9a9afff4fdfe35a685bbbf | Java | zxwtry/store | /demo/201606/D002_MYSQLCase/src/data160418/MYSQLBasic.java | WINDOWS-1252 | 1,364 | 2.296875 | 2 | [] | no_license | package data160418;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.junit.Test;
public class MYSQLBasic {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/simpleonlinestore?"
+ "user=root&password=&useUnicode=true&characterEncoding=UTF8";
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(url);
Statement statement = conn.createStatement();
String sql = "insert into seller values("
+ "default, \'zxw271@163.com\',"
+ "\'123456\', \'ΰ\', \'ΰ\',"
+ "\'13776103581\',\'http:\\\\' , 1"
+ ")";
statement.execute(sql);
sql = "select * from seller";
ResultSet resultSet = statement.executeQuery(sql);
int count = 0;
while (resultSet.next()) {
System.out.println(count++ +resultSet.getString("name"));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != conn) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
@Test
public void TestTransfer () {
String s = "https://console.qcloud.com/cvm/securitygroup";
System.out.println(s);
}
}
| true |
79450035deb4836b7495d7e25f6331e971f758a7 | Java | denis554/drools | /drools-core/src/main/java/org/drools/core/util/HierarchyEncoderImpl.java | UTF-8 | 15,844 | 2.125 | 2 | [
"Apache-2.0"
] | permissive | /*
* Copyright 2013 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.drools.core.util;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
/**
* Encodes a hierachy using bit masks, according to the algorithm described in
* M.F. van Bommel, P. Wang, Encoding Multiple Inheritance Hierarchies for Lattice Operations
* Data & Knowledge Engineering 50 (2004) 175-194
*
* @param <T>
*/
public class HierarchyEncoderImpl<T> extends CodedHierarchyImpl<T> implements HierarchyEncoder<T>, Externalizable {
private ImmutableBitSet bottom = new ImmutableBitSet();
public BitSet getBottom() {
return bottom;
}
@Override
public void writeExternal( ObjectOutput objectOutput ) throws IOException {
super.writeExternal( objectOutput );
objectOutput.writeObject( bottom );
}
@Override
public void readExternal( ObjectInput objectInput ) throws IOException, ClassNotFoundException {
super.readExternal( objectInput );
bottom = (ImmutableBitSet) objectInput.readObject();
}
public BitSet encode( T member, Collection<T> parents ) {
BitSet existing = getCode( member );
if ( existing != null ) {
return existing;
}
HierNode<T> node = new HierNode<T>( member );
Set<HierNode<T>> parentNodes = floor( parents );
for ( HierNode<T> parentNode : parentNodes ) {
node.addParent( parentNode );
parentNode.addChild( node );
}
encode( node );
add( node );
return node.getBitMask();
}
@Override
protected void add( HierNode<T> node ) {
super.add( node );
bottom.merge( node.getBitMask() );
}
public void clear() {
super.clear();
bottom = new ImmutableBitSet();
}
// Debug only
List<T> ancestorValues( T name ) {
List<T> anx = new ArrayList<T>();
Set<HierNode<T>> nodes = ancestorNodes( getNode(name) );
for ( HierNode<T> node : nodes ) {
anx.add( node.getValue() );
}
return anx;
}
protected void encode( HierNode<T> node ) {
Collection<HierNode<T>> parents = node.getParents();
//System.out.println( "Trying to encode " + node );
switch ( parents.size() ) {
case 0 :
BitSet zero = new BitSet();
if ( hasKey(zero) ) {
HierNode root = getNodeByKey(zero);
if ( root.getValue() != null ) {
fixedRoot = true;
HierNode previousRoot = root;
root = new HierNode( (Object) null );
root.addChild( previousRoot );
previousRoot.addParent( root );
root.setBitMask( zero );
propagate( previousRoot, freeBit( root ) );
add( root );
}
node.addParent( root );
updateMask( node, increment( root.getBitMask(), freeBit( root ) ) );
} else {
updateMask( node, new BitSet() );
}
break;
case 1 :
HierNode<T> parent = parents.iterator().next();
updateMask( node, increment( parent.getBitMask(), freeBit( parent ) ) );
break;
default:
inheritMerged( node );
//System.out.println( " ----------------------------------------------------------------------------------------- " );
resolveConflicts( node );
break;
}
}
protected void resolveConflicts( HierNode<T> x ) {
boolean conflicted = false;
Collection<HierNode<T>> nodes = new ArrayList<HierNode<T>>( getNodes() );
for ( HierNode<T> y : nodes ) {
if ( incomparable( x, y ) ) {
// System.out.println( " \t\tIncomparability between " + x + " and " + y );
int sup = superset( y, x );
if ( sup == 0 ) {
//System.out.println( " \t\tIncomparable, with same mask " + y );
// can't use update mask here, or the already existing node would be removed
x.setBitMask( increment( x.getBitMask(), freeBit( x ) ) );
propagate( y, freeBit( x, y ) );
}
if ( sup > 0 ) {
// System.out.println( " \t\tIncomparable, but as parent " + y );
updateMask( x, increment( x.getBitMask(), freeBit( x ) ) );
}
int sub = superset( x, y );
if ( sub > 0 ) {
// System.out.println( " \t\tIncomparable, but as child " + y );
modify( x, y );
conflicted = true;
}
}
}
if ( conflicted ) {
inheritMerged( x );
resolveConflicts( x );
}
}
protected void modify( HierNode<T> x, HierNode<T> y ) {
//System.out.println( "Modifying on a inc between " + x + " and " + y );
int i = freeBit( x, y );
//System.out.println( "I " + i );
//System.out.println( "Getting parents of " + y + " >> " + y.getParents() );
Collection<HierNode<T>> py = y.getParents();
BitSet t = new BitSet( y.getBitMask().length() );
for ( HierNode<T> parent : py ) {
t.or( parent.getBitMask() );
}
BitSet d = singleBitDiff( t, y.getBitMask() );
int inDex = d.nextSetBit( 0 );
if ( inDex < 0 ) {
propagate( y, i );
} else {
//System.out.println( "D " + toBinaryString( d ) );
Set<HierNode<T>> ancestors = ancestorNodes( x );
Set<HierNode<T>> affectedAncestors = new HashSet<HierNode<T>>();
for ( HierNode<T> anc : ancestors ) {
if ( anc.getBitMask().get( inDex ) ) {
affectedAncestors.add( anc );
}
}
//System.out.println( "Ancestors of " + x + " >> " + ancestors );
//System.out.println( "Affected " + x + " >> " + affectedAncestors );
if ( affectedAncestors.size() == 0 ) {
return;
}
Set<HierNode<T>> gcs = gcs( affectedAncestors );
//System.out.println( "GCS of Affected " + gcs );
Set<HierNode<T>> affectedDescendants = new HashSet<HierNode<T>>();
for ( HierNode<T> g : gcs ) {
affectedDescendants.addAll( descendantNodes( g ) );
}
affectedDescendants.remove( x ); // take x out it's not yet in the set
int dx = firstOne( d );
if ( bottom.get( i ) ) {
i = freeBit( new HierNode<T>( bottom ) );
}
for ( HierNode<T> sub : affectedDescendants ) {
boolean keepsBit = false;
for ( HierNode<T> sup : sub.getParents() ) {
if ( ! keepsBit && ! affectedDescendants.contains( sup ) && sup.getBitMask().get( inDex ) ) {
keepsBit = true;
}
}
BitSet subMask = sub.getBitMask();
if ( ! keepsBit ) {
subMask = decrement( subMask, dx );
}
subMask = increment( subMask, i );
updateMask( sub, subMask );
//System.out.println( "\tModified Desc" + sub );
}
inDex = d.nextSetBit( inDex + 1 );
}
}
protected void updateMask( HierNode<T> node, BitSet mask ) {
boolean in = node.getBitMask() != null && contains ( node );
if ( in ) { remove( node ); }
node.setBitMask( mask );
if ( in ) { add( node ); }
}
protected void inheritMerged( HierNode<T> x ) {
BitSet mask = new BitSet( x.getBitMask() != null ? x.getBitMask().length() : 1 );
for ( HierNode<T> p : x.getParents() ) {
mask.or(p.getBitMask());
}
updateMask(x, mask);
}
protected Set<HierNode<T>> gcs( Set<HierNode<T>> set ) {
Set<HierNode<T>> s = new HashSet<HierNode<T>>();
Iterator<HierNode<T>> iter = set.iterator();
BitSet a = new BitSet( this.size() );
a.or( iter.next().getBitMask() );
while ( iter.hasNext() ) {
a.and( iter.next().getBitMask() );
}
//System.out.println( "Root mask for ceil " + toBinaryString( a ) );
for ( HierNode<T> node : getNodes() ) {
if ( superset( node.getBitMask(), a ) >= 0 ) {
s.add( node );
}
}
Set<HierNode<T>> cl = ceil( s );
return cl;
}
protected Set<HierNode<T>> ceil( Set<HierNode<T>> s ) {
//System.out.println( "Looking for the ceiling of " + s);
if ( s.size() <= 1 ) { return s; }
Set<HierNode<T>> ceil = new HashSet<HierNode<T>>( s );
for ( HierNode<T> x : s ) {
for( HierNode<T> y : s ) {
if ( superset( x, y ) > 0 ) {
ceil.remove( x );
break;
}
}
}
//System.out.println("Found ceiling " + ceil);
return ceil;
}
protected Set<HierNode<T>> floor( Set<HierNode<T>> s ) {
//System.out.println( "Looking for the floor of " + s);
if ( s.size() <= 1 ) { return s; }
Set<HierNode<T>> ceil = new HashSet<HierNode<T>>( s );
for ( HierNode<T> x : s ) {
for( HierNode<T> y : s ) {
if ( superset( y, x ) > 0 ) {
ceil.remove( x );
break;
}
}
}
//System.out.println("Found ceiling " + ceil);
return ceil;
}
private Set<HierNode<T>> floor( Collection<T> parents ) {
Set<HierNode<T>> floor = new HashSet();
Set<HierNode<T>> subs = new HashSet();
for ( T s : parents ) {
HierNode<T> x = getNode( s );
subs.addAll( floor );
boolean minimal = true;
for ( HierNode<T> y : subs ) {
if ( superset( x, y ) > 0 ) {
floor.remove( y );
}
if ( superset( y, x ) > 0 ) {
minimal = false;
break;
}
}
if ( minimal ) {
floor.add( x );
}
subs.clear();
}
return floor;
}
protected void propagate( HierNode<T> y, int bit ) {
Set<HierNode<T>> descendants = descendantNodes(y);
for ( HierNode<T> s : descendants ) {
updateMask( s, increment( s.getBitMask(), bit ) );
}
}
protected int freeBit( HierNode<T> x ) {
return freeBit( x, null );
}
protected int freeBit( HierNode<T> x, HierNode<T> z ) {
//System.out.println( "Looking for a free bit in node " + x );
BitSet forbid = new BitSet( this.size() );
forbid.or( x.getBitMask() );
for ( HierNode<T> y : getNodes() ) {
if ( superset( y, x ) > 0 ) {
//System.out.println( "\t\t Subtype " + y + " contributes " + toBinaryString( y.getBitMask() ) );
forbid.or( y.getBitMask() );
}
if ( z != null ) {
if ( superset( y, z ) > 0 ) {
// System.out.println( "\t\t Subtype " + y + " contributes " + toBinaryString( y.getBitMask() ) );
forbid.or( y.getBitMask() );
}
}
if ( superset( x, y ) < 0 ) {
BitSet diff = singleBitDiff( x.getBitMask(), y.getBitMask() );
//System.out.println( "\t\t Incomparable " + y + " contributes " + toBinaryString( diff ) );
forbid.or(diff);
}
}
//System.out.println( "\t Forbidden mask " + toBinaryString( forbid ) );
return firstZero( forbid );
}
protected boolean incomparable( HierNode<T> c1, HierNode<T> c2 ) {
if ( c1 == c2 ) { return false; }
Set<HierNode<T>> sup1 = ancestorNodes( c1 );
Set<HierNode<T>> sup2 = ancestorNodes( c2 );
return ! ( sup1.contains( c2 ) || sup2.contains( c1 ) );
}
BitSet increment( BitSet id, int i ) {
BitSet x = new BitSet( Math.max( i + 1, id.length() ) );
x.or( id );
x.set(i);
return x;
}
BitSet decrement( BitSet id, int d ) {
BitSet x = new BitSet( id.length() );
x.or( id );
x.clear(d);
return x;
}
BitSet singleBitDiff( BitSet x, BitSet y ) {
BitSet t = new BitSet( x.length() );
t.or( x );
t.flip(0, t.size());
t.and( y );
switch ( t.cardinality() ) {
case 0 : return t;
case 1 : return t;
default: return new BitSet();
}
}
int firstOne( BitSet t ) {
return t.nextSetBit(0);
}
int firstZero( BitSet t ) {
return t.nextClearBit(0);
}
private class ImmutableBitSet extends BitSet {
@Override
public void flip(int bitIndex) { throw new UnsupportedOperationException( "Read Only" ); }
@Override
public void flip(int fromIndex, int toIndex) { throw new UnsupportedOperationException( "Read Only" ); }
@Override
public void set(int bitIndex) { throw new UnsupportedOperationException( "Read Only" ); }
@Override
public void set(int bitIndex, boolean value) { throw new UnsupportedOperationException( "Read Only" ); }
@Override
public void set(int fromIndex, int toIndex) { throw new UnsupportedOperationException( "Read Only" ); }
@Override
public void set(int fromIndex, int toIndex, boolean value) { throw new UnsupportedOperationException( "Read Only" ); }
@Override
public void clear(int bitIndex) { throw new UnsupportedOperationException( "Read Only" ); }
@Override
public void clear(int fromIndex, int toIndex) { throw new UnsupportedOperationException( "Read Only" ); }
@Override
public void clear() { throw new UnsupportedOperationException( "Read Only" ); }
@Override
public void and(BitSet set) { throw new UnsupportedOperationException( "Read Only" ); }
@Override
public void or(BitSet set) { throw new UnsupportedOperationException( "Read Only" ); }
@Override
public void xor(BitSet set) { throw new UnsupportedOperationException( "Read Only" ); }
@Override
public void andNot(BitSet set) { throw new UnsupportedOperationException( "Read Only" ); }
protected void merge( BitSet set ) {
super.or( set );
}
}
}
| true |
bfb0aa5745cc2443f19b6d835331da827d8d88d5 | Java | ig90/Java-GUI | /src/tematy_03_04/Kolo.java | UTF-8 | 833 | 3.59375 | 4 | [] | no_license |
public class Kolo extends Figura implements Obliczenie{
private int promien;
protected String fig = "Koło";
public Kolo(int x, int y, int r){
super(x, y);
promien = r;
}
public String toString(){
return fig + super.toString() +"\n Promień koła: " + promien;
}
public void pozycja(int x, int y) {
String s = "Punkt (" + x + ", " + y + ") znajduje się ";
if (x > this.x + promien || y > this.y + promien) {
s += "na zewnątrz koła";
}
else {
s += "wewnątrz koła";
}
System.out.println(s);
}
public void obliczObwod() {
System.out.println("Obwód Koła: " + 2*Math.PI*promien);
}
public void obliczPole() {
System.out.println("Pole koła: "+ Math.PI*promien*promien);
}
}
| true |
671b701ca77a965ee97bda1538cc9f5488d39a17 | Java | joantune/bennu-renderers | /fenix-web-framework/src/main/java/pt/ist/fenixWebFramework/servlets/listeners/ShutdownContextListener.java | UTF-8 | 2,279 | 2.625 | 3 | [] | no_license | package pt.ist.fenixWebFramework.servlets.listeners;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Enumeration;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import pt.ist.fenixframework.FenixFramework;
@WebListener
public class ShutdownContextListener implements ServletContextListener {
private static final Logger logger = LoggerFactory.getLogger(ShutdownContextListener.class);
private ClassLoader thisClassLoader;
@Override
public void contextInitialized(ServletContextEvent context) {
// Nothing, this listener is only meant to perform some cleanup on
// shutdown
}
@Override
public void contextDestroyed(ServletContextEvent context) {
FenixFramework.shutdown();
this.thisClassLoader = this.getClass().getClassLoader();
interruptThreads();
deregisterJDBCDrivers();
}
private void deregisterJDBCDrivers() {
Enumeration<Driver> drivers = DriverManager.getDrivers();
while (drivers.hasMoreElements()) {
Driver driver = drivers.nextElement();
ClassLoader loader = driver.getClass().getClassLoader();
if (loader != null && loader.equals(this.thisClassLoader)) {
try {
DriverManager.deregisterDriver(driver);
System.out.println("Successfully deregistered JDBC driver " + driver);
} catch (SQLException e) {
logger.warn("Failed to deregister JDBC driver " + driver + ". This may cause a potential leak.", e);
}
}
}
}
private void interruptThreads() {
for (Thread thread : Thread.getAllStackTraces().keySet()) {
if (thread == null || thread.getContextClassLoader() != thisClassLoader || thread == Thread.currentThread()) {
continue;
}
if (thread.isAlive()) {
logger.info("Killing initiated thread: " + thread + " of class " + thread.getClass());
thread.interrupt();
}
}
}
}
| true |
09fe9fad9e62fe0009b329f34d742a7b951f4d7f | Java | Question-bank-management-system/Question-bank-management-system | /src/main/java/com/demo/common/model/base/BaseTempPaper.java | UTF-8 | 786 | 1.773438 | 2 | [] | no_license | package com.demo.common.model.base;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.IBean;
/**
* Generated by JFinal, do not modify this file.
*/
@SuppressWarnings("serial")
public abstract class BaseTempPaper<M extends BaseTempPaper<M>> extends Model<M> implements IBean {
public void setId(java.lang.Integer id) {
set("id", id);
}
public java.lang.Integer getId() {
return getInt("id");
}
public void setTestPaperid(java.lang.Integer testPaperid) {
set("test_paperid", testPaperid);
}
public java.lang.Integer getTestPaperid() {
return getInt("test_paperid");
}
public void setTopicid(java.lang.Integer topicid) {
set("topicid", topicid);
}
public java.lang.Integer getTopicid() {
return getInt("topicid");
}
}
| true |
268e1135ce9065e6735520b0b384a33dc93b34f5 | Java | freddie1363/Java | /20200108/src/co/kim/dto/JobDisplay.java | UTF-8 | 745 | 2.5625 | 3 | [] | no_license | package co.kim.dto;
import java.util.ArrayList;
import java.util.List;
public class JobDisplay {
// JobServiceImpl job; 추후 spring framework 사용시 interface 객체를 호출 사용함
private List<JobDto> list;
public void allSelectDisplay() { //전체리스트를 보여주는 메소드
JobServiceImpl jobs = new JobServiceImpl();
list = new ArrayList<JobDto>();
try {
list = jobs.selectAll();
} catch (Exception e) {
e.printStackTrace();
}
for(JobDto dto : list) {
System.out.print(dto.getJob_id() + " | ");
System.out.print(dto.getJob_title() + " | ");
System.out.print(dto.getMax_salary() + " | ");
System.out.println(dto.getMin_salary() + " | ");
}
}
}
| true |
58b2c0191bf407b960c87c4658469b03d1e3291c | Java | jsonxk/SXDGMS2 | /src/com/xk/Controller/UnitController.java | UTF-8 | 2,433 | 1.921875 | 2 | [] | no_license | package com.xk.Controller;
import java.util.List;
import net.sf.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.fasterxml.jackson.annotation.JsonFormat.Value;
import com.xk.DaoImpl.AllDao;
import com.xk.orm.Unit;
import com.xk.service.AllService;
/**
* @author: xk
* @date:2017年10月31日 下午5:00:48
* @version :
* 单位管理
*/
@Controller
@RequestMapping("Unit")
public class UnitController {
@Autowired
private AllService allService;
//查找单位信息
@RequestMapping(value="/selectAllUnit",method=RequestMethod.POST)
public @ResponseBody JSONArray selectAllUnit(@RequestParam(value="unitname",required=false) String unitname,@RequestParam("unitstatus") String unitstatus,@RequestParam(value="pageSize") String pageSize,@RequestParam(value="offset") String offset){
return allService.getuniBll().selectUnitByname(unitname,unitstatus,Integer.parseInt(pageSize),Integer.parseInt(offset));
}
//添加单位信息
@RequestMapping(value="/InsertUnit",method=RequestMethod.POST)
public @ResponseBody boolean InsertUnit(@RequestBody List<Unit> list){
//return allService.getuniBll().selectUnitByname(unitname,Integer.parseInt(pageSize),Integer.parseInt(offset));
return allService.getuniBll().InsertUnit(list);
}
/*
* 查找单位类别
*/
@RequestMapping(value="/SelectUnitType",method=RequestMethod.POST)
public @ResponseBody JSONArray SelectUnitType(@RequestParam("unittype")String unittype){
return JSONArray.fromObject(allService.getuniBll().SelectUnitType(unittype));
}
/*
* 删除单位
* 并不是真正的删除只是修改状态
*/
@RequestMapping(value="/DelUnit",method=RequestMethod.POST)
public @ResponseBody boolean DelUnit(@RequestParam("unitid")String unitid){
return allService.getuniBll().DelUnit(Integer.parseInt(unitid));
}
/*
* 修改单位信息
*/
@RequestMapping(value="/ModifyUnit",method=RequestMethod.POST)
public @ResponseBody boolean ModifyUnit(@RequestBody List<Unit> unitlist){
return allService.getuniBll().unittypeModify(unitlist);
}
}
| true |
902adc300e26ab8904f50aaf9eb5391331db7ace | Java | linjr12138/RS-company | /rs-web/src/main/java/com/linjr/controller/DeptController.java | UTF-8 | 2,996 | 2.09375 | 2 | [] | no_license | package com.linjr.controller;
import com.linjr.aop.annotation.MyLog;
import com.linjr.entity.db1.SysDept;
import com.linjr.service.DeptService;
import com.linjr.utils.DataResult;
import com.linjr.vo.req.DeptAddReqVO;
import com.linjr.vo.req.DeptUpdateReqVO;
import com.linjr.vo.resp.DeptRespNodeVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.List;
@RestController
@RequestMapping("/api")
@Api(tags = "组织管理-部门管理", description = "部门管理相关接口")
public class DeptController {
@Autowired
private DeptService deptService;
@GetMapping("/depts")
@ApiOperation(value = "查询所有部门数据")
@MyLog(title = "组织管理-部门管理", action = "获取部门数据列表")
@RequiresPermissions("sys:dept:list")
public DataResult<List<SysDept>> getAllDept() {
DataResult result = DataResult.success();
result.setData(deptService.selectAll());
return result;
}
@GetMapping("/dept/tree")
@ApiOperation(value = "查询所有部门树数据")
@MyLog(title = "组织管理-部门管理", action = "获取部门树")
@RequiresPermissions(value = {"sys:user:update", "sys:user:add", "sys:dept:add", "sys:dept:update"}, logical = Logical.OR)
public DataResult<List<DeptRespNodeVO>> getDeptTree(@RequestParam(required = false) String deptId) {
DataResult result = DataResult.success();
result.setData(deptService.deptTreeList(deptId));
return result;
}
@PostMapping("/dept")
@ApiOperation(value = "新增部门数据接口")
@MyLog(title = "组织管理-部门管理", action = "新增部门数据列表")
@RequiresPermissions("sys:dept:add")
public DataResult<SysDept> addDept(@RequestBody @Valid DeptAddReqVO vo) {
DataResult result = DataResult.success();
result.setData(deptService.addDept(vo));
return result;
}
@PutMapping("/dept")
@ApiOperation(value = "跟新部门数据接口")
@MyLog(title = "组织管理-部门管理", action = "跟新部门数据列表")
@RequiresPermissions("sys:dept:update")
public DataResult updateDept(@RequestBody @Valid DeptUpdateReqVO vo) {
deptService.updateDept(vo);
DataResult result = DataResult.success();
return result;
}
@DeleteMapping("/dept/{id}")
@ApiOperation(value = "删除部门接口")
@MyLog(title = "组织管理-部门管理", action = "删除部门数据列表")
@RequiresPermissions("sys:dept:delete")
public DataResult deletedDepts(@PathVariable("id") String id) {
deptService.deletedDept(id);
DataResult result = DataResult.success();
return result;
}
}
| true |
24d60ba2a7fedc47536a7b5745fe916101d9481a | Java | ChristianKonrad/struts2-conversation | /struts2-conversation-plugin/src/main/java/com/google/code/rees/scope/conversation/ConversationUtil.java | UTF-8 | 9,553 | 2.1875 | 2 | [] | no_license | /*******************************************************************************
*
* Struts2-Conversation-Plugin - An Open Source Conversation- and Flow-Scope Solution for Struts2-based Applications
* =================================================================================================================
*
* Copyright (C) 2012 by Rees Byars
* http://code.google.com/p/struts2-conversation/
*
* **********************************************************************************************************************
*
* 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.
*
* **********************************************************************************************************************
*
* $Id: ConversationUtil.java reesbyars $
******************************************************************************/
package com.google.code.rees.scope.conversation;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import com.google.code.rees.scope.conversation.context.ConversationContext;
/**
* Provides static methods intended primarily for use internally and in unit
* testing. Use outside of these contexts should come only as a last resort.
*
* @author rees.byars
*
*/
public class ConversationUtil {
/**
* Given a conversation name, returns the ID of the conversation for the
* currently executing thread.
*
* @param conversationName
* @return
*/
public static String getId(String conversationName) {
if (!conversationName.endsWith(ConversationConstants.CONVERSATION_NAME_SUFFIX)) {
conversationName += ConversationConstants.CONVERSATION_NAME_SUFFIX;
}
ConversationAdapter adapter = ConversationAdapter.getAdapter();
String id = (String) adapter.getRequestContext().get(conversationName);
return id;
}
/**
* Given a conversation field's name, the value of the field is returned
* from a conversation map in the current thread.
*
* @param fieldName
* @return
*/
public static Object getField(String fieldName) {
Object field = null;
ConversationAdapter adapter = ConversationAdapter.getAdapter();
if (adapter != null) {
Map<String, String> requestContext = adapter.getRequestContext();
for (Entry<String, String> entry : requestContext.entrySet()) {
String name = entry.getKey();
String id = entry.getValue();
Map<String, Object> conversationContext = adapter.getConversationContext(name, id);
if (conversationContext != null) {
field = (Object) conversationContext.get(fieldName);
if (field != null)
break;
}
}
}
return field;
}
/**
* Given a conversation field's name and class, the value of the field is
* returned from a conversation map in the current thread.
*
* @param <T>
* @param fieldName
* @param fieldClass
* @return
*/
public static <T> T getField(String fieldName, Class<T> fieldClass) {
return getField(fieldName, fieldClass, getConversations());
}
/**
* Given a conversation field's name and class and an Array of conversation
* names, the value of the field is returned from the first conversation in
* the Array that contains an instance of the field.
*
* @param <T>
* @param fieldName
* @param fieldClass
* @param conversations
* @return
*/
@SuppressWarnings("unchecked")
public static <T> T getField(String fieldName, Class<T> fieldClass,String[] conversations) {
T field = null;
ConversationAdapter adapter = ConversationAdapter.getAdapter();
if (adapter != null) {
for (String conversationName : conversations) {
String id = getId(conversationName);
if (id != null) {
Map<String, Object> conversationContext = adapter.getConversationContext(conversationName, id);
if (conversationContext != null) {
field = (T) conversationContext.get(fieldName);
if (field != null)
break;
}
}
}
}
return field;
}
/**
* Given a conversation field's name and an instance, the value is set for
* the field in all active conversations of which the field is a member.
*
* @param fieldName
* @param fieldValue
*/
public static void setField(String fieldName, Object fieldValue) {
ConversationAdapter adapter = ConversationAdapter.getAdapter();
if (adapter != null) {
Map<String, String> requestContext = adapter.getRequestContext();
for (Entry<String, String> entry : requestContext.entrySet()) {
String name = entry.getKey();
String id = entry.getValue();
Map<String, Object> conversationContext = adapter.getConversationContext(name, id);
if (conversationContext != null) {
conversationContext.put(fieldName, fieldValue);
}
}
}
}
/**
* A convenience method for beginning a conversation programmatically
*
* @param name
* @param maxIdleTimeMillis
* @return
*/
public static ConversationContext begin(String name, long maxIdleTimeMillis) {
return begin(name, ConversationAdapter.getAdapter(), maxIdleTimeMillis);
}
/**
* A convenience method for beginning a conversation programmatically
*
* @param name
* @param adapter
* @param maxIdleTimeMillis
* @return
*/
public static ConversationContext begin(String name, ConversationAdapter adapter, long maxIdleTimeMillis) {
ConversationContext context = adapter.beginConversation(name, maxIdleTimeMillis);
String id = context.getId();
adapter.getViewContext().put(name, id);
adapter.getRequestContext().put(name, id);
return context;
}
/**
* Persist a conversation programmatically
*
* @param name
* @return The {@link ConversationContext} or <code>null</code> if the
* conversation is not active
*/
public static ConversationContext persist(String name) {
return persist(name, ConversationAdapter.getAdapter());
}
/**
* Persist a conversation programmatically
*
* @param name
* @return The {@link ConversationContext} or <code>null</code> if the
* conversation is not active
*/
public static ConversationContext persist(String name, ConversationAdapter adapter) {
String id = adapter.getRequestContext().get(name);
if (id == null) {
return null;
}
adapter.getViewContext().put(name, id);
return adapter.getConversationContext(name, id);
}
/**
* A convenience method for ending a conversation programmatically.
*
* @param name
* @return The {@link ConversationContext} or <code>null</code> if the
* conversation is not active
*/
public static ConversationContext end(String name) {
return end(name, ConversationAdapter.getAdapter());
}
/**
* A convenience method for ending a conversation programmatically.
*
* @param name
* @return The {@link ConversationContext} or <code>null</code> if the
* conversation is not active
*/
public static ConversationContext end(String name, ConversationAdapter adapter) {
String id = adapter.getRequestContext().remove(name);
if (id == null) {
return null;
}
adapter.getViewContext().remove(name);
return adapter.endConversation(name, id);
}
/**
* Given the conversation name, returns that conversation's context for the
* current request.
*
* @param name
* @return The {@link ConversationContext} or <code>null</code> if the
* conversation is not active
*/
public static ConversationContext getContext(String name) {
ConversationAdapter adapter = ConversationAdapter.getAdapter();
String id = adapter.getRequestContext().get(name);
if (id == null) {
return null;
}
return adapter.getConversationContext(name, id);
}
/**
* An array of all active conversations for the current request.
*
* @return
*/
public static String[] getConversations() {
List<String> convoIds = new ArrayList<String>();
ConversationAdapter adapter = ConversationAdapter.getAdapter();
if (adapter != null) {
Map<String, String> requestContext = adapter.getRequestContext();
convoIds.addAll(requestContext.keySet());
}
return convoIds.toArray(new String[convoIds.size()]);
}
/**
* Returns an array of all the conversation IDs on the current request
*
* @return
*/
public static String[] getIds() {
List<String> convoIds = new ArrayList<String>();
ConversationAdapter adapter = ConversationAdapter.getAdapter();
if (adapter != null) {
Map<String, String> requestContext = adapter.getRequestContext();
convoIds.addAll(requestContext.values());
}
return convoIds.toArray(new String[convoIds.size()]);
}
/**
* Used to remove undesired characters from conversation names
*
* @param conversationName
* @return
*/
public static String sanitizeName(String conversationName) {
return conversationName.replaceAll(":", "").replaceAll(",", "");
}
}
| true |
685cfc80078fe93377538f18101f0500d2b17fe1 | Java | pm4j/org.pm4j | /pm4j-core/src/main/java/org/pm4j/core/pm/impl/PmExpressionApiHandler.java | UTF-8 | 2,381 | 2.203125 | 2 | [
"BSD-2-Clause"
] | permissive | package org.pm4j.core.pm.impl;
import org.apache.commons.lang.StringUtils;
import org.pm4j.core.exception.PmRuntimeException;
import org.pm4j.core.pm.PmConversation;
import org.pm4j.core.pm.PmObject;
import org.pm4j.core.pm.api.PmExpressionApi;
import org.pm4j.core.pm.impl.pathresolver.PathResolver;
import org.pm4j.core.pm.impl.pathresolver.PmExpressionPathResolver;
import org.pm4j.navi.NaviHistoryNamedObjectResolver;
public class PmExpressionApiHandler {
/**
* @param expression
* expression for the object to find.
* @return the found object or <code>null</code> when not found.
*/
public Object findByExpression(PmObject pm, String expression) {
if (StringUtils.isBlank(expression)) {
throw new PmRuntimeException(pm, "'null' and blank property keys are not supported.");
}
PathResolver pr = PmExpressionPathResolver.parse(
expression,
PmExpressionApi.getSyntaxVersion(pm));
return pr.getValue(pm);
}
/**
* Finds the object. Tries to resolve not found objects using
* {@link #handleNamedPmObjectNotFound(String)}.
*/
public Object findNamedObject(PmObject pm, String objName) {
Object result = _findNamedObjectImpl(pm, objName);
if (result == null) {
// prevent double initialization:
synchronized(PmUtil.getRootConversation(pm)) {
result = _findNamedObjectImpl(pm, objName);
if (result == null) {
PmConversationImpl s = (PmConversationImpl)pm.getPmConversation();
s.handleNamedPmObjectNotFound(objName);
result = _findNamedObjectImpl(pm, objName);
}
}
}
return result;
}
/**
* Finds an object within the named object scopes of the application.
*
* @param objName Name of the object to find.
* @return The found instance of <code>null</code>.
*/
protected static Object _findNamedObjectImpl(PmObject pm, String objName) {
Object result = null;
PmConversation pmConversation = (PmConversationImpl)pm.getPmConversation();
// TODO olaf: move that out as a very optional configuration part of the conversation or view connector...
result = new NaviHistoryNamedObjectResolver(pmConversation).findObject(objName);
if (result == null) {
result = pmConversation.getPmNamedObject(objName);
}
return result;
}
}
| true |
1b91c8a45531b69f61963b35aa530a8d34a58c7b | Java | mayimchen/meet | /app/src/main/java/com/agmbat/meetyou/edituserinfo/EditGenderActivity.java | UTF-8 | 3,734 | 2.203125 | 2 | [] | no_license | package com.agmbat.meetyou.edituserinfo;
import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.widget.Button;
import android.widget.TextView;
import com.agmbat.android.utils.WindowUtils;
import com.agmbat.imsdk.asmack.XMPPManager;
import com.agmbat.imsdk.imevent.LoginUserUpdateEvent;
import com.agmbat.imsdk.user.LoginUser;
import com.agmbat.meetyou.R;
import com.agmbat.meetyou.helper.GenderHelper;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
/**
* 编辑性别界面
*/
public class EditGenderActivity extends Activity {
/**
* 男性
*/
@BindView(R.id.btn_gender_male)
TextView mGenderMaleView;
/**
* 女性
*/
@BindView(R.id.btn_gender_female)
TextView mGenderFemaleView;
/**
* 保存button
*/
@BindView(R.id.btn_save)
Button mSaveButton;
/**
* 用户选中的性别
*/
private int mGender;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
WindowUtils.setStatusBarColor(this, getResources().getColor(R.color.bg_status_bar));
setContentView(R.layout.activity_edit_gender);
ButterKnife.bind(this);
EventBus.getDefault().register(this);
LoginUser user = XMPPManager.getInstance().getRosterManager().getLoginUser();
updateGenderSelected(user.getGender());
}
@Override
protected void onDestroy() {
super.onDestroy();
EventBus.getDefault().unregister(this);
}
@Override
public void finish() {
super.finish();
overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
}
/**
* 收到vcard更新信息
*
* @param event
*/
@Subscribe(threadMode = ThreadMode.MAIN)
public void onEvent(LoginUserUpdateEvent event) {
LoginUser user = event.getLoginUser();
updateGenderSelected(user.getGender());
}
/**
* 点击返回键
*/
@OnClick(R.id.title_btn_back)
void onClickBack() {
finish();
}
/**
* 点击返回键
*/
@OnClick(R.id.btn_gender_male)
void onClickMale() {
mGender = GenderHelper.GENDER_MALE;
updateGenderSelected(mGender);
}
/**
* 点击返回键
*/
@OnClick(R.id.btn_gender_female)
void onClickFemale() {
mGender = GenderHelper.GENDER_FEMALE;
updateGenderSelected(mGender);
}
/**
* 点击保存
*/
@OnClick(R.id.btn_save)
void onClickSave() {
LoginUser user = XMPPManager.getInstance().getRosterManager().getLoginUser();
if (mGender == user.getGender()) {
// 未修改
finish();
} else {
// TODO 需要添加loading框
// 修改性别
user.setGender(mGender);
XMPPManager.getInstance().getRosterManager().saveLoginUser(user);
finish();
}
}
private void updateGenderSelected(int gender) {
if (gender == GenderHelper.GENDER_MALE) {
mGenderMaleView.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_selected, 0);
mGenderFemaleView.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
} else if (gender == GenderHelper.GENDER_FEMALE) {
mGenderMaleView.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
mGenderFemaleView.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_selected, 0);
}
}
}
| true |
20e275780ea133f73c5a2c56aff99b34fe54dce7 | Java | OshadhaKarunarathne/Mobile-app-development-Mr.claim | /app/src/main/java/com/example/mrclaim/Home.java | UTF-8 | 8,683 | 1.875 | 2 | [] | no_license | package com.example.mrclaim;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;
import com.example.mrclaim.MyAccidents.MyAccidentNavActivity;
import com.example.mrclaim.MyVehicles.MyVehiclesActivity;
import com.example.mrclaim.ShowCase.ShowCaseActivity;
import com.example.mrclaim.SignPack.LoginActivity;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.material.navigation.NavigationView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.squareup.picasso.Picasso;
public class Home extends AppCompatActivity {
//side bar
DrawerLayout drawerLayout;
NavigationView navigationView;
ImageView menuIcon;
LinearLayout contentView;
ActionBarDrawerToggle toggle;
// side bar itesms
TextView naUsername;
ImageView navPro;
//for image slider
private ViewFlipper viewFlipper;
private ImageView imageView;
//to store the image for database
StorageReference storageReference;
DatabaseReference databaseReference ;
FirebaseDatabase firebaseDatabase;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home_activity);
init();
navigationDrawer();
slider();
LoadProfileData();
}
@Override
protected void onStart() {
super.onStart();
LoadProfileData();
}
private void LoadProfileData() {
//loading image from the database
storageReference= FirebaseStorage.getInstance().getReference();
StorageReference profileRef=storageReference.child("Users/"+FirebaseAuth.getInstance().getUid()+"/Profile.jpg");
profileRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
@Override
public void onSuccess(Uri uri) {
Picasso.get().load(uri)
.into(navPro);
}
});
//Log.e("Curent user id",FirebaseAuth.getInstance().getUid());
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference yourRef = rootRef.child("UserData").child(FirebaseAuth.getInstance().getUid());
ValueEventListener eventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
String birthday = dataSnapshot.child("birthday").getValue(String.class);
String firstname = dataSnapshot.child("firstname").getValue(String.class);
String lastname = dataSnapshot.child("lastname").getValue(String.class);
String nic = dataSnapshot.child("nic").getValue(String.class);
naUsername.setText(""+firstname);
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.e("Curent user id",databaseError.getMessage());
}
};
yourRef.addListenerForSingleValueEvent(eventListener);
}
private void slider() {
// image flipper
int images[] = {R.drawable.image1, R.drawable.image2, R.drawable.image3};
for (int image : images) {
flipperImages(image);
}
}
public void flipperImages(int image) {
// image flipper animation controlling
imageView = new ImageView(this);
imageView.setBackgroundResource(image);
viewFlipper.addView(imageView);
viewFlipper.setFlipInterval(5000); // image flipper interval in milliseconds.
viewFlipper.setAutoStart(true);
viewFlipper.setInAnimation(this, android.R.anim.slide_in_left);
viewFlipper.setOutAnimation(this, android.R.anim.slide_out_right);
}
private void init() {
drawerLayout = findViewById(R.id.drawer_layout);
navigationView = (NavigationView) findViewById(R.id.navigation_view);
menuIcon = findViewById(R.id.menu_icon);
contentView = findViewById(R.id.content);
viewFlipper = findViewById(R.id.flipper);
//inlize the side bar
View heder=navigationView.getHeaderView( 0 );
naUsername=heder.findViewById( R.id.navBar_name );
navPro=heder.findViewById( R.id.navPro );
}
private void navigationDrawer() {
navigationView.bringToFront();
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.home:
//startActivity(new Intent(MainActivity.this,MyAccident.class));
Toast.makeText(Home.this, "Returned to home", Toast.LENGTH_SHORT).show();
navigationView.setCheckedItem(R.id.home);
drawerLayout.closeDrawer(GravityCompat.START);
break;
case R.id.log_out:
FirebaseAuth.getInstance().signOut();
Intent intent = new Intent(Home.this, LoginActivity.class);
startActivity(intent);
finish();
break;
case R.id.profile:
Intent intent1 = new Intent(Home.this, ProfileActivity.class);
startActivity(intent1);
finish();
break;
case R.id.aboutUs:
Intent intent2 = new Intent(Home.this, AboutUS.class);
startActivity(intent2);
break;
case R.id.contactus:
Intent intent4 = new Intent(Home.this, ContactUs.class);
startActivity(intent4);
break;
case R.id.acchistory:
Intent intent6 = new Intent(Home.this, ShowCaseActivity.class);
startActivity(intent6);
case R.id.coverage:
Intent intent8 = new Intent(Home.this,MyVehiclesActivity.class);
startActivity(intent8);
}
return false;
}
});
menuIcon.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (drawerLayout.isDrawerVisible(GravityCompat.START))
drawerLayout.closeDrawer(GravityCompat.START);
else drawerLayout.openDrawer(GravityCompat.START);
}
});
// animateNavigationDrawer();
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
if (toggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void EmergencyCall119(View view) {
String number = "119";
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse("tel:" + number));
startActivity(intent);
}
public void Emergency_Vehicle114(View view) {
String number = "1414";
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse("tel:" + number));
startActivity(intent);
}
public void goToMyAccidentScreen(View view) {
startActivity( new Intent(Home.this, MyAccidentNavActivity.class));
}
public void goToMyInsuranceScreen(View view) {
startActivity( new Intent(Home.this, MyVehiclesActivity.class));
}
} | true |
b7dbb0ea8fa85fb83d6579b26e89842e8fd76fb2 | Java | jinseka/java_project0 | /spring09/src/main/java/com/mega/mvc09/MovieController.java | UTF-8 | 726 | 2.28125 | 2 | [] | no_license | package com.mega.mvc09;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class MovieController {
@Autowired
MovieDAO dao; // 스프링이 만들어 놓은 싱클톤 객체의 주소를 넣어준다.
@RequestMapping("movie.do")
public String pay(String title ,int price) {
System.out.println(title);
System.out.println(price);
if (price >=10000) {
return "price"; //views/pass.jsp
} else {
return "redirect:movie.jsp";
}
}
@RequestMapping("price.do")
public void name() {
dao.price();
}
}
| true |
fea2da2e36e33476004b61c8d7eeb4a266e71d26 | Java | Jsorgensen/YahooWeatherAPI | /app/src/main/java/yahooweather/jsorgensen/com/yahooweatherapi/data/Channel.java | UTF-8 | 2,742 | 2.296875 | 2 | [] | no_license | package yahooweather.jsorgensen.com.yahooweatherapi.data;
import org.json.JSONObject;
import java.net.URL;
/**
* Created by MECH on 10/30/2017.
*/
public class Channel implements JSONPopulator {
private Units units;
private Item item;
private ImageWeather image;
private String title;
private String link_string;
private URL link_url;
private String description;
private String language;
private String last_build_date;
private int ttl;
private LocationWeather location;
private Wind wind;
private Atmosphere atmosphere;
private Astronomy astronomy;
private ImageWeather imageWeather;
@Override
public void populate(JSONObject data) {
units = new Units();
units.populate(data.optJSONObject("units"));
title = data.optString("title");
link_string = data.optString("link");
try {
link_url = new URL(link_string);
}catch(Exception e){
}
description = data.optString("description");
language = data.optString("language");
last_build_date = data.optString("lastBuildDate");
ttl = data.optInt("ttl");
location = new LocationWeather();
location.populate(data.optJSONObject("location"));
wind = new Wind();
wind.populate(data.optJSONObject("wind"));
atmosphere = new Atmosphere();
atmosphere.populate(data.optJSONObject("atmosphere"));
astronomy = new Astronomy();
astronomy.populate(data.optJSONObject("astronomy"));
image = new ImageWeather();
image.populate(data.optJSONObject("image"));
item = new Item();
item.populate(data.optJSONObject("item"));
}
public Units getUnits() {
return units;
}
public Item getItem() {
return item;
}
public ImageWeather getImage() {
return image;
}
public String getTitle() {
return title;
}
public String getLink_string() {
return link_string;
}
public URL getLink_url() {
return link_url;
}
public String getDescription() {
return description;
}
public String getLanguage() {
return language;
}
public String getLast_build_date() {
return last_build_date;
}
public int getTtl() {
return ttl;
}
public LocationWeather getLocation() {
return location;
}
public Wind getWind() {
return wind;
}
public Atmosphere getAtmosphere() {
return atmosphere;
}
public Astronomy getAstronomy() {
return astronomy;
}
public ImageWeather getImageWeather() {
return imageWeather;
}
}
| true |
e32f639493c11b8c927465cf0bf8fcde5ad767c1 | Java | 12security/zoom-android-app | /sources/com/onedrive/sdk/generated/IBaseItemRequest.java | UTF-8 | 1,051 | 1.875 | 2 | [] | no_license | package com.onedrive.sdk.generated;
import com.onedrive.sdk.concurrency.ICallback;
import com.onedrive.sdk.core.ClientException;
import com.onedrive.sdk.extensions.Item;
import com.onedrive.sdk.http.IHttpRequest;
public interface IBaseItemRequest extends IHttpRequest {
@Deprecated
Item create(Item item) throws ClientException;
@Deprecated
void create(Item item, ICallback<Item> iCallback);
void delete() throws ClientException;
void delete(ICallback<Void> iCallback);
IBaseItemRequest expand(String str);
Item get() throws ClientException;
void get(ICallback<Item> iCallback);
Item patch(Item item) throws ClientException;
void patch(Item item, ICallback<Item> iCallback);
Item post(Item item) throws ClientException;
void post(Item item, ICallback<Item> iCallback);
IBaseItemRequest select(String str);
IBaseItemRequest top(int i);
@Deprecated
Item update(Item item) throws ClientException;
@Deprecated
void update(Item item, ICallback<Item> iCallback);
}
| true |
a3cf53812b46497f9819c575cefda94df7d22e07 | Java | Mahim1997/AI-Projects | /AI-1 Missionaries Cannibals/Runner.java | UTF-8 | 7,923 | 3.515625 | 4 | [] | no_license | package problem1;
import java.util.*;
public class Runner {
Helper helper;
Stack<Node> stack;
List<Node> closedList;
public int numNodesExpanded = 0;
public int numNodesExplored = 0;
public List<Node> finalPath;
public long timeElapsed;
Queue<Node> queue;
public Runner(String s) {
this.helper = new Helper();
this.closedList = new ArrayList<>();
this.finalPath = new ArrayList<>();
if (s.toUpperCase().contains("BFS".toUpperCase())) {
this.queue = new LinkedList<>();
this.stack = null;
} else if (s.toUpperCase().contains("DFS".toUpperCase())) {
this.stack = new Stack<>();
this.queue = null;
} else {
this.stack = null;
this.queue = null;
this.helper = null;
this.closedList = null;
this.finalPath = null;
}
}
public void runBFS() {
Node startNode = Initializer.getInitialNode();
queue.add(startNode);
long startTime = System.currentTimeMillis();
while (queue.isEmpty() == false) { //While queue is not empty .....
long endTime = System.currentTimeMillis();
this.timeElapsed = (endTime - startTime);
this.numNodesExplored = this.closedList.size() + this.queue.size(); //Number of expanded nodes = number of visited nodes + number of nodes yet to be visited.
if (this.timeElapsed >= Initializer.maxTimeInMs) {
Writer.writeComparison("\n<Time Limit exceeded for BFS>"
+ " NO solution exists for BFS .. Initial number of cannibals = " + Initializer.numberOfCannibalsInitial
+ " , missionaries = " + Initializer.numberOfMissionariesInitial
+ " , max number of possible nodes expanded = " + Initializer.maxNumberOfExpandedNodes
+ ", and max time limit in seconds = " + (Initializer.maxTimeInMs / 1000));
this.numNodesExpanded = helper.printVisitedList(closedList, "BFS");
return;
}
if (this.numNodesExpanded >= Initializer.maxNumberOfExpandedNodes) {
Writer.writeComparison("\n<Limit exceeded for BFS, max num of expanded nodes>"
+ " NO solution exists for BFS .. Initial number of cannibals = " + Initializer.numberOfCannibalsInitial
+ " , missionaries = " + Initializer.numberOfMissionariesInitial
+ " , max number of possible nodes expanded = " + Initializer.maxNumberOfExpandedNodes
+ ", and max time limit in seconds = " + (Initializer.maxTimeInMs / 1000));
this.numNodesExpanded = helper.printVisitedList(closedList, "BFS");
return;
}
Node node = queue.remove();
// this.numNodesExplored++;
if (this.closedList.contains(node) == true) {
continue;
} else {
this.closedList.add(node);
this.numNodesExpanded = this.closedList.size();
this.numNodesExplored = this.closedList.size() + this.queue.size();
}
List<Node> childrenList = this.helper.getChildren(node);
for (Node n : childrenList) {
//Check the child whether it is accepting state, if so then terminate ...
if (n.isFinalNode()) {
this.numNodesExplored = this.closedList.size() + this.queue.size(); //If any other child node was added to queue in between
this.numNodesExpanded = this.helper.printFinalPath(n, "BFS", this.closedList, startTime, endTime);
return;
}
//Check if the child is valid node or not, if valid then insert it into queue
if (n.isValidNode() == true) {
if(queue.contains(n)==false){
queue.add(n);
}
}
}
}
Writer.writeComparison("\n<Queue becomes empty> No solution exists for BFS .. Initial number of cannibals = " + Initializer.numberOfCannibalsInitial
+ " , missionaries = " + Initializer.numberOfMissionariesInitial
+ " , max number of possible nodes expanded = " + Initializer.maxNumberOfExpandedNodes
+ ", and max time limit in sec = " + (Initializer.maxTimeInMs / 1000));
helper.printVisitedList(closedList, "BFS");
}
public void runDFS() {
Node startNode = Initializer.getInitialNode();
stack.push(startNode);
long startTime = System.currentTimeMillis();
while (stack.isEmpty() == false) { //While queue is not empty .....
long endTime = System.currentTimeMillis();
this.timeElapsed = (endTime - startTime);
this.numNodesExplored = this.closedList.size() + this.stack.size();
if (this.timeElapsed >= Initializer.maxTimeInMs) {
Writer.writeComparison("\n<Limit exceeded for DFS, max num of expanded nodes>"
+ " No solution exists for DFS .. Initial number of cannibals = " + Initializer.numberOfCannibalsInitial
+ " , missionaries = " + Initializer.numberOfMissionariesInitial
+ " , and max number of possible nodes expanded = " + Initializer.maxNumberOfExpandedNodes);
this.numNodesExpanded = helper.printVisitedList(closedList, "DFS");
return;
}
if (this.numNodesExpanded >= Initializer.maxNumberOfExpandedNodes) {
Writer.writeComparison("\n<Limit exceeded for DFS, max num of expanded nodes>"
+ " No solution exists for DFS .. Initial number of cannibals = " + Initializer.numberOfCannibalsInitial
+ " , missionaries = " + Initializer.numberOfMissionariesInitial
+ " , max number of possible nodes expanded = " + Initializer.maxNumberOfExpandedNodes
+ " , and max time limit(in sec) = " + (Initializer.maxTimeInMs / 1000));
this.numNodesExpanded = helper.printVisitedList(closedList, "DFS");
return;
}
Node node = stack.pop();
if (closedList.contains(node) == true) {
continue;
} else {
closedList.add(node);
this.numNodesExpanded = closedList.size();
this.numNodesExplored = this.closedList.size() + this.stack.size();
}
List<Node> childrenList = helper.getChildren(node);
for (Node n : childrenList) {
if (n.isFinalNode()) {
this.numNodesExplored = this.closedList.size() + this.stack.size(); //If any other child was added to stack in between
this.numNodesExpanded = helper.printFinalPath(n, "DFS", this.closedList, startTime, endTime);
return;
}
if (n.isValidNode()) {
//this.numNodesExplored++;
if(stack.contains(n) == false){
stack.push(n);
}
}
}
}
Writer.writeComparison("\n<Stack becomes empty> No solution exists for DFS .. Initial number of cannibals = " + Initializer.numberOfCannibalsInitial
+ " , missionaries = " + Initializer.numberOfMissionariesInitial
+ " , max number of possible nodes expanded = " + Initializer.maxNumberOfExpandedNodes
+ " , and max time limit (in sec) = " + (Initializer.maxTimeInMs / 1000));
helper.printVisitedList(closedList, "DFS");
}
}
| true |
332b776ea8adb67b7cbe06dd28d037fa78b11aea | Java | dineshbias/coreJava | /CoreJava/src/main/java/com/test/meth/TestL.java | UTF-8 | 1,357 | 3.40625 | 3 | [] | no_license | /**
*
*/
package com.test.meth;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;
/**
* @author edinjos
*
*/
public class TestL {
public TestL() {
System.out.println("TestL constructor");
}
public static void main(String[] args) {
System.out.println("TestL main");
List<Animal> animals = new ArrayList<Animal>();
animals.add(new Animal("Fish", false, true));
animals.add(new Animal("Kangaroo", true, false));
animals.add(new Animal("Rabbit", true, false));
animals.add(new Animal("Turtle", false, true));
TestL t = new TestL();
t.print(animals, a -> {return a.canHop();} );
t.print(animals, a -> a.canSwim() );
}
private void print(List<Animal> animals, Predicate<Animal> checker) {
for(Animal a : animals){
if(checker.test(a)){
System.out.print(a.getSpecies()+" ");
}
}
System.out.println(" ");
}
}
class Animal {
private String species;
private boolean canHop;
private boolean canSwim;
public Animal(String species, boolean canHop, boolean canSwim) {
this.species = species;
this.canHop = canHop;
this.canSwim = canSwim;
}
public boolean canHop() {
return canHop;
}
public boolean canSwim() {
return canSwim;
}
public String getSpecies() {
return species;
}
}
| true |
6500391997df94b4f4748c492b71dabbc5ff91e7 | Java | santiagomrv/pipelines | /gbif/src/test/java/org/gbif/pipelines/interpretation/columns/BasicTemporalInterpretationTest.java | UTF-8 | 4,807 | 2.5625 | 3 | [
"Apache-2.0"
] | permissive | package org.gbif.pipelines.interpretation.columns;
import org.gbif.dwc.terms.DwcTerm;
import org.gbif.pipelines.interpretation.column.InterpretationFactory;
import org.gbif.pipelines.interpretation.column.InterpretationResult;
import org.junit.Assert;
import org.junit.Test;
public class BasicTemporalInterpretationTest {
@Test
public void testNullOnDay() {
final InterpretationResult<Integer> interpret = InterpretationFactory.interpret(DwcTerm.day, null);
System.out.println(interpret);
Assert.assertEquals(0, interpret.getIssueList().size());
Assert.assertEquals(0, interpret.getLineageList().size());
}
@Test
public void testOutOfRangeDay() {
final InterpretationResult<Integer> interpret = InterpretationFactory.interpret(DwcTerm.day, "-35");
System.out.println(interpret);
Assert.assertEquals(1, interpret.getIssueList().size());
Assert.assertEquals(1, interpret.getLineageList().size());
}
@Test
public void testOutOfRangeDay2() {
final InterpretationResult<Integer> interpret = InterpretationFactory.interpret(DwcTerm.day, "32");
System.out.println(interpret);
Assert.assertEquals(1, interpret.getIssueList().size());
Assert.assertEquals(1, interpret.getLineageList().size());
}
@Test
public void testEmptyDay() {
final InterpretationResult<Integer> interpret = InterpretationFactory.interpret(DwcTerm.day, "");
System.out.println(interpret);
Assert.assertEquals(1, interpret.getIssueList().size());
Assert.assertEquals(1, interpret.getLineageList().size());
}
@Test
public void testValidDay() {
final InterpretationResult<Integer> interpret = InterpretationFactory.interpret(DwcTerm.day, "12");
System.out.println(interpret);
Assert.assertEquals(0, interpret.getIssueList().size());
Assert.assertEquals(0, interpret.getLineageList().size());
}
//********************* MONTH **************************
@Test
public void testNullOnMonth() {
final InterpretationResult<Integer> interpret = InterpretationFactory.interpret(DwcTerm.month, null);
System.out.println(interpret);
Assert.assertEquals(0, interpret.getIssueList().size());
Assert.assertEquals(0, interpret.getLineageList().size());
}
@Test
public void testOutOfRangeMonth() {
final InterpretationResult<Integer> interpret = InterpretationFactory.interpret(DwcTerm.month, "-1");
System.out.println(interpret);
Assert.assertEquals(1, interpret.getIssueList().size());
Assert.assertEquals(1, interpret.getLineageList().size());
}
@Test
public void testOutOfRangeMonth2() {
final InterpretationResult<Integer> interpret = InterpretationFactory.interpret(DwcTerm.month, "22");
System.out.println(interpret);
Assert.assertEquals(1, interpret.getIssueList().size());
Assert.assertEquals(1, interpret.getLineageList().size());
}
@Test
public void testEmptyMonth() {
final InterpretationResult<Integer> interpret = InterpretationFactory.interpret(DwcTerm.month, "");
System.out.println(interpret);
Assert.assertEquals(1, interpret.getIssueList().size());
Assert.assertEquals(1, interpret.getLineageList().size());
}
@Test
public void testValidMonth() {
final InterpretationResult<Integer> interpret = InterpretationFactory.interpret(DwcTerm.month, "12");
System.out.println(interpret);
Assert.assertEquals(0, interpret.getIssueList().size());
Assert.assertEquals(0, interpret.getLineageList().size());
}
/***************************YEAR **************************/
@Test
public void testNullOnYear() {
final InterpretationResult<Integer> interpret = InterpretationFactory.interpret(DwcTerm.year, null);
System.out.println(interpret);
Assert.assertEquals(0, interpret.getIssueList().size());
Assert.assertEquals(0, interpret.getLineageList().size());
}
@Test
public void testOutOfRangeYear() {
final InterpretationResult<Integer> interpret = InterpretationFactory.interpret(DwcTerm.year, "-1");
System.out.println(interpret);
Assert.assertEquals(1, interpret.getIssueList().size());
Assert.assertEquals(1, interpret.getLineageList().size());
}
@Test
public void testEmptyYear() {
final InterpretationResult<Integer> interpret = InterpretationFactory.interpret(DwcTerm.year, "");
System.out.println(interpret);
Assert.assertEquals(1, interpret.getIssueList().size());
Assert.assertEquals(1, interpret.getLineageList().size());
}
@Test
public void testValidYear() {
final InterpretationResult<Integer> interpret = InterpretationFactory.interpret(DwcTerm.year, "2012");
System.out.println(interpret);
Assert.assertEquals(0, interpret.getIssueList().size());
Assert.assertEquals(0, interpret.getLineageList().size());
}
}
| true |
744f523e2cbdb3dab7608f8e030c7c26d5c737af | Java | FRCGirlsOnFire5679/FireCode2020 | /src/main/java/frc/robot/commands/auto/DoNothing.java | UTF-8 | 165 | 1.601563 | 2 | [] | no_license | package frc.robot.commands.auto;
import edu.wpi.first.wpilibj.command.CommandGroup;
public class DoNothing extends CommandGroup {
public DoNothing() {
}
}
| true |
41d438e71f1044ba9ca57ab90700c3a64ce7d712 | Java | SnjLy/source_code_repo | /src/main/java/recommend/scene/api/StrategyHandler.java | UTF-8 | 232 | 1.734375 | 2 | [] | no_license | package recommend.scene.api;
/**
* @author : LiuYong
* Created by Ly on 2019-08-13.
* @Package: recommend.scene.api
* @Description:
* @function:
*/
public interface StrategyHandler {
public void init(Context context);
}
| true |
90def2033b749e113c921115a8b25342ff991482 | Java | Sparklink/barcode-webservice | /src/main/java/org/barcodeapi/server/gen/types/Code128Generator.java | UTF-8 | 1,951 | 2.28125 | 2 | [
"Apache-2.0"
] | permissive | package org.barcodeapi.server.gen.types;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import org.barcodeapi.core.utils.CodeUtils;
import org.barcodeapi.server.gen.CodeGenerator;
import org.barcodeapi.server.gen.CodeType;
import org.json.JSONObject;
import org.krysalis.barcode4j.HumanReadablePlacement;
import org.krysalis.barcode4j.impl.code128.Code128Bean;
import org.krysalis.barcode4j.output.bitmap.BitmapCanvasProvider;
import org.krysalis.barcode4j.tools.UnitConv;
public class Code128Generator extends CodeGenerator {
private Code128Bean generator;
private final int dpi = 150;
public Code128Generator() {
super(CodeType.Code128);
// Setup Code128 generator
generator = new Code128Bean();
// barcode128Bean.setBarHeight(height);
double moduleWidth = UnitConv.in2mm(2.5f / dpi);
generator.setModuleWidth(moduleWidth);
/**
* The minimum width of the Quiet Zone to the left and right of the 128 Bar Code
* is 10x, where x is the minimum width of a module. It is mandatory at the left
* and right side of the barcode.
*
* https://en.wikipedia.org/wiki/Code_128#Quiet_zone
*
*/
generator.doQuietZone(true);
generator.setQuietZone(10 * moduleWidth);
generator.setMsgPosition(HumanReadablePlacement.HRP_BOTTOM);
generator.setHeight(UnitConv.in2mm(1));
}
@Override
public String onValidateRequest(String data) {
return CodeUtils.parseControlChars(data);
}
@Override
public synchronized byte[] onRender(String data, JSONObject options) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
BitmapCanvasProvider canvasProvider = new BitmapCanvasProvider(//
out, "image/x-png", dpi, BufferedImage.TYPE_BYTE_BINARY, false, 0);
generator.generateBarcode(canvasProvider, data);
canvasProvider.getBufferedImage();
canvasProvider.finish();
out.close();
return out.toByteArray();
}
}
| true |
d37252059f4c4b39df9610bab78928096917992f | Java | zhaocj/topjet_java_code | /cust_java_code/cust_java_code/top_admin/src/main/java/com/topjet/manage/domain/model/SysMenuModel.java | UTF-8 | 2,386 | 1.976563 | 2 | [] | no_license | package com.topjet.manage.domain.model;
import java.util.Date;
public class SysMenuModel extends BaseModel {
private Integer id;
private String name;
private String url;
private Integer parentId;
private Integer deleted;
private Date createTime;
private Date updateTime;
private Integer rank;
private String actions;
private Integer createBy;
private Integer updateBy;
private Integer version;
private String cssStyle;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public Integer getParentId() {
return parentId;
}
public void setParentId(Integer parentId) {
this.parentId = parentId;
}
public Integer getDeleted() {
return deleted;
}
public void setDeleted(Integer deleted) {
this.deleted = deleted;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public Integer getRank() {
return rank;
}
public void setRank(Integer rank) {
this.rank = rank;
}
public String getActions() {
return actions;
}
public void setActions(String actions) {
this.actions = actions;
}
public Integer getCreateBy() {
return createBy;
}
public void setCreateBy(Integer createBy) {
this.createBy = createBy;
}
public Integer getUpdateBy() {
return updateBy;
}
public void setUpdateBy(Integer updateBy) {
this.updateBy = updateBy;
}
public Integer getVersion() {
return version;
}
public void setVersion(Integer version) {
this.version = version;
}
public String getCssStyle() {
return cssStyle;
}
public void setCssStyle(String cssStyle) {
this.cssStyle = cssStyle;
}
} | true |
bdfec9e18d04f8843c5c951d6b3fec0623f7d2cc | Java | KeyBridge/lib-faces-common | /src/main/java/ch/keybridge/faces/converter/PhoneNumberConverter.java | UTF-8 | 2,517 | 2.375 | 2 | [] | no_license | /*
* Copyright 2020 Key Bridge. All rights reserved. Use is subject to license
* terms.
*
* This software code is protected by Copyrights and remains the property of
* Key Bridge and its suppliers, if any. Key Bridge reserves all rights in and to
* Copyrights and no license is granted under Copyrights in this Software
* License Agreement.
*
* Key Bridge generally licenses Copyrights for commercialization pursuant to
* the terms of either a Standard Software Source Code License Agreement or a
* Standard Product License Agreement. A copy of either Agreement can be
* obtained upon request by sending an email to info@keybridgewireless.com.
*
* All information contained herein is the property of Key Bridge and its
* suppliers, if any. The intellectual and technical concepts contained herein
* are proprietary.
*/
package ch.keybridge.faces.converter;
import com.google.i18n.phonenumbers.NumberParseException;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.i18n.phonenumbers.Phonenumber;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
/**
* JSF converter to pretty print phone numbers using the Google `libphonenumber`
* library.
*
* @see <a href="https://github.com/google/libphonenumber">libphonenumber</a>
* @author Key Bridge
* @since v0.41.4 created 2020-08-08
*/
public class PhoneNumberConverter implements Converter {
private static final PhoneNumberUtil PHONE_UTIL = PhoneNumberUtil.getInstance();
/**
* {@inheritDoc} capture a pretty print phone number.
*/
@Override
public Object getAsObject(FacesContext context, UIComponent component, String value) {
if (value == null) {
return null;
}
try {
Phonenumber.PhoneNumber phoneNumber = PHONE_UTIL.parse(value, "US");
return String.valueOf(phoneNumber.getNationalNumber());
} catch (NumberParseException numberParseException) {
return value;
}
}
/**
* {@inheritDoc} pretty print a phone number.
*/
@Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
if (value == null) {
return null;
}
String numberSequence = String.valueOf(value);
try {
Phonenumber.PhoneNumber phoneNumber = PHONE_UTIL.parse(numberSequence, "US");
return PHONE_UTIL.format(phoneNumber, PhoneNumberUtil.PhoneNumberFormat.NATIONAL);
} catch (NumberParseException numberParseException) {
return numberSequence;
}
}
}
| true |
b34a082b1e8a1b1c6e56a624c47fe51694853f0a | Java | dman900/RuneScape | /RuneScape/TRiBot/RS2/Random/DuelArena.java | UTF-8 | 1,512 | 2.65625 | 3 | [] | no_license | package scripts;
import java.awt.Color;
import java.awt.Point;
import java.util.Random;
import org.tribot.api.Screen;
import org.tribot.api.Timing;
import org.tribot.api.input.Keyboard;
import org.tribot.api.input.Mouse;
import org.tribot.api.types.colour.ColourPoint;
import org.tribot.api.types.colour.Tolerance;
import org.tribot.script.Script;
import org.tribot.script.ScriptManifest;
@ScriptManifest(authors = { "J J" }, category = "Duel Arena", name = "Duel Arena script")
public class DuelArena extends Script{
public int randomRange(int aFrom, int aTo){
return (aTo - new Random().nextInt((Math.abs(aTo - aFrom) + 1)));
}
private void typeText(){
switch(randomRange(0, 4)){
case 0: Keyboard.typeSend("Boxing 10-17m maxed x2"); break;
case 1: Keyboard.typeSend("Boxing 10-17m when maxed x2"); break;
case 2: Keyboard.typeSend("Box 10-17m maxed x2"); break;
case 3: Keyboard.typeSend("Box 10-17m if maxed x2"); break;
case 4: Keyboard.typeSend("Boxing 10-17m maxed x2 clean me"); break;
}
}
private boolean findChallenge(){
ColourPoint[] duel = Screen.findColours(new Color(126, 50, 0), 10, 494, 350, 501, new Tolerance(5));
if (duel.length > 50){
int i = randomRange(0, duel.length);
Point DP = new Point(duel[i].point);
Mouse.move(DP);
if (Timing.waitUptext("challenge", 1000)){
Mouse.click(1);
return true;
}
}
return false;
}
@Override
public void run() {
while (!findChallenge()){
typeText();
}
}
} | true |
f2ee44c5aa255653209640e14d479c5937fcdaef | Java | eswari27ws/maven | /src/main/java/com/Base_Class/Base_Class.java | UTF-8 | 3,016 | 2.640625 | 3 | [] | no_license | package com.Base_Class;
import java.awt.Robot;
import java.awt.AWTException;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
public class Base_Class {
public static WebDriver driver;
public static WebDriver getBrowser(String type) {
if (type.equalsIgnoreCase("chrome")) {
System.setProperty("webdriver.chrome.driver",
System.getProperty("user.dir") + "//Driver//chromedriver.exe");
driver = new ChromeDriver();
} else if (type.equalsIgnoreCase("firefox")) {
System.setProperty("webdriver.chrome.driver",
System.getProperty("user.dir") + "//Driver//chromedriver.exe");
driver = new FirefoxDriver();
}
driver.manage().window().maximize();
return driver;
}
public static void minimize(int width, int height) {
Dimension d = new Dimension(width, height);
driver.manage().window().setSize(d);
}
public static void getUrl(String url) {
driver.get(url);
}
public static void sendkey(WebElement element, String value) {
element.sendKeys(value);
}
public static void click(WebElement element) {
element.click();
}
public static void sleep(int value) throws InterruptedException {
Thread.sleep(value);
}
public static void javascript() {
JavascriptExecutor j = (JavascriptExecutor) driver;
j.executeScript("window.scroll(0,800)", "");
}
public static void action(WebElement element) {
Actions a = new Actions(driver);
a.contextClick(element).build().perform();
}
public static void action2(WebElement element) {
Actions a = new Actions(driver);
a.click(element).build().perform();
}
public static void action3(WebElement element, String enter) {
Actions a = new Actions(driver);
a.click(element).sendKeys(enter).build().perform();
}
public static void robot() throws AWTException {
Robot r = new Robot();
r.keyPress(KeyEvent.VK_DOWN);
r.keyRelease(KeyEvent.VK_DOWN);
r.keyPress(KeyEvent.VK_ENTER);
r.keyRelease(KeyEvent.VK_ENTER);
}
public static void robot2() throws AWTException {
Robot r = new Robot();
r.keyPress(KeyEvent.VK_TAB);
r.keyRelease(KeyEvent.VK_TAB);
r.keyPress(KeyEvent.VK_ENTER);
r.keyRelease(KeyEvent.VK_ENTER);
}
public static void screenshot(String values) throws IOException {
TakesScreenshot ks = (TakesScreenshot) driver;
File sour = ks.getScreenshotAs(OutputType.FILE);
File Desti = new File("C:\\Users\\DELL\\eclipse-workspace\\Selenium_Basic\\Screenshot\\"+values+".png");
FileUtils.copyFile(sour, Desti);
}
public static void close() {
driver.close();
}
public static void quit() {
driver.quit();
}
}
| true |
32551ffeed7a8df09c386b4fb8b6228ea9dcda6c | Java | littlexiaotimpro/learning-and-practicing | /spring-boot-start/src/main/java/com/practice/start/controller/StockController.java | UTF-8 | 891 | 2.28125 | 2 | [] | no_license | package com.practice.start.controller;
import com.practice.start.service.StockService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.Map;
/**
* 并发条件下库存控制器
*/
@RestController
@RequestMapping(value = "/order")
public class StockController {
@Autowired
private StockService stockService;
@PostMapping(value = "/stock")
public void pay(@RequestBody Map<String, Integer> params) throws Exception {
stockService.handleStock(params);
throw new Exception("测试异常父类");
}
@GetMapping(value = "/consistent")
public void isConsistent(){
stockService.isConsistent();
throw new NullPointerException("空指针异常");
}
@GetMapping(value = "/aspect")
public String aspect(){
return "Aspect";
}
}
| true |
827a636d78303ccb07ad8dbdcf9f39978f1a6667 | Java | PizzioDario/mightyblock-posts | /src/main/java/com/mightyblock/posts/config/authentication/TokenProvider.java | UTF-8 | 1,755 | 2.453125 | 2 | [] | no_license | package com.mightyblock.posts.config.authentication;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
@Slf4j
@Component
public class TokenProvider {
private final String HEADER = "Authorization";
private final String PREFIX = "Bearer ";
@Value("${conf.token.secretkey}")
private String secretKey;
/**
* Function to validate the token of a request
*
* @param request request to evaluate
* @return TokenDto generated token
*/
public Claims validateToken(HttpServletRequest request) {
String token = request.getHeader(HEADER).replace(PREFIX, "");
return Jwts.parser().setSigningKey(secretKey.getBytes()).parseClaimsJws(token).getBody();
}
/**
* This function validates if the request has an Authorization header with the prefix Bearer
*
* @param request request to evaluate
* @return boolean result of the validation
*/
public boolean tokenExists(HttpServletRequest request) {
String authenticationHeader = request.getHeader(HEADER);
return (authenticationHeader != null && authenticationHeader.startsWith(PREFIX));
}
/**
* returns userId from the token
* @param authorizationHeader Authorization header content
* @return userId from the token
*/
public String getUserId(String authorizationHeader) {
String token = authorizationHeader.substring(PREFIX.length());
return (String) Jwts.parser().setSigningKey(secretKey.getBytes()).parseClaimsJws(token).getBody().get("userId");
}
}
| true |
a37a97b0727721caf81b028bf7a3a65e112a62e4 | Java | BorgeJH/sonat-meldingsvarsler | /meldingsvarsler-fasit-forslag/src/test/java/no/sonat/meldingsvarsler/MeldingsSenderTest.java | UTF-8 | 3,939 | 2.03125 | 2 | [] | no_license | package no.sonat.meldingsvarsler;
import no.sonat.meldingsvarsler.infrastructure.abonnent.AbonnentRepositoryReader;
import no.sonat.meldingsvarsler.infrastructure.abonnent.AbonnentRepositoryStatistikk;
import no.sonat.meldingsvarsler.infrastructure.abonnent.AbonnentRepositoryWriter;
import no.sonat.meldingsvarsler.meldinger.MeldingProsessor;
import no.sonat.meldingsvarsler.meldinger.epost.EpostAbonnent;
import no.sonat.meldingsvarsler.meldinger.epost.EpostMelding;
import no.sonat.meldingsvarsler.meldinger.epost.EpostProsessor;
import no.sonat.meldingsvarsler.meldinger.facebook.FacebookAbonnent;
import no.sonat.meldingsvarsler.meldinger.facebook.FacebookMelding;
import no.sonat.meldingsvarsler.meldinger.facebook.FacebookProsessor;
import no.sonat.meldingsvarsler.infrastructure.meldinger.MeldingRepository;
import no.sonat.meldingsvarsler.infrastructure.meldinger.MeldingRepositoryWriter;
import no.sonat.meldingsvarsler.meldinger.sms.SMSAbonnent;
import no.sonat.meldingsvarsler.meldinger.sms.SMSMelding;
import no.sonat.meldingsvarsler.meldinger.sms.SMSProsessor;
import no.sonat.meldingsvarsler.stubs.AbonnentRepositoryStub;
import no.sonat.meldingsvarsler.stubs.MeldingRepositoryStub;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
class MeldingsSenderTest {
final MeldingRepositoryStub meldingRepositoryStub = new MeldingRepositoryStub();
final AbonnentRepositoryStub abonnentRepositoryStub = new AbonnentRepositoryStub();
final MeldingRepository meldingRepositoryReader = meldingRepositoryStub;
final AbonnentRepositoryReader abonnentRepositoryReader = abonnentRepositoryStub;
final AbonnentRepositoryStatistikk abonnentRepositoryStatistikk = abonnentRepositoryStub;
final List<MeldingProsessor> meldingProsessorer = new ArrayList<>();
final MeldingSender meldingSender = new MeldingSender(meldingRepositoryReader, abonnentRepositoryReader, meldingProsessorer);
final AbonnentRepositoryWriter abonnentRepositoryWriter = abonnentRepositoryStub;
final MeldingRepositoryWriter meldingRepositoryWriter = meldingRepositoryStub;
@BeforeEach
void initEach() {
meldingProsessorer.add(new EpostProsessor());
meldingProsessorer.add(new FacebookProsessor());
meldingProsessorer.add(new SMSProsessor());
meldingRepositoryWriter.leggTilMelding(new SMSMelding("Vårens kleskolleksjon har kommet. Løp og kjøp. Førstemann til mølla!!"));
meldingRepositoryWriter.leggTilMelding(new EpostMelding("Løp og kjøp. Førstemann til mølla!!",
"Vårens kleskolleksjon har kommet. "));
meldingRepositoryWriter.leggTilMelding(new FacebookMelding("Vårens kleskolleksjon har kommet. Løp og kjøp. Førstemann til mølla!! Del på Facebook."));
abonnentRepositoryWriter.leggTilAbonnent(new SMSAbonnent("Per Hansen", "909 65 253"));
abonnentRepositoryWriter.leggTilAbonnent(new SMSAbonnent("Mohammed Normann", "77881111"));
abonnentRepositoryWriter.leggTilAbonnent(new SMSAbonnent("Per Abdullah", "77881111"));
abonnentRepositoryWriter.leggTilAbonnent(new SMSAbonnent("Knut Pettersen", "77665551"));
abonnentRepositoryWriter.leggTilAbonnent(new EpostAbonnent("Per Hansen", "per@epost.no"));
abonnentRepositoryWriter.leggTilAbonnent(new EpostAbonnent("Kari Normann", "kari.normann@epost.no"));
abonnentRepositoryWriter.leggTilAbonnent(new FacebookAbonnent("Per Knutsen", "per.knutsen@epost.no"));
}
@Test
public void sendMeldinger() {
meldingSender.sendMeldinger();
}
@Test
public void visStatistikk(){
abonnentRepositoryReader.hentAbonnenter().stream()
.map(abonnent -> abonnent.getClass())
.distinct()
.forEach(aClass ->
System.out.println(aClass.getSimpleName() + ":" + abonnentRepositoryStatistikk.antallAbonnererPaa(aClass)
));
}
} | true |
7716034d8bbe95677e1aef9def4ba56a85b41051 | Java | SaeefMinhaz/ScrollableTabViewWithViewpager | /app/src/main/java/com/example/user/scrollabletabview/model/masterCategoryModel/masterCategory/Child.java | UTF-8 | 1,551 | 2.28125 | 2 | [] | no_license | package com.example.user.scrollabletabview.model.masterCategoryModel.masterCategory;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
/**
* Created by SHOVON on 2/5/2018.
*/
public class Child {
@SerializedName("id")
@Expose
private Integer id;
@SerializedName("name")
@Expose
private String name;
@SerializedName("thumb")
@Expose
private String thumb;
@SerializedName("banner")
@Expose
private String banner;
@SerializedName("parent_id")
@Expose
private String parent_id;
@SerializedName("starting_price")
@Expose
private String starting_price;
public String getParent_id() {
return parent_id;
}
public void setParent_id(String parent_id) {
this.parent_id = parent_id;
}
public String getStarting_price() {
return starting_price;
}
public void setStarting_price(String starting_price) {
this.starting_price = starting_price;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getThumb() {
return thumb;
}
public void setThumb(String thumb) {
this.thumb = thumb;
}
public String getBanner() {
return banner;
}
public void setBanner(String banner) {
this.banner = banner;
}
}
| true |
8c2c4cfa005c141b0f088ea657756fb463c60cef | Java | dandyxu/JavaTraining | /Jsd1309/src/com/dandy/day03/Ex1.java | GB18030 | 325 | 2.421875 | 2 | [] | no_license | package com.dandy.day03;
public class Ex1 {
//ĵҪeclipseеĿݼcopy lineΪctrl+alt+pagedown
//syso+alt+/Զȫ
//ctrl+shift+fΪformat
public static void main(String[] args) {
int i=0;
while (i < 10) {
i += 1;
System.out.print(i);
}
}
}
| true |
d54354593c6070a3ddc37d23ee8086c869d2f3e8 | Java | duskbat/picture_manager | /pm_service/src/main/java/com/pm/service/PictureUserService.java | UTF-8 | 912 | 1.625 | 2 | [] | no_license | package com.pm.service;
import com.pm.entity.PictureUser;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* Created by Dell on 2017/8/24.
*/
public interface PictureUserService {
//插入更新收藏位
int insertMark(List<PictureUser> pictureUserList);
//用户全部图片查询
List<PictureUser> selectPicUser();
//批量更新购物车
int updateShop(List<PictureUser> pictureUserList);
//批量更新多图比较
int updateCompare(List<PictureUser> pictureUserList);
PictureUser selectPicUserById(Long id);
int DeleteMarkBatch(List<PictureUser> fileUpList);
List<PictureUser> selectClientMark(Long userid);
List<PictureUser> selectClientShop(@Param("userid") Long userid, @Param("shopid") Long shopid);
List<PictureUser> selectClientCompare(@Param("userid") Long userid, @Param("compareid") Long compareid);
}
| true |
745a815fd89bda90ff12fead8eea2aa9c4af392b | Java | Jaddori/Arbitrage | /app/src/main/java/com/spacecat/arbitrage/Vec2.java | UTF-8 | 1,160 | 3.34375 | 3 | [] | no_license | package com.spacecat.arbitrage;
/**
* Created by Nix on 2018-03-06.
*/
public class Vec2
{
final float FLOAT_ERR = 0.0001f;
public float x;
public float y;
public Vec2()
{
x = y = 0.0f;
}
public Vec2( float value )
{
x = y = value;
}
public Vec2( float x, float y )
{
this.x = x;
this.y = y;
}
public Vec2( Vec2 ref )
{
x = ref.x;
y = ref.y;
}
public boolean equals( Vec2 ref )
{
return ( Math.abs( x - ref.x ) < FLOAT_ERR && Math.abs( y - ref.y ) < FLOAT_ERR );
}
public void add( float value )
{
x += value;
y += value;
}
public void add( Vec2 ref )
{
x += ref.x;
y += ref.y;
}
public void sub( float value )
{
x -= value;
y -= value;
}
public void sub( Vec2 ref )
{
x -= ref.x;
y -= ref.y;
}
public void mul( float value )
{
x *= value;
y *= value;
}
public void mul( Vec2 ref )
{
x *= ref.x;
y *= ref.y;
}
public void div( float value )
{
x /= value;
y /= value;
}
public void div( Vec2 ref )
{
x /= ref.x;
y /= ref.y;
}
public void normalize()
{
div( magnitude() );
}
public float magnitude()
{
return (float)Math.sqrt( x*x + y*y );
}
}
| true |
e92b51f2dbcd275c77debf7999b32cd5d876b3b8 | Java | UnleveledGaming/PPerms | /src/com/github/gizmo0320/PowerfulPermsAPI/Response.java | UTF-8 | 419 | 2.578125 | 3 | [
"MIT"
] | permissive | package com.github.gizmo0320.PowerfulPermsAPI;
public class Response {
protected boolean success = false;
protected String response = "";
public Response(boolean success, String response) {
this.success = success;
this.response = response;
}
public String getResponse() {
return this.response;
}
public boolean succeeded() {
return this.success;
}
}
| true |
6a66a3e523ba2ab3b68f129c47e7a667c3294b0a | Java | usernamegaofeng/distributed-oauth-sso | /distributed-oauth2-server/src/main/java/pers/micro/oauth/service/CustomUserDetailsService.java | UTF-8 | 553 | 1.859375 | 2 | [] | no_license | package pers.micro.oauth.service;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
/**
* @author Gaofeng
* @date 2021/3/24 下午5:29
* @description: 继承原来的UserDetailsService新增自定义方法
*/
public interface CustomUserDetailsService extends UserDetailsService {
UserDetails loadUserByUsername(String var1, String var2) throws UsernameNotFoundException;
}
| true |
143719466387ffa2538d0d40f479933f3001c657 | Java | Nagisa12321/LL1 | /src/main/java/com/jtchen/tools/strTool.java | UTF-8 | 3,571 | 3.265625 | 3 | [] | no_license | package com.jtchen.tools;
import com.jtchen.structure.MidProduct;
import java.util.*;
/**
* @author jtchen
* @version 1.0
* @date 2021/1/4 0:17
*/
@SuppressWarnings({"unchecked", "rawtypes"})
public class strTool {
/**
* @param str 每一行输入的式子 e.g. S' -> a b c S' | @ --> S' -> {{a, b, c, S'}, { @}}
* (空格隔开)
* @return 转换之后的Map映射
*/
public static void ConversionMap(String str, HashMap<String, List<List<String>>> map) {
List<List<String>> list = turnList(str);
turnMap(list, map);
}
/**
* 把字符串转换为list, 并检查格式有无错误
*
* @param str e.g. S' -> a b c S' | @ --> {{S'}, {a, b, c, S'}, { @}}
* @return 把string转为List的格式组合
*/
private static List<List<String>> turnList(String str) {
String[] tmp = str.split(" ");
// 第一个为‘|’, 第二个不为‘->’, 总个数小于3
if (tmp.length < 3 || !tmp[1].equals("->") || tmp[0].equals("|"))
throw new IllegalArgumentException("输入式子错误");
// 有连续两个'|' 或者'-->' 的位置不对
for (int i = 0; i < tmp.length - 1; i++) {
if (tmp[i].equals("|") && tmp[i + 1].equals("|"))
throw new IllegalArgumentException("输入式子错误");
if (tmp[i].equals("->") && i != 1)
throw new IllegalArgumentException("输入式子错误");
}
// '|' 在最后
if (tmp[tmp.length - 1].equals("|")) throw new IllegalArgumentException("输入式子错误");
// 循环填入list中
List<List<String>> list = new ArrayList<>();
List<String> tmp1 = new ArrayList<>();
for (String s : tmp) {
if (s.equals("->") || s.equals("|")) {
list.add(new ArrayList<>(tmp1));
tmp1.clear();
} else tmp1.add(s);
}
list.add(new ArrayList<>(tmp1));
return list;
}
/**
* 把格式组合转换为最终map形式
*
* @param list e.g. {{S'}, {a, b, c, S'}, { @}}
* -> S' -> {{a, b, c, S'}, { @}}
*/
public static void turnMap
(List<List<String>> list, Map<String, List<List<String>>> map) {
String s = list.get(0).get(0);
list.remove(0);
// 如果map中存在s, 则在原有基础上添加
if (map.containsKey(s)) map.get(s).addAll(list);
else map.put(s, list);
}
/**
* 给出一个式子, 提取其非终结符(左侧)
*
* @param s e.g. "S -> Q c | c"
* @return e.g. "S"
*/
public static String FirstNonterminal(String s) {
String[] strings = s.split(" ");
return strings[0];
}
/* 去重复 */
public static void removeDuplicate(List list) {
HashSet h = new HashSet(list);
list.clear();
list.addAll(h);
}
public static String toProduction(String key, List<String> list) {
StringBuilder builder = new StringBuilder();
builder.append(key).append(" -> ");
for (int i = 0; i < list.size(); i++) {
if (i < list.size() - 1)
builder.append(list.get(i)).append(" ");
else builder.append(list.get(i));
}
return builder.toString();
}
public static boolean contains(List<MidProduct> products, String key) {
for (var product : products) {
if (product.getKey().equals(key)) return true;
}
return false;
}
}
| true |
337673c36597c7d1c943cb31b6385da8d451f9ba | Java | dennislee928/meme-generrator | /main.java | UTF-8 | 3,466 | 2.84375 | 3 | [] | no_license | import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.ImageIcon;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.imageio.ImageIO;
public class main extends JFrame {
JFrame mainFrame = new JFrame();
JPanel imagePanel = new JPanel();
JPanel buttonPanel = new JPanel();
JLabel databaseLabel = new JLabel();
JLabel searchLabel = new JLabel();
JButton databaseButton = new JButton("從資料庫選擇圖片");
JButton searchButton = new JButton("讓問號貓貓幫你自己決定素材!");
users u1;
public main() throws MalformedURLException, IOException {
setTitle("Select Your Material!");
CreateLabel();
CreateOther();
CreateRandom();
mainFrame.setLayout(new BorderLayout());
mainFrame.add(imagePanel, BorderLayout.CENTER);
mainFrame.add(buttonPanel, BorderLayout.SOUTH);
mainFrame.setSize(410, 250);
mainFrame.setVisible(true);
}
public void setUsers(users u) {
this.u1 = u;
}
//-----------------------------------------------------------------
public void CreateLabel() throws MalformedURLException, IOException {
// ------------------------------
ImageIcon imageIcon2 = new ImageIcon(ImageIO.read(
new URL("https://stickershop.line-scdn.net/stickershop/v1/product/10060443/LINEStorePC/main.png")));
Image image2 = imageIcon2.getImage();
Image newimg2 = image2.getScaledInstance(200, 200, java.awt.Image.SCALE_SMOOTH);
imageIcon2 = new ImageIcon(newimg2);
databaseLabel = new JLabel(imageIcon2);
// -----------------------------------------
ImageIcon imageIcon4 = new ImageIcon(
ImageIO.read(new File("C:\\Users\\User\\108_2\\FinalProject\\img\\Cry_Cat.png")));
Image image4 = imageIcon4.getImage();
Image newimg4 = image4.getScaledInstance(200, 200, java.awt.Image.SCALE_SMOOTH);
imageIcon4 = new ImageIcon(newimg4);
searchLabel = new JLabel(imageIcon4);
// -----------------------------------------
imagePanel.setLayout(new GridLayout(1, 2));
imagePanel.add(searchLabel);
imagePanel.add(databaseLabel);
buttonPanel.setLayout(new GridLayout(1,2));
}
// ----------------------------------------------------------
public void CreateOther() {
class Other implements ActionListener {
public void actionPerformed(ActionEvent e) {
try {
MemeFrame f = new MemeFrame();
f.setUsers(u1);}
catch(IOException e1) {
e1.printStackTrace();
}
}
}
databaseButton.addActionListener(new Other());
buttonPanel.add(databaseButton);
}
// ----------------------------------------------------------
public void CreateRandom() {
class Random implements ActionListener {
public void actionPerformed(ActionEvent e) {
try {
Frame4 f = new Frame4();
f.setUsers(u1);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
searchButton.addActionListener(new Random());
buttonPanel.add(searchButton);
}
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
main m1 = new main();
// m1.create();
}
}
| true |
0bdc4cfa77ec57db785aae0107190e389fa71745 | Java | akshayvarun/GDH | /src/main/java/com/gdh/main/Constants.java | UTF-8 | 1,308 | 1.726563 | 2 | [
"MIT"
] | permissive | package com.gdh.main;
public final class Constants {
public static final String GROUPID = "groupId";
public static final String MEMBERS = "members";
public static final String GENERATOR = "generator";
public static final String PRIME = "prime";
public static final String RETRIES = "retries";
public static final String IP = "ip";
public static final String PORT = "port";
public static final String ROUND = "round";
public static final String PARTIAL_KEY = "partial_key";
public static final String GROUPS = "groups";
public static final String ACK = "ack";
public static final String EXCEPTIONTIMEOUTEXCEEDED = "Timeout exceeded ";
public static final String EXCEPTIONRETRIESEXCEEDED = "Retries exceeded ";
public static final int BUFFER_SIZE = 2500;
public static final int CIPHER_SIZE = 1024;
public static final int EXCHANGE_TIMEOUT = 60000;
public static final int SEND_RETRY_TIMEOUT = 2000;
public static final int DEFAULT_RETRY = 5;
public static final int BITS_256 = 32;
public static final String NEGO_CALL = " called negotiation for group ";
public static final String LOG_OUT = "Outgoing";
public static final String LOG_IN = "Incoming";
private Constants() {
}
}
| true |
b593a4c6e5c17cc1965127bcb9282bda05c7ab14 | Java | petergphillips/spectrum | /src/test/java/given/a/spec/with/exception/in/constructor/Fixture.java | UTF-8 | 560 | 2.734375 | 3 | [
"MIT"
] | permissive | package given.a.spec.with.exception.in.constructor;
class Fixture {
public static Class<?> getSpecThatThrowsAnExceptionInConstructor() {
class Spec {
{
if (true) {
throw new SomeException("kaboom");
}
}
}
return Spec.class;
}
public static class SomeException extends RuntimeException {
private static final long serialVersionUID = 1L;
public SomeException(final String message) {
super(message);
}
}
}
| true |
05b36ee6d462e5d1ffd685d83ee701969091d53c | Java | ChoHwaJin/JAVA_STUDY | /src/icehs/science/chapter05/GradeIfElseTest1.java | UHC | 635 | 3.078125 | 3 | [] | no_license | package icehs.science.chapter05;
public class GradeIfElseTest1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int dongScore = 92;
if (dongScore >= 90 && dongScore <= 100) {
System.out.println("A Դϴ.");
} else if (dongScore >= 80 && dongScore < 90) {
System.out.println("B Դϴ.");
} else if (dongScore >= 70 && dongScore < 80) {
System.out.println("C Դϴ.");
} else if (dongScore >= 60 && dongScore <70) {
System.out.println("D Դϴ.");
} else {
System.out.println("F Դϴ.");
}
}
}
| true |
85af1bf188d5b386d5b235d7ef0db2c4d230d7f1 | Java | jdcloud-api/jdcloud-sdk-java | /vpc/src/main/java/com/jdcloud/sdk/service/vpc/model/AssignNetworkInterfaceSecondaryIps.java | UTF-8 | 5,780 | 1.75 | 2 | [
"Apache-2.0"
] | permissive | /*
* Copyright 2018 JDCLOUD.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.
*
*
*
*
*
* Contact:
*
* NOTE: This class is auto generated by the jdcloud code generator program.
*/
package com.jdcloud.sdk.service.vpc.model;
import java.util.List;
import java.util.ArrayList;
import com.jdcloud.sdk.annotation.Required;
/**
* assignNetworkInterfaceSecondaryIps
*/
public class AssignNetworkInterfaceSecondaryIps implements java.io.Serializable {
private static final long serialVersionUID = 1L;
/**
* 网卡ID
* Required:true
*/
@Required
private String networkInterfaceId;
/**
* secondary ip被其他接口占用时,是否抢占。false:非抢占重分配,true:抢占重分配,默认抢占重分配。默认值:true
*/
private Boolean force;
/**
* 指定分配的secondaryIp地址
*/
private List<String> secondaryIps;
/**
* 指定自动分配的secondaryIp个数
*/
private Number secondaryIpCount;
/**
* 指定分配的网段掩码长度, 支持26、27、28,不能与secondaryIpCount或secondaryIps同时指定,不支持抢占重分配
*/
private Integer secondaryIpMaskLen;
/**
* get 网卡ID
*
* @return
*/
public String getNetworkInterfaceId() {
return networkInterfaceId;
}
/**
* set 网卡ID
*
* @param networkInterfaceId
*/
public void setNetworkInterfaceId(String networkInterfaceId) {
this.networkInterfaceId = networkInterfaceId;
}
/**
* get secondary ip被其他接口占用时,是否抢占。false:非抢占重分配,true:抢占重分配,默认抢占重分配。默认值:true
*
* @return
*/
public Boolean getForce() {
return force;
}
/**
* set secondary ip被其他接口占用时,是否抢占。false:非抢占重分配,true:抢占重分配,默认抢占重分配。默认值:true
*
* @param force
*/
public void setForce(Boolean force) {
this.force = force;
}
/**
* get 指定分配的secondaryIp地址
*
* @return
*/
public List<String> getSecondaryIps() {
return secondaryIps;
}
/**
* set 指定分配的secondaryIp地址
*
* @param secondaryIps
*/
public void setSecondaryIps(List<String> secondaryIps) {
this.secondaryIps = secondaryIps;
}
/**
* get 指定自动分配的secondaryIp个数
*
* @return
*/
public Number getSecondaryIpCount() {
return secondaryIpCount;
}
/**
* set 指定自动分配的secondaryIp个数
*
* @param secondaryIpCount
*/
public void setSecondaryIpCount(Number secondaryIpCount) {
this.secondaryIpCount = secondaryIpCount;
}
/**
* get 指定分配的网段掩码长度, 支持26、27、28,不能与secondaryIpCount或secondaryIps同时指定,不支持抢占重分配
*
* @return
*/
public Integer getSecondaryIpMaskLen() {
return secondaryIpMaskLen;
}
/**
* set 指定分配的网段掩码长度, 支持26、27、28,不能与secondaryIpCount或secondaryIps同时指定,不支持抢占重分配
*
* @param secondaryIpMaskLen
*/
public void setSecondaryIpMaskLen(Integer secondaryIpMaskLen) {
this.secondaryIpMaskLen = secondaryIpMaskLen;
}
/**
* set 网卡ID
*
* @param networkInterfaceId
*/
public AssignNetworkInterfaceSecondaryIps networkInterfaceId(String networkInterfaceId) {
this.networkInterfaceId = networkInterfaceId;
return this;
}
/**
* set secondary ip被其他接口占用时,是否抢占。false:非抢占重分配,true:抢占重分配,默认抢占重分配。默认值:true
*
* @param force
*/
public AssignNetworkInterfaceSecondaryIps force(Boolean force) {
this.force = force;
return this;
}
/**
* set 指定分配的secondaryIp地址
*
* @param secondaryIps
*/
public AssignNetworkInterfaceSecondaryIps secondaryIps(List<String> secondaryIps) {
this.secondaryIps = secondaryIps;
return this;
}
/**
* set 指定自动分配的secondaryIp个数
*
* @param secondaryIpCount
*/
public AssignNetworkInterfaceSecondaryIps secondaryIpCount(Number secondaryIpCount) {
this.secondaryIpCount = secondaryIpCount;
return this;
}
/**
* set 指定分配的网段掩码长度, 支持26、27、28,不能与secondaryIpCount或secondaryIps同时指定,不支持抢占重分配
*
* @param secondaryIpMaskLen
*/
public AssignNetworkInterfaceSecondaryIps secondaryIpMaskLen(Integer secondaryIpMaskLen) {
this.secondaryIpMaskLen = secondaryIpMaskLen;
return this;
}
/**
* add item to 指定分配的secondaryIp地址
*
* @param secondaryIp
*/
public void addSecondaryIp(String secondaryIp) {
if (this.secondaryIps == null) {
this.secondaryIps = new ArrayList<>();
}
this.secondaryIps.add(secondaryIp);
}
} | true |
644b43f9cddcc57134da3cdb84e1b25d5ef872ac | Java | NaudhizFehu/finalproject_dev04 | /backend/src/main/java/com/dev4/sunbbang/member/MemberService.java | UTF-8 | 2,567 | 2.34375 | 2 | [] | no_license | package com.dev4.sunbbang.member;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.dev4.sunbbang.model.AuthVO;
import com.dev4.sunbbang.model.MemberVO;
import com.dev4.sunbbang.repository.BakeryRepository;
import com.dev4.sunbbang.repository.MemberRepository;
import com.dev4.sunbbang.util.Define;
@Transactional
@Service
public class MemberService {
@Autowired
MemberRepository memberRepository;
@Autowired
BakeryRepository bakeryRepository;
public void join(MemberVO memberVO) {
memberRepository.save(memberVO);
}
public AuthVO login(MemberVO memberVO) {
MemberVO loginMember = memberRepository.findByMemberIdAndPassword(memberVO.getMemberId(), memberVO.getPassword()).get();
AuthVO authVO = new AuthVO(loginMember);
if(authVO.getGrade().equals("1")) {
authVO.setCopRegNum(bakeryRepository.findByMemberVO(loginMember).get().getCopRegNum());
}
return authVO;
}
public List<String> findId(MemberVO memberVO){
List<MemberVO> list = memberRepository.findByPhoneNumberAndEmail(memberVO.getPhoneNumber(), memberVO.getEmail()).get();
List<String> returnList = new ArrayList<String>();
for(MemberVO vo : list) {
String id = vo.getMemberId();
if(id.length()<=7) {
id = id.substring(0, id.length()-3);
id += "***";
} else {
id = id.substring(0, id.length()-4);
id += "****";
}
returnList.add(id);
}
return returnList;
}
public AuthVO findPassword(MemberVO memberVO){
return new AuthVO(memberRepository.findByMemberIdAndPhoneNumberAndEmail(memberVO.getMemberId(), memberVO.getPhoneNumber(), memberVO.getEmail()).get());
}
public void changePassword(MemberVO memberVO) {
memberRepository.findById(memberVO.getMemberSeq()).get().setPassword(memberVO.getPassword());
}
public Optional<MemberVO> myPage(MemberVO memberVO){
return memberRepository.findByMemberId(memberVO.getMemberId());
}
public void changeMember(MemberVO memberVO) {
memberRepository.save(memberVO);
}
public void quit(MemberVO memberVO){
if(memberVO.getGrade().equals("1")) {
File file = new File(Define.IMAGE_SAVE_PATH
+ bakeryRepository.findByMemberVO(memberVO).get().getBakeryPath());
bakeryRepository.deleteByMemberVO(memberVO);
file.delete();
}
memberRepository.deleteByMemberIdAndPassword(memberVO.getMemberId(), memberVO.getPassword());
}
}
| true |
c6957e022154a2e9a6aaf2ee70f1041a22775d95 | Java | whitesharks/Big_Data | /.svn/pristine/78/7899bea6d74cf742b29d028ea68cd028039bcbb7.svn-base | UTF-8 | 210 | 1.671875 | 2 | [] | no_license | package com.jp.tic.common.event;
import java.util.concurrent.ConcurrentLinkedQueue;
public interface EventTrigger<T> {
public String getTriggerName();
public ConcurrentLinkedQueue<T> getEventParamPool();
}
| true |
3f1eaaa17d9714bea4e2a06019264476e30f3815 | Java | MaximGol11/java_test_01 | /src/Qa_AutomationCourse/Homework_3/Month.java | UTF-8 | 314 | 2.640625 | 3 | [] | no_license | package Qa_AutomationCourse.Homework_3;
public class Month {
String monthName;
int dayCount;
int workDayCount;
public Month(String monthName, int dayCount, int workDayCount) {
this.monthName = monthName;
this.dayCount = dayCount;
this.workDayCount = workDayCount;
}
}
| true |
01ff3e27453ac7d711ed1aaa6f7f82b1121befdb | Java | ChoLong02/Education_Java_Basic | /BasicJava/src/problem/BubbleSort.java | UTF-8 | 1,527 | 3.703125 | 4 | [] | no_license | package problem;
import java.util.Scanner;
public class BubbleSort {
static int[] data = new int[5];
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒");
System.out.println("▒▒ 보글보글 버블정렬 Ver1.2");
System.out.println("▒▒ 5개의 무작위 수를 입력해주세요.");
for (int i = 0; i < data.length; i++) {
while(true) {
System.out.print("▒▒ "+(i+1)+"번수>>");
int num = sc.nextInt();
if(duplicateNum(num)) {
data[i] = num;
break;
}
}
}
// 초기값 출력
System.out.println("초기값========================");
viewData();
// 정렬
int temp = 0;
for(int i = 0 ; i < data.length ; i ++) { //버블 정렬
for(int j = 0 ; j < data.length -i -1 ; j ++) {
if(data[j]>data[j+1]) {
temp = data[j];
data[j] = data[j+1];
data[j+1] = temp;
}
}
viewData();
}
// 출력
// viewData();
}
public static boolean duplicateNum(int num) {
boolean flag = true;
for (int i = 0; i < data.length; i++) {
if(data[i] == num) {
flag = false;
}
}
return flag;
}
public static void viewData() {
System.out.println("===========================");
for (int i = 0; i < data.length; i++) {
System.out.print(data[i]+" ");
}
System.out.println();
}
}
| true |
356837945eca158745b7b04bf5aee716976f066c | Java | viktorijaMi/share-a-book | /book-shop-ddd/authentication/src/main/java/mk/ukim/finki/emt/authentication/service/UserService.java | UTF-8 | 1,239 | 2.265625 | 2 | [] | no_license | package mk.ukim.finki.emt.authentication.service;
import mk.ukim.finki.emt.authentication.domain.model.User;
import mk.ukim.finki.emt.authentication.domain.model.UserId;
import mk.ukim.finki.emt.authentication.rest.forms.UserLoginForm;
import mk.ukim.finki.emt.authentication.rest.forms.UserRegisterForm;
import org.springframework.security.core.userdetails.UserDetailsService;
import java.util.Optional;
public interface UserService extends UserDetailsService {
/**
* This method returns the user with id userId
* @param userId
* @return
*/
User findById(UserId userId);
/**
* This method returns the user with username username
* @param username
* @return
*/
User findByUsername(String username);
/**
* This method returns the userId of the registered user with data from userRegisterForm
* (further to be implemented with password encoder)
* @param userRegisterForm
* @return
*/
UserId register(UserRegisterForm userRegisterForm);
/**
* This method returns the logged in user
* (further to be implemented with password encoder)
* @param userLoginForm
* @return
*/
User login(UserLoginForm userLoginForm);
}
| true |
9f2307f285814f200924a3f34797fdea041b50e8 | Java | novakt28/A0B36PR2 | /Semestralni_prace/src/semestralni/prace/boat/Boat.java | UTF-8 | 1,093 | 3.203125 | 3 | [] | no_license | package semestralni.prace.boat;
import java.util.Arrays;
/**
*
* @author Tommzs
*/
public abstract class Boat {
String name;
int x;
int y;
int size;
boolean killed;
boolean[] health;
public Boat(String name, int x, int y, int size) {
this.name = name;
this.x = x;
this.y = y;
this.size = size;
this.killed = false;
this.health = new boolean[size];
Arrays.fill(health, true);
}
boolean isKilled(){
for (int i = 0; i < health.length; i++) {
if (health[i]==false) {
killed = true;
return killed;
}
}
return false;
}
public String getName() {
return name;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public void setX(int x) {
this.x = x;
}
public void setY(int y) {
this.y = y;
}
abstract void putInArray();
}
| true |
936719f62994720c845fd8d7a8c71f9b26b26c9a | Java | fjh658/bindiff | /src_procyon/org/jfree/util/SortOrder.java | UTF-8 | 1,076 | 2.828125 | 3 | [] | no_license | package org.jfree.util;
import java.io.*;
public final class SortOrder implements Serializable
{
private static final long serialVersionUID = -2124469847758108312L;
public static final SortOrder ASCENDING;
public static final SortOrder DESCENDING;
private String name;
private SortOrder(final String name) {
this.name = name;
}
public String toString() {
return this.name;
}
public boolean equals(final Object o) {
return this == o || (o instanceof SortOrder && this.name.equals(((SortOrder)o).toString()));
}
public int hashCode() {
return this.name.hashCode();
}
private Object readResolve() {
if (this.equals(SortOrder.ASCENDING)) {
return SortOrder.ASCENDING;
}
if (this.equals(SortOrder.DESCENDING)) {
return SortOrder.DESCENDING;
}
return null;
}
static {
ASCENDING = new SortOrder("SortOrder.ASCENDING");
DESCENDING = new SortOrder("SortOrder.DESCENDING");
}
}
| true |
cf2fe7e9d40ffca930bdf082b18c0e79d9f9075b | Java | SlonSky/android | /Labs/app/src/main/java/slon/sky/dev/labs/MainActivity.java | UTF-8 | 1,114 | 2.140625 | 2 | [] | no_license | package slon.sky.dev.labs;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText etFirstName = (EditText) findViewById(R.id.firstName);
final EditText etLastName = (EditText) findViewById(R.id.lastName);
Button btnRevive = (Button) findViewById(R.id.button);
btnRevive.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this.getBaseContext(), Hello.class);
intent.putExtra("firstName", etFirstName.getText().toString());
intent.putExtra("lastName", etLastName.getText().toString());
startActivity(intent);
}
});
}
}
| true |
7ef0d4cdc26c37e659def4696f22c7514d686db6 | Java | zhwei4150/monitor_manager | /antsAgent/src/main/java/com/bonree/ants/manager/agent/command/AbstractCmdExecutor.java | UTF-8 | 286 | 2.1875 | 2 | [] | no_license | package com.bonree.ants.manager.agent.command;
public abstract class AbstractCmdExecutor implements CmdExecutor{
private final String name;
public AbstractCmdExecutor(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
| true |
7bffd140f5ac48559a96f3f3d65b30b3b4b8d956 | Java | smallgowk/coin | /CoinHub/app/src/main/java/com/phanduy/interfaces/GetLocationListener.java | UTF-8 | 270 | 1.820313 | 2 | [] | no_license | package com.phanduy.interfaces;
import android.location.Location;
/**
* Created by duyuno on 8/3/16.
*/
public interface GetLocationListener {
public void onNotConnected();
public void onComplete(Location location);
public void onErrorForPermission();
}
| true |
0d9eb65f79504cef8b7d6ff7ffcfc193c1e14059 | Java | suniltota/TRIDent-CD | /src/main/java/com/actualize/mortgage/cd/datamodels/NegativeAmortization.java | UTF-8 | 923 | 2.125 | 2 | [] | no_license | package com.actualize.mortgage.cd.datamodels;
import org.w3c.dom.Element;
import com.actualize.mortgage.cd.domainmodels.MISMODataAccessObject;
/**
* represents NegativeAmortization in MISMO XML
* @author sboragala
*
*/
public class NegativeAmortization extends MISMODataAccessObject {
private static final long serialVersionUID = -5227757461474596317L;
public final String negativeAmortizationLimitMonthsCount;
public final String negativeAmortizationMaximumLoanBalanceAmount;
public final String negativeAmortizationType;
public NegativeAmortization(String NS, Element element) {
super(element);
negativeAmortizationLimitMonthsCount = getValueAddNS("NegativeAmortizationLimitMonthsCount");
negativeAmortizationMaximumLoanBalanceAmount = getValueAddNS("NegativeAmortizationMaximumLoanBalanceAmount");
negativeAmortizationType = getValueAddNS("NegativeAmortizationType");
}
}
| true |
2519d13ef68fe84d5d1de545ea447145bcc5c648 | Java | propra13-orga/gruppeA1 | /src/gruppeA1/dungeon/Map.java | UTF-8 | 3,616 | 3.171875 | 3 | [] | no_license | package gruppeA1.dungeon;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import javax.swing.JComponent;
import gruppeA1.dungeon.Tile;
public class Map extends JComponent {
private static final long serialVersionUID = 1L;
private static int sizeX = 20;
private static int sizeY = 20;
private static int tileSize = 24;
private int mapNr;
public int getMapNr() {
return this.mapNr;
}
private char playerSpawnPoint;
private Tile[][] tiles;
public Tile getTileAt(int x, int y) {
return this.tiles[x][y];
}
private Player player;
private ArrayList<Enemy> enemies;
public ArrayList<Enemy> getEnemies() {
return enemies;
}
private Game game;
public Map(int mapNr, char playerSpawnPoint, Game game) {
this.mapNr = mapNr;
this.playerSpawnPoint = playerSpawnPoint;
this.game = game;
this.readMap();
this.setSize(480,480);
}
public void paintComponent(Graphics graphics) {
super.paintComponent(graphics);
Graphics2D graphics2D = (Graphics2D) graphics;
for (int x = 0; x < sizeX; x++) {
for (int y = 0; y < sizeY; y ++) {
this.tiles[x][y].draw(graphics2D);
}
}
this.player.draw(graphics2D);
for (Enemy enemy: this.enemies) {
enemy.draw(graphics2D);
}
}
private void readMap() {
BufferedReader bufferedReader = null;
try {
bufferedReader = new BufferedReader(new FileReader("resources/maps/map-"+this.mapNr+".txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String line;
int countX;
int countY = 0;
this.tiles = new Tile[sizeX][sizeY];
this.enemies = new ArrayList<Enemy>();
try {
while ((line = bufferedReader.readLine()) != null) {
countX = 0;
for (char type: line.toCharArray()) {
this.tiles[countX][countY] = new Tile(countX, countY, tileSize, this, type);
if (type == '0' && this.playerSpawnPoint == '0') {
this.player = new Player(countX, countY, tileSize, this);
}
if (type == 'x' && this.playerSpawnPoint == 'x') {
this.player = new Player(countX, countY, tileSize, this);
}
if (type == 'e') {
this.enemies.add(new Enemy(countX, countY, tileSize, this));
}
countX++;
}
countY++;
}
} catch (IOException e) {
e.printStackTrace();
}
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void movePlayer(int x, int y) {
if (this.tryToMoveEntity(this.player, x, y)) {
Tile targetTile = this.tiles[this.player.getX()][this.player.getY()];
if (targetTile.isEntrance()) {
this.game.previousMap();
}
if (targetTile.isExit()) {
this.game.nextMap();
}
if (targetTile.isEnemy()) {
this.game.stopGame(false);
}
this.repaint();
}
}
public void moveEnemy(Enemy enemy, int x, int y) {
if (this.tryToMoveEntity(enemy, x, y)) {
if (this.player.getX() == enemy.getX() && this.player.getY() == enemy.getY()) {
this.game.stopGame(false);
}
}
}
public boolean tryToMoveEntity(MoveableEntity moveableEntity, int x, int y) {
int moveableEntityX = moveableEntity.getX();
int moveableEntityY = moveableEntity.getY();
if(moveableEntityX == 0 || moveableEntityX == sizeX-1 || moveableEntityY == 0 || moveableEntityY == sizeY-1) {
return false;
}
Tile targetTile = this.tiles[moveableEntityX+x][moveableEntityY+y];
return moveableEntity.moveTo(targetTile);
}
}
| true |
868316d0a61a55e2ba56f665030e0ab513e10189 | Java | vitorino87/SuperClassReferenceSubClass | /src/superclassreferencesubclass/BoxWeight.java | UTF-8 | 465 | 2.296875 | 2 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package superclassreferencesubclass;
/**
*
* @author tiago.lucas
*/
public class BoxWeight extends Box{
double weight;
BoxWeight(double w, double h, double d, double m){
width=w;
height=h;
depth=d;
weight=m;
}
}
| true |
c468b2f37bb82461f6619de6bd26593517901c59 | Java | nastysizonenko/Server-applications | /Laba2Var4/src/com/company/MediumGroup.java | UTF-8 | 471 | 2.828125 | 3 | [] | no_license | package com.company;
public class MediumGroup extends GamesRoom{
private int price;
private Toys toys;
public MediumGroup(String model, int price, int number) {
this.price= price;
this.toys = Toys.MediumCar_and_Ball;
super.setNumber(number);
}
@Override
public String toString() {
return "MediumGroup{ " + "Number =" + super.getNumber() + ", price =" + price + ", toys =" + toys + " }";
}
} | true |
bcc482f3dfe7b419ec4d12123edc35781eb20c99 | Java | Anvar235/WarehouseDataRest | /src/main/java/uz/pdp/task/repository/OutputRepository.java | UTF-8 | 410 | 1.71875 | 2 | [] | no_license | package uz.pdp.task.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
import uz.pdp.task.entitty.Output;
import uz.pdp.task.projection.CustomOutput;
@RepositoryRestResource(path = "output", excerptProjection = CustomOutput.class)
public interface OutputRepository extends JpaRepository<Output, Integer> {
}
| true |
b9e050bb17796717d318323828d7b98ef0bab2d5 | Java | zetaapps/myntra | /thunderbird/src/main/java/zeta/android/thunderbird/api/idpapi/response/params/IdpMyntraLoginParams.java | UTF-8 | 385 | 1.789063 | 2 | [
"Apache-2.0"
] | permissive | package zeta.android.thunderbird.api.idpapi.response.params;
public class IdpMyntraLoginParams {
public final String action;
public final String userId;
public final String password;
public IdpMyntraLoginParams(String action, String userId, String password) {
this.action = action;
this.userId = userId;
this.password = password;
}
}
| true |
35b083ff5b279cb1b3ff05f5c0cb7abe38630713 | Java | Comcast/jclouds-labs | /azurecompute/src/main/java/org/jclouds/azurecompute/domain/ProfileDefinitionEndpointParams.java | UTF-8 | 6,175 | 2.171875 | 2 | [
"Apache-2.0"
] | permissive | /*
* 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.jclouds.azurecompute.domain;
import com.google.auto.value.AutoValue;
import org.jclouds.azurecompute.domain.ProfileDefinition.Status;
import org.jclouds.azurecompute.domain.ProfileDefinitionEndpoint.Type;
import org.jclouds.javax.annotation.Nullable;
/**
* Encapsulates the list of Azure Traffic Manager endpoints. You can define up to 100 endpoints in the list.
*
* @see <a href="https://msdn.microsoft.com/en-us/library/azure/hh758257.aspx">docs</a>
*/
@AutoValue
public abstract class ProfileDefinitionEndpointParams {
ProfileDefinitionEndpointParams() {
} // For AutoValue only!
/**
* Specifies the endpoint domain name. The value depends on endpoint type. If Type is CloudService, the value must be
* a fully qualified domain name (FQDN) of a cloud service that belongs to the subscription ID that owns the
* definition. If Type is AzureWebsite, the value must be an FQDN of an Azure web site that belongs to the
* subscription ID that owns the definition. If Type is Any, the value can be any FQDN for an Azure service or a
* service outside of Azure.
*
* @return endpoint domain name.
*/
public abstract String domain();
/**
* Specifies the status of the monitoring endpoint. If set to Enabled, the endpoint is considered by the load
* balancing method and is monitored. Possible values are:Enabled, Disabled
*
* @return status of the monitoring endpoint.
*/
public abstract Status status();
/**
* Optional. Specifies the type of endpoint being added to the definition. Possible values are: CloudService,
* AzureWebsite, Any, TrafficManager.
*
* If there is more than one AzureWebsite endpoint, they must be in different datacenters. This limitation doesn’t
* apply to cloud services. The default value is CloudService. Use the TrafficManager type when configuring nested
* profiles..
*
* @return endpoint type.
* @see <a href="https://msdn.microsoft.com/en-us/library/azure/hh744833.aspx">Traffic Manager Overview</a>
*/
@Nullable
public abstract Type type();
/**
* Required when LoadBalancingMethod is set to Performance and Type is set to Any or TrafficManager. Specifies the
* name of the Azure region. The Location cannot be specified for endpoints of type CloudService or AzureWebsite, in
* which the locations are determined from the service.
*
* @return endpoint protocol.
* @see <a href="https://msdn.microsoft.com/en-us/library/gg441293.aspx">List Locations</a>
*/
@Nullable
public abstract String location();
/**
* Optional. Can be specified when Type is set to TrafficManager. The minimum number of healthy endpoints within a
* nested profile that determines whether any of the endpoints within that profile can receive traffic. Default value
* is 1.
*
* @return minimum number of healthy endpoints.
*/
@Nullable
public abstract Integer min();
/**
* Optional. Specifies the priority of the endpoint in load balancing. The higher the weight, the more frequently the
* endpoint will be made available to the load balancer. The value must be greater than 0. For endpoints that do not
* specify a weight value, a default weight of 1 will be used.
*
* @return endpoint priority.
*/
@Nullable
public abstract Integer weight();
public Builder toBuilder() {
return builder().fromImageParams(this);
}
public static Builder builder() {
return new Builder();
}
public static final class Builder {
private String domain;
private Status status;
private Type type;
private String location;
private Integer min;
private Integer weight;
public Builder domain(final String domain) {
this.domain = domain;
return this;
}
public Builder status(final Status status) {
this.status = status;
return this;
}
public Builder type(final Type type) {
this.type = type;
return this;
}
public Builder location(final String location) {
this.location = location;
return this;
}
public Builder min(final Integer min) {
this.min = min;
return this;
}
public Builder weight(final Integer weight) {
this.weight = weight;
return this;
}
public ProfileDefinitionEndpointParams build() {
return ProfileDefinitionEndpointParams.create(
domain,
status,
type,
location,
min,
weight);
}
public Builder fromImageParams(final ProfileDefinitionEndpointParams in) {
return domain(in.domain())
.status(in.status())
.type(in.type())
.location(in.location())
.min(in.min())
.weight(in.weight());
}
}
private static ProfileDefinitionEndpointParams create(
final String domain,
final Status status,
final Type type,
final String location,
final Integer min,
final Integer weight) {
return new AutoValue_ProfileDefinitionEndpointParams(domain, status, type, location, min, weight);
}
}
| true |
6e5bc7c0ae4441511ee6dc99baf537163827ccd1 | Java | X901/Baking_App | /app/src/main/java/com/basil/bakingapp/RecipeVideoPlayerActivity.java | UTF-8 | 1,729 | 1.539063 | 2 | [] | no_license | package com.basil.bakingapp;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import com.google.android.exoplayer2.DefaultLoadControl;
import com.google.android.exoplayer2.ExoPlayerFactory;
import com.google.android.exoplayer2.LoadControl;
import com.google.android.exoplayer2.SimpleExoPlayer;
import com.google.android.exoplayer2.extractor.DefaultExtractorsFactory;
import com.google.android.exoplayer2.extractor.ExtractorsFactory;
import com.google.android.exoplayer2.source.ExtractorMediaSource;
import com.google.android.exoplayer2.source.MediaSource;
import com.google.android.exoplayer2.trackselection.AdaptiveTrackSelection;
import com.google.android.exoplayer2.trackselection.DefaultTrackSelector;
import com.google.android.exoplayer2.trackselection.TrackSelection;
import com.google.android.exoplayer2.trackselection.TrackSelector;
import com.google.android.exoplayer2.ui.SimpleExoPlayerView;
import com.google.android.exoplayer2.upstream.BandwidthMeter;
import com.google.android.exoplayer2.upstream.DefaultBandwidthMeter;
import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory;
import com.google.android.exoplayer2.upstream.DefaultHttpDataSourceFactory;
import com.google.android.exoplayer2.util.Util;
import butterknife.BindView;
import butterknife.ButterKnife;
public class RecipeVideoPlayerActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recipe_video_player);
ButterKnife.bind(this);
}
}
| true |
acbfbf4a566a95090955429c7ed00e8a4e2835ec | Java | EunSuGim/my_tasty | /src/main/java/com/counchcoding/project/web/dto/CategoriesRequestSaveDto.java | UTF-8 | 599 | 2.21875 | 2 | [] | no_license | package com.counchcoding.project.web.dto;
import com.counchcoding.project.domain.categories.Categories;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
@Getter
@NoArgsConstructor
public class CategoriesRequestSaveDto {
private String name;
private String code;
@Builder
public CategoriesRequestSaveDto(String name, String code){
this.name = name;
this.code = code;
}
public Categories toEntity(){
return Categories.builder()
.name(name)
.code(code)
.build();
}
}
| true |
482aacce48502b1e12752012de520463d3eb04a6 | Java | nedjo4real/SoftUni-Java | /Technology Fundamentals with Java/02. Data-Types-and-Variables/02. Data-Types-and-Variables-Exercises/Elevator.java | UTF-8 | 363 | 3.0625 | 3 | [] | no_license | import java.util.Scanner;
//Elevator
public class Elevator {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
double n = Double.parseDouble(scan.nextLine());
double p = Double.parseDouble(scan.nextLine());
int courses = (int) Math.ceil((double) n/p);
System.out.println(courses);
}
}
| true |
2425b775e2b48d06aad0f506c4314579df09923a | Java | aijingsun6/leetcode | /src/main/java/org/alking/p300/P347.java | UTF-8 | 1,363 | 3.234375 | 3 | [] | no_license | package org.alking.p300;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.PriorityQueue;
public class P347 {
public int[] topKFrequent(int[] nums, int k) {
HashMap<Integer, Integer> counterMap = new HashMap<>();
for (int v : nums) {
counterMap.put(v, counterMap.getOrDefault(v, 0) + 1);
}
PriorityQueue<Map.Entry<Integer, Integer>> queue = new PriorityQueue<>(new Comparator<Map.Entry<Integer, Integer>>() {
@Override
public int compare(Map.Entry<Integer, Integer> o1, Map.Entry<Integer, Integer> o2) {
return o1.getValue() - o2.getValue();
}
});
int size = counterMap.size();
size = Math.min(size, k);
for (Map.Entry<Integer, Integer> entry : counterMap.entrySet()) {
if (queue.size() < k) {
queue.offer(entry);
} else {
Map.Entry<Integer, Integer> old = queue.peek();
if (entry.getValue() > old.getValue()) {
queue.poll();
queue.offer(entry);
}
}
}
int[] result = new int[size];
for (int idx = size - 1; idx >= 0; idx--) {
result[idx] = queue.poll().getKey();
}
return result;
}
}
| true |
533ddaa7f46a4bb8e7420f3e3270ab188f90eecd | Java | kovalchuk12/last_crocodile_version | /app/src/main/java/com/makarevich/dmitry/crock/room/Eng_Transport.java | UTF-8 | 786 | 2.296875 | 2 | [] | no_license | package com.makarevich.dmitry.crock.room;
import android.arch.persistence.room.ColumnInfo;
import android.arch.persistence.room.Entity;
import android.arch.persistence.room.PrimaryKey;
@Entity(tableName = "eng_transport")
public class Eng_Transport {
@PrimaryKey(autoGenerate = true)
private int id_eng_transport;
@ColumnInfo(name = "transport_english")
private String transport_eng;
public int getId_eng_transport() {
return id_eng_transport;
}
public void setId_eng_transport(int id_eng_transport) {
this.id_eng_transport = id_eng_transport;
}
public String getTransport_eng() {
return transport_eng;
}
public void setTransport_eng(String transport_eng) {
this.transport_eng = transport_eng;
}
}
| true |
3cb726927ce6bcb0649dcdb2d348e8b5b999ca49 | Java | BertrandAudinet/ddd-tetris | /src/main/java/tetris/domain/battle/event/BattleEventQueue.java | UTF-8 | 1,341 | 2.875 | 3 | [] | no_license | package tetris.domain.battle.event;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
public class BattleEventQueue implements BattleListener {
private Queue<BattleEvent> queue;
public BattleEventQueue(List<BattleEvent> events) {
queue = new LinkedList<BattleEvent>(events);
}
public BattleEventQueue() {
this(Collections.EMPTY_LIST);
}
public void push(BattleEvent event) {
queue.add(event);
}
public BattleEvent peek() {
return queue.peek();
}
public List<BattleEvent> values() {
final List<BattleEvent> events = new ArrayList<BattleEvent>();
for (BattleEvent event : queue) {
events.add(event);
}
return events;
}
public BattleEventQueue push(BattleEventQueue eventQueue) {
List<BattleEvent> events = this.values();
events.addAll(eventQueue.values());
return new BattleEventQueue(events);
}
@Override
public void penaltyLineAdded(BattlePenaltyLineAdded event) {
push(event);
}
@Override
public void tetrisJoined(BattleTetrisJoined event) {
push(event);
}
@Override
public void battleStarted(BattleStarted event) {
push(event);
}
}
| true |
25876b9f8eec2f433957575b762405c32ad06cf8 | Java | SreeHarsha1/Playground | /Finding the maximum element's index/Main.java | UTF-8 | 534 | 3 | 3 | [] | no_license | import java.util.Scanner;
class Main
{
public static void main(String args[])
{
//Try your code here
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int arr[]=new int[n];
for(int i=0;i<n;i++)
{
arr[i]=in.nextInt();
}
sos(arr,n);
}
public static void sos(int arr[],int n)
{
int max=arr[0],index=0;
for(int i=1;i<n;i++)
{
if(max<arr[i])
{
max=arr[i];
index=i;
}
}
System.out.println(index);
//Try your code here
}
} | true |
fd30340468df6334b4aab539e5165a864ea5c1a6 | Java | FuriousPws002/furious-util | /src/test/java/com/furious/util/unsafe/ReflectionsTest.java | UTF-8 | 567 | 2.609375 | 3 | [] | no_license | package com.furious.util.unsafe;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.lang.reflect.Field;
import org.junit.jupiter.api.Test;
class ReflectionsTest {
private static class TestStaticField {
private static final Integer val = 1;
private TestStaticField() {
}
}
@Test
public void testSetStaticField() throws Exception {
Field field = TestStaticField.class.getDeclaredField("val");
Reflections.setField(null, field, 2);
assertEquals(2, TestStaticField.val);
}
} | true |
829c20207cb9dfd062bbdf8ca5a126ad79915ad5 | Java | ewade1/frc319-2018 | /src/org/usfirst/frc/team319/robot/commands/autonomous_paths/RightWallToRightScaleNullZone.java | UTF-8 | 913 | 1.882813 | 2 | [] | no_license | package org.usfirst.frc.team319.robot.commands.autonomous_paths;
import org.usfirst.frc.team319.arcs.RightWallToRightScaleNullZoneArc;
import org.usfirst.frc.team319.robot.commands.FollowArc;
import org.usfirst.frc.team319.robot.commands.TeleopGoToDunkPose;
import org.usfirst.frc.team319.robot.commands.autonomous_subsystems.GoToDunkPose;
import org.usfirst.frc.team319.robot.commands.cubecollector.CubeCollectorSpit;
import org.usfirst.frc.team319.robot.commands.elevator.GoToCollectPose;
import edu.wpi.first.wpilibj.command.CommandGroup;
/**
*/
public class RightWallToRightScaleNullZone extends CommandGroup {
public RightWallToRightScaleNullZone() {
addSequential(new FollowArc(new RightWallToRightScaleNullZoneArc()));
addSequential(new TeleopGoToDunkPose());
addSequential(new CubeCollectorSpit(-0.75), 0.5);
addSequential(new GoToCollectPose());
}
}
| true |
d40075896ee561865a9d4465b303689c66cb1330 | Java | Opalised/Apec | /src/main/java/Apec/Components/Gui/Menu/ApecMenu.java | UTF-8 | 4,907 | 2.28125 | 2 | [
"MIT"
] | permissive | package Apec.Components.Gui.Menu;
import Apec.ApecMain;
import Apec.Component;
import Apec.ComponentId;
import Apec.Settings.Setting;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.gui.ScaledResolution;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraftforge.client.event.GuiScreenEvent;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import java.io.IOException;
import java.util.ArrayList;
public class ApecMenu extends Component {
protected Minecraft mc = Minecraft.getMinecraft();
public ApecMenu() {
super(ComponentId.SETTINGS_MENU);
}
@Override
protected void onEnable() {
ApecMenuGui apecMenuGui = new ApecMenuGui();
mc.displayGuiScreen(apecMenuGui);
this.Toggle();
}
private class ApecMenuGui extends GuiScreen {
@Override
public void initGui() {
super.initGui();
ScaledResolution sr = new ScaledResolution(mc);
int h = sr.getScaledHeight()/2;
int w = sr.getScaledWidth()/2;
for (int i = 0;i < ApecMain.Instance.settingsManager.settings.size();i++) {
buttonList.add(new ApecMenuButton(i,w-235+(i%3)*160,h-120 + 60*(i/3),15*10,5*10, ApecMain.Instance.settingsManager.settings.get(i)));
}
}
@Override
public void drawScreen(int mouseX, int mouseY, float partialTicks) {
ScaledResolution sr = new ScaledResolution(mc);
int h = sr.getScaledHeight()/2;
int w = sr.getScaledWidth()/2;
final int spaceBetweenLines = 60, spaceBetweenRows = 160;
drawRect(w-245,h-130,w+245,h+130,0x990a0a0a);
for (int i = 0;i < ApecMain.Instance.settingsManager.settings.size();i++) {
Setting s = ApecMain.Instance.settingsManager.settings.get(i);
boolean enabled = ApecMain.Instance.settingsManager.settings.get(i).enabled;
int x = w-235+(i%3)*160;
int y = h-120 + spaceBetweenLines * (i/3);
drawRectangleAt(x,y,15,5,mouseX,mouseY);
GlStateManager.pushMatrix();
GlStateManager.scale(1.1f,1.1f,1.1f);
mc.fontRendererObj.drawString(s.name,(int)((x+7) / 1.1f),(int)((y+6) / 1.1f), enabled ? 0x00ff00 : 0xff0000);
GlStateManager.popMatrix();
GlStateManager.pushMatrix();
GlStateManager.scale(0.8f,0.8f,0.8f);
drawWrappedString(s.description,(int)((x+7) / 0.8f),(int)((y + 18) / 0.8f),0xffffff);
GlStateManager.popMatrix();
}
super.drawScreen(mouseX, mouseY, partialTicks);
}
public void drawWrappedString(String s,int x,int y,int c) {
final int widthToWrap = 110;
ArrayList<String> lines = new ArrayList<String>();
int il = 0;
for (char ch : s.toCharArray()) {
if (lines.size() == il) lines.add("");
lines.set(il,lines.get(il).concat(String.valueOf(ch)));
if (mc.fontRendererObj.getStringWidth(lines.get(il)) >= widthToWrap && ch == ' ') il++;
}
for (int i = 0;i < lines.size();i++) {
mc.fontRendererObj.drawString(lines.get(i),x,y + (int)(i*10/0.8f),c);
}
}
@Override
public boolean doesGuiPauseGame() {
return false;
}
public void drawRectangleAt(int x,int y,int w,int h,int mX,int mY) {
drawRect(x,y,x+w*10,y+h*10,0x99151515);
for (int i = 0;i < w;i++) {
drawLineComponent(x + i *10,y-1,x + (i+1)*10,y+1,mX,mY);
drawLineComponent(x + i *10,y-1 + h*10,x + (i+1)*10,y+1+ h*10,mX,mY);
}
for (int i = 0;i < h;i++) {
drawLineComponent(x-1,y+i*10,x+ 1,y+(i+1)*10,mX,mY);
drawLineComponent(x-1+ w*10,y+i*10,x + 1 + w*10,y+(i+1)*10,mX,mY);
}
}
private void drawLineComponent(int left,int top,int right,int bottom,int mX,int mY) {
double range = 45;
double dist = Math.sqrt(Math.pow(left - mX,2) + Math.pow(top - mY,2));
if (dist > range) dist = range;
drawRect(left,top,right,bottom,0xffffff | ((int)(0xff * ((range-dist)/range)) << 24));
}
@Override
protected void mouseClicked(int mouseX, int mouseY, int mouseButton) throws IOException {
super.mouseClicked(mouseX, mouseY, mouseButton);
if (mouseButton == 0) for (net.minecraft.client.gui.GuiButton guiButton : this.buttonList)
if (guiButton.mousePressed(mc, mouseX, mouseY)) ((ApecMenuButton) guiButton).ToggleSetting();
}
}
}
| true |
434bbeba792e1f982c4d8cc5f5830a938779bce7 | Java | wangjianlin1985/android_library_seat | /安卓客户端/src/com/mobileclient/handler/SeatStateListHandler.java | UTF-8 | 1,758 | 2.375 | 2 | [] | no_license | package com.mobileclient.handler;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import com.mobileclient.domain.SeatState;
public class SeatStateListHandler extends DefaultHandler {
private List<SeatState> seatStateList = null;
private SeatState seatState;
private String tempString;
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
super.characters(ch, start, length);
if (seatState != null) {
String valueString = new String(ch, start, length);
if ("stateId".equals(tempString))
seatState.setStateId(new Integer(valueString).intValue());
else if ("stateName".equals(tempString))
seatState.setStateName(valueString);
}
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
super.endElement(uri, localName, qName);
if("SeatState".equals(localName)&&seatState!=null){
seatStateList.add(seatState);
seatState = null;
}
tempString = null;
}
@Override
public void startDocument() throws SAXException {
super.startDocument();
seatStateList = new ArrayList<SeatState>();
}
@Override
public void startElement(String uri, String localName, String qName,Attributes attributes) throws SAXException {
super.startElement(uri, localName, qName, attributes);
if ("SeatState".equals(localName)) {
seatState = new SeatState();
}
tempString = localName;
}
public List<SeatState> getSeatStateList() {
return this.seatStateList;
}
}
| true |
a6c18b5be9f2c13896f2506a7fd8ec50f6309fe9 | Java | yan-hai/leetcode | /src/test/java/com/nobodyhub/leetcode/ReverseVowelsOfAStringTest.java | UTF-8 | 900 | 2.984375 | 3 | [] | no_license | package com.nobodyhub.leetcode;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
* @author Ryan
* @since 04/12/2017
*/
public class ReverseVowelsOfAStringTest {
@Test
public void test() {
String s = "hello";
String expected = "holle";
ReverseVowelsOfAString solution = new ReverseVowelsOfAString();
assertEquals(expected, solution.reverseVowels(s));
}
@Test
public void test1() {
String s = "leetcode";
String expected = "leotcede";
ReverseVowelsOfAString solution = new ReverseVowelsOfAString();
assertEquals(expected, solution.reverseVowels(s));
}
@Test
public void test2() {
String s = "aA";
String expected = "Aa";
ReverseVowelsOfAString solution = new ReverseVowelsOfAString();
assertEquals(expected, solution.reverseVowels(s));
}
} | true |
505ad9b3084b542cec1b70b067d764fd7bf3e9a4 | Java | tangpengPlus/baozhong | /bz_interface/src/main/java/com/bz/open/core/service/pay/AlipayService.java | UTF-8 | 688 | 1.984375 | 2 | [] | no_license | package com.bz.open.core.service.pay;
import com.bz.framework.error.exception.PayException;
import com.bz.open.core.vo.request.alipay.AliPayRequest;
/**
*
*
* 作者:唐鹏
* 创建时间:2017年11月6日上午10:49:08
* 描述:Alipay服务实现
* 备注:
*/
public interface AlipayService {
/**
*
*
* 作者:唐鹏
* 创建时间:2017年11月6日上午11:23:42
* 描述:支付宝支付开放服务
* 备注:
* @param aliPayRequest:支付宝支付请求参数 {@link AliPayRequest}
* @return
* @throws PayException {@link PayException}支付异常信息封装
*/
public String AlipayMobilePhoneOrder(AliPayRequest aliPayRequest)throws PayException;
}
| true |
7ecc716554c0b04e68332e1bffc950c441a9905c | Java | doublethink/Tag-and-Track | /src/nz/co/doublethink/tagandtrack/CustomAdapter.java | UTF-8 | 2,623 | 2.484375 | 2 | [] | no_license | package nz.co.doublethink.tagandtrack;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class CustomAdapter extends ArrayAdapter<Specimen>{
private ArrayList<Specimen> entries;
private Activity activity;
public CustomAdapter(Activity a, int textViewResourceId, ArrayList<Specimen> entries) {
super(a, textViewResourceId, entries);
this.entries = entries;
this.activity = a;
}
public static class ViewHolder{
public TextView item1;
public TextView item2;
public ImageView image;
public Bitmap scaledbitmap = null;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
ViewHolder holder;
if (v == null) {
LayoutInflater vi =
(LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.grid_item, null);
holder = new ViewHolder();
holder.item1 = (TextView) v.findViewById(R.id.big);
holder.item2 = (TextView) v.findViewById(R.id.small);
holder.image = (ImageView) v.findViewById(R.id.image);
v.setTag(holder);
}
else
holder=(ViewHolder)v.getTag();
final Specimen custom = entries.get(position);
if (custom != null) {
holder.item1.setText(custom.uid);
holder.item2.setText(custom.species);
Uri uri = Uri.parse(custom.photo);
holder.image.setImageURI(null);
if (!custom.isDynamic){
holder.image.setImageURI(uri);
} else {
holder.image.setImageBitmap(dynamicBitmap(convertView,uri,holder));
}
}
return v;
}
@SuppressWarnings("static-access")
private Bitmap dynamicBitmap(View view, Uri uri,ViewHolder holder){
if (holder.scaledbitmap==null){
try{
Bitmap originalbitmap = MediaStore.Images.Media.getBitmap(view.getContext().getContentResolver(), uri);
holder.scaledbitmap = originalbitmap.createScaledBitmap(originalbitmap, 90, 160, true);
} catch (Exception e){
System.out.println("Failed to get image");
}
}
return holder.scaledbitmap;
}
}
| true |
c3e763ac5e8fac355d9b3a1d35a407f7502736fb | Java | barunsarraf/Movie_Web_Spring_Boot | /Movie-RestFul-API-using-Spring-Boot-MongoDatabase/src/main/java/com/stackroute/Movie/config/ApplicationConfiguration.java | UTF-8 | 2,326 | 1.960938 | 2 | [] | no_license | package com.stackroute.Movie.config;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import springfox.documentation.service.Contact;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.h2.server.web.WebServlet;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
@EnableTransactionManagement
public class ApplicationConfiguration {
//this is for h2 console to view the tables in web
// to access this type localhost:8080/console in your browser
@Bean
ServletRegistrationBean servletRegistrationBean()
{
ServletRegistrationBean servletRegistrationBean= new ServletRegistrationBean(new WebServlet());
servletRegistrationBean.addUrlMappings("/console/*");
return servletRegistrationBean;
}
@Bean
public Docket productApi() {
return new Docket(DocumentationType.SWAGGER_2)
.select().apis(RequestHandlerSelectors.basePackage("com.stackroute"))
.paths(PathSelectors.regex("/api.*"))
.build().apiInfo(metaData());
}
private ApiInfo metaData() {
ApiInfo apiInfo = new ApiInfo(
"Spring Boot REST API",
"Spring Boot REST API for Movie App",
"1.0",
"Terms of service",
new Contact("Barun Sarraf", "https://stackroute.com", "barunsaraf1@gmail.com"),
"Apache License Version 2.0",
"https://www.apache.org/licenses/LICENSE-2.0");
return apiInfo;
}
//uncomment this too while using value based annotation injection in application context
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer()
{
return new PropertySourcesPlaceholderConfigurer();
}
}
| true |
b18946ab4812dc7d4d1896e495ca32ecca8d550c | Java | lejdiprifti/suggestion | /server-app/src/main/java/com/ikubinfo/project/entity/State.java | UTF-8 | 98 | 1.515625 | 2 | [] | no_license | package com.ikubinfo.project.entity;
public enum State {
PROPOSED,
CREATED,
DECLINED
}
| true |
e4023a03513f613613dcc88f8cc7bd7d49e5ce4e | Java | guochens/JianZhiOffer | /src/com/sgc/p2/p25.java | UTF-8 | 3,523 | 3.265625 | 3 | [] | no_license | package com.sgc.p2;
import javax.swing.*;
import java.util.*;
public class p25 {
public static void main(String[] args) {
TreeNode t1 = new TreeNode(4);
TreeNode t2 = new TreeNode(2);
TreeNode t3 = new TreeNode(6);
TreeNode t4 = new TreeNode(1);
TreeNode t5 = new TreeNode(3);
TreeNode t6 = new TreeNode(5);
TreeNode t7 = new TreeNode(7);
TreeNode root1 = t1;
root1.left = t2;
root1.right = t3;
t2.left = t4;
t2.right = t5;
t3.left = t6;
t3.right = t7;
// TreeNode test = Convert(root1);
TreeNode test1 = Convert1(root1);
}
// public static TreeNode Convert(TreeNode pRootOfTree) {
// if(pRootOfTree==null){
// return null;
// }
// TreeNode preHead = null;
//
// Stack<TreeNode> stack = new Stack<>();
// Set<TreeNode> set = new HashSet<>();
// stack.add(pRootOfTree);
// while(!stack.isEmpty()){
// TreeNode curr = stack.peek();
// if(set.contains(curr)){
// if(set.contains(curr.right)){
// TreeNode temp = stack.pop();
// preHead.right = temp;
// temp.left = preHead;
// preHead = preHead.right;
// }else{
// if(set.contains(curr.right)){
// stack.pop();
// }
// }
// }
// if(curr.left!=null){
// stack.add(curr.left);
// }else{
// preHead = stack.pop();
// preHead = preHead.right;
// }
// }
// }
public static TreeNode Convert(TreeNode pRootOfTree) {
if(pRootOfTree==null){
return null;
}
Map<Integer,TreeNode> map = new HashMap<>();
Stack<TreeNode> stack = new Stack<>();
stack.push(pRootOfTree);
while (!stack.isEmpty()){
TreeNode temp = stack.pop();
map.put(temp.val,temp);
if(temp.left!=null){
stack.push(temp.left);
}
if(temp.right!=null){
stack.push(temp.right);
}
}
ArrayList<Integer> arrayList = new ArrayList<>();
arrayList.addAll(map.keySet());
arrayList.sort(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o1>o2?1:-1;
}
});
TreeNode preHead = new TreeNode(0);
TreeNode head = map.get(arrayList.get(0));
head.left = null;
preHead.right = head;
for(int i = 1;i<arrayList.size();i++){
TreeNode t = map.get(arrayList.get(i));
head.right = t;
t.left = head;
head = head.right;
}
head.right = null;
return preHead.right;
}
static TreeNode head = null;
static TreeNode prehead = null;
public static TreeNode Convert1(TreeNode pRootOfTree) {
convertsub(pRootOfTree);
return prehead;
}
public static void convertsub(TreeNode root){
if(root==null){
return;
}
convertsub(root.left);
if(head==null){
head = root;
prehead = root;
}else{
head.right = root;
root.left = head;
head = head.right;
}
convertsub(root.right);
}
}
| true |
a04952fbbbef97205f334a5c2aafee4ee5f813ba | Java | rahulrainaaa/TatvaAdventure | /app/src/main/java/com/tatva/tatvaadventure/httphandler/ASyncHttpHandler.java | UTF-8 | 4,050 | 2.65625 | 3 | [] | no_license | package com.tatva.tatvaadventure.httphandler;
import android.os.AsyncTask;
import android.util.Log;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
public class ASyncHttpHandler extends AsyncTask<String, String, String> {
private HttpCallback callback = null;
private JSONObject jsonRequest = null;
private String url = null;
private int STATUS_CODE = -1;
private int tag = -1;
private String STATUS_MESSAGE = null;
public ASyncHttpHandler(HttpCallback callback, String url, JSONObject jsonRequest, int tag) {
this.callback = callback;
this.jsonRequest = jsonRequest;
this.tag = tag;
this.url = url;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected String doInBackground(String... params) {
try {
//Create HttpURLConnection and set request properties
URL url = new URL(this.url);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestMethod("POST");
//Create output stream and write data-request
OutputStream os = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(jsonRequest.toString());
writer.flush();
writer.close();
os.close();
//Open and check the connectivity
urlConnection.connect();
STATUS_CODE = urlConnection.getResponseCode();
STATUS_MESSAGE = urlConnection.getResponseMessage();
if (STATUS_CODE == 200) {
InputStream it = new BufferedInputStream(urlConnection.getInputStream());
InputStreamReader read = new InputStreamReader(it);
BufferedReader buff = new BufferedReader(read);
StringBuilder dta = new StringBuilder();
String chunks;
while ((chunks = buff.readLine()) != null) {
dta.append(chunks);
}
return dta.toString();
} else {
return null;
}
} catch (Exception e) {
STATUS_CODE = -1;
STATUS_MESSAGE = "Connection Failed";
return null;
}
}
@Override
protected void onPostExecute(String s) {
if (STATUS_CODE == 200) {
//SUCCESS
if (callback != null) {
callback.onHttpSuccess(STATUS_CODE, STATUS_MESSAGE, s.trim(), tag);
} else {
Log.d("ASyncHttpHandler", "SUCCESS, But httpCallback is null");
}
} else if (STATUS_CODE == -1) {
//ERROR
if (callback != null) {
callback.onHttpError(tag);
} else {
Log.d("ASyncHttpHandler", "FAIL, But httpCallback is null");
}
} else {
//FAILED
if (callback != null) {
callback.onHttpFail(STATUS_CODE, STATUS_MESSAGE, tag);
} else {
Log.d("ASyncHttpHandler", "ERROR-EXCEPTION, But httpCallback is null");
}
}
super.onPostExecute(s);
}
/**
* @method destroyAll
* @desc Close, Remove, null the objects
*/
private void destroyAll() {
callback = null;
jsonRequest = null;
STATUS_MESSAGE = null;
}
@Override
protected void finalize() throws Throwable {
destroyAll();
super.finalize();
}
}
| true |
86ecdcb6183971772eda2ae016b5eae1556191ce | Java | egydGIT/javaBackend | /src/main/java/catalog/CatalogItem.java | UTF-8 | 1,238 | 2.640625 | 3 | [] | no_license | /*
CatalogItem osztály: Minden katalógus elemnek van egy jellemzők listája melyek lehetnek akár nyomtatottak vagy audio-k.
Továbbá minden katalógus elemnek van ára és egy regisztrációs száma.
*/
package catalog;
import java.util.ArrayList;
import java.util.List;
public class CatalogItem {
private List<Feature> features = new ArrayList<>();
private final int price;
private final String registrationNumber;
public CatalogItem(List<Feature> features, int price, String registrationNumber) {
this.features = features;
this.price = price;
this.registrationNumber = registrationNumber;
}
// public int fullLengthAtOneItem() {
//
// }
//
// public List<String> getContributors() {
// return null;
// }
//
// public String getTitle() {
// return null;
// }
//
// public boolean hasAudioFeature() {
//
// }
//
// public boolean hasPrintedFeature() {
//
// }
//
// public int numberOfPagesAtOneItem() {
//
// }
public List<Feature> getFeatures() {
return features;
}
public int getPrice() {
return price;
}
public String getRegistrationNumber() {
return registrationNumber;
}
}
| true |
5e88e1f3195aa7d48ec2aae47d5cf24b10002283 | Java | Kalinin-Maksim-JavaDev/MultySimSystems | /Implementation/Scenarios/Implementation.Scenarios/src/Model/Models/Scenarios/Actions/ActionScenario.java | UTF-8 | 1,819 | 2.375 | 2 | [] | no_license | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Model.Models.Scenarios.Actions;
import Application.Build.Panels.Control.Manipulator.IManipulator;
import Application.Build.Panels.Control.Manipulator.IManipulator.IAction;
import Logic.Model.Scenarios.IScenario;
import Logic.Model.Scenarios.IScenarioMotionReciver;
import Platform.Core.IArgument;
/**
*
* @author kalinin
*/
public abstract class ActionScenario implements IAction {
protected int grad;
protected IScenario scenario;
protected IScenarioMotionReciver scenarioMotionReciver;
IManipulator manipulator;
public ActionScenario() {
}
public ActionScenario(int grad, IScenario scenario, IScenarioMotionReciver motionsReciver) {
this.grad = grad;
this.scenario = scenario;
this.scenarioMotionReciver = motionsReciver;
}
public void setManipulator(IManipulator manipulator) {
this.manipulator = manipulator;
}
public static IAction Blank() {
return new ActionScenario() {
public void Abort(IArgument[] arg_) {
throw new UnsupportedOperationException("Not supported yet.");
}
public void Do(IArgument[] arg_) {
throw new UnsupportedOperationException("Not supported yet.");
}
public void Move(IArgument[] arg_) {
throw new UnsupportedOperationException("Not supported yet.");
}
public void Select(IArgument[] arg_) {
throw new UnsupportedOperationException("Not supported yet.");
}
public void Selecting(IArgument[] arg_) {
throw new UnsupportedOperationException("Not supported yet.");
}
};
}
}
| true |
aa1907f37a49a6e64de151508e7179ed81880052 | Java | mahmud83/KalkulatorFaroidh | /app/src/main/java/com/example/nikkoekasaputra/kalkulatorfaroid/Detail.java | UTF-8 | 5,574 | 2.015625 | 2 | [] | no_license | package com.example.nikkoekasaputra.kalkulatorfaroid;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
public class Detail extends Activity {
String sNama, sJK, sHarta, sHutang, sPengurusan, sWasiat, sTotal,
sAnakLakilaki, sAnakPerempuan, sSuami, sIstri, sAyah,
sIbu, sKakek, sNenek, sSaudaraKandung, sSaudariKandung;
protected Cursor cursor;
DataHelper dbHelper;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
dbHelper = new DataHelper(this);
SQLiteDatabase db = dbHelper.getReadableDatabase();
cursor = db.rawQuery("select * from data_pewaris, data_ahli_waris where data_pewaris.nama_pewaris = data_ahli_waris.nama_pewaris AND data_pewaris.nama_pewaris = '"+getIntent().getStringExtra("nama_pewaris")+"'", null);
cursor.moveToFirst();
if(cursor.getCount()>0){
cursor.moveToPosition(0);
sNama = cursor.getString(0).toString();
sJK = cursor.getString(1).toString();
sHarta = cursor.getString(2).toString();
sHutang = cursor.getString(3).toString();
sPengurusan = cursor.getString(4).toString();
sWasiat = cursor.getString(5).toString();
sTotal = cursor.getString(6).toString();
sAnakLakilaki = cursor.getString(8).toString();
sAnakPerempuan = cursor.getString(9).toString();
sSuami = cursor.getString(10).toString();
sIstri = cursor.getString(11).toString();
sAyah = cursor.getString(12).toString();
sIbu = cursor.getString(13).toString();
sKakek = cursor.getString(14).toString();
sNenek = cursor.getString(15).toString();
sSaudaraKandung = cursor.getString(16).toString();
sSaudariKandung = cursor.getString(17).toString();
}
//default jika data ahli waris bernilai 0, maka tidak ditampilkan
//awal state
if (sAnakLakilaki.equals("Rp. 0")) {
LinearLayout GAnakLakilaki = (LinearLayout) findViewById(R.id.GAnakLakilaki);
GAnakLakilaki.setVisibility(View.GONE);
}
if (sAnakPerempuan.equals("Rp. 0")) {
LinearLayout GAnakPerempuan = (LinearLayout) findViewById(R.id.GAnakPerempuan);
GAnakPerempuan.setVisibility(View.GONE);
}
if (sSuami.equals("Rp. 0")) {
LinearLayout GSuami = (LinearLayout) findViewById(R.id.GSuami);
GSuami.setVisibility(View.GONE);
}
if (sIstri.equals("Rp. 0")) {
LinearLayout GIstri = (LinearLayout) findViewById(R.id.GIstri);
GIstri.setVisibility(View.GONE);
}
if (sAyah.equals("Rp. 0")) {
LinearLayout GAyah = (LinearLayout) findViewById(R.id.GAyah);
GAyah.setVisibility(View.GONE);
}
if (sIbu.equals("Rp. 0")) {
LinearLayout GIbu = (LinearLayout) findViewById(R.id.GIbu);
GIbu.setVisibility(View.GONE);
}
if (sKakek.equals("Rp. 0")) {
LinearLayout GKakek = (LinearLayout) findViewById(R.id.GKakek);
GKakek.setVisibility(View.GONE);
}
if (sNenek.equals("Rp. 0")) {
LinearLayout GNenek = (LinearLayout) findViewById(R.id.GNenek);
GNenek.setVisibility(View.GONE);
}
if (sSaudaraKandung.equals("Rp. 0")) {
LinearLayout GSaudaraKandung = (LinearLayout) findViewById(R.id.GSaudaraKandung);
GSaudaraKandung.setVisibility(View.GONE);
}
if (sSaudariKandung.equals("Rp. 0")) {
LinearLayout GSaudariKandung = (LinearLayout) findViewById(R.id.GSaudariKandung);
GSaudariKandung.setVisibility(View.GONE);
}
//akhir state
// ---------------------------
TextView tvNama = (TextView) findViewById(R.id.showNama);
TextView tvJK = (TextView) findViewById(R.id.showJK);
TextView tvHarta = (TextView) findViewById(R.id.RpJumlah);
TextView tvHutang = (TextView) findViewById(R.id.RpHutang);
TextView tvPengurusanJenazah = (TextView) findViewById(R.id.RpPengurusanJenazah);
TextView tvWasiat = (TextView) findViewById(R.id.RpWasiat);
TextView tvJumlah = (TextView) findViewById(R.id.RpTotal);
TextView AnakLakilaki1 = (TextView) findViewById(R.id.AnakLakilaki1);
TextView AnakPerempuan1 = (TextView) findViewById(R.id.AnakPerempuan1);
TextView Suami1 = (TextView) findViewById(R.id.Suami1);
TextView Istri1 = (TextView) findViewById(R.id.Istri1);
TextView Ayah1 = (TextView) findViewById(R.id.Ayah1);
TextView Ibu1 = (TextView) findViewById(R.id.Ibu1);
TextView Kakek1 = (TextView) findViewById(R.id.Kakek1);
TextView Nenek1 = (TextView) findViewById(R.id.Nenek1);
TextView SaudaraKandung1 = (TextView) findViewById(R.id.SaudaraKandung1);
TextView SaudariKandung1 = (TextView) findViewById(R.id.SaudariKandung1);
//memasukkan nilai ke textview
tvNama.setText(sNama);
tvJK.setText(sJK);
tvHarta.setText(sHarta);
tvHutang.setText(sHutang);
tvPengurusanJenazah.setText(sPengurusan);
tvWasiat.setText(sWasiat);
tvJumlah.setText(sTotal);
AnakLakilaki1.setText(sAnakLakilaki);
AnakPerempuan1.setText(sAnakPerempuan);
Suami1.setText(sSuami);
Istri1.setText(sIstri);
Ayah1.setText(sAyah);
Ibu1.setText(sIbu);
Kakek1.setText(sKakek);
Nenek1.setText(sNenek);
SaudaraKandung1.setText(sSaudaraKandung);
SaudariKandung1.setText(sSaudariKandung);
ImageButton btnback = (ImageButton) findViewById(R.id.back);
btnback.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
}
private int harta(int i) {
// TODO Auto-generated method stub
return 0;
}
}
| true |
4788789a12ba565f6da68390a0e86c0f5fc0e3ad | Java | RickHuisman/ChatApp | /app/src/main/java/com/example/rickh/chatapp/fragments/ContactsTabFragment.java | UTF-8 | 5,027 | 2.015625 | 2 | [] | no_license | package com.example.rickh.chatapp.fragments;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.constraint.ConstraintLayout;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.rickh.chatapp.R;
import com.example.rickh.chatapp.activities.FriendRequestsActivity;
import com.example.rickh.chatapp.adapters.ContactsListAdapter;
import com.example.rickh.chatapp.models.User;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.firestore.CollectionReference;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.EventListener;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.FirebaseFirestoreException;
import com.google.firebase.firestore.QuerySnapshot;
import com.simplecityapps.recyclerview_fastscroll.views.FastScrollRecyclerView;
import java.util.ArrayList;
public class ContactsTabFragment extends Fragment {
private View mView;
private ContactsListAdapter mAdapter;
private FastScrollRecyclerView mContactsList;
private ConstraintLayout mFriendsRequestsContainer;
private ArrayList<User> mListContacts;
public ContactsTabFragment() {
}
public static ContactsTabFragment newInstance() {
return new ContactsTabFragment();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mView = inflater.inflate(R.layout.fragment_contacts_tab, container, false);
mContactsList = mView.findViewById(R.id.contacts_list);
mFriendsRequestsContainer = mView.findViewById(R.id.friend_requests_container);
mFriendsRequestsContainer.setOnClickListener(friendsRequestsClick);
final FirebaseFirestore db = FirebaseFirestore.getInstance();
final String mCurrentUser = FirebaseAuth.getInstance().getCurrentUser().getUid();
final CollectionReference contactsRef = db.collection("users").document(mCurrentUser).collection("friends");
contactsRef.addSnapshotListener(new EventListener<QuerySnapshot>() {
@Override
public void onEvent(@javax.annotation.Nullable QuerySnapshot queryDocumentSnapshots, @javax.annotation.Nullable FirebaseFirestoreException e) {
if (e != null) {
System.out.println("Listen failed. " + e);
return;
}
mListContacts = new ArrayList<>();
if (queryDocumentSnapshots != null && !queryDocumentSnapshots.isEmpty()) {
for (DocumentSnapshot document: queryDocumentSnapshots) {
String contactUid = document.get("userUid").toString();
db
.collection("users")
.document(contactUid)
.get()
.addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
String username = (String) task.getResult().get("username");
String imageDownloadUrl = (String) task.getResult().get("downloadUrl");
String userUid = (String) task.getResult().get("userUid");
if (!userUid.equals(mCurrentUser))
mListContacts.add(new User(imageDownloadUrl, username, userUid, false, false, false));
setUpAdapter(mListContacts);
}
});
}
} else {
setUpAdapter(mListContacts);
}
}
});
return mView;
}
View.OnClickListener friendsRequestsClick = new View.OnClickListener() {
@Override
public void onClick(View view) {
startActivity(new Intent(getContext(), FriendRequestsActivity.class));
}
};
private void setUpAdapter(ArrayList<User> userList) {
if (!userList.isEmpty()) {
mAdapter = new ContactsListAdapter(getContext(), userList);
mContactsList.setLayoutManager(new LinearLayoutManager(getContext()));
mContactsList.setAdapter(mAdapter);
}
}
}
| true |
d8ed84a0a4347b8fd2e73a1a9828cb1805cd496d | Java | MicroFocus/sv-configurator | /src/main/java/com/microfocus/sv/svconfigurator/processor/DeployProcessor.java | UTF-8 | 4,976 | 1.640625 | 2 | [
"MIT"
] | permissive | /*
* Certain versions of software and/or documents ("Material") accessible here may contain branding from
* Hewlett-Packard Company (now HP Inc.) and Hewlett Packard Enterprise Company. As of September 1, 2017,
* the Material is now offered by Micro Focus, a separately owned and operated company. Any reference to the HP
* and Hewlett Packard Enterprise/HPE marks is historical in nature, and the HP and Hewlett Packard Enterprise/HPE
* marks are the property of their respective owners.
* __________________________________________________________________
* MIT License
*
* Copyright (c) 2012-2022 Micro Focus or one of its affiliates.
*
* The only warranties for products and services of Micro Focus and its affiliates
* and licensors ("Micro Focus") are set forth in the express warranty statements
* accompanying such products and services. Nothing herein should be construed as
* constituting an additional warranty. Micro Focus shall not be liable for technical
* or editorial errors or omissions contained herein.
* The information contained herein is subject to change without notice.
* __________________________________________________________________
*
*/
package com.microfocus.sv.svconfigurator.processor;
import java.util.ArrayList;
import java.util.List;
import com.microfocus.sv.svconfigurator.core.impl.jaxb.AgentConfigurations;
import com.microfocus.sv.svconfigurator.service.ServiceAmendingServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.microfocus.sv.svconfigurator.core.IProject;
import com.microfocus.sv.svconfigurator.core.IService;
import com.microfocus.sv.svconfigurator.core.impl.exception.CommandExecutorException;
import com.microfocus.sv.svconfigurator.core.impl.exception.CommunicatorException;
import com.microfocus.sv.svconfigurator.serverclient.ICommandExecutor;
import com.microfocus.sv.svconfigurator.serverclient.ICommandExecutorFactory;
import com.microfocus.sv.svconfigurator.util.ProjectUtils;
public class DeployProcessor implements IDeployProcessor {
private static final Logger LOG = LoggerFactory.getLogger(DeployProcessor.class);
private final ICommandExecutorFactory commandExecutorFactory;
public DeployProcessor(ICommandExecutorFactory commandExecutorFactory) {
this.commandExecutorFactory = commandExecutorFactory;
}
@Override
public ICommandExecutorFactory getCommandExecutorFactory() {
return commandExecutorFactory;
}
@Override
public void process(DeployProcessorInput input, ICommandExecutor exec) throws CommunicatorException, CommandExecutorException {
IProject proj = input.getProject();
if (proj == null) {
throw new CommandExecutorException("You have to specify the project.");
}
exec.setForce(input.isForce());
IService svc = ProjectUtils.findProjElem(proj.getServices(), input.getService(), ProjectUtils.ENTITY_VIRTUAL_SERVICE);
if (input.isUndeploy()) {
this.undeploy(proj, exec, svc);
} else {
deploy(proj, exec, svc, input);
}
}
private void deploy(IProject proj, ICommandExecutor exec, IService service, DeployProcessorInput input) throws CommunicatorException, CommandExecutorException {
List<IService> services = new ArrayList<IService>();
if (service == null) {
for (IService svc : proj.getServices()) {
services.add(svc);
}
} else {
services.add(service);
}
List<IService> updatedServices = updateAndValidateServiceAgents(exec, input, services);
for (IService svc : updatedServices) {
exec.deployService(svc, proj.getProjectPassword(), input.isImportLoggedMessages());
}
if (service == null) {
LOG.info(proj + " successfully deployed.");
}
}
private List<IService> updateAndValidateServiceAgents(ICommandExecutor exec, DeployProcessorInput input, List<IService> services) throws CommunicatorException, CommandExecutorException {
AgentConfigurations agentConfigurations = exec.getAgents();
ServiceAmendingServiceImpl serviceAmendingService = new ServiceAmendingServiceImpl(agentConfigurations, services);
if (input.isAgentRemappingRequired()) {
serviceAmendingService.remapAgents(input.getAgentRemapping());
}
serviceAmendingService.remapAgentsByNames();
if (input.isFirstAgentFailover()) {
serviceAmendingService.agentFallback();
}
serviceAmendingService.verifyAndSetNames();
return serviceAmendingService.applyAgentChanges();
}
private void undeploy(IProject proj, ICommandExecutor exec, IService svc) throws CommunicatorException, CommandExecutorException {
if (svc == null) {
exec.undeploy(proj);
} else {
exec.undeployService(svc);
}
}
}
| true |
63d96dab598ce4ad8c40c948e938ae708fcc2874 | Java | Youhoseong/verpic-backend | /src/main/java/teamverpic/verpicbackend/domain/preview/dao/DetailTopicRepository.java | UTF-8 | 341 | 1.734375 | 2 | [] | no_license | package teamverpic.verpicbackend.domain.preview.dao;
import org.springframework.data.jpa.repository.JpaRepository;
import teamverpic.verpicbackend.domain.preview.domain.DetailTopic;
import java.util.List;
public interface DetailTopicRepository extends JpaRepository<DetailTopic, Long> {
List<DetailTopic> findByPreviewId(Long id);
}
| true |
4d67051154f4e32de2a7dbb357dddf756032b783 | Java | gwmccort/examples | /java-examples/src/main/java/com/lordofthejars/main/Main.java | UTF-8 | 480 | 2.453125 | 2 | [] | no_license | package com.lordofthejars.main;
import com.lordofthejars.bar.BarComponent;
import com.lordofthejars.foo.FooComponent;
/**
* sl4j example <br>
* from: http://www.javacodegeeks.com/2012/04/using-slf4j-with-logback-tutorial.html
*
* @author Glen
*
*/
public class Main {
public static void main(String args[]) {
BarComponent barComponent = new BarComponent();
barComponent.bar();
FooComponent fooComponent = new FooComponent();
fooComponent.foo();
}
}
| true |
6569cfeadec3b66bc0d5713a7876b71446becd05 | Java | Alexandr1246/ONPU_CalculatorFX_Demo | /src/main/java/com/example/calculatorfx_212/CalculatorApplication.java | UTF-8 | 858 | 2.53125 | 3 | [] | no_license | package com.example.calculatorfx_212;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.stage.Stage;
import java.io.IOException;
public class CalculatorApplication extends Application {
public static Calculator calculator;
@Override
public void start(Stage stage) throws IOException {
FXMLLoader fxmlLoader = new FXMLLoader(CalculatorApplication.class.getResource("hello-view.fxml"));
Scene scene = new Scene(fxmlLoader.load(), 300, 400);
stage.setTitle("CalculatorFX");
stage.getIcons().add(new Image("https://www.iconsdb.com/icons/preview/green/calculator-xxl.png"));
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
calculator = new Calculator();
launch();
}
} | true |
b4a98ba418265851c81ce8e5336d6818d853d40c | Java | hasanain/euler | /notdone/Euler146.java | UTF-8 | 574 | 3.28125 | 3 | [] | no_license | import java.util.Date;
/*
Project Euler Problem 146
=========================
The smallest positive integer n for which the numbers n^2+1, n^2+3, n^2+7,
n^2+9, n^2+13, and n^2+27 are consecutive primes is 10. The sum of all
such integers n below one-million is 1242490.
What is the sum of all such integers n below 150 million?
*/
public class Euler146 {
public static void main(String[] args) {
Date start, end;
start = new Date();
end = new Date();
System.out.println("Execution Time: " + (end.getTime() -start.getTime()));
}
}
| true |
fe4380e5b95593be6fcb9d5ede406b6f48ceb362 | Java | leeshi/RandomPoetry | /app/src/main/java/com/lishi/adruino/randompoetry/model/OnLoadListener.java | UTF-8 | 190 | 1.617188 | 2 | [] | no_license | package com.lishi.adruino.randompoetry.model;
public interface OnLoadListener {
void loadSuccess(Object data);
void loadFailed();
void loadOver();
Object getLoadOption();
}
| true |
d1f1a3cdec59fd8264c3ac0af4ac3e98e067710d | Java | Aidenat9/AdvancedAndroid | /advanceandroid/src/main/java/com/github/tianmu19/advanceandroid/mvp/model/entity/wanandroid/TreeBean.java | UTF-8 | 871 | 2.234375 | 2 | [] | no_license | package com.github.tianmu19.advanceandroid.mvp.model.entity.wanandroid;
import java.util.ArrayList;
import java.util.List;
/**
* @author jingbin
* @data 2018/9/15
* @description
*/
public class TreeBean {
private int errorCode;
private String errorMsg;
private List<TreeItemBean> data;
public int getErrorCode() {
return errorCode;
}
public void setErrorCode(int errorCode) {
this.errorCode = errorCode;
}
public String getErrorMsg() {
return errorMsg == null ? "" : errorMsg;
}
public void setErrorMsg(String errorMsg) {
this.errorMsg = errorMsg;
}
public List<TreeItemBean> getData() {
if (data == null) {
return new ArrayList<>();
}
return data;
}
public void setData(List<TreeItemBean> data) {
this.data = data;
}
}
| true |
616ad5a9a1de65efe3bc3732fd65683ddd3e3f40 | Java | kkiruban/CSharpProjects | /webdriver/Testng/sfdc-WebdriverNormal/src/BasicWebdriverCommands/basicWebdriverCommands.java | UTF-8 | 5,606 | 2.359375 | 2 | [] | no_license | package BasicWebdriverCommands;
import org.testng.annotations.Test;
import org.testng.annotations.BeforeMethod;
import java.util.Iterator;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
public class basicWebdriverCommands {
public static WebDriver driver;
@BeforeMethod
public void beforeMethod() throws InterruptedException {
// to launch a firefox browser
System.setProperty("webdriver.chrome.driver", "C:\\Ruby22-x64\\bin\\chromedriver.exe");
driver = new ChromeDriver();
// naviagte to salesforce url
driver.get("https://test.salesforce.com/");
// implicit wait method
driver.manage().timeouts().implicitlyWait(40, TimeUnit.SECONDS);
// selenium command to maximize the browser
driver.manage().window().maximize();
// to pass username in text box
driver.findElement(By.id("username")).sendKeys("dsintegration-admin@servicesource.com.sitnxtqlik");
// to pass username in text box
driver.findElement(By.id("password")).sendKeys("srevds123!");
// to perform click action on login button
driver.findElement(By.name("Login")).click();
// implicit wait
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
}
@Test
public void createaccount() {
System.out.println(driver.getCurrentUrl());
driver.findElement(By.xpath("//a[@title='Accounts Tab']")).click();
// get title
String actualtitle=driver.getTitle();
String expectedtitle="Accounts: Home ~ Salesforce - Performance Edition";
if(actualtitle.equalsIgnoreCase(expectedtitle)){
System.out.println("title has expected");
}else{
System.out.println("title has not expected");
}
// explict wait
WebDriverWait wait = new WebDriverWait(driver, 20);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.name("new")));
driver.findElement(By.name("new")).click();
Random rand = new Random();
int randint = rand.nextInt(1000);
String randomaccount = "smoke-test-account-" + String.valueOf(randint);
driver.findElement(By.id("acc2")).sendKeys(randomaccount);
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.findElement(By.xpath(".//*[@id='acc3_lkwgt']/img")).click();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
// handling frames and windows
Set<String> set = driver.getWindowHandles();
Iterator<String> it = set.iterator();
String parentwindow = it.next();
String childwindow = it.next();
driver.switchTo().window(childwindow);
driver.switchTo().frame("searchFrame");
wait.until(ExpectedConditions.visibilityOfElementLocated(By.name("lksrch")));
driver.findElement(By.xpath(".//*[@id='lksrch']")).sendKeys("smoke-test");
driver.findElement(By.name("go")).click();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.switchTo().defaultContent();
driver.switchTo().frame("resultsFrame");
driver.findElement(By.linkText("smoke-test-account-123")).click();
// driver.switchTo().defaultContent();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.switchTo().window(parentwindow);
driver.findElement(By.id("acc5")).sendKeys("112");
driver.manage().timeouts().implicitlyWait(40, TimeUnit.SECONDS);
driver.findElement(By.name("save")).click();
driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
}
@Test
public void createContact() {
System.out.println(driver.getCurrentUrl());
driver.findElement(By.xpath("//a[@title='Contacts Tab']")).click();
// get title
String actualtitle=driver.getTitle();
String expectedtitle="Contacts: Home ~ Salesforce - Performance Edition";
Assert.assertEquals(actualtitle, expectedtitle);
// explict wait
WebDriverWait wait = new WebDriverWait(driver, 20);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.name("new")));
driver.findElement(By.name("new")).click();
Random rand = new Random();
int randint = rand.nextInt(1000);
String randomcontact = "smoke-test-contact-" + String.valueOf(randint);
driver.findElement(By.id("name_lastcon2")).sendKeys(randomcontact);
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.findElement(By.xpath(".//*[@id='con4_lkwgt']/img")).click();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
// handling frames and windows
Set<String> set = driver.getWindowHandles();
Iterator<String> it = set.iterator();
String parentwindow = it.next();
String childwindow = it.next();
driver.switchTo().window(childwindow);
driver.switchTo().frame("searchFrame");
wait.until(ExpectedConditions.visibilityOfElementLocated(By.name("lksrch")));
driver.findElement(By.xpath(".//*[@id='lksrch']")).sendKeys("smoke-test");
driver.findElement(By.name("go")).click();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.switchTo().defaultContent();
driver.switchTo().frame("resultsFrame");
driver.findElement(By.linkText("smoke-test-account-123")).click();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.switchTo().window(parentwindow);
driver.manage().timeouts().implicitlyWait(40, TimeUnit.SECONDS);
driver.findElement(By.name("save")).click();
}
@AfterMethod
public void afterMethod() {
driver.quit();
}
}
| true |
8d6dab2fd8747012aa950362751c4127796c1261 | Java | laidayuan/SmartMvp | /marsframework/src/main/java/com/dada/marsframework/monitor/ActivityMonitor.java | UTF-8 | 4,924 | 2.140625 | 2 | [] | no_license | package com.dada.marsframework.monitor;
import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.v4.content.LocalBroadcastManager;
import com.dada.marsframework.utils.LogUtils;
import java.lang.ref.WeakReference;
import java.util.HashMap;
/**
* Created by laidayuan on 2018/10/22.
*/
public class ActivityMonitor implements Application.ActivityLifecycleCallbacks {
private static ActivityMonitor sInstance;
private boolean mIsFrameMonitor = false;
private Handler mHandler = new Handler(Looper.getMainLooper());
private boolean mPaused = true;
private Runnable mCheckForegroundRunnable;
private boolean mForeground = false;
//当前Activity的弱引用
private WeakReference<Activity> mActivityReference;
protected final String TAG = "MyActivityLifeCycle";
public static final int ACTIVITY_ON_RESUME = 0;
public static final int ACTIVITY_ON_PAUSE = 1;
private ActivityMonitor() {
}
public static ActivityMonitor getInstance() {
if (sInstance==null) {
synchronized(ActivityMonitor.class) {
if (sInstance==null) {
sInstance = new ActivityMonitor();
}
}
}
return sInstance;
}
public void enableFrameMonitor(boolean enable) {
mIsFrameMonitor = enable;
}
public Activity getCurrentActivity() {
if (mActivityReference != null) {
return mActivityReference.get();
}
return null;
}
public boolean isForground() {
return mForeground;
}
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
LogUtils.d(TAG, activity.getLocalClassName() + " " + "onActivityCreated");
mActivityReference = new WeakReference<Activity>(activity);
}
@Override
public void onActivityStarted(Activity activity) {
LogUtils.d(TAG, activity.getLocalClassName() + " " + "onActivityStarted");
}
@Override
public void onActivityResumed(Activity activity) {
String activityName = activity.getClass().getName();
notifyActivityChanged(activity, activityName, ACTIVITY_ON_RESUME);
mPaused = false;
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN && mIsFrameMonitor
/*&& ConfigManager.getInstance().isFrameSkipCheckOn()*//*配置是否开启统计*/) {
FrameSkipMonitor.getInstance().setActivityName(activityName);
FrameSkipMonitor.getInstance().onActivityResume();
if (!mForeground) {
FrameSkipMonitor.getInstance().start();
}
}
mForeground = true;
if (mCheckForegroundRunnable != null) {
mHandler.removeCallbacks(mCheckForegroundRunnable);
}
mActivityReference = new WeakReference<Activity>(activity);
}
@Override
public void onActivityPaused(Activity activity) {//pause事件后是否在前台要分情况判断
notifyActivityChanged(activity, activity.getClass().getName(), ACTIVITY_ON_PAUSE);
mPaused = true;
if (mCheckForegroundRunnable != null) {
mHandler.removeCallbacks(mCheckForegroundRunnable);
}
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN)
FrameSkipMonitor.getInstance().onActivityPause();
mHandler.postDelayed(mCheckForegroundRunnable = new Runnable() {
@Override
public void run() {
if (mPaused && mForeground) {
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN && mIsFrameMonitor
/*&& ConfigManager.getInstance().isFrameSkipCheckOn()*//*配置是否开启统计*/) {
FrameSkipMonitor.getInstance().report();
}
mForeground = false;
}
}
}, 1000);
}
@Override
public void onActivityStopped(Activity activity) {
LogUtils.d(TAG, activity.getLocalClassName() + " " + "onActivityStopped");
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
}
@Override
public void onActivityDestroyed(Activity activity) {
LogUtils.d(TAG, activity.getLocalClassName() + " " + "onActivityDestroyed");
}
private void notifyActivityChanged(Context context, String activityName, int lifeState) {
Intent intent = new Intent("com.dada.android.activity_change");
intent.putExtra("activity_name", activityName);
intent.putExtra("activity_life", lifeState);
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
}
}
| true |
5cb4b6d388b69b6b659dcdfe37c3d64af9a85cf3 | Java | andreronquetti/sneer | /code/src/sneer/bricks/network/computers/addresses/sighting/impl/SightingPublisherImpl.java | UTF-8 | 1,189 | 2.1875 | 2 | [] | no_license | package sneer.bricks.network.computers.addresses.sighting.impl;
import static sneer.foundation.environments.Environments.my;
import sneer.bricks.expression.tuples.TupleSpace;
import sneer.bricks.hardware.cpu.lang.contracts.WeakContract;
import sneer.bricks.identity.seals.Seal;
import sneer.bricks.network.computers.addresses.sighting.Sighting;
import sneer.bricks.network.computers.addresses.sighting.SightingPublisher;
import sneer.bricks.network.computers.sockets.connections.ConnectionManager;
import sneer.bricks.network.computers.sockets.connections.ContactSighting;
import sneer.foundation.lang.Consumer;
class SightingPublisherImpl implements SightingPublisher {
private final ConnectionManager connectionManager = my(ConnectionManager.class);
{
my(TupleSpace.class).keep(Sighting.class);
}
@SuppressWarnings("unused")
private final WeakContract _refToAvoidGc = connectionManager.contactSightings().addReceiver(new Consumer<ContactSighting>() { @Override public void consume(ContactSighting sighting) {
sighted(sighting.seal(), sighting.ip());
}});
private void sighted(Seal seal, String ip) {
my(TupleSpace.class).acquire(new Sighting(seal, ip));
}
}
| true |
a8f71fcce22eb7d450d9b0bd57d12e30154889ba | Java | jzt-Tesla/BloodPressureDiary | /app/src/main/java/de/asteromania/groehl/bloodpressurediary/views/AddDataItemActivity.java | UTF-8 | 6,971 | 2.203125 | 2 | [] | no_license | package de.asteromania.groehl.bloodpressurediary.views;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.NumberPicker;
import android.widget.TextView;
import android.widget.TimePicker;
import java.util.Calendar;
import java.util.Collection;
import de.asteromania.groehl.bloodpressurediary.R;
import de.asteromania.groehl.bloodpressurediary.database.DatabaseService;
import de.asteromania.groehl.bloodpressurediary.domain.DataItem;
import de.asteromania.groehl.bloodpressurediary.domain.DataItemType;
public class AddDataItemActivity extends AppCompatActivity {
public static final String EXTRA = "de.asteromania.groehl.bloodpressurediary.AddDataItemActivity.EXTRA";
private static final int MAX_NUMBER_VALUE = 299;
private static final int MIN_NUMBER_VALUE = 1;
private static final int NUMBER_VALUE = 100;
private static final int MAX_DECIMAL_VALUE = 9;
private static final int MIN_DECIMAL_VALUE = 0;
private static final int DECIMAL_VALUE = 0;
private static final int MAX_BP_VALUE = 499;
private static final int MIN_BP_VALUE = 0;
private static final int BP_SYS_VALUE = 128;
private static final int BP_DIA_VALUE = 72;
private DatabaseService databaseService;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
databaseService = new DatabaseService(this);
String extraString = getIntent().getStringExtra(EXTRA);
DataItemType currentType = DataItemType.valueOf(extraString);
if (currentType == null) {
finish();
}
setContentView(currentType.getAddItemView());
TextView titleView = (TextView) findViewById(R.id.textViewAddTitle);
Button buttonAdd = (Button) findViewById(R.id.buttonAdd);
switch(currentType)
{
case SYSTOLE:
case DIASTOLE:
DataItem systole = new DataItem(DataItemType.SYSTOLE, BP_SYS_VALUE, 0);
Collection<? extends DataItem> collectionSystole = databaseService.getDataItemDatabaseAccess().getLastNItemsByType(1, DataItemType.SYSTOLE);
if(collectionSystole!=null && !collectionSystole.isEmpty())
systole = (DataItem) collectionSystole.toArray()[0];
DataItem diastole = new DataItem(DataItemType.DIASTOLE, BP_DIA_VALUE, 0);
Collection<? extends DataItem> collectionDiastole = databaseService.getDataItemDatabaseAccess().getLastNItemsByType(1, DataItemType.DIASTOLE);
if(collectionDiastole!=null && !collectionDiastole.isEmpty())
diastole = (DataItem) collectionDiastole.toArray()[0];
titleView.setText(String.format(getString(R.string.addValue), getString(R.string.dataTypeBloodPressure)));
final NumberPicker npSystole = (NumberPicker) findViewById(R.id.numberPickerSystole);
npSystole.setMaxValue(MAX_BP_VALUE);
npSystole.setMinValue(MIN_BP_VALUE);
npSystole.setValue((int) systole.getValue());
final NumberPicker npDiastole = (NumberPicker) findViewById(R.id.numberPickerDiastole);
npDiastole.setMaxValue(MAX_BP_VALUE);
npDiastole.setMinValue(MIN_BP_VALUE);
npDiastole.setValue((int) diastole.getValue());
TextView unit = (TextView) findViewById(R.id.textViewUnitSystole);
if(systole !=null && systole.getItemType()!=null)
unit.setText(systole.getItemType().getUnitString());
buttonAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
databaseService.getDataItemDatabaseAccess().addItem(new DataItem(DataItemType.SYSTOLE, npSystole.getValue(), getCurrentTime()));
databaseService.getDataItemDatabaseAccess().addItem(new DataItem(DataItemType.DIASTOLE, npDiastole.getValue(), getCurrentTime()));
finish();
}
});
break;
default:
DataItem item = new DataItem(currentType, NUMBER_VALUE, 0);
Collection<? extends DataItem> collection = databaseService.getDataItemDatabaseAccess().getLastNItemsByType(1, currentType);
if(collection!=null && !collection.isEmpty())
item = (DataItem) collection.toArray()[0];
final NumberPicker npNumber = (NumberPicker) findViewById(R.id.numberPickerNumber);
npNumber.setMaxValue(MAX_NUMBER_VALUE);
npNumber.setMinValue(MIN_NUMBER_VALUE);
npNumber.setValue((int) item.getValue());
final NumberPicker npDecimal = (NumberPicker) findViewById(R.id.numberPickerDecimal);
npDecimal.setMaxValue(MAX_DECIMAL_VALUE);
npDecimal.setMinValue(MIN_DECIMAL_VALUE);
if (item != null)
npDecimal.setValue((int) ((item.getValue()*10)%10));
else
npDecimal.setValue(DECIMAL_VALUE);
if(item !=null && item.getItemType()!=null)
titleView.setText(String.format(getString(R.string.addValue), getString(item.getItemType().getText())));
TextView unitNormal = (TextView) findViewById(R.id.textViewUnit);
if(item !=null && item.getItemType()!=null)
unitNormal.setText(item.getItemType().getUnitString());
final DataItem buttonItem = item;
buttonAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(buttonItem !=null && buttonItem.getItemType()!=null)
databaseService.getDataItemDatabaseAccess().addItem(new DataItem(buttonItem.getItemType(), (npNumber.getValue()+(npDecimal.getValue()/10.0)), getCurrentTime()));
finish();
}
});
break;
}
TimePicker tp = (TimePicker) findViewById(R.id.timePicker);
tp.setIs24HourView(true);
}
private long getCurrentTime() {
TimePicker timePicker = (TimePicker) findViewById(R.id.timePicker);
DatePicker datePicker = (DatePicker) findViewById(R.id.datePicker);
int month = datePicker.getMonth();
int day = datePicker.getDayOfMonth();
int year = datePicker.getYear();
int hour = timePicker.getCurrentHour();
int minute = timePicker.getCurrentMinute();
Calendar c = Calendar.getInstance();
c.set(year, month, day, hour, minute);
return c.getTimeInMillis();
}
} | true |
4e46beb02026d7fa41db7c5705a35e79e853d89f | Java | Kaiserlucas/Kniffel | /test/kniffel/protocolBinding/StreamBindingReceiverTests.java | UTF-8 | 4,160 | 2.8125 | 3 | [] | no_license | package kniffel.protocolBinding;
import dummyImplementations.KniffelReceiverDummy;
import kniffel.data.ScoreTableRows;
import org.junit.Test;
import java.io.*;
public class StreamBindingReceiverTests {
@Test
public void receiveDiceRollTest() throws InterruptedException, IOException {
//Create an InputStream with the arguments needed for the command
int playerID = 1;
int[] exampleDiceValues = new int[] {1, 2, 3, 4, 5};
//Create ByteArrayOutputStream with the arguments required for the command to pass to the DataInputStream
ByteArrayOutputStream os = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(os);
dos.writeInt(Commands.ROLL_DICE);
for(int diceValue : exampleDiceValues) {
dos.writeInt(diceValue);
}
dos.writeInt(playerID);
InputStream is = new ByteArrayInputStream(os.toByteArray());
DataInputStream dis = new DataInputStream(is);
//Set up receiver
KniffelReceiverDummy engine = new KniffelReceiverDummy();
StreamBindingReceiver receiver = new StreamBindingReceiver(dis, engine);
receiver.start();
receiver.join();
assert(engine.isRollDiceReceived());
}
@Test
public void receiveEndTurnTest() throws InterruptedException, IOException {
//Create an InputStream with the arguments needed for the command
int playerID = 1;
int score = 20;
//Create ByteArrayOutputStream with the arguments required for the command to pass to the DataInputStream
ByteArrayOutputStream os = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(os);
dos.writeInt(Commands.END_TURN);
dos.writeInt(ScoreTableRows.CHANCE);
dos.writeInt(score);
dos.writeInt(playerID);
InputStream is = new ByteArrayInputStream(os.toByteArray());
DataInputStream dis = new DataInputStream(is);
//Set up receiver
KniffelReceiverDummy engine = new KniffelReceiverDummy();
StreamBindingReceiver receiver = new StreamBindingReceiver(dis, engine);
receiver.start();
receiver.join();
assert(engine.isEndTurnReceived());
}
@Test
public void receiveChangeDiceStateTest() throws InterruptedException, IOException {
//Create an InputStream with the arguments needed for the command
int playerID = 1;
int diceIndex = 1;
//Create ByteArrayOutputStream with the arguments required for the command to pass to the DataInputStream
ByteArrayOutputStream os = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(os);
dos.writeInt(Commands.CHANGE_DICE_STATE);
dos.writeInt(diceIndex);
dos.writeInt(playerID);
InputStream is = new ByteArrayInputStream(os.toByteArray());
DataInputStream dis = new DataInputStream(is);
//Set up receiver
KniffelReceiverDummy engine = new KniffelReceiverDummy();
StreamBindingReceiver receiver = new StreamBindingReceiver(dis, engine);
receiver.start();
receiver.join();
assert(engine.isChangeDiceStateReceived());
}
@Test
public void receiveEndGameTest() throws InterruptedException, IOException {
//Create an InputStream with the arguments needed for the command
int playerID = 1;
//Create ByteArrayOutputStream with the arguments required for the command to pass to the DataInputStream
ByteArrayOutputStream os = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(os);
dos.writeInt(Commands.END_GAME);
dos.writeInt(playerID);
InputStream is = new ByteArrayInputStream(os.toByteArray());
DataInputStream dis = new DataInputStream(is);
//Set up receiver
KniffelReceiverDummy engine = new KniffelReceiverDummy();
StreamBindingReceiver receiver = new StreamBindingReceiver(dis, engine);
receiver.start();
receiver.join();
assert(engine.isSaveGameReceived());
}
}
| true |
7420a57a43ad21e084c2c396957113a624018b24 | Java | FrankDeGroot/wiremock-demo | /src/main/java/fjtdg/demo/response_template/ResponseTemplateGreetingController.java | UTF-8 | 1,261 | 2.484375 | 2 | [] | no_license | package fjtdg.demo.response_template;
import fjtdg.demo.Greeting;
import fjtdg.demo.Weather;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.concurrent.atomic.AtomicLong;
@RestController
public class ResponseTemplateGreetingController {
private static final String template = "Hello, (%d) %s %s!";
private final AtomicLong counter = new AtomicLong();
private final ResponseTemplateWeatherClient responseTemplateWeatherClient;
public ResponseTemplateGreetingController(ResponseTemplateWeatherClient responseTemplateWeatherClient) {
this.responseTemplateWeatherClient = responseTemplateWeatherClient;
}
@RequestMapping("/template/greeting")
public Greeting greeting(@RequestParam(value = "name", defaultValue = "World") String name) {
final String location = "World".equals(name) ? "Here": "There";
final long id = counter.incrementAndGet();
final Weather weather = responseTemplateWeatherClient.getWeather(id, location);
return new Greeting(id,
String.format(template, weather.getId(), weather.getSky(), name));
}
} | true |
e258a570381bc532d7a39bfb9d47de71bb02cd57 | Java | maofangyun/annotation-cache | /src/main/java/com/mfy/advisor/CachePointCut.java | UTF-8 | 2,085 | 2.375 | 2 | [] | no_license | package com.mfy.advisor;
import com.mfy.annotation.EasyCache;
import com.mfy.annotation.Lock;
import com.mfy.cache.CacheProperties;
import com.mfy.lock.LockProperties;
import org.springframework.aop.support.AopUtils;
import org.springframework.aop.support.StaticMethodMatcherPointcut;
import org.springframework.core.MethodClassKey;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.core.annotation.AnnotationUtils;
import java.lang.reflect.Method;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
public class CachePointCut extends StaticMethodMatcherPointcut {
public static final ConcurrentMap<MethodClassKey, CacheProperties> ATTRIBUTE_CACHE = new ConcurrentHashMap<>();
@Override
public boolean matches(Method method, Class<?> targetClass) {
MethodClassKey key = getCacheKey(method,targetClass);
CacheProperties cacheProperties = ATTRIBUTE_CACHE.get(key);
if(cacheProperties != null){
return true;
} else {
cacheProperties = new CacheProperties();
}
Method specificMethod = AopUtils.getMostSpecificMethod(method, targetClass);
if(AnnotatedElementUtils.hasAnnotation(targetClass, EasyCache.class)
|| AnnotatedElementUtils.hasAnnotation(specificMethod,EasyCache.class)){
EasyCache annotation = AnnotationUtils.getAnnotation(specificMethod, EasyCache.class);
cacheProperties.setCacheNames(annotation.cacheNames());
cacheProperties.setMethod(specificMethod);
cacheProperties.setExpire(annotation.expire());
cacheProperties.setKey(annotation.key());
LockProperties lockProperties = new LockProperties();
Lock lock = annotation.lock();
lockProperties.setKey(lock.key());
lockProperties.setLockName(lock.lockName());
lockProperties.setExpire(lock.expire());
cacheProperties.setLockProperties(lockProperties);
ATTRIBUTE_CACHE.putIfAbsent(key,cacheProperties);
return true;
}
return false;
}
public static MethodClassKey getCacheKey(Method method, Class<?> targetClass) {
return new MethodClassKey(method, targetClass);
}
}
| true |
a2504240bf004579bc6b597e242a02174ab6214c | Java | majp-mi/interview | /JavaCodes/JUCDemo/src/main/java/com/juc/demo/SynchronizedDemo.java | UTF-8 | 2,242 | 3.53125 | 4 | [] | no_license | package com.juc.demo;
import java.util.concurrent.TimeUnit;
/**
* @ClassName SynchronizedDemo
* @Author majp
* @Description 普通锁和静态同步锁的代码验证
* synchronized锁定的是当前类的实例对象this
* static synchronized锁的是当前类的对象Class
* 普通方法不在同步锁的范围内
* @Date 2020-05-04 0004 11:48
* Version 1.0
**/
class Phone {
// 普通同步方法
public synchronized void sendEmail() {
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("invoke sendEmail(),2s");
}
// 普通同步方法
public synchronized void sendMsg() {
System.out.println("invoke sendMsg()");
}
// 静态同步方法
public static synchronized void call() {
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("invoke static call(),2s");
}
// 静态同步方法
public static synchronized void wechat() {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("invoke static wechat(),1s");
}
// 普通方法
public void sayHello() {
System.out.println("invoke sayHello()");
}
}
/**
* synchronized锁定的是当前类的实例对象this
* static synchronized锁的是当前类的对象Class
* 普通方法不在同步锁的范围内
*/
public class SynchronizedDemo {
public static void main(String[] args) throws InterruptedException {
Phone phone = new Phone();
Phone phone2 = new Phone();
new Thread(() -> {
phone.sendEmail(); // 等待2s
phone.call(); // 等待2s
}, "AA").start();
Thread.sleep(100);
new Thread(() -> {
phone.sendMsg();
// phone2.sendMsg();
phone.wechat();
// phone2.wechat();
}, "BB").start();
new Thread(() -> {
phone.sayHello();
// phone2.sayHello();
}, "CC").start();
}
}
| true |
61708c9a263ae35d421bae5d747eb00ca5f12070 | Java | PaulinaBinas/book-cataloq | /src/main/java/com/pbinas/books/service/UserService.java | UTF-8 | 386 | 2.09375 | 2 | [] | no_license | package com.pbinas.books.service;
import com.pbinas.books.model.entity.UserEntity;
import java.util.List;
public interface UserService {
UserEntity getUser(String username);
UserEntity getUser(long id);
List<UserEntity> getAllUsers();
void saveUser(UserEntity user);
UserEntity addUser(String username, String password);
UserEntity getLoggedInUser();
}
| true |
9385fbf45c60678ea9c6380e799e25992761446f | Java | niteshch/InterviewBit | /StacksAndQueues/MinStack.java | WINDOWS-1252 | 1,640 | 4.5 | 4 | [] | no_license | package StacksAndQueues;
import java.util.Stack;
/*
Min Stack
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
push(x) Push element x onto stack.
pop() Removes the element on top of the stack.
top() Get the top element.
getMin() Retrieve the minimum element in the stack.
Note that all the operations have to be constant time operations.
Questions to ask the interviewer :
Q: What should getMin() do on empty stack?
A: In this case, return -1.
Q: What should pop do on empty stack?
A: In this case, nothing.
Q: What should top() do on empty stack?
A: In this case, return -1
NOTE
If you are using your own declared global variables, make sure to clear them out in the constructor.
*/
public class MinStack {
Stack<Integer> stack = new Stack<Integer>();
Stack<Integer> minStack = new Stack<Integer>();
public void push(int x) {
stack.push(x);
if(minStack.isEmpty()){
minStack.push(x);
}else if(minStack.peek() > x){
minStack.push(x);
}
}
public void pop() {
if(!stack.isEmpty()){
int element = stack.pop();
int minElement = minStack.peek();
if(element == minElement){
minStack.pop();
}
}
}
public int top() {
if(!stack.isEmpty()){
return stack.peek();
}else{
return -1;
}
}
public int getMin() {
if(!minStack.isEmpty()){
return minStack.peek();
}else{
return -1;
}
}
}
| true |
b4781a011233ba0eaf7a4440949ee20df03dc93e | Java | typohh/GoRatingServer | /src/typo/ranking/server/server/HeartBeat.java | UTF-8 | 836 | 2.078125 | 2 | [] | no_license | package typo.ranking.server.server;
public class HeartBeat {
public static long sNoValue = Long.MIN_VALUE;
public static long getOutstandingRequest( long pUserId ) {
Long outstanding = (Long) Storage.get().getCache( "outstanding" + pUserId );
if( outstanding != null ) {
return outstanding;
}
return sNoValue;
}
public static void setOutstandingRequest( long pUserId ) {
Storage.get().putCache( "outstanding" + pUserId , System.currentTimeMillis() );
}
public static long getPing( long pUserId ) {
Long ping = (Long) Storage.get().getCache( "ping" + pUserId );
if( ping != null ) {
return ping;
}
return sNoValue;
}
public static void setPing( long pUserId ) {
Storage.get().putCache( "ping" + pUserId , System.currentTimeMillis() );
Storage.get().delCache( "outstanding" + pUserId );
}
}
| true |
b1b314c240757fcf16dd680b80b3550d45f6b7c1 | Java | king019/docker | /src/main/java/com/k/docker/jenkins/util/PathUtil.java | UTF-8 | 583 | 2.0625 | 2 | [] | no_license | package com.k.docker.jenkins.util;
public class PathUtil {
public static String getResource() {
String res;
res = "src/main/resources/";
return res;
}
public static String getResource(String path) {
String res;
res = getResource().concat(path);
return res;
}
public static String getTargetPath() {
String res;
res = "target/";
return res;
}
public static String getTargetPath(String path) {
String res;
res = getTargetPath() + path;
return res;
}
}
| true |
56f5f3fcdd3781be07630686b7e87983c2f8878c | Java | xiaoronghui/MyJava | /src/main/java/设计模式/创建型设计模式/抽象工厂模式/Bed.java | UTF-8 | 106 | 1.929688 | 2 | [] | no_license | package 设计模式.创建型设计模式.抽象工厂模式;
public class Bed implements Furnitrue{
}
| true |