blob_id
stringlengths
40
40
__id__
int64
225
39,780B
directory_id
stringlengths
40
40
path
stringlengths
6
313
content_id
stringlengths
40
40
detected_licenses
list
license_type
stringclasses
2 values
repo_name
stringlengths
6
132
repo_url
stringlengths
25
151
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
70
visit_date
timestamp[ns]
revision_date
timestamp[ns]
committer_date
timestamp[ns]
github_id
int64
7.28k
689M
star_events_count
int64
0
131k
fork_events_count
int64
0
48k
gha_license_id
stringclasses
23 values
gha_fork
bool
2 classes
gha_event_created_at
timestamp[ns]
gha_created_at
timestamp[ns]
gha_updated_at
timestamp[ns]
gha_pushed_at
timestamp[ns]
gha_size
int64
0
40.4M
gha_stargazers_count
int32
0
112k
gha_forks_count
int32
0
39.4k
gha_open_issues_count
int32
0
11k
gha_language
stringlengths
1
21
gha_archived
bool
2 classes
gha_disabled
bool
1 class
content
stringlengths
7
4.37M
src_encoding
stringlengths
3
16
language
stringclasses
1 value
length_bytes
int64
7
4.37M
extension
stringclasses
24 values
filename
stringlengths
4
174
language_id
stringclasses
1 value
entities
list
contaminating_dataset
stringclasses
0 values
malware_signatures
list
redacted_content
stringlengths
7
4.37M
redacted_length_bytes
int64
7
4.37M
alphanum_fraction
float32
0.25
0.94
alpha_fraction
float32
0.25
0.94
num_lines
int32
1
84k
avg_line_length
float32
0.76
99.9
std_line_length
float32
0
220
max_line_length
int32
5
998
is_vendor
bool
2 classes
is_generated
bool
1 class
max_hex_length
int32
0
319
hex_fraction
float32
0
0.38
max_unicode_length
int32
0
408
unicode_fraction
float32
0
0.36
max_base64_length
int32
0
506
base64_fraction
float32
0
0.5
avg_csv_sep_count
float32
0
4
is_autogen_header
bool
1 class
is_empty_html
bool
1 class
shard
stringclasses
16 values
1c7e422b4f6a55c1255d28d1a7861d7bc82680c5
11,862,699,728,996
6235d3b43a49a6d7fea4344300874e8e6853f020
/src/main/java/com/ss/android/ugc/aweme/shortvideo/mvtemplate/choosemedia/MvImageChooseAdapter.java
6a7ad2e06558164b3bb96cfac28875c893a6a8a0
[]
no_license
junges521/src_awe
https://github.com/junges521/src_awe
a12bcfeb6c62bd55afba7147b83f4e3df8797019
cff4a5e230f3346f493df79744e6f2a6f20a47e2
refs/heads/master
2020-07-13T19:37:36.253000
2019-08-29T10:47:51
2019-08-29T10:47:51
205,140,726
0
0
null
true
2019-08-29T10:41:58
2019-08-29T10:41:58
2019-08-29T08:24:29
2019-08-23T11:31:27
177,015
0
0
0
null
false
false
package com.ss.android.ugc.aweme.shortvideo.mvtemplate.choosemedia; import android.content.Context; import android.graphics.Bitmap; import android.support.v7.widget.RecyclerView; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.TextView; import com.bytedance.common.utility.Lists; import com.bytedance.common.utility.UIUtils; import com.meituan.robust.ChangeQuickRedirect; import com.meituan.robust.PatchProxy; import com.ss.android.ugc.aweme.C0906R; import com.ss.android.ugc.aweme.base.n; import com.ss.android.ugc.aweme.base.ui.RemoteImageView; import com.ss.android.ugc.aweme.mediachoose.w; import com.ss.android.ugc.aweme.property.a; import com.ss.android.ugc.aweme.shortvideo.util.ai; import com.ss.android.ugc.aweme.utils.ax; import com.ss.android.ugc.aweme.utils.co; import com.ss.android.ugc.aweme.utils.e; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Locale; import kotlin.Unit; import org.json.JSONException; import org.json.JSONObject; public class MvImageChooseAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { /* renamed from: a reason: collision with root package name */ public static ChangeQuickRedirect f68565a; /* renamed from: b reason: collision with root package name */ public int f68566b = 12; /* renamed from: c reason: collision with root package name */ public String f68567c; /* renamed from: d reason: collision with root package name */ final Context f68568d; /* renamed from: e reason: collision with root package name */ public List<b> f68569e = new ArrayList(); /* renamed from: f reason: collision with root package name */ public d f68570f; public c g; public boolean h = true; public boolean i; int j; w k; private final List<b> l = new ArrayList(); private int m; private double n; static class ViewHolder extends RecyclerView.ViewHolder { /* renamed from: a reason: collision with root package name */ public static ChangeQuickRedirect f68581a; /* renamed from: b reason: collision with root package name */ RemoteImageView f68582b; /* renamed from: c reason: collision with root package name */ TextView f68583c; /* renamed from: d reason: collision with root package name */ TextView f68584d; /* renamed from: e reason: collision with root package name */ FrameLayout f68585e; /* renamed from: f reason: collision with root package name */ View f68586f; String g; b h; int i; public final void a() { if (PatchProxy.isSupport(new Object[0], this, f68581a, false, 78023, new Class[0], Void.TYPE)) { PatchProxy.accessDispatch(new Object[0], this, f68581a, false, 78023, new Class[0], Void.TYPE); return; } this.f68583c.setText(""); this.f68583c.setBackgroundResource(2130838038); } ViewHolder(View view) { super(view); } } interface a { void a(); } public static class b extends com.ss.android.ugc.aweme.music.b.a.a { /* renamed from: a reason: collision with root package name */ public static ChangeQuickRedirect f68587a; /* renamed from: b reason: collision with root package name */ int f68588b = -1; private b(long j) { super(j); } public static b a(com.ss.android.ugc.aweme.music.b.a.a aVar) { com.ss.android.ugc.aweme.music.b.a.a aVar2 = aVar; if (PatchProxy.isSupport(new Object[]{aVar2}, null, f68587a, true, 78021, new Class[]{com.ss.android.ugc.aweme.music.b.a.a.class}, b.class)) { return (b) PatchProxy.accessDispatch(new Object[]{aVar2}, null, f68587a, true, 78021, new Class[]{com.ss.android.ugc.aweme.music.b.a.a.class}, b.class); } b bVar = new b(aVar2.f56314d); bVar.f56315e = aVar2.f56315e; bVar.f56316f = aVar2.f56316f; bVar.g = aVar2.g; bVar.h = aVar2.h; bVar.i = aVar2.i; bVar.j = aVar2.j; bVar.k = aVar2.k; bVar.l = aVar2.l; bVar.m = aVar2.m; bVar.n = aVar2.n; bVar.o = aVar2.o; return bVar; } } public interface c { void a(com.ss.android.ugc.aweme.music.b.a.a aVar); void a(List<b> list); } public interface d { void a(View view, com.ss.android.ugc.aweme.music.b.a.a aVar); } public long getItemId(int i2) { return (long) i2; } private void a() { if (PatchProxy.isSupport(new Object[0], this, f68565a, false, 78001, new Class[0], Void.TYPE)) { PatchProxy.accessDispatch(new Object[0], this, f68565a, false, 78001, new Class[0], Void.TYPE); return; } for (b bVar : this.l) { bVar.f68588b = -1; } } public int getItemCount() { if (!PatchProxy.isSupport(new Object[0], this, f68565a, false, 78014, new Class[0], Integer.TYPE)) { return this.l.size(); } return ((Integer) PatchProxy.accessDispatch(new Object[0], this, f68565a, false, 78014, new Class[0], Integer.TYPE)).intValue(); } private void a(View view) { if (PatchProxy.isSupport(new Object[]{view}, this, f68565a, false, 78008, new Class[]{View.class}, Void.TYPE)) { PatchProxy.accessDispatch(new Object[]{view}, this, f68565a, false, 78008, new Class[]{View.class}, Void.TYPE); return; } ViewGroup.LayoutParams layoutParams = view.getLayoutParams(); if (!(layoutParams == null || layoutParams.width == this.m)) { int i2 = layoutParams.height; double d2 = (double) this.m; double d3 = this.n; Double.isNaN(d2); if (i2 != ((int) (d2 * d3))) { layoutParams.width = this.m; double d4 = (double) this.m; double d5 = this.n; Double.isNaN(d4); layoutParams.height = (int) (d4 * d5); } } } public final void a(Collection<? extends b> collection) { if (PatchProxy.isSupport(new Object[]{collection}, this, f68565a, false, 78002, new Class[]{Collection.class}, Void.TYPE)) { PatchProxy.accessDispatch(new Object[]{collection}, this, f68565a, false, 78002, new Class[]{Collection.class}, Void.TYPE); return; } this.l.clear(); this.l.addAll(collection); notifyDataSetChanged(); } public final void a(boolean z) { if (PatchProxy.isSupport(new Object[]{Byte.valueOf(z ? (byte) 1 : 0)}, this, f68565a, false, 78000, new Class[]{Boolean.TYPE}, Void.TYPE)) { PatchProxy.accessDispatch(new Object[]{Byte.valueOf(z)}, this, f68565a, false, 78000, new Class[]{Boolean.TYPE}, Void.TYPE); return; } a(); this.h = z; if (!Lists.isEmpty(this.f68569e)) { this.f68569e.clear(); if (this.g != null) { this.g.a(this.f68569e); } } notifyDataSetChanged(); } public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i2) { int i3 = 0; if (PatchProxy.isSupport(new Object[]{viewGroup, Integer.valueOf(i2)}, this, f68565a, false, 78003, new Class[]{ViewGroup.class, Integer.TYPE}, RecyclerView.ViewHolder.class)) { return (RecyclerView.ViewHolder) PatchProxy.accessDispatch(new Object[]{viewGroup, Integer.valueOf(i2)}, this, f68565a, false, 78003, new Class[]{ViewGroup.class, Integer.TYPE}, RecyclerView.ViewHolder.class); } View inflate = LayoutInflater.from(this.f68568d).inflate(C0906R.layout.s2, viewGroup, false); ViewHolder viewHolder = new ViewHolder(inflate); viewHolder.f68582b = (RemoteImageView) inflate.findViewById(C0906R.id.bm8); viewHolder.f68583c = (TextView) inflate.findViewById(C0906R.id.arj); viewHolder.f68585e = (FrameLayout) inflate.findViewById(C0906R.id.afr); viewHolder.f68586f = inflate.findViewById(C0906R.id.cp0); viewHolder.f68584d = (TextView) inflate.findViewById(C0906R.id.a8_); TextView textView = viewHolder.f68584d; if (!this.i) { i3 = 8; } textView.setVisibility(i3); return viewHolder; } public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int i2) { final b bVar; String str; int i3; float f2; float f3; int i4 = i2; if (PatchProxy.isSupport(new Object[]{viewHolder, Integer.valueOf(i2)}, this, f68565a, false, 78004, new Class[]{RecyclerView.ViewHolder.class, Integer.TYPE}, Void.TYPE)) { PatchProxy.accessDispatch(new Object[]{viewHolder, Integer.valueOf(i2)}, this, f68565a, false, 78004, new Class[]{RecyclerView.ViewHolder.class, Integer.TYPE}, Void.TYPE); return; } final ViewHolder viewHolder2 = (ViewHolder) viewHolder; if (PatchProxy.isSupport(new Object[]{viewHolder2, Integer.valueOf(i2)}, this, f68565a, false, 78005, new Class[]{ViewHolder.class, Integer.TYPE}, Void.TYPE)) { PatchProxy.accessDispatch(new Object[]{viewHolder2, Integer.valueOf(i2)}, this, f68565a, false, 78005, new Class[]{ViewHolder.class, Integer.TYPE}, Void.TYPE); return; } a((View) viewHolder2.f68582b); a(viewHolder2.f68586f); b bVar2 = this.l.get(i4); if (bVar2 == null) { ai.b("mediaModel is empty " + i4 + " cur type: " + this.j + " " + this.l.size()); } viewHolder2.h = bVar2; viewHolder2.i = i4; if (PatchProxy.isSupport(new Object[]{viewHolder2}, this, f68565a, false, 78007, new Class[]{ViewHolder.class}, Void.TYPE)) { PatchProxy.accessDispatch(new Object[]{viewHolder2}, this, f68565a, false, 78007, new Class[]{ViewHolder.class}, Void.TYPE); bVar = bVar2; } else { FrameLayout frameLayout = viewHolder2.f68585e; if (this.h) { i3 = 0; } else { i3 = 8; } frameLayout.setVisibility(i3); if (viewHolder2.h.f68588b >= 0) { viewHolder2.f68586f.setVisibility(0); int i5 = viewHolder2.h.f68588b; bVar = bVar2; if (PatchProxy.isSupport(new Object[]{Integer.valueOf(i5)}, viewHolder2, ViewHolder.f68581a, false, 78022, new Class[]{Integer.TYPE}, Void.TYPE)) { PatchProxy.accessDispatch(new Object[]{Integer.valueOf(i5)}, viewHolder2, ViewHolder.f68581a, false, 78022, new Class[]{Integer.TYPE}, Void.TYPE); } else { viewHolder2.f68583c.setText(String.valueOf(i5)); viewHolder2.f68583c.setBackgroundResource(2130838039); } f3 = 1.0f; f2 = 1.1f; } else { bVar = bVar2; viewHolder2.a(); viewHolder2.f68586f.setVisibility(4); if (this.f68569e.size() >= this.f68566b) { f3 = 0.5f; } else { f3 = 1.0f; } f2 = 1.0f; } if (viewHolder2.f68582b.getAlpha() != f3) { viewHolder2.f68582b.setAlpha(f3); } if (viewHolder2.f68582b.getScaleX() != f2) { viewHolder2.f68582b.setScaleX(f2); viewHolder2.f68582b.setScaleY(f2); } } String str2 = "file://" + bVar.f56315e; if (!TextUtils.equals(viewHolder2.g, str2)) { viewHolder2.g = str2; com.ss.android.ugc.aweme.base.c.a(viewHolder2.f68582b, viewHolder2.g, this.m, this.m, Bitmap.Config.ARGB_4444); } viewHolder2.itemView.setOnClickListener(new ax() { /* renamed from: a reason: collision with root package name */ public static ChangeQuickRedirect f68571a; public final void a(View view) { boolean z = true; if (PatchProxy.isSupport(new Object[]{view}, this, f68571a, false, 78018, new Class[]{View.class}, Void.TYPE)) { PatchProxy.accessDispatch(new Object[]{view}, this, f68571a, false, 78018, new Class[]{View.class}, Void.TYPE); return; } if (viewHolder2.h.f68588b >= 0 || MvImageChooseAdapter.this.f68569e.size() < MvImageChooseAdapter.this.f68566b) { z = false; } if (!z && MvImageChooseAdapter.this.f68570f != null) { MvImageChooseAdapter.this.f68570f.a(view, bVar); } } }); viewHolder2.f68585e.setOnClickListener(new ax() { /* renamed from: a reason: collision with root package name */ public static ChangeQuickRedirect f68575a; public final void a(View view) { if (PatchProxy.isSupport(new Object[]{view}, this, f68575a, false, 78019, new Class[]{View.class}, Void.TYPE)) { PatchProxy.accessDispatch(new Object[]{view}, this, f68575a, false, 78019, new Class[]{View.class}, Void.TYPE); return; } MvImageChooseAdapter mvImageChooseAdapter = MvImageChooseAdapter.this; ViewHolder viewHolder = viewHolder2; if (PatchProxy.isSupport(new Object[]{viewHolder}, mvImageChooseAdapter, MvImageChooseAdapter.f68565a, false, 78009, new Class[]{ViewHolder.class}, Void.TYPE)) { PatchProxy.accessDispatch(new Object[]{viewHolder}, mvImageChooseAdapter, MvImageChooseAdapter.f68565a, false, 78009, new Class[]{ViewHolder.class}, Void.TYPE); } else if (viewHolder.h.f68588b >= 0) { int i = viewHolder.h.f68588b; viewHolder.h.f68588b = -1; viewHolder.a(); viewHolder.f68586f.animate().alpha(0.0f).setDuration(3000).withEndAction(new Runnable(viewHolder) { /* renamed from: a reason: collision with root package name */ public static ChangeQuickRedirect f68578a; /* renamed from: b reason: collision with root package name */ final /* synthetic */ ViewHolder f68579b; public final void run() { if (PatchProxy.isSupport(new Object[0], this, f68578a, false, 78020, new Class[0], Void.TYPE)) { PatchProxy.accessDispatch(new Object[0], this, f68578a, false, 78020, new Class[0], Void.TYPE); return; } this.f68579b.f68586f.setVisibility(4); this.f68579b.f68586f.setAlpha(1.0f); MvImageChooseAdapter.this.notifyItemChanged(this.f68579b.i); } { this.f68579b = r2; } }).start(); viewHolder.f68582b.animate().scaleY(1.0f).scaleX(1.0f).setDuration(300).start(); int i2 = 0; for (int i3 = 0; i3 < mvImageChooseAdapter.f68569e.size(); i3++) { b bVar = mvImageChooseAdapter.f68569e.get(i3); if (bVar.f56314d == viewHolder.h.f56314d) { i2 = i3; } if (bVar.f68588b > i) { bVar.f68588b--; } } mvImageChooseAdapter.f68569e.remove(i2); mvImageChooseAdapter.notifyDataSetChanged(); if (mvImageChooseAdapter.g != null) { mvImageChooseAdapter.g.a(mvImageChooseAdapter.f68569e); } } else if (mvImageChooseAdapter.f68569e.size() >= mvImageChooseAdapter.f68566b) { com.bytedance.ies.dmt.ui.d.a.b(mvImageChooseAdapter.f68568d, mvImageChooseAdapter.f68567c).a(); } else { b bVar2 = viewHolder.h; r rVar = new r(mvImageChooseAdapter, viewHolder); if (PatchProxy.isSupport(new Object[]{bVar2, rVar}, mvImageChooseAdapter, MvImageChooseAdapter.f68565a, false, 78010, new Class[]{com.ss.android.ugc.aweme.music.b.a.a.class, a.class}, Void.TYPE)) { PatchProxy.accessDispatch(new Object[]{bVar2, rVar}, mvImageChooseAdapter, MvImageChooseAdapter.f68565a, false, 78010, new Class[]{com.ss.android.ugc.aweme.music.b.a.a.class, a.class}, Void.TYPE); return; } if (1 == mvImageChooseAdapter.j) { if (PatchProxy.isSupport(new Object[]{bVar2, rVar}, mvImageChooseAdapter, MvImageChooseAdapter.f68565a, false, 78012, new Class[]{com.ss.android.ugc.aweme.music.b.a.a.class, a.class}, Void.TYPE)) { PatchProxy.accessDispatch(new Object[]{bVar2, rVar}, mvImageChooseAdapter, MvImageChooseAdapter.f68565a, false, 78012, new Class[]{com.ss.android.ugc.aweme.music.b.a.a.class, a.class}, Void.TYPE); } else { if (mvImageChooseAdapter.k == null) { if (com.ss.android.ugc.aweme.port.in.a.M.a(a.C0682a.VideoLegalCheckInLocal)) { mvImageChooseAdapter.k = new com.ss.android.ugc.aweme.mediachoose.d(mvImageChooseAdapter.f68568d); } else { mvImageChooseAdapter.k = new com.ss.android.ugc.aweme.mediachoose.a(mvImageChooseAdapter.f68568d); } mvImageChooseAdapter.k.a("enter_from_multi"); } mvImageChooseAdapter.k.a(bVar2, 0, -1, new s(mvImageChooseAdapter, rVar), new t(mvImageChooseAdapter)); } } else { if (PatchProxy.isSupport(new Object[]{bVar2, rVar}, mvImageChooseAdapter, MvImageChooseAdapter.f68565a, false, 78011, new Class[]{com.ss.android.ugc.aweme.music.b.a.a.class, a.class}, Void.TYPE)) { PatchProxy.accessDispatch(new Object[]{bVar2, rVar}, mvImageChooseAdapter, MvImageChooseAdapter.f68565a, false, 78011, new Class[]{com.ss.android.ugc.aweme.music.b.a.a.class, a.class}, Void.TYPE); return; } double d2 = (double) bVar2.l; double d3 = (double) bVar2.m; Double.isNaN(d3); if (d2 <= d3 * 2.2d) { double d4 = (double) bVar2.m; double d5 = (double) bVar2.l; Double.isNaN(d5); if (d4 <= d5 * 2.2d) { e.a().a(bVar2.f56315e, co.IMAGE); rVar.a(); } } com.bytedance.ies.dmt.ui.d.a.c(mvImageChooseAdapter.f68568d, (int) C0906R.string.c6q).a(); } } } }); if (bVar.g == 4) { int round = Math.round((((float) bVar.h) * 1.0f) / 1000.0f); TextView textView = viewHolder2.f68584d; if (PatchProxy.isSupport(new Object[]{Integer.valueOf(round)}, this, f68565a, false, 78006, new Class[]{Integer.TYPE}, String.class)) { str = (String) PatchProxy.accessDispatch(new Object[]{Integer.valueOf(round)}, this, f68565a, false, 78006, new Class[]{Integer.TYPE}, String.class); } else { int i6 = round % 60; int i7 = round / 60; int i8 = i7 / 60; int i9 = i7 % 60; if (i8 == 0) { str = String.format(Locale.CHINA, "%02d:%02d", new Object[]{Integer.valueOf(i9), Integer.valueOf(i6)}); } else { str = String.format(Locale.CHINA, "%02d:%02d:%02d", new Object[]{Integer.valueOf(i8), Integer.valueOf(i9), Integer.valueOf(i6)}); } } textView.setText(str); } } /* access modifiers changed from: package-private */ public final /* synthetic */ Unit a(a aVar, String str, Long l2) { a(str, 0, l2.longValue(), "select"); aVar.a(); return null; } /* access modifiers changed from: package-private */ public final /* synthetic */ Unit a(String str, Long l2, Integer num) { a(str, 1, l2.longValue(), "select"); n.a("aweme_movie_import_error_rate", 1, com.ss.android.ugc.aweme.app.d.c.a().a("errorCode", String.valueOf(num)).b()); d.a(this.f68568d, num.intValue(), -1); return null; } private void a(String str, int i2, long j2, String str2) { String str3 = str; long j3 = j2; String str4 = str2; if (PatchProxy.isSupport(new Object[]{str3, Integer.valueOf(i2), new Long(j3), str4}, this, f68565a, false, 78013, new Class[]{String.class, Integer.TYPE, Long.TYPE, String.class}, Void.TYPE)) { Object[] objArr = {str3, Integer.valueOf(i2), new Long(j3), str4}; Object[] objArr2 = objArr; PatchProxy.accessDispatch(objArr2, this, f68565a, false, 78013, new Class[]{String.class, Integer.TYPE, Long.TYPE, String.class}, Void.TYPE); return; } try { JSONObject jSONObject = new JSONObject(); jSONObject.put("duration", (int) j3); n.a("aweme_video_import_duration", jSONObject, com.ss.android.ugc.aweme.app.d.c.a().a("status", String.valueOf(i2)).a("scene_name", str4).a("type", str3).b()); } catch (JSONException unused) { } } public MvImageChooseAdapter(Context context, int i2, double d2, float f2, int i3, int i4) { this.f68568d = context; this.n = 1.0d; context.getResources().getDimensionPixelOffset(C0906R.dimen.ij); this.m = ((UIUtils.getScreenWidth(context) - (((int) UIUtils.dip2Px(this.f68568d, 1.5f)) * 3)) + 0) / 4; this.f68567c = this.f68568d.getString(C0906R.string.sr); this.j = i4; } }
UTF-8
Java
22,925
java
MvImageChooseAdapter.java
Java
[]
null
[]
package com.ss.android.ugc.aweme.shortvideo.mvtemplate.choosemedia; import android.content.Context; import android.graphics.Bitmap; import android.support.v7.widget.RecyclerView; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.TextView; import com.bytedance.common.utility.Lists; import com.bytedance.common.utility.UIUtils; import com.meituan.robust.ChangeQuickRedirect; import com.meituan.robust.PatchProxy; import com.ss.android.ugc.aweme.C0906R; import com.ss.android.ugc.aweme.base.n; import com.ss.android.ugc.aweme.base.ui.RemoteImageView; import com.ss.android.ugc.aweme.mediachoose.w; import com.ss.android.ugc.aweme.property.a; import com.ss.android.ugc.aweme.shortvideo.util.ai; import com.ss.android.ugc.aweme.utils.ax; import com.ss.android.ugc.aweme.utils.co; import com.ss.android.ugc.aweme.utils.e; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Locale; import kotlin.Unit; import org.json.JSONException; import org.json.JSONObject; public class MvImageChooseAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { /* renamed from: a reason: collision with root package name */ public static ChangeQuickRedirect f68565a; /* renamed from: b reason: collision with root package name */ public int f68566b = 12; /* renamed from: c reason: collision with root package name */ public String f68567c; /* renamed from: d reason: collision with root package name */ final Context f68568d; /* renamed from: e reason: collision with root package name */ public List<b> f68569e = new ArrayList(); /* renamed from: f reason: collision with root package name */ public d f68570f; public c g; public boolean h = true; public boolean i; int j; w k; private final List<b> l = new ArrayList(); private int m; private double n; static class ViewHolder extends RecyclerView.ViewHolder { /* renamed from: a reason: collision with root package name */ public static ChangeQuickRedirect f68581a; /* renamed from: b reason: collision with root package name */ RemoteImageView f68582b; /* renamed from: c reason: collision with root package name */ TextView f68583c; /* renamed from: d reason: collision with root package name */ TextView f68584d; /* renamed from: e reason: collision with root package name */ FrameLayout f68585e; /* renamed from: f reason: collision with root package name */ View f68586f; String g; b h; int i; public final void a() { if (PatchProxy.isSupport(new Object[0], this, f68581a, false, 78023, new Class[0], Void.TYPE)) { PatchProxy.accessDispatch(new Object[0], this, f68581a, false, 78023, new Class[0], Void.TYPE); return; } this.f68583c.setText(""); this.f68583c.setBackgroundResource(2130838038); } ViewHolder(View view) { super(view); } } interface a { void a(); } public static class b extends com.ss.android.ugc.aweme.music.b.a.a { /* renamed from: a reason: collision with root package name */ public static ChangeQuickRedirect f68587a; /* renamed from: b reason: collision with root package name */ int f68588b = -1; private b(long j) { super(j); } public static b a(com.ss.android.ugc.aweme.music.b.a.a aVar) { com.ss.android.ugc.aweme.music.b.a.a aVar2 = aVar; if (PatchProxy.isSupport(new Object[]{aVar2}, null, f68587a, true, 78021, new Class[]{com.ss.android.ugc.aweme.music.b.a.a.class}, b.class)) { return (b) PatchProxy.accessDispatch(new Object[]{aVar2}, null, f68587a, true, 78021, new Class[]{com.ss.android.ugc.aweme.music.b.a.a.class}, b.class); } b bVar = new b(aVar2.f56314d); bVar.f56315e = aVar2.f56315e; bVar.f56316f = aVar2.f56316f; bVar.g = aVar2.g; bVar.h = aVar2.h; bVar.i = aVar2.i; bVar.j = aVar2.j; bVar.k = aVar2.k; bVar.l = aVar2.l; bVar.m = aVar2.m; bVar.n = aVar2.n; bVar.o = aVar2.o; return bVar; } } public interface c { void a(com.ss.android.ugc.aweme.music.b.a.a aVar); void a(List<b> list); } public interface d { void a(View view, com.ss.android.ugc.aweme.music.b.a.a aVar); } public long getItemId(int i2) { return (long) i2; } private void a() { if (PatchProxy.isSupport(new Object[0], this, f68565a, false, 78001, new Class[0], Void.TYPE)) { PatchProxy.accessDispatch(new Object[0], this, f68565a, false, 78001, new Class[0], Void.TYPE); return; } for (b bVar : this.l) { bVar.f68588b = -1; } } public int getItemCount() { if (!PatchProxy.isSupport(new Object[0], this, f68565a, false, 78014, new Class[0], Integer.TYPE)) { return this.l.size(); } return ((Integer) PatchProxy.accessDispatch(new Object[0], this, f68565a, false, 78014, new Class[0], Integer.TYPE)).intValue(); } private void a(View view) { if (PatchProxy.isSupport(new Object[]{view}, this, f68565a, false, 78008, new Class[]{View.class}, Void.TYPE)) { PatchProxy.accessDispatch(new Object[]{view}, this, f68565a, false, 78008, new Class[]{View.class}, Void.TYPE); return; } ViewGroup.LayoutParams layoutParams = view.getLayoutParams(); if (!(layoutParams == null || layoutParams.width == this.m)) { int i2 = layoutParams.height; double d2 = (double) this.m; double d3 = this.n; Double.isNaN(d2); if (i2 != ((int) (d2 * d3))) { layoutParams.width = this.m; double d4 = (double) this.m; double d5 = this.n; Double.isNaN(d4); layoutParams.height = (int) (d4 * d5); } } } public final void a(Collection<? extends b> collection) { if (PatchProxy.isSupport(new Object[]{collection}, this, f68565a, false, 78002, new Class[]{Collection.class}, Void.TYPE)) { PatchProxy.accessDispatch(new Object[]{collection}, this, f68565a, false, 78002, new Class[]{Collection.class}, Void.TYPE); return; } this.l.clear(); this.l.addAll(collection); notifyDataSetChanged(); } public final void a(boolean z) { if (PatchProxy.isSupport(new Object[]{Byte.valueOf(z ? (byte) 1 : 0)}, this, f68565a, false, 78000, new Class[]{Boolean.TYPE}, Void.TYPE)) { PatchProxy.accessDispatch(new Object[]{Byte.valueOf(z)}, this, f68565a, false, 78000, new Class[]{Boolean.TYPE}, Void.TYPE); return; } a(); this.h = z; if (!Lists.isEmpty(this.f68569e)) { this.f68569e.clear(); if (this.g != null) { this.g.a(this.f68569e); } } notifyDataSetChanged(); } public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i2) { int i3 = 0; if (PatchProxy.isSupport(new Object[]{viewGroup, Integer.valueOf(i2)}, this, f68565a, false, 78003, new Class[]{ViewGroup.class, Integer.TYPE}, RecyclerView.ViewHolder.class)) { return (RecyclerView.ViewHolder) PatchProxy.accessDispatch(new Object[]{viewGroup, Integer.valueOf(i2)}, this, f68565a, false, 78003, new Class[]{ViewGroup.class, Integer.TYPE}, RecyclerView.ViewHolder.class); } View inflate = LayoutInflater.from(this.f68568d).inflate(C0906R.layout.s2, viewGroup, false); ViewHolder viewHolder = new ViewHolder(inflate); viewHolder.f68582b = (RemoteImageView) inflate.findViewById(C0906R.id.bm8); viewHolder.f68583c = (TextView) inflate.findViewById(C0906R.id.arj); viewHolder.f68585e = (FrameLayout) inflate.findViewById(C0906R.id.afr); viewHolder.f68586f = inflate.findViewById(C0906R.id.cp0); viewHolder.f68584d = (TextView) inflate.findViewById(C0906R.id.a8_); TextView textView = viewHolder.f68584d; if (!this.i) { i3 = 8; } textView.setVisibility(i3); return viewHolder; } public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int i2) { final b bVar; String str; int i3; float f2; float f3; int i4 = i2; if (PatchProxy.isSupport(new Object[]{viewHolder, Integer.valueOf(i2)}, this, f68565a, false, 78004, new Class[]{RecyclerView.ViewHolder.class, Integer.TYPE}, Void.TYPE)) { PatchProxy.accessDispatch(new Object[]{viewHolder, Integer.valueOf(i2)}, this, f68565a, false, 78004, new Class[]{RecyclerView.ViewHolder.class, Integer.TYPE}, Void.TYPE); return; } final ViewHolder viewHolder2 = (ViewHolder) viewHolder; if (PatchProxy.isSupport(new Object[]{viewHolder2, Integer.valueOf(i2)}, this, f68565a, false, 78005, new Class[]{ViewHolder.class, Integer.TYPE}, Void.TYPE)) { PatchProxy.accessDispatch(new Object[]{viewHolder2, Integer.valueOf(i2)}, this, f68565a, false, 78005, new Class[]{ViewHolder.class, Integer.TYPE}, Void.TYPE); return; } a((View) viewHolder2.f68582b); a(viewHolder2.f68586f); b bVar2 = this.l.get(i4); if (bVar2 == null) { ai.b("mediaModel is empty " + i4 + " cur type: " + this.j + " " + this.l.size()); } viewHolder2.h = bVar2; viewHolder2.i = i4; if (PatchProxy.isSupport(new Object[]{viewHolder2}, this, f68565a, false, 78007, new Class[]{ViewHolder.class}, Void.TYPE)) { PatchProxy.accessDispatch(new Object[]{viewHolder2}, this, f68565a, false, 78007, new Class[]{ViewHolder.class}, Void.TYPE); bVar = bVar2; } else { FrameLayout frameLayout = viewHolder2.f68585e; if (this.h) { i3 = 0; } else { i3 = 8; } frameLayout.setVisibility(i3); if (viewHolder2.h.f68588b >= 0) { viewHolder2.f68586f.setVisibility(0); int i5 = viewHolder2.h.f68588b; bVar = bVar2; if (PatchProxy.isSupport(new Object[]{Integer.valueOf(i5)}, viewHolder2, ViewHolder.f68581a, false, 78022, new Class[]{Integer.TYPE}, Void.TYPE)) { PatchProxy.accessDispatch(new Object[]{Integer.valueOf(i5)}, viewHolder2, ViewHolder.f68581a, false, 78022, new Class[]{Integer.TYPE}, Void.TYPE); } else { viewHolder2.f68583c.setText(String.valueOf(i5)); viewHolder2.f68583c.setBackgroundResource(2130838039); } f3 = 1.0f; f2 = 1.1f; } else { bVar = bVar2; viewHolder2.a(); viewHolder2.f68586f.setVisibility(4); if (this.f68569e.size() >= this.f68566b) { f3 = 0.5f; } else { f3 = 1.0f; } f2 = 1.0f; } if (viewHolder2.f68582b.getAlpha() != f3) { viewHolder2.f68582b.setAlpha(f3); } if (viewHolder2.f68582b.getScaleX() != f2) { viewHolder2.f68582b.setScaleX(f2); viewHolder2.f68582b.setScaleY(f2); } } String str2 = "file://" + bVar.f56315e; if (!TextUtils.equals(viewHolder2.g, str2)) { viewHolder2.g = str2; com.ss.android.ugc.aweme.base.c.a(viewHolder2.f68582b, viewHolder2.g, this.m, this.m, Bitmap.Config.ARGB_4444); } viewHolder2.itemView.setOnClickListener(new ax() { /* renamed from: a reason: collision with root package name */ public static ChangeQuickRedirect f68571a; public final void a(View view) { boolean z = true; if (PatchProxy.isSupport(new Object[]{view}, this, f68571a, false, 78018, new Class[]{View.class}, Void.TYPE)) { PatchProxy.accessDispatch(new Object[]{view}, this, f68571a, false, 78018, new Class[]{View.class}, Void.TYPE); return; } if (viewHolder2.h.f68588b >= 0 || MvImageChooseAdapter.this.f68569e.size() < MvImageChooseAdapter.this.f68566b) { z = false; } if (!z && MvImageChooseAdapter.this.f68570f != null) { MvImageChooseAdapter.this.f68570f.a(view, bVar); } } }); viewHolder2.f68585e.setOnClickListener(new ax() { /* renamed from: a reason: collision with root package name */ public static ChangeQuickRedirect f68575a; public final void a(View view) { if (PatchProxy.isSupport(new Object[]{view}, this, f68575a, false, 78019, new Class[]{View.class}, Void.TYPE)) { PatchProxy.accessDispatch(new Object[]{view}, this, f68575a, false, 78019, new Class[]{View.class}, Void.TYPE); return; } MvImageChooseAdapter mvImageChooseAdapter = MvImageChooseAdapter.this; ViewHolder viewHolder = viewHolder2; if (PatchProxy.isSupport(new Object[]{viewHolder}, mvImageChooseAdapter, MvImageChooseAdapter.f68565a, false, 78009, new Class[]{ViewHolder.class}, Void.TYPE)) { PatchProxy.accessDispatch(new Object[]{viewHolder}, mvImageChooseAdapter, MvImageChooseAdapter.f68565a, false, 78009, new Class[]{ViewHolder.class}, Void.TYPE); } else if (viewHolder.h.f68588b >= 0) { int i = viewHolder.h.f68588b; viewHolder.h.f68588b = -1; viewHolder.a(); viewHolder.f68586f.animate().alpha(0.0f).setDuration(3000).withEndAction(new Runnable(viewHolder) { /* renamed from: a reason: collision with root package name */ public static ChangeQuickRedirect f68578a; /* renamed from: b reason: collision with root package name */ final /* synthetic */ ViewHolder f68579b; public final void run() { if (PatchProxy.isSupport(new Object[0], this, f68578a, false, 78020, new Class[0], Void.TYPE)) { PatchProxy.accessDispatch(new Object[0], this, f68578a, false, 78020, new Class[0], Void.TYPE); return; } this.f68579b.f68586f.setVisibility(4); this.f68579b.f68586f.setAlpha(1.0f); MvImageChooseAdapter.this.notifyItemChanged(this.f68579b.i); } { this.f68579b = r2; } }).start(); viewHolder.f68582b.animate().scaleY(1.0f).scaleX(1.0f).setDuration(300).start(); int i2 = 0; for (int i3 = 0; i3 < mvImageChooseAdapter.f68569e.size(); i3++) { b bVar = mvImageChooseAdapter.f68569e.get(i3); if (bVar.f56314d == viewHolder.h.f56314d) { i2 = i3; } if (bVar.f68588b > i) { bVar.f68588b--; } } mvImageChooseAdapter.f68569e.remove(i2); mvImageChooseAdapter.notifyDataSetChanged(); if (mvImageChooseAdapter.g != null) { mvImageChooseAdapter.g.a(mvImageChooseAdapter.f68569e); } } else if (mvImageChooseAdapter.f68569e.size() >= mvImageChooseAdapter.f68566b) { com.bytedance.ies.dmt.ui.d.a.b(mvImageChooseAdapter.f68568d, mvImageChooseAdapter.f68567c).a(); } else { b bVar2 = viewHolder.h; r rVar = new r(mvImageChooseAdapter, viewHolder); if (PatchProxy.isSupport(new Object[]{bVar2, rVar}, mvImageChooseAdapter, MvImageChooseAdapter.f68565a, false, 78010, new Class[]{com.ss.android.ugc.aweme.music.b.a.a.class, a.class}, Void.TYPE)) { PatchProxy.accessDispatch(new Object[]{bVar2, rVar}, mvImageChooseAdapter, MvImageChooseAdapter.f68565a, false, 78010, new Class[]{com.ss.android.ugc.aweme.music.b.a.a.class, a.class}, Void.TYPE); return; } if (1 == mvImageChooseAdapter.j) { if (PatchProxy.isSupport(new Object[]{bVar2, rVar}, mvImageChooseAdapter, MvImageChooseAdapter.f68565a, false, 78012, new Class[]{com.ss.android.ugc.aweme.music.b.a.a.class, a.class}, Void.TYPE)) { PatchProxy.accessDispatch(new Object[]{bVar2, rVar}, mvImageChooseAdapter, MvImageChooseAdapter.f68565a, false, 78012, new Class[]{com.ss.android.ugc.aweme.music.b.a.a.class, a.class}, Void.TYPE); } else { if (mvImageChooseAdapter.k == null) { if (com.ss.android.ugc.aweme.port.in.a.M.a(a.C0682a.VideoLegalCheckInLocal)) { mvImageChooseAdapter.k = new com.ss.android.ugc.aweme.mediachoose.d(mvImageChooseAdapter.f68568d); } else { mvImageChooseAdapter.k = new com.ss.android.ugc.aweme.mediachoose.a(mvImageChooseAdapter.f68568d); } mvImageChooseAdapter.k.a("enter_from_multi"); } mvImageChooseAdapter.k.a(bVar2, 0, -1, new s(mvImageChooseAdapter, rVar), new t(mvImageChooseAdapter)); } } else { if (PatchProxy.isSupport(new Object[]{bVar2, rVar}, mvImageChooseAdapter, MvImageChooseAdapter.f68565a, false, 78011, new Class[]{com.ss.android.ugc.aweme.music.b.a.a.class, a.class}, Void.TYPE)) { PatchProxy.accessDispatch(new Object[]{bVar2, rVar}, mvImageChooseAdapter, MvImageChooseAdapter.f68565a, false, 78011, new Class[]{com.ss.android.ugc.aweme.music.b.a.a.class, a.class}, Void.TYPE); return; } double d2 = (double) bVar2.l; double d3 = (double) bVar2.m; Double.isNaN(d3); if (d2 <= d3 * 2.2d) { double d4 = (double) bVar2.m; double d5 = (double) bVar2.l; Double.isNaN(d5); if (d4 <= d5 * 2.2d) { e.a().a(bVar2.f56315e, co.IMAGE); rVar.a(); } } com.bytedance.ies.dmt.ui.d.a.c(mvImageChooseAdapter.f68568d, (int) C0906R.string.c6q).a(); } } } }); if (bVar.g == 4) { int round = Math.round((((float) bVar.h) * 1.0f) / 1000.0f); TextView textView = viewHolder2.f68584d; if (PatchProxy.isSupport(new Object[]{Integer.valueOf(round)}, this, f68565a, false, 78006, new Class[]{Integer.TYPE}, String.class)) { str = (String) PatchProxy.accessDispatch(new Object[]{Integer.valueOf(round)}, this, f68565a, false, 78006, new Class[]{Integer.TYPE}, String.class); } else { int i6 = round % 60; int i7 = round / 60; int i8 = i7 / 60; int i9 = i7 % 60; if (i8 == 0) { str = String.format(Locale.CHINA, "%02d:%02d", new Object[]{Integer.valueOf(i9), Integer.valueOf(i6)}); } else { str = String.format(Locale.CHINA, "%02d:%02d:%02d", new Object[]{Integer.valueOf(i8), Integer.valueOf(i9), Integer.valueOf(i6)}); } } textView.setText(str); } } /* access modifiers changed from: package-private */ public final /* synthetic */ Unit a(a aVar, String str, Long l2) { a(str, 0, l2.longValue(), "select"); aVar.a(); return null; } /* access modifiers changed from: package-private */ public final /* synthetic */ Unit a(String str, Long l2, Integer num) { a(str, 1, l2.longValue(), "select"); n.a("aweme_movie_import_error_rate", 1, com.ss.android.ugc.aweme.app.d.c.a().a("errorCode", String.valueOf(num)).b()); d.a(this.f68568d, num.intValue(), -1); return null; } private void a(String str, int i2, long j2, String str2) { String str3 = str; long j3 = j2; String str4 = str2; if (PatchProxy.isSupport(new Object[]{str3, Integer.valueOf(i2), new Long(j3), str4}, this, f68565a, false, 78013, new Class[]{String.class, Integer.TYPE, Long.TYPE, String.class}, Void.TYPE)) { Object[] objArr = {str3, Integer.valueOf(i2), new Long(j3), str4}; Object[] objArr2 = objArr; PatchProxy.accessDispatch(objArr2, this, f68565a, false, 78013, new Class[]{String.class, Integer.TYPE, Long.TYPE, String.class}, Void.TYPE); return; } try { JSONObject jSONObject = new JSONObject(); jSONObject.put("duration", (int) j3); n.a("aweme_video_import_duration", jSONObject, com.ss.android.ugc.aweme.app.d.c.a().a("status", String.valueOf(i2)).a("scene_name", str4).a("type", str3).b()); } catch (JSONException unused) { } } public MvImageChooseAdapter(Context context, int i2, double d2, float f2, int i3, int i4) { this.f68568d = context; this.n = 1.0d; context.getResources().getDimensionPixelOffset(C0906R.dimen.ij); this.m = ((UIUtils.getScreenWidth(context) - (((int) UIUtils.dip2Px(this.f68568d, 1.5f)) * 3)) + 0) / 4; this.f68567c = this.f68568d.getString(C0906R.string.sr); this.j = i4; } }
22,925
0.56554
0.511101
485
46.26804
45.192947
224
false
false
0
0
0
0
0
0
1.247423
false
false
13
91cd913be896d99082d18d03b15ca7ec5c957edc
27,350,351,762,397
132105870c2aba29e556177eb3cce9a73a05ba0d
/app/src/main/java/com/app/tools/H264decoder.java
6d954bda67ad84a485b01ea610bbda680a31c654
[]
no_license
wwcob6/LRPHProject
https://github.com/wwcob6/LRPHProject
2551e755218a6365bde00e01668bc1d23ae6882e
96f6ac11f4085e5f2697b9cf5dd67b4bcd1a710e
refs/heads/master
2023-03-20T09:51:07.352000
2021-02-17T08:55:35
2021-02-17T08:55:35
323,892,401
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.app.tools; import android.media.MediaCodec; import android.media.MediaCodecInfo; import android.media.MediaFormat; import android.util.Log; import android.view.Surface; import java.io.IOException; import java.nio.ByteBuffer; /** * Created by asus on 2017/6/16. */ //硬编码 public class H264decoder { private static final String TAG = "H264decoder"; private MediaCodec mCodec; private final static String MIME_TYPE = "video/avc"; // H.264 Advanced Video // private final static int VIDEO_WIDTH = 1280; // private final static int VIDEO_HEIGHT = 720; private final static int VIDEO_WIDTH = 352; private final static int VIDEO_HEIGHT = 288; private final static int TIME_INTERNAL = 10; private final static int HEAD_OFFSET=512; private long BUFFER_TIMEOUT = 0; int mCount = 0; public void initDecoder(Surface surface) { try { mCodec = MediaCodec.createDecoderByType(MIME_TYPE); Log.d("陈工","1"); } catch (IOException e) { e.printStackTrace(); } MediaFormat mediaFormat = MediaFormat.createVideoFormat(MIME_TYPE, VIDEO_WIDTH, VIDEO_HEIGHT); Log.d("陈工","2"); // byte[] header_sps = new byte[]{0x00, 0x00, 0x00, 0x01, 0x67, 0x42, (byte) 0x80, 0x1F, (byte) 0xDA, 0x01, 0x40, 0x16, (byte) 0xE8, (byte) 0x06, (byte) 0xD0, (byte) 0xA1, (byte) 0x35}; // byte[] header_pps = new byte[]{0x00, 0x00, 0x00, 0x01, 0x68, (byte) 0xCE, 0x06, (byte) 0xE2}; mediaFormat.setInteger(MediaFormat.KEY_COLOR_FORMAT, MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420Flexible); Log.d("陈工","3"); // mediaFormat.setByteBuffer("csd-0", ByteBuffer.wrap(header_sps)); // mediaFormat.setByteBuffer("csd-1", ByteBuffer.wrap(header_pps)); mCodec.configure(mediaFormat, surface, null, 0); Log.d("陈工","4"); mCodec.start(); Log.d("陈工","5"); } public boolean onFrame(byte[] buf, int offset, int length) { // Get input buffer index ByteBuffer[] inputBuffers = mCodec.getInputBuffers(); int inputBufferIndex = mCodec.dequeueInputBuffer(-1); // int inputBufferIndex = mCodec.dequeueInputBuffer(BUFFER_TIMEOUT); if (inputBufferIndex >= 0) { ByteBuffer inputBuffer = inputBuffers[inputBufferIndex]; inputBuffer.clear(); inputBuffer.put(buf, offset, length); mCodec.queueInputBuffer(inputBufferIndex, 0, length, mCount * TIME_INTERNAL, 0); mCount++; } else { return false; } // Get output buffer index MediaCodec.BufferInfo bufferInfo = new MediaCodec.BufferInfo(); int outputBufferIndex = mCodec.dequeueOutputBuffer(bufferInfo, 0); // int outputBufferIndex = mCodec.dequeueOutputBuffer(bufferInfo, BUFFER_TIMEOUT); //循环解码,知道数据全部解码完成 while (outputBufferIndex >= 0) { mCodec.releaseOutputBuffer(outputBufferIndex, true); //释放缓冲区的时候需要注意第二个参数设置为true,表示解码显示在Surface上 outputBufferIndex = mCodec.dequeueOutputBuffer(bufferInfo, 0); } Log.e("Media", "onFrame end"); return true; } }
UTF-8
Java
3,348
java
H264decoder.java
Java
[ { "context": "on;\nimport java.nio.ByteBuffer;\n\n/**\n * Created by asus on 2017/6/16.\n */\n//硬编码\npublic class H264decoder ", "end": 262, "score": 0.9993025064468384, "start": 258, "tag": "USERNAME", "value": "asus" }, { "context": "ities.COLOR_FormatYUV420Flexible);\n Log.d(\"陈工\",\"3\");\n// mediaFormat.setByteBuffer(\"csd-0", "end": 1648, "score": 0.929570198059082, "start": 1646, "tag": "NAME", "value": "陈工" }, { "context": "re(mediaFormat, surface, null, 0);\n Log.d(\"陈工\",\"4\");\n mCodec.start();\n Log.d(\"陈工\"", "end": 1880, "score": 0.8994483351707458, "start": 1878, "tag": "NAME", "value": "陈工" }, { "context": "陈工\",\"4\");\n mCodec.start();\n Log.d(\"陈工\",\"5\");\n }\n\n public boolean onFrame(byte[] b", "end": 1929, "score": 0.5821333527565002, "start": 1928, "tag": "NAME", "value": "工" } ]
null
[]
package com.app.tools; import android.media.MediaCodec; import android.media.MediaCodecInfo; import android.media.MediaFormat; import android.util.Log; import android.view.Surface; import java.io.IOException; import java.nio.ByteBuffer; /** * Created by asus on 2017/6/16. */ //硬编码 public class H264decoder { private static final String TAG = "H264decoder"; private MediaCodec mCodec; private final static String MIME_TYPE = "video/avc"; // H.264 Advanced Video // private final static int VIDEO_WIDTH = 1280; // private final static int VIDEO_HEIGHT = 720; private final static int VIDEO_WIDTH = 352; private final static int VIDEO_HEIGHT = 288; private final static int TIME_INTERNAL = 10; private final static int HEAD_OFFSET=512; private long BUFFER_TIMEOUT = 0; int mCount = 0; public void initDecoder(Surface surface) { try { mCodec = MediaCodec.createDecoderByType(MIME_TYPE); Log.d("陈工","1"); } catch (IOException e) { e.printStackTrace(); } MediaFormat mediaFormat = MediaFormat.createVideoFormat(MIME_TYPE, VIDEO_WIDTH, VIDEO_HEIGHT); Log.d("陈工","2"); // byte[] header_sps = new byte[]{0x00, 0x00, 0x00, 0x01, 0x67, 0x42, (byte) 0x80, 0x1F, (byte) 0xDA, 0x01, 0x40, 0x16, (byte) 0xE8, (byte) 0x06, (byte) 0xD0, (byte) 0xA1, (byte) 0x35}; // byte[] header_pps = new byte[]{0x00, 0x00, 0x00, 0x01, 0x68, (byte) 0xCE, 0x06, (byte) 0xE2}; mediaFormat.setInteger(MediaFormat.KEY_COLOR_FORMAT, MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420Flexible); Log.d("陈工","3"); // mediaFormat.setByteBuffer("csd-0", ByteBuffer.wrap(header_sps)); // mediaFormat.setByteBuffer("csd-1", ByteBuffer.wrap(header_pps)); mCodec.configure(mediaFormat, surface, null, 0); Log.d("陈工","4"); mCodec.start(); Log.d("陈工","5"); } public boolean onFrame(byte[] buf, int offset, int length) { // Get input buffer index ByteBuffer[] inputBuffers = mCodec.getInputBuffers(); int inputBufferIndex = mCodec.dequeueInputBuffer(-1); // int inputBufferIndex = mCodec.dequeueInputBuffer(BUFFER_TIMEOUT); if (inputBufferIndex >= 0) { ByteBuffer inputBuffer = inputBuffers[inputBufferIndex]; inputBuffer.clear(); inputBuffer.put(buf, offset, length); mCodec.queueInputBuffer(inputBufferIndex, 0, length, mCount * TIME_INTERNAL, 0); mCount++; } else { return false; } // Get output buffer index MediaCodec.BufferInfo bufferInfo = new MediaCodec.BufferInfo(); int outputBufferIndex = mCodec.dequeueOutputBuffer(bufferInfo, 0); // int outputBufferIndex = mCodec.dequeueOutputBuffer(bufferInfo, BUFFER_TIMEOUT); //循环解码,知道数据全部解码完成 while (outputBufferIndex >= 0) { mCodec.releaseOutputBuffer(outputBufferIndex, true); //释放缓冲区的时候需要注意第二个参数设置为true,表示解码显示在Surface上 outputBufferIndex = mCodec.dequeueOutputBuffer(bufferInfo, 0); } Log.e("Media", "onFrame end"); return true; } }
3,348
0.639456
0.60235
82
38.439026
31.419312
192
false
false
0
0
0
0
0
0
1.207317
false
false
13
1fc3cf67538536f6137f8e7358b94694b40b9c8b
14,096,082,694,569
f3445b41c336431baae1edbaea4e15bbbccf6d3a
/Course_Java/src/day09/shape/Circle.java
9e2026e63a2ba952e4dab7161c396557c12ca95a
[]
no_license
CPUdream/Course_Java
https://github.com/CPUdream/Course_Java
0ea6f1ba1de81c3b8842516d5587fb651efeaac0
bd117096bc62543f8c1a7a717d500114c70ec794
refs/heads/master
2016-09-05T19:21:43.773000
2015-07-16T02:19:27
2015-07-16T02:19:27
39,171,621
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package day09.shape; import day08.Point; public class Circle extends Shape{ Point center; double r; public Circle(int x, int y, double r){ this(new Point(x,y), r); } public Circle(Point center, double r) { this.center = center; this.r = r; } //属于当前对像的方法 public double area(){ return Math.PI * r *r; } public boolean contains(Point p) { return center.distance(p) <= r; } }
UTF-8
Java
415
java
Circle.java
Java
[]
null
[]
package day09.shape; import day08.Point; public class Circle extends Shape{ Point center; double r; public Circle(int x, int y, double r){ this(new Point(x,y), r); } public Circle(Point center, double r) { this.center = center; this.r = r; } //属于当前对像的方法 public double area(){ return Math.PI * r *r; } public boolean contains(Point p) { return center.distance(p) <= r; } }
415
0.65995
0.649874
23
16.26087
13.452711
40
false
false
0
0
0
0
0
0
1.565217
false
false
13
37b8c4cc3fdf483294176c240cc56cd6fc1bb5c0
26,276,609,941,504
a02f307dd4868d95929721372a964dd03afb33c3
/src/main/java/accesoAObjetos/AccesoAAdministrador.java
18378a357830bcf1fbc75453d1f75be55a75d71e
[]
no_license
ErikssonHerlo/HOSPITAL
https://github.com/ErikssonHerlo/HOSPITAL
803c7919c5844a6fa92b930e41cfed4fe630a5a2
93c865db52d46130d675db3f5a64dded1a4f33ef
refs/heads/master
2022-12-27T21:50:55.864000
2020-10-08T20:24:37
2020-10-08T20:24:37
301,024,121
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * 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 accesoAObjetos; import conexionMySQL.Conexion; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import objetos.Administrador; /** * * @author erikssonherlo */ public class AccesoAAdministrador { public boolean insertarNuevoAdministrador(Administrador administrador) { String queryDividido1 = "INSERT INTO Usuario(Codigo, Nombre, DPI, Telefono, Correo, Password, Tipo_Usuario) " + "VALUES(?,?,?,?,?,?,?)"; String queryDividido2 = "INSERT INTO Administrador(Usuario_Codigo, Nombre) " + "VALUES(?,?)"; try { PreparedStatement enviarDividido1 = Conexion.conexion.prepareStatement(queryDividido1); //Envio de los Datos Principales del administrador a la Tabla Usuario enviarDividido1.setString(1, administrador.getCodigo()); enviarDividido1.setString(2, administrador.getNombre()); enviarDividido1.setString(3, administrador.getDPI()); enviarDividido1.setString(4, administrador.getTelefono()); enviarDividido1.setString(5, administrador.getCorreo()); enviarDividido1.setString(6, administrador.getPassword()); enviarDividido1.setInt(7, 1); enviarDividido1.executeUpdate(); //Envia los Datos Complementarios del Administrador a la tabla administrador PreparedStatement enviarDividido2 = Conexion.conexion.prepareStatement(queryDividido2); enviarDividido2.setString(1, administrador.getCodigo()); enviarDividido2.setString(2, administrador.getNombre()); enviarDividido2.executeUpdate(); return true; } catch (SQLException ex) { ex.printStackTrace(System.out); return false; } } /** * VERIFICACION DEL INGRESO ADECUADO DE LOS ADMINISTRADORES A LA BASE DE DATOS * @return */ public boolean verificarEstadoDB(){ Administrador admin = null; ResultSet rs = Conexion.getTabla("SELECT u.Codigo, u.Nombre, u.DPI, u.Telefono, u.Correo, u.Password, u.Tipo_Usuario FROM Usuario u INNER JOIN Administrador a ON a.Usuario_Codigo = u.Codigo"); try { while (rs.next()) { admin = new Administrador(rs.getString("Codigo"), rs.getString("Nombre"),rs.getString("DPI"), rs.getString("Telefono"), rs.getString("Correo"), rs.getString("Password"), rs.getInt("Tipo_Usuario")); } } catch (Exception e) { } if(admin == null) { return false; } else { return true; } } /** * Metodo de Validacion, recibe los parametros desde el formulario, verifica si existe el usuario * y si este existe, verifica que su contraseña sea correcta * @param codigoAdmin * @param password * @return * @throws SQLException */ public Administrador validacionLogin(String codigoAdmin, String password) throws SQLException { Administrador admin = obtenerAdministrador(codigoAdmin); if (admin != null && admin.getPassword().equals(password)) { return admin; } return null; } /** * Obtenemos el Administrador con una busqueda entorno a su codigo * @param codigoAdministrador * @return */ public Administrador obtenerAdministrador(String codigoAdministrador){ Administrador admin = null; try { String query ="SELECT u.Codigo, u.Nombre, u.DPI, u.Telefono, u.Correo, u.Password, u.Tipo_Usuario FROM Usuario u INNER JOIN Administrador a ON a.Usuario_Codigo = u.Codigo WHERE a.Usuario_Codigo = ?"; PreparedStatement enviar = Conexion.conexion.prepareStatement(query); ResultSet rs = null; enviar.setString(1, codigoAdministrador); rs=enviar.executeQuery(); while (rs.next()) { admin = new Administrador(rs.getString("Codigo"), rs.getString("Nombre"),rs.getString("DPI"), rs.getString("Telefono"), rs.getString("Correo"), rs.getString("Password"), rs.getInt("Tipo_Usuario")); } } catch (Exception e) { } return admin; } } /* PreparedStatement preSt = connection.prepareStatement(BUSCAR_USUARIO); preSt.setInt(1, idUsuario); ResultSet result = preSt.executeQuery(); Usuario usuario = null; while (result.next()) { usuario = new Usuario( result.getInt(Usuario.USUARIO_ID_DB_NAME), result.getString(Usuario.NOMBRE_DB_NAME), result.getString(Usuario.PROFESION_DB_NAME), result.getString(Usuario.PASSWORD_DB_NAME) ); } return usuario; */ /* ASI HICE CONSULTAS CON PARAMETROS v private void mostrarTablaBusqueda(String fechaInicioConsulta, String fechaFinalConsulta) throws SQLException { //NITDelCliente = NITCliente; DefaultTableModel model = new DefaultTableModel(); try { String query ="SELECT SUM(Cantidad_Venta),Codigo_Producto,GROUP_CONCAT(DISTINCT v.Fecha) FROM DETALLE_VENTAS d INNER JOIN VENTAS v ON d.Id_Ventas=v.Id_Ventas WHERE v.Fecha BETWEEN ? AND ? GROUP BY Codigo_Producto ORDER BY SUM(Cantidad_Venta) DESC LIMIT 10"; PreparedStatement enviar = Conexion.conexion.prepareStatement(query); ResultSet rs = null; enviar.setString(1, fechaInicioConsulta); enviar.setString(2, fechaFinalConsulta); rs=enviar.executeQuery(); model.setColumnIdentifiers(new Object[]{"Cantidad de Productos Vendidos", "Codigo Producto", "Fecha en la que se Vendieron más Productos"}); while (rs.next()) { model.addRow(new Object[]{rs.getInt("SUM(Cantidad_Venta)"), rs.getString("Codigo_Producto"), rs.getString("GROUP_CONCAT(DISTINCT v.Fecha)")}); } tablePedidos.setModel(model); } catch (SQLException e) { e.printStackTrace(System.out); } } */
UTF-8
Java
6,607
java
AccesoAAdministrador.java
Java
[ { "context": ";\nimport objetos.Administrador;\n\n/**\n *\n * @author erikssonherlo\n */\npublic class AccesoAAdministrador {\n \n ", "end": 423, "score": 0.9991497993469238, "start": 410, "tag": "USERNAME", "value": "erikssonherlo" }, { "context": "ministrador(rs.getString(\"Codigo\"), rs.getString(\"Nombre\"),rs.getString(\"DPI\"), rs.getString(\"Telefono\"), ", "end": 4459, "score": 0.9587267637252808, "start": 4453, "tag": "NAME", "value": "Nombre" } ]
null
[]
/* * 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 accesoAObjetos; import conexionMySQL.Conexion; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import objetos.Administrador; /** * * @author erikssonherlo */ public class AccesoAAdministrador { public boolean insertarNuevoAdministrador(Administrador administrador) { String queryDividido1 = "INSERT INTO Usuario(Codigo, Nombre, DPI, Telefono, Correo, Password, Tipo_Usuario) " + "VALUES(?,?,?,?,?,?,?)"; String queryDividido2 = "INSERT INTO Administrador(Usuario_Codigo, Nombre) " + "VALUES(?,?)"; try { PreparedStatement enviarDividido1 = Conexion.conexion.prepareStatement(queryDividido1); //Envio de los Datos Principales del administrador a la Tabla Usuario enviarDividido1.setString(1, administrador.getCodigo()); enviarDividido1.setString(2, administrador.getNombre()); enviarDividido1.setString(3, administrador.getDPI()); enviarDividido1.setString(4, administrador.getTelefono()); enviarDividido1.setString(5, administrador.getCorreo()); enviarDividido1.setString(6, administrador.getPassword()); enviarDividido1.setInt(7, 1); enviarDividido1.executeUpdate(); //Envia los Datos Complementarios del Administrador a la tabla administrador PreparedStatement enviarDividido2 = Conexion.conexion.prepareStatement(queryDividido2); enviarDividido2.setString(1, administrador.getCodigo()); enviarDividido2.setString(2, administrador.getNombre()); enviarDividido2.executeUpdate(); return true; } catch (SQLException ex) { ex.printStackTrace(System.out); return false; } } /** * VERIFICACION DEL INGRESO ADECUADO DE LOS ADMINISTRADORES A LA BASE DE DATOS * @return */ public boolean verificarEstadoDB(){ Administrador admin = null; ResultSet rs = Conexion.getTabla("SELECT u.Codigo, u.Nombre, u.DPI, u.Telefono, u.Correo, u.Password, u.Tipo_Usuario FROM Usuario u INNER JOIN Administrador a ON a.Usuario_Codigo = u.Codigo"); try { while (rs.next()) { admin = new Administrador(rs.getString("Codigo"), rs.getString("Nombre"),rs.getString("DPI"), rs.getString("Telefono"), rs.getString("Correo"), rs.getString("Password"), rs.getInt("Tipo_Usuario")); } } catch (Exception e) { } if(admin == null) { return false; } else { return true; } } /** * Metodo de Validacion, recibe los parametros desde el formulario, verifica si existe el usuario * y si este existe, verifica que su contraseña sea correcta * @param codigoAdmin * @param password * @return * @throws SQLException */ public Administrador validacionLogin(String codigoAdmin, String password) throws SQLException { Administrador admin = obtenerAdministrador(codigoAdmin); if (admin != null && admin.getPassword().equals(password)) { return admin; } return null; } /** * Obtenemos el Administrador con una busqueda entorno a su codigo * @param codigoAdministrador * @return */ public Administrador obtenerAdministrador(String codigoAdministrador){ Administrador admin = null; try { String query ="SELECT u.Codigo, u.Nombre, u.DPI, u.Telefono, u.Correo, u.Password, u.Tipo_Usuario FROM Usuario u INNER JOIN Administrador a ON a.Usuario_Codigo = u.Codigo WHERE a.Usuario_Codigo = ?"; PreparedStatement enviar = Conexion.conexion.prepareStatement(query); ResultSet rs = null; enviar.setString(1, codigoAdministrador); rs=enviar.executeQuery(); while (rs.next()) { admin = new Administrador(rs.getString("Codigo"), rs.getString("Nombre"),rs.getString("DPI"), rs.getString("Telefono"), rs.getString("Correo"), rs.getString("Password"), rs.getInt("Tipo_Usuario")); } } catch (Exception e) { } return admin; } } /* PreparedStatement preSt = connection.prepareStatement(BUSCAR_USUARIO); preSt.setInt(1, idUsuario); ResultSet result = preSt.executeQuery(); Usuario usuario = null; while (result.next()) { usuario = new Usuario( result.getInt(Usuario.USUARIO_ID_DB_NAME), result.getString(Usuario.NOMBRE_DB_NAME), result.getString(Usuario.PROFESION_DB_NAME), result.getString(Usuario.PASSWORD_DB_NAME) ); } return usuario; */ /* ASI HICE CONSULTAS CON PARAMETROS v private void mostrarTablaBusqueda(String fechaInicioConsulta, String fechaFinalConsulta) throws SQLException { //NITDelCliente = NITCliente; DefaultTableModel model = new DefaultTableModel(); try { String query ="SELECT SUM(Cantidad_Venta),Codigo_Producto,GROUP_CONCAT(DISTINCT v.Fecha) FROM DETALLE_VENTAS d INNER JOIN VENTAS v ON d.Id_Ventas=v.Id_Ventas WHERE v.Fecha BETWEEN ? AND ? GROUP BY Codigo_Producto ORDER BY SUM(Cantidad_Venta) DESC LIMIT 10"; PreparedStatement enviar = Conexion.conexion.prepareStatement(query); ResultSet rs = null; enviar.setString(1, fechaInicioConsulta); enviar.setString(2, fechaFinalConsulta); rs=enviar.executeQuery(); model.setColumnIdentifiers(new Object[]{"Cantidad de Productos Vendidos", "Codigo Producto", "Fecha en la que se Vendieron más Productos"}); while (rs.next()) { model.addRow(new Object[]{rs.getInt("SUM(Cantidad_Venta)"), rs.getString("Codigo_Producto"), rs.getString("GROUP_CONCAT(DISTINCT v.Fecha)")}); } tablePedidos.setModel(model); } catch (SQLException e) { e.printStackTrace(System.out); } } */
6,607
0.612112
0.607116
178
36.112358
43.618477
265
false
false
0
0
0
0
0
0
0.713483
false
false
13
118be6c4515c7d1496c67e74496c4fcb7eb819df
3,384,434,234,371
9c0c7c37cb8be134e0a8e8c5aab57fc08c5fee03
/src/blogic/entity/Cognate.java
f67d8155bf737e945576d2ec4f7885c0ae65c4d6
[]
no_license
NSPilipchak/crm_person
https://github.com/NSPilipchak/crm_person
ba5129bd621824f9b547a38422b5fb401550191c
5b1c203aae0f28f7e8b6ec66811b669f52d6cad5
refs/heads/master
2020-03-24T23:27:34.938000
2018-08-01T09:46:54
2018-08-01T09:46:54
143,039,957
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package blogic.entity; import javax.persistence.*; import java.io.Serializable; @Entity @Table(name = "cognate") public class Cognate implements Comparable<Cognate>, Serializable { @Id @Column(name = "cognate_id", unique = true, length = 10) @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "cognate_gen") @SequenceGenerator(name = "cognate_gen", sequenceName = "cognate_sequence", allocationSize = 1) private int id; @Column(unique = true, nullable = false, length = 15) private String cognate; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getCognate() { return cognate; } public void setCognate(String cognate) { this.cognate = cognate; } @Override public String toString() { return "Cognate{" + "id='" + id + '\'' + ", cognate='" + cognate + '\'' + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Cognate cognate1 = (Cognate) o; if (id != cognate1.id) return false; return cognate != null ? cognate.equals(cognate1.cognate) : cognate1.cognate == null; } @Override public int hashCode() { int result = id; result = 31 * result + (cognate != null ? cognate.hashCode() : 0); return result; } @Override public int compareTo(Cognate o) { return cognate.compareToIgnoreCase(o.cognate); } }
UTF-8
Java
1,622
java
Cognate.java
Java
[]
null
[]
package blogic.entity; import javax.persistence.*; import java.io.Serializable; @Entity @Table(name = "cognate") public class Cognate implements Comparable<Cognate>, Serializable { @Id @Column(name = "cognate_id", unique = true, length = 10) @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "cognate_gen") @SequenceGenerator(name = "cognate_gen", sequenceName = "cognate_sequence", allocationSize = 1) private int id; @Column(unique = true, nullable = false, length = 15) private String cognate; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getCognate() { return cognate; } public void setCognate(String cognate) { this.cognate = cognate; } @Override public String toString() { return "Cognate{" + "id='" + id + '\'' + ", cognate='" + cognate + '\'' + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Cognate cognate1 = (Cognate) o; if (id != cognate1.id) return false; return cognate != null ? cognate.equals(cognate1.cognate) : cognate1.cognate == null; } @Override public int hashCode() { int result = id; result = 31 * result + (cognate != null ? cognate.hashCode() : 0); return result; } @Override public int compareTo(Cognate o) { return cognate.compareToIgnoreCase(o.cognate); } }
1,622
0.581998
0.574599
66
23.575758
24.247499
99
false
false
0
0
0
0
0
0
0.454545
false
false
13
a17733c57bc4f4caaae18fe631607947ddecb475
5,729,486,380,630
2954520b4f7100481be805b8ba3d8a50fc0314dd
/app/operations/core/OperationType.java
e7de6fd0614a7a5cbf9c910d6624dbb5b9058d0f
[]
no_license
jesubiag/wifree
https://github.com/jesubiag/wifree
3bdff7a795cbbc7869ca7483c6db4e265f54dcf0
df0cf81d2e36e5b7eb153164c2a72e8328a29af0
refs/heads/master
2021-08-26T08:49:43.436000
2021-08-21T19:33:45
2021-08-21T19:33:45
89,517,223
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package operations.core; public enum OperationType { REQUEST, RESPONSE }
UTF-8
Java
79
java
OperationType.java
Java
[]
null
[]
package operations.core; public enum OperationType { REQUEST, RESPONSE }
79
0.746835
0.746835
7
10.285714
11.28481
27
false
false
0
0
0
0
0
0
0.714286
false
false
13
8cd15488881f6ff96ed5cf1d33c16cbe339909d1
14,843,406,982,250
3909f7298d3208ac46ce97971f41a0d55600a98b
/6月8号验收/src/PriceLogicInterface.java
6cdf4c3960570adf43120b6f90b82178a3eb6488
[]
no_license
Viskaz/SE4.8
https://github.com/Viskaz/SE4.8
5cf1c85d6dfbcd34d740886d3e229a5cad56cd9b
447486e33b2bf5ec8c42a47d0df8c0de5a703676
refs/heads/master
2020-03-25T07:43:55.887000
2018-08-16T07:11:26
2018-08-16T07:11:26
143,578,782
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public interface PriceLogicInterface { public double readPrice(String filename); public boolean writePrice(String filename, String price); }
UTF-8
Java
149
java
PriceLogicInterface.java
Java
[]
null
[]
public interface PriceLogicInterface { public double readPrice(String filename); public boolean writePrice(String filename, String price); }
149
0.785235
0.785235
4
36.25
21.992897
61
false
false
0
0
0
0
0
0
0.75
false
false
13
177f3515d6e3fa80f9853192ca2ea1f7987ec4ed
23,201,413,338,145
1a50e48ae0cd5ec90e5e91a6d5670f57994ef48e
/it.unibo.iss.group2.drone/src/it/unibo/iss/group2/sensors/FuelSensor.java
6a4417b1243308c585f0f64e2f1c3bed9ce3e2d7
[]
no_license
flagg19/Progetto-ISS
https://github.com/flagg19/Progetto-ISS
0423ff03bf0b348b0f7b53200befd33c15212f67
d98f1034ed94d84db921bb71e19e1fdb3ba5a266
refs/heads/master
2021-03-12T20:44:55.689000
2014-06-28T08:18:16
2014-06-28T08:18:16
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package it.unibo.iss.group2.sensors; import it.unibo.iss.group2.implementations.measures.Fuel; import it.unibo.iss.group2.interfaces.measures.IFuel; import it.unibo.iss.group2.interfaces.measures.ISpeed; import it.unibo.iss.group2.interfaces.globals.*; public class FuelSensor implements ISensor<IFuel> { Fuel curFuel; public FuelSensor() { curFuel = new Fuel(Globals.MAX_FUEL); } @Override public IFuel getValue(ISpeed speed) { Double consumption = speed.getSpeedAsDouble() * Globals.CONSUMPTION_PARAM / 3600; curFuel = new Fuel(curFuel.getFuelAsDouble() - consumption); return curFuel; } }
UTF-8
Java
613
java
FuelSensor.java
Java
[]
null
[]
package it.unibo.iss.group2.sensors; import it.unibo.iss.group2.implementations.measures.Fuel; import it.unibo.iss.group2.interfaces.measures.IFuel; import it.unibo.iss.group2.interfaces.measures.ISpeed; import it.unibo.iss.group2.interfaces.globals.*; public class FuelSensor implements ISensor<IFuel> { Fuel curFuel; public FuelSensor() { curFuel = new Fuel(Globals.MAX_FUEL); } @Override public IFuel getValue(ISpeed speed) { Double consumption = speed.getSpeedAsDouble() * Globals.CONSUMPTION_PARAM / 3600; curFuel = new Fuel(curFuel.getFuelAsDouble() - consumption); return curFuel; } }
613
0.766721
0.752039
22
26.863636
25.295158
83
false
false
0
0
0
0
0
0
1.181818
false
false
13
301f0df2a03a4fddb583102ae59c0f4394a0e273
28,948,079,580,514
8b3e4f89989c17ae416c5041e6b6412c81d57b59
/src/com/example/menu/Fragmentos.java
4ad3a3f4a3fb01c9fcda627f2fb829cbf79c4595
[]
no_license
jccuevas/com.example.menu.Menus
https://github.com/jccuevas/com.example.menu.Menus
b0e2d3bc65c39189c8c2e22470102252eaa2ad11
72b1381f0f0b069428709afffb0ce52d4fee4150
refs/heads/master
2020-06-04T22:51:47.314000
2015-12-03T09:08:04
2015-12-03T09:08:04
42,650,995
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.menu; import android.app.Activity; import android.app.Fragment; import android.app.FragmentManager; import android.app.FragmentTransaction; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; public class Fragmentos extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.layout_fragments); } public void show() { FragmentManager fm = getFragmentManager(); FragmentTransaction ft = fm.beginTransaction(); Fragment fragment = fm.findFragmentById(R.id.fragment_viewer); if (fragment != null) { if (!fragment.isVisible()) { ft.show(fragment); ft.setTransitionStyle(FragmentTransaction.TRANSIT_FRAGMENT_FADE); ft.addToBackStack(null); ft.commit(); } } } public void replace() { FragmentManager fm = getFragmentManager(); FragmentTransaction ft = fm.beginTransaction(); Fragment fragment = fm.findFragmentById(R.id.fragment_container); if (fragment == null) { Barra barra = new Barra(); ft.add(R.id.fragment_viewer, barra); ft.setTransitionStyle(FragmentTransaction.TRANSIT_FRAGMENT_FADE); ft.addToBackStack(null); ft.commit(); } else { Barra barra = new Barra(); ft.replace(R.id.fragment_viewer, barra); ft.remove(fragment); // ft.setTransitionStyle(FragmentTransaction.TRANSIT_FRAGMENT_FADE); ft.addToBackStack(null); ft.commit(); } } public void hide() { FragmentManager fm = getFragmentManager(); Fragment fragment = fm.findFragmentById(R.id.fragment_viewer); FragmentTransaction ft = fm.beginTransaction(); if (fragment != null) { ft.hide(fragment); ft.setTransitionStyle(FragmentTransaction.TRANSIT_FRAGMENT_FADE); ft.addToBackStack(null); ft.commit(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_fragmentos, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_hidePanel: hide(); return true; case R.id.menu_showPanel: show(); return true; case R.id.menu_replacePanel: replace(); return true; } return false; } }
UTF-8
Java
2,259
java
Fragmentos.java
Java
[]
null
[]
package com.example.menu; import android.app.Activity; import android.app.Fragment; import android.app.FragmentManager; import android.app.FragmentTransaction; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; public class Fragmentos extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.layout_fragments); } public void show() { FragmentManager fm = getFragmentManager(); FragmentTransaction ft = fm.beginTransaction(); Fragment fragment = fm.findFragmentById(R.id.fragment_viewer); if (fragment != null) { if (!fragment.isVisible()) { ft.show(fragment); ft.setTransitionStyle(FragmentTransaction.TRANSIT_FRAGMENT_FADE); ft.addToBackStack(null); ft.commit(); } } } public void replace() { FragmentManager fm = getFragmentManager(); FragmentTransaction ft = fm.beginTransaction(); Fragment fragment = fm.findFragmentById(R.id.fragment_container); if (fragment == null) { Barra barra = new Barra(); ft.add(R.id.fragment_viewer, barra); ft.setTransitionStyle(FragmentTransaction.TRANSIT_FRAGMENT_FADE); ft.addToBackStack(null); ft.commit(); } else { Barra barra = new Barra(); ft.replace(R.id.fragment_viewer, barra); ft.remove(fragment); // ft.setTransitionStyle(FragmentTransaction.TRANSIT_FRAGMENT_FADE); ft.addToBackStack(null); ft.commit(); } } public void hide() { FragmentManager fm = getFragmentManager(); Fragment fragment = fm.findFragmentById(R.id.fragment_viewer); FragmentTransaction ft = fm.beginTransaction(); if (fragment != null) { ft.hide(fragment); ft.setTransitionStyle(FragmentTransaction.TRANSIT_FRAGMENT_FADE); ft.addToBackStack(null); ft.commit(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_fragmentos, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_hidePanel: hide(); return true; case R.id.menu_showPanel: show(); return true; case R.id.menu_replacePanel: replace(); return true; } return false; } }
2,259
0.717131
0.717131
102
21.147058
20.331274
71
false
false
0
0
0
0
0
0
2.009804
false
false
13
9567ad653f28e68dfd46a1d6feff9a5c3211ac03
19,447,611,928,497
1f2073269378e734b5c9baafa23890558b004673
/spring2.5/src/com/helloweenvsfei/orm/dao/impl/CatDaoImpl.java
605767366caaf180626072511fa3990b75f633a9
[]
no_license
hungmans6779/Java-Web-integration-development
https://github.com/hungmans6779/Java-Web-integration-development
7db40c418c13c3efa27e249cdf1e8fe8e39dfa83
289d03edd927484e30b053d1e23b218f003d2359
refs/heads/master
2020-04-14T01:14:35.712000
2018-12-30T02:28:32
2018-12-30T02:28:32
163,555,635
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.helloweenvsfei.orm.dao.impl; import java.util.List; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; import com.helloweenvsfei.orm.bean.Cat; import com.helloweenvsfei.orm.dao.ICatDao; public class CatDaoImpl extends HibernateDaoSupport implements ICatDao { // 儲存物件 public void createCat(Cat cat){ this.getHibernateTemplate().persist(cat); // 使用Template 儲存物件 } // 查詢所有物件 public List<Cat> listCats(){ return this.getHibernateTemplate().find("select c from Cat c "); // 使用 Template 查詢 } // 傳回物件數量 public int getCatsCount(){ return Integer.valueOf(this.getSession(true).createQuery("select count(c) from Cat c ").uniqueResult().toString()); } // 根據名字查詢物件(根據名字查詢Cat) public Cat findCatByName(String name){ List <Cat> catList = this.getHibernateTemplate().find("select c from Cat c where c.name = ? ",name); // 使用 Template if(catList.size()>0){ // 如果有資料 return catList.get(0); // 傳回第一條 } return null; } }
BIG5
Java
1,125
java
CatDaoImpl.java
Java
[]
null
[]
package com.helloweenvsfei.orm.dao.impl; import java.util.List; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; import com.helloweenvsfei.orm.bean.Cat; import com.helloweenvsfei.orm.dao.ICatDao; public class CatDaoImpl extends HibernateDaoSupport implements ICatDao { // 儲存物件 public void createCat(Cat cat){ this.getHibernateTemplate().persist(cat); // 使用Template 儲存物件 } // 查詢所有物件 public List<Cat> listCats(){ return this.getHibernateTemplate().find("select c from Cat c "); // 使用 Template 查詢 } // 傳回物件數量 public int getCatsCount(){ return Integer.valueOf(this.getSession(true).createQuery("select count(c) from Cat c ").uniqueResult().toString()); } // 根據名字查詢物件(根據名字查詢Cat) public Cat findCatByName(String name){ List <Cat> catList = this.getHibernateTemplate().find("select c from Cat c where c.name = ? ",name); // 使用 Template if(catList.size()>0){ // 如果有資料 return catList.get(0); // 傳回第一條 } return null; } }
1,125
0.695397
0.692458
49
19.836735
29.469006
116
false
false
0
0
0
0
0
0
0.408163
false
false
13
acd0f1f924ab5371be90e9badc70d62969c2000c
5,265,629,917,701
83718d25437357d37d5166178f477a33adc280d8
/src/StringProgramms/StringUpper2Low.java
e6e2ed798eed29419c68e711a6c2932a3e5187ab
[]
no_license
limonkanti/Graph_Data_Structure_In_Java_Part2_UL
https://github.com/limonkanti/Graph_Data_Structure_In_Java_Part2_UL
5879625c8eb4092a9f0f8698ae7a9f8d8614978d
9abb041386ed15be14553fddd93b19d1b12b2183
refs/heads/master
2020-07-04T02:09:51.334000
2016-11-19T16:50:22
2016-11-19T16:50:22
74,221,154
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package StringProgramms; public class StringUpper2Low { public static void main(String[] args) { String s="LIMON"; System.out.println(s.toLowerCase()); } }
UTF-8
Java
189
java
StringUpper2Low.java
Java
[]
null
[]
package StringProgramms; public class StringUpper2Low { public static void main(String[] args) { String s="LIMON"; System.out.println(s.toLowerCase()); } }
189
0.624339
0.619048
11
16.09091
16.811546
44
false
false
0
0
0
0
0
0
0.272727
false
false
13
3505c16a5fad918e24fa56e48ee53ad0d7d8fcc0
33,724,083,213,818
fe0ce24f465e8ccd05a7556dd485692284127f24
/src/test/java/net/gundabad/jgoo/ReaderTest.java
35c34ae89826a66b635bbb866dec2c7e6b28129e
[]
no_license
ndwarf/ool
https://github.com/ndwarf/ool
222ac3d489803e50b9f5083e5c1ec13e00e22a4b
19b9fe499fce7de261c0ef443648b1b3a0f383bb
refs/heads/master
2016-08-09T16:56:09.629000
2015-08-08T20:52:32
2015-08-08T20:52:32
36,250,214
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * 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 net.gundabad.jgoo; import java.io.IOException; import java.util.List; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import org.junit.Test; /** * * @author ndwarf */ public class ReaderTest { @Test public void verifyEOFObjectIsEOFObject() { assertTrue(Reader._isEOFObject(Reader._EOF_OBJECT)); } @Test public void verifyNonEOFObjectIsNotEOFObject() { assertFalse(Reader._isEOFObject('x')); assertFalse(Reader._isEOFObject(null)); assertFalse(Reader._isEOFObject('\0')); assertFalse(Reader._isEOFObject("")); } @Test public void verifyReadcReadsCharacter() { IInputPort inport = new InputPortStringWrapper("test input 1"); try { assertThat(Reader._readc(inport), is(equalTo('t'))); } catch (IOException x) { fail("Caught exception"); } } @Test public void verifyMultipleReadcsReadsCharacters() { IInputPort inport = new InputPortStringWrapper("test input 1"); try { assertThat(Reader._readc(inport), is(equalTo('t'))); assertThat(Reader._readc(inport), is(equalTo('e'))); assertThat(Reader._readc(inport), is(equalTo('s'))); assertThat(Reader._readc(inport), is(equalTo('t'))); assertThat(Reader._readc(inport), is(equalTo(' '))); assertThat(Reader._readc(inport), is(equalTo('i'))); assertThat(Reader._readc(inport), is(equalTo('n'))); assertThat(Reader._readc(inport), is(equalTo('p'))); assertThat(Reader._readc(inport), is(equalTo('u'))); assertThat(Reader._readc(inport), is(equalTo('t'))); assertThat(Reader._readc(inport), is(equalTo(' '))); assertThat(Reader._readc(inport), is(equalTo('1'))); assertThat(Reader._readc(inport), is(equalTo(Reader._EOF_OBJECT))); } catch (IOException x) { fail("Caught exception"); } } @Test public void verifyUnreadcsUnreadsCharacters() { IInputPort inport = new InputPortStringWrapper("test input 1"); try { assertThat(Reader._readc(inport), is(equalTo('t'))); assertThat(Reader._readc(inport), is(equalTo('e'))); assertThat(Reader._readc(inport), is(equalTo('s'))); assertThat(Reader._readc(inport), is(equalTo('t'))); Reader._unreadc('t', inport); assertThat(Reader._readc(inport), is(equalTo('t'))); // XXX: Can the character be arbitrary? If not, what's the point? // What should the semantics of this be? Reader._unreadc('x', inport); assertThat(Reader._readc(inport), is(equalTo('t'))); } catch (IOException x) { fail("Caught exception"); } } @Test public void verifyReadObjectReadsSymbols() { IInputPort inport = new InputPortStringWrapper("test input 1"); assertThat((String) Reader._readObject(inport), is(equalTo("test"))); assertThat((String) Reader._readObject(inport), is(equalTo("input"))); assertThat((Long) Reader._readObject(inport), is(equalTo(Long.valueOf(1)))); assertThat((Character) Reader._readObject(inport), is(equalTo(Reader._EOF_OBJECT))); } @Test public void verifyReadObjectReadsLists() { IInputPort inport = new InputPortStringWrapper("(test input (1))"); Object result = Reader._readObject(inport); assertTrue(result instanceof List); List resultList = (List) result; assertThat(resultList.size(), is(equalTo(3))); result = resultList.get(2); assertTrue(result instanceof List); resultList = (List) result; assertThat(resultList.size(), is(equalTo(1))); } @Test(expected=JGooNLE.class) public void verifyReadObjectFailsToReadMalformedList() { // :-> "unexpected eof reading list" IInputPort inport = new InputPortStringWrapper("(test input (1)"); Reader._readObject(inport); } @Test(expected=JGooNLE.class) public void verifyReadObjectFailsToReadExtraneousCloseList() { // :-> "unexpected eof reading list" IInputPort inport = new InputPortStringWrapper("(test input (1)))"); // Expected to read first list; tested elsewhere Reader._readObject(inport); // Expected to fail; too many ')' Reader._readObject(inport); } @Test public void literalIntegersAreReadAsLongs() { IInputPort inport = new InputPortStringWrapper("123"); Object form = Reader._readObject(inport); assertThat((Long) form, is(equalTo(Long.valueOf(123)))); } @Test public void literalFloatsAreReadAsDoubles() { IInputPort inport = new InputPortStringWrapper("123.45"); Object form = Reader._readObject(inport); assertThat((Double) form, is(equalTo(123.45))); } }
UTF-8
Java
5,368
java
ReaderTest.java
Java
[ { "context": "rt.fail;\nimport org.junit.Test;\n\n/**\n *\n * @author ndwarf\n */\npublic class ReaderTest {\n \n @Test\n ", "end": 572, "score": 0.9996592402458191, "start": 566, "tag": "USERNAME", "value": "ndwarf" } ]
null
[]
/* * 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 net.gundabad.jgoo; import java.io.IOException; import java.util.List; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import org.junit.Test; /** * * @author ndwarf */ public class ReaderTest { @Test public void verifyEOFObjectIsEOFObject() { assertTrue(Reader._isEOFObject(Reader._EOF_OBJECT)); } @Test public void verifyNonEOFObjectIsNotEOFObject() { assertFalse(Reader._isEOFObject('x')); assertFalse(Reader._isEOFObject(null)); assertFalse(Reader._isEOFObject('\0')); assertFalse(Reader._isEOFObject("")); } @Test public void verifyReadcReadsCharacter() { IInputPort inport = new InputPortStringWrapper("test input 1"); try { assertThat(Reader._readc(inport), is(equalTo('t'))); } catch (IOException x) { fail("Caught exception"); } } @Test public void verifyMultipleReadcsReadsCharacters() { IInputPort inport = new InputPortStringWrapper("test input 1"); try { assertThat(Reader._readc(inport), is(equalTo('t'))); assertThat(Reader._readc(inport), is(equalTo('e'))); assertThat(Reader._readc(inport), is(equalTo('s'))); assertThat(Reader._readc(inport), is(equalTo('t'))); assertThat(Reader._readc(inport), is(equalTo(' '))); assertThat(Reader._readc(inport), is(equalTo('i'))); assertThat(Reader._readc(inport), is(equalTo('n'))); assertThat(Reader._readc(inport), is(equalTo('p'))); assertThat(Reader._readc(inport), is(equalTo('u'))); assertThat(Reader._readc(inport), is(equalTo('t'))); assertThat(Reader._readc(inport), is(equalTo(' '))); assertThat(Reader._readc(inport), is(equalTo('1'))); assertThat(Reader._readc(inport), is(equalTo(Reader._EOF_OBJECT))); } catch (IOException x) { fail("Caught exception"); } } @Test public void verifyUnreadcsUnreadsCharacters() { IInputPort inport = new InputPortStringWrapper("test input 1"); try { assertThat(Reader._readc(inport), is(equalTo('t'))); assertThat(Reader._readc(inport), is(equalTo('e'))); assertThat(Reader._readc(inport), is(equalTo('s'))); assertThat(Reader._readc(inport), is(equalTo('t'))); Reader._unreadc('t', inport); assertThat(Reader._readc(inport), is(equalTo('t'))); // XXX: Can the character be arbitrary? If not, what's the point? // What should the semantics of this be? Reader._unreadc('x', inport); assertThat(Reader._readc(inport), is(equalTo('t'))); } catch (IOException x) { fail("Caught exception"); } } @Test public void verifyReadObjectReadsSymbols() { IInputPort inport = new InputPortStringWrapper("test input 1"); assertThat((String) Reader._readObject(inport), is(equalTo("test"))); assertThat((String) Reader._readObject(inport), is(equalTo("input"))); assertThat((Long) Reader._readObject(inport), is(equalTo(Long.valueOf(1)))); assertThat((Character) Reader._readObject(inport), is(equalTo(Reader._EOF_OBJECT))); } @Test public void verifyReadObjectReadsLists() { IInputPort inport = new InputPortStringWrapper("(test input (1))"); Object result = Reader._readObject(inport); assertTrue(result instanceof List); List resultList = (List) result; assertThat(resultList.size(), is(equalTo(3))); result = resultList.get(2); assertTrue(result instanceof List); resultList = (List) result; assertThat(resultList.size(), is(equalTo(1))); } @Test(expected=JGooNLE.class) public void verifyReadObjectFailsToReadMalformedList() { // :-> "unexpected eof reading list" IInputPort inport = new InputPortStringWrapper("(test input (1)"); Reader._readObject(inport); } @Test(expected=JGooNLE.class) public void verifyReadObjectFailsToReadExtraneousCloseList() { // :-> "unexpected eof reading list" IInputPort inport = new InputPortStringWrapper("(test input (1)))"); // Expected to read first list; tested elsewhere Reader._readObject(inport); // Expected to fail; too many ')' Reader._readObject(inport); } @Test public void literalIntegersAreReadAsLongs() { IInputPort inport = new InputPortStringWrapper("123"); Object form = Reader._readObject(inport); assertThat((Long) form, is(equalTo(Long.valueOf(123)))); } @Test public void literalFloatsAreReadAsDoubles() { IInputPort inport = new InputPortStringWrapper("123.45"); Object form = Reader._readObject(inport); assertThat((Double) form, is(equalTo(123.45))); } }
5,368
0.627049
0.621647
141
37.070923
25.786259
92
false
false
0
0
0
0
0
0
0.737589
false
false
13
b501d858e8384ba7ade01628612a5d4c634d462a
26,895,085,220,347
e9bb1221686e9f4dc3f0ca641394ccc1bb3c6e5b
/JavaPractice/src/practice/MultipleInheritance.java
eaf42415bc2a91dc406e0c45775d4450bcb1fc61
[]
no_license
MeghanaMJ/NewRepository
https://github.com/MeghanaMJ/NewRepository
c3942acaf0057575d0e5c3f4b9e078e44a94baa8
347275d81a8a50cf15f6e1e2608500765addcfff
refs/heads/master
2020-08-12T21:21:06.977000
2019-10-13T16:43:51
2019-10-13T16:43:51
214,845,269
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/*package practice; class School { void write() { System.out.println("Writing..."); } } class Stud { void read() { System.out.println("Reading..."); } } class MultipleInheritance extends School,Stud { public static void main(String[] args) { MultilevelInheritance m=new MultilevelInheritance(); m.read(); m.write(); } }*/
UTF-8
Java
378
java
MultipleInheritance.java
Java
[]
null
[]
/*package practice; class School { void write() { System.out.println("Writing..."); } } class Stud { void read() { System.out.println("Reading..."); } } class MultipleInheritance extends School,Stud { public static void main(String[] args) { MultilevelInheritance m=new MultilevelInheritance(); m.read(); m.write(); } }*/
378
0.597884
0.597884
28
11.357142
15.652965
54
false
false
0
0
0
0
0
0
0.892857
false
false
13
c6cb06403d9f9e107a7dd86de47d49fab7b7b91d
2,336,462,231,697
8e5e528d64a1c41ef8effed01772240c7c9b18b6
/Tikape-master/Tikape-master/ryhmatyo/src/main/java/tikape/ryhmatyo/Main.java
283846d1259f851e1dc0e5bbcf145433ea8951e0
[]
no_license
vislaava/Tikape
https://github.com/vislaava/Tikape
8631650a1ab9febea8f6346509425d87c193e77e
d97df72fbd2f90147dcda86cd01919d65e9059ea
refs/heads/master
2021-01-18T08:40:09.006000
2016-03-15T21:54:03
2016-03-15T21:54:03
52,676,358
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * 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 tikape.ryhmatyo; import java.sql.*; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import spark.ModelAndView; import static spark.Spark.get; import static spark.Spark.post; import spark.template.thymeleaf.ThymeleafTemplateEngine; public class Main { public static void main(String[] args) throws Exception { Database database = new Database("jdbc:sqlite:Keskustelupalsta.db"); ViestiDao viestiDao = new ViestiDao(database); KeskusteluDao keskuDao = new KeskusteluDao(database); // Viesti v = viestiDao.findOne(1); // AihealueDao aiheDao = new AihealueDao(database); // Aihealue a = aiheDao.findOne(1); // database.setDebugMode(true); // // System.out.println(a.getId()); // database.update("INSERT INTO Viesti (paivamaara, teksti, kirjoittaja, keskustelu) VALUES ('2016-02-22', 'Hola!', 'Tanja', '1')"); // // List<Viesti> viestit = database.queryAndCollect("SELECT * FROM Viesti", // rs -> new Viesti(rs.getInt("id"), rs.getString("paivamaara"), rs.getString("teksti"), rs.getString("kirjoittaja"), rs.getInt("keskustelu"))); // // for (Viesti viesti : viestit) { // System.out.println(viesti.getTeksti()); // } get("/sivu", (req, res) -> { AihealueDao aihedao = new AihealueDao(database); List<Aihealue> aiheetlista = aihedao.findAll(); HashMap map = new HashMap<>(); map.put("teksti", "Aihealueet"); map.put("aihealueet", aiheetlista); return new ModelAndView(map, "index"); }, new ThymeleafTemplateEngine()); get("/sivu2", (req, res) -> { KeskusteluDao keskudao = new KeskusteluDao(database); List<Keskustelu> keskulista = keskudao.findAll(); HashMap map = new HashMap<>(); map.put("teksti", "Keskustelut"); map.put("keskustelut", keskulista); return new ModelAndView(map, "keskustelut"); }, new ThymeleafTemplateEngine()); get("/sivu3", (req, res) -> { ViestiDao viestidao = new ViestiDao(database); List<Viesti> viestitlista = viestidao.findAll(); HashMap map = new HashMap<>(); map.put("teksti", "Viestit"); map.put("viestit", viestitlista); map.put("keskustelualue", 1); return new ModelAndView(map, "yksiKeskustelu"); }, new ThymeleafTemplateEngine()); post("/uusiViesti", (req, res) -> { String nimi = req.queryParams("nimi"); String viesti = req.queryParams("viesti"); Viesti viestioljo = new Viesti("pvm", viesti, nimi, Integer.parseInt(req.queryParams("keskustelualue"))); viestiDao.insert(viestioljo); return "Kerrotaan siitä tiedon lähettäjälle: " + nimi + viesti; }); post("/uusiKeskustelu", (req, res) -> { String nimi = req.queryParams("nimi"); String viesti = req.queryParams("otsikko"); Keskustelu keskuoljo = new Keskustelu("pvm", nimi, Integer.parseInt(req.queryParams("aiheelualue"))); keskuDao.insert(keskuoljo); return "Viesti on vastaanotettu: " + nimi + viesti; }); post("/sivu2", (req, res) -> { String id = req.queryParams("id"); int id2 = Integer.parseInt(id); keskuDao.findOne(id2); return "Viesti on vastaanotettu: " + id; }); get("/alue/:id", (req, res) -> { HashMap map = new HashMap<>(); map.put("teksti", req.params("id")); Collection<Integer> kokoelma = new ArrayList<>(); String id = req.params(":id"); int idd = Integer.parseInt(id); kokoelma.add(idd); List<Keskustelu> keskustelut = keskuDao.findAllIn(kokoelma); map.put("keskustelut", keskustelut); return new ModelAndView(map, "keskustelut"); }, new ThymeleafTemplateEngine()); get("alue/:id1/keskustelu/:id", (req, res) -> { HashMap map = new HashMap<>(); map.put("teksti", req.params("id")); Collection<Integer> kokoelma = new ArrayList<>(); System.out.println("id"); String id = req.params(":id"); System.out.println(id); int idd = Integer.parseInt(id); kokoelma.add(idd); List<Viesti> viestit = viestiDao.findAllIn(kokoelma); map.put("teksti", "Viestit"); map.put("viestit", viestit); map.put("keskustelualue", req.params(":id")); return new ModelAndView(map, "yksiKeskustelu"); }, new ThymeleafTemplateEngine()); } }
UTF-8
Java
5,054
java
Main.java
Java
[ { "context": ") -> {\n String nimi = req.queryParams(\"nimi\");\n String viesti = req.queryParams(\"o", "end": 3242, "score": 0.7239296436309814, "start": 3238, "tag": "NAME", "value": "nimi" } ]
null
[]
/* * 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 tikape.ryhmatyo; import java.sql.*; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import spark.ModelAndView; import static spark.Spark.get; import static spark.Spark.post; import spark.template.thymeleaf.ThymeleafTemplateEngine; public class Main { public static void main(String[] args) throws Exception { Database database = new Database("jdbc:sqlite:Keskustelupalsta.db"); ViestiDao viestiDao = new ViestiDao(database); KeskusteluDao keskuDao = new KeskusteluDao(database); // Viesti v = viestiDao.findOne(1); // AihealueDao aiheDao = new AihealueDao(database); // Aihealue a = aiheDao.findOne(1); // database.setDebugMode(true); // // System.out.println(a.getId()); // database.update("INSERT INTO Viesti (paivamaara, teksti, kirjoittaja, keskustelu) VALUES ('2016-02-22', 'Hola!', 'Tanja', '1')"); // // List<Viesti> viestit = database.queryAndCollect("SELECT * FROM Viesti", // rs -> new Viesti(rs.getInt("id"), rs.getString("paivamaara"), rs.getString("teksti"), rs.getString("kirjoittaja"), rs.getInt("keskustelu"))); // // for (Viesti viesti : viestit) { // System.out.println(viesti.getTeksti()); // } get("/sivu", (req, res) -> { AihealueDao aihedao = new AihealueDao(database); List<Aihealue> aiheetlista = aihedao.findAll(); HashMap map = new HashMap<>(); map.put("teksti", "Aihealueet"); map.put("aihealueet", aiheetlista); return new ModelAndView(map, "index"); }, new ThymeleafTemplateEngine()); get("/sivu2", (req, res) -> { KeskusteluDao keskudao = new KeskusteluDao(database); List<Keskustelu> keskulista = keskudao.findAll(); HashMap map = new HashMap<>(); map.put("teksti", "Keskustelut"); map.put("keskustelut", keskulista); return new ModelAndView(map, "keskustelut"); }, new ThymeleafTemplateEngine()); get("/sivu3", (req, res) -> { ViestiDao viestidao = new ViestiDao(database); List<Viesti> viestitlista = viestidao.findAll(); HashMap map = new HashMap<>(); map.put("teksti", "Viestit"); map.put("viestit", viestitlista); map.put("keskustelualue", 1); return new ModelAndView(map, "yksiKeskustelu"); }, new ThymeleafTemplateEngine()); post("/uusiViesti", (req, res) -> { String nimi = req.queryParams("nimi"); String viesti = req.queryParams("viesti"); Viesti viestioljo = new Viesti("pvm", viesti, nimi, Integer.parseInt(req.queryParams("keskustelualue"))); viestiDao.insert(viestioljo); return "Kerrotaan siitä tiedon lähettäjälle: " + nimi + viesti; }); post("/uusiKeskustelu", (req, res) -> { String nimi = req.queryParams("nimi"); String viesti = req.queryParams("otsikko"); Keskustelu keskuoljo = new Keskustelu("pvm", nimi, Integer.parseInt(req.queryParams("aiheelualue"))); keskuDao.insert(keskuoljo); return "Viesti on vastaanotettu: " + nimi + viesti; }); post("/sivu2", (req, res) -> { String id = req.queryParams("id"); int id2 = Integer.parseInt(id); keskuDao.findOne(id2); return "Viesti on vastaanotettu: " + id; }); get("/alue/:id", (req, res) -> { HashMap map = new HashMap<>(); map.put("teksti", req.params("id")); Collection<Integer> kokoelma = new ArrayList<>(); String id = req.params(":id"); int idd = Integer.parseInt(id); kokoelma.add(idd); List<Keskustelu> keskustelut = keskuDao.findAllIn(kokoelma); map.put("keskustelut", keskustelut); return new ModelAndView(map, "keskustelut"); }, new ThymeleafTemplateEngine()); get("alue/:id1/keskustelu/:id", (req, res) -> { HashMap map = new HashMap<>(); map.put("teksti", req.params("id")); Collection<Integer> kokoelma = new ArrayList<>(); System.out.println("id"); String id = req.params(":id"); System.out.println(id); int idd = Integer.parseInt(id); kokoelma.add(idd); List<Viesti> viestit = viestiDao.findAllIn(kokoelma); map.put("teksti", "Viestit"); map.put("viestit", viestit); map.put("keskustelualue", req.params(":id")); return new ModelAndView(map, "yksiKeskustelu"); }, new ThymeleafTemplateEngine()); } }
5,054
0.582969
0.579397
150
32.586666
29.287355
159
false
false
0
0
0
0
0
0
0.946667
false
false
13
8334fc5df19a533bf81c6eff6d2ebdccb695282e
2,336,462,230,483
4a627a99cdf202019fa4088ca23316e9cc427e7b
/nyd-cash-pay/nyd-cash-pay-api/src/main/java/com/nyd/pay/api/zzl/HelibaoFilesConfigService.java
8c8fcd4e7f0851547897f1f1528f4bda5e5e81bf
[]
no_license
P79N6A/zlqb
https://github.com/P79N6A/zlqb
4bdcc62db76f8b4fdd4176c06812c9bd8ac2148b
66a8781e74216ead7ea4969d89972c16e9d45b54
refs/heads/master
2020-07-13T14:18:36.941000
2019-08-26T12:22:20
2019-08-26T12:22:20
205,096,175
0
1
null
true
2019-08-29T06:30:30
2019-08-29T06:30:30
2019-08-29T06:26:27
2019-08-29T06:25:43
0
0
0
0
null
false
false
package com.nyd.pay.api.zzl; import com.nyd.order.entity.zzl.HelibaoFilesConfig; public interface HelibaoFilesConfigService { public HelibaoFilesConfig queryHelibaoFilesConfigInfo(); }
UTF-8
Java
205
java
HelibaoFilesConfigService.java
Java
[]
null
[]
package com.nyd.pay.api.zzl; import com.nyd.order.entity.zzl.HelibaoFilesConfig; public interface HelibaoFilesConfigService { public HelibaoFilesConfig queryHelibaoFilesConfigInfo(); }
205
0.765854
0.765854
11
16.636364
22.418633
57
false
false
0
0
0
0
0
0
0.545455
false
false
13
592c30f297114ff9d5303dc16a8a76814bffd16f
8,890,582,324,481
bd9d83c3470ecde06de79e8ce04f8f2f65664b04
/spring/kinds-of-injection/src/main/java/com/example/kindsofinjection/controller/ConstructorController.java
30df59d720a37145fbdd28d16a0ffaa76336fa96
[]
no_license
yukihane/hello-java
https://github.com/yukihane/hello-java
b85a482e797892743bb43a60944b3708e87af21d
305c0eb113a41f9c393c35f927fb2183324f2222
refs/heads/main
2023-03-10T08:40:51.328000
2023-01-27T04:47:37
2023-01-27T04:47:37
43,946,811
10
2
null
false
2023-03-07T05:08:33
2015-10-09T09:44:52
2022-11-16T10:56:46
2023-03-07T05:08:28
2,119
7
1
30
Java
false
false
package com.example.kindsofinjection.controller; import com.example.kindsofinjection.service.MyService; import lombok.RequiredArgsConstructor; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * コンストラクタインジェクションを行ったコントローラ実装サンプル。 * Lombokの {@code @RequiredArgsConstructor} と {@code final}フィールドを組み合わせることで * 明示的にコンストラクタを書かずに済む。 */ @RestController @RequestMapping("/constructor") @RequiredArgsConstructor public class ConstructorController { private final MyService myService; @GetMapping public String greet() { return myService.greet(); } }
UTF-8
Java
845
java
ConstructorController.java
Java
[]
null
[]
package com.example.kindsofinjection.controller; import com.example.kindsofinjection.service.MyService; import lombok.RequiredArgsConstructor; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * コンストラクタインジェクションを行ったコントローラ実装サンプル。 * Lombokの {@code @RequiredArgsConstructor} と {@code final}フィールドを組み合わせることで * 明示的にコンストラクタを書かずに済む。 */ @RestController @RequestMapping("/constructor") @RequiredArgsConstructor public class ConstructorController { private final MyService myService; @GetMapping public String greet() { return myService.greet(); } }
845
0.798307
0.798307
25
27.360001
22.605982
74
false
false
0
0
0
0
0
0
0.32
false
false
13
6d75ae71f2acb22e2618e39332b7a494507a4f61
11,338,713,687,199
833c13d845ed3ba866205cf0caf8be234c4ff3f8
/app/src/main/java/com/example/notanotherworkoutapp/activity/DeleteUserActivity.java
25ca43546e23e5116170ce5afa6d58c8bd77ed38
[]
no_license
TheLippyT/NotAnotherWorkoutApp
https://github.com/TheLippyT/NotAnotherWorkoutApp
17c17915c817fa4fe6b2e63c41dc7581294658c8
a64a93cec43adb0684b944f87bce44bf2017a7d3
refs/heads/master
2021-07-09T09:24:48.688000
2021-04-27T23:08:35
2021-04-27T23:08:35
242,020,930
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.notanotherworkoutapp.activity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.example.notanotherworkoutapp.R; import com.example.notanotherworkoutapp.app.MainActivity; import com.example.notanotherworkoutapp.database.DataBaseHelper; public class DeleteUserActivity extends MainActivity { DataBaseHelper myDb; Button deleteData; private EditText deleteUser; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_delete_user); myDb = new DataBaseHelper(this); deleteUser = (EditText)findViewById(R.id.deleteusername); deleteData = (Button)findViewById(R.id.deleteData); deleteData.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { Integer deleteRows = myDb.deleteData(deleteUser.getText().toString()); if(deleteRows>0) Toast.makeText(DeleteUserActivity.this,"User removed", Toast.LENGTH_LONG).show(); else Toast.makeText(DeleteUserActivity.this,"User not removed",Toast.LENGTH_LONG).show(); } } ); } }
UTF-8
Java
1,450
java
DeleteUserActivity.java
Java
[]
null
[]
package com.example.notanotherworkoutapp.activity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.example.notanotherworkoutapp.R; import com.example.notanotherworkoutapp.app.MainActivity; import com.example.notanotherworkoutapp.database.DataBaseHelper; public class DeleteUserActivity extends MainActivity { DataBaseHelper myDb; Button deleteData; private EditText deleteUser; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_delete_user); myDb = new DataBaseHelper(this); deleteUser = (EditText)findViewById(R.id.deleteusername); deleteData = (Button)findViewById(R.id.deleteData); deleteData.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { Integer deleteRows = myDb.deleteData(deleteUser.getText().toString()); if(deleteRows>0) Toast.makeText(DeleteUserActivity.this,"User removed", Toast.LENGTH_LONG).show(); else Toast.makeText(DeleteUserActivity.this,"User not removed",Toast.LENGTH_LONG).show(); } } ); } }
1,450
0.646897
0.646207
40
35.25
27.947048
112
false
false
0
0
0
0
0
0
0.625
false
false
13
b634409abaf71850d59be19b52bf05dcf64cbcd8
541,165,932,274
f28a1b18ec167554412aeb1b4f2486b725e770bc
/src/wdx/r2sv/ctci/arrays_and_strings/q1_8.java
a92423cc1e7a3936668572792ae764a4b0426d63
[]
no_license
wdxtub/ctci-6e
https://github.com/wdxtub/ctci-6e
6c39e40cf0dd3c9124db5af5333ff1ff35d626dd
f063541b8e40e2bac0087fa3337a76bc8b4b29e7
refs/heads/master
2016-09-08T00:25:26.618000
2015-10-06T12:46:03
2015-10-06T12:46:03
41,998,689
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package wdx.r2sv.ctci.arrays_and_strings; import wdx.r2sv.ctci.IAlgo; /** * Created by dawang on 9/7/15. * Question - Zero Matrix * * Write an algorithm such that if an element in an MxN matrix is 0, its entire * row and column are set to 0 */ public class q1_8 implements IAlgo { private static int[][] matrix= { {1, 2, 3, 4}, {5, 6, 0, 8}, {9, 0, 11, 12}, {13, 14, 15, 16}}; private static int[][] answer= { {1, 0, 0, 4}, {0, 0, 0, 0}, {0, 0, 0, 0}, {13, 0, 0, 16}}; /** * We can reduce the space to O(1) by using the first row and the first * column to record if we need to set the specific row or column to zero. * * 1. Check if the first row and first column have any zeros * 2. Iterate through the rest of the matrix, setting matrix[i][0] and * matrix[0][j] to zero whenever there's a zero in matrix[i][j] * 3. Iterate through rest of matrix, nullifying row i if there's a zero * in matrix[i][0] * 4. Iterate through rest of matrix, nullifying column j if there's a zero * in matrix[0][j] * 5. Nullify the first row and first column , if necessary (based on 1.) */ public static int[][] zeroMatrix(int[][] mat, int n){ /* boolean rowHasZero = false; boolean colHasZero = false; // Check if first row has a zero for (int j = 0; j < mat[0].length; j++){ if (mat[0][j] == 0){ rowHasZero = true; break; } } // Check if first column has a zero for (int i = 0; i < mat.length; i++){ if (mat[i][0] == 0){ colHasZero = true; break; } } // Check for zeros in the rest of the array for(int i = 1; i < mat.length; i++){ for (int j = 1; j < mat[0].length; j++){ if (mat[i][j] == 0){ mat[i][0] = 0; mat[0][j] = 0; } } } // Nullify rows based on values in first column for (int i = 1; i < mat.length; i++){ if (mat[i][0] == 0){ nullifyRow(mat, i); } } // Nullify columns based on values in first row for (int j = 1; j < mat[0].length; j++){ if (mat[0][j] == 0){ nullifyColumn(mat, j); } } if (rowHasZero){ nullifyRow(mat, 0); } if (colHasZero){ nullifyColumn(mat, 0); } return mat; */ boolean[] zeroRow = new boolean[n]; boolean[] zeroCol = new boolean[n]; for (int i = 0; i < n; i++){ for (int j = 0; j < n; j++){ if (mat[i][j] == 0){ zeroRow[i] = true; zeroCol[j] = true; } } } for (int i = 0; i < n; i++){ if (zeroRow[i] == true){ for (int j = 0; j < n; j++){ mat[i][j] = 0; } } } for (int j = 0; j < n; j++){ if (zeroCol[j] == true){ for (int i = 0; i < n; i++){ mat[i][j] = 0; } } } return mat; } public static void nullifyRow(int[][] mat, int row){ for (int j = 0; j < mat[0].length; j++){ mat[row][j] = 0; } } public static void nullifyColumn(int[][] mat, int col){ for (int i = 0; i < mat.length; i++){ mat[i][col] = 0; } } public static void testAlgo(){ matrix = zeroMatrix(matrix, 4); System.out.println("Testcase #1"); for (int i = 0; i < 4; i++){ for (int j = 0; j < 4; j++){ if (matrix[i][j] != answer[i][j]){ System.out.println("WA"); } } } System.out.println("AC"); } }
UTF-8
Java
4,098
java
q1_8.java
Java
[ { "context": "s;\n\nimport wdx.r2sv.ctci.IAlgo;\n\n/**\n * Created by dawang on 9/7/15.\n * Question - Zero Matrix\n *\n * Write ", "end": 96, "score": 0.9984336495399475, "start": 90, "tag": "USERNAME", "value": "dawang" } ]
null
[]
package wdx.r2sv.ctci.arrays_and_strings; import wdx.r2sv.ctci.IAlgo; /** * Created by dawang on 9/7/15. * Question - Zero Matrix * * Write an algorithm such that if an element in an MxN matrix is 0, its entire * row and column are set to 0 */ public class q1_8 implements IAlgo { private static int[][] matrix= { {1, 2, 3, 4}, {5, 6, 0, 8}, {9, 0, 11, 12}, {13, 14, 15, 16}}; private static int[][] answer= { {1, 0, 0, 4}, {0, 0, 0, 0}, {0, 0, 0, 0}, {13, 0, 0, 16}}; /** * We can reduce the space to O(1) by using the first row and the first * column to record if we need to set the specific row or column to zero. * * 1. Check if the first row and first column have any zeros * 2. Iterate through the rest of the matrix, setting matrix[i][0] and * matrix[0][j] to zero whenever there's a zero in matrix[i][j] * 3. Iterate through rest of matrix, nullifying row i if there's a zero * in matrix[i][0] * 4. Iterate through rest of matrix, nullifying column j if there's a zero * in matrix[0][j] * 5. Nullify the first row and first column , if necessary (based on 1.) */ public static int[][] zeroMatrix(int[][] mat, int n){ /* boolean rowHasZero = false; boolean colHasZero = false; // Check if first row has a zero for (int j = 0; j < mat[0].length; j++){ if (mat[0][j] == 0){ rowHasZero = true; break; } } // Check if first column has a zero for (int i = 0; i < mat.length; i++){ if (mat[i][0] == 0){ colHasZero = true; break; } } // Check for zeros in the rest of the array for(int i = 1; i < mat.length; i++){ for (int j = 1; j < mat[0].length; j++){ if (mat[i][j] == 0){ mat[i][0] = 0; mat[0][j] = 0; } } } // Nullify rows based on values in first column for (int i = 1; i < mat.length; i++){ if (mat[i][0] == 0){ nullifyRow(mat, i); } } // Nullify columns based on values in first row for (int j = 1; j < mat[0].length; j++){ if (mat[0][j] == 0){ nullifyColumn(mat, j); } } if (rowHasZero){ nullifyRow(mat, 0); } if (colHasZero){ nullifyColumn(mat, 0); } return mat; */ boolean[] zeroRow = new boolean[n]; boolean[] zeroCol = new boolean[n]; for (int i = 0; i < n; i++){ for (int j = 0; j < n; j++){ if (mat[i][j] == 0){ zeroRow[i] = true; zeroCol[j] = true; } } } for (int i = 0; i < n; i++){ if (zeroRow[i] == true){ for (int j = 0; j < n; j++){ mat[i][j] = 0; } } } for (int j = 0; j < n; j++){ if (zeroCol[j] == true){ for (int i = 0; i < n; i++){ mat[i][j] = 0; } } } return mat; } public static void nullifyRow(int[][] mat, int row){ for (int j = 0; j < mat[0].length; j++){ mat[row][j] = 0; } } public static void nullifyColumn(int[][] mat, int col){ for (int i = 0; i < mat.length; i++){ mat[i][col] = 0; } } public static void testAlgo(){ matrix = zeroMatrix(matrix, 4); System.out.println("Testcase #1"); for (int i = 0; i < 4; i++){ for (int j = 0; j < 4; j++){ if (matrix[i][j] != answer[i][j]){ System.out.println("WA"); } } } System.out.println("AC"); } }
4,098
0.422889
0.397267
148
26.68919
20.218018
79
false
false
0
0
0
0
0
0
0.709459
false
false
13
ba2a67dec3606848a6b53444a0ea607e61e61c40
27,771,258,604,207
a2287f9dc7ebf21b9c085a2e2390c0e6b2ec16bd
/tippspiel/src/main/java/de/kraemer/tim/tippspiel/ControllerExtender.java
7ffb1bb4217b00ef3d3008fc214b3d0a292ff299
[]
no_license
kraemerstim/TippSpielApp
https://github.com/kraemerstim/TippSpielApp
938aeedad6212381bd2449c7a23a020a3edb6a04
87d32187d94beab21f6239343ff926b5ef893f90
refs/heads/master
2021-01-21T16:10:04.522000
2017-06-13T21:34:15
2017-06-13T21:34:15
91,876,922
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package de.kraemer.tim.tippspiel; import java.util.HashSet; import java.util.Set; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.ui.Model; import de.kraemer.tim.tippspiel.account.Account; import de.kraemer.tim.tippspiel.player.Player; import de.kraemer.tim.tippspiel.room.Room; import de.kraemer.tim.tippspiel.security.CustomUser; public class ControllerExtender { public static void InsertHeaderModelAttributes(Model model) { Account account = GetLoggedInUserAccount(); if (account != null) { // Räume hinzufügen Set<Room> rooms = new HashSet<Room>(); for (Player player : account.getPlayers()) { rooms.add(player.getRoom()); } model.addAttribute("rooms", rooms); } } public static Account GetLoggedInUserAccount() { Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal(); if (principal != null && principal instanceof CustomUser) { return ((CustomUser) principal).getAccount(); } return null; } }
UTF-8
Java
1,035
java
ControllerExtender.java
Java
[]
null
[]
package de.kraemer.tim.tippspiel; import java.util.HashSet; import java.util.Set; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.ui.Model; import de.kraemer.tim.tippspiel.account.Account; import de.kraemer.tim.tippspiel.player.Player; import de.kraemer.tim.tippspiel.room.Room; import de.kraemer.tim.tippspiel.security.CustomUser; public class ControllerExtender { public static void InsertHeaderModelAttributes(Model model) { Account account = GetLoggedInUserAccount(); if (account != null) { // Räume hinzufügen Set<Room> rooms = new HashSet<Room>(); for (Player player : account.getPlayers()) { rooms.add(player.getRoom()); } model.addAttribute("rooms", rooms); } } public static Account GetLoggedInUserAccount() { Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal(); if (principal != null && principal instanceof CustomUser) { return ((CustomUser) principal).getAccount(); } return null; } }
1,035
0.753146
0.753146
37
26.918919
24.323694
91
false
false
0
0
0
0
0
0
1.540541
false
false
13
40de153445777ce15d1d9e4dceed0e2e0b92ccf9
27,771,258,601,968
5fa24c3b54efe6e04c8b12e7eb14d33abffff94c
/SFChannelManager/src/stayflexi/cm/pms/manifest/AllRoomAllocationInfo.java
6f923c1f43d0291ab26c40229d3b9632a599a528
[]
no_license
basarooms/channelmanager
https://github.com/basarooms/channelmanager
5777953e748cd6fb755345674297bd8e2e3a91b6
7f67215d5c2c4e3c0aea74c203960a1ca01abfc0
refs/heads/master
2020-02-22T10:36:20.049000
2017-08-30T20:10:57
2017-08-30T20:10:57
100,143,520
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/*- * Copyright (C) 2017 StayFlexi, Inc - All rights reserved. * Unauthorized copying of this file, via any medium is strictly prohibited * Proprietary and confidential */ package stayflexi.cm.pms.manifest; import java.util.List; /** * Simple POJO containing the room allocation information that will be sent to * the channels */ public class AllRoomAllocationInfo { private List<RoomAllocationInfo> roomAllocationInfoList; public List<RoomAllocationInfo> getRoomAllocationInfoList() { return roomAllocationInfoList; } public void setRoomAllocationInfoList (List<RoomAllocationInfo> roomAllocationInfoList) { this.roomAllocationInfoList = roomAllocationInfoList; } public static class RoomAllocationInfo { private String roomTypeId; private int roomCount; private String fromDate; private String toDate; private List<String> daysIncluded; public List<String> getDaysIncluded() { return daysIncluded; } public void setDaysIncluded(List<String> daysIncluded) { this.daysIncluded = daysIncluded; } public String getRoomTypeId() { return roomTypeId; } public void setRoomTypeId(String roomTypeId) { this.roomTypeId = roomTypeId; } public int getRoomCount() { return roomCount; } public void setRoomCount(int roomCount) { this.roomCount = roomCount; } public String getFromDate() { return fromDate; } public void setFromDate(String fromDate) { this.fromDate = fromDate; } public String getToDate() { return toDate; } public void setToDate(String toDate) { this.toDate = toDate; } } }
UTF-8
Java
1,877
java
AllRoomAllocationInfo.java
Java
[]
null
[]
/*- * Copyright (C) 2017 StayFlexi, Inc - All rights reserved. * Unauthorized copying of this file, via any medium is strictly prohibited * Proprietary and confidential */ package stayflexi.cm.pms.manifest; import java.util.List; /** * Simple POJO containing the room allocation information that will be sent to * the channels */ public class AllRoomAllocationInfo { private List<RoomAllocationInfo> roomAllocationInfoList; public List<RoomAllocationInfo> getRoomAllocationInfoList() { return roomAllocationInfoList; } public void setRoomAllocationInfoList (List<RoomAllocationInfo> roomAllocationInfoList) { this.roomAllocationInfoList = roomAllocationInfoList; } public static class RoomAllocationInfo { private String roomTypeId; private int roomCount; private String fromDate; private String toDate; private List<String> daysIncluded; public List<String> getDaysIncluded() { return daysIncluded; } public void setDaysIncluded(List<String> daysIncluded) { this.daysIncluded = daysIncluded; } public String getRoomTypeId() { return roomTypeId; } public void setRoomTypeId(String roomTypeId) { this.roomTypeId = roomTypeId; } public int getRoomCount() { return roomCount; } public void setRoomCount(int roomCount) { this.roomCount = roomCount; } public String getFromDate() { return fromDate; } public void setFromDate(String fromDate) { this.fromDate = fromDate; } public String getToDate() { return toDate; } public void setToDate(String toDate) { this.toDate = toDate; } } }
1,877
0.629196
0.627064
77
23.376623
22.061331
78
false
false
0
0
0
0
0
0
0.285714
false
false
13
7101abf8fe39b2999c4b5404c6c28de9f8018ce2
3,178,275,801,103
1a2e983b82522a18bf0436ea74881a6a378139ff
/src/com/ryong21/manager/PlayStatusListener.java
c182edd18cb2c8ec104e2ae6afe1332591e7f6f5
[ "Apache-2.0" ]
permissive
GinRyan/RecordWithSpeex
https://github.com/GinRyan/RecordWithSpeex
e5f411bbd0db0729f89e16d1b4c0ddc64c171f24
293b6aa66272221c46099d28c8cb50c64fb181ad
refs/heads/master
2016-09-05T19:53:34.786000
2015-04-27T07:23:01
2015-04-27T07:23:01
33,734,243
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ryong21.manager; public interface PlayStatusListener { public void OnPlayStatus(int status); }
UTF-8
Java
128
java
PlayStatusListener.java
Java
[]
null
[]
package com.ryong21.manager; public interface PlayStatusListener { public void OnPlayStatus(int status); }
128
0.6875
0.671875
7
16.285715
17.268587
42
false
false
0
0
0
0
0
0
0.428571
false
false
13
b4464a25eefb417ab98231586c36be30c3ca2062
7,138,235,653,878
16de5f576c96f29ac97ff491c70959acdb0fa192
/mobs/Gelatinous_Cube.java
68c103c70688ed58504bde11d1eb95c3ff899e53
[]
no_license
Hunter-Bobeck/Flash_Mob
https://github.com/Hunter-Bobeck/Flash_Mob
4e8b538b375a8dad9d68a92cb2313c22b60cb8c4
2b59717f194ebfc63cabbc2ab6fc2183c598d200
refs/heads/master
2021-01-10T17:55:39.478000
2017-07-05T23:17:51
2017-07-05T23:17:51
44,571,691
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package mobs; import utilities.*; public class Gelatinous_Cube extends Mob { public Gelatinous_Cube() { large = true; unconscious = true; nonliving = true; health_min = 48; health_max = 112; health = Random.integer_from(health_min, health_max); fortitude = Function.line(health_min, 18, health_max, 22, health); agility = Random.integer_from(2, 4); block = fortitude + agility; strength = Function.line(health_min, 13, health_max, 15, health); damage_min = 1; damage_max = agility + strength; } }
UTF-8
Java
546
java
Gelatinous_Cube.java
Java
[]
null
[]
package mobs; import utilities.*; public class Gelatinous_Cube extends Mob { public Gelatinous_Cube() { large = true; unconscious = true; nonliving = true; health_min = 48; health_max = 112; health = Random.integer_from(health_min, health_max); fortitude = Function.line(health_min, 18, health_max, 22, health); agility = Random.integer_from(2, 4); block = fortitude + agility; strength = Function.line(health_min, 13, health_max, 15, health); damage_min = 1; damage_max = agility + strength; } }
546
0.659341
0.630037
29
17.862068
19.634108
68
false
false
0
0
0
0
0
0
2.241379
false
false
13
c543025e73cceadcf011831658da9e5d7e40ab1b
12,790,412,615,816
0bba0bac3865b2e70a0d268e9eba42c8de513a3c
/mantis-control-plane/mantis-control-plane-server/src/main/java/io/mantisrx/master/api/akka/route/v1/ParamName.java
4bd0b5994c93fbd03f2d19dc2c0af78f13ba468e
[ "Apache-2.0" ]
permissive
Netflix/mantis
https://github.com/Netflix/mantis
f5206c1d1a127ea76c4e47f31db4dd654ed620f9
cafbe81a6c22128cafbbb7b90b2d107501a28e44
refs/heads/master
2023-08-17T18:28:46.594000
2023-08-16T04:21:03
2023-08-16T04:21:03
190,664,284
1,393
197
Apache-2.0
false
2023-09-14T21:04:02
2019-06-06T23:44:48
2023-09-12T20:27:34
2023-09-14T21:04:00
27,325
1,345
170
81
Java
false
false
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.mantisrx.master.api.akka.route.v1; public class ParamName { public static String PROJECTION_FIELDS = "fields"; public static String PROJECTION_TARGET = "fromObj"; public static String SORT_BY = "sortBy"; public static String SORT_ASCENDING = "ascending"; public static String PAGINATION_LIMIT = "pageSize"; public static String PAGINATION_OFFSET = "offset"; public static String JOB_COMPACT = "compact"; public static String JOB_FILTER_MATCH = "matching"; public static String JOBCLUSTER_FILTER_MATCH = "matching"; public static String REASON = "reason"; public static String USER = "user"; public static String SEND_HEARTBEAT = "sendHB"; public static String ARCHIVED = "archived"; public static String SERVER_FILTER_LIMIT = "limit"; }
UTF-8
Java
1,406
java
ParamName.java
Java
[ { "context": "/*\n * Copyright 2019 Netflix, Inc.\n *\n * Licensed under the Apache License, Ve", "end": 28, "score": 0.7526872158050537, "start": 21, "tag": "NAME", "value": "Netflix" }, { "context": "ASON = \"reason\";\n public static String USER = \"user\";\n public static String SEND_HEARTBEAT = \"send", "end": 1244, "score": 0.992312490940094, "start": 1240, "tag": "USERNAME", "value": "user" } ]
null
[]
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.mantisrx.master.api.akka.route.v1; public class ParamName { public static String PROJECTION_FIELDS = "fields"; public static String PROJECTION_TARGET = "fromObj"; public static String SORT_BY = "sortBy"; public static String SORT_ASCENDING = "ascending"; public static String PAGINATION_LIMIT = "pageSize"; public static String PAGINATION_OFFSET = "offset"; public static String JOB_COMPACT = "compact"; public static String JOB_FILTER_MATCH = "matching"; public static String JOBCLUSTER_FILTER_MATCH = "matching"; public static String REASON = "reason"; public static String USER = "user"; public static String SEND_HEARTBEAT = "sendHB"; public static String ARCHIVED = "archived"; public static String SERVER_FILTER_LIMIT = "limit"; }
1,406
0.723329
0.716927
37
37
25.623047
75
false
false
0
0
0
0
0
0
0.567568
false
false
13
c93609d3fc7d0e5473b449f1df9e4f700396de69
19,937,238,196,442
33d2cb3de7eee7d47dc499a20037ae4f23d28fd0
/packages/apps/CAN/src/com/can/ui/CanChoose.java
40bb3b8be27eaae1ebcf6e64ea75e0efda77e95e
[]
no_license
lvxiaojia/yecon
https://github.com/lvxiaojia/yecon
0e139c9dddac12a71d55184bb10eaa658c3b906f
87658d255c405802d906be389353ef2b2e828d59
refs/heads/master
2020-05-18T05:31:19.781000
2018-06-07T05:11:17
2018-06-07T05:11:17
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.can.ui; import java.util.ArrayList; import com.can.activity.R; import com.can.assist.CanXml; import com.can.assist.CanXml.CarType_Info; import com.can.assist.CanXml.E_Update_Type; import com.can.ui.draw.AutoText; import com.can.ui.draw.PopDialog; import com.can.ui.draw.PopDialog.E_POPDIALOG_TYPE; import com.can.ui.draw.PopDialog.OnConfirmListener; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.os.PowerManager; import android.os.SystemProperties; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; /** * ClassName:CanChoose * * @function:车型选择界面 * @author Kim * @Date: 2016-6-4 上午9:32:54 * @Copyright: Copyright (c) 2016 * @version 1.0 */ public class CanChoose extends Activity implements OnClickListener, OnItemClickListener { private static CarType_Info mObjCarTypeInfo = null; protected final String TAG = this.getClass().getName(); protected final String CAN_ICON = "persist.sys.fun.canbus"; protected AutoText mObjTextCanBox = null; protected AutoText mObjTextCanSeries = null; protected AutoText mObjTextCanType = null; protected AutoText mObjTextCanCfg = null; protected Button mObjBtnCanBox = null; protected Button mObjBtnCanSeries = null; protected Button mObjBtnCanType = null; protected Button mObjBtnCanCfg = null; protected ListView mObjListInfo = null; protected listAdapter mObjlistAdapter = null; public ArrayList<String> mArrayList = new ArrayList<String>(); private E_Update_Type mEUpdateType = E_Update_Type.eUpdate_Type_None; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.choose); } @Override protected void onResume() { // TODO Auto-generated method stub super.onResume(); init(); } @Override public void onBackPressed() { // TODO Auto-generated method stub super.onBackPressed(); } @Override protected void onPause() { // TODO Auto-generated method stub this.finish(); super.onPause(); } private void init() { mObjCarTypeInfo = CanXml.getInfo(getApplicationContext()); mObjBtnCanBox = (Button) findViewById(R.id.btn_can_box); mObjBtnCanBox.setOnClickListener(this); mObjBtnCanSeries = (Button) findViewById(R.id.btn_can_line); mObjBtnCanSeries.setOnClickListener(this); mObjBtnCanType = (Button) findViewById(R.id.btn_can_type); mObjBtnCanType.setOnClickListener(this); mObjBtnCanCfg = (Button) findViewById(R.id.btn_can_cfg); mObjBtnCanCfg.setOnClickListener(this); Button ObjBtnSure = (Button) findViewById(R.id.btn_can_sure); ObjBtnSure.setOnClickListener(this); mObjTextCanBox = (AutoText) findViewById(R.id.tx_can_box_name); mObjTextCanSeries = (AutoText) findViewById(R.id.tx_can_line_name); mObjTextCanType = (AutoText) findViewById(R.id.tx_can_type_name); mObjTextCanCfg = (AutoText) findViewById(R.id.tx_can_cfg_name); mObjlistAdapter = new listAdapter(getApplicationContext()); mObjListInfo = (ListView) findViewById(R.id.list_can_info); mObjListInfo.setAdapter(mObjlistAdapter); mObjListInfo.setOnItemClickListener(this); boolean bret = false; Log.i(TAG, "++++++++++++++++++====:"+SystemProperties.getBoolean(CAN_ICON, bret)); CanXml.parseCanxml(this); setValue(null); } public class listAdapter extends BaseAdapter { private Context mObjContext; private LayoutInflater mObjInflater; public listAdapter(Context context) { // TODO Auto-generated constructor stub mObjContext = context; mObjInflater = (LayoutInflater) mObjContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @Override public int getCount() { // TODO Auto-generated method stub return mArrayList.size(); } @Override public Object getItem(int position) { // TODO Auto-generated method stub return mArrayList.get(position); } @Override public long getItemId(int position) { // TODO Auto-generated method stub return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub TextView objTextView; if (convertView == null) { convertView = mObjInflater.inflate(R.layout.choose_listview, null); objTextView = (TextView) convertView.findViewById(R.id.tx_list_info); convertView.setTag(objTextView); } else { objTextView = (TextView) convertView.getTag(); } if (objTextView != null) { objTextView.setText(mArrayList.get(position)); } return convertView; } } public void setValue(String strVal) { StringBuffer strText = new StringBuffer(); CarType_Info objCarTypeInfo = null; if (strVal != null) { switch (mEUpdateType) { case eUpdate_Type_CanBox: objCarTypeInfo = CanXml.getAttr(mEUpdateType, strVal, null, null); break; case eUpdate_Type_CanSeries: objCarTypeInfo = CanXml.getAttr(mEUpdateType, mObjTextCanBox.getText().toString(), strVal, null); break; case eUpdate_Type_CanType: objCarTypeInfo = CanXml.getAttr(mEUpdateType, mObjTextCanBox.getText().toString(), mObjTextCanSeries.getText().toString(), strVal); break; case eUpdate_Type_CanCfg: break; default: break; } } else { objCarTypeInfo = mObjCarTypeInfo; } if (objCarTypeInfo != null) { if (objCarTypeInfo.strBoxName != null) { strText.append(objCarTypeInfo.strBoxName.toString()); } mObjTextCanBox.setText(strText.toString()); strText.delete(0, strText.length()); if (objCarTypeInfo.strSeriesName != null) { strText.append(objCarTypeInfo.strSeriesName.toString()); } mObjTextCanSeries.setText(strText.toString()); strText.delete(0, strText.length()); if (objCarTypeInfo.strTypeName != null) { strText.append(objCarTypeInfo.strTypeName.toString()); } mObjTextCanType.setText(strText.toString()); strText.delete(0, strText.length()); if (objCarTypeInfo.strCfgName != null) { strText.append(objCarTypeInfo.strCfgName.toString()); } mObjTextCanCfg.setText(strText.toString()); } } private void sure() { if (!mObjCarTypeInfo.strBoxName.equals(mObjTextCanBox.getText().toString()) || !mObjCarTypeInfo.strSeriesName.equals(mObjTextCanSeries.getText().toString()) || !mObjCarTypeInfo.strTypeName.equals(mObjTextCanType.getText().toString()) || !mObjCarTypeInfo.strCfgName.equals(mObjTextCanCfg.getText().toString())) { // 比较是否选择相同的车型 条件是只要有一个不相等就认为要改变 CarType_Info objCarTypeInfo = CanXml.getAttr(mObjTextCanBox.getText().toString(), mObjTextCanSeries.getText().toString(), mObjTextCanType.getText().toString(), mObjTextCanCfg.getText().toString()); if (objCarTypeInfo != null) { //// 能到这里保证车型绝对是有效的 除非xml配置错误 // 设置波特率 // 设置桌面图标状态 SystemProperties.set(CAN_ICON, (objCarTypeInfo.iNeedIcon == 1) ? "1" : "0"); // 保存车型数据 if (CanXml.setCanDescribe(objCarTypeInfo)) { Log.i(TAG, "set CarTypeInfo: " + mObjTextCanBox.getText().toString() + " " + mObjTextCanSeries.getText().toString() + " " + mObjTextCanType.getText().toString() + " " + mObjTextCanCfg.getText().toString()); showTips(getResources().getString(R.string.tx_can_tips_str), true); } } }else { showTips(getResources().getString(R.string.tx_can_tips_same), false); } } @Override public void onClick(View v) { // TODO Auto-generated method stub int iID = v.getId(); switch (iID) { case R.id.btn_can_box: case R.id.btn_can_line: case R.id.btn_can_type: case R.id.btn_can_cfg: case R.id.btn_can_sure: setlist(iID); break; default: break; } } private void setlist(int iID) { boolean bChange = true; ArrayList<String> ObjArrayList = null; E_Update_Type eType = E_Update_Type.eUpdate_Type_None; switch (iID) { case R.id.btn_can_box: ObjArrayList = CanXml.getCanboxlist(); eType = E_Update_Type.eUpdate_Type_CanBox; break; case R.id.btn_can_line: ObjArrayList = CanXml.getCanSeries(mObjTextCanBox.getText().toString()); eType = E_Update_Type.eUpdate_Type_CanSeries; break; case R.id.btn_can_type: ObjArrayList = CanXml.getCanType(mObjTextCanBox.getText().toString(), mObjTextCanSeries.getText().toString()); eType = E_Update_Type.eUpdate_Type_CanType; break; case R.id.btn_can_cfg: ObjArrayList = CanXml.getCanCfg(); eType = E_Update_Type.eUpdate_Type_CanCfg; break; case R.id.btn_can_sure: bChange = false; sure(); break; default: bChange = false; break; } if (bChange) { if (!ObjArrayList.isEmpty()) { mEUpdateType = eType; mArrayList = ObjArrayList; mObjListInfo.setVisibility(View.VISIBLE); mObjlistAdapter.notifyDataSetChanged(); } else { Log.i(TAG, "ObjArrayList is empty!"); } } } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // TODO Auto-generated method stub setValue((String) mObjlistAdapter.getItem(position)); } private void showTips(String string, final boolean boff){ PopDialog dialog = new PopDialog(string, E_POPDIALOG_TYPE.ePopDialog_choose); dialog.setOnConfirmListener(new OnConfirmListener() { @Override public void onConfirm() { // TODO Auto-generated method stub if (boff) { PowerManager pManager=(PowerManager) getSystemService(Context.POWER_SERVICE); pManager.reboot(""); } } @Override public void onSelPos(int iPos) { // TODO Auto-generated method stub } @Override public void onSeekVal(int iVal) { // TODO Auto-generated method stub } }); dialog.show(getFragmentManager(), "sw"); } }
UTF-8
Java
10,230
java
CanChoose.java
Java
[ { "context": "sName:CanChoose\n * \n * @function:车型选择界面\n * @author Kim\n * @Date: 2016-6-4 上午9:32:54\n * @Copyright: Copyr", "end": 963, "score": 0.9987266659736633, "start": 960, "tag": "NAME", "value": "Kim" } ]
null
[]
package com.can.ui; import java.util.ArrayList; import com.can.activity.R; import com.can.assist.CanXml; import com.can.assist.CanXml.CarType_Info; import com.can.assist.CanXml.E_Update_Type; import com.can.ui.draw.AutoText; import com.can.ui.draw.PopDialog; import com.can.ui.draw.PopDialog.E_POPDIALOG_TYPE; import com.can.ui.draw.PopDialog.OnConfirmListener; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.os.PowerManager; import android.os.SystemProperties; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; /** * ClassName:CanChoose * * @function:车型选择界面 * @author Kim * @Date: 2016-6-4 上午9:32:54 * @Copyright: Copyright (c) 2016 * @version 1.0 */ public class CanChoose extends Activity implements OnClickListener, OnItemClickListener { private static CarType_Info mObjCarTypeInfo = null; protected final String TAG = this.getClass().getName(); protected final String CAN_ICON = "persist.sys.fun.canbus"; protected AutoText mObjTextCanBox = null; protected AutoText mObjTextCanSeries = null; protected AutoText mObjTextCanType = null; protected AutoText mObjTextCanCfg = null; protected Button mObjBtnCanBox = null; protected Button mObjBtnCanSeries = null; protected Button mObjBtnCanType = null; protected Button mObjBtnCanCfg = null; protected ListView mObjListInfo = null; protected listAdapter mObjlistAdapter = null; public ArrayList<String> mArrayList = new ArrayList<String>(); private E_Update_Type mEUpdateType = E_Update_Type.eUpdate_Type_None; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.choose); } @Override protected void onResume() { // TODO Auto-generated method stub super.onResume(); init(); } @Override public void onBackPressed() { // TODO Auto-generated method stub super.onBackPressed(); } @Override protected void onPause() { // TODO Auto-generated method stub this.finish(); super.onPause(); } private void init() { mObjCarTypeInfo = CanXml.getInfo(getApplicationContext()); mObjBtnCanBox = (Button) findViewById(R.id.btn_can_box); mObjBtnCanBox.setOnClickListener(this); mObjBtnCanSeries = (Button) findViewById(R.id.btn_can_line); mObjBtnCanSeries.setOnClickListener(this); mObjBtnCanType = (Button) findViewById(R.id.btn_can_type); mObjBtnCanType.setOnClickListener(this); mObjBtnCanCfg = (Button) findViewById(R.id.btn_can_cfg); mObjBtnCanCfg.setOnClickListener(this); Button ObjBtnSure = (Button) findViewById(R.id.btn_can_sure); ObjBtnSure.setOnClickListener(this); mObjTextCanBox = (AutoText) findViewById(R.id.tx_can_box_name); mObjTextCanSeries = (AutoText) findViewById(R.id.tx_can_line_name); mObjTextCanType = (AutoText) findViewById(R.id.tx_can_type_name); mObjTextCanCfg = (AutoText) findViewById(R.id.tx_can_cfg_name); mObjlistAdapter = new listAdapter(getApplicationContext()); mObjListInfo = (ListView) findViewById(R.id.list_can_info); mObjListInfo.setAdapter(mObjlistAdapter); mObjListInfo.setOnItemClickListener(this); boolean bret = false; Log.i(TAG, "++++++++++++++++++====:"+SystemProperties.getBoolean(CAN_ICON, bret)); CanXml.parseCanxml(this); setValue(null); } public class listAdapter extends BaseAdapter { private Context mObjContext; private LayoutInflater mObjInflater; public listAdapter(Context context) { // TODO Auto-generated constructor stub mObjContext = context; mObjInflater = (LayoutInflater) mObjContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @Override public int getCount() { // TODO Auto-generated method stub return mArrayList.size(); } @Override public Object getItem(int position) { // TODO Auto-generated method stub return mArrayList.get(position); } @Override public long getItemId(int position) { // TODO Auto-generated method stub return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub TextView objTextView; if (convertView == null) { convertView = mObjInflater.inflate(R.layout.choose_listview, null); objTextView = (TextView) convertView.findViewById(R.id.tx_list_info); convertView.setTag(objTextView); } else { objTextView = (TextView) convertView.getTag(); } if (objTextView != null) { objTextView.setText(mArrayList.get(position)); } return convertView; } } public void setValue(String strVal) { StringBuffer strText = new StringBuffer(); CarType_Info objCarTypeInfo = null; if (strVal != null) { switch (mEUpdateType) { case eUpdate_Type_CanBox: objCarTypeInfo = CanXml.getAttr(mEUpdateType, strVal, null, null); break; case eUpdate_Type_CanSeries: objCarTypeInfo = CanXml.getAttr(mEUpdateType, mObjTextCanBox.getText().toString(), strVal, null); break; case eUpdate_Type_CanType: objCarTypeInfo = CanXml.getAttr(mEUpdateType, mObjTextCanBox.getText().toString(), mObjTextCanSeries.getText().toString(), strVal); break; case eUpdate_Type_CanCfg: break; default: break; } } else { objCarTypeInfo = mObjCarTypeInfo; } if (objCarTypeInfo != null) { if (objCarTypeInfo.strBoxName != null) { strText.append(objCarTypeInfo.strBoxName.toString()); } mObjTextCanBox.setText(strText.toString()); strText.delete(0, strText.length()); if (objCarTypeInfo.strSeriesName != null) { strText.append(objCarTypeInfo.strSeriesName.toString()); } mObjTextCanSeries.setText(strText.toString()); strText.delete(0, strText.length()); if (objCarTypeInfo.strTypeName != null) { strText.append(objCarTypeInfo.strTypeName.toString()); } mObjTextCanType.setText(strText.toString()); strText.delete(0, strText.length()); if (objCarTypeInfo.strCfgName != null) { strText.append(objCarTypeInfo.strCfgName.toString()); } mObjTextCanCfg.setText(strText.toString()); } } private void sure() { if (!mObjCarTypeInfo.strBoxName.equals(mObjTextCanBox.getText().toString()) || !mObjCarTypeInfo.strSeriesName.equals(mObjTextCanSeries.getText().toString()) || !mObjCarTypeInfo.strTypeName.equals(mObjTextCanType.getText().toString()) || !mObjCarTypeInfo.strCfgName.equals(mObjTextCanCfg.getText().toString())) { // 比较是否选择相同的车型 条件是只要有一个不相等就认为要改变 CarType_Info objCarTypeInfo = CanXml.getAttr(mObjTextCanBox.getText().toString(), mObjTextCanSeries.getText().toString(), mObjTextCanType.getText().toString(), mObjTextCanCfg.getText().toString()); if (objCarTypeInfo != null) { //// 能到这里保证车型绝对是有效的 除非xml配置错误 // 设置波特率 // 设置桌面图标状态 SystemProperties.set(CAN_ICON, (objCarTypeInfo.iNeedIcon == 1) ? "1" : "0"); // 保存车型数据 if (CanXml.setCanDescribe(objCarTypeInfo)) { Log.i(TAG, "set CarTypeInfo: " + mObjTextCanBox.getText().toString() + " " + mObjTextCanSeries.getText().toString() + " " + mObjTextCanType.getText().toString() + " " + mObjTextCanCfg.getText().toString()); showTips(getResources().getString(R.string.tx_can_tips_str), true); } } }else { showTips(getResources().getString(R.string.tx_can_tips_same), false); } } @Override public void onClick(View v) { // TODO Auto-generated method stub int iID = v.getId(); switch (iID) { case R.id.btn_can_box: case R.id.btn_can_line: case R.id.btn_can_type: case R.id.btn_can_cfg: case R.id.btn_can_sure: setlist(iID); break; default: break; } } private void setlist(int iID) { boolean bChange = true; ArrayList<String> ObjArrayList = null; E_Update_Type eType = E_Update_Type.eUpdate_Type_None; switch (iID) { case R.id.btn_can_box: ObjArrayList = CanXml.getCanboxlist(); eType = E_Update_Type.eUpdate_Type_CanBox; break; case R.id.btn_can_line: ObjArrayList = CanXml.getCanSeries(mObjTextCanBox.getText().toString()); eType = E_Update_Type.eUpdate_Type_CanSeries; break; case R.id.btn_can_type: ObjArrayList = CanXml.getCanType(mObjTextCanBox.getText().toString(), mObjTextCanSeries.getText().toString()); eType = E_Update_Type.eUpdate_Type_CanType; break; case R.id.btn_can_cfg: ObjArrayList = CanXml.getCanCfg(); eType = E_Update_Type.eUpdate_Type_CanCfg; break; case R.id.btn_can_sure: bChange = false; sure(); break; default: bChange = false; break; } if (bChange) { if (!ObjArrayList.isEmpty()) { mEUpdateType = eType; mArrayList = ObjArrayList; mObjListInfo.setVisibility(View.VISIBLE); mObjlistAdapter.notifyDataSetChanged(); } else { Log.i(TAG, "ObjArrayList is empty!"); } } } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // TODO Auto-generated method stub setValue((String) mObjlistAdapter.getItem(position)); } private void showTips(String string, final boolean boff){ PopDialog dialog = new PopDialog(string, E_POPDIALOG_TYPE.ePopDialog_choose); dialog.setOnConfirmListener(new OnConfirmListener() { @Override public void onConfirm() { // TODO Auto-generated method stub if (boff) { PowerManager pManager=(PowerManager) getSystemService(Context.POWER_SERVICE); pManager.reboot(""); } } @Override public void onSelPos(int iPos) { // TODO Auto-generated method stub } @Override public void onSeekVal(int iVal) { // TODO Auto-generated method stub } }); dialog.show(getFragmentManager(), "sw"); } }
10,230
0.710119
0.707837
362
26.845304
23.931263
135
false
false
0
0
0
0
0
0
2.458564
false
false
13
0f237e94b0211b3e268f28c65932d0e35e75c883
27,247,272,530,849
90e59a6cf7ff74a818c575c8ccd93eeda9403659
/src/main/java/com/yancy/controller/showAccountController.java
b3c5fe0ed2b48f04deaf615b32a33c562e281381
[]
no_license
softwarexyy/springmvc
https://github.com/softwarexyy/springmvc
c6ec787afbef04bfb04f6441a5c6e6c3fabf066c
d4220caae184e1ef542027286d5829335c50950e
refs/heads/master
2020-04-09T08:49:01.507000
2019-03-16T14:45:21
2019-03-16T14:45:21
160,209,370
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.yancy.controller; import java.io.IOException; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.List; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.yancy.model.AccInfo; import com.yancy.model.User; import com.yancy.service.AccInfoService; /** * showAccount.jsp页面跳转至 我的账户 控制器 * * @author Yancy * */ @Controller public class showAccountController { @Resource private AccInfoService accInfoService; @RequestMapping(value = "/showAccount", method = RequestMethod.POST) public void showAccount(HttpServletRequest request, HttpServletResponse response, HttpSession session) { String username = request.getParameter("username"); System.out.println("showAccount传入的用户名:" + username); // 返回json数据 response.setContentType("application/json"); try { response.getWriter().println("{\"result\":\"success\"}"); // 拼装json报文 } catch (IOException e) { System.out.println(" ===== 返回response失败 ==== "); e.printStackTrace(); } } /** * 查询用户下挂账户 * @return 下挂账号的list列表 */ @RequestMapping(value = "/getSubAccount", method = RequestMethod.POST) @ResponseBody public List<String> getSubAccount(HttpServletRequest request) { List<String> list = new ArrayList<String>(); list = accInfoService.getSubAcc(request.getParameter("username")); return list; } /** * 查询某账号详细信息 * @param request * @return */ @RequestMapping(value = "/qrySubAccountInfo", method = RequestMethod.POST) @ResponseBody public AccInfo qrySubAccountInfo(HttpServletRequest request) { AccInfo accInfo = new AccInfo(); accInfo = accInfoService.getAccInfoDetail(request.getParameter("account")); return accInfo; } /** * 获取总财富值 * @param request * @return */ @RequestMapping(value = "/getSum", method = RequestMethod.POST) @ResponseBody public String getSum(HttpServletRequest request) { AccInfo accInfo = new AccInfo(); accInfo = accInfoService.getAccInfoDetail(request.getParameter("account")); double sum = accInfo.getCurrentDeposit() + accInfo.getFinacialDeposit() + accInfo.getTimeDeposit(); String sumFormat = new DecimalFormat(",###.##").format(sum); //格式化金额 return sumFormat; } }
UTF-8
Java
2,757
java
showAccountController.java
Java
[ { "context": "\n * showAccount.jsp页面跳转至 我的账户 控制器\r\n * \r\n * @author Yancy\r\n *\r\n */\r\n@Controller\r\npublic class showAccountCo", "end": 731, "score": 0.7435888051986694, "start": 726, "tag": "NAME", "value": "Yancy" } ]
null
[]
package com.yancy.controller; import java.io.IOException; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.List; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.yancy.model.AccInfo; import com.yancy.model.User; import com.yancy.service.AccInfoService; /** * showAccount.jsp页面跳转至 我的账户 控制器 * * @author Yancy * */ @Controller public class showAccountController { @Resource private AccInfoService accInfoService; @RequestMapping(value = "/showAccount", method = RequestMethod.POST) public void showAccount(HttpServletRequest request, HttpServletResponse response, HttpSession session) { String username = request.getParameter("username"); System.out.println("showAccount传入的用户名:" + username); // 返回json数据 response.setContentType("application/json"); try { response.getWriter().println("{\"result\":\"success\"}"); // 拼装json报文 } catch (IOException e) { System.out.println(" ===== 返回response失败 ==== "); e.printStackTrace(); } } /** * 查询用户下挂账户 * @return 下挂账号的list列表 */ @RequestMapping(value = "/getSubAccount", method = RequestMethod.POST) @ResponseBody public List<String> getSubAccount(HttpServletRequest request) { List<String> list = new ArrayList<String>(); list = accInfoService.getSubAcc(request.getParameter("username")); return list; } /** * 查询某账号详细信息 * @param request * @return */ @RequestMapping(value = "/qrySubAccountInfo", method = RequestMethod.POST) @ResponseBody public AccInfo qrySubAccountInfo(HttpServletRequest request) { AccInfo accInfo = new AccInfo(); accInfo = accInfoService.getAccInfoDetail(request.getParameter("account")); return accInfo; } /** * 获取总财富值 * @param request * @return */ @RequestMapping(value = "/getSum", method = RequestMethod.POST) @ResponseBody public String getSum(HttpServletRequest request) { AccInfo accInfo = new AccInfo(); accInfo = accInfoService.getAccInfoDetail(request.getParameter("account")); double sum = accInfo.getCurrentDeposit() + accInfo.getFinacialDeposit() + accInfo.getTimeDeposit(); String sumFormat = new DecimalFormat(",###.##").format(sum); //格式化金额 return sumFormat; } }
2,757
0.723429
0.723429
88
27.829546
26.381477
105
false
false
0
0
0
0
0
0
1.409091
false
false
13
9142449599fa829064ff9d898184ef4efa95da31
27,702,539,066,798
6a694b62647c48845f2c0b95849f8a0cadd53d34
/src/main/java/net/anglesmith/eudaemon/exception/EudaemonParsingException.java
670c5915d889f1e9592816b55065a49db599f5b6
[]
no_license
CorneliusAnglesmith/Eudaemon
https://github.com/CorneliusAnglesmith/Eudaemon
51ca1358fbfabcd999bf19d1b7318c78b312c406
c94a791823f22cddedfc389998d9c8d775e20fec
refs/heads/master
2023-04-04T12:32:31.463000
2023-03-30T16:49:51
2023-03-30T16:49:51
155,940,771
0
0
null
false
2023-03-30T16:49:52
2018-11-03T02:01:49
2020-01-18T15:48:17
2023-03-30T16:49:51
213
0
0
0
Java
false
false
package net.anglesmith.eudaemon.exception; /** * Thrown when specific parsing tasks (like those used by the "roll" command) fail irrecoverably. */ public class EudaemonParsingException extends EudaemonRuntimeException { public EudaemonParsingException(String message) { super(message); } public EudaemonParsingException(String message, Throwable cause) { super(message, cause); } }
UTF-8
Java
418
java
EudaemonParsingException.java
Java
[]
null
[]
package net.anglesmith.eudaemon.exception; /** * Thrown when specific parsing tasks (like those used by the "roll" command) fail irrecoverably. */ public class EudaemonParsingException extends EudaemonRuntimeException { public EudaemonParsingException(String message) { super(message); } public EudaemonParsingException(String message, Throwable cause) { super(message, cause); } }
418
0.736842
0.736842
14
28.857143
31.516111
97
false
false
0
0
0
0
0
0
0.357143
false
false
13
485c57613932322a93e6b36fbaa220267e31c232
30,451,318,134,701
22a849a44d6c8d2227169f742775ac1d0f28aadc
/common/src/main/java/com/yc/designpattern/decorator/Runner.java
3be9a8135ecfba2ec6fe7c47ad3f3f6e28f2a521
[]
no_license
yc637/java-learning
https://github.com/yc637/java-learning
a691f766862c5487e2d3141af91799db4d4e3efc
3781053d80bfa0717413be7e546f722a726c6914
refs/heads/master
2023-04-13T19:59:30.090000
2023-03-17T08:15:17
2023-03-17T08:15:17
183,981,664
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.yc.designpattern.decorator; /** * 装饰器模式测试运行类 * * @author yc * @date 2018年08月08日 10:10:27 */ public class Runner { public static void main(String[] args) { Component component = new ConcreteComponent(); ConcreteDecoratorA decoratorA = new ConcreteDecoratorA(component); decoratorA.method(); decoratorA.methodA(); ConcreteDecoratorB decoratorB = new ConcreteDecoratorB(component); decoratorB.method(); decoratorB.methodB(); System.out.println("----------------装饰器B对装饰器A(装饰器A对原始类进行了装饰)进行装饰--------------"); ConcreteDecoratorB decoratorB1 = new ConcreteDecoratorB(decoratorA); decoratorB1.method(); } }
UTF-8
Java
780
java
Runner.java
Java
[ { "context": "attern.decorator;\n\n/**\n * 装饰器模式测试运行类\n *\n * @author yc\n * @date 2018年08月08日 10:10:27\n */\npublic class Ru", "end": 75, "score": 0.9991844892501831, "start": 73, "tag": "USERNAME", "value": "yc" } ]
null
[]
package com.yc.designpattern.decorator; /** * 装饰器模式测试运行类 * * @author yc * @date 2018年08月08日 10:10:27 */ public class Runner { public static void main(String[] args) { Component component = new ConcreteComponent(); ConcreteDecoratorA decoratorA = new ConcreteDecoratorA(component); decoratorA.method(); decoratorA.methodA(); ConcreteDecoratorB decoratorB = new ConcreteDecoratorB(component); decoratorB.method(); decoratorB.methodB(); System.out.println("----------------装饰器B对装饰器A(装饰器A对原始类进行了装饰)进行装饰--------------"); ConcreteDecoratorB decoratorB1 = new ConcreteDecoratorB(decoratorA); decoratorB1.method(); } }
780
0.648305
0.625706
25
27.32
26.92318
89
false
false
0
0
0
0
0
0
0.44
false
false
13
80d3a58f06345df65ddd476111d7b459919a1c82
7,748,121,013,835
8721ed335effaf47754239d1ab8412fa531d6c9a
/src/main/java/com/gsr/myschool/front/client/web/application/inscription/popup/ConfirmationInscriptionPresenter.java
313e3609f9bbacd9c9bea8407e0885938e8c9c2c
[]
no_license
imrabti/myschool
https://github.com/imrabti/myschool
76dbc5ec3baeb8f91fc74bbe4a4b5258fcf7a139
f7e216617bd95cf77d875fbdd0ba9daec12fee97
refs/heads/master
2021-01-16T18:20:33.395000
2014-04-07T08:38:16
2014-04-07T08:38:16
7,561,397
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.gsr.myschool.front.client.web.application.inscription.popup; import com.google.gwt.event.shared.HasHandlers; import com.google.gwt.user.client.ui.Widget; import com.google.inject.Inject; import com.google.web.bindery.event.shared.EventBus; import com.gsr.myschool.front.client.web.application.inscription.event.DossierSubmitEvent; import com.gwtplatform.mvp.client.HasUiHandlers; import com.gwtplatform.mvp.client.PopupView; import com.gwtplatform.mvp.client.PresenterWidget; import com.gsr.myschool.front.client.web.application.inscription.popup.ConfirmationInscriptionPresenter.MyView; public class ConfirmationInscriptionPresenter extends PresenterWidget<MyView> implements ConfirmationInscriptionUiHandlers { public interface MyView extends PopupView, HasUiHandlers<ConfirmationInscriptionUiHandlers> { void initConfirmation(); } private HasHandlers source; @Inject public ConfirmationInscriptionPresenter(final EventBus eventBus, final MyView view) { super(eventBus, view); getView().setUiHandlers(this); } @Override public void validateInscription(Boolean agreeInformations) { DossierSubmitEvent.fire(source, agreeInformations); getView().hide(); } public void setSource(HasHandlers source) { this.source = source; } protected void onReveal() { getView().initConfirmation(); } }
UTF-8
Java
1,421
java
ConfirmationInscriptionPresenter.java
Java
[]
null
[]
package com.gsr.myschool.front.client.web.application.inscription.popup; import com.google.gwt.event.shared.HasHandlers; import com.google.gwt.user.client.ui.Widget; import com.google.inject.Inject; import com.google.web.bindery.event.shared.EventBus; import com.gsr.myschool.front.client.web.application.inscription.event.DossierSubmitEvent; import com.gwtplatform.mvp.client.HasUiHandlers; import com.gwtplatform.mvp.client.PopupView; import com.gwtplatform.mvp.client.PresenterWidget; import com.gsr.myschool.front.client.web.application.inscription.popup.ConfirmationInscriptionPresenter.MyView; public class ConfirmationInscriptionPresenter extends PresenterWidget<MyView> implements ConfirmationInscriptionUiHandlers { public interface MyView extends PopupView, HasUiHandlers<ConfirmationInscriptionUiHandlers> { void initConfirmation(); } private HasHandlers source; @Inject public ConfirmationInscriptionPresenter(final EventBus eventBus, final MyView view) { super(eventBus, view); getView().setUiHandlers(this); } @Override public void validateInscription(Boolean agreeInformations) { DossierSubmitEvent.fire(source, agreeInformations); getView().hide(); } public void setSource(HasHandlers source) { this.source = source; } protected void onReveal() { getView().initConfirmation(); } }
1,421
0.764251
0.764251
41
33.658535
30.552322
111
false
false
0
0
0
0
0
0
0.536585
false
false
13
21e2f53b945b2f745b7718ac7d2591f45bf5518d
7,748,121,012,045
d38629a33471977fbeb24d0d467d3f47044f7116
/drinkkikone/src/test/java/drinkkikone/tests/AinesosaTest.java
67ba22406721f195bfbccf49813d201917cd0897
[]
no_license
Savipulu/Bar-Kappas-Drinkkikone
https://github.com/Savipulu/Bar-Kappas-Drinkkikone
852af1ee583c056a827173ae41d18af034797f45
3c63a4e949f56bb3fca67e43a5c88d144be45f12
refs/heads/master
2021-01-17T17:46:11.224000
2016-03-20T23:42:07
2016-03-20T23:42:07
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package drinkkikone.tests; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; import drinkkikone.domain.Ainesosa; public class AinesosaTest { private Ainesosa ainesosa1; private Ainesosa ainesosa2; private Ainesosa ainesosa3; public AinesosaTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { ainesosa1 = new Ainesosa("Karpalolikööri", 22.0); ainesosa2 = new Ainesosa("Karpalolikööri", 28.0); ainesosa3 = new Ainesosa("Bailey's", 17.0); } @After public void tearDown() { } @Test public void konstruktoriAsettaaNimenOikein() { assertEquals("Karpalolikööri", ainesosa1.getNimi()); } @Test public void konstruktoriAsettaaAlkoholipitoisuudenOikein() { assertEquals(22.0, ainesosa1.getAlkoholipitoisuus(), 0.0001); } @Test public void toStringToimiiOikein() { assertEquals("Karpalolikööri", ainesosa1.toString()); } @Test public void equalsMetodiFalseJosNimetEri() { assertEquals(false, ainesosa1.equals(ainesosa3)); } @Test public void equalsMetodiTrueJosNimetSamat() { assertEquals(true, ainesosa1.equals(ainesosa2)); } }
UTF-8
Java
1,476
java
AinesosaTest.java
Java
[ { "context": "ööri\", 28.0);\n ainesosa3 = new Ainesosa(\"Bailey's\", 17.0);\n }\n \n @After\n public void ", "end": 732, "score": 0.5534907579421997, "start": 728, "tag": "NAME", "value": "iley" } ]
null
[]
package drinkkikone.tests; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; import drinkkikone.domain.Ainesosa; public class AinesosaTest { private Ainesosa ainesosa1; private Ainesosa ainesosa2; private Ainesosa ainesosa3; public AinesosaTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { ainesosa1 = new Ainesosa("Karpalolikööri", 22.0); ainesosa2 = new Ainesosa("Karpalolikööri", 28.0); ainesosa3 = new Ainesosa("Bailey's", 17.0); } @After public void tearDown() { } @Test public void konstruktoriAsettaaNimenOikein() { assertEquals("Karpalolikööri", ainesosa1.getNimi()); } @Test public void konstruktoriAsettaaAlkoholipitoisuudenOikein() { assertEquals(22.0, ainesosa1.getAlkoholipitoisuus(), 0.0001); } @Test public void toStringToimiiOikein() { assertEquals("Karpalolikööri", ainesosa1.toString()); } @Test public void equalsMetodiFalseJosNimetEri() { assertEquals(false, ainesosa1.equals(ainesosa3)); } @Test public void equalsMetodiTrueJosNimetSamat() { assertEquals(true, ainesosa1.equals(ainesosa2)); } }
1,476
0.65327
0.632834
63
22.285715
20.165527
69
false
false
0
0
0
0
0
0
0.444444
false
false
13
57346bd7468c4d60f2d8e8ef52fe3a4be493f85a
20,779,051,789,337
f2789ca0c264264ef0b173e6a61c0d687821e40f
/src/test/java/com/gnp/autos/wsp/emisor/eot/movimiento/CabeceraReqTest.java
e29b0db46f377c23870c8f6e9de2a400e4e280bd
[]
no_license
JavoMosso/javaMicroserviceEmision
https://github.com/JavoMosso/javaMicroserviceEmision
69302c6650cae7a6fb88548f935a063885a1941d
8cb93bba3651f296b380cbb431573cc7dd2f20ae
refs/heads/master
2020-12-08T05:35:12.256000
2020-01-09T20:40:23
2020-01-09T20:40:23
232,900,212
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.gnp.autos.wsp.emisor.eot.movimiento; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.MockitoAnnotations; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.util.ReflectionTestUtils; @RunWith(SpringRunner.class) public class CabeceraReqTest { /* Clase Test. */ @InjectMocks private static CabeceraReq base; @InjectMocks private static CabeceraReq equal; @InjectMocks private static CabeceraReq notEqual; @InjectMocks private static CabeceraReq nulo; @InjectMocks private static CabeceraReq object3; @Before public void initMocks() { base = new CabeceraReq(); ReflectionTestUtils.setField(base, "idTransaccion", "idTransaccion"); ReflectionTestUtils.setField(base, "cveTransaccion", "cveTransaccion"); ReflectionTestUtils.setField(base, "idActor", "idActor"); ReflectionTestUtils.setField(base, "idRol", "idRol"); ReflectionTestUtils.setField(base, "idPerfil", "idPerfil"); equal = new CabeceraReq(); ReflectionTestUtils.setField(equal, "idTransaccion", base.getIdTransaccion()); ReflectionTestUtils.setField(equal, "cveTransaccion", base.getCveTransaccion()); ReflectionTestUtils.setField(equal, "idActor", base.getIdActor()); ReflectionTestUtils.setField(equal, "idRol", base.getIdRol()); ReflectionTestUtils.setField(equal, "idPerfil", base.getIdPerfil()); notEqual = new CabeceraReq(); ReflectionTestUtils.setField(notEqual, "idTransaccion", "idTransaccionnot"); ReflectionTestUtils.setField(notEqual, "cveTransaccion", "cveTransaccionnot"); ReflectionTestUtils.setField(notEqual, "idActor", "idActornot"); ReflectionTestUtils.setField(notEqual, "idRol", "idRolnot"); ReflectionTestUtils.setField(notEqual, "idPerfil", "idPerfilnot"); nulo = null; object3 = new CabeceraReq(); ReflectionTestUtils.setField(object3, "idTransaccion", base.getIdTransaccion()); ReflectionTestUtils.setField(object3, "cveTransaccion", base.getCveTransaccion()); ReflectionTestUtils.setField(object3, "idActor", base.getIdActor()); ReflectionTestUtils.setField(object3, "idRol", base.getIdRol()); ReflectionTestUtils.setField(object3, "idPerfil", base.getIdPerfil()); MockitoAnnotations.initMocks(this); } @Test public void test() { base.setIdTransaccion("idTransaccion"); assertNotNull(base.getIdTransaccion()); base.setCveTransaccion("cveTransaccion"); assertNotNull(base.getCveTransaccion()); base.setIdActor("idActor"); assertNotNull(base.getIdActor()); base.setIdRol("idRol"); assertNotNull(base.getIdRol()); base.setIdPerfil("idPerfil"); assertNotNull(base.getIdPerfil()); } @Test public void testEquals() { assertEquals("idTransaccion", base.getIdTransaccion()); assertEquals(base, equal); assertEquals(base.hashCode(), base.hashCode()); assertEquals(base.hashCode(), equal.hashCode()); } @Test public void testDifferent() { assertNotEquals("idTransaccionnot", base.getIdTransaccion()); assertNotEquals(base, notEqual); assertNotEquals(base.hashCode(), notEqual.hashCode()); assertNotEquals(base.hashCode(), nulo); } @Test public void testAssert() { assertTrue(base.canEqual(base)); assertTrue(base.equals(base)); assertTrue(base.canEqual(equal)); assertTrue(base.equals(equal)); } @Test public void testDeny() { assertFalse(base.equals(notEqual)); assertFalse(base.equals(null)); } @Test public void testNull() { nulo.setIdTransaccion(null); assertNull(nulo.getIdTransaccion()); } @Test public void testNotNull() { assertNotNull(base); assertNotNull(base.toString()); } @Test public void testReflexive() { assertEquals(base, base); } @Test public void testSymmetric() { assertEquals(base, equal); assertEquals(equal, base); } @Test public void testTransitive() { assertEquals(base, equal); assertEquals(equal, object3); assertEquals(base, object3); } }
UTF-8
Java
4,761
java
CabeceraReqTest.java
Java
[]
null
[]
package com.gnp.autos.wsp.emisor.eot.movimiento; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.MockitoAnnotations; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.util.ReflectionTestUtils; @RunWith(SpringRunner.class) public class CabeceraReqTest { /* Clase Test. */ @InjectMocks private static CabeceraReq base; @InjectMocks private static CabeceraReq equal; @InjectMocks private static CabeceraReq notEqual; @InjectMocks private static CabeceraReq nulo; @InjectMocks private static CabeceraReq object3; @Before public void initMocks() { base = new CabeceraReq(); ReflectionTestUtils.setField(base, "idTransaccion", "idTransaccion"); ReflectionTestUtils.setField(base, "cveTransaccion", "cveTransaccion"); ReflectionTestUtils.setField(base, "idActor", "idActor"); ReflectionTestUtils.setField(base, "idRol", "idRol"); ReflectionTestUtils.setField(base, "idPerfil", "idPerfil"); equal = new CabeceraReq(); ReflectionTestUtils.setField(equal, "idTransaccion", base.getIdTransaccion()); ReflectionTestUtils.setField(equal, "cveTransaccion", base.getCveTransaccion()); ReflectionTestUtils.setField(equal, "idActor", base.getIdActor()); ReflectionTestUtils.setField(equal, "idRol", base.getIdRol()); ReflectionTestUtils.setField(equal, "idPerfil", base.getIdPerfil()); notEqual = new CabeceraReq(); ReflectionTestUtils.setField(notEqual, "idTransaccion", "idTransaccionnot"); ReflectionTestUtils.setField(notEqual, "cveTransaccion", "cveTransaccionnot"); ReflectionTestUtils.setField(notEqual, "idActor", "idActornot"); ReflectionTestUtils.setField(notEqual, "idRol", "idRolnot"); ReflectionTestUtils.setField(notEqual, "idPerfil", "idPerfilnot"); nulo = null; object3 = new CabeceraReq(); ReflectionTestUtils.setField(object3, "idTransaccion", base.getIdTransaccion()); ReflectionTestUtils.setField(object3, "cveTransaccion", base.getCveTransaccion()); ReflectionTestUtils.setField(object3, "idActor", base.getIdActor()); ReflectionTestUtils.setField(object3, "idRol", base.getIdRol()); ReflectionTestUtils.setField(object3, "idPerfil", base.getIdPerfil()); MockitoAnnotations.initMocks(this); } @Test public void test() { base.setIdTransaccion("idTransaccion"); assertNotNull(base.getIdTransaccion()); base.setCveTransaccion("cveTransaccion"); assertNotNull(base.getCveTransaccion()); base.setIdActor("idActor"); assertNotNull(base.getIdActor()); base.setIdRol("idRol"); assertNotNull(base.getIdRol()); base.setIdPerfil("idPerfil"); assertNotNull(base.getIdPerfil()); } @Test public void testEquals() { assertEquals("idTransaccion", base.getIdTransaccion()); assertEquals(base, equal); assertEquals(base.hashCode(), base.hashCode()); assertEquals(base.hashCode(), equal.hashCode()); } @Test public void testDifferent() { assertNotEquals("idTransaccionnot", base.getIdTransaccion()); assertNotEquals(base, notEqual); assertNotEquals(base.hashCode(), notEqual.hashCode()); assertNotEquals(base.hashCode(), nulo); } @Test public void testAssert() { assertTrue(base.canEqual(base)); assertTrue(base.equals(base)); assertTrue(base.canEqual(equal)); assertTrue(base.equals(equal)); } @Test public void testDeny() { assertFalse(base.equals(notEqual)); assertFalse(base.equals(null)); } @Test public void testNull() { nulo.setIdTransaccion(null); assertNull(nulo.getIdTransaccion()); } @Test public void testNotNull() { assertNotNull(base); assertNotNull(base.toString()); } @Test public void testReflexive() { assertEquals(base, base); } @Test public void testSymmetric() { assertEquals(base, equal); assertEquals(equal, base); } @Test public void testTransitive() { assertEquals(base, equal); assertEquals(equal, object3); assertEquals(base, object3); } }
4,761
0.675698
0.673598
134
34.52985
23.949165
90
false
false
0
0
0
0
0
0
0.992537
false
false
13
a655ccd01a0e66f63cec9dd3360d5cce5f81f72a
5,763,846,128,501
f6a3bed6eb27bf70c26356bd5ebbff63d53f129b
/src/java/compus/model/compusBean.java
65be13dfed20e1b1d6dfef7c4415b46eff866f15
[]
no_license
mutabazimat/campus-recruitment
https://github.com/mutabazimat/campus-recruitment
83d51b409e2a41aac5de354b1fafb6598ed84c75
624a99a0eb6e3606a9576359b9789b6262e4beff
refs/heads/master
2020-05-03T02:14:08.990000
2019-03-29T08:38:20
2019-03-29T08:38:20
178,363,286
0
0
null
false
2019-03-29T08:38:21
2019-03-29T08:22:09
2019-03-29T08:28:52
2019-03-29T08:38:20
0
0
0
0
null
false
null
package compus.model; /** * * @author Matthew */ public class compusBean { }
UTF-8
Java
87
java
compusBean.java
Java
[ { "context": "\npackage compus.model;\n\n/**\n *\n * @author Matthew\n */\npublic class compusBean {\n \n}\n", "end": 49, "score": 0.9997392892837524, "start": 42, "tag": "NAME", "value": "Matthew" } ]
null
[]
package compus.model; /** * * @author Matthew */ public class compusBean { }
87
0.597701
0.597701
9
8.555555
9.250959
25
false
false
0
0
0
0
0
0
0.111111
false
false
13
1c687811aa28be3c855b01afe111ebfe134f5b14
7,352,984,016,117
dc34931e5e58ddb93e414193241860be2cd83827
/src/UML/Situacao.java
b9f0a6f0e939ead32de7003d1a4dab9e37ee367f
[]
no_license
alcalcides/treinamentosJava
https://github.com/alcalcides/treinamentosJava
63785112bd7a5a0b46748d8954532187258bb1fd
8bdee0227e62422815d4ecbe78effd0b62654fc3
refs/heads/master
2023-06-24T03:38:40.745000
2021-07-24T20:13:45
2021-07-24T20:13:45
363,304,111
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package UML; public enum Situacao { FERIAS, DEMITIDO, ATIVO, AFASTADO; }
UTF-8
Java
79
java
Situacao.java
Java
[]
null
[]
package UML; public enum Situacao { FERIAS, DEMITIDO, ATIVO, AFASTADO; }
79
0.696203
0.696203
9
7.777778
6.646265
22
false
false
0
0
0
0
0
0
1
false
false
13
777b78a41c2c1f0c10ce16913692f047caff285f
11,244,224,449,804
89af70db2be39ce9051a625f29eeb41089a785bd
/Contests/Codeforces/DivCmb_413E.java
25e521f9daa69e002e876c2ea6baec7ea3486bb7
[]
no_license
bit24/USACO
https://github.com/bit24/USACO
b5ddcb1423aecb3ae775e44365dcbb1f7cbc96e1
7c03ac997f0a9b0ba77cf4731e011003bfe89aaf
refs/heads/master
2020-04-15T00:50:54.053000
2020-04-11T00:48:45
2020-04-11T00:48:45
51,056,374
6
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collections; import java.util.PriorityQueue; import java.util.StringTokenizer; public class DivCmb_413E { @SuppressWarnings("unchecked") public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer inputData = new StringTokenizer(reader.readLine()); final int numO = Integer.parseInt(inputData.nextToken()); final int numTR = Integer.parseInt(inputData.nextToken()); final int numLR = Integer.parseInt(inputData.nextToken()); int[] cost = new int[numO]; inputData = new StringTokenizer(reader.readLine()); for (int i = 0; i < numO; i++) { cost[i] = Integer.parseInt(inputData.nextToken()); } boolean[][] like = new boolean[numO][2]; for (int i = 0; i < 2; i++) { int numI = Integer.parseInt(reader.readLine()); inputData = new StringTokenizer(reader.readLine()); for (int j = 0; j < numI; j++) { like[Integer.parseInt(inputData.nextToken()) - 1][i] = true; } } reader.close(); ArrayList<Integer>[] sLike = new ArrayList[] { new ArrayList<Integer>(), new ArrayList<Integer>() }; ArrayList<Integer> bLike = new ArrayList<Integer>(); PriorityQueue<Integer> nQueue = new PriorityQueue<Integer>(); for (int i = 0; i < numO; i++) { if (like[i][0] && like[i][1]) { bLike.add(cost[i]); } else if (!like[i][0] && !like[i][1]) { nQueue.add(cost[i]); } else { sLike[like[i][0] ? 0 : 1].add(cost[i]); } } Collections.sort(sLike[0]); Collections.sort(sLike[1]); Collections.sort(bLike); ArrayDeque<Integer> bQueue = new ArrayDeque<Integer>(bLike); ArrayDeque<Integer>[] sQueue = new ArrayDeque[] { new ArrayDeque<Integer>(sLike[0]), new ArrayDeque<Integer>(sLike[1]) }; ArrayDeque<Integer>[] cItems = new ArrayDeque[] { new ArrayDeque<Integer>(), new ArrayDeque<Integer>(), new ArrayDeque<Integer>() }; long cCost = 0; int bLR = (int) max(0L, ((long) numTR) - sQueue[0].size() - sQueue[1].size() - nQueue.size(), ((long) numLR) - sQueue[0].size(), ((long) numLR) - sQueue[1].size(), 2L * numLR - numTR); assert (bLR >= 0); if (bLR > bQueue.size() || bLR > numTR) { System.out.println(-1); return; } for (int i = 0; i < bLR; i++) { cCost += bQueue.remove(); } for (int i = 0; i < 2; i++) { assert (sQueue[i].size() >= numLR - bLR); for (int j = bLR; j < numLR; j++) { int nx = sQueue[i].remove(); cItems[i].add(nx); cCost += nx; } nQueue.addAll(sQueue[i]); } for (int i = 0; i < ((long) numTR) - bLR - cItems[0].size() - cItems[1].size(); i++) { int nItem = nQueue.remove(); cCost += nItem; cItems[2].add(nItem); } while (!bQueue.isEmpty()) { int nx = bQueue.remove(); int rep1 = 0; for (int i = 0; i < 3; i++) { if (!cItems[i].isEmpty() && rep1 < cItems[i].getLast() - nx) { rep1 = cItems[i].getLast() - nx; } } if (!cItems[0].isEmpty() && !cItems[1].isEmpty() && !nQueue.isEmpty() && ((long) cItems[0].getLast()) + cItems[1].getLast() - nx - nQueue.peek() > rep1) { if (((long) cItems[0].getLast()) + cItems[1].getLast() - nx - nQueue.peek() <= 0) { break; } cCost += ((long) -cItems[0].getLast()) - cItems[1].getLast() + nx + nQueue.remove(); nQueue.add(cItems[0].removeLast()); nQueue.add(cItems[1].removeLast()); } else { if (rep1 <= 0) { break; } for (int i = 0; i < 3; i++) { if (!cItems[i].isEmpty() && rep1 == cItems[i].getLast() - nx) { int rem = cItems[i].removeLast(); cCost += ((long) -rem) + nx; nQueue.add(rem); break; } } } } assert (cCost != -1); if (cCost == -1) { throw new RuntimeException(); } System.out.println(cCost); } static long max(long... items) { long max = items[0]; for (long i : items) { if (i > max) { max = i; } } return max; } }
UTF-8
Java
4,062
java
DivCmb_413E.java
Java
[]
null
[]
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collections; import java.util.PriorityQueue; import java.util.StringTokenizer; public class DivCmb_413E { @SuppressWarnings("unchecked") public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer inputData = new StringTokenizer(reader.readLine()); final int numO = Integer.parseInt(inputData.nextToken()); final int numTR = Integer.parseInt(inputData.nextToken()); final int numLR = Integer.parseInt(inputData.nextToken()); int[] cost = new int[numO]; inputData = new StringTokenizer(reader.readLine()); for (int i = 0; i < numO; i++) { cost[i] = Integer.parseInt(inputData.nextToken()); } boolean[][] like = new boolean[numO][2]; for (int i = 0; i < 2; i++) { int numI = Integer.parseInt(reader.readLine()); inputData = new StringTokenizer(reader.readLine()); for (int j = 0; j < numI; j++) { like[Integer.parseInt(inputData.nextToken()) - 1][i] = true; } } reader.close(); ArrayList<Integer>[] sLike = new ArrayList[] { new ArrayList<Integer>(), new ArrayList<Integer>() }; ArrayList<Integer> bLike = new ArrayList<Integer>(); PriorityQueue<Integer> nQueue = new PriorityQueue<Integer>(); for (int i = 0; i < numO; i++) { if (like[i][0] && like[i][1]) { bLike.add(cost[i]); } else if (!like[i][0] && !like[i][1]) { nQueue.add(cost[i]); } else { sLike[like[i][0] ? 0 : 1].add(cost[i]); } } Collections.sort(sLike[0]); Collections.sort(sLike[1]); Collections.sort(bLike); ArrayDeque<Integer> bQueue = new ArrayDeque<Integer>(bLike); ArrayDeque<Integer>[] sQueue = new ArrayDeque[] { new ArrayDeque<Integer>(sLike[0]), new ArrayDeque<Integer>(sLike[1]) }; ArrayDeque<Integer>[] cItems = new ArrayDeque[] { new ArrayDeque<Integer>(), new ArrayDeque<Integer>(), new ArrayDeque<Integer>() }; long cCost = 0; int bLR = (int) max(0L, ((long) numTR) - sQueue[0].size() - sQueue[1].size() - nQueue.size(), ((long) numLR) - sQueue[0].size(), ((long) numLR) - sQueue[1].size(), 2L * numLR - numTR); assert (bLR >= 0); if (bLR > bQueue.size() || bLR > numTR) { System.out.println(-1); return; } for (int i = 0; i < bLR; i++) { cCost += bQueue.remove(); } for (int i = 0; i < 2; i++) { assert (sQueue[i].size() >= numLR - bLR); for (int j = bLR; j < numLR; j++) { int nx = sQueue[i].remove(); cItems[i].add(nx); cCost += nx; } nQueue.addAll(sQueue[i]); } for (int i = 0; i < ((long) numTR) - bLR - cItems[0].size() - cItems[1].size(); i++) { int nItem = nQueue.remove(); cCost += nItem; cItems[2].add(nItem); } while (!bQueue.isEmpty()) { int nx = bQueue.remove(); int rep1 = 0; for (int i = 0; i < 3; i++) { if (!cItems[i].isEmpty() && rep1 < cItems[i].getLast() - nx) { rep1 = cItems[i].getLast() - nx; } } if (!cItems[0].isEmpty() && !cItems[1].isEmpty() && !nQueue.isEmpty() && ((long) cItems[0].getLast()) + cItems[1].getLast() - nx - nQueue.peek() > rep1) { if (((long) cItems[0].getLast()) + cItems[1].getLast() - nx - nQueue.peek() <= 0) { break; } cCost += ((long) -cItems[0].getLast()) - cItems[1].getLast() + nx + nQueue.remove(); nQueue.add(cItems[0].removeLast()); nQueue.add(cItems[1].removeLast()); } else { if (rep1 <= 0) { break; } for (int i = 0; i < 3; i++) { if (!cItems[i].isEmpty() && rep1 == cItems[i].getLast() - nx) { int rem = cItems[i].removeLast(); cCost += ((long) -rem) + nx; nQueue.add(rem); break; } } } } assert (cCost != -1); if (cCost == -1) { throw new RuntimeException(); } System.out.println(cCost); } static long max(long... items) { long max = items[0]; for (long i : items) { if (i > max) { max = i; } } return max; } }
4,062
0.592565
0.577056
148
26.445946
25.850737
105
false
false
0
0
0
0
0
0
2.831081
false
false
13
acd595b4baddac19eceb52d4c7423ceb61605fd2
22,643,067,592,558
52dc9d80b9ac0fd076608bab443cc465c16f5bd4
/benchmark/src/main/java/de/tub/dima/babelfish/benchmark/parser/ArrowCSVImporter.java
338ea044615289b62c34a2115364f083ff37f5d1
[ "Apache-2.0" ]
permissive
TU-Berlin-DIMA/babelfish
https://github.com/TU-Berlin-DIMA/babelfish
9316ac56b6b85166babdf1ca26aba92a8a7dadcf
4926384d994ab4ab324a056d69be64d9b52ed7a0
refs/heads/master
2023-08-15T09:59:04.259000
2021-10-20T08:17:51
2021-10-20T08:17:51
415,998,147
11
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package de.tub.dima.babelfish.benchmark.parser; import de.tub.dima.babelfish.benchmark.datatypes.Lineitem; import de.tub.dima.babelfish.benchmark.tcph.BufferDump; import de.tub.dima.babelfish.storage.Buffer; import de.tub.dima.babelfish.storage.BufferManager; import de.tub.dima.babelfish.storage.Catalog; import de.tub.dima.babelfish.storage.Unit; import de.tub.dima.babelfish.storage.layout.*; import de.tub.dima.babelfish.typesytem.record.LuthRecord; import de.tub.dima.babelfish.typesytem.record.Record; import de.tub.dima.babelfish.typesytem.record.RecordUtil; import de.tub.dima.babelfish.typesytem.record.SchemaExtractionException; import de.tub.dima.babelfish.typesytem.schema.Schema; import de.tub.dima.babelfish.typesytem.schema.field.DateField; import de.tub.dima.babelfish.typesytem.schema.field.NumericField; import de.tub.dima.babelfish.typesytem.schema.field.SchemaField; import de.tub.dima.babelfish.typesytem.schema.field.TextField; import de.tub.dima.babelfish.typesytem.udt.Date; import de.tub.dima.babelfish.typesytem.valueTypes.Char; import de.tub.dima.babelfish.typesytem.valueTypes.number.integer.Int_16; import de.tub.dima.babelfish.typesytem.valueTypes.number.integer.Int_32; import de.tub.dima.babelfish.typesytem.valueTypes.number.integer.Int_64; import de.tub.dima.babelfish.typesytem.valueTypes.number.integer.Int_8; import de.tub.dima.babelfish.typesytem.valueTypes.number.numeric.Numeric; import de.tub.dima.babelfish.typesytem.valueTypes.number.numeric.Precision; import de.tub.dima.babelfish.typesytem.variableLengthType.MaxLength; import de.tub.dima.babelfish.typesytem.variableLengthType.StringText; import de.tub.dima.babelfish.typesytem.variableLengthType.Text; import org.apache.arrow.memory.RootAllocator; import org.apache.arrow.vector.*; import org.apache.arrow.vector.types.pojo.Field; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.LineNumberReader; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.function.BiConsumer; public class ArrowCSVImporter { public static void importArrow(String path, RootAllocator allocator) throws IOException, SchemaExtractionException { BufferManager bufferManager = new BufferManager(); // import lineorder.tbl importTable(bufferManager, path + "lineitem.tbl", "table.lineitem", CSVLineitem.class, new BiConsumer<List<String>, List<FieldVector>>() { @Override public void accept(List<String> fields, List<FieldVector> fieldVectors) { int currentCount = fieldVectors.get(0).getValueCount(); IntVector field_0 = (IntVector) fieldVectors.get(0); field_0.setSafe(currentCount, Integer.valueOf(fields.get(0))); fieldVectors.get(0).setValueCount(currentCount + 1); IntVector field_1 = (IntVector) fieldVectors.get(1); field_1.setSafe(currentCount, Integer.valueOf(fields.get(1))); IntVector field_2 = (IntVector) fieldVectors.get(2); field_2.setSafe(currentCount, Integer.valueOf(fields.get(2))); IntVector field_3 = (IntVector) fieldVectors.get(3); field_3.setSafe(currentCount, Integer.valueOf(fields.get(3))); DecimalVector field_4 = (DecimalVector) fieldVectors.get(4); field_4.setSafe(currentCount, (long) (Float.valueOf(fields.get(4)) * 100)); DecimalVector field_5 = (DecimalVector) fieldVectors.get(5); field_5.setSafe(currentCount, (long) (Float.valueOf(fields.get(5)) * 100)); DecimalVector field_6 = (DecimalVector) fieldVectors.get(6); field_6.setSafe(currentCount, (long) (Float.valueOf(fields.get(6)) * 100)); DecimalVector field_7 = (DecimalVector) fieldVectors.get(7); field_7.setSafe(currentCount, (long) (Float.valueOf(fields.get(7)) * 100)); TimeMilliVector field_10 = (TimeMilliVector) fieldVectors.get(10); field_10.setSafe(currentCount, Date.parse(fields.get(10))); TimeMilliVector field_11 = (TimeMilliVector) fieldVectors.get(11); field_11.setSafe(currentCount, Date.parse(fields.get(11))); TimeMilliVector field_12 = (TimeMilliVector) fieldVectors.get(12); field_12.setSafe(currentCount, Date.parse(fields.get(12))); VarCharVector field_13 = (VarCharVector) fieldVectors.get(13); field_13.setSafe(currentCount, new org.apache.arrow.vector.util.Text(fields.get(13))); VarCharVector field_14 = (VarCharVector) fieldVectors.get(14); field_14.setSafe(currentCount, new org.apache.arrow.vector.util.Text(fields.get(14))); VarCharVector field_15 = (VarCharVector) fieldVectors.get(15); field_15.setSafe(currentCount, new org.apache.arrow.vector.util.Text(fields.get(15))); } }, "\\|", false, allocator); importTable(bufferManager, path + "customer.tbl", "table.customer", CSVCustomer.class, new BiConsumer<List<String>, List<FieldVector>>() { @Override public void accept(List<String> fields, List<FieldVector> fieldVectors) { int currentCount = fieldVectors.get(0).getValueCount(); IntVector field_0 = (IntVector) fieldVectors.get(0); field_0.setSafe(currentCount, Integer.valueOf(fields.get(0))); fieldVectors.get(0).setValueCount(currentCount + 1); // c_name VarCharVector field_1 = (VarCharVector) fieldVectors.get(1); field_1.setSafe(currentCount, new org.apache.arrow.vector.util.Text(fields.get(1))); // c_address VarCharVector field_2 = (VarCharVector) fieldVectors.get(2); field_2.setSafe(currentCount, new org.apache.arrow.vector.util.Text(fields.get(2))); // c_nationke IntVector field_3 = (IntVector) fieldVectors.get(3); field_3.setSafe(currentCount, Integer.valueOf(fields.get(3))); // c_phone VarCharVector field_4 = (VarCharVector) fieldVectors.get(4); field_4.setSafe(currentCount, new org.apache.arrow.vector.util.Text(fields.get(4))); // c_acctbal DecimalVector field_5 = (DecimalVector) fieldVectors.get(5); field_5.setSafe(currentCount, (long) (Float.valueOf(fields.get(5)) * 100)); // c_mktsegment VarCharVector field_6 = (VarCharVector) fieldVectors.get(6); field_6.setSafe(currentCount, new org.apache.arrow.vector.util.Text(new StringText(fields.get(6), 10).toString())); // c_comment VarCharVector field_7 = (VarCharVector) fieldVectors.get(7); field_7.setSafe(currentCount, new org.apache.arrow.vector.util.Text(fields.get(7))); } }, "\\|", false, allocator); importTable(bufferManager, path + "orders.tbl", "table.orders", CSVOrders.class, new BiConsumer<List<String>, List<FieldVector>>() { @Override public void accept(List<String> fields, List<FieldVector> fieldVectors) { // o_orderkey int currentCount = fieldVectors.get(0).getValueCount(); IntVector field_0 = (IntVector) fieldVectors.get(0); field_0.setSafe(currentCount, Integer.valueOf(fields.get(0))); fieldVectors.get(0).setValueCount(currentCount + 1); // o_custkey IntVector field_1 = (IntVector) fieldVectors.get(1); field_1.setSafe(currentCount, Integer.valueOf(fields.get(1))); // o_orderstatus VarCharVector field_2 = (VarCharVector) fieldVectors.get(2); field_2.setSafe(currentCount, new org.apache.arrow.vector.util.Text(fields.get(2))); // o_totalprice DecimalVector field_3 = (DecimalVector) fieldVectors.get(3); field_3.setSafe(currentCount, (long) (Float.valueOf(fields.get(3)) * 100)); // o_orderdate TimeMilliVector field_4 = (TimeMilliVector) fieldVectors.get(4); field_4.setSafe(currentCount, Date.parse(fields.get(4))); // o_orderpriority VarCharVector field_5 = (VarCharVector) fieldVectors.get(5); field_5.setSafe(currentCount, new org.apache.arrow.vector.util.Text(fields.get(5))); // o_clerk VarCharVector field_6 = (VarCharVector) fieldVectors.get(6); field_6.setSafe(currentCount, new org.apache.arrow.vector.util.Text(fields.get(6))); // o_shippriority IntVector field_7 = (IntVector) fieldVectors.get(7); field_7.setSafe(currentCount, Integer.valueOf(fields.get(7))); // o_clerk VarCharVector field_8 = (VarCharVector) fieldVectors.get(8); field_8.setSafe(currentCount, new org.apache.arrow.vector.util.Text(fields.get(8))); } }, "\\|", false, allocator); } public static void importTable(BufferManager bufferManager, String path, String tableName, Class<? extends Record> type, BiConsumer<List<String>, List<FieldVector>> parser, String slitter, boolean skipHeader, RootAllocator allocator) throws SchemaExtractionException, IOException { Schema schema = RecordUtil.createSchema(type); PhysicalSchema physicalSchema = new PhysicalSchema.Builder(schema).build(); String cacheName = tableName + ".tmp"; // if (isCached(cacheName)) { // registerTmpBuffer(bufferManager, cacheName, physicalSchema, tableName, factory); //} else { parseCSV(bufferManager, path, cacheName, schema, physicalSchema, tableName, parser, slitter, skipHeader, allocator); //} } public static List<FieldVector> getFields(Schema schema, RootAllocator allocator) { List<FieldVector> fields = new ArrayList<>(); for (SchemaField schemaField : schema.getFields()) { fields.add(getField(schemaField, allocator)); } return fields; } public static FieldVector getField(SchemaField field, RootAllocator allocator) { if (field instanceof NumericField) { return new DecimalVector(field.getName(), allocator, ((NumericField) field).getPrecission(), ((NumericField) field).getPrecission()); } else if (field instanceof DateField) { return new TimeMilliVector(field.getName(), allocator); } else if (field instanceof TextField) { return new VarCharVector(field.getName(), allocator); } else if (Char.class.isAssignableFrom(field.getType())) { return new VarCharVector(field.getName(), allocator); } else if (Int_8.class.isAssignableFrom(field.getType())) { return new TinyIntVector(field.getName(), allocator); } else if (Int_16.class.isAssignableFrom(field.getType())) { return new SmallIntVector(field.getName(), allocator); } else if (Int_32.class.isAssignableFrom(field.getType())) { return new IntVector(field.getName(), allocator); } else if (Int_64.class.isAssignableFrom(field.getType())) { return new BigIntVector(field.getName(), allocator); } else { return null; } } public static void parseCSV(BufferManager bufferManager, String path, String tmpPath, Schema schema, PhysicalSchema physicalSchema, String tableName, BiConsumer<List<String>, List<FieldVector>> parser, String slitter, boolean skipHeader, RootAllocator allocator) throws IOException { int recordsInFile = countLines(path); //int recordsInFile = 1000; FileReader fr = new FileReader(path); //RootAllocator allocator = new RootAllocator(); List<FieldVector> fields = getFields(schema, allocator); LineNumberReader br = new LineNumberReader(fr); String line = br.readLine(); if (skipHeader) line = br.readLine(); while (line != null && br.getLineNumber() < recordsInFile) { String[] stringFields = line.split(slitter); parser.accept(Arrays.asList(stringFields), fields); line = br.readLine(); } List<Field> arrowFields = new ArrayList<>(); List<FieldVector> arrowFieldVectors = new ArrayList<>(); for (FieldVector fieldVector : fields) { if (fieldVector != null) { fieldVector.setValueCount(recordsInFile - 1); arrowFields.add(fieldVector.getField()); arrowFieldVectors.add(fieldVector); } } VectorSchemaRoot schemaRoot = new VectorSchemaRoot(arrowFields, arrowFieldVectors); //ByteArrayOutputStream out = new ByteArrayOutputStream(); //ArrowStreamWriter writer = new ArrowStreamWriter( // schemaRoot, // null, // Channels.newChannel(out)); //writer.start(); //writer.writeBatch(); //writer.end(); System.out.println("DUMP BUFFER TO TEMP"); //Catalog.getInstance().registerLayout(tableName, physicalVariableLengthLayout); Catalog.getInstance().registerArrowLayout(tableName, schemaRoot); System.out.println("DUMP DONE"); } public static void registerTmpBuffer(BufferManager bufferManager, String tempPath, PhysicalSchema physicalSchema, String tableName, PhysicalLayoutFactory factory) { System.out.println("USE TMP file"); Buffer buffer = BufferDump.readBuffer(tempPath, bufferManager); PhysicalLayout physicalVariableLengthLayout = factory.create(physicalSchema, buffer.getSize().getBytes()); Catalog.getInstance().registerLayout(tableName, physicalVariableLengthLayout); Catalog.getInstance().registerBuffer(tableName, buffer); System.out.println("Reading temp file done "); System.out.println("Buffer has " + physicalVariableLengthLayout.getNumberOfRecordsInBuffer(buffer) + " records"); } public static boolean isCached(String path) { return new File(path).exists(); } public static Buffer readFile(String path) throws IOException, SchemaExtractionException { BufferManager bufferManager = new BufferManager(); Schema lineitemSchema = RecordUtil.createSchema(Lineitem.class); PhysicalSchema physicalSchema = new PhysicalSchema.Builder(lineitemSchema).build(); if (new File("lineitem.tmp").exists()) { System.out.println("USE TMP file"); Buffer buffer = BufferDump.readBuffer("lineitem.tmp", bufferManager); PhysicalLayout physicalVariableLengthLayout = new PhysicalColumnLayout(physicalSchema, buffer.getSize().getBytes()); Catalog.getInstance().registerLayout("table.lineitem", physicalVariableLengthLayout); System.out.println("Reading temp file done "); System.out.println("Buffer has " + physicalVariableLengthLayout.getNumberOfRecordsInBuffer(buffer) + " records"); return buffer; } int recordsInFile = countLines(path); //int recordsInFile = 1000; FileReader fr = new FileReader(path); long bufferSize = ((((long) physicalSchema.getFixedRecordSize()) * recordsInFile) + 1024); System.out.println("Buffer Size: " + (bufferSize)); Buffer buffer = bufferManager.allocateBuffer(new Unit.Bytes(bufferSize)); //PhysicalRowLayout physicalVariableLengthLayout = new PhysicalRowLayout(physicalSchema); PhysicalLayout physicalVariableLengthLayout = new PhysicalColumnLayout(physicalSchema, buffer.getSize().getBytes()); physicalVariableLengthLayout.initBuffer(buffer); LineNumberReader br = new LineNumberReader(fr); String line = br.readLine(); while (line != null && br.getLineNumber() < recordsInFile) { String[] fields = line.split("\\|"); /*Lineitem li = new Lineitem( Integer.valueOf(fields[0]), Integer.valueOf(fields[1]), Integer.valueOf(fields[2]), Integer.valueOf(fields[3]), Float.valueOf(fields[4]), Float.valueOf(fields[5]), Float.valueOf(fields[6]), Float.valueOf(fields[7]), new Char(fields[8].toCharArray()[0]), new Char(fields[9].toCharArray()[0]), new Date(fields[10]), new Date(fields[11]), new Date(fields[12]), null, null, null ); */ GenericSerializer.serialize(lineitemSchema, physicalVariableLengthLayout, buffer, null ); line = br.readLine(); } System.out.println("Buffer has " + physicalVariableLengthLayout.getNumberOfRecordsInBuffer(buffer) + " records"); System.out.println("DUMP BUFFER TO TEMP"); BufferDump.dumpBuffer("lineitem.tmp", buffer); System.out.println("DUMP DONE"); return buffer; } private static int countLines(String filename) throws IOException { LineNumberReader reader = new LineNumberReader(new FileReader(filename)); int cnt = 0; String lineRead = ""; while ((lineRead = reader.readLine()) != null) { } cnt = reader.getLineNumber(); reader.close(); return cnt; } @LuthRecord(name = "Lineitem") public class CSVLineitem implements Record { public int l_orderkey; public int l_partkey; public int l_suppkey; public int l_linenumber; @Precision(value = 2) public Numeric l_quantity; @Precision(value = 2) public Numeric l_extendedprice; @Precision(value = 2) public Numeric l_discount; @Precision(value = 2) public Numeric l_tax; public Char l_returnflag; public Char l_linestatus; public Date l_shipdate; public Date l_commitdate; public Date l_reciptdate; @MaxLength(length = 25) public Text shipinstruct; @MaxLength(length = 10) public Text shipmode; @MaxLength(length = 44) public Text comment; public CSVLineitem(int l_orderkey, int l_partkey, int l_suppkey, int l_linenumber, Numeric l_quantity, Numeric l_extendedprice, Numeric l_discount, Numeric l_tax, Char l_returnflag, Char l_linestatus, Date l_shipdate, Date l_commitdate, Date l_reciptdate) { this.l_orderkey = l_orderkey; this.l_partkey = l_partkey; this.l_suppkey = l_suppkey; this.l_linenumber = l_linenumber; this.l_quantity = l_quantity; this.l_extendedprice = l_extendedprice; this.l_discount = l_discount; this.l_tax = l_tax; this.l_returnflag = l_returnflag; this.l_linestatus = l_linestatus; this.l_shipdate = l_shipdate; this.l_commitdate = l_commitdate; this.l_reciptdate = l_reciptdate; } } @LuthRecord(name = "Customer") public class CSVCustomer implements Record { public int c_custkey; @MaxLength(length = 25) public Text c_name; @MaxLength(length = 40) public Text c_address; public int c_nationkey; @MaxLength(length = 15) public Text c_phone; @Precision(value = 2) public Numeric c_acctbal; @MaxLength(length = 10) public Text c_mktsegment; @MaxLength(length = 117) public Text c_comment; public CSVCustomer(int c_custkey, Text c_name, Text c_address, int c_nationkey, Text c_phone, Numeric c_acctbal, Text c_mktsegment, Text c_comment) { this.c_custkey = c_custkey; this.c_name = c_name; this.c_address = c_address; this.c_nationkey = c_nationkey; this.c_phone = c_phone; this.c_acctbal = c_acctbal; this.c_mktsegment = c_mktsegment; this.c_comment = c_comment; } } @LuthRecord(name = "Orders ") public class CSVOrders implements Record { public int o_orderkey; public int o_custkey; public Char o_orderstatus; @Precision(value = 2) public Numeric o_totalprice; public Date o_orderdate; @MaxLength(length = 15) public Text o_orderpriority; @MaxLength(length = 15) public Text o_clerk; public int o_shippriority; @MaxLength(length = 79) public Text o_comment; public CSVOrders(int o_orderkey, int o_custkey, Char o_orderstatus, Numeric o_totalprice, Date o_orderdate, Text o_orderpriority, Text o_clerk, int o_shippriority, Text o_comment) { this.o_orderkey = o_orderkey; this.o_custkey = o_custkey; this.o_orderstatus = o_orderstatus; this.o_totalprice = o_totalprice; this.o_orderdate = o_orderdate; this.o_orderpriority = o_orderpriority; this.o_clerk = o_clerk; this.o_shippriority = o_shippriority; this.o_comment = o_comment; } } }
UTF-8
Java
21,908
java
ArrowCSVImporter.java
Java
[ { "context": "s.c_custkey = c_custkey;\n this.c_name = c_name;\n this.c_address = c_address;\n ", "end": 20526, "score": 0.6630340814590454, "start": 20525, "tag": "NAME", "value": "c" }, { "context": "c_custkey = c_custkey;\n this.c_name = c_name;\n this.c_address = c_address;\n ", "end": 20526, "score": 0.5090359449386597, "start": 20526, "tag": "NAME", "value": "" } ]
null
[]
package de.tub.dima.babelfish.benchmark.parser; import de.tub.dima.babelfish.benchmark.datatypes.Lineitem; import de.tub.dima.babelfish.benchmark.tcph.BufferDump; import de.tub.dima.babelfish.storage.Buffer; import de.tub.dima.babelfish.storage.BufferManager; import de.tub.dima.babelfish.storage.Catalog; import de.tub.dima.babelfish.storage.Unit; import de.tub.dima.babelfish.storage.layout.*; import de.tub.dima.babelfish.typesytem.record.LuthRecord; import de.tub.dima.babelfish.typesytem.record.Record; import de.tub.dima.babelfish.typesytem.record.RecordUtil; import de.tub.dima.babelfish.typesytem.record.SchemaExtractionException; import de.tub.dima.babelfish.typesytem.schema.Schema; import de.tub.dima.babelfish.typesytem.schema.field.DateField; import de.tub.dima.babelfish.typesytem.schema.field.NumericField; import de.tub.dima.babelfish.typesytem.schema.field.SchemaField; import de.tub.dima.babelfish.typesytem.schema.field.TextField; import de.tub.dima.babelfish.typesytem.udt.Date; import de.tub.dima.babelfish.typesytem.valueTypes.Char; import de.tub.dima.babelfish.typesytem.valueTypes.number.integer.Int_16; import de.tub.dima.babelfish.typesytem.valueTypes.number.integer.Int_32; import de.tub.dima.babelfish.typesytem.valueTypes.number.integer.Int_64; import de.tub.dima.babelfish.typesytem.valueTypes.number.integer.Int_8; import de.tub.dima.babelfish.typesytem.valueTypes.number.numeric.Numeric; import de.tub.dima.babelfish.typesytem.valueTypes.number.numeric.Precision; import de.tub.dima.babelfish.typesytem.variableLengthType.MaxLength; import de.tub.dima.babelfish.typesytem.variableLengthType.StringText; import de.tub.dima.babelfish.typesytem.variableLengthType.Text; import org.apache.arrow.memory.RootAllocator; import org.apache.arrow.vector.*; import org.apache.arrow.vector.types.pojo.Field; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.LineNumberReader; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.function.BiConsumer; public class ArrowCSVImporter { public static void importArrow(String path, RootAllocator allocator) throws IOException, SchemaExtractionException { BufferManager bufferManager = new BufferManager(); // import lineorder.tbl importTable(bufferManager, path + "lineitem.tbl", "table.lineitem", CSVLineitem.class, new BiConsumer<List<String>, List<FieldVector>>() { @Override public void accept(List<String> fields, List<FieldVector> fieldVectors) { int currentCount = fieldVectors.get(0).getValueCount(); IntVector field_0 = (IntVector) fieldVectors.get(0); field_0.setSafe(currentCount, Integer.valueOf(fields.get(0))); fieldVectors.get(0).setValueCount(currentCount + 1); IntVector field_1 = (IntVector) fieldVectors.get(1); field_1.setSafe(currentCount, Integer.valueOf(fields.get(1))); IntVector field_2 = (IntVector) fieldVectors.get(2); field_2.setSafe(currentCount, Integer.valueOf(fields.get(2))); IntVector field_3 = (IntVector) fieldVectors.get(3); field_3.setSafe(currentCount, Integer.valueOf(fields.get(3))); DecimalVector field_4 = (DecimalVector) fieldVectors.get(4); field_4.setSafe(currentCount, (long) (Float.valueOf(fields.get(4)) * 100)); DecimalVector field_5 = (DecimalVector) fieldVectors.get(5); field_5.setSafe(currentCount, (long) (Float.valueOf(fields.get(5)) * 100)); DecimalVector field_6 = (DecimalVector) fieldVectors.get(6); field_6.setSafe(currentCount, (long) (Float.valueOf(fields.get(6)) * 100)); DecimalVector field_7 = (DecimalVector) fieldVectors.get(7); field_7.setSafe(currentCount, (long) (Float.valueOf(fields.get(7)) * 100)); TimeMilliVector field_10 = (TimeMilliVector) fieldVectors.get(10); field_10.setSafe(currentCount, Date.parse(fields.get(10))); TimeMilliVector field_11 = (TimeMilliVector) fieldVectors.get(11); field_11.setSafe(currentCount, Date.parse(fields.get(11))); TimeMilliVector field_12 = (TimeMilliVector) fieldVectors.get(12); field_12.setSafe(currentCount, Date.parse(fields.get(12))); VarCharVector field_13 = (VarCharVector) fieldVectors.get(13); field_13.setSafe(currentCount, new org.apache.arrow.vector.util.Text(fields.get(13))); VarCharVector field_14 = (VarCharVector) fieldVectors.get(14); field_14.setSafe(currentCount, new org.apache.arrow.vector.util.Text(fields.get(14))); VarCharVector field_15 = (VarCharVector) fieldVectors.get(15); field_15.setSafe(currentCount, new org.apache.arrow.vector.util.Text(fields.get(15))); } }, "\\|", false, allocator); importTable(bufferManager, path + "customer.tbl", "table.customer", CSVCustomer.class, new BiConsumer<List<String>, List<FieldVector>>() { @Override public void accept(List<String> fields, List<FieldVector> fieldVectors) { int currentCount = fieldVectors.get(0).getValueCount(); IntVector field_0 = (IntVector) fieldVectors.get(0); field_0.setSafe(currentCount, Integer.valueOf(fields.get(0))); fieldVectors.get(0).setValueCount(currentCount + 1); // c_name VarCharVector field_1 = (VarCharVector) fieldVectors.get(1); field_1.setSafe(currentCount, new org.apache.arrow.vector.util.Text(fields.get(1))); // c_address VarCharVector field_2 = (VarCharVector) fieldVectors.get(2); field_2.setSafe(currentCount, new org.apache.arrow.vector.util.Text(fields.get(2))); // c_nationke IntVector field_3 = (IntVector) fieldVectors.get(3); field_3.setSafe(currentCount, Integer.valueOf(fields.get(3))); // c_phone VarCharVector field_4 = (VarCharVector) fieldVectors.get(4); field_4.setSafe(currentCount, new org.apache.arrow.vector.util.Text(fields.get(4))); // c_acctbal DecimalVector field_5 = (DecimalVector) fieldVectors.get(5); field_5.setSafe(currentCount, (long) (Float.valueOf(fields.get(5)) * 100)); // c_mktsegment VarCharVector field_6 = (VarCharVector) fieldVectors.get(6); field_6.setSafe(currentCount, new org.apache.arrow.vector.util.Text(new StringText(fields.get(6), 10).toString())); // c_comment VarCharVector field_7 = (VarCharVector) fieldVectors.get(7); field_7.setSafe(currentCount, new org.apache.arrow.vector.util.Text(fields.get(7))); } }, "\\|", false, allocator); importTable(bufferManager, path + "orders.tbl", "table.orders", CSVOrders.class, new BiConsumer<List<String>, List<FieldVector>>() { @Override public void accept(List<String> fields, List<FieldVector> fieldVectors) { // o_orderkey int currentCount = fieldVectors.get(0).getValueCount(); IntVector field_0 = (IntVector) fieldVectors.get(0); field_0.setSafe(currentCount, Integer.valueOf(fields.get(0))); fieldVectors.get(0).setValueCount(currentCount + 1); // o_custkey IntVector field_1 = (IntVector) fieldVectors.get(1); field_1.setSafe(currentCount, Integer.valueOf(fields.get(1))); // o_orderstatus VarCharVector field_2 = (VarCharVector) fieldVectors.get(2); field_2.setSafe(currentCount, new org.apache.arrow.vector.util.Text(fields.get(2))); // o_totalprice DecimalVector field_3 = (DecimalVector) fieldVectors.get(3); field_3.setSafe(currentCount, (long) (Float.valueOf(fields.get(3)) * 100)); // o_orderdate TimeMilliVector field_4 = (TimeMilliVector) fieldVectors.get(4); field_4.setSafe(currentCount, Date.parse(fields.get(4))); // o_orderpriority VarCharVector field_5 = (VarCharVector) fieldVectors.get(5); field_5.setSafe(currentCount, new org.apache.arrow.vector.util.Text(fields.get(5))); // o_clerk VarCharVector field_6 = (VarCharVector) fieldVectors.get(6); field_6.setSafe(currentCount, new org.apache.arrow.vector.util.Text(fields.get(6))); // o_shippriority IntVector field_7 = (IntVector) fieldVectors.get(7); field_7.setSafe(currentCount, Integer.valueOf(fields.get(7))); // o_clerk VarCharVector field_8 = (VarCharVector) fieldVectors.get(8); field_8.setSafe(currentCount, new org.apache.arrow.vector.util.Text(fields.get(8))); } }, "\\|", false, allocator); } public static void importTable(BufferManager bufferManager, String path, String tableName, Class<? extends Record> type, BiConsumer<List<String>, List<FieldVector>> parser, String slitter, boolean skipHeader, RootAllocator allocator) throws SchemaExtractionException, IOException { Schema schema = RecordUtil.createSchema(type); PhysicalSchema physicalSchema = new PhysicalSchema.Builder(schema).build(); String cacheName = tableName + ".tmp"; // if (isCached(cacheName)) { // registerTmpBuffer(bufferManager, cacheName, physicalSchema, tableName, factory); //} else { parseCSV(bufferManager, path, cacheName, schema, physicalSchema, tableName, parser, slitter, skipHeader, allocator); //} } public static List<FieldVector> getFields(Schema schema, RootAllocator allocator) { List<FieldVector> fields = new ArrayList<>(); for (SchemaField schemaField : schema.getFields()) { fields.add(getField(schemaField, allocator)); } return fields; } public static FieldVector getField(SchemaField field, RootAllocator allocator) { if (field instanceof NumericField) { return new DecimalVector(field.getName(), allocator, ((NumericField) field).getPrecission(), ((NumericField) field).getPrecission()); } else if (field instanceof DateField) { return new TimeMilliVector(field.getName(), allocator); } else if (field instanceof TextField) { return new VarCharVector(field.getName(), allocator); } else if (Char.class.isAssignableFrom(field.getType())) { return new VarCharVector(field.getName(), allocator); } else if (Int_8.class.isAssignableFrom(field.getType())) { return new TinyIntVector(field.getName(), allocator); } else if (Int_16.class.isAssignableFrom(field.getType())) { return new SmallIntVector(field.getName(), allocator); } else if (Int_32.class.isAssignableFrom(field.getType())) { return new IntVector(field.getName(), allocator); } else if (Int_64.class.isAssignableFrom(field.getType())) { return new BigIntVector(field.getName(), allocator); } else { return null; } } public static void parseCSV(BufferManager bufferManager, String path, String tmpPath, Schema schema, PhysicalSchema physicalSchema, String tableName, BiConsumer<List<String>, List<FieldVector>> parser, String slitter, boolean skipHeader, RootAllocator allocator) throws IOException { int recordsInFile = countLines(path); //int recordsInFile = 1000; FileReader fr = new FileReader(path); //RootAllocator allocator = new RootAllocator(); List<FieldVector> fields = getFields(schema, allocator); LineNumberReader br = new LineNumberReader(fr); String line = br.readLine(); if (skipHeader) line = br.readLine(); while (line != null && br.getLineNumber() < recordsInFile) { String[] stringFields = line.split(slitter); parser.accept(Arrays.asList(stringFields), fields); line = br.readLine(); } List<Field> arrowFields = new ArrayList<>(); List<FieldVector> arrowFieldVectors = new ArrayList<>(); for (FieldVector fieldVector : fields) { if (fieldVector != null) { fieldVector.setValueCount(recordsInFile - 1); arrowFields.add(fieldVector.getField()); arrowFieldVectors.add(fieldVector); } } VectorSchemaRoot schemaRoot = new VectorSchemaRoot(arrowFields, arrowFieldVectors); //ByteArrayOutputStream out = new ByteArrayOutputStream(); //ArrowStreamWriter writer = new ArrowStreamWriter( // schemaRoot, // null, // Channels.newChannel(out)); //writer.start(); //writer.writeBatch(); //writer.end(); System.out.println("DUMP BUFFER TO TEMP"); //Catalog.getInstance().registerLayout(tableName, physicalVariableLengthLayout); Catalog.getInstance().registerArrowLayout(tableName, schemaRoot); System.out.println("DUMP DONE"); } public static void registerTmpBuffer(BufferManager bufferManager, String tempPath, PhysicalSchema physicalSchema, String tableName, PhysicalLayoutFactory factory) { System.out.println("USE TMP file"); Buffer buffer = BufferDump.readBuffer(tempPath, bufferManager); PhysicalLayout physicalVariableLengthLayout = factory.create(physicalSchema, buffer.getSize().getBytes()); Catalog.getInstance().registerLayout(tableName, physicalVariableLengthLayout); Catalog.getInstance().registerBuffer(tableName, buffer); System.out.println("Reading temp file done "); System.out.println("Buffer has " + physicalVariableLengthLayout.getNumberOfRecordsInBuffer(buffer) + " records"); } public static boolean isCached(String path) { return new File(path).exists(); } public static Buffer readFile(String path) throws IOException, SchemaExtractionException { BufferManager bufferManager = new BufferManager(); Schema lineitemSchema = RecordUtil.createSchema(Lineitem.class); PhysicalSchema physicalSchema = new PhysicalSchema.Builder(lineitemSchema).build(); if (new File("lineitem.tmp").exists()) { System.out.println("USE TMP file"); Buffer buffer = BufferDump.readBuffer("lineitem.tmp", bufferManager); PhysicalLayout physicalVariableLengthLayout = new PhysicalColumnLayout(physicalSchema, buffer.getSize().getBytes()); Catalog.getInstance().registerLayout("table.lineitem", physicalVariableLengthLayout); System.out.println("Reading temp file done "); System.out.println("Buffer has " + physicalVariableLengthLayout.getNumberOfRecordsInBuffer(buffer) + " records"); return buffer; } int recordsInFile = countLines(path); //int recordsInFile = 1000; FileReader fr = new FileReader(path); long bufferSize = ((((long) physicalSchema.getFixedRecordSize()) * recordsInFile) + 1024); System.out.println("Buffer Size: " + (bufferSize)); Buffer buffer = bufferManager.allocateBuffer(new Unit.Bytes(bufferSize)); //PhysicalRowLayout physicalVariableLengthLayout = new PhysicalRowLayout(physicalSchema); PhysicalLayout physicalVariableLengthLayout = new PhysicalColumnLayout(physicalSchema, buffer.getSize().getBytes()); physicalVariableLengthLayout.initBuffer(buffer); LineNumberReader br = new LineNumberReader(fr); String line = br.readLine(); while (line != null && br.getLineNumber() < recordsInFile) { String[] fields = line.split("\\|"); /*Lineitem li = new Lineitem( Integer.valueOf(fields[0]), Integer.valueOf(fields[1]), Integer.valueOf(fields[2]), Integer.valueOf(fields[3]), Float.valueOf(fields[4]), Float.valueOf(fields[5]), Float.valueOf(fields[6]), Float.valueOf(fields[7]), new Char(fields[8].toCharArray()[0]), new Char(fields[9].toCharArray()[0]), new Date(fields[10]), new Date(fields[11]), new Date(fields[12]), null, null, null ); */ GenericSerializer.serialize(lineitemSchema, physicalVariableLengthLayout, buffer, null ); line = br.readLine(); } System.out.println("Buffer has " + physicalVariableLengthLayout.getNumberOfRecordsInBuffer(buffer) + " records"); System.out.println("DUMP BUFFER TO TEMP"); BufferDump.dumpBuffer("lineitem.tmp", buffer); System.out.println("DUMP DONE"); return buffer; } private static int countLines(String filename) throws IOException { LineNumberReader reader = new LineNumberReader(new FileReader(filename)); int cnt = 0; String lineRead = ""; while ((lineRead = reader.readLine()) != null) { } cnt = reader.getLineNumber(); reader.close(); return cnt; } @LuthRecord(name = "Lineitem") public class CSVLineitem implements Record { public int l_orderkey; public int l_partkey; public int l_suppkey; public int l_linenumber; @Precision(value = 2) public Numeric l_quantity; @Precision(value = 2) public Numeric l_extendedprice; @Precision(value = 2) public Numeric l_discount; @Precision(value = 2) public Numeric l_tax; public Char l_returnflag; public Char l_linestatus; public Date l_shipdate; public Date l_commitdate; public Date l_reciptdate; @MaxLength(length = 25) public Text shipinstruct; @MaxLength(length = 10) public Text shipmode; @MaxLength(length = 44) public Text comment; public CSVLineitem(int l_orderkey, int l_partkey, int l_suppkey, int l_linenumber, Numeric l_quantity, Numeric l_extendedprice, Numeric l_discount, Numeric l_tax, Char l_returnflag, Char l_linestatus, Date l_shipdate, Date l_commitdate, Date l_reciptdate) { this.l_orderkey = l_orderkey; this.l_partkey = l_partkey; this.l_suppkey = l_suppkey; this.l_linenumber = l_linenumber; this.l_quantity = l_quantity; this.l_extendedprice = l_extendedprice; this.l_discount = l_discount; this.l_tax = l_tax; this.l_returnflag = l_returnflag; this.l_linestatus = l_linestatus; this.l_shipdate = l_shipdate; this.l_commitdate = l_commitdate; this.l_reciptdate = l_reciptdate; } } @LuthRecord(name = "Customer") public class CSVCustomer implements Record { public int c_custkey; @MaxLength(length = 25) public Text c_name; @MaxLength(length = 40) public Text c_address; public int c_nationkey; @MaxLength(length = 15) public Text c_phone; @Precision(value = 2) public Numeric c_acctbal; @MaxLength(length = 10) public Text c_mktsegment; @MaxLength(length = 117) public Text c_comment; public CSVCustomer(int c_custkey, Text c_name, Text c_address, int c_nationkey, Text c_phone, Numeric c_acctbal, Text c_mktsegment, Text c_comment) { this.c_custkey = c_custkey; this.c_name = c_name; this.c_address = c_address; this.c_nationkey = c_nationkey; this.c_phone = c_phone; this.c_acctbal = c_acctbal; this.c_mktsegment = c_mktsegment; this.c_comment = c_comment; } } @LuthRecord(name = "Orders ") public class CSVOrders implements Record { public int o_orderkey; public int o_custkey; public Char o_orderstatus; @Precision(value = 2) public Numeric o_totalprice; public Date o_orderdate; @MaxLength(length = 15) public Text o_orderpriority; @MaxLength(length = 15) public Text o_clerk; public int o_shippriority; @MaxLength(length = 79) public Text o_comment; public CSVOrders(int o_orderkey, int o_custkey, Char o_orderstatus, Numeric o_totalprice, Date o_orderdate, Text o_orderpriority, Text o_clerk, int o_shippriority, Text o_comment) { this.o_orderkey = o_orderkey; this.o_custkey = o_custkey; this.o_orderstatus = o_orderstatus; this.o_totalprice = o_totalprice; this.o_orderdate = o_orderdate; this.o_orderpriority = o_orderpriority; this.o_clerk = o_clerk; this.o_shippriority = o_shippriority; this.o_comment = o_comment; } } }
21,908
0.628355
0.616852
470
45.612766
35.254017
265
false
false
0
0
0
0
0
0
0.929787
false
false
13
37275e0d13959a396af92d67456593a2cc082cae
22,643,067,590,450
b2d3bfb3b06c4ef0f4fef83efc22f0e49b23d6ab
/subscription/src/test/java/com/faziz/subscription/TruncatorTest.java
560cc784f04a06b6daab3246d0a00db063acd43e
[]
no_license
faziz/assignment1
https://github.com/faziz/assignment1
fc17166d8707e47c4cabf391e2c92516cdb307ab
766d6f3bcaca8d01ebace014982f3897770d7465
refs/heads/master
2021-01-15T17:19:42.312000
2017-08-09T10:32:04
2017-08-09T10:32:04
99,751,495
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.faziz.subscription; import org.junit.Test; import static org.junit.Assert.*; public class TruncatorTest { public TruncatorTest() { } @Test public void testInputIsLargerThanLimit() { String input = "123456789012345678901234567890"; Integer limit = 5; Truncator truncator = new Truncator(); String truncated = truncator.truncate(input, limit); assertEquals("12 ... (truncated) ... 90", truncated); } @Test public void testInputIsSmallerThanLimit() { String input = "1234567890"; Integer limit = 5; Truncator truncator = new Truncator(); String truncated = truncator.truncate(input, limit); assertEquals(input, truncated); } @Test public void testInputIsEqualsToLimit() { String input = "123456789012345678901234567890"; Integer limit = 31; Truncator truncator = new Truncator(); String truncated = truncator.truncate(input, limit); assertEquals(input, truncated); } }
UTF-8
Java
1,124
java
TruncatorTest.java
Java
[]
null
[]
package com.faziz.subscription; import org.junit.Test; import static org.junit.Assert.*; public class TruncatorTest { public TruncatorTest() { } @Test public void testInputIsLargerThanLimit() { String input = "123456789012345678901234567890"; Integer limit = 5; Truncator truncator = new Truncator(); String truncated = truncator.truncate(input, limit); assertEquals("12 ... (truncated) ... 90", truncated); } @Test public void testInputIsSmallerThanLimit() { String input = "1234567890"; Integer limit = 5; Truncator truncator = new Truncator(); String truncated = truncator.truncate(input, limit); assertEquals(input, truncated); } @Test public void testInputIsEqualsToLimit() { String input = "123456789012345678901234567890"; Integer limit = 31; Truncator truncator = new Truncator(); String truncated = truncator.truncate(input, limit); assertEquals(input, truncated); } }
1,124
0.603203
0.533808
45
23.977777
20.471649
61
false
false
0
0
0
0
0
0
0.533333
false
false
13
1e00547e20cbc821adda273204a04ab2d5165be4
17,600,776,041,767
3fe7303fb885840f1663121cedb220aba15cfd0b
/java/com/desarrolladorgmail/a/jose/stickerscity/Otros/GuardarGifs.java
f23b5d6ec4251ee6da450de4822be0dd4f3dbb09
[]
no_license
sAPIaDeveloper/App-Sticker-s-City
https://github.com/sAPIaDeveloper/App-Sticker-s-City
04a73f2e5ee507b74adc167255fbd8db4bc753a3
52e01504a5c618593987634566fc127d3a15a537
refs/heads/master
2020-05-21T08:11:02.345000
2019-05-23T09:20:14
2019-05-23T09:20:14
185,974,461
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.desarrolladorgmail.a.jose.stickerscity.Otros; import android.content.Context; import android.graphics.Bitmap; import android.media.MediaScannerConnection; import android.net.Uri; import android.os.Environment; import android.util.Log; import android.widget.Toast; import java.io.*; import java.text.SimpleDateFormat; import java.util.Calendar; public class GuardarGifs { private Context TheThis; private String carpeta = "StickerCity"; private String fichero = "gif"; private boolean escritura; private boolean lectura; public void comprobarAlmacenamiento(){ String estado = Environment.getExternalStorageState(); if (estado.equals(Environment.MEDIA_MOUNTED)) { Log.i("Ficheros", "Tarjeta montada"); lectura = true; escritura = true; } else if (estado.equals(Environment.MEDIA_MOUNTED_READ_ONLY)) { Log.i("Ficheros", "Tarjeta montada para solo lectura"); lectura = true; escritura = false; } else { Log.i("Ficheros", "Tarjeta desmontada"); lectura = false; escritura = false; } } public void guardarImagen(Context context, Bitmap ImageToSave) { comprobarAlmacenamiento(); if(lectura && escritura ){ TheThis = context; String file_path = Environment.getExternalStorageDirectory().getAbsolutePath()+System.getProperty("file.separator")+carpeta; String CurrentDateAndTime = getCurrentDateAndTime(); File dir = new File(file_path); if (!dir.exists()) { dir.mkdirs(); } File file = new File(dir, fichero + CurrentDateAndTime + ".gif"); try { file.createNewFile(); FileOutputStream fOut = new FileOutputStream(file); ImageToSave.compress(Bitmap.CompressFormat.WEBP, 85, fOut); fOut.flush(); fOut.close(); MakeSureFileWasCreatedThenMakeAvabile(file); Toast.makeText(TheThis, "Gif guardado en la galería.", Toast.LENGTH_SHORT).show(); } catch(Exception e) { Toast.makeText(TheThis, "¡No se ha podido guardar el gif!", Toast.LENGTH_SHORT).show(); } }else{Toast.makeText(TheThis, "Existe problemas con tu almacenamiento externo", Toast.LENGTH_SHORT).show();} } private void MakeSureFileWasCreatedThenMakeAvabile(File file){ MediaScannerConnection.scanFile(TheThis, new String[] { file.toString() } , null, new MediaScannerConnection.OnScanCompletedListener() { public void onScanCompleted(String path, Uri uri) { } }); } private String getCurrentDateAndTime() { Calendar c = Calendar.getInstance(); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd-HH-mm-­ss"); String formattedDate = df.format(c.getTime()); return formattedDate; } }
UTF-8
Java
3,215
java
GuardarGifs.java
Java
[]
null
[]
package com.desarrolladorgmail.a.jose.stickerscity.Otros; import android.content.Context; import android.graphics.Bitmap; import android.media.MediaScannerConnection; import android.net.Uri; import android.os.Environment; import android.util.Log; import android.widget.Toast; import java.io.*; import java.text.SimpleDateFormat; import java.util.Calendar; public class GuardarGifs { private Context TheThis; private String carpeta = "StickerCity"; private String fichero = "gif"; private boolean escritura; private boolean lectura; public void comprobarAlmacenamiento(){ String estado = Environment.getExternalStorageState(); if (estado.equals(Environment.MEDIA_MOUNTED)) { Log.i("Ficheros", "Tarjeta montada"); lectura = true; escritura = true; } else if (estado.equals(Environment.MEDIA_MOUNTED_READ_ONLY)) { Log.i("Ficheros", "Tarjeta montada para solo lectura"); lectura = true; escritura = false; } else { Log.i("Ficheros", "Tarjeta desmontada"); lectura = false; escritura = false; } } public void guardarImagen(Context context, Bitmap ImageToSave) { comprobarAlmacenamiento(); if(lectura && escritura ){ TheThis = context; String file_path = Environment.getExternalStorageDirectory().getAbsolutePath()+System.getProperty("file.separator")+carpeta; String CurrentDateAndTime = getCurrentDateAndTime(); File dir = new File(file_path); if (!dir.exists()) { dir.mkdirs(); } File file = new File(dir, fichero + CurrentDateAndTime + ".gif"); try { file.createNewFile(); FileOutputStream fOut = new FileOutputStream(file); ImageToSave.compress(Bitmap.CompressFormat.WEBP, 85, fOut); fOut.flush(); fOut.close(); MakeSureFileWasCreatedThenMakeAvabile(file); Toast.makeText(TheThis, "Gif guardado en la galería.", Toast.LENGTH_SHORT).show(); } catch(Exception e) { Toast.makeText(TheThis, "¡No se ha podido guardar el gif!", Toast.LENGTH_SHORT).show(); } }else{Toast.makeText(TheThis, "Existe problemas con tu almacenamiento externo", Toast.LENGTH_SHORT).show();} } private void MakeSureFileWasCreatedThenMakeAvabile(File file){ MediaScannerConnection.scanFile(TheThis, new String[] { file.toString() } , null, new MediaScannerConnection.OnScanCompletedListener() { public void onScanCompleted(String path, Uri uri) { } }); } private String getCurrentDateAndTime() { Calendar c = Calendar.getInstance(); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd-HH-mm-­ss"); String formattedDate = df.format(c.getTime()); return formattedDate; } }
3,215
0.589975
0.589352
91
33.31868
28.046225
136
false
false
0
0
0
0
0
0
0.703297
false
false
13
e39d04ae2d433a226d03ce60f8edbbd1e6ac95f9
8,340,826,517,156
ce890c188747d80ca4dedaeab00bbc07270bcfc5
/Program/src/main/java/project/thangnd/controllers/CommentController.java
5032cd827ebb5075938df2bf3d3589832ef09d26
[]
no_license
thangkuu1/project
https://github.com/thangkuu1/project
69b7f95f60a626f4834b93f0d9a9a84e6bb755ec
fc300c3afbb65d93ca22e0d1556ae148f7e5ecab
refs/heads/master
2020-05-25T22:19:49.326000
2019-05-22T14:22:08
2019-05-22T14:22:08
188,013,505
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package project.thangnd.controllers; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpSession; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import project.thangnd.dtos.CommentDto; import project.thangnd.models.Comment; import project.thangnd.models.User; import project.thangnd.services.CommentService; import project.thangnd.services.UserService; @Controller public class CommentController { Logger logger = Logger.getLogger(CommentController.class); @Autowired private CommentService cmtService; @Autowired private UserService userService; @RequestMapping(value="comment") @ResponseBody Map<String, Object> comment(@RequestParam("content_cmt") String content_cmt, @RequestParam("id_rest") String id_rest, HttpSession session){ Map<String, Object> map = new HashMap<String, Object>(); StringBuffer sb = new StringBuffer(); List<CommentDto> list_comment = new ArrayList<>(); sb.append(" " ); try { Comment cmt = new Comment(); cmt.setCmt_status("I"); cmt.setContent_cmt(content_cmt); Date date = new Date(); DateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); cmt.setDate(format.format(date)); cmt.setId_rest(Integer.parseInt(id_rest)); User user = (User) session.getAttribute("user"); cmt.setId_user(user.getUser_id()); int result = cmtService.insertComment(cmt); if(result == 1){ sb.append("insert comment success"); }else{ sb.append("insert comment failed " ); } list_comment = loadCommentDto(Integer.parseInt(id_rest)); if(list_comment.size() > 0){ map.put("data", list_comment); System.out.println("CommentController # list comment success"); }else{ System.out.println("CommentController # list comment error"); } } catch (Exception e) { e.printStackTrace(); // System.out.println("CommentController insertComment error"); logger.error(" error"); } System.out.println("content_cmt: " + content_cmt +" id_rest: " + id_rest); // System.out.println(sb); logger.info(sb); return map; } @RequestMapping(value="loadcomment") @ResponseBody Map<String, Object> listcomment(@RequestParam("id_rest") String id_rest, HttpSession session){ Map<String, Object> map = new HashMap<>(); StringBuffer sb = new StringBuffer(); sb.append("CommentController #loadcomment "); List<CommentDto> list_comment = new ArrayList<>(); try { // list_comment = cmtService.listComment(); list_comment = loadCommentDto(Integer.parseInt(id_rest)); if(list_comment.size() > 0){ sb.append("List comment is value "); map.put("data", list_comment); }else{ sb.append("list comment is not value"); } } catch (Exception e) { e.printStackTrace(); // System.out.println("CommentController #listcomment"); logger.error("error"); } logger.info(sb); return map; } public List<CommentDto> loadCommentDto(int id_rest){ List<CommentDto> listCommentDto = new ArrayList<>(); List<Comment> listComment = new ArrayList<>(); StringBuffer sb = new StringBuffer(); try { listComment = cmtService.listComment(id_rest); if(listComment == null){ sb.append("List comment is not value"); listComment = null; }else{ sb.append("List comment is value"); for(int i = 0; i < listComment.size(); i++ ){ CommentDto cmt_dto = new CommentDto(); cmt_dto.setContent_cmt(listComment.get(i).getContent_cmt()); cmt_dto.setDate(listComment.get(i).getDate()); cmt_dto.setId_cmt(listComment.get(i).getId_cmt()); cmt_dto.setId_rest(String.valueOf(listComment.get(i).getId_rest())); cmt_dto.setId_user(String.valueOf(listComment.get(i).getId_user())); User user = userService.getUserById(listComment.get(i).getId_user()); if(user == null){ sb.append("User is not value "); }else{ sb.append("User is value " ); cmt_dto.setImage_user(user.getImage_user()); cmt_dto.setUsername(user.getUsername()); } listCommentDto.add(cmt_dto); for(int j = 0; j < listCommentDto.size() ; j++){ sb.append(listCommentDto.get(i).toString()); } } } } catch (Exception e) { e.printStackTrace(); listComment = null; System.out.println("CommentController #loadComment error"); logger.error("error exception"); } // System.out.println(sb); logger.info(sb); return listCommentDto; } }
UTF-8
Java
4,806
java
CommentController.java
Java
[]
null
[]
package project.thangnd.controllers; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpSession; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import project.thangnd.dtos.CommentDto; import project.thangnd.models.Comment; import project.thangnd.models.User; import project.thangnd.services.CommentService; import project.thangnd.services.UserService; @Controller public class CommentController { Logger logger = Logger.getLogger(CommentController.class); @Autowired private CommentService cmtService; @Autowired private UserService userService; @RequestMapping(value="comment") @ResponseBody Map<String, Object> comment(@RequestParam("content_cmt") String content_cmt, @RequestParam("id_rest") String id_rest, HttpSession session){ Map<String, Object> map = new HashMap<String, Object>(); StringBuffer sb = new StringBuffer(); List<CommentDto> list_comment = new ArrayList<>(); sb.append(" " ); try { Comment cmt = new Comment(); cmt.setCmt_status("I"); cmt.setContent_cmt(content_cmt); Date date = new Date(); DateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); cmt.setDate(format.format(date)); cmt.setId_rest(Integer.parseInt(id_rest)); User user = (User) session.getAttribute("user"); cmt.setId_user(user.getUser_id()); int result = cmtService.insertComment(cmt); if(result == 1){ sb.append("insert comment success"); }else{ sb.append("insert comment failed " ); } list_comment = loadCommentDto(Integer.parseInt(id_rest)); if(list_comment.size() > 0){ map.put("data", list_comment); System.out.println("CommentController # list comment success"); }else{ System.out.println("CommentController # list comment error"); } } catch (Exception e) { e.printStackTrace(); // System.out.println("CommentController insertComment error"); logger.error(" error"); } System.out.println("content_cmt: " + content_cmt +" id_rest: " + id_rest); // System.out.println(sb); logger.info(sb); return map; } @RequestMapping(value="loadcomment") @ResponseBody Map<String, Object> listcomment(@RequestParam("id_rest") String id_rest, HttpSession session){ Map<String, Object> map = new HashMap<>(); StringBuffer sb = new StringBuffer(); sb.append("CommentController #loadcomment "); List<CommentDto> list_comment = new ArrayList<>(); try { // list_comment = cmtService.listComment(); list_comment = loadCommentDto(Integer.parseInt(id_rest)); if(list_comment.size() > 0){ sb.append("List comment is value "); map.put("data", list_comment); }else{ sb.append("list comment is not value"); } } catch (Exception e) { e.printStackTrace(); // System.out.println("CommentController #listcomment"); logger.error("error"); } logger.info(sb); return map; } public List<CommentDto> loadCommentDto(int id_rest){ List<CommentDto> listCommentDto = new ArrayList<>(); List<Comment> listComment = new ArrayList<>(); StringBuffer sb = new StringBuffer(); try { listComment = cmtService.listComment(id_rest); if(listComment == null){ sb.append("List comment is not value"); listComment = null; }else{ sb.append("List comment is value"); for(int i = 0; i < listComment.size(); i++ ){ CommentDto cmt_dto = new CommentDto(); cmt_dto.setContent_cmt(listComment.get(i).getContent_cmt()); cmt_dto.setDate(listComment.get(i).getDate()); cmt_dto.setId_cmt(listComment.get(i).getId_cmt()); cmt_dto.setId_rest(String.valueOf(listComment.get(i).getId_rest())); cmt_dto.setId_user(String.valueOf(listComment.get(i).getId_user())); User user = userService.getUserById(listComment.get(i).getId_user()); if(user == null){ sb.append("User is not value "); }else{ sb.append("User is value " ); cmt_dto.setImage_user(user.getImage_user()); cmt_dto.setUsername(user.getUsername()); } listCommentDto.add(cmt_dto); for(int j = 0; j < listCommentDto.size() ; j++){ sb.append(listCommentDto.get(i).toString()); } } } } catch (Exception e) { e.printStackTrace(); listComment = null; System.out.println("CommentController #loadComment error"); logger.error("error exception"); } // System.out.println(sb); logger.info(sb); return listCommentDto; } }
4,806
0.697461
0.696213
145
32.144829
22.200645
109
false
false
0
0
0
0
0
0
3.124138
false
false
13
97c5d81af413eb71cc37f03024e0f176c5aeddae
8,443,905,709,432
793d41e5c5820cd5e1ef4dabf212d96a64efaee0
/src/ast/AtomExpr.java
84d95784d2e931d9732c5090f22863cad1c4f1b2
[ "MIT" ]
permissive
adraghici/srtool
https://github.com/adraghici/srtool
45361b9b435a63c9a780b7975f58955b338de6c3
5fd873a793d9dfc23aae5c7d9833e298d2c4b6a0
refs/heads/master
2016-08-12T07:41:14.126000
2016-01-23T00:47:31
2016-01-23T00:47:31
44,448,217
1
0
null
false
2015-10-18T18:50:30
2015-10-17T17:57:27
2015-10-18T17:09:08
2015-10-18T18:40:41
0
1
0
1
Java
null
null
package ast; public interface AtomExpr extends Expr { }
UTF-8
Java
57
java
AtomExpr.java
Java
[]
null
[]
package ast; public interface AtomExpr extends Expr { }
57
0.77193
0.77193
4
13.25
16.145821
40
false
false
0
0
0
0
0
0
0.25
false
false
13
b16f734746a439bad2d75231a26c4a6f92ad8ef7
4,853,313,071,081
c9bfbf9269610d4d55f70df2b6b3381db2a026c5
/service-task/src/main/java/com/idream/feign/impl/FeignUserServiceHystric.java
938430bc9d5b9bbde84b5b7528b5c76c899d4b0d
[]
no_license
moutainhigh/idream-community
https://github.com/moutainhigh/idream-community
1b076671a2e7df0d70094e3a6162d550340ac2f5
c59e84d0c260005c0a6de5e3e3a4cc4c51da5339
refs/heads/master
2021-09-22T07:03:59.357000
2018-09-06T07:37:27
2018-09-06T07:37:27
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.idream.feign.impl; import com.idream.commons.lib.dto.JSONPublicDto; import com.idream.commons.lib.dto.user.FindUserInfoDto; import com.idream.feign.FeignUserService; import org.springframework.web.bind.annotation.RequestParam; /** * 调用service-user服务接口发生异常时处理 * * @author hejiang */ public class FeignUserServiceHystric implements FeignUserService { @Override public JSONPublicDto<FindUserInfoDto> getUserInfoById(@RequestParam("authUserId") Integer authUserId) { return null; } @Override public JSONPublicDto updateUserStatistics() { return null; } }
UTF-8
Java
637
java
FeignUserServiceHystric.java
Java
[ { "context": "m;\n\n/**\n * 调用service-user服务接口发生异常时处理\n *\n * @author hejiang\n */\npublic class FeignUserServiceHystric implemen", "end": 295, "score": 0.9992567896842957, "start": 288, "tag": "USERNAME", "value": "hejiang" } ]
null
[]
package com.idream.feign.impl; import com.idream.commons.lib.dto.JSONPublicDto; import com.idream.commons.lib.dto.user.FindUserInfoDto; import com.idream.feign.FeignUserService; import org.springframework.web.bind.annotation.RequestParam; /** * 调用service-user服务接口发生异常时处理 * * @author hejiang */ public class FeignUserServiceHystric implements FeignUserService { @Override public JSONPublicDto<FindUserInfoDto> getUserInfoById(@RequestParam("authUserId") Integer authUserId) { return null; } @Override public JSONPublicDto updateUserStatistics() { return null; } }
637
0.756137
0.756137
24
24.458334
27.140038
107
false
false
0
0
0
0
0
0
0.291667
false
false
13
fc480a6e6db409afd8be829cc10ca0972b769f58
16,904,991,300,625
d2f97c338308037a4bfd73bdf7d52cf7531ae834
/src/Array/ConstructBinaryTreeFromPreorderAndInorderTraversal.java
444f03a9be389d407e8077a6019d79cceaaf387b
[]
no_license
zherogerluo/leetcode
https://github.com/zherogerluo/leetcode
3c3066c3c4c22943ee28c585ff4338fd994b9f5f
2291699e2459d0c2f708a7eaa259b320c6c2d052
refs/heads/master
2020-03-18T20:32:40.626000
2019-04-18T01:46:10
2019-04-18T01:46:10
135,222,841
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
../Tree/ConstructBinaryTreeFromPreorderAndInorderTraversal.java
UTF-8
Java
63
java
ConstructBinaryTreeFromPreorderAndInorderTraversal.java
Java
[]
null
[]
../Tree/ConstructBinaryTreeFromPreorderAndInorderTraversal.java
63
0.920635
0.920635
1
63
0
63
false
false
0
0
0
0
0
0
0
false
false
13
c0e2e54f5064c8b26da9fc5e8ac691643e6ed48f
19,585,050,892,210
5c95f25f8481005288d9fb826be1025f4f6f05da
/app/src/main/java/com/example/weatherapp/MainActivity.java
edfe567639d6f3b9921d1e651bd7e99c778e8b92
[]
no_license
RickMu/WeatherApp-Android
https://github.com/RickMu/WeatherApp-Android
5bab26b11c509229ac6102c4511443e957f2786b
e88c3a69597ecda5e9f5a733e3d9376a19dae523
refs/heads/master
2021-01-19T10:05:23.652000
2017-04-19T15:33:02
2017-04-19T15:33:02
87,825,094
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.weatherapp; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.drawable.Drawable; import android.location.Location; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.ActivityCompat; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.example.weatherapp.Weather.Current; import com.example.weatherapp.Weather.Day; import com.example.weatherapp.Weather.Forcast; import com.example.weatherapp.Weather.Hour; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.location.LocationServices; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import okhttp3.Call; import okhttp3.Callback; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener { private static final String TAG = MainActivity.class.getSimpleName(); public static final String DAILY_FORCAST = "DAYILY_FORCAST"; Forcast mForcast; private double latitude = -37.814, longitude = 144.96332; private GoogleApiClient mGoogleApiClient = null; @BindView(R.id.humidityMeasureId) TextView mHumidity; @BindView(R.id.precepValue) TextView mPrecepValue; @BindView(R.id.precepLabel) TextView mPrecepLabel; @BindView(R.id.temperatureId) TextView mTemperature; @BindView(R.id.timeID) TextView mTime; @BindView(R.id.weatherDescription) TextView mSummary; @BindView(R.id.weatherIconId) ImageView mIconImageView; @BindView(R.id.refreshImage) ImageView mRefreshImg; @BindView(R.id.refreshProgress) ProgressBar mProgressBar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); mProgressBar.setVisibility(View.INVISIBLE); if (mGoogleApiClient == null) { mGoogleApiClient = new GoogleApiClient.Builder(this) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(LocationServices.API) .build(); } mRefreshImg.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { getForcast(latitude, longitude); } }); } private void getForcast(double latitude, double longitude) { String secretKey = "3be6c051769f52fc39f671377b21b49b"; String forcastUrl = "https://api.darksky.net/forecast/" + secretKey + "/" + latitude + "," + longitude; if (isNetworkAvailable()) { toggleRefresh(); OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url(forcastUrl) .build(); Call call = client.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { Log.e(TAG, "Failure to connect: ", e); } @Override public void onResponse(Call call, Response response) { try { String jsonData = response.body().string(); Log.v(TAG, jsonData); if (response.isSuccessful()) { try { mForcast = parseForcastDetails(jsonData); runOnUiThread(new Runnable() { @Override public void run() { toggleRefresh(); updateForcast(); } }); } catch (JSONException e) { e.printStackTrace(); } } else { alertUserAboutError(); } } catch (IOException e) { Log.e(TAG, "Exception caught: ", e); } } }); } else { Toast.makeText(this, "Network Connection Error", Toast.LENGTH_LONG).show(); } } private void updateForcast() { Current mCurrentWeather = mForcast.getCurrent(); mTemperature.setText(mCurrentWeather.getCelsius() + ""); mTime.setText("At time " + mCurrentWeather.getFormatedTime() + " it will be"); mHumidity.setText(mCurrentWeather.getHumidity() + ""); mPrecepValue.setText(mCurrentWeather.getPrecipProbaility() + "%"); mSummary.setText(mCurrentWeather.getSummary()); Drawable drawable = getResources().getDrawable(mCurrentWeather.getIconId()); mIconImageView.setImageDrawable(drawable); } private void toggleRefresh() { if (mProgressBar.getVisibility() == View.INVISIBLE) { mProgressBar.setVisibility(View.VISIBLE); mRefreshImg.setVisibility(View.INVISIBLE); } else { mRefreshImg.setVisibility(View.VISIBLE); mProgressBar.setVisibility(View.INVISIBLE); } } private Forcast parseForcastDetails(String jsonData) throws JSONException { Forcast forcast = new Forcast(); forcast.setCurrent(getCurrentWeather(jsonData)); forcast.setDailyForcast(getDailyForcast(jsonData)); forcast.setHourlyForcast(getHourlyForcast(jsonData)); return forcast; } private Day[] getDailyForcast(String jsonData) throws JSONException { JSONObject weatherData = new JSONObject(jsonData); String timeZone = weatherData.getString("timezone"); JSONObject dailyDataJSON = weatherData.getJSONObject("daily"); JSONArray dailyDataJSONArray = dailyDataJSON.getJSONArray("data"); Day[] dailyData = new Day[dailyDataJSONArray.length()]; for (int i = 0; i < dailyDataJSONArray.length(); i++) { JSONObject daily = dailyDataJSONArray.getJSONObject(i); Day day = new Day(); day.setTime(daily.getLong("time")); day.setIcon(daily.getString("icon")); day.setSummary(daily.getString("summary")); day.setTemperatureMax(daily.getDouble("temperatureMax")); day.setTimeZone(timeZone); dailyData[i] = day; } return dailyData; } private Hour[] getHourlyForcast(String jsonData) throws JSONException { JSONObject weatherData = new JSONObject(jsonData); String timeZone = weatherData.getString("timezone"); JSONObject hourlyDataJSON = weatherData.getJSONObject("hourly"); JSONArray hourlyDataJSONArray = hourlyDataJSON.getJSONArray("data"); Hour[] hourlyData = new Hour[hourlyDataJSONArray.length()]; for (int i = 0; i < hourlyDataJSONArray.length(); i++) { JSONObject hourly = hourlyDataJSONArray.getJSONObject(i); Hour hour = new Hour(); hour.setTime(hourly.getLong("time")); hour.setIcon(hourly.getString("icon")); hour.setSummary(hourly.getString("summary")); hour.setTemperorary(hourly.getDouble("temperature")); hour.setTimeZone(timeZone); hourlyData[i] = hour; } return hourlyData; } private Current getCurrentWeather(String jsonData) throws JSONException { JSONObject weatherData = new JSONObject(jsonData); String timeZone = weatherData.getString("timezone"); JSONObject currently = weatherData.getJSONObject("currently"); Current currentWeather = new Current(); currentWeather.setHumidity(currently.getDouble("humidity")); currentWeather.setPrecipProbaility(currently.getDouble("precipProbability")); currentWeather.setTemperature(currently.getDouble("temperature")); currentWeather.setIcon(currently.getString("icon")); currentWeather.setSummary(currently.getString("summary")); currentWeather.setTimeZone(timeZone); currentWeather.setTime(currently.getLong("time")); Log.d(TAG, currentWeather.getTime() + ""); return currentWeather; } private boolean isNetworkAvailable() { ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo info = manager.getActiveNetworkInfo(); boolean isAvalilable = false; if (info != null && info.isConnected()) { isAvalilable = true; } return isAvalilable; } private void alertUserAboutError() { AlertDialogFragment alert = new AlertDialogFragment(); alert.show(getFragmentManager(), "error_dialog"); } @OnClick(R.id.dailyButton) public void startDailyActivity(View view) { Intent intent = new Intent(this, DailyForcastActivity.class); intent.putExtra(DAILY_FORCAST, mForcast.getDailyForcast()); startActivity(intent); } @Override public void onConnected(@Nullable Bundle bundle) { Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); this.latitude = location.getLatitude(); this.longitude = location.getLongitude(); Log.v(TAG,"Location is possibily read: "+latitude +", "+longitude ); getForcast(latitude, longitude); } @Override public void onConnectionSuspended(int i) { Log.i(TAG, "Connection suspended"); mGoogleApiClient.connect(); } @Override public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + connectionResult.getErrorCode()); } @Override protected void onStart() { mGoogleApiClient.connect(); super.onStart(); } @Override protected void onStop() { mGoogleApiClient.disconnect(); super.onStop(); } }
UTF-8
Java
10,899
java
MainActivity.java
Java
[ { "context": ", double longitude) {\n String secretKey = \"3be6c051769f52fc39f671377b21b49b\";\n String forcastUrl = \"https://api.darksk", "end": 3212, "score": 0.9997074604034424, "start": 3180, "tag": "KEY", "value": "3be6c051769f52fc39f671377b21b49b" } ]
null
[]
package com.example.weatherapp; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.drawable.Drawable; import android.location.Location; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.ActivityCompat; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.example.weatherapp.Weather.Current; import com.example.weatherapp.Weather.Day; import com.example.weatherapp.Weather.Forcast; import com.example.weatherapp.Weather.Hour; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.location.LocationServices; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import okhttp3.Call; import okhttp3.Callback; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener { private static final String TAG = MainActivity.class.getSimpleName(); public static final String DAILY_FORCAST = "DAYILY_FORCAST"; Forcast mForcast; private double latitude = -37.814, longitude = 144.96332; private GoogleApiClient mGoogleApiClient = null; @BindView(R.id.humidityMeasureId) TextView mHumidity; @BindView(R.id.precepValue) TextView mPrecepValue; @BindView(R.id.precepLabel) TextView mPrecepLabel; @BindView(R.id.temperatureId) TextView mTemperature; @BindView(R.id.timeID) TextView mTime; @BindView(R.id.weatherDescription) TextView mSummary; @BindView(R.id.weatherIconId) ImageView mIconImageView; @BindView(R.id.refreshImage) ImageView mRefreshImg; @BindView(R.id.refreshProgress) ProgressBar mProgressBar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); mProgressBar.setVisibility(View.INVISIBLE); if (mGoogleApiClient == null) { mGoogleApiClient = new GoogleApiClient.Builder(this) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(LocationServices.API) .build(); } mRefreshImg.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { getForcast(latitude, longitude); } }); } private void getForcast(double latitude, double longitude) { String secretKey = "<KEY>"; String forcastUrl = "https://api.darksky.net/forecast/" + secretKey + "/" + latitude + "," + longitude; if (isNetworkAvailable()) { toggleRefresh(); OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url(forcastUrl) .build(); Call call = client.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { Log.e(TAG, "Failure to connect: ", e); } @Override public void onResponse(Call call, Response response) { try { String jsonData = response.body().string(); Log.v(TAG, jsonData); if (response.isSuccessful()) { try { mForcast = parseForcastDetails(jsonData); runOnUiThread(new Runnable() { @Override public void run() { toggleRefresh(); updateForcast(); } }); } catch (JSONException e) { e.printStackTrace(); } } else { alertUserAboutError(); } } catch (IOException e) { Log.e(TAG, "Exception caught: ", e); } } }); } else { Toast.makeText(this, "Network Connection Error", Toast.LENGTH_LONG).show(); } } private void updateForcast() { Current mCurrentWeather = mForcast.getCurrent(); mTemperature.setText(mCurrentWeather.getCelsius() + ""); mTime.setText("At time " + mCurrentWeather.getFormatedTime() + " it will be"); mHumidity.setText(mCurrentWeather.getHumidity() + ""); mPrecepValue.setText(mCurrentWeather.getPrecipProbaility() + "%"); mSummary.setText(mCurrentWeather.getSummary()); Drawable drawable = getResources().getDrawable(mCurrentWeather.getIconId()); mIconImageView.setImageDrawable(drawable); } private void toggleRefresh() { if (mProgressBar.getVisibility() == View.INVISIBLE) { mProgressBar.setVisibility(View.VISIBLE); mRefreshImg.setVisibility(View.INVISIBLE); } else { mRefreshImg.setVisibility(View.VISIBLE); mProgressBar.setVisibility(View.INVISIBLE); } } private Forcast parseForcastDetails(String jsonData) throws JSONException { Forcast forcast = new Forcast(); forcast.setCurrent(getCurrentWeather(jsonData)); forcast.setDailyForcast(getDailyForcast(jsonData)); forcast.setHourlyForcast(getHourlyForcast(jsonData)); return forcast; } private Day[] getDailyForcast(String jsonData) throws JSONException { JSONObject weatherData = new JSONObject(jsonData); String timeZone = weatherData.getString("timezone"); JSONObject dailyDataJSON = weatherData.getJSONObject("daily"); JSONArray dailyDataJSONArray = dailyDataJSON.getJSONArray("data"); Day[] dailyData = new Day[dailyDataJSONArray.length()]; for (int i = 0; i < dailyDataJSONArray.length(); i++) { JSONObject daily = dailyDataJSONArray.getJSONObject(i); Day day = new Day(); day.setTime(daily.getLong("time")); day.setIcon(daily.getString("icon")); day.setSummary(daily.getString("summary")); day.setTemperatureMax(daily.getDouble("temperatureMax")); day.setTimeZone(timeZone); dailyData[i] = day; } return dailyData; } private Hour[] getHourlyForcast(String jsonData) throws JSONException { JSONObject weatherData = new JSONObject(jsonData); String timeZone = weatherData.getString("timezone"); JSONObject hourlyDataJSON = weatherData.getJSONObject("hourly"); JSONArray hourlyDataJSONArray = hourlyDataJSON.getJSONArray("data"); Hour[] hourlyData = new Hour[hourlyDataJSONArray.length()]; for (int i = 0; i < hourlyDataJSONArray.length(); i++) { JSONObject hourly = hourlyDataJSONArray.getJSONObject(i); Hour hour = new Hour(); hour.setTime(hourly.getLong("time")); hour.setIcon(hourly.getString("icon")); hour.setSummary(hourly.getString("summary")); hour.setTemperorary(hourly.getDouble("temperature")); hour.setTimeZone(timeZone); hourlyData[i] = hour; } return hourlyData; } private Current getCurrentWeather(String jsonData) throws JSONException { JSONObject weatherData = new JSONObject(jsonData); String timeZone = weatherData.getString("timezone"); JSONObject currently = weatherData.getJSONObject("currently"); Current currentWeather = new Current(); currentWeather.setHumidity(currently.getDouble("humidity")); currentWeather.setPrecipProbaility(currently.getDouble("precipProbability")); currentWeather.setTemperature(currently.getDouble("temperature")); currentWeather.setIcon(currently.getString("icon")); currentWeather.setSummary(currently.getString("summary")); currentWeather.setTimeZone(timeZone); currentWeather.setTime(currently.getLong("time")); Log.d(TAG, currentWeather.getTime() + ""); return currentWeather; } private boolean isNetworkAvailable() { ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo info = manager.getActiveNetworkInfo(); boolean isAvalilable = false; if (info != null && info.isConnected()) { isAvalilable = true; } return isAvalilable; } private void alertUserAboutError() { AlertDialogFragment alert = new AlertDialogFragment(); alert.show(getFragmentManager(), "error_dialog"); } @OnClick(R.id.dailyButton) public void startDailyActivity(View view) { Intent intent = new Intent(this, DailyForcastActivity.class); intent.putExtra(DAILY_FORCAST, mForcast.getDailyForcast()); startActivity(intent); } @Override public void onConnected(@Nullable Bundle bundle) { Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); this.latitude = location.getLatitude(); this.longitude = location.getLongitude(); Log.v(TAG,"Location is possibily read: "+latitude +", "+longitude ); getForcast(latitude, longitude); } @Override public void onConnectionSuspended(int i) { Log.i(TAG, "Connection suspended"); mGoogleApiClient.connect(); } @Override public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + connectionResult.getErrorCode()); } @Override protected void onStart() { mGoogleApiClient.connect(); super.onStart(); } @Override protected void onStop() { mGoogleApiClient.disconnect(); super.onStop(); } }
10,872
0.63382
0.629783
304
34.851974
25.762985
144
false
false
0
0
0
0
0
0
0.605263
false
false
13
81bedfc30490b3abf8041336932f5543305cfb9e
7,430,293,452,816
474dcf63b721974bd714bce2f61c729933061d69
/src/main/java/me/iseunghan/trellospringmvc/service/PocketService.java
4ee9c5d89254f1984756f28f1edad41ce58c1de2
[]
no_license
iseunghan/trello-springmvc
https://github.com/iseunghan/trello-springmvc
dec331cb22593b1bafe3164e43f3fdf791f440d3
657efdbc28ccdcbcf9c9c19b87d5d4ae2bfcf51d
refs/heads/master
2023-06-21T11:45:46.602000
2021-07-19T13:46:44
2021-07-19T13:46:44
343,962,464
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package me.iseunghan.trellospringmvc.service; import javassist.NotFoundException; import me.iseunghan.trellospringmvc.domain.Board; import me.iseunghan.trellospringmvc.domain.Pocket; import me.iseunghan.trellospringmvc.domain.PocketDto; import me.iseunghan.trellospringmvc.repository.BoardRepository; import me.iseunghan.trellospringmvc.repository.CardRepository; import me.iseunghan.trellospringmvc.repository.PocketRepository; import org.apache.logging.log4j.util.Strings; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.time.LocalDateTime; import java.util.List; @Service public class PocketService { @Autowired private BoardRepository boardRepository; @Autowired private PocketRepository pocketRepository; @Autowired private CardRepository cardRepository; private static int positionSequence = 0; /** * 포켓을 추가하는 메소드 * @param pocketDto * @return 포켓의 id값 */ public Long addPocket(Long boardId, PocketDto pocketDto) { if (Strings.isBlank(pocketDto.getTitle())) { throw new IllegalStateException("공백을 입력할 수 없습니다."); } Board board = boardRepository.findById(boardId).get(); Pocket pocket = new Pocket(); pocket.setTitle(pocketDto.getTitle()); pocket.setPosition(pocketDto.getPosition()); pocket.setCreatedAt(LocalDateTime.now()); pocket.setUpdatedAt(pocket.getCreatedAt()); pocket.setPosition(positionSequence++); pocket.updateBoard(board); pocketRepository.save(pocket); return pocket.getId(); } /** * 해당 보드의 모든 포켓을 조회하는 메소드 * @return List<Pocket> */ public List<Pocket> findAll(Long boardId) { return pocketRepository.findPocketsByBoard_idOrderByPosition(boardId); } /** * 하나의 포켓을 조회하는 메소드 * @param id (조회하고 싶은 포켓의 아이디) * @return Pocket * @throws NotFoundException (존재하지 않는 포켓일 경우) */ public Pocket findOne(Long id) throws NotFoundException { return pocketRepository.findById(id) .orElseThrow(() -> new NotFoundException("id: " + id + "은 존재하지 않는 포켓입니다.")); } /** * 하나의 포켓을 수정하는 메소드 * * Dto 필드 값이 들어있으면 수정 후 리포지토리에 저장 * @param id (수정하고 싶은 포켓의 아이디) * @param pocketDto * @return Pocket (수정 된 포켓) * @throws NotFoundException */ public Pocket updatePocket(Long id, PocketDto pocketDto) throws NotFoundException { Pocket pocket = pocketRepository.findById(id) .orElseThrow(() -> new NotFoundException("id: " + id + "은 존재하지 않는 포켓입니다.")); if (pocketDto.getTitle() != null) { pocket.setTitle(pocketDto.getTitle()); } if (pocketDto.getBoardId() != null) { Board board = boardRepository.findById(pocketDto.getBoardId()).get(); pocket.updateBoard(board); } if (pocketDto.getPosition() > 0) { if (pocketDto.getPosition() == 10000) { pocket.setPosition(positionSequence++); }else { // position에 담긴 값은 drop item의 pocketId이다. Pocket pocket1 = pocketRepository.findById(Long.parseLong(String.valueOf(pocketDto.getPosition()))).get(); int position = pocket1.getPosition(); List<Pocket> pockets = pocketRepository.findPocketsByBoard_Id(pocketDto.getBoardId()); pockets.forEach(pocket2 -> { if (pocket2.getPosition() >= position) { pocket2.setPosition(pocket2.getPosition() + 1); } }); positionSequence++; pocket.setPosition(position); } } pocket.setUpdatedAt(LocalDateTime.now()); return pocketRepository.save(pocket); } /** * 하나의 포켓을 삭제하는 메소드 * * 해당 포켓의 아이디와, 포켓이 속한 보드의 아이디를 함께 받습니다. * @param boardId * @param pocketId * @return true(성공여부) * @throws NotFoundException */ public boolean deletePocket(Long boardId, Long pocketId) throws NotFoundException { Pocket pocket = pocketRepository.findById(pocketId) .orElseThrow(() -> new NotFoundException("id : " + pocketId + "는 존재하지 않는 포켓입니다.")); pocketRepository.delete(pocket); return true; } }
UTF-8
Java
4,825
java
PocketService.java
Java
[]
null
[]
package me.iseunghan.trellospringmvc.service; import javassist.NotFoundException; import me.iseunghan.trellospringmvc.domain.Board; import me.iseunghan.trellospringmvc.domain.Pocket; import me.iseunghan.trellospringmvc.domain.PocketDto; import me.iseunghan.trellospringmvc.repository.BoardRepository; import me.iseunghan.trellospringmvc.repository.CardRepository; import me.iseunghan.trellospringmvc.repository.PocketRepository; import org.apache.logging.log4j.util.Strings; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.time.LocalDateTime; import java.util.List; @Service public class PocketService { @Autowired private BoardRepository boardRepository; @Autowired private PocketRepository pocketRepository; @Autowired private CardRepository cardRepository; private static int positionSequence = 0; /** * 포켓을 추가하는 메소드 * @param pocketDto * @return 포켓의 id값 */ public Long addPocket(Long boardId, PocketDto pocketDto) { if (Strings.isBlank(pocketDto.getTitle())) { throw new IllegalStateException("공백을 입력할 수 없습니다."); } Board board = boardRepository.findById(boardId).get(); Pocket pocket = new Pocket(); pocket.setTitle(pocketDto.getTitle()); pocket.setPosition(pocketDto.getPosition()); pocket.setCreatedAt(LocalDateTime.now()); pocket.setUpdatedAt(pocket.getCreatedAt()); pocket.setPosition(positionSequence++); pocket.updateBoard(board); pocketRepository.save(pocket); return pocket.getId(); } /** * 해당 보드의 모든 포켓을 조회하는 메소드 * @return List<Pocket> */ public List<Pocket> findAll(Long boardId) { return pocketRepository.findPocketsByBoard_idOrderByPosition(boardId); } /** * 하나의 포켓을 조회하는 메소드 * @param id (조회하고 싶은 포켓의 아이디) * @return Pocket * @throws NotFoundException (존재하지 않는 포켓일 경우) */ public Pocket findOne(Long id) throws NotFoundException { return pocketRepository.findById(id) .orElseThrow(() -> new NotFoundException("id: " + id + "은 존재하지 않는 포켓입니다.")); } /** * 하나의 포켓을 수정하는 메소드 * * Dto 필드 값이 들어있으면 수정 후 리포지토리에 저장 * @param id (수정하고 싶은 포켓의 아이디) * @param pocketDto * @return Pocket (수정 된 포켓) * @throws NotFoundException */ public Pocket updatePocket(Long id, PocketDto pocketDto) throws NotFoundException { Pocket pocket = pocketRepository.findById(id) .orElseThrow(() -> new NotFoundException("id: " + id + "은 존재하지 않는 포켓입니다.")); if (pocketDto.getTitle() != null) { pocket.setTitle(pocketDto.getTitle()); } if (pocketDto.getBoardId() != null) { Board board = boardRepository.findById(pocketDto.getBoardId()).get(); pocket.updateBoard(board); } if (pocketDto.getPosition() > 0) { if (pocketDto.getPosition() == 10000) { pocket.setPosition(positionSequence++); }else { // position에 담긴 값은 drop item의 pocketId이다. Pocket pocket1 = pocketRepository.findById(Long.parseLong(String.valueOf(pocketDto.getPosition()))).get(); int position = pocket1.getPosition(); List<Pocket> pockets = pocketRepository.findPocketsByBoard_Id(pocketDto.getBoardId()); pockets.forEach(pocket2 -> { if (pocket2.getPosition() >= position) { pocket2.setPosition(pocket2.getPosition() + 1); } }); positionSequence++; pocket.setPosition(position); } } pocket.setUpdatedAt(LocalDateTime.now()); return pocketRepository.save(pocket); } /** * 하나의 포켓을 삭제하는 메소드 * * 해당 포켓의 아이디와, 포켓이 속한 보드의 아이디를 함께 받습니다. * @param boardId * @param pocketId * @return true(성공여부) * @throws NotFoundException */ public boolean deletePocket(Long boardId, Long pocketId) throws NotFoundException { Pocket pocket = pocketRepository.findById(pocketId) .orElseThrow(() -> new NotFoundException("id : " + pocketId + "는 존재하지 않는 포켓입니다.")); pocketRepository.delete(pocket); return true; } }
4,825
0.632597
0.629183
132
32.280304
26.270536
122
false
false
0
0
0
0
0
0
0.386364
false
false
13
a00215fefb081263945b8494db941e12541feee2
10,144,712,784,190
eac3fe22fa794b9518408fd45e321c546975c700
/edbackend/src/main/java/net/zf/edbackend/daoimpl/UserDAOImpl.java
e490fcab1c538fcfe6b70260fbab50520f59935d
[]
no_license
zaarafakih/ezeedecor
https://github.com/zaarafakih/ezeedecor
ce755cb1b2711f75b9db8436ee8af58e5a2563af
9fb1492eb5957363904163462c323f3c83a95951
refs/heads/master
2020-04-20T00:37:33.701000
2019-04-15T05:45:54
2019-04-15T05:45:54
168,523,860
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package net.zf.edbackend.daoimpl; import java.util.List; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import net.zf.edbackend.dao.UserDAO; import net.zf.edbackend.dto.address; import net.zf.edbackend.dto.cart; import net.zf.edbackend.dto.user; @Repository("userDAO") @Transactional public class UserDAOImpl implements UserDAO { @Autowired private SessionFactory sessionFactory; @Override public boolean addUser(user user) { try{ sessionFactory.getCurrentSession().persist(user); return true; }catch(Exception ex){ return false; } } @Override public boolean updateCart(cart cart) { try{ sessionFactory.getCurrentSession().update(cart); return true; }catch(Exception ex){ return false; } } @Override public boolean addAddress(address address) { try{ sessionFactory.getCurrentSession().persist(address); return true; }catch(Exception ex){ return false; } } @Override public user getUserByEmail(String emailid) { String sql="FROM user WHERE email=:emailid"; try{ return sessionFactory.getCurrentSession().createQuery(sql, user.class).setParameter("emailid", emailid).getSingleResult(); }catch(Exception ex){ ex.printStackTrace(); return null; } } @Override public address getBillingAddress(user user){ String sql="FROM address WHERE userr= :user AND billing= :billing"; try{ return sessionFactory .getCurrentSession() .createQuery(sql, address.class) .setParameter("user", user) .setParameter("billing", true) .getSingleResult(); }catch(Exception ex){ ex.printStackTrace(); return null; } } @Override public List<address> listShippingAddress(user user) { String sql="FROM address WHERE userr= :user AND shipping=:shipping"; try{ return sessionFactory.getCurrentSession() .createQuery(sql, address.class) .setParameter("user", user) .setParameter("shipping", true) .getResultList(); }catch(Exception ex){ ex.printStackTrace(); return null; } } }
UTF-8
Java
2,217
java
UserDAOImpl.java
Java
[]
null
[]
package net.zf.edbackend.daoimpl; import java.util.List; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import net.zf.edbackend.dao.UserDAO; import net.zf.edbackend.dto.address; import net.zf.edbackend.dto.cart; import net.zf.edbackend.dto.user; @Repository("userDAO") @Transactional public class UserDAOImpl implements UserDAO { @Autowired private SessionFactory sessionFactory; @Override public boolean addUser(user user) { try{ sessionFactory.getCurrentSession().persist(user); return true; }catch(Exception ex){ return false; } } @Override public boolean updateCart(cart cart) { try{ sessionFactory.getCurrentSession().update(cart); return true; }catch(Exception ex){ return false; } } @Override public boolean addAddress(address address) { try{ sessionFactory.getCurrentSession().persist(address); return true; }catch(Exception ex){ return false; } } @Override public user getUserByEmail(String emailid) { String sql="FROM user WHERE email=:emailid"; try{ return sessionFactory.getCurrentSession().createQuery(sql, user.class).setParameter("emailid", emailid).getSingleResult(); }catch(Exception ex){ ex.printStackTrace(); return null; } } @Override public address getBillingAddress(user user){ String sql="FROM address WHERE userr= :user AND billing= :billing"; try{ return sessionFactory .getCurrentSession() .createQuery(sql, address.class) .setParameter("user", user) .setParameter("billing", true) .getSingleResult(); }catch(Exception ex){ ex.printStackTrace(); return null; } } @Override public List<address> listShippingAddress(user user) { String sql="FROM address WHERE userr= :user AND shipping=:shipping"; try{ return sessionFactory.getCurrentSession() .createQuery(sql, address.class) .setParameter("user", user) .setParameter("shipping", true) .getResultList(); }catch(Exception ex){ ex.printStackTrace(); return null; } } }
2,217
0.717636
0.717636
102
20.735294
21.122856
125
false
false
0
0
0
0
0
0
2.215686
false
false
13
e3f6bd9a1207b4798ab2981cc7173d7d7bf0df02
17,111,149,739,780
2bea0216e594c8e7362a35cbbe6ee0bde71660d4
/app/src/main/java/com/harry/ebangbang/function/errand_list/going_on/GoingOnFragment.java
823d300f19109a55af75bffbf8efaee038fe3197
[]
no_license
harryhasai/EBangBang
https://github.com/harryhasai/EBangBang
e3d4bf38b69c6c268da54e91b92225d839c10c73
a24f1afe16509725b7783ee4152c9fed617bd31c
refs/heads/master
2020-04-04T22:26:56.113000
2019-02-21T02:51:06
2019-02-21T02:51:06
156,324,119
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.harry.ebangbang.function.errand_list.going_on; import android.content.Intent; import android.net.Uri; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import com.chad.library.adapter.base.BaseQuickAdapter; import com.harry.ebangbang.R; import com.harry.ebangbang.app_final.DisposableFinal; import com.harry.ebangbang.base.BaseFragment; import com.harry.ebangbang.network.entity.ErrandListEntity; import java.util.ArrayList; import java.util.List; /** * Created by Harry on 2018/12/15. * 进行中的跑腿订单 */ public class GoingOnFragment extends BaseFragment<GoingOnPresenter> { private GoingOnAdapter adapter; @Override protected int setupView() { return R.layout.fragment_going_on; } @Override protected void initView(View view) { RecyclerView recyclerView = view.findViewById(R.id.recycler_view); recyclerView.setLayoutManager(new LinearLayoutManager(mActivity)); adapter = new GoingOnAdapter(R.layout.item_going_on); recyclerView.setAdapter(adapter); adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() { @Override public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) { ErrandListEntity.DataBean bean = (ErrandListEntity.DataBean) adapter.getData().get(position); switch (view.getId()) { case R.id.tv_call_rider: Intent intent = new Intent(Intent.ACTION_DIAL); Uri data = Uri.parse("tel:" + bean.ridePhone); intent.setData(data); startActivity(intent); break; case R.id.tv_rider_location: Intent intent1 = new Intent(mActivity, RiderLocationActivity.class); intent1.putExtra("latitude", bean.rideLatitude); intent1.putExtra("longitude", bean.rideLongitude); startActivity(intent1); break; } } }); mPresenter.getGoingOnList(); } @Override protected ArrayList<Object> cancelNetWork() { ArrayList<Object> tags = new ArrayList<>(); tags.add(DisposableFinal.GOING_ON_FRAGMENT_GET_GOING_ON_LIST); return tags; } @Override protected GoingOnPresenter bindPresenter() { return new GoingOnPresenter(); } public void getGoingOnList(List<ErrandListEntity.DataBean> data) { adapter.setNewData(data); } }
UTF-8
Java
2,694
java
GoingOnFragment.java
Java
[ { "context": "rayList;\nimport java.util.List;\n\n/**\n * Created by Harry on 2018/12/15.\n * 进行中的跑腿订单\n */\npublic class Going", "end": 564, "score": 0.9935771822929382, "start": 559, "tag": "NAME", "value": "Harry" } ]
null
[]
package com.harry.ebangbang.function.errand_list.going_on; import android.content.Intent; import android.net.Uri; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import com.chad.library.adapter.base.BaseQuickAdapter; import com.harry.ebangbang.R; import com.harry.ebangbang.app_final.DisposableFinal; import com.harry.ebangbang.base.BaseFragment; import com.harry.ebangbang.network.entity.ErrandListEntity; import java.util.ArrayList; import java.util.List; /** * Created by Harry on 2018/12/15. * 进行中的跑腿订单 */ public class GoingOnFragment extends BaseFragment<GoingOnPresenter> { private GoingOnAdapter adapter; @Override protected int setupView() { return R.layout.fragment_going_on; } @Override protected void initView(View view) { RecyclerView recyclerView = view.findViewById(R.id.recycler_view); recyclerView.setLayoutManager(new LinearLayoutManager(mActivity)); adapter = new GoingOnAdapter(R.layout.item_going_on); recyclerView.setAdapter(adapter); adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() { @Override public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) { ErrandListEntity.DataBean bean = (ErrandListEntity.DataBean) adapter.getData().get(position); switch (view.getId()) { case R.id.tv_call_rider: Intent intent = new Intent(Intent.ACTION_DIAL); Uri data = Uri.parse("tel:" + bean.ridePhone); intent.setData(data); startActivity(intent); break; case R.id.tv_rider_location: Intent intent1 = new Intent(mActivity, RiderLocationActivity.class); intent1.putExtra("latitude", bean.rideLatitude); intent1.putExtra("longitude", bean.rideLongitude); startActivity(intent1); break; } } }); mPresenter.getGoingOnList(); } @Override protected ArrayList<Object> cancelNetWork() { ArrayList<Object> tags = new ArrayList<>(); tags.add(DisposableFinal.GOING_ON_FRAGMENT_GET_GOING_ON_LIST); return tags; } @Override protected GoingOnPresenter bindPresenter() { return new GoingOnPresenter(); } public void getGoingOnList(List<ErrandListEntity.DataBean> data) { adapter.setNewData(data); } }
2,694
0.640777
0.635549
78
33.333332
27.788887
109
false
false
0
0
0
0
0
0
0.538462
false
false
13
f1012f72fbede488e9e1db9aad1a69fdab0be682
31,172,872,662,414
f8a0e4edc8979c3d18da26b0f38fc965a7d3ffb7
/src/main/java/org/quantrserver/table/User.java
9edbf04b84f272f883037bb3a8305ace4f00c268
[]
no_license
mcheung63/quantr-server
https://github.com/mcheung63/quantr-server
35986370113acdf405393b0ca74b4e522d63d17a
da4c90e7d7bc1ef54033871fdcc1334b5cc6e888
refs/heads/master
2017-11-02T07:54:58.185000
2016-07-29T19:18:53
2016-07-29T19:18:53
64,388,587
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.quantrserver.table; import static javax.persistence.GenerationType.IDENTITY; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "user") public class User { @Id @GeneratedValue(strategy = IDENTITY) @Column(name = "id", unique = true, nullable = false) public Integer id; public String username; public String password; public boolean enable; }
UTF-8
Java
505
java
User.java
Java
[]
null
[]
package org.quantrserver.table; import static javax.persistence.GenerationType.IDENTITY; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "user") public class User { @Id @GeneratedValue(strategy = IDENTITY) @Column(name = "id", unique = true, nullable = false) public Integer id; public String username; public String password; public boolean enable; }
505
0.782178
0.782178
22
21.954546
16.625494
56
false
false
0
0
0
0
0
0
0.909091
false
false
13
18a1a064b262d9b3e642855a8cd55693a6709eb2
31,172,872,658,356
5f5613bb5d36dd3b4f8c66b0b926fe4b6334699c
/src/examples/Geometry.java
c89eca8666c3b78d084fd7916f9225e6877c47e6
[]
no_license
gppeixoto/sparta-testgen
https://github.com/gppeixoto/sparta-testgen
60fc3aa5fcb302b7ee5e7e3c84be9892ded35c05
22382ca2a6912b1837752764ab76f69e9ad53c84
refs/heads/master
2020-04-11T00:38:41.622000
2014-07-31T21:26:01
2014-07-31T21:26:01
22,322,165
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package examples; class Rectangle { private double length; private double height; public Rectangle(double x, double y){ this.length = x; this.height = y; } public double getLength(){ return this.length; } public double getHeight(){ return this.height; } public void setLength(double l){ this.length = l; } public void setHeight(double h){ this.height = h; } } class Circle{ private double radius; public Circle(double r){ this.radius = r; } public void setRadius(double r){ this.radius = r; } public double getRadius(){ return this.radius; } public double shrink(double factor){ return this.radius*factor; } } public class Geometry { public static void main(String[] args){ Circle c = new Circle(3.14); Rectangle r = new Rectangle(10,0.8); double s = c.shrink(0.8); double g = c.getRadius(); double sX = 0.8*g; double sY = 0.6*s; r.setLength(sX); r.setHeight(sY); } }
UTF-8
Java
1,016
java
Geometry.java
Java
[]
null
[]
package examples; class Rectangle { private double length; private double height; public Rectangle(double x, double y){ this.length = x; this.height = y; } public double getLength(){ return this.length; } public double getHeight(){ return this.height; } public void setLength(double l){ this.length = l; } public void setHeight(double h){ this.height = h; } } class Circle{ private double radius; public Circle(double r){ this.radius = r; } public void setRadius(double r){ this.radius = r; } public double getRadius(){ return this.radius; } public double shrink(double factor){ return this.radius*factor; } } public class Geometry { public static void main(String[] args){ Circle c = new Circle(3.14); Rectangle r = new Rectangle(10,0.8); double s = c.shrink(0.8); double g = c.getRadius(); double sX = 0.8*g; double sY = 0.6*s; r.setLength(sX); r.setHeight(sY); } }
1,016
0.615157
0.602362
60
15.933333
12.912354
41
false
false
0
0
0
0
0
0
0.4
false
false
13
14869c95ad2ede2b75235271d00cc13e4e2afb52
10,986,526,367,137
be33d9a8b9df89f63943b566d085e3a445c95489
/GrainSystem/src/com/aisino/grain/ui/HelpActivity.java
4ca44e4712e0be8f1ae65204f40310ac51c3cb6a
[]
no_license
VegeChou/GrainSystem
https://github.com/VegeChou/GrainSystem
fc5633b8677bf45d688449b1d8b01f655c28cfd8
e2999b820ea93c8ecd575f9cd44141a91fa52aa3
refs/heads/master
2021-01-01T20:11:18.960000
2014-03-10T09:06:37
2014-03-10T09:06:37
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.aisino.grain.ui; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import com.aisino.grain.R; import com.aisino.grain.beans.ApkInfo; import com.aisino.grain.model.Constants; import com.aisino.grain.ui.util.WaitDialog; import com.google.gson.Gson; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.DialogInterface.OnCancelListener; import android.content.SharedPreferences.Editor; import android.content.pm.PackageManager.NameNotFoundException; import android.graphics.drawable.ColorDrawable; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.util.Log; import android.view.Gravity; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnKeyListener; import android.view.WindowManager.LayoutParams; import android.widget.Button; import android.widget.EditText; import android.widget.PopupWindow; import android.widget.TextView; import android.widget.Toast; public class HelpActivity extends BaseActivity { private static final String TAG = "HelpActivity"; private static final int NOT_CON_SERVER = 0; private static final int NO_SD_CARD = 1; private static final int DOWNLOADING = 2; private static final int DOWNLOAD_FINISH = 3; private static final int DOWNLOAD_SIZE = 4; //UI private Button mSoftwareUpdateButton = null; private TextView mAboutTextView = null; private ProgressDialog mProgressDialog = null; private EditText mUpdateServerIPEditText = null; private EditText mUpdateServerPortEditText = null; private EditText mUpdateServerCheckPathEditText = null; private EditText mUpdateServerDownloadPathEditText = null; //Menu菜单 private PopupWindow mPopupWindowMenu = null; //Menu菜单 private LayoutInflater mLayoutInflater = null; private TextView mTextView = null; //多线程 private Handler mThreadHandler = null; //System private Context mContext = null; private SharedPreferences mUpdateServerSharedPreferences = null; private Editor mUpdateServerEditor = null; //Data private String mAbout = null; private ApkInfo mCurrentApkInfo = null; private ApkInfo mServerApkInfo = null; private String mUpdateServerIP = null; private String mUpdateServerPort = null; private String mUpdateServerCheckPath = null; private String mUpdateServerDownloadPath = null; private String mUpdateServerCheckURL = null; private String mUpdateServerDownloadURL = null; private int mFileSize = 0; private int mDownloadSize = 0; private Handler mHandler = new Handler(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_help); InitCtrl(); } @Override public boolean onCreateOptionsMenu(Menu menu) { //弹出自定义Menu // Inflate the menu; this adds items to the action bar if it is present. menu.add("menu");// 必须创建一项 return true; } private void InitCtrl() { //UI mAboutTextView = (TextView)findViewById(R.id.help_tv_about); mSoftwareUpdateButton = (Button)findViewById(R.id.help_btn_software_update); mSoftwareUpdateButton.setOnClickListener(new SoftwareUpdateOnClickListener()); mThreadHandler = new Handler(){ @Override public void handleMessage(Message msg) { switch (msg.what) { case NOT_CON_SERVER: Toast.makeText(mContext, "无法连接服务器,请检查网络!", Toast.LENGTH_LONG).show(); break; case NO_SD_CARD: Toast.makeText(mContext, "下载更新包,请插入SD卡!", Toast.LENGTH_LONG).show(); break; case DOWNLOADING: mProgressDialog.setProgress(mDownloadSize); break; case DOWNLOAD_FINISH: Toast.makeText(mContext, "下载已完成!", Toast.LENGTH_LONG).show(); break; case DOWNLOAD_SIZE: mProgressDialog.setMax(mFileSize); break; default: break; } super.handleMessage(msg); } }; //System mContext = this; //Data mCurrentApkInfo = new ApkInfo(); mServerApkInfo = new ApkInfo(); //初始化菜单 InitPopupWindowMenu(); //显示相关信息 DisplayInfo(); } @Override protected void onResume() { mUpdateServerSharedPreferences = getSharedPreferences("AppUpdate", Context.MODE_PRIVATE); mUpdateServerEditor = mUpdateServerSharedPreferences.edit(); mUpdateServerIP = mUpdateServerSharedPreferences.getString("Update_Server_IP", getString(R.string.update_server_ip)); mUpdateServerPort = mUpdateServerSharedPreferences.getString("Update_Server_Port", getString(R.string.update_server_port)); mUpdateServerCheckPath = mUpdateServerSharedPreferences.getString("Update_Server_Check_Path", getString(R.string.update_server_check_path)); mUpdateServerDownloadPath = mUpdateServerSharedPreferences.getString("Update_Server_Download_Path", getString(R.string.update_server_download_path)); mUpdateServerCheckURL = "http://" + mUpdateServerIP + ":" + mUpdateServerPort + mUpdateServerCheckPath; mUpdateServerDownloadURL = "http://" + mUpdateServerIP + ":" + mUpdateServerPort + mUpdateServerDownloadPath; super.onResume(); } /** * 拦截MENU,实现自定义菜单 */ @Override public boolean onMenuOpened(int featureId, Menu menu) { if(mPopupWindowMenu != null){ if(!mPopupWindowMenu.isShowing()){ /*最重要的一步:弹出显示 在指定的位置(parent) 最后两个参数 是相对于 x / y 轴的坐标*/ mPopupWindowMenu.showAtLocation(mTextView, Gravity.CENTER, 0, 0); } else { mPopupWindowMenu.dismiss(); } } return false;// 返回为true 则显示系统menu } public void InitPopupWindowMenu(){ mLayoutInflater = (LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View view = mLayoutInflater.inflate(R.layout.menu_settings, null); mTextView = (TextView)view.findViewById(R.id.tv); mTextView.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { LayoutInflater factory = LayoutInflater.from(mContext); final View textEntryView = factory.inflate(R.layout.update_url_dialog, null); mUpdateServerIPEditText = (EditText) textEntryView.findViewById(R.id.update_url_dialog_et_update_server_ip); mUpdateServerPortEditText = (EditText) textEntryView.findViewById(R.id.update_url_dialog_et_update_server_port); mUpdateServerCheckPathEditText = (EditText) textEntryView.findViewById(R.id.update_url_dialog_et_update_server_check_path); mUpdateServerDownloadPathEditText = (EditText) textEntryView.findViewById(R.id.update_url_dialog_et_update_server_download_path); mUpdateServerIPEditText.setText(mUpdateServerIP); mUpdateServerPortEditText.setText(mUpdateServerPort); mUpdateServerCheckPathEditText.setText(mUpdateServerCheckPath); mUpdateServerDownloadPathEditText.setText(mUpdateServerDownloadPath); new AlertDialog.Builder(mContext) .setTitle("更新服务器配置") .setView(textEntryView) .setPositiveButton("确认", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { mUpdateServerIP = mUpdateServerIPEditText.getText().toString(); mUpdateServerEditor.putString("Update_Server_IP", mUpdateServerIP); mUpdateServerPort = mUpdateServerPortEditText.getText().toString(); mUpdateServerEditor.putString("Update_Server_Port", mUpdateServerPort); mUpdateServerCheckPath = mUpdateServerCheckPathEditText.getText().toString(); mUpdateServerEditor.putString("Update_Server_Check_Path", mUpdateServerCheckPath); mUpdateServerDownloadPath = mUpdateServerDownloadPathEditText.getText().toString(); mUpdateServerEditor.putString("Update_Server_Download_Path", mUpdateServerDownloadPath); mUpdateServerEditor.commit(); } }) .create().show(); mPopupWindowMenu.dismiss(); } }); mTextView.setFocusableInTouchMode(true); mTextView.setOnKeyListener(new OnKeyListener() { @Override public boolean onKey(View arg0, int arg1, KeyEvent arg2) { if ((arg1 == KeyEvent.KEYCODE_MENU)&&(mPopupWindowMenu.isShowing())) { mPopupWindowMenu.dismiss(); return true; } return false; } }); //用Popupwindow弹出menu mPopupWindowMenu = new PopupWindow(view,LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT); mPopupWindowMenu.setFocusable(true); mPopupWindowMenu.setBackgroundDrawable(new ColorDrawable()); } private void DisplayInfo() { mCurrentApkInfo = GetCurrentVerInfo(); mAbout = getString(R.string.title)+"\n\n"+getString(R.string.copyright)+"\n"+"Version:"+mCurrentApkInfo.getVersionName(); mAboutTextView.setText(mAbout); } class SoftwareUpdateOnClickListener implements OnClickListener{ @Override public void onClick(View v) { mProcessDialog = WaitDialog.createLoadingDialog(mContext, "正在校验中......"); OnCancelListener LoadingDialogCancelListener = new OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { } }; mProcessDialog.setOnCancelListener(LoadingDialogCancelListener); mProcessDialog.show(); new Thread(new Runnable() { @Override public void run() { Looper.prepare(); try { //连接系统更新服务器,查看网络是否连接 if (!CheckToUpdate()) { Message message = new Message(); message.what = NOT_CON_SERVER; mThreadHandler.sendMessage(message); } } catch (NameNotFoundException e) { e.printStackTrace(); } mProcessDialog.dismiss(); Looper.loop(); } }).start(); } } private ApkInfo GetCurrentVerInfo(){ ApkInfo ApkInfo = new ApkInfo(); try { ApkInfo.setPackageName(mContext.getPackageManager().getPackageInfo(mContext.getPackageName(), 0).packageName); ApkInfo.setVersionCode(mContext.getPackageManager().getPackageInfo(mContext.getPackageName(), 0).versionCode); ApkInfo.setVersionName(mContext.getPackageManager().getPackageInfo(mContext.getPackageName(), 0).versionName); } catch (NameNotFoundException e) { e.printStackTrace(); ApkInfo.setVersionCode(0); ApkInfo.setVersionName(""); } return ApkInfo; } //check new version and update private boolean CheckToUpdate() throws NameNotFoundException { if(GetServerVersion()){ if((mServerApkInfo.getVersionCode() > mCurrentApkInfo.getVersionCode()) && (mServerApkInfo.getPackageName().equals(mCurrentApkInfo.getPackageName()))){ //Current Version is old ShowUpdateDialog(); } return true; } else { return false; } } class UpdateOnClickListener implements OnClickListener{ @Override public void onClick(View v) { mPopupWindowDialog.dismiss(); ShowDownloadProgressBar(); } } //show Update Dialog private void ShowUpdateDialog(){ String msg = "当前版本:" + mCurrentApkInfo.getVersionName() + "\n" + "发现新版本:" + mServerApkInfo.getVersionName() + "\n" + "是否更新?"; mPopupWindowDialog.setOKOnClickListener(new UpdateOnClickListener()); mPopupWindowDialog.setTitle("软件更新"); mPopupWindowDialog.setCancelVisible(true); mPopupWindowDialog.showMessage(msg); } private void ShowDownloadProgressBar() { mProgressDialog = new ProgressDialog(HelpActivity.this); mProgressDialog.setTitle("正在下载"); mProgressDialog.setMax(mFileSize); mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); mProgressDialog.show(); new Thread(new Runnable() { @Override public void run(){ DownloadUpdate(mUpdateServerDownloadURL); } }).start(); } //Get Server Version from Server:version.json private boolean GetServerVersion() { try{ String verjson = GetApkInfoFromServer(mUpdateServerCheckURL); Gson gson = new Gson(); ApkInfo apkInfo = gson.fromJson(verjson, ApkInfo.class); try { mServerApkInfo.setVersionCode(apkInfo.getVersionCode()); mServerApkInfo.setVersionName(apkInfo.getVersionName()); mServerApkInfo.setPackageName(apkInfo.getPackageName()); } catch (Exception e) { mServerApkInfo.setVersionCode(0); mServerApkInfo.setVersionName(""); mServerApkInfo.setPackageName(""); return false; } }catch(Exception e){ Log.e(TAG, e.getMessage()); return false; } return true; } private void DownloadUpdate(String url){ HttpClient client = new DefaultHttpClient(); HttpGet get = new HttpGet(url); HttpResponse response; try { response = client.execute(get); HttpEntity entity = response.getEntity(); mFileSize = (int)entity.getContentLength(); Log.isLoggable("DownTag", mFileSize); Message message_size = new Message(); message_size.what = DOWNLOAD_SIZE; mThreadHandler.sendMessage(message_size); InputStream inputStream = entity.getContent(); if(inputStream == null){ throw new RuntimeException("isStream is null"); } if (!ExistSDCard()) { Message message = new Message(); message.what = NO_SD_CARD; mThreadHandler.sendMessage(message); mProgressDialog.dismiss(); return; } File file = new File(Environment.getExternalStorageDirectory(),Constants.APP_NAME); FileOutputStream fileOutputStream = new FileOutputStream(file); byte[] buf = new byte[1024]; int readNum = -1; do{ readNum = inputStream.read(buf); if(readNum <= 0) break; fileOutputStream.write(buf, 0, readNum); mDownloadSize += readNum; Message message = new Message(); message.what = DOWNLOADING; mThreadHandler.sendMessage(message); try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } } while(true); inputStream.close(); fileOutputStream.close(); Message message = new Message(); message.what = DOWNLOAD_FINISH; mThreadHandler.sendMessage(message); HaveDownLoad(); }catch(ClientProtocolException e){ e.printStackTrace(); mProgressDialog.dismiss(); }catch(IOException e){ e.printStackTrace(); mProgressDialog.dismiss(); } } //cancel progressBar and start new App protected void HaveDownLoad() { mHandler.post(new Runnable(){ public void run(){ mProgressDialog.cancel(); Dialog installDialog = new AlertDialog.Builder(HelpActivity.this) .setTitle("下载完成") .setMessage("是否安装新的应用") .setPositiveButton("确定", new DialogInterface.OnClickListener(){ @Override public void onClick(DialogInterface dialog, int which) { InstallUpdateApk(); finish(); } }) .setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { finish(); } }) .create(); installDialog.show(); } }); } private void InstallUpdateApk() { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType(Uri.fromFile( new File(Environment.getExternalStorageDirectory(),Constants.APP_NAME)), "application/vnd.android.package-archive"); startActivity(intent); } /** * 获取网址内容 * @param url * @return * @throws Exception */ private String GetApkInfoFromServer(String url) throws Exception{ StringBuilder sb = new StringBuilder(); HttpClient client = new DefaultHttpClient(); HttpParams httpParams = client.getParams(); //设置网络超时参数 HttpConnectionParams.setConnectionTimeout(httpParams, 5000); HttpConnectionParams.setSoTimeout(httpParams, 8000); HttpResponse response = client.execute(new HttpGet(url)); HttpEntity entity = response.getEntity(); if (entity != null) { BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"), 8192); String line = null; while ((line = reader.readLine())!= null){ sb.append(line + "\n"); } reader.close(); } return sb.toString(); } private boolean ExistSDCard() { if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { return true; } else return false; } }
UTF-8
Java
17,772
java
HelpActivity.java
Java
[]
null
[]
package com.aisino.grain.ui; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import com.aisino.grain.R; import com.aisino.grain.beans.ApkInfo; import com.aisino.grain.model.Constants; import com.aisino.grain.ui.util.WaitDialog; import com.google.gson.Gson; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.DialogInterface.OnCancelListener; import android.content.SharedPreferences.Editor; import android.content.pm.PackageManager.NameNotFoundException; import android.graphics.drawable.ColorDrawable; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.util.Log; import android.view.Gravity; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnKeyListener; import android.view.WindowManager.LayoutParams; import android.widget.Button; import android.widget.EditText; import android.widget.PopupWindow; import android.widget.TextView; import android.widget.Toast; public class HelpActivity extends BaseActivity { private static final String TAG = "HelpActivity"; private static final int NOT_CON_SERVER = 0; private static final int NO_SD_CARD = 1; private static final int DOWNLOADING = 2; private static final int DOWNLOAD_FINISH = 3; private static final int DOWNLOAD_SIZE = 4; //UI private Button mSoftwareUpdateButton = null; private TextView mAboutTextView = null; private ProgressDialog mProgressDialog = null; private EditText mUpdateServerIPEditText = null; private EditText mUpdateServerPortEditText = null; private EditText mUpdateServerCheckPathEditText = null; private EditText mUpdateServerDownloadPathEditText = null; //Menu菜单 private PopupWindow mPopupWindowMenu = null; //Menu菜单 private LayoutInflater mLayoutInflater = null; private TextView mTextView = null; //多线程 private Handler mThreadHandler = null; //System private Context mContext = null; private SharedPreferences mUpdateServerSharedPreferences = null; private Editor mUpdateServerEditor = null; //Data private String mAbout = null; private ApkInfo mCurrentApkInfo = null; private ApkInfo mServerApkInfo = null; private String mUpdateServerIP = null; private String mUpdateServerPort = null; private String mUpdateServerCheckPath = null; private String mUpdateServerDownloadPath = null; private String mUpdateServerCheckURL = null; private String mUpdateServerDownloadURL = null; private int mFileSize = 0; private int mDownloadSize = 0; private Handler mHandler = new Handler(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_help); InitCtrl(); } @Override public boolean onCreateOptionsMenu(Menu menu) { //弹出自定义Menu // Inflate the menu; this adds items to the action bar if it is present. menu.add("menu");// 必须创建一项 return true; } private void InitCtrl() { //UI mAboutTextView = (TextView)findViewById(R.id.help_tv_about); mSoftwareUpdateButton = (Button)findViewById(R.id.help_btn_software_update); mSoftwareUpdateButton.setOnClickListener(new SoftwareUpdateOnClickListener()); mThreadHandler = new Handler(){ @Override public void handleMessage(Message msg) { switch (msg.what) { case NOT_CON_SERVER: Toast.makeText(mContext, "无法连接服务器,请检查网络!", Toast.LENGTH_LONG).show(); break; case NO_SD_CARD: Toast.makeText(mContext, "下载更新包,请插入SD卡!", Toast.LENGTH_LONG).show(); break; case DOWNLOADING: mProgressDialog.setProgress(mDownloadSize); break; case DOWNLOAD_FINISH: Toast.makeText(mContext, "下载已完成!", Toast.LENGTH_LONG).show(); break; case DOWNLOAD_SIZE: mProgressDialog.setMax(mFileSize); break; default: break; } super.handleMessage(msg); } }; //System mContext = this; //Data mCurrentApkInfo = new ApkInfo(); mServerApkInfo = new ApkInfo(); //初始化菜单 InitPopupWindowMenu(); //显示相关信息 DisplayInfo(); } @Override protected void onResume() { mUpdateServerSharedPreferences = getSharedPreferences("AppUpdate", Context.MODE_PRIVATE); mUpdateServerEditor = mUpdateServerSharedPreferences.edit(); mUpdateServerIP = mUpdateServerSharedPreferences.getString("Update_Server_IP", getString(R.string.update_server_ip)); mUpdateServerPort = mUpdateServerSharedPreferences.getString("Update_Server_Port", getString(R.string.update_server_port)); mUpdateServerCheckPath = mUpdateServerSharedPreferences.getString("Update_Server_Check_Path", getString(R.string.update_server_check_path)); mUpdateServerDownloadPath = mUpdateServerSharedPreferences.getString("Update_Server_Download_Path", getString(R.string.update_server_download_path)); mUpdateServerCheckURL = "http://" + mUpdateServerIP + ":" + mUpdateServerPort + mUpdateServerCheckPath; mUpdateServerDownloadURL = "http://" + mUpdateServerIP + ":" + mUpdateServerPort + mUpdateServerDownloadPath; super.onResume(); } /** * 拦截MENU,实现自定义菜单 */ @Override public boolean onMenuOpened(int featureId, Menu menu) { if(mPopupWindowMenu != null){ if(!mPopupWindowMenu.isShowing()){ /*最重要的一步:弹出显示 在指定的位置(parent) 最后两个参数 是相对于 x / y 轴的坐标*/ mPopupWindowMenu.showAtLocation(mTextView, Gravity.CENTER, 0, 0); } else { mPopupWindowMenu.dismiss(); } } return false;// 返回为true 则显示系统menu } public void InitPopupWindowMenu(){ mLayoutInflater = (LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View view = mLayoutInflater.inflate(R.layout.menu_settings, null); mTextView = (TextView)view.findViewById(R.id.tv); mTextView.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { LayoutInflater factory = LayoutInflater.from(mContext); final View textEntryView = factory.inflate(R.layout.update_url_dialog, null); mUpdateServerIPEditText = (EditText) textEntryView.findViewById(R.id.update_url_dialog_et_update_server_ip); mUpdateServerPortEditText = (EditText) textEntryView.findViewById(R.id.update_url_dialog_et_update_server_port); mUpdateServerCheckPathEditText = (EditText) textEntryView.findViewById(R.id.update_url_dialog_et_update_server_check_path); mUpdateServerDownloadPathEditText = (EditText) textEntryView.findViewById(R.id.update_url_dialog_et_update_server_download_path); mUpdateServerIPEditText.setText(mUpdateServerIP); mUpdateServerPortEditText.setText(mUpdateServerPort); mUpdateServerCheckPathEditText.setText(mUpdateServerCheckPath); mUpdateServerDownloadPathEditText.setText(mUpdateServerDownloadPath); new AlertDialog.Builder(mContext) .setTitle("更新服务器配置") .setView(textEntryView) .setPositiveButton("确认", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { mUpdateServerIP = mUpdateServerIPEditText.getText().toString(); mUpdateServerEditor.putString("Update_Server_IP", mUpdateServerIP); mUpdateServerPort = mUpdateServerPortEditText.getText().toString(); mUpdateServerEditor.putString("Update_Server_Port", mUpdateServerPort); mUpdateServerCheckPath = mUpdateServerCheckPathEditText.getText().toString(); mUpdateServerEditor.putString("Update_Server_Check_Path", mUpdateServerCheckPath); mUpdateServerDownloadPath = mUpdateServerDownloadPathEditText.getText().toString(); mUpdateServerEditor.putString("Update_Server_Download_Path", mUpdateServerDownloadPath); mUpdateServerEditor.commit(); } }) .create().show(); mPopupWindowMenu.dismiss(); } }); mTextView.setFocusableInTouchMode(true); mTextView.setOnKeyListener(new OnKeyListener() { @Override public boolean onKey(View arg0, int arg1, KeyEvent arg2) { if ((arg1 == KeyEvent.KEYCODE_MENU)&&(mPopupWindowMenu.isShowing())) { mPopupWindowMenu.dismiss(); return true; } return false; } }); //用Popupwindow弹出menu mPopupWindowMenu = new PopupWindow(view,LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT); mPopupWindowMenu.setFocusable(true); mPopupWindowMenu.setBackgroundDrawable(new ColorDrawable()); } private void DisplayInfo() { mCurrentApkInfo = GetCurrentVerInfo(); mAbout = getString(R.string.title)+"\n\n"+getString(R.string.copyright)+"\n"+"Version:"+mCurrentApkInfo.getVersionName(); mAboutTextView.setText(mAbout); } class SoftwareUpdateOnClickListener implements OnClickListener{ @Override public void onClick(View v) { mProcessDialog = WaitDialog.createLoadingDialog(mContext, "正在校验中......"); OnCancelListener LoadingDialogCancelListener = new OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { } }; mProcessDialog.setOnCancelListener(LoadingDialogCancelListener); mProcessDialog.show(); new Thread(new Runnable() { @Override public void run() { Looper.prepare(); try { //连接系统更新服务器,查看网络是否连接 if (!CheckToUpdate()) { Message message = new Message(); message.what = NOT_CON_SERVER; mThreadHandler.sendMessage(message); } } catch (NameNotFoundException e) { e.printStackTrace(); } mProcessDialog.dismiss(); Looper.loop(); } }).start(); } } private ApkInfo GetCurrentVerInfo(){ ApkInfo ApkInfo = new ApkInfo(); try { ApkInfo.setPackageName(mContext.getPackageManager().getPackageInfo(mContext.getPackageName(), 0).packageName); ApkInfo.setVersionCode(mContext.getPackageManager().getPackageInfo(mContext.getPackageName(), 0).versionCode); ApkInfo.setVersionName(mContext.getPackageManager().getPackageInfo(mContext.getPackageName(), 0).versionName); } catch (NameNotFoundException e) { e.printStackTrace(); ApkInfo.setVersionCode(0); ApkInfo.setVersionName(""); } return ApkInfo; } //check new version and update private boolean CheckToUpdate() throws NameNotFoundException { if(GetServerVersion()){ if((mServerApkInfo.getVersionCode() > mCurrentApkInfo.getVersionCode()) && (mServerApkInfo.getPackageName().equals(mCurrentApkInfo.getPackageName()))){ //Current Version is old ShowUpdateDialog(); } return true; } else { return false; } } class UpdateOnClickListener implements OnClickListener{ @Override public void onClick(View v) { mPopupWindowDialog.dismiss(); ShowDownloadProgressBar(); } } //show Update Dialog private void ShowUpdateDialog(){ String msg = "当前版本:" + mCurrentApkInfo.getVersionName() + "\n" + "发现新版本:" + mServerApkInfo.getVersionName() + "\n" + "是否更新?"; mPopupWindowDialog.setOKOnClickListener(new UpdateOnClickListener()); mPopupWindowDialog.setTitle("软件更新"); mPopupWindowDialog.setCancelVisible(true); mPopupWindowDialog.showMessage(msg); } private void ShowDownloadProgressBar() { mProgressDialog = new ProgressDialog(HelpActivity.this); mProgressDialog.setTitle("正在下载"); mProgressDialog.setMax(mFileSize); mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); mProgressDialog.show(); new Thread(new Runnable() { @Override public void run(){ DownloadUpdate(mUpdateServerDownloadURL); } }).start(); } //Get Server Version from Server:version.json private boolean GetServerVersion() { try{ String verjson = GetApkInfoFromServer(mUpdateServerCheckURL); Gson gson = new Gson(); ApkInfo apkInfo = gson.fromJson(verjson, ApkInfo.class); try { mServerApkInfo.setVersionCode(apkInfo.getVersionCode()); mServerApkInfo.setVersionName(apkInfo.getVersionName()); mServerApkInfo.setPackageName(apkInfo.getPackageName()); } catch (Exception e) { mServerApkInfo.setVersionCode(0); mServerApkInfo.setVersionName(""); mServerApkInfo.setPackageName(""); return false; } }catch(Exception e){ Log.e(TAG, e.getMessage()); return false; } return true; } private void DownloadUpdate(String url){ HttpClient client = new DefaultHttpClient(); HttpGet get = new HttpGet(url); HttpResponse response; try { response = client.execute(get); HttpEntity entity = response.getEntity(); mFileSize = (int)entity.getContentLength(); Log.isLoggable("DownTag", mFileSize); Message message_size = new Message(); message_size.what = DOWNLOAD_SIZE; mThreadHandler.sendMessage(message_size); InputStream inputStream = entity.getContent(); if(inputStream == null){ throw new RuntimeException("isStream is null"); } if (!ExistSDCard()) { Message message = new Message(); message.what = NO_SD_CARD; mThreadHandler.sendMessage(message); mProgressDialog.dismiss(); return; } File file = new File(Environment.getExternalStorageDirectory(),Constants.APP_NAME); FileOutputStream fileOutputStream = new FileOutputStream(file); byte[] buf = new byte[1024]; int readNum = -1; do{ readNum = inputStream.read(buf); if(readNum <= 0) break; fileOutputStream.write(buf, 0, readNum); mDownloadSize += readNum; Message message = new Message(); message.what = DOWNLOADING; mThreadHandler.sendMessage(message); try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } } while(true); inputStream.close(); fileOutputStream.close(); Message message = new Message(); message.what = DOWNLOAD_FINISH; mThreadHandler.sendMessage(message); HaveDownLoad(); }catch(ClientProtocolException e){ e.printStackTrace(); mProgressDialog.dismiss(); }catch(IOException e){ e.printStackTrace(); mProgressDialog.dismiss(); } } //cancel progressBar and start new App protected void HaveDownLoad() { mHandler.post(new Runnable(){ public void run(){ mProgressDialog.cancel(); Dialog installDialog = new AlertDialog.Builder(HelpActivity.this) .setTitle("下载完成") .setMessage("是否安装新的应用") .setPositiveButton("确定", new DialogInterface.OnClickListener(){ @Override public void onClick(DialogInterface dialog, int which) { InstallUpdateApk(); finish(); } }) .setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { finish(); } }) .create(); installDialog.show(); } }); } private void InstallUpdateApk() { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType(Uri.fromFile( new File(Environment.getExternalStorageDirectory(),Constants.APP_NAME)), "application/vnd.android.package-archive"); startActivity(intent); } /** * 获取网址内容 * @param url * @return * @throws Exception */ private String GetApkInfoFromServer(String url) throws Exception{ StringBuilder sb = new StringBuilder(); HttpClient client = new DefaultHttpClient(); HttpParams httpParams = client.getParams(); //设置网络超时参数 HttpConnectionParams.setConnectionTimeout(httpParams, 5000); HttpConnectionParams.setSoTimeout(httpParams, 8000); HttpResponse response = client.execute(new HttpGet(url)); HttpEntity entity = response.getEntity(); if (entity != null) { BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"), 8192); String line = null; while ((line = reader.readLine())!= null){ sb.append(line + "\n"); } reader.close(); } return sb.toString(); } private boolean ExistSDCard() { if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { return true; } else return false; } }
17,772
0.699356
0.696999
514
32.846302
27.593309
154
false
false
0
0
0
0
0
0
2.579767
false
false
13
71070487c4725c2344ab139a0b86fcd8c69b2c76
21,096,879,388,854
55d37e0e2ec9cdfbc8b317629775b327da88de44
/src/dodona/feedback/Format.java
21f7948705abc47193fee67d0187883ce64a6cf4
[ "MIT" ]
permissive
dodona-edu/judge-java12
https://github.com/dodona-edu/judge-java12
f811696a90831a4c08a9df556750982203ab1666
6bef355a9be2e73fb0a4207528c696b48fd2403f
refs/heads/master
2022-05-07T04:34:29.715000
2022-02-18T10:47:38
2022-03-25T14:01:24
208,259,780
1
4
MIT
false
2022-03-25T14:23:55
2019-09-13T12:25:07
2022-02-18T10:50:43
2022-03-25T14:16:39
1,560
1
2
5
Java
false
false
package dodona.feedback; public enum Format { PLAIN, /* Formatted as plain text */ HTML, /* HTML markup is not escaped */ MARKDOWN, /* Converted to HTML using Cramdown */ CODE, /* Preserves whitespace and rendered in monospace */ PYTHON, /* CODE, with python highlighting */ JAVASCRIPT; /* CODE, with javascript highlighting */ }
UTF-8
Java
378
java
Format.java
Java
[]
null
[]
package dodona.feedback; public enum Format { PLAIN, /* Formatted as plain text */ HTML, /* HTML markup is not escaped */ MARKDOWN, /* Converted to HTML using Cramdown */ CODE, /* Preserves whitespace and rendered in monospace */ PYTHON, /* CODE, with python highlighting */ JAVASCRIPT; /* CODE, with javascript highlighting */ }
378
0.637566
0.637566
10
36.799999
22.679506
68
false
false
0
0
0
0
0
0
0.9
false
false
13
909a8de30ef9701cad2a9f5040139a6e7a1c32d4
7,524,782,733,594
fb1f01ac8a219dfdce205ec4538cc6501f9825c8
/src/xadrez/pecas/Peao.java
1f6520e4db6686e658cc838dae14946502b81bc8
[]
no_license
RafaelBonotto/sistemaJogoDeXadrex-java
https://github.com/RafaelBonotto/sistemaJogoDeXadrex-java
38804e601af0635cb1b738d6ce4ae040d1ac9211
16a4b5fc212a515e8ff18eeef45946248819d3a1
refs/heads/master
2022-12-04T03:24:13.976000
2020-08-22T17:25:09
2020-08-22T17:25:09
283,907,033
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package xadrez.pecas; import jogo.Posicao; import jogo.Tabuleiro; import xadrez.Cor; import xadrez.Partida; import xadrez.XadrezPeca; public class Peao extends XadrezPeca { private Partida partida; public Peao(Tabuleiro tabuleiro, Cor cor, Partida partida) { super(tabuleiro, cor); this.partida = partida; } @Override public boolean[][] movimentosPossiveis() { boolean[][] mat = new boolean[getTabuleiro().getLinhas()][getTabuleiro().getColunas()]; Posicao p = new Posicao(0, 0); if(getCor() == Cor.BRANCO){ p.setValores(posicao.getLinha() - 1, posicao.getColuna()); if(getTabuleiro().posicaoExiste(p) && !getTabuleiro().pecaExiste(p)){ mat [p.getLinha()][p.getColuna()] = true; } p.setValores(posicao.getLinha() - 2, posicao.getColuna()); Posicao p2 = new Posicao(posicao.getLinha() - 1, posicao.getColuna()); if(getTabuleiro().posicaoExiste(p) && !getTabuleiro().pecaExiste(p) && getTabuleiro().posicaoExiste(p2) && !getTabuleiro().pecaExiste(p2) && getContagemDeMovimentos() == 0){ mat [p.getLinha()][p.getColuna()] = true; } p.setValores(posicao.getLinha() - 1, posicao.getColuna() - 1); if(getTabuleiro().posicaoExiste(p) && existePecaDoOponente(p)){ mat [p.getLinha()][p.getColuna()] = true; } p.setValores(posicao.getLinha() - 1, posicao.getColuna() + 1); if(getTabuleiro().posicaoExiste(p) && existePecaDoOponente(p)){ mat [p.getLinha()][p.getColuna()] = true; } // #Movimento Especial En Passant Branca if(posicao.getLinha() == 3){ Posicao esquerda = new Posicao(posicao.getLinha(), posicao.getColuna() - 1); if(getTabuleiro().posicaoExiste(esquerda) && existePecaDoOponente(esquerda) && getTabuleiro().peca(esquerda) == partida.getVuneravelEnPassant()){ mat[esquerda.getLinha() - 1][esquerda.getColuna()] = true; } Posicao direita = new Posicao(posicao.getLinha(), posicao.getColuna() + 1); if(getTabuleiro().posicaoExiste(direita) && existePecaDoOponente(direita) && getTabuleiro().peca(direita) == partida.getVuneravelEnPassant()){ mat[direita.getLinha() - 1][direita.getColuna()] = true; } } } else{ p.setValores(posicao.getLinha() + 1, posicao.getColuna()); if(getTabuleiro().posicaoExiste(p) && !getTabuleiro().pecaExiste(p)){ mat [p.getLinha()][p.getColuna()] = true; } p.setValores(posicao.getLinha() + 2, posicao.getColuna()); Posicao p2 = new Posicao(posicao.getLinha() + 1, posicao.getColuna()); if(getTabuleiro().posicaoExiste(p) && !getTabuleiro().pecaExiste(p) && getTabuleiro().posicaoExiste(p2) && !getTabuleiro().pecaExiste(p2) && getContagemDeMovimentos() == 0){ mat [p.getLinha()][p.getColuna()] = true; } p.setValores(posicao.getLinha() + 1, posicao.getColuna() - 1); if(getTabuleiro().posicaoExiste(p) && existePecaDoOponente(p)){ mat [p.getLinha()][p.getColuna()] = true; } p.setValores(posicao.getLinha() + 1, posicao.getColuna() + 1); if(getTabuleiro().posicaoExiste(p) && existePecaDoOponente(p)){ mat [p.getLinha()][p.getColuna()] = true; } // #Movimento Especial En Passant Preta if(posicao.getLinha() == 4){ Posicao esquerda = new Posicao(posicao.getLinha(), posicao.getColuna() - 1); if(getTabuleiro().posicaoExiste(esquerda) && existePecaDoOponente(esquerda) && getTabuleiro().peca(esquerda) == partida.getVuneravelEnPassant()){ mat[esquerda.getLinha() + 1][esquerda.getColuna()] = true; } Posicao direita = new Posicao(posicao.getLinha(), posicao.getColuna() + 1); if(getTabuleiro().posicaoExiste(direita) && existePecaDoOponente(direita) && getTabuleiro().peca(direita) == partida.getVuneravelEnPassant()){ mat[direita.getLinha() + 1][direita.getColuna()] = true; } } } return mat; } @Override public String toString(){ return "P"; } }
UTF-8
Java
4,485
java
Peao.java
Java
[]
null
[]
package xadrez.pecas; import jogo.Posicao; import jogo.Tabuleiro; import xadrez.Cor; import xadrez.Partida; import xadrez.XadrezPeca; public class Peao extends XadrezPeca { private Partida partida; public Peao(Tabuleiro tabuleiro, Cor cor, Partida partida) { super(tabuleiro, cor); this.partida = partida; } @Override public boolean[][] movimentosPossiveis() { boolean[][] mat = new boolean[getTabuleiro().getLinhas()][getTabuleiro().getColunas()]; Posicao p = new Posicao(0, 0); if(getCor() == Cor.BRANCO){ p.setValores(posicao.getLinha() - 1, posicao.getColuna()); if(getTabuleiro().posicaoExiste(p) && !getTabuleiro().pecaExiste(p)){ mat [p.getLinha()][p.getColuna()] = true; } p.setValores(posicao.getLinha() - 2, posicao.getColuna()); Posicao p2 = new Posicao(posicao.getLinha() - 1, posicao.getColuna()); if(getTabuleiro().posicaoExiste(p) && !getTabuleiro().pecaExiste(p) && getTabuleiro().posicaoExiste(p2) && !getTabuleiro().pecaExiste(p2) && getContagemDeMovimentos() == 0){ mat [p.getLinha()][p.getColuna()] = true; } p.setValores(posicao.getLinha() - 1, posicao.getColuna() - 1); if(getTabuleiro().posicaoExiste(p) && existePecaDoOponente(p)){ mat [p.getLinha()][p.getColuna()] = true; } p.setValores(posicao.getLinha() - 1, posicao.getColuna() + 1); if(getTabuleiro().posicaoExiste(p) && existePecaDoOponente(p)){ mat [p.getLinha()][p.getColuna()] = true; } // #Movimento Especial En Passant Branca if(posicao.getLinha() == 3){ Posicao esquerda = new Posicao(posicao.getLinha(), posicao.getColuna() - 1); if(getTabuleiro().posicaoExiste(esquerda) && existePecaDoOponente(esquerda) && getTabuleiro().peca(esquerda) == partida.getVuneravelEnPassant()){ mat[esquerda.getLinha() - 1][esquerda.getColuna()] = true; } Posicao direita = new Posicao(posicao.getLinha(), posicao.getColuna() + 1); if(getTabuleiro().posicaoExiste(direita) && existePecaDoOponente(direita) && getTabuleiro().peca(direita) == partida.getVuneravelEnPassant()){ mat[direita.getLinha() - 1][direita.getColuna()] = true; } } } else{ p.setValores(posicao.getLinha() + 1, posicao.getColuna()); if(getTabuleiro().posicaoExiste(p) && !getTabuleiro().pecaExiste(p)){ mat [p.getLinha()][p.getColuna()] = true; } p.setValores(posicao.getLinha() + 2, posicao.getColuna()); Posicao p2 = new Posicao(posicao.getLinha() + 1, posicao.getColuna()); if(getTabuleiro().posicaoExiste(p) && !getTabuleiro().pecaExiste(p) && getTabuleiro().posicaoExiste(p2) && !getTabuleiro().pecaExiste(p2) && getContagemDeMovimentos() == 0){ mat [p.getLinha()][p.getColuna()] = true; } p.setValores(posicao.getLinha() + 1, posicao.getColuna() - 1); if(getTabuleiro().posicaoExiste(p) && existePecaDoOponente(p)){ mat [p.getLinha()][p.getColuna()] = true; } p.setValores(posicao.getLinha() + 1, posicao.getColuna() + 1); if(getTabuleiro().posicaoExiste(p) && existePecaDoOponente(p)){ mat [p.getLinha()][p.getColuna()] = true; } // #Movimento Especial En Passant Preta if(posicao.getLinha() == 4){ Posicao esquerda = new Posicao(posicao.getLinha(), posicao.getColuna() - 1); if(getTabuleiro().posicaoExiste(esquerda) && existePecaDoOponente(esquerda) && getTabuleiro().peca(esquerda) == partida.getVuneravelEnPassant()){ mat[esquerda.getLinha() + 1][esquerda.getColuna()] = true; } Posicao direita = new Posicao(posicao.getLinha(), posicao.getColuna() + 1); if(getTabuleiro().posicaoExiste(direita) && existePecaDoOponente(direita) && getTabuleiro().peca(direita) == partida.getVuneravelEnPassant()){ mat[direita.getLinha() + 1][direita.getColuna()] = true; } } } return mat; } @Override public String toString(){ return "P"; } }
4,485
0.575474
0.567893
91
48.285713
43.252464
185
false
false
0
0
0
0
0
0
0.626374
false
false
13
aa1fec6203582c73b9a3d96467c88337c3b2d1b6
26,096,221,325,997
9a24e37fcbe47cd98ac43577340430615b68def9
/core/src/main/java/com/sdu/spark/rpc/netty/NettyLocalResponseCallback.java
f5bf7715bce565d9f44ec63a2420e973e1cd4c38
[]
no_license
nysyxxg/JSpark
https://github.com/nysyxxg/JSpark
79e8fa53787db989640b9fc42529a148888fc58f
c44bd6e96d15cabe34cd8bba0dcef1ab58bda2f8
refs/heads/master
2021-01-20T23:36:34.749000
2017-08-05T08:42:50
2017-08-05T08:42:50
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.sdu.spark.rpc.netty; import com.sdu.spark.rpc.LocalResponseCallback; import java.util.concurrent.*; /** * @author hanhan.zhang * */ public class NettyLocalResponseCallback<T> implements LocalResponseCallback<T> { private CountDownLatch finished = new CountDownLatch(1); private T value; private Throwable error; @Override public void onSuccess(T value) { this.value = value; finished.countDown(); } @Override public void onFailure(Throwable cause) { this.error = cause; finished.countDown(); } public T getResponse() throws ExecutionException, InterruptedException { finished.await(); if (error != null) { throw new ExecutionException("task execute exception", error); } return value; } }
UTF-8
Java
832
java
NettyLocalResponseCallback.java
Java
[ { "context": "k;\n\nimport java.util.concurrent.*;\n\n/**\n * @author hanhan.zhang\n * */\npublic class NettyLocalResponseCal", "end": 133, "score": 0.8264756202697754, "start": 130, "tag": "NAME", "value": "han" }, { "context": "import java.util.concurrent.*;\n\n/**\n * @author hanhan.zhang\n * */\npublic class NettyLocalResponseCallback<T> ", "end": 142, "score": 0.6567452549934387, "start": 133, "tag": "USERNAME", "value": "han.zhang" } ]
null
[]
package com.sdu.spark.rpc.netty; import com.sdu.spark.rpc.LocalResponseCallback; import java.util.concurrent.*; /** * @author hanhan.zhang * */ public class NettyLocalResponseCallback<T> implements LocalResponseCallback<T> { private CountDownLatch finished = new CountDownLatch(1); private T value; private Throwable error; @Override public void onSuccess(T value) { this.value = value; finished.countDown(); } @Override public void onFailure(Throwable cause) { this.error = cause; finished.countDown(); } public T getResponse() throws ExecutionException, InterruptedException { finished.await(); if (error != null) { throw new ExecutionException("task execute exception", error); } return value; } }
832
0.652644
0.651442
37
21.486486
22.521606
80
false
false
0
0
0
0
0
0
0.405405
false
false
13
cac958d71176e593b30bffca3bf2843c38e2a75f
12,463,995,152,956
71975999c9d702a0883ec9038ce3e76325928549
/src2.4.0/src/main/java/com/qiyukf/nimlib/d/e/a/a.java
a4b6d0400f7b65404de9f0bfa2a194b1b338aa8f
[]
no_license
XposedRunner/PhysicalFitnessRunner
https://github.com/XposedRunner/PhysicalFitnessRunner
dc64179551ccd219979a6f8b9fe0614c29cd61de
cb037e59416d6c290debbed5ed84c956e705e738
refs/heads/master
2020-07-15T18:18:23.001000
2019-09-02T04:21:34
2019-09-02T04:21:34
205,620,387
3
2
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.qiyukf.nimlib.d.e.a; import android.annotation.TargetApi; import android.app.Activity; import android.app.Application; import android.app.Application.ActivityLifecycleCallbacks; import android.content.Context; import android.os.Build.VERSION; import android.os.Bundle; import android.os.Handler; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; @TargetApi(14) final class a implements ActivityLifecycleCallbacks { private static a a; private boolean b = true; private boolean c = false; private Handler d = new Handler(); private Runnable e; private List<com.qiyukf.nimlib.d.e.a.b.a> f = new CopyOnWriteArrayList(); a() { } @TargetApi(14) static void a(Context context) { String stringBuilder; if (VERSION.SDK_INT < 14 || context == null || !(context instanceof Application) || a != null) { StringBuilder stringBuilder2 = new StringBuilder("app can not register activity lifecycle callbacks, sdk version="); stringBuilder2.append(VERSION.SDK_INT); stringBuilder = stringBuilder2.toString(); } else { a = new a(); ((Application) context).registerActivityLifecycleCallbacks(a); stringBuilder = "app register activity lifecycle callbacks success"; } com.qiyukf.nimlib.d.a.b.a.a(stringBuilder); } static void a(com.qiyukf.nimlib.d.e.a.b.a aVar) { if (!a() && aVar != null && !a.f.contains(aVar)) { a.f.add(aVar); com.qiyukf.nimlib.d.a.b.a.a("add AppForegroundObserver"); } } private static boolean a() { return a == null; } static void b(Context context) { if (context != null && (context instanceof Application) && a != null) { ((Application) context).unregisterActivityLifecycleCallbacks(a); a.f.clear(); a = null; } } static void b(com.qiyukf.nimlib.d.e.a.b.a aVar) { if (!a() && aVar != null) { a.f.remove(aVar); com.qiyukf.nimlib.d.a.b.a.a("remove AppForegroundObserver"); } } public final void onActivityCreated(Activity activity, Bundle bundle) { } public final void onActivityDestroyed(Activity activity) { } public final void onActivityPaused(Activity activity) { this.c = true; if (this.e != null) { this.d.removeCallbacks(this.e); } else { this.e = new Runnable() { public final void run() { if (a.this.b && a.this.c) { a.this.b = false; com.qiyukf.nimlib.d.a.b.a.a("app in background"); for (com.qiyukf.nimlib.d.e.a.b.a b : a.this.f) { try { b.b(); } catch (Exception e) { StringBuilder stringBuilder = new StringBuilder("AppForegroundObserver threw exception! e="); stringBuilder.append(e.getMessage()); com.qiyukf.nimlib.d.a.b.a.a(stringBuilder.toString()); } } } } }; } this.d.postDelayed(this.e, 500); } public final void onActivityResumed(Activity activity) { this.c = false; int i = this.b ^ 1; this.b = true; if (this.e != null) { this.d.removeCallbacks(this.e); } if (i != 0) { com.qiyukf.nimlib.d.a.b.a.a("app on foreground"); for (com.qiyukf.nimlib.d.e.a.b.a a : this.f) { try { a.a(); } catch (Exception e) { StringBuilder stringBuilder = new StringBuilder("AppForegroundObserver threw exception! e="); stringBuilder.append(e.getMessage()); com.qiyukf.nimlib.d.a.b.a.a(stringBuilder.toString()); } } } } public final void onActivitySaveInstanceState(Activity activity, Bundle bundle) { } public final void onActivityStarted(Activity activity) { } public final void onActivityStopped(Activity activity) { } }
UTF-8
Java
4,478
java
a.java
Java
[]
null
[]
package com.qiyukf.nimlib.d.e.a; import android.annotation.TargetApi; import android.app.Activity; import android.app.Application; import android.app.Application.ActivityLifecycleCallbacks; import android.content.Context; import android.os.Build.VERSION; import android.os.Bundle; import android.os.Handler; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; @TargetApi(14) final class a implements ActivityLifecycleCallbacks { private static a a; private boolean b = true; private boolean c = false; private Handler d = new Handler(); private Runnable e; private List<com.qiyukf.nimlib.d.e.a.b.a> f = new CopyOnWriteArrayList(); a() { } @TargetApi(14) static void a(Context context) { String stringBuilder; if (VERSION.SDK_INT < 14 || context == null || !(context instanceof Application) || a != null) { StringBuilder stringBuilder2 = new StringBuilder("app can not register activity lifecycle callbacks, sdk version="); stringBuilder2.append(VERSION.SDK_INT); stringBuilder = stringBuilder2.toString(); } else { a = new a(); ((Application) context).registerActivityLifecycleCallbacks(a); stringBuilder = "app register activity lifecycle callbacks success"; } com.qiyukf.nimlib.d.a.b.a.a(stringBuilder); } static void a(com.qiyukf.nimlib.d.e.a.b.a aVar) { if (!a() && aVar != null && !a.f.contains(aVar)) { a.f.add(aVar); com.qiyukf.nimlib.d.a.b.a.a("add AppForegroundObserver"); } } private static boolean a() { return a == null; } static void b(Context context) { if (context != null && (context instanceof Application) && a != null) { ((Application) context).unregisterActivityLifecycleCallbacks(a); a.f.clear(); a = null; } } static void b(com.qiyukf.nimlib.d.e.a.b.a aVar) { if (!a() && aVar != null) { a.f.remove(aVar); com.qiyukf.nimlib.d.a.b.a.a("remove AppForegroundObserver"); } } public final void onActivityCreated(Activity activity, Bundle bundle) { } public final void onActivityDestroyed(Activity activity) { } public final void onActivityPaused(Activity activity) { this.c = true; if (this.e != null) { this.d.removeCallbacks(this.e); } else { this.e = new Runnable() { public final void run() { if (a.this.b && a.this.c) { a.this.b = false; com.qiyukf.nimlib.d.a.b.a.a("app in background"); for (com.qiyukf.nimlib.d.e.a.b.a b : a.this.f) { try { b.b(); } catch (Exception e) { StringBuilder stringBuilder = new StringBuilder("AppForegroundObserver threw exception! e="); stringBuilder.append(e.getMessage()); com.qiyukf.nimlib.d.a.b.a.a(stringBuilder.toString()); } } } } }; } this.d.postDelayed(this.e, 500); } public final void onActivityResumed(Activity activity) { this.c = false; int i = this.b ^ 1; this.b = true; if (this.e != null) { this.d.removeCallbacks(this.e); } if (i != 0) { com.qiyukf.nimlib.d.a.b.a.a("app on foreground"); for (com.qiyukf.nimlib.d.e.a.b.a a : this.f) { try { a.a(); } catch (Exception e) { StringBuilder stringBuilder = new StringBuilder("AppForegroundObserver threw exception! e="); stringBuilder.append(e.getMessage()); com.qiyukf.nimlib.d.a.b.a.a(stringBuilder.toString()); } } } } public final void onActivitySaveInstanceState(Activity activity, Bundle bundle) { } public final void onActivityStarted(Activity activity) { } public final void onActivityStopped(Activity activity) { } }
4,478
0.533274
0.530147
128
32.984375
28.220667
128
false
false
0
0
0
0
0
0
0.484375
false
false
13
12c179a4c4d20e26cc06e33e6a876626f635d6a3
33,741,263,139,226
a9ac3b659eb3c9dc9606989a26150bafa2f20ad2
/shell/src/main/java/com/javaasc/shell/api/ShellConnectionHandler.java
55cef82fa17c43a86ba0c66ae5d07d491022a434
[ "Apache-2.0" ]
permissive
alonana/JavaAsc
https://github.com/alonana/JavaAsc
1cb2f2b2d4b0af51fa2fde5a3ab9254426f9a7d3
d601ca24ba0dbe884318f0c9b3a4085c61e9b0a7
refs/heads/master
2021-01-10T14:30:03.015000
2016-04-08T14:56:32
2016-04-08T14:56:32
54,869,418
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.javaasc.shell.api; public interface ShellConnectionHandler { void handleConnection(ShellConnection connection) throws Exception; }
UTF-8
Java
148
java
ShellConnectionHandler.java
Java
[]
null
[]
package com.javaasc.shell.api; public interface ShellConnectionHandler { void handleConnection(ShellConnection connection) throws Exception; }
148
0.824324
0.824324
5
28.6
26.582701
71
false
false
0
0
0
0
0
0
0.4
false
false
13
e4e45296e85ba07e1c0708f8dc65c7218b9abd71
24,077,586,720,424
0eed4e9bf238a7b960efd82c0d3fb9713920e630
/Naresh-IT/src/com/nareshit/service/SearchService.java
22820ef548db64f0516ca4706879fcba8d20b9fb
[]
no_license
arbajshaikh/naresh-it
https://github.com/arbajshaikh/naresh-it
b032b4cb33b16d847fa670c32ae656f2d646c581
4dfe9cafdae9ebac099c2870452825abadc35997
refs/heads/master
2020-04-26T12:43:22.552000
2019-03-10T10:00:07
2019-03-10T10:00:07
173,558,696
2
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.nareshit.service; import java.util.List; import com.nareshit.dto.StudentsDTO; public interface SearchService { public List<StudentsDTO> searchRecord(String course)throws Exception; }
UTF-8
Java
213
java
SearchService.java
Java
[]
null
[]
package com.nareshit.service; import java.util.List; import com.nareshit.dto.StudentsDTO; public interface SearchService { public List<StudentsDTO> searchRecord(String course)throws Exception; }
213
0.760563
0.760563
11
17.363636
21.806057
70
false
false
0
0
0
0
0
0
0.545455
false
false
13
7f9561767af29a202c611fe0b43274766fd05e5f
2,662,879,771,633
c7be7e5bb3dc8802e2dd1d45f164d8981bb0f4ca
/basiclibrary/lib/src/test/java/basiclibrary/LibraryTest.java
076c780c63d4760ab4085e6f0e828965937f5387
[]
no_license
yazanabdulhafez/java-fundamentals
https://github.com/yazanabdulhafez/java-fundamentals
be2aff94f95f6071e4021517826a28c459d44039
af5708ff0e016373579bb2c11bfbe221eb5aaab0
refs/heads/main
2023-08-29T19:09:37.018000
2021-10-19T22:11:23
2021-10-19T22:11:23
415,552,825
0
0
null
false
2021-10-19T22:11:13
2021-10-10T10:27:52
2021-10-17T16:46:04
2021-10-19T22:11:13
167
0
0
1
Java
false
false
/* * This Java source file was generated by the Gradle 'init' task. */ package basiclibrary; import org.junit.Test; import java.util.ArrayList; import static basiclibrary.Library.*; import static org.junit.Assert.*; public class LibraryTest { @Test public void testRollMethod() { int[] actualResult=Library.roll(4); assertEquals(4,actualResult.length); } @Test public void testContainDuplicateMethod() { int[] testArr={1,2,2,5}; boolean actualResult=containsDuplicates(testArr); assertTrue(actualResult); } @Test public void testAverageMethod() { int[] testArr={1,2,3,4,5}; double expectedResult=3; double actualResult=calculateAverage(testArr); assertEquals(expectedResult,actualResult,0); } @Test public void testGetLowestAverageArrayMethod() { int[][] testArr={ {66, 64, 58, 65, 71, 57, 60}, {57, 65, 65, 70, 72, 65, 51}, {55, 54, 60, 53, 59, 57, 61}, {65, 56, 55, 52, 55, 62, 57} }; int[] actualResult=getBackLowAvgArray(testArr); int[] expectedResult={55, 54, 60, 53, 59, 57, 61}; assertArrayEquals(expectedResult,actualResult); } @Test public void testAnalyzingWeatherDataMethod() { int[][] inArr = { {66, 64, 58, 65, 71, 57, 60}, {57, 65, 65, 70, 72, 65, 51}, {55, 54, 60, 53, 59, 57, 61}, {65, 56, 55, 52, 55, 62, 57} }; ArrayList<String> testList = new ArrayList<>(); testList.add("minimum value: 51"); testList.add("maximum value: 72"); testList.add("Never saw temperature: 63"); testList.add("Never saw temperature: 67"); testList.add("Never saw temperature: 68"); testList.add("Never saw temperature: 69"); assertEquals( testList ,Library.analyzingWeatherData(inArr)); } @Test public void testTallyMethod() { ArrayList<String> testList = new ArrayList<>(); testList.add("Bush"); testList.add("Bush"); testList.add("Bush"); testList.add("Shrub"); testList.add("Hedge"); testList.add("Shrub"); testList.add("Bush"); testList.add("Hedge"); testList.add("Bush"); String expectedResult="Bush"; String actualResult=Library.tally(testList); assertEquals(expectedResult,actualResult); } }
UTF-8
Java
2,478
java
LibraryTest.java
Java
[]
null
[]
/* * This Java source file was generated by the Gradle 'init' task. */ package basiclibrary; import org.junit.Test; import java.util.ArrayList; import static basiclibrary.Library.*; import static org.junit.Assert.*; public class LibraryTest { @Test public void testRollMethod() { int[] actualResult=Library.roll(4); assertEquals(4,actualResult.length); } @Test public void testContainDuplicateMethod() { int[] testArr={1,2,2,5}; boolean actualResult=containsDuplicates(testArr); assertTrue(actualResult); } @Test public void testAverageMethod() { int[] testArr={1,2,3,4,5}; double expectedResult=3; double actualResult=calculateAverage(testArr); assertEquals(expectedResult,actualResult,0); } @Test public void testGetLowestAverageArrayMethod() { int[][] testArr={ {66, 64, 58, 65, 71, 57, 60}, {57, 65, 65, 70, 72, 65, 51}, {55, 54, 60, 53, 59, 57, 61}, {65, 56, 55, 52, 55, 62, 57} }; int[] actualResult=getBackLowAvgArray(testArr); int[] expectedResult={55, 54, 60, 53, 59, 57, 61}; assertArrayEquals(expectedResult,actualResult); } @Test public void testAnalyzingWeatherDataMethod() { int[][] inArr = { {66, 64, 58, 65, 71, 57, 60}, {57, 65, 65, 70, 72, 65, 51}, {55, 54, 60, 53, 59, 57, 61}, {65, 56, 55, 52, 55, 62, 57} }; ArrayList<String> testList = new ArrayList<>(); testList.add("minimum value: 51"); testList.add("maximum value: 72"); testList.add("Never saw temperature: 63"); testList.add("Never saw temperature: 67"); testList.add("Never saw temperature: 68"); testList.add("Never saw temperature: 69"); assertEquals( testList ,Library.analyzingWeatherData(inArr)); } @Test public void testTallyMethod() { ArrayList<String> testList = new ArrayList<>(); testList.add("Bush"); testList.add("Bush"); testList.add("Bush"); testList.add("Shrub"); testList.add("Hedge"); testList.add("Shrub"); testList.add("Bush"); testList.add("Hedge"); testList.add("Bush"); String expectedResult="Bush"; String actualResult=Library.tally(testList); assertEquals(expectedResult,actualResult); } }
2,478
0.581921
0.520985
78
30.76923
20.286362
69
false
false
0
0
0
0
0
0
1.448718
false
false
13
875e03ae939593a989b6b1b75fd6c3a8ee871a5e
24,068,996,790,739
32772a802575197503a3d9e279c388fe15b7ec14
/src/main/java/org/example/untitled/db/DocumentDao.java
1ba035dee57cb45e4912ff962ff99f518a50b55b
[]
no_license
gun-pi/java-dagger-lambda-activemq-jdbc
https://github.com/gun-pi/java-dagger-lambda-activemq-jdbc
a3c147bfd0f02083c6881c50830dec4cde036783
ad480ef4f22dc2a8052f000fcee2f2594ae975f9
refs/heads/master
2023-05-06T03:06:20.886000
2021-05-27T12:47:49
2021-05-27T12:47:49
362,086,345
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.example.untitled.db; import java.sql.*; public class DocumentDao { private static final String DATABASE_URL = "jdbc:postgresql://database-1.cx96u0a6s3vd.eu-central-1.rds.amazonaws.com:5432/postgres"; private static final String DATABASE_USERNAME = "postgres"; private static final String DATABASE_PASSWORD = "exampleexample"; private static final String QUERY = "INSERT INTO documents (content, published_on) VALUES (?, ?) RETURNING id"; public Long save(DocumentEntity documentEntity) { try (Connection connection = DriverManager.getConnection(DATABASE_URL, DATABASE_USERNAME, DATABASE_PASSWORD); PreparedStatement statement = connection.prepareStatement(QUERY, Statement.RETURN_GENERATED_KEYS)) { connection.setAutoCommit(false); statement.setString(1, documentEntity.getContent()); statement.setTimestamp(2, Timestamp.valueOf(documentEntity.getPublishedOn())); statement.executeUpdate(); ResultSet rs = statement.getGeneratedKeys(); Long id = null; if (rs.next()) { id = rs.getLong(1); } connection.commit(); return id; } catch (Exception e) { throw new RuntimeException(e); } } }
UTF-8
Java
1,323
java
DocumentDao.java
Java
[ { "context": " private static final String DATABASE_USERNAME = \"postgres\";\n private static final String DATABASE_PASSWO", "end": 293, "score": 0.9955507516860962, "start": 285, "tag": "USERNAME", "value": "postgres" }, { "context": " private static final String DATABASE_PASSWORD = \"exampleexample\";\n private static final String QUERY = \"INSERT", "end": 363, "score": 0.9969340562820435, "start": 349, "tag": "PASSWORD", "value": "exampleexample" } ]
null
[]
package org.example.untitled.db; import java.sql.*; public class DocumentDao { private static final String DATABASE_URL = "jdbc:postgresql://database-1.cx96u0a6s3vd.eu-central-1.rds.amazonaws.com:5432/postgres"; private static final String DATABASE_USERNAME = "postgres"; private static final String DATABASE_PASSWORD = "<PASSWORD>"; private static final String QUERY = "INSERT INTO documents (content, published_on) VALUES (?, ?) RETURNING id"; public Long save(DocumentEntity documentEntity) { try (Connection connection = DriverManager.getConnection(DATABASE_URL, DATABASE_USERNAME, DATABASE_PASSWORD); PreparedStatement statement = connection.prepareStatement(QUERY, Statement.RETURN_GENERATED_KEYS)) { connection.setAutoCommit(false); statement.setString(1, documentEntity.getContent()); statement.setTimestamp(2, Timestamp.valueOf(documentEntity.getPublishedOn())); statement.executeUpdate(); ResultSet rs = statement.getGeneratedKeys(); Long id = null; if (rs.next()) { id = rs.getLong(1); } connection.commit(); return id; } catch (Exception e) { throw new RuntimeException(e); } } }
1,319
0.65155
0.640967
33
39.090908
35.288734
117
false
false
0
0
0
0
0
0
0.727273
false
false
13
acd35bdf91e6687719adbae9c4b44d788c22b5f3
26,731,876,512,550
d5e2a078cb2642372ac7c2f83007f219579e1e80
/app/src/main/java/com/example/listviewproject/MainActivity.java
81465a3eacded78495fdce7d2d2aa06020acae3d
[]
no_license
Ghassan-Aljaafri/List-View-Project
https://github.com/Ghassan-Aljaafri/List-View-Project
833f9cfddb310e538b8832ee2e81166e41ce4e75
6dd9361b45dfd8217caee731eae7a986459c7442
refs/heads/master
2020-11-29T16:24:48.361000
2019-12-26T00:09:24
2019-12-26T00:09:24
230,167,208
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.listviewproject; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import android.content.DialogInterface; import android.content.Intent; import android.media.midi.MidiDeviceService; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.ListView; import android.widget.Toast; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { ListView listView; EditText editText; ArrayList<String> arrayList; ArrayAdapter<String> arrayAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); this.listView = findViewById(R.id.listView); this.editText = findViewById(R.id.addItemEditeText); this.arrayList = new ArrayList(); this.arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 , arrayList); listView.setAdapter(arrayAdapter); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent intent = new Intent(getApplicationContext(), ShowActivity.class); intent.putExtra("index", position); intent.putExtra("value", String.valueOf(arrayList.get(position))); startActivity(intent); } }); listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) { new AlertDialog.Builder(MainActivity.this) .setTitle("Warning!") .setPositiveButton("Confirm", new DialogInterface.OnClickListener() { final int item = position; @Override public void onClick(DialogInterface dialog, int which) { arrayList.remove(item); arrayAdapter.notifyDataSetChanged(); Toast.makeText(MainActivity.this, "Item removed", Toast.LENGTH_SHORT).show(); } }) .setMessage("Are you sure to delete this item?") .setNeutralButton("cancel", null) .setIcon(android.R.drawable.ic_dialog_alert) .show(); return false; } }); } public void addItem(View view) { String item = editText.getText().toString(); if (!item.isEmpty()) { arrayList.add(editText.getText().toString()); arrayAdapter.notifyDataSetChanged(); } else { Toast.makeText(this, "Please add an Item", Toast.LENGTH_SHORT).show(); } } }
UTF-8
Java
3,156
java
MainActivity.java
Java
[]
null
[]
package com.example.listviewproject; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import android.content.DialogInterface; import android.content.Intent; import android.media.midi.MidiDeviceService; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.ListView; import android.widget.Toast; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { ListView listView; EditText editText; ArrayList<String> arrayList; ArrayAdapter<String> arrayAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); this.listView = findViewById(R.id.listView); this.editText = findViewById(R.id.addItemEditeText); this.arrayList = new ArrayList(); this.arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 , arrayList); listView.setAdapter(arrayAdapter); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent intent = new Intent(getApplicationContext(), ShowActivity.class); intent.putExtra("index", position); intent.putExtra("value", String.valueOf(arrayList.get(position))); startActivity(intent); } }); listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) { new AlertDialog.Builder(MainActivity.this) .setTitle("Warning!") .setPositiveButton("Confirm", new DialogInterface.OnClickListener() { final int item = position; @Override public void onClick(DialogInterface dialog, int which) { arrayList.remove(item); arrayAdapter.notifyDataSetChanged(); Toast.makeText(MainActivity.this, "Item removed", Toast.LENGTH_SHORT).show(); } }) .setMessage("Are you sure to delete this item?") .setNeutralButton("cancel", null) .setIcon(android.R.drawable.ic_dialog_alert) .show(); return false; } }); } public void addItem(View view) { String item = editText.getText().toString(); if (!item.isEmpty()) { arrayList.add(editText.getText().toString()); arrayAdapter.notifyDataSetChanged(); } else { Toast.makeText(this, "Please add an Item", Toast.LENGTH_SHORT).show(); } } }
3,156
0.609632
0.609316
80
38.450001
28.788843
109
false
false
0
0
0
0
0
0
0.7375
false
false
13
fe54cfa4c2a54eb8268e3b7d5fdc148c6e564ba1
12,893,491,851,492
745d5aea1c3c1968bff56830da9849cb625ab35c
/simpleimage.core/src/test/java/com/alibaba/simpleimage/ScaleTest.java
592c9635e1d8e3c30e52ff03fa8df02adf7f5659
[ "Apache-2.0" ]
permissive
SnrtIevg/simpleimage
https://github.com/SnrtIevg/simpleimage
4032da7460ae2072b118a1cfa27f83a328665358
0edd2b29e26008adb4159c6f90cf243488d50327
refs/heads/master
2020-12-20T01:28:41.087000
2020-01-24T02:29:56
2020-01-24T02:29:56
235,915,355
0
0
Apache-2.0
true
2020-01-24T00:47:02
2020-01-24T00:47:02
2020-01-21T16:02:29
2018-03-08T12:49:15
56,754
0
0
0
null
false
false
/** * Project: headquarters-biz-image File Created at 2010-6-11 $Id$ Copyright 2008 Alibaba.com Croporation Limited. All * rights reserved. This software is the confidential and proprietary information of Alibaba Company. * ("Confidential Information"). You shall not disclose such Confidential Information and shall use it only in * accordance with the terms of the license agreement you entered into with Alibaba.com. */ package com.alibaba.simpleimage; import java.awt.RenderingHints; import java.awt.image.BufferedImage; import java.awt.image.renderable.ParameterBlock; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import javax.media.jai.Interpolation; import javax.media.jai.JAI; import javax.media.jai.PlanarImage; import javax.media.jai.RenderedOp; import org.apache.commons.io.IOUtils; import com.alibaba.simpleimage.jai.scale.LanczosScaleOp; import com.alibaba.simpleimage.render.ReadRender; import com.alibaba.simpleimage.render.WriteRender; /** * TODO Comment of ScaleTest * * @author wendell */ public class ScaleTest extends BaseTest { static final File path = new File("./src/test/resources/conf.test/simpleimage/scale"); static float scale = 0.2f; static double dScale = 0.2; public void testNearest() throws Exception { doScale("Nearest"); } public void testBilinear() throws Exception { doScale("Bilinear"); } public void testBicubic() throws Exception { doScale("Bicubic"); } public void testBicubic2() throws Exception { doScale("Bicubic2"); } public void testSubsampleAverage() throws Exception { doScale("SubsampleAverage"); } public void testLanczos() throws Exception { doScale("Lanczos"); } public void doScale(String name) throws Exception { for (File imgFile : path.listFiles()) { if (imgFile.getName().lastIndexOf("jpg") < 0) { continue; } if (imgFile.getName().indexOf("result") > 0) { continue; } String filename = imgFile.getName().substring(0, imgFile.getName().lastIndexOf(".")); InputStream in = new FileInputStream(imgFile); OutputStream out = new FileOutputStream(new File(resultDir, "SCALE_" + filename + "-" + name + ".jpg")); WriteRender wr = null; try { ReadRender rr = new ReadRender(in, true); ImageWrapper wi = rr.render(); PlanarImage img = wi.getAsPlanarImage(); if ("progbicu".equalsIgnoreCase(name)) { img = doProgressiveBicubic(img); } else if ("Nearest".equalsIgnoreCase(name)) { img = doScaleNearest(img); } else if ("Bilinear".equalsIgnoreCase(name)) { img = doScaleBilinear(img); } else if ("Bicubic".equalsIgnoreCase(name)) { img = doScaleBicubic(img); } else if ("Bicubic2".equalsIgnoreCase(name)) { img = doScaleBicubic2(img); } else if ("SubsampleAverage".equalsIgnoreCase(name)) { img = doSubsampleAverage(img); } else if ("lanczos".equalsIgnoreCase(name)){ img = doLanczos(img); } else { throw new IllegalArgumentException("Unknown alg " + name); } wi.setImage(img); wr = new WriteRender(wi, out); wr.render(); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } } } public PlanarImage doProgressiveBicubic(PlanarImage op) throws Exception { int dstWidth = 220; int w = op.getWidth(); while (w > dstWidth) { scale = 0.6f; ParameterBlock pb = new ParameterBlock(); pb.addSource(op); pb.add(scale); pb.add(scale); pb.add(0.0F); pb.add(0.0F); pb.add(Interpolation.getInstance(Interpolation.INTERP_BICUBIC)); RenderingHints qualityHints = new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); op = JAI.create("scale", pb, qualityHints); w = (int) (scale * w); } return op; } public PlanarImage doScaleNearest(PlanarImage op) throws Exception { ParameterBlock pb = new ParameterBlock(); pb.addSource(op); pb.add(scale); pb.add(scale); pb.add(0.0F); pb.add(0.0F); pb.add(Interpolation.getInstance(Interpolation.INTERP_NEAREST)); RenderingHints qualityHints = new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); op = JAI.create("scale", pb, qualityHints); return op; } public PlanarImage doScaleBilinear(PlanarImage op) throws Exception { ParameterBlock pb = new ParameterBlock(); pb.addSource(op); pb.add(scale); pb.add(scale); pb.add(0.0F); pb.add(0.0F); pb.add(Interpolation.getInstance(Interpolation.INTERP_BILINEAR)); RenderingHints qualityHints = new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); op = JAI.create("scale", pb, qualityHints); return op; } public PlanarImage doScaleBicubic(PlanarImage op) throws Exception { ParameterBlock pb = new ParameterBlock(); pb.addSource(op); pb.add(scale); pb.add(scale); pb.add(0.0F); pb.add(0.0F); pb.add(Interpolation.getInstance(Interpolation.INTERP_BICUBIC)); RenderingHints qualityHints = new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); op = JAI.create("scale", pb, qualityHints); return op; } public PlanarImage doScaleBicubic2(PlanarImage op) throws Exception { ParameterBlock pb = new ParameterBlock(); pb.addSource(op); pb.add(scale); pb.add(scale); pb.add(0.0F); pb.add(0.0F); pb.add(Interpolation.getInstance(Interpolation.INTERP_BICUBIC_2)); RenderingHints qualityHints = new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); op = JAI.create("scale", pb, qualityHints); return op; } public PlanarImage doSubsampleAverage(PlanarImage op) throws Exception { double zoom = dScale; ParameterBlock pb = new ParameterBlock(); pb.addSource(op); pb.add(zoom); pb.add(zoom); RenderingHints qualityHints = new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); RenderedOp zoomOp = JAI.create("SubsampleAverage", pb, qualityHints); return zoomOp; } public PlanarImage doLanczos(PlanarImage op) throws Exception { LanczosScaleOp scaleOp = new LanczosScaleOp(dScale, dScale); BufferedImage dst = scaleOp.compute(op.getAsBufferedImage()); return PlanarImage.wrapRenderedImage(dst); } }
UTF-8
Java
7,689
java
ScaleTest.java
Java
[ { "context": ";\n\n/**\n * TODO Comment of ScaleTest\n * \n * @author wendell\n */\npublic class ScaleTest extends BaseTest {\n\n ", "end": 1115, "score": 0.9991121292114258, "start": 1108, "tag": "USERNAME", "value": "wendell" } ]
null
[]
/** * Project: headquarters-biz-image File Created at 2010-6-11 $Id$ Copyright 2008 Alibaba.com Croporation Limited. All * rights reserved. This software is the confidential and proprietary information of Alibaba Company. * ("Confidential Information"). You shall not disclose such Confidential Information and shall use it only in * accordance with the terms of the license agreement you entered into with Alibaba.com. */ package com.alibaba.simpleimage; import java.awt.RenderingHints; import java.awt.image.BufferedImage; import java.awt.image.renderable.ParameterBlock; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import javax.media.jai.Interpolation; import javax.media.jai.JAI; import javax.media.jai.PlanarImage; import javax.media.jai.RenderedOp; import org.apache.commons.io.IOUtils; import com.alibaba.simpleimage.jai.scale.LanczosScaleOp; import com.alibaba.simpleimage.render.ReadRender; import com.alibaba.simpleimage.render.WriteRender; /** * TODO Comment of ScaleTest * * @author wendell */ public class ScaleTest extends BaseTest { static final File path = new File("./src/test/resources/conf.test/simpleimage/scale"); static float scale = 0.2f; static double dScale = 0.2; public void testNearest() throws Exception { doScale("Nearest"); } public void testBilinear() throws Exception { doScale("Bilinear"); } public void testBicubic() throws Exception { doScale("Bicubic"); } public void testBicubic2() throws Exception { doScale("Bicubic2"); } public void testSubsampleAverage() throws Exception { doScale("SubsampleAverage"); } public void testLanczos() throws Exception { doScale("Lanczos"); } public void doScale(String name) throws Exception { for (File imgFile : path.listFiles()) { if (imgFile.getName().lastIndexOf("jpg") < 0) { continue; } if (imgFile.getName().indexOf("result") > 0) { continue; } String filename = imgFile.getName().substring(0, imgFile.getName().lastIndexOf(".")); InputStream in = new FileInputStream(imgFile); OutputStream out = new FileOutputStream(new File(resultDir, "SCALE_" + filename + "-" + name + ".jpg")); WriteRender wr = null; try { ReadRender rr = new ReadRender(in, true); ImageWrapper wi = rr.render(); PlanarImage img = wi.getAsPlanarImage(); if ("progbicu".equalsIgnoreCase(name)) { img = doProgressiveBicubic(img); } else if ("Nearest".equalsIgnoreCase(name)) { img = doScaleNearest(img); } else if ("Bilinear".equalsIgnoreCase(name)) { img = doScaleBilinear(img); } else if ("Bicubic".equalsIgnoreCase(name)) { img = doScaleBicubic(img); } else if ("Bicubic2".equalsIgnoreCase(name)) { img = doScaleBicubic2(img); } else if ("SubsampleAverage".equalsIgnoreCase(name)) { img = doSubsampleAverage(img); } else if ("lanczos".equalsIgnoreCase(name)){ img = doLanczos(img); } else { throw new IllegalArgumentException("Unknown alg " + name); } wi.setImage(img); wr = new WriteRender(wi, out); wr.render(); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } } } public PlanarImage doProgressiveBicubic(PlanarImage op) throws Exception { int dstWidth = 220; int w = op.getWidth(); while (w > dstWidth) { scale = 0.6f; ParameterBlock pb = new ParameterBlock(); pb.addSource(op); pb.add(scale); pb.add(scale); pb.add(0.0F); pb.add(0.0F); pb.add(Interpolation.getInstance(Interpolation.INTERP_BICUBIC)); RenderingHints qualityHints = new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); op = JAI.create("scale", pb, qualityHints); w = (int) (scale * w); } return op; } public PlanarImage doScaleNearest(PlanarImage op) throws Exception { ParameterBlock pb = new ParameterBlock(); pb.addSource(op); pb.add(scale); pb.add(scale); pb.add(0.0F); pb.add(0.0F); pb.add(Interpolation.getInstance(Interpolation.INTERP_NEAREST)); RenderingHints qualityHints = new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); op = JAI.create("scale", pb, qualityHints); return op; } public PlanarImage doScaleBilinear(PlanarImage op) throws Exception { ParameterBlock pb = new ParameterBlock(); pb.addSource(op); pb.add(scale); pb.add(scale); pb.add(0.0F); pb.add(0.0F); pb.add(Interpolation.getInstance(Interpolation.INTERP_BILINEAR)); RenderingHints qualityHints = new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); op = JAI.create("scale", pb, qualityHints); return op; } public PlanarImage doScaleBicubic(PlanarImage op) throws Exception { ParameterBlock pb = new ParameterBlock(); pb.addSource(op); pb.add(scale); pb.add(scale); pb.add(0.0F); pb.add(0.0F); pb.add(Interpolation.getInstance(Interpolation.INTERP_BICUBIC)); RenderingHints qualityHints = new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); op = JAI.create("scale", pb, qualityHints); return op; } public PlanarImage doScaleBicubic2(PlanarImage op) throws Exception { ParameterBlock pb = new ParameterBlock(); pb.addSource(op); pb.add(scale); pb.add(scale); pb.add(0.0F); pb.add(0.0F); pb.add(Interpolation.getInstance(Interpolation.INTERP_BICUBIC_2)); RenderingHints qualityHints = new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); op = JAI.create("scale", pb, qualityHints); return op; } public PlanarImage doSubsampleAverage(PlanarImage op) throws Exception { double zoom = dScale; ParameterBlock pb = new ParameterBlock(); pb.addSource(op); pb.add(zoom); pb.add(zoom); RenderingHints qualityHints = new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); RenderedOp zoomOp = JAI.create("SubsampleAverage", pb, qualityHints); return zoomOp; } public PlanarImage doLanczos(PlanarImage op) throws Exception { LanczosScaleOp scaleOp = new LanczosScaleOp(dScale, dScale); BufferedImage dst = scaleOp.compute(op.getAsBufferedImage()); return PlanarImage.wrapRenderedImage(dst); } }
7,689
0.592535
0.586162
217
34.433178
29.086815
117
false
false
0
0
0
0
0
0
0.626728
false
false
13
a876d92a77dd391013241d256b857e9baedaa6ea
27,479,200,791,980
782d5d6bd6637c5f8fcc1be3db4ff33c2ac7d15e
/src/main/java/com/baicai/futurekiller/data/EContract.java
8b57ecc8b1d8c233b4ab9023cf3a5a4952a345b2
[]
no_license
xiaoyuzxcasd/futurekiller
https://github.com/xiaoyuzxcasd/futurekiller
2377a5f57a5466a016345f87677177998a7d4112
27741a9f5f78da59851619d15083e75365dfe51c
refs/heads/master
2022-06-22T23:37:30.329000
2019-06-17T06:47:19
2019-06-17T06:47:19
51,816,110
0
0
null
false
2022-06-21T00:49:34
2016-02-16T07:17:20
2019-06-17T06:47:35
2022-06-21T00:49:31
27
0
0
3
Java
false
false
package com.baicai.futurekiller.data; import java.util.HashMap; import java.util.Map; public enum EContract { /** 螺纹钢 */ RB(1) /** 白银 */ ,AG(2) /** 黄金 */ ,AU(3) /** 沪铜 */ ,CU(4) /** 沪铝 */ ,AL(5) /** 沪锌 */ ,ZN(6) /** 沪铅 */ ,PB(7) /** 橡胶 */ ,RU(8) /** 燃油 */ ,FU(9) /** 线材 */ ,WR(10) /** 大豆 */ ,A(11) /** 豆粕 */ ,M(12) /** 豆油 */ ,Y(13) /** 焦炭 */ ,J(14) /** 玉米 */ ,C(15) /** 乙烯 */ ,L(16) /** 棕油 */ ,P(17) /** PVC */ ,V(18) /** 菜籽 */ ,RS(19) /** 菜粕 */ ,RM(20) /** 玻璃 */ ,FG(21) /** 棉花 */ ,CF(22) /** 强麦 */ ,WS(23) /** 籼稻 */ ,ER(24) /** 甲醇 */ ,ME(25) /** 菜油 */ ,RO(26) /** 甲酸 */ ,TA(27) ; private static final Map<Integer, EContract> id2Contract = initId2Contract(); private int id; private EContract(int id) { this.id = id; } public int getId() { return id; } private static Map<Integer, EContract> initId2Contract() { Map<Integer, EContract> map = new HashMap<Integer, EContract>(); for (EContract contract : EContract.values()) { map.put(contract.getId(), contract); } return map; } public static EContract getEContractById(int id) { return id2Contract.get(id); } }
UTF-8
Java
1,344
java
EContract.java
Java
[]
null
[]
package com.baicai.futurekiller.data; import java.util.HashMap; import java.util.Map; public enum EContract { /** 螺纹钢 */ RB(1) /** 白银 */ ,AG(2) /** 黄金 */ ,AU(3) /** 沪铜 */ ,CU(4) /** 沪铝 */ ,AL(5) /** 沪锌 */ ,ZN(6) /** 沪铅 */ ,PB(7) /** 橡胶 */ ,RU(8) /** 燃油 */ ,FU(9) /** 线材 */ ,WR(10) /** 大豆 */ ,A(11) /** 豆粕 */ ,M(12) /** 豆油 */ ,Y(13) /** 焦炭 */ ,J(14) /** 玉米 */ ,C(15) /** 乙烯 */ ,L(16) /** 棕油 */ ,P(17) /** PVC */ ,V(18) /** 菜籽 */ ,RS(19) /** 菜粕 */ ,RM(20) /** 玻璃 */ ,FG(21) /** 棉花 */ ,CF(22) /** 强麦 */ ,WS(23) /** 籼稻 */ ,ER(24) /** 甲醇 */ ,ME(25) /** 菜油 */ ,RO(26) /** 甲酸 */ ,TA(27) ; private static final Map<Integer, EContract> id2Contract = initId2Contract(); private int id; private EContract(int id) { this.id = id; } public int getId() { return id; } private static Map<Integer, EContract> initId2Contract() { Map<Integer, EContract> map = new HashMap<Integer, EContract>(); for (EContract contract : EContract.values()) { map.put(contract.getId(), contract); } return map; } public static EContract getEContractById(int id) { return id2Contract.get(id); } }
1,344
0.478191
0.438611
86
12.395349
14.177676
78
false
false
0
0
0
0
0
0
1.453488
false
false
13
56a9f22028b3a3ff262cb9c5767be80f0fc27fc1
19,567,871,003,480
53f9939adf76326f901be3aed08c7bb289c3b7b2
/manage/backend/src/main/java/mn/astvision/starter/api/ArticleApi.java
e11adcc6c38eeae031f4f7a69d752e242543c999
[]
no_license
Badamtsetseg/frontend
https://github.com/Badamtsetseg/frontend
64ae38c8752648b220a03f62eb268dd85f206e19
6ff5e4e89f13756880b26275b916451ddc73c119
refs/heads/main
2023-07-09T12:48:15.986000
2021-08-05T10:54:43
2021-08-05T10:54:43
395,301,729
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package mn.astvision.starter.api; import lombok.extern.slf4j.Slf4j; import mn.astvision.starter.api.request.DeleteRequest; import mn.astvision.starter.api.request.antd.AntdPagination; import mn.astvision.starter.api.response.antd.AntdTableDataList; import mn.astvision.starter.dao.ArticleDao; import mn.astvision.starter.model.Article; import mn.astvision.starter.model.auth.User; import mn.astvision.starter.model.enums.ArticleType; import mn.astvision.starter.repository.ArticleRepository; import mn.astvision.starter.repository.auth.UserRepository; import mn.astvision.starter.service.ArticleService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.access.annotation.Secured; import org.springframework.util.ObjectUtils; import org.springframework.web.bind.annotation.*; import java.security.Principal; import java.time.LocalDateTime; @Slf4j @Secured("ROLE_ARTICLE_MANAGE") @RestController @RequestMapping("/api/article") public class ArticleApi { @Autowired private ArticleRepository articleRepository; @Autowired private ArticleDao articleDAO; @Autowired private ArticleService articleService; @Autowired private UserRepository userRepository; @GetMapping public ResponseEntity<?> list(ArticleType type, String title, String authorId, Boolean hot, Boolean visible, Boolean deleted, AntdPagination pagination) { AntdTableDataList<Article> listData = new AntdTableDataList<>(); pagination.setTotal(articleDAO.count(type, title, authorId, hot, visible, deleted)); listData.setPagination(pagination); listData.setList(articleService.list(type, title, authorId, hot, visible, deleted, pagination.toPageRequest(), null)); return ResponseEntity.ok(listData); } @GetMapping("{id}") public ResponseEntity<Article> get(@PathVariable String id) { return ResponseEntity.ok().body(articleRepository.findById(id).orElse(null)); } @PutMapping("update") public ResponseEntity<?> update(@RequestBody Article updateRequest, Principal principal) { User user = userRepository.findByUsernameAndDeletedFalse(principal.getName()); if (user == null) return ResponseEntity.status(HttpStatus.FORBIDDEN).body("Хандах эрхгүй байна"); Article article; if (ObjectUtils.isEmpty(updateRequest.getId())) { article = new Article(); article.setCreatedBy(user.getId()); article.setCreatedDate(LocalDateTime.now()); } else { article = articleRepository.findById(updateRequest.getId()).orElse(null); if (article == null) return ResponseEntity.badRequest().body("Нийтлэл олдсонгүй: " + updateRequest.getId()); article.setModifiedBy(user.getId()); article.setModifiedDate(LocalDateTime.now()); } if (ObjectUtils.isEmpty(updateRequest.getTitle())) return ResponseEntity.badRequest().body("Гарчиг хоосон байна"); article.setType(updateRequest.getType()); article.setTitle(updateRequest.getTitle()); article.setShortContent(updateRequest.getShortContent()); article.setContent(updateRequest.getContent()); article.setAuthorId(updateRequest.getAuthorId()); article.setHot(updateRequest.isHot()); article.setVisible(updateRequest.isVisible()); article.setPremium(updateRequest.isPremium()); article.setCover(updateRequest.getCover()); article = articleRepository.save(article); return ResponseEntity.ok(article); } @DeleteMapping("delete") public ResponseEntity<?> delete(@RequestBody DeleteRequest deleteRequest, Principal principal) { if (ObjectUtils.isEmpty(deleteRequest.getId())) return ResponseEntity.badRequest().body("ID хоосон байна"); User user = userRepository.findByUsernameAndDeletedFalse(principal.getName()); if (user == null) return ResponseEntity.status(HttpStatus.FORBIDDEN).body("Хандах эрхгүй байна"); try { Article article = articleRepository.findById(deleteRequest.getId()).orElse(null); if (article == null) return ResponseEntity.badRequest().body("Нийтлэл олдсонгүй: " + deleteRequest.getId()); article.setDeleted(true); article.setModifiedBy(user.getId()); article.setModifiedDate(LocalDateTime.now()); articleRepository.save(article); return ResponseEntity.ok().body(null); } catch (Exception e) { return ResponseEntity.badRequest().body(e.getMessage()); } } }
UTF-8
Java
4,883
java
ArticleApi.java
Java
[]
null
[]
package mn.astvision.starter.api; import lombok.extern.slf4j.Slf4j; import mn.astvision.starter.api.request.DeleteRequest; import mn.astvision.starter.api.request.antd.AntdPagination; import mn.astvision.starter.api.response.antd.AntdTableDataList; import mn.astvision.starter.dao.ArticleDao; import mn.astvision.starter.model.Article; import mn.astvision.starter.model.auth.User; import mn.astvision.starter.model.enums.ArticleType; import mn.astvision.starter.repository.ArticleRepository; import mn.astvision.starter.repository.auth.UserRepository; import mn.astvision.starter.service.ArticleService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.access.annotation.Secured; import org.springframework.util.ObjectUtils; import org.springframework.web.bind.annotation.*; import java.security.Principal; import java.time.LocalDateTime; @Slf4j @Secured("ROLE_ARTICLE_MANAGE") @RestController @RequestMapping("/api/article") public class ArticleApi { @Autowired private ArticleRepository articleRepository; @Autowired private ArticleDao articleDAO; @Autowired private ArticleService articleService; @Autowired private UserRepository userRepository; @GetMapping public ResponseEntity<?> list(ArticleType type, String title, String authorId, Boolean hot, Boolean visible, Boolean deleted, AntdPagination pagination) { AntdTableDataList<Article> listData = new AntdTableDataList<>(); pagination.setTotal(articleDAO.count(type, title, authorId, hot, visible, deleted)); listData.setPagination(pagination); listData.setList(articleService.list(type, title, authorId, hot, visible, deleted, pagination.toPageRequest(), null)); return ResponseEntity.ok(listData); } @GetMapping("{id}") public ResponseEntity<Article> get(@PathVariable String id) { return ResponseEntity.ok().body(articleRepository.findById(id).orElse(null)); } @PutMapping("update") public ResponseEntity<?> update(@RequestBody Article updateRequest, Principal principal) { User user = userRepository.findByUsernameAndDeletedFalse(principal.getName()); if (user == null) return ResponseEntity.status(HttpStatus.FORBIDDEN).body("Хандах эрхгүй байна"); Article article; if (ObjectUtils.isEmpty(updateRequest.getId())) { article = new Article(); article.setCreatedBy(user.getId()); article.setCreatedDate(LocalDateTime.now()); } else { article = articleRepository.findById(updateRequest.getId()).orElse(null); if (article == null) return ResponseEntity.badRequest().body("Нийтлэл олдсонгүй: " + updateRequest.getId()); article.setModifiedBy(user.getId()); article.setModifiedDate(LocalDateTime.now()); } if (ObjectUtils.isEmpty(updateRequest.getTitle())) return ResponseEntity.badRequest().body("Гарчиг хоосон байна"); article.setType(updateRequest.getType()); article.setTitle(updateRequest.getTitle()); article.setShortContent(updateRequest.getShortContent()); article.setContent(updateRequest.getContent()); article.setAuthorId(updateRequest.getAuthorId()); article.setHot(updateRequest.isHot()); article.setVisible(updateRequest.isVisible()); article.setPremium(updateRequest.isPremium()); article.setCover(updateRequest.getCover()); article = articleRepository.save(article); return ResponseEntity.ok(article); } @DeleteMapping("delete") public ResponseEntity<?> delete(@RequestBody DeleteRequest deleteRequest, Principal principal) { if (ObjectUtils.isEmpty(deleteRequest.getId())) return ResponseEntity.badRequest().body("ID хоосон байна"); User user = userRepository.findByUsernameAndDeletedFalse(principal.getName()); if (user == null) return ResponseEntity.status(HttpStatus.FORBIDDEN).body("Хандах эрхгүй байна"); try { Article article = articleRepository.findById(deleteRequest.getId()).orElse(null); if (article == null) return ResponseEntity.badRequest().body("Нийтлэл олдсонгүй: " + deleteRequest.getId()); article.setDeleted(true); article.setModifiedBy(user.getId()); article.setModifiedDate(LocalDateTime.now()); articleRepository.save(article); return ResponseEntity.ok().body(null); } catch (Exception e) { return ResponseEntity.badRequest().body(e.getMessage()); } } }
4,883
0.710587
0.70996
116
40.284481
31.363773
158
false
false
0
0
0
0
0
0
0.715517
false
false
13
14ccd36c932a23c4330d3e03172acfd638314a3c
25,786,983,676,592
04bcebcc4f98a67f7ac4e4adf988afac5ee5b6d6
/pcalculadora_fracao/test/pcalculadorafracao/PCalculadoraTest.java
82be0375f15ccaf58c5572cafbaab3466516f84b
[]
no_license
jkmanaus/calculadora_fracao
https://github.com/jkmanaus/calculadora_fracao
4eb8d4ed16ebadc9fdfdb3c33d2a931e0f19d175
95adf24e81b17e2b75095159916772af7069a68e
refs/heads/main
2023-04-15T15:43:01.227000
2021-04-27T00:35:02
2021-04-27T00:35:02
361,932,807
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * 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 pcalculadorafracao; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author John */ public class PCalculadoraTest { public PCalculadoraTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } /** * Test of somar method, of class PCalculadora. */ @Test public void testSomar() { System.out.println("somar"); int num1 = 10; int den1 = 2; int num2 = 12; int den2 = 3; PCalculadora instance = new PCalculadora(); double expResult = 14.0; double result = instance.somar(num1, den1, num2, den2); assert(expResult == result); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of subtrair method, of class PCalculadora. */ @Test public void testSubtrair() { System.out.println("subtrair"); int num1 = 10; int den1 = 2; int num2 = 12; int den2 = 3; PCalculadora instance = new PCalculadora(); double expResult = -4.0; double result = instance.subtrair(num1, den1, num2, den2); assertEquals(expResult, result, 0.0); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of multiplicar method, of class PCalculadora. */ @Test public void testMultiplicar() { System.out.println("multiplicar"); int num1 = 10; int den1 = 2; int num2 = 12; int den2 = 3; PCalculadora instance = new PCalculadora(); double expResult = 20.0; double result = instance.multiplicar(num1, den1, num2, den2); assertEquals(expResult, result, 0.0); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of dividir method, of class PCalculadora. */ @Test public void testDividir() { System.out.println("dividir"); int num1 = 10; int den1 = 2; int num2 = 12; int den2 = 3; PCalculadora instance = new PCalculadora(); double expResult = 1.0; double result = instance.dividir(num1, den1, num2, den2); assertEquals(expResult, result, 0.0); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } }
UTF-8
Java
2,982
java
PCalculadoraTest.java
Java
[ { "context": " static org.junit.Assert.*;\r\n\r\n/**\r\n *\r\n * @author John\r\n */\r\npublic class PCalculadoraTest {\r\n \r\n pu", "end": 367, "score": 0.9128525257110596, "start": 363, "tag": "NAME", "value": "John" } ]
null
[]
/* * 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 pcalculadorafracao; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author John */ public class PCalculadoraTest { public PCalculadoraTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } /** * Test of somar method, of class PCalculadora. */ @Test public void testSomar() { System.out.println("somar"); int num1 = 10; int den1 = 2; int num2 = 12; int den2 = 3; PCalculadora instance = new PCalculadora(); double expResult = 14.0; double result = instance.somar(num1, den1, num2, den2); assert(expResult == result); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of subtrair method, of class PCalculadora. */ @Test public void testSubtrair() { System.out.println("subtrair"); int num1 = 10; int den1 = 2; int num2 = 12; int den2 = 3; PCalculadora instance = new PCalculadora(); double expResult = -4.0; double result = instance.subtrair(num1, den1, num2, den2); assertEquals(expResult, result, 0.0); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of multiplicar method, of class PCalculadora. */ @Test public void testMultiplicar() { System.out.println("multiplicar"); int num1 = 10; int den1 = 2; int num2 = 12; int den2 = 3; PCalculadora instance = new PCalculadora(); double expResult = 20.0; double result = instance.multiplicar(num1, den1, num2, den2); assertEquals(expResult, result, 0.0); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of dividir method, of class PCalculadora. */ @Test public void testDividir() { System.out.println("dividir"); int num1 = 10; int den1 = 2; int num2 = 12; int den2 = 3; PCalculadora instance = new PCalculadora(); double expResult = 1.0; double result = instance.dividir(num1, den1, num2, den2); assertEquals(expResult, result, 0.0); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } }
2,982
0.575453
0.551308
102
27.235294
22.152845
83
false
false
0
0
0
0
0
0
0.686275
false
false
13
e698e0123e180af5206ff3012c345875f0814057
25,142,738,601,631
cf6d55e88e8f4a030819b81a667593df0cdab47c
/src/main/java/com/cerbansouto/compucar/services/ServicePublisher.java
0889bb39cb72aa5535c43a1d7335e4d20f4123f6
[]
no_license
bcerban/compucar
https://github.com/bcerban/compucar
ae79bd61d1c5acb6e9453d31c44845547068c560
2e01b7994e07bd1b83eec81de783a52108a202e3
refs/heads/develop
2021-07-12T09:55:53.974000
2019-11-28T17:02:50
2019-11-28T17:02:50
211,555,919
0
0
null
false
2020-10-13T17:36:05
2019-09-28T20:09:42
2019-11-28T17:03:00
2020-10-13T16:54:58
143
0
0
1
Java
false
false
package com.cerbansouto.compucar.services; import com.cerbansouto.compucar.dtos.Event; import com.cerbansouto.compucar.model.Service; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.messaging.Message; import org.springframework.messaging.MessageChannel; import org.springframework.messaging.support.MessageBuilder; import org.springframework.stereotype.Component; @Component @Slf4j public class ServicePublisher { @Autowired private MessageChannel serviceChannel; public void publish(Service service) { try { com.cerbansouto.compucar.dtos.Service serviceDto = new com.cerbansouto.compucar.dtos.Service(); serviceDto.setCode(service.getCode()); serviceDto.setEvents(service.getEvents().stream() .map(e -> new Event(service.getCode(), e.getName(), e.getPayload())) .toArray(Event[]::new)); Message<com.cerbansouto.compucar.dtos.Service> message = MessageBuilder.withPayload(serviceDto).build(); serviceChannel.send(message); } catch (Exception e) { log.error(e.getMessage(), e); } } }
UTF-8
Java
1,215
java
ServicePublisher.java
Java
[]
null
[]
package com.cerbansouto.compucar.services; import com.cerbansouto.compucar.dtos.Event; import com.cerbansouto.compucar.model.Service; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.messaging.Message; import org.springframework.messaging.MessageChannel; import org.springframework.messaging.support.MessageBuilder; import org.springframework.stereotype.Component; @Component @Slf4j public class ServicePublisher { @Autowired private MessageChannel serviceChannel; public void publish(Service service) { try { com.cerbansouto.compucar.dtos.Service serviceDto = new com.cerbansouto.compucar.dtos.Service(); serviceDto.setCode(service.getCode()); serviceDto.setEvents(service.getEvents().stream() .map(e -> new Event(service.getCode(), e.getName(), e.getPayload())) .toArray(Event[]::new)); Message<com.cerbansouto.compucar.dtos.Service> message = MessageBuilder.withPayload(serviceDto).build(); serviceChannel.send(message); } catch (Exception e) { log.error(e.getMessage(), e); } } }
1,215
0.706173
0.703704
32
36.96875
29.467657
116
false
false
0
0
0
0
0
0
0.59375
false
false
13
d90f788c9bc2146850070a89da2b41c6816f0b2a
21,388,937,191,108
ef0c1514e9af6de3ba4a20e0d01de7cc3a915188
/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/fluent/models/QueryResultsInner.java
633149d8ec813a1d9171f9c77c8e8a32435afae1
[ "MIT", "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-unknown-license-reference", "LGPL-2.1-or-later", "CC0-1.0", "BSD-3-Clause", "UPL-1.0", "Apache-2.0", "LicenseRef-scancode-public-domain", "BSD-2-Clause", "LicenseRef-scancode-generic-cla" ]
permissive
Azure/azure-sdk-for-java
https://github.com/Azure/azure-sdk-for-java
0902d584b42d3654b4ce65b1dad8409f18ddf4bc
789bdc6c065dc44ce9b8b630e2f2e5896b2a7616
refs/heads/main
2023-09-04T09:36:35.821000
2023-09-02T01:53:56
2023-09-02T01:53:56
2,928,948
2,027
2,084
MIT
false
2023-09-14T21:37:15
2011-12-06T23:33:56
2023-09-14T17:19:10
2023-09-14T21:37:14
3,043,660
1,994
1,854
1,435
Java
false
false
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.network.fluent.models; import com.azure.core.annotation.Fluent; import com.azure.resourcemanager.network.models.SingleQueryResult; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.List; /** Query result. */ @Fluent public final class QueryResultsInner { /* * Number of total records matching the query. */ @JsonProperty(value = "matchingRecordsCount") private Long matchingRecordsCount; /* * Array containing the results of the query */ @JsonProperty(value = "signatures") private List<SingleQueryResult> signatures; /** Creates an instance of QueryResultsInner class. */ public QueryResultsInner() { } /** * Get the matchingRecordsCount property: Number of total records matching the query. * * @return the matchingRecordsCount value. */ public Long matchingRecordsCount() { return this.matchingRecordsCount; } /** * Set the matchingRecordsCount property: Number of total records matching the query. * * @param matchingRecordsCount the matchingRecordsCount value to set. * @return the QueryResultsInner object itself. */ public QueryResultsInner withMatchingRecordsCount(Long matchingRecordsCount) { this.matchingRecordsCount = matchingRecordsCount; return this; } /** * Get the signatures property: Array containing the results of the query. * * @return the signatures value. */ public List<SingleQueryResult> signatures() { return this.signatures; } /** * Set the signatures property: Array containing the results of the query. * * @param signatures the signatures value to set. * @return the QueryResultsInner object itself. */ public QueryResultsInner withSignatures(List<SingleQueryResult> signatures) { this.signatures = signatures; return this; } /** * Validates the instance. * * @throws IllegalArgumentException thrown if the instance is not valid. */ public void validate() { if (signatures() != null) { signatures().forEach(e -> e.validate()); } } }
UTF-8
Java
2,386
java
QueryResultsInner.java
Java
[]
null
[]
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.network.fluent.models; import com.azure.core.annotation.Fluent; import com.azure.resourcemanager.network.models.SingleQueryResult; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.List; /** Query result. */ @Fluent public final class QueryResultsInner { /* * Number of total records matching the query. */ @JsonProperty(value = "matchingRecordsCount") private Long matchingRecordsCount; /* * Array containing the results of the query */ @JsonProperty(value = "signatures") private List<SingleQueryResult> signatures; /** Creates an instance of QueryResultsInner class. */ public QueryResultsInner() { } /** * Get the matchingRecordsCount property: Number of total records matching the query. * * @return the matchingRecordsCount value. */ public Long matchingRecordsCount() { return this.matchingRecordsCount; } /** * Set the matchingRecordsCount property: Number of total records matching the query. * * @param matchingRecordsCount the matchingRecordsCount value to set. * @return the QueryResultsInner object itself. */ public QueryResultsInner withMatchingRecordsCount(Long matchingRecordsCount) { this.matchingRecordsCount = matchingRecordsCount; return this; } /** * Get the signatures property: Array containing the results of the query. * * @return the signatures value. */ public List<SingleQueryResult> signatures() { return this.signatures; } /** * Set the signatures property: Array containing the results of the query. * * @param signatures the signatures value to set. * @return the QueryResultsInner object itself. */ public QueryResultsInner withSignatures(List<SingleQueryResult> signatures) { this.signatures = signatures; return this; } /** * Validates the instance. * * @throws IllegalArgumentException thrown if the instance is not valid. */ public void validate() { if (signatures() != null) { signatures().forEach(e -> e.validate()); } } }
2,386
0.677284
0.677284
81
28.456791
26.35421
89
false
false
0
0
0
0
0
0
0.17284
false
false
13
f295699f360ee8360369dd784b14e9bfd44170ba
20,306,605,423,084
625764fd38200c86041ee7ad0e0ef60da9a39cd5
/yudao-framework/yudao-spring-boot-starter-web/src/main/java/cn/iocoder/yudao/framework/web/core/handler/GlobalExceptionHandler.java
1dd82c6fa08155dc1aaf286a8e877f4c4d6ab657
[ "Apache-2.0", "MIT" ]
permissive
YunaiV/onemall
https://github.com/YunaiV/onemall
7e86f09690a21e1e286cdd651f837c68410bef35
5f96b50bad9950090612f7623f98e72a94796bc2
refs/heads/master
2023-03-11T13:09:15.877000
2023-03-05T14:38:04
2023-03-05T14:38:04
184,611,677
6,197
2,270
null
null
null
null
null
null
null
null
null
null
null
null
null
package cn.iocoder.yudao.framework.web.core.handler; import cn.hutool.core.exceptions.ExceptionUtil; import cn.hutool.core.map.MapUtil; import cn.hutool.extra.servlet.ServletUtil; import cn.iocoder.yudao.framework.apilog.core.service.ApiErrorLog; import cn.iocoder.yudao.framework.common.exception.ServiceException; import cn.iocoder.yudao.framework.common.pojo.CommonResult; import cn.iocoder.yudao.framework.apilog.core.service.ApiErrorLogFrameworkService; import cn.iocoder.yudao.framework.common.util.monitor.TracerUtils; import cn.iocoder.yudao.framework.web.core.util.WebFrameworkUtils; import cn.iocoder.yudao.framework.common.util.json.JsonUtils; import cn.iocoder.yudao.framework.common.util.servlet.ServletUtils; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.security.access.AccessDeniedException; import org.springframework.util.Assert; import org.springframework.validation.BindException; import org.springframework.validation.FieldError; import org.springframework.web.HttpRequestMethodNotSupportedException; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.MissingServletRequestParameterException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException; import org.springframework.web.servlet.NoHandlerFoundException; import javax.servlet.http.HttpServletRequest; import javax.validation.ConstraintViolation; import javax.validation.ConstraintViolationException; import javax.validation.ValidationException; import java.time.LocalDateTime; import java.util.Map; import static cn.iocoder.yudao.framework.common.exception.enums.GlobalErrorCodeConstants.*; /** * 全局异常处理器,将 Exception 翻译成 CommonResult + 对应的异常编号 * * @author 芋道源码 */ @RestControllerAdvice @AllArgsConstructor @Slf4j public class GlobalExceptionHandler { private final String applicationName; private final ApiErrorLogFrameworkService apiErrorLogFrameworkService; /** * 处理所有异常,主要是提供给 Filter 使用 * 因为 Filter 不走 SpringMVC 的流程,但是我们又需要兜底处理异常,所以这里提供一个全量的异常处理过程,保持逻辑统一。 * * @param request 请求 * @param ex 异常 * @return 通用返回 */ public CommonResult<?> allExceptionHandler(HttpServletRequest request, Throwable ex) { if (ex instanceof MissingServletRequestParameterException) { return missingServletRequestParameterExceptionHandler((MissingServletRequestParameterException) ex); } if (ex instanceof MethodArgumentTypeMismatchException) { return methodArgumentTypeMismatchExceptionHandler((MethodArgumentTypeMismatchException) ex); } if (ex instanceof MethodArgumentNotValidException) { return methodArgumentNotValidExceptionExceptionHandler((MethodArgumentNotValidException) ex); } if (ex instanceof BindException) { return bindExceptionHandler((BindException) ex); } if (ex instanceof ConstraintViolationException) { return constraintViolationExceptionHandler((ConstraintViolationException) ex); } if (ex instanceof ValidationException) { return validationException((ValidationException) ex); } if (ex instanceof NoHandlerFoundException) { return noHandlerFoundExceptionHandler((NoHandlerFoundException) ex); } if (ex instanceof HttpRequestMethodNotSupportedException) { return httpRequestMethodNotSupportedExceptionHandler((HttpRequestMethodNotSupportedException) ex); } // if (ex instanceof RequestNotPermitted) { // return requestNotPermittedExceptionHandler(request, (RequestNotPermitted) ex); // } if (ex instanceof ServiceException) { return serviceExceptionHandler((ServiceException) ex); } if (ex instanceof AccessDeniedException) { return accessDeniedExceptionHandler(request, (AccessDeniedException) ex); } return defaultExceptionHandler(request, ex); } /** * 处理 SpringMVC 请求参数缺失 * * 例如说,接口上设置了 @RequestParam("xx") 参数,结果并未传递 xx 参数 */ @ExceptionHandler(value = MissingServletRequestParameterException.class) public CommonResult<?> missingServletRequestParameterExceptionHandler(MissingServletRequestParameterException ex) { log.warn("[missingServletRequestParameterExceptionHandler]", ex); return CommonResult.error(BAD_REQUEST.getCode(), String.format("请求参数缺失:%s", ex.getParameterName())); } /** * 处理 SpringMVC 请求参数类型错误 * * 例如说,接口上设置了 @RequestParam("xx") 参数为 Integer,结果传递 xx 参数类型为 String */ @ExceptionHandler(MethodArgumentTypeMismatchException.class) public CommonResult<?> methodArgumentTypeMismatchExceptionHandler(MethodArgumentTypeMismatchException ex) { log.warn("[missingServletRequestParameterExceptionHandler]", ex); return CommonResult.error(BAD_REQUEST.getCode(), String.format("请求参数类型错误:%s", ex.getMessage())); } /** * 处理 SpringMVC 参数校验不正确 */ @ExceptionHandler(MethodArgumentNotValidException.class) public CommonResult<?> methodArgumentNotValidExceptionExceptionHandler(MethodArgumentNotValidException ex) { log.warn("[methodArgumentNotValidExceptionExceptionHandler]", ex); FieldError fieldError = ex.getBindingResult().getFieldError(); assert fieldError != null; // 断言,避免告警 return CommonResult.error(BAD_REQUEST.getCode(), String.format("请求参数不正确:%s", fieldError.getDefaultMessage())); } /** * 处理 SpringMVC 参数绑定不正确,本质上也是通过 Validator 校验 */ @ExceptionHandler(BindException.class) public CommonResult<?> bindExceptionHandler(BindException ex) { log.warn("[handleBindException]", ex); FieldError fieldError = ex.getFieldError(); assert fieldError != null; // 断言,避免告警 return CommonResult.error(BAD_REQUEST.getCode(), String.format("请求参数不正确:%s", fieldError.getDefaultMessage())); } /** * 处理 Validator 校验不通过产生的异常 */ @ExceptionHandler(value = ConstraintViolationException.class) public CommonResult<?> constraintViolationExceptionHandler(ConstraintViolationException ex) { log.warn("[constraintViolationExceptionHandler]", ex); ConstraintViolation<?> constraintViolation = ex.getConstraintViolations().iterator().next(); return CommonResult.error(BAD_REQUEST.getCode(), String.format("请求参数不正确:%s", constraintViolation.getMessage())); } /** * 处理 Dubbo Consumer 本地参数校验时,抛出的 ValidationException 异常 */ @ExceptionHandler(value = ValidationException.class) public CommonResult<?> validationException(ValidationException ex) { log.warn("[constraintViolationExceptionHandler]", ex); // 无法拼接明细的错误信息,因为 Dubbo Consumer 抛出 ValidationException 异常时,是直接的字符串信息,且人类不可读 return CommonResult.error(BAD_REQUEST); } /** * 处理 SpringMVC 请求地址不存在 * * 注意,它需要设置如下两个配置项: * 1. spring.mvc.throw-exception-if-no-handler-found 为 true * 2. spring.mvc.static-path-pattern 为 /statics/** */ @ExceptionHandler(NoHandlerFoundException.class) public CommonResult<?> noHandlerFoundExceptionHandler(NoHandlerFoundException ex) { log.warn("[noHandlerFoundExceptionHandler]", ex); return CommonResult.error(NOT_FOUND.getCode(), String.format("请求地址不存在:%s", ex.getRequestURL())); } /** * 处理 SpringMVC 请求方法不正确 * * 例如说,A 接口的方法为 GET 方式,结果请求方法为 POST 方式,导致不匹配 */ @ExceptionHandler(HttpRequestMethodNotSupportedException.class) public CommonResult<?> httpRequestMethodNotSupportedExceptionHandler(HttpRequestMethodNotSupportedException ex) { log.warn("[httpRequestMethodNotSupportedExceptionHandler]", ex); return CommonResult.error(METHOD_NOT_ALLOWED.getCode(), String.format("请求方法不正确:%s", ex.getMessage())); } // TODO 芋艿:暂时去掉 // /** // * 处理 Resilience4j 限流抛出的异常 // */ // @ExceptionHandler(value = RequestNotPermitted.class) // public CommonResult<?> requestNotPermittedExceptionHandler(HttpServletRequest req, RequestNotPermitted ex) { // log.warn("[requestNotPermittedExceptionHandler][url({}) 访问过于频繁]", req.getRequestURL(), ex); // return CommonResult.error(TOO_MANY_REQUESTS); // } /** * 处理 Spring Security 权限不足的异常 * * 来源是,使用 @PreAuthorize 注解,AOP 进行权限拦截 */ @ExceptionHandler(value = AccessDeniedException.class) public CommonResult<?> accessDeniedExceptionHandler(HttpServletRequest req, AccessDeniedException ex) { log.warn("[accessDeniedExceptionHandler][userId({}) 无法访问 url({})]", WebFrameworkUtils.getLoginUserId(req), req.getRequestURL(), ex); return CommonResult.error(FORBIDDEN); } /** * 处理业务异常 ServiceException * * 例如说,商品库存不足,用户手机号已存在。 */ @ExceptionHandler(value = ServiceException.class) public CommonResult<?> serviceExceptionHandler(ServiceException ex) { log.info("[serviceExceptionHandler]", ex); return CommonResult.error(ex.getCode(), ex.getMessage()); } /** * 处理系统异常,兜底处理所有的一切 */ @ExceptionHandler(value = Exception.class) public CommonResult<?> defaultExceptionHandler(HttpServletRequest req, Throwable ex) { log.error("[defaultExceptionHandler]", ex); // 插入异常日志 this.createExceptionLog(req, ex); // 返回 ERROR CommonResult return CommonResult.error(INTERNAL_SERVER_ERROR.getCode(), INTERNAL_SERVER_ERROR.getMsg()); } private void createExceptionLog(HttpServletRequest req, Throwable e) { // 插入错误日志 ApiErrorLog errorLog = new ApiErrorLog(); try { // 初始化 errorLog initExceptionLog(errorLog, req, e); // 执行插入 errorLog apiErrorLogFrameworkService.createApiErrorLog(errorLog); } catch (Throwable th) { log.error("[createExceptionLog][url({}) log({}) 发生异常]", req.getRequestURI(), JsonUtils.toJsonString(errorLog), th); } } private void initExceptionLog(ApiErrorLog errorLog, HttpServletRequest request, Throwable e) { // 处理用户信息 errorLog.setUserId(WebFrameworkUtils.getLoginUserId(request)); errorLog.setUserType(WebFrameworkUtils.getLoginUserType(request)); // 设置异常字段 errorLog.setExceptionName(e.getClass().getName()); errorLog.setExceptionMessage(ExceptionUtil.getMessage(e)); errorLog.setExceptionRootCauseMessage(ExceptionUtil.getRootCauseMessage(e)); errorLog.setExceptionStackTrace(ExceptionUtil.stacktraceToString(e)); StackTraceElement[] stackTraceElements = e.getStackTrace(); Assert.notEmpty(stackTraceElements, "异常 stackTraceElements 不能为空"); StackTraceElement stackTraceElement = stackTraceElements[0]; errorLog.setExceptionClassName(stackTraceElement.getClassName()); errorLog.setExceptionFileName(stackTraceElement.getFileName()); errorLog.setExceptionMethodName(stackTraceElement.getMethodName()); errorLog.setExceptionLineNumber(stackTraceElement.getLineNumber()); // 设置其它字段 errorLog.setTraceId(TracerUtils.getTraceId()); errorLog.setApplicationName(applicationName); errorLog.setRequestUrl(request.getRequestURI()); Map<String, Object> requestParams = MapUtil.<String, Object>builder() .put("query", ServletUtil.getParamMap(request)) .put("body", ServletUtil.getBody(request)).build(); errorLog.setRequestParams(JsonUtils.toJsonString(requestParams)); errorLog.setRequestMethod(request.getMethod()); errorLog.setUserAgent(ServletUtils.getUserAgent(request)); errorLog.setUserIp(ServletUtil.getClientIP(request)); errorLog.setExceptionTime(LocalDateTime.now()); } }
UTF-8
Java
13,019
java
GlobalExceptionHandler.java
Java
[ { "context": "xception 翻译成 CommonResult + 对应的异常编号\n *\n * @author 芋道源码\n */\n@RestControllerAdvice\n@AllArgsConstructor\n", "end": 1910, "score": 0.8738971948623657, "start": 1909, "tag": "NAME", "value": "芋" }, { "context": "xception 翻译成 CommonResult + 对应的异常编号\n *\n * @author 芋道源码\n */\n@RestControllerAdvice\n@AllArgsConstructor\n@Sl", "end": 1913, "score": 0.7062073349952698, "start": 1909, "tag": "USERNAME", "value": "芋道源码" } ]
null
[]
package cn.iocoder.yudao.framework.web.core.handler; import cn.hutool.core.exceptions.ExceptionUtil; import cn.hutool.core.map.MapUtil; import cn.hutool.extra.servlet.ServletUtil; import cn.iocoder.yudao.framework.apilog.core.service.ApiErrorLog; import cn.iocoder.yudao.framework.common.exception.ServiceException; import cn.iocoder.yudao.framework.common.pojo.CommonResult; import cn.iocoder.yudao.framework.apilog.core.service.ApiErrorLogFrameworkService; import cn.iocoder.yudao.framework.common.util.monitor.TracerUtils; import cn.iocoder.yudao.framework.web.core.util.WebFrameworkUtils; import cn.iocoder.yudao.framework.common.util.json.JsonUtils; import cn.iocoder.yudao.framework.common.util.servlet.ServletUtils; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.security.access.AccessDeniedException; import org.springframework.util.Assert; import org.springframework.validation.BindException; import org.springframework.validation.FieldError; import org.springframework.web.HttpRequestMethodNotSupportedException; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.MissingServletRequestParameterException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException; import org.springframework.web.servlet.NoHandlerFoundException; import javax.servlet.http.HttpServletRequest; import javax.validation.ConstraintViolation; import javax.validation.ConstraintViolationException; import javax.validation.ValidationException; import java.time.LocalDateTime; import java.util.Map; import static cn.iocoder.yudao.framework.common.exception.enums.GlobalErrorCodeConstants.*; /** * 全局异常处理器,将 Exception 翻译成 CommonResult + 对应的异常编号 * * @author 芋道源码 */ @RestControllerAdvice @AllArgsConstructor @Slf4j public class GlobalExceptionHandler { private final String applicationName; private final ApiErrorLogFrameworkService apiErrorLogFrameworkService; /** * 处理所有异常,主要是提供给 Filter 使用 * 因为 Filter 不走 SpringMVC 的流程,但是我们又需要兜底处理异常,所以这里提供一个全量的异常处理过程,保持逻辑统一。 * * @param request 请求 * @param ex 异常 * @return 通用返回 */ public CommonResult<?> allExceptionHandler(HttpServletRequest request, Throwable ex) { if (ex instanceof MissingServletRequestParameterException) { return missingServletRequestParameterExceptionHandler((MissingServletRequestParameterException) ex); } if (ex instanceof MethodArgumentTypeMismatchException) { return methodArgumentTypeMismatchExceptionHandler((MethodArgumentTypeMismatchException) ex); } if (ex instanceof MethodArgumentNotValidException) { return methodArgumentNotValidExceptionExceptionHandler((MethodArgumentNotValidException) ex); } if (ex instanceof BindException) { return bindExceptionHandler((BindException) ex); } if (ex instanceof ConstraintViolationException) { return constraintViolationExceptionHandler((ConstraintViolationException) ex); } if (ex instanceof ValidationException) { return validationException((ValidationException) ex); } if (ex instanceof NoHandlerFoundException) { return noHandlerFoundExceptionHandler((NoHandlerFoundException) ex); } if (ex instanceof HttpRequestMethodNotSupportedException) { return httpRequestMethodNotSupportedExceptionHandler((HttpRequestMethodNotSupportedException) ex); } // if (ex instanceof RequestNotPermitted) { // return requestNotPermittedExceptionHandler(request, (RequestNotPermitted) ex); // } if (ex instanceof ServiceException) { return serviceExceptionHandler((ServiceException) ex); } if (ex instanceof AccessDeniedException) { return accessDeniedExceptionHandler(request, (AccessDeniedException) ex); } return defaultExceptionHandler(request, ex); } /** * 处理 SpringMVC 请求参数缺失 * * 例如说,接口上设置了 @RequestParam("xx") 参数,结果并未传递 xx 参数 */ @ExceptionHandler(value = MissingServletRequestParameterException.class) public CommonResult<?> missingServletRequestParameterExceptionHandler(MissingServletRequestParameterException ex) { log.warn("[missingServletRequestParameterExceptionHandler]", ex); return CommonResult.error(BAD_REQUEST.getCode(), String.format("请求参数缺失:%s", ex.getParameterName())); } /** * 处理 SpringMVC 请求参数类型错误 * * 例如说,接口上设置了 @RequestParam("xx") 参数为 Integer,结果传递 xx 参数类型为 String */ @ExceptionHandler(MethodArgumentTypeMismatchException.class) public CommonResult<?> methodArgumentTypeMismatchExceptionHandler(MethodArgumentTypeMismatchException ex) { log.warn("[missingServletRequestParameterExceptionHandler]", ex); return CommonResult.error(BAD_REQUEST.getCode(), String.format("请求参数类型错误:%s", ex.getMessage())); } /** * 处理 SpringMVC 参数校验不正确 */ @ExceptionHandler(MethodArgumentNotValidException.class) public CommonResult<?> methodArgumentNotValidExceptionExceptionHandler(MethodArgumentNotValidException ex) { log.warn("[methodArgumentNotValidExceptionExceptionHandler]", ex); FieldError fieldError = ex.getBindingResult().getFieldError(); assert fieldError != null; // 断言,避免告警 return CommonResult.error(BAD_REQUEST.getCode(), String.format("请求参数不正确:%s", fieldError.getDefaultMessage())); } /** * 处理 SpringMVC 参数绑定不正确,本质上也是通过 Validator 校验 */ @ExceptionHandler(BindException.class) public CommonResult<?> bindExceptionHandler(BindException ex) { log.warn("[handleBindException]", ex); FieldError fieldError = ex.getFieldError(); assert fieldError != null; // 断言,避免告警 return CommonResult.error(BAD_REQUEST.getCode(), String.format("请求参数不正确:%s", fieldError.getDefaultMessage())); } /** * 处理 Validator 校验不通过产生的异常 */ @ExceptionHandler(value = ConstraintViolationException.class) public CommonResult<?> constraintViolationExceptionHandler(ConstraintViolationException ex) { log.warn("[constraintViolationExceptionHandler]", ex); ConstraintViolation<?> constraintViolation = ex.getConstraintViolations().iterator().next(); return CommonResult.error(BAD_REQUEST.getCode(), String.format("请求参数不正确:%s", constraintViolation.getMessage())); } /** * 处理 Dubbo Consumer 本地参数校验时,抛出的 ValidationException 异常 */ @ExceptionHandler(value = ValidationException.class) public CommonResult<?> validationException(ValidationException ex) { log.warn("[constraintViolationExceptionHandler]", ex); // 无法拼接明细的错误信息,因为 Dubbo Consumer 抛出 ValidationException 异常时,是直接的字符串信息,且人类不可读 return CommonResult.error(BAD_REQUEST); } /** * 处理 SpringMVC 请求地址不存在 * * 注意,它需要设置如下两个配置项: * 1. spring.mvc.throw-exception-if-no-handler-found 为 true * 2. spring.mvc.static-path-pattern 为 /statics/** */ @ExceptionHandler(NoHandlerFoundException.class) public CommonResult<?> noHandlerFoundExceptionHandler(NoHandlerFoundException ex) { log.warn("[noHandlerFoundExceptionHandler]", ex); return CommonResult.error(NOT_FOUND.getCode(), String.format("请求地址不存在:%s", ex.getRequestURL())); } /** * 处理 SpringMVC 请求方法不正确 * * 例如说,A 接口的方法为 GET 方式,结果请求方法为 POST 方式,导致不匹配 */ @ExceptionHandler(HttpRequestMethodNotSupportedException.class) public CommonResult<?> httpRequestMethodNotSupportedExceptionHandler(HttpRequestMethodNotSupportedException ex) { log.warn("[httpRequestMethodNotSupportedExceptionHandler]", ex); return CommonResult.error(METHOD_NOT_ALLOWED.getCode(), String.format("请求方法不正确:%s", ex.getMessage())); } // TODO 芋艿:暂时去掉 // /** // * 处理 Resilience4j 限流抛出的异常 // */ // @ExceptionHandler(value = RequestNotPermitted.class) // public CommonResult<?> requestNotPermittedExceptionHandler(HttpServletRequest req, RequestNotPermitted ex) { // log.warn("[requestNotPermittedExceptionHandler][url({}) 访问过于频繁]", req.getRequestURL(), ex); // return CommonResult.error(TOO_MANY_REQUESTS); // } /** * 处理 Spring Security 权限不足的异常 * * 来源是,使用 @PreAuthorize 注解,AOP 进行权限拦截 */ @ExceptionHandler(value = AccessDeniedException.class) public CommonResult<?> accessDeniedExceptionHandler(HttpServletRequest req, AccessDeniedException ex) { log.warn("[accessDeniedExceptionHandler][userId({}) 无法访问 url({})]", WebFrameworkUtils.getLoginUserId(req), req.getRequestURL(), ex); return CommonResult.error(FORBIDDEN); } /** * 处理业务异常 ServiceException * * 例如说,商品库存不足,用户手机号已存在。 */ @ExceptionHandler(value = ServiceException.class) public CommonResult<?> serviceExceptionHandler(ServiceException ex) { log.info("[serviceExceptionHandler]", ex); return CommonResult.error(ex.getCode(), ex.getMessage()); } /** * 处理系统异常,兜底处理所有的一切 */ @ExceptionHandler(value = Exception.class) public CommonResult<?> defaultExceptionHandler(HttpServletRequest req, Throwable ex) { log.error("[defaultExceptionHandler]", ex); // 插入异常日志 this.createExceptionLog(req, ex); // 返回 ERROR CommonResult return CommonResult.error(INTERNAL_SERVER_ERROR.getCode(), INTERNAL_SERVER_ERROR.getMsg()); } private void createExceptionLog(HttpServletRequest req, Throwable e) { // 插入错误日志 ApiErrorLog errorLog = new ApiErrorLog(); try { // 初始化 errorLog initExceptionLog(errorLog, req, e); // 执行插入 errorLog apiErrorLogFrameworkService.createApiErrorLog(errorLog); } catch (Throwable th) { log.error("[createExceptionLog][url({}) log({}) 发生异常]", req.getRequestURI(), JsonUtils.toJsonString(errorLog), th); } } private void initExceptionLog(ApiErrorLog errorLog, HttpServletRequest request, Throwable e) { // 处理用户信息 errorLog.setUserId(WebFrameworkUtils.getLoginUserId(request)); errorLog.setUserType(WebFrameworkUtils.getLoginUserType(request)); // 设置异常字段 errorLog.setExceptionName(e.getClass().getName()); errorLog.setExceptionMessage(ExceptionUtil.getMessage(e)); errorLog.setExceptionRootCauseMessage(ExceptionUtil.getRootCauseMessage(e)); errorLog.setExceptionStackTrace(ExceptionUtil.stacktraceToString(e)); StackTraceElement[] stackTraceElements = e.getStackTrace(); Assert.notEmpty(stackTraceElements, "异常 stackTraceElements 不能为空"); StackTraceElement stackTraceElement = stackTraceElements[0]; errorLog.setExceptionClassName(stackTraceElement.getClassName()); errorLog.setExceptionFileName(stackTraceElement.getFileName()); errorLog.setExceptionMethodName(stackTraceElement.getMethodName()); errorLog.setExceptionLineNumber(stackTraceElement.getLineNumber()); // 设置其它字段 errorLog.setTraceId(TracerUtils.getTraceId()); errorLog.setApplicationName(applicationName); errorLog.setRequestUrl(request.getRequestURI()); Map<String, Object> requestParams = MapUtil.<String, Object>builder() .put("query", ServletUtil.getParamMap(request)) .put("body", ServletUtil.getBody(request)).build(); errorLog.setRequestParams(JsonUtils.toJsonString(requestParams)); errorLog.setRequestMethod(request.getMethod()); errorLog.setUserAgent(ServletUtils.getUserAgent(request)); errorLog.setUserIp(ServletUtil.getClientIP(request)); errorLog.setExceptionTime(LocalDateTime.now()); } }
13,019
0.723876
0.723292
272
43.08456
33.976261
128
false
false
0
0
0
0
0
0
0.566176
false
false
13
6c093e3b62010510dc7279b7d0720a67f1210f0e
2,980,707,360,183
3fe51ec4cab97b99f3978cf6bdec62cca0c5f693
/src/main/java/com/techlooper/pojo/FootPrint.java
a173627cb4b6aeb0d2b84e2126d792e4aa763a95
[]
no_license
chrisshayan/TechLooperImport
https://github.com/chrisshayan/TechLooperImport
542e56384fe92174d5d53059e31117708de12b86
43f220f5cfe7ff6a70dbd7d259831703d917bfdd
refs/heads/master
2021-01-25T06:05:53.589000
2015-03-01T16:06:37
2015-03-01T16:06:37
29,576,627
0
5
null
false
2015-04-13T11:40:54
2015-01-21T07:07:01
2015-03-01T16:06:39
2015-04-13T11:40:54
1,361
0
2
0
Java
null
null
package com.techlooper.pojo; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import java.util.HashMap; import java.util.Map; /** * Created by phuonghqh on 2/4/15. */ @JsonIgnoreProperties(ignoreUnknown = true) public class FootPrint { private Integer lastPageNumber = 0; private Map<String, String> crawlers = new HashMap<>(); public Integer getLastPageNumber() { return lastPageNumber; } public void setLastPageNumber(Integer lastPageNumber) { this.lastPageNumber = lastPageNumber; } public Map<String, String> getCrawlers() { return crawlers; } public void setCrawlers(Map<String, String> crawlers) { this.crawlers = crawlers; } public static class FootPrintBuilder { private FootPrint footPrint; public FootPrintBuilder withCrawler(String country, String fromTo) { footPrint.crawlers.put(country, fromTo); return this; } public static FootPrintBuilder footPrint(FootPrint footPrint) { FootPrintBuilder builder = new FootPrintBuilder(); builder.footPrint = footPrint; return builder; } private FootPrintBuilder() { footPrint = new FootPrint(); } public FootPrintBuilder withLastPageNumber(Integer lastPageNumber) { footPrint.lastPageNumber = lastPageNumber; return this; } public FootPrintBuilder withCrawlers(Map<String, String> crawlers) { footPrint.crawlers = crawlers; return this; } public static FootPrintBuilder footPrint() { return new FootPrintBuilder(); } public FootPrint build() { return footPrint; } } }
UTF-8
Java
1,796
java
FootPrint.java
Java
[ { "context": ".HashMap;\nimport java.util.Map;\n\n/**\n * Created by phuonghqh on 2/4/15.\n */\n@JsonIgnoreProperties(ignoreUnknow", "end": 169, "score": 0.999614417552948, "start": 160, "tag": "USERNAME", "value": "phuonghqh" } ]
null
[]
package com.techlooper.pojo; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import java.util.HashMap; import java.util.Map; /** * Created by phuonghqh on 2/4/15. */ @JsonIgnoreProperties(ignoreUnknown = true) public class FootPrint { private Integer lastPageNumber = 0; private Map<String, String> crawlers = new HashMap<>(); public Integer getLastPageNumber() { return lastPageNumber; } public void setLastPageNumber(Integer lastPageNumber) { this.lastPageNumber = lastPageNumber; } public Map<String, String> getCrawlers() { return crawlers; } public void setCrawlers(Map<String, String> crawlers) { this.crawlers = crawlers; } public static class FootPrintBuilder { private FootPrint footPrint; public FootPrintBuilder withCrawler(String country, String fromTo) { footPrint.crawlers.put(country, fromTo); return this; } public static FootPrintBuilder footPrint(FootPrint footPrint) { FootPrintBuilder builder = new FootPrintBuilder(); builder.footPrint = footPrint; return builder; } private FootPrintBuilder() { footPrint = new FootPrint(); } public FootPrintBuilder withLastPageNumber(Integer lastPageNumber) { footPrint.lastPageNumber = lastPageNumber; return this; } public FootPrintBuilder withCrawlers(Map<String, String> crawlers) { footPrint.crawlers = crawlers; return this; } public static FootPrintBuilder footPrint() { return new FootPrintBuilder(); } public FootPrint build() { return footPrint; } } }
1,796
0.635857
0.633074
70
24.657143
23.242132
76
false
false
0
0
0
0
0
0
0.414286
false
false
13
ef1f0e83c15661eef1886f4afcc5129558017e9d
2,980,707,362,633
444074cc977dce30fc6edb8b1f76219ec8de70fd
/src/com/company/Main.java
35c752d2a6898491ef6fee356c30bac8777af553
[]
no_license
ErnestoChe/Cache
https://github.com/ErnestoChe/Cache
4a084f7705944aa4a19f81c1867bcfd46adca50c
21c0679076986cf1bec10c6666f1ade36f5a7040
refs/heads/master
2020-05-06T13:43:58.328000
2019-04-08T13:17:26
2019-04-08T13:17:26
180,152,872
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.company; public class Main { public static void main(String[] args) { // write your code here NativeCache<Integer> nc = new NativeCache<>(7, Integer.class); nc.put("qwe", 1); nc.put("asd", 2); nc.put("zxc", 3); nc.put("rty", 4); nc.put("fgh", 5); nc.put("vbn", 6); nc.put("uio", 7); nc.log(); for (int i = 0; i < 3; i++) { nc.get("qwe"); nc.get("asd"); nc.get("zxc"); nc.get("rty"); } nc.get("uio"); for (int i = 0; i < 5; i++) { nc.get("fgh"); nc.get("vbn"); } nc.get("fgh"); System.out.println(); nc.log(); nc.put("uio", 7); nc.log(); nc.put("qwerty", 2); nc.log(); nc.put("topchik", 12); nc.log(); } }
UTF-8
Java
884
java
Main.java
Java
[]
null
[]
package com.company; public class Main { public static void main(String[] args) { // write your code here NativeCache<Integer> nc = new NativeCache<>(7, Integer.class); nc.put("qwe", 1); nc.put("asd", 2); nc.put("zxc", 3); nc.put("rty", 4); nc.put("fgh", 5); nc.put("vbn", 6); nc.put("uio", 7); nc.log(); for (int i = 0; i < 3; i++) { nc.get("qwe"); nc.get("asd"); nc.get("zxc"); nc.get("rty"); } nc.get("uio"); for (int i = 0; i < 5; i++) { nc.get("fgh"); nc.get("vbn"); } nc.get("fgh"); System.out.println(); nc.log(); nc.put("uio", 7); nc.log(); nc.put("qwerty", 2); nc.log(); nc.put("topchik", 12); nc.log(); } }
884
0.397059
0.378959
37
22.891891
12.415735
70
false
false
0
0
0
0
0
0
1.135135
false
false
13
22c5fdcd09e61a0c1e6c6bff0571708c4a3eede0
6,356,551,642,785
c56cdb7210dd588432643a67dcfa3cc617612e1b
/mall-kill/mall-kill-dubbo-server-interface/src/main/java/cn/mlm/mall/kill/pojo/ItemKillSuccess.java
2ba2eb93a9e6afb1b4083d7b4ab3884fd6d7ad45
[]
no_license
Jacklinsir/mall
https://github.com/Jacklinsir/mall
47bd13261ff559101747b2398b67e1f1880c1017
9ccc1b3a9e4e74222399b322b57247ab2db9f860
refs/heads/master
2022-08-01T13:49:36.431000
2019-12-26T04:51:55
2019-12-26T04:51:55
226,466,082
32
4
null
null
null
null
null
null
null
null
null
null
null
null
null
package cn.mlm.mall.kill.pojo; import lombok.Data; import lombok.ToString; import java.util.Date; @Data public class ItemKillSuccess { private String code; private Integer itemId; private Integer killId; private String userId; private Byte status; private Date createTime; private Integer diffTime; }
UTF-8
Java
338
java
ItemKillSuccess.java
Java
[]
null
[]
package cn.mlm.mall.kill.pojo; import lombok.Data; import lombok.ToString; import java.util.Date; @Data public class ItemKillSuccess { private String code; private Integer itemId; private Integer killId; private String userId; private Byte status; private Date createTime; private Integer diffTime; }
338
0.721893
0.721893
24
13.125
12.872168
30
false
false
0
0
0
0
0
0
0.458333
false
false
13
4286a9d51ae1549d231e071fbb35224792c0ea76
11,751,030,580,210
6033620f755c679bbd8086300765577a30b9f573
/05-尚硅谷宋红康(好)/02-代码手敲/day25-泛型与File/src/com/atguigu/java3/FileTest.java
044aebd047e7eae51f826dd2d7dd79eed4a6903d
[ "MIT" ]
permissive
lm101845/LearnJava
https://github.com/lm101845/LearnJava
dbd1dc34fca5a163d7fdaa509940d34d07014a31
4947f507ad6011e6d64089b0e04d0aa92d4823d5
refs/heads/master
2023-05-25T10:37:34.038000
2022-12-21T08:53:28
2022-12-21T08:53:28
345,279,998
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.atguigu.java3; /** * @Author liming * @Date 2022/8/6 23:38 **/ import org.junit.Test; import java.io.File; import java.io.IOException; import java.util.Date; /** * File类的使用 * * 1. File类的一个对象,代表一个文件或一个文件目录(俗称:文件夹) * 2. File类声明在java.io包下 * 3. File类中涉及到关于文件或文件目录的创建、删除、重命名、修改时间、文件大小等方法, * 并未涉及到写入或读取文件内容的操作。如果需要读取或写入文件内容,必须使用IO流来完成。 * 4. 后续File类的对象常会作为参数传递到流的构造器中,指明读取或写入的"终点". */ public class FileTest { /** 1.如何创建File类的实例 File(String filePath) File(String parentPath,String childPath) File(File parentFile,String childPath) 2. 相对路径:相较于某个路径下,指明的路径。 绝对路径:包含盘符在内的文件或文件目录的路径 3.路径分隔符 windows:\\ unix:/ */ @Test public void test1(){ //构造器1 File file1 = new File("hello.txt"); //相对于当前module File file2 = new File("D:\\test.txt"); System.out.println(file1); System.out.println(file2); //构造器2 File file3 = new File("D:\\workspace_idea1","JavaSenior"); System.out.println(file3); //构造器3: File file4 = new File(file3,"hi.txt"); System.out.println(file4); } /** public String getAbsolutePath():获取绝对路径 public String getPath() :获取路径 public String getName() :获取名称 public String getParent():获取上层文件目录路径。若无,返回null public long length() :获取文件长度(即:字节数)。不能获取目录的长度。 public long lastModified() :获取最后一次的修改时间,毫秒值 如下的两个方法适用于文件目录: public String[] list() :获取指定目录下的所有文件或者文件目录的名称数组 public File[] listFiles() :获取指定目录下的所有文件或者文件目录的File数组 */ @Test public void test2(){ File file1 = new File("hello.txt"); File file2 = new File("d:\\io\\hi.txt"); //此时这些方法调用属于内存层面的方法调用,还没涉及到硬盘中要有这些文件 System.out.println(file1.getAbsoluteFile()); System.out.println(file1.getPath()); System.out.println(file1.getName()); System.out.println(file1.getParent()); System.out.println(file1.length()); System.out.println(new Date(file1.lastModified())); System.out.println(); System.out.println(file2.getAbsolutePath()); System.out.println(file2.getPath()); System.out.println(file2.getName()); System.out.println(file2.getParent()); System.out.println(file2.length()); System.out.println(file2.lastModified()); } @Test public void test3(){ File file = new File("D:\\io"); String[] list = file.list(); for (String s: list) { System.out.println(s); } File[] files = file.listFiles(); for (File f: files) { System.out.println(f); } } /** public boolean renameTo(File dest):把文件重命名为指定的文件路径 比如:file1.renameTo(file2)为例: 要想保证返回true,需要file1在硬盘中是存在的,且file2不能在硬盘中存在。 */ @Test public void test4(){ File file1 = new File("hello.txt"); File file2 = new File("D:\\io\\hi.txt"); boolean renameTo = file1.renameTo(file2); System.out.println(renameTo); } /** public boolean isDirectory():判断是否是文件目录 public boolean isFile() :判断是否是文件 public boolean exists() :判断是否存在 public boolean canRead() :判断是否可读 public boolean canWrite() :判断是否可写 public boolean isHidden() :判断是否隐藏 */ @Test public void test5(){ File file1 = new File("hello.txt"); file1 = new File("hello1.txt"); System.out.println(file1.isDirectory()); System.out.println(file1.isFile()); System.out.println(file1.exists()); System.out.println(file1.canRead()); System.out.println(file1.canWrite()); System.out.println(file1.isHidden()); System.out.println(); File file2 = new File("d:\\io"); file2 = new File("d:\\io1"); System.out.println(file2.isDirectory()); System.out.println(file2.isFile()); System.out.println(file2.exists()); System.out.println(file2.canRead()); System.out.println(file2.canWrite()); System.out.println(file2.isHidden()); } /** 创建硬盘中对应的文件或文件目录 public boolean createNewFile() :创建文件。若文件存在,则不创建,返回false public boolean mkdir() :创建文件目录。如果此文件目录存在,就不创建了。如果此文件目录的上层目录不存在,也不创建。 public boolean mkdirs() :创建文件目录。如果此文件目录存在,就不创建了。如果上层文件目录不存在,一并创建 删除磁盘中的文件或文件目录 public boolean delete():删除文件或者文件夹 删除注意事项:Java中的删除不走回收站。 */ @Test public void test6() throws IOException { File file1 = new File("hi.txt"); if(!file1.exists()){ //文件的创建 file1.createNewFile(); System.out.println("创建成功"); }else{//文件存在 file1.delete(); System.out.println("删除成功"); } } @Test public void test7(){ //文件目录的创建 File file1 = new File("d:\\io\\io1\\io3"); boolean mkdir = file1.mkdir(); if(mkdir){ System.out.println("创建成功1"); } File file2 = new File("d:\\io\\io1\\io4"); boolean mkdir1 = file2.mkdirs(); if(mkdir1){ System.out.println("创建成功2"); } //要想删除成功,io4文件目录下不能有子目录或文件 File file3 = new File("D:\\io\\io1\\io4"); file3 = new File("D:\\io\\io1"); System.out.println(file3.delete()); } }
UTF-8
Java
6,677
java
FileTest.java
Java
[ { "context": "package com.atguigu.java3;\n\n/**\n * @Author liming\n * @Date 2022/8/6 23:38\n **/\n\nimport org.junit.Te", "end": 49, "score": 0.999447226524353, "start": 43, "tag": "USERNAME", "value": "liming" } ]
null
[]
package com.atguigu.java3; /** * @Author liming * @Date 2022/8/6 23:38 **/ import org.junit.Test; import java.io.File; import java.io.IOException; import java.util.Date; /** * File类的使用 * * 1. File类的一个对象,代表一个文件或一个文件目录(俗称:文件夹) * 2. File类声明在java.io包下 * 3. File类中涉及到关于文件或文件目录的创建、删除、重命名、修改时间、文件大小等方法, * 并未涉及到写入或读取文件内容的操作。如果需要读取或写入文件内容,必须使用IO流来完成。 * 4. 后续File类的对象常会作为参数传递到流的构造器中,指明读取或写入的"终点". */ public class FileTest { /** 1.如何创建File类的实例 File(String filePath) File(String parentPath,String childPath) File(File parentFile,String childPath) 2. 相对路径:相较于某个路径下,指明的路径。 绝对路径:包含盘符在内的文件或文件目录的路径 3.路径分隔符 windows:\\ unix:/ */ @Test public void test1(){ //构造器1 File file1 = new File("hello.txt"); //相对于当前module File file2 = new File("D:\\test.txt"); System.out.println(file1); System.out.println(file2); //构造器2 File file3 = new File("D:\\workspace_idea1","JavaSenior"); System.out.println(file3); //构造器3: File file4 = new File(file3,"hi.txt"); System.out.println(file4); } /** public String getAbsolutePath():获取绝对路径 public String getPath() :获取路径 public String getName() :获取名称 public String getParent():获取上层文件目录路径。若无,返回null public long length() :获取文件长度(即:字节数)。不能获取目录的长度。 public long lastModified() :获取最后一次的修改时间,毫秒值 如下的两个方法适用于文件目录: public String[] list() :获取指定目录下的所有文件或者文件目录的名称数组 public File[] listFiles() :获取指定目录下的所有文件或者文件目录的File数组 */ @Test public void test2(){ File file1 = new File("hello.txt"); File file2 = new File("d:\\io\\hi.txt"); //此时这些方法调用属于内存层面的方法调用,还没涉及到硬盘中要有这些文件 System.out.println(file1.getAbsoluteFile()); System.out.println(file1.getPath()); System.out.println(file1.getName()); System.out.println(file1.getParent()); System.out.println(file1.length()); System.out.println(new Date(file1.lastModified())); System.out.println(); System.out.println(file2.getAbsolutePath()); System.out.println(file2.getPath()); System.out.println(file2.getName()); System.out.println(file2.getParent()); System.out.println(file2.length()); System.out.println(file2.lastModified()); } @Test public void test3(){ File file = new File("D:\\io"); String[] list = file.list(); for (String s: list) { System.out.println(s); } File[] files = file.listFiles(); for (File f: files) { System.out.println(f); } } /** public boolean renameTo(File dest):把文件重命名为指定的文件路径 比如:file1.renameTo(file2)为例: 要想保证返回true,需要file1在硬盘中是存在的,且file2不能在硬盘中存在。 */ @Test public void test4(){ File file1 = new File("hello.txt"); File file2 = new File("D:\\io\\hi.txt"); boolean renameTo = file1.renameTo(file2); System.out.println(renameTo); } /** public boolean isDirectory():判断是否是文件目录 public boolean isFile() :判断是否是文件 public boolean exists() :判断是否存在 public boolean canRead() :判断是否可读 public boolean canWrite() :判断是否可写 public boolean isHidden() :判断是否隐藏 */ @Test public void test5(){ File file1 = new File("hello.txt"); file1 = new File("hello1.txt"); System.out.println(file1.isDirectory()); System.out.println(file1.isFile()); System.out.println(file1.exists()); System.out.println(file1.canRead()); System.out.println(file1.canWrite()); System.out.println(file1.isHidden()); System.out.println(); File file2 = new File("d:\\io"); file2 = new File("d:\\io1"); System.out.println(file2.isDirectory()); System.out.println(file2.isFile()); System.out.println(file2.exists()); System.out.println(file2.canRead()); System.out.println(file2.canWrite()); System.out.println(file2.isHidden()); } /** 创建硬盘中对应的文件或文件目录 public boolean createNewFile() :创建文件。若文件存在,则不创建,返回false public boolean mkdir() :创建文件目录。如果此文件目录存在,就不创建了。如果此文件目录的上层目录不存在,也不创建。 public boolean mkdirs() :创建文件目录。如果此文件目录存在,就不创建了。如果上层文件目录不存在,一并创建 删除磁盘中的文件或文件目录 public boolean delete():删除文件或者文件夹 删除注意事项:Java中的删除不走回收站。 */ @Test public void test6() throws IOException { File file1 = new File("hi.txt"); if(!file1.exists()){ //文件的创建 file1.createNewFile(); System.out.println("创建成功"); }else{//文件存在 file1.delete(); System.out.println("删除成功"); } } @Test public void test7(){ //文件目录的创建 File file1 = new File("d:\\io\\io1\\io3"); boolean mkdir = file1.mkdir(); if(mkdir){ System.out.println("创建成功1"); } File file2 = new File("d:\\io\\io1\\io4"); boolean mkdir1 = file2.mkdirs(); if(mkdir1){ System.out.println("创建成功2"); } //要想删除成功,io4文件目录下不能有子目录或文件 File file3 = new File("D:\\io\\io1\\io4"); file3 = new File("D:\\io\\io1"); System.out.println(file3.delete()); } }
6,677
0.590213
0.571132
195
26.143589
19.086575
72
false
false
0
0
0
0
0
0
0.374359
false
false
13
0a29be4653910a4cdefc7ba6bc99d3824016f791
35,854,387,024,960
6ff31d99b44d75db08e4e2ca4833b921cf48ac05
/Data Structures/ZombieMain.java
dd36ec7501d9640d634cfd66261c5eb5fdc79665
[]
no_license
GregMurray30/ClassWork
https://github.com/GregMurray30/ClassWork
65b8363731d07ece897155e6a160bc10b6720783
89f3b7ac71ad9c834286618be81b14d88b0278f8
refs/heads/master
2021-09-10T11:38:59.405000
2018-03-25T20:20:33
2018-03-25T20:20:33
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.*; class ZombieMain { class Zombie { public double hunger; public boolean madeKill = false; public boolean makesKill(double numHumans, double numZombies, double rand) { double killFactor = (numHumans)/4*(numHumans+numZombies); if ( killFactor >= rand) { madeKill = true; } return madeKill; } public void updateHunger() { if (madeKill) { hunger = 0.0; } else { hunger ++; } } public void reanimate(ArrayList zombieList, ArrayList humanList, boolean madeKill) { if (madeKill) { zombieList.add(new Zombie()); } } Zombie() { hunger = 0.0; madeKill = false; } } import java.util.*; class Human { public double age; public void updateAge() { age ++; } public void breed(ArrayList aList, boolean bool) { if (bool) { aList.add(new Human()); } } public boolean hasChild(double rand) { if (rand <= 0.05) { return true; } else { return false; } } Human() { age = 23.0; } } import java.util.*; class Simulation { //Random number generator method static double randomGenerator() { Random rnd = new Random(); rnd.setSeed(1234); double rand = rnd.nextDouble(); return rand; } //Declare the arrayLists for zombies and humans. static ArrayList<Zombie> zombieList = new ArrayList<Zombie>(); static ArrayList<Human> humanList = new ArrayList<Human>(); //Initialize the temporary arrays iteratively and then add each //element of that array into the arrayLists static void initHumanLists () { for (int i = 0; i < 100; i ++) { humanList.add(new Human()); } System.out.println(humanList.size()); } static void initZombieLists() { for (int a = 0; a < 20; a ++) { zombieList.add(new Zombie()); } System.out.println(zombieList.size()); } //Spring method to simulate the human breeding season static void Spring() { for (int i = 0; i < humanList.size(); i ++) { if (humanList.get(i).age >= 14) { double fertility = randomGenerator(); humanList.get(i).breed(humanList, humanList.get(i).hasChild(fertility)); } } } static void Summer() { int counter = 0; for (Iterator<Zombie> it = zombieList.iterator(); it.hasNext();) { double rand = randomGenerator(); boolean madeKill = it.next().makesKill(humanList.size(), zombieList.size(), rand); if (madeKill){ counter ++; } } for (int i = 0; i < counter; i++) { zombieList.add(new Zombie()); humanList.remove(0); } } static void Fall() { for (int i = 0; i < humanList.size(); i ++) { humanList.get(i).updateAge(); } for (int j = 0; j < zombieList.size(); j ++) { zombieList.get(j).updateHunger(); } } static void Winter() { for (Iterator<Zombie> it = zombieList.iterator(); it.hasNext();) { if (it.next().hunger>= 3.0) { it.remove(); } } } static void printOutput() { double avgAge = 0; double avgHunger = 0; for (int i = 0; i < humanList.size(); i ++) { avgAge = avgAge + humanList.get(i).age; } avgAge = avgAge/humanList.size(); for (int i = 0; i < zombieList.size(); i ++) { avgHunger = avgHunger + zombieList.get(i).hunger; } avgHunger = avgHunger/zombieList.size(); System.out.printf("There are " + humanList.size() + " humans (avg age %.2f) and " + zombieList.size() + " zombies (avg hunger %.2f)\n", avgAge, avgHunger); } public static void main(String[] args) { initHumanLists(); initZombieLists(); System.out.println(randomGenerator()); for (int i = 1; i <= 10; i ++) { printOutput(); Spring(); Summer(); Fall(); Winter(); } } } }
UTF-8
Java
3,795
java
ZombieMain.java
Java
[]
null
[]
import java.util.*; class ZombieMain { class Zombie { public double hunger; public boolean madeKill = false; public boolean makesKill(double numHumans, double numZombies, double rand) { double killFactor = (numHumans)/4*(numHumans+numZombies); if ( killFactor >= rand) { madeKill = true; } return madeKill; } public void updateHunger() { if (madeKill) { hunger = 0.0; } else { hunger ++; } } public void reanimate(ArrayList zombieList, ArrayList humanList, boolean madeKill) { if (madeKill) { zombieList.add(new Zombie()); } } Zombie() { hunger = 0.0; madeKill = false; } } import java.util.*; class Human { public double age; public void updateAge() { age ++; } public void breed(ArrayList aList, boolean bool) { if (bool) { aList.add(new Human()); } } public boolean hasChild(double rand) { if (rand <= 0.05) { return true; } else { return false; } } Human() { age = 23.0; } } import java.util.*; class Simulation { //Random number generator method static double randomGenerator() { Random rnd = new Random(); rnd.setSeed(1234); double rand = rnd.nextDouble(); return rand; } //Declare the arrayLists for zombies and humans. static ArrayList<Zombie> zombieList = new ArrayList<Zombie>(); static ArrayList<Human> humanList = new ArrayList<Human>(); //Initialize the temporary arrays iteratively and then add each //element of that array into the arrayLists static void initHumanLists () { for (int i = 0; i < 100; i ++) { humanList.add(new Human()); } System.out.println(humanList.size()); } static void initZombieLists() { for (int a = 0; a < 20; a ++) { zombieList.add(new Zombie()); } System.out.println(zombieList.size()); } //Spring method to simulate the human breeding season static void Spring() { for (int i = 0; i < humanList.size(); i ++) { if (humanList.get(i).age >= 14) { double fertility = randomGenerator(); humanList.get(i).breed(humanList, humanList.get(i).hasChild(fertility)); } } } static void Summer() { int counter = 0; for (Iterator<Zombie> it = zombieList.iterator(); it.hasNext();) { double rand = randomGenerator(); boolean madeKill = it.next().makesKill(humanList.size(), zombieList.size(), rand); if (madeKill){ counter ++; } } for (int i = 0; i < counter; i++) { zombieList.add(new Zombie()); humanList.remove(0); } } static void Fall() { for (int i = 0; i < humanList.size(); i ++) { humanList.get(i).updateAge(); } for (int j = 0; j < zombieList.size(); j ++) { zombieList.get(j).updateHunger(); } } static void Winter() { for (Iterator<Zombie> it = zombieList.iterator(); it.hasNext();) { if (it.next().hunger>= 3.0) { it.remove(); } } } static void printOutput() { double avgAge = 0; double avgHunger = 0; for (int i = 0; i < humanList.size(); i ++) { avgAge = avgAge + humanList.get(i).age; } avgAge = avgAge/humanList.size(); for (int i = 0; i < zombieList.size(); i ++) { avgHunger = avgHunger + zombieList.get(i).hunger; } avgHunger = avgHunger/zombieList.size(); System.out.printf("There are " + humanList.size() + " humans (avg age %.2f) and " + zombieList.size() + " zombies (avg hunger %.2f)\n", avgAge, avgHunger); } public static void main(String[] args) { initHumanLists(); initZombieLists(); System.out.println(randomGenerator()); for (int i = 1; i <= 10; i ++) { printOutput(); Spring(); Summer(); Fall(); Winter(); } } } }
3,795
0.587615
0.576812
177
19.440678
22.104736
157
false
false
0
0
0
0
0
0
2.220339
false
false
13
4e1614493ac37d96b76ad817d5423af340b67a83
37,383,395,376,702
ef913940a836da2bfa166c1e630fd4c4cd025ddf
/src/org/fw/little/base/boot/JettyStart.java
9adddeee2495be48d3c5ef6fcf1e9d9c1731f277
[]
no_license
liangpeng9631/log4j2-write-DB
https://github.com/liangpeng9631/log4j2-write-DB
31bfa0a3369898d9084db4156086d889df0b61df
97b30bd6b4352d9ad71431ecbfef84a95c006f30
refs/heads/master
2020-04-25T02:44:55.221000
2019-02-26T09:24:04
2019-02-26T09:24:04
172,451,132
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.fw.little.base.boot; import java.util.EnumSet; import javax.servlet.DispatcherType; import javax.servlet.Filter; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.servlet.FilterHolder; import org.eclipse.jetty.webapp.WebAppContext; public class JettyStart { private String confClass; /** * 端口 * **/ private int port; /** * 站点个根目录 * **/ private String pub; /** * 过滤器 * **/ private Filter filter; /** * 欢迎页面 * **/ private String[] welcomeFiles; public JettyStart(){} /** * 设置配置文件 * **/ public void setConfClass(String confClass) { this.confClass = confClass; } /** * 端口 * **/ public void setPort(int port) { this.port = port; } /** * 站点根目录 * **/ public void setPub(String pub) { this.pub = pub; } /** * 欢迎页列表 * **/ public void setWelcomeFiles(String[] welcomeFiles) { this.welcomeFiles = welcomeFiles; } /** * 设置过滤器 * **/ public void setFilter(Filter filter) { this.filter = filter; } public void run() { EnumSet<DispatcherType> all = EnumSet.of(DispatcherType.ASYNC, DispatcherType.ERROR, DispatcherType.FORWARD, DispatcherType.INCLUDE, DispatcherType.REQUEST); final Server server = new Server(port); server.setStopAtShutdown(true); try { FilterHolder filterHolder = new FilterHolder(filter); filterHolder.setInitParameter("configClass", confClass); WebAppContext context = new WebAppContext(pub,"/"); context.addFilter(filterHolder, "/*", all); context.setWelcomeFiles(welcomeFiles); context.setDefaultsDescriptor("webdefault.xml"); server.setHandler(context); server.start(); server.join(); } catch (Exception e) { e.printStackTrace(); } } }
UTF-8
Java
1,881
java
JettyStart.java
Java
[]
null
[]
package org.fw.little.base.boot; import java.util.EnumSet; import javax.servlet.DispatcherType; import javax.servlet.Filter; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.servlet.FilterHolder; import org.eclipse.jetty.webapp.WebAppContext; public class JettyStart { private String confClass; /** * 端口 * **/ private int port; /** * 站点个根目录 * **/ private String pub; /** * 过滤器 * **/ private Filter filter; /** * 欢迎页面 * **/ private String[] welcomeFiles; public JettyStart(){} /** * 设置配置文件 * **/ public void setConfClass(String confClass) { this.confClass = confClass; } /** * 端口 * **/ public void setPort(int port) { this.port = port; } /** * 站点根目录 * **/ public void setPub(String pub) { this.pub = pub; } /** * 欢迎页列表 * **/ public void setWelcomeFiles(String[] welcomeFiles) { this.welcomeFiles = welcomeFiles; } /** * 设置过滤器 * **/ public void setFilter(Filter filter) { this.filter = filter; } public void run() { EnumSet<DispatcherType> all = EnumSet.of(DispatcherType.ASYNC, DispatcherType.ERROR, DispatcherType.FORWARD, DispatcherType.INCLUDE, DispatcherType.REQUEST); final Server server = new Server(port); server.setStopAtShutdown(true); try { FilterHolder filterHolder = new FilterHolder(filter); filterHolder.setInitParameter("configClass", confClass); WebAppContext context = new WebAppContext(pub,"/"); context.addFilter(filterHolder, "/*", all); context.setWelcomeFiles(welcomeFiles); context.setDefaultsDescriptor("webdefault.xml"); server.setHandler(context); server.start(); server.join(); } catch (Exception e) { e.printStackTrace(); } } }
1,881
0.639889
0.639889
107
15.878505
17.118996
65
false
false
0
0
0
0
0
0
1.906542
false
false
13
a10c6972782284ce991499d65a1abb15c4e01b85
37,383,395,378,288
cab3f7913aa2b1b0c129d3821e7aef815abe9553
/app/src/main/java/app/reytum/com/seep/game/DealCards.java
7173182a4f31872be8fa280158f02908fd06c74e
[]
no_license
reytum/Seep
https://github.com/reytum/Seep
903f5886fd609f7ecb81393db1051f8258765c43
f8a9c0285b662abb72b39e65a193d2eacde8f83f
refs/heads/master
2020-09-16T09:24:51.873000
2018-04-13T14:32:22
2018-04-13T14:32:22
67,188,870
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package app.reytum.com.seep.game; import java.io.Serializable; import java.util.ArrayList; import app.reytum.com.seep.utils.Card; import app.reytum.com.seep.utils.Deck; /** * Created by reytum on 3/9/16. */ public class DealCards implements Serializable { ArrayList<Card> playerOneCards; ArrayList<Card> playerTwoCards; ArrayList<Card> playerThreeCards; ArrayList<Card> playerFourCards; ArrayList<Card> tableDealtCards; private Deck deck; public DealCards() { deck = new Deck(); deck.shuffle(); playerOneCards = new ArrayList<>(); playerTwoCards = new ArrayList<>(); playerThreeCards = new ArrayList<>(); playerFourCards = new ArrayList<>(); tableDealtCards = new ArrayList<>(); } public ArrayList<Card> getPlayerOneCards() { return playerOneCards; } public ArrayList<Card> getPlayerTwoCards() { return playerTwoCards; } public ArrayList<Card> getPlayerThreeCards() { return playerThreeCards; } public ArrayList<Card> getPlayerFourCards() { return playerFourCards; } public ArrayList<Card> getTableDealtCards() { return tableDealtCards; } public void dealOpeningCards() { for (int i = 0; i < 4; i++) { playerTwoCards.add(deck.dealCard()); playerThreeCards.add(deck.dealCard()); playerFourCards.add(deck.dealCard()); } for (int i = 0; i < 12; i++) { playerOneCards.add(deck.dealCard()); } } public void dealTableCards() { for (int i = 0; i < 4; i++) { tableDealtCards.add(deck.dealCard()); } } public void dealAllCards() { for (int i = 0; i < 8; i++) { playerTwoCards.add(deck.dealCard()); playerThreeCards.add(deck.dealCard()); playerFourCards.add(deck.dealCard()); } } public static Boolean inValidCardsDealt(ArrayList<Card> cards) { int pointsCounter = 0; int faceCardCounter = 0; for (int i = 0; i < cards.size(); i++) { if (cards.get(i).getSuit() == Card.SPADES) { pointsCounter++; } if (((cards.get(i).getValue() == 9) && (cards.get(i).getSuit() == Card.SPADES)) || (cards.get(i).getValue() == 10) || (cards.get(i).getValue() == Card.JACK) || (cards.get(i).getValue() == Card.QUEEN) || (cards.get(i).getValue() == Card.KING)) { faceCardCounter++; } } if ((pointsCounter == 0) || (faceCardCounter == 0)) { return true; } else return false; } }
UTF-8
Java
2,678
java
DealCards.java
Java
[ { "context": "app.reytum.com.seep.utils.Deck;\n\n/**\n * Created by reytum on 3/9/16.\n */\npublic class DealCards implements ", "end": 196, "score": 0.9995554089546204, "start": 190, "tag": "USERNAME", "value": "reytum" } ]
null
[]
package app.reytum.com.seep.game; import java.io.Serializable; import java.util.ArrayList; import app.reytum.com.seep.utils.Card; import app.reytum.com.seep.utils.Deck; /** * Created by reytum on 3/9/16. */ public class DealCards implements Serializable { ArrayList<Card> playerOneCards; ArrayList<Card> playerTwoCards; ArrayList<Card> playerThreeCards; ArrayList<Card> playerFourCards; ArrayList<Card> tableDealtCards; private Deck deck; public DealCards() { deck = new Deck(); deck.shuffle(); playerOneCards = new ArrayList<>(); playerTwoCards = new ArrayList<>(); playerThreeCards = new ArrayList<>(); playerFourCards = new ArrayList<>(); tableDealtCards = new ArrayList<>(); } public ArrayList<Card> getPlayerOneCards() { return playerOneCards; } public ArrayList<Card> getPlayerTwoCards() { return playerTwoCards; } public ArrayList<Card> getPlayerThreeCards() { return playerThreeCards; } public ArrayList<Card> getPlayerFourCards() { return playerFourCards; } public ArrayList<Card> getTableDealtCards() { return tableDealtCards; } public void dealOpeningCards() { for (int i = 0; i < 4; i++) { playerTwoCards.add(deck.dealCard()); playerThreeCards.add(deck.dealCard()); playerFourCards.add(deck.dealCard()); } for (int i = 0; i < 12; i++) { playerOneCards.add(deck.dealCard()); } } public void dealTableCards() { for (int i = 0; i < 4; i++) { tableDealtCards.add(deck.dealCard()); } } public void dealAllCards() { for (int i = 0; i < 8; i++) { playerTwoCards.add(deck.dealCard()); playerThreeCards.add(deck.dealCard()); playerFourCards.add(deck.dealCard()); } } public static Boolean inValidCardsDealt(ArrayList<Card> cards) { int pointsCounter = 0; int faceCardCounter = 0; for (int i = 0; i < cards.size(); i++) { if (cards.get(i).getSuit() == Card.SPADES) { pointsCounter++; } if (((cards.get(i).getValue() == 9) && (cards.get(i).getSuit() == Card.SPADES)) || (cards.get(i).getValue() == 10) || (cards.get(i).getValue() == Card.JACK) || (cards.get(i).getValue() == Card.QUEEN) || (cards.get(i).getValue() == Card.KING)) { faceCardCounter++; } } if ((pointsCounter == 0) || (faceCardCounter == 0)) { return true; } else return false; } }
2,678
0.571695
0.563854
94
27.489361
30.357004
256
false
false
0
0
0
0
0
0
0.606383
false
false
13
05c3e9a162fa4a9b0ea0004bbb56664c58103472
18,433,999,690,551
bf79c916f639542901a19925d64b5285d0eb7f96
/src/main/java/se/gameoflife/util/InputParser.java
9d3805ce7068f2bd8449f3242185ae2ac77adb1c
[]
no_license
mattiaspalmgren/game-of-life
https://github.com/mattiaspalmgren/game-of-life
baa8e9b65a55ac5baef6eb2b18797a12d27acb30
49de56d57586969be82ad11d95f7465bf39f8227
refs/heads/master
2020-04-18T23:53:32.939000
2019-01-27T16:49:46
2019-01-27T16:49:46
167,832,867
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package se.gameoflife.util; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import se.gameoflife.model.Point; public class InputParser { private static final int SIZE_INDEX = 0; private static final String POINT_SEPARATOR = ","; private static final int X_INDEX = 0; private static final int Y_INDEX = 1; private InputParser() { throw new IllegalStateException("Utility class"); } public static int parseSize(String[] input) { return Integer.parseInt(input[SIZE_INDEX]); } public static List<Point> parsePoints(String[] input) { return Stream.of(input) .skip(1) // Skip size .map(InputParser::parsePoint) .collect(Collectors.toList()); } private static Point parsePoint(String input) { String[] inputArr = input.split(POINT_SEPARATOR); int x = Integer.parseInt(inputArr[X_INDEX]); int y = Integer.parseInt(inputArr[Y_INDEX]); return new Point(x, y); } }
UTF-8
Java
979
java
InputParser.java
Java
[]
null
[]
package se.gameoflife.util; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import se.gameoflife.model.Point; public class InputParser { private static final int SIZE_INDEX = 0; private static final String POINT_SEPARATOR = ","; private static final int X_INDEX = 0; private static final int Y_INDEX = 1; private InputParser() { throw new IllegalStateException("Utility class"); } public static int parseSize(String[] input) { return Integer.parseInt(input[SIZE_INDEX]); } public static List<Point> parsePoints(String[] input) { return Stream.of(input) .skip(1) // Skip size .map(InputParser::parsePoint) .collect(Collectors.toList()); } private static Point parsePoint(String input) { String[] inputArr = input.split(POINT_SEPARATOR); int x = Integer.parseInt(inputArr[X_INDEX]); int y = Integer.parseInt(inputArr[Y_INDEX]); return new Point(x, y); } }
979
0.696629
0.692543
35
26.971428
19.479639
57
false
false
0
0
0
0
0
0
0.514286
false
false
13
0e4a830ac12edbdbd1fbcfdeae222c68d6aa5fd2
8,555,574,914,719
939c6e37846e94cfe4d709c74abefc69fe36cef8
/Core/src/AlgolXXI/Core/Utils/LanguageException.java
c3de5e2bb27b577f4543b79590d5260a359eeb4a
[]
no_license
andreddosantos/portugol
https://github.com/andreddosantos/portugol
5abb7fa970d43c4b02a5c38327278a6da1c23e9d
9e9a7d4e3f36ded61000c449b8b20aaa6c76c9f8
refs/heads/master
2021-01-19T06:26:48.834000
2014-12-15T14:59:57
2014-12-15T14:59:57
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/*****************************************************************************/ /**** Copyright (C) 2006 ****/ /**** Ant�nio Manuel Rodrigues Manso ****/ /**** e-mail: manso@ipt.pt ****/ /**** url : http://orion.ipt.pt/~manso manso@ipt.pt ****/ /**** Instituto Polit�cnico de Tomar ****/ /**** Escola Superior de Tecnologia de Tomar ****/ /*****************************************************************************/ /* * ExceptionCompileError.java * * Created on 12 de Outubro de 2005, 22:32 * */ package AlgolXXI.Core.Utils; /** * Exce��es da linguagem * @author Ant�nio M@nuel Rodrigues M@nso<br> * Departamento de Engenharia Inform�tica<br> * Escola Superior de Tecnologia de Tomar<br> * Intituto Polit�cnico de Tomar<br> * Estrada da Serra<br> * 2350 - Tomar - Portugal<br> * <br> * Web site: http://orion.ipt.pt/~manso/<br> * Email: manso@ipt.pt <br> */ public class LanguageException extends Exception { /** * numero da linha */ public int line ; // numero da linha /** * texto da linha */ public String codeLine; //Linha de c�digo /** * causa da excep��o */ public String error; /** * solu��o da excep��o */ public String solution; /** * Contrutor * @param l n�mero da linha * @param code texto da linha de c�digo * @param e texto do erro * @param s texto da solu��o */ public LanguageException(int l, String code, String e, String s) { super(e); line = l; codeLine = code; error = e; solution = s; } /** * Contrutor * @param e texto do erro * @param s Texto da excep��o */ public LanguageException(String e, String s) { super(e); line = 0; codeLine = ""; error = e; solution = s; } /** * Excepções baseadas no codigo de erro * @param line - linha onde ocorreu o erro para poder destacada * @param CODEID - Código do ERRO */ public LanguageException( int line , int ERROR_ID) { super(); this.line = line; // esta string é lida do ficheiro XML como o erro ERROR_ID error = " NECESSARIO UM FICHEIRO XML COM ERROS"; // esta string é lida do ficheiro XML como o erro ERROR_ID solution = " PARA IR BUSCAR AS EXCEPÇOES"; } /** * Mostra a excep��o */ public void Show(){ System.out.println(GetError()); } /** * devolve uma string com a excep��o * @return texto da excep��o */ public String GetError(){ StringBuffer str = new StringBuffer(); str.append("INSTRU��O:\t" +codeLine + "\n"); str.append("ERRO:\t" + error + "\n"); str.append("SOLU��O:\t" +solution +"\n"); str.append("Linha:\t" +line ); return str.toString(); } /** * return object String * @return excep��o */ public String toString(){ return GetError(); } }
UTF-8
Java
3,334
java
LanguageException.java
Java
[ { "context": " ****/\n/**** Ant�nio Manuel Rodrigues Manso ****/\n/**** ", "end": 200, "score": 0.999870240688324, "start": 170, "tag": "NAME", "value": "Ant�nio Manuel Rodrigues Manso" }, { "context": " ****/\n/**** e-mail: manso@ipt.pt ****/\n", "end": 270, "score": 0.9999194741249084, "start": 258, "tag": "EMAIL", "value": "manso@ipt.pt" }, { "context": "*/\n/**** url : http://orion.ipt.pt/~manso manso@ipt.pt ****/\n/**** Instituto Polit�cnic", "end": 380, "score": 0.9999145865440369, "start": 368, "tag": "EMAIL", "value": "manso@ipt.pt" }, { "context": "ore.Utils;\n/**\n * Exce��es da linguagem\n * @author Ant�nio M@nuel Rodrigues M@nso<br>\n * Departamento de Engenharia Inform�tica", "end": 822, "score": 0.9817994832992554, "start": 796, "tag": "NAME", "value": "Ant�nio M@nuel Rodrigues M" }, { "context": "te: http://orion.ipt.pt/~manso/<br>\n * Email: manso@ipt.pt <br>\n */\npublic class LanguageException extends E", "end": 1095, "score": 0.9999165534973145, "start": 1083, "tag": "EMAIL", "value": "manso@ipt.pt" } ]
null
[]
/*****************************************************************************/ /**** Copyright (C) 2006 ****/ /**** <NAME> ****/ /**** e-mail: <EMAIL> ****/ /**** url : http://orion.ipt.pt/~manso <EMAIL> ****/ /**** Instituto Polit�cnico de Tomar ****/ /**** Escola Superior de Tecnologia de Tomar ****/ /*****************************************************************************/ /* * ExceptionCompileError.java * * Created on 12 de Outubro de 2005, 22:32 * */ package AlgolXXI.Core.Utils; /** * Exce��es da linguagem * @author <NAME>@nso<br> * Departamento de Engenharia Inform�tica<br> * Escola Superior de Tecnologia de Tomar<br> * Intituto Polit�cnico de Tomar<br> * Estrada da Serra<br> * 2350 - Tomar - Portugal<br> * <br> * Web site: http://orion.ipt.pt/~manso/<br> * Email: <EMAIL> <br> */ public class LanguageException extends Exception { /** * numero da linha */ public int line ; // numero da linha /** * texto da linha */ public String codeLine; //Linha de c�digo /** * causa da excep��o */ public String error; /** * solu��o da excep��o */ public String solution; /** * Contrutor * @param l n�mero da linha * @param code texto da linha de c�digo * @param e texto do erro * @param s texto da solu��o */ public LanguageException(int l, String code, String e, String s) { super(e); line = l; codeLine = code; error = e; solution = s; } /** * Contrutor * @param e texto do erro * @param s Texto da excep��o */ public LanguageException(String e, String s) { super(e); line = 0; codeLine = ""; error = e; solution = s; } /** * Excepções baseadas no codigo de erro * @param line - linha onde ocorreu o erro para poder destacada * @param CODEID - Código do ERRO */ public LanguageException( int line , int ERROR_ID) { super(); this.line = line; // esta string é lida do ficheiro XML como o erro ERROR_ID error = " NECESSARIO UM FICHEIRO XML COM ERROS"; // esta string é lida do ficheiro XML como o erro ERROR_ID solution = " PARA IR BUSCAR AS EXCEPÇOES"; } /** * Mostra a excep��o */ public void Show(){ System.out.println(GetError()); } /** * devolve uma string com a excep��o * @return texto da excep��o */ public String GetError(){ StringBuffer str = new StringBuffer(); str.append("INSTRU��O:\t" +codeLine + "\n"); str.append("ERRO:\t" + error + "\n"); str.append("SOLU��O:\t" +solution +"\n"); str.append("Linha:\t" +line ); return str.toString(); } /** * return object String * @return excep��o */ public String toString(){ return GetError(); } }
3,271
0.480699
0.474877
118
26.661016
22.266954
79
false
false
0
0
0
0
0
0
0.279661
false
false
13
4dcadc1d454ad1a8e481b07c5538f14bbc95d801
23,356,032,167,052
b01332bd1b0eac2adb901ce121b0ba481e82a126
/buyB2c/buyb2c-advertPosition/src/main/java/com/ande/buyb2c/advert/service/AdvertPositionServiceImpl.java
86c1ab63fd0d438ea010d8939568772834a39c12
[]
no_license
xlh198593/resin
https://github.com/xlh198593/resin
5783690411bd23723c27f942b9ebaa6b992c4c3b
9632d32feaeeac3792118269552d3ff5ba976b39
refs/heads/master
2022-12-21T00:17:43.048000
2019-07-17T02:13:54
2019-07-17T02:13:54
81,401,320
0
2
null
false
2022-12-16T05:02:24
2017-02-09T02:49:12
2019-07-17T02:20:25
2022-12-16T05:02:21
50,074
0
2
38
Java
false
false
package com.ande.buyb2c.advert.service; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.StringUtils; import com.ande.buyb2c.advert.dao.AdvertPositionDetailMapper; import com.ande.buyb2c.advert.dao.AdvertPositionMapper; import com.ande.buyb2c.advert.entity.AdvertPosition; import com.ande.buyb2c.advert.entity.AdvertPositionDetail; import com.ande.buyb2c.common.util.BaseServiceImpl; import com.ande.buyb2c.common.util.IBaseDao; import com.ande.buyb2c.common.util.SessionUtil; import com.ande.buyb2c.user.entity.AdminUser; /** * @author chengzb * @date 2018年2月2日下午6:24:36 */ @Service public class AdvertPositionServiceImpl extends BaseServiceImpl<AdvertPosition> implements IAdvertPositionService { @Resource private AdvertPositionMapper advertPositionMapper; @Resource private AdvertPositionDetailMapper advertPositionDetailMapper; @Resource private SessionUtil<AdminUser> sessionUtil; @Override protected IBaseDao<AdvertPosition> getMapper() { return advertPositionMapper; } @Override @Transactional public int add(AdvertPosition entity,HttpServletRequest request) throws Exception{ entity.setCreateTime(new Date()); entity.setAdminId(sessionUtil.getAdminUser(request).getAdminId()); advertPositionMapper.insertSelective(entity); List<AdvertPositionDetail> list = entity.getList(); if(list!=null&&list.size()!=0){ for(AdvertPositionDetail ad:list){ ad.setAdvertPositionId(entity.getAdvertPositionId()); } advertPositionDetailMapper.addBatch(list); } return 1; } @Override @Transactional public int updateByPrimaryKeySelective(AdvertPosition entity) throws Exception { advertPositionMapper.updateByPrimaryKeySelective(entity); List<AdvertPositionDetail> list = entity.getList(); StringBuffer buffer=new StringBuffer(); List<AdvertPositionDetail> newList=new ArrayList<AdvertPositionDetail>(); List<AdvertPositionDetail> updateList=new ArrayList<AdvertPositionDetail>(); if(list!=null&&list.size()!=0){ for(AdvertPositionDetail ad:list){ if(ad.getAdvertPositionDetailId()!=null){ if(StringUtils.isEmpty(ad.getImage())){ //删除 buffer.append(ad.getAdvertPositionDetailId()+","); }else{ updateList.add(ad); } }else{ //新增 ad.setAdvertPositionId(entity.getAdvertPositionId()); newList.add(ad); } } } if(newList.size()!=0){ advertPositionDetailMapper.addBatch(newList); } if(updateList.size()!=0){ advertPositionDetailMapper.updateBatch(updateList); } if(buffer.length()!=0){ String str=buffer.toString(); advertPositionDetailMapper.del(str.substring(0,str.length()-1)); } return 1; } }
UTF-8
Java
2,941
java
AdvertPositionServiceImpl.java
Java
[ { "context": "ande.buyb2c.user.entity.AdminUser;\n\n/**\n * @author chengzb\n * @date 2018年2月2日下午6:24:36\n */\n@Service\npublic c", "end": 799, "score": 0.9996506571769714, "start": 792, "tag": "USERNAME", "value": "chengzb" } ]
null
[]
package com.ande.buyb2c.advert.service; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.StringUtils; import com.ande.buyb2c.advert.dao.AdvertPositionDetailMapper; import com.ande.buyb2c.advert.dao.AdvertPositionMapper; import com.ande.buyb2c.advert.entity.AdvertPosition; import com.ande.buyb2c.advert.entity.AdvertPositionDetail; import com.ande.buyb2c.common.util.BaseServiceImpl; import com.ande.buyb2c.common.util.IBaseDao; import com.ande.buyb2c.common.util.SessionUtil; import com.ande.buyb2c.user.entity.AdminUser; /** * @author chengzb * @date 2018年2月2日下午6:24:36 */ @Service public class AdvertPositionServiceImpl extends BaseServiceImpl<AdvertPosition> implements IAdvertPositionService { @Resource private AdvertPositionMapper advertPositionMapper; @Resource private AdvertPositionDetailMapper advertPositionDetailMapper; @Resource private SessionUtil<AdminUser> sessionUtil; @Override protected IBaseDao<AdvertPosition> getMapper() { return advertPositionMapper; } @Override @Transactional public int add(AdvertPosition entity,HttpServletRequest request) throws Exception{ entity.setCreateTime(new Date()); entity.setAdminId(sessionUtil.getAdminUser(request).getAdminId()); advertPositionMapper.insertSelective(entity); List<AdvertPositionDetail> list = entity.getList(); if(list!=null&&list.size()!=0){ for(AdvertPositionDetail ad:list){ ad.setAdvertPositionId(entity.getAdvertPositionId()); } advertPositionDetailMapper.addBatch(list); } return 1; } @Override @Transactional public int updateByPrimaryKeySelective(AdvertPosition entity) throws Exception { advertPositionMapper.updateByPrimaryKeySelective(entity); List<AdvertPositionDetail> list = entity.getList(); StringBuffer buffer=new StringBuffer(); List<AdvertPositionDetail> newList=new ArrayList<AdvertPositionDetail>(); List<AdvertPositionDetail> updateList=new ArrayList<AdvertPositionDetail>(); if(list!=null&&list.size()!=0){ for(AdvertPositionDetail ad:list){ if(ad.getAdvertPositionDetailId()!=null){ if(StringUtils.isEmpty(ad.getImage())){ //删除 buffer.append(ad.getAdvertPositionDetailId()+","); }else{ updateList.add(ad); } }else{ //新增 ad.setAdvertPositionId(entity.getAdvertPositionId()); newList.add(ad); } } } if(newList.size()!=0){ advertPositionDetailMapper.addBatch(newList); } if(updateList.size()!=0){ advertPositionDetailMapper.updateBatch(updateList); } if(buffer.length()!=0){ String str=buffer.toString(); advertPositionDetailMapper.del(str.substring(0,str.length()-1)); } return 1; } }
2,941
0.76531
0.755388
91
31.120878
23.544596
83
false
false
0
0
0
0
0
0
2.395604
false
false
13
02740fbae85946b9d2e07b67db981d495a62ed8a
16,449,724,762,804
0885745cfbd8b8d98f3c1367cf8b47ddc9ea851c
/src/Solution/RemoveDuplicatesFromSortedList.java
9ea5a30c09f788542303c6721449adb1de70e325
[]
no_license
zhangtemplar/LeetCode
https://github.com/zhangtemplar/LeetCode
07e03d6b713bb56c9a45ce8b0dfcdd3f8602b0db
c1c672a6c0abaacf0fae6aa3e53925355a62d1cb
refs/heads/master
2021-01-10T21:14:11.139000
2014-03-03T22:24:04
2014-03-03T22:24:04
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { public ListNode deleteDuplicates(ListNode head) { // Note: The Solution object is instantiated only once and is reused by each test case. if (head==null || head.next==null) { return head; } ListNode node=head; while(node!=null && node.next!=null) { // we find an duplicate if (node.val==node.next.val) { // remove the next element node.next=node.next.next; } else { // otherwise continue; node=node.next; } } return head; } }
UTF-8
Java
884
java
RemoveDuplicatesFromSortedList.java
Java
[]
null
[]
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { public ListNode deleteDuplicates(ListNode head) { // Note: The Solution object is instantiated only once and is reused by each test case. if (head==null || head.next==null) { return head; } ListNode node=head; while(node!=null && node.next!=null) { // we find an duplicate if (node.val==node.next.val) { // remove the next element node.next=node.next.next; } else { // otherwise continue; node=node.next; } } return head; } }
884
0.466063
0.466063
36
23.555555
18.276342
95
false
false
0
0
0
0
0
0
0.333333
false
false
13
2618c7c80acaa8fcd1ed1e7b48ae460e56093c96
29,300,266,908,017
79ca915d2908307cbd168520b3f42e6f575c267b
/library/base/src/main/java/com/aihui/lib/base/ui/BaseActivity.java
4abc82586278837f8c2e82189bbdf7aba65dca01
[]
no_license
chnng/learnGit
https://github.com/chnng/learnGit
f47cf3d54e4fe83da609891e1b7a29f67644b660
c7622f441c134dcdb163d64c01dfa2dda8737fc7
refs/heads/master
2021-01-11T04:46:33.977000
2019-04-28T01:37:22
2019-04-28T01:37:22
71,128,457
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.aihui.lib.base.ui; import android.content.res.Configuration; import android.os.Bundle; import android.view.Window; import android.view.WindowManager; import com.aihui.lib.base.api.eventbus.EventMessage; import com.aihui.lib.base.api.eventbus.EventTag; import com.aihui.lib.base.app.IBaseComponent; import com.aihui.lib.base.ui.patch.AndroidBug5497Workaround; import com.aihui.lib.base.util.ApplicationUtils; import com.aihui.lib.base.util.SystemUIUtils; import com.aihui.lib.base.util.ToastUtils; import com.trello.rxlifecycle3.components.support.RxAppCompatActivity; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import org.greenrobot.eventbus.ThreadMode; import java.util.List; import androidx.annotation.ColorRes; import androidx.annotation.LayoutRes; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import butterknife.ButterKnife; import butterknife.Unbinder; import pub.devrel.easypermissions.EasyPermissions; /** * Created by 路传涛 on 2017/5/24. */ public abstract class BaseActivity extends RxAppCompatActivity implements IBaseComponent, EasyPermissions.PermissionCallbacks { private Unbinder mUnbinder; private boolean mResumed; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); int contentViewId = getContentViewId(); if (!setUniqueContent(contentViewId)) { setContentView(contentViewId); } //setStatusBarTint(); registerApi(); initData(); initEvent(); if (SystemUIUtils.navigationBarHide) { AndroidBug5497Workaround.assistActivity(this); } } @Override protected void onDestroy() { super.onDestroy(); unregisterApi(); } @Override protected void onResume() { super.onResume(); hideNavigationBar(); mResumed = true; } @Override protected void onPause() { super.onPause(); mResumed = false; } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); switch (newConfig.orientation) { case Configuration.ORIENTATION_PORTRAIT: if (!shouldHideNavigationBar()) { SystemUIUtils.showNavigationBar(getWindow()); } break; case Configuration.ORIENTATION_LANDSCAPE: hideNavigationBar(); break; } } @Override public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); if (hasFocus) { hideNavigationBar(); } } /** * 绑定api */ private void registerApi() { EventBus.getDefault().register(this); mUnbinder = ButterKnife.bind(this); } /** * 解绑api */ private void unregisterApi() { EventBus.getDefault().unregister(this); mUnbinder.unbind(); } protected boolean isActivityResumed() { return mResumed; } /** * 注册EventBus的Activity 必须实现 EventBus其中的一个方法 * 这里实现一个EventBus中的方法,不需要的子类可以不必再实现 * * @param event */ @Subscribe(threadMode = ThreadMode.MAIN) public void onMessage(EventMessage event) { switch (event.key) { case EventTag.KEYBOARD_HIDDEN: hideNavigationBar(); break; default: break; } } // /** // * 设置状态栏的颜色 // */ // private void setStatusBarTint() { // if (ApplicationUtils.isKitkat()) { // setTranslucentStatus(true); // } // // SystemBarTintManager tintManager = new SystemBarTintManager(this); // tintManager.setStatusBarTintEnabled(true); // tintManager.setStatusBarTintResource(R.color.colorPrimary); // } // // /** // * 设置状态栏颜色透明 // * // * @param on // */ // @TargetApi(19) // private void setTranslucentStatus(boolean on) { // Window win = getWindow(); // WindowManager.LayoutParams winParams = win.getAttributes(); // final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS; // if (on) { // winParams.flags |= bits; // } else { // winParams.flags &= ~bits; // } // win.setAttributes(winParams); // } /** * 隐藏虚拟按键,并且全屏 */ public void hideNavigationBar() { if (shouldHideNavigationBar()) { // 全屏主题隐藏导航栏 SystemUIUtils.hideNavigationBar(this); } } private boolean shouldHideNavigationBar() { return SystemUIUtils.navigationBarHide && (((getWindow().getAttributes().flags & WindowManager.LayoutParams.FLAG_FULLSCREEN) != 0) || getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE); } private long exitTime; /** * 连续按两次返回键退出程序 */ protected void exitBy2Click() { if ((System.currentTimeMillis() - exitTime) > 2000) { ToastUtils.toast("再按一次退出程序"); exitTime = System.currentTimeMillis(); } else { finish(); } } protected boolean setUniqueContent(@LayoutRes int contentViewId) { return contentViewId == 0; } protected void setStatusBarColor(@ColorRes int colorId) { if (ApplicationUtils.isLollipop()) { Window window = getWindow(); window.setStatusBarColor(getResources().getColor(colorId)); } } @Override public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) { } @Override public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) { } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); // Forward results to EasyPermissions EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this); } }
UTF-8
Java
6,658
java
BaseActivity.java
Java
[ { "context": "ermissions.EasyPermissions;\r\n\r\n/**\r\n * Created by 路传涛 on 2017/5/24.\r\n */\r\n\r\npublic abstract class BaseA", "end": 1047, "score": 0.9988659620285034, "start": 1044, "tag": "NAME", "value": "路传涛" } ]
null
[]
package com.aihui.lib.base.ui; import android.content.res.Configuration; import android.os.Bundle; import android.view.Window; import android.view.WindowManager; import com.aihui.lib.base.api.eventbus.EventMessage; import com.aihui.lib.base.api.eventbus.EventTag; import com.aihui.lib.base.app.IBaseComponent; import com.aihui.lib.base.ui.patch.AndroidBug5497Workaround; import com.aihui.lib.base.util.ApplicationUtils; import com.aihui.lib.base.util.SystemUIUtils; import com.aihui.lib.base.util.ToastUtils; import com.trello.rxlifecycle3.components.support.RxAppCompatActivity; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import org.greenrobot.eventbus.ThreadMode; import java.util.List; import androidx.annotation.ColorRes; import androidx.annotation.LayoutRes; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import butterknife.ButterKnife; import butterknife.Unbinder; import pub.devrel.easypermissions.EasyPermissions; /** * Created by 路传涛 on 2017/5/24. */ public abstract class BaseActivity extends RxAppCompatActivity implements IBaseComponent, EasyPermissions.PermissionCallbacks { private Unbinder mUnbinder; private boolean mResumed; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); int contentViewId = getContentViewId(); if (!setUniqueContent(contentViewId)) { setContentView(contentViewId); } //setStatusBarTint(); registerApi(); initData(); initEvent(); if (SystemUIUtils.navigationBarHide) { AndroidBug5497Workaround.assistActivity(this); } } @Override protected void onDestroy() { super.onDestroy(); unregisterApi(); } @Override protected void onResume() { super.onResume(); hideNavigationBar(); mResumed = true; } @Override protected void onPause() { super.onPause(); mResumed = false; } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); switch (newConfig.orientation) { case Configuration.ORIENTATION_PORTRAIT: if (!shouldHideNavigationBar()) { SystemUIUtils.showNavigationBar(getWindow()); } break; case Configuration.ORIENTATION_LANDSCAPE: hideNavigationBar(); break; } } @Override public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); if (hasFocus) { hideNavigationBar(); } } /** * 绑定api */ private void registerApi() { EventBus.getDefault().register(this); mUnbinder = ButterKnife.bind(this); } /** * 解绑api */ private void unregisterApi() { EventBus.getDefault().unregister(this); mUnbinder.unbind(); } protected boolean isActivityResumed() { return mResumed; } /** * 注册EventBus的Activity 必须实现 EventBus其中的一个方法 * 这里实现一个EventBus中的方法,不需要的子类可以不必再实现 * * @param event */ @Subscribe(threadMode = ThreadMode.MAIN) public void onMessage(EventMessage event) { switch (event.key) { case EventTag.KEYBOARD_HIDDEN: hideNavigationBar(); break; default: break; } } // /** // * 设置状态栏的颜色 // */ // private void setStatusBarTint() { // if (ApplicationUtils.isKitkat()) { // setTranslucentStatus(true); // } // // SystemBarTintManager tintManager = new SystemBarTintManager(this); // tintManager.setStatusBarTintEnabled(true); // tintManager.setStatusBarTintResource(R.color.colorPrimary); // } // // /** // * 设置状态栏颜色透明 // * // * @param on // */ // @TargetApi(19) // private void setTranslucentStatus(boolean on) { // Window win = getWindow(); // WindowManager.LayoutParams winParams = win.getAttributes(); // final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS; // if (on) { // winParams.flags |= bits; // } else { // winParams.flags &= ~bits; // } // win.setAttributes(winParams); // } /** * 隐藏虚拟按键,并且全屏 */ public void hideNavigationBar() { if (shouldHideNavigationBar()) { // 全屏主题隐藏导航栏 SystemUIUtils.hideNavigationBar(this); } } private boolean shouldHideNavigationBar() { return SystemUIUtils.navigationBarHide && (((getWindow().getAttributes().flags & WindowManager.LayoutParams.FLAG_FULLSCREEN) != 0) || getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE); } private long exitTime; /** * 连续按两次返回键退出程序 */ protected void exitBy2Click() { if ((System.currentTimeMillis() - exitTime) > 2000) { ToastUtils.toast("再按一次退出程序"); exitTime = System.currentTimeMillis(); } else { finish(); } } protected boolean setUniqueContent(@LayoutRes int contentViewId) { return contentViewId == 0; } protected void setStatusBarColor(@ColorRes int colorId) { if (ApplicationUtils.isLollipop()) { Window window = getWindow(); window.setStatusBarColor(getResources().getColor(colorId)); } } @Override public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) { } @Override public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) { } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); // Forward results to EasyPermissions EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this); } }
6,658
0.612179
0.608305
222
27.072073
23.762985
121
false
false
0
0
0
0
0
0
0.405405
false
false
13
b3628197f281b16f7def8dfc75ae9589e18bbda8
6,468,220,774,827
d767871ae60c5cb1532c6c36cb1878add77983ff
/app/src/main/java/com/ccq/bangdream/setting/SettingPreference.java
02f1f1ea6bdbafac54464abbb9416e91e3324d42
[ "Apache-2.0" ]
permissive
minatoyukina/BangDream
https://github.com/minatoyukina/BangDream
0ddaf67b7fa70f4a9269d59776a752c9630a4760
ff5c28cdd2dc993681e3e75fb2e5a3db82e9817c
refs/heads/master
2020-04-28T03:39:06.361000
2019-06-12T15:53:27
2019-06-12T15:53:27
174,945,581
3
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ccq.bangdream.setting; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.net.Uri; import android.os.Bundle; import android.preference.Preference; import android.preference.PreferenceFragment; import android.support.annotation.Nullable; import android.support.v7.app.AlertDialog; import android.util.Log; import android.view.View; import com.ccq.bangdream.R; import com.ccq.bangdream.util.CheckUpdateUtil; import com.ccq.bangdream.util.MyApplication; import java.io.File; import java.util.Objects; public class SettingPreference extends PreferenceFragment { private File file; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); getPreferenceManager(); addPreferencesFromResource(R.xml.setting_preference); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); final Preference clearCache = findPreference("clear_cache"); file = Objects.requireNonNull(MyApplication.getContext().getCacheDir()); long totalSpace = getFolderSize(file); Log.d("file", file.toString()); clearCache.setSummary("已使用缓存大小: " + (float) totalSpace / (1024 * 1024) + "M"); clearCache.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { delete(file); AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle("提示").setMessage("\n清理完成").setPositiveButton("确定", null).show(); clearCache.setSummary("已使用缓存大小: 0M"); return true; } private void delete(File parent) { if (parent.isDirectory()) { File[] files = parent.listFiles(); for (File child : files) { delete(child); } } else { boolean delete = parent.delete(); Log.d("delete", String.valueOf(delete)); } } }); Preference update = findPreference("update"); PackageManager manager = MyApplication.getContext().getPackageManager(); try { PackageInfo packageInfo = manager.getPackageInfo(MyApplication.getContext().getPackageName(), 0); String versionName = packageInfo.versionName; update.setSummary("当前版本: " + versionName); } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } update.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity()); dialog.setTitle("检查更新"); boolean flag = CheckUpdateUtil.checkUpdate(); if (flag) { dialog.setMessage("\n有新版本"); dialog.setPositiveButton("去更新", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://github.com/minatoyukina/BangDream/releases")); startActivity(intent); } }); dialog.setNegativeButton("忽略", null); dialog.show(); } else { dialog.setPositiveButton("确定", null); dialog.setMessage("\n已是最新版本").show(); } return true; } }); Preference aboutUs = findPreference("contract_us"); aboutUs.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { Intent intent = new Intent(Intent.ACTION_SENDTO); intent.setData(Uri.parse("mailto:uzi9mm7@gmail.com")); startActivity(intent); return true; } }); Preference licence = findPreference("licence"); licence.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { String[] items = {"Jsoup", "GreenDao", "Glide", "glide-transformations", "sqlite", "MPAndroidChart"}; AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity()); dialog.setTitle("开源库"); dialog.setItems(items, null); dialog.setPositiveButton("确定", null); dialog.show(); return true; } }); Preference specialLinks = findPreference("special_links"); specialLinks.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity()); String[] items = { "bandori.party", "谱面保管所", "官方twitter", "日服下载更新"}; dialog.setTitle("special links").setItems(items, new DialogInterface.OnClickListener() { Intent intent; @Override public void onClick(DialogInterface dialogInterface, int i) { switch (i) { case 0: intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://bandori.party")); break; case 1: intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.sdvx.in/bandri/sort/def.htm")); break; case 2: intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://twitter.com/bang_dream_gbp")); break; case 3: intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://apps.qoo-app.com/app/4847")); break; default: break; } startActivity(intent); } }).setPositiveButton("确定", null).show(); return true; } }); // Preference donate = findPreference("donate"); // donate.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { // @Override // public boolean onPreferenceClick(Preference preference) { // return false; // } // }); } /** * 获取文件夹大小 * * @param file File实例 * @return long */ private static long getFolderSize(File file) { long size = 0; try { java.io.File[] fileList = file.listFiles(); for (File aFileList : fileList) { if (aFileList.isDirectory()) { size = size + getFolderSize(aFileList); } else { size = size + aFileList.length(); } } } catch (Exception e) { e.printStackTrace(); } return size; } }
UTF-8
Java
8,108
java
SettingPreference.java
Java
[ { "context": "Intent.ACTION_VIEW, Uri.parse(\"https://github.com/minatoyukina/BangDream/releases\"));\n ", "end": 3598, "score": 0.9996392130851746, "start": 3586, "tag": "USERNAME", "value": "minatoyukina" }, { "context": "\n intent.setData(Uri.parse(\"mailto:uzi9mm7@gmail.com\"));\n startActivity(intent);\n ", "end": 4405, "score": 0.9999117255210876, "start": 4388, "tag": "EMAIL", "value": "uzi9mm7@gmail.com" }, { "context": "Intent.ACTION_VIEW, Uri.parse(\"http://twitter.com/bang_dream_gbp\"));\n break;\n ", "end": 6520, "score": 0.997326135635376, "start": 6506, "tag": "USERNAME", "value": "bang_dream_gbp" } ]
null
[]
package com.ccq.bangdream.setting; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.net.Uri; import android.os.Bundle; import android.preference.Preference; import android.preference.PreferenceFragment; import android.support.annotation.Nullable; import android.support.v7.app.AlertDialog; import android.util.Log; import android.view.View; import com.ccq.bangdream.R; import com.ccq.bangdream.util.CheckUpdateUtil; import com.ccq.bangdream.util.MyApplication; import java.io.File; import java.util.Objects; public class SettingPreference extends PreferenceFragment { private File file; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); getPreferenceManager(); addPreferencesFromResource(R.xml.setting_preference); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); final Preference clearCache = findPreference("clear_cache"); file = Objects.requireNonNull(MyApplication.getContext().getCacheDir()); long totalSpace = getFolderSize(file); Log.d("file", file.toString()); clearCache.setSummary("已使用缓存大小: " + (float) totalSpace / (1024 * 1024) + "M"); clearCache.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { delete(file); AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle("提示").setMessage("\n清理完成").setPositiveButton("确定", null).show(); clearCache.setSummary("已使用缓存大小: 0M"); return true; } private void delete(File parent) { if (parent.isDirectory()) { File[] files = parent.listFiles(); for (File child : files) { delete(child); } } else { boolean delete = parent.delete(); Log.d("delete", String.valueOf(delete)); } } }); Preference update = findPreference("update"); PackageManager manager = MyApplication.getContext().getPackageManager(); try { PackageInfo packageInfo = manager.getPackageInfo(MyApplication.getContext().getPackageName(), 0); String versionName = packageInfo.versionName; update.setSummary("当前版本: " + versionName); } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } update.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity()); dialog.setTitle("检查更新"); boolean flag = CheckUpdateUtil.checkUpdate(); if (flag) { dialog.setMessage("\n有新版本"); dialog.setPositiveButton("去更新", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://github.com/minatoyukina/BangDream/releases")); startActivity(intent); } }); dialog.setNegativeButton("忽略", null); dialog.show(); } else { dialog.setPositiveButton("确定", null); dialog.setMessage("\n已是最新版本").show(); } return true; } }); Preference aboutUs = findPreference("contract_us"); aboutUs.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { Intent intent = new Intent(Intent.ACTION_SENDTO); intent.setData(Uri.parse("mailto:<EMAIL>")); startActivity(intent); return true; } }); Preference licence = findPreference("licence"); licence.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { String[] items = {"Jsoup", "GreenDao", "Glide", "glide-transformations", "sqlite", "MPAndroidChart"}; AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity()); dialog.setTitle("开源库"); dialog.setItems(items, null); dialog.setPositiveButton("确定", null); dialog.show(); return true; } }); Preference specialLinks = findPreference("special_links"); specialLinks.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity()); String[] items = { "bandori.party", "谱面保管所", "官方twitter", "日服下载更新"}; dialog.setTitle("special links").setItems(items, new DialogInterface.OnClickListener() { Intent intent; @Override public void onClick(DialogInterface dialogInterface, int i) { switch (i) { case 0: intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://bandori.party")); break; case 1: intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.sdvx.in/bandri/sort/def.htm")); break; case 2: intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://twitter.com/bang_dream_gbp")); break; case 3: intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://apps.qoo-app.com/app/4847")); break; default: break; } startActivity(intent); } }).setPositiveButton("确定", null).show(); return true; } }); // Preference donate = findPreference("donate"); // donate.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { // @Override // public boolean onPreferenceClick(Preference preference) { // return false; // } // }); } /** * 获取文件夹大小 * * @param file File实例 * @return long */ private static long getFolderSize(File file) { long size = 0; try { java.io.File[] fileList = file.listFiles(); for (File aFileList : fileList) { if (aFileList.isDirectory()) { size = size + getFolderSize(aFileList); } else { size = size + aFileList.length(); } } } catch (Exception e) { e.printStackTrace(); } return size; } }
8,098
0.543866
0.541101
200
38.779999
29.618603
140
false
false
0
0
0
0
0
0
0.63
false
false
13
f7e7a0be38d82a7529e7a07fe61fb2ae346ee458
29,575,144,818,804
dfa7cd26747e7ae66a9aaa463f3aab5fe878997f
/EasemobPlug/app/src/main/java/com/apkplug/easemobplug/Processores/EaseAddFriend.java
ac8b4d528c170cf3e33e2df7d32535be78538247
[]
no_license
fjg1989/SDKDemo
https://github.com/fjg1989/SDKDemo
6fb18a406d5ff0c633d2553b2804e6c474659067
6d326772b3c28bc7f8fd3f62840f43edf7d3a2fd
refs/heads/master
2021-01-10T22:15:07.893000
2016-09-28T02:05:31
2016-09-28T02:05:31
70,330,417
1
0
null
true
2016-10-08T12:42:29
2016-10-08T12:42:29
2016-09-29T08:33:18
2016-09-28T02:08:40
131,878
0
0
0
null
null
null
package com.apkplug.easemobplug.Processores; import com.hyphenate.chat.EMClient; import com.hyphenate.exceptions.HyphenateException; import org.osgi.framework.BundleContext; import java.net.URI; import java.util.HashMap; /** * Created by qinfeng on 2016/7/22. */ public class EaseAddFriend extends BaseProcessor { public EaseAddFriend(BundleContext context) { super(context); } @Override public void Receive(URI uri, HashMap<String, Object> hashMap) { String username = (String) hashMap.get("UserName"); try { EMClient.getInstance().contactManager().addContact(username, "you have to accept"); dispatchAgent.reply(getMsgId(),true,"success"); } catch (HyphenateException e) { dispatchAgent.reply(getMsgId(),false,e); } } }
UTF-8
Java
825
java
EaseAddFriend.java
Java
[ { "context": ".URI;\nimport java.util.HashMap;\n\n/**\n * Created by qinfeng on 2016/7/22.\n */\npublic class EaseAddFriend exte", "end": 250, "score": 0.9996180534362793, "start": 243, "tag": "USERNAME", "value": "qinfeng" }, { "context": "{\n String username = (String) hashMap.get(\"UserName\");\n try {\n EMClient.getInstance", "end": 539, "score": 0.987463653087616, "start": 531, "tag": "USERNAME", "value": "UserName" } ]
null
[]
package com.apkplug.easemobplug.Processores; import com.hyphenate.chat.EMClient; import com.hyphenate.exceptions.HyphenateException; import org.osgi.framework.BundleContext; import java.net.URI; import java.util.HashMap; /** * Created by qinfeng on 2016/7/22. */ public class EaseAddFriend extends BaseProcessor { public EaseAddFriend(BundleContext context) { super(context); } @Override public void Receive(URI uri, HashMap<String, Object> hashMap) { String username = (String) hashMap.get("UserName"); try { EMClient.getInstance().contactManager().addContact(username, "you have to accept"); dispatchAgent.reply(getMsgId(),true,"success"); } catch (HyphenateException e) { dispatchAgent.reply(getMsgId(),false,e); } } }
825
0.683636
0.675152
29
27.448277
25.230778
95
false
false
0
0
0
0
0
0
0.62069
false
false
13
c24d2964d82d1271f3776f104f549d55d71592d0
29,575,144,817,866
f1184317d95906df6953dc40650e1baa7a647b8c
/Spring-BatchService-Complete/src/main/java/br/com/batch/process/PersonItemWriter.java
13df108a31289e71c38ef83eda62a33f11184352
[]
no_license
halyssonnobrega/Spring-BatchService
https://github.com/halyssonnobrega/Spring-BatchService
bc96902cf4ce9a858c9c9b6b90a13cd758018038
cbde8b45f400ef7c185a7f4cf952d1e2b358c187
refs/heads/master
2021-07-14T19:48:53.645000
2017-10-18T18:51:29
2017-10-18T18:51:29
106,493,658
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package br.com.batch.process; import java.util.List; import org.assertj.core.util.Files; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.batch.core.annotation.AfterWrite; import org.springframework.batch.core.annotation.BeforeWrite; import org.springframework.batch.item.ExecutionContext; import org.springframework.batch.item.ItemWriter; import org.springframework.batch.item.file.FlatFileItemWriter; import org.springframework.batch.item.file.transform.PassThroughLineAggregator; import org.springframework.core.io.FileSystemResource; import br.com.batch.entity.Person; public class PersonItemWriter implements ItemWriter<Person> { private static final Logger log = LoggerFactory.getLogger(PersonItemWriter.class); private FlatFileItemWriter<Person> writer; private FileSystemResource resource; public PersonItemWriter() { this.writer = new FlatFileItemWriter<>(); this.resource = new FileSystemResource("target/output-teste.txt"); } @BeforeWrite private void deleteFile() { Files.delete(resource.getFile()); } @Override public void write(List<? extends Person> items) throws Exception { log.info("BATCH JOB WRITER"); this.writer.setResource(new FileSystemResource(resource.getFile())); this.writer.setLineAggregator(new PassThroughLineAggregator<>()); this.writer.afterPropertiesSet(); this.writer.open(new ExecutionContext()); this.writer.write(items); } @AfterWrite private void close() { this.writer.close(); } }
UTF-8
Java
1,551
java
PersonItemWriter.java
Java
[]
null
[]
package br.com.batch.process; import java.util.List; import org.assertj.core.util.Files; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.batch.core.annotation.AfterWrite; import org.springframework.batch.core.annotation.BeforeWrite; import org.springframework.batch.item.ExecutionContext; import org.springframework.batch.item.ItemWriter; import org.springframework.batch.item.file.FlatFileItemWriter; import org.springframework.batch.item.file.transform.PassThroughLineAggregator; import org.springframework.core.io.FileSystemResource; import br.com.batch.entity.Person; public class PersonItemWriter implements ItemWriter<Person> { private static final Logger log = LoggerFactory.getLogger(PersonItemWriter.class); private FlatFileItemWriter<Person> writer; private FileSystemResource resource; public PersonItemWriter() { this.writer = new FlatFileItemWriter<>(); this.resource = new FileSystemResource("target/output-teste.txt"); } @BeforeWrite private void deleteFile() { Files.delete(resource.getFile()); } @Override public void write(List<? extends Person> items) throws Exception { log.info("BATCH JOB WRITER"); this.writer.setResource(new FileSystemResource(resource.getFile())); this.writer.setLineAggregator(new PassThroughLineAggregator<>()); this.writer.afterPropertiesSet(); this.writer.open(new ExecutionContext()); this.writer.write(items); } @AfterWrite private void close() { this.writer.close(); } }
1,551
0.767892
0.766602
50
29.02
25.323105
83
false
false
0
0
0
0
0
0
1.22
false
false
13
29401e704fabc40ed83516c68db3eff4f12af51a
18,743,237,299,704
5f7215685967bfcbfc9ce38da1645348f35755cc
/Ch12_Concurrency/src/main/java/ekel/generators/EvenGenerator.java
2a362dd8c34973a3f7dc315cf3a9027b64881267
[]
no_license
tifoha/OCP
https://github.com/tifoha/OCP
7a3a25e1c4de9790456c9aaaeedccd42e23a549d
1444f704c637b5a50bcd687df012721ea920c00a
refs/heads/master
2020-12-25T16:55:43.311000
2016-08-22T16:44:21
2016-08-22T16:44:21
41,903,849
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package ekel.generators; import ekel.utils.IntGenerator; public class EvenGenerator extends IntGenerator { private int value; public EvenGenerator() { this(0); } public EvenGenerator(int value) { this.value = value; } @Override public int next() { value++; Thread.yield(); value++; return value; } }
UTF-8
Java
388
java
EvenGenerator.java
Java
[]
null
[]
package ekel.generators; import ekel.utils.IntGenerator; public class EvenGenerator extends IntGenerator { private int value; public EvenGenerator() { this(0); } public EvenGenerator(int value) { this.value = value; } @Override public int next() { value++; Thread.yield(); value++; return value; } }
388
0.57732
0.574742
25
14.52
13.629732
50
false
false
0
0
0
0
0
0
0.36
false
false
13
945a11dc9ef7d3e2fb74d993cfb6d3dcb4a96557
2,929,167,722,097
101dc34da0c8f65f4d8d702be3cef7bc90764f72
/src/main/java/com/annonce/app/controller/FormationController.java
91829622469d8a99a66742f7390ff1ce99cf27ae
[]
no_license
badrhsn/annonceformation
https://github.com/badrhsn/annonceformation
d7d698655db02c35ca6ed36adf9a590c25829939
6722cd542c74ca74402de33e6430a6588a1edc1d
refs/heads/master
2022-05-24T10:42:58.443000
2020-05-03T21:59:45
2020-05-03T21:59:45
261,029,494
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.annonce.app.controller; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.security.Principal; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import javax.servlet.http.HttpSession; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import com.annonce.app.model.Formation; import com.annonce.app.model.User; import com.annonce.app.repository.UserRepository; import com.annonce.app.service.FormationService; import com.annonce.app.service.UserService; @Controller @RequestMapping("/formateur") public class FormationController { @Autowired private UserService userService; @Autowired private FormationService formationService; @Autowired private UserRepository userRepository; @GetMapping("/dashboard") public String showDashboard(Model model, HttpSession session) { User user = userService.findByEmail(session.getAttribute("nom").toString()); model.addAttribute("user",user); return "/formateur/dashboard"; } @GetMapping("/addformation") public String showaddformation(Model model,HttpSession session) { String email = session.getAttribute("nom").toString(); model.addAttribute("formation",new Formation()); return "/formateur/addformation"; } @PostMapping("/addformation") public String addFormation(@RequestParam(name="title", defaultValue=" ",required=false) String title, @RequestParam(name="subtitle", defaultValue=" ",required=false) String subtitle, @RequestParam(name="price", defaultValue=" ",required=false) String price, @RequestParam(name="language", defaultValue=" ",required=false) String language, @RequestParam(name="date_depart", defaultValue=" ",required=false) String date_depart, @RequestParam(name="limit_student", defaultValue=" ",required=false) String limit_student, @RequestParam(name="categorie", defaultValue=" ",required=false) String categorie, @RequestParam(name="duration", defaultValue=" ",required=false) String duration, @RequestParam(name="place", defaultValue=" ",required=false) String place, @RequestParam(name="description", defaultValue=" ",required=false) String description, Model model,HttpSession httpSession, @RequestParam(name="img",required = false) MultipartFile imgUrl) throws IOException { System.out.println("badr2"); model.addAttribute("success",true); Formation formation = new Formation(); DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd"); Date date = new Date(); formation.setCreation_date(dateFormat.format(date)); formation.setCurrent_student("0"); formation.setActive(1); formation.setCategorie(categorie); formation.setDate_depart(date_depart); formation.setDescription(description); formation.setDuration(duration); formation.setLanguage(language); formation.setPlace(place); formation.setLimit_student(limit_student); formation.setTitle(title); formation.setSubtitle(subtitle); formation.setPrice(price); String folder = System.getProperty("user.dir")+"\\src\\main\\resources\\static\\formationimg\\"; System.out.print(folder); byte[] bytes = imgUrl.getBytes(); Path path = Paths.get(folder+imgUrl.getOriginalFilename()); Files.write(path, bytes); formation.setImg("/photos/"+imgUrl.getOriginalFilename()); formationService.addFormation(formation, userService.findOne(httpSession.getAttribute("nom").toString())); return "/formateur/addformation"; } @GetMapping("/listformation") public String showListFormation(String formation_number, Model model, HttpSession session) { String email = session.getAttribute("nom").toString(); model.addAttribute("formations",formationService.findUserFormation(userService.findOne(email))); User user = userService.findByEmail(session.getAttribute("nom").toString()); model.addAttribute("user",user); return "/formateur/listformation"; } @PostMapping("/listformation/{id}") public String deleteFormtion(@PathVariable String id) { formationService.deleteFormation(Long.parseLong(id)); return "redirect:/formateur/listformation"; } @GetMapping("/updateformation") public String showUpdatePage(String formation_id,Model model, Principal principal,HttpSession httpSession) { String email = httpSession.getAttribute("nom").toString(); httpSession.setAttribute("formation_id", formation_id); model.addAttribute("newformation", new Formation()); model.addAttribute("formation",formationService.findFormation(Long.parseLong(formation_id))); return "/formateur/updateformation"; } @PostMapping("/updateformation") public String updateFormation(@RequestParam(name="title", defaultValue=" ",required=false) String title, @RequestParam(name="subtitle", defaultValue=" ",required=false) String subtitle, @RequestParam(name="price", defaultValue=" ",required=false) String price, @RequestParam(name="language", defaultValue=" ",required=false) String language, @RequestParam(name="date_depart", defaultValue=" ",required=false) String date_depart, @RequestParam(name="limit_student", defaultValue=" ",required=false) String limit_student, @RequestParam(name="categorie", defaultValue=" ",required=false) String categorie, @RequestParam(name="duration", defaultValue=" ",required=false) String duration, @RequestParam(name="place", defaultValue=" ",required=false) String place, @RequestParam(name="description", defaultValue=" ",required=false) String description, Model model,HttpSession httpSession, @RequestParam(name="img",required = false) MultipartFile imgUrl) throws IOException { Formation oldFormation = formationService.findFormation(Long.parseLong((String)httpSession.getAttribute("formation_id"))); if(!imgUrl.isEmpty()) { String folder = System.getProperty("user.dir")+"\\src\\main\\resources\\static\\formationimg\\"; System.out.print(folder); byte[] bytes = imgUrl.getBytes(); Path path = Paths.get(folder+imgUrl.getOriginalFilename()); Files.write(path, bytes); oldFormation.setImg("/photos/"+imgUrl.getOriginalFilename()); } oldFormation.setTitle(title); oldFormation.setSubtitle(subtitle); oldFormation.setPrice(price); oldFormation.setLanguage(language); oldFormation.setDate_depart(date_depart); oldFormation.setLimit_student(limit_student); oldFormation.setCategorie(categorie); oldFormation.setDuration(duration); oldFormation.setPlace(place); oldFormation.setDescription(description); formationService.addFormation(oldFormation, userService.findOne(httpSession.getAttribute("nom").toString())); return "redirect:/formateur/updateformation"+"?formation_id="+(String)httpSession.getAttribute("formation_id"); } @GetMapping("/prerequis") public String pre(String formation_id,HttpSession session,Model model) { User user = userService.findByEmail(session.getAttribute("nom").toString()); model.addAttribute("user",user); session.setAttribute("pre", formation_id); return "/formateur/prerequis"; } @PostMapping("/prerequis") public String prePost(@RequestParam(value = "title") String[] pre,HttpSession session,Model model) { Formation formation = formationService.findFormation(Long.parseLong(session.getAttribute("pre").toString())); User user = userService.findByEmail(session.getAttribute("nom").toString()); model.addAttribute("user",user); formation.setPrerequis(pre); formationService.updateFormation(formation); return "/formateur/prerequis"; } @GetMapping("/consulter") public String consulterView(Model model, String formation_id) { System.out.println("id = " + formation_id); Formation formation = formationService.findFormation(Long.parseLong(formation_id)); if(formation.getActive() == 0) { model.addAttribute("active", false); } else { model.addAttribute("active", true); } model.addAttribute("formation", formation); return "/formateur/consulter"; } @GetMapping("/startFormation") public String startFormation(String formation_id, Model model) { Formation formation = formationService.findFormation(Long.parseLong(formation_id)); formation.setActive(0); formationService.updateFormation(formation); return "redirect:/formateur/listformation"; } }
UTF-8
Java
8,852
java
FormationController.java
Java
[]
null
[]
package com.annonce.app.controller; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.security.Principal; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import javax.servlet.http.HttpSession; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import com.annonce.app.model.Formation; import com.annonce.app.model.User; import com.annonce.app.repository.UserRepository; import com.annonce.app.service.FormationService; import com.annonce.app.service.UserService; @Controller @RequestMapping("/formateur") public class FormationController { @Autowired private UserService userService; @Autowired private FormationService formationService; @Autowired private UserRepository userRepository; @GetMapping("/dashboard") public String showDashboard(Model model, HttpSession session) { User user = userService.findByEmail(session.getAttribute("nom").toString()); model.addAttribute("user",user); return "/formateur/dashboard"; } @GetMapping("/addformation") public String showaddformation(Model model,HttpSession session) { String email = session.getAttribute("nom").toString(); model.addAttribute("formation",new Formation()); return "/formateur/addformation"; } @PostMapping("/addformation") public String addFormation(@RequestParam(name="title", defaultValue=" ",required=false) String title, @RequestParam(name="subtitle", defaultValue=" ",required=false) String subtitle, @RequestParam(name="price", defaultValue=" ",required=false) String price, @RequestParam(name="language", defaultValue=" ",required=false) String language, @RequestParam(name="date_depart", defaultValue=" ",required=false) String date_depart, @RequestParam(name="limit_student", defaultValue=" ",required=false) String limit_student, @RequestParam(name="categorie", defaultValue=" ",required=false) String categorie, @RequestParam(name="duration", defaultValue=" ",required=false) String duration, @RequestParam(name="place", defaultValue=" ",required=false) String place, @RequestParam(name="description", defaultValue=" ",required=false) String description, Model model,HttpSession httpSession, @RequestParam(name="img",required = false) MultipartFile imgUrl) throws IOException { System.out.println("badr2"); model.addAttribute("success",true); Formation formation = new Formation(); DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd"); Date date = new Date(); formation.setCreation_date(dateFormat.format(date)); formation.setCurrent_student("0"); formation.setActive(1); formation.setCategorie(categorie); formation.setDate_depart(date_depart); formation.setDescription(description); formation.setDuration(duration); formation.setLanguage(language); formation.setPlace(place); formation.setLimit_student(limit_student); formation.setTitle(title); formation.setSubtitle(subtitle); formation.setPrice(price); String folder = System.getProperty("user.dir")+"\\src\\main\\resources\\static\\formationimg\\"; System.out.print(folder); byte[] bytes = imgUrl.getBytes(); Path path = Paths.get(folder+imgUrl.getOriginalFilename()); Files.write(path, bytes); formation.setImg("/photos/"+imgUrl.getOriginalFilename()); formationService.addFormation(formation, userService.findOne(httpSession.getAttribute("nom").toString())); return "/formateur/addformation"; } @GetMapping("/listformation") public String showListFormation(String formation_number, Model model, HttpSession session) { String email = session.getAttribute("nom").toString(); model.addAttribute("formations",formationService.findUserFormation(userService.findOne(email))); User user = userService.findByEmail(session.getAttribute("nom").toString()); model.addAttribute("user",user); return "/formateur/listformation"; } @PostMapping("/listformation/{id}") public String deleteFormtion(@PathVariable String id) { formationService.deleteFormation(Long.parseLong(id)); return "redirect:/formateur/listformation"; } @GetMapping("/updateformation") public String showUpdatePage(String formation_id,Model model, Principal principal,HttpSession httpSession) { String email = httpSession.getAttribute("nom").toString(); httpSession.setAttribute("formation_id", formation_id); model.addAttribute("newformation", new Formation()); model.addAttribute("formation",formationService.findFormation(Long.parseLong(formation_id))); return "/formateur/updateformation"; } @PostMapping("/updateformation") public String updateFormation(@RequestParam(name="title", defaultValue=" ",required=false) String title, @RequestParam(name="subtitle", defaultValue=" ",required=false) String subtitle, @RequestParam(name="price", defaultValue=" ",required=false) String price, @RequestParam(name="language", defaultValue=" ",required=false) String language, @RequestParam(name="date_depart", defaultValue=" ",required=false) String date_depart, @RequestParam(name="limit_student", defaultValue=" ",required=false) String limit_student, @RequestParam(name="categorie", defaultValue=" ",required=false) String categorie, @RequestParam(name="duration", defaultValue=" ",required=false) String duration, @RequestParam(name="place", defaultValue=" ",required=false) String place, @RequestParam(name="description", defaultValue=" ",required=false) String description, Model model,HttpSession httpSession, @RequestParam(name="img",required = false) MultipartFile imgUrl) throws IOException { Formation oldFormation = formationService.findFormation(Long.parseLong((String)httpSession.getAttribute("formation_id"))); if(!imgUrl.isEmpty()) { String folder = System.getProperty("user.dir")+"\\src\\main\\resources\\static\\formationimg\\"; System.out.print(folder); byte[] bytes = imgUrl.getBytes(); Path path = Paths.get(folder+imgUrl.getOriginalFilename()); Files.write(path, bytes); oldFormation.setImg("/photos/"+imgUrl.getOriginalFilename()); } oldFormation.setTitle(title); oldFormation.setSubtitle(subtitle); oldFormation.setPrice(price); oldFormation.setLanguage(language); oldFormation.setDate_depart(date_depart); oldFormation.setLimit_student(limit_student); oldFormation.setCategorie(categorie); oldFormation.setDuration(duration); oldFormation.setPlace(place); oldFormation.setDescription(description); formationService.addFormation(oldFormation, userService.findOne(httpSession.getAttribute("nom").toString())); return "redirect:/formateur/updateformation"+"?formation_id="+(String)httpSession.getAttribute("formation_id"); } @GetMapping("/prerequis") public String pre(String formation_id,HttpSession session,Model model) { User user = userService.findByEmail(session.getAttribute("nom").toString()); model.addAttribute("user",user); session.setAttribute("pre", formation_id); return "/formateur/prerequis"; } @PostMapping("/prerequis") public String prePost(@RequestParam(value = "title") String[] pre,HttpSession session,Model model) { Formation formation = formationService.findFormation(Long.parseLong(session.getAttribute("pre").toString())); User user = userService.findByEmail(session.getAttribute("nom").toString()); model.addAttribute("user",user); formation.setPrerequis(pre); formationService.updateFormation(formation); return "/formateur/prerequis"; } @GetMapping("/consulter") public String consulterView(Model model, String formation_id) { System.out.println("id = " + formation_id); Formation formation = formationService.findFormation(Long.parseLong(formation_id)); if(formation.getActive() == 0) { model.addAttribute("active", false); } else { model.addAttribute("active", true); } model.addAttribute("formation", formation); return "/formateur/consulter"; } @GetMapping("/startFormation") public String startFormation(String formation_id, Model model) { Formation formation = formationService.findFormation(Long.parseLong(formation_id)); formation.setActive(0); formationService.updateFormation(formation); return "redirect:/formateur/listformation"; } }
8,852
0.762427
0.761862
231
37.320347
32.332573
126
false
false
0
0
0
0
0
0
2.450217
false
false
13
97fca88ed84cba08555b4fea195e45b498d4f565
25,314,537,264,391
b1ca800c7dd198e46ac8fef05b540f942681ec41
/app/src/main/java/com/example/keerthana/popularmovies/MovieItemListActivity.java
e688eb0ca2573dbff3d4bffbfe0424c64d72b713
[]
no_license
keer25/Popular-Movies
https://github.com/keer25/Popular-Movies
236905dab59a627fa265fefc2143dff9cd4067a8
9189099c98f84c2803461f5bbad68426dc57720b
refs/heads/master
2021-01-09T20:47:29.433000
2017-01-03T13:21:16
2017-01-03T13:21:16
60,086,964
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.keerthana.popularmovies; import android.annotation.TargetApi; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.res.Configuration; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.support.v4.view.MenuItemCompat; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.util.ArraySet; import android.util.DisplayMetrics; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import com.squareup.picasso.Picasso; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.lang.reflect.Array; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URI; import java.net.URL; import java.util.ArrayList; import java.util.HashSet; import java.util.List; public class MovieItemListActivity extends AppCompatActivity { /** * Whether or not the activity is in two-pane mode, i.e. running on a tablet * device. */ public final String[] map= {"top_rated", "popular", "favourites"}; public static String APP_ID ; public static JSONArray movieList; int pos; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_movieitem_list); APP_ID = this.getString(R.string.APIKEY); RecyclerView recyclerView = (RecyclerView) findViewById(R.id.movieitem_list); assert recyclerView != null; GridLayoutManager layout = new GridLayoutManager(getApplicationContext(), calSpan()); recyclerView.setLayoutManager(layout); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); toolbar.setTitle(getTitle()); toolbar.setLogo(R.mipmap.ic_launcher); } @Override protected void onResume(){ super.onResume(); if (pos == 2){ new GetFavouritesTask(getBaseContext(), MovieItemListActivity.this).execute(); Log.d("ACTIVITY_TRACK", "Recalculating favourites"); } } private int calSpan(){ DisplayMetrics metrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(metrics); int span = (int) (metrics.widthPixels/(metrics.xdpi*0.75)); Log.i("Span for grid",String.valueOf(span)); if (span <= 0) return 1; else return span; } @Override public boolean onCreateOptionsMenu(Menu menu){ getMenuInflater().inflate(R.menu.movie_list_menu, menu); MenuItem item = menu.findItem(R.id.spinner); Spinner spinner = (Spinner) MenuItemCompat.getActionView(item); ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.preference, R.layout.spinner_item); adapter.setDropDownViewResource(R.layout.spinner_dropdown_item); spinner.setAdapter(adapter); // set the adapter to provide layout of rows and content spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @TargetApi(Build.VERSION_CODES.M) @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { String pref = map[position]; pos = position; GetMoviesTask getMoviesTask = new GetMoviesTask(getApplicationContext(), MovieItemListActivity.this); if (isNetworkAvailable()) { if (position != 2){ getMoviesTask.execute(pref); }else { new GetFavouritesTask(getBaseContext(), MovieItemListActivity.this).execute(); } } else { Toast.makeText(getApplicationContext(), R.string.network_error, Toast.LENGTH_LONG).show(); } } @Override public void onNothingSelected(AdapterView<?> parent) { } }); return super.onCreateOptionsMenu(menu); } public boolean isNetworkAvailable() { ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); return activeNetworkInfo != null && activeNetworkInfo.isConnected(); } @Override public void onConfigurationChanged (Configuration newConfig) { RecyclerView recyclerView = (RecyclerView) findViewById(R.id.movieitem_list); assert recyclerView != null; GridLayoutManager layout = new GridLayoutManager(getApplicationContext(), calSpan()); recyclerView.setLayoutManager(layout); super.onConfigurationChanged(newConfig); } }
UTF-8
Java
5,535
java
MovieItemListActivity.java
Java
[ { "context": "package com.example.keerthana.popularmovies;\n\nimport android.annotation.TargetA", "end": 29, "score": 0.9965269565582275, "start": 20, "tag": "USERNAME", "value": "keerthana" } ]
null
[]
package com.example.keerthana.popularmovies; import android.annotation.TargetApi; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.res.Configuration; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.support.v4.view.MenuItemCompat; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.util.ArraySet; import android.util.DisplayMetrics; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import com.squareup.picasso.Picasso; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.lang.reflect.Array; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URI; import java.net.URL; import java.util.ArrayList; import java.util.HashSet; import java.util.List; public class MovieItemListActivity extends AppCompatActivity { /** * Whether or not the activity is in two-pane mode, i.e. running on a tablet * device. */ public final String[] map= {"top_rated", "popular", "favourites"}; public static String APP_ID ; public static JSONArray movieList; int pos; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_movieitem_list); APP_ID = this.getString(R.string.APIKEY); RecyclerView recyclerView = (RecyclerView) findViewById(R.id.movieitem_list); assert recyclerView != null; GridLayoutManager layout = new GridLayoutManager(getApplicationContext(), calSpan()); recyclerView.setLayoutManager(layout); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); toolbar.setTitle(getTitle()); toolbar.setLogo(R.mipmap.ic_launcher); } @Override protected void onResume(){ super.onResume(); if (pos == 2){ new GetFavouritesTask(getBaseContext(), MovieItemListActivity.this).execute(); Log.d("ACTIVITY_TRACK", "Recalculating favourites"); } } private int calSpan(){ DisplayMetrics metrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(metrics); int span = (int) (metrics.widthPixels/(metrics.xdpi*0.75)); Log.i("Span for grid",String.valueOf(span)); if (span <= 0) return 1; else return span; } @Override public boolean onCreateOptionsMenu(Menu menu){ getMenuInflater().inflate(R.menu.movie_list_menu, menu); MenuItem item = menu.findItem(R.id.spinner); Spinner spinner = (Spinner) MenuItemCompat.getActionView(item); ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.preference, R.layout.spinner_item); adapter.setDropDownViewResource(R.layout.spinner_dropdown_item); spinner.setAdapter(adapter); // set the adapter to provide layout of rows and content spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @TargetApi(Build.VERSION_CODES.M) @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { String pref = map[position]; pos = position; GetMoviesTask getMoviesTask = new GetMoviesTask(getApplicationContext(), MovieItemListActivity.this); if (isNetworkAvailable()) { if (position != 2){ getMoviesTask.execute(pref); }else { new GetFavouritesTask(getBaseContext(), MovieItemListActivity.this).execute(); } } else { Toast.makeText(getApplicationContext(), R.string.network_error, Toast.LENGTH_LONG).show(); } } @Override public void onNothingSelected(AdapterView<?> parent) { } }); return super.onCreateOptionsMenu(menu); } public boolean isNetworkAvailable() { ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); return activeNetworkInfo != null && activeNetworkInfo.isConnected(); } @Override public void onConfigurationChanged (Configuration newConfig) { RecyclerView recyclerView = (RecyclerView) findViewById(R.id.movieitem_list); assert recyclerView != null; GridLayoutManager layout = new GridLayoutManager(getApplicationContext(), calSpan()); recyclerView.setLayoutManager(layout); super.onConfigurationChanged(newConfig); } }
5,535
0.695754
0.693586
145
37.172413
26.323542
117
false
false
0
0
0
0
0
0
0.758621
false
false
13
b09cbacf96fe1f34acb59040f102402390883275
26,603,027,453,455
160663a72233aecbb05714b0aa7d3984e3e44c20
/L4E1_CompositePattern_Solution/src/edu/tum/cs/l1/pse/MenuComponent.java
5700bc752893511e8cb823270e6604637711ab23
[]
no_license
amitjoy/software-patterns
https://github.com/amitjoy/software-patterns
d92e192770d9ea914b8e382e1edb813d26f0849c
5db3ef039738295116f6c28bf14058ce594bc805
refs/heads/master
2021-01-10T13:44:31.212000
2015-11-02T06:10:05
2015-11-02T06:10:05
45,375,350
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package edu.tum.cs.l1.pse; //Example taken from Head First Design Patterns public abstract class MenuComponent { protected String name; protected String description; public String getName() { return name; } public String getDescription() { return description; } public void print() { throw new UnsupportedOperationException(); } }
UTF-8
Java
351
java
MenuComponent.java
Java
[]
null
[]
package edu.tum.cs.l1.pse; //Example taken from Head First Design Patterns public abstract class MenuComponent { protected String name; protected String description; public String getName() { return name; } public String getDescription() { return description; } public void print() { throw new UnsupportedOperationException(); } }
351
0.740741
0.737892
21
15.714286
15.934816
47
false
false
0
0
0
0
0
0
0.952381
false
false
13
27e380b592558992dcb173de6adff0992fd54a64
31,851,477,488,306
4ec74c12c875cb3d8407e82a74b00176adf09799
/spider-engine/src/test/java/com/gesangwu/spider/engine/task/test/SynergyTaskTest.java
6063c2a2d8bf30ff2e126d95673f9e78257d4b2a
[]
no_license
vickzhu/stock
https://github.com/vickzhu/stock
1b5282f08f311381047470931076e4807783ac8d
d79134ea95fb29ec5585a6ee432af3f9a457a594
refs/heads/master
2021-01-09T20:57:59.440000
2020-10-22T13:07:16
2020-10-22T13:07:16
61,874,853
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.gesangwu.spider.engine.task.test; import javax.annotation.Resource; import org.junit.Test; import com.gesangwu.spider.engine.task.SynergyTask; import com.gesangwu.spider.engine.test.BaseTest; public class SynergyTaskTest extends BaseTest { @Resource private SynergyTask task; // @Test public void execute(){ task.execute(); } @Test public void analyze(){ task.analyze("2017-06-01"); } }
UTF-8
Java
444
java
SynergyTaskTest.java
Java
[]
null
[]
package com.gesangwu.spider.engine.task.test; import javax.annotation.Resource; import org.junit.Test; import com.gesangwu.spider.engine.task.SynergyTask; import com.gesangwu.spider.engine.test.BaseTest; public class SynergyTaskTest extends BaseTest { @Resource private SynergyTask task; // @Test public void execute(){ task.execute(); } @Test public void analyze(){ task.analyze("2017-06-01"); } }
444
0.704955
0.686937
24
16.5
17.385338
51
false
false
0
0
0
0
0
0
0.958333
false
false
8
80b7a31ab852a7ae0928f4ee61ca2e39f09f72bb
10,711,648,450,098
b92312612498a1d619904f6f6d04fde74c308e07
/src/agendatelefonicarmifin/ClockClient.java
aff67f2092ae99def6b0494549d1a2979a329d16
[]
no_license
anamariaconstantin/first
https://github.com/anamariaconstantin/first
cdcc3a1c3f2b2ced83c0b44c31cdc01ffeec0519
90dfdce4df66def2baf236aa753e1938b1af642c
refs/heads/master
2021-01-09T06:09:16.621000
2017-02-04T15:31:37
2017-02-04T15:31:37
80,926,479
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package agendatelefonicarmifin; /** * * @author ana-maria.constantin */ import java.io.*; import java.net.*; import java.text.*; import java.util.*; /** * * @author student */ public class ClockClient { /** * @param args the command line arguments */ //algoritmul lui Cristian public static void main(String[] args) throws IOException { String port,hostName; BufferedReader stdIn = new BufferedReader( new InputStreamReader(System.in)); // System.out.println("Dati portul"); int portNumber = 1098; System.out.println("Dati hostname-ul"); hostName=stdIn.readLine(); try ( Socket echoSocket = new Socket(hostName, portNumber); PrintWriter out = new PrintWriter(echoSocket.getOutputStream(), true); BufferedReader in = new BufferedReader( new InputStreamReader(echoSocket.getInputStream())); ) { String userInput; System.out.println("Clientul este on!"); long T0; long serverTime; long T1; long finalTime; out.println(T0=System.currentTimeMillis()); serverTime = Long.parseLong(in.readLine()); T1 =System.currentTimeMillis(); finalTime = serverTime + (T1-T0)/2; DateFormat formatter = new SimpleDateFormat("HH:mm:ss:SSS"); System.out.println("Timp client : " + formatter.format(new Date(T1))); System.out.println("Timp server : " + formatter.format(new Date(serverTime))); System.out.println("Timpul clientului dupa reset: " + formatter.format(new Date(finalTime))); out.println("Exit"); } catch (UnknownHostException e) { System.err.println("Nu se cunoaste hostul " + hostName); System.exit(1); } catch (IOException e) { System.err.println("Err la citire! " + hostName); System.exit(1); } } }
UTF-8
Java
2,232
java
ClockClient.java
Java
[ { "context": "package agendatelefonicarmifin;\n\n/**\n *\n * @author ana-maria.constantin\n */\nimport java.io.*;\nimport java.net.*;\nimport j", "end": 71, "score": 0.9984085559844971, "start": 51, "tag": "NAME", "value": "ana-maria.constantin" }, { "context": "java.text.*;\nimport java.util.*;\n/**\n *\n * @author student\n */\npublic class ClockClient {\n\n /**\n * @p", "end": 178, "score": 0.9962300658226013, "start": 171, "tag": "USERNAME", "value": "student" } ]
null
[]
package agendatelefonicarmifin; /** * * @author ana-maria.constantin */ import java.io.*; import java.net.*; import java.text.*; import java.util.*; /** * * @author student */ public class ClockClient { /** * @param args the command line arguments */ //algoritmul lui Cristian public static void main(String[] args) throws IOException { String port,hostName; BufferedReader stdIn = new BufferedReader( new InputStreamReader(System.in)); // System.out.println("Dati portul"); int portNumber = 1098; System.out.println("Dati hostname-ul"); hostName=stdIn.readLine(); try ( Socket echoSocket = new Socket(hostName, portNumber); PrintWriter out = new PrintWriter(echoSocket.getOutputStream(), true); BufferedReader in = new BufferedReader( new InputStreamReader(echoSocket.getInputStream())); ) { String userInput; System.out.println("Clientul este on!"); long T0; long serverTime; long T1; long finalTime; out.println(T0=System.currentTimeMillis()); serverTime = Long.parseLong(in.readLine()); T1 =System.currentTimeMillis(); finalTime = serverTime + (T1-T0)/2; DateFormat formatter = new SimpleDateFormat("HH:mm:ss:SSS"); System.out.println("Timp client : " + formatter.format(new Date(T1))); System.out.println("Timp server : " + formatter.format(new Date(serverTime))); System.out.println("Timpul clientului dupa reset: " + formatter.format(new Date(finalTime))); out.println("Exit"); } catch (UnknownHostException e) { System.err.println("Nu se cunoaste hostul " + hostName); System.exit(1); } catch (IOException e) { System.err.println("Err la citire! " + hostName); System.exit(1); } } }
2,232
0.529122
0.522849
70
30.885714
24.398211
109
false
false
0
0
0
0
0
0
0.514286
false
false
8
a4b3cd2b8bfd37be2351f3eeaa2ae9221a4f1ed0
35,897,336,666,757
864717c7718890869b5601b7b0df4ae981313c82
/tongce/trunk/tcmc-ortholink-service/src/main/java/com/tc/ortholink/eot/service/dao/IEotStatusActionDictDao.java
ba7b64efaacffbe58b9dde60a969e83158e5ee82
[]
no_license
YAYO2016/project
https://github.com/YAYO2016/project
639c16e28f563bd724795b5ed6e8093c0f285dd6
c50e08f7d8b44065b4ea2afd34222a89d85fbf40
refs/heads/master
2020-04-04T16:22:08.151000
2018-11-05T11:16:18
2018-11-05T11:16:18
156,074,783
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.tc.ortholink.eot.service.dao; import com.tc.ortholink.eot.service.model.EotStatusActionDict; import com.tc.ortholink.service.dao.IHbdDao; /** * Created by zhanghaiyang on 2017/9/8. */ public interface IEotStatusActionDictDao extends IHbdDao<EotStatusActionDict> { }
UTF-8
Java
282
java
IEotStatusActionDictDao.java
Java
[ { "context": ".ortholink.service.dao.IHbdDao;\n\n/**\n * Created by zhanghaiyang on 2017/9/8.\n */\npublic interface IEotStatusActio", "end": 182, "score": 0.9961691498756409, "start": 170, "tag": "USERNAME", "value": "zhanghaiyang" } ]
null
[]
package com.tc.ortholink.eot.service.dao; import com.tc.ortholink.eot.service.model.EotStatusActionDict; import com.tc.ortholink.service.dao.IHbdDao; /** * Created by zhanghaiyang on 2017/9/8. */ public interface IEotStatusActionDictDao extends IHbdDao<EotStatusActionDict> { }
282
0.797872
0.776596
10
27.200001
28.006428
79
false
false
0
0
0
0
0
0
0.3
false
false
8
f8d85830f69f63f8eabfdc60d7f83d617c12aca0
36,197,984,381,880
d13cf92dcd0065cfc7e5ec2adcdeae6dd1c5a3a7
/Backend/ejercicioSpring/src/main/java/com/ejercicioSpring/model/InsertProductoDTO.java
dd57cc6add08802fca35a319e837cb34fc38297e
[]
no_license
RaulB0/Ejercicios
https://github.com/RaulB0/Ejercicios
01b2de8631dce5b05948879676e4b98ab39bc3d0
4b65d905fa8c21b0d1de2e11530a99c0a7619c12
refs/heads/master
2023-01-29T01:19:32.615000
2020-04-15T15:27:10
2020-04-15T15:27:10
253,205,189
0
0
null
false
2023-01-01T18:26:30
2020-04-05T10:09:02
2020-04-15T15:27:21
2023-01-01T18:26:29
1,338
0
0
23
Java
false
false
package com.ejercicioSpring.model; import com.fasterxml.jackson.annotation.JsonBackReference; import com.fasterxml.jackson.annotation.JsonManagedReference; import java.util.List; public class InsertProductoDTO { private int codigo; private String nombre; private int color; private String fecha_creacion; private int[] listaCategorias; public InsertProductoDTO() { } public InsertProductoDTO(int codigo, String nombre, int color, String fecha_creacion, int[] listaCategorias) { this.codigo = codigo; this.nombre = nombre; this.color = color; this.fecha_creacion = fecha_creacion; this.listaCategorias = listaCategorias; } public int getCodigo() { return codigo; } public void setCodigo(int codigo) { this.codigo = codigo; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public int getColor() { return color; } public void setColor(int color) { this.color = color; } public String getFecha_creacion() { return fecha_creacion; } public void setFecha_creacion(String fecha_creacion) { this.fecha_creacion = fecha_creacion; } public int[] getListaCategorias() { return listaCategorias; } public void setListaCategorias(int[] listaCategorias) { this.listaCategorias = listaCategorias; } }
UTF-8
Java
1,499
java
InsertProductoDTO.java
Java
[]
null
[]
package com.ejercicioSpring.model; import com.fasterxml.jackson.annotation.JsonBackReference; import com.fasterxml.jackson.annotation.JsonManagedReference; import java.util.List; public class InsertProductoDTO { private int codigo; private String nombre; private int color; private String fecha_creacion; private int[] listaCategorias; public InsertProductoDTO() { } public InsertProductoDTO(int codigo, String nombre, int color, String fecha_creacion, int[] listaCategorias) { this.codigo = codigo; this.nombre = nombre; this.color = color; this.fecha_creacion = fecha_creacion; this.listaCategorias = listaCategorias; } public int getCodigo() { return codigo; } public void setCodigo(int codigo) { this.codigo = codigo; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public int getColor() { return color; } public void setColor(int color) { this.color = color; } public String getFecha_creacion() { return fecha_creacion; } public void setFecha_creacion(String fecha_creacion) { this.fecha_creacion = fecha_creacion; } public int[] getListaCategorias() { return listaCategorias; } public void setListaCategorias(int[] listaCategorias) { this.listaCategorias = listaCategorias; } }
1,499
0.652435
0.652435
67
21.373135
21.523909
114
false
false
0
0
0
0
0
0
0.41791
false
false
8
7d81c6c46ef06ee677cd234f02dc2318ee28a531
18,107,582,146,006
6d1bc185584552164f4dc36ae317e67081702b1d
/trunk/src/java/Dao/NotaDao.java
eb5e33617ac3a3aee7888832c53a3569bf82f86c
[]
no_license
comppet/DataPET
https://github.com/comppet/DataPET
789ddc96f88d5d2838748cd32b87df7fe5dd1b08
d681da1de0a4b08ac6d190a00615cfe16da955a7
refs/heads/master
2016-09-06T03:41:11.336000
2013-06-10T18:48:28
2013-06-10T18:48:28
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Dao; import Model.Nota; import java.sql.SQLException; import java.util.ArrayList; /** * Esta é uma interface extendida de Dao de uma Nota. * * @author Tiago Peres * @version 3.0 * @since 3.0 */ public interface NotaDao extends Dao<Nota> { ArrayList<Nota> listarTodos(int idAluno) throws SQLException; ArrayList<Nota> listarTodosGrupo (int idGrupo, int ano, int semestre) throws SQLException; }
UTF-8
Java
520
java
NotaDao.java
Java
[ { "context": "erface extendida de Dao de uma Nota.\n *\n * @author Tiago Peres\n * @version 3.0\n * @since 3.0\n */\npublic interfac", "end": 276, "score": 0.9998419284820557, "start": 265, "tag": "NAME", "value": "Tiago Peres" } ]
null
[]
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Dao; import Model.Nota; import java.sql.SQLException; import java.util.ArrayList; /** * Esta é uma interface extendida de Dao de uma Nota. * * @author <NAME> * @version 3.0 * @since 3.0 */ public interface NotaDao extends Dao<Nota> { ArrayList<Nota> listarTodos(int idAluno) throws SQLException; ArrayList<Nota> listarTodosGrupo (int idGrupo, int ano, int semestre) throws SQLException; }
515
0.72447
0.716763
22
22.59091
25.004835
94
false
false
0
0
0
0
0
0
0.454545
false
false
8
2818af0f9e3fda681f42fd90859add63bffeff84
3,496,103,403,588
8672e8d173afdda3bf22a7b799cf3c94d88f948e
/spring-boot-15-rabbitmq/src/main/java/com/zzw/rabbitmq/route/Consumer2.java
121cdf73c30a3f40e126a1600b0a5c1a8627cbad
[ "MIT" ]
permissive
834640725/springboot-learning-1
https://github.com/834640725/springboot-learning-1
f624c502552373a9f265ab5724539b3134cccaae
4e23f8f1672aed011c7b325e90ff84d59d477ebe
refs/heads/master
2023-08-18T22:02:43.327000
2021-01-13T15:15:28
2021-01-13T15:15:28
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.zzw.rabbitmq.route; import com.rabbitmq.client.*; import com.zzw.rabbitmq.utils.RabbitMQUtils; import java.io.IOException; public class Consumer2 { // junit 测试不支持多线程,所以测试消费者要在main主线成中运行 public static void main(String[] args) throws IOException { // 获取连接对象 Connection connection = RabbitMQUtils.getConnection(); // 获取连接中的通道对象 Channel channel = connection.createChannel(); String exchangeName = "logs_direct"; // 声明交换机 以及交换机类型 direct channel.exchangeDeclare(exchangeName, "direct"); // 临时队列 String queueName = channel.queueDeclare().getQueue(); // 绑定交换机和队列 channel.queueBind(queueName, exchangeName, "info"); channel.queueBind(queueName, exchangeName, "error"); channel.queueBind(queueName, exchangeName, "warning"); // 消费消息 channel.basicConsume(queueName, true, new DefaultConsumer(channel) { @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { System.out.println("消费者2:" + new String(body)); } }); } }
UTF-8
Java
1,349
java
Consumer2.java
Java
[]
null
[]
package com.zzw.rabbitmq.route; import com.rabbitmq.client.*; import com.zzw.rabbitmq.utils.RabbitMQUtils; import java.io.IOException; public class Consumer2 { // junit 测试不支持多线程,所以测试消费者要在main主线成中运行 public static void main(String[] args) throws IOException { // 获取连接对象 Connection connection = RabbitMQUtils.getConnection(); // 获取连接中的通道对象 Channel channel = connection.createChannel(); String exchangeName = "logs_direct"; // 声明交换机 以及交换机类型 direct channel.exchangeDeclare(exchangeName, "direct"); // 临时队列 String queueName = channel.queueDeclare().getQueue(); // 绑定交换机和队列 channel.queueBind(queueName, exchangeName, "info"); channel.queueBind(queueName, exchangeName, "error"); channel.queueBind(queueName, exchangeName, "warning"); // 消费消息 channel.basicConsume(queueName, true, new DefaultConsumer(channel) { @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { System.out.println("消费者2:" + new String(body)); } }); } }
1,349
0.653942
0.652282
37
31.567568
30.283829
144
false
false
0
0
0
0
0
0
0.702703
false
false
8
01034bf5d63fec5fa84b1b5a7f5bf0b057384259
5,205,500,385,870
5bc8f14ef682ec657f66cf0456f60d97aeb4cbb2
/HotelBookings.java
b46073c45e8f7d2de4e2535c89ea4e8b2deed9a0
[]
no_license
DiegoJRivera/arrayList_parentAndChildClasses
https://github.com/DiegoJRivera/arrayList_parentAndChildClasses
0932e4130e5ca5d305d0a2573861c59abbeb0219
d9073e41a115a7d6e5fbaf42621e3bc5ced4ac86
refs/heads/master
2021-01-13T14:07:05.032000
2016-12-16T00:08:36
2016-12-16T00:08:36
76,161,627
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Practical Exercise 5 developed by Diego Rivera for Programming Fundamentals class. * 09/09/2016 * HotelBookings aplication allows the creation of the different hotel objects. * Objects created are to be added to an ArrayList called "hotel". * There is menu system that allows to the user select the type of room followed * by imputing the room number from the keyboard. * The menu also have a rates section listing the different room rates, as well * an option to list all currently booked out rooms and an exit button. */ package practicalexercise5; /** * * @author diegorivera * 09/09/2016 * HotelBookings.java */ import javax.swing.JOptionPane; import java.util.ArrayList; public class HotelBookings { /** * @param args the command line arguments */ public static void main(String[] args) { //ArrayList hotel declaration ArrayList<HotelRoom> hotel = new ArrayList<>(); while (true) { //Display input menu int choice = Integer.parseInt( JOptionPane.showInputDialog(null, "--HOTEL RENTAL SYSTEM--\n\n" + "1. Choose a room type\n" + "2. Room rates information\n" + "3. Rooms currently booked\n\n" + "4. Exit")); if (choice != 4) { switch (choice) { case 1://Option 1 Choose a room type int select = Integer.parseInt(JOptionPane.showInputDialog(null, "1. Normal Hotel room\n" + "2. Suite\n\n" + "Choose room type")); int roomNo; //conditional to pass values to select rooms if (select == 1 || select == 2) { roomNo = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter room number")); HotelRoom room = null; switch (select) { case 1: room = new HotelRoom(roomNo);//Option 1 Hotel Room break; case 2: room = new Suite(roomNo);//Option 2 Suite break; } hotel.add(room); //Display room booked JOptionPane.showMessageDialog(null, "--Rooms Booked out--\n\n" + room.toString()); } break; case 2://Option 2 Room rates info JOptionPane.showMessageDialog(null, "NIGHTLY ROOM RATES\n\n" + "Rooms numbered 1-" + (HotelRoom.ROOM_THRESHOLD - 1) + "= $" + HotelRoom.RATE_SMALL + "\nAll other rooms are $" + HotelRoom.RATE_LARGE + "\n\n" + "Suites have an extra $" + Suite.SURCHARGE + " surcharge applied"); break; case 3://Option 3 display Currently rooms booked String searchResults = "", searchList = ""; searchResults += hotel.toString(); if (searchResults.length() < 4) { JOptionPane.showMessageDialog(null, "No Rooms Booked yet"); } else { for (int i = 0; i < hotel.size(); i++) { HotelRoom hotelroom = hotel.get(i); searchList += hotelroom.toString() + "\n"; } JOptionPane.showMessageDialog(null, "--Rooms Booked out--\n\n" + searchList); } break; } } else { System.exit(0);//Exit the program }//end else } //end while }//end main }
UTF-8
Java
4,248
java
HotelBookings.java
Java
[ { "context": "/*\n * Practical Exercise 5 developed by Diego Rivera for Programming Fundamentals class.\n * 09/09/2016", "end": 52, "score": 0.9999003410339355, "start": 40, "tag": "NAME", "value": "Diego Rivera" }, { "context": " */\npackage practicalexercise5;\n\n/**\n *\n * @author diegorivera\n * 09/09/2016\n * HotelBookings.java\n */\nimport ja", "end": 595, "score": 0.9983762502670288, "start": 584, "tag": "USERNAME", "value": "diegorivera" } ]
null
[]
/* * Practical Exercise 5 developed by <NAME> for Programming Fundamentals class. * 09/09/2016 * HotelBookings aplication allows the creation of the different hotel objects. * Objects created are to be added to an ArrayList called "hotel". * There is menu system that allows to the user select the type of room followed * by imputing the room number from the keyboard. * The menu also have a rates section listing the different room rates, as well * an option to list all currently booked out rooms and an exit button. */ package practicalexercise5; /** * * @author diegorivera * 09/09/2016 * HotelBookings.java */ import javax.swing.JOptionPane; import java.util.ArrayList; public class HotelBookings { /** * @param args the command line arguments */ public static void main(String[] args) { //ArrayList hotel declaration ArrayList<HotelRoom> hotel = new ArrayList<>(); while (true) { //Display input menu int choice = Integer.parseInt( JOptionPane.showInputDialog(null, "--HOTEL RENTAL SYSTEM--\n\n" + "1. Choose a room type\n" + "2. Room rates information\n" + "3. Rooms currently booked\n\n" + "4. Exit")); if (choice != 4) { switch (choice) { case 1://Option 1 Choose a room type int select = Integer.parseInt(JOptionPane.showInputDialog(null, "1. Normal Hotel room\n" + "2. Suite\n\n" + "Choose room type")); int roomNo; //conditional to pass values to select rooms if (select == 1 || select == 2) { roomNo = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter room number")); HotelRoom room = null; switch (select) { case 1: room = new HotelRoom(roomNo);//Option 1 Hotel Room break; case 2: room = new Suite(roomNo);//Option 2 Suite break; } hotel.add(room); //Display room booked JOptionPane.showMessageDialog(null, "--Rooms Booked out--\n\n" + room.toString()); } break; case 2://Option 2 Room rates info JOptionPane.showMessageDialog(null, "NIGHTLY ROOM RATES\n\n" + "Rooms numbered 1-" + (HotelRoom.ROOM_THRESHOLD - 1) + "= $" + HotelRoom.RATE_SMALL + "\nAll other rooms are $" + HotelRoom.RATE_LARGE + "\n\n" + "Suites have an extra $" + Suite.SURCHARGE + " surcharge applied"); break; case 3://Option 3 display Currently rooms booked String searchResults = "", searchList = ""; searchResults += hotel.toString(); if (searchResults.length() < 4) { JOptionPane.showMessageDialog(null, "No Rooms Booked yet"); } else { for (int i = 0; i < hotel.size(); i++) { HotelRoom hotelroom = hotel.get(i); searchList += hotelroom.toString() + "\n"; } JOptionPane.showMessageDialog(null, "--Rooms Booked out--\n\n" + searchList); } break; } } else { System.exit(0);//Exit the program }//end else } //end while }//end main }
4,242
0.446092
0.436205
97
42.793816
29.102711
117
false
false
0
0
0
0
0
0
0.402062
false
false
8
60df44cae9f2d30168380c0d292bd81dcf9a934c
25,262,997,658,860
3e097c7d83752be7947ca1777bdd8a3254c30a65
/src/org/csu/mypetstore/web/servlet/AddItemToCartServlet.java
88e94a731c389987b570b3eaec6284dfb5961475
[]
no_license
Hydrapse/mypetstore-servlet
https://github.com/Hydrapse/mypetstore-servlet
4d5ba12fa0c1430939d0dae4735f273c18a38313
f59fea12883c2288aacc50cc976b3e52ea3c35bd
refs/heads/master
2022-11-07T16:40:01.697000
2020-03-02T15:19:42
2020-03-02T15:19:42
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.csu.mypetstore.web.servlet; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.csu.mypetstore.domain.Cart; import org.csu.mypetstore.domain.Item; import org.csu.mypetstore.service.CatalogService; import org.csu.mypetstore.service.impl.CatalogServiceImpl; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; /** * Created by Enzo Cotter on 2019/10/7. */ public class AddItemToCartServlet extends HttpServlet { private static final Logger logger = LogManager.getLogger(AddItemToCartServlet.class); //定义处理该请求所需要的数据 private String workingItemId; private Cart cart; //调用业务逻辑层 private CatalogService catalogService; public String getWorkingItemId() { return workingItemId; } public void setWorkingItemId(String workingItemId) { this.workingItemId = workingItemId; } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { workingItemId = req.getParameter("workingItemId"); HttpSession session = req.getSession(); cart = (Cart) session.getAttribute("cart"); if (cart == null) { cart = new Cart(); } if (cart.containsItemId(workingItemId)) { cart.incrementQuantityByItemId(workingItemId); } else { catalogService = new CatalogServiceImpl(); Item item = catalogService.getItem(workingItemId); boolean isInStock = catalogService.isItemInStock(workingItemId); cart.addItem(item, isInStock); } session.setAttribute("cart", cart); logger.info("添加item " + workingItemId +" 至购物车"); resp.sendRedirect("viewCart"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
UTF-8
Java
2,164
java
AddItemToCartServlet.java
Java
[ { "context": "on;\nimport java.io.IOException;\n\n/**\n * Created by Enzo Cotter on 2019/10/7.\n */\npublic class AddItemToCartServl", "end": 581, "score": 0.9998693466186523, "start": 570, "tag": "NAME", "value": "Enzo Cotter" } ]
null
[]
package org.csu.mypetstore.web.servlet; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.csu.mypetstore.domain.Cart; import org.csu.mypetstore.domain.Item; import org.csu.mypetstore.service.CatalogService; import org.csu.mypetstore.service.impl.CatalogServiceImpl; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; /** * Created by <NAME> on 2019/10/7. */ public class AddItemToCartServlet extends HttpServlet { private static final Logger logger = LogManager.getLogger(AddItemToCartServlet.class); //定义处理该请求所需要的数据 private String workingItemId; private Cart cart; //调用业务逻辑层 private CatalogService catalogService; public String getWorkingItemId() { return workingItemId; } public void setWorkingItemId(String workingItemId) { this.workingItemId = workingItemId; } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { workingItemId = req.getParameter("workingItemId"); HttpSession session = req.getSession(); cart = (Cart) session.getAttribute("cart"); if (cart == null) { cart = new Cart(); } if (cart.containsItemId(workingItemId)) { cart.incrementQuantityByItemId(workingItemId); } else { catalogService = new CatalogServiceImpl(); Item item = catalogService.getItem(workingItemId); boolean isInStock = catalogService.isItemInStock(workingItemId); cart.addItem(item, isInStock); } session.setAttribute("cart", cart); logger.info("添加item " + workingItemId +" 至购物车"); resp.sendRedirect("viewCart"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
2,159
0.708807
0.704545
67
30.522388
26.674578
114
false
false
0
0
0
0
0
0
0.58209
false
false
8
8a415e9dfa43000bdd505a706b013978185f561b
25,262,997,659,650
498839a954c1ed6ba53838723c650a483f7bed5e
/app/src/main/java/helloworld/com/kalkulator/Postavke.java
60526f040137ceea858a736499b237b9074ab6b2
[]
no_license
oanicic/kalkulator
https://github.com/oanicic/kalkulator
f92bd0e0384e37c93eb6d05d0c234ce2b9aa8a2f
7c3bbd8964b778d3c57fbd64d012b55f6cc11ede
refs/heads/master
2020-03-05T14:39:28.384000
2015-12-11T20:14:52
2015-12-11T20:14:52
47,726,958
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package helloworld.com.kalkulator; import android.content.res.Configuration; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.Toast; import java.util.Locale; public class Postavke extends AppCompatActivity { RadioGroup skupina; RadioButton radioEngl, radioHrv, radioFr; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_postavke); skupina=(RadioGroup)findViewById(R.id.radioPostavke); radioEngl=(RadioButton)findViewById(R.id.radioButtonEngl); radioFr=(RadioButton)findViewById(R.id.radioButtonFr); radioHrv=(RadioButton)findViewById(R.id.radioButtonHr); } public void postaviHrvatski(View view){ String languageToLoad = "hr"; Locale locale = new Locale(languageToLoad); Locale.setDefault(locale); Configuration config = new Configuration(); config.locale = locale; getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics()); this.setContentView(R.layout.activity_postavke); String poruka = getString(R.string.toastJezik); Toast.makeText(getApplicationContext(), poruka, Toast.LENGTH_SHORT).show(); } public void postaviEngleski(View view){ String languageToLoad = "en"; Locale locale = new Locale(languageToLoad); Locale.setDefault(locale); Configuration config = new Configuration(); config.locale = locale; getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics()); this.setContentView(R.layout.activity_postavke); String poruka = getString(R.string.toastJezik); Toast.makeText(getApplicationContext(), poruka, Toast.LENGTH_SHORT).show(); } public void postaviFrancuski(View view){ String languageToLoad = "fr"; Locale locale = new Locale(languageToLoad); Locale.setDefault(locale); Configuration config = new Configuration(); config.locale = locale; getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics()); this.setContentView(R.layout.activity_postavke); String poruka = getString(R.string.toastJezik); Toast.makeText(getApplicationContext(), poruka, Toast.LENGTH_SHORT).show(); } }
UTF-8
Java
2,650
java
Postavke.java
Java
[]
null
[]
package helloworld.com.kalkulator; import android.content.res.Configuration; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.Toast; import java.util.Locale; public class Postavke extends AppCompatActivity { RadioGroup skupina; RadioButton radioEngl, radioHrv, radioFr; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_postavke); skupina=(RadioGroup)findViewById(R.id.radioPostavke); radioEngl=(RadioButton)findViewById(R.id.radioButtonEngl); radioFr=(RadioButton)findViewById(R.id.radioButtonFr); radioHrv=(RadioButton)findViewById(R.id.radioButtonHr); } public void postaviHrvatski(View view){ String languageToLoad = "hr"; Locale locale = new Locale(languageToLoad); Locale.setDefault(locale); Configuration config = new Configuration(); config.locale = locale; getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics()); this.setContentView(R.layout.activity_postavke); String poruka = getString(R.string.toastJezik); Toast.makeText(getApplicationContext(), poruka, Toast.LENGTH_SHORT).show(); } public void postaviEngleski(View view){ String languageToLoad = "en"; Locale locale = new Locale(languageToLoad); Locale.setDefault(locale); Configuration config = new Configuration(); config.locale = locale; getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics()); this.setContentView(R.layout.activity_postavke); String poruka = getString(R.string.toastJezik); Toast.makeText(getApplicationContext(), poruka, Toast.LENGTH_SHORT).show(); } public void postaviFrancuski(View view){ String languageToLoad = "fr"; Locale locale = new Locale(languageToLoad); Locale.setDefault(locale); Configuration config = new Configuration(); config.locale = locale; getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics()); this.setContentView(R.layout.activity_postavke); String poruka = getString(R.string.toastJezik); Toast.makeText(getApplicationContext(), poruka, Toast.LENGTH_SHORT).show(); } }
2,650
0.698868
0.698491
70
36.857143
24.619555
83
false
false
0
0
0
0
0
0
0.785714
false
false
8
dde116abcfb890b1f4ea16190aaa07feb806622a
9,637,906,649,970
c28d407b93331070b924ff52f252e5ea7aa3074b
/jvm/src/main/java/slack/MagicDictionary.java
e840a4395054adafa37fa01526bf228390ead634
[]
no_license
jtroxel/interview_code
https://github.com/jtroxel/interview_code
aa1a1c4d978bf312ef1a8ae4e4711665769cdfaf
afef9ed3ffcdab53bbda9e2cbb4e2cc16bcc7fb1
refs/heads/master
2022-05-14T23:23:14.582000
2022-03-31T14:23:37
2022-03-31T14:23:37
2,037,428
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package slack; /* PROBLEM: Transformation dictionary 1) Given a dictionary of words, determine whether it is possible to transform a given word into another with a fixed number of characters 2) Modify the approach so that transitions between varying quantities were possible 3) Modify the code to work as an API with lots of words added to the dictionary, but few tests boolean isTransformable(String start, String end, List<String> dict) EX: "dog" -> "hat", dict = ["dog", "cat", "hot", "hog", "eat", "dug", "dig"] QUESTIONS?: - Each intermediate transorm has to be in the dict. SOLUTION IDEAS / INTUITION - This reminds me of using a Trie to store a language, or list of valid tokens, so head->d->o->g \->u->g \->c->a->t - traverse: match frist, see if there are 2nd alternatives. - for current letter, need to look back as well? - Or How about a Matrix? | d, o, g | | c, a, t | | h, o, t | | h, o, g | | d, i, g | | d, u, g | - Brute force - So we want to check a word against a list, looking for only N character diffs. Can also check the end against the list. Meet in the middle. Each time looking for overlapping results, or sets. Idea is a double loop, searching forward and backwards. We have a positive if the resulting sets overlap. Loop ?? - Compare [dog] <-> [hat] - Forward: search [dog] -> dig, hog (+dog) - Backward: search [hat] -> hot (+hat) (second pass) - Compare [dog, dig, hog] <-> [hat, hot] -> this case means 2 transform away - search [dig, hog] -> [dog, dug] + [hot,dog] + [dig, hog] -> oh we add to a matchLeft list - search [hat, hot] -> [cat, hot] + [hot] + [hat, hot] -> add to matchRight (third) - Compare [dog, dug, hot, dig, hog] <-> [cat, hot, hat] Dictionary len = N, max word length = K. X = chars to change. K/X outer loop, N*N string compares innder loop. O(N**2) */ import java.util.*; import com.google.common.collect.Lists; import com.google.common.collect.Sets; class MagicDictionary { private int max_word_length = 3; private int matchChars = 1; public static void main(String[] args) { List<String> dict = Lists.newArrayList("dog", "cat", "hot", "hog", "eat", "dug", "dig"); MagicDictionary transformer = new MagicDictionary(); assert transformer.isTransformable("dog", "hat", dict); } public boolean isTransformable(String start, String end, List<String> dict) { Set<String> searchLeft = Sets.newHashSet(start); Set<String> searchRight = Sets.newHashSet(end); int pass = 1; do { System.out.println("Left: " + searchLeft + " Right: " + searchRight + " Pass: " + pass); if (!Collections.disjoint(searchLeft, searchRight)) { System.out.println("Found!!! "); return true; } searchLeft.addAll(searchStringsOneDiff(searchLeft, dict)); searchRight.addAll(searchStringsOneDiff(searchRight, dict)); pass += 1; } while (pass <= max_word_length); return false; } private Set<String> searchStringsOneDiff(Set<String> searchFor, List<String>dict) { Set<String> retSet = new HashSet<>(); for (String searchWord : searchFor) { System.out.println("Comparing search: " + searchWord); for (String dictWord : dict) { System.out.println(". to " + dictWord); int matchingChars = 0; if (searchWord.equals(dictWord)) continue; for (int i = 0; i < dictWord.length(); i++) { if (searchWord.charAt(i) == dictWord.charAt(i)) { System.out.println(". - char match " + dictWord.charAt(i)); matchingChars += 1; } } System.out.println(". total matching " + matchingChars); if (matchingChars == (dictWord.length() - this.matchChars)) { System.out.println("Found word " + dictWord + " from " + searchWord); retSet.add(dictWord); } } System.out.println("Return Set: " + retSet.toString()); return retSet; } return null; } }
UTF-8
Java
4,008
java
MagicDictionary.java
Java
[]
null
[]
package slack; /* PROBLEM: Transformation dictionary 1) Given a dictionary of words, determine whether it is possible to transform a given word into another with a fixed number of characters 2) Modify the approach so that transitions between varying quantities were possible 3) Modify the code to work as an API with lots of words added to the dictionary, but few tests boolean isTransformable(String start, String end, List<String> dict) EX: "dog" -> "hat", dict = ["dog", "cat", "hot", "hog", "eat", "dug", "dig"] QUESTIONS?: - Each intermediate transorm has to be in the dict. SOLUTION IDEAS / INTUITION - This reminds me of using a Trie to store a language, or list of valid tokens, so head->d->o->g \->u->g \->c->a->t - traverse: match frist, see if there are 2nd alternatives. - for current letter, need to look back as well? - Or How about a Matrix? | d, o, g | | c, a, t | | h, o, t | | h, o, g | | d, i, g | | d, u, g | - Brute force - So we want to check a word against a list, looking for only N character diffs. Can also check the end against the list. Meet in the middle. Each time looking for overlapping results, or sets. Idea is a double loop, searching forward and backwards. We have a positive if the resulting sets overlap. Loop ?? - Compare [dog] <-> [hat] - Forward: search [dog] -> dig, hog (+dog) - Backward: search [hat] -> hot (+hat) (second pass) - Compare [dog, dig, hog] <-> [hat, hot] -> this case means 2 transform away - search [dig, hog] -> [dog, dug] + [hot,dog] + [dig, hog] -> oh we add to a matchLeft list - search [hat, hot] -> [cat, hot] + [hot] + [hat, hot] -> add to matchRight (third) - Compare [dog, dug, hot, dig, hog] <-> [cat, hot, hat] Dictionary len = N, max word length = K. X = chars to change. K/X outer loop, N*N string compares innder loop. O(N**2) */ import java.util.*; import com.google.common.collect.Lists; import com.google.common.collect.Sets; class MagicDictionary { private int max_word_length = 3; private int matchChars = 1; public static void main(String[] args) { List<String> dict = Lists.newArrayList("dog", "cat", "hot", "hog", "eat", "dug", "dig"); MagicDictionary transformer = new MagicDictionary(); assert transformer.isTransformable("dog", "hat", dict); } public boolean isTransformable(String start, String end, List<String> dict) { Set<String> searchLeft = Sets.newHashSet(start); Set<String> searchRight = Sets.newHashSet(end); int pass = 1; do { System.out.println("Left: " + searchLeft + " Right: " + searchRight + " Pass: " + pass); if (!Collections.disjoint(searchLeft, searchRight)) { System.out.println("Found!!! "); return true; } searchLeft.addAll(searchStringsOneDiff(searchLeft, dict)); searchRight.addAll(searchStringsOneDiff(searchRight, dict)); pass += 1; } while (pass <= max_word_length); return false; } private Set<String> searchStringsOneDiff(Set<String> searchFor, List<String>dict) { Set<String> retSet = new HashSet<>(); for (String searchWord : searchFor) { System.out.println("Comparing search: " + searchWord); for (String dictWord : dict) { System.out.println(". to " + dictWord); int matchingChars = 0; if (searchWord.equals(dictWord)) continue; for (int i = 0; i < dictWord.length(); i++) { if (searchWord.charAt(i) == dictWord.charAt(i)) { System.out.println(". - char match " + dictWord.charAt(i)); matchingChars += 1; } } System.out.println(". total matching " + matchingChars); if (matchingChars == (dictWord.length() - this.matchChars)) { System.out.println("Found word " + dictWord + " from " + searchWord); retSet.add(dictWord); } } System.out.println("Return Set: " + retSet.toString()); return retSet; } return null; } }
4,008
0.633733
0.630489
110
35.436363
34.913277
197
false
false
0
0
0
0
0
0
1
false
false
8
2b8b3e5f7bbed2bba2ff02729bcfe22cae66fe36
6,605,659,764,213
394aa19887e6c0dcd4ded58de6bedf842c180f6f
/Climb_Stairs_with_min_moves.java
6812a8a73d6d874224afca78feef39ff78d88e02
[]
no_license
pat-the-bat/Dynamic-Programming-Java-
https://github.com/pat-the-bat/Dynamic-Programming-Java-
ae3fc06583a80054caf45975ee6cbad739822377
faa210a98834a7ef507e21569c45d9d323b6734f
refs/heads/master
2022-12-24T17:53:24.405000
2020-09-30T06:50:33
2020-09-30T06:50:33
297,063,390
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
//print the minimum number of moves in which one can move to the top import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws Exception { // write your code here Scanner scn=new Scanner(System.in); int n=scn.nextInt(); int[] arr=new int[n]; for(int i=0;i<n;i++){ arr[i]=scn.nextInt(); } Integer[] dp=new Integer[n+1]; dp[n]=0; for (int i=n-1;i>=0;i--){ if (arr[i]>0){ int min=Integer.MAX_VALUE; for(int j=1;j<=arr[i] && i+j<dp.length;j++){ if (dp[i+j]!=null){ min=Math.min(min,dp[i+j]); } } if(min!=Integer.MAX_VALUE){ dp[i]=min+1; } } } System.out.println(dp[0]); } }
UTF-8
Java
977
java
Climb_Stairs_with_min_moves.java
Java
[]
null
[]
//print the minimum number of moves in which one can move to the top import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws Exception { // write your code here Scanner scn=new Scanner(System.in); int n=scn.nextInt(); int[] arr=new int[n]; for(int i=0;i<n;i++){ arr[i]=scn.nextInt(); } Integer[] dp=new Integer[n+1]; dp[n]=0; for (int i=n-1;i>=0;i--){ if (arr[i]>0){ int min=Integer.MAX_VALUE; for(int j=1;j<=arr[i] && i+j<dp.length;j++){ if (dp[i+j]!=null){ min=Math.min(min,dp[i+j]); } } if(min!=Integer.MAX_VALUE){ dp[i]=min+1; } } } System.out.println(dp[0]); } }
977
0.407369
0.398158
38
24.710526
17.030788
69
false
false
0
0
0
0
0
0
0.5
false
false
8
6b9235f0e927d8c21a727c7e293ce4a1f8a4f83e
8,942,121,936,604
c403c89edb94dbf1e4561f7cc9a6042e0a11c9ee
/app/src/main/java/com/yctech/kexin/MainActivity.java
4dd755d36bebddfe6869bb930270e70be11a41d5
[]
no_license
yccycc/KeXin
https://github.com/yccycc/KeXin
cbccc0c1f26fe358e9849263f70b5f566e726983
829897e487c3f4170863b2b3ddc0f8329fa2766d
refs/heads/master
2021-01-10T01:08:36.743000
2015-12-14T07:11:48
2015-12-14T07:11:48
46,757,648
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.yctech.kexin; import android.app.Activity; import android.media.MediaPlayer; import android.os.Bundle; import android.os.PowerManager; import android.speech.tts.TextToSpeech; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Locale; import java.util.Random; public class MainActivity extends AppCompatActivity implements View.OnClickListener, TextToSpeech.OnInitListener { private static final int THREE = 3; private static final int FOUR = 4; private static final int FIVE = 5; private static final int SIX = 6; private static final int SEVEN = 7; private static final int EIGHT = 8; private static final int NINE = 9; private static final int TEN = 10; private static final int ELEVEN = 11; private static final int TWELVE = 12; private Button mStart; private TextView mTiShiTv; public int getmCount() { return mCount; } public void setmCount(int mCount) { this.mCount = mCount; } private int mCount = 3; private MediaPlayer mediaPlayer; private Random random; private List<Integer> list; private int modeFlag = THREE; private TextView nowModeTv; private Button stopBtn; private Button loop; private TextToSpeech tts; private Boolean readFlag = false; PowerManager powerManager; PowerManager.WakeLock wakeLock; PlayThread playThread; LoopThread loopThread; private class LoopThread extends Thread{ @Override public void run() { super.run(); while(!Thread.interrupted()){ try { Thread.sleep(1000*(readFlag? mCount+mCount/2 :mCount+2)); } catch (InterruptedException e) { break; } MainActivity.this.getWindow().getDecorView().post(new Runnable() { @Override public void run() { mStart.performClick(); } }); } } } private class PlayThread extends Thread{ @Override @SuppressWarnings( "deprecation" ) public void run() { super.run(); list = new ArrayList<>(); MainActivity.this.getWindow().getDecorView().post(new Runnable() { @Override public void run() { mTiShiTv.setText("next"); } }); for(int i=0 ;i < mCount;i++){ mediaPlayer = MediaPlayer.create(MainActivity.this,getRandomRawId()); mediaPlayer.start(); try { Thread.sleep(1000); } catch (InterruptedException e) { break; } if(null!=mediaPlayer){ mediaPlayer.stop(); mediaPlayer.release(); mediaPlayer = null; } } MainActivity.this.getWindow().getDecorView().post(new Runnable() { @Override public void run() { mTiShiTv.setText(Arrays.toString(list.toArray())); if (readFlag) { tts.setSpeechRate(10); tts.speak(Arrays.toString(list.toArray()), TextToSpeech.QUEUE_FLUSH, null); } } }); MainActivity.this.getWindow().getDecorView().post(new Runnable() { @Override public void run() { mStart.setEnabled(true); } }); } } private void assignViews() { mStart = (Button) findViewById(R.id.start); mTiShiTv = (TextView) findViewById(R.id.tishiTv); nowModeTv = (TextView) findViewById(R.id.now_mode); stopBtn = (Button) findViewById(R.id.stop); loop = (Button) findViewById(R.id.loop); } @Override @SuppressWarnings( "deprecation" ) protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Snackbar.make(view, "nice day", Snackbar.LENGTH_SHORT) .setAction("Action", null).show(); } }); assignViews(); mStart.setOnClickListener(this); stopBtn.setOnClickListener(this); loop.setOnClickListener(this); random = new Random(); tts = new TextToSpeech(this,this); tts.setLanguage(Locale.CHINESE); nowModeTv.setText("CDE"); powerManager = (PowerManager) getSystemService(Activity.POWER_SERVICE); wakeLock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK,"mylock"); wakeLock.acquire(); } private int getRandomRawId(){ float temp =random.nextFloat(); if(THREE==modeFlag){ if(0<=temp&&temp<0.33){list.add(1);return R.raw.c;} if(0.33<=temp&&temp<0.66){list.add(2);return R.raw.d;} if(0.66<=temp&&temp<1){list.add(3);return R.raw.e;} } if(FOUR==modeFlag){ if(0<=temp&&temp<0.25){list.add(1);return R.raw.c;} if(0.25<=temp&&temp<0.5){list.add(2);return R.raw.d;} if(0.5<=temp&&temp<0.75){list.add(3);return R.raw.e;} if(0.75<=temp&&temp<1){list.add(6);return R.raw.a;} } if(FIVE==modeFlag){ if(0<=temp&&temp<0.2){list.add(1);return R.raw.c;} if(0.2<=temp&&temp<0.4){list.add(2);return R.raw.d;} if(0.4<=temp&&temp<0.6){list.add(3);return R.raw.e;} if(0.6<=temp&&temp<0.8){list.add(4);return R.raw.f;} if(0.8<=temp&&temp<1){list.add(5);return R.raw.g;} } if(SIX==modeFlag){ if(0<=temp&&temp<0.15){list.add(1);return R.raw.c;} if(0.15<=temp&&temp<0.3){list.add(2);return R.raw.d;} if(0.3<=temp&&temp<0.45){list.add(3);return R.raw.e;} if(0.45<=temp&&temp<0.6){list.add(4);return R.raw.f;} if(0.6<=temp&&temp<0.75){list.add(5);return R.raw.g;} if(0.75<=temp&&temp<1){list.add(6);return R.raw.a;} } if(SEVEN==modeFlag){ if(0<=temp&&temp<0.14){list.add(1);return R.raw.c;} if(0.14<=temp&&temp<0.28){list.add(2);return R.raw.d;} if(0.28<=temp&&temp<0.42){list.add(3);return R.raw.e;} if(0.42<=temp&&temp<0.56){list.add(4);return R.raw.f;} if(0.56<=temp&&temp<0.7){list.add(5);return R.raw.g;} if(0.7<=temp&&temp<0.84){list.add(6);return R.raw.a;} if(0.84<=temp&&temp<1){list.add(7);return R.raw.b;} } if(EIGHT==modeFlag){ if(0<=temp&&temp<0.5){list.add(2);return R.raw.d;} if(0.5<=temp&&temp<1){list.add(3);return R.raw.e;} } if(NINE==modeFlag){ if(0<=temp&&temp<0.5){list.add(3);return R.raw.e;} if(0.5<=temp&&temp<1){list.add(4);return R.raw.f;} } if(TEN==modeFlag){ if(0<=temp&&temp<0.33){list.add(2);return R.raw.d;} if(0.33<=temp&&temp<0.66){list.add(3);return R.raw.e;} if(0.66<=temp&&temp<1){list.add(4);return R.raw.f;} } if(ELEVEN==modeFlag){ if(0<=temp&&temp<0.5){list.add(1);return R.raw.c;} if(0.5<=temp&&temp<1){list.add(2);return R.raw.d;} } if(TWELVE==modeFlag){ if(0<=temp&&temp<0.33){list.add(5);return R.raw.g;} if(0.33<=temp&&temp<0.66){list.add(6);return R.raw.a;} if(0.66<=temp&&temp<1){list.add(7);return R.raw.b;} } return R.raw.c; } @Override @SuppressWarnings( "deprecation" ) public void onClick(final View v) { switch (v.getId()){ case R.id.start: tts.stop(); v.setEnabled(false); playThread = new PlayThread(); playThread.start(); break; case R.id.stop: mStart.setEnabled(true); if(null!=playThread){ playThread.interrupt(); } if(null!=loopThread){ loopThread.interrupt(); } loop.setEnabled(true); if(null!=mediaPlayer){ Toast.makeText(this,"wait a minute",Toast.LENGTH_LONG).show(); } break; case R.id.loop: loop.setEnabled(false); mStart.performClick(); loopThread = new LoopThread(); loopThread.start(); break; } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()){ case R.id.cde: Toast.makeText(this,"cde",Toast.LENGTH_SHORT).show(); modeFlag = THREE; nowModeTv.setText("CDE"); break; case R.id.cdea: Toast.makeText(this,"cdea",Toast.LENGTH_SHORT).show(); modeFlag = FOUR; nowModeTv.setText("CDEA"); break; case R.id.cdefg: Toast.makeText(this,"cdefg",Toast.LENGTH_SHORT).show(); modeFlag = FIVE; nowModeTv.setText("CDEFG"); break; case R.id.cdefga: Toast.makeText(this,"cdefga",Toast.LENGTH_SHORT).show(); modeFlag = SIX; nowModeTv.setText("CDEFGA"); break; case R.id.cdefgab: Toast.makeText(this,"cdefgab",Toast.LENGTH_SHORT).show(); modeFlag = SEVEN; nowModeTv.setText("CDEFGAB"); break; case R.id.de: Toast.makeText(this,"de",Toast.LENGTH_SHORT).show(); modeFlag = EIGHT; nowModeTv.setText("DE"); break; case R.id.ef: Toast.makeText(this,"ef",Toast.LENGTH_SHORT).show(); modeFlag = NINE; nowModeTv.setText("EF"); break; case R.id.def: Toast.makeText(this,"def",Toast.LENGTH_SHORT).show(); modeFlag = TEN; nowModeTv.setText("DEF"); break; case R.id.cd: Toast.makeText(this,"cd",Toast.LENGTH_SHORT).show(); modeFlag = ELEVEN; nowModeTv.setText("CD"); break; case R.id.read_on: Toast.makeText(this,"read is on",Toast.LENGTH_SHORT).show(); readFlag = Boolean.TRUE; break; case R.id.read_off: Toast.makeText(this,"read is off",Toast.LENGTH_SHORT).show(); readFlag = Boolean.FALSE; break; case R.id.gab: Toast.makeText(this,"gab",Toast.LENGTH_SHORT).show(); modeFlag = TWELVE; nowModeTv.setText("GAB"); break; } return super.onOptionsItemSelected(item); } @Override public void onInit(int status) { } @Override protected void onDestroy() { super.onDestroy(); if(wakeLock.isHeld()){ wakeLock.release(); } tts.shutdown(); tts.stop(); } }
UTF-8
Java
12,367
java
MainActivity.java
Java
[]
null
[]
package com.yctech.kexin; import android.app.Activity; import android.media.MediaPlayer; import android.os.Bundle; import android.os.PowerManager; import android.speech.tts.TextToSpeech; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Locale; import java.util.Random; public class MainActivity extends AppCompatActivity implements View.OnClickListener, TextToSpeech.OnInitListener { private static final int THREE = 3; private static final int FOUR = 4; private static final int FIVE = 5; private static final int SIX = 6; private static final int SEVEN = 7; private static final int EIGHT = 8; private static final int NINE = 9; private static final int TEN = 10; private static final int ELEVEN = 11; private static final int TWELVE = 12; private Button mStart; private TextView mTiShiTv; public int getmCount() { return mCount; } public void setmCount(int mCount) { this.mCount = mCount; } private int mCount = 3; private MediaPlayer mediaPlayer; private Random random; private List<Integer> list; private int modeFlag = THREE; private TextView nowModeTv; private Button stopBtn; private Button loop; private TextToSpeech tts; private Boolean readFlag = false; PowerManager powerManager; PowerManager.WakeLock wakeLock; PlayThread playThread; LoopThread loopThread; private class LoopThread extends Thread{ @Override public void run() { super.run(); while(!Thread.interrupted()){ try { Thread.sleep(1000*(readFlag? mCount+mCount/2 :mCount+2)); } catch (InterruptedException e) { break; } MainActivity.this.getWindow().getDecorView().post(new Runnable() { @Override public void run() { mStart.performClick(); } }); } } } private class PlayThread extends Thread{ @Override @SuppressWarnings( "deprecation" ) public void run() { super.run(); list = new ArrayList<>(); MainActivity.this.getWindow().getDecorView().post(new Runnable() { @Override public void run() { mTiShiTv.setText("next"); } }); for(int i=0 ;i < mCount;i++){ mediaPlayer = MediaPlayer.create(MainActivity.this,getRandomRawId()); mediaPlayer.start(); try { Thread.sleep(1000); } catch (InterruptedException e) { break; } if(null!=mediaPlayer){ mediaPlayer.stop(); mediaPlayer.release(); mediaPlayer = null; } } MainActivity.this.getWindow().getDecorView().post(new Runnable() { @Override public void run() { mTiShiTv.setText(Arrays.toString(list.toArray())); if (readFlag) { tts.setSpeechRate(10); tts.speak(Arrays.toString(list.toArray()), TextToSpeech.QUEUE_FLUSH, null); } } }); MainActivity.this.getWindow().getDecorView().post(new Runnable() { @Override public void run() { mStart.setEnabled(true); } }); } } private void assignViews() { mStart = (Button) findViewById(R.id.start); mTiShiTv = (TextView) findViewById(R.id.tishiTv); nowModeTv = (TextView) findViewById(R.id.now_mode); stopBtn = (Button) findViewById(R.id.stop); loop = (Button) findViewById(R.id.loop); } @Override @SuppressWarnings( "deprecation" ) protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Snackbar.make(view, "nice day", Snackbar.LENGTH_SHORT) .setAction("Action", null).show(); } }); assignViews(); mStart.setOnClickListener(this); stopBtn.setOnClickListener(this); loop.setOnClickListener(this); random = new Random(); tts = new TextToSpeech(this,this); tts.setLanguage(Locale.CHINESE); nowModeTv.setText("CDE"); powerManager = (PowerManager) getSystemService(Activity.POWER_SERVICE); wakeLock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK,"mylock"); wakeLock.acquire(); } private int getRandomRawId(){ float temp =random.nextFloat(); if(THREE==modeFlag){ if(0<=temp&&temp<0.33){list.add(1);return R.raw.c;} if(0.33<=temp&&temp<0.66){list.add(2);return R.raw.d;} if(0.66<=temp&&temp<1){list.add(3);return R.raw.e;} } if(FOUR==modeFlag){ if(0<=temp&&temp<0.25){list.add(1);return R.raw.c;} if(0.25<=temp&&temp<0.5){list.add(2);return R.raw.d;} if(0.5<=temp&&temp<0.75){list.add(3);return R.raw.e;} if(0.75<=temp&&temp<1){list.add(6);return R.raw.a;} } if(FIVE==modeFlag){ if(0<=temp&&temp<0.2){list.add(1);return R.raw.c;} if(0.2<=temp&&temp<0.4){list.add(2);return R.raw.d;} if(0.4<=temp&&temp<0.6){list.add(3);return R.raw.e;} if(0.6<=temp&&temp<0.8){list.add(4);return R.raw.f;} if(0.8<=temp&&temp<1){list.add(5);return R.raw.g;} } if(SIX==modeFlag){ if(0<=temp&&temp<0.15){list.add(1);return R.raw.c;} if(0.15<=temp&&temp<0.3){list.add(2);return R.raw.d;} if(0.3<=temp&&temp<0.45){list.add(3);return R.raw.e;} if(0.45<=temp&&temp<0.6){list.add(4);return R.raw.f;} if(0.6<=temp&&temp<0.75){list.add(5);return R.raw.g;} if(0.75<=temp&&temp<1){list.add(6);return R.raw.a;} } if(SEVEN==modeFlag){ if(0<=temp&&temp<0.14){list.add(1);return R.raw.c;} if(0.14<=temp&&temp<0.28){list.add(2);return R.raw.d;} if(0.28<=temp&&temp<0.42){list.add(3);return R.raw.e;} if(0.42<=temp&&temp<0.56){list.add(4);return R.raw.f;} if(0.56<=temp&&temp<0.7){list.add(5);return R.raw.g;} if(0.7<=temp&&temp<0.84){list.add(6);return R.raw.a;} if(0.84<=temp&&temp<1){list.add(7);return R.raw.b;} } if(EIGHT==modeFlag){ if(0<=temp&&temp<0.5){list.add(2);return R.raw.d;} if(0.5<=temp&&temp<1){list.add(3);return R.raw.e;} } if(NINE==modeFlag){ if(0<=temp&&temp<0.5){list.add(3);return R.raw.e;} if(0.5<=temp&&temp<1){list.add(4);return R.raw.f;} } if(TEN==modeFlag){ if(0<=temp&&temp<0.33){list.add(2);return R.raw.d;} if(0.33<=temp&&temp<0.66){list.add(3);return R.raw.e;} if(0.66<=temp&&temp<1){list.add(4);return R.raw.f;} } if(ELEVEN==modeFlag){ if(0<=temp&&temp<0.5){list.add(1);return R.raw.c;} if(0.5<=temp&&temp<1){list.add(2);return R.raw.d;} } if(TWELVE==modeFlag){ if(0<=temp&&temp<0.33){list.add(5);return R.raw.g;} if(0.33<=temp&&temp<0.66){list.add(6);return R.raw.a;} if(0.66<=temp&&temp<1){list.add(7);return R.raw.b;} } return R.raw.c; } @Override @SuppressWarnings( "deprecation" ) public void onClick(final View v) { switch (v.getId()){ case R.id.start: tts.stop(); v.setEnabled(false); playThread = new PlayThread(); playThread.start(); break; case R.id.stop: mStart.setEnabled(true); if(null!=playThread){ playThread.interrupt(); } if(null!=loopThread){ loopThread.interrupt(); } loop.setEnabled(true); if(null!=mediaPlayer){ Toast.makeText(this,"wait a minute",Toast.LENGTH_LONG).show(); } break; case R.id.loop: loop.setEnabled(false); mStart.performClick(); loopThread = new LoopThread(); loopThread.start(); break; } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()){ case R.id.cde: Toast.makeText(this,"cde",Toast.LENGTH_SHORT).show(); modeFlag = THREE; nowModeTv.setText("CDE"); break; case R.id.cdea: Toast.makeText(this,"cdea",Toast.LENGTH_SHORT).show(); modeFlag = FOUR; nowModeTv.setText("CDEA"); break; case R.id.cdefg: Toast.makeText(this,"cdefg",Toast.LENGTH_SHORT).show(); modeFlag = FIVE; nowModeTv.setText("CDEFG"); break; case R.id.cdefga: Toast.makeText(this,"cdefga",Toast.LENGTH_SHORT).show(); modeFlag = SIX; nowModeTv.setText("CDEFGA"); break; case R.id.cdefgab: Toast.makeText(this,"cdefgab",Toast.LENGTH_SHORT).show(); modeFlag = SEVEN; nowModeTv.setText("CDEFGAB"); break; case R.id.de: Toast.makeText(this,"de",Toast.LENGTH_SHORT).show(); modeFlag = EIGHT; nowModeTv.setText("DE"); break; case R.id.ef: Toast.makeText(this,"ef",Toast.LENGTH_SHORT).show(); modeFlag = NINE; nowModeTv.setText("EF"); break; case R.id.def: Toast.makeText(this,"def",Toast.LENGTH_SHORT).show(); modeFlag = TEN; nowModeTv.setText("DEF"); break; case R.id.cd: Toast.makeText(this,"cd",Toast.LENGTH_SHORT).show(); modeFlag = ELEVEN; nowModeTv.setText("CD"); break; case R.id.read_on: Toast.makeText(this,"read is on",Toast.LENGTH_SHORT).show(); readFlag = Boolean.TRUE; break; case R.id.read_off: Toast.makeText(this,"read is off",Toast.LENGTH_SHORT).show(); readFlag = Boolean.FALSE; break; case R.id.gab: Toast.makeText(this,"gab",Toast.LENGTH_SHORT).show(); modeFlag = TWELVE; nowModeTv.setText("GAB"); break; } return super.onOptionsItemSelected(item); } @Override public void onInit(int status) { } @Override protected void onDestroy() { super.onDestroy(); if(wakeLock.isHeld()){ wakeLock.release(); } tts.shutdown(); tts.stop(); } }
12,367
0.525107
0.506833
343
35.055393
21.077391
114
false
false
0
0
0
0
0
0
0.80758
false
false
8
50504258a41b564cfd68481151b6cb99e610e145
24,833,500,925,844
2c6b840a23566f143b1fb150b32b10f2aa2f7765
/src/com/koreaap/rms/cm/commonPop/web/CommonPopController.java
a5932a216646d294818fa9f23976df310b1c9a6e
[]
no_license
Lee-Myung-Chul/mc
https://github.com/Lee-Myung-Chul/mc
45d1145cb240e2b38df87921d1f19309bdf0832a
39da1fb35275de269b9c5dd8b2c01f46a8d95dad
refs/heads/master
2021-08-02T12:20:57.907000
2021-07-27T00:07:24
2021-07-27T00:07:24
67,489,237
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.koreaap.rms.cm.commonPop.web; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.koreaap.rms.cm.commonPop.persistence.CommonPopMapper; import com.koreaap.rms.cm.commonPop.service.CommonPopService; import com.koreaap.rms.framework.MroConstants; import com.koreaap.rms.framework.ui.MroRequest; import com.koreaap.rms.framework.ui.MroResponse; import com.koreaap.rms.framework.util.TreeUtil; @Controller @RequestMapping("/cm/commonPop") public class CommonPopController { private Logger logger = LoggerFactory.getLogger(getClass()); @Autowired private CommonPopMapper commonPopMapper; @Autowired private CommonPopService commonPopService; /** * 공통팝업 테이블정보, 테이블컬럼정보 조회 */ @RequestMapping("/findTableJobInfo") @ResponseBody public MroResponse findTableInfo(@RequestParam Map<String, Object> param) { String tableJobId = (String) param.get("tableJobId"); List<Map<String, Object>> tableJobInfo = commonPopMapper.findTableJobInfo(tableJobId); List<Map<String, Object>> tableJobList = commonPopMapper.findTableJobList(tableJobId); return new MroResponse().addList("tableJobInfo", tableJobInfo).addList("tableJobList", tableJobList); } /** * 공통팝업 테이블정보에 따른 데이터 조회 */ @RequestMapping("/findTableJobData") @ResponseBody public MroResponse findTableJobData(@RequestBody MroRequest req) { Map<String, Object> param = new HashMap<String, Object>(); param.put("tableJobId", req.getParam("tableJobId")); // tableJobId param.put("keyValues", req.getDataSet("keyValues", HashMap.class)); // 키와 키값은 파라미터로 넘어옴 List<Map<String, Object>> tableJobData = commonPopService.findTableJobData(param); return new MroResponse().addList("tableJobData", tableJobData); } /** * 공통팝업 데이터 수정 */ @RequestMapping("/saveTableJobData") @ResponseBody public MroResponse saveTableJobData(@RequestBody MroRequest req) { Map<String, Object> param = new HashMap<String, Object>(); param.put("tableJobId", req.getParam("tableJobId")); // tableJobId param.put("status", req.getParam("status")); // insert / update / delete param.put("keyValues", req.getDataSet("keyValues", HashMap.class)); // 키와 키값 param.put("colValues", req.getDataSet("colValues", HashMap.class)); // 컬럼과 컬럼값 commonPopService.saveTableJobData(param); return new MroResponse(); } }
UTF-8
Java
3,029
java
CommonPopController.java
Java
[]
null
[]
package com.koreaap.rms.cm.commonPop.web; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.koreaap.rms.cm.commonPop.persistence.CommonPopMapper; import com.koreaap.rms.cm.commonPop.service.CommonPopService; import com.koreaap.rms.framework.MroConstants; import com.koreaap.rms.framework.ui.MroRequest; import com.koreaap.rms.framework.ui.MroResponse; import com.koreaap.rms.framework.util.TreeUtil; @Controller @RequestMapping("/cm/commonPop") public class CommonPopController { private Logger logger = LoggerFactory.getLogger(getClass()); @Autowired private CommonPopMapper commonPopMapper; @Autowired private CommonPopService commonPopService; /** * 공통팝업 테이블정보, 테이블컬럼정보 조회 */ @RequestMapping("/findTableJobInfo") @ResponseBody public MroResponse findTableInfo(@RequestParam Map<String, Object> param) { String tableJobId = (String) param.get("tableJobId"); List<Map<String, Object>> tableJobInfo = commonPopMapper.findTableJobInfo(tableJobId); List<Map<String, Object>> tableJobList = commonPopMapper.findTableJobList(tableJobId); return new MroResponse().addList("tableJobInfo", tableJobInfo).addList("tableJobList", tableJobList); } /** * 공통팝업 테이블정보에 따른 데이터 조회 */ @RequestMapping("/findTableJobData") @ResponseBody public MroResponse findTableJobData(@RequestBody MroRequest req) { Map<String, Object> param = new HashMap<String, Object>(); param.put("tableJobId", req.getParam("tableJobId")); // tableJobId param.put("keyValues", req.getDataSet("keyValues", HashMap.class)); // 키와 키값은 파라미터로 넘어옴 List<Map<String, Object>> tableJobData = commonPopService.findTableJobData(param); return new MroResponse().addList("tableJobData", tableJobData); } /** * 공통팝업 데이터 수정 */ @RequestMapping("/saveTableJobData") @ResponseBody public MroResponse saveTableJobData(@RequestBody MroRequest req) { Map<String, Object> param = new HashMap<String, Object>(); param.put("tableJobId", req.getParam("tableJobId")); // tableJobId param.put("status", req.getParam("status")); // insert / update / delete param.put("keyValues", req.getDataSet("keyValues", HashMap.class)); // 키와 키값 param.put("colValues", req.getDataSet("colValues", HashMap.class)); // 컬럼과 컬럼값 commonPopService.saveTableJobData(param); return new MroResponse(); } }
3,029
0.766494
0.765803
86
32.662792
29.19924
103
false
false
0
0
0
0
0
0
1.616279
false
false
8
60298b1c98a0a7558eece0a7ff8e0739c5c08993
32,478,542,726,694
1e105b9e1458ea38094a5ad59170cb7eb68c3a32
/src/lesson3/secondPart/Task317.java
3c9b18ff7474a87f94964776d6c31553dc49f95e
[]
no_license
dapastushenko/dapastushenkoITMONew
https://github.com/dapastushenko/dapastushenkoITMONew
80d29c6beda3fd6c2613d15f786d18456e6699c8
b8af9fb163608946257dc9931f8fc92512da2c1b
refs/heads/master
2021-08-31T07:57:12.536000
2017-12-20T18:03:57
2017-12-20T18:03:57
109,152,011
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* Создать двумерный массив из 6 строк по 7 столбцов в каждой из случайных целых чисел из отрезка [0;9]. Вывести массив на экран. Преобразовать массив таким образом, чтобы на первом месте в каждой строке стоял её наибольший элемент. При этом изменять состав массива нельзя, а можно только переставлять элементы в рамках одной строки. Порядок остальных элементов строки не важен (т.е. можно соврешить только одну перестановку, а можно отсортировать по убыванию каждую строку). Вывести преобразованный массив на экран. */ package lesson3.secondPart; import java.util.Arrays; public class Task317 { public static void main(String[] args) { int[][] rndarray = new int[6][7]; int first = 0; int position = 0; int max = 0; for (int i = 0; i <= 5; i++) { for (int n = 0; n <= 6; n++) { rndarray[i][n] = (int) (Math.random() * (9 + 0)); if (rndarray[i][n] > max) { max = rndarray[i][n]; position = n; } } first = rndarray[i][0]; rndarray[i][0] = max; rndarray[i][position] = first; } for (int i = 0; i < rndarray.length; i++) { System.out.println(Arrays.toString(rndarray[i])); } } }
UTF-8
Java
1,731
java
Task317.java
Java
[]
null
[]
/* Создать двумерный массив из 6 строк по 7 столбцов в каждой из случайных целых чисел из отрезка [0;9]. Вывести массив на экран. Преобразовать массив таким образом, чтобы на первом месте в каждой строке стоял её наибольший элемент. При этом изменять состав массива нельзя, а можно только переставлять элементы в рамках одной строки. Порядок остальных элементов строки не важен (т.е. можно соврешить только одну перестановку, а можно отсортировать по убыванию каждую строку). Вывести преобразованный массив на экран. */ package lesson3.secondPart; import java.util.Arrays; public class Task317 { public static void main(String[] args) { int[][] rndarray = new int[6][7]; int first = 0; int position = 0; int max = 0; for (int i = 0; i <= 5; i++) { for (int n = 0; n <= 6; n++) { rndarray[i][n] = (int) (Math.random() * (9 + 0)); if (rndarray[i][n] > max) { max = rndarray[i][n]; position = n; } } first = rndarray[i][0]; rndarray[i][0] = max; rndarray[i][position] = first; } for (int i = 0; i < rndarray.length; i++) { System.out.println(Arrays.toString(rndarray[i])); } } }
1,731
0.577304
0.560548
36
35.472221
33.347069
116
false
false
0
0
0
0
0
0
0.638889
false
false
8
e7be03cc97d2aed5ee39c667340f09bf333685cf
8,521,215,152,393
1cb3170060692376e77733fdda58ed1e3303ad89
/src/com/chat/client/model/UserLoader.java
dce02a7ff484bcbc26325ae5770690a3f47d99ad
[]
no_license
blackice999/Chat-server
https://github.com/blackice999/Chat-server
5b1457447c6e70ed6c0c2aefb38adfe051c093fd
9c5ebfe45d050f6e707e0463704535a348f58394
refs/heads/master
2021-01-23T02:16:08.151000
2017-03-23T17:54:55
2017-03-23T17:54:55
85,980,916
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.chat.client.model; import java.io.*; import java.util.ArrayList; import java.util.List; /** * Created by vhernest on 12/11/15. */ public class UserLoader { public static List<User> loadUsers(InputStream in) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(in)); List<User> users = new ArrayList<>(); String line; while ((line = reader.readLine()) != null) { User user = User.parse(line); users.add(user); } return users; } public static List<User> loadUsers(String fileName) throws IOException { return loadUsers(new FileInputStream(fileName)); } }
UTF-8
Java
702
java
UserLoader.java
Java
[ { "context": "rayList;\nimport java.util.List;\n\n/**\n * Created by vhernest on 12/11/15.\n */\npublic class UserLoader {\n\n p", "end": 128, "score": 0.9996474385261536, "start": 120, "tag": "USERNAME", "value": "vhernest" } ]
null
[]
package com.chat.client.model; import java.io.*; import java.util.ArrayList; import java.util.List; /** * Created by vhernest on 12/11/15. */ public class UserLoader { public static List<User> loadUsers(InputStream in) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(in)); List<User> users = new ArrayList<>(); String line; while ((line = reader.readLine()) != null) { User user = User.parse(line); users.add(user); } return users; } public static List<User> loadUsers(String fileName) throws IOException { return loadUsers(new FileInputStream(fileName)); } }
702
0.639601
0.631054
28
24.071428
24.519567
78
false
false
0
0
0
0
0
0
0.392857
false
false
8
4d9fa302aaa1f16b141f10ee3801aa305f0cafe7
26,104,811,293,621
b4d455a3d82a2dd8140470b7c7d0f756d58396a9
/src/arthmetic/MaximalRectangle.java
05624e5a63b0517109cc004f53f8f78dfef1956e
[]
no_license
ermaoyu/Work
https://github.com/ermaoyu/Work
17024ef91b83d8b17294646a879961678d91e4ec
6c9da556b5c8841fd83a1e7a32630a3a6328aea4
refs/heads/master
2020-03-30T04:18:53.757000
2019-08-19T15:16:40
2019-08-19T15:16:40
150,736,537
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package arthmetic; import java.util.Stack; public class MaximalRectangle { /** * 求最大子矩阵的大小 * 给定一个整型矩形map,其中的值只有0和1两种,求其中全是1的所有矩形区域中, * 最大的矩形区域为1的数量 * */ public static int maxRecsize(int[][] map){ if(map == null || map.length == 0|| map[0].length == 0){ return 0; } int maxArea = 0; int[] height = new int[map[0].length]; for (int i = 0;i< map.length;i++){ for (int j = 0;j< map[0].length;j++){ height[j] = map[i][j] == 0?0:height[j]+1; } maxArea = Math.max(maxRecFromBottom(height),maxArea); } return maxArea; } //单调栈{4,3,2,5,6} public static int maxRecFromBottom(int[] height){ if (height == null || height.length == 0){ return 0; } int maxArea = 0; Stack<Integer> stack = new Stack<Integer>(); for (int i = 0;i < height.length ; i++){ while (!stack.isEmpty() && height[i] <= height[stack.peek()]){ int j = stack.pop(); int k = stack.isEmpty()?-1:stack.peek(); int curArea = (i - k -1) * height[j]; maxArea = Math.max(maxArea,curArea); } stack.push(i); } while (!stack.isEmpty()){ int j = stack.pop(); int k = stack.isEmpty()?-1:stack.peek(); int curArea = (height.length- k -1) * height[j]; maxArea = Math.max(maxArea,curArea); } return maxArea; } }
UTF-8
Java
1,672
java
MaximalRectangle.java
Java
[]
null
[]
package arthmetic; import java.util.Stack; public class MaximalRectangle { /** * 求最大子矩阵的大小 * 给定一个整型矩形map,其中的值只有0和1两种,求其中全是1的所有矩形区域中, * 最大的矩形区域为1的数量 * */ public static int maxRecsize(int[][] map){ if(map == null || map.length == 0|| map[0].length == 0){ return 0; } int maxArea = 0; int[] height = new int[map[0].length]; for (int i = 0;i< map.length;i++){ for (int j = 0;j< map[0].length;j++){ height[j] = map[i][j] == 0?0:height[j]+1; } maxArea = Math.max(maxRecFromBottom(height),maxArea); } return maxArea; } //单调栈{4,3,2,5,6} public static int maxRecFromBottom(int[] height){ if (height == null || height.length == 0){ return 0; } int maxArea = 0; Stack<Integer> stack = new Stack<Integer>(); for (int i = 0;i < height.length ; i++){ while (!stack.isEmpty() && height[i] <= height[stack.peek()]){ int j = stack.pop(); int k = stack.isEmpty()?-1:stack.peek(); int curArea = (i - k -1) * height[j]; maxArea = Math.max(maxArea,curArea); } stack.push(i); } while (!stack.isEmpty()){ int j = stack.pop(); int k = stack.isEmpty()?-1:stack.peek(); int curArea = (height.length- k -1) * height[j]; maxArea = Math.max(maxArea,curArea); } return maxArea; } }
1,672
0.477012
0.458493
51
29.705883
20.551508
74
false
false
0
0
0
0
0
0
0.843137
false
false
8
674dcfbe0c13b6d24e32d1bc35655876e93f9bfc
24,670,292,177,928
93647fa791502432f93c962ffe3ce02f35cf8c1c
/支付/支付文档/支付宝跨境购/cross_border_mobile_payment/cross-border_mobile_payment/WAP API codes/src/com/alipay/client/security/Signature.java
e831c3aae842a552308a23d58310329780b5953a
[]
no_license
lsjing/GitHub.Doc
https://github.com/lsjing/GitHub.Doc
fdfbf2db0f699a158d40e91cdd124817c27db116
4e4f4d0fd9b1ef4dd6a29d13096d2e3e6cc74443
refs/heads/master
2020-03-13T04:36:44.883000
2018-02-22T03:17:21
2018-02-22T03:17:21
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * Alipay.com Inc. * Copyright (c) 2005-2006 All Rights Reserved. */ package com.alipay.client.security; /** * 签名接口 * @author jun.huyj * @version $Id: Signature.java, v 0.1 2008-8-21 下午02:55:03 stone.zhangjl Exp $ */ public interface Signature { /** * 对原始数据进行签名 * * @param content 原始数据 * @param key 私钥 * @return 签名 * @throws Exception */ public String sign(String content, String key) throws Exception; /** * 验证签名 * * @param content 原始数据 * @param sign 签名 * @param key 公钥 * @return 签名验证通过 False 签名验证失败 * @throws Exception */ public boolean verify(String content, String sign, String key) throws Exception; }
GB18030
Java
809
java
Signature.java
Java
[ { "context": ".alipay.client.security;\n\n\n/**\n * 签名接口 \n * @author jun.huyj\n * @version $Id: Signature.java, v 0.1 2008-8-21 ", "end": 145, "score": 0.9988845586776733, "start": 137, "tag": "USERNAME", "value": "jun.huyj" } ]
null
[]
/** * Alipay.com Inc. * Copyright (c) 2005-2006 All Rights Reserved. */ package com.alipay.client.security; /** * 签名接口 * @author jun.huyj * @version $Id: Signature.java, v 0.1 2008-8-21 下午02:55:03 stone.zhangjl Exp $ */ public interface Signature { /** * 对原始数据进行签名 * * @param content 原始数据 * @param key 私钥 * @return 签名 * @throws Exception */ public String sign(String content, String key) throws Exception; /** * 验证签名 * * @param content 原始数据 * @param sign 签名 * @param key 公钥 * @return 签名验证通过 False 签名验证失败 * @throws Exception */ public boolean verify(String content, String sign, String key) throws Exception; }
809
0.6
0.567832
35
19.428572
21.094732
84
false
false
0
0
0
0
0
0
0.2
false
false
8
760a470753aed90f7440fd8bd80e544b8d27acfa
20,633,022,896,978
e42aa169716a87abb1ba238f574cff731d8139f3
/src/main/java/com/xzit/spring/controller/OrderController.java
93764ead23f2be0ca8322c272360ac7d49be4f92
[]
no_license
rongfan-xzit/courserDesign
https://github.com/rongfan-xzit/courserDesign
90584caaef69902c5e51f999c4fa49def2745d32
21740cb44eb75376daf9e52ccc45c0012a21785e
refs/heads/master
2022-12-20T23:29:25.374000
2020-01-08T09:58:03
2020-01-08T09:58:03
231,222,274
0
0
null
false
2022-12-16T12:13:44
2020-01-01T13:52:02
2020-01-08T09:58:23
2022-12-16T12:13:41
43,513
0
0
12
JavaScript
false
false
package com.xzit.spring.controller; import com.github.pagehelper.PageInfo; import com.xzit.spring.dto.AjaxOutput; import com.xzit.spring.dto.Datagrid; import com.xzit.spring.dto.StaffDto; import com.xzit.spring.entity.Complaints; import com.xzit.spring.entity.Order; import com.xzit.spring.entity.WorkOrder; import com.xzit.spring.entity.WorkOrder1; import com.xzit.spring.service.OrderService; import com.xzit.spring.service.WorkOrderService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.ModelAndView; import javax.validation.Valid; import java.text.ParseException; import java.util.Date; import java.util.List; @Controller @RequestMapping("/order") public class OrderController { @Autowired private OrderService orderService; /** * 跳转到处理工单页面 * @return */ @RequestMapping("/disposeOrderPage") public String disposeOrderPage() { return "disposeOrderPage"; } /** * 查看订单状态页面接口 * @return */ @GetMapping("/find") @ResponseBody public Datagrid<Order> find(@RequestParam(value = "page", defaultValue = "1", required = false) int page, @RequestParam(value = "limit", defaultValue = "10", required = false) int rows) { Datagrid<Order> staffDatagrid = new Datagrid<>(); //查询是否存在工单编号 PageInfo<Order> staffPageInfo = orderService.selectOrder(page,rows); staffDatagrid.setCode(0); staffDatagrid.setCount(staffPageInfo.getTotal()); staffDatagrid.setData(staffPageInfo.getList()); staffDatagrid.setMsg("已投诉工单信息列表"); return staffDatagrid; } // /** // * 订单处理页面查询订单编号接口 // * @return // */ // @RequestMapping("/selectOrderId/{OrderId}") // @ResponseBody // public AjaxOutput selectOrderId(@PathVariable String OrderId) // { // AjaxOutput ajaxOutput = new AjaxOutput(); // //查询是否存在订单编号 // Order order = orderService.selectOrderrInf(OrderId); // if(null != order){ // ajaxOutput.setData(order); // }else { // ajaxOutput.setMsgkey("vailderror"); // ajaxOutput.setMessage("此订单编号不存在,请重新填写!"); // } // return ajaxOutput; // } /** * 根据订单编号查看订单状态接口 * @return */ @GetMapping("/disposeOrderByOrderId/{OrderId}") @ResponseBody public Datagrid<Order> disposeOrderByOrderId(@RequestParam(value = "page", defaultValue = "1", required = false) int page, @RequestParam(value = "limit", defaultValue = "10", required = false) int rows, @PathVariable String OrderId) { Datagrid<Order> staffDatagrid = new Datagrid<>(); //查询是否存在工单编号 PageInfo<Order> staffPageInfo = orderService.selectOrderByOrderId(page,rows,OrderId); staffDatagrid.setCode(0); staffDatagrid.setCount(staffPageInfo.getTotal()); staffDatagrid.setData(staffPageInfo.getList()); staffDatagrid.setMsg("已投诉工单信息列表"); return staffDatagrid; } /** * 根据根据订单编号处理订单信息 */ @RequestMapping("/updateByOrderId/{OrderId}") @ResponseBody public AjaxOutput updateByOrderId( @PathVariable String OrderId) { AjaxOutput ajaxOutput = new AjaxOutput(); int coun = orderService.updateByOrderId(OrderId); if(coun >0){ ajaxOutput.setMsgkey("vailderror"); ajaxOutput.setMessage("订单信息处理成功!"); }else { ajaxOutput.setMsgkey("vailderror"); ajaxOutput.setMessage("订单信息处理出现错误!"); } return ajaxOutput; } /** * 用于根据订单编号删除订单信息 */ @RequestMapping("/deleteByOrderId/{OrderId}") @ResponseBody public AjaxOutput deleteByOrderId(@PathVariable String OrderId) { orderService.deleteByOrderId(OrderId); AjaxOutput ajaxOutput = new AjaxOutput(); ajaxOutput.setMsgkey("delSuccess"); ajaxOutput.setMessage("删除成功"); return ajaxOutput; } }
UTF-8
Java
4,596
java
OrderController.java
Java
[]
null
[]
package com.xzit.spring.controller; import com.github.pagehelper.PageInfo; import com.xzit.spring.dto.AjaxOutput; import com.xzit.spring.dto.Datagrid; import com.xzit.spring.dto.StaffDto; import com.xzit.spring.entity.Complaints; import com.xzit.spring.entity.Order; import com.xzit.spring.entity.WorkOrder; import com.xzit.spring.entity.WorkOrder1; import com.xzit.spring.service.OrderService; import com.xzit.spring.service.WorkOrderService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.ModelAndView; import javax.validation.Valid; import java.text.ParseException; import java.util.Date; import java.util.List; @Controller @RequestMapping("/order") public class OrderController { @Autowired private OrderService orderService; /** * 跳转到处理工单页面 * @return */ @RequestMapping("/disposeOrderPage") public String disposeOrderPage() { return "disposeOrderPage"; } /** * 查看订单状态页面接口 * @return */ @GetMapping("/find") @ResponseBody public Datagrid<Order> find(@RequestParam(value = "page", defaultValue = "1", required = false) int page, @RequestParam(value = "limit", defaultValue = "10", required = false) int rows) { Datagrid<Order> staffDatagrid = new Datagrid<>(); //查询是否存在工单编号 PageInfo<Order> staffPageInfo = orderService.selectOrder(page,rows); staffDatagrid.setCode(0); staffDatagrid.setCount(staffPageInfo.getTotal()); staffDatagrid.setData(staffPageInfo.getList()); staffDatagrid.setMsg("已投诉工单信息列表"); return staffDatagrid; } // /** // * 订单处理页面查询订单编号接口 // * @return // */ // @RequestMapping("/selectOrderId/{OrderId}") // @ResponseBody // public AjaxOutput selectOrderId(@PathVariable String OrderId) // { // AjaxOutput ajaxOutput = new AjaxOutput(); // //查询是否存在订单编号 // Order order = orderService.selectOrderrInf(OrderId); // if(null != order){ // ajaxOutput.setData(order); // }else { // ajaxOutput.setMsgkey("vailderror"); // ajaxOutput.setMessage("此订单编号不存在,请重新填写!"); // } // return ajaxOutput; // } /** * 根据订单编号查看订单状态接口 * @return */ @GetMapping("/disposeOrderByOrderId/{OrderId}") @ResponseBody public Datagrid<Order> disposeOrderByOrderId(@RequestParam(value = "page", defaultValue = "1", required = false) int page, @RequestParam(value = "limit", defaultValue = "10", required = false) int rows, @PathVariable String OrderId) { Datagrid<Order> staffDatagrid = new Datagrid<>(); //查询是否存在工单编号 PageInfo<Order> staffPageInfo = orderService.selectOrderByOrderId(page,rows,OrderId); staffDatagrid.setCode(0); staffDatagrid.setCount(staffPageInfo.getTotal()); staffDatagrid.setData(staffPageInfo.getList()); staffDatagrid.setMsg("已投诉工单信息列表"); return staffDatagrid; } /** * 根据根据订单编号处理订单信息 */ @RequestMapping("/updateByOrderId/{OrderId}") @ResponseBody public AjaxOutput updateByOrderId( @PathVariable String OrderId) { AjaxOutput ajaxOutput = new AjaxOutput(); int coun = orderService.updateByOrderId(OrderId); if(coun >0){ ajaxOutput.setMsgkey("vailderror"); ajaxOutput.setMessage("订单信息处理成功!"); }else { ajaxOutput.setMsgkey("vailderror"); ajaxOutput.setMessage("订单信息处理出现错误!"); } return ajaxOutput; } /** * 用于根据订单编号删除订单信息 */ @RequestMapping("/deleteByOrderId/{OrderId}") @ResponseBody public AjaxOutput deleteByOrderId(@PathVariable String OrderId) { orderService.deleteByOrderId(OrderId); AjaxOutput ajaxOutput = new AjaxOutput(); ajaxOutput.setMsgkey("delSuccess"); ajaxOutput.setMessage("删除成功"); return ajaxOutput; } }
4,596
0.64911
0.64677
131
31.587786
25.53216
126
false
false
0
0
0
0
0
0
0.526718
false
false
8