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 |
---|---|---|---|---|---|---|---|---|---|---|---|
40256700f44688055203cf7795bcd60599035d33
|
Java
|
uec/uecgatk
|
/src/edu/usc/epigenome/uecgatk/nmerContexts/NmerCollection.java
|
UTF-8
| 302 | 1.789063 | 2 |
[] |
no_license
|
package edu.usc.epigenome.uecgatk.nmerContexts;
/**
* @author benb
*
* This keeps a list of NmerWithRef objects. Used extensively for bisulfite-seq analysis,
* where any given analysis is interested in (one or more) particular contexts. For instance:
*
*
*/
public class NmerCollection {
}
| true |
0a6dcb1a7e26fa3e58657522327a18be701950ee
|
Java
|
gsb7814/studygit
|
/pcash/src/com/sxmccitlab/pcash/po/VoucherDetail.java
|
UTF-8
| 3,158 | 2.0625 | 2 |
[] |
no_license
|
package com.sxmccitlab.pcash.po;
import java.sql.Timestamp;
import java.util.Date;
/**
* TVoucherDetail entity. @author MyEclipse Persistence Tools
*/
public class VoucherDetail implements java.io.Serializable {
// Fields
private VoucherDetailId id;
private String voucherDate;
private String voucherAbstract;
private String accountCode;
private Double fdebit;
private Double fcredit;
private String chargeFlag;
private Date chargeTime;
private String rollbackFlag;
private Date rollbackTime;
private Long id_1;
private String currencyDetail;
// Constructors
/** default constructor */
public VoucherDetail() {
}
/** minimal constructor */
public VoucherDetail(VoucherDetailId id) {
this.id = id;
}
/** full constructor */
public VoucherDetail(VoucherDetailId id, String voucherDate,
String voucherAbstract, String accountCode, Double fdebit,
Double fcredit, String chargeFlag, Timestamp chargeTime,
String rollbackFlag, Timestamp rollbackTime, Long id_1,
String currencyDetail) {
this.id = id;
this.voucherDate = voucherDate;
this.voucherAbstract = voucherAbstract;
this.accountCode = accountCode;
this.fdebit = fdebit;
this.fcredit = fcredit;
this.chargeFlag = chargeFlag;
this.chargeTime = chargeTime;
this.rollbackFlag = rollbackFlag;
this.rollbackTime = rollbackTime;
this.id_1 = id_1;
this.currencyDetail = currencyDetail;
}
// Property accessors
public VoucherDetailId getId() {
return this.id;
}
public void setId(VoucherDetailId id) {
this.id = id;
}
public String getVoucherDate() {
return this.voucherDate;
}
public void setVoucherDate(String voucherDate) {
this.voucherDate = voucherDate;
}
public String getVoucherAbstract() {
return this.voucherAbstract;
}
public void setVoucherAbstract(String voucherAbstract) {
this.voucherAbstract = voucherAbstract;
}
public String getAccountCode() {
return this.accountCode;
}
public void setAccountCode(String accountCode) {
this.accountCode = accountCode;
}
public Double getFdebit() {
return this.fdebit;
}
public void setFdebit(Double fdebit) {
this.fdebit = fdebit;
}
public Double getFcredit() {
return this.fcredit;
}
public void setFcredit(Double fcredit) {
this.fcredit = fcredit;
}
public String getChargeFlag() {
return this.chargeFlag;
}
public void setChargeFlag(String chargeFlag) {
this.chargeFlag = chargeFlag;
}
public String getRollbackFlag() {
return this.rollbackFlag;
}
public void setRollbackFlag(String rollbackFlag) {
this.rollbackFlag = rollbackFlag;
}
public Date getChargeTime() {
return chargeTime;
}
public void setChargeTime(Date chargeTime) {
this.chargeTime = chargeTime;
}
public Date getRollbackTime() {
return rollbackTime;
}
public void setRollbackTime(Date rollbackTime) {
this.rollbackTime = rollbackTime;
}
public Long getId_1() {
return this.id_1;
}
public void setId_1(Long id_1) {
this.id_1 = id_1;
}
public String getCurrencyDetail() {
return this.currencyDetail;
}
public void setCurrencyDetail(String currencyDetail) {
this.currencyDetail = currencyDetail;
}
}
| true |
67812521fa26433ff97bba0a119eed55838638c9
|
Java
|
soldiers1989/clothingShop
|
/CustomClothing-web/src/com/tl/customclothing/test/Test_001_connector.java
|
UTF-8
| 478 | 2.1875 | 2 |
[] |
no_license
|
package com.tl.customclothing.test;
import java.util.List;
import com.tl.customclothing.mapper.CountMapper;
import com.tl.customclothing.util.database.JDBCTemplate;
public class Test_001_connector
{
public static void main(String[] args)
{
// 测试连接数据库
JDBCTemplate jdbcTemplate = new JDBCTemplate();
String sql = "call test001_lianjie()";
List<Object> list = jdbcTemplate.query(sql, new CountMapper(), null);
System.out.println(list.get(0));
}
}
| true |
f59d3f3d60b1c2f810f46dc05d191ce0c8b70e98
|
Java
|
movilla1/elcanPOS
|
/src/com/elcansoftware/elcanpos/elcanPosDataHelper.java
|
UTF-8
| 3,333 | 2.46875 | 2 |
[] |
no_license
|
package com.elcansoftware.elcanpos;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class elcanPosDataHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "elcanpos.db";
private static final int DATABASE_VERSION = 1;
private static final String POS_TABLE_NAME = "articles";
private static final String POS_TABLE_CREATE =
"CREATE TABLE " + POS_TABLE_NAME + " (" +
"_id integer primary key autoincrement," +
"sku TEXT, " +
"name TEXT, " +
"image TEXT, " +
"stock integer, " +
"description TEXT, " +
"category TEXT, " +
"price FLOAT);";
private static final String POS_TABLE_NAMEMFS = "mostfrecuent";
private static final String POS_TABLE_MFS_CREATE =
"CREATE TABLE " + POS_TABLE_NAMEMFS + " (" +
"_id integer primary key autoincrement,"+
"sku TEXT UNIQUE, " +
"tcount interger);";
private static final String POS_TABLE_CAT = "categories";
private static final String POS_TABLE_CAT_CREATE =
"CREATE TABLE " + POS_TABLE_CAT + " (" +
"_id integer primary key autoincrement,"+
"category TEXT UNIQUE, " +
"catdesc TEXT);";
private static final String POS_TABLE_ORDERS = "orders";
private static final String POS_TABLE_ORDERS_CREATE =
"CREATE TABLE "+POS_TABLE_ORDERS+" ( " +
"_id integer primary key autoincrement,"+
" orderdate TEXT," +
" total FLOAT," +
" posid TEXT,"+
" synced integer,"+
" skulist TEXT)";
public elcanPosDataHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(POS_TABLE_CREATE);
db.execSQL(POS_TABLE_MFS_CREATE);
db.execSQL(POS_TABLE_ORDERS_CREATE);
db.execSQL(POS_TABLE_CAT_CREATE);
db.execSQL("INSERT INTO mostfrecuent VALUES(1,'tst1',2)");
db.execSQL("INSERT INTO mostfrecuent VALUES(2,'tst2',1)");
db.execSQL("INSERT INTO mostfrecuent VALUES(3,'tst3',3)");
db.execSQL("INSERT INTO articles VALUES (1,'tst1','Test art1','lock',5,'Test Article 1, while a test','01/01','12.3')");
db.execSQL("INSERT INTO articles VALUES (2,'tst2','Test art2','lock',7,'Test Article 2, while a test','01/01','13.3')");
db.execSQL("INSERT INTO articles VALUES (3,'tst3','Test art3','lock',3,'Test Article 3, while a test','01/02','1.3')");
//db.execSQL("INSERT INTO settings VALUES (1,'pos1','http://www.aeromodelismoelcan.com/index.php?option=com_vm2elcanpos&tmpl=component&task=getData&format=raw','movilla','pass123')");
db.execSQL("INSERT INTO categories VALUES (1,'01/01','Propelers/Folding')");
db.execSQL("INSERT INTO categories VALUES (2,'01/02','Propelers/Electric')");
}
@Override
public void onUpgrade(SQLiteDatabase db, int arg1, int arg2) {
db.execSQL("DROP TABLE IF EXISTS "+POS_TABLE_NAME);
db.execSQL("DROP TABLE IF EXISTS "+POS_TABLE_ORDERS);
db.execSQL("DROP TABLE IF EXISTS "+POS_TABLE_NAMEMFS);
db.execSQL("DROP TABLE IF EXISTS "+POS_TABLE_CAT);
onCreate(db);
}
}
| true |
21b4d2931065cf6a4c1676839818ef41b75e0aff
|
Java
|
zzzke/MyChat
|
/app/src/main/java/com/example/zhaok/mychat/StartPageActivity.java
|
UTF-8
| 1,344 | 2.078125 | 2 |
[] |
no_license
|
package com.example.zhaok.mychat;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class StartPageActivity extends AppCompatActivity {
private Button alradyHaveAccountButton;
private Button needAccountButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start_page);
alradyHaveAccountButton = (Button)findViewById(R.id.already_have_account_button);
needAccountButton = (Button)findViewById(R.id.need_account_button);
needAccountButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent registerIntent = new Intent(getApplicationContext(),RegisterActivity.class);
startActivity(registerIntent);
}
});
alradyHaveAccountButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent loginIntent = new Intent(getApplicationContext(),LoginActivity.class);
startActivity(loginIntent);
}
});
}
}
| true |
52bc5416badac364cd407745d7d085718795f506
|
Java
|
bradh/mti
|
/src/main/java/mti/commons/elasticsearch/NativeElasticsearchTemplate.java
|
UTF-8
| 7,753 | 2.109375 | 2 |
[] |
no_license
|
package mti.commons.elasticsearch;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import org.elasticsearch.action.admin.indices.alias.IndicesAliasesResponse;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequestBuilder;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.action.admin.indices.refresh.RefreshResponse;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.client.Client;
import org.elasticsearch.search.SearchHit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.databind.ObjectMapper;
public class NativeElasticsearchTemplate
{
private final Logger log = LoggerFactory.getLogger(
this.getClass());
private Client client;
private ObjectMapper mapper;
public NativeElasticsearchTemplate(
Client client,
ObjectMapper mapper ) {
this.client = client;
this.mapper = mapper;
}
public boolean createIndex(
String indexName ) {
CreateIndexRequestBuilder createIndexRequestBuilder = client.admin().indices().prepareCreate(
indexName);
CreateIndexResponse response = createIndexRequestBuilder.execute().actionGet();
return response.isAcknowledged();
}
public boolean createAlias(
String indexName,
String aliasName ) {
IndicesAliasesResponse createAliasResponse = client.admin().indices().prepareAliases().addAlias(
indexName,
aliasName).execute().actionGet();
return createAliasResponse.isAcknowledged();
}
public boolean indexExists(
String indexName ) {
return client.admin().indices().prepareExists(
indexName).execute().actionGet().isExists();
}
public <T extends ESModel> boolean index(
String indexName,
String type,
T o ) {
boolean created = false;
try {
String source = mapper.writeValueAsString(
o);
IndexResponse response = client
.prepareIndex(
indexName,
type,
o.getId())
.setSource(
source)
.get();
created = response.isCreated();
if (created) {
o.setId(
response.getId());
}
}
catch (Exception e) {
log.error(
e.getMessage(),
e);
}
return created;
}
public <T extends ESModel> void bulkIndex(
String indexName,
String type,
Collection<T> objects ) {
try {
BulkRequestBuilder bulkRequest = client.prepareBulk();
for (T object : objects) {
String source = mapper.writeValueAsString(
object);
bulkRequest.add(
client.prepareIndex(
indexName,
type,
object.getId()).setSource(
source));
}
BulkResponse response = bulkRequest.execute().get();
// not so friendly way of allowing collections
// unfortunately collection does not implement get(index)
if (objects instanceof List) {
List<T> l = (List<T>) objects;
for (BulkItemResponse item : response.getItems()) {
if (!item.isFailed()) {
l.get(
item.getItemId()).setId(
item.getId());
}
}
}
}
catch (Exception e) {
log.error(
e.getMessage(),
e);
}
}
public <T extends ESModel> List<T> queryForList(
SearchRequestBuilder searchQuery,
Class<T> clazz ) {
SearchResponse response = searchQuery.setSize(
Integer.MAX_VALUE).execute().actionGet();
List<T> results = new ArrayList<T>(
response.getHits().getHits().length);
for (int i = 0; i < response.getHits().getHits().length; ++i) {
try {
SearchHit hit = response.getHits().getHits()[i];
T result = mapper.readValue(
hit.getSourceAsString(),
clazz);
result.setId(
hit.getId());
results.add(
result);
}
catch (Exception e) {
log.error(
e.getMessage(),
e);
}
}
return results;
}
public <T extends ESModel> List<T> queryForPage(
SearchRequestBuilder searchQuery,
int pageNumber,
int pageSize,
Class<T> clazz ) {
SearchResponse response = searchQuery
.setFrom(
pageNumber * pageSize)
.setSize(
pageSize)
.execute()
.actionGet();
List<T> results = new ArrayList<T>(
response.getHits().getHits().length);
for (int i = 0; i < response.getHits().getHits().length; ++i) {
try {
SearchHit hit = response.getHits().getHits()[i];
T result = mapper.readValue(
hit.getSourceAsString(),
clazz);
result.setId(
hit.getId());
results.add(
result);
}
catch (Exception e) {
log.error(
e.getMessage(),
e);
}
}
results.removeAll(
Arrays.asList(
"",
null));
return results;
}
public <T extends ESModel> T findOne(
String index,
String type,
String id,
Class<T> clazz ) {
T result = null;
try {
GetResponse response = client.prepareGet(
index,
type,
id).execute().get();
if (response.isExists()) {
result = mapper.readValue(
response.getSourceAsBytes(),
clazz);
result.setId(
response.getId());
}
}
catch (Exception e) {
log.error(
e.getMessage(),
e);
}
return result;
}
public <T extends ESModel> T queryForOne(
SearchRequestBuilder searchQuery,
Class<T> clazz ) {
SearchResponse response = searchQuery.execute().actionGet();
T result = null;
try {
if (response.getHits().getTotalHits() > 0L) {
result = mapper.readValue(
response.getHits().getHits()[0].getSourceAsString(),
clazz);
result.setId(response.getHits().getHits()[0].getId());
}
}
catch (Exception e) {
log.error(
e.getMessage(),
e);
}
return result;
}
public long count(
SearchRequestBuilder searchQuery ) {
SearchResponse response = searchQuery.setSearchType(
SearchType.COUNT).execute().actionGet();
return response.getHits().getTotalHits();
}
public SearchRequestBuilder NativeSearchQueryBuilder() {
return new SearchRequestBuilder(
this.client);
}
public <T extends ESModel> boolean delete(
String index,
String type,
T instance ) {
boolean result = false;
try {
DeleteResponse response = client.prepareDelete(
index,
type,
instance.getId()).execute().get();
result = response.isFound();
}
catch (Exception e) {
log.error(
e.getMessage(),
e);
}
return result;
}
public <T extends ESModel> int delete(
String index,
String type,
Collection<T> objects ) {
int result = 0;
try {
// DeleteResponse response = client.prepareDelete(index, type,
// instance.getId()).execute().get();
BulkRequestBuilder bulkRequest = client.prepareBulk();
for (T object : objects) {
bulkRequest.add(
client.prepareDelete(
index,
type,
object.getId()));
}
BulkResponse response = bulkRequest.execute().get();
if (response.hasFailures()) {
for (BulkItemResponse item : response.getItems()) {
if (!item.isFailed()) ++result;
}
}
else {
result = objects.size();
}
}
catch (Exception e) {
log.error(
e.getMessage(),
e);
}
return result;
}
public boolean refresh(
String index ) {
boolean success = false;
try {
RefreshResponse result = client.admin().indices().prepareRefresh(
index).execute().get();
success = (result.getShardFailures().length == 0);
}
catch (Exception e) {
log.error(
e.getMessage(),
e);
}
return success;
}
}
| true |
1af993e02ad9a7a254b58d825ad74259bd18acde
|
Java
|
WindWZQ/CameraXQRCode
|
/scan/src/main/java/com/wzq/scan/util/LogUtil.java
|
UTF-8
| 398 | 1.804688 | 2 |
[] |
no_license
|
package com.wzq.scan.util;
import android.util.Log;
import com.wzq.scan.core.ScanConstant;
public class LogUtil {
public static void e(String TAG, String content) {
if (ScanConstant.debug) {
Log.e(TAG, content);
}
}
public static void i(String TAG, String content) {
if (ScanConstant.debug) {
Log.i(TAG, content);
}
}
}
| true |
ebf1508eb041e9710fb30342bec9214ba8856e26
|
Java
|
sedyukov/DotsGame
|
/src/GameCanvas.java
|
UTF-8
| 357 | 2.9375 | 3 |
[] |
no_license
|
import javax.swing.*;
import java.awt.*;
public class GameCanvas extends JPanel {
private final Game game;
public GameCanvas(Game game){
this.game = game;
}
@Override
public void paint(Graphics g) {
super.paint(g);
for(GameObject gameObject: game.gameObjects){
gameObject.draw(g);
}
}
}
| true |
526153e07975fee312f917150771a8a975587e81
|
Java
|
fanmengmeng/lssg
|
/src/main/java/com/lssg/dao/sys/UserRoleMapper.java
|
UTF-8
| 280 | 1.625 | 2 |
[] |
no_license
|
package com.lssg.dao.sys;
import com.lssg.common.config.MyMapper;
import com.lssg.model.sys.UserRole;
import org.springframework.stereotype.Repository;
@Repository
public interface UserRoleMapper extends MyMapper<UserRole> {
void deleteUserRolesByUserId(Integer[] userIds);
}
| true |
964651b2ff2b638447a8e148eaaac87764d2cc8f
|
Java
|
ElementiumST/hodgepodge
|
/src/com/festp/remain/LeashedPlayer.java
|
UTF-8
| 5,589 | 2.140625 | 2 |
[
"MIT"
] |
permissive
|
package com.festp.remain;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.craftbukkit.v1_13_R2.entity.CraftLeash;
import org.bukkit.entity.Bat;
import org.bukkit.entity.Chicken;
import org.bukkit.entity.Entity;
import org.bukkit.entity.LeashHitch;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.util.Vector;
import com.festp.Utils;
public class LeashedPlayer {
public static final String beacon_id = "leashing";
private static final float pull_k = 0.02f, kxz = 0.05f, ky = 0.08f;
LivingEntity workaround;
Entity leashed;
private int cooldown_new = 0;
private static final int ticks_new = 60;
private int cooldown_break = 0;
private static final int ticks_break = 20;
//!onGround, Ep = mgh, Ek = mv^2/2, distance = l, vx -> vertical flat, which contains both player and leashHolder
//Ep = Gh, Ek = v^2
private static final double G = 15, kspeed = 0.1d, E_friction = /*0.998*/1 //2g
/*, R_PULL = 6, R_PULL_SQUARE = R_PULL*R_PULL*/, R = 8, R_SQUARE = R*R, R_BREAK_SQUARE = 140, PULL_MARGIN = 1, PULL_R2 = (R-PULL_MARGIN)*(R-PULL_MARGIN);
private double last_fall_h = 0, E = 0;
private Vector Vold = new Vector();
private boolean up_dir = false;
public LeashedPlayer(Entity holder, Entity leashed) {
cooldown_break = ticks_break;
workaround = (LivingEntity) Utils.spawnBeacon(leashed.getLocation(), beacon_id, Bat.class);
this.leashed = leashed;
workaround.setLeashHolder(holder);
}
public boolean tick() {
if(cooldown_new > 0) {
cooldown_new -= 1;
}
else if(cooldown_break > 0) {
cooldown_break -= 1;
}
else if(workaround.isLeashed() && !workaround.isDead() && !leashed.isDead() && workaround.getWorld() == leashed.getWorld() && workaround.getLeashHolder().getWorld() == leashed.getWorld()
&& !(leashed instanceof Player && !((Player)leashed).isOnline() ) ) {
/*((Bat)workaround).setAwake(true);
Vector velocity = calc_velocity();
leashed.setVelocity(velocity);
workaround.setVelocity(velocity.multiply(-1));*/
double dist2 = leashed.getLocation().distanceSquared(workaround.getLeashHolder().getLocation());
if(dist2 > R_BREAK_SQUARE) {
leashed.getWorld().dropItem(leashed.getLocation(), new ItemStack(Material.LEAD, 1));
removeWorkaround();
return false;
}
else if(dist2 > PULL_R2) { //R_SQUARE
Vector velocity = calc_velocity_to_LeashHolder();
Block b = leashed.getLocation().getBlock();
int dx = (int)Math.signum(velocity.getX()), dz = (int)Math.signum(velocity.getZ());
if(velocity.getY() < 0.3)
if( b.getRelative(dx, 0, 0).getType().isSolid() || b.getRelative(0, 0, dz).getType().isSolid() || b.getRelative(dx, 0, dz).getType().isSolid() )
velocity.add(new Vector(0, 0.3, 0));
leashed.setVelocity(velocity);
}
workaround.teleport(leashed);
/* TELEPORT TO PIG OR SOMETHING SAME
if(dist2 > 100) {
workaround.remove();
return false;
}
else if(dist2 > 64) {
Vector velocity = calc_velocity_to_LeashFake();
leashed.teleport(workaround);
leashed.setVelocity(velocity);
//workaround.setVelocity(velocity.multiply(-1));
}
else {
workaround.teleport(leashed);
}*/
if(leashed instanceof Player) {
Player p = (Player)leashed;
if(p.isSneaking()) {
cooldown_new = ticks_new;
removeWorkaround();
}
}
}
else {
workaround.getWorld().dropItem(workaround.getLocation(), new ItemStack(Material.LEAD, 1));
removeWorkaround();
return false;
}
return true;
}
private Vector calc_dist() {
Location bat = workaround.getLocation(), player = leashed.getLocation();
return new Vector(bat.getX()-player.getX(), bat.getY()-player.getY(), bat.getZ()-player.getZ());
}
private Vector calc_velocity_to_LeashFake() {
Location bat = workaround.getLocation(), player = leashed.getLocation();
return new Vector( (bat.getX()-player.getX())*kxz, (bat.getY()-player.getY())*ky, (bat.getZ()-player.getZ())*kxz );
}
private Vector calc_velocity_to_LeashHolder() {
Location loc_holder = workaround.getLeashHolder().getLocation(), loc_leashed = leashed.getLocation();
double dx = loc_holder.getX()-loc_leashed.getX(), dy = loc_holder.getY()-loc_leashed.getY(), dz = loc_holder.getZ()-loc_leashed.getZ();
double distance = dx*dx + dy*dy + dz*dz;
Vector velocity = new Vector( dx, dy, dz); //to center
double distance_k;
if(distance < R_SQUARE) {
distance_k = 1 - distance / R_SQUARE;
velocity.multiply(new Vector(1, -1, 1));
} else
distance_k = distance / R_SQUARE - 1;
velocity.multiply(distance_k*pull_k);
Vector old_velocity = leashed.getVelocity();
old_velocity.add(new Vector(0, -0.01, 0));
System.out.printf(Utils.vectorToString(leashed.getVelocity())+" "+Utils.vectorToString(velocity));
boolean codirectional = Math.signum(old_velocity.getY()) == Math.signum(velocity.getY());
if(codirectional)
velocity.setY(velocity.getY()*0.33).add( old_velocity.multiply(E_friction).multiply(new Vector(1, 0.66, 1)) );
else
velocity.add(old_velocity.multiply(E_friction));
System.out.println("vec: "+Utils.vectorToString(velocity));
return velocity;
}
public boolean isCooldownless() {
return cooldown_new == 0 && cooldown_break == 0;
}
public void removeWorkaround() {
if(workaround.isLeashed() && (workaround.getLeashHolder() instanceof LeashHitch || workaround.getLeashHolder() instanceof CraftLeash))
workaround.getLeashHolder().remove();
workaround.remove();
}
}
| true |
92a49d9ad09d1edab024cff6113b8dc9a686953f
|
Java
|
muneeramalik/bill-java-integral-rules
|
/src/main/java/org/sonar/com/csc/java/MyJavaRulesDefinition.java
|
UTF-8
| 3,667 | 1.929688 | 2 |
[] |
no_license
|
/*
* Copyright (C) 2009-2014 SonarSource SA
* All rights reserved
* mailto:contact AT sonarsource DOT com
*/
package org.sonar.com.csc.java;
import java.io.IOException;
import java.net.URL;
import java.util.Locale;
import javax.annotation.Nullable;
import org.sonar.api.rule.RuleStatus;
import org.sonar.api.server.debt.DebtRemediationFunction;
import org.sonar.api.server.rule.RulesDefinition;
import org.sonar.plugins.java.Java;
import org.sonar.squidbridge.annotations.AnnotationBasedRulesDefinition;
import com.google.common.base.Charsets;
import com.google.common.io.Resources;
import com.google.gson.Gson;
/**
* @author mmalik25
*
*/
/**
* Declare rule metadata in server repository of rules.
* That allows to list the rules in the page "Rules".
*/
public class MyJavaRulesDefinition implements RulesDefinition {
public static final String REPOSITORY_KEY = "integral-java";
private final Gson gson = new Gson();
@Override
public void define(Context context) {
NewRepository repository = context
.createRepository(REPOSITORY_KEY, Java.KEY)
.setName("Integral");
new AnnotationBasedRulesDefinition(repository, Java.KEY)
.addRuleClasses(/* don't fail if no SQALE annotations */ false, RulesList.getChecks());
for (NewRule rule : repository.rules()) {
String metadataKey = rule.key();
// Setting internal key is essential for rule templates (see SONAR-6162), and it is not done by AnnotationBasedRulesDefinition from
// sslr-squid-bridge version 2.5.1:
rule.setInternalKey(metadataKey);
rule.setHtmlDescription(readRuleDefinitionResource(metadataKey + ".html"));
addMetadata(rule, metadataKey);
}
repository.done();
}
@Nullable
private static String readRuleDefinitionResource(String fileName) {
URL resource = MyJavaRulesDefinition.class.getResource("/org/sonar/l10n/java/rules/integral/" + fileName);
if (resource == null) {
return null;
}
try {
return Resources.toString(resource, Charsets.UTF_8);
} catch (IOException e) {
throw new IllegalStateException("Failed to read: " + resource, e);
}
}
private void addMetadata(NewRule rule, String metadataKey) {
String json = readRuleDefinitionResource(metadataKey + ".json");
if (json != null) {
RuleMetadata metadata = gson.fromJson(json, RuleMetadata.class);
rule.setSeverity(metadata.defaultSeverity.toUpperCase(Locale.US));
rule.setName(metadata.title);
rule.setTags(metadata.tags);
rule.setStatus(RuleStatus.valueOf(metadata.status.toUpperCase(Locale.US)));
if (metadata.remediation != null) {
// metadata.remediation is null for template rules
rule.setDebtRemediationFunction(metadata.remediation.remediationFunction(rule.debtRemediationFunctions()));
rule.setGapDescription(metadata.remediation.linearDesc);
}
}
}
private static class RuleMetadata {
String title;
String status;
@Nullable
Remediation remediation;
String[] tags;
String defaultSeverity;
}
private static class Remediation {
String func;
String constantCost;
String linearDesc;
String linearOffset;
String linearFactor;
private DebtRemediationFunction remediationFunction(DebtRemediationFunctions drf) {
if (func.startsWith("Constant")) {
return drf.constantPerIssue(constantCost.replace("mn", "min"));
}
if ("Linear".equals(func)) {
return drf.linear(linearFactor.replace("mn", "min"));
}
return drf.linearWithOffset(linearFactor.replace("mn", "min"), linearOffset.replace("mn", "min"));
}
}
}
| true |
6e542ffc8925309e2444a940da89cbfd0e281b0b
|
Java
|
dwikyrestu/kotlin-read-online-api
|
/app/src/main/java/com/dplamongan/devkotlin/User.java
|
UTF-8
| 215 | 2.0625 | 2 |
[] |
no_license
|
package com.dplamongan.devkotlin;
public class User {
String name;
String last_name;
public User(String name, String last_name) {
this.name = name;
this.last_name = last_name;
}
}
| true |
8b7f7d001cad7998a3109761dbd02c6ea6b64561
|
Java
|
happyflyer/leetcode-debug
|
/written_exam/src/main/java/org/example/exam/jd1/Solution1.java
|
UTF-8
| 2,434 | 3.765625 | 4 |
[] |
no_license
|
package org.example.exam.jd1;
import java.util.Scanner;
/**
* 小明搬进了一个新的小区里,对里面的环境和住户都比较陌生,
* 小明发现这个小区的房屋是一个网格型排列,所有房屋在一个网格状的地图上。
* 小区一共有n户人家,我们假设每户人家的位置表示为(x,y)。
* 小明觉得如果两家是邻居的话,他们的关系应该会更好一些。
* 现在我们定义当两户人家处在相同的任意一个对角线上的时候,则两户人家为邻居。
* 现在小明想要统计这样的邻居一共有多少对。
* 输入描述:
* 第一行1个整数n,0<n<=10^5,表示有n户人家。
* 接下来n行,第i行包含两个整数xi,yi,0<xi,yi<=1000,
* 表示第i户人家的位置为(xi,yi)。
* 输出描述:
* 一行一个整数,表示有多少对邻居。
* <p>
* 输入:
* 5
* 3 4
* 4 5
* 5 6
* 4 7
* 3 8
* 输出:
* 6
* 说明:
* 对于样例输入,以下几对人家均为邻居
* (3,4)与(4,5)
* (3,4)与(5,6)
* (4,5)与(5,6)
* (5,6)与(4,7)
* (5,6)与(3,8)
* (4,7)与(3,8)
* <p>
* AC:72%
*
* @author lifei
*/
public class Solution1 {
public static void getCount(int[][] arr) {
int n = arr.length;
int cnt = 0;
for (int i = 0; i < n - 1; i++) {
int xi = arr[i][0];
int yi = arr[i][1];
for (int j = i + 1; j < n; j++) {
int xj = arr[j][0];
int yj = arr[j][1];
if (yj - yi == xj - xi || xi + yi == xj + yj) {
System.out.println("(" + xi + ", " + yi + ") - (" + xj + ", " + yj + ")");
cnt++;
}
}
}
System.out.println(cnt);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[][] arr = new int[n][2];
int i = 0;
while (i < n) {
int[] xy = new int[2];
xy[0] = sc.nextInt();
xy[1] = sc.nextInt();
arr[i] = xy;
i++;
}
// int[][] arr = new int[][]{
// {3, 4},
// {4, 5},
// {5, 6},
// {4, 7},
// {3, 8}
// };
getCount(arr);
}
}
| true |
345df2298866329fc73fbdaa5cfba6ffa4f98953
|
Java
|
ZoomPoppy/Algorithm
|
/src/com/zz/homework/chapter_2/Example/Merge.java
|
UTF-8
| 1,027 | 3.578125 | 4 |
[] |
no_license
|
package com.zz.homework.chapter_2.Example;
/**
* Created by zz on 2016-08-16.
*/
public class Merge {
//自顶向上
public static void sort(Comparable[] a, int lo, int hi) {
if (hi <= lo) {
return;
}
int mid = (hi - lo) / 2 + lo;
sort(a, lo, mid);
sort(a, mid + 1, hi);
merge(a, lo, mid, hi);
}
//利用另外的一个数组来进行归并排序
public static void merge(Comparable[] a, int lo, int mid, int hi) {
Comparable[] aux = new Comparable[a.length];
int j = mid + 1;
int k = lo;
for (int i = 0; i < a.length; i++) {
aux[i] = a[i];
}
for (int i = 0; i <= hi; i++) {
if (k > mid) a[i] = aux[j++];
else if (j > hi) a[i] = aux[k++];
else if (less(aux[k], aux[j])) a[i] = aux[k++];
else a[i] = aux[j++];
}
}
public static boolean less(Comparable a, Comparable b) {
return a.compareTo(b) == -1;
}
}
| true |
461500acde21ccec2eb1c64e0637900e2fd5978f
|
Java
|
christinabannon/DSA
|
/midterm/Stock.java
|
UTF-8
| 873 | 3.03125 | 3 |
[] |
no_license
|
package midterm;
public class Stock
{
private int ghost, fire, ice;
private int transactions = 0;
public Stock (int ghost, int fire, int ice)
{
this.ghost = ghost;
this.fire = fire;
this.ice = ice;
}
public void give(int g, int f, int i) throws OOSException
{
if (ghost >=g && fire >= f && ice >= i)
{
ghost -= g;
fire -=f;
ice -= i;
transactions++;
}
}
public void accept(int g, int f, int i)
{
ghost += g;
fire +=f;
ice += i;
transactions++;
}
public int getTransactions()
{
return transactions;
}
public void setGhost(int ghost) {
this.ghost = ghost;
}
public void setFire(int fire) {
this.fire = fire;
}
public void setIce(int ice) {
this.ice = ice;
}
public int getGhost() {
return ghost;
}
public int getFire() {
return fire;
}
public int getIce() {
return ice;
}
}
| true |
4fc73e1700f4640979e76b9b062b733d3dadd456
|
Java
|
avh4/rectified
|
/src/main/java/net/avh4/tools/rectified/swing/EditPanelView.java
|
UTF-8
| 1,758 | 2.359375 | 2 |
[] |
no_license
|
package net.avh4.tools.rectified.swing;
import net.avh4.tools.rectified.EditPanel;
import net.avh4.tools.rectified.Observables;
import net.avh4.tools.rectified.model.ColorComponent;
import net.avh4.tools.rectified.model.Component;
import net.avh4.tools.rectified.uimodel.cqrs.SelectionQuery;
import net.avh4.framework.uilayer.mvc.Channel;
import net.avh4.framework.uilayer.mvc.Observer;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.*;
public class EditPanelView extends JPanel implements Observer {
private final Channel<SelectionQuery> selection;
private boolean changing;
private final JColorChooser chooser;
public EditPanelView(Observables observables, final EditPanel panel) {
chooser = new JColorChooser(Color.BLUE);
add(chooser);
chooser.getSelectionModel().addChangeListener(new ChangeListener() {
@Override public void stateChanged(ChangeEvent e) {
if (changing) return;
final int argb = chooser.getColor().getRGB();
panel.actions().setColor(argb);
}
});
selection = observables.selection();
observables.selection().watch(this);
}
@Override public void update() {
final Component component = selection.get().selectedComponent();
if (component instanceof ColorComponent) {
changing = true;
chooser.setColor(((ColorComponent) component).color());
changing = false;
chooser.setVisible(true);
} else {
chooser.setVisible(false);
}
}
@Override public Dimension getPreferredSize() {
return new Dimension(300, 300);
}
}
| true |
87358a56601d741a14d34dc37fadb419df47ffc1
|
Java
|
cycloon/jameica
|
/src/de/willuhn/jameica/gui/internal/action/RepositoryOpen.java
|
ISO-8859-1
| 1,656 | 2.109375 | 2 |
[] |
no_license
|
/**********************************************************************
*
* Copyright (c) by Olaf Willuhn
* All rights reserved
*
**********************************************************************/
package de.willuhn.jameica.gui.internal.action;
import java.net.URL;
import de.willuhn.jameica.gui.Action;
import de.willuhn.jameica.gui.GUI;
import de.willuhn.jameica.gui.internal.parts.RepositoryList;
import de.willuhn.jameica.gui.internal.views.RepositoryDetails;
import de.willuhn.jameica.services.RepositoryService;
import de.willuhn.jameica.system.Application;
import de.willuhn.logging.Logger;
import de.willuhn.util.ApplicationException;
/**
* Oeffnet die Liste der Plugins eines Repository.
*/
public class RepositoryOpen implements Action
{
/**
* @see de.willuhn.jameica.gui.Action#handleAction(java.lang.Object)
*/
public void handleAction(Object context) throws ApplicationException
{
if (context instanceof RepositoryList.UrlObject)
context = ((RepositoryList.UrlObject)context).getUrl();
if (context instanceof String)
{
try
{
context = new URL(context.toString());
}
catch (Exception e)
{
Logger.error("invalid url: " + context);
}
}
if (!(context instanceof URL))
{
try
{
context = new URL(RepositoryService.SYSTEM_REPOSITORY);
}
catch (Exception e)
{
Logger.error("invalid URL of system repository",e);
throw new ApplicationException(Application.getI18n().tr("Fehler beim ffnen des Repository"));
}
}
GUI.startView(RepositoryDetails.class,context);
}
}
| true |
54c6e02198a54da2ee8b5cd75160678709629527
|
Java
|
riaz035/Note-Manager
|
/1906/Simple-Notes-Manager-master/app/src/main/java/com/notes/iit/simplenotesmanager/NotesListActivity.java
|
UTF-8
| 4,338 | 2.203125 | 2 |
[] |
no_license
|
package com.notes.iit.simplenotesmanager;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.widget.CursorAdapter;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
public class NotesListActivity extends AppCompatActivity {
FloatingActionButton noteEditOpenButton;
ListView listView;
SqliteHelper sqliteHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notes_list);
initalizeViews();
noteEditOpenButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent=new Intent(NotesListActivity.this, ListEditActivity.class);
startActivity(intent);
}
});
sqliteHelper=new SqliteHelper(this);
Cursor cursor= sqliteHelper.retriveAllNotesCursor();
CursorAdapter cursorAdapter=new NotesListAdapter(this,cursor);
listView.setAdapter(cursorAdapter);
listView.setLongClickable(true);
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int position, long id) {
//sqliteHelper.getRorId(listView.getSelectedItemPosition());
SingleAlert(id);
Log.v("long clicked","pos: " + position);
return true;
}
});
}
private void initalizeViews() {
noteEditOpenButton=(FloatingActionButton)findViewById(R.id.fab);
listView=(ListView)findViewById(R.id.list);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater=getMenuInflater();
inflater.inflate(R.menu.list_menu,menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
case R.id.delete:
Alert();
break;
}
return super.onOptionsItemSelected(item);
}
public void Alert(){
AlertDialog.Builder builder1 = new AlertDialog.Builder(this);
builder1.setMessage("Are you sure you want to delete all notes?");
builder1.setCancelable(true);
builder1.setPositiveButton(
"Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
sqliteHelper.delete();
}
});
builder1.setNegativeButton(
"No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert11 = builder1.create();
alert11.show();
}
public void SingleAlert(final long position){
AlertDialog.Builder builder1 = new AlertDialog.Builder(this);
builder1.setMessage("Are you sure you want to delete this note?");
builder1.setCancelable(true);
builder1.setPositiveButton(
"Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
sqliteHelper.deleteInterestId(position);
}
});
builder1.setNegativeButton(
"No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert11 = builder1.create();
alert11.show();
}
}
| true |
7795f30397f5002a3054ec62e6276b4f27378ba7
|
Java
|
falconetpt/algoexpert
|
/src/main/java/mid/SortStack.java
|
UTF-8
| 310 | 3.046875 | 3 |
[] |
no_license
|
package mid;
import java.util.List;
import java.util.stream.Stream;
public class SortStack {
public List<Integer> sortStack(List<Integer> stack) {
final Stream<Integer> stream = stack.stream()
.sorted();
stream.peek(i -> stack.remove(0))
.forEach(stack::add);
return stack;
}
}
| true |
2a08a9b3bf22db92ec858e153ec680b4afa55ec2
|
Java
|
whatahellmw2/listaExerciciosPPS
|
/exercicio1/src/main/java/business/marcas/removeNomeDasMarcas.java
|
UTF-8
| 770 | 2.515625 | 3 |
[] |
no_license
|
package business.marcas;
import java.util.ArrayList;
/*
* 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.
*/
/**
*
* @author Thiago
*/
public class removeNomeDasMarcas {
ArrayList<IMarcasComerciais> marcas;
public removeNomeDasMarcas(){
this.marcas= new ArrayList<>();
}
public void addMarca(IMarcasComerciais marca){
this.marcas.add(marca);
}
public String removerMarcasDoTexto(String texto){
for(IMarcasComerciais m:marcas){
texto=UtilitarioString.getInstancia().substitui(texto, m.getNome(), m.getSimbolo());
}
return texto;
}
}
| true |
5b2f2c19d4d224e4fbac4781278a15c55b3df718
|
Java
|
942391815/test
|
/test/test-test/src/main/java/com/test/java/algorithm/find/test/One.java
|
UTF-8
| 726 | 3.25 | 3 |
[] |
no_license
|
package com.test.java.algorithm.find.test;
public class One {
public static void main(String[] args) {
int[][] num = num(4, 4);
System.out.println(num[4][1]);
System.out.println(num[4][2]);
System.out.println(num[4][3]);
}
public static int[][] num(int row, int column) {
int[][] arr = new int[row + 1][column + 1];
arr[0][0] = 1;
arr[1][0] = 1;
arr[1][1] = 1;
for (int i = 0; i < arr.length; i++) {
arr[i][0] = 1;
}
for (int i = 2; i <= row; i++) {
for (int j = 1; j <= column; j++) {
arr[i][j] = arr[i - 1][j] + arr[i - 1][j - 1];
}
}
return arr;
}
}
| true |
5984da4d8c5d69d7713e9136507a513c51415db7
|
Java
|
sabo99/EatIt-Android
|
/app/src/main/java/com/alvin/androideatit/SearchActivity.java
|
UTF-8
| 6,014 | 2.125 | 2 |
[] |
no_license
|
package com.alvin.androideatit;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.alvin.androideatit.Adapter.MySearchAdapter;
import com.alvin.androideatit.Common.Common;
import com.alvin.androideatit.Model.FoodModel;
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.mancj.materialsearchbar.MaterialSearchBar;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
public class SearchActivity extends AppCompatActivity {
@BindView(R.id.searchBar)
MaterialSearchBar searchBar;
@BindView(R.id.recycler_search)
RecyclerView recycler_search;
@BindView(R.id.search_null)
TextView search_null;
@BindView(R.id.tool_bar)
Toolbar toolbar;
Unbinder unbinder;
List<String> suggestList = new ArrayList<>();
List<FoodModel> localDataSource = new ArrayList<>();
MySearchAdapter adapter, searchAdapter;
List<FoodModel> tempList = null;
List<FoodModel> result = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
unbinder = ButterKnife.bind(this);
//initToolsBar();
recycler_search.setLayoutManager(new GridLayoutManager(this, 1));
localDataSource.clear();
loadAllFoods();
searchBar.setHint("Search your food");
searchBar.setCardViewElevation(10);
searchBar.addTextChangeListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
List<String> suggest = new ArrayList<>();
suggest.clear();
for (String search : suggestList) {
if (search.toLowerCase().contains(searchBar.getText().toLowerCase())) ;
suggest.add(search);
}
searchBar.setLastSuggestions(suggest);
}
@Override
public void afterTextChanged(Editable s) {
search_null.setVisibility(View.GONE);
}
});
searchBar.setOnSearchActionListener(new MaterialSearchBar.OnSearchActionListener() {
@Override
public void onSearchStateChanged(boolean enabled) {
if (!enabled)
recycler_search.setAdapter(adapter); // Restore all list of Food
}
@Override
public void onSearchConfirmed(CharSequence text) {
startSearchFoods(text);
}
@Override
public void onButtonClicked(int buttonCode) {
}
});
}
private void initToolsBar() {
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
//getSupportActionBar().setTitle("Search");
}
private void loadAllFoods() {
tempList = new ArrayList<>();
DatabaseReference foodRef = FirebaseDatabase.getInstance().getReference(Common.ALLFOODS_REF);
foodRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot ds:dataSnapshot.getChildren()){
FoodModel model;
model = ds.getValue(FoodModel.class);
tempList.add(model);
displayListFood(tempList);
//buildSuggestList(tempList);
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
private void buildSuggestList(List<FoodModel> tempList) {
for (FoodModel food:tempList)
suggestList.add(food.getName());
searchBar.setLastSuggestions(suggestList);
searchBar.setMaxSuggestionCount(4);
}
private void displayListFood(List<FoodModel> tempList) {
localDataSource = tempList;
adapter = new MySearchAdapter(this, tempList);
recycler_search.setAdapter(adapter);
}
private void startSearchFoods(CharSequence text) {
result = new ArrayList<>();
for (FoodModel foodModel:localDataSource)
if (foodModel.getName().toLowerCase().contains(text) || foodModel.getName().contains(text)){
result.add(foodModel);
search_null.setVisibility(View.GONE);
}
else
search_null.setVisibility(View.VISIBLE);
searchAdapter = new MySearchAdapter(this, result);
recycler_search.setAdapter(searchAdapter);
}
@Override
protected void onStop() {
adapter.clearCompositeDisposable();
DatabaseReference.goOffline(); // Clear Reference
suggestList.clear();
//searchBar.clearSuggestions();
localDataSource.clear();
tempList.clear();
finish();
super.onStop();
}
@Override
protected void onStart() {
super.onStart();
//searchBar.clearSuggestions();
suggestList.clear();
localDataSource.clear();
tempList.clear();
}
}
| true |
e8323d3ef686de1045eab48df1152068e7581bfa
|
Java
|
ztmark/springbootref
|
/src/main/java/io/ztmark/service/MyUserDetailsService.java
|
UTF-8
| 897 | 2.15625 | 2 |
[] |
no_license
|
package io.ztmark.service;
import io.ztmark.domain.User;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import java.util.Collections;
import java.util.List;
/**
* Author: Mark
* Date : 16/3/29
*/
public class MyUserDetailsService implements UserDetailsService {
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = new User("mark", 23);
List<SimpleGrantedAuthority> authorities = Collections.singletonList(new SimpleGrantedAuthority("USER"));
return new org.springframework.security.core.userdetails.User(user.getName(), "12345", authorities);
}
}
| true |
a745e2ddb5911602c99c5b4bef258d7dea3bc45a
|
Java
|
paulpell/miam
|
/src/org/paulpell/miam/net/NetMethods.java
|
UTF-8
| 4,382 | 2.671875 | 3 |
[] |
no_license
|
package org.paulpell.miam.net;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import org.paulpell.miam.geom.Pointd;
import org.paulpell.miam.net.TimestampedMessage.MsgTypes;
public class NetMethods
{
private static final int TIMESTAMP_START_POS = 0;
private static final int TYPE_START_POS = 4;
private static final int FROM_START_POS = 8;
private static final int LENGTH_START_POS = 12;
private static final int PAYLOAD_START_POS = 16;
public static void sendMessage(Socket socket, TimestampedMessage msg)
throws IOException
{
int length = 4 + // timestamp
4 + // msg type (int)
4 + // from (byte)
4 + // length (int)
msg.length_;
int type = TimestampedMessage.type2int_.get(msg.type_);
byte[] packet = new byte[length];
System.arraycopy(int2bytes(msg.timestamp_), 0, packet, TIMESTAMP_START_POS, 4);
System.arraycopy(int2bytes(type), 0, packet, TYPE_START_POS, 4);
System.arraycopy(int2bytes(msg.from_), 0, packet, FROM_START_POS, 4);
System.arraycopy(int2bytes(msg.length_), 0, packet, LENGTH_START_POS, 4);
if (null != msg.payload_)
System.arraycopy(msg.payload_, 0, packet, PAYLOAD_START_POS, msg.length_);
OutputStream outStream = socket.getOutputStream();
outStream.write(packet);
}
public static TimestampedMessage receiveMessage(final Socket socket)
throws IOException
{
InputStream inStream = socket.getInputStream();
int timestamp = readInt(inStream);
int type = readInt(inStream);
int from = readInt(inStream);
int length = readInt(inStream);
byte[] payload = null;
if (length > 0)
{
payload = new byte[length];
int n = inStream.read(payload, 0, length);
if (n != length)
throw new IOException("Could not read expected number of bytes for payload!");
}
MsgTypes t = TimestampedMessage.int2type_.get(type);
return new TimestampedMessage(timestamp, from, t, payload);
}
private static int readInt(InputStream inStream)
throws IOException
{
byte[] bytes = new byte[4];
int n = inStream.read(bytes, 0, 4);
if (n != 4)
throw new IOException("EOF");
return bytes2int(bytes);
}
protected static byte[] int2bytes(int i)
{
return new byte[]
{(byte)(i >> 24),
(byte)(i >> 16),
(byte)(i >> 8),
(byte)i};
}
protected static int bytes2int (byte[] b)
{
return ((0xFF & b[0]) << 24)
| ((0xFF & b[1]) << 16)
| ((0xFF & b[2]) << 8)
| ((0xFF & b[3]));
}
// from param is inclusive, to is exclusive
public static byte[] getSubBytes(byte[] bs, int from, int to)
{
byte[] bsout = new byte[to - from];
for (int i=from; i < to; ++i)
bsout[i - from] = bs[i];
return bsout;
}
// this function does:
// - toset[from] = toread[0]
// - toset[from+1] = toread[1]
// etc.
// from param is inclusive, to is exclusive
public static void setSubBytes(byte[] toread, byte[] toset, int from, int to)
{
for (int i=from; i < to; ++i)
toset[i] = toread[i - from];
}
protected static byte[] point2bytes(Pointd p)
{
String x = double2str(p.x_);
String y = double2str(p.y_);
byte[] bs = new byte[x.length() + y.length() + 2];
bs[0] = (byte)x.length();
setSubBytes(x.getBytes(), bs, 1, x.length() + 1);
bs[x.length() + 1] = (byte)y.length();
setSubBytes(y.getBytes(), bs, x.length() + 2, x.length() + y.length() + 2);
return bs;
}
// TODO: how to do str2point? Outside, we need the remaining string, if it is not the end of the float repr
protected static Pointd bytes2point(byte[] s)
{
int xlen = 0xFF & s[0];
int ylen = 0xFF & s[xlen + 1];
String sx = new String(getSubBytes(s, 1, xlen + 1));
String sy = new String(getSubBytes(s, xlen + 2, xlen + 2 + ylen));
double x = str2double(sx);
double y = str2double(sy);
return new Pointd(x, y);
}
protected static String double2str(double d)
{
return ""+Double.doubleToRawLongBits(d);
}
protected static double str2double(String s)
{
return Double.longBitsToDouble(new Long(s));
}
public static byte[] parseIP(String s)
{
String[] ss = s.split("\\.");
if (ss.length != 4)
return null;
byte[] bs = new byte[4];
for (int i=0; i<4; ++i)
{
try
{
int b = Integer.parseInt(ss[i]);
bs[i] = (byte)b;
} catch (NumberFormatException e)
{
return null;
}
}
return bs;
}
}
| true |
f055a08ecdf96277f3bbfdedceb13fd03d8f76a6
|
Java
|
Artmozaec/BookDict
|
/src/programdirection/rms/onestoremanyrecords/OneStoryManyRecords.java
|
WINDOWS-1251
| 3,462 | 3.09375 | 3 |
[] |
no_license
|
package onestoremanyrecords;
import javax.microedition.rms.*;
import java.util.Vector;
public class OneStoryManyRecords{
//
public String recordStoreName;
//
private boolean errorStore;
public OneStoryManyRecords(String inStoreName){
recordStoreName = inStoreName;
errorStore = false;
}
public boolean isOk(){
return !errorStore;
}
private boolean existRecordName(String[] stores){
for(int ch=0; ch<stores.length; ch++){
//System.out.println("store = "+stores[ch]);
if (recordStoreName.equals(stores[ch])) return true;
}
return false;
}
// -
private boolean recordStoreCheck(){
String[] stores;
//
stores = RecordStore.listRecordStores();
// !
if (stores == null) return false;
// ?
if (!existRecordName(stores)) return false;
return true;
}
public Vector restoreData(){
Vector storeRecords = new Vector();
//, - ?
if (!recordStoreCheck()){
//System.out.println(" ");
errorStore = true;
return storeRecords;
}
StoreRecord currentRecord;
RecordStore recordStore;
try{
//
recordStore = RecordStore.openRecordStore(recordStoreName, true);
//System.out.println("otkrili hranilishe recordStore = "+recordStore);
//
//System.out.println(" = "+recordStore.getNumRecords());
for (int ch=1; ch<=recordStore.getNumRecords(); ch++){
currentRecord = new StoreRecord(recordStore.getRecord(ch));
storeRecords.addElement(currentRecord);
//System.out.println("$$$$$$$$$$$$$$$$restoreData()$$$$$$$$$$$$$$$$$="+ch);
}
//
recordStore.closeRecordStore();
//System.out.println("zakryli hranilishe ");
} catch (RecordStoreException rse){
errorStore = true;
}
return storeRecords;
}
private void deleteStore(){
try{
//
RecordStore.deleteRecordStore(recordStoreName);
} catch( RecordStoreNotFoundException e ){
//
//System.out.println("deleteStore() >>>> netHranilisha");
} catch( RecordStoreException e ){
//
//System.out.println("deleteStore() >>>> hranilishe otkrito");
}
}
public void saveData(Vector records){
RecordStore recordStore;
//
deleteStore();
try{
//
recordStore = RecordStore.openRecordStore(recordStoreName, true);
StoreRecord currentRecord;
for (int ch=0; ch<records.size(); ch++){
currentRecord = (StoreRecord)records.elementAt(ch);
byte[] rec = currentRecord.getData();
recordStore.addRecord(rec, 0, rec.length);
//System.out.println("$$$$$$$$$$$$$$$$saveData()$$$$$$$$$$$$$$$$$="+ch);
}
//
recordStore.closeRecordStore();
} catch (RecordStoreException rse){
errorStore = true;
}
}
}
| true |
e6651ccf25c8a8c8d0a58dd1dae3ecae85f81365
|
Java
|
SharathTSK/week1.assginment
|
/arrays/SecondLargestValue.java
|
UTF-8
| 273 | 2.9375 | 3 |
[] |
no_license
|
package assignment.week1.day2.arrays;
import java.util.Arrays;
public class SecondLargestValue {
public static void main(String[] args) {
int data[]= {3,2,11,4,6,7};
Arrays.sort(data);
System.out.println(data[data.length-2]);
}
}
| true |
3c0ac6988c8857d5c33d5a01ec3e6178d0d41147
|
Java
|
DimaShum/Test-tasks-for-GP-Solution.-Stage-2
|
/2-Calc/src/Main.java
|
UTF-8
| 800 | 3.1875 | 3 |
[] |
no_license
|
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws Exception {
Calc calc = new Calc();
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
try {
System.out.println(calc.estimate(reader.readLine()));
//System.out.println(calc.estimate("(2+2)*2"));
//System.out.println(calc.estimate("(4+3)*2^-2"));
//System.out.println(calc.estimate("5+1/0"));
//System.out.println(calc.estimate("(17^4+5*974^3 3+2.24*4.75)^0"));
//System.out.println(calc.estimate("(17 ^ 4 + 5 * 974 ^ 33 + 2,24 * 4,75) ^ 0"));
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
| true |
1fe776a9075786b719b45b2d91bc7cf47425b983
|
Java
|
lzbCoder/Digibird_Study
|
/java-spring--demo/src/main/java/com/spring/test/SpringIocDemo.java
|
UTF-8
| 1,018 | 2.875 | 3 |
[] |
no_license
|
package com.spring.test;
import com.spring.domain.Student;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* 该类用于对{@code spring}中{@code IoC}思想进行演示
*
* @author lzb
* @version 1.0
*/
public class SpringIocDemo {
/** 定义日志记录器,用于打印日志 */
private static final Logger LOGGER = LoggerFactory.getLogger(SpringIocDemo.class);
/**
* 该方法获取{@code BeanFactory}对象,使用该工厂对象读取
* {@code ApplicationContext.xml}文件,通过获取{@code bean}的
* {@code id},来创建该{@code bean}的对象。
*/
public static void main(String[] args) {
BeanFactory factory = new ClassPathXmlApplicationContext("ApplicationContext*.xml");
Student student = (Student) factory.getBean("student");
LOGGER.info("Student对象为" + student);
}
}
| true |
71025f45c49fea26274aa43c43f6da08d7dab7c9
|
Java
|
hivinau/RSSReader
|
/app/src/main/java/fr/unicaen/info/users/hivinaugraffe/apps/android/rssreader/globals/DatabaseConstant.java
|
UTF-8
| 733 | 1.789063 | 2 |
[] |
no_license
|
package fr.unicaen.info.users.hivinaugraffe.apps.android.rssreader.globals;
public class DatabaseConstant {
public static final String TABLE_CHANNELS = "channels";
public static final String TABLE_ITEMS = "items";
public static final String TABLE_COLUMN_CHANNEL = "channel";
public static final String TABLE_COLUMN_TITLE = "title";
public static final String TABLE_COLUMN_DESCRIPTION = "description";
public static final String TABLE_COLUMN_DATE = "date";
public static final String TABLE_COLUMN_LINK = "link";
public static final String TABLE_COLUMN_COPYRIGHT = "copyright";
public static final String TABLE_COLUMN_GUID = "guid";
public static final String TABLE_COLUMN_IMAGE = "image";
}
| true |
edf2916bffebc94439febc2f027904432e4b49e4
|
Java
|
loan-app/loanshop-android
|
/provider/src/main/java/com/ailiangbao/provider/bll/inject/prefs/ProviderApplicationPrefsModule.java
|
UTF-8
| 864 | 1.90625 | 2 |
[] |
no_license
|
package com.ailiangbao.provider.bll.inject.prefs;
import android.content.Context;
import com.ailiangbao.provider.bll.inject.scope.Provider_Scope_Application;
import com.ailiangbao.provider.dal.prefs.PrefsConstants;
import com.ailiangbao.provider.dal.prefs.PrefsHelper;
import javax.inject.Named;
import dagger.Module;
import dagger.Provides;
@Module
public class ProviderApplicationPrefsModule {
@Provides
@Named(PrefsConstants.PREFS_GLOBAL)
@Provider_Scope_Application
public PrefsHelper providerGlobalPrefsHelper() {
return new PrefsHelper("h_global_prefs", getModeCompat());
}
private static int getModeCompat() {
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
// return Context.MODE_MULTI_PROCESS;
// }
return Context.MODE_PRIVATE;
}
}
| true |
30029ec7799f268f631b4a99b0767cb1611b6171
|
Java
|
KilianKrause/coderadar
|
/coderadar-core/src/test/java/io/reflectoring/coderadar/projectadministration/module/GetModuleServiceTest.java
|
UTF-8
| 1,329 | 2.203125 | 2 |
[
"MIT"
] |
permissive
|
package io.reflectoring.coderadar.projectadministration.module;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
import io.reflectoring.coderadar.projectadministration.domain.Module;
import io.reflectoring.coderadar.projectadministration.port.driven.module.GetModulePort;
import io.reflectoring.coderadar.projectadministration.service.module.GetModuleService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
@ExtendWith(MockitoExtension.class)
class GetModuleServiceTest {
@Mock private GetModulePort getModulePortMock;
private GetModuleService testSubject;
@BeforeEach
void setUp() {
this.testSubject = new GetModuleService(getModulePortMock);
}
@Test
void returnsGetModuleResponseForModule() {
// given
long moduleId = 1L;
String path = "module-path";
Module module = new Module().setId(moduleId).setPath(path);
Module expectedResponse = new Module(moduleId, path);
when(getModulePortMock.get(moduleId)).thenReturn(module);
// when
Module actualResponse = testSubject.get(moduleId);
// then
assertThat(actualResponse).isEqualTo(expectedResponse);
}
}
| true |
c100ae5296de6c8c1c92bf00145515d1cf07667f
|
Java
|
taink3107/capstonev6
|
/src/main/java/com/cmms/demo/endpoint/RoleController.java
|
UTF-8
| 3,212 | 2.125 | 2 |
[] |
no_license
|
package com.cmms.demo.endpoint;
import com.cmms.demo.domain.MyMessage;
import com.cmms.demo.domain.RolePOJO;
import com.cmms.demo.dto.RoleDTO;
import com.cmms.demo.service.RoleService;
import com.cmms.demo.serviceImpl.RoleServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import javax.management.relation.Role;
import java.util.List;
import java.util.stream.Collectors;
@RestController
@RequestMapping(value = "/api/v1/role",name = "Quản lý phân quyền")
@CrossOrigin("*")
public class RoleController {
@Autowired
RoleService roleService;
@GetMapping(value = "/getOne/{id}", name = "Xem thông tin 1 quyền")
@PreAuthorize("{@appAuthorizer.authorize(authentication, '/getOne','GET', this)}")
public ResponseEntity<RoleDTO> getOneRoleById(@PathVariable Integer id) {
RolePOJO role = roleService.getOneById(id);
return new ResponseEntity<>(RoleDTO.from(role), HttpStatus.OK);
}
@GetMapping(name = "Xem tất cả quyền")
@PreAuthorize("{@appAuthorizer.authorize(authentication, '','GET', this)}")
public ResponseEntity<List<RoleDTO>> getAllRole() {
List<RolePOJO> role = roleService.findAll();
return new ResponseEntity<>(role.stream().map(RoleDTO::from).collect(Collectors.toList()), HttpStatus.OK);
}
@GetMapping(value = "/roles-by-user")
public ResponseEntity<List<RoleDTO>> getAllRoleByUser() {
List<RolePOJO> role = roleService.roleByUser();
return new ResponseEntity<>(role.stream().map(RoleDTO::from).collect(Collectors.toList()), HttpStatus.OK);
}
@PostMapping(value = "/update", name = "Cập nhật quyền")
@PreAuthorize("{@appAuthorizer.authorize(authentication, '/update','POST', this)}")
public ResponseEntity<RoleDTO> updateInfoRole(@RequestBody RoleDTO dto) {
RolePOJO role = roleService.update(dto);
return new ResponseEntity<>(RoleDTO.from(role), HttpStatus.OK);
}
@PostMapping(value = "/create", name = "Tạo quyền truy cập mới")
@PreAuthorize("{@appAuthorizer.authorize(authentication, '/create','POST', this)}")
public ResponseEntity<RoleDTO> createRole(@RequestBody RoleDTO dto) {
RolePOJO role = roleService.create(dto);
return new ResponseEntity<>(RoleDTO.from(role), HttpStatus.OK);
}
@PostMapping(value = "/delete/{role}", name = "Xóa quyền")
@PreAuthorize("{@appAuthorizer.authorize(authentication, '/delete','POST', this)}")
public ResponseEntity<MyMessage> deleteRole(@PathVariable Integer role) {
MyMessage myMessage = new MyMessage();
if (role != null) {
try {
roleService.delete(role);
myMessage.setMessage("Xóa thành công");
} catch (Exception e) {
myMessage.setMessage(e.getMessage());
return new ResponseEntity<>(myMessage, HttpStatus.OK);
}
}
return new ResponseEntity<>(myMessage, HttpStatus.OK);
}
}
| true |
310687b7ae588bec471ed458735d4ef3cd9eaf04
|
Java
|
pedroaleao/codigo-sem-barreiras
|
/curso-java-resolucoes/src/parte_02/exercicio_02/Main.java
|
UTF-8
| 3,206 | 3.65625 | 4 |
[] |
no_license
|
package parte_02.exercicio_02;
import java.util.ArrayList;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] diasDaSemanas = {1, 2, 3, 4, 5, 6, 7};
// diasDaSemanas[6] = 999; // Trocando o valor do array manualmente na posição 6
// Iterar sobre arrays
System.out.println("Enhanced for ou for each");
for (int dia : diasDaSemanas) {
System.out.println(dia);
}
System.out.println("For padrão");
for (int i = 0; i < diasDaSemanas.length; i++) {
System.out.println(diasDaSemanas[i]);
}
// Nao precisa se preocupar com isso agora...
System.out.println("For com lambda");
Arrays.stream(diasDaSemanas)
//.filter(diaSemana -> diaSemana % 2 == 0) // Se quiser filtrar somente pares, remova os comentários desta linha
.forEach(System.out::println);
System.out.println("-----------------------------------");
int[] arrayDeInt = {1, 2, 3, 4, 5};
for (int i : arrayDeInt) {
i = 5;
System.out.println(i);
}
for (int i : arrayDeInt) {
System.out.println(i);
}
String[] arrayDeString = {"asd", "qwert"};
System.out.println("------------------------");
for (String s : arrayDeString) {
s = "ttt";
System.out.println(s);
}
for (String s : arrayDeString) {
System.out.println(s);
}
for (int i = 0; i < arrayDeInt.length; i++) {
arrayDeInt[i] = 999;
System.out.println(arrayDeInt[i]);
}
for (int i = 0; i < arrayDeInt.length; i++) {
System.out.println(arrayDeInt[i]);
}
System.out.println("Imprimir array sem for");
System.out.println(Arrays.toString(arrayDeInt));
System.out.println(" ---------------- ");
System.out.println("Alterando o conteúdo de um objeto com o loop foreach");
Teste[] arrayDeTeste = {new Teste(1), new Teste(2), new Teste(3)};
for (Teste t : arrayDeTeste) {
// t.teste = 9; // Alteração do valor da referencia do objeto
t = new Teste(9); // Alterando a cópia de t do escopo local do for, isso não afetou o array original
System.out.println(t);
}
for (Teste t : arrayDeTeste) {
System.out.println(t);
}
System.out.println("Array List");
var minhaListaDeInteiros = new ArrayList<Integer>();
for (int i = 0; i < 100_000; i++) {
minhaListaDeInteiros.add(i);
}
minhaListaDeInteiros.forEach(System.out::println);
for (Integer item : minhaListaDeInteiros) {
System.out.println(item);
}
// Wrappers
// int = Integer
// char = Character
// long = Long
// float = Float
// byte = Byte
// double = Double
// short = Short
// boolean = Boolean
ArrayList<Object> cabeQualquerCoisa;
var variavelSoTipoStringInferidaAutomaticamente = "";
}
}
| true |
d0b9da2f1873b9eb9cdd83b0c38815b904358c79
|
Java
|
maskwang520/Jplus
|
/Jplus/src/com/jplus/controller/IndexMapperController.java
|
UTF-8
| 7,556 | 2.3125 | 2 |
[] |
no_license
|
package com.jplus.controller;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.ParseException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.jplus.model.AccessSum;
import com.jplus.model.BBSRecommend;
import com.jplus.model.FriendLink;
import com.jplus.model.NavUrl;
import com.jplus.service.AccessSumService;
import com.jplus.service.BBSRecommendService;
import com.jplus.service.FriendLinkService;
import com.jplus.service.NavUrlService;
import com.jplus.service.SystemManageService;
import com.jplus.util.DateUtil;
/**
* @title 系统初始化 动作控制层
*
* @author Chitry
* @time 2015.10.30
*
* @description 需要进行初始化的session域对象数据
* 1.访问量
* 2.友情链接
* 3.合作案例
* 4.合作单位
*/
@Controller
public class IndexMapperController {
private AccessSumService accessSumService;//访问量信息
private FriendLinkService friendLinkService;//友情链接信息
private NavUrlService navUrlService;//合作案例信息
private BBSRecommendService bbsRecommendService;//合作单位信息
private SystemManageService systemManageService;
public SystemManageService getSystemManageService() {
return systemManageService;
}
@Autowired
public void setSystemManageService(SystemManageService systemManageService) {
this.systemManageService = systemManageService;
}
public AccessSumService getAccessSumService() {
return accessSumService;
}
public FriendLinkService getFriendLinkService() {
return friendLinkService;
}
public NavUrlService getNavUrlService() {
return navUrlService;
}
public BBSRecommendService getBBSRecommendService() {
return bbsRecommendService;
}
@Autowired
public void setAccessSumService(AccessSumService accessSumService) {
this.accessSumService = accessSumService;
}
@Autowired
public void setFriendLinkService(FriendLinkService friendLinkService) {
this.friendLinkService = friendLinkService;
}
@Autowired
public void setNavUrlService(NavUrlService navUrlService) {
this.navUrlService = navUrlService;
}
@Autowired
public void setBBSRecommendService(BBSRecommendService bbsRecommendService) {
this.bbsRecommendService = bbsRecommendService;
}
@SuppressWarnings("finally")
@RequestMapping("JplusIndex")
public String index(HttpServletRequest request){
try {
HttpSession session = request.getSession();
/**
* 1.访问量更新数据初始化
*/
List<AccessSum> aslist = new ArrayList<AccessSum>();
aslist = accessSumService.getAll();
//访问量更新
String now = DateUtil.getnow();
String old = null;
long tdday = 0;
int nowacces = 0;
int lastyear = 0;
int lastmonth = 0;
int lastweek = 0;
int yest = 0;
int yyest = 0;
AccessSum asses = new AccessSum();
for (int od = 0; od < aslist.size(); od++) {
asses = aslist.get(od);
old = DateUtil.cknow(asses.getAsMaxdate());
try {
tdday = Long.parseLong(DateUtil.getTimeDifferent(now, old, 1));
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
// 年浏览量初始化
switch (asses.getId()) {
case 1:// 历史总浏览量
nowacces = asses.getAsSum()+1;// 记录本次是历史上第几次访问
asses.setAsSum(nowacces);
asses.setAsMax(asses.getAsSum());//记录历史峰值
break;
case 2:// 今年总浏览量
if (tdday >= 365) {lastyear=asses.getAsSum();asses.setAsSum(0);asses.setAsMaxdate(DateUtil.kcnow((now)));}
asses.setAsSum(asses.getAsSum() + 1);
asses.setAsMax(asses.getAsSum());//记录历史峰值
break;
case 3:// 本月总流量
if (tdday >= 30) {lastmonth=asses.getAsSum();asses.setAsSum(0);asses.setAsMaxdate(DateUtil.kcnow((now)));}
asses.setAsSum(asses.getAsSum() + 1);
asses.setAsMax(asses.getAsSum());//记录历史峰值
break;
case 4:// 本周总浏览量
if (tdday >= 7) {lastweek=asses.getAsSum();asses.setAsSum(0);asses.setAsMaxdate(DateUtil.kcnow((now)));}
asses.setAsSum(asses.getAsSum() + 1);
asses.setAsMax(asses.getAsSum());//记录历史峰值
break;
case 5:// 今天浏览量
if (tdday >= 1) {yest=asses.getAsSum();asses.setAsSum(0);asses.setAsMaxdate(DateUtil.kcnow((now)));}
asses.setAsSum(asses.getAsSum() + 1);
asses.setAsMax(asses.getAsSum());//记录历史峰值
break;
case 6:// 去年浏览量
if (lastyear!=0) {asses.setAsSum(lastyear);asses.setAsMax(asses.getAsSum());asses.setAsMaxdate(DateUtil.kcnow((now)));}break;
case 7:// 上月浏览量
if (lastmonth!=0) {asses.setAsSum(lastmonth);asses.setAsMax(asses.getAsSum());asses.setAsMaxdate(DateUtil.kcnow((now)));}break;
case 8:// 上周浏览量
if (lastweek!=0) {asses.setAsSum(lastweek);asses.setAsMax(asses.getAsSum());asses.setAsMaxdate(DateUtil.kcnow((now)));}break;
case 9:// 昨天浏览量
if (yest!=0) {yyest=asses.getAsSum();asses.setAsSum(yest);asses.setAsMax(asses.getAsSum());asses.setAsMaxdate(DateUtil.kcnow((now)));}break;
case 10://前天浏览量
if (yyest!=0) {asses.setAsSum(yyest);asses.setAsMax(asses.getAsSum());asses.setAsMaxdate(DateUtil.kcnow((now)));}break;
default:
break;
}
try {
accessSumService.update(asses);
} catch (Exception e) {
e.printStackTrace();
}
}
session.setAttribute("nowaccess", nowacces);
/**
* 2.友情链接数据初始化
*/
List<FriendLink> friendlinklist = new ArrayList<FriendLink>();
friendlinklist = systemManageService.findFriendlink();
session.setAttribute("fllist", friendlinklist);
/**
* 3.合作案例数据初始化
*/
//1.合作案例-作品
List<NavUrl> allist = new ArrayList<NavUrl>();
List<NavUrl> navlist = new ArrayList<NavUrl>();
allist = navUrlService.getAll();
for(NavUrl n:allist){
NavUrl nav = new NavUrl();
String []str1=n.getnUrl().split("@");
nav.setNpic(str1[0]);//图片路径
nav.setnUrl(str1[1]);//链接地址
nav.setnName(n.getnName());//作品名称
nav.setnTitle(n.getnTitle());//作品小标题
nav.setnDescriptions(n.getnDescriptions());//作品描述
navlist.add(nav);
}
session.setAttribute("examplelist", navlist);
/**
* 4.合作单位数据初始化
*/
List<BBSRecommend> bbsrecommendlist = new ArrayList<BBSRecommend>();
List<BBSRecommend> bbsrelist = new ArrayList<BBSRecommend>();
bbsrecommendlist = bbsRecommendService.getAll();
for(BBSRecommend n:bbsrecommendlist){
String []str1=n.getBrPurl().split("@");
BBSRecommend br = new BBSRecommend();
br.setBrPurl(str1[0]);//图片1路径
br.setBrPurl2(str1[1]);//图片1路径
br.setBrUrl(n.getBrUrl());//链接地址
br.setBrName(n.getBrName());//单位名称
br.setBrTitle(n.getBrTitle());//单位标题
br.setBrDescriptions(n.getBrDescriptions());//单位描述
bbsrelist.add(br);
}
session.setAttribute("bbslist", bbsrelist);
/**
* 汇总转发
*/
//return "index";//listAll页面
} catch (Exception e) {
e.printStackTrace();
request.setAttribute("InfoMessage", "添加信息失败!具体异常信息:" + e.getMessage());
} finally {
return "index";
}
}
}
| true |
957b59d63b6b6e6a2b74e3600ae29c850ec967ea
|
Java
|
IRH01/smart_statistics
|
/src/main/java/com/hhly/smartdata/service/daily/DailyLoginStatisticsService.java
|
UTF-8
| 4,692 | 2.171875 | 2 |
[] |
no_license
|
package com.hhly.smartdata.service.daily;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.hhly.smartdata.dto.enume.SourceTypeEnum;
import com.hhly.smartdata.mapper.member.SystemConfigMapper;
import com.hhly.smartdata.mapper.smartdata.DailyLoginReportMapper;
import com.hhly.smartdata.model.smartdata.DailyLoginReport;
import com.hhly.smartdata.util.DateUtil;
import com.hhly.smartdata.util.JsonUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Created by Iritchie.ren on 2017/10/17.
*/
@Service
public class DailyLoginStatisticsService{
@Autowired
private DailyLoginReportMapper dailyLoginReportMapper;
@Autowired
private SystemConfigMapper systemConfigMapper;
public Map<String, Object> getLastTotalRegister() throws Exception{
Date now = new Date();
String yesterdayStr = DateUtil.getYesterdayStr(now);
return this.dailyLoginReportMapper.selectByDaily(yesterdayStr);
}
/**
* 根据查询条件统计登录来源
*
* @param monthOfYear
* @return
* @throws Exception
*/
public Map<String, List> search(String monthOfYear) throws Exception{
if(StringUtils.isEmpty(monthOfYear)){
monthOfYear = DateUtil.date2String(new Date(), "yyyy-MM-dd");
}
String monthFirstDayStr = DateUtil.getMonthFirstDayStr(monthOfYear);
String monthEndDayStr = DateUtil.getMonthEndDayStr(monthOfYear);
//平台信息
String configValue = systemConfigMapper.getConfigValueByKey("hhly:playOne:systemConfig:common:platformCode");
Map<String, String> platformMap = JsonUtil.jsonStr2Map(configValue);
//获取条件范围的所有日期
List<DailyLoginReport> dailyLoginReportList = dailyLoginReportMapper.searchByTime(monthFirstDayStr, monthEndDayStr);
//获取当年所有日期
Set<String> statisticsDaySet = Sets.newLinkedHashSet();
for(DailyLoginReport item : dailyLoginReportList){
if(!statisticsDaySet.contains(item.getStatisticsDay())){
statisticsDaySet.add(item.getStatisticsDay());
}
}
List<Map<String, Object>> list = Lists.newArrayList();
//每行数据拼接,同一个时间为一行
for(String dateStr : statisticsDaySet){
List<Object> dataList = Lists.newArrayList();
for(SourceTypeEnum sourceTypeEnum : SourceTypeEnum.values()){
//综合
for(DailyLoginReport dailyLoginReport : dailyLoginReportList){
if(dailyLoginReport.getStatisticsDay().equals(dateStr) && dailyLoginReport.getSourceType().equals(sourceTypeEnum.getCode()) && dailyLoginReport.getPlatformCode().equals("zong_he")){
dataList.add(dailyLoginReport.getLoginPopulation());
dataList.add(dailyLoginReport.getPlayPopulation());
break;
}
}
//各个平台的
for(String platformCode : platformMap.keySet()){
for(DailyLoginReport dailyLoginReport : dailyLoginReportList){
if(dailyLoginReport.getStatisticsDay().equals(dateStr)
&& dailyLoginReport.getSourceType().equals(sourceTypeEnum.getCode())
&& dailyLoginReport.getPlatformCode().equals(platformCode)){
dataList.add(dailyLoginReport.getPlayPopulation());
break;
}
}
}
}
Map<String, Object> trData = Maps.newHashMap();
trData.put("time", dateStr);
trData.put("data", dataList);
list.add(trData);
}
//title拼接
List<String> title = Lists.newArrayList();
for(SourceTypeEnum sourceTypeEnum : SourceTypeEnum.values()){
title.add(sourceTypeEnum.getDesc() + "登录人数");
title.add(sourceTypeEnum.getDesc() + "玩游戏人数");
for(String platformCode : platformMap.keySet()){
title.add(sourceTypeEnum.getDesc() + "-" + platformMap.get(platformCode));
}
}
Map<String, List> resultMap = Maps.newHashMap();
resultMap.put("title", title);
resultMap.put("list", list);
return resultMap;
}
}
| true |
36c3661a73e558db48a2c25a60729955c61089a4
|
Java
|
cdisi/cw
|
/src/main/java/com/zk/cw/yonga_seti/YongaSeti.java
|
UTF-8
| 547 | 2.34375 | 2 |
[] |
no_license
|
package com.zk.cw.yonga_seti;
public class YongaSeti {
private Integer id;
private String ad;
public YongaSeti() {
}
public YongaSeti(Integer id, String ad) {
this.id = id;
this.ad = ad;
}
public void setId(Integer id) {
this.id=id;
}
public Integer getId() {
return this.id;
}
public void setAd(String ad) {
this.ad=ad;
}
public String getAd() {
return this.ad;
}
@Override
public String toString()
{
return ad;
}
}
| true |
bff176ada31845b9db41932ae495cd5825b815ff
|
Java
|
vamseems/Android-Nanodegree
|
/Project 2/PopMov/app/src/main/java/com/vchamakura/popmov/MovieDetailItem.java
|
UTF-8
| 1,043 | 2.125 | 2 |
[] |
no_license
|
package com.vchamakura.popmov;
import org.json.JSONObject;
import java.util.ArrayList;
/**
* Created by vchamakura on 04/03/16 at 1:07 AM.
* Copyrights reserved to Vamsee Chamakura
*/
public class MovieDetailItem {
final String title;
final String movieID;
final String posterURL;
final String backDrop;
final String plot;
final String voteAverage;
final String releaseDate;
final ArrayList<JSONObject> videos;
final ArrayList<JSONObject> reviews;
public MovieDetailItem(String title, String movieID, String posterURL, String backDrop, String plot,
String voteAverage, String releaseDate, ArrayList<JSONObject> videos,
ArrayList<JSONObject> reviews) {
this.title = title;
this.movieID = movieID;
this.posterURL = posterURL;
this.backDrop = backDrop;
this.plot = plot;
this.voteAverage = voteAverage;
this.releaseDate = releaseDate;
this.videos = videos;
this.reviews = reviews;
}
}
| true |
ce101f3cf96b46169b57e27b3e9b80a45a61b133
|
Java
|
exbergamot/SnakeQLearning
|
/src/main/java/snake/swing/tabs/DataPanel.java
|
UTF-8
| 4,744 | 2.5625 | 3 |
[] |
no_license
|
package snake.swing.tabs;
import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class DataPanel extends JPanel{
private static Map<String, List<String>> fieldMap = new HashMap<>();
public static final String LEARNING_CONFIGURATION = "Learning configuration";
public static final String ALGORITHM = "Algorithm";
public static final String RL_CONFIGURATION = "RL configuration";
public static final String LAYER_TYPE = "Layer type";
public static final String LAYER_CONFIGURATION = "Layer configuration";
public static final String NETWORK_STRUCTURE = "Network structure";
public static final String NETWORK_STRUCTURE_TO_LAYERS = "Network structure to layers";
static{
List<String> learningConfigurationList = new ArrayList<>();
learningConfigurationList.add("id");
learningConfigurationList.add("max epoch step");
learningConfigurationList.add("max step");
learningConfigurationList.add("experience replay max size");
learningConfigurationList.add("batch size");
learningConfigurationList.add("target update frequency");
learningConfigurationList.add("update start");
learningConfigurationList.add("reward factor");
learningConfigurationList.add("gamma");
learningConfigurationList.add("error clamp");
learningConfigurationList.add("min epsilon");
learningConfigurationList.add("epsilon anneal step");
learningConfigurationList.add("max threads");
learningConfigurationList.add("regularization");
learningConfigurationList.add("learning rate");
fieldMap.put(LEARNING_CONFIGURATION, learningConfigurationList);
List<String> algorithm = new ArrayList<>();
algorithm.add("id");
algorithm.add("name");
fieldMap.put(ALGORITHM, algorithm);
List<String> rlConfiguration = new ArrayList<>();
rlConfiguration.add("id");
rlConfiguration.add("algorithm");
rlConfiguration.add("learning configuration");
rlConfiguration.add("network structure");
fieldMap.put(RL_CONFIGURATION, rlConfiguration);
List<String> layerType = new ArrayList<>();
layerType.add("id");
layerType.add("name");
fieldMap.put(LAYER_TYPE, layerType);
List<String> layerConfiguration = new ArrayList<>();
layerConfiguration.add("id");
layerConfiguration.add("layer type");
layerConfiguration.add("kernel size");
layerConfiguration.add("stride");
layerConfiguration.add("padding");
layerConfiguration.add("output count");
fieldMap.put(LAYER_CONFIGURATION, layerConfiguration);
List<String> networkStructureLayerConfig = new ArrayList<>();
networkStructureLayerConfig.add("network structure id");
networkStructureLayerConfig.add("layer configuration id");
networkStructureLayerConfig.add("sequence");
fieldMap.put(NETWORK_STRUCTURE_TO_LAYERS, networkStructureLayerConfig);
List<String> networkStructure = new ArrayList<>();
networkStructure.add("id");
networkStructure.add("name");
fieldMap.put(NETWORK_STRUCTURE, networkStructure);
}
public DataPanel(String type, String[] existingElements) {
this.setLayout(null);
List<String> fields = fieldMap.get(type);
JLabel topLabel = new JLabel(type);
topLabel.setBounds(10,10,150, 10);
this.add(topLabel);
JList list = new JList();
list.setListData(existingElements);
list.setBounds(10,25,150, (fields.size() - 1) * 40 + 20);
this.add(list);
for (int i = 0; i < fields.size(); i++) {
JLabel fieldLable = new JLabel(fields.get(i) + ":");
JTextField fieldInput = new JTextField();
this.add(fieldLable);
this.add(fieldInput);
fieldLable.setBounds(200, 10 + i * 40,200,10);
fieldInput.setBounds(200, 25 + i * 40, 200, 20);
}
JButton create = new JButton("Create");
JButton update = new JButton("Update");
JButton delete = new JButton("Delete");
create.setBounds(40, fields.size() * 40 + 30, 100, 20);
update.setBounds(40 + 120, fields.size() * 40 + 30, 100, 20);
delete.setBounds(40 + 240, fields.size() * 40 + 30, 100, 20);
this.add(create);
this.add(update);
this.add(delete);
this.setSize(410,fields.size() * 40 + 60);
this.setBounds(0,0,410, fields.size() * 40 + 60);
this.setPreferredSize(new Dimension(410, fields.size() * 40 + 60));
}
}
| true |
a22b67f14b8205a43b9db51c49ce4974b7f44a8b
|
Java
|
TaisiiaFenz/University
|
/Semester_6/DistributedComputing/test_2/src/main/java/dao/CatalogDaoImpl.java
|
UTF-8
| 1,944 | 3.03125 | 3 |
[] |
no_license
|
package dao;
import models.Catalog;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class CatalogDaoImpl implements DAO<Catalog>{
Connection connection;
public CatalogDaoImpl(Connection connection) {
this.connection = connection;
}
@Override
public List<Catalog> findAll() {
List<Catalog> catalogList = new ArrayList<>();
try (Statement statement = connection.createStatement()) {
ResultSet resultSet = statement.executeQuery("SELECT * FROM catalog");
while (resultSet.next()) {
Catalog catalog = new Catalog();
catalog.setId(resultSet.getInt("id"));
catalog.setName(resultSet.getString("name"));
catalog.setCatalog(resultSet.getString("catalog"));
catalogList.add(catalog);
}
} catch (SQLException e) {
e.printStackTrace();
}
return catalogList;
}
@Override
public Catalog save(Catalog item) {
try {
PreparedStatement preparedStatement
= connection.prepareStatement("INSERT INTO catalog(name,catalog) VALUES(?,?)");
preparedStatement.setString(1, item.getName());
preparedStatement.setString(2, item.getCatalog());
preparedStatement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
return item;
}
@Override
public boolean deleteById(int id) {
try {
PreparedStatement preparedStatement = connection.prepareStatement("DELETE FROM catalog WHERE id=?");
preparedStatement.setInt(1, id);
preparedStatement.executeUpdate();
return true;
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
@Override
public void close() throws Exception { }
}
| true |
cd75ccb39322fd7037fab238730d98cc9b1b63c3
|
Java
|
ayusuke7/ProcessamentoDigitalImagens
|
/ProcessamentoDigitalImagem/src/controle/ConverteMatToImage.java
|
UTF-8
| 1,259 | 3.21875 | 3 |
[] |
no_license
|
package controle;
import java.awt.image.BufferedImage;
import org.opencv.core.Mat;
/**
*
* @author YU7
*/
public class ConverteMatToImage {
public BufferedImage converteMatImage(Mat matrix) {
int colunas = matrix.cols();
int linhas = matrix.rows();
int elemSize = (int) matrix.elemSize();
byte[] data = new byte[colunas * linhas * elemSize];
int type;
matrix.get(0, 0, data);
switch (matrix.channels()) {
case 1:
type = BufferedImage.TYPE_BYTE_GRAY;
break;
case 3:
type = BufferedImage.TYPE_3BYTE_BGR;
// bgr to rgb
byte b;
for (int i = 0; i < data.length; i = i + 3) {
b = data[i];
data[i] = data[i + 2];
data[i + 2] = b;
}
break;
default:
return null;
}
//Cria a Imagem através do vetor [] Bytes
BufferedImage img = new BufferedImage(colunas, linhas, type);
img.getRaster().setDataElements(0, 0, colunas, linhas, data);
return img;
}
}
| true |
a75c8690d340676383e3cbecf802277ab3346ca7
|
Java
|
KMikulcak/siw
|
/monitoring_api_data_access/src/main/java/swi_dal/DataSource/Contract/IDataSource.java
|
UTF-8
| 229 | 1.921875 | 2 |
[] |
no_license
|
package swi_dal.DataSource.Contract;
import java.util.List;
import swi_dal.Dto.Order;
import swi_dal.Dto.State;
public interface IDataSource {
List<State> GetStates(String filter);
List<Order> GetOrders(String filter);
}
| true |
616fbfa0ee6de9a3a92dbf1c49279dace3b3c7ce
|
Java
|
andreas-schilling/spring-boot-thymeleaf-test
|
/src/main/java/de/twt_gmbh/cube/model/Nameable.java
|
UTF-8
| 84 | 1.882813 | 2 |
[] |
no_license
|
package de.twt_gmbh.cube.model;
public interface Nameable
{
String getLabel();
}
| true |
2098710ddd3aba23cb0a18007001f7cc2194a60c
|
Java
|
KateKlus/TaskManager
|
/backend/src/main/java/ru/compito/taskmanager/controller/TemplateAttributesController.java
|
UTF-8
| 3,331 | 1.867188 | 2 |
[] |
no_license
|
package ru.compito.taskmanager.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import ru.compito.taskmanager.config.ServiceConstants;
import ru.compito.taskmanager.entity.Attribute;
import ru.compito.taskmanager.entity.CustomField;
import ru.compito.taskmanager.entity.Task;
import ru.compito.taskmanager.entity.TaskTemplate;
import ru.compito.taskmanager.service.AttributeService;
import ru.compito.taskmanager.service.ContentRelatedRoleService;
import ru.compito.taskmanager.service.TaskService;
import ru.compito.taskmanager.service.TaskTemplateService;
import java.util.List;
@RestController
@RequestMapping(value = ServiceConstants.TASKTEMPLATE_PATH)
public class TemplateAttributesController {
@Autowired
private AttributeService attributeService;
@Autowired
private ContentRelatedRoleService contentRelatedRoleService;
@Autowired
private TaskService taskService;
@GetMapping(value = "/{taskTemplateId}/attributes/", produces = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody ResponseEntity<Object> getAttributes(@PathVariable Integer taskTemplateId) {
List<Attribute> attributes = attributeService.findByTaskTemplateId(taskTemplateId);
return new ResponseEntity<>(attributes, HttpStatus.OK);
}
@GetMapping(value = "/{taskTemplateId}/attributes/{attributeId}/", produces = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody ResponseEntity<Attribute> getAttribute(@PathVariable Integer taskTemplateId, @PathVariable Integer attributeId) {
Attribute attribute = attributeService.getByTaskTemplateAndAttributeId(taskTemplateId,attributeId);
if(attribute==null)
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
else
return new ResponseEntity<>(attribute, HttpStatus.OK);
}
@PostMapping(value = "/{taskTemplateId}/attributes/", consumes = MediaType.APPLICATION_JSON_VALUE,
produces = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody ResponseEntity<Attribute> createAttribute(@PathVariable Integer taskTemplateId, @RequestBody Attribute attribute) {
Task task = taskService.getByTaskTemplateId(taskTemplateId);
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
Attribute newAttribute = attributeService.save(taskTemplateId, attribute);
return new ResponseEntity<>(newAttribute, HttpStatus.CREATED);
}
@DeleteMapping("/{taskTemplateId}/attributes/")
@ResponseStatus(HttpStatus.NO_CONTENT)
public @ResponseBody ResponseEntity<?> deleteAttributes(@PathVariable Integer taskTemplateId) {
Task task = taskService.getByTaskTemplateId(taskTemplateId);
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
attributeService.deleteAllForTaskTemplate(taskTemplateId);
return new ResponseEntity<>(HttpStatus.OK);
}
}
| true |
37f4d7f6f4af1b17e09567cc369c663f583e999b
|
Java
|
mahdiabdollahpour/Algorithms-Design-and-Analysis
|
/src/algo2/ClusteringBig.java
|
UTF-8
| 4,406 | 2.671875 | 3 |
[] |
no_license
|
package algo2;
import java.io.*;
import java.util.ArrayList;
import java.util.HashSet;
/**
* Created by ASUS on 28/01/2018.
*/
public class ClusteringBig {
// static class Node {
// int num;
// String bin;
//
// public Node(int num, String bin) {
// this.num = num;
// this.bin = bin;
// }
// }
public static void main(String[] args) {
BufferedReader bf = null;
try {
bf = new BufferedReader(new FileReader(new File("clustering_big.txt")));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String s = null;
try {
s = bf.readLine();
} catch (IOException e) {
e.printStackTrace();
}
String[] tok = s.split(" ");
int n = Integer.parseInt(tok[0]);
int r = Integer.parseInt(tok[1]);
ArrayList<String> nodes = null;
HashSet<Integer> nodesIntVal = null;
try {
nodes = new ArrayList<>(n);
nodesIntVal = new HashSet<>(n);
for (int i = 0; i < n; i++) {
s = bf.readLine();
s = s.replaceAll("\\s", "");
int num = Integer.parseInt(s, 2);
if (nodesIntVal.contains(num)) {
// System.out.println("repeated");
} else {
nodes.add(s);
nodesIntVal.add(num);
}
}
} catch (IOException e) {
e.printStackTrace();
}
int maxNode = (int) (Math.pow(2, 24));
// System.out.println(maxNode);
comp = new Obj[maxNode];
for (int i = 0; i < maxNode; i++) {
comp[i] = new Obj(i, 0);
}
// System.out.println(n);
n = nodes.size();
components = n;
// System.out.println(n);
for (int i = 0; i < nodes.size(); i++) {
String node = nodes.get(i);
int num = Integer.parseInt(node, 2);
ArrayList<Integer> nearBy = nearByNodes(node);
for (int i1 = 0; i1 < nearBy.size(); i1++) {
int near = nearBy.get(i1);
if (nodesIntVal.contains(near)) {
if (find(num) != find(near)) {
Union(num, near);
components--;
}
}
}
}
System.out.println(components);
}
static int components;
private static void nearByRec(ArrayList<Integer> tillNow, String node, String byNow, int howDiff, int i) {
if (i == 24) {
if (howDiff != 0) {
tillNow.add(Integer.parseInt(byNow, 2));
}
return;
}
if (howDiff >= 2) {
String pass1 = byNow.concat(String.valueOf(node.charAt(i)));
nearByRec(tillNow, node, pass1, howDiff, i + 1);
} else {
String pass1 = byNow.concat(String.valueOf(node.charAt(i)));
nearByRec(tillNow, node, pass1, howDiff, i + 1);
if (node.charAt(i) == '0') {
String pass2 = byNow.concat("1");
nearByRec(tillNow, node, pass2, howDiff + 1, i + 1);
} else {
String pass2 = byNow.concat("0");
nearByRec(tillNow, node, pass2, howDiff + 1, i + 1);
}
}
}
private static ArrayList<Integer> nearByNodes(String node) {
ArrayList<Integer> nbn = new ArrayList<>();
nearByRec(nbn, node, "", 0, 0);
return nbn;
}
private static class Obj {
int parent;
int rank;
public Obj(int parent, int rank) {
this.parent = parent;
this.rank = rank;
}
}
private static Obj[] comp;
static int find(int i) {
if (comp[i].parent != i) {
comp[i].parent = find(comp[i].parent);
}
return comp[i].parent;
}
static void Union(int x, int y) {
int xroot = find(x);
int yroot = find(y);
if (comp[xroot].rank < comp[yroot].rank) {
comp[xroot].parent = yroot;
} else if (comp[xroot].rank > comp[yroot].rank) {
comp[yroot].parent = xroot;
} else {
comp[yroot].parent = xroot;
comp[xroot].rank++;
}
}
}
| true |
1188381d67f1e81071f4a4dc8f70562ef6e504ce
|
Java
|
rajes95/object_oriented_design
|
/05_constructors_accessors_mutators/Problem_1/Problem_1.java
|
UTF-8
| 1,882 | 3.703125 | 4 |
[] |
no_license
|
import teamRecords.Team;
import teamRecords.Competition;
/**
*
* Problem_1.java
*
* This class file contains a main function whose purpose is to test the Team
* class and vis-a-vis the Competition class as well located in the teamRecords
* package.
*
* The team class is used to keep track of the team members and competition
* information for a school's entries in programming competitions.
*
* @author Rajesh Sakhamuru
* @version 6/13/2019
*
*/
public class Problem_1
{
/**
*
* In order to test the Team and Competition, a Team, "lhs" is initialized along
* with 3 competitions.
*
* A deep copy is created and then modified called "lhs_copy" and both it and
* the original are printed out (using toString() print statements) to verify
* that the changes did not impact the original "lhs" Team.
*
* @param args
*
*/
public static void main(String[] args)
{
Team lhs = new Team("Vikings", "Son Heung-min", "Luigi Mario",
"Rafael Nadal", "James Bond");
Competition eastBowl = new Competition("East Bowl", lhs.getName1(),
lhs.getName2(), 2001);
Competition westBowl = new Competition("West Bowl", lhs.getName3(),
lhs.getName4(), 2002);
Competition cleganeBowl = new Competition("Clegane Bowl",
"Sandor Clegane", "Ser Gregor Clegane", 2003);
lhs.setCompetition1(eastBowl);
lhs.setCompetition2(westBowl);
System.out.println("LHS_Team: \n--------\n" + lhs);
Team lhs_copy = new Team(lhs);
// Modify lhs_copy (consequently also testing setters)
lhs_copy.setTeamName("Bad Intentions");
lhs_copy.setCompetition1(cleganeBowl);
lhs_copy.getCompetition1().setYear(2019);
lhs_copy.setName1(cleganeBowl.getWinner());
lhs_copy.setName2(cleganeBowl.getRunnerUp());
lhs_copy.setName4("007");
System.out.println("LHS_Team Copy after Changes: \n--------\n" + lhs_copy);
System.out.println("LHS_Team after Changes: \n--------\n" + lhs);
}
}
| true |
4ec1544395c6820b1965dd7a7cdd3bb013746772
|
Java
|
MarcBerneman/Space-Golf
|
/src/gui_componenten/MainMenuPanel.java
|
UTF-8
| 1,399 | 2.828125 | 3 |
[] |
no_license
|
package gui_componenten;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JPanel;
import tools.LevelQueue;
public class MainMenuPanel extends JPanel implements ActionListener {
private static final long serialVersionUID = -3801890339594484316L;
private final JButton Play = new JButton("Play");
private final JButton PlayLevel = new JButton("Level");
private final JButton PlayRandom = new JButton("Random Level");
private GameMain window;
public MainMenuPanel(GameMain window) {
this.window = window;
Play.addActionListener(this);
PlayLevel.addActionListener(this);
PlayRandom.addActionListener(this);
add(Play);
add(PlayLevel);
add(PlayRandom);
}
@Override
public void actionPerformed(ActionEvent e) {
//Play = begin vanaf level 1; PlayLevel = kies een level; Playrandom = geeft random level
if (e.getSource() == Play) {
GameMain.totalstrokes = 0;
PlayPanel p = new PlayPanel(window,new LevelQueue(LevelQueue.REALGAME));
window.switchPanel(p);
} else if (e.getSource() == PlayLevel) {
GameMain.totalstrokes = -1;
LevelMenuPanel p = new LevelMenuPanel(window);
window.switchPanel(p);
} else if (e.getSource() == PlayRandom) {
GameMain.totalstrokes = -1;
PlayPanel p = new PlayPanel(window,new LevelQueue(LevelQueue.RANDOMLEVEL));
window.switchPanel(p);
}
}
}
| true |
90f51532cb0fb945c16456ce50c3538dcc82f877
|
Java
|
DoanVanToan/AndroidViewModelViblo012018
|
/app/src/main/java/sample/toandoan/com/androidviewmodel_viblo012018/sharedata/master/MasterAdapter.java
|
UTF-8
| 2,288 | 2.453125 | 2 |
[] |
no_license
|
package sample.toandoan.com.androidviewmodel_viblo012018.sharedata.master;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
/**
* Created by doan.van.toan on 1/10/18.
*/
public class MasterAdapter extends RecyclerView.Adapter<MasterAdapter.ViewHolder> {
private List<String> mData;
private OnItemClickListenner mListenner;
public MasterAdapter() {
mData = new ArrayList<>();
}
public void addData(List<String> data) {
if (data == null) {
return;
}
mData.addAll(data);
notifyDataSetChanged();
}
public void setListenner(OnItemClickListenner listenner) {
mListenner = listenner;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(android.R.layout.simple_list_item_1, parent, false);
return new ViewHolder(view, mListenner);
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.bindData(mData.get(position));
}
@Override
public int getItemCount() {
return mData != null ? mData.size() : 0;
}
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView mTextView;
private OnItemClickListenner mListenner;
public ViewHolder(View itemView, OnItemClickListenner listenner) {
super(itemView);
mTextView = itemView.findViewById(android.R.id.text1);
mListenner = listenner;
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mListenner.onClick(mData.get(getAdapterPosition()));
}
});
}
public void bindData(String name) {
if (TextUtils.isEmpty(name)) {
return;
}
mTextView.setText(name);
}
}
public interface OnItemClickListenner {
void onClick(String result);
}
}
| true |
ce3e0770db3d07312616aa82ebee720a45d9188b
|
Java
|
SteveTan86/Spark-POC
|
/src/main/java/me/stevetan/sparkpoc/controller/Index.java
|
UTF-8
| 758 | 2.28125 | 2 |
[] |
no_license
|
package me.stevetan.sparkpoc.controller;
import me.stevetan.sparkpoc.model.User;
import me.stevetan.sparkpoc.util.Database;
import spark.Request;
import spark.Response;
import javax.persistence.EntityManager;
/**
* Created by stevetan on 19/8/16.
*/
public class Index {
public static Object handleHelloWorld(Request request, Response response) {
EntityManager entityManager = Database.getEntityManagerFactory().createEntityManager();
entityManager.getTransaction().begin();
User user = User
.builder()
.name("Steve")
.build();
entityManager.persist(user);
entityManager.getTransaction().commit();
entityManager.close();
return user;
}
}
| true |
baceb2e544a232fa5884d230a309653b3e4b5b19
|
Java
|
djveljkovic15/Domaci7
|
/src/dzo/mvcrest/shop/ShopService.java
|
UTF-8
| 535 | 2.34375 | 2 |
[] |
no_license
|
package dzo.mvcrest.shop;
import java.util.List;
/**
* Servisni sloj se bavi svom "biznis logikom"
*/
public class ShopService {
public List<Shop> getShops(String shopName){
return ShopRepository.getShops(shopName);
}
public Shop getShopById(Integer id){
return ShopRepository.getShopById(id);
}
public Shop addShop(Shop shop){
return ShopRepository.addShop(shop);
}
public Shop getShopByName(String shopName) {
return ShopRepository.getShopByName(shopName);
}
}
| true |
d76b5a13c9f1d7a54c7414a0dadf19dba0bf2cbc
|
Java
|
JetBrains/teamcity-rest
|
/src/jetbrains/buildServer/server/rest/model/problem/TestCounters.java
|
UTF-8
| 3,873 | 1.820313 | 2 |
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright 2000-2022 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jetbrains.buildServer.server.rest.model.problem;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import jetbrains.buildServer.Used;
import jetbrains.buildServer.server.rest.data.problem.TestCountersData;
import jetbrains.buildServer.server.rest.model.Fields;
import jetbrains.buildServer.server.rest.swagger.annotations.ModelDescription;
import jetbrains.buildServer.server.rest.util.DefaultValueAware;
import jetbrains.buildServer.server.rest.util.ValueWithDefault;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@XmlType(name = "testCounters", propOrder = {
"ignored",
"failed",
"muted",
"success",
"all",
"newFailed",
"duration"
})
@XmlRootElement(name = "testCounters")
@ModelDescription("Represents a test results counter (how many times this test was successful/failed/muted/ignored).")
public class TestCounters implements DefaultValueAware {
@NotNull
private final TestCountersData myTestCountersData;
@NotNull
private Fields myFields = Fields.NONE;
@Used("javax.xml")
public TestCounters() {
myTestCountersData = new TestCountersData();
}
public TestCounters(@NotNull TestCountersData testCountersData) {
myTestCountersData = testCountersData;
}
public TestCounters(@NotNull final Fields fields, @NotNull TestCountersData testCountersData) {
myFields = fields;
myTestCountersData = testCountersData;
}
@XmlAttribute(name = "failed")
@Nullable
public Integer getFailed() {
return ValueWithDefault.decideDefault(myFields.isIncluded("failed", false, true), myTestCountersData.getFailed());
}
@XmlAttribute(name = "muted")
@Nullable
public Integer getMuted() {
return ValueWithDefault.decideDefault(myFields.isIncluded("muted", false, true), myTestCountersData.getMuted());
}
@XmlAttribute(name = "success")
@Nullable
public Integer getSuccess() {
return ValueWithDefault.decideDefault(myFields.isIncluded("success", false, true), myTestCountersData.getPassed());
}
@XmlAttribute(name = "all")
@Nullable
public Integer getAll() {
return ValueWithDefault.decideDefault(myFields.isIncluded("all"), myTestCountersData.getCount());
}
@XmlAttribute(name = "ignored")
@Nullable
public Integer getIgnored() {
return ValueWithDefault.decideDefault(myFields.isIncluded("ignored", false, true), myTestCountersData.getIgnored());
}
@XmlAttribute(name = "newFailed")
@Nullable
public Integer getNewFailed() {
return ValueWithDefault.decideDefault(myFields.isIncluded("newFailed", false, true), myTestCountersData.getNewFailed());
}
@XmlAttribute(name = "duration")
@Nullable
public Long getDuration() {
return ValueWithDefault.decideDefault(myFields.isIncluded("duration", false, true), myTestCountersData.getDuration());
}
@Override
public boolean isDefault() {
return ValueWithDefault.isAllDefault(
myTestCountersData.getCount(),
myTestCountersData.getPassed(),
myTestCountersData.getFailed(),
myTestCountersData.getDuration(),
myTestCountersData.getMuted(),
myTestCountersData.getIgnored(),
myTestCountersData.getNewFailed()
);
}
}
| true |
9d867334e7a49db909b351a061b03a7493cf69a5
|
Java
|
opel13may/MyApplication2
|
/app/src/main/java/charlie/myapplication/Main3Activity.java
|
UTF-8
| 14,405 | 2.4375 | 2 |
[] |
no_license
|
package charlie.myapplication;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class Main3Activity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
//set home button go back to page2
Button home = (Button) findViewById(R.id.button2);
home.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent startintent = new Intent(getApplicationContext(),Main2Activity.class);
finish();
startActivity(startintent);
}
});
//set name to all edit text and spinner
final EditText keyamount = (EditText) findViewById(R.id.keyamount);
final Spinner spinner1 = (Spinner) findViewById(R.id.spinner1);
final Spinner spinner2 = (Spinner) findViewById(R.id.spinner2);
Button convert = (Button) findViewById(R.id.button1);
final TextView result = (TextView) findViewById(R.id.textView);
//load shared preference to spinner1&2
SharedPreferences sharedPref1 = getSharedPreferences("data1",MODE_PRIVATE);
int spinnerValue1 = sharedPref1.getInt("userChoiceSpinner1",-1);
spinner1.setSelection(spinnerValue1);
SharedPreferences sharedPref2 = getSharedPreferences("data1",MODE_PRIVATE);
int spinnerValue2 = sharedPref2.getInt("userChoiceSpinner2",-1);
spinner2.setSelection(spinnerValue2);
convert.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//change edit text to string
String num = keyamount.getText().toString();
//change string to int
int num1 = Integer.parseInt(num);
String spinner01 = spinner1.getSelectedItem().toString();
String spinner02 = spinner2.getSelectedItem().toString();
//toast msg when user key invalid number
if (num1 <= 0){
Toast.makeText(Main3Activity.this,"Invalid Input",Toast.LENGTH_LONG).show();
}
//SGD part exchange rate
else{
if(spinner01.equals("Singapore Dollar") && spinner02.equals("US Dollar")){
double value = num1 * 0.747;
result.setText("$"+value);
}
if(spinner01.equals("Singapore Dollar") && spinner02.equals("Malaysia Ringgit")){
double value = num1 * 2.978;
result.setText("RM"+value);
}
if(spinner01.equals("Singapore Dollar") && spinner02.equals("Singapore Dollar")){
double value = num1 * 1;
result.setText("S$"+value);
}
if(spinner01.equals("Singapore Dollar") && spinner02.equals("British pound")){
double value = num1 * 0.559;
result.setText("£"+value);
}
if(spinner01.equals("Singapore Dollar") && spinner02.equals("Euro")){
double value = num1 * 0.639;
result.setText("€"+value);
}
if(spinner01.equals("Singapore Dollar") && spinner02.equals("Japanese Yen")){
double value = num1 * 81.800;
result.setText("¥"+value);
}
if(spinner01.equals("Singapore Dollar") && spinner02.equals("Thai Baht")){
double value = num1 * 23.928114;
result.setText("฿"+value);
}
//ringgit part
if(spinner01.equals("Malaysia Ringgit") && spinner02.equals("US Dollar")){
double value = num1 * 0.250;
result.setText("$"+value);
}
if(spinner01.equals("Malaysia Ringgit") && spinner02.equals("Malaysia Ringgit")){
double value = num1 * 1;
result.setText("RM"+value);
}
if(spinner01.equals("Malaysia Ringgit") && spinner02.equals("Singapore Dollar")){
double value = num1 * 0.335;
result.setText("S$"+value);
}
if(spinner01.equals("Malaysia Ringgit") && spinner02.equals("British pound")){
double value = num1 * 0.187 ;
result.setText("£"+value);
}
if(spinner01.equals("Malaysia Ringgit") && spinner02.equals("Euro")){
double value = num1 * 0.214 ;
result.setText("€"+value);
}
if(spinner01.equals("Malaysia Ringgit") && spinner02.equals("Japanese Yen")){
double value = num1 * 27.461 ;
result.setText("¥"+value);
}
if(spinner01.equals("Malaysia Ringgit") && spinner02.equals("Thai Baht")) {
double value = num1 * 8.032;
result.setText("฿" + value);
}
//US Dollar part
if(spinner01.equals("US Dollar") && spinner02.equals("US Dollar")){
double value = num1 * 1 ;
result.setText("$"+value);
}
if(spinner01.equals("US Dollar") && spinner02.equals("Malaysia Ringgit")){
double value = num1 * 3.987 ;
result.setText("RM"+value);
}
if(spinner01.equals("US Dollar") && spinner02.equals("Singapore Dollar")){
double value = num1 * 1.338 ;
result.setText("S$"+value);
}
if(spinner01.equals("US Dollar") && spinner02.equals("British pound")){
double value = num1 * 0.749 ;
result.setText("£"+value);
}
if(spinner01.equals("US Dollar") && spinner02.equals("Euro")){
double value = num1 * 0.857 ;
result.setText("€"+value);
}
if(spinner01.equals("US Dollar") && spinner02.equals("Japanese Yen")){
double value = num1 * 109.493;
result.setText("¥"+value);
}
if(spinner01.equals("US Dollar") && spinner02.equals("Thai Baht")) {
double value = num1 * 32.021;
result.setText("฿" + value);
}
//British pound part
if(spinner01.equals("British pound") && spinner02.equals("US Dollar")){
double value = num1 * 1.335;
result.setText("$"+value);
}
if(spinner01.equals("British pound") && spinner02.equals("Malaysia Ringgit")){
double value = num1 * 5.324;
result.setText("RM"+value);
}
if(spinner01.equals("British pound") && spinner02.equals("Singapore Dollar")){
double value = num1 * 1.786;
result.setText("$"+value);
}
if(spinner01.equals("British pound") && spinner02.equals("British pound")){
double value = num1 * 1;
result.setText("£"+value);
}
if(spinner01.equals("British pound") && spinner02.equals("Euro")){
double value = num1 * 1.144;
result.setText("€"+value);
}
if(spinner01.equals("British pound") && spinner02.equals("Japanese Yen")){
double value = num1 * 146.175;
result.setText("¥"+value);
}
if(spinner01.equals("British pound") && spinner02.equals("Thai Baht")) {
double value = num1 * 42.740;
result.setText("฿" + value);
}
//Euro part
if(spinner01.equals("Euro") && spinner02.equals("US Dollar")){
double value = num1 * 1.166;
result.setText("$"+value);
}
if(spinner01.equals("Euro") && spinner02.equals("Malaysia Ringgit")){
double value = num1 * 4.652;
result.setText("RM"+value);
}
if(spinner01.equals("Euro") && spinner02.equals("Singapore Dollar")){
double value = num1 * 1.561;
result.setText("S$"+value);
}
if(spinner01.equals("Euro") && spinner02.equals("British pound")){
double value = num1 * 0.873;
result.setText("£"+value);
}
if(spinner01.equals("Euro") && spinner02.equals("Euro")){
double value = num1 * 1;
result.setText("€"+value);
}
if(spinner01.equals("Euro") && spinner02.equals("Japanese Yen")){
double value = num1 * 127.730075;
result.setText("¥"+value);
}
if(spinner01.equals("Euro") && spinner02.equals("Thai Baht")) {
double value = num1 * 37.355;
result.setText("฿" + value);
}
//Japanese Yen part
if(spinner01.equals("Japanese Yen") && spinner02.equals("US Dollar")){
double value = num1 * 0.009 ;
result.setText("$"+value);
}
if(spinner01.equals("Japanese Yen") && spinner02.equals("Malaysia Ringgit")){
double value = num1 * 0.036 ;
result.setText("RM"+value);
}
if(spinner01.equals("Japanese Yen") && spinner02.equals("Singapore Dollar")){
double value = num1 * 0.012;
result.setText("S$"+value);
}
if(spinner01.equals("Japanese Yen") && spinner02.equals("British pound")){
double value = num1 * 0.006;
result.setText("£"+value);
}
if(spinner01.equals("Japanese Yen") && spinner02.equals("Euro")){
double value = num1 * 0.007;
result.setText("€"+value);
}
if(spinner01.equals("Japanese Yen") && spinner02.equals("Japanese Yen")){
double value = num1 * 1;
result.setText("¥"+value);
}
if(spinner01.equals("Japanese Yen") && spinner02.equals("Thai Baht")) {
double value = num1 * 0.292;
result.setText("฿" + value);
}
//thai baht part
if(spinner01.equals("Thai Baht") && spinner02.equals("US Dollar")) {
double value = num1 * 0.031;
result.setText("$" + value);
}
if(spinner01.equals("Thai Baht") && spinner02.equals("Malaysia Ringgit")) {
double value = num1 * 0.124;
result.setText("RM" + value);
}
if(spinner01.equals("Thai Baht") && spinner02.equals("Singapore Dollar")) {
double value = num1 * 0.041;
result.setText("S$" + value);
}
if(spinner01.equals("Thai Baht") && spinner02.equals("British pound")) {
double value = num1 * 0.023;
result.setText("£" + value);
}
if(spinner01.equals("Thai Baht") && spinner02.equals("Euro")) {
double value = num1 * 0.026 ;
result.setText("€" + value);
}
if(spinner01.equals("Thai Baht") && spinner02.equals("Japanese Yen")) {
double value = num1 * 3.419;
result.setText("¥" + value);
}
if(spinner01.equals("Thai Baht") && spinner02.equals("Thai Baht")) {
double value = num1 * 1;
result.setText("฿" + value);
}
}
//save user selected spinner position
int choice1 = spinner1.getSelectedItemPosition();
SharedPreferences sharedPref1 = getSharedPreferences("data1",0);
SharedPreferences.Editor prefEditor1 = sharedPref1.edit();
prefEditor1.putInt("userChoiceSpinner1",choice1);
prefEditor1.apply();
int choice2 = spinner2.getSelectedItemPosition();
SharedPreferences sharedPref2 = getSharedPreferences("data1",0);
SharedPreferences.Editor prefEditor2 = sharedPref1.edit();
prefEditor2.putInt("userChoiceSpinner2",choice2);
prefEditor2.apply();
}
});
}
}
| true |
4f39bece901391dba9f59090019e7fad208075a6
|
Java
|
ericdoppelt/xml-casino
|
/src/engine/evaluator/handevaluator/HandEvaluatorInterface.java
|
UTF-8
| 712 | 3.078125 | 3 |
[
"MIT"
] |
permissive
|
package engine.evaluator.handevaluator;
import engine.hand.PlayerHand;
/**
* Interface implemented by hand evaluator, single public service to compare two hands
* @author Max Smith
*/
public interface HandEvaluatorInterface {
/**
* Compares two Hands and determines a winner based on the hierarchy given via an XML file.
* This method essentially forms the implementation of said hierarchy by determining winners based off of it.
* @param playerHand1 is the first hand to compare
* @param playerHand2 is the second hand to compare
* @return either -1 (first hand wins), 0 (push), or 1 (second hand wins).
*/
int compare(PlayerHand playerHand1, PlayerHand playerHand2);
}
| true |
5c9f54099d811770d9cc2d043a47c91d763fc838
|
Java
|
javiergarciacotado/social-service
|
/src/test/java/co/tide/exercise/configuration/PropertiesReaderIT.java
|
UTF-8
| 1,521 | 2.71875 | 3 |
[] |
no_license
|
package co.tide.exercise.configuration;
import org.junit.Test;
import java.io.IOException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;
public class PropertiesReaderIT {
private static final String UNKNOWN_PROPERTY = "some.property";
private static final String VALID_PROPERTY = "social.service.property";
private static final String PROPERTIES_FILE = "/application.properties";
@Test(expected = NullPointerException.class)
public void givenNullFileNameThrowNullPointerException() throws IOException {
PropertiesReader propertiesReader = new PropertiesReader(null);
assertNull(propertiesReader);
fail("Shoul have thrown exception");
}
@Test
public void givenAEmptyFileNameReturnEmptyPropertyValue() throws IOException {
PropertiesReader propertiesReader = new PropertiesReader("");
assertEquals("", propertiesReader.get(UNKNOWN_PROPERTY));
}
@Test
public void givenAValidFileNameAndUnknownPropertyNameReturnEmpty() throws IOException {
PropertiesReader propertiesReader = new PropertiesReader(PROPERTIES_FILE);
assertEquals("", propertiesReader.get(UNKNOWN_PROPERTY));
}
@Test
public void givenAValidFileNameAndKnownPropertyReturnValue() throws IOException {
PropertiesReader propertiesReader = new PropertiesReader(PROPERTIES_FILE);
assertEquals("test", propertiesReader.get(VALID_PROPERTY));
}
}
| true |
ffd9ff1ea0b8e45245dbd9a0b67db917b191e08d
|
Java
|
Sistema-de-atendimento-hospitalar/notificacao-service
|
/src/main/java/br/com/bublemedical/notificationservice/controller/TokenController.java
|
UTF-8
| 1,237 | 2.078125 | 2 |
[] |
no_license
|
package br.com.bublemedical.notificationservice.controller;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import br.com.bublemedical.notificationservice.domain.request.TokenRequest;
import br.com.bublemedical.notificationservice.domain.request.ValidarTokenRequest;
import br.com.bublemedical.notificationservice.service.TokenService;
@RestController
@CrossOrigin
public class TokenController {
@Autowired
private TokenService tokenService;
@PostMapping("/v1/autorization/token")
@ResponseStatus(HttpStatus.CREATED)
public void createToken(@RequestBody @Valid TokenRequest tokenRequest) {
tokenService.gerarToken(tokenRequest);
}
@PostMapping("/v1/autorization/token/valid")
public void validToken(@RequestBody @Valid ValidarTokenRequest tokenRequest) throws Exception {
tokenService.validarToken(tokenRequest);
}
}
| true |
1f4135a50adb383e84e7734d680ca95008200130
|
Java
|
hackugyo/GATEMail
|
/GATEmail/src/jp/hackugyo/gatemail/util/ImeUtils.java
|
UTF-8
| 2,806 | 2.453125 | 2 |
[] |
no_license
|
package jp.hackugyo.gatemail.util;
import android.app.Dialog;
import android.content.Context;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
/**
* 文字入力を表示・非表示します.
*
* @author kwatanabe
*
*/
public class ImeUtils {
/**
* 文字入力を開きます.
*
* @see <a
* href="http://stackoverflow.com/questions/2403632/android-show-soft-keyboard-automatically-when-focus-is-on-an-edittext">参考ページ</a>
*/
public static void openIme(View view, Context context, Dialog dialog) {
// view.setFocusableInTouchMode(true);
view.requestFocus();
dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE//
| WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
InputMethodManager inputMethodManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
// inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0);
// inputMethodManager.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT, null);
// http://stackoverflow.com/questions/4761741/show-soft-keyboard-when-the-device-is-landscape-mode
inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, InputMethodManager.HIDE_IMPLICIT_ONLY);
inputMethodManager.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
// inputMethodManager.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
// inputMethodManager.showSoftInputFromInputMethod(view.getApplicationWindowToken(), InputMethodManager.SHOW_IMPLICIT);
// view.requestFocus();
// カーソルを末尾に移動
if (view instanceof EditText) {
EditText et = (EditText) view;
et.setSelection(et.getText().length());
}
}
/**
* 文字入力を閉じます.
*
* @param view
* @param context
*/
public static void closeIme(View view, Context context) {
if (context == null) {
LogUtils.w("Trying closing IME, but context is null.");
return;
}
InputMethodManager inputMethodManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.toggleSoftInput(0, InputMethodManager.HIDE_IMPLICIT_ONLY);
// hideSoftInputFromInputMethodは使わない
// http://stackoverflow.com/questions/3858362/hide-soft-keyboard
// inputMethodManager.hideSoftInputFromInputMethod(view.getApplicationWindowToken(), InputMethodManager.HIDE_IMPLICIT_ONLY);
inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
| true |
4761a77957d58d975b104a4a1442eb528800d3e7
|
Java
|
xchnba/spring_boot_mybits
|
/src/main/java/com/example/demo/mall/controller/TestController.java
|
UTF-8
| 1,944 | 1.914063 | 2 |
[] |
no_license
|
package com.example.demo.mall.controller;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.util.WebUtils;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
@Controller
@RequestMapping("/test")
public class TestController {
@RequestMapping("/look")
public String look(){
return "/test/look";
}
@RequestMapping("/menu")
public String menu(){
return "/test/menu";
}
@RequestMapping("/upload")
public String upload(HttpServletRequest request){
MultipartFile file = null;
String name="haha";
InputStream inputStream=null;
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart){
MultipartHttpServletRequest multipartRequest = WebUtils.getNativeRequest(request, MultipartHttpServletRequest.class);
file = multipartRequest.getFile("file");
name = file.getOriginalFilename();
try {
inputStream = file.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
}
String a="nihaoa";
System.out.println(name);
return "/test/look";
}
@RequestMapping("/addcss")
public String addcss(HttpServletRequest request){
return "/page/jskzcss";
}
@RequestMapping("/select")
public String select(){
String a = "2122323";
return "/test/selectPage";
}
@RequestMapping("/showPdf")
public String showPdf(){
String a = "2122323";
return "/test/showPdf";
}
}
| true |
77f71e1b206ca9b21fcc91cf46171d682e391445
|
Java
|
joshalumasa/sports-backend
|
/src/main/java/com/api/backend/App.java
|
UTF-8
| 230 | 1.710938 | 2 |
[] |
no_license
|
package com.api.backend;
public class App {
public static void main(String[] args) throws Exception {
System.out.println("#No.1 Sports App");
ApiCalls api = new ApiCalls();
api.fetchLeagues();
}
}
| true |
c9a7d7cf92066b1c6cd3b5a665f2155886888b0b
|
Java
|
megchisp/car-repair-shop
|
/src/main/java/negocio/ManoDeObraManager.java
|
UTF-8
| 1,641 | 2.609375 | 3 |
[] |
no_license
|
package negocio;
import java.util.List;
import persistencia.IManoDeObraDao;
import persistencia.ManoDeObra;
import persistencia.ManoDeObraDao;
import persistencia.Servicio;
public class ManoDeObraManager implements IManoDeObraManager {
private int estadoFinal;
IManoDeObraDao manoDeObraDao;
public ManoDeObraManager(){
manoDeObraDao = new ManoDeObraDao();
}
public int agregar(ManoDeObra manoDeObra) throws Exception {
if( validarDatos( manoDeObra ) )
estadoFinal = manoDeObraDao.agregar( manoDeObra );
return estadoFinal;
}
private boolean validarDatos(ManoDeObra manoDeObra) {
// if( manoDeObra.getPrecio() <= 0 ){
// estadoFinal = 2;
// return false;
// }
return true;
}
public int modificar(ManoDeObra manoDeObra) throws Exception {
if( validarDatos( manoDeObra ) )
estadoFinal = manoDeObraDao.modificar( manoDeObra );
return estadoFinal;
}
public int eliminar(ManoDeObra manoDeObra) throws Exception {
if(true)
estadoFinal = manoDeObraDao.eliminar(manoDeObra);
return estadoFinal;
}
public List<ManoDeObra> listaManosDeObras(Servicio servicio) throws Exception {
return manoDeObraDao.listaManosDeObras(servicio);
}
public List<String> listaNombreManosDeObras() throws Exception {
return manoDeObraDao.listaNombreManosDeObras();
}
public List<ManoDeObra> listaManosDeObras() throws Exception {
return manoDeObraDao.listaManosDeObras();
}
public int nextID() throws Exception {
return manoDeObraDao.nextID();
}
public int lastValue() throws Exception {
return manoDeObraDao.lastValue();
}
}
| true |
123882315d57398b8ce723b6c4be67dd430e3170
|
Java
|
cloudkeeper-project/cloudkeeper
|
/cloudkeeper-core/cloudkeeper-basic/src/main/java/xyz/cloudkeeper/simple/SingleVMCloudKeeper.java
|
UTF-8
| 10,087 | 1.976563 | 2 |
[
"Apache-2.0"
] |
permissive
|
package xyz.cloudkeeper.simple;
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.actor.Props;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import scala.concurrent.Await;
import scala.concurrent.duration.Duration;
import xyz.cloudkeeper.interpreter.AdministratorActorCreator;
import xyz.cloudkeeper.interpreter.CloudKeeperEnvironmentBuilder;
import xyz.cloudkeeper.interpreter.ExecutorActorCreator;
import xyz.cloudkeeper.interpreter.InstanceProviderActorCreator;
import xyz.cloudkeeper.interpreter.MasterInterpreterActorCreator;
import xyz.cloudkeeper.model.api.CloudKeeperEnvironment;
import xyz.cloudkeeper.model.api.executor.ModuleConnectorProvider;
import xyz.cloudkeeper.model.api.executor.SimpleModuleExecutor;
import xyz.cloudkeeper.model.api.staging.InstanceProvider;
import xyz.cloudkeeper.model.api.staging.StagingAreaProvider;
import xyz.cloudkeeper.model.api.util.RecursiveDeleteVisitor;
import xyz.cloudkeeper.staging.MapStagingArea;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Objects;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicBoolean;
public final class SingleVMCloudKeeper {
private final Logger log = LoggerFactory.getLogger(getClass());
private static final String ADMINISTRATOR_NAME = "administrator";
private static final String MASTER_INTERPRETER_NAME = "master-interpreter";
private static final String EXECUTOR_NAME = "executor";
private static final String INSTANCE_PROVIDER_NAME = "instance-provider";
private static final String INSTANCE_PROVIDER_PATH = "/user/" + INSTANCE_PROVIDER_NAME;
private final boolean ownsActorSystem;
private final ActorSystem actorSystem;
private final AtomicBoolean isShutDown = new AtomicBoolean(false);
private final CountDownLatch shutdownLatch = new CountDownLatch(1);
private final ActorRef administrator;
private final ActorRef masterInterpreter;
private final ActorRef executor;
private final InstanceProvider instanceProvider;
private final boolean ownsWorkspaceBasePath;
private final Path workspaceBasePath;
private SingleVMCloudKeeper(
boolean ownsActorSystem,
ActorSystem actorSystem,
ActorRef administrator,
ActorRef masterInterpreter,
ActorRef executor,
InstanceProvider instanceProvider,
boolean ownsWorkspaceBasePath,
Path workspaceBasePath
) {
this.ownsActorSystem = ownsActorSystem;
this.actorSystem = actorSystem;
this.administrator = administrator;
this.masterInterpreter = masterInterpreter;
this.executor = executor;
this.instanceProvider = instanceProvider;
this.ownsWorkspaceBasePath = ownsWorkspaceBasePath;
this.workspaceBasePath = workspaceBasePath;
}
public static final class Builder {
private ActorSystem actorSystem;
private Path workspaceBasePath = null;
private InstanceProvider instanceProvider = null;
private long firstExecutionId = 0;
public Builder setWorkspaceBasePath(Path workspaceBasePath) {
this.workspaceBasePath = Objects.requireNonNull(workspaceBasePath);
return this;
}
public Builder setActorSystem(ActorSystem actorSystem) {
this.actorSystem = Objects.requireNonNull(actorSystem);
return this;
}
public Builder setInstanceProvider(InstanceProvider instanceProvider) {
this.instanceProvider = Objects.requireNonNull(instanceProvider);
return this;
}
public Builder setFirstExecutionId(long firstExecutionId) {
this.firstExecutionId = firstExecutionId;
return this;
}
/**
* Returns a new {@link SingleVMCloudKeeper} instance using the attributes of this builder.
*
* @return the new {@link SingleVMCloudKeeper} instance
* @throws BuilderException if construction fails
*/
public SingleVMCloudKeeper build() {
boolean success = false;
ActorSystem actualActorSystem = actorSystem;
try {
boolean ownsWorkspaceBasePath = workspaceBasePath == null;
Path actualWorkspaceBasePath = ownsWorkspaceBasePath
? Files.createTempDirectory(SingleVMCloudKeeper.class.getSimpleName())
: workspaceBasePath;
boolean ownsActorSystem = actorSystem == null;
actualActorSystem = ownsActorSystem
? ActorSystem.create()
: actorSystem;
Executor runnableExecutor = actualActorSystem.dispatcher();
ActorRef administrator = actualActorSystem.actorOf(
Props.create(AdministratorActorCreator.getInstance()), ADMINISTRATOR_NAME);
ActorRef masterInterpreter = actualActorSystem.actorOf(
Props.create(new MasterInterpreterActorCreator(firstExecutionId)), MASTER_INTERPRETER_NAME);
ModuleConnectorProvider moduleConnectorProvider
= new PrefetchingModuleConnectorProvider(actualWorkspaceBasePath);
SimpleModuleExecutor simpleModuleExecutor
= new LocalSimpleModuleExecutor.Builder(runnableExecutor, moduleConnectorProvider).build();
ActorRef executor = actualActorSystem.actorOf(
Props.create(new ExecutorActorCreator(simpleModuleExecutor)), EXECUTOR_NAME);
InstanceProvider actualInstanceProvider = instanceProvider;
if (actualInstanceProvider == null) {
actualInstanceProvider = new SimpleInstanceProvider.Builder(runnableExecutor).build();
}
actualActorSystem.actorOf(
Props.create(new InstanceProviderActorCreator(actualInstanceProvider)),
INSTANCE_PROVIDER_NAME
);
SingleVMCloudKeeper cloudKeeper = new SingleVMCloudKeeper(ownsActorSystem, actualActorSystem,
administrator, masterInterpreter, executor, actualInstanceProvider, ownsWorkspaceBasePath,
actualWorkspaceBasePath);
success = true;
return cloudKeeper;
} catch (IOException | BuilderException exception) {
throw new BuilderException(SingleVMCloudKeeper.class.toString(), exception);
} finally {
if (!success) {
if (actualActorSystem != null) {
actualActorSystem.terminate();
}
}
}
}
}
@Override
protected void finalize() {
shutdown();
}
private final class CleanUpThread implements Runnable {
@Override
public void run() {
if (ownsActorSystem) {
try {
Await.result(actorSystem.terminate(), Duration.Inf());
} catch (Exception exception) {
log.error("Failed to shutdown actor system.", exception);
}
}
if (ownsWorkspaceBasePath) {
try {
Files.walkFileTree(workspaceBasePath, RecursiveDeleteVisitor.getInstance());
} catch (IOException exception) {
log.error(String.format(
"Failed to delete workspace base path at %s.", workspaceBasePath
), exception);
}
}
shutdownLatch.countDown();
}
}
/**
* Stops this CloudKeeper system asynchronously.
*
* <p>If a synchronous shutdown is needed, {@link #awaitTermination()} should be called subsequent to this method.
*/
public SingleVMCloudKeeper shutdown() {
if (isShutDown.compareAndSet(false, true)) {
new Thread(new CleanUpThread()).start();
}
return this;
}
/**
* Blocks the current thread until the CloudKeeper system has been shutdown.
*
* <p>This method also blocks if {@link #shutdown()} has <em>not</em> been called, yet.
*
* @throws InterruptedException if the current thread is interrupted while waiting
*/
public void awaitTermination() throws InterruptedException {
shutdownLatch.await();
}
public final class EnvironmentBuilder {
private StagingAreaProvider stagingAreaProvider
= (runtimeContext, executionTrace, ignored) -> new MapStagingArea(runtimeContext, executionTrace);
private boolean cleaningRequested = true;
private EnvironmentBuilder() { }
public EnvironmentBuilder setCleaningRequested(boolean cleaningRequested) {
this.cleaningRequested = cleaningRequested;
return this;
}
public EnvironmentBuilder setStagingAreaProvider(StagingAreaProvider stagingAreaProvider) {
this.stagingAreaProvider = stagingAreaProvider;
return this;
}
/**
* Returns a new {@link CloudKeeperEnvironment} instance using the attributes of this builder.
*
* @return the new {@link SingleVMCloudKeeper} instance
* @throws BuilderException if construction fails
*/
public CloudKeeperEnvironment build() {
CloudKeeperEnvironmentBuilder builder = new CloudKeeperEnvironmentBuilder(
actorSystem.dispatcher(), administrator, masterInterpreter, executor, instanceProvider,
stagingAreaProvider
);
builder
.setCleaningRequested(cleaningRequested)
.setInstanceProviderActorPath(INSTANCE_PROVIDER_PATH);
return builder.build();
}
}
public EnvironmentBuilder newCloudKeeperEnvironmentBuilder() {
return new EnvironmentBuilder();
}
}
| true |
8da54e463a7a42227950c5939ca0d2f04ee50ab4
|
Java
|
Encephalon5/javahardway
|
/ReceiptRevisited.java
|
UTF-8
| 1,156 | 3.09375 | 3 |
[] |
no_license
|
import java.io.PrintWriter;
import java.util.Scanner;
public class ReceiptRevisited {
public static void main( String[]args ) throws Exception {
PrintWriter fileout = new PrintWriter("receipt.txt");
Scanner keyboard = new Scanner(System.in);
double pG, nG, net, tax;
System.out.print("How many gallons did you purchase? > ");
nG = keyboard.nextDouble();
System.out.print("What was the cost per gallon? > ");
pG = keyboard.nextDouble();
tax = 1.06;
net = (nG * pG) * tax;
fileout.println( "+------------------------+" );
fileout.println( " " );
fileout.println( " CORNER STORE " );
fileout.println( " " );
fileout.println( " 2014-06-25 4:38PM " );
fileout.println( " " );
fileout.println( " Gallons: " + nG + " " );
fileout.println( " Price/Gallon: $ "+pG+" " );
fileout.println( " " );
fileout.println( " Fuel total: " +net+ " " );
fileout.println( " " );
fileout.println( "+------------------------+" );
fileout.close();
}
}
| true |
ccae3c038e8d666a09ebe21d0cf8ae9863306e41
|
Java
|
LartTyler/SolusRpg-bukkit
|
/src/me/dbstudios/solusrpg/SolusRpg.java
|
UTF-8
| 2,236 | 2.171875 | 2 |
[] |
no_license
|
package me.dbstudios.solusrpg;
import java.lang.reflect.Method;
import java.util.logging.Level;
import java.util.logging.Logger;
import me.dbstudios.solusrpg.config.Configuration;
import me.dbstudios.solusrpg.entities.stats.AuxStat;
import me.dbstudios.solusrpg.events.EventDistributor;
import me.dbstudios.solusrpg.events.RpgStockListener;
import me.dbstudios.solusrpg.gui.SimlConverter;
import me.dbstudios.solusrpg.language.LanguageManager;
import org.bukkit.Bukkit;
import org.bukkit.plugin.java.JavaPlugin;
public class SolusRpg extends JavaPlugin {
private static final Logger logger = Logger.getLogger("Minecraft");
private static final Class<?>[] init = new Class<?>[] {
Configuration.class,
LanguageManager.class,
RpgChannelFactory.class,
AuxStatFactory.class,
RpgClassFactory.class,
RpgPlayerFactory.class,
RpgPopupFactory.class,
SimlConverter.class
};
private static SolusRpg instance = null;
public void onEnable() {
long loadStart = System.currentTimeMillis();
instance = this;
Bukkit.getPluginManager().registerEvents(new EventDistributor(), this);
Bukkit.getPluginManager().registerEvents(new RpgStockListener(), this);
for (Class<?> cl : init)
try {
cl.getMethod("initialize").invoke(null);
} catch (Exception e) {
SolusRpg.log(Level.SEVERE, String.format("Could not initialize required class %s; SolusRpg will be disabled until server restart", cl.getSimpleName()));
e.printStackTrace();
Bukkit.getPluginManager().disablePlugin(this);
return;
}
SolusRpg.log("Successfully loaded in {0} milliseconds.", System.currentTimeMillis() - loadStart);
}
public void onDisable() {
}
public static void log(String message) {
SolusRpg.log(Level.INFO, message);
}
public static void log(String message, Object... args) {
SolusRpg.log(Level.INFO, message, args);
}
public static void log(Level level, String message) {
logger.log(level, "[SolusRpg] {0}", message);
}
public static void log(Level level, String message, Object... args) {
for (int i = 0; i < args.length; i++)
message = message.replace("{" + i + "}", args[i] + "");
SolusRpg.log(level, message);
}
public static SolusRpg getInstance() {
return instance;
}
}
| true |
1ac3ab69b4f364a4ed0051654ead91ec1ba1bc90
|
Java
|
wzh1212/mll_parent
|
/mll_security/src/main/java/com/xmcc/mll_security/core/social/SocialConfig.java
|
UTF-8
| 2,740 | 1.96875 | 2 |
[] |
no_license
|
package com.xmcc.mll_security.core.social;
import com.xmcc.mll_security.core.social.qq.QQConnectionFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.security.crypto.encrypt.Encryptors;
import org.springframework.social.UserIdSource;
import org.springframework.social.config.annotation.ConnectionFactoryConfigurer;
import org.springframework.social.config.annotation.EnableSocial;
import org.springframework.social.config.annotation.SocialConfigurerAdapter;
import org.springframework.social.connect.ConnectionFactory;
import org.springframework.social.connect.ConnectionFactoryLocator;
import org.springframework.social.connect.UsersConnectionRepository;
import org.springframework.social.connect.jdbc.JdbcUsersConnectionRepository;
import org.springframework.social.security.AuthenticationNameUserIdSource;
import org.springframework.social.security.SpringSocialConfigurer;
import javax.sql.DataSource;
@Configuration
@EnableSocial
@Slf4j
public class SocialConfig extends SocialConfigurerAdapter {
@Autowired
private DataSource dataSource;
@Autowired(required = false)
private ConnectionSignUp connectionSignUp;
@Override
public UsersConnectionRepository getUsersConnectionRepository(ConnectionFactoryLocator connectionFactoryLocator) {
//第三个参数 是加密的 我们不做任何操作
JdbcUsersConnectionRepository jdbcUsersConnectionRepository = new JdbcUsersConnectionRepository(dataSource, connectionFactoryLocator, Encryptors.noOpText());
//如果需要给表加前缀
// jdbcUsersConnectionRepository.setTablePrefix("xxxx");
if (connectionSignUp != null){
jdbcUsersConnectionRepository.setConnectionSignUp(connectionSignUp);
}
log.info("success。。。");
return jdbcUsersConnectionRepository;
}
@Bean
public SpringSocialConfigurer springSocialConfigurer(){
return new SpringSocialConfigurer();
}
@Override
public void addConnectionFactories(ConnectionFactoryConfigurer connectionFactoryConfigurer, Environment environment){
connectionFactoryConfigurer.addConnectionFactory(createConnectionFactory());
}
public ConnectionFactory<?> createConnectionFactory() {
return new
//参数1:appid 参数2:appSecurity
QQConnectionFactory("101548802","6ac7e06dc0b0fb04da42e0c36c14ae29");
}
@Override
public UserIdSource getUserIdSource() {
return new AuthenticationNameUserIdSource();
}
}
| true |
fc654ed87c27478955956681e03b1ac0bf1eb995
|
Java
|
nitvic793/sling-android
|
/app/src/main/java/in/sling/utils/Chat.java
|
UTF-8
| 12,859 | 1.617188 | 2 |
[] |
no_license
|
package in.sling.utils;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v7.widget.LinearLayoutManager;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;
import com.quickblox.auth.QBAuth;
import com.quickblox.auth.model.QBSession;
import com.quickblox.chat.QBChatService;
import com.quickblox.chat.QBPrivateChat;
import com.quickblox.chat.QBPrivateChatManager;
import com.quickblox.chat.listeners.QBPrivateChatManagerListener;
import com.quickblox.chat.model.QBDialog;
import com.quickblox.chat.model.QBDialogType;
import com.quickblox.core.QBEntityCallback;
import com.quickblox.core.exception.QBResponseException;
import com.quickblox.core.helper.StringifyArrayList;
import com.quickblox.core.request.QBRequestGetBuilder;
import com.quickblox.messages.QBPushNotifications;
import com.quickblox.messages.model.QBEnvironment;
import com.quickblox.messages.model.QBEvent;
import com.quickblox.messages.model.QBNotificationChannel;
import com.quickblox.messages.model.QBNotificationType;
import com.quickblox.messages.model.QBPushType;
import com.quickblox.messages.model.QBSubscription;
import com.quickblox.users.QBUsers;
import com.quickblox.users.model.QBUser;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import in.sling.adapters.ChatDialogsAdapter;
import in.sling.models.ChatDialogViewModel;
import in.sling.models.Data;
import in.sling.models.User;
import in.sling.models.UserPopulated;
import in.sling.services.CustomCallback;
import in.sling.services.DataService;
import in.sling.services.RestFactory;
import in.sling.services.SlingService;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
/**
* Created by nitiv on 5/20/2016.
*/
public class Chat {
private static Chat chatInstance;
QBChatService chatService = QBChatService.getInstance();
UserPopulated slingUser;
QBRequestGetBuilder requestBuilder = new QBRequestGetBuilder();
QBUser mUser;
SharedPreferences preferences;
SlingService api;
DataService dataService;
ArrayList<QBUser> chatUsers = new ArrayList<>();
ArrayList<ChatDialogViewModel> dialogs = new ArrayList<>();
TelephonyManager systemService;
ContentResolver contentResolver;
public static void initialize(UserPopulated user, SharedPreferences preferences, Activity activity){
chatInstance = new Chat(user, preferences);
chatInstance.systemService = (TelephonyManager)activity.getSystemService(
Context.TELEPHONY_SERVICE);
chatInstance.contentResolver = activity.getContentResolver();
}
public static Chat getChatInstance(){
return chatInstance;
}
private Chat(UserPopulated user, SharedPreferences preferences){
slingUser = user;
this.preferences = preferences;
dataService = new DataService(preferences);
api = RestFactory.createService(preferences.getString("token",""));
requestBuilder.setLimit(100);
// chatSignUpOrIn(slingUser);
}
//
// Subscribe to Push Notifications
public void subscribeToPushNotifications(String registrationID,final CustomCallback cb) {
QBSubscription subscription = new QBSubscription(QBNotificationChannel.GCM);
subscription.setEnvironment(QBEnvironment.PRODUCTION);
//
String deviceId;
final TelephonyManager mTelephony = systemService;
if (mTelephony.getDeviceId() != null) {
deviceId = mTelephony.getDeviceId(); //*** use for mobiles
} else {
deviceId = Settings.Secure.getString(contentResolver,
Settings.Secure.ANDROID_ID); //*** use for tablets
}
subscription.setDeviceUdid(deviceId);
//
subscription.setRegistrationID(registrationID);
//
QBPushNotifications.createSubscription(subscription, new QBEntityCallback<ArrayList<QBSubscription>>() {
@Override
public void onSuccess(ArrayList<QBSubscription> subscriptions, Bundle args) {
Log.i("Push","Subscribed successfully");
cb.onCallback();
}
@Override
public void onError(QBResponseException error) {
Log.e("Push","Error " + error.getMessage());
cb.onCallback();
}
});
}
public void sendNotifications(StringifyArrayList<Integer> userIds){
Log.i("Push",userIds.get(0).toString());
QBEvent event = new QBEvent();
event.setUserIds(userIds);
event.setEnvironment(QBEnvironment.PRODUCTION);
event.setNotificationType(QBNotificationType.PUSH);
event.setPushType(QBPushType.GCM);
HashMap<String, Object> data = new HashMap<String, Object>();
data.put("data.message", "Hello");
data.put("data.type", "welcome message");
event.setMessage(data);
QBPushNotifications.createEvent(event, new QBEntityCallback<QBEvent>() {
@Override
public void onSuccess(QBEvent qbEvent, Bundle args) {
// sent
}
@Override
public void onError(QBResponseException errors) {
}
});
}
public void createSession(final CustomCallback cb){
final QBUser user = new QBUser(slingUser.getId(), slingUser.getId());
//user.setFullName(slingUser.getFirstName() + " " + slingUser.getLastName());
if(slingUser.getQuickBloxId()==null){
QBAuth.createSession(new QBEntityCallback<QBSession>() {
@Override
public void onSuccess(final QBSession session, Bundle params) {
// success, login to chat
QBUsers.signUp(user, new QBEntityCallback<QBUser>() {
@Override
public void onSuccess(final QBUser user, Bundle args) {
Log.i("QB","Sign up "+ user.getId() );
mUser = user;
slingUser.setQuickBloxId(user.getId().toString());
dataService.setUser(slingUser);
mUser.setId(user.getId());
api.updateQuickBloxId(slingUser.getId(),user.getId().toString()).enqueue(new Callback<Data<UserPopulated>>() {
@Override
public void onResponse(Call<Data<UserPopulated>> call, Response<Data<UserPopulated>> response) {
Log.i("Chat", "User signed up");
cb.onCallback();
}
@Override
public void onFailure(Call<Data<UserPopulated>> call, Throwable t) {
cb.onCallback();
}
});
}
@Override
public void onError(QBResponseException error) {
// error
Log.e("Chat","Error " + error.getMessage());
QBAuth.createSession(user, new QBEntityCallback<QBSession>() {
@Override
public void onSuccess(QBSession qbSession, Bundle bundle) {
mUser = user;
mUser.setId(qbSession.getUserId());
cb.onCallback();
Log.i("Chat", "Session created");
}
@Override
public void onError(QBResponseException e) {
Log.e("Chat Error", e.getMessage());
cb.onCallback();
}
});
}
});
}
@Override
public void onError(QBResponseException errors) {
Log.e("Chat","Error " + errors.getMessage());
cb.onCallback();
}
});
}
else{
QBAuth.createSession(user, new QBEntityCallback<QBSession>() {
@Override
public void onSuccess(QBSession qbSession, Bundle bundle) {
mUser = user;
mUser.setId(qbSession.getUserId());
cb.onCallback();
Log.i("Chat", "Session created");
}
@Override
public void onError(QBResponseException e) {
Log.e("Chat Error", e.getMessage());
cb.onCallback();
}
});
}
}
public void loadUsers(List<User> userList, CustomCallback cb){
ArrayList<User> users = new ArrayList<>(userList);
ArrayList<String> logins = new ArrayList<>();
for(User u: users){
logins.add(u.getId());
}
}
public QBUser getCurrentUser(){
return mUser;
}
public QBChatService getChatService(){
return chatService;
}
public QBUser getQbUser(String id) throws QBResponseException{
return QBUsers.getUserByLogin(id);
}
public void createDialog(int opponentId, QBEntityCallback<QBDialog> cb){
try
{
chatService.getPrivateChatManager().createDialog(opponentId,cb);
}
catch (Exception e)
{
cb.onError(null);
}
}
public QBPrivateChatManager getPrivateChatManager(){
return chatService.getPrivateChatManager();
}
public void loginChat(final CustomCallback cb){
if(chatService.isLoggedIn()){
cb.onCallback();
return;
}
chatService.login(mUser, new QBEntityCallback() {
@Override
public void onSuccess(Object o, Bundle bundle) {
cb.onCallback();
Log.i("Chat","Logged in");
}
@Override
public void onError(QBResponseException e) {
Log.e("Chat Error", e.getMessage());
}
});
}
private void chatSignUpOrIn(final UserPopulated user){
final QBUser qbUser = new QBUser(user.getId(), user.getId());
qbUser.setFullName(user.getFirstName() + " " + user.getLastName());
if(user.getQuickBloxId()==null){
Log.i("QB", "null");
QBUsers.signUp(qbUser, new QBEntityCallback<QBUser>() {
@Override
public void onSuccess(QBUser qbUser, Bundle bundle) {
user.setQuickBloxId(qbUser.getId().toString());
}
@Override
public void onError(QBResponseException e) {
}
});
}
else{
//login
}
}
public void getDialogs(final CustomCallback cb) {
QBRequestGetBuilder requestGetBuilder = new QBRequestGetBuilder();
requestGetBuilder.setLimit(100);
getChatService().getChatDialogs(QBDialogType.PRIVATE, requestGetBuilder, new QBEntityCallback<ArrayList<QBDialog>>() {
@Override
public void onSuccess(ArrayList<QBDialog> qbDialogs, Bundle bundle) {
for (final QBDialog d : qbDialogs) {
ChatDialogViewModel chatDialogViewModel = new ChatDialogViewModel();
chatDialogViewModel.setName(d.getName());
chatDialogViewModel.setLastText(d.getLastMessage());
DateTime dt = new DateTime();
chatDialogViewModel.setDate(dt.toString(DateTimeFormat.forPattern("dd MMM yyyy")));
chatDialogViewModel.setId(d.getDialogId());
dialogs.add(chatDialogViewModel);
}
Log.i("Chat Dialogs","Loaded");
if(cb!=null){
cb.onCallback();
}
}
@Override
public void onError(QBResponseException e) {
Log.e("Chat Dialogs",e.getMessage());
if(cb!=null){
cb.onCallback();
}
}
});
}
}
| true |
a50ae0c5315d84febea0a855302e0ee2461414c7
|
Java
|
duchuan1314/Du_ExamWeb
|
/Du_ExamWeb/src/dao/QuestionKuBean.java
|
UTF-8
| 7,217 | 2.375 | 2 |
[] |
no_license
|
package dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import entity.QuestionKuEntity;
public class QuestionKuBean {
public static final String mysqlusername = "root";
public static final String mysqlpassword = "123456";
public static final String classdriver = "com.mysql.jdbc.Driver";
public static final String url = "jdbc:mysql://localhost:3306/exam";
private Connection con;
private ResultSet rs;
private PreparedStatement psmt;
private Statement st;
//获得当前页面的所有用户
public List<QuestionKuEntity> getAllQuestionDatils(int currentPageNum){
int beginPageNum = (currentPageNum-1)*6;
int pageSize = 6;
List<QuestionKuEntity> questionKuEntities = new ArrayList<QuestionKuEntity>();
try {
Class.forName(classdriver);
con = DriverManager.getConnection(url, mysqlusername, mysqlpassword);
String sql = "select * from questionKu limit ?,?";
psmt = con.prepareStatement(sql);
psmt.setInt(1, beginPageNum);
psmt.setInt(2, pageSize);
rs = psmt.executeQuery();
QuestionKuEntity qkEntity = null;
while (rs.next()) {
qkEntity = new QuestionKuEntity();
qkEntity.setId(rs.getInt("id"));
qkEntity.setType_Code(rs.getInt("type_Code"));
qkEntity.setQuestionName(rs.getString("questionName"));
qkEntity.setOptionA(rs.getString("optionA"));
qkEntity.setOptionB(rs.getString("optionB"));
qkEntity.setOptionC(rs.getString("optionC"));
qkEntity.setOptionD(rs.getString("optionD"));
qkEntity.setAnswer(rs.getString("answer"));
qkEntity.setComment(rs.getString("comment"));
questionKuEntities.add(qkEntity);
}
} catch (Exception e) {
e.printStackTrace();
}
return questionKuEntities;
}
//获取记录数,得出页数
public int getPageCount() {
int total = 0;
int pageCounts = 0;
try {
Class.forName(classdriver);
con = DriverManager.getConnection(url, mysqlusername, mysqlpassword);
String sql = "select count(*) from questionKu";
st = con.createStatement();
rs = st.executeQuery(sql);
while (rs.next()) {
total = rs.getInt(1);//或得总记录数
pageCounts = (total - 1) / 6 + 1;//计算页数
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {con.close();} catch (SQLException e) {e.printStackTrace();}
}
return pageCounts;
}
public void deleteQuetionKu(int id){
try {
Class.forName(classdriver);
con = DriverManager.getConnection(url, mysqlusername, mysqlpassword);
String sql = "delete from questionKu where id=?";
psmt = con.prepareStatement(sql);
psmt.setInt(1, id);
psmt.execute();
} catch (Exception e) {
e.printStackTrace();
}finally {
try {con.close();psmt.close();} catch (SQLException e) {e.printStackTrace();}
}
}
public void addQuestionKu(int type_Code,String questionName,String optionA,String optionB,String optionC,String optionD,String answer,String comment){
try {
Class.forName(classdriver);
con = DriverManager.getConnection(url, mysqlusername, mysqlpassword);
String sql = "insert into questionKu (type_Code,questionName,optionA,optionB,optionC,optionD,answer,comment) values(?,?,?,?,?,?,?,?)";
psmt = con.prepareStatement(sql);
psmt.setInt(1, type_Code);
psmt.setString(2, questionName);
psmt.setString(3, optionA);
psmt.setString(4, optionB);
psmt.setString(5, optionC);
psmt.setString(6, optionD);
psmt.setString(7, answer);
psmt.setString(8, comment);
psmt.execute();
} catch (Exception e) {
e.printStackTrace();
}finally{try{con.close();psmt.close();}catch(Exception e){e.printStackTrace();}}
}
// 通过id获取要编辑的哪一行的值
public QuestionKuEntity EditQuestionDatils(int id){
QuestionKuEntity qkEntity = null;
try {
Class.forName(classdriver);
con = DriverManager.getConnection(url, mysqlusername, mysqlpassword);
String sql = "select * from questionKu where id=?";
psmt = con.prepareStatement(sql);
psmt.setInt(1, id);
rs = psmt.executeQuery();
while (rs.next()) {
qkEntity = new QuestionKuEntity();
qkEntity.setId(rs.getInt("id"));
qkEntity.setType_Code(rs.getInt("type_Code"));
qkEntity.setQuestionName(rs.getString("questionName"));
qkEntity.setOptionA(rs.getString("optionA"));
qkEntity.setOptionB(rs.getString("optionB"));
qkEntity.setOptionC(rs.getString("optionC"));
qkEntity.setOptionD(rs.getString("optionD"));
qkEntity.setAnswer(rs.getString("answer"));
qkEntity.setComment(rs.getString("comment"));
}
} catch (Exception e) {
e.printStackTrace();
}
finally{try {con.close();psmt.close();} catch (SQLException e) {e.printStackTrace();}}
return qkEntity;
}
public void EditQuestionDatils2(int id,int type_Code,String questionName,String optionA,String optionB,String optionC,String optionD,String answer,String comment){
try {
Class.forName(classdriver);
con = DriverManager.getConnection(url, mysqlusername, mysqlpassword);
String sql = "update questionKu set type_Code=?,questionName=?,optionA=?,optionB=?,optionC=?,optionD=?,answer=?,comment=? where id=?";
psmt = con.prepareStatement(sql);
psmt.setInt(1, type_Code);
psmt.setString(2, questionName);
psmt.setString(3, optionA);
psmt.setString(4, optionB);
psmt.setString(5, optionC);
psmt.setString(6, optionD);
psmt.setString(7, answer);
psmt.setString(8, comment);
psmt.setInt(9, id);
psmt.execute();
} catch (Exception e) {
e.printStackTrace();
}
finally{try {con.close();psmt.close();} catch (SQLException e) {e.printStackTrace();}}
}
//TestExam
public List<QuestionKuEntity> getExamQuestions(int typeCode,int questionNum){
List<QuestionKuEntity> questionKuEntities = new ArrayList<QuestionKuEntity>();
try {
Class.forName(classdriver);
con = DriverManager.getConnection(url, mysqlusername, mysqlpassword);
String sql = "select * from questionKu where type_Code = ? limit 0,?";
psmt = con.prepareStatement(sql);
psmt.setInt(1, typeCode);
psmt.setInt(2, questionNum);
rs = psmt.executeQuery();
QuestionKuEntity qkEntity = null;
while (rs.next()) {
qkEntity = new QuestionKuEntity();
qkEntity.setId(rs.getInt("id"));
qkEntity.setType_Code(rs.getInt("type_Code"));
qkEntity.setQuestionName(rs.getString("questionName"));
qkEntity.setOptionA(rs.getString("optionA"));
qkEntity.setOptionB(rs.getString("optionB"));
qkEntity.setOptionC(rs.getString("optionC"));
qkEntity.setOptionD(rs.getString("optionD"));
qkEntity.setAnswer(rs.getString("answer"));
qkEntity.setComment(rs.getString("comment"));
questionKuEntities.add(qkEntity);
}
} catch (Exception e) {
e.printStackTrace();
}
return questionKuEntities;
}
}
| true |
d909d536658c9aa9579fc8c5fc5f24fefea29818
|
Java
|
liquid-mind/warp
|
/src/exwrapper/ch/shaktipat/exwrapper/java/lang/ProcessWrapper.java
|
UTF-8
| 260 | 2.265625 | 2 |
[
"Apache-2.0"
] |
permissive
|
package ch.shaktipat.exwrapper.java.lang;
public class ProcessWrapper
{
public static int waitFor( Process process )
{
try
{
return process.waitFor();
}
catch ( InterruptedException e )
{
throw new InterruptedExceptionWrapper( e );
}
}
}
| true |
4c9256ea7a5c849e55a2c6e910f04c9ff41a81ca
|
Java
|
Agnieszka-L/agnieszka_lachendro-kodilla_tester
|
/kodilla-intro/src/main/java/RandomNumbers.java
|
UTF-8
| 872 | 3.9375 | 4 |
[] |
no_license
|
import java.util.Random;
public class RandomNumbers {
public static void main(String[] args) {
Random random = new Random();
int sum = 0;
int max = 0;
int min = 31;
while (sum <= 5000) {
int number = random.nextInt(31);
System.out.println("Wylosowana liczba to: " + number);
sum = sum + number;
System.out.println("Suma wszystkich wylosowanych liczb do tej pory to: " + sum);
if (number > max) {
max = number;
System.out.println("Aktualny maks = " + max);
}
if (number < min) {
min = number;
System.out.println("Aktualny min = " + min);
}
}
System.out.println("Finalny max = " + max);
System.out.println("Finalny min = " + min);
}
}
| true |
c49152378d229a80694d8ebff1a82526b00aa0fa
|
Java
|
muraliremod7/iFocusConnect
|
/app/src/main/java/com/app/ifocusmission/Notification.java
|
UTF-8
| 1,952 | 1.914063 | 2 |
[] |
no_license
|
package com.app.ifocusmission;
import com.app.ifcousmission.R;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
public class Notification extends Activity {
Button alert,suc_stores,event_update;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.notifications);
alert=(Button)findViewById(R.id.alert);
suc_stores=(Button)findViewById(R.id.suc_stores);
event_update =(Button)findViewById(R.id.event_updates);
ImageView btn_back=(ImageView)findViewById(R.id.btn_back);
btn_back.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
}
});
alert.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//Intent i= new Intent(getApplicationContext(), Enquries_activity.class);
//startActivity(i);
Toast.makeText(getApplicationContext(), "Alerts Coming Soon", Toast.LENGTH_LONG).show();
}
});
suc_stores.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i= new Intent(getApplicationContext(), Webview.class);
startActivity(i);
}
});
event_update.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i= new Intent(getApplicationContext(), Webview_events_update.class);
startActivity(i);
//Toast.makeText(getApplicationContext(), "Events Updates are Coming Soon", Toast.LENGTH_LONG).show();
}
});
}
}
| true |
eda4363f78760a784e673607522c0c490003eeab
|
Java
|
yukungao/InTheaterNow
|
/boxbuster1/src/main/java/com/yukun/boxbuster1/http/entity/HttpTicket.java
|
UTF-8
| 684 | 2.359375 | 2 |
[] |
no_license
|
package com.yukun.boxbuster1.http.entity;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import com.yukun.boxbuster1.entity.Ticket;
@XmlRootElement(name = "ticket")
public class HttpTicket {
@XmlElement
public long id;
@XmlElement
public long movieId;
@XmlElement
public long theaterId;
@XmlElement
public double price;
@XmlElement
public boolean status;
protected HttpTicket() {
}
public HttpTicket(Ticket ticket) {
this.id = ticket.getId();
this.movieId = ticket.getMovie().getId();
this.theaterId = ticket.getTheater().getId();
this.price = ticket.getPrice();
this.status = ticket.getStatus();
}
}
| true |
0a0eaccef4aa6540020840c1cf18375739b84358
|
Java
|
shulieTech/Takin-web
|
/takin-web-entrypoint/src/main/java/io/shulie/takin/web/entrypoint/controller/dashboard/WorkBenchController.java
|
UTF-8
| 1,852 | 1.984375 | 2 |
[] |
no_license
|
package io.shulie.takin.web.entrypoint.controller.dashboard;
import java.util.List;
import javax.annotation.Resource;
import io.shulie.takin.common.beans.annotation.ActionTypeEnum;
import io.shulie.takin.common.beans.annotation.AuthVerification;
import io.shulie.takin.web.biz.constant.BizOpConstants;
import io.shulie.takin.web.biz.pojo.response.dashboard.QuickAccessResponse;
import io.shulie.takin.web.biz.pojo.response.dashboard.UserWorkBenchResponse;
import io.shulie.takin.web.biz.service.dashboard.QuickAccessService;
import io.shulie.takin.web.biz.service.dashboard.WorkBenchService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author mubai
* @date 2020-06-28 17:56
*/
@RestController
@RequestMapping("api/workbench")
@Api(tags = "WorkBenchController", value = "工作台接口")
@Slf4j
public class WorkBenchController {
@Resource
private WorkBenchService workBenchService;
@Resource
private QuickAccessService quickAccessService;
@GetMapping("user")
@AuthVerification(
moduleCode = BizOpConstants.ModuleCode.DASHBOARD_APPMANAGE,
needAuth = ActionTypeEnum.QUERY
)
public UserWorkBenchResponse workBench() {
try {
return workBenchService.getWorkBench();
} catch (Exception e) {
log.error("获取工作台数据失败", e);
throw e;
}
}
@GetMapping("user/access")
public List<QuickAccessResponse> quickAccess() {
try {
return quickAccessService.list();
} catch (Exception e) {
log.error("获取快捷入口失败", e);
throw e;
}
}
}
| true |
e32bc8917c17ddfa7dd97a3eea4db4764886fbdd
|
Java
|
hivemq/hivemq-community-edition
|
/src/test/java/com/hivemq/mqtt/handler/connect/NoTlsHandshakeIdleHandlerTest.java
|
UTF-8
| 4,097 | 1.960938 | 2 |
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright 2019-present HiveMQ GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hivemq.mqtt.handler.connect;
import com.hivemq.bootstrap.ClientConnectionContext;
import com.hivemq.bootstrap.UndefinedClientConnection;
import com.hivemq.configuration.service.entity.Listener;
import com.hivemq.configuration.service.entity.TlsTcpListener;
import com.hivemq.mqtt.handler.disconnect.MqttServerDisconnector;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.embedded.EmbeddedChannel;
import org.junit.Before;
import org.junit.Test;
import java.util.concurrent.atomic.AtomicBoolean;
import static io.netty.handler.timeout.IdleStateEvent.FIRST_READER_IDLE_STATE_EVENT;
import static io.netty.handler.timeout.IdleStateEvent.FIRST_WRITER_IDLE_STATE_EVENT;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* @author Florian Limpöck
*/
@SuppressWarnings("NullabilityAnnotations")
public class NoTlsHandshakeIdleHandlerTest {
private MqttServerDisconnector mqttServerDisconnector;
private NoTlsHandshakeIdleHandler handler;
private EmbeddedChannel channel;
private AtomicBoolean userEventTriggered;
private final Listener connectedListener = mock(TlsTcpListener.class);
@Before
public void setUp() throws Exception {
mqttServerDisconnector = mock(MqttServerDisconnector.class);
handler = new NoTlsHandshakeIdleHandler(mqttServerDisconnector);
userEventTriggered = new AtomicBoolean(false);
final ChannelInboundHandlerAdapter eventAdapter = new ChannelInboundHandlerAdapter() {
@Override
public void userEventTriggered(final ChannelHandlerContext ctx, final Object evt) {
userEventTriggered.set(true);
}
};
channel = new EmbeddedChannel();
final ClientConnectionContext clientConnection =
new UndefinedClientConnection(channel, null, connectedListener);
channel.attr(ClientConnectionContext.CHANNEL_ATTRIBUTE_NAME).set(clientConnection);
channel.pipeline().addLast(handler);
channel.pipeline().addLast(eventAdapter);
}
@Test
public void test_nothing_happens_for_non_idle_state_event() throws Exception {
handler.userEventTriggered(channel.pipeline().context(handler), "SomeEvent");
verify(mqttServerDisconnector, never()).logAndClose(any(Channel.class), any(), any());
assertTrue(userEventTriggered.get());
}
@Test
public void test_nothing_happens_for_idle_state_writer_event() throws Exception {
handler.userEventTriggered(channel.pipeline().context(handler), FIRST_WRITER_IDLE_STATE_EVENT);
verify(mqttServerDisconnector, never()).logAndClose(any(Channel.class), any(), any());
assertTrue(userEventTriggered.get());
}
@Test
public void test_idle_state_reader_event() throws Exception {
when(connectedListener.getPort()).thenReturn(1234);
handler.userEventTriggered(channel.pipeline().context(handler), FIRST_READER_IDLE_STATE_EVENT);
verify(mqttServerDisconnector, times(1)).logAndClose(any(Channel.class), any(), any());
assertFalse(userEventTriggered.get());
}
}
| true |
e147bf53b9103dd30fb381f8e27ee6e9a005432a
|
Java
|
AybarsAcar/RecipeProjectJavaMVC
|
/src/main/java/dev/aybarsacar/recipeproject/repositories/CategoryRepository.java
|
UTF-8
| 564 | 2.328125 | 2 |
[] |
no_license
|
package dev.aybarsacar.recipeproject.repositories;
import dev.aybarsacar.recipeproject.domain.Category;
import org.springframework.data.repository.CrudRepository;
import java.util.Optional;
/**
* this is hte Repository we specify our query methods to interact with the db
* Repository layer
*/
public interface CategoryRepository extends CrudRepository<Category, Long>
{
/**
* using optional return type to avoid errors with null type returns
*
* @param description
* @return
*/
Optional<Category> findByDescription(String description);
}
| true |
36474087df268690a28087fc867da69859bf3c78
|
Java
|
pan1394/SqlParser
|
/Bee/src/com/linkstec/bee/core/codec/basic/BasicScannerPath.java
|
UTF-8
| 734 | 1.960938 | 2 |
[] |
no_license
|
package com.linkstec.bee.core.codec.basic;
import com.linkstec.bee.core.fw.BParameter;
import com.linkstec.bee.core.fw.logic.BLogicBody;
public class BasicScannerPath {
private BasicScannerPath parent;
private BParameter parameter;
private BLogicBody body;
public BasicScannerPath() {
}
public BLogicBody getBody() {
return body;
}
public void setBody(BLogicBody body) {
this.body = body;
}
public BParameter getParameter() {
return parameter;
}
public void setParameter(BParameter parameter) {
this.parameter = parameter;
}
public BasicScannerPath getParent() {
return parent;
}
public void setParent(BasicScannerPath parent) {
this.parent = parent;
}
}
| true |
80bf33bd7254068c58b93ba844ae9ddbd37ed0b6
|
Java
|
ArundhadiyarSagar/github
|
/LeftRotate.java
|
UTF-8
| 587 | 3.765625 | 4 |
[] |
no_license
|
package com.arrayPrograms;
public class LeftRotate {
public static void main(String[] args) {
int arr[] = new int[] {1,2,3,4,5};
System.out.println("Elements of The Array");
for(int i=0;i<arr.length;i++) {
System.out.print(" " + arr[i]);
}
int n=1; //Times of LEFT Rotation
for(int i=0;i<n;i++) {
int j,first;
first = arr[0];
for(j=0;j<arr.length-1;j++) {
arr[j]=arr[j+1];
}
arr[j]=first;
}
System.out.println("\nLeft Rotate of The Array");
for(int i=0;i<arr.length;i++) {
System.out.print(" " + arr[i]);
}
}
}
| true |
c2a8f6867d7c6c9a7ba9c19791f02880f3c8eff5
|
Java
|
SpreadWater/LastClassDemo
|
/app/src/main/java/com/example/lastclassdemo/adapter/RecordPagerAdapter.java
|
UTF-8
| 987 | 2.375 | 2 |
[] |
no_license
|
package com.example.lastclassdemo.adapter;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import java.util.List;
/**
* @author SpreadWater
* @Date 2020-12-04
* @Time 21:41
* @description
*/
public class RecordPagerAdapter extends FragmentPagerAdapter {
List<Fragment> fragmentList;
String[] titles = {"支出", "收入"};
public RecordPagerAdapter(@NonNull FragmentManager fm, List<Fragment> fragmentList) {
super(fm);
this.fragmentList = fragmentList;
}
@NonNull
@Override
public Fragment getItem(int position) {
return fragmentList.get(position);
}
@Override
public int getCount() {
return fragmentList.size();
}
@Nullable
@Override
public CharSequence getPageTitle(int position) {
return titles[position];
}
}
| true |
db29dee81f8db5b5d1eaddf80e1dffadcf42ee9e
|
Java
|
abarbay/YR
|
/Java/genericmethod/src/main/java/genericmethod/ArrayMiddleObjectFinder.java
|
UTF-8
| 487 | 3.21875 | 3 |
[] |
no_license
|
package genericmethod;
public class ArrayMiddleObjectFinder {
public <T> T findMiddleObject(T... arr) throws IllegalArgumentException {
if (arr == null) {
throw new NullPointerException();
}
if (arr.length == 0) {
throw new IllegalArgumentException();
}
if (arr.length % 2 == 0) {
throw new IllegalArgumentException("Even number of elements");
}
return arr[(arr.length - 1) / 2];
}
}
| true |
d9b5e260461767e34b079a03a0d757ffcd32bf8f
|
Java
|
Reekdnroxx7/inventory
|
/codes/admin/src/main/java/com/x404/admin/manage/sys/tools/ClientSort.java
|
UTF-8
| 289 | 1.921875 | 2 |
[] |
no_license
|
package com.x404.admin.manage.sys.tools;
import java.util.Comparator;
public class ClientSort implements Comparator<UserInfo> {
public int compare(UserInfo prev, UserInfo now) {
return (int) (now.getLogindatetime().getTime() - prev.getLogindatetime().getTime());
}
}
| true |
c399955035c38e51ea1717893b1a20ac691ecc4c
|
Java
|
joncruz96/SistemaEscolaCore
|
/src/main/java/com/totvs/escola/core/turma/exception/AlunosTurmaNotFoundException.java
|
UTF-8
| 494 | 1.929688 | 2 |
[] |
no_license
|
package com.totvs.escola.core.turma.exception;
import com.totvs.tjf.api.context.stereotype.ApiErrorParameter;
import com.totvs.tjf.api.context.stereotype.error.ApiBadRequest;
@ApiBadRequest("AlunosTurmaNotFoundException")
public class AlunosTurmaNotFoundException extends RuntimeException {
private static final long serialVersionUID = 2100396918453973429L;
@ApiErrorParameter
private final String aluno;
public AlunosTurmaNotFoundException(String aluno) {
this.aluno = aluno;
}
}
| true |
a851de5b46ae22ef5adf57ccd742e285c8441d6c
|
Java
|
cenbow/pop
|
/pop/src/com/ai/bdx/pop/service/impl/PopReceiveCepDataHandlerImpl.java
|
UTF-8
| 3,199 | 2.078125 | 2 |
[] |
no_license
|
package com.ai.bdx.pop.service.impl;
import net.sf.json.JSONObject;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.ai.bdx.pop.buffer.IDataHandle;
import com.ai.bdx.pop.model.PopPolicyBaseinfo;
import com.ai.bdx.pop.model.PopPolicyRule;
import com.ai.bdx.pop.service.IPopSendOddService;
import com.ai.bdx.pop.util.ContactControlUtil;
import com.ai.bdx.pop.util.PopConstant;
import com.ai.bdx.pop.util.SpringContext;
import com.ai.bdx.pop.wsclient.ISendPccInfoService;
import com.ai.bdx.pop.wsclient.PolicyOptType;
import com.asiainfo.biframe.utils.string.StringUtil;
/***
* 接收cep返回结果数据逻辑handler
* @author liyz
* */
public class PopReceiveCepDataHandlerImpl implements IDataHandle{
private static Logger log = LogManager.getLogger(PopReceiveCepDataHandlerImpl.class);
private IPopSendOddService popSendOddService;
public IPopSendOddService getPopSendOddService() {
return popSendOddService;
}
public void setPopSendOddService(IPopSendOddService popSendOddService) {
this.popSendOddService = popSendOddService;
}
@Override
public void handle(JSONObject msg) {
try{
//入库处理 2张表 POP_RULE_SEND_ruleid(xxxx) POP_SEND_taskid(xxxx)
String ruleId = (String) msg.get("rule_id");
String phone_no = (String) msg.get("phone_no");
String taskId = ContactControlUtil.getCurrentTaskId(ruleId);
String ruleSendTableName = ContactControlUtil.getRuleSendTableNameForRuleId(ruleId);
String taskSendTableName = ContactControlUtil.getTaskSendTableNameForTaskId(taskId,ruleId);
if(StringUtil.isNotEmpty(ruleSendTableName) && StringUtil.isNotEmpty(taskSendTableName) ){
String ruleSendSql = PopConstant.INSERT_DATA_TO_TABLE.replace("{table}", ruleSendTableName).replace("{column}", "(product_no)").replace("{?}", "(?)");
String taskSendSql = PopConstant.INSERT_DATA_TO_TABLE.replace("{table}", taskSendTableName).replace("{column}", "(product_no)").replace("{?}", "(?)");
//POP_RULE_SEND_
popSendOddService.saveDataToDbForSql(ruleSendSql, new Object[]{phone_no});
//POP_SEND_
popSendOddService.saveDataToDbForSql(taskSendSql, new Object[]{phone_no});
//log.debug("执行sql:"+taskSendSql);
//add by jinl 20150819 根据需求增加参数 策略级别
PopPolicyRule rule = PopPolicyRule.dao().findById(ruleId);
String policy_level_id="";
if(rule!=null){
String policyId=rule.getStr(PopPolicyRule.COL_POLICY_ID);
PopPolicyBaseinfo baseInfo = PopPolicyBaseinfo.dao().findById(policyId);
if(baseInfo!=null){
policy_level_id = baseInfo.get(PopPolicyBaseinfo.COL_POLICY_LEVEL_ID).toString();
}
}
//实时派单接口拍到PCC
ISendPccInfoService sendPccInfoService = SpringContext.getBean("sendPccInfoService",ISendPccInfoService.class);
sendPccInfoService.singlePhoneOpt( PolicyOptType.OPEN.getValue(), phone_no, ruleId,policy_level_id);
log.info("phone_no={} ruleId={} policy_level_id={}",phone_no,ruleId,policy_level_id);
}else{
log.error("ruleSendTableName,taskSendTableName 是 null!当前ruleId:"+ruleId+"++++taskId:"+taskId);
}
}catch(Exception e){
e.printStackTrace();
}
}
}
| true |
7f82ef8959e11ec17aac898e5796fa554c4bbdb2
|
Java
|
Kurisasa/MyApplication
|
/app/src/main/java/com/example/myapplication/adapters/InvoiceDateAdapter.java
|
UTF-8
| 3,633 | 2.46875 | 2 |
[] |
no_license
|
package com.example.myapplication.adapters;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.example.myapplication.R;
import com.example.myapplication.model.DateModel;
import com.example.myapplication.utils.CommonFunctions;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
/**
* Created by manish on 17/7/18.
*/
public class InvoiceDateAdapter extends RecyclerView.Adapter<InvoiceDateAdapter.InvoiceViewHolder>{
Context context;
private ArrayList<DateModel> dateModels;
OnSelectedDateListener onSelectedDateListener;
public InvoiceDateAdapter(Context context, ArrayList<DateModel> dateModels, OnSelectedDateListener onSelectedDateListener){
this.context = context;
this.dateModels = dateModels;
this.onSelectedDateListener = onSelectedDateListener;
}
@NonNull
@Override
public InvoiceViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.date_list_row,parent,false);
return new InvoiceViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull InvoiceViewHolder holder, int position) {
final DateModel dateModel = dateModels.get(position);
holder.date_text.setText(convertStringToData(dateModel.getDate()));
/*try{
SimpleDateFormat sd1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
Date dt = sd1.parse(dateModel.getDate());
SimpleDateFormat sd2 = new SimpleDateFormat("dd-mmm-yyyy");
String newDate = sd2.format(dt);
}catch (Exception ex){
ex.printStackTrace();
}*/
holder.date_text.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onSelectedDateListener.selectedDate(dateModel);
}
});
}
public static String convertStringToData(String stringData) {
SimpleDateFormat originalFormat = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat targetFormat = new SimpleDateFormat("dd MMM yyyy" );
Date date;
String oldformat,newformat;
try {
date = originalFormat.parse(stringData);
oldformat = originalFormat.format(date);
newformat = targetFormat.format(date);
System.out.println("Old Format : " + originalFormat.format(date));
System.out.println("New Format : " + targetFormat.format(date));
return newformat;
} catch (ParseException ex) {
// Handle Exception.
}
return stringData;
}
@Override
public int getItemCount() {
if (dateModels != null)
return dateModels.size();
else
return 0;
}
public class InvoiceViewHolder extends RecyclerView.ViewHolder{
TextView date_text, calendar_icon;
public InvoiceViewHolder(View view){
super(view);
calendar_icon = view.findViewById(R.id.calendar_icon);
date_text = view.findViewById(R.id.tv_invoice_date);
calendar_icon.setTypeface(CommonFunctions.setFontIcon(context));
calendar_icon.setText("J");
}
}
public interface OnSelectedDateListener{
void selectedDate(DateModel dateModel);
}
}
| true |
ce599508aacb848672170dff24c351794ed2634a
|
Java
|
keyur2714/Design-Pattern-With-Java
|
/FlyWeightDesignPatternDemo/src/com/webstack/dp/VehicleFactory.java
|
UTF-8
| 992 | 2.859375 | 3 |
[] |
no_license
|
package com.webstack.dp;
import java.util.HashMap;
import java.util.Map;
import com.webstack.dto.HeroBike;
import com.webstack.dto.HyundaiCar;
import com.webstack.dto.SuzukiBike;
import com.webstack.dto.TataCar;
import com.webstack.dto.Vehicle;
public class VehicleFactory {
static Map<String,Vehicle> vehicleMaps = new HashMap<>();
public static Vehicle getVehicle(String type,String color) throws Exception{
Vehicle vehicle = null;
if(vehicleMaps.containsKey(type+"_"+color)) {
vehicle = vehicleMaps.get(type+"_"+color);
}else {
switch (type) {
case "HyundaiCar":
vehicle = new HyundaiCar(color);
break;
case "TataCar":
vehicle = new TataCar(color);
break;
case "SuzukiBike":
vehicle = new SuzukiBike(color);
break;
case "HeroBike":
vehicle = new HeroBike(color);
break;
default:
throw new Exception("Object type Not Found...!");
}
vehicleMaps.put(type+"_"+color,vehicle);
}
return vehicle;
}
}
| true |
c9c821d4e17233f37e135cd5ffad9a88465969d1
|
Java
|
slimmtl/cellbase
|
/cellbase-server/src/main/java/org/opencb/cellbase/server/ws/regulatory/RegulatoryWSServer.java
|
UTF-8
| 5,155 | 1.976563 | 2 |
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright 2015 OpenCB
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.opencb.cellbase.server.ws.regulatory;
import io.swagger.annotations.*;
import org.opencb.cellbase.core.api.RegulationDBAdaptor;
import org.opencb.cellbase.server.exception.SpeciesException;
import org.opencb.cellbase.server.exception.VersionException;
import org.opencb.cellbase.server.ws.GenericRestWSServer;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import java.io.IOException;
@Path("/{version}/{species}/regulatory")
@Produces("text/plain")
@Api(value = "Regulation", description = "Gene expression regulation RESTful Web Services API")
public class RegulatoryWSServer extends GenericRestWSServer {
public RegulatoryWSServer(@PathParam("version")
@ApiParam(name = "version", value = "Use 'latest' for last stable version",
defaultValue = "latest") String version,
@PathParam("species")
@ApiParam(name = "species", value = "Name of the species, e.g.: hsapiens. For a full list "
+ "of potentially available species ids, please refer to: "
+ "http://bioinfo.hpc.cam.ac.uk/cellbase/webservices/rest/latest/meta/species") String species,
@Context UriInfo uriInfo,
@Context HttpServletRequest hsr) throws VersionException, SpeciesException, IOException {
super(version, species, uriInfo, hsr);
}
@GET
@Path("/featureType")
@ApiOperation(httpMethod = "GET", value = "Retrieves a list of available regulatory feature types",
response = String.class, responseContainer = "QueryResponse")
@ApiImplicitParams({
@ApiImplicitParam(name = "region",
value = "Comma separated list of genomic regions to be queried, e.g.: 1:6635137-6635325",
required = false, dataType = "list of strings", paramType = "query"),
@ApiImplicitParam(name = "featureClass",
value = "Comma separated list of regulatory region classes, e.g.: "
+ "Histone,Transcription Factor. Exact text matches will be returned. For a full"
+ "list of available regulatory types: "
+ "http://bioinfo.hpc.cam.ac.uk/cellbase/webservices/rest/latest/hsapiens/regulatory/featureClass",
required = false, dataType = "list of strings", paramType = "query")
})
public Response getFeatureTypes() {
try {
parseQueryParams();
RegulationDBAdaptor regulationDBAdaptor = dbAdaptorFactory2.getRegulationDBAdaptor(this.species, this.assembly);
return createOkResponse(regulationDBAdaptor.distinct(query, "featureType"));
} catch (Exception e) {
return createErrorResponse(e);
}
}
@GET
@Path("/featureClass")
@ApiOperation(httpMethod = "GET", value = "Retrieves a list of available regulatory feature classes",
response = String.class, responseContainer = "QueryResponse")
@ApiImplicitParams({
@ApiImplicitParam(name = "region",
value = "Comma separated list of genomic regions to be queried, e.g.: 1:6635137-6635325",
required = false, dataType = "list of strings", paramType = "query"),
@ApiImplicitParam(name = "featureType",
value = "Comma separated list of regulatory region types, e.g.: "
+ "TF_binding_site,histone_acetylation_site. Exact text matches will be returned. For a full"
+ "list of available regulatory types: "
+ "http://bioinfo.hpc.cam.ac.uk/cellbase/webservices/rest/latest/hsapiens/regulatory/featureType\n ",
required = false, dataType = "list of strings", paramType = "query")
})
public Response getFeatureClasses() {
try {
parseQueryParams();
RegulationDBAdaptor regulationDBAdaptor = dbAdaptorFactory2.getRegulationDBAdaptor(this.species, this.assembly);
return createOkResponse(regulationDBAdaptor.distinct(query, "featureClass"));
} catch (Exception e) {
return createErrorResponse(e);
}
}
}
| true |
c6b8bb7b81559dbb2cc2a26b6db112b6fef10f41
|
Java
|
MyCloudream/java1017
|
/HelloJava/src/cn/ucai/day09/p9/Person.java
|
WINDOWS-1252
| 132 | 1.953125 | 2 |
[] |
no_license
|
package cn.ucai.day09.p9;
public class Person {
public static void m(){
System.out.println("Personľ̬m");
}
}
| true |
c1663a1789eb7fb9ee56902787a3e4b08ca5d839
|
Java
|
CristianRad/Simulare
|
/src/Service/BillService.java
|
UTF-8
| 959 | 2.890625 | 3 |
[] |
no_license
|
package Service;
import Domain.Bill;
import Repository.BillRepository;
import java.util.List;
public class BillService {
private BillRepository billRepository;
/**
* Instantiates a service for bills.
* @param billRepository is the repository used.
*/
public BillService(BillRepository billRepository) {
this.billRepository = billRepository;
}
/**
* Adds a bill.
* @param id is the ID of the bill to add.
* @param sum is the sum of the bill to add.
* @param description is the description of the bill to add.
* @param date is the date of the bill to add.
*/
public void addBill(String id, int sum, String description, String date) {
Bill bill = new Bill(id, sum, description, date);
billRepository.insert(bill);
}
/**
* @return a list of all bills.
*/
public List<Bill> getAllBills() {
return billRepository.getAll();
}
}
| true |
5b45afff1a81db7c08cca4e02205acedee8c1a77
|
Java
|
fredyw/coding4fun
|
/src/main/java/coding4fun/Problem7.java
|
UTF-8
| 622 | 3.84375 | 4 |
[
"MIT"
] |
permissive
|
package coding4fun;
/**
* Reverse a string in-place.
* <p>
* Input: Hi there, hello world
* Output: dlrow olleh ,ereht iH
*/
public class Problem7 {
private static void reverse(char[] string) {
for (int i = 0; i < string.length / 2; i++) {
char tmp = string[i];
string[i] = string[string.length - 1 - i];
string[string.length - 1 - i] = tmp;
}
}
public static void main(String[] args) {
String str = "Hi there, hello world";
char[] chrArray = str.toCharArray();
reverse(chrArray);
System.out.println(chrArray);
}
}
| true |
07a01ef00bcec47b7ae7244f87d05bb0f02d8e5a
|
Java
|
thuhiensp/Generator
|
/output/PFontFaceSet.java
|
UTF-8
| 4,006 | 1.773438 | 2 |
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright 2019 SmartTrade Technologies
* Pony SDK
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.ponysdk.core.ui2;
import com.ponysdk.core.model.ServerToClientModel;
import com.ponysdk.core.writer.ModelWriter;
import com.ponysdk.core.server.application.UIContext;
import java.util.Objects;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.function.Consumer;
public class PFontFaceSet extends PEventTarget {
private static final Logger log = LoggerFactory.getLogger(PFontFaceSet.class);
private PFontFaceSet(){
}
public void setOnloading(final PEventHandlerNonNull onloading, final PEventAttributesName... atrsEventName) {
setAttribute(PAttributeNames.ONLOADING, new AttributeCallBack(onloading, atrsEventName));
log.info("onloading" + onloading.getClass().getName());
}
public void setOnloadingdone(final PEventHandlerNonNull onloadingdone, final PEventAttributesName... atrsEventName) {
setAttribute(PAttributeNames.ONLOADINGDONE, new AttributeCallBack(onloadingdone, atrsEventName));
log.info("onloadingdone" + onloadingdone.getClass().getName());
}
public void setOnloadingerror(final PEventHandlerNonNull onloadingerror, final PEventAttributesName... atrsEventName) {
setAttribute(PAttributeNames.ONLOADINGERROR, new AttributeCallBack(onloadingerror, atrsEventName));
log.info("onloadingerror" + onloadingerror.getClass().getName());
}
public PEventHandlerNonNull getOnloading(){
return (PEventHandlerNonNull) getAttribute(PAttributeNames.ONLOADING);
}
public PEventHandlerNonNull getOnloadingdone(){
return (PEventHandlerNonNull) getAttribute(PAttributeNames.ONLOADINGDONE);
}
public PEventHandlerNonNull getOnloadingerror(){
return (PEventHandlerNonNull) getAttribute(PAttributeNames.ONLOADINGERROR);
}
@Override
protected PLeafTypeNoArgs widgetNoArgs() {
return null;
}
@Override
protected PLeafTypeWithArgs widgetWithArgs() {
return null;
}
public void check(final Consumer<Boolean> cback,String font){
cbacksSequence++;
cbacks.put(cbacksSequence, cback);
final ModelWriter writer = UIContext.get().getWriter();
writer.beginPObject2();
writer.write(ServerToClientModel.POBJECT2_METHOD, getID());
writer.write(ServerToClientModel.POBJECT2_NUM_METHOD, PMethodNames.CHECK_TYPESTRING_BOOLEAN.getValue());
writer.write(ServerToClientModel.POBJECT2_METHOD_CALLBACK, cbacksSequence);
writer.write(ServerToClientModel.POBJECT2_ARRAY_ARGUMENTS, new Object[] {font});
writer.endObject();
}
public void check(final Consumer<Boolean> cback,String font, String text){
cbacksSequence++;
cbacks.put(cbacksSequence, cback);
final ModelWriter writer = UIContext.get().getWriter();
writer.beginPObject2();
writer.write(ServerToClientModel.POBJECT2_METHOD, getID());
writer.write(ServerToClientModel.POBJECT2_NUM_METHOD, PMethodNames.CHECK_TYPESTRING_TYPESTRING_BOOLEAN.getValue());
writer.write(ServerToClientModel.POBJECT2_METHOD_CALLBACK, cbacksSequence);
writer.write(ServerToClientModel.POBJECT2_ARRAY_ARGUMENTS, new Object[] {font,text});
writer.endObject();
}
public PPromise<PFontFace[]> load(String font) {
return null;
}
public PPromise<PFontFace[]> load(String font, String text) {
return null;
}
}
| true |
b466261318c7dcdc9e2e894a16f2ca363041b11d
|
Java
|
srad/LiquidSands
|
/src/de/frankfurt/uni/vcp/net/Info.java
|
UTF-8
| 1,474 | 3.3125 | 3 |
[] |
no_license
|
package de.frankfurt.uni.vcp.net;
import java.lang.reflect.Field;
import java.util.HashMap;
/**
* <h3> This is the base class, from which all other network relevant information
* datastructures are inherited. </h3>
*
* <p> To prepare for a more or less easy mapping between network-messages and
* corresponding info-datastructures the string value given to the constructor
* will be split into "key=value", wich are inserted in a hash-table.
* </p>
*/
public class Info {
HashMap<String,String> tags = new HashMap<String,String>();
/**
* <h3> Create a new Info instance. </h3>
*
* <p> The string given will be split at spaces. </p>
* <p> Every part of the form key=value" will be inserted in a hash
* map as mapping "key" to "value"
*
* @param string The string, from which to initialize key-value mappings
*/
public Info (String string) {
for (String part : string.split(" ")){
String[] s = part.split ("=");
String key = s[0];
String value = (s.length > 1)? s[1] : "";
tags.put(key, value);
}
}
/**
* Dump the contents of all fields of this class.
*/
@Override
public String toString() {
String s = getClass().getSimpleName() + ":";
for (Field f : getClass().getDeclaredFields()) {
try {
s += " " + f.getName() + "=" + f.get(this);
} catch (Exception e) { }
}
return s;
}
}
| true |
5208e0bce81fee02996e205ddee48cb952e4ff9d
|
Java
|
kkaren/BasesDadesAvan_Practiques
|
/Practica1_BDA/src/practica1_bda/Usuari.java
|
UTF-8
| 2,035 | 2.75 | 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 practica1_bda;
import java.io.Serializable;
import javax.persistence.*;
/**
* Classe usuari
* @author Karen i Judit
*/
@Entity
@Table(name="USUARI")
public class Usuari implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="id")
private Integer id;
@Column(name="usr")
private String nom_usuari;
@Column(name="pwd")
private String password;
/**
* Constructor buit
*/
public Usuari() {
super();
// TODO Auto-generated constructor stub
}
/**
* Constructor amb tots els paramaetres
* @param id
* @param nom_usuari
* @param password
*/
public Usuari(Integer id, String nom_usuari, String password) {
super();
this.id = id;
this.nom_usuari = nom_usuari;
this.password = password;
}
/**
* Constructor sense id, es genera automaticament
* @param nom_usuari
* @param password
*/
public Usuari(String nom_usuari, String password) {
super();
this.nom_usuari = nom_usuari;
this.password = password;
}
/**
*
* @return
*/
public Integer getId() {
return id;
}
/**
*
* @param id
*/
public void setId(Integer id) {
this.id = id;
}
/**
*
* @return
*/
public String getNom_usuari() {
return nom_usuari;
}
/**
*
* @param nom_usuari
*/
public void setNom_usuari(String nom_usuari) {
this.nom_usuari = nom_usuari;
}
/**
*
* @return
*/
public String getPassword() {
return password;
}
/**
*
* @param password
*/
public void setPassword(String password) {
this.password = password;
}
}
| true |
78b3dd9dc9f41f2d6da31752b624a9840ec1b3ff
|
Java
|
niyueming/baseContextLibrary
|
/src/main/java/net/nym/basecontextlibrary/common/NBaseApplication.java
|
UTF-8
| 1,423 | 2.21875 | 2 |
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright (c) 2017 Ni YueMing<[email protected]>
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*
*/
package net.nym.basecontextlibrary.common;
import android.app.Activity;
import android.app.Application;
import android.content.res.Resources;
/**
* @author niyueming
* @date 2017-03-15
* @time 15:25
*/
public class NBaseApplication extends Application implements ActivityLifecycleMonitor.OnForegroundListener {
public static NBaseApplication app;
@Override
public void onCreate() {
super.onCreate();
app = this;
registerActivityLifecycleCallbacks(new ActivityLifecycleMonitor(this));
}
public Resources getAppResources(){
return app.getResources();
}
@Override
public void onForeground(Activity activity) {
System.out.println("前台");
}
@Override
public void onBackground(Activity activity) {
System.out.println("后台");
}
}
| true |
37326ef6a7d088fbc1b4151c983c64a3bc4e3c6b
|
Java
|
gargk981/DailyQuestions
|
/CntSAMaxEleGrtThanK.java
|
UTF-8
| 700 | 3.1875 | 3 |
[] |
no_license
|
package classDSQuestions;
import java.util.*;
public class CntSAMaxEleGrtThanK {
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
System.out.print("Enter number of elements you want to enter in array: ");
int n=sc.nextInt();
int[] arr=new int[n];
System.out.println("Enter array elements:");
for(int i=0;i<n;i++)
arr[i]=sc.nextInt();
System.out.print("Enter value of k: ");
int k=sc.nextInt();
int count=0;
for(int i=0;i<n;i++){
for(int j=i;j<n;j++){
int max=0;
for(int t=i;t<=j;t++){
if(arr[t]>max)
max=arr[t];
}
if(max>k)
count++;
}
}
System.out.print(count);
}
}
| true |
d337c41b0dc2724b182916e1b8198170b491a83b
|
Java
|
pablohayden/address-book-rest-api
|
/src/main/java/com/pablo/addressbook/AddressBook.java
|
UTF-8
| 902 | 2.703125 | 3 |
[] |
no_license
|
package com.pablo.addressbook;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import com.fasterxml.jackson.annotation.JsonIgnore;
public class AddressBook {
private List<Contact> contacts = new ArrayList<Contact>();
private Filter filter;
public AddressBook() {
}
public AddressBook(List<Contact> contacts) {
this.contacts = contacts;
}
public List<Contact> getContacts() {
return contacts;
}
public void setContacts(List<Contact> contacts) {
this.contacts = contacts;
}
public Filter getFilter() {
return filter;
}
@JsonIgnore
public void applyFilter(Filter filter) {
this.filter = filter;
String regex = "(?i:.*" + filter.getName() + ".*)";
this.contacts = this.contacts.stream()
.filter(contact -> contact.getName().matches(regex))
.collect(Collectors.toList());
}
}
| true |
231049162567993f184e49eafe5ffcc0ee270144
|
Java
|
addurisimhadri/batchprocess
|
/src/main/java/com/sim/batchprocessing/dao/SongMetaContentRepository.java
|
UTF-8
| 368 | 1.757813 | 2 |
[] |
no_license
|
package com.sim.batchprocessing.dao;
import org.springframework.data.jpa.repository.JpaRepository;
import com.sim.batchprocessing.entity.SongContentId;
import com.sim.batchprocessing.entity.SongMeta;
public interface SongMetaContentRepository extends JpaRepository<SongMeta, SongContentId> {
SongMeta findBySmIdAndContentTypeId(int smId, int contentTypeId);
}
| true |
c702ee7da49a097bb080410fc7933a383c99a71d
|
Java
|
laivizhu/laivizhu.github.io
|
/knowledge/src/com/laivi/knowledge/basic/model/po/JsonEntity.java
|
UTF-8
| 184 | 1.757813 | 2 |
[] |
no_license
|
package com.laivi.knowledge.basic.model.po;
/**
* User: [email protected] Time: 12-8-15 下午4:20
*/
public interface JsonEntity {
String toJson();
String toFormJson(boolean success);
}
| true |
2e20382526cc79328e221d5d0846c2adffdca2c0
|
Java
|
renallen/Algrithom
|
/DataStructAndAlgorithm/src/com/bob/Offer/swap.java
|
UTF-8
| 161 | 2.609375 | 3 |
[] |
no_license
|
package com.bob.Offer;
public class swap {
public void swap(int a,int b){
a=a^b;
b=a^b;
a=a^b;
}
public void swap1(int a,int b){
a=a+b;
b=a-b;
a=a-b;
}
}
| true |
045a1b03010f2e110995673c9a17bd53d2d29cf4
|
Java
|
anantkshirsagar/DesignPatterns
|
/src/com/patterns/abstract_factory_ex2/Rectangle.java
|
UTF-8
| 238 | 3.25 | 3 |
[] |
no_license
|
package com.patterns.abstract_factory_ex2;
public class Rectangle extends Shape{
private int width;
public Rectangle(int width) {
this.width = width;
}
@Override
public int getWidth() {
return this.width;
}
}
| true |
6b4f5ebb4a4a85c0465e14dbef377234868ac7a7
|
Java
|
quazuo/PO-Robson
|
/src/commands/Variable.java
|
UTF-8
| 882 | 2.953125 | 3 |
[] |
no_license
|
package commands;
import util.InvalidProgramException;
import util.RobsonExecutionException;
import java.util.HashMap;
import java.util.HashSet;
public class Variable extends Command {
private final String nazwa;
public Variable(String nazwa) {
super("Zmienna");
this.nazwa = nazwa;
}
public String getNazwa() {
return nazwa;
}
@Override
public double execute(HashMap<String, Double> variables) throws RobsonExecutionException {
if (!variables.containsKey(nazwa))
throw new RobsonExecutionException("Odwołanie do niezainicjalizowanej zmiennej");
return variables.get(nazwa);
}
@Override
public String toJavaString(int indent, boolean isProgram, HashSet<String> usedVars,
Command program) throws InvalidProgramException {
return nazwa;
}
}
| true |
30134c36a650bda74f7bc143596ff5708ffbe6e8
|
Java
|
545923664/xx-im
|
/xx-im/src/main/java/com/jzwl/instant/service/impl/FileServiceImpl.java
|
UTF-8
| 5,946 | 2.28125 | 2 |
[] |
no_license
|
package com.jzwl.instant.service.impl;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.jzwl.base.service.MongoService;
import com.jzwl.base.service.RedisService;
import com.jzwl.instant.pojo.ChatFileBean;
import com.jzwl.instant.service.FileService;
import com.jzwl.instant.util.IC;
import com.jzwl.instant.util.L;
import com.jzwl.instant.util.Util;
@Component
public class FileServiceImpl implements FileService {
@Autowired
private RedisService redisService;
@Autowired
private MongoService mongoService;
/**
* 上传聊天文件
*/
public String upload(HttpServletRequest request, String username,
String fileName) {
try {
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
// 获得文件:
MultipartFile file = multipartRequest.getFile("file");
if (null != file) {
// 获得输入流:
InputStream input = file.getInputStream();
BufferedInputStream in = new BufferedInputStream(input);
String AppPath = getAppPath(request);
File serverFileDir = new File(AppPath);
if (!serverFileDir.exists()) {
serverFileDir.mkdir();
}
String uuid = Util.getUUID();
String saveFileName = uuid + "_" + fileName;
FileOutputStream fo = new FileOutputStream(AppPath
+ saveFileName);
BufferedOutputStream out = new BufferedOutputStream(fo);
byte[] buf = new byte[4 * 1024];
int len = in.read(buf);// 读文件,将读到的内容放入到buf数组中,返回的是读到的长度
while (len != -1) {
out.write(buf, 0, len);
len = in.read(buf);
}
out.close();
fo.close();
in.close();
input.close();
ChatFileBean fileBean = new ChatFileBean();
fileBean.setId(uuid);
fileBean.setFileName(saveFileName);
/**
*
*/
fileBean.setAccessUrl(getSaveDir() + saveFileName);
fileBean.setRealPath(AppPath + saveFileName);
fileBean.setUploadDate(Util.getCurrDate());
fileBean.setUploadUserName(username);
mongoService.save(IC.mongodb_fileinfo, fileBean);
return fileBean.getAccessUrl();
}
return null;
} catch (Exception e) {
e.printStackTrace();
L.out("request stream is not find file field");
return null;
}
}
/**
* 上传图片
*/
public String uploadPic(HttpServletRequest request, String username,
String fileName) {
try {
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
// 获得文件:
MultipartFile file = multipartRequest.getFile("file");
if (null != file) {
// 获得输入流:
InputStream input = file.getInputStream();
BufferedInputStream in = new BufferedInputStream(input);
String AppPath = getAppPath(request);
File serverFileDir = new File(AppPath);
if (!serverFileDir.exists()) {
serverFileDir.mkdir();
}
String uuid = Util.getUUID();
String saveFileName = uuid + "_" + fileName;
FileOutputStream fo = new FileOutputStream(AppPath
+ saveFileName);
BufferedOutputStream out = new BufferedOutputStream(fo);
byte[] buf = new byte[4 * 1024];
int len = in.read(buf);// 读文件,将读到的内容放入到buf数组中,返回的是读到的长度
while (len != -1) {
out.write(buf, 0, len);
len = in.read(buf);
}
out.close();
fo.close();
in.close();
input.close();
//
String accessUrl = getSaveDir() + saveFileName;
return accessUrl;
}
return null;
} catch (Exception e) {
e.printStackTrace();
L.out("request stream is not find file field");
return null;
}
}
/**
* 上传多图片
*/
public Set<String> uploadPics(HttpServletRequest request, String username) {
Set<String> uploadUrls = new HashSet<String>();
try {
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
List<MultipartFile> fileList = multipartRequest.getFiles("file");
if (null != fileList && fileList.size() > 0) {
for (MultipartFile file : fileList) {
if (null != file) {
// 获得输入流:
InputStream input = file.getInputStream();
BufferedInputStream in = new BufferedInputStream(input);
String AppPath = getAppPath(request);
File serverFileDir = new File(AppPath);
if (!serverFileDir.exists()) {
serverFileDir.mkdir();
}
String uuid = Util.getUUID();
String saveFileName = uuid + "_"
+ file.getOriginalFilename();
FileOutputStream fo = new FileOutputStream(AppPath
+ saveFileName);
BufferedOutputStream out = new BufferedOutputStream(fo);
byte[] buf = new byte[4 * 1024];
int len = in.read(buf);// 读文件,将读到的内容放入到buf数组中,返回的是读到的长度
while (len != -1) {
out.write(buf, 0, len);
len = in.read(buf);
}
out.close();
fo.close();
in.close();
input.close();
//
String accessUrl = getSaveDir() + saveFileName;
uploadUrls.add(accessUrl);
}
}
}
return uploadUrls;
} catch (Exception e) {
e.printStackTrace();
L.out("request stream is not find file field");
return uploadUrls;
}
}
public String getSaveDir() {
return "/upload/";
}
public String getAppPath(HttpServletRequest request) {
String AppPath = request.getSession().getServletContext()
.getRealPath("/")
+ getSaveDir();
return AppPath;
}
}
| true |
0ade55d7fbcd7491faa1b9540b6e0fb7f1012795
|
Java
|
Marta2909/JAVA-course
|
/KursJava_Pojazd/src/WlasciwosciPojazdu.java
|
UTF-8
| 231 | 2.46875 | 2 |
[] |
no_license
|
public abstract class WlasciwosciPojazdu {
public void nieZaSzybko(int predkosc, int predkoscMax){
if(predkosc*2 == predkoscMax){
System.out.println("Nie jedziesz za szybko?");
}
}
public abstract void skrec(int kat);
}
| true |
15df91525acbe6261323718541ebd291e2935c40
|
Java
|
wangchen1206/springcloud
|
/spring-demo/src/main/java/com/cc/learn/concurrent/CustomRejectionHandler.java
|
UTF-8
| 570 | 2.546875 | 3 |
[] |
no_license
|
package com.cc.learn.concurrent;
import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
/**
* Description
*
* @author wangchen
* @createDate 2020/11/05
*/
@Slf4j
public class CustomRejectionHandler implements RejectedExecutionHandler {
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
log.info("队列已满。。。,提交任务线程执行任务");
if (!executor.isShutdown()) {
r.run();
}
}
}
| true |
b045bd3cd775a6bd1c90aaae59270d5e1a4e895b
|
Java
|
theFlowerAndTheWind/NewWaterChain
|
/app/src/main/java/com/shuzijieshui/www/waterchain/contract/presenter/BuyBackPresenter.java
|
UTF-8
| 1,235 | 2.25 | 2 |
[] |
no_license
|
package com.shuzijieshui.www.waterchain.contract.presenter;
import com.shuzijieshui.www.waterchain.base.BaseActivity;
import com.shuzijieshui.www.waterchain.contract.BasePresenter;
import com.shuzijieshui.www.waterchain.contract.model.BuyBackModel;
import com.shuzijieshui.www.waterchain.contract.model.callback.CommonCallback;
import com.shuzijieshui.www.waterchain.contract.view.CommonViewImpl;
public class BuyBackPresenter extends BasePresenter<CommonViewImpl> {
private BuyBackModel buyBackModel;
public BuyBackPresenter(BuyBackModel buyBackModel) {
this.buyBackModel = buyBackModel;
}
public void buyBack(BaseActivity activity, float count) {
if (buyBackModel == null) {
buyBackModel = new BuyBackModel();
}
buyBackModel.buyBack(activity, count, new CommonCallback() {
@Override
public void onRequestSucc(Object o) {
if (mView != null) {
mView.onRequestSucc(o);
}
}
@Override
public void onRequestFail(String msg) {
if (mView != null) {
mView.onRequestFail(msg);
}
}
});
}
}
| true |
93540e0a4e69877aaf1225f64998249e41ef4b1f
|
Java
|
NenadPantelic/java-functional
|
/java-functional-examples/src/main/java/streams/_Stream.java
|
UTF-8
| 2,059 | 3.25 | 3 |
[
"MIT"
] |
permissive
|
package streams;
import static streams._Stream.Person.Gender.MALE;
import static streams._Stream.Person.Gender.FEMALE;
import static streams._Stream.Person.Gender.PREFER_NOT_TO_SAY;
import streams._Stream.Person.Gender;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
public class _Stream {
public static void main(String[] args) {
List<Person> people = List.of(
new Person("John", MALE),
new Person("Maria", FEMALE),
new Person("Aysha", FEMALE),
new Person("Alex", MALE),
new Person("Alice", FEMALE),
new Person("Jay", PREFER_NOT_TO_SAY)
);
System.out.println("Genders:");
Set<Gender> genders = people
.stream()
.map(Person::getGender)
.collect(Collectors.toSet());
System.out.println(genders);
System.out.println("Name lengths:");
people
.stream()
.map(Person::getName)
.mapToInt(String::length)
.forEach(System.out::println);
System.out.print("All females? ");
boolean containsOnlyFemales = people
.stream()
.allMatch(person -> person.getGender().equals(FEMALE));
System.out.println(containsOnlyFemales);
}
static class Person {
private final String name;
private final Gender gender;
Person(String name, Gender gender) {
this.name = name;
this.gender = gender;
}
public String getName() {
return name;
}
public Gender getGender() {
return gender;
}
enum Gender {
MALE,
FEMALE,
PREFER_NOT_TO_SAY
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", gender=" + gender +
'}';
}
}
}
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.