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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
2fc3942648b004b344833b8154015df80770dba1
|
Java
|
GangaSuresh/malwareAnalysis_
|
/app/src/main/java/com/example/malwaredetect/displayReport.java
|
UTF-8
| 3,308
| 2.03125
| 2
|
[] |
no_license
|
package com.example.malwaredetect;
import android.os.Bundle;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;
import com.google.android.material.tabs.TabLayout;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class displayReport extends AppCompatActivity{
RecyclerView recyclerView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.displayreport);
final TextView url=findViewById(R.id.url);
final TextView scanDate=findViewById(R.id.scanDate);
final TextView positives=findViewById(R.id.positives);
final TextView total=findViewById(R.id.total);
final TextView urltf=findViewById(R.id.urltf);
recyclerView = (RecyclerView)findViewById(R.id.recyclerView);
try {
JSONObject jsonObj = new JSONObject(getIntent().getStringExtra("report"));
System.out.println("2nd page");
System.out.println(jsonObj.toString());
if(jsonObj.has("url")) {
url.setText(jsonObj.getString("url"));
}
else{
urltf.setText("Hash:");
url.setText(jsonObj.getString("resource"));
}
scanDate.setText(jsonObj.getString("scan_date"));
positives.setText(jsonObj.getString("positives"));
total.setText(jsonObj.getString("total"));
System.out.println("scans");
Iterator<String> iter = jsonObj.getJSONObject("scans").keys(); //This should be the iterator you want.
List<String> name = new ArrayList<>();
List<String> detected = new ArrayList<>();
List<String> result = new ArrayList<>();
while(iter.hasNext()){
String cur=iter.next();
name.add(cur);
detected.add(jsonObj.getJSONObject("scans").getJSONObject(cur).getString("detected"));
result.add(jsonObj.getJSONObject("scans").getJSONObject(cur).getString("result"));
//System.out.println(jsonObj.getJSONObject("scans").getJSONObject(cur).getString("detected"));
}
System.out.println(name);
System.out.println(detected);
System.out.println(result);
MyAdapter myAdapter=new MyAdapter(this,name,detected,result);
recyclerView.setAdapter(myAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
}catch (Exception ex){
System.out.println("mmmmmmmmm");
System.out.println(ex);
}
}
}
| true
|
105c04065d27a275c5881d6bb589c1f5056d6fd4
|
Java
|
arleymauricio/trayectoseguro_android
|
/app/src/main/java/com/zyght/trayectoseguro/driver_services/Utils.java
|
UTF-8
| 1,785
| 2.859375
| 3
|
[] |
no_license
|
package com.zyght.trayectoseguro.driver_services;
import android.util.Log;
/**
* Created by Arley Mauricio Duarte on 8/7/17.
*/
public class Utils {
private static String TAG = "Utils";
public static String getHumanTimeFormatFromMilliseconds(long milliseconds){
String message = "";
Log.d(TAG, "getHumanTimeFormatFromMilliseconds:"+milliseconds);
String hoursText = "horas";
String minutesText = "minutos";
String secondsText = "segundos";
if (milliseconds >= 1000){
int seconds = (int) (milliseconds / 1000) % 60;
int minutes = (int) ((milliseconds / (1000 * 60)) % 60);
int hours = (int) ((milliseconds / (1000 * 60 * 60)) % 24);
int days = (int) (milliseconds / (1000 * 60 * 60 * 24));
if(hours == 1){
hoursText = "hora";
}
if(minutes == 1){
minutesText = "minuto";
}
if(seconds == 1){
secondsText = "segundo";
}
if((days == 0) && (hours != 0)){
message = String.format("%d %s %d %s %d %s ", hours, hoursText, minutes,minutesText, seconds, secondsText);
}else if((hours == 0) && (minutes != 0)){
message = String.format("%d %s %d %s ", minutes,minutesText, seconds,secondsText);
}else if((days == 0) && (hours == 0) && (minutes == 0)){
message = String.format("%d %s ", seconds, secondsText);
}else{
message = String.format("%d día %d %s %d %s %d %s", days, hours, hoursText, minutes, minutesText, seconds, secondsText);
}
} else{
message = "menos de un segundo.";
}
return message;
}
}
| true
|
282c16805d742242af01f4bd0fc5d4b2f343fd70
|
Java
|
xthian82/Utilities
|
/src/py/com/snowtech/sort/LeastSignificantDigit.java
|
UTF-8
| 835
| 3.375
| 3
|
[] |
no_license
|
package py.com.snowtech.sort;
import py.com.snowtech.util.Utils;
/**
* Least Significant Digit
*
* fixed-length W string
*
* @author cristhian
*
*/
public class LeastSignificantDigit {
public static void sort(String[] a, int W) {
int R = 256;
int N = a.length;
String[] aux = new String[N];
for (int d = W-1; d >= 0; d--) {
int[] count = new int[R + 1];
for (int i=0; i<N; i++)
count[a[i].charAt(d) + 1]++;
for (int r=0; r < R; r++)
count[r+1] += count[r];
for (int i=0; i<N; i++)
aux[ count[ a[i].charAt(d) ]++ ] = a[i];
for (int i=0; i<N; i++)
a[i] = aux[i];
}
}
public static void main(String[] args) {
String[] s = {"elf", "abf", "baa", "oba", "abc", "det", "dte", "efg"};
Utils.print(s);
LeastSignificantDigit.sort(s, 3);
Utils.print(s);
}
}
| true
|
478d1d79ff9cbd24cad948d3c1c67fe9eb5a3320
|
Java
|
AndroidRL/MyResidenty
|
/app/src/main/java/com/residency/myresidency/MixActivity/MainActivity.java
|
UTF-8
| 844
| 1.75
| 2
|
[] |
no_license
|
package com.residency.myresidency.MixActivity;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.residency.myresidency.R;
import java.util.Locale;
public class MainActivity extends AppCompatActivity {
Button btn;
TextView name;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = findViewById(R.id.btn);
name = findViewById(R.id.name);
}
}
| true
|
5b4d453c4099fbd93028a2a2d89938366be6d19c
|
Java
|
rucky2013/netty-queue
|
/src/main/java/org/mitallast/queue/common/collection/ImmutableLongMap.java
|
UTF-8
| 1,362
| 2.625
| 3
|
[
"MIT"
] |
permissive
|
package org.mitallast.queue.common.collection;
public interface ImmutableLongMap<V> {
public final static ImmutableLongMap EMPTY = new ImmutableLongMap<Object>() {
@Override
public long emptyKey() {
return 0;
}
@Override
public int size() {
return 0;
}
@Override
public boolean isEmpty() {
return true;
}
@Override
public boolean containsKey(long key) {
return false;
}
@Override
public Object get(long key) {
return null;
}
@Override
public void forEach(LongMapConsumer<Object> consumer) {
}
};
public static <V> ImmutableLongMapBuilder<V> builder() {
return new ImmutableLongOpenMapBuilder<V>();
}
public static <V> ImmutableLongMapBuilder<V> builder(long emptyKey) {
return new ImmutableLongOpenMapBuilder<V>(emptyKey);
}
@SuppressWarnings("unchecked")
public static <V> ImmutableLongMap<V> empty() {
return EMPTY;
}
long emptyKey();
int size();
boolean isEmpty();
boolean containsKey(long key);
V get(long key);
void forEach(LongMapConsumer<V> consumer);
public static interface LongMapConsumer<V> {
void accept(long key, V value);
}
}
| true
|
12021311d62c09507fe23cab1a0c71f3558e384a
|
Java
|
tainaoual/Pyramid-Academy-TAI
|
/IdeaProjects/car/src/com/company/Main.java
|
UTF-8
| 300
| 2.703125
| 3
|
[] |
no_license
|
package com.company;
public class Main {
public static void main(String[] args) {
// write your code here
Car car1 = new Car("Ford", 10000);
Van van1 = new Van("Toyota", 20000);
System.out.println("Car1: " + car1);
System.out.println("Van1: " + van1);
}
}
| true
|
fcd996c48974589dc25ee55db4105dd18ab26841
|
Java
|
isd-soft/annual-leave-assistant
|
/backend/src/main/java/isd/internship/ala/services/HolidayService.java
|
UTF-8
| 385
| 2.109375
| 2
|
[] |
no_license
|
package isd.internship.ala.services;
import isd.internship.ala.models.Holiday;
import java.util.HashMap;
import java.util.List;
public interface HolidayService {
List<HashMap<String, String>> getAll();
Holiday getById(Integer id);
Holiday create(Holiday holiday);
Holiday update(Integer id, Holiday holiday);
void deleteById(Integer id);
void deleteAll();
}
| true
|
943b79b62bc4e4b3b29d2aec42bf8d0d05ed4e6c
|
Java
|
BaseMax/PopularAndroidSource
|
/bazaar8.apk-decompiled/sources/c/e/a/a/j/o.java
|
UTF-8
| 5,101
| 1.679688
| 2
|
[] |
no_license
|
package c.e.a.a.j;
import android.os.Handler;
import c.e.a.a.Z;
import c.e.a.a.j.v;
import c.e.a.a.j.w;
import c.e.a.a.n.A;
import c.e.a.a.o.C0737e;
import c.e.a.a.o.I;
import java.io.IOException;
import java.util.HashMap;
/* compiled from: CompositeMediaSource */
public abstract class o<T> extends m {
/* renamed from: f reason: collision with root package name */
public final HashMap<T, b> f8961f = new HashMap<>();
/* renamed from: g reason: collision with root package name */
public Handler f8962g;
/* renamed from: h reason: collision with root package name */
public A f8963h;
/* compiled from: CompositeMediaSource */
private final class a implements w {
/* renamed from: a reason: collision with root package name */
public final T f8964a;
/* renamed from: b reason: collision with root package name */
public w.a f8965b;
public a(T t) {
this.f8965b = o.this.a((v.a) null);
this.f8964a = t;
}
public void a(int i2, v.a aVar, w.b bVar, w.c cVar) {
if (d(i2, aVar)) {
this.f8965b.b(bVar, a(cVar));
}
}
public void b(int i2, v.a aVar) {
if (d(i2, aVar)) {
this.f8965b.b();
}
}
public void c(int i2, v.a aVar) {
if (d(i2, aVar)) {
this.f8965b.a();
}
}
public final boolean d(int i2, v.a aVar) {
v.a aVar2;
if (aVar != null) {
aVar2 = o.this.a(this.f8964a, aVar);
if (aVar2 == null) {
return false;
}
} else {
aVar2 = null;
}
o.this.a(this.f8964a, i2);
w.a aVar3 = this.f8965b;
if (aVar3.f8981a != i2 || !I.a((Object) aVar3.f8982b, (Object) aVar2)) {
this.f8965b = o.this.a(i2, aVar2, 0);
}
return true;
}
public void a(int i2, v.a aVar, w.b bVar, w.c cVar, IOException iOException, boolean z) {
if (d(i2, aVar)) {
this.f8965b.a(bVar, a(cVar), iOException, z);
}
}
public void b(int i2, v.a aVar, w.b bVar, w.c cVar) {
if (d(i2, aVar)) {
this.f8965b.a(bVar, a(cVar));
}
}
public void c(int i2, v.a aVar, w.b bVar, w.c cVar) {
if (d(i2, aVar)) {
this.f8965b.c(bVar, a(cVar));
}
}
public void b(int i2, v.a aVar, w.c cVar) {
if (d(i2, aVar)) {
this.f8965b.a(a(cVar));
}
}
public void a(int i2, v.a aVar) {
if (d(i2, aVar)) {
this.f8965b.c();
}
}
public void a(int i2, v.a aVar, w.c cVar) {
if (d(i2, aVar)) {
this.f8965b.b(a(cVar));
}
}
public final w.c a(w.c cVar) {
o oVar = o.this;
T t = this.f8964a;
long j2 = cVar.f8998f;
oVar.a(t, j2);
o oVar2 = o.this;
T t2 = this.f8964a;
long j3 = cVar.f8999g;
oVar2.a(t2, j3);
if (j2 == cVar.f8998f && j3 == cVar.f8999g) {
return cVar;
}
w.c cVar2 = new w.c(cVar.f8993a, cVar.f8994b, cVar.f8995c, cVar.f8996d, cVar.f8997e, j2, j3);
return cVar2;
}
}
/* compiled from: CompositeMediaSource */
private static final class b {
/* renamed from: a reason: collision with root package name */
public final v f8967a;
/* renamed from: b reason: collision with root package name */
public final v.b f8968b;
/* renamed from: c reason: collision with root package name */
public final w f8969c;
public b(v vVar, v.b bVar, w wVar) {
this.f8967a = vVar;
this.f8968b = bVar;
this.f8969c = wVar;
}
}
public int a(T t, int i2) {
return i2;
}
public long a(T t, long j2) {
return j2;
}
public abstract v.a a(T t, v.a aVar);
public void a(A a2) {
this.f8963h = a2;
this.f8962g = new Handler();
}
public void b() {
for (b next : this.f8961f.values()) {
next.f8967a.a(next.f8968b);
next.f8967a.a(next.f8969c);
}
this.f8961f.clear();
}
/* renamed from: b */
public abstract void a(T t, v vVar, Z z, Object obj);
public void a() {
for (b bVar : this.f8961f.values()) {
bVar.f8967a.a();
}
}
public final void a(T t, v vVar) {
C0737e.a(!this.f8961f.containsKey(t));
C0716a aVar = new C0716a(this, t);
a aVar2 = new a(t);
this.f8961f.put(t, new b(vVar, aVar, aVar2));
Handler handler = this.f8962g;
C0737e.a(handler);
vVar.a(handler, (w) aVar2);
vVar.a((v.b) aVar, this.f8963h);
}
}
| true
|
255b5ab20d61f55205798e6e6b484a770af52039
|
Java
|
uzuume/android-app-makers-2017
|
/app/src/main/java/fr/paug/androidmakers/ui/util/AgendaFilterMenu.java
|
UTF-8
| 3,154
| 2.21875
| 2
|
[] |
no_license
|
package fr.paug.androidmakers.ui.util;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.SubMenu;
import fr.paug.androidmakers.R;
/**
* Created by stan on 26/03/2017.
*/
public class AgendaFilterMenu implements MenuItem.OnMenuItemClickListener {
private static final String PREF_FILTER_LANGUAGE_SELECTED = "filter_language_selected";
private final SharedPreferences mSharedPreferences;
private MenuFilterListener mMenuFilterListener;
private String mTitleAll;
private String mSelectedOption;
private SubMenu mFilter;
private String[] mLanguages;
public AgendaFilterMenu(Context context, Menu menu, MenuInflater inflater) {
mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
inflater.inflate(R.menu.filter, menu);
MenuItem item = menu.findItem(R.id.filter);
mFilter = item.getSubMenu();
mFilter.setHeaderTitle(R.string.filter_language_header);
mTitleAll = context.getString(R.string.filter_language_all);
mSelectedOption = mSharedPreferences.getString(PREF_FILTER_LANGUAGE_SELECTED, null);
refreshFilters();
}
public void setMenuFilterListener(MenuFilterListener menuFilterListener) {
mMenuFilterListener = menuFilterListener;
}
public void setLanguages(String... languages) {
mLanguages = languages;
refreshFilters();
}
public String getLanguageFilter() {
return mSelectedOption;
}
@Override
public boolean onMenuItemClick(MenuItem item) {
String newOption = item.getTitle().toString();
if (newOption.equals(mSelectedOption)) {
return true;
}
mSelectedOption = newOption;
if (mSelectedOption.equals(mTitleAll)) {
mSelectedOption = null;
}
saveInPreference();
refreshFilters();
if (mMenuFilterListener != null) {
mMenuFilterListener.onFilterChanged();
}
return true;
}
private void saveInPreference() {
SharedPreferences.Editor editor = mSharedPreferences.edit();
if (mSelectedOption == null) {
editor.remove(PREF_FILTER_LANGUAGE_SELECTED);
} else {
editor.putString(PREF_FILTER_LANGUAGE_SELECTED, mSelectedOption);
}
editor.apply();
}
private void refreshFilters() {
mFilter.clear();
addFilterItem(mTitleAll, mSelectedOption == null);
if (mLanguages != null) {
for (String language : mLanguages) {
addFilterItem(language, language.equals(mSelectedOption));
}
}
}
private void addFilterItem(String label, boolean checked) {
MenuItem menuItem = mFilter.add(label);
menuItem.setCheckable(true);
menuItem.setChecked(checked);
menuItem.setOnMenuItemClickListener(this);
}
public interface MenuFilterListener {
void onFilterChanged();
}
}
| true
|
7e57a63e7038adb250399f77ed8976d33e9ed679
|
Java
|
TenshiLupus/mooc-java-programming-i
|
/part02-Part02_04.ComparingNumbers/src/main/java/ComparingNumbers.java
|
UTF-8
| 539
| 3.890625
| 4
|
[] |
no_license
|
import java.util.Scanner;
public class ComparingNumbers {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int v1 = Integer.valueOf(scanner.nextLine());
int v2 = Integer.valueOf(scanner.nextLine());
if(v1 > v2){
System.out.println(v1 + " is greater than " + v2);
}else if(v1 < v2){
System.out.println(v1 + " is smaller than " + v2);
}else{
System.out.println(v1 + " is equal to " + v2);
}
}
}
| true
|
437f9a6148d6bd32a8689c17ee3b21f465352af1
|
Java
|
Juessa/AquaWarp
|
/src/main/java/org/anhcraft/aquawarp/Listeners/TpWarpLocked.java
|
UTF-8
| 3,060
| 2.265625
| 2
|
[] |
no_license
|
package org.anhcraft.aquawarp.Listeners;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerChatEvent;
import org.anhcraft.aquawarp.API.WarpMethods;
import org.anhcraft.aquawarp.Commands.TpWarp;
import org.anhcraft.aquawarp.Exceptions.WarpNotFound;
import org.anhcraft.aquawarp.Exceptions.WrongSaveDataType;
import org.anhcraft.aquawarp.Util.Configuration;
import org.anhcraft.aquawarp.Util.Strings;
import java.sql.SQLException;
import java.util.ArrayList;
/**
* Copyright (c) by Anh Craft. All rights reserved.
* Licensed under the apache license v2.0.
*/
public class TpWarpLocked extends WarpMethods implements Listener {
public static ArrayList<String> players = new ArrayList();
public static ArrayList<CommandSender> senders = new ArrayList();
public static ArrayList<String> warps = new ArrayList();
public static void tpWarpLocked(String warp, String player, CommandSender sender) {
Player p = Bukkit.getServer().getPlayerExact(player);
Boolean m = false;
for(Player x : Bukkit.getServer().getOnlinePlayers()) {
if(x.getName().equals(player)){
m = true;
}
}
if(m){
Strings.sendSender(Configuration.message.getString("require_enter_password").replace("@warp",warp), sender);
warps.add(warp);
players.add(p.getName());
senders.add(sender);
} else {
Strings.sendSender(Configuration.message.getString("player_require_online"), sender);
}
}
@EventHandler(priority = EventPriority.HIGHEST)
public void enterPassword(PlayerChatEvent e){
Player p = e.getPlayer();
String ns = p.getName();
Boolean uq = false;
int uo = -1;
for(int v = 0; v < players.size(); v++){
String px = players.get(v);
if(px.equals(ns)){
uq = true;
uo = v;
break;
} else {
continue;
}
}
if(uq){
e.setCancelled(true);
String pass = e.getMessage();
String warp = warps.get(uo);
String player = players.get(uo);
CommandSender sender = senders.get(uo);
String hashPass = Strings.hashAutoType(pass);
warps.remove(warp);
players.remove(p.getName());
senders.remove(sender);
try {
if(hashPass.equals(getPasswordAutoSaveDataType(warp))){
TpWarp.teleport(warp, player, sender);
} else {
Strings.sendSender(Configuration.message.getString("wrong_password").replace("@warp",warp), sender);
}
} catch(WarpNotFound | SQLException | WrongSaveDataType es) {
es.printStackTrace();
}
}
}
}
| true
|
5ac1b49877d62ddfb176375fb952fe898749d68d
|
Java
|
fionser/weiboFetcher
|
/jnu/util/PriorityRQ.java
|
UTF-8
| 769
| 3.078125
| 3
|
[] |
no_license
|
package jnu.util;
import java.util.PriorityQueue;
import java.util.Queue;
/**
* Name:PriorityRQ
* User:fionser
* Date:12-12-17
*/
public class PriorityRQ <E extends Comparable>{
private final int DEFAULT_CAP = 1000;
private Queue<E> rq;
public PriorityRQ(int queueCap) {
if (queueCap <= 0) {
queueCap = DEFAULT_CAP;
}
rq = new PriorityQueue<E>(queueCap);
}
public synchronized void put(E tsk) {
if (tsk != null) {
rq.offer(tsk);
}
}
public synchronized E get() {
return isEmpty() ? null : rq.remove();
}
public synchronized boolean isEmpty() {
return rq.isEmpty();
}
public synchronized int size() {
return rq.size();
}
}
| true
|
4a4a9c632dff6240a879dea2d147e116ddaf3adc
|
Java
|
prodigasistemas/gsan
|
/src/gcom/gui/relatorio/cadastro/categoria/GerarRelatorioCategoriaManterAction.java
|
ISO-8859-1
| 3,532
| 2.09375
| 2
|
[] |
no_license
|
package gcom.gui.relatorio.cadastro.categoria;
import gcom.cadastro.imovel.Categoria;
import gcom.cadastro.imovel.FiltroCategoria;
import gcom.relatorio.ExibidorProcessamentoTarefaRelatorio;
import gcom.relatorio.cadastro.categoria.RelatorioManterCategoria;
import gcom.seguranca.acesso.usuario.Usuario;
import gcom.tarefa.TarefaRelatorio;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.validator.DynaValidatorForm;
/**
* action responsvel pela exibio do relatrio de bairro manter
*
* @author Svio Luiz
* @created 11 de Julho de 2005
*/
public class GerarRelatorioCategoriaManterAction extends
ExibidorProcessamentoTarefaRelatorio {
/**
* < <Descrio do mtodo>>
*
* @param actionMapping
* Descrio do parmetro
* @param actionForm
* Descrio do parmetro
* @param httpServletRequest
* Descrio do parmetro
* @param httpServletResponse
* Descrio do parmetro
* @return Descrio do retorno
*/
public ActionForward execute(ActionMapping actionMapping,
ActionForm actionForm, HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse) {
// cria a varivel de retorno
ActionForward retorno = null;
// Mudar isso quando tiver esquema de segurana
HttpSession sessao = httpServletRequest.getSession(false);
DynaValidatorForm pesquisarActionForm = (DynaValidatorForm) actionForm;
FiltroCategoria filtroCategoria = (FiltroCategoria) sessao
.getAttribute("filtroCategoria");
// Inicio da parte que vai mandar os parametros para o relatrio
Categoria categoriaParametros = new Categoria();
Integer id = null;
String idPesquisar = (String) pesquisarActionForm.get("id");
if (idPesquisar != null && !idPesquisar.equals("")) {
id = new Integer(idPesquisar);
}
Short indicadorDeUso = null;
if (pesquisarActionForm.get("indicadorUso") != null
&& !pesquisarActionForm.get("indicadorUso").equals("")) {
indicadorDeUso = new Short((String) pesquisarActionForm.get("indicadorUso"));
}
// seta os parametros que sero mostrados no relatrio
categoriaParametros.setId(id);
categoriaParametros.setDescricao((String) pesquisarActionForm.get("descricao"));
categoriaParametros.setIndicadorUso(indicadorDeUso);
// Fim da parte que vai mandar os parametros para o relatrio
String tipoRelatorio = httpServletRequest.getParameter("tipoRelatorio");
RelatorioManterCategoria relatorioManterCategoria = new RelatorioManterCategoria(
(Usuario)(httpServletRequest.getSession(false)).getAttribute("usuarioLogado"));
relatorioManterCategoria.addParametro("filtroCategoria", filtroCategoria);
relatorioManterCategoria.addParametro("categoriaParametros", categoriaParametros);
if (tipoRelatorio == null) {
tipoRelatorio = TarefaRelatorio.TIPO_PDF + "";
}
relatorioManterCategoria.addParametro("tipoFormatoRelatorio", Integer
.parseInt(tipoRelatorio));
retorno = processarExibicaoRelatorio(relatorioManterCategoria, tipoRelatorio,
httpServletRequest, httpServletResponse, actionMapping);
// devolve o mapeamento contido na varivel retorno
return retorno;
}
}
| true
|
8d6f1c06ee103beda2c9f67f0a701f5c1a432c3c
|
Java
|
magenta-aps/datafordeler
|
/plugin/gladdrreg/src/main/java/dk/magenta/datafordeler/gladdrreg/data/district/DistrictRegistration.java
|
UTF-8
| 908
| 2.1875
| 2
|
[] |
permissive
|
package dk.magenta.datafordeler.gladdrreg.data.district;
import dk.magenta.datafordeler.core.database.Registration;
import javax.persistence.Index;
import javax.persistence.Table;
import java.time.OffsetDateTime;
/**
* Created by lars on 16-05-17.
*/
@javax.persistence.Entity
@Table(name = "gladdrreg_district_registration", indexes = {
@Index(name = "gladdrreg_district_entity", columnList = "entity_id"),
@Index(name = "gladdrreg_district_registration_from", columnList = "registrationFrom"),
@Index(name = "gladdrreg_district_registration_to", columnList = "registrationTo")
})
public class DistrictRegistration extends Registration<DistrictEntity, DistrictRegistration, DistrictEffect> {
@Override
protected DistrictEffect createEmptyEffect(OffsetDateTime effectFrom, OffsetDateTime effectTo) {
return new DistrictEffect(this, effectFrom, effectTo);
}
}
| true
|
2e768c8d3adb238cbd55f4f656b66be63d478b95
|
Java
|
DiegoteGitHub/solstice-backend-challenge
|
/src/main/java/com/dlalo/solsticebackend/model/Address.java
|
UTF-8
| 1,436
| 2.53125
| 3
|
[] |
no_license
|
package com.dlalo.solsticebackend.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Address implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column
private String city;
@Column
private String streetName;
@Column
private Integer streetNumber;
@Column
private String stateCd;
public Address() {
}
public Address(String city, String streetName, Integer streetNumber, String stateCd) {
this.city = city;
this.streetName = streetName;
this.streetNumber = streetNumber;
this.stateCd = stateCd;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getStreetName() {
return streetName;
}
public void setStreetName(String streetName) {
this.streetName = streetName;
}
public Integer getStreetNumber() {
return streetNumber;
}
public void setStreetNumber(Integer streetNumber) {
this.streetNumber = streetNumber;
}
public String getStateCd() {
return stateCd;
}
public void setStateCd(String stateCd) {
this.stateCd = stateCd;
}
}
| true
|
e11195bf0c9ae4b13be035bfc02254fda375bc5b
|
Java
|
drozdofp/testApp
|
/app/src/main/java/com/pavel/tinkoff_news/apapters/NewsAdapter.java
|
UTF-8
| 2,960
| 2.421875
| 2
|
[] |
no_license
|
package com.pavel.tinkoff_news.apapters;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.pavel.tinkoff_news.R;
import com.pavel.tinkoff_news.entities.News;
import com.pavel.tinkoff_news.helpers.DateHelper;
import io.realm.RealmChangeListener;
import io.realm.RealmResults;
/**
* Created by pavel on 19.08.2016.
*/
public class NewsAdapter extends RecyclerView.Adapter<NewsAdapter.NewsViewHolder> {
private Context context;
private RealmResults<News> newsResult;
private OnItemNewsClickListener onItemNewsClickListener;
public NewsAdapter(Context context, RealmResults<News> newsResult, OnItemNewsClickListener onItemNewsClickListener) {
this.context = context;
this.newsResult = newsResult;
this.onItemNewsClickListener = onItemNewsClickListener;
this.newsResult.addChangeListener(new RealmChangeListener<RealmResults<News>>() {
@Override
public void onChange(RealmResults<News> element) {
notifyDataSetChanged();
}
});
}
@Override
public NewsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new NewsViewHolder(LayoutInflater.from(context).inflate(R.layout.item_news, parent, false));
}
@Override
public void onBindViewHolder(NewsViewHolder holder, int position) {
holder.setNews(newsResult.get(position));
}
@Override
public int getItemCount() {
return newsResult != null ? newsResult.size() : 0;
}
public class NewsViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private TextView tvTitleNews;
private TextView tvPublicationDateNews;
private News currentNews;
public NewsViewHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
tvTitleNews = (TextView) itemView.findViewById(R.id.tv_title_news);
tvPublicationDateNews = (TextView) itemView.findViewById(R.id.tv_publication_date_news);
}
public void setNews(News currentNews) {
this.currentNews = currentNews;
tvTitleNews.setText(Html.fromHtml(currentNews.getText()));
String publicationString = String.format("%s %s", context.getString(R.string.publication_date), DateHelper.convertTimeStampToDateFormat(currentNews.getPublicationDate()));
tvPublicationDateNews.setText(publicationString);
}
@Override
public void onClick(View v) {
if (onItemNewsClickListener != null) {
onItemNewsClickListener.onNewsClick(currentNews.getId());
}
}
}
public interface OnItemNewsClickListener {
void onNewsClick(int newsId);
}
}
| true
|
37a3137b4a21890966816943df2aceac971e6984
|
Java
|
chenyueling/mockito_training
|
/src/test/java/MockTest.java
|
UTF-8
| 5,444
| 2.71875
| 3
|
[] |
no_license
|
import org.junit.Test;
import org.mockito.InOrder;
import java.util.LinkedList;
import java.util.List;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
/**
* ┏┓ ┏┓+ +
* ┏┛┻━━━┛┻┓ + +
* ┃ ┃
* ┃ ━ ┃ ++ + + +
* ████━████ ┃+
* ┃ ┃ +
* ┃ ┻ ┃
* ┃ ┃ + +
* ┗━┓ ┏━┛
* ┃ ┃
* ┃ ┃ + + + +
* ┃ ┃ Code is far away from bug with the animal protecting
* ┃ ┃ + 神兽保佑,代码无BUG
* ┃ ┃
* ┃ ┃ +
* ┃ ┗━━━┓ + +
* ┃ ┣┓
* ┃ ┏┛
* ┗┓┓┏━┳┓┏┛ + + + +
* ┃┫┫ ┃┫┫
* ┗┻┛ ┗┻┛+ + + +
* Copyright (c) 2016 Mljia , All rights reserved.
* http://www.mljia.cn/
*
* @author Paul
* @description
* @since 2016/7/14.
*/
public class MockTest {
/*验证一些行为*/
@Test
public void behaviour() {
List mockedList = mock(List.class);
mockedList.add("one");
mockedList.clear();
/*验证是否添加过 one*/
verify(mockedList).add("one");
/*验证是否清除过数组*/
verify(mockedList).clear();
}
/*立一些桩,当执行某些操作的时候给出相应的状态*/
@Test
public void stubbing() {
LinkedList mockedList = mock(LinkedList.class);
when(mockedList.get(0)).thenReturn("first");
when(mockedList.get(1)).thenReturn(new RuntimeException());
System.out.println(mockedList.get(0));
System.out.println(mockedList.get(1));
System.out.println(mockedList.get(999));
verify(mockedList).get(0);
}
/**/
@Test
public void argumentMatchers() {
LinkedList mockedList = mock(LinkedList.class);
when(mockedList.get(anyInt())).thenReturn("element");
//stubbing using hamcrest (let's say isValid() returns your own hamcrest matcher):
/*when(mockedList.contains(argThat(isValid()))).thenReturn("element");*/
System.out.println(mockedList.get(999));
verify(mockedList).get(anyInt());
}
@Test
public void numberOfInvocations() {
LinkedList mockedList = mock(LinkedList.class);
mockedList.add("once");
mockedList.add("twice");
mockedList.add("twice");
mockedList.add("three times");
mockedList.add("three times");
mockedList.add("three times");
/*不传递默认为一次*/
verify(mockedList).add("once");
verify(mockedList, times(1)).add("once");
verify(mockedList, times(2)).add("twice");
verify(mockedList, times(3)).add("three times");
verify(mockedList, never()).add("never happened");
}
@Test
public void stubbingMethodException() {
Object o = mock(Object.class);
doThrow(new RuntimeException()).when(o).toString();
o.toString();
}
/*验证指定的调用次序*/
@Test
public void verificationInOrder() {
List singleMock = mock(List.class);
singleMock.add("was added first");
singleMock.add("was added second");
InOrder inOrder = inOrder(singleMock);
inOrder.verify(singleMock).add("was added first");
inOrder.verify(singleMock).add("was added second");
List firstMock = mock(List.class);
List secondMock = mock(List.class);
List third = mock(List.class);
firstMock.add("was called first");
secondMock.add("was called second");
inOrder = inOrder(firstMock, secondMock);
inOrder.verify(firstMock).add("was called first");
inOrder.verify(secondMock).add("was called second");
}
/*验证某些方法是否被调用过*/
@Test
public void neverHappened() {
List mockOne = mock(List.class);
List mockTwo = mock(List.class);
List mockThree = mock(List.class);
//using mocks - only mockOne is interacted
mockOne.add("one");
/*验证方法被调用过*/
//ordinary verification
verify(mockOne).add("one");
//验证方法没有没调用过
//verify that method was never called on a mock
verify(mockOne, never()).add("two");
//mockTwo.add("");
//verify that other mocks were not interacted
/*验证某个对象从来没有被使用过*/
verifyZeroInteractions(mockTwo, mockThree);
}
}
| true
|
d0bb9494f71950c3c102e0e8fe2b7702c2790190
|
Java
|
Bolodya1997/Storage
|
/src/main/java/ru/nsu/fit/popov/storage/util/StartPort.java
|
UTF-8
| 273
| 1.929688
| 2
|
[] |
no_license
|
package ru.nsu.fit.popov.storage.util;
import se.sics.kompics.PortType;
import se.sics.kompics.Start;
public class StartPort extends PortType {
// TODO: think about implementing custom Control port
public StartPort() {
indication(Start.class);
}
}
| true
|
40db62ed1d73b45fe020f6d12e5a38cf4c0cc70d
|
Java
|
P79N6A/icse_20_user_study
|
/methods/Method_400.java
|
UTF-8
| 1,704
| 2.71875
| 3
|
[] |
no_license
|
@SuppressWarnings({"rawtypes","unchecked"}) public void arrayAdd(Object rootObject,Object... values){
if (values == null || values.length == 0) {
return;
}
if (rootObject == null) {
return;
}
init();
Object currentObject=rootObject;
Object parentObject=null;
for (int i=0; i < segments.length; ++i) {
if (i == segments.length - 1) {
parentObject=currentObject;
}
currentObject=segments[i].eval(this,rootObject,currentObject);
}
Object result=currentObject;
if (result == null) {
throw new JSONPathException("value not found in path " + path);
}
if (result instanceof Collection) {
Collection collection=(Collection)result;
for ( Object value : values) {
collection.add(value);
}
return;
}
Class<?> resultClass=result.getClass();
Object newResult;
if (resultClass.isArray()) {
int length=Array.getLength(result);
Object descArray=Array.newInstance(resultClass.getComponentType(),length + values.length);
System.arraycopy(result,0,descArray,0,length);
for (int i=0; i < values.length; ++i) {
Array.set(descArray,length + i,values[i]);
}
newResult=descArray;
}
else {
throw new JSONException("unsupported array put operation. " + resultClass);
}
Segment lastSegment=segments[segments.length - 1];
if (lastSegment instanceof PropertySegment) {
PropertySegment propertySegment=(PropertySegment)lastSegment;
propertySegment.setValue(this,parentObject,newResult);
return;
}
if (lastSegment instanceof ArrayAccessSegment) {
((ArrayAccessSegment)lastSegment).setValue(this,parentObject,newResult);
return;
}
throw new UnsupportedOperationException();
}
| true
|
a17f0e2012a1ccf3b2b452a023c04a2e124d01cf
|
Java
|
ilshatlatypov/demoapp2-server
|
/src/main/java/ru/jvdev/demoapp/server/config/RestConfig.java
|
UTF-8
| 684
| 1.976563
| 2
|
[] |
no_license
|
package ru.jvdev.demoapp.server.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.rest.core.config.RepositoryRestConfiguration;
import org.springframework.data.rest.webmvc.config.RepositoryRestConfigurerAdapter;
import ru.jvdev.demoapp.server.model.Employee;
import ru.jvdev.demoapp.server.model.Task;
/**
* @author <a href="mailto:ilatypov@wiley.com">Ilshat Latypov</a>
* @since 18.11.2016
*/
@Configuration
public class RestConfig extends RepositoryRestConfigurerAdapter {
@Override
public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {
config.exposeIdsFor(Employee.class, Task.class);
}
}
| true
|
987b45eb1bc7892252811adeffe3fbc543693a06
|
Java
|
ArtinTD/shol
|
/src/main/java/kon/shol/searchengine/parser/LangDetector.java
|
UTF-8
| 3,635
| 2.375
| 2
|
[] |
no_license
|
package kon.shol.searchengine.parser;
import com.google.common.base.Optional;
import com.optimaize.langdetect.LanguageDetector;
import com.optimaize.langdetect.LanguageDetectorBuilder;
import com.optimaize.langdetect.i18n.LdLocale;
import com.optimaize.langdetect.ngram.NgramExtractors;
import com.optimaize.langdetect.profiles.LanguageProfile;
import com.optimaize.langdetect.profiles.LanguageProfileReader;
import com.optimaize.langdetect.text.CommonTextObjectFactories;
import com.optimaize.langdetect.text.TextObject;
import com.optimaize.langdetect.text.TextObjectFactory;
import kon.shol.searchengine.crawler.Fetcher;
import kon.shol.searchengine.parser.exceptions.InvalidLanguageException;
import kon.shol.searchengine.parser.exceptions.UnknownLanguageException;
import org.jsoup.nodes.Document;
import java.io.IOException;
import java.util.List;
class LangDetector {
private final String ENGLISH_LANGUAGE = "en";
private static String detectLang(Document document) throws IOException {
List<LanguageProfile> languageProfiles = new LanguageProfileReader().readAllBuiltIn();
LanguageDetector languageDetector = LanguageDetectorBuilder.create(NgramExtractors.standard())
.withProfiles(languageProfiles)
.build();
TextObjectFactory textObjectFactory = CommonTextObjectFactories.forDetectingOnLargeText();
try {
TextObject textObject = textObjectFactory.forText(document.text());
Optional<LdLocale> lang = languageDetector.detect(textObject);
return lang.get().getLanguage();
} catch (IllegalStateException e) {
try {
TextObject textObject = textObjectFactory.forText(document.select("meta[name=description]")
.attr("content"));
Optional<LdLocale> lang = languageDetector.detect(textObject);
return lang.get().getLanguage();
} catch (Exception e2) {
try {
TextObject textObject = textObjectFactory.forText(new String(new char[20]).replace("\0", document.title() + " "));
Optional<LdLocale> lang = languageDetector.detect(textObject);
return lang.get().getLanguage();
} catch (Exception e3) {
throw new UnknownLanguageException(document.location());
}
}
}
}
/*
public String detectLanguage(Document document) throws IOException {
System.out.println(document.text());
LanguageIdentifier identifier = new LanguageIdentifier(document.text());
return identifier.getLanguage();
// TODO: THIS IS NOT WORKING :|
}*/
private boolean checkMetaLanguage(Document document, String language) {
if (!document.select("html").attr("lang").contains(language) && !document.select("html").attr("lang").isEmpty()) {
return false;
}
return true;
}
boolean isEnglish(Document document) throws IOException {
if (!checkMetaLanguage(document, ENGLISH_LANGUAGE)) {
throw new InvalidLanguageException("Meta not English: " + document.location());
} else if (!detectLang(document).equals(ENGLISH_LANGUAGE)) {
throw new InvalidLanguageException("Text not English: " + document.location());
}
return true;
}
public static void main(String args[]) throws IOException {
Fetcher fetcher = new Fetcher();
Document document = fetcher.fetch("http://wikipedia.org");
System.out.println(detectLang(document));
}
}
| true
|
9ee0876184b3791992caacfcf7dbfe6c9e8abc6c
|
Java
|
fesine/school-exam
|
/src/main/java/cn/edu/hebau/exam/po/ExamScorePo.java
|
UTF-8
| 1,445
| 2.015625
| 2
|
[] |
no_license
|
package cn.edu.hebau.exam.po;
import com.fesine.dao.BasePo;
/**
* @description: t_exam_score表对应的实体类
* @author: Fesine
* @createTime:2018/05/08
* @update:修改内容
* @author: Fesine
* @updateTime:2018/05/08
*/
public class ExamScorePo extends BasePo {
private static final long serialVersionUID = 1L;
//alias
public static final String TABLE_ALIAS = "ExamScore";
public static final String ALIAS_ID = "主键";
public static final String ALIAS_STU_NO = "学号";
public static final String ALIAS_EXAM_ID = "考试编号";
public static final String ALIAS_SCORE = "成绩";
//columns START
/**
* 主键 db_column: id
*/
private Integer id;
/**
* 学号 db_column: stu_no
*/
private String stuNo;
/**
* 考试编号 db_column: exam_id
*/
private Integer examId;
/**
* 成绩 db_column: score
*/
private Integer score;
//columns END
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
public String getStuNo() {
return this.stuNo;
}
public void setStuNo(String stuNo) {
this.stuNo = stuNo;
}
public Integer getExamId() {
return this.examId;
}
public void setExamId(Integer examId) {
this.examId = examId;
}
public Integer getScore() {
return this.score;
}
public void setScore(Integer score) {
this.score = score;
}
}
| true
|
ebf22e7b6031b2f245c55cd34b6876910236021e
|
Java
|
ashi1994/API_Automation_Framework
|
/src/main/java/com/core/ExcelHandleUsingFillo.java
|
UTF-8
| 1,606
| 2.515625
| 3
|
[] |
no_license
|
package com.core;
import org.testng.annotations.Test;
import com.codoid.products.exception.FilloException;
import com.codoid.products.fillo.*;
public class ExcelHandleUsingFillo {
Fillo fc=new Fillo();
@Test
public void readFile() throws FilloException {
Connection conn=fc.getConnection(System.getProperty("user.dir")+"/payload/daily_meal_ingestion_product.xlsx");
String strQuery="Select * from Sheet1";
Recordset recordset=conn.executeQuery(strQuery);
while(recordset.next()){
System.out.println(recordset.getField("Store ID*"));
}
recordset.close();
conn.close();
}
@Test
public void insertValue() throws FilloException {
//System.setProperty("ROW", "1");//Table start row
//System.setProperty("COLUMN", "3");//Table start column
Connection conn=fc.getConnection(System.getProperty("user.dir")+"/payload/UpdateExcel.xlsx");
//String strQuery="INSERT INTO Sheet1 (Store ID,External SKU*,dietary preference) VALUES ('100','UK','Something')";
//String strQuery="INSERT INTO 'Sheet1'(Store ID,External SKU,dietary preference) VALUES ('100','UK','Something')";
String strQuery="INSERT INTO Sheet1 (Name,Country) VALUES('Peter','UK')";
conn.executeUpdate(strQuery);
conn.close();
}
@Test
public void upadateValue() throws FilloException {
Fillo fillo=new Fillo();
Connection connection=fillo.getConnection(System.getProperty("user.dir")+"/payload/daily_meal_ingestion_product.xlsx");
String strQuery="Update Sheet1 Set Store ID*='200' where External SKU*=2";
connection.executeUpdate(strQuery);
connection.close();
}
}
| true
|
71fb507138ff9dd31699186e20c89c9efe302fa8
|
Java
|
KaungMyat-Min/encrypted-exo
|
/app/src/main/java/mm/com/blueplanet/bppay/encryptedexo/MainActivity.java
|
UTF-8
| 4,614
| 2.0625
| 2
|
[] |
no_license
|
package mm.com.blueplanet.bppay.encryptedexo;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import com.google.android.exoplayer2.DefaultLoadControl;
import com.google.android.exoplayer2.DefaultRenderersFactory;
import com.google.android.exoplayer2.ExoPlayerFactory;
import com.google.android.exoplayer2.SimpleExoPlayer;
import com.google.android.exoplayer2.source.ExtractorMediaSource;
import com.google.android.exoplayer2.source.MediaSource;
import com.google.android.exoplayer2.trackselection.AdaptiveTrackSelection;
import com.google.android.exoplayer2.trackselection.DefaultTrackSelector;
import com.google.android.exoplayer2.trackselection.TrackSelection;
import com.google.android.exoplayer2.trackselection.TrackSelector;
import com.google.android.exoplayer2.ui.PlayerView;
import com.google.android.exoplayer2.upstream.BandwidthMeter;
import com.google.android.exoplayer2.upstream.DefaultBandwidthMeter;
import com.google.android.exoplayer2.upstream.DefaultHttpDataSourceFactory;
import com.google.android.exoplayer2.util.Log;
import com.google.android.exoplayer2.util.Util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class MainActivity extends AppCompatActivity {
private CipherOutputStream outputStream;
private final String TAG = MainActivity.class.getSimpleName();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.btn_encrypt).setOnClickListener(view -> {
encrypt();
});
findViewById(R.id.btn_play).setOnClickListener(view -> {
Intent intent = new Intent(getApplicationContext(), PlayerActivity.class);
MainActivity.this.startActivity(intent);
});
findViewById(R.id.btn_decrypt).setOnClickListener(view -> {
decrypt();
});
}
private void decrypt() {
try {
File encryptedFile = new File(getExternalFilesDir("haha"), "encrypt.mp4");
Cipher cipher = getCipher(Cipher.DECRYPT_MODE);
CipherInputStream cipherInputStream = new CipherInputStream(new FileInputStream(encryptedFile), cipher);
File decryptedFile = new File(getExternalFilesDir("haha"), "decrypted.mp4");
OutputStream outputStream = new FileOutputStream(decryptedFile);
byte[] buffer = new byte[8 * 1024];
int bytesRead;
while ((bytesRead = cipherInputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
cipherInputStream.close();
outputStream.close();
} catch (Exception e) {
}
}
private void encrypt() {
try {
File file = new File(getExternalFilesDir("haha"), "1.mp4");
InputStream inputStream = new FileInputStream(file);
Cipher cipher = getCipher(Cipher.ENCRYPT_MODE);
File encryptedFile = new File(getExternalFilesDir("haha"), "encrypt.mp4");
OutputStream fos = new FileOutputStream(encryptedFile);
outputStream = new CipherOutputStream(fos, cipher);
byte[] buffer = new byte[8 * 1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
Log.d(TAG, "DONE");
} catch (Exception e) {
}
}
private Cipher getCipher(int mode) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException, InvalidKeyException {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
SecretKeySpec keySpec = new SecretKeySpec("0123456789012345".getBytes(), "AES");
IvParameterSpec ivSpec = new IvParameterSpec("0123459876543210".getBytes());
cipher.init(mode, keySpec, ivSpec);
return cipher;
}
}
| true
|
5e53b207a3d6946270c5d865d3b798cb560796c6
|
Java
|
yoann1995/Projet-SEP
|
/src/application/Afficheur.java
|
UTF-8
| 862
| 2.875
| 3
|
[] |
no_license
|
package application;
import java.util.concurrent.ExecutionException;
import javax.swing.JTextArea;
import observer.CapteurAsync;
import observer.Observer;
/**
* Obsever of capteurAsync.
*
* @author yoann et Mehidine
*/
public class Afficheur implements Observer<CapteurAsync>{
/** Graphic text which will be modifiate. */
private JTextArea txtCounter;
/**
* Constructor of Afficheur
*
* @param counter the counter
*/
public Afficheur(JTextArea counter) {
txtCounter = counter;
}
/* (non-Javadoc)
* @see observer.Observer#update(java.lang.Object)
*/
@Override
public void update(CapteurAsync subject) {
// TODO Auto-generated method stub
try {
txtCounter.setText(subject.getValue().get().toString());
} catch (InterruptedException | ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| true
|
d71e15760da4a7c900c0f920640d9888ad6a6b9e
|
Java
|
moutainhigh/agency
|
/build_debug/src/com/greatchn/agency/controller/system/IndexController.java
|
UTF-8
| 10,385
| 1.929688
| 2
|
[] |
no_license
|
package com.greatchn.agency.controller.system;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.greatchn.agency.bean.UserInfo;
import com.greatchn.agency.common.constants.Constants;
import com.greatchn.agency.service.employee.EmployeeService;
import com.greatchn.agency.service.enterprise.EnterpriseLoginSrv;
import com.greatchn.agency.service.enterprise.EnterpriseRegisterSrv;
import com.greatchn.agency.web.NotNeedIntercepter;
import com.greatchn.agency.web.UserLoginIntercepter;
import com.greatchn.db.po.agency.EmployeeInfo;
import com.greatchn.db.po.agency.EnterpriseInfo;
import com.greatchn.db.po.system.SystemFunction;
import com.greatchn.utils.annotation.SaveLog;
import com.greatchn.utils.bean.Result;
import com.greatchn.utils.tools.ConstantUtil;
@Controller
@RequestMapping("/")
public class IndexController {
@Resource
EmployeeService employeeService;
@Resource
EnterpriseLoginSrv enterpriseLoginSrv;
@Resource
EnterpriseRegisterSrv enterpriseRegisterSrv;
/**
* 主页视图
*/
private static final String VIEW_INDEX = "index/index";
/**
* 欢迎页视图
*/
private static final String VIEW_WELCOME = "index/home";
/**
* 员工登录页
*/
private static final String EMP_TO_LOGIN = "login/employee_login";
/**
* 企业登录页
*/
private static final String TO_LOGIN = "login/enterprise_login";
/**
* 没有权限视图
*/
private static final String NO_AUTH = "wrong/noAuth";
/**
* 404错误页面
*/
private static final String VIEW_ERROR_404 = "wrong/404";
/**
* 500错误页面
*/
private static final String VIEW_ERROR_500 = "wrong/500";
/**
* css组件demo页
*/
private static final String DEMO_INDEX = "index";
/**
* 默认首页
*
* @param session
* @return
*/
@RequestMapping
@NotNeedIntercepter
public ModelAndView index(HttpSession session) {
Object user = session.getAttribute(Constants.SESSION_LOGIN_USER);
ModelAndView view = null;
if (user == null) {
// 跳转到登录页面
view = new ModelAndView("redirect:/toLogin");
} else {
// 转发到首页
view = new ModelAndView(VIEW_INDEX);
}
return view;
}
/**
*
* <p>
* 去员工登录页
* </p>
*
* @return ModelAndView
* @author zy
* @time 2017-11-17
*/
@RequestMapping("/toLogin")
@SaveLog(info = "去员工登录页")
@NotNeedIntercepter
@UserLoginIntercepter
public ModelAndView toLogin(HttpServletRequest request) {
return new ModelAndView(EMP_TO_LOGIN);
}
/**
*
* <p>
* 去企业登录页
* </p>
*
* @return
* @throws Exception
* @author CHR 2017-11-30
*/
@RequestMapping("/toEnterpriseLogin")
@SaveLog(info = "去企业登录页")
@NotNeedIntercepter
@UserLoginIntercepter
public ModelAndView toEnterpriseLogin() throws Exception {
return new ModelAndView(TO_LOGIN);
}
/**
*
* <p>
* 员工登录
* </p>
*
* @param request
* @param response
* @param userName
* 登录用户名:master@企业id
* @param password
* @param cookieType
* long-为记住密码一周 short-会话级(浏览器关闭失效)
* @return
* @throws Exception
* @author zy 2017-11-14
*/
@RequestMapping("/empLogin")
@SaveLog(info = "员工登录")
@NotNeedIntercepter
@UserLoginIntercepter
public ModelAndView employeeLogin(HttpServletRequest request, HttpServletResponse response, String userName, String password, String cookieType) throws Exception {
ModelAndView modelAndView = new ModelAndView(EMP_TO_LOGIN); // 错误跳转到员工登录页
String message = ConstantUtil.getValue("LOGIN_ERROR_INFO"); // 默认错误提示信息用户不存在或密码错误
if (StringUtils.isNotEmpty(userName)) {
String reg = "^[A-Za-z0-9_]{1,}@[^@][0-9]{1,12}$"; // 验证格式账号格式是否正确
Pattern regp = Pattern.compile(reg);
Matcher regm = regp.matcher(userName);
boolean flag = regm.matches();
if(flag){
String[] str = StringUtils.split(userName, "@");
// 1、获取员工的所属企业id
String eid = str[1];
// 2、获取个性账号
String account = str[0];
// 判断是否为master账号,若是则不可登录
if (!StringUtils.equals(ConstantUtil.getValue("emp_account"), account)) {
UserInfo user = employeeService.Login(request, response, account, eid, password, "N", cookieType);
if (user != null) {
// 登录功返成回首页
modelAndView.setViewName("redirect:/");
message = null;
}
}
}
} else {// 用户直接刷新页面无错误信息
message = null;
}
modelAndView.addObject("message", message);
return modelAndView;
}
/**
*
* <p>
* 企业登录
* </p>
*
* @param email
* @param password
* @param cookieType
* cookie类型(浏览器cookie或7天cookie)
* @param response
* @throws Exception
* @author CHR 2017-11-28
* @return
*/
@RequestMapping("/enterpriseLogin")
@NotNeedIntercepter
@UserLoginIntercepter
@SaveLog(info = "企业登录")
public ModelAndView login(String email, String password, String cookieType, HttpServletResponse response, HttpSession session, HttpServletRequest request) throws Exception {
if (StringUtils.isEmpty(email) && StringUtils.isEmpty(password)) {
return new ModelAndView(TO_LOGIN);
}
EnterpriseInfo enterprise = enterpriseLoginSrv.login(email, password);
if (enterprise == null) {
return new ModelAndView(TO_LOGIN).addObject("message", ConstantUtil.getValue("LOGIN_ERROR_INFO"));
} else if (Constants.FOR_ACTIVATE.equals(enterprise.getState())) {
return new ModelAndView("redirect:/register/enterpriseRegisterSuc?id=" + enterprise.getId() + "&flag=login");
} else {
// 用户登录
EmployeeInfo employeeInfo = employeeService.findByEidAndAccount(enterprise.getId(), ConstantUtil.getValue("emp_account"));
if (employeeInfo != null) {
UserInfo user = employeeService.Login(request, response, employeeInfo.getAccount(), employeeInfo.getEId().toString(), password, "N", cookieType);
// 登陆成功
if (user != null) {
// 去首页
return new ModelAndView("redirect:/");
} else {
// 去登录页
return new ModelAndView(TO_LOGIN).addObject("message", ConstantUtil.getValue("LOGIN_ERROR_INFO"));
}
} else {
// 去登录页
return new ModelAndView(TO_LOGIN).addObject("message", ConstantUtil.getValue("LOGIN_ERROR_INFO"));
}
}
}
/**
*
* <p>
* 获取用户基本信息
* </p>
*
* @param session
* @return
* @author LZhang 2017-11-23
*/
@RequestMapping("/get_session_info")
@ResponseBody
@SaveLog(info = "获取用户session基本信息")
public Result getSessionInfo(HttpSession session) {
UserInfo user = (UserInfo) session.getAttribute(Constants.SESSION_LOGIN_USER);
if (user != null) {
return Result.success(user);
} else {
return Result.fail("");
}
}
/**
*
* <p>
* 404、500、无授权页面
* </p>
*
* @return
*/
@RequestMapping("/blank")
public ModelAndView blank() {
return new ModelAndView(VIEW_WELCOME);
}
@RequestMapping("/404")
public ModelAndView _404() {
return new ModelAndView(VIEW_ERROR_404);
}
@RequestMapping("/500")
public ModelAndView _500() {
return new ModelAndView(VIEW_ERROR_500);
}
/**
*
* <p>
* 去css组件demo页
* </p>
*
* * @return
*/
@RequestMapping("/demo")
public ModelAndView toDemo() {
return new ModelAndView(DEMO_INDEX);
}
/**
*
* <p>
* 退出登录
* </p>
*
* @return
* @throws Exception
* @author CHR 2017-12-1
*/
@RequestMapping("/loginOut")
@NotNeedIntercepter
@SaveLog(info = "退出登录")
public ModelAndView loginOut(HttpServletRequest request, HttpServletResponse response) throws Exception {
request.getSession().removeAttribute(Constants.SESSION_LOGIN_USER);
Cookie[] cookies = request.getCookies();// 获取一个cookie数组
if (cookies != null && cookies.length > 0) {
for (int i = 0; i < cookies.length; i++) {
if (Constants.COOKIE_LOGIN_USER_BROWSER.equals(cookies[i].getName()) || Constants.COOKIE_LOGIN_USER.equals(cookies[i].getName())) {
cookies[i].setMaxAge(0);
cookies[i].setPath("/");
response.addCookie(cookies[i]);
}
}
}
return new ModelAndView("redirect:/");
}
/**
* 跳转功能页面,如果允许跳转,则直接转发到具体的功能页面,如果不允许,转发到无授权页面
*
* @param session
* @return
* @author LWang 2017.11.24
*/
@RequestMapping("/link/{fun_code}")
public ModelAndView link(HttpServletRequest request, HttpSession session, @PathVariable("fun_code") String funCode) {
UserInfo user = (UserInfo) session.getAttribute(Constants.SESSION_LOGIN_USER);
SystemFunction fun = user.getFun(funCode);
ModelAndView view;
if (fun != null) {
if (fun.getAction().toUpperCase().startsWith("http")) {
view = new ModelAndView(fun.getAction());
} else {
view = new ModelAndView("redirect:" + fun.getAction() + "?" + request.getQueryString());
}
} else {
view = new ModelAndView(NO_AUTH);
}
return view;
}
/**
*
* <p>
* 获取用户状态
* </p>
*
* @return
* @author CHR 2017-11-25
*/
@RequestMapping("/getState")
@ResponseBody
@SaveLog(info = "获取用户状态")
public Result getState(HttpSession session) {
EnterpriseInfo enterpriseInfo = new EnterpriseInfo();
UserInfo user = (UserInfo) session.getAttribute(Constants.SESSION_LOGIN_USER);
EmployeeInfo employee = user.getEmployee();
if (ConstantUtil.getValue("emp_account").equals(employee.getAccount())) {
enterpriseInfo = enterpriseRegisterSrv.getEnterpriseInfo(employee.getEId());
user.setEnterprise(enterpriseInfo);
session.setAttribute(Constants.SESSION_LOGIN_USER, user);
}
return Result.success(enterpriseInfo.getState());
}
}
| true
|
d33adac91482f13a4651c3a09e512d247b8fe113
|
Java
|
Tragueta/UniOpetSAPNew
|
/app/src/main/java/com/example/guilhermetragueta/uniopetsap20/activity/HomeFB.java
|
UTF-8
| 1,805
| 2.03125
| 2
|
[] |
no_license
|
package com.example.guilhermetragueta.uniopetsap20.activity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.example.guilhermetragueta.uniopetsap20.R;
import com.facebook.AccessToken;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import java.util.ArrayList;
public class HomeFB extends Activity {
private Button btnLogout;
private FirebaseAuth firebaseAuth;
private TextView txtLocaliza;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_fb);
firebaseAuth = FirebaseAuth.getInstance();
btnLogout = findViewById(R.id.btnLogoutFB);
txtLocaliza = findViewById(R.id.txtLocalizaFB);
// Metodo usado para redirecionar o usuario para tela de 'Localizar campus UniOpet'
txtLocaliza.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent localizaIntent = new Intent(HomeFB.this, UnidadesUniOpetFB.class);
startActivity(localizaIntent);
finish();
}
});
// Metodo utilizado para realizar o logout do app
btnLogout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AccessToken.setCurrentAccessToken(null);
firebaseAuth.signOut();
Intent loginIntent = new Intent(HomeFB.this, MainActivity.class);
startActivity(loginIntent);
finish();
}
});
}
}
| true
|
10fed84abfae0e94b74d896fcb95a149effc6804
|
Java
|
lusoalex/talk-api-security
|
/back/src/main/java/com/github/lusoalex/talkapisecurity/model/User.java
|
UTF-8
| 1,643
| 2.546875
| 3
|
[
"Apache-2.0"
] |
permissive
|
package com.github.lusoalex.talkapisecurity.model;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.experimental.Wither;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import java.io.Serializable;
@ApiModel(description = "User representation only used as demo.")
@Entity
@Wither
@Data
@AllArgsConstructor
public class User implements Serializable {
@Id
@ApiModelProperty(hidden = true, notes = "Unique identifier of the user.", example = "0a74c71b-fd98-4c99-b4c7-1bfd981c9912")
private String id;
@ApiModelProperty(notes = "First name of the user.", example = "John", required = true, position = 1)
private String firstName;
@ApiModelProperty(notes = "Last name of the user.", example = "Doe", required = true, position = 2)
private String lastName;
@Column(unique=true)
@ApiModelProperty(notes = "username/login of the user.", example = "rand0mlY", required = true, position = 3)
private String username;
@ApiModelProperty(notes = "password of the user.", example = "rand0mlY", required = true, position = 4)
private String password;
public User() {
}
//standard setters and getters
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
'}';
}
}
| true
|
f08d3e8573e5a0eb82b7d3379448aa0cee88f057
|
Java
|
jormaral/allocalgis
|
/seguridad/localgismezcla/geocoder/src/org/deegree_impl/services/wfs/db/PointDBDataStoreOutputGML.java
|
UTF-8
| 16,672
| 2.03125
| 2
|
[] |
no_license
|
/*---------------- FILE HEADER ------------------------------------------
This file is part of deegree.
Copyright (C) 2001 by:
EXSE, Department of Geography, University of Bonn
http://www.giub.uni-bonn.de/exse/
lat/lon Fitzke/Fretter/Poth GbR
http://www.lat-lon.de
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact:
Andreas Poth
lat/lon Fitzke/Fretter/Poth GbR
Meckenheimer Allee 176
53115 Bonn
Germany
E-Mail: poth@lat-lon.de
Jens Fitzke
Department of Geography
University of Bonn
Meckenheimer Allee 166
53115 Bonn
Germany
E-Mail: jens.fitzke@uni-bonn.de
---------------------------------------------------------------------------*/
package org.deegree_impl.services.wfs.db;
import java.io.StringReader;
import java.io.StringWriter;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.deegree.gml.GMLFeatureCollection;
import org.deegree.model.table.Table;
import org.deegree.services.wfs.DataStoreOutputFormat;
import org.deegree.services.wfs.WFSConstants;
import org.deegree.services.wfs.configuration.FeatureType;
import org.deegree.services.wfs.configuration.GeoFieldIdentifier;
import org.deegree.services.wfs.configuration.TableDescription;
import org.deegree.tools.Parameter;
import org.deegree.tools.ParameterList;
import org.deegree.xml.DOMPrinter;
import org.deegree.xml.XMLTools;
import org.deegree_impl.gml.GMLFeatureCollection_Impl;
import org.deegree_impl.model.geometry.GeometryFactory;
import org.deegree_impl.tools.Debug;
import org.deegree_impl.tools.StringExtend;
import org.w3c.dom.Document;
/**
* Implements the DataStoreOutputFormat interface to format the result of a
* data accessing class returned within the values of a HashMap as GML
* feature collection
*
* <p>-----------------------------------------------------------------------</p>
*
* @author <a href="mailto:poth@lat-lon.de">Andreas Poth</a>
* @version $Revision: 1.1 $ $Date: 2009/07/09 07:25:32 $
* <p>
*/
public class PointDBDataStoreOutputGML implements DataStoreOutputFormat {
private double minx = 9E99;
private double miny = 9E99;
private double maxx = -9E99;
private double maxy = -9E99;
private GeometryFactory factory = new GeometryFactory();
/**
* formats the data store at the values of the HashMap into
* one single data structure.
*/
public Object format(HashMap map, ParameterList paramList) throws Exception {
Debug.debugMethodBegin( this, "format" );
Parameter p = paramList.getParameter( WFSConstants.NAMESPACE );
String s = "";
if ( p != null ) s = (String)p.getValue();
// create the basic gml document
StringBuffer gml = new StringBuffer(250000);
gml.append( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" );
gml.append( "<gml:Collection xmlns:gml=\"http://www.opengis.net/gml\" " + s + ">");
gml.append( "<gml:boundedBy><gml:Box><gml:coord><gml:X>-9E99</gml:X>" );
gml.append( "<gml:Y>-9E99</gml:Y></gml:coord><gml:coord><gml:X>9E99</gml:X>" );
gml.append( "<gml:Y>9E99</gml:Y></gml:coord></gml:Box></gml:boundedBy>" );
Iterator iterator = map.values().iterator();
// for each table within the received HashMap
while ( iterator.hasNext() ) {
ParameterList pl = (ParameterList)iterator.next();
p = pl.getParameter( WFSConstants.TABLE );
Table table = (Table)p.getValue();
// for each row of each table a feature will be created and added to
// the feature collection
gml = tableToGML( table, pl, gml );
}
gml.append("</gml:Collection>");
Document doc = XMLTools.parse( new StringReader( gml.toString() ) );
// create the feature collection that will contain all requested
// features (table rows)
GMLFeatureCollection fc = new GMLFeatureCollection_Impl( doc.getDocumentElement() );
fc.setBoundingBox( minx, miny, maxx, maxy );
p = paramList.getParameter( WFSConstants.FILTER );
if ( p != null ) {
s = DOMPrinter.nodeToString( ((GMLFeatureCollection_Impl)fc).getAsElement(), "" );
doc = xsltTransformGetFeature(s, (String)p.getValue() );
fc = new GMLFeatureCollection_Impl( doc.getDocumentElement() );
}
Debug.debugMethodEnd();
return fc;
}
/**
* creates a <tt>GMLFeatureCollection</tt> from a <tt>Table</tt>. the
* method is recursivly called to create complex features.
*/
private StringBuffer tableToGML(Table table, ParameterList pl,
StringBuffer gml) throws Exception {
Debug.debugMethodBegin( this, "tableToGML" );
ArrayList baseStack = new ArrayList();
HashMap propNameCache = new HashMap();
String tableName = table.getTableName();
FeatureType ft = (FeatureType)pl.getParameter( WFSConstants.FEATURETYPE ).getValue();
String[] columnNames = table.getColumnNames();
TableDescription td = ft.getTableByName( tableName );
// get id property name
String idProp = td.getIdField();
// get coordinate reference system
String crs = (String)pl.getParameter( WFSConstants.CRS ).getValue();
for (int r = 0; r < table.getRowCount(); r++) {
gml.append( "<gml:featureMember>" );
Object[] row = table.getRow( r );
int cnt = 0;
for (int i = 0; i < row.length; i++) {
if ( row[i] != null ) {
cnt+= row[i].toString().length();
}
}
StringBuffer feat = new StringBuffer(cnt);
// clear register of already handled geo fields
baseStack.clear();
String id = "ID" + r;
// transform the current row of the table to a GMLFeature
for (int i = 0; i < row.length; i++) {
// get feature id
if ( columnNames[i].equalsIgnoreCase( idProp ) ) {
id = row[i].toString();
try {
double d = Double.parseDouble( id );
id = "ID" + (int)d;
} catch (Exception ee) {
id = id.replace(' ','_');
}
}
String pn = null;
if ( columnNames[i].equals( "COUNTCOUNT" ) ) {
pn = "_COUNT_";
} else {
String s = ft.getPropertyFromAlias( columnNames[i] );
if ( s == null ) s = ft.getPropertyFromAlias( tableName + "." + columnNames[i] );
if ( s == null ) s = tableName + "." + columnNames[i];
pn = (String)propNameCache.get( columnNames[i] );
if ( pn == null ) {
pn = formatPropertyName( s );
propNameCache.put( columnNames[i], pn );
}
}
// get geometry column identfier
GeoFieldIdentifier gfi = td.getGeoFieldIdentifier( columnNames[i] );
if ( gfi == null ) {
// create and add none-geometry properties to the feature
if ( row[i] != null && row[i] instanceof Table ) {
// create complex property
StringBuffer gml_ = new StringBuffer( "<gml:Collection>" );
// recursive call of the method
gml_ = tableToGML( (Table)row[i], pl, gml_ );
gml_.append( "</gml:Collection>" );
feat.append( "<" + pn + ">" ).append( gml_.toString() );
feat.append( "</" + pn + ">" );
} else {
if ( row[i] != null ) {
feat.append( "<" + pn + ">" );
if ( row[i] != null ) {
feat.append( XMLTools.validateCDATA( row[i].toString() ) );
}
feat.append( "</" + pn + ">" );
} else {
// create an empty property
feat.append( "<" + pn + "/>" );
}
}
} else {
String base = gfi.getDatastoreFieldBaseName();
// check if geom field has already been handled
if ( !baseStack.contains( base ) ) {
String s = ft.getPropertyFromAlias( base );
if ( s == null ) s = ft.getPropertyFromAlias( tableName + "." + base );
if ( s == null ) s = tableName + "." + base;
pn = (String)propNameCache.get( base );
if ( pn == null ) {
pn = formatPropertyName( s );
propNameCache.put( base, pn );
}
baseStack.add( base );
int dim = gfi.getDimension();
// get x- and y-column indizes
int x = getColumnIndex( columnNames, base + "_X" );
int y = getColumnIndex( columnNames, base + "_Y" );
// not supported yet
// int z = -1;
// if ( dim == 3 ) z = getColumnIndex( columnNames, base + "_Z" );
// create and add geometry property to the feature
if ( row[x] != null && row[y] != null ) {
updateBoundingBox( row[x].toString(), row[y].toString() );
String s_ = getGeoProperty( pn, row[x].toString(), row[y].toString(), crs );
feat.append( "<" + pn + ">" ).append( s_ );
feat.append( "</" + pn + ">" );
} else {
// create an empty property
feat.append( "<" + pn + "/>" );
}
}
}
}
gml.append( "<" + td.getTargetName() + " fid=\"" + id + "\">" );
// add feature to the feature collection
gml.append( feat );
gml.append( "</" + td.getTargetName() + ">" );
gml.append( "</gml:featureMember>" );
}
Debug.debugMethodEnd();
return gml;
}
/**
* the method formats a slash-seperated property name like /cities/ID
* to a dot-seperated xml-valid name --> cities.ID
*/
private String formatPropertyName(String property)
{
property = property.replace( '/', '.' );
property = property.replace( '@', '.' );
return StringExtend.validateString( property, "." );
}
/**
* returns the index of the submitted name within the also submitted
* array of column names
*/
private int getColumnIndex(String[] columnNames, String name) {
int pos = name.lastIndexOf('.');
if ( pos > -1 ) {
name = name.substring( pos+1, name.length() );
}
for (int i = 0; i < columnNames.length; i++) {
if ( columnNames[i].equalsIgnoreCase( name ) ) {
return i;
}
}
return -1;
}
/**
* creates a <tt>GMLProperty<tt> from its <tt>String<tt> representation.
*/
private String getGeoProperty(String name, String x, String y, String crs ) throws Exception {
StringBuffer sb = new StringBuffer(50);
if ( crs != null && crs.indexOf( ":" ) > -1 ) {
String[] cs = StringExtend.toArray( crs, ":", false );
crs = "http://www.opengis.net/gml/srs/" + cs[0].toLowerCase() + ".xml#" + cs[1];
sb.append( "<gml:Point srsName=\"" + crs + "\">" );
} else {
sb.append( "<gml:Point>" );
}
sb.append( "<gml:coordinates cs=\",\" decimal=\".\" ts=\" \">" );
sb.append( x + "," + y );
sb.append( "</gml:coordinates>" );
sb.append( "</gml:Point>" );
return sb.toString();
}
/**
* updates the bounding box of the <tt>GMLFeatureCollection<tt>.
*/
private void updateBoundingBox(String xs, String ys) {
double x = Double.parseDouble( xs );
double y = Double.parseDouble( ys );
if ( x < minx ) minx = x;
if ( x > maxx ) maxx = x;
if ( y < miny ) miny = y;
if ( y > maxy ) maxy = y;
}
/**
* transforms the response to a GetRecord/Feature request using
* a predefined xslt-stylesheet
*/
private Document xsltTransformGetFeature(String gml, String xsltURL) {
Debug.debugMethodBegin( this, "xsltTransformGetFeature" );
Document document = null;
try {
document = XMLTools.parse( new StringReader( gml ) );
// Use the static TransformerFactory.newInstance() method to instantiate
// a TransformerFactory. The javax.xml.transform.TransformerFactory
// system property setting determines the actual class to instantiate --
// org.apache.xalan.transformer.TransformerImpl.
TransformerFactory tFactory = TransformerFactory.newInstance();
// Use the TransformerFactory to instantiate a Transformer that will work with
// the stylesheet you specify. This method call also processes the stylesheet
// into a compiled Templates object.
URL url = new URL( xsltURL );
Transformer transformer =
tFactory.newTransformer( new StreamSource( url.openStream() ) );
// Use the Transformer to apply the associated Templates object to an XML document
// (foo.xml) and write the output to a file (foo.out).
StringWriter sw = new StringWriter();
transformer.transform(new DOMSource(document), new StreamResult( sw ));
document = XMLTools.parse( new StringReader( sw.toString() ) );
} catch(Exception e) {
Debug.debugException( e, "an error/fault body for the soap message will be created");
//TODO exception
}
Debug.debugMethodEnd();
return document;
}
}
| true
|
e3ac7bca745a18451c82be13bf3a9e26ee8d01f2
|
Java
|
J-Cake/Ark
|
/src/main/java/au/com/jschneiderprojects/ark/Lexer/Grammar/TokenType.java
|
UTF-8
| 397
| 2.078125
| 2
|
[] |
no_license
|
package au.com.jschneiderprojects.ark.Lexer.Grammar;
public enum TokenType {
String,
Int,
Float,
Boolean,
Null,
Block,
Operator,
Construct,
Comma,
SubReference,
LeftParenthesis,
RightParenthesis,
LeftBracket,
RightBracket,
LeftBrace,
RightBrace,
Reference,
NewLine,
Comment,
Invocation,
Assignment,
Lambda
}
| true
|
3c070a134b0e194c99c6b33d07600d6dd8a71a41
|
Java
|
chenguoku/AllWorkSpace
|
/designMode/装饰着模式/MyProject/src/com/hh/coffeebar/coffee/Coffee.java
|
UTF-8
| 169
| 2.28125
| 2
|
[] |
no_license
|
package com.hh.coffeebar.coffee;
import com.hh.coffeebar.Drink;
public class Coffee extends Drink {
@Override
public float cost() {
return super.getPrice();
}
}
| true
|
c1ba1994c041270e15e51fcee63a4cf3d5afb5e1
|
Java
|
MattChad1/P4_MaReu
|
/app/src/main/java/com/mchadeville/mareu/util/Utils.java
|
UTF-8
| 2,221
| 2.890625
| 3
|
[] |
no_license
|
package com.mchadeville.mareu.util;
import com.google.android.material.textfield.TextInputLayout;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
public class Utils {
public static String textFromTextInputLayout(TextInputLayout til) {
return Objects.requireNonNull(til.getEditText()).getText().toString();
}
public static String listToStringRevert(List<String> list) {
String re = "";
for (int i= list.size() -1 ; i>=0; i--) {
if (!re.isEmpty()) re += "\n";
re += list.get(i);
}
return re;
}
public static String listToString(List<String> list) {
String re = "";
for (String st: list) {
if (!re.isEmpty()) re += ", ";
re += st;
}
return re;
}
public static Calendar dateStringToCalendar(String str) {
String[] c = str.split("/");
Calendar cdr = Calendar.getInstance();
cdr.set(Integer.parseInt(c[2]), Integer.parseInt(c[1]) - 1, Integer.parseInt(c[0]));
return cdr;
}
public static String calendarToString(Calendar cal) {
SimpleDateFormat format1 = new SimpleDateFormat("dd/MM/yyyy");
return format1.format(cal.getTime());
}
public static long daysBetween(Calendar startDate, Calendar endDate) {
//Make sure we don't change the parameter passed
Calendar newStart = Calendar.getInstance();
newStart.setTimeInMillis(startDate.getTimeInMillis());
newStart.set(Calendar.HOUR_OF_DAY, 0);
newStart.set(Calendar.MINUTE, 0);
newStart.set(Calendar.SECOND, 0);
newStart.set(Calendar.MILLISECOND, 0);
Calendar newEnd = Calendar.getInstance();
newEnd.setTimeInMillis(endDate.getTimeInMillis());
newEnd.set(Calendar.HOUR_OF_DAY, 0);
newEnd.set(Calendar.MINUTE, 0);
newEnd.set(Calendar.SECOND, 0);
newEnd.set(Calendar.MILLISECOND, 0);
long end = newEnd.getTimeInMillis();
long start = newStart.getTimeInMillis();
return TimeUnit.MILLISECONDS.toDays(Math.abs(end - start));
}
}
| true
|
3e269e6c9627c5810d2c6765b620389a2bea7a9b
|
Java
|
vaibhavsaxena022/Java
|
/gcdorhcf.java
|
UTF-8
| 405
| 2.953125
| 3
|
[] |
no_license
|
import javax.swing.*;
import java.util.*;
public class gcdorhcf
{
public static void main(String[] args)
{
int num1 = Integer.parseInt(JOptionPane.showInputDialog("enter num1 : "));
int num2 = Integer.parseInt(JOptionPane.showInputDialog("enter num2 : "));
while(num1 != num2)
{
if(num1>num2)
num1 = num1-num2;
else
num2 = num2-num1;
}
System.out.println("hcf : "+num2);
}
}
| true
|
ae2dc34e4d5372ac2d293b493603803b64cf2713
|
Java
|
rbsysnn/AI-Shepherd-Robot
|
/src/main.java
|
UTF-8
| 501
| 2.09375
| 2
|
[] |
no_license
|
import lejos.hardware.Button;
public class main {
public static void main(String[] args )
{
Robot farripas = new Robot();
//farripas.debugReconhe();
//farripas.reconheceTabuleiro();
//farripas.debugMatrizPrint();
farripas.debugFactores();
farripas.calculaBarreiras();
farripas.imprimeNumBarrreiras();
System.out.println("Carregue em qualquer botao para comecar o jogo.");
Button.waitForAnyPress();
farripas.preenchePeso();
farripas.meteNoCurral(1);
return;
}
}
| true
|
2494ee5876034b3587348b0a22e055006dc547c6
|
Java
|
Saipreetha/javawipro
|
/inheritance/Employee.java
|
UTF-8
| 771
| 3.296875
| 3
|
[] |
no_license
|
package inheritance;
public class Employee extends Person{
double annualSalary;
int yearOfJoining;
String natInsuNum;
Employee(){
super("Sam");
}
Employee(double annualSalary){
super();
this.annualSalary=annualSalary;
}
Employee(String natInsuNum){
this();
this.natInsuNum=natInsuNum;
}
void display(){
System.out.println("The salary of the person is:"+annualSalary);
}
void disp2(){
System.out.println("The national insurance number of the person is:"+natInsuNum);
}
}
class TestEmployee{
public static void main(String args[]){
Employee me1 = new Employee(2.89);
Employee me = new Employee("12309");
me1.display();
me.disp2();
}
}
| true
|
7f32cec936669fd9e595351c7589e4cb3e3300fc
|
Java
|
kvourlakidis/project-euler
|
/Problem022.java
|
UTF-8
| 1,517
| 3.671875
| 4
|
[] |
no_license
|
import java.io.IOException;
import java.io.FileReader;
import java.io.BufferedReader;
import java.util.ArrayList;
/*
Using Problem022.txt, a text file containing five-thousand first names,
begin by sorting them into alphabetical order. Then working out the
alphabetical value for each name, multiply this value by its alphabetical
position in the list to obtain a name score.
For example, when the list is sorted into alphabetical order, COLIN, which
is worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list.
So, COLIN would obtain a score of 938 x 53 = 49714.
What is the total of all the name scores in the file?
*/
public class Problem022 {
public static void main(String[] args) throws IOException {
String file = "Problem022.txt";
FileReader reader = new FileReader(file);
BufferedReader breader = new BufferedReader(reader);
String lineString = "";
lineString = breader.readLine();
String[] names = lineString.split(",");
System.out.println(names.length);
}
String[] sort(String[] a) {
}
void transpose(String[] array, int a, int b) {
if (array[a] == array[b]) {
return;
} else if (a < b && array[a] > array[b]) {
String temp = array[a];
array[a] = array[b];
array[b] = temp;
} else if (a > b && array[a] < array[b]) {
temp = array[a];
array[a] = array[b];
array[b] = temp;
}
}
}
| true
|
c34fcc83afcc9fbd74d436c8886646a6d734bdb8
|
Java
|
tsuzcx/qq_apk
|
/com.tencent.token/classes.jar/com/tencent/token/core/bean/ZzbIntroItem.java
|
UTF-8
| 642
| 1.703125
| 2
|
[] |
no_license
|
package com.tencent.token.core.bean;
import java.io.Serializable;
import org.json.JSONObject;
public class ZzbIntroItem
implements Serializable
{
private static final long serialVersionUID = -2457137122729009982L;
public String desc;
public String title;
public ZzbIntroItem(JSONObject paramJSONObject)
{
this.title = paramJSONObject.optString("title");
this.desc = paramJSONObject.optString("desc");
}
}
/* Location: L:\local\mybackup\temp\qq_apk\com.tencent.token\classes.jar
* Qualified Name: com.tencent.token.core.bean.ZzbIntroItem
* JD-Core Version: 0.7.0.1
*/
| true
|
bf5c8962b56303620d1a22db29bd8ed1a002c2dc
|
Java
|
soneyahossain/hcc-gap-recommender
|
/experiments/subjects/xstream/src/java/com/thoughtworks/xstream/core/util/QuickWriter.java
|
UTF-8
| 2,585
| 2.484375
| 2
|
[
"MIT"
] |
permissive
|
/*
* Copyright (C) 2004, 2005, 2006 Joe Walnes.
* Copyright (C) 2006, 2007, 2009 XStream Committers.
* All rights reserved.
*
* The software in this package is published under the terms of the BSD
* style license a copy of which has been included with this distribution in
* the LICENSE.txt file.
*
* Created on 07. March 2004 by Joe Walnes
*/
package com.thoughtworks.xstream.core.util;
import com.thoughtworks.xstream.io.StreamException;
import java.io.IOException;
import java.io.Writer;
public class QuickWriter {
private final Writer writer;
private char[] buffer;
private int pointer;
public QuickWriter(Writer writer) {
this(writer, 1024);
}
public QuickWriter(Writer writer, int bufferSize) {
this.writer = writer;
buffer = new char[bufferSize];
}
public void write(String str) {
int len = str.length();
if (pointer + len >= buffer.length) {
flush();
if (len > buffer.length) {
raw(str.toCharArray());
return;
}
}
str.getChars(0, len, buffer, pointer);
pointer += len;
}
public void write(char c) {
if (pointer + 1 >= buffer.length) {
flush();
if (buffer.length == 0) {
raw(c);
return;
}
}
buffer[pointer++] = c;
}
public void write(char[] c) {
int len = c.length;
if (pointer + len >= buffer.length) {
flush();
if (len > buffer.length) {
raw(c);
return;
}
}
System.arraycopy(c, 0, buffer, pointer, len);
pointer += len;
}
public void flush() {
try {
writer.write(buffer, 0, pointer);
pointer = 0;
writer.flush();
} catch (IOException e) {
throw new StreamException(e);
}
}
public void close() {
try {
writer.write(buffer, 0, pointer);
pointer = 0;
writer.close();
} catch (IOException e) {
throw new StreamException(e);
}
}
private void raw(char[] c) {
try {
writer.write(c);
writer.flush();
} catch (IOException e) {
throw new StreamException(e);
}
}
private void raw(char c) {
try {
writer.write(c);
writer.flush();
} catch (IOException e) {
throw new StreamException(e);
}
}
}
| true
|
c1837f9dcd5f212909afcd0e988fa22ced21f4cd
|
Java
|
D1version/JavaRush
|
/javarush/test/level22/lesson05/task01/Solution.java
|
UTF-8
| 1,283
| 3.609375
| 4
|
[] |
no_license
|
package com.javarush.test.level22.lesson05.task01;
/* Найти подстроку
Метод getPartOfString должен возвращать подстроку начиная с символа после 1-го пробела и до конца слова,
которое следует после 4-го пробела.
Пример: "JavaRush - лучший сервис обучения Java."
Результат: "- лучший сервис обучения"
На некорректные данные бросить исключение TooShortStringException (сделать исключением).
Сигнатуру метода getPartOfString не менять.
*/
public class Solution
{
public static String getPartOfString(String string) throws TooShortStringException
{
String result = null;
if (string == null || string.isEmpty() || !string.contains(" ") || string.length() < 5)
throw new TooShortStringException();
String[] arr = string.split(" ");
if (arr.length < 5)
throw new TooShortStringException();
result = arr[1] + " " + arr[2] + " " + arr[3] + " " + arr[4];
return result;
}
public static class TooShortStringException extends Exception
{
}
}
| true
|
7da5935bfa9bc5187df57db18080777ac78e17a3
|
Java
|
alireza-ansaripour/Database
|
/src/controller/ClauseNode.java
|
UTF-8
| 16,356
| 3.125
| 3
|
[] |
no_license
|
package controller;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import controller.commands.OrException;
public class ClauseNode {
private boolean isLeaf;
public int operator;//0:AND, 1:OR. this Node can not be leaf.
private ClauseNode leftNode;
private ClauseNode rightNode;
private int aggregationFunction;//0:MAX, 1:MIN, 2:SUM, 3:AVE.
private String aggregationVariable;//a variable name like MAX(aggregationVariable).
private int aggregationValue;//value of aggregation function.
private int singleOperator;//4:> ,3:>= ,2:= ,1:<= ,1:< .this Node must be leaf.
private String variableName;//if this Node is a leaf must has an operand.
private String variableValue;//if this Node is a leaf its variable must has a value.
public boolean not = false;//if this Node is a leaf can has a not operator.if true its operator is != else =.
private boolean isConst;
private boolean constant;
private boolean isFull;//if this node has two children or this node is leaf this variable is true.
/**
* constructor.
* @param operator 0:AND, 1:OR.
*/
public ClauseNode(int operator){
this.isLeaf=false;
this.isConst=false;
this.isFull=false;
this.operator=operator;
}
/**
* constructor.
* called when condition is a leaf.(does not contain AND or OR)
* @param condition if condition does not contains AND or OR or NOT then we can send it to this constructor.
*/
public ClauseNode(String condition){
this.isLeaf=true;
this.isFull=true;
if(condition.equals("TRUE")){
this.isConst=true;
this.constant=true;
}
else if(condition.equals("FALSE")){
this.isConst=true;
this.constant=false;
}
else{
this.isConst=false;
int operator;
String temp;
if(condition.contains(">=")==true){
operator=3;
temp=">=";
}
else if(condition.contains("<=")==true){
operator=1;
temp="<=";
}
else if(condition.contains(">")==true){
operator=4;
temp=">";
}
else if(condition.contains("=")==true){
operator=2;
temp="=";
}
//condition.contains("<")==true
else{
operator=0;
temp="<";
}
String[] result=condition.split(temp);
this.singleOperator=operator;
this.variableName=clearSpace(result[0]);
this.variableValue=clearSpace(result[1]);
}
}
/**
* gets a string and remove free space of start and end of it.
* @param str
* @return
*/
private String clearSpace(String str){
int index1=0;
int index2=str.length()-1;
for(;str.charAt(index1)==' ';index1++){
}
for(;str.charAt(index2)==' ';index2--){
}
return str.substring(index1, index2+1);
}
/**
* this constructor is used when all operator in WHERE clause are AND and there is no constant
* or OR operator.
* @param variables an array: array[][0] is variable name, array[][1] is variable value,
* array[][2] is operator.
*/
public ClauseNode(String[][] variables){
if(variables.length==1){
this.isLeaf=true;
this.isConst=false;
this.variableName=variables[0][0];
this.variableValue=variables[0][1];
if(variables[0][2].equals(">")==true){
this.singleOperator=4;
}
else if(variables[0][2].equals(">=")==true){
this.singleOperator=3;
}
else if(variables[0][2].equals("=")==true){
this.singleOperator=2;
}
else if(variables[0][2].equals("<=")==true){
this.singleOperator=1;
}
// variables[0][2].equals("<")==true
else{
this.singleOperator=0;
}
return;
}
this.isLeaf=false;
this.isConst=false;
this.isFull=true;
String[][] left=new String[variables.length-1][2];
String[][] right=new String[1][2];
for(int i=0;i<left.length;i++){
left[i]=variables[i];
}
right[0]=variables[variables.length-1];
this.rightNode=new ClauseNode(right);
this.leftNode=new ClauseNode(left);
this.operator=0;
return;
}
/**
* constructor just used for having condition.
* @param condition single aggregation condition like "MAX(id)>12" or "MIN ( id) <= 10".
* @param havingCondition it is not important.
* @throws InvalidParam if condition does not match condition string.
*/
public ClauseNode(String condition,boolean havingCondition){
String matchingString="\\s*([A-Za-z]*)\\s+([A-Za-z]*)\\s+(.*)\\s*";
Pattern pattern=Pattern.compile(matchingString);
Matcher matcher=pattern.matcher(condition);
if(matcher.find()==true){
String[] functions={"MAX","MIN","SUM","AVE"};
boolean founded=false;
for(int i=0;i<functions.length;i++){
if(matcher.group(1).equals(functions[i])){
this.aggregationFunction=i;
founded=true;
break;
}
}
this.aggregationVariable=matcher.group(2);
int operatorLength;
String operatorAndValue=matcher.group(3);
//4:>, 3:>=, 2:=, 1:<=, 0:<.
if(operatorAndValue.startsWith(">=")==true){
this.singleOperator=3;
operatorLength=2;
}
else if(operatorAndValue.startsWith("<=")==true){
this.singleOperator=1;
operatorLength=2;
}
else if(operatorAndValue.startsWith(">")==true){
this.singleOperator=4;
operatorLength=1;
}
else if(operatorAndValue.startsWith("=")==true){
this.singleOperator=2;
operatorLength=1;
}
//<
else{
this.singleOperator=0;
operatorLength=1;
}
for(;;operatorLength++){
if(operatorAndValue.charAt(operatorLength)!=' '){
break;
}
}
int lastSpace=operatorAndValue.length()-1;
for(;operatorAndValue.charAt(lastSpace)==' ';lastSpace--){
}
String val=operatorAndValue.substring(operatorLength,lastSpace+1);
this.aggregationValue=Integer.parseInt(val);
}
this.isLeaf=true;
this.isConst=false;
}
/**
* gets two ClauseNode and set them to this object. used for ClauseNode that has a compare operator.
* @param rightNode one of the ClauseNode objects.
* @param leftNode one of the ClauseNode objects.
*
*/
public void addChild(ClauseNode rightNode,ClauseNode leftNode){
this.rightNode=rightNode;
this.leftNode=leftNode;
this.isFull=true;
}
/**
* checks condition of this Node(if this Node is leaf) or its subtree(if this Node is not leaf)
* then returns result.
* @param columnsName a HashMap<column name, index of this column in table> to get variable with its name
* and get its column index then get its value in values array.
* @param values row of a table that is values of a record.
*
*/
public boolean checkCondition(HashMap<String,Integer> columnNames,String[] values)
throws Exception,NoVariable{
if(this.isLeaf==true){
if(this.isConst==true){
if(this.not==true){
return !this.constant;
}
else{
return this.constant;
}
}
Integer index=(Integer)columnNames.get(this.variableName);
if(index==null){
throw new NoVariable();
}
String value=values[index.intValue()];
try{
boolean result;
String checkValue=InputHandler.getValue(this.variableValue, columnNames, values);
// single operator is >
if(this.singleOperator==4){
// result=Integer.parseInt(value)>Integer.parseInt(this.variableValue);
result=Integer.parseInt(value)>Integer.parseInt(checkValue);
}
// single operator is >=
else if(this.singleOperator==3){
// result=Integer.parseInt(value)>=Integer.parseInt(this.variableValue);
result=Integer.parseInt(value)>=Integer.parseInt(checkValue);
}
// single operator is =
else if(this.singleOperator==2){
// result=this.variableValue.equals(value);
result=checkValue.equals(value);
}
// single operator is <=
else if(this.singleOperator==1){
// result=Integer.parseInt(value)<=Integer.parseInt(this.variableValue);
result=Integer.parseInt(value)<=Integer.parseInt(checkValue);
}
// single operator is <. this.singleOperator==0
else{
// result=Integer.parseInt(value)<Integer.parseInt(this.variableValue);
result=Integer.parseInt(value)<Integer.parseInt(checkValue);
}
if(this.not==true){
return !(result);
}
//this.not==false
else{
return result;
}
}
//value==null
catch(NullPointerException exception){
return false;
}
}
//this.isLeaf==false.
else{
boolean leftResult;
boolean rightResult;
//this.operator is AND.
if(this.operator==0){
if(this.leftNode!=null){
leftResult=this.leftNode.checkCondition(columnNames, values);
}
else{
throw new Exception();
}
//in AND if one of operands is false result become false.
if(leftResult==false){
if(this.not==true){
return true;
}
else{
return false;
}
}
//leftResult == true
else{
if(this.rightNode!=null){
rightResult=this.rightNode.checkCondition(columnNames, values);
}
else{
throw new Exception();
}
}
if(this.not==false){
return leftResult && rightResult;
}
else{
return !(leftResult&&rightResult);
}
}
//this.operator is OR.
else if(this.operator==1){
if(this.leftNode!=null){
leftResult=this.leftNode.checkCondition(columnNames, values);
}
else{
throw new Exception();
}
//in OR if one of operands is true result become true.
if(leftResult==true){
if(this.not==true){
return false;
}
else{
return true;
}
}
//leftResult==false
else{
if(this.rightNode!=null){
if(this.not==true){
return !this.rightNode.checkCondition(columnNames, values);
}
else{
return this.rightNode.checkCondition(columnNames, values);
}
}
else{
throw new Exception();
}
}
}
}
throw new Exception();
}
/**
* gets values and names of a group of variables then checks this clauseNode condition is valid
* on this group of variables.
* @param values values of this variable group. order of this variables must be same by order of names.
* @param names names of this variable group.
* @return if this condition is satisfied by this variable group returns true else returns false.
*/
public boolean checkAggregationCondition(String[][] values,String[] names){
for(int i=0;i<values.length;i++){
for(int j=0;j<values[0].length;j++){
System.out.print(values[i][j]+" ");
}
System.out.println();
}
System.out.println("begin");
System.out.println("aggFunc: "+this.aggregationFunction);
System.out.println("aggVari: "+this.aggregationVariable);
System.out.println("aggVal: "+this.aggregationValue);
System.out.println("single: "+this.singleOperator);
System.out.println("after");
boolean result = false;
//if this clauseNode does not contains AND, OR.
if(this.isLeaf==true){
int variableIndex=0;
for(int i=0;i<names.length;i++){
if(names[i].equals(this.aggregationVariable)){
variableIndex=i;
break;
}
}
int calculateValue=0;
//MAX.
if(this.aggregationFunction==0){
calculateValue=Integer.parseInt(values[0][variableIndex]);
int temp=0;
for(int i=0;i<values.length;i++){
temp=Integer.parseInt(values[i][variableIndex]);
if(calculateValue<temp){
calculateValue=temp;
}
}
System.out.println("cal: "+calculateValue);
}
//MIN.
else if(this.aggregationFunction==1){
calculateValue=Integer.parseInt(values[0][variableIndex]);
int temp=0;
for(int i=0;i<values.length;i++){
temp=Integer.parseInt(values[i][variableIndex]);
if(temp<calculateValue){
calculateValue=temp;
}
}
}
//SUM.
else if(this.aggregationFunction==2){
calculateValue=0;
int temp=0;
for(int i=0;i<values.length;i++){
temp=Integer.parseInt(values[i][variableIndex]);
calculateValue+=temp;
}
}
//AVE.
else{
calculateValue=0;
int temp=0;
for(int i=0;i<values.length;i++){
temp=Integer.parseInt(values[i][variableIndex]);
calculateValue+=temp;
}
calculateValue=calculateValue/values.length;
}
//>
if(this.singleOperator==4&&calculateValue>this.aggregationValue){
result=true;
}
//>=
else if(this.singleOperator==3&&calculateValue>=this.aggregationValue){
result=true;
}
//==
else if(this.singleOperator==2&&calculateValue==this.aggregationValue){
result=true;
}
//<=
else if(this.singleOperator==1&&calculateValue<=this.aggregationValue){
result=true;
}
//<
else if(this.singleOperator==0&&calculateValue<this.aggregationValue){
result=true;
}
else{
result=false;
}
}
//this is not a leaf in condition tree. contains AND, OR.
else{
boolean right=this.rightNode.checkAggregationCondition(values, names);
boolean left=this.leftNode.checkAggregationCondition(values, names);
//AND.
if(this.operator==0){
result=right&&left;
}
//OR.
else if(this.operator==1){
result=right||left;
}
}
if(this.not==false){
return result;
}
else{
return !result;
}
}
/**
* before a condition is there is a NOT this function reverse its sign.
*/
public void inverseSign(){
if(not==true){
not=false;
}
else{
not=true;
}
}
/**
* @return if this node is leaf or if has binary operator and has two children returns true else returns false.
*/
public boolean isFull(){
return this.isFull;
}
/**
* @return if this clause does not contains AND,OR and is not TRUE,FALSE
* returns an array: array[][0]:variable name , array[][1]:variable value, array[][2]:operator.
* @throws Exception if this node is TRUE,FALSE or contains AND,OR.
*/
public String[][] getVariable()throws OrException,TrueCondition,FalseCondition{
String[][] result = null;
if(this.isLeaf==true&&this.isConst==false){
String operator;
if(this.singleOperator==4){
operator=">";
}
else if(this.singleOperator==3){
operator=">=";
}
else if(this.singleOperator==2){
operator="=";
}
else if(this.singleOperator==1){
operator="<=";
}
else{
operator="<";
}
result=new String[1][3];
result[0]=new String[]{this.variableName,this.variableValue,operator};
}
else if(this.isLeaf==false){
if(this.operator==1){
throw new OrException();
}
String[][] left;
try{
left=this.leftNode.getVariable();
}
catch(TrueCondition exception){
left=new String[0][0];
}
String[][] right;
try{
right=this.rightNode.getVariable();
}
catch(TrueCondition exception){
right=new String[0][0];
}
result=new String[right.length+left.length][3];
int index=0;
for(index=0;index<left.length;index++){
result[index]=left[index];
}
for(int i=0;i<right.length;i++,index++){
result[index]=right[i];
}
}
else if(this.isConst==true){
if(this.not==false){
if(this.constant==true){
throw new TrueCondition();
}
else{
throw new FalseCondition();
}
}
else{
if(this.constant==true){
throw new FalseCondition();
}
else{
throw new TrueCondition();
}
}
}
return result;
}
@Override
public String toString(){
String result="";
if(this.isLeaf==true){
if(this.isConst==true){
result=this.constant+"";
}
else{
String temp;
// ">"
if(this.singleOperator==4){
temp=">";
}
// ">="
else if(this.singleOperator==3){
temp=">=";
}
// "="
else if(this.singleOperator==2){
temp="=";
}
// "<="
else if(this.singleOperator==1){
temp="<=";
}
// "<"
else{
temp="<";
}
result=this.variableName+" "+temp+" "+this.variableValue;
}
}
// binary operators
else{
String temp;
if(this.not==true){
result+="NOT ";
}
if(this.operator==0){
temp="AND";
}
else{
temp="OR";
}
result+=this.leftNode.toString()+" "+temp+" "+this.rightNode.toString();
}
return result;
}
}
| true
|
4d8d8512abc462269508c20f7b54900f8b1cd091
|
Java
|
jwnichls/puc
|
/edu/cmu/hcii/puc/parser/ActiveIfTable.java
|
UTF-8
| 4,031
| 2.71875
| 3
|
[
"MIT"
] |
permissive
|
/**
* ActiveIfTable.java
*
* This table represents the parsing of active-if statements which
* appear within group, state, and command tags. This table parses
* these statements into RawDependency objects, which are converted
* into a dependency graph in the second parsing iteration (see
* SpecParser.java)
*
* Out Edges
* ---------
* end( ACTIVEIF_TAG ) --> STATE_PARSE_STATE ||
* COMMAND_PARSE_STATE ||
* GROUP_PARSE_STATE
*
* In Edges
* --------
* STATE_PARSE_STATE --> ACTIVEIF_TAG
* COMMAND_PARSE_STATE --> ACTIVEIF_TAG
* GROUP_PARSE_STATE --> ACTIVEIF_TAG
*/
// Package Definition
package edu.cmu.hcii.puc.parser;
// Import Declarations
import java.lang.*;
import java.util.Vector;
import org.xml.sax.Attributes;
import edu.cmu.hcii.puc.Dependency;
import edu.cmu.hcii.puc.DependencyFormula;
import edu.cmu.hcii.puc.AND;
import edu.cmu.hcii.puc.OR;
import edu.cmu.hcii.puc.EqualsDependency;
import edu.cmu.hcii.puc.GreaterThanDependency;
import edu.cmu.hcii.puc.LessThanDependency;
// Class Definition
public class ActiveIfTable extends ParseStateTable {
//**************************
// Member Variables
//**************************
DependencyFormula m_Formula;
ParseStateTable m_ReturnTable;
DependencyFormula m_Cursor;
boolean m_bProcessingTag;
String m_sTagName;
String m_sStateName;
Vector m_pStack;
//**************************
// Constructor
//**************************
public ActiveIfTable( SpecParser parser, ParseStateTable returnTable ) {
super( parser );
m_ReturnTable = returnTable;
m_bProcessingTag = false;
m_Cursor = m_Formula = new AND();
m_pStack = new Vector();
m_pStack.addElement( m_Cursor );
}
//**************************
// Parsing Methods
//**************************
public ParseStateTable handleStartTag( String name,
Attributes atts ) {
if ( name.equals( SpecParser.OR_TAG ) ) {
DependencyFormula temp = new OR();
m_Cursor.addFormula( temp );
m_Cursor = temp;
m_pStack.addElement( m_Cursor );
}
else if ( name.equals( SpecParser.AND_TAG ) ) {
DependencyFormula temp = new AND();
m_Cursor.addFormula( temp );
m_Cursor = temp;
m_pStack.addElement( m_Cursor );
}
else {
// assume that only possible tags here are equals,
// greaterthan, and lessthan.
m_bProcessingTag = true;
m_sTagName = name;
m_sStateName = atts.getValue( SpecParser.STATE_ATTRIBUTE );
}
return this;
}
public ParseStateTable handleEndTag( String name ) {
if ( name.equals( SpecParser.ACTIVEIF_TAG ) ) {
// probably should check for some error conditions here
if ( m_pStack.size() != 1 ) {
m_Parser.addWarning( "active-if didn't have proper stack size" );
}
return m_ReturnTable;
}
else if ( name.equals( SpecParser.OR_TAG ) ||
name.equals( SpecParser.AND_TAG ) ) {
m_Cursor = (DependencyFormula)m_pStack.lastElement();
m_pStack.removeElementAt( m_pStack.size() - 1 );
}
return super.handleEndTag( name );
}
public void characters( String str ) {
if ( m_bProcessingTag ) {
Dependency d;
if ( m_sTagName.equals( SpecParser.EQUALS_TAG ) ) {
d = new EqualsDependency( m_sStateName, str );
}
else if ( m_sTagName.equals( SpecParser.GREATERTHAN_TAG ) ) {
d = new GreaterThanDependency( m_sStateName, str );
}
else if ( m_sTagName.equals( SpecParser.LESSTHAN_TAG ) ) {
d = new LessThanDependency( m_sStateName, str );
}
else {
d = null;
m_Parser.addWarning( "Invalid dependency tag in specification." );
}
m_Cursor.addDependency( d );
m_bProcessingTag = false;
}
}
public DependencyFormula getFormula() {
return m_Formula;
}
}
| true
|
cbb6a6e4f99c0f4a3f59d2b563fcba9dba3dd48f
|
Java
|
melalex/search-engine-scraper
|
/src/test/java/com/zephyr/scraper/crawler/manager/impl/CrawlingManagerImplTest.java
|
UTF-8
| 1,654
| 2.125
| 2
|
[] |
no_license
|
package com.zephyr.scraper.crawler.manager.impl;
import com.zephyr.scraper.crawler.provider.CrawlingProvider;
import com.zephyr.scraper.domain.external.SearchEngine;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import static org.junit.Assert.assertEquals;
@RunWith(MockitoJUnitRunner.class)
public class CrawlingManagerImplTest {
@Mock
private CrawlingProvider bingCrawlingProvider;
@Mock
private CrawlingProvider googleCrawlingProvider;
@Mock
private CrawlingProvider yahooCrawlingProvider;
@Mock
private CrawlingProvider duckDuckGoCrawlingProvider;
@Mock
private CrawlingProvider yandexCrawlingProvider;
@InjectMocks
private CrawlingManagerImpl testInstance;
@Before
public void setUp() {
testInstance.init();
}
@Test
public void shouldManageGoogle() {
assertEquals(googleCrawlingProvider, testInstance.manage(SearchEngine.GOOGLE));
}
@Test
public void shouldManageBing() {
assertEquals(bingCrawlingProvider, testInstance.manage(SearchEngine.BING));
}
@Test
public void shouldManageYahoo() {
assertEquals(yahooCrawlingProvider, testInstance.manage(SearchEngine.YAHOO));
}
@Test
public void shouldManageYandex() {
assertEquals(yandexCrawlingProvider, testInstance.manage(SearchEngine.YANDEX));
}
@Test
public void shouldManageDuckDuckGo() {
assertEquals(duckDuckGoCrawlingProvider, testInstance.manage(SearchEngine.DUCKDUCKGO));
}
}
| true
|
458b1a302a27a3cac9c9c8d82e5222dccffc8a52
|
Java
|
linuxsch/ma-modules-public
|
/Reports/src/com/serotonin/m2m2/reports/ReportPurgeDefinition.java
|
UTF-8
| 1,338
| 2.140625
| 2
|
[] |
no_license
|
/*
Copyright (C) 2014 Infinite Automation Systems Inc. All rights reserved.
@author Matthew Lohbihler
*/
package com.serotonin.m2m2.reports;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.joda.time.DateTime;
import com.serotonin.m2m2.Common;
import com.serotonin.m2m2.db.dao.SystemSettingsDao;
import com.serotonin.m2m2.module.PurgeDefinition;
import com.serotonin.m2m2.util.DateUtils;
public class ReportPurgeDefinition extends PurgeDefinition {
private static final Log LOG = LogFactory.getLog(ReportPurgeDefinition.class);
public static final String REPORT_PURGE_PERIOD_TYPE = "reports.REPORT_PURGE_PERIOD_TYPE";
public static final String REPORT_PURGE_PERIODS = "reports.REPORT_PURGE_PERIODS";
@Override
public void execute(long runtime) {
DateTime cutoff = DateUtils.truncateDateTime(new DateTime(runtime), Common.TimePeriods.DAYS);
cutoff = DateUtils.minus(cutoff,
SystemSettingsDao.instance.getIntValue(REPORT_PURGE_PERIOD_TYPE),
SystemSettingsDao.instance.getIntValue(REPORT_PURGE_PERIODS));
int deleteCount = ReportDao.getInstance().purgeReportsBefore(cutoff.getMillis());
if (deleteCount > 0)
LOG.info("Report purge ended, " + deleteCount + " report instances deleted");
}
}
| true
|
d7edbec34ba11e6f937af9a074c121df4191a8e3
|
Java
|
smcpeak/earthshape
|
/src/earthshape/StarCatalog.java
|
WINDOWS-1252
| 9,353
| 3.0625
| 3
|
[
"BSD-2-Clause"
] |
permissive
|
// StarCatalog.java
// See copyright.txt for license and terms of use.
package earthshape;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import util.FloatUtil;
/** A small, hardcoded catalog of star locations on the celestial
* sphere. This is used to synthesize observational data that
* should match the online planetarium I am using. Each object
* represents one star. */
public class StarCatalog {
// ---- Class data ----
// Regex patterns used by 'parse'.
private static Pattern raPattern = Pattern.compile("(\\d+)h(\\d+)m(\\d+)s");
private static Pattern decPattern = Pattern.compile("([-+0-9]+)(\\d+)'(\\d+)\"");
// ---- Instance data ----
// Name of the star.
String name;
// Degrees east of the Sun's position at vernal equinox
// along the celestial equator to the star's hour circle.
float rightAscensionDegrees;
// Degrees North of the celestial equator.
float declinationDegrees;
// ---- Methods ----
public StarCatalog(
String name_,
float rightAscensionDegrees_,
float declinationDegrees_)
{
this.name = name_;
this.rightAscensionDegrees = rightAscensionDegrees_;
this.declinationDegrees = declinationDegrees_;
}
/** Construct a catalog entry from strings representing right
* ascension and declination as they appear in the in-the-sky.org
* catalog. */
public static StarCatalog parse(String name, String rightAscensionTime, String declinationDMS)
{
float rightAscensionDegrees;
{
Matcher m = raPattern.matcher(rightAscensionTime);
if (m.matches()) {
int hour = Integer.valueOf(m.group(1));
int minute = Integer.valueOf(m.group(2));
int second = Integer.valueOf(m.group(3));
rightAscensionDegrees = (float)(hour*15.0 + minute*(15.0/60) + second*(15.0/3600));
}
else {
throw new RuntimeException(
"StarCatalog.parse: could not parse RA: "+rightAscensionTime);
}
}
float declinationDegrees;
{
Matcher m = decPattern.matcher(declinationDMS);
if (m.matches()) {
int degree = Integer.valueOf(m.group(1));
boolean negative = degree < 0;
if (negative) {
// Flip the sign on degree; we must negate the
// entire result, not just the degree portion.
degree = -degree;
}
int minute = Integer.valueOf(m.group(2));
int second = Integer.valueOf(m.group(3));
declinationDegrees = (float)(degree + minute/60.0 + second/3600.0);
if (negative) {
declinationDegrees = -declinationDegrees;
}
}
else {
throw new RuntimeException(
"StarCatalog.parse: could not parse declination: "+declinationDMS);
}
}
return new StarCatalog(name, rightAscensionDegrees, declinationDegrees);
}
/** Return a hardcoded array of star catalog entries. The source
* of this data is in-the-sky.org. */
public static StarCatalog[] makeCatalog()
{
return new StarCatalog[] {
parse("Capella", "05h16m41s", "+4559'56\""),
parse("Betelgeuse", "05h55m10s", "+0724'25\""),
parse("Rigel", "05h14m32s", "-0812'05\""),
parse("Aldebaran", "04h35m55s", "+1630'35\""),
parse("Sirius", "06h45m09s", "-1642'47\""),
parse("Procyon", "07h39m18s", "+0513'39\""),
parse("Polaris", "02h31m47s", "+8915'50\""),
parse("Dubhe", "11h03m43s", "+6145'03\"")
};
}
/** Return the Sun's position in the sky at
* 2017-03-05 20:00 -08:00. */
public static StarCatalog sunPosition()
{
return parse("Sun", "23h06m00s", "-0600'00\"");
}
/** Construct a star observation for a given observer time and location.
*
* @param unixTime is seconds since 1970-01-01 00:00 GMT.
* @param latitude is degrees North of the equator.
* @param longitude is degrees East of the prime meridian. */
public StarObservation makeObservation(
double unixTime,
float latitudeDegrees,
float longitudeDegrees)
{
// First, we need to calculate Greenwich Mean Sidereal Time
// corresponding to the given unixTime, in degrees.
float gmstDegrees = unixTimeToGMST(unixTime) * 15.0f;
// Next, calculate the "hour angle", which basically offsets
// the RA due to time and longitude. The equation I use
// comes from:
//
// https://en.wikipedia.org/wiki/Celestial_coordinate_system
//
// except their longitude has a flipped sign.
float hourAngleDegrees = gmstDegrees + longitudeDegrees - this.rightAscensionDegrees;
// I need some things in radians now.
float latitudeRadians = FloatUtil.degreesToRadiansf(latitudeDegrees);
float declRadians = FloatUtil.degreesToRadiansf(this.declinationDegrees);
float hourAngleRadians = FloatUtil.degreesToRadiansf(hourAngleDegrees);
// Now we can calculate azimuth and elevation in degrees. The
// formulas are derived from the same wikipedia page.
float azimuthRadians = (float)Math.atan2(
Math.sin(hourAngleRadians),
Math.cos(hourAngleRadians) * Math.sin(latitudeRadians) -
Math.tan(declRadians) * Math.cos(latitudeRadians));
float elevationRadians = (float)Math.asin(
Math.sin(latitudeRadians) * Math.sin(declRadians) +
Math.cos(latitudeRadians) * Math.cos(declRadians) * Math.cos(hourAngleRadians));
// The above formula yields an azimuth in [-pi,pi] where
// 0 is South. I want 0 to be North and a range of [0,2pi],
// so add pi now.
azimuthRadians += Math.PI;
// Finally, combine everything into an observation.
return new StarObservation(
latitudeDegrees,
longitudeDegrees,
this.name,
FloatUtil.radiansToDegreesf(azimuthRadians),
FloatUtil.radiansToDegreesf(elevationRadians));
}
/** Convert a given unix time to Greenwich Mean Sidereal Time,
* in hours, modulo 24 hours */
public float unixTimeToGMST(double unixTime)
{
// Wikipedia gives the following equation at
// https://en.wikipedia.org/wiki/Sidereal_time:
//
// GMST = 18.697374558 + 24.06570982441908 D
//
// where D is the number of elapsed UT1 days since
// 2000-01-01 12:00 UT. That reference time is 946728000
// in unix time.
double elapsedSeconds = unixTime - 946728000.0;
double elapsedDays = elapsedSeconds / (24*60*60);
double gmstRaw = 18.697374558 + 24.06570982441908 * elapsedDays;
// Mod by 24 hours. After that, 'float' has
// adequate precision.
return (float)(gmstRaw - Math.floor(gmstRaw / 24.0) * 24.0);
}
/** Calculate and print one observation, and compare it to what is
* in the manually gathered observation data. */
private static void printObs(StarObservation[] manualObs, StarCatalog sc,
double unixTime, float latitude, float longitude)
{
StarObservation obs = sc.makeObservation(unixTime, latitude, longitude);
System.out.println(obs);
// Find the corresponding manual entry.
boolean found = false;
for (StarObservation m : manualObs) {
if (m.name.equals(obs.name) &&
m.latitude == latitude &&
m.longitude == longitude)
{
float diffAzimuth = obs.azimuth - m.azimuth;
float diffElevation = obs.elevation - m.elevation;
System.out.println("diffAz="+diffAzimuth+", diffEl="+diffElevation);
if (Math.abs(diffAzimuth) > 0.3 || Math.abs(diffElevation) > 0.3) {
System.out.println("OBSERVATION DIFFERS FROM CALCULATION");
}
found = true;
break;
}
}
if (!found) {
System.out.println("NOT FOUND IN MANUAL OBSERVATIONS");
}
}
public static void main(String args[])
{
// Get the manual data.
StarObservation[] manualObs = StarObservation.getManualObservations();
// Calculate and print out observation data corresponding
// to the points I gathered manually. The purpose is to
// confirm that my mathematical predictions agree with the
// manual observations.
double obsUnixTime = 1488772800.0;
StarCatalog catalog[] = makeCatalog();
for (StarCatalog sc : catalog) {
printObs(manualObs, sc, obsUnixTime, 38, -122);
printObs(manualObs, sc, obsUnixTime, 38, -113);
printObs(manualObs, sc, obsUnixTime, 38, -104);
printObs(manualObs, sc, obsUnixTime, 38, -95);
printObs(manualObs, sc, obsUnixTime, 38, -86);
}
}
}
// EOF
| true
|
bf3cbb15c895aae1747ddd4001b1991d1d148d4f
|
Java
|
logyou/moda
|
/moda-entity/src/main/java/com/moda/entity/exception/AccessException.java
|
UTF-8
| 1,230
| 2.46875
| 2
|
[] |
no_license
|
package com.moda.entity.exception;
/**
* 访问异常类,用于访问异常抛出
*
* @author lyh
* @create 2018-9-21
*/
public class AccessException extends ServiceException {
public AccessException() {
super();
}
public AccessException(Integer status) {
super(status);
}
public AccessException(String message) {
super(message);
}
public AccessException(Object parameter) {
super(parameter);
}
public AccessException(Throwable cause) {
super(cause);
}
public AccessException(Integer status, String message) {
super(status, message);
}
public AccessException(String message, Throwable cause) {
super(message, cause);
}
public AccessException(String message, Object parameter) {
super(message, parameter);
}
public AccessException(Integer status, String message, Object parameter) {
super(status, message, parameter);
}
public AccessException(String message, Throwable cause,
boolean enableSuppression,
boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
| true
|
b32ed31629d68f834635555c339e22ca98a9ce69
|
Java
|
HakunaMatatacoc/daydayup
|
/src/com/mvc/MVCTest.java
|
UTF-8
| 465
| 2.421875
| 2
|
[] |
no_license
|
package com.mvc;
public class MVCTest {
public static void main(String[] args) {
Employee model = new Employee();
model.setName("Michael");
model.setId("1");
EmployeeView view = new EmployeeView();
EmployeeController employeeController = new EmployeeController(model,view);
employeeController.updateView();
employeeController.setEmployeeName("Big Michael");
employeeController.updateView();
}
}
| true
|
104ccebaafc2d05c463145e23f93f168a0bd473d
|
Java
|
CaptainJ93/SpringStudy
|
/scm/.svn/pristine/10/104ccebaafc2d05c463145e23f93f168a0bd473d.svn-base
|
UTF-8
| 2,122
| 2
| 2
|
[] |
no_license
|
package com.best1.scm.modules.webapi.mapper;
import com.best1.scm.modules.webapi.mapper.Data;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
public class ShowapiResBody implements Serializable{
/**
*
*/
private static final long serialVersionUID = -247337684920592067L;
private String mailNo;
private String update;
private Date updateStr;
private Integer ret_code;
private boolean flag;
private Integer status;
private String tel;
private String expSpellName;
private List<Data> data;
private String msg;
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public String getMailNo() {
return mailNo;
}
public void setMailNo(String mailNo) {
this.mailNo = mailNo;
}
public String getUpdate() {
return update;
}
public void setUpdate(String update) {
this.update = update;
}
public Date getUpdateStr() {
return updateStr;
}
public void setUpdateStr(Date updateStr) {
this.updateStr = updateStr;
}
public Integer getRet_code() {
return ret_code;
}
public void setRet_code(Integer ret_code) {
this.ret_code = ret_code;
}
public boolean isFlag() {
return flag;
}
public void setFlag(boolean flag) {
this.flag = flag;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
public String getExpSpellName() {
return expSpellName;
}
public void setExpSpellName(String expSpellName) {
this.expSpellName = expSpellName;
}
public List<Data> getData() {
return data;
}
public void setData(List<Data> data) {
this.data = data;
}
@Override
public String toString() {
return "ShowapiResBody [mailNo=" + mailNo + ", update=" + update
+ ", updateStr=" + updateStr + ", ret_code=" + ret_code
+ ", flag=" + flag + ", status=" + status + ", tel=" + tel
+ ", expSpellName=" + expSpellName + ", data=" + data + "]";
}
}
| true
|
32b5858e356a0a199f7d1f099a3c7e85fdbdf13e
|
Java
|
bellmit/crane
|
/equipment-monitor-iot/src/main/java/com/xywg/equipment/monitor/iot/modular/crane/service/impl/ProjectCraneMutiCollisionAvoidanceSetServiceImpl.java
|
UTF-8
| 797
| 1.617188
| 2
|
[] |
no_license
|
package com.xywg.equipment.monitor.iot.modular.crane.service.impl;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.xywg.equipment.monitor.iot.modular.crane.dao.ProjectCraneMutiCollisionAvoidanceSetMapper;
import com.xywg.equipment.monitor.iot.modular.crane.model.ProjectCraneMutiCollisionAvoidanceSet;
import com.xywg.equipment.monitor.iot.modular.crane.service.IProjectCraneMutiCollisionAvoidanceSetService;
import org.springframework.stereotype.Service;
/**
* <p>
* 服务实现类
* </p>
*
* @author hy
* @since 2019-06-18
*/
@Service
public class ProjectCraneMutiCollisionAvoidanceSetServiceImpl extends ServiceImpl<ProjectCraneMutiCollisionAvoidanceSetMapper, ProjectCraneMutiCollisionAvoidanceSet> implements IProjectCraneMutiCollisionAvoidanceSetService {
}
| true
|
9ab43df0366191c3d33c685b8ed913bceab49703
|
Java
|
longxing/SmallZhiDemo
|
/VoiceSoundWave/src/com/voice/voicesoundwave/SoundWaveControl.java
|
UTF-8
| 9,977
| 2
| 2
|
[] |
no_license
|
package com.voice.voicesoundwave;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import android.content.Context;
import com.iii360.sup.common.utl.LogManager;
import com.voice.voicesoundwave.StreamDecoder.StreamDecoderRunnableInterface;
public class SoundWaveControl {
public static SoundWaveControl mSoundWaveControl = null;
public static final int SEND_START = -1;
public static final int SEND_STOP = 1;
public static final int MSG_RECEIVED_GOOD_BROADCAST = 3;
public int status = 1;
public int statusListener = 1;
private Timer mTimer = null;
private PlayThread mPlayThread;
private byte[] mSendArray;
private String mCorrectBroadcast;
private MicrophoneListener microphoneListener = null;
private StreamDecoder sDecoder = null;
private ByteArrayOutputStream decodedStream = new ByteArrayOutputStream();
private Context mContext;
private StreamDecoderInterface mStreamDecoderInterface;
private StreamDecoderRunnableInterface mStreamDecoderRunnableInterface;
private StreamDecoderRunnableInterface mStreamDecoderRunnableInterfaceSOS;
private StringAndByteUtil mStringAndByteUtil;
private Map<String,Integer> isStop;
public interface StreamDecoderInterface {
public void onResult(String result);
}
private void stopListening() {
try {
if (microphoneListener != null)
microphoneListener.quit();
microphoneListener = null;
if (sDecoder != null)
sDecoder.quit();
sDecoder = null;
} catch (Exception e) {
}
}
public static SoundWaveControl getInstance(Context context) {
if (mSoundWaveControl == null) {
mSoundWaveControl = new SoundWaveControl(context);
}
return mSoundWaveControl;
}
private SoundWaveControl(Context context) {
mContext = context;
mStringAndByteUtil = new StringAndByteUtil(context);
isStop = new HashMap<String,Integer>();
statusListener = 1;
mStreamDecoderRunnableInterface = new StreamDecoderRunnableInterface() {
@Override
public void onResult(byte[] result) {
// TODO Auto-generated method stub
}
@Override
public void onComplent() {
// TODO Auto-generated method stub
status = 1;
stopSendData();
LogManager.e("decoded status=" + status);
}
};
mStreamDecoderRunnableInterfaceSOS = new StreamDecoderRunnableInterface() {
@Override
public void onResult(byte[] result) {
// TODO Auto-generated method stub
byte[] res = new byte[result.length / 2];
for (int i = 0 , j = 0;i < result.length;i+=2,j++) {
res[j] = (byte) ((result[i] & 0x0f) | (result[i+1] << 4));
}
mCorrectBroadcast = mStringAndByteUtil.bytesToString(res);
// try {
// mCorrectBroadcast = new String(res,"UTF-8");
// } catch (UnsupportedEncodingException e1) {
// // TODO Auto-generated catch block
// e1.printStackTrace();
// }
statusListener = 1;
stopListening();
AudioManagerStreamVolume.getIntence(mContext).setVolumeMax();
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
try {
Thread.sleep(300);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
long tPlay = playSOS(0);
LogManager.e("decoded>>>>>>>>>>>>>>>>>>>>> tPlay <<<<<<<<<<<<<<<<<<<<<" + tPlay);
if (tPlay > -1)
// start listening when playing is finished
{
// if (mTimer != null) {
// mTimer.cancel();
// }
mTimer.schedule(new StopSOSTimerTask(), tPlay * 4);
}
}
}).start();
}
@Override
public void onComplent() {
// TODO Auto-generated method stub
// stopSendData(mContext);
}
};
// mTimer.purge();
}
public synchronized void sendData(String data) {
if (status == SEND_START) {
return;
}
if (mPlayThread != null) {
mPlayThread.stopPlay();
}
AudioManagerStreamVolume.getIntence(mContext).setVolumeMax();
final long tPlay = playData(data, 0);
final long millisPlayTime = (long) ((Constants.kPlayJitter + Constants.kDurationsPerSOS)
* Constants.kSamplesPerDuration / Constants.kSamplingFrequency * 1000);
status = SEND_START;
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
isStop.put(Thread.currentThread().toString(), SEND_START);
// while (status == SEND_START) {
while (isStop.get(Thread.currentThread().toString()) == SEND_START) {
try {
Thread.sleep(tPlay);
// if (status != SEND_STOP) {
if (isStop.get(Thread.currentThread().toString()) != SEND_STOP) {
if (mPlayThread != null) {
mPlayThread.stopPlay();
}
listentSOS();
} else {
return;
}
Thread.sleep((long) (millisPlayTime * 1.5));
if (isStop.get(Thread.currentThread().toString()) != SEND_STOP) {
stopListening();
Thread.sleep(1);
if (mPlayThread != null) {
mPlayThread.stopPlay();
}
if (isStop.get(Thread.currentThread().toString()) != SEND_STOP) {
mPlayThread = AudioUtils.performData(mSendArray, 0,false);
}
} else {
if (mPlayThread != null) {
mPlayThread.stopPlay();
}
return;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
}
}
}
}).start();
}
private class StopSOSTimerTask extends TimerTask {
public StopSOSTimerTask() {
}
@Override
public void run() {
AudioManagerStreamVolume.getIntence(mContext).seterVolume();
mStreamDecoderInterface.onResult(mCorrectBroadcast);
this.cancel();
}
}
public synchronized long playData(String input, long delay) {
long millisPlayTime = -1;
try {
// try to play the file
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream outputstream = new DataOutputStream(baos);
outputstream.writeChars(input);
// byte[] inputBytes = input.getBytes("UTF-8");
byte[] inputBytes = mStringAndByteUtil.ascToBytes(input);
byte[] inputResult = new byte[inputBytes.length * 2];
for (int i = 0 , j = 0;i < inputBytes.length;i++,j+=2) {
inputResult[j] = (byte) (inputBytes[i] & 0x0f);
inputResult[j+1] = (byte) (inputBytes[i] >> 4 & 0x0f);
}
mSendArray = AudioUtils.performArray(inputResult, delay);
mPlayThread = AudioUtils.performData(mSendArray, 0,false);
/**
* length of play time (ms) = nDurations * samples/duration * 1/fs *
* 1000
*/
millisPlayTime = (long) ((Constants.kPlayJitter
+ Constants.kDurationsPerHail + Constants.kBytesPerDuration
* inputBytes.length + Constants.kDurationsPerCRC)
* Constants.kSamplesPerDuration
/ Constants.kSamplingFrequency * 1000);
}
catch (Exception e) {
System.out
.println("Could not encode " + input + " because of " + e);
}
return millisPlayTime + 5;
}
public synchronized void stopSendData() {
stopListening();
if (null != mPlayThread) {
mPlayThread.stopPlay();
}
AudioManagerStreamVolume.getIntence(mContext).seterVolume();
Iterator<String> it = isStop.keySet().iterator();
while(it.hasNext()){
String key = (String) it.next();
isStop.put(key, SEND_STOP);
}
status = SEND_STOP;
}
private synchronized void listentSOS() {
stopListening();
decodedStream.reset();
// the StreamDecoder uses the Decoder to decode samples put in its
// AudioBuffer
// StreamDecoder starts a thread
sDecoder = new StreamDecoder(decodedStream,
mStreamDecoderRunnableInterface, true);
// the MicrophoneListener feeds the microphone samples into the
// AudioBuffer
// MicrophoneListener starts a thread
microphoneListener = new MicrophoneListener(sDecoder.getAudioBuffer());
}
public synchronized void listent(StreamDecoderInterface inter) {
LogManager.e("decoded>>>>>>>>> listent <<<<<<<" + statusListener);
if (statusListener != 1) {
return;
}
statusListener = -1;
stopListening();
// LogManager.e("decoded>>>>>>>>> stop listening <<<<<<<");
// Intent intent = new Intent();
// intent.setAction("VOICESOUNDWAVE_SERVICE_STOP_BACK_WAKE_UP_LISTEN");
// mContext.sendBroadcast(intent);
// try {
// Thread.sleep(10000);
// } catch (InterruptedException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
mTimer = new Timer();
mStreamDecoderInterface = inter;
decodedStream.reset();
// the StreamDecoder uses the Decoder to decode samples put in its
// AudioBuffer
// StreamDecoder starts a thread
sDecoder = new StreamDecoder(decodedStream,
mStreamDecoderRunnableInterfaceSOS, false);
// the MicrophoneListener feeds the microphone samples into the
// AudioBuffer
// MicrophoneListener starts a thread
microphoneListener = new MicrophoneListener(sDecoder.getAudioBuffer());
}
public synchronized void stopListent() {
// LogManager.e("decoded>>>>>>>>> stopListent <<<<<<<");
// Intent intent = new Intent();
// intent.setAction("VOICESOUNDWAVE_SERVICE_START_BACK_WAKE_UP_LISTEN");
// mContext.sendBroadcast(intent);
this.stopListening();
statusListener = 1;
}
public long playSOS(long delay) {
long millisPlayTime = -1;
try {
// try to play the file
AudioUtils.performSOS(delay,true);
/**
* length of play time (ms) = nDurations * samples/duration * 1/fs *
* 1000
*/
millisPlayTime = (long) ((Constants.kPlayJitter + Constants.kDurationsPerSOS)
* Constants.kSamplesPerDuration
/ Constants.kSamplingFrequency * 1000);
}
catch (Exception e) {
LogManager.e("Could not perform SOS because of " + e);
}
return millisPlayTime;
}
}
| true
|
ce4dee603adb3eb93fa4970c249c6fc4effff6d6
|
Java
|
Flemmli97/RuneCraftory
|
/common/src/main/java/io/github/flemmli97/runecraftory/common/spells/GustSpell.java
|
UTF-8
| 1,357
| 2.4375
| 2
|
[] |
no_license
|
package io.github.flemmli97.runecraftory.common.spells;
import io.github.flemmli97.runecraftory.api.Spell;
import io.github.flemmli97.runecraftory.common.entities.misc.EntityWindGust;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.Mob;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.phys.Vec3;
public class GustSpell extends Spell {
@Override
public boolean use(ServerLevel level, LivingEntity entity, ItemStack stack, float rpUseMultiplier, int amount, int lvl) {
if (!Spell.tryUseWithCost(entity, stack, this.rpCost()))
return false;
EntityWindGust gust = new EntityWindGust(level, entity);
gust.setPos(gust.getX(), gust.getY() + 1.5, gust.getZ());
if (entity instanceof Mob mob && mob.getTarget() != null) {
LivingEntity target = mob.getTarget();
Vec3 dir = target.position().subtract(entity.position());
double len = dir.length();
if (len > 6)
len = 1;
dir = new Vec3(dir.x(), 0, dir.z()).normalize().scale(len);
gust.setRotationTo(target.getX() + dir.x(), target.getY() + target.getBbHeight() * 0.3, target.getZ() + dir.z(), 0);
}
level.addFreshEntity(gust);
return true;
}
}
| true
|
a6f12f3af2cf0b7758914a38b7baf134e05d5f6b
|
Java
|
a2393439531/quick-ea
|
/ea-gateway-layer/api-gateway-1.0/src/test/java/com/glcxw/service/AppServiceTest.java
|
UTF-8
| 3,314
| 2.078125
| 2
|
[
"MIT"
] |
permissive
|
package com.glcxw.service;
import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.bugjc.ea.gateway.mapper.*;
import com.bugjc.ea.gateway.model.*;
import com.bugjc.ea.gateway.service.AppService;
import com.glcxw.Tester;
import com.glcxw.util.CreateSecurityKey;
import com.glcxw.util.IdWorker;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.Date;
@Slf4j
public class AppServiceTest extends Tester {
@Resource
private AppMapper appMapper;
@Resource
private ZuulRouteMapper zuulRouteMapper;
@Resource
private AppRouteMapper appRouteMapper;
@Resource
private AppVersionMapMapper appVersionMapMapper;
@Resource
private AppSecurityConfigMapper appSecurityConfigMapper;
/**
* 创建一个业务应用
*/
@Test
public void testCreateBusinessApp(){
String desc = "授权认证业务";
Date date = new Date();
//1.创建APP
App app = new App();
app.setCreateTime(date);
app.setDescription(desc);
app.setType(1);
app.setEnabled(true);
app.setAppId(IdWorker.getNextId());
BeanUtil.copyProperties(CreateSecurityKey.getKeyPair(),app);
log.info("APP:{}",JSON.toJSONString(app));
appMapper.insert(app);
//2.创建业务路由配置
String path = "/jwt/**";
String applicationName = "jwt-server";
CustomZuulRoute customZuulRoute = new CustomZuulRoute();
customZuulRoute.setId(applicationName);
customZuulRoute.setPath(path);
customZuulRoute.setServiceId(applicationName);
customZuulRoute.setUrl(null);
customZuulRoute.setRibbonUrl(null);
customZuulRoute.setRetryable(false);
customZuulRoute.setStripPrefix(true);
customZuulRoute.setEnabled(true);
customZuulRoute.setDescription(desc);
zuulRouteMapper.insert(customZuulRoute);
//3.创建应用路由类
AppRoute appRoute = new AppRoute();
appRoute.setAppId(app.getAppId());
appRoute.setRouteId(customZuulRoute.getId());
appRoute.setIsDebug(false);
appRoute.setEnabled(true);
appRoute.setCreateTime(date);
appRouteMapper.insert(appRoute);
//4.创建版本映射表
String defaultVersion = "1.0";
AppVersionMap appVersionMap = new AppVersionMap();
appVersionMap.setAppId(app.getAppId());
appVersionMap.setVersionNo(defaultVersion);
appVersionMap.setPath("/");
appVersionMap.setMapPath("/");
appVersionMap.setDescription(desc);
appVersionMap.setCreateTime(date);
appVersionMapMapper.insert(appVersionMap);
//5.创建安全配置
AppSecurityConfig appSecurityConfig = new AppSecurityConfig();
appSecurityConfig.setAppId(app.getAppId());
appSecurityConfig.setPath(path);
appSecurityConfig.setVerifySignature(true);
appSecurityConfig.setVerifyToken(true);
appSecurityConfig.setEnabled(true);
appSecurityConfig.setDescription(desc);
appSecurityConfig.setCreateTime(date);
appSecurityConfigMapper.insert(appSecurityConfig);
}
}
| true
|
f960bbd9f39b6e72f9f3173038885f5da2363c47
|
Java
|
andreyscherbin/Introduction-To-Java
|
/4_Programming_with_classes/Агрегация и композиция.2/src/com/company/Wheel.java
|
UTF-8
| 199
| 2.625
| 3
|
[] |
no_license
|
package com.company;
public class Wheel {
private String wheelModel;
Wheel() {
wheelModel = "";
}
Wheel(String wheelModel) {
this.wheelModel = wheelModel;
}
}
| true
|
1e6a8fa8eeac0cdf056c50d1dc2783bfd3bb0528
|
Java
|
jiangren-mel-tutor-1905/cheng-projects
|
/W4/topic4/src/fp/topic4/notgeneric/Customer.java
|
UTF-8
| 104
| 1.9375
| 2
|
[] |
no_license
|
package fp.topic4.notgeneric;
public class Customer
{
public String getName()
{
return "temp";
}
}
| true
|
ba30e5335e1af6d87aa904776936845df7e30193
|
Java
|
ShaileshAtBimsym/olaper
|
/src/main/java/org/olap/server/processor/functions/OlapFunctionFactory.java
|
UTF-8
| 2,809
| 2.40625
| 2
|
[
"MIT"
] |
permissive
|
package org.olap.server.processor.functions;
import java.lang.reflect.Constructor;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.olap.server.driver.util.ParseUtils;
import org.olap4j.OlapException;
import org.olap4j.mdx.CallNode;
import org.olap4j.mdx.IdentifierNode;
import org.olap4j.mdx.IdentifierSegment;
import org.olap4j.mdx.LiteralNode;
import org.olap4j.mdx.ParseTreeNode;
import org.olap4j.mdx.Quoting;
import org.olap4j.metadata.Cube;
import org.reflections.Reflections;
@SuppressWarnings({ "unchecked", "rawtypes" })
public class OlapFunctionFactory {
private Map<String, Class> functionMap = new HashMap<String, Class>();
public static final OlapFunctionFactory INSTANCE = new OlapFunctionFactory(
annotated_classes(OlapFunction.class.getPackage(), OlapFunctionName.class)
);
public OlapFunctionFactory(Set<Class<?>> f_classes) {
for(Class c: f_classes){
OlapFunctionName name = (OlapFunctionName) c.getAnnotation(OlapFunctionName.class);
functionMap.put(name.name(), c);
}
}
private static Set<Class<?>> annotated_classes(Package in_package, Class<OlapFunctionName> with_annotation) {
Reflections reflections = new Reflections(in_package.getName());
return reflections.getTypesAnnotatedWith(with_annotation);
}
public OlapOp function(ParseTreeNode node, Cube cube) throws OlapException{
if(node==null){
return new NullFunction(cube);
}else if(node instanceof CallNode ){
String name = ((CallNode) node).getOperatorName().toLowerCase();
OlapOp op = getOlapOp(node, name, cube);
if(op==null)
throw new OlapException("Function "+name+" is not implemented, fail to process "+ParseUtils.toString(node));
return op;
}else if(node instanceof IdentifierNode){
IdentifierNode inode = (IdentifierNode) node;
IdentifierSegment seg_op = inode.getSegmentList().get(inode.getSegmentList().size()-1);
OlapOp op = null;
if(seg_op.getQuoting()!=Quoting.QUOTED)
op = getOlapOp(node, seg_op.getName(), cube);
if(op!=null)
return op;
return new IdentifiedMember((IdentifierNode) node, cube);
}else if(node instanceof LiteralNode){
return new LiteralMember((LiteralNode) node, cube);
}else{
throw new OlapException("Unsupported expression: "+ParseUtils.toString(node));
}
}
protected OlapOp getOlapOp(ParseTreeNode op_node, String name, Cube cube)
throws OlapException {
Class c = functionMap.get(name.toLowerCase());
if(c==null)
return null;
try {
Constructor cons = c.getConstructor(new Class[]{op_node.getClass(), Cube.class});
return (OlapOp) cons.newInstance(op_node, cube);
} catch (Exception e) {
throw new RuntimeException("Fail to run function "+name, e);
}
}
}
| true
|
e7568592e9106a0ec58bf801d890d77e33bcd7f3
|
Java
|
st411ar/core-java
|
/src/edition-10/volume-1/chapter-03/HexDouble/HexDouble.java
|
UTF-8
| 6,829
| 3.421875
| 3
|
[] |
no_license
|
/*
hex float / double consists of 3 parts:
1) mantissa - hex float point number
2) exponent - dec integer number
3) base - equals 2 and marks by symbol 'p'
*/
public class HexDouble {
public static void main(String[] args) {
System.out.println("\ninteger part without fraction part and exponent");
// compilation error
// print(1.0, 0x1.0);
printDecAndHex(1.0, 0x1.0p0);
printDecAndHex(2.0, 0x2.0p0);
printDecAndHex(9.0, 0x9.0p0);
printDecAndHex(10.0, 0xa.0p0);
printDecAndHex(11.0, 0xb.0p0);
printDecAndHex(15.0, 0xf.0p0);
printDecAndHex(16.0, 0x10.0p0);
printDecAndHex(17.0, 0x11.0p0);
printDecAndHex(25.0, 0x19.0p0);
printDecAndHex(26.0, 0x1a.0p0);
printDecAndHex(27.0, 0x1b.0p0);
printDecAndHex(31.0, 0x1f.0p0);
printDecAndHex(32.0, 0x20.0p0);
// also you may use next integer format
printDecAndHex(32, 0x20);
printDecAndHex(32e0, 0x20p0);
System.out.println("\ninteger part and exponent without fraction part");
// 1 * 10 ^ 0 = 1 * 1 = 1
// 0x1 * 2 ^ 0 = 1 * 1 = 1
printDecAndHex(1.0e0, 0x1.0p0);
// 1 * 10 ^ 1 = 1 * 10 = 10
// 0x1 * 2 ^ 1 = 1 * 2 = 2
printDecAndHex(1.0e1, 0x1.0p1);
// 1 * 10 ^ 2 = 1 * 100 = 100
// 0x1 * 2 ^ 2 = 1 * 4 = 4
printDecAndHex(1.0e2, 0x1.0p2);
// 1 * 10 ^ 3 = 1 * 1000 = 1000
// 0x1 * 2 ^ 3 = 1 * 8 = 8
printDecAndHex(1.0e3, 0x1.0p3);
// 2 * 10 ^ 3 = 2 * 1000 = 2000
// 0x2 * 2 ^ 3 = 2 * 8 = 16
printDecAndHex(2.0e3, 0x2.0p3);
// 9 * 10 ^ 3 = 9 * 1000 = 9000
// 0x9 * 2 ^ 3 = 9 * 8 = 72
printDecAndHex(9.0e3, 0x9.0p3);
// 10 * 10 ^ 3 = 10 * 1000 = 10000
// 0xa * 2 ^ 3 = 10 * 8 = 80
printDecAndHex(10.0e3, 0xa.0p3);
// 11 * 10 ^ 3 = 11 * 1000 = 11000
// 0xb * 2 ^ 3 = 11 * 8 = 88
printDecAndHex(11.0e3, 0xb.0p3);
// 15 * 10 ^ 3 = 15 * 1000 = 15000
// 0xf * 2 ^ 3 = 15 * 8 = 120
printDecAndHex(15.0e3, 0xf.0p3);
// 16 * 10 ^ 3 = 16 * 1000 = 16000
// 0x10 * 2 ^ 3 = 16 * 8 = 128
printDecAndHex(16.0e3, 0x10.0p3);
// 17 * 10 ^ 3 = 17 * 1000 = 17000
// 0x11 * 2 ^ 3 = 17 * 8 = 136
printDecAndHex(17.0e3, 0x11.0p3);
// also you may use next integer format
printDecAndHex(17e3, 0x11p3);
System.out.println("\nfraction part without integer part and exponent");
// 0.1 = 0 + 1 / 10 = 0.1
// 0x0.1 = 0 + 1 / 16 = 0.0625
printDecAndHex(0.1, 0x0.1p0);
// 0.2 = 0 + 2 / 10 = 0.2
// 0x0.2 = 0 + 2 / 16 = 0.125
printDecAndHex(0.2, 0x0.2p0);
// 0.3 = 0 + 3 / 10 = 0.3
// 0x0.3 = 0 + 3 / 16 = 0.1875
printDecAndHex(0.3, 0x0.3p0);
// 0.8 = 0 + 8 / 10 = 0.8
// 0x0.8 = 0 + 8 / 16 = 0.5
printDecAndHex(0.8, 0x0.8p0);
// 0.9 = 0 + 9 / 10 = 0.9
// 0x0.9 = 0 + 9 / 16 = 0.5625
printDecAndHex(0.9, 0x0.ap0);
// 0.9 = 0 + 9 / 10 = 0.9
// 0x0.a = 0 + a / 16 = 0 + 10 / 16 = 0.625
printDecAndHex(0.9, 0x0.ap0);
// 0.9 = 0 + 9 / 10 = 0.9
// 0x0.b = 0 + b / 16 = 0 + 11 / 16 = 0.6875
printDecAndHex(0.9, 0x0.bp0);
// 0.9 = 0 + 9 / 10 = 0.9
// 0x0.f = 0 + f / 16 = 0 + 15 / 16 = 0.9375
printDecAndHex(0.9, 0x0.fp0);
// 0.11 = 0 + 1 / 10 + 1 / 100 = 0.11
// 0x0.11 = 0 + 1 / 16 + 1 / 256 = 0 + 0.0625 + 0.00390625 = 0.06640625
printDecAndHex(0.11, 0x0.11p0);
System.out.println("\nfraction part and exponent without integer part");
// 0.1 * 10 ^ 0 = (0 + 1 / 10) * 1 = 0.1
// 0x0.1 * 2 ^ 0 = (0 + 1 / 16) * 1 = 0.0625
printDecAndHex(0.1e0, 0x0.1p0);
// 0.1 * 10 ^ 1 = (0 + 1 / 10) * 10 = 1
// 0x0.1 * 2 ^ 1 = (0 + 1 / 16) * 2 = 0.125
printDecAndHex(0.1e1, 0x0.1p1);
// 0.1 * 10 ^ 2 = (0 + 1 / 10) * 100 = 10
// 0x0.1 * 2 ^ 2 = (0 + 1 / 16) * 3 = 0.25
printDecAndHex(0.1e2, 0x0.1p2);
// 0.1 * 10 ^ 3 = (0 + 1 / 10) * 1000 = 100
// 0x0.1 * 2 ^ 3 = (0 + 1 / 16) * 8 = 0.5
printDecAndHex(0.1e3, 0x0.1p3);
// 0.1 * 10 ^ 4 = (0 + 1 / 10) * 10000 = 1000
// 0x0.1 * 2 ^ 4 = (0 + 1 / 16) * 16 = 1
printDecAndHex(0.1e4, 0x0.1p4);
// 0.2 * 10 ^ 4 = (0 + 2 / 10) * 10000 = 2000
// 0x0.2 * 2 ^ 4 = (0 + 2 / 16) * 16 = 2
printDecAndHex(0.2e4, 0x0.2p4);
// 0.9 * 10 ^ 4 = (0 + 9 / 10) * 10000 = 9000
// 0x0.9 * 2 ^ 4 = (0 + 9 / 16) * 16 = 9
printDecAndHex(0.9e4, 0x0.9p4);
// 1.0 * 10 ^ 4 = 1 * 10000 = 10000
// 0x0.a * 2 ^ 4 = (0 + 10 / 16) * 16 = 10
printDecAndHex(1.0e4, 0x0.ap4);
// 1.1 * 10 ^ 4 = (1 + 1 / 10) * 10000 = 11000
// 0x0.b * 2 ^ 4 = (0 + 11 / 16) * 16 = 11
printDecAndHex(1.1e4, 0x0.bp4);
// 1.5 * 10 ^ 4 = (1 + 5 / 10) * 10000 = 15000
// 0x0.f * 2 ^ 4 = (0 + 15 / 16) * 16 = 15
printDecAndHex(1.5e4, 0x0.fp4);
// 1.6 * 10 ^ 4 = (1 + 6 / 10) * 10000 = 16000
// 0x1.0 * 2 ^ 4 = 1 * 16 = 16
printDecAndHex(1.6e4, 0x1.0p4);
// 1.7 * 10 ^ 4 = (1 + 7 / 10) * 10000 = 17000
// 0x1.1 * 2 ^ 4 = (1 + 1 / 16) * 16 = 17
printDecAndHex(1.7e4, 0x1.1p4);
System.out.println("\ninteger and fraction parts without exponent");
// 1.1 = 1 + 1 / 10 = 1.1
// 0x1.1 = 1 + 1 / 16 = 1.0625
printDecAndHex(1.1, 0x1.1p0);
// 2.2 = 2 + 2 / 10 = 2.2
// 0x2.2 = 2 + 2 / 16 = 2.125
printDecAndHex(2.2, 0x2.2p0);
// 9.9 = 9 + 9 / 10 = 9.9
// 0x9.9 = 9 + 9 / 16 = 9.5625
printDecAndHex(9.9, 0x9.9p0);
// 9.92 = 9 + 9 / 10 + 9 / 100 = 9.99
// 0x9.99 = 9 + 9 / 16 + 9 / 256 = 9.94921875
printDecAndHex(9.99, 0x9.99p0);
// 10.9 = 1 * 10 + 9 / 10 = 10.9
// 0xa.a = 10 + 10 / 16 = 10.625
printDecAndHex(10.9, 0xa.ap0);
// 10.99 = 1 * 10 + 9 / 10 + 9 / 100 = 10.99
// 0xf.f = 15 + 15 / 16 = 15.8375
printDecAndHex(10.99, 0xf.fp0);
System.out.println("\ninteger, fraction parts with exponent");
// 1.1e1 = (1 + 1 / 10) * 10 ^ 1 = 1.1 * 10 = 11
// 0x1.1p1 = (1 + 1 / 16) * 2 ^ 1 = 1.0625 * 2 = 2.125
printDecAndHex(1.1e1, 0x1.1p1);
// 1.1e2 = (1 + 1 / 10) * 10 ^ 2 = 1.1 * 100 = 110
// 0x1.1p2 = (1 + 1 / 16) * 2 ^ 2 = 1.0625 * 4 = 4.25
printDecAndHex(1.1e2, 0x1.1p2);
// 1.1e3 = (1 + 1 / 10) * 10 ^ 3 = 1.1 * 1000 = 1100
// 0x1.1p3 = (1 + 1 / 16) * 2 ^ 3 = 1.0625 * 8 = 8.5
printDecAndHex(1.1e3, 0x1.1p3);
// 1.1e4 = (1 + 1 / 10) * 10 ^ 4 = 1.1 * 10000 = 11000
// 0x1.1p4 = (1 + 1 / 16) * 2 ^ 4 = 1.0625 * 16 = 17
printDecAndHex(1.1e4, 0x1.1p4);
System.out.println("\ninteger, fraction parts with negative exponent");
// 1.1e-1 = (1 + 1 / 10) / 10 ^ 1 = 1.1 / 10 = 0.11
// 0x1.1p-1 = (1 + 1 / 16) / 2 ^ 1 = 1.0625 / 2 = 0.53125
printDecAndHex(1.1e-1, 0x1.1p-1);
// 1.1e-2 = (1 + 1 / 10) / 10 ^ 2 = 1.1 / 100 = 0.011
// 0x1.1p-2 = (1 + 1 / 16) / 2 ^ 2 = 1.0625 / 4 = 0.265625
printDecAndHex(1.1e-2, 0x1.1p-2);
System.out.println("\nHorstmann's example");
// 1.0e-3 = 1 / 10 ^ 3 = 1 / 1000 = 0.001
// 0x1.0p-3 = 1 / 2 ^ 3 = 1 / 8 = 0.125
printDecAndHex(1.0e-3, 0x1.0p-3);
}
private static void printDecAndHex(double dec, double hex) {
System.out.print("equals: " + (dec == hex));
System.out.print("\tdec:\t" + dec);
System.out.println("\thex:\t" + hex);
}
}
| true
|
8feeea364309d61a142d427dd28e6ed3f0d3cbb6
|
Java
|
titilomt/Projects_CCPuc
|
/grafos/Matriz.java
|
UTF-8
| 5,300
| 3.171875
| 3
|
[] |
no_license
|
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class Matriz{
public static int [][] matrix;
public static String []grafo;
public static Scanner in = new Scanner(System.in);
public static void main(String[] args) {
String name = "";
grafo = new String [100];
for(int i = 0; i < 100; i++)grafo[i]= "-9999";
int option = 0;
try {
while (option > -1) {
option = menu();
switch (option) {
case 1:
System.out.println("Entrar com nome do arquivo: (Se o arquivo possuir extencao favor digitar)");
name = in.next();
name = "//tmp//"+name;
FileReader fr = new FileReader (name);
BufferedReader br = new BufferedReader(fr);
int contador = 0;
String line = br.readLine();
while (line != null) {
grafo[contador] = line;// build the monstro
contador++;
line = br.readLine();
}
grafo = formatGrafo(grafo);
br.close();
matrix = buildMatrix(grafo); // mandar para matriz
printMatrix(matrix);
break;
case 2:
int[][] complement = buildComplementMatrix(matrix); // matrix complementar
printMatrix(complement);
break;
case 3:
System.out
.println("Entrar com vertice desejado (1 to N): ");
int ver = in.nextInt();
int resp = degreeVertice(ver, matrix);
System.out.println("O grau do vertice, " + ver + " = "
+ resp);
break;
case 4:
boolean is = isComplete(matrix);
if (is) {
System.out.println("Grafo completo");
} else
System.out.println("Grafo nao e completo");
break;
case 5:
int[] teste = allDegreeVertice(matrix);
System.out
.println("Entrar com o vertice para ver se e adjacente (1 to N): ");
int i = in.nextInt() - 1;
if (teste[i] > 0) {
i = i + 1;
System.out.println("O vertice " + i
+ " tem adjacencia.");
} else {
i = i + 1;
System.out.println("O vertice " + i
+ " nao possui adjacencia.");
}
break;
case 0:
System.out.println("Fora do menu!");
break;
}
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException ioe){
ioe.printStackTrace();
}
}
public static int menu(){
int resp = 0;
System.out.println("Bem vindo, o que deseja fazer ?");
System.out
.println("1 - Gravar o grafo;\n2 - Construir matriz complementar;\n3 - "
+ "Descobrir o grau do vertice;\n4 - Grafo completo ou nao;\n5 - Descobrir a adjacencia do vertice; "
+ "\nDigite -1 para terminar.\n");
resp = in.nextInt();
return resp;
}
public static String [] formatGrafo(String [] grafo){
String [] grafoFormatado =null;
int contador = 0;
while(grafo[contador]!="-9999") {contador++;}
grafoFormatado = new String [contador];
for(int i = 0; i < contador; i++){
grafoFormatado[i] = grafo[i];
}
return grafoFormatado;
}
public static int [][] buildMatrix(String [] grafo){
int hight = Integer.parseInt(grafo[0]);
int [][] matrix = new int [hight][hight];
for(int i=0; i < hight; i++){
String [] tmp = grafo[i+1].split(",");
for (int j = 0; j < hight; j++){
matrix[i][j] = Integer.parseInt(tmp[j]);
}
}
return matrix;
}
public static int [][] buildComplementMatrix(int [][]matrix){
int hight = matrix.length;
int [][] complement = new int [hight][hight];
for(int i = 0; i < hight; i++){
for(int j = 0; j < hight; j++){
if(i!=j){
complement[i][j] = matrix[i][j] != 0 ? 0: 1;
} else {
complement[i][j] = matrix[i][j];
}
}
}
return complement;
}
public static int degreeVertice(int vertice, int[][]matrix){
vertice = vertice - 1;
int resp = 0;
for (int i = 0; i < matrix.length; i++){
if(matrix[i][vertice] != 0){
resp++;
}
}
return resp;
}
public static int [] allDegreeVertice(int [][]matrix){
int []allDegree = new int [matrix.length];
for(int i = 0; i < matrix.length; i++){
allDegree[i] = 0;
}
for (int i = 0; i < matrix.length; i++){
for(int j = 0; j < matrix.length; j++){
if(matrix[i][j]!=0){
allDegree[j]++;
}
}
}
return allDegree;
}
public static void printMatrix(int matrix[][]){
for (int i = 0; i < matrix.length; i++){
for(int j = 0; j < matrix.length; j++){
System.out.print("["+matrix[i][j]+"] ");
}
System.out.println();
}
}
public static boolean isComplete(int [][]matrix){
boolean resp = true;
for(int i = 0; i < matrix.length; i++){
for (int j = 0; j < matrix.length; j++){
if(j!=i && matrix[i][j] == 0){
resp = false;
}
}
}
return resp;
}
public int[][] getMatrix() {
return matrix;
}
public void setMatrix(int[][] matrix) {
this.matrix = matrix;
}
public static String[] getGrafo() {
return grafo;
}
public static void setGrafo(String[] grafo) {
Matriz.grafo = grafo;
}
}
| true
|
36da740283a1544afabfe203bee273c4ca38b349
|
Java
|
sp2020jarvan2/CS3240
|
/src/sg/tests/NFATest.java
|
UTF-8
| 9,121
| 2.59375
| 3
|
[] |
no_license
|
package sg.tests;
import java.util.HashSet;
import sg.Util;
import sg.fa.DFA;
import sg.fa.NFA;
import sg.fa.State;
import sg.fa.Transition;
public class NFATest
{
public static void main(String[] args)
{
// NFA n = NFA.makeRangedNFA('9', '0');
// test100();
// test04();
// test03();
// test101();
// test104();
// testTransitionPull();
}
public static void testTransitionPull()
{
NFA nfa1 = NFA.makeRangedNFA('A', 'Z');
HashSet<Character> hs = NFA.oneLayerTransitions(nfa1);
Util.prettyPrint(hs);
Util.reallyPrettyPrint(hs);
}
// THIS ONE IS GREAT
public static void test104()
{
NFA nfa1 = NFA.makeRangedNFA('0', '1');
nfa1.prettyPrint();
System.out.println("------------");
NFA nfa2 = NFA.makeRangedNFA('0', '1');
NFA nfa3 = NFA.star(nfa2);
NFA nfa4 = NFA.concatenate(nfa1, nfa3);
nfa4.setAcceptToken("$INT");
// System.out.println("------------");
// nfa4.prettyPrint();
// System.out.println("------------");
// lower (lower|digit)*
NFA nfa5 = NFA.makeRangedNFA('a', 'b');
NFA nfa6 = NFA.makeRangedNFA('0', '1');
NFA nfa7 = NFA.union(nfa5, nfa6);
NFA nfa8 = NFA.star(nfa7);
NFA nfa9 = NFA.makeRangedNFA('a', 'b');
NFA nfa10 = NFA.concatenate(nfa9, nfa8);
nfa10.setAcceptToken("$IDENTIFIER");
// DFA dfa2 = DFA.convertNFA(nfa4);
// String[] testStrings2 =
// { "0", "1", "01", "" , "askdjadsk", "00000"};
// boolean[] answers2 =
// {
// true, true, true, false, false, true
// };
// NFATest.advancedTest(dfa2, testStrings2, answers2);
//
// $FLOAT ($DIGIT)+ \. ($DIGIT)+
NFA nfa90 = NFA.makeRangedNFA('0', '1');
NFA nfa91 = NFA.makeRangedNFA('0', '1');
nfa91 = NFA.star(nfa91);
NFA nfa92 = NFA.makeRangedNFA('0', '1');
NFA nfa93 = NFA.makeRangedNFA('0', '1');
nfa93 = NFA.star(nfa93);
NFA dot = NFA.makeCharNFA('.');
NFA n94 = NFA.concatenate(nfa90, nfa91);
NFA n95 = NFA.concatenate(nfa92, nfa93);
NFA n96 = NFA.concatenate(n94, dot);
NFA n97 = NFA.concatenate(n96, n95);
n97.setAcceptToken("$FLOAT");
NFA nfa11 = NFA.union(nfa4, nfa10);
NFA nfa122 = NFA.union(nfa11, n97);
// NFA nfa122 = NFA.union(nfa4, n97);
// DFA dfa = DFA.convertNFA(nfa11);
// nfa122.prettyPrint();
DFA dfa = DFA.convertNFA(nfa122);
String[] testStrings =
{ "0", "1", "01", "a10", "bbbbb", "101asdad", "a8aa8a88s8das8a8",
"0.0", ".34234", "1.0", "1.", ".111" };
boolean[] answers =
{ true, true, true, true, true, false, false, true, false, true, false,
false };
NFATest.advancedTest(dfa, testStrings, answers);
// dfa.prettyPrint();
}
public static void test101()
{
// 0-9 OR A-Z
NFA nfa1 = NFA.makeRangedNFA('0', '9');
nfa1.setAcceptToken("$DIGIT");
NFA nfa2 = NFA.makeRangedNFA('A', 'Z');
nfa2.setAcceptToken("$UPPER");
NFA nfa3 = NFA.union(nfa1, nfa2);
DFA dfa = DFA.convertNFA(nfa3);
String[] testStrings =
{ "A", "B", "AA", "", "0", "1", "9", "b" };
boolean[] answers =
{ true, true, false, false, true, true, true, false };
NFATest.advancedTest(dfa, testStrings, answers);
}
public static void test100()
{
NFA nfaA = NFA.makeRangedNFA('0', '9');
DFA dfaA = DFA.convertNFA(nfaA);
String[] testStrings =
{ "a", "b", "aa", "", "0", "1", "9" };
boolean[] answers =
{ false, false, false, false, true, true, true };
NFATest.testAll(dfaA, testStrings, answers);
}
public static void test02()
{
// a
NFA nfaA = NFA.makeCharNFA('a');
DFA dfaA = DFA.convertNFA(nfaA);
String[] testStrings =
{ "a", "b", "aa", "" };
boolean[] answers =
{ true, false, false, false };
NFATest.testAll(dfaA, testStrings, answers);
}
public static void test03()
{
// (a|b)*
NFA nfaA = NFA.makeCharNFA('a');
NFA nfaB = NFA.makeCharNFA('b');
NFA aUb = NFA.union(nfaA, nfaB);
NFA aorbstar = NFA.star(aUb);
DFA dfaAll = DFA.convertNFA(aorbstar);
String[] testStrings =
{ "a", "b", "abba", "c", "" };
boolean[] answers =
{ true, true, true, false, true };
NFATest.testAll(dfaAll, testStrings, answers);
}
public static void test04()
{
// intLETTER*=DIGIT*
NFA DIGIT = NFA.makeRangedNFA('0', '9');
NFA digitStar = NFA.star(DIGIT);
NFA LETTER = NFA.makeRangedNFA('A', 'Z');
// NFA LETTER = NFA.makeRangedNFA((char)32, (char)(126));
NFA letterStar = NFA.star(LETTER);
NFA eq = NFA.makeCharNFA('=');
NFA i = NFA.makeCharNFA('i');
NFA n = NFA.makeCharNFA('n');
NFA t = NFA.makeCharNFA('t');
NFA myInt = NFA.concatenate(NFA.concatenate(i, n), t);
NFA all = NFA.concatenate(NFA.concatenate(myInt, letterStar),
NFA.concatenate(eq, digitStar));
DFA dfaAll = DFA.convertNFA(all);
// dfaAll.prettyPrint();
String[] testStrings =
{ "intAWWWYEAH=65", "intBITCHESANDHOES=7876320487643987", "abba", "c",
"", "intB=1", "intq=1" };
boolean[] answers =
{ true, true, false, false, false, true, false };
NFATest.testAll(dfaAll, testStrings, answers);
}
public static void test01()
{
// ((a|b)c)*
System.out.println("NFA 1: ");
State s1pre = new State("s1p", false);
State s1mid = new State("s1m", false);
State s1fin = new State("s1f", true);
s1pre.addTransition(new Transition('a', s1mid));
s1mid.addTransition(new Transition(Transition.EPSILON, s1fin));
NFA nfa1 = new NFA(s1pre, s1fin);
State s2pre = new State("s2p", false);
State s2mid = new State("s2m", false);
State s2fin = new State("s2f", true);
s2pre.addTransition(new Transition('b', s2mid));
s2mid.addTransition(new Transition(Transition.EPSILON, s2fin));
NFA nfa2 = new NFA(s2pre, s2fin);
NFA nfa3 = NFA.union(nfa1, nfa2);
State s3pre = new State("s3p", false);
State s3mid = new State("s3m", false);
State s3fin = new State("s3f", true);
s3pre.addTransition(new Transition('c', s3mid));
s3mid.addTransition(new Transition(Transition.EPSILON, s3fin));
NFA nfa4 = new NFA(s3pre, s3fin);
NFA nfa5 = NFA.concatenate(nfa3, nfa4);
NFA nfa6 = NFA.star(nfa5);
nfa6.prettyPrint();
System.out.println("\nTurn it into a DFA");
DFA dfa = DFA.convertNFA(nfa6);
dfa.prettyPrint();
String[] testStrings =
{ "", "ac", "bc", "acac", "bcbc", "acbc", "acacacacacacacbc", "d",
"cacacac", "a" };
boolean[] answers =
{ true, true, true, true, true, true, true, false, false, false };
for (int i = 0; i < testStrings.length; i++)
{
boolean b = dfa.validate(testStrings[i]);
String s = b == answers[i] ? "Pass" : "Fail";
System.out.println("Test " + (i + 1) + ": " + testStrings[i]
+ " -> " + s);
}
}
public static void testAll(DFA dfa, String[] testStrings, boolean[] answers)
{
for (int i = 0; i < testStrings.length; i++)
{
boolean b = dfa.validate(testStrings[i]);
String s = b == answers[i] ? "Pass" : "Fail";
if (s == "Pass")
System.out.println("Test " + (i + 1) + ": " + testStrings[i]
+ " -> " + s);
else
System.err.println("Test " + (i + 1) + ": " + testStrings[i]
+ " -> " + s);
}
}
public static void advancedTest(DFA dfa, String[] testStrings,
boolean[] answers)
{
boolean bbbb = true;
for (int i = 0; i < testStrings.length; i++)
{
Object[] o = dfa.specialValidate(testStrings[i]);
Boolean bb = (Boolean) o[0];
boolean b = bb.booleanValue();
String s = b == answers[i] ? "Pass" : "Fail";
System.out.println("Test " + (i + 1) + ": " + testStrings[i]
+ " -> " + s);
bbbb &= (b == answers[i]);
if (b) // so it is supposed to accept
{
String thetoken = (String) o[1];
System.out.println("\tAccept, token is: " + thetoken);
}
else
{
System.out.println("\tDoes not accept");
}
}
if (!bbbb)
System.out.println("failed");
else
System.out.println("All pass");
}
}
| true
|
33bce91420b44a8b037ca71379224547f42f5ed9
|
Java
|
CyberFlameGO/Scalebound
|
/Shared/src/main/java/dev/scalebound/shared/profiles/ProfileDownloadLog.java
|
UTF-8
| 283
| 1.671875
| 2
|
[] |
no_license
|
package dev.scalebound.shared.profiles;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.ToString;
@Getter
@ToString
@AllArgsConstructor
public class ProfileDownloadLog
{
private String fileName;
private String folder = null;
private String url;
}
| true
|
9a203abad17a8757a0d0cc9313f4d3e1d5b58170
|
Java
|
nntoan/vietspider
|
/client/src/main/java/org/vietspider/client/ClientConsole.java
|
UTF-8
| 12,891
| 2.046875
| 2
|
[
"Apache-2.0"
] |
permissive
|
/***************************************************************************
* Copyright 2001-2008 The VietSpider All rights reserved. *
**************************************************************************/
package org.vietspider.client;
import java.io.Console;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.ConnectException;
import java.util.Date;
import org.apache.http.Header;
import org.apache.http.conn.HttpHostConnectException;
import org.apache.http.message.BasicHeader;
import org.vietspider.client.common.ClientConnector2;
import org.vietspider.client.common.CrawlerClientHandler;
import org.vietspider.client.common.DataClientHandler;
import org.vietspider.common.io.RWData;
import org.vietspider.common.io.UtilFile;
import org.vietspider.common.text.CalendarUtils;
import org.vietspider.net.client.AbstClientConnector.HttpData;
import org.vietspider.net.server.CrawlerStatus;
import org.vietspider.net.server.URLPath;
import org.vietspider.user.User;
/**
* Author : Nhu Dinh Thuan
* nhudinhthuan@yahoo.com
* Jun 26, 2008
*/
public class ClientConsole {
private Console console;
private ClientConnector2 connector;
private boolean connected = false;
private final static int MIN_SIZE = 98;
public ClientConsole() {
console = System.console();
}
// private void summary(String cmd) throws Throwable {
// String [] elements = cmd.split(" ");
// if(elements.length < 3) return;
// console.printf("Please wait...");
// String date = elements[2];
// new CrawlReporterHandler(new String[]{date}).download(console);
// }
private void downloadLog(String cmd) throws Exception {
String [] elements = cmd.split(" ");
if(elements.length < 3) return;
console.printf("Please wait...");
String date = elements[2];
File folder;
if(elements.length > 3) {
folder = new File(elements[3]);
} else {
folder = UtilFile.getFolder("client");
}
Date instanceDate = CalendarUtils.getDateFormat().parse(date);
date = CalendarUtils.getFolderFormat().format(instanceDate);
Header [] headers = new Header[] {
new BasicHeader("action", "load.file"),
new BasicHeader("file", "track/logs/"+date+".log")
};
HttpData httpData = connector.loadResponse(URLPath.FILE_HANDLER, new byte[0], headers);
// Header header = httpResponse.getFirstHeader("Content-Length");
File file = new File(folder, date+".log");
InputStream contentInput = null;
try {
FileOutputStream fileOuput = new FileOutputStream(file);
contentInput = httpData.getStream();
RWData.getInstance().save(fileOuput, contentInput);
contentInput.close();
} finally {
connector.release(httpData);
if(contentInput != null) contentInput.close();
}
console.printf("\nlog path: "+file.getAbsolutePath()+"\n");
}
private void handleCommand(String cmd) throws Throwable {
if(cmd.equals("crawler s")) {
CrawlerClientHandler crawlerClientHandler = new CrawlerClientHandler();
int status = crawlerClientHandler.mornitorCrawler(CrawlerStatus.START_OR_STOP);
if(status == -1) {
console.printf("Crawler stopped.\n");
} else if(status == 0) {
console.printf("Crawler is executing.\n");
}
} else if(cmd.equals("crawler stop")) {
CrawlerClientHandler crawlerClientHandler = new CrawlerClientHandler();
int status = crawlerClientHandler.mornitorCrawler(CrawlerStatus.RUNNING);
if(status == 0) {
status = crawlerClientHandler.mornitorCrawler(CrawlerStatus.START_OR_STOP);
}
if(status == -1) console.printf("Crawler stopped.\n");
} else if(cmd.equals("crawler execute") || cmd.equals("crawler start")) {
CrawlerClientHandler crawlerClientHandler = new CrawlerClientHandler();
int status = crawlerClientHandler.mornitorCrawler(CrawlerStatus.RUNNING);
if(status == -1) {
status = crawlerClientHandler.mornitorCrawler(CrawlerStatus.START_OR_STOP);
}
if(status == 0) console.printf("Crawler is executing.\n");
} else if (cmd.equals("crawler status")) {
CrawlerStatus status = new CrawlerClientHandler().getCrawlerStatus(CrawlerStatus.RUNNING);
if(status.getStatus() == -1) {
console.printf("Crawler stopped.\n");
} else if(status.getStatus() == 0) {
console.printf("Crawler is executing.\n");
}
console.printf("Total thread is " + status.getTotalThread()+"\n");
String [] threadStatus = status.getThreadStatus();
if(threadStatus != null) {
console.printf("------------------------------------------------------------------\n");
for(String ele : threadStatus) {
if(ele.length() > MIN_SIZE) ele = ele.substring(0, MIN_SIZE-3) + "...";
console.writer().println(ele);
}
console.printf("------------------------------------------------------------------\n");
}
console.writer().flush();
} else if (cmd.equals("crawler info")) {
CrawlerClientHandler crawlerClientHandler = new CrawlerClientHandler();
printCrawler(crawlerClientHandler.viewPool());
} else if (cmd.startsWith("crawler view executor")) {
int index = 0;
try {
index = Integer.parseInt(cmd.substring(cmd.indexOf("executor")+8).trim());
} catch (Exception e) {
e.printStackTrace();
index = 0;
}
CrawlerClientHandler crawlerClientHandler = new CrawlerClientHandler();
printCrawler(crawlerClientHandler.viewExecutor(index));
} else if(cmd.startsWith("download log ")) {
downloadLog(cmd);
// } else if(cmd.startsWith("crawler report ")) {
// summary(cmd);
} else if(cmd.equals("help")) {
console.printf("Help\t\t\t\t\t Show help\n");
console.printf("\n");
console.printf("Crawler s\t\t\t\t Start, stop or execute crawler service\n");
console.printf("Crawler start\t\t\t\t Start or execute crawler\n");
console.printf("Crawler stop\t\t\t\t Stop crawler\n");
console.printf("Crawler execute\t\t\t\t Start or execute crawler\n");
console.printf("\n");
console.printf("Crawler info\t\t\t\t Show crawler information\n");
console.printf("Crawler status\t\t\t\t Show crawler status with all executor\n");
console.printf("Crawler view executor [index]\t\t Show executor information by index\n");
console.printf("\n");
console.printf("Crawler status\t\t\t\t Show crawler status with all executor\n");
console.printf("Crawler view executor [index]\t\t Show executor information by index\n");
// console.printf("Crawler report $date \t\t\t Report crawl data\n");
console.printf("\n");
console.printf("Download log $date $folder\t\t Download log file\n");
console.printf("\n");
console.printf("Server shutdown\t\t\t\t Shutdown server application\n");
} else if(cmd == null || cmd.trim().isEmpty()) {
return;
} else {
console.printf("Unknown command\n");
console.printf("Type 'help' for help.\n");
}
}
private void printCrawler(String value) {
if(value.equals("-1")) {
console.printf("Crawler stopped.\n");
} else {
console.printf(value);
console.printf("\n");
}
console.flush();
}
private String readLine(String label) {
String value = console.readLine(label);
if(value == null) readLine("vietspider>");
value = value.toLowerCase().trim();
if(value.isEmpty()) readLine("vietspider>");
if(value.equals("exit")) System.exit(0);
if(value.startsWith("connect to ")) {
try {
connect(value.substring(value.indexOf("to") + 2).trim(), null, null);
} catch (Exception e) {
e.printStackTrace();
}
}
if(label.indexOf('?') > -1) return value;
if(connector == null) {
connect(readLine("Connect to(host:port)? "), null, null);
} else if(!connected) {
login(null, null);
}
if (value.equals("server shutdown")) {
String sure = readLine("Are you sure shutdown server?");
if(sure.equals("yes") || sure.equals("y")) {
try {
DataClientHandler.getInstance().exitApplication();
} catch (HttpHostConnectException e) {
console.printf("Server shutdown successfull!\n");
} catch (ConnectException e) {
console.printf("Server shutdown successfull!\n");
} catch (Exception e) {
e.printStackTrace();
}
return value;
}
} else {
try {
handleCommand(value);
} catch (Throwable e) {
e.printStackTrace();
}
}
try {
Thread.sleep(300);
} catch (Exception e) {
}
readLine("vietspider>");
return value;
}
private void connect(String value, String username, String [] args) {
value = value.trim();
String [] elements = value.split(":");
if(elements.length < 2) {
console.printf("Incorrect input. Try again.\n");
connect(readLine("Connect to(host:port)? "), null, null);
}
try {
connector = ClientConnector2.currentInstance(elements[0].trim(), elements[1].trim());
} catch (Exception e) {
e.printStackTrace();
}
connected = false;
try {
Thread.sleep(800);
} catch (Exception e) {
}
login(username, args);
}
private void login(String username, String [] args) {
while(username == null || username.trim().isEmpty()) {
username = readLine("Username? ");
}
String password = new String(console.readPassword("Password? "));
while(password == null || password.trim().isEmpty()) {
password = new String(console.readPassword("Password? "));
}
String message = "";
try {
int ping = connector.ping(username, password);
connected = ping > -1;
if(ping < -2) {
message = "Cann't connect to "+connector.getRemoteURL();
console.printf(message);
console.printf("\n");
connect(readLine("Connect to(host:port)? "), null, null);
return;
} else if (ping == -2) {
message = "Incorrect username!";
console.printf(message);
console.printf("\n");
login(null, args);
return;
} else if (ping == -1) {
message = "Incorrect password!";
login(username, args);
return;
} else if(ping == 0) {
message = "incorrect mode!";
}
} catch (Exception e) {
// e.printStackTrace();
if(e.getMessage() != null && e.getMessage().trim().length() > 0) {
message = e.getMessage();
} else {
message = e.toString();
}
}
if( (message != null && message.trim().endsWith("refused"))
|| (connector.getPermission() != User.ROLE_ADMIN)) {
console.printf(message);
console.printf("\n");
connect(readLine("Connect to(host:port)? "), null, null);
return;
}
if(connected) {
console.printf("Login successfull!\n");
handleCommand(args);
readLine("vietspider> ");
return;
}
console.printf(message);
console.printf("\n");
login(null, null);
}
private void handleCommand(String [] args) {
if(args == null) return;
for(String cmd : args) {
cmd = cmd.trim();
if(!cmd.toLowerCase().startsWith("--cmd")) continue;
if(cmd.indexOf('=') < 0) continue;
cmd = cmd.substring(cmd.indexOf('=')+1).trim();
if(cmd.charAt(0) == '\"') cmd = cmd.substring(1);
if(cmd.charAt(cmd.length() - 1) == '\"') {
cmd = cmd.substring(0, cmd.length() - 1);
}
try {
handleCommand(cmd);
} catch (Throwable e) {
e.printStackTrace();
}
}
}
public static void start(Object [] args) {
System.setProperty("file.encoding", "utf-8");
ClientConsole clientConsole = new ClientConsole();
String [] values = (String[])args;
while(true) {
if(values == null || values.length < 1) {
clientConsole.connect(clientConsole.readLine("Connect to(host:port)? "), null, null);
} else {
String url = values[0];
String username = null;
if(url.indexOf('@') > -1) {
username = url.substring(0, url.indexOf('@')).trim();
url = url.substring(url.indexOf('@') + 1).trim();
}
String [] cmd = new String[values.length-1];
for(int i = 1; i < values.length; i++) {
cmd[i-1] = values[i];
}
clientConsole.connect(url, username, cmd);
args = null;
}
try {
Thread.sleep(1000);
} catch (Exception e) {
}
}
}
public static final void main(String... aArgs){
ClientConsole clientConsole = new ClientConsole();
clientConsole.connect(clientConsole.readLine("Connect to(host:port)? "), null, null);
}
}
| true
|
684282071b867a815a0b98c5f9da2f44efb31817
|
Java
|
yanndemel/GWT-Gen
|
/gwt-naked-core/src/main/java/com/hiperf/common/ui/client/widget/CloseablePopupPanel.java
|
UTF-8
| 8,206
| 1.921875
| 2
|
[] |
no_license
|
package com.hiperf.common.ui.client.widget;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.DivElement;
import com.google.gwt.dom.client.Node;
import com.google.gwt.dom.client.TableCellElement;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.resources.client.ClientBundle;
import com.google.gwt.resources.client.ImageResource;
import com.google.gwt.user.client.DOM;
import com.google.gwt.dom.client.Element;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.Event.NativePreviewEvent;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.ResizeDialogBox;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.user.client.ui.Widget;
import com.hiperf.common.ui.client.i18n.NakedConstants;
public class CloseablePopupPanel extends ResizeDialogBox {
//private static final String NAKED_DIALOG_BOX = "naked-dialogBox";
public static final String CLOSE_TABLE_1 = "<table width=\"100%\" height=\"100%\" ><tr><td align=\"center\" width=\"100%\"/>";
public static final String CLOSE_TABLE_2 = "<td></td></tr></table>";
public interface Images extends ClientBundle {
ImageResource close_small();
}
private boolean hideOnEscape;
private boolean resize = true;
private boolean forceClose = false;
private ScrollPanel scrollPanel = null;
private FlexTable mainPanel = null;
//private HorizontalPanel caption = null;
private PopupMediator mediator;
private Image img;
public static final Images images = GWT.create(Images.class);
public void initPopup(boolean hideOnEscape) {
setStylePrimaryName(DEFAULT_STYLENAME);
setGlassEnabled(true);
this.hideOnEscape = hideOnEscape;
mediator = new PopupMediator(this);
init();
}
public CloseablePopupPanel() {
super();
}
public void init() {
newCloseImage();
HTML caption = initCloseImage();
// Add click handler to caption
caption.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
event.stopPropagation();
// Get x,y caption click relative to the anchor
final int x = event.getRelativeX(img.getElement());
final int y = event.getRelativeY(img.getElement());
//GWT.log("x="+x+", y="+y+" -- img.getOffsetWidth()="+img.getOffsetWidth()+", img.getOffsetHeight()="+img.getOffsetHeight());
// Check click was within bounds of anchor
if(x >= 0 && y >= 0 &&
x <= img.getOffsetWidth() &&
y <= img.getOffsetHeight()) {
// Raise event on anchor
img.fireEvent(event);
}
}
});
mainPanel = new FlexTable();
mainPanel.setBorderWidth(0);
mainPanel.setCellPadding(1);
mainPanel.setCellSpacing(0);
scrollPanel = new ScrollPanel(mainPanel);
super.add(scrollPanel);
}
public Image newCloseImage() {
this.img = new Image(images.close_small());
img.setTitle(NakedConstants.constants.closePopup());
img.setStylePrimaryName("close-button");
img.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
event.stopPropagation();
hide();
}
});
return img;
}
public HTML initCloseImage() {
if(getCaption() != null && getCaption().getText() != null && getCaption().getText().length() > 0) {
getCaption().setHTML(CLOSE_TABLE_1 + "<span>" + getCaption().getText() + "</span>" + CLOSE_TABLE_2);
}
else
getCaption().setHTML(CLOSE_TABLE_1 + " " + CLOSE_TABLE_2);
final HTML caption = ((HTML)getCaption());
DivElement captionDiv = DivElement.as(caption.getElement());
captionDiv.setAttribute("style", "height: 40px; vertical-align: middle; cursor: move;");
Element el = caption.getElement();
Element tdElt;
if(el.getChildCount() > 0) {
Node child = el.getChild(0);
if(child.getChildCount() > 0)
child = child.getChild(0);
if(child.getChildCount() > 0)
child = child.getChild(0);
if(child.getChildCount() > 1) {
child = child.getChild(1);
tdElt = TableCellElement.as(child);
tdElt.setAttribute("style", "cursor: pointer;");
tdElt.appendChild(img.getElement());
}
else if(child.getChildCount() > 0) {
child = child.getChild(0);
tdElt = TableCellElement.as(child);
tdElt.appendChild(img.getElement());
} else
child.appendChild(img.getElement());
}
return caption;
}
@Override
public void add(final Widget w) {
if(mainPanel!=null) {
mainPanel.setWidget(1, 0, w);
DOM.setElementAttribute(mainPanel.getParent().getElement(), "align", "center");
if(resize) {
addPanelResizedListener(new PanelResizeListener() {
@Override
public void onResized(Integer width, Integer height) {
mainPanel.setWidth("100%");
mainPanel.setHeight("100%");
mainPanel.getFlexCellFormatter().setWidth(1, 0, "100%");
mainPanel.getFlexCellFormatter().setHeight(1, 0, "100%");
Widget widget = mainPanel.getWidget(1, 0);
widget.setWidth("100%");
widget.setHeight("100%");
if(widget instanceof AbstractObjectPanel) {
AbstractObjectPanel w2 = (AbstractObjectPanel)widget;
w2.getObjectForm().setWidth("100%");
w2.getObjectForm().setHeight("100%");
w2.getObjectForm().getFormGrid().setWidth("100%");
w2.getObjectForm().getFormGrid().setHeight("100%");
} else if(widget instanceof TablePanel) {
TablePanel w2 = (TablePanel)widget;
w2.getTable().setWidth("100%");
w2.getTable().setHeight("100%");
w2.getPanel().setWidth("100%");
w2.getPanel().setHeight("100%");
}
}
});
}
}
else {
super.add(w);
if(resize) {
addPanelResizedListener(new PanelResizeListener() {
@Override
public void onResized(Integer width, Integer height) {
w.setWidth("100%");
w.setHeight("100%");
}
});
}
}
}
@Override
protected void onLoad() {
int clientWidth = Window.getClientWidth();
if(clientWidth < getOffsetWidth()) {
scrollPanel.setWidth(clientWidth + "px");
}
super.onLoad();
}
public void clearMainPanel() {
if(mainPanel!=null && mainPanel.getRowCount() > 1) {
Element div = mainPanel.getWidget(1,0).getParent().getParent().getElement();
if(div != null) {
String s = div.getAttribute("style");
if(s != null) {
int i = s.indexOf("width");
if(i >= 0) {
s = removeAttribute(div, s, i);
}
i = s.indexOf("height");
if(i >= 0) {
s = removeAttribute(div, s, i);
}
getContainerElement().removeAttribute("width");
getContainerElement().removeAttribute("height");
}
}
mainPanel.clearCell(1, 0);
}
}
private String removeAttribute(Element div, String s, int i) {
int j = s.indexOf(";", i);
if(j>i && j+1 < s.length()) {
if(i>0)
s = s.substring(0, i) + s.substring(j + 1);
else
s = s.substring(j + 1);
} else if(i>0)
s = s.substring(0, i);
else
s = "";
div.setAttribute("style", s);
return s;
}
public Widget getMainWidget() {
if(mainPanel!=null && mainPanel.getRowCount() > 1)
return mainPanel.getWidget(1,0);
return getWidget();
}
protected void onPreviewNativeEvent(NativePreviewEvent event) {
if(hideOnEscape) {
Event e = Event.as(event.getNativeEvent());
switch(e.getTypeInt()) {
case Event.ONKEYUP:
switch(e.getKeyCode()) {
case KeyCodes.KEY_ESCAPE:
hide();
event.cancel();
break;
default:
break;
}
break;
default:
break;
}
}
}
public boolean isForceClose() {
return forceClose;
}
public void setForceClose(boolean forceClose) {
this.forceClose = forceClose;
}
@Override
public void clear() {
super.clear();
mainPanel = null;
}
public PopupMediator getMediator() {
return mediator;
}
@Override
public void setPopupTitle(String s) {
getCaption().setText(s);
initCloseImage();
}
public void setResize(boolean resize) {
this.resize = resize;
}
}
| true
|
c05b900c6bbec630ab64f584fe20ee7807cea18e
|
Java
|
QuantumSoundings/Juxs
|
/JUX_COMMON/mods/juxs/item/ModItems.java
|
UTF-8
| 792
| 2.046875
| 2
|
[] |
no_license
|
package mods.juxs.item;
import cpw.mods.fml.common.registry.GameRegistry;
import cpw.mods.fml.common.registry.LanguageRegistry;
import net.minecraft.item.Item;
import net.minecraft.item.ItemRecord;
public class ModItems {
public static Item feelingGood;
public static Item sprintDude;
public static void init(){
feelingGood= new FeelingGood(4444);
sprintDude= new SprintDude(4445);
GameRegistry.registerItem(feelingGood, "FeelingGood");
LanguageRegistry.addName(feelingGood,"Michael Buble- Feeling Good");
GameRegistry.registerItem(sprintDude, "Sprint Dude");
LanguageRegistry.addName(sprintDude, "Sprint Dude");
//ItemRecord fg= new ItemRecord(4444,"mods/Juxs/sound/feeling_good.ogg");
}
}
| true
|
62d5e4b32168961263de2cc41fb91875eaa5b6a1
|
Java
|
shelimingming/spring-demo
|
/src/test/java/com/sheliming/spring/demo/ioc_anno/TestSpringIoC.java
|
UTF-8
| 770
| 2.5
| 2
|
[] |
no_license
|
package com.sheliming.spring.demo.ioc_anno;
import com.sheliming.spring.demo.ioc_anno.configuration.SpringConfiguration;
import com.sheliming.spring.demo.ioc_anno.service.UserService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class TestSpringIoC {
@Test
public void test1() {
// 创建纯注解方式的spring容器
ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfiguration.class);
//从容器中获取Bean的实例
UserService service = context.getBean(UserService.class);
service.saveUser();
UserService service2 = (UserService) context.getBean("userService");
service2.saveUser();
}
}
| true
|
64dcc178d5cf58be2023860596eb90e9efaf063c
|
Java
|
diopside/twclone
|
/TWClone/src/entities/units/buildings/Hall.java
|
UTF-8
| 548
| 2.640625
| 3
|
[] |
no_license
|
package entities.units.buildings;
import entities.Faction;
import entities.world.Territory;
public class Hall extends Building {
/*
* The halls in the game will represent the centers of government, varying levels will influence things like population growth, tax income,
* loyalty, and building productivity
*/
public boolean canBuild(Faction f, Territory t) {
// TODO Auto-generated method stub.
return false;
}
public void build(Faction f, Territory t) {
// TODO Auto-generated method stub.
}
}
| true
|
f5cc90409112fbde0c4846be8ee2cc6394d29d3c
|
Java
|
abhishekSen999/UnderstandingJava
|
/src/understandingJava/multithreading/MultithreadingDemoMainUsingLambda.java
|
UTF-8
| 1,336
| 3.90625
| 4
|
[] |
no_license
|
package understandingJava.multithreading;
import java.sql.SQLOutput;
import java.util.Arrays;
public class MultithreadingDemoMainUsingLambda {
private static int[] numbers = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
private static int sumOfFirstHalf = 0;
private static int sumOfSecondHalf = 0;
//
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
int[] firstHalf = Arrays.copyOfRange(numbers, 0, 5);
int[] secondHalf = Arrays.copyOfRange(numbers, 5, 10);
// Thread to sum first half
Thread t1 = new Thread(() -> {
for (int num : firstHalf) {
System.out.println("Thread 1 is adding: " + num);
sumOfFirstHalf += num;
}
System.out.println("thread 1 captured Sum: " + sumOfFirstHalf);
});
Thread t2 = new Thread(() -> {
for (int num : secondHalf) {
System.out.println("Thread 2 is adding: " + num);
sumOfSecondHalf += num;
}
System.out.println("thread 2 captured Sum: " + sumOfSecondHalf);
});
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("Sum is: " + (sumOfFirstHalf + sumOfSecondHalf));
}
}
| true
|
d96fd1d3cd296de6ef76e09f368adf5d5160baee
|
Java
|
wb-brave/spring-springboot-java-Learn-develop
|
/Program_wubin/src/main/java/thinkinjava/chapter15/generics/arrays/UnboundedWildcards1.java
|
UTF-8
| 1,638
| 3.5
| 4
|
[] |
no_license
|
package thinkinjava.chapter15.generics.arrays;
import java.util.ArrayList;
import java.util.List;
/**
* @author wubin
* @Description
* @project Learn-develop
* @package thinkinjava.chapter15.generics.arrays
* @email wubin326@qq.com
* @date 2018/11/20
* Modification History:
* Date Author Version Description
* ----------------------------------------------------------------------
* 2018/11/20 wubin 0.0.1
*/
public class UnboundedWildcards1 {
static List list1;
static List<?> list2;
static List<? extends Object> list3;
static void assign1(List list) {
list1 = list;
list2 = list;
list3 = list; // Warning: unchecked conversion
// Found: List, Required: List<? extends Object>
}
static void assign2(List<?> list) {
list1 = list;
list2 = list;
list3 = list;
}
static void assign3(List<? extends Object> list) {
list1 = list;
list2 = list;
list3 = list;
}
public static void main(String[] args) {
assign1(new ArrayList());
assign2(new ArrayList());
assign3(new ArrayList()); // Warning:
// Unchecked conversion. Found: ArrayList
// Required: List<? extends Object>
assign1(new ArrayList<String>());
assign2(new ArrayList<String>());
assign3(new ArrayList<String>());
// Both forms are acceptable as List<?>:
List<?> wildList = new ArrayList();
wildList = new ArrayList<String>();
assign1(wildList);
assign2(wildList);
assign3(wildList);
}
}
| true
|
67a64ee2188e132d4e0a52e7261d5d087703ee88
|
Java
|
MadByteDE/StorageDrawers
|
/packs/Forestry/src/com/jaquadro/minecraft/storagedrawers/packs/forestry/core/ModBlocks.java
|
UTF-8
| 4,551
| 2.171875
| 2
|
[
"MIT"
] |
permissive
|
package com.jaquadro.minecraft.storagedrawers.packs.forestry.core;
import com.jaquadro.minecraft.storagedrawers.api.IStorageDrawersApi;
import com.jaquadro.minecraft.storagedrawers.api.StorageDrawersApi;
import com.jaquadro.minecraft.storagedrawers.api.config.IBlockConfig;
import com.jaquadro.minecraft.storagedrawers.api.config.IUserConfig;
import com.jaquadro.minecraft.storagedrawers.api.pack.BlockConfiguration;
import com.jaquadro.minecraft.storagedrawers.api.pack.IPackBlockFactory;
import com.jaquadro.minecraft.storagedrawers.api.pack.IPackDataResolver;
import com.jaquadro.minecraft.storagedrawers.packs.forestry.StorageDrawersPack;
import cpw.mods.fml.common.registry.GameData;
import net.minecraft.block.Block;
public class ModBlocks
{
public static Block[] fullDrawers1;
public static Block[] fullDrawers2;
public static Block[] fullDrawers4;
public static Block[] halfDrawers2;
public static Block[] halfDrawers4;
public static Block[] trim;
public void init () {
IStorageDrawersApi api = StorageDrawersApi.instance();
if (api == null)
return;
IPackBlockFactory factory = api.packFactory();
IPackDataResolver[] resolvers = StorageDrawersPack.instance.resolvers;
fullDrawers1 = new Block[resolvers.length];
fullDrawers2 = new Block[resolvers.length];
fullDrawers4 = new Block[resolvers.length];
halfDrawers2 = new Block[resolvers.length];
halfDrawers4 = new Block[resolvers.length];
trim = new Block[resolvers.length];
for (int i = 0; i < resolvers.length; i++) {
IPackDataResolver resolver = resolvers[i];
fullDrawers1[i] = factory.createBlock(BlockConfiguration.BasicFull1, resolver);
fullDrawers2[i] = factory.createBlock(BlockConfiguration.BasicFull2, resolver);
fullDrawers4[i] = factory.createBlock(BlockConfiguration.BasicFull4, resolver);
halfDrawers2[i] = factory.createBlock(BlockConfiguration.BasicHalf2, resolver);
halfDrawers4[i] = factory.createBlock(BlockConfiguration.BasicHalf4, resolver);
trim[i] = factory.createBlock(BlockConfiguration.Trim, resolver);
}
IUserConfig config = api.userConfig();
IBlockConfig blockConfig = config.blockConfig();
char[] tail = new char[] { 'A', 'B' };
if (blockConfig.isBlockEnabled(blockConfig.getBlockConfigName(BlockConfiguration.BasicFull1))) {
for (int i = 0; i < resolvers.length; i++)
factory.registerBlock(fullDrawers1[i], "fullDrawers1" + tail[i]);
}
if (blockConfig.isBlockEnabled(blockConfig.getBlockConfigName(BlockConfiguration.BasicFull2))) {
for (int i = 0; i < resolvers.length; i++)
factory.registerBlock(fullDrawers2[i], "fullDrawers2" + tail[i]);
}
if (blockConfig.isBlockEnabled(blockConfig.getBlockConfigName(BlockConfiguration.BasicFull4))) {
for (int i = 0; i < resolvers.length; i++)
factory.registerBlock(fullDrawers4[i], "fullDrawers4" + tail[i]);
}
if (blockConfig.isBlockEnabled(blockConfig.getBlockConfigName(BlockConfiguration.BasicHalf2))) {
for (int i = 0; i < resolvers.length; i++)
factory.registerBlock(halfDrawers2[i], "halfDrawers2" + tail[i]);
}
if (blockConfig.isBlockEnabled(blockConfig.getBlockConfigName(BlockConfiguration.BasicHalf4))) {
for (int i = 0; i < resolvers.length; i++)
factory.registerBlock(halfDrawers4[i], "halfDrawers4" + tail[i]);
}
if (blockConfig.isBlockEnabled(blockConfig.getBlockConfigName(BlockConfiguration.Trim))) {
for (int i = 0; i < resolvers.length; i++)
factory.registerBlock(trim[i], "trim" + tail[i]);
}
if (!config.addonConfig().showAddonItemsNEI()) {
for (int i = 0; i < resolvers.length; i++) {
factory.hideBlock(getQualifiedName(fullDrawers1[i]));
factory.hideBlock(getQualifiedName(fullDrawers2[i]));
factory.hideBlock(getQualifiedName(fullDrawers4[i]));
factory.hideBlock(getQualifiedName(halfDrawers2[i]));
factory.hideBlock(getQualifiedName(halfDrawers4[i]));
factory.hideBlock(getQualifiedName(trim[i]));
}
}
}
public static String getQualifiedName (Block block) {
return GameData.getBlockRegistry().getNameForObject(block);
}
}
| true
|
1fff57180d21e02b0ab9e3baed82b4ea031acaab
|
Java
|
garfiny/VehicleSurvey
|
/src/main/java/vehiclesurvey/reports/AbstractReport.java
|
UTF-8
| 957
| 2.828125
| 3
|
[] |
no_license
|
package vehiclesurvey.reports;
import vehiclesurvey.TimePeriod;
public abstract class AbstractReport implements Report {
private static final long MINUTES_OF_DAY = 24 * 60;
private TimePeriod period;
public AbstractReport(TimePeriod period) {
this.setPeriod(period);
}
@Override
public String[] getHeaders() {
int range = getRange();
String[] headers = new String[range];
for (int i = 1; i < range; i++) {
headers[i] = String.format(" #%02d", i);
}
headers[0] = "Range";
return headers;
}
@Override
public String getHeaderFormat() {
StringBuilder sb = new StringBuilder("%13s");
for (int i = 1; i < getRange(); i++) {
sb.append("%5s");
}
sb.append("%n");
return sb.toString();
}
protected int getRange() {
return (int) (MINUTES_OF_DAY / getPeriod().minutesOfPeriod() + 1);
}
public TimePeriod getPeriod() {
return period;
}
public void setPeriod(TimePeriod period) {
this.period = period;
}
}
| true
|
6c9ac3e1a319964df05ced921730c77404dbef2b
|
Java
|
aheadlcx/analyzeApk
|
/budejie/sources/com/ishumei/d/h.java
|
UTF-8
| 9,146
| 1.757813
| 2
|
[] |
no_license
|
package com.ishumei.d;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.ScanResult;
import android.telephony.TelephonyManager;
import android.text.format.Formatter;
import com.baidu.mobads.interfaces.utils.IXAdSystemUtils;
import com.ishumei.b.d;
import com.ishumei.f.e;
import java.io.File;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import net.vidageek.a.b.c;
public class h {
private static h d = null;
private Object a = null;
private Context b = null;
private Object c = null;
private h() {
try {
this.b = d.a;
if (this.b != null) {
this.a = new c().a(this.b).a().a(com.ishumei.f.d.g("989a8bac868c8b9a92ac9a8d89969c9a")).a(new Object[]{com.ishumei.f.d.g("88969996")});
if (this.a != null) {
this.c = new c().a(this.a).a().a(com.ishumei.f.d.g("989a8bbc9091919a9c8b969091b6919990")).a(new Object[0]);
}
}
} catch (Exception e) {
}
}
public static h a() {
if (d == null) {
synchronized (h.class) {
if (d == null) {
d = new h();
}
}
}
return d;
}
public static String a(int i) {
switch (i) {
case -101:
return IXAdSystemUtils.NT_WIFI;
case -1:
return "nil";
case 0:
return "unknown";
case 1:
return "2g.gprs";
case 2:
return "2g.edge";
case 3:
return "3g.umts";
case 4:
return "2g.cdma";
case 5:
return "3g.evdo_0";
case 6:
return "3g.evdo_a";
case 7:
return "2g.1xrtt";
case 8:
return "3g.hsdpa";
case 9:
return "3g.hsupa";
case 10:
return "3g.hspa";
case 11:
return "2g.iden";
case 12:
return "3g.evdo_b";
case 13:
return "4g.lte";
case 14:
return "3g.ehrpd";
case 15:
return "3g.hspap";
default:
return String.format("%d", new Object[]{Integer.valueOf(i)});
}
}
private String j() {
try {
NetworkInfo activeNetworkInfo = ((ConnectivityManager) this.b.getSystemService("connectivity")).getActiveNetworkInfo();
int type;
if (activeNetworkInfo != null && activeNetworkInfo.isAvailable() && activeNetworkInfo.isConnected()) {
type = activeNetworkInfo.getType();
if (type == 1) {
type = -101;
} else {
if (type == 0) {
type = ((TelephonyManager) this.b.getSystemService("phone")).getNetworkType();
}
type = 0;
}
return a(type);
}
type = -1;
return a(type);
} catch (Throwable e) {
com.ishumei.f.c.a(e);
}
}
public String b() {
String str = "";
try {
if (this.c == null) {
return str;
}
String str2 = (String) new c().a(this.c).a().a(com.ishumei.f.d.g("989a8bacacb6bb")).a();
if (str2 != null) {
return str2;
}
try {
return "";
} catch (Exception e) {
return str2;
}
} catch (Exception e2) {
return str;
}
}
public String c() {
String str = "";
try {
if (this.c == null) {
return str;
}
String str2 = (String) new c().a(this.c).a().a(com.ishumei.f.d.g("989a8bbdacacb6bb")).a();
if (str2 != null) {
return str2;
}
try {
return "";
} catch (Exception e) {
return str2;
}
} catch (Exception e2) {
return str;
}
}
public String d() {
String str = "";
try {
if (this.c == null) {
return str;
}
String str2 = (String) new c().a(this.c).a().a(com.ishumei.f.d.g("989a8bb29e9cbe9b9b8d9a8c8c")).a();
if (str2 != null) {
return str2;
}
try {
return "";
} catch (Exception e) {
return str2;
}
} catch (Exception e2) {
return str;
}
}
public String e() {
String str = "";
try {
if (this.c == null) {
return str;
}
String formatIpAddress = Formatter.formatIpAddress(((Integer) new c().a(this.c).a().a(com.ishumei.f.d.g("989a8bb68fbe9b9b8d9a8c8c")).a()).intValue());
if (formatIpAddress != null) {
return formatIpAddress;
}
try {
return "";
} catch (Exception e) {
return formatIpAddress;
}
} catch (Exception e2) {
return str;
}
}
public List<String> f() {
List<String> arrayList = new ArrayList();
try {
if (this.a != null) {
for (ScanResult scanResult : (List) new c().a(this.a).a().a(com.ishumei.f.d.g("989a8bac9c9e91ad9a8c8a938b8c")).a()) {
String str = (String) new c().a(scanResult).b().a(com.ishumei.f.d.g("bdacacb6bb"));
arrayList.add(e.d(str) + "," + ((Integer) new c().a(scanResult).b().a(com.ishumei.f.d.g("939a899a93"))).intValue());
}
}
} catch (Exception e) {
}
return arrayList;
}
public String g() {
String d;
try {
d = e.d((String) new c().a(new c().b(com.ishumei.f.d.g("9e919b8d90969bd19d938a9a8b90908b97d1bd938a9a8b90908b97be9b9e8f8b9a8d")).a().a(com.ishumei.f.d.g("989a8bbb9a999e8a938bbe9b9e8f8b9a8d")).a()).a().a(com.ishumei.f.d.g("989a8bbe9b9b8d9a8c8c")).a());
return d == null ? "" : d;
} catch (Throwable e) {
com.ishumei.f.c.a(e);
try {
d = e.d(e.a(new File(com.ishumei.f.d.g("d09a998cd09d938a9a8b90908b97d09d8ba09e9b9b8d"))));
return d == null ? "" : d;
} catch (Throwable e2) {
com.ishumei.f.c.a(e2);
return null;
}
}
}
public String h() {
String str = "";
try {
if (this.b == null) {
return str;
}
str = j();
return str == null ? "" : str;
} catch (Exception e) {
return str;
}
}
public List<String> i() {
List<String> arrayList = new ArrayList();
try {
Object a = new c().b(com.ishumei.f.d.g("959e899ed1919a8bd1b19a8b88908d94b6918b9a8d999e9c9a")).a().a(com.ishumei.f.d.g("989a8bb19a8b88908d94b6918b9a8d999e9c9a8c")).a();
Method a2 = new c().a(Enumeration.class).b().b(com.ishumei.f.d.g("979e8cb2908d9aba939a929a918b8c")).a();
Method a3 = new c().a(Enumeration.class).b().b(com.ishumei.f.d.g("919a878bba939a929a918b")).a();
while (((Boolean) a2.invoke(a, new Object[0])).booleanValue()) {
NetworkInterface networkInterface = (NetworkInterface) a3.invoke(a, new Object[0]);
if (!networkInterface.isLoopback()) {
String str = "";
String str2 = "";
byte[] hardwareAddress = networkInterface.getHardwareAddress();
String d = (hardwareAddress == null || hardwareAddress.length <= 0) ? str2 : e.d(e.a(hardwareAddress));
if (!(d.isEmpty() || d.equals("000000000000"))) {
Enumeration inetAddresses = networkInterface.getInetAddresses();
while (inetAddresses.hasMoreElements()) {
InetAddress inetAddress = (InetAddress) inetAddresses.nextElement();
if (!inetAddress.isLoopbackAddress()) {
str2 = inetAddress.getHostAddress();
if (str2.length() < 15) {
break;
}
}
}
str2 = str;
arrayList.add(networkInterface.getDisplayName() + "," + str2 + "," + d);
}
}
}
} catch (Exception e) {
}
return arrayList;
}
}
| true
|
b27cee6c6f5fb3ecb386e5af37c71dbf9d5ce2a6
|
Java
|
snehajakovvuri/ADJ1264
|
/Program3/RmiClient.java
|
UTF-8
| 520
| 3
| 3
|
[] |
no_license
|
import java.rmi.*;
import java.util.*;
public class RmiClient {
public static void main(String args[]) throws Exception{
int n,result;
Scanner sc = new Scanner(System.in);
System.out.println("Enter n value:");
n = sc.nextInt();
Armstrong a = (Armstrong)Naming.lookup("rmi://localhost:1099/ArmstrongServer");
result = a.Arm(n);
if(result==n){
System.out.println("The given number is Armstrong number");
}
else {
System.out.println("The given number is not Armstrong number");
}
}
}
| true
|
a25d356b844fa32af3efd2fa81b18443faf332cd
|
Java
|
maciejKrasny/SzeregowanieZada-alg.-genetyczny-
|
/src/instancjeOrazRozwiazania/OdczytIZapis.java
|
UTF-8
| 16,980
| 2.71875
| 3
|
[] |
no_license
|
package instancjeOrazRozwiazania;
/*
* 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.
*/
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import ogolne.Element;
import ogolne.Przerwanie;
import ogolne.Zadanie;
import glowne.Main;
import glowne.Main;
/**
*
* @author PC
*/
public class OdczytIZapis {
private List <Element> rozwiazanieMaszyna0 = new ArrayList<>();
private List <Element> rozwiazanieMaszyna1 = new ArrayList<>();
private int liczbaPrzerwM1 = 0;
private int czasPrzerwM1 = 0;
private int liczbaPrzerwM2 = 0;
private int czasPrzerwM2 = 0;
private int liczbaPrzerwIdleM1 = 0;
private int czasPrzerwIdleM1 = 0;
private int liczbaPrzerwIdleM2 = 0;
private int czasPrzerwIdleM2 = 0;
/**
* odczytanie instancji
* @param nrInstancji numer odczytywanej instancji
* @throws IOException
*/
public void odczytaj(int nrInstancji) throws IOException {
String plik = "instancje/strojenie/instancja" + nrInstancji + ".problem";
BufferedInputStream stream = new BufferedInputStream(new FileInputStream(plik));
BufferedReader in = new BufferedReader(new InputStreamReader(stream));
String linia;
String liniaSplit[];
in.readLine();
Main.iloscZadan = Integer.parseInt(in.readLine());
// odczytywanie zadań
for(int nrZad = 0; nrZad < Main.iloscZadan; nrZad++) {
linia = in.readLine();
linia = linia.replaceAll("\\s","");
liniaSplit = linia.split(";");
Zadanie zad = new Zadanie(nrZad,
Integer.parseInt(liniaSplit[0]),
Integer.parseInt(liniaSplit[1]),
Integer.parseInt(liniaSplit[4]));
Main.zadania.add(zad);
}
// odczytywanie przerwań
while(!(linia = in.readLine()).equals("*** EOF ***")) {
linia = linia.replaceAll("\\s","");
liniaSplit = linia.split(";");
Przerwanie przerwa = new Przerwanie(
Integer.parseInt(liniaSplit[0]),
Integer.parseInt(liniaSplit[1]),
Integer.parseInt(liniaSplit[2]),
Integer.parseInt(liniaSplit[3]));
Main.przerwania.add(przerwa);
}
in.close();
// sortujemy przerwania - najpierw przerwania na pierwszej maszynie po kolei, potem te na drugiej
Collections.sort(Main.przerwania, new KomparatorCzasStartuPrzerwania());
}
/**
* odczytanie instancji za pomocą podanej ścieżki
* @param sciezka gdzie jest plik
* @param nrInstancji numer odczytywanej instancji
* @throws IOException
*/
public void odczytajSciezka(String sciezka, int nrInstancji) throws IOException {
String plik = "instancje/" + sciezka + nrInstancji + ".problem";
BufferedInputStream stream = new BufferedInputStream(new FileInputStream(plik));
BufferedReader in = new BufferedReader(new InputStreamReader(stream));
String linia;
String liniaSplit[];
in.readLine();
Main.iloscZadan = Integer.parseInt(in.readLine());
// odczytywanie zadań
for(int nrZad = 0; nrZad < Main.iloscZadan; nrZad++) {
linia = in.readLine();
linia = linia.replaceAll("\\s","");
liniaSplit = linia.split(";");
Zadanie zad = new Zadanie(nrZad,
Integer.parseInt(liniaSplit[0]),
Integer.parseInt(liniaSplit[1]),
Integer.parseInt(liniaSplit[4]));
Main.zadania.add(zad);
}
// odczytywanie przerwań
while(!(linia = in.readLine()).equals("*** EOF ***")) {
linia = linia.replaceAll("\\s","");
liniaSplit = linia.split(";");
Przerwanie przerwa = new Przerwanie(
Integer.parseInt(liniaSplit[0]),
Integer.parseInt(liniaSplit[1]),
Integer.parseInt(liniaSplit[2]),
Integer.parseInt(liniaSplit[3]));
Main.przerwania.add(przerwa);
}
in.close();
Collections.sort(Main.przerwania, new KomparatorCzasStartuPrzerwania());
}
/**
* zapis rozwiązania
* @param nrInstancji numer instancji, której rozwiązanie zapisujemy
* @throws IOException
*/
public void zapis(int nrInstancji) throws IOException {
rozwiazanieMaszyna0 = new ArrayList<>();
rozwiazanieMaszyna1 = new ArrayList<>();
liczbaPrzerwM1 = 0;
czasPrzerwM1 = 0;
liczbaPrzerwM2 = 0;
czasPrzerwM2 = 0;
liczbaPrzerwIdleM1 = 0;
czasPrzerwIdleM1 = 0;
liczbaPrzerwIdleM2 = 0;
czasPrzerwIdleM2 = 0;
String plik = "rozwiazania/nowy/instancja" + nrInstancji + ".rozwiazanie";
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(plik)));
out.write("**** " + Integer.toString(nrInstancji) + " ****\n");
out.write(Integer.toString(Main.najlepszyCzas) + "; "
+ Integer.toString(Main.sredniLosowy) + "\n");
ustawZadania();
out.write("M1: ");
for (Element element1 : rozwiazanieMaszyna0) {
out.write(element1.getNazwa());
// jeśli element jest operacja to nazwę tworzymy troche inaczej
if(element1.getId() >= 0) {
out.write(Integer.toString(element1.getId()));
}
out.write(", " + element1.getCzasStartu() + ", " + element1.getCzasOperacji() + "; ");
}
out.write("\nM2: ");
for (Element element2 : rozwiazanieMaszyna1) {
out.write(element2.getNazwa());
// jeśli element jest operacja to nazwę tworzymy troche inaczej
if(element2.getId() >= 0) {
out.write(Integer.toString(element2.getId()));
}
out.write(", " + element2.getCzasStartu() + ", " + element2.getCzasOperacji() + "; ");
}
out.write("\n");
out.write(liczbaPrzerwM1 + ", " + czasPrzerwM1 + '\n');
out.write(liczbaPrzerwM2 + ", " + czasPrzerwM2 + '\n');
out.write(liczbaPrzerwIdleM1 + ", " + czasPrzerwIdleM1 + '\n');
out.write(liczbaPrzerwIdleM2 + ", " + czasPrzerwIdleM2 + '\n');
out.write("*** EOF ***");
out.close();
}
/**
* zapis rozwiązania za pomocą podanej ścieżki
* @param sciezka gdzie jest plik
* @param nrInstancji numer instancji której rozwiązanie zapisujemy
* @throws IOException
*/
public void zapisSciezka(String sciezka, int nrInstancji) throws IOException {
rozwiazanieMaszyna0 = new ArrayList<>();
rozwiazanieMaszyna1 = new ArrayList<>();
liczbaPrzerwM1 = 0;
czasPrzerwM1 = 0;
liczbaPrzerwM2 = 0;
czasPrzerwM2 = 0;
liczbaPrzerwIdleM1 = 0;
czasPrzerwIdleM1 = 0;
liczbaPrzerwIdleM2 = 0;
czasPrzerwIdleM2 = 0;
String plik = "rozwiazania/" + sciezka + nrInstancji + ".rozwiazanie";
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(plik)));
out.write("**** " + Integer.toString(nrInstancji) + " ****\n");
out.write(Integer.toString(Main.najlepszyCzas) + "; "
+ Integer.toString(Main.sredniLosowy) + "\n");
ustawZadania();
out.write("M1: ");
for (Element element1 : rozwiazanieMaszyna0) {
out.write(element1.getNazwa());
// jeśli element jest operacja to nazwę tworzymy troche inaczej
if(element1.getId() >= 0) {
out.write(Integer.toString(element1.getId()));
}
out.write(", " + element1.getCzasStartu() + ", " + element1.getCzasOperacji() + "; ");
}
out.write("\nM2: ");
for (Element element2 : rozwiazanieMaszyna1) {
out.write(element2.getNazwa());
// jeśli element jest operacja to nazwę tworzymy troche inaczej
if(element2.getId() >= 0) {
out.write(Integer.toString(element2.getId()));
}
out.write(", " + element2.getCzasStartu() + ", " + element2.getCzasOperacji() + "; ");
}
out.write("\n");
out.write(liczbaPrzerwM1 + ", " + czasPrzerwM1 + '\n');
out.write(liczbaPrzerwM2 + ", " + czasPrzerwM2 + '\n');
out.write(liczbaPrzerwIdleM1 + ", " + czasPrzerwIdleM1 + '\n');
out.write(liczbaPrzerwIdleM2 + ", " + czasPrzerwIdleM2 + '\n');
out.write("*** EOF ***");
out.close();
}
/**
* ustawienie operacji na maszynach wraz z dodaniem przerwań technicznych i przerw, gdy maszyna nic nie robi
*/
public void ustawZadania() {
int czasAktualny = 0;
Zadanie tempZad;
// najpierw dodajemy przerwania na maszyny
for (Przerwanie przerwanie : Main.przerwania) {
if( przerwanie.getNumerMaszyny() == 0 ) {
rozwiazanieMaszyna0.add(new Element(
"maint"+przerwanie.getNrPrzerwania()+"_M1",
-1,
przerwanie.getCzasStartu(),
przerwanie.getCzas()));
liczbaPrzerwM1++;
czasPrzerwM1 += przerwanie.getCzas();
}
else {
rozwiazanieMaszyna1.add(new Element(
"maint"+przerwanie.getNrPrzerwania()+"_M2",
-1,
przerwanie.getCzasStartu(),
przerwanie.getCzas()));
liczbaPrzerwM2++;
czasPrzerwM2 += przerwanie.getCzas();
}
}
int nrPozycji = 0;
// dodajemy operacje na maszynę pierwszą
for (Integer nrZadania : Main.najlepszeRozw.getMaszyna0()) {
tempZad = Main.zadania.get(nrZadania);
// jeśli czas rozpoczęcia zadania (readytime) jest większy od czau aktualnego to staje się on czasem aktualnym
if (czasAktualny < tempZad.getCzasRozpoczecia()) {
czasAktualny = tempZad.getCzasRozpoczecia();
}
// jeśli na maszynie w obecnym miejscu byłoby pusto to po prostu operację dodajemy na listę
while(rozwiazanieMaszyna0.size() != nrPozycji) {
// jeśli przerwanie zaczyna się w czasie wykonywania operacji to operacje dodajemy za przerwaniem
if(rozwiazanieMaszyna0.get(nrPozycji).getCzasStartu() < czasAktualny + tempZad.getCzasOp0()) {
czasAktualny = rozwiazanieMaszyna0.get(nrPozycji).getCzasStartu() + rozwiazanieMaszyna0.get(nrPozycji).getCzasOperacji();
nrPozycji++;
}
else break;
}
// dodajemy operację pierwszą na pierwszą maszynę w wybranym miejscu jako element
rozwiazanieMaszyna0.add(nrPozycji, new Element(
"o1_",
tempZad.getId(),
czasAktualny,
tempZad.getCzasOp0()));
czasAktualny += tempZad.getCzasOp0();
nrPozycji++;
}
czasAktualny = 0;
nrPozycji = 0;
// dodajemy operacje na drugą maszynę
for (Integer nrZadania : Main.najlepszeRozw.getMaszyna1()) {
tempZad = Main.zadania.get(nrZadania);
// sprawdzamy kiedy zakończyła się operacja pierwsza zadania i jeśli po czasie aktualnym to staje się on nowym czasem aktualnym
for (int j = 0; j < rozwiazanieMaszyna0.size(); j++){
if (rozwiazanieMaszyna0.get(j).getNazwa().equals("o1_")
&& tempZad.getId()== rozwiazanieMaszyna0.get(j).getId() ) {
czasAktualny = Math.max(czasAktualny,
(rozwiazanieMaszyna0.get(j).getCzasStartu()
+rozwiazanieMaszyna0.get(j).getCzasOperacji()));
break;
}
}
while (rozwiazanieMaszyna1.size() != nrPozycji) {
// jeśli przerwanie zaczyna się przed skończeniem wykonywania operacji
if(rozwiazanieMaszyna1.get(nrPozycji).getCzasStartu() < czasAktualny + tempZad.getCzasOp1()) {
// czas aktualny może zmienić wartość na czas zakończenia przerwania jeśli przerwanie wystąpiło w trakcie (mogło mieć miejsce o wiele wcześniej niż kiedy zaczęła się operacja)
czasAktualny = Math.max(czasAktualny,
rozwiazanieMaszyna1.get(nrPozycji).getCzasStartu() +
rozwiazanieMaszyna1.get(nrPozycji).getCzasOperacji());
nrPozycji++;
}
else break;
}
// dodanie operacji drugiej na maszynę
rozwiazanieMaszyna1.add(nrPozycji, new Element(
"o2_",
tempZad.getId(),
czasAktualny,
tempZad.getCzasOp1()));
}
// dodanie czasów gdy maszyna nic nie robi (idle) na maszynę pierwszą
int czasTrwania = 0;
nrPozycji = 0;
czasAktualny = 0;
while(nrPozycji < rozwiazanieMaszyna0.size()) {
// jeśli czas aktualny nie zgadza się z czasem rozpoczęcia operacji / przerwania na maszynie to oznacza to, że maszyna nic w tym czasie nie robiła więc dodajemy przerwę idle
if(czasAktualny < rozwiazanieMaszyna0.get(nrPozycji).getCzasStartu()) {
czasTrwania = rozwiazanieMaszyna0.get(nrPozycji).getCzasStartu() - czasAktualny;
rozwiazanieMaszyna0.add(nrPozycji, new Element(
"idle" + liczbaPrzerwIdleM1 + "_M1",
-2,
czasAktualny,
czasTrwania));
liczbaPrzerwIdleM1++;
czasPrzerwIdleM1 += czasTrwania;
czasAktualny += czasTrwania;
nrPozycji++;
continue;
}
czasAktualny += rozwiazanieMaszyna0.get(nrPozycji).getCzasOperacji();
nrPozycji++;
}
nrPozycji = 0;
czasAktualny = 0;
// dodanie czasów gdy maszyna nic nie robi (idle) na maszynę drugą
while(nrPozycji < rozwiazanieMaszyna1.size()) {
// jeśli czas aktualny nie zgadza się z czasem rozpoczęcia operacji / przerwania na maszynie to oznacza to, że maszyna nic w tym czasie nie robiła więc dodajemy przerwę idle
if(czasAktualny < rozwiazanieMaszyna1.get(nrPozycji).getCzasStartu()) {
czasTrwania = rozwiazanieMaszyna1.get(nrPozycji).getCzasStartu() - czasAktualny;
rozwiazanieMaszyna1.add(nrPozycji, new Element(
"idle" + (liczbaPrzerwIdleM1 + liczbaPrzerwIdleM2) + "_M2",
-2,
czasAktualny,
czasTrwania));
liczbaPrzerwIdleM2++;
czasPrzerwIdleM2 += czasTrwania;
czasAktualny += czasTrwania;
nrPozycji++;
continue;
}
czasAktualny += rozwiazanieMaszyna1.get(nrPozycji).getCzasOperacji();
nrPozycji++;
}
}
}
/**
* Komparator do ustawiania przerwań - najpierw przerwania na pierwszej maszynie po kolei, potem te na drugiej
*/
class KomparatorCzasStartuPrzerwania implements Comparator<Przerwanie> {
@Override
public int compare(Przerwanie p1, Przerwanie p2) {
if(p1.getNumerMaszyny() == p2.getNumerMaszyny())
return p1.getCzasStartu() - p2.getCzasStartu();
else return p1.getNumerMaszyny() - p2.getNumerMaszyny();
}
}
| true
|
c383707705673d888a70da731d5072a458ec5535
|
Java
|
red-projects/mediateca-media-server
|
/src/main/java/com/red_projects/mediateca/services/user/OpenUserService.java
|
UTF-8
| 5,269
| 2.296875
| 2
|
[] |
no_license
|
package com.red_projects.mediateca.services.user;
import com.red_projects.mediateca.communication.requests.RegisterRequest;
import com.red_projects.mediateca.entities.utils.TokenAction;
import com.red_projects.mediateca.entities.utils.UserStatus;
import com.red_projects.mediateca.repositories.UserRepository;
import com.red_projects.mediateca.entities.Token;
import com.red_projects.mediateca.entities.utils.AccessLevel;
import com.red_projects.mediateca.entities.User;
import com.red_projects.mediateca.security.PasswordRequirements;
import com.red_projects.mediateca.security.PasswordValidator;
import com.red_projects.mediateca.utils.AuthStatus;
import com.red_projects.mediateca.utils.SecurityUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Optional;
@Service
public class OpenUserService {
private final UserRepository userRepository;
@Autowired
public OpenUserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
public boolean isUsernameUnique(String username) {
Optional<User> user = userRepository.findByUsername(username);
return user.isEmpty();
}
public boolean isValidPassword(String password) {
// password
PasswordRequirements requirements = SecurityUtil.passwordRequirements;
PasswordValidator passwordValidator = new PasswordValidator(requirements, password);
return passwordValidator.passesRequirements();
}
public boolean createUser(RegisterRequest userInfo) {
User user = new User(userInfo.getFirstName(), userInfo.getLastName());
user.setEmailAddress(userInfo.getEmailAddress());
user.setUsername(userInfo.getUsername());
user.setStatus(UserStatus.UNVERIFIED.name());
user.setPassword(SecurityUtil.bCryptEncode(userInfo.getPassword()));
// generate verification code
String passcode = SecurityUtil.generateVerificationCode();
Token token = new Token(TokenAction.VERIFY_EMAIL, user.getId());
token.setEncryptedCode(SecurityUtil.bCryptEncode(passcode));
// if first user created make as admin
if (userRepository.countByAccessLevel(AccessLevel.OWNER.name()) < 1) {
user.setAccessLevel(AccessLevel.OWNER.name());
}
// insert
userRepository.save(user);
// queue verification email
System.out.println("VerificationCode: " + SecurityUtil.base64Encode(passcode));
// TODO: CREATE EMAIL REQUESTER
return true;
}
public AuthStatus authenticateUser(String username, String password) {
Optional<User> opUser = userRepository.findByUsername(username);
if (opUser.isPresent()) {
User user = opUser.get();
// check if user has is not unverified or deactivated
if (user.getStatus().contentEquals(UserStatus.ACTIVE.toString())) {
boolean matches = SecurityUtil.bCryptCompare(password, user.getPassword());
if (matches) {
if (user.getAccessLevel().contentEquals(AccessLevel.ADMIN.name())) return AuthStatus.SUCCESS_ADMIN;
else if (user.getAccessLevel().contentEquals(AccessLevel.OWNER.name())) return AuthStatus.SUCCESS_OWNER;
else return AuthStatus.SUCCESS;
}
else
return AuthStatus.FAILED;
}
return AuthStatus.UNVERIFIED_DEACTIVATED;
}
return AuthStatus.FAILED;
}
public AuthStatus verifyUserEmail(String email, String verificationCode) {
if (verificationCode.length() > 0) {
ArrayList<User> users = userRepository.findByEmailAddress(email);
for (User user : users) {
boolean matches = SecurityUtil.bCryptCompare(verificationCode, user.getVerificationCode());
if (matches) {
user.setStatus(UserStatus.ACTIVE.name());
user.setVerificationCode(null);
userRepository.save(user);
return AuthStatus.SUCCESS;
}
}
}
return AuthStatus.FAILED;
}
public String authenticateCredentialsForEmail(String username) {
Optional<User> opUser = userRepository.findByUsername(username);
if (opUser.isPresent()) {
User user = opUser.get();
// check if user has is not unverified or deactivated
if (user.getStatus().contentEquals(UserStatus.ACTIVE.name())) {
return user.getEmailAddress();
}
return AuthStatus.UNVERIFIED_DEACTIVATED.name();
}
return AuthStatus.FAILED.name();
}
public boolean resetPasswordRequest(String username) {
Optional<User> optionalUser = userRepository.findByUsername(username);
if (optionalUser.isPresent()) {
User user = optionalUser.get();
// check if user
if (user.getStatus().contentEquals(UserStatus.ACTIVE.name())) {
// submit reset password email request
}
}
return false;
}
}
| true
|
2d01aae04ca7a359b54058cf157a9902bc05abff
|
Java
|
nerydlg/dailyCodingProblems
|
/src/test/java/com/nerydlg/daily/coding/problems/medium/ConsecutiveSubArraysTest.java
|
UTF-8
| 1,767
| 3.125
| 3
|
[] |
no_license
|
package com.nerydlg.daily.coding.problems.medium;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.stream.Collectors;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
class ConsecutiveSubArraysTest {
ConsecutiveSubArrays subject;
@Test
void TestEasy() {
// GIVEN
subject = new ConsecutiveSubArrays();
int[] input = { 3, 4, 1, 6, 2 };
/**
* i = 0 -> [3]
* i = 1 -> [3,4] [4,1] [4]
* i = 2 -> [1]
* i = 3 -> [3, 4, 1, 6] [4, 1, 6][1,6][6][6,2]
* i = 4 -> [2]
**/
int[] expected = { 1, 3, 1, 5, 1 };
// WHEN
int[] actual = subject.countSubarrays(input);
// THEN
assertArrayEquals(expected, actual);
}
@Test
void TestNormal() {
// GIVEN
subject = new ConsecutiveSubArrays();
int[] input = { 1, 2, 8, 5, 3 };
int[] expected = { 1, 2, 5, 2, 1 };
// WHEN
int[] actual = subject.countSubarrays(input);
// THEN
assertArrayEquals(expected, actual);
}
@Test
void TestNormal_1() {
// GIVEN
subject = new ConsecutiveSubArrays();
int[] input = { 5,4,1,2,6,3,7 };
int[] expected = { 4,3,1,2,6,1,7 };
// WHEN
int[] actual = subject.countSubarrays(input);
// THEN
assertArrayEquals(expected, actual);
}
@Test
void testTwo() {
// GIVEN
subject = new ConsecutiveSubArrays();
int[] input = { 2, 4, 7, 1, 5, 3 };
int[] expected = { 1, 2, 6, 1, 3, 1 };
// WHEN
int[] actual = subject.countSubarrays(input);
// THEN
assertArrayEquals(expected, actual);
}
}
| true
|
0868ffe055e3cf104eeb4d14c8f32f38ad943e44
|
Java
|
AgustinBettati/ayed
|
/src/main/metroviasAgustin/Simulation.java
|
UTF-8
| 1,275
| 3.03125
| 3
|
[] |
no_license
|
package main.metroviasAgustin;
import java.util.Scanner;
/**
* @author Agustin Bettati
* @version 1.0
*
* This class simulates a full day of work of the metrovia service
*/
public class Simulation {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter amount of windows (from 3 to 10): ");
int amountOfWindows = scanner.nextInt();
Service metrovia = new Service(amountOfWindows);
for(int i = 0; i <= 57600; i+= 10){
if(i < 57570) {
metrovia.newCicle(i);
}
else{
metrovia.lastCicles(i);
}
}
System.out.println("-- General statistics for each window -- \n");
for(int i = 0; i < amountOfWindows; i++){
System.out.println("Window number " + (i+1));
System.out.println("Average waited time: " + String.format("%.2f", metrovia.getAverageTimeWaited(i)));
System.out.println("Amount of money collected: " + String.format("%.2f", metrovia.getAmountOfMoneyCollected(i)));
System.out.println("Amount of free time: " + metrovia.getAmountOfFreeTime(i));
System.out.println(" ----------");
}
}
}
| true
|
4ced1b3fc6bf671917cbb289bd9c0161f0204fc2
|
Java
|
BerndMuller/jsf-im-detail
|
/src/main/java/de/jsfpraxis/detail/vc/EmailValidator.java
|
UTF-8
| 807
| 2.28125
| 2
|
[
"MIT"
] |
permissive
|
package de.jsfpraxis.detail.vc;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;
@FacesValidator("emailValidator")
public class EmailValidator implements Validator<String> {
@Override
public void validate(FacesContext context, UIComponent component, String email) throws ValidatorException {
if (email == null || email.isEmpty()) {
return; // sollte @NotNull oder RequiredValidator pruefen
}
if (! email.matches(".+@.+\\..+")) {
throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Fehlerhafte E-Mail-Syntax", "Fehlerhafte E-Mail-Syntax"));
}
}
}
| true
|
bc1281d40d00188258f8223f545e98400a2916e2
|
Java
|
pengju1218/decompiled-apk
|
/src/main/java/androidx/constraintlayout/solver/widgets/Guideline.java
|
UTF-8
| 13,067
| 2.109375
| 2
|
[] |
no_license
|
package androidx.constraintlayout.solver.widgets;
import androidx.constraintlayout.solver.LinearSystem;
import androidx.constraintlayout.solver.SolverVariable;
import androidx.constraintlayout.solver.widgets.ConstraintAnchor;
import androidx.constraintlayout.solver.widgets.ConstraintWidget;
import java.util.ArrayList;
public class Guideline extends ConstraintWidget {
public static final int HORIZONTAL = 0;
public static final int RELATIVE_BEGIN = 1;
public static final int RELATIVE_END = 2;
public static final int RELATIVE_PERCENT = 0;
public static final int RELATIVE_UNKNWON = -1;
public static final int VERTICAL = 1;
protected float Z = -1.0f;
protected int aa = -1;
protected int ab = -1;
private ConstraintAnchor mAnchor = this.q;
private Rectangle mHead;
private int mHeadSize;
private boolean mIsPositionRelaxed;
private int mMinimumPosition;
private int mOrientation;
public Guideline() {
this.mOrientation = 0;
this.mIsPositionRelaxed = false;
this.mMinimumPosition = 0;
this.mHead = new Rectangle();
this.mHeadSize = 8;
this.y.clear();
this.y.add(this.mAnchor);
int length = this.x.length;
for (int i = 0; i < length; i++) {
this.x[i] = this.mAnchor;
}
}
public void addToSolver(LinearSystem linearSystem) {
ConstraintWidgetContainer constraintWidgetContainer = (ConstraintWidgetContainer) getParent();
if (constraintWidgetContainer != null) {
ConstraintAnchor anchor = constraintWidgetContainer.getAnchor(ConstraintAnchor.Type.LEFT);
ConstraintAnchor anchor2 = constraintWidgetContainer.getAnchor(ConstraintAnchor.Type.RIGHT);
boolean z = this.A != null && this.A.z[0] == ConstraintWidget.DimensionBehaviour.WRAP_CONTENT;
if (this.mOrientation == 0) {
anchor = constraintWidgetContainer.getAnchor(ConstraintAnchor.Type.TOP);
anchor2 = constraintWidgetContainer.getAnchor(ConstraintAnchor.Type.BOTTOM);
z = this.A != null && this.A.z[1] == ConstraintWidget.DimensionBehaviour.WRAP_CONTENT;
}
if (this.aa != -1) {
SolverVariable createObjectVariable = linearSystem.createObjectVariable(this.mAnchor);
linearSystem.addEquality(createObjectVariable, linearSystem.createObjectVariable(anchor), this.aa, 6);
if (z) {
linearSystem.addGreaterThan(linearSystem.createObjectVariable(anchor2), createObjectVariable, 0, 5);
}
} else if (this.ab != -1) {
SolverVariable createObjectVariable2 = linearSystem.createObjectVariable(this.mAnchor);
SolverVariable createObjectVariable3 = linearSystem.createObjectVariable(anchor2);
linearSystem.addEquality(createObjectVariable2, createObjectVariable3, -this.ab, 6);
if (z) {
linearSystem.addGreaterThan(createObjectVariable2, linearSystem.createObjectVariable(anchor), 0, 5);
linearSystem.addGreaterThan(createObjectVariable3, createObjectVariable2, 0, 5);
}
} else if (this.Z != -1.0f) {
linearSystem.addConstraint(LinearSystem.createRowDimensionPercent(linearSystem, linearSystem.createObjectVariable(this.mAnchor), linearSystem.createObjectVariable(anchor), linearSystem.createObjectVariable(anchor2), this.Z, this.mIsPositionRelaxed));
}
}
}
public boolean allowedInBarrier() {
return true;
}
public void analyze(int i) {
ConstraintAnchor constraintAnchor;
ResolutionAnchor resolutionAnchor;
int i2;
ConstraintAnchor constraintAnchor2;
ResolutionAnchor resolutionAnchor2;
ResolutionAnchor resolutionNode;
int i3;
ConstraintAnchor constraintAnchor3;
ResolutionAnchor resolutionNode2;
ConstraintWidget parent = getParent();
if (parent != null) {
if (getOrientation() == 1) {
this.q.getResolutionNode().dependsOn(1, parent.q.getResolutionNode(), 0);
this.s.getResolutionNode().dependsOn(1, parent.q.getResolutionNode(), 0);
if (this.aa != -1) {
this.p.getResolutionNode().dependsOn(1, parent.p.getResolutionNode(), this.aa);
resolutionAnchor2 = this.r.getResolutionNode();
constraintAnchor3 = parent.p;
} else if (this.ab != -1) {
this.p.getResolutionNode().dependsOn(1, parent.r.getResolutionNode(), -this.ab);
resolutionNode2 = this.r.getResolutionNode();
constraintAnchor2 = parent.r;
resolutionNode = constraintAnchor2.getResolutionNode();
i3 = -this.ab;
resolutionAnchor2.dependsOn(1, resolutionNode, i3);
} else if (this.Z != -1.0f && parent.getHorizontalDimensionBehaviour() == ConstraintWidget.DimensionBehaviour.FIXED) {
i2 = (int) (((float) parent.B) * this.Z);
this.p.getResolutionNode().dependsOn(1, parent.p.getResolutionNode(), i2);
resolutionAnchor = this.r.getResolutionNode();
constraintAnchor = parent.p;
resolutionAnchor.dependsOn(1, constraintAnchor.getResolutionNode(), i2);
return;
} else {
return;
}
} else {
this.p.getResolutionNode().dependsOn(1, parent.p.getResolutionNode(), 0);
this.r.getResolutionNode().dependsOn(1, parent.p.getResolutionNode(), 0);
if (this.aa != -1) {
this.q.getResolutionNode().dependsOn(1, parent.q.getResolutionNode(), this.aa);
resolutionAnchor2 = this.s.getResolutionNode();
constraintAnchor3 = parent.q;
} else if (this.ab != -1) {
this.q.getResolutionNode().dependsOn(1, parent.s.getResolutionNode(), -this.ab);
resolutionNode2 = this.s.getResolutionNode();
constraintAnchor2 = parent.s;
resolutionNode = constraintAnchor2.getResolutionNode();
i3 = -this.ab;
resolutionAnchor2.dependsOn(1, resolutionNode, i3);
} else if (this.Z != -1.0f && parent.getVerticalDimensionBehaviour() == ConstraintWidget.DimensionBehaviour.FIXED) {
i2 = (int) (((float) parent.C) * this.Z);
this.q.getResolutionNode().dependsOn(1, parent.q.getResolutionNode(), i2);
resolutionAnchor = this.s.getResolutionNode();
constraintAnchor = parent.q;
resolutionAnchor.dependsOn(1, constraintAnchor.getResolutionNode(), i2);
return;
} else {
return;
}
}
resolutionNode = constraintAnchor3.getResolutionNode();
i3 = this.aa;
resolutionAnchor2.dependsOn(1, resolutionNode, i3);
}
}
/* access modifiers changed from: package-private */
public void c() {
float x = ((float) getX()) / ((float) getParent().getWidth());
if (this.mOrientation == 0) {
x = ((float) getY()) / ((float) getParent().getHeight());
}
setGuidePercent(x);
}
public void cyclePosition() {
if (this.aa != -1) {
c();
} else if (this.Z != -1.0f) {
e();
} else if (this.ab != -1) {
d();
}
}
/* access modifiers changed from: package-private */
public void d() {
int x = getX();
if (this.mOrientation == 0) {
x = getY();
}
setGuideBegin(x);
}
/* access modifiers changed from: package-private */
public void e() {
int width = getParent().getWidth() - getX();
if (this.mOrientation == 0) {
width = getParent().getHeight() - getY();
}
setGuideEnd(width);
}
public ConstraintAnchor getAnchor() {
return this.mAnchor;
}
public ConstraintAnchor getAnchor(ConstraintAnchor.Type type) {
switch (type) {
case LEFT:
case RIGHT:
if (this.mOrientation == 1) {
return this.mAnchor;
}
break;
case TOP:
case BOTTOM:
if (this.mOrientation == 0) {
return this.mAnchor;
}
break;
case BASELINE:
case CENTER:
case CENTER_X:
case CENTER_Y:
case NONE:
return null;
}
throw new AssertionError(type.name());
}
public ArrayList<ConstraintAnchor> getAnchors() {
return this.y;
}
public Rectangle getHead() {
Rectangle rectangle = this.mHead;
int drawX = getDrawX() - this.mHeadSize;
int drawY = getDrawY();
int i = this.mHeadSize;
rectangle.setBounds(drawX, drawY - (i * 2), i * 2, i * 2);
if (getOrientation() == 0) {
Rectangle rectangle2 = this.mHead;
int drawX2 = getDrawX() - (this.mHeadSize * 2);
int drawY2 = getDrawY();
int i2 = this.mHeadSize;
rectangle2.setBounds(drawX2, drawY2 - i2, i2 * 2, i2 * 2);
}
return this.mHead;
}
public int getOrientation() {
return this.mOrientation;
}
public int getRelativeBegin() {
return this.aa;
}
public int getRelativeBehaviour() {
if (this.Z != -1.0f) {
return 0;
}
if (this.aa != -1) {
return 1;
}
return this.ab != -1 ? 2 : -1;
}
public int getRelativeEnd() {
return this.ab;
}
public float getRelativePercent() {
return this.Z;
}
public String getType() {
return "Guideline";
}
public void setDrawOrigin(int i, int i2) {
int i3;
float f;
if (this.mOrientation == 1) {
int i4 = i - this.H;
if (this.aa != -1) {
setGuideBegin(i4);
return;
} else if (this.ab != -1) {
setGuideEnd(getParent().getWidth() - i4);
return;
} else if (this.Z != -1.0f) {
f = (float) i4;
i3 = getParent().getWidth();
} else {
return;
}
} else {
int i5 = i2 - this.I;
if (this.aa != -1) {
setGuideBegin(i5);
return;
} else if (this.ab != -1) {
setGuideEnd(getParent().getHeight() - i5);
return;
} else if (this.Z != -1.0f) {
f = (float) i5;
i3 = getParent().getHeight();
} else {
return;
}
}
setGuidePercent(f / ((float) i3));
}
public void setGuideBegin(int i) {
if (i > -1) {
this.Z = -1.0f;
this.aa = i;
this.ab = -1;
}
}
public void setGuideEnd(int i) {
if (i > -1) {
this.Z = -1.0f;
this.aa = -1;
this.ab = i;
}
}
public void setGuidePercent(float f) {
if (f > -1.0f) {
this.Z = f;
this.aa = -1;
this.ab = -1;
}
}
public void setGuidePercent(int i) {
setGuidePercent(((float) i) / 100.0f);
}
public void setMinimumPosition(int i) {
this.mMinimumPosition = i;
}
public void setOrientation(int i) {
if (this.mOrientation != i) {
this.mOrientation = i;
this.y.clear();
this.mAnchor = this.mOrientation == 1 ? this.p : this.q;
this.y.add(this.mAnchor);
int length = this.x.length;
for (int i2 = 0; i2 < length; i2++) {
this.x[i2] = this.mAnchor;
}
}
}
public void setPositionRelaxed(boolean z) {
if (this.mIsPositionRelaxed != z) {
this.mIsPositionRelaxed = z;
}
}
public void updateFromSolver(LinearSystem linearSystem) {
if (getParent() != null) {
int objectVariableValue = linearSystem.getObjectVariableValue(this.mAnchor);
if (this.mOrientation == 1) {
setX(objectVariableValue);
setY(0);
setHeight(getParent().getHeight());
setWidth(0);
return;
}
setX(0);
setY(objectVariableValue);
setWidth(getParent().getWidth());
setHeight(0);
}
}
}
| true
|
03d81d492a34eae0f98ca33f2b9e27550df246b0
|
Java
|
Yuriel849/JSP
|
/src/study/QueryServlet.java
|
UTF-8
| 2,196
| 3.375
| 3
|
[] |
no_license
|
/* Shows on screen the id and pw parameters from the request,
* also shows the value of the count variable on this servlet file,
* IMPORTANT a servlet is reused, meaning the value of count is NOT reinitialized!
*/
package study;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class QueryServlet
*/
@WebServlet("/QueryServlet")
public class QueryServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public QueryServlet() {
super();
// TODO Auto-generated constructor stub
}
// 인스턴스 변수 (iv) 선언
int count = 0;
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 요청 시 넘어온 값을 읽는다.
String id = request.getParameter("id");
String pw = request.getParameter("pw");
// 응답을 작성한다.
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE html>");
out.println("<html lang=\"en\">");
out.println("<head>");
out.println("</head>");
out.println("<body>");
out.println(" <h1>Hello, "+id+".</h1>");
out.println(" <h1>Your password is "+pw+".</h1>");
out.println(" <h1>The count is "+ ++count +".</h1>");
// servlet은 1회용이 아니다! 그렇기 때문에 iv인 count가 초기화되지 않는다!
// servlet에서는 iv 사용하지 말고 lv 쓰거나, iv 쓰더라도 동기화처리가 필수!
out.println("</body>");
out.println("</html>");
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
| true
|
0b1d4e90fd6e4a6041cf750713e9400d4cfd1a94
|
Java
|
adgrigorov/Java
|
/Objects&Classes Exercises/9. RawData/src/com/company/Main.java
|
UTF-8
| 2,350
| 3.484375
| 3
|
[] |
no_license
|
package com.company;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int numberOfCars = Integer.parseInt(sc.nextLine());
ArrayList<Car> cars = new ArrayList<>();
for (int i = 0; i < numberOfCars; i++) {
String[] input = sc.nextLine().split("\\s+");
String carModel = input[0];
int engineSpeed = Integer.parseInt(input[1]);
int enginePower = Integer.parseInt(input[2]);
int cargoWeight = Integer.parseInt(input[3]);
String cargoType = input[4];
ArrayList<Tire> tires = new ArrayList<>();
for (int inputElement = 5; inputElement < 12; inputElement+=2) {
int nextInputElement = inputElement + 1;
double tirePressure = Double.parseDouble(input[inputElement]);
int tireAge = Integer.parseInt(input[nextInputElement]);
Tire tire = new Tire(tirePressure, tireAge);
tires.add(tire);
}
Engine engine = new Engine(engineSpeed, enginePower);
Cargo cargo = new Cargo(cargoWeight, cargoType);
Car car = new Car(carModel, engine, cargo, tires);
cars.add(car);
}
String carType = sc.nextLine();
List<String> model = new ArrayList<>();
if (carType.equals("fragile")) {
for (int i = 0; i < cars.size(); i++) {
if (cars.get(i).getCargo().getType().equals("fragile")) {
if (cars.get(i).getTires().get(i).getPressure() < 1) {
model.add(cars.get(i).getModel());
}
}
}
model.forEach(System.out::println);
}
else if (carType.equals("flammable")) {
for (int i = 0; i < cars.size(); i++) {
if (cars.get(i).getCargo().getType().equals("flammable")) {
if (cars.get(i).getEngine().getPower() > 250) {
model.add(cars.get(i).getModel());
}
}
}
model.forEach(System.out::println);
}
}
}
| true
|
d0575ba737b4f0dc232515f96d7a01d625d1b8dd
|
Java
|
Open-Succinct-Community/swf-all
|
/swf/src/main/java/com/venky/swf/plugins/background/core/CompositeTask.java
|
UTF-8
| 2,666
| 2.625
| 3
|
[
"MIT"
] |
permissive
|
package com.venky.swf.plugins.background.core;
import com.venky.core.util.MultiException;
import com.venky.swf.db.Database;
import com.venky.swf.db.Transaction;
import java.util.Iterator;
import java.util.LinkedList;
public class CompositeTask implements Task {
private final LinkedList<Task> tasks ;
private static final long serialVersionUID = -6287257141086371584L;
private boolean splitTasksOnException = false;
public CompositeTask(){
this.tasks = new LinkedList<>();
}
private Priority priority = Priority.LOW;
public CompositeTask(Task...tasks ) {
this(false,tasks);
}
public CompositeTask(boolean splitTasksOnException , Task...tasks ) {
this.splitTasksOnException = splitTasksOnException;
this.tasks = new LinkedList<>();
add(tasks);
}
public void add(Task... tasks){
for (Task t : tasks){
this.tasks.add(t);
if (priority.getValue() > t.getTaskPriority().getValue()){ //Lower the value higher the priority.
priority = t.getTaskPriority();
}
canExecuteRemotely = canExecuteRemotely && t.canExecuteRemotely();
}
}
private boolean canExecuteRemotely = true;
@Override
public boolean canExecuteRemotely(){
return canExecuteRemotely;
}
@Override
public Priority getTaskPriority(){
return priority;
}
@Override
public void execute() {
Transaction parentTxn = Database.getInstance().getTransactionManager().createTransaction();
try {
MultiException multiException = new MultiException();
for (Iterator<Task> taskIterator = tasks.iterator(); taskIterator.hasNext() ; ) {
Task task = taskIterator.next();
Transaction txn = Database.getInstance().getTransactionManager().createTransaction();
try {
task.execute();
txn.commit();
taskIterator.remove();
}catch (Exception ex){
txn.rollback(ex);// Task not removed will be resubmitted if required.
multiException.add(ex);
}
}
if (!tasks.isEmpty()) {
if (splitTasksOnException){
TaskManager.instance().executeAsync(tasks,false); //Submit errored tasks for retry. // May throw serializable exception
}else {
throw multiException;
}
}
parentTxn.commit(); //Don't waste work done by successful tasks.
}catch ( Exception ex ) {
parentTxn.rollback(ex);
throw ex;
}
}
}
| true
|
e9d453d6c8325c34604c9532a0ac0bfcc8df198d
|
Java
|
Fafhner/Studia
|
/AZNU/micro-services/Courier/src/main/java/org/bp/courier/model/CourierTypes.java
|
UTF-8
| 637
| 2.421875
| 2
|
[] |
no_license
|
package org.bp.courier.model;
import java.util.ArrayList;
import java.util.List;
public class CourierTypes {
private static CourierTypes instance = new CourierTypes();
private List<String> types;
private CourierTypes() {
types = new ArrayList<>();
types.add("courier");
types.add("locker");
}
public static CourierTypes getInstance(){
if (instance == null)
instance = new CourierTypes();
return instance;
}
public List<String> getTypes() {
return types;
}
public void setTypes(List<String> types) {
this.types = types;
}
}
| true
|
c047724fc3c0e8b763319dda7e4d63d3eb01168a
|
Java
|
NickJoudrey/Assignment04-4U
|
/src/Game.java
|
UTF-8
| 4,868
| 3.390625
| 3
|
[] |
no_license
|
import java.awt.Color;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author joudn2217
*/
public class Game {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Board board = new Board(12, 12);
//create board
Dalek[] dalek = new Dalek[3];
//create an array of 3 daleks
for (int i = 0; i < dalek.length; i++) {
int randomR = (int) (Math.random() * 12);
int randomC = (int) (Math.random() * 12);
board.putPeg(Color.black, randomR, randomC);
dalek[i] = new Dalek(randomR, randomC);
}
//pick a random col and row between 0-11 and place a black peg there
//use the random coordinates to create a new dalek
int randomRDoc = (int) (Math.random() * 12);
int randomCDoc = (int) (Math.random() * 12);
Doctor doc = new Doctor(randomRDoc, randomCDoc);
board.putPeg(Color.green, randomRDoc, randomCDoc);
//pick a random col and row between 0-11, create a new doctor at those coordinates and place a green peg there
while (true) {
if (dalek[0].getCol() == dalek[1].getCol() && dalek[0].getRow() == dalek[1].getRow()) {
dalek[0].crash();
dalek[1].crash();
board.putPeg(Color.red, dalek[0].getRow(), dalek[0].getCol());
}
//if dalek 0 and dalek 1 are on the same coords make them crash and place a red peg
if (dalek[0].getCol() == dalek[2].getCol() && dalek[0].getRow() == dalek[2].getRow()) {
dalek[0].crash();
dalek[2].crash();
board.putPeg(Color.red, dalek[0].getRow(), dalek[0].getCol());
}
//if dalek 0 and dalek 2 are on the same coords make them crash and place a red peg
if (dalek[1].getCol() == dalek[2].getCol() && dalek[1].getRow() == dalek[2].getRow()) {
dalek[1].crash();
dalek[2].crash();
board.putPeg(Color.red, dalek[1].getRow(), dalek[1].getCol());
}
//if dalek 1 and dalek 2 are on the same coords make them crash and place a red peg
boolean lose = false;
//create boolean to allow for loops to crash the while loop
for (int i = 0; i < dalek.length; i++) {
if (doc.getRow() == dalek[i].getRow() && doc.getCol() == dalek[i].getCol()) {
board.putPeg(Color.yellow, doc.getRow(), doc.getCol());
board.displayMessage("You have been captured by a Dalek! You lose!");
lose = true;
}
}
if (lose) {
break;
}
//if the doctor is on the same coords of any of the dalek put a yellow peg at the coords tell the user they lost and set lose to true
for (int i = 0; i < dalek.length; i++) {
if (dalek[i].hasCrashed() == true && dalek[i].getRow() == doc.getRow() && dalek[i].getCol() == doc.getCol()) {
board.putPeg(Color.yellow, doc.getRow(), doc.getCol());
board.displayMessage("You have crashed into a pile of Dalek rubble! You lose!");
lose = true;
}
}
//if the doctor and 2 crashed daleks are on the set of coords
if (lose) {
break;
}
//break the while loop if the lose is true
if (dalek[0].hasCrashed() && dalek[1].hasCrashed() && dalek[2].hasCrashed()) {
board.displayMessage("All Dalek's have crashed! You win!");
break;
}
//if all daleks crash you win and break while loop
board.displayMessage("Please click the board to move the doctor");
Coordinate click = board.getClick();
int row = click.getRow();
int col = click.getCol();
board.removePeg(doc.getRow(), doc.getCol());
doc.move(row, col);
board.putPeg(Color.green, doc.getRow(), doc.getCol());
//get click from user and move doc using move method in doctor class
for (int i = 0; i < dalek.length; i++) {
board.removePeg(dalek[i].getRow(), dalek[i].getCol());
}
//delete all dalek pegs
for (int i = 0; i < dalek.length; i++) {
dalek[i].advanceTowards(doc);
board.putPeg(Color.black, dalek[i].getRow(), dalek[i].getCol());
//use the advance toward dalek method to make them advance
}
}
}
}
| true
|
33b686b15e04f96af4fa38a0dc6c45b4bf133a43
|
Java
|
urvishjarvis1/AndroidSdkFeature
|
/ScopedDirectoryAccessDemo/app/src/main/java/com/example/urvish/scopeddirectoryaccessdemo/MainActivity.java
|
UTF-8
| 3,813
| 2.234375
| 2
|
[] |
no_license
|
package com.example.urvish.scopeddirectoryaccessdemo;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.storage.StorageManager;
import android.os.storage.StorageVolume;
import android.provider.MediaStore;
import android.support.v4.provider.DocumentFile;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private static final int REQCODE = 1;
private static final String TAG =MainActivity.class.getSimpleName() ;
private StorageManager mStorageManager;
private StorageVolume mStoreVolume;
private Uri mUri;
private List<Uri> imgs;
private GridView gridView;
private GridViewAdapter mGridAdapter;
private ArrayList<Bitmap> bitmaps;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mStorageManager = (StorageManager) getSystemService(STORAGE_SERVICE);
if (mStorageManager != null) mStoreVolume = mStorageManager.getPrimaryStorageVolume();
Intent intent = mStoreVolume.createAccessIntent(Environment.DIRECTORY_PICTURES);
startActivityForResult(intent, REQCODE);
imgs=new ArrayList<>();
bitmaps=new ArrayList<>();
((Button)findViewById(R.id.button)).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = mStoreVolume.createAccessIntent(Environment.DIRECTORY_PICTURES);
startActivityForResult(intent, REQCODE);
}
});
}
private void getBitMaps() {
for(Uri uri:imgs){
try {
bitmaps.add(MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri));
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQCODE) {
if (resultCode == RESULT_OK) {
((Button)findViewById(R.id.button)).setEnabled(false);
((TextView) findViewById(R.id.status)).setVisibility(View.GONE);
DocumentFile folder=DocumentFile.fromTreeUri(this,data.getData());
Log.d(TAG, "onActivityResult: "+folder.isDirectory());
Log.d(TAG, "onActivityResult: "+folder.getName());
if(folder.getName().contains("Pictures")){
DocumentFile subFolder=folder.findFile("Screenshots");
if (subFolder.exists()){
for(DocumentFile file:subFolder.listFiles()){
if(!file.isDirectory())
imgs.add(file.getUri());
}
getBitMaps();
gridView=(GridView) findViewById(R.id.gridview);
mGridAdapter=new GridViewAdapter(this, bitmaps);
gridView.setAdapter(mGridAdapter);
}
}
} else {
((TextView) findViewById(R.id.status)).setVisibility(View.VISIBLE);
((TextView) findViewById(R.id.status)).setText("In oder to use this functionality you need to give the permission");
}
}
}
}
| true
|
4c43bd6b10f61d55f683244c43eb8567fe2b76a7
|
Java
|
tectronics/texttc
|
/src/opl/textc/Stop.java
|
WINDOWS-1255
| 7,919
| 2.5
| 2
|
[] |
no_license
|
package opl.textc;
import android.text.Html;
public class Stop {
private String stopId = ""; // XML: StopId
private String name = ""; // XML: stop title TODO: Change to title
private String code = ""; // derived from somewhere else
private String lon = "";
private String lat = "";
private String tag = "";
private String direction = ""; // w, e, n, s
private String stopTag = "";
private String customName = "";
private boolean usesPreciseStopCode;
private float distanceBetween;
private String directionDetailed = "";
private String infoFavouritesRouteDetailed = "";
public Stop() {
}
public Stop(String stopID, String name, String code) {
this.setStopId(stopID);
this.setName(name);
this.setCode(code);
}
public Stop(String stopId2, String name2, String code2, String lon2,
String lat2, String tag2, String direction2, String stopTag2,
String customName2) {
stopId = stopId2;
name = name2;
code = code2;
lon = lon2;
lat = lat2;
tag = tag2;
direction = direction2;
stopTag = stopTag2;
customName = customName2;
}
public void setStopId(String stopID) {
this.stopId = stopID;
}
public String getStopId() {
return stopId;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setCode(String code) {
this.code = code;
}
public String getCode() {
return code;
}
// TODO : PUT THIS IN UTIL PACKAGAE
public String toString() {
return getName();
}
public void setLon(String lon) {
this.lon = lon;
}
public String getLon() {
return lon;
}
public void setLat(String lat) {
this.lat = lat;
}
public String getLat() {
return lat;
}
public void setTag(String tag) {
this.tag = tag;
}
public String getTag() {
return tag;
}
public void setDirection(String direction) {
this.direction = direction;
}
public void setDirectionDetailed(String dirDetailed) {
this.directionDetailed = dirDetailed;
}
public String getDirection() {
return direction;
}
public Stop copy() {
Stop copy = new Stop();
copy.name = name;
copy.stopId = stopId;
copy.code = code;
copy.direction = direction;
copy.directionDetailed = directionDetailed;
copy.tag = tag;
copy.lon = lon;
copy.lat = lat;
copy.stopTag = stopTag;
return copy;
}
public void setStopTag(String stopTag) {
this.stopTag = stopTag;
}
public String getStopTag() {
return stopTag;
}
/**
* Finds any property that's null and sets it to empty string. TODO:
* complete this
*/
public void fixNullEntries() {
if (code == null)
code = "";
if (direction == null)
direction = "no direction";
if (stopId == null)
stopId = "";
if (name == null)
name = "";
if (lon == null)
lon = "";
if (lat == null)
lat = "";
if (tag == null)
tag = "";
if (direction == null)
direction = "";
if (directionDetailed == null)
directionDetailed = "";
if (stopTag == null)
stopTag = "";
}
public void setCustomName(String customName) {
this.customName = customName;
}
public String getCustomName() {
return customName;
}
public String getQuickInfo() {
return stopTag + " " + getDirectionShort() + " " + getName();
}
public String getLongInfo2() {
return "ROUTE: " + stopTag + "\n" + "DIRECTION: " + directionDetailed
+ "\n" + "STOP: " + name + "\n" + "SMS CODE: " + stopId + "\n";
}
public String getLongInfo() {
return stopTag + "\n" + directionDetailed + "\n" + name + "\n" + stopId
+ " (SMS code)\n";
}
public void setDistanceBetween(float distanceBetween) {
this.distanceBetween = distanceBetween;
}
public float getDistanceBetween() {
return distanceBetween;
}
public void setUsesPreciseStopCode(boolean parseBoolean) {
this.usesPreciseStopCode = parseBoolean;
}
public boolean isUsesPreciseStopCode() {
return usesPreciseStopCode;
}
public String getDirectionDetailed() {
return directionDetailed.length() == 0 ? direction
: this.directionDetailed.replace("towards", "to").replace(
"Station", "Stn");
}
public String getDirectionDetailedActual() {
return directionDetailed.length() == 0 ? direction
: this.directionDetailed;
}
public int getGeoPointLat() {
double lat = Double.parseDouble(this.lat);
return (int) (lat * 1e6);
}
public int getGeoPointLon() {
double lon = Double.parseDouble(this.lon);
return (int) (lon * 1e6);
}
public String getTextDelimitedFormat(String delim) {
return stopId + delim + name + delim + code + delim + lon + delim + lat
+ delim + tag + delim + direction + delim + stopTag + delim
+ customName + delim
// + distanceBetween + delim
+ String.valueOf(usesPreciseStopCode);
}
public static Stop arrayToStop(String[] arrayedFavStop) {
Stop newStop = new Stop();
newStop.setCode(arrayedFavStop[2]);
newStop.setCustomName(arrayedFavStop[8]);
newStop.setDirection(arrayedFavStop[6]);
newStop.setLat(arrayedFavStop[4]);
newStop.setLon(arrayedFavStop[3]);
newStop.setStopId(arrayedFavStop[0]);
newStop.setName(arrayedFavStop[1]);
newStop.setStopTag(arrayedFavStop[7]);
newStop.setTag(arrayedFavStop[5]);
newStop.setUsesPreciseStopCode(Boolean.parseBoolean(arrayedFavStop[9]));
return newStop;
}
public CharSequence getDirectionShort() {
try {
// String res = direction.substring(0, 1).toUpperCase();
// if (!res.equalsIgnoreCase("w")){
// return res;
// } else {
// return "w";
// }
return direction.substring(0, 1).toLowerCase();
} catch (Exception e) {
return "?";
}
}
public void setInfoFavouritesRouteDetailed(
String infoFavouritesRouteDetailed) {
this.infoFavouritesRouteDetailed = infoFavouritesRouteDetailed;
}
public CharSequence getRouteDetailed(boolean isSimple) {
if (isSimple)
return Html.fromHtml("<b>" + this.stopTag + "</b>");
if (infoFavouritesRouteDetailed == null
|| infoFavouritesRouteDetailed.length() == 0) {
String[] splitted = directionDetailed.split("-");
if (splitted.length == 2) {
infoFavouritesRouteDetailed = splitted[1].trim()
.replace("towards", "to").replace("Station", "Stn");
String[] splitRouteInfo = infoFavouritesRouteDetailed
.split(" ");
int lenRouteInfoArray = splitRouteInfo.length;
for (int i = 0; i < lenRouteInfoArray; i++) {
if (i == 0) {
infoFavouritesRouteDetailed = "<b>" + splitRouteInfo[i]
+ "</b><small>";
} else {
infoFavouritesRouteDetailed += " " + splitRouteInfo[i];
}
}
infoFavouritesRouteDetailed += "</small>";
} else {
return this.getStopTag();
}
}
return Html.fromHtml(infoFavouritesRouteDetailed);
}
public static String formatDirection(String rawDir, boolean keepDir) {
String res = "";
try {
String[] splitted = rawDir.split("-");
if (splitted.length == 2) {
res = keepDir ? splitted[0] : "";
res += splitted[1].trim().replace("towards", "to")
.replace("Station", "Stn");
String[] splitRouteInfo = res.split(" ");
int lenRouteInfoArray = splitRouteInfo.length;
for (int i = 0; i < lenRouteInfoArray; i++) {
if (i == 0) {
if (keepDir)
res = "<b>" + splitRouteInfo[i] + " ";
else
res = "<b>" + splitRouteInfo[i] + "</b><small>";
} else if (i == 1 && keepDir) {
res += "<b>" + splitRouteInfo[i] + "</b><small>";
} else {
res += " " + splitRouteInfo[i];
}
}
res += "</small>";
} else {
return rawDir;
}
} catch (Exception e) {
res = rawDir;
}
return res;
}
}
| true
|
46374200d6702bbe6fbb0719cf1133ee18a8d806
|
Java
|
Shreya546/java-project
|
/src/java_Qu16/java_Qu16.java
|
UTF-8
| 392
| 3.390625
| 3
|
[] |
no_license
|
package java_Qu16;
import java.util.Scanner;
public class java_Qu16 {
public static void main (String[]args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a number:");
int n = input.nextInt();
if(n % 2 == 0) {
System.out.println("The given number is even.");
}else
System.out.println("The given number is odd.");
input.close();
}
}
| true
|
33e9869c4466885b263fd141c0fa9962f73b327d
|
Java
|
alexandrecadan/Lista8.3_LivroAutor5AgoraVai
|
/src/lista8/pkg3_livroautor5agoravai/Lista83_LivroAutor5AgoraVai.java
|
UTF-8
| 6,920
| 2.90625
| 3
|
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package lista8.pkg3_livroautor5agoravai;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Scanner;
/**
*
* @author alexandre
*/
public class Lista83_LivroAutor5AgoraVai {
private AutorDAO autorDAO;
private LivroDAO livroDAO;
public Lista83_LivroAutor5AgoraVai() throws Exception {
autorDAO = new AutorDAO();
livroDAO = new LivroDAO();
}
public static void main(String args[]) throws Exception {
Lista83_LivroAutor5AgoraVai main = new Lista83_LivroAutor5AgoraVai();
String opcao = "";
while (true) {
try {
System.out.println("Escolha uma das opções e tecle <ENTER>: ");
System.out.println(" 1 - Incluir Autor");
System.out.println(" 2 - Incluir Livro");
System.out.println(" 3 - Listar Autores");
System.out.println(" 4 - Listar Livro com autores");
System.out.println(" 5 - Listar Autores de um livro");
System.out.println(" 6 - Listar Livros de um autor");
System.out.println(" 7 - Sair");
Scanner sc = new Scanner(System.in, "ISO-8859-1");
opcao = sc.nextLine();
switch (opcao) {
case "1":
main.incluirAutor();
break;
case "2":
main.incluirLivro();
break;
case "3":
main.listarAutores();
break;
case "4":
main.listarLivroComAutores();
break;
case "5":
main.lerAutores();
break;
case "6":
main.lerLivro();
break;
default:
System.out.println("Opção inválida.");
break;
}
if (opcao.equals("7")) {
break;
}
} catch (Exception ex) {
System.out.println("Falha na operação. Mensagem=" + ex.getMessage());
//ex.printStackTrace();
}
}
}
public void incluirAutor() {
System.out.print("Digite o nome do autor:");
Scanner sc = new Scanner(System.in, "ISO-8859-1");
String nome = sc.nextLine();
//Autor autor = new Autor(nome);
int numLivros = 1;
List<Livro> listaLivros = new ArrayList();
int idLivro;
do {
try {
Scanner sc3 = new Scanner(System.in);
System.out.print("ID Livro " + numLivros + ":");
idLivro = sc3.nextInt();
if (idLivro == -1){
break;
}
Livro livro = livroDAO.consultarLivro(idLivro);
if (livro != null) {
listaLivros.add(livro);
numLivros++;
} else {
System.out.println("Livro não existe!");
}
} catch (Exception ex) {
ex.printStackTrace();
System.out.println("ID livro não é inteiro ou inválido!");
}
} while (true);
Autor autor = new Autor(nome, listaLivros);
autorDAO.inserirAutor(autor);
}
public void incluirLivro() {
System.out.print("Digite o título do livro:");
Scanner sc = new Scanner(System.in, "ISO-8859-1");
String titulo = sc.nextLine();
int numAutores = 1;
List<Autor> listaAutores = new ArrayList();
int idAutor;
do {
try {
Scanner sc2 = new Scanner(System.in, "ISO-8859-1");
System.out.print("ID Autor " + numAutores + ":");
idAutor = sc2.nextInt();
if (idAutor == -1) {
break;
}
Autor autor = autorDAO.consultarAutor(idAutor);
if (autor != null) {
listaAutores.add(autor);
numAutores++;
} else {
System.out.println("Autor não existe!");
}
} catch (Exception ex) {
System.out.println("ID autor não é inteiro ou inválido!");
}
} while (true);
Livro livro = new Livro(titulo, listaAutores);
livroDAO.inserirLivro(livro);
}
public void listarAutores() throws Exception {
List<Autor> listaAutores = autorDAO.listarAutores();
Collections.sort(listaAutores, new Comparator<Autor>() {
public int compare(Autor arg0, Autor arg1) {
return arg0.getNome().compareToIgnoreCase(arg1.getNome());
}
});
System.out.println("ID\tNOME");
for (Autor autor : listaAutores) {
System.out.println(autor.getId() + " \t" + autor.getNome());
}
}
public void listarLivroComAutores() throws Exception {
List<Livro> listaLivros = livroDAO.listarLivroComAutores();
Collections.sort(listaLivros, new Comparator<Livro>() {
public int compare(Livro arg0, Livro arg1) {
String titulo = arg0.getTitulo();
int i = titulo.compareToIgnoreCase(arg1.getTitulo());
return i;
}
});
System.out.println("ID\tTitulo do Livro\tAutores");
for (Livro livro : listaLivros) {
System.out.print(livro.getId() + "\t" + livro.getTitulo() + "\t");
for (Autor autor : livro.getAutores()) {
System.out.print(autor.getNome() + ";");
}
System.out.print("\n");
}
}
//CASE 5
public void lerAutores() throws Exception {
System.out.println("Digite o id do livro");
Scanner sc = new Scanner(System.in);
int id = sc.nextInt();
Connection con = ConnectionFactory.getConnection();
for (Autor lista : LivroDAO.lerAutores(id, con)) {
System.out.println(lista.getNome());
}
}
//CASE 6
public void lerLivro() throws Exception {
System.out.println("Digite o id do autor");
Scanner sc = new Scanner(System.in);
int id = sc.nextInt();
Connection con = ConnectionFactory.getConnection();
for (Livro lista : AutorDAO.lerLivro(id, con)) {
System.out.println(lista.getTitulo());
}
}
}
| true
|
bdc30f6fb00c59d998166400673c01451e8fe3dc
|
Java
|
LanceDai/learn
|
/design_pattern/Decorator_pattern/src/main/java/StarbuzzCoffee/Espresso.java
|
UTF-8
| 205
| 2.5625
| 3
|
[] |
no_license
|
package StarbuzzCoffee;
public class Espresso extends Beverage {
public Espresso() {
setDescription("StarbuzzCoffee.Espresso");
}
public double cost() {
return 1.99;
}
}
| true
|
644e21b88be23920e1dbc5194df917d24b6a47b9
|
Java
|
JosephArbelaez/1802-banking-JosephArbelaez
|
/src/main/java/com/revature/Main.java
|
UTF-8
| 1,391
| 3.09375
| 3
|
[] |
no_license
|
package com.revature;
import java.util.List;
import java.util.Scanner;
import com.revature.controller.Database;
import com.revature.controller.Login;
import com.revature.controller.Transactions;
import com.revature.exception.InputException;
import com.revature.exception.LoginException;
import com.revature.model.BankMember;
/**
* Create an instance of your controller and launch your application.
*
* Try not to have any logic at all on this class.
*/
public class Main {
public static void main(String[] args) throws LoginException, InputException {
// Variables
Scanner scanner = new Scanner(System.in);
int custID;
// Ask the user if they have an account.
String c = Login.createAccount();
/*
* Great! If they said yes then they continue, if
* no, they have to create an account.
*/
if (c.contains("n")){
Login.newAccount();
}
// Either way they have to log in.
try {
custID = Login.login();
} catch (LoginException e) {
throw new LoginException("Unable to login.");
}
// The customer selects an transaction option.
int d = Transactions.option();
// Now to the money, honey!
switch (d){
case 1:
Transactions.withdrawl(custID);
break;
case 2:
Transactions.deposit(custID);
break;
case 3:
Transactions.viewBalance(custID);
break;
case 4:
Database.selectAll(custID);
}
System.exit(0);
}
}
| true
|
1309b0f4107d3a5b4eda90c80e3f21e3f0d77539
|
Java
|
idok/scss-lint-plugin
|
/intellij-common/src/main/java/com/wix/annotator/AnnotatorUtils.java
|
UTF-8
| 1,531
| 1.945313
| 2
|
[] |
no_license
|
package com.wix.annotator;
import com.intellij.codeInsight.daemon.impl.HighlightInfoType;
import com.intellij.codeInsight.daemon.impl.SeverityRegistrar;
import com.intellij.lang.annotation.HighlightSeverity;
import com.intellij.openapi.editor.colors.EditorColorsManager;
import com.intellij.openapi.editor.colors.EditorColorsScheme;
import com.intellij.openapi.editor.colors.TextAttributesKey;
import com.intellij.openapi.editor.markup.TextAttributes;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public final class AnnotatorUtils {
private AnnotatorUtils() {
}
@NotNull
public static TextAttributes getTextAttributes(@Nullable EditorColorsScheme editorColorsScheme, @NotNull SeverityRegistrar severityRegistrar, @NotNull HighlightSeverity severity) {
TextAttributes textAttributes = severityRegistrar.getTextAttributesBySeverity(severity);
if (textAttributes != null) {
return textAttributes;
}
EditorColorsScheme colorsScheme = getColorsScheme(editorColorsScheme);
HighlightInfoType.HighlightInfoTypeImpl infoType = severityRegistrar.getHighlightInfoTypeBySeverity(severity);
TextAttributesKey key = infoType.getAttributesKey();
return colorsScheme.getAttributes(key);
}
@NotNull
private static EditorColorsScheme getColorsScheme(@Nullable EditorColorsScheme customScheme) {
return customScheme == null ? EditorColorsManager.getInstance().getGlobalScheme() : customScheme;
}
}
| true
|
3c87ebd5e45293bc3a5a3a00b5dabfd18f5b5724
|
Java
|
flaime/ResultatTavalaKanot
|
/src/main/java/paresePdf/Lopp.java
|
UTF-8
| 5,670
| 2.703125
| 3
|
[] |
no_license
|
package paresePdf;
import java.util.ArrayList;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.beans.value.ObservableIntegerValue;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
public class Lopp {
private final StringProperty Datum = new SimpleStringProperty("non");
private final StringProperty distans = new SimpleStringProperty("non");
private final StringProperty tid = new SimpleStringProperty("non");
private final StringProperty klass = new SimpleStringProperty("non");
private final StringProperty typ = new SimpleStringProperty("non"); //likt final mellanhet osv
private final IntegerProperty typNummerInteger = new SimpleIntegerProperty(-1);
private final StringProperty typNummerString = new SimpleStringProperty("-1");
private final IntegerProperty loppNummerInteger = new SimpleIntegerProperty(-1);
private final StringProperty loppNummerString = new SimpleStringProperty("-1");
private ObservableList<Bana> banorna = FXCollections.observableArrayList();
public Lopp(String datum, String distans, String tid, String klass, String typ, int typNummer, int loppNummer) {
this.Datum.set(datum);
this.distans.set(distans);
this.tid.set(tid);
this.klass.set(klass);
this.typ.set(typ);
this.typNummerInteger.set(typNummer);
this.typNummerString.set(typNummer+"");
this.loppNummerInteger.set(loppNummer);
this.loppNummerString.set(loppNummer+"");
}
public ObservableList<Bana> getBanorna(){
return banorna;
}
public void addBana(ArrayList<Bana> banor) {
banorna.addAll(banor);
}
public void setLoppNummer(int loppNummer){
this.loppNummerInteger.set(loppNummer);
this.loppNummerString.set(loppNummer+"");
}
public void setTypNummer(int typNummer){
this.typNummerInteger.set(typNummer);
this.typNummerString.set(typNummer+"");
}
public IntegerProperty getLoppNummerIntegerProperty(){
return loppNummerInteger;
}
public StringProperty getloppnummerStringProperty (){
return loppNummerString;
}
public String getloppnummer (){
return loppNummerString.getValue();
}
public IntegerProperty getTypNummerIntegerProperty(){
return typNummerInteger;
}
public StringProperty getTypNummerStringProperty (){
return typNummerString;
}
public String getTypNummer (){
return typNummerString.getValue();
}
public StringProperty getKlassStringProperty() {
return klass;
}
public StringProperty getDatumStringProperty() {
return Datum;
}
public StringProperty getDistansStringProperty() {
return distans;
}
public StringProperty getTidStringProperty() {
return tid;
}
public StringProperty getTypStringProperty() {
return typ;
}
public String getKlass() {
return klass.getValue();
}
public String getDatum() {
return Datum.getValue();
}
public String getDistans() {
return distans.getValue();
}
public String getTid() {
return tid.getValue();
}
public String getTyp() {
return typ.getValue();
}
public String toString(){
String ret = "Datum: " + Datum.get()+ "\nDistans: " + distans.get() + "\ntid: " +tid.get() + "\nklass: " + klass.get() + "\n\"typ\": " + typ.get() + "\n\"typ\" nummer: "+ typNummerInteger.get() + "\nloppnummer: " + loppNummerString.get();
for(Bana b : banorna){
ret+= "\n"+b +"\n";
}
return ret;
}
public void setdistans(String text) {
distans.setValue(text);
}
public void setKlass(String text) {
klass.setValue(text);
}
public void setStartTid(String text) {
tid.setValue(text);
}
public void setTypAvLopp(String text) {
typ.setValue(text);
}
public void setTypAvLoppNummer(int text) {
typNummerInteger.setValue(text);
typNummerString.setValue(text+"");
}
public void setDatum(String text) {
Datum.setValue(text);
}
public String getJson() {
String json = "{";
json += transformTillVärde("dateTime", Datum.getValue() + "T" + tid.getValue() + ":00");
json += ",";
json += transformTillVärde("distance", distans.getValue());
json += ",";
json += transformTillVärde("time", tid.getValue());
json += ",";
json += transformTillVärde("raceClass", klass.getValue());
json += ",";
json += transformTillVärde("type", typ.getValue());
json += ",";
json += transformTillVärde("typeNumber", typNummerString.getValue());
json += ",";
json += transformTillVärde("raceNummer", loppNummerString.getValue());
json += ",\"tracks\":[";
//banor
for(int i=0; i < banorna.size(); i++)
{
// Console.Write(A[i]);
json += banorna.get(i).getJson();
if (i != banorna.size()-1)
json += ",";
// Console.Write(",");
}
json += "]}";
return json;
}
private String transformTillVärde(String namn , String värde){
return "\""+namn+"\":\""+värde+"\"";
}
public boolean FinnsBanaMedNummer(String nummer) {
for(Bana x : banorna){
if(nummer.equalsIgnoreCase(x.getBanaNummer().getValue()))
return true;
}
return false;
}
public boolean FinnsBanaMedNamnet(String namn) {//TODO skriv den b�ttre s� att den letar efter namn i namnet och inte efter att det m�ste vara identiskt... typ K4:a eller s�
for(Bana x : banorna){
if(namn.trim().equalsIgnoreCase(x.getNamn().getValue().trim()))
return true;
}
return false;
}
public boolean FinnsBanaMedKLubben(String klubb) {
for(Bana x : banorna){
if(klubb.trim().equalsIgnoreCase(x.getKlubb().getValue().trim()))
return true;
}
return false;
}
}
| true
|
fc99ec4adacfbf02a67676c2760c9edb87dce759
|
Java
|
a88238327/CustomerLogin
|
/src/main/java/entity/selectdata.java
|
UTF-8
| 57,631
| 2.25
| 2
|
[] |
no_license
|
package entity;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.*;
import jdk.nashorn.internal.runtime.linker.LinkerCallSite;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class selectdata {
public static boolean userphone(String phone) {
Connection conn = null;
Statement stmt = null;
PreparedStatement pstmt = null;
String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";//驱动类
String username = new DataUser().getUsername();//数据库用户名
String DBpassword = new DataUser().getPassword();//数据库密码
String sql = "select * from sellers where phone='" + phone + "'";//查询语句
System.out.println(sql);
String DBurl = new DataUrl().getUrl();//连接数据库的地址
try {
Class.forName(driver);//加载驱动器类
conn = DriverManager.getConnection(DBurl, username, DBpassword);//建立连接
//建立处理的SQL语句
pstmt = conn.prepareStatement(sql);
System.out.println(pstmt.toString());
ResultSet rs = pstmt.executeQuery();
if (rs.next()) {
rs.close();
pstmt.close();//关闭SQL语句集
conn.close();//关闭连接
return true;//手机号已存在
}
rs.close();
pstmt.close();//关闭SQL语句集
conn.close();//关闭连接
} catch (Exception e) {
// TODO: handle exception
}
return false;
}
public static boolean userphonepassword(String phone, String password) {
Connection conn = null;
Statement stmt = null;
PreparedStatement pstmt = null;
String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";//驱动类
String username = new DataUser().getUsername();//数据库用户名
String DBpassword = new DataUser().getPassword();//数据库密码
String sql = "select * from customer where USER_FORM_INFO_FLAG_MOBILE='" + phone + "' and password='" + password + "'";//查询语句
System.out.println(sql);
String DBurl = new DataUrl().getUrl();//连接数据库的地址
try {
Class.forName(driver);//加载驱动器类
conn = DriverManager.getConnection(DBurl, username, DBpassword);//建立连接
//建立处理的SQL语句
pstmt = conn.prepareStatement(sql);
System.out.println(pstmt.toString());
ResultSet rs = pstmt.executeQuery();
if (rs.next()) {
rs.close();
pstmt.close();//关闭SQL语句集
conn.close();//关闭连接
return true;//手机号已存在
}
rs.close();
pstmt.close();//关闭SQL语句集
conn.close();//关闭连接
} catch (Exception e) {
// TODO: handle exception
}
return false;
}
public static boolean usermaster(String phone) {
Connection conn = null;
Statement stmt = null;
PreparedStatement pstmt = null;
String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";//驱动类
String username = new DataUser().getUsername();//数据库用户名
String DBpassword = new DataUser().getPassword();//数据库密码
String sql = "select mastername from sellers where phone='" + phone + "' and mastername is not null";//查询语句
System.out.println(sql);
String DBurl = new DataUrl().getUrl();//连接数据库的地址
try {
Class.forName(driver);//加载驱动器类
conn = DriverManager.getConnection(DBurl, username, DBpassword);//建立连接
//建立处理的SQL语句
pstmt = conn.prepareStatement(sql);
System.out.println(pstmt.toString());
ResultSet rs = pstmt.executeQuery();
if (rs.next()) {
rs.close();
pstmt.close();//关闭SQL语句集
conn.close();//关闭连接
return true;//手机号已存在
}
rs.close();
pstmt.close();//关闭SQL语句集
conn.close();//关闭连接
} catch (Exception e) {
// TODO: handle exception
}
return false;
}
public static String getservice(String phone) {
Connection conn = null;
Statement stmt = null;
PreparedStatement pstmt = null;
String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";//驱动类
String username = new DataUser().getUsername();//数据库用户名
String DBpassword = new DataUser().getPassword();//数据库密码
String sql = "select name from seller_service where sellerphone='" + phone + "' and enable='1'";//查询语句
System.out.println(sql);
String DBurl = new DataUrl().getUrl();//连接数据库的地址
HashMap<String, String> map = new HashMap<String, String>();
List list = new ArrayList();
try {
Class.forName(driver);//加载驱动器类
conn = DriverManager.getConnection(DBurl, username, DBpassword);//建立连接
//建立处理的SQL语句
pstmt = conn.prepareStatement(sql);
System.out.println(pstmt.toString());
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
list.add(rs.getString("name"));
// return true;//手机号已存在
}
if (list.isEmpty()) {
rs.close();
pstmt.close();//关闭SQL语句集
conn.close();//关闭连接
return "null";
}
rs.close();
pstmt.close();//关闭SQL语句集
conn.close();//关闭连接
} catch (Exception e) {
// TODO: handle exception
}
JSONArray jsonObject = JSONArray.fromObject(list);
System.out.println(jsonObject.toString());
return jsonObject.toString();
}
public static boolean usercar(String number) {
Connection conn = null;
Statement stmt = null;
PreparedStatement pstmt = null;
String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";//驱动类
String username = new DataUser().getUsername();//数据库用户名
String DBpassword = new DataUser().getPassword();//数据库密码
String sql = "select 号牌号码 from usercars where 号牌号码='" + number + "'";//查询语句
System.out.println(sql);
String DBurl = new DataUrl().getUrl();//连接数据库的地址
try {
Class.forName(driver);//加载驱动器类
conn = DriverManager.getConnection(DBurl, username, DBpassword);//建立连接
//建立处理的SQL语句
pstmt = conn.prepareStatement(sql);
System.out.println(pstmt.toString());
ResultSet rs = pstmt.executeQuery();
if (rs.next()) {
return true;
}
rs.close();
pstmt.close();//关闭SQL语句集
conn.close();//关闭连接
} catch (Exception e) {
System.out.println(e);
}
return false;
}
public static String getuserphone(String number) {
Connection conn = null;
Statement stmt = null;
PreparedStatement pstmt = null;
String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";//驱动类
String username = new DataUser().getUsername();//数据库用户名
String DBpassword = new DataUser().getPassword();//数据库密码
String sql = "select phone from usercars where 号牌号码='" + number + "'";//查询语句
System.out.println(sql);
String DBurl = new DataUrl().getUrl();//连接数据库的地址
try {
Class.forName(driver);//加载驱动器类
conn = DriverManager.getConnection(DBurl, username, DBpassword);//建立连接
//建立处理的SQL语句
pstmt = conn.prepareStatement(sql);
System.out.println(pstmt.toString());
ResultSet rs = pstmt.executeQuery();
if (rs.next()) {
String phone = rs.getString("phone");
return phone;
}
rs.close();
pstmt.close();//关闭SQL语句集
conn.close();//关闭连接
} catch (Exception e) {
System.out.println(e);
}
return null;
}
public static String getopenid(String userphone) {
Connection conn = null;
Statement stmt = null;
PreparedStatement pstmt = null;
String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";//驱动类
String username = new DataUser().getUsername();//数据库用户名
String DBpassword = new DataUser().getPassword();//数据库密码
String sql = "select openid from customer where USER_FORM_INFO_FLAG_MOBILE='" + userphone + "'";//查询语句
System.out.println(sql);
String DBurl = new DataUrl().getUrl();//连接数据库的地址
try {
Class.forName(driver);//加载驱动器类
conn = DriverManager.getConnection(DBurl, username, DBpassword);//建立连接
//建立处理的SQL语句
pstmt = conn.prepareStatement(sql);
System.out.println(pstmt.toString());
ResultSet rs = pstmt.executeQuery();
if (rs.next()) {
String openid = rs.getString("openid");
return openid;
}
rs.close();
pstmt.close();//关闭SQL语句集
conn.close();//关闭连接
} catch (Exception e) {
System.out.println(e);
}
return null;
}
public static String getsellername(String sellerphone) {
Connection conn = null;
Statement stmt = null;
PreparedStatement pstmt = null;
String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";//驱动类
String username = new DataUser().getUsername();//数据库用户名
String DBpassword = new DataUser().getPassword();//数据库密码
String sql = "select name from sellers where phone='" + sellerphone + "'";//查询语句
System.out.println(sql);
String DBurl = new DataUrl().getUrl();//连接数据库的地址
try {
Class.forName(driver);//加载驱动器类
conn = DriverManager.getConnection(DBurl, username, DBpassword);//建立连接
//建立处理的SQL语句
pstmt = conn.prepareStatement(sql);
System.out.println(pstmt.toString());
ResultSet rs = pstmt.executeQuery();
if (rs.next()) {
String name = rs.getString("name");
return name;
}
rs.close();
pstmt.close();//关闭SQL语句集
conn.close();//关闭连接
} catch (Exception e) {
System.out.println(e);
}
return null;
}
public static String getsellerphone(String orderID) {
Connection conn = null;
Statement stmt = null;
PreparedStatement pstmt = null;
String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";//驱动类
String username = new DataUser().getUsername();//数据库用户名
String DBpassword = new DataUser().getPassword();//数据库密码
String sql = "select sellerphone from userorder where orderID='" + orderID + "'";//查询语句
System.out.println(sql);
String DBurl = new DataUrl().getUrl();//连接数据库的地址
try {
Class.forName(driver);//加载驱动器类
conn = DriverManager.getConnection(DBurl, username, DBpassword);//建立连接
//建立处理的SQL语句
pstmt = conn.prepareStatement(sql);
System.out.println(pstmt.toString());
ResultSet rs = pstmt.executeQuery();
if (rs.next()) {
String sellerphone = rs.getString("sellerphone");
return sellerphone;
}
rs.close();
pstmt.close();//关闭SQL语句集
conn.close();//关闭连接
} catch (Exception e) {
System.out.println(e);
}
return null;
}
public static String getsellerinfo(String sellerphone) {
Connection conn = null;
Statement stmt = null;
PreparedStatement pstmt = null;
String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";//驱动类
String username = new DataUser().getUsername();//数据库用户名
String DBpassword = new DataUser().getPassword();//数据库密码
String sql = "select name,touxiang from sellers where phone='" + sellerphone + "'";//查询语句
System.out.println(sql);
String DBurl = new DataUrl().getUrl();//连接数据库的地址
try {
Class.forName(driver);//加载驱动器类
conn = DriverManager.getConnection(DBurl, username, DBpassword);//建立连接
//建立处理的SQL语句
pstmt = conn.prepareStatement(sql);
System.out.println(pstmt.toString());
ResultSet rs = pstmt.executeQuery();
if (rs.next()) {
HashMap<String, String> map = new HashMap<String, String>();
map.put("name", rs.getString("name"));
map.put("touxiang", rs.getString("touxiang"));
JSONObject jsonObject = JSONObject.fromObject(map);
return jsonObject.toString();
}
rs.close();
pstmt.close();//关闭SQL语句集
conn.close();//关闭连接
} catch (Exception e) {
System.out.println(e);
}
return null;
}
public static boolean selectevaluation(String orderID) {
Connection conn = null;
Statement stmt = null;
PreparedStatement pstmt = null;
String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";//驱动类
String username = new DataUser().getUsername();//数据库用户名
String DBpassword = new DataUser().getPassword();//数据库密码
String sql = "select orderID from evaluation where orderID='" + orderID + "'";//查询语句
System.out.println(sql);
String DBurl = new DataUrl().getUrl();//连接数据库的地址
try {
Class.forName(driver);//加载驱动器类
conn = DriverManager.getConnection(DBurl, username, DBpassword);//建立连接
//建立处理的SQL语句
pstmt = conn.prepareStatement(sql);
System.out.println(pstmt.toString());
ResultSet rs = pstmt.executeQuery();
if (rs.next()) {
rs.close();
pstmt.close();//关闭SQL语句集
conn.close();//关闭连接
return false;
}
rs.close();
pstmt.close();//关闭SQL语句集
conn.close();//关闭连接
} catch (Exception e) {
System.out.println(e);
}
return true;
}
public static String getqr(String string) {
// TODO Auto-generated method stub
return null;
}
public static boolean selectcarnum(String haopaihaoma) {
Connection conn = null;
Statement stmt = null;
PreparedStatement pstmt = null;
String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";//驱动类
String username = new DataUser().getUsername();//数据库用户名
String DBpassword = new DataUser().getPassword();//数据库密码
String sql = "select 号牌号码 from cars where 号牌号码='" + haopaihaoma + "'";//查询语句
System.out.println(sql);
String DBurl = new DataUrl().getUrl();//连接数据库的地址
try {
Class.forName(driver);//加载驱动器类
conn = DriverManager.getConnection(DBurl, username, DBpassword);//建立连接
//建立处理的SQL语句
pstmt = conn.prepareStatement(sql);
System.out.println(pstmt.toString());
ResultSet rs = pstmt.executeQuery();
if (rs.next()) {
rs.close();
pstmt.close();//关闭SQL语句集
conn.close();//关闭连接
return true;
}
rs.close();
pstmt.close();//关闭SQL语句集
conn.close();//关闭连接
} catch (Exception e) {
System.out.println(e);
}
return false;
}
public static String carbassinfo(String phone) {
Connection conn = null;
Statement stmt = null;
PreparedStatement pstmt = null;
String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";//驱动类
String username = new DataUser().getUsername();//数据库用户名
String DBpassword = new DataUser().getPassword();//数据库密码
String sql = "select 号牌号码,车牌颜色 from cars where phone='" + phone + "'";//查询语句
System.out.println(sql);
String DBurl = new DataUrl().getUrl();//连接数据库的地址
ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
try {
Class.forName(driver);//加载驱动器类
conn = DriverManager.getConnection(DBurl, username, DBpassword);//建立连接
//建立处理的SQL语句
pstmt = conn.prepareStatement(sql);
System.out.println(pstmt.toString());
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
HashMap<String, String> map = new HashMap<String, String>();
map.put("number", rs.getString("号牌号码"));
map.put("color", rs.getString("车牌颜色"));
list.add(map);
}
rs.close();
pstmt.close();//关闭SQL语句集
conn.close();//关闭连接
if (list.isEmpty()) {
return "";
}
JSONArray jsonArray = JSONArray.fromObject(list);
return jsonArray.toString();
} catch (Exception e) {
System.out.println(e);
}
return null;
}
public static String getmarkers(String servicename, String city) {
Connection conn = null;
Statement stmt = null;
PreparedStatement pstmt = null;
String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";//驱动类
String username = new DataUser().getUsername();//数据库用户名
String DBpassword = new DataUser().getPassword();//数据库密码
String sql = "select sellers.phone,sellers.lat,sellers.lng from sellers,seller_service where sellers.phone=seller_service.sellerphone and seller_service.enable=1 and seller_service.name='" + servicename + "' and sellers.city='" + city + "'";//查询语句
System.out.println(sql);
String DBurl = new DataUrl().getUrl();//连接数据库的地址
ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
try {
Class.forName(driver);//加载驱动器类
conn = DriverManager.getConnection(DBurl, username, DBpassword);//建立连接
//建立处理的SQL语句
pstmt = conn.prepareStatement(sql);
System.out.println(pstmt.toString());
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
HashMap<String, String> map = new HashMap<String, String>();
map.put("phone", rs.getString("phone"));
map.put("lat", rs.getString("lat"));
map.put("lng", rs.getString("lng"));
list.add(map);
}
rs.close();
pstmt.close();//关闭SQL语句集
conn.close();//关闭连接
if (list.isEmpty()) {
return "";
}
JSONArray jsonArray = JSONArray.fromObject(list);
return jsonArray.toString();
} catch (Exception e) {
System.out.println(e);
}
return null;
}
public static String getmarkersinfo(String phone, String servicename) {
Connection conn = null;
Statement stmt = null;
PreparedStatement pstmt = null;
String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";//驱动类
String username = new DataUser().getUsername();//数据库用户名
String DBpassword = new DataUser().getPassword();//数据库密码
String sql = "select name,address,sellerID,touxiang from sellers where phone='" + phone + "'";//查询语句
System.out.println(sql);
String DBurl = new DataUrl().getUrl();//连接数据库的地址
HashMap<String, String> map = new HashMap<String, String>();
try {
Class.forName(driver);//加载驱动器类
conn = DriverManager.getConnection(DBurl, username, DBpassword);//建立连接
//建立处理的SQL语句
pstmt = conn.prepareStatement(sql);
System.out.println(pstmt.toString());
ResultSet rs = pstmt.executeQuery();
if (rs.next()) {
map.put("name", rs.getString("name"));
map.put("address", rs.getString("address"));
map.put("sellerID", rs.getString("sellerID"));
map.put("touxiang", rs.getString("touxiang"));
map.put("compelet", selectdata.getcountcomplete(phone, servicename));
}
rs.close();
pstmt.close();//关闭SQL语句集
conn.close();//关闭连接
JSONObject jsonObject = JSONObject.fromObject(map);
return jsonObject.toString();
} catch (Exception e) {
System.out.println(e);
}
return "";
}
public static String getuserorders(String phone) {
Connection conn = null;
Statement stmt = null;
PreparedStatement pstmt = null;
String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";//驱动类
String username = new DataUser().getUsername();//数据库用户名
String DBpassword = new DataUser().getPassword();//数据库密码
String sql = "select sellerphone,name,orderID,status from userorder where userphone='" + phone + "'";//查询语句
System.out.println(sql);
String DBurl = new DataUrl().getUrl();//连接数据库的地址
ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
try {
Class.forName(driver);//加载驱动器类
conn = DriverManager.getConnection(DBurl, username, DBpassword);//建立连接
//建立处理的SQL语句
pstmt = conn.prepareStatement(sql);
System.out.println(pstmt.toString());
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
HashMap<String, String> map = new HashMap<String, String>();
map.put("touxiang", selectdata.getsellertouxiang(rs.getString("sellerphone")));
map.put("name", selectdata.getsellername(rs.getString("sellerphone")));
map.put("status", rs.getString("status"));
map.put("content", rs.getString("name"));
map.put("orderID", rs.getString("orderID"));
map.put("evaluation", selectdata.getevaluation(rs.getString("orderID")));
list.add(map);
}
if (list.isEmpty()) {
return "";
}
rs.close();
pstmt.close();//关闭SQL语句集
conn.close();//关闭连接
JSONArray jsonObject = JSONArray.fromObject(list);
return jsonObject.toString();
} catch (Exception e) {
System.out.println(e);
}
return "";
}
private static String getevaluation(String orderID) {
Connection conn = null;
Statement stmt = null;
PreparedStatement pstmt = null;
String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";//驱动类
String username = new DataUser().getUsername();//数据库用户名
String DBpassword = new DataUser().getPassword();//数据库密码
String sql = "select orderID from evaluation where orderID='" + orderID + "'";//查询语句
System.out.println(sql);
String DBurl = new DataUrl().getUrl();//连接数据库的地址
HashMap<String, String> map = new HashMap<String, String>();
try {
Class.forName(driver);//加载驱动器类
conn = DriverManager.getConnection(DBurl, username, DBpassword);//建立连接
//建立处理的SQL语句
pstmt = conn.prepareStatement(sql);
System.out.println(pstmt.toString());
ResultSet rs = pstmt.executeQuery();
if (rs.next()) {
return "true";
}
rs.close();
pstmt.close();//关闭SQL语句集
conn.close();//关闭连接
} catch (Exception e) {
System.out.println(e);
}
return "false";
}
private static String getsellertouxiang(String phone) {
Connection conn = null;
Statement stmt = null;
PreparedStatement pstmt = null;
String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";//驱动类
String username = new DataUser().getUsername();//数据库用户名
String DBpassword = new DataUser().getPassword();//数据库密码
String sql = "select touxiang from sellers where phone='" + phone + "'";//查询语句
System.out.println(sql);
String DBurl = new DataUrl().getUrl();//连接数据库的地址
HashMap<String, String> map = new HashMap<String, String>();
try {
Class.forName(driver);//加载驱动器类
conn = DriverManager.getConnection(DBurl, username, DBpassword);//建立连接
//建立处理的SQL语句
pstmt = conn.prepareStatement(sql);
System.out.println(pstmt.toString());
ResultSet rs = pstmt.executeQuery();
if (rs.next()) {
return rs.getString("touxiang");
}
rs.close();
pstmt.close();//关闭SQL语句集
conn.close();//关闭连接
JSONObject jsonObject = JSONObject.fromObject(map);
return jsonObject.toString();
} catch (Exception e) {
System.out.println(e);
}
return "";
}
public static String getsharenumber(String phone) {
Connection conn = null;
Statement stmt = null;
PreparedStatement pstmt = null;
String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";//驱动类
String username = new DataUser().getUsername();//数据库用户名
String DBpassword = new DataUser().getPassword();//数据库密码
String sql = "select count(openid) as count from customer where share='" + phone + "' and openid is not null";//查询语句
System.out.println(sql);
String DBurl = new DataUrl().getUrl();//连接数据库的地址
try {
Class.forName(driver);//加载驱动器类
conn = DriverManager.getConnection(DBurl, username, DBpassword);//建立连接
//建立处理的SQL语句
pstmt = conn.prepareStatement(sql);
System.out.println(pstmt.toString());
ResultSet rs = pstmt.executeQuery();
if (rs.next()) {
return rs.getString("count");
}
rs.close();
pstmt.close();//关闭SQL语句集
conn.close();//关闭连接
} catch (Exception e) {
System.out.println(e);
}
return "";
}
public static String getphone(String openid) {
Connection conn = null;
Statement stmt = null;
PreparedStatement pstmt = null;
String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";//驱动类
String username = new DataUser().getUsername();//数据库用户名
String DBpassword = new DataUser().getPassword();//数据库密码
String sql = "select USER_FORM_INFO_FLAG_MOBILE from customer where openid='" + openid + "' and USER_FORM_INFO_FLAG_MOBILE is not null";//查询语句
System.out.println(sql);
String DBurl = new DataUrl().getUrl();//连接数据库的地址
HashMap<String, String> map = new HashMap<String, String>();
try {
Class.forName(driver);//加载驱动器类
conn = DriverManager.getConnection(DBurl, username, DBpassword);//建立连接
//建立处理的SQL语句
pstmt = conn.prepareStatement(sql);
System.out.println(pstmt.toString());
ResultSet rs = pstmt.executeQuery();
if (rs.next()) {
return rs.getString("USER_FORM_INFO_FLAG_MOBILE");
}
rs.close();
pstmt.close();//关闭SQL语句集
conn.close();//关闭连接
JSONObject jsonObject = JSONObject.fromObject(map);
return jsonObject.toString();
} catch (Exception e) {
System.out.println(e);
}
return "";
}
public static boolean commercialEnable(String phone) {
Connection conn = null;
Statement stmt = null;
PreparedStatement pstmt = null;
String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";//驱动类
String username = new DataUser().getUsername();//数据库用户名
String DBpassword = new DataUser().getPassword();//数据库密码
String sql = "select max(createtime) from insurance where phone='" + phone + "' and type='commercial'";//查询语句
System.out.println(sql);
String DBurl = new DataUrl().getUrl();//连接数据库的地址
try {
Class.forName(driver);//加载驱动器类
conn = DriverManager.getConnection(DBurl, username, DBpassword);//建立连接
//建立处理的SQL语句
pstmt = conn.prepareStatement(sql);
System.out.println(pstmt.toString());
ResultSet rs = pstmt.executeQuery();
if (rs.next()) {
//判断是否在一年有效期内
if (ValidDate.isValidDate(rs.getString("createtime"), 365)) {
return true;
} else {
return false;
}
}
rs.close();
pstmt.close();//关闭SQL语句集
conn.close();//关闭连接
} catch (Exception e) {
System.out.println(e);
}
return false;
}
public static boolean apponintment_exist(String phone, String eventcontent) {
Connection conn = null;
Statement stmt = null;
PreparedStatement pstmt = null;
String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";//驱动类
String username = new DataUser().getUsername();//数据库用户名
String DBpassword = new DataUser().getPassword();//数据库密码
String sql = "select phone from appointment where phone='" + phone + "' and status='未处理' and eventcontent='" + eventcontent + "'";//查询语句
System.out.println(sql);
String DBurl = new DataUrl().getUrl();//连接数据库的地址
try {
Class.forName(driver);//加载驱动器类
conn = DriverManager.getConnection(DBurl, username, DBpassword);//建立连接
//建立处理的SQL语句
pstmt = conn.prepareStatement(sql);
System.out.println(pstmt.toString());
ResultSet rs = pstmt.executeQuery();
if (rs.next()) {
return true;
}
rs.close();
pstmt.close();//关闭SQL语句集
conn.close();//关闭连接
} catch (Exception e) {
System.out.println(e);
}
return false;
}
public static boolean selectlicense(String zhenghao) {
Connection conn = null;
Statement stmt = null;
PreparedStatement pstmt = null;
String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";//驱动类
String username = new DataUser().getUsername();//数据库用户名
String DBpassword = new DataUser().getPassword();//数据库密码
String sql = "select 证号 from driving_licence where 证号='" + zhenghao + "'";//查询语句
System.out.println(sql);
String DBurl = new DataUrl().getUrl();//连接数据库的地址
try {
Class.forName(driver);//加载驱动器类
conn = DriverManager.getConnection(DBurl, username, DBpassword);//建立连接
//建立处理的SQL语句
pstmt = conn.prepareStatement(sql);
System.out.println(pstmt.toString());
ResultSet rs = pstmt.executeQuery();
if (rs.next()) {
rs.close();
pstmt.close();//关闭SQL语句集
conn.close();//关闭连接
return true;
}
rs.close();
pstmt.close();//关闭SQL语句集
conn.close();//关闭连接
} catch (Exception e) {
System.out.println(e);
}
return false;
}
public static String driving_licenceinfo(String phone) {
Connection conn = null;
Statement stmt = null;
PreparedStatement pstmt = null;
String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";//驱动类
String username = new DataUser().getUsername();//数据库用户名
String DBpassword = new DataUser().getPassword();//数据库密码
String sql = "select 姓名,性别,准驾车型,初次领证日期,有效期至,档案号,证号 from driving_licence where phone='" + phone + "'";//查询语句
System.out.println(sql);
HashMap<String, String> map = new HashMap<String, String>();
String DBurl = new DataUrl().getUrl();//连接数据库的地址
try {
Class.forName(driver);//加载驱动器类
conn = DriverManager.getConnection(DBurl, username, DBpassword);//建立连接
//建立处理的SQL语句
pstmt = conn.prepareStatement(sql);
System.out.println(pstmt.toString());
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
map.put("姓名", rs.getString("姓名"));
map.put("性别", rs.getString("性别"));
map.put("准驾车型", rs.getString("准驾车型"));
map.put("初次领证日期", rs.getString("初次领证日期"));
map.put("有效期至", rs.getString("有效期至"));
map.put("档案号", rs.getString("档案号"));
map.put("证号", rs.getString("证号"));
}
rs.close();
pstmt.close();//关闭SQL语句集
conn.close();//关闭连接
if (map.isEmpty()) {
return "";
}
JSONObject jsonObject = JSONObject.fromObject(map);
return jsonObject.toString();
} catch (Exception e) {
System.out.println(e);
}
return null;
}
public static String getlist(String servicename, String city) {
Connection conn = null;
Statement stmt = null;
PreparedStatement pstmt = null;
String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";//驱动类
String username = new DataUser().getUsername();//数据库用户名
String DBpassword = new DataUser().getPassword();//数据库密码
String sql = "select sellers.name,sellers.touxiang,sellers.address,sellers.sellerID,sellers.phone from sellers,seller_service where sellers.phone=seller_service.sellerphone and seller_service.enable=1 and seller_service.name='" + servicename + "' and sellers.city='" + city + "'";//查询语句
System.out.println(sql);
String DBurl = new DataUrl().getUrl();//连接数据库的地址
ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
try {
Class.forName(driver);//加载驱动器类
conn = DriverManager.getConnection(DBurl, username, DBpassword);//建立连接
//建立处理的SQL语句
pstmt = conn.prepareStatement(sql);
System.out.println(pstmt.toString());
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
HashMap<String, String> map = new HashMap<String, String>();
map.put("name", rs.getString("name"));
map.put("touxiang", rs.getString("touxiang"));
map.put("address", rs.getString("address"));
map.put("sellerID", rs.getString("sellerID"));
map.put("complete", selectdata.getcountcomplete(rs.getString("phone"), servicename));
list.add(map);
}
rs.close();
pstmt.close();//关闭SQL语句集
conn.close();//关闭连接
if (list.isEmpty()) {
return "";
}
JSONArray jsonArray = JSONArray.fromObject(list);
return jsonArray.toString();
} catch (Exception e) {
System.out.println(e);
}
return null;
}
private static String getcountcomplete(String phone, String servicename) {
Connection conn = null;
Statement stmt = null;
PreparedStatement pstmt = null;
String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";//驱动类
String username = new DataUser().getUsername();//数据库用户名
String DBpassword = new DataUser().getPassword();//数据库密码
String sql = "select count(sellerphone) as count from userorder where sellerphone='" + phone + "' and name='" + servicename + "'";//查询语句
System.out.println(sql);
String count = "0";
HashMap<String, String> map = new HashMap<String, String>();
String DBurl = new DataUrl().getUrl();//连接数据库的地址
try {
Class.forName(driver);//加载驱动器类
conn = DriverManager.getConnection(DBurl, username, DBpassword);//建立连接
//建立处理的SQL语句
pstmt = conn.prepareStatement(sql);
System.out.println(pstmt.toString());
ResultSet rs = pstmt.executeQuery();
if (rs.next()) {
count = rs.getString("count");
}
rs.close();
pstmt.close();//关闭SQL语句集
conn.close();//关闭连接
} catch (Exception e) {
System.out.println(e);
}
return count;
}
public static String getsellerinfo_forstore(String sellerID) {
Connection conn = null;
Statement stmt = null;
PreparedStatement pstmt = null;
String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";//驱动类
String username = new DataUser().getUsername();//数据库用户名
String DBpassword = new DataUser().getPassword();//数据库密码
String sql = "select name,address,servicephone,touxiang,lat,lng from sellers where sellerID='" + sellerID + "'";//查询语句
System.out.println(sql);
HashMap<String, String> map = new HashMap<String, String>();
String DBurl = new DataUrl().getUrl();//连接数据库的地址
try {
Class.forName(driver);//加载驱动器类
conn = DriverManager.getConnection(DBurl, username, DBpassword);//建立连接
//建立处理的SQL语句
pstmt = conn.prepareStatement(sql);
System.out.println(pstmt.toString());
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map2 = new HashMap<String, String>();
map2.put("src", rs.getString("touxiang"));
list.add(map2);
JSONArray jsonArray2 = JSONArray.fromObject(list);
System.out.println(jsonArray2.toString());
map.put("name", rs.getString("name"));
map.put("touxiang", jsonArray2.toString());
map.put("address", rs.getString("address"));
map.put("phone", rs.getString("servicephone"));
map.put("lat", rs.getString("lat"));
map.put("lng", rs.getString("lng"));
}
if (map.isEmpty()) {
return "";
}
//获取text
//获取总数
HashMap<String, String> map2 = new HashMap<>();
String total = selectdata.getevaluationtotal(sellerID);
map2.put("total", total);
if (total.equals("0")) {
JSONObject jsonObject = JSONObject.fromObject(map2);
map.put("text", jsonObject.toString());
} else {
//获取最新的一条文字评价
sql = "select top 1 customer.touxiangpath,nickname,evaluation from evaluation,userorder,customer where evaluation.orderID=userorder.orderID and userorder.userphone=customer.USER_FORM_INFO_FLAG_MOBILE and evaluation is not null and evaluation!='' and evaluation.orderID in (select orderID from userorder,sellers where sellerphone=phone and sellerID='" + sellerID + "') order by evaluation.createtime desc";//查询语句
System.out.println(sql);
pstmt = conn.prepareStatement(sql);
System.out.println(pstmt.toString());
ResultSet rs1 = pstmt.executeQuery();
rs1.next();
map2.put("content", rs1.getString("evaluation"));
if (rs1.getString("nickname") == null) {
map2.put("name", "匿名");
} else {
map2.put("name", rs1.getString("nickname"));
}
if (rs1.getString("touxiangpath") == null) {
map2.put("touxiang", "https://cloud.hnjtbf.com/img/chejia.png");
} else {
map2.put("name", rs1.getString("touxiangpath"));
}
rs1.close();
JSONObject jsonObject = JSONObject.fromObject(map2);
map.put("text", jsonObject.toString());
//获取img
ArrayList<HashMap<String, String>> list = new ArrayList<>();
sql = "select sum(Total_photos) as total from evaluation where orderID in (select orderID from userorder,sellers where sellerphone=phone and sellerID='" + sellerID + "')";//查询语句
System.out.println(sql);
pstmt = conn.prepareStatement(sql);
System.out.println(pstmt.toString());
ResultSet rs2 = pstmt.executeQuery();
HashMap<String, String> map3 = new HashMap<>();
if (rs2.next()) {
//取出总的照片数
map3.put("total", rs2.getString("total"));
if (!rs2.getString("total").equals("0")) {
ArrayList<HashMap<String, String>> list1 = new ArrayList<>();
sql = "select top 4 name from evaluation,evaluation_imgs where evaluation_imgs.orderID=evaluation.orderID and evaluation.orderID in (select orderID from userorder,sellers where sellerphone=phone and sellerID='" + sellerID + "') order by evaluation_imgs.createtime desc";//查询语句
System.out.println(sql);
pstmt = conn.prepareStatement(sql);
System.out.println(pstmt.toString());
ResultSet rs3 = pstmt.executeQuery();
while (rs3.next()) {
HashMap<String, String> map4 = new HashMap<>();
map4.put("img", "https://cloud.hnjtbf.com/img/evaluation/" + rs3.getString("name"));
list1.add(map4);
}
JSONArray jsonArray = JSONArray.fromObject(list1);
map3.put("imgs", jsonArray.toString());
rs3.close();
}
JSONObject jsonObject1 = JSONObject.fromObject(map3);
map.put("img", jsonObject1.toString());
rs2.close();
}
}
JSONObject jsonObject = JSONObject.fromObject(map);
rs.close();
pstmt.close();//关闭SQL语句集
conn.close();//关闭连接
return jsonObject.toString();
} catch (Exception e) {
System.out.println(e);
}
return null;
}
private static String getevaluationtotal(String sellerID) {
Connection conn = null;
Statement stmt = null;
PreparedStatement pstmt = null;
String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";//驱动类
String username = new DataUser().getUsername();//数据库用户名
String DBpassword = new DataUser().getPassword();//数据库密码
String sql = "select count(orderID) as count from evaluation where orderID in (select orderID from userorder,sellers where sellerphone=phone and sellerID='" + sellerID + "')";//查询语句
System.out.println(sql);
HashMap<String, String> map = new HashMap<String, String>();
String DBurl = new DataUrl().getUrl();//连接数据库的地址
try {
Class.forName(driver);//加载驱动器类
conn = DriverManager.getConnection(DBurl, username, DBpassword);//建立连接
//建立处理的SQL语句
pstmt = conn.prepareStatement(sql);
System.out.println(pstmt.toString());
ResultSet rs = pstmt.executeQuery();
String total = "0";
while (rs.next()) {
total = rs.getString("count");
}
rs.close();
pstmt.close();//关闭SQL语句集
conn.close();//关闭连接
return total;
} catch (Exception e) {
System.out.println(e);
}
return null;
}
public static String getcars(String phone) {
Connection conn = null;
Statement stmt = null;
PreparedStatement pstmt = null;
String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";//驱动类
String username = new DataUser().getUsername();//数据库用户名
String DBpassword = new DataUser().getPassword();//数据库密码
String sql = "select 号牌号码 from cars where phone='" + phone + "'";//查询语句
System.out.println(sql);
ArrayList<HashMap<String, String>> list = new ArrayList<>();
String DBurl = new DataUrl().getUrl();//连接数据库的地址
try {
Class.forName(driver);//加载驱动器类
conn = DriverManager.getConnection(DBurl, username, DBpassword);//建立连接
//建立处理的SQL语句
pstmt = conn.prepareStatement(sql);
System.out.println(pstmt.toString());
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
HashMap<String, String> map = new HashMap<String, String>();
map.put("号牌号码", rs.getString("号牌号码"));
list.add(map);
}
rs.close();
pstmt.close();//关闭SQL语句集
conn.close();//关闭连接
if (list.isEmpty()) {
return "nocar";
}
JSONArray jsonArray = JSONArray.fromObject(list);
return jsonArray.toString();
} catch (Exception e) {
System.out.println(e);
}
return null;
}
public static String getcarbaoxianinfo(String carnum) {
Connection conn = null;
Statement stmt = null;
PreparedStatement pstmt = null;
String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";//驱动类
String username = new DataUser().getUsername();//数据库用户名
String DBpassword = new DataUser().getPassword();//数据库密码
String sql = "select insurance,Excluding_deductible,type from insurance where 号牌号码='" + carnum + "' and insurance.createtime=(select max(createtime) from insurance where 号牌号码='" + carnum + "' )";//查询语句
System.out.println(sql);
ArrayList<HashMap<String, String>> list = new ArrayList<>();
String DBurl = new DataUrl().getUrl();//连接数据库的地址
try {
Class.forName(driver);//加载驱动器类
conn = DriverManager.getConnection(DBurl, username, DBpassword);//建立连接
//建立处理的SQL语句
pstmt = conn.prepareStatement(sql);
System.out.println(pstmt.toString());
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
HashMap<String, String> map = new HashMap<String, String>();
map.put("insurance", rs.getString("insurance"));
map.put("Excluding_deductible", rs.getString("Excluding_deductible"));
map.put("type", rs.getString("type"));
list.add(map);
}
rs.close();
pstmt.close();//关闭SQL语句集
conn.close();//关闭连接
if (list.isEmpty()) {
return "noinsurance";
}
JSONArray jsonArray = JSONArray.fromObject(list);
return jsonArray.toString();
} catch (Exception e) {
System.out.println(e);
}
return null;
}
public static HashMap<String, String> getcarsinfo(String carnum) {
Connection conn = null;
PreparedStatement pstmt = null;
String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";//驱动类
String username = new DataUser().getUsername();//数据库用户名
String DBpassword = new DataUser().getPassword();//数据库密码
String sql = "select 品牌型号 from cars where 号牌号码='" + carnum + "'";//查询语句
System.out.println(sql);
HashMap<String, String> map = new HashMap<String, String>();
String DBurl = new DataUrl().getUrl();//连接数据库的地址
try {
Class.forName(driver);//加载驱动器类
conn = DriverManager.getConnection(DBurl, username, DBpassword);//建立连接
//建立处理的SQL语句
pstmt = conn.prepareStatement(sql);
System.out.println(pstmt.toString());
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
map.put("品牌型号", rs.getString("品牌型号"));
}
rs.close();
pstmt.close();//关闭SQL语句集
conn.close();//关闭连接
if (map.isEmpty()) {
return null;
}
return map;
} catch (Exception e) {
System.out.println(e);
}
return null;
}
public static String hasremind(String carnum, String phone) {
Connection conn = null;
PreparedStatement pstmt = null;
String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";//驱动类
String username = new DataUser().getUsername();//数据库用户名
String DBpassword = new DataUser().getPassword();//数据库密码
String sql = "select remmind_content,stauts from remind where 号牌号码='" + carnum + "' and phone='" + phone + "'";//查询语句
System.out.println(sql);
ArrayList<HashMap<String, String>> list = new ArrayList<>();
String DBurl = new DataUrl().getUrl();//连接数据库的地址
try {
Class.forName(driver);//加载驱动器类
conn = DriverManager.getConnection(DBurl, username, DBpassword);//建立连接
//建立处理的SQL语句
pstmt = conn.prepareStatement(sql);
System.out.println(pstmt.toString());
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
HashMap<String, String> map = new HashMap<String, String>();
map.put("remmind_content", rs.getString("remmind_content"));
map.put("stauts", rs.getString("stauts"));
list.add(map);
}
rs.close();
pstmt.close();//关闭SQL语句集
conn.close();//关闭连接
if (list.isEmpty()) {
return "";
}
JSONArray jsonArray = JSONArray.fromObject(list);
return jsonArray.toString();
} catch (Exception e) {
System.out.println(e);
}
return null;
}
public static String getevalution(String sellerID) {
Connection conn = null;
PreparedStatement pstmt = null;
String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";//驱动类
String username = new DataUser().getUsername();//数据库用户名
String DBpassword = new DataUser().getPassword();//数据库密码
HashMap<String, String> map = new HashMap<String, String>();
String DBurl = new DataUrl().getUrl();//连接数据库的地址
try {
Class.forName(driver);//加载驱动器类
conn = DriverManager.getConnection(DBurl, username, DBpassword);//建立连接
//建立处理的SQL语句
//查询文字评价与orderID
String sql1 = "select CONVERT(nvarchar(10),evaluation.createtime,111) as time,evaluation,evaluation.orderID,Total_photos,nickname,touxiangpath,name from evaluation,customer,userorder where userorder.orderID=evaluation.orderID and userphone=USER_FORM_INFO_FLAG_MOBILE and evaluation.orderID in (select orderID from userorder where sellerphone=(select sellerphone from sellers where sellerID='" + sellerID + "')) order by evaluation.createtime desc";//查询语句
System.out.println(sql1);
pstmt = conn.prepareStatement(sql1);
System.out.println(pstmt.toString());
ResultSet rs1 = pstmt.executeQuery();
ArrayList<evalutionjson> list1 = new ArrayList<>();
while (rs1.next())
{
String touxiangpath;
if (rs1.getString("touxiangpath") == null) {
touxiangpath = "img/chejia.png";
} else {
touxiangpath = rs1.getString("touxiangpath");
}
String name;
if (rs1.getString("nickname") == null) {
name = "匿名";
} else {
name = rs1.getString("nickname");
}
String content;
if (rs1.getString("evaluation") == "") {
content = "此用户没有填写评价";
} else {
content = rs1.getString("evaluation");
}
evalutionjson json = new evalutionjson(touxiangpath, name, content, rs1.getString("time"), rs1.getString("name"));
String sql2 = "select name from evaluation_imgs where orderID='" + rs1.getString("orderID") + "'";//查询语句
System.out.println(sql2);
pstmt = conn.prepareStatement(sql2);
System.out.println(pstmt.toString());
ResultSet rs2 = pstmt.executeQuery();
while (rs2.next()) {
imgjson imgjs = new imgjson("https://cloud.hnjtbf.com/img/evaluation/" + rs2.getString("name"));
json.imgs.add(imgjs);
}
list1.add(json);
rs2.close();
}
rs1.close();
pstmt.close();//关闭SQL语句集
conn.close();//关闭连接
if (list1.isEmpty()) {
return "";
}
JSONArray jsonArray = JSONArray.fromObject(list1);
return jsonArray.toString();
} catch (Exception e) {
System.out.println(e);
}
return null;
}
}
| true
|
e4da5b6824118d19fc068de51872043083321883
|
Java
|
HyHyena/PayOff
|
/back/src/main/java/ru/dreamteam/properties/PlatformEndpointPropertiesHolder.java
|
UTF-8
| 358
| 1.632813
| 2
|
[] |
no_license
|
package ru.dreamteam.properties;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties(prefix = "platform.endpoint")
@Getter
@Setter
public class PlatformEndpointPropertiesHolder {
private String payout;
private String balance;
private String status;
}
| true
|
cd4f9975e5df21a0332018761ef85eeaf24d585b
|
Java
|
AscariaQuynn/ZoneOfUprising
|
/src/cz/ascaria/zoneofuprising/gui/LoadingLayout.java
|
UTF-8
| 1,831
| 2.484375
| 2
|
[] |
no_license
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package cz.ascaria.zoneofuprising.gui;
import com.jme3.math.Vector2f;
import com.jme3.math.Vector4f;
import cz.ascaria.zoneofuprising.utils.AssetsHelper;
import tonegod.gui.controls.windows.Panel;
import tonegod.gui.core.Element;
/**
*
* @author Ascaria Quynn
*/
public class LoadingLayout extends BaseLayout {
private Panel background;
public boolean isOpened() {
return null != background;
}
@Override
public void open() {
super.open();
check();
if(isOpened()) {
close();
}
// Create background
background = new Panel(screen, Vector2f.ZERO, dimensions, Vector4f.ZERO, "Interface/bg-planet-asteroids.jpg");
background.setIsMovable(false);
background.setIsResizable(false);
background.setIsEnabled(false);
// Create logo
background.addChild(getLogo());
// Create loading text
Vector2f loadingPos = AssetsHelper.scaleOf(dimensions, new Vector2f(0.95f, 0.92f));
Vector2f loadingDims = AssetsHelper.widthOf(app.getAssetManager().loadTexture("Interface/loading.png"), dimensions, 0.25f);
Element loading = new Element(screen, "Loading", loadingPos.subtractLocal(loadingDims), loadingDims, Vector4f.ZERO, "Interface/loading.png");
loading.setIsMovable(false);
loading.setIsResizable(false);
background.addChild(loading);
screen.addElement(background);
}
@Override
public void close() {
super.close();
if(null != background) {
background.hide();
screen.removeElement(background);
background = null;
}
}
}
| true
|
0fa27e62ffa052cf834760f31d80882bfbc0aa2b
|
Java
|
Mitbewohner/BarBot
|
/app/src/main/java/com/example/tutorial/IngredientEntity.java
|
UTF-8
| 2,116
| 2.578125
| 3
|
[] |
no_license
|
package com.example.tutorial;
import android.arch.persistence.room.ColumnInfo;
import android.arch.persistence.room.Entity;
import android.arch.persistence.room.PrimaryKey;
import android.support.annotation.NonNull;
@Entity
public class IngredientEntity implements Comparable<IngredientEntity> {
@PrimaryKey(autoGenerate = true)
private long uid;
@ColumnInfo(name = "name")
private String name;
@ColumnInfo(name = "coordinate")
private int coordinate;
@ColumnInfo(name = "hold")
private int hold;
@ColumnInfo(name = "wait")
private int wait;
@ColumnInfo(name = "isActive")
private boolean isActive;
public long getUid() {
return uid;
}
public void setUid(long uid) {
this.uid = uid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getCoordinate() {
return coordinate;
}
public void setCoordinate(int coordinate) {
this.coordinate = coordinate;
}
public int getHold() {
return hold;
}
public void setHold(int hold) {
this.hold = hold;
}
public int getWait() {
return wait;
}
public void setWait(int wait) {
this.wait = wait;
}
public boolean isActive() {
return isActive;
}
public void setActive(boolean active) {
isActive = active;
}
@Override
public int compareTo(@NonNull IngredientEntity o) {
return this.name.compareToIgnoreCase(o.getName());
}
@Override
public String toString() {
return this.name;
}
@Override
public int hashCode() {
return (int)this.uid * 7;
}
@Override
public boolean equals(Object o) {
if (o == null) {
return false;
}
if (o.getClass() != IngredientEntity.class) {
return false;
}
IngredientEntity ingr = (IngredientEntity) o;
if (ingr.getUid() == this.uid) {
return true;
}
return false;
}
}
| true
|
aa44812cf302eb6c179a2be651196a61fb157c53
|
Java
|
cenbow/2016_sp_mobile
|
/mobile-cache/src/main/java/com/shangpin/cache/CacheKey.java
|
UTF-8
| 344
| 1.914063
| 2
|
[] |
no_license
|
package com.shangpin.cache;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.PARAMETER })
@Documented
public @interface CacheKey {
}
| true
|
d0bc24a11f00cdaad28e00cff9fda8df1e5153c3
|
Java
|
sd1990/TIJ
|
/base/src/main/java/org/songdan/tij/exception/ExceptionUtil.java
|
UTF-8
| 476
| 2.609375
| 3
|
[] |
no_license
|
package org.songdan.tij.exception;
/**
* @author: Songdan
* @create: 2018-11-07 16:23
**/
public class ExceptionUtil {
public static RuntimeException launderThrowable(Throwable throwable) {
if (throwable instanceof RuntimeException) {
return (RuntimeException) throwable;
}
if (throwable instanceof Error) {
throw (Error)throwable;
}
throw new IllegalStateException("未知异常", throwable);
}
}
| true
|
06e35a971992c2c2482903bde1b252246c6c9823
|
Java
|
nhutam123/C0221G1-le-nhu-tam
|
/module2/src/bai10_list/bai_tap/bai2/MyLinkedListTest.java
|
UTF-8
| 713
| 2.8125
| 3
|
[] |
no_license
|
package bai10_list.bai_tap.bai2;
public class MyLinkedListTest {
public static void main(String[] args) {
MyLinkedList elements=new MyLinkedList();
elements.addFirst(12);
elements.addLast(5);
elements.addLast(5);
elements.printList();
System.out.println("add");
elements.add1(1,2);
elements.printList();
System.out.println("get");
System.out.println(elements.get(2));
System.out.println(elements.getFirst());
System.out.println(elements.getLast());
System.out.println("remove");
System.out.println(elements.remove(1));
System.out.println("list");
elements.printList();
}
}
| true
|
27cf7bc5e226d45374cb5fc17cf7554ff60f42bc
|
Java
|
benny201/AndroidTestDemos
|
/FragmentProject/app/src/main/java/com/example/benny/fragmentproject/NewsContentActivity.java
|
UTF-8
| 1,081
| 2.3125
| 2
|
[] |
no_license
|
package com.example.benny.fragmentproject;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
/**
* Created by benny on 16/11/19.
*/
public class NewsContentActivity extends Activity {
public static void actionStart(Context context, String newsTitile, String newsContent) {
Intent intent = new Intent(context,NewsContentActivity.class);
intent.putExtra("news_title",newsTitile);
intent.putExtra("news_content",newsContent);
context.startActivity(intent);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.news_content);
String newsTitle = getIntent().getStringExtra("news_title");
String newsContent = getIntent().getStringExtra("news_content");
NewsContentFragment newsContentFragment = (NewsContentFragment) getFragmentManager().findFragmentById(R.id.news_content_fragment);
newsContentFragment.refresh(newsTitle,newsContent);
}
}
| true
|
21cbe74dd180240906bbc61cea7bff689de4f912
|
Java
|
vladislavkotx/Java-Labs
|
/src/main/java/classwork/java8/employees/Employee.java
|
UTF-8
| 1,124
| 3.296875
| 3
|
[] |
no_license
|
package classwork.java8.employees;
import lombok.Builder;
import lombok.Data;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@Data
@Builder
public class Employee {
private String name;
private int salary;
public static void main(String[] args) {
Employee max = Employee.builder()
.name("Max")
.salary(10)
.build();
Employee alex = Employee.builder()
.name("Alex")
.salary(100)
.build();
List<Employee> list = List.of(max, alex);
Map<Seniority, Long> seniorityLongMap = EmployeeUtils.groupBySeniority(list);
System.out.println(seniorityLongMap);
// int sum = EmployeeUtils.employeeSum(list);
// System.out.println(sum);
//
// List<String> strings = EmployeeUtils.getNamesSortedBySalary(list);
// System.out.println(strings);
//
// Map<String, Employee> stringEmployeeMap = EmployeeUtils.mapNameToEmployee(list);
// System.out.println(stringEmployeeMap);
}
}
| true
|
a97c1624a5e5377de4d586b493cc760e91fd0232
|
Java
|
fanyunle/chachong
|
/src/main/java/com/ssmobject/service/TeacherDateService.java
|
UTF-8
| 777
| 1.789063
| 2
|
[] |
no_license
|
package com.ssmobject.service;
import com.github.pagehelper.PageInfo;
import com.ssmobject.pojo.TeacherClassDate;
import com.ssmobject.pojo.TeacherCourseDate;
import com.ssmobject.pojo.TeacherScoreDate;
import com.ssmobject.pojo.TeacherStudentDate;
public interface TeacherDateService {
PageInfo<TeacherStudentDate> TeacherSearchStudent(String id, int page, int limit);
PageInfo<TeacherStudentDate> TeacherGetStudentList(int page, int limit);
int deleteUser(String scoreid,String scoresname,String scorecname);
int insertUser(TeacherScoreDate scoreDate);
int updateUser(TeacherScoreDate scoreDate);
PageInfo<TeacherCourseDate> TeacherGetCourseList(int page, int limit);
PageInfo<TeacherClassDate> TeacherGetClassList(int page, int limit);
}
| true
|
14506cbcb4cde7d0e6a955404d980a20187b85a5
|
Java
|
kobylynskyi/graphql-java-codegen
|
/src/main/java/com/kobylynskyi/graphql/codegen/supplier/MergeableMappingConfigSupplier.java
|
UTF-8
| 2,143
| 2.5
| 2
|
[
"MIT"
] |
permissive
|
package com.kobylynskyi.graphql.codegen.supplier;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.kobylynskyi.graphql.codegen.model.MappingConfig;
import com.kobylynskyi.graphql.codegen.utils.Utils;
import com.typesafe.config.Config;
import com.typesafe.config.ConfigException;
import com.typesafe.config.ConfigFactory;
import com.typesafe.config.ConfigRenderOptions;
import java.io.File;
import java.util.List;
/**
* Retrieve a MappingConfig from JSON or HOCON configuration file.
*
* @author valinha
*/
public class MergeableMappingConfigSupplier implements MappingConfigSupplier {
private static final ConfigRenderOptions configRenderOptions = ConfigRenderOptions.concise();
private final String jsonConfig;
/**
* Instantiates a new Json configuration file supplier.
*
* @param configFiles List of files, either JSON or HOCON.
*/
public MergeableMappingConfigSupplier(List<String> configFiles) {
this.jsonConfig = parseConfigAndMerged(configFiles);
}
/**
* parser list of config files.
*
* @param confFiles List of files, either JSON or HOCON.
* @return The string of the configuration after merging.
*/
private static String parseConfigAndMerged(List<String> confFiles) {
try {
if (confFiles == null || confFiles.isEmpty()) {
return null;
}
return confFiles.stream()
.map(c -> ConfigFactory.parseFile(new File(c)))
.reduce(Config::withFallback)
.map(value -> value.root().render(configRenderOptions))
.orElse(null);
} catch (ConfigException ce) {
return null;
}
}
@Override
public MappingConfig get() {
if (jsonConfig != null && !jsonConfig.isEmpty()) {
try {
return Utils.OBJECT_MAPPER.readValue(jsonConfig, MappingConfig.class);
} catch (ConfigException | JsonProcessingException e) {
throw new IllegalArgumentException(e);
}
}
return null;
}
}
| true
|
ca2c86d6b6c9f7881267e309ce98d155ae0b39e6
|
Java
|
PassionateWsj/CodeDiary
|
/app/src/main/java/com/jameswong/codediary/DiaryView.java
|
UTF-8
| 381
| 1.742188
| 2
|
[] |
no_license
|
package com.jameswong.codediary;
/**
* ****************************************************
* author: JamesWong
* created on: 2017年07月13日 15:54
* e-mail: PassionateWsj@outlook.com
* name:
* desc:
* ****************************************************
*/
public interface DiaryView {
void onResultSuccess(WeatherBean weatherBean);
void onResultFailure();
}
| true
|