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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
0c08093e03030892d12b1639ea0439bf4124a887 | Java | goodwell42/GCChat | /app/src/main/java/com/goodwell42/gcchat/view/LayoutMoments.java | UTF-8 | 2,599 | 2.203125 | 2 | [] | no_license | package com.goodwell42.gcchat.view;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import com.goodwell42.gcchat.R;
import com.goodwell42.gcchat.adapter.AdapterMomentItem;
import com.goodwell42.gcchat.util.MomentMsg;
import java.util.ArrayList;
import java.util.List;
public class LayoutMoments extends Fragment {
private View rootView;
private List<MomentMsg> momentMsgList;
private RecyclerView momentRecyclerView;
private AdapterMomentItem adapterMomentItem;
private TextView tvNewMoment;
private Button btnSend;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.layout_moments, container, false);
initViews();
return rootView;
}
private void initViews() {
momentRecyclerView = (RecyclerView) rootView.findViewById(R.id.rv_list_moments);
tvNewMoment = (TextView) rootView.findViewById(R.id.tv_moment_new);
btnSend = (Button) rootView.findViewById(R.id.btn_moment_send);
momentMsgList = new ArrayList<>();
for (int i = 1; i < 10; i++) {
MomentMsg momentMsg = new MomentMsg();
momentMsg.setUsername("Stark " + i);
momentMsg.setIconID(R.drawable.avasterwe);
momentMsg.setMoment("moments,moments,moments,moments,moments,moments" + i);
momentMsg.setGood((i % 3) == 1 ? R.drawable.good : R.drawable.ungood);
momentMsgList.add(momentMsg);
}
adapterMomentItem = new AdapterMomentItem(getContext(), momentMsgList);
momentRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
momentRecyclerView.setAdapter(adapterMomentItem);
btnSend.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
MomentMsg momentMsg = new MomentMsg();
momentMsg.setUsername("Stark ");
momentMsg.setIconID(R.drawable.avasterwe);
momentMsg.setMoment(tvNewMoment.getText().toString());
momentMsg.setGood(R.drawable.ungood);
momentMsgList.add(momentMsg);
}
});
}
}
| true |
fb3c33e2cddb6ef0be5ce91734d2cd89118fd8f0 | Java | paquoc/SnackFood | /app/src/main/java/com/miniproject16cntn/a1612543/snackfood/AddRestaurant.java | UTF-8 | 10,582 | 1.976563 | 2 | [] | no_license | package com.miniproject16cntn.a1612543.snackfood;
import android.Manifest;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.TimePicker;
import com.google.android.gms.common.GooglePlayServicesNotAvailableException;
import com.google.android.gms.common.GooglePlayServicesRepairableException;
import com.google.android.gms.location.places.Place;
import com.google.android.gms.location.places.ui.PlacePicker;
import com.google.android.gms.maps.model.LatLng;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
public class AddRestaurant extends AppCompatActivity {
private static final int REQUEST_CAMERA = 1;
private static final int REQUEST_GALLERY = 2;
private static final int REQUEST_PLACE_PICKER = 3;
private EditText editTextName;
private List<EditText> editTextsFood;
private List<EditText> editTextsPrice;
private List<EditText> editTextsUnit;
private EditText editTextStartTime;
private EditText editTextEndTime;
private EditText editTextDescription;
private Button btnAdd;
private Button btnChooseImage;
private Button btnGetCamera;
private ImageView imageView;
private Button btnPlacePicker;
private LatLng latLng;
private TextView textView;
private Calendar calendar;
public static final String CODE = "ADDRESTAURANT";
private TimePickerDialog.OnTimeSetListener startTimeSetListener;
private TimePickerDialog.OnTimeSetListener endTimeSetListener;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_restaurant);
initWidget();
calendar = Calendar.getInstance();
startTimeSetListener = new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
calendar.set(Calendar.HOUR,hourOfDay);
calendar.set(Calendar.MINUTE, minute);
updateLabel(editTextStartTime, hourOfDay, minute);
}
};
editTextStartTime.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN)
new TimePickerDialog(AddRestaurant.this, startTimeSetListener, calendar.get(Calendar.HOUR),
calendar.get(Calendar.MINUTE), true).show();
return true;
}
});
endTimeSetListener = new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
calendar.set(Calendar.HOUR,hourOfDay);
calendar.set(Calendar.MINUTE, minute);
updateLabel(editTextEndTime, hourOfDay, minute);
}
};
editTextEndTime.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN)
new TimePickerDialog(AddRestaurant.this, endTimeSetListener, calendar.get(Calendar.HOUR),
calendar.get(Calendar.MINUTE), true).show();
return true;
}
});
btnChooseImage.setOnClickListener(new ButtonChooseImageEvent());
btnGetCamera.setOnClickListener(new ButtonGetCameraEvent());
btnAdd.setOnClickListener(new MyButtonAddEvent());
btnPlacePicker.setOnClickListener(new MyButtonPlacePickerEvent());
}
private void updateLabel(EditText editTextStartTime, int hourOfDay, int minute) {
String s = "";
if (hourOfDay < 10)
s += "0";
s += String.valueOf(hourOfDay) + ":";
if (minute< 10)
s+= "0";
s+= String.valueOf(minute);
editTextStartTime.setText(s);
}
private void initWidget() {
editTextName = findViewById(R.id.add_name);
editTextsFood = new ArrayList<EditText>();
editTextsFood.add((EditText) findViewById(R.id.add_food1));
editTextsFood.add((EditText) findViewById(R.id.add_food2));
editTextsFood.add((EditText) findViewById(R.id.add_food3));
editTextsPrice = new ArrayList<EditText>();
editTextsPrice.add((EditText) findViewById(R.id.add_price1));
editTextsPrice.add((EditText) findViewById(R.id.add_price2));
editTextsPrice.add((EditText) findViewById(R.id.add_price3));
editTextsUnit = new ArrayList<EditText>();
editTextsUnit.add((EditText) findViewById(R.id.add_unit1));
editTextsUnit.add((EditText) findViewById(R.id.add_unit2));
editTextsUnit.add((EditText) findViewById(R.id.add_unit3));
editTextStartTime = findViewById(R.id.add_start_time);
editTextEndTime = findViewById(R.id.add_end_time);
editTextDescription = findViewById(R.id.add_description);
btnChooseImage = findViewById(R.id.btn_choose_image);
btnGetCamera = findViewById(R.id.btn_get_camera);
btnAdd = findViewById(R.id.btn_add_restaurant);
imageView = findViewById(R.id.add_imageview);
btnPlacePicker = findViewById(R.id.add_pick_place);
textView = findViewById(R.id.add_tvaddress);
}
private class ButtonChooseImageEvent implements View.OnClickListener {
@Override
public void onClick(View v) {
if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED){
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_GALLERY);
}
else {
openGallery();
}
}
}
private void openGallery() {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, REQUEST_GALLERY);
}
private class ButtonGetCameraEvent implements View.OnClickListener {
@Override
public void onClick(View v) {
if (checkSelfPermission(Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED){
requestPermissions(new String[]{Manifest.permission.CAMERA}, REQUEST_CAMERA);
}
else {
openCamera();
}
}
}
private void openCamera() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if(requestCode == REQUEST_GALLERY && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
openGallery();
} else if (requestCode == REQUEST_CAMERA && grantResults[0] == PackageManager.PERMISSION_GRANTED){
openCamera();
}
}
private class MyButtonAddEvent implements View.OnClickListener {
@Override
public void onClick(View v) {
Restaurant r = new Restaurant();
r.setName(editTextName.getText().toString());
r.setListEating(getString(editTextsFood));
r.setPrice(getString(editTextsPrice));
r.setUnit(getString(editTextsUnit));
r.setAddress(textView.getText().toString());
r.setLatLng(latLng);
r.setStartTime(editTextStartTime.getText().toString());
r.setEndTime(editTextEndTime.getText().toString());
r.setDescription(editTextDescription.getText().toString());
r.setImage(((BitmapDrawable) imageView.getDrawable()).getBitmap());
r.setFavorite(0);
MainActivity.dbRestaurant.addRestaurant(r);
Intent intent = new Intent(AddRestaurant.this, MainActivity.class);
startActivity(intent);
}
}
private String getString(List<EditText> editText) {
String s = "";
int i = 0;
for (i = 0; i < editText.size() - 1; i++)
s+= editText.get(i).getText().toString() + ", ";
s+= editText.get(i).getText().toString();
return s;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == REQUEST_GALLERY && resultCode == RESULT_OK){
Uri selectedImage = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImage);
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
Log.i("TAG", "Some exception " + e);
}
}
else if (requestCode == REQUEST_CAMERA && resultCode == RESULT_OK)
{
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
}
else if(requestCode == REQUEST_PLACE_PICKER && resultCode == RESULT_OK)
{
Place place = PlacePicker.getPlace(data, this);
latLng = place.getLatLng();
textView.setText(place.getAddress());
}
}
private class MyButtonPlacePickerEvent implements View.OnClickListener {
@Override
public void onClick(View v) {
PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder();
try {
startActivityForResult(builder.build(AddRestaurant.this), REQUEST_PLACE_PICKER);
} catch (GooglePlayServicesRepairableException | GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
}
}
}
| true |
d53425c857072d6d6f0afbb367ce712b8811e48c | Java | jcp19/micro-benchmarks | /src/main/java/rexbenchmarks/Example3Thread1.java | UTF-8 | 587 | 3.03125 | 3 | [] | no_license | package rexbenchmarks;
import java.util.concurrent.locks.Lock;
public class Example3Thread1 extends Thread {
Lock lock;
Counter c;
public Example3Thread1(Lock lock, Counter c) {
this.lock = lock;
this.c = c;
}
@Override
public void run() {
for(int i = 0; i < 10; i++) {
//forces the read to happen
System.out.println(c.x);
}
for(int i = 0; i < 10; i++) {
lock.lock();
c.x = 1;
lock.unlock();
}
System.out.println("Thread 0 terminou");
}
}
| true |
f830fdfb8bd79f9299f79f176745ea25ba3cb55e | Java | damofujiki/UnsagaMod-for-1.12 | /src/main/java/mods/hinasch/unsaga/skillpanel/SkillPanelRegistry.java | UTF-8 | 10,655 | 1.859375 | 2 | [] | no_license | package mods.hinasch.unsaga.skillpanel;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import com.google.common.collect.ImmutableList;
import com.mojang.realmsclient.util.Pair;
import mods.hinasch.lib.registry.PropertyRegistry;
import mods.hinasch.lib.util.Statics;
import mods.hinasch.unsaga.core.item.misc.skillpanel.SkillPanelCapability;
import mods.hinasch.unsaga.init.UnsagaItems;
import net.minecraft.entity.Entity;
import net.minecraft.entity.ai.attributes.AttributeModifier;
import net.minecraft.entity.monster.EntityCreeper;
import net.minecraft.entity.monster.EntityZombie;
import net.minecraft.entity.passive.EntityAnimal;
import net.minecraft.item.ItemStack;
import net.minecraft.util.WeightedRandom;
import net.minecraft.util.math.MathHelper;
public class SkillPanelRegistry extends PropertyRegistry<SkillPanel>{
protected static SkillPanelRegistry INSTANCE;
// public SkillPanel punch,kick,throwing,shield,specialMoveMaster,punchMaster;
// public SkillPanel ironBody,toughness,ironWill;
// public SkillPanel familiarFire,familiarWater,familiarEarth,familiarWood,familiarMetal;
// public SkillPanel magicExpert,thriftSaver;
// public SkillPanel zombiePhobia,creeperPhobia;
// public SkillPanel magicBlend;
// public SkillPanel roadGuide,caveGuide,knowledgeBuildings;
// public SkillPanel swimming,avoidTrap;
// public SkillPanel locksmith,defuse,sharpEye;
// public SkillPanel eavesdrop;
// public SkillPanel chestMaster;
// public SkillPanel smartMove,obstacleCrossing;
//
// /** gratuity=マハラジャ*/
// public SkillPanel monger,maharaja,fashionable;
// public SkillPanel artiste,inconspicious;
// public SkillPanel quickFix;
// public SkillPanel fortuneTeller,arcaneTongue;
// public SkillPanel pacifistForAnimals;
// public SkillPanel toolCustomize,accessoryForge;
// public SkillPanel watchingOut,fortify;
// public SkillPanel adaptability,dummy;
public List<SkillPanel> familiars;
public List<SkillPanel> damageAgainstSkills;
public List<SkillPanel> statusUpSkills;
public List<Pair<SkillPanel,Predicate<Entity>>> negativeSkills1;
public List<Pair<SkillPanel,Predicate<Entity>>> negativeSkills2;
public static final int RARITY_MIRACLE = 2;
public static final int RARITY_ULTRARARE = 5;
public static final int RARITY_RARE = 10;
public static final int RARITY_UNCOMMON = 20;
public static final int RARITY_COMMON = 30;
public static final AttributeModifier SWIM_MODIFIER = new AttributeModifier(UUID.fromString("509167a3-a2ef-42fb-9dda-f4258b6a88f7"),"skillPanel.swim",30.0D,Statics.OPERATION_INCREMENT);
public static SkillPanelRegistry instance(){
if(INSTANCE==null){
INSTANCE = new SkillPanelRegistry();
}
return INSTANCE;
}
protected SkillPanelRegistry(){
}
@Override
public void init() {
// TODO 自動生成されたメソッド・スタブ
EventSkillPanel.register();
}
@Override
public void preInit() {
// TODO 自動生成されたメソッド・スタブ
this.registerObjects();
}
@Override
protected void registerObjects() {
//
// this.dummy = new SkillPanel("dummy");
// //宝箱関連
// this.locksmith = new SkillPanel("unlock");
// this.defuse = new SkillPanel("defuse");
// this.sharpEye = new SkillPanel("penetration");
// this.fortuneTeller = new SkillPanel("divination").setIcon(IconType.ROLL).setRarity(RARITY_UNCOMMON);
// this.avoidTrap = new SkillPanel("agility");
// this.chestMaster = new SkillPanel("chest_master").setIcon(IconType.KEY).setRarity(RARITY_ULTRARARE);
// //店
// this.artiste = new SkillPanel("luckyfind").setIcon(IconType.COMMUNICATION);
// this.monger = new SkillPanel("discount").setIcon(IconType.COMMUNICATION).setRarity(RARITY_UNCOMMON);
// this.maharaja = new SkillPanel("gratuity").setIcon(IconType.COMMUNICATION).setRarity(RARITY_UNCOMMON);
// this.fashionable = new SkillPanel("fashionable").setIcon(IconType.COMMUNICATION).setRarity(RARITY_RARE);
// //術
// this.arcaneTongue = new SkillPanel("arcane_tongue").setIcon(IconType.ROLL);
// this.magicBlend = new SkillPanel("magic_blend").setIcon(IconType.ROLL).setRarity(RARITY_RARE);
// this.magicExpert = new SkillPanel("magic_expert").setIcon(IconType.ROLL).setRarity(RARITY_ULTRARARE);
// //コンバット
// this.specialMoveMaster = new SkillPanel("weapon_master").setIcon(IconType.MELEE).setRarity(RARITY_ULTRARARE);
// this.punch = new SkillPanel("punch").setIcon(IconType.MELEE);
// this.ironBody = new SkillPanel("super_armor").setIcon(IconType.PROTECT).setRarity(RARITY_RARE)
// .setAttributeModifier(SharedMonsterAttributes.ARMOR, new AttributeModifier(UUID.fromString("1a2e5ddc-08f5-491c-a5a1-9af9d30aae34"),"skillPanel.ironBody",0.25D,0));
// this.fortify = new SkillPanel("fortify").setIcon(IconType.PROTECT).setRarity(RARITY_RARE)
// .setAttributeModifier(AdditionalStatus.MENTAL, new AttributeModifier(UUID.fromString("fe8f7d76-6f97-4c50-b133-a4d36cbee89d"),"skillPanel.fortify",0.25D,0));
// this.toughness = new SkillPanel("toughness").setIcon(IconType.PROTECT).setRarity(RARITY_UNCOMMON).setDamageAgainst(DamageSource.FALL);
// this.ironWill = new SkillPanel("iron_mind").setIcon(IconType.PROTECT).setRarity(RARITY_RARE).setDamageAgainst(DamageSource.STARVE,DamageSource.WITHER);
// this.eavesdrop = new SkillPanel("eavesdrop").setIcon(IconType.KEY).setRarity(RARITY_RARE);
// this.shield = new SkillPanel("shield").setIcon(IconType.PROTECT).setRarity(RARITY_UNCOMMON);
//
// //案内
// this.roadGuide = new SkillPanel("road_adviser").setIcon(IconType.ROLL);
// this.caveGuide = new SkillPanel("cavern_exprorer").setIcon(IconType.ROLL);
//
// //アイテム
// this.toolCustomize = new SkillPanel("tool_customize").setIcon(IconType.MELEE).setRarity(RARITY_RARE);
// this.thriftSaver = new SkillPanel("saving_damage").setIcon(IconType.ROLL).setRarity(RARITY_RARE);
// this.quickFix = new SkillPanel("easy_repair").setIcon(IconType.ROLL).setRarity(RARITY_RARE);
// //ネガティヴ
// this.zombiePhobia = new SkillPanel("zombie_phobia").setIcon(IconType.NEGATIVE).setNegativeSkill(true).setRarity(RARITY_RARE);
// this.creeperPhobia = new SkillPanel("creeper_phobia").setIcon(IconType.NEGATIVE).setNegativeSkill(true).setRarity(RARITY_RARE);
// this.pacifistForAnimals = new SkillPanel("no_killing_animals").setIcon(IconType.NEGATIVE).setNegativeSkill(true).setRarity(RARITY_RARE);
// //ファミリア
// this.familiarEarth = new SkillPanel("familiar_earth").setIcon(IconType.FAMILIAR).setRarity(RARITY_COMMON).setElement(FiveElements.Type.EARTH);
// this.familiarFire = new SkillPanel("familiar_Fire").setIcon(IconType.FAMILIAR).setRarity(RARITY_COMMON).setElement(FiveElements.Type.FIRE);
// this.familiarMetal = new SkillPanel("familiar_metal").setIcon(IconType.FAMILIAR).setRarity(RARITY_COMMON).setElement(FiveElements.Type.METAL);
// this.familiarWater = new SkillPanel("familiar_water").setIcon(IconType.FAMILIAR).setRarity(RARITY_COMMON).setElement(FiveElements.Type.WATER);
// this.familiarWood = new SkillPanel("familiar_wood").setIcon(IconType.FAMILIAR).setRarity(RARITY_COMMON).setElement(FiveElements.Type.WOOD);
// //動作系
// this.swimming = new SkillPanel("swimming").setIcon(IconType.ROLL).setRarity(RARITY_UNCOMMON);
// this.adaptability = new SkillPanel("adaptability").setIcon(IconType.ROLL).setRarity(RARITY_RARE);
// this.smartMove = new SkillPanel("smart_move").setIcon(IconType.KEY).setRarity(RARITY_RARE);
// this.obstacleCrossing = new SkillPanel("obstacle_crossing").setIcon(IconType.ROLL);
// //その他
// this.inconspicious = new SkillPanel("inconspicious").setIcon(IconType.COMMUNICATION).setRarity(RARITY_ULTRARARE);
//
// //実装するか微妙
//
// this.accessoryForge = new SkillPanel("accessory_forge").setIcon(IconType.MELEE).setRarity(RARITY_RARE);
// this.watchingOut = new SkillPanel("watching_out").setRarity(RARITY_RARE);
// this.knowledgeBuildings = new SkillPanel("knowledge_buildings").setIcon(IconType.ROLL);
// this.usableSkills = Lists.newArrayList(roadAdviser,cavernExprorer);
this.familiars = ImmutableList.of(SkillPanels.FAMILIAR_EARTH,SkillPanels.FAMILIAR_FIRE,SkillPanels.FAMILIAR_METAL
,SkillPanels.FAMILIAR_WATER,SkillPanels.FAMILIAR_WOOD);
this.damageAgainstSkills = ImmutableList.of(SkillPanels.TOUGHNESS,SkillPanels.IRON_WILL);
this.negativeSkills1 = ImmutableList.of(Pair.of(SkillPanels.PHOBIA_ZOMBIE, in -> in instanceof EntityZombie),Pair.of(SkillPanels.PHOBIA_CREEPER, in -> in instanceof EntityCreeper));
this.negativeSkills2 = ImmutableList.of(Pair.of(SkillPanels.PACIFIST_ANIMALS, in -> in instanceof EntityAnimal));
this.statusUpSkills = ImmutableList.of(SkillPanels.FORTIFY,SkillPanels.IRON_BODY);
SkillPanels.register();
// this.put(punch,arcaneTongue,magicBlend,locksmith,defuse,sharpEye,artiste);
// this.put(monger,maharaja,fortuneTeller,zombiePhobia,creeperPhobia,pacifistForAnimals);
// this.put(ironBody,toughness,roadGuide,caveGuide);
// this.put(toolCustomize,ironWill,fashionable);
// this.put(swimming,adaptability,shield,quickFix);
// this.put(familiarEarth,familiarFire,familiarWater,familiarMetal,familiarWood);
// this.put(thriftSaver,eavesdrop,specialMoveMaster,magicExpert,smartMove,obstacleCrossing);
}
public void register(SkillPanel... panels){
this.put(panels);
}
public ItemStack getItemStack(SkillPanel panel,int level){
ItemStack stack = new ItemStack(UnsagaItems.GROWTH_PANEL,1);
if(SkillPanelCapability.adapter.hasCapability(stack)){
SkillPanelCapability.adapter.getCapability(stack).setPanel(panel);
SkillPanelCapability.adapter.getCapability(stack).setLevel(MathHelper.clamp(level, 1, 5));
}
return stack;
}
public static class WeightedRandomPanel extends WeightedRandom.Item{
public final SkillPanel panel;
public int level;
public WeightedRandomPanel(int par1,SkillPanel data) {
super(par1);
this.panel = data;
// TODO 自動生成されたコンストラクター・スタブ
}
public WeightedRandomPanel(int par1,SkillPanel data,int level){
this(par1,data);
this.level = level;
}
@Override
public String toString(){
return "["+this.panel.getPropertyName()+" level:"+this.level+" weight:"+this.itemWeight+"]";
}
}
public List<WeightedRandomPanel> makeWeightedRandomPanels(){
return this.getProperties().stream().flatMap(data ->{
List<WeightedRandomPanel> list = new ArrayList();
// if(data.isWIP){
// return list.stream();
// }
for(int i=0;i<5;i++){
list.add(new WeightedRandomPanel(data.getRarity(),data,i));
}
return list.stream();
}).collect(Collectors.toList());
}
}
| true |
7df80de4a3e9e3a2d4a4561d5403b4bb5807c823 | Java | tahaJemmali/gark-Android | /app/src/main/java/com/example/gark/entites/MatchType.java | UTF-8 | 105 | 1.859375 | 2 | [] | no_license | package com.example.gark.entites;
public enum MatchType {
Round,
Quarter,
Semi,
Final
}
| true |
d36b99d4bf511864c4d00d74572c6deb5dd4df74 | Java | ministryofjustice/laa-maat-court-data-api | /maat-court-data-api/src/main/java/gov/uk/courtdata/repository/FinancialAssessmentRepository.java | UTF-8 | 1,649 | 1.945313 | 2 | [
"MIT",
"LicenseRef-scancode-proprietary-license"
] | permissive | package gov.uk.courtdata.repository;
import gov.uk.courtdata.entity.FinancialAssessmentEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import java.util.Optional;
@Repository
public interface FinancialAssessmentRepository extends JpaRepository<FinancialAssessmentEntity, Integer> {
@Modifying
@Query(value = "UPDATE TOGDATA.FINANCIAL_ASSESSMENTS fa set fa.REPLACED = 'Y' WHERE fa.REP_ID = :repId", nativeQuery = true)
void updateAllPreviousFinancialAssessmentsAsReplaced(@Param("repId") Integer repId);
@Modifying
@Query(value = "UPDATE TOGDATA.FINANCIAL_ASSESSMENTS fa set fa.REPLACED = 'Y' WHERE fa.ID <> :id AND fa.REP_ID = :repId", nativeQuery = true)
void updatePreviousFinancialAssessmentsAsReplaced(@Param("repId") Integer repId, @Param("id") Integer id);
@Query(value = "SELECT * FROM TOGDATA.FINANCIAL_ASSESSMENTS fa WHERE fa.REP_ID = :repId AND DATE_COMPLETED IS NOT NULL AND fa.REPLACED = 'N'", nativeQuery = true)
Optional<FinancialAssessmentEntity> findCompletedAssessmentByRepId(@Param("repId") Integer repId);
@Query(value = "SELECT count(*) FROM TOGDATA.FINANCIAL_ASSESSMENTS fa WHERE fa.REP_ID = :repId AND fa.REPLACED = 'N' AND (fa.VALID IS NULL OR fa.VALID <> 'N') AND (fa.FASS_FULL_STATUS = 'IN PROGRESS' OR fa.FASS_INIT_STATUS = 'IN PROGRESS')", nativeQuery = true)
Long findOutstandingFinancialAssessments(@Param("repId") Integer repId);
}
| true |
c096a2a53501a6964f90432dc896cfff9b56805c | Java | gaich/BetterBatteryStats | /BetterBatteryStats/src/com/asksven/betterbatterystats/data/GoogleAnalytics.java | UTF-8 | 4,631 | 1.890625 | 2 | [
"Apache-2.0"
] | permissive | /*
* Copyright (C) 2011 asksven
*
* 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.asksven.betterbatterystats.data;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.preference.PreferenceManager;
import com.google.android.apps.analytics.GoogleAnalyticsTracker;
/**
* A wrapper around google analytics
* @author sven
*
*/
public class GoogleAnalytics
{
private static GoogleAnalytics m_singleton = null;
private static GoogleAnalyticsTracker m_tracker = null;
private static boolean m_bActive = false;
/** constants for the reported actions */
public static final String ACTIVITY_ABOUT = "/AboutActivity";
public static final String ACTIVITY_ALARMS = "/AlarmsActivity";
public static final String ACTIVITY_KWL = "/RawKwlActivity";
public static final String ACTIVITY_NET = "/RawNetActivity";
public static final String ACTIVITY_CPU = "/RawCpuActivity";
public static final String ACTIVITY_PERMS = "/PermissionsActivity";
public static final String ACTIVITY_BATTERY_GRAPH = "/BatteryGraphActivity";
public static final String ACTIVITY_BATTERY_GRAPH2 = "/BatteryGraph2Activity";
public static final String ACTIVITY_BATTERY_GRAPH_SERIES = "/BatteryGraphSeriesActivity";
public static final String ACTIVITY_HELP = "/HelpActivity";
public static final String ACTIVITY_HOWTO = "/HowtoActivity";
public static final String ACTIVITY_README = "/ReadmeActivity";
public static final String ACTIVITY_HIST = "/HistActivity";
public static final String ACTIVITY_PREFERENCES = "/PreferencesActivity";
public static final String ACTIVITY_STATS = "/StatsActivity";
public static final String ACTION_DUMP = "/ActionDump";
public static final String ACTION_SET_CUSTOM_REF = "/ActionSetCustmRef";
private GoogleAnalytics()
{
}
/**
* Returns the singleton
* @param context
* @return a singleton instance
*/
public static GoogleAnalytics getInstance(Context context)
{
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
m_bActive = sharedPrefs.getBoolean("use_analytics", true);
if (m_singleton == null)
{
m_singleton = new GoogleAnalytics();
if (m_bActive)
{
m_tracker = GoogleAnalyticsTracker.getInstance();
// Start the tracker in manual dispatch mode...
m_tracker.startNewSession("TRACKING_CODE_HERE", 20, context);
// set custom vars
// Scopes are encoded to integers: Visitor=1, Session=2, Page=3
int versionFree = 0;
if (context.getPackageName().contains("xdaedition"))
{
versionFree = 1;
}
m_tracker.setCustomVar(1, "Version", "Paid", versionFree);
int versionCode = 0;
try
{
PackageInfo pinfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
versionCode = pinfo.versionCode;
}
catch (Exception e)
{
}
m_tracker.setCustomVar(1, "Release", "Number", versionCode);
}
}
return m_singleton;
}
/**
* Send a single Activity to tracking
* @param page the name of an Activity
*/
public void trackPage(String page)
{
if ((m_tracker != null) && m_bActive )
{
m_tracker.trackPageView(page);
}
}
/**
* Tracks the main screen including the parameters used for display
* @param context
* @param page
* @param stat
* @param statType
* @param sort
*/
public void trackStats(Context context, String page, int stat, int statType, int sort)
{
if ((m_tracker != null) && m_bActive )
{
m_tracker.trackPageView(page
+ StatsProvider.getInstance(context).statToUrl(stat)
+ StatsProvider.getInstance(context).statTypeToUrl(statType)
+ "Sort" + sort);
}
}
public void trackStats(Context context, String page, int stat, String refFrom, String refTo, int sort)
{
if ((m_tracker != null) && m_bActive )
{
m_tracker.trackPageView(page
+ StatsProvider.getInstance(context).statToUrl(stat)
+ "From" + refFrom
+ "To" + refTo
+ "Sort" + sort);
}
}
}
| true |
bd039c89404639a7b9d621e8ed0230640ef3fa1c | Java | AndrejLee/UploadImageFromStorage | /app/src/main/java/com/example/cpu10152_local/testrecyclerview/ImageCache.java | UTF-8 | 830 | 2.609375 | 3 | [] | no_license | package com.example.cpu10152_local.testrecyclerview;
import android.graphics.Bitmap;
import android.util.LruCache;
/**
* Created by cpu10152-local on 04/04/2018.
*/
public class ImageCache extends LruCache<Integer, Bitmap> {
/**
* @param maxSize for caches that do not override {@link #sizeOf}, this is
* the maximum number of entries in the cache. For all other caches,
* this is the maximum sum of the sizes of the entries in this cache.
*/
public ImageCache(int maxSize) {
super(maxSize);
}
@Override
protected int sizeOf(Integer key, Bitmap value) {
return value.getByteCount();
}
@Override
protected void entryRemoved(boolean evicted, Integer key, Bitmap oldValue, Bitmap newValue) {
oldValue.recycle();
}
}
| true |
72f3fb881f943d27fbdf6e49be3011afefc98d9a | Java | wim82/Backend-MeetingRoom | /MeetingRoom/src/main/java/be/kawi/meetingroom/service/UserService.java | UTF-8 | 1,833 | 2.421875 | 2 | [] | no_license | package be.kawi.meetingroom.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import be.kawi.meetingroom.dao.UserDAO;
import be.kawi.meetingroom.exceptions.CorruptDatabaseException;
import be.kawi.meetingroom.exceptions.NoSuchFullNameException;
import be.kawi.meetingroom.exceptions.NoSuchMeetingRoomException;
import be.kawi.meetingroom.model.MeetingRoom;
import be.kawi.meetingroom.model.Reservation;
import be.kawi.meetingroom.model.User;
@Service
public class UserService {
@Autowired
private UserDAO userDAO;
@Transactional
public List<User> getUsers() {
return userDAO.getUsers();
}
@Transactional
public User login(User user) {
List<User> possibleUsers = userDAO.getUser(user);
if (possibleUsers.isEmpty()) {
throw new NoSuchFullNameException();
}
if (possibleUsers.size() > 1) {
throw new CorruptDatabaseException("There are 2 users with the same name in the database");
}
User result = possibleUsers.get(0);
return result;
}
@Transactional
public User login(String fullName) {
User user = new User();
user.setFullName(fullName.trim());
return login(user);
}
@Transactional
public User getUserByFullName(String fullName) {
User user = new User();
user.setFullName(fullName.trim());
List<User> possibleUsers = userDAO.getUser(user);
//List<MeetingRoom> possibleMeetingRooms = meetingRoomDAO.getMeetingRoom(meetingRoom);
if (possibleUsers.isEmpty()) {
throw new NoSuchFullNameException();
}
if (possibleUsers.size() > 1) {
throw new CorruptDatabaseException("There are 2 users with the same fullName in the database");
}
User result = possibleUsers.get(0);
return result;
}
}
| true |
db9ca88f8f301f286e2efaafec349a11ada2c972 | Java | binsoopark/android_nfc_communication_example | /app/src/main/java/com/soobinpark/example/nfccommunication/ByteUtils.java | UTF-8 | 604 | 2.609375 | 3 | [] | no_license | package com.soobinpark.example.nfccommunication;
import java.io.UnsupportedEncodingException;
public class ByteUtils {
static String ReadRecordByCharEnc(byte[] payload) throws UnsupportedEncodingException {
int languageCodeLength = payload[0] & 0x3F; // 5th bit defines language code length
String charEncType = ((payload[0] & 0x80) == 0) ? "UTF-8" : "UTF-16"; // 7th bit defines utf-8 or utf-16
// text length starts after control byte language code
return new String(payload, languageCodeLength + 1, payload.length - languageCodeLength - 1, charEncType);
}
}
| true |
c9210cf615229f1ca610bfda64fc436b1ad96a5b | Java | kmsabrin/MemoryMappedGraphComputation | /MemoryMappedGraphComputation/src/edu/gatech/memory_mapping_alg/EdgeListIndex.java | UTF-8 | 2,314 | 2.828125 | 3 | [] | no_license | package edu.gatech.memory_mapping_alg;
import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel.MapMode;
public class EdgeListIndex {
// assumptions: nodes are contiguous, no breakage in node ids
// assumptions: edge list is sorted by node ids
//
public static void getEdgeListIndex(String binFileName, String idxFileName) {
try {
RandomAccessFile srcFile = new RandomAccessFile(binFileName, "r");
RandomAccessFile idxFile = new RandomAccessFile(idxFileName, "rw");
// DataOutputStream idxFile = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(idxFileName)));
long binFileSize = srcFile.length();
long bufferLimit = 2097152000; // 2000 MB
int currentNode = 0;
int currentNodeDegree = 0;
long currentNodeOffset = 0;
long currentPosition = 0;
long loadFrom = 0;
while (loadFrom < binFileSize) {
long remaining = Math.min(binFileSize - loadFrom, bufferLimit);
ByteBuffer srcbb = srcFile.getChannel().map(MapMode.READ_ONLY, loadFrom, remaining);
loadFrom += remaining;
while (srcbb.hasRemaining()) {
int src = srcbb.getInt();
srcbb.getInt();
if (src != currentNode) {
// if (src != currentNode+1) System.out.println(currentNode+1);
idxFile.seek(currentNode*12);
idxFile.writeLong(currentNodeOffset);
idxFile.writeInt(currentNodeDegree);
currentNode = src;
currentNodeDegree = 0;
currentNodeOffset = currentPosition;
// while(currentNode < src) {
// //System.out.println(src+"----"+currentNode);
// idxFile.writeLong(-1);
// idxFile.writeInt(-1);
// ++currentNode;
// }
}
++currentNodeDegree;
currentPosition += 2;
}
}
srcFile.close();
idxFile.close();
}
catch(IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
getEdgeListIndex("C://Users//Lupu//Downloads//LiveJournal//LiveJournal.txt.bin", "C://Users//Lupu//Downloads//LiveJournal//LiveJournal.index.bin");
}
}
| true |
5fb8b2897d565408916cfa1b60389fb689560d53 | Java | suresh1kumar/microservice-springboot | /Resume_Builder/src/com/nacre/resume_builder/action/addPersonalDetails.java | UTF-8 | 3,079 | 2.34375 | 2 | [] | no_license | package com.nacre.resume_builder.action;
import java.io.IOException;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.nacre.resume_builder.daoException.DatabaseException;
import com.nacre.resume_builder.dto.PersonalDetailsDto;
import com.nacre.resume_builder.serviceI.PersonalDetailsServiceI;
import com.nacre.resume_builder.serviceImpl.PersonalDetailsServiceImpl;
@WebServlet("/addPersonalDetails")
public class addPersonalDetails extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
boolean flag=false;
/*HttpSession session=request.getSession(false);
int uid=(int)session.getAttribute("uid");*/
int uid=4;
String fname=request.getParameter("txtfname");
String lname=request.getParameter("txtlname");
String fathername=request.getParameter("txtfathername");
String mothername=request.getParameter("txtmothername");
String dob=request.getParameter("txtdob");
String countryname=request.getParameter("scountry");
String statename=request.getParameter("sstate");
String cityname=request.getParameter("scity");
String gender=request.getParameter("gender");
int pincode =Integer.parseInt(request.getParameter("txtpincode"));
String addr=request.getParameter("txtaddr");
PersonalDetailsDto pdd=new PersonalDetailsDto();
try {
java.util.Date date =new SimpleDateFormat("MM/dd/yyyy").parse(dob);
java.sql.Date sqlDate=new java.sql.Date(date.getTime());
pdd.setDob(sqlDate);
System.out.println(date);
} catch (ParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
pdd.setUserId(uid);
pdd.setFname(fname);
pdd.setLname(lname);
pdd.setFathname(fathername);
pdd.setMothname(mothername);
pdd.setCountryname(countryname);
pdd.setStatename(statename);
pdd.setCityname(cityname);
pdd.setGender(gender);
pdd.setPincode(pincode);
pdd.setAddr(addr);
PersonalDetailsServiceI pds=new PersonalDetailsServiceImpl();
try {
flag=pds.addPersonalDetailsService(pdd);
} catch (DatabaseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(flag){
System.out.println("addesd successfully");
}
else{
System.out.println("failed");
}
//response.getWriter().append("Served at: ").append(request.getContextPath());
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
| true |
d3b153ce31fabb696c84e7d85b08a28fc10ca875 | Java | Esemplor/Lesson0 | /src/main/java/ee/bcs/valiit/codewars/Codewars1.java | UTF-8 | 227 | 1.734375 | 2 | [] | no_license | //package ee.bcs.valiit.codewars;
//
//import static org.junit.Assert.*;
//import org.junit.Test;
//
//public class Codewars1 {
// public static int howOld(final String herOld) {
//
//
//
// return vanus;
// }
//}
| true |
7e08a2034a3aa33e0dcaff3d6efab729a01c974e | Java | vincci1988/ASHE | /ASHE/src/agent/Fold.java | UTF-8 | 241 | 2.34375 | 2 | [] | no_license | package agent;
public class Fold extends ActionBase {
public Fold(int playerID) {
super(playerID);
}
public String toString() {
return "Player[" + playerID + "]: Fold";
}
String compress() {
return "f";
}
}
| true |
785ce9d76502b5042323d428802c2cc72371f445 | Java | loren9527/truck-1 | /src/main/java/com/bysj/rj/service/CheckInfoService.java | UTF-8 | 1,810 | 2.265625 | 2 | [] | no_license | package com.bysj.rj.service;
import com.bysj.rj.dao.CheckInfoEntityMapper;
import com.bysj.rj.entity.CheckInfoEntity;
import com.bysj.rj.entity.CheckInfoEntityExample;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
/**
* @Author: yangliu
* @Description:
* @Date: Created in 2017/5/13 0013.
*/
@Service
public class CheckInfoService {
@Resource
private CheckInfoEntityMapper checkInfoEntityMapper;
/**
* 查找所有检查信息
* @return
*/
public List<CheckInfoEntity> getAllCheckInfo(){
CheckInfoEntityExample example = new CheckInfoEntityExample();
example.setOrderByClause("id DESC");
return checkInfoEntityMapper.selectByExample(example);
}
/**
* 单条插入
* @param checkInfoEntity
* @return
*/
public int addNewCheckInfo(CheckInfoEntity checkInfoEntity){
int count = checkInfoEntityMapper.insertSelective(checkInfoEntity);
return count;
}
/**
* 更新
* @param entity
* @return
*/
public int updateCheckInfo(CheckInfoEntity entity){
return checkInfoEntityMapper.updateByPrimaryKeySelective(entity);
}
/**
* 根据ID查找
* @param id
* @return
*/
public CheckInfoEntity findOneById(Long id){
return checkInfoEntityMapper.selectByPrimaryKey(id);
}
/**
* 删除
* @param id
* @return
*/
public int deleteCheckInfoById(Long id){
return checkInfoEntityMapper.deleteByPrimaryKey(id);
}
/**
* 条件查询
* @param example
* @return
*/
public List<CheckInfoEntity> findBySelect(CheckInfoEntityExample example){
return checkInfoEntityMapper.selectByExample(example);
}
}
| true |
42ead5562098f97e01b32c85651cbde3f72c0ebc | Java | rafalcurylo/hilbert-curve | /src/main/java/com/rafalcurylo/hilbertCurve/HilbertPainter.java | UTF-8 | 1,925 | 3.265625 | 3 | [
"Apache-2.0"
] | permissive | package com.rafalcurylo.hilbertCurve;
import java.awt.*;
/**
* @author - rafal.curylo@gmail.com
*/
public class HilbertPainter {
private final int h;
private final int targetLevel;
private final Graphics2D graphics2D;
public HilbertPainter(int height, int targetLevel, Graphics2D graphics2D) {
this.h = height;
this.targetLevel = targetLevel;
this.graphics2D = graphics2D;
}
public void paint(Position startingPosition) {
Position pos = new Position(startingPosition.getX(), startingPosition.getY());
figA(targetLevel, pos);
}
private void figA(int level, Position pos) {
if (level > 0) {
figD(level-1, pos); pos.move(-h, 0); line(pos);
figA(level-1, pos); pos.move(0, -h); line(pos);
figA(level-1, pos); pos.move(h, 0); line(pos);
figB(level-1, pos);
}
}
private void figB(int level, Position pos) {
if (level > 0) {
figC(level-1, pos); pos.move(0, h); line(pos);
figB(level-1, pos); pos.move(h, 0); line(pos);
figB(level-1, pos); pos.move(0, -h); line(pos);
figA(level-1, pos);
}
}
private void figC(int level, Position pos) {
if (level > 0) {
figB(level-1, pos); pos.move(h, 0); line(pos);
figC(level-1, pos); pos.move(0, h); line(pos);
figC(level-1, pos); pos.move(-h, 0); line(pos);
figD(level-1, pos);
}
}
private void figD(int level, Position pos) {
if (level > 0) {
figA(level-1, pos); pos.move(0, -h); line(pos);
figD(level-1, pos); pos.move(-h, 0); line(pos);
figD(level-1, pos); pos.move(0, h); line(pos);
figC(level-1, pos);
}
}
private void line(Position pos) {
graphics2D.drawLine(pos.getxPrev(), pos.getyPrev(), pos.getX(), pos.getY());
}
} | true |
55e48a72237644982e761bbc3f3a2470fe1db406 | Java | Saggarwal9/Online-Courses-Notes | /Inversion of Control/XML/TrackCoach.java | UTF-8 | 289 | 2.171875 | 2 | [] | no_license | package ioc;
public class TrackCoach implements Coach{
@Override
public String getDailyWorkout() {
return "Run a hard 5k";
}
@Override
public String getSportName() {
// TODO Auto-generated method stub
return "Track";
}
}
| true |
fb51af91c6c09fe095d11e769562fea28923a33c | Java | gaoyao99409/springcloud | /springcloud-shardingjdbc-new/src/main/java/com/springcloud/springcloudshardingjdbcnew/util/BeanTools.java | UTF-8 | 5,628 | 2.65625 | 3 | [] | no_license | package com.springcloud.springcloudshardingjdbcnew.util;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.google.common.collect.Maps;
import org.apache.commons.beanutils.PropertyUtils;
import org.springframework.cglib.beans.BeanCopier;
/**
* 反射工具类
*
* @author litianyi
* <p>
* 2016年2月8日
*/
public class BeanTools {
private static Map<String, BeanCopier> beanMap = Maps.newConcurrentMap();
/**
* 复制指定的属性集合
*
* @return true 复制成功
*/
public static <T> boolean copySomeProperties(T from, T to, String[] properties) {
try {
for (String property : properties) {
Object value = PropertyUtils.getProperty(from, property);
PropertyUtils.setProperty(to, property, value);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 复制对象 将tempObject不为空字段 复制到 bean 中
*
* @param bean
* @param tempObject
* @return
*/
public static <T> T copyNonNullProperty(T bean, Object tempObject) {
Field[] fields = null;
try {
fields = tempObject.getClass().getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
if (!"serialVersionUID".equals(fields[i].getName()) && fields[i].getModifiers() == Modifier.PRIVATE) {
Object value = PropertyUtils.getProperty(tempObject, fields[i].getName());
if (value != null) {
PropertyUtils.setProperty(bean, fields[i].getName(), value);
}
}
}
} catch (Exception e) {
e.printStackTrace();
return bean;
}
return bean;
}
/**
* 获取一个对象的非空属性
*
* @param obj
* @param excludeProperty
* @return
* @author BennyTian
* @date 2015年5月26日 上午11:41:07
*/
public static Map<String, Object> getNonNullProperty(Object obj, String... excludeProperty) {
Map<String, Object> properties = new HashMap<String, Object>();
if (obj == null) {
return properties;
}
Set<String> excludeProperties = new HashSet<String>();
if (excludeProperty != null && excludeProperty.length > 0) {
for (String p : excludeProperty) {
excludeProperties.add(p);
}
}
Field[] fields = null;
try {
fields = obj.getClass().getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
if (!excludeProperties.contains(fields[i].getName()) && !"serialVersionUID".equals(fields[i].getName()) && fields[i].getModifiers() == Modifier.PRIVATE) {
Object value = PropertyUtils.getProperty(obj, fields[i].getName());
if (value != null) {
properties.put(fields[i].getName(), value);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return properties;
}
/**
* 将实体类Bean 转换成 Json 可使用的 Vo
*
* @param bean
* @param voClass
* @return
*/
public static <K> K convertBeanToVo(Object bean, Class<K> voClass) {
K vo = null;
try {
vo = voClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
String key = bean.getClass().getName() + ":" + voClass.getName();
if (!beanMap.containsKey(key)) {
BeanCopier copier = BeanCopier.create(bean.getClass(), voClass, false);
beanMap.put(key, copier);
}
BeanCopier beanCopier = beanMap.get(key);
beanCopier.copy(bean, vo, null);
return vo;
}
/**
* 将父类集合属性copy到子类集合中
*
* @param parentClass
* @param childClass
* @param tempList
* @return
*/
public static <T, K> List<T> copyParentList(Class<K> parentClass, Class<T> childClass, List<K> tempList) {
if (tempList == null) {
return null;
}
BeanCopier beanCopier = BeanCopier.create(parentClass, childClass, false);
List<T> list = new ArrayList<T>();
try {
for (K obj : tempList) {
T newInstance = childClass.newInstance();
beanCopier.copy(obj, newInstance, null);
list.add(newInstance);
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
return list;
}
/**
* 将父类属性copy到子类中
*
* @param parentClass
* @param childClass
* @param parent
* @return
*/
public static <T, K> T copyParentToChild(Class<K> parentClass, Class<T> childClass, K parent) {
if (parent == null) {
return null;
}
BeanCopier beanCopier = BeanCopier.create(parentClass, childClass, false);
T newInstance = null;
try {
newInstance = childClass.newInstance();
beanCopier.copy(parent, newInstance, null);
} catch (Exception e) {
e.printStackTrace();
return null;
}
return newInstance;
}
}
| true |
7f9809ef79e5e6f899de4d8eb563b152ea16598d | Java | igoral5/load_telemetry | /src/com/shturmann/telemetry/UnitsCSVParser.java | UTF-8 | 1,034 | 2.015625 | 2 | [] | no_license | package com.shturmann.telemetry;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
/**
* Created by igor on 15.08.14.
*/
public class UnitsCSVParser extends UnitsParser
{
public UnitsCSVParser(DateTimeZone timeZone, String worker_name)
{
super(timeZone, worker_name);
}
@Override
public void start_doc()
{
clear();
}
@Override
public void next(String[] line)
{
int srv_id = Integer.parseInt(line[0]);
int uniqueid = Integer.parseInt(line[1]);
int tt_id = Integer.parseInt(line[2]);
DateTime u_timenav = fmt.parseDateTime(line[7]).withZoneRetainFields(timeZone);
double u_lat = Double.parseDouble(line[8]);
double u_long = Double.parseDouble(line[9]);
int u_speed = Integer.parseInt(line[10]);
int u_course = Integer.parseInt(line[11]);
int u_inv = Integer.parseInt(line[12]);
add(srv_id, uniqueid, tt_id, u_timenav, u_lat, u_long, u_speed, u_course, u_inv, line[4]);
}
}
| true |
3d8f93fa37803aa28904848700cbebd6a103804c | Java | shuiyou/UITest | /src/main/java/Utils/CollectionStudy1.java | UTF-8 | 658 | 3 | 3 | [] | no_license | package Utils;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
/**
* Created by hanxiaodi on 17/7/26.
*/
public class CollectionStudy1 {
public static void main(String[] args){
List<String> staff = new LinkedList<String>();
staff.add("AMY");
staff.add("BOY");
staff.add("Caler");
Iterator<String> iter = staff.iterator();
String first = iter.next();
String second = iter.next();
iter.remove();
// System.out.println(first);
for(String element:staff){
iter.hasNext();
System.out.println(element);
}
}
}
| true |
68de4928a5c2cc015f110ec2244e0e47e406bbef | Java | SerjKrukov/pftask | /src/main/java/com/serj/pftask/model/HolidayRepository.java | UTF-8 | 169 | 1.546875 | 2 | [] | no_license | package com.serj.pftask.model;
import org.springframework.data.repository.CrudRepository;
public interface HolidayRepository extends CrudRepository<Holiday, Long> {
}
| true |
755bc0249bae2ccd3e55100b3a5f39f216777699 | Java | seongmu/HouseFinanceService | /src/main/java/com/kakao/housefinance/repo/HouFncSuppStatRepository.java | UTF-8 | 8,156 | 1.953125 | 2 | [] | no_license | package com.kakao.housefinance.repo;
import java.util.List;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import com.kakao.housefinance.model.HouFncSuppStat;
public interface HouFncSuppStatRepository extends JpaRepository<HouFncSuppStat, Long>, JpaSpecificationExecutor<HouFncSuppStat> {
@Query(value = "select YEAR" +
" , SUM(JUTAECK) + SUM(KOOKMIN) + SUM(WOORI) + SUM(SHINHAN) + SUM(CITI) + SUM(HANA) + SUM(NONGHYUP) + SUM(KE) + SUM(ETC) AS ALL_SUM" +
" , SUM(JUTAECK) JUTAECK_SUM" +
" , SUM(KOOKMIN) KOOKMIN_SUM" +
" , SUM(WOORI) WOORI_SUM" +
" , SUM(SHINHAN) SHINHAN_SUM" +
" , SUM(CITI) CITI_SUM" +
" , SUM(HANA) HANA_SUM" +
" , SUM(NONGHYUP) NONGHYUP_SUM" +
" , SUM(KE) KE_SUM" +
" , SUM(ETC) ETC_SUM" +
" FROM hou_fnc_supp_stat" +
" group by YEAR" +
" order by YEAR", nativeQuery = true)
List<Object[]> findAllSumHouFncSuppStat();
@Query(value = " SELECT B.YEAR" +
" ,B.INSTITUTE AS BANK" +
" ,B.JUTAECK_SUM AS MAX_AMOUNT" +
" FROM" +
" (" +
" (SELECT A.YEAR" +
" ,'주택도시기금' AS INSTITUTE" +
" ,A.JUTAECK_SUM" +
" FROM" +
" (" +
" SELECT YEAR" +
" , SUM(JUTAECK) JUTAECK_SUM" +
" , SUM(KOOKMIN) KOOKMIN_SUM" +
" , SUM(WOORI) WOORI_SUM" +
" , SUM(SHINHAN) SHINHAN_SUM" +
" , SUM(CITI) CITI_SUM" +
" , SUM(HANA) HANA_SUM" +
" , SUM(NONGHYUP) NONGHYUP_SUM" +
" , SUM(KE) KE_SUM" +
" , SUM(ETC) ETC_SUM" +
" FROM HOU_FNC_SUPP_STAT" +
" GROUP BY YEAR" +
" ORDER BY YEAR" +
" ) A" +
" ORDER BY A.JUTAECK_SUM DESC" +
" LIMIT 1)" +
" UNION" +
" (SELECT A.YEAR" +
" ,'국민은행' AS INSTITUTE" +
" ,A.KOOKMIN_SUM" +
" FROM" +
" (" +
" SELECT YEAR" +
" , SUM(JUTAECK) JUTAECK_SUM" +
" , SUM(KOOKMIN) KOOKMIN_SUM" +
" , SUM(WOORI) WOORI_SUM" +
" , SUM(SHINHAN) SHINHAN_SUM" +
" , SUM(CITI) CITI_SUM" +
" , SUM(HANA) HANA_SUM" +
" , SUM(NONGHYUP) NONGHYUP_SUM" +
" , SUM(KE) KE_SUM" +
" , SUM(ETC) ETC_SUM" +
" FROM HOU_FNC_SUPP_STAT" +
" GROUP BY YEAR" +
" ORDER BY YEAR" +
" ) A" +
" ORDER BY A.KOOKMIN_SUM DESC" +
" LIMIT 1)" +
" UNION" +
" (SELECT A.YEAR" +
" ,'우리은행' AS INSTITUTE" +
" ,A.WOORI_SUM" +
" FROM" +
" (" +
" SELECT YEAR" +
" , SUM(JUTAECK) JUTAECK_SUM" +
" , SUM(KOOKMIN) KOOKMIN_SUM" +
" , SUM(WOORI) WOORI_SUM" +
" , SUM(SHINHAN) SHINHAN_SUM" +
" , SUM(CITI) CITI_SUM" +
" , SUM(HANA) HANA_SUM" +
" , SUM(NONGHYUP) NONGHYUP_SUM" +
" , SUM(KE) KE_SUM" +
" , SUM(ETC) ETC_SUM" +
" FROM HOU_FNC_SUPP_STAT" +
" GROUP BY YEAR" +
" ORDER BY YEAR" +
" ) A" +
" ORDER BY A.WOORI_SUM DESC" +
" LIMIT 1)" +
" UNION" +
" (SELECT A.YEAR" +
" ,'신한은행' AS INSTITUTE" +
" ,A.SHINHAN_SUM" +
" FROM" +
" (" +
" SELECT YEAR" +
" , SUM(JUTAECK) JUTAECK_SUM" +
" , SUM(KOOKMIN) KOOKMIN_SUM" +
" , SUM(WOORI) WOORI_SUM" +
" , SUM(SHINHAN) SHINHAN_SUM" +
" , SUM(CITI) CITI_SUM" +
" , SUM(HANA) HANA_SUM" +
" , SUM(NONGHYUP) NONGHYUP_SUM" +
" , SUM(KE) KE_SUM" +
" , SUM(ETC) ETC_SUM" +
" FROM HOU_FNC_SUPP_STAT" +
" GROUP BY YEAR" +
" ORDER BY YEAR" +
" ) A" +
" ORDER BY A.SHINHAN_SUM DESC" +
" LIMIT 1)" +
" UNION" +
" (SELECT A.YEAR" +
" ,'한국시티은행' AS INSTITUTE" +
" ,A.CITI_SUM" +
" FROM" +
" (" +
" SELECT YEAR" +
" , SUM(JUTAECK) JUTAECK_SUM" +
" , SUM(KOOKMIN) KOOKMIN_SUM" +
" , SUM(WOORI) WOORI_SUM" +
" , SUM(SHINHAN) SHINHAN_SUM" +
" , SUM(CITI) CITI_SUM" +
" , SUM(HANA) HANA_SUM" +
" , SUM(NONGHYUP) NONGHYUP_SUM" +
" , SUM(KE) KE_SUM" +
" , SUM(ETC) ETC_SUM" +
" FROM HOU_FNC_SUPP_STAT" +
" GROUP BY YEAR" +
" ORDER BY YEAR" +
" ) A" +
" ORDER BY A.CITI_SUM DESC" +
" LIMIT 1)" +
" UNION" +
" (SELECT A.YEAR" +
" ,'하나은행' AS INSTITUTE" +
" ,A.HANA_SUM" +
" FROM" +
" (" +
" SELECT YEAR" +
" , SUM(JUTAECK) JUTAECK_SUM" +
" , SUM(KOOKMIN) KOOKMIN_SUM" +
" , SUM(WOORI) WOORI_SUM" +
" , SUM(SHINHAN) SHINHAN_SUM" +
" , SUM(CITI) CITI_SUM" +
" , SUM(HANA) HANA_SUM" +
" , SUM(NONGHYUP) NONGHYUP_SUM" +
" , SUM(KE) KE_SUM" +
" , SUM(ETC) ETC_SUM" +
" FROM HOU_FNC_SUPP_STAT" +
" GROUP BY YEAR" +
" ORDER BY YEAR" +
" ) A" +
" ORDER BY A.HANA_SUM DESC" +
" LIMIT 1)" +
" UNION" +
" (SELECT A.YEAR" +
" ,'농협은행/수협은행' AS INSTITUTE" +
" ,A.NONGHYUP_SUM" +
" FROM" +
" (" +
" SELECT YEAR" +
" , SUM(JUTAECK) JUTAECK_SUM" +
" , SUM(KOOKMIN) KOOKMIN_SUM" +
" , SUM(WOORI) WOORI_SUM" +
" , SUM(SHINHAN) SHINHAN_SUM" +
" , SUM(CITI) CITI_SUM" +
" , SUM(HANA) HANA_SUM" +
" , SUM(NONGHYUP) NONGHYUP_SUM" +
" , SUM(KE) KE_SUM" +
" , SUM(ETC) ETC_SUM" +
" FROM HOU_FNC_SUPP_STAT" +
" GROUP BY YEAR" +
" ORDER BY YEAR" +
" ) A" +
" ORDER BY A.NONGHYUP_SUM DESC" +
" LIMIT 1)" +
" UNION" +
" (SELECT A.YEAR" +
" ,'외환은행' AS INSTITUTE" +
" ,A.KE_SUM" +
" FROM" +
" (" +
" SELECT YEAR" +
" , SUM(JUTAECK) JUTAECK_SUM" +
" , SUM(KOOKMIN) KOOKMIN_SUM" +
" , SUM(WOORI) WOORI_SUM" +
" , SUM(SHINHAN) SHINHAN_SUM" +
" , SUM(CITI) CITI_SUM" +
" , SUM(HANA) HANA_SUM" +
" , SUM(NONGHYUP) NONGHYUP_SUM" +
" , SUM(KE) KE_SUM" +
" , SUM(ETC) ETC_SUM" +
" FROM HOU_FNC_SUPP_STAT" +
" GROUP BY YEAR" +
" ORDER BY YEAR" +
" ) A" +
" ORDER BY A.KE_SUM DESC" +
" LIMIT 1)" +
" UNION" +
" (SELECT A.YEAR" +
" ,'기타은행' AS INSTITUTE" +
" ,A.ETC_SUM" +
" FROM" +
" (" +
" SELECT YEAR" +
" , SUM(JUTAECK) JUTAECK_SUM" +
" , SUM(KOOKMIN) KOOKMIN_SUM" +
" , SUM(WOORI) WOORI_SUM" +
" , SUM(SHINHAN) SHINHAN_SUM" +
" , SUM(CITI) CITI_SUM" +
" , SUM(HANA) HANA_SUM" +
" , SUM(NONGHYUP) NONGHYUP_SUM" +
" , SUM(KE) KE_SUM" +
" , SUM(ETC) ETC_SUM" +
" FROM HOU_FNC_SUPP_STAT" +
" GROUP BY YEAR" +
" ORDER BY YEAR" +
" ) A" +
" ORDER BY A.ETC_SUM DESC" +
" LIMIT 1)" +
" ) B " +
" ORDER BY B.JUTAECK_SUM DESC" +
" LIMIT 1", nativeQuery = true)
List<Object[]> findMaxSuppAmtInst();
@Query(value = " (SELECT YEAR"+
" , SUM(KE)/12 KE_AVG"+
" , '외환은행' BANK"+
" FROM HOU_FNC_SUPP_STAT"+
" GROUP BY YEAR"+
" ORDER BY SUM(KE)/12 ASC"+
" LIMIT 1)"+
" UNION"+
" (SELECT YEAR"+
" , SUM(KE)/12 KE_AVG"+
" , '외환은행' BANK"+
" FROM HOU_FNC_SUPP_STAT"+
" GROUP BY YEAR"+
" ORDER BY SUM(KE)/12 DESC"+
" LIMIT 1)", nativeQuery = true)
List<Object[]> findMinMaxKeAvg();
@Query(value = "SELECT * FROM HOU_FNC_SUPP_STAT WHERE MONTH = :month", nativeQuery = true)
List<HouFncSuppStat> findPredSuppAmountByYearAsc(@Param("month") String month);
} | true |
637a563d5bd1589300239bb2424e0298dce79214 | Java | mkesy/DeansOffice | /src/main/java/com/config/MvcConfig.java | UTF-8 | 907 | 1.984375 | 2 | [] | no_license | package com.config;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import javax.sql.DataSource;
/**
* Created by Mikolaj on 12.09.2017.
*/
@Configuration
public class MvcConfig extends WebMvcConfigurerAdapter {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/home").setViewName("index");
}
@Bean
@ConfigurationProperties("spring.datasource")
public DataSource dataSource() {
return DataSourceBuilder.create().build();
}
}
| true |
511952f2ea6b3a67113b6876984d688569bb7d34 | Java | xaedes/open-loop-search-for-general-video-game-playing | /src/TeamTopbug_HR/TraverseNodes/AStar.java | UTF-8 | 2,238 | 2.84375 | 3 | [] | no_license | package TeamTopbug_HR.TraverseNodes;
import TeamTopbug_HR.HeuristicComparator;
import TeamTopbug_HR.Node;
import TeamTopbug_HR.NodeAdvance;
import controllers.Heuristics.StateHeuristic;
import core.game.StateObservation;
import java.util.*;
public abstract class AStar extends Base {
protected StateHeuristic heuristic;
public AStar(Node origin, NodeAdvance advance, TraverseCallback callback, StateHeuristic heuristic) {
super(origin, advance, callback);
this.heuristic = heuristic;
}
class OpenListComparator implements Comparator<Node> {
private StateHeuristic h;
public OpenListComparator(StateHeuristic h) {
this.h = h;
}
@Override
public int compare(Node o1, Node o2) {
Double g1 = ((Double)o1.traversalMeta);
Double g2 = ((Double)o2.traversalMeta);
Double f1 = g1 + h.evaluateState(o1.stateObs);
Double f2 = g2 + h.evaluateState(o2.stateObs);
return f1.compareTo(f2);
}
}
@Override
public void startTraverse() {
PriorityQueue<Node> open = new PriorityQueue<Node>(10,new OpenListComparator(heuristic));
Set<Node> closed = new HashSet<Node>();
open.add(origin);
origin.traversalMeta = new Double(0);
do {
Node current = open.remove();
if (callback.traverse(current)) {
closed.add(current);
List<Node> advanced = advance.advance(current);
for (Node node : advanced) {
if(closed.contains(node))
continue;
Double g = ((Double)current.traversalMeta) + cost(node);
if(open.contains(node) && g > ((Double)node.traversalMeta))
continue;
current.traversalMeta = g;
node.traversalMeta = (Double)(g + heuristic.evaluateState(node.stateObs));
if(open.contains(node)){
open.remove(node);
}
open.add(node);
}
}
} while (!open.isEmpty());
}
abstract protected double cost(Node node);
}
| true |
787e1838719f8eceb62ef86dff84ad962093b183 | Java | Bgh237/Programming_Course_Java | /chapter5/ArrayBloodTypes.java | UTF-8 | 734 | 3.46875 | 3 | [] | no_license | package chapter5;
import java.text.DecimalFormat;
import java.util.Scanner;
public class ArrayBloodTypes {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
DecimalFormat dec = new DecimalFormat("0");
String[] bloodType = { "A+", "O-", "AB+", "O+", "AB+", "AB+", "O-", "AB+", "O+", "AB+" };
System.out.print("Enter blood type: ");
String type = input.nextLine();
double total = bloodType.length;
double counter = 0;
for (int i = 0; i < total; i++) {
if (bloodType[i].contains(type)) {
counter++;
}
}
double percentage = (counter / total) * 100;
System.out.println(dec.format(percentage) + ",0 %");
input.close();
}
}
| true |
6c19297cb6f69b3a32db2c658a103e5e1dc11e0c | Java | mechevarria/cp-sso | /springboot-api/src/main/java/com/sapns2/springbootapi/types/TypesService.java | UTF-8 | 744 | 2.21875 | 2 | [] | no_license | package com.sapns2.springbootapi.types;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
@Service
public class TypesService {
@Autowired
private JdbcTemplate jdbcTemplate;
public List<String> getData() {
String query = "SELECT DISTINCT TA_TYPE FROM \"$TA_EVENT.fti_notes\"";
List<String> data = new ArrayList<>();
List<Map<String, Object>> rows = jdbcTemplate.queryForList(query);
for (Map<String, Object> row : rows) {
data.add((String) row.get("TA_TYPE"));
}
return data;
}
} | true |
b153e10d16a868b96a72b918706dc1342fe26959 | Java | JeffRhine/jeffJavaExercises | /m1-w3d2-unit-testing-exercises/src/test/java/com/techelevator/HomeworkAssignmentTest.java | UTF-8 | 2,142 | 2.984375 | 3 | [] | no_license | package com.techelevator;
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class HomeworkAssignmentTest {
HomeworkAssignment sut;
@Before //part of arrange step, works for every test
public void setUp() throws Exception {
sut = new HomeworkAssignment(100);
}
@After
public void tearDown() throws Exception {
}
@Test
public void testConstructor() {
assertEquals(100,sut.getPossibleMarks());
}
@Test
public void testLetterGradeA() {
//arrange step, arranging test data
sut.setTotalMarks(100);
//act
String grade = sut.getLetterGrade();
//assert
assertEquals("A",grade);
}
@Test
public void testLetterGradeF() {
sut.setTotalMarks(50);
String grade = sut.getLetterGrade();
assertEquals("F",grade);
}
@Test
public void testLetterGradeAlow() {
sut.setTotalMarks(90);
String grade = sut.getLetterGrade();
assertEquals("A",grade);
}
@Test
public void testLetterGradeB() {
sut.setTotalMarks(89);
String grade = sut.getLetterGrade();
assertEquals("B",grade);
}
@Test
public void testLetterGradeBlow() {
sut.setTotalMarks(80);
String grade = sut.getLetterGrade();
assertEquals("B",grade);
}
@Test
public void testLetterGradeC() {
sut.setTotalMarks(79);
String grade = sut.getLetterGrade();
assertEquals("C",grade);
}
@Test
public void testLetterGradeClow() {
sut.setTotalMarks(70);
String grade = sut.getLetterGrade();
assertEquals("C",grade);
}
@Test
public void testLetterGradeD() {
sut.setTotalMarks(69);
String grade = sut.getLetterGrade();
assertEquals("D",grade);
}
@Test
public void testLetterGradeDlow() {
sut.setTotalMarks(60);
String grade = sut.getLetterGrade();
assertEquals("D",grade);
}
@Test
public void testLetterGradeAPlus() {
//arrange step, arranging test data
sut.setTotalMarks(101);
//act
String grade = sut.getLetterGrade();
//assert
assertEquals("A",grade);
}
@Test
public void testLetterGradeFMinus() {
sut.setTotalMarks(-1);
String grade = sut.getLetterGrade();
assertEquals("F",grade);
}
}
| true |
0d4b7188854ab7c5e08eab62620a8bfc31a0ad46 | Java | dvtkachenko/JavaGroup2016 | /src/com/brainacad/module2_02/lab/Matrix.java | UTF-8 | 1,899 | 3.484375 | 3 | [] | no_license | package com.brainacad.module2_02.lab;
import java.util.Arrays;
/**
* Created by Дима on 03.12.2016.
*/
public class Matrix {
private boolean checkMatrix(int[][] matr1, int [][] matr2) {
if(matr1.length != matr2.length)
return false;
else {
int size = matr1.length;
for (int row = 0; row < size; row++) {
if (matr1[row].length != size || matr2[row].length != size) {
return false;
}
}
}
return true;
}
public void printMatrix(int[][] matr) {
for (int[] row : matr) {
System.out.println(Arrays.toString(row));
}
}
public int[][] addMatrix(int[][] matr1, int [][] matr2) {
if (!checkMatrix(matr1, matr2))
return null;
int[][] result = new int[matr1.length][matr1.length];
for (int i=0; i < result.length; i++) {
for (int j=0; j < result.length; j++) {
result[i][j] = matr1[i][j] + matr2[i][j];
}
}
return result;
}
public int[][] initMatrix(int size) {
int [][] matrix = new int[size][size];
for (int i=0; i < matrix.length; i++) {
for (int j=0; j < matrix.length; j++) {
matrix[i][j] = (int)(Math.random()*10);
}
}
return matrix;
}
public int[][] multMatrix(int[][] matr1, int [][] matr2) {
if (!checkMatrix(matr1,matr2))
return null;
int [][] result = new int[matr1.length][matr1.length];
for (int i=0; i < result.length; i++) {
for (int j=0; j < result.length; j++) {
for (int k =0; k < result.length; k++) {
result[i][j] += matr1[i][k] * matr2[k][j];
}
}
}
return result;
}
}
| true |
4793ed021b3201e9189534aaf31a22fd0576501a | Java | stramosk98/At.05---Vetor-e-Matriz | /atx15.java | UTF-8 | 695 | 3.09375 | 3 | [] | no_license | package vetor;
import java.util.Scanner;
public class atx15 {
public static void main(String[] args) {
Scanner entrada = new Scanner(System.in);
int[] n = new int[30];
int[] m = new int[30];
int j = 0;
int media = 0;
for(int i = 0; i < 30; i++){
System.out.println("Digite uma idade: " );
n[i] = Integer.parseInt(entrada.nextLine());
for(int h = 0; h < 30; h++){
System.out.println("Digite a altura: " );
m[h] = Integer.parseInt(entrada.nextLine());
media += (m[h]);
if(n[i] > 13 && n[i] < media)
j += (n[i]);
}
}
media = media / 30;
System.out.println(j);
entrada.close();
}
}
| true |
df4aabdab537e1d2cf25f2183a1d8163f1a4afb6 | Java | CundariNicolas/unqui-poo2-cundari | /test/tp3/unq/MultioperadorTestCase.java | UTF-8 | 1,393 | 2.984375 | 3 | [] | no_license | package tp3.unq;
import static org.junit.jupiter.api.Assertions.*;
import java.util.ArrayList;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class MultioperadorTestCase {
ArrayList<Integer> arregloEnteros = new ArrayList<Integer>();
ArrayList<Integer> arregloEnteros2 = new ArrayList<Integer>();
ArrayList<Integer> arregloEnteros3 = new ArrayList<Integer>();
Multioperador operador = new Multioperador();
@BeforeEach
void setUp() throws Exception {
arregloEnteros.add(3);
arregloEnteros.add(5);
arregloEnteros.add(2);
arregloEnteros2.add(-2);
arregloEnteros2.add(-5);
arregloEnteros2.add(-5);
arregloEnteros3.add(-4);
arregloEnteros3.add(10);
arregloEnteros3.add(-1);
}
@Test
void testOperadoresSumar() {
assertEquals(10, operador.sumar(arregloEnteros));
assertEquals(-12, operador.sumar(arregloEnteros2));
assertEquals(5, operador.sumar(arregloEnteros3));
}
@Test
void testOperadoresResta() {
assertEquals(-10, operador.restar(arregloEnteros));
assertEquals(12 ,operador.restar(arregloEnteros2));
assertEquals(-5, operador.restar(arregloEnteros3));
}
@Test
void testOperadoresMult() {
assertEquals(30, operador.multiplicar(arregloEnteros));
assertEquals(-50, operador.multiplicar(arregloEnteros2));
assertEquals(40, operador.multiplicar(arregloEnteros3));
}
}
| true |
864890e7c7e55be517020a2e6fab77d598e7d8a3 | Java | scc-digitalhub/dremio-oss | /sabot/kernel/src/main/java/com/dremio/sabot/exec/cursors/FileReaderMonitor.java | UTF-8 | 2,716 | 2.28125 | 2 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | /*
* Copyright (C) 2017-2019 Dremio Corporation
*
* 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.dremio.sabot.exec.cursors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.dremio.sabot.threads.sharedres.SharedResource;
import com.google.common.base.Preconditions;
/**
* Monitor to block reader if it has caught up with the writer.
*/
class FileReaderMonitor {
private static final Logger logger = LoggerFactory.getLogger(FileReaderMonitor.class);
private final SharedResource resource;
private long writeCursor;
private long readCursor;
private boolean writerFinished;
FileReaderMonitor(SharedResource resource) {
this.resource = resource;
resource.markBlocked();
}
void updateWriteCursor(long updatedCursor) {
synchronized (resource) {
Preconditions.checkArgument(updatedCursor >= writeCursor);
writeCursor = updatedCursor;
if (!resource.isAvailable() && writeCursor > readCursor) {
// writer has moved ahead, unblock the reader resource.
//logger.debug("unblock resource {} writeCursor {} readCursor {}", resource.getName(), writeCursor, readCursor);
resource.markAvailable();
}
}
}
void markWriterFinished() {
synchronized (resource) {
writerFinished = true;
resource.markAvailable();
}
}
void updateReadCursor(long updatedCursor) {
synchronized (resource) {
Preconditions.checkArgument(updatedCursor >= readCursor,
"cursor should not decrease, updatedCursor " + updatedCursor + " readCursor " + readCursor);
Preconditions.checkArgument(updatedCursor <= writeCursor,
"read cursor should be <= writeCursor, updatedCursor " + updatedCursor + " writeCursor " + writeCursor);
readCursor = updatedCursor;
if (readCursor == writeCursor && !writerFinished) {
// reader has caught up to the writer, block the reader resource.
//logger.debug("block resource {} writeCursor {} readCursor {}", resource.getName(), writeCursor, readCursor);
resource.markBlocked();
}
}
}
long getReadCursor() {
return readCursor;
}
long getWriteCursor() {
return writeCursor;
}
}
| true |
9b9d26ff743a39406ae025b6ad4b4bff09ef7691 | Java | abhishekshakya-np/java | /src/abishek/learn1.java | UTF-8 | 316 | 2.578125 | 3 | [] | no_license | package abishek;
import java.util.Scanner;
class learn1 {
public static void main(String args[]) {
Scanner bucky = new Scanner(System.in);
int boy = 6;
int girls = 4;
System.out.println(boy++);
System.out.println(boy);
System.out.println(girls--);
System.out.println(girls);
bucky.close();
}
}
| true |
e96a50a32375d89a68f03506fb3f9990bbc3a464 | Java | dhineshd/Bioscope | /app/src/main/java/com/trioscope/chameleon/stream/PreviewStreamer.java | UTF-8 | 5,841 | 2.25 | 2 | [] | no_license | package com.trioscope.chameleon.stream;
import android.graphics.Bitmap;
import com.google.gson.Gson;
import com.trioscope.chameleon.ChameleonApplication;
import com.trioscope.chameleon.camera.impl.FrameInfo;
import com.trioscope.chameleon.listener.CameraFrameAvailableListener;
import com.trioscope.chameleon.listener.CameraFrameBuffer;
import com.trioscope.chameleon.listener.CameraFrameData;
import com.trioscope.chameleon.types.CameraInfo;
import com.trioscope.chameleon.types.Size;
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.lang.ref.WeakReference;
import java.nio.ByteBuffer;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
/**
* Created by dhinesh.dharman on 9/28/15.
*/
@Slf4j
@RequiredArgsConstructor
public class PreviewStreamer implements NetworkStreamer, CameraFrameAvailableListener {
private static final int STREAMING_FRAMES_PER_SEC = 15;
private static final int STREAMING_COMPRESSION_QUALITY = 30; // 0 worst - 100 best
private static final Size DEFAULT_STREAM_IMAGE_SIZE = new Size(480, 270); // 16 : 9
private static final int MAX_TOLERABLE_CONSECUTIVE_FAILURE_COUNT = 0;
@NonNull
private volatile CameraFrameBuffer cameraFrameBuffer;
private volatile OutputStream destOutputStream;
private volatile long previousFrameSendTimeMs = 0;
private final ByteArrayOutputStream stream =
new ByteArrayOutputStream(ChameleonApplication.STREAM_IMAGE_BUFFER_SIZE_BYTES);
private final Gson gson = new Gson();
private Size cameraFrameSize = ChameleonApplication.getDefaultCameraFrameSize();
private int streamPreviewWidth = DEFAULT_STREAM_IMAGE_SIZE.getWidth();
private int streamPreviewHeight = DEFAULT_STREAM_IMAGE_SIZE.getHeight();
private int consecutiveFailureCount = 0;
private ByteBuffer inputByteBuffer = ByteBuffer.allocateDirect(
cameraFrameSize.getWidth() * cameraFrameSize.getHeight() * 3/2);
private ByteBuffer outputByteBuffer = ByteBuffer.allocateDirect(
streamPreviewWidth * streamPreviewHeight * 3/2);
private ByteBuffer scalingByteBuffer = ByteBuffer.allocateDirect(
streamPreviewWidth * streamPreviewHeight * 3/2);
private ByteBuffer rotationByteBuffer = ByteBuffer.allocateDirect(
streamPreviewWidth * streamPreviewHeight * 3/2);
@Override
public void startStreaming(OutputStream destOs) {
if (destOs != null) {
destOutputStream = destOs;
cameraFrameBuffer.addListener(this);
consecutiveFailureCount = 0;
previousFrameSendTimeMs = 0;
}
}
@Override
public void stopStreaming() {
cameraFrameBuffer.removeListener(this);
destOutputStream = null;
}
@Override
public boolean isStreaming() {
// Sent something recently
return (System.currentTimeMillis() - previousFrameSendTimeMs) <= 1000;
}
@Override
public void onFrameAvailable(final CameraInfo cameraInfos, final CameraFrameData data, final FrameInfo frameInfo) {
int cameraWidth = cameraInfos.getCameraResolution().getWidth();
int cameraHeight = cameraInfos.getCameraResolution().getHeight();
if (shouldStreamCurrentFrame()) {
log.debug("Decided to send current frame across stream");
try {
stream.reset();
inputByteBuffer.clear();
outputByteBuffer.clear();
byte[] byteArray = null;
if (cameraInfos.getEncoding() == CameraInfo.ImageEncoding.YUV_420_888) {
if (data.getBytes() != null) {
inputByteBuffer.put(data.getBytes());
byteArray = CameraFrameUtil.convertYUV420888ByteBufferToJPEGByteArray(
inputByteBuffer, outputByteBuffer, scalingByteBuffer,
rotationByteBuffer, stream, cameraWidth, cameraHeight, streamPreviewWidth,
streamPreviewHeight, STREAMING_COMPRESSION_QUALITY,
frameInfo.isHorizontallyFlipped(), frameInfo.getOrientationDegrees());
}
} else if (cameraInfos.getEncoding() == CameraInfo.ImageEncoding.NV21) {
byteArray = CameraFrameUtil.convertNV21ToJPEGByteArray(data.getBytes(),
stream, cameraWidth, cameraHeight, streamPreviewWidth, streamPreviewHeight,
STREAMING_COMPRESSION_QUALITY);
} else if (cameraInfos.getEncoding() == CameraInfo.ImageEncoding.RGBA_8888) {
new WeakReference<Bitmap>(CameraFrameUtil.convertToBmp(data.getInts(), cameraWidth, cameraHeight)).get()
.compress(Bitmap.CompressFormat.JPEG, STREAMING_COMPRESSION_QUALITY, stream);
byteArray = stream.toByteArray();
}
if (byteArray != null) {
log.debug("Stream image type = {}, size = {} bytes", cameraInfos.getEncoding(), byteArray.length);
destOutputStream.write(byteArray, 0, byteArray.length);
}
previousFrameSendTimeMs = System.currentTimeMillis();
consecutiveFailureCount = 0;
} catch (Exception e) {
consecutiveFailureCount++;
log.warn("Failed to send data to client", e);
}
}
}
private boolean shouldStreamCurrentFrame() {
return ((destOutputStream != null) &&
(consecutiveFailureCount <= MAX_TOLERABLE_CONSECUTIVE_FAILURE_COUNT) &&
((System.currentTimeMillis() - previousFrameSendTimeMs) >=
(1000 / STREAMING_FRAMES_PER_SEC)));
}
}
| true |
41e51ffa639ee1dce472f35a81c97ebe13a4cbf1 | Java | mexmanny/msccbrewery | /src/main/java/spring/project/msccbrewery/web/controller/BeerController.java | UTF-8 | 2,520 | 2.15625 | 2 | [] | no_license | package spring.project.msccbrewery.web.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import spring.project.msccbrewery.services.BeerService;
import spring.project.msccbrewery.web.client.BreweryClient;
import spring.project.msccbrewery.web.model.BeerDto;
import java.util.UUID;
@RequestMapping("/api/v1/beer")
@RestController //includes repsonse body and controller
public class BeerController {
@Value("${sfg.brewery.apiHost}")
String apiHost;
@Autowired
private final BeerService beerService;
@Autowired
BreweryClient breweryClient;
public BeerController (BeerService beerService) {
this.beerService = beerService;
}
@GetMapping({"/{beerId}"})
public ResponseEntity<BeerDto> getBeer (@PathVariable ("beerId")UUID beerId) {
return new ResponseEntity<>(beerService.getBeerById(beerId), HttpStatus.OK);
}
@PostMapping
public ResponseEntity saveNewBeer (@RequestBody BeerDto beerDto) {
BeerDto saveDto = beerService.saveNewBeer(beerDto);
HttpHeaders headers = new HttpHeaders();
//todo add hostname to url
breweryClient.setApiHost(apiHost);
headers.add("Location", "/api/v1/beer/" + saveDto.getId().toString()) ;
return new ResponseEntity(headers, HttpStatus.CREATED);
}
@PutMapping({"/{beerId}"})
public ResponseEntity updateBeerById(@PathVariable ("beerId")UUID beerId, @RequestBody BeerDto beerDto) {
//beerService.updateBeer(beerId, beerDto);
return new ResponseEntity(HttpStatus.NO_CONTENT);
}
@DeleteMapping ({"/{beerId}"})
@ResponseStatus(HttpStatus.NO_CONTENT)
public void deleteBeer (@PathVariable UUID beerId) {
// beerService.deleteById(beerId);
}
}
| true |
757b803be26dbffb51f39b89c31d5bc3cc16681d | Java | IlyasPatel/rest | /src/main/java/QeHttpRequest.java | UTF-8 | 3,318 | 2.546875 | 3 | [] | no_license | import org.apache.http.HttpHeaders;
import org.apache.http.entity.ContentType;
import java.io.File;
import java.io.InputStream;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;
public class QeHttpRequest {
private URI uri;
private Map<String, String> headers = new HashMap<>();
private String certificate;
private File certificateFile;
private HttpVerb verb;
private String body;
private QeHttpRequest() {
this.certificate = "";
this.body = "";
this.verb = HttpVerb.GET;
}
public static Builder newBuilder() {
return new Builder();
}
private final QeHttpRequest setUri(URI uri) {
this.uri = uri;
return this;
}
public static class Builder {
private QeHttpRequest request = new QeHttpRequest();
public Builder withUri(URI uri) {
request.setUri(uri);
return this;
}
public Builder withDefaultHeaders() {
withContentTypeHeader();
return this;
}
public Builder withHeader(String name, String value) {
request.headers.put(name, value);
return this;
}
public Builder withContentTypeHeader() {
request.headers.put(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString());
return this;
}
public Builder withHeaders(Map<String, String> httpHeaders) {
httpHeaders.forEach((k, v) -> {
request.headers.put(k, v);
});
return this;
}
public Builder withNoHeaders() {
request.headers.clear();
return this;
}
public Builder withCertificate(File certificate) {
request.certificateFile = certificate;
return this;
}
public Builder get() {
request.verb = HttpVerb.GET;
return this;
}
public Builder post() {
request.verb = HttpVerb.POST;
return this;
}
public Builder post(String body) {
request.verb = HttpVerb.POST;
request.body = body;
return this;
}
public Builder put() {
request.verb = HttpVerb.PUT;
return this;
}
public Builder delete() {
request.verb = HttpVerb.DELETE;
return this;
}
public Builder options() {
request.verb = HttpVerb.OPTIONS;
return this;
}
public Builder head() {
request.verb = HttpVerb.HEAD;
return this;
}
public QeHttpRequest build() {
return request;
}
private InputStream getCertificateInputStream() {
return QeHttpRequest.class.getResourceAsStream(request.certificate);
}
}
public URI getUri() {
return uri;
}
public Map<String, String> getHttpHeaders() {
return headers;
}
public String getCertificate() {
return certificate;
}
public File getCertificateFile() {
return certificateFile;
}
public HttpVerb getVerb() {
return verb;
}
public String getBody() {
return body;
}
}
| true |
370ca79df6d93812a8e3e357646ad8f4248fc573 | Java | dtrimo/battleships.isdc.eu | /src/main/java/eu/isdc/internship/service/livegame/events/UserLeftGameEvent.java | UTF-8 | 267 | 1.5625 | 2 | [] | no_license | package eu.isdc.internship.service.livegame.events;
public class UserLeftGameEvent extends UserRelatedGameEvent{
public UserLeftGameEvent(){}
public UserLeftGameEvent(Long userId, Long gameId, Long startConfigId){
super(userId, gameId, startConfigId);
}
}
| true |
12f7af7e1b5c661db4228385f2c2d570c16cd11d | Java | dozzman/coding-practice | /Java/sorting/BubbleSort.java | UTF-8 | 832 | 3.828125 | 4 | [
"Apache-2.0"
] | permissive | package sorting;
import java.lang.*;
import java.util.*;
public class BubbleSort<T extends Comparable<T>> extends Sorter<T>
{
public String sortName() { return "Bubble Sort"; }
public void sort(T array [])
{
boolean swapped = true;
while (swapped == true)
{
swapped = false;
for(int i = 1; i < array.length; i++)
{
// javadocs gives the relation as { (x,y) s.t. x.compareTo(y) <= 0}, however I am making
// it { (x,y) s.t. x.compareTo(y) < 0 } so that were not swapping equal values
if (array[i].compareTo(array[i-1]) < 0)
{
// swap the values
swap(array, i, i-1);
swapped = true;
}
}
}
}
}
| true |
24c5c0bb16b8aecde89370997865aaa8e2e64d02 | Java | Jaime001/Store-and-Products-JAVA | /src/Helper.java | UTF-8 | 3,855 | 3.453125 | 3 | [] | no_license | import java.util.ArrayList;
import java.util.Locale;
import java.util.Scanner;
public class Helper {
public static String outputStringInput(String text){
Scanner scan = new Scanner(System.in);
System.out.println(text);
return scan.next();
}
public static Integer outputIntegerInput(String text){
Scanner scan = new Scanner(System.in);
System.out.println(text);
return scan.nextInt();
}
public static void informationStoreByProduct(ArrayList<Store> storesList){
boolean flag = false;
String productName = Helper.outputStringInput("Input product name: ");
// capitalize first letter
productName = productName.substring(0, 1).toUpperCase() + productName.substring(1).toLowerCase();
for (Store store: storesList) {
for (Product product: store.storeListOfProducts) {
if (product.productName.equals(productName)){
System.out.println("Store ID: " + store.storeID + ", Store name: " + store.storeName + ", Location: " + store.location());
flag = true;
}
}
}
if (flag == false) System.out.println("The product doesn't exist!");
}
public static void locationStore(ArrayList<Store> storesList){
String name = Helper.outputStringInput("Input store name: ");
name = name.substring(0, 1).toUpperCase() + name.substring(1).toLowerCase();
String location = null;
for (Store store: storesList) {
if (name.equals(store.storeName())){
location = store.location();
}
}
if (location == null) System.out.println("The store doesn't exist!");
else System.out.println(location);
}
public static void totalProduct(ArrayList<Store> storesList){
double total = 0;
String name = Helper.outputStringInput("Input store name: ");
name = name.substring(0, 1).toUpperCase() + name.substring(1).toLowerCase();
for (Store store: storesList) {
if (name.equals(store.storeName())){
for (Product product: store.storeListOfProducts) {
System.out.println(product.productName + ": " + product.productCost);
total += product.productCost;
}
System.out.println("The total is: " + total);
}
}
if (total == 0) System.out.println("The store doesn't exist!");
}
public static void compareProducts(ArrayList<Store> storesList){
boolean flag = false;
String name = Helper.outputStringInput("Input product name: ");
name = name.substring(0, 1).toUpperCase() + name.substring(1).toLowerCase();
for (Store store: storesList) {
for (Product product: store.storeListOfProducts) {
if (product.productName.equals(name)){
System.out.println(store.storeName + ": " + product.productName + "(" + product.productCost + ")");
flag = true;
}
}
}
if (flag == false) System.out.println("The product doesn't exist!");
}
public static void welcome(){
System.out.println("Welcome to this program, choose an option between 1 and 4: ");
System.out.println("1) Display the store details with Store id, name and location for the given product name.");
System.out.println("2) Display the location details to the user for the requested store name.");
System.out.println("3) Display the Total products asset value of the store for the requested store name.");
System.out.println("4) Compare the prices of the requested product name by the user in all the relevant stores in the\n" +
"mall and display.");
}
}
| true |
0d26a0c7d3167749ddf88993102e4ce757106b36 | Java | Aaronong/ThePrinceRPG | /src/items/MagicianItems.java | UTF-8 | 2,930 | 3.171875 | 3 | [] | no_license | package items;
public class MagicianItems {
private int myStaff;
private int myMagicEssence;
private int myArmour;
private String[] Staff = new String[5];
private String[] MagicEssence = new String[5];
private String[] LightArmour = new String[5];
private int[] StaffInt = new int[5];
private int[] MagicEssenceInt = new int[5];
private int[] LightArmourVit = new int[5];
private String[] StaffDes = new String[5];
private String[] MagicEssenceDes = new String[5];
private String[] LightArmourDes = new String[5];
public MagicianItems(){
//Set these variables
myStaff = 0;
myMagicEssence = 0;
myArmour = 0;
//Get these variables
Staff[0] = "Oak Staff";
Staff[1] = "Wizard's pride";
Staff[2] = "Manabreaker";
Staff[3] = "Dark Laevateinn";
Staff[4] = "Seraphim";
MagicEssence[0] = "Rabbit's Foot";
MagicEssence[1] = "Magic Mushroom";
MagicEssence[2] = "Timeless Myst";
MagicEssence[3] = "Fairy Dust";
MagicEssence[4] = "Phoenix Teardrop";
LightArmour[0] = "Plain Robe";
LightArmour[1] = "Explorer's moonlight";
LightArmour[2] = "Dark Chaos Robe";
LightArmour[3] = "Oriental Fury";
LightArmour[4] = "Balzag's Requiem";
StaffInt[0] = 5;
StaffInt[1] = 10;
StaffInt[2] = 15;
StaffInt[3] = 20;
StaffInt[4] = 25;
MagicEssenceInt[0] = 3;
MagicEssenceInt[1] = 6;
MagicEssenceInt[2] = 9;
MagicEssenceInt[3] = 12;
MagicEssenceInt[4] = 15;
LightArmourVit[0] = 5;
LightArmourVit[1] = 10;
LightArmourVit[2] = 15;
LightArmourVit[3] = 20;
LightArmourVit[4] = 25;
StaffDes[0] = "Int +5";
StaffDes[1] = "Int + 10";
StaffDes[2] = "Int + 15";
StaffDes[3] = "Int + 20";
StaffDes[4] = "Int + 25";
MagicEssenceDes[0] = "Int +3";
MagicEssenceDes[1] = "Int +6";
MagicEssenceDes[2] = "Int +9";
MagicEssenceDes[3] = "Int +12";
MagicEssenceDes[4] = "Int +15";
LightArmourDes[0] = "Vit +5";
LightArmourDes[1] = "Vit +10";
LightArmourDes[2] = "Vit +15";
LightArmourDes[3] = "Vit +20";
LightArmourDes[4] = "Vit +25";
}
public void setMyStaff (int i){
myStaff = i;
}
public void setMyMagicEssence (int i){
myMagicEssence = i;
}
public void setMyArmour (int i){
myArmour = i;
}
public String getStaffName(){
return Staff[myStaff];
}
public String getMagicEssenceName(){
return MagicEssence[myMagicEssence];
}
public String getArmourName(){
return LightArmour[myArmour];
}
public int getStaffInt(){
return StaffInt[myStaff];
}
public int getMagicEssenceInt(){
return MagicEssenceInt[myMagicEssence];
}
public int getArmourVit(){
return LightArmourVit[myArmour];
}
public String getStaffDes(){
return StaffDes[myStaff];
}
public String getMagicEssenceDes(){
return MagicEssenceDes[myMagicEssence];
}
public String getArmourDes(){
return LightArmourDes[myArmour];
}
}
| true |
da629c3de4b54ed8b23c0e9de90d7ae02b64c3a3 | Java | polipoly/defaultRepository | /mblog/mblog-extend/src/main/java/mblog/extend/planet/CommentPlanet.java | UTF-8 | 868 | 1.90625 | 2 | [
"Apache-2.0"
] | permissive | /*
+--------------------------------------------------------------------------
| Mblog [#RELEASE_VERSION#]
| ========================================
| Copyright (c) 2014, 2015 mtons. All Rights Reserved
| http://www.mtons.com
|
+---------------------------------------------------------------------------
*/
package mblog.extend.planet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import mblog.data.Comment;
import mtons.modules.pojos.Paging;
/**
* @author langhsu
*
*/
public interface CommentPlanet {
Paging paging(Paging paging, long toId);
Paging paging4Home(Paging paging, long authoId);
/**
* 发表评论
* @param comment
* @return
*/
long post(Comment comment);
void delete(List<Long> ids);
/**
* 带作者验证的删除
* @param id
* @param authorId
*/
void delete(long id, long authorId);
}
| true |
2827eb1d3368419e7c72ba3c897de3a1fa952451 | Java | anaelChardan/Mines-A1-CoursArchitecture | /EntrainementControle/src/data/phrase/IPhrase.java | UTF-8 | 502 | 2.578125 | 3 | [] | no_license | package data.phrase;
import vocabulary.Vocabulaire;
public interface IPhrase {
/**
* Taille de la phrase.
* @return
*/
public int size();
public String toString();
/**
* Check if the sentence is meaningful.
* @return
*/
public boolean meaningful();
/**
* Teste si PAUL est en premier.
* @return
*/
public boolean isPaul();
/**
* Teste si PIERRE est premier et EAU dedans.
* @return
*/
public boolean isPierreEau();
public boolean contient(Vocabulaire voc);
}
| true |
f9359d476d83a608c6eb2247118ff2b2cdc09074 | Java | PiotrTrawinski/Kalambury | /Kalambury/src/kalambury/server/ServerMessage.java | UTF-8 | 896 | 2.578125 | 3 | [] | no_license | package kalambury.server;
import kalambury.sendableData.SendableData;
public class ServerMessage {
public enum ReceiverType{
All,
AllExcept,
One
}
private final SendableData data;
private final ReceiverType receiverType;
private final int param;
public ServerMessage(SendableData data, ReceiverType receiverType, int param){
this.data = data;
this.receiverType = receiverType;
this.param = param;
}
public ServerMessage(SendableData data, ReceiverType receiverType){
this.data = data;
this.receiverType = receiverType;
this.param = -1;
}
public SendableData getData(){
return data;
}
public ReceiverType getReceiverType(){
return receiverType;
}
public int getParam(){
return param;
}
}
| true |
e705a4056ca77b44f94fa6920e0fa813aa522b0d | Java | henrique3m/appservice-java-api | /src/gen/java/io/swagger/api/BooksApi.java | UTF-8 | 3,942 | 2.171875 | 2 | [] | no_license | package io.swagger.api;
import io.swagger.model.*;
import io.swagger.api.BooksApiService;
import io.swagger.api.factories.BooksApiServiceFactory;
import io.swagger.annotations.ApiParam;
import io.swagger.jaxrs.*;
import io.swagger.model.Book;
import java.util.List;
import io.swagger.api.NotFoundException;
import java.io.InputStream;
import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
import org.glassfish.jersey.media.multipart.FormDataParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.SecurityContext;
import javax.ws.rs.*;
import javax.validation.constraints.*;
@Path("/books")
@io.swagger.annotations.Api(description = "the books API")
@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaJerseyServerCodegen", date = "2017-06-25T15:20:54.704Z")
public class BooksApi {
private final BooksApiService delegate = BooksApiServiceFactory.getBooksApi();
@DELETE
@Path("/{isbn}")
@Produces({ "application/json", "text/json" })
@io.swagger.annotations.ApiOperation(value = "Delete book from store", notes = "", response = void.class, tags={ "Book", })
@io.swagger.annotations.ApiResponses(value = {
@io.swagger.annotations.ApiResponse(code = 200, message = "OK", response = void.class) })
public Response deleteBook(@ApiParam(value = "",required=true) @PathParam("isbn") String isbn
,@Context SecurityContext securityContext)
throws NotFoundException {
return delegate.deleteBook(isbn,securityContext);
}
@GET
@Path("/isbn/{isbn}")
@Produces({ "application/json", "text/json" })
@io.swagger.annotations.ApiOperation(value = "Get book by ISBN", notes = "", response = Book.class, tags={ "Book", })
@io.swagger.annotations.ApiResponses(value = {
@io.swagger.annotations.ApiResponse(code = 200, message = "OK", response = Book.class) })
public Response getBookByIsbn(@ApiParam(value = "",required=true) @PathParam("isbn") String isbn
,@Context SecurityContext securityContext)
throws NotFoundException {
return delegate.getBookByIsbn(isbn,securityContext);
}
@GET
@Produces({ "application/json", "text/json" })
@io.swagger.annotations.ApiOperation(value = "", notes = "", response = Book.class, responseContainer = "List", tags={ "Book", })
@io.swagger.annotations.ApiResponses(value = {
@io.swagger.annotations.ApiResponse(code = 200, message = "OK", response = Book.class, responseContainer = "List") })
public Response getBooks(@Context SecurityContext securityContext)
throws NotFoundException {
return delegate.getBooks(securityContext);
}
@GET
@Path("/author/{author}")
@Produces({ "application/json", "text/json" })
@io.swagger.annotations.ApiOperation(value = "Get books by Author", notes = "", response = Book.class, responseContainer = "List", tags={ "Book", })
@io.swagger.annotations.ApiResponses(value = {
@io.swagger.annotations.ApiResponse(code = 200, message = "OK", response = Book.class, responseContainer = "List") })
public Response getBooksByAuthor(@ApiParam(value = "",required=true) @PathParam("author") String author
,@Context SecurityContext securityContext)
throws NotFoundException {
return delegate.getBooksByAuthor(author,securityContext);
}
@POST
@Produces({ "application/json", "text/json" })
@io.swagger.annotations.ApiOperation(value = "Add a new book to the store", notes = "", response = void.class, tags={ "Book", })
@io.swagger.annotations.ApiResponses(value = {
@io.swagger.annotations.ApiResponse(code = 200, message = "OK", response = void.class) })
public Response insertBook(@ApiParam(value = "" ) Book book
,@Context SecurityContext securityContext)
throws NotFoundException {
return delegate.insertBook(book,securityContext);
}
}
| true |
7f6870192b16e2fb4f29f405667d9f78b9741d23 | Java | hortonworks/cloudbreak | /core/src/main/java/com/sequenceiq/cloudbreak/service/cluster/EmbeddedDatabaseService.java | UTF-8 | 6,519 | 1.609375 | 2 | [
"LicenseRef-scancode-warranty-disclaimer",
"ANTLR-PD",
"CDDL-1.0",
"bzip2-1.0.6",
"Zlib",
"BSD-3-Clause",
"MIT",
"EPL-1.0",
"LicenseRef-scancode-proprietary-license",
"LicenseRef-scancode-jdbm-1.00",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | package com.sequenceiq.cloudbreak.service.cluster;
import java.util.Optional;
import javax.inject.Inject;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import com.sequenceiq.cloudbreak.api.endpoint.v4.common.StackType;
import com.sequenceiq.cloudbreak.api.endpoint.v4.stacks.request.database.DatabaseAvailabilityType;
import com.sequenceiq.cloudbreak.auth.altus.EntitlementService;
import com.sequenceiq.cloudbreak.auth.crn.Crn;
import com.sequenceiq.cloudbreak.cloud.service.CloudParameterCache;
import com.sequenceiq.cloudbreak.cmtemplate.CMRepositoryVersionUtil;
import com.sequenceiq.cloudbreak.cmtemplate.CmTemplateProcessor;
import com.sequenceiq.cloudbreak.cmtemplate.CmTemplateProcessorFactory;
import com.sequenceiq.cloudbreak.domain.Blueprint;
import com.sequenceiq.cloudbreak.domain.Template;
import com.sequenceiq.cloudbreak.domain.VolumeTemplate;
import com.sequenceiq.cloudbreak.domain.VolumeUsageType;
import com.sequenceiq.cloudbreak.domain.stack.Database;
import com.sequenceiq.cloudbreak.dto.StackDto;
import com.sequenceiq.cloudbreak.dto.StackDtoDelegate;
import com.sequenceiq.cloudbreak.service.blueprint.BlueprintService;
import com.sequenceiq.cloudbreak.view.ClusterView;
import com.sequenceiq.cloudbreak.view.InstanceGroupView;
import com.sequenceiq.cloudbreak.view.StackView;
@Component
public class EmbeddedDatabaseService {
private static final Logger LOGGER = LoggerFactory.getLogger(EmbeddedDatabaseService.class);
private static final String SSL_ENFORCEMENT_MIN_RUNTIME_VERSION = "7.2.2";
@Inject
private CloudParameterCache cloudParameterCache;
@Inject
private EntitlementService entitlementService;
@Inject
private CmTemplateProcessorFactory cmTemplateProcessorFactory;
@Inject
private BlueprintService blueprintService;
public boolean isEmbeddedDatabaseOnAttachedDiskEnabled(StackDtoDelegate stack, ClusterView cluster) {
return isEmbeddedDatabaseOnAttachedDiskEnabledInternal(stack.getExternalDatabaseCreationType(), stack.getCloudPlatform(), cluster);
}
boolean isEmbeddedDatabaseOnAttachedDiskEnabledByStackView(StackView stack, ClusterView cluster, Database database) {
return isEmbeddedDatabaseOnAttachedDiskEnabledInternal(database != null ? database.getExternalDatabaseAvailabilityType() : null,
stack.getCloudPlatform(), cluster);
}
private boolean isEmbeddedDatabaseOnAttachedDiskEnabledInternal(DatabaseAvailabilityType externalDatabaseCreationType, String cloudPlatform,
ClusterView cluster) {
DatabaseAvailabilityType externalDatabase = ObjectUtils.defaultIfNull(externalDatabaseCreationType, DatabaseAvailabilityType.NONE);
String databaseCrn = cluster == null ? "" : cluster.getDatabaseServerCrn();
return DatabaseAvailabilityType.NONE == externalDatabase
&& StringUtils.isEmpty(databaseCrn)
&& cloudParameterCache.isVolumeAttachmentSupported(cloudPlatform);
}
public boolean isAttachedDiskForEmbeddedDatabaseCreated(StackDto stack) {
Optional<InstanceGroupView> gatewayGroup = stack.getGatewayGroup();
return stack.getCluster().getEmbeddedDatabaseOnAttachedDisk()
&& calculateVolumeCountOnGatewayGroup(gatewayGroup.map(InstanceGroupView::getTemplate)) > 0;
}
public boolean isAttachedDiskForEmbeddedDatabaseCreated(ClusterView cluster, Optional<InstanceGroupView> gatewayGroup) {
return cluster.getEmbeddedDatabaseOnAttachedDisk() && calculateVolumeCountOnGatewayGroup(gatewayGroup.map(InstanceGroupView::getTemplate)) > 0;
}
public boolean isSslEnforcementForEmbeddedDatabaseEnabled(StackView stackView, ClusterView clusterView, Database database) {
String accountId = Crn.safeFromString(stackView.getResourceCrn()).getAccountId();
StackType stackType = stackView.getType();
boolean sslEnforcementEnabled = false;
if (stackType == StackType.DATALAKE) {
sslEnforcementEnabled = true;
} else if (stackType == StackType.WORKLOAD) {
sslEnforcementEnabled = entitlementService.databaseWireEncryptionDatahubEnabled(accountId);
}
String runtime = getRuntime(clusterView);
boolean response = sslEnforcementEnabled && isEmbeddedDatabaseOnAttachedDiskEnabledByStackView(stackView, clusterView, database) &&
isSslEnforcementSupportedForRuntime(runtime);
LOGGER.info("Embedded DB SSL enforcement is {} for runtime version {}", response ? "enabled" : "disabled", runtime);
return response;
}
private String getRuntime(ClusterView clusterView) {
String runtime = null;
Optional<String> blueprintTextOpt = blueprintService.getByClusterId(clusterView.getId()).map(Blueprint::getBlueprintText);
if (blueprintTextOpt.isPresent()) {
CmTemplateProcessor cmTemplateProcessor = cmTemplateProcessorFactory.get(blueprintTextOpt.get());
runtime = cmTemplateProcessor.getStackVersion();
LOGGER.info("Blueprint text is available for stack, found runtime version '{}'", runtime);
} else {
LOGGER.warn("Blueprint text is unavailable for stack, thus runtime version cannot be determined.");
}
return runtime;
}
private boolean isSslEnforcementSupportedForRuntime(String runtime) {
if (StringUtils.isBlank(runtime)) {
// While this may happen for custom data lakes, it is not possible for DH clusters
LOGGER.info("Runtime version is NOT specified, embedded DB SSL enforcement is NOT permitted");
return false;
}
boolean permitted = CMRepositoryVersionUtil.isVersionNewerOrEqualThanLimited(() -> runtime, () -> SSL_ENFORCEMENT_MIN_RUNTIME_VERSION);
LOGGER.info("Embedded DB SSL enforcement {} permitted for runtime version {}", permitted ? "is" : "is NOT", runtime);
return permitted;
}
private int calculateVolumeCountOnGatewayGroup(Optional<Template> gatewayGroupTemplate) {
Template template = gatewayGroupTemplate.orElse(null);
return template == null ? 0 : template.getVolumeTemplates().stream()
.filter(volumeTemplate -> volumeTemplate.getUsageType() == VolumeUsageType.DATABASE)
.mapToInt(VolumeTemplate::getVolumeCount).sum();
}
}
| true |
7f846f04c2217a813bd08b5bccb770dd04f4e1ae | Java | amitmkr/JavaPrep | /src/main/java/com/apm/completableFuture/CompletableFutureTest.java | UTF-8 | 2,840 | 3.390625 | 3 | [] | no_license | package com.apm.completableFuture;
import java.util.Collections;
import java.util.concurrent.CompletableFuture;
import static java.lang.Thread.sleep;
public class CompletableFutureTest {
private static CompletableFuture<?> printMultiplicationSync(int num1, int num2) {
return
getNumberAfterDelay(num1)
.thenCombine(getNumberAfterDelay(num2), CompletableFutureTest::multiply)
.thenAccept(multResult -> System.out.println("The result is " + multResult));
}
private static CompletableFuture<Void> printMultiplicationSync(int num1, int num2, int num3) {
return
getNumberAfterDelay(num1)
.thenCombine(getNumberAfterDelay(num2), CompletableFutureTest::multiply)
.thenCombine(getNumberAfterDelay(num3), CompletableFutureTest::multiply)
.thenAccept(multResult -> System.out.println("The result is " + multResult));
}
/* private static CompletableFuture<Void> printMultiplicationAsync(int num1, int num2) {
getNumberAfterDelay(num1)
.thenCombineAsync(getNumberAfterDelay(num2), CompletableFutureTest::multiply)
.thenAccept(multResult -> System.out.println("The result is " + multResult));
}*/
private static CompletableFuture<Integer> getNumberAfterDelay(int num) {
return CompletableFuture.supplyAsync(() -> {
System.out.println("Getting number in " + num + " seconds");
try { sleep(num * 1000); } catch (Exception e) { System.out.println("Caught Exception"); e.printStackTrace();}
System.out.println("Now returning number after " + num + " seconds");
return Integer.valueOf(num);
}
);
}
private static Integer multiply(Integer number1, Integer number2) {
return number1 * number2;
}
public static void main(String[] args) {
System.out.println("Trying sync with 2 numbers ...");
CompletableFuture<?> first = printMultiplicationSync(5, 10);
System.out.println("Trying sync with 3 numbers ...");
CompletableFuture<?> second = printMultiplicationSync(6, 18, 12);
System.out.println("Waiting for CompletableFutures");
first.join();
second.join();
System.out.println("All CompletableFutures Done");
//System.out.println("Trying async ...");
//printMultiplicationAsync(5, 10);
//try { sleep(60 * 1000) ; } catch (Exception e) { System.out.println("Caught Exception"); e.printStackTrace();}
}
}
/*
Trying sync with 2 numbers ...
Trying sync with 3 numbers ...
Getting number in 18 seconds
Getting number in 10 seconds
Getting number in 6 seconds
Getting number in 12 seconds
Getting number in 5 seconds
Now returning number after 5 seconds
Now returning number after 6 seconds
Now returning number after 10 seconds
The result is 50
Now returning number after 12 seconds
Now returning number after 18 seconds
The result is 1296
Process finished with exit code 0
*/
| true |
cabc0040ed56be76587625aa3409d28609a3475c | Java | LordH/Image-Viewer | /image-viewer-client/src/se/viewer/image/gui/components/viewer/ViewerPanel.java | UTF-8 | 6,342 | 2.375 | 2 | [] | no_license | package se.viewer.image.gui.components.viewer;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.util.ArrayList;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import se.viewer.image.containers.Image;
import se.viewer.image.containers.Tag;
import se.viewer.image.tokens.DeliverThumbnailsToken;
/**
* Class that represents a panel with a picture on it.
* @author Harald Brege
*/
public class ViewerPanel extends JPanel implements ViewerInterface{
private static final long serialVersionUID = -5742181472489084300L;
private String displaying;
private Tag currentTag;
private Image source;
private ImagePanelLarge imagePanel;
private SidePanel sidePanel;
private ThumbnailsPanel thumbnailPanel;
private JPanel rightPanel;
private CardLayout card;
private JFrame parent;
private JProgressBar progress;
private JLabel message;
private JPanel loadingPanel;
public ViewerPanel(JFrame frame) {
this.parent = frame;
}
/**
* Creates a new image view panel
*/
public ViewerPanel() {
//Setting up all components
setLayout(new GridBagLayout());
sidePanel = new SidePanel(null);
sidePanel.setMinimumSize(new Dimension(600, 1));
imagePanel = new ImagePanelLarge();
imagePanel.setVisible(true);
thumbnailPanel = new ThumbnailsPanel(null);
thumbnailPanel.setVisible(true);
progress = new JProgressBar(0, 100);
message = new JLabel();
loadingPanel = new JPanel();
loadingPanel.setLayout(new GridBagLayout());
loadingPanel.setBorder(BorderFactory.createLineBorder(Color.GRAY));
loadingPanel.setPreferredSize(new Dimension(200, 70));
JPanel container = new JPanel(new GridBagLayout());
card = new CardLayout();
rightPanel = new JPanel(card);
rightPanel.add(imagePanel, IMAGE);
rightPanel.add(thumbnailPanel, THUMBNAILS);
rightPanel.add(container, LOADING);
JScrollPane scrollLeft = new JScrollPane(sidePanel);
scrollLeft.getVerticalScrollBar().setUnitIncrement(10);
scrollLeft.getHorizontalScrollBar().setUnitIncrement(10);
scrollLeft.setAutoscrolls(true);
scrollLeft.setBorder(BorderFactory.createLineBorder(Color.GRAY));
scrollLeft.setMinimumSize(new Dimension(320, 1));
JScrollPane scrollRight = new JScrollPane(rightPanel);
scrollRight.getVerticalScrollBar().setUnitIncrement(10);
scrollRight.getHorizontalScrollBar().setUnitIncrement(10);
scrollRight.setAutoscrolls(true);
// scrollRight.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
scrollRight.setName("scroll right");
scrollRight.setBorder(BorderFactory.createLineBorder(Color.GRAY));
scrollRight.addComponentListener(new ComponentListener() {
@Override
public void componentResized(ComponentEvent e) {
if(source != null)
imagePanel.setSizeToFit();
thumbnailPanel.redraw();
updateUI();
}
@Override
public void componentShown(ComponentEvent e) {}
@Override
public void componentMoved(ComponentEvent e) {}
@Override
public void componentHidden(ComponentEvent e) {}
});
//Adding components to the panel
GridBagConstraints c = new GridBagConstraints();
c.anchor = GridBagConstraints.CENTER;
c.fill = GridBagConstraints.VERTICAL;
c.gridx = 0;
c.gridy = 0;
c.weighty = 1;
c.insets = new Insets(40, 40, 40, 20);
add(scrollLeft, c);
c.fill = GridBagConstraints.BOTH;
c.gridx = 1;
c.weightx = 1;
c.insets = new Insets(40, 20, 40, 40);
add(scrollRight, c);
//Adding components to the loading panel
c.anchor = GridBagConstraints.CENTER;
c.fill = GridBagConstraints.NONE;
c.gridx = 0;
c.gridy = 0;
c.weightx = 1;
c.weighty = 1;
c.insets = new Insets(10, 10, 0, 10);
loadingPanel.add(message, c);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridy = 1;
c.weighty = 0;
c.insets = new Insets(10, 10, 10, 10);
loadingPanel.add(progress, c);
c.anchor = GridBagConstraints.CENTER;
c.fill = GridBagConstraints.NONE;
c.gridx = 0;
c.gridy = 0;
container.add(loadingPanel, c);
revalidate();
repaint();
}
//=======================================
// IMAGE HANDLING METHODS
//---------------------------------------
@Override
public void displayImage() {
thumbnailPanel.clearDisplay();
displaying = IMAGE;
currentTag = null;
card.show(rightPanel, IMAGE);
}
@Override
public void setImage(Image image) {
source = image;
imagePanel.setImage(source);
sidePanel.setImage(source);
}
@Override
public void clearImage() {
setImage(null);
}
//=======================================
// TAG HANDLING METHODS
//---------------------------------------
@Override
public void setTags(ArrayList<Tag> tags) {
sidePanel.setTags(tags);
}
//=======================================
// LOADING PANEL HANDLING METHODS
//---------------------------------------
@Override
public void displayLoading() {
thumbnailPanel.clearDisplay();
displaying = LOADING;
card.show(rightPanel, LOADING);
}
@Override
public void setUpdateProgress(String message, int percent) {
this.message.setText(message + " " + percent + "%");
progress.setValue(percent);
}
//=======================================
// THUMBNAIL HANDLING METHODS
//---------------------------------------
@Override
public void displayThumbnails() {
imagePanel.setImage(null);
card.show(rightPanel, THUMBNAILS);
displaying = THUMBNAILS;
parent.setTitle(currentTag.getName());
}
@Override
public void setThumbnails(DeliverThumbnailsToken token) {
if(!token.getTag().equals(currentTag)) {
if(displaying == THUMBNAILS)
thumbnailPanel.clearDisplay();
thumbnailPanel.clearList();
currentTag = token.getTag();
}
thumbnailPanel.addThumbnails(token.getThumbnails());
validate();
thumbnailPanel.repaint();
}
} | true |
3d951b1dc2f0d767586e8eacded5d4dac42fd949 | Java | anccelo/natSystemExo | /exerciceCartes/src/test/java/model/JouerTest.java | UTF-8 | 888 | 2.609375 | 3 | [] | no_license | package model;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import static org.junit.jupiter.api.Assertions.assertEquals;
@ExtendWith(MockitoExtension.class)
public class JouerTest {
private final Joueur jouer = new Joueur("joeur1");
@Mock
Carte carteMock;
@Test
void should_return_zero_when_no_card_has_been_assigned_to_the_player() {
int actual = jouer.getCartes().size();
int expected = 0;
assertEquals(expected, actual);
}
@Test
void should_return_two_when_two_cards_has_been_assigned_to_the_player() {
jouer.assignACard(carteMock);
jouer.assignACard(carteMock);
int actual = jouer.getCartes().size();
int expected = 2;
assertEquals(expected, actual);
}
}
| true |
16eb1b8c307e32a2b229f8ddbde502112426f717 | Java | SGordon94/CS2334Project2 | /Project2_CS2334/src/Meeting.java | UTF-8 | 5,709 | 3.421875 | 3 | [] | no_license | import java.io.Serializable;
import java.util.*;
/**A data-oriented class. Meetings are contained within Conferences.
* They contain ConferencePapers.
*
* @version 1.0
*/
public class Meeting implements Serializable{
private static final long serialVersionUID = 6553738379612061434L;
private String month;
private String year;
private Location location;
private ArrayList<Scholar> programChairs;
private ArrayList<Scholar> committeeMembers;
private ArrayList<ConferencePaper> papers = new ArrayList<ConferencePaper>();
/**The constructor for Meeting objects.
*
* @param fields the date the meeting took place
* @param chairs the program chairs of the meeting
* @param members the committee memebers of the meeting
*/
public Meeting(String[] fields, ArrayList<Scholar> chairs, ArrayList<Scholar> members){
month = fields[0];
year = fields[1];
location = new Location(fields[2], fields[3], fields[4]);
programChairs = chairs;
committeeMembers = members;
}
/**Adds the passed ConferencePaper to this Meeting.
*
* @param pape the passed paper
*/
public void addPaper(ConferencePaper pape){
papers.add(pape);
}
/**Removes the passed ConferencePaper from this Meeting, if
* it is present.
*
* @param pape the passed paper
*/
public void removePaper(ConferencePaper pape){
papers.remove(pape);
}
/**Overrides the inherited equals() method from Object. Uses
* the date and Location as the basis for comparison.
*
* @param meet the passed Meeting
* @return whether the passed Meeting equals this one
*/
public boolean equals(Meeting meet){
if(this.month.equals(meet.getMonth())){
if(this.year.equals(meet.getYear())){
if(this.location.equals(meet.getLocation())){
return true;
}
}
}
return false;
}
/**Returns the month.
*
* @return the month
*/
public String getMonth(){
return month;
}
/**Returns the year.
*
* @return the year
*/
public String getYear(){
return year;
}
/**Returns the Location.
*
* @return the Location
*/
public Location getLocation(){
return location;
}
/**Returns the Scholar ArrayList of program chairs.
*
* @return the ArrayList of program chairs
*/
public ArrayList<Scholar> getProgramChairs(){
return programChairs;
}
/**Checks if the passed Scholar exists within the program chairs.
*
* @param key the passed Scholar
* @return whether the Scholar was found
*/
public boolean containsProgramChair(Scholar key){
if(programChairs.contains(key)){
return true;
}
return false;
}
/**Returns the Scholar ArrayList of committee members.
*
* @return the ArrayList of committee members
*/
public ArrayList<Scholar> getCommitteeMembers(){
return committeeMembers;
}
/**Checks if the passed Scholar exists within the committee members.
*
* @param key the passed Scholar
* @return whether the Scholar was found
*/
public boolean containsCommitteeMember(Scholar key){
if(committeeMembers.contains(key)){
return true;
}
return false;
}
/**Removes the passed Scholar from the contained ArrayLists.
*
* @param key the passed Scholar
*/
public void removeScholar(Scholar key){
programChairs.remove(key);
committeeMembers.remove(key);
}
/**Checks to make sure scholars are present in both ArrayLists.
*
* @return whether the ArrayLists are empty
*/
public boolean isAListEmpty(){
if((programChairs.size() > 0) && (committeeMembers.size() > 0)){
return false;
}
return true;
}
/**Returns the amount of papers contained within this Meeting.
*
* @return the size of the ConferencePaper ArrayList
*/
public int getPaperListSize(){
return papers.size();
}
/**Returns the indicated Conference.
*
* @param index the index of the desired Conference
* @return the indicated Conference
*/
public ConferencePaper getPaper(int index){
return papers.get(index);
}
/**Returns the ArrayList of ConferencePapers.
*
* @return the ArrayList of papers
*/
public ArrayList<ConferencePaper> getPapers(){
return papers;
}
/**Returns this Meeting's program chairs as a string.
*
* @return the Meeting's program chairs
*/
public String getAllProgramChairs(){
String allProgramChairs = "";
for(int index = 0; index < programChairs.size(); ++index){
allProgramChairs += programChairs.get(index).returnNameInString() + "\n\t";
}
return allProgramChairs;
}
/**Returns this Meeting's committee members as a string.
*
* @return the Meeting's committee members
*/
public String getAllCommitteeMembers(){
String allCommitteeMembers = "";
for(int index = 0; index < committeeMembers.size(); ++index){
allCommitteeMembers += committeeMembers.get(index).returnNameInString() + "\n\t";
}
return allCommitteeMembers;
}
/**Returns this Meeting's papers as a string.
*
* @return the Meeting's papers
*/
public String getAllPapers(){
String allPapers = "";
if(papers != null){
for(int index = 0; index < papers.size(); ++index){
allPapers += papers.get(index).getTitleOfPaper() + "\n\t";
}
}else{
allPapers = "No papers have been added.";
}
return allPapers;
}
/**Overrides the inherited toString() method from Object. Returns
* the month, year, and Location that this Meeting takes place.
*
* @return the month, year, and Location
*/
public String toString(){
return (month+", "+year+" // "+location.toString());
}
}
| true |
fc86e4f3d43aa2a411b233112887c8fe5bd1a4fd | Java | SupaHotFiya-Security/curcon-backend | /src/main/java/nl/hu/curcon/service/MillerNiveauService.java | UTF-8 | 206 | 1.742188 | 2 | [] | no_license | package nl.hu.curcon.service;
import java.util.List;
import nl.hu.curcon.dto.MillerNiveauDto;
public interface MillerNiveauService {
MillerNiveauDto find(int id);
List<MillerNiveauDto> findAll();
}
| true |
a91300bf60bd925fc6f6611d753557fcfceddfb5 | Java | Synesso/instinct | /core/src/main/java/com/googlecode/instinct/expect/state/checker/EventObjectChecker.java | UTF-8 | 1,014 | 1.90625 | 2 | [
"Apache-2.0",
"BSD-3-Clause",
"MIT",
"W3C",
"SAX-PD"
] | permissive | /*
* Copyright 2006-2007 Tom Adams
*
* 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.googlecode.instinct.expect.state.checker;
import java.util.EventObject;
public interface EventObjectChecker<T extends EventObject> extends ObjectChecker<T> {
<U extends EventObject> void isAnEventFrom(Class<U> cls, Object object);
void isAnEventFrom(Object source);
<U extends EventObject> void isNotAnEventFrom(Class<U> aClass, Object object);
void isNotAnEventFrom(Object object);
}
| true |
a186f6631a96c6561e38648b350a58ddccab29ef | Java | 320761248/blog | /zxz_blog/src/main/java/com/zxz/service/UserService.java | UTF-8 | 190 | 1.617188 | 2 | [] | no_license | package com.zxz.service;
import com.zxz.util.Result;
/**
* Created by limi on 2017/10/15.
*/
public interface UserService {
public Result addUser(String email, String password);
}
| true |
70a374bbdf9d462ef2b3c9779bcd9b1f77dfcb2d | Java | DeKal/Kata-BowlingGame | /src/Game.java | UTF-8 | 1,580 | 3.234375 | 3 | [] | no_license | public class Game {
private int[] rolls = new int[21];
private int currentRoll = 0;
public void roll(int pins) {
rolls[currentRoll++] = pins;
}
public int score() {
int totalScore = 0;
int scoreIndex = 0;
for (int frame = 0; frame <= 10; ++ frame) {
if (isStrike(scoreIndex)) {
totalScore += 10 + strikeBonus(scoreIndex);
scoreIndex ++;
}
else if (isSpare(scoreIndex)){
totalScore += 10 + spareBonus(scoreIndex);
scoreIndex += 2;
}
else {
totalScore += totalScore(scoreIndex);
scoreIndex += 2;
}
}
totalScore += last21thRolls();
return totalScore;
}
private boolean isStrike(int scoreIndex) {
return scoreIndex < rolls.length && rolls[scoreIndex] == 10;
}
private int strikeBonus(int scoreIndex) {
return rolls[scoreIndex + 1] + rolls[scoreIndex + 2];
}
private int totalScore(int scoreIndex) {
if (scoreIndex < rolls.length - 1) {
return rolls[scoreIndex] + rolls[scoreIndex + 1];
}
else {
return rolls[scoreIndex];
}
}
private int spareBonus(int scoreIndex) {
return rolls[scoreIndex + 2];
}
private boolean isSpare(int scoreIndex) {
return scoreIndex + 1 < rolls.length && rolls[scoreIndex] + rolls[scoreIndex + 1] == 10;
}
private int last21thRolls() {
return rolls[20];
}
}
| true |
40587af7da452963663d898bb034b353c533f961 | Java | yaju1234/teacher | /app/src/main/java/com/mdgroup/teacher/schoolmodel/ModelNews.java | UTF-8 | 2,506 | 2.125 | 2 | [] | no_license | package com.mdgroup.teacher.schoolmodel;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.io.Serializable;
public class ModelNews implements Serializable {
@SerializedName("NEWS_ID")
@Expose
private String NEWS_ID;
@SerializedName("NEWS_HEADING")
@Expose
private String NEWS_HEADING;
@SerializedName("NEWS_DESCRIPTION")
@Expose
private String NEWS_DESCRIPTION;
@SerializedName("NEWS_UPLOAD_DATE")
@Expose
private String NEWS_UPLOAD_DATE;
@SerializedName("NEWS_MAIN_IMG")
@Expose
private String NEWS_MAIN_IMG;
@SerializedName("NEWS_SUB_IMG1")
@Expose
private String NEWS_SUB_IMG1;
@SerializedName("NEWS_SUB_IMG2")
@Expose
private String NEWS_SUB_IMG2;
@SerializedName("NEWS_SUB_IMG3")
@Expose
private String NEWS_SUB_IMG3;
public String getNEWS_ID() {
return NEWS_ID;
}
public void setNEWS_ID(String NEWS_ID) {
this.NEWS_ID = NEWS_ID;
}
public String getNEWS_HEADING() {
return NEWS_HEADING;
}
public void setNEWS_HEADING(String NEWS_HEADING) {
this.NEWS_HEADING = NEWS_HEADING;
}
public String getNEWS_DESCRIPTION() {
return NEWS_DESCRIPTION;
}
public void setNEWS_DESCRIPTION(String NEWS_DESCRIPTION) {
this.NEWS_DESCRIPTION = NEWS_DESCRIPTION;
}
public String getNEWS_UPLOAD_DATE() {
return NEWS_UPLOAD_DATE;
}
public void setNEWS_UPLOAD_DATE(String NEWS_UPLOAD_DATE) {
this.NEWS_UPLOAD_DATE = NEWS_UPLOAD_DATE;
}
public String getNEWS_MAIN_IMG() {
return NEWS_MAIN_IMG;
}
public void setNEWS_MAIN_IMG(String NEWS_MAIN_IMG) {
this.NEWS_MAIN_IMG = NEWS_MAIN_IMG;
}
public String getNEWS_SUB_IMG1() {
return NEWS_SUB_IMG1;
}
public void setNEWS_SUB_IMG1(String NEWS_SUB_IMG1) {
this.NEWS_SUB_IMG1 = NEWS_SUB_IMG1;
}
public String getNEWS_SUB_IMG2() {
return NEWS_SUB_IMG2;
}
public void setNEWS_SUB_IMG2(String NEWS_SUB_IMG2) {
this.NEWS_SUB_IMG2 = NEWS_SUB_IMG2;
}
public String getNEWS_SUB_IMG3() {
return NEWS_SUB_IMG3;
}
public void setNEWS_SUB_IMG3(String NEWS_SUB_IMG3) {
this.NEWS_SUB_IMG3 = NEWS_SUB_IMG3;
}
public ModelNews() {
}
}
| true |
7d54fcf1fb43f8e9a217c8ca866acc5feca2bc87 | Java | sumit784/crawler-3 | /src/test/java/com/qinyuan15/crawler/core/http/lib/TestProxyPool.java | UTF-8 | 1,818 | 2.515625 | 3 | [] | no_license | package com.qinyuan15.crawler.core.http.lib;
import com.qinyuan15.crawler.core.http.proxy.ProxyPool;
import com.qinyuan15.crawler.dao.Proxy;
import java.util.ArrayList;
import java.util.List;
/**
* A ProxyPool for testing
* Created by qinyuan on 15-1-2.
*/
public class TestProxyPool implements ProxyPool {
private List<Proxy> proxies = new ArrayList<Proxy>();
private int pointer;
public TestProxyPool() {
//proxies.add(createProxy("218.5.74.174", 80));
proxies.add(createProxy("219.246.65.143", 3128));
/*
proxies.add(createProxy("124.42.127.221", 8086));
proxies.add(createProxy("120.206.78.245", 8123));
proxies.add(createProxy("218.207.172.236", 80));
proxies.add(createProxy("113.105.224.87", 80));
proxies.add(createProxy("36.250.74.87", 80));
proxies.add(createProxy("117.177.243.7", 80));
proxies.add(createProxy("121.42.146.187", 80));
proxies.add(createProxy("183.207.229.137", 9001));
proxies.add(createProxy("111.161.126.101", 80));
proxies.add(createProxy("222.87.129.218", 82));
proxies.add(createProxy("183.211.117.222", 8123));
proxies.add(createProxy("113.105.224.87", 80));
proxies.add(createProxy("114.36.162.55", 9064));
proxies.add(createProxy("111.1.3.38", 8000));
*/
}
public int size() {
return proxies.size();
}
@Override
public Proxy next() {
if (proxies.size() == 0) {
return null;
}
if (pointer >= proxies.size()) {
pointer = 0;
}
return proxies.get(pointer++);
}
private Proxy createProxy(String host, int port) {
Proxy proxy = new Proxy();
proxy.setHost(host);
proxy.setPort(port);
return proxy;
}
}
| true |
4a0be994bb3bc87cf1373a45a9857228791266a7 | Java | AnuruddhaSrimalWeerawardhana/gymSystem1_ | /src/controllers/FinanceDelete_IncomeServlet.java | UTF-8 | 1,527 | 2.359375 | 2 | [] | no_license | package controllers;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import DBHelpers.Finance_IncomeDeleteQuery;
/**
* Servlet implementation class FinanceDelete_IncomeServlet
*/
public class FinanceDelete_IncomeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public FinanceDelete_IncomeServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int incomeID = Integer.parseInt(request.getParameter("id"));
Finance_IncomeDeleteQuery dq = new Finance_IncomeDeleteQuery("gym_management","root","apple12");
dq.doDelete (incomeID);
String url = "/FinanceRead_IncomeServlet";
RequestDispatcher dispatcher = request.getRequestDispatcher(url);
dispatcher.forward(request, response);
}
}
| true |
9e05b123f8682daa929a39ecdcb5866c6f9275a6 | Java | jprante/datastructures | /datastructures-api/src/main/java/org/xbib/datastructures/api/Generator.java | UTF-8 | 175 | 1.859375 | 2 | [
"Apache-2.0"
] | permissive | package org.xbib.datastructures.api;
import java.io.IOException;
import java.io.Writer;
public interface Generator {
void generate(Writer writer) throws IOException;
}
| true |
a1d95d71f2c2638e6477dec75a2846cff01101f3 | Java | SuperFatSeries/CourseServer | /src/main/java/com/dds/sfscourse/dto/CourseInfoDto.java | UTF-8 | 1,418 | 2.1875 | 2 | [
"Apache-2.0"
] | permissive | package com.dds.sfscourse.dto;
import com.fasterxml.jackson.annotation.JsonProperty;
public class CourseInfoDto {
@JsonProperty(value = "courseware_count")
Integer coursewareCount;
@JsonProperty(value = "dated_count")
Integer datedCount;
@JsonProperty(value = "homework_count")
Integer homeworkCount;
@JsonProperty(value = "submit_count")
Integer submitCount;
public CourseInfoDto(Integer coursewareCount, Integer datedCount, Integer homeworkCount, Integer submitCount) {
this.coursewareCount = coursewareCount;
this.datedCount = datedCount;
this.homeworkCount = homeworkCount;
this.submitCount = submitCount;
}
public Integer getCoursewareCount() {
return coursewareCount;
}
public void setCoursewareCount(Integer coursewareCount) {
this.coursewareCount = coursewareCount;
}
public Integer getDatedCount() {
return datedCount;
}
public void setDatedCount(Integer datedCount) {
this.datedCount = datedCount;
}
public Integer getHomeworkCount() {
return homeworkCount;
}
public void setHomeworkCount(Integer homeworkCount) {
this.homeworkCount = homeworkCount;
}
public Integer getSubmitCount() {
return submitCount;
}
public void setSubmitCount(Integer submitCount) {
this.submitCount = submitCount;
}
}
| true |
736b84cdd00d413209af54618ba602fc612fe957 | Java | wushenjiang/TDTreeHole | /app/src/main/java/com/androidlearing/tdtreehole/pojo/PostAndRepost.java | UTF-8 | 1,032 | 2.125 | 2 | [] | no_license | package com.androidlearing.tdtreehole.pojo;
import com.androidlearing.tdtreehole.bean.ItemBean;
import com.androidlearing.tdtreehole.bean.ItemBeanRepost;
import java.util.List;
/**
* @ProjectName: TDTreeHole
* @Package: com.androidlearing.tdtreehole.pojo
* @ClassName: PostAndRepost
* @Description: java类作用描述
* @Author: 武神酱丶
* @CreateDate: 2020/4/19 23:09
* @UpdateUser: 更新者
* @UpdateDate: 2020/4/19 23:09
* @UpdateRemark: 更新说明
* @Version: 1.0
*/
public class PostAndRepost {
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
private int type;
private ItemBean post;
private ItemBeanRepost reposts;
public ItemBean getPost() {
return post;
}
public void setPost(ItemBean post) {
this.post = post;
}
public ItemBeanRepost getReposts() {
return reposts;
}
public void setReposts(ItemBeanRepost reposts) {
this.reposts = reposts;
}
}
| true |
848d1d57b239844f972a6a264459a6442bb9999e | Java | apache/flink | /flink-runtime/src/main/java/org/apache/flink/runtime/operators/chaining/SynchronousChainedCombineDriver.java | UTF-8 | 10,026 | 1.664063 | 2 | [
"BSD-3-Clause",
"OFL-1.1",
"ISC",
"MIT",
"Apache-2.0"
] | permissive | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.flink.runtime.operators.chaining;
import org.apache.flink.api.common.functions.Function;
import org.apache.flink.api.common.functions.GroupCombineFunction;
import org.apache.flink.api.common.functions.util.FunctionUtils;
import org.apache.flink.api.common.typeutils.TypeComparator;
import org.apache.flink.api.common.typeutils.TypeComparatorFactory;
import org.apache.flink.api.common.typeutils.TypeSerializer;
import org.apache.flink.api.common.typeutils.TypeSerializerFactory;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.core.memory.MemorySegment;
import org.apache.flink.runtime.jobgraph.tasks.AbstractInvokable;
import org.apache.flink.runtime.memory.MemoryManager;
import org.apache.flink.runtime.operators.BatchTask;
import org.apache.flink.runtime.operators.sort.FixedLengthRecordSorter;
import org.apache.flink.runtime.operators.sort.InMemorySorter;
import org.apache.flink.runtime.operators.sort.NormalizedKeySorter;
import org.apache.flink.runtime.operators.sort.QuickSort;
import org.apache.flink.runtime.util.NonReusingKeyGroupedIterator;
import org.apache.flink.runtime.util.ReusingKeyGroupedIterator;
import org.apache.flink.util.Collector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.List;
/**
* The chained variant of the combine driver which is also implemented in GroupReduceCombineDriver.
* In contrast to the GroupReduceCombineDriver, this driver's purpose is only to combine the values
* received in the chain. It is used by the GroupReduce and the CombineGroup transformation.
*
* @see org.apache.flink.runtime.operators.GroupReduceCombineDriver
* @param <IN> The data type consumed by the combiner.
* @param <OUT> The data type produced by the combiner.
*/
public class SynchronousChainedCombineDriver<IN, OUT> extends ChainedDriver<IN, OUT> {
private static final Logger LOG =
LoggerFactory.getLogger(SynchronousChainedCombineDriver.class);
/**
* Fix length records with a length below this threshold will be in-place sorted, if possible.
*/
private static final int THRESHOLD_FOR_IN_PLACE_SORTING = 32;
// --------------------------------------------------------------------------------------------
private InMemorySorter<IN> sorter;
private GroupCombineFunction<IN, OUT> combiner;
private TypeSerializer<IN> serializer;
private TypeComparator<IN> groupingComparator;
private AbstractInvokable parent;
private final QuickSort sortAlgo = new QuickSort();
private List<MemorySegment> memory;
private volatile boolean running = true;
// --------------------------------------------------------------------------------------------
@Override
public void setup(AbstractInvokable parent) {
this.parent = parent;
@SuppressWarnings("unchecked")
final GroupCombineFunction<IN, OUT> combiner =
BatchTask.instantiateUserCode(
this.config, userCodeClassLoader, GroupCombineFunction.class);
this.combiner = combiner;
FunctionUtils.setFunctionRuntimeContext(combiner, getUdfRuntimeContext());
}
@Override
public void openTask() throws Exception {
// open the stub first
final Configuration stubConfig = this.config.getStubParameters();
BatchTask.openUserCode(this.combiner, stubConfig);
// ----------------- Set up the sorter -------------------------
// instantiate the serializer / comparator
final TypeSerializerFactory<IN> serializerFactory =
this.config.getInputSerializer(0, this.userCodeClassLoader);
final TypeComparatorFactory<IN> sortingComparatorFactory =
this.config.getDriverComparator(0, this.userCodeClassLoader);
final TypeComparatorFactory<IN> groupingComparatorFactory =
this.config.getDriverComparator(1, this.userCodeClassLoader);
this.serializer = serializerFactory.getSerializer();
TypeComparator<IN> sortingComparator = sortingComparatorFactory.createComparator();
this.groupingComparator = groupingComparatorFactory.createComparator();
MemoryManager memManager = this.parent.getEnvironment().getMemoryManager();
final int numMemoryPages =
memManager.computeNumberOfPages(this.config.getRelativeMemoryDriver());
this.memory = memManager.allocatePages(this.parent, numMemoryPages);
// instantiate a fix-length in-place sorter, if possible, otherwise the out-of-place sorter
if (sortingComparator.supportsSerializationWithKeyNormalization()
&& this.serializer.getLength() > 0
&& this.serializer.getLength() <= THRESHOLD_FOR_IN_PLACE_SORTING) {
this.sorter =
new FixedLengthRecordSorter<IN>(
this.serializer, sortingComparator.duplicate(), this.memory);
} else {
this.sorter =
new NormalizedKeySorter<IN>(
this.serializer, sortingComparator.duplicate(), this.memory);
}
if (LOG.isDebugEnabled()) {
LOG.debug(
"SynchronousChainedCombineDriver object reuse: "
+ (this.objectReuseEnabled ? "ENABLED" : "DISABLED")
+ ".");
}
}
@Override
public void closeTask() throws Exception {
if (this.running) {
BatchTask.closeUserCode(this.combiner);
}
}
@Override
public void cancelTask() {
this.running = false;
dispose(true);
}
// --------------------------------------------------------------------------------------------
public Function getStub() {
return this.combiner;
}
public String getTaskName() {
return this.taskName;
}
@Override
public void collect(IN record) {
this.numRecordsIn.inc();
// try writing to the sorter first
try {
if (this.sorter.write(record)) {
return;
}
} catch (IOException e) {
throw new ExceptionInChainedStubException(this.taskName, e);
}
// do the actual sorting
try {
sortAndCombine();
} catch (Exception e) {
throw new ExceptionInChainedStubException(this.taskName, e);
}
this.sorter.reset();
try {
if (!this.sorter.write(record)) {
throw new IOException(
"Cannot write record to fresh sort buffer. Record too large.");
}
} catch (IOException e) {
throw new ExceptionInChainedStubException(this.taskName, e);
}
}
// --------------------------------------------------------------------------------------------
@Override
public void close() {
try {
sortAndCombine();
} catch (Exception e) {
throw new ExceptionInChainedStubException(this.taskName, e);
}
this.outputCollector.close();
dispose(false);
}
private void dispose(boolean ignoreException) {
try {
sorter.dispose();
} catch (Exception e) {
// May happen during concurrent modification when canceling. Ignore.
if (!ignoreException) {
throw e;
}
} finally {
parent.getEnvironment().getMemoryManager().release(this.memory);
}
}
private void sortAndCombine() throws Exception {
final InMemorySorter<IN> sorter = this.sorter;
if (objectReuseEnabled) {
if (!sorter.isEmpty()) {
this.sortAlgo.sort(sorter);
// run the combiner
final ReusingKeyGroupedIterator<IN> keyIter =
new ReusingKeyGroupedIterator<IN>(
sorter.getIterator(), this.serializer, this.groupingComparator);
// cache references on the stack
final GroupCombineFunction<IN, OUT> stub = this.combiner;
final Collector<OUT> output = this.outputCollector;
// run stub implementation
while (this.running && keyIter.nextKey()) {
stub.combine(keyIter.getValues(), output);
}
}
} else {
if (!sorter.isEmpty()) {
this.sortAlgo.sort(sorter);
// run the combiner
final NonReusingKeyGroupedIterator<IN> keyIter =
new NonReusingKeyGroupedIterator<IN>(
sorter.getIterator(), this.groupingComparator);
// cache references on the stack
final GroupCombineFunction<IN, OUT> stub = this.combiner;
final Collector<OUT> output = this.outputCollector;
// run stub implementation
while (this.running && keyIter.nextKey()) {
stub.combine(keyIter.getValues(), output);
}
}
}
}
}
| true |
e7dacb0ba6d2b1b1041f2d878f06dd2e7cdb80c0 | Java | simao-ferreira/PD_ThreeRow | /src/MainWithGui.java | UTF-8 | 256 | 1.648438 | 2 | [] | no_license |
import logic.ObservableGame;
import ui.gui.ThreeInRowView;
public class MainWithGui
{
public static void main(String[] args)
{
//ThreeInRowView GUI = new ThreeInRowView(new ObservableGame());
}
}
| true |
b88fff282225529da2c5d70f6a1d3ff108754eb0 | Java | hataoka/Lunch_Spring | /src/main/app/model/Purchase.java | UTF-8 | 398 | 2.390625 | 2 | [] | no_license | package app.model;
import java.io.Serializable;
import java.sql.Date;
import lombok.Data;
@Data
public class Purchase implements Serializable {
private String id;
private Date purchase_date;
private int suu;
public Purchase() {
}
public Purchase(String id, Date purchase_date, int suu) {
this.id = id;
this.purchase_date = purchase_date;
this.suu = suu;
}
} | true |
f70533dcaf7d8d402dab389f9544d837dda1c802 | Java | yogurts/Aircraft | /src/com/Exception/SumTest.java | UTF-8 | 716 | 3.09375 | 3 | [] | no_license | package com.Exception;
import static org.junit.Assert.*;
import org.junit.Test;
/**
* @author Ita
*
* 保证程序在修改后其结果仍然是正确的 测试驱动的开发过程 JUnit
* @Test来标注测试函数
* 在测试中常用的语句:
* fail(信息);//表示程序出错
* assertEqauls(参数1,参数2) //表示程序要保证两个参数要相等
* assertNull(参数); //表示参数要为null
*
*/
public class SumTest {
@Test
public void testSum() {
Sum s = new Sum();
assertEquals(s.sum(1,10), 11);
//fail("Not yet implemented");
}
@Test
public void testSum1() {
Sum s = new Sum();
assertEquals(s.sum(1,10), s.sum(10,1));
//fail("Not yet implemented");
}
}
| true |
63ea35b09713f32ef3122af5b25440e6f12b4b8c | Java | ftc8626/2015-2016 | /ftc_app-master/FtcRobotController/src/main/java/org/umeprep/ftc/FTC8626/Speedy/Motion.java | UTF-8 | 9,992 | 2.3125 | 2 | [
"MIT"
] | permissive | package org.umeprep.ftc.FTC8626.Speedy;
import com.qualcomm.robotcore.hardware.DcMotor;
import com.qualcomm.robotcore.hardware.DcMotorController;
import com.qualcomm.robotcore.util.ElapsedTime;
import com.qualcomm.robotcore.util.Range;
// for telemetry.addData...
//import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import com.qualcomm.robotcore.eventloop.opmode.OpMode;
import org.umeprep.ftc.FTC8626.Speedy.autonomous.DriveMoveDirection;
import org.umeprep.ftc.FTC8626.Speedy.autonomous.DriveTurnDirection;
/**
* Created by Andre on 3/3/2016.
*/
public final class Motion {
private final int ANDYMARK_MOTORS_TICKS_PER_REVOLUTION = 1120;
private final int DISTANCE_ERROR_TOLERANCE_IN_TICKS = 50;
private final int WHEEL_DIAMETER = 4;
private final double WHEEL_CIRCUMFERENCE = WHEEL_DIAMETER * Math.PI;
private final double HEADING_TOLERANCE_DEGREES = 1.1;
// Adjust the MOVE_POWER_FACTOR based on the smoothness of floor surface
private final double DRIVE_SLOW_POWER = .15;
private final double DEFAULT_DRIVE_MOTOR_POWER = .6;
private final double MOVE_POWER_FACTOR = .75; // Multiplier to reduce the actual power
private final double SLOW_MOVE_POWER_FACTOR = .5;
private final double MOVE_POWER_HEADING_ADJUSTMENT = .008;
private final double TURN_POWER = .7; //.15
private final double SLOW_TURN_POWER = .1;
private final double SUPER_SLOW_TURN_POWER = .8;
private final double TURN_POWER_FACTOR = 1.5;
private Navigation navigation;
//private double lastDesiredHeading;
private DcMotor motorRight;
private DcMotor motorLeft;
public Motion(Navigation navigationParameter, DcMotor motorRightParameter,DcMotor motorLeftParameter){
motorRight = motorRightParameter;
motorLeft = motorLeftParameter;
navigation = navigationParameter;
}
public Motion(DcMotor motorRightParameter,DcMotor motorLeftParameter){
motorRight = motorRightParameter;
motorLeft = motorLeftParameter;
}
public void simpleMoveBackwards() {
//double movePower = Range.clip(DEFAULT_DRIVE_MOTOR_POWER * SLOW_MOVE_POWER_FACTOR, -1, 1);
setMotorPower(.17);
}
public void move(DriveMoveDirection robotMoveDirection, double distanceInInches, double lastDesiredHeading) throws InterruptedException {
double movePower = DEFAULT_DRIVE_MOTOR_POWER;
double initialHeading = lastDesiredHeading;
double currentHeading = initialHeading;
motorRight.setMode(DcMotorController.RunMode.RUN_USING_ENCODERS);
motorLeft.setMode(DcMotorController.RunMode.RUN_USING_ENCODERS);
motorRight.setMode(DcMotorController.RunMode.RESET_ENCODERS);
motorLeft.setMode(DcMotorController.RunMode.RESET_ENCODERS);
double distanceInRevolutions = distanceInInches / WHEEL_CIRCUMFERENCE;
int distanceInTicks = (int)Math.round(distanceInRevolutions * ANDYMARK_MOTORS_TICKS_PER_REVOLUTION);
int currentRightPosition = motorRight.getCurrentPosition();
int currentLeftPosition = motorLeft.getCurrentPosition();
int targetRightPosition;
int targetLeftPosition;
if (robotMoveDirection == DriveMoveDirection.Forward) {
targetRightPosition = currentRightPosition + distanceInTicks;
targetLeftPosition = currentLeftPosition + distanceInTicks;
}
else {
targetRightPosition = currentRightPosition - distanceInTicks;
targetLeftPosition = currentLeftPosition - distanceInTicks;
}
motorRight.setTargetPosition(targetRightPosition);
motorLeft.setTargetPosition(targetLeftPosition);
motorRight.setMode(DcMotorController.RunMode.RUN_TO_POSITION);
motorLeft.setMode(DcMotorController.RunMode.RUN_TO_POSITION);
// Start slow
double initialMovePower = movePower;
if (distanceInInches > 17) {
// Adjust the power based on the factor (change based on smoothness of floor surface)
initialMovePower = Range.clip(movePower * MOVE_POWER_FACTOR, -1, 1);
//telemetry.addData("lastDesired","heading: " + lastDesiredHeading);
for (int counter = 1; counter < 25; counter++) {
setMotorPower(initialMovePower/25 * counter);
Thread.sleep(50);
}
}
else
{
// Adjust the power based on the factor (change based on smoothness of floor surface)
initialMovePower = Range.clip(movePower * SLOW_MOVE_POWER_FACTOR, -1, 1);
}
double rightPositionDifference = motorRight.getCurrentPosition() - targetRightPosition;
double leftPositionDifference = motorLeft.getCurrentPosition() - targetLeftPosition;
ElapsedTime moveElapsedTime = new ElapsedTime();
moveElapsedTime.reset();
while (Math.abs(rightPositionDifference) > DISTANCE_ERROR_TOLERANCE_IN_TICKS ||
Math.abs(leftPositionDifference) > DISTANCE_ERROR_TOLERANCE_IN_TICKS) {
//|| (timeout > 0 && moveElapsedTime.time() > timeout)) {
double headingDifference = navigation.getHeadingDifference(lastDesiredHeading);
double rightPower = Range.clip(initialMovePower * MOVE_POWER_FACTOR, -1, 1);
double leftPower = rightPower;
if (headingDifference > 0) {
leftPower -= MOVE_POWER_HEADING_ADJUSTMENT;
rightPower += MOVE_POWER_HEADING_ADJUSTMENT;
} else if (headingDifference < 0) {
leftPower += MOVE_POWER_HEADING_ADJUSTMENT;
rightPower -= MOVE_POWER_HEADING_ADJUSTMENT;
}
if (rightPositionDifference > DISTANCE_ERROR_TOLERANCE_IN_TICKS)
rightPower = -rightPower;
if (leftPositionDifference > DISTANCE_ERROR_TOLERANCE_IN_TICKS)
leftPower = -leftPower;
setMotorPower(rightPower, leftPower);
Thread.sleep(20);
rightPositionDifference = motorRight.getCurrentPosition() - targetRightPosition;
leftPositionDifference = motorLeft.getCurrentPosition() - targetLeftPosition;
}
stopDriveMotors();
Thread.sleep(300);
}
public double turn(DriveTurnDirection direction, double turnAngle, double lastDesiredHeading) throws InterruptedException {
motorRight.setMode(DcMotorController.RunMode.RUN_WITHOUT_ENCODERS);
motorLeft.setMode(DcMotorController.RunMode.RUN_WITHOUT_ENCODERS);
turnAngle = Range.clip(turnAngle, 0, 180);
turnAngle = (direction == DriveTurnDirection.Left) ? -turnAngle : turnAngle;
// Adjust the turnPowerFactor based on the smoothness of floor surface
double turnPower = Range.clip(TURN_POWER * TURN_POWER_FACTOR, -1, 1);
// Determine how far off the robot is currently
//telemetry.addData("lastDesired","heading: " + lastDesiredHeading);
double headingDrift = navigation.getAngleCorrectionAfterDrift(direction, lastDesiredHeading);
//telemetry.addData("drift", "in heading: " + headingDrift);
// Correct turn amount for existing drift
if (Math.abs(headingDrift) > HEADING_TOLERANCE_DEGREES) {
if (direction == DriveTurnDirection.Right)
turnAngle = Utility.normalizeDegrees(turnAngle + headingDrift); // Drift will be a negative number in some cases
else
turnAngle = Utility.normalizeDegrees(turnAngle - headingDrift); // Drift will be a negative number in some cases
}
double desiredHeading = Utility.normalizeDegrees(lastDesiredHeading + turnAngle); //currentHeading + turnAngle);
//telemetry.addData("desired","heading: " + desiredHeading);
// Reset the last desired heading with the new direction
lastDesiredHeading = desiredHeading;
double headingDifference = navigation.getHeadingDifference(desiredHeading);
while (Math.abs(headingDifference) > HEADING_TOLERANCE_DEGREES) {
if (Math.abs(headingDifference) < 80) {
turnPower = SLOW_TURN_POWER * TURN_POWER_FACTOR;
} else if (Math.abs(headingDifference) < 40) {
turnPower = SUPER_SLOW_TURN_POWER * TURN_POWER_FACTOR;
}
if (headingDifference > 0) { //direction == DriveTurnDirection.Left) {
// Turn left
motorRight.setPower(turnPower);
motorLeft.setPower(0);
} else {
// Turn right
motorRight.setPower(0);
motorLeft.setPower(turnPower);
}
/*
double desiredMinusCurrent = desiredHeading - getHeading();
if (desiredMinusCurrent > 180 || (desiredMinusCurrent < 0 && desiredMinusCurrent > -180)) {
// Turning left
motorRight.setPower(turnPower);
motorLeft.setPower(0);
} else if ((desiredMinusCurrent > 0 && desiredMinusCurrent <= 180) || desiredMinusCurrent <= -180) {
// Turning right
motorRight.setPower(0);
motorLeft.setPower(turnPower);
} else {
stopDriveMotors();
}
*/
headingDifference = navigation.getHeadingDifference(desiredHeading);
Thread.sleep(20); // simulate the slower looping of a TeleOp mode - 50 times per second
}
stopDriveMotors();
Thread.sleep(300); // Rest the motors after turning
return lastDesiredHeading;
}
public void setMotorPower(double power) {
setMotorPower(power, power);
}
public void setMotorPower(double rightPower, double leftPower) {
motorRight.setPower(rightPower);
motorLeft.setPower(leftPower);
}
public void stopDriveMotors() {
setMotorPower(0);
}
}
| true |
77b18b723f0bfcb657b96f2be77279692d303ca6 | Java | sohnoun/floto | /builder/src/main/java/io/github/floto/builder/FlotoBuilderParameters.java | UTF-8 | 386 | 1.96875 | 2 | [
"Apache-2.0"
] | permissive | package io.github.floto.builder;
import com.beust.jcommander.Parameter;
import io.github.floto.core.FlotoCommonParameters;
public class FlotoBuilderParameters extends FlotoCommonParameters {
@Parameter(names = "--compile-check", description = "Only run the compilation step, return exit code 0 iff compile is successful and without warnings")
public boolean compileCheck = false;
}
| true |
c3c5da07c7827c32cab40dd510d70ce10090c15d | Java | facebook/buck | /src/com/facebook/buck/android/exopackage/ExopackageInfo.java | UTF-8 | 3,680 | 1.953125 | 2 | [
"Apache-2.0"
] | permissive | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.buck.android.exopackage;
import com.facebook.buck.core.sourcepath.SourcePath;
import com.facebook.buck.core.util.immutables.BuckStyleValue;
import com.facebook.buck.core.util.immutables.BuckStyleValueWithBuilder;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import java.util.Optional;
import java.util.stream.Stream;
import org.immutables.value.Value;
@BuckStyleValueWithBuilder
public abstract class ExopackageInfo {
@BuckStyleValue
public interface DexInfo {
SourcePath getMetadata();
SourcePath getDirectory();
static DexInfo of(SourcePath metadata, SourcePath directory) {
return ImmutableDexInfo.of(metadata, directory);
}
}
@BuckStyleValue
public interface NativeLibsInfo {
SourcePath getMetadata();
SourcePath getDirectory();
static NativeLibsInfo of(SourcePath metadata, SourcePath directory) {
return ImmutableNativeLibsInfo.of(metadata, directory);
}
}
@BuckStyleValue
public interface ResourcesInfo {
ImmutableList<ExopackagePathAndHash> getResourcesPaths();
static ResourcesInfo of(ImmutableList<ExopackagePathAndHash> resourcesPaths) {
return ImmutableResourcesInfo.of(resourcesPaths);
}
}
public abstract Optional<ExopackageInfo.DexInfo> getDexInfo();
public abstract Optional<ImmutableList<ExopackageInfo.DexInfo>> getModuleInfo();
public abstract Optional<ExopackageInfo.NativeLibsInfo> getNativeLibsInfo();
public abstract Optional<ExopackageInfo.ResourcesInfo> getResourcesInfo();
public Stream<SourcePath> getRequiredPaths() {
Stream.Builder<SourcePath> paths = Stream.builder();
getNativeLibsInfo()
.ifPresent(
info -> {
paths.add(info.getMetadata());
paths.add(info.getDirectory());
});
getDexInfo()
.ifPresent(
info -> {
paths.add(info.getMetadata());
paths.add(info.getDirectory());
});
getModuleInfo()
.ifPresent(
modules ->
modules.forEach(
info -> {
paths.add(info.getMetadata());
paths.add(info.getDirectory());
}));
getResourcesInfo()
.ifPresent(
info ->
info.getResourcesPaths()
.forEach(
pair -> {
paths.add(pair.getPath());
paths.add(pair.getHashPath());
}));
return paths.build();
}
@Value.Check
protected void check() {
Preconditions.checkArgument(
getDexInfo().isPresent()
|| getNativeLibsInfo().isPresent()
|| getResourcesInfo().isPresent()
|| getModuleInfo().isPresent(),
"ExopackageInfo must have something to install.");
}
public static Builder builder() {
return new Builder();
}
public static class Builder extends ImmutableExopackageInfo.Builder {}
}
| true |
90bfa6c3b67f62be5db7920606bfb7399002d522 | Java | dineshndr/Handson | /SpringHandson/src/main/java/example8/CourseList.java | UTF-8 | 1,337 | 2.890625 | 3 | [] | no_license | package example8;
import java.util.List;
import javax.swing.text.DefaultStyledDocument;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
@Component
public class CourseList {
private List<Course> courseList = new ArrayList();
public CourseList() {
}
public CourseList(List<Course> courseList) {
super();
this.courseList = courseList;
}
public List<Course> getCourseList() {
return courseList;
}
public void setCourseList(List<Course> courseList) {
this.courseList = courseList;
}
public void insert(Course course) {
this.courseList.add(course);
}
public String discount()
{
int n = courseList.size();
int i=0;
double a[] = new double[n];
for(Course c:this.courseList)
{
a[i] = c.getFee();
i++;
}
double max=a[0],min=a[0];
for(int k=1;k<a.length;k++)
{
if(a[k]>max)
{
max = a[k];
}
else if(a[k]<min)
{
min = a[k];
}
}
String high=null,low=null;
for(Course d:this.courseList)
{
if(d.getFee()==max)
{
high=d.getName();
}
else if(d.getFee()==min)
{
low = d.getName();
}
}
String ms="Discount for "+ high +" course is "+ (max/10)+" Discount for "+low+" course is "+(min*0.05);
return ms;
}
} | true |
b1526140902908a290dd3743cc968c47cf9a219a | Java | cckmit/fcs | /FBPM/RM_20170401/fcs-rm-integration/src/main/java/com/born/fcs/rm/integration/common/impl/ClientAutowiredBaseService.java | UTF-8 | 1,077 | 1.507813 | 2 | [] | no_license | package com.born.fcs.rm.integration.common.impl;
import com.born.fcs.pm.ws.service.report.ToReportService;
import org.springframework.beans.factory.annotation.Autowired;
import com.born.fcs.pm.biz.service.common.OperationJournalService;
import com.born.fcs.pm.biz.service.common.SiteMessageService;
import com.born.fcs.pm.biz.service.common.SysParameterService;
import com.born.fcs.pm.ws.service.common.FormMessageTempleteService;
import com.born.fcs.pm.ws.service.common.ProjectService;
import com.born.fcs.pm.ws.service.sms.SMSService;
public class ClientAutowiredBaseService extends ClientBaseSevice {
@Autowired
protected SiteMessageService siteMessageWebService;
@Autowired
protected SysParameterService sysParameterWebService;
@Autowired
protected SMSService sMSWebService;
@Autowired
protected FormMessageTempleteService formMessageTempleteWebService;
@Autowired
protected ProjectService projectWebService;
@Autowired
protected OperationJournalService operationJournalWebService;
@Autowired
protected ToReportService toReportWebService;
}
| true |
2be048bdce7a88bb7f13f836161958240999055e | Java | hellen365/hotel-urbano | /maven-projeto/src/main/java/br/com/silva/modelo/Reserva.java | UTF-8 | 1,540 | 2.25 | 2 | [] | no_license | package br.com.silva.modelo;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="reserva")
public class Reserva {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@Column(length=30)
private String hotel;
@Column(length=10)
private String entrada;
@Column(length=10)
private String saida;
@Column(length=10)
private int adulto;
@Column(length=10)
private int crianca;
@Column(length=10)
private int tipoQuarto;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getHotel() {
return hotel;
}
public void setHotel(String hotel) {
this.hotel = hotel;
}
public String getEntrada() {
return entrada;
}
public void setEntrada(String entrada) {
this.entrada = entrada;
}
public String getSaida() {
return saida;
}
public void setSaida(String saida) {
this.saida = saida;
}
public int getAdulto() {
return adulto;
}
public void setAdulto(int adulto) {
this.adulto = adulto;
}
public int getCrianca() {
return crianca;
}
public void setCrianca(int crianca) {
this.crianca = crianca;
}
public int getTipoQuarto() {
return tipoQuarto;
}
public void setTipoQuarto(int tipoQuarto) {
this.tipoQuarto = tipoQuarto;
}
}
| true |
16df9321637586c7d5445233fc079e14ffeb258d | Java | DaedalusGame/MistyWorld_Open | /src/main/java/ru/liahim/mist/capability/SkillCapability.java | UTF-8 | 1,872 | 2.265625 | 2 | [
"Apache-2.0"
] | permissive | package ru.liahim.mist.capability;
import ru.liahim.mist.capability.handler.ISkillCapaHandler;
import net.minecraft.nbt.NBTBase;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.EnumFacing;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.capabilities.ICapabilitySerializable;
import net.minecraftforge.common.capabilities.Capability.IStorage;
import net.minecraftforge.common.capabilities.CapabilityInject;
public class SkillCapability {
@CapabilityInject(ISkillCapaHandler.class)
public static final Capability<ISkillCapaHandler> CAPABILITY_SKILL = null;
public static class Storage<T extends ISkillCapaHandler> implements IStorage<ISkillCapaHandler> {
@Override
public NBTBase writeNBT(Capability<ISkillCapaHandler> capability, ISkillCapaHandler instance, EnumFacing side) {
return instance.serializeNBT();
}
@Override
public void readNBT(Capability<ISkillCapaHandler> capability, ISkillCapaHandler instance, EnumFacing side, NBTBase nbt) {
instance.deserializeNBT((NBTTagCompound)nbt);
}
}
public static class Provider implements ICapabilitySerializable<NBTTagCompound> {
ISkillCapaHandler instance = CAPABILITY_SKILL.getDefaultInstance();
@Override
public boolean hasCapability(Capability<?> capability, EnumFacing facing) {
return capability == CAPABILITY_SKILL;
}
@Override
public <T> T getCapability(Capability<T> capability, EnumFacing facing) {
return hasCapability(capability, facing) ? CAPABILITY_SKILL.<T>cast(instance) : null;
}
@Override
public NBTTagCompound serializeNBT() {
return (NBTTagCompound) CAPABILITY_SKILL.getStorage().writeNBT(CAPABILITY_SKILL, instance, null);
}
@Override
public void deserializeNBT(NBTTagCompound nbt) {
CAPABILITY_SKILL.getStorage().readNBT(CAPABILITY_SKILL, instance, null, nbt);
}
}
} | true |
31b94eff7e63c72b332b2fb5f22eb558f9714821 | Java | birfincankafein/customcamera | /app/src/main/java/com/birfincankafein/customcamerademo/CapturedMedia.java | UTF-8 | 2,773 | 2.34375 | 2 | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | package com.birfincankafein.customcamerademo;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaMetadataRetriever;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Parcel;
import android.os.ParcelFileDescriptor;
import android.os.Parcelable;
import android.provider.MediaStore;
import android.provider.OpenableColumns;
import java.io.FileDescriptor;
import java.io.InputStream;
/**
* Created by metehantoksoy on 10.04.2018.
*/
public abstract class CapturedMedia implements Parcelable {
private final Uri fileUri;
private final FileType fileType;
private Bitmap thumbnail;
private String fileName;
private String fileSize;
public CapturedMedia(Uri fileUri, FileType fileType, Context context) {
this.fileUri = fileUri;
this.fileType = fileType;
thumbnail = createThumbnail(context);
initProperties(context);
}
protected CapturedMedia(Parcel in) {
this.fileUri = in.readParcelable(Uri.class.getClassLoader());
int tmpFileType = in.readInt();
this.fileType = tmpFileType == -1 ? null : FileType.values()[tmpFileType];
this.thumbnail = in.readParcelable(Bitmap.class.getClassLoader());
this.fileName = in.readString();
this.fileSize = in.readString();
}
private void initProperties(Context mContext){
Cursor returnCursor = mContext.getContentResolver().query(fileUri, null, null, null, null);
int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
int sizeIndex = returnCursor.getColumnIndex(OpenableColumns.SIZE);
returnCursor.moveToFirst();
fileName = returnCursor.getString(nameIndex);
Long tmpFileSize = returnCursor.getLong(sizeIndex);
fileSize = tmpFileSize + " B - " + (tmpFileSize/1048576) + "MB";
returnCursor.close();
}
protected abstract Bitmap createThumbnail(Context mContext);
protected abstract void initSpecificProperties(Context mContext);
public Bitmap getThumbnail(){
return thumbnail;
}
public Uri getFileUri() {
return fileUri;
}
public FileType getFileType() {
return fileType;
}
public String getFileName() {
return fileName;
}
public String getFileSize() {
return fileSize;
}
protected void setThumbnail(Bitmap thumbnail){
this.thumbnail = thumbnail;
}
public enum FileType{
PICTURE(0), VIDEO(1);
private final int type;
FileType(int type) {
this.type = type;
}
public int getType() {
return type;
}
}
}
| true |
00dc2a07143a7f365aaacf244908ac0ebffa683c | Java | tim4724/RoverRemoteControl | /app/src/main/java/com/tim/domi/remotecontrol/RemoteControl.java | UTF-8 | 4,141 | 2.671875 | 3 | [] | no_license | package com.tim.domi.remotecontrol;
import android.util.Log;
import com.tim.domi.remotecontrol.listener.RemoteListener;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import static com.tim.domi.remotecontrol.Util.putInt;
import static com.tim.domi.remotecontrol.Util.readInt;
import static com.tim.domi.remotecontrol.Util.sleepUninterruptibly;
public class RemoteControl {
private static final String TAG = "RemoteControl";
private final RemoteListener listener;
private DatagramSocket socket;
private Sender sender;
private Receiver receiver;
public RemoteControl(RemoteListener listener) throws SocketException {
this.listener = listener;
socket = new DatagramSocket();
socket.setSoTimeout(1000);
}
public void start() {
cancel();
receiver = new Receiver();
sender = new Sender();
receiver.start();
sender.start();
}
public void newData(int speed, int steering) {
sender.newData(speed, steering);
}
private class Sender extends Thread {
private boolean cancelled;
private byte[] data = new byte[10];
private int seqenceNr = 0;
@Override
public void run() {
try {
DatagramPacket packet = new DatagramPacket(data, data.length,
new InetSocketAddress("192.168.13.38", 5005));
Log.d(TAG, "try to connect to " + packet.getSocketAddress());
while (!cancelled) {
putInt(seqenceNr++, data, 0);
putInt((int) System.currentTimeMillis(), data, 4);
socket.send(packet);
if (!cancelled) sleepUninterruptibly(100);//max send 10 packets a second
if (!interrupted() && !cancelled) Util.sleep(250);
}
} catch (Exception e) {
errorOccurred(e);
}
}
void newData(int speed, int steering) {
data[8] = (byte) speed;
data[9] = (byte) steering;
this.interrupt();
}
}
private class Receiver extends Thread {
private boolean cancelled, connected;
@Override
public void run() {
byte[] data = new byte[10];
DatagramPacket packet = new DatagramPacket(data, data.length);
long connectedAt = System.currentTimeMillis();
try {
while (!cancelled) {
try {
socket.receive(packet);
connectedAt = System.currentTimeMillis();
updateConnState(true);
listener.pingUpdate(((int) connectedAt) - readInt(data, 4));
} catch (SocketTimeoutException e) {
updateConnState(false);
if (System.currentTimeMillis() - connectedAt > 4000) {
//no packet received for 4 seconds -> rethrow sockettimeout exception
throw e;
}
}
}
} catch (Exception e) {
errorOccurred(e);
}
}
private void updateConnState(boolean connected) {
if (this.connected != connected) {
this.connected = connected;
if (connected) {
Log.d(TAG, "connected to rover");
listener.onConnected();
} else {
Log.d(TAG, "not connected to rover");
listener.onNotConnected();
}
}
}
}
private void errorOccurred(Exception e) {
Log.e(TAG, "error occurred", e);
listener.failed(e);
cancel();
}
public void cancel() {
Log.d(TAG, "cancel");
if (sender != null) sender.cancelled = true;
if (receiver != null) receiver.cancelled = true;
}
}
| true |
d6f8e719849600241de7088549591bccc27dbd8b | Java | ChenJingLei/wing | /caur2cd-test/src/main/java/com/chinatel/caur2cdtest/storage/StorageProperties.java | UTF-8 | 454 | 1.914063 | 2 | [] | no_license | package com.chinatel.caur2cdtest.storage;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
@PropertySource("classpath:storage.properties")
@Data
@ConfigurationProperties(ignoreUnknownFields = false, prefix = "storage")
public class StorageProperties {
/**
* Folder location for storing files
*/
private String location;
}
| true |
962e37eaf529d93b20ce4a6660197eb08ecd4bec | Java | jieshengmu/cms | /CMS/src/main/java/cn/itsource/exception/AuthenticationException.java | UTF-8 | 488 | 2.25 | 2 | [] | no_license | package cn.itsource.exception;
/**
* @Title: AuthenticationException.java
* @author:牟胜杰
* @Package:cn.itsource.exception
* @Description:(作用:自定义异常)
* @date:2020年7月15日 下午6:53:30
* @version:V1.0
*/
public class AuthenticationException extends Exception {
private static final long serialVersionUID = 6787649159132179408L;
public AuthenticationException() {
super();
}
public AuthenticationException(String message) {
super(message);
}
}
| true |
f4ec5e9c9d0dd1a3d21fc333008e9c1f4672dc4d | Java | thiagocast/projetoturma8c | /projetofinal/src/main/java/br/com/projetofinal/controller/DevCadastros.java | UTF-8 | 1,524 | 2.234375 | 2 | [] | no_license | package br.com.projetofinal.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import br.com.projetofinal.beans.Atividade;
import br.com.projetofinal.beans.Ocorrencia;
import br.com.projetofinal.beans.Usuario;
import br.com.projetofinal.dao.AtividadeDAO;
import br.com.projetofinal.dao.OcorrenciaDAO;
import br.com.projetofinal.dao.UsuarioDAO;
public class DevCadastros {
@Autowired
private OcorrenciaDAO daoOcorrencia;
@Autowired
private UsuarioDAO daoUsuario;
@Autowired
private AtividadeDAO daoAtividade;
@PostMapping("/gravarocorrencia")
public ResponseEntity<Ocorrencia> gravarOcorrencia(@RequestBody Ocorrencia dados){
try {
daoOcorrencia.save(dados);
return ResponseEntity.ok(dados);
} catch (Exception e) {
return ResponseEntity.status(500).build();
}
}
@PostMapping("/gravarousuario")
public ResponseEntity<Usuario> gravarUsuario(@RequestBody Usuario dados){
try {
daoUsuario.save(dados);
return ResponseEntity.ok(dados);
} catch (Exception e) {
return ResponseEntity.status(500).build();
}
}
@PostMapping("/gravarAtividade")
public ResponseEntity<Atividade> gravarAtividade(@RequestBody Atividade dados){
try {
daoAtividade.save(dados);
return ResponseEntity.ok(dados);
} catch (Exception e) {
return ResponseEntity.status(500).build();
}
}
}
| true |
094ac24e300b8d87f55460b02f2c978c92239d42 | Java | youduim/youdu-sdk-java | /src/main/java/im/youdu/sdk/server/IReceiveYdMsg.java | UTF-8 | 154 | 1.734375 | 2 | [] | no_license | package im.youdu.sdk.server;
import im.youdu.sdk.entity.ReceiveMessage;
public interface IReceiveYdMsg {
public void receive(ReceiveMessage msg);
}
| true |
c465871ff3541c7fcc5447c2dff8076d5d623087 | Java | zbartholomew/VariousProjects | /InventoryManagement/test/com/zbartholomew/ProductInventoryManagerTest.java | UTF-8 | 4,322 | 3.1875 | 3 | [] | no_license | package com.zbartholomew;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* <h1> {@link ProductInventoryManager} testing class. </h1>
* <p> Verifies the picking and restocking of a Products inventory
* and checks the {@link RestockingResult} / {@link PickingResult}
* return values are correct</p>
*
* @author Zach Bartholomew
*/
public class ProductInventoryManagerTest {
@BeforeClass
public static void createDummyData() {
Location location1 = new Location("First1 location1");
new Product("123", 12, location1);
Location location2 = new Location("Second2 location2");
new Product("456", 60, location2);
Location location3 = new Location("Third3 location3");
new Product("789", 100, location3);
Location location4 = new Location("Fourth4 location4");
new Product("147", 0, location4);
new Product("452", 5, location4);
}
@Test
public void testSuccessfulPickProduct() {
ProductInventoryManager manager = new ProductInventoryManager();
PickingResult pickingResult = manager.pickProduct("123", 4);
Product product = ProductInventoryManager.getProductMap().get("123");
String message = "Success Picking!" +
"\nProduct ID: " + product.getId() +
"\nLocation: " + product.getLocation().getName() +
"\nAmount Picked: " + 4 +
"\nNew Inventory: " + product.getInventory();
assertEquals(message, pickingResult.getDetailMessage());
}
@Test
public void testUnsuccessfulPickProductShouldGetErrorMessage() {
ProductInventoryManager manager = new ProductInventoryManager();
PickingResult pickingResult = manager.pickProduct("123", 13);
Product product = ProductInventoryManager.getProductMap().get("123");
String message = "Failure Picking!" +
"\nProduct ID: " + product.getId() +
"\nLocation: " + product.getLocation().getName() +
"\nAmount Requested to Pick: " + 13 +
"\nInventory: " + product.getInventory() +
"\nFailure Message: " + "Not enough inventory to process request.";
assertEquals(message, pickingResult.getDetailMessage());
}
@Test
public void testSuccessfulRestockProduct() {
ProductInventoryManager manager = new ProductInventoryManager();
RestockingResult restockingResult = manager.restockProduct("452", 100);
Product product = ProductInventoryManager.getProductMap().get("452");
String message = "Success Restocking!" +
"\nProduct ID: " + product.getId() +
"\nLocation: " + product.getLocation().getName() +
"\nAmount Restocked: " + 100 +
"\nNew Inventory: " + product.getInventory();
assertEquals(message, restockingResult.getDetailMessage());
}
@Test
public void testUnsuccessfulRestockProductShouldGetErrorMessage() {
ProductInventoryManager manager = new ProductInventoryManager();
RestockingResult restockingResult = manager.restockProduct("789", Integer.MAX_VALUE - 2);
Product product = ProductInventoryManager.getProductMap().get("789");
String message = "Failure Restocking!" +
"\nProduct ID: " + product.getId() +
"\nLocation: " + product.getLocation().getName() +
"\nAmount Requested to Restock: " + (Integer.MAX_VALUE - 2) +
"\nInventory: " + product.getInventory() +
"\nFailure Message: " + "Too much inventory to process request. Inventory cannot exceed: " +
Product.maxInventory + ".";
assertEquals(message, restockingResult.getDetailMessage());
}
@Test (expected = IllegalArgumentException.class)
public void testProductIDNotFoundPicking() {
ProductInventoryManager inventoryManager = new ProductInventoryManager();
inventoryManager.pickProduct("54997998", 3);
}
@Test (expected = IllegalArgumentException.class)
public void testProductIDNotFoundRestocking() {
ProductInventoryManager inventoryManager = new ProductInventoryManager();
inventoryManager.restockProduct("54997998", 3);
}
} | true |
51222c935432a54f7519ef844401d4c289c27690 | Java | unuldur/Uminc | /app/src/main/java/com/unuldur/uminc/model/IEtudiant.java | UTF-8 | 444 | 2 | 2 | [] | no_license | package com.unuldur.uminc.model;
import java.io.Serializable;
import java.util.List;
import java.util.Set;
/**
* Created by Unuldur on 06/12/2017.
*/
public interface IEtudiant extends Serializable {
String getNUmEtu();
String getPassword();
List<UE> getUEs();
List<UE> getActualUEs();
List<Note> getNotes();
void setNotes(List<Note> notes);
void addCalendar(ICalendar calendar);
ICalendar getCalendar();
}
| true |
4ab114ca01f90af4421ffc7f33b86be459cff0c5 | Java | nngo2/SWE | /business/Quantity.java | UTF-8 | 842 | 2.75 | 3 | [] | no_license | package business;
/**
* Stored at the business level since it's business data. Not stored in product subsystem because contains gui data
*/
public class Quantity {
private String quantityRequested;
private String quantityAvailable;
public Quantity(String quantityRequested) {
this.quantityRequested = quantityRequested;
}
/**
* @return the quantityRequested
* @uml.property name="quantityRequested"
*/
public String getQuantityRequested() {
return quantityRequested;
}
/**
* @return the quantityAvailable
* @uml.property name="quantityAvailable"
*/
public String getQuantityAvailable() {
return quantityAvailable;
}
/**
* @param quantityAvailable the quantityAvailable to set
* @uml.property name="quantityAvailable"
*/
public void setQuantityAvailable(String q) {
quantityAvailable = q;
}
}
| true |
ddec05d4da9fb06d015d78dc66e3e9e2a1cf3be5 | Java | Thomas-art-hue/boot_03 | /src/main/java/com/example/interceptor/Sessioniceptor.java | UTF-8 | 1,314 | 2.671875 | 3 | [] | no_license | package com.example.interceptor;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class Sessioniceptor extends HandlerInterceptorAdapter {
/**
* true放行
*
* @param request
* @param response
* @param handler
* @return
* @throws Exception
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("==============拦截器===================");
// 除掉项目名称时访问页面当前路径
String url = request.getRequestURI();
System.out.println("路径" + url);
HttpSession session = request.getSession();
Object user = session.getAttribute("us");
System.out.println("是空的嘛?:" + user);
if (user == null) {
//获取当前请求的路径
System.out.println("走重定向");
//告诉ajax我重定向的路径
response.sendRedirect("/index.html");
return false;
} else {
System.out.println("路径" + url);
return true;
}
}
} | true |
4c5673acc605421d54c9256421c1e8c2c980d3be | Java | Rohan009/LeapYear | /LeapYear.java | UTF-8 | 645 | 3.5625 | 4 | [] | no_license | import java.util.ArrayList;
import java.util.List;
public class LeapYear {
public static void main(String[] args) {
List<Integer> leapYears = new ArrayList<>();
leapYears.add(1700);
leapYears.add(1900);
leapYears.add(2000);
leapYears.add(1600);
leapYears.add(100);
leapYears.add(1996);
leapYears.add(2012);
leapYears.add(1991);
leapYears.add(400);
leapYears.add(202);
for(Integer year : leapYears)
System.out.println(checkLeapYear(year));
}
static boolean checkLeapYear(int leapYear) {
return leapYear % 4 == 0 && (leapYear % 100 != 0 || leapYear % 400 == 0);
}
}
| true |
c5a7c05d1a0f7aa9a71a3b1d7b26f21484f8e22f | Java | kedarkhetia/PubSub-Framework | /src/main/java/cs601/project2/brokerImpl/AsyncOrderedDispatchBroker.java | UTF-8 | 2,670 | 3.203125 | 3 | [] | no_license | package cs601.project2.brokerImpl;
import java.util.concurrent.ConcurrentLinkedQueue;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import cs601.project2.broker.Broker;
import cs601.project2.collections.AsyncBlockingQueue;
import cs601.project2.roles.Subscriber;
/**
* AsyncOrderedDispatchBroker is used to deliver events
* that are published by publishers to subscribers, Asynchronously
* and in ordered manner.
*
* @author kmkhetia
*
*/
public class AsyncOrderedDispatchBroker<T> implements Broker<T>, Runnable {
private volatile boolean shutdownFlag;
private ConcurrentLinkedQueue<Subscriber<T>> subscribers;
private AsyncBlockingQueue<T> blockingQueue;
private int QUEUE_SIZE = 1000;
private int TIMEOUT = 300;
private final static Logger log = LogManager.getLogger(AsyncOrderedDispatchBroker.class);
/**
* Constructor for AsyncOrderedDispatchBroker.
*/
public AsyncOrderedDispatchBroker() {
subscribers = new ConcurrentLinkedQueue<Subscriber<T>>();
log.info("Created Blocking queue with size=" + QUEUE_SIZE);
blockingQueue = new AsyncBlockingQueue<T>(QUEUE_SIZE);
shutdownFlag = false;
}
/**
* Run method that will send published data
* Asynchronously.
*
* @param item
*/
@Override
public void run() {
T element = blockingQueue.poll(TIMEOUT);
log.info("Starting to publish data on blocking queue.");
while(!shutdownFlag || !blockingQueue.isEmpty()) {
if(element != null) {
for(Subscriber<T> i : subscribers) {
i.onEvent(element);
}
}
element = blockingQueue.poll(TIMEOUT);
}
// Publishing last event
if(element != null) {
for(Subscriber<T> i : subscribers) {
i.onEvent(element);
}
}
log.info("Completed publishing data to blocking queue.");
}
/**
* Called by a publisher to publish a new item. The
* item will be delivered to all current subscribers.
*
* @param item
*/
@Override
public void publish(T item) {
if(!shutdownFlag) {
blockingQueue.put(item);
}
}
/**
* Called once by each subscriber. Subscriber will be
* registered and receive notification of all future
* published items.
*
* @param subscriber
*/
@Override
public void subscribe(Subscriber<T> subscriber) {
subscribers.add(subscriber);
}
/**
* Indicates this broker should stop accepting new
* items to be published and shut down all threads.
* The method will block until all items that have been
* published have been delivered to all subscribers.
*/
@Override
public void shutdown() {
log.info("Shutdown broker called");
shutdownFlag = true;
log.info("shutdownFlag=" + shutdownFlag);
}
}
| true |
e57135f8c6c1ce4d561fac80f77e5225766f30a7 | Java | Iratu/videostreamer | /backend/src/main/java/org/eientei/video/backend/config/PersistenceConfiguration.java | UTF-8 | 857 | 1.789063 | 2 | [] | no_license | package org.eientei.video.backend.config;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.orm.hibernate4.HibernateExceptionTranslator;
import javax.persistence.EntityManagerFactory;
/**
* User: iamtakingiteasy
* Date: 2015-05-05
* Time: 18:56
*/
@Configuration
public class PersistenceConfiguration {
@Autowired
private EntityManagerFactory entityManagerFactory;
@Bean
public SessionFactory sessionFactory() {
return entityManagerFactory.unwrap(SessionFactory.class);
}
@Bean
public HibernateExceptionTranslator persistenceExceptionTranslationPostProcessor() {
return new HibernateExceptionTranslator();
}
}
| true |
139018f98b238f93220bcfb87ee75d0409683cdf | Java | kumarh1982/rsocket | /rsocket-transport-netty/src/main/java/com/jauntsdn/rsocket/transport/netty/WebsocketUriHandler.java | UTF-8 | 2,132 | 2.296875 | 2 | [
"Apache-2.0"
] | permissive | /*
* Copyright 2015-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jauntsdn.rsocket.transport.netty;
import com.jauntsdn.rsocket.transport.ClientTransport;
import com.jauntsdn.rsocket.transport.ServerTransport;
import com.jauntsdn.rsocket.transport.netty.client.WebsocketClientTransport;
import com.jauntsdn.rsocket.transport.netty.server.WebsocketServerTransport;
import com.jauntsdn.rsocket.uri.UriHandler;
import java.net.URI;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
/**
* An implementation of {@link UriHandler} that creates {@link WebsocketClientTransport}s and {@link
* WebsocketServerTransport}s.
*/
public final class WebsocketUriHandler implements UriHandler {
private static final List<String> SCHEME = Arrays.asList("ws", "wss", "http", "https");
@Override
public Optional<ClientTransport> buildClient(URI uri) {
Objects.requireNonNull(uri, "uri must not be null");
if (SCHEME.stream().noneMatch(scheme -> scheme.equals(uri.getScheme()))) {
return Optional.empty();
}
return Optional.of(WebsocketClientTransport.create(uri));
}
@Override
public Optional<ServerTransport> buildServer(URI uri) {
Objects.requireNonNull(uri, "uri must not be null");
if (SCHEME.stream().noneMatch(scheme -> scheme.equals(uri.getScheme()))) {
return Optional.empty();
}
int port = UriUtils.isSecure(uri) ? UriUtils.getPort(uri, 443) : UriUtils.getPort(uri, 80);
return Optional.of(WebsocketServerTransport.create(uri.getHost(), port));
}
}
| true |
903355c2a8c1384e78e6d03a72a2b34ec24342f6 | Java | idoroshev/RevolutTest | /src/main/java/org/idorashau/revoluttest/dto/Account.java | UTF-8 | 834 | 2.375 | 2 | [] | no_license | package org.idorashau.revoluttest.dto;
import java.util.UUID;
public class Account {
private UUID accountId;
private long balance;
private String currency;
public Account() {
}
public Account(UUID accountId, long balance, String currency) {
this.accountId = accountId;
this.balance = balance;
this.currency = currency;
}
public UUID getAccountId() {
return accountId;
}
public void setAccountId(UUID accountId) {
this.accountId = accountId;
}
public long getBalance() {
return balance;
}
public void setBalance(long balance) {
this.balance = balance;
}
public String getCurrency() {
return currency;
}
public void setCurrency(String currency) {
this.currency = currency;
}
}
| true |
043f5d3d4ed50c1ec5628008949ecb6664e95ff6 | Java | ridajawda/pm-test | /pm-test/src/main/java/zfp/com/pmtest/repository/ConsultantRepository.java | UTF-8 | 333 | 1.609375 | 2 | [] | no_license | package zfp.com.pmtest.repository;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import zfp.com.pmtest.entity.Client;
import zfp.com.pmtest.entity.Consultant;
@Repository
public interface ConsultantRepository extends CrudRepository<Consultant, Long>{
}
| true |
3580bddcaffba88b216d2e090123063576766edf | Java | sususama/PTA | /src/LeetCode/剑指offer/TranslateNum.java | UTF-8 | 1,099 | 4.125 | 4 | [] | no_license | package LeetCode.剑指offer;
public class TranslateNum {
public int translateNum(int num) {
// 这道题我们可以首先把每个下标看成单独的数字进行翻译,然后和它的前一位进行合并
// 看他们是否合法,即前一位和当前为组合为 10 - 25,如果合法,就将其进行统计,否则就不计数
String str = String.valueOf(num);
// 分别代表:最多可以翻译的数量,上一个的最大数量,上上一个最大数量
int answer = 1,ind = 0,last = 0;
for (int i = 0; i < str.length(); i++){
// 进行数组滚动,将所有的下标向右移动
last = ind;
ind = answer;
answer = 0;
answer+= ind;
if (i == 0) continue;
// 进行判断,如果数字合法,就计数
// 取出上一个数字
String temp = str.substring(i - 1, i + 1);
if (temp.compareTo("25") <= 0 && temp.compareTo("10") >= 0)
answer += last;
}
return answer;
}
}
| true |
ced368fc3530c8b0ab69c9ec5af0af845327c342 | Java | Blizzzer/DBClientUganda | /src/com/resources/RestrictedValuesStrings.java | UTF-8 | 736 | 2.359375 | 2 | [] | no_license | package com.resources;
import java.util.Arrays;
import java.util.List;
public final class RestrictedValuesStrings {
public static List<String> tankerPosition = Arrays.asList( "G", "D", "C", "L");
public static List<String> engineerType = Arrays.asList( "BC", "EE", "ME", "ED");
public static List<String> engineerDrink = Arrays.asList( "O", "M", "RB", "RS");
public static List<String> soldierRank = Arrays.asList( "P", "C", "L");
public static List<String> equipmentType = Arrays.asList( "AR", "SG", "SR", "TK");
public static List<String> weaponCaliber = Arrays.asList("5.56", "7.62", "9mm", ".45", ".44M", ".50M", ".22", "12g", ".357M");
public static List<String> fuelType = Arrays.asList("D", "G");
}
| true |
6ca8f8b316ecbc4f33bd06e87443b269f7da5889 | Java | 201DevC/201-Backend | /src/main/java/com/cs201/sendo/mappers/CategoryRepository.java | UTF-8 | 892 | 1.914063 | 2 | [] | no_license | package com.cs201.sendo.mappers;
import com.cs201.sendo.models.Category;
import com.cs201.sendo.models.paging.PagingParams;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
import java.util.List;
@Mapper
@Repository
public interface CategoryRepository {
Long getCategoryLv1Count();
List<Category> getCategoryLv1List(@Param("param") PagingParams params);
Long getCategoryLv2Count(@Param("parentId") Long parentId);
List<Category> getCategoryLv2List(@Param("param") PagingParams params, @Param("parentId") Long parentId);
Long getCategoryLv3Count(@Param("parentId") Long parentId);
List<Category> getCategoryLv3List(@Param("param") PagingParams params, @Param("parentId") Long parentId);
List<Long> getCategoryIdLv2ByParentIds(@Param("lv1Ids") List<Long> lv1Ids);
}
| true |
0d11d550b27fcd4a03e46eedb82d0d6566302cdb | Java | oceanbhardwaj/LeetcodeJulyChallenge | /ReverseBits.java | UTF-8 | 428 | 2.984375 | 3 | [] | no_license | public class Solution {
// you need treat n as an unsigned value
public int reverseBits(int n) {
boolean sign=false;
if(n<0)
sign=true;
int res=0;
for(int i=0;i<31;i++)
{
res|=(n & 1);
n=n>>1;
res=res<<1;
}
if(sign==true)
res=res+1;
return res;
}
} | true |
86b4341359fb1b2c8dc5ca441580b8e557bbc6b3 | Java | jupiter-tools/spring-test-mongo | /src/test/java/com/jupiter/tools/spring/test/mongo/internal/expect/match/smart/groovy/MatchGroovyTest.java | UTF-8 | 3,033 | 2.421875 | 2 | [] | no_license | package com.jupiter.tools.spring.test.mongo.internal.expect.match.smart.groovy;
import com.antkorwin.commonutils.exceptions.InternalException;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import java.util.Date;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Created on 22.12.2018.
*
* @author Korovin Anatoliy
*/
class MatchGroovyTest {
private final MatchGroovy matchGroovy = new MatchGroovy();
@Nested
class MatchTests {
@Test
void simpleValueComparing() {
// Act
boolean match = matchGroovy.match(123, "groovy-match: value == 123");
// Asserts
assertThat(match).isEqualTo(true);
}
@Test
void compareValueWithSum() {
// Act
boolean match = matchGroovy.match(55, "groovy-match: value == (1..10).sum()");
// Asserts
assertThat(match).isEqualTo(true);
}
@Test
void checkDateAndTime() {
// Act
boolean match = matchGroovy.match(new Date(),
"groovy-match: new Date().getTime() - value.getTime() < 10000");
// Asserts
assertThat(match).isEqualTo(true);
}
}
@Nested
class NecessaryTests {
@Test
void necessary() {
boolean necessary = matchGroovy.isNecessary("groovy-match: value == 123");
assertThat(necessary).isEqualTo(true);
}
@Test
void notNecessary() {
boolean necessary = matchGroovy.isNecessary("groovy: value == 123");
assertThat(necessary).isFalse();
}
@Test
void withoutGroovyPrefix() {
boolean necessary = matchGroovy.isNecessary("value == 123");
assertThat(necessary).isFalse();
}
@Test
void notGroovy() {
boolean necessary = matchGroovy.isNecessary("123");
assertThat(necessary).isFalse();
}
@Test
void wrongTypeOfValue() {
boolean necessary = matchGroovy.isNecessary(1024);
assertThat(necessary).isFalse();
}
}
@Nested
class CornerCaseTests {
@Test
void notBooleanResult() {
// Act
InternalException exception = Assertions.assertThrows(InternalException.class, () -> {
matchGroovy.match(55, "groovy-match: (1..10).sum()");
});
assertThat(exception.getMessage()).contains("groovy-match: must return a boolean value instead of {55}");
}
@Test
void wrongGroovyScript() {
// Act
InternalException exception = Assertions.assertThrows(InternalException.class, () -> {
matchGroovy.match(55, "groovy-match: *p = (1..10).sum() ");
});
assertThat(exception.getMessage()).contains("Groovy engine evaluate error");
}
}
} | true |
7ba655139d9e4915221ef1c3f1d27151dad467f6 | Java | tfmorris/Names | /score/src/main/java/org/folg/names/score/FeaturesScorer.java | UTF-8 | 2,042 | 2.421875 | 2 | [
"Apache-2.0",
"CC-BY-SA-4.0"
] | permissive | /*
* Copyright 2011 Foundation for On-Line Genealogy, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.folg.names.score;
/**
* Sum weighted features to compute a score
* The weights were generated by running training data provided by Ancestry.com through Weka's Logistic learner
*/
public class FeaturesScorer {
private final boolean isSurname;
public FeaturesScorer(boolean isSurname) {
this.isSurname = isSurname;
}
public double score(Features features) {
if (isSurname) {
// Logistic (F=86.2)
//wed -5.6122
//nys 0.4026
//sdx 0.1687
//rsdx 0.5052
//dmsdx 0.9679
//lev 0.3696
//Intercept 7.7697
return 7.7697 +
features.weightedEditDistance * -5.6122 +
features.nysiis * 0.4026 +
features.soundex * 0.1687 +
features.refinedSoundex * 0.5052 +
features.dmSoundex * 0.9679 +
features.levenstein * 0.3696;
}
else {
// Logistic (F=94.4)
//wed -7.3705
//sdx 0.0699
//rsdx 0.6476
//dmsdx 1.2748
//lev 0.4359
//Intercept 11.5572
return 11.5572 +
features.weightedEditDistance * -7.3705 +
// nysiis not useful for givennames
features.soundex * 0.0699 +
features.refinedSoundex * 0.6476 +
features.dmSoundex * 1.2748 +
features.levenstein * 0.4359;
}
}
}
| true |
7b84c160d513c04598ba38a237ed86c9fff5b731 | Java | llxqb/Kencanme | /app/src/main/java/com/shushan/kencanme/app/mvp/ui/activity/loveMe/LoveMePeopleControl.java | UTF-8 | 1,201 | 2.15625 | 2 | [] | no_license | package com.shushan.kencanme.app.mvp.ui.activity.loveMe;
import com.shushan.kencanme.app.entity.request.LikeRequest;
import com.shushan.kencanme.app.entity.request.MyFriendsRequest;
import com.shushan.kencanme.app.entity.request.RequestFreeChat;
import com.shushan.kencanme.app.entity.response.MyFriendsResponse;
import com.shushan.kencanme.app.mvp.presenter.LoadDataView;
import com.shushan.kencanme.app.mvp.presenter.Presenter;
/**
* Created by li.liu on 2019/05/28.
*/
public class LoveMePeopleControl {
public interface LoveMePeopleView extends LoadDataView {
void getLoveMePeopleInfoSuccess(MyFriendsResponse myFriendsResponse);
void getLikeSuccess(String msg);
void chatNumSuccess();
}
public interface PresenterLoveMePeople extends Presenter<LoveMePeopleView> {
/**
* 好友/喜欢的人列表
*/
void onRequestMyFriendList(MyFriendsRequest myFriendsRequest);
/**
* 喜欢
*/
void onRequestLike(LikeRequest likeRequest);
/**
* 密聊接口
* 统计今日密聊次数
*/
void onRequestChatNum(RequestFreeChat requestFreeChat);
}
}
| true |
cc40811b9115fb3feffcfc63055e2736510af1fb | Java | khatwaniNikhil/microservices-breaking-up-a-monolith | /monolith/src/main/java/com/xebia/msa/domain/Account.java | UTF-8 | 1,917 | 2.640625 | 3 | [] | no_license | package com.xebia.msa.domain;
import javax.persistence.Entity;
import javax.persistence.Id;
import java.util.UUID;
@Entity
public class Account {
@Id
private UUID uuid;
private String address;
private String phoneNumber;
private String email;
public Account() {}
public Account(UUID uuid, String address, String phoneNumber, String email) {
this.uuid = uuid;
this.address = address;
this.phoneNumber = phoneNumber;
this.email = email;
}
public Account(String address, String phoneNumber, String email) {
this.uuid = UUID.randomUUID();
this.address = address;
this.phoneNumber = phoneNumber;
this.email = email;
}
public UUID getUuid() {
return uuid;
}
public void setUuid(UUID uuid) {
this.uuid = uuid;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "Account{" +
"uuid=" + uuid +
", address='" + address + '\'' +
", phoneNumber='" + phoneNumber + '\'' +
", email='" + email + '\'' +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Account account = (Account) o;
return uuid.equals(account.uuid);
}
@Override
public int hashCode() {
return uuid.hashCode();
}
}
| true |
c413450497f87716ad82368d33a74400ff6a15bd | Java | fontanellileonardo/CarRenting-KeyValue | /src/Utils.java | UTF-8 | 865 | 2.484375 | 2 | [] | no_license | import java.time.LocalDate;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.TimeZone;
public class Utils {
public final static int CAR_MANAGER = 1,
USER_TABLE = 2,
FEEDBACK_TABLE = 3,
RESERVATION_TABLE = 4;
public final static long MIN_MARK = 1L;
public final static Integer MAX_MARK = 5;
// Return the current date (java.sql.Date)
public static java.sql.Date getCurrentSqlDate() {
Calendar cal = Calendar.getInstance();
java.sql.Date date = new java.sql.Date(cal.getTimeInMillis());
return date;
}
public static java.sql.Date localDateToSqlDate(LocalDate localDate) {
java.util.Date date = java.util.Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
java.sql.Date sqlDate = new java.sql.Date(date.getTime());
return sqlDate;
}
}
| true |
c01f23fbf152b505d1d479ecb4201fac67c9e219 | Java | Sudarsan-Sridharan/java-fix | /fix-engine-jackson/src/main/java/me/kolek/fix/engine/jackson/FixEngineConfigurationDeserializer.java | UTF-8 | 1,440 | 2.1875 | 2 | [] | no_license | package me.kolek.fix.engine.jackson;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import me.kolek.fix.engine.config.FixEngineConfiguration;
import me.kolek.fix.engine.config.FixSessionConfiguration;
import java.io.IOException;
import java.util.List;
public class FixEngineConfigurationDeserializer extends JsonDeserializer<FixEngineConfiguration> {
public static final FixEngineConfigurationDeserializer INSTANCE = new FixEngineConfigurationDeserializer();
@Override
public FixEngineConfiguration deserialize(JsonParser p, DeserializationContext ctxt)
throws IOException, JsonProcessingException {
DelegateBuilder builder = ctxt.readValue(p, DelegateBuilder.class);
return builder.delegate.build();
}
private static class DelegateBuilder {
FixEngineConfiguration.Builder delegate = new FixEngineConfiguration.Builder();
public void setAcceptorHost(String acceptorHost) {
delegate.acceptorHost(acceptorHost);
}
public void setAcceptorPort(Integer acceptorPort) {
delegate.acceptorPort(acceptorPort);
}
public void setSessions(List<FixSessionConfiguration> sessions) {
sessions.forEach(delegate::session);
}
}
}
| true |
6eb68593001d9d541c2434a19f6b20bf0d3dfab6 | Java | Daso/POO | /UPCMatricula/src/upcmatricula/UPCMatricula.java | UTF-8 | 262 | 1.609375 | 2 | [] | no_license | package upcmatricula;
import models.*;
import vistas.MatriculaView;
public class UPCMatricula {
public static void main(String[] args) {
MatriculaView matriculaview = new MatriculaView();
matriculaview.matricular();
}
}
| true |
f91fdf9c2cb7dac0029e8919c2cc1d1a169559c8 | Java | otokatari/androidMusic | /app/src/main/java/otokatari/com/otokatari/Model/s/RequestInfo/CommentsShareWithID.java | UTF-8 | 696 | 1.8125 | 2 | [] | no_license | package otokatari.com.otokatari.Model.s.RequestInfo;
public class CommentsShareWithID {
private String musicid;
private String commentid;
private CommentsShare commentsShare;
public String getMusicid() {
return musicid;
}
public CommentsShare getCommentsShare() {
return commentsShare;
}
public String getCommentid() {
return commentid;
}
public void setMusicid(String musicid) {
this.musicid = musicid;
}
public void setCommentid(String commentid) {
this.commentid = commentid;
}
public void setCommentsShare(CommentsShare commentsShare) {
this.commentsShare = commentsShare;
}
}
| true |
74c3d48d3581a6cb21cd235736372769e4439706 | Java | lichong6232/SwordToOffer | /src/cn/bupt/swordToOffer/GetKminNumber.java | UTF-8 | 3,134 | 3.34375 | 3 | [] | no_license | package cn.bupt.swordToOffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class GetKminNumber {
public static void main(String[] args) {
GetKminNumber getKminNumber=new GetKminNumber();
int input[]={4,5,1,6,2,7,3,8};
int k=9;
List<Integer> list=getKminNumber.GetLeastNumbers_Solution(input, k);
System.out.println(list);
}
public ArrayList<Integer> GetLeastNumbers_Solution(int [] input, int k) {
if(k<1||k>input.length){
return new ArrayList<Integer>();
}
int kThMinNumber=getKthNumber(input, k);
Integer res[]=new Integer[k];
int index=0;
for(int i=0;i<input.length;i++){
if(input[i]<kThMinNumber){
res[index++]=input[i];
}
}
while(index<k){
res[index++]=kThMinNumber;
}
ArrayList<Integer> list=new ArrayList<Integer>(Arrays.asList(res));
return list;
}
public int getKthNumber(int input[],int k){
int copyArray[]=copyArray(input);
return selection(input, 0, copyArray.length-1, k-1);
}
public int[] copyArray(int[] arr) {
int[] res = new int[arr.length];
for (int i = 0; i != res.length; i++) {
res[i] = arr[i];
}
return res;
}
public int selection(int input[],int start,int end,int k){
if(start==end){
return input[start];
}
int pivot=getMedianOfMedian(input, start, end);
int partition[]=partition(input,start,end,pivot);
if(k>=partition[0]&&k<=partition[1]){
return input[k];
}else if(k<partition[0]){
return selection(input, start, partition[0]-1, k);
}else{
return selection(input, partition[1]+1, end, k);
}
}
public int[] partition(int[] arr, int begin, int end, int pivotValue) {
int small = begin - 1;
int cur = begin;
int big = end + 1;
while (cur != big) {
if (arr[cur] < pivotValue) {
swap(arr, ++small, cur++);
} else if (arr[cur] > pivotValue) {
swap(arr, cur, --big);
} else {
cur++;
}
}
int[] range = new int[2];
range[0] = small + 1;
range[1] = big - 1;
return range;
}
public int getMedianOfMedian(int input[],int start,int end){
int sum=end-start+1;
int mArrayLength=sum/5+(sum%5==0?0:1);
int mArray[]=new int[mArrayLength];
for(int i=0;i<mArrayLength;i++){
int startI=start+i*5;
int endI=startI+4;
mArray[i]=getMedian(input, startI, Math.min(endI, end));
}
return getMedian(mArray, 0, mArrayLength-1);
}
public int getMedian(int input[],int start,int end){
insertSort(input, start, end);
int mid=(start+end)/2+(start+end)%2;
return input[mid];
}
public void swap(int input[],int start,int end){
if(start!=end){
input[start]=input[start]^input[end];
input[end]=input[start]^input[end];
input[start]=input[start]^input[end];
}
}
public void insertSort(int input[],int start,int end){
for(int i=start+1;i<=end;i++){
int temp=input[i];
int j=i-1;
while(j>=0&&input[j]>temp){
input[j+1]=input[j];
j--;
}
input[j+1]=temp;
}
}
}
| true |
6f16c5c1abc49d1ef9f199c1d09a8cab6e9b4cbd | Java | FanZicheng/ccden | /src/main/java/com/coaledu/org/iservice/IPositionService.java | UTF-8 | 392 | 1.976563 | 2 | [] | no_license | package com.coaledu.org.iservice;
import java.util.List;
import com.coaledu.org.model.Position;
public interface IPositionService {
public void addPosition(Position position);
public void deletePositionById(Integer id);
public void updatePosition(Position position);
public Position getPositionById(Integer id);
public List<Position> getAllPosition();
}
| true |
fef36305037735facda4f680eba3cc9a19ce32bd | Java | KafferAffer/SoftwareEksamensProjekt | /EksamensProjekt/src/Applikationslag/Redskaber/Dates.java | UTF-8 | 433 | 2.640625 | 3 | [] | no_license | package Applikationslag.Redskaber;
import java.time.LocalDate;
import java.time.temporal.WeekFields;
import java.util.Locale;
public final class Dates {
public static int getCurrentWeek() {
LocalDate date = LocalDate.now();
WeekFields weekFields = WeekFields.of(Locale.getDefault());
return date.get(weekFields.weekOfWeekBasedYear());
}
public static int getYear()
{
return (LocalDate.now().getYear());
}
}
| true |