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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
903a99a7f646e4f0b953d1da92f2a79a5bff81cd
|
Java
|
jzoom/zoom
|
/zoom-common/src/main/java/com/jzoom/zoom/common/res/ClassResolver.java
|
UTF-8
| 2,059
| 2.734375
| 3
|
[
"Apache-2.0"
] |
permissive
|
package com.jzoom.zoom.common.res;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jzoom.zoom.common.Clearable;
import org.jzoom.zoom.common.Destroyable;
import com.jzoom.zoom.common.filter.Filter;
/**
* 对类进行解析,本类选择性的对一些类进行解析,可以指定类名、类进行解析,可以指定是否解析方法和字段
* @author jzoom
*
*/
public abstract class ClassResolver implements Clearable,Destroyable {
protected static Log log = LogFactory.getLog(ClassResolver.class);
protected Filter<String> patternFilter;
protected Filter<Class<?>> classFilter;
public ClassResolver() {
}
public void destroy() {
clear();
this.patternFilter = null;
this.classFilter = null;
}
/**
* 对名称是否有要求?
*/
public boolean acceptClassName(String className) {
return patternFilter == null ? true : patternFilter.accept(className);
}
/**
* 对类是否有要求?
* @param clazz
* @return
*/
public boolean acceptClass(Class<?> clazz) {
return classFilter == null ? true : classFilter.accept(clazz);
}
public void visitMethod(Method method) {
}
public void visitField(Field field) {
}
public void visitClass(Class<?> clazz) {
}
public Filter<String> getPatternFilter() {
return patternFilter;
}
public void setClassNameFilter(Filter<String> patternFilter) {
this.patternFilter = patternFilter;
}
public Filter<Class<?>> getClassFilter() {
return classFilter;
}
public void setClassFilter(Filter<Class<?>> classFilter) {
this.classFilter = classFilter;
}
/**
* 清理,当进行完一个类的解析之后,本方法会被调用
*/
@Override
public void clear() {
}
/**
* 是否解析字段?
* @return
*/
public abstract boolean resolveFields() ;
/**
* 是否解析方法?
* @return
*/
public abstract boolean resolveMethods() ;
/**
* 结束
*/
public void end() {
}
}
| true
|
aba7077815784805448ae7522e4eefc59fa4eea3
|
Java
|
danielogen/msc_research
|
/selected projects/mobile/Telegram-v6.1.1/TMessagesProj/src/main/java/org/telegram/messenger/voip/JNIUtilities.java
|
UTF-8
| 4,055
| 1.992188
| 2
|
[
"MIT"
] |
permissive
|
package org.telegram.messenger.voip;
import android.annotation.TargetApi;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.LinkAddress;
import android.net.LinkProperties;
import android.net.Network;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.telephony.SubscriptionManager;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import org.telegram.messenger.ApplicationLoader;
import org.telegram.messenger.FileLog;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
/**
* Created by grishka on 16.01.2018.
*/
public class JNIUtilities{
@TargetApi(23)
public static String getCurrentNetworkInterfaceName(){
ConnectivityManager cm=(ConnectivityManager) ApplicationLoader.applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE);
Network net=cm.getActiveNetwork();
if(net==null)
return null;
LinkProperties props=cm.getLinkProperties(net);
if(props==null)
return null;
return props.getInterfaceName();
}
public static String[] getLocalNetworkAddressesAndInterfaceName(){
ConnectivityManager cm=(ConnectivityManager) ApplicationLoader.applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE);
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){
Network net=cm.getActiveNetwork();
if(net==null)
return null;
LinkProperties linkProps=cm.getLinkProperties(net);
if(linkProps==null)
return null;
String ipv4=null, ipv6=null;
for(LinkAddress addr:linkProps.getLinkAddresses()){
InetAddress a=addr.getAddress();
if(a instanceof Inet4Address){
if(!a.isLinkLocalAddress()){
ipv4=a.getHostAddress();
}
}else if(a instanceof Inet6Address){
if(!a.isLinkLocalAddress() && (a.getAddress()[0] & 0xF0) != 0xF0){
ipv6=a.getHostAddress();
}
}
}
return new String[]{linkProps.getInterfaceName(), ipv4, ipv6};
}else{
try{
Enumeration<NetworkInterface> itfs=NetworkInterface.getNetworkInterfaces();
if(itfs==null)
return null;
while(itfs.hasMoreElements()){
NetworkInterface itf=itfs.nextElement();
if(itf.isLoopback() || !itf.isUp())
continue;
Enumeration<InetAddress> addrs=itf.getInetAddresses();
String ipv4=null, ipv6=null;
while(addrs.hasMoreElements()){
InetAddress a=addrs.nextElement();
if(a instanceof Inet4Address){
if(!a.isLinkLocalAddress()){
ipv4=a.getHostAddress();
}
}else if(a instanceof Inet6Address){
if(!a.isLinkLocalAddress() && (a.getAddress()[0] & 0xF0) != 0xF0){
ipv6=a.getHostAddress();
}
}
}
return new String[]{itf.getName(), ipv4, ipv6};
}
return null;
}catch(Exception x){
FileLog.e(x);
return null;
}
}
}
// [name, country, mcc, mnc]
public static String[] getCarrierInfo(){
TelephonyManager tm=(TelephonyManager) ApplicationLoader.applicationContext.getSystemService(Context.TELEPHONY_SERVICE);
if(Build.VERSION.SDK_INT>=24){
tm=tm.createForSubscriptionId(SubscriptionManager.getDefaultDataSubscriptionId());
}
if(!TextUtils.isEmpty(tm.getNetworkOperatorName())){
String mnc="", mcc="";
String carrierID=tm.getNetworkOperator();
if(carrierID!=null && carrierID.length()>3){
mcc=carrierID.substring(0, 3);
mnc=carrierID.substring(3);
}
return new String[]{tm.getNetworkOperatorName(), tm.getNetworkCountryIso().toUpperCase(), mcc, mnc};
}
return null;
}
public static int[] getWifiInfo(){
try{
WifiManager wmgr=(WifiManager) ApplicationLoader.applicationContext.getSystemService(Context.WIFI_SERVICE);
WifiInfo info=wmgr.getConnectionInfo();
return new int[]{info.getRssi(), info.getLinkSpeed()};
}catch(Exception ignore){}
return null;
}
public static String getSupportedVideoCodecs() {
return "";
}
public static int getMaxVideoResolution() {
return 320;
}
}
| true
|
833cb42acdfcad6212c66006d65cf82ce377ea81
|
Java
|
SwatiJP29/New_JEE
|
/JPAHibernate/JPM_Banking_Assignment/src/com/jpm/banking/entities/CurrentAccount.java
|
UTF-8
| 580
| 2.15625
| 2
|
[] |
no_license
|
package com.jpm.banking.entities;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.Table;
@Entity
@Table(name="CURRENT_ACC")
public class CurrentAccount extends Account {
private Long overDraftLimit;
public CurrentAccount() {
// TODO Auto-generated constructor stub
}
public CurrentAccount(Double balance, Set<Customer> customer, Long overDraftLimit) {
super(balance, customer);
this.overDraftLimit = overDraftLimit;
}
public CurrentAccount(Long overDraftLimit) {
super();
this.overDraftLimit = overDraftLimit;
}
}
| true
|
eac399e3a40bf471ad56bf5e77e03d389d7054f0
|
Java
|
BeyondPerception/SherlineClientController
|
/src/test/java/processTest.java
|
UTF-8
| 415
| 2.78125
| 3
|
[] |
no_license
|
import java.io.IOException;
public class processTest {
public static void main(String[] args) throws IOException, InterruptedException {
Process linuxCNC = new ProcessBuilder("/usr/bin/nc", "-k", "-l", "5007").start();
Thread.sleep(5000);
linuxCNC.destroy();
while (linuxCNC.isAlive()) {
linuxCNC.destroy();
System.out.println(linuxCNC.isAlive());
}
System.out.println(linuxCNC.isAlive());
}
}
| true
|
dd61a7f61543cc6d097c58106e2b117372db6c6f
|
Java
|
allenly3/MagicWorld
|
/core/src/com/somoplay/magicworld/Sprite/Bullet.java
|
UTF-8
| 3,140
| 2.5
| 2
|
[] |
no_license
|
package com.somoplay.magicworld.Sprite;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.BodyDef;
import com.badlogic.gdx.physics.box2d.Fixture;
import com.badlogic.gdx.physics.box2d.FixtureDef;
import com.badlogic.gdx.physics.box2d.PolygonShape;
import com.badlogic.gdx.physics.box2d.World;
import com.somoplay.magicworld.MagicWorld;
import com.somoplay.magicworld.Resource.LoadResource;
import com.somoplay.magicworld.Screens.PlayScreen;
import com.somoplay.magicworld.WorldContactListener;
import java.util.ArrayList;
public class Bullet{
public static Texture texture;
public static TextureRegion region;
public Vector2 position;
public boolean destroyed = false;
public boolean toBeDestroyed = false;
public PlayScreen screen;
public World world;
public Body bulletBody;
public Bullet(PlayScreen screen, Vector2 position){
this.position = position;
this.screen = screen;
world = screen.getWorld();
if(texture == null){
texture = LoadResource.assetManager.get("images/blt.png");
region = new TextureRegion(texture );
}
defineBullet();
}
// Creates the body and fixture of the bullets that the player shoots
public void defineBullet(){
BodyDef bdef = new BodyDef();
if(screen.player.state==1||screen.player.state==2) {
bdef.position.set(screen.player.body.getPosition().x + 0.16f, screen.player.body.getPosition().y + 0.10f);
}
if(screen.player.state==3||screen.player.state==4) {
bdef.position.set(screen.player.body.getPosition().x - 0.10f, screen.player.body.getPosition().y + 0.10f);
}
bdef.type = BodyDef.BodyType.DynamicBody;
bulletBody = world.createBody(bdef);
bulletBody.setGravityScale(0);
FixtureDef fdef = new FixtureDef();
PolygonShape shape = new PolygonShape();
shape.setAsBox(8/ MagicWorld.PPM,8/MagicWorld.PPM);
fdef.shape = shape;
fdef.isSensor = true;
bulletBody.createFixture(fdef).setUserData(this);
if(screen.player.state==1||screen.player.state==2) {
bulletBody.setLinearVelocity(2, 0);
}
if(screen.player.state==3||screen.player.state==4) {
bulletBody.setLinearVelocity(-2, 0);
}
}
public void render(SpriteBatch batch){
if(!destroyed)
batch.draw(region, bulletBody.getPosition().x - 8/ MagicWorld.PPM , bulletBody.getPosition().y - 8/ MagicWorld.PPM, 16/MagicWorld.PPM,16/MagicWorld.PPM);
}
public void update(float dt){
if(toBeDestroyed && !destroyed){
world.destroyBody(bulletBody);
destroyed = true;
}
}
public Body getBody(){
return bulletBody;
}
public void setToDestroy(){
toBeDestroyed = true;
}
}
| true
|
9fcccdce6bddb1b52eb079be39f203abf9274c4c
|
Java
|
Visualtaggy/Minimalist-TicTacToe-Android
|
/app/src/main/java/com/example/minimalisttic_tac_toe/MainActivity.java
|
UTF-8
| 3,286
| 2.625
| 3
|
[] |
no_license
|
package com.example.minimalisttic_tac_toe;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Activity;
import android.content.Intent;
import android.media.Image;
import android.os.Bundle;
import android.view.View;
import android.widget.GridLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
// 0: circle, 1: cross
public int currentPlayer = 1;
//2: blank
int[] gameState = {2,2,2,2,2,2,2,2,2};
//All possible indexes needed to win a game
int[][] winPossibilities = {{0,1,2},{3,4,5},{6,7,8},{0,3,6},{1,4,7},{2,5,8},{0,4,8},{2,4,6}};
//Game Status
boolean gameRunning = true;
int drawCounter = 0;
public void fadeIn (View view){
ImageView circle_cross = (ImageView) view;
ImageView result = findViewById(R.id.result_screen);
ImageView p_again = findViewById(R.id.try_again);
int index = Integer.parseInt(circle_cross.getTag().toString());
if (gameState[index] == 2 && gameRunning) {
gameState[index] = currentPlayer;
//Hides X or O from screen
circle_cross.setTranslationY(-1500);
//Using counter to track turns b/w p1 and p2
if (currentPlayer == 0) {
circle_cross.setImageResource(R.drawable.circle);
currentPlayer = 1;
drawCounter++;
} else {
circle_cross.setImageResource(R.drawable.cross);
currentPlayer = 0;
drawCounter++;
}
// Drops X or O down
circle_cross.animate().translationYBy(1500).setDuration(300);
//loop to check if player has won or not
for (int[] winningPosition : winPossibilities) {
if (gameState[winningPosition[0]] == gameState[winningPosition[1]] && gameState[winningPosition[1]] == gameState[winningPosition[2]] && gameState[winningPosition[0]] != 2) {
if (currentPlayer == 0) {
result.setImageResource(R.drawable.x_won);
} else {
result.setImageResource(R.drawable.o_won);
}
gameRunning = false;
p_again.setVisibility(View.VISIBLE);
p_again.setImageResource(R.drawable.play_again);
}
}
}
// Checking if the game ended in a draw
if(drawCounter == 9){
result.setImageResource(R.drawable.draw);
p_again.setVisibility(View.VISIBLE);
p_again.setImageResource(R.drawable.play_again);
}
}
public void playAgain(View view){
//Restarting Activity to play again
Intent intent = getIntent();
overridePendingTransition(0, 0);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
finish();
overridePendingTransition(0, 0);
startActivity(intent);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
| true
|
50d17b07f370c91fe7b2736a9abad2f7be76cea0
|
Java
|
beanrootbaob/weiit-saas
|
/weiit-saas-api/src/main/java/com/weiit/web/base/ApiService.java
|
UTF-8
| 2,413
| 2.421875
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.weiit.web.base;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.weiit.core.entity.E;
import com.weiit.core.service.BaseService;
import com.weiit.core.service.impl.AbstractService;
import com.weiit.web.common.ApiResponseCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.math.BigDecimal;
/**
* Created by 罗鸿强 on 2018/9/19.
*/
public abstract class ApiService extends AbstractService implements BaseService {
public final Logger logger = LoggerFactory.getLogger(this.getClass());
/**
* 直接返回json对象
*
* @param object
* @return
*/
public String toJson(Object object) {
String result = JSON.toJSONString(object, SerializerFeature.WriteMapNullValue,
SerializerFeature.DisableCircularReferenceDetect);
logger.info("返回参数:{}",result);
return result;
}
/**
* 直接返回api接口,默认方法返回成功状态
*
* @param object
* @return
*/
public String toJsonAPI(Object object) {
E e = new E();
e.set("code", "0");
e.set("message", "success");
e.set("data", object);
return toJson(e);
}
/**
* 直接返回api接口,可自定义返回message,code
*
* @param object
* @param message
* @param code
* @return
*/
public String toJsonAPI(Object object, String message, String code) {
E e = new E();
e.set("code", code);
e.set("message", message);
e.set("data", object);
return toJson(e);
}
public String toJsonAPI(ApiResponseCode apiResponseCode){
E result = new E();
result.set("code", apiResponseCode.getCode());
result.set("message", apiResponseCode.getMessage());
return toJson(result);
}
public <T> T getObject(String json,Class clazz){
return (T) JSON.parseObject(json,clazz);
}
/**
* 四舍五入
*
* */
public double getDoubleValue(BigDecimal bigDecimal){
return bigDecimal.setScale(2,BigDecimal.ROUND_HALF_DOWN).doubleValue();
}
/**
* 四舍五入支付精度缺失会少一分钱
*
* */
public int getInterValue(BigDecimal bigDecimal){
return bigDecimal.setScale(0,BigDecimal.ROUND_HALF_DOWN).intValue();
}
}
| true
|
a318cce3b6f4e88afc2828c12bb2ea13b25c0f6a
|
Java
|
utalo/ontologyUpdate
|
/OntologyUpdate/src-test/com/hp/hpl/jena/sparql/suites/TestNodeValue.java
|
UTF-8
| 29,016
| 2.25
| 2
|
[
"Apache-2.0",
"BSD-3-Clause"
] |
permissive
|
/*
* (c) Copyright 2005, 2006, 2007, 2008 Hewlett-Packard Development Company, LP
* All rights reserved.
* [See end of file]
*/
package com.hp.hpl.jena.sparql.suites;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.TimeZone;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import com.hp.hpl.jena.datatypes.xsd.XSDDatatype;
import com.hp.hpl.jena.graph.Node;
import com.hp.hpl.jena.sparql.expr.ExprEvalException;
import com.hp.hpl.jena.sparql.expr.NodeValue;
import com.hp.hpl.jena.sparql.expr.nodevalue.XSDFuncOp;
import com.hp.hpl.jena.sparql.util.Utils;
/** com.hp.hpl.jena.query.test.TestNodeValue
*
* @author Andy Seaborne
*/
public class TestNodeValue extends TestCase
{
static final double doubleAccuracy = 0.00000001d ;
// Many tests are in TestExpressionARQ by using the parser to build NodeValues
// Just some basic testing here
public static TestSuite suite()
{
TestSuite ts = new TestSuite(TestNodeValue.class) ;
ts.setName(Utils.classShortName(TestNodeValue.class)) ;
return ts ;
}
public void testInt1()
{
NodeValue v = NodeValue.makeInteger(5) ;
assertTrue("Not a number: "+v, v.isNumber()) ;
assertTrue("Not an integer: "+v, v.isInteger()) ;
assertFalse("Is a node: "+v, v.hasNode()) ;
}
public void testInt2()
{
NodeValue v = NodeValue.makeNodeInteger(5) ;
assertTrue("Not a number: "+v, v.isNumber()) ;
assertTrue("Not an integer: "+v, v.isInteger()) ;
assertTrue("Not a node: "+v, v.hasNode()) ;
}
public void testInt3()
{
NodeValue v1 = NodeValue.makeNodeInteger(5) ;
NodeValue v2 = NodeValue.makeInteger(5) ;
assertTrue("Not same integer: "+v1+" & "+v2, v1.getInteger().equals(v2.getInteger())) ;
}
public void testFloat1()
{
NodeValue v = NodeValue.makeFloat(5) ;
assertTrue("Not a number: "+v, v.isNumber()) ;
assertTrue("Not a float: "+v, v.isFloat()) ;
assertTrue("Float not a double: "+v, v.isDouble()) ;
assertFalse("No node: "+v, v.hasNode()) ;
}
public void testFloat2()
{
NodeValue v = NodeValue.makeNodeFloat(5) ;
assertTrue("Not a number: "+v, v.isNumber()) ;
assertTrue("Not a float: "+v, v.isDouble()) ;
assertTrue("Float not a double: "+v, v.isDouble()) ;
assertTrue("Not a node: "+v, v.hasNode()) ;
}
public void testFloat3()
{
NodeValue v1 = NodeValue.makeNodeFloat(5.7f) ;
NodeValue v2 = NodeValue.makeFloat(5.7f) ;
assertTrue("Not same float: "+v1+" & "+v2, v1.getFloat() == v2.getFloat()) ;
assertTrue("Not same float as double: "+v1+" & "+v2, v1.getDouble() == v2.getDouble()) ;
}
public void testDouble1()
{
NodeValue v = NodeValue.makeDouble(5) ;
assertTrue("Not a number: "+v, v.isNumber()) ;
assertTrue("Not a double: "+v, v.isDouble()) ;
assertFalse("No node: "+v, v.hasNode()) ;
}
public void testDouble2()
{
NodeValue v = NodeValue.makeNodeDouble(5) ;
assertTrue("Not a number: "+v, v.isNumber()) ;
assertTrue("Not a double: "+v, v.isDouble()) ;
assertTrue("Not a node: "+v, v.hasNode()) ;
}
public void testDouble3()
{
NodeValue v1 = NodeValue.makeNodeDouble(5.7) ;
NodeValue v2 = NodeValue.makeDouble(5.7) ;
assertTrue("Not same double: "+v1+" & "+v2, v1.getDouble() == v2.getDouble()) ;
}
public void testDecimal1()
{
NodeValue v = NodeValue.makeDecimal(new BigDecimal("1.3")) ;
assertTrue("Not a number: "+v, v.isNumber()) ;
assertTrue("Not a double: "+v, v.isDecimal()) ;
assertFalse("Is a node: "+v, v.hasNode()) ;
}
public void testDecimal2()
{
NodeValue v = NodeValue.makeNodeDecimal("1.3") ;
assertTrue("Not a number: "+v, v.isNumber()) ;
assertTrue("Not a double: "+v, v.isDecimal()) ;
assertTrue("Not a node: "+v, v.hasNode()) ;
}
public void testDecimal3()
{
NodeValue v1 = NodeValue.makeDecimal(new BigDecimal("1.3")) ;
NodeValue v2 = NodeValue.makeNodeDecimal("1.3") ;
assertTrue("Not same decimal: "+v1+" & "+v2, v1.getDecimal().compareTo(v2.getDecimal()) == 0 ) ;
assertEquals("Not same decimal by equals: "+v1+" & "+v2, v1, v2) ;
}
public void testDateTime1()
{
Calendar cal = new GregorianCalendar() ;
cal.setTimeZone(TimeZone.getTimeZone("GMT")) ;
// Clear/ set all fields (milliseconds included).
cal.setTimeInMillis(0) ;
cal.set(2005,01,18,20,39,10) ; // NB Months from 0, not 1
NodeValue v = NodeValue.makeDateTime(cal) ;
assertTrue("Not a dateTime: "+v, v.isDateTime()) ;
assertFalse("A date: "+v, v.isDate()) ;
// DateTimes always have nodes because we used that to parse the thing.
}
public void testDateTime2()
{
NodeValue v = NodeValue.makeNodeDateTime("2005-02-18T20:39:10Z") ;
assertTrue("Not a dateTime: "+v, v.isDateTime()) ;
assertFalse("A date: "+v, v.isDate()) ;
assertTrue("Not a node: "+v, v.hasNode()) ;
}
// NodeValue v = NodeValue.makeNode("2005-02-18T20:39:10Z", XSDDatatype.XSDdateTime) ;
// assertTrue("Not a dateTime: "+v, v.isDate()) ;
// assertNotNull("No node: "+v, v.getNode()) ;
public void testDateTime3()
{
NodeValue v1 = NodeValue.makeDateTime("2005-02-18T20:39:10Z") ;
NodeValue v2 = NodeValue.makeNodeDateTime("2005-02-18T20:39:10Z") ;
assertEquals("Not Calendar.equals: ", v1.getDateTime(), v2.getDateTime()) ;
}
public void testDateTime4()
{
Calendar cal1 = new GregorianCalendar() ;
cal1.setTimeZone(TimeZone.getTimeZone("GMT")) ;
// Clear/ set all fields (milliseconds included).
cal1.setTimeInMillis(0) ;
cal1.set(2005,01,18,20,39,10) ; // NB Months from 0, not 1
NodeValue v = NodeValue.makeNode("2005-02-18T20:39:10Z", XSDDatatype.XSDdateTime) ;
assertTrue("Not a dateTime: "+v, v.isDateTime()) ;
assertFalse("A date: "+v, v.isDate()) ;
assertTrue("Not a node: "+v, v.hasNode()) ;
Calendar cal2 = v.getDateTime().asCalendar() ;
assertEquals("Not equal: "+v, cal1, cal2) ;
}
public void testDateTime5()
{
boolean b = NodeValue.VerboseWarnings ;
try {
NodeValue.VerboseWarnings = false ;
// Illegal lexical for a dateTime.
NodeValue v = NodeValue.makeNode("2005-02-18", XSDDatatype.XSDdateTime) ;
assertFalse("Date!: "+v, v.isDate()) ;
assertFalse("Datetime!: "+v, v.isDateTime()) ;
} finally {
NodeValue.VerboseWarnings = b;
}
}
public void testDate1()
{
Calendar cal = new GregorianCalendar() ;
cal.setTimeZone(TimeZone.getTimeZone("GMT")) ;
// Clear/ set all fields (milliseconds included).
cal.setTimeInMillis(0) ;
// NB Months from 0, not 1
// For a date, must be time = 00:00:00
cal.set(2005,01,18,0,0,0) ;
NodeValue v = NodeValue.makeDate(cal) ;
assertTrue("Not a date: "+v, v.isDate()) ;
assertFalse("A dateTime: "+v, v.isDateTime()) ;
// DateTimes always have nodes because we used that to parse the thing.
}
public void testDate2()
{
NodeValue v = NodeValue.makeNodeDate("2005-02-18") ;
assertTrue("Not a date: "+v, v.isDate()) ;
assertFalse("A dateTime: "+v, v.isDateTime()) ;
assertTrue("Not a node: "+v, v.hasNode()) ;
}
public void testDate3()
{
NodeValue v1 = NodeValue.makeDate("2005-02-18+01:00") ;
NodeValue v2 = NodeValue.makeNodeDate("2005-02-18+01:00") ;
assertEquals("Not Calendar.equals: ", v1.getDate(), v2.getDate()) ;
}
public void testDate4()
{
Calendar cal1 = new GregorianCalendar() ;
cal1.setTimeZone(TimeZone.getTimeZone("GMT")) ;
// Clear/ set all fields (milliseconds included).
cal1.setTimeInMillis(0) ;
// Must be ",0,0,0"
cal1.set(2005,01,18,0,0,0) ; // NB Months from 0, not 1
NodeValue v = NodeValue.makeNode("2005-02-18Z", XSDDatatype.XSDdate) ;
assertTrue("Not a date: "+v, v.isDate()) ;
assertFalse("A dateTime: "+v, v.isDateTime()) ;
assertTrue("Not a node: "+v, v.hasNode()) ;
Calendar cal2 = v.getDate().asCalendar() ;
assertEquals("Not equal: "+v, cal1, cal2) ;
}
public void testDate5()
{
boolean b = NodeValue.VerboseWarnings ;
try {
NodeValue.VerboseWarnings = false ;
// Illegal lexical for a date.
NodeValue v = NodeValue.makeNode("2005-02-18T20:39:10Z", XSDDatatype.XSDdate) ;
assertFalse("Datetime!: "+v, v.isDateTime()) ;
assertFalse("Date!: "+v, v.isDate()) ;
} finally {
NodeValue.VerboseWarnings = b;
}
}
public void testNodeInt1()
{
NodeValue v = NodeValue.makeNode("57", XSDDatatype.XSDinteger) ;
assertTrue("Not a number: "+v, v.isNumber()) ;
assertTrue("Not an integer: "+v, v.isInteger()) ;
assertTrue("Not a node: "+v, v.hasNode()) ;
}
public void testNodeInt2()
{
NodeValue v = NodeValue.makeNode("57", XSDDatatype.XSDdouble) ;
assertTrue("Not a number: "+v, v.isNumber()) ;
assertTrue("Not a double: "+v, v.isDouble()) ;
assertTrue("Not a node: "+v, v.hasNode()) ;
}
public void testNodeInt3()
{
NodeValue v = NodeValue.makeNode("57", XSDDatatype.XSDinteger) ;
assertTrue("Not a number: "+v, v.isNumber()) ;
assertTrue("Not an integer: "+v, v.isInteger()) ;
assertTrue("Not a node: "+v, v.hasNode()) ;
String actualStr = v.asQuotedString() ;
assertEquals("Print form mismatch", "57", actualStr) ;
}
public void testNodeInt4()
{
NodeValue v = NodeValue.makeNodeInteger(18) ;
assertTrue("Not a number: "+v, v.isNumber()) ;
assertTrue("Not an integer: "+v, v.isInteger()) ;
assertTrue("Not a node: "+v, v.hasNode()) ;
String actualStr = v.asQuotedString() ;
assertEquals("Print form mismatch", "18", actualStr) ;
}
public void testNodeInt5()
{
// Legal as a bare integer but not canonical form
NodeValue v = NodeValue.makeNodeInteger("018") ;
assertTrue("Not a number: "+v, v.isNumber()) ;
assertTrue("Not an integer: "+v, v.isInteger()) ;
assertTrue("Not a node: "+v, v.hasNode()) ;
String actualStr = v.asQuotedString() ;
assertEquals("Print form mismatch", "018", actualStr) ;
}
public void testNodeFloat1()
{
// Theer is no SPARQL representation in short form of a float.
NodeValue v = NodeValue.makeNode("57.0", XSDDatatype.XSDfloat) ;
assertTrue("Not a number: "+v, v.isNumber()) ;
assertTrue("Not a float: "+v, v.isFloat()) ;
assertTrue("Not a double(float): "+v, v.isDouble()) ;
assertTrue("Not a node: "+v, v.hasNode()) ;
String actualStr = v.asQuotedString() ;
assertEquals("Print form mismatch",
"\"57.0\"^^<"+XSDDatatype.XSDfloat.getURI()+">",
actualStr);
}
public void testNodeDouble1()
{
// Note input form is legal and canomical as a lexical form double
NodeValue v = NodeValue.makeNode("57.0e0", XSDDatatype.XSDdouble) ;
assertTrue("Not a number: "+v, v.isNumber()) ;
assertTrue("Not a double: "+v, v.isDouble()) ;
assertTrue("Not a node: "+v, v.hasNode()) ;
String actualStr = v.asQuotedString() ;
assertEquals("Print form mismatch", "57.0e0", actualStr) ;
// "\"57\"^^<"+XSDDatatype.XSDdouble.getURI()+">",
// actualStr);
}
public void testNodeDouble2()
{
// Note input form is not legal as a lexical form double
NodeValue v = NodeValue.makeNode("57", XSDDatatype.XSDdouble) ;
assertTrue("Not a number: "+v, v.isNumber()) ;
assertTrue("Not a double: "+v, v.isDouble()) ;
assertTrue("Not a node: "+v, v.hasNode()) ;
String actualStr = v.asQuotedString() ;
assertEquals("Print form mismatch",
"\"57\"^^<"+XSDDatatype.XSDdouble.getURI()+">",
actualStr);
}
public void testNodeDouble3()
{
// Note input form is legal but not canonical as a bare FP
NodeValue v = NodeValue.makeNode("057.0e0", XSDDatatype.XSDdouble) ;
assertTrue("Not a number: "+v, v.isNumber()) ;
assertTrue("Not a double: "+v, v.isDouble()) ;
assertTrue("Not a node: "+v, v.hasNode()) ;
String actualStr = v.asQuotedString() ;
assertEquals("Print form mismatch", "057.0e0", actualStr);
}
public void testNodeBool1()
{
NodeValue v = NodeValue.makeNode("true", XSDDatatype.XSDboolean) ;
assertTrue("Not a boolean: "+v, v.isBoolean()) ;
assertTrue("Not a node: "+v, v.hasNode()) ;
assertTrue("Not satisfied: "+v, v.getBoolean());
}
public void testNodeBool2()
{
NodeValue v = NodeValue.makeNode("false", XSDDatatype.XSDboolean) ;
assertTrue("Not a boolean: "+v, v.isBoolean()) ;
assertTrue("Not a node: "+v, v.hasNode()) ;
assertFalse("Satisfied: "+v, v.getBoolean()) ;
}
public void testNodeBool3()
{
NodeValue v = NodeValue.makeBoolean(true) ;
assertTrue("Not a boolean: "+v, v.isBoolean()) ;
//assertTrue("Not a node: "+v, v.hasNode()) ;
assertTrue("Not true: "+v, v.getBoolean()) ;
assertTrue("Not true: "+v, XSDFuncOp.booleanEffectiveValue(v)) ;
}
public void testNodeBool4()
{
NodeValue v = NodeValue.makeBoolean(false) ;
assertTrue("Not a boolean: "+v, v.isBoolean()) ;
//assertTrue("Not a node: "+v, v.hasNode()) ;
assertFalse("Not false: "+v, v.getBoolean()) ;
assertFalse("Not false: "+v, XSDFuncOp.booleanEffectiveValue(v)) ;
}
public void testBadLexcial1()
{
boolean b = NodeValue.VerboseWarnings ;
try {
NodeValue.VerboseWarnings = false ;
NodeValue v = NodeValue.makeNodeInteger("abc") ;
assertFalse("Good integer: "+v, v.isInteger()) ;
assertFalse("Good number: "+v, v.isNumber()) ;
} finally { NodeValue.VerboseWarnings = b ; }
}
public void testBadLexcial2()
{
boolean b = NodeValue.VerboseWarnings ;
try {
NodeValue.VerboseWarnings = false ;
NodeValue v = NodeValue.makeNodeInteger("1.8") ;
assertFalse("Good integer: "+v, v.isInteger()) ;
assertFalse("Good number: "+v, v.isNumber()) ;
} finally { NodeValue.VerboseWarnings = b ; }
}
public void testBadLexcial3()
{
boolean b = NodeValue.VerboseWarnings ;
try {
NodeValue.VerboseWarnings = false ;
NodeValue v = NodeValue.makeDateTime("2005-10-34T00:00:01Z") ;
assertFalse("Good date: "+v, v.isDateTime()) ;
} finally { NodeValue.VerboseWarnings = b ; }
}
public void testBadLexcial4()
{
boolean b = NodeValue.VerboseWarnings ;
try {
// Has a space
String s = "2005-10-14T 09:30:23+01:00" ;
NodeValue.VerboseWarnings = false ;
NodeValue v1 = NodeValue.makeDateTime(s) ;
assertFalse("Good date: "+v1, v1.isDateTime()) ;
s = s.replaceAll(" ", "") ;
NodeValue v2 = NodeValue.makeDateTime(s) ;
assertTrue("Bad date: "+v2, v2.isDateTime()) ;
} finally { NodeValue.VerboseWarnings = b ; }
}
// Effective boolean value rules.
// boolean: value of the boolean
// string: length(string) > 0 is true
// numeric: number != Nan && number != 0 is true
// http://www.w3.org/TR/xquery/#dt-ebv
public void testEBV1()
{
assertTrue("Not a boolean", NodeValue.TRUE.isBoolean()) ;
assertTrue("Not true", NodeValue.TRUE.getBoolean()) ;
assertTrue("Not true", XSDFuncOp.booleanEffectiveValue(NodeValue.TRUE)) ;
}
public void testEBV2()
{
assertTrue("Not a boolean", NodeValue.FALSE.isBoolean()) ;
assertFalse("Not false", NodeValue.FALSE.getBoolean()) ;
assertFalse("Not false", XSDFuncOp.booleanEffectiveValue(NodeValue.FALSE)) ;
}
public void testEBV3()
{
NodeValue v = NodeValue.makeInteger(1) ;
assertFalse("It's a boolean: "+v, v.isBoolean()) ;
//assertTrue("Not a node: "+v, v.hasNode()) ;
try { v.getBoolean() ; fail("getBoolean should fail") ; } catch (ExprEvalException e) {}
assertTrue("Not EBV true: "+v, XSDFuncOp.booleanEffectiveValue(v)) ;
}
public void testEBV4()
{
NodeValue v = NodeValue.makeInteger(0) ;
assertFalse("It's a boolean: "+v, v.isBoolean()) ;
//assertTrue("Not a node: "+v, v.hasNode()) ;
try { v.getBoolean() ; fail("getBoolean should fail") ; } catch (ExprEvalException e) {}
assertFalse("Not EBV false: "+v, XSDFuncOp.booleanEffectiveValue(v)) ;
}
public void testEBV5()
{
NodeValue v = NodeValue.makeString("xyz") ;
assertFalse("It's a boolean: "+v, v.isBoolean()) ;
//assertTrue("Not a node: "+v, v.hasNode()) ;
try { v.getBoolean() ; fail("getBoolean should fail") ; } catch (ExprEvalException e) {}
assertTrue("Not EBV true: "+v, XSDFuncOp.booleanEffectiveValue(v)) ;
}
public void testEBV6()
{
NodeValue v = NodeValue.makeString("") ;
assertFalse("It's a boolean: "+v, v.isBoolean()) ;
//assertTrue("Not a node: "+v, v.hasNode()) ;
try { v.getBoolean() ; fail("getBoolean should fail") ; } catch (ExprEvalException e) {}
assertFalse("Not EBV false: "+v, XSDFuncOp.booleanEffectiveValue(v)) ;
}
public void testFloatDouble1()
{
NodeValue v1 = NodeValue.makeNodeDouble("1.5") ;
NodeValue v2 = NodeValue.makeNode("1.5", XSDDatatype.XSDfloat) ;
assertTrue("Should be equal: 1.5 float and 1.5 double", NodeValue.sameAs(v1, v2)) ;
}
public void testFloatDouble5()
{
NodeValue v1 = NodeValue.makeNodeDouble("1.3") ;
NodeValue v2 = NodeValue.makeNode("1.3", XSDDatatype.XSDfloat) ;
assertFalse("Should not be equal: 1.3 float and 1.3 double", NodeValue.sameAs(v1, v2)) ;
}
// More effective boolean values - see TestExpressionARQ
public void testString1()
{
NodeValue v = NodeValue.makeString("string") ;
assertTrue("Not a string: "+v, v.isString()) ;
assertFalse("Is a node: "+v, v.hasNode()) ;
}
public void testNodeString1()
{
NodeValue v = NodeValue.makeNode("string", null, (String)null) ; // Plain literal
assertTrue("Not a string: "+v, v.isString()) ;
assertTrue("Not a node: "+v, v.hasNode()) ;
}
public void testNodeString2()
{
NodeValue v = NodeValue.makeNode("string", null, (String)null) ; // Plain literal
assertTrue("Not a string: "+v, v.isString()) ;
assertTrue("Not a node: "+v, v.hasNode()) ;
String actualStr = v.asQuotedString() ;
assertEquals("Print form mismatch", "\"string\"", actualStr) ;
}
public void testNodeString3()
{
NodeValue v = NodeValue.makeNode("string", XSDDatatype.XSDstring) ; // XSD String literal
assertTrue("Not a string: "+v, v.isString()) ;
assertTrue("Not a node: "+v, v.hasNode()) ;
String actualStr = v.asQuotedString() ;
assertEquals("Print form mismatch",
"\"string\"^^<"+XSDDatatype.XSDstring.getURI()+">",
actualStr) ;
}
// TODO testSameValueDecimal tests
// TODO sameValueAs mixed tests
public void testSameValue1()
{
NodeValue nv1 = NodeValue.makeInteger(5) ;
NodeValue nv2 = NodeValue.makeInteger(7) ;
assertTrue("Same values ("+nv1+","+nv2+")", NodeValue.notSameAs(nv1, nv2)) ;
assertFalse("Same values ("+nv1+","+nv2+")", NodeValue.sameAs(nv1, nv2)) ;
NodeValue nv3 = NodeValue.makeInteger(5) ;
assertTrue("Different values ("+nv1+","+nv3+")", NodeValue.sameAs(nv1, nv3)) ;
assertFalse("Different values - notNotSame ("+nv1+","+nv3+")", NodeValue.notSameAs(nv1, nv3)) ;
}
public void testSameValue2()
{
NodeValue nv1 = NodeValue.makeInteger(5) ;
NodeValue nv2 = NodeValue.makeNodeInteger(7) ;
assertTrue("Same values ("+nv1+","+nv2+")", NodeValue.notSameAs(nv1, nv2)) ;
assertFalse("Same values ("+nv1+","+nv2+")", NodeValue.sameAs(nv1, nv2)) ;
NodeValue nv3 = NodeValue.makeNodeInteger(5) ;
assertTrue("Different values ("+nv1+","+nv3+")", NodeValue.sameAs(nv1, nv3)) ;
assertFalse("Different values - notNotSame ("+nv1+","+nv3+")", NodeValue.notSameAs(nv1, nv3)) ;
}
public void testSameValue3()
{
NodeValue nv1 = NodeValue.makeDecimal("1.5") ;
NodeValue nv2 = NodeValue.makeDecimal("1.6") ;
assertTrue("Same values ("+nv1+","+nv2+")", NodeValue.notSameAs(nv1, nv2)) ;
assertFalse("Same values ("+nv1+","+nv2+")", NodeValue.sameAs(nv1, nv2)) ;
NodeValue nv3 = NodeValue.makeDecimal("1.50") ;
assertTrue("Different values ("+nv1+","+nv3+")", NodeValue.sameAs(nv1, nv3)) ;
assertFalse("Different values - notNotSame ("+nv1+","+nv3+")", NodeValue.notSameAs(nv1, nv3)) ;
}
public void testSameValue4()
{
NodeValue nv1 = NodeValue.makeDecimal("3") ;
NodeValue nv2 = NodeValue.makeInteger(4) ;
assertTrue("Same values ("+nv1+","+nv2+")", NodeValue.notSameAs(nv1, nv2)) ;
assertFalse("Same values ("+nv1+","+nv2+")", NodeValue.sameAs(nv1, nv2)) ;
NodeValue nv3 = NodeValue.makeInteger(3) ;
assertTrue("Different values ("+nv1+","+nv3+")", NodeValue.sameAs(nv1, nv3)) ;
assertFalse("Different values - notNotSame ("+nv1+","+nv3+")", NodeValue.notSameAs(nv1, nv3)) ;
}
public void testSameValue5()
{
NodeValue nv1 = NodeValue.makeDecimal("-1.5") ; // Must be exact for double and decimal
NodeValue nv2 = NodeValue.makeDouble(1.5) ;
assertTrue("Same values ("+nv1+","+nv2+")", NodeValue.notSameAs(nv1, nv2)) ;
assertFalse("Same values ("+nv1+","+nv2+")", NodeValue.sameAs(nv1, nv2)) ;
NodeValue nv3 = NodeValue.makeDouble(-1.5) ;
assertTrue("Different values ("+nv1+","+nv3+")", NodeValue.sameAs(nv1, nv3)) ;
assertFalse("Different values - notNotSame ("+nv1+","+nv3+")", NodeValue.notSameAs(nv1, nv3)) ;
}
public void testSameValue6()
{
NodeValue nv1 = NodeValue.makeNodeInteger(17) ;
NodeValue nv2 = NodeValue.makeDouble(34) ;
assertTrue("Same values ("+nv1+","+nv2+")", NodeValue.notSameAs(nv1, nv2)) ;
assertFalse("Same values ("+nv1+","+nv2+")", NodeValue.sameAs(nv1, nv2)) ;
NodeValue nv3 = NodeValue.makeDouble(17) ;
assertTrue("Different values ("+nv1+","+nv3+")", NodeValue.sameAs(nv1, nv3)) ;
assertFalse("Different values - notNotSame ("+nv1+","+nv3+")", NodeValue.notSameAs(nv1, nv3)) ;
}
public void testSameValue7()
{
NodeValue nv1 = NodeValue.makeBoolean(true) ;
NodeValue nv2 = NodeValue.makeString("a") ;
assertTrue("Same values ("+nv1+","+nv2+")", NodeValue.notSameAs(nv1, nv2)) ;
assertFalse("Same values ("+nv1+","+nv2+")", NodeValue.sameAs(nv1, nv2)) ;
NodeValue nv3 = NodeValue.makeNodeBoolean(true) ;
assertTrue("Different values ("+nv1+","+nv3+")", NodeValue.sameAs(nv1, nv3)) ;
assertFalse("Different values - notNotSame ("+nv1+","+nv3+")", NodeValue.notSameAs(nv1, nv3)) ;
}
public void testLang1()
{
Node n1 = Node.createLiteral("xyz", "en", null) ;
NodeValue nv1 = NodeValue.makeNode(n1) ;
Node n2 = Node.createLiteral("xyz", "en", null) ;
NodeValue nv2 = NodeValue.makeNode(n2) ;
assertTrue(NodeValue.sameAs(nv1, nv2)) ;
}
public void testLang2()
{
Node n1 = Node.createLiteral("xyz", "en", null) ;
NodeValue nv1 = NodeValue.makeNode(n1) ;
Node n2 = Node.createLiteral("xyz", "EN", null) ;
NodeValue nv2 = NodeValue.makeNode(n2) ;
assertTrue(NodeValue.sameAs(nv1, nv2)) ;
assertFalse(nv1.equals(nv2)) ;
}
public void testLang3()
{
Node n1 = Node.createLiteral("xyz", "en", null) ;
NodeValue nv1 = NodeValue.makeNode(n1) ;
Node n2 = Node.createLiteral("xyz", "en", null) ;
NodeValue nv2 = NodeValue.makeNode(n2) ;
assertFalse(NodeValue.notSameAs(nv1, nv2)) ;
}
public void testLang4()
{
Node n1 = Node.createLiteral("xyz", "en", null) ;
NodeValue nv1 = NodeValue.makeNode(n1) ;
Node n2 = Node.createLiteral("xyz", "EN", null) ;
NodeValue nv2 = NodeValue.makeNode(n2) ;
assertFalse(NodeValue.notSameAs(nv1, nv2)) ;
assertFalse(nv1.equals(nv2)) ;
}
public void testEquals1()
{
NodeValue nv1 = NodeValue.makeInteger(1) ;
NodeValue nv2 = NodeValue.makeInteger(1) ;
assertEquals("Not NodeValue.equals()", nv1, nv2) ;
}
public void testEquals2()
{
NodeValue nv1 = NodeValue.makeNodeInteger(1) ;
NodeValue nv2 = NodeValue.makeInteger(1) ;
assertEquals("Not NodeValue.equals()", nv1, nv2) ;
}
public void testEquals3()
{ // Make different ways but equals
NodeValue nv1 = NodeValue.makeInteger(1) ;
NodeValue nv2 = NodeValue.makeNodeInteger(1) ;
assertEquals("Not NodeValue.equals()", nv1, nv2) ;
}
public void testEquals4()
{
NodeValue nv1 = NodeValue.makeNode(Node.createURI("http://example")) ;
NodeValue nv2 = NodeValue.makeNode(Node.createURI("http://example")) ;
assertEquals("Not NodeValue.equals()", nv1 , nv2) ;
}
public void testNotEquals1()
{
NodeValue nv1 = NodeValue.makeInteger(1) ;
NodeValue nv2 = NodeValue.makeInteger(2) ;
assertFalse("NodeValue.equals()", nv1.equals(nv2)) ;
}
public void testNotEquals2()
{
NodeValue nv1 = NodeValue.makeNodeInteger(1) ;
NodeValue nv2 = NodeValue.makeNodeString("1") ;
assertFalse("NodeValue.equals()", nv1.equals(nv2)) ;
}
public void testNotEquals3()
{ //Literals and URIs are different.
NodeValue nv1 = NodeValue.makeNode(Node.createURI("http://example")) ;
NodeValue nv2 = NodeValue.makeNode(Node.createLiteral("http://example")) ;
assertFalse("NodeValue.equals()", nv1.equals(nv2)) ;
}
}
/*
* (c) Copyright 2005, 2006, 2007, 2008 Hewlett-Packard Development Company, LP
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
| true
|
297a417d210c8eec386dbe13c6139e8f5f79c746
|
Java
|
JohnTo88/Wize_L-D
|
/src/test/java/talentwize/Test_FunctionalAccess_ProjectManagementPermission_ProjectBoard.java
|
UTF-8
| 18,128
| 1.976563
| 2
|
[] |
no_license
|
package talentwize;
import java.lang.reflect.Method;
import org.openqa.selenium.WebDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import Ulties.PropertyManager;
import Ulties.TestLogger;
import Ulties.TestManager;
import Ulties.TienIch;
import controller.WebDriversManager;
import talentwize.pages.ActualVolumeBoard;
import talentwize.pages.Administration;
import talentwize.pages.CheckInBoard;
import talentwize.pages.Dashboard;
import talentwize.pages.EmployeeList;
import talentwize.pages.Form_CreateProject;
import talentwize.pages.Form_EditActualVolume;
import talentwize.pages.Form_EditKPIDetail;
import talentwize.pages.Form_EditProject;
import talentwize.pages.HomePage;
import talentwize.pages.KPIBoard;
import talentwize.pages.ProjectBoard;
import talentwize.pages.Roles;
import talentwize.pages.Users;
public class Test_FunctionalAccess_ProjectManagementPermission_ProjectBoard extends TestManager {
HomePage homePage;
WebDriver driver;
PropertyManager propertyManager;
Dashboard dashboard;
Administration administration;
Users users;
Roles roles;
String UserRoleName;
EmployeeList employeeList;
KPIBoard kPIBoard;
Form_EditKPIDetail editKPIDetail;
CheckInBoard checkinBoard;
ActualVolumeBoard actualVolumeBoard;
ProjectBoard projectBoard;
Form_EditActualVolume editActualVolume;
Form_CreateProject createProject;
Form_EditProject editProject;
@BeforeTest
public void KhoiTaoCacNguonTaiNguyen() {
propertyManager = new PropertyManager();
propertyManager.loadData();
driver = WebDriversManager.moTrinhDuyet("chrome");
homePage = new HomePage(driver);
dashboard = new Dashboard(driver);
administration = new Administration(driver);
roles = new Roles(driver);
users = new Users(driver);
employeeList = new EmployeeList(driver);
kPIBoard = new KPIBoard(driver);
editKPIDetail = new Form_EditKPIDetail(driver);
checkinBoard = new CheckInBoard(driver);
actualVolumeBoard = new ActualVolumeBoard(driver);
editActualVolume = new Form_EditActualVolume(driver);
projectBoard = new ProjectBoard(driver);
createProject = new Form_CreateProject(driver);
editProject = new Form_EditProject(driver);
homePage.moLinkWeb(propertyManager.getURL_TalentWize());
}
@BeforeMethod
public void PrintNameTestCase(Method method) {
TestLogger.info("====== Begin Testcase : " + method.getName() + " ========");
}
@Test(priority = 1)
public void TT_979() throws InterruptedException {
TestLogger.info("=================TT_979 ====================");
TestLogger.info("1. Login with Administrator account.");
homePage.SignInWith(propertyManager.getEmailAdmin(), propertyManager.getPasswordAdmin());
if (dashboard.isDashboardMenuDisplayed() == true) {
setStatusTest("pass", "Dang Nhap Thanh Cong");
} else {
setStatusTest("fail", "Dang Nhap khong Thanh Cong");
}
TestLogger.info("2. Go to Administration - User Management - Roles tab");
administration.clickMenuAdministration();
administration.clickMenuUserManagement();
administration.openRolesTab();
TestLogger.info("Create Automation User Role Name and Role Type is Admin :");
UserRoleName = "Project Settings|No permission" + TienIch.taoRandomSo(3);
roles.createUserRoleNameWithRoleTypeAdmin(UserRoleName);
TestLogger.info("Unchecked on Project Management Permission - Project Board | Read");
roles.uncheckbox_Read_ProjectBoard();
TestLogger.info("5. Click Save button");
roles.clickButtonSave();
administration.openTabUsers();
TestLogger.info("Assign role " + UserRoleName + " to employee : " + propertyManager.getEmailUserTW());
users.searchUsername(propertyManager.getEmailUserTW());
// Assign role Automation to this employee
users.assignUserWithNewRole(propertyManager.getEmailUserTW(), UserRoleName);
TestLogger.info("6. Log out");
dashboard.logout();
TestLogger.info("7. Login with test account : " + propertyManager.getEmailUserTW());
homePage.SignInWith(propertyManager.getEmailUserTW(), propertyManager.getPasswordUserTW());
administration.clickMenuProjectManagement();
if (administration.isSubMenuProjectBoardDisplayed() == false) {
setStatusTest("pass", "User CANNOT see/do:\r\n" + "1. Project Board menu");
} else {
setStatusTest("fail", "User STILL CAN see/do:\r\n" + "1. Project Board menu");
}
TestLogger.info("=================END TT_979====================");
}
@Test(priority = 2)
public void TT_974() throws InterruptedException {
TestLogger.info("=================TT_974 ====================");
TestLogger.info("1. Login with Administrator account.");
homePage.SignInWith(propertyManager.getEmailAdmin(), propertyManager.getPasswordAdmin());
if (dashboard.isDashboardMenuDisplayed() == true) {
setStatusTest("pass", "Dang Nhap Thanh Cong");
} else {
setStatusTest("fail", "Dang Nhap khong Thanh Cong");
}
TestLogger.info("2. Go to Administration - User Management - Roles tab");
administration.clickMenuAdministration();
administration.clickMenuUserManagement();
administration.openRolesTab();
TestLogger.info("Create Automation User Role Name and Role Type is Admin :");
UserRoleName = "Project Management|Project Board|Read" + TienIch.taoRandomSo(3);
roles.createUserRoleNameWithRoleTypeAdmin(UserRoleName);
TestLogger.info("Unchecked on Project Management Permission - Project Board | Read");
roles.uncheckbox_Read_ProjectBoard();
TestLogger.info("Check on Project Management Permission - Project Board | Read");
roles.checkbox_Read_ProjectBoard();
TestLogger.info("5. Click Save button");
roles.clickButtonSave();
administration.openTabUsers();
TestLogger.info("Assign role " + UserRoleName + " to employee : " + propertyManager.getEmailUserTW());
users.searchUsername(propertyManager.getEmailUserTW());
// Assign role Automation to this employee
users.assignUserWithNewRole(propertyManager.getEmailUserTW(), UserRoleName);
TestLogger.info("6. Log out");
dashboard.logout();
TestLogger.info("7. Login with test account : " + propertyManager.getEmailUserTW());
homePage.SignInWith(propertyManager.getEmailUserTW(), propertyManager.getPasswordUserTW());
TestLogger.info("Open Project Management >> Project Board");
administration.scrollToBottomPage();
administration.clickMenuProjectManagement();
administration.clickSubMenuProjectBoard();
if (projectBoard.isBtnExportDisplayed() == true) {
setStatusTest("pass", "User can see /do:\r\n" + "1. Data table\r\n" + "2. Export button");
} else {
setStatusTest("fail", "User can NOT see /do:\r\n" + "1. Data table\r\n" + "2. Export button");
}
TestLogger.info("Expect : User cannot see/do:\r\n" + "1. Create button\r\n"
+ "2. Action button > Project Information\r\n" + "3. Delete function");
projectBoard.clickButtonAction();
if (projectBoard.isIcoDeleteDisplayed() == false && projectBoard.isBtnCreateDisplayed() == false
&& projectBoard.isBtnProjectInformationDisplayed() == false) {
setStatusTest("pass", "User cannot see/do:\r\n" + "1. Create button\r\n"
+ "2. Action button > Project Information\r\n" + "3. Delete function");
} else {
setStatusTest("fail", " User STILL can see/do:\r\n" + "1. Create button\r\n"
+ "2. Action button > Project Information\r\n" + "3. Delete function");
}
TestLogger.info("=================END TT_974====================");
}
@Test(priority = 3)
public void TT_977() throws InterruptedException {
TestLogger.info("=================TT_977 ====================");
TestLogger.info("1. Login with Administrator account.");
homePage.SignInWith(propertyManager.getEmailAdmin(), propertyManager.getPasswordAdmin());
if (dashboard.isDashboardMenuDisplayed() == true) {
setStatusTest("pass", "Dang Nhap Thanh Cong");
} else {
setStatusTest("fail", "Dang Nhap khong Thanh Cong");
}
TestLogger.info("2. Go to Administration - User Management - Roles tab");
administration.clickMenuAdministration();
administration.clickMenuUserManagement();
administration.openRolesTab();
TestLogger.info("Create Automation User Role Name and Role Type is Admin :");
UserRoleName = "Project Management|Project Board|Read" + TienIch.taoRandomSo(3);
roles.createUserRoleNameWithRoleTypeAdmin(UserRoleName);
TestLogger.info("Unchecked on Project Management Permission - Project Board | Read");
roles.uncheckbox_Read_ProjectBoard();
TestLogger.info("Check on Project Management Permission - Project Board | Create");
roles.checkbox_Create_ProjectBoard();
TestLogger.info("5. Click Save button");
roles.clickButtonSave();
administration.openTabUsers();
TestLogger.info("Assign role " + UserRoleName + " to employee : " + propertyManager.getEmailUserTW());
users.searchUsername(propertyManager.getEmailUserTW());
// Assign role Automation to this employee
users.assignUserWithNewRole(propertyManager.getEmailUserTW(), UserRoleName);
TestLogger.info("6. Log out");
dashboard.logout();
TestLogger.info("7. Login with test account : " + propertyManager.getEmailUserTW());
homePage.SignInWith(propertyManager.getEmailUserTW(), propertyManager.getPasswordUserTW());
administration.scrollToBottomPage();
administration.clickMenuProjectManagement();
TestLogger.info("Open Project Management >> Project Board");
administration.clickSubMenuProjectBoard();
TestLogger.info("Expect : User can see /do:\r\n" + "1. Data table\r\n" + "2. Export button ");
if (projectBoard.isBtnExportDisplayed() == true) {
setStatusTest("pass", "User can see /do:\r\n" + "1. Data table\r\n" + "2. Export button");
} else {
setStatusTest("fail", " User can NOT see /do:\r\n" + "1. Data table\r\n" + "2. Export button");
}
projectBoard.clickButtonAction();
if (projectBoard.isBtnProjectInformationDisplayed() == false && projectBoard.isIcoDeleteDisplayed() == false) {
setStatusTest("pass",
"User cannot see/do:\r\n" + "1. Action button > Project Information\r\n" + "2. Delete function");
}
else {
setStatusTest("fail",
"User STILL CAN see/do:\r\n" + "1. Action button > Project Information\r\n" + "2. Delete function");
}
projectBoard.clickButtonCreate();
createProject.createProject(TienIch.taoRandomChu(12), TienIch.taoRandomSo(6));
if (projectBoard.isMessageAddSuccessDisplayed() == true) {
setStatusTest("pass", "Displays msg \"Create new project successfully\"");
} else {
setStatusTest("fail", "DOES NOT Displays msg \"Create new project successfully\"");
}
TestLogger.info("=================END TT_977====================");
}
@Test(priority = 4)
public void TT_976() throws InterruptedException {
TestLogger.info("=================TT_976 ====================");
TestLogger.info("1. Login with Administrator account.");
homePage.SignInWith(propertyManager.getEmailAdmin(), propertyManager.getPasswordAdmin());
if (dashboard.isDashboardMenuDisplayed() == true) {
setStatusTest("pass", "Dang Nhap Thanh Cong");
} else {
setStatusTest("fail", "Dang Nhap khong Thanh Cong");
}
TestLogger.info("2. Go to Administration - User Management - Roles tab");
administration.clickMenuAdministration();
administration.clickMenuUserManagement();
administration.openRolesTab();
TestLogger.info("Create Automation User Role Name and Role Type is Admin :");
UserRoleName = "Project Management|Project Board|Update" + TienIch.taoRandomSo(3);
roles.createUserRoleNameWithRoleTypeAdmin(UserRoleName);
TestLogger.info("Unchecked on Project Management Permission - Project Board | Read");
roles.uncheckbox_Read_ProjectBoard();
TestLogger.info(" Check on Project Management Permission - Project Board| Update");
roles.checkbox_Update_ProjectBoard();
TestLogger.info("5. Click Save button");
roles.clickButtonSave();
administration.openTabUsers();
TestLogger.info("Assign role " + UserRoleName + " to employee : " + propertyManager.getEmailUserTW());
users.searchUsername(propertyManager.getEmailUserTW());
// Assign role Automation to this employee
users.assignUserWithNewRole(propertyManager.getEmailUserTW(), UserRoleName);
TestLogger.info("6. Log out");
dashboard.logout();
TestLogger.info("7. Login with test account : " + propertyManager.getEmailUserTW());
homePage.SignInWith(propertyManager.getEmailUserTW(), propertyManager.getPasswordUserTW());
administration.scrollToBottomPage();
administration.clickMenuProjectManagement();
TestLogger.info("Open Project Management >> Project Board");
administration.clickSubMenuProjectBoard();
TestLogger.info("Expect : User can see /do:\r\n" + "1. Data table\r\n" + "2. Export button ");
if (projectBoard.isBtnExportDisplayed() == true) {
setStatusTest("pass", "User can see /do:\r\n" + "1. Data table\r\n" + "2. Export button");
} else {
setStatusTest("fail", " User can NOT see /do:\r\n" + "1. Data table\r\n" + "2. Export button");
}
projectBoard.clickButtonAction();
if (projectBoard.isBtnProjectInformationDisplayed() == true) {
setStatusTest("pass", "User can see/do:\r\n" + "1. Action button > Project Information\r\n" + "");
}
else {
setStatusTest("fail", "User STILL CAN see/do:\r\n" + "1. Action button > Project Information\r\n" + "");
}
if (projectBoard.isIcoDeleteDisplayed() == false) {
setStatusTest("pass", "User cannot see/do:\r\n" + "1. Delete function");
} else {
setStatusTest("fail", "User STILL CAN see/do:\r\n" + "1. Delete function");
}
TestLogger.info("3. Click on button \"Action\"\r\n" + "4. Click on option \"Project Information\"\r\n"
+ "5. Click on button \"Update\"");
projectBoard.clickOnProjectInformation();
editProject.UpdateProject();
if (projectBoard.isMessageUpdateSuccessDisplayed() == true) {
setStatusTest("pass", "Displays msg \"Update project successfully\"");
} else {
setStatusTest("fail", "DOES NOT Displays msg \"Update project successfully\"");
}
TestLogger.info("=================END TT_976====================");
}
@Test(priority = 5)
public void TT_978() throws InterruptedException {
TestLogger.info("=================TT_978 ====================");
TestLogger.info("1. Login with Administrator account.");
homePage.SignInWith(propertyManager.getEmailAdmin(), propertyManager.getPasswordAdmin());
if (dashboard.isDashboardMenuDisplayed() == true) {
setStatusTest("pass", "Dang Nhap Thanh Cong");
} else {
setStatusTest("fail", "Dang Nhap khong Thanh Cong");
}
TestLogger.info("2. Go to Administration - User Management - Roles tab");
administration.clickMenuAdministration();
administration.clickMenuUserManagement();
administration.openRolesTab();
TestLogger.info("Create Automation User Role Name and Role Type is Admin :");
UserRoleName = "Project Management|Project Board|Delete" + TienIch.taoRandomSo(3);
roles.createUserRoleNameWithRoleTypeAdmin(UserRoleName);
TestLogger.info("Unchecked on Project Management Permission - Project Board | Read");
roles.uncheckbox_Read_ProjectBoard();
TestLogger.info(" Check on Project Management Permission - Project Board| Delete");
roles.checkbox_Delete_ProjectBoard();
TestLogger.info("5. Click Save button");
roles.clickButtonSave();
administration.openTabUsers();
TestLogger.info("Assign role " + UserRoleName + " to employee : " + propertyManager.getEmailUserTW());
users.searchUsername(propertyManager.getEmailUserTW());
// Assign role Automation to this employee
users.assignUserWithNewRole(propertyManager.getEmailUserTW(), UserRoleName);
TestLogger.info("6. Log out");
dashboard.logout();
TestLogger.info("7. Login with test account : " + propertyManager.getEmailUserTW());
homePage.SignInWith(propertyManager.getEmailUserTW(), propertyManager.getPasswordUserTW());
administration.scrollToBottomPage();
administration.clickMenuProjectManagement();
TestLogger.info("Open Project Management >> Project Board");
administration.clickSubMenuProjectBoard();
TestLogger.info("Expect : User can see /do:\r\n" + "1. Data table\r\n" + "2. Export button ");
if (projectBoard.isBtnExportDisplayed() == true && projectBoard.isIcoDeleteDisplayed() == true) {
setStatusTest("pass",
"User can see /do:\r\n" + "1. Data table\r\n" + "2. Export button" + "4. Delete function");
} else {
setStatusTest("fail",
" User can NOT see /do:\r\n" + "1. Data table\r\n" + "2. Export button" + "4. Delete function");
}
projectBoard.clickButtonAction();
if (projectBoard.isBtnProjectInformationDisplayed() == false && projectBoard.isBtnCreateDisplayed() == false) {
setStatusTest("pass",
"User cannot see/do:\r\n" + "1. Create button\r\n" + "2. Action button > Project Information");
}
else {
setStatusTest("fail",
"User STILL CAN see/do:\r\n" + "1. Create button\r\n" + "2. Action button > Project Information");
}
projectBoard.deleteProjectName();
if (projectBoard.isMessageDeleteSuccessDisplayed() == true) {
setStatusTest("pass", "Displays msg \"Project deleted successfully!\"");
} else {
setStatusTest("fail", "DOES NOT Displays msg \"Project deleted successfully!\"");
}
TestLogger.info("=================END TT_978====================");
}
@AfterMethod(alwaysRun = true)
public void finishTestCase(Method method) throws InterruptedException {
// logout
if (dashboard.isProfileDisplayed() == true) {
dashboard.logout();
}
homePage.moLinkWeb(propertyManager.getURL_TalentWize());
homePage.SignInWith(propertyManager.getEmailAdmin(), propertyManager.getPasswordAdmin());
administration.clickMenuAdministration();
administration.clickMenuUserManagement();
administration.openRolesTab();
roles.searchRoles(UserRoleName);
roles.Delete_Role();
if (dashboard.isProfileDisplayed() == true) {
dashboard.logout();
}
TestLogger.info("====== End Testcase : " + method.getName() + " ======");
}
@AfterTest(alwaysRun = true)
public void dongTrinhDuyet() {
driver.close();
}
}
| true
|
3e88234db876f4498c162fc3592afcd84d6e65ab
|
Java
|
TheConstructor/tbmgmt
|
/web/src/main/java/de/uni_muenster/cs/comsys/tbmgmt/web/model/experiment/FilteredExperimentWithLog.java
|
UTF-8
| 6,960
| 1.710938
| 2
|
[] |
no_license
|
package de.uni_muenster.cs.comsys.tbmgmt.web.model.experiment;
import de.uni_muenster.cs.comsys.tbmgmt.core.db.dao.experiment.result.ExperimentLogEntryDao;
import de.uni_muenster.cs.comsys.tbmgmt.core.db.dao.experiment.result.ExperimentReplicationResultDao;
import de.uni_muenster.cs.comsys.tbmgmt.core.db.entities.GeneratedIdEntity;
import de.uni_muenster.cs.comsys.tbmgmt.core.db.entities.GeneratedIdEntity_;
import de.uni_muenster.cs.comsys.tbmgmt.core.db.entities.experiment.Experiment;
import de.uni_muenster.cs.comsys.tbmgmt.core.db.entities.experiment.action.ExperimentAction;
import de.uni_muenster.cs.comsys.tbmgmt.core.db.entities.experiment.action.ExperimentAction_;
import de.uni_muenster.cs.comsys.tbmgmt.core.db.entities.experiment.result.ExperimentLogEntry;
import de.uni_muenster.cs.comsys.tbmgmt.core.db.entities.experiment.result.ExperimentLogEntry_;
import de.uni_muenster.cs.comsys.tbmgmt.core.db.entities.node.Node;
import de.uni_muenster.cs.comsys.tbmgmt.core.model.LogLevel;
import de.uni_muenster.cs.comsys.tbmgmt.core.utils.TbmgmtUtil;
import de.uni_muenster.cs.comsys.tbmgmt.web.model.Pagination;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.function.Supplier;
/**
* Model for viewExperiment. Remember to add binding in viewExperiment-flow.xml if you want to be able to set
* something in the view.
*/
@Configurable
public class FilteredExperimentWithLog extends FilteredExperiment implements Serializable {
@Autowired
private transient ExperimentReplicationResultDao replicationResultDao;
@Autowired
private transient ExperimentLogEntryDao logEntryDao;
private String onlyContaining = null;
private Long onlyReplication = null;
private Long onlyIteration = null;
private Long onlyNode = null;
private Long onlyActionBlock = null;
private Long onlyAction = null;
private LogLevel onlyLogLevel = null;
private final Experiment experiment;
public FilteredExperimentWithLog(final Experiment experiment) {
super(experiment);
this.experiment = experiment;
}
public String getOnlyContaining() {
return onlyContaining;
}
public void setOnlyContaining(final String onlyContaining) {
this.onlyContaining = onlyContaining;
}
public Long getOnlyReplication() {
return onlyReplication;
}
public void setOnlyReplication(final Long onlyReplication) {
this.onlyReplication = onlyReplication;
}
public Long getOnlyIteration() {
return onlyIteration;
}
public void setOnlyIteration(final Long onlyIteration) {
this.onlyIteration = onlyIteration;
}
public Long getOnlyNode() {
return onlyNode;
}
public void setOnlyNode(final Long onlyNode) {
this.onlyNode = onlyNode;
}
public Long getOnlyActionBlock() {
return onlyActionBlock;
}
public void setOnlyActionBlock(final Long onlyActionBlock) {
this.onlyActionBlock = onlyActionBlock;
}
public Long getOnlyAction() {
return onlyAction;
}
public void setOnlyAction(final Long onlyAction) {
this.onlyAction = onlyAction;
}
public LogLevel getOnlyLogLevel() {
return onlyLogLevel;
}
public void setOnlyLogLevel(final LogLevel onlyLogLevel) {
this.onlyLogLevel = onlyLogLevel;
}
public List<Node> getUsedNodes() {
final ArrayList<Node> nodes = new ArrayList<>(experiment.getUsedNodes().values());
nodes.sort((n1, n2) -> n1.getName().compareTo(n2.getName()));
return nodes;
}
public Pagination<ExperimentLogEntry> getLogEntries(final String[] pageParam, final String[] perPageParam) {
int page = 0;
int perPage = 20;
if (pageParam != null && pageParam.length > 0) {
try {
page = Integer.parseInt(pageParam[0]);
} catch (NumberFormatException e) {
}
}
if (perPageParam != null && perPageParam.length > 0) {
try {
perPage = Integer.parseInt(perPageParam[0]);
} catch (NumberFormatException e) {
}
}
return new Pagination<>(logEntryDao, (cb, logEntryRoot) -> {
final List<Predicate> predicates = new ArrayList<>();
predicates.add(cb.equal(logEntryRoot.get(ExperimentLogEntry_.experiment), experiment));
if (StringUtils.isNotBlank(onlyContaining)) {
predicates.add(cb.like(cb.lower(logEntryRoot.get(ExperimentLogEntry_.message)),
cb.lower(cb.literal("%" + TbmgmtUtil.escapeLikeString(onlyContaining) + "%")),
TbmgmtUtil.LIKE_ESCAPE_CHAR));
}
addIdEqualsPredicate(cb, predicates, () -> logEntryRoot.get(ExperimentLogEntry_.replicationResult),
onlyReplication);
addIdEqualsPredicate(cb, predicates, () -> logEntryRoot.get(ExperimentLogEntry_.variableValues),
onlyIteration);
addIdEqualsPredicate(cb, predicates, () -> logEntryRoot.get(ExperimentLogEntry_.node), onlyNode);
if (onlyAction != null || onlyActionBlock != null) {
final Path<ExperimentAction> actionPath = logEntryRoot.get(ExperimentLogEntry_.action);
addIdEqualsPredicate(cb, predicates, () -> actionPath.get(ExperimentAction_.experimentActionBlock),
onlyActionBlock);
addIdEqualsPredicate(cb, predicates, () -> actionPath, onlyAction);
}
if (onlyLogLevel != null) {
predicates.add(cb.equal(logEntryRoot.get(ExperimentLogEntry_.logLevel), onlyLogLevel));
}
return cb.and(predicates.toArray(new Predicate[predicates.size()]));
}, (cb, logEntryRoot) -> {
return Collections.singletonList(cb.desc(logEntryRoot.get(ExperimentLogEntry_.created)));
}, perPage, page, "");
}
// path as Supplier so we don't generate unnecessary joins
private static <T extends GeneratedIdEntity> void addIdEqualsPredicate(final CriteriaBuilder cb,
final List<Predicate> predicates,
final Supplier<Path<T>> path,
final Long value) {
if (value != null) {
predicates.add(cb.equal(path.get().get(GeneratedIdEntity_.id), value));
}
}
}
| true
|
a5e467454f00e0b28ca0a79296a0dd3e627cb9b8
|
Java
|
jasonbrianhall/Jaspersoft-Studio
|
/com.jaspersoft.studio/src/com/jaspersoft/studio/property/section/report/ReportSection.java
|
UTF-8
| 4,712
| 1.640625
| 2
|
[] |
no_license
|
/*******************************************************************************
* Copyright (C) 2010 - 2016. TIBCO Software Inc. All Rights Reserved. Confidential & Proprietary.
******************************************************************************/
package com.jaspersoft.studio.property.section.report;
import net.sf.jasperreports.engine.design.JasperDesign;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import com.jaspersoft.studio.messages.Messages;
import com.jaspersoft.studio.model.MReport;
import com.jaspersoft.studio.properties.view.TabbedPropertySheetPage;
import com.jaspersoft.studio.property.section.AbstractSection;
import com.jaspersoft.studio.property.section.report.util.PHolderUtil;
/**
* The location section on the location tab.
*
* @author Chicu Veaceslav
*/
public class ReportSection extends AbstractSection {
/**
* @see org.eclipse.ui.views.properties.tabbed.ITabbedPropertySection#createControls(org.eclipse.swt.widgets.Composite,
* org.eclipse.ui.views.properties.tabbed.TabbedPropertySheetPage)
*/
public void createControls(Composite parent, TabbedPropertySheetPage tabbedPropertySheetPage) {
super.createControls(parent, tabbedPropertySheetPage);
parent.setLayout(new GridLayout(1, false));
GridData gd = new GridData(GridData.FILL_HORIZONTAL);
gd.grabExcessHorizontalSpace = true;
Composite firstSection = getWidgetFactory().createComposite(parent);
firstSection.setLayout(new GridLayout(3, false));
firstSection.setLayoutData(gd);
gd = new GridData(GridData.FILL_HORIZONTAL);
gd.horizontalSpan = 2;
createWidget4Property(firstSection, JasperDesign.PROPERTY_NAME).getControl().setLayoutData(gd);
gd = new GridData(GridData.FILL_HORIZONTAL);
gd.horizontalSpan = 2;
createWidget4Property(firstSection, PHolderUtil.COM_JASPERSOFT_STUDIO_REPORT_DESCRIPTION).getControl()
.setLayoutData(gd);
gd = new GridData();
gd.horizontalSpan = 2;
createWidget4Property(firstSection, JasperDesign.PROPERTY_LANGUAGE).getControl().setLayoutData(gd);
createWidget4Property(firstSection, JasperDesign.PROPERTY_IMPORTS);
createWidget4Property(firstSection, JasperDesign.PROPERTY_FORMAT_FACTORY_CLASS);
gd = new GridData();
gd.horizontalSpan = 2;
createWidget4Property(firstSection, JasperDesign.PROPERTY_WHEN_NO_DATA_TYPE).getControl().setLayoutData(gd);
gd = new GridData(GridData.FILL_HORIZONTAL);
gd.horizontalSpan = 3;
createWidget4Property(firstSection, JasperDesign.PROPERTY_TITLE_NEW_PAGE, false).getControl().setLayoutData(gd);
gd = new GridData(GridData.FILL_HORIZONTAL);
gd.horizontalSpan = 3;
createWidget4Property(firstSection, JasperDesign.PROPERTY_SUMMARY_NEW_PAGE, false).getControl().setLayoutData(gd);
gd = new GridData(GridData.FILL_HORIZONTAL);
gd.horizontalSpan = 3;
createWidget4Property(firstSection, JasperDesign.PROPERTY_SUMMARY_WITH_PAGE_HEADER_AND_FOOTER, false).getControl()
.setLayoutData(gd);
gd = new GridData(GridData.FILL_HORIZONTAL);
gd.horizontalSpan = 3;
createWidget4Property(firstSection, JasperDesign.PROPERTY_FLOAT_COLUMN_FOOTER, false).getControl()
.setLayoutData(gd);
gd = new GridData(GridData.FILL_HORIZONTAL);
gd.horizontalSpan = 3;
createWidget4Property(firstSection, JasperDesign.PROPERTY_IGNORE_PAGINATION, false).getControl().setLayoutData(gd);
gd = new GridData(GridData.FILL_HORIZONTAL);
gd.horizontalSpan = 3;
createWidget4Property(firstSection, MReport.PROPERY_CREATE_BOOKMARKS, false).getControl().setLayoutData(gd);
}
@Override
protected void initializeProvidedProperties() {
super.initializeProvidedProperties();
addProvidedProperties(JasperDesign.PROPERTY_NAME, Messages.MReport_report_name);
addProvidedProperties(JasperDesign.PROPERTY_LANGUAGE, Messages.common_language);
addProvidedProperties(JasperDesign.PROPERTY_IMPORTS, Messages.MReport_imports);
addProvidedProperties(JasperDesign.PROPERTY_FORMAT_FACTORY_CLASS, Messages.MReport_format_factory_class);
addProvidedProperties(JasperDesign.PROPERTY_WHEN_NO_DATA_TYPE, Messages.MReport_when_no_data_type);
addProvidedProperties(JasperDesign.PROPERTY_TITLE_NEW_PAGE, Messages.MReport_title_on_a_new_page);
addProvidedProperties(JasperDesign.PROPERTY_SUMMARY_NEW_PAGE, Messages.MReport_summary_on_a_new_page);
addProvidedProperties(JasperDesign.PROPERTY_SUMMARY_WITH_PAGE_HEADER_AND_FOOTER,
Messages.MReport_summary_with_page_header_and_footer);
addProvidedProperties(JasperDesign.PROPERTY_FLOAT_COLUMN_FOOTER, Messages.MReport_float_column_footer);
addProvidedProperties(JasperDesign.PROPERTY_IGNORE_PAGINATION, Messages.MReport_ignore_pagination);
}
}
| true
|
b97e22799fd69f7f06c6c559c0ef414092371b78
|
Java
|
anukat2015/TableView
|
/src/edu/umn/genomics/graph/DrawableShape.java
|
UTF-8
| 2,309
| 2.640625
| 3
|
[] |
no_license
|
/*
* @(#) $RCSfile: DrawableO.java,v $ $Revision: 1.2 $ $Date: 2002/07/30 19:44:49 $ $Name: TableView1_2 $
*
* Center for Computational Genomics and Bioinformatics
* Academic Health Center, University of Minnesota
* Copyright (c) 2000-2002. The Regents of the University of Minnesota
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
* see: http://www.gnu.org/copyleft/gpl.html
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
package edu.umn.genomics.graph;
import java.awt.*;
import java.awt.geom.*;
import edu.umn.genomics.table.ExceptionHandler;
/**
* An item to be drawn.
*
* @author J Johnson
* @version $Revision: 1.2 $ $Date: 2002/07/30 19:44:49 $ $Name: TableView1_2 $
* @since 1.0
* @see javax.swing.table.TableModel
* @see javax.swing.ListSelectionModel
* @see Graph
*/
public class DrawableShape implements Drawable {
Shape shape = new Line2D.Double(0.,0.,0.,0.);
public DrawableShape() {
}
public DrawableShape(Shape shape) {
setShape(shape);
}
public void setShape(Shape shape) {
this.shape = shape;
}
public Shape getShape() {
return shape;
}
/*
* Draw using the given graphics context at the given point.
* @param g the graphics context.
* @param xAxis The X axis of the graph.
* @param yAxis The Y axis of the graph.
*/
public void draw(Graphics g, int x, int y) {
try {
Graphics2D g2 = (Graphics2D)g;
g2.translate(x,y);
g2.draw(shape);
g2.translate(-x,-y);
} catch (Exception ex) {
ExceptionHandler.popupException(""+ex);
}
}
public String toString() {
return this.getClass().getSimpleName() + ",Shape=" + getShape();
}
}
| true
|
205f3ca5b54f8f872911347d407e6b1ab0a6267b
|
Java
|
CGreenup/Project2-Trivia-Bird-Backend
|
/src/main/java/com/revature/services/GameService.java
|
UTF-8
| 1,177
| 2.640625
| 3
|
[] |
no_license
|
package com.revature.services;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.revature.models.Answer;
import com.revature.models.Profile;
import com.revature.repo.ProfileDAO;
@Service
public class GameService {
private Logger log;
private ProfileDAO profileDAO;
@Autowired
public GameService(ProfileDAO dao) {
super();
this.profileDAO = dao;
log = LoggerFactory.getLogger(GameService.class);
}
public void updateProfile(Answer answer) {
Profile profile = profileDAO.findByUsername(answer.getUsername());
//Get the data
int numberOfAttemptedQuestions = profile.getNumber_of_questions() + 1;
int numberOfCorrectAnswers = profile.getScore();
if(answer.getAnswer().equals(answer.getCorrectAnswer())) {
numberOfCorrectAnswers++;
}
profile.setNumber_of_questions(numberOfAttemptedQuestions);
profile.setScore(numberOfCorrectAnswers);
profile.setAccuracy(numberOfCorrectAnswers/numberOfAttemptedQuestions);
log.info("Updating profile: " + profile.toString());
profileDAO.update(profile);
}
}
| true
|
f80b099157d6ab14832ea6addec23c0fcad230bc
|
Java
|
ECNURunner/runner
|
/app/src/main/java/com/zjut/runner/util/DialogUtil.java
|
UTF-8
| 1,979
| 2.28125
| 2
|
[] |
no_license
|
package com.zjut.runner.util;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.zjut.runner.R;
import com.zjut.runner.widget.MaterialDialog;
/**
* Created by Phuylai on 2016/12/3.
*/
public class DialogUtil {
public static void showCallDialog(final Context context) {
View layout = ((Activity) context).getLayoutInflater().inflate(
R.layout.frame_call_dialog, null);
Button btn_call = (Button) layout.findViewById(R.id.bt_call);
btn_call.getBackground().setAlpha(Constants.DEF_OPAQUE);
TextView tv_line = (TextView) layout.findViewById(R.id.tv_hotline);
final String phoneNumber = "13127771810";
tv_line.setText(context.getString((R.string.str_hotline), "13127771810"));
final AlertDialog.Builder dialog = new AlertDialog.Builder(context);
dialog.setView(layout);
final AlertDialog alertDialog = dialog.create();
alertDialog.show();
btn_call.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + phoneNumber));
context.startActivity(intent);
alertDialog.dismiss();
}
});
}
public static void showDialog(Context context, int title, int message){
final MaterialDialog materialDialog = new MaterialDialog(context);
materialDialog.setTitle(title);
materialDialog.setMessage(message);
materialDialog.setPositiveButton(R.string.button_ok, new View.OnClickListener() {
@Override
public void onClick(View v) {
materialDialog.dismiss();
}
});
materialDialog.show();
}
}
| true
|
d45cb19fe3734d17731ae00fac1803a7e40b5485
|
Java
|
gulaftab/DeckardDockerised
|
/era_bcb_sample/6/selected/402336.java
|
UTF-8
| 5,679
| 2.515625
| 3
|
[] |
no_license
|
package org.regilo.ftp.client;
import java.io.File;
import java.io.IOException;
import java.net.SocketException;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.log4j.Logger;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.jobs.Job;
import org.regilo.ftp.client.exceptions.FtpException;
import org.regilo.ftp.model.FtpSiteConnector;
public class FtpClient {
private static final Logger log = Logger.getLogger(FtpClient.class);
public static final String PATH_SEPARATOR = "/";
private FtpSiteConnector connector;
public FtpClient(FtpSiteConnector connector) {
this.connector = connector;
}
/**
* Uploads a file via ftp
*
* @param localFile the file to upload
* @param remoteDirectory remote directory
* @param remoteFile remote file name
* @param async if true runs as Job
* @param createRootDir if true create the remote directory
* @param monitor IProgressMonitor to report progress information
* @throws FtpException
*/
public void upload(final File localFile, String remoteDirectory, String remoteFile, boolean async, final boolean createRootDir, IProgressMonitor monitor) throws FtpException {
String remotePath = connector.getRemoteDirectory();
if (remoteDirectory == null) {
remotePath += PATH_SEPARATOR + remoteFile;
} else {
remotePath += remoteDirectory + PATH_SEPARATOR + remoteFile;
}
remotePath = FtpUtils.normalize(remotePath);
final String finalRemotePath = remotePath;
log.debug("remotePath: " + remotePath);
if (async) {
Job uploader = new Job("ftp upload") {
@Override
protected IStatus run(IProgressMonitor monitor) {
try {
FtpUtils.upload(connector, localFile, finalRemotePath, createRootDir, monitor);
} catch (FtpException e) {
e.printStackTrace();
}
return null;
}
};
uploader.schedule();
} else {
FtpUtils.upload(connector, localFile, remotePath, createRootDir, monitor);
}
}
public void download(String remoteDirectory, String remoteFile, final File localFile, boolean async, IProgressMonitor monitor) throws FtpException {
String remotePath = connector.getRemoteDirectory();
if (remoteDirectory == null) {
remotePath += PATH_SEPARATOR + remoteFile;
} else {
remotePath += remoteDirectory + PATH_SEPARATOR + remoteFile;
}
remotePath = FtpUtils.normalize(remotePath);
final String finalRemotePath = remotePath;
log.debug("remotePath: " + remotePath);
if (async) {
Job downloader = new Job("ftp upload") {
@Override
protected IStatus run(IProgressMonitor monitor) {
try {
FtpUtils.download(connector, localFile, finalRemotePath, monitor);
} catch (FtpException e) {
e.printStackTrace();
}
return null;
}
};
downloader.schedule();
} else {
FtpUtils.download(connector, localFile, finalRemotePath, monitor);
}
}
public void chmod(String remoteFile, String mode) {
String remotePath = connector.getRemoteDirectory();
remotePath += PATH_SEPARATOR + remoteFile;
FTPClient ftp = new FTPClient();
try {
String hostname = connector.getUrl().getHost();
ftp.connect(hostname);
log.info("Connected to " + hostname);
log.info(ftp.getReplyString());
boolean loggedIn = ftp.login(connector.getUsername(), connector.getPassword());
if (loggedIn) {
String parameters = "chmod " + mode + " " + remotePath;
ftp.site(parameters);
ftp.logout();
}
ftp.disconnect();
} catch (SocketException e) {
log.error("File chmod failed with message: " + e.getMessage());
} catch (IOException e) {
log.error("File chmod failed with message: " + e.getMessage());
} finally {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException ioe) {
}
}
}
}
public void delete(String remoteFile) {
String remotePath = connector.getRemoteDirectory();
remotePath += PATH_SEPARATOR + remoteFile;
FTPClient ftp = new FTPClient();
try {
String hostname = connector.getUrl().getHost();
ftp.connect(hostname);
log.info("Connected to " + hostname);
log.info(ftp.getReplyString());
boolean loggedIn = ftp.login(connector.getUsername(), connector.getPassword());
if (loggedIn) {
ftp.deleteFile(remotePath);
ftp.logout();
}
ftp.disconnect();
} catch (SocketException e) {
log.error("File chmod failed with message: " + e.getMessage());
} catch (IOException e) {
log.error("File chmod failed with message: " + e.getMessage());
} finally {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException ioe) {
}
}
}
}
}
| true
|
2a92a286237bab22f95677a84c5a7ba41624c1c4
|
Java
|
rockoddy/Week2Lab_Calculators
|
/src/java/Servlet/AgeCalculatorServlet.java
|
UTF-8
| 2,581
| 2.859375
| 3
|
[] |
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 Servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author 798125
*/
public class AgeCalculatorServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
getServletContext().getRequestDispatcher("/WEB-INF/agecalculator.jsp")
.forward(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String Age = request.getParameter("age");
String m="please Enter your age";
String m1="Your next birth Date is On";
String m2="Please Enter the Number Not String";
int a=0;
// to view print statements see the Output window -> Apache Tomcat tab
System.out.println(Age);
// to view log statements see the Output window -> Apache Tomcat Log tab
log(Age);
try{
if (Age == null || Age.equals("")) {
request.setAttribute("message",m);
getServletContext().getRequestDispatcher("/WEB-INF/agecalculator.jsp")
.forward(request, response);
return;
}
}
catch(Exception e)
{
request.setAttribute("message2",m2);
getServletContext().getRequestDispatcher("/WEB-INF/agecalculator.jsp")
.forward(request, response);
return;
}
try{
a=Integer.valueOf(Age);
a++;
}catch(Exception e)
{
request.setAttribute("message2",m2);
getServletContext().getRequestDispatcher("/WEB-INF/agecalculator.jsp")
.forward(request, response);
return;
}
request.setAttribute("message1",m1);
request.setAttribute("aa", a);
getServletContext().getRequestDispatcher("/WEB-INF/agecalculator.jsp").forward(request, response);
}
}
| true
|
3fb7fcdff240157cc4f08cfb7ab9215dc6cc3ec1
|
Java
|
Temxter/Web-excel
|
/src/main/java/dao/Dao.java
|
UTF-8
| 707
| 2.53125
| 3
|
[] |
no_license
|
package dao;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import java.util.List;
import java.util.function.Consumer;
public interface Dao<T> {
T get(int id);
List<T> getAll();
void save(T t);
void update(T t);
void delete(T t);
static void executeInsideTransaction(EntityManager entityManager, Consumer<EntityManager> action){
EntityTransaction transaction = entityManager.getTransaction();
try {
transaction.begin();
action.accept(entityManager);
transaction.commit();
} catch (RuntimeException e) {
transaction.rollback();
throw e;
}
}
}
| true
|
1f0ff2043501df2a39799efe7c9e81954f5b8fe4
|
Java
|
light-work/guiceSide
|
/src/org/guiceside/web/annotation/Token.java
|
UTF-8
| 609
| 2.015625
| 2
|
[] |
no_license
|
package org.guiceside.web.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* <p>
* Token防重复提交注解<br/>
* 显示声明在Action方法之上<br/>
* 可验证当前方法是否重复提交<br/>
* </p>
* @author zhenjia <a href='mailto:zhenjiaWang@gmail.com'>email</a>
* @since JDK1.5
* @version 1.0 $Date:200808
* @see org.guiceside.web.interceptor.TokenValidatorInterceptor
*
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Token {
}
| true
|
972c20258d6def791bef9896a11c59387fb8c7c4
|
Java
|
JakubSzwedowicz/AaDS
|
/List_8/test/BiHeap/BiHeapTest.java
|
UTF-8
| 2,814
| 2.9375
| 3
|
[] |
no_license
|
package BiHeap;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/**
* @author Jakub Szwedowicz
* @version 1.0
* date: 17.05.2021
* email: kuba.szwedowicz@gmail.com
*/
class BiHeapTest {
private BiHeap<Integer> heap;
@BeforeEach
void setUp() {
heap = new BiHeap<Integer>();
heap = BiHeap.insert(heap, new BiHeapNode<Integer>(10));
heap = BiHeap.insert(heap, new BiHeapNode<Integer>(1));
heap = BiHeap.insert(heap, new BiHeapNode<Integer>(2));
heap = BiHeap.insert(heap, new BiHeapNode<Integer>(5));
heap = BiHeap.insert(heap, new BiHeapNode<Integer>(12));
heap = BiHeap.insert(heap, new BiHeapNode<Integer>(3));
heap = BiHeap.insert(heap, new BiHeapNode<Integer>(7));
heap = BiHeap.insert(heap, new BiHeapNode<Integer>(23));
}
@Test
void testSize() {
Assertions.assertEquals(8, heap.size());
BiHeap.delete(heap, heap.getHead());
Assertions.assertEquals(7, heap.size());
}
@Test
void testInsert() {
BiHeapNode<Integer> node = new BiHeapNode<Integer>(0);
heap = BiHeap.insert(heap, node);
Assertions.assertEquals(node, BiHeap.minimum(heap));
BiHeap.extractMin(heap);
BiHeapNode<Integer> minNode = new BiHeapNode<Integer>(1);
Assertions.assertEquals(minNode, BiHeap.minimum(heap));
}
@Test
void testMinimum() {
BiHeapNode<Integer> node = new BiHeapNode<Integer>(1);
Assertions.assertEquals(node, BiHeap.minimum(heap));
BiHeap.delete(heap, BiHeap.minimum(heap));
node = new BiHeapNode<Integer>(2);
Assertions.assertEquals(node, BiHeap.minimum(heap));
}
@Test
void testExtractMin() {
BiHeapNode<Integer> node = new BiHeapNode<Integer>(1);
Assertions.assertEquals(node, BiHeap.extractMin(heap));
node = new BiHeapNode<Integer>(2);
Assertions.assertEquals(node, BiHeap.extractMin(heap));
node = new BiHeapNode<Integer>(3);
Assertions.assertEquals(node, BiHeap.extractMin(heap));
}
@Test
void testDelete() {
BiHeapNode<Integer> minNode = BiHeap.minimum(heap);
BiHeap.delete(heap, minNode);
Assertions.assertEquals(new BiHeapNode<Integer>(2), BiHeap.minimum(heap));
minNode = new BiHeapNode<Integer>(-10);
heap = BiHeap.insert(heap, minNode);
Assertions.assertEquals(minNode, BiHeap.minimum(heap));
}
@Test
void testDecreaseKey() {
BiHeapNode<Integer> node = heap.getHead();
node = node.child;
node = node.child;
node = node.sibling;
BiHeap.decreaseKey(heap, node, -10);
Assertions.assertEquals(new BiHeapNode<Integer>(-10), BiHeap.minimum(heap));
}
}
| true
|
9ed8a07ff4dc3d5c1e4247a2097f6da57020a45b
|
Java
|
stickgoal/trainning-projects
|
/simplecrawler/src/main/java/me/maiz/trainningproject/App.java
|
UTF-8
| 1,404
| 2.25
| 2
|
[] |
no_license
|
package me.maiz.trainningproject;
import me.maiz.trainningproject.core.SimpleNewsCrawler;
import me.maiz.trainningproject.module.CSDNNewsAdapter;
import me.maiz.trainningproject.core.SimpleCrawler;
import me.maiz.trainningproject.module.NewsCrawlConfig;
import java.io.IOException;
/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args )
{
// SimpleCrawler crawler = new SimpleCrawler();
// crawler.startCrawlingWith(new String[]{"http://news.baidu.com/"});
SimpleNewsCrawler simpleNewsCrawler = new SimpleNewsCrawler();
try {
// simpleNewsCrawler.startCrawlingWith(NewsCrawlConfig.CSDN_NEWS_CONFIG);
NewsCrawlConfig crawlConfig = NewsCrawlConfig.builder().crawlTimesMax(10)
.seedsUrls(new String[]{"http://www.ftchinese.com"})
.newLinkSelector(null)
.targetElementSelector(new String[]{".items>.item-container"})
.titleSelector(".item-headline-link")
.urlSelector(".item-headline-link")
.introSelector(".item-lead")
.contentBodySelector("#story-body-container")
.build();
simpleNewsCrawler.startCrawlingWith(NewsCrawlConfig.THEPAPER_NEWS_CONFIG);
} catch (IOException e) {
e.printStackTrace();
}
}
}
| true
|
1f42445da8104b5cbcefb0ca7bd843da0562b13b
|
Java
|
kafayat/CucumberTest
|
/src/com/pizza/dialog/LoginDialog.java
|
UTF-8
| 1,483
| 2.21875
| 2
|
[] |
no_license
|
package com.pizza.dialog;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import com.pizza.pages.BaseNavigation;
public class LoginDialog extends BaseNavigation {
By loginButton = By.cssSelector("div.v-dialog--active button[aria-label='login']");
By alertMessage = By.cssSelector("div.v-dialog--active i + div");
By dismissIcon = By.cssSelector("div.v-dialog--active a.v-alert__dismissible");
By userNameField = By.cssSelector("div.v-dialog--active input[id*='username']");
By passowrdField = By.cssSelector("div.v-dialog--active input[id*='password']");
By signupLink = By.linkText("Sign Up");
public LoginDialog(WebDriver driver) {
super(driver);
// TODO Auto-generated constructor stub
}
public void ClickLogin() {
driver.findElement(loginButton).sendKeys(Keys.ENTER);
}
public String GetAlertMessage() {
return driver.findElement(alertMessage).getText();
}
public void ClickDismissIcon() {
driver.findElement(dismissIcon).click();
}
public void setUserName(String username) {
driver.findElement(userNameField).sendKeys(username);
}
public void setPassowrd(String password) {
driver.findElement(passowrdField).sendKeys(password);
}
//public void clickSignUpLink() {
// driver.findElement(signupLink).click();
//}
public SignUpDialog clickSignUpLink() {
driver.findElement(signupLink).click();
return new SignUpDialog(driver);
}
}
| true
|
5e4b2a661ebc7919ce8d24006076fda65eb64e9e
|
Java
|
willigro/p_site_eleicao
|
/ProjetoEleicao/Testes/suiteTest/EleicaoTestSuite.java
|
UTF-8
| 843
| 1.570313
| 2
|
[] |
no_license
|
package suiteTest;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import controllerTest.ControllerAvaliacaoTest;
import controllerTest.ControllerProjetoTest;
import controllerTest.ControllerUsuarioTest;
import dao.classes.UsuarioDAO;
import dao.classesTest.AvaliacaoTest;
import dao.classesTest.CandidatoDAOTest;
import dao.classesTest.ComentarioTest;
import dao.classesTest.ProjetoTest;
import dao.classesTest.UsuarioDAOTest;
import daoTest.DAOGenericoTest;
@RunWith(Suite.class)
@Suite.SuiteClasses({
ControllerAvaliacaoTest.class,
ControllerProjetoTest.class,
ControllerUsuarioTest.class,
AvaliacaoTest.class,
ComentarioTest.class,
ProjetoTest.class,
UsuarioDAOTest.class,
DAOGenericoTest.class,
CandidatoDAOTest.class
})
public class EleicaoTestSuite {
}
| true
|
acb7db467121568c1277f07fa0d0aacaa027be11
|
Java
|
neilebliss/ChamberAnimation
|
/src/main/com/buildingt/ChamberAnimation.java
|
UTF-8
| 5,008
| 3.203125
| 3
|
[] |
no_license
|
package com.buildingt;
import com.buildingt.Container.ChamberFrame;
import com.buildingt.Particle.EmptyParticle;
import com.buildingt.Particle.LeftParticle;
import com.buildingt.Particle.BaseParticle;
import com.buildingt.Particle.RightParticle;
import com.buildingt.Particle.XParticle;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ChamberAnimation
{
public static void main(String[] args)
{
String inputFrame = "X < > "; // simple default input
if (args.length > 0 && args[0] != null)
{
inputFrame = args[0];
}
List<String> outputFrames = produceAnimation(inputFrame);
for (String frame : outputFrames)
{
System.out.println(frame);
}
}
/**
* given an input string, produce a sequence of animation frames modelling the
* movement of the represented particles.
* @param inputFrame
* @return
*/
public static List<String> produceAnimation(String inputFrame)
{
ArrayList<BaseParticle> inputFrameAsParticles = convertInputFrameToParticles(inputFrame);
ChamberFrame startingChamber = new ChamberFrame().setParticles(inputFrameAsParticles);
List<String> outputFrames = modelChamber(startingChamber);
return outputFrames;
}
private static ArrayList<BaseParticle> convertInputFrameToParticles(String frame)
{
ArrayList<BaseParticle> convertedFrame = new ArrayList<BaseParticle>(frame.length());
for (char element : frame.toCharArray())
{
switch(element)
{
case '<':
convertedFrame.add(new LeftParticle());
break;
case '>':
convertedFrame.add(new RightParticle());
break;
case 'X':
convertedFrame.add(new XParticle());
break;
default:
convertedFrame.add(new EmptyParticle());
}
}
return convertedFrame;
}
public static List<String> modelChamber(ChamberFrame inputFrame) throws IllegalArgumentException
{
if (inputFrame == null)
{
throw new IllegalArgumentException("Needs a non-null chamber");
}
List<ChamberFrame> outputFrames = new ArrayList<ChamberFrame>();
outputFrames.add(inputFrame);
ChamberFrame nextOutputFrame = inputFrame;
while (!nextOutputFrame.isEmpty())
{
nextOutputFrame = animateFrame(nextOutputFrame);
outputFrames.add(nextOutputFrame);
}
List<String> outputStrings = showOutputFrames(outputFrames);
return outputStrings;
}
private static ChamberFrame animateFrame(ChamberFrame frame)
{
BaseParticle[] inputFrameElements = frame.getParticles().toArray(new BaseParticle[frame.getParticles().size()]);
BaseParticle[] outputParticles = initializeEmptyParticleSet(inputFrameElements.length);
for (int i = 0; i < inputFrameElements.length; i++)
{
switch (inputFrameElements[i].getRepresentation())
{
case '<':
if (i > 0)
{
outputParticles[i-1] = new LeftParticle();
}
break;
case '>':
if (i < outputParticles.length - 1)
{
outputParticles[i+1] = new RightParticle();
}
break;
case 'X':
// GROT - there's a bug in handling the overlap of multiple X particles.
// this isn't yet taking advantage of the decay properties of the particle.
if (i > 0) // this is the same logic as in the previous cases, find a way to combine this.
{
outputParticles[i-1] = new LeftParticle();
}
if (i < outputParticles.length - 2)
{
outputParticles[i+1] = new RightParticle();
}
break;
}
}
frame = new ChamberFrame().setParticles(new ArrayList(Arrays.asList(outputParticles)));
return frame;
}
private static BaseParticle[] initializeEmptyParticleSet(int length)
{
BaseParticle[] outputParticles = new BaseParticle[length];
Arrays.fill(outputParticles, new EmptyParticle()); // fill it with spaces;
return outputParticles;
}
private static List<String> showOutputFrames(List<ChamberFrame> outputFrames)
{
List<String> outputStrings = new ArrayList<String>();
for (ChamberFrame frame : outputFrames)
{
outputStrings.add("\"" + frame.toString() + "\"");
}
return outputStrings;
}
}
| true
|
fdce1c1beb2520b043b8307443cc9c123525b170
|
Java
|
Moritz-HS/LifeCoding
|
/src/GUI/Spiel.java
|
UTF-8
| 3,000
| 2.765625
| 3
|
[] |
no_license
|
package ÜbungGUI;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
public class Spiel extends JFrame{
private Fenster fenster;
// Spielfeld
private JTextField feld00;
private JTextField feld01;
private JTextField feld02;
private JTextField feld10;
private JTextField feld11;
private JTextField feld12;
private JTextField feld20;
private JTextField feld21;
private JTextField feld22;
private JLabel punkte1;
private JLabel punkte2;
private JTextField punkteAnzahl1;
private JTextField punkteAnzahl2;
private JButton abbrechen;
private int zähler;
private int zähler2;
public Spiel() {
setLayout(null);
setSize(900,600);
setLocation(200,100);
setVisible(true);
setResizable(true);
setTitle("Viel Glück");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setzteSpielfeld();
// punkteStand();
add(feld00);
add(feld01);
add(feld02);
add(feld10);
add(feld11);
add(feld12);
add(feld20);
add(feld21);
add(feld22);
// add(punkte1);
// add(punkteAnzahl1);
// add(punkte2);
// add(punkteAnzahl2);
abbrechen = new JButton("Abbrechen");
abbrechen.setBounds(550, 450, 150, 50);
add(abbrechen);
Händler händler = new Händler();
abbrechen.addActionListener(händler);
}
public void setzteSpielfeld() {
feld00 = new JTextField(1);
feld00.setBounds(250, 75, 100, 100);
feld01 = new JTextField(1);
feld01.setBounds(350, 75, 100, 100);
feld02 = new JTextField(1);
feld02.setBounds(450, 75, 100, 100);
feld10 = new JTextField(1);
feld10.setBounds(250, 175, 100, 100);
feld11 = new JTextField(1);
feld11.setBounds(350, 175, 100, 100);
feld12 = new JTextField(1);
feld12.setBounds(450, 175, 100, 100);
feld20 = new JTextField(1);
feld20.setBounds(250, 275, 100, 100);
feld21 = new JTextField(1);
feld21.setBounds(350, 275, 100, 100);
feld22 = new JTextField(1);
feld22.setBounds(450, 275, 100, 100);
}
public void punkteStand() {
punkte1 = new JLabel(fenster.getSpieler1() + " (" + fenster.getZeichen()[0] + ") ");
punkte1.setBounds(30, 125, 100, 30);
punkteAnzahl1 = new JTextField(zähler);
punkteAnzahl1.setBounds(140, 125, 50, 30);
punkteAnzahl1.setEditable(false);
punkte2 = new JLabel(fenster.getSpieler2() + " (" + fenster.getZeichen()[1] + ") ");
punkte2.setBounds(30, 250, 100, 30);
punkteAnzahl2 = new JTextField(zähler2);
punkteAnzahl2.setBounds(140, 250, 50, 30);
punkteAnzahl2.setEditable(false);
}
public class Händler implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == abbrechen) {
if(JOptionPane.showConfirmDialog(null, "Wollen sie das Spiel wirklich beenden?","Sicher",JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
dispose();
}
}
}
}
}
| true
|
c42684243b8215fb889935b072e579da72283db8
|
Java
|
StuyPulse/newbie-ed
|
/2021/04_oop/elaine_ye/Main.java
|
UTF-8
| 306
| 2.84375
| 3
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
public class Main {
public static void main(String[] args) {
Car shinyCar = new Car("Toyota");
System.out.println(shinyCar);
for (int i = 0; i < 21; i++) {
shinyCar.drive();
}
shinyCar.repair();
for (int i = 0; i < 21; i++) {
shinyCar.drive();
}
}
}
| true
|
a7ca9fa0f259744b72968f983906595e97355d6a
|
Java
|
Raminbrm37/OnlineTicket_Servlet
|
/src/main/java/ir/maktab/dao/AbstractDao.java
|
UTF-8
| 895
| 2.453125
| 2
|
[] |
no_license
|
package ir.maktab.dao;
import javax.persistence.EntityManager;
import ir.maktab.model.IEntity;
public abstract class AbstractDao<E extends IEntity,T> {
protected EntityManager entityManager;
public AbstractDao(EntityManager entityManager) {
this.entityManager = entityManager;
}
public void save(IEntity entity){
entityManager.getTransaction().begin();
entityManager.persist(entity);
entityManager.getTransaction().commit();
}
public void delete(IEntity entity){
// entityManager.getTransaction().begin();
entityManager.remove(entity);
/// entityManager.getTransaction().commit();
}
public void update(IEntity entity){
entityManager.merge(entity);
}
public E loadById(T id){
return entityManager.find(getEntityClass(),id);
}
public abstract Class<E> getEntityClass();
}
| true
|
24e47c5aa12441aef65bc48f34c5bb30bce3bd1c
|
Java
|
rdomloge/catholicon-ms-club
|
/application/src/main/java/com/domloge/catholiconmsclub/ClubController.java
|
UTF-8
| 1,984
| 2.1875
| 2
|
[
"MIT"
] |
permissive
|
package com.domloge.catholiconmsclub;
import java.util.List;
import javax.validation.Valid;
import com.domloge.catholiconmsclublibrary.Club;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import org.reactivestreams.Publisher;
import io.micronaut.http.annotation.Body;
import io.micronaut.http.annotation.Controller;
import io.micronaut.http.annotation.Delete;
import io.micronaut.http.annotation.Get;
import io.micronaut.http.annotation.Patch;
import io.micronaut.http.annotation.Post;
import io.micronaut.http.annotation.QueryValue;
import io.reactivex.Maybe;
import io.reactivex.Single;
@Controller("/clubs")
public class ClubController<T extends Club> {
private final ClubRepository clubRepository;
public ClubController(ClubRepository clubRepository) {
this.clubRepository = clubRepository;
}
@Get("/")
Single<List<Club>> list() {
return clubRepository.list();
}
@Get("/search/findClubByClubIdAndSeasonId")
Maybe<Club> findClubByClubIdAndSeasonId(@QueryValue int clubId, @QueryValue int season) {
return clubRepository.find(clubId, season);
}
@Get("/search/findClubByTeamId")
Maybe<Club> findClubByTeamId(@QueryValue int teamId) {
return clubRepository.findClubByTeamId(teamId);
}
@Get("/search/findClubBySeason")
Single<List<Club>> findClubBySeason(@QueryValue int season) {
return clubRepository.find(season);
}
@Get("/search/countClubBySeason")
Single<Long> countClubBySeason(@QueryValue int season) {
return clubRepository.count(season);
}
@Patch("/")
void updateClub(@Valid @Body T club) {
clubRepository.update(club);
}
@Post("/")
Single<Club> save(@Valid @Body T club) {
return clubRepository.save(club);
}
@Delete("/")
void delete(@QueryValue int clubId, @QueryValue int season) {
clubRepository.delete(clubId, season);
}
}
| true
|
f921a574ba7976ad68a06c3abf83c02416e0f559
|
Java
|
malinGH/teach-interactive-manager
|
/src/main/java/com/teach/manager/teachmanager/manager/student/StudentManager.java
|
UTF-8
| 1,001
| 2.078125
| 2
|
[] |
no_license
|
package com.teach.manager.teachmanager.manager.student;
import com.teach.manager.teachmanager.pojo.Page;
import com.teach.manager.teachmanager.pojo.Query;
import com.teach.manager.teachmanager.pojo.vo.StudentBaseVo;
import com.teach.manager.teachmanager.pojo.vo.StudentVo;
/**
* @program: teach-interactive-manager
* @InterfaceName: StudentManager
* @description: 学生功能的相关处理
* @author: malin
* @create: 2019-04-17 10:10
**/
public interface StudentManager {
/**
* @Description: 获取学生信息
* @Param1: query
* @return: com.teach.manager.teachmanager.pojo.Page<com.teach.manager.teachmanager.pojo.vo.StudentVo>
* @Author: malin
* @Date: 2019-04-17
*/
Page<StudentVo> findStudentInfoByPage(Query<StudentVo> query);
/**
* @Description: 添加学生信息
* @Param1: studentBaseVo
* @return: boolean
* @Author: malin
* @Date: 2019-04-18
*/
boolean addStudentInfo(StudentBaseVo studentBaseVo);
}
| true
|
bab0fd26da3e52c48bdb38260e41afe666a108c6
|
Java
|
aaronjazhiel/testProteux
|
/src/test/BsProteoxUserMails.java
|
UTF-8
| 3,259
| 2.015625
| 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 test;
import java.io.Serializable;
import java.util.Collection;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
/**
*
* @author Aarón Delgado
*/
@Entity
@Table(name = "BS_PROTEOX_USER_MAILS")
@NamedQueries({
@NamedQuery(name = "BsProteoxUserMails.findAll", query = "SELECT b FROM BsProteoxUserMails b")})
public class BsProteoxUserMails implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Basic(optional = false)
@Column(name = "IDUSERMAIL")
private Long idusermail;
@Basic(optional = false)
@Column(name = "MAIL")
private String mail;
@Column(name = "USER_AUTH")
private String userAuth;
@Column(name = "PASS_AUTH")
private String passAuth;
@OneToMany(mappedBy = "idusermail")
private Collection<BsProteox2tradeUsers> bsProteox2tradeUsersCollection;
public BsProteoxUserMails() {
}
public BsProteoxUserMails(Long idusermail) {
this.idusermail = idusermail;
}
public BsProteoxUserMails(Long idusermail, String mail) {
this.idusermail = idusermail;
this.mail = mail;
}
public Long getIdusermail() {
return idusermail;
}
public void setIdusermail(Long idusermail) {
this.idusermail = idusermail;
}
public String getMail() {
return mail;
}
public void setMail(String mail) {
this.mail = mail;
}
public String getUserAuth() {
return userAuth;
}
public void setUserAuth(String userAuth) {
this.userAuth = userAuth;
}
public String getPassAuth() {
return passAuth;
}
public void setPassAuth(String passAuth) {
this.passAuth = passAuth;
}
public Collection<BsProteox2tradeUsers> getBsProteox2tradeUsersCollection() {
return bsProteox2tradeUsersCollection;
}
public void setBsProteox2tradeUsersCollection(Collection<BsProteox2tradeUsers> bsProteox2tradeUsersCollection) {
this.bsProteox2tradeUsersCollection = bsProteox2tradeUsersCollection;
}
@Override
public int hashCode() {
int hash = 0;
hash += (idusermail != null ? idusermail.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof BsProteoxUserMails)) {
return false;
}
BsProteoxUserMails other = (BsProteoxUserMails) object;
if ((this.idusermail == null && other.idusermail != null) || (this.idusermail != null && !this.idusermail.equals(other.idusermail))) {
return false;
}
return true;
}
@Override
public String toString() {
return "test.BsProteoxUserMails[ idusermail=" + idusermail + " ]";
}
}
| true
|
3403d834b37082c5e133981a5fa43569c6190c54
|
Java
|
horacehylee/generator-libgdx
|
/generators/app/templates/sources/core/src/package/ResourceProvider.java
|
UTF-8
| 255
| 1.867188
| 2
|
[
"MIT"
] |
permissive
|
package <%= projectPackage %>;
import javax.inject.Inject;
import javax.inject.Singleton;
@Singleton
public class ResourceProvider {
@Inject
public ResourceProvider() {
}
public String getLogo() {
return "badlogic.jpg";
}
}
| true
|
3b269036d55d786f5798911efb77dcc5157977ab
|
Java
|
yuechen-cynthia/Metro-Madness-JavaProject
|
/metro madness/core/src/com/unimelb/swen30006/metromadness/Simulation.java
|
UTF-8
| 1,676
| 2.875
| 3
|
[] |
no_license
|
package com.unimelb.swen30006.metromadness;
import java.util.ArrayList;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.unimelb.swen30006.metromadness.stations.Station;
import com.unimelb.swen30006.metromadness.tracks.Line;
import com.unimelb.swen30006.metromadness.trains.LargeCargoTrain;
import com.unimelb.swen30006.metromadness.trains.SmallCargoTrain;
import com.unimelb.swen30006.metromadness.trains.Train;
public class Simulation {
public ArrayList<Station> stations;
public ArrayList<Line> lines;
public ArrayList<Train> trains;
public Simulation(String fileName) {
// Create a map reader and read in the file
MapReader m = new MapReader(fileName);
m.process();
// Create a list of lines
this.lines = new ArrayList<Line>();
this.lines.addAll(m.getLines());
// Create a list of stations
this.stations = new ArrayList<Station>();
this.stations.addAll(m.getStations());
// Create a list of trains
this.trains = new ArrayList<Train>();
this.trains.addAll(m.getTrains());
}
// Update all the trains in the simulation
public void update() {
// Update all the trains
for (Train t : this.trains) {
// Update all cargo trains
if ((t instanceof SmallCargoTrain) || (t instanceof LargeCargoTrain)) {
t.cargoUpdate(Gdx.graphics.getDeltaTime());
} else {
// Update all non-cargo trains
t.update(Gdx.graphics.getDeltaTime());
}
}
}
public void render(ShapeRenderer renderer) {
for (Line l : this.lines) {
l.render(renderer);
}
for (Train t : this.trains) {
t.render(renderer);
}
for (Station s : this.stations) {
s.render(renderer);
}
}
}
| true
|
7789ffc9461ec4ca484b1e0ad3068136f4ffbedf
|
Java
|
zelenski/stanford-cpp-library
|
/Archived/Karel/src/stanford/karel/KarelProgram.java
|
UTF-8
| 11,225
| 2.640625
| 3
|
[] |
no_license
|
/*
* This file implements the KarelProgram class.
*
* @author Marty Stepp (based on Eric Roberts version)
* @version 2015/04/05
* - added "Options" menu bar for Ms. Karel mode
* @version 2015/04/01
* - improved scrollbar appearance in error dialogs
* - added "About" menu bar
* @version 2015/03/31
* - commented out unused field 'program'
* - changed to use Swing graphical components
* - improved error dialog to display program stack trace
* - added setStatus method to display program state
*/
package stanford.karel;
import acm.program.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import java.util.*;
import javax.swing.*;
/**
* This class is a subclass of <code><a href="Program.html">Program</a></code>
* that runs a Karel program.
*/
public class KarelProgram extends Program {
/** Directory where *.w Karel world files are found. */
public static final String WORLDS_DIRECTORY = "worlds";
/** File extension for Karel worlds. */
public static final String WORLD_EXTENSION = ".w";
public static final int NORTH = KarelWorld.NORTH;
public static final int EAST = KarelWorld.EAST;
public static final int SOUTH = KarelWorld.SOUTH;
public static final int WEST = KarelWorld.WEST;
public static final int INFINITE = KarelWorld.INFINITE;
public static final int SIMPLE = KarelWorld.SIMPLE;
public static final int FANCY = KarelWorld.FANCY;
public static final Color BLACK = Color.BLACK;
public static final Color BLUE = Color.BLUE;
public static final Color CYAN = Color.CYAN;
public static final Color DARK_GRAY = Color.DARK_GRAY;
public static final Color GRAY = Color.GRAY;
public static final Color GREEN = Color.GREEN;
private static final Color DARK_YELLOW = Color.YELLOW.darker().darker().darker();
private static final Color DARK_GREEN = Color.GREEN.darker().darker();
private static final Color DARK_RED = Color.RED.darker();
// private static final Color DARK_BLUE = Color.BLUE.darker();
public static final Color LIGHT_GRAY = Color.LIGHT_GRAY;
public static final Color MAGENTA = Color.MAGENTA;
public static final Color ORANGE = Color.ORANGE;
public static final Color PINK = Color.PINK;
public static final Color RED = Color.RED;
public static final Color WHITE = Color.WHITE;
public static final Color YELLOW = Color.YELLOW;
private static final String CONFIG_FILE_NAME = "karel-settings.txt";
/* Private state */
private KarelWorld world;
private KarelControlPanel controlPanel;
private KarelErrorDialog errorDialog;
private JLabel statusLabel;
private JCheckBoxMenuItem msKarelItem;
private boolean started;
public static enum State { RUNNING, STOPPED, ERROR };
public Event<State> StateEvent = new Event<State>("StateEvent");
/**
* Creates a new Karel program.
*/
public KarelProgram() {
world = createWorld();
world.setRepaintFlag(false);
world.setDisplayFlag(false);
world.init(10, 10);
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
panel.add(BorderLayout.CENTER, world);
controlPanel = new KarelControlPanel(this);
world.setMonitor(controlPanel);
panel.add(BorderLayout.WEST, controlPanel);
add(panel);
// set up status label
statusLabel = new JLabel("Welcome to Karel!");
statusLabel.setFont(statusLabel.getFont().deriveFont(Font.BOLD));
add(statusLabel, BorderLayout.SOUTH);
validate();
}
/**
* Contains the code to be executed for each specific program subclass. If
* you are defining your own <code>KarelProgram</code> class, you need to
* override the definition of <code>main</code> so that it contains the code
* for your application.
*/
public void main() {
/* Empty */
}
public void setStatus(String status) {
if (status.contains("Running")) {
statusLabel.setForeground(DARK_YELLOW);
} else if (status.contains("due to an error")) {
statusLabel.setForeground(DARK_RED);
} else if (status.contains("Finished")) {
statusLabel.setForeground(DARK_GREEN);
} else {
// put back to default label color
statusLabel.setForeground(new JLabel().getForeground());
}
statusLabel.setText(status);
}
/**
* Returns the <code>KarelWorld</code> object in which Karel lives.
*
* @return The <code>KarelWorld</code> object in which Karel lives
*/
public KarelWorld getWorld() {
return world;
}
/**
* Returns the default directory in which Karel's worlds live.
*
* @return The directory in which Karel's worlds lives
*/
public static String getWorldDirectory() {
String dir = System.getProperty("user.dir");
if (new File(dir, WORLDS_DIRECTORY).isDirectory()) {
dir += File.separator + WORLDS_DIRECTORY;
}
return dir;
}
/**
* Creates the <code>KarelWorld</code> in which Karel lives. Subclasses can
* override this method to create their own <code>KarelWorld</code> types.
*
* @return The <code>World</code> object in which Karel lives
* @noshow student
*/
protected KarelWorld createWorld() {
return new KarelWorld();
}
/**
* Checks to see whether this program has started.
*
* @noshow student
*/
protected boolean isStarted() {
if (world == null || !super.isStarted())
return false;
Dimension size = world.getSize();
return (size != null) && (size.width != 0) && (size.height != 0);
}
protected Karel getKarel() {
return world.getKarel();
}
public void add(Karel karel) {
add(karel, 1, 1, KarelWorld.EAST, KarelWorld.INFINITE);
}
public void add(Karel karel, int x, int y, int dir, int nBeepers) {
karel.setLocation(x, y);
karel.setDirection(dir);
karel.setBeepersInBag(nBeepers);
world.add(karel);
}
public void start(String[] args) {
super.start(args);
}
protected void setStartupObject(Object obj) {
super.setStartupObject(obj);
}
protected void augmentMenuBar() {
// try to set up JMenuBar
try {
ProgramMenuBar bar = getConsole().getMenuBar();
bar.removeAll();
JMenu fileMenu = new JMenu("File");
fileMenu.setMnemonic('F');
JMenuItem quitItem = new JMenuItem("Quit");
quitItem.setMnemonic('Q');
quitItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
stop();
destroy();
setVisible(false);
try {
System.exit(0);
} catch (Exception e) {
// empty
}
}
});
fileMenu.add(quitItem);
JMenu optionsMenu = new JMenu("Options");
optionsMenu.setMnemonic('O');
msKarelItem = new JCheckBoxMenuItem("Ms. Karel");
msKarelItem.setMnemonic('M');
msKarelItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
world.setMsKarel(msKarelItem.isSelected());
saveConfiguration();
}
});
optionsMenu.add(msKarelItem);
JMenu helpMenu = new JMenu("Help");
helpMenu.setMnemonic('H');
JMenuItem aboutItem = new JMenuItem("About Karel...");
aboutItem.setActionCommand("About Karel...");
aboutItem.setMnemonic('A');
aboutItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
JOptionPane.showMessageDialog(KarelProgram.this, Version.ABOUT_MESSAGE);
}
});
helpMenu.add(aboutItem);
bar.add(fileMenu);
bar.add(optionsMenu);
bar.add(helpMenu);
} catch (Exception e) {
// empty
}
}
protected void loadConfiguration(Properties props) {
try {
String tmpDir = System.getProperty("java.io.tmpdir");
if (tmpDir != null) {
File configFile = new File(tmpDir, CONFIG_FILE_NAME);
if (!configFile.exists()) {
return;
}
FileInputStream input = new FileInputStream(configFile);
props.load(input);
input.close();
if (props.containsKey("mskarel")) {
boolean msKarel = Boolean.parseBoolean(String.valueOf(props.get("mskarel")));
msKarelItem.setSelected(msKarel);
world.setMsKarel(msKarel);
}
}
} catch (Exception ex) {
// ex.printStackTrace();
// empty
}
}
protected void saveConfiguration(Properties props) {
try {
String tmpDir = System.getProperty("java.io.tmpdir");
if (tmpDir != null) {
File configFile = new File(tmpDir, CONFIG_FILE_NAME);
props.put("mskarel", String.valueOf(msKarelItem.isSelected()));
FileOutputStream out = new FileOutputStream(configFile);
props.store(out, "Karel configuration file");
out.close();
}
} catch (Exception ex) {
// ex.printStackTrace();
// empty
}
}
public void loadInitialWorld() {
String karelClass = getParameter("karel");
if (karelClass == null) {
Karel karel = (Karel) getStartupObject();
karelClass = karel.getClass().getName();
karelClass = karelClass.substring(karelClass.lastIndexOf(".") + 1);
}
String worldName = getParameter("world");
if (worldName == null)
worldName = karelClass;
try {
URL url = new URL(getCodeBase(), WORLDS_DIRECTORY + File.separator + worldName + WORLD_EXTENSION);
URLConnection connection = url.openConnection();
world.load(new InputStreamReader(connection.getInputStream()));
} catch (Exception ex) {
/* Ignore this error */
}
}
protected void startRun() {
augmentMenuBar();
if (!isAppletMode()) {
loadConfiguration();
}
Karel karel = null;
String karelClass = getParameter("karel");
if (karelClass == null) {
karel = (Karel) getStartupObject();
karelClass = karel.getClass().getName();
karelClass = karelClass.substring(karelClass.lastIndexOf(".") + 1);
} else {
try {
karel = (Karel) Class.forName(karelClass).newInstance();
} catch (Exception ex) {
System.out.println("Exception: " + ex);
}
}
if (karel != null) {
world.add(karel);
setTitle(karelClass);
loadInitialWorld();
}
world.setRepaintFlag(true);
world.setDisplayFlag(true);
world.repaint();
while (true) {
started = false;
synchronized (this) {
while (!started) {
try {
wait();
} catch (InterruptedException ex) {
/* Empty */
}
}
}
Throwable throwable = null;
try {
if (karel == null) {
main();
} else {
karel.run();
setStatus("Finished running.");
}
world.setRepaintFlag(true);
world.repaint();
} catch (Exception ex) {
throwable = ex;
} catch (StackOverflowError err) {
throwable = err;
}
if (throwable == null) {
StateEvent.fire(State.STOPPED);
} else {
setStatus("Halted due to an error.");
StateEvent.fire(State.ERROR);
if (errorDialog == null) {
errorDialog = new KarelErrorDialog(this);
}
String errorMessage = throwable.getMessage();
if (errorMessage == null || errorMessage.isEmpty()) {
errorMessage = "";
if (throwable instanceof StackOverflowError) {
errorMessage = "Infinite method calls.";
}
}
while (!errorMessage.endsWith("\n\n")) {
errorMessage += "\n";
}
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
PrintStream out = new PrintStream(bytes);
throwable.printStackTrace(out);
String stackTrace = bytes.toString();
errorDialog.error(errorMessage, stackTrace);
}
}
}
void signalStarted() {
synchronized (this) {
StateEvent.fire(State.RUNNING);
started = true;
notifyAll();
}
}
}
| true
|
d53e47f53c4ae872e6c4cd5a810625b82c938a8e
|
Java
|
etarakci-hvl/owl
|
/src/main/java/ch/ethz/idsc/sophus/math/Decibel.java
|
UTF-8
| 677
| 2.484375
| 2
|
[] |
no_license
|
// code by ob, jph
package ch.ethz.idsc.sophus.math;
import ch.ethz.idsc.tensor.RealScalar;
import ch.ethz.idsc.tensor.Scalar;
import ch.ethz.idsc.tensor.Tensor;
import ch.ethz.idsc.tensor.sca.Log;
import ch.ethz.idsc.tensor.sca.ScalarUnaryOperator;
public enum Decibel implements ScalarUnaryOperator {
FUNCTION;
// ---
private static final ScalarUnaryOperator LOG10 = Log.base(10);
private static final Scalar _20 = RealScalar.of(20);
@Override
public Scalar apply(Scalar scalar) {
return LOG10.apply(scalar).multiply(_20);
}
@SuppressWarnings("unchecked")
public static <T extends Tensor> T of(T tensor) {
return (T) tensor.map(FUNCTION);
}
}
| true
|
c6d94ccd74cef712f757a63f6fb3076390373634
|
Java
|
doncorley/kpme
|
/pm/impl/src/main/java/org/kuali/kpme/pm/positionreporttype/service/PositionReportTypeServiceImpl.java
|
UTF-8
| 2,596
| 2
| 2
|
[] |
no_license
|
/**
* Copyright 2004-2013 The Kuali Foundation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl2.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kuali.kpme.pm.positionreporttype.service;
import java.util.List;
import org.joda.time.LocalDate;
import org.kuali.kpme.pm.positionreporttype.PositionReportType;
import org.kuali.kpme.pm.positionreporttype.dao.PositionReportTypeDao;
public class PositionReportTypeServiceImpl implements PositionReportTypeService {
private PositionReportTypeDao positionReportTypeDao;
public PositionReportTypeDao getPositionReportTypeDao() {
return positionReportTypeDao;
}
public void setPositionReportTypeDao(PositionReportTypeDao positionReportTypeDao) {
this.positionReportTypeDao = positionReportTypeDao;
}
@Override
public PositionReportType getPositionReportTypeById(String pmPositionReportTypeId) {
return positionReportTypeDao.getPositionReportTypeById(pmPositionReportTypeId);
}
@Override
public List<PositionReportType> getPositionReportTypeList(String positionReportType, String institution, String location, LocalDate asOfDate) {
return positionReportTypeDao.getPositionReportTypeList(positionReportType, institution, location, asOfDate);
}
@Override
public List<PositionReportType> getPositionReportTypeListByType(String positionReportType) {
return positionReportTypeDao.getPositionReportTypeListByType(positionReportType);
}
@Override
public List<PositionReportType> getPrtListWithInstitutionCodeAndDate(String institutionCode, LocalDate asOfDate) {
return positionReportTypeDao.getPrtListWithInstitutionCodeAndDate(institutionCode, asOfDate);
}
@Override
public List<PositionReportType> getPrtListWithLocationAndDate(String location,LocalDate asOfDate) {
return positionReportTypeDao.getPrtListWithLocationAndDate(location, asOfDate);
}
@Override
public PositionReportType getPositionReportType(
String positionReportType, LocalDate asOfDate) {
return positionReportTypeDao.getPositionReportType(positionReportType, asOfDate);
}
}
| true
|
680d3702bb66c957080db7dd35f7ab519e20197b
|
Java
|
lizhongze123/Convention
|
/business/main_module/main_hourglass/src/main/java/com/gz0101/hzwy/hourglass/contract/HourglassOrderContract.java
|
UTF-8
| 435
| 1.578125
| 2
|
[] |
no_license
|
package com.gz0101.hzwy.hourglass.contract;
import com.gz0101.hzwy.baselibrary.mvp.BasePresenter;
import com.gz0101.hzwy.baselibrary.mvp.BaseView;
import com.gz0101.hzwy.baselibrary.request.respone.bean.ShopListBean;
import java.util.List;
public interface HourglassOrderContract {
interface HourglassOrderView extends BaseView {
}
interface HourglassOrderPresenter extends BasePresenter<HourglassOrderView> {
}
}
| true
|
1347b34de29b1489b6fe09cd71cfed5649a0bef7
|
Java
|
MrHusm/motionManageV2
|
/src/main/java/com/manage/model/Banner_App.java
|
UTF-8
| 4,471
| 2.09375
| 2
|
[] |
no_license
|
package com.manage.model;
import java.util.Date;
public class Banner_App {
private Integer id;
private Integer pageType;//1 应用推荐页 2每日福利页
private String name;//广告名称
private Integer type;//方式 1 直投 2 sdk
private Integer appType;//直投广告类型 1 应用推荐 2 图片
private String appName;//应用名称
private String appVersion;//应用版本
private String appIntro;//应用简介
private String img;//图片地址
private String url;//应用地址或图片跳转地址
private String size;//应用大小
private String appPackName;//应用包名
private String sdkInfo;//sdk信息
private Integer repayType;//赠送类型 1铜币 2 代金券
private Integer money;//赠送金额
private Integer cashCouponId;//代金券ID
private String versions;//发布版本
private Integer channelType;//渠道限制 0全部 1仅在 2仅不在
private String channelIds;//发布渠道
private String startDate; //开始日期
private String endDate; //结束日期
private Integer idx;//顺序
private Integer state;//0未开始 1已开始 2已结束
private Date createDate;//创建时间
private Date updateDate;//修改时间
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getPageType() {
return pageType;
}
public void setPageType(Integer pageType) {
this.pageType = pageType;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getType() {
return type;
}
public void setType(Integer type) {
this.type = type;
}
public Integer getAppType() {
return appType;
}
public void setAppType(Integer appType) {
this.appType = appType;
}
public String getAppName() {
return appName;
}
public void setAppName(String appName) {
this.appName = appName;
}
public String getAppVersion() {
return appVersion;
}
public void setAppVersion(String appVersion) {
this.appVersion = appVersion;
}
public String getAppIntro() {
return appIntro;
}
public void setAppIntro(String appIntro) {
this.appIntro = appIntro;
}
public String getImg() {
return img;
}
public void setImg(String img) {
this.img = img;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getSize() {
return size;
}
public void setSize(String size) {
this.size = size;
}
public String getAppPackName() {
return appPackName;
}
public void setAppPackName(String appPackName) {
this.appPackName = appPackName;
}
public String getSdkInfo() {
return sdkInfo;
}
public void setSdkInfo(String sdkInfo) {
this.sdkInfo = sdkInfo;
}
public Integer getRepayType() {
return repayType;
}
public void setRepayType(Integer repayType) {
this.repayType = repayType;
}
public Integer getMoney() {
return money;
}
public void setMoney(Integer money) {
this.money = money;
}
public Integer getCashCouponId() {
return cashCouponId;
}
public void setCashCouponId(Integer cashCouponId) {
this.cashCouponId = cashCouponId;
}
public String getVersions() {
return versions;
}
public void setVersions(String versions) {
this.versions = versions;
}
public String getChannelIds() {
return channelIds;
}
public void setChannelIds(String channelIds) {
this.channelIds = channelIds;
}
public String getStartDate() {
return startDate;
}
public void setStartDate(String startDate) {
this.startDate = startDate;
}
public String getEndDate() {
return endDate;
}
public void setEndDate(String endDate) {
this.endDate = endDate;
}
public Integer getIdx() {
return idx;
}
public void setIdx(Integer idx) {
this.idx = idx;
}
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
public Date getUpdateDate() {
return updateDate;
}
public void setUpdateDate(Date updateDate) {
this.updateDate = updateDate;
}
public Integer getChannelType() {
return channelType;
}
public void setChannelType(Integer channelType) {
this.channelType = channelType;
}
public Integer getState() {
return state;
}
public void setState(Integer state) {
this.state = state;
}
}
| true
|
f1585cbe8ea81adfa1372bfa837ee0c0d118e18a
|
Java
|
leiqjl/leetcode
|
/src/com/leiqjl/SignOfTheProductOfAnArray.java
|
UTF-8
| 475
| 3.25
| 3
|
[] |
no_license
|
package com.leiqjl;
/**
* 1822. Sign of the Product of an Array - Easy
*/
public class SignOfTheProductOfAnArray {
//Constraints:
//
//1 <= nums.length <= 1000
//-100 <= nums[i] <= 100
public int arraySign(int[] nums) {
int result = 1;
for (int num : nums) {
if (num == 0) {
return 0;
} else if (num < 0) {
result = -result;
}
}
return result;
}
}
| true
|
57174abe680725b6d5907252cd6b524e9b1589fc
|
Java
|
paragon94/SESTI
|
/src/main/java/controller/ZapiszWydzialController.java
|
UTF-8
| 1,815
| 2.59375
| 3
|
[] |
no_license
|
package main.java.controller;
import javafx.scene.layout.AnchorPane;
import main.helper.AlertBox;
import main.java.model.entity.Wydzial;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Alert;
import javafx.scene.control.TextField;
public class ZapiszWydzialController {
@FXML
private AnchorPane zapiszWydzialOkno;
@FXML
private TextField nazwa;
@FXML
private TextField symbol;
@FXML
private TextField numerKonta;
@FXML
private TextField uwagi;
private int id;
private String tekst;
public void setWydzial(Wydzial wydzial) {
nazwa.setText(wydzial.getNazwa());
symbol.setText(wydzial.getSymbol());
numerKonta.setText(wydzial.getNumerKonta());
uwagi.setText(wydzial.getUwagi());
id = wydzial.getId();
}
@FXML
void zapiszWydzialAction(ActionEvent e) {
if (nazwa.getText().isEmpty() || symbol.getText().isEmpty() || numerKonta.getText().isEmpty()) {
new AlertBox("Poniższe pola są wymagane:\nNazwa\nSymbol\nNumer konta",
"Błąd", new Alert(Alert.AlertType.ERROR));
} else {
Wydzial wydzial = new Wydzial(nazwa.getText(), symbol.getText(), numerKonta.getText(), uwagi.getText());
wydzial.setId(id);
wydzial.zapisz();
new AlertBox(tekst, "Uwaga", new Alert(Alert.AlertType.INFORMATION));
zapiszWydzialOkno.getScene().getWindow().hide();
}
}
public void czyscWydzialAction() {
czyscWydzial();
}
private void czyscWydzial() {
nazwa.setText("");
symbol.setText("");
numerKonta.setText("");
uwagi.setText("");
}
void setTekst(String tekst) {
this.tekst = tekst;
}
}
| true
|
d2955fd6a1e535ae0fcfdf1fa12b07f156888ff1
|
Java
|
azanaera/toggle-isbtf
|
/generated/pcftest/DesktopQueuedActivitiesLV.java
|
UTF-8
| 16,686
| 1.507813
| 2
|
[] |
no_license
|
package pcftest;
import gw.lang.SimplePropertyProcessing;
import gw.smoketest.platform.web.BooleanValueElement;
import gw.smoketest.platform.web.DateElement;
import gw.smoketest.platform.web.IteratorEntriesWithPaging;
import gw.smoketest.platform.web.IteratorEntryCheckboxElement;
import gw.smoketest.platform.web.OptionElement;
import gw.smoketest.platform.web.PCFElement;
import gw.smoketest.platform.web.PCFElementId;
import gw.smoketest.platform.web.PCFLocation;
import gw.smoketest.platform.web.PagingElement;
import gw.smoketest.platform.web.RowElement;
import gw.smoketest.platform.web.SelectElement;
import gw.smoketest.platform.web.SelectorCellElement;
import gw.smoketest.platform.web.ValueElement;
import gw.testharness.ISmokeTest;
import javax.annotation.processing.Generated;
import pcftest.DesktopQueuedActivitiesLV.AssignmentDateHeader;
import pcftest.DesktopQueuedActivitiesLV.CaseIDHeader;
import pcftest.DesktopQueuedActivitiesLV.DueDateHeader;
import pcftest.DesktopQueuedActivitiesLV.EscalatedHeader;
import pcftest.DesktopQueuedActivitiesLV.ExposureHeader;
import pcftest.DesktopQueuedActivitiesLV.ExternallyOwnedHeader;
import pcftest.DesktopQueuedActivitiesLV.InsuredHeader;
import pcftest.DesktopQueuedActivitiesLV.NewActivityHeader;
import pcftest.DesktopQueuedActivitiesLV.PriorityHeader;
import pcftest.DesktopQueuedActivitiesLV.SubjectHeader;
import pcftest.DesktopQueuedActivitiesLV._ListPaging;
import pcftest.DesktopQueuedActivitiesLV.entry;
import pcftest.DesktopQueuedActivitiesLV.entry.CaseID;
import pcftest.DesktopQueuedActivitiesLV.entry.Insured;
import pcftest.DesktopQueuedActivitiesLV.entry.Subject;
import pcftest.DesktopQueuedActivitiesLV.entry._Select;
import pcftest.DesktopQueuedActivitiesLV.entry._ViewDetail;
@SimplePropertyProcessing
@Generated(comments = "config/web/pcf/desktop/queues/DesktopQueuedActivitiesLV.pcf", date = "", value = "com.guidewire.pcfgen.PCFClassGenerator")
public class DesktopQueuedActivitiesLV extends PCFElement {
public final static String CHECKSUM = "a4619c81df206c7a0fdec2b9292c9815";
public DesktopQueuedActivitiesLV(ISmokeTest helper, PCFElementId componentId) {
super(helper, componentId);
}
public AssignmentDateHeader getAssignmentDateHeader() {
return getOrCreateProperty("AssignmentDateHeader", "AssignmentDateHeader", gw.smoketest.platform.web.PCFElementId.PCFElementScope.ListViewHeader, pcftest.DesktopQueuedActivitiesLV.AssignmentDateHeader.class);
}
public CaseIDHeader getCaseIDHeader() {
return getOrCreateProperty("CaseIDHeader", "CaseIDHeader", gw.smoketest.platform.web.PCFElementId.PCFElementScope.ListViewHeader, pcftest.DesktopQueuedActivitiesLV.CaseIDHeader.class);
}
public DueDateHeader getDueDateHeader() {
return getOrCreateProperty("DueDateHeader", "DueDateHeader", gw.smoketest.platform.web.PCFElementId.PCFElementScope.ListViewHeader, pcftest.DesktopQueuedActivitiesLV.DueDateHeader.class);
}
public EscalatedHeader getEscalatedHeader() {
return getOrCreateProperty("EscalatedHeader", "EscalatedHeader", gw.smoketest.platform.web.PCFElementId.PCFElementScope.ListViewHeader, pcftest.DesktopQueuedActivitiesLV.EscalatedHeader.class);
}
public ExposureHeader getExposureHeader() {
return getOrCreateProperty("ExposureHeader", "ExposureHeader", gw.smoketest.platform.web.PCFElementId.PCFElementScope.ListViewHeader, pcftest.DesktopQueuedActivitiesLV.ExposureHeader.class);
}
public ExternallyOwnedHeader getExternallyOwnedHeader() {
return getOrCreateProperty("ExternallyOwnedHeader", "ExternallyOwnedHeader", gw.smoketest.platform.web.PCFElementId.PCFElementScope.ListViewHeader, pcftest.DesktopQueuedActivitiesLV.ExternallyOwnedHeader.class);
}
public InsuredHeader getInsuredHeader() {
return getOrCreateProperty("InsuredHeader", "InsuredHeader", gw.smoketest.platform.web.PCFElementId.PCFElementScope.ListViewHeader, pcftest.DesktopQueuedActivitiesLV.InsuredHeader.class);
}
public NewActivityHeader getNewActivityHeader() {
return getOrCreateProperty("NewActivityHeader", "NewActivityHeader", gw.smoketest.platform.web.PCFElementId.PCFElementScope.ListViewHeader, pcftest.DesktopQueuedActivitiesLV.NewActivityHeader.class);
}
public PriorityHeader getPriorityHeader() {
return getOrCreateProperty("PriorityHeader", "PriorityHeader", gw.smoketest.platform.web.PCFElementId.PCFElementScope.ListViewHeader, pcftest.DesktopQueuedActivitiesLV.PriorityHeader.class);
}
public SubjectHeader getSubjectHeader() {
return getOrCreateProperty("SubjectHeader", "SubjectHeader", gw.smoketest.platform.web.PCFElementId.PCFElementScope.ListViewHeader, pcftest.DesktopQueuedActivitiesLV.SubjectHeader.class);
}
public IteratorEntryCheckboxElement get_Checkbox() {
return getOrCreateProperty("_Checkbox", "_Checkbox", null, gw.smoketest.platform.web.IteratorEntryCheckboxElement.class);
}
@SuppressWarnings(value = "unchecked")
public IteratorEntriesWithPaging<entry> get_Entries() {
return getOrCreateEntries(gw.smoketest.platform.web.PCFElementId.PCFElementScope.ListViewRowIteratorEntry, pcftest.DesktopQueuedActivitiesLV.entry.class, gw.smoketest.platform.web.IteratorEntriesWithPaging.class);
}
public _ListPaging get_ListPaging() {
return getOrCreateProperty("_ListPaging", "_ListPaging", null, pcftest.DesktopQueuedActivitiesLV._ListPaging.class);
}
@SimplePropertyProcessing
@Generated(comments = "config/web/pcf/desktop/queues/DesktopQueuedActivitiesLV.pcf", date = "", value = "com.guidewire.pcfgen.PCFClassGenerator")
public static class AssignmentDateHeader extends ValueElement {
public AssignmentDateHeader(ISmokeTest helper, PCFElementId componentId) {
super(helper, componentId);
}
public PCFLocation click() {
return clickThis(gw.smoketest.platform.web.PCFLocation.class);
}
}
@SimplePropertyProcessing
@Generated(comments = "config/web/pcf/desktop/queues/DesktopQueuedActivitiesLV.pcf", date = "", value = "com.guidewire.pcfgen.PCFClassGenerator")
public static class CaseIDHeader extends ValueElement {
public CaseIDHeader(ISmokeTest helper, PCFElementId componentId) {
super(helper, componentId);
}
public PCFLocation click() {
return clickThis(gw.smoketest.platform.web.PCFLocation.class);
}
}
@SimplePropertyProcessing
@Generated(comments = "config/web/pcf/desktop/queues/DesktopQueuedActivitiesLV.pcf", date = "", value = "com.guidewire.pcfgen.PCFClassGenerator")
public static class DueDateHeader extends ValueElement {
public DueDateHeader(ISmokeTest helper, PCFElementId componentId) {
super(helper, componentId);
}
public PCFLocation click() {
return clickThis(gw.smoketest.platform.web.PCFLocation.class);
}
}
@SimplePropertyProcessing
@Generated(comments = "config/web/pcf/desktop/queues/DesktopQueuedActivitiesLV.pcf", date = "", value = "com.guidewire.pcfgen.PCFClassGenerator")
public static class EscalatedHeader extends ValueElement {
public EscalatedHeader(ISmokeTest helper, PCFElementId componentId) {
super(helper, componentId);
}
public PCFLocation click() {
return clickThis(gw.smoketest.platform.web.PCFLocation.class);
}
}
@SimplePropertyProcessing
@Generated(comments = "config/web/pcf/desktop/queues/DesktopQueuedActivitiesLV.pcf", date = "", value = "com.guidewire.pcfgen.PCFClassGenerator")
public static class ExposureHeader extends ValueElement {
public ExposureHeader(ISmokeTest helper, PCFElementId componentId) {
super(helper, componentId);
}
public PCFLocation click() {
return clickThis(gw.smoketest.platform.web.PCFLocation.class);
}
}
@SimplePropertyProcessing
@Generated(comments = "config/web/pcf/desktop/queues/DesktopQueuedActivitiesLV.pcf", date = "", value = "com.guidewire.pcfgen.PCFClassGenerator")
public static class ExternallyOwnedHeader extends ValueElement {
public ExternallyOwnedHeader(ISmokeTest helper, PCFElementId componentId) {
super(helper, componentId);
}
public PCFLocation click() {
return clickThis(gw.smoketest.platform.web.PCFLocation.class);
}
}
@SimplePropertyProcessing
@Generated(comments = "config/web/pcf/desktop/queues/DesktopQueuedActivitiesLV.pcf", date = "", value = "com.guidewire.pcfgen.PCFClassGenerator")
public static class InsuredHeader extends ValueElement {
public InsuredHeader(ISmokeTest helper, PCFElementId componentId) {
super(helper, componentId);
}
public PCFLocation click() {
return clickThis(gw.smoketest.platform.web.PCFLocation.class);
}
}
@SimplePropertyProcessing
@Generated(comments = "config/web/pcf/desktop/queues/DesktopQueuedActivitiesLV.pcf", date = "", value = "com.guidewire.pcfgen.PCFClassGenerator")
public static class NewActivityHeader extends ValueElement {
public NewActivityHeader(ISmokeTest helper, PCFElementId componentId) {
super(helper, componentId);
}
public PCFLocation click() {
return clickThis(gw.smoketest.platform.web.PCFLocation.class);
}
}
@SimplePropertyProcessing
@Generated(comments = "config/web/pcf/desktop/queues/DesktopQueuedActivitiesLV.pcf", date = "", value = "com.guidewire.pcfgen.PCFClassGenerator")
public static class PriorityHeader extends ValueElement {
public PriorityHeader(ISmokeTest helper, PCFElementId componentId) {
super(helper, componentId);
}
public PCFLocation click() {
return clickThis(gw.smoketest.platform.web.PCFLocation.class);
}
}
@SimplePropertyProcessing
@Generated(comments = "config/web/pcf/desktop/queues/DesktopQueuedActivitiesLV.pcf", date = "", value = "com.guidewire.pcfgen.PCFClassGenerator")
public static class SubjectHeader extends ValueElement {
public SubjectHeader(ISmokeTest helper, PCFElementId componentId) {
super(helper, componentId);
}
public PCFLocation click() {
return clickThis(gw.smoketest.platform.web.PCFLocation.class);
}
}
@SimplePropertyProcessing
@Generated(comments = "config/web/pcf/desktop/queues/DesktopQueuedActivitiesLV.pcf", date = "", value = "com.guidewire.pcfgen.PCFClassGenerator")
public static class _ListPaging extends PagingElement {
public _ListPaging(ISmokeTest helper, PCFElementId componentId) {
super(helper, componentId);
}
public PCFLocation click() {
return clickThis(gw.smoketest.platform.web.PCFLocation.class);
}
}
@SimplePropertyProcessing
@Generated(comments = "config/web/pcf/desktop/queues/DesktopQueuedActivitiesLV.pcf", date = "", value = "com.guidewire.pcfgen.PCFClassGenerator")
public static class entry extends RowElement {
public entry(ISmokeTest helper, PCFElementId componentId) {
super(helper, componentId);
}
public DateElement getAssignmentDate() {
return getOrCreateProperty("AssignmentDate", "AssignmentDate", null, gw.smoketest.platform.web.DateElement.class);
}
public CaseID getCaseID() {
return getOrCreateProperty("CaseID", "CaseID", null, pcftest.DesktopQueuedActivitiesLV.entry.CaseID.class);
}
public DateElement getDueDate() {
return getOrCreateProperty("DueDate", "DueDate", null, gw.smoketest.platform.web.DateElement.class);
}
public BooleanValueElement getEscalated() {
return getOrCreateProperty("Escalated", "Escalated", null, gw.smoketest.platform.web.BooleanValueElement.class);
}
public ValueElement getExposure() {
return getOrCreateProperty("Exposure", "Exposure", null, gw.smoketest.platform.web.ValueElement.class);
}
public BooleanValueElement getExternallyOwned() {
return getOrCreateProperty("ExternallyOwned", "ExternallyOwned", null, gw.smoketest.platform.web.BooleanValueElement.class);
}
public Insured getInsured() {
return getOrCreateProperty("Insured", "Insured", null, pcftest.DesktopQueuedActivitiesLV.entry.Insured.class);
}
public BooleanValueElement getNewActivity() {
return getOrCreateProperty("NewActivity", "NewActivity", null, gw.smoketest.platform.web.BooleanValueElement.class);
}
public pcftest.DesktopQueuedActivitiesLV.entry.Priority getPriority() {
return getOrCreateProperty("Priority", "Priority", null, pcftest.DesktopQueuedActivitiesLV.entry.Priority.class);
}
public Subject getSubject() {
return getOrCreateProperty("Subject", "Subject", null, pcftest.DesktopQueuedActivitiesLV.entry.Subject.class);
}
public IteratorEntryCheckboxElement get_Checkbox() {
return getOrCreateProperty("_Checkbox", "_Checkbox", null, gw.smoketest.platform.web.IteratorEntryCheckboxElement.class);
}
public _Select get_Select() {
return getOrCreateProperty("_Select", "_Select", null, pcftest.DesktopQueuedActivitiesLV.entry._Select.class);
}
public _ViewDetail get_ViewDetail() {
return getOrCreateProperty("_ViewDetail", "_ViewDetail", null, pcftest.DesktopQueuedActivitiesLV.entry._ViewDetail.class);
}
@SimplePropertyProcessing
@Generated(comments = "config/web/pcf/desktop/queues/DesktopQueuedActivitiesLV.pcf", date = "", value = "com.guidewire.pcfgen.PCFClassGenerator")
public static class CaseID extends ValueElement {
public CaseID(ISmokeTest helper, PCFElementId componentId) {
super(helper, componentId);
}
public PCFLocation click() {
return clickThis(gw.smoketest.platform.web.PCFLocation.class);
}
}
@SimplePropertyProcessing
@Generated(comments = "config/web/pcf/desktop/queues/DesktopQueuedActivitiesLV.pcf", date = "", value = "com.guidewire.pcfgen.PCFClassGenerator")
public static class Insured extends ValueElement {
public Insured(ISmokeTest helper, PCFElementId componentId) {
super(helper, componentId);
}
public ClaimContactDetailPopup click() {
return clickThis(pcftest.ClaimContactDetailPopup.class);
}
}
@SimplePropertyProcessing
@Generated(comments = "config/web/pcf/desktop/queues/DesktopQueuedActivitiesLV.pcf", date = "", value = "com.guidewire.pcfgen.PCFClassGenerator")
public static class Priority extends SelectElement {
public Priority(ISmokeTest helper, PCFElementId componentId) {
super(helper, componentId);
}
public OptionElement getOptionByTypeKey(typekey.Priority arg) {
return getOptionByValue(arg == null ? null : arg.getCode());
}
public typekey.Priority getTypeKeyValue() {
String myValue = getValue();return myValue == null || myValue.isEmpty() ? null : typekey.Priority.getTypeKey(myValue);
}
public void setTypeKeyValue(typekey.Priority arg) {
setValue(arg == null ? null : arg.getCode());
}
}
@SimplePropertyProcessing
@Generated(comments = "config/web/pcf/desktop/queues/DesktopQueuedActivitiesLV.pcf", date = "", value = "com.guidewire.pcfgen.PCFClassGenerator")
public static class Subject extends ValueElement {
public Subject(ISmokeTest helper, PCFElementId componentId) {
super(helper, componentId);
}
public PCFLocation click() {
return clickThis(gw.smoketest.platform.web.PCFLocation.class);
}
}
@SimplePropertyProcessing
@Generated(comments = "config/web/pcf/desktop/queues/DesktopQueuedActivitiesLV.pcf", date = "", value = "com.guidewire.pcfgen.PCFClassGenerator")
public static class _Select extends SelectorCellElement {
public _Select(ISmokeTest helper, PCFElementId componentId) {
super(helper, componentId);
}
public PCFLocation click() {
return clickThis(gw.smoketest.platform.web.PCFLocation.class);
}
}
@SimplePropertyProcessing
@Generated(comments = "config/web/pcf/desktop/queues/DesktopQueuedActivitiesLV.pcf", date = "", value = "com.guidewire.pcfgen.PCFClassGenerator")
public static class _ViewDetail extends BooleanValueElement {
public _ViewDetail(ISmokeTest helper, PCFElementId componentId) {
super(helper, componentId);
}
public PCFLocation click() {
return clickThis(gw.smoketest.platform.web.PCFLocation.class);
}
}
}
}
| true
|
21c9d0d5e09934ad09afb8bd9f479fd6398239d7
|
Java
|
AliRifaiBedir/Android_Codes
|
/AndroidXMLRssReader/app/src/main/java/com/example/androidxmlrssreader/MainActivity.java
|
UTF-8
| 9,864
| 2.15625
| 2
|
[] |
no_license
|
package com.example.androidxmlrssreader;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
public class MainActivity extends AppCompatActivity {
Context context = this;
ListView listView;
ArrayList<String> xmlList = new ArrayList<>();
ArrayList<String> xmlLink = new ArrayList<>();
ArrayList<String> xmlImg = new ArrayList<>();
/*Rss reader için bilinen bir siteye git en başta veya
en sonda Rss tıkla.
Rss:Yeni eklenen içeriğe kolayca ulaşabilmek.Mesela
o siteye yeni bir haber,makale düştüğünde sana hemen haber
geliyor.
*/
/*Biz şimdi son dakika RSS almak isityoruz
BUrada iki aktivity var.Listview de btün başlık
bütün haberler listelensin.Fakat nasıl listelensin
bunu listte custom olarak solda haberin resmi
sağda haberin başlığı.A
Aynı zamanda habere tıkladığğımızda da habere gönderecek
yani linkini de almamız lazım.
1)İMAGE
2)TİTLE
3)LİNK
bilgilerine ulaşmamız lazım
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new arkaPlanIsleri().execute();
//Bunu en son yapıyotuz
listView = findViewById(R.id.list);
//Burada listelenen elemana tıklayınca tıkalanan habere gönderecek
//Bu yüzden xmlLink çalıştırmamız lazım
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Burada listelenen elemana tıklayınca tıkalanan habere gönderecek
//Bu yüzden xmlLink çalıştırmamız lazım.Bütn bilgiler arraylist
//halinde dönmesi lazım çünkü eleman sayısnı bilmiyoruz
Uri link = Uri.parse(xmlLink.get(position));
Intent opernBrowser = new Intent(Intent.ACTION_VIEW, link);
startActivity(opernBrowser);
//Böylece haber geldiğimde habere tıkaldığımzda haberre gidecez
}
});
}
//Biz bu sınıfı customAdpetre olacak layoutInflater ile ulaşıp özellştircez
public class MyCustomAdapter extends ArrayAdapter<String> {
public MyCustomAdapter(@NonNull Context context, int textViewResourceId, @NonNull ArrayList<String> xmlList) {
super(context, textViewResourceId, xmlList);
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
View row = convertView;
if (row == null) {
LayoutInflater layoutInflater = getLayoutInflater();
row = layoutInflater.inflate(R.layout.list, parent, false);
//(hangi liste,ViewGroup,false)
//Böylece xmlList teki list biizm row oldu
}
TextView textView = row.findViewById(R.id.text);
textView.setText(xmlList.get(position));
//Pozisyonuyla gelen elemanı gösteiyor
ImageView imageView = row.findViewById(R.id.img);
imageView.setImageResource(R.mipmap.ic_launcher_round);
return row;
}
}
public class arkaPlanIsleri extends AsyncTask<Void, Void, Void> {
ProgressDialog dialog = new ProgressDialog(context);
@Override
protected void onPreExecute() {
super.onPreExecute();
dialog.setMessage("Yükleniyor");
dialog.show();
//Haberler gelmeden önce bu çıkacak
}
@Override
protected Void doInBackground(Void... params) {
xmlList = getListFromXml("https://www.milliyet.com.tr/rss/rssnew/sondakikarss.xml");
//Siteinin adresini kopyaladık yani string gönderdik ve bize dizi döndürdü
xmlLink = getListFromXml("https://www.milliyet.com.tr/rss/rssnew/sondakikarss.xml");
return null;
// xmlImg=
}
@Override
protected void onPostExecute(Void o) {
//İşelem bittikten sonra
MyCustomAdapter adapter = new MyCustomAdapter(context, R.layout.list, xmlList);
listView.setAdapter(adapter);
dialog.dismiss();
super.onPostExecute(o);
}
}
public ArrayList<String> getListFromXml(String STRNG) {
//sTRİNG DEĞERİ BURDA BİZİM URL ASLINDA
ArrayList<String> list = new ArrayList<>();
try {
URL url = new URL(STRNG);
DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
//Ayrıştırıcı çağıramya çalışıyoruz
DocumentBuilder dBuilder = dfactory.newDocumentBuilder();
Document document = dBuilder.parse(new InputSource(url.openStream()));
//Dönen değer docement olduğu için değişken tanımladık
document.getDocumentElement().normalize();
//XML den bilgi çekerken üstteki 4 lodu kullanıyoruz
//daha sonra for ile elemanalra ulaşacaz
NodeList nodeListItem = document.getElementsByTagName("item");
//Burada bütün ıtemları çekiyoruz şimdi for ile title bilgisine ulaşalım
for (int i = 0; i < nodeListItem.getLength(); i++) {
Node node = nodeListItem.item(i);
//Böylece ilk elemanı aldık
Element elementMain = (Element) node;
//node çevirdik
NodeList nodeListTitle = elementMain.getElementsByTagName("title");
//Böylece item içindeki hangi tagi alacağımızı söylyırz
Element elementTitle = (Element) nodeListTitle.item(0);
//Böylece elemtTitleda verimiz bulunuyor
list.add(elementTitle.getChildNodes().item(0).getNodeValue());
//bÖYLECE DEĞERİ arrayliste attık
//Burada item içinde dolaşıp tittle içindeki ilk veriyi
//alıp diziye ekliyor ve bu metod geri diziyi döndürüüyr
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return list;//En son bunu yaptık
}
public ArrayList<String> getListLinkFromXml(String STRNG) {
//sTRİNG DEĞERİ BURDA BİZİM URL ASLINDA
//Burada da aynı kodu kopyaladık ve ismi değiştirdik
//amacımız item içindeki link bilgisine ulaşacaz
ArrayList<String> list = new ArrayList<>();
try {
URL url = new URL(STRNG);
DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
//Ayrıştırıcı çağıramya çalışıyoruz
DocumentBuilder dBuilder = dfactory.newDocumentBuilder();
Document document = dBuilder.parse(new InputSource(url.openStream()));
//Dönen değer docement olduğu için değişken tanımladık
document.getDocumentElement().normalize();
//XML den bilgi çekerken üstteki 4 lodu kullanıyoruz
//daha sonra for ile elemanalra ulaşacaz
NodeList nodeListItem = document.getElementsByTagName("item");
//Burada bütün ıtemları çekiyoruz şimdi for ile title bilgisine ulaşalım
for (int i = 0; i < nodeListItem.getLength(); i++) {
Node node = nodeListItem.item(i);
//Böylece ilk elemanı aldık
Element elementMain = (Element) node;
//node çevirdik
NodeList nodeListTitle = elementMain.getElementsByTagName("link");
//Böylece item içindeki hangi link alacağımızı söylyırz
Element elementTitle = (Element) nodeListTitle.item(0);
//Böylece elemtTitleda verimiz bulunuyor
list.add(elementTitle.getChildNodes().item(0).getNodeValue());
//bÖYLECE DEĞERİ arrayliste attık
//Burada item içinde dolaşıp tittle içindeki ilk veriyi
//alıp diziye ekliyor ve bu metod geri diziyi döndürüüyr
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return list;//En son bunu yaptık
}
}
| true
|
3fa80f7ef35dd26dae5a9fbe47b7519cf7a60e29
|
Java
|
headwirecom/peregrine-cms
|
/platform/commons/src/main/java/com/peregrine/commons/concurrent/DeBouncer.java
|
UTF-8
| 2,446
| 3.28125
| 3
|
[
"Apache-2.0"
] |
permissive
|
package com.peregrine.commons.concurrent;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
* Found at <a href=
* "https://stackoverflow.com/questions/4742210/implementing-debounce-in-java">Stack
* Overflow</a>
*/
public final class DeBouncer<Argument> implements Callback<Argument> {
private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
private final ConcurrentHashMap<Argument, TimerTask> delayedTasks = new ConcurrentHashMap<Argument, TimerTask>();
private final Callback<Argument> callback;
private final int interval;
private final TimeUnit timeUnit;
public DeBouncer(final Callback<Argument> callback, final int interval, final TimeUnit timeUnit) {
this.callback = callback;
this.interval = interval;
this.timeUnit = timeUnit;
}
public DeBouncer(final Callback<Argument> callback, final int interval) {
this(callback, interval, TimeUnit.MILLISECONDS);
}
public void call(final Argument key) {
final TimerTask task = new TimerTask(key);
TimerTask prev;
do {
prev = delayedTasks.putIfAbsent(key, task);
if (prev == null) {
scheduler.schedule(task, interval, timeUnit);
}
} while (prev != null && !prev.extend());
}
public Set<Argument> terminate() {
scheduler.shutdownNow();
return delayedTasks.keySet();
}
/** The task that wakes up when the wait time elapses */
private final class TimerTask implements Runnable {
private final Object lock = new Object();
private final Argument key;
private long dueTime;
public TimerTask(final Argument key) {
this.key = key;
extend();
}
public boolean extend() {
synchronized (lock) {
if (dueTime < 0) { // Task has been shutdown
return false;
}
dueTime = System.currentTimeMillis() + interval;
return true;
}
}
public void run() {
synchronized (lock) {
final long remaining = dueTime - System.currentTimeMillis();
if (remaining > 0) { // Re-schedule task
scheduler.schedule(this, remaining, timeUnit);
} else { // Mark as terminated and invoke callback
dueTime = -1;
try {
callback.call(key);
} finally {
delayedTasks.remove(key);
}
}
}
}
}
}
| true
|
1e9a33ff76d7cf8b6942e2a3ebd26a81e5bcd5b2
|
Java
|
pechoutmatej/ALG2_codes
|
/zHodin/Intro_oop/src/cz/tul/alg/matpech/oop/Point.java
|
UTF-8
| 1,212
| 3.640625
| 4
|
[] |
no_license
|
package cz.tul.alg.matpech.oop;
public class Point {
//data
private double x;
private double y;
//constructor
public Point()
{
}
public Point(double x, double y){
this.x = x;
this.y = y;
}
//setter
public void setX(double x){
this.x = x;
}
public void setY(double y){
this.y = y;
}
//getter
public double getX(){
return x;
}
public double getY(){
return y;
}
//methods
public double getDistance(){
return Math.sqrt(x*x + y*y);
}
public double pointToPointDistance(Point a, Point b)
{
double fBracket = b.getX() - a.getX();
double sBracket = b.getY() - a.getY();
double result = Math.sqrt(fBracket*fBracket + sBracket*sBracket);
return Math.abs(result);
}
public double pointDistance(Point b){
double fBracket = b.x - x;
double sBracket = b.y - y;
double result = Math.sqrt(fBracket*fBracket + sBracket*sBracket);
return Math.abs(result);
}
public String toString(){
return "x=" + x + ", y=" + y;
}
}
| true
|
84973f3b925594b66259f26774e5ec81438d158b
|
Java
|
YuejunChen/TiscketTest
|
/app/src/main/java/test/study/select_city/fragment/FutOrderFragment.java
|
UTF-8
| 1,538
| 2.109375
| 2
|
[
"Apache-2.0"
] |
permissive
|
package test.study.select_city.fragment;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
import test.study.select_city.R;
import test.study.select_city.adapter.TiscketAdapter;
import test.study.select_city.bean.Ticket;
/**
* Created by Mr.Chen on 2017/8/27.
*/
public class FutOrderFragment extends Fragment {
private List<Ticket> ticketList = new ArrayList<Ticket>();
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
super.onCreateView(inflater, container, savedInstanceState);
View view = inflater.inflate(R.layout.activity_hisorder, container,false);
TiscketAdapter adapter = new TiscketAdapter(getActivity(), R.layout.ticket_order, ticketList);
ListView listView = (ListView)view. findViewById(R.id.list_view);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Ticket ticket= ticketList.get(position);
}
});
return view;
}
@Override
public void onActivityCreated(Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
}
}
| true
|
fa94402e04515867749b4ab9b0d8b36621a2e9ba
|
Java
|
urcandenisa/Software-Programming
|
/BankOfAmerica/src/main/java/presentation/controller/EmployeeUpDelController.java
|
UTF-8
| 3,367
| 2.53125
| 3
|
[] |
no_license
|
package presentation.controller;
import businessLogic.AccountBusiness;
import model.Account;
import model.Client;
import presentation.view.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
public class EmployeeUpDelController {
private EmployeeUpdateDelete employeeUpdateDelete;
private EmployeeRead employeeRead;
private EmployeeUpdateRegister employeeUpdateRegister;
private AccountsRead accountsRead;
private TransferMoney transferMoney;
private AccountBusiness accountBusiness;
private PayBills payBills;
public EmployeeUpDelController(EmployeeUpdateDelete employeeUpdateDelete, EmployeeRead employeeRead, EmployeeUpdateRegister employeeUpdateRegister, AccountsRead accountsRead, TransferMoney transferMoney, PayBills payBills, AccountBusiness accountBusiness){
this.employeeUpdateDelete = employeeUpdateDelete;
this.employeeRead = employeeRead;
this.accountsRead = accountsRead;
this.employeeUpdateRegister = employeeUpdateRegister;
this.transferMoney = transferMoney;
this.payBills = payBills;
this.accountBusiness = accountBusiness;
employeeUpdateDelete.addActionListener(new ButtonListener());
}
class ButtonListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
Client client = (Client) employeeUpdateDelete.getShowEmployee().getModel().getElementAt(0);
List<Account> accounts = accountBusiness.searchAfter("personalNumericalCode",client.getPersonalNumericalCode());
if(e.getSource() == employeeUpdateDelete.getBack()){
employeeUpdateDelete.resetValues();
employeeUpdateDelete.setVisible(false);
employeeRead.setVisible(true);
employeeRead.resetValues();
}
if(e.getSource() == employeeUpdateDelete.getUpdate()){
employeeUpdateDelete.setVisible(false);
employeeUpdateRegister.setProceed("Complete at least one field in order to proceed:");
employeeUpdateRegister.setVisible(true);
}
if(e.getSource() == employeeUpdateDelete.getShowAccounts()){
employeeUpdateDelete.setVisible(false);
accountsRead.resetValues();
// Client client = (Client) employeeUpdateDelete.getShowEmployee().getModel().getElementAt(0);
// List<Account> accounts = accountBussiness.searchAfter("personalNumericalCode",client.getPersonalNumericalCode());
int size = accounts == null ? 0 : accounts.size();
accountsRead.setFound("We found " + size + " matching(s):");
accountsRead.setFoundAccounts(accounts);
accountsRead.setVisible(true);
}
if(e.getSource() == employeeUpdateDelete.getTransferMoney()){
employeeUpdateDelete.setVisible(false);
transferMoney.setFoundAccounts(accounts);
transferMoney.setVisible(true);
}
if(e.getSource() == employeeUpdateDelete.getPayBills()){
employeeUpdateDelete.setVisible(false);
payBills.setFoundAccounts(accounts);
payBills.setVisible(true);
}
}
}
}
| true
|
9356e1338b5975d509926444a747f97f2fc09fe1
|
Java
|
vanjac/SeatingChartGenerator
|
/libraries/seatingchart/src/seatingchart/DrawCanvas.java
|
UTF-8
| 410
| 2.453125
| 2
|
[] |
no_license
|
package seatingchart;
import processing.core.*;
import controlP5.*;
import java.util.*;
public class DrawCanvas extends Canvas {
List<CDrawable> drawnObjects;
public void add(CDrawable d) {
drawnObjects.add(d);
}
public DrawCanvas() {
drawnObjects = new ArrayList<CDrawable>();
}
public void draw(PGraphics a) {
for(CDrawable d : drawnObjects) {
d.draw(a);
}
}
}
| true
|
2dd060cfd5e375a4119657b6b267665a9f28ffce
|
Java
|
meetmmpatel/Core_java
|
/src/day/six/exceptions/FinallyExample.java
|
UTF-8
| 440
| 3.421875
| 3
|
[] |
no_license
|
package day.six.exceptions;
import java.util.Scanner;
public class FinallyExample {
static Scanner scan = new Scanner(System.in);
public static void main(String args[]) {
myMethod();
}
public static int myMethod() {
try {
//
System.exit(0);
return 112;
}
finally {
scan.close();
System.out.println("This is Finally block");
System.out.println("Finally block ran even after return statement");
}
}
}
| true
|
4b941acdc90b213dfa5825ae81a21570efe2001e
|
Java
|
Slbw/tvos
|
/app/src/main/java/com/ifxme/tvos/mvp/ui/view/UserView.java
|
UTF-8
| 279
| 1.59375
| 2
|
[] |
no_license
|
package com.ifxme.tvos.mvp.ui.view;
import com.ifxme.tvos.mvp.model.User;
import java.util.List;
/**
* Created by Slbw on 2016/8/19.
*/
public interface UserView extends BaseView{
void showProgress();
void hideProgress();
void showUserList(List<User> data);
}
| true
|
06d51722a5fc8d4bc619d9ab51d014e7e36c6603
|
Java
|
Rishabh-Mehta/OA-Practice
|
/Codility_practice/sortMatrixByOccurrences.java
|
UTF-8
| 2,517
| 3.40625
| 3
|
[] |
no_license
|
package Codility_practice;
import java.util.*;
public class sortMatrixByOccurrences {
public static int[][] sortMatrixByOcc(int[][] m) {
// (number, count)
Map<Integer,Integer> map = new TreeMap<>();
HashMap<Integer,List<Integer>> diagonalMap = new HashMap<>();
Comparator<Integer> comp = new Comparator<Integer>(){
@Override
public int compare(Integer o1, Integer o2) {
if(map.get(o1) == map.get(o2)){
return Integer.compare(o2, o1);
}
else{
return map.get(o2) - map.get(o1);
}
}
};
PriorityQueue<Integer> minHeap = new PriorityQueue<>(comp);
for(int i=0;i<m.length;i++){
for(int j=0;j<m[i].length;j++){
map.put(m[i][j],map.getOrDefault(m[i][j], 0)+1);
List<Integer> temp;
if(diagonalMap.containsKey(i+j)){
temp= diagonalMap.get(i+j);
}
else{
temp = new ArrayList<>();
}
temp.add(m[i][j]);
diagonalMap.put(i+j,temp);
}
}
for(int num:map.keySet()){
int size = map.get(num);
while(size !=0){
minHeap.add(num);
size--;
}
}
for(int i=0;i<m.length+m[0].length-1;i++){
int size = diagonalMap.get(i).size();
List<Integer> temp = new ArrayList<>();
while(size!=0 && !minHeap.isEmpty()){
int val = minHeap.poll();
temp.add(val);
size--;
}
diagonalMap.put(i,temp);
}
for(int i=0;i<m.length;i++){
for(int j=0;j<m[i].length;j++){
m[i][j]=diagonalMap.get(i+j).get(0);
diagonalMap.get(i+j).remove(0);
}
}
return m;
}
public static void main(String[] args) {
int[][] input = {{ 1, 4, -2},
{-2, 3, 4},
{ 3, 1, 3}};
int[][] res = sortMatrixByOcc(input);
for(int i=0;i<res.length;i++){
for(int j=0;j<res[i].length;j++){
System.out.print(res[i][j]+" ");
}
System.out.println();
}
}
}
| true
|
3fc3beb7babe422ce0b33effa6b350e8f0f39361
|
Java
|
sap344/egyptianRatScrew
|
/Game_View.java
|
UTF-8
| 18,271
| 3.28125
| 3
|
[] |
no_license
|
/*
* Shreya Patel
* sap344@drexel.edu
* CS338:GUI, Project 3 - Egyptian Rat Screw Card Game
*/
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
import javax.swing.border.*;
public class Game_View {
private JPanel TopPanel = new JPanel();
private JPanel LeftPanel = new JPanel();
private JPanel CenterPanel = new JPanel();
private JPanel RightPanel = new JPanel();
private JPanel BottomPanel = new JPanel();
private Color backGroundColor = new Color(40,102,10);
private JLabel GameTitle = new JLabel("Egyptian Rat Screw");
private JLabel GameSubTitle = new JLabel("Slap your way to a win!");
private JLabel LeadLabel = new JLabel();
private JLabel CenterLabel = new JLabel();
private JButton NewGameButton = new JButton("New Game");
private JButton EndGameButton = new JButton("End Game");
private JButton HelpButton = new JButton("Help");
private ImageIcon centerCard = new ImageIcon();
private ImageIcon deck_left = new ImageIcon("images/deck_left.gif");
private ImageIcon deck_right = new ImageIcon("images/deck_right.gif");
private JLabel deck_left_label = new JLabel();
private JLabel deck_right_label = new JLabel();
private JLabel user1Label = new JLabel();
private JLabel user2Label = new JLabel();
private JPanel gamePanel = new JPanel(new BorderLayout());
// creates the entire panel
protected Container CreateGUI() {
gamePanel.setFocusable(true);
SetupTopPanel();
SetupLeftPanel();
SetupCenterPanel();
SetupRightPanel();
SetupBottomPanel();
gamePanel.add(TopPanel, BorderLayout.NORTH);
gamePanel.add(LeftPanel, BorderLayout.WEST);
gamePanel.add(CenterPanel, BorderLayout.CENTER);
gamePanel.add(RightPanel, BorderLayout.EAST);
gamePanel.add(BottomPanel, BorderLayout.SOUTH);
gamePanel.setBackground(backGroundColor);
gamePanel.addKeyListener(new FrameKeyListener());
return gamePanel;
}
// actions
public void FlipCard(String imageFile) {
this.centerCard = new ImageIcon(imageFile);
this.CenterLabel.setText("");
this.CenterLabel.setBorder(BorderFactory.createLineBorder(new Color(88,44,44), 8));
this.CenterLabel.setBackground(new Color(30,53,18));
this.CenterLabel.setIcon(centerCard);
this.user1Label.setText("User1: " + user1Pile.GetNumberOfCardsInDeck());
this.user2Label.setText("User2: " + user2Pile.GetNumberOfCardsInDeck());
this.LeadLabel.setFont(new Font("HanziPen TC", Font.BOLD, 20));
this.LeadLabel.setText(whoIsLeading());
}
public void NewGameView() {
this.deck_left_label.setIcon(deck_left);
this.deck_right_label.setIcon(deck_right);
this.CenterLabel.setForeground(new Color(30,53,18));
this.CenterLabel.setBackground(Color.WHITE);
this.CenterLabel.setText("User1 goes first - press 'a' to flip a card.");
}
public void EndGameView(String winner) {
this.CenterLabel.setIcon(null);
this.CenterLabel.setForeground(Color.WHITE);
this.CenterLabel.setText(winner);
}
public void SlapPile() {
this.centerCard = new ImageIcon("images/hand.gif");
this.CenterLabel.setIcon(centerCard);
}
// listener classes
public class NewGameListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
NewGame();
NewGameView();
gamePanel.grabFocus();
}
}
public class EndGameListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
String winner = EndGame();
EndGameView(winner);
}
}
public class HelpListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
String howTo = String.format("%s\n%s\n%s\n\t%s\n\t%s\n\t%s\n\t%s\n\t\t%s\n\t\t%s\n\n%s\n%ss ",
"This application provides any user with a fun and exciting card game! Two players can play at a time on 1 keyboard.",
"Each player just needs to use 2 keys - one for flipping over a card from their stack, and the other for slapping the pile in the middle.",
"The point of the game is to get all the cards in the deck by slapping the middle pile. The rules are as follows:",
"• The game begins user 1 flipping over the first card, the user keeps flipping until he/she flips over an Ace, King, Queen, or a Jack (A/K/Q/J).",
"• Let’s say User1 flips over an A,then User2 has 4flips/chances to flip over another A/K/Q/J. If User2 flips over a Q in their second chance, then the turn moves to User1, who now has 2 chances to get an A/K/Q/J. This goes back an forth.",
"• Once a user takes up all the chances he/she has for that turn and still has not flipped over an A/K/Q/J, then the other user gets the middle pile.",
"• The fun part of the game are the two slapping rules, where you can slap the pile to take it if one of these rules are followed:",
"– Double: when two of the same value cards (ex. 5, 5) are flipped over consecutively",
"– Sandwich: when two two cards of equivalent value are laid down consecutively, but with one card of different value between them (ex. 4,7,4)",
"The user1 keys are as follows: flip = ‘a’ | slap = ’s’",
"The user2 keys are as follows: flip = ‘;’ | slap = ‘’’");
JTextArea jta = new JTextArea(howTo);
jta.setEditable(false);
JScrollPane jsp = new JScrollPane(jta);
jsp.setPreferredSize(new Dimension(1200, 300));
JOptionPane.showMessageDialog(gamePanel,
jsp,
"How To Play",
JOptionPane.PLAIN_MESSAGE);
}
}
public class FrameKeyListener implements KeyListener{
public void keyTyped(KeyEvent e) {
if (e.getKeyChar() == 'a') // user1 flips card (key: a)
{
if (CurrentPlayer.equals("user1"))
{
Card flippedCard = User_1_FlipsCard();
FlipCard(flippedCard.getCardImageFile());
CheckFlippedCardAndUpdateTurns(flippedCard);
}
else
{
LeadLabel.setText("Not your turn User1!");
}
}
else if (e.getKeyChar() == 's') // user1 slaps pile (key: s)
{
User_1_SlapsPile();
SlapPile();
}
else if (e.getKeyChar() == ';') // user2 flips card (key: ;)
{
if (CurrentPlayer.equals("user2"))
{
Card flippedCard = User_2_FlipsCard();
FlipCard(flippedCard.getCardImageFile());
CheckFlippedCardAndUpdateTurns(flippedCard);
}
else
{
LeadLabel.setText("Not your turn User2!");
}
}
else if (e.getKeyChar() == '\'') // user2 slaps pile (key: ')
{
User_2_SlapsPile();
SlapPile();
}
else
{
// do nothing
}
}
public void keyPressed(KeyEvent e) { }
public void keyReleased(KeyEvent e) { }
}
// set view component settings
void SetupTopPanel() {
TopPanel.setLayout(new BorderLayout());
TopPanel.setBackground(backGroundColor);
TopPanel.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED));
//---
JPanel titlePanel = new JPanel();
titlePanel.setLayout(new BoxLayout(titlePanel, BoxLayout.Y_AXIS));
titlePanel.setBackground(backGroundColor);
GameTitle.setFont(new Font("HanziPen TC", Font.BOLD, 80));
GameTitle.setForeground(Color.WHITE);
GameSubTitle.setFont(new Font("HanziPen TC", Font.BOLD, 50));
GameSubTitle.setForeground(Color.WHITE);
titlePanel.add(GameTitle);
titlePanel.add(GameSubTitle);
//---
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.Y_AXIS));
buttonPanel.setBackground(backGroundColor);
Border empty = new EmptyBorder (0,20,20,160);
buttonPanel.setBorder(empty);
JPanel newGameButtonPanel = new JPanel(); // this is only to keep my preferred button size
newGameButtonPanel.setBackground(backGroundColor);
NewGameButton.setPreferredSize(new Dimension(120,60));
NewGameButton.setFont(new Font("HanziPen TC", Font.BOLD, 20));
NewGameButton.setForeground(new Color(40,102,10));
NewGameButton.addActionListener(new NewGameListener());
newGameButtonPanel.add(NewGameButton);
JPanel endGameButtonPanel = new JPanel();
endGameButtonPanel.setBackground(backGroundColor);
EndGameButton.setPreferredSize(new Dimension(120,60));
EndGameButton.setFont(new Font("HanziPen TC", Font.BOLD, 20));
EndGameButton.setForeground(new Color(40,102,10));
EndGameButton.addActionListener(new EndGameListener());
endGameButtonPanel.add(EndGameButton);
buttonPanel.add(Box.createRigidArea(new Dimension(0,10)));
buttonPanel.add(newGameButtonPanel);
buttonPanel.add(Box.createRigidArea(new Dimension(0,30)));
buttonPanel.add(endGameButtonPanel);
//---
TopPanel.add(titlePanel, BorderLayout.CENTER);
TopPanel.add(buttonPanel, BorderLayout.WEST);
}
void SetupLeftPanel() {
LeftPanel.setLayout(new BorderLayout());
LeftPanel.setBackground(backGroundColor);
LeftPanel.setBorder(new EmptyBorder(0,150,0,50));
//---
user1Label.setText("User1");
user1Label.setFont(new Font("HanziPen TC", Font.BOLD, 40));
user1Label.setForeground(Color.WHITE);
user1Label.setBorder(new EmptyBorder(10,0,0,0));
//---
LeftPanel.add(user1Label, BorderLayout.NORTH);
LeftPanel.add(deck_left_label, BorderLayout.CENTER);
}
void SetupCenterPanel() {
CenterPanel.setLayout(new BorderLayout());
CenterPanel.setBackground(backGroundColor);
//---
LeadLabel.setFont(new Font("HanziPen TC", Font.BOLD, 40));
LeadLabel.setForeground(Color.WHITE);
LeadLabel.setBorder(new EmptyBorder(10,0,0,0));
LeadLabel.setHorizontalAlignment(SwingConstants.CENTER);
//CenterLabel.setIcon(centerCard);
CenterLabel.setText("Click the [New Game] button to begin!");
CenterLabel.setFont(new Font("HanziPen TC", Font.BOLD, 30));
CenterLabel.setForeground(new Color(30,53,18));
CenterLabel.setBackground(Color.WHITE);
CenterLabel.setBorder(BorderFactory.createLineBorder(Color.WHITE, 8));
CenterLabel.setHorizontalAlignment(SwingConstants.CENTER);
CenterLabel.setOpaque(true);
//---
CenterPanel.add(LeadLabel, BorderLayout.SOUTH);
CenterPanel.add(CenterLabel, BorderLayout.CENTER);
}
void SetupRightPanel() {
RightPanel.setLayout(new BorderLayout());
RightPanel.setBackground(backGroundColor);
RightPanel.setBorder(new EmptyBorder(0,50,0,150));
//---
user2Label.setText("User2");
user2Label.setFont(new Font("HanziPen TC", Font.BOLD, 40));
user2Label.setForeground(Color.WHITE);
user2Label.setBorder(new EmptyBorder(10,0,0,0));
//---
RightPanel.add(user2Label, BorderLayout.NORTH);
RightPanel.add(deck_right_label, BorderLayout.CENTER);
}
void SetupBottomPanel() {
BottomPanel.setLayout(new BorderLayout());
BottomPanel.setBackground(backGroundColor);
//---
JPanel helpPanel = new JPanel();
helpPanel.setBorder(new EmptyBorder(0,10,10,0));
helpPanel.setBackground(backGroundColor);
HelpButton.setPreferredSize(new Dimension(70,40));
HelpButton.setFont(new Font("HanziPen TC", Font.BOLD, 15));
HelpButton.setForeground(new Color(40,102,10));
HelpButton.addActionListener(new HelpListener());
helpPanel.add(HelpButton);
//---
BottomPanel.add(helpPanel, BorderLayout.WEST);
}
//======================================================================
//======================================================================
//======================================================================
// properties
private static Deck middlePile = new Deck(52);
private static Deck user1Pile = new Deck(0);
private static Deck user2Pile = new Deck(0);
private static List<Card> CardTracker = new ArrayList<Card>();
private static int NumOfTurns;
private static String CurrentPlayer;
private static boolean isFirstTurn;
public void StartGame() {
// -- put 26 shuffled cards into the user1's pile
for (int i = 0; i< 26; i++)
{
Card c = middlePile.DrawCardFromDeck();
//user1Pile.AddToNewDeck(c);
user1Pile.PutCardInDeck(c);
}
// -- put the other shuffled 26 in user2's pile
for (int i = 0; i< 26; i++)
{
Card c = middlePile.DrawCardFromDeck();
//user2Pile.AddToNewDeck(c);
user2Pile.PutCardInDeck(c);
}
// user1 always goes first
CurrentPlayer = "user1";
isFirstTurn = true;
}
// methods
public Card User_1_FlipsCard() {
Card flippedCard = user1Pile.DrawCardFromDeck();
middlePile.PutCardInDeck(flippedCard);
CardTracker.add(flippedCard);
return flippedCard;
}
public Card User_2_FlipsCard() {
Card flippedCard = user2Pile.DrawCardFromDeck();
middlePile.PutCardInDeck(flippedCard);
CardTracker.add(flippedCard);
return flippedCard;
}
public void CheckFlippedCardAndUpdateTurns(Card flippedCard) {
int rank = flippedCard.getRank();
if (isFirstTurn && (rank != 0 || rank != 12 || rank != 11 || rank != 10))
{
SwitchPlayers();
isFirstTurn = false;
}
else
{
isFirstTurn = false;
if (rank == 0)
{
// if card is an Ace
NumOfTurns = 4;
SwitchPlayers();
}
else if (rank == 12)
{
// if card is a King
NumOfTurns = 3;
SwitchPlayers();
}
else if (rank == 11)
{
// if card is a Queen
NumOfTurns = 2;
SwitchPlayers();
}
else if (rank == 10)
{
// if card is a Jack
NumOfTurns = 1;
SwitchPlayers();
}
else
{
// if some other card
NumOfTurns = NumOfTurns - 1;
}
// if out of turns
if (NumOfTurns == 0)
{
if (CurrentPlayer == "user1") // then user2 gets the pile
{
for (int i = 0; i < middlePile.GetNumberOfCardsInDeck() + 1; i++)
{
Card c = middlePile.DrawCardFromDeck();
user2Pile.PutCardInDeck(c);
}
LeadLabel.setFont(new Font("HanziPen TC", Font.BOLD, 10));
LeadLabel.setText("You're out of turns - User 2 gets the pile!");
CurrentPlayer = "user2";
}
else // if currentPlayer = user 2, then user 1 gets the pile
{
for (int i = 0; i < middlePile.GetNumberOfCardsInDeck() + 1; i++)
{
Card c = middlePile.DrawCardFromDeck();
user1Pile.PutCardInDeck(c);
}
LeadLabel.setFont(new Font("HanziPen TC", Font.BOLD, 10));
LeadLabel.setText("You're out of turns - User 1 gets the pile!");
CurrentPlayer = "user1";
}
//middlePile.ClearPile();
CardTracker.clear();
}
}
}
public void SwitchPlayers() {
String player = CurrentPlayer;
if (player.equals("user1"))
{
CurrentPlayer = "user2";
}
else
{
CurrentPlayer = "user1";
}
}
public void User_1_SlapsPile() {
// is called when the user hit his/her slap key
// if valid slapRule give the slapper the middle pile, else give the opponent the middle pile
if (checkSlapRule())
{
int total = middlePile.GetNumberOfCardsInDeck();
for (int n = 0; n < total; n++)
{
Card c = middlePile.DrawCardFromDeck();
user1Pile.PutCardInDeck(c);
}
LeadLabel.setBorder(BorderFactory.createLineBorder(Color.WHITE));
LeadLabel.setText("user1 takes the pile!");
CurrentPlayer = "user1";
}
else
{
int total = middlePile.GetNumberOfCardsInDeck();
for (int n = 0; n < total; n++)
{
Card c = middlePile.DrawCardFromDeck();
user2Pile.PutCardInDeck(c);
}
LeadLabel.setFont(new Font("HanziPen TC", Font.BOLD, 10));
LeadLabel.setBorder(BorderFactory.createLineBorder(Color.WHITE));
LeadLabel.setText("Sorry - invalid Slap --> user2 takes the pile!");
CurrentPlayer = "user2";
}
CardTracker.clear();
}
public void User_2_SlapsPile() {
// is called when the user hit his/her slap key
// if valid slapRule give the slapper the middle pile, else give the opponent the middle pile
if (checkSlapRule())
{
int total = middlePile.GetNumberOfCardsInDeck();
for (int n = 0; n < total; n++)
{
Card c = middlePile.DrawCardFromDeck();
user2Pile.PutCardInDeck(c);
}
LeadLabel.setBorder(BorderFactory.createLineBorder(Color.WHITE));
LeadLabel.setText("user2 takes the pile!");
CurrentPlayer = "user2";
}
else
{
int total = middlePile.GetNumberOfCardsInDeck();
for (int n = 0; n < total; n++)
{
Card c = middlePile.DrawCardFromDeck();
user1Pile.PutCardInDeck(c);
}
LeadLabel.setFont(new Font("HanziPen TC", Font.BOLD, 10));
LeadLabel.setBorder(BorderFactory.createLineBorder(Color.WHITE));
LeadLabel.setText("Sorry - invalid Slap --> user1 takes the pile!");
CurrentPlayer = "user1";
}
CardTracker.clear();
}
public void NewGame() {
// reset all decks and call constructor again to distribute cards
user1Pile = new Deck(0);
user2Pile = new Deck(0);
middlePile = new Deck(52);
StartGame(); // CHECK THIS and make sure its okay
}
public String EndGame() {
String winner = "";
int user1Pts = user1Pile.GetNumberOfCardsInDeck();
int user2Pts = user2Pile.GetNumberOfCardsInDeck();
if (user1Pts > user2Pts)
{
winner = "User1 wins!";
}
else if (user1Pts < user2Pts)
{
winner = "User2 wins!";
}
else
{
winner = "Tie!";
}
return winner;
}
private boolean checkSlapRule() {
boolean isSlapperValid = false; // give the slapper the middle pile
int num = middlePile.GetNumberOfCardsInDeck();
p("middlePile num: " + num);
p("cardTracker: " + CardTracker.size());
if (num >= 2)
{
Card a = CardTracker.get(num-1);
Card b = CardTracker.get(num-2);
if (a.getRank() == b.getRank())
{
isSlapperValid = true;
}
else if (num >= 3)
{
Card c = CardTracker.get(num-3);
if (a.getRank() == c.getRank())
{
isSlapperValid = true;
}
}
else
{
isSlapperValid = false;
}
}
return isSlapperValid;
}
private String whoIsLeading() {
String lead = "";
int user1Pts = user1Pile.GetNumberOfCardsInDeck();
int user2Pts = user2Pile.GetNumberOfCardsInDeck();
if (user1Pts > user2Pts)
{
lead = "User1 is leading!";
}
else if (user1Pts < user2Pts)
{
lead = "User2 is leading!";
}
else
{
lead = "Both users are tied currently!";
}
return lead;
}
private void p(String print) {
System.out.println(print);
}
}
| true
|
ed3c94359b0bbb819deb7203911ddacf2c6d9718
|
Java
|
eslamengi/BigData-Cloud-Projects
|
/Assignment10/src/main/java/com/refactorlabs/cs378/SearcherVDPMapper.java
|
UTF-8
| 3,080
| 2.46875
| 2
|
[] |
no_license
|
package com.refactorlabs.cs378;
import org.apache.avro.Schema;
import org.apache.avro.mapred.AvroKey;
import org.apache.avro.mapred.AvroValue;
import org.apache.avro.mapred.Pair;
import org.apache.avro.mapreduce.AvroJob;
import org.apache.avro.mapreduce.AvroKeyInputFormat;
import org.apache.avro.mapreduce.AvroKeyOutputFormat;
import org.apache.avro.mapreduce.AvroMultipleOutputs;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.DoubleWritable;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import org.apache.hadoop.util.GenericOptionsParser;
import java.io.IOException;
import java.util.*;
/**
* The Map class for word count. Extends class Mapper, provided by Hadoop.
* This class defines the map() function for the word count example.
*/
public class SearcherVDPMapper extends Mapper<AvroKey<Pair<CharSequence, Session>>, NullWritable, Text, DoubleArrayWritable> {
/**
* Local variable "word" will contain the word identified in the input.
* The Hadoop Text object is mutable, so we can reuse the same object and
* simply reset its value as each word in the input is encountered.
*/
private Text word = new Text("VDPCount, idCountInSRP, CTR");
/**
* Each count output from the map() function is "1", so to minimize small
* object creation we can use a constant for this output value/object.
*/
private final static DoubleWritable ONE = new DoubleWritable(1L);
private DoubleWritable[] doubleWritables = new DoubleWritable[2];
private DoubleArrayWritable outputValue = new DoubleArrayWritable();
@Override
public void map(AvroKey<Pair<CharSequence, Session>> key, NullWritable value, Context context)
throws IOException, InterruptedException {
String type;
double countVDP = 0.0;
double idCountInSRP = 0.0;
System.out.println("Set up the mapper in VDP, Bitch!!!");
for (Impression impression: key.datum().value().getImpressions()) {
System.out.println("New Impression in VDP!!!");
type = impression.getImpressionType().toString();
if(type.equals("VDP")){
countVDP++;
}
else if(type.equals("SRP")){
if(impression.getId() != null)
idCountInSRP += impression.getId().size();
}
}
// Write out all of the values (count) of the keys (words) in map
context.getCounter("Mapper Counts", "Output Words").increment(1L);
doubleWritables[0] = new DoubleWritable(countVDP);
doubleWritables[1] = new DoubleWritable(idCountInSRP);
outputValue.set(doubleWritables);
System.out.println("Write this to reducer!!!");
context.write(word, outputValue);
}
}
| true
|
54bac7dca0f5cd90a00db0dd9594459900e4ad05
|
Java
|
luupanu/cybersecuritybase-project
|
/src/main/java/sec/project/controller/Controllers.java
|
UTF-8
| 2,411
| 2.375
| 2
|
[] |
no_license
|
package sec.project.controller;
import java.sql.SQLException;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import sec.project.database.Database;
import sec.project.database.MessageDao;
import sec.project.database.SignupDao;
import sec.project.domain.Message;
import sec.project.domain.Signup;
import sec.project.repository.SignupRepository;
import sec.project.repository.MessageRepository;
@Controller
public class Controllers {
private final Database database;
private final SignupDao signupDao;
private final MessageDao messageDao;
@Autowired
private SignupRepository signupRepository;
@Autowired
private MessageRepository messageRepository;
// set up our in-memory DB here
public Controllers() throws SQLException {
this.database = new Database("jdbc:h2:mem:db");
this.signupDao = new SignupDao(database);
this.messageDao = new MessageDao(database);
}
@RequestMapping("*")
public String defaultMapping() {
return "redirect:/form";
}
@RequestMapping(value = "/form", method = RequestMethod.GET)
public String loadForm(Model model) {
List<Signup> attendees = signupRepository.findAll();
List<Message> messages = messageRepository.findAll();
model.addAttribute("count", attendees.size());
model.addAttribute("messages", messages);
return "form";
}
@RequestMapping(value = "/form", method = RequestMethod.POST)
public String submitForm(@RequestParam String name, @RequestParam String address, @RequestParam String creditcard) {
signupDao.addSignup(name, address, creditcard);
return "done";
}
@RequestMapping(value = "/message", method = RequestMethod.POST)
public String submitMessage(@RequestParam String message) {
messageDao.addMessage(message);
return "redirect:/form";
}
@RequestMapping("/admin")
public String loadAdmin(Model model) {
List<Signup> attendees = signupRepository.findAll();
model.addAttribute("attendees", attendees);
return "admin";
}
}
| true
|
b2c44bab848aed9273827ae6b2768bbf51fe4d14
|
Java
|
peloba/noa-libre-mvn
|
/src/main/java/ag/ion/noa/internal/text/DocumentIndexService.java
|
UTF-8
| 4,996
| 1.828125
| 2
|
[] |
no_license
|
/****************************************************************************
* *
* NOA (Nice Office Access) *
* ------------------------------------------------------------------------ *
* *
* The Contents of this file are made available subject to *
* the terms of GNU Lesser General Public License Version 2.1. *
* *
* GNU Lesser General Public License Version 2.1 *
* ======================================================================== *
* Copyright 2003-2006 by IOn AG *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Lesser General Public *
* License version 2.1, as published by the Free Software Foundation. *
* *
* This library is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public *
* License along with this library; if not, write to the Free Software *
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, *
* MA 02111-1307 USA *
* *
* Contact us: *
* http://www.ion.ag *
* http://ubion.ion.ag *
* info@ag.ion.ag *
* *
****************************************************************************/
/*
* Last changes made by $Author: andreas $, $Date: 2006-10-04 14:14:28 +0200 (Mi, 04 Okt 2006) $
*/
package ag.ion.noa.internal.text;
import ag.ion.bion.officelayer.util.Assert;
import ag.ion.noa.text.IDocumentIndex;
import ag.ion.noa.text.IDocumentIndexService;
import com.sun.star.container.XIndexAccess;
import com.sun.star.text.XDocumentIndex;
import com.sun.star.text.XDocumentIndexesSupplier;
import com.sun.star.text.XTextDocument;
import com.sun.star.uno.UnoRuntime;
import java.util.ArrayList;
import java.util.List;
/**
* Service for document indices.
*
* @author Andreas Bröker
* @version $Revision: 10398 $
* @date 17.08.2006
*/
public class DocumentIndexService implements IDocumentIndexService {
private XTextDocument textDocument = null;
//----------------------------------------------------------------------------
/**
* Constructs new DocumentIndexProvider.
*
* @param textDocument XTextDocument interface to be used
* @author Andreas Bröker
* @date 17.08.2006
*/
public DocumentIndexService(XTextDocument textDocument) {
Assert.isNotNull(textDocument, XTextDocument.class, this);
this.textDocument = textDocument;
}
//----------------------------------------------------------------------------
/**
* Returns available document indexes.
*
* @return available document indexes
* @author Andreas Bröker
* @date 17.08.2006
*/
public IDocumentIndex[] getDocumentIndexes() {
XDocumentIndexesSupplier documentIndexesSupplier = (XDocumentIndexesSupplier) UnoRuntime
.queryInterface(XDocumentIndexesSupplier.class, textDocument);
if (documentIndexesSupplier == null) {
return new IDocumentIndex[0];
}
XIndexAccess indexAccess = documentIndexesSupplier.getDocumentIndexes();
List list = new ArrayList();
for (int i = 0, n = indexAccess.getCount(); i < n; i++) {
try {
Object object = indexAccess.getByIndex(i);
XDocumentIndex documentIndex = (XDocumentIndex) UnoRuntime
.queryInterface(XDocumentIndex.class, object);
if (documentIndex != null) {
list.add(new DocumentIndex(documentIndex));
}
} catch (Throwable throwable) {
//do not consume
}
}
return (IDocumentIndex[]) list.toArray(new IDocumentIndex[list.size()]);
}
//----------------------------------------------------------------------------
}
| true
|
4704d36f8ed5abf64ac4330e0811f4b6478879ef
|
Java
|
bellmit/washington-sgge-1-0-0
|
/NewAcademia/sensus-lc-interface/src/main/java/com/sensus/lc/analytics/model/response/AnalyticsResponse.java
|
UTF-8
| 3,144
| 2.265625
| 2
|
[] |
no_license
|
package com.sensus.lc.analytics.model.response;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.sensus.common.model.response.Response;
import com.sensus.lc.analytics.model.AnalyticsGroup;
import com.sensus.lc.analytics.model.AnalyticsGroupColumns;
import com.sensus.lc.light.model.Light;
/**
* The Class AnalyticsResponse.
*
* @author - QAT Brazil
*
*/
public class AnalyticsResponse extends Response
{
/** The lights. */
private List<Light> lights;
/** The alert values. */
private Map<String, Integer> alertsByType;
/** The columns. */
private List<AnalyticsGroupColumns> columns = new ArrayList<AnalyticsGroupColumns>();
/** The file name. */
private String fileName;
/** The analyticsGroups. */
private List<AnalyticsGroup> analyticsGroups;
/**
* Gets the lights.
*
* @return the lights
*/
public List<Light> getLights()
{
return this.lights;
}
/**
* Sets the lights.
*
* @param lights the new lights
*/
public void setLights(List<Light> lights)
{
this.lights = lights;
}
/**
* Gets the alerts by type.
*
* @return the alerts by type
*/
public Map<String, Integer> getAlertsByType()
{
return this.alertsByType;
}
/**
* Sets the alerts by type.
*
* @param alertsByTypes the alerts by type
*/
public void setAlertsByType(Map<String, Integer> alertsByTypes)
{
this.alertsByType = alertsByTypes;
}
/**
* Gets the columns.
*
* @return the columns
*/
public List<AnalyticsGroupColumns> getColumns()
{
return this.columns;
}
/**
* Sets the columns.
*
* @param columns the new columns
*/
public void setColumns(List<AnalyticsGroupColumns> columns)
{
this.columns = columns;
}
/**
* Gets the file name.
*
* @return the file name
*/
public String getFileName()
{
return this.fileName;
}
/**
* Sets the file name.
*
* @param fileName the new file name
*/
public void setFileName(String fileName)
{
this.fileName = fileName;
}
/**
* Sets the analytics groups.
*
* @param analyticsGroups the new analytics groups
*/
public void setAnalyticsGroups(List<AnalyticsGroup> analyticsGroups)
{
this.analyticsGroups = analyticsGroups;
}
/**
* Gets the analytics groups.
*
* @return the analytics groups
*/
public List<AnalyticsGroup> getAnalyticsGroups()
{
return this.analyticsGroups;
}
/*
* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString()
{
return "AnalyticsResponse [getLights()=" + this.getLights() + ", getAlertsByType()=" + this.getAlertsByType()
+ ", getColumns()=" + this.getColumns() + ", getFileName()=" + this.getFileName()
+ ", getAnalyticsGroups()="
+ this.getAnalyticsGroups() + ", getMessageIterator()=" + this.getMessageIterator()
+ ", getMessageList()="
+ this.getMessageList() + ", getMessageInfoList()=" + this.getMessageInfoList()
+ ", isOperationSuccess()="
+ this.isOperationSuccess() + "]";
}
}
| true
|
93b3627e8f1b79f2f86a9b30836cb055b17e2db8
|
Java
|
razvanbretoiu/jUCMNav-import-UCMs
|
/src/receive/ReceiveObj.java
|
UTF-8
| 2,192
| 2.265625
| 2
|
[] |
no_license
|
package receive;
import java.util.List;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement( name = "RECEIVEOBJ" )
public class ReceiveObj {
private int idUCMSource;
private int idUCMTarget;
private int stubSource;
private List<StartPoint> startPoint;
private List<EndPoint> endPoint;
public ReceiveObj(int idUCMSource, int idUCMTarget, int stubSource, List<StartPoint> startPoint,
List<EndPoint> endPoint) {
super();
this.idUCMSource = idUCMSource;
this.idUCMTarget = idUCMTarget;
this.stubSource = stubSource;
this.startPoint = startPoint;
this.endPoint = endPoint;
}
public ReceiveObj() {
super();
}
/**
* @return the idUCMSource
*/
public int getIdUCMSource() {
return idUCMSource;
}
/**
* @param idUCMSource the idUCMSource to set
*/
@XmlElement( name = "idUCMSource" )
public void setIdUCMSource(int idUCMSource) {
this.idUCMSource = idUCMSource;
}
/**
* @return the idUCMTarget
*/
public int getIdUCMTarget() {
return idUCMTarget;
}
/**
* @param idUCMTarget the idUCMTarget to set
*/
@XmlElement( name = "idUCMTarget" )
public void setIdUCMTarget(int idUCMTarget) {
this.idUCMTarget = idUCMTarget;
}
/**
* @return the stubSource
*/
public int getStubSource() {
return stubSource;
}
/**
* @param stubSource the stubSource to set
*/
@XmlElement( name = "stubSource" )
public void setStubSource(int stubSource) {
this.stubSource = stubSource;
}
/**
* @return the startPoint
*/
public List<StartPoint> getStartPoint() {
return startPoint;
}
/**
* @param startPoint the startPoint to set
*/
@XmlElement( name = "startPoint" )
public void setStartPoint(List<StartPoint> startPoint) {
this.startPoint = startPoint;
}
/**
* @return the endPoint
*/
public List<EndPoint> getEndPoint() {
return endPoint;
}
/**
* @param endPoint the endPoint to set
*/
@XmlElement( name = "endPoint" )
public void setEndPoint(List<EndPoint> endPoint) {
this.endPoint = endPoint;
}
}
| true
|
8e5fec6488bebe8406c95b5a9b0ec04c7dce7b98
|
Java
|
csarron/GmsWear
|
/shared/src/main/java/com/cscao/apps/shared/Utils.java
|
UTF-8
| 5,417
| 2.390625
| 2
|
[
"MIT"
] |
permissive
|
package com.cscao.apps.shared;
import android.content.Context;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.os.SystemClock;
import android.support.annotation.NonNull;
import android.widget.ImageView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.cscao.libs.gmswear.connectivity.FileTransfer;
import com.google.android.gms.wearable.Channel;
import com.google.android.gms.wearable.WearableStatusCodes;
import com.orhanobut.logger.Logger;
import org.apache.commons.io.IOUtils;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* Created by qqcao on 11/4/16.
*
* File utilities
*/
public class Utils {
public static File copyFileToPrivateDataIfNeededAndReturn(Context context, String fileName) {
File downloadFolder = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS);
File file = new File(downloadFolder, fileName);
if (!downloadFolder.exists()) {
boolean hasDirCreated = downloadFolder.mkdirs();
if (!hasDirCreated) {
Logger.e("cannot create download folder");
return null;
}
}
if (file.exists()) {
Logger.d("File already exists in the target location");
return file;
} else {
try {
if (!file.createNewFile()) {
return null;
}
} catch (IOException e) {
e.printStackTrace();
}
}
try {
InputStream inputStream = context.getAssets().open(fileName);
FileOutputStream fileOutputStream = new FileOutputStream(file);
IOUtils.copy(inputStream, fileOutputStream);
return file;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static void showToast(Context context, String message) {
Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
}
public static void sendSelectedImage(final Uri uri, ImageView imageView) {
final Context context = imageView.getContext();
// show image locally
Glide.with(context).load(uri).into(imageView);
// send to wearable
FileTransfer fileTransferHighLevel = new FileTransfer.Builder()
.setOnChannelOutputStreamListener(new FileTransfer.OnChannelOutputStreamListener() {
@Override
public void onOutputStreamForChannelReady(int statusCode, Channel channel,
final OutputStream outputStream) {
if (statusCode != WearableStatusCodes.SUCCESS) {
Logger.e("Failed to open a channel, status code: " + statusCode);
return;
}
sendFile(context, uri, outputStream);
}
}).build();
fileTransferHighLevel.requestOutputStream();
}
private static void sendFile(final Context context, final Uri uri, final OutputStream os) {
new Thread(new Runnable() {
@Override
public void run() {
try {
InputStream is = context.getContentResolver().openInputStream(uri);
assert is != null;
IOUtils.copy(is, os);
is.close();
os.close();
// }
} catch (IOException e) {
Logger.e("startTransfer(): IO Error while reading/writing", e);
}
}
}).start();
}
public static void setImageFromInputStream(final InputStream inputStream,
final ImageView imageView) {
final Context context = imageView.getContext();
new AsyncTask<Void, Void, File>() {
@Override
protected File doInBackground(Void... params) {
try {
File imageFile = new File(context.getCacheDir(),
"temp" + SystemClock.elapsedRealtime());
FileOutputStream outputStream = new FileOutputStream(imageFile);
IOUtils.copy(inputStream, outputStream);
return imageFile;
} catch (IOException e) {
e.printStackTrace();
closeStreams();
}
return null;
}
@Override
protected void onPostExecute(File imageFile) {
if (imageFile != null) {
Logger.d("setting image");
Glide.with(context).load(imageFile).into(imageView);
} else {
Logger.e("image file null");
}
}
void closeStreams() {
try {
if (inputStream != null) {
inputStream.close();
}
} catch (IOException e) {
// no-op
}
}
}.execute();
}
@NonNull
public static String getElapsedTimeMsg() {
return "" + SystemClock.elapsedRealtime();
}
}
| true
|
f8293ece36a2024f93e09bf750fb656ffc4141e7
|
Java
|
naseem91/SpeechRecorderSBT
|
/javautils/src/main/java/ipsk/swing/table/AutoFontCellRenderer.java
|
UTF-8
| 3,993
| 2.625
| 3
|
[] |
no_license
|
// IPS Java Utils
// (c) Copyright 2009-2011
// Institute of Phonetics and Speech Processing,
// Ludwig-Maximilians-University, Munich, Germany
//
//
// This file is part of IPS Java Utils
//
//
// IPS Java Utils is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, version 3 of the License.
//
// IPS Java Utils is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with IPS Java Utils. If not, see <http://www.gnu.org/licenses/>.
package ipsk.swing.table;
import ipsk.awt.font.AutoFontFamilyManager;
import java.awt.Component;
import java.awt.Font;
import java.util.List;
import javax.swing.JTable;
import javax.swing.table.TableCellRenderer;
/**
* Wrapper to disable the default cell renderer component if the value of the cell is null.
* This is currently used to disable the check box of Boolean null values.
* @author K.Jaensch, klausj@phonetik.uni-muenchen.de
*
*/
public class AutoFontCellRenderer implements TableCellRenderer {
private TableCellRenderer defRenderer;
private AutoFontFamilyManager fontManager=null;
/**
* @return array of preferred font families
* @see ipsk.awt.font.AutoFontFamilyManager#getPreferredFontFamilies()
*/
public String[] getPreferredFontFamilies() {
return fontManager.getPreferredFontFamilies();
}
/**
* @param preferredFontFamilies
* @see ipsk.awt.font.AutoFontFamilyManager#setPreferredFontFamilies(java.lang.String[])
*/
public void setPreferredFontFamilies(String[] preferredFontFamilies) {
fontManager.setPreferredFontFamilies(preferredFontFamilies);
}
/**
* @return true if searching on all other fonts
* @see ipsk.awt.font.AutoFontFamilyManager#isSearchOtherFonts()
*/
public boolean isSearchOtherFonts() {
return fontManager.isSearchOtherFonts();
}
/**
* @param searchOtherFonts
* @see ipsk.awt.font.AutoFontFamilyManager#setSearchOtherFonts(boolean)
*/
public void setSearchOtherFonts(boolean searchOtherFonts) {
fontManager.setSearchOtherFonts(searchOtherFonts);
}
/**
* @return list of font families, in which a suitable font will be searched
* @see ipsk.awt.font.AutoFontFamilyManager#getFontFamilies()
*/
public List<String> getFontFamilies() {
return fontManager.getFontFamilies();
}
/**
* Create Cell renderer wrapper which disables components for null values.
* @param defRenderer
*/
public AutoFontCellRenderer(TableCellRenderer defRenderer){
super();
this.defRenderer=defRenderer;
fontManager=new AutoFontFamilyManager();
}
/**
* Create Cell renderer wrapper which disables components for null values.
* @param defRenderer
*/
public AutoFontCellRenderer(TableCellRenderer defRenderer,String[] preferredFontFamilies,boolean searchOtherFonts){
super();
this.defRenderer=defRenderer;
fontManager=new AutoFontFamilyManager(preferredFontFamilies, searchOtherFonts);
}
/**
* Implementation of TableCellRenderer
*/
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
Component defComp = defRenderer.getTableCellRendererComponent(table,
value, isSelected, hasFocus, row, column);
if (defComp != null && value !=null) {
String valStr=value.toString();
Font cmpFont=defComp.getFont();
Font dFont=fontManager.getFontCanDisplay(cmpFont, valStr);
if(dFont!=cmpFont){
defComp.setFont(dFont);
}
}
return defComp;
}
}
| true
|
68e59d6cb87c4c0a004312cf1192268b5a61004b
|
Java
|
xmprise/BongPlayer
|
/src/com/example/bongplayer2/fragment/FragmentStream.java
|
UTF-8
| 31,459
| 1.507813
| 2
|
[] |
no_license
|
package com.example.bongplayer2.fragment;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.AsyncQueryHandler;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.ContentObserver;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore.Video;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.LoaderManager;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.text.Editable;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebView.FindListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.example.bongplayer2.R;
import com.example.bongplayer2.VideoActivity;
import com.example.bongplayer2.R.attr;
import com.example.bongplayer2.R.drawable;
import com.example.bongplayer2.R.id;
import com.example.bongplayer2.R.layout;
import com.example.bongplayer2.R.menu;
import com.example.bongplayer2.R.string;
import com.example.bongplayer2.Utils.CursorUtils;
import com.example.bongplayer2.adapter.StreamAdapter;
import com.example.bongplayer2.adapter.StreamCursorAdapter;
import com.example.bongplayer2.bean.FileExplorerItem;
import com.example.bongplayer2.bean.StreamListViewData;
import com.example.bongplayer2.dialog.ListMenuDialog;
import com.google.code.androidsmb.DBAdapter;
import com.google.code.androidsmb.DB_Open;
import com.google.code.androidsmb.ListFiles;
import com.google.code.androidsmb.WiFiDirectActivity;
import com.yixia.zi.preference.APreference;
import com.yixia.zi.provider.Session;
import com.yixia.zi.utils.UIUtils;
import java.util.ArrayList;
public class FragmentStream extends BaseFragment
implements LoaderManager.LoaderCallbacks<Cursor>, AdapterView.OnItemClickListener
{
private final String LOGTAG ="FragmentStream";
private Session session;
private StreamCursorAdapter streamCursorAdapter;
private StreamAdapter streamAdapter;
private ListMenuDialog listMenuDialog;
private FileExplorerItem fileExplorerItem;
private BaseFragment.EditModeListener fragmentStreamEditListener;
private StreamCursorAdapter.IconClickListener FragmentStreamIconClickListener = null;
private final FragmentStreamContentObserver fragmentStreamContentObserver = new FragmentStreamContentObserver(this, new Handler());
private ListView sambaListView;
private ListView httpListView;
private ArrayList<StreamListViewData> streamListViewDataArray = new ArrayList<StreamListViewData>();
private StreamListViewData sambaSection;
private StreamListViewData httpSection;
private StreamListViewData sambaAdd;
private StreamListViewData httpaAdd;
private static ArrayList<ArrayList<String>> streamURLArray = new ArrayList<ArrayList<String>>();
private static ArrayList<StreamAdapter> streamAdapterArray;
private DBAdapter database;
private Cursor cursor;
private View menu;
TextView url;
DB_Open db_open;
private SQLiteDatabase db;
private Dialog a()
{
Log.d(LOGTAG, "Dialog");
AlertDialog.Builder builder = new AlertDialog.Builder(this.mContext).setIcon(android.R.id.icon);
View view = LayoutInflater.from(this.mContext).inflate(R.layout.dialog_one_edittext, null);
EditText editText = (EditText)view.findViewById(R.id.dialog_one_edittext_edittext);
builder.setTitle(R.string.action_add_group);
builder.setView(view);
//builder.setPositiveButton(R.string.dialog_button_ok, new nf(this, editText));
return setDismissDialog(builder, 2);
}
protected void changeMenuMore(int paramInt1, int paramInt2, boolean paramBoolean)
{
Log.d(LOGTAG, "changeMenuMore");
if (this.mMenuMore != null)
{
((ImageView)this.mMenuMore.findViewById(2131558533)).setImageResource(UIUtils.getAttrValue(getActivity(), paramInt1).resourceId);
((TextView)this.mMenuMore.findViewById(2131558534)).setText(paramInt2);
this.mMenuMore.setEnabled(paramBoolean);
}
}
private void setEdit()
{
if (streamAdapter == null)
return;
else{
boolean[] itemsIsCheck = streamAdapter.getChecked();
if ((itemsIsCheck != null) && (isEditMode()))
{
int checkCnt = itemsIsCheck.length;
mMenuDelete.setEnabled(false);
for(int i=0;i<checkCnt;i++)
{
if(itemsIsCheck[i] != false)
{
mMenuDelete.setEnabled(true);
break;
}
}
}
}
}
public boolean checkNameExists(int paramInt, String paramString)
{
Log.d(LOGTAG, "checkNameExists");
// Byte code:
// 0: aload_0
// 1: invokevirtual 111\011me/abitno/media/explorer/FragmentStreamFolder:getContentResolver\011()Landroid/content/ContentResolver;
// 4: astore 5
// 6: getstatic 117\011me/abitno/media/provider/StreamProvider:CONTENT_URI\011Landroid/net/Uri;
// 9: astore 6
// 11: iconst_1
// 12: anewarray 119\011java/lang/String
// 15: astore 7
// 17: aload 7
// 19: iconst_0
// 20: ldc 207
// 22: aastore
// 23: iconst_2
// 24: anewarray 119\011java/lang/String
// 27: astore 8
// 29: aload 8
// 31: iconst_0
// 32: new 121\011java/lang/StringBuilder
// 35: dup
// 36: invokespecial 122\011java/lang/StringBuilder:<init>\011()V
// 39: iload_1
// 40: invokevirtual 210\011java/lang/StringBuilder:append\011(I)Ljava/lang/StringBuilder;
// 43: invokevirtual 130\011java/lang/StringBuilder:toString\011()Ljava/lang/String;
// 46: aastore
// 47: aload 8
// 49: iconst_1
// 50: aload_2
// 51: aastore
// 52: aload 5
// 54: aload 6
// 56: aload 7
// 58: ldc 212
// 60: aload 8
// 62: aconst_null
// 63: invokevirtual 216\011android/content/ContentResolver:query\011(Landroid/net/Uri;[Ljava/lang/String;Ljava/lang/String;[Ljava/lang/String;Ljava/lang/String;)Landroid/database/Cursor;
// 66: astore 9
// 68: aload 9
// 70: astore 4
// 72: aload 4
// 74: ifnull +57 -> 131
// 77: aload 4
// 79: invokeinterface 222 1 0
// 84: istore 11
// 86: iload 11
// 88: ifle +43 -> 131
// 91: iconst_1
// 92: istore 10
// 94: aload 4
// 96: ifnull +10 -> 106
// 99: aload 4
// 101: invokeinterface 225 1 0
// 106: iload 10
// 108: ireturn
// 109: astore_3
// 110: aconst_null
// 111: astore 4
// 113: aload 4
// 115: ifnull +10 -> 125
// 118: aload 4
// 120: invokeinterface 225 1 0
// 125: aload_3
// 126: athrow
// 127: astore_3
// 128: goto -15 -> 113
// 131: iconst_0
// 132: istore 10
// 134: goto -40 -> 94
//
// Exception table:
// from\011to\011target\011type
// 0\01168\011109\011finally
// 77\01186\011127\011finally
return true;
}
public void deleteCheckedGroup(ArrayList paramArrayList)
{
Log.d(LOGTAG, "deleteCheckedGroup");
//new AlertDialog.Builder(getActivity()).setIcon(17301543).setTitle(2131361867).setMessage(2131361870).setPositiveButton(2131361877, new nh(this, paramArrayList)).setNegativeButton(2131361878, null).show();
}
public void deleteGroup(long paramLong)
{
Log.d(LOGTAG, "deleteGroup");
//new AlertDialog.Builder(getActivity()).setIcon(17301543).setTitle(2131361867).setMessage(2131361870).setPositiveButton(2131361877, new ni(this, paramLong)).setNegativeButton(2131361878, null).show();
}
public void onActivityCreated(Bundle paramBundle)
{
Log.d(LOGTAG, "onActivityCreated");
super.onActivityCreated(paramBundle);
//getListView().setOnItemLongClickListener(this);
getListView().setOnItemLongClickListener(new OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int position, long id) {
// TODO Auto-generated method stub
StreamListViewData streamListViewData = streamAdapter.getItem(position);
//Log.i(LOGTAG, "Item Click : " + position + " : " + streamListViewData.data);
final String selectItem = streamListViewData.data;
if(streamListViewData.type == null){
return false;
}
else{
final String items[] = { "Connect", "Modify", "Delete" };
new AlertDialog.Builder(getActivity())
.setSingleChoiceItems(items, 0, null)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
int selectedPosition = ((AlertDialog)dialog).getListView().getCheckedItemPosition();
//0 1 ...
ArrayList<String> arr = new ArrayList<String>();
Cursor c;
switch(selectedPosition){
case 0: // Connect
c = db.rawQuery("SELECT url,name,pwd, _user_id FROM db_user WHERE url= '" +selectItem +"'", null);
c.moveToFirst();
c.getCount();
String intentURL = "";
String intentname = "";
String intentpwd = "";
for(int i=0;i<c.getCount();i++){
arr.add(c.getString(0));
intentURL = c.getString(0);
intentname = c.getString(1);
intentpwd = c.getString(2);
Log.i(LOGTAG, "ITEM : " + c.getString(1) + " : " + c.getString(0));
c.moveToNext();
}
Intent intent = new Intent(getActivity(), ListFiles.class);
intent.putExtra("IPaddress" , intentURL);
intent.putExtra("username" , intentname);
intent.putExtra("password" , intentpwd);
startActivity(intent);
break;
case 1: // Modify
AlertDialog.Builder alert = new AlertDialog.Builder(getActivity());
alert.setTitle("SMB Information Modify");
alert.setMessage("SMB URL :");
//Setup text area for user input
final EditText url = new EditText(getActivity());
alert.setView(url);
alert.setMessage("SMB UserName :");
//Setup text area for user input
final EditText name = new EditText(getActivity());
alert.setView(name);
alert.setMessage("SMB UserPassword :");
//Setup text area for user input
final EditText pwd = new EditText(getActivity());
alert.setView(pwd);
//Setup what happens when the user clicks either buttons
alert.setPositiveButton("Modify Information", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int whichbutton) {
// TODO Auto-generated method stub
}
});
alert.show();
break;
case 2: // Delete
db_open.deleteTitle(selectItem);
c = db.rawQuery("SELECT url, _user_id FROM db_user", null);
c.moveToFirst();
c.getCount();
for(int i=0;i<c.getCount();i++){
arr.add(c.getString(0));
sambaAdd = new StreamListViewData();
sambaAdd.data = c.getString(0);
sambaAdd.type = "URL";
sambaAdd.urlType = "Samba";
//streamListViewDataArray.add(sambaAdd);
streamAdapter.add(sambaAdd);
Log.i(LOGTAG, "ITEM : " + c.getString(1) + " : " + c.getString(0));
c.moveToNext();
}
break;
}
}
})
.show();
Log.i("HERE :" ,streamListViewData.data);
}
return false;
}
});
//getLoaderManager().initLoader(1, null, this);
}
public void onAttach(Activity paramActivity)
{
Log.d(LOGTAG, "onAttach");
super.onAttach(paramActivity);
//paramActivity.getContentResolver().registerContentObserver(StreamProvider.CONTENT_URI, true, fragmentStreamContentObserver);
}
public boolean onBackPressed()
{
Log.d(LOGTAG, "onBackPressed");
if (isEditMode())
{
fragmentStreamEditListener.onCancelEditClick();
setEditMode();
return true;
}
else
{
return super.onBackPressed();
}
}
public void onCreate(Bundle paramBundle)
{
Log.d(LOGTAG, "onCreate");
super.onCreate(paramBundle);
// streamCursorAdapter = new StreamCursorAdapter(getActivity(), FragmentStreamIconClickListener);
// fragmentStreamEditListener = streamCursorAdapter.mEditModeListener;
// setListAdapter(streamCursorAdapter);
// streamAdapter = new StreamAdapter(getActivity(), textViewResourceId, folderInfoList);
db_open = new DB_Open(getActivity());
db = db_open.getWritableDatabase();
sambaSection = new StreamListViewData();
sambaSection.data = "Samba";
sambaSection.type = "Section";
streamListViewDataArray.add(sambaSection);
ArrayList<String> arr = new ArrayList<String>();
Cursor c = db.rawQuery("SELECT url, _user_id FROM db_user", null);
c.moveToFirst();
c.getCount();
for(int i=0;i<c.getCount();i++){
arr.add(c.getString(0));
sambaAdd = new StreamListViewData();
sambaAdd.data = c.getString(0);
sambaAdd.type = "URL";
sambaAdd.urlType = "Samba";
streamListViewDataArray.add(sambaAdd);
//Log.i(LOGTAG, "ITEM : " + c.getString(1) + " : " + c.getString(0));
c.moveToNext();
}
sambaAdd = new StreamListViewData();
sambaAdd.data = "ADD Samba";
sambaAdd.type = "AddBtn";
sambaAdd.urlType = "Samba";
// Here Line in Input SQLite data code.
streamListViewDataArray.add(sambaAdd);
httpSection = new StreamListViewData();
httpSection.data = "http";
httpSection.type = "Section";
streamListViewDataArray.add(httpSection);
httpaAdd = new StreamListViewData();
httpaAdd.data = "ADD http";
httpaAdd.type = "AddBtn";
httpaAdd.urlType = "Http";
streamListViewDataArray.add(httpaAdd);
streamAdapter = new StreamAdapter(getActivity(), R.layout.file_explorer_stream_section_row, streamListViewDataArray);
fragmentStreamEditListener = streamAdapter.mEditModeListener;
setListAdapter(streamAdapter);
setHasOptionsMenu(true);
session = new Session(getActivity());
streamAdapter.createChecked();
// database = new DBAdapter(getActivity());
// //database.deleteAll();
// database.open();
//
// cursor = database.getAllTitles();
//
// @SuppressWarnings("deprecation")
// ListAdapter adapter = new SimpleCursorAdapter(getActivity(), R.layout.file_explorer_stream_section_row, cursor,
// new String[] {cursor.getColumnName(cursor.getColumnIndex("url"))}, new int[] {android.R.id.text1});
//setListAdapter(adapter);
//Log.i("SQLITE","data : " + cursor.getString(cursor.getColumnIndex("url")));
//setEmptyData(paramCursor, R.drawable.mylist_empty_tips, R.string.file_explorer_no_data);
}
public View onCreateView(LayoutInflater paramLayoutInflater, ViewGroup paramViewGroup, Bundle paramBundle)
{
Log.d(LOGTAG, "onCreateView");
tabName = "stream";
View view = super.onCreateView(paramLayoutInflater, paramViewGroup, paramBundle);
changeMenuMore(R.attr.action_add_group, R.string.action_add_group, true);
return view;
}
private class StreamAdapterSetAsyncTask extends AsyncTask<Void, StreamAdapter, Void> {
@Override
protected Void doInBackground(Void... params) {
Log.d(LOGTAG, "streamURLArray size>>"+streamURLArray.size());
for (ArrayList<String> URL : streamURLArray) {
//StreamAdapter streamAdapter = new StreamAdapter(getActivity(), R.layout.file_explorer_stream_row, URL);
streamAdapterArray.add(streamAdapter);
publishProgress(streamAdapter);
}
return null;
}
@Override
protected void onProgressUpdate(StreamAdapter... streamAdapter) {
int currViewId = 1;
Log.d(LOGTAG, "onProgressUpdate");
Log.d(LOGTAG, "streamAdapterArray size>>"+streamAdapterArray.size());
// LinearLayout ll = (LinearLayout) findViewById(R.id.sousboissons_linearlayout);
Log.d(LOGTAG, "onProgressUpdate for");
// TextView sousCategorieTitle = new TextView(getActivity(), null);
// sousCategorieTitle.setText(streamAdapter1.sousCategory);
// sousCategorieTitle.setBackgroundColor(getResources().getColor(R.color.green));
// sousCategorieTitle.setTextSize(19);
// sousCategorieTitle.setTextColor(getResources().getColor(R.color.white));
// sousCategorieTitle.setGravity(Gravity.CENTER);
// LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,
// LinearLayout.LayoutParams.WRAP_CONTENT);
// layoutParams.setMargins(0, 0, 0, 0);
// sousCategorieTitle.setLayoutParams(layoutParams);
//setListAdapter(streamAdapter);
// LinearLayout.LayoutParams layoutParams2 = new LinearLayout.LayoutParams(
// LinearLayout.LayoutParams.FILL_PARENT,
// LinearLayout.LayoutParams.FILL_PARENT);
// layoutParams2.setMargins(17, 0, 17, 0);
// listview.setLayoutParams(layoutParams2);
//
// ll.setPadding(15, 15, 15, 0);
// ll.addView(sousCategorieTitle);
// ll.addView(listview);
currViewId++;
}
}
public Dialog onCreateDialog(int paramInt)
{
Log.d(LOGTAG, "onCreateDialog");
switch (paramInt)
{
default:
return super.onCreateDialog(paramInt);
case 1:
return openDialogSamba();
case 2:
return a();
}
}
public Loader<Cursor> onCreateLoader(int paramInt, Bundle paramBundle)
{
Log.d(LOGTAG, "onCreateLoader");
String[] proj2 = {"distinct replace("+CursorUtils.VIDEO_PATH+", "+CursorUtils.VIDEO_NAME+",'')", CursorUtils.VIDEO_ID};
return new CursorLoader(getActivity(), Video.Media.EXTERNAL_CONTENT_URI, proj2, null , null, null);
}
public void onLoadFinished(Loader<Cursor> paramLoader, Cursor paramCursor)
{
Log.d(LOGTAG, "onLoadFinished");
if (getActivity() == null)
return;
else
{
streamCursorAdapter.changeCursor(paramCursor);
streamAdapter.createChecked();
setEmptyData(paramCursor, R.drawable.mylist_empty_tips, R.string.file_explorer_no_data);
//restorePosition("stream_folder_last_selection", "stream_folder_last_scroll_top");
}
}
public void onDetach()
{
Log.d(LOGTAG, "onDetach");
super.onDetach();
getActivity().getContentResolver().unregisterContentObserver(fragmentStreamContentObserver);
}
public void onEditMenuClick(View paramView)
{
Log.d(LOGTAG, "onEditMenuClick");
switch (paramView.getId())
{
case 2131558530:
streamCursorAdapter.toggleChecked();
updateMenuStatus();
case 2131558531:
deleteCheckedGroup(streamCursorAdapter.getCheckedStreamFolder());
default:
case 2131558528:
a().show();
case 2131558529:
case 2131558532:
}
}
public void onItemClick(AdapterView paramAdapterView, View paramView, int paramInt, long paramLong)
{
Log.d(LOGTAG, "onItemClick");
switch (paramInt)
{
default:
case 0:
case 1:
case 2:
}
while (true)
{
// return;
// nd localnd = new nd(this, getActivity().getContentResolver());
// String[] arrayOfString1 = StreamCursorAdapter.StreamFolderQuery.ONE_FOLDER_PROJECTION;
// String[] arrayOfString2 = new String[1];
// arrayOfString2[0] = fileExplorerItem._id;
// localnd.startQuery(0, null, StreamProvider.CONTENT_URI, arrayOfString1, "parent_id = ? AND is_directory = 0", arrayOfString2, "access_count DESC");
// continue;
// deleteGroup(fileExplorerItem._id);
// continue;
// renameGroup(fileExplorerItem.name, fileExplorerItem._id);
}
}
public void onListItemClick(ListView paramListView, View paramView, int paramInt, long paramLong)
{
Log.d(LOGTAG, "onListItemClick");
Log.d(LOGTAG, "paramInt>>>" + paramInt);
if (isEditMode())
{
streamAdapter.setChecked(paramInt);
updateMenuStatus();
}
else
{
StreamListViewData streamListViewData = streamAdapter.getItem(paramInt);
String urlType = null;
String type = null;
if(streamListViewData.urlType == null){
return;
}
else{
urlType = streamListViewData.urlType;
}
if(streamListViewData.type == null){
return;}
else{
type = streamListViewData.type;
Log.i("HERE :" ,streamListViewData.data);
}
if(type.equals("URL"))
{
if(urlType.equals("Samba"))
{
}
else if(urlType.equals("Http"))
{
}
}
else if(type.equals("AddBtn"))
{
if(urlType.equals("Samba"))
{
openDialogSamba().show();
}
else if(urlType.equals("Http"))
{
openDialogHttp().show();
}
}
}
}
public void onLoaderReset(Loader paramLoader)
{
Log.d(LOGTAG, "onLoaderReset");
streamCursorAdapter.swapCursor(null);
}
public void wifiOnOff(MenuItem paramMenuItem)
{
String service = this.mContext.WIFI_SERVICE;
WifiManager wifi = (WifiManager)this.mContext.getSystemService(service);
if(!wifi.isWifiEnabled()){
if(wifi.getWifiState() != WifiManager.WIFI_STATE_ENABLED){
wifi.setWifiEnabled(true);
Log.i("DEBUG_TAG", "============wifi WIFI_STATE_ENABLED");
paramMenuItem.setIcon(R.drawable.action_wifi);
}
}else{
wifi.setWifiEnabled(false);
Log.i("DEBUG_TAG", "============wifi action_wifi_search");
paramMenuItem.setIcon(R.drawable.action_wifi_search);
}
}
public void onCreateOptionsMenu(Menu paramMenu, MenuInflater paramMenuInflater)
{
Log.d(LOGTAG, "onCreateOptionsMenu");
paramMenuInflater.inflate(R.menu.menu_stream_folder, paramMenu);
String service = this.mContext.WIFI_SERVICE;
WifiManager wifi = (WifiManager)this.mContext.getSystemService(service);
if(!wifi.isWifiEnabled())
{
paramMenu.findItem(R.id.menu_wifi).setIcon(R.drawable.action_wifi_search);
}
else
{
paramMenu.findItem(R.id.menu_wifi).setIcon(R.drawable.action_wifi);
}
super.onCreateOptionsMenu(paramMenu, paramMenuInflater);
}
public boolean onOptionsItemSelected(MenuItem paramMenuItem)
{
Log.d(LOGTAG, "onOptionsItemSelected");
switch (paramMenuItem.getItemId())
{
case R.id.menu_wifi:
wifiOnOff(paramMenuItem);
break;
case R.id.menu_search:
Intent intent = new Intent(getActivity(), WiFiDirectActivity.class);
startActivityForResult(intent, 1);
break;
case R.id.menu_open_url:
openDialogSamba().show();
break;
case R.id.menu_edit:
if (isEditMode())
{
setEditMode();
fragmentStreamEditListener.onCancelEditClick();
Log.d(LOGTAG, "onCancelEditClick!");
}
else
{
if(streamAdapter.getChecked().length != 0)
{
setEditMode();
fragmentStreamEditListener.onEditClick();
updateMenuStatus();
Log.d(LOGTAG, "onEditClick!");
}
}
break;
default:
}
return super.onOptionsItemSelected(paramMenuItem);
}
public void onPause()
{
Log.d(LOGTAG, "onPause");
super.onPause();
saveCurrentPosition("stream_folder_last_selection", "stream_folder_last_scroll_top");
}
public void onResume()
{
Log.d(LOGTAG, "onResume");
super.onResume();
}
public void renameGroup(String paramString, long paramLong)
{
// Log.d(LOGTAG, "renameGroup");
// AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()).setIcon(17301543);
// View view = LayoutInflater.from(getActivity()).inflate(2130968605, null);
// EditText localEditText = (EditText)view.findViewById(2131558458);
// builder.setTitle(paramString);
// localEditText.setText(paramString);
// builder.setView(view);
// builder.setPositiveButton(2131361875, new ng(this, localEditText, paramString, paramLong));
// builder.setNegativeButton(2131361876, null);
// builder.show();
}
public void updateMenuStatus()
{
Log.d(LOGTAG, "updateMenuStatus");
if (streamCursorAdapter == null)
return;
else
{
boolean[] itemsIsCheck = streamCursorAdapter.getChecked();
ImageView imageView = (ImageView)this.mMenuDelete.findViewById(2131558530);
if ((itemsIsCheck != null) && (isEditMode()))
{
int i = itemsIsCheck.length;
int j = 0;
int k = 0;
while (true)
{
if (j < i)
{
if (itemsIsCheck[j] != false)
{
imageView.setEnabled(true);
mMenuDelete.setEnabled(true);
}
}
else
{
if (k != itemsIsCheck.length)
break;
imageView.setEnabled(false);
mMenuDelete.setEnabled(false);
break;
}
k++;
j++;
}
}
imageView.setEnabled(false);
mMenuDelete.setEnabled(false);
}
}
protected Dialog openDialogSamba()
{
Log.d(LOGTAG, "urlOpenDialog");
return openDialogSamba(null);
}
protected Dialog openDialogHttp()
{
Log.d(LOGTAG, "urlOpenDialog");
return openDialogHttp(null);
}
protected Dialog openDialogSamba(Bundle paramBundle)
{
Log.d(LOGTAG, "urlOpenDialog");
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setIcon(UIUtils.getAttrValue(getActivity(), R.attr.file_url).resourceId);
View view = LayoutInflater.from(mContext).inflate(R.layout.dialog_add_samba, null);
EditText sambaUrlText = (EditText)view.findViewById(R.id.dialog_add_samba_url_edittext);
EditText sambaName = (EditText)view.findViewById(R.id.dialog_add_samba_name_edittext);
EditText sambaPwd = (EditText)view.findViewById(R.id.dialog_add_samba_pwd_edittext);
// if (paramBundle == null)
// {
//
// }
// else
// {
sambaUrlText.requestFocus();
sambaUrlText.setSelectAllOnFocus(true);
sambaUrlText.setSelection(0, sambaUrlText.getText().length());
//int size = aPreference_url.getAll().size();
((InputMethodManager)getActivity().getSystemService("input_method")).toggleSoftInput(2, 1);
builder.setTitle(R.string.dialog_add_samba_title);
builder.setView(view);
builder.setPositiveButton(R.string.dialog_button_ok, new DialogOKOnClickListener(this, sambaUrlText, sambaName, sambaPwd, "Samba"));
return setDismissDialog(builder, 1);
// }
}
protected Dialog openDialogHttp(Bundle paramBundle)
{
Log.d(LOGTAG, "urlOpenDialog");
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setIcon(UIUtils.getAttrValue(getActivity(), R.attr.file_url).resourceId);
View view = LayoutInflater.from(mContext).inflate(R.layout.dialog_add_http, null);
EditText httpUrlEditText = (EditText)view.findViewById(R.id.dialog_add_http_url_edittext);
httpUrlEditText.requestFocus();
httpUrlEditText.setSelectAllOnFocus(true);
httpUrlEditText.setSelection(0, httpUrlEditText.getText().length());
((InputMethodManager)getActivity().getSystemService("input_method")).toggleSoftInput(2, 1);
builder.setTitle(R.string.dialog_add_samba_title);
builder.setView(view);
builder.setPositiveButton(R.string.dialog_button_ok, new DialogOKOnClickListener(this, httpUrlEditText, null, null, "Http"));
return setDismissDialog(builder, 1);
}
public final class DialogOKOnClickListener
implements DialogInterface.OnClickListener
{
private EditText url;
private EditText name;
private EditText pwd;
private String type;
public DialogOKOnClickListener(FragmentStream paramFragmentStream, EditText url, EditText name, EditText pwd, String type)
{
this.url = url;
this.name = name;
this.pwd = pwd;
this.type = type;
}
public final void onClick(DialogInterface paramDialogInterface, int paramInt)
{
//streamListViewData.data = url.getText().toString();
//"smb://"+streamListViewData.data+"/"
//Log.d(LOGTAG, "sambaUrl>>>"+url.getText().toString() + name.getText().toString() + pwd.getText().toString());
db_open.insertTitle(url.getText().toString(), name.getText().toString(), pwd.getText().toString());
// database.insertTitle(url.getText().toString(), name.getText().toString(), pwd.getText().toString());
// cursor.requery();
StreamListViewData streamListViewData = new StreamListViewData();
streamListViewData.data = url.getText().toString();
streamListViewData.type = "URL";
streamListViewData.urlType = type;
//Log.i("TYPE", "TYPE :" + type);//Samba
streamAdapter.add(streamListViewData);
// String str = this.a.getText().toString().trim();
// if (!TextUtils.isEmpty(str))
// {
// int i = 0;
// int j = this.b.getSelectedItemPosition();
// if (j >= 0)
// i = ((BaseFragment.Group)this.c.get(j)).id;
// Intent localIntent = new Intent(this.e.getActivity(), VideoPlayActivity.class);
// localIntent.setAction("android.intent.action.SEND");
// localIntent.putExtra("urlName", this.d.getText().toString());
// localIntent.putExtra("groupId", i);
// localIntent.setData(Uri.parse(str));
// this.e.startActivity(localIntent);
// }
// this.e.removeDialog(1);
}
}
public class FragmentStreamContentObserver extends ContentObserver {
private final String LOGTAG = "MyContentObserver";
private FragmentStream fragmentStream;
public FragmentStreamContentObserver(FragmentStream fragmentStream, Handler handler) {
super(handler);
// TODO Auto-generated constructor stub
fragmentStream = fragmentStream;
}
public final void onChange(boolean paramBoolean)
{
Log.d(LOGTAG, "onChange");
if (fragmentStream.getActivity() == null)
{
Log.d(LOGTAG, "getActivity null");
return;
}
else
{
Loader loader = fragmentStream.getLoaderManager().getLoader(2);
Log.d(LOGTAG, "getActivity not null");
if (loader != null)
{
Log.d(LOGTAG, "loader not null forceLoad");
loader.forceLoad();
}
}
}
}
}
| true
|
9dde0a2ff949005ee48b6eb850ff46291714621e
|
Java
|
dan975/selenium-browser
|
/src/main/java/demo/projects/sut/mapping/pages/ProductQuickViewPage.java
|
UTF-8
| 9,924
| 2.234375
| 2
|
[] |
no_license
|
package demo.projects.sut.mapping.pages;
import demo.projects.sut.mapping.selectors.pages.base.ProductPageSelectors;
import demo.projects.sut.mapping.test.data.ProductContent;
import demo.projects.test.framework.annotations.ThreadComponent;
import demo.projects.test.framework.driver.abstraction.WebElementWrapper;
import lombok.Setter;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.FluentWait;
import org.springframework.beans.factory.annotation.Autowired;
import java.time.Duration;
import java.util.List;
import java.util.stream.Collectors;
import static demo.projects.Constants.ONE_SECOND_IN_MILLISECONDS;
import static java.time.temporal.ChronoUnit.SECONDS;
import static org.junit.Assert.assertEquals;
/**
* Product quick view page.
* Pop up displayed to user when clicking "Quick view" after hovering
* on {@link demo.projects.sut.mapping.element.wrappers.ProductCard}'s image element.
* <p>
* Demo note:
* Quick view pop up is displayed in an iframe.
* Page object implements frame switching logic, where page has a flag for checking whether current quick view's
* iframe is focused when retrieving the page's elements and switches to "Quick view"'s iframe or default content
* as needed.
* <p>
* Since this is the only GUI node encapsulating object of the SUT that requires iframe switching
* the provided solution suffices. However in real life case a more robust and easier to maintain logic of
* switching iframes should be implemented as follows:
* 1. Create Enum for currently focused frame, with an enum value for each SUT iframe that requires to be
* switched to during test run and default content.
* 2. Encapsulate logic for switching to each frame in a single class such as
* {@link demo.projects.test.framework.driver.abstraction.DriverWrapper} or {@link BasePageComponent}
* and store the enum value of currently focused on iframe, default content.
* 3. Before call to Selenium driver server to retrieve {@link WebElement} check whether correct iframe
* or default content is focused on for WebElement retrieval call.
* 4. In after each test case hook reset the focused view enum value
* in object defined in step 2. to default content view.
* <p>
* The check and switch defined in step 3. can be implemented by adding the method call
* to each {@link WebElement} retrieval call as is currently implemented in this "Quick View"'s page object or
* by AOP by creating an aspect with before advices where for different page object
* different before advice would be applied.
*/
@Slf4j
@ThreadComponent
public class ProductQuickViewPage extends BasePageComponent {
private static final int QUICK_VIEW_LOAD_TIME_OUT_IN_SECONDS = 9;
private static final String ON_SALE_CONTENT_PRICE_TEXT_BASE = "$%.2f\n-%d%%\n$%.2f";
private static final String REGULAR_CONTENT_PRICE_TEXT_BASE = "$%.2f";
@Autowired
private ProductPageSelectors productPageSelectors;
@Setter
private boolean isFocusedOnQuickViewFrame = false;
/**
* @return Image displayed above product image thumbnails element.
*/
public WebElementWrapper getPrimaryImage() {
switchToQuickViewFrameIfNotFocused();
return getDriverWrapper().waitUntilVisible(productPageSelectors.getPrimaryImage());
}
/**
* @return Product title element.
*/
public WebElementWrapper getTitle() {
switchToQuickViewFrameIfNotFocused();
return getDriverWrapper().waitUntilVisible(productPageSelectors.getTitle());
}
/**
* Method asserts product's title, price content, description are as expected.
*
* Demo note:
* Product page contains more GUI elements with product specific text contents
* (e.g. Model name, product condition). Same as with {@link ProductPage} text content assertion is partial.
* @param productContent Expected product content.
*/
public void assertTextContentIsAsExpected(ProductContent productContent) {
log.info("asserting text content for product content {}", productContent);
var expectedTitle = productContent.getTitle();
var actualTitle = getTitle().getText();
assertEquals(expectedTitle, actualTitle);
var expectedPriceContent = getExpectedContentPriceText(productContent);
String actualPriceContent = getPriceContent().getText();
assertEquals(expectedPriceContent, actualPriceContent);
var expectedDescription = productContent.getDescription();
var actualDescription = getDescription().getText();
assertEquals(expectedDescription, actualDescription);
}
private String getExpectedContentPriceText(ProductContent productContent) {
if (productContent.isProductOnSale()) {
return getSaleContentPriceText(productContent);
} else {
return getRegularContentPriceText(productContent);
}
}
private String getSaleContentPriceText(ProductContent productContent) {
var regularPrice = productContent.getRegularPrice();
var salePrice = productContent.getSalePrice();
var salePercentage = productContent.getSalePercentage();
return String.format(ON_SALE_CONTENT_PRICE_TEXT_BASE, salePrice, salePercentage, regularPrice);
}
private String getRegularContentPriceText(ProductContent productContent) {
double regularPrice = productContent.getRegularPrice();
return String.format(REGULAR_CONTENT_PRICE_TEXT_BASE, regularPrice);
}
/**
* @return Price content element.
*/
public WebElementWrapper getPriceContent() {
switchToQuickViewFrameIfNotFocused();
return getDriverWrapper().waitUntilVisible(productPageSelectors.getPriceContent());
}
/**
* @return Description element.
*/
public WebElementWrapper getDescription() {
switchToQuickViewFrameIfNotFocused();
return getDriverWrapper().waitUntilVisible(productPageSelectors.getDescription());
}
/**
* @return Quantity input element.
*/
public WebElementWrapper getQuantityInput() {
switchToQuickViewFrameIfNotFocused();
return getDriverWrapper().waitUntilVisible(productPageSelectors.getQuantityInput());
}
/**
* Method clicks add to cart button.
* <p>
* Clicking encapsulated in separate method so as to ensure switching back to default content.
*/
public void clickAddToCartBtn() {
getAddToCartBtn().click();
switchToDefaultContentIfNotFocused();
}
private WebElementWrapper getAddToCartBtn() {
switchToQuickViewFrameIfNotFocused();
return getDriverWrapper().waitUntilVisible(productPageSelectors.getAddToCartBtn());
}
/**
* @return Color selection option elements.
*/
public List<WebElementWrapper> getColorOptions() {
switchToQuickViewFrameIfNotFocused();
return getDriverWrapper().waitUntilFirstVisibleAndFindAll(productPageSelectors.getColorOption());
}
/**
* @return Thumbnail elements.
*/
public List<WebElementWrapper> getThumbnails() {
switchToQuickViewFrameIfNotFocused();
var res = getDriverWrapper().getDriver().findElements(productPageSelectors.getThumbnail());
return res.stream()
.filter(WebElement::isDisplayed)
.map(e -> getWebElementWrapperFactory().getWebElementWrapper(e))
.collect(Collectors.toList());
}
/**
* @return Close quick view button.
*/
public WebElementWrapper getCloseQuickViewBtn() {
switchToDefaultContentIfNotFocused();
return getDriverWrapper().waitUntilVisible(productPageSelectors.getCloseQuickViewBtn());
}
private void switchToDefaultContentIfNotFocused() {
log.debug("isFocusedOnQuickViewFrame = {}.", isFocusedOnQuickViewFrame);
if (isFocusedOnQuickViewFrame) {
log.debug("switching frames");
getDriverWrapper().getDriver().switchTo().defaultContent();
log.debug("switched to default view");
isFocusedOnQuickViewFrame = false;
}
}
private void switchToQuickViewFrameIfNotFocused() {
log.debug("isFocusedOnQuickViewFrame = {}.", isFocusedOnQuickViewFrame);
if (!isFocusedOnQuickViewFrame) {
log.debug("switched frames");
switchToQuickViewFrame();
isFocusedOnQuickViewFrame = true;
}
}
@SneakyThrows
private void switchToQuickViewFrame() {
waitUntilQuickViewFinishedLoading();
var quickViewFrame = getQuickViewFrame();
getDriverWrapper().getDriver().switchTo().frame(quickViewFrame);
Thread.sleep(ONE_SECOND_IN_MILLISECONDS);
}
private WebElement getQuickViewFrame() {
return getDriverWrapper().getDriver().findElement(productPageSelectors.getQuickViewFrame());
}
/**
* Method waits until quick view loading spinner disappears indicating "Quick view" pop up loaded.
*/
public void waitUntilQuickViewFinishedLoading() {
FluentWait<WebDriver> waitForSpinner = new FluentWait<>(getDriverWrapper().getDriver())
.withTimeout(Duration.of(QUICK_VIEW_LOAD_TIME_OUT_IN_SECONDS, SECONDS))
.pollingEvery(Duration.of(1, SECONDS))
.ignoring(NoSuchElementException.class);
By spinnerSelector = productPageSelectors.getQuickViewLoadingSpinner();
waitForSpinner.until((ExpectedCondition<Boolean>) driver -> {
log.trace("waiting for spinner to disappear");
return driver.findElements(spinnerSelector).size() == 0;
});
}
}
| true
|
a89b2dde4ef3d34b39faf26708825874a6657899
|
Java
|
Myrninvollo/LOTR-Minecraft-Mod
|
/LOTR/src/main/java/lotr/client/render/entity/LOTRRenderRabbit.java
|
UTF-8
| 1,073
| 2.21875
| 2
|
[] |
no_license
|
package lotr.client.render.entity;
import java.util.HashMap;
import java.util.Map;
import lotr.client.model.LOTRModelRabbit;
import lotr.common.entity.animal.LOTREntityRabbit;
import net.minecraft.client.renderer.entity.RenderLiving;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.util.ResourceLocation;
import org.lwjgl.opengl.GL11;
public class LOTRRenderRabbit extends RenderLiving
{
private static Map rabbitSkins = new HashMap();
public LOTRRenderRabbit()
{
super(new LOTRModelRabbit(), 0.3F);
}
@Override
protected ResourceLocation getEntityTexture(Entity entity)
{
int i = ((LOTREntityRabbit)entity).getRabbitType();
String s = String.valueOf(i);
ResourceLocation r = (ResourceLocation)rabbitSkins.get(s);
if (r == null)
{
r = new ResourceLocation("lotr:mob/rabbit/" + s + ".png");
rabbitSkins.put(s, r);
}
return r;
}
@Override
protected void preRenderCallback(EntityLivingBase entity, float f)
{
GL11.glScalef(0.75F, 0.75F, 0.75F);
}
}
| true
|
e854c68d20835dbd2369b91faa4053dda8e35671
|
Java
|
sachinshikhare/exchange-rates-backend-service
|
/src/test/java/com/example/exchangeratesservice/controller/ExchangeRatesControllerTest.java
|
UTF-8
| 3,714
| 2.015625
| 2
|
[] |
no_license
|
package com.example.exchangeratesservice.controller;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.when;
import com.example.exchangeratesservice.ExchangeRatesServiceApplication;
import com.example.exchangeratesservice.TestDataSetup;
import com.example.exchangeratesservice.model.ExchangeRatesResponse;
import com.example.exchangeratesservice.service.ExchangeRatesService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import org.junit.Before;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.json.JsonParseException;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import static org.junit.Assert.*;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = ExchangeRatesServiceApplication.class)
@WebAppConfiguration
public class ExchangeRatesControllerTest{
protected MockMvc mvc;
@MockBean
ExchangeRatesService exchangeRatesService;
@Autowired
WebApplicationContext webApplicationContext;
@BeforeEach
public void setUp() {
mvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
@Test
public void testFetchExchangeRatesFromExternalService() throws Exception {
when(exchangeRatesService.fetchAndSaveHistoricExchangeRates(anyString(), anyString(), anyInt())).thenReturn(true);
String uri = "/api/v1/exchange-rates";
MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.get(uri)
.accept(MediaType.APPLICATION_JSON_VALUE)).andReturn();
int status = mvcResult.getResponse().getStatus();
assertEquals(200, status);
}
@Test
public void testGetExchangeRates() throws Exception {
when(exchangeRatesService.retrieveExchangeRates()).thenReturn(TestDataSetup.getExchangeRatesResponse());
String uri = "/api/v1/exchange-rates/months";
MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.get(uri)
.accept(MediaType.APPLICATION_JSON_VALUE)).andReturn();
int status = mvcResult.getResponse().getStatus();
assertEquals(200, status);
System.out.println("resp: " + mvcResult.getResponse().getContentAsString());
ExchangeRatesResponse response = mapFromJson(mvcResult.getResponse().getContentAsString(), ExchangeRatesResponse.class);
assertEquals("USD", response.getBaseCurrency());
}
protected String mapToJson(Object obj) throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.writeValueAsString(obj);
}
protected <T> T mapFromJson(String json, Class<T> clazz)
throws JsonParseException, JsonMappingException, IOException {
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.readValue(json, clazz);
}
}
| true
|
6482402a192afff66a5759c1c9f0cbfd42aaff15
|
Java
|
zhuyihao/NewIM
|
/newim-gateway/src/main/java/com/whosbean/newim/gateway/handler/WsConnectedHandler.java
|
UTF-8
| 1,620
| 2.328125
| 2
|
[] |
no_license
|
package com.whosbean.newim.gateway.handler;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.util.CharsetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Created by yaming_deng on 14-9-5.
*/
public class WsConnectedHandler extends SimpleChannelInboundHandler<FullHttpRequest>
{
protected static Logger logger = LoggerFactory.getLogger(WsConnectedHandler.class);
public WsConnectedHandler() {
super(false);
}
private static final ByteBuf NOT_FOUND =
Unpooled.unreleasableBuffer(Unpooled.copiedBuffer("NOT FOUND", CharsetUtil.US_ASCII));
@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest req)
throws Exception
{
String uri = req.getUri();
// add websocket handler for the request uri where app lives
ChannelPipeline pipeline = ctx.pipeline();
pipeline.addLast(new WsServerProtocolHandler(uri));
// now add our application handler
pipeline.addLast(new WsMessageHandler());
// remConnection, app is attached and websocket handler in place
pipeline.remove(this);
// pass the request on
ctx.fireChannelRead(req);
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
super.channelInactive(ctx);
logger.info("WsConnection inactive.");
}
}
| true
|
a7489445b0aebdb504d9d4749331244bce93c04e
|
Java
|
liwen666/component
|
/coding_tx/src/main/java/com/temp/common/base/excel/table/TableModel.java
|
UTF-8
| 2,291
| 2.4375
| 2
|
[] |
no_license
|
package com.temp.common.base.excel.table;
import lombok.*;
import lombok.experimental.Accessors;
import lombok.extern.slf4j.Slf4j;
import java.lang.reflect.Field;
/**
* <p>
* 描述
* </p>
*
* @author lw
* @since 2019/5/26 23:40
*/
@Data
@Getter
@Setter
@Slf4j
@Builder
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
public class TableModel {
private String[] firtLine = {"教育系统新冠肺炎疫情防控期学生信息登记表"};
private String[] secoundLine = {"学校", "一小", "年级:四年级", "班级:一班", "填表日期: 2020年 2 月 9 日"};
private String[] thridLine = {"姓名", "性别", "身份证号", "家庭住址", "联系电话", "学校意见与建议:"};
private String[] line4 = {"冯灿", "女", "411526200910070185", "彭畈村大梓树组", "1569198173"};
private String[] line5 = {"本人近期身体状况","", "正常","","", "负责人\t\n签 字:"};
private String[] line6 = {"本人近十四天活动轨迹","", "居家","",""};
private String[] line7 = {"居家其他亲属","", "正常","",""};
private String[] line8 = {"居家其他亲属近期身体状况","", "正常","","", "2020年 月 日"};
private String[] line9 = {"(此表全校学生一人一份)"};
private String[] line10 = {"填表人:", "冯灿", "","本人(家长)签字:", "审核人:"};
private String[] line11 = {"说明:1、“近十四天活动轨迹”填2月1日后生活的地点和走过的地方;"};
private String[] line12 = {" 2、“身体状况”填有无确诊病例、疑似病例、发热或正常等情况;"};
private String[] line13 = {" 3、“学校意见与建议”填可以入班、在家隔离、到医院就诊等。"};
public static void main(String[] args) {
Field[] declaredFields = TableModel.class.getDeclaredFields();
System.out.println(declaredFields.length);
int line = declaredFields.length;
for (Field f : declaredFields) {
if (f.getName().equals("log")) {
line -= 1;
continue;
}
System.out.println(f.getName());
}
System.out.println(line);
}
}
| true
|
cc2e43ee666e9e491d7ff4d19c5065003f82b0da
|
Java
|
Antonyan/rocket-test
|
/src/main/java/core/modules/database/models/DbQueryMetadata.java
|
UTF-8
| 488
| 2.28125
| 2
|
[
"MIT"
] |
permissive
|
package core.modules.database.models;
import java.util.Map;
public class DbQueryMetadata {
private final String tableName;
private final Map<String, String> tableData;
public DbQueryMetadata(String tableName, Map<String, String> tableData) {
this.tableName = tableName;
this.tableData = tableData;
}
public String getTableName() {
return tableName;
}
public Map<String, String> getTableData() {
return tableData;
}
}
| true
|
cdba1ff943abcf5434b5e769ab743af46ee577c1
|
Java
|
zhangkang65/ERP-Project
|
/src/main/java/com/dy/bus/vo/SalesVo.java
|
UTF-8
| 501
| 1.867188
| 2
|
[] |
no_license
|
package com.dy.bus.vo;/**
* ClassName:SalesVo
* Package:com.dy.bus.vo
* Description:
*
* @Date:2020/3/24 10:51
* @Author:Dong
*/
import com.dy.bus.entity.Sales;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Date;
/**
*ClassName:SalesVo
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class SalesVo extends Sales {
private Integer page;
private Integer limit;
private Date begintime;
private Date endtime;
}
| true
|
7ebeba9d41637a1518bfd8b83656b66f09c7b18e
|
Java
|
MinJu-A/INHA_AIR
|
/INHA_AIR/src/be/Inquiry/Inquiry.java
|
UTF-8
| 5,720
| 2.5625
| 3
|
[] |
no_license
|
package be.Inquiry;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Font;
import java.awt.Menu;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.LineBorder;
import be.main.MainForm;
import be.menu.MenuBar;
public class Inquiry extends JFrame implements ActionListener {
// Title 및 사이즈 설정
private String title = "INHA AIR";
private int width = 1120, height = 770;
// 상단 메뉴바
private MenuBar menubar;
//--가상의 고객이 선택한 정보
private JPanel jpInquiry1; // 시간 선택시 비행기1
private JPanel jpInquiry2; // 비행기 2
private JPanel jpInquiry3; // 비행기 3
private Color crInfo = new Color(240,240,240);//고객이 선택한 정보를 나타내는 바의 색
private Color crGrey = new Color(230,240,250);
private Color crPaleblue = new Color(230,240,250);
Font fontGothic = new Font("Gothic", Font.BOLD, 20); // 고딕
Font fontNanumGothic9 = new Font("NanumGothic", Font.BOLD, 9); // 나눔고딕 18
Font fontNanumGothic12 = new Font("NanumGothic", Font.BOLD, 12); // 나눔고딕 18
Font fontNanumGothic15= new Font("NanumGothic", Font.BOLD, 15); // 나눔고딕 18
Font fontNanumGothic18 = new Font("NanumGothic", Font.BOLD, 18); // 나눔고딕 18
Font fontNanumGothic18Plain = new Font("NanumGothic", Font.PLAIN, 18); // 나눔고딕 18
Font fontNanumGothic20 = new Font("NanumGothic", Font.BOLD, 20); // 나눔고딕 20
Font fontNanumGothic22 = new Font("NanumGothic", Font.BOLD, 22); // 나눔고딕 20
Font fontNanumGothic25 = new Font("NanumGothic", Font.BOLD, 25); // 나눔고딕 25
Font fontNanumGothic30 = new Font("NanumGothic", Font.BOLD, 30); // 나눔고딕 30
private JPanel jpInquiryTop;
private JPanel jpInquiry4;
private JLabel lblRNum;
private JLabel lblRName;
private Component lblRDate;
private JLabel lblRDep;
private Component lblRArr;
private Component lblRSeat;
private JButton btnDetail1;
private Component btnDetail2;
private JButton btnDetail3;
private Component btnDetail4;
public Inquiry() {
setTitle(title);
setSize(width, height);
setResizable(false);
setLocationRelativeTo(this);
setDefaultCloseOperation(EXIT_ON_CLOSE);
// 레이아웃 설정
setLayout(null);
// 배경색
Container c = getContentPane();
c.setBackground(Color.WHITE);
// 상단 메뉴바
setUpMenu();
jpInquiryTop = new JPanel(); //고객이 선택한 정보를 표시하는 바
jpInquiryTop.setLayout(null);
jpInquiryTop.setSize(1000,42);
jpInquiryTop.setLocation(70,100);
jpInquiryTop.setBackground(crGrey);
lblRNum = new JLabel("예약 번호");
lblRNum.setBounds(80, 10, 80, 20);
lblRNum.setFont(fontNanumGothic15);
lblRName = new JLabel("예약자명");
lblRName.setBounds(230, 10, 80, 20);
lblRName.setFont(fontNanumGothic15);
lblRDate = new JLabel("가는 날");
lblRDate.setBounds(380, 10, 80, 20);
lblRDate.setFont(fontNanumGothic15);
lblRDep = new JLabel("출발");
lblRDep.setBounds(530, 10, 80, 20);
lblRDep.setFont(fontNanumGothic15);
lblRArr = new JLabel("도착");
lblRArr.setBounds(650, 10, 80, 20);
lblRArr.setFont(fontNanumGothic15);
lblRSeat = new JLabel("좌석");
lblRSeat.setBounds(770, 10, 80, 20);
lblRSeat.setFont(fontNanumGothic15);
btnDetail1 = new JButton("예약 상세");
btnDetail1.setBounds(880, 40, 90, 35);
btnDetail1.setFont(fontNanumGothic12);
btnDetail1.setBackground(crPaleblue);
btnDetail1.addActionListener(this);
btnDetail2 = new JButton("예약 상세");
btnDetail2.setBounds(880, 40, 90, 35);
btnDetail2.setFont(fontNanumGothic12);
btnDetail2.setBackground(crPaleblue);
btnDetail3 = new JButton("예약 상세");
btnDetail3.setBounds(880, 40, 90, 35);
btnDetail3.setFont(fontNanumGothic12);
btnDetail3.setBackground(crPaleblue);
btnDetail4 = new JButton("예약 상세");
btnDetail4.setBounds(880, 40, 90, 35);
btnDetail4.setFont(fontNanumGothic12);
btnDetail4.setBackground(crPaleblue);
jpInquiryTop.add(lblRNum);
jpInquiryTop.add(lblRName);
jpInquiryTop.add(lblRDate);
jpInquiryTop.add(lblRDep);
jpInquiryTop.add(lblRArr);
jpInquiryTop.add(lblRSeat);
jpInquiry1 = new JPanel(); //3개의 시간표 중 선택 1
jpInquiry1.setLayout(null);
jpInquiry1.setSize(1000,110);
jpInquiry1.setLocation(70,152);
jpInquiry1.setBackground(crInfo);
jpInquiry2 = new JPanel();//선택 2
jpInquiry2.setLayout(null);
jpInquiry2.setSize(1000,110);
jpInquiry2.setLocation(70,274);
jpInquiry2.setBackground(crInfo);
jpInquiry3 = new JPanel();// 선택 3
jpInquiry3.setLayout(null);
jpInquiry3.setSize(1000,110);
jpInquiry3.setLocation(70,396);
jpInquiry3.setBackground(crInfo);
jpInquiry4 = new JPanel();// 선택 3
jpInquiry4.setLayout(null);
jpInquiry4.setSize(1000,110);
jpInquiry4.setLocation(70,518);
jpInquiry4.setBackground(crInfo);
jpInquiry1.add(btnDetail1);
jpInquiry2.add(btnDetail2);
jpInquiry3.add(btnDetail3);
jpInquiry4.add(btnDetail4);
add(jpInquiryTop);
add(jpInquiry1);
add(jpInquiry2);
add(jpInquiry3);
add(jpInquiry4);
setVisible(true);
}
// 상단 메뉴바
private void setUpMenu() {
menubar = new MenuBar();
add(menubar.getPnTOP());
}
public static void main(String[] args) {
new Inquiry();
}
@Override
public void actionPerformed(ActionEvent e) {
Object obj = e.getSource();
if(obj == btnDetail1) {
MemberInquiryDetail Mid = new MemberInquiryDetail();
}
}
}
| true
|
9f007c9d5a48879c8c5edbf71c652a058ac9f5ed
|
Java
|
tinyDong/algorithm
|
/src/Practice/minTree.java
|
UTF-8
| 1,284
| 3.25
| 3
|
[] |
no_license
|
package Practice;
import java.util.ArrayList;
import java.util.Arrays;
public class minTree {
private static int[] prim(int[][] matrix) {
int[] parents = new int[matrix.length];
parents[0] = -1;
ArrayList<Integer> reachedList = new ArrayList<>();
reachedList.add(0);
int from = 0 , to = 0;
while (reachedList.size() < matrix.length){
Integer weight = Integer.MAX_VALUE;
for (Integer reached :reachedList) {
for (int i = 0; i < matrix.length; i++) {
if (!reachedList.contains(i)&&matrix[reached][i]<weight){
weight = matrix[reached][i];
from = reached;
to = i;
}
}
}
reachedList.add(to);
parents[to] = from;
}
return parents;
}
public static void main(String[] args) {
int[][] matrix = new int[][]{
{0, 4, 3, 100, 100},
{4, 0, 8, 7, 0},
{3, 8, 0, 100, 1},
{100, 7, 100, 0, 9},
{100, 100, 1, 9, 0}
};
int[] rparents = prim(matrix);
System.out.println(Arrays.toString(rparents));
}
}
| true
|
c9e1a035cbf7c7d0670afd18ff6c65c40bb2536e
|
Java
|
sinnott74/DanSin
|
/WebClient/src/dansin/interceptors/ejb/EJBInterceptor.java
|
UTF-8
| 5,239
| 2.265625
| 2
|
[] |
no_license
|
package dansin.interceptors.ejb;
import java.lang.reflect.Field;
import java.util.Properties;
import javax.ejb.EJB;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NameClassPair;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
public class EJBInterceptor extends AbstractInterceptor {
private static final long serialVersionUID = 6562306000097938512L;
private String context = new String();
private boolean debug = false;
public void setContext(String context) {
this.context = context;
}
public String getContext() {
return context;
}
public void setDebug(boolean debug) {
this.debug = debug;
}
public boolean isDebug() {
return debug;
}
@Override
public String intercept(ActionInvocation invocation)
throws ClassCastException, Exception {
Object action = invocation.getAction();
for (Field field : action.getClass().getDeclaredFields()) {
if (field.isAnnotationPresent(EJB.class)) {
Properties prop=new Properties();
prop.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.openejb.client.RemoteInitialContextFactory");
prop.put("java.naming.provider.url", "ejbd://localhost:4201");
InitialContext initialContext = new InitialContext(prop);
String mappedName = field.getAnnotation(EJB.class).mappedName();
Object ejb = null;
if (null != mappedName && 0 != mappedName.trim().length()) {
try {
if (debug) {
System.out.println("Lookup " + mappedName.trim());
}
ejb = initialContext.lookup(mappedName.trim());
} catch (NamingException e) {
}
} else {
try {
if (debug) {
System.out.println("Lookup "
+ field.getType().getSimpleName());
}
ejb = initialContext.lookup(field.getType()
.getSimpleName());
} catch (NamingException e) {
}
if (null == ejb) {
try {
if (debug) {
System.out.println("Lookup "
+ field.getType().getName());
}
ejb = initialContext.lookup(field.getType()
.getName());
} catch (NamingException e) {
}
}
if (null == ejb) {
ejb = lookup(initialContext, context.split(","), field);
}
if (null == ejb) {
ejb = lookup(initialContext, initialContext.list(""),
field, true);
}
}
if (null != ejb) {
boolean wasAccessable = field.isAccessible();
field.setAccessible(true);
field.set(action, field.getType().cast(ejb));
field.setAccessible(wasAccessable);
}
}
}
return invocation.invoke();
}
private Object lookup(InitialContext initialContext, String[] contexts,
Field field) {
Object ejb = null;
for (String context : contexts) {
try {
if (debug) {
System.out.println("Lookup "
+ (context.endsWith("/") ? context.substring(0,
context.lastIndexOf("/")) : context) + "/"
+ field.getType().getName());
}
ejb = initialContext.lookup((context.endsWith("/") ? context
.substring(0, context.lastIndexOf("/")) : context)
+ "/" + field.getType().getName());
} catch (NamingException e) {
}
if (null == ejb) {
try {
if (debug) {
System.out.println("Lookup "
+ (context.endsWith("/") ? context.substring(0,
context.lastIndexOf("/")) : context)
+ "/" + field.getType().getSimpleName());
}
ejb = initialContext
.lookup((context.endsWith("/") ? context.substring(
0, context.lastIndexOf("/")) : context)
+ "/" + field.getType().getSimpleName());
} catch (NamingException e) {
}
}
if (null != ejb) {
break;
}
ejb = null;
}
return ejb;
}
private Object lookup(InitialContext initialContext,
NamingEnumeration<NameClassPair> namingEnumeration, Field field,
boolean recurse) {
Object ejb = null;
try {
while (namingEnumeration.hasMore()) {
NameClassPair next;
try {
next = namingEnumeration.next();
} catch (NamingException e) {
continue;
}
if (null == next) {
continue;
}
try {
if (debug) {
System.out.println("Lookup " + next.getName() + "/"
+ field.getType().getName());
}
ejb = initialContext.lookup(next.getName() + "/"
+ field.getType().getName());
} catch (NamingException e) {
}
if (null == ejb) {
try {
if (debug) {
System.out.println("Lookup " + next.getName() + "/"
+ field.getType().getSimpleName());
}
ejb = initialContext.lookup(next.getName() + "/"
+ field.getType().getSimpleName());
} catch (NamingException e) {
}
}
if (null == ejb && recurse) {
return lookup(initialContext,
initialContext.list(next.getName()), field, recurse);
}
if (null != ejb) {
break;
}
ejb = null;
}
} catch (NamingException e) {
}
return ejb;
}
}
| true
|
fcb1f857cef44d9c798ac023e74cda78929af5d7
|
Java
|
richie1412/git_hub_rep
|
/wxxr-mobile-client/wxxr-mobile-communicationhelper-android-quanguo/src/com/wxxr/callhelper/qg/ui/SiMiContactsResetPasswordActivity.java
|
UTF-8
| 7,440
| 1.945313
| 2
|
[] |
no_license
|
package com.wxxr.callhelper.qg.ui;
import java.util.HashMap;
import java.util.concurrent.Callable;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.wxxr.callhelper.qg.R;
import com.wxxr.callhelper.qg.CMProgressMonitor;
import com.wxxr.callhelper.qg.IPrivateSMService;
import com.wxxr.callhelper.qg.IPrivateSimiNetService;
import com.wxxr.callhelper.qg.constant.Constant;
import com.wxxr.callhelper.qg.framework.BaseActivity;
import com.wxxr.callhelper.qg.ui.gd.GDCMProgressMonitor;
import com.wxxr.callhelper.qg.ui.gd.GDSimiContactsActvity;
import com.wxxr.callhelper.qg.utils.Tools;
import com.wxxr.mobile.core.api.AbstractProgressMonitor;
/**
* 充值密码的弹出框 , 和 验证 失败 的弹出框
*
* @author yangrunfei
*
*/
public class SiMiContactsResetPasswordActivity extends BaseActivity {
private EditText tv_contact_num;
private TextView ll_concel, ll_sure, ll_sure_check;
private boolean showErrTip = false;
private TextView tv_simi_errcodetip;
private LinearLayout gd_simi_input_div;
private TextView tv_title_name;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.gd_resetpass);
String err = getIntent().getStringExtra("errcheckcode");
tv_simi_errcodetip = (TextView) findViewById(R.id.tv_simi_errcodetip);
gd_simi_input_div = (LinearLayout) findViewById(R.id.gd_simi_input_div);
tv_title_name = (TextView) findViewById(R.id.tv_dialog_top);
if (err != null && err.length() > 0) {
tv_title_name.setText("检验码有错误");
gd_simi_input_div.setVisibility(View.GONE);
tv_simi_errcodetip.setVisibility(View.VISIBLE);
} else {
TextView tip = (TextView) findViewById(R.id.et_simi_divline);
String text = tip.getText().toString();
String email_address = getService(IPrivateSMService.class)
.getBindedEmail();
text = text.replace("#", email_address);
tip.setText(text);
}
ll_concel = (TextView) findViewById(R.id.ll_simi_add_concel);
ll_concel.setOnClickListener(this);
ll_sure_check = (TextView) findViewById(R.id.ll_simi_add_check);
ll_sure = (TextView) findViewById(R.id.ll_simi_add_sure);
ll_sure.setOnClickListener(this);
tv_contact_num = (EditText) findViewById(R.id.et_simi_authcode);
tv_contact_num.addTextChangedListener(new TextWatcher() {
@Override
public void afterTextChanged(Editable s) {
if(s.length() > 0){
ll_sure.setVisibility(View.VISIBLE);
ll_sure_check.setVisibility(View.GONE);
}else{
ll_sure.setVisibility(View.GONE);
ll_sure_check.setVisibility(View.VISIBLE);
}
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
});
sendEmailMsg();
}
void showVercodeErr() {
showErrTip = true;
tv_title_name.setText("检验码有错误");
gd_simi_input_div.setVisibility(View.GONE);
tv_simi_errcodetip.setText(Tools.ToDBC(tv_simi_errcodetip.getText().toString()));
tv_simi_errcodetip.setVisibility(View.VISIBLE);
ll_sure.setVisibility(View.VISIBLE);
ll_sure_check.setVisibility(View.GONE);
ll_concel.setText("需要客服协助");
ll_sure.setText("返回");
}
private void sendEmailMsg() {
CMProgressMonitor monitor = new CMProgressMonitor(this) {
@Override
protected void handleDone(Object returnVal) {
if (returnVal instanceof Boolean) {
if ((Boolean) returnVal) {
// goInputCodepage();
} else {
// showMessageBox("发送验证码邮件失败,请重试");
Toast.makeText(SiMiContactsResetPasswordActivity.this, "发送验证码邮件失败,请重试", 1).show();
}
} else {
// showMessageBox("发送验证码邮件失败,请重试");
Toast.makeText(SiMiContactsResetPasswordActivity.this, "发送验证码邮件失败,请重试", 1).show();
}
}
@Override
protected void handleFailed(Throwable cause) {
}
// @Override
// protected Map<String, Object> getDialogParams() {
// Map<String, Object> map = new HashMap<String, Object>();
// map.put(DIALOG_PARAM_KEY_TITLE, "系统提示:");
// map.put(DIALOG_PARAM_KEY_MESSAGE,"正在发送验证邮件,请稍等");
// return map;
// }
};
monitor.executeOnMonitor(new Callable<Object>() {
@Override
public Object call() throws Exception {
String email = getService(IPrivateSMService.class)
.getBindedEmail();
return getService(IPrivateSimiNetService.class)
.generateCheckCode(getFramework().getDeviceId(), email);
}
});
}
protected void goServerCheck(final String number) {
GDCMProgressMonitor monitor = new GDCMProgressMonitor(this) {
@Override
protected void handleDone(Object returnVal) {
if (returnVal instanceof Boolean) {
if ((Boolean) returnVal) {
tv_contact_num.setText("");
Intent intent = new Intent(getApplicationContext(),
SiMiSuoHomePasswordActivity.class);
intent.putExtra("editPwd", 1);
startActivityForResult(intent, 1000);
} else {
// showCheckFail();
showVercodeErr();
}
} else {
// showCheckFail();
showVercodeErr();
}
}
@Override
protected void handleFailed(Throwable cause) {
// showCheckFail();
showVercodeErr();
}
};
monitor.executeOnMonitor(new Callable<Object>() {
@Override
public Object call() throws Exception {
// TODO Auto-generated method stub
String email = getService(IPrivateSMService.class)
.getBindedEmail();
return getService(IPrivateSimiNetService.class)
.verifyCheckCode(getFramework().getDeviceId(), email,
number);
}
});
}
protected void showCheckFail() {
runOnUiThread(new Runnable() {
@Override
public void run() {
showVercodeErr();
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1000) {
switch(resultCode){
case RESULT_OK:
setResult(RESULT_OK);
finish();
break;
// case Constant.PWD_EDIT_SUCCESS:
// setResult(RESULT_OK);
// finish();
// break;
}
}
super.onActivityResult(requestCode, resultCode, data);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.ll_simi_add_sure:
if (showErrTip) {
// 返回
finish();
// startActivity(new Intent(this, SiMiSuoThirdPassword.class));
} else {
String editContent = tv_contact_num.getText().toString();
if(!TextUtils.isEmpty(editContent)){
goServerCheck(editContent);
ll_sure.setVisibility(View.GONE);
ll_sure_check.setVisibility(View.VISIBLE);
}else{
Toast.makeText(this, "请输入校验码", 0).show();
}
}
break;
case R.id.ll_simi_add_concel:
if (showErrTip) {
// 客服
Tools.call(this, "01082652086");
} else {
finish();
}
break;
}
}
}
| true
|
f4afd195e6f9d1f41b1ea550d3af1232a6be9585
|
Java
|
jackcurtin/project_2_bookkeeper
|
/src/main/java/com/bookkeeper/demo/model/Book.java
|
UTF-8
| 2,583
| 2.3125
| 2
|
[] |
no_license
|
package com.bookkeeper.demo.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.sun.istack.NotNull;
import javax.persistence.*;
import java.util.List;
@Entity
@Table(name = "books")
public class Book {
public List<UserProfile> getUserFavorite() {
return userFavorite;
}
public void setUserFavorite(List<UserProfile> userFavorite) {
this.userFavorite = userFavorite;
}
@Id
@Column
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column
@NotNull
private String title;
@Column
private String synopsis;
@Column
private int pageCount;
@Column
private Long isbn;
@ManyToOne
private Genre genre;
@ManyToOne
private Author author;
@ManyToOne
private Publisher publisher;
@ManyToMany(mappedBy = "userFavoriteBooks")
@JsonIgnore
private List<UserProfile> userFavorite;
public Book() {
}
public Book(String title, String synopsis, int pageCount, Long isbn) {
this.title = title;
this.synopsis = synopsis;
this.pageCount = pageCount;
this.isbn = isbn;
}
public Long getId() {
return id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getSynopsis() {
return synopsis;
}
public void setSynopsis(String synopsis) {
this.synopsis = synopsis;
}
public int getPageCount() {
return pageCount;
}
public void setPageCount(int pageCount) {
this.pageCount = pageCount;
}
public Long getIsbn() {
return isbn;
}
public void setIsbn(Long isbn) {
this.isbn = isbn;
}
@Override
public String toString() {
return "Book{" +
"id=" + id +
", title='" + title + '\'' +
", synopsis='" + synopsis + '\'' +
", pageCount=" + pageCount +
", isbn=" + isbn +
'}';
}
public Genre getGenre() {
return genre;
}
public void setGenre(Genre genre) {
this.genre = genre;
}
public void setAuthor(Author author) {
this.author = author;
}
public void setPublisher(Publisher publisher) {
this.publisher = publisher;
}
public Author getAuthor() {
return author;
}
public Publisher getPublisher() {
return publisher;
}
}
| true
|
476f3164381c8964cf4d4bc59aea2152522ca69f
|
Java
|
kaibeat/CheNet
|
/app/src/main/java/com/example/mynet/RequestDevicesClass.java
|
UTF-8
| 3,887
| 2.171875
| 2
|
[
"MIT"
] |
permissive
|
package com.example.mynet;
import android.util.Log;
import com.alibaba.fastjson.JSON;
import com.example.mynet.javabean.DevicesInfoBean;
import com.example.mynet.javabean.DevicesRequestBean;
import com.example.mynet.javabean.LoginPostBean;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import static com.example.mynet.LoginPostClass.loginResponseBean;
public class RequestDevicesClass {
static String TAG = "testhttp";
public static DevicesInfoBean devicesInfoBean1;
static List<DevicesInfoBean> devicesInfoBeanArrayList = new ArrayList<>();
public static void RequestDevices() {
OkHttpClient client = new OkHttpClient().newBuilder()
.readTimeout(3, TimeUnit.SECONDS)
.build();
Request request = new Request.Builder()
.url("http://10.16.0.12:8081/portal/api/v2/session/list")
.method("GET", null)
.addHeader("accept", "*/*")
.addHeader("accept-encoding", "gzip, deflate")
.addHeader("accept-language", "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6")
.addHeader("authorization", loginResponseBean.getToken())
.addHeader("content-type", "application/json")
.addHeader("dnt", "1")
.addHeader("host", "10.16.0.12:8081")
.addHeader("proxy-connection", "keep-alive")
.addHeader("referer", "http://10.16.0.12:8081/deviceList")
.addHeader("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.67 Safari/537.36 Edg/87.0.664.47")
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.d(TAG, e.getMessage());
}
@Override
public void onResponse(Call call, okhttp3.Response response) throws IOException {
String responseData = response.body().string();
DevicesRequestBean devicesRequestBean = JSON.parseObject(responseData, DevicesRequestBean.class);
Log.d(TAG, "查询设备的json: " + devicesRequestBean.getSessions());
Log.d(TAG, "查询到的设备数量: " + devicesRequestBean.getSessions().size());
devicesInfoBeanArrayList.clear();
for (int i = 0; i < devicesRequestBean.getSessions().size(); i++) {
DevicesRequestBean.SessionsBean sessionsBean = devicesRequestBean.getSessions().get(i);
DevicesInfoBean devicesInfoBean = setSessionsBean(sessionsBean);
devicesInfoBeanArrayList.add(i, devicesInfoBean);
Log.d(TAG, "查询的设备保存为" + devicesInfoBean.toString());
Log.d(TAG, "onResponse: 保存的设备名字为"+devicesInfoBean.getDeviceType());
Log.d(TAG, "onResponse: 保存的设备id为"+devicesInfoBean.getAcct_unique_id());
}
}
});
}
private static DevicesInfoBean setSessionsBean(DevicesRequestBean.SessionsBean sessionsBean) {
DevicesInfoBean devicesInfoBean = new DevicesInfoBean();
devicesInfoBean.setDeviceType(sessionsBean.getDeviceType());
devicesInfoBean.setFramed_ip_address(sessionsBean.getFramed_ip_address());
devicesInfoBean.setCalling_station_id(sessionsBean.getCalling_station_id());
devicesInfoBean.setAcct_start_time(sessionsBean.getAcct_start_time());
devicesInfoBean.setAcct_unique_id(sessionsBean.getAcct_unique_id());
return devicesInfoBean;
}
}
| true
|
05a4d00b6a21455c9d72554e5b3e25c0b0a96de0
|
Java
|
joaoalfredopires/projeto-automacao-1-RESET
|
/src/test/java/pageObjects/LoginPage.java
|
UTF-8
| 1,219
| 2.625
| 3
|
[] |
no_license
|
package pageObjects;
import elementMapper.LoginPageElementMapper;
import io.qameta.allure.Step;
import org.openqa.selenium.support.PageFactory;
import utils.Browser;
import java.util.Random;
public class LoginPage extends LoginPageElementMapper {
//Gerador de email
String emailAleatorio = "email_de_teste_joao"+ new Random().nextInt() +"@gmail.com";
public LoginPage(){
PageFactory.initElements(Browser.getCurrentDriver(), this);
}
@Step("Preencher o campo email para conta existente")
public void fillEmail(){
email.sendKeys("email_de_teste@gmail.com");
}
@Step("Preencher o campo de senha para conta existente")
public void fillPasswd(){
passwd.sendKeys("teste123");
}
@Step("Click no botão de Sign In para conta existente")
public void clickButtonSubmitLogin(){
SubmitLogin.click();
}
@Step("Preencher campo de email para criação de nova conta")
public void fillEmailCreateAnAccount(){
email_create.sendKeys(emailAleatorio);
System.out.println("Email criado: "+ emailAleatorio);
}
@Step("Click no botão de Criar uma conta")
public void clickSubmitCreate(){
SubmitCreate.click();
}
}
| true
|
1ccd6f4f132c8b949df2555a889fba16b2164326
|
Java
|
Igincan/Cardventure
|
/Cardventure/Cardventure/src/karty/kuzlo/Hnis.java
|
UTF-8
| 775
| 2.234375
| 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 karty.kuzlo;
import karty.rozhrania.IDegradovatelna;
import karty.Karta;
import karty.Kuzlo;
import zaklad.Hrac;
/**
*
* @author Iginčan
*/
public class Hnis extends Kuzlo {
public Hnis(Hrac majtelKarty) {
super("Hnis", majtelKarty);
}
@Override
public void pouzi() {
for (int i = 1; i <= 3; i++) {
Karta karta = super.getMajtelKarty().getKartuZRuky(i);
if (karta instanceof IDegradovatelna) {
((IDegradovatelna) karta).degraduj();
}
}
}
}
| true
|
f7375af686ce0d0bc64b5ea05af7b799c74b0bf0
|
Java
|
gonzabazzi/OblMarzo2021
|
/OblMarzo2021/src/oblmarzo2021/NodoCiudad.java
|
UTF-8
| 697
| 2.765625
| 3
|
[] |
no_license
|
package oblmarzo2021;
public class NodoCiudad {
int dato;
String nombre;
NodoCiudad siguiente;
public NodoCiudad(int dato,String nombre) {
this.dato = dato;
this.siguiente = null;
this.nombre=nombre;
}
public int getDato() {
return dato;
}
public void setDato(int dato) {
this.dato = dato;
}
public NodoCiudad getSiguiente() {
return siguiente;
}
public void setSiguiente(NodoCiudad siguiente) {
this.siguiente = siguiente;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
}
| true
|
50612eefca5adde4738508221dfdaab6b564b094
|
Java
|
Rapheo/Garden_management_system-java-
|
/server/src/main/java/request/controllers/UserRoleController.java
|
UTF-8
| 583
| 2.265625
| 2
|
[] |
no_license
|
package request.controllers;
import bll.service.GenericService;
import bll.service.RoleService;
import model.UserRole;
import request.ClientHandler;
public class UserRoleController extends CrudController<UserRole> {
public UserRoleController(GenericService<UserRole> service, ClientHandler clientHandler) {
super(service, clientHandler);
}
public void findByName() {
String name = (String) clientHandler.receiveFromClient();
UserRole userRole = ((RoleService) service).findByName(name);
clientHandler.sendToClient(userRole);
}
}
| true
|
439f65c00bf37c9ddbb3d5b79606845642272bb6
|
Java
|
hello123hk/spark_tutorial
|
/src/main/java/com/spark/rdd_tutorial/tutorial4/MapToPairRdd.java
|
UTF-8
| 1,476
| 2.875
| 3
|
[] |
no_license
|
package com.spark.rdd_tutorial.tutorial4;
import com.spark.rdd.tutorial.util.Constant;
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.function.PairFunction;
import org.apache.spark.api.java.function.VoidFunction;
import scala.Tuple2;
/**
* Created by zhaikaishun on 2017/8/20.
*/
public class MapToPairRdd {
public static void main(String[] args) {
SparkConf sparkConf = new SparkConf().setAppName("MapToPairRdd").setMaster("local");
JavaSparkContext sc = new JavaSparkContext(sparkConf);
sc.setLogLevel("WARN");
JavaRDD<String> lines = sc.textFile(Constant.filePath);
//输入的是一个string的字符串,输出的是一个(String, Integer) 的map
JavaPairRDD<String, Integer> pairRDD = lines.<String, Integer>mapToPair(new PairFunction<String, String, Integer>() {
@Override
public Tuple2<String, Integer> call(String s) throws Exception {
return new Tuple2<String, Integer>(s.split("\\s+")[0], 1);
}
});
//输出
pairRDD.foreach(new VoidFunction<Tuple2<String, Integer>>() {
@Override
public void call(Tuple2<String, Integer> tp) throws Exception {
System.out.println("key: "+tp._1+" value: "+tp._2);
}
});
}
}
| true
|
f906276d2a38a065ae4ad34daa63b3dd64ba700a
|
Java
|
intaek78/coupon33
|
/cancellation/src/main/java/coupon/MemberCancelled.java
|
UTF-8
| 1,109
| 2.28125
| 2
|
[] |
no_license
|
package coupon;
public class MemberCancelled extends AbstractEvent {
private Long id;
private String status;
private String memId;
private Long memNo;
private String memNm;
private String withdrawDate;
public MemberCancelled(){
super();
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getMemId() {
return memId;
}
public void setMemId(String memId) {
this.memId = memId;
}
public Long getMemNo() { return memNo; }
public void setMemNo(Long memNo) {
this.memNo = memNo;
}
public String getMemNm() {
return memNm;
}
public void setMemNm(String memNm) {
this.memNm = memNm;
}
public String getWithdrawDate() {
return withdrawDate;
}
public void setWithdrawDate(String withdrawDate) {
this.withdrawDate = withdrawDate;
}
}
| true
|
b4a647aedafaf77b4da80ef3f98b10a28e9eb645
|
Java
|
mestreengaisaber/SPRING
|
/spring-boot-oracle-rest/src/main/java/es/satec/angolatelecom/sigo/sim/stock/service/config/DbConfiguration.java
|
UTF-8
| 1,227
| 1.898438
| 2
|
[
"MIT"
] |
permissive
|
package es.satec.angolatelecom.sigo.sim.stock.service.config;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration
@ComponentScan("es.satec.angolatelecom.sim.provision.service")
@EnableAutoConfiguration
@EntityScan(basePackages = {"es.satec.angolatelecom.sigo.sim.stock.service.dto"})
@EnableJpaRepositories(basePackages = {"es.satec.angolatelecom.sigo.sim.stock.service.repository"})
@EnableTransactionManagement
public class DbConfiguration {
/**
@Bean
public DataSource dataSource(){
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("oracle.jdbc.driver.OracleDriver");
dataSource.setUrl("jdbc:oracle:thin:@213.134.50.3:1521/ATDEVMAD");
dataSource.setUsername( "SIGOINT" );
dataSource.setPassword( "SATEC2016" );
return dataSource;
}
*/
}
| true
|
08810c426b83277db9ffaf7c97d7bd400465d62e
|
Java
|
daveshanley/jgooglesafebrowsing
|
/v2/src/main/java/com/buildabrand/gsb/util/GSBRemote.java
|
UTF-8
| 4,998
| 2.546875
| 3
|
[] |
no_license
|
package com.buildabrand.gsb.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import com.buildabrand.gsb.exception.GSBBadRequestException;
import com.buildabrand.gsb.exception.GSBException;
import com.buildabrand.gsb.exception.GSBNotAuthorizedException;
import com.buildabrand.gsb.exception.GSBTooManyRequestsException;
import com.buildabrand.gsb.exception.GSBVersionNotSupportedException;
/**
* GSBException
* Generic GSB Exception that may be thrown by any number of classes
*
* <h4>Copyright and License</h4>
* This code is copyright (c) Buildabrand Ltd, 2011 except where
* otherwise stated. It is released as
* open-source under the Creative Commons NC-SA license. See
* <a href="http://creativecommons.org/licenses/by-nc-sa/2.5/">http://creativecommons.org/licenses/by-nc-sa/2.5/</a>
* for license details. This code comes with no warranty or support.
*
* @author Dave Shanley <dave@buildabrand.com>
*/
public class GSBRemote {
/**
* Returns String of remote HTTP request.
* @param url
* @return
* @throws com.buildabrand.gsb.exception
* @deprecated use {@link #returnRequest(URL, String)} instead
*/
public static String returnRequest(URL url) throws GSBException {
try {
/* set up the connection */
URLConnection connection = (URLConnection)url.openConnection();
InputStreamReader isr = new InputStreamReader(connection.getInputStream(),"UTF8");
BufferedReader reader = new BufferedReader(isr);
/* read in the server response */
String s;
StringWriter data = new StringWriter();
while((s = reader.readLine())!=null) {
data.append(s + "\n");
}
/* return as string */
return data.toString();
} catch (MalformedURLException exp) {
throw new GSBException("malformed URL: " + url.toString());
} catch (IOException exp) {
throw new GSBException("unable to read from url stream: " + url.toString() + ", server said: " + exp.getMessage());
}
}
/**
* * Returns String of remote HTTP request.
* @param url
* @param body
* @return body of remote request.
* @throws GSBException
*/
public static String returnRequest(URL url, String body) throws GSBException {
PostMethod method = new PostMethod(url.toExternalForm());
try {
RequestEntity entity = new StringRequestEntity(body,null,null);
HttpClient httpclient = new HttpClient();
method.setRequestEntity(entity);
int result = httpclient.executeMethod(method);
/* bad request returned */
if(result==400) throw new GSBBadRequestException("bad request error returned by server: The HTTP request was not correctly formed. The client did not provide all required CGI parameters.");
if(result==401) throw new GSBNotAuthorizedException("client id invalid error returned by server: The client id is invalid.");
if(result==503) throw new GSBTooManyRequestsException("service unavilable error returned by server: The server cannot handle the request. Clients MUST follow the backoff behavior specified in the Request Frequency section.");
if(result==505) throw new GSBVersionNotSupportedException("service unavilable error returned by server: The server CANNOT handle the requested protocol major version.");
if(result==200) return method.getResponseBodyAsString();
throw new GSBException("Unknown server exception, no content returned!");
} catch (UnsupportedEncodingException exp) {
throw new GSBException("unsupported encoding excption on url/data: " + url.toString() + ", message: " + exp.getMessage());
} catch (IOException exp) {
throw new GSBException("IO Exception: " + url.toString() + ", message: " + exp.getMessage());
}
}
/**
* Returns BufferedReader from remote HTTP request
* @param url
* @return
* @throws com.buildabrand.gsb.exception
*/
public static BufferedReader returnRawRequest(URL url) throws GSBException {
try {
/* set up the connection */
URLConnection connection = (URLConnection)url.openConnection();
InputStreamReader isr = new InputStreamReader(connection.getInputStream(),"UTF8");
BufferedReader reader = new BufferedReader(isr);
return reader;
} catch (MalformedURLException exp) {
throw new GSBException("malformed URL: " + url.toString());
} catch (IOException exp) {
throw new GSBException("unable to read from url stream: " + url.toString() + ", server said: " + exp.getMessage());
}
}
}
| true
|
26ec1e2374b9faf41c88f8cefb73982ef5bb41d1
|
Java
|
yyxx828/baseboot2
|
/src/main/java/com/xajiusuo/jpa/util/AbstractMapp.java
|
UTF-8
| 20,581
| 2.3125
| 2
|
[] |
no_license
|
package com.xajiusuo.jpa.util;
import com.xajiusuo.jpa.util.exception.MappException;
import java.io.PrintStream;
import java.io.Serializable;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
abstract class AbstractMapp {
private static final DateFormat DF_yyyy_MM_dd_HH_mm_ss = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
private static final DateFormat DF_yyyy_MM_dd = new SimpleDateFormat("yyyy-MM-dd");
private static final DateFormat DF_yyyy_MM = new SimpleDateFormat("yyyy-MM-dd");
private static final DateFormat DF_yyyy = new SimpleDateFormat("yyyy");
private static final DateFormat DF_yyyy_MM_DD_HH_mm = new SimpleDateFormat("yyyy-MM-dd HH:mm");
private static final DateFormat DF_MM_dd_yyyy = new SimpleDateFormat("MM/dd/yyyy");
private boolean isControl = true;
/**
* @since 要加载的实体
* */
protected Object entity = null;
/**
* @since 实体类
* */
protected Class<? extends Object> entityclass = null;
/**
* @since 父类Mapp
* */
protected IMapp superMapp = null;
/**
* @since 实体父级类
* */
protected Class<? extends Object> superclass = null;
/**
* @since 定义变量属性集合
* */
protected Map<String, Field> map_df = new HashMap<String, Field>();
/**
* @since 定义变量属性集合(不区分大小写)
* */
protected Map<String, Field> map_df0 = new HashMap<String, Field>();
/**
* @since 定义常量属性集合
* */
protected Map<String, Field> map_ds = new HashMap<String, Field>();
/**
* @since 定义方法集合
* */
protected Map<String, Method> map_dm = new HashMap<String, Method>();
/***
* 嵌套对象
*/
protected Map<String,IMapp> objs = new HashMap<String,IMapp>();
/**
* @since 输出平台
* */
protected PrintStream out;
/**
* @since 默认平台
* */
private static PrintStream oldout = System.out;
protected AbstractMapp() {
}
protected AbstractMapp(Object entity) {
load(entity);
}
protected void isunload() {
if(entity == null)
throw new MappException("实体为空");
}
protected void isload() {
if(this.entity != null) {
throw new MappException("实体未被解除");
}
}
protected IMapp getParentIMapp() {
if(superMapp == null) {
if(entityclass.getSuperclass() == null)
return null;
superMapp = Mapp.createMapp();
((Mapp)superMapp).entity = this.entity;
superclass = entityclass.getSuperclass();
((Mapp)superMapp).loadclass(superclass);
}
return superMapp;
}
protected final void loadclass(Class<?> entityclass) {
this.entityclass = entityclass;
Field[] fds = this.entityclass.getDeclaredFields();
Method[] mds = this.entityclass.getDeclaredMethods();
for(Field fd : fds) {
fd.setAccessible(isControl);
if(fd.toGenericString().indexOf("final") < 0){
map_df.put(fd.getName(), fd);
map_df0.put(fd.getName().toLowerCase(), fd);
}else{
map_ds.put(fd.getName(), fd);
}
}
for(Method md : mds) {
md.setAccessible(isControl);
map_dm.put(md.getName(), md);
}
((Mapp)this).superMapp = ((Mapp)this).getParentIMapp();
}
public IMapp load(Object entity) {
try {
if(entity == null) {
throw new NullPointerException();
}
if(this.entity != null && this.entity.getClass().equals(entity.getClass())){
this.entity = entity;
return (Mapp)this;
}
isload();
unLoad();
this.entity = entity;
loadclass(entity.getClass());
}catch(Exception e) {
throw new RuntimeException(e);
}
return (Mapp)this;
}
public void reload(Object entity) {
unLoad();
load(entity);
}
public void unLoad() {
if(entity == null)
return;
synchronized(entity) {
if(superMapp != null)
superMapp.unLoad();
map_df.clear();
map_df0.clear();
map_ds.clear();
map_dm.clear();
objs.values().forEach(m -> m.unLoad());
objs.clear();
}
}
public String getFieldType(String fieldName) {
Field f = null;
isunload();
f = getField(fieldName);
if(f != null)
return f.toGenericString();
return null;
}
public String getTypeMethodString(String fieldName) {
Method f = null;
try {
isunload();
f = getMethod(fieldName);
}catch(Exception e) {
e.printStackTrace();
}
if(f != null)
return f.toGenericString();
return null;
}
/**
* @since 获得fieldName对应属性
* */
public Field getField(String fieldName) {
Field fl = null;
isunload();
if(fl == null)
fl = map_df.get(fieldName);
if(fl == null)
fl = map_df0.get(fieldName.toLowerCase());
if(fl == null)
fl = map_ds.get(fieldName);
if(fl == null) {
if(superMapp != null)
fl = superMapp.getField(fieldName);
}
if(fl == null)
throw new MappException(fieldName);
return fl;
}
/**
* @since 获得methodName对应方法
* */
public Method getMethod(String methodName) {
Method method = null;
try {
isunload();
method = map_dm.get(methodName);
if(method == null)
method = superMapp.getMethod(methodName);
if(method == null)
throw new MappException(methodName);
}catch(Exception e) {
}
return method;
}
public Object invoke(String methodName, Object... args) {
Method m = getMethod(methodName);
if(m == null) {
return superMapp.invoke(methodName, args);
}else {
try {
return m.invoke(entity, args);
}catch(Exception e) {
throw new MappException(e);
}
}
}
public void invokeSetMethod(String methodName, Object value) {
Method m = getMethod(methodName);
if(m == null) {
superMapp.invokeSetMethod(methodName, value);
}else {
try {
m.invoke(entity, getField0(m.getReturnType().getSimpleName(), value));
}catch(Exception e) {
throw new MappException(e);
}
}
}
/**
* @since 获得所有方法
* */
public Collection<Method> getMethods() {
isunload();
return map_dm.values();
}
public Object getObjectbyField(String fieldName) {
if(fieldName.contains(".")){
String pro = fieldName.substring(0,fieldName.indexOf("."));
IMapp m = objs.get(pro);
if(m == null){
m = Mapp.createMapp(getObjectbyField(pro));
objs.put(pro,m);
}
return m.getObjectbyField(fieldName.substring(fieldName.indexOf(".") + 1));
}
Object obj = null;
try {
isunload();
try {
obj = map_dm.get("get" + fieldName.substring(0,1).toUpperCase() + fieldName.substring(1)).invoke(entity);
} catch (Exception e) {}
if(obj == null){
obj = getField(fieldName).get(entity);
}
}catch(Exception e1) {
throw new MappException(fieldName, e1);
}
return obj;
}
protected boolean noProperties(String key) {
if(map_ds.containsKey(key)) {
throw new MappException("不包含的属性");
}else {
if(superMapp != null) {
if(((Mapp)superMapp).noProperties(key))
return false;
}
}
return true;
}
/**
* @since 是否变量
* */
protected boolean isvaried(String key) {
if(map_df.containsKey(key))
return true;
else {
if(superMapp != null) {
if(((Mapp)superMapp).isvaried(key)) {
return true;
}
}
}
throw new MappException(key);
}
/**
* @since 是否常量
* */
protected boolean isConstant(String key) {
if(map_ds.containsKey(key))
return true;
if(superMapp != null) {
if(((Mapp)superMapp).isConstant(key))
return true;
}
throw new MappException(key);
}
public boolean containsField(String fieldName) {
try {
return isvaried(fieldName);
}catch(MappException e) {
return false;
}
}
public boolean containsConstant(String fieldName) {
try {
return isConstant(fieldName);
}catch(Exception e) {
return false;
}
}
public boolean containsMethod(String methodName) {
if(map_dm.containsKey(methodName))
return true;
else if(superMapp != null) {
return superMapp.containsMethod(methodName);
}else {
return false;
}
}
public void setObject(String fieldName, Object value) {
try {
isvaried(fieldName);
noProperties(fieldName);
if(map_df.containsKey(fieldName)) {
map_df.get(fieldName).set(entity, getField0(getSimpleName(fieldName), value));
}else {
if(superMapp != null) {
superMapp.setObject(fieldName, value);
}
}
}catch(Exception e) {
}
}
public void setObjectIgnore(String fieldname, Object value) {
try {
String fieldName = fieldname.toLowerCase();
if(map_df0.containsKey(fieldName)) {
map_df0.get(fieldName).set(entity, getField0(getSimpleName(fieldName), value));
}else {
if(superMapp != null) {
superMapp.setObject(fieldName, value);
}
}
}catch(Exception e) {
}
}
public void setValue(Map<String,Object> map){
if(map != null){
for(String s : map.keySet()){
setObject(s, map.get(s));
}
}
}
public void setValueIgnore(Map<String,Object> map){
if(map != null){
for(String s : map.keySet()){
setObjectIgnore(s, map.get(s));
}
}
}
public void setObjectbyString(String fieldName, String value) {
try {
if(map_df.containsKey(fieldName)) {
map_df.get(fieldName).set(entity, getField0(getSimpleName(fieldName), value));
}
}catch(Exception e) {
}
}
public boolean isDate(String fieldName) {
return "Date".equals(getSimpleName(fieldName));
}
public String getSimpleName(String fieldName) {
try {
return getField(fieldName).getType().getSimpleName();
}catch(Exception e) {
return null;
}
}
public Set<String> getFields() {
Set<String> list = new HashSet<String>();
list.addAll(map_df.keySet());
if(superMapp != null)
list.addAll(superMapp.getFields());
return list;
}
public Class<?> getFieldInterface(String field, int... num) {
if(getField(field) == null)
return null;
Class<?> res = getField(field).getType();
if(num == null || num.length < 1)
return res;
for(int i = 0; i < num.length; i++) {
try {
res = (Class<?>)res.getInterfaces()[num[i]];
}catch(Exception e) {
return null;
}
}
return res;
}
public Class<?> getFieldSuper(String field, int grade, int... num) {
if(getField(field) == null)
return null;
Class<?> res = getField(field).getType();
if(grade == 0)
return res;
for(int i = 0; i < grade; i++) {
try {
res = res.getSuperclass();
}catch(Exception e) {
return null;
}
}
if(num != null) {
for(int i = 0; i < num.length; i++) {
try {
res = (Class<?>)res.getInterfaces()[num[i]];
}catch(Exception e) {
return null;
}
}
}
return res;
}
public List<String> getFieldByClass(Class<? extends Serializable> className) {
List<String> res = new ArrayList<String>(0);
Iterator<String> df = map_df.keySet().iterator();
while(df.hasNext()) {
String f = df.next();
try {
if(isin(getField(f).getType(), className)) {
res.add(f);
}
}catch(Exception e) {
}
}
return res;
}
private boolean isin(Object obj, Class<?> className) {
if(obj == null || className == null)
return false;
if(obj.getClass().equals(className))
return true;
Class<?> t = obj.getClass();
while(t != null) {
if(t.getClass().equals(className))
return true;
t = t.getSuperclass();
}
Type[] ts = obj.getClass().getGenericInterfaces();
if(isinterface(ts, className))
return true;
return false;
}
private boolean isinterface(Type[] ts, Class<?> className) {
if(ts == null || ts.length < 1)
return false;
for(Type t : ts) {
System.out.println((Class<?>)t);
if(((Class<?>)t).equals(className))
return true;
else if(isinterface(((Class<?>)t).getGenericInterfaces(), className))
return true;
}
return false;
}
public Map<String, Object> getProperties() {
Map<String, Object> list = new HashMap<String, Object>(map_ds);
if(superMapp != null)
list.putAll(superMapp.getProperties());
return list;
}
public void setout(PrintStream out) {
this.out = out;
if(superMapp != null)
((Mapp)superMapp).out = out;
}
public void showAllBody(boolean... allinfor) {
boolean all = false;
if(allinfor != null && allinfor.length > 0)
all = allinfor[0];
if(entity == null) {
throw new MappException("没有实体");
}
if(out != null)
System.setOut(out);
System.out.println("\n===============================");
System.out.println("对象" + entityclass.getSimpleName() + "常量、变量、方法");
System.out.println("===============================\n");
showConstDeclare(all);// 显示自定义常量属性
showFieldDeclare(all);// 显示自定义变量属性
showMethodDeclare(all);// 显示自定义方法
if(superMapp != null) {
superMapp.showAllBody(all);
}
}
public void showByParm(int... value) {
try {
if(entity == null) {
throw new MappException("实体为空");
}
if(out != null)
System.setOut(out);
if(value == null)
return;
for(int key : value) {
System.out.println("==========================");
switch(key) {
case IMapp.show_field_declare:
System.out.println("该类变量属性:" + entityclass.getSimpleName());
System.out.println("==========================\n");
showFieldDeclare(false);
break;
case IMapp.show_field_parend:
System.out.println("父级变量属性");
System.out.println("==========================\n");
showFieldParent();
break;
case IMapp.show_method_declare:
System.out.println("该类方法:" + entityclass.getSimpleName());
System.out.println("==========================\n");
showMethodDeclare(false);
break;
case IMapp.show_method_parend:
System.out.println("父类方法");
System.out.println("==========================\n");
showMethodParent();
break;
case IMapp.show_const_declare:
System.out.println("该类常量属性:" + entityclass.getSimpleName());
System.out.println("==========================\n");
showConstDeclare(false);
break;
case IMapp.show_const_parend:
System.out.println("父类常量属性");
System.out.println("==========================\n");
showConstParent();
break;
default:
break;
}
}
System.out.println("==========================");
}finally {
System.setOut(oldout);
}
}
/**
* @param all
* @since 定义常量属性
* */
protected void showConstDeclare(boolean all) {
if(all) {
for(String key : map_ds.keySet()) {
System.out.printf("属性:常量\t%s\n值:\t%s\n\n", getFieldType(key), getObjectbyField(key));
}
}else {
for(String key : map_ds.keySet()) {
System.out.printf("属性:常量\t%s\t%s\n\n", getField(key).getType().getSimpleName() + "\t" + key,
getObjectbyField(key));
}
}
}
/**
* @since 父类常量属性
* */
private void showConstParent() {
if(superMapp != null)
((Mapp)superMapp).showConstDeclare(false);
}
/**
* @since 定义变量属性
* */
protected void showFieldDeclare(boolean all) {
if(all) {
for(String key : map_df.keySet()) {
System.out.printf("属性:变量\t%s\t%s\n\n", getFieldType(key), getObjectbyField(key));
}
}else {
for(String key : map_df.keySet()) {
System.out.printf("属性:变量\t%s\t%s\n\n", getField(key).getType().getSimpleName() + "\t" + key,
getObjectbyField(key));
}
}
}
/**
* @since 父类变量属性
* */
private void showFieldParent() {
if(superMapp != null)
((Mapp)superMapp).showFieldDeclare(false);
}
/**
* @since 定义方法
* */
protected void showMethodDeclare(boolean all) {
Set<String> set = map_dm.keySet();
if(all) {
for(String key : set) {
System.out.printf("定义方法:\t%s\n默认返回值:\t%s\n\n", getTypeMethodString(key), getMethod(key)
.getDefaultValue());
}
}else {
for(String key : set) {
System.out
.printf("方法:\t%s\t%s\n\n", getMethod(key).toGenericString(), getMethod(key).getDefaultValue());
}
}
}
/**
* @since 父类方法
* */
private void showMethodParent() {
if(superMapp != null)
((Mapp)superMapp).showMethodDeclare(false);
}
public Long getVersion() {
Field field = null;
try {
field = getField("serialVersionUID");
return Long.parseLong(field.get(entity).toString());
}catch(Exception e) {
}
return 0L;
}
/**
* @since 将字符串或对象赋值给变量
* */
@SuppressWarnings("deprecation")
public Object getField0(String type, Object value) {
try {
if("String".equals(type)) {
return value.toString();
}else if("int".equals(type) || "Integer".equals(type)) {
if(!(value instanceof Integer))
return Integer.valueOf(value.toString());
}else if("Date".equals(type)) {
if(!(value instanceof Date)) {
try{
return new Date(value.toString());
}catch(Exception ee) {
try {
return DF_yyyy_MM_dd_HH_mm_ss.parse(value.toString());
}catch(Exception e) {
try {
return DF_yyyy_MM_DD_HH_mm.parse(value.toString());
}catch(Exception e1) {
try {
return DF_MM_dd_yyyy.parse(value.toString());
}catch(Exception e2) {
try {
return DF_yyyy_MM_dd.parseObject(value.toString());
}catch(Exception e3) {
try {
return DF_yyyy_MM.parseObject(value.toString());
}catch(Exception e4) {
try {
return DF_yyyy.parseObject(value.toString());
}catch(Exception e5) {
return null;
}
}
}
}
}
}
}
}else{
return value;
}
}else if("double".equals(type) || "Double".equals(type)) {
if(!(value instanceof Double))
return Double.valueOf(value.toString());
}else if("char".equals(type) || "Character".equals(type)) {
if(!(value instanceof Character))
return Character.valueOf(value.toString().charAt(0));
}else if("boolean".equals(type) || "Boolean".equals(type)) {
if(!(value instanceof Boolean)) {
if("1".equals(value) || "0".equals(value) || "true".equals(value) || "false".equals(value)) {
return "true".equals(value) || "1".equals(value);
}else {
return null;
}
}
}else if("short".equals(type) || "Short".equals(type)) {
if(!(value instanceof Short))
return Short.valueOf(value.toString());
}else if("long".equals(type) || "Long".equals(type)) {
if(!(value instanceof Long))
return Long.valueOf(value.toString());
}else if("byte".equals(type) || "Byte".equals(type)) {
if(!(value instanceof Byte))
return Byte.valueOf(value.toString());
}else if("BigDecimal".equals(type)) {
if(!(value instanceof BigDecimal))
return BigDecimal.valueOf(Double.valueOf(value.toString()));
}else if("BigInteger".equals(type)) {
if(!(value instanceof BigInteger))
return BigInteger.valueOf(Long.valueOf(value.toString()));
}else if("Timestamp".equals(type)) {
if(!(value instanceof Timestamp))
return new Timestamp(((Date)getField0("Date", value)).getTime());
}
}catch(Exception e) {
return null;
}
return value;
}
public void setControl(boolean isControl) {
this.isControl = isControl;
}
public Class<?> getEntityClass() {
return entityclass;
}
public <A extends Annotation> A getAnnotation(Class<A> annotationClass) {
if(annotationClass == null)
throw new NullPointerException();
return (A)entityclass.getAnnotation(annotationClass);
}
public <A extends Annotation> A getMethodAnnotation(Class<A> annotationClass, String name) {
return getMethod(name).getAnnotation(annotationClass);
}
public <A extends Annotation> A getMethodAnnotationAddGet(Class<A> annotationClass, String name) {
if(name.toUpperCase().charAt(0) != name.charAt(0)) {
return getMethod("get" + name.toUpperCase().charAt(0) + name.substring(1)).getAnnotation(annotationClass);
}else {
return null;
}
}
public Method getProperByAnnotation(Class<? extends Annotation> annotationClass) {
for(Method m : getMethods()) {
if(m.getAnnotation(annotationClass) != null) {
return m;
}
}
return null;
}
public List<Method> getPropersByAnnotation(Class<? extends Annotation> annotationClass) {
List<Method> list = new ArrayList<Method>(0);
for(Method m : getMethods()) {
if(m.getAnnotation(annotationClass) != null) {
list.add(m);
}
}
return list;
}
@SuppressWarnings("unchecked")
public <T> T getEntityByClass(T t) {
return (T)entity;
}
}
| true
|
3fd1eb348a1be63cdeb7427dcdc59ecc705ab697
|
Java
|
Z-P-J/ZHttp
|
/zhttp-core/src/main/java/com/zpj/http/core/HttpConfig.java
|
UTF-8
| 5,988
| 2.265625
| 2
|
[] |
no_license
|
package com.zpj.http.core;
import android.text.TextUtils;
import com.zpj.http.ZHttp;
import com.zpj.http.utils.UrlUtil;
import com.zpj.http.utils.Validate;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Locale;
import java.util.Map;
public class HttpConfig extends BaseConfig<HttpConfig> {
private final Collection<IHttp.KeyVal> data = new ArrayList<>();
protected URL originalUrl;
protected URL url;
protected IHttp.Method method = IHttp.Method.GET;
protected String body = null;
private IHttp.HttpEngine httpEngine;
public HttpConfig httpFactory(IHttp.HttpEngine httpEngine) {
this.httpEngine = httpEngine;
return this;
}
public IHttp.HttpEngine httpFactory() {
Validate.notNull(httpEngine, "HttpFactory must not be null");
return httpEngine;
}
public URL url() {
return url;
}
public URL getOriginalUrl() {
return originalUrl;
}
public HttpConfig url(String url) {
try {
url = url.trim();
String tempUrl = url.toLowerCase();
boolean isHttp = tempUrl.startsWith("http://") || tempUrl.startsWith("https://");
if (!isHttp) {
if (tempUrl.contains("://")) {
throw new MalformedURLException("Only http and https protocols supported!");
}
if (baseUrl == null) {
throw new MalformedURLException("You must set baseUrl firstly!");
}
if (!tempUrl.startsWith("/")) {
url = "/" + url;
}
url = baseUrl.resolve(url).toString();
}
this.url = new URL(UrlUtil.encodeUrl(url));
if (this.originalUrl == null) {
this.originalUrl = this.url;
}
} catch (Exception e) {
throw new IllegalArgumentException("Malformed URL: " + url, e);
}
return this;
}
public HttpConfig url(URL url) {
// this.url = url;
// if (this.originalUrl == null) {
// this.originalUrl = this.url;
// }
// return this;
return url(url.toString());
}
public IHttp.Method method() {
return method;
}
public HttpConfig method(IHttp.Method method) {
this.method = method;
return this;
}
public HttpConfig range(String range) {
this.headers.put(HttpHeader.RANGE, range);
return this;
}
public HttpConfig range(long start) {
this.headers.put(HttpHeader.RANGE, String.format(Locale.ENGLISH, "bytes=%d-", start));
return this;
}
public HttpConfig range(long start, long end) {
this.headers.put(HttpHeader.RANGE, String.format(Locale.ENGLISH, "bytes=%d-%d", start, end));
return this;
}
public HttpConfig requestBody(String body) {
this.body = body;
return this;
}
public String requestBody() {
return body;
}
public HttpConfig data(IHttp.KeyVal keyval) {
if (keyval != null) {
data.add(keyval);
}
return this;
}
public Collection<IHttp.KeyVal> data() {
return data;
}
public HttpConfig data(String key, String value) {
return data(HttpKeyVal.create(key, value));
}
public HttpConfig data(String key, String filename, InputStream inputStream) {
return data(HttpKeyVal.create(key, filename, inputStream));
}
public HttpConfig data(String key, String filename, InputStream inputStream, IHttp.OnStreamWriteListener listener) {
return data(HttpKeyVal.create(key, filename, inputStream, listener));
}
public HttpConfig data(String key, String filename, InputStream inputStream, String contentType) {
return data(HttpKeyVal.create(key, filename, inputStream).contentType(contentType));
}
public HttpConfig data(Map<String, String> data) {
if (data != null) {
for (Map.Entry<String, String> entry : data.entrySet()) {
data(HttpKeyVal.create(entry.getKey(), entry.getValue()));
}
}
return this;
}
public HttpConfig data(Collection<IHttp.KeyVal> data) {
if (data != null) {
for (IHttp.KeyVal entry : data) {
data(entry);
}
}
return this;
}
public IHttp.KeyVal data(String key) {
if (!TextUtils.isEmpty(key)) {
for (IHttp.KeyVal keyVal : data()) {
if (keyVal.key().equals(key))
return keyVal;
}
}
return null;
}
public boolean needsMultipart() {
// multipart mode, for files. add the header if we see something with an inputstream, and return a non-null boundary
for (IHttp.KeyVal keyVal : data()) {
if (keyVal.hasInputStream())
return true;
}
return false;
}
public IHttp.Request request() {
return httpFactory().createRequest(this);
}
public IHttp.Connection connection() {
return httpFactory().createConnection(request());
}
public IHttp.Response execute() throws IOException {
return connection().execute();
}
public void enqueue(IHttp.Callback callback) {
connection().enqueue(callback);
}
public String toStr() throws IOException {
return execute().bodyString();
}
public <T> T parse(IHttp.Parser parser) throws IOException {
return execute().parse(parser);
}
public <T> T parse(Type type) throws IOException {
return execute().parse(type);
}
public <T> T parse(Class<T> clazz) throws IOException {
return execute().parse(clazz);
}
}
| true
|
a375bfae78f3ae16282f933590cf95d7d71f1c63
|
Java
|
marsopensource/CAP
|
/cap-codegen/src/main/java/com/comtop/cap/codegen/model/WrapperException.java
|
UTF-8
| 4,627
| 2.3125
| 2
|
[] |
no_license
|
/******************************************************************************
* Copyright (C) 2014 ShenZhen ComTop Information Technology Co.,Ltd
* All Rights Reserved.
* 本软件为深圳康拓普开发研制。未经本公司正式书面同意,其他任何个人、团体不得使用、
* 复制、修改或发布本软件.
*****************************************************************************/
package com.comtop.cap.codegen.model;
import java.util.Observable;
import java.util.Observer;
import com.comtop.cap.bm.metadata.entity.model.ExceptionVO;
import com.comtop.cap.bm.metadata.entity.model.MethodType;
import com.comtop.cap.codegen.model.WrapperEntity.ImportNotifyArgs;
import com.comtop.cap.ptc.login.utils.CapLoginUtil;
import com.comtop.cip.jodd.util.StringUtil;
/**
*
* 异常元数据包装类
*
* @author 龚斌
* @since 1.0
* @version 2015年10月21日 龚斌
*/
public final class WrapperException extends Observable {
/** 异常 */
private final ExceptionVO ex;
/**
* 构造函数
*
* @param ex 异常
* @param observer 导入类观察者
* @param methodType 异常所在方法类型
*/
WrapperException(final ExceptionVO ex, final Observer observer, final String methodType) {
super();
this.ex = ex;
this.addObserver(observer);
String strExceptionFullName = ex.getModelPackage() + ".exception." + getExceptionType();
this.setChanged();
notifyObservers(this);
this.setChanged();
notifyObservers(new ImportNotifyArgs(ImportNotifyArgs.ABS_FACADE_IMPORT, strExceptionFullName, this));
if (MethodType.BLANK.getValue().equals(methodType)) { // 空方法
this.setChanged();
notifyObservers(new ImportNotifyArgs(ImportNotifyArgs.IMP_FACADE_IMPORT, strExceptionFullName, this));
}
if (MethodType.USER_DEFINED_SQL.getValue().equals(methodType) || MethodType.QUERY_MODELING.getValue().equals(methodType)) { // 自定义sql方法 ,查询建模
this.setChanged();
notifyObservers(new ImportNotifyArgs(ImportNotifyArgs.ABS_SERVICE_IMPORT, strExceptionFullName, this));
}
}
/**
* 获取异常类型
*
* @return 异常类型
*/
public String getExceptionType() {
return StringUtil.capitalize(ex.getEngName());
}
/**
* 获取异常所在包路径
*
*
* @return 包路径
*/
public String getPackagePath() {
return ex.getModelPackage();
}
/**
* 获取异常注释
*
*
* @return 异常注释
*/
public String getComment() {
return ex.getChName();
}
/**
* @return 获取异常作者名
*/
public String getAuthor(){
//return ex.getCreaterName();
return CapLoginUtil.getCapCurrentUserSession().getBmEmployeeName();
//return SystemHelper.getCurUserInfo().getEmployeeName();
}
/**
*
* @see java.lang.Object#hashCode()
* @return a hash code value for this object.
*/
@Override
public int hashCode() {
final int iPrime = 31;
int iResult = 1;
iResult = iPrime * iResult + ((this.getExceptionType() == null) ? 0 : this.getExceptionType().hashCode());
iResult = iPrime * iResult + ((this.getPackagePath() == null) ? 0 : this.getPackagePath().hashCode());
return iResult;
}
/**
*
* @see java.lang.Object#equals(java.lang.Object)
* @param obj the reference object with which to compare.
* @return <code>true</code> if this object is the same as the obj
* argument; <code>false</code> otherwise.
*/
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
WrapperException objOther = (WrapperException) obj;
if (this.getExceptionType() == null) {
if (objOther.getExceptionType() != null) {
return false;
}
} else if (!this.getExceptionType().equals(objOther.getExceptionType())) {
return false;
}
if (this.getPackagePath() == null) {
if (objOther.getPackagePath() != null) {
return false;
}
} else if (!this.getPackagePath().equals(objOther.getPackagePath())) {
return false;
}
return true;
}
}
| true
|
6f2eeb10fe00fd8bf438a3aa5f912e8f25aa4c21
|
Java
|
tram0808/BaiTapQuaTrinhAndroid
|
/Selfie/app/src/main/java/com/example/selfie/GalleryActivity.java
|
UTF-8
| 2,566
| 2.28125
| 2
|
[] |
no_license
|
package com.example.selfie;
import android.database.Cursor;
import android.os.Bundle;
import android.util.SparseBooleanArray;
import android.view.ContextMenu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.util.ArrayList;
public class GalleryActivity extends AppCompatActivity {
ListView list;
ArrayList<HinhAnh> arrayHinhAnh;
HinhAnhAdapter adapter;
CheckBox chB;
Button btnXoa;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
setContentView(R.layout.gallery);
chB=(CheckBox) findViewById(R.id.checkBox);
btnXoa=(Button) findViewById(R.id.btnDel);
list=(ListView) findViewById(R.id.listView);
arrayHinhAnh= new ArrayList<>();
adapter=new HinhAnhAdapter(GalleryActivity.this, arrayHinhAnh);
list.setAdapter(adapter);
getData();
registerForContextMenu(list);
btnXoa.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(GalleryActivity.this,"Đã xóa",Toast.LENGTH_SHORT).show();
}
});
}
private void getData(){
//lay du lieu
Cursor cursor=MainActivity.database.GetData("SELECT * FROM HinhAnh");
arrayHinhAnh.clear();
while (cursor.moveToNext()){
arrayHinhAnh.add(new HinhAnh(
cursor.getInt(0),
cursor.getString(1),
cursor.getBlob(2)
));
}
adapter.notifyDataSetChanged();
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
MenuInflater im=getMenuInflater();
im.inflate(R.menu.menu_context,menu);
}
@Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info=(AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
HinhAnh Img= arrayHinhAnh.get(info.position);
MainActivity.database.QuerryData("DELETE FROM HinhAnh WHERE Ten='"+Img.getTen()+"'");
Toast.makeText(this,"Đã xóa", Toast.LENGTH_SHORT).show();
getData();
return false;
}
}
| true
|
5c631b159bbadb6fa30c9170f988461b3437f54a
|
Java
|
maciejBart99/repository-explorer
|
/src/main/java/com/repositories/explorer/stars/api/StarsController.java
|
UTF-8
| 2,100
| 2.171875
| 2
|
[] |
no_license
|
package com.repositories.explorer.stars.api;
import com.repositories.explorer.shared.api.handlers.ApiError;
import com.repositories.explorer.shared.domain.RepositoryFetchException;
import com.repositories.explorer.shared.domain.RepositoryHost;
import com.repositories.explorer.shared.domain.UserNotFoundException;
import com.repositories.explorer.stars.StarsService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/stars")
@Tag(name = "stars")
public class StarsController {
@Autowired
private StarsService starsService;
@GetMapping("/{user}")
@Operation(summary = "Get total stars for user")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "OK"),
@ApiResponse(responseCode = "404", description = "User not found", content = @Content(schema = @Schema(implementation = ApiError.class))),
@ApiResponse(responseCode = "500", description = "Unknown problem occurred", content = @Content(schema = @Schema(implementation = ApiError.class)))
})
public ResponseEntity<StarsDto> getUserStars(@PathVariable(required = true) String user) throws UserNotFoundException, RepositoryFetchException {
// easy to change host
int stars = starsService.getStars(user, RepositoryHost.Github);
StarsDto dto = new StarsDto(stars);
return new ResponseEntity<>(dto, HttpStatus.OK);
}
}
| true
|
6354c800b6e7751091dbdcb1516efa34fafdbced
|
Java
|
Solykk/interactive_CV
|
/src/main/java/model/Chat.java
|
UTF-8
| 12,207
| 2.359375
| 2
|
[] |
no_license
|
package model;
import control.CVApplication;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.control.TextArea;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseEvent;
import javafx.scene.paint.Color;
import javafx.scene.shape.Polygon;
import javafx.stage.Stage;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
/**
* Created by Solyk on 08.05.2017.
*/
public class Chat implements ChatProperties, Runnable{
private ServerSocketChannel serverSocketChannel;
private SocketChannel makeChannel;
private volatile SocketChannel threadChannel;
private String myIpAddress;
private int myPort;
private ByteBuffer buffOutput = ByteBuffer.allocate(BuffSize);
private ByteBuffer buffInput = ByteBuffer.allocate(BuffSize);
private Group chatWindow;
private Stage stageForChat;
private TextArea input;
private TextArea output;
private Polygon sendButton;
private boolean runWhileController;
private static boolean findConnectionWhileController;
private int sendReceiveStat = -1;
public Chat(Group group, Stage stageForChat) {
this.chatWindow = group;
this.runWhileController = true;
this.stageForChat = stageForChat;
this.input = (TextArea) chatWindow.getChildren().get(9);
this.output = (TextArea)chatWindow.getChildren().get(10);
this.sendButton = (Polygon) chatWindow.getChildren().get(14);
init();
}
private void init() {
findConnectionWhileController = true;
try {
InetAddress ip = InetAddress.getLocalHost();
myIpAddress = ip.getHostAddress();
} catch (UnknownHostException e) {
e.printStackTrace();
}
findFreePort();
chatWindow.getChildren().get(12).setOnMouseClicked(event13 -> {
disconnect();
CVApplication.isChatWindowOn = Boolean.FALSE;
chatWindow = null;
stageForChat.close();
runWhileController = false;
});
chatWindow.getChildren().get(14).setOnMouseClicked(new EventHandler<MouseEvent>(){
@Override
public void handle(MouseEvent event) {
sendMessage(makeChannel, input.getText(), true);
input.clear();
}
});
chatWindow.getChildren().get(9).setOnKeyPressed(new EventHandler<KeyEvent>() {
@Override
public void handle(KeyEvent event) {
if(event.getCode().equals(KeyCode.ENTER)){
sendMessage(makeChannel, input.getText(), true);
input.clear();
}
}
});
}
private void findFreePort() {
int tryPort = 4444;
while (true) {
try {
new ServerSocket(tryPort);
myPort = tryPort;
break;
} catch (IOException e) {
tryPort++;
}
}
}
private void boundListener() {
try {
serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.socket().bind(new InetSocketAddress(myIpAddress, myPort));
serverSocketChannel.configureBlocking(false);
}
catch (Exception e) {
e.printStackTrace();
}
}
private void process() throws InterruptedException, IOException {
if (makeChannel == null){
connect();
}
if (makeChannel != null) {
readChannel(makeChannel);
}
}
private SocketChannel getValidConnection(){
Thread t0 = new Thread() {
@Override
public void run() {
for (int i = 3333; i < 3338; i++) {
threadSleep(SleepTime);
try {
if(threadChannel != null || !findConnectionWhileController || !CVApplication.isChatWindowOn){
break;
}
threadChannel = SocketChannel.open(new InetSocketAddress("192.168.0.100", i));
findConnectionWhileController = false;
break;
} catch (IOException e) {
e.printStackTrace();
}
}
}
};
t0.start();
Thread t1 = new Thread() {
@Override
public void run() {
for (int i = 3333; i < 3338; i++) {
threadSleep(SleepTime);
try {
if(threadChannel != null || !findConnectionWhileController || !CVApplication.isChatWindowOn){
break;
}
threadChannel = SocketChannel.open(new InetSocketAddress("192.168.0.101", i));
findConnectionWhileController = false;
break;
} catch (IOException e) {
e.printStackTrace();
}
}
}
};
t1.start();
Thread t2 = new Thread() {
@Override
public void run() {
for (int i = 3333; i < 3338; i++) {
threadSleep(SleepTime);
try {
if(threadChannel != null || !findConnectionWhileController || !CVApplication.isChatWindowOn){
break;
}
threadChannel = SocketChannel.open(new InetSocketAddress("192.168.0.102", i));
findConnectionWhileController = false;
break;
} catch (IOException e) {
e.printStackTrace();
}
}
}
};
t2.start();
Thread t3 = new Thread() {
@Override
public void run() {
for (int i = 3333; i < 3338; i++) {
threadSleep(SleepTime);
try {
if(threadChannel != null || !findConnectionWhileController || !CVApplication.isChatWindowOn){
break;
}
threadChannel = SocketChannel.open(new InetSocketAddress("192.168.0.103", i));
findConnectionWhileController = false;
break;
} catch (IOException e) {
e.printStackTrace();
}
}
}
};
t3.start();
Thread t4 = new Thread() {
@Override
public void run() {
for (int i = 3333; i < 3338; i++) {
threadSleep(SleepTime);
try {
if(threadChannel != null || !findConnectionWhileController || !CVApplication.isChatWindowOn){
break;
}
threadChannel = SocketChannel.open(new InetSocketAddress("192.168.0.104", i));
findConnectionWhileController = false;
break;
} catch (IOException e) {
e.printStackTrace();
}
}
}
};
t4.start();
threadSleep(1000);
return threadChannel;
}
private void connect() throws InterruptedException, IOException {
try {
if (serverSocketChannel == null){
boundListener();
}
makeChannel = getValidConnection();
threadSleep(SleepTime);
if (makeChannel != null) {
sendMessage(makeChannel, "ONLINE".toUpperCase() + "\n", false);
sendButton.setFill(Color.rgb(127,255,0));
}
} catch (Exception e) {
throw new InterruptedException();
}
}
private int readChannel(SocketChannel ch) throws IOException {
int readBytesNum = 0;
if (!ch.isOpen() || ch.socket().isClosed() || !ch.socket().isBound() ) {
return readBytesNum;
}
try {
while ((readBytesNum = ch.read(buffInput)) > 0) {
String receivedMessage = buffToString(buffInput, readBytesNum);
if (receivedMessage.equals(DisconnectMessage)){
disconnect();
} else {
if (!receivedMessage.equals(DisconnectMessage)) {
output.setStyle("-fx-text-fill: chartreuse");
output.appendText("\n" + (sendReceiveStat != 0 ? "\tDMITRIY_LYASHENKO:\n" : "") + receivedMessage);
setSendReceiveStat(0);
} else {
output.setStyle("-fx-text-fill: chartreuse");
output.appendText(DisconnectMessage);
disconnect();
}
}
buffInput.clear();
}
} catch (ClosedChannelException e) {
disconnect();
throw e;
}
return readBytesNum;
}
@Override
public void run() {
boundListener();
while (runWhileController) {
try {
threadSleep(SleepTime);
process();
} catch (Exception e) {
sendButton.setFill(Color.rgb(255, 40, 0));
setSendReceiveStat(-1);
makeChannel = null;
threadChannel = null;
e.printStackTrace();
}
}
disconnect();
}
private void disconnect() {
try {
if (makeChannel != null && makeChannel.isOpen()) {
sendMessage(makeChannel, DisconnectMessage, false);
makeChannel.close();
}
if (threadChannel != null && threadChannel.isOpen()) {
threadChannel.close();
}
if (serverSocketChannel != null && serverSocketChannel.isOpen()) {
serverSocketChannel.close();
}
}
catch (IOException e) {
e.printStackTrace();
}
finally {
makeChannel = null;
serverSocketChannel = null;
threadChannel = null;
findConnectionWhileController = true;
}
}
private void sendMessage(SocketChannel channel, String message, boolean verbose) {
if (channel == null || message == null) {
return;
}
buffOutput.clear();
buffOutput.put(message.getBytes());
buffOutput.flip();
try {
while (buffOutput.hasRemaining()) {
channel.write(buffOutput);
if (verbose) {
output.setStyle("-fx-text-fill: white");
output.appendText((sendReceiveStat != 1 ? "\n\tYOU:" : "") + "\t\n" +
buffToString(buffOutput, buffOutput.limit()));
setSendReceiveStat(1);
}
}
buffOutput.flip();
}
catch (IOException ex) {
ex.printStackTrace();
}
}
public void threadSleep(int time) {
try {
Thread.sleep(time);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void setSendReceiveStat(int sendReceiveStat) {
this.sendReceiveStat = sendReceiveStat;
}
public SocketChannel getThreadChannel() {
return threadChannel;
}
public void setThreadChannel(SocketChannel threadChannel) {
this.threadChannel = threadChannel;
}
}
| true
|
ddf1c9d73daa4930626cdb7c755c7835a92eb547
|
Java
|
pabllo007/cca
|
/Entidades/ContaCapitalEntidadesEJB/src/test/java/br/com/sicoob/cca/entidades/negocio/enums/CCAEntidadeEnumCodeCoverageTest.java
|
UTF-8
| 1,496
| 2.0625
| 2
|
[] |
no_license
|
package br.com.sicoob.cca.entidades.negocio.enums;
import org.junit.Assert;
import org.junit.Test;
public class CCAEntidadeEnumCodeCoverageTest {
@Test
public void verificaEnumsNaoVazios() {
Assert.assertTrue(EnumGrupoHistorico.values().length > 0);
Assert.assertTrue(EnumMotivoDevolucao.values().length > 0);
Assert.assertTrue(EnumPerfilConfiguracaoCapital.values().length > 0);
Assert.assertTrue(EnumSituacaoCadastroProposta.values().length > 0);
Assert.assertTrue(EnumSituacaoContaCapital.values().length > 0);
Assert.assertTrue(EnumSituacaoParcela.values().length > 0);
Assert.assertTrue(EnumSituacaoParcelamento.values().length > 0);
Assert.assertTrue(EnumTipoCooperativa.values().length > 0);
Assert.assertTrue(EnumTipoDocumento.values().length > 0);
Assert.assertTrue(EnumTipoHistoricoCCA.values().length > 0);
Assert.assertTrue(EnumTipoIntegralizacao.values().length > 0);
Assert.assertTrue(EnumTipoLote.values().length > 0);
Assert.assertTrue(EnumTipoParcelamento.values().length > 0);
Assert.assertTrue(EnumTipoPeriodoDebito.values().length > 0);
Assert.assertTrue(EnumTipoPesquisa.values().length > 0);
Assert.assertTrue(EnumTipoPesquisaDebitoIndeterminado.values().length > 0);
Assert.assertTrue(EnumTipoPessoa.values().length > 0);
Assert.assertTrue(EnumTipoSubscricaoCapital.values().length > 0);
Assert.assertTrue(EnumTipoValorConfiguracaoCapital.values().length > 0);
Assert.assertTrue(EnumTipoValorDebito.values().length > 0);
}
}
| true
|
2bd220bfc33717f7176526daff08ca708300b233
|
Java
|
codeherlife/escon-day-go
|
/app/src/main/java/com/codeherlife/escondaygo/EventHelper.java
|
UTF-8
| 801
| 3.203125
| 3
|
[] |
no_license
|
package com.codeherlife.escondaygo;
import java.util.ArrayList;
/**
* Created by melanie on 3/18/18.
*/
public class EventHelper {
public static int getCountByWeekday(ArrayList<Event> eventsList, Event.Weekday day) {
// write a for loop, use a local counter to count if x
// the day for each event is equal to the day
// passed in as a parameter
//for (){
//}
int count = 0;
for (int i = 0; i < eventsList.size() -1; i++) {
Event thisEvent = eventsList.get(i);
Event.Weekday dayOfEvent = thisEvent.getDay();
if (dayOfEvent == day) {
count = count + 1;
//++count;
System.out.println(count);
}
}
return count;
}
}
| true
|
934e5cfff41cd9c673cf813dc5658389ee7f6dc1
|
Java
|
noshadowtcc/noshadow-android
|
/app/src/main/java/com/noshadow/app/AppConstants.java
|
UTF-8
| 397
| 2.015625
| 2
|
[] |
no_license
|
package com.noshadow.app;
import android.support.annotation.IntDef;
/**
* Created by LucasZambon on 30/04/2018.
*/
public class AppConstants {
public static final String TAG_BASE_JOB = "JOB_QUEUE";
@IntDef({JobProority.HIGH, JobProority.MEDIUM, JobProority.LOW})
public @interface JobProority {
int HIGH = 1000;
int MEDIUM = 100;
int LOW = 10;
}
}
| true
|
26232d1785ed5aff352207f267a6503e1855fb6d
|
Java
|
Old-Camel/flink-learn
|
/movie/src/main/java/test/flink/movie/service/client/impl/MovieServiceImpl.java
|
UTF-8
| 421
| 1.84375
| 2
|
[] |
no_license
|
package test.flink.movie.service.client.impl;
import test.flink.movie.bean.HotBean;
import test.flink.movie.dao.MovieMapper;
import test.flink.movie.service.client.MovieService;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class MovieServiceImpl implements MovieService {
@Override
public List<HotBean> queryHot() {
return MovieMapper.queryHotMovies();
}
}
| true
|
22f09e658bc0f486682144b61e8a9960fd956474
|
Java
|
ramezmaher/assignment-1.1
|
/MySpecialArrayUtils.java
|
UTF-8
| 1,724
| 3.609375
| 4
|
[] |
no_license
|
package college;
public class MySpecialArrayUtils {
public static void reverse(int[] arr) {
int var;
int count;
for (count=0 ; count<(arr.length/2) ; count++ ) {
var = arr[count];
arr[count]=arr[(arr.length-1)-count];
arr[(arr.length-1)-count]=var;
}
}
public static int[] sumEvenOdd(int[] arr) {
int arrayOfSum[] = {0,0} ;
int count ;
for (count = 0 ; count < (arr.length) ; count++) {
if (arr[count] % 2 == 0) {
arrayOfSum[0] += arr[count];
}
else {
arrayOfSum[1] += arr[count];
}
}
return arrayOfSum ;
}
public static double average(int[] arr) {
double average = 0;
for (int i =0 ; i< arr.length ; i++) {
average += arr[i]/arr.length;
}
return average;
}
public static void moveValue(int[] arr, int val) {
int x,i;
for ( i=0 ; i<(arr.length) ; i++) {
if (arr[i] != val) {
continue;
}
else {
x=i+1;
while (arr[x-1] == val && x<=(arr.length-1)){
if (arr[x] == val){
x++;
if (x>(arr.length-1)){
break;
}
}
else {
arr[x-1]=arr[x];
arr[x]=val;
x--;
}
}
}
}
}
public static void transpose(int[] [] arr) {
int i,j,t;
if (arr.length == 0) {
return;
}
for (i=0 ; i<arr.length ; i++) {
for (j=i ; j<arr[i].length ; j++) {
if (arr.length != arr[i].length) {
return;
}
t=arr[j][i];
arr[j][i]=arr[i][j];
arr[i][j]=t;
}
}
}
}
| true
|
eb739339e5f0e6031be613387f395ed75b332ba0
|
Java
|
x3ro/tinyos-legacy
|
/tinyos-1.x/contrib/rincon/tools/java/com/rincon/flashbridgeviewer/ViewerCommands.java
|
UTF-8
| 2,266
| 2.28125
| 2
|
[
"Intel"
] |
permissive
|
package com.rincon.flashbridgeviewer;
/*
* Copyright (c) 2004-2006 Rincon Research Corporation.
* All rights reserved.
*
* Rincon Research will permit distribution and use by others subject to
* the restrictions of a licensing agreement which contains (among other things)
* the following restrictions:
*
* 1. No credit will be taken for the Work of others.
* 2. It will not be resold for a price in excess of reproduction and
* distribution costs.
* 3. Others are not restricted from copying it or using it except as
* set forward in the licensing agreement.
* 4. Commented source code of any modifications or additions will be
* made available to Rincon Research on the same terms.
* 5. This notice will remain intact and displayed prominently.
*
* Copies of the complete licensing agreement may be obtained by contacting
* Rincon Research, 101 N. Wilmot, Suite 101, Tucson, AZ 85711.
*
* There is no warranty with this product, either expressed or implied.
* Use at your own risk. Rincon Research is not liable or responsible for
* damage or loss incurred or resulting from the use or misuse of this software.
*/
public class ViewerCommands {
public static final short CMD_READ = 0;
public static final short CMD_WRITE = 1;
public static final short CMD_ERASE = 2;
public static final short CMD_FLUSH = 4;
public static final short CMD_PING = 5;
public static final short CMD_CRC = 6;
public static final short REPLY_READ = 10;
public static final short REPLY_WRITE = 11;
public static final short REPLY_ERASE = 12;
public static final short REPLY_FLUSH = 14;
public static final short REPLY_PING = 15;
public static final short REPLY_CRC = 16;
public static final short REPLY_READ_CALL_FAILED = 20;
public static final short REPLY_WRITE_CALL_FAILED = 21;
public static final short REPLY_ERASE_CALL_FAILED = 22;
public static final short REPLY_FLUSH_CALL_FAILED = 24;
public static final short REPLY_CRC_CALL_FAILED = 26;
public static final short REPLY_READ_FAILED = 30;
public static final short REPLY_WRITE_FAILED = 31;
public static final short REPLY_ERASE_FAILED = 32;
public static final short REPLY_FLUSH_FAILED = 34;
public static final short REPLY_CRC_FAILED = 36;
}
| true
|
997c18eac1f0693b678fff74d97b3f963372bf73
|
Java
|
itp265/fall2021
|
/CoffeeOLD/15Week/15_GUI/src/OpeningController.java
|
UTF-8
| 1,531
| 2.734375
| 3
|
[] |
no_license
|
import java.time.LocalDate;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.Button;
import javafx.scene.control.DatePicker;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
public class OpeningController {
@FXML
private TextField firstnameTF;
@FXML
private TextField lNameTF;
@FXML
private DatePicker datePicker;
@FXML
private Button submitButton;
@FXML
private Label errorMessage;
private MainApp myApp;
public void setMainApp(MainApp app) {
myApp = app;
}
@FXML
void doSubmit(ActionEvent event) {
System.out.println("Someone clicked the submit button");
if( firstnameTF.getText().isBlank() || lNameTF.getText().isBlank() || datePicker.getValue() == null) {
errorMessage.setText("You do not fill out all of the necessary form components");
Alert alert = new Alert(AlertType.ERROR);
alert.setTitle("Warning Dialog");
alert.setHeaderText(null);
alert.setContentText("You didn't enter all the data, please fill out all fields");
alert.showAndWait();
}
else {
String name = firstnameTF.getText() + " " + lNameTF.getText();
LocalDate bday = datePicker.getValue();
System.out.println("Got person data: " + name + " with bday = " + bday);
errorMessage.setText("");
myApp.goToSecondScene();
}
}
}
| true
|
06042b3f73519c8651e3cfdcc7d256f5f09acf3d
|
Java
|
gobige/autocodetemplate
|
/src/main/java/com/example/autocodetemplate/ohter/practice/IO/BIOTest.java
|
UTF-8
| 6,287
| 3.15625
| 3
|
[] |
no_license
|
package com.example.autocodetemplate.ohter.practice.IO;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
/**
* BIO的一些例子
*/
public class BIOTest {
public static void main(String[] args) throws Exception{
new Thread(new Runnable() {
@Override
public void run() {
BIOServer.start();
}
}).start();
Thread.sleep(1000);
new Thread(new Runnable() {
@Override
public void run() {
NIOClient nioClient = new NIOClient("192.168.1.120", 9527);
nioClient.run();
try {
Thread.sleep(1000);
nioClient.sendMes("hello world");
} catch (Exception e) {
}
}
}).start();
}
}
final class BIOClient {
public static final String SERVER_IP = "192.168.1.120";
public static final int SERVER_PORT = 14399;
// java 中的静态方法时公用的,多线程模式下也会造成阻塞
public static void sendMes(String mes) {
Socket socket = null;
try {
socket = new Socket(SERVER_IP, SERVER_PORT);
clientInputOutStream(socket,mes);
} catch (Exception e) {
System.err.println("BIO客户端=》套接字创建失败-》" + e.getMessage());
return;
}finally {
try {
socket.close();
System.out.println("BIO客户端=》socket流关闭");
} catch (Exception e) {
System.err.println("BIO客户端=》socket流关闭失败-》" + e.getMessage());
}
}
}
/**
* 客户端获取流
* @param socket
* @param mes
*/
public static void clientInputOutStream(Socket socket,String mes) {
BufferedReader bufferedReader = null;
PrintWriter printWriter = null;
try {
bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
printWriter = new PrintWriter(socket.getOutputStream(), true);
System.out.println("BIO客户端=》发送数据");
printWriter.println(mes);
System.out.println("BIO客户端=》发送数据完成");
// 客户端会一直等待服务端的回复或者断开连接的通知
System.out.println("BIO客户端=》得到服务器答复:" + bufferedReader.readLine());
}catch (Exception e) {
System.err.println("BIO客户端=》io流创建失败-》" + e.getMessage());
return;
}finally {
try {
bufferedReader.close();
printWriter.close();
System.out.println("BIO客户端=》io流关闭");
} catch (Exception e) {
System.err.println("BIO客户端=》io流关闭失败-》" + e.getMessage());
}
}
}
}
final class BIOServer {
public static ServerSocket serverSocket;
public static void start() {
serverSocket = SingleServerSocket.getInstance();
while (true) {
System.out.println("BIO服务器=》等待连接");
try {
Socket socket = serverSocket.accept();
new Thread(new Runnable() {
@Override
public void run() {
serverInputOutputStream(socket);
}
}).start();
} catch (Exception e) {
System.err.println("BIO服务器=》socket套接字获取失败:-》" + e.getMessage());
return;
}
}
}
/**
* 服务端获取流
* @param socket
*/
public static void serverInputOutputStream(Socket socket) {
BufferedReader in = null;
PrintWriter out = null;
try {
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);
String receiptMes;
while (true) {
try {
// 如果客户端不断开连接或自身服务端不断开连接,服务端会一直等待客户端发送数据
if ((receiptMes = in.readLine()) == null) {
break;
}
System.out.println("BIO服务器=》获取到数据:" + receiptMes);
Thread.sleep(8000);
out.println("我已收到你的数据:" + receiptMes);
} catch (Exception e) {
System.err.println("BIO服务器=》流数据读取失败-》" + e.getMessage());
return;
}
}
} catch (Exception e) {
System.err.println("BIO服务器=》流获取失败-》" + e.getMessage());
return;
}finally {
try {
in.close();
out.close();
System.out.println("BIO服务器=》io流关闭");
} catch (Exception e) {
System.err.println("BIO服务器=》io流关闭失败-》" + e.getMessage());
}
}
}
}
class SingleServerSocket {
private SingleServerSocket(){};
private static final int BIO_SERVER_PORT = 14399;
private volatile static ServerSocket serverSocket = null;
public static ServerSocket getInstance() {
if (serverSocket == null) {
synchronized (ServerSocket.class) {
if (serverSocket == null) {
try {
serverSocket = new ServerSocket(BIO_SERVER_PORT);
InetAddress internetAddress = serverSocket.getInetAddress();
System.out.println("初始化BIO服务器成功,端口号:" + BIO_SERVER_PORT);
} catch (Exception e) {
System.err.println("初始化BIO服务器失败:-》" + e.getMessage());
}
}
}
}
return serverSocket;
}
}
| true
|
94a531bf5fb2cb4acbc91abbb7df7459106f7e11
|
Java
|
whitten/buguldey-ai-foss
|
/eclipse_projects/Intercosmic_incubation/src/kernel/launcher/IntercosmicKernelLauncher_SpawnKernel.java
|
UTF-8
| 534
| 2.203125
| 2
|
[] |
no_license
|
package kernel.launcher;
import kernel.util.ExceptionUtil;
import kernel.util.NamedCaller;
import gui.util.ExceptionUtilGUI;
public class IntercosmicKernelLauncher_SpawnKernel {
public static void main(String[] args){
try{
lockThiscomputerMutexForIntercosmicKernel();
if(kernelExistsOnThisComputer()){
unlockThiscomputerMutexForIntercosmicKernel();
return;
}
installKernelOnThisComputer();
unlockThiscomputerMutexForIntercosmicKernel();
}catch(Throwable t){
ExceptionUtil.handleException(t);
}
}
}
| true
|
97355c7026aee62bf8ddc296f3abf35e98dba51d
|
Java
|
harry1080/vs
|
/src/com/vshow/control/item/ToTimeAction.java
|
UTF-8
| 3,741
| 2.0625
| 2
|
[] |
no_license
|
package com.vshow.control.item;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.opensymphony.xwork.Action;
import com.opensymphony.xwork.ActionContext;
import com.vshow.control.tool.Constant;
import com.vshow.control.tool.Local;
public class ToTimeAction implements Action {
private int tType=1; //1.当前时间显示 2.正计时 3倒计时
private int tsType=1; //当前时间显示
//1.yyyy-MM-dd
//2.yyyy年MM月dd日
//3.MM-dd-yyyy
//4.HH:mm:ss
//5.HH:mm
//6.HH时mm分ss秒
//7.星期
private int ttDa=1; //计时显示 天 (0不显示 1显示)
private int ttHo=1; //计时显示 时 (0不显示 1显示)
private int ttMi=1; //计时显示 分 (0不显示 1显示)
private int ttSs=1; //计时显示 秒 (0不显示 1显示)
private String ttTimePoint; // 计时时间点 yyyy-MM-dd HH:mm:ss
private int fs=24; //字体大小
private String fcolor="000000";//字体颜色
private int xy_x=0;
private int xy_y=0;
private int width;
private int height;
private int tKtype=2; //计时类型
private int advancedType; //字体显示类型 0默认 1高级
private int unitShow=0; //倒计时单位是否显示 0不显示 1显示
public String execute() throws Exception {
ActionContext ctx = ActionContext.getContext();
Map session = ctx.getSession();
Local local= (Local) session.get("local");
if(ttTimePoint==null||ttTimePoint.equals("0")){
ttTimePoint=Constant.getCurrentDate();
}
if(tType==1){
tKtype=2;
}else if(tType==2){
tKtype=2;
}else if(tType==3){
tKtype=3;
}
return SUCCESS;
}
public int gettKtype() {
return tKtype;
}
public void settKtype(int tKtype) {
this.tKtype = tKtype;
}
public int getXy_x() {
return xy_x;
}
public void setXy_x(int xy_x) {
this.xy_x = xy_x;
}
public int getXy_y() {
return xy_y;
}
public void setXy_y(int xy_y) {
this.xy_y = xy_y;
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public int gettType() {
return tType;
}
public void settType(int tType) {
this.tType = tType;
}
public int getTsType() {
return tsType;
}
public void setTsType(int tsType) {
this.tsType = tsType;
}
public int getTtDa() {
return ttDa;
}
public void setTtDa(int ttDa) {
this.ttDa = ttDa;
}
public int getTtHo() {
return ttHo;
}
public void setTtHo(int ttHo) {
this.ttHo = ttHo;
}
public int getTtMi() {
return ttMi;
}
public void setTtMi(int ttMi) {
this.ttMi = ttMi;
}
public int getTtSs() {
return ttSs;
}
public void setTtSs(int ttSs) {
this.ttSs = ttSs;
}
public String getTtTimePoint() {
return ttTimePoint;
}
public int getAdvancedType() {
return advancedType;
}
public void setAdvancedType(int advancedType) {
this.advancedType = advancedType;
}
public void setTtTimePoint(String ttTimePoint) {
this.ttTimePoint = ttTimePoint;
}
public int getFs() {
return fs;
}
public void setFs(int fs) {
this.fs = fs;
}
public String getFcolor() {
return fcolor;
}
public void setFcolor(String fcolor) {
this.fcolor = fcolor;
}
public int getUnitShow() {
return unitShow;
}
public void setUnitShow(int unitShow) {
this.unitShow = unitShow;
}
}
| true
|
6e4588edaf096e7f14d63f40522cbf48dc89c305
|
Java
|
Software-Engineering-Course-Design-Team/Course-Registration
|
/src/com/action/admin/AddDepServlet.java
|
UTF-8
| 1,948
| 2.34375
| 2
|
[] |
no_license
|
package com.action.admin;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.control.DB.DepartOP;
import com.model.javabean.DepInfo;
/**
* Servlet implementation class AddDepServlet
*/
@WebServlet("/AddDepServlet")
public class AddDepServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
String name = request.getParameter("name");
if (name.equals("")) name = null;
try {
DepInfo dep = new DepInfo();
dep.setName(name);
DepartOP depOp=new DepartOP();
long DID = depOp.InsertDepart(dep);
String message = null;
if(DID==10005) {
message = "添加学院失败!原因:信息不完整;";
}else if(DID==10006) {
message = "添加学院失败!原因:数据库插入操作失败;";
}else {
message = "添加学院成功!学院Id:"+DID+";";
}
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
out.print("<script>alert('"+message+"');window.location.href='RootMenu.html'</script>");
}catch(Exception e)
{
String path=request.getHeader("Referer");
String last=path.substring(path.length()-1);
String s[]=path.split("/");
String lastURL;
for(int i=0;i<s.length;i++)
{
System.out.println(s[i]);
}
if(last.equals("/")||s[s.length-1].equals(request.getHeader("Referer")))
{
lastURL="";
}
else
{
lastURL=s[s.length-1];
}
request.setAttribute("lastURL",lastURL );
request.getRequestDispatcher("/SqlConnError.jsp").forward(request,response);
e.printStackTrace();
}
}
}
| true
|
0ecc840e263821364d85f12b1b8d25d3bd3d9a27
|
Java
|
enriquefelix876/sistema-de-asistencias
|
/app/src/main/java/mx/itson/sistemadeasistencias/entidades/Aula.java
|
UTF-8
| 151
| 1.554688
| 2
|
[] |
no_license
|
package mx.itson.sistemadeasistencias.entidades;
public class Aula {
private int id;
private String nombre;
private String edificio;
}
| true
|
efc68f82eea2793a30fa13f3536fcbb589acc034
|
Java
|
BharathPalanivelu/repotest
|
/src/main/java/com/thoughtworks/xstream/converters/collections/MapConverter.java
|
UTF-8
| 3,857
| 2.484375
| 2
|
[] |
no_license
|
package com.thoughtworks.xstream.converters.collections;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.ExtendedHierarchicalStreamWriterHelper;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.mapper.Mapper;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
public class MapConverter extends AbstractCollectionConverter {
private final Class type;
public MapConverter(Mapper mapper) {
this(mapper, (Class) null);
}
public MapConverter(Mapper mapper, Class cls) {
super(mapper);
this.type = cls;
if (cls != null && !Map.class.isAssignableFrom(cls)) {
throw new IllegalArgumentException(cls + " not of type " + Map.class);
}
}
public boolean canConvert(Class cls) {
Class cls2 = this.type;
if (cls2 != null) {
return cls.equals(cls2);
}
return cls.equals(HashMap.class) || cls.equals(Hashtable.class) || cls.getName().equals("java.util.LinkedHashMap") || cls.getName().equals("java.util.concurrent.ConcurrentHashMap") || cls.getName().equals("sun.font.AttributeMap");
}
public void marshal(Object obj, HierarchicalStreamWriter hierarchicalStreamWriter, MarshallingContext marshallingContext) {
String serializedClass = mapper().serializedClass(Map.Entry.class);
for (Map.Entry entry : ((Map) obj).entrySet()) {
ExtendedHierarchicalStreamWriterHelper.startNode(hierarchicalStreamWriter, serializedClass, entry.getClass());
writeItem(entry.getKey(), marshallingContext, hierarchicalStreamWriter);
writeItem(entry.getValue(), marshallingContext, hierarchicalStreamWriter);
hierarchicalStreamWriter.endNode();
}
}
public Object unmarshal(HierarchicalStreamReader hierarchicalStreamReader, UnmarshallingContext unmarshallingContext) {
Map map = (Map) createCollection(unmarshallingContext.getRequiredType());
populateMap(hierarchicalStreamReader, unmarshallingContext, map);
return map;
}
/* access modifiers changed from: protected */
public void populateMap(HierarchicalStreamReader hierarchicalStreamReader, UnmarshallingContext unmarshallingContext, Map map) {
populateMap(hierarchicalStreamReader, unmarshallingContext, map, map);
}
/* access modifiers changed from: protected */
public void populateMap(HierarchicalStreamReader hierarchicalStreamReader, UnmarshallingContext unmarshallingContext, Map map, Map map2) {
while (hierarchicalStreamReader.hasMoreChildren()) {
hierarchicalStreamReader.moveDown();
putCurrentEntryIntoMap(hierarchicalStreamReader, unmarshallingContext, map, map2);
hierarchicalStreamReader.moveUp();
}
}
/* access modifiers changed from: protected */
public void putCurrentEntryIntoMap(HierarchicalStreamReader hierarchicalStreamReader, UnmarshallingContext unmarshallingContext, Map map, Map map2) {
hierarchicalStreamReader.moveDown();
Object readItem = readItem(hierarchicalStreamReader, unmarshallingContext, map);
hierarchicalStreamReader.moveUp();
hierarchicalStreamReader.moveDown();
Object readItem2 = readItem(hierarchicalStreamReader, unmarshallingContext, map);
hierarchicalStreamReader.moveUp();
map2.put(readItem, readItem2);
}
/* access modifiers changed from: protected */
public Object createCollection(Class cls) {
Class cls2 = this.type;
if (cls2 != null) {
cls = cls2;
}
return super.createCollection(cls);
}
}
| true
|
319b6ca50ced7ff74ec0c8dd22d2276f59cee5e0
|
Java
|
GoldenAppStudio/Coaching_Admin_2021
|
/app/src/main/java/studio/goldenapp/coaching/admin/VideoListActivity.java
|
UTF-8
| 7,340
| 1.945313
| 2
|
[] |
no_license
|
package studio.goldenapp.coaching.admin;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.ethanhua.skeleton.Skeleton;
import com.ethanhua.skeleton.SkeletonScreen;
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 java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class VideoListActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video_list);
getSupportActionBar().setTitle("Video List");
DatabaseReference video_reference;
List<Video> video_list = new ArrayList<>();
RecyclerView video_recyclerview;
final VideoRecycler[] video_adapter = new VideoRecycler[1];
video_recyclerview = findViewById(R.id.video_recycler);
video_recyclerview.setHasFixedSize(true);
video_recyclerview.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
SkeletonScreen skeletonScreen = Skeleton.bind(video_recyclerview)
.adapter(video_adapter[0])
.load(R.layout.video_recycler)
.show();
video_reference = FirebaseDatabase.getInstance().getReference("store/videos/");
video_reference.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
Video video = dataSnapshot.getValue(Video.class);
video_list.add(video);
}
Collections.reverse(video_list);
video_adapter[0] = new VideoRecycler(VideoListActivity.this, video_list);
video_recyclerview.setAdapter(video_adapter[0]);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
class VideoRecycler extends RecyclerView.Adapter<VideoRecycler.ViewHolder> {
View view;
Context context;
List<Video> MainImageUploadInfoList;
public VideoRecycler(Context context, List<Video> TempList) {
this.MainImageUploadInfoList = TempList;
this.context = context;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.video_recycler, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
final Video video = MainImageUploadInfoList.get(position);
holder.title.setText(video.getVideo_title());
holder.details.setText(String.format("by %s (%s)", video.getVideo_teacher(), video.getVideo_upload_time()));
holder.itemView.setOnClickListener(v -> {
Dialog myDialog = new Dialog(context);
myDialog.setContentView(R.layout.show_popup);
TextView title = myDialog.findViewById(R.id.notification_title_popup);
TextView content = myDialog.findViewById(R.id.notification_content_popup);
title.setText(video.getVideo_title());
content.setText(video.getVideo_description());
myDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
myDialog.show();
});
holder.delete_video.setOnClickListener(view -> new AlertDialog.Builder(context)
.setTitle("Are you sure?")
.setMessage("You are about to delete this video which cannot be undone. Continue?")
.setNegativeButton("No", (dialog, which) -> dialog.dismiss())
.setPositiveButton("Yes",
(dialog, which) -> {
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("store/videos/");
databaseReference.child(video.getVideo_id()).removeValue();
StorageReference reference = FirebaseStorage.getInstance().getReference("store/videos");
reference.child(video.getVideo_id() + ".mp4").delete();
Intent intent = new Intent(context, VideoListActivity.class);
context.startActivity(intent);
((Activity) context).finish();
Toast.makeText(context, "Video deleted from database", Toast.LENGTH_SHORT).show();
}).create().show());
}
@Override
public int getItemCount() {
return MainImageUploadInfoList.size();
}
static class ViewHolder extends RecyclerView.ViewHolder {
TextView title, details;
ImageView delete_video;
public ViewHolder(View itemView) {
super(itemView);
title = itemView.findViewById(R.id.video_title_recycler);
details = itemView.findViewById(R.id.video_details_recycler);
delete_video = itemView.findViewById(R.id.delete_video);
}
}
}
class Video {
String video_title, video_teacher, video_upload_time;
String video_strike_price, video_price, video_id;
String video_description;
public Video() {
}
public Video(String video_title, String video_teacher, String video_upload_time, String video_strike_price, String video_price, String video_id, String video_description) {
this.video_title = video_title;
this.video_teacher = video_teacher;
this.video_upload_time = video_upload_time;
this.video_strike_price = video_strike_price;
this.video_price = video_price;
this.video_id = video_id;
this.video_description = video_description;
}
public String getVideo_title() {
return video_title;
}
public String getVideo_description() {
return video_description;
}
public String getVideo_teacher() {
return video_teacher;
}
public String getVideo_upload_time() {
return video_upload_time;
}
public String getVideo_strike_price() {
return video_strike_price;
}
public String getVideo_price() {
return video_price;
}
public String getVideo_id() {
return video_id;
}
}
| true
|
41fca2d21d68715afa00d1b896bb0008a6521f54
|
Java
|
baggednismo/BaseMVVM
|
/app/src/main/java/com/devinmartinolich/basemvvm/view/activity/BaseActivity.java
|
UTF-8
| 23,874
| 1.632813
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.devinmartinolich.basemvvm.view.activity;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.PersistableBundle;
import android.transition.ChangeBounds;
import android.transition.ChangeImageTransform;
import android.transition.ChangeTransform;
import android.transition.Fade;
import android.transition.TransitionSet;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import com.devinmartinolich.basemvvm.BaseMVVM;
import com.devinmartinolich.basemvvm.R;
import com.devinmartinolich.basemvvm.utils.AppLog;
import com.devinmartinolich.basemvvm.utils.Constants;
import com.devinmartinolich.basemvvm.utils.FabricUtils;
import com.devinmartinolich.basemvvm.utils.SharedPrefUtils;
import com.devinmartinolich.basemvvm.view.fragment.BaseFragment;
import com.devinmartinolich.basemvvm.view.fragment.MainFragment;
import com.devinmartinolich.basemvvm.view.interfaces.DialogListener;
import com.devinmartinolich.basemvvm.view.interfaces.FirebaseAnalyticsListener;
import com.google.android.material.snackbar.Snackbar;
import com.google.firebase.analytics.FirebaseAnalytics;
import org.jetbrains.annotations.NotNull;
public class BaseActivity extends AppCompatActivity implements FirebaseAnalyticsListener {
private static final String TAG = "BaseActivity";
private Dialog progressDialog = null;
protected BaseFragment mLastFragment;
private String prevTag;
Handler handler;
Runnable runnable;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AppLog.d(TAG, "-> onCreate() called with: savedInstanceState = [" + savedInstanceState + "]");
BaseMVVM.setFirebaseAnalytics(FirebaseAnalytics.getInstance(this));
setupActionBar();
initTimeout();
}
@Override
protected void onPostCreate(@Nullable Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
AppLog.d(TAG, "-> onPostCreate() called with: savedInstanceState = [" + savedInstanceState + "]");
}
@Override
protected void onPostResume() {
super.onPostResume();
AppLog.d(TAG, "-> onPostResume() called");
}
@Override
protected void onDestroy() {
super.onDestroy();
AppLog.d(TAG, "-> onDestroy() called");
}
@Override
public void onPostCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
super.onPostCreate(savedInstanceState, persistentState);
AppLog.d(TAG, "-> onPostCreate() called with: savedInstanceState = [" + savedInstanceState + "], persistentState = [" + persistentState + "]");
}
@Override
protected void onRestart() {
super.onRestart();
AppLog.d(TAG, "-> onRestart() called");
}
@Override
public void onTrimMemory(int level) {
super.onTrimMemory(level);
AppLog.d(TAG, "-> onTrimMemory() called with: level = [" + level + "]");
}
@Override
public void onAttachFragment(Fragment fragment) {
super.onAttachFragment(fragment);
AppLog.d(TAG, "-> onAttachFragment() called with: fragment = [" + fragment + "]");
}
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
}
@Override
public void onBackPressed() {
AppLog.d(TAG, "-> onBackPressed()");
FragmentManager fragmentManager = getSupportFragmentManager();
/*
* To get the last loaded fragment which is currently visible
*/
if (mLastFragment == null) {
String lastTag = fragmentManager.getBackStackEntryAt(fragmentManager.getBackStackEntryCount() - 1).getName();
mLastFragment = (BaseFragment) fragmentManager.findFragmentByTag(lastTag);
}
/*
* Check if there is more than 1 fragment currently opened
*/
if (fragmentManager.getBackStackEntryCount() > 1) {
AppLog.d(TAG, "getBackStackEntryCount() > 1");
goBack();
} else {
AppLog.d(TAG, "else finish");
finish();
}
}
@Override
public void onLowMemory() {
super.onLowMemory();
AppLog.d(TAG, "-> onLowMemory() called");
}
@Override
public void onPause() {
AppLog.d(TAG, "-> onPause()");
super.onPause();
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
AppLog.d(TAG, "-> onNewIntent() called with: intent = [" + intent + "]");
}
@Override
public void onResume() {
super.onResume();
AppLog.d(TAG, "-> onResume()");
}
@Override
protected void onResumeFragments() {
super.onResumeFragments();
AppLog.d(TAG, "-> onResumeFragments() called");
}
/**
* Name: hideSoftKeyboard
* Created by Devin Martinolich on 1/1/2018
* Modified by
* Purpose: To hide soft keyboard
*/
public void hideSoftKeyboard() {
AppLog.d(TAG, "hideSoftKeyboard()");
View view = this.getCurrentFocus();
if (view != null) {
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
/**
* Name: showSoftKeyboard
* Created by Devin Martinolich on 1/1/2018
* Modified by
* Purpose: To show soft keyboard
*/
public void showSoftKeyboard() {
View view = this.getCurrentFocus();
if (view != null) {
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInputFromInputMethod(view.getWindowToken(), 0);
}
}
/**
* Name: showDialog
* Created by Devin Martinolich on 1/4/2018
* Modified by Devin Martinolich on 1/21/2020
* Purpose: Display dialog for show error or warning
* @param mContext
* @param sTitle - Nullable: if null it will not show a title in dialog
* @param sMessage
* @param sNegativeBtn - Nullable: If null it will not show a negative button in dialog
* @param mDialogListener
*/
public void showDialog(Context mContext, @Nullable String sTitle, String sMessage, @Nullable String sNegativeBtn, final DialogListener mDialogListener) {
hideSoftKeyboard();
AlertDialog.Builder mBuilder = new AlertDialog.Builder(mContext)
.setMessage(sMessage)
.setTitle(sTitle)
.setPositiveButton(R.string.btn_ok, (dialog, whichButton) -> {
dialog.dismiss();
if (mDialogListener != null)
mDialogListener.onDismiss(Constants.RequestCodes.DIALOG_POSITIVE_BTN);
});
if (sNegativeBtn != null) {
mBuilder.setNegativeButton(sNegativeBtn, (dialog, whichButton) -> {
dialog.dismiss();
if (mDialogListener != null)
mDialogListener.onDismiss(Constants.RequestCodes.DIALOG_NEGATIVE_BTN);
});
}
AlertDialog errorDialog = mBuilder.create();
errorDialog.setCancelable(false);
errorDialog.show();
errorDialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(ContextCompat.getColor(mContext, R.color.colorAccent));
doKeepDialog(errorDialog);
}
/**
* Name: doKeepDialog
* Created by Devin Martinolich on 1/4/2018
* Modified by
* Purpose: Keep dialog display when screen is rotating
* @param dialog
*/
private void doKeepDialog(Dialog dialog) {
WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
lp.copyFrom(dialog.getWindow().getAttributes());
lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
dialog.getWindow().setAttributes(lp);
}
/**
* Name: showSnackBarWithOK
* Created by Devin Martinolich on 1/4/2018
* Modified by
* Purpose: Display snackbar with one action button
* @param view
* @param message
* @param time
*/
public void showSnackBarWithOK(View view, final String message, final int time) {
final Snackbar snackBar = Snackbar.make(view, message, time);
snackBar.setAction("OK", v -> snackBar.dismiss());
hideSoftKeyboard();
snackBar.show();
}
/**
* Name: showSnackBarWithOneActionButton
* Created by Devin Martinolich on 1/4/2018
* Modified by
* Purpose: Display snackbar with one action button and title
* @param view
* @param message
* @param time
* @param actionTitle
* @param actionClickListener
*/
public void showSnackBarWithOneActionButton(View view, String message, int time, String actionTitle, View.OnClickListener actionClickListener) {
Snackbar snackbar = Snackbar
.make(view, message, time)
.setAction(actionTitle, actionClickListener);
hideSoftKeyboard();
snackbar.show();
}
/**
* Name: showProgressDialog
* Created by Devin Martinolich on 1/4/2018
* Modified by
* Purpose: To show progress dialog
*
* @param context
*/
public void showProgressDialog(Context context) {
AppLog.d(TAG, "-> showProgressDialog() called");
String message = "";
if (context != null && !((Activity) context).isFinishing()) {
if (progressDialog == null || !progressDialog.isShowing()) {
progressDialog = new Dialog(context);
progressDialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
try {
int dividerId = progressDialog.getContext().getResources().getIdentifier("android:id/titleDivider", null, null);
View divider = progressDialog.findViewById(dividerId);
if (divider != null)
divider.setBackgroundColor(context.getResources().getColor(R.color.transparent));
} catch (Exception e) {
AppLog.e(TAG, e.getMessage());
FabricUtils.fabricException(e);
e.printStackTrace();
}
try {
TextView mTitle = (TextView) progressDialog.findViewById(android.R.id.title);
if (mTitle != null)
mTitle.setGravity(Gravity.RIGHT | Gravity.CENTER_VERTICAL);
int x = Resources.getSystem().getIdentifier("titleDivider", "id", "android");
View titleDivider = progressDialog.findViewById(x);
if (titleDivider != null)
titleDivider.setBackgroundColor(context.getResources().getColor(R.color.transparent));
} catch (Exception e) {
AppLog.e(TAG, e.getMessage());
FabricUtils.fabricException(e);
e.printStackTrace();
}
progressDialog.setContentView(R.layout.dialog_custom_progressbar);
TextView tvMessage = (TextView) progressDialog.findViewById(R.id.txtMessage);
if (!message.equals(""))
tvMessage.setText(message);
progressDialog.setCancelable(true);
if (!((Activity) context).isFinishing()) {
progressDialog.show();
blockUserInput(true);
}
}
}
else
AppLog.e(TAG, "Context: " + context.toString());
}
/**
* Name: hideProgressDialog
* Created by Devin Martinolich on 1/4/2018
* Modified by
* Purpose: To hide progress dialog
*/
public void hideProgressDialog() {
AppLog.d(TAG, "-> hideProgressDialog() called");
try {
if (progressDialog != null && progressDialog.isShowing()) {
blockUserInput(false);
progressDialog.dismiss();
}
} catch (Throwable throwable) {
AppLog.e(TAG, throwable.toString());
FabricUtils.fabricException(throwable);
}
finally {
progressDialog = null;
}
}
/**
* Name: blockUserInput
* Created by Devin Martinolich on 12/3/2019
* Modified by
* Purpose: To disable the input on a view completely. This should be used during dialogs
* that make API calls to prevent the user from breaking the process.
*/
public void blockUserInput(Boolean lockControls) {
if (lockControls)
getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE, WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
else
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
}
/**
* Name: loadFragment
* Created by Devin Martinolich 12/11/2019
* Modified by
* Purpose: Load new fragment
*
* @param aClass as class object of the opening fragment
* @param aTag as tag of the opening fragment
* @param aBundle as data to pass to the opening fragment
*/
public void loadFragment(Class aClass, String aTag, Bundle aBundle) {
AppLog.d(TAG, "loadFragment()");
AppLog.d(TAG, "loadFragment() called with: aClass = [" + aClass + "], aTag = [" + aTag + "], aBundle = [" + aBundle + "]");
BaseFragment fragmentToShow = (BaseFragment) Fragment.instantiate(this, aClass.getName(), aBundle);
FragmentManager fragmentManager = getSupportFragmentManager();
int fragmentCount = fragmentManager.getBackStackEntryCount();
AppLog.d(TAG, "Current fragment: " + (fragmentCount > 0 ? fragmentManager.getBackStackEntryAt(fragmentCount - 1).getName() : "null"));
/*
* Only open the fragment once. User can click many times if the device is slow between
* Fragment transactions. Check the current fragment and don't allow move if its the same.
* If the user is at the MainFragment already and tries to logout, we need to allow that.
*/
if (fragmentManager.getBackStackEntryCount() <= 0 ||
(fragmentCount > 0 &&
!fragmentManager.getBackStackEntryAt(fragmentCount - 1).getName().equals(aTag)) ||
fragmentManager.getBackStackEntryAt(fragmentCount - 1).getName().equals("MainFragment")) {
AppLog.d(TAG, "We should open the new fragment");
TransitionSet transitionSet = new TransitionSet();
transitionSet.setOrdering(TransitionSet.ORDERING_TOGETHER);
transitionSet.addTransition(new ChangeBounds()).
addTransition(new ChangeTransform()).
addTransition(new ChangeImageTransform());
fragmentToShow.setSharedElementEnterTransition(transitionSet);
fragmentToShow.setEnterTransition(new Fade());
if (mLastFragment != null)
mLastFragment.setExitTransition(new Fade());
fragmentToShow.setSharedElementReturnTransition(transitionSet);
fragmentManager.beginTransaction()
.replace(R.id.flContainer, fragmentToShow, aTag)
.addToBackStack(aTag)
.commitAllowingStateLoss();
mLastFragment = fragmentToShow;
prevTag = aTag;
}
else {
AppLog.d(TAG, "Fragment is already open, user probably clicked a button multiple times.");
}
}
/**
* Name: goBack
* Created by Devin Martinolich 12/11/2019
* Modified by
* Purpose: Called when moving to previous fragment
*/
public void goBack() {
AppLog.d(TAG, "goBack()");
try
{
FragmentManager fragmentManager = getSupportFragmentManager();
/*
* To get the last loaded fragment which is currently visible
*/
if (mLastFragment == null) {
String lastTag = fragmentManager.getBackStackEntryAt(fragmentManager.getBackStackEntryCount() - 1).getName();
mLastFragment = (BaseFragment) fragmentManager.findFragmentByTag(lastTag);
}
/*
* This will set the result from current fragment to pass to previous fragment while going back.
*/
// Object object = mLastFragment.setResult();
super.onBackPressed();
String msTag = fragmentManager.getBackStackEntryAt(fragmentManager.getBackStackEntryCount() - 1).getName();
AppLog.d(TAG, msTag);
mLastFragment = (BaseFragment) fragmentManager.findFragmentByTag(msTag);
prevTag = msTag;
/*
* Pass the result object to current visible fragment received from closing fragment
*/
// fragmentToResume.getResult(object);
} catch (Exception e) {
AppLog.e(TAG, e.getMessage());
FabricUtils.fabricException(e);
e.printStackTrace();
}
}
/**
* Name: popFragment
* Created by Devin Martinolich 1/2/2020
* Modified by
* Purpose: Reset the view back to a specific fragment.
*
* @param aClass
*/
public void popFragment(String aClass, int flag) {
AppLog.d(TAG, "-> popFragment()");
getSupportFragmentManager().popBackStack(aClass, flag);
}
/**
* Name: setupActionBar
* Created by Devin Martinolich 12/12/2019
* Modified by
* Purpose: Single method to enable/disable features of the ActionBar
*/
public void setupActionBar(){
AppLog.d(TAG, "-> setupActionBar()");
ActionBar mActionBar = getSupportActionBar();
if (mActionBar != null) {
AppLog.d(TAG, "ActionBar != null");
mActionBar.setDisplayShowTitleEnabled(true);
}
}
/**
* Name: hasTelephony
* Created by Devin Martinolich 12/16/2019
* Modified by
* Purpose: Get the device type as it relates to telephony functionality
* @return boolean
*/
public boolean hasTelephony() {
return getPackageManager().hasSystemFeature(PackageManager.FEATURE_TELEPHONY);
}
/**
* Name: initTimeout
* Created by Devin Martinolich 12/18/2019
* Modified by
* Purpose: Define the action of the runnable and what will happen when
* user reaches or exceeds the timeout period.
* NOTE: This will also work if the app is paused BUT will not work if the app is destroyed.
*/
public void initTimeout() {
AppLog.d(TAG, "-> initTimeout");
handler = new Handler();
runnable = () -> {
AppLog.d(TAG, "User was inactive for " +
Constants.DefaultValues.DEFAULT_TIMEOUT_MILLISECONDS +
" milliseconds or " +
Constants.DefaultValues.DEFAULT_TIMEOUT_MILLISECONDS / 60000 +
" minutes.");
// If the user is logged in
if (SharedPrefUtils.getBool(BaseMVVM.getAppInstance().getApplicationContext(),
Constants.SharedPrefName.APP_PREFS,
Constants.SharedPrefKeys.LOGGED_IN,
false)) {
// Set the login flag to false
SharedPrefUtils.setBool(BaseMVVM.getAppInstance().getApplicationContext(),
Constants.SharedPrefName.APP_PREFS,
Constants.SharedPrefKeys.LOGGED_IN,
false);
// Return the user back to the login fragment
loadFragment(MainFragment.class, MainFragment.class.getSimpleName(), null);
}
};
startHandler();
}
@Override
public void onUserInteraction() {
AppLog.d(TAG, "-> onUserInteraction()");
super.onUserInteraction();
stopHandler();
startHandler();
}
/**
* Name: stopHandler
* Created by Devin Martinolich 12/18/2019
* Modified by
* Purpose: Stop the handler that is tracking the login time.
*/
public void stopHandler() {
AppLog.d(TAG, "-> stopHandler()");
handler.removeCallbacks(runnable);
}
/**
* Name: startHandler
* Created by Devin Martinolich 12/18/2019
* Modified by
* Purpose: Start a new handler to track the timeout period.
*/
public void startHandler() {
AppLog.d(TAG, "-> startHandler()");
handler.postDelayed(runnable, Constants.DefaultValues.DEFAULT_TIMEOUT_MILLISECONDS);
}
/**
* Name: logAnalytics
* Created by Devin Martinolich 12/10/2019
* Modified by
* Purpose: Manually send analytical data to Firebase
*
* @param type
* @param item
*/
@Override
public void logAnalytics(String type, String item, @NotNull String event) {
AppLog.d(TAG, "-> logAnalytics(" + type + ", " + item + ")");
Bundle bundle = new Bundle();
bundle.putString(type, item);
if (BaseMVVM.getFirebaseAnalytics() == null) {
AppLog.d(TAG, "Firebase Analytics is null...");
}
else if (event.length() <= 0){
AppLog.d(TAG, "Event was empty, unable to log an empty event.");
}
else {
BaseMVVM.getFirebaseAnalytics().logEvent(event, bundle);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
AppLog.d(TAG, "-> onCreateOptionsMenu()");
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.main, menu);
if (SharedPrefUtils.getBool(BaseMVVM.getAppInstance().getApplicationContext(),
Constants.SharedPrefName.APP_PREFS,
Constants.SharedPrefKeys.LOGGED_IN,
false)) {
menu.add(Menu.NONE, Constants.RequestCodes.LOGOUT, Menu.NONE,"Logout");
}
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
AppLog.d(TAG, "Menu clicked.");
switch (item.getItemId()) {
case Constants.RequestCodes.LOGOUT:
AppLog.d(TAG, "Logout clicked in menu.");
// Set the login flag to false
SharedPrefUtils.setBool(BaseMVVM.getAppInstance().getApplicationContext(),
Constants.SharedPrefName.APP_PREFS,
Constants.SharedPrefKeys.LOGGED_IN,
false);
// Return the user back to the login fragment
popFragment(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
loadFragment(MainFragment.class, MainFragment.class.getSimpleName(), null);
return true;
case android.R.id.home:
AppLog.d(TAG, "Back button clicked");
onBackPressed();
return true;
}
return false;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
}
| true
|
a73c5b62f6813aeeeb6ed13bc1b0a1c53e9fe76d
|
Java
|
archimatetool/archi
|
/com.archimatetool.commandline/src/com/archimatetool/commandline/ICommandLineProvider.java
|
UTF-8
| 1,223
| 2.265625
| 2
|
[
"MIT",
"LicenseRef-scancode-free-unknown"
] |
permissive
|
/**
* This program and the accompanying materials
* are made available under the terms of the License
* which accompanies this distribution in the file LICENSE.txt
*/
package com.archimatetool.commandline;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Options;
/**
* Interface for a Command Line Provider
*
* @author Phillip Beauvoir
*/
public interface ICommandLineProvider {
String EXTENSION_ID = "com.archimatetool.commandline.commandlineProvider"; //$NON-NLS-1$
int PRIORITY_LOAD_OR_CREATE_MODEL = 10;
int PRIORITY_IMPORT = 20;
int PRIORITY_RUN_SCRIPT = 30;
int PRIORITY_REPORT_OR_EXPORT = 40;
int PRIORITY_SAVE_MODEL = 50;
/**
* Run the command
* @param commandLine options
* @throws Exception
*/
default void run(CommandLine commandLine) throws Exception {}
/**
* @return A list of options that this provider supports or null if none
*/
default Options getOptions() {
return null;
}
/**
* @return priority of this provider
* A value of PRIORITY_REPORT_OR_EXPORT is the default
*/
default int getPriority() {
return PRIORITY_REPORT_OR_EXPORT;
}
}
| true
|