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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
ff08f69367a90fb64bcc86d678845d514d58c5f7
|
Java
|
ActianCorp/OpenROAD_json
|
/java/JsonHttpURLConnection.java
|
UTF-8
| 1,689
| 2.796875
| 3
|
[] |
no_license
|
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class JsonHttpURLConnection {
public static void main(String[] args) throws Exception {
JsonHttpURLConnection jsonrpc = new JsonHttpURLConnection();
System.out.println("\nHttp JSON RPC POST request");
jsonrpc.sendPost();
}
private void sendPost() throws Exception {
String url = System.getenv("ORJSON_URL");
if (url == null || url.isEmpty()) {
url = "http://localhost:8080/openroad/jsonrpcservertest";
} else {
url = url + "/jsonrpcservertest";
}
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestProperty("Content-Type", "application/json");
con.setRequestMethod("POST");
String urlParameters = "{\"jsonrpc\": \"2.0\", \"id\": 1, \"method\": \"subtract\" , \"params\": {\"subtrahend\": 23.4, \"minuend\": 42.8}}";
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + urlParameters);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println("Response : " + response.toString());
}
}
| true
|
bada512dedee6b2f59545b75f39b8b9bde12ce02
|
Java
|
onnet/J
|
/L10/src/ru/iam/Main.java
|
UTF-8
| 3,860
| 3.453125
| 3
|
[] |
no_license
|
package ru.iam;
import java.util.*;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
// write your code here
//1.
System.out.println("1. Написать метод, который на входе получает коллекцию объектов, а возвращает коллекцию уже без дубликатов");
List<String> strings = List.of("first", "second", "third", "first", "second");
System.out.println(setFilter(strings));
//2.
System.out.println("2. Сравнение ArrayList и LinkedList.\n");
ListTypesCompare();
//3.
System.out.println("3. Создайте Map (Map<User, Integer>).\n");
Map<User, Integer> myUsersMap = Map.of(
new User("Ivan"), 5,
new User("Petr"), 4,
new User("Vasiliy"), 3,
new User("Luka"), 4
);
System.out.print("Input name (ex. Ivan): ");
Scanner console = new Scanner(System.in);
String username = console.nextLine();
Optional SearchResult = myUsersMap.entrySet()
.stream()
.filter(entry -> Objects.equals(entry.getKey().getName(), username))
.map(Map.Entry::getValue)
.findFirst();
if (SearchResult.isPresent()) {
System.out.println("\nUser " + username + " score is " + SearchResult.get().toString());
} else {
System.out.println("\nSorry, no user found");
}
//4.
System.out.println("\n4. Вернуть нужно объект Map<K, Integer>.\n");
String array[] = { "Пиво", "Вино", "Водка", "Водка", "Водка", "Газировка", "Газировка" };
Map<String, Long> mymap = convertArrayToMap(array);
System.out.println("MyMap: " + mymap);
}
static Set<String> setFilter(List<String> str) {
Set<String> stringsSet = new HashSet<>();
str.forEach(stringsSet::add);
return stringsSet;
}
private static int random() {
return new Random().nextInt(1000000);
}
public static void ListTypesCompare() {
int tmp;
long start_ms;
List<Integer> arrayList = new ArrayList<>();
List<Integer> linkedList = new LinkedList<>();
for (int i = 0; i < 1000000; i++) {
tmp = random();
arrayList.add(tmp);
linkedList.add(tmp);
}
start_ms = System.nanoTime();
for (int i = 0; i < 100000; i++) {
arrayList.get((random()));
}
System.out.println("ArrayList operations duration: " + (System.nanoTime() - start_ms) / 1000000);
start_ms = System.nanoTime();
for (int i = 0; i < 1000; i++) {
linkedList.get((random()));
}
System.out.println("LinkedList operations duration: " + (System.nanoTime() - start_ms) / 1000000);
}
static class User {
User(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
private String name;
}
public static <T> Map<T,Long> convertArrayToMap(T array[])
{
Set<T> set = new HashSet<>();
Collections.addAll(set, array);
Map<T,Long> map = set.stream()
// Map<T,T> map = Set.of(array).stream()
.collect(
// Collectors.toMap(x -> x, x -> x, (oldValue, newValue) -> newvalue)
Collectors.toMap(x -> x, x ->
Arrays.stream(array).filter(i -> i == x).count()
)
);
return map;
}
}
| true
|
563975f47f26346d31501cb45067ca2c10658830
|
Java
|
jlsheshen/SevenStarSteward
|
/SevenStarSteward/sevenStarSteward/src/main/java/com/sevenstar/steward2016/adapter/SelectCleanServiceAdapter.java
|
UTF-8
| 3,926
| 2.09375
| 2
|
[] |
no_license
|
package com.sevenstar.steward2016.adapter;
import java.util.List;
import org.xutils.view.annotation.ViewInject;
import android.content.Context;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import com.alibaba.fastjson.JSONObject;
import com.lib.shiguotao.adapter.SGTHolderDefAdapter;
import com.lib.shiguotao.adapter.holder.BaseViewHolder;
import com.lib.shiguotao.utils.ViewUtils;
import com.sevenstar.steward2016.R;
import com.sevenstar.steward2016.adapter.viewholder.DefHolderView;
public class SelectCleanServiceAdapter extends SGTHolderDefAdapter<JSONObject> implements OnCheckedChangeListener {
public int index = -1;
public SelectCleanServiceAdapter(Context context, List<JSONObject> list, Object... objects) {
super(context, list, objects);
}
@Override
protected BaseViewHolder<JSONObject> getHolderView(View layout) {
// TODO Auto-generated method stub
return new FeatureOrderViewHolder(layout);
}
@Override
protected int getLayoutRes() {
// TODO Auto-generated method stub
return R.layout.select_clean_service_item_layout;
}
// implements TextWatche
public class FeatureOrderViewHolder extends DefHolderView<JSONObject> {
@ViewInject(R.id.service_et_one)
public EditText oneET;
// @ViewInject(R.id.service_et_two)
// EditText twoET;
@ViewInject(R.id.service_et_three)
public EditText threeET;
@ViewInject(R.id.service_et_four)
public EditText fourET;
@ViewInject(R.id.checkbox)
public CheckBox checkbox;
public FeatureOrderViewHolder(View layout) {
super(layout);
checkbox.setOnCheckedChangeListener(SelectCleanServiceAdapter.this);
}
@Override
public void update(JSONObject entity, Object... objects) {
if (entity != null) {
// oneET.removeTextChangedListener(this);
// threeET.removeTextChangedListener(this);
// fourET.removeTextChangedListener(this);
ViewUtils.setTextData(oneET, entity.getIntValue("Price") + "Ԫ");
// ViewUtils.setTextData(twoET,
// entity.getString("HouseTypeName"));
ViewUtils.setTextData(threeET, entity.getString("Target"));
ViewUtils.setTextData(fourET, entity.getString("Hours") + "Сʱ");
checkbox.setTag(getIndex());
if (index == getIndex()) {
// ViewUtils.requestEtFocus(oneET, true);
// ViewUtils.requestEtFocus(twoET, true);
// ViewUtils.requestEtFocus(threeET, true);
// ViewUtils.requestEtFocus(fourET, true);
// oneET.addTextChangedListener(this);
// threeET.addTextChangedListener(this);
// fourET.addTextChangedListener(this);
} else {
// ViewUtils.requestEtFocus(oneET, false);
// ViewUtils.requestEtFocus(twoET, false);
// ViewUtils.requestEtFocus(threeET, false);
// ViewUtils.requestEtFocus(fourET, false);
checkbox.setChecked(false);
}
}
}
//
// @Override
// public void afterTextChanged(Editable s) {
// // TODO Auto-generated method stub
// if (oneET.isFocusable() && index != -1) {
// JSONObject json = getItem(index);
// json.put("Price", oneET.getText().toString().replace("Ԫ", ""));
// json.put("Target", threeET.getText().toString());
// json.put("Hours", fourET.getText().toString().replace("Сʱ", ""));
// }
// }
//
// @Override
// public void beforeTextChanged(CharSequence s, int start, int count,
// int after) {
// // TODO Auto-generated method stub
//
// }
//
// @Override
// public void onTextChanged(CharSequence s, int start, int before, int
// count) {
// // TODO Auto-generated method stub
//
// }
}
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
if (isChecked) {
Object obj = buttonView.getTag();
if (obj != null) {
index = (Integer) obj;
}
notifyDataSetChanged();
}
}
}
| true
|
f2badc930352e5ff041b4263b90782371f7651c5
|
Java
|
achudzicki/MyExpanses
|
/src/main/java/com/chudzick/expanses/builders/NotificationMessageListBuilder.java
|
UTF-8
| 1,312
| 2.59375
| 3
|
[] |
no_license
|
package com.chudzick.expanses.builders;
import com.chudzick.expanses.domain.responses.SimpleNotificationMsg;
import java.util.LinkedList;
import java.util.List;
public class NotificationMessageListBuilder {
private final List<SimpleNotificationMsg> allNotifications;
public NotificationMessageListBuilder() {
this.allNotifications = new LinkedList<>();
}
public NotificationMessageListBuilder withSuccessNotification(String msg) {
SimpleNotificationMsg simpleNotificationMsg = prepareNotification(true, msg);
allNotifications.add(simpleNotificationMsg);
return this;
}
public NotificationMessageListBuilder withFailureNotificationMsg(String msg) {
SimpleNotificationMsg simpleNotificationMsg = prepareNotification(false, msg);
allNotifications.add(simpleNotificationMsg);
return this;
}
public List<SimpleNotificationMsg> getNotificationList() {
return this.allNotifications;
}
private SimpleNotificationMsg prepareNotification(boolean isSuccess, String message) {
SimpleNotificationMsg simpleNotificationMsg = new SimpleNotificationMsg();
simpleNotificationMsg.setMessage(message);
simpleNotificationMsg.setSuccess(isSuccess);
return simpleNotificationMsg;
}
}
| true
|
2b4612d97e7c8b7819ad5570d623174bba7fbb4d
|
Java
|
FeiyiZHAO/Jeu-de-gestion
|
/javaproject/Fenetre.java
|
ISO-8859-1
| 1,340
| 3.125
| 3
|
[] |
no_license
|
package javaproject;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Fenetre extends JFrame implements ActionListener{
/**
*
*/
private static final long serialVersionUID = 1L;
public Fenetre(){
this.setTitle("Jeu de gestion");
this.setSize(300, 120);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
JPanel p1 = new JPanel();
Button b1 = new Button("Jouer");
b1.addActionListener(this);
//On dfinit le layout en lui indiquant qu'il travaillera en ligne
p1.setLayout(new BoxLayout(p1, BoxLayout.LINE_AXIS));
p1.add(b1);
JPanel p2 = new JPanel();
Button b2 = new Button("Rgles");
b2.addActionListener(this);
//Idem pour cette ligne
p2.setLayout(new BoxLayout(p2, BoxLayout.LINE_AXIS));
p2.add(b2);
JPanel p3 = new JPanel();
//On positionne maintenant ces trois lignes en colonne
p3.setLayout(new BoxLayout(p3, BoxLayout.PAGE_AXIS));
p3.add(p1);
p3.add(p2);
this.getContentPane().add(p3);
this.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
String composant = e.getActionCommand();
if(composant=="Jouer") {
new FenetreNiv();
this.dispose();}
if(composant=="Rgles")
System.out.println("non");
}
}
| true
|
645d5ac3e3051138988a3d91067d6d608d89cfad
|
Java
|
mvchain/cryptovault-android
|
/app/src/main/java/com/mvc/cryptovault_android/adapter/rvAdapter/TogeChildAdapter.java
|
UTF-8
| 3,470
| 1.84375
| 2
|
[] |
no_license
|
package com.mvc.cryptovault_android.adapter.rvAdapter;
import android.annotation.TargetApi;
import android.os.Build;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.mvc.cryptovault_android.R;
import com.mvc.cryptovault_android.bean.TogeBean;
import java.util.Date;
import java.util.List;
public class TogeChildAdapter extends BaseQuickAdapter<TogeBean.DataBean, BaseViewHolder> {
public TogeChildAdapter(int layoutResId, @Nullable List<TogeBean.DataBean> data) {
super(layoutResId, data);
}
@TargetApi(Build.VERSION_CODES.M)
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
protected void convert(BaseViewHolder helper, TogeBean.DataBean item) {
ImageView togeIcon = helper.getView(R.id.toge_child_icon);
TextView submit = helper.getView(R.id.toge_child_submit);
helper.setText(R.id.toge_child_title, item.getProjectName());
if (item.getStatus() == 1) {
submit.setText(R.string.toge_com);
submit.setVisibility(View.VISIBLE);
submit.setBackground(ContextCompat.getDrawable(mContext,R.drawable.bg_toge_child_item_tv_blue));
submit.setTextColor(ContextCompat.getColor(mContext,R.color.white));
submit.setEnabled(true);
helper.setText(R.id.toge_child_sj, TimeUtils.getFitTimeSpan(new Date(item.getStopAt()),new Date(System.currentTimeMillis()), 4));
} else if (item.getStatus() == 0) {
submit.setVisibility(View.GONE);
helper.setText(R.id.toge_child_sj, "即将开始");
} else {
submit.setText(R.string.toge_end);
submit.setVisibility(View.VISIBLE);
submit.setBackground(ContextCompat.getDrawable(mContext,R.drawable.bg_toge_child_item_tv_gray));
submit.setTextColor(ContextCompat.getColor(mContext,R.color.gray_white));
submit.setEnabled(false);
helper.setText(R.id.toge_child_sj, R.string.toge_end);
}
helper.setText(R.id.toge_child_recevie_type, "接收币种:" + item.getBaseTokenName());
helper.setText(R.id.toge_child_recevie_bespoke, "预约时间:" + TimeUtils.millis2String(item.getStartedAt()));
helper.setText(R.id.toge_child_gm, item.getTotal() + " " + item.getTokenName());
helper.setText(R.id.toge_child_xg, item.getProjectLimit() + " " + item.getTokenName());
helper.setText(R.id.toge_child_jg, "1 " + item.getTokenName() + " = " + item.getRatio() + " " + item.getBaseTokenName());
helper.setText(R.id.toge_child_bl, item.getReleaseValue() + "%");
RequestOptions options = new RequestOptions().fallback(R.drawable.default_project).placeholder(R.drawable.loading_img).error(R.drawable.default_project);
Glide.with(mContext).load(item.getProjectImage()).apply(options).into(togeIcon);
helper.getView(R.id.toge_child_submit).setOnClickListener(null);
helper.addOnClickListener(R.id.toge_child_submit);
}
}
| true
|
c28af3a0d6fcf62b22005a81716d4448300d730c
|
Java
|
Ferido07/oms
|
/src/main/java/com/kft/oms/service/AssociationService.java
|
UTF-8
| 766
| 1.945313
| 2
|
[] |
no_license
|
package com.kft.oms.service;
import com.kft.crud.service.CrudService;
import com.kft.oms.domain.Association;
import com.kft.oms.model.AssociationModel;
import com.kft.oms.repository.AssociationRepository;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import java.util.Optional;
public interface AssociationService extends CrudService<Association,Integer,AssociationRepository> {
Optional<Association> findByName(String name);
Optional<AssociationModel> findByIdAsAssociationModel(Integer id);
Optional<AssociationModel> findByNameAsAssociationModel(String name);
Page<AssociationModel> findAll(Pageable pageable);
Page<AssociationModel> findByNameStartingWith(String name, Pageable pageable);
}
| true
|
11134c2298359f225b63d3fbab3bced8e0e8fce4
|
Java
|
gledcarneiro/archetype_rabelo
|
/src/main/resources/archetype-resources/src/main/java/bean/EcfRecebimentoNaoFiscalPagamentoBean.java
|
UTF-8
| 3,708
| 2.078125
| 2
|
[] |
no_license
|
#set( $symbol_pound = '#' )
#set( $symbol_dollar = '$' )
#set( $symbol_escape = '\' )
package ${package}.bean;
import java.io.Serializable;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.event.ActionEvent;
import org.omnifaces.util.Messages;
import ${package}.dao.EcfRecebimentoNaoFiscalPagamentoDAO;
import ${package}.domain.EcfRecebimentoNaoFiscalPagamento;
@SuppressWarnings("serial")
@ManagedBean
@ViewScoped
public class EcfRecebimentoNaoFiscalPagamentoBean implements Serializable {
private EcfRecebimentoNaoFiscalPagamento recebimentoNaoFiscalPagamento;
private List<EcfRecebimentoNaoFiscalPagamento> recebimentoNaoFiscalPagamentos;
public EcfRecebimentoNaoFiscalPagamento getRecebimentoNaoFiscalPagamento() {
return recebimentoNaoFiscalPagamento;
}
public void setRecebimentoNaoFiscalPagamento(EcfRecebimentoNaoFiscalPagamento recebimentoNaoFiscalPagamento) {
this.recebimentoNaoFiscalPagamento = recebimentoNaoFiscalPagamento;
}
public List<EcfRecebimentoNaoFiscalPagamento> getRecebimentoNaoFiscalPagamentos() {
return recebimentoNaoFiscalPagamentos;
}
public void setRecebimentoNaoFiscalPagamentos(List<EcfRecebimentoNaoFiscalPagamento> recebimentoNaoFiscalPagamentos) {
this.recebimentoNaoFiscalPagamentos = recebimentoNaoFiscalPagamentos;
}
public void novo() {
recebimentoNaoFiscalPagamento = new EcfRecebimentoNaoFiscalPagamento();
}
@PostConstruct
public void listar() {
try {
EcfRecebimentoNaoFiscalPagamentoDAO recebimentoNaoFiscalPagamentoDAO = new EcfRecebimentoNaoFiscalPagamentoDAO();
recebimentoNaoFiscalPagamentos = recebimentoNaoFiscalPagamentoDAO.listar();
} catch (RuntimeException erro) {
Messages.addGlobalError("Ocorreu um erro ao listar os recebimentoNaoFiscalPagamentos !");
erro.printStackTrace();
}
}
public void salvar() {
try {
EcfRecebimentoNaoFiscalPagamentoDAO recebimentoNaoFiscalPagamentoDAO = new EcfRecebimentoNaoFiscalPagamentoDAO();
recebimentoNaoFiscalPagamentoDAO.merge(recebimentoNaoFiscalPagamento);
recebimentoNaoFiscalPagamento = new EcfRecebimentoNaoFiscalPagamento();
recebimentoNaoFiscalPagamentos = recebimentoNaoFiscalPagamentoDAO.listar();
Messages.addGlobalInfo("RecebimentoNaoFiscalPagamento salvo com sucesso");
} catch (RuntimeException erro) {
Messages.addGlobalError("Ocorreu um erro ao salvar o recebimentoNaoFiscalPagamento !");
erro.printStackTrace();
}
}
public void excluir(ActionEvent evento) {
try {
recebimentoNaoFiscalPagamento = (EcfRecebimentoNaoFiscalPagamento) evento.getComponent().getAttributes().get("recebimentoNaoFiscalPagamentoSelecionada");
EcfRecebimentoNaoFiscalPagamentoDAO recebimentoNaoFiscalPagamentoDAO = new EcfRecebimentoNaoFiscalPagamentoDAO();
recebimentoNaoFiscalPagamentoDAO.excluir(recebimentoNaoFiscalPagamento);
recebimentoNaoFiscalPagamentos = recebimentoNaoFiscalPagamentoDAO.listar();
Messages.addGlobalInfo("RecebimentoNaoFiscalPagamento excluida com sucesso");
} catch (RuntimeException erro) {
Messages.addGlobalInfo("Ocorreu um erro ao excluir o recebimentoNaoFiscalPagamento !");
erro.printStackTrace();
}
}
public void editar(ActionEvent evento) {
try {
recebimentoNaoFiscalPagamento = (EcfRecebimentoNaoFiscalPagamento) evento.getComponent().getAttributes().get("recebimentoNaoFiscalPagamentoSelecionada");
Messages.addGlobalInfo("RecebimentoNaoFiscalPagamento excluido com sucesso");
} catch (RuntimeException erro) {
Messages.addGlobalInfo("Ocorreu um erro ao excluir o recebimentoNaoFiscalPagamento !");
erro.printStackTrace();
}
}
}
| true
|
2920b96799256f873e4cc8672586047639a04153
|
Java
|
uslu16/Android-Basics-Nanodegree
|
/Project4/app/src/main/java/com/example/sabdar/project4/activity/PlaylistActivity.java
|
UTF-8
| 3,052
| 2.140625
| 2
|
[] |
no_license
|
package com.example.sabdar.project4.activity;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;
import com.example.sabdar.project4.R;
import com.example.sabdar.project4.adapters.AlbumAdapter;
import com.example.sabdar.project4.adapters.PlaylistAdapter;
import com.example.sabdar.project4.data.DataResource;
import com.example.sabdar.project4.pojo.Album;
import com.example.sabdar.project4.pojo.Playlist;
import java.util.ArrayList;
import butterknife.BindView;
import butterknife.ButterKnife;
public class PlaylistActivity extends AppCompatActivity {
//initialize and refer Artist Grid View
@BindView(R.id.playlistList)
ListView playlistList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_playlist);
ButterKnife.bind(this);
//initialize Playlist, Artist Names from String Array
String[] mPlayListNames = getResources().getStringArray(R.array.genreList);
String[] mArtistNames = getResources().getStringArray(R.array.artistList);
ArrayList<Playlist> mPlaylists = new ArrayList<>();
mPlaylists.add(new Playlist(mPlayListNames[0], DataResource.albumImages[0], 12, mArtistNames[0]));
mPlaylists.add(new Playlist(mPlayListNames[1], DataResource.albumImages[1], 7, mArtistNames[1]));
mPlaylists.add(new Playlist(mPlayListNames[2], DataResource.albumImages[2], 20, mArtistNames[2]));
mPlaylists.add(new Playlist(mPlayListNames[3], DataResource.albumImages[3], 2, mArtistNames[3]));
mPlaylists.add(new Playlist(mPlayListNames[4], DataResource.albumImages[4], 22, mArtistNames[4]));
mPlaylists.add(new Playlist(mPlayListNames[5], DataResource.albumImages[5], 42, mArtistNames[5]));
mPlaylists.add(new Playlist(mPlayListNames[6], DataResource.albumImages[6], 45, mArtistNames[6]));
mPlaylists.add(new Playlist(mPlayListNames[7], DataResource.albumImages[7], 65, mArtistNames[7]));
mPlaylists.add(new Playlist(mPlayListNames[8], DataResource.albumImages[8], 34, mArtistNames[8]));
mPlaylists.add(new Playlist(mPlayListNames[9], DataResource.albumImages[9], 11, mArtistNames[9]));
PlaylistAdapter playlistAdapter = new PlaylistAdapter(this, mPlaylists);
playlistList.setAdapter(playlistAdapter);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.home) {
Intent intent = new Intent(this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
return super.onOptionsItemSelected(item);
}
}
| true
|
3584f22ab1e067bd33ac2812ba3a401cf3ad65c6
|
Java
|
kaiser-developer/Desafio
|
/src/Main.java
|
UTF-8
| 956
| 3.125
| 3
|
[] |
no_license
|
public class Main {
public static void main(String[] args) {
DigitalHouse digitalHouse = new DigitalHouse();
digitalHouse.registrarProfessorTitular("Joao", "de Deus", 0, "Mestre");
digitalHouse.registrarProfessorAdjunto("Kaique", "de Souza", 1, 40);
digitalHouse.registrarCurso("Full Stack", 20001, 3);
digitalHouse.registrarCurso("Android", 20002, 2);
digitalHouse.matricularAluno("Carlos", "de Limeira", 3);
digitalHouse.matricularAluno("Kaique", "de Janeiro", 6);
digitalHouse.matricularAluno("Franck", "Aguiar", 7);
digitalHouse.matricularAluno("Pepe", "Moreno", 8);
digitalHouse.matricularAluno("Fabio", "Santos", 9);
digitalHouse.matricularAluno(3, 20001);
digitalHouse.matricularAluno(6, 20001);
digitalHouse.matricularAluno(7, 20002);
digitalHouse.matricularAluno(8, 20002);
digitalHouse.matricularAluno(9, 20002);
}
}
| true
|
cae2b691d383624178208779890c52ac6d3376a4
|
Java
|
HYKINGDOM/cuncurrency-red-packet
|
/src/main/java/com/redis/cuncurrency/red/packet/cuncurrencyredpacket/service/serviceImp/RedPacketRecordServiceImpl.java
|
UTF-8
| 1,134
| 2.09375
| 2
|
[] |
no_license
|
package com.redis.cuncurrency.red.packet.cuncurrencyredpacket.service.serviceImp;
import com.redis.cuncurrency.red.packet.cuncurrencyredpacket.domain.RedPacketRecord;
import com.redis.cuncurrency.red.packet.cuncurrencyredpacket.mapper.RedPacketRecordMapper;
import com.redis.cuncurrency.red.packet.cuncurrencyredpacket.service.RedPacketRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class RedPacketRecordServiceImpl implements RedPacketRecordService {
@Autowired
private RedPacketRecordMapper redPacketRecordMapper;
@Override
public List<RedPacketRecord> getRedPacketRecord(RedPacketRecord redPacketRecord) {
return redPacketRecordMapper.getRedPacketRedcord(redPacketRecord);
}
@Override
public Boolean createRedPacketRecord(RedPacketRecord redPacketRecord) {
try {
redPacketRecordMapper.createRedPacketRecord(redPacketRecord);
} catch (Exception e) {
e.getMessage();
return false;
}
return true;
}
}
| true
|
2ad71267d801e05da4fc0d168f9e896ab7bd94d0
|
Java
|
vialdevelopment/tori
|
/src/main/java/io/github/vialdevelopment/tori/mixin/mixins/MixinLightmapTextureManager.java
|
UTF-8
| 816
| 1.898438
| 2
|
[] |
no_license
|
package io.github.vialdevelopment.tori.mixin.mixins;
import io.github.vialdevelopment.tori.client.modules.render.BrightnessModule;
import net.minecraft.client.render.LightmapTextureManager;
import net.minecraft.client.util.math.Vector3f;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Redirect;
@Mixin(LightmapTextureManager.class)
public class MixinLightmapTextureManager {
@Redirect(method = "update", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/util/math/Vector3f;lerp(Lnet/minecraft/client/util/math/Vector3f;F)V", ordinal = 5))
private void lerpWrapper(Vector3f vector3f, Vector3f vector, float delta) {
vector3f.lerp(vector, BrightnessModule.INSTANCE.getState() ? 1000f : delta);
}
}
| true
|
60721e65b073df715b959f1e4a880681f86f0f5a
|
Java
|
kylepamintuan/CECS_277
|
/project1 - Review/src/project1/Main.java
|
UTF-8
| 4,969
| 3.953125
| 4
|
[] |
no_license
|
package project1;
/*
Kyle Pamintuan
Cecs 277
9/15/15
Project 1: ArrayList (Game of War)
*/
import java.util.*;
public class Main
{
public static void main(String[] args)
{
//Create ArrayLists
List<String> deck = new ArrayList<String>();
List<String> player1 = new ArrayList<String>();
List<String> player2 = new ArrayList<String>();
List<String> pile = new ArrayList<String>(); //Array for cards at War
//Create Deck
String[] suit = {"Clubs", "Diamonds", "Hearts", "Spades"};
for(int i = 0; i < 4; i++)
{
for(int j = 2; j <= 10; j++)
{
deck.add(j + " of " + suit[i]);
}
deck.add("Jack of " + suit[i]);
deck.add("Queen of " + suit[i]);
deck.add("King of " + suit[i]);
deck.add("Ace of " + suit[i]);
}
//Shuffle Deck
Collections.shuffle(deck);
//Split Deck
for(int i = 0; i< 26;i++)
{
player1.add(deck.get(i));
}
for(int i = 26; i < 52; i++)
{
player2.add(deck.get(i));
}
//Begin Game
System.out.println("========================= Game Of War Begins! =========================");
System.out.println();
while (true)
{
char[] rank = new char[3]; //Array to store ranks (the first character of every card)
int[] value = new int[14]; //Array to give all ranks a value
int counter = 0;//This counts cards being moved to pile
for(int i = 1; i <= 26; i = i + 4)
{
rank[1] = player1.get(0).charAt(0);
rank[2] = player2.get(0).charAt(0);
for (int j = 1; j <= 2; j++)
{
if(rank[j] == 'J')
{
value[j] = 10;
}
else if(rank[j] == 'Q')
{
value[j] = 11;
}
else if(rank[j] == 'K')
{
value[j] = 12;
}
else if(rank[j] == 'A')
{
value[j] = 13;
}
else
{
value[j] = Character.getNumericValue(rank[j]) - 1;
}
}
//Prints both players' card at play
System.out.println("Player 1 plays " + player1.get(0));
System.out.println("Player 2 plays " + player2.get(0));
//Announces winner of a Round
//Gives all appropriate cards to the winner and adds them to the bottom of the winner's deck
if(value[1] > value[2])
{
System.out.println("Player 1 Wins the Round!");
System.out.println();
player1.add(player1.get(0));
player1.add(player2.get(0));
player1.remove(0);
player2.remove(0);
if(i != 1) //Checks for a War
{
for(int j = 0; j < counter; j++)
{
player1.add(pile.get(0));
pile.remove(0);
}
}
break;//Ends the round
}
else if(value[1] < value[2])
{
System.out.println("Player 2 Wins the Round!");
System.out.println();
player2.add(player2.get(0));
player2.add(player1.get(0));
player2.remove(0);
player1.remove(0);
if(i != 1) //Checks for a War
{
for(int j = 0; j < counter; j++)
{
player2.add(pile.get(0));
pile.remove(0);
}
}
break; //Ends the round
}
//If both players' cards are equal ranks, a War begins!
else
{
System.out.println("----------------WAR!---------------");
//Checks if both players have only one card left. If not, continue the war.
if(player1.size() != 1 && player2.size() != 1)
{
pile.add(player1.get(0));
player1.remove(0);
counter++;
pile.add(player2.get(0));
player2.remove(0);
counter++;
}
for(int j = 0; j < 3; j++)
{
//Checks if both players have only one card left. If so, the war will not continue.
if(player1.size() == 1 || player2.size() == 1)
{
break;
}
//Each player places three faced-down cards with the name "xx"
System.out.println("Player 1 plays xx");
System.out.println("Player 2 plays xx");
pile.add(player1.get(0));
player1.remove(0);
counter++;
pile.add(player2.get(0));
player2.remove(0);
counter++;
}
}
}
//End Game and Announce Winner
if(player2.isEmpty())
{
System.out.println("Game Over");
System.out.println();
System.out.println("****** PLAYER 1 WINS THE GAME! *****");
break;
}
else if(player1.isEmpty())
{
System.out.println("Game Over");
System.out.println();
System.out.println("****** PLAYER 2 WINS THE GAME! *****");
break;
}
}
}
}
| true
|
0f07d94a8d749bb9f178da0e6c4e6a5e9dbb6b63
|
Java
|
hundredin/spring-multi-module-boilerplate
|
/common/src/main/java/com.spring.boilerplate.common/dao/hibernate/LinkRepositoryImpl.java
|
UTF-8
| 2,097
| 2.28125
| 2
|
[] |
no_license
|
package com.spring.boilerplate.common.dao.hibernate;
import com.spring.boilerplate.common.dao.GenericRepository;
import com.spring.boilerplate.common.dao.LinkRepository;
import com.spring.boilerplate.common.domain.Link;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.criteria.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@Repository("linkRepository")
@Transactional
public class LinkRepositoryImpl extends GenericRepository<Link> implements LinkRepository {
public LinkRepositoryImpl() {
super(Link.class);
}
@Override
public List<Link> findByDate(Date fromDate, Date toDate) {
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<Link> query = builder.createQuery(Link.class);
Root<Link> root = query.from(Link.class);
query.where(builder.between(root.get("createdAt"), fromDate, toDate));
return entityManager.createQuery(query)
.getResultList();
}
@Override
public List<Link> findBiggerThan(Integer like, Integer view) {
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<Link> query = builder.createQuery(Link.class);
Root<Link> root = query.from(Link.class);
List<Predicate> predicates = new ArrayList<>();
predicates.add(builder.gt(root.get("like"), like));
predicates.add(builder.gt(root.get("view"), view));
query.where(predicates.toArray(new Predicate[predicates.size()]));
return entityManager.createQuery(query)
.getResultList();
}
@Override
public Link findByHashId(String hashId) {
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<Link> query = builder.createQuery(Link.class);
Root<Link> root = query.from(Link.class);
query.where(builder.equal(root.get("hashId"), hashId));
return entityManager.createQuery(query).getSingleResult();
}
}
| true
|
9e99dbc956aa545c7e34900c8783df65515dac95
|
Java
|
jay-from-future/InformationSystem
|
/src/main/java/com/railwaycompany/persistence/dao/interfaces/UserDao.java
|
UTF-8
| 486
| 2.515625
| 3
|
[] |
no_license
|
package com.railwaycompany.persistence.dao.interfaces;
import com.railwaycompany.persistence.entities.User;
/**
* GenericDAO<User> interface for work with User entities.
*/
public interface UserDao extends GenericDAO<User> {
/**
* Find user by login and password.
*
* @param login - User login
* @return User with this login and password or null if user with this parameters
* does not exists in data source.
*/
User findUser(String login);
}
| true
|
f3143eeb631c22407add96567f0a43dbe747903d
|
Java
|
RunAsOnehhb/assess
|
/src/main/java/com/assess/intern/Continue.java
|
UTF-8
| 1,729
| 3.8125
| 4
|
[] |
no_license
|
package com.assess.intern;
/**
* @Author: RunAsOne
* @Date: 2020/11/23 11:04
*/
import java.util.ArrayList;
import java.util.List;
import java.util.TreeSet;
/**
* 给定一个未排序的整数数组 nums ,找出数字连续的最长序列(不要求序列元素在原数组中连续)的长度。
* <p>
* 进阶:你可以设计并实现时间复杂度为 O(n) 的解决方案吗?
* <p>
* 示例 1:
* 输入:nums = [100,4,200,1,3,2]
* 输出:4
* 解释:最长数字连续序列是 [1, 2, 3, 4]。它的长度为 4。
* <p>
* 示例 2:
* 输入:nums = [0,3,7,2,5,8,4,6,0,1]
* 输出:9
* <p>
* 提示:
* <p>
* 0 <= nums.length <= 10^4
* -10^9 <= nums[i] <= 10^9
*/
public class Continue {
public static int num(int[] nums) {
TreeSet<Integer> set = new TreeSet<>();
for (int num : nums) {
//TreeSet有序排放
set.add(num);
}
int length = 1;
TreeSet<Integer> numSet = new TreeSet<>();
for (int num : set) {
if (set.contains(num + 1)) {
length = length + 1;
} else {
//如果set中不包含num+1 说明他已经到尽头了 重新一个长度来计算
numSet.add(length);
length = 1;
}
}
//把按顺序排的set转化为list
List<Integer> list = new ArrayList<>(numSet);
if (list.isEmpty()) {
return 0;
}
//因为treeSet按顺序排的所以最后一位就是最大值
return list.get(list.size() - 1);
}
public static void main(String[] args) {
int[] nums = new int[]{0,-1};
System.out.println(num(nums));
}
}
| true
|
95efb05b06312359a1deb2f6cac5f5c12a9ff689
|
Java
|
iantal/AndroidPermissions
|
/apks/playstore_apps/com_spotify_music/source/com/fasterxml/jackson/databind/ser/std/ClassSerializer.java
|
UTF-8
| 488
| 2.09375
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.fasterxml.jackson.databind.ser.std;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
public class ClassSerializer
extends StdScalarSerializer<Class<?>>
{
public ClassSerializer()
{
super(Class.class, false);
}
public void serialize(Class<?> paramClass, JsonGenerator paramJsonGenerator, SerializerProvider paramSerializerProvider)
{
paramJsonGenerator.writeString(paramClass.getName());
}
}
| true
|
7129a77671d6764551fa53ab15f885eaa06de7dc
|
Java
|
hdulqs/NC65_SCM_SO
|
/salebusirule/src/client/nc/ui/so/tranmatrel/action/TranMatRelSaveAction.java
|
GB18030
| 4,286
| 2.03125
| 2
|
[] |
no_license
|
package nc.ui.so.tranmatrel.action;
import java.awt.event.ActionEvent;
import nc.bs.framework.common.NCLocator;
import nc.itf.so.tranmatrel.ITranMatRelMaintain;
import nc.ui.pub.beans.MessageDialog;
import nc.ui.pubapp.uif2app.actions.SaveAction;
import nc.ui.pubapp.uif2app.model.BillManageModel;
import nc.ui.so.tranmatrel.rule.BillDataValidateRule;
import nc.ui.so.tranmatrel.view.CardForm;
import nc.ui.uif2.UIState;
import nc.ui.uif2.model.HierachicalDataAppModel;
import nc.vo.pub.BusinessException;
import nc.vo.pubapp.pattern.exception.ExceptionUtils;
import nc.vo.pubapp.pattern.model.transfer.bill.ClientBillCombinServer;
import nc.vo.pubapp.pattern.model.transfer.bill.ClientBillToServer;
import nc.vo.so.tranmatrel.entity.TranMatRelVO;
import nc.vo.trade.checkrule.VOChecker;
@SuppressWarnings("serial")
public class TranMatRelSaveAction extends SaveAction {
private CardForm view;
public CardForm getView() {
return this.view;
}
public void setView(CardForm view) {
this.view = view;
}
@Override
public void doAction(ActionEvent e) throws Exception {
this.view.getBillCardPanel().stopEditing();
if (VOChecker.isEmpty(this.getModel().getContext().getPk_org())) {
MessageDialog.showWarningDlg(this.view, null, nc.vo.ml.NCLangRes4VoTransl.getNCLangRes().getStrByID("4006007_0","04006007-0001")/*@res "ѡ֯"*/);
return;
}
Object value = this.getEditor().getValue();
this.view.validateValue();
this.validate(value);
if (this.getModel().getUiState() == UIState.ADD) {
this.insertBill(value);
this.getModel().setUiState(UIState.NOT_EDIT);
if (this.getModel() instanceof HierachicalDataAppModel) {
((HierachicalDataAppModel) this.getModel()).setSelectedData(value);
// ˳ɵ
}
}
else if (this.getModel().getUiState() == UIState.EDIT) {
this.updateBill(value);
this.getModel().setUiState(UIState.NOT_EDIT);
}
this.showSuccessInfo();
}
private void insertBill(Object value) {
TranMatRelVO bill =
new ClientBillToServer<TranMatRelVO>()
.constructInsert(new TranMatRelVO[] {
(TranMatRelVO) value
})[0];
BillDataValidateRule check = new BillDataValidateRule();
check.validate(bill);
TranMatRelVO retvo = null;
try {
ITranMatRelMaintain service =
NCLocator.getInstance().lookup(ITranMatRelMaintain.class);
retvo = service.insert(bill);
// ̨仯VOǰ̨ϲ
ClientBillCombinServer<TranMatRelVO> util =
new ClientBillCombinServer<TranMatRelVO>();
util.combine(new TranMatRelVO[] {
(TranMatRelVO) value
}, new TranMatRelVO[] {
retvo
});
}
catch (BusinessException e) {
ExceptionUtils.wrappException(e);
}
this.getModel().directlyAdd(value);
}
private void updateBill(Object value) {
int index = ((BillManageModel) this.getModel()).findBusinessData(value);
if (index == -1) {
ExceptionUtils.wrappBusinessException(nc.vo.ml.NCLangRes4VoTransl.getNCLangRes().getStrByID("4006007_0","04006007-0002")/*@res "ıʱȡǰ̨VO"*/);
}
TranMatRelVO data =
(TranMatRelVO) ((BillManageModel) this.getModel()).getData().get(index);
// dataΪǰmodelеݣvalueΪǰϵ
TranMatRelVO bill =
new ClientBillToServer<TranMatRelVO>().construct(new TranMatRelVO[] {
data
}, new TranMatRelVO[] {
(TranMatRelVO) value
})[0];
BillDataValidateRule check = new BillDataValidateRule();
check.validate(data);
TranMatRelVO ret = null;
ITranMatRelMaintain service =
NCLocator.getInstance().lookup(ITranMatRelMaintain.class);
try {
ret = service.update(bill);
// ̨仯VOǰ̨ϲ
ClientBillCombinServer<TranMatRelVO> util =
new ClientBillCombinServer<TranMatRelVO>();
util.combine(new TranMatRelVO[] {
(TranMatRelVO) value
}, new TranMatRelVO[] {
ret
});
}
catch (BusinessException e) {
ExceptionUtils.wrappException(e);
}
this.getModel().directlyUpdate(value);
}
}
| true
|
abcc320d2d4b98a79f7ba470caa0ef9d73070a90
|
Java
|
francoisOberholzer/corsh
|
/corsh/src/problems/cec2006/G03.java
|
UTF-8
| 1,479
| 2.9375
| 3
|
[] |
no_license
|
package problems.cec2006;
import java.util.Vector;
import problems.AbstractProblem;
//CEC 2006
public class G03 extends AbstractProblem {
private static int dimension = 10;
private static double[] domainsMin = new double[]{0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
private static double[] domainsMax = new double[]{1, 1, 1, 1, 1, 1, 1, 1, 1, 1};
private final double e = 0.0001;
public Double fitness(Vector<Double> x) {
double f1, f2 = Math.sqrt((double) dimension), f;
f1 = 1.0;
for(int i = 0; i < dimension; i++)
{
f1 = f2 * f1 * x.get(i);
}
f = -f1;
return f;
}
public double violation(Vector<Double> x) {
double h, h1;
h1 = 0.0;
for(int i = 0; i < dimension; i++)
{
h1 = h1 + x.get(i) * x.get(i);
}
h = h1 - 1.0;
if ((h - e) <= 0) {
h = 0;
}
return h;
}
public double[] violationArray(Vector<Double> x) {
double h, h1;
h1 = 0.0;
for(int i = 0; i < dimension; i++)
{
h1 = h1 + x.get(i) * x.get(i);
}
h = h1 - 1.0;
if ((h - e) <= 0) {
h = 0;
}
return new double[] {h};
}
public int getDimension() {
return dimension;
}
public double[] getDomainsMin() {
return domainsMin;
}
public double[] getDomainsMax() {
return domainsMax;
}
public String getName() {
return "G03_10D";
}
}
| true
|
dd0ca56d24034979513ea0c01b406648557c4134
|
Java
|
SXiang/JUnitWebTest
|
/selenium-wd/tests/surveyor/regression/source/ObserverViewPageTest2.java
|
UTF-8
| 14,352
| 1.976563
| 2
|
[] |
no_license
|
package surveyor.regression.source;
import static org.junit.Assert.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;
import common.source.Log;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.runner.RunWith;
import org.junit.Test;
import org.openqa.selenium.support.PageFactory;
import surveyor.scommon.actions.DriverViewPageActions;
import surveyor.scommon.actions.LoginPageActions;
import surveyor.scommon.source.DriverViewPage;
import surveyor.scommon.source.LoginPage;
import surveyor.scommon.source.ManageCustomersPage;
import surveyor.scommon.source.SurveyorTestRunner;
import surveyor.scommon.actions.ObserverViewPageActions;
import surveyor.scommon.source.ObserverViewPage;
import surveyor.scommon.source.PageObjectFactory;
import surveyor.scommon.source.SurveyorConstants.LicensedFeatures;
/*
* **** NOTES ****:
* 1. Action based tests that work on MapView (Survey, Observer, Driver) can derive from BaseMapViewTest.
* 2. If any of the tests do NOT use TestEnvironment actions for starting Analyzer and simulator then
* they should follow this convention to start simulator:
* Mark the test as TC*_SimulatorTest_* and it will be detected as Simulator based test and will trigger
* installation of Simulator pre-requisites before running the test.
*
*/
@RunWith(SurveyorTestRunner.class)
public class ObserverViewPageTest2 extends BaseMapViewTest {
// Change this: When test defaulted to Analyzer 1.
private DriverViewPageActions driverViewPageAction;
private ArrayList<ObserverViewPageActions> observerViewPageActionList = new ArrayList<ObserverViewPageActions>();
private ArrayList<ObserverViewPage> observerViewPageList = new ArrayList<ObserverViewPage>();
private DriverViewPage driverViewPage;
private static ManageCustomersPage manageCustomersPage;
private static Map<String, String> testAccount;
public ObserverViewPageTest2() throws IOException {
super();
}
@BeforeClass
public static void beforeTestClass() {
initializeTestObjects();
}
@Before
public void beforeTestMethod() {
try {
initializeTestObjects();
initializePageObjects();
initializePageActionsList();
initializeBasePageActions();
initializeObserverViewPageActionList();
driverViewPageAction = new DriverViewPageActions(getDriver(), getBaseURL(), getTestSetup());
if(testAccount == null){
testAccount = createTestAccount("ObserverViewTest2");
} else {
getLoginPage().open();
getLoginPage().loginNormalAs(getTestSetup().getLoginUser(), getTestSetup().getLoginPwd());
manageCustomersPage.open();
manageCustomersPage.editAndSelectLicensedFeatures(testAccount.get("customerName"), LicensedFeatures.values());
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void initializePageObjects() {
PageObjectFactory pageObjectFactory = new PageObjectFactory();
driverViewPage = pageObjectFactory.getDriverViewPage();
PageFactory.initElements(getDriver(), driverViewPage);
manageCustomersPage = pageObjectFactory.getManageCustomersPage();
PageFactory.initElements(getDriver(), manageCustomersPage);
LoginPage loginPage = pageObjectFactory.getLoginPage();
setLoginPage(loginPage);
PageFactory.initElements(getDriver(), loginPage);
}
private void initializeObserverViewPageActionList(){
for(int i = observerViewPageActionList.size(); i < driverList.size(); i++){
observerViewPageActionList.add(new ObserverViewPageActions(driverList.get(i), baseURLList.get(i), testSetupList.get(i)));
// Initialize page objects.
observerViewPageList.add(new ObserverViewPage(driverList.get(i), baseURLList.get(i), testSetupList.get(i)));
PageFactory.initElements(getDriver(), observerViewPageList.get(i));
}
}
private void startDrivingSurvey(Integer analyzerRowId, Integer surveyRowId, Integer idleTimeInSeconds) throws Exception {
startDrivingSurvey(driverViewPageAction, analyzerRowId, surveyRowId, idleTimeInSeconds);
}
private void startDrivingSurvey(String analyzerSerialNumber, String analyzerSharedkey, Integer analyzerRowId, Integer surveyRowId, Integer idleTimeInSeconds) throws Exception {
startDrivingSurvey(driverViewPageAction,analyzerSerialNumber, analyzerSharedkey, analyzerRowId, surveyRowId, idleTimeInSeconds);
}
private void stopSurveyAndAnalyzer() {
stopSurveyAndAnalyzer(driverViewPageAction);
}
private void loginAsObserver(int userRowID) throws Exception {
loginAsObserver(userRowID, 0);
}
private void loginAsObserver(int userRowID, int index) throws Exception {
loginPageActionList.get(index).open(EMPTY, NOTSET);
LoginPageActions.workingDataRow.set(null);
loginPageActionList.get(index).login(EMPTY, userRowID); /* Picarro Admin */
}
private void loginAsObserver(String usernameColonPassword, int index) throws Exception {
loginPageActionList.get(index).open(EMPTY, NOTSET);
LoginPageActions.workingDataRow.set(null);
loginPageActionList.get(index).login(usernameColonPassword,NOTSET) ;
}
private void loginAsDriver(int userRowID) throws Exception {
loginPageAction.get().open(EMPTY, NOTSET);
LoginPageActions.workingDataRow.set(null);
loginPageAction.get().login(EMPTY, userRowID); /* Picarro Admin */
}
private void loginAsDriver(String usernameColonPassword) throws Exception {
loginPageAction.get().open(EMPTY, NOTSET);
LoginPageActions.workingDataRow.set(null);
loginPageAction.get().login(usernameColonPassword,NOTSET) ;
}
/**
* Test Case ID: TC299_SimulatorTest_VerifyObserverViewInfo
* Test Description:
* - Log into UI as customer user (Utility Admin, Support, Driver)
* - On Home Page, click on Surveyors
* - Click on Online link
* Result:
* - User is navigated to Dashboard
* - User is taken to list of Surveyors for that customer
* - User is navigated to Observer View
* - Lag time between Driver and Observer view to display survey data should not be higher than 8 sec
* - Survey information till the current time should be displayed
*/
@Test /*Lack of verification of 'Lag time between Driver and Observer view to display survey data should not be higher than 8 sec'*/
public void TC299_VerifyObserverViewInfo() throws Exception{
Log.info("\nTestcase - TC299_SimulatorTest_VerifyObserverViewInfo\n");
loginAsDriver(USER_ROW_ID_PICARRO_DRIVER);
startDrivingSurvey(ANALYZER3_REPLAY_ROW_ID, SURVEY_STANDARD1_ROW_ID, ONE_SECOND);
loginAsObserver(USER_ROW_ID_PICARRO_DRIVER);
String analyzer = getTestEnvironmentAction().getWorkingAnalyzerSerialNumber();
homePageActionList.get(0).clickOnFirstMatchingOnlineSurveyorLink(analyzer, NOTSET);
observerViewPageActionList.get(0).getObserverViewPage().waitForPageLoad();
observerViewPageActionList.get(0).waitForConnectionToComplete(EMPTY, NOTSET);
assertTrue(observerViewPageActionList.get(0).verifyObserverViewPageIsOpened(EMPTY, NOTSET));
stopSurveyAndAnalyzer();
}
/**
* Test Case ID: TC353_CurtainViewIsDisplayedAndUserIsAbleToFollowTheVehicle
* Test Description:Observer View - Curtain View is displayed and user is able to Follow the vehicle
* - Script:
* - On Home Page, click on Picarro Surveyors -> Online -> Curtain
* - Click on Return.
* - Turn Position OFF and click on Curtain
* - Click on Return
* Result:
* - Red color cursor will move along with car position and blue spikes are displayed
* - Cursor will stop moving but blue spikes will be displayed
* - User will be returned to Observer View page
*/
@Test /*TBD: verifySpikesAreDisplayed, verifyRedCursorIsMovingWithCarPosition*/
public void TC353_CurtainViewIsDisplayedAndUserIsAbleToFollowTheVehicle() throws Exception{
Log.info("\nTestcase - TC353_CurtainViewIsDisplayedAndUserIsAbleToFollowTheVehicle\n");
loginAsDriver(USER_ROW_ID_PICARRO_DRIVER);
startDrivingSurvey(ANALYZER3_REPLAY_ROW_ID, SURVEY_STANDARD1_ROW_ID, ONE_SECOND);
loginAsObserver(USER_ROW_ID_PICARRO_DRIVER);
String analyzer = getTestEnvironmentAction().getWorkingAnalyzerSerialNumber();
homePageActionList.get(0).clickOnFirstMatchingOnlineSurveyorLink(analyzer, NOTSET);
observerViewPageActionList.get(0).getObserverViewPage().waitForPageLoad();
observerViewPageActionList.get(0).waitForConnectionToComplete(EMPTY, NOTSET);
assertTrue(observerViewPageActionList.get(0).verifyObserverViewPageIsOpened(EMPTY, NOTSET));
observerViewPageActionList.get(0).showCurtainView(EMPTY, NOTSET);
// assertTrue(observerViewPageActionList.get(0).verifySpikesAreDisplayed(EMPTY, NOTSET));
// assertTrue(observerViewPageActionList.get(0).verifyRedCursorIsMovingWithCarPosition(EMPTY, NOTSET));
observerViewPageActionList.get(0).clickOnCurtainReturnButton(EMPTY, NOTSET);
observerViewPageActionList.get(0).clickOnPositionButton(EMPTY, NOTSET);
observerViewPageActionList.get(0).turnOffPosition(EMPTY, NOTSET);
observerViewPageActionList.get(0).showCurtainView(EMPTY, NOTSET);
// assertTrue(observerViewPageActionList.get(0).verifySpikesAreDisplayed(EMPTY, NOTSET));
// assertFalse(observerViewPageActionList.get(0).verifyRedCursorIsMovingWithCarPosition(EMPTY, NOTSET));
observerViewPageActionList.get(0).clickOnCurtainReturnButton(EMPTY, NOTSET);
stopSurveyAndAnalyzer();
}
/**
* Test Case ID: TC2133_CurtainViewIsNotAvailableWithoutLicense
* Test Description:Observer View - Curtain View is displayed and user is able to Follow the vehicle
* Script:
* - Log into UI
* - Click Online link for one of the customer's surveyors
* - Check bottom panel for Curtain View button
* Result:
* - User is navigated to Observer View for selected surveyor
* - Curtain View button should not be present
*/
@Test
public void TC2133_CurtainViewIsNotAvailableWithoutLicense() throws Exception{
Log.info("\nTestcase - TC2133_CurtainViewIsNotAvailableWithoutLicense\n");
String analyzerName = testAccount.get("analyzerName");
String analyzerSharedKey = testAccount.get("analyzerSharedKey");
String userName = testAccount.get("userName");
String userPassword = testAccount.get("userPassword");
String customerName = testAccount.get("customerName");
loginAsDriver(USER_ROW_ID_AUTOMATION_ADMIN);
manageCustomersPage.open();
manageCustomersPage.editAndUnSelectLicensedFeatures(customerName, LicensedFeatures.CURTAINVIEW);
loginAsDriver(userName+":"+userPassword);
loginAsObserver(userName+":"+userPassword, 0);
startDrivingSurvey(analyzerName, analyzerSharedKey, ANALYZER1_REPLAY_ROW_ID, SURVEY_STANDARD1_ROW_ID, ONE_SECOND);
homePageActionList.get(0).open(getLiveObservePath(), NOTSET);
observerViewPageActionList.get(0).waitForConnectionToComplete(EMPTY, NOTSET);
assertTrue(observerViewPageActionList.get(0).verifyObserverViewPageIsOpened(EMPTY, NOTSET));
assertFalse(observerViewPageActionList.get(0).getObserverViewPage().isCurtainButtonPresent());
stopSurveyAndAnalyzer();
}
/* * Test Case ID: TC2079_UserNotAbleToNavigateToObserverViewOnFleetMapScreenWithoutLicense
* Script:
* - Log in as utility admin or supervisor
* - On home page, click on Fleet map
* Results:
* - Fleet map link is present
* - Fleet Map page showing locations of customer's surveyor vehicles.
* - Online status is present for surveyor but it's not clickable (i.e. Suveyor name link is not click able). User can't navigate to observer view
*/
@Test
public void TC2079_UserNotAbleToNavigateToObserverViewOnFleetMapScreenWithoutLicense() throws Exception {
Log.info("\nRunning TC2079_UserNotAbleToNavigateToObserverViewOnFleetMapScreenWithoutLicense");
String analyzerName = testAccount.get("analyzerName");
String analyzerSharedKey = testAccount.get("analyzerSharedKey");
String userName = testAccount.get("userName");
String userPassword = testAccount.get("userPassword");
String customerName = testAccount.get("customerName");
loginAsDriver(USER_ROW_ID_AUTOMATION_ADMIN);
manageCustomersPage.open();
manageCustomersPage.editAndUnSelectLicensedFeatures(customerName, LicensedFeatures.FLEETMAPVIEW);
loginAsDriver(userName+":"+userPassword);
loginAsObserver(userName+":"+userPassword, 0);
startDrivingSurvey(analyzerName, analyzerSharedKey, ANALYZER1_REPLAY_ROW_ID, SURVEY_STANDARD1_ROW_ID, ONE_SECOND);
homePageActionList.get(0).open(getLiveObservePath(), NOTSET);
observerViewPageActionList.get(0).waitForConnectionToComplete(EMPTY, NOTSET);
assertTrue(observerViewPageActionList.get(0).verifyObserverViewPageIsOpened(EMPTY, NOTSET));
assertFalse(observerViewPageActionList.get(0).getObserverViewPage().verifyFleetMapLinkIsClickable());
stopSurveyAndAnalyzer();
}
/* * Test Case ID: TC2080_ObserverLinknotPresentWithoutLicense
* Script:
* - Log in as utility admin or supervisor
* - On home page, Surveyor section present on dashboard
* - Click on Online link present next to online Surveyor in Active Surveyors section
* - Log in as Picarro admin
* - Navigate to Manage Customer page and click on Edit button of above customer (Eg, CNP)
* - Disable "Observer View" privilege
* - Log in as utility admin or supervisor
* - On home page, Surveyor section present on dashboard
* Results:
* - Online link will be available for all online surveyors only. Offline surveyor will not have any clickable link
* - User is navigated to Observer view
* - Online status is present but its not clickable
*/
@Test
public void TC2080_ObserverLinknotPresentWithoutLicense() throws Exception {
Log.info("\nRunning TC2080_ObserverLinknotPresentWithoutLicense");
String analyzerName = testAccount.get("analyzerName");
String analyzerSharedKey = testAccount.get("analyzerSharedKey");
String userName = testAccount.get("userName");
String userPassword = testAccount.get("userPassword");
String customerName = testAccount.get("customerName");
loginAsDriver(USER_ROW_ID_AUTOMATION_ADMIN);
manageCustomersPage.open();
manageCustomersPage.editAndUnSelectLicensedFeatures(customerName, LicensedFeatures.OBSERVERVIEW);
loginAsDriver(userName+":"+userPassword);
loginAsObserver(userName+":"+userPassword, 0);
startDrivingSurvey(analyzerName, analyzerSharedKey, ANALYZER1_REPLAY_ROW_ID, SURVEY_STANDARD1_ROW_ID, ONE_SECOND);
homePageActionList.get(0).getHomePage().open();
assertFalse(homePageActionList.get(0).getHomePage().verifyLinkFirstOnlineSurveyorClickable());
stopSurveyAndAnalyzer();
}
}
| true
|
f3c3c7d1df0d153a71c98be06cdbdc64754b81ee
|
Java
|
fgsantana/peoplem-api
|
/src/test/java/com/github/fgsantana/peoplemapi/service/PersonServiceTest.java
|
UTF-8
| 1,633
| 2.171875
| 2
|
[] |
no_license
|
package com.github.fgsantana.peoplemapi.service;
import com.github.fgsantana.peoplemapi.dto.PersonDTO;
import com.github.fgsantana.peoplemapi.dto.ResponseMessage;
import com.github.fgsantana.peoplemapi.entity.Person;
import com.github.fgsantana.peoplemapi.exception.CPFConstraintViolationException;
import com.github.fgsantana.peoplemapi.repository.PersonRepository;
import com.github.fgsantana.peoplemapi.utils.PersonUtils;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;
import static com.github.fgsantana.peoplemapi.utils.PersonUtils.createFakeDTO;
import static com.github.fgsantana.peoplemapi.utils.PersonUtils.createFakeEntity;
import static org.hamcrest.Matchers.any;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
public class PersonServiceTest {
@Mock
PersonRepository repo;
@InjectMocks
PersonService personService;
@Test
void testGivenPersonDTOThenReturnSavedMessage() throws CPFConstraintViolationException {
PersonDTO personDTO = createFakeDTO();
Person expctdSavedPerson = createFakeEntity();
Mockito.when(repo.save(expctdSavedPerson)).thenReturn(expctdSavedPerson);
ResponseMessage expectedSuccessMessage = ResponseMessage.builder().message("Person with ID " + repo.save(expctdSavedPerson).getId() + " created").build();
ResponseMessage succesMessage = personService.createPerson(personDTO);
}
}
| true
|
584cc20c9d0937a79a69808ee94abd70f139d242
|
Java
|
daydayupforever/CoinExchange-Doc
|
/doc/08第八章_服务中台_财务系统的开发/源码/coin-finance/finance-service/src/main/java/com/bjsxt/service/CoinConfigService.java
|
UTF-8
| 532
| 1.921875
| 2
|
[] |
no_license
|
package com.bjsxt.service;
import com.bjsxt.domain.CoinConfig;
import com.baomidou.mybatisplus.extension.service.IService;
public interface CoinConfigService extends IService<CoinConfig> {
/**
* 通过币种的id 查询币种的配置信息
* @param coinId
* 币种的id
* @return
* 币种的配置信息
*/
CoinConfig findByCoinId(Long coinId);
/**
* 新增或修改币种配置
* @param coinConfig
* @return
*/
boolean updateOrSave(CoinConfig coinConfig);
}
| true
|
06e1025e42d83a41445e9faf8e54d01e3331ac0b
|
Java
|
AntenehAdmasu/CompetitiveProgrammingLabs
|
/Code Camp/PopularQuestions/LetterCombinationsOfPhoneNumber.java
|
UTF-8
| 1,772
| 3.3125
| 3
|
[] |
no_license
|
// Question link : https://leetcode.com/problems/letter-combinations-of-a-phone-number/
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class LetterCombinationsOfPhoneNumber {
public static void main(String[] args) {
System.out.println(new LetterCombinationsOfPhoneNumber().letterCombinations("23"));
}
public List<String> letterCombinations(String digits) {
HashMap<String, ArrayList<String>> numberLetterMap = new HashMap<>();
List<String> answer = new ArrayList<>();
if(digits.length() == 0) return answer;
int charCode = (97);
for (int i = 0; i <= 7; i++) {
int range = (i == 5 || i == 7) ? 4 : 3;
ArrayList<String> letters = new ArrayList<>();
int counter = 0;
String letter = "";
while (counter < range) {
letter = Character.toString((char) charCode++);
letters.add(letter);
counter++;
}
numberLetterMap.put("" + (i + 2), letters);
}
answer.add("");
for (int i = 0; i < digits.length() ; i++) {
answer = generateCombination(Character.toString(digits.charAt(i)), answer,numberLetterMap);
}
return answer;
}
public List<String> generateCombination(String number, List<String> currentCombination, HashMap<String, ArrayList<String>> numberLetterMap){
List<String> newCombination = new ArrayList<>();
for (String comb: currentCombination) {
for (String letter: numberLetterMap.get(number)) {
String newcomb = comb + letter;
newCombination.add(newcomb);
}
}
return newCombination;
}
}
| true
|
8600676af29887ec5c3e25c757d373d27de14574
|
Java
|
commercetools/commercetools-sdk-java-v2
|
/commercetools/commercetools-sdk-java-api/src/main/java-generated/com/commercetools/api/models/order/OrderAddReturnInfoAction.java
|
UTF-8
| 5,413
| 2.375
| 2
|
[
"Apache-2.0",
"GPL-2.0-only",
"EPL-2.0",
"CDDL-1.0",
"MIT",
"BSD-3-Clause",
"Classpath-exception-2.0"
] |
permissive
|
package com.commercetools.api.models.order;
import java.time.*;
import java.time.ZonedDateTime;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.databind.annotation.*;
import io.vrap.rmf.base.client.utils.Generated;
/**
* <p>Produces the Return Info Added Message.</p>
*
* <hr>
* Example to create an instance using the builder pattern
* <div class=code-example>
* <pre><code class='java'>
* OrderAddReturnInfoAction orderAddReturnInfoAction = OrderAddReturnInfoAction.builder()
* .plusItems(itemsBuilder -> itemsBuilder)
* .build()
* </code></pre>
* </div>
*/
@Generated(value = "io.vrap.rmf.codegen.rendering.CoreCodeGenerator", comments = "https://github.com/commercetools/rmf-codegen")
@JsonDeserialize(as = OrderAddReturnInfoActionImpl.class)
public interface OrderAddReturnInfoAction extends OrderUpdateAction {
/**
* discriminator value for OrderAddReturnInfoAction
*/
String ADD_RETURN_INFO = "addReturnInfo";
/**
* <p>Value to set.</p>
* @return returnTrackingId
*/
@JsonProperty("returnTrackingId")
public String getReturnTrackingId();
/**
* <p>Items to be returned. Must not be empty.</p>
* @return items
*/
@NotNull
@Valid
@JsonProperty("items")
public List<ReturnItemDraft> getItems();
/**
* <p>Value to set. If not set, it defaults to the current date and time.</p>
* @return returnDate
*/
@JsonProperty("returnDate")
public ZonedDateTime getReturnDate();
/**
* <p>Value to set.</p>
* @param returnTrackingId value to be set
*/
public void setReturnTrackingId(final String returnTrackingId);
/**
* <p>Items to be returned. Must not be empty.</p>
* @param items values to be set
*/
@JsonIgnore
public void setItems(final ReturnItemDraft... items);
/**
* <p>Items to be returned. Must not be empty.</p>
* @param items values to be set
*/
public void setItems(final List<ReturnItemDraft> items);
/**
* <p>Value to set. If not set, it defaults to the current date and time.</p>
* @param returnDate value to be set
*/
public void setReturnDate(final ZonedDateTime returnDate);
/**
* factory method
* @return instance of OrderAddReturnInfoAction
*/
public static OrderAddReturnInfoAction of() {
return new OrderAddReturnInfoActionImpl();
}
/**
* factory method to create a shallow copy OrderAddReturnInfoAction
* @param template instance to be copied
* @return copy instance
*/
public static OrderAddReturnInfoAction of(final OrderAddReturnInfoAction template) {
OrderAddReturnInfoActionImpl instance = new OrderAddReturnInfoActionImpl();
instance.setReturnTrackingId(template.getReturnTrackingId());
instance.setItems(template.getItems());
instance.setReturnDate(template.getReturnDate());
return instance;
}
/**
* factory method to create a deep copy of OrderAddReturnInfoAction
* @param template instance to be copied
* @return copy instance
*/
@Nullable
public static OrderAddReturnInfoAction deepCopy(@Nullable final OrderAddReturnInfoAction template) {
if (template == null) {
return null;
}
OrderAddReturnInfoActionImpl instance = new OrderAddReturnInfoActionImpl();
instance.setReturnTrackingId(template.getReturnTrackingId());
instance.setItems(Optional.ofNullable(template.getItems())
.map(t -> t.stream()
.map(com.commercetools.api.models.order.ReturnItemDraft::deepCopy)
.collect(Collectors.toList()))
.orElse(null));
instance.setReturnDate(template.getReturnDate());
return instance;
}
/**
* builder factory method for OrderAddReturnInfoAction
* @return builder
*/
public static OrderAddReturnInfoActionBuilder builder() {
return OrderAddReturnInfoActionBuilder.of();
}
/**
* create builder for OrderAddReturnInfoAction instance
* @param template instance with prefilled values for the builder
* @return builder
*/
public static OrderAddReturnInfoActionBuilder builder(final OrderAddReturnInfoAction template) {
return OrderAddReturnInfoActionBuilder.of(template);
}
/**
* accessor map function
* @param <T> mapped type
* @param helper function to map the object
* @return mapped value
*/
default <T> T withOrderAddReturnInfoAction(Function<OrderAddReturnInfoAction, T> helper) {
return helper.apply(this);
}
/**
* gives a TypeReference for usage with Jackson DataBind
* @return TypeReference
*/
public static com.fasterxml.jackson.core.type.TypeReference<OrderAddReturnInfoAction> typeReference() {
return new com.fasterxml.jackson.core.type.TypeReference<OrderAddReturnInfoAction>() {
@Override
public String toString() {
return "TypeReference<OrderAddReturnInfoAction>";
}
};
}
}
| true
|
fd8538f720ff8b3fc1e3de5a76907fb10d5627e4
|
Java
|
LeReunionais/integrator
|
/src/main/java/interfaces/Requester.java
|
UTF-8
| 2,721
| 2.421875
| 2
|
[] |
no_license
|
package interfaces;
import com.google.gson.Gson;
import entities.Particle;
import entities.Work;
import entities.WorkResult;
import org.zeromq.ZContext;
import org.zeromq.ZMQ;
import registry.Registry;
import registry.Service;
import updator.SimpleUpdator;
import java.util.UUID;
/**
* Created on 4/23/16.
*/
public class Requester {
private final Gson gson = new Gson();
private final Registry registry;
public Requester(Registry registry) {
this.registry = registry;
}
private class ReadyRequest {
private final String jsonrpc = "2.0";
private final String method = "ready";
private final String params;
private final UUID id;
ReadyRequest(String name) {
this.params = name;
this.id = UUID.randomUUID();
}
}
private class ReadyReply {
private final String jsonrpc = "2.0";
private Work result;
private UUID id;
Work getWork() {
return result;
}
}
private class ResultRequest {
private final String jsonrpc = "2.0";
private final String method = "result";
private final WorkResult params;
private final UUID id;
ResultRequest(WorkResult params, UUID id) {
this.params = params;
this.id = id;
}
}
public void run() {
ZContext context = new ZContext();
String ready_json = gson.toJson(new ReadyRequest("George"));
SimpleUpdator simpleUpdator = new SimpleUpdator();
ZMQ.Socket socket = context.createSocket(ZMQ.REQ);
Service integrator = registry.whereis("integrator");
socket.connect(integrator.getEndpoint());
while (true) {
System.out.println("Sending message");
socket.send(ready_json, 0);
System.out.println("Waiting for reply");
String message = socket.recvStr(0);
System.out.println(message);
ReadyReply reply_message = gson.fromJson(message, ReadyReply.class);
System.out.println(reply_message);
Particle particle_updated = simpleUpdator.update(reply_message.getWork());
WorkResult params = new WorkResult(particle_updated, reply_message.getWork().getWorkId());
ResultRequest result_request = new ResultRequest(params, reply_message.id);
String result_request_json = gson.toJson(result_request);
System.out.println("Sending result");
socket.send(result_request_json, 0);
System.out.println("Waiting result");
String result_reply = socket.recvStr(0);
System.out.println(result_reply);
}
}
}
| true
|
5738612bce2e0ac46b2fc140e6533e3ba64cd40a
|
Java
|
ebonycross/Sample-Programs
|
/Java/ECross_CS204_Assignment3/src/ServiceOrdersManagerInterface.java
|
UTF-8
| 3,836
| 3.46875
| 3
|
[] |
no_license
|
import java.util.ListIterator;
import java.util.Vector;
/**
* This class that holds all the service order objects in the ordered linked-lists that
* keep the objects ordered based on a particular key. This class adds to the data structures
* (Start Service) and deletes from the data structures (Finish Service).
* It also returns the contents of the ordered linked lists.
*
* Used for Assignment 2 Spring 2015
*
* @author original version by Professor Karchner
*
*/
public interface ServiceOrdersManagerInterface{
/**
* Creates a Service Order object and adds it to the ordered linked lists
* @param orderNum service order number
* @param owner name of owner
* @param make make of car
* @param model model of car
* @param oilChange oil check
* @param safetyCheck safety check
* @param emissionsCheck emission test check
* @return true if added, and false if order not added
* @throws ServiceException if Service Order Number is already in use
*/
public boolean startService(int orderNum, String owner, String make, String model, String oilChange, String safetyCheck, String emissionsCheck) throws ServiceException;
/**
* Adds a Service Order to the ordered linked lists. This is for testing purposes.
* Not intended to be used by the user
* @param order a Service Order to be added to the ordered linked lists.
* @return true if the startService was successful
* @throws ServiceException if Service Order Number is already in use
*/
public boolean startService(ServiceOrder order) throws ServiceException;
/**
* Removes the Service Order from the ordered linked lists
* @param orderNum Service Order Number
* @return true if the finishService is successful
* @throws ServiceException if the Service Order Number is not found
*/
public boolean finishService(int orderNum) throws ServiceException;
/**
* Returns a two dimensional array of Strings to populate a JTable
* @param key, how service orders are to be ordered 1 = service order number, 2 = owner name (last, first),
* 3 = model
* @return a two dimensional array of Strings to populate a JTable
* order for key 1 = order num, owner, make, model, oilChange, safetyCheck, emissionsCheck
* order for key 2 = owner, order num, make, model, oilChange, safetyCheck, emissionsCheck
* order for key 3 = model, owner, make, order num, oilChange, safetyCheck, emissionsCheck
*/
public String[][] listByKeyTable(int key);
/**
* Returns a Vector of Strings to populate a JList
* @param key how service orders are to be ordered 1 = service order number, 2 = owner name (last, first),
* 3 = model
* @return a Vector of Strings to populate a JList
* order for key 1 = order num, owner, make, model, oilChange, safetyCheck, emissionsCheck
* order for key 2 = owner, order num, make, model, oilChange, safetyCheck, emissionsCheck
* order for key 3 = model, owner, make, order num, oilChange, safetyCheck, emissionsCheck
*/
public Vector<String> listByKeyVector(int key);
/**
* Returns the reference to the order number if found or null if not found
* @param orderNum the order number to look for
* @return the reference to the service order object or null if not found
*/
public ServiceOrder findOrderNum(int orderNum);
/**
* Returns a string with all the current Service Orders in the following format:
*
* Line Information
* 1 Order # (integer)
* 2 Owner (last name, first name) (String)
* 3 make (String)
* 4 model (String)
* 5 oilChange (String) either "yes" or "no"
* 6 safetyCheck (String) either "yes" or "no"
* 7 emissionsCheck (String) either "yes" or "no"
* ** No blank lines between Service Orders
* @return a String that can be used with a PrintWriter object to write to a file.
*/
public String toString();
}
| true
|
97ced951cc85c83f4c8040d499fca82fa73276f2
|
Java
|
mauriciocarvalho51/Biblioteca_livros
|
/Crud_biblioteca_pessoal_versao01/src/dao/BibliotecaDAO.java
|
MacCentralEurope
| 4,368
| 3
| 3
|
[] |
no_license
|
package dao;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import pojo.Escritor;
import pojo.Livro;
public class BibliotecaDAO {
public Escritor findEscritorByNome(String name) {
Escritor escritor = null;
String cmd = "select * from autor where nome= ?";
Connection db = null;
PreparedStatement st = null;
ResultSet rs = null;
try {
Properties props = new Properties();
props.load(new FileInputStream("CRUD.properties"));
String url = props.getProperty("url");
db = DriverManager.getConnection(url, props);
st = db.prepareStatement(cmd);
st.setString(2, name);
rs = st.executeQuery();
while (rs.next()) {
int codautor = rs.getInt(1);
String nome = rs.getString(2);
String nacionalidade = rs.getString(3);
escritor = new Escritor(codautor, nome, nacionalidade);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (rs != null) {
rs.close();
}
if (st != null) {
st.close();
}
if (db != null) {
db.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return escritor;
}
public void insertEscritor(Escritor escritor) {
String cmd = "insert into autor(nome, nacionalidade) values (?, ?)";
Connection db = null;
PreparedStatement st = null;
try {
// abrir conexo
Properties props = new Properties();
props.load(new FileInputStream("CRUD.properties"));
String url = props.getProperty("url");
db = DriverManager.getConnection(url, props);
st = db.prepareStatement(cmd);
st.setString(1, escritor.getNome());
st.setString(2, escritor.getNacionalidade());
int r = st.executeUpdate();
if (r != 1) {
throw new RuntimeException("Erro ao inserir Autor!");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (st != null) {
st.close();
}
if (db != null) {
db.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
public List<Escritor> findEscritorByNacionalidade(String pais) {
String cmd = "select * from autor where nacionalidade= ?";
List<Escritor> autores = new ArrayList<Escritor>();
Connection db = null;
PreparedStatement st = null;
ResultSet rs = null;
try {
Properties props = new Properties();
props.load(new FileInputStream("CRUD.properties"));
String url = props.getProperty("url");
db = DriverManager.getConnection(url, props);
st = db.prepareStatement(cmd);
st.setString(1, pais);
rs = st.executeQuery();
while (rs.next()) {
int codautor = rs.getInt(1);
String nome = rs.getString(2);
String nacionalidade = rs.getString(3);
autores.add(new Escritor(codautor, nome, nacionalidade));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (rs != null) {
rs.close();
}
if (st != null) {
st.close();
}
if (db != null) {
db.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return autores;
}
public List<Livro> findLivros() {
//String cmd = "select * from livro";
String cmd = "select * from livro, autor where livro.cod_autor = autor.cod_autor";
List<Livro> livros = new ArrayList<Livro>();
Connection db = null;
PreparedStatement st = null;
ResultSet rs = null;
try {
Properties props = new Properties();
props.load(new FileInputStream("CRUD.properties"));
String url = props.getProperty("url");
db = DriverManager.getConnection(url, props);
st = db.prepareStatement(cmd);
//st.setString(1, pais);
rs = st.executeQuery();
while (rs.next()) {
int codlivro = rs.getInt(1);
String nome = rs.getString(2);
int codescritor = rs.getInt(3);
String escritor = rs.getString(5);
livros.add(new Livro(codlivro, nome, codescritor, escritor));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (rs != null) {
rs.close();
}
if (st != null) {
st.close();
}
if (db != null) {
db.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return livros;
}
}
| true
|
a893fd4979c257b096f1cd716721e3f6789d47a8
|
Java
|
will0815/pinot
|
/thirdeye/thirdeye-pinot/src/test/java/com/linkedin/thirdeye/tools/FetchAutoTuneResult.java
|
UTF-8
| 3,684
| 2.5
| 2
|
[
"Apache-2.0",
"BSD-3-Clause"
] |
permissive
|
package com.linkedin.thirdeye.tools;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class FetchAutoTuneResult {
private static final Logger LOG = LoggerFactory.getLogger(FetchAutoTuneResult.class);
private static final String CSVSUFFIX = ".csv";
private static final Integer DEFAULT_NEXPECTEDANOMALIES = 3;
/**
* Tool to fetch auto tune results using auto tune endpoint based on collection;
* evaluate alert filter using evaluation endpoint
* @param args
* args[0]: Type of AutoTune, default value is: AUTOTUNE
* args[1]: Start time of merged anomaly in milliseconds
* args[2]: End time of merged anomaly in milliseconds
* args[3]: Path to Persistence File
* args[4]: Collection Name
* args[6]: File directory (read and write file)
* args[7]: Holiday periods to remove from dataset. Holiday starts in format: milliseconds1,milliseconds2
* args[8]: Holiday periods to remove from dataset. Holiday ends in format: milliseconds1,milliseconds2
* @throws Exception
*/
public static void main(String[] args) throws Exception{
if(args.length < 8){
LOG.error("Error: Insufficient number of arguments", new IllegalArgumentException());
return;
}
String AUTOTUNE_TYPE = args[0];
Long STARTTIME = Long.valueOf(args[1]);
Long ENDTIME = Long.valueOf(args[2]);
String path2PersistenceFile = args[3];
String Collection = args[4];
String DIR_TO_FILE = args[5];
String holidayStarts = args[6];
String holidayEnds = args[7];
AutoTuneAlertFilterTool executor = new AutoTuneAlertFilterTool(new File(path2PersistenceFile));
List<Long> functionIds = executor.getAllFunctionIdsByCollection(Collection);
Map<String, String> outputMap = new HashMap<>();
for(Long functionId : functionIds){
StringBuilder outputVal = new StringBuilder();
// evaluate current alert filter
String origEvals = executor.evalAnomalyFunctionAlertFilterToEvalNode(functionId, STARTTIME, ENDTIME, holidayStarts, holidayEnds).toCSVString();
// evaluate labels, if has no labels, go to initiate alert filter, else go to tune alert filter
Long autotuneId;
Boolean isInitAutoTune = !executor.checkAnomaliesHasLabels(functionId, STARTTIME, ENDTIME, holidayStarts, holidayEnds);
if(isInitAutoTune){
autotuneId = Long.valueOf(executor.getInitAutoTuneByFunctionId(functionId, STARTTIME, ENDTIME, AUTOTUNE_TYPE, DEFAULT_NEXPECTEDANOMALIES, holidayStarts, holidayEnds));
} else{
// tune by functionId
autotuneId = Long.valueOf(executor.getTunedAlertFilterByFunctionId(functionId, STARTTIME, ENDTIME, AUTOTUNE_TYPE, holidayStarts, holidayEnds));
}
boolean isUpdated = autotuneId != -1;
String tunedEvals = "";
if(isUpdated){
// after tuning, evaluate tuned results by autotuneId
tunedEvals = executor.evalAutoTunedAlertFilterToEvalNode(autotuneId, STARTTIME, ENDTIME, holidayStarts, holidayEnds).toCSVString();
}
outputVal.append(origEvals)
.append(isUpdated)
.append(",")
.append(tunedEvals);
outputMap.put(String.valueOf(functionId), outputVal.toString());
}
// write to file
String header = "FunctionId" + "," + AutoTuneAlertFilterTool.EvaluationNode.getCSVSchema() + "," + "isModelUpdated" + "," +AutoTuneAlertFilterTool.EvaluationNode.getCSVSchema();
executor.writeMapToCSV(outputMap, DIR_TO_FILE + Collection + CSVSUFFIX, header);
LOG.info("Write evaluations to file: {}", DIR_TO_FILE + Collection + CSVSUFFIX);
}
}
| true
|
40dbfacd019bcde4301443d84f8e94c0e7067ae0
|
Java
|
Muhidin90/Demo
|
/app/src/main/java/com/example/demo/MainActivity.java
|
UTF-8
| 3,128
| 2.171875
| 2
|
[] |
no_license
|
package com.example.demo;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.example.demo.ui.login.LoginActivity;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
public class MainActivity extends AppCompatActivity {
EditText emailId, password;
Button btnSignUp;
TextView tvSignIn;
FirebaseAuth mFirebaseAuth;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mFirebaseAuth = FirebaseAuth.getInstance();
emailId = findViewById(R.id.editText);
password = findViewById(R.id.editText2);
btnSignUp = findViewById(R.id.button2);
tvSignIn = findViewById(R.id.textView);
btnSignUp.setOnClickListener(new View.onclickListner() {
public void onclick(View v) {
string email = emailId.getText().toString();
//this is test comment
string pwd = password.getText().toString();
if (email.isEmpty()) {
emailId.setError("Please anter email id ");
emailId.requestFocus();
} else if (pwd.isEmpty()) {
password.setError("Please enter your password");
password.requestFocus();
} else if (email.isEmpty() && pwd.isEmpty()) {
Toast.makeText(MainActivity.this, "Fields are empty", Toast.LENGTH_SHORT).show();
} else if ((!email.isEmpty() && pwd.isEmpyty())) {
mFirebaseAuth.createUserWithEmailAndPassword(email, pwd).addOnCompleteListener(MainActivity.this, new OnCompleteListener<com.google.firebase.auth.AuthResult>() {
@Override
public void onComplete(@NonNull Task<com.google.firebase.auth.AuthResult> task) {
if (!task.isSuccessful()) {
Toast.makeText(MainActivity.this, "Signup unsuccesssful, please try Again ", Toast.LENGTH_SHORT).show();
} else {
startActivity(new Intent(packageContext:
MainActivity.this, HomeActivity.class));
}
}
});
}
else{
Toast.makeText(MainActivity.this, "Errror occured!", Toast.LENGTH_SHORT).show();
}
}
});
tvSignIn.setOnContextClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
intent i = new Intent (createPackageContext:MainActivity.this, LoginActivity.class);
startActivities(i);
}
});
}
}
| true
|
48a228c5e8f1846776c3dbbc369a90b83ea95fe6
|
Java
|
tempbottle/xipki
|
/ca/ca-server/src/main/java/org/xipki/ca/server/Version.java
|
UTF-8
| 1,482
| 2.46875
| 2
|
[] |
no_license
|
/*
* Copyright (c) 2014 Lijun Liao
*
* TO-BE-DEFINE
*
*/
package org.xipki.ca.server;
import java.io.InputStream;
import java.util.jar.Manifest;
/**
* @author Lijun Liao
*/
final public class Version
{
public static String PRODUCT_NAME = "XiPKI";
public static void main(String []argv)
{
System.out.println(getVersion());
}
/**
* @return the Maven Version, SVN Revision and Build timestamp as a human-readable String.
*/
public static String getVersion()
{
StringBuilder version = new StringBuilder();
try
{
InputStream is = Version.class.getResourceAsStream("/MANIFEST.MF");
java.util.jar.Manifest man = new Manifest(is);
java.util.jar.Attributes jattr = man.getMainAttributes();
// Copyright
// Maven Version, SVN Revision, Build timestamp
version.append(jattr.getValue("Implementation-Copyright")).append("\n");
version.append("Version: ");
version.append(jattr.getValue("Implementation-Version")).append(" ");
version.append("Revision: ");
version.append(jattr.getValue("Implementation-Build")).append(" ");
version.append("Build at: ");
version.append(jattr.getValue("Implementation-Build-Timestamp")).append(" ");
}
catch (Exception e)
{
return PRODUCT_NAME;
}
return version.toString();
}
}
| true
|
f11024d19f50ba59143eb5b3d9ec589c337394d5
|
Java
|
mquasten/portfolio
|
/portfolio.domain/src/main/java/de/mq/portfolio/exchangerate/ExchangeRate.java
|
UTF-8
| 405
| 1.890625
| 2
|
[] |
no_license
|
package de.mq.portfolio.exchangerate;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map.Entry;
import de.mq.portfolio.gateway.Gateway;
import de.mq.portfolio.share.Data;
public interface ExchangeRate {
String source();
String target();
List<Data> rates();
void assign(final Collection<Data> rates);
Collection<Entry<Gateway, Date>> updates();
}
| true
|
47794d13d0572d36696a9227541a07c3af43234d
|
Java
|
HeydrichBeillschmidt/MxCompiler
|
/src/main/java/Mx/IR/Instruction/Alloca.java
|
UTF-8
| 1,250
| 2.703125
| 3
|
[] |
no_license
|
package Mx.IR.Instruction;
import Mx.IR.IRBlock;
import Mx.IR.IRVisitor;
import Mx.IR.Operand.Register;
import Mx.IR.TypeSystem.IRType;
import Mx.IR.TypeSystem.PointerType;
public class Alloca extends IRInst {
private final Register dst;
private final IRType allocType;
public Alloca(IRBlock block, Register dst, IRType allocType) {
super(block);
this.dst = dst;
this.allocType = allocType;
assert (new PointerType(allocType)).equals(dst.getType());
}
@Override
public Register getDst() {
return dst;
}
public IRType getAllocType() {
return allocType;
}
@Override
public boolean needWriteBack() {
return true;
}
@Override
public void actuallyWritten() {
dst.setDef(this);
}
@Override
public IRInst copyToBlock(IRBlock block) {
Alloca ans = new Alloca(block, dst.getCopy(), allocType);
ans.dst.setDef(ans);
return ans;
}
@Override
public String toString() {
return dst.toString() + " = alloca " + allocType.toString()
+ ", align " + allocType.size();
}
@Override
public void accept(IRVisitor visitor) {
visitor.visit(this);
}
}
| true
|
59d063675d6970345d741b513a524a43a42d398a
|
Java
|
ccf05017/til
|
/Backend/Spring/Java/toby/src/main/java/com/poppo/toby/services/UserServiceImpl.java
|
UTF-8
| 2,873
| 2.453125
| 2
|
[] |
no_license
|
package com.poppo.toby.services;
import com.poppo.toby.domain.Level;
import com.poppo.toby.domain.User;
import com.poppo.toby.userDao.UserDao;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import java.util.List;
public class UserServiceImpl implements UserService {
public static final int MIN_LOG_COUNT_FOR_SILVER = 50;
public static final int MIN_RECOMMEND_FOR_GOLD = 30;
private UserDao userDao;
private UserLevelUpgradePolicy userLevelUpgradePolicy;
private MailSender mailSender;
public UserServiceImpl(UserDao userDao, UserLevelUpgradePolicy userLevelUpgradePolicy, MailSender mailSender) {
this.userDao = userDao;
this.userLevelUpgradePolicy = userLevelUpgradePolicy;
this.mailSender = mailSender;
}
@Override
public void upgradeLevels() {
// Transaction과 관련된 코드는 모두 제거했다.
List<User> users = userDao.getAll();
for (User user : users) {
if (userLevelUpgradePolicy.canUpgradeLevel(user)) {
upgradeLevel(user);
}
}
}
@Override
public void add(User user) {
if (user.getLevel() == null) {
user.setLevel(Level.BASIC);
}
userDao.add(user);
}
protected void upgradeLevel(User user) {
userLevelUpgradePolicy.upgradeLevel(user);
userDao.update(user);
sendUpgradeEmail(user);
}
// 스프링이 제공하는 메일 추상화
private void sendUpgradeEmail(User user) {
SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
simpleMailMessage.setTo(user.getEmail());
simpleMailMessage.setFrom("tobyPractise@gmail.com");
simpleMailMessage.setSubject("Upgrade 안내");
simpleMailMessage.setText(user.getName() + "님의 등급이 " + user.getLevel().name() + " 으로 업그레이드 됐습니다.");
mailSender.send(simpleMailMessage);
}
// 가장 전형적인 자바 메일 발송 코드
// private void sendUpgradeEmail(User user) {
// Properties props = new Properties();
// props.put("mail.smtp.host", "mail.ksug.org");
// Session session = Session.getInstance(props);
//
// MimeMessage mimeMessage = new MimeMessage(session);
// try {
// mimeMessage.setFrom(new InternetAddress("admin@ksug.org"));
// mimeMessage.addRecipient(Message.RecipientType.TO,
// new InternetAddress(user.getEmail()));
// mimeMessage.setSubject("Upgrade 안내");
// mimeMessage.setText(user.getName() + "님의 등급이 " + user.getLevel().name() + " 으로 업그레이드 됐습니다.");
// Transport.send(mimeMessage);
// } catch (MessagingException e) {
// throw new RuntimeException(e);
// }
// }
}
| true
|
d589950b961e4243f09de322599cfccc83fa0bde
|
Java
|
yamyam-e/Study-at-KG-ITBank
|
/Spring_Works/Spring14_SMVC_Mybatis/src/main/java/spring/mvc/spring14/J04_Exception.java
|
UTF-8
| 1,508
| 2.84375
| 3
|
[] |
no_license
|
package spring.mvc.spring14;
import java.util.ArrayList;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class J04_Exception {
@RequestMapping(value="j04_exception", method=RequestMethod.GET)
public String go(){
return "j04_exc01_Home";
}
// 1. bean 활용 (예: classpath:/z04_exception/exception-context.xml)
// 스프링프레임워크에 예외처리를 감시하는 빈을 만드는 것
@RequestMapping("nullpointExc")
public void nullExc(){
ArrayList listc = null;
listc.add(10);
}
// 2. 메소드 직접 처리 방식
@RequestMapping("indexOutExc")
public void indexEx(){
int[] a = { 10, 20 };
a[3] = 30;
}
@ExceptionHandler(ArrayIndexOutOfBoundsException.class)
public String catchExc(ArrayIndexOutOfBoundsException e){
System.out.println("인덱스 예외 처리 메소드");
return "j04_exc03_indexOut";
}
// 3. 최상위 Exception 설정
@RequestMapping(value="j04_exception", method=RequestMethod.POST)
public String works(
@RequestParam(value="num1") Integer num1,
@RequestParam(value="num2") Integer num2
){
int res = num1 / num2;
return "j04_exception";
}
}
| true
|
82fefd5a83c69eaf5792c716e10b1e2877324ef4
|
Java
|
SlivkaEvgen/ServletsJSP
|
/src/main/java/org/homework/util/PropertiesLoader.java
|
UTF-8
| 1,078
| 2.71875
| 3
|
[] |
no_license
|
package org.homework.util;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.util.Properties;
public class PropertiesLoader implements Serializable {
private static final long serialVersionUID = 10000000007L;
private static final String PROPERTIES_FILE_NAME = "application.properties";
private static final Properties PROPERTIES;
static {
System.out.println("load properties");
PROPERTIES = new Properties();
try (InputStream is = getInputStream(PROPERTIES_FILE_NAME)) {
PROPERTIES.load(is);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
public static String getProperties(final String name) {
System.out.println(" property getProperties");
return PROPERTIES.getProperty(name);
}
public static InputStream getInputStream(final String fileName) {
System.out.println(" property getInputStream");
return PropertiesLoader.class.getClassLoader().getResourceAsStream(fileName);
}
}
| true
|
3f3c9d6d37383ad6c1f9f3c7403fab6ca5242be1
|
Java
|
MastrottiSoftware/Google-jam-2019
|
/Qualification/Foregone_solution.java
|
UTF-8
| 721
| 3.09375
| 3
|
[] |
no_license
|
import java.util.*;
import java.io.*;
public class Solution{
public static void main(String[] args) {
Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
int T = in.nextInt();
String num;
String A;
int B;
for(int i=0; i<T; i++){
B = 0;
num = in.next();
char[] myChar = num.toCharArray();
for(int j=0; j<myChar.length; j++){
if(myChar[j] == '4'){
myChar[j] = '3';
int preB = 1;
for(int k=0; k<myChar.length-(j+1); k++){
preB = preB*10;
}
B = B+preB;
}
}
A = new String(myChar);
System.out.println("Case #"+(i+1)+": "+A+" "+B);
}
}
}
| true
|
2597be4c5ed374f3934233d4bc9dec7ddcca350b
|
Java
|
TheShen21/inleiding-java
|
/src/h12/h12praktijk.java
|
UTF-8
| 1,338
| 3.1875
| 3
|
[] |
no_license
|
package h12;
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class h12praktijk extends Applet {
String[] namen;
String[] nummers;
TextField tekstNamen;
TextField tekstNummers;
int teller = 0;
Button knop;
boolean zoek;
public void init() {
tekstNamen = new TextField("", 10);
tekstNummers = new TextField("", 10);
namen = new String[10];
nummers = new String[10];
add(tekstNamen);
add(tekstNummers);
knop = new Button("k");
knop.addActionListener(new KnopListener());
add(knop);
zoek = false;
}
public void paint(Graphics g) {
if (zoek) {
for (int i = 0; i < namen.length; i++) {
g.drawString("" + namen[i], 60, 20 * i + 60);
g.drawString("" + nummers[i], 160, 20 * i + 60);
}
}
}
class KnopListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
namen[teller] = tekstNamen.getText();
nummers[teller] = tekstNummers.getText();
teller++;
if (teller > 9) {
zoek = true;
}
tekstNummers.setText("");
tekstNamen.setText("");
repaint();
}
}
}
| true
|
8db9155be87522bbb3cd01b11d9ed8f431a17419
|
Java
|
scarolyne/SiPP
|
/Sistema-para-Planejamento-de-Projetos/trunk/tcc/src/java/bean/ProjetoFatorComplexidade.java
|
UTF-8
| 1,186
| 2.25
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package bean;
import java.io.Serializable;
/**
*
* @author Asus PC
*/
public class ProjetoFatorComplexidade implements Serializable{
private int id;
private FatorComplexidade fator;
private Projeto projeto;
private int classificacao;
public ProjetoFatorComplexidade() {
projeto = new Projeto();
fator = new FatorComplexidade();
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public FatorComplexidade getFator() {
return fator;
}
public void setFator(FatorComplexidade fator) {
this.fator = fator;
}
public Projeto getProjeto() {
return projeto;
}
public void setProjeto(Projeto projeto) {
this.projeto = projeto;
}
public int getClassificacao() {
return classificacao;
}
public void setClassificacao(int classificacao) {
this.classificacao = classificacao;
}
}
| true
|
82c9a57424c9856e0ddf532671973e4ead2c7666
|
Java
|
crazyqin/pgms
|
/src/com/pgms/action/FileDownloadAction.java
|
UTF-8
| 875
| 2.15625
| 2
|
[] |
no_license
|
package com.pgms.action;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import org.apache.struts2.ServletActionContext;
public class FileDownloadAction {
private String fileName;
private String fileDSTName;
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getFileDSTName() {
return fileDSTName;
}
public void setFileDSTName(String fileDSTName) {
this.fileDSTName = fileDSTName;
}
public InputStream getInputStream() throws UnsupportedEncodingException{
System.out.println(fileName);
fileDSTName=new Date().toString()+".xls";
return ServletActionContext.getServletContext().getResourceAsStream("/xls_tj/"+fileName);
}
public String execute(){
return "success";
}
}
| true
|
af79e2a10ae80bec887127edf754c3aba07e6bbe
|
Java
|
NinjaCap/NinjaCaptain
|
/bestpick/HomeTab/HomeFragment.java
|
UTF-8
| 2,763
| 2.375
| 2
|
[] |
no_license
|
package com.bestpickindia.android.bestpick.HomeTab;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Gallery;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.bestpickindia.android.bestpick.R;
/**
* Created by HP on 6/21/2016.
*/
public class HomeFragment extends Fragment {
static TextView mDotsText[];
private int mDotsCount;
private LinearLayout mDotsLayout;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater , ViewGroup container,Bundle savedInstanceState){
return inflater.inflate(R.layout.home_layout,null);
}
@Override
public void onViewCreated(final View view, final Bundle savedInstanceState){
super.onViewCreated(view, savedInstanceState);
Gallery gallery = (Gallery)getView().findViewById(R.id.gallery);
gallery.setAdapter(new ImageAdapter(getActivity()));
mDotsLayout = (LinearLayout)getView().findViewById(R.id.image_count);
//here we count the number of images we have to know how many dots we need
mDotsCount = gallery.getAdapter().getCount();
//here we create the dots
//as you can see the dots are nothing but "." of large size
mDotsText = new TextView[mDotsCount];
//here we set the dots
for (int i = 0; i < mDotsCount; i++) {
mDotsText[i] = new TextView(getActivity());
mDotsText[i].setText(".");
mDotsText[i].setTextSize(45);
mDotsText[i].setTypeface(null, Typeface.BOLD);
mDotsText[i].setTextColor(android.graphics.Color.GRAY);
mDotsLayout.addView(mDotsText[i]);
}
//when we scroll the images we have to set the dot that corresponds to the image to White and the others
//will be Gray
gallery.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView adapterView, View view, int pos, long l) {
for (int i = 0; i < mDotsCount; i++) {
HomeFragment.mDotsText[i]
.setTextColor(Color.GRAY);
}
HomeFragment.mDotsText[pos]
.setTextColor(Color.WHITE);
}
@Override
public void onNothingSelected(AdapterView adapterView) {
}
});
}
}
| true
|
6711d49113b35b0359563c26b59836eb713cfc19
|
Java
|
afeng5853/Classwork
|
/src/TimeSortingAlgo.java
|
UTF-8
| 3,265
| 3.203125
| 3
|
[] |
no_license
|
import java.math.BigInteger;
import java.util.Arrays;
import java.util.Random;
import java.util.function.Function;
import CountingSort.CountingSort;
import Lab3_2.ArrayMethods2;
import Lab3_3.ArrayMethods3;
import QuickSort.ArrayMethod4;
public class TimeSortingAlgo {
public static void main(String[] args) {
int maxInt = 100000;
int iterations = 100000;
System.out.println("Random integer test 0-255, iterations " + iterations + " for counting and merge");
int[] test = generateRandomIntArr(100000, maxInt);
int[] test2 = Arrays.copyOfRange(test, 0, test.length);
int[] test3 = Arrays.copyOfRange(test2, 0, test.length);
BigInteger countingSortTime = calculateTime(test, CountingSort::countingSort, 50);
System.out.println("Counting sort: " + countingSortTime);
BigInteger mergeSortTime = calculateTime(test, TimeSortingAlgo::mergeSort, 50);
System.out.println("Merge sort: " + mergeSortTime);
long time = System.nanoTime();
Arrays.sort(test);
System.out.println("Array.sort: " + (System.nanoTime() - time));
long time2 = System.nanoTime();
ArrayMethod4.quickSort(test2, 0, test.length);
System.out.println("Quick sort: " + (System.nanoTime() - time2));
long time3 = System.nanoTime();
ArrayMethods3.insertionSort(test3);
System.out.println("Insertion sort: " + (System.nanoTime() - time3));
long time4 = System.nanoTime();
ArrayMethods3.selectionSort(test3);
System.out.println("Selection sort: " + (System.nanoTime() - time4));
long time5 = System.nanoTime();
ArrayMethods3.bubbleSort(test3);
System.out.println("Bubble sort: " + (System.nanoTime() - time5));
}
public static int[] generateRandomIntArr(int size, int maxInt) {
Random r = new Random();
int[] test = new int[size];
for (int i = 0; i < test.length; i++) {
test[i] = r.nextInt(maxInt);
}
return test;
}
public static BigInteger calculateTime(int[] a, Function<int[],int[]> func, int iterations) {
BigInteger sum = BigInteger.valueOf(0);
for (int i = 0; i < iterations; i++) {
long time = System.nanoTime();
func.apply(a);
sum = sum.add(BigInteger.valueOf((System.nanoTime() - time)));
}
return sum.divide(BigInteger.valueOf(iterations));
}
public static int[] merge(int[] list1, int[] list2) {
int[] result = new int[list1.length + list2.length];
int i = 0; // list 1 index
int j = 0; // list 2 index
int resultIdx = 0;
while (i < list1.length || j < list2.length) {
if (i == list1.length) {
result[resultIdx] = list2[j];
j++;
}
else if (j == list2.length) {
result[resultIdx] = list1[i];
i++;
}
else if (list1[i] < list2[j]) {
result[resultIdx] = list1[i];
i++;
}
else {
result[resultIdx] = list2[j];
j++;
}
resultIdx++;
}
return result;
}
public static int[] mergeSort(int[] list) {
if (list.length <= 1) {
return list;
}
else {
int mid = list.length / 2;
int[] split1 = Arrays.copyOfRange(list, 0, mid);
int[] split2 = Arrays.copyOfRange(list, mid, list.length);
return merge(mergeSort(split1), mergeSort(split2));
}
}
}
| true
|
3bc7d4e42c41018c718a51ee474b019c32b3e6bd
|
Java
|
PassanisiJ/MancalaCS151
|
/MancalaDialog.java
|
UTF-8
| 3,935
| 2.890625
| 3
|
[] |
no_license
|
package mancala;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
public class MancalaDialog extends JDialog
{
private Container frame;
private int stoneCount;
private DesignLayout[] designs;
private DesignLayout design;
private int width = 525;
private int height = 400;
public MancalaDialog(JFrame parent, DesignLayout[] designs) throws IOException
{
super(parent, true);
this.designs = designs;
stoneCount = 3;
design = designs[0];
frame = getContentPane();
setSize(width,height);
JPanel wholePanel = new JPanel(new BorderLayout());
JPanel subCenterPanel = new JPanel(new BorderLayout());
JPanel stonePanel = new JPanel();
JPanel designPanel = new JPanel();
wholePanel.setBackground(Color.WHITE);
stonePanel.setBackground(Color.WHITE);
designPanel.setBackground(Color.WHITE);
//Create panel to hold image
JPanel titleImage = new JPanel();
titleImage.setLayout(new BorderLayout());
//Add the image for the Mancala title
BufferedImage myPicture = ImageIO.read(new File("mancala.jpg"));
JLabel picLabel = new JLabel(new ImageIcon(myPicture));
//Add the image to the panel
titleImage.add(picLabel, BorderLayout.NORTH);
titleImage.setBackground(Color.WHITE);
wholePanel.add(titleImage, BorderLayout.NORTH);
JLabel chooseStones = new JLabel("Choose number of initial stones : ");
stonePanel.add(chooseStones);
JRadioButton three = new JRadioButton("Three", true);
JRadioButton four = new JRadioButton("Four");
ButtonGroup stoneGroup = new ButtonGroup();
stonePanel.add(three);
three.addActionListener(setStoneCount(3));
stoneGroup.add(three);
stonePanel.add(four);
four.addActionListener(setStoneCount(4));
stoneGroup.add(four);
subCenterPanel.add(stonePanel, BorderLayout.NORTH);
JLabel chooseDesign = new JLabel("Choose a design : ");
designPanel.add(chooseDesign);
JRadioButton[] designButtons = new JRadioButton[designs.length];
ButtonGroup designGroup = new ButtonGroup();
for (int i = 0; i < designs.length; i++)
{
designButtons[i] = new JRadioButton(designs[i].getName(), i == 0);
designPanel.add(designButtons[i]);
designGroup.add(designButtons[i]);
designButtons[i].addActionListener(setDesign(i));
}
subCenterPanel.add(designPanel, BorderLayout.CENTER);
JButton startButton = new JButton("Start");
startButton.addActionListener(new
ActionListener()
{
public void actionPerformed(ActionEvent event)
{
frame.setVisible(false);
dispose();
}
});
subCenterPanel.add(startButton, BorderLayout.SOUTH);
wholePanel.add(subCenterPanel, BorderLayout.CENTER);
frame.add(wholePanel);
}
public void display()
{
setVisible(true);
}
public ActionListener setStoneCount(int stoneNum)
{
return new
ActionListener()
{
public void actionPerformed(ActionEvent event)
{
stoneCount = stoneNum;
}
};
}
public ActionListener setDesign(final int designNum)
{
return new
ActionListener()
{
public void actionPerformed(ActionEvent event)
{
design = designs[designNum];
}
};
}
public int getStoneNum()
{
return stoneCount;
}
public DesignLayout getDesign()
{
return design;
}
}
| true
|
5466e250b08ecb7301d8336c6f31c77f20b4a9cf
|
Java
|
Surti/AndroBoum
|
/app/src/main/java/com/example/leman/androboum/OtherUserActivity.java
|
UTF-8
| 4,690
| 2.015625
| 2
|
[] |
no_license
|
package com.example.leman.androboum;
import android.content.Context;
import android.content.Intent;
import android.media.Image;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.firebase.ui.storage.images.FirebaseImageLoader;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import java.util.ArrayList;
import java.util.List;
public class OtherUserActivity extends AppCompatActivity {
private List<Profil> userList = new ArrayList<>();
private MyArrayAdapter adapter;
private boolean filterConnected = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
final List<Profil> userList = new ArrayList<>();
final MyPagerAdapter adapter = new MyPagerAdapter(this, userList);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_other_user);
final ViewPager pager = (ViewPager) findViewById(R.id.pager);
// on obtient l'intent utilisé pour l'appel
Intent intent = getIntent();
// on va chercher la valeur du paramètre position, et on
// renvoie zéro si ce paramètre n'est pas positionné (ce qui ne devrait
// pas arriver dans notre cas).
final int position = intent.getIntExtra("position", 0);
filterConnected = intent.getBooleanExtra("filter", false);
//Log.v("Test",""+filterConnected);
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference().child("Users");
ValueEventListener postListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
userList.clear();
for (DataSnapshot child : dataSnapshot.getChildren()) {
if (filterConnected) {
if (child.getValue(Profil.class).isConnected() == true)
userList.add(child.getValue(Profil.class));
}else{
userList.add(child.getValue(Profil.class));
}
}
adapter.notifyDataSetChanged();
pager.setCurrentItem(position);
}
@Override
public void onCancelled(DatabaseError databaseError) {
// Getting Post failed, log a message
Log.v("AndroBoum", "loadPost:onCancelled", databaseError.toException());
}
};
mDatabase.addValueEventListener(postListener);
pager.setAdapter(adapter);
}
private void downloadImage(Profil p) {
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference photoRef = storage.getReference().child(p.getEmail() + "/photo.jpg");
if (photoRef == null) return;
ImageView imageView = (ImageView) findViewById(R.id.imageView3);
// Load the image using Glide
Glide.with(this /* context */).using(new FirebaseImageLoader())
.load(photoRef)
.skipMemoryCache(true)
.diskCacheStrategy(DiskCacheStrategy.NONE)
.placeholder(R.drawable.ic_person_black_24dp)
.into(imageView);
}
private class MyArrayAdapter extends ArrayAdapter<Profil> {
List<Profil> liste;
private MyArrayAdapter(Context context, int resource, List<Profil> liste) {
super(context, resource, liste);
this.liste = liste;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView tv = new TextView(getContext());
tv.setText(liste.get(position).getEmail());
return tv;
}
@Override
public int getCount() {
return liste.size();
}
}
}
| true
|
4b9b7033c8db22e01632a1b3eb3c620ddeee93d5
|
Java
|
MichaelDark/lab-java
|
/src/ua/nure/temnokhud/task4/WordContainer.java
|
UTF-8
| 1,258
| 3.296875
| 3
|
[] |
no_license
|
package ua.nure.temnokhud.task4;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static java.lang.System.*;
import static ua.nure.temnokhud.task4.Utility.readFile;
public class WordContainer {
ArrayList<Word> words = new ArrayList<>();
public WordContainer(String path) {
StringBuilder input;
try {
input = readFile(path);
} catch (Exception ex) {
return;
}
Pattern p = Pattern.compile("\\b[\\p{L}-]+\\b");
Matcher m = p.matcher(input);
while (m.find()) {
Word word = new Word(m.group());
int index = this.words.indexOf(word);
if (index != -1) {
this.words.get(index).incrementFrequency();
} else {
this.words.add(word);
}
}
}
public List<Word> getWords(){
return this.words;
}
public List<Word> sort() {
Collections.sort(this.words);
return this.words;
}
public void print() {
for (Word word : this.words) {
out.println("'" + word.getText() + "': " + word.getFrequency());
}
}
}
| true
|
462aecd0f69ac21c4f3f8b77fb95eea698db829c
|
Java
|
dwalton/Random-Code-Challenges
|
/Challenge/ChallengePair.java
|
UTF-8
| 791
| 2.96875
| 3
|
[] |
no_license
|
/**
* This class contains a pair of Challenges
* Used for providing a set of 2 questions and answers
*/
public class ChallengePair
{
public Challenge first;
public Challenge second;
public ChallengePair(Fragment q0, String a0,
Fragment q1, String a1)
{
first = new Challenge(q0, a0);
second = new Challenge(q1, a1);
}
public ChallengePair(Challenge f, Challenge s)
{
first = f;
second = s;
}
public ChallengePair()
{
//set first and second manually, later
first = null;
second = null;
}
public String toString()
{
return first.toString() + "\n" + second.toString();
}
public String toGoogleForm()
{
return "\"" + first.question.toString().replaceAll("\"", "\"\"") + "\"";
}
}
| true
|
c02c15fe0a2daceaa679424a470e34718c1f4d61
|
Java
|
gchq/stroom
|
/stroom-resource/stroom-resource-impl/src/test/java/stroom/resource/impl/TestResourceStore.java
|
UTF-8
| 2,437
| 2.3125
| 2
|
[
"LicenseRef-scancode-proprietary-license",
"Apache-2.0",
"CDDL-1.0",
"GPL-1.0-or-later",
"LGPL-2.0-or-later",
"MPL-1.0",
"CC-BY-4.0",
"LicenseRef-scancode-public-domain",
"EPL-1.0"
] |
permissive
|
/*
* Copyright 2016 Crown Copyright
*
* 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 stroom.resource.impl;
import stroom.task.api.SimpleTaskContextFactory;
import stroom.util.shared.ResourceKey;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import static org.assertj.core.api.Assertions.assertThat;
class TestResourceStore {
@TempDir
static Path tempDir;
@Test
void testSimple() throws IOException {
final ResourceStoreImpl resourceStore = new ResourceStoreImpl(() -> tempDir, new SimpleTaskContextFactory());
resourceStore.execute();
final ResourceKey key1 = resourceStore.createTempFile("TestResourceStore1.dat");
assertThat(key1.toString().endsWith("TestResourceStore1.dat")).isTrue();
final ResourceKey key2 = resourceStore.createTempFile("TestResourceStore2.dat");
assertThat(key2.toString().endsWith("TestResourceStore2.dat")).isTrue();
Files.createFile(resourceStore.getTempFile(key1));
Files.createFile(resourceStore.getTempFile(key2));
assertThat(Files.isRegularFile(resourceStore.getTempFile(key1))).isTrue();
assertThat(Files.isRegularFile(resourceStore.getTempFile(key2))).isTrue();
// Roll to Old
resourceStore.execute();
final Path file1 = resourceStore.getTempFile(key1);
assertThat(Files.isRegularFile(file1)).isTrue();
final Path file2 = resourceStore.getTempFile(key2);
assertThat(Files.isRegularFile(file2)).isTrue();
// Roll to Delete
resourceStore.execute();
assertThat(resourceStore.getTempFile(key1)).isNull();
assertThat(Files.isRegularFile(file1)).isFalse();
assertThat(resourceStore.getTempFile(key2)).isNull();
assertThat(Files.isRegularFile(file2)).isFalse();
}
}
| true
|
e47977fcbb4f66320831ab75a236bffd3a0f72be
|
Java
|
mrjdrs/design-patterns
|
/domain-driven-design/src/demo1/package-info.java
|
UTF-8
| 38
| 1.507813
| 2
|
[] |
no_license
|
/**
* 贫血模式
*/
package demo1;
| true
|
7a2f6994a2ba4aab38a32c0423a3d7d81bb030b7
|
Java
|
sd-giovannini/azkaban-groovy-plugin
|
/src/main/groovy/eu/spaziodati/azkaban/Reflection.java
|
UTF-8
| 1,361
| 2.859375
| 3
|
[] |
no_license
|
package eu.spaziodati.azkaban;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
public class Reflection {
public static <T> T get(Class cc, String field) {
return get(cc, null, field);
}
public static <T> T get(Object obj, String field) {
return get(obj.getClass(), obj, field);
}
@SuppressWarnings("unchecked")
public static <T> T get(Class<?> clazz, Object instance, String field) {
try {
Field f = clazz.getDeclaredField(field);
f.setAccessible(true);
return (T) f.get(instance);
} catch (Exception e ){
throw new RuntimeException(e);
}
}
public static void set(Object instance, String field, Object value) {
set(instance.getClass(), instance, field, value);
}
public static void set(Class<?> clazz, Object instance, String field, Object value) {
try {
Field f = clazz.getDeclaredField(field);
f.setAccessible(true);
Field modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
modifiersField.setInt(f, f.getModifiers() & ~Modifier.FINAL);
f.set(instance, value);
} catch (Exception e ) {
throw new RuntimeException(e);
}
}
}
| true
|
72476ea7a8b33fe6b7b7234267a8c156972e00fc
|
Java
|
travel-manager/server
|
/logic/src/main/java/com/travelmanager/services/NotificationService.java
|
UTF-8
| 1,622
| 2.25
| 2
|
[] |
no_license
|
package com.travelmanager.services;
import com.travelmanager.models.Notification;
import com.travelmanager.repositories.INotificationRepository;
import org.aspectj.weaver.ast.Not;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.hateoas.ResourceSupport;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class NotificationService extends HateoasService<Notification, Integer> {
private INotificationRepository repository;
@Autowired
public NotificationService(INotificationRepository _repo) {
super(_repo);
repository = _repo;
}
public void update(Notification object){
if(repository.findById(object.id).isPresent()){
Notification ent = repository.findById(object.id).get();
ent.setContent(object.getContent());
ent.setIcon(object.getIcon());
ent.setTimestamp(object.getTimestamp());
ent.setTrip(object.getTrip());
ent.setType(object.getType());
repository.save(ent);
}
}
@Override
public Class<? extends HateoasService<Notification, Integer>> getClazz() {
return this.getClass();
}
@Override
public Class<? extends ResourceSupport> getType() {
return Notification.class;
}
public List<Notification> getAllNotificationsByTripId(int tripId) {
return repository.getAllMarkersByTripId(tripId);
}
public boolean deleteAllNotificationsByTripId(int tripId) {
repository.deleteAllMarkersByTripId(tripId);
return true;
}
}
| true
|
fc523ee867fd232762a7d013b4562e40adfd6c4f
|
Java
|
skyrunwith/CRRrspy
|
/app/src/main/java/com/youngheart/entity/UserInfo.java
|
UTF-8
| 2,175
| 2.03125
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.youngheart.entity;
import java.io.Serializable;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Created by Administrator on 2016/4/22.
*/
public class UserInfo implements Serializable{
private String uid;
private String loginname;
private String loginpass;
private String email;
private String gender;
private String image;
private int status;
private String activationCode;
private List<ProductComment> tProductcommentEntitySet;
private int admin; //1为admin,2为普通用户
public List<ProductComment> gettProductcommentEntitySet() {
return tProductcommentEntitySet;
}
public void settProductcommentEntitySet(List<ProductComment> tProductcommentEntitySet) {
this.tProductcommentEntitySet = tProductcommentEntitySet;
}
public int getAdmin() {
return admin;
}
public void setAdmin(int admin) {
this.admin = admin;
}
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
public String getLoginname() {
return loginname;
}
public void setLoginname(String loginname) {
this.loginname = loginname;
}
public String getLoginpass() {
return loginpass;
}
public void setLoginpass(String loginpass) {
this.loginpass = loginpass;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getActivationCode() {
return activationCode;
}
public void setActivationCode(String activationCode) {
this.activationCode = activationCode;
}
}
| true
|
e67aab9f9b0d10feaff43ada574135243d3c8e49
|
Java
|
ChannD/ChannAlbum
|
/src/main/java/com/chann/album/config/security/MyUserDetailsService.java
|
UTF-8
| 1,350
| 2.234375
| 2
|
[] |
no_license
|
package com.chann.album.config.security;
import com.chann.album.entity.Role;
import com.chann.album.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
@Component
public class MyUserDetailsService implements UserDetailsService {
@Autowired
private UserRepository userRepository;
@Override
public UserDetails loadUserByUsername(String s) {
com.chann.album.entity.User user = userRepository.findByUsername(s);
List<SimpleGrantedAuthority> authorities = new ArrayList<>();
// for (Role role : user.getRoles()) {
authorities.add(new SimpleGrantedAuthority("admin"));
// }
return new User(user.getUsername()
, user.getPassword()
,true, true, true ,true
, authorities);
}
}
| true
|
c9e971680808ed1ab6d9cf2b8acea63019bab850
|
Java
|
Leo-Shang/web_server
|
/Web_server.java
|
UTF-8
| 6,247
| 3.125
| 3
|
[] |
no_license
|
import java.io.*;
import java.net.*;
import java.lang.String;
import java.util.*;
import java.text.SimpleDateFormat;
public class Web_server {
private Socket socket;
private Web_server(){ // Constructor
//in = null;
socket = null;
//serverSocket = null;
//reader = null;
}
private void setup(int portNum){ // setup the server socket and port number
try {
ServerSocket serverSocket = new ServerSocket(portNum);
System.out.println("Waiting for client to connect\n");
socket = serverSocket.accept();
receive_request(); // receive a request from client
} catch (IOException e) {
System.out.println("File Transfer Failed");
}
finally{ // terminate the connection after file transfer
try {
socket.close();
socket = null;
} catch (IOException e) {
System.out.println("Connection Termination Failed");
}
System.out.println("TCP Connection Terminated");
}
}
private void receive_request(){ // receive request, determine file name and http version
try {
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String current_line = in.readLine();
String header_line = current_line;
String client_req = "";
while(in.ready()){
System.out.println(current_line);
client_req += current_line;
current_line = in.readLine();
}
System.out.println("\n");
String[] reqLine = header_line.split(" ");
String command = reqLine[0];
String file = reqLine[1];
String version = reqLine[2];
if(command.equals("GET")) {
if(version.equals("HTTP/1.1")) {
try {
file = file.substring(1);
send_file("HTTP/1.1 200 OK\r\n", file); // when http version is supported
in.close();
} catch (Exception e) {
System.out.println("Error Occurred");
}
}
else {
try {
file = file.substring(1);
System.out.println("HTTP Version Not Supported");
send_file("HTTP/1.1 505 HTTP Version Not Supported\r\n", file); // when http version is not supported
in.close();
}
catch (Exception e) {
System.out.println("Error Occurred");
}
}
}
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
private void send_file(String status,String file) throws IOException { // send the file and header, status to the client
FileReader filereader;
PrintWriter output = null;
try {
File f = new File(file);
if(f.exists()) { // if the file exists
filereader = new FileReader(f);
BufferedReader reader = new BufferedReader(filereader);
output = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())));
String form = f.getName();
int posi = f.getName().indexOf('.');
form = form.substring(posi + 1);
String response = "";
response += status; // send the status line
if (status.equals("HTTP/1.1 200 OK\r\n")) { // 200 will enter this section, 505 by default will not enter
String current_time = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(Calendar.getInstance().getTime());
response += "Date: " + current_time + "\r\n";
response += "Server: Maoshun's Web Server\r\n";
response += "Content-Length: " + f.length() + "\r\n";
response += "Content-Type: " + form + "\r\n";
response += "Connection: Closed\r\n\r\n";
String content;
while ((content = reader.readLine()) != null) {
response += (content + "\r\n");
}
}
output.print(response);
output.flush();
System.out.println(response);
}
else{ // if file not exist (404)
output = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())));
output.print("HTTP/1.1 404 Not Found \r\n");
System.out.println("HTTP/1.1 404 Not Found \r\n");
}
}
catch (IOException e) {
System.out.println(e.getMessage());
}
finally{
assert output != null;
output.close();
}
}
public static void main(String args[]){ // main method
int[] queue = {11111,11112,11113,11114,11115,11116};
int points_to = 0;
Web_server server;
while(queue.length <= 6 && queue.length >= 0) {
server = new Web_server();
server.setup(queue[points_to]);
points_to = (points_to + 1) % 6 ;
}
}
}
| true
|
7b42b99fbbfd9735d0ca6213d7d759dd844d205e
|
Java
|
wang-shun/erp_xiajun
|
/globalshop-biz1-app/src/main/java/com/wangqin/globalshop/biz1/app/dal/dataObject/ChannelShopDO.java
|
UTF-8
| 2,579
| 1.90625
| 2
|
[] |
no_license
|
package com.wangqin.globalshop.biz1.app.dal.dataObject;
import java.util.Date;
public class ChannelShopDO extends BaseModel {
private Long id;
private Long version;
private String creator;
private String modifier;
private String channelNo;
private String companyNo;
private String shopName;
private String shopCode;
private Date expiresTime;
private String proxyUrl;
private String shopType;
private Boolean open;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getVersion() {
return version;
}
public void setVersion(Long version) {
this.version = version;
}
public String getCreator() {
return creator;
}
@Override
public void setCreator(String creator) {
this.creator = creator == null ? null : creator.trim();
}
public String getModifier() {
return modifier;
}
@Override
public void setModifier(String modifier) {
this.modifier = modifier == null ? null : modifier.trim();
}
public String getChannelNo() {
return channelNo;
}
public void setChannelNo(String channelNo) {
this.channelNo = channelNo == null ? null : channelNo.trim();
}
public String getCompanyNo() {
return companyNo;
}
@Override
public void setCompanyNo(String companyNo) {
this.companyNo = companyNo == null ? null : companyNo.trim();
}
public String getShopName() {
return shopName;
}
public void setShopName(String shopName) {
this.shopName = shopName == null ? null : shopName.trim();
}
public String getShopCode() {
return shopCode;
}
public void setShopCode(String shopCode) {
this.shopCode = shopCode == null ? null : shopCode.trim();
}
public Date getExpiresTime() {
return expiresTime;
}
public void setExpiresTime(Date expiresTime) {
this.expiresTime = expiresTime;
}
public String getProxyUrl() {
return proxyUrl;
}
public void setProxyUrl(String proxyUrl) {
this.proxyUrl = proxyUrl == null ? null : proxyUrl.trim();
}
public String getShopType() {
return shopType;
}
public void setShopType(String shopType) {
this.shopType = shopType == null ? null : shopType.trim();
}
public Boolean getOpen() {
return open;
}
public void setOpen(Boolean open) {
this.open = open;
}
}
| true
|
2e165f9c39b0a279c542a4e89615057f447e55ee
|
Java
|
834155292/design-pattern
|
/Creational-Singleton/src/main/java/com/zboy/example/creational/singleton/example03/HungrySingleton.java
|
UTF-8
| 287
| 2.40625
| 2
|
[] |
no_license
|
package com.zboy.example.creational.singleton.example03;
public class HungrySingleton {
private static final HungrySingleton instance = new HungrySingleton();
private HungrySingleton() {
}
public static HungrySingleton getInstance() {
return instance;
}
}
| true
|
5031701b4a273f74ab112ed5ae597f428d7bb646
|
Java
|
Letractively/jcms-iqbon
|
/ jcms-iqbon/JCms/src/com/iqbon/jcms/domain/mapRow/FtpSettingMapper.java
|
UTF-8
| 754
| 2.15625
| 2
|
[] |
no_license
|
package com.iqbon.jcms.domain.mapRow;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.jdbc.core.RowMapper;
import com.iqbon.jcms.domain.FtpSetting;
public class FtpSettingMapper implements RowMapper<FtpSetting> {
@Override
public FtpSetting mapRow(ResultSet rs, int rowNum) throws SQLException {
FtpSetting ftp = new FtpSetting();
ftp.setFtpIp(rs.getString("ftp_ip"));
ftp.setFtpPort(rs.getString("ftp_port"));
ftp.setUsername(rs.getString("username"));
ftp.setPassword(rs.getString("password"));
ftp.setFtpPath(rs.getString("ftp_path"));
ftp.setFtpPushRate(rs.getInt("ftp_push_rate"));
ftp.setEnable(rs.getBoolean("enable"));
return ftp;
}
}
| true
|
55fbfdb16b3cf408bf37abc1b51da31f56c2efd5
|
Java
|
leiqjl/leetcode
|
/src/com/leiqjl/MatchsticksToSquare.java
|
UTF-8
| 1,263
| 3.4375
| 3
|
[] |
no_license
|
package com.leiqjl;
import java.util.Arrays;
/**
* 473. Matchsticks to Square - Medium
*/
public class MatchsticksToSquare {
//1 <= matchsticks.length <= 15
//1 <= matchsticks[i] <= 10^8
//todo
public boolean makesquare(int[] matchsticks) {
if (matchsticks == null || matchsticks.length < 4) {
return false;
}
int sum = 0;
for (int m : matchsticks) {
sum += m;
}
int len = sum / 4;
if (len * 4 != sum) {
return false;
}
Arrays.sort(matchsticks);
return dfs(matchsticks.length - 1, new int[4], matchsticks, len);
}
private boolean dfs(int index, int[] sums, int[] matchsticks, int len) {
if (index < 0) {
if (sums[0] == len && sums[1] == len && sums[2] == len) {
return true;
}
return false;
}
for (int i = 0; i < 4; i++) {
if (sums[i] + matchsticks[index] <= len) {
sums[i] += matchsticks[index];
if (dfs(index - 1, sums, matchsticks, len)) {
return true;
}
sums[i] -= matchsticks[index];
}
}
return false;
}
}
| true
|
b4a8c10cbca18ee706edeac5389e933345dbc401
|
Java
|
Witsacco/Mockery
|
/src/com/witsacco/mockery/client/UpdatePackage.java
|
UTF-8
| 1,716
| 2.921875
| 3
|
[] |
no_license
|
package com.witsacco.mockery.client;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
/*
* Represents an update to a room, with its most current standings and list of messages.
*/
public class UpdatePackage implements Serializable {
private static final long serialVersionUID = 1L;
// The time this UpdatePackage was created
private Date timestamp;
// Current standings as of `timestamp`
private ArrayList< DisplayUser > currentStandings;
// Messages that are new or have been updated as of `timestamp`
private ArrayList< DisplayMessage > updatedMessages;
public UpdatePackage() {
// Need this for use on the server side.
}
/**
* @param currentStandings
* @param messages
*/
public UpdatePackage( ArrayList< DisplayUser > currentStandings, ArrayList< DisplayMessage > messages ) {
timestamp = new Date();
this.currentStandings = currentStandings;
this.updatedMessages = messages;
}
/**
* @return the currentStandings
*/
public ArrayList< DisplayUser > getCurrentStandings() {
return currentStandings;
}
/**
* @param currentStandings
* the currentStandings to set
*/
public void setCurrentStandings( ArrayList< DisplayUser > currentStandings ) {
this.currentStandings = currentStandings;
}
/**
* @return the messages
*/
public ArrayList< DisplayMessage > getUpdatedMessages() {
return updatedMessages;
}
/**
* @param messages
* the messages to set
*/
public void setUpdatedMessages( ArrayList< DisplayMessage > messages ) {
this.updatedMessages = messages;
}
/**
* @return the Date when this UpdatePackage was created
*/
public Date getTimestamp() {
return timestamp;
}
}
| true
|
7c0652b0b47362362035da7f87c0955bbb0a1c86
|
Java
|
pmatosevic/CarRepairs
|
/moj-autoservis-backend/src/main/java/org/infiniteam/autoservice/model/ServiceLabor.java
|
UTF-8
| 1,120
| 2.296875
| 2
|
[] |
no_license
|
package org.infiniteam.autoservice.model;
import javax.persistence.*;
@Entity
public class ServiceLabor implements Product {
@Id @GeneratedValue
private Long serviceLaborId;
@ManyToOne
private AutoService autoService;
@Column(nullable = false)
private String serviceName = "";
@Column(nullable = false)
private double price;
public Long getServiceLaborId() {
return serviceLaborId;
}
public void setServiceLaborId(Long serviceLaborId) {
this.serviceLaborId = serviceLaborId;
}
public AutoService getAutoService() {
return autoService;
}
public void setAutoService(AutoService autoService) {
this.autoService = autoService;
}
public String getServiceName() {
return serviceName;
}
public void setServiceName(String serviceName) {
this.serviceName = serviceName;
}
@Override
public String getName() {
return serviceName;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
}
| true
|
e88ce317469b8e0ea75873e6dfbe519b01aa0b82
|
Java
|
LukeNgirubiu/SupplierApp
|
/app/src/main/java/com/luke/supplierapp/subscriberDetails.java
|
UTF-8
| 2,908
| 2.140625
| 2
|
[] |
no_license
|
package com.luke.supplierapp;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.firestore.CollectionReference;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
import com.squareup.picasso.Picasso;
import java.util.List;
import de.hdodenhof.circleimageview.CircleImageView;
public class subscriberDetails extends RecyclerView.Adapter<subscriberDetails.Viewing> {
private List<setSubsriptions> list;
private Context context;
public subscriberDetails(List<setSubsriptions> list, Context context) {
this.list = list;
this.context = context;
}
@NonNull
@Override
public Viewing onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.subscriberdatails, parent, false);
return new Viewing(view);
}
@Override
public void onBindViewHolder(@NonNull final Viewing holder, int position) {
final setSubsriptions users = list.get(position);
FirebaseFirestore firestore=FirebaseFirestore.getInstance();
if (users.isSeen()==false){
holder.seenS.setText("New");
}
else {
holder.seenS.setText("");
}
DocumentReference coll=firestore.collection("usersDetails").document(users.getBuyerId());
coll.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
@Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
userDetails us=documentSnapshot.toObject(userDetails.class);
Picasso.get().load(us.getImagePath()).into(holder.imageP);
holder.firstN.setText(us.getFirstName());
holder.secondN.setText(us.getSecondName());
holder.Contact.setText(us.getContact());
}
});
}
@Override
public int getItemCount() {
return list.size();
}
public class Viewing extends RecyclerView.ViewHolder {
TextView firstN, secondN, Contact, seenS;
CircleImageView imageP;
public Viewing(View itemView) {
super(itemView);
firstN = itemView.findViewById(R.id.fName);
secondN = itemView.findViewById(R.id.sName);
Contact = itemView.findViewById(R.id.phonecontact);
imageP = itemView.findViewById(R.id.profImage);
seenS = itemView.findViewById(R.id.seen);
}
}
}
| true
|
6bbdfcea6e483f149cecea636eeccbcd8060e001
|
Java
|
exutic/MasterMind
|
/app/src/main/java/com/example/mastermind/SplashScreen/Splash_Activity.java
|
UTF-8
| 882
| 2.09375
| 2
|
[] |
no_license
|
package com.example.mastermind.SplashScreen;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import com.example.mastermind.MainActivity.MainActivity;
import com.example.mastermind.R;
public class Splash_Activity extends AppCompatActivity {
private static final int SPLASH_DISPLAY_LENGTH = 1500;
/* access modifiers changed from: protected */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_);
new Handler().postDelayed(new Runnable() {
public void run() {
Splash_Activity.this.startActivity(new Intent(Splash_Activity.this, MainActivity.class));
Splash_Activity.this.finish();
}
}, SPLASH_DISPLAY_LENGTH);
}
}
| true
|
37b00b6c201e295da41fb76ed26eea83ed4af1f3
|
Java
|
limbuKuldip/BlueMind
|
/app/src/main/java/com/bluemind/bluemind/challenge_activity/ChallengesList.java
|
UTF-8
| 1,381
| 2.0625
| 2
|
[] |
no_license
|
package com.bluemind.bluemind.challenge_activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import com.bluemind.bluemind.R;
public class ChallengesList extends AppCompatActivity {
private Button completeButton, viewButton;
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.challengeslist);
final String UID = getIntent().getStringExtra("userID");
completeButton = (Button) findViewById(R.id.rideComplete);
completeButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent completeIntent = new Intent(getApplicationContext(), CompleteButton.class);
startActivity(completeIntent);
completeIntent.putExtra("userId", UID);
}
});
viewButton = (Button) findViewById(R.id.activityoneViewButton);
viewButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent viewIntent = new Intent(getApplicationContext(), ViewButton.class);
startActivity(viewIntent);
}
});
}
}
| true
|
17ab1aa3376f91b9ce31afeb4947305dd02a4298
|
Java
|
Jingtian1989/config
|
/config.client/src/main/java/org/config/client/PublisherRegistrar.java
|
UTF-8
| 1,265
| 2.46875
| 2
|
[] |
no_license
|
package org.config.client;
import java.util.concurrent.ConcurrentHashMap;
/**
* Created by jingtian.zjt on 2014/12/9.
*/
public class PublisherRegistrar{
private static final ConcurrentHashMap<String, Publisher> publishers = new ConcurrentHashMap<String, Publisher>();
public static Publisher query(ClientRegistration registration) {
return publishers.get(registration.getClientId());
}
public static Publisher query(String clientId) {
return publishers.get(clientId);
}
public static Publisher register(ClientRegistration registration) {
Publisher publisher = query(registration);
if (publisher != null) {
return publisher;
}
publisher = new Publisher(registration);
publishers.put(registration.getClientId(), publisher);
return publisher;
}
public static void unregister(ClientRegistration registration) {
Publisher publisher = query(registration);
if (publisher != null) {
publisher.setState(ConfigClient.CLIENT_UNREGISTERED);
ClientWorker.getInstance().signal();
}
}
protected static Publisher[] getPublishers() {
return publishers.values().toArray(new Publisher[0]);
}
}
| true
|
bbd704c0ddef3fbb4a9e2d905879d94a55c39e14
|
Java
|
junxiwen/mgrApi
|
/trunk/src/main/java/com/ys/mgr/dao/SysRoleDaoImpl.java
|
UTF-8
| 2,697
| 2.0625
| 2
|
[] |
no_license
|
package com.ys.mgr.dao;
import com.ys.mgr.form.request.SysRoleForm;
import com.ys.mgr.po.SysRole;
import net.miidi.fsj.util.sjp.dao.BaseDaoImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* Created by fsj on 2017/5/24.
*/
@Repository
public class SysRoleDaoImpl extends BaseDaoImpl<SysRole, Integer> implements SysRoleDao {
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
public List<SysRole> selectForList(SysRoleForm sysRoleForm) throws Exception {
StringBuffer sql = new StringBuffer(super.buildSelectSql(false));
MapSqlParameterSource params = buildParams(sysRoleForm, sql, true, true);
return super.selectForListByNamedParameter(sql.toString(),params);
}
@Override
public long selectForCount(SysRoleForm sysRoleForm) throws Exception {
StringBuffer sql = new StringBuffer(super.buildSelectSql(true));
MapSqlParameterSource params = buildParams(sysRoleForm, sql, false, false);
return super.selectForCountByNamedParameter(sql.toString(),params);
}
private MapSqlParameterSource buildParams(SysRoleForm sysRoleForm, StringBuffer sql, boolean needOrder, boolean needLimit) throws Exception{
MapSqlParameterSource params = new MapSqlParameterSource();
if (sysRoleForm != null) {
sql.append(" where 1=1 ");
if (needOrder) {
sql.append(sysRoleForm.getOrderSql(SysRole.class));
}
if (needLimit) {
sql.append(sysRoleForm.getLimitSql());
}
}
return params;
}
@Override
public int deleteById(Integer id) throws Exception {
jdbcTemplate.update("DELETE FROM sys_role_resource WHERE roleId = ?", id);
jdbcTemplate.update("DELETE FROM sys_user_role WHERE roleId = ?", id);
return super.deleteById(id);
}
@Override
public Integer getRoleIdByUserId(Integer mgrUserId) {
String sql = "SELECT roleId FROM `sys_user_role` WHERE userId=?";
try {
return jdbcTemplate.queryForObject(sql, Integer.class, mgrUserId);
}catch (EmptyResultDataAccessException e){
return null;
}
}
@Override
public List<Integer> selectedResourcesIds(Integer id) throws Exception {
return jdbcTemplate.queryForList("SELECT resourceId FROM sys_role_resource WHERE roleId = ?", Integer.class, id);
}
}
| true
|
7ef54b05342d4eeb58c0690ef8c1b3f00fd29a53
|
Java
|
ThirdIInc/Third-I-Portal
|
/hrsaas/src/org/struts/action/payroll/BankStatementAction.java
|
UTF-8
| 4,269
| 2.5
| 2
|
[
"Apache-2.0"
] |
permissive
|
package org.struts.action.payroll;
import org.paradyne.bean.payroll.BankStatement;
import org.paradyne.model.payroll.BankStatementModel;
/*
*
* @author Hemant
*
*/
public class BankStatementAction extends org.struts.lib.ParaActionSupport{
BankStatement bean;
static org.apache.log4j.Logger logger=org.apache.log4j.Logger.getLogger(org.struts.lib.ParaActionSupport.class);public void prepare_local() throws Exception {
logger.info(">>>>>Inside prepare_local()");
bean=new BankStatement();
}
public Object getModel(){
return bean;
}
public String report(){
BankStatementModel model=new BankStatementModel();
model.initiate(context,session);
model.generateReport(bean,response);
model.terminate();
return null;
}
public String f9bank() throws Exception {
//
// BUILD COMPLETE QUERY (ALONG WITH PARAMETERS) WHICH GIVES THE DESIRED
// OUTPUT ALONG WITH PROFILES
//
logger.info("Inside-->report()");
String query = " SELECT BANK_MICR_CODE,BANK_NAME FROM HRMS_BANK ORDER BY BANK_NAME";
// SET THE HEADER NAMES OF TABLE WHICH IS DISPLAYED IN POP-UP WINDOW. *
String[] headers = {"Code","Bank"};
//DEFINE THE PERCENT WIDTH OF EACH COLUMN
String[] headerWidth = {"30", "30"};
// -SET THE FIELDNAMES INTO WHICH THE VALUES ARE BEING POPULATED AFTER A
// ROW IS SELECTED. -USEFULL IN CASES WHERE SUBMIT FLAG IS 'false'
// -PARENT FORM WILL SHOW THE VALUES IN THE FILDS CORRSPONDING TO COLUMN
// INDEX. NOTE: LENGHT OF COLUMN INDEX MUST BE SAME AS THE LENGTH OF
// FIELDNAMES
//
String[] fieldNames = { "bankCode","bank" };
// SET THE COLUMN INDEX E.G. SUPPOSE THE POP-UP SHOWS 4 COLUMNS, BUT ON
// CLICKING A ROW ONLY SECOND AND FORTH COLUMN VALUES NEED TO BE SHOWN
// IN THE PARENT WINDOW FIELDS THEN THE COLUMN INDEX CAN BE {1,3}
//NOTE: COLUMN NUMBERS STARTS WITH 0
int[] columnIndex = { 0,1};
// WHEN SET TO 'true' WILL SUBMIT THE FORM
String submitFlag = "false";
// IF THE 'submitFlag' IS 'true' , THE FORM WILL SUBMIT AND CALL
// FOLLOWING METHOD IN THE ACTION * NAMING CONVENSTION: <NAME OF
// ACTION>_<METHOD TO CALL>.action
String submitToMethod = "";
// CALL THIS METHOD AFTER ALL PARAMETERS ARE DEFINED *
setF9Window(query, headers, headerWidth, fieldNames, columnIndex,
submitFlag, submitToMethod);
return "f9page";
}
public String f9payBill() throws Exception {
/**
* BUILD COMPLETE QUERY (ALONG WITH PARAMETERS) WHICH GIVES THE DESIRED
* OUTPUT ALONG WITH PROFILES
*/
String query = " SELECT PAYBILL_ID,PAYBILL_GROUP FROM HRMS_PAYBILL ORDER BY PAYBILL_ID";
/**
* SET THE HEADER NAMES OF TABLE WHICH IS DISPLAYED IN POP-UP WINDOW. *
*/
String[] headers = { "Pay Bill Code","Pay Bill Group" };
/**
* DEFINE THE PERCENT WIDTH OF EACH COLUMN
*/
String[] headerWidth = { "25","25" };
/**
* -SET THE FIELDNAMES INTO WHICH THE VALUES ARE BEING POPULATED AFTER A
* ROW IS SELECTED. -USEFULL IN CASES WHERE SUBMIT FLAG IS 'false'
* -PARENT FORM WILL SHOW THE VALUES IN THE FILDS CORRSPONDING TO COLUMN
* INDEX. NOTE: LENGHT OF COLUMN INDEX MUST BE SAME AS THE LENGTH OF
* FIELDNAMES
*/
String[] fieldNames = { "payBill"};
/**
* SET THE COLUMN INDEX E.G. SUPPOSE THE POP-UP SHOWS 4 COLUMNS, BUT ON
* CLICKING A ROW ONLY SECOND AND FORTH COLUMN VALUES NEED TO BE SHOWN
* IN THE PARENT WINDOW FIELDS THEN THE COLUMN INDEX CAN BE {1,3}
*
* NOTE: COLUMN NUMBERS STARTS WITH 0
*
*/
int[] columnIndex = { 0,1 };
/**
* WHEN SET TO 'true' WILL SUBMIT THE FORM
*
*/
String submitFlag = "false";
/**
* IF THE 'submitFlag' IS 'true' , THE FORM WILL SUBMIT AND CALL
* FOLLOWING METHOD IN THE ACTION * NAMING CONVENSTION: <NAME OF
* ACTION>_<METHOD TO CALL>.action
*/
String submitToMethod = "";
/**
* CALL THIS METHOD AFTER ALL PARAMETERS ARE DEFINED *
*/
logger.info("1");
setF9Window(query, headers, headerWidth, fieldNames, columnIndex,
submitFlag, submitToMethod);
logger.info("4");
return "f9page";
}
}
| true
|
3ac2758e132a93fbfbb2dc6506dd2f748a665d88
|
Java
|
piresalexsandro/Estudos-VV
|
/OrientacaoAObjetos/src/Client.java
|
UTF-8
| 68
| 1.820313
| 2
|
[] |
no_license
|
public class Client {
public String nome;
public int codCli;
}
| true
|
4cb946a72a7f6857beb6e51e587164210d0eb09d
|
Java
|
ToBe-Liu/seleniumTest
|
/src/test/java/com/yatou/automation/test/order/ChromeTest2.java
|
UTF-8
| 2,260
| 2.078125
| 2
|
[] |
no_license
|
package com.yatou.automation.test.order;
import com.yatou.automation.listeners.TestNGListener;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
/**
* Created by Administrator on 2017/8/13.
*/
public class ChromeTest2 {
private WebDriver driver;
@BeforeClass
public void setupClass() {
//ChromeDriverManager.getInstance().useTaobaoMirror().setup();
System.setProperty("webdriver.chrome.driver", "D:\\webDrivers\\chromedriver.exe");
ChromeOptions chromeOptions = new ChromeOptions();
//chromeOptions.addArguments("--headless");
//chromeOptions.addArguments("--disable-gpu");
//chromeOptions.addArguments("--window-size=1920,1080");
driver = new ChromeDriver(chromeOptions);
System.out.println("ChromeTest2:"+driver);
TestNGListener.setDriver(driver);
driver.manage().window().maximize();
}
@AfterClass
public void teardown() {
if (driver != null) {
//driver.quit();
}
}
@Test(description = "新增预约量尺测试")
@Parameters({"username","password"})
public void testLogin(String username, String password) throws NoSuchFieldException, IllegalAccessException, InterruptedException {
/* driver.get(StoreConstants.LOGINURL);
Logger.log("打开门店首页!");
WebElement userNo = WaitUtil.fluentWait(driver, 10, "10秒内没有找到门店首页!", (driver1) -> driver.findElement(By.name("userNo")));
if (userNo != null) {
LoginPage loginPage = PageFactory.initElements(driver, LoginPage.class);
System.out.println("ChromeTest1:"+loginPage);
loginPage.login(username,password);
}*/
}
/*@Test(description = "新增预约量尺测试")
public void testAddMeasure() {
LoginPage loginPage = PageFactory.initElements(driver, LoginPage.class);
loginPage.login(StoreAccountConstants.ADVISER_USERNAME,StoreAccountConstants.ADVISER_PASSWORD);
}*/
}
| true
|
b90c831b588f3e303b930a982c7bcc3078d840a3
|
Java
|
erikgaal/qwirkle
|
/src/main/java/nl/utwente/ewi/qwirkle/client/GameController.java
|
UTF-8
| 9,842
| 3.375
| 3
|
[] |
no_license
|
package nl.utwente.ewi.qwirkle.client;
import nl.utwente.ewi.qwirkle.client.ui.IUserInterface;
import nl.utwente.ewi.qwirkle.client.ui.TextUserInterface;
import nl.utwente.ewi.qwirkle.model.*;
import nl.utwente.ewi.qwirkle.util.Logger;
import java.util.*;
/**
* Controlls all the aspects from a game. For every game a new GameController should be made.
*/
public class GameController {
/**
* The minimum amount of players in a game.
*/
public static final int MIN_PLAYERS = 2;
/**
* The maximum amount of players in a game.
*/
public static final int MAX_PLAYERS = 4;
/**
* Represents the amount of bonus points given to the last player's turn.
* @deprecated This is not used in the current implementation
*/
@Deprecated
public static final int POINTS_LAST_TURN = 6;
/**
* Stores the game board.
*/
private Board board;
/**
* Stores the User Interface.
*/
private TextUserInterface ui;
/**
* Stores the deck.
*/
private Deck deck;
/**
* Stores the players taking part in the game.
*/
private List<Player> playerList;
/**
* Stores the index of the player in playerList who is on turn.
*/
private int playerTurn;
/**
*Initializes the game. Also adds the UI as an observer to the board.
* @param ui The User Interface the player uses.
* @param playerList A list of the player taking part in the game.
* @throws PlayerAmountInvalidException Thrown when the player amount is not within the set bounds.
*/
public GameController(TextUserInterface ui, List<Player> playerList) throws PlayerAmountInvalidException {
if (playerList != null && playerList.size() >= MIN_PLAYERS && playerList.size() <= MAX_PLAYERS && ui != null) {
this.playerList = playerList;
this.deck = new Deck();
this.board = new Board();
this.ui = ui;
this.board.addObserver(ui);
} else {
int size;
if (playerList == null) {
size = 0;
} else {
size = playerList.size();
}
throw new PlayerAmountInvalidException(String.format("The player amount %d is not between %d and %d, or is null, or no ui is given.", size, MIN_PLAYERS, MAX_PLAYERS));
}
}
/**
* Initializes a game by shuffling the deck, giving hands to players and determining the starting player.
*/
private void init() {
this.deck = new Deck();
this.deck.shuffle();
for (Player p : playerList) {
p.emptyHand();
try {
p.addTile(deck.drawHand());
} catch (EmptyDeckException e) {
Logger.fatal("A hand could not be drawn. This can not occur in a normal game.");
System.exit(0);
}
}
// Determine the starting player
playerTurn = 0;
for (int i = 1; i < playerList.size(); i++ ) {
Logger.debug("Longeststreak of " + playerList.get(i).getName() + " is " + playerList.get(i).longestStreak());
Logger.debug("Longeststreak of " + getCurrentPlayer().getName() + " is " + getCurrentPlayer().longestStreak());
if (playerList.get(i).longestStreak() > getCurrentPlayer().longestStreak()) {
playerTurn = i;
}
}
}
/**
* Plays whole game. This consists of a turn of a player, refilling the player's hand, check if the game has ended and passing the turn.
*/
public void play() {
init();
while (true) {
doTurn();
for (int i = getCurrentPlayer().getHand().size(); i < Deck.HAND_SIZE; i++) { // Add missing tiles to hand
try {
getCurrentPlayer().addTile(this.deck.drawTile());
} catch (EmptyDeckException ignored) {}
}
if (isEnded()) { // Check if game has ended
//getCurrentPlayer().addScore(POINTS_LAST_TURN);
break;
}
nextPlayer();
}
ui.gameOver(true);
}
/**
* Includes all the actions in a turn of a single player, marked by playerTurn.
*/
private void doTurn() {
boolean putPossible = this.board.isPutPossible(getCurrentPlayer().getHand());
int tradeAmount = Math.min(getCurrentPlayer().getHand().size(), this.deck.remaining());
if (this.board.isEmpty()) {
tradeAmount = 0;
}
if (tradeAmount == 0 && !putPossible) {
//Pass
Logger.debug("TURN PASSED!");
} else {
Board.MoveType movetype;
if (tradeAmount > 0 && putPossible) {
movetype = getCurrentPlayer().getMoveType();
} else {
if (tradeAmount > 0) {
movetype = Board.MoveType.TRADE;
} else {
movetype = Board.MoveType.PUT;
}
}
if (movetype == Board.MoveType.TRADE) { // ASK TRADE
List<Tile> tradeMove = null;
while (tradeMove == null) {
tradeMove = getCurrentPlayer().getTradeMove();
if (tradeMove != null) {
if (tradeMove.size() < 1 || tradeMove.size() > tradeAmount) {
tradeMove = null;
} else {
List<Tile> phand = getCurrentPlayer().getHand();
for (Tile t : tradeMove) {
if (!phand.remove(t)) {
tradeMove = null;
break;
}
}
}
}
}
List<Tile> newTiles = new ArrayList<>();
for (int i = 1; i <= tradeMove.size(); i++) {
try {
newTiles.add(this.deck.drawTile());
} catch (EmptyDeckException e) {
Logger.fatal("Could not draw a tile while checks are finished. This is most likely a bug.");
}
}
for (Tile t : tradeMove) {
try {
getCurrentPlayer().removeTile(t);
} catch (TileDoesNotExistException e) {
Logger.error("Error: Could not remove tile from hand during trade, because it is not in the hand.");
}
this.deck.addTile(t);
}
getCurrentPlayer().addTile(newTiles);
} else { // ASK PUT
Map<Coordinate, Tile> putMove;
do {
putMove = getCurrentPlayer().getPutMove();
} while((putMove.size() < getCurrentPlayer().longestStreak() && this.board.isEmpty()) || !this.board.validateMove(putMove));
int score = this.board.doMove(putMove);
if (score > 0) {
getCurrentPlayer().addScore(score);
try {
getCurrentPlayer().removeTile(new ArrayList<>(putMove.values()));
} catch (TileDoesNotExistException e) {
Logger.fatal("ERROR: Tile put was not in player hand.");
e.printStackTrace();
}
}
}
}
}
/**
* Checks if a game has ended.
* @return Boolean if a game has ended.
*/
private boolean isEnded() {
if (getCurrentPlayer().getHand().size() <= 0) {
return true;
}
if (getDeckRemaining() <= 0) {
boolean checker = true;
for (Player p : getPlayers()) {
if (this.board.isPutPossible(p.getHand())) {
checker = false;
}
}
if (checker) {
return true;
}
}
return false;
}
/**
* Calculates the next player and puts it in playerTurn.
*/
private void nextPlayer() {
playerTurn = (playerTurn + 1) % playerList.size();
}
/**
* Get a copy of the board.
* @return The copied board.
*/
public Board getBoardCopy() {
return this.board.getCopy();
}
/**
* Returns the player who is on turn from the playerList.
* @return The player who is on turn.
*/
public Player getCurrentPlayer() {
return this.playerList.get(this.playerTurn);
}
public void setCurrentPlayer(Player p) {
playerTurn = playerList.indexOf(p);
}
/**
* Get the list of players taking part in the game.
* @return The list of players taking part in the game.
*/
public List<Player> getPlayers() { return this.playerList; }
/**
* Get the amount of tiles remaining in the deck.
* @return The amount of tiles remaining in the deck.s
*/
public int getDeckRemaining() { return this.deck.remaining(); }
/**
* Returns the current User Interface.
* @return The current User Interface.
*/
public TextUserInterface getUI() { return ui; }
/**
* Puts a tile on the board without further checking. This is used for being a slave of the server, according to the Protocol.
* @param c The Coordinate to put the Tile on.
* @param t The Tile to put on the Board.
*/
public void put(Coordinate c, Tile t) { board.put(c, t); }
/**
* Returns the Deck of the current game.
* @return The Deck of the current game.
*/
public Deck getDeck() { return deck; }
}
| true
|
5af77006dc22dc99f0d890c5bae3685849a3f13f
|
Java
|
Thiagopg7/prosangue
|
/ProSangue/src/persistencia/DoadorBD.java
|
UTF-8
| 7,424
| 2.3125
| 2
|
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package persistencia;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javax.swing.JOptionPane;
import objetos.Doador;
/**
*
* @author PMPALMEIRA15
*/
public class DoadorBD {
public Banco conexao;
public DoadorBD() {
conexao = new Banco();
}
// private int id;
// private int fkDoador;
// private boolean hepatiteB;
// private boolean hepatiteC;
// private boolean chagas;
// private boolean sifilis;
// private boolean aids;
// private boolean htlv;
// private boolean testeAnemia;
// private boolean triagemClinica;
// private Timestamp horario;
// private String imunohematologia;
public void cadastrar(Doador doador) {
try {
conexao.conectar();
Statement declaracao = conexao.con.createStatement();
declaracao.executeUpdate("INSERT INTO Doador (nome, endereco, data_nascimento, nome_pai, nome_mae, rg, tipo_sangue, sexo) " + "VALUES('"
+ doador.getNome() + "','"
+ doador.getEndereco() + "','"
+ doador.getDataNascimento() + "','"
+ doador.getPai() + "','"
+ doador.getMae() + "','"
+ doador.getRg() + "','"
+ doador.getTipoSangue() + "','"
+ doador.getSexo() + "')");
conexao.desconectar();
JOptionPane.showMessageDialog(null, "Cadastro feito com sucesso."); //Mensagem de confirmação da operação
} catch (SQLException ex) {
Logger.getLogger(DoadorBD.class.getName()).log(Level.SEVERE, null, ex);
JOptionPane.showMessageDialog(null, "Número de doador já cadastrado. Tente novamente.", "Número inválido", JOptionPane.ERROR_MESSAGE);
}
}
public ObservableList<Doador> buscarTodosBD() throws SQLException {
ObservableList<Doador> doadorList = FXCollections.observableArrayList();
ResultSet consulta;
conexao.conectar();
Statement declaracao;
try {
declaracao = conexao.con.createStatement();
consulta = declaracao.executeQuery("SELECT * FROM Doador");
while (consulta.next()) {
Doador doador = new Doador();
doador.setID(consulta.getInt("id"));
doador.setDataNascimento(consulta.getDate("data_nascimento"));
doador.setNome(consulta.getString("nome"));
doador.setEndereco(consulta.getString("endereco"));
doador.setPai(consulta.getString("nome_pai"));
doador.setMae(consulta.getString("nome_mae"));
doador.setRg(consulta.getString("rg"));
doador.setTipoSangue(consulta.getString("tipo_sangue"));
doador.setUltimaDoacao(consulta.getTimestamp("ultima_doacao"));
doador.setSexo(consulta.getString("sexo"));
doadorList.add(doador);
}
conexao.desconectar();
} catch (SQLException ex) {
Logger.getLogger(DoadorBD.class.getName()).log(Level.SEVERE, null, ex);
}
return doadorList;
}
public Doador buscarIndividualBD(int ID) {
try {
Doador doador = new Doador();
conexao.conectar();
ResultSet consulta;
Statement declaracao = conexao.con.createStatement();
consulta = declaracao.executeQuery("SELECT * FROM Doador WHERE id =" + ID);
while (consulta.next()) {
doador.setID(consulta.getInt("id"));
doador.setDataNascimento(consulta.getDate("data_nascimento"));
doador.setNome(consulta.getString("nome"));
doador.setEndereco(consulta.getString("endereco"));
doador.setPai(consulta.getString("nome_pai"));
doador.setMae(consulta.getString("nome_mae"));
doador.setRg(consulta.getString("rg"));
doador.setTipoSangue(consulta.getString("tipo_sangue"));
doador.setUltimaDoacao(consulta.getTimestamp("ultima_doacao"));
doador.setSexo(consulta.getString("sexo"));
}
//System.out.println("Resultado da busca - IDDoador:" + doador.getID() + ". Lugares:" + doador.getLugares() + ". Ocupada:" + doador.getOcupada());
conexao.desconectar();
return doador;
} catch (SQLException ex) {
Logger.getLogger(DoadorBD.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
public void alterar(Doador doador) {
try {
conexao.conectar();
Statement declaracao;
declaracao = conexao.con.createStatement();
if (doador.getUltimaDoacao() != null) {
declaracao.executeUpdate("UPDATE doador SET nome = '" + doador.getNome()
+ "', data_nascimento ='" + doador.getDataNascimento()
+ "', endereco ='" + doador.getEndereco()
+ "', nome_pai ='" + doador.getPai()
+ "', nome_mae ='" + doador.getMae()
+ "', rg ='" + doador.getRg()
+ "', ultima_doacao ='" + doador.getUltimaDoacao()
+ "', tipo_sangue ='" + doador.getTipoSangue()
+ "', sexo ='" + doador.getSexo()
+ "' WHERE id = " + doador.getID());
} else {
declaracao.executeUpdate("UPDATE doador SET nome = '" + doador.getNome()
+ "', data_nascimento ='" + doador.getDataNascimento()
+ "', endereco ='" + doador.getEndereco()
+ "', nome_pai ='" + doador.getPai()
+ "', nome_mae ='" + doador.getMae()
+ "', rg ='" + doador.getRg()
+ "', tipo_sangue ='" + doador.getTipoSangue()
+ "', sexo ='" + doador.getSexo()
+ "' WHERE id = " + doador.getID());
}
conexao.desconectar();
JOptionPane.showMessageDialog(null, "Alteração da doador " + doador.getID() + " feita com sucesso."); //Mensagem de confirmação
} catch (SQLException ex) {
Logger.getLogger(DoadorBD.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void excluir(Doador doador) {
try {
conexao.conectar();
Statement declaracao = conexao.con.createStatement();
declaracao.executeUpdate("DELETE FROM doador WHERE id = " + doador.getID());
conexao.desconectar();
JOptionPane.showMessageDialog(null, "Doador " + doador.getID() + " excluída com sucesso."); //Mensagem de confirmação da operação
} catch (SQLException ex) {
Logger.getLogger(DoadorBD.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
| true
|
55b68ae8a7086f45f253a5ad5e4ad836ccbdefc3
|
Java
|
gxtaillon/Antiyoy-1
|
/core/src/yio/tro/antiyoy/behaviors/RbCampaignLevel.java
|
UTF-8
| 361
| 1.734375
| 2
|
[] |
no_license
|
package yio.tro.antiyoy.behaviors;
import yio.tro.antiyoy.ButtonLighty;
/**
* Created by ivan on 18.11.2015.
*/
public class RbCampaignLevel extends ReactBehavior {
@Override
public void reactAction(ButtonLighty buttonLighty) {
getGameController(buttonLighty).loadCampaignLevel(getYioGdxGame(buttonLighty).getSelectedLevelIndex());
}
}
| true
|
dbf303a77900c6fc9dc0818ccaba8fb01cc82be5
|
Java
|
taoshihan1991/javademo
|
/CollectionDemo/mapDemo.java
|
GB18030
| 2,103
| 4.15625
| 4
|
[] |
no_license
|
/*
Map:һһԪ
mapΪ˫м CollectionΪм
mapд洢ľǼֵ
mapб뱣֤Ψһ
÷:
1.
value put(key,value);
2.ж
boolean isEmpty()
boolean containskey()
boolean containsValue()
3.ɾ
void clear();map
value remove(key);ָkeyɾֵ
4.ȡ
value get(key)
int size() ; ȡֵԵĸ
*/
import java.util.Map;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
public class mapDemo{
public static void main(String[] args){
Map<Integer,String> map=new HashMap<Integer,String>();
//method(map);
//method2(map);
method3(map);
}
public static void method(Map<Integer,String> map){
System.out.println(map.put(8,"xiaoming"));//null
System.out.println(map.put(9,"xiaoming"));//null
System.out.println(map);//{8=xiaoming, 9=xiaoming}
}
public static void method2(Map<Integer,String> map){
map.put(1,"taoshihan1");
map.put(2,"taoshihan2");
map.put(3,"taoshihan3");
map.put(4,"taoshihan4");
/*
ȡmapеԪ
ԭ:ͨkeySetȡmapеļڵSet
ٶÿһͨMapϵgetȡӦֵ
*/
Set<Integer> keySet=map.keySet();
Iterator it=keySet.iterator();
while(it.hasNext()){
Integer key=(Integer)it.next();
String value=map.get(key);
System.out.println(key+":"+value);
}
}
public static void method3(Map<Integer,String> map){
map.put(1,"taoshihan1");
map.put(2,"taoshihan2");
map.put(3,"taoshihan3");
map.put(4,"taoshihan4");
/*
ȡmapеԪ
ԭ:ͨentrySetȡmapӳϵڵSet
ٶSetϽеȡӳϵ,ȻgetKey() getValue
*/
Set<Map.Entry<Integer,String>> entrySet=map.entrySet();
Iterator it=entrySet.iterator();
while(it.hasNext()){
Map.Entry<Integer,String> me=(Map.Entry<Integer,String>)it.next();
Integer key=me.getKey();
String value=me.getValue();
System.out.println(key+":"+value);
}
}
}
| true
|
742b9fd36835ba37621903b671e1cc698813e801
|
Java
|
scrumdod/DB
|
/src/filesystem/FileSystemItemQuerier.java
|
UTF-8
| 4,728
| 3.09375
| 3
|
[] |
no_license
|
package filesystem;
import java.util.ArrayList;
import java.util.Iterator;
/**Responsibility:
* - Is able to query a file system item from any given path
* (e.g. Directory-Object "Temp" from "C:\temp")
*/
class FileSystemItemQuerier {
IDrive currentDrive;
public FileSystemItemQuerier(IDrive currentDrive) {
this.currentDrive = currentDrive;
}
public FileSystemItem getItemFromPath(String givenItemPath) {
String givenItemPathPatched = cleanItemPathString(givenItemPath);
if(isSpecialDirectory(givenItemPathPatched))
return getItemFromSpecialDirectory(givenItemPathPatched);
givenItemPathPatched = makeAbsolutePathFromRelative(givenItemPathPatched);
return findMoreComplexPathsRecursive(givenItemPathPatched, currentDrive.getCurrentDirectory());
}
private String cleanItemPathString(String givenItemPath) {
String givenItemPathPatched = replaceForwardWithBackwardSlash(givenItemPath);
givenItemPathPatched = removeEndingBacklash(givenItemPathPatched);
givenItemPathPatched = expandPointBacklash(givenItemPathPatched); // ".\"
givenItemPathPatched = expandPointPointBacklash(givenItemPathPatched); // "..\"
return givenItemPathPatched;
}
private String replaceForwardWithBackwardSlash(String givenItemPath) {
return givenItemPath.replace('/', '\\');
}
private String removeEndingBacklash(String givenItemPath) {
givenItemPath = givenItemPath.trim();
if( givenItemPath.charAt(givenItemPath.length()-1) == '\\'
&& givenItemPath.length() >= 2) {
givenItemPath = givenItemPath.substring(0, givenItemPath.length()-1);
}
return givenItemPath;
}
private String expandPointBacklash(String givenItemPath) {
if(givenItemPath.length() >= 2) {
if(givenItemPath.substring(0, 2).compareTo(".\\") == 0) {
givenItemPath = givenItemPath.substring(2, givenItemPath.length());
}
}
return givenItemPath;
}
private String expandPointPointBacklash(String givenItemPath) {
if(givenItemPath.length() >= 3) {
if(givenItemPath.substring(0, 3).compareTo("..\\") == 0) {
StringBuilder temp = new StringBuilder();
temp.append(getParentDirectorysAbsolutePath());
temp.append("\\");
temp.append(givenItemPath.substring(3, givenItemPath.length()));
givenItemPath = temp.toString();
}
}
return givenItemPath;
}
private String getParentDirectorysAbsolutePath() {
return currentDrive.getCurrentDirectory().getParent().getPath();
}
private String makeAbsolutePathFromRelative(String givenItemPath) {
if(givenItemPath.charAt(0) == '\\') {
return currentDrive.getDriveName() + givenItemPath;
}
if(givenItemPath.length() == 1 || givenItemPath.charAt(1) != ':') {
return currentDrive.getCurrentDirectory() + "\\" + givenItemPath;
}
return givenItemPath;
}
private boolean isSpecialDirectory(String givenItemPath) {
if(isRootPath(givenItemPath))
return true;
if(isCurrentDirectory(givenItemPath))
return true;
if(isParentDirectory(givenItemPath))
return true;
return false;
}
private FileSystemItem getItemFromSpecialDirectory(String givenItemPath) {
if(isRootPath(givenItemPath)) {
return currentDrive.getRootDirectory();
}
if(isCurrentDirectory(givenItemPath)) {
return currentDrive.getCurrentDirectory();
}
if(isParentDirectory(givenItemPath)) {
Directory parent = currentDrive.getCurrentDirectory().getParent();
if(parent == null) { // Case if current directory is already root
parent = currentDrive.getRootDirectory();
}
return parent;
}
// Neither Root or Parent directory: Call isSpecialDirectory() before
throw new IllegalStateException();
}
private boolean isRootPath(String givenItemPath) {
if(givenItemPath.compareTo("\\") == 0) return true;
if(givenItemPath.compareTo("C:") == 0) return true;
if(givenItemPath.compareTo("C:\\") == 0) return true;
return false;
}
private boolean isCurrentDirectory(String givenItemPath) {
return givenItemPath.compareTo(".") == 0 ? true : false;
}
private boolean isParentDirectory(String givenItemPath) {
return givenItemPath.compareTo("..") == 0 ? true : false;
}
private FileSystemItem findMoreComplexPathsRecursive(String givenItemName, Directory directoryToLookup) {
ArrayList<FileSystemItem> content = directoryToLookup.getContent();
Iterator<FileSystemItem> it = content.iterator();
while(it.hasNext()) {
FileSystemItem item = it.next();
String pathName = item.getPath();
if(pathName.equalsIgnoreCase(givenItemName)) {
return item;
}
if(item.isDirectory() == true) {
FileSystemItem retVal = this.findMoreComplexPathsRecursive(givenItemName, (Directory)item);
if(retVal != null) {
return retVal;
}
}
}
return null;
}
}
| true
|
841893a1b1d8799a29dfa6a253d7b898be93d0b2
|
Java
|
PavelNiporka/Dependency-Injection
|
/src/main/java/ReadWriteObjectSerializable/WriteObject.java
|
UTF-8
| 1,187
| 3.265625
| 3
|
[] |
no_license
|
package ReadWriteObjectSerializable;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
public class WriteObject {
public static void main(String[] args) {
Person person1 = new Person(1, "Bob");
//ReadWriteObject.Person person2 = new ReadWriteObject.Person(2, "Mike");
// ReadWriteObject.Person[] people = {new ReadWriteObject.Person(1, "Bob"), new ReadWriteObject.Person(2, "Mike"), new ReadWriteObject.Person(3, "Tom")};
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("people.bin"))) {
// FileOutputStream fos = new FileOutputStream("people.bin");
// ObjectOutputStream oos = new ObjectOutputStream((fos));
// oos.writeObject(person1);
// oos.writeObject(person2);
// oos.close();
// oos.writeInt(people.length);
// for (ReadWriteObject.Person person : people) {
// oos.writeObject(person);
// }
oos.writeObject(person1);
// fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
| true
|
2005ff106a756db6717314e1c4ef13af97548c9f
|
Java
|
DA120B-Pang/OnlineShop
|
/src/zaar/admin/edit/PredicateFilters/product/FilterInterfacesProd.java
|
UTF-8
| 599
| 2.203125
| 2
|
[] |
no_license
|
package zaar.admin.edit.PredicateFilters.product;
import zaar.admin.edit.filterPopUps.CompareOperator;
import zaar.product.Product;
public class FilterInterfacesProd {
public interface SetFilterProduct {
public void filter(FilterActionProduct filter, boolean remove);
public void setPredicate();
}
public interface FilterActionProduct {
/**
* Predicate filter for Product
* @param p Product
* @return boolean
*/
public boolean Compare(Product p);
public void setFilter(SetFilterProduct setFilter);
}
}
| true
|
cb43b540167d5a88e60b04ae6baf8f92b6840b19
|
Java
|
mitul-garg/DSA
|
/src/DoublyLinkedList/Implementation.java
|
UTF-8
| 2,161
| 4
| 4
|
[] |
no_license
|
package DoublyLinkedList;
public class Implementation {
public static void main(String[] args) {
Node head = null;
printLL(head);
head = insertAtHead(head,20);
printLL(head);
head = insertAtHead(head,10);
printLL(head);
head = insertAtTail(head, 30);
printLL(head);
head = insertAtTail(head, 40);
printLL(head);
head = reverseLL(head);
printLL(head);
System.out.println(head.data + " Verifies that head is changed");
System.out.println("=============");
head = deleteFromHead(head);
printLL(head);
head = deleteFromTail(head);
printLL(head);
}
public static Node deleteFromTail (Node head) {
if (head == null || head.next == null)
return null;
Node curr;
for (curr=head; curr.next.next != null; curr=curr.next) {
}
curr.next = null;
return head;
}
public static Node deleteFromHead (Node head) {
if (head == null || head.next == null) {
return null;
}
head.next.prev = null;
return head.next;
}
public static Node reverseLL (Node head) {
if (head.next == null)
return head;
Node curr = head;
while (curr.next != null) {
Node temp = curr.next;
curr.next = curr.prev;
curr.prev = temp;
curr = curr.prev;
}
Node temp = curr.next;
curr.next = curr.prev;
curr.prev = temp;
return curr;
}
public static Node insertAtTail (Node head, int x) {
Node newNode = new Node(x);
if (head == null) {
return newNode;
}
Node curr;
for (curr=head; curr.next!=null; curr=curr.next) {
}
newNode.prev = curr;
curr.next = newNode;
return head;
}
public static Node insertAtHead (Node head, int x) {
Node newNode = new Node(x);
if (head == null) {
return newNode;
}
newNode.next = head;
head.prev = newNode;
return newNode;
}
public static void printLL (Node head) {
for (Node curr=head; curr!=null; curr=curr.next) {
System.out.println(curr.data);
}
System.out.println("=============");
}
}
class Node {
int data;
Node next;
Node prev;
Node (int data) {
this.data = data;
}
}
// Circular Doubly Linked List has tail.next = head and head.prev = tail and the operations can
// be done in a similar way.
| true
|
c6d8c5edd1e582e99203030ceb23fd3126282a51
|
Java
|
AkashiSeijyuurou/algorithm011-class02
|
/Week_04/robotSim.java
|
UTF-8
| 2,521
| 3.328125
| 3
|
[] |
no_license
|
//机器人在一个无限大小的网格上行走,从点 (0, 0) 处开始出发,面向北方。该机器人可以接收以下三种类型的命令:
//
//
// -2:向左转 90 度
// -1:向右转 90 度
// 1 <= x <= 9:向前移动 x 个单位长度
//
//
// 在网格上有一些格子被视为障碍物。
//
// 第 i 个障碍物位于网格点 (obstacles[i][0], obstacles[i][1])
//
// 机器人无法走到障碍物上,它将会停留在障碍物的前一个网格方块上,但仍然可以继续该路线的其余部分。
//
// 返回从原点到机器人所有经过的路径点(坐标为整数)的最大欧式距离的平方。
//
//
//
// 示例 1:
//
// 输入: commands = [4,-1,3], obstacles = []
//输出: 25
//解释: 机器人将会到达 (3, 4)
//
//
// 示例 2:
//
// 输入: commands = [4,-1,4,-2,4], obstacles = [[2,4]]
//输出: 65
//解释: 机器人在左转走到 (1, 8) 之前将被困在 (1, 4) 处
//
//
//
//
// 提示:
//
//
// 0 <= commands.length <= 10000
// 0 <= obstacles.length <= 10000
// -30000 <= obstacle[i][0] <= 30000
// -30000 <= obstacle[i][1] <= 30000
// 答案保证小于 2 ^ 31
//
// Related Topics 贪心算法
// 👍 101 👎 0
import java.util.HashSet;
import javafx.scene.effect.SepiaTone;
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public int robotSim(int[] commands, int[][] obstacles) {
int ans = 0;
int direction = 0; //0北 1东 2南 3西
int[][] add = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
int x = 0;
int y = 0;
Set<String> set = new HashSet<>();
for (int i = 0; i < obstacles.length; i++) {
set.add(obstacles[i][0] + "," + obstacles[i][1]);
}
for (int steps : commands) {
int new_x = 0;
int new_y = 0;
if (steps >= 0) {
for (int i = 0; i < steps; i++) {
new_x = x + add[direction][0];
new_y = y + add[direction][1];
if (set.contains(new_x + "," + new_y)) {
break;
}
x = new_x;
y = new_y;
ans = Math.max(ans, x * x + y * y);
}
}else {
direction = steps == -1 ? (direction + 1) % 4 : (direction + 3) % 4;
}
}
return ans;
}
}
//leetcode submit region end(Prohibit modification and deletion)
| true
|
dd433ec2486a598e6f329fbfb53717a8cdc57afe
|
Java
|
ymw520369/gaeagame
|
/LogicServer/src/main/java/com/gaea/game/logic/lhd/LHDMessageHandler.java
|
UTF-8
| 1,692
| 2.1875
| 2
|
[] |
no_license
|
package com.gaea.game.logic.lhd;
import com.gaea.game.core.ws.Command;
import com.gaea.game.core.ws.MessageType;
import com.gaea.game.logic.constant.MessageConst;
import com.gaea.game.logic.data.PlayerController;
import com.gaea.game.logic.manager.LogicLogger;
import com.gaea.game.logic.room.RoomController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* Created on 2017/8/30.
*
* @author Alan
* @since 1.0
*/
@Component
@MessageType(MessageConst.LHD.TYPE)
public class LHDMessageHandler {
@Autowired
LogicLogger logicLogger;
Logger log = LoggerFactory.getLogger(getClass());
@Command(MessageConst.LHD.REQ_BET)
public void bet(PlayerController playerController, BetMessage betMessage) {
log.debug("收到玩家押注信息,roleUid={},roleName={}", playerController.playerId, playerController.playerName);
logicLogger.logBet(playerController, betMessage);
RoomController roomController = playerController.roomController;
if (roomController != null && roomController.gameController != null) {
roomController.gameController.onMessage(playerController, betMessage);
}
}
@Command(MessageConst.LHD.REQ_LHD_STATUS_COUNTDOWN)
public void syncCountdown(PlayerController playerController, StatusMessage statusMessage) {
RoomController roomController = playerController.roomController;
if (roomController != null && roomController.gameController != null) {
roomController.gameController.onMessage(playerController, statusMessage);
}
}
}
| true
|
42bc60f0ee2988a47e8c59c22732be24fd5bca2f
|
Java
|
moutainhigh/gedapi
|
/update_borrow/src/main/java/com/resoft/multds/accounting/PLContract/service/PLContractService.java
|
UTF-8
| 3,243
| 1.625
| 2
|
[] |
no_license
|
package com.resoft.multds.accounting.PLContract.service;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.resoft.multds.accounting.PLContract.dao.PLContractDao;
import com.resoft.multds.accounting.PLContract.entity.PLContract;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.persistence.annotation.DbType;
import com.thinkgem.jeesite.common.service.CrudService;
import com.thinkgem.jeesite.modules.act.entity.MyMap;
@Service
@DbType("acc.dbType")
@Transactional(value = "ACC", readOnly = true)
public class PLContractService extends CrudService<PLContractDao, PLContract> {
public PLContract get(String id) {
return super.get(id);
}
public List<PLContract> findList(PLContract plContract) {
return super.findList(plContract);
}
public Page<PLContract> findPage(Page<PLContract> page, PLContract plContract) {
return super.findPage(page, plContract);
}
/**
* 查询详情页合同基本信息
*
* @param contractNo
* @return
*/
public List<MyMap> findCheckDailyContractBaseInfo(String contractNo) {
return super.dao.findCheckDailyContractBaseInfo(contractNo);
}
public Page<MyMap> getToCheck25PLContract(Page<MyMap> page, MyMap paramMap) {
paramMap.setPage(page);
page.setList(this.dao.getToCheck25PLContract(paramMap));
return page;
}
/**
* 抵(质)押物管理 合同信息
*
* @param page
* @param paramMap
* @return
*/
public Page<MyMap> findAssetContractList(Page<MyMap> page, MyMap paramMap) {
paramMap.setPage(page);
page.setList(super.dao.findAssetContractList(paramMap));
return page;
}
@Transactional(readOnly = false)
public void updateContractStatusByContractNo(Map<String, Object> param) {
this.dao.updateContractStatusByContractNo(param);
}
/**
* 获取指定合同未偿还金额
*/
public BigDecimal getOutStandingCapitalAmount(String contractNo) {
return this.dao.getOutStandingCapitalAmount(contractNo);
}
@Transactional(readOnly = false)
public void updateAccStaRepayPlanStatus(Map<String, String> param) {
this.dao.updateAccStaRepayPlanStatus(param);
}
@Transactional(readOnly = false)
public void insertAccDeductApply(Map<String, String> param) {
this.dao.insertAccDeductApply(param);
}
@Transactional(readOnly = false)
public void insertAccDeductResult(Map<String, String> param) {
this.dao.insertAccDeductResult(param);
}
public String getPeriodNumByContractNo(String contractNo) {
return this.dao.getPeriodNumByContractNo(contractNo);
}
/**
* 根据合同编号查询身份证号
*
* @param contractNo
* @return
*/
public List<String> findIdNumByContractNo(String contractNo) {
return super.dao.findIdNumByContractNo(contractNo);
}
public Map<String, Object> getAccStaContractStatusByContractNo(String contractNo) {
return this.dao.getAccStaContractStatusByContractNo(contractNo);
}
/**
* 根据合同编号查询合同信息
*
* @param contractNo
* @return
*/
public List<PLContract> findListByContractNo(String contractNo) {
return super.dao.findListByContractNo(contractNo);
}
}
| true
|
1bdec0553ac855d0430d0240b781064128a4fd6e
|
Java
|
Alfian878787/50AH-code
|
/hack023/src/com/manning/androidhacks/hack023/HackApplication.java
|
UTF-8
| 1,010
| 2.171875
| 2
|
[
"MIT"
] |
permissive
|
/*******************************************************************************
* Copyright (c) 2012 Manning
* See the file license.txt for copying permission.
******************************************************************************/
package com.manning.androidhacks.hack023;
import com.manning.androidhacks.hack023.authenticator.AuthenticatorActivity;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Application;
import android.content.Intent;
public class HackApplication extends Application {
public Account getCurrentAccount() {
AccountManager accountManager = AccountManager.get(this);
Account[] accounts = accountManager
.getAccountsByType(AuthenticatorActivity.PARAM_ACCOUNT_TYPE);
if (accounts.length > 0) {
return accounts[0];
} else {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
return null;
}
}
}
| true
|
897358a705854135f738c3b038fea72ebf16ad3b
|
Java
|
friedhelmensch/blindflug
|
/src/de/kapuzenholunder/germanwings/data/time/TimeRange.java
|
UTF-8
| 591
| 3.078125
| 3
|
[] |
no_license
|
package de.kapuzenholunder.germanwings.data.time;
public class TimeRange
{
Time minTimeInfo;
Time maxTimeInfo;
public TimeRange(Time minTime, Time maxTime)
{
if(minTime == null || maxTime == null) throw new IllegalArgumentException("fromTime or toTime was null");
if(maxTime.isSmaller(minTime)) throw new IllegalArgumentException("from must be smaller than to");
this.minTimeInfo = minTime;
this.maxTimeInfo = maxTime;
}
public Time getMinTime()
{
return this.minTimeInfo;
}
public Time getMaxTime()
{
return this.maxTimeInfo;
}
}
| true
|
90f332e19752f48609aedb67fa0b051edf247fc9
|
Java
|
Humblefool97/Rajeev_DataStructureAssignmentSolution
|
/src/com/greatlearning/assignment3/modifiedBST/Driver.java
|
UTF-8
| 528
| 2.96875
| 3
|
[] |
no_license
|
package com.greatlearning.assignment3.modifiedBST;
public class Driver {
public static void main(String[] args) {
ModifyBST instanse = new ModifyBST();
ModifyBST.Node node = new ModifyBST.Node(50);
node.left = new ModifyBST.Node(30);
node.right = new ModifyBST.Node(60);
node.left.left = new ModifyBST.Node(10);
node.left.right = new ModifyBST.Node(40);
instanse.constructRightSkewedTree(node);
instanse.printTree(instanse.getSkewedTreeRootNode());
}
}
| true
|
9ba8f57811749757bcd40def2ac4377199a507a2
|
Java
|
onap-oof-pci-poc/ccsdk
|
/features/sdnr/wt/odlux/core/provider/src/test/java/org/onap/ccsdk/features/sdnr/odlux/test/TestBundleLoaderImpl.java
|
UTF-8
| 3,005
| 1.835938
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*******************************************************************************
* ============LICENSE_START========================================================================
* ONAP : ccsdk feature sdnr wt
* =================================================================================================
* Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved.
* =================================================================================================
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
* ============LICENSE_END==========================================================================
******************************************************************************/
package org.onap.ccsdk.features.sdnr.odlux.test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import org.onap.ccsdk.features.sdnr.wt.odlux.OdluxBundleLoaderImpl;
import org.onap.ccsdk.features.sdnr.wt.odlux.model.bundles.OdluxBundle;
import org.onap.ccsdk.features.sdnr.wt.odlux.model.bundles.OdluxBundleLoader;
public class TestBundleLoaderImpl {
@Test
public void test() {
OdluxBundleLoader loader = OdluxBundleLoaderImpl.getInstance();
int loaded = loader.getNumberOfBundles();
OdluxBundle bundle1 = new OdluxBundle();
bundle1.setBundleName("b1");
bundle1.setIndex(0);
bundle1.setLoader(loader);
OdluxBundle bundle2 = new OdluxBundle();
bundle2.setBundleName("b2");
bundle2.setIndex(55);
bundle2.setLoader(loader);
bundle1.initialize();
bundle2.initialize();
assertNotNull(bundle1.getResourceFileContent("index.html"));
assertNotNull(bundle2.getResourceFileContent("index2.html"));
assertEquals(loaded+2, loader.getNumberOfBundles());
loader.addBundle(bundle1);
loader.addBundle(bundle2);
assertEquals(loaded+2, loader.getNumberOfBundles());
loader.removeBundle(bundle1);
loader.removeBundle(bundle2);
assertEquals(loaded, loader.getNumberOfBundles());
assertTrue(bundle1.hasResource("index.html"));
assertTrue(bundle2.hasResource("index2.html"));
assertNotNull(bundle1.getLoader());
assertEquals(0,bundle1.getIndex());
bundle1.clean();
bundle2.clean();
assertEquals(loaded,loader.getNumberOfBundles());
}
}
| true
|
8547569a880494e792036290f6c4e390c1737fe5
|
Java
|
mehdi-mbl/NTM
|
/src/test/java/uia/NeuralTuringMachineTest.java
|
UTF-8
| 2,899
| 3.09375
| 3
|
[] |
no_license
|
package uia;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import uia.activation.Sigmoid;
import uia.ntm.NeuralTuringMachine;
import uia.run.RunSequenceLearner;
import uia.sequence.XORSequenceGenerator;
import java.util.Arrays;
public class NeuralTuringMachineTest {
RunSequenceLearner sequenceLearner;
@Before
public void setUp() throws Exception {
/*
Here set the parameters of the NTM:
1st parameter: Size of you input data vector
2nd parameter: number of column in the memory. Should match the input data vector size.
3rd parameter: number of raws in the memory. usually matches your data size.
4th parameter: number of heads you want to have.
5th parameter: The number of nodes in the hidden layer of the controller
6th parameter: The training data. I have some examples. You can generate your own data.
To do that create a class that implements SequenceGenerator.java
interface and implement the generateSequence function. There you can generate any random
data or import data from a file.
7th parameter: Select the activation function. I have only implemented a sigmoid activation which works just fine.
But you can implement your own as long as it implements ActivationFunction.java interface.
8th parameter: Set the error bellow which the learning process stops.
*/
sequenceLearner= new RunSequenceLearner(8,8, 32,
1, 64, new XORSequenceGenerator(), new Sigmoid(), 0.01);
}
@After
public void tearDown() throws Exception {
}
@Test
public void trainNTM() throws Exception{
/*
Here is the function that trains the NTM
To print the memory and head, set verbose to True
*/
sequenceLearner.runNTM(false);
}
@Test
public void trainAndTestNTM() throws Exception{
/*
Here is the function that trains and test the NTM
*/
// First train the NTM
sequenceLearner.runNTM(false);
NeuralTuringMachine ntm = new NeuralTuringMachine(sequenceLearner.machine);
// Get your test data. Same here as explained in 6th parameter
XORSequenceGenerator test= new XORSequenceGenerator();
test.generateSequence(1,8);
System.out.println("NTM Test");
// Get your output
System.out.println("input= "+ Arrays.toString(test.getInput()[0]));
ntm.process(test.getInput()[0]);
double[] output =ntm.getOutput();
//Round up output elements
for (int i=0; i <output.length;i++) {
output[i]=(double) Math.round(output[i]*100)/100;
}
//Print output
System.out.println("Output "+Arrays.toString(output));
System.out.println("Ideal "+Arrays.toString(test.getOutput()[0]));
}
}
| true
|
8788a1f0d222d8dce1abe15edc2c8bcbd2b7f673
|
Java
|
Gnxela/JavaDiscordBot
|
/src/bot/util/StreamUtil.java
|
UTF-8
| 469
| 2.34375
| 2
|
[] |
no_license
|
package bot.util;
import net.dv8tion.jda.api.entities.MessageEmbed;
import java.util.Map;
public class StreamUtil {
public static MessageEmbed.Field entryToField(Map.Entry<String, String> entry) {
return new MessageEmbed.Field(entry.getKey(), entry.getValue(), false, true);
}
public static MessageEmbed.Field entryToFieldInline(Map.Entry<String, Object> entry) {
return new MessageEmbed.Field(entry.getKey(), entry.getValue().toString(), true, true);
}
}
| true
|
94ea706781aa2b3330ae6feebb2ddbd2b9ed68b2
|
Java
|
klim705/checkers-online
|
/src/checkers/CheckersServer.java
|
UTF-8
| 7,682
| 2.640625
| 3
|
[] |
no_license
|
package checkers;
import com.esotericsoftware.kryonet.Connection;
import com.esotericsoftware.kryonet.Listener;
import com.esotericsoftware.kryonet.Server;
import com.esotericsoftware.minlog.Log;
import java.io.IOException;
public class CheckersServer {
Server server;
int numPlayers = 0;
int numRestarts = 0; // keeps track of how many clients opted to restart the game
public CheckersServer(int port) throws IOException {
server = new Server() {
protected Connection newConnection() {
return new CheckersConnection();
}
};
Network.register(server);
server.addListener(new Listener() {
public void received(Connection c, Object object) {
CheckersConnection connection = (CheckersConnection) c;
// code to be executed if there is new player connection
if (object instanceof Network.NewConnect) {
if (numPlayers < 2) {
if (numPlayers == 0) {
// set player color red
// Pl
((CheckersConnection) c).color = "red";
Network.Player networkPlayer = new Network.Player();
networkPlayer.playerColor = Piece.Color.RED;
server.sendToTCP(connection.getID(), networkPlayer);
} else {
// set player color black
((CheckersConnection) c).color = "black";
Network.Player networkPlayer = new Network.Player();
networkPlayer.playerColor = Piece.Color.BLACK;
server.sendToTCP(connection.getID(), networkPlayer);
}
numPlayers++;
System.out.println(((CheckersConnection) c).color + " is connected");
if (numPlayers == 2) {
Network.NetBoard netBoard = new Network.NetBoard();
netBoard.board = new Board();
server.sendToAllTCP(netBoard);
}
} else {
// tell the client trying to connect that the game's full
System.out.println("Client attempted to connect to full game");
Network.EndGame endGame = new Network.EndGame();
endGame.reason = "full";
server.sendToTCP(connection.getID(), endGame);
}
return;
}
// code to be executed if the object received is a NetBoard
if (object instanceof Network.NetBoard) {
// Relay the board to the other client
Network.NetBoard updateBoard = (Network.NetBoard) object;
server.sendToAllExceptTCP(connection.getID(), updateBoard);
Network.EndGame endGameRed = new Network.EndGame();
Network.EndGame endGameBlack = new Network.EndGame();
if (connection.color.equals("red")) {
if (updateBoard.board.areAllCaptured(Piece.Color.RED) || !updateBoard.board.canPlayerMove(Piece.Color.RED)) {
endGameRed.reason = "loss";
server.sendToTCP(connection.getID(), endGameRed);
endGameBlack.reason = "win";
server.sendToAllExceptTCP(connection.getID(), endGameBlack);
} else if (updateBoard.board.areAllCaptured(Piece.Color.BLACK) || !updateBoard.board.canPlayerMove(Piece.Color.BLACK)) {
endGameRed.reason = "win";
server.sendToTCP(connection.getID(), endGameRed);
endGameBlack.reason = "loss";
server.sendToAllExceptTCP(connection.getID(), endGameBlack);
}
} else {
if (updateBoard.board.areAllCaptured(Piece.Color.RED) || !updateBoard.board.canPlayerMove(Piece.Color.RED)) {
endGameRed.reason = "win";
server.sendToTCP(connection.getID(), endGameRed);
endGameBlack.reason = "loss";
server.sendToAllExceptTCP(connection.getID(), endGameBlack);
} else if (updateBoard.board.areAllCaptured(Piece.Color.BLACK) || !updateBoard.board.canPlayerMove(Piece.Color.BLACK)) {
endGameRed.reason = "loss";
server.sendToTCP(connection.getID(), endGameRed);
endGameBlack.reason = "win";
server.sendToAllExceptTCP(connection.getID(), endGameBlack);
}
}
return;
}
if (object instanceof Network.EndGame) {
Network.EndGame endGame = (Network.EndGame) object;
// relay the reason to the client for it to process
server.sendToAllExceptTCP(connection.getID(), endGame);
if (endGame.reason.equals("forfeit")) {
Network.EndGame selfForfeit = new Network.EndGame();
selfForfeit.reason = "selfforfeit";
server.sendToTCP(connection.getID(), selfForfeit);
}
return;
}
if (object instanceof Network.RestartGame) {
Network.RestartGame restartGame = (Network.RestartGame) object;
if (restartGame.restart) {
numRestarts++;
if (numRestarts == 1) {
// other client still needs to decide to restart or not
} else if (numRestarts == 2) {
numRestarts = 0; // reset the counter
Network.NetBoard netBoard = new Network.NetBoard();
netBoard.board = new Board();
server.sendToAllTCP(netBoard);
}
}
}
}
// code to be executed if a client disconnects
public void disconnected(Connection c) {
CheckersConnection connection = (CheckersConnection) c;
if (connection.color != null) {
//insert code to be executed here
System.out.println(((CheckersConnection) c).color + " disconnected");
numPlayers--;
Network.EndGame endGame = new Network.EndGame();
endGame.reason = "disconnect";
server.sendToAllExceptTCP(connection.getID(), endGame);
}
}
});
server.bind(port);
server.start();
System.out.println("Server started");
}
static class CheckersConnection extends Connection {
public String color;
}
public static void main(String[] args) throws IOException {
int port;
if (args.length == 1) {
port = Integer.parseInt(args[0]);
} else {
System.out.println("Must provide a port number");
return;
}
Log.set(Log.LEVEL_DEBUG);
new CheckersServer(port);
}
}
| true
|
2c186fb469c77eb918b27b4fee3629ca24176af3
|
Java
|
hayu4998/Java_Practice
|
/CoinToss.java
|
UTF-8
| 443
| 3.4375
| 3
|
[] |
no_license
|
import java.util.Scanner;
public class CoinToss{
public static void main(String[] args){
System.out.println("Coin Toss Simulation");
System.out.println("[1]Head\t[2]Tail");
if(((byte)Math.random()*2+1) == get_bet()){
System.out.println("You Win");
}else{
System.out.println("You Lose");
}
}
static byte get_bet(){
System.out.println("What is your bet");
Scanner in = new Scanner(System.in);
return in.nextByte();
}
}
| true
|
cd975fa739bca13d67e33e1893ddc927d31f32b1
|
Java
|
martijnmeeldijk/24_Meeldijk_Pauwels_Verbist_KassaApp_2019
|
/src/controller/KassaViewController.java
|
UTF-8
| 5,416
| 2.515625
| 3
|
[] |
no_license
|
package controller;
import javafx.collections.ObservableList;
import model.artikel.Artikel;
import model.artikel.LogObject;
import model.Winkel;
import model.bestelling.Bestelling;
import model.bestelling.state.Actief;
import model.bestelling.state.Afgesloten;
import model.kasticket.TicketFacade;
import model.korting.Korting;
import view.panels.KassaOverviewPane;
public class KassaViewController implements Observer {
private KassaOverviewPane kassaOverviewPane;
private Winkel winkel;
public KassaViewController(Winkel winkel) {
this.winkel = winkel;
winkel.add(this);
}
private double getKorting() {
double totaal = 0.0;
for (Korting k : winkel.getKortingen()) {
totaal += k.getKorting(AantalList.getList(winkel));
}
return totaal;
}
private void setPrijzen() {
kassaOverviewPane.setPrijzen(String.valueOf(getOriginalPrice()),String.valueOf(getKorting()),String.valueOf(getOriginalPrice()-getKorting()));
}
private double getOriginalPrice() {
double totaal = 0.0;
for (Artikel artikel : getBestelling().getArtikels()) {
totaal += artikel.getVerkoopprijs();
}
return totaal;
}
public void setKassaView(KassaOverviewPane kassaOverviewPane) {
this.kassaOverviewPane = kassaOverviewPane;
}
public void addArtikkel(int code) {
if (getBestelling().itemBestaat(code)) {
winkel.addArtikel(code);
setPrijzen();
} else {
kassaOverviewPane.displayErrorMessage("niet bestaande code");
}
}
public void removeArtikkel(int code) {
if (getBestelling().itemBestaat(code)) {
winkel.removeArtikel(code);
setPrijzen();
} else {
kassaOverviewPane.displayErrorMessage("niet bestaande code");
}
}
public ObservableList<Artikel> getArtikels() {
return winkel.getActieveBestelling().getArtikels();
}
@Override
public void update() {
if (kassaOverviewPane != null) {
kassaOverviewPane.setArtikels(getArtikels());
viewLabelReset();
}
}
public void zetOnHold() {
try {
if (winkel.getpassiveBestelling() != null) {
kassaOverviewPane.displayErrorMessage("er is al een bestelling on hold");
} else {
if (winkel.getActieveBestelling().getArtikels().size() != 0) {
winkel.getActieveBestelling().zetOnHold();
winkel.addBestelling();
viewLabelReset();
winkel.notifyObserver();
} else {
kassaOverviewPane.displayErrorMessage("de bestelling is leeg");
}
}
} catch (Exception e) {
kassaOverviewPane.displayErrorMessage(e.getMessage());
}
}
public void zetActief() {
try {
if(winkel.getpassiveBestelling()!=null){
if (winkel.getActieveBestelling().getArtikels().size() == 0) {
winkel.removeActiveBestelling();
winkel.getpassiveBestelling().zetActief();
winkel.setTimeheld(0);
viewLabelReset();
winkel.notifyObserver();
} else {
kassaOverviewPane.displayErrorMessage("er is een verkoop bezig");
}
}
else {
kassaOverviewPane.displayErrorMessage("Geen on hold bestelling");
}
} catch (Exception e) {
kassaOverviewPane.displayErrorMessage(e.getMessage());
}
}
//geeft de andere bestelling terug als de eerste on hold staat
public Bestelling getBestelling() {
return winkel.getActieveBestelling();
}
public void annuleer() {
winkel.annuleerBestelling();
viewLabelReset();
winkel.notifyObserver();
}
private void viewLabelReset() {
setPrijzen();
}
public void handelBestellingAf() {
if (winkel.getActieveBestelling().getCurrentState() instanceof Actief) {
sluitAf();
} else if (winkel.getActieveBestelling().getCurrentState() instanceof Afgesloten) {
// hier moet de code voor wat er gebeurt als er op de betaal knop gedrukt wordt
LogObject logObject = new LogObject(getOriginalPrice(), getKorting(), (getOriginalPrice() - getKorting()));
winkel.addLog(logObject);
System.out.print(TicketFacade.makeTicket(winkel));
winkel.changeVooraadVoorAfgeslotenVooraad();
winkel.getActieveBestelling().getDataInMemory().saveData();
//alle on hold bestellingen moeten hun data nu nog refreshen!!
if(winkel.getpassiveBestelling()!=null){
winkel.getpassiveBestelling().getDataInMemory().loadData();
}
winkel.removeActiveBestelling();
winkel.addBestelling();
winkel.notifyObserver();
boolean verlopen = winkel.checkHoldBestelling();
if(verlopen) kassaOverviewPane.onHoldVerlopen();
}
}
private void sluitAf() {
try {
winkel.getActieveBestelling().sluitAf();
} catch (Exception e) {
kassaOverviewPane.displayErrorMessage(e.getMessage());
}
}
}
| true
|
2691f096276ddb9396af156f8cc2cf40b31e64e1
|
Java
|
bearcat926/microservicecloud
|
/services/service-user/model-cart/src/main/java/edu/bearcat/microservice/service/impl/CartServiceImpl.java
|
UTF-8
| 1,496
| 2.015625
| 2
|
[] |
no_license
|
package edu.bearcat.microservice.service.impl;
import edu.bearcat.microservice.dao.CartDao;
import edu.bearcat.microservice.entities.Cart;
import edu.bearcat.microservice.entities.ProductVO;
import edu.bearcat.microservice.service.ICartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* <p>
* 购物车表 服务实现类
* </p>
*
* @author haohao
* @since 2019-04-10
*/
@Service
public class CartServiceImpl implements ICartService {
@Autowired
private CartDao cartDao;
@Override
public Cart selectByIds(Cart cart) {
return cartDao.selectByIds(cart);
}
@Override
public Cart selectByCartId(Cart cart) {
return cartDao.selectByCartId(cart);
}
@Override
public boolean insertCart(Cart cart) {
return cartDao.insertCart(cart);
}
@Override
public boolean insertCartDetails(ProductVO productVO) {
return cartDao.insertCartDetails(productVO);
}
@Override
public boolean updateCart(Cart cart) {
return cartDao.updateCart(cart);
}
@Override
public boolean updateCartDetails(ProductVO productVO) {
return cartDao.updateCartDetails(productVO);
}
@Override
public boolean deleteCart(Cart cart) {
return cartDao.deleteCart(cart);
}
@Override
public boolean deleteCartDetails(ProductVO productVO) {
return cartDao.deleteCartDetails(productVO);
}
}
| true
|
2d4144a83a2bc9e377a3bbbc42c4faea5796daf9
|
Java
|
un097/wuxianchangchun
|
/SurfingScene3.0/src/cn/ffcs/surfingscene/road/RoadMainActivity.java
|
UTF-8
| 11,823
| 1.726563
| 2
|
[
"Apache-2.0"
] |
permissive
|
package cn.ffcs.surfingscene.road;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.LocalBroadcastManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationSet;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import cn.ffcs.surfingscene.R;
import cn.ffcs.surfingscene.common.Key;
import cn.ffcs.surfingscene.datamgr.RoadVideoListMgr;
import cn.ffcs.ui.tools.TopUtil;
import cn.ffcs.wisdom.tools.AppHelper;
import cn.ffcs.wisdom.tools.StringUtil;
import com.baidu.mapapi.map.MapView.LayoutParams;
public class RoadMainActivity extends GlobaleyeBaseGroupActivity {
private FrameLayout container;
private Button tab_1;
private Button tab_2;
private Button tab_3;
private Button tab_4;
private String title;
private String eyeType;
private boolean isNoRoad = false;
private LinearLayout tabLayout;
private static ImageView collectImage;
private static int[] tabLocation = new int[2];
private LinearLayout topLayout;
private static int topHeight;
private static int tabWidth;
private static int tabHeight;
private boolean first = true;
private List<View> viewList = new ArrayList<View>();
private View fourthView, oneView, oldView;
@Override
protected void initComponents() {
topLayout = (LinearLayout) findViewById(R.id.top);
tabLayout = (LinearLayout) findViewById(R.id.tab_layout);
container = (FrameLayout) findViewById(R.id.container);
collectImage = (ImageView) findViewById(R.id.collect_anim);
tab_1 = (Button) findViewById(R.id.tab_1);
tab_2 = (Button) findViewById(R.id.tab_2);
tab_3 = (Button) findViewById(R.id.tab_3);
tab_4 = (Button) findViewById(R.id.tab_4);
initTab(tab_1, tab_2, tab_3, tab_4);
}
/**
* 初始化tab
*
* @param view
*/
private void initTab(View... view) {
int width = AppHelper.getScreenWidth(mContext) / view.length;
for (int i = 0; i < view.length; i++) {
view[i].getLayoutParams().width = width;
view[i].setOnClickListener(new OnTabClickListener());
}
}
class OnTabClickListener implements OnClickListener {
@Override
public void onClick(View v) {
int id = v.getId();
if (id == R.id.tab_1) {
clickTab1();
} else if (id == R.id.tab_2) {
clickTab2();
} else if (id == R.id.tab_3) {
clickTab3();
} else if (id == R.id.tab_4) {
clickTab4();
}
}
}
/**
* 点击第一个按钮
*/
private void clickTab1() {
tab_1.setBackgroundResource(R.drawable.glo_tab_select);
tab_2.setBackgroundDrawable(null);
tab_3.setBackgroundDrawable(null);
tab_4.setBackgroundDrawable(null);
// container.addView(getLocalActivityManager().startActivity(
// "tab1",
// new Intent(mContext, OftenBlockedActivity.class).addFlags(
// Intent.FLAG_ACTIVITY_CLEAR_TOP).putExtras(getIntent().getExtras()))
// .getDecorView());
refreshView("tab1");
// refreshView(1);
// handler.sendEmptyMessage(1);
}
/**
* 点击按钮2
*/
private void clickTab2() {
tab_1.setBackgroundDrawable(null);
tab_2.setBackgroundResource(R.drawable.glo_tab_select);
tab_3.setBackgroundDrawable(null);
tab_4.setBackgroundDrawable(null);
// container.addView(getLocalActivityManager().startActivity(
// "tab2",
// new Intent(mContext, RoadMapActivity.class)
// .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
// .putExtras(getIntent().getExtras())).getDecorView());
refreshView("tab2");
// refreshView(2);
// handler.sendEmptyMessage(2);
}
/**
* 点击按钮3
*/
private void clickTab3() {
tab_1.setBackgroundDrawable(null);
tab_2.setBackgroundDrawable(null);
tab_3.setBackgroundResource(R.drawable.glo_tab_select);
tab_4.setBackgroundDrawable(null);
refreshView("tab3");
// refreshView(3);
// handler.sendEmptyMessage(3);
}
/**
* 点击按钮4
*/
private void clickTab4() {
tab_1.setBackgroundDrawable(null);
tab_2.setBackgroundDrawable(null);
tab_3.setBackgroundDrawable(null);
tab_4.setBackgroundResource(R.drawable.glo_tab_select);
// container.addView(getLocalActivityManager().startActivity(
// "tab4",
// new Intent(mContext, RoadCollectActivity.class).addFlags(
// Intent.FLAG_ACTIVITY_CLEAR_TOP).putExtras(getIntent().getExtras()))
// .getDecorView());
refreshView("tab4");
// refreshView(4);
// handler.sendEmptyMessage(4);
}
private void removeViews() {
if (oneView != null) {
container.removeView(oneView);
}
if (fourthView != null) {
container.removeView(fourthView);
}
}
@Override
protected void initData() {
// registerBackBroadcast();
eyeType = getIntent().getStringExtra(Key.K_GLO_TYPE);
if (eyeType != null) {
isNoRoad = true;
}
getIntent().putExtra(Key.K_IS_NO_ROAD, isNoRoad);
}
@Override
protected int getMainContentViewId() {
return R.layout.glo_act_road_main;
}
@Override
protected void setCustomTitleTop() {
title = getIntent().getStringExtra(Key.K_TITLE_NAME);
if (StringUtil.isEmpty(title)) {
title = getString(R.string.glo_road_video);
}
if (isNoRoad) {
tabLayout.setVisibility(View.GONE);
} else {
ImageView topRight = (ImageView) findViewById(R.id.top_right);
TopUtil.updateRight(topRight, R.drawable.glo_search);
topRight.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(mActivity, SearchResultActivity.class);
i.putExtras(getIntent().getExtras());
i.putExtra(Key.K_RETURN_TITLE, title);
startActivity(i);
}
});
}
TopUtil.updateTitle(mActivity, R.id.top_title, title);
}
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (first) {
first = false;
tab_4.getLocationOnScreen(tabLocation);
topHeight = topLayout.getHeight();
tabWidth = tab_4.getWidth();
tabHeight = tab_4.getHeight();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
clickTab1();
}
}, 50);
}
}
public static void startCollectAnim(int startX, int startY) {
AnimationSet set = new AnimationSet(true);
set.setInterpolator(new AccelerateDecelerateInterpolator());
set.setDuration(500);
set.setAnimationListener(new AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
collectImage.setVisibility(View.VISIBLE);
}
@Override
public void onAnimationRepeat(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
collectImage.setVisibility(View.GONE);
}
});
// 平移
TranslateAnimation translateAnimation = new TranslateAnimation(
TranslateAnimation.ABSOLUTE, startX,
TranslateAnimation.ABSOLUTE, tabLocation[0] + tabWidth / 2,
TranslateAnimation.ABSOLUTE, startY - topHeight,
TranslateAnimation.ABSOLUTE, tabLocation[1] - topHeight
- (tabHeight / 3));
// 渐变
AlphaAnimation alphaAnimation = new AlphaAnimation(1f, 0.3f);
set.addAnimation(translateAnimation);
set.addAnimation(alphaAnimation);
collectImage.startAnimation(set);
}
private void refreshView(String id) {
boolean flag = false; // 判断View是否存在
View historyView = null;
Activity historyActivity = getLocalActivityManager().getActivity(id);
if (historyActivity != null) {
historyView = historyActivity.getWindow().getDecorView();
} else {
historyView = createView(id);
}
for (int i = 0, size = viewList.size(); i < size; i++) {
View v = viewList.get(i);
if (null != v && !v.equals(historyView)) {
v.setVisibility(View.GONE);
} else if (null != v && v.equals(historyView)) {
v.setVisibility(View.VISIBLE);
flag = true;
}
}
if (!flag && historyView != null) {
// 加载Activity
container.addView(historyView, new LinearLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
viewList.add(historyView);
} else if (historyView != null) {
// 全部和收藏tab 涉及到动态变化,不缓存view了
removeViews();
if ("tab1".equals(id)) {
oneView = getLocalActivityManager().startActivity(
"tab1",
new Intent(mContext, MapGroupListActivity.class)
.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
.putExtras(getIntent().getExtras()))
.getDecorView();
container.addView(oneView);
} else if ("tab4".equals(id)) {
fourthView = getLocalActivityManager().startActivity(
"tab4",
new Intent(mContext, RoadCollectActivity.class)
.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
.putExtras(getIntent().getExtras()))
.getDecorView();
container.addView(fourthView);
}
}
}
// 新开线程加载点
private Handler handler = new Handler() {
public void handleMessage(Message msg) {
int id = msg.what;
if (1 == id) {
refreshView(1);
}
if (2 == id) {
refreshView(2);
}
if (3 == id) {
refreshView(3);
}
if (4 == id) {
refreshView(4);
}
};
};
private void refreshView(int id) {
if (oldView != null)
container.removeView(oldView);
View historyView = createView("tab" + id);
// 加载Activity
container.addView(historyView, new LinearLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
oldView = historyView;
}
private View createView(String id) {
View view = null;
// 全部
if ("tab1".equals(id)) {
view = getLocalActivityManager().startActivity(
"tab1",
new Intent(mContext, MapGroupListActivity.class).setFlags(
Intent.FLAG_ACTIVITY_CLEAR_TOP).putExtras(
getIntent().getExtras())).getDecorView();
oneView = view;
} else if ("tab2".equals(id)) {
view = getLocalActivityManager().startActivity(
"tab2",
new Intent(mContext, RoadMapActivity.class).setFlags(
Intent.FLAG_ACTIVITY_CLEAR_TOP).putExtras(
getIntent().getExtras())).getDecorView();
} else if ("tab3".equals(id)) {
// 常常堵
view = getLocalActivityManager().startActivity(
"tab3",
new Intent(mContext, OftenBlockedActivity.class).setFlags(
Intent.FLAG_ACTIVITY_CLEAR_TOP).putExtras(
getIntent().getExtras())).getDecorView();
} else if ("tab4".equals(id)) {
view = getLocalActivityManager().startActivity(
"tab4",
new Intent(mContext, RoadCollectActivity.class).setFlags(
Intent.FLAG_ACTIVITY_CLEAR_TOP).putExtras(
getIntent().getExtras())).getDecorView();
fourthView = view;
}
return view;
}
@Override
public void finish() {
super.finish();
RoadVideoListMgr.getInstance().clearData();// 清除缓存
}
// private BroadcastReceiver mBroadcastReceiver;
// private void registerBackBroadcast() {
// mBroadcastReceiver = new BackBroadcastReceiver();
// IntentFilter filter = new IntentFilter();
// filter.addAction("road_back_action");
// registerReceiver(mBroadcastReceiver, filter);
// }
//
// private class BackBroadcastReceiver extends BroadcastReceiver {
// @Override
// public void onReceive(Context context, Intent intent) {
// int resultCode = intent.getIntExtra("resultCode", 0);
// if (resultCode == 0) {
// clickTab1();
// } else if (resultCode == 1) {
// clickTab2();
// } else if (resultCode == 2) {
// clickTab3();
// } else if (resultCode == 3) {
// clickTab4();
// }
// }
// }
}
| true
|
3a35a7cbdc233de1c189ba164ea80b840d16ec9f
|
Java
|
anumshaikh/DataStructure
|
/src/stacks/StackUsingLinkedList.java
|
UTF-8
| 1,856
| 4.09375
| 4
|
[] |
no_license
|
package stacks;
public class StackUsingLinkedList {
Node top;
@Override
public String toString() {
return "StackUsingLinkedList [top=" + top + "]";
}
public StackUsingLinkedList() {
top = null;
}
static class Node {
String data;
Node next;
@Override
public String toString() {
return "Node [data=" + data + ", next=" + next + "]";
}
Node(String data) {
this.data = data;
this.next = null;
}
Node() {
this.data = null;
this.next = null;
}
}
public Boolean isEmpty() {
if (top == null)
return true;
else
return false;
}
public Boolean push(String element) {
Node node = new Node(element);
if (isEmpty()) {
top = node;
} else
{
node.next = top;
top = node;
}
return true;
}
public String pop() {
if (isEmpty())
{
System.out.println("Stack underflow");
return null;
}
String value = top.data;
if (top.next == null)
top = null;
else
top = top.next;
return value;
}
public String peek() {
if(!isEmpty()) {
return top.data;
}
else
{
System.out.println("Stack underflow");
return null;
}
}
public static void main(String[] args) {
StackUsingLinkedList stack = new StackUsingLinkedList();
System.out.println("Initial stack " + stack);
stack.push("Anum");
System.out.println("Add first element " + stack);
stack.push("Sara");
System.out.println("Add Second element " + stack);
System.out.println("peek at stack "+stack.peek());
stack.pop();
System.out.println("\nAfter first pop " + stack);
System.out.println("Is stack empty " + stack.isEmpty());
System.out.println("peek at stack "+stack.peek());
stack.pop();
System.out.println("\nAfter Second pop " + stack);
System.out.println("Is stack empty " + stack.isEmpty());
System.out.println("peek at stack "+stack.peek());
}
}
| true
|
20080a637f9ca8686fd36c2245be855259069d8d
|
Java
|
edersonjseder/FootballCheck
|
/SoccerCheck/app/src/main/java/com/soccer/soccercheck/listeners/OnCompetitionsItemSelectedListener.java
|
UTF-8
| 317
| 1.921875
| 2
|
[] |
no_license
|
package com.soccer.soccercheck.listeners;
import com.soccer.soccercheck.model.Competition;
/**
* Created by root on 06/11/16.
*/
public interface OnCompetitionsItemSelectedListener {
// called when user selects a contact
public void onCompetitionsItemSelected(Competition competition, int position);
}
| true
|
d9a69a50faacd7e0f561cad1295ad15443fd2ba7
|
Java
|
MaBiereEtMoi/mabiereetmoi-api
|
/src/main/java/com/mabiereetmoi/api/barcode/BarCodeController.java
|
UTF-8
| 904
| 2.171875
| 2
|
[] |
no_license
|
package com.mabiereetmoi.api.barcode;
import com.mabiereetmoi.api.beer.Beer;
import com.mabiereetmoi.api.beer.BeerConverter;
import com.mabiereetmoi.api.beer.BeerDto;
import lombok.AllArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@RestController
@AllArgsConstructor
@RequestMapping("/barcode")
public class BarCodeController {
private final BarCodeService barCodeService;
private final BeerConverter beerConverter;
@PostMapping
public ResponseEntity<BarCode> saveBarcode(@RequestBody BarCode barCode) {
return ResponseEntity.ok(barCodeService.saveBarcode(barCode));
}
@GetMapping("/{barCode}")
@CrossOrigin
public BeerDto getBeerByBarcode(@PathVariable String barCode){
return beerConverter.entityToDto(barCodeService.getBeerByBarCode(barCode));
}
}
| true
|
31bab1e8c53348941ba75bf0c182fb03e461524e
|
Java
|
xogus1107/Algorithm_sol
|
/java/토마토_백준.java
|
UTF-8
| 1,654
| 2.8125
| 3
|
[] |
no_license
|
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class Main {
static int N;
static int M;
static int H;
static int map[][][];
static int dx[] = {0,0,-1,1,0,0};
static int dy[] = {-1,1,0,0,0,0};
static int dz[] = {0,0,0,0,-1,1};
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
M = sc.nextInt();
N= sc.nextInt();
H= sc.nextInt();
map = new int[H][N][M];
int m = N*M*H;
Queue<tomato> q = new LinkedList<tomato>();
for (int i = 0; i < H; i++) {
for (int j = 0; j < N; j++) {
for (int k = 0; k < M; k++) {
map[i][j][k] = sc.nextInt();
if(map[i][j][k]==1) {
q.add(new tomato(i,j,k));
}
}
}
}
int count =0;
while(!q.isEmpty()) {
int length = q.size();
for(int i=0; i<length; i++) {
tomato node = q.poll();
for(int j=0; j<6; j++){
int nz= node.z+dz[j];
int ny= node.y +dy[j];
int nx =node.x +dx[j];
if(nx<0 ||ny<0|| nz<0 || nx>=M || ny>=N|| nz>=H) continue;
if(map[nz][ny][nx]==1 || map[nz][ny][nx]==-1) continue;
map[nz][ny][nx]=1;
q.add(new tomato(nz,ny,nx));
}
}
count++;
}
int flag=0;
for (int i = 0; i < H; i++) {
for (int j = 0; j < N; j++) {
for (int k = 0; k < M; k++) {
if(map[i][j][k]==0) {
flag = 1;
}
}
}
}
if(flag==1) {
System.out.println(-1);
}
else {
System.out.println(count-1);
}
}
}
class tomato{
int y;
int x;
int z;
public tomato(int z, int y, int x) {
this.x = x;
this.y = y;
this.z = z;
}
}
| true
|
325b05a72ea90739c5bc8b075ae0a6c8f840f16f
|
Java
|
kimth0719/objects
|
/Theater/Step1/src/com/theater/step9_2/Main.java
|
UTF-8
| 664
| 2.4375
| 2
|
[] |
no_license
|
package com.theater.step9_2;
import java.time.DayOfWeek;
import java.time.Duration;
import java.time.LocalTime;
public class Main {
public static void main() {
ServiceLocator.provide(new AmountDiscountPolicy(Money.wons(800),
new SequenceCondition(1),
new SequenceCondition(10),
new PeriodCondition(DayOfWeek.MONDAY, LocalTime.of(10, 0), LocalTime.of(11, 59)),
new PeriodCondition(DayOfWeek.THURSDAY, LocalTime.of(10,0), LocalTime.of(20, 59))
));
Movie avatar = new Movie("아바타",
Duration.ofMinutes(120),
Money.wons(10000));
}
}
| true
|
8aea9fb753e8e0a8ca99606ae1f69290cbb2c11f
|
Java
|
fangyana/test_project
|
/project/pro-system/src/main/java/com/f/pro/dto/dept/AddDeptDTO.java
|
UTF-8
| 917
| 1.929688
| 2
|
[] |
no_license
|
package com.f.pro.dto.dept;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* @Author: FangYN
* @Date: 2020/4/3
* @Description:
*/
@ApiModel
@Data
@EqualsAndHashCode(callSuper = false)
public class AddDeptDTO {
@ApiModelProperty(value = "部门名称")
private String name;
@ApiModelProperty(value = "上级部门id")
private Integer parentId;
@ApiModelProperty(value = "排序")
private Integer sort;
@ApiModelProperty(value = "省id")
private String provinceId;
@ApiModelProperty(value = "市id")
private String cityId;
@ApiModelProperty(value = "区/县id")
private String countyId;
@ApiModelProperty(value = "部门类型(1:机构,2:学校)")
private String deptType;
@ApiModelProperty(value = "部门编号")
private String deptNo;
}
| true
|
93d95432d71ad6375f3838860a026dc843c5bd17
|
Java
|
CracklyBody/GuitarShop
|
/src/main/java/maksim_ovchinnikov/GuitarShop/exception/UserLowCashException.java
|
UTF-8
| 177
| 2.125
| 2
|
[] |
no_license
|
package maksim_ovchinnikov.GuitarShop.exception;
public class UserLowCashException extends RuntimeException{
public UserLowCashException(String message){super(message);}
}
| true
|
7f100a4b3d324f2b7f61cd14c1812a5b7fe67c6a
|
Java
|
ntpbright/pa1
|
/src/allFile/Weight.java
|
UTF-8
| 565
| 2.765625
| 3
|
[] |
no_license
|
package allFile;
/**
*
* @author Nuttapatprom CHongamorkulprapa
*
* object enum Weight implements from Interface Unit
*/
public enum Weight implements Unit{
GRAM("Gram",1.0),
MILLIGRAM("Milligrams",1000),
KILOGRAMS("Kilograms",0.001),
CARAT("Carats",5),
HAP("Hap",60000),
CHANG("Chang",1200);
public final String name;
public final double value;
private Weight(String name , double value){
this.name = name;
this.value = value;
}
@Override
public double getValue(){
return value;
}
@Override
public String toString(){
return name;
}
}
| true
|
069a86a0850360bc651f4d8dc8a9aac906bafb66
|
Java
|
fazoolmail89/gopawpaw
|
/Capricornus/src/com/gopawpaw/erp/hibernate/e/AbstractEmsgMstrId.java
|
UTF-8
| 1,915
| 2.453125
| 2
|
[] |
no_license
|
package com.gopawpaw.erp.hibernate.e;
/**
* AbstractEmsgMstrId entity provides the base persistence definition of the
* EmsgMstrId entity. @author MyEclipse Persistence Tools
*/
public abstract class AbstractEmsgMstrId implements java.io.Serializable {
// Fields
private String emsgDomain;
private Integer emsgTrnbr;
// Constructors
/** default constructor */
public AbstractEmsgMstrId() {
}
/** minimal constructor */
public AbstractEmsgMstrId(String emsgDomain) {
this.emsgDomain = emsgDomain;
}
/** full constructor */
public AbstractEmsgMstrId(String emsgDomain, Integer emsgTrnbr) {
this.emsgDomain = emsgDomain;
this.emsgTrnbr = emsgTrnbr;
}
// Property accessors
public String getEmsgDomain() {
return this.emsgDomain;
}
public void setEmsgDomain(String emsgDomain) {
this.emsgDomain = emsgDomain;
}
public Integer getEmsgTrnbr() {
return this.emsgTrnbr;
}
public void setEmsgTrnbr(Integer emsgTrnbr) {
this.emsgTrnbr = emsgTrnbr;
}
public boolean equals(Object other) {
if ((this == other))
return true;
if ((other == null))
return false;
if (!(other instanceof AbstractEmsgMstrId))
return false;
AbstractEmsgMstrId castOther = (AbstractEmsgMstrId) other;
return ((this.getEmsgDomain() == castOther.getEmsgDomain()) || (this
.getEmsgDomain() != null
&& castOther.getEmsgDomain() != null && this.getEmsgDomain()
.equals(castOther.getEmsgDomain())))
&& ((this.getEmsgTrnbr() == castOther.getEmsgTrnbr()) || (this
.getEmsgTrnbr() != null
&& castOther.getEmsgTrnbr() != null && this
.getEmsgTrnbr().equals(castOther.getEmsgTrnbr())));
}
public int hashCode() {
int result = 17;
result = 37
* result
+ (getEmsgDomain() == null ? 0 : this.getEmsgDomain()
.hashCode());
result = 37 * result
+ (getEmsgTrnbr() == null ? 0 : this.getEmsgTrnbr().hashCode());
return result;
}
}
| true
|
2d8c6ad1f6e132ba28f22e54d56e442a7ae8b94d
|
Java
|
gODeaLoAple/Devy
|
/src/main/java/com/urfu/Devy/bot/telegram/TelegramBotBuilder.java
|
UTF-8
| 1,037
| 2.203125
| 2
|
[] |
no_license
|
package main.java.com.urfu.Devy.bot.telegram;
import main.java.com.urfu.Devy.bot.Bot;
import main.java.com.urfu.Devy.bot.BotBuildException;
import main.java.com.urfu.Devy.bot.BotBuilder;
import org.telegram.telegrambots.ApiContextInitializer;
import org.telegram.telegrambots.meta.TelegramBotsApi;
import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException;
public class TelegramBotBuilder implements BotBuilder {
@Override
public void build(Bot bot) throws BotBuildException {
if (bot instanceof TelegramBot) {
try {
ApiContextInitializer.init();
new TelegramBotsApi()
.registerBot(new TelegramBotListener((TelegramBot) bot));
bot.startTrackRepositoriesOnStart();
} catch (TelegramApiRequestException e) {
throw new BotBuildException(e.getMessage());
}
}
else
throw new BotBuildException("Bot must extends " + TelegramBot.class.getName());
}
}
| true
|
76bb9143b90057ba2338aba81302892e7cb9d881
|
Java
|
abhinavmanthri/ds-algos
|
/src/codechef/long_challenge_06_2020_div2/ChefAndString.java
|
UTF-8
| 1,941
| 3.703125
| 4
|
[] |
no_license
|
package codechef.long_challenge_06_2020_div2;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
public class ChefAndString {
/*
* There are N students standing in a row and numbered 1 through N from left to right. You are given a string S with length N, where for each valid i, the i-th character of S is 'x' if the i-th student is a girl or 'y' if this student is a boy. Students standing next to each other in the row are friends.
The students are asked to form pairs for a dance competition. Each pair must consist of a boy and a girl. Two students can only form a pair if they are friends. Each student can only be part of at most one pair. What is the maximum number of pairs that can be formed?
Input
The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows.
The first and only line of each test case contains a single string S.
Output
For each test case, print a single line containing one integer ― the maximum number of pairs.
Constraints
1≤T≤100
1≤N≤105
|S|=N
S contains only characters 'x' and 'y'
the sum of N over all test cases does not exceed 3⋅105
Subtasks
Subtask #1 (100 points): original constraints
Example Input
3
xy
xyxxy
yy
Example Output
1
2
0
*/
public static void main(String[] args) {
BufferedReader r = new BufferedReader (new InputStreamReader (System.in));
String s;
try {
while ((s=r.readLine())!=null) {
int t = Integer.parseInt(s);
for (int i = 0; i < t; i++) {
char[] ar = r.readLine().toCharArray();
int temp = 0;
for (int j = 0; j < ar.length-1; j++) {
if(ar[j]!=ar[j+1]) {
j++;
temp++;
}
}
System.out.println(temp);
}
}
}
catch(Exception e)
{
}
finally
{
try {
r.close();
} catch (IOException e) {
}
}
}
}
| true
|
f954fbded071c74421832514d29bfde7134111e9
|
Java
|
Mysoulmateangle/java-learn-project
|
/MarketSystem/src/com/zhou/dao/productsDao.java
|
UTF-8
| 402
| 2.015625
| 2
|
[] |
no_license
|
package com.zhou.dao;
import com.zhou.bean.products;
public interface productsDao {
public int addproduct(products products) ;//增加商品
public int deleteproduct(String productid) ;//删除商品按id
public void queryproduct() ;//查询商品信息
public void queryProductById(String productId) ;//通过ID进行查找
public int updateproduct(products products) ;//更新商品信息
}
| true
|