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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
44016186380489fbbc78fd3f6a9c04d3bb9a80cd | Java | andyzhou192/server-interface-ats | /src/test/java/net/protocol/httpclient/HttpClientTest.java | UTF-8 | 1,614 | 2.40625 | 2 | [] | no_license | package net.protocol.httpclient;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import net.protocol.httpclient.HttpClientImpl;
public class HttpClientTest {
public static void main(String[] args) throws FileNotFoundException {
try {
String uri = "http://10.10.10.10/path";
String headers = "Connection: keep-alive\r\nContent-Type: application/x-www-form-urlencoded\r\nContent-Length: 52\r\nHost: 10.10.10.10\r\nUser-Agent: Apache-HttpClient/4.5.2 (Java/1.8.0_111)";
String params = "loginName=13900000000&loginPassword=123456789&type=1";
HttpClientImpl client = new HttpClientImpl(uri, headers, params);
HttpResponse rsp = client.doPost();
System.out.println(rsp.getStatusLine().getStatusCode() + ":" + rsp.getStatusLine().getReasonPhrase());
System.out.println(EntityUtils.toString(rsp.getEntity()));
System.out.println(client.getCookieStore().getCookies());
String url = "http://10.10.10.10/path";
String header = "Content-Type:application/json;charset=UTF-8";
String param = "enterpriseCode=1234";
HttpClientImpl client2 = new HttpClientImpl(url, header, param, client.getCookieStore());
HttpResponse rsp2 = client2.doGet();
System.out.println(rsp2.getStatusLine().getStatusCode() + ":" + rsp2.getStatusLine().getReasonPhrase());
System.out.println(EntityUtils.toString(rsp2.getEntity()));
System.out.println(client2.getCookieStore().getCookies());
client.close();
client2.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
| true |
3b5660f51562d32250d2b563788a366a763302fd | Java | lockingroad/ForFunApp | /app/src/main/java/com/linewow/xhyy/forfunapp/UI/beauty/BeautyFragment.java | UTF-8 | 3,272 | 1.773438 | 2 | [] | no_license | package com.linewow.xhyy.forfunapp.UI.beauty;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.linewow.xhyy.forfunapp.R;
import com.linewow.xhyy.forfunapp.app.AppConstant;
import com.linewow.xhyy.funlibrary.base.BaseFragment;
import com.linewow.xhyy.forfunapp.entity.BeautyInfo;
import com.linewow.xhyy.funlibrary.activity.BeautyPhotoActivity;
import java.util.List;
import butterknife.Bind;
import butterknife.OnClick;
/**
* Created by LXR on 2017/1/19.
*/
public class BeautyFragment extends BaseFragment<BeautyPresenter,BeautyModel> implements BeautyContract.View {
@Bind(R.id.beauty_recycler)
RecyclerView beautyRecycler;
@Bind(R.id.beauty_swipe)
SwipeRefreshLayout beautySwipe;
private String TAG = "BeautyFragment";
private BeautyAdapter adapter;
@Override
protected int getLayoutId() {
return R.layout.fragment_beauty;
}
@Override
protected void initView() {
LinearLayoutManager manager=new LinearLayoutManager(context);
manager.setOrientation(LinearLayoutManager.VERTICAL);
beautyRecycler.setLayoutManager(manager);
beautyRecycler.setItemAnimator(new DefaultItemAnimator());
}
@OnClick(R.id.channel_float_button)
public void onClick() {
rxManager.post(AppConstant.NEWS_LIST_TO_TOP,"");
}
@Override
protected void initPresenter() {
presenter.setVM(this,model);
}
@Override
public void refresh(List<BeautyInfo> list) {
adapter.setNewData(list);
beautySwipe.setRefreshing(false);
}
@Override
public void load(List<BeautyInfo> list) {
adapter.addData(list);
}
@Override
public void err(String err) {
}
@Override
public void start(List<BeautyInfo> list) {
adapter=new BeautyAdapter(list);
beautyRecycler.setAdapter(adapter);
beautySwipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
presenter.refresh();
}
});
adapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
@Override
public void onLoadMoreRequested() {
presenter.load();
}
});
beautyRecycler.addOnItemTouchListener(new OnItemClickListener() {
@Override
public void SimpleOnItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
BeautyInfo info=adapter.getItem(i);
ImageView imageView= (ImageView) view.findViewById(R.id.beauty_img);
BeautyPhotoActivity.startBeautyPhotot(context,imageView,info.url);
}
});
}
@Override
public void loadComplete() {
adapter.loadComplete();
}
@Override
public void scrollToTop() {
beautyRecycler.smoothScrollToPosition(0);
}
}
| true |
60f737ed20f00b2b9083583ccc09e85ca3971bc7 | Java | rekeles/cloud_note | /src/test/java/test/service/TestNoteService.java | GB18030 | 1,448 | 2.171875 | 2 | [] | no_license | package test.service;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import cn.tedu.cloud_note.entity.Note;
import cn.tedu.cloud_note.service.NoteService;
import cn.tedu.cloud_note.util.NoteResult;
public class TestNoteService {
@Resource
private NoteService noteService;
@Before
public void init() {
String[] conf= {"conf/spring-applicationContext.xml","conf/spring-applicationContext.xml"};
ApplicationContext ac=new ClassPathXmlApplicationContext(conf);
noteService=ac.getBean("noteService", NoteService.class);
}
@Test
public void testLoadNote(){
NoteResult<List<Map<String, String>>> result=noteService.loadNote("6d763ac9-dca3-42d7-a2a7-a08053095c08");
System.out.println(result.toString());
}
@Test
public void testLoad() {
NoteResult<Note> result=noteService.load("01da5d69-89d5-4140-9585-b559a97f9cb0");
System.out.println(result.toString());
}
@Test
public void testUpdate() {
NoteResult<Object> result=noteService.updateNote("01da5d69-89d5-4140-9585-b559a97f9cb0", "", "");
System.out.println(result.getStatus());
}
@Test
public void testAdd() {
NoteResult<String> result=noteService.addNote("222", "2222", "һ");
System.out.println(result);
}
}
| true |
59b2eae93c9e270a849adff177581b6765be2fe9 | Java | kenuosec/Decompiled-Whatsapp | /android/support/v7/widget/AdapterHelper.java | UTF-8 | 53,933 | 2 | 2 | [] | no_license | package android.support.v7.widget;
import android.support.v4.util.Pools.Pool;
import android.support.v4.util.Pools.SimplePool;
import android.support.v7.widget.RecyclerView.ViewHolder;
import com.whatsapp.arj;
import java.util.ArrayList;
import java.util.List;
import org.v;
import org.whispersystems.Y;
import org.whispersystems.aF;
import org.whispersystems.at;
class AdapterHelper implements Callback {
private static final String[] z;
final Callback mCallback;
final boolean mDisableRecycler;
private int mExistingUpdateTypes;
Runnable mOnItemProcessedCallback;
final OpReorderer mOpReorderer;
final ArrayList mPendingUpdates;
final ArrayList mPostponedList;
private Pool mUpdateOpPool;
interface Callback {
ViewHolder findViewHolder(int i);
void markViewHoldersUpdated(int i, int i2, Object obj);
void offsetPositionsForAdd(int i, int i2);
void offsetPositionsForMove(int i, int i2);
void offsetPositionsForRemovingInvisible(int i, int i2);
void offsetPositionsForRemovingLaidOutOrNewView(int i, int i2);
void onDispatchFirstPass(UpdateOp updateOp);
void onDispatchSecondPass(UpdateOp updateOp);
}
class UpdateOp {
private static final String[] z;
int cmd;
int itemCount;
Object payload;
int positionStart;
static {
String[] strArr = new String[8];
String str = "-\u000e";
Object obj = -1;
String[] strArr2 = strArr;
String[] strArr3 = strArr;
int i = 0;
while (true) {
char[] toCharArray = str.toCharArray();
int length = toCharArray.length;
char[] cArr = toCharArray;
for (int i2 = 0; length > i2; i2++) {
int i3;
char c = cArr[i2];
switch (i2 % 5) {
case v.m /*0*/:
i3 = 64;
break;
case at.g /*1*/:
i3 = 120;
break;
case at.i /*2*/:
i3 = 116;
break;
case at.o /*3*/:
i3 = 60;
break;
default:
i3 = 60;
break;
}
cArr[i2] = (char) (i3 ^ c);
}
str = new String(cArr).intern();
switch (obj) {
case v.m /*0*/:
strArr2[i] = str;
str = "5\b";
i = 2;
strArr2 = strArr3;
obj = 1;
break;
case at.g /*1*/:
strArr2[i] = str;
str = "\u007fG";
i = 3;
strArr2 = strArr3;
obj = 2;
break;
case at.i /*2*/:
strArr2[i] = str;
str = "!\u001c\u0010";
i = 4;
strArr2 = strArr3;
obj = 3;
break;
case at.o /*3*/:
strArr2[i] = str;
i = 5;
strArr2 = strArr3;
str = "l\u000bN";
obj = 4;
break;
case at.p /*4*/:
strArr2[i] = str;
i = 6;
str = "l\bN";
obj = 5;
strArr2 = strArr3;
break;
case at.m /*5*/:
strArr2[i] = str;
i = 7;
str = "#B";
obj = 6;
strArr2 = strArr3;
break;
case Y.f /*6*/:
strArr2[i] = str;
z = strArr3;
return;
default:
strArr2[i] = str;
str = "2\u0015";
i = 1;
strArr2 = strArr3;
obj = null;
break;
}
}
}
UpdateOp(int i, int i2, int i3, Object obj) {
this.cmd = i;
this.positionStart = i2;
this.itemCount = i3;
this.payload = obj;
}
String cmdToString() {
switch (this.cmd) {
case at.g /*1*/:
return z[4];
case at.i /*2*/:
return z[1];
case at.p /*4*/:
return z[2];
case aF.u /*8*/:
return z[0];
default:
return z[3];
}
}
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
UpdateOp updateOp = (UpdateOp) obj;
if (this.cmd != updateOp.cmd) {
return false;
}
if (this.cmd == 8 && Math.abs(this.itemCount - this.positionStart) == 1 && this.itemCount == updateOp.positionStart && this.positionStart == updateOp.itemCount) {
return true;
}
if (this.itemCount != updateOp.itemCount) {
return false;
}
if (this.positionStart != updateOp.positionStart) {
return false;
}
if (this.payload != null) {
if (this.payload.equals(updateOp.payload)) {
return true;
}
return false;
} else if (updateOp.payload != null) {
return false;
} else {
return true;
}
}
public String toString() {
return Integer.toHexString(System.identityHashCode(this)) + "[" + cmdToString() + z[5] + this.positionStart + z[7] + this.itemCount + z[6] + this.payload + "]";
}
public int hashCode() {
return (((this.cmd * 31) + this.positionStart) * 31) + this.itemCount;
}
}
static {
String[] strArr = new String[4];
String str = "{G\teal\u000f\b\u007fy(K\u000fc}i[\u0005x-iK\u00020bz\u000f\u000b\u007f{m\u000f\u0000\u007f\u007f(_\u0014u-dN\u001f\u007fx|";
Object obj = -1;
String[] strArr2 = strArr;
String[] strArr3 = strArr;
int i = 0;
while (true) {
char[] toCharArray = str.toCharArray();
int length = toCharArray.length;
char[] cArr = toCharArray;
for (int i2 = 0; length > i2; i2++) {
int i3;
char c = cArr[i2];
switch (i2 % 5) {
case v.m /*0*/:
i3 = 8;
break;
case at.g /*1*/:
i3 = 47;
break;
case at.i /*2*/:
i3 = arj.Theme_checkboxStyle;
break;
case at.o /*3*/:
i3 = 16;
break;
default:
i3 = 13;
break;
}
cArr[i2] = (char) (i3 ^ c);
}
str = new String(cArr).intern();
switch (obj) {
case v.m /*0*/:
strArr2[i] = str;
str = "gA\ni-zJ\u000b\u007f{m\u000f\u0007~i(Z\u0016tl|JF\u007f}{\u000f\u0005qc(M\u00030ia\\\u0016qykG\u0003t-aAFvdz\\\u00120}i\\\u0015";
i = 2;
strArr2 = strArr3;
obj = 1;
break;
case at.g /*1*/:
strArr2[i] = str;
i = 3;
strArr2 = strArr3;
str = "]A\r~b\u007fAFe}lN\u0012u-g_FdtxJFvbz\u000f";
obj = 2;
break;
case at.i /*2*/:
strArr2[i] = str;
z = strArr3;
return;
default:
strArr2[i] = str;
str = "g_FcegZ\nt-jJFbhe@\u0010u-g]Fe}lN\u0012u#";
i = 1;
strArr2 = strArr3;
obj = null;
break;
}
}
}
/* JADX WARNING: inconsistent code. */
/* Code decompiled incorrectly, please refer to instructions dump. */
void consumeUpdatesInOnePass() {
/*
r9 = this;
r2 = 0;
r3 = android.support.v7.widget.RecyclerView.ViewHolder.a;
r9.consumePostponedUpdates();
r0 = r9.mPendingUpdates;
r4 = r0.size();
r1 = r2;
L_0x000d:
if (r1 >= r4) goto L_0x0029;
L_0x000f:
r0 = r9.mPendingUpdates;
r0 = r0.get(r1);
r0 = (android.support.v7.widget.AdapterHelper.UpdateOp) r0;
r5 = r0.cmd; Catch:{ IllegalArgumentException -> 0x0074 }
switch(r5) {
case 1: goto L_0x0031;
case 2: goto L_0x0041;
case 3: goto L_0x001c;
case 4: goto L_0x0051;
case 5: goto L_0x001c;
case 6: goto L_0x001c;
case 7: goto L_0x001c;
case 8: goto L_0x0063;
default: goto L_0x001c;
};
L_0x001c:
r0 = r9.mOnItemProcessedCallback; Catch:{ IllegalArgumentException -> 0x007a }
if (r0 == 0) goto L_0x0025;
L_0x0020:
r0 = r9.mOnItemProcessedCallback; Catch:{ IllegalArgumentException -> 0x007a }
r0.run(); Catch:{ IllegalArgumentException -> 0x007a }
L_0x0025:
r0 = r1 + 1;
if (r3 == 0) goto L_0x007c;
L_0x0029:
r0 = r9.mPendingUpdates;
r9.recycleUpdateOpsAndClearList(r0);
r9.mExistingUpdateTypes = r2;
return;
L_0x0031:
r5 = r9.mCallback; Catch:{ IllegalArgumentException -> 0x0076 }
r5.onDispatchSecondPass(r0); Catch:{ IllegalArgumentException -> 0x0076 }
r5 = r9.mCallback; Catch:{ IllegalArgumentException -> 0x0076 }
r6 = r0.positionStart; Catch:{ IllegalArgumentException -> 0x0076 }
r7 = r0.itemCount; Catch:{ IllegalArgumentException -> 0x0076 }
r5.offsetPositionsForAdd(r6, r7); Catch:{ IllegalArgumentException -> 0x0076 }
if (r3 == 0) goto L_0x001c;
L_0x0041:
r5 = r9.mCallback; Catch:{ IllegalArgumentException -> 0x0078 }
r5.onDispatchSecondPass(r0); Catch:{ IllegalArgumentException -> 0x0078 }
r5 = r9.mCallback; Catch:{ IllegalArgumentException -> 0x0078 }
r6 = r0.positionStart; Catch:{ IllegalArgumentException -> 0x0078 }
r7 = r0.itemCount; Catch:{ IllegalArgumentException -> 0x0078 }
r5.offsetPositionsForRemovingInvisible(r6, r7); Catch:{ IllegalArgumentException -> 0x0078 }
if (r3 == 0) goto L_0x001c;
L_0x0051:
r5 = r9.mCallback; Catch:{ IllegalArgumentException -> 0x0072 }
r5.onDispatchSecondPass(r0); Catch:{ IllegalArgumentException -> 0x0072 }
r5 = r9.mCallback; Catch:{ IllegalArgumentException -> 0x0072 }
r6 = r0.positionStart; Catch:{ IllegalArgumentException -> 0x0072 }
r7 = r0.itemCount; Catch:{ IllegalArgumentException -> 0x0072 }
r8 = r0.payload; Catch:{ IllegalArgumentException -> 0x0072 }
r5.markViewHoldersUpdated(r6, r7, r8); Catch:{ IllegalArgumentException -> 0x0072 }
if (r3 == 0) goto L_0x001c;
L_0x0063:
r5 = r9.mCallback; Catch:{ IllegalArgumentException -> 0x0072 }
r5.onDispatchSecondPass(r0); Catch:{ IllegalArgumentException -> 0x0072 }
r5 = r9.mCallback; Catch:{ IllegalArgumentException -> 0x0072 }
r6 = r0.positionStart; Catch:{ IllegalArgumentException -> 0x0072 }
r0 = r0.itemCount; Catch:{ IllegalArgumentException -> 0x0072 }
r5.offsetPositionsForMove(r6, r0); Catch:{ IllegalArgumentException -> 0x0072 }
goto L_0x001c;
L_0x0072:
r0 = move-exception;
throw r0;
L_0x0074:
r0 = move-exception;
throw r0; Catch:{ IllegalArgumentException -> 0x0076 }
L_0x0076:
r0 = move-exception;
throw r0; Catch:{ IllegalArgumentException -> 0x0078 }
L_0x0078:
r0 = move-exception;
throw r0; Catch:{ IllegalArgumentException -> 0x0072 }
L_0x007a:
r0 = move-exception;
throw r0;
L_0x007c:
r1 = r0;
goto L_0x000d;
*/
throw new UnsupportedOperationException("Method not decompiled: android.support.v7.widget.AdapterHelper.consumeUpdatesInOnePass():void");
}
void recycleUpdateOpsAndClearList(List list) {
int i = ViewHolder.a;
int size = list.size();
int i2 = 0;
while (i2 < size) {
recycleUpdateOp((UpdateOp) list.get(i2));
int i3 = i2 + 1;
if (i != 0) {
break;
}
i2 = i3;
}
list.clear();
}
AdapterHelper(Callback callback) {
this(callback, false);
}
private void applyMove(UpdateOp updateOp) {
postponeAndUpdateViewHolders(updateOp);
}
/* JADX WARNING: inconsistent code. */
/* Code decompiled incorrectly, please refer to instructions dump. */
private void applyUpdate(android.support.v7.widget.AdapterHelper.UpdateOp r12) {
/*
r11 = this;
r5 = 1;
r9 = 4;
r1 = 0;
r6 = android.support.v7.widget.RecyclerView.ViewHolder.a;
r2 = r12.positionStart;
r0 = r12.positionStart;
r3 = r12.itemCount;
r7 = r0 + r3;
r4 = -1;
r3 = r12.positionStart;
r0 = r1;
L_0x0011:
if (r3 >= r7) goto L_0x006e;
L_0x0013:
r8 = r11.mCallback;
r8 = r8.findViewHolder(r3);
if (r8 != 0) goto L_0x0021;
L_0x001b:
r8 = r11.canFindInPreLayout(r3); Catch:{ IllegalArgumentException -> 0x0061 }
if (r8 == 0) goto L_0x0031;
L_0x0021:
if (r4 != 0) goto L_0x002e;
L_0x0023:
r4 = r12.payload;
r0 = r11.obtainUpdateOp(r9, r2, r0, r4);
r11.dispatchAndUpdateViewHolders(r0);
r0 = r1;
r2 = r3;
L_0x002e:
if (r6 == 0) goto L_0x006a;
L_0x0030:
r4 = r5;
L_0x0031:
if (r4 != r5) goto L_0x003e;
L_0x0033:
r4 = r12.payload;
r0 = r11.obtainUpdateOp(r9, r2, r0, r4);
r11.postponeAndUpdateViewHolders(r0);
r0 = r1;
r2 = r3;
L_0x003e:
r4 = r2;
r2 = r0;
r0 = r1;
L_0x0041:
r2 = r2 + 1;
r3 = r3 + 1;
if (r6 == 0) goto L_0x0065;
L_0x0047:
r1 = r2;
r2 = r4;
L_0x0049:
r3 = r12.itemCount;
if (r1 == r3) goto L_0x0056;
L_0x004d:
r3 = r12.payload;
r11.recycleUpdateOp(r12);
r12 = r11.obtainUpdateOp(r9, r2, r1, r3);
L_0x0056:
if (r0 != 0) goto L_0x005d;
L_0x0058:
r11.dispatchAndUpdateViewHolders(r12); Catch:{ IllegalArgumentException -> 0x0063 }
if (r6 == 0) goto L_0x0060;
L_0x005d:
r11.postponeAndUpdateViewHolders(r12); Catch:{ IllegalArgumentException -> 0x0063 }
L_0x0060:
return;
L_0x0061:
r0 = move-exception;
throw r0;
L_0x0063:
r0 = move-exception;
throw r0;
L_0x0065:
r10 = r0;
r0 = r2;
r2 = r4;
r4 = r10;
goto L_0x0011;
L_0x006a:
r4 = r2;
r2 = r0;
r0 = r5;
goto L_0x0041;
L_0x006e:
r1 = r0;
r0 = r4;
goto L_0x0049;
*/
throw new UnsupportedOperationException("Method not decompiled: android.support.v7.widget.AdapterHelper.applyUpdate(android.support.v7.widget.AdapterHelper$UpdateOp):void");
}
boolean hasPendingUpdates() {
try {
return this.mPendingUpdates.size() > 0;
} catch (IllegalArgumentException e) {
throw e;
}
}
/* JADX WARNING: inconsistent code. */
/* Code decompiled incorrectly, please refer to instructions dump. */
void dispatchFirstPassAndUpdateViewHolders(android.support.v7.widget.AdapterHelper.UpdateOp r5, int r6) {
/*
r4 = this;
r0 = android.support.v7.widget.RecyclerView.ViewHolder.a;
r1 = r4.mCallback; Catch:{ IllegalArgumentException -> 0x002e }
r1.onDispatchFirstPass(r5); Catch:{ IllegalArgumentException -> 0x002e }
r1 = r5.cmd; Catch:{ IllegalArgumentException -> 0x002e }
switch(r1) {
case 2: goto L_0x0019;
case 3: goto L_0x000c;
case 4: goto L_0x0022;
default: goto L_0x000c;
};
L_0x000c:
r0 = new java.lang.IllegalArgumentException; Catch:{ IllegalArgumentException -> 0x0017 }
r1 = z; Catch:{ IllegalArgumentException -> 0x0017 }
r2 = 2;
r1 = r1[r2]; Catch:{ IllegalArgumentException -> 0x0017 }
r0.<init>(r1); Catch:{ IllegalArgumentException -> 0x0017 }
throw r0; Catch:{ IllegalArgumentException -> 0x0017 }
L_0x0017:
r0 = move-exception;
throw r0;
L_0x0019:
r1 = r4.mCallback; Catch:{ IllegalArgumentException -> 0x0030 }
r2 = r5.itemCount; Catch:{ IllegalArgumentException -> 0x0030 }
r1.offsetPositionsForRemovingInvisible(r6, r2); Catch:{ IllegalArgumentException -> 0x0030 }
if (r0 == 0) goto L_0x002d;
L_0x0022:
r1 = r4.mCallback; Catch:{ IllegalArgumentException -> 0x0017 }
r2 = r5.itemCount; Catch:{ IllegalArgumentException -> 0x0017 }
r3 = r5.payload; Catch:{ IllegalArgumentException -> 0x0017 }
r1.markViewHoldersUpdated(r6, r2, r3); Catch:{ IllegalArgumentException -> 0x0017 }
if (r0 != 0) goto L_0x000c;
L_0x002d:
return;
L_0x002e:
r0 = move-exception;
throw r0; Catch:{ IllegalArgumentException -> 0x0030 }
L_0x0030:
r0 = move-exception;
throw r0; Catch:{ IllegalArgumentException -> 0x0017 }
*/
throw new UnsupportedOperationException("Method not decompiled: android.support.v7.widget.AdapterHelper.dispatchFirstPassAndUpdateViewHolders(android.support.v7.widget.AdapterHelper$UpdateOp, int):void");
}
AdapterHelper(Callback callback, boolean z) {
this.mUpdateOpPool = new SimplePool(30);
this.mPendingUpdates = new ArrayList();
this.mPostponedList = new ArrayList();
this.mExistingUpdateTypes = 0;
this.mCallback = callback;
this.mDisableRecycler = z;
this.mOpReorderer = new OpReorderer(this);
}
/* JADX WARNING: inconsistent code. */
/* Code decompiled incorrectly, please refer to instructions dump. */
public android.support.v7.widget.AdapterHelper.UpdateOp obtainUpdateOp(int r3, int r4, int r5, java.lang.Object r6) {
/*
r2 = this;
r0 = r2.mUpdateOpPool;
r0 = r0.acquire();
r0 = (android.support.v7.widget.AdapterHelper.UpdateOp) r0;
if (r0 != 0) goto L_0x0013;
L_0x000a:
r0 = new android.support.v7.widget.AdapterHelper$UpdateOp;
r0.<init>(r3, r4, r5, r6);
r1 = android.support.v7.widget.RecyclerView.ViewHolder.a; Catch:{ IllegalArgumentException -> 0x001c }
if (r1 == 0) goto L_0x001b;
L_0x0013:
r0.cmd = r3; Catch:{ IllegalArgumentException -> 0x001c }
r0.positionStart = r4; Catch:{ IllegalArgumentException -> 0x001c }
r0.itemCount = r5; Catch:{ IllegalArgumentException -> 0x001c }
r0.payload = r6; Catch:{ IllegalArgumentException -> 0x001c }
L_0x001b:
return r0;
L_0x001c:
r0 = move-exception;
throw r0;
*/
throw new UnsupportedOperationException("Method not decompiled: android.support.v7.widget.AdapterHelper.obtainUpdateOp(int, int, int, java.lang.Object):android.support.v7.widget.AdapterHelper$UpdateOp");
}
/* JADX WARNING: inconsistent code. */
/* Code decompiled incorrectly, please refer to instructions dump. */
public int applyPendingUpdatesToPosition(int r8) {
/*
r7 = this;
r3 = android.support.v7.widget.RecyclerView.ViewHolder.a;
r0 = r7.mPendingUpdates;
r4 = r0.size();
r0 = 0;
r2 = r0;
r1 = r8;
L_0x000b:
if (r2 >= r4) goto L_0x005e;
L_0x000d:
r0 = r7.mPendingUpdates;
r0 = r0.get(r2);
r0 = (android.support.v7.widget.AdapterHelper.UpdateOp) r0;
r5 = r0.cmd; Catch:{ IllegalArgumentException -> 0x0036 }
switch(r5) {
case 1: goto L_0x0020;
case 2: goto L_0x0029;
case 8: goto L_0x003f;
default: goto L_0x001a;
}; Catch:{ IllegalArgumentException -> 0x0036 }
L_0x001a:
r0 = r1;
L_0x001b:
r1 = r2 + 1;
if (r3 == 0) goto L_0x005b;
L_0x001f:
return r0;
L_0x0020:
r5 = r0.positionStart; Catch:{ IllegalArgumentException -> 0x0036 }
if (r5 > r1) goto L_0x001a;
L_0x0024:
r5 = r0.itemCount;
r1 = r1 + r5;
if (r3 == 0) goto L_0x001a;
L_0x0029:
r5 = r0.positionStart; Catch:{ IllegalArgumentException -> 0x0038 }
if (r5 > r1) goto L_0x001a;
L_0x002d:
r5 = r0.positionStart;
r6 = r0.itemCount;
r5 = r5 + r6;
if (r5 <= r1) goto L_0x003a;
L_0x0034:
r0 = -1;
goto L_0x001f;
L_0x0036:
r0 = move-exception;
throw r0;
L_0x0038:
r0 = move-exception;
throw r0;
L_0x003a:
r5 = r0.itemCount;
r1 = r1 - r5;
if (r3 == 0) goto L_0x001a;
L_0x003f:
r5 = r0.positionStart; Catch:{ IllegalArgumentException -> 0x0055 }
if (r5 != r1) goto L_0x0047;
L_0x0043:
r1 = r0.itemCount;
if (r3 == 0) goto L_0x001a;
L_0x0047:
r5 = r0.positionStart; Catch:{ IllegalArgumentException -> 0x0057 }
if (r5 >= r1) goto L_0x004d;
L_0x004b:
r1 = r1 + -1;
L_0x004d:
r0 = r0.itemCount; Catch:{ IllegalArgumentException -> 0x0059 }
if (r0 > r1) goto L_0x001a;
L_0x0051:
r1 = r1 + 1;
r0 = r1;
goto L_0x001b;
L_0x0055:
r0 = move-exception;
throw r0;
L_0x0057:
r0 = move-exception;
throw r0;
L_0x0059:
r0 = move-exception;
throw r0;
L_0x005b:
r2 = r1;
r1 = r0;
goto L_0x000b;
L_0x005e:
r0 = r1;
goto L_0x001f;
*/
throw new UnsupportedOperationException("Method not decompiled: android.support.v7.widget.AdapterHelper.applyPendingUpdatesToPosition(int):int");
}
/* JADX WARNING: inconsistent code. */
/* Code decompiled incorrectly, please refer to instructions dump. */
private void dispatchAndUpdateViewHolders(android.support.v7.widget.AdapterHelper.UpdateOp r12) {
/*
r11 = this;
r2 = 0;
r1 = 1;
r9 = android.support.v7.widget.RecyclerView.ViewHolder.a;
r0 = r12.cmd; Catch:{ IllegalArgumentException -> 0x001b }
if (r0 == r1) goto L_0x000e;
L_0x0008:
r0 = r12.cmd; Catch:{ IllegalArgumentException -> 0x0019 }
r3 = 8;
if (r0 != r3) goto L_0x001d;
L_0x000e:
r0 = new java.lang.IllegalArgumentException; Catch:{ IllegalArgumentException -> 0x0019 }
r1 = z; Catch:{ IllegalArgumentException -> 0x0019 }
r2 = 0;
r1 = r1[r2]; Catch:{ IllegalArgumentException -> 0x0019 }
r0.<init>(r1); Catch:{ IllegalArgumentException -> 0x0019 }
throw r0; Catch:{ IllegalArgumentException -> 0x0019 }
L_0x0019:
r0 = move-exception;
throw r0;
L_0x001b:
r0 = move-exception;
throw r0; Catch:{ IllegalArgumentException -> 0x0019 }
L_0x001d:
r0 = r12.positionStart;
r3 = r12.cmd;
r4 = r11.updatePositionWithPostponed(r0, r3);
r3 = r12.positionStart;
r0 = r12.cmd;
switch(r0) {
case 2: goto L_0x004c;
case 3: goto L_0x002c;
case 4: goto L_0x004a;
default: goto L_0x002c;
};
L_0x002c:
r0 = new java.lang.IllegalArgumentException; Catch:{ IllegalArgumentException -> 0x0048 }
r1 = new java.lang.StringBuilder; Catch:{ IllegalArgumentException -> 0x0048 }
r1.<init>(); Catch:{ IllegalArgumentException -> 0x0048 }
r2 = z; Catch:{ IllegalArgumentException -> 0x0048 }
r3 = 1;
r2 = r2[r3]; Catch:{ IllegalArgumentException -> 0x0048 }
r1 = r1.append(r2); Catch:{ IllegalArgumentException -> 0x0048 }
r1 = r1.append(r12); Catch:{ IllegalArgumentException -> 0x0048 }
r1 = r1.toString(); Catch:{ IllegalArgumentException -> 0x0048 }
r0.<init>(r1); Catch:{ IllegalArgumentException -> 0x0048 }
throw r0; Catch:{ IllegalArgumentException -> 0x0048 }
L_0x0048:
r0 = move-exception;
throw r0;
L_0x004a:
if (r9 == 0) goto L_0x00af;
L_0x004c:
if (r9 != 0) goto L_0x002c;
L_0x004e:
r0 = r2;
L_0x004f:
r5 = r1;
r6 = r4;
r4 = r3;
r3 = r1;
L_0x0053:
r7 = r12.itemCount;
if (r3 >= r7) goto L_0x0088;
L_0x0057:
r7 = r12.positionStart;
r8 = r0 * r3;
r7 = r7 + r8;
r8 = r12.cmd;
r8 = r11.updatePositionWithPostponed(r7, r8);
r7 = r12.cmd; Catch:{ IllegalArgumentException -> 0x00a7 }
switch(r7) {
case 2: goto L_0x00a3;
case 3: goto L_0x0067;
case 4: goto L_0x009c;
default: goto L_0x0067;
};
L_0x0067:
r7 = r2;
L_0x0068:
if (r7 == 0) goto L_0x006e;
L_0x006a:
r5 = r5 + 1;
if (r9 == 0) goto L_0x0084;
L_0x006e:
r7 = r12.cmd;
r10 = r12.payload;
r6 = r11.obtainUpdateOp(r7, r6, r5, r10);
r11.dispatchFirstPassAndUpdateViewHolders(r6, r4);
r11.recycleUpdateOp(r6);
r6 = r12.cmd;
r7 = 4;
if (r6 != r7) goto L_0x0082;
L_0x0081:
r4 = r4 + r5;
L_0x0082:
r5 = r1;
r6 = r8;
L_0x0084:
r3 = r3 + 1;
if (r9 == 0) goto L_0x0053;
L_0x0088:
r0 = r12.payload;
r11.recycleUpdateOp(r12);
if (r5 <= 0) goto L_0x009b;
L_0x008f:
r1 = r12.cmd;
r0 = r11.obtainUpdateOp(r1, r6, r5, r0);
r11.dispatchFirstPassAndUpdateViewHolders(r0, r4);
r11.recycleUpdateOp(r0);
L_0x009b:
return;
L_0x009c:
r7 = r6 + 1;
if (r8 != r7) goto L_0x00ab;
L_0x00a0:
r7 = r1;
L_0x00a1:
if (r9 == 0) goto L_0x0068;
L_0x00a3:
if (r8 != r6) goto L_0x00ad;
L_0x00a5:
r7 = r1;
goto L_0x0068;
L_0x00a7:
r0 = move-exception;
throw r0; Catch:{ IllegalArgumentException -> 0x00a9 }
L_0x00a9:
r0 = move-exception;
throw r0;
L_0x00ab:
r7 = r2;
goto L_0x00a1;
L_0x00ad:
r7 = r2;
goto L_0x0068;
L_0x00af:
r0 = r1;
goto L_0x004f;
*/
throw new UnsupportedOperationException("Method not decompiled: android.support.v7.widget.AdapterHelper.dispatchAndUpdateViewHolders(android.support.v7.widget.AdapterHelper$UpdateOp):void");
}
/* JADX WARNING: inconsistent code. */
/* Code decompiled incorrectly, please refer to instructions dump. */
void preProcess() {
/*
r5 = this;
r2 = android.support.v7.widget.RecyclerView.ViewHolder.a;
r0 = r5.mOpReorderer;
r1 = r5.mPendingUpdates;
r0.reorderOps(r1);
r0 = r5.mPendingUpdates;
r3 = r0.size();
r0 = 0;
r1 = r0;
L_0x0011:
if (r1 >= r3) goto L_0x002d;
L_0x0013:
r0 = r5.mPendingUpdates;
r0 = r0.get(r1);
r0 = (android.support.v7.widget.AdapterHelper.UpdateOp) r0;
r4 = r0.cmd; Catch:{ IllegalArgumentException -> 0x0048 }
switch(r4) {
case 1: goto L_0x0033;
case 2: goto L_0x0038;
case 3: goto L_0x0020;
case 4: goto L_0x003d;
case 5: goto L_0x0020;
case 6: goto L_0x0020;
case 7: goto L_0x0020;
case 8: goto L_0x0042;
default: goto L_0x0020;
};
L_0x0020:
r0 = r5.mOnItemProcessedCallback; Catch:{ IllegalArgumentException -> 0x004e }
if (r0 == 0) goto L_0x0029;
L_0x0024:
r0 = r5.mOnItemProcessedCallback; Catch:{ IllegalArgumentException -> 0x004e }
r0.run(); Catch:{ IllegalArgumentException -> 0x004e }
L_0x0029:
r0 = r1 + 1;
if (r2 == 0) goto L_0x0050;
L_0x002d:
r0 = r5.mPendingUpdates;
r0.clear();
return;
L_0x0033:
r5.applyAdd(r0); Catch:{ IllegalArgumentException -> 0x004a }
if (r2 == 0) goto L_0x0020;
L_0x0038:
r5.applyRemove(r0); Catch:{ IllegalArgumentException -> 0x004c }
if (r2 == 0) goto L_0x0020;
L_0x003d:
r5.applyUpdate(r0); Catch:{ IllegalArgumentException -> 0x0046 }
if (r2 == 0) goto L_0x0020;
L_0x0042:
r5.applyMove(r0); Catch:{ IllegalArgumentException -> 0x0046 }
goto L_0x0020;
L_0x0046:
r0 = move-exception;
throw r0;
L_0x0048:
r0 = move-exception;
throw r0; Catch:{ IllegalArgumentException -> 0x004a }
L_0x004a:
r0 = move-exception;
throw r0; Catch:{ IllegalArgumentException -> 0x004c }
L_0x004c:
r0 = move-exception;
throw r0; Catch:{ IllegalArgumentException -> 0x0046 }
L_0x004e:
r0 = move-exception;
throw r0;
L_0x0050:
r1 = r0;
goto L_0x0011;
*/
throw new UnsupportedOperationException("Method not decompiled: android.support.v7.widget.AdapterHelper.preProcess():void");
}
void reset() {
recycleUpdateOpsAndClearList(this.mPendingUpdates);
recycleUpdateOpsAndClearList(this.mPostponedList);
this.mExistingUpdateTypes = 0;
}
/* JADX WARNING: inconsistent code. */
/* Code decompiled incorrectly, please refer to instructions dump. */
private int updatePositionWithPostponed(int r10, int r11) {
/*
r9 = this;
r8 = 8;
r7 = 2;
r6 = 1;
r5 = android.support.v7.widget.RecyclerView.ViewHolder.a;
r0 = r9.mPostponedList;
r0 = r0.size();
r0 = r0 + -1;
r4 = r0;
r1 = r10;
L_0x0010:
if (r4 < 0) goto L_0x00b4;
L_0x0012:
r0 = r9.mPostponedList;
r0 = r0.get(r4);
r0 = (android.support.v7.widget.AdapterHelper.UpdateOp) r0;
r2 = r0.cmd; Catch:{ IllegalArgumentException -> 0x00f0 }
if (r2 != r8) goto L_0x0086;
L_0x001e:
r2 = r0.positionStart; Catch:{ IllegalArgumentException -> 0x00f0 }
r3 = r0.itemCount; Catch:{ IllegalArgumentException -> 0x00f0 }
if (r2 >= r3) goto L_0x002a;
L_0x0024:
r3 = r0.positionStart;
r2 = r0.itemCount;
if (r5 == 0) goto L_0x002e;
L_0x002a:
r3 = r0.itemCount;
r2 = r0.positionStart;
L_0x002e:
if (r1 < r3) goto L_0x0062;
L_0x0030:
if (r1 > r2) goto L_0x0062;
L_0x0032:
r2 = r0.positionStart; Catch:{ IllegalArgumentException -> 0x00f2 }
if (r3 != r2) goto L_0x004c;
L_0x0036:
if (r11 != r6) goto L_0x0040;
L_0x0038:
r2 = r0.itemCount; Catch:{ IllegalArgumentException -> 0x00f6 }
r2 = r2 + 1;
r0.itemCount = r2; Catch:{ IllegalArgumentException -> 0x00f6 }
if (r5 == 0) goto L_0x0048;
L_0x0040:
if (r11 != r7) goto L_0x0048;
L_0x0042:
r2 = r0.itemCount; Catch:{ IllegalArgumentException -> 0x00f8 }
r2 = r2 + -1;
r0.itemCount = r2; Catch:{ IllegalArgumentException -> 0x00f8 }
L_0x0048:
r1 = r1 + 1;
if (r5 == 0) goto L_0x0084;
L_0x004c:
if (r11 != r6) goto L_0x0056;
L_0x004e:
r2 = r0.positionStart; Catch:{ IllegalArgumentException -> 0x00fa }
r2 = r2 + 1;
r0.positionStart = r2; Catch:{ IllegalArgumentException -> 0x00fa }
if (r5 == 0) goto L_0x005e;
L_0x0056:
if (r11 != r7) goto L_0x005e;
L_0x0058:
r2 = r0.positionStart; Catch:{ IllegalArgumentException -> 0x00fc }
r2 = r2 + -1;
r0.positionStart = r2; Catch:{ IllegalArgumentException -> 0x00fc }
L_0x005e:
r1 = r1 + -1;
if (r5 == 0) goto L_0x0084;
L_0x0062:
r2 = r0.positionStart; Catch:{ IllegalArgumentException -> 0x00fe }
if (r1 >= r2) goto L_0x0084;
L_0x0066:
if (r11 != r6) goto L_0x0076;
L_0x0068:
r2 = r0.positionStart; Catch:{ IllegalArgumentException -> 0x0102 }
r2 = r2 + 1;
r0.positionStart = r2; Catch:{ IllegalArgumentException -> 0x0102 }
r2 = r0.itemCount; Catch:{ IllegalArgumentException -> 0x0102 }
r2 = r2 + 1;
r0.itemCount = r2; Catch:{ IllegalArgumentException -> 0x0102 }
if (r5 == 0) goto L_0x0084;
L_0x0076:
if (r11 != r7) goto L_0x0084;
L_0x0078:
r2 = r0.positionStart; Catch:{ IllegalArgumentException -> 0x0104 }
r2 = r2 + -1;
r0.positionStart = r2; Catch:{ IllegalArgumentException -> 0x0104 }
r2 = r0.itemCount; Catch:{ IllegalArgumentException -> 0x0104 }
r2 = r2 + -1;
r0.itemCount = r2; Catch:{ IllegalArgumentException -> 0x0104 }
L_0x0084:
if (r5 == 0) goto L_0x011e;
L_0x0086:
r2 = r0.positionStart; Catch:{ IllegalArgumentException -> 0x0106 }
if (r2 > r1) goto L_0x009c;
L_0x008a:
r2 = r0.cmd; Catch:{ IllegalArgumentException -> 0x0106 }
if (r2 != r6) goto L_0x0093;
L_0x008e:
r2 = r0.itemCount;
r1 = r1 - r2;
if (r5 == 0) goto L_0x011e;
L_0x0093:
r2 = r0.cmd; Catch:{ IllegalArgumentException -> 0x0108 }
if (r2 != r7) goto L_0x011e;
L_0x0097:
r2 = r0.itemCount;
r1 = r1 + r2;
if (r5 == 0) goto L_0x011e;
L_0x009c:
if (r11 != r6) goto L_0x00a6;
L_0x009e:
r2 = r0.positionStart; Catch:{ IllegalArgumentException -> 0x010a }
r2 = r2 + 1;
r0.positionStart = r2; Catch:{ IllegalArgumentException -> 0x010a }
if (r5 == 0) goto L_0x011e;
L_0x00a6:
if (r11 != r7) goto L_0x011e;
L_0x00a8:
r2 = r0.positionStart; Catch:{ IllegalArgumentException -> 0x010c }
r2 = r2 + -1;
r0.positionStart = r2; Catch:{ IllegalArgumentException -> 0x010c }
r0 = r1;
L_0x00af:
r1 = r4 + -1;
if (r5 == 0) goto L_0x011a;
L_0x00b3:
r1 = r0;
L_0x00b4:
r0 = r9.mPostponedList;
r0 = r0.size();
r0 = r0 + -1;
r2 = r0;
L_0x00bd:
if (r2 < 0) goto L_0x00ef;
L_0x00bf:
r0 = r9.mPostponedList;
r0 = r0.get(r2);
r0 = (android.support.v7.widget.AdapterHelper.UpdateOp) r0;
r3 = r0.cmd; Catch:{ IllegalArgumentException -> 0x010e }
if (r3 != r8) goto L_0x00df;
L_0x00cb:
r3 = r0.itemCount; Catch:{ IllegalArgumentException -> 0x0110 }
r4 = r0.positionStart; Catch:{ IllegalArgumentException -> 0x0110 }
if (r3 == r4) goto L_0x00d5;
L_0x00d1:
r3 = r0.itemCount; Catch:{ IllegalArgumentException -> 0x0112 }
if (r3 >= 0) goto L_0x00eb;
L_0x00d5:
r3 = r9.mPostponedList; Catch:{ IllegalArgumentException -> 0x0114 }
r3.remove(r2); Catch:{ IllegalArgumentException -> 0x0114 }
r9.recycleUpdateOp(r0); Catch:{ IllegalArgumentException -> 0x0114 }
if (r5 == 0) goto L_0x00eb;
L_0x00df:
r3 = r0.itemCount; Catch:{ IllegalArgumentException -> 0x0116 }
if (r3 > 0) goto L_0x00eb;
L_0x00e3:
r3 = r9.mPostponedList; Catch:{ IllegalArgumentException -> 0x0116 }
r3.remove(r2); Catch:{ IllegalArgumentException -> 0x0116 }
r9.recycleUpdateOp(r0); Catch:{ IllegalArgumentException -> 0x0116 }
L_0x00eb:
r0 = r2 + -1;
if (r5 == 0) goto L_0x0118;
L_0x00ef:
return r1;
L_0x00f0:
r0 = move-exception;
throw r0;
L_0x00f2:
r0 = move-exception;
throw r0; Catch:{ IllegalArgumentException -> 0x00f4 }
L_0x00f4:
r0 = move-exception;
throw r0; Catch:{ IllegalArgumentException -> 0x00f6 }
L_0x00f6:
r0 = move-exception;
throw r0; Catch:{ IllegalArgumentException -> 0x00f8 }
L_0x00f8:
r0 = move-exception;
throw r0;
L_0x00fa:
r0 = move-exception;
throw r0; Catch:{ IllegalArgumentException -> 0x00fc }
L_0x00fc:
r0 = move-exception;
throw r0;
L_0x00fe:
r0 = move-exception;
throw r0; Catch:{ IllegalArgumentException -> 0x0100 }
L_0x0100:
r0 = move-exception;
throw r0; Catch:{ IllegalArgumentException -> 0x0102 }
L_0x0102:
r0 = move-exception;
throw r0; Catch:{ IllegalArgumentException -> 0x0104 }
L_0x0104:
r0 = move-exception;
throw r0;
L_0x0106:
r0 = move-exception;
throw r0;
L_0x0108:
r0 = move-exception;
throw r0;
L_0x010a:
r0 = move-exception;
throw r0; Catch:{ IllegalArgumentException -> 0x010c }
L_0x010c:
r0 = move-exception;
throw r0;
L_0x010e:
r0 = move-exception;
throw r0; Catch:{ IllegalArgumentException -> 0x0110 }
L_0x0110:
r0 = move-exception;
throw r0; Catch:{ IllegalArgumentException -> 0x0112 }
L_0x0112:
r0 = move-exception;
throw r0; Catch:{ IllegalArgumentException -> 0x0114 }
L_0x0114:
r0 = move-exception;
throw r0; Catch:{ IllegalArgumentException -> 0x0116 }
L_0x0116:
r0 = move-exception;
throw r0;
L_0x0118:
r2 = r0;
goto L_0x00bd;
L_0x011a:
r4 = r1;
r1 = r0;
goto L_0x0010;
L_0x011e:
r0 = r1;
goto L_0x00af;
*/
throw new UnsupportedOperationException("Method not decompiled: android.support.v7.widget.AdapterHelper.updatePositionWithPostponed(int, int):int");
}
private boolean canFindInPreLayout(int i) {
int i2 = ViewHolder.a;
int size = this.mPostponedList.size();
int i3 = 0;
while (i3 < size) {
UpdateOp updateOp = (UpdateOp) this.mPostponedList.get(i3);
try {
int i4;
if (updateOp.cmd == 8) {
if (findPositionOffset(updateOp.itemCount, i3 + 1) == i) {
return true;
}
} else if (updateOp.cmd == 1) {
int i5 = updateOp.positionStart + updateOp.itemCount;
i4 = updateOp.positionStart;
while (i4 < i5) {
try {
if (findPositionOffset(i4, i3 + 1) != i) {
i4++;
if (i2 != 0) {
break;
}
}
return true;
} catch (IllegalArgumentException e) {
throw e;
}
}
}
i4 = i3 + 1;
if (i2 != 0) {
break;
}
i3 = i4;
} catch (IllegalArgumentException e2) {
throw e2;
} catch (IllegalArgumentException e22) {
throw e22;
}
}
return false;
}
/* JADX WARNING: inconsistent code. */
/* Code decompiled incorrectly, please refer to instructions dump. */
int findPositionOffset(int r7, int r8) {
/*
r6 = this;
r2 = android.support.v7.widget.RecyclerView.ViewHolder.a;
r0 = r6.mPostponedList;
r3 = r0.size();
r1 = r7;
L_0x0009:
if (r8 >= r3) goto L_0x0066;
L_0x000b:
r0 = r6.mPostponedList;
r0 = r0.get(r8);
r0 = (android.support.v7.widget.AdapterHelper.UpdateOp) r0;
r4 = r0.cmd; Catch:{ IllegalArgumentException -> 0x0041 }
r5 = 8;
if (r4 != r5) goto L_0x002f;
L_0x0019:
r4 = r0.positionStart; Catch:{ IllegalArgumentException -> 0x0041 }
if (r4 != r1) goto L_0x0021;
L_0x001d:
r1 = r0.itemCount;
if (r2 == 0) goto L_0x0064;
L_0x0021:
r4 = r0.positionStart; Catch:{ IllegalArgumentException -> 0x0043 }
if (r4 >= r1) goto L_0x0027;
L_0x0025:
r1 = r1 + -1;
L_0x0027:
r4 = r0.itemCount; Catch:{ IllegalArgumentException -> 0x0045 }
if (r4 > r1) goto L_0x0064;
L_0x002b:
r1 = r1 + 1;
if (r2 == 0) goto L_0x0064;
L_0x002f:
r4 = r0.positionStart; Catch:{ IllegalArgumentException -> 0x0049 }
if (r4 > r1) goto L_0x0064;
L_0x0033:
r4 = r0.cmd; Catch:{ IllegalArgumentException -> 0x004b }
r5 = 2;
if (r4 != r5) goto L_0x0054;
L_0x0038:
r4 = r0.positionStart; Catch:{ IllegalArgumentException -> 0x004d }
r5 = r0.itemCount; Catch:{ IllegalArgumentException -> 0x004d }
r4 = r4 + r5;
if (r1 >= r4) goto L_0x004f;
L_0x003f:
r0 = -1;
L_0x0040:
return r0;
L_0x0041:
r0 = move-exception;
throw r0;
L_0x0043:
r0 = move-exception;
throw r0;
L_0x0045:
r0 = move-exception;
throw r0; Catch:{ IllegalArgumentException -> 0x0047 }
L_0x0047:
r0 = move-exception;
throw r0; Catch:{ IllegalArgumentException -> 0x0049 }
L_0x0049:
r0 = move-exception;
throw r0; Catch:{ IllegalArgumentException -> 0x004b }
L_0x004b:
r0 = move-exception;
throw r0; Catch:{ IllegalArgumentException -> 0x004d }
L_0x004d:
r0 = move-exception;
throw r0;
L_0x004f:
r4 = r0.itemCount;
r1 = r1 - r4;
if (r2 == 0) goto L_0x0064;
L_0x0054:
r4 = r0.cmd; Catch:{ IllegalArgumentException -> 0x0062 }
r5 = 1;
if (r4 != r5) goto L_0x0064;
L_0x0059:
r0 = r0.itemCount;
r0 = r0 + r1;
L_0x005c:
r8 = r8 + 1;
if (r2 != 0) goto L_0x0040;
L_0x0060:
r1 = r0;
goto L_0x0009;
L_0x0062:
r0 = move-exception;
throw r0;
L_0x0064:
r0 = r1;
goto L_0x005c;
L_0x0066:
r0 = r1;
goto L_0x0040;
*/
throw new UnsupportedOperationException("Method not decompiled: android.support.v7.widget.AdapterHelper.findPositionOffset(int, int):int");
}
boolean hasAnyUpdateTypes(int i) {
try {
return (this.mExistingUpdateTypes & i) != 0;
} catch (IllegalArgumentException e) {
throw e;
}
}
int findPositionOffset(int i) {
return findPositionOffset(i, 0);
}
void consumePostponedUpdates() {
int i = ViewHolder.a;
int size = this.mPostponedList.size();
int i2 = 0;
while (i2 < size) {
this.mCallback.onDispatchSecondPass((UpdateOp) this.mPostponedList.get(i2));
int i3 = i2 + 1;
if (i != 0) {
break;
}
i2 = i3;
}
recycleUpdateOpsAndClearList(this.mPostponedList);
this.mExistingUpdateTypes = 0;
}
private void applyRemove(UpdateOp updateOp) {
int i = ViewHolder.a;
int i2 = updateOp.positionStart;
int i3 = updateOp.positionStart + updateOp.itemCount;
Object obj = -1;
int i4 = updateOp.positionStart;
int i5 = 0;
while (i4 < i3) {
Object obj2;
int i6;
if (this.mCallback.findViewHolder(i4) == null) {
try {
if (!canFindInPreLayout(i4)) {
obj2 = obj;
obj = null;
if (obj2 == 1) {
postponeAndUpdateViewHolders(obtainUpdateOp(2, i2, i5, null));
obj = 1;
}
obj2 = null;
if (obj != null) {
i6 = i4 - i5;
i4 = i3 - i5;
if (i != 0) {
i3 = 1;
} else {
i5 = 1;
i6++;
if (i != 0) {
obj = obj2;
break;
}
i3 = i4;
i4 = i6;
obj = obj2;
}
} else {
i6 = i4;
i4 = i3;
i3 = i5;
}
i5 = i3 + 1;
i6++;
if (i != 0) {
obj = obj2;
break;
}
i3 = i4;
i4 = i6;
obj = obj2;
}
} catch (IllegalArgumentException e) {
throw e;
}
}
if (obj == null) {
dispatchAndUpdateViewHolders(obtainUpdateOp(2, i2, i5, null));
obj = 1;
} else {
obj = null;
}
if (i == 0) {
int i7 = 1;
if (obj != null) {
i6 = i4 - i5;
i4 = i3 - i5;
if (i != 0) {
i3 = 1;
} else {
i5 = 1;
i6++;
if (i != 0) {
obj = obj2;
break;
}
i3 = i4;
i4 = i6;
obj = obj2;
}
} else {
i6 = i4;
i4 = i3;
i3 = i5;
}
i5 = i3 + 1;
i6++;
if (i != 0) {
obj = obj2;
break;
}
i3 = i4;
i4 = i6;
obj = obj2;
} else {
obj2 = 1;
if (obj2 == 1) {
postponeAndUpdateViewHolders(obtainUpdateOp(2, i2, i5, null));
obj = 1;
}
obj2 = null;
if (obj != null) {
i6 = i4;
i4 = i3;
i3 = i5;
} else {
i6 = i4 - i5;
i4 = i3 - i5;
if (i != 0) {
i5 = 1;
i6++;
if (i != 0) {
obj = obj2;
break;
}
i3 = i4;
i4 = i6;
obj = obj2;
} else {
i3 = 1;
}
}
i5 = i3 + 1;
i6++;
if (i != 0) {
obj = obj2;
break;
}
i3 = i4;
i4 = i6;
obj = obj2;
}
}
if (i5 != updateOp.itemCount) {
recycleUpdateOp(updateOp);
updateOp = obtainUpdateOp(2, i2, i5, null);
}
if (obj == null) {
try {
dispatchAndUpdateViewHolders(updateOp);
if (i == 0) {
return;
}
} catch (IllegalArgumentException e2) {
throw e2;
}
}
postponeAndUpdateViewHolders(updateOp);
}
public void recycleUpdateOp(UpdateOp updateOp) {
try {
if (!this.mDisableRecycler) {
updateOp.payload = null;
this.mUpdateOpPool.release(updateOp);
}
} catch (IllegalArgumentException e) {
throw e;
}
}
private void applyAdd(UpdateOp updateOp) {
postponeAndUpdateViewHolders(updateOp);
}
/* JADX WARNING: inconsistent code. */
/* Code decompiled incorrectly, please refer to instructions dump. */
private void postponeAndUpdateViewHolders(android.support.v7.widget.AdapterHelper.UpdateOp r6) {
/*
r5 = this;
r0 = android.support.v7.widget.RecyclerView.ViewHolder.a;
r1 = r5.mPostponedList; Catch:{ IllegalArgumentException -> 0x0059 }
r1.add(r6); Catch:{ IllegalArgumentException -> 0x0059 }
r1 = r6.cmd; Catch:{ IllegalArgumentException -> 0x0059 }
switch(r1) {
case 1: goto L_0x002a;
case 2: goto L_0x0040;
case 3: goto L_0x000c;
case 4: goto L_0x004b;
case 5: goto L_0x000c;
case 6: goto L_0x000c;
case 7: goto L_0x000c;
case 8: goto L_0x0035;
default: goto L_0x000c;
};
L_0x000c:
r0 = new java.lang.IllegalArgumentException; Catch:{ IllegalArgumentException -> 0x0028 }
r1 = new java.lang.StringBuilder; Catch:{ IllegalArgumentException -> 0x0028 }
r1.<init>(); Catch:{ IllegalArgumentException -> 0x0028 }
r2 = z; Catch:{ IllegalArgumentException -> 0x0028 }
r3 = 3;
r2 = r2[r3]; Catch:{ IllegalArgumentException -> 0x0028 }
r1 = r1.append(r2); Catch:{ IllegalArgumentException -> 0x0028 }
r1 = r1.append(r6); Catch:{ IllegalArgumentException -> 0x0028 }
r1 = r1.toString(); Catch:{ IllegalArgumentException -> 0x0028 }
r0.<init>(r1); Catch:{ IllegalArgumentException -> 0x0028 }
throw r0; Catch:{ IllegalArgumentException -> 0x0028 }
L_0x0028:
r0 = move-exception;
throw r0;
L_0x002a:
r1 = r5.mCallback; Catch:{ IllegalArgumentException -> 0x005b }
r2 = r6.positionStart; Catch:{ IllegalArgumentException -> 0x005b }
r3 = r6.itemCount; Catch:{ IllegalArgumentException -> 0x005b }
r1.offsetPositionsForAdd(r2, r3); Catch:{ IllegalArgumentException -> 0x005b }
if (r0 == 0) goto L_0x0058;
L_0x0035:
r1 = r5.mCallback; Catch:{ IllegalArgumentException -> 0x005d }
r2 = r6.positionStart; Catch:{ IllegalArgumentException -> 0x005d }
r3 = r6.itemCount; Catch:{ IllegalArgumentException -> 0x005d }
r1.offsetPositionsForMove(r2, r3); Catch:{ IllegalArgumentException -> 0x005d }
if (r0 == 0) goto L_0x0058;
L_0x0040:
r1 = r5.mCallback; Catch:{ IllegalArgumentException -> 0x005f }
r2 = r6.positionStart; Catch:{ IllegalArgumentException -> 0x005f }
r3 = r6.itemCount; Catch:{ IllegalArgumentException -> 0x005f }
r1.offsetPositionsForRemovingLaidOutOrNewView(r2, r3); Catch:{ IllegalArgumentException -> 0x005f }
if (r0 == 0) goto L_0x0058;
L_0x004b:
r1 = r5.mCallback; Catch:{ IllegalArgumentException -> 0x0028 }
r2 = r6.positionStart; Catch:{ IllegalArgumentException -> 0x0028 }
r3 = r6.itemCount; Catch:{ IllegalArgumentException -> 0x0028 }
r4 = r6.payload; Catch:{ IllegalArgumentException -> 0x0028 }
r1.markViewHoldersUpdated(r2, r3, r4); Catch:{ IllegalArgumentException -> 0x0028 }
if (r0 != 0) goto L_0x000c;
L_0x0058:
return;
L_0x0059:
r0 = move-exception;
throw r0; Catch:{ IllegalArgumentException -> 0x005b }
L_0x005b:
r0 = move-exception;
throw r0; Catch:{ IllegalArgumentException -> 0x005d }
L_0x005d:
r0 = move-exception;
throw r0; Catch:{ IllegalArgumentException -> 0x005f }
L_0x005f:
r0 = move-exception;
throw r0; Catch:{ IllegalArgumentException -> 0x0028 }
*/
throw new UnsupportedOperationException("Method not decompiled: android.support.v7.widget.AdapterHelper.postponeAndUpdateViewHolders(android.support.v7.widget.AdapterHelper$UpdateOp):void");
}
}
| true |
ac229b80079fef5030c81fe43203c0aeaf95e85c | Java | matned666/TasksApp | /src/main/java/eu/mrndesign/matned/springApp/adapter/SqlProjectRepository.java | UTF-8 | 553 | 1.953125 | 2 | [] | no_license | package eu.mrndesign.matned.springApp.adapter;
import eu.mrndesign.matned.springApp.model.Project;
import eu.mrndesign.matned.springApp.model.repositories.ProjectRepository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface SqlProjectRepository extends ProjectRepository, JpaRepository<Project, Integer> {
@Override
@Query("from Project g")
List<Project> findAll();
}
| true |
4386af8ea45b237a9634e5c77acf4d216e3f3059 | Java | ECHT-zyyzyyzyy/hapiweb | /test_block/src/main/java/com/hapiweb/test_block/service/ServiceImpl/BlockServiceImpl.java | UTF-8 | 3,174 | 2.296875 | 2 | [
"Unlicense"
] | permissive | package com.hapiweb.test_block.service.ServiceImpl;
import com.hapiweb.test_block.JWT.UserLoginToken;
import com.hapiweb.test_block.dao.BlockMapper;
import com.hapiweb.test_block.dto.BlockDTO;
import com.hapiweb.test_block.entity.Block;
import com.hapiweb.test_block.entity.BlockExample;
import com.hapiweb.test_block.service.BlockService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Comparator;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
@Service
@UserLoginToken(required = true)
public class BlockServiceImpl implements BlockService {
@Autowired
BlockMapper blockMapper;
public static synchronized String getGenkey(){
return UUID.randomUUID().toString().replaceAll("-","");
}
@Override
@Transactional
public boolean editBlock(BlockDTO blockDTO) {
Block block = blockMapper.selectByPrimaryKey(blockDTO.getBlock().getGenkey());
if(block != null){
blockMapper.updateByPrimaryKey(blockDTO.getBlock());
return true;
}else{
throw new RuntimeException("无此板块");
}
}
@Override
public BlockDTO getBlockByName(BlockDTO blockDTO) {
BlockExample blockExample = new BlockExample();
BlockExample.Criteria criteria = blockExample.createCriteria();
criteria.andNameEqualTo(blockDTO.getBlock().getName());
List<Block> blocks = blockMapper.selectByExample(blockExample);
if(blocks.size()!=0){
BlockDTO blockDTO1 = new BlockDTO();
blockDTO1.setBlock(blocks.get(0));
return blockDTO1;
}
return null;
}
@Override
public BlockDTO getBlockById(String id) {
Block block = blockMapper.selectByPrimaryKey(id);
BlockDTO blockDTO = new BlockDTO();
blockDTO.setBlock(block);
return blockDTO;
}
@Override
public List<Block> list() {
return blockMapper.selectByExample(null).stream().sorted(Comparator.comparing(Block::getName)).collect(Collectors.toList());
}
@Override
public List<Block> queryForList(String key) {
BlockExample blockExample = new BlockExample();
BlockExample.Criteria criteria = blockExample.createCriteria();
criteria.andNameLike("%" + key + "%");
return blockMapper.selectByExample(blockExample);
}
@Override
@Transactional
public BlockDTO addBlock(BlockDTO blockDTO) {
Block block = blockDTO.getBlock();
BlockExample blockExample = new BlockExample();
blockExample.createCriteria().andNameEqualTo(block.getName());
List<Block> blocks = blockMapper.selectByExample(blockExample);
if(blocks.size()==0){
do {
block.setGenkey(getGenkey());
}while(blockMapper.selectByPrimaryKey(block.getGenkey())!=null);
blockMapper.insert(block);
}
BlockDTO blockDTO1 = new BlockDTO();
blockDTO1.setBlock(block);
return blockDTO1;
}
}
| true |
d28c69afcdc9da628f45252f80e73c3110b48cb6 | Java | WallaceMao/rsq-user-midware | /src/main/java/com/rishiqing/midware/user/util/DateUtil.java | UTF-8 | 662 | 2.984375 | 3 | [] | no_license | package com.rishiqing.midware.user.util;
import java.util.Date;
/**
* Created by on 2017/7/10.Wallace
*/
public class DateUtil {
public String name;
/**
* 如果first > second则,返回1,如果first == second,则返回0,如果first < second,则返回-1
* @param first
* @param second
* @return
*/
public static int compare(Date first, Date second){
long firstVal = first.getTime();
long secondVal = second.getTime();
if(firstVal > secondVal){
return 1;
}else if(firstVal == secondVal){
return 0;
}else {
return -1;
}
}
}
| true |
50b96efb41658ebf4ea8a5dd799361c2fe66a1c4 | Java | gbif/pipelines | /livingatlas/pipelines/src/main/java/au/org/ala/pipelines/beam/DwcaToVerbatimPipeline.java | UTF-8 | 2,963 | 2.078125 | 2 | [
"Apache-2.0"
] | permissive | package au.org.ala.pipelines.beam;
import java.nio.file.Paths;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.beam.sdk.Pipeline;
import org.apache.beam.sdk.PipelineResult;
import org.gbif.api.model.pipelines.StepType;
import org.gbif.pipelines.common.PipelinesVariables.Pipeline.Conversion;
import org.gbif.pipelines.common.beam.DwcaIO;
import org.gbif.pipelines.common.beam.metrics.MetricsHandler;
import org.gbif.pipelines.common.beam.options.InterpretationPipelineOptions;
import org.gbif.pipelines.common.beam.options.PipelinesOptionsFactory;
import org.gbif.pipelines.common.beam.utils.PathBuilder;
import org.gbif.pipelines.transforms.core.VerbatimTransform;
import org.slf4j.MDC;
/**
* Pipeline that reads a DwCA an converts to AVRO using the {@link
* org.gbif.pipelines.io.avro.ExtendedRecord}
*
* <p>Pipeline sequence:
*
* <pre>
* 1) Reads DwCA archive and converts to {@link org.gbif.pipelines.io.avro.ExtendedRecord}
* 2) Writes data to verbatim.avro file
* </pre>
*
* <p>How to run:
*
* <pre>{@code
* java -cp target/ingest-gbif-standalone-BUILD_VERSION-shaded.jar some.properties
*
* or pass all parameters:
*
* java -cp target/ingest-gbif-standalone-BUILD_VERSION-shaded.jar
* --pipelineStep=DWCA_TO_VERBATIM \
* --datasetId=9f747cff-839f-4485-83a1-f10317a92a82
* --attempt=1
* --runner=SparkRunner
* --targetPath=/path/GBIF/output/
* --inputPath=/path/GBIF/input/dwca/9f747cff-839f-4485-83a1-f10317a92a82.dwca
*
* }</pre>
*/
@Slf4j
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class DwcaToVerbatimPipeline {
public static void main(String[] args) {
InterpretationPipelineOptions options = PipelinesOptionsFactory.createInterpretation(args);
run(options);
}
public static void run(InterpretationPipelineOptions options) {
MDC.put("datasetKey", options.getDatasetId());
MDC.put("attempt", options.getAttempt().toString());
MDC.put("step", StepType.DWCA_TO_VERBATIM.name());
log.info("Adding step 1: Options");
String inputPath = options.getInputPath();
String targetPath = PathBuilder.buildDatasetAttemptPath(options, Conversion.FILE_NAME, false);
String tmpPath = PathBuilder.getTempDir(options);
boolean isDir = Paths.get(inputPath).toFile().isDirectory();
DwcaIO.Read reader =
isDir
? DwcaIO.Read.fromLocation(inputPath)
: DwcaIO.Read.fromCompressed(inputPath, tmpPath);
log.info("Adding step 2: Pipeline steps");
Pipeline p = Pipeline.create(options);
p.apply("Read from Darwin Core Archive", reader)
.apply("Write to avro", VerbatimTransform.create().write(targetPath).withoutSharding());
log.info("Running the pipeline");
PipelineResult result = p.run();
result.waitUntilFinish();
MetricsHandler.saveCountersToTargetPathFile(options, result.metrics());
log.info("Pipeline has been finished");
}
}
| true |
490474410ba7b09b262a5bb5ce4db7655a3ccd84 | Java | RiickNogueira/fullstack-springboot-and-vuejs-backend | /src/main/java/com/richardson/springbootapi/service/PerfilService.java | UTF-8 | 1,087 | 2.421875 | 2 | [] | no_license | package com.richardson.springbootapi.service;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.richardson.springbootapi.model.Perfil;
import com.richardson.springbootapi.repository.PerfilRepository;
import com.richardson.springbootapi.service.exception.ObjectNotFoundException;
@Service
public class PerfilService {
@Autowired
private PerfilRepository repo;
public Perfil find(Integer id) {
Optional<Perfil> obj = repo.findById(id);
return obj.orElseThrow(
() -> new ObjectNotFoundException("Não foi encontrado nenhum perfil com este Id (" + id + ")"));
}
public List<Perfil> findAll() {
return repo.findAllByOrderByNomeAsc();
}
public Perfil create(Perfil obj) {
obj.setId(null);
return repo.save(obj);
}
public Perfil update(Perfil updatedObj) {
Perfil obj = find(updatedObj.getId());
obj.setNome(updatedObj.getNome());
return repo.save(obj);
}
public void delete(Integer id) {
repo.deleteById(find(id).getId());
}
}
| true |
676b62953dd330a6f50c480bebd350bbe51d4e43 | Java | benech17/Multiple-Board-Games | /src/main/java/games/saboteur/view/JPanelUp.java | UTF-8 | 709 | 2.75 | 3 | [
"MIT"
] | permissive | package games.saboteur.view;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
public class JPanelUp extends JPanel {
//JPanel with an image background
private BufferedImage img;
public JPanelUp(String file) {
BufferedImage i;
try {
i = ImageIO.read(getClass().getResourceAsStream(file));
} catch (IOException e) {
i = null;
System.out.println("didn't find it :(");
}
img = i;
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(img,0, 0,1500,600,this);
}
}
| true |
f9d511430492c811977416b18cad9992c7d4bbad | Java | alexis-mhdz/Java-Spring-Framework-CRUD | /src/main/java/com/indra/crud/service/DepartmentService.java | UTF-8 | 383 | 2.03125 | 2 | [] | no_license | package com.indra.crud.service;
import java.util.List;
import com.indra.crud.model.Department;
public interface DepartmentService {
String insertDepartment(Department department);
List<Department> searchAllDepartments();
Department searchDepartment(Department department);
String updateDepartment(Department department);
String deleteDepartment(Department department);
}
| true |
04327d19fe0fad50a119117e0ec37689ec4df561 | Java | Oskar-jun/Java-game | /Main.java | UTF-8 | 13,544 | 2.84375 | 3 | [] | no_license | import java.util.Scanner;
public class Main {
public static final String ANSI_ORANGE = "\033[48:5:166:0m\033[m\n";
public static final String ANSI_RESET = "\u001B[0m";
public static final String ANSI_BLACK = "\u001B[30m";
public static final String ANSI_RED = "\u001B[31m";
public static final String ANSI_GREEN = "\u001B[32m";
public static final String ANSI_YELLOW = "\u001B[33m";
public static final String ANSI_BLUE = "\u001B[34m";
public static final String ANSI_PURPLE = "\u001B[35m";
public static final String ANSI_CYAN = "\u001B[36m";
public static final String ANSI_WHITE = "\u001B[37m";
//Ico of player 🚶 🚢 🚣 I have been choosing between this icons ️
//Ico of kraken and pirates 🦑, ,🏴☠ ️ ,🚢 ,🐙 [🐲] - was 1st draft
//Ico of edge of the world 🌌 smth like a portal 🕳️ 🌊 [☣] - was 1st draft
//Ico of item 🧰 It`s expected that player takes item from the chest
//Ico of water 🌫️
public static void mapRepresent( Object[] worldLayer, Object[] playerLayer ) {
int gridNum = 20;
int startGrid = 0;
for (int i = 0; i < 40; i++) {
if ( gridNum == 19 )
System.out.print( " " );
for (int j = startGrid; j < startGrid + gridNum; j++) {
if ( playerLayer[ j ] != null ) {
System.out.print( ANSI_PURPLE + "\uD83D\uDEA3\u200D" + ANSI_RESET );
} else if ( worldLayer[ j ] instanceof Enemy ) {
if ( ( ( Enemy ) worldLayer[ j ] ).getName( ).equals( "Ugly Kraken, fear of depth" ) ) { /* different Icons for
the different enemies. Literally doing same,
but more interesting :) */
System.out.print( ANSI_RED + "\uD83E\uDD91" + ANSI_RESET );
} else if ( ( ( Enemy ) worldLayer[ j ] ).getName( ).equals( "Pirates of the Caribbean" ) )
System.out.print( ANSI_RED + "☠ " + ANSI_RESET );
} else if ( worldLayer[ j ] instanceof Item ) {
System.out.print( ANSI_YELLOW + "\uD83E\uDDF0 " + ANSI_RESET );
} else if ( worldLayer[ j ] instanceof Edge_Of_The_World ) {
System.out.print( "\uD83C\uDF0C " ); // Edge of the world
} else {
System.out.print( ANSI_CYAN + "\uD83C\uDF2B " + ANSI_RESET );
}
}
startGrid += gridNum;
if ( gridNum == 20 ) {
gridNum = 19;
} else {
gridNum = 20;
}
System.out.println( );
System.out.print( " " );
}
}
public static void interact( Player currentPlayer, Item foundItem, Object[] world_level ) {
System.out.println( "If you want to pick up " + foundItem.getName( ) + " press E, then Enter, or Enter to skip it " );
Scanner scanner = new Scanner( System.in );
String interact = scanner.nextLine( );
switch ( interact ) {
case ( "E" ), ( "e" ) -> {
if ( currentPlayer.takeItem( foundItem )) {
currentPlayer.wear( foundItem );
if (foundItem.getName().equals( "Super durable sail fabric" )) {
currentPlayer.takenDamage ( -10 ); // by negative numbers we add hp to ship
} else if (foundItem.getName().equals( "Stern from hardened wood" )) {
currentPlayer.takenDamage ( -25 );
} else currentPlayer.takenDamage ( -50 );
}
checkItem( world_level, foundItem );
System.out.println("Total health now is " + ANSI_RED
+ currentPlayer.getHealth() + ANSI_PURPLE);
world_level[ currentPlayer.getPosition( ) ] = null;
}
}
}
public static void moveMain( Player currentPlayer, int index, Object[] world_layer, Object[] player_level ) {
player_level[ currentPlayer.getPosition( ) ] = null;
player_level[ currentPlayer.move( index ) ] = currentPlayer;
if ( world_layer[ currentPlayer.getPosition( ) ] != null ) {
System.out.println( ANSI_YELLOW + "There is something here..." + ANSI_RESET );
if ( world_layer[ currentPlayer.getPosition( ) ] instanceof Edge_Of_The_World ) {
currentPlayer.die( );
System.out.print( ANSI_GREEN + "That is the end great adventurer! Mighty elders warned you that our world is flat and thus, who faced the edge of it, never came back. You fall to the" + ANSI_PURPLE + " black hole of infinity " + ANSI_RESET );
}
if ( world_layer[ currentPlayer.getPosition( ) ] instanceof Enemy ) {
System.out.println( "It is an enemy!" );
fight( currentPlayer, ( Enemy ) world_layer[ currentPlayer.getPosition( ) ], world_layer );
}
if ( world_layer[ currentPlayer.getPosition( ) ] instanceof Item ) {
interact( currentPlayer, ( Item ) world_layer[ currentPlayer.getPosition( ) ], world_layer );
}
}
}
public static Object[] worldPregen( ) {
double itemSpawnChance = 0.0, enemySpawnChance = 0.0;
Object[] world = new Object[ 780 ]; // firstly I did 143 hexagonal grid, than 480, than 780. Think that it will be enough.
for (int i = 0; i < 780; i++) {
if ( ( int ) ( Math.random( ) + itemSpawnChance ) >= 1 ) {
world[ i ] = new Ship_Boosters( ANSI_CYAN + "Super durable sail fabric",10 ); /* 3 intuitive levels of items, blue - ordinary, purple - epic and yellow - legendary.
At least at that point of time I expect myself to give some HP upgrade according to the class of item.
Change of the color of Upper "Edge of the world" portals was "Bug" but I decided to make it as a feature:
If world is flat, so upper portals are like generating the treasure chests for the other world, being linked
by such a portals :)
*/
itemSpawnChance = 0.0;
} else {
itemSpawnChance += 0.000961;
if ( ( int ) ( Math.random( ) + itemSpawnChance ) >= 1 ) {
world[ i ] = new Ship_Boosters( ANSI_PURPLE + "Stern from hardened wood",25 ); // I know that it`s not the best way but I found no other option to reset the color.
itemSpawnChance = 0.0;
} else {
itemSpawnChance += 0.05961;
if ( ( int ) ( Math.random( ) + itemSpawnChance ) >= 1 ) {
world[ i ] = new Ship_Boosters( ANSI_YELLOW + "Heat-resistant ship bow",50 );
itemSpawnChance = 0.0;
} else {
itemSpawnChance += 0.05961;
if ( ( int ) ( Math.random( ) + enemySpawnChance ) >= 1 ) {
world[ i ] = new Enemy( "Ugly Kraken, fear of depth" );
enemySpawnChance = 0.0;
} else {
enemySpawnChance += 0.05961;
if ( ( int ) ( Math.random( ) + enemySpawnChance ) >= 1 ) {
world[ i ] = new Enemy( "Pirates of the Caribbean" );
enemySpawnChance = 0.0;
} else {
enemySpawnChance += 0.05961;
}
}
}
}
}
for (int j = 0; j < 742; j += 39)
world[ j ] = new Edge_Of_The_World( ); // counting from zero so index of array will be +1
for (int k = 1; k < 39; k++) // counting from 1
world[ k ] = new Edge_Of_The_World( );
for (int l = 19; l < 760; l += 39) // same count from 20-1=19
world[ l ] = new Edge_Of_The_World( );
for (int l = 779; l > 741; l--) // indexes therefore -1
world[ l ] = new Edge_Of_The_World( );
}
return world;
}
public static void fight( Player currentPlayer, Enemy currentEnemy, Object[] world_level ) {
while ( ( !currentEnemy.checkIfDead( ) ) && ( !currentPlayer.checkIfDead( ) ) ) {
switch ( ( int ) ( Math.random( ) * 6 ) ) {
case ( 0 ) -> currentPlayer.takenDamage( ( int ) ( Math.random( ) + 11 ) );
case ( 1 ) -> {
System.out.println( "Enemy missed" + ANSI_RED + " CRITICALLY." + ANSI_RESET );
currentEnemy.takenDamage( ( int ) ( Math.random( ) + 10 ) );
currentEnemy.takenDamage( ( int ) ( Math.random( ) + 10 ) );
}
case ( 3 ) -> currentEnemy.takenDamage( ( int ) ( Math.random( ) + 16 ) );
case ( 4 ) -> {
System.out.println( "You missed" + ANSI_RED + " \uD835\uDC02\uD835\uDC11\uD835\uDC08\uD835\uDC13\uD835\uDC08\uD835\uDC02\uD835\uDC00\uD835\uDC0B\uD835\uDC0B\uD835\uDC18 " + ANSI_RESET ); // special font of Crit. miss
if ( currentEnemy.getName( ).equals( "Ugly Kraken, fear of depth" ) ) {
currentPlayer.takenDamage( ( int ) Math.random( ) + 50 ); // as far as its GREAT KRAKEN, We are almost always dead when meeting him
} else currentPlayer.takenDamage( ( int ) Math.random( ) + 10 );
}
}
}
if ( currentEnemy.checkIfDead( ) ) world_level[ currentPlayer.getPosition( ) ] = null;
}
public static void checkItem ( Object[] world_level ,Item foundItem ) {
for ( int i = 0; i < 780; i++ ) {
if ( ( world_level[i] instanceof Item ) && ( ( Item ) world_level[i] ).getName( ).equals( foundItem.getName( ) ) )
world_level[i] = null;
}
}
public static void main( String[] args ) {
Player player_Alex = new Player( "Alex" );
Object[] world_level = worldPregen( );
Object[] player_level = new Object[ 780 ];
Scanner scannerMain = new Scanner( System.in );
player_level[ 439 ] = player_Alex;
player_Alex.setPosition( 439 ); //World is having a Hexagons grid so we are starting in +- the middle of it.
while ( !player_Alex.checkIfDead( ) ) {
mapRepresent( world_level, player_level );
System.out.println( "Make your move:" + ANSI_GREEN + " W " + ANSI_RESET + "for going [\uD83E\uDC81] to North," + ANSI_GREEN + " E " + ANSI_RESET + "for going [\uD83E\uDC85] to North-East," + ANSI_GREEN + " X " + ANSI_RESET + "for going [\uD83E\uDC86] to South-East," + ANSI_GREEN + " S " + ANSI_RESET + " for going [\uD83E\uDC83] to South," + ANSI_GREEN + " Z " + ANSI_RESET + "for going [\uD83E\uDC87] to South-West," + ANSI_GREEN + " Q " + ANSI_RESET + "for going [\uD83E\uDC84] to North-West , then press enter" );
String move = scannerMain.nextLine( );
switch ( move ) {
case ( "W" ), ( "w" ) -> moveMain( player_Alex, -39, world_level, player_level );
case ( "E" ), ( "e" ) -> moveMain( player_Alex, -19, world_level, player_level );
case ( "X" ), ( "x" ) -> moveMain( player_Alex, 20, world_level, player_level );
case ( "S" ), ( "s" ) -> moveMain( player_Alex, 39, world_level, player_level );
case ( "Z" ), ( "z" ) -> moveMain( player_Alex, 19, world_level, player_level );
case ( "Q" ), ( "q" ) -> moveMain( player_Alex, -20, world_level, player_level );
}
}
System.out.println( "\n" + ANSI_RED + " Game over. " );
// 1 Complete Edge of the world }} Done
// Hz what else
// 2 Item Hp increase system
// auto weraing of items
// differinciation of items
// Different classes for pirates and kraken }}Done
/* Also, I had one perfect idea which I hope I will realize later on on my own. That`s the idea of making world infinite
by using edge of the world as a drop or teleport to the middle of new playing grid, making it not only cool legend, but also working algorythm.
*/
}
} | true |
d24dae541f15599e9483f451c1ce6485384a155a | Java | Jamonek/Algorithms | /Matrix.java | UTF-8 | 2,883 | 3.5 | 4 | [] | no_license | import java.util.Arrays;
public class Matrix {
private static double determinant(double[][] matrix) {
if (matrix.length != matrix[0].length)
throw new IllegalStateException("invalid dimensions");
if (matrix.length == 2)
return matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0];
double det = 0;
for (int i = 0; i < matrix[0].length; i++)
det += Math.pow(-1, i) * matrix[0][i]
* determinant(minor(matrix, 0, i));
return det;
}
private static double[][] inverse(double[][] matrix) {
double[][] inverse = new double[matrix.length][matrix.length];
// minors and cofactors
for (int i = 0; i < matrix.length; i++)
for (int j = 0; j < matrix[i].length; j++)
inverse[i][j] = Math.pow(-1, i + j)
* determinant(minor(matrix, i, j));
// adjugate and determinant
double det = 1.0 / determinant(matrix);
for (int i = 0; i < inverse.length; i++) {
for (int j = 0; j <= i; j++) {
double temp = inverse[i][j];
inverse[i][j] = inverse[j][i] * det;
inverse[j][i] = temp * det;
}
}
return inverse;
}
private static double[][] minor(double[][] matrix, int row, int column) {
double[][] minor = new double[matrix.length - 1][matrix.length - 1];
for (int i = 0; i < matrix.length; i++)
for (int j = 0; i != row && j < matrix[i].length; j++)
if (j != column)
minor[i < row ? i : i - 1][j < column ? j : j - 1] = matrix[i][j];
return minor;
}
private static double[][] multiply(double[][] a, double[][] b) {
if (a[0].length != b.length)
throw new IllegalStateException("invalid dimensions");
double[][] matrix = new double[a.length][b[0].length];
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < b[0].length; j++) {
double sum = 0;
for (int k = 0; k < a[i].length; k++)
sum += a[i][k] * b[k][j];
matrix[i][j] = sum;
}
}
return matrix;
}
private static double[][] transpose(double[][] matrix) {
double[][] transpose = new double[matrix[0].length][matrix.length];
for (int i = 0; i < matrix.length; i++)
for (int j = 0; j < matrix[i].length; j++)
transpose[j][i] = matrix[i][j];
return transpose;
}
public static void main(String[] args) {
// example 1 - solving a system of equations
double[][] a = { { 1, 1, 1 }, { 0, 2, 5 }, { 2, 5, -1 } };
double[][] b = { { 6 }, { -4 }, { 27 } };
double[][] matrix = multiply(inverse(a), b);
for (double[] i : matrix)
System.out.println(Arrays.toString(i));
System.out.println();
// example 2 - solving a normal equation for linear regression
double[][] x = { { 2104, 5, 1, 45 }, { 1416, 3, 2, 40 },
{ 1534, 3, 2, 30 }, { 852, 2, 1, 36 } };
double[][] y = { { 460 }, { 232 }, { 315 }, { 178 } };
matrix = multiply(
multiply(inverse(multiply(transpose(x), x)), transpose(x)), y);
for (double[] i : matrix)
System.out.println(Arrays.toString(i));
}
}
| true |
de39a91bc3e82ccd2b6f9f7d51277c51f6bfb00a | Java | hnzswqc/crm | /src/com/hnzskj/base/core/bean/Operate.java | UTF-8 | 3,559 | 2.125 | 2 | [] | no_license | /*
* @项目名称: crm
* @文件名称: Operate.java
* @日期: 2015-8-28 下午03:38:35
* @版权: 2015 河南中审科技有限公司
* @开发公司或单位:河南中审科技有限公司研发部
*/
package com.hnzskj.base.core.bean;
/**
* 项目名称:crm <br/>
* 类名称:Operate.java <br/>
* 类描述:操作功能实体对象 <br/>
* 创建人:King <br/>
* 创建时间:2015-8-28 下午03:38:35 <br/>
* 修改人:King <br/>
* 修改时间:2015-8-28 下午03:38:35 <br/>
* 修改备注: <br/>
* @version 1.0
*/
public class Operate {
/**
* 操作uuid
*/
private String operateUuid;
/**
* 唯一标识
*/
private String operateKey;
/**
* 操作名称
*/
private String operateName;
/**
* 图标
*/
private String operateIcon;
/**
* 说明信息
*/
private String operateNote;
/**
* 排序号
*/
private Integer operateOrderBy;
/**
* 创建时间
*/
private String createTime;
/**
* 所属功能连接uuid
*/
private String powerUuid;
/**
* 用户信息注入
*/
private User user = null;
/**
* 操作uuid
* @return the operateUuid
*/
public String getOperateUuid() {
return operateUuid;
}
/**
* 操作uuid
* @param operateUuid the operateUuid to set
*/
public void setOperateUuid(String operateUuid) {
this.operateUuid = operateUuid;
}
/**
* 唯一标识
* @return the operateKey
*/
public String getOperateKey() {
return operateKey;
}
/**
* 唯一标识
* @param operateKey the operateKey to set
*/
public void setOperateKey(String operateKey) {
this.operateKey = operateKey;
}
/**
* 操作名称
* @return the operateName
*/
public String getOperateName() {
return operateName;
}
/**
* 操作名称
* @param operateName the operateName to set
*/
public void setOperateName(String operateName) {
this.operateName = operateName;
}
/**
* 图标
* @return the operateIcon
*/
public String getOperateIcon() {
return operateIcon;
}
/**
* 图标
* @param operateIcon the operateIcon to set
*/
public void setOperateIcon(String operateIcon) {
this.operateIcon = operateIcon;
}
/**
* 说明信息
* @return the operateNote
*/
public String getOperateNote() {
return operateNote;
}
/**
* 说明信息
* @param operateNote the operateNote to set
*/
public void setOperateNote(String operateNote) {
this.operateNote = operateNote;
}
/**
* 排序号
* @return the operateOrderBy
*/
public Integer getOperateOrderBy() {
return operateOrderBy;
}
/**
* 排序号
* @param operateOrderBy the operateOrderBy to set
*/
public void setOperateOrderBy(Integer operateOrderBy) {
this.operateOrderBy = operateOrderBy;
}
/**
* 创建时间
* @return the createTime
*/
public String getCreateTime() {
return createTime;
}
/**
* 创建时间
* @param createTime the createTime to set
*/
public void setCreateTime(String createTime) {
this.createTime = createTime;
}
/**
* 所属功能连接uuid
* @return the powerUuid
*/
public String getPowerUuid() {
return powerUuid;
}
/**
* 所属功能连接uuid
* @param powerUuid the powerUuid to set
*/
public void setPowerUuid(String powerUuid) {
this.powerUuid = powerUuid;
}
/**
* 用户信息注入
* @return the user
*/
public User getUser() {
return user;
}
/**
* 用户信息注入
* @param user the user to set
*/
public void setUser(User user) {
this.user = user;
}
}
| true |
fc886c953f66349deed5af198a41fc5f86c7c929 | Java | jaalorsa517/fundamentosJava | /src/main/java/fund_java/ejercicio1/views/Principal.java | UTF-8 | 2,446 | 3.671875 | 4 | [] | no_license | package fund_java.ejercicio1.views;
import java.util.Scanner;
import fund_java.ejercicio1.controllers.Competencia;
import fund_java.utils.util;
public class Principal {
private Competencia competencia;
// CONSTRUCTOR
public Principal() {
this.competencia = new Competencia();
}
public void interact() {
int option = 0;
while (option != 5) {
option = util.validatorInt(menu());
optionSelected(option);
}
}
private String menu() {
return " COMPETENCIA \n" + "1. Registrar atleta. \n" + "2. Datos del campeon.\n"
+ "3. Atleta por pais. \n" + "4. Tiempo promedio de todos los atletas. \n" + "5. Salir \n";
}
private void optionSelected(int option) {
switch (option) {
case 1:
System.out.println(this.competencia.registerAthlete(registrar()));
break;
case 2:
String[] champion = competencia.getCampeon();
if (champion == null) {
System.out.println("No existe atletas!\n");
} else {
System.out.println("El campeon actual es: \nNombre:" + champion[0] + "\nNacionalidad: "
+ champion[1] + "\nTiempo: " + champion[2] + "\n");
}
break;
case 3:
System.out.println(competencia.athleteByCountry(country()));
break;
case 4:
System.out.println("El tiempo promedio de los atletas registrados es: " + competencia.mediaTime()+"\n");
break;
case 5:
System.out.println("Fin ejercicio 1\n");
break;
default:
System.out.println("Opción incorrecta, intenta nuevamente\n");
break;
}
}
private String country() {
Scanner country = new Scanner(System.in);
System.out.println("Ingrese el país que quieres filtrar");
return util.capitalize(country.nextLine());
}
private String[] registrar() {
String[] atleta = new String[3];
atleta[0] = util.capitalize(util.validatorEmpty("Nombre del atleta"));
atleta[1] = util.capitalize(util.validatorEmpty("Nacionalidad del atleta"));
atleta[2] = util.validatorEmpty("Tiempo en segundos del atleta");
return atleta;
}
} | true |
cd90764963e463ff0f585daf16cd40c29e114500 | Java | aa86799/stoneMyAllDemo | /src/com/stone/ui/TestCustomPreferenceActivity.java | UTF-8 | 391 | 1.617188 | 2 | [] | no_license | package com.stone.ui;
import com.stone.R;
import android.os.Bundle;
import android.preference.PreferenceActivity;
public class TestCustomPreferenceActivity extends PreferenceActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.custom_preference);
}
}
| true |
0eb42caa9e9a76a6bbb22bd812df9afcd0258ea6 | Java | vietdq2412/Java_10_List | /implementArrayList/src/Main.java | UTF-8 | 624 | 3.28125 | 3 | [] | no_license | import list.*;
public class Main {
public static void main(String[] args) {
MySimpleList<Integer> listInteger = new MySimpleList<Integer>();
listInteger.add(1);
listInteger.add(2);
listInteger.add(3);
listInteger.add(3);
listInteger.add(4);
listInteger.add(7);
listInteger.add(22);
listInteger.remove(3);
boolean c = listInteger.contains(3);
System.out.println(c);
listInteger.clear();
for (int i =0; i< listInteger.getSize(); i++){
System.out.println(listInteger.getElement(i));
}
}
}
| true |
c15e78a5bc638eb5d7e34d705b80a37f6ed3c4c6 | Java | riomerke/CecilioBo | /AppDisfruta2/src/main/java/com/solvertic/disfruta/entity/ValoresDeAtributos.java | UTF-8 | 93 | 1.539063 | 2 | [] | no_license | package com.solvertic.disfruta.entity;
public enum ValoresDeAtributos {
No, Default
}
| true |
1aebcacdfb66c4e635ddfe8e29f013f8930a5433 | Java | marciofk/hva-pc-assignment-3 | /src/main/java/teaching/client/ClientChatRun.java | UTF-8 | 420 | 2.28125 | 2 | [] | no_license | package teaching.client;
import teaching.common.Config;
public class ClientChatRun {
public static void main(String[] args) {
if(args.length > 0) {
updateParams(args);
}
new ClientChatImpl();
}
private static void updateParams(String[] args) {
Config.getInstance().setServer(args[0]);
if(args.length > 1) {
Config.getInstance().setPort(Integer.parseInt(args[1]));
}
}
}
| true |
1fb0b8808f5f21545efef4c61dfd36c9d564c87d | Java | liwen666/springcloud_new | /quartz_test/src/main/java/jrx/batch/dataflow/quartz/IQuartzManager.java | UTF-8 | 1,369 | 2.234375 | 2 | [] | no_license | package jrx.batch.dataflow.quartz;
/**
* @author: looyii
* @Date: 2019/10/16 10:10
* @Description:
*/
public interface IQuartzManager {
/**
* 刷新 quartzJob任务
*
* @throws Exception
*/
void refreshSystemQuartzJob() throws Exception;
/**
* 停止 quartz 作业
*/
void destroyQuartz();
/**
* 初始化 quartz 作业
*
* @throws Exception
*/
void initSystemQuartzJob() throws Exception;
/**
* 暂停 quartz 作业
*
* @param jobName 作业名称
* @param jobGroupName 作业分组
*/
void pauseJob(String jobName, String jobGroupName) ;
/**
* 刷新 quartz 作业
*
* @param jobName 作业名称
* @param jobGroupName 作业分组
* @throws Exception
*/
void refreshAloneQuartzJob(String jobName, String jobGroupName) throws Exception;
/**
* 恢复 quartz 作业
*
* @param jobName 作业名称
* @param jobGroupName 作业分组
* @throws Exception
*/
void resumeJob(String jobName, String jobGroupName) throws Exception;
/**
* 删除 quartz 作业
*
* @param jobName 作业名称
* @param jobGroupName 作业分组
* @throws Exception
*/
void deleteJob(String jobName, String jobGroupName) throws Exception;
}
| true |
c3de53d49f369aaaff0e68c8d2b786fe436e6e5f | Java | lakshmisowjanya-vanguri/StringPrograms | /CharacterCount.java | UTF-8 | 634 | 3.703125 | 4 | [] | no_license | import java.util.*;
class CharacterCount1 {
void display() {
Scanner s=new Scanner(System.in);
System.out.println("enter string");
String st=s.nextLine();
String str=st.toUpperCase();
int l=str.length();
char ch[]=new char[l];
for(int i=0;i<l;i++) {
ch[i]=str.charAt(i);
}
for(int i=0;i<l;i++) {
int count=0;
for(int j=i+1;j<l;j++) {
if(ch[i]==ch[j]) {
ch[i]=ch[l-1];
j--;
l--;
count++;
}
}
System.out.println(ch[i]+":"+" "+(count+1));
}
}
}
class CharacterCount {
public static void main(String k[]) {
CharacterCount1 d=new CharacterCount1();
d.display();
}
}
| true |
88d2dfb944901101f98f92978b1a8c7c68b15a34 | Java | ni247/jialian_c-2Java | /heima_day1301/src/com/itheima/service/AccountService4tl.java | UTF-8 | 751 | 1.867188 | 2 | [] | no_license | package com.itheima.service;
import java.sql.Connection;
import org.apache.commons.dbutils.QueryRunner;
import com.itheima.dao.AccountDao;
import com.itheima.dao.AccountDao4tl;
import com.itheima.utils.DatasSourceUtils;
import com.itheima.utils.JdbcUtils;
public class AccountService4tl {
public void account(String fromuser, String touser, String money) throws Exception {
AccountDao4tl dao = new AccountDao4tl();
try {
DatasSourceUtils.startTransaction();
dao.accountOut(fromuser, money);
// int i = 1 / 0;
dao.accountIn(touser, money);
DatasSourceUtils.commitAndCloseQuiety();
} catch (Exception e) {
e.printStackTrace();
DatasSourceUtils.rollbackAndCloseQuiety();
throw e;
}
}
}
| true |
c81e4ea1fce395d49ad09003d1f83b4acee8af59 | Java | shailendra333/threadlogic | /src/java/com/oracle/ateam/threadlogic/categories/ExternalizedNestedThreadGroupsCategory.java | UTF-8 | 24,368 | 1.601563 | 2 | [] | no_license | /**
* Copyright (c) 2012 egross, sabha.
*
* ThreadLogic - parses thread dumps and provides analysis/guidance
* It is based on the popular TDA tool. Thank you!
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v2.1
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*/
package com.oracle.ateam.threadlogic.categories;
import com.oracle.ateam.threadlogic.filter.*;
import com.oracle.ateam.threadlogic.HealthLevel;
import com.oracle.ateam.threadlogic.ThreadLogic;
import com.oracle.ateam.threadlogic.advisories.ThreadLogicConstants;
import com.oracle.ateam.threadlogic.ThreadInfo;
import com.oracle.ateam.threadlogic.advisories.RestOfWLSThreadGroup;
import com.oracle.ateam.threadlogic.advisories.ThreadGroup;
import com.oracle.ateam.threadlogic.advisories.ThreadAdvisory;
import com.oracle.ateam.threadlogic.advisories.ThreadGroupFactory;
import com.oracle.ateam.threadlogic.advisories.ThreadGroup.HotCallPattern;
import com.oracle.ateam.threadlogic.utils.CustomLogger;
import com.oracle.ateam.threadlogic.xml.ComplexGroup;
import com.oracle.ateam.threadlogic.xml.GroupsDefnParser;
import com.oracle.ateam.threadlogic.xml.SimpleGroup;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.logging.Logger;
import javax.swing.tree.DefaultMutableTreeNode;
public class ExternalizedNestedThreadGroupsCategory extends NestedCategory {
private Category threads;
private String overview = null;
private ThreadGroup unknownThreadGroup;
private CompositeFilter wlsCompositeFilter;
private CompositeFilter nonwlsCompositeFilter;
private CompositeFilter unknownCompositeFilter;
private NestedCategory nestedWLSCategory, nestedNonWLSCategory;
private LinkedList<ThreadInfo> threadLinkedList = new LinkedList<ThreadInfo>();
private ArrayList<ThreadGroup> threadGroupList = new ArrayList<ThreadGroup>();
private ArrayList<ThreadGroup> wlsThreadGroupList = new ArrayList<ThreadGroup>();
private ArrayList<ThreadGroup> nonWlsThreadGroupList = new ArrayList<ThreadGroup>();
private Filter ldapThreadsFilter, muxerThreadsFilter, aqAdapterThreadsFilter;
private ArrayList<Filter> allWLSFilterList, allNonWLSFilterList;
private static ArrayList<Filter> allNonWLSStaticFilterList, allWLSStaticFilterList;
private Filter wlsJMSFilter1 = new Filter("WLS JMS", "(weblogic.jms)|(weblogic.messaging)", 2, false, false, true);
private Filter wlsJMSFilter2 = new Filter("WLS JMS", "JmsDispatcher", 0, false, false, true);
private static Filter allWLSThreadStackFilter, allWLSThreadNameFilter;
private static Logger theLogger = CustomLogger.getLogger("ThreadGroupsCategory");
public static String DICTIONARY_KEYS;
public static String THREADTYPEMAPPER_KEYS;
public static String PATH_SEPARATOR = "|";
public static String GROUPDEFS_EXT_DIRECTORY = "threadlogic.groups";
public static final Hashtable<String, Filter> allKnownFilterMap = new Hashtable<String, Filter>();
public static String wlsThreadStackPattern, wlsThreadNamePattern;
private int totalWlsDefaultExecuteThreads, maxWlsDefaultExecuteThreadId = -1;
private int[] wlsDefaultExecuteThreadIds = new int[800];
private static final String REST_OF_WLS = "Rest of WLS";
static {
init();
}
// Cache the Group Definitions and clone the saved filters...
// instead of reading each time... for each TD
private static void init() {
createExternalFilterList();
if (allWLSStaticFilterList == null || allNonWLSStaticFilterList == null) {
allWLSStaticFilterList = createInternalFilterList(ThreadLogicConstants.WLS_THREADGROUP_DEFN_XML);
allNonWLSStaticFilterList = createInternalFilterList(ThreadLogicConstants.NONWLS_THREADGROUP_DEFN_XML);
}
allWLSThreadStackFilter = new Filter("WLS Stack", wlsThreadStackPattern, 2, false, false, true);
allWLSThreadNameFilter = new Filter("WLS Name", wlsThreadNamePattern, 0, false, false, true);
theLogger.finest("WLS Thread Stack Pattern: " + wlsThreadStackPattern);
theLogger.finest("WLS Thread Name Pattern: " + wlsThreadNamePattern);
}
/**
* This method is expected to find two externally defined Group Defns.
* One should be for WLS and other for Non-WLS
*/
private static void createExternalFilterList() {
String externalGroupDefnDirectory = System.getProperty(GROUPDEFS_EXT_DIRECTORY, "groupsdef");
File folder = new File(externalGroupDefnDirectory);
if (folder.exists()) {
theLogger.info("\n\nAttempting to load Groups Defn files from directory: " + externalGroupDefnDirectory);
theLogger.warning("Alert!! There can only be two files - WLSGroups.xml and NonWLSGroups.xml files within the above directory");
File[] listOfFiles = folder.listFiles();
for(File file: listOfFiles) {
try {
theLogger.info("Attempting to load GroupsDefn from external resource: " + file.getAbsolutePath());
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
boolean isWLSGroup = !file.getName().toLowerCase().contains("nonwls");
theLogger.info("Parsing file - " + file.getName() + " as a WLS Group Definition file??:" + isWLSGroup);
ArrayList<Filter> filterList = parseFilterList(bis, isWLSGroup);
if (filterList.size() > 0) {
if (isWLSGroup)
allWLSStaticFilterList = filterList;
else
allNonWLSStaticFilterList = filterList;
}
} catch(Exception ioe) {
theLogger.warning("ERROR!! Problem in reading Group Defn from external file: " + ioe.getMessage());
ioe.printStackTrace();
}
}
}
return;
}
private static ArrayList<Filter> createInternalFilterList(String groupsDefnXml) {
ClassLoader cl = ThreadLogicConstants.class.getClassLoader();
theLogger.finest("\n\nAttempting to load GroupsDefn from packaged threadlogic jar: " + groupsDefnXml);
boolean isWLSGroup = !(groupsDefnXml.toLowerCase().contains("nonwls"));
return parseFilterList(cl.getResourceAsStream(groupsDefnXml), isWLSGroup);
}
private static ArrayList<Filter> parseFilterList(InputStream is, boolean isWLSGroup) {
GroupsDefnParser groupsDefnParser = null;
ArrayList<Filter> filterArr = new ArrayList<Filter>();
try {
groupsDefnParser = new GroupsDefnParser(is);
groupsDefnParser.run();
ArrayList<SimpleGroup> simpleGrpList = groupsDefnParser.getSimpleGrpList();
ArrayList<ComplexGroup> complexGrpList = groupsDefnParser.getComplexGrpList();
boolean empty = true;
StringBuffer sbufStack = new StringBuffer(100);
StringBuffer sbufName = new StringBuffer(100);
sbufStack.append("(weblogic)|(Weblogic)");
sbufName.append("(weblogic)");
for (SimpleGroup smpGrp : simpleGrpList) {
generateSimpleFilter(smpGrp, filterArr);
boolean againstStack = smpGrp.getMatchLocation().equals("stack");
ArrayList<String> patternList = smpGrp.getPatternList();
for(String pattern: patternList) {
if (againstStack) {
sbufStack.append("|(" + pattern + ")");
} else {
sbufName.append("|(" + pattern + ")");
}
}
}
for (ComplexGroup cmplxGrp : complexGrpList) {
generateCompositeFilter(cmplxGrp, filterArr);
}
if (isWLSGroup) {
wlsThreadStackPattern = sbufStack.toString();
wlsThreadNamePattern = sbufName.toString();
}
} catch (Exception e) {
theLogger.warning("ERROR!! Unable to load or parse the Group Definition Resource:" + e.getMessage());
e.printStackTrace();
}
return filterArr;
}
private static void generateSimpleFilter(SimpleGroup smpGrp, ArrayList<Filter> filterList) {
String filterName = smpGrp.getName();
ArrayList<String> patternList = smpGrp.getPatternList();
String pattern = "";
int count = patternList.size();
if (count <= 0) {
return;
}
if (count == 1) {
pattern = patternList.get(0);
} else if (count > 1) {
StringBuffer sbuf = new StringBuffer("(" + patternList.get(0) + ")");
for (int i = 1; i < count; i++) {
sbuf.append("|(" + patternList.get(i) + ")");
}
pattern = sbuf.toString();
}
int filterRuleToApply = Filter.HAS_IN_STACK_RULE;
if (smpGrp.getMatchLocation().equals("name")) {
filterRuleToApply = Filter.HAS_IN_TITLE_RULE;
}
Filter simpleFilter = new Filter(filterName, pattern, filterRuleToApply, false, false, smpGrp.isInclusion());
simpleFilter.setExcludedAdvisories(smpGrp.getExcludedAdvisories());
simpleFilter.setInfo(filterName);
if (allKnownFilterMap.containsKey(filterName)) {
theLogger.warning("Group Definition already exists:" + filterName + ", use different name or update existing Group Defintion");
} else {
allKnownFilterMap.put(filterName, simpleFilter);
}
if (smpGrp.isVisible()) {
filterList.add(simpleFilter);
}
return;
}
private static void generateCompositeFilter(ComplexGroup cmplxGrp, ArrayList<Filter> filterList) {
String filterName = cmplxGrp.getName();
CompositeFilter compositeFilter = new CompositeFilter(filterName);
compositeFilter.setExcludedAdvisories(cmplxGrp.getExcludedAdvisories());
compositeFilter.setInfo(filterName);
for (String simpleGrpKey : cmplxGrp.getInclusionList()) {
Filter simpleFilter = allKnownFilterMap.get(simpleGrpKey);
if (simpleFilter == null) {
theLogger.warning("ERROR: Simple Group referred by name:" + simpleGrpKey + " not declared previously or name mismatch!!, Fix the error");
Thread.dumpStack();
continue;
}
compositeFilter.addFilter(simpleFilter, true);
}
for (String simpleGrpKey : cmplxGrp.getExclusionList()) {
Filter simpleFilter = allKnownFilterMap.get(simpleGrpKey);
if (simpleFilter == null) {
theLogger.warning("ERROR: Simple Group referred by name:" + simpleGrpKey + " not declared previously or name mismatch!!, Fix the error");
Thread.dumpStack();
continue;
}
compositeFilter.addFilter(simpleFilter, false);
}
allKnownFilterMap.put(filterName, compositeFilter);
if (cmplxGrp.isVisible()) {
filterList.add(compositeFilter);
}
return;
}
private void cloneDefinedFilters() {
allWLSFilterList = new ArrayList<Filter>();
allNonWLSFilterList = new ArrayList<Filter>();
for (Filter filter : allNonWLSStaticFilterList) {
allNonWLSFilterList.add(filter);
}
for (Filter filter : allWLSStaticFilterList) {
allWLSFilterList.add(filter);
}
}
public ExternalizedNestedThreadGroupsCategory() {
super("Thread Groups");
cloneDefinedFilters();
}
public Category getThreads() {
return threads;
}
public void setThreads(Category threads) {
this.threads = threads;
for (int i = 0; i < threads.getNodeCount(); i++) {
ThreadInfo ti = (ThreadInfo) ((DefaultMutableTreeNode) threads.getNodeAt(i)).getUserObject();
threadLinkedList.add(ti);
}
addFilters();
// Sort the thread groups and nested threads by health
this.threadGroupList = ThreadGroup.sortByHealth(this.threadGroupList);
}
public Collection<ThreadGroup> getThreadGroups() {
return this.threadGroupList;
}
public Collection<ThreadGroup> getWLSThreadGroups() {
return this.wlsThreadGroupList;
}
public Collection<ThreadGroup> getNonWLSThreadGroups() {
return this.nonWlsThreadGroupList;
}
public NestedCategory getWLSThreadsCategory() {
return nestedWLSCategory;
}
public NestedCategory getNonWLSThreadsCategory() {
return nestedNonWLSCategory;
}
private void createNonWLSFilterCategories() {
nonwlsCompositeFilter = new CompositeFilter("Non-WLS Thread Groups");
nonwlsCompositeFilter.setInfo("Non-WebLogic Thread Groups");
// Exclude all wls related threads for it
nonwlsCompositeFilter.addFilter(allWLSThreadStackFilter, false);
nonwlsCompositeFilter.addFilter(allWLSThreadNameFilter, false);
addToFilters(nonwlsCompositeFilter);
nestedNonWLSCategory = getSubCategory(nonwlsCompositeFilter.getName());
addUnknownThreadGroupFilter();
for (Filter filter : allNonWLSFilterList) {
nestedNonWLSCategory.addToFilters(filter);
}
}
private void addUnknownThreadGroupFilter() {
unknownCompositeFilter = new CompositeFilter("Unknown or Custom");
unknownThreadGroup = ThreadGroupFactory.createThreadGroup(unknownCompositeFilter.getName());
threadGroupList.add(unknownThreadGroup);
for (Filter filter : allNonWLSFilterList) {
unknownCompositeFilter.addFilter(filter, false);
}
for (Filter filter : allWLSFilterList) {
unknownCompositeFilter.addFilter(filter, false);
}
// Add the unknownCompositeFilter to the allNonWLSFilterList
allNonWLSFilterList.add(unknownCompositeFilter);
}
private void createWLSFilterCategories() {
wlsCompositeFilter = new CompositeFilter("WLS Thread Groups");
wlsCompositeFilter.setInfo("WebLogic Thread Groups");
// Include all wls related threads for it
wlsCompositeFilter.addFilter(allWLSThreadStackFilter, true);
wlsCompositeFilter.addFilter(allWLSThreadNameFilter, true);
addToFilters(wlsCompositeFilter);
nestedWLSCategory = getSubCategory(wlsCompositeFilter.getName());
// Create a new filter for captuing just the wls & wls jms threads that dont fall under any known wls thread groups
CompositeFilter wlsJMSThreadsFilter = new CompositeFilter("WLS JMS");
wlsJMSThreadsFilter.addFilter(wlsJMSFilter1, true);
wlsJMSThreadsFilter.addFilter(wlsJMSFilter2, true);
nestedWLSCategory.addToFilters(wlsJMSThreadsFilter);
CompositeFilter wlsThreadsFilter = new CompositeFilter(REST_OF_WLS);
wlsThreadsFilter.addFilter(allWLSThreadStackFilter, true);
wlsThreadsFilter.addFilter(allWLSThreadNameFilter, true);
// Exclude wls jms from pure wls related group
wlsThreadsFilter.addFilter(wlsJMSFilter1, false);
wlsThreadsFilter.addFilter(wlsJMSFilter2, false);
nestedWLSCategory.addToFilters(wlsThreadsFilter);
for (Filter filter : allWLSFilterList) {
nestedWLSCategory.addToFilters(filter);
wlsThreadsFilter.addFilter(filter, false);
wlsJMSThreadsFilter.addFilter(filter, false);
}
allWLSFilterList.add(wlsJMSThreadsFilter);
allWLSFilterList.add(wlsThreadsFilter);
}
private void addFilters() {
createWLSFilterCategories();
createNonWLSFilterCategories();
// Create references to the Muxer, AQ Adapter and LDAP Filters as they are referred for Exclusion for the nested Filter for Socket Read
for (Filter filter : allKnownFilterMap.values()) {
if (filter instanceof CompositeFilter) {
continue;
}
String filterName = filter.getName().toLowerCase();
if (filterName.contains("muxer")) {
muxerThreadsFilter = filter;
} else if (filterName.startsWith("ldap")) {
ldapThreadsFilter = filter;
} else if (filterName.contains("aq adapter")) {
aqAdapterThreadsFilter = filter;
}
}
Arrays.fill(wlsDefaultExecuteThreadIds, -1);
LinkedList<ThreadInfo> pendingThreadList = new LinkedList<ThreadInfo>(threadLinkedList);
createThreadGroups(pendingThreadList, allWLSFilterList, true, nestedWLSCategory);
createThreadGroups(pendingThreadList, allNonWLSFilterList, false, nestedNonWLSCategory);
// Check for Missing ExecuteThread Ids now that WLS related threads have been filtered.
StringBuffer missingExecuteThreadIdsBuf = new StringBuffer(100);
boolean firstThread = true;
for (int i = 0; i <= maxWlsDefaultExecuteThreadId; i++) {
if (wlsDefaultExecuteThreadIds[i] == -1) {
if (!firstThread)
missingExecuteThreadIdsBuf.append(", ");
missingExecuteThreadIdsBuf.append("ExecuteThread: '" + i + "'");
firstThread = false;
}
}
if (missingExecuteThreadIdsBuf.length() > 0) {
theLogger.warning("WLS Default ExecuteThreads Missing : "
+ missingExecuteThreadIdsBuf.toString());
ThreadGroup restOfWLSTG = null;
for(ThreadGroup tg: wlsThreadGroupList) {
if (tg.getName().equals(REST_OF_WLS)) {
restOfWLSTG = tg;
ThreadAdvisory missingThreadAdvisory
= ThreadAdvisory.lookupThreadAdvisoryByName(
ThreadLogicConstants.WLS_EXECUTETHREADS_MISSING);
missingThreadAdvisory.setDescrp(missingThreadAdvisory.getDescrp()
+ ". Missing Thread Ids: " + missingExecuteThreadIdsBuf.toString());
((RestOfWLSThreadGroup)restOfWLSTG).addMissingThreadsAdvisory(missingThreadAdvisory);
break;
}
}
if (restOfWLSTG != null) {
for(Filter filter: allWLSFilterList) {
if (filter.getName().equals(REST_OF_WLS)) {
Filter restOfWLSFilter = filter;
restOfWLSFilter.setInfo(restOfWLSTG.getOverview());
break;
}
}
}
}
// For the rest of the unknown type threads, add them to the unknown group
for (ThreadInfo ti : pendingThreadList) {
unknownThreadGroup.addThread(ti);
ti.setThreadGroup(unknownThreadGroup);
}
createThreadGroupNestedCategories(unknownThreadGroup, unknownCompositeFilter, nestedNonWLSCategory);
}
private void createThreadGroups(LinkedList<ThreadInfo> pendingThreadList, ArrayList<Filter> filterList, boolean isWLSThreadGroup, NestedCategory parentCategory) {
for (Filter filter : filterList) {
String name = filter.getName();
// Special processing for Unknown thread group
// only the remaining threads have to be added to Unknown thread group
if (name.contains("Unknown")) {
continue;
}
ThreadGroup tg = ThreadGroupFactory.createThreadGroup(name);
ArrayList<String> excludedAdvisories = filter.getExcludedAdvisories();
if (excludedAdvisories != null && excludedAdvisories.size() > 0) {
for(String advisoryId: filter.getExcludedAdvisories()) {
//theLogger.finest(name + " > Adding exclusion for:" + advisoryId);
ThreadAdvisory tadv = ThreadAdvisory.lookupThreadAdvisoryByName(advisoryId);
//theLogger.finest("Found ThreadAdvisory :" + tadv);
if (tadv != null)
tg.addToExclusionList(tadv);
}
}
boolean foundAtleastOneThread = false;
for (Iterator<ThreadInfo> iterator = pendingThreadList.iterator(); iterator.hasNext();) {
ThreadInfo ti = iterator.next();
// Check for the thread id and mark it for WLS Default ExecuteThreads
if (isWLSThreadGroup) {
int threadId = getWLSDefaultExecuteThreadId(ti);
if (threadId >= 0) {
if (threadId > maxWlsDefaultExecuteThreadId) {
maxWlsDefaultExecuteThreadId = threadId;
}
incrementTotalWLSDefaultExecuteThreads();
wlsDefaultExecuteThreadIds[threadId] = 1;
}
}
if (filter.matches(ti)) {
//theLogger.finest("Found Match against filter: " + filter.getName() + ", for Thread:" + ti.getName());
tg.addThread(ti);
ti.setThreadGroup(tg);
iterator.remove();
foundAtleastOneThread = true;
}
}
if (foundAtleastOneThread) {
threadGroupList.add(tg);
if (isWLSThreadGroup) {
wlsThreadGroupList.add(tg);
} else {
nonWlsThreadGroupList.add(tg);
}
createThreadGroupNestedCategories(tg, filter, parentCategory);
}
}
}
private void createThreadGroupNestedCategories(ThreadGroup tg, Filter associatedFilter, NestedCategory parentCategory) {
tg.runAdvisory();
NestedCategory nestedCategory = parentCategory.getSubCategory(associatedFilter.getName());
HealthLevelAdvisoryFilter warningFilter = new HealthLevelAdvisoryFilter("Threads at Warning Or Above",
HealthLevel.WARNING);
nestedCategory.addToFilters(warningFilter);
// nestedCategory.addToFilters(blockedFilter);
// nestedCategory.addToFilters(stuckFilter);
// nestedCategory.setAsBlockedIcon();
CompositeFilter readsCompositeFilter = new CompositeFilter("Reading Data From Remote Endpoint");
readsCompositeFilter.setInfo("The thread is waiting for a remote response or still reading incoming request (via socket or rmi call)");
Filter waitingOnRemote = new Filter("Reading Data From Remote Endpoint", "(socketRead)|(ResponseImpl.waitForData)",
2, false, false, true);
readsCompositeFilter.addFilter(waitingOnRemote, true);
readsCompositeFilter.addFilter(ldapThreadsFilter, false);
readsCompositeFilter.addFilter(muxerThreadsFilter, false);
readsCompositeFilter.addFilter(aqAdapterThreadsFilter, false);
nestedCategory.addToFilters(readsCompositeFilter);
ArrayList<HotCallPattern> hotPatterns = tg.getHotPatterns();
if (hotPatterns.size() > 0) {
int count = 1;
ThreadAdvisory hotcallPatternAdvsiory = ThreadAdvisory.getHotPatternAdvisory();
for (HotCallPattern hotcall : hotPatterns) {
HotCallPatternFilter fil = new HotCallPatternFilter("Hot Call Pattern - " + count, hotcall.geThreadPattern());
String color = hotcallPatternAdvsiory.getHealth().getBackgroundRGBCode();
StringBuffer sb = new StringBuffer("<font size=5>Advisories: ");
ThreadLogic.appendAdvisoryLink(sb, hotcallPatternAdvsiory);
sb.append("</font><br><br>");
fil.setInfo(sb.toString() + "<pre> Multiple Threads are exhibiting following call execution pattern:\n"
+ hotcall.geThreadPattern() + "</pre>");
nestedCategory.addToFilters(fil);
count++;
}
}
associatedFilter.setInfo(tg.getOverview());
}
public boolean isWLSDefaultExecuteThread(ThreadInfo ti) {
String threadName = ti.getName();
if (threadName == null)
return false;
return threadName.contains("weblogic.kernel.Default") && threadName.contains("ExecuteThread");
}
public int getWLSDefaultExecuteThreadId(ThreadInfo ti) {
if (!isWLSDefaultExecuteThread(ti))
return -1;
try {
int threadIdBeginIndex = ti.getName().indexOf("ExecuteThread: '") + 16;// "ExecuteThread: 'ID';
int threadIdEndIndex = ti.getName().indexOf("'", threadIdBeginIndex+1);
return Integer.parseInt(ti.getName().substring(threadIdBeginIndex, threadIdEndIndex));
} catch(Exception e) {
return -1;
}
}
public int getTotalWLSDefaultExecuteThreads() {
return totalWlsDefaultExecuteThreads;
}
public int incrementTotalWLSDefaultExecuteThreads() {
return ++totalWlsDefaultExecuteThreads;
}
public int getMaxWLSDefaultExecuteThreadId() {
return maxWlsDefaultExecuteThreadId;
}
}
| true |
9c8d84249cea266443a0fcda031d055f5dda3e17 | Java | thiagoleao/service-extrato-cc | /src/main/java/br/com/banco/serviceextratocc/db/repository/ExtratoContaCorrenteRepository.java | UTF-8 | 385 | 1.734375 | 2 | [] | no_license | package br.com.banco.serviceextratocc.db.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import br.com.banco.serviceextratocc.db.model.ExtratoContaCorrente;
public interface ExtratoContaCorrenteRepository extends JpaRepository<ExtratoContaCorrente, Long> {
List<ExtratoContaCorrente> findByContaID(Long contaID);
}
| true |
0ef38b7990523af1e9e9fd2eb079cbf4358d8cc3 | Java | artemyakovenko28/IO | /src/_5_labs/_2_stream/_4_strategy/BAOSTest.java | UTF-8 | 470 | 2.84375 | 3 | [] | no_license | package _5_labs._2_stream._4_strategy;
import java.io.IOException;
import java.util.Arrays;
public class BAOSTest {
public static void main(String[] args) throws IOException {
BAOSWithStrategyWithoutCopying baos = new BAOSWithStrategyWithoutCopying(2);
for (int k = 0; k < 20; k++) {
baos.write((byte) (Math.random() * 10));
}
System.out.println(Arrays.toString(baos.toByteArray()));
baos.showBuffers();
}
}
| true |
8f44a71140d945401251da388d399b0f94ee866d | Java | davidCabrera11/CodePath_FlashcardApp | /app/src/main/java/com/example/dc11/flashcardapp/MainActivity.java | UTF-8 | 2,478 | 2.515625 | 3 | [] | no_license | package com.example.dc11.flashcardapp;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Flash Card Question
findViewById(R.id.flashcardQuestion).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
findViewById(R.id.flashcardAnswer).setVisibility(View.VISIBLE);
findViewById(R.id.flashcardQuestion).setVisibility(View.INVISIBLE);
}
});
// Flash Card Answer
findViewById(R.id.flashcardAnswer).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
findViewById(R.id.flashcardAnswer).setVisibility(View.INVISIBLE);
findViewById(R.id.flashcardQuestion).setVisibility(View.VISIBLE);
}
});
//Go to addCard Activity
findViewById(R.id.addCardScreen).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Intent to go to the addCard Activity
// And to retrieve data from activity addCardActivity
// with the identification number of 100
Intent intent = new Intent(MainActivity.this, addCardActivity.class);
MainActivity.this.startActivityForResult(intent, 100);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 100) { // this 100 needs to match the 100 we used when we called startActivityForResult!
String strQuestion = data.getExtras().getString("question"); // 'string1' needs to match the key we used when we put the string in the Intent
String strAnswer = data.getExtras().getString("answer");
//Change Text View in Main
((TextView) findViewById(R.id.flashcardQuestion)).setText(strQuestion);
((TextView) findViewById(R.id.flashcardAnswer)).setText(strAnswer);
}
}
} | true |
49943d19cb2f48e338f888459e11592935f175c3 | Java | silionXi/SerializableAndParcelable | /app/src/main/java/com/silion/serializableandparcelable/SecondActivity.java | UTF-8 | 1,305 | 2.46875 | 2 | [] | no_license | package com.silion.serializableandparcelable;
import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.widget.LinearLayout;
import android.widget.TextView;
/**
* Created by silion on 2015/10/14.
*/
public class SecondActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
LinearLayout layout = (LinearLayout) findViewById(R.id.contentLayout);
TextView serializableTextView = new TextView(this);
TextView parcelableTextView = new TextView(this);
SerializableObject serializableObject = (SerializableObject) getIntent().getSerializableExtra("serializable");
ParcelableObject parcelableObject = getIntent().getParcelableExtra("parcelable");
if (serializableObject != null) {
serializableTextView.setText("str = " + serializableObject.getStr() + ", i = " + serializableObject.getI());
}
if (parcelableObject != null) {
parcelableTextView.setText("str = " + parcelableObject.getStr() + ", i = " + parcelableObject.getI());
}
layout.addView(serializableTextView);
layout.addView(parcelableTextView);
}
}
| true |
1a39ad1c34c29ec1b289472152d087f6de889b2d | Java | new-silvermoon/MoodWearApp | /app/src/main/java/com/silvermoon/moodwearapp/model/MoodDBHelper.java | UTF-8 | 1,256 | 2.375 | 2 | [] | no_license | package com.silvermoon.moodwearapp.model;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class MoodDBHelper extends SQLiteOpenHelper {
public static final int DB_VERSION = 1;
public MoodDBHelper(Context context) {
super(context, MoodContract.DB_NAME, null, DB_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
final String createMoodQuery = "CREATE TABLE " + MoodContract.Mood.TABLE_NAME + " ("
+ MoodContract.Mood._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ MoodContract.Mood.MOOD_NAME + " TEXT, "
+ MoodContract.Mood.INSRTD_TSMP + " INTEGER DEFAULT 0 "
+ ")";
final String createDistractQuery = "CREATE TABLE " + MoodContract.Distraction.TABLE_NAME + " ("
+ MoodContract.Distraction._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ MoodContract.Distraction.INSRTD_TSMP + " INTEGER DEFAULT 0 "
+ ")";
db.execSQL(createMoodQuery);
db.execSQL(createDistractQuery);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
| true |
20ea49cfcca5af41391e478abe6c3c2330c9d813 | Java | maximusfl/pvt | /glucozaDisplay/src/main/java/by/pvt/user/AppUserRepository.java | UTF-8 | 1,239 | 2.1875 | 2 | [] | no_license | package by.pvt.user;
import by.pvt.pojo.AppUser;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import java.util.logging.Logger;
@Repository
public class AppUserRepository {
private static Logger log = Logger.getLogger("AppUserRepo");
@Autowired
SessionFactory sessionFactory;
public Integer findUserCountByLogin(String username) {
return sessionFactory.getCurrentSession()
.createQuery("from AppUser where username like :param1", AppUser.class)
.setParameter("param1", username)
.list()
.size();
}
public void save(AppUser user) {
sessionFactory.getCurrentSession().save(user);
}
public AppUser findUserByLogin(String username) {
try {
return sessionFactory.getCurrentSession()
.createQuery("from AppUser where username like :param1", AppUser.class)
.setParameter("param1", username)
.getSingleResult();
} catch (Exception e) {
log.warning(e.getMessage());
return null;
}
}
}
| true |
b2d9e09df4417d9cf6d887312e3c0201c9cf5fc4 | Java | IDemiurge/Eidolons | /Eidolon-Core/src/main/java/eidolons/game/battlecraft/rules/buff/EssenceBuffRule.java | UTF-8 | 3,748 | 2.078125 | 2 | [] | no_license | package eidolons.game.battlecraft.rules.buff;
import eidolons.ability.conditions.shortcut.StdPassiveCondition;
import eidolons.ability.effects.common.ModifyValueEffect;
import eidolons.ability.effects.continuous.BehaviorModeEffect;
import eidolons.content.PARAMS;
import eidolons.game.battlecraft.rules.RuleEnums;
import eidolons.game.battlecraft.rules.RuleEnums.COMBAT_RULES;
import main.ability.effects.Effect;
import main.ability.effects.Effect.MOD;
import main.ability.effects.Effects;
import main.ability.effects.container.ConditionalEffect;
import main.content.VALUE;
import main.content.enums.entity.UnitEnums;
import main.content.enums.system.AiEnums;
import main.content.enums.system.MetaEnums;
import main.elements.conditions.Condition;
import main.elements.conditions.NotCondition;
import main.entity.Ref.KEYS;
import main.game.core.game.GenericGame;
import main.system.auxiliary.StringMaster;
import main.system.auxiliary.Strings;
public class EssenceBuffRule extends DC_BuffRule {
public static final String[] buffNames = {
MetaEnums.STD_BUFF_NAME.Panic.getName(),
MetaEnums.STD_BUFF_NAME.Fearful.getName(),
MetaEnums.STD_BUFF_NAME.Inspired.getName()
};
public static final String[] formulas = {"1", "20", "200",};
public static final String parameterString = PARAMS.SPIRIT.getName()
+ Strings.VERTICAL_BAR + PARAMS.RESISTANCE.getName();
public EssenceBuffRule(GenericGame game) {
super(game);
}
@Override
protected Effect getEffect() {
return getEffect(this.level);
}
protected Effect getEffect(int level) {
switch (level) {
case 0: {
return new ConditionalEffect(new NotCondition(new StdPassiveCondition(
UnitEnums.STANDARD_PASSIVES.FEARLESS)),
new Effects(new ModifyValueEffect(parameterString,
MOD.MODIFY_BY_PERCENT, "("
+ StringMaster.getValueRef(KEYS.SOURCE, getValue()) + "-"
+ formulas[level] + ")*2"), new BehaviorModeEffect(
AiEnums.BEHAVIOR_MODE.PANIC)));
// return new OwnershipChangeEffect();
}
case 1: {
return new ConditionalEffect(new NotCondition(new StdPassiveCondition(
UnitEnums.STANDARD_PASSIVES.FEARLESS)), new Effects(new ModifyValueEffect(
parameterString, MOD.MODIFY_BY_PERCENT, "("
+ StringMaster.getValueRef(KEYS.SOURCE, getValue()) + "-"
+ formulas[level] + ")*2")));
}
case 2: {
String maxFormula = "100";
return new Effects(new ModifyValueEffect(parameterString,
MOD.MODIFY_BY_PERCENT, "("
+ StringMaster.getValueRef(KEYS.SOURCE, getValue()) + "-"
+ formulas[level] + ")/4", maxFormula));
}
}
return null;
}
protected Condition getBuffConditions() {
return new NotCondition(new StdPassiveCondition(UnitEnums.STANDARD_PASSIVES.DISPASSIONATE));
}
@Override
protected boolean isConditionGreater(Integer level) {
if (level == getMaxLevel()) {
return true;
}
return super.isConditionGreater(level);
}
@Override
public Integer getMaxLevel() {
return 2;
}
@Override
protected VALUE getValue() {
return PARAMS.C_ESSENCE;
}
protected String[] getConditionFormulas() {
return formulas;
}
@Override
protected String[] getBuffNames() {
return buffNames;
}
@Override
protected COMBAT_RULES getCombatRuleEnum() {
return RuleEnums.COMBAT_RULES.ESSENCE;
}
}
| true |
e1305990055671bfab7c59b6719b119f3cdc801b | Java | FRCTeam3255/BenchBot2016 | /src/org/usfirst/frc/team3255/robot/RobotMap.java | UTF-8 | 2,235 | 2.71875 | 3 | [] | no_license | package org.usfirst.frc.team3255.robot;
/**
* The RobotMap is a mapping from the ports sensors and actuators are wired into
* to a variable name. This provides flexibility changing wiring, makes checking
* the wiring easier and significantly reduces the number of magic numbers
* floating around.
*/
public class RobotMap {
// For example to map the left and right motors, you could define the
// following variables to use with your drivetrain subsystem.
// public static int leftMotor = 1;
// public static int rightMotor = 2;
//Joysticks
public static final int JOYSTICK_DRIVER = 0;
public static final int JOYSTICK_MANIPULATOR = 1;
// PWM Ports
public static final int DRIVETRAIN_FRONT_LEFT_TALON = 0;
public static final int DRIVETRAIN_BACK_LEFT_TALON = 1;
public static final int DRIVETRAIN_FRONT_RIGHT_TALON = 2;
public static final int DRIVETRAIN_BACK_RIGHT_TALON = 3;
public static final int CASSETTE_LEFT_LIFT_TALON = 6;
public static final int CASSETTE_RIGHT_LIFT_TALON = 7;
// CAN Bus IDs
public static final int DRIVETRAIN_FRONT_LEFT_CANTALON = 0;
public static final int DRIVETRAIN_BACK_LEFT_CANTALON = 1;
public static final int DRIVETRAIN_FRONT_RIGHT_CANTALON = 2;
public static final int DRIVETRAIN_BACK_RIGHT_CANTALON = 3;
public static final int SHOOTER_LEFT_FLYWHEEL_CANTALON = 4;
public static final int SHOOTER_RIGHT_FLYWHEEL_CANTALON = 5;
// Digital IO Ports
public static final int DRIVETRAIN_LEFT_ENCODER_CHA = 2;
public static final int DRIVETRAIN_LEFT_ENCODER_CHB = 3;
public static final int CASSETTE_LIFT_ENCODER_CHA = 8;
public static final int CASSETTE_LIFT_ENCODER_CHB = 9;
public static final int SHOOTER_FLYWHEEL_ENCODER_CHA = 4;
public static final int SHOOTER_FLYWHEEL_ENCODER_CHB = 5;
// Solenoids
public static final int SOLENOID_OPEN = 6;
public static final int SOLENOID_CLOSE = 7;
//Axies
public static final int AXIS_ARCADE_MOVE = 1;
public static final int AXIS_ARCADE_ROTATE = 2;
// If you are using multiple modules, make sure to define both the port
// number and the module. For example you with a rangefinder:
// public static int rangefinderPort = 1;
// public static int rangefinderModule = 1;
}
| true |
799a0585e6b6d008bce60d59883e9bec5fc90e33 | Java | longoro1/Taekwondo-Time-Tracker-Android | /app/src/main/java/com/hackbitstudios/taekwondo_time_tracker_android/SettingsActivity.java | UTF-8 | 2,101 | 2.53125 | 3 | [
"Apache-2.0"
] | permissive | package com.hackbitstudios.taekwondo_time_tracker_android;
import android.app.ActionBar;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.view.MenuItem;
public class SettingsActivity extends PreferenceActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Add back button to action bar
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
setupSimplePreferencesScreen();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == android.R.id.home) {
this.finish();
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* Shows the simplified settings UI if the device configuration if the
* device configuration dictates that a simplified, single-pane UI should be
* shown.
*/
private void setupSimplePreferencesScreen() {
// Add 'general' preferences.
addPreferencesFromResource(R.xml.preferences);
}
/**
* A preference value change listener that updates the preference's summary
* to reflect its new value.
*/
private static Preference.OnPreferenceChangeListener sBindPreferenceSummaryToValueListener = new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object value) {
// Get and store the preference on change
String stringValue = value.toString();
preference.setSummary(stringValue);
return true;
}
};
}
| true |
c24a69069df5bd5ef993e86d2a44902eef13c77a | Java | Oleglogin/yaruna | /src/main/java/ua/lv/service/ElseImgService.java | UTF-8 | 287 | 1.851563 | 2 | [] | no_license | package ua.lv.service;
import ua.lv.entity.ElseImg;
import java.util.List;
/**
* Created by User on 07.04.2019.
*/
public interface ElseImgService {
void addElseImg(ElseImg elseImg);
void deleteElseImg(int id);
List<ElseImg>elseImgList();
ElseImg findOne(int id);
}
| true |
a02cd0eb12117130df0f8293afebad8238d7947c | Java | aleguzman5/Flooring-Mastery | /src/main/java/com/sg/flooringmastery/dao/OrderProdDaoStubImpl.java | UTF-8 | 3,028 | 2.59375 | 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 com.sg.flooringmastery.dao;
import com.sg.flooringmastery.dto.Order;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
/**
*
* @author Alejandro
*/
public class OrderProdDaoStubImpl implements OrderDao {
Order onlyOrder;
List<Order> orderList = new ArrayList<>();
public OrderProdDaoStubImpl() {
onlyOrder = new Order(1);
onlyOrder.setCustomerName("John Doe");
onlyOrder.setState("IN");
onlyOrder.setProductType("Wood");
onlyOrder.setArea(new BigDecimal(10));
onlyOrder.setDate("092017");
onlyOrder.setSqFtLaborCost(BigDecimal.ZERO);
onlyOrder.setSqFtMaterialCost(BigDecimal.ZERO);
onlyOrder.setTaxRate(BigDecimal.ZERO);
onlyOrder.setTotalLaborCost(BigDecimal.ZERO);
onlyOrder.setTotalMaterialCost(BigDecimal.ZERO);
onlyOrder.setTotalTax(BigDecimal.ONE);
onlyOrder.setTotalTotal(BigDecimal.ZERO);
orderList.add(onlyOrder);
}
@Override
public Order addOrder(Order order) throws FlooringPersistenceException {
if (order.getOrderNum() == onlyOrder.getOrderNum()) {
return onlyOrder;
} else {
return null;
}
}
@Override
public List<Order> getOrdersFromCertainDate(String date) throws FlooringPersistenceException {
return orderList.stream()
.filter(o -> o.getDate().equals(date))
.collect(Collectors.toList());
}
@Override
public Order removeOrder(int orderNum, String date) throws FlooringPersistenceException {
if (orderNum == onlyOrder.getOrderNum() && date.equals(onlyOrder.getDate())) {
return onlyOrder;
} else {
return null;
}
}
@Override
public void saveCurrentWork() throws FlooringPersistenceException {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public Order getOrder(int orderNum, String date) throws FlooringPersistenceException {
if (orderNum == onlyOrder.getOrderNum() && date.equals(onlyOrder.getDate())) {
return onlyOrder;
} else {
return null;
}
}
@Override
public int getTotalOfOrders() throws FlooringPersistenceException {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public Order editOrder(Order order) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public List<Order> getAllOrders() {
return orderList;
}
}
| true |
138fd193298f4ed972a4a367625852571df34f9e | Java | KnzHz/fpv_live | /src/main/java/com/dji/lifecycle/core/annotation/OnLifecycleEvent.java | UTF-8 | 385 | 2.015625 | 2 | [] | no_license | package com.dji.lifecycle.core.annotation;
import com.dji.lifecycle.core.LifecycleEvent;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface OnLifecycleEvent {
LifecycleEvent value();
}
| true |
6637431fcf388b3ec27f3c566f1e7cda0567fb24 | Java | AmadaGS/eoeGeekCamp-201312 | /AmadaGS/2014-01-10/Book.java | GB18030 | 871 | 3.265625 | 3 | [] | no_license | package com.eoe.oop.day02.entity;
public class Book {
public int id;//
public String name;//
public Person author;//
public String isbn;//
public double price;//
public Book(){
}
public Book(int id, String name, Person author, String isbn, double price) {
super();
this.id = id;
this.name = name;
this.author = author;
this.isbn = isbn;
this.price = price;
}
@Override
public String toString() {
return this.name;
}
@Override
public boolean equals(Object obj) {
Book book=null;
if(obj==null){
return false;
}
if(obj instanceof Book){
book=(Book) obj;
}else{
return false;
}
return this.isbn.equals(book.isbn);
}
public String details(){
return ":"+this.name+
"\n:"+this.author.toString()+
"\n:"+this.isbn+
"\n:"+this.price+"Ԫ";
}
}
| true |
d19e2baf1abef4da03ea893d808090c78861736f | Java | lichaoliu/lottery | /src/main/java/com/lottery/ticket/checker/worker/HuanCaiVenderTicketCheckWorker.java | UTF-8 | 5,251 | 2.109375 | 2 | [] | no_license | package com.lottery.ticket.checker.worker;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import com.lottery.common.contains.lottery.TerminalType;
import com.lottery.common.contains.lottery.TicketVenderStatus;
import com.lottery.common.contains.ticket.TicketVender;
import com.lottery.common.util.DateUtil;
import com.lottery.common.util.HTTPUtil;
import com.lottery.common.util.MD5Util;
import com.lottery.core.domain.ticket.Ticket;
import com.lottery.ticket.IVenderConfig;
import com.lottery.ticket.IVenderConverter;
import com.lottery.ticket.sender.worker.XmlParse;
import com.lottery.ticket.vender.impl.huancai.HuancaiConfig;
@Component
public class HuanCaiVenderTicketCheckWorker extends AbstractVenderTicketCheckWorker {
private final Logger caidaolog= LoggerFactory.getLogger("caidao-warn");
@Override
public List<TicketVender> process(List<Ticket> ticketList, IVenderConfig venderConfig,IVenderConverter venderConverter) throws Exception {
return dealResult(ticketList, venderConfig);
}
/**
* 查票结果处理
*
*/
private List<TicketVender> dealResult(List<Ticket> ticketBatchList, IVenderConfig venderConfig) {
List<TicketVender> ticketvenderList = new ArrayList<TicketVender>();
String messageStr="";
String returnStr="";
try {
Map<String, Ticket> ticketMap = new HashMap<String, Ticket>();
for (Ticket ticket : ticketBatchList) {
ticketMap.put(ticket.getId(), ticket);
}
messageStr = getElement(ticketBatchList, venderConfig);
caidaolog.error("环彩查询:{}",messageStr);
returnStr = HTTPUtil.sendPostMsg(venderConfig.getRequestUrl(), messageStr);
HashMap<String, String> mapCode = XmlParse.getElementAttribute("/", "response", returnStr);
String code = mapCode.get("code");
if (code.equals("0000")) {
List<HashMap<String, String>> mapLists = XmlParse.getElementAttributeList("response/tickets/", "ticket", returnStr);
if(mapLists==null||mapLists.isEmpty()){
for (Ticket ticket : ticketBatchList) {
TicketVender ticketVender = createTicketVender(venderConfig.getTerminalId(), TerminalType.T_HUANCAI);
ticketVender.setStatus(TicketVenderStatus.not_found);
ticketVender.setMessage("不存在此票");
ticketVender.setId(ticket.getId());
ticketvenderList.add(ticketVender);
ticketVender.setResponseMessage(returnStr);
}
return ticketvenderList;
}
for (HashMap<String, String> map : mapLists) {
String ticketId = map.get("ticketid");
String status = map.get("status");
TicketVender ticketVender = createTicketVender(venderConfig.getTerminalId(), TerminalType.T_HUANCAI);
ticketVender.setId(ticketId);
ticketVender.setStatusCode(status);
ticketVender.setSendMessage(messageStr);
ticketVender.setResponseMessage(returnStr);
ticketvenderList.add(ticketVender);
if ("1".equals(status)) {
ticketVender.setStatus(TicketVenderStatus.printing);
ticketVender.setMessage("出票中");
} else if ("2".equals(status)) {
ticketVender.setStatus(TicketVenderStatus.success);
ticketVender.setMessage("出票成功");
ticketVender.setPrintTime(new Date());
} else if ("3".equals(status)) {
ticketVender.setStatus(TicketVenderStatus.failed);
ticketVender.setMessage("出票失败");
} else {
ticketVender.setStatus(TicketVenderStatus.unkown);
ticketVender.setMessage("未知异常");
}
}
} else {
logger.error("环彩查票返回结果异常,发送:{},返回:{}", messageStr, returnStr);
}
} catch (Exception e) {
logger.error("环彩查票异常,发送:{},返回:{},异常为", messageStr, returnStr);
logger.error(e.getMessage(),e);
}
return ticketvenderList;
}
/**
* 查票前拼串
*
* @param ticketBatchList
* 票集合
* @return
* @throws Exception
* @throws Exception
*/
private String getElement(List<Ticket> ticketBatchList, IVenderConfig huancaiConfig) throws Exception {
String queryCode = "1003";
// 头部
String md = "";
XmlParse xmlParse = null;
String messageId=DateUtil.format("yyyyMMddHHmmss", new Date());;
xmlParse = HuancaiConfig.addGxHead(queryCode,huancaiConfig.getAgentCode(),messageId);
Element bodyeElement = xmlParse.getBodyElement();
Element elements = bodyeElement.addElement("tickets");
HashMap<String, Object> bodyAttr = null;
for (Ticket ticket : ticketBatchList) {
bodyAttr = new HashMap<String, Object>();
bodyAttr.put("ticketid", ticket.getId());
Element element2 = elements.addElement("ticket");
xmlParse.addElementAttribute(element2,bodyAttr);
}
try {
md = MD5Util.toMd5(huancaiConfig.getAgentCode()+messageId + huancaiConfig.getKey() + xmlParse.getBodyElement().asXML());
} catch (Exception e) {
logger.error("加密异常" + e.getMessage());
}
xmlParse.addHeaderElement("digest", md);
return "cmd="+queryCode+"&msg="+xmlParse.asXML();
}
@Override
protected TerminalType getTerminalType() {
return TerminalType.T_HUANCAI;
}
}
| true |
2afef87535706f95e3c1f9d8af00f29431906679 | Java | google-code/blunet | /blunet-client/view/ExitAlert.java | UTF-8 | 1,302 | 2.4375 | 2 | [] | no_license | package view;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.MIDletStateChangeException;
import core.*;
import util.*;
import blunet.blunet;
public class ExitAlert extends BaseScreen {
private Command Cancel, Exit;
private Alert alert;
Displayable current;
public ExitAlert(blunet midlet) {
super(midlet);
alert = new Alert("", "Exit?", null, AlertType.CONFIRMATION);
Exit = new Command("Yes", Command.ITEM, 1);
Cancel = new Command("No", Command.CANCEL, 1);
alert.addCommand(Cancel);
alert.addCommand(Exit);
alert.setTimeout(Alert.FOREVER);
alert.setCommandListener(this);
displayable = alert;
current = Display.getDisplay(midlet).getCurrent();
}
public void commandAction(Command cmd, Displayable d) {
if (cmd == Exit) {
try {
// all clean up works go here
alert.removeCommand(Exit);
alert.removeCommand(Cancel);
alert.setString("Exiting ...");
midlet.destroyApp(true);
midlet.notifyDestroyed();
} catch (Exception e) {
System.out.println("Exit: " + e.toString());
Display.getDisplay(midlet).setCurrent(current);
}
}
if (cmd == Cancel) {
Display.getDisplay(midlet).setCurrent(current);
}
}
}
| true |
dd08e57aab10206b0b2c6b8829ec71c7d8dec747 | Java | arharg/marketsurveys | /src/main/java/com/mrs/marketsurveys/domain/SurveyOrganisation.java | UTF-8 | 103 | 1.75 | 2 | [] | no_license | package com.mrs.marketsurveys.domain;
public enum SurveyOrganisation {
OMNIBUS, ADHOC, SYNDICATED;
}
| true |
585a6d9e61014d3efe18a44e0b2168cda2a7114f | Java | beck766/SchoolMates | /app/src/main/java/com/beck/helloschoolmate/model/repository/AddFriSearchRepository.java | UTF-8 | 1,309 | 2.171875 | 2 | [] | no_license | package com.beck.helloschoolmate.model.repository;
import android.content.Context;
import android.util.Log;
import com.beck.base.util.NetworkUtils;
import com.beck.helloschoolmate.model.http.ApiClient;
import com.beck.helloschoolmate.model.http.ApiConstants;
import com.beck.helloschoolmate.model.http.entity.addfriend.AddFriSearchRequest;
import com.beck.helloschoolmate.model.http.entity.addfriend.AddFriSearchResponse;
import com.beck.helloschoolmate.model.http.service.MatesService;
import io.reactivex.Emitter;
import io.reactivex.Observable;
/**
* Created by beck on 2018/6/2.
*/
public class AddFriSearchRepository {
private static final String TAG = "AddFriSearchRepository";
public Observable<AddFriSearchResponse> getAddFriResponse(Context context, String accessToken, AddFriSearchRequest request) {
if (!NetworkUtils.isNetworkConnected(context)) {
Log.i(TAG, "getLoginResponse: 网络异常");
return Observable.create(Emitter::onComplete);
}
Observable<AddFriSearchResponse> addFriSearchResponseObservable = ApiClient.initMatesService(ApiConstants.MATE_HOST, MatesService.class).addFriendSearch(accessToken, request);
assert addFriSearchResponseObservable != null;
return addFriSearchResponseObservable;
}
}
| true |
2813d4a0b4a61034359ce418f4d2db7b075cd66b | Java | MangeshTak/Freelancer-Springboot | /Freelancer_Server/src/main/java/com/entity/Bid.java | UTF-8 | 1,248 | 2.265625 | 2 | [] | no_license | package com.entity;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
@Entity // This tells Hibernate to make a table out of this class
@Table(name="bid")
public class Bid {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Integer id;
String bidPrice;
String days;
String user;
String status;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "project_id", nullable = false)
Projects projects;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getBidPrice() {
return bidPrice;
}
public void setBidPrice(String bidPrice) {
this.bidPrice = bidPrice;
}
public String getDays() {
return days;
}
public void setDays(String days) {
this.days = days;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
| true |
be20fe5e60897b0ef04a26ce0fb435b7c8c1333e | Java | namdda/bitsaltlux_semiproject | /src/main/java/co/kr/wdt/achievement/dao/AchievementDao.java | UTF-8 | 871 | 2.046875 | 2 | [] | no_license | package co.kr.wdt.achievement.dao;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import co.kr.wdt.achievement.vo.AchievementVo;
import co.kr.wdt.common.dao.CommonSqlDao2;
@Repository
public class AchievementDao extends CommonSqlDao2{
private static String PREFIX = "AchievementMapper.";
// 생성
public void insert(int todono) {
insert(PREFIX+"insert", todono);
}
// 삭제 기능
public boolean deleteProc(int todono) {
return 1 == (int)delete(PREFIX+"delete", todono);
}
// 수정 기능
public boolean updateProc(AchievementVo vo) {
return 1 == (int)update(PREFIX+"update",vo);
}
// 조회 기능 (todo번호)
public AchievementVo selectByTodoNo(int todono) {
return (AchievementVo)selectOne(PREFIX+"select",todono);
}
} | true |
e461abbc46cd58c654942bb151e958a7f0010b41 | Java | bokimilinkovic/xml-web-services | /cars-ads-app/src/main/java/CarsAdsApp/model/dto/AdDTO.java | UTF-8 | 1,406 | 2.40625 | 2 | [] | no_license | package CarsAdsApp.model.dto;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import java.time.LocalDateTime;
public class AdDTO {
private String startDate;
private String endDate;
private String place;
private Long carId;
private Long priceListId;
public AdDTO() {
}
public AdDTO(String startDate, String endDate, String place, Long car, Long priceListId) {
this.startDate = startDate;
this.endDate = endDate;
this.place = place;
this.carId = car;
this.priceListId = priceListId;
}
public String getStartDate() {
return startDate;
}
public void setStartDate(String startDate) {
this.startDate = startDate;
}
public String getEndDate() {
return endDate;
}
public void setEndDate(String endDate) {
this.endDate = endDate;
}
public String getPlace() {
return place;
}
public void setPlace(String place) {
this.place = place;
}
public Long getCarId() {
return carId;
}
public void setCarId(Long car) {
this.carId = car;
}
public Long getPriceListId() {
return priceListId;
}
public void setPriceListId(Long priceListId) {
this.priceListId = priceListId;
}
}
| true |
6764c89c6d9e52ebc6d886d41f8a646f4519da33 | Java | haney-oliver/RSAEncryption | /src/model/generator/RsaEncryptionKeyGenerator.java | UTF-8 | 1,653 | 3.046875 | 3 | [] | no_license | package model.generator;
import java.awt.*;
import java.math.BigInteger;
import static model.generator.PrimeNumberGenerator.generatePrime;
public class RsaEncryptionKeyGenerator {
private final BigInteger ONE = new BigInteger("1");
private final BigInteger ZERO = new BigInteger("0");
private BigInteger p = generatePrime();
private BigInteger q = generatePrime();
private BigInteger n = p.multiply(q); // modulus
private BigInteger phi = (p.subtract(new BigInteger("1"))).multiply(q.subtract(new BigInteger("1")));
private BigInteger e = generateE(); // public exponent or encryption exponent
private BigInteger d = generateD(); // private exponent or decryption exponent
public RsaEncryptionKeyGenerator() {
System.out.println(p);
System.out.println(q);
System.out.println(phi);
System.out.println(e);
System.out.println(d);
}
// Generate the encryption exponent
private BigInteger generateE() {
BigInteger e = generatePrime();
if (e.gcd(phi) != ONE && (e.compareTo(ONE) == -1 || e.compareTo(phi) == 1 || e.compareTo(ONE) == 0 || e.compareTo(phi) == 0)) {
return null;
}
return e;
}
//Generate the decryption exponent
private BigInteger generateD() {
BigInteger d = e.modInverse(phi);
if((((e.multiply(d)).subtract(ONE)).mod(phi)).equals(ZERO)) {
return d;
}
return null;
}
//Getters for keys
public BigInteger getPublicKey() { return e; }
public BigInteger getPrivateKey() { return d; }
public BigInteger getN() {return n;}
}
| true |
d99f62e66ef765a9d9b72fcd9122a64126f186a5 | Java | finos/waltz | /waltz-data/src/main/java/org/finos/waltz/data/entity_named_note/EntityNamedNoteDao.java | UTF-8 | 5,868 | 1.820313 | 2 | [
"Apache-2.0",
"LicenseRef-scancode-unknown",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-generic-cla",
"CC0-1.0"
] | permissive | /*
* Waltz - Enterprise Architecture
* Copyright (C) 2016, 2017, 2018, 2019 Waltz open source project
* See README.md for more information
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific
*
*/
package org.finos.waltz.data.entity_named_note;
import org.finos.waltz.data.GenericSelector;
import org.finos.waltz.schema.tables.records.EntityNamedNoteRecord;
import org.finos.waltz.model.EntityKind;
import org.finos.waltz.model.EntityReference;
import org.finos.waltz.model.UserTimestamp;
import org.finos.waltz.model.entity_named_note.EntityNamedNote;
import org.finos.waltz.model.entity_named_note.ImmutableEntityNamedNote;
import org.jooq.DSLContext;
import org.jooq.Record;
import org.jooq.RecordMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import java.sql.Timestamp;
import java.util.List;
import java.util.Set;
import static org.finos.waltz.schema.Tables.ENTITY_NAMED_NOTE_TYPE;
import static org.finos.waltz.schema.tables.EntityNamedNote.ENTITY_NAMED_NOTE;
import static org.finos.waltz.common.Checks.checkNotNull;
@Repository
public class EntityNamedNoteDao {
private static final RecordMapper<Record, EntityNamedNote> TO_DOMAIN_MAPPER = record -> {
EntityNamedNoteRecord r = record.into(ENTITY_NAMED_NOTE);
return ImmutableEntityNamedNote
.builder()
.entityReference(EntityReference.mkRef(
EntityKind.valueOf(r.getEntityKind()),
r.getEntityId()))
.namedNoteTypeId(r.getNamedNoteTypeId())
.noteText(r.getNoteText())
.provenance(r.getProvenance())
.lastUpdatedAt(r.getLastUpdatedAt().toLocalDateTime())
.lastUpdatedBy(r.getLastUpdatedBy())
.build();
};
private final DSLContext dsl;
@Autowired
public EntityNamedNoteDao(DSLContext dsl) {
checkNotNull(dsl, "dsl cannot be null");
this.dsl = dsl;
}
public List<EntityNamedNote> findByEntityReference(EntityReference ref) {
checkNotNull(ref, "ref cannot be null");
return dsl
.select(ENTITY_NAMED_NOTE.fields())
.from(ENTITY_NAMED_NOTE)
.where(ENTITY_NAMED_NOTE.ENTITY_KIND.eq(ref.kind().name()))
.and(ENTITY_NAMED_NOTE.ENTITY_ID.eq(ref.id()))
.fetch(TO_DOMAIN_MAPPER);
}
public boolean save(EntityReference ref, long namedNoteTypeId, String noteText, UserTimestamp lastUpdate) {
checkNotNull(ref, "ref cannot be null");
checkNotNull(lastUpdate, "lastUpdate cannot be null");
EntityNamedNoteRecord record = dsl.newRecord(ENTITY_NAMED_NOTE);
record.setEntityId(ref.id());
record.setEntityKind(ref.kind().name());
record.setNoteText(noteText);
record.setNamedNoteTypeId(namedNoteTypeId);
record.setLastUpdatedAt(Timestamp.valueOf(lastUpdate.at()));
record.setLastUpdatedBy(lastUpdate.by());
record.setProvenance("waltz");
if (dsl.executeUpdate(record) == 1) {
return true;
} else {
return dsl.executeInsert(record) == 1;
}
}
public boolean remove(EntityReference ref, long namedNoteTypeId) {
checkNotNull(ref, "ref cannot be null");
return dsl.deleteFrom(ENTITY_NAMED_NOTE)
.where(ENTITY_NAMED_NOTE.ENTITY_KIND.eq(ref.kind().name()))
.and(ENTITY_NAMED_NOTE.ENTITY_ID.eq(ref.id()))
.and(ENTITY_NAMED_NOTE.NAMED_NOTE_TYPE_ID.eq(namedNoteTypeId))
.execute() == 1;
}
public boolean remove(EntityReference ref) {
checkNotNull(ref, "ref cannot be null");
return dsl.deleteFrom(ENTITY_NAMED_NOTE)
.where(ENTITY_NAMED_NOTE.ENTITY_KIND.eq(ref.kind().name()))
.and(ENTITY_NAMED_NOTE.ENTITY_ID.eq(ref.id()))
.execute() > 0;
}
public Set<EntityNamedNote> findByNoteTypeExtId(String noteTypeExtId) {
return dsl
.select(ENTITY_NAMED_NOTE.fields())
.from(ENTITY_NAMED_NOTE)
.innerJoin(ENTITY_NAMED_NOTE_TYPE).on(ENTITY_NAMED_NOTE.NAMED_NOTE_TYPE_ID.eq(ENTITY_NAMED_NOTE_TYPE.ID))
.where(ENTITY_NAMED_NOTE_TYPE.EXTERNAL_ID.eq(noteTypeExtId))
.fetchSet(TO_DOMAIN_MAPPER);
}
public Set<EntityNamedNote> findByNoteTypeExtIdAndEntityReference(String noteTypeExtId, EntityReference entityReference) {
return dsl
.select(ENTITY_NAMED_NOTE.fields())
.from(ENTITY_NAMED_NOTE)
.innerJoin(ENTITY_NAMED_NOTE_TYPE).on(ENTITY_NAMED_NOTE.NAMED_NOTE_TYPE_ID.eq(ENTITY_NAMED_NOTE_TYPE.ID))
.where(ENTITY_NAMED_NOTE_TYPE.EXTERNAL_ID.eq(noteTypeExtId))
.and(ENTITY_NAMED_NOTE.ENTITY_KIND.eq(entityReference.kind().name()))
.and(ENTITY_NAMED_NOTE.ENTITY_ID.eq(entityReference.id()))
.fetchSet(TO_DOMAIN_MAPPER);
}
public int deleteByParentSelector(GenericSelector selector) {
return dsl
.deleteFrom(ENTITY_NAMED_NOTE)
.where(ENTITY_NAMED_NOTE.ENTITY_ID.in(selector.selector())
.and(ENTITY_NAMED_NOTE.ENTITY_KIND.eq(selector.kind().name())))
.execute();
}
}
| true |
f872866d08227086daf5a8c407492dfc6853bbe9 | Java | kbaseIncubator/trees2 | /lib/src/us/kbase/cdmientityapi/FieldsSubsystem.java | UTF-8 | 4,978 | 1.726563 | 2 | [
"MIT"
] | permissive |
package us.kbase.cdmientityapi;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Generated;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
/**
* <p>Original spec-file type: fields_Subsystem</p>
*
*
*/
@JsonInclude(JsonInclude.Include.NON_NULL)
@Generated("com.googlecode.jsonschema2pojo")
@JsonPropertyOrder({
"id",
"version",
"curator",
"notes",
"description",
"usable",
"private",
"cluster_based",
"experimental"
})
public class FieldsSubsystem {
@JsonProperty("id")
private String id;
@JsonProperty("version")
private Long version;
@JsonProperty("curator")
private String curator;
@JsonProperty("notes")
private String notes;
@JsonProperty("description")
private String description;
@JsonProperty("usable")
private Long usable;
@JsonProperty("private")
private Long _private;
@JsonProperty("cluster_based")
private Long clusterBased;
@JsonProperty("experimental")
private Long experimental;
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
@JsonProperty("id")
public String getId() {
return id;
}
@JsonProperty("id")
public void setId(String id) {
this.id = id;
}
public FieldsSubsystem withId(String id) {
this.id = id;
return this;
}
@JsonProperty("version")
public Long getVersion() {
return version;
}
@JsonProperty("version")
public void setVersion(Long version) {
this.version = version;
}
public FieldsSubsystem withVersion(Long version) {
this.version = version;
return this;
}
@JsonProperty("curator")
public String getCurator() {
return curator;
}
@JsonProperty("curator")
public void setCurator(String curator) {
this.curator = curator;
}
public FieldsSubsystem withCurator(String curator) {
this.curator = curator;
return this;
}
@JsonProperty("notes")
public String getNotes() {
return notes;
}
@JsonProperty("notes")
public void setNotes(String notes) {
this.notes = notes;
}
public FieldsSubsystem withNotes(String notes) {
this.notes = notes;
return this;
}
@JsonProperty("description")
public String getDescription() {
return description;
}
@JsonProperty("description")
public void setDescription(String description) {
this.description = description;
}
public FieldsSubsystem withDescription(String description) {
this.description = description;
return this;
}
@JsonProperty("usable")
public Long getUsable() {
return usable;
}
@JsonProperty("usable")
public void setUsable(Long usable) {
this.usable = usable;
}
public FieldsSubsystem withUsable(Long usable) {
this.usable = usable;
return this;
}
@JsonProperty("private")
public Long getPrivate() {
return _private;
}
@JsonProperty("private")
public void setPrivate(Long _private) {
this._private = _private;
}
public FieldsSubsystem withPrivate(Long _private) {
this._private = _private;
return this;
}
@JsonProperty("cluster_based")
public Long getClusterBased() {
return clusterBased;
}
@JsonProperty("cluster_based")
public void setClusterBased(Long clusterBased) {
this.clusterBased = clusterBased;
}
public FieldsSubsystem withClusterBased(Long clusterBased) {
this.clusterBased = clusterBased;
return this;
}
@JsonProperty("experimental")
public Long getExperimental() {
return experimental;
}
@JsonProperty("experimental")
public void setExperimental(Long experimental) {
this.experimental = experimental;
}
public FieldsSubsystem withExperimental(Long experimental) {
this.experimental = experimental;
return this;
}
@JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
@JsonAnySetter
public void setAdditionalProperties(String name, Object value) {
this.additionalProperties.put(name, value);
}
@Override
public String toString() {
return ((((((((((((((((((((("FieldsSubsystem"+" [id=")+ id)+", version=")+ version)+", curator=")+ curator)+", notes=")+ notes)+", description=")+ description)+", usable=")+ usable)+", _private=")+ _private)+", clusterBased=")+ clusterBased)+", experimental=")+ experimental)+", additionalProperties=")+ additionalProperties)+"]");
}
}
| true |
4ffb10c0f24f3a6afa810628b3066bc55d5f009e | Java | untra/gdxhex | /core/src/untra/scene/debug/DebugScene.java | UTF-8 | 1,397 | 2.578125 | 3 | [] | no_license | package untra.scene.debug;
import untra.graphics.Draw_Object;
import java.util.Scanner;
import untra.scene.IScene;
import untra.database.Database;
import untra.database.Klass;
import untra.driver.Input;
public class DebugScene implements IScene {
private boolean refresh = true;
private DebugWindow debugwindow = new DebugWindow();
@Override
public void update() {
debugwindow.update();
if (refresh) {
refresh = false;
refresh();
return;
}
if (debugwindow.active && Input.leftPressed()) {
int i = debugwindow.index;
}
if (debugwindow.active && Input.rightPressed()) {
refresh = true;
}
}
public void refresh() {
debugwindow.active = false;
Scanner in = new Scanner(System.in);
System.out.println("SELECT DATA ITEM\n" + "A - Classes\n" + "");
char selection = in.next().charAt(0);
selection = Character.toUpperCase(selection);
String[] commands;
switch (selection) {
case 'A': // classes
{
commands = new String[Database.classes.length];
int i = 0;
for (Klass klass : Database.classes) {
commands[i] = klass.toString();
System.out.println(i);
i++;
}
debugwindow.commands = commands;
debugwindow.active = true;
break;
}
default:
break;
}
}
@Override
public void draw(Draw_Object s_batch) {
debugwindow.draw(s_batch);
}
@Override
public void dispose() {
debugwindow.dispose();
}
}
| true |
bd5c3cbbed80da8c062feb9f9008db624cb3084d | Java | dhganey/advent-of-code-2016 | /day-1/TurnDirection.java | UTF-8 | 35 | 2.078125 | 2 | [] | no_license | public enum TurnDirection {
L, R
} | true |
baa51d7e4f349c4676816d2a8769201a8a253404 | Java | skoumalcz/joogar | /example/src/main/java/net/skoumal/joogar/example/activities/SugarActivity.java | UTF-8 | 2,241 | 2.5 | 2 | [
"Apache-2.0"
] | permissive | package net.skoumal.joogar.example.activities;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import net.skoumal.joogar.example.models.NewNote;
import net.skoumal.joogar.example.models.Note;
import net.skoumal.joogar.example.models.Tag;
import net.skoumal.joogar.example.models.TextNote;
import net.skoumal.joogar.shared.JoogarDatabaseResult;
import net.skoumal.joogar.shared.JoogarRecord;
import com.example.R;
public class SugarActivity extends Activity
{
/**
* Called when the activity is first created.
*/
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initDb();
// join example
JoogarRecord.find(Note.class, null, null, null, null, null, new JoogarRecord.OneToOnePrefetch("tag", "tagId", "id"));
Intent intent = new Intent(this, NoteListActivity.class);
startActivity(intent);
}
private void initDb() {
JoogarRecord.deleteAll(Note.class);
JoogarRecord.deleteAll(TextNote.class);
JoogarRecord.deleteAll(Tag.class);
JoogarRecord.deleteAll(NewNote.class);
Tag t1 = new Tag("tag1");
Tag t2 = new Tag("tag2");
JoogarRecord.save(t1);
JoogarRecord.save(t2);
Note n1 = new Note( 10, "note1", "description1", t1);
Note n2 = new Note(11, "note12", "description2", t1);
Note n3 = new Note( 12, "note13", "description3", t2);
Note n4 = new Note( 13, "note4", "description4", t2);
TextNote textNote = new TextNote();
textNote.desc = "Test";
JoogarRecord.save(textNote);
JoogarRecord.save(n1);
JoogarRecord.save(n2);
JoogarRecord.save(n3);
JoogarRecord.save(n4);
n1.setDescription("matrix");
n1.setTitle("atrix");
JoogarRecord.save(n1);
n2.setDescription("matrix");
n2.setTitle("satrix");
JoogarRecord.save(n2);
n3.setDescription("matrix");
n3.setTitle("batrix");
JoogarRecord.save(n3);
NewNote newNote = new NewNote();
newNote.name = "name";
JoogarRecord.save(newNote);
}
}
| true |
f3e8e43c5568daffa01fea3b97d6239aec3ca2c2 | Java | dumbwelder/LeetcodeAnswer | /src/q46/Solution.java | UTF-8 | 898 | 2.890625 | 3 | [] | no_license | package q46;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
public class Solution {
List<List<Integer>> res = new ArrayList<>();
public List<List<Integer>> permute(int[] nums) {
List<Integer> l = new LinkedList();
for (int i : nums) {
l.add(i);
}
List<Integer> result = new ArrayList<>();
int len = l.size();
per(result, l);
return res;
}
public void per(List<Integer> result, List<Integer> l) {
if (l.size() == 0) {
res.add(result);
} else {
for (int i = 0; i < l.size(); i++) {
List<Integer> res = new ArrayList<Integer>(result);
res.add(l.get(i));
List<Integer> ll = new ArrayList<Integer>(l);
ll.remove(i);
per(res, ll);
}
}
}
}
| true |
6aed82c2bfd78eb65c96a1a8f01eb90c45914d89 | Java | danielPaulinoMesquita/ReactSpringUdemy | /cursoBackEnd/src/main/java/com/example/curso/service/impl/UsuarioServiceImpl.java | UTF-8 | 1,774 | 2.4375 | 2 | [] | no_license | package com.example.curso.service.impl;
import com.example.curso.exception.ErroAutenticacao;
import com.example.curso.exception.RegraDeNegocioException;
import com.example.curso.model.entity.Usuario;
import com.example.curso.model.repository.UsuarioRepository;
import com.example.curso.service.UsuarioService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.annotation.Transient;
import org.springframework.stereotype.Service;
import java.util.Optional;
@Service
public class UsuarioServiceImpl implements UsuarioService {
@Autowired
private UsuarioRepository usuarioRepository;
public UsuarioServiceImpl(UsuarioRepository usuarioRepository) {
this.usuarioRepository = usuarioRepository;
}
@Override
public Usuario autenticar(String email, String senha) {
Optional<Usuario> usuario= usuarioRepository.findByEmail(email);
if(!usuario.isPresent()){
throw new ErroAutenticacao("Usuário não encontrado para o email informado. ");
}
if (!usuario.get().getSenha().equals(senha)){
throw new ErroAutenticacao("Senha Inválida.");
}
return usuario.get();
}
@Override
@Transient
public Usuario salvarUsuario(Usuario usuario) {
validarEmail(usuario.getEmail());
return usuarioRepository.save(usuario);
}
@Override
public void validarEmail(String email) {
boolean existe= usuarioRepository.existsByEmail(email);
if (existe){
throw new RegraDeNegocioException("Já Existe um Usuário cadastrado com esse Email!");
}
}
@Override
public Optional<Usuario> obterPorId(Long id) {
return usuarioRepository.findById(id);
}
}
| true |
62f82baa307ce30a488acca8d4b7f5b8a2c92c73 | Java | gvega10/aplicacioncarteleracine | /app/src/main/java/cartelera/um/cartelera/activities/LogInActivity.java | UTF-8 | 3,808 | 2.09375 | 2 | [] | no_license | package cartelera.um.cartelera.activities;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.AppCompatAutoCompleteTextView;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.util.List;
import javax.security.auth.login.LoginException;
import cartelera.um.cartelera.R;
import cartelera.um.cartelera.auth.AuthenticationManager;
import cartelera.um.cartelera.auth.AuthenticationManagerFactory;
import cartelera.um.cartelera.entities.Review;
import cartelera.um.cartelera.entities.User;
import cartelera.um.cartelera.services.ServiceLocator;
import cartelera.um.cartelera.services.ServiceLocatorFactory;
import io.reactivex.observers.DisposableObserver;
import io.reactivex.schedulers.Schedulers;
public class LogInActivity extends AppCompatActivity {
private EditText passwordEditText;
private AppCompatAutoCompleteTextView emailTextView;
private Button logInButton;
private ServiceLocator sl;
private Toolbar toolbar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_log_in);
setToolbar();
setUpView();
sl = getServicelocator();
logInButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String email = emailTextView.getText().toString();
String password = passwordEditText.getText().toString();
sl.getAuthService()
.signIn(email, password)
.subscribeOn(Schedulers.io())
.observeOn(sl.getSchedulers())
.subscribe(new DisposableObserver<User>() {
@Override
public void onNext(User userSigned) {
AuthenticationManager Auth = AuthenticationManagerFactory.getIntance(LogInActivity.this);
Auth.setCurrentUser(userSigned);
finish();
}
@Override
public void onError(Throwable e) {
Toast.makeText(LogInActivity.this, "Error al iniciar sesion", Toast.LENGTH_SHORT).show();
}
@Override
public void onComplete() {
}
});
}
});
}
private void setToolbar() {
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final ActionBar ab = getSupportActionBar();
if (ab != null) {
ab.setHomeAsUpIndicator(R.drawable.arrow_left);
ab.setDisplayHomeAsUpEnabled(true);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case android.R.id.home:
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void setUpView(){
passwordEditText = findViewById(R.id.password_input);
emailTextView = findViewById(R.id.email_input);
logInButton = findViewById(R.id.log_in_button);
}
public ServiceLocator getServicelocator(){
if(sl == null){
return ServiceLocatorFactory.getInstance(getApplicationContext());
}
return sl;
}
}
| true |
ea5ea0149504c59f1e6f4bf3241feb90a5678e61 | Java | sushiprieto/ProyectoFinalCurso | /SomeFoodServer/app/src/main/java/com/trabajo/carlos/somefoodserver/OrderDetailActivity.java | UTF-8 | 2,034 | 2.21875 | 2 | [] | no_license | package com.trabajo.carlos.somefoodserver;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.TextView;
import com.trabajo.carlos.somefoodserver.Common.Common;
import com.trabajo.carlos.somefoodserver.ViewHolder.OrderDetailAdapter;
public class OrderDetailActivity extends AppCompatActivity {
private TextView txvId, txvPhone, txvAddress, txvTotal, txvComment;
String order_id_value = "";
RecyclerView rcvListFoods;
RecyclerView.LayoutManager layoutManager;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_order_detail);
txvId = (TextView)findViewById(R.id.orderDetail_txvId);
txvPhone = (TextView)findViewById(R.id.orderDetail_txvPhone);
txvAddress = (TextView)findViewById(R.id.orderDetail_txvAddress);
txvTotal = (TextView)findViewById(R.id.orderDetail_txvTotal);
txvComment = (TextView)findViewById(R.id.orderDetail_txvComment);
rcvListFoods = (RecyclerView)findViewById(R.id.orderDetail_rcvListFood);
rcvListFoods.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
rcvListFoods.setLayoutManager(layoutManager);
if (getIntent() != null){
order_id_value = getIntent().getStringExtra("OrderId");
//Establecemos los valores
txvId.setText(order_id_value);
txvPhone.setText(Common.currentRequest.getPhone());
txvAddress.setText(Common.currentRequest.getAddress());
txvTotal.setText(Common.currentRequest.getTotal());
txvComment.setText(Common.currentRequest.getComment());
OrderDetailAdapter adapter = new OrderDetailAdapter(Common.currentRequest.getFoods());
adapter.notifyDataSetChanged();
rcvListFoods.setAdapter(adapter);
}
}
}
| true |
ec8fdcf2791529662367383a55c096da2a4b9dad | Java | JNfeicui-zshujuan/GitDroid | /app/src/main/java/com/feicuiedu/gitdroid/hotrepositor/Repo.java | UTF-8 | 1,289 | 2.28125 | 2 | [] | no_license | package com.feicuiedu.gitdroid.hotrepositor;
import com.feicuiedu.gitdroid.httpclient.User;
import com.google.gson.annotations.SerializedName;
import java.io.Serializable;
/**
* Created by zhengshujuan on 2016/7/6.
* 具体到一个仓库的实体类,bean.
*/
public class Repo implements Serializable{
public int getId() {
return id;
}
public int getStargazerCount() {
return stargazerCount;
}
public int getForksCount() {
return forksCount;
}
private int id;
//仓库名称
@SerializedName("name")
private String name;
//仓库全名
@SerializedName("full_name")
private String fullName;
public String getDescription() {
return description;
}
public String getFullName() {
return fullName;
}
public String getName() {
return name;
}
//仓库描述
@SerializedName("description")
private String description;
//在github上被关注的数量
@SerializedName("stargazers_count")
private int stargazerCount;
//被拷贝的数量
@SerializedName("forks_count")
private int forksCount;
//本仓库的拥有者
@SerializedName("owner")
private User owner;
public User getOwner() {
return owner;
}
}
| true |
6a58aab9f499348db205959fa1148651615085d8 | Java | chenrenyiabc/graduation_project | /src/main/java/com/bigdata/service/analysis/AnalysisService.java | UTF-8 | 1,393 | 1.984375 | 2 | [] | no_license | package com.bigdata.service.analysis;
import com.bigdata.bean.DataFlow;
import com.bigdata.bean.DataSource;
import com.bigdata.dao.analysis.AnalysisDao;
import java.util.List;
public class AnalysisService {
AnalysisDao ad = new AnalysisDao();
public List<String> queryDataSource(int userId) {
return ad.queryDataSource(userId);
}
public Boolean saveFlow(String name, int userId, int flow_status, int source_id, int flow_type, String hive_sql, Object o, String result_table, String result_path) {
return ad.saveFlow(name, userId, flow_status, source_id, flow_type, hive_sql, o, result_table, result_path);
}
public Boolean saveFlowHQL(String name, int userId, int flow_status, int flow_type, String hive_sql, String result_table) {
return ad.saveFlowHQL(name, userId, flow_status, flow_type, hive_sql, result_table);
}
public DataFlow queryExistFlow(String flowId) {
return ad.queryExistFlow(flowId);
}
public Boolean updateMRFlow(String process_name, String chooseData, String chooseAlgorithm, String resultPath, String flowId) {
return ad.updateMRFlow(process_name, chooseData, chooseAlgorithm, resultPath, flowId);
}
public Boolean updateHQLFlow(String name, String hive_sql, String result_table, String flowId) {
return ad.updateHQLFlow(name, hive_sql, result_table, flowId);
}
}
| true |
f1ecf3ea8019a28606d83e29fab397796711f66b | Java | tiago719/PA | /Trab/src/Logic/Cartas/Trap.java | UTF-8 | 1,522 | 2.859375 | 3 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Logic.Cartas;
import Logic.GameData;
import java.io.Serializable;
/**
*
* @author Tiago Coutinho
*/
public class Trap extends AdaptadorCartas implements Serializable
{
public Trap(GameData g)
{
super(g);
}
@Override
public String toString()
{
String s = "Carta: TRAP\n";
return s;
}
@Override
public String infoCarta()
{
String s = "Traps - Description\n";
s += "1: Mold Miasma - A terrible stench seems to have added a layer of white and blue hair on your meat. Lose 1 Food ration.\n";
s += "2: Tripwire - You tripped and fell hard to the ground. A Gold piece was ejected from your bag. Lose 1 Gold.\n";
s += "3: Acid Mist - Powerful acid falls from the ceiling and damages your equipment. Lose 1 Armor.\n";
s += "4: Spring Blades - You walked on a pressure plate and jumped just in time to avoid losing your head. Lose 1 HP.\n";
s += "5: Moving Walls - Moving walls were about to crush you, but you sacriced your sword to save yourself. Lose 1 XP.\n";
s += "6: Pit - You fell into a hole and landed a Level below. You broke a bone. Lose 2 HP and move your character token to the dungeon Area directly under the current one.";
return s;
}
}
| true |
10d4cf78538d4d518fdf0004f4d5da721e06661f | Java | vasilgramov/java-oop-advanced | /ExamPreparation/JavaOOPAdvancedExamPreparation19April2017/Emergency/src/collection/EmergencyRegister.java | UTF-8 | 237 | 2.28125 | 2 | [] | no_license | package collection;
/**
* Created by vladix on 4/18/17.
*/
public interface EmergencyRegister<T> {
int size();
void enqueueEmergency(T emergency);
T dequeueEmergency();
T peekEmergency();
Boolean isEmpty();
}
| true |
607b752185eeba3896f01bbd9169bd97a07af393 | Java | darciopacifico/omr | /di-pepsico/src/main/java/br/com/mastersaf/util/HibernateDaoImpl.java | UTF-8 | 11,153 | 2.328125 | 2 | [
"Apache-2.0"
] | permissive | package br.com.mastersaf.util;
import java.io.Serializable;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.FetchMode;
import org.hibernate.Session;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.jpa.support.JpaDaoSupport;
/**
* Generic dao implementation for basic data operations with Hibernate
* @author Rodrigo Rodrigues <rodrigorodriguesweb arroba gmail.com>
*/
public class HibernateDaoImpl extends JpaDaoSupport implements Dao {
/**
* Persist a object
* @param transaction actual transaction
*/
public void create(Bean bean) throws Exception {
getJpaTemplate().persist(bean);
}
public void remove(Bean bean, Serializable serializable) throws Exception {
getJpaTemplate().remove(getJpaTemplate().getReference(bean.getClass(), serializable));
}
/**
* Remove a object from persistence
* @param object
* @param transaction
* @throws Exception
*/
public void remove(Bean bean) throws Exception {
Session session = (Session) getJpaTemplate().getEntityManagerFactory().createEntityManager().getDelegate();
session.delete(bean);
session = null;
}
/**
* Update the data of object
* @param transaction actual transaction
*/
public void save(Bean bean) throws Exception {
getJpaTemplate().merge(bean);
}
/**
* Return number of criteria
* @param expression
* @param transaction
* @return
* @throws Exception
*/
@SuppressWarnings("unchecked")
public Long getCount(CriteriaExpression expression) throws Exception {
Session session = (Session) getJpaTemplate().getEntityManagerFactory().createEntityManager().getDelegate();
Number count = null;
String instanceObject = expression.getObjectName();
Criteria criteria = session.createCriteria(Class.forName(instanceObject));
Collection filters = expression.getFilters();
if(filters!=null){
Iterator it = filters.iterator();
while(it.hasNext()){
Filter filter = (Filter)it.next();
criteria.add(getResrictionFromCriteria(filter));
}
}
count = (Number) criteria.setProjection(Projections.rowCount()).uniqueResult();
session = null;
return new Long(count.longValue());
}
/**
* Get a collection object from a criteria expression
* @param transaction actual transaction
*/
@SuppressWarnings("unchecked")
public List get(CriteriaExpression expression) throws Exception {
Session session = (Session) getJpaTemplate().getEntityManagerFactory().createEntityManager().getDelegate();
List list = null;
String instanceObject = expression.getObjectName();
Criteria criteria = session.createCriteria(Class.forName(instanceObject));
Collection filters = expression.getFilters();
if(filters!=null){
Iterator it = filters.iterator();
while(it.hasNext()){
Filter filter = (Filter)it.next();
criteria.add(getResrictionFromCriteria(filter));
}
}
List orders = expression.getOrders();
if(orders!=null){
Iterator it = orders.iterator();
while(it.hasNext()){
Order order = (Order)it.next();
if (order.getOperation().equals(OrderOperator.ASC)){
criteria.addOrder(org.hibernate.criterion.Order.asc(order.getAttribute()));
} else {
criteria.addOrder(org.hibernate.criterion.Order.desc(order.getAttribute()));
}
}
}
Page page = expression.getPage();
if(page!=null){
if(page.getFirstItem()>0)
criteria.setFirstResult(page.getFirstItem().intValue());
if(page.getMaxItens()>0)
criteria.setMaxResults(page.getMaxItens().intValue());
}
list = criteria.list();
session = null;
return list;
}
/**
* Get component Criteria of Hibernate
* @param filter
* @return
*/
private Criterion getResrictionFromCriteria(Filter filter) {
Criterion simpleExpression = null;
Object value = filter.getValue();
String attribute = filter.getAttribute();
FilterOperator operator = filter.getOperation();
if(operator!=null){
if(operator.equals(FilterOperator.CONTAINS))
simpleExpression = Restrictions.ilike(attribute,"%" + value + "%");
else if(operator.equals(FilterOperator.END_WITH))
simpleExpression = Restrictions.ilike(attribute,"%" + value );
else if(operator.equals(FilterOperator.START_WITH))
simpleExpression = Restrictions.ilike(attribute,value + "%" );
else if(operator.equals(FilterOperator.EQUAL))
simpleExpression = Restrictions.eq(attribute,value);
else if(operator.equals(FilterOperator.GREATER_THAN))
simpleExpression = Restrictions.gt(attribute,value);
else if(operator.equals(FilterOperator.GREATER_THAN_OR_EQUAL))
simpleExpression = Restrictions.ge(attribute,value);
else if(operator.equals(FilterOperator.LESS_THAN))
simpleExpression = Restrictions.lt(attribute,value);
else if(operator.equals(FilterOperator.LESS_THAN_OR_EQUAL))
simpleExpression = Restrictions.le(attribute,value);
else if(operator.equals(FilterOperator.NOT_EQUAL))
simpleExpression = Restrictions.ne(attribute,value);
else if(operator.equals(FilterOperator.IS_NULL))
simpleExpression = Restrictions.isNull(attribute);
}
return simpleExpression;
}
/**
* Get a object with some aggregate objects. The id of object need be id
* @param objectName Name of class to be selected
* @param id ID of the object
* @param associations Name of attributes of aggregate objects to be return together with the main object
* @param transaction actual transaction
*/
@SuppressWarnings("unchecked")
public Bean getByIdWithRelations(String objectName, Serializable id, String[] associations) throws Exception {
Session session = (Session) getJpaTemplate().getEntityManagerFactory().createEntityManager().getDelegate();
Object object = null;
Criteria filter = session.createCriteria(Class.forName(objectName));
if(id instanceof String)
filter.add(Restrictions.eq("id",(String)id));
else
filter.add(Restrictions.eq("id",(Long)id));
if(associations!=null && associations.length>0){
switch (associations.length){
case 1:
filter.setFetchMode(associations[0],FetchMode.JOIN);
break;
case 2:
filter.setFetchMode(associations[0],FetchMode.JOIN).setFetchMode(associations[1],FetchMode.JOIN);
break;
case 3:
filter.setFetchMode(associations[0],FetchMode.JOIN).setFetchMode(associations[1],FetchMode.JOIN).setFetchMode(associations[2],FetchMode.JOIN);
break;
case 4:
filter.setFetchMode(associations[0],FetchMode.JOIN).setFetchMode(associations[1],FetchMode.JOIN).setFetchMode(associations[2],FetchMode.JOIN).setFetchMode(associations[3],FetchMode.JOIN);
break;
case 5:
filter.setFetchMode(associations[0],FetchMode.JOIN).setFetchMode(associations[1],FetchMode.JOIN).setFetchMode(associations[2],FetchMode.JOIN).setFetchMode(associations[3],FetchMode.JOIN).setFetchMode(associations[4],FetchMode.JOIN);
break;
}
}
List objects = filter.list();
if(objects!=null && objects.size()>0){
object = objects.get(0);
}
session = null;
return (Bean) object;
}
/**
* Get a list of object with some agregate objects. The id of object need be id
* @param objectName Name of class to be selected
* @param associations Name of attributes of agregate objects to be return together with the main object
* @param transaction actual transaction
* @throws Exception
*/
@SuppressWarnings("unchecked")
public List<Bean> getWithRelations(String objectName, String[] associations) throws Exception {
Session session = (Session) getJpaTemplate().getEntityManagerFactory().createEntityManager().getDelegate();
List<Bean> objects = null;
Criteria filter = session.createCriteria(Class.forName(objectName));
if(associations!=null && associations.length>0){
if(associations.length == 1){
filter.setFetchMode(associations[0], FetchMode.SELECT);
} else {
for (int i = 0; i < associations.length; i++) {
filter.setFetchMode(associations[i], FetchMode.JOIN);
}
}
/*switch (associations.length){
case 1:
filter.setFetchMode(associations[0], FetchMode.SELECT);
break;
case 2:
filter.setFetchMode(associations[0], FetchMode.JOIN).setFetchMode(associations[1],FetchMode.JOIN);
break;
case 3:
filter.setFetchMode(associations[0], FetchMode.JOIN).setFetchMode(associations[1],FetchMode.JOIN).setFetchMode(associations[2],FetchMode.JOIN);
break;
case 4:
filter.setFetchMode(associations[0], FetchMode.JOIN).setFetchMode(associations[1],FetchMode.JOIN).setFetchMode(associations[2],FetchMode.JOIN).setFetchMode(associations[3],FetchMode.JOIN);
break;
case 5:
filter.setFetchMode(associations[0], FetchMode.JOIN).setFetchMode(associations[1],FetchMode.JOIN).setFetchMode(associations[2],FetchMode.JOIN).setFetchMode(associations[3],FetchMode.JOIN).setFetchMode(associations[4],FetchMode.JOIN);
break;
}*/
}
objects = filter.list();
session = null;
return objects;
}
/**
* Get a list of object from a HSQL criteria
*/
@SuppressWarnings("unchecked")
public List<Bean> getFromHql(String hsql) throws Exception {
Session session = (Session) getJpaTemplate().getEntityManagerFactory().createEntityManager().getDelegate();
List<Bean> result = session.createQuery(hsql).list();
session = null;
return result;
}
/**
* Get a list of object from a SQL criteria
*/
@SuppressWarnings("unchecked")
public List<Bean> getFromSql(String sql) throws Exception {
Session session = (Session) getJpaTemplate().getEntityManagerFactory().createEntityManager().getDelegate();
List<Bean> result = null;
result = session.createSQLQuery(sql).list();
session = null;
return result;
}
/**
* Return number of criteria
*/
public Long getCount(Class<? extends Bean> clazz) throws Exception {
CriteriaExpression expression = new CriteriaExpression(clazz);
return getCount(expression);
}
/**
* Return number of criteria.
*/
public Long getCount(Bean bean) throws Exception {
CriteriaExpression expression = new CriteriaExpression(bean.getClass());
expression.addFilters(UtilSS.getMapAttribute(bean), true);
return getCount(expression);
}
/**
* Return number of criteria.
*/
public Long getCountWithEquals(Bean bean) throws Exception {
CriteriaExpression expression = new CriteriaExpression(bean.getClass());
expression.addFilters(UtilSS.getMapAttribute(bean), false);
return getCount(expression);
}
public Session getSession() {
return (Session) getJpaTemplate().getEntityManagerFactory().createEntityManager().getDelegate();
}
} | true |
338599ca250c10a884a8c88e4032e0765bc0a7f3 | Java | EleC0TroN/Flux | /src/main/java/szewek/flux/util/market/MarketUtil.java | UTF-8 | 2,056 | 2.453125 | 2 | [
"MIT"
] | permissive | package szewek.flux.util.market;
import net.minecraft.item.ItemStack;
import net.minecraft.item.MerchantOffer;
import net.minecraft.nbt.NBTUtil;
import net.minecraft.util.ResourceLocation;
import szewek.flux.F;
import java.util.Set;
import java.util.function.BiPredicate;
public final class MarketUtil {
private MarketUtil() {}
public static boolean doTransaction(MerchantOffer offer, ItemStack stack1, ItemStack stack2) {
boolean accept = canAccept(offer, stack1, stack2);
if (accept) {
stack1.shrink(offer.func_222205_b().getCount());
if (!offer.getBuyingStackSecond().isEmpty()) {
stack2.shrink(offer.getBuyingStackSecond().getCount());
}
}
return accept;
}
public static boolean canAccept(MerchantOffer offer, ItemStack stack1, ItemStack stack2) {
final ItemStack offerStack = offer.getBuyingStackFirst();
if (F.Tags.MARKET_ACCEPT.contains(offerStack.getItem())) {
final ItemStack offerStack2 = offer.getBuyingStackSecond();
return customEqualWithoutDamage(MarketUtil::matchingItemTag, stack1, offerStack)
&& stack1.getCount() >= offerStack.getCount()
&& customEqualWithoutDamage(ItemStack::isItemEqual, stack2, offerStack2)
&& stack2.getCount() >= offerStack2.getCount();
} else {
return offer.matches(stack1, stack2);
}
}
private static boolean customEqualWithoutDamage(BiPredicate<ItemStack, ItemStack> func, ItemStack left, ItemStack right) {
if (right.isEmpty() && left.isEmpty()) {
return true;
} else {
ItemStack stack = left.copy();
if (stack.getItem().isDamageable()) {
stack.setDamage(stack.getDamage());
}
return func.test(stack, right) && (!right.hasTag() || stack.hasTag() && NBTUtil.areNBTEquals(right.getTag(), stack.getTag(), false));
}
}
private static boolean matchingItemTag(ItemStack left, ItemStack right) {
if (ItemStack.areItemsEqual(left, right)) {
return true;
}
Set<ResourceLocation> checkTags = right.getItem().getTags();
Set<ResourceLocation> tags = left.getItem().getTags();
return checkTags.containsAll(tags);
}
}
| true |
bafa05c52a82e45b89e06e7a6ae15b7902565321 | Java | LifeJoice/gaea-common-db | /src/main/java/org/gaea/data/dataset/domain/XmlApiDataSource.java | UTF-8 | 1,259 | 2.375 | 2 | [] | no_license | package org.gaea.data.dataset.domain;
import java.io.Serializable;
/**
* 这个是基于接口调用获取数据的数据集的配置。
* Created by iverson on 2017年11月30日16:09:23
*/
public class XmlApiDataSource implements Serializable {
// private String name;
// private String code;
/* 通过接口请求数据的方式,默认POST。value=post|get */
private String requestType = REQUEST_TYPE_POST;
public static final String REQUEST_TYPE_POST = "post";
public static final String REQUEST_TYPE_GET = "get";
/* Api请求的定义,包括请求参数、请求方式等 */
private XmlApiRequest request;
/* Api响应的定义,包括响应数据的抽取等 */
private XmlApiResponse response;
public String getRequestType() {
return requestType;
}
public void setRequestType(String requestType) {
this.requestType = requestType;
}
public XmlApiRequest getRequest() {
return request;
}
public void setRequest(XmlApiRequest request) {
this.request = request;
}
public XmlApiResponse getResponse() {
return response;
}
public void setResponse(XmlApiResponse response) {
this.response = response;
}
}
| true |
20d22b900244972922b5504bba1cbb35e9d2ed67 | Java | LMT-lmt/springboot-blog | /src/main/java/cn/imlmt/blog/mapper/CommentMapper.java | UTF-8 | 580 | 1.976563 | 2 | [] | no_license | package cn.imlmt.blog.mapper;
import cn.imlmt.blog.entities.Comment;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
@Mapper
public interface CommentMapper {
Comment getCommentById(Long id);
//获取顶层评论或子评论
List<Comment> getCommentListByBlogIdParentId(@Param("blogId") Long blogId,
@Param("parentId") Long parentId);
//获取父级评论的父级id
Long getParentCommentId(Long id);
int saveComment(Comment comment);
}
| true |
8ed14d71178352c54755afb1349f8c8f4fb0bbac | Java | Cognizant-Training-Coimbatore/Lab-Excercise-Batch-2 | /GOPIKAMG/29-01-2020/pgmd29_q1.java | UTF-8 | 1,229 | 3.40625 | 3 | [] | no_license | package project1;
import java.util.Scanner;
interface printable
{
public void display();
}
class Rectangle implements printable
{
public void display()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the length and breadth");
int l=sc.nextInt();
int b=sc.nextInt();
System.out.println("length :" +l +" "+"breadth :" +b);
}
}
class Sportscar implements printable
{
public void display()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the brand and mileage");
String brand =sc.nextLine();
int m=sc.nextInt();
System.out.println("brand:" +brand+" "+ "mileage:"+m);
}
}
class Manager implements printable
{
public void display( )
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the name and dept");
String name =sc.nextLine();
String dept=sc.nextLine();
System.out.println("name : "+name+ " "+"dept: "+dept);
}
}
public class pgmd29_q1 {
public static void main(String[] args) {
Rectangle obj1=new Rectangle();
obj1.display();
Sportscar obj2=new Sportscar();
obj2.display();
Manager obj3=new Manager();
obj3.display();
}
}
| true |
d99ed17482839859500a3ee30d1ac177397f81bb | Java | shuimuren/zx | /app/src/main/java/com/zhixing/work/zhixin/network/response/ChildDepartmentResult.java | UTF-8 | 1,780 | 2.234375 | 2 | [] | no_license | package com.zhixing.work.zhixin.network.response;
import com.zhixing.work.zhixin.bean.ChildDepartmentBean;
import com.zhixing.work.zhixin.network.BaseResult;
import java.util.List;
/**
* Created by lhj on 2018/7/18.
* Description: 子部门
*/
public class ChildDepartmentResult extends BaseResult {
/**
* Content : {"CurrentDepartmentName":"XXX科技有限公司","SubDepartments":[{"DepartmentId":8,"DepartmentName":"技术部"},{"DepartmentId":12,"DepartmentName":"营销部"}]}
*/
private ContentBean Content;
private String departmentId;
public String getDepartmentId() {
return departmentId;
}
public void setDepartmentId(String departmentId) {
this.departmentId = departmentId;
}
public ContentBean getContent() {
return Content;
}
public void setContent(ContentBean Content) {
this.Content = Content;
}
public static class ContentBean {
/**
* CurrentDepartmentName : XXX科技有限公司
* SubDepartments : [{"DepartmentId":8,"DepartmentName":"技术部"},{"DepartmentId":12,"DepartmentName":"营销部"}]
*/
private String CurrentDepartmentName;
private List<ChildDepartmentBean> SubDepartments;
public String getCurrentDepartmentName() {
return CurrentDepartmentName;
}
public void setCurrentDepartmentName(String CurrentDepartmentName) {
this.CurrentDepartmentName = CurrentDepartmentName;
}
public List<ChildDepartmentBean> getSubDepartments() {
return SubDepartments;
}
public void setSubDepartments(List<ChildDepartmentBean> SubDepartments) {
this.SubDepartments = SubDepartments;
}
}
}
| true |
4ab351f0faa21253d81f25664ea66923e93a72f6 | Java | lamnguyen5464/RCT-WhereMyImage | /android/app/src/main/java/com/wheremyimages/utilities/BitmapUtils.java | UTF-8 | 2,550 | 2.6875 | 3 | [] | no_license | package com.wheremyimages.utilities;
import android.content.Context;
import android.content.ContextWrapper;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
public class BitmapUtils {
public static Bitmap loadBitmap(String url) {
Bitmap bitmap = null;
try {
InputStream in = new java.net.URL(url).openStream();
if (in != null) {
bitmap = BitmapFactory.decodeStream(in);
in.close();
}
} catch (IOException e) {
Log.d("@@@", "Could not load Bitmap from: " + url);
}
return bitmap;
}
public static String saveToStorage(Context context, Bitmap bitmapImage, String fileName) {
ContextWrapper cw = new ContextWrapper(context);
File directory = cw.getDir("imageDirect", Context.MODE_PRIVATE);
// Create imageDir
File myPath = new File(directory, fileName);
try {
FileOutputStream fos = new FileOutputStream(myPath);
if (fos != null) {
bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
}
} catch (Exception e) {
e.printStackTrace();
}
return directory.getAbsolutePath();
}
public static Bitmap loadFromStorage(String path, String fileName) {
Bitmap res = null;
try {
File f = new File(path, fileName);
res = BitmapFactory.decodeStream(new FileInputStream(f));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return res;
}
public static String getImageName(String url) {
StringBuilder res = new StringBuilder();
int firstIndex = url.length() - 1;
while (url.charAt(firstIndex) != '/' && firstIndex > 0) {
firstIndex--;
}
for (int i = firstIndex + 1; i < url.length(); i++) {
res.append(url.charAt(i));
}
return res.toString();
}
public static float dpFromPx(final Context context, final float px) {
return px / context.getResources().getDisplayMetrics().density;
}
public static float pxFromDp(final Context context, final float dp) {
return dp * context.getResources().getDisplayMetrics().density;
}
}
| true |
f4b4c2b4a4b49b10a4f82175c8527ec8483c7c2f | Java | TREQA/NegoescuVlad | /MyApplication/src/MostenirePolimorfismProfessor.java | UTF-8 | 296 | 2.546875 | 3 | [] | no_license | public abstract class MostenirePolimorfismProfessor extends MostenirePolimorfismPerson{
public String className;
public MostenirePolimorfismProfessor(String firstName, String lastName, String className){
super (firstName, lastName);
this.className = className;
}
}
| true |
e703e3532063da229f45ef4a2569340cde04906e | Java | ED1978/ThemeParkHomework | /src/test/java/VisitorTest.java | UTF-8 | 1,284 | 2.859375 | 3 | [] | no_license | import attractions.Dogems;
import org.junit.Before;
import org.junit.Test;
import people.Visitor;
import themeParkStuff.ThemePark;
import static org.junit.Assert.assertEquals;
public class VisitorTest {
Visitor visitor;
Dogems dogems;
ThemePark themePark;
@Before
public void before(){
visitor = new Visitor("Bert", 21, 140, 100.00);
dogems = new Dogems();
themePark = new ThemePark("Louden Castle");
}
@Test
public void hasName() {
assertEquals("Bert", visitor.getName());
}
@Test
public void hasAge() {
assertEquals(21, visitor.getAge());
}
@Test
public void hasMoney() {
assertEquals(100.00, visitor.getMoney(), 0.01);
}
@Test
public void canGetHeight() {
assertEquals(140, visitor.getHeight());
}
@Test
public void canAddMoney() {
visitor.increaseMoney(1.99);
assertEquals(101.99, visitor.getMoney(), 0.01);
}
@Test
public void canDecreaseMoney() {
visitor.decreaseMoney(1.00);
assertEquals(99.00, visitor.getMoney(), 0.01);
}
@Test
public void canGiveScore() {
visitor.giveRating(themePark , "Dogems", 6);
assertEquals(6, themePark.getDogemsRating());
}
}
| true |
bfe235ae71462a88e7a7008a5fbf72aa56d1bbc3 | Java | zarebcn/codethen | /src/ejerciciosobjetos/Book.java | UTF-8 | 1,300 | 3.171875 | 3 | [] | no_license | package ejerciciosobjetos;
import java.util.ArrayList;
import java.util.List;
public class Book {
private String author;
private String title;
private ChapterList chapterList;
// private List<Chapter> chapterList = new ArrayList<>();
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public ChapterList getChapters() {
return chapterList;
}
public void setChapters(ChapterList chapterList) {
this.chapterList = chapterList;
}
/*public List<Chapter> getChapters() {
return chapterList;
}
public void setChapters(List<Chapter> chapterList) {
this.chapters = chapterList;
}*/
String totalPages() {
return "Total pages: " + chapterList.get(chapterList.size() - 1).getEndPage();
}
public String toString() {
String info = "";
info = title + "\n";
info += "By " + author + "\n";
for (int i = 0; i < chapterList.size(); i++) {
info += i + 1 + " - " + chapterList.get(i).toString() + "\n";
}
return info;
}
}
| true |
fb5945d026e1a0143d0138180159fb83ec987187 | Java | lawkentdev/bottomgavigationbar | /app/src/main/java/com/kent/android/bottomnavigationbar/MainActivity.java | UTF-8 | 8,188 | 1.953125 | 2 | [
"Apache-2.0"
] | permissive | package com.kent.android.bottomnavigationbar;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.kent.android.bottomnavigationbar.fragment.NavigationFragment;
import com.kent.android.bottomnavigationbar.fragment.RadioFragment;
import com.kent.android.bottomnavigationbar.fragment.TabLayoutFragment;
import com.kent.android.bottomnavigationbar.fragment.TabLayoutFragment2;
import com.kent.android.bottomnavigationbar.fragment.TextTabFragment;
import com.kent.android.bottomnavigationbar.utils.SnackBarUtils;
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, View.OnClickListener {
private DrawerLayout mDrawerLayout;
private Toolbar mToolbar;
private NavigationView mNavigationView;
private ActionBarDrawerToggle mDrawerToggle;
private NavigationFragment mNavigationFragment;
private RadioFragment mRadioFragment;
private LinearLayout mRadioBadge;//the badge for radioGroup menu
private TextView mRadioMsg;
private TextTabFragment mTextTabFragment;
private TabLayoutFragment mTabLayoutFragment;
private TabLayoutFragment2 mTabLayoutFragment2;
private NightModeHelper mNightModeHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
mNightModeHelper = new NightModeHelper(this, R.style.BaseTheme);
setContentView(R.layout.activity_main);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mToolbar = (Toolbar) findViewById(R.id.tool_bar);
mNavigationView = (NavigationView) findViewById(R.id.navigation_view);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, mToolbar, R.string.drawer_layout_open, R.string.drawer_layout_close);
mDrawerToggle.syncState();
mDrawerToggle.setDrawerIndicatorEnabled(true);
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerLayout.setStatusBarBackgroundColor(ContextCompat.getColor(this, R.color.colorPrimaryDark));
View headerView = mNavigationView.getHeaderView(0);
headerView.setOnClickListener(this);
mNavigationView.setItemIconTintList(null);
mNavigationView.setNavigationItemSelectedListener(this);
mNavigationView.setItemTextColor(ContextCompat.getColorStateList(this, R.color.bg_drawer_navigation));
mNavigationView.setItemIconTintList(ContextCompat.getColorStateList(this, R.color.bg_drawer_navigation));
// mRadioBadge = (LinearLayout) mNavigationView.getMenu().findItem(R.id.menu_radio_group).getActionView();
// mRadioMsg = (TextView) mRadioBadge.findViewById(R.id.msg);
// mRadioMsg.setText("8");
setNavigationViewChecked(0);
setCurrentFragment();
}
private void setNavigationViewChecked(int position) {
mNavigationView.getMenu().getItem(position).setChecked(true);
Log.i("Kevin", "the count of menu item is--->" + mNavigationView.getMenu().size() + "");
for (int i = 0; i < mNavigationView.getMenu().size(); i++) {
if (i != position) {
mNavigationView.getMenu().getItem(i).setChecked(false);
}
}
}
private void setCurrentFragment() {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
mNavigationFragment = NavigationFragment.newInstance(getString(R.string.navigation_navigation_bar));
transaction.replace(R.id.frame_content, mNavigationFragment).commit();
}
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
switch (item.getItemId()) {
case R.id.menu_bottom_navigation_bar:
if (mNavigationFragment == null) {
mNavigationFragment = NavigationFragment.newInstance(getString(R.string.navigation_navigation_bar));
}
transaction.replace(R.id.frame_content, mNavigationFragment);
Snackbar.make(mDrawerLayout, "NavigationBar", Snackbar.LENGTH_SHORT).show();
setNavigationViewChecked(0);
break;
case R.id.menu_radio_group:
if (mRadioFragment == null) {
mRadioFragment = RadioFragment.newInstance(getString(R.string.navigation_radio_bar));
}
transaction.replace(R.id.frame_content, mRadioFragment);
// Snackbar.make(mDrawerLayout, "RadioGroup", Snackbar.LENGTH_SHORT).show();
SnackBarUtils.showSnackBar(mDrawerLayout, getString(R.string.navigation_radio_bar), this);
setNavigationViewChecked(1);
break;
case R.id.menu_text_view:
if (mTextTabFragment == null) {
mTextTabFragment = TextTabFragment.newInstance(getString(R.string.navigation_text_tab));
}
transaction.replace(R.id.frame_content, mTextTabFragment);
Snackbar.make(mDrawerLayout, "TextView + LinearLayout", Snackbar.LENGTH_SHORT).show();
setNavigationViewChecked(2);
break;
case R.id.menu_tab_layout:
if (mTabLayoutFragment == null) {
mTabLayoutFragment = TabLayoutFragment.newInstance(getString(R.string.navigation_tab_layout));
}
transaction.replace(R.id.frame_content, mTabLayoutFragment);
setNavigationViewChecked(3);
Snackbar.make(mDrawerLayout, "TabLayout + ViewPager", Snackbar.LENGTH_SHORT).show();
break;
case R.id.menu_tab_layout2:
if (mTabLayoutFragment2 == null) {
mTabLayoutFragment2 = TabLayoutFragment2.newInstance(getString(R.string.navigation_tab_layout2));
}
transaction.replace(R.id.frame_content, mTabLayoutFragment2);
setNavigationViewChecked(4);
Snackbar.make(mDrawerLayout, "TabLayout + ViewPager 2", Snackbar.LENGTH_SHORT).show();
break;
}
mDrawerLayout.closeDrawers();
transaction.commit();
return true;
}
@Override
public void onClick(View view) {
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.home:
mDrawerLayout.openDrawer(GravityCompat.START);
return true;
case R.id.settings:
Snackbar.make(mDrawerLayout, "Settings", Snackbar.LENGTH_SHORT).show();
return true;
case R.id.share:
mNightModeHelper.toggle();
// Configuration newConfig = new Configuration(getResources().getConfiguration());
// newConfig.uiMode &= ~Configuration.UI_MODE_NIGHT_MASK;
// newConfig.uiMode |= uiNightMode;
// getResources().updateConfiguration(newConfig, null);
// recreate();
return true;
}
return super.onOptionsItemSelected(item);
}
}
| true |
ccb2f355a4b661652f4f58fea999383af8453d6f | Java | tuansidau/Phan_Mem_mo_hinh_phan_lop | /Tour/src/BLL/NhanVienBLL.java | UTF-8 | 3,207 | 2.546875 | 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 BLL;
import DAL.NhanVienDAL;
import DTO.NhanvienDTO;
import java.util.ArrayList;
/**
*
* @author Nam
*/
public class NhanVienBLL {
public static ArrayList<NhanvienDTO> sumArr;
public NhanvienDTO nhanvienDTO;
NhanVienDAL dal = new NhanVienDAL();
public NhanVienBLL()
{
sumArr = new ArrayList<NhanvienDTO>();
}
public void docNhanvien()
{
sumArr = dal.docNhanvien();
}
public void themNhanvien(NhanvienDTO object)
{
sumArr.add(object);
dal.themNhanvien(object);
}
public void suaNhanvien(NhanvienDTO object)
{
dal.suaNhanvien(object);
for(NhanvienDTO a : sumArr)
{
if(a.getNv_id() == object.getNv_id())
{
a.setNv_ten(object.getNv_ten());
a.setNv_sdt(object.getNv_sdt());
a.setNv_ngaysinh(object.getNv_ngaysinh());
a.setNv_nhiemvu(object.getNv_nhiemvu());
a.setNv_email(object.getNv_email());
break;
}
}
}
public void xoaNhanvien(int id)
{
dal.xoaNhanvien(id);
for(NhanvienDTO a : sumArr)
{
if(a.getNv_id() == id)
{
sumArr.remove(a);
break;
}
}
}
public ArrayList<NhanvienDTO> search(String str, int index)
{
ArrayList<NhanvienDTO> result = new ArrayList <NhanvienDTO>();
for(NhanvienDTO a : sumArr)
{
if(index == 0)//all
{
if(a.getNv_ten().toUpperCase().contains(str)
|| a.getNv_nhiemvu().toUpperCase().contains(str)
|| a.getNv_sdt().toUpperCase().contains(str)
|| a.getNv_email().toUpperCase().contains(str))
{
result.add(a);
}
} else if (index == 1) {//ten
if(a.getNv_ten().toUpperCase().contains(str))
{
result.add(a);
}
} else if (index == 2) {//sdt
if( a.getNv_sdt().toUpperCase().contains(str))
{
result.add(a);
}
} else if (index == 3) {//nhiem vu
if(a.getNv_nhiemvu().toUpperCase().contains(str))
{
result.add(a);
}
} else if (index == 4) {//mail
if(a.getNv_email().toUpperCase().contains(str))
{
result.add(a);
}
}
}
return result;
}
public void suaTrangthai(int id, int trangthai)
{
dal.suaTrangthai(id, trangthai);
for(NhanvienDTO a : sumArr)
{
if(a.getNv_id() == id)
{
a.setNv_trangthai(trangthai);
break;
}
}
}
}
| true |
d56b1678083aee1dc181e65252724a058eb3cc18 | Java | knitomi90ELTE/adminsystem-web | /src/main/java/hu/kniznertamas/adminsystem/dal/balance/user/repository/UserBalanceRepository.java | UTF-8 | 676 | 1.773438 | 2 | [] | no_license | package hu.kniznertamas.adminsystem.dal.balance.user.repository;
import hu.kniznertamas.adminsystem.dal.balance.user.entity.UserBalanceEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import java.time.LocalDate;
import java.util.Set;
/**
* Created by Tamas_Knizner on 2017-03-30.
*/
public interface UserBalanceRepository extends JpaRepository<UserBalanceEntity, Long> {
Set<UserBalanceEntity> findAllByCompleted(LocalDate completed);
Set<UserBalanceEntity> findAllByCompletedIsNull();
Set<UserBalanceEntity> findAllByCompletedIsNotNull();
Set<UserBalanceEntity> findAllByUserEntity_IdAndCompletedIsNotNull(Long userEntityId);
}
| true |
45eab862c439842ca74e88ca8cc89c741acb7005 | Java | tejarspl/apache-camel-with-ibm-mq | /camel-with-ibm-mq/src/main/java/com/asp/proxy/tcp/AspTcpRequest.java | UTF-8 | 384 | 2.21875 | 2 | [] | no_license | package com.asp.proxy.tcp;
public class AspTcpRequest {
private String rawMessage;
private String charsetName;
public AspTcpRequest(String rawMessage, String charsetName) {
super();
this.rawMessage = rawMessage;
this.charsetName = charsetName;
}
public String getRawMessage() {
return rawMessage;
}
public String getCharsetName() {
return charsetName;
}
}
| true |
1390954348621d85cadc3d66346614067463d9ab | Java | xxxrt/031902442 | /SensitiveWord/SensitiveWord/src/main/java/com/mindflow/py4j/Converter.java | UTF-8 | 278 | 1.96875 | 2 | [] | no_license | package com.mindflow.py4j;
import com.mindflow.py4j.exception.IllegalPinyinException;
/**
* @author Ricky Fung
*/
public interface Converter {
String[] getPinyin(char ch) throws IllegalPinyinException;
String getPinyin(String chinese) throws IllegalPinyinException;
}
| true |
b1c7bb7ff71de89ce31e69ff4fd55c37ad32dc59 | Java | kiworkshop/community | /community-backend/core/core-auth/src/main/java/org/kiworkshop/community/auth/dto/AuthenticationDto.java | UTF-8 | 452 | 1.953125 | 2 | [] | no_license | package org.kiworkshop.community.auth.dto;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Getter;
@Getter
public class AuthenticationDto {
@JsonProperty("access_token")
private String accessToken;
@JsonProperty("token_type")
private String tokenType;
@JsonProperty("refresh_token")
private String refreshToken;
@JsonProperty("expires_in")
private int expiresIn;
@JsonProperty("scope")
private String scope;
}
| true |
57c828aed783dd41b4a9b317f009e464b9d15038 | Java | StElenaa/Project-Kovalenko | /Project Kovalenko/src/com/company/lesson15/WeightOfBoxes.java | WINDOWS-1251 | 1,272 | 3.671875 | 4 | [] | no_license | package com.company.lesson15;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import com.company.lesson14.HeavyBox;
/**
* , HeavyBox. getBoxes
* . 300 ,
* .
*
* @author Elen
*
*/
public class WeightOfBoxes {
public static void main(String[] args) {
List<HeavyBox> boxes = new ArrayList<>();
boxes.add(new HeavyBox(34, 76, 9, 170));
boxes.add(new HeavyBox(34, 76, 9, 305));
boxes.add(new HeavyBox(34, 76, 9, 140));
boxes.add(new HeavyBox(34, 76, 9, 340));
System.out.println(getBoxes(boxes));
System.out.println(boxes);
}
public static List<HeavyBox> getBoxes(List<HeavyBox> boxes) {
List<HeavyBox> newList = new ArrayList<>();
Iterator<HeavyBox> iterator = boxes.iterator();
while (iterator.hasNext()) {
HeavyBox heavyBox = iterator.next();
if (heavyBox.getWeight() > 300) {
iterator.remove();
newList.add(heavyBox);
}
}
return newList;
}
}
| true |
149220432ff314e05fd6b449a0123e39882413ac | Java | aeells/spark | /server/src/test/java/testutil/MyTestUtil.java | UTF-8 | 1,435 | 2.671875 | 3 | [
"Apache-2.0"
] | permissive | package testutil;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;
import spark.utils.IOUtils;
public class MyTestUtil {
private int port;
public MyTestUtil(int port) {
this.port = port;
}
public UrlResponse doMethod(String requestMethod, String path, String body)
throws Exception {
URL url = new URL("http://localhost:" + port + path);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod(requestMethod);
if (requestMethod.equals("POST") && body != null) {
connection.setDoOutput(true);
connection.getOutputStream().write(body.getBytes());
}
connection.connect();
String res = IOUtils.toString(connection.getInputStream());
UrlResponse response = new UrlResponse();
response.body = res;
response.status = connection.getResponseCode();
response.headers = connection.getHeaderFields();
return response;
}
public int getPort() {
return port;
}
public static class UrlResponse {
public Map<String, List<String>> headers;
public String body;
public int status;
}
public static void sleep(long time) {
try {
Thread.sleep(time);
} catch (Exception e) {}
}
}
| true |
b081f0300fe0a5c4769908027c298f3028a4ee75 | Java | WhiteLie1/code_back | /javademo/IdeaProjects/basic-code/day04-code/src/cn/itcast/day04/demo01/Extends/Demo02/Demo01Override.java | UTF-8 | 798 | 3.15625 | 3 | [] | no_license | package cn.itcast.day04.demo01.Extends.Demo02;
/*
方法覆盖重写注意事项:
1.必须保证父子类之间的名称相同,参数列表也相同
@Override 写在方法前面,用来检测是不是有效的正确覆盖重写。
这个注解就算不写,只要满足要求,也是正确的方法覆盖重写
2.子类的方法的返回值必须是小于等于父类方法的返回值范围
小扩展提示:java.lang.Object类是所有类的公共最高父类(祖宗类)。java.lang.String就是Object子类
3.子类方法的权限必须【大于等于】父类方法的权限修饰符
备注:小拓展提示: public > protected >(default) > private
备注:(default)不是关键字default,而是什么都不写,留空
*/
public class Demo01Override {
public int num;
}
| true |
5e795e875476eebadb4fa88a6283478082c5d4d6 | Java | Elsopeen/LyokoMod-1.15 | /src/main/java/elsopeen/lyokomod/world/dimension/MountainDim.java | UTF-8 | 1,920 | 2.296875 | 2 | [] | no_license | package elsopeen.lyokomod.world.dimension;
import elsopeen.lyokomod.init.ModBlocks;
import elsopeen.lyokomod.world.dimension.util.*;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.ChunkPos;
import net.minecraft.util.math.Vec3d;
import net.minecraft.world.World;
import net.minecraft.world.dimension.Dimension;
import net.minecraft.world.dimension.DimensionType;
import net.minecraft.world.gen.ChunkGenerator;
import javax.annotation.Nullable;
public class MountainDim extends Dimension {
public MountainDim(World world, DimensionType dimensionType){
super(world,dimensionType,0.0f);
}
@Override
public ChunkGenerator<?> createChunkGenerator() {
LyokoGenSettings lyokoGenSettings = new LyokoGenSettings();
lyokoGenSettings.setDefaultBlock(ModBlocks.MOUNTAIN_ROCK.get().getDefaultState());
lyokoGenSettings.setDefaultFluid(ModBlocks.NUMERIC_SEA_FLUID_BLOCK.get().getDefaultState());
return new LyokoChunkGenerator(world,
new LyokoMountainBiomeProvider(new LyokoBiomeProviderSettings(this.world.getWorldInfo())),
lyokoGenSettings);
}
@Nullable
@Override
public BlockPos findSpawn(ChunkPos chunkPosIn, boolean checkValid) {
return null;
}
@Nullable
@Override
public BlockPos findSpawn(int posX, int posZ, boolean checkValid) {
return null;
}
@Override
public float calculateCelestialAngle(long worldTime, float partialTicks) {
return 0;
}
@Override
public boolean isSurfaceWorld() {
return false;
}
@Override
public Vec3d getFogColor(float celestialAngle, float partialTicks) {
return new Vec3d(0xdb,0xc2,0xff);
}
@Override
public boolean canRespawnHere() {
return false;
}
@Override
public boolean doesXZShowFog(int x, int z) {
return false;
}
}
| true |
1a6b626333cc8a117f70b7559a48e9d09f2049c1 | Java | mokelab/BearDance | /app/src/main/java/net/exkazuu/mimicdance/interpreter/Pose.java | UTF-8 | 1,484 | 2.828125 | 3 | [] | no_license | package net.exkazuu.mimicdance.interpreter;
public class Pose {
private final boolean[] bodyPart2up;
public Pose() {
bodyPart2up = new boolean[4];
}
public boolean validate(Iterable<ActionType> actions) {
for (ActionType actionType : actions) {
if (actionType == ActionType.Jump) {
for (boolean up : bodyPart2up) {
if (up) {
return false;
}
}
} else if (actionType.isUp() == bodyPart2up[actionType.toBodyPart().ordinal()]) {
return false;
}
}
return true;
}
public void change(Iterable<ActionType> actions) {
for (ActionType actionType : actions) {
if (actionType != ActionType.Jump) {
bodyPart2up[actionType.toBodyPart().ordinal()] = actionType.isUp();
}
}
}
public void reset() {
for (int i = 0; i < bodyPart2up.length; i++) {
bodyPart2up[i] = false;
}
}
public boolean isLeftHandUp() {
return bodyPart2up[BodyPartType.LeftHand.ordinal()];
}
public boolean isRightHandUp() {
return bodyPart2up[BodyPartType.RightHand.ordinal()];
}
public boolean isLeftFootUp() {
return bodyPart2up[BodyPartType.LeftFoot.ordinal()];
}
public boolean isRightFootUp() {
return bodyPart2up[BodyPartType.RightFoot.ordinal()];
}
}
| true |
38dffe007e0c3fecd25ff0d660ac6f5031517f59 | Java | dezi/TVPush | /brl/src/main/java/de/xavaro/android/brl/publics/SmartPlugHandler.java | UTF-8 | 1,355 | 2.125 | 2 | [] | no_license | package de.xavaro.android.brl.publics;
import org.json.JSONObject;
import de.xavaro.android.brl.base.BRL;
import de.xavaro.android.brl.comm.BRLCommand;
import de.xavaro.android.brl.simple.Json;
import de.xavaro.android.brl.simple.Simple;
import de.xavaro.android.pub.interfaces.pub.PUBSmartPlug;
public class SmartPlugHandler implements PUBSmartPlug
{
private String uuid;
private String ipaddr;
private String macaddr;
public SmartPlugHandler(String uuid, String ipaddr, String macaddr)
{
this.uuid = uuid;
this.ipaddr = ipaddr;
this.macaddr = macaddr;
}
@Override
public boolean setPlugState(final int onoff)
{
Runnable runnable = new Runnable()
{
@Override
public void run()
{
int res = BRLCommand.setPowerStatus(ipaddr, macaddr, onoff);
if (res >= 0)
{
JSONObject status = new JSONObject();
Json.put(status, "uuid", uuid);
Json.put(status, "plugstate", res);
BRL.instance.onDeviceStatus(status);
}
}
};
Simple.runBackground(runnable);
return true;
}
@Override
public boolean setLEDState(int onoff)
{
return false;
}
}
| true |
d659e56c9d711ad5ff9080ada0bddb79aeaee4c8 | Java | SarahCam/Week_07_Day_4 | /src/main/java/Cleric.java | UTF-8 | 350 | 2.609375 | 3 | [] | no_license | import java.util.ArrayList;
public class Cleric extends Player implements IHeal {
private ArrayList<HealingTool> healingTools;
public Cleric(String name) {
super(name);
this.healingTools = new ArrayList<>();
}
@Override
public ArrayList<HealingTool> getHealingToolList() {
return healingTools;
}
}
| true |
a9f0d4d76a834a83d4f2a86ccba03b812c678614 | Java | riugduso/TransMoney | /TransNumber.java | UTF-8 | 2,019 | 3.71875 | 4 | [] | no_license | import java.util.Scanner;
class TransNumber {
public static void main(String[] args) {
char capNumber[] = {'零','壹','贰','叁','肆','伍','陆','柒','捌','玖'}; //capNumber[]存储大写数字汉字
String unit[] = {"","圆","拾","佰","仟","万","拾","佰","仟","亿","拾","佰","仟"}; //unit[]存储每一个位数所对应的大写汉字单位 unit[0]="",方便对应。
Scanner sc = new Scanner(System.in); //键盘录入数据
System.out.println("请输入12位以内任意整数:");
long num;
//判断输入数据合理性
while(true){
num = sc.nextLong();
String line = num +"";
if(line.length() > 12){
System.out.println("您输入的数据位数过大!请重输:");
}else {
break;
}
}
int times = 0; //记录除的次数
long shang = 0; //记录每一次的商
long yushu = 0; //记录每一次的余数
String str = "";
while(true){
shang = num / 10; //得到商
yushu = num % 10; //得到余数
if(shang == 0 && yushu == 0){ //当商和余数同时为0时退出循环
break;
}else{ //否则,将商重新赋值给num,继续循环
num = shang;
}
times++; //次数加1,得到每位数据
str = capNumber[ (int) yushu]+unit[times] + str; //将大写数字汉字和大写单位连接赋值给str
} //去除字符串中的0
str = str.replaceAll("零[拾佰仟]","零").replaceAll("零+亿","亿").replaceAll("零{4}万", "")
.replaceAll("零+万","万").replaceAll("零+圆","圆").replaceAll("零+", "零")+"整";
System.out.println("阿拉伯数字转换成中国传统形式为: ");
System.out.println(str); //输出字符串
}
} | true |
37fda4226f5ab0071c433eb11516a468c7e23262 | Java | Nidum/orm-problems | /src/main/java/eleks/mentorship/entity/Course.java | UTF-8 | 1,360 | 2.828125 | 3 | [] | no_license | package eleks.mentorship.entity;
import javax.persistence.*;
import static javax.persistence.GenerationType.IDENTITY;
@Entity
@Table(name = "course")
public class Course {
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "id", unique = true, nullable = false)
private int id;
@Column(name = "name", nullable = false, length = 50)
private String name;
@Column(name = "hours")
private int hours;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "teacher", nullable = false)
private Teacher teacher;
public Course() {
}
public Course(String name, int hours, Teacher teacher) {
this.name = name;
this.hours = hours;
this.teacher = teacher;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getHours() {
return hours;
}
public void setHours(int hours) {
this.hours = hours;
}
public Teacher getTeacher() {
return teacher;
}
public void setTeacher(Teacher teacher) {
this.teacher = teacher;
}
@Override
public String toString() {
return name + ": " + hours + "h";
}
}
| true |
0449c155b1d2ed2cba73f15178eb6e78cdc1e1e8 | Java | darling001/vandream-mall | /src/main/java/com/vandream/mall/business/service/impl/DemandServiceImpl.java | UTF-8 | 16,779 | 1.9375 | 2 | [] | no_license | package com.vandream.mall.business.service.impl;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.vandream.mall.business.constant.AttachmentType;
import com.vandream.mall.business.constant.BusinessType;
import com.vandream.mall.business.dao.AttachmentDAO;
import com.vandream.mall.business.dao.DemandHeadDAO;
import com.vandream.mall.business.dao.DemandLineDAO;
import com.vandream.mall.business.dao.SolutionHeadDAO;
import com.vandream.mall.business.domain.Attachment;
import com.vandream.mall.business.dto.BxApiResult;
import com.vandream.mall.business.dto.aus.AttachmentDTO;
import com.vandream.mall.business.dto.demand.*;
import com.vandream.mall.business.execption.DemandException;
import com.vandream.mall.business.execption.SmsMsgException;
import com.vandream.mall.business.service.AddressService;
import com.vandream.mall.business.service.DemandService;
import com.vandream.mall.business.vo.AddressVO;
import com.vandream.mall.business.vo.demand.*;
import com.vandream.mall.commons.constant.ResultStatusConstant;
import com.vandream.mall.commons.service.ApiExecutorBxService;
import com.vandream.mall.commons.utils.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author dingjie
* @date 2018/3/28
* @time 19:48
* Description:
*/
@Service("demandService")
public class DemandServiceImpl implements DemandService {
private static final Logger logger = LoggerFactory.getLogger(DemandServiceImpl.class);
@Autowired
private AddressService addressService;
@Autowired
private ApiExecutorBxService apiExecutorBxService;
@Autowired
private DemandHeadDAO demandHeadDAO;
@Autowired
private SolutionHeadDAO solutionHeadDAO;
@Autowired
private DemandLineDAO demandLineDAO;
@Autowired
private AttachmentDAO attachmentDAO;
/* 需求类型10:简要;20:详细 */
private final String DEMAND_TYPE = "20";
private final String DEMAND_TO_BE_CONFIRMED = "35";
private final String DEMAND_QUERY_ALL = "all";
@Override
public Boolean addDemandInfo(DemandHeadVO demandHeadVO) throws DemandException {
Map<String, Object> validation = ValidatorUtils.validation(demandHeadVO);
if (ObjectUtil.isNotEmpty(validation)) {
DemandException demandException = new DemandException(ResultStatusConstant.INPUT_PARAM_ERROR);
demandException.setMessage(JSON.toJSONString(validation));
throw demandException;
}
if (!RegexUtil.isChinaMobilePhone(demandHeadVO.getDemandPhone())) {
throw new DemandException(ResultStatusConstant.SMS_MESSAGE_PHONE_NOT_MATCH);
}
DemandHeadLineDTO demandHeadLineDTO = null;
try {
/* 将入参VO对象转换为DTO对象 */
demandHeadLineDTO = ObjectUtil.transfer(demandHeadVO, DemandHeadLineDTO.class);
demandHeadLineDTO.setDeliveryPeriodStart(DateUtils.formatDate(
new java.util.Date(demandHeadVO.getDateTimeStart()), "yyyyMMdd"));
demandHeadLineDTO.setDeliveryPeriodEnd(DateUtils.formatDate(
new java.util.Date(demandHeadVO.getDateTimeEnd()), "yyyyMMdd"));
String demandType = demandHeadVO.getDemandType();
//根据需求类型获取三种需求信息
if (StringUtil.isNotBlank(demandType)) {
//简要需求(包含文本需求和附件需求)
String attachName = demandHeadVO.getAttachmentName();
if (StringUtil.isNotBlank(attachName)) {
//存储附件需求
Attachment attachment = new Attachment();
attachment.setAttachmentName(demandHeadVO.getAttachmentName());
attachment.setAttachmentPath(demandHeadVO.getAttachmentPath());
attachment.setAttachmentType(AttachmentType.PSD_DEMAND_FILE);
attachment.setFileSize(new BigDecimal(demandHeadVO.getFileSize()));
attachment.setFileType(demandHeadVO.getFileType());
List<Attachment> attachmentList = new ArrayList<Attachment>();
attachmentList.add(attachment);
demandHeadLineDTO.setAttachmentList(attachmentList);
} else {
//存储文本需求
demandHeadLineDTO.setAttachmentList(null);
}
if (demandType.equals(DEMAND_TYPE)) {
//存储详细需求
Object demandDis = demandHeadVO.getDemandDiscuss();
if (ObjectUtil.isEmpty(demandDis)) {
throw new DemandException(ResultStatusConstant.DEMAND_DISCUSS_PARAM_CAN_NOT_NULL);
}
String demandDiscuss = JSON.toJSONString(demandDis);
List<DemandLineVO> demandLineVOList = JSONUtil.toList(demandDiscuss, DemandLineVO.class);
List<SubLineDTO> demandLineDTOList = null;
demandLineDTOList = ObjectUtil.transfer(demandLineVOList, SubLineDTO.class);
demandHeadLineDTO.setSubLineList(demandLineDTOList);
}
}
//获取地址信息
String addressId = demandHeadVO.getAddressId();
if (StringUtil.isNotBlank(addressId)) {
AddressVO addressVO = addressService.getAddressById(demandHeadVO.getCompanyId(), addressId);
if (ObjectUtil.isNotEmpty(addressVO)) {
StringBuilder stringBuilder = new StringBuilder();
String provinceName = addressVO.getProvinceName();
String cityName = addressVO.getCityName();
String countyName = addressVO.getCountyName();
String phone = addressVO.getContactNumber();
String userName = addressVO.getContacts();
String addressDetail = addressVO.getAddress();
stringBuilder.append(addressDetail).append("(" + userName + " 收)").append(phone);
demandHeadLineDTO.setCustomerConsigneetName(userName);
demandHeadLineDTO.setCustomerConsigneetPhone(phone);
demandHeadLineDTO.setSiteRegionCode(addressVO.getProvinceCode());
demandHeadLineDTO.setSiteRegionName(provinceName);
demandHeadLineDTO.setSiteCityCode(addressVO.getCityCode());
demandHeadLineDTO.setSiteCityName(cityName);
demandHeadLineDTO.setSiteCountyCode(addressVO.getAreaCode());
demandHeadLineDTO.setSiteCountyName(countyName);
demandHeadLineDTO.setCustomerSiteArea(stringBuilder.toString());
demandHeadLineDTO.setSiteCountryCode(addressVO.getCountryCode());
demandHeadLineDTO.setSiteCountryName(addressVO.getCountryName());
}
}
//业务类型
demandHeadLineDTO.setBusinessType(BusinessType.PSD_DEMAND);
//需求详述
demandHeadLineDTO.setDemandDiscuss(demandHeadVO.getDemandRemark());
//账套code
demandHeadLineDTO.setBookCode("1000");
//来源类别(10 商城)
demandHeadLineDTO.setFromType("10");
//需求提出人
demandHeadLineDTO.setOperatorUserId(demandHeadVO.getUserId());
demandHeadLineDTO.setOperatorUserName(demandHeadVO.getUserName());
demandHeadLineDTO.setAccountId(demandHeadVO.getUserId());
demandHeadLineDTO.setAccountName(demandHeadVO.getUserName());
//调用 api添加需求
String resultStr = apiExecutorBxService.addDemandInfo(demandHeadLineDTO);
if (StringUtil.isBlank(resultStr)) {
//调用宝信接口失败
throw new DemandException(ResultStatusConstant.REMOTE_INTERFACE_CALL_FAILURE);
}
BxApiResult bxApiResult = JSONUtil.toBean(resultStr, BxApiResult.class);
if (ObjectUtil.isNotEmpty(bxApiResult)) {
if ("1".equals(bxApiResult.getStatus().toString())) {
return true;
} else {
throw new DemandException(ResultStatusConstant.REMOTE_INTERFACE_CALL_FAILURE);
}
}
}catch(DemandException se){
logger.error("=====DemandException====addDemandInfo={}",se.toString());
throw se;
} catch (Exception e) {
logger.error("======addDemandInfo={}", e.toString());
throw new DemandException(ResultStatusConstant.DEMAND_PUBLISH_EXCEPTION);
}
return false;
}
@Override
public DemandResponseVO findDemandList(DemandRequestVO demandRequestVO) throws DemandException {
Map<String, Object> validation = ValidatorUtils.validation(demandRequestVO, null);
if (ObjectUtil.isNotEmpty(validation)) {
DemandException demandException = new DemandException(ResultStatusConstant.INPUT_PARAM_ERROR);
demandException.setMessage(JSON.toJSONString(validation));
throw demandException;
}
DemandResponseVO demandResponseVO = new DemandResponseVO();
//根据前台关键字与起始时间查询需求订单
try {
int pageNo = demandRequestVO.getPageNo();
int pageSize = demandRequestVO.getPageSize();
List<DemandBillVO> demandBillVOList = null;
PageHelper.startPage(pageNo, pageSize);
String demandStatus = demandRequestVO.getDemandStatus();
//处理提交结束时间
Long endDate = demandRequestVO.getSubmitEndTime();
if (null != endDate && endDate > 0) {
endDate += (1000 * 60 * 60 * 24);
demandRequestVO.setSubmitEndTime(endDate);
}
//当搜索全部或待确认状态 的需求单时需要单独处理
if (null != demandStatus && !"".equals(demandStatus)) {
if (DEMAND_QUERY_ALL.equals(demandRequestVO.getDemandStatus())) {
demandRequestVO.setDemandStatus("");
}
}
demandBillVOList = demandHeadDAO.selectDemandSolutionList(demandRequestVO);
demandResponseVO.setDemandBillVOList(demandBillVOList);
demandResponseVO.setPageNo(pageNo);
demandResponseVO.setPageSize(demandBillVOList.size());
PageInfo<DemandBillVO> pageInfo = new PageInfo<>(demandBillVOList);
Long totalSize = pageInfo.getTotal();
demandResponseVO.setTotalSize(totalSize.intValue());
} catch (Exception e) {
logger.error("======findDemandList={}", e.toString());
throw new DemandException(ResultStatusConstant.DEMAND_LIST_QUERY_FAILED);
}
return demandResponseVO;
}
@Override
public List<DemandSolutionVO> findSchemeList(String userId, String demandId) throws DemandException {
if (StringUtil.isBlank(userId) || StringUtil.isBlank(demandId)) {
throw new DemandException(ResultStatusConstant.DEMAND_SOLUTION_PARAM_CAN_NOT_NULL);
}
List<DemandSolutionVO> demandSolutionVOList = null;
try {
List<DemandSolutionDTO> demandSolutionList = solutionHeadDAO.getDemandSolutionList(userId, demandId);
demandSolutionVOList = ObjectUtil.transfer(demandSolutionList, DemandSolutionVO.class);
} catch (Exception e) {
logger.error("======findSchemeList={}", e.toString());
throw new DemandException(ResultStatusConstant.DEMAND_SOLUTION_LIST_QUERY_FAILED);
}
return demandSolutionVOList;
}
@Override
public Boolean updateSchemeStatus(DemandStatusVO demandStatusVO) throws DemandException {
Map<String, Object> validation = ValidatorUtils.validation(demandStatusVO);
if (ObjectUtil.isNotEmpty(validation)) {
DemandException demandException = new DemandException(ResultStatusConstant
.INPUT_PARAM_ERROR);
demandException.setMessage(JSON.toJSONString(validation));
throw demandException;
}
DemandStatusDTO demandStatusDTO = new DemandStatusDTO();
try {
if (null != demandStatusVO) {
demandStatusDTO = ObjectUtil.transfer(demandStatusVO, DemandStatusDTO.class);
demandStatusDTO.setOperatorUserId(demandStatusVO.getUserId());
demandStatusDTO.setOperatorUserName(demandStatusVO.getUserName());
}
if (null != demandStatusDTO) {
String resultStatus = apiExecutorBxService.updateSchemeStatus(demandStatusDTO);
if (null != resultStatus && !"".equals(resultStatus)) {
BxApiResult bxApiResult = JSONUtil.toBean(resultStatus, BxApiResult.class);
if (null != bxApiResult) {
if ("1".equals(bxApiResult.getStatus().toString())) {
return true;
} else {
//调用宝信接口失败
throw new DemandException(ResultStatusConstant.REMOTE_INTERFACE_CALL_FAILURE);
}
}
}
}
} catch (Exception e) {
logger.error("======updateSchemeStatus={}", e.toString());
throw new DemandException(ResultStatusConstant.DEMAND_SOLUTION_STATUS_UPDATE_FAILED);
}
return false;
}
@Override
public DemandDetailVO getDemandInfo(String userId, String demandId) throws DemandException {
if (StringUtil.isBlank(userId) || StringUtil.isBlank(demandId)) {
throw new DemandException(ResultStatusConstant.DEMAND_SOLUTION_PARAM_CAN_NOT_NULL);
}
DemandRequestVO demandRequestVO = new DemandRequestVO();
demandRequestVO.setUserId(userId);
demandRequestVO.setDemandId(demandId);
DemandDetailVO demandDetailVO = new DemandDetailVO();
try {
//获取需求单主表信息
DemandDetailDTO demandDetailDTO = demandHeadDAO.selectDetailByDemandId(demandRequestVO);
if (null != demandDetailDTO) {
//查询需求单对应的附件表信息
Map<String, Object> map = new HashMap<>();
map.put("billNo", demandId);
map.put("businessType", BusinessType.PSD_DEMAND);
map.put("attachmentType", AttachmentType.PSD_DEMAND_FILE);
List<AttachmentDTO> attachmentList = attachmentDAO.findByBillNo(map);
//判断附件是否为空,不为空就把附件名与路径放在demandDetailDTO对应属性上
if (null != attachmentList && attachmentList.size() > 0) {
demandDetailDTO.setFileName(attachmentList.get(0).getFileName());
demandDetailDTO.setFilePath(attachmentList.get(0).getFilePath());
}
List<DemandLineDetailDTO> demandLineList = demandLineDAO.getDemandLineList(demandRequestVO);
List<DemandSolutionVO> schemeList = findSchemeList(userId, demandId);
List<DemandVisitLogVO> visitLogs = demandLineDAO.getdemandVisitLogs(demandRequestVO);
demandDetailVO = ObjectUtil.transfer(demandDetailDTO, DemandDetailVO.class);
List<DemandLineDetailDTO> demandLineDTOList=new ArrayList<>();
if(ObjectUtil.isNotEmpty(demandLineList)){
for(DemandLineDetailDTO dl:demandLineList){
if(StringUtil.isNotBlank(dl.getItemName())){
demandLineDTOList.add(dl);
}
}
demandDetailVO.setDemandLineDetailDTOList(demandLineDTOList);
}else{
demandDetailVO.setDemandLineDetailDTOList(null);
}
demandDetailVO.setDemandSolutionVOList(schemeList);
demandDetailVO.setLogList(visitLogs);
}
} catch (Exception e) {
logger.error("=======getDemandInfo={}",e.toString());
throw new DemandException(ResultStatusConstant.DEMAND_DETAIL_INFO_QUERY_FAILED);
}
return demandDetailVO;
}
}
| true |
2b4a4d1c1833705fe4f9c16cd1f73b048bf80c5b | Java | silzoons/order-from-scratch | /order-from-scratch/src/main/java/com/switchfully/orderfromscratch/api/CustomerController.java | UTF-8 | 1,177 | 2.21875 | 2 | [] | no_license | package com.switchfully.orderfromscratch.api;
import com.switchfully.orderfromscratch.service.CustomerService;
import com.switchfully.orderfromscratch.service.dto.GetCustomerDto;
import com.switchfully.orderfromscratch.service.dto.CustomerDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping(path="/customers")
public class CustomerController {
private CustomerService customerService;
@Autowired
public CustomerController(CustomerService customerService) {
this.customerService = customerService;
}
@PostMapping(produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(HttpStatus.CREATED)
public void createCustomer(@RequestBody CustomerDto customerDto){
customerService.createCustomer(customerDto);
}
@GetMapping(produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(HttpStatus.OK)
public List<GetCustomerDto> getAllCustomers(){
return customerService.getAllCustomers();
}
}
| true |
504342c876a11be6c528ce8e8667a409c20f1f48 | Java | kajolingale/Java | /Q62.java | UTF-8 | 710 | 2.9375 | 3 | [] | no_license | package a1;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Q62 {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader("/D/abcd.txt"));
int ch;
char charToSearch='a';
int counter=0;
while((ch=reader.read()) != -1) {
if(charToSearch == (char)ch) {
counter++;
}
};
reader.close();
System.out.println("a occurs " + counter+ " times");
}
}
| true |
2de4d7ba6418c66c0d06801b7ae6eb9994c4e327 | Java | mikelduke/AnoWS | /src/main/java/com/mikelduke/webservice/annotations/AWS.java | UTF-8 | 468 | 2.078125 | 2 | [
"Apache-2.0"
] | permissive | /**
*
*/
package com.mikelduke.webservice.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @author Mikel
*
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface AWS {
String path();
String method() default "*";
boolean startsWith() default false;
String description() default "A Webservice";
}
| true |
ea843e6daa1f9c2bc202589141f8b0a3dde20525 | Java | yjzhong89/spring-cloud | /cloud-stream-rabbitmq-consumer8802/src/main/java/com/zyj/springcloud/controller/ReceiveMessageController.java | UTF-8 | 641 | 2.265625 | 2 | [] | no_license | package com.zyj.springcloud.controller;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.cloud.stream.messaging.Sink;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;
/**
* @author yjzhong
* @date 2020/10/14 16:34
*/
@Component
@EnableBinding(Sink.class)
public class ReceiveMessageController {
@StreamListener(Sink.INPUT)
public void input(Message<String> message) {
System.out.println("消费者1号,接收到的消息是:" + message.getPayload());
}
}
| true |
78897a9d2b642c57b7ab1861b6b9e06922750eb4 | Java | AlanRun/match_test | /src/smc/TimeTest.java | UTF-8 | 3,366 | 2.078125 | 2 | [] | no_license | package smc;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import helper.DataUrls;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import utils.HttpRequester;
import utils.HttpRespons;
public class TimeTest {
private static String jz_url = DataUrls.ft_qlive;
private static String url = DataUrls.ft_collect;
static Map<String, String> params = new HashMap<String, String>();
public static String getJZMatchs(String issue) throws IOException {
HttpRequester request = new HttpRequester();
request.setDefaultContentEncoding("utf-8");
HttpRespons hr = request.sendGet(jz_url + issue);
String matchs = "";
String json = hr.getContent();
if (json == null || json.equals("")) {
System.out.println("empty content!!!");
return matchs;
} else {
// System.out.println(json);
}
JSONObject obj = JSONObject.fromObject(json);
JSONArray MIarray = obj.getJSONArray("MI");
for (int i = 0; i < MIarray.size(); i++) {
JSONObject MI = MIarray.getJSONObject(i);
JSONArray MSarray = MI.getJSONArray("MS");
for (int j = 0; j < MSarray.size(); j++) {
JSONObject M = MSarray.getJSONObject(j);
int match = M.getInt("MId");
String NUM = M.getString("NUM");
int IC = M.getInt("IC");
int SO = M.getInt("SO");
String SS = M.getString("SS");
if (!(NUM.equals("032") || NUM.equals("033"))) {
continue;
} else {
// if (IC == 1) {
// continue;
// }
request = new HttpRequester();
request.setDefaultContentEncoding("UTF-8");
hr = request.sendGet(url + match);
json = hr.getContent();
if (json == null || json.equals("")) {
System.out.println("json is empty");
} else {
// System.out.println(json);
}
obj = JSONObject.fromObject(json);
MIarray = obj.getJSONArray("MI");
MI = MIarray.getJSONObject(i);
MSarray = MI.getJSONArray("MS");
M = MSarray.getJSONObject(0);
int SO1 = M.getInt("SO");
String SS1 = M.getString("SS");
Date d = new Date();
String ssss = d.toString() + "\t" + NUM + "\t列表源:" + SO + "\t比分列表时间:" + SS + "\t方案详情时间:" + SS1
+ "\t方案源:" + SO1;
System.out.println(ssss);
saveToFile(ssss, "log.txt", false);
matchs = matchs + match;
if (j < MSarray.size() - 1) {
matchs = matchs + ",";
}
break;
}
}
}
System.out.println();
return matchs;
}
public static void saveToFile(String text, String path, boolean isClose) {
File file = new File(path);
BufferedWriter bf = null;
try {
FileOutputStream outputStream = new FileOutputStream(file, true);
OutputStreamWriter outWriter = new OutputStreamWriter(outputStream);
bf = new BufferedWriter(outWriter);
bf.append(text);
bf.newLine();
bf.flush();
if (isClose)
bf.close();
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException, InterruptedException {
for (int i = 0; i < 9 * 60 * 5; i++) {
getJZMatchs("2017-09-05");
Thread.sleep(1 * 1000);
}
}
}
| true |
5f439ae88d83101ff30cebbf35f4d686d637eded | Java | jaimegc/raddarapp | /app/src/main/java/com/raddarapp/presentation/general/viewmodel/builder/FootprintRankingViewModelBuilder.java | UTF-8 | 5,148 | 1.96875 | 2 | [
"Apache-2.0"
] | permissive | package com.raddarapp.presentation.general.viewmodel.builder;
import com.raddarapp.presentation.general.viewmodel.FootprintRankingViewModel;
public class FootprintRankingViewModelBuilder {
private String key;
private String title;
private String media;
private String userKey;
private String username;
private String userImage;
private String userLevel;
private int userRelationship;
private String creationMoment;
private int mediaType;
private int visibility;
private int sponsored;
private long comments;
private long scope;
private int category;
private int level;
private double latitude;
private double longitude;
private String audio;
private long likes;
private long dislikes;
private int type;
private boolean visible;
private String zoneName;
private String parentZoneName;
private String countryEmoji;
private boolean powerSelected;
public FootprintRankingViewModelBuilder() {}
public FootprintRankingViewModel build() {
return new FootprintRankingViewModel(key, title, media, userKey, username, userImage, userLevel,
userRelationship, creationMoment, mediaType, visibility, sponsored, comments, scope, category,
level, latitude, longitude, audio, likes, dislikes, type, visible, zoneName, parentZoneName,
countryEmoji, powerSelected);
}
public FootprintRankingViewModelBuilder withKey(String key) {
this.key = key;
return this;
}
public FootprintRankingViewModelBuilder withTitle(String title) {
this.title = title;
return this;
}
public FootprintRankingViewModelBuilder withMedia(String media) {
this.media = media;
return this;
}
public FootprintRankingViewModelBuilder withUserKey(String userKey) {
this.userKey = userKey;
return this;
}
public FootprintRankingViewModelBuilder withUsername(String username) {
this.username = username;
return this;
}
public FootprintRankingViewModelBuilder withUserImage(String userImage) {
this.userImage = userImage;
return this;
}
public FootprintRankingViewModelBuilder withUserLevel(String userLevel) {
this.userLevel = userLevel;
return this;
}
public FootprintRankingViewModelBuilder withUserRelationship(int userRelationship) {
this.userRelationship = userRelationship;
return this;
}
public FootprintRankingViewModelBuilder withCreationMoment(String creationMoment) {
this.creationMoment = creationMoment;
return this;
}
public FootprintRankingViewModelBuilder withMediaType(int mediaType) {
this.mediaType = mediaType;
return this;
}
public FootprintRankingViewModelBuilder withVisibility(int visibility) {
this.visibility = visibility;
return this;
}
public FootprintRankingViewModelBuilder withSponsored(int sponsored) {
this.sponsored = sponsored;
return this;
}
public FootprintRankingViewModelBuilder withComments(long comments) {
this.comments = comments;
return this;
}
public FootprintRankingViewModelBuilder withScope(long scope) {
this.scope = scope;
return this;
}
public FootprintRankingViewModelBuilder withCategory(int category) {
this.category = category;
return this;
}
public FootprintRankingViewModelBuilder withLevel(int level) {
this.level = level;
return this;
}
public FootprintRankingViewModelBuilder withLatitude(double latitude) {
this.latitude = latitude;
return this;
}
public FootprintRankingViewModelBuilder withLongitude(double longitude) {
this.longitude = longitude;
return this;
}
public FootprintRankingViewModelBuilder withAudio(String audio) {
this.audio = audio;
return this;
}
public FootprintRankingViewModelBuilder withLikes(long likes) {
this.likes = likes;
return this;
}
public FootprintRankingViewModelBuilder withDislikes(long dislikes) {
this.dislikes = dislikes;
return this;
}
public FootprintRankingViewModelBuilder withPowerSelected(boolean powerSelected) {
this.powerSelected = powerSelected;
return this;
}
public FootprintRankingViewModelBuilder withType(int type) {
this.type = type;
return this;
}
public FootprintRankingViewModelBuilder withVisible(boolean visible) {
this.visible = visible;
return this;
}
public FootprintRankingViewModelBuilder withZoneName(String zoneName) {
this.zoneName = zoneName;
return this;
}
public FootprintRankingViewModelBuilder withParentZoneName(String parentZoneName) {
this.parentZoneName = parentZoneName;
return this;
}
public FootprintRankingViewModelBuilder withCountryEmoji(String countryEmoji) {
this.countryEmoji = countryEmoji;
return this;
}
}
| true |
e183d7934b7b137672d36429ca28d18a1fcb92e8 | Java | klevispashollari/algorithms | /src/boomfilter/DefaultHashFunction.java | UTF-8 | 394 | 2.96875 | 3 | [] | no_license | package boomfilter;
/**
* A default implementation of the {@link HashFunction} interface.
* This implementation simply returns {@link Object#hashCode()}.
*
* @param <T> The type for which a hash value is calculated
*/
public class DefaultHashFunction<T> implements HashFunction<T> {
/**
* {@inheritDoc}
*/
@Override
public int hash(T element) {
return element.hashCode();
}
}
| true |
07fae9cfdf91f3f92bfdedf5fbee54ea06af9fe2 | Java | moutainhigh/dousto | /oms-rs/src/main/java/com/ibm/oms/rs/service/impl/OmsQueryOrderInfoServiceImpl.java | UTF-8 | 1,033 | 1.882813 | 2 | [] | no_license | /**
*
*/
package com.ibm.oms.rs.service.impl;
import javax.annotation.Resource;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import com.ibm.oms.intf.intf.WdOrderDTO;
import com.ibm.oms.rs.service.OmsQueryOrderInfoService;
import com.ibm.oms.service.business.WdOrderListService;
import com.ibm.sc.rs.service.impl.BaseRsServiceImpl;
/**
* 微店 查询订单信息
* @author xiaonanxiang
*
*/
@Component("omsQueryOrderInfoService")
public class OmsQueryOrderInfoServiceImpl extends BaseRsServiceImpl implements OmsQueryOrderInfoService {
private final Logger logger = LoggerFactory.getLogger(getClass());
@Resource
WdOrderListService wdOrderListService;
@Override
public WdOrderDTO wdOmsQueryOrderInfoDTO(String aliasOrderNo) {
WdOrderDTO wdOrderDTO = new WdOrderDTO();
wdOrderDTO = wdOrderListService.findOrderList(aliasOrderNo);
return wdOrderDTO;
}
}
| true |
97749db72da786f0c1169e0157a3516bca27f1c2 | Java | yenchaohao/ZA101G1 | /src/com/emp/model/EmpSequenceGenerator.java | UTF-8 | 1,355 | 2.390625 | 2 | [] | no_license | package com.emp.model;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import org.hibernate.HibernateException;
import org.hibernate.engine.SessionImplementor;
import org.hibernate.id.IdentifierGenerator;
public class EmpSequenceGenerator implements IdentifierGenerator{
private static DataSource ds = null;
static {
try {
Context ctx = new InitialContext();
ds = (DataSource) ctx.lookup("java:comp/env/jdbc/G1Local");
} catch (NamingException e) {
e.printStackTrace();
}
}
@Override
public Serializable generate(SessionImplementor session, Object object)
throws HibernateException {
String prefix = "E";
String empid = null;
Connection con;
try {
con = ds.getConnection();
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT ex_emp_seq.NEXTVAL as nextval FROM DUAL");
while(rs.next()){
int nextval = rs.getInt("nextval");
empid = prefix + nextval;
}
con.close();
} catch (SQLException e) {
throw new HibernateException("Unable to generate Sequence");
}
return empid;
}
}
| true |
883f94f74148aca7928291815d27d16995a11789 | Java | Coder-Leon/basic_algorithms | /src/Code_05_SmallSum.java | UTF-8 | 2,770 | 3.359375 | 3 | [] | no_license | import java.util.Arrays;
public class Code_05_SmallSum {
public static int smallSum(int[] arr) {
if (arr == null || arr.length < 2) {
return 0;
}
return mergeSort(arr, 0, arr.length - 1);
}
public static int mergeSort(int[] arr, int left, int right) {
if (left == right) {
return 0;
}
int middle = left + ((right - left) >> 1);
return mergeSort(arr, left, middle) + mergeSort(arr, middle + 1, right)
+ merge(arr, left, middle, right);
}
public static int merge(int[] arr, int left, int middle, int right) {
int[] help = new int[right - left + 1];
int i = 0;
int p1 = left;
int p2 = middle + 1;
int res = 0;
while (p1 <= middle && p2 <= right) {
res += arr[p1] < arr[p2] ? (right - p2 + 1) * arr[p1] : 0; // 计算每次分治后的最小和
help[i++] = arr[p1] < arr[p2] ? arr[p1++] : arr[p2++];
}
while (p1 <= middle) {
help[i++] = arr[p1++];
}
while (p2 <= right) {
help[i++] = arr[p2++];
}
for (i = 0; i < help.length; i++) {
arr[left + i] = help[i];
}
return res;
}
public static void main(String[] args) {
int testTime = 500000;
int maxSize = 50;
int maxValue = 100;
boolean succeed = true;
// test case
for (int i = 0; i < testTime; i++) {
int[] arr1 = generateRandomArray(maxSize, maxValue);
int[] arr2 = Arrays.copyOf(arr1, arr1.length);
if (smallSum(arr1) != comparator(arr2)) {
succeed = false;
System.out.println(Arrays.toString(arr1));
System.out.println(Arrays.toString(arr2));
break;
}
}
System.out.println(succeed ? "Bingo!!!" : "Shit!!!");
int[] arr = generateRandomArray(maxSize, maxValue);
System.out.println(Arrays.toString(arr));
System.out.println(smallSum(arr));
}
// for test
private static int comparator(int[] arr) {
if (arr == null) {
return 0;
}
int res = 0;
for (int i = 1; i < arr.length; i++) {
for (int j = 0; j < i; j++) {
res += arr[j] < arr[i] ? arr[j] : 0;
}
}
return res;
}
// for test
private static int[] generateRandomArray(int maxSize, int maxValue) {
int[] arr = new int[(int) ((maxSize + 1) * Math.random())];
for (int i = 0; i < arr.length; i++) {
arr[i] = (int) ((maxValue + 1) * Math.random()) - (int) (maxValue * Math.random());
}
return arr;
}
}
| true |
eebfb40681d6fb9849dd43bacdf47b34e85f61d0 | Java | noahkoch/Dad-Classifieds-Backup | /Project/Resin/src/com/classified/customer/CreditCard.java | UTF-8 | 20,671 | 2.453125 | 2 | [] | no_license | package com.classified.customer;
import java.util.Vector;
import java.util.HashMap;
import java.util.Iterator;
///import org.apache.turbine.services.db.TurbineDB;
///import org.apache.turbine.util.db.pool.DBConnection;
///import org.apache.turbine.util.TurbineConfig;
import com.classified.exceptions.CustomerActivityException;
import java.sql.*;
import javax.sql.*;
import java.util.ResourceBundle;
///import org.apache.log4j.Category;
import javax.naming.NamingException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingEnumeration;
import javax.naming.directory.InitialDirContext;
import java.text.SimpleDateFormat;
import java.text.ParseException;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Date;
/**
* Holds the credit card information used in the wallet and in recorded
* orders.<P>
*
* Copyright 2002, James M. Turner
* No warranty is made as to the fitness of this code for any
* particular purpose. It is included for demonstration purposes
* only.
*
* @author James M. Turner
*/
public class CreditCard implements Cloneable{
///static Category cat = Category.getInstance(CreditCard.class);
private static ResourceBundle sql_bundle =
ResourceBundle.getBundle("com.classified.customer.SQLQueries");
protected int cardID;
protected Address address;
protected Customer customer;
protected String cardOwner;
protected String cardType;
protected String cardNumber;
protected int expMonth;
protected int expYear;
/**
* Returns the unique Card ID, which is an autoincrementing
* database column used to uniquely identify each credit card record.
*
* @return the card ID
**/
public int getCardID(){
return cardID;
}
/**
* Sets the unique card ID, which is an autoincrementing
* database column used to uniquely identify each card record.
* Note that in normal usage, this should not be used because IDs
* are assigned by the database.
*
* @param id the card ID
**/
public void setCardID(int id){
cardID = id;
}
/**
* Returns the billing address of this card.
*
* @return The address
**/
public Address getAddress(){
return address;
}
/**
* Sets the billing address of this card.
*
* @param addr The address
**/
public void setAddress(Address addr){
address = addr;
}
/**
* Returns the customer associated with this card.
*
* @return The customer
**/
public Customer getCustomer(){
return customer;
}
/**
* Sets the customer associated with this card.
*
* @param cust The customer
**/
public void setCustomer(Customer cust){
customer = cust;
}
/**
* Returns the card owner name of this card.
*
* @return The card owner as a string
**/
public String getCardOwner(){
return cardOwner;
}
/**
* Sets the card owner name of this card.
*
* @param name The card owner as a string
**/
public void setCardOwner(String name) {
cardOwner = name;
}
/**
* Returns the credit card type of this card.<BR>
* Valid values are:
* <LI>VISA
* <LI>MC
* <LI>DISC
* <LI>AMEX
*
* @return The card type as a string
**/
public String getCardType(){
return cardType;
}
/**
* Sets the credit card type of this card.<BR>
* Valid values are:
* <LI>VISA
* <LI>MC
* <LI>DISC
* <LI>AMEX
*
* @param name The card type as a string
**/
public void setCardType(String name) {
cardType = name;
}
/**
* Returns the credit card number of this card.
*
* @return The card number as a string
**/
public String getCardNumber(){
return cardNumber;
}
/**
* Returns the credit card number of this card with all but the
* last four digits obscured with stars.
*
* @return The obscured card number as a string
**/
public String getObscuredNumber(){
if((cardNumber != null) && (cardNumber.length() > 6)){
String digitsOnly = getDigitsOnly(cardNumber);
String allStars = "****************************************";
return digitsOnly.substring(0,2) +
allStars.substring(0, digitsOnly.length() - 6) +
digitsOnly.substring(digitsOnly.length() - 4, digitsOnly.length());
}else{
return "";
}
}
/**
* Sets the credit card number of this card.
*
* @param name The card number
**/
public void setCardNumber(String name){
cardNumber = name;
}
/**
* Returns the credit card expiration month of this card.
*
* @return The card expiration month as an int
**/
public int getExpMonth(){
return expMonth;
}
/**
* Sets the credit card expiration month of this card.
*
* @param month The card expiration month as an int
**/
public void setExpMonth(int month){
expMonth = month;
}
/**
* Returns the credit card expiration year of this card.
*
* @return The card expiration year as an int (4 digit)
**/
public int getExpYear(){
return expYear;
}
/**
* Sets the credit card expiration year of this card.
*
* @param year The card expiration year as an int (4 digit)
**/
public void setExpYear(int year){
expYear = year;
}
private HashMap validationErrors = new HashMap();
/**
* Returns a validation error against a specific field. If a field
* was found to have an error during
* {@link #validateCreditCard validateCreditCard}, the error message
* can be accessed via this method.
*
* @param fieldname The bean property name of the field
* @return The error message for the field or null if none is
* present.
**/
public String getFieldError(String fieldname){
return((String)validationErrors.get(fieldname));
}
/**
* Sets the validation error against a specific field. Used by
* {@link #validateCreditCard validateCreditCard}.
*
* @param fieldname The bean property name of the field
* @param error The error message for the field or null if none is
* present.
**/
public void addFieldError(String fieldname, String error){
validationErrors.put(fieldname, error);
}
/**
* Validates that the expiration date is after today.
*
* @param expMonth The expiration month
* @param expYear The expiration year
* @return <code>true</code> if the date is valid, otherwise
* <code>false</code>
**/
public boolean validateCCDate(int expMonth, int expYear){
SimpleDateFormat formatter = new SimpleDateFormat ("MM/yy");
try{
GregorianCalendar c = new GregorianCalendar();
c.setTime(formatter.parse(expMonth + "/" + expYear));
c.roll(Calendar.MONTH, 1);
c.set(Calendar.DATE, 1);
c.set(Calendar.HOUR, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
Date now = new Date();
return (now.compareTo(c.getTime()) < 0);
}catch (ParseException ex){
System.out.println("CrediCard bean parse exception " + ex);
};
return false;
}
/**
* Returns only the numeric characters from a string.
*
* @param s The string to be stripped of non-numerics
* @return A string composed only of numbers.
**/
private String getDigitsOnly (String s){
StringBuffer digitsOnly = new StringBuffer();
char c;
for (int i = 0; i < s.length (); i++){
c = s.charAt (i);
if (Character.isDigit (c)){
digitsOnly.append(c);
}
}
return digitsOnly.toString ();
}
/**
* Validates the credit card against the standard prefixes and
* checksums for credit card numbers
*
* @param cardNumber The credit card number
* @return <code>true</code> if the number is valid, otherwise
* <code>false</code>
**/
public boolean validateCreditCardNumber (String cardNumber){
String digitsOnly = getDigitsOnly (cardNumber);
int sum = 0;
int digit = 0;
int addend = 0;
boolean timesTwo = false;
int digitLength = digitsOnly.length();
boolean foundcard = false;
// MC
if(digitsOnly.startsWith("51") || digitsOnly.startsWith("52")
|| digitsOnly.startsWith("53") || digitsOnly.startsWith("54")){
if (digitLength != 16) return false;
foundcard = true;
}
// VISA
if (digitsOnly.startsWith("4")){
if ((digitLength != 16) && (digitLength != 13)) return false;
foundcard = true;
}
// AMEX
if(digitsOnly.startsWith("34") || digitsOnly.startsWith("37")){
if (digitLength != 15) return false;
foundcard = true;
}
// DISC
if (digitsOnly.startsWith("6011")){
if (digitLength != 16) return false;
foundcard = true;
}
if (!foundcard) return false;
for (int i = digitsOnly.length () - 1; i >= 0; i--){
digit = Integer.parseInt (digitsOnly.substring (i, i + 1));
if (timesTwo){
addend = digit * 2;
if (addend > 9){
addend -= 9;
}
}else{
addend = digit;
}
sum += addend;
timesTwo = !timesTwo;
}
int modulus = sum % 10;
return modulus == 0;
}
/**
* Validates the credit card against a number of checks including
* missing fields, invalid expiration date and bad checksum on the
* card number.
*
* @return <code>true</code> if the card passes the validation
* checks, otherwise <code>false</code>
**/
public boolean validateCreditCard(){
validationErrors.clear();
boolean valid = true;
if ((cardType == null) || (cardType.length() == 0)){
addFieldError("cardType", "Card Type is required.");
valid = false;
}
if ((cardOwner == null) || (cardOwner.length() == 0)){
addFieldError("cardOwner", "Cardholder Name is required.");
valid = false;
}
if ((cardNumber == null) || (cardNumber.length() == 0)){
addFieldError("cardNumber", "Card Number is required.");
valid = false;
}else{
if(!validateCreditCardNumber(cardNumber)){
addFieldError("cardNumber", "Invalid Card Number");
valid = false;
}
}
if(expMonth == 0){
addFieldError("expMonth", "Expiration Month is required.");
valid = false;
}
if(expYear == 0){
addFieldError("expYear", "Expiration Year is required.");
valid = false;
}
if(!validateCCDate(expMonth, expYear)){
addFieldError("expYear", "Expired Card Date");
valid = false;
}
return valid;
}
/**
* Given an card ID, returns a new card object populated
* from the database, or null if no such card exists.
*
* @param ID The unique ID of the card in the database
* @return A populated CreditCard object, or null if none found.
* @throws CustomeryActivityException Thrown on database errors
**/
public static CreditCard findCreditCard(int cardID)
throws CustomerActivityException{
CreditCard cc = null;
///DBConnection dbConn = null;
/////////////// Start test ///////////////////////
javax.sql.DataSource pool;
Connection dbConnection = null;
try{
System.out.println("Customer.updateCustomer bean: start");
Context env = (Context) new InitialContext().lookup("java:comp/env");
pool = (DataSource) env.lookup("jdbc/Classifieds");
dbConnection = pool.getConnection();
if (pool == null){
System.out.println("Can't get database connection");
throw new CustomerActivityException();
}
//}catch(NamingException e){
// throw new CustomerActivityException(e);
//}
/////////// END TEST
///try{
/// dbConn = TurbineDB.getConnection();
/// if (dbConn == null){
/// cat.error("Can't get database connection");
/// throw new CustomerActivityException();
/// }
PreparedStatement pstmt =
dbConnection.prepareStatement(sql_bundle.getString("creditQuery"));
pstmt.setInt(1, cardID);
ResultSet rs = pstmt.executeQuery();
if(rs.next()){
cc = new CreditCard();
cc.setCardID(rs.getInt("CARD_ID"));
cc.setCardType(rs.getString("CARD_TYPE"));
cc.setCardNumber(rs.getString("CARD_NUMBER"));
cc.setCardOwner(rs.getString("CARD_OWNERNAME"));
cc.setExpMonth(rs.getInt("CARD_EXPMONTH"));
cc.setExpYear(rs.getInt("CARD_EXPYEAR"));
cc.setAddress(Address.findAddress(rs.getInt("ADDRESS_KEY")));
}else{
///cat.error("Couldn't find record for Credit Card");
System.out.println("Couldn't find record for Credit Card");
}
rs.close();
pstmt.close();
} catch (Exception e){
///cat.error("Error during findCreditCard", e);
System.out.println("Error during findCreditCard " + e);
throw new CustomerActivityException();
}finally{
try{
///TurbineDB.releaseConnection(dbConn);
dbConnection.close();
}catch (Exception e){
///cat.error("Error during release connection", e);
System.out.println("Error during release connection " + e);
}
}
System.out.println("Credit card is " + cc + ", card id is " + cc.getCardID());
return cc;
}
/**
* Creates a new card in the database and sets the card ID
* of the object to the newly created record's ID
*
* @throws CustomerActivityException Thrown if there is an error
* inserting the record in the database.
**/
public void createCreditCard() throws CustomerActivityException{
///DBConnection dbConn = null;
///DBConnection dbConn = null;
/////////////// Start test ///////////////////////
javax.sql.DataSource pool;
Connection dbConnection = null;
try{
System.out.println("Customer.updateCustomer bean: start");
Context env = (Context) new InitialContext().lookup("java:comp/env");
pool = (DataSource) env.lookup("jdbc/Classifieds");
dbConnection = pool.getConnection();
if (pool == null){
System.out.println("Can't get database connection");
throw new CustomerActivityException();
}
//}catch(NamingException e){
// throw new CustomerActivityException(e);
//}
/////////// END TEST
///try{
/// dbConn = TurbineDB.getConnection();
/// if (dbConn == null){
// cat.error("Can't get database connection");
/// throw new CustomerActivityException();
/// }
PreparedStatement pstmt =
dbConnection.prepareStatement(sql_bundle.getString("creditInsert"));
pstmt.setInt(1, getCustomer().getCustomerId());
pstmt.setString(2, getCardType());
pstmt.setString(3, getCardNumber());
pstmt.setString(4, getCardOwner());
pstmt.setInt(5, getExpMonth());
pstmt.setInt(6, getExpYear());
pstmt.setInt(7, getAddress().getAddressID());
pstmt.executeUpdate();
pstmt.close();
pstmt = dbConnection.prepareStatement(sql_bundle.getString("addressID"));
ResultSet rs = pstmt.executeQuery();
if(rs.next()){
setCardID( rs.getInt(1));
}else{
///cat.error("Couldn't find record for new Credit Card");
System.out.println("Couldn't find record for new Credit Card");
}
rs.close();
pstmt.close();
}catch(Exception e){
///cat.error("Error during createCreditCard", e);
System.out.println("Error during createCreditCard " + e);
throw new CustomerActivityException();
}finally{
try{
///TurbineDB.releaseConnection(dbConn);
dbConnection.close();
}catch (Exception e){
///cat.error("Error during release connection", e);
System.out.println("Error during release connection " + e);
}
}
}
/**
* Updates an card in the database.
*
* @throws CustomerActivityException Thrown if there is an error
* updating the record in the database.
**/
public void updateCreditCard() throws CustomerActivityException{
///DBConnection dbConn = null;
/////////////// Start test ///////////////////////
javax.sql.DataSource pool;
Connection dbConnection = null;
try{
System.out.println("Customer.updateCustomer bean: start");
Context env = (Context) new InitialContext().lookup("java:comp/env");
pool = (DataSource) env.lookup("jdbc/Classifieds");
dbConnection = pool.getConnection();
if (pool == null){
System.out.println("Can't get database connection");
throw new CustomerActivityException();
}
//}catch(NamingException e){
// throw new CustomerActivityException(e);
//}
/////////// END TEST
///try{
///dbConn = TurbineDB.getConnection();
///if(dbConn == null){
/// cat.error("Can't get database connection");
/// throw new CustomerActivityException();
///}
PreparedStatement pstmt =
dbConnection.prepareStatement(sql_bundle.getString("creditUpdate"));
pstmt.setInt(1, getCustomer().getCustomerId());
pstmt.setString(2, getCardType());
pstmt.setString(3, getCardNumber());
pstmt.setString(4, getCardOwner());
pstmt.setInt(5, getExpMonth());
pstmt.setInt(6, getExpYear());
pstmt.setInt(7, getAddress().getAddressID());
pstmt.setInt(8, getCardID());
pstmt.executeUpdate();
pstmt.close();
}catch(Exception e){
///cat.error("Error during updateCreditCard", e);
System.out.println("Error during updateCreditCard" + e);
throw new CustomerActivityException();
}finally{
try{
///TurbineDB.releaseConnection(dbConn);
dbConnection.close();
}catch (Exception e){
///cat.error("Error during release connection", e);
System.out.println("Error during release connection " + e);
}
}
}
/**
* Deletes an card from the database.
*
* @throws CustomerActivityException Thrown if there is an error
* deleting the record in the database.
**/
public void deleteCreditCard() throws CustomerActivityException{
///DBConnection dbConn = null;
/////////////// Start test ///////////////////////
javax.sql.DataSource pool;
Connection dbConnection = null;
try{
System.out.println("Customer.updateCustomer bean: start");
Context env = (Context) new InitialContext().lookup("java:comp/env");
pool = (DataSource) env.lookup("jdbc/Classifieds");
dbConnection = pool.getConnection();
if (pool == null){
System.out.println("Can't get database connection");
throw new CustomerActivityException();
}
//}catch(NamingException e){
// throw new CustomerActivityException(e);
//}
/////////// END TEST
///try{
/// dbConn = TurbineDB.getConnection();
/// if(dbConn == null){
/// cat.error("Can't get database connection");
/// throw new CustomerActivityException();
/// }
getAddress().deleteAddress();
PreparedStatement pstmt =
dbConnection.prepareStatement(sql_bundle.getString("creditDelete"));
pstmt.setInt(1, getCardID());
pstmt.executeUpdate();
pstmt.close();
}catch(Exception e){
///cat.error("Error during deleteCreditCard", e);
System.out.println("Error during deleteCreditCard" + e);
throw new CustomerActivityException();
}finally{
try{
///TurbineDB.releaseConnection(dbConn);
dbConnection.close();
}catch (Exception e){
///cat.error("Error during release connection", e);
System.out.println("Error during release connection" + e);
}
}
}
/**
* Returns a copy of the CreditCard object
*
* @returns A duplicate of the object
**/
public Object clone() throws java.lang.CloneNotSupportedException{
return super.clone();
}
}
| true |
575fe6dff5de50f29e8e3a3703bd5e17808c4fb3 | Java | koko1313/spring-api-games-database | /src/main/java/uni/fmi/rest/AuthorizationController.java | UTF-8 | 4,324 | 2.296875 | 2 | [] | no_license | package uni.fmi.rest;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpSession;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import uni.fmi.models.RoleModel;
import uni.fmi.models.UserModel;
import uni.fmi.repositories.RoleRepository;
import uni.fmi.repositories.UserRepository;
@CrossOrigin(origins = "*", allowedHeaders = "*", allowCredentials = "true")
@RestController
public class AuthorizationController {
private UserDetailsService userDetailsService;
private UserRepository userRepo;
private RoleRepository roleRepo;
private PasswordEncoder passwordEncoder;
public AuthorizationController(UserDetailsService userDetailsService, UserRepository userRepo, RoleRepository roleRepo, PasswordEncoder passwordEncoder) {
this.userDetailsService = userDetailsService;
this.userRepo = userRepo;
this.roleRepo = roleRepo;
this.passwordEncoder = passwordEncoder;
}
@PostMapping(path = "/login")
public ResponseEntity<UserModel> login(
@RequestParam(value = "username") String username,
@RequestParam(value = "password") String password) {
UserModel user = userRepo.findByUsername(username);
if(user != null) {
// if the password matches
if(passwordEncoder.matches(password, user.getPassword())) {
UserDetails userDetails = userDetailsService.loadUserByUsername(user.getUsername());
if(userDetails != null) {
Authentication authentication = new UsernamePasswordAuthenticationToken(userDetails.getUsername(), userDetails.getPassword(), userDetails.getAuthorities());
SecurityContextHolder.getContext().setAuthentication(authentication);
}
return new ResponseEntity<>(user, HttpStatus.OK);
}
}
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
@PostMapping(path = "/register")
public ResponseEntity<UserModel> register(
@RequestParam(value = "username") String username,
@RequestParam(value = "password") String password,
@RequestParam(value = "repassword") String repassword) {
// if username or password is null
if(username.equals("") || password.equals("")) {
return new ResponseEntity<>(HttpStatus.NOT_ACCEPTABLE);
}
// if there is already user with this name
if(userRepo.findByUsername(username) != null) {
return new ResponseEntity<>(HttpStatus.CONFLICT);
}
// if both passwords does not match
if(!password.equals(repassword)) {
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
UserModel user = new UserModel();
user.setUsername(username);
user.setPassword(passwordEncoder.encode(password));
// set ROLE_USER
List<RoleModel> roles = new ArrayList<RoleModel>();
RoleModel role = roleRepo.findRoleByName("ROLE_USER");
roles.add(role);
user.setRoles(roles);
user = userRepo.saveAndFlush(user);
if(user != null) {
return new ResponseEntity<>(user, HttpStatus.CREATED);
}
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
@PostMapping(path = "/logout-user")
public boolean logout(HttpSession session) {
session.invalidate();
return true;
}
@GetMapping(path = "/getWhoAmI")
public ResponseEntity<UserModel> getWhoAmI(Authentication authentication) {
// if there is no authenticated user
if(authentication == null) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
String loggedUsername = SecurityContextHolder.getContext().getAuthentication().getName();
UserModel loggedUser = userRepo.findByUsername(loggedUsername);
return new ResponseEntity<>(loggedUser, HttpStatus.OK);
}
}
| true |
6ed3d6e57220506ac36c01fcaed6418d838ae5a5 | Java | sergey-selivanov/billing | /webui/src/main/java/sssii/billing/ui/VaadinSessionHelper.java | UTF-8 | 2,336 | 2.15625 | 2 | [] | no_license | package sssii.billing.ui;
import com.vaadin.server.VaadinSession;
import sssii.billing.common.Constants;
import sssii.billing.common.entity.rs.Settings;
import sssii.billing.common.entity.rs.User;
import sssii.billing.common.security.AuthenticationTokenDetails;
import sssii.billing.ui.entity.InvoiceDraft;
public abstract class VaadinSessionHelper {
public static void newInvoiceDraft() {
VaadinSession.getCurrent().setAttribute(InvoiceDraft.class, new InvoiceDraft());
}
public static InvoiceDraft getInvoiceDraft() {
InvoiceDraft i = VaadinSession.getCurrent().getAttribute(InvoiceDraft.class);
if(i == null) {
i = new InvoiceDraft();
VaadinSession.getCurrent().setAttribute(InvoiceDraft.class, i);
}
return i;
}
public static void putSettings(Settings s) {
VaadinSession.getCurrent().setAttribute(Settings.class, s);
}
public static Settings getSettings() {
return VaadinSession.getCurrent().getAttribute(Settings.class);
}
public static User getUser() {
return VaadinSession.getCurrent().getAttribute(User.class);
}
public static void putUser(User u) {
VaadinSession.getCurrent().setAttribute(User.class, u);
}
public static void setAttr(String name, Object value) {
VaadinSession.getCurrent().setAttribute(name, value);
}
public static Object getAttr(String name) {
return VaadinSession.getCurrent().getAttribute(name);
}
public static void setString(String name, String value) {
VaadinSession.getCurrent().setAttribute(name, value);
}
public static String getString(String name) {
return (String)VaadinSession.getCurrent().getAttribute(name);
}
public static String getTokenHeader() {
return "Bearer " + (String)VaadinSession.getCurrent().getAttribute(Constants.SESSION_TOKEN);
}
public static void putTokenDetails(AuthenticationTokenDetails details) {
VaadinSession.getCurrent().setAttribute(AuthenticationTokenDetails.class, details);
}
public static AuthenticationTokenDetails getTokenDetails() {
return VaadinSession.getCurrent().getAttribute(AuthenticationTokenDetails.class);
}
}
| true |
d927c56d0dc3326778f5601c68c33f428fa84746 | Java | FishTechnology/pokkar-api_springboot | /src/main/java/com/us/pokkarapi/services/gameplayer/processors/GamePlayerServiceProcessorMapper.java | UTF-8 | 404 | 1.609375 | 2 | [
"MIT"
] | permissive | /**
*
*/
package com.us.pokkarapi.services.gameplayer.processors;
import com.us.pokkarapi.services.gameplayer.datacontracts.daos.GamePlayerDao;
import com.us.pokkarapi.services.gameplayer.datacontracts.dtos.CreateGamePlayerDto;
/**
* @author sajansoosaimicheal
*
*/
public interface GamePlayerServiceProcessorMapper {
GamePlayerDao mapGamePlayerDao(CreateGamePlayerDto createGamePlayerDto);
}
| true |
7b0e7337fce51cfb9ffa61c868a3120d8f019188 | Java | iamahmedalaa/MY-TAXS | /app/src/main/java/com/elmaghraby/android/ProfitActivity.java | UTF-8 | 3,513 | 2.078125 | 2 | [] | no_license | package com.elmaghraby.android;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
/******************************************************************************
Copyright (c) 2020, Created By Ahmed Alaa Elmaghraby. *
******************************************************************************/
public class ProfitActivity extends BaseActivity {
private TextView individualCTextView;
private TextView companyCTextView;
private static int selectedFragment = 0;
Fragment fragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profit);
setStatusBarGradiant(this, R.color.md_teal_600);
forceLocale(this, "en");
individualCTextView = findViewById(R.id.individual_tv_id);
companyCTextView = findViewById(R.id.company_tv_id);
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_container_fl_id, IndividualFragment.newInstance()).commit();
individualCTextView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (selectedFragment != 1) {
selectedFragment = 1;
individualCTextView.setBackground(getResources().getDrawable(R.color.md_teal_A700));
companyCTextView.setBackground(getResources().getDrawable(R.color.md_teal_600));
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_container_fl_id, IndividualFragment.newInstance()).commit();
}
}
});
companyCTextView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (selectedFragment != 2) {
selectedFragment = 2;
companyCTextView.setBackground(getResources().getDrawable(R.color.md_teal_A700));
individualCTextView.setBackground(getResources().getDrawable(R.color.md_teal_600));
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_container_fl_id, CompanyFragment.newInstance()).commit();
}
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Bundle bundle = new Bundle();
Fragment fragment;
if (requestCode == 1 && resultCode == RESULT_OK) {
bundle.putString("VALUE", data.getExtras().getString("RESPONSE"));
fragment = IndividualFragment.newInstance();
fragment.setArguments(bundle);
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container_fl_id, fragment).commitAllowingStateLoss();
} else if (requestCode == 2 && resultCode == RESULT_OK) {
bundle.putString("VALUE", data.getExtras().getString("RESPONSE"));
fragment = CompanyFragment.newInstance();
fragment.setArguments(bundle);
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container_fl_id, fragment).commitAllowingStateLoss();
}
}
}
| true |
a48ee3e546c05f088a670932bdec0cf0053d225a | Java | pbhupen01/spring_all | /src/main/java/com/practice/spring/dto/ErrorResponse.java | UTF-8 | 957 | 2.421875 | 2 | [] | no_license | package com.practice.spring.dto;
import lombok.Data;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.http.HttpStatus;
import java.text.SimpleDateFormat;
import java.util.Date;
@Data
public class ErrorResponse {
private HttpStatus status;
private String timestamp;
private String message;
private String debugMessage;
public ErrorResponse(HttpStatus status, String message) {
this.status = status;
this.message = message;
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
this.timestamp = formatter.format(new Date());
}
public ErrorResponse(HttpStatus status, String message, Exception ex) {
this(status, message);
this.debugMessage = ExceptionUtils.getStackTrace(ex);
}
public String toString()
{
return String.format("HttpStatus: %s. Error Message: %s", status.toString(), message);
}
}
| true |
6444ef7a5ea3376395548724eacc49fe58c9d4e3 | Java | MatiasGrondona/POO-UNNE-SERIES | /Integrador/GestionBiblioteca.java | UTF-8 | 1,247 | 3.078125 | 3 | [] | no_license |
/**
* Write a description of class GestionBiblioteca here.
*
* @author (your name)
* @version (a version number or a date)
*/
import java.util.*;
public class GestionBiblioteca
{
public static void main(String [] args){
Ventana v1 = new Ventana();
v1.setVisible(true);//hacemos visible la ventana
/*Calendar fechaRetiro = new GregorianCalendar();
Biblioteca biblio1 = new Biblioteca("TayMorgensten");
biblio1.nuevoSocioDocente(12345678, "Fulano", "Sociales");
biblio1.nuevoSocioDocente(87654321, "Mengano", "Naturales");
biblio1.nuevoSocioEstudiante(23456789, "Juancito","LSI");
biblio1.nuevoLibro("Harry Potter",3,"Planeta",2015);
biblio1.nuevoLibro("Narnia", 5, "Nube de tinta",2007);
biblio1.prestarLibro(fechaRetiro, biblio1.getSocios().get(2), biblio1.getLibros().get(0));
biblio1.prestarLibro(fechaRetiro, biblio1.getSocios().get(0), biblio1.getLibros().get(1));
System.out.println("el libro lo tiene: "+biblio1.quienTieneElLibro(biblio1.getLibros().get(0)));
System.out.println(biblio1.listaDeSocios());
System.out.println(biblio1.listaDeLibros());
*/
}
}
| true |