blob_id
stringlengths 40
40
| language
stringclasses 1
value | repo_name
stringlengths 5
132
| path
stringlengths 2
382
| src_encoding
stringclasses 34
values | length_bytes
int64 9
3.8M
| score
float64 1.5
4.94
| int_score
int64 2
5
| detected_licenses
listlengths 0
142
| license_type
stringclasses 2
values | text
stringlengths 9
3.8M
| download_success
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|
5f2b9d418d89d6cf0f64c7e91083593c8442359b
|
Java
|
thuan-nguyenduc/mb-web-browser-for-android
|
/mb-browser/app/src/main/java/com/xlab/vbrowser/utils/Browsers.java
|
UTF-8
| 9,692
| 2.015625
| 2
|
[
"MIT"
] |
permissive
|
/* -*- Mode: Java; c-basic-offset: 4; tab-width: 20; indent-tabs-mode: nil; -*-
Copyright by MonnyLab */
package com.xlab.vbrowser.utils;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Helpful tools for dealing with other browsers.
*/
public class Browsers {
public enum KnownBrowser {
FIREFOX("org.mozilla.firefox"),
FIREFOX_BETA("org.mozilla.firefox_beta"),
FIREFOX_AURORA("org.mozilla.fennec_aurora"),
FIREFOX_NIGHTLY("org.mozilla.fennec"),
CHROME("com.android.chrome"),
CHROME_BETA("com.chrome.beta"),
CHROME_DEV("com.chrome.dev"),
CHROME_CANARY("com.chrome.canary"),
OPERA("com.opera.browser"),
OPERA_BETA("com.opera.browser.beta"),
OPERA_MINI("com.opera.mini.native"),
OPERA_MINI_BETA("com.opera.mini.native.beta"),
UC_BROWSER("com.UCMobile.intl"),
UC_BROWSER_MINI("com.uc.browser.en"),
ANDROID_STOCK_BROWSER("com.android.browser"),
SAMSUNG_INTERNET("com.sec.android.app.sbrowser"),
DOLPHIN_BROWSER("mobi.mgeek.TunnyBrowser"),
BRAVE_BROWSER("com.brave.browser"),
LINK_BUBBLE("com.linkbubble.playstore"),
ADBLOCK_BROWSER("org.adblockplus.browser"),
CHROMER("arun.com.chromer"),
FLYNX("com.flynx"),
GHOSTERY_BROWSER("com.ghostery.android.ghostery");
public final String packageName;
KnownBrowser(String packageName) {
this.packageName = packageName;
}
}
// Sample URL handled by traditional web browsers. Used to find installed (basic) web browsers.
public static final String TRADITIONAL_BROWSER_URL = "http://google.com";
private final Map<String, ActivityInfo> browsers;
private final ActivityInfo defaultBrowser;
// This will contain installed firefox branded browser ordered by priority from Firefox,
// Firefox_Beta, Firefox Aurora and Firefox_Nightly. If multiple firefox branded browser is
// installed then higher priority one will be stored here
private ActivityInfo firefoxBrandedBrowser;
public Browsers(Context context, @NonNull String url) {
final PackageManager packageManager = context.getPackageManager();
final Uri uri = Uri.parse(url);
final Map<String, ActivityInfo> browsers = resolveBrowsers(context, packageManager, uri);
// If there's a default browser set then modern Android systems won't return other browsers
// anymore when using queryIntentActivities(). That's annoying and our only option is
// to go through a list of known browsers and see if anyone of them is installed and
// wants to handle our URL.
findKnownBrowsers(packageManager, browsers, uri);
this.browsers = browsers;
this.defaultBrowser = findDefault(context, packageManager, uri);
this.firefoxBrandedBrowser = findFirefoxBrandedBrowser();
}
private ActivityInfo findFirefoxBrandedBrowser() {
if (browsers.containsKey(KnownBrowser.FIREFOX.packageName)) {
return browsers.get(KnownBrowser.FIREFOX.packageName);
} else if (browsers.containsKey(KnownBrowser.FIREFOX_BETA.packageName)) {
return browsers.get(KnownBrowser.FIREFOX_BETA.packageName);
} else if (browsers.containsKey(KnownBrowser.FIREFOX_AURORA.packageName)) {
return browsers.get(KnownBrowser.FIREFOX_AURORA.packageName);
} else if (browsers.containsKey(KnownBrowser.FIREFOX_NIGHTLY.packageName)) {
return browsers.get(KnownBrowser.FIREFOX_NIGHTLY.packageName);
}
return null;
}
private Map<String, ActivityInfo> resolveBrowsers(Context context, PackageManager packageManager, @NonNull Uri uri) {
final Map<String, ActivityInfo> browsers = new HashMap<>();
final Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(uri);
final List<ResolveInfo> infos = packageManager.queryIntentActivities(intent, 0);
for (ResolveInfo info : infos) {
if (!context.getPackageName().equals(info.activityInfo.packageName)) {
browsers.put(info.activityInfo.packageName, info.activityInfo);
}
}
return browsers;
}
private void findKnownBrowsers(PackageManager packageManager, Map<String, ActivityInfo> browsers, @NonNull Uri uri) {
for (final KnownBrowser browser : KnownBrowser.values()) {
if (browsers.containsKey(browser.packageName)) {
continue;
}
// resolveActivity() can be slow if the package isn't installed (e.g. 200ms on an N6 with a bad WiFi connection).
// Hence we query if the package is installed first, and only call resolveActivity for installed packages.
// getPackageInfo() is fast regardless of a package being installed
try {
// We don't need the result, we only need to detect when the package doesn't exist
packageManager.getPackageInfo(browser.packageName, 0);
} catch (PackageManager.NameNotFoundException e) {
continue;
}
final Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(uri);
intent.setPackage(browser.packageName);
final ResolveInfo info = packageManager.resolveActivity(intent, 0);
if (info == null || info.activityInfo == null) {
continue;
}
if (!info.activityInfo.exported) {
continue;
}
browsers.put(info.activityInfo.packageName, info.activityInfo);
}
}
private ActivityInfo findDefault(Context context, PackageManager packageManager, @NonNull Uri uri) {
final Intent intent = new Intent(Intent.ACTION_VIEW, uri);
final ResolveInfo resolveInfo = packageManager.resolveActivity(intent, 0);
if (resolveInfo == null || resolveInfo.activityInfo == null) {
return null;
}
if (!resolveInfo.activityInfo.exported) {
// We are not allowed to launch this activity.
return null;
}
if (!browsers.containsKey(resolveInfo.activityInfo.packageName)
&& !resolveInfo.activityInfo.packageName.equals(context.getPackageName())) {
// This default browser wasn't returned when we asked for *all* browsers. It's likely
// that this is actually the resolver activity (aka intent chooser). Let's ignore it.
return null;
}
return resolveInfo.activityInfo;
}
/**
* Does this user have a default browser that is not Firefox (release) or Focus (this build).
*/
public boolean hasThirdPartyDefaultBrowser(Context context) {
return defaultBrowser != null
&& !defaultBrowser.packageName.equals(KnownBrowser.FIREFOX.packageName)
&& !(firefoxBrandedBrowser != null && defaultBrowser.packageName.equals(firefoxBrandedBrowser.packageName))
&& !defaultBrowser.packageName.equals(context.getPackageName());
}
/**
* Is (regular) the default browser of the user?
*/
public boolean isFirefoxDefaultBrowser() {
if (defaultBrowser == null) {
return false;
}
return defaultBrowser.packageName.equals(KnownBrowser.FIREFOX.packageName)
|| defaultBrowser.packageName.equals(KnownBrowser.FIREFOX_BETA.packageName)
|| defaultBrowser.packageName.equals(KnownBrowser.FIREFOX_AURORA.packageName)
|| defaultBrowser.packageName.equals(KnownBrowser.FIREFOX_NIGHTLY.packageName);
}
public @Nullable ActivityInfo getDefaultBrowser() {
return defaultBrowser;
}
/**
* Does this user have browsers installed that are not Focus, Firefox or the default browser?
*/
public boolean hasMultipleThirdPartyBrowsers(Context context) {
if (browsers.size() > 1) {
// There are more than us and Firefox.
return true;
}
for (ActivityInfo info : browsers.values()) {
if (info != defaultBrowser
&& !info.packageName.equals(KnownBrowser.FIREFOX.packageName)
&& !info.packageName.equals(context.getPackageName())) {
// There's at least one browser that is not Focus or Firefox and also not the
// default browser.
return true;
}
}
return false;
}
public boolean isInstalled(KnownBrowser browser) {
return browsers.containsKey(browser.packageName);
}
/**
* Is *this* application the default browser?
*/
public boolean isDefaultBrowser(Context context) {
return defaultBrowser != null && context.getPackageName().equals(defaultBrowser.packageName);
}
public ActivityInfo[] getInstalledBrowsers() {
final Collection<ActivityInfo> collection = browsers.values();
return collection.toArray(new ActivityInfo[collection.size()]);
}
public boolean hasFirefoxBrandedBrowserInstalled() {
return firefoxBrandedBrowser != null;
}
public ActivityInfo getFirefoxBrandedBrowser() {
return firefoxBrandedBrowser;
}
}
| true
|
862b2ccbc476237bcf0dc54e23f19c8272f7f33b
|
Java
|
portungkeat/AutoLockPhone
|
/app/src/main/java/com/example/portk/autolockphone/ScrollingActivity.java
|
UTF-8
| 2,149
| 2.03125
| 2
|
[] |
no_license
|
package com.example.portk.autolockphone;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Intent;
import android.os.Bundle;
import android.os.PowerManager;
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.View;
import android.view.Menu;
import android.view.MenuItem;
public class ScrollingActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scrolling);
DevicePolicyManager dpm = (DevicePolicyManager) getSystemService(DEVICE_POLICY_SERVICE);
ComponentName componentName = new ComponentName(this, AutoLockService.class);
if (!dpm.isAdminActive(componentName)){
Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, componentName);
intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, "自动锁屏");
startActivity(intent);
}
FloatingActionButton start= (FloatingActionButton) this.findViewById(R.id.start);
FloatingActionButton stop= (FloatingActionButton) this.findViewById(R.id.stop);
start.setOnClickListener(new clickListent());
stop.setOnClickListener(new clickListent());
stop.setEnabled(false);
}
class clickListent implements View.OnClickListener {
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.start:
Intent startIntent=new Intent(v.getContext(),AutoLockService.class);
startService(startIntent);
break;
case R.id.stop:
Intent stopIntent=new Intent(v.getContext(),AutoLockService.class);
stopService(stopIntent);
break;
}
}
}
}
| true
|
48cc06f5b1b87a129241d364b9f71971c8b3aede
|
Java
|
huijia0211/design_pattern
|
/src/main/java/com/huijia/creational/builder/v3/Test.java
|
UTF-8
| 318
| 2.140625
| 2
|
[] |
no_license
|
package com.huijia.creational.builder.v3;
public class Test {
public static void main(String[] args) {
Course course = Course.newBuilder().courseName("课程名").coursePPT("课程PPT").courseVideo("课程").courseArticle("课程").courseQA("课程").build();
System.out.println(course);
}
}
| true
|
52f74fafcd3eb91777006a30f63d35635a5ba2cb
|
Java
|
whoamipl/spring-family
|
/src/main/java/com/example/springdemo/domain/Parent.java
|
UTF-8
| 1,584
| 2.6875
| 3
|
[] |
no_license
|
package com.example.springdemo.domain;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import java.util.List;
public class Parent {
private Parent myMom;
private Parent myDad;
private Parent myMomInLaw;
private Parent myDadInLaw;
@Autowired
private List<Child> list;
public String getChild() {
return list
.stream()
.map(childName -> childName.getFirstName() + " ")
.reduce("Dzieci: ", (acc, name) -> acc + name);
}
private String firstName;
private String yob;
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getFirstName() {
return firstName;
}
public void setYob(String yob) {
this.yob = yob;
}
public String getYob() {
return yob;
}
public void setMyMom(Parent myMom) {
this.myMom = myMom;
}
public Parent getMyMom() {
return myMom;
}
public void setMyDad(Parent myDad) {
this.myDad = myDad;
}
public Parent getMyDad() {
return myDad;
}
public void setMyMomInLaw(Parent myMomInLaw) {
this.myMomInLaw = myMomInLaw;
}
public Parent getMyMomInLaw() {
return myMomInLaw;
}
public void setMyDadInLaw(Parent myDadInLaw) {
this.myDadInLaw = myDadInLaw;
}
public Parent getMyDadInLaw() {
return myDadInLaw;
}
}
| true
|
b3c53404e7152274de150e3c58e5e6b3edd33d77
|
Java
|
amruteshqa/automation
|
/automation/src/keywordDriverFramework/Flib.java
|
UTF-8
| 424
| 2.515625
| 3
|
[] |
no_license
|
package keywordDriverFramework;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
public class Flib {
public String readProperyFile(String proppath,String key) throws IOException
{
FileInputStream fis = new FileInputStream(proppath);
Properties prop = new Properties();
prop.load(fis);
String data = prop.getProperty(key);
return data;
}
}
| true
|
09ee8926e033f74e8e0cca41edcac0bea877f5e5
|
Java
|
a-baluevsky/ACC.RU.IAC.CUD
|
/ru.spb.iac.cud/user-web/src/main/java/ru/spb/iac/cud/uarm/web/context/reg/UserOrgManBean.java
|
WINDOWS-1251
| 2,480
| 1.84375
| 2
|
[] |
no_license
|
package ru.spb.iac.cud.uarm.web.context.reg;
import java.io.Serializable;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ru.spb.iac.cud.uarm.ejb.context.reg.UserOrgManEJB;
import ru.spb.iac.cud.uarm.ejb.entity.JournAppOrgManagerBssT;
import ru.spb.iac.cud.uarm.util.CUDUserConsoleConstants;
import ru.spb.iac.cud.uarm.web.context.user.UserSessionBean;
@ManagedBean(name = "userOrgManBean")
@RequestScoped
public class UserOrgManBean implements Serializable {
private static final Logger LOGGER = LoggerFactory.getLogger(UserOrgManBean.class);
@EJB(beanName = "CUDUserConsole-ejb.jar#UserOrgManEJB")
private UserOrgManEJB userOrgManEJB;
@ManagedProperty("#{userSessionBean}")
private UserSessionBean userSessionBean;
private static final long serialVersionUID = 1L;
private String reason;
private Long roleCUD;
public void action() {
try {
LOGGER.debug("userOrgManBean:action:01");
HttpSession hs = (HttpSession)FacesContext.getCurrentInstance().getExternalContext().getSession(false);
Long authUserID = (Long) hs.getAttribute(CUDUserConsoleConstants.authUserID);
JournAppOrgManagerBssT t1 = new JournAppOrgManagerBssT();
t1.setModeExec(1L); //ADD
t1.setStatus(0L);
//
t1.setAcUsersKnlT2Long(authUserID);
//
t1.setAcUsersKnlT1Long(authUserID);
userOrgManEJB.save(t1);
FacesContext
.getCurrentInstance()
.getExternalContext()
.redirect(
((HttpServletRequest) FacesContext
.getCurrentInstance().getExternalContext()
.getRequest()).getContextPath()
+ "/context/app/org_man/list.xhtml");
} catch (Exception e) {
LOGGER.error("userOrgManBean:action:error:", e);
}
}
public String getReason() {
return reason;
}
public void setReason(String reason) {
this.reason = reason;
}
public UserSessionBean getUserSessionBean() {
return userSessionBean;
}
public void setUserSessionBean(UserSessionBean userSessionBean) {
this.userSessionBean = userSessionBean;
}
public Long getRoleCUD() {
return roleCUD;
}
public void setRoleCUD(Long roleCUD) {
this.roleCUD = roleCUD;
}
}
| true
|
d47f91c44889a3cac57f0613a759755c2ea42e2a
|
Java
|
ZZZxm/Charlie-Chocolate-Factory
|
/src/team/charliechocolatefactory/person/visitor/Visitor.java
|
UTF-8
| 2,943
| 3.0625
| 3
|
[] |
no_license
|
package team.charliechocolatefactory.person.visitor;
import team.charliechocolatefactory.person.Person;
import team.charliechocolatefactory.person.visitor.limit.Context;
import team.charliechocolatefactory.scene.Scene;
import team.charliechocolatefactory.scene.publicarea.PublicArea;
/**
* @author Brian.Z
* @project chocolateFactory
* @classname Visitor
* @description visitors of the chocolate factory, who can visit the exhibition hall and the exploration hall
* @date 2020/11/7 18:26
*/
public class Visitor extends Person {
public String identity = "Visitor";
public int visitCode;
private Context visitLimit;
public Visitor(String name, int age, Sex sex) {
super(name, age, sex);
String[] persons = {this.identity};
String[] publicAreas = {"publicArea", "experienceRoom", "exhibitionRoom"};
this.visitLimit = new Context(persons, publicAreas);
}
public Visitor(String name, int age, Sex sex, int visitCode) {
super(name, age, sex);
String[] persons = {this.identity};
String[] publicAreas = {"publicArea", "experienceRoom", "exhibitionRoom"};
this.visitLimit = new Context(persons, publicAreas);
this.visitCode = visitCode;
}
/**
* visit a public area
* However, a visitor can only be allowed to visit some place when it is not full.
*
* @param dest destination
*/
public boolean visit(PublicArea dest) {
if (!dest.isFull()) {
System.out.println("Visitor " + this.name + "visits" + dest.toString());
this.moveTo(dest);
return true;
} else {
System.out.println("Sorry, the" + dest.toString() + "is already full.");
return false;
}
}
public boolean canEnter(String dest) {
String move = this.identity + " enter " + dest;
if (this.visitLimit.canEnter(move)) {
System.out.println(this.name + " can enter" + dest);
return true;
} else {
System.out.println("Sorry! " + this.name + " cannot enter " + dest);
return false;
}
}
/**
* Visitor can only visit the public areas.
*
* @param dest destination
*/
@Override
public void moveTo(Scene dest) {
if (this.canEnter(dest.toString())) {
this.location = dest;
System.out.println(this.identity + " " + this.name + " moves to " + dest.toString());
} else {
System.out.println("Sorry, " + this.identity + " " + this.name + "can 't go to" + dest.toString());
}
}
public int getVisitCode() {
return visitCode;
}
/**
* set the initial asset of the visitor;
*/
@Override
protected void setInitialAsset() {
this.asset = 1000;
}
@Override
public String toString() {
return "class Visitor extends Person";
}
}
| true
|
8bfbabba7f90a23b9a75445dafdd3ed8a5f3f2ff
|
Java
|
danielperez9430/Third-party-Telegram-Apps-Spy
|
/Talagram/com/google/android/gms/internal/firebase_messaging/zza.java
|
UTF-8
| 2,664
| 1.945313
| 2
|
[] |
no_license
|
package com.google.android.gms.internal.firebase_messaging;
import java.io.PrintStream;
public final class zza {
final class com.google.android.gms.internal.firebase_messaging.zza$zza extends zzb {
com.google.android.gms.internal.firebase_messaging.zza$zza() {
super();
}
public final void zza(Throwable arg1, Throwable arg2) {
}
}
private static final zzb zza;
private static final int zzb;
static {
com.google.android.gms.internal.firebase_messaging.zza$zza v2_3;
zzf v2_1;
Integer v1;
int v0 = 1;
try {
v1 = zza.zza();
if(v1 == null) {
goto label_11;
}
}
catch(Throwable v2) {
v1 = null;
goto label_23;
}
try {
if(v1.intValue() >= 19) {
v2_1 = new zzf();
goto label_42;
}
label_11:
if((Boolean.getBoolean("com.google.devtools.build.android.desugar.runtime.twr_disable_mimic") ^ 1) != 0) {
zze v2_2 = new zze();
goto label_42;
}
v2_3 = new com.google.android.gms.internal.firebase_messaging.zza$zza();
goto label_42;
label_10:
}
catch(Throwable v2) {
goto label_10;
}
label_23:
PrintStream v3 = System.err;
String v4 = com.google.android.gms.internal.firebase_messaging.zza$zza.class.getName();
StringBuilder v6 = new StringBuilder(String.valueOf(v4).length() + 132);
v6.append("An error has occured when initializing the try-with-resources desuguring strategy. The default strategy ");
v6.append(v4);
v6.append("will be used. The error is: ");
v3.println(v6.toString());
v2.printStackTrace(System.err);
v2_3 = new com.google.android.gms.internal.firebase_messaging.zza$zza();
label_42:
zza.zza = ((zzb)v2_1);
if(v1 == null) {
}
else {
v0 = v1.intValue();
}
zza.zzb = v0;
}
private static Integer zza() {
Object v0 = null;
try {
return Class.forName("android.os.Build$VERSION").getField("SDK_INT").get(v0);
}
catch(Exception v1) {
System.err.println("Failed to retrieve value from android.os.Build$VERSION.SDK_INT due to the following exception.");
v1.printStackTrace(System.err);
return ((Integer)v0);
}
}
public static void zza(Throwable arg1, Throwable arg2) {
zza.zza.zza(arg1, arg2);
}
}
| true
|
6501406dddd6e51268486944afe1ba3e3e4c7790
|
Java
|
weiloo126/javaDesignPattern
|
/src/main/java/com/sample/javaDesignMode/creational/factoryMethod/staticFactoryMethod/SendFactory.java
|
UTF-8
| 529
| 2.546875
| 3
|
[] |
no_license
|
package com.sample.javaDesignMode.creational.factoryMethod.staticFactoryMethod;
import com.sample.javaDesignMode.creational.factoryMethod.MailSender;
import com.sample.javaDesignMode.creational.factoryMethod.Sender;
import com.sample.javaDesignMode.creational.factoryMethod.SmsSender;
/**
*
* @date 2017年11月14日
*/
public class SendFactory {
public static Sender produceMail(){
return new MailSender();
}
public static Sender produceSms(){
return new SmsSender();
}
}
| true
|
d77f30cf78ebaae8c4f6b0db8b08c1ceb2123961
|
Java
|
Clowdtech/Mpositive-App
|
/src/app/src/main/java/clowdtech/mpositive/areas/reporting/transaction/adapters/TransactionSummaryAdapter.java
|
UTF-8
| 2,816
| 2.3125
| 2
|
[] |
no_license
|
package clowdtech.mpositive.areas.reporting.transaction.adapters;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.List;
import clowdtech.mpositive.R;
import clowdtech.mpositive.areas.reporting.transaction.viewModels.TransactionListItemViewModel;
public class TransactionSummaryAdapter extends BaseAdapter {
private List<TransactionListItemViewModel> _originalData;
private final LayoutInflater _inflater;
private int _unselectedTextColour;
private int _refundedTextColour;
public TransactionSummaryAdapter(Context context, List<TransactionListItemViewModel> _originalData) {
this._originalData = _originalData;
_inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Resources _resources = context.getResources();
_refundedTextColour = Color.RED;
_unselectedTextColour = _resources.getColor(R.color.font_primary);
}
public int getCount() {
return _originalData.size();
}
public Object getItem(int position) {
return _originalData.get(position);
}
public long getItemId(int position) {
return _originalData.get(position).getId();
}
public static class ViewHolder {
public TextView text;
public TextView total;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
ViewHolder holder;
if (convertView == null) {
vi = _inflater.inflate(R.layout.reporting_transaction_row_template, parent, false);
holder = new ViewHolder();
holder.text = (TextView) vi.findViewById(R.id.reporting_row_text);
holder.total = (TextView) vi.findViewById(R.id.reporting_row_value);
vi.setTag(holder);
} else {
holder = (ViewHolder) vi.getTag();
}
TransactionListItemViewModel sku = _originalData.get(position);
setViewStyle(holder, sku.isRefunded());
holder.text.setText(sku.getTitle());
holder.total.setText(sku.getInfo());
return vi;
}
private void setViewStyle(ViewHolder holder, Boolean refunded) {
// set style of unselected but refunded
if (refunded) {
holder.text.setTextColor(_refundedTextColour);
holder.total.setTextColor(_refundedTextColour);
return;
}
// set style of unselected
holder.text.setTextColor(_unselectedTextColour);
holder.total.setTextColor(_unselectedTextColour);
}
}
| true
|
3ab1960cbbfdef5fe670320e693a07297e6c88f5
|
Java
|
suzi2001/stocktracker
|
/StocksTracker/StocksTracker/src/main/java/stocks/tracker/stocks_tracker/printer/EmptyCompareResultPrinter.java
|
UTF-8
| 273
| 1.96875
| 2
|
[] |
no_license
|
package stocks.tracker.stocks_tracker.printer;
public class EmptyCompareResultPrinter extends CompareResultPrinter {
public EmptyCompareResultPrinter() {
super();
}
@Override
public void printCompareResult() {
//Doesn't print anything
}
}
| true
|
7504dbec26ce230eeb6b377c169f586402af922a
|
Java
|
gitter-badger/SwimCoachOrganizer
|
/src/main/java/ch/tiim/sco/lenex/LenexLoadTask.java
|
UTF-8
| 888
| 2.609375
| 3
|
[] |
no_license
|
package ch.tiim.sco.lenex;
import ch.tiim.sco.lenex.model.Lenex;
import ch.tiim.sco.util.ByteCountingInputStream;
import javafx.concurrent.Task;
import java.nio.file.Path;
public class LenexLoadTask extends Task<Lenex> {
private final Path path;
public LenexLoadTask(Path path) {
this.path = path;
}
@Override
protected Lenex call() throws Exception {
LenexParser parser = new LenexParser();
updateMessage("Parsing LENEX");
Lenex lenex = parser.read(path, new Updater());
updateMessage("Done");
return lenex;
}
private class Updater implements ByteCountingInputStream.Updater {
private long max = 1;
@Override
public void update(long i) {
updateProgress(i, max);
}
@Override
public void setMax(long i) {
max = i;
}
}
}
| true
|
df42eea41a9da8cccbe7948a3c6e4d115bd48a76
|
Java
|
DavidLuna0/ads-metodologia
|
/src/main/java/br/com/metodologia/controllers/ProfessorController.java
|
UTF-8
| 1,377
| 2.125
| 2
|
[] |
no_license
|
package br.com.metodologia.controllers;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import br.com.metodologia.models.Professor;
import br.com.metodologia.repositories.ProfessorRepository;
@Controller
public class ProfessorController {
@Autowired
private ProfessorRepository pr;
@RequestMapping(value="/professor", method=RequestMethod.POST)
public String cadastrarAluno(@Valid Professor professor , BindingResult result, RedirectAttributes attributes) {
pr.save(professor);
return "redirect:/professor";
}
@RequestMapping("/professor")
public ModelAndView listaAlunos() {
ModelAndView mv = new ModelAndView("cadProfessor");
Iterable<Professor> professores = pr.findAll();
mv.addObject("professores", professores);
return mv;
}
@RequestMapping("/deleteP")
public String deletarProfessor(long id) {
Professor professor = pr.findById(id);
pr.delete(professor);
return "redirect:/professor";
}
}
| true
|
864f93e5cbf207a3aad08590fa8fe49d85c5c3e9
|
Java
|
nanthiniprabakaran/ecommerence-backend
|
/src/main/java/com/niit/userdao/CustomerDAO.java
|
UTF-8
| 265
| 2.15625
| 2
|
[] |
no_license
|
package com.niit.userdao;
import com.niit.model.Customer;
import com.niit.model.ShippingAddress;
public interface CustomerDAO {
void registerCustomer(Customer customer);
boolean isEmailUnique(String email);
ShippingAddress getShippingAddress(int id);
}
| true
|
c383226677e867b97e7ae30e38fe8223a6d2fbf6
|
Java
|
YanaSlukhai/msdiploma
|
/src/main/java/com/diploma/jenatriplestoreservice/repositories/TSRepositoryJenaImpl.java
|
UTF-8
| 5,613
| 2.28125
| 2
|
[] |
no_license
|
package com.diploma.jenatriplestoreservice.repositories;
import com.diploma.jenatriplestoreservice.domain.OntologyClass;
import com.diploma.jenatriplestoreservice.domain.RDFResource;
import org.apache.jena.ontology.OntClass;
import org.apache.jena.ontology.OntModel;
import org.apache.jena.ontology.OntModelSpec;
import org.apache.jena.ontology.TransitiveProperty;
import org.apache.jena.query.*;
import org.apache.jena.rdf.model.*;
import org.apache.jena.tdb.TDBFactory;
import org.apache.jena.update.*;
import org.apache.jena.util.FileManager;
import org.apache.jena.util.iterator.ExtendedIterator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;
@SuppressWarnings("deprecation")
@Repository
public class TSRepositoryJenaImpl implements TSRepository{
private Dataset dataset;
private static final Logger log = LoggerFactory.getLogger( TSRepositoryJenaImpl.class );
public TSRepositoryJenaImpl(){
dataset = TDBFactory.createDataset("triplestore");
log.info("Dataset was successfully created");
}
public void loadOntology(String path)
{
Model model = null;
dataset.begin( ReadWrite.WRITE );
try
{
model = dataset.getDefaultModel();
FileManager.get().readModel( model, path );
dataset.commit();
}
finally
{
log.info("Loading of " + path + " ontology is complete ");
dataset.end();
}
}
public List<RDFResource> listAllOntResources(){
dataset.begin( ReadWrite.READ );
List<RDFResource> allOntResources = new ArrayList<>();
try {
Model model = dataset.getDefaultModel();
ResIterator it = model.listSubjects();
while (it.hasNext()) {
Resource node = it.next();
List<String> properties = new ArrayList<String>();
StmtIterator stmtIt = node.listProperties();
while (stmtIt.hasNext()) {
Statement st = stmtIt.next();
properties.add(st.getObject().toString());
}
RDFResource nextRDFresource = new RDFResource(node.asResource().getURI(),
node.asResource().getNameSpace(),
properties);
node.asResource().getNameSpace();
allOntResources.add(nextRDFresource);
}
dataset.commit() ;
} finally {
dataset.end() ;
}
return allOntResources;
}
public String execSPARQLReadQuery(String sparqlQuery) {
dataset.begin(ReadWrite.READ);
QueryExecution qExec = QueryExecutionFactory.create(sparqlQuery, dataset);
ResultSet rs = qExec.execSelect();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ResultSetFormatter.outputAsJSON(outputStream, rs);
String jsonRS = new String(outputStream.toByteArray());
dataset.commit();
return jsonRS;
}
public void execSPARQLUpdateQuery(String sparqlQuery) {
dataset.begin(ReadWrite.WRITE);
try {
GraphStore graphStore = GraphStoreFactory.create(dataset);
UpdateRequest request = UpdateFactory.create(sparqlQuery);
UpdateProcessor proc = UpdateExecutionFactory.create(request, graphStore);
proc.execute();
dataset.commit();
} finally {
dataset.end();
}
}
public List<String> listTransitiveProperties() {
dataset.begin(ReadWrite.READ);
List transitiveProps = new ArrayList<String>();
try {
Model model = dataset.getDefaultModel();
OntModel ontModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_DL_MEM, model);
ExtendedIterator<TransitiveProperty> iterator = ontModel.listTransitiveProperties();
while (iterator.hasNext()) {
TransitiveProperty transProp = iterator.next();
transitiveProps.add(transProp.getURI());
}
dataset.commit() ;
} finally {
dataset.end() ;
}
return transitiveProps;
}
public List<OntologyClass> listOntClasses() {
dataset.begin(ReadWrite.READ);
List <OntologyClass> ontClasses = new ArrayList<OntologyClass>();
try {
Model model = dataset.getDefaultModel();
OntModel ontModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_DL_MEM, model);
ExtendedIterator<OntClass> iterator = ontModel.listClasses();
while (iterator.hasNext()) {
OntClass ontClass = iterator.next();
ExtendedIterator<OntClass> listSubClasses= ontClass.listSubClasses();
List <String> classInstances = new ArrayList<>();
while (listSubClasses.hasNext()){
OntClass subclass = listSubClasses.next();
classInstances.add(subclass.getURI());
}
OntologyClass domainOntologyClass = new OntologyClass(ontClass.getURI(), classInstances);
ontClasses.add(domainOntologyClass);
}
dataset.commit() ;
} finally {
dataset.end() ;
}
return ontClasses;
}
}
| true
|
436e2656a241c767214e9e9416db5eed5f22d7d0
|
Java
|
smartinternz02/SPS-10649-Car-Resale-Value-Prediction
|
/ConvertData.java
|
UTF-8
| 1,054
| 3.359375
| 3
|
[] |
no_license
|
import java.util.*;
import java.lang.*;
import java.io.*;
public class ConvertData {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new FileReader("E:/oracleProject/test-data_b.csv"));
BufferedWriter bw = new BufferedWriter(new FileWriter("E:/oracleProject/test_data_b.csv"));
String line = "";
while ((line = br.readLine()) != null) {
String[] values = line.split(",", -1);
// make an array out of line
String writableString = "";
//initial string which will be the final output for the row
ArrayList al = new ArrayList();
// use array list because can edit array and modify size easily
for (String element : values) {
if (element==null || element.length()==0) {
al.add("0");
} else {
al.add(element);
}
}
for (Object s : al){ // add commas between each element of arraylist
writableString += s + ",";
}
writableString = writableString.substring(0, // remove last comma
writableString.length() - 1);
bw.write(writableString + "\n");
//writes the line and carriage return
}
br.close();
bw.close();
}
}
| true
|
b1d4d60043c9424254f263720cc1915425e406ad
|
Java
|
markandeyulu/manoj-learnings
|
/Spring classes backup/EcommerceApp-11_27/src/main/java/com/amazon/app/App.java
|
UTF-8
| 1,468
| 2.796875
| 3
|
[] |
no_license
|
package com.amazon.app;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args )
{
//ApplicationContext context = new AnnotationConfigApplicationContext(Config.class);
//Profiling - which set of objects I want to load in memory in container
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.getEnvironment().setActiveProfiles("production"); // to set the profile by coding. check AnnotationConfigApplicationContext is used instead interface.
// you can choose any number of profiles by comma for different instances. testing,production, etc. If you give multiple profile, you will have multiple objects for that profiled objects created in memory.
//that time if you want to use autowire you have to use qualifier with bean name to get the object you need.
context.register(Config.class); // order is very important. first plain object. set profile and register them to class. then refresh.
context.refresh(); // Between code and property file, compiler will give you priority to code.
ProductApp productApp = context.getBean(ProductApp.class);//you cant use @autowire in main since object should have been created before
productApp.displayAllProductDetails();
}
}
| true
|
b4e1db73024319ca92d3da1a8fe97340ddb68714
|
Java
|
AKSHAYAUOTE1/repository2
|
/src/logical/CompareString.java
|
UTF-8
| 573
| 3.03125
| 3
|
[] |
no_license
|
package logical;
import java.util.HashMap;
import java.util.Set;
public class CompareString {
public static void main(String[] args) {
String[]ar = {"java","jdbc","c","python","c"};
HashMap<String, Integer> str = new HashMap<String,Integer>();
for (String str2 : ar) {
if(str.containsKey(str2)) {
str.put(str2, str.get(str2)+1);
}
else {
str.put(str2, 1);
}
Set<String> str3 = str.keySet();
for (String str4 : str3) {
if(str.get(str4)>1) {
System.out.println(str4);
}
}
}
}
}
| true
|
9eb08746b1a891edb624f3dca1ade2acace75aee
|
Java
|
june97y/training001_mission003
|
/src/main/java/com/miss3/mission_003/Mission003Application.java
|
UTF-8
| 591
| 2.015625
| 2
|
[] |
no_license
|
package com.miss3.mission_003;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import java.sql.DriverManager;
import java.sql.SQLException;
@SpringBootApplication
public class Mission003Application
{
public static void main(String[] args)
{
/*String url = "jdbc";
String user = "";
String pwd = "";
try
{
Connection myConn = DriverManager.getConnection(url, user, pwd);
}
catch(SQLException e)
{
e.printStackTrace();
}*/
SpringApplication.run(Mission003Application.class, args);
}
}
| true
|
56e990624db5a9a118150c912bad825e5ce3d514
|
Java
|
amit93jais/jms-poc
|
/ResponseOrder/src/main/java/com/poc/processor/OrderProcessor.java
|
UTF-8
| 949
| 2.375
| 2
|
[] |
no_license
|
package com.poc.processor;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.poc.bean.Part;
import com.poc.repository.OrderRepository;
/**
*
* @author amitjaiswal
*
*This is processor for OrderProcessorRouteBuilder.This processor class will de-serialize
* the bean coming from queue.
*/
@Component
public class OrderProcessor implements Processor {
static final Logger log = LoggerFactory.getLogger(OrderProcessor.class);
@Autowired
private OrderRepository orderRepository;
@Override
public void process(Exchange exchange) {
Part part = null;
try {
part = exchange.getIn().getBody(Part.class);
} catch (Exception e) {
e.printStackTrace();
}
log.info("order processiong", part);
orderRepository.save(part);
}
}
| true
|
3551bdf74e542bc011236f744d2bb47a50e82bc6
|
Java
|
rizvi95/Projects
|
/Project2Files/Java/realbot/src/main/java/ubc/aacjhy/realbot/Main_Window.java
|
UTF-8
| 3,345
| 2.875
| 3
|
[] |
no_license
|
package ubc.aacjhy.realbot;
import processing.core.PApplet;
import processing.serial.Serial;
import java.util.ArrayList;
public class Main_Window extends Window {
private ArrayList<Window> windows;
private Serial myPort;
private boolean console_f = false;
private boolean midi_f = false;
public Window selected_window;
public Main_Window(PApplet p, String type, Serial myPort) {
super(p, type,0, 0, p.width, p.height);
this.myPort = myPort;
windows = new ArrayList<Window>();
}
@Override
public void render() {
for (Window window : windows) {
window.render();
}
}
public void addWindow(Window nbr, int type, int resize_axis) {
Window new_window;
switch(type) {
case 0:
new_window = new Midi_Window(p, "midi_sequencer", myPort,0, 0, p.width, p.height);
midi_f = true;
break;
case 1:
new_window = new Console_Window(p, "console", myPort,0, 0, p.width, p.height);
console_f = true;
break;
case 2:
new_window = new Controller_Window(p, "controller", myPort, 0, 0, p.width, p.height);
break;
default:
return;
}
if (nbr != this && new_window != null) {
resizeWindows(nbr, new_window, resize_axis);
}
windows.add(new_window);
}
public Window getWindow(int index) {
if (index < windows.size()) {
return windows.get(index);
}
return null;
}
private void resizeWindows(Window one, Window two, int resize_axis) {
if (resize_axis == 0) {
two.setFullX(one.getFullX() + one.getFullWidth() / 2);
two.setFullY(one.getFullY());
two.setFullWidth(one.getFullWidth() / 2);
two.setFullHeight((one.getFullHeight()));
one.setFullWidth(two.getFullX() - one.getFullX());
} else {
two.setFullX(one.getFullX());
two.setFullY(one.getFullY() + one.getFullHeight()/2);
two.setFullWidth(one.getFullWidth());
two.setFullHeight(one.getFullHeight()/2);
one.setFullHeight(two.getFullY() - one.getFullY());
}
one.updateValues();
two.updateValues();
}
public Window getMouseWindow() {
for (Window window : windows) {
if (p.mouseX >= window.getX() && p.mouseX <= window.getX() + window.getWidth() && p.mouseY >= window.getY() && p.mouseY <= window.getY() + window.getHeight()) {
if (window == selected_window) {
return window;
} else {
if (selected_window != null) {
selected_window.clearSelected();
}
selected_window = window;
selected_window.setSelected();
}
return window;
}
}
return this;
}
public Console_Window getConsole() {
if (console_f) {
return (Console_Window)windows.get(1);
}
return null;
}
}
| true
|
ae69ee2d673cd661f932fbc80ce642aac289d410
|
Java
|
jaunerc/effective-java-practice
|
/src/main/java/ch/travbit/practice/ej/chapter2/item9/FileReadApp.java
|
UTF-8
| 980
| 3.671875
| 4
|
[
"MIT"
] |
permissive
|
package ch.travbit.practice.ej.chapter2.item9;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
/**
* [item 9: Prefer try-with-resources to try-finally]
*
* This class represents a small app that reads the first line of a file.
*/
public class FileReadApp {
private FileReadApp() {
}
public void readFirstLine(String path) {
// try-with-resources doesn't need a finally block to close the resources
// this is done automatically.
try (BufferedReader reader = new BufferedReader(new FileReader(path))) {
System.out.println(reader.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
String path = FileReadApp.class.getClassLoader()
.getResource("chapter2/item9/some_text.txt").getPath();
FileReadApp app = new FileReadApp();
app.readFirstLine(path);
}
}
| true
|
2aefc893b9fc1430ea281f0e84178d2809ebea6e
|
Java
|
zkzong/java
|
/designpattern/src/main/java/org/example/designpattern/gof_quanke_name/simplefactory/product/ConcreteProductA.java
|
UTF-8
| 218
| 2.125
| 2
|
[
"Apache-2.0"
] |
permissive
|
package org.example.designpattern.gof_quanke_name.simplefactory.product;
/**
* Created by Zong on 2016/11/23.
*/
public class ConcreteProductA extends Product {
@Override
public void methodDiff() {
}
}
| true
|
cddae4ebd43455cc9053227b8a2c1d910eb2ec4b
|
Java
|
Zxhhhh/Evaluation
|
/src/main/java/com/why/Evaluation/service/Exam_PaperService.java
|
UTF-8
| 1,725
| 1.953125
| 2
|
[] |
no_license
|
package com.why.Evaluation.service;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import com.why.Evaluation.dto.Bigquestion;
import com.why.Evaluation.dto.Questions;
public interface Exam_PaperService {
/**
* 获取试卷的所有大题
* @param response
* @param paper_id
* @return
*/
public List<Bigquestion> getBigquestions(HttpServletResponse response,Integer paper_id);
/**
* 获取一道大题的所有小题
* @param response
* @param question_ids
* @return
*/
public List<Questions> getQuestionsFromBigquestion(HttpServletResponse response,String question_ids);
/**
* 新增大题
* @param response
* @param paper_id
* @return
*/
public Bigquestion addBigquestion(HttpServletResponse response,Integer paper_id,Integer part_id);
/**
* 删除大题
* @param paper_id
* @param part_id
* @param bigquestion_id
*/
public boolean deleteBigquestion(HttpServletResponse response,Integer paper_id,Integer part_id,Integer bigquestion_id);
/**
* 绑定试题到大题中
* @param bigquestion_id
* @param question_id
* @return
*/
public boolean bindQuestionToBigquestion(Integer bigquestion_id,Integer question_id);
/**
* 解除大题中绑定的试题
* @param bigquestion_id
* @param question_id
* @return
*/
public boolean unbindQuestionToBigquestion(Integer bigquestion_id,Integer question_id);
/**
* 在试题库选择试题加入到大题中
* @param question_ids
* @param bigquestion_id
* @return
*/
public boolean choiceQUestionsToBigquestion(String[] question_ids,Integer bigquestion_id);
public boolean deleteQuestionsFromBigquestionService(Integer bigquestion_id,Integer question_id);
}
| true
|
f452608a1d1efa1456f5429610555f7719966a6d
|
Java
|
samehkh88/Selenium2
|
/src/test/java/runner/TestRunner.java
|
UTF-8
| 675
| 1.945313
| 2
|
[] |
no_license
|
package runner;
import io.cucumber.testng.CucumberOptions;
import org.testng.annotations.DataProvider;
import tests.TestBase;
@CucumberOptions(features = "src/test/java/features"
, glue = {"steps"}
, plugin = {"pretty" , "html:target/cucumber-html-report"})
public class TestRunner extends TestBase {
// the test runner shout extend from TestBase
// TestBase should extend from AbstractTestNGCucumberTests to make cucumber work
// to run it parallel i should add plugin maven-surefire-plugin and override this method
@Override
@DataProvider(parallel = true)
public Object[][] scenarios() {
return super.scenarios();
}
}
| true
|
9ea405ead1b2f8356b5687e436deb1237b96b8c8
|
Java
|
RobertLemmens/AudioStreamBox
|
/src/main/java/Standard/AbstractController.java
|
UTF-8
| 577
| 2.6875
| 3
|
[] |
no_license
|
package Standard;
import java.util.ArrayList;
/**
* Created by rober on 1-11-2015.
*/
public abstract class AbstractController {
private ArrayList<AbstractModel> models = new ArrayList<>();
private ArrayList<AbstractView> views = new ArrayList<>();
public void addView(AbstractView view) {
views.add(view);
}
public void addModel(AbstractModel model){
models.add(model);
}
public void removeView(int index) {
views.remove(index);
}
public void removeModel(int index) {
models.remove(index);
}
}
| true
|
5b9a62870e35d7fe0ff67007b8233e6386f5950a
|
Java
|
TVerse/mancala
|
/src/main/java/nl/sogyo/mancala/AI/AI.java
|
UTF-8
| 3,094
| 3.125
| 3
|
[] |
no_license
|
package nl.sogyo.mancala.AI;
import java.util.ArrayList;
import nl.sogyo.mancala.backend.Mancala;
public class AI {
private Mancala mancala;
private final int player;
public AI(Mancala mancala, int player) {
this.mancala = mancala;
this.player = player;
}
Mancala getMancala() {
return this.mancala;
}
public int getPlayer() {
return this.player;
}
public int getBestMove(int depth) {
int bestScore = Integer.MIN_VALUE;
int bestMove = 0;
for (int i = 1; i <= 6; i++) {
Mancala newState = this.mancala.deepClone();
boolean hasMoved = newState.doMove(i);
if (hasMoved) {
int score = 0;
if (newState.getCurrentTurn() != this.mancala.getCurrentTurn()) {
score = this.getScoreMinimize(newState, depth - 1);
} else {
score = this.getScoreMaximize(newState, depth);
}
if (score > bestScore) {
bestScore = score;
bestMove = i;
}
}
}
System.out.println(this.leafCount);
return bestMove;
}
public int leafCount = 0;
private int getScoreMaximize(Mancala currentState, int depth) {
if ((depth <= 0) || !currentState.canCurrentPlayerMove()) {
return this.getHeuristicScore(currentState);
}
int bestScore = Integer.MIN_VALUE;
for (int i = 1; i <= 6; i++) {
Mancala newState = currentState.deepClone();
boolean hasMoved = newState.doMove(i);
if (hasMoved) {
int score = 0;
if (newState.getCurrentTurn() != currentState.getCurrentTurn()) {
score = this.getScoreMinimize(newState, depth - 1);
} else {
score = this.getScoreMaximize(newState, depth);
}
bestScore = Math.max(bestScore, score);
}
}
return bestScore;
}
private int getScoreMinimize(Mancala currentState, int depth) {
if ((depth <= 0) || !currentState.canCurrentPlayerMove()) {
return this.getHeuristicScore(currentState);
}
int bestScore = Integer.MAX_VALUE;
for (int i = 1; i <= 6; i++) {
Mancala newState = currentState.deepClone();
boolean hasMoved = newState.doMove(i);
if (hasMoved) {
int score = 0;
if (newState.getCurrentTurn() != currentState.getCurrentTurn()) {
score = -this.getScoreMaximize(newState, depth - 1);
} else {
score = -this.getScoreMinimize(newState, depth);
}
bestScore = Math.min(bestScore, score);
}
}
return bestScore;
}
public int getHeuristicScore(Mancala currentState) {
this.leafCount++;
ArrayList<Integer> stoneAmounts = currentState.getStoneAmounts();
int score = 0 * this.getTentativeScoreDiff(currentState, stoneAmounts);
score += 2 * this.getKalahaScoreDiff(currentState, stoneAmounts);
return score;
}
public int getTentativeScoreDiff(Mancala currentStatee, ArrayList<Integer> stoneAmounts) {
int result = 0;
for (int i = 0; i < 7; i++) {
result += stoneAmounts.get(i);
}
for (int i = 7; i < 14; i++) {
result -= stoneAmounts.get(i);
}
return result;
}
public int getKalahaScoreDiff(Mancala currentStatee, ArrayList<Integer> stoneAmounts) {
int kalahaOne = stoneAmounts.get(6);
int kalahaTwo = stoneAmounts.get(6 + 7);
return kalahaOne - kalahaTwo;
}
}
| true
|
11894de9be8168cf179fb570d401ed512a4b4404
|
Java
|
samybej/PIDEV-Java
|
/src/Service/AdminRHService.java
|
UTF-8
| 4,701
| 2.1875
| 2
|
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Service;
import Entity.AdminRH;
import Entity.Chauffeur;
import Entity.Client;
import Entity.Meuble;
import Entity.Postulation;
import Entity.Reservation;
import config.ConfigBD;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
public class AdminRHService {
Connection cnx = ConfigBD.getInstance().getCnx();
public void ajouterAdminRH(AdminRH a){
String requete="INSERT INTO adminrh (login,mdp,etat_compte,mail) VALUES (?,?,?,?)";
try {
PreparedStatement pst = cnx.prepareStatement(requete);
pst.setString(1, a.getLogin());
pst.setString(2, a.getMdp());
pst.setInt(3, a.getEtat_compte());
pst.setString(4, a.getMail());
pst.executeUpdate();
} catch (SQLException ex) {
Logger.getLogger(ClientService.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void modifierAdminRH(AdminRH a){
String requete="UPDATE adminrh set login=?, mdp=?, etat_compte=?, mail=? WHERE login=?";
try {
PreparedStatement pst = cnx.prepareStatement(requete);
pst.setString(1, a.getLogin());
pst.setString(2, a.getMdp());
pst.setInt(3, a.getEtat_compte());
pst.setString(4, a.getMail());
pst.setString(5, a.getLogin());
pst.executeUpdate();
} catch (SQLException ex) {
Logger.getLogger(ClientService.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void supprimerAdminRH(AdminRH a){
String requete = "DELETE FROM adminrh WHERE login=?";
try {
PreparedStatement statement = cnx.prepareStatement(requete);
statement.setString(1, a.getLogin());
statement.executeUpdate();
} catch (SQLException ex) {
Logger.getLogger(ClientService.class.getName()).log(Level.SEVERE, null, ex);
}
}
public List<AdminRH> getListAdminRH(){
List<AdminRH> list = new ArrayList<>();
String requete="SELECT * from adminrh";
try {
Statement st = cnx.createStatement();
ResultSet rs = st.executeQuery(requete);
while (rs.next()){
AdminRH a = new AdminRH();
a.setLogin(rs.getString(1));
a.setMdp(rs.getString(2));
a.setEtat_compte(rs.getInt(3));
a.setMail(rs.getString(4));
list.add(a);
}
} catch (SQLException ex) {
Logger.getLogger(ClientService.class.getName()).log(Level.SEVERE, null, ex);
}
return list;
}
public void validerPostulation(Postulation p,Chauffeur c){
String requete="DELETE FROM postulation WHERE id_client=?";
try {
PreparedStatement statement = cnx.prepareStatement(requete);
statement.setInt(1, p.getId_client());
statement.executeUpdate();
ChauffeurService chService = new ChauffeurService();
chService.ajouterChauffeur(c);
} catch (SQLException ex) {
Logger.getLogger(ClientService.class.getName()).log(Level.SEVERE, null, ex);
}
}
public AdminRH recupererAdminLogin(String mail,String mdp)
{
AdminRH c = new AdminRH();
String requete = "SELECT * FROM adminrh WHERE login = ? and mdp = ?";
try {
PreparedStatement st = cnx.prepareStatement(requete);
st.setString(1, mail);
st.setString(2, mdp);
ResultSet rs = st.executeQuery();
while (rs.next()){
c.setLogin(rs.getString(1));
c.setMdp(rs.getString("mdp"));
c.setEtat_compte(rs.getInt(3));
c.setMail(rs.getString(4));
}
} catch (SQLException ex) {
Logger.getLogger(ReservationService.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println(c);
return c;
}
}
| true
|
7c5a1f814c33898b25c62c630aaca3700d07352f
|
Java
|
Ravizinho/JogoDaMemoria
|
/JogoDaMemoriaLibras/Jogador.java
|
UTF-8
| 1,226
| 3.4375
| 3
|
[] |
no_license
|
package JogoDaMemoriaLibras;
public class Jogador {
private String nome;
private int numeroDeJogadas;
/**
* Construtor default
*/
public Jogador(){ }
/**
* Construtor que tem como par�metros um nome e um n�mero de jogadas
* @param nome
* @param numJogadas
*/
public Jogador(String nome){
this.nome = nome;
this.numeroDeJogadas = 0;
}
/**
* M�todo que altera o nome do jogador e recebe como par�metro um novo nome
* @param novoNome
*/
public void setJogador(String novoNome){
this.nome = novoNome;
}
/**
* m�todo que retorna o nome do jogador
* @return retorna um nome do tipo String
*/
public String getNome(){
return this.nome;
}
/**
* m�todo que reseta o numero de jogadas de um jogador
*/
public void resetaNumeroDeJogadas(){
this.numeroDeJogadas = 0;
}
/**
* m�todo que retorna o n�mero de jogadas
* @return numeroDeJogadas
*/
public int getNumeroDeJogadas(){
return this.numeroDeJogadas;
}
/**
* m�todo que armazena o n�mero de jogadas, recebe como par�metro o n�mero de jogadas
* @param numeroDeJogadas
*/
public void setArmazenaNumeroDeJogadas(int numeroDeJogadas){
this.numeroDeJogadas += numeroDeJogadas;
}
}
| true
|
ed7aef60e8fb02fc5fd42b84d020a693a659e14b
|
Java
|
IliaWoodman/JavaCore
|
/src/GenericsLessons/ASD.java
|
UTF-8
| 662
| 3.53125
| 4
|
[] |
no_license
|
package GenericsLessons;
import java.util.ArrayList;
import java.util.List;
public class ASD {
public static void main(String[] args) {
List<ABC> a = new ArrayList<>();
a.add(new A());
a.add(new B());
a.add(new C());
for (ABC abc : a){
abc.method();
}
}
}
class ABC {
public void method(){};
}
class A extends ABC {
@Override
public void method() {
System.out.println("A");
}
}
class B extends ABC {
@Override
public void method() {
System.out.println("B");
}
}
class C extends ABC {
@Override
public void method() {
System.out.println("C");
}
}
| true
|
803c59c3cb9018b8df083268ae145bcea2bcf766
|
Java
|
hbartek230/kodilla-final-project
|
/src/test/java/com/kodilla/exchangesystem/service/CurrencyServiceTestSuite.java
|
UTF-8
| 3,942
| 2.3125
| 2
|
[] |
no_license
|
package com.kodilla.exchangesystem.service;
import com.kodilla.exchangesystem.domain.Currency;
import com.kodilla.exchangesystem.domain.CurrencyRate;
import com.kodilla.exchangesystem.exception.CurrencyNotFoundException;
import com.kodilla.exchangesystem.repository.CurrencyRepository;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.*;
@RunWith(SpringRunner.class)
@SpringBootTest
public class CurrencyServiceTestSuite {
@Autowired
private CurrencyService service;
@MockBean
private CurrencyRepository repository;
@Mock
private CurrencyRate currencyRate;
@Test
public void should_returnEmptyCurrencyList() {
// given
List<Currency> expectedList = Collections.emptyList();
when(repository.findAll()).thenReturn(Collections.emptyList());
// when
List<Currency> testedList = service.getCurrencies();
// then
assertEquals(testedList.size(), expectedList.size());
}
@Test
public void should_returnOneElementCurrencyList() {
// given
Currency currency = new Currency(1L, "Dolar", "USD", currencyRate);
List<Currency> expectedList = Collections.singletonList(currency);
when(repository.findAll()).thenReturn(expectedList);
// when
List<Currency> testedList = service.getCurrencies();
// then
assertEquals(testedList.size(), expectedList.size());
assertEquals(testedList.get(0).getCurrencyName(), expectedList.get(0).getCurrencyName());
assertEquals(testedList.get(0).getCurrencyCode(), expectedList.get(0).getCurrencyCode());
}
@Test
public void should_returnSpecifiedIdElementFromCurrencyList() throws CurrencyNotFoundException {
// given
Currency currency = new Currency(2L, "Euro", "EUR", currencyRate);
when(repository.findById(anyLong())).thenReturn(Optional.of(currency));
// when
Currency testedCurrency = service.getSingleCurrency(anyLong());
// then
assertEquals(testedCurrency.getId(), currency.getId());
assertEquals(testedCurrency.getCurrencyName(), currency.getCurrencyName());
assertEquals(testedCurrency.getCurrencyCode(), currency.getCurrencyCode());
}
@Test
public void should_returnSpecifiedCurrencyCodeElementFromList() throws CurrencyNotFoundException {
// given
Currency currency = new Currency(2L, "Euro", "EUR", currencyRate);
when(repository.findByCurrencyCode(anyString())).thenReturn(Optional.of(currency));
// when
Currency testedCurrency = service.getCurrencyByCode(anyString());
// then
assertEquals(testedCurrency.getId(), currency.getId());
assertEquals(testedCurrency.getCurrencyName(), currency.getCurrencyName());
assertEquals(testedCurrency.getCurrencyCode(), currency.getCurrencyCode());
}
@Test
public void should_addNewCurrency() {
// given
Currency currency = new Currency(2L, "Euro", "EUR", currencyRate);
when(repository.save(currency)).thenReturn(currency);
// when
service.addCurrency(currency);
// then
verify(repository, times(1)).save(currency);
}
@Test
public void should_deleteCurrency() {
// given
doNothing().when(repository).deleteById(anyLong());
// when
service.deleteCurrency(anyLong());
// then
verify(repository, times(1)).deleteById(anyLong());
}
}
| true
|
3a05907409a1fc63e06134f66763f2be1965df89
|
Java
|
mattstep/atlas
|
/src/main/java/com/ning/atlas/ProvisionedSystemTemplate.java
|
UTF-8
| 2,911
| 2.375
| 2
|
[
"BSD-3-Clause",
"MIT",
"Apache-2.0"
] |
permissive
|
package com.ning.atlas;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.SettableFuture;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicInteger;
public class ProvisionedSystemTemplate extends ProvisionedTemplate
{
private List<? extends ProvisionedTemplate> children;
public ProvisionedSystemTemplate(String type, String name, My my, List<? extends ProvisionedTemplate> children)
{
super(type, name, my);
this.children = new ArrayList<ProvisionedTemplate>(children);
}
public List<? extends ProvisionedTemplate> getChildren()
{
return children;
}
@Override
public ListenableFuture<InitializedTemplate> initialize(Executor ex, ProvisionedTemplate root)
{
final AtomicInteger remaining = new AtomicInteger(getChildren().size());
final List<InitializedTemplate> init_children = new CopyOnWriteArrayList<InitializedTemplate>();
final SettableFuture<InitializedTemplate> rs = SettableFuture.create();
for (ProvisionedTemplate template : getChildren()) {
final ListenableFuture<? extends InitializedTemplate> child = template.initialize(ex, root);
child.addListener(new Runnable()
{
@Override
public void run()
{
try {
final InitializedTemplate ct = child.get();
init_children.add(ct);
if (remaining.decrementAndGet() == 0) {
rs.set(new InitializedSystemTemplate(getType(),
getName(),
getMy(),
init_children));
}
}
catch (InterruptedException e) {
e.printStackTrace();
System.exit(1);
}
catch (ExecutionException e) {
e.printStackTrace();
System.exit(1);
}
}
}, ex);
}
return rs;
}
}
| true
|
fca57a3b82e2ffd7fd0f6b70b5c098495e381b40
|
Java
|
txusballesteros/inheritance_or_composition
|
/app/src/main/java/com/txusballesteros/labs/navigation/command/NoteDetailNavigationCommand.java
|
UTF-8
| 2,689
| 1.789063
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright Txus Ballesteros 2016 (@txusballesteros)
*
* This file is part of some open source application.
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
* Contact: Txus Ballesteros <txus.ballesteros@gmail.com>
*/
package com.txusballesteros.labs.navigation.command;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityOptionsCompat;
import android.view.View;
import com.txusballesteros.labs.R;
import com.txusballesteros.labs.domain.model.Note;
import com.txusballesteros.labs.domain.model.NoteType;
import com.txusballesteros.labs.view.activity.NoteDetailActivity;
public class NoteDetailNavigationCommand extends NavigationCommand {
private final Note note;
private final View sharedView;
public NoteDetailNavigationCommand(Context context, Note note, View sharedView) {
super(context);
this.note = note;
this.sharedView = sharedView;
}
@NonNull @Override
Intent onRequestIntent(Context context) {
final Intent intent = new Intent(context, NoteDetailActivity.class);
intent.putExtra(NoteDetailActivity.EXTRA_NOTE_TYPE, note.getType().ordinal());
intent.putExtra(NoteDetailActivity.EXTRA_NOTE_ID, note.getId());
return intent;
}
@Nullable @Override
protected Bundle onRequestActivityOptions() {
Bundle result = null;
if (sharedView != null && note.getType() == NoteType.IMAGE) {
final Activity activity = (Activity) getContext();
final Resources resources = activity.getResources();
ActivityOptionsCompat activityOptionsCompat = ActivityOptionsCompat
.makeSceneTransitionAnimation(activity, sharedView, resources.getString(R.string.transition_note_image));
result = activityOptionsCompat.toBundle();
}
return result;
}
}
| true
|
d6c412d374b88944780fb216e78093bd7aad6568
|
Java
|
TheWizard91/Album_base_source_from_JADX
|
/sources/com/google/android/gms/location/places/internal/zzd.java
|
UTF-8
| 2,137
| 1.710938
| 2
|
[] |
no_license
|
package com.google.android.gms.location.places.internal;
import android.text.style.CharacterStyle;
import com.google.android.gms.common.data.DataHolder;
import com.google.android.gms.common.internal.Preconditions;
import com.google.android.gms.location.places.AutocompletePrediction;
import java.util.Collections;
import java.util.List;
public final class zzd extends zzaw implements AutocompletePrediction {
public zzd(DataHolder dataHolder, int i) {
super(dataHolder, i);
}
public final String getPlaceId() {
return zzb("ap_place_id", (String) null);
}
public final List<Integer> getPlaceTypes() {
return zzb("ap_place_types", (List<Integer>) Collections.emptyList());
}
public final CharSequence getFullText(CharacterStyle characterStyle) {
return zzi.zzb(zzd(), zzg(), characterStyle);
}
public final CharSequence getPrimaryText(CharacterStyle characterStyle) {
return zzi.zzb(zze(), zzh(), characterStyle);
}
public final CharSequence getSecondaryText(CharacterStyle characterStyle) {
return zzi.zzb(zzf(), zzi(), characterStyle);
}
private final String zzd() {
return zzb("ap_description", "");
}
private final String zze() {
return zzb("ap_primary_text", "");
}
private final String zzf() {
return zzb("ap_secondary_text", "");
}
private final List<zzb> zzg() {
return zzb("ap_matched_subscriptions", zzb.CREATOR, Collections.emptyList());
}
private final List<zzb> zzh() {
return zzb("ap_primary_text_matched", zzb.CREATOR, Collections.emptyList());
}
private final List<zzb> zzi() {
return zzb("ap_secondary_text_matched", zzb.CREATOR, Collections.emptyList());
}
public final /* synthetic */ Object freeze() {
String placeId = getPlaceId();
List<Integer> placeTypes = getPlaceTypes();
int zzc = zzc("ap_personalization_type", 6);
String zzd = zzd();
return new zzc(placeId, placeTypes, zzc, (String) Preconditions.checkNotNull(zzd), zzg(), zze(), zzh(), zzf(), zzi());
}
}
| true
|
d9a22d0db71afad1345f45ae040087e1f284f4d2
|
Java
|
sblevins/the_amazing_maze_of_doom
|
/src/GameState/LevelEditor.java
|
UTF-8
| 7,598
| 2.84375
| 3
|
[] |
no_license
|
package GameState;
import java.awt.Color;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.IOException;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import maze.Board;
public class LevelEditor {
private JFrame window = new JFrame("Level Editor");
private Board b = new Board();//data to be exported
JLabel back;//the background
private JLabel[][] labels;//array of tiles
int xSelected = 0;//location of selected tile
int ySelected = 0;
JTextField interval;//text field for editing timer interval
JButton key;//adds key to selected tile
JTextField order;//inputs order in which the traps fire
JLabel location;//displays selected trap in edit section
Handler theHandler = new Handler();//handles user input
JPanel p = new JPanel();
JButton Null = new JButton("NULL");//button to set a trap to null
JButton ok = new JButton("OK");//button to push input to interface
JButton save = new JButton("Save");//button saves map to binary file
JTextField name = new JTextField("");
private int maxOrder = 0;
LevelEditor(){
p.setLayout(null);
labels = new JLabel[7][9];
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setResizable(false);
window.pack();
window.setSize(700, 654);
back = new JLabel("");
Image img = new ImageIcon(this.getClass().getResource("/editboard.png")).getImage();
back.setIcon(new ImageIcon(img));
back.setSize(500,615);
createLabels();
p.add(back);
createInput();
window.add(p);
window.validate();
window.setVisible(true);
}
public void createLabels(){//adds labels to screen, multiple for loops help keep the labels in line.
for(int y=0;y<3;y++){
for(int x=0;x<7;x++){
labels[x][y] = new JLabel("NULL");
labels[x][y].setHorizontalAlignment(SwingConstants.CENTER);
labels[x][y].setForeground(Color.RED);
labels[x][y].setSize(57,57);
labels[x][y].setBackground(Color.WHITE);
labels[x][y].setOpaque(true);
labels[x][y].setLocation(29+x*64,43+y*64);
labels[x][y].setVisible(true);
back.add(labels[x][y]);
}
}
for(int y=3;y<7;y++){
for(int x=0;x<7;x++){
labels[x][y] = new JLabel("NULL");
labels[x][y].setHorizontalAlignment(SwingConstants.CENTER);
labels[x][y].setForeground(Color.RED);
labels[x][y].setBackground(Color.WHITE);
labels[x][y].setSize(57,57);
labels[x][y].setOpaque(true);
labels[x][y].setLocation(29+x*64,44+y*64);
labels[x][y].setVisible(true);
back.add(labels[x][y]);
}
}
for(int y=7;y<9;y++){
for(int x=0;x<7;x++){
labels[x][y] = new JLabel("NULL");
labels[x][y].setHorizontalAlignment(SwingConstants.CENTER);
labels[x][y].setForeground(Color.RED);
labels[x][y].setBackground(Color.WHITE);
labels[x][y].setSize(57,57);
labels[x][y].setOpaque(true);
labels[x][y].setLocation(29+x*64,45+y*64);
labels[x][y].setVisible(true);
back.add(labels[x][y]);
}
}
}
public void createInput(){
Null.addActionListener(theHandler);
Null.setSize(100,20);
Null.setLocation(530,140);
ok.addActionListener(theHandler);
ok.setSize(75,20);
ok.setLocation(542,170);
JLabel intervalLabel = new JLabel("Interval");
intervalLabel.setSize(50,20);
intervalLabel.setLocation(530,50);
JLabel orderLabel = new JLabel("Order");
orderLabel.setSize(50,20);
orderLabel.setLocation(540,75);
window.addMouseListener(theHandler);
order = new JTextField("1");
order.addActionListener(theHandler);
order.setSize(50,20);
order.setLocation(580,75);
key = new JButton("Add Key");
key.addActionListener(theHandler);
key.setSize(100,20);
key.setLocation(530,110);
interval = new JTextField("1000");
interval.addActionListener(theHandler);
interval.setSize(50,20);
interval.setLocation(580,50);
location = new JLabel("No Location Selected");
location.setSize(300,100);
location.setLocation(530,-25);
name.setSize(100,20);
name.setLocation(570,530);
JLabel nameLabel = new JLabel("Name: ");
nameLabel.setSize(50,20);
nameLabel.setLocation(520,529);
save.addActionListener(theHandler);
save.setSize(100,20);
save.setLocation(530, 565);
p.add(save);
p.add(nameLabel);
p.add(name);
p.add(Null);
p.add(ok);
p.add(orderLabel);
p.add(intervalLabel);
p.add(interval);
p.add(key);
p.add(order);
p.add(location);
p.setVisible(true);
window.add(p);
}
public boolean export() throws IOException{
int key = 0;//used to detect if there is more than 1 key on the editor
for(int x = 0; x < 7; x++){
for(int y = 0; y < 9; y++){
if(labels[x][y].getText()=="KEY")
key++;
}
}
if(key>1)
return false;
for(int x = 0; x <7; x++){
for(int y = 0; y < 9; y++){
if(labels[x][y].getText()=="KEY"){
b.setKey(x, y);
b.setTrapNull(x, y);
}
else if(labels[x][y].getText()=="NULL"){
b.setTrapNull(x,y);
}
else{
try {
b.setTrapOrder(x, y, Integer.parseInt(labels[x][y].getText()));
}
catch(NumberFormatException ex){
System.out.println("Trap"+x+","+y+"has been set to null since there wasn no valid input");
}
}
}
try {
int inter = Integer.parseInt(interval.getText());
b.setInterval(inter);
} catch(NumberFormatException ex){
System.out.println("Must enter a number in interval field");
}
b.setMaxOrder(maxOrder);
}
System.out.println("attempting to write file");
Board.writeToFile(b, name.getText());
System.out.println("file successfully written");
return true;
}
public static void main(String[] args){
new LevelEditor();
}
private class Handler implements ActionListener, MouseListener{
public void actionPerformed(ActionEvent e){
if(e.getSource()==Null){
labels[xSelected][ySelected].setText("NULL");
}
else if(e.getSource()==ok&&labels[xSelected][ySelected]!=null){
try {
int ord = Integer.parseInt(order.getText());
labels[xSelected][ySelected].setText(""+ord);
if(ord>=maxOrder)
maxOrder = ord;
} catch(NumberFormatException ex){
System.out.println("Must enter a number in order field");
}
}
else if(e.getSource()==key&&labels[xSelected][ySelected]!=null){
labels[xSelected][ySelected].setText("KEY");
}
else if(e.getSource()==save){
try {
if(!export())
System.out.print("export failed");
} catch (IOException e1) {
System.out.println("fml");
}
}
}
@Override
public void mouseClicked(MouseEvent e) {
//leave empty
}
@Override
public void mouseEntered(MouseEvent e) {
// leave empty
}
@Override
public void mouseExited(MouseEvent e) {
// leave empty
}
@Override
public void mousePressed(MouseEvent e) {
int tempX = 0;
int tempY = 0;
if((e.getX()<481&&e.getY()<644)&&e.getX()>29&&e.getY()>68){
if(labels[xSelected][ySelected]!=null){
tempX = xSelected;
tempY = ySelected;
}
xSelected = (e.getX()-33)/64;
ySelected = (e.getY()-68)/64;
if(labels[xSelected][ySelected]!=null)
labels[tempX][tempY].setBackground(Color.WHITE);
labels[xSelected][ySelected] = labels[(e.getX()-33)/64][(e.getY()-68)/64];
labels[xSelected][ySelected].setBackground(Color.BLUE);
}
}
@Override
public void mouseReleased(MouseEvent arg0) {
}
}
}
| true
|
f337a705e059b5b227224e346a0cb6b25cd8da77
|
Java
|
d495435207/ding_ssm_dubbo
|
/ding_ssm_dubbo/ding/ding-biz/ding-biz-manager/src/test/java/com/ding/biz/manager/RedisTest.java
|
UTF-8
| 718
| 1.859375
| 2
|
[] |
no_license
|
package com.ding.biz.manager;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.alibaba.fastjson.JSON;
import com.ding.biz.dao.user.data.UserDO;
import com.ding.biz.manager.user.UserManager;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:/spring/ding-mgr-context.xml"})
public class RedisTest {
@Autowired
private UserManager userManger;
@Test
public void test() {
UserDO userDO = userManger.get(2);
System.out.println(JSON.toJSONString(userDO));
}
}
| true
|
f83f6715ee3a6fe938ade1a029223eef0ad41798
|
Java
|
drivedreams/weibocreed_android
|
/src/com/weibo/net/weiboinfo.java
|
UTF-8
| 931
| 2.09375
| 2
|
[] |
no_license
|
package com.weibo.net;
public class weiboinfo {
private long weiboId;
public long getWeiboId() {
return weiboId;
}
public void setWeiboId(long weiboId) {
this.weiboId = weiboId;
}
public String getRetweetedStatuscontent() {
return retweetedStatuscontent;
}
public void setRetweetedStatuscontent(String retweetedStatuscontent) {
this.retweetedStatuscontent = retweetedStatuscontent;
}
public long getuId() {
return uId;
}
public void setuId(long uId) {
this.uId = uId;
}
private String content;
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
private long retweetedStatuscontentId;
public long getRetweetedStatuscontentId() {
return retweetedStatuscontentId;
}
public void setRetweetedStatuscontentId(long retweetedStatuscontentId) {
this.retweetedStatuscontentId = retweetedStatuscontentId;
}
private String retweetedStatuscontent;
private long uId;
}
| true
|
ab29e5b77b4a1778c4f4e415091414b88a589029
|
Java
|
am910021/SEOUrl-Public
|
/src/seourl/thread/JumingController.java
|
UTF-8
| 1,123
| 1.875
| 2
|
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package seourl.thread;
import seourl.data.UrlDataSet;
import seourl.filter.JumingFilter;
import seourl.thread.ex.ControllerAbstract;
import seourl.type.Filter;
/**
*
* @author Yuri
*/
public class JumingController extends ControllerAbstract<UrlDataSet> {
public JumingController(int pid, UrlDataSet dataSet) {
super(pid, Filter.JUMING, dataSet);
}
@Override
public void run() {
JumingFilter j = new JumingFilter(pid, filter);
j.setCookiePath("cache/" + filter.toString() + "/");
j.setCookie(pid + "-cookie.bin");
j.loadCookie();
j.loadWeb("http://www.juming.com");
j.login();
j.saveCookie();
String url;
while (dsa.hasNext()) {
url = dsa.getNext();
j.doAnalysis(url);
packMap.put(url, j.getJp());
}
j.saveCookie();
j.close();
}
}
| true
|
6ab6abb2294a9f8cf165c6a8429e054472a877ba
|
Java
|
gaywind/wifier
|
/app/src/main/java/com/traffic/wifiapp/mvp/presenter/FeedBackPresenter.java
|
UTF-8
| 1,531
| 2.125
| 2
|
[] |
no_license
|
package com.traffic.wifiapp.mvp.presenter;
import android.app.Activity;
import com.traffic.wifiapp.R;
import com.traffic.wifiapp.base.BasePresenter;
import com.traffic.wifiapp.bean.entry.FeedBack;
import com.traffic.wifiapp.bean.response.SimpleResult;
import com.traffic.wifiapp.mvp.view.FeedBackIView;
import com.traffic.wifiapp.retrofit.ApiManager;
import com.traffic.wifiapp.rxjava.RxHelper;
import com.traffic.wifiapp.rxjava.RxSubscribe;
/**
* Created by xy on 16/5/16.
*/
public class FeedBackPresenter extends BasePresenter<FeedBackIView> {
public FeedBackPresenter(Activity mContext, FeedBackIView mView) {
super(mContext, mView);
}
//登录
public void submit(String title,String content) {
FeedBack f=new FeedBack(title,content);
ApiManager.mApiService.feedBack(f).compose(RxHelper.handleResult())
.subscribe(new RxSubscribe<SimpleResult>(mContext, R.string.mine_join_submit_success) {
@Override
protected void _onNext(SimpleResult r) {
if(r!=null){
showToast(r.getMsg());
if(r.isIsSuccess())
mView.submitSuccess();
}
}
@Override
protected void _onError(String message) {
showToast(message);
}
});
}
}
| true
|
5a875a698742f55353342116a2f2951d9e48b586
|
Java
|
matejhacin/Roomies-Android
|
/app/src/main/java/com/matejhacin/roomies/adapters/TasksRecyclerViewAdapter.java
|
UTF-8
| 3,270
| 2.4375
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.matejhacin.roomies.adapters;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import com.matejhacin.roomies.R;
import com.matejhacin.roomies.interfaces.TaskCardClickListener;
import com.matejhacin.roomies.models.Task;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* Created by Domen Lanišnik on 19. 12. 2016.
*/
public class TasksRecyclerViewAdapter extends RecyclerView.Adapter<TasksRecyclerViewAdapter.ViewHolder> {
private List<Task> taskList;
private TaskCardClickListener taskCardClickListener;
public TasksRecyclerViewAdapter(List<Task> taskList, TaskCardClickListener taskCardClickListener) {
this.taskList = taskList;
this.taskCardClickListener = taskCardClickListener;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_task, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(final ViewHolder holder, int position) {
final Task task = taskList.get(position);
holder.titleTextView.setText(task.getTitle());
holder.descriptionTextView.setText(task.getDescription());
holder.awardPointTextView.setText(String.valueOf(task.getValue()));
holder.doneButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (taskCardClickListener != null) {
taskCardClickListener.onDoneClicked(task, holder.getAdapterPosition());
}
}
});
holder.editButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (taskCardClickListener != null) {
taskCardClickListener.onEditClicked(task, holder.getAdapterPosition());
}
}
});
holder.doneAndDeleteButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(taskCardClickListener != null){
taskCardClickListener.onDoneAndDeleteClicked(task, holder.getAdapterPosition());
}
}
});
}
@Override
public int getItemCount() {
return taskList.size();
}
static class ViewHolder extends RecyclerView.ViewHolder {
@BindView(R.id.card_task_title)
TextView titleTextView;
@BindView(R.id.card_task_description)
TextView descriptionTextView;
@BindView(R.id.card_task_award_points)
TextView awardPointTextView;
@BindView(R.id.card_task_done_button)
Button doneButton;
@BindView(R.id.card_task_edit_button)
Button editButton;
@BindView(R.id.card_task_done_and_delete_button)
Button doneAndDeleteButton;
ViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
}
}
| true
|
44853059abdbed1dedc6fe1283db6ad75154a491
|
Java
|
64kilobit/DseaPraktikum
|
/src/tag1/Aufgabe3.java
|
UTF-8
| 1,539
| 3.34375
| 3
|
[] |
no_license
|
package tag1;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Scanner;
/**
*
* @author Ken Schalhorn, Marco Ehl
* @location 03-428
*/
public class Aufgabe3 {
public int longestAlternatingSubsequence(int[] a) {
int[][] alternation = new int[a.length][2];
for (int i = 0; i < a.length; i++) {
alternation[i][0] = 1;
alternation[i][1] = 1;
for (int j = 0; j < i; j++) {
if (a[i] < a[j]) {
alternation[i][0] = Math.max(alternation[j][1] + 1,
alternation[i][0]);
} else {
if (a[i] > a[j]) {
alternation[i][1] = Math.max(alternation[j][0] + 1,
alternation[i][1]);
}
}
}
}
return Math.max(alternation[a.length - 1][0],
alternation[a.length - 1][1]);
}
public static void main(String[] args) {
FileReader fr;
try {
fr = new FileReader("smaple.in");
BufferedReader br = new BufferedReader(fr);
Scanner scan= new Scanner(br);
ArrayList<int[]> array=new ArrayList<int[]>() ;
int n = scan.nextInt();
while(n>0){
int m =scan.nextInt();
int[] arr =new int[m];
int l =0;
while(l<m){
arr[l]=scan.nextInt();
l++;
}
array.add(arr);
long result = (new Aufgabe3()).longestAlternatingSubsequence(arr);
System.out.println(result);
n--;
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| true
|
daa5bf3a6a55656d764ca31454bf45eb719e2b2a
|
Java
|
vishalzadoo/Lambda
|
/HandyAWS/src/main/java/com/handy/aws/functions/Product.java
|
UTF-8
| 1,780
| 2.734375
| 3
|
[] |
no_license
|
package com.handy.aws.functions;
public class Product {
public Product(int id, String title, String type, String desc, String filename, int height, int width, float price,
int rating) {
super();
this.id = id;
this.title = title;
this.type = type;
this.desc = desc;
this.filename = filename;
this.height = height;
this.width = width;
this.price = price;
this.rating = rating;
}
public Product() {
}
int id;
@Override
public String toString() {
return "Product [id=" + id + ", title=" + title + ", type=" + type + ", desc=" + desc + ", filename=" + filename
+ ", height=" + height + ", width=" + width + ", price=" + price + ", rating=" + rating + "]";
}
String title;
String type;
String desc;
String filename;
int height;
int width;
float price;
int rating;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getFilename() {
return filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public int getRating() {
return rating;
}
public void setRating(int rating) {
this.rating = rating;
}
}
| true
|
aa3ffbfe9ae2525c36fbdd0fa27f26b27927e4de
|
Java
|
XiaSakura/Canteen_ordering_system
|
/sell-restapi/src/main/java/com/cqnu/sell/restapi/service/OrderService.java
|
UTF-8
| 231
| 1.554688
| 2
|
[] |
no_license
|
package com.cqnu.sell.restapi.service;
import java.util.List;
import com.cqnu.sell.manager.bean.OrderDto;
public interface OrderService {
List<OrderDto> getOrderByUid(Integer id);
Boolean insertOrder(OrderDto orderDto);
}
| true
|
cbcedd9fecf246d870e1c2eb2a6258adeb0817ad
|
Java
|
eliseoabelcarh/JAVA-ort
|
/1er Cuatrimestre/UMLInstitucionAlumnoCursada2/src/curso/Curso.java
|
UTF-8
| 659
| 2.625
| 3
|
[] |
no_license
|
package curso;
import escolaridad.Escolaridad;
public class Curso {
private String nombre;
private Escolaridad escolaridad;
public Curso(String nombre, Escolaridad escolaridad) {
super();
this.nombre = nombre;
this.escolaridad = escolaridad;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public Escolaridad getEscolaridad() {
return escolaridad;
}
public void setEscolaridad(Escolaridad escolaridad) {
this.escolaridad = escolaridad;
}
@Override
public String toString() {
return "Curso [nombre=" + nombre + ", escolaridad=" + escolaridad + "]";
}
}
| true
|
9c9216c9f9a84da8358ac3b933e56a2e53d1ec05
|
Java
|
mtetaud/digmarket-api
|
/app/services/coinbase/CoinbaseInputParameters.java
|
UTF-8
| 412
| 1.75
| 2
|
[] |
no_license
|
package services.coinbase;
import services.common.models.InputParameters;
import java.util.HashMap;
public class CoinbaseInputParameters extends InputParameters {
public CoinbaseInputParameters() {
this.host = "https://api.pro.coinbase.com";
this.httpHeaders =
new HashMap<String, String>() {{
put("CB-ACCESS-KEY", "ek1OyAzDbb5Nsq0tjyVIvxfOqdgqRx9jm6MMST4S7PLUIP6xi2OxbtwoPNCq7REgTzQmCw49WY0N+dwAY2Ifug==");
}};
}
}
| true
|
1bb131987f529e10b42b6b37246884079af02eb5
|
Java
|
mehdialemi/sbm-big-graphs
|
/src/main/java/ir/ac/sbu/graph/spark/pattern/index/fonl/value/Meta.java
|
UTF-8
| 535
| 2.5
| 2
|
[] |
no_license
|
package ir.ac.sbu.graph.spark.pattern.index.fonl.value;
import java.io.Serializable;
public class Meta implements Serializable {
public int degree;
public Meta() {}
public Meta(int degree) {
this.degree = degree;
}
public Meta(Meta meta) {
degree = meta.degree;
}
public int getDegree() {
return degree;
}
public void setDegree(int degree) {
this.degree = degree;
}
@Override
public String toString() {
return "degree: " + degree;
}
}
| true
|
848d980574f25a797f932b15750127c0626cda57
|
Java
|
sxc588/studio
|
/MicroService/studio_project/support-ws/support-service-app/src/main/java/com/github/support/entitlement/ws/impl/UserServiceWsImpl10.java
|
UTF-8
| 1,560
| 2.25
| 2
|
[] |
no_license
|
package com.github.support.entitlement.ws.impl;
import java.util.ArrayList;
import java.util.List;
import javax.jws.WebService;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import com.github.support.entitlement.Dao.UserDao;
import com.github.support.entitlement.entity.User;
import com.github.support.entitlement.ws.UserServiceWs;
@Path(value="/userservicews")
public class UserServiceWsImpl10 implements UserServiceWs
{
private UserDao userDao ;
@GET
@Path("/add")
@Produces(MediaType.APPLICATION_JSON)
@Override
public void insert(String userid, String username, String useremail, int userage)
{
User user= new User();
user.setUserage(userage);
user.setUseremail(useremail);
user.setUserid(userid);
user.setUsername(username);
userDao.insert(user);
System. out .println( "insert successfully!" );
}
@GET
@Path("/user")
@Produces("text/plain")
@Override
public User getUserById(String userid)
{
return userDao.findUserById(userid);
}
@GET
@Path("/users")
@Produces("application/json")
@Consumes("application/json")
@Override
public List<User> getAllUsers()
{
User user= new User();
user.setUserage(10);
user.setUseremail("useremail");
user.setUserid("userid");
user.setUsername("username");
List<User> users= new ArrayList<User>();
users.add(user);
return users;
}
}
| true
|
abdeba7cef4a56e082119b90ae26fd498090f937
|
Java
|
debmalya/TransactionAnalyser
|
/src/test/java/org/deb/loader/CSVLoaderImplTest.java
|
UTF-8
| 827
| 2.265625
| 2
|
[
"Apache-2.0"
] |
permissive
|
package org.deb.loader;
import java.io.IOException;
import java.text.ParseException;
import java.util.Collection;
import org.deb.loader.impl.CSVLoaderImpl;
import org.deb.model.Transaction;
import org.junit.Assert;
import org.junit.Test;
public class CSVLoaderImplTest {
@Test
public void testLoadTransactions() {
CSVLoader loader = new CSVLoaderImpl();
try {
Collection<Transaction> transactions = loader.loadTransactions("./src/main/resources/transactions.csv");
Assert.assertNotNull(transactions);
// There is a reverse transaction, that transaction and related payment transaction will not be loaded.
Assert.assertEquals(4, transactions.size());
} catch (IOException | ParseException e) {
e.printStackTrace();
Assert.assertFalse(e.getMessage(),true);
}
}
}
| true
|
3d89f805d45b96a17bf35aa0f5af1837213cba99
|
Java
|
mosainet/Server_Manage_Plugin
|
/vRealize_Plugin/test/test-src/com/huawei/adapter/util/UtilsTest.java
|
UTF-8
| 733
| 2.265625
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.huawei.adapter.util;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
/**
* ConvertUtils单元测试类.
* @author harbor
*
*/
public class UtilsTest {
@Test
public void testConvertHealthState() {
assertEquals("Normal", ConvertUtils.convertHealthState(0));
assertEquals("Offline", ConvertUtils.convertHealthState(-1));
assertEquals("Unknown", ConvertUtils.convertHealthState(-2));
assertEquals("Faulty", ConvertUtils.convertHealthState(-3));
assertEquals("Faulty", ConvertUtils.convertHealthState(898));
}
@Test
public void testConvertPower() {
assertEquals("500", ConvertUtils.convertPower("500.0 W"));
}
}
| true
|
78434928e4460d09678af766709bb0839b737f34
|
Java
|
MVMurrell/VolunteerUp
|
/JPAItMakesAVillage/src/main/java/com/itmakesavillage/jpaproject/entities/ItemsNeeded.java
|
UTF-8
| 1,902
| 2.4375
| 2
|
[] |
no_license
|
package com.itmakesavillage.jpaproject.entities;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToOne;
import javax.persistence.Table;
@Entity
@Table(name="items_project")
public class ItemsNeeded {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@ManyToOne
@JoinColumn(name="project_id")
private Project project;
@OneToOne
@JoinColumn(name="item_id")
private Item item;
@Column(name="quantity_needed")
private int quantity;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Project getProject() {
return project;
}
public void setProject(Project project) {
this.project = project;
}
public Item getItem() {
return item;
}
public void setItem(Item item) {
this.item = item;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantiy) {
this.quantity = quantiy;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ItemsNeeded other = (ItemsNeeded) obj;
if (id != other.id)
return false;
return true;
}
@Override
public String toString() {
return "ItemsNeeded [id=" + id + ", project=" + project + ", item=" + item + ", quantiy=" + quantity + "]";
}
public ItemsNeeded(int id, Project project, Item item, int quantiy) {
super();
this.id = id;
this.project = project;
this.item = item;
this.quantity = quantiy;
}
public ItemsNeeded() {
super();
}
}
| true
|
17409e00a7e22f66082901780615568084b001d5
|
Java
|
PavelTCo/gwt-testtask
|
/test-task/src/main/java/com/example/test/task/shared/NamedData.java
|
UTF-8
| 670
| 2.46875
| 2
|
[] |
no_license
|
package com.example.test.task.shared;
import java.io.Serializable;
/**
*
* Data object which has name.
*
* @author Ilya Sviridov
*
*/
public class NamedData extends DataObject implements Serializable {
private static final long serialVersionUID = -3014279964664221172L;
/**
* Name
*/
String name;
/**
* Name getter
*
* @return
*/
public String getName() {
return name;
}
/**
* Name setter
*
* @return
*/
public void setName(String name) {
this.name = name;
}
/**
* Constructor
*/
public NamedData() {
super();
}
/**
* Constructor
*/
public NamedData(int id, String name) {
super(id);
this.name = name;
}
}
| true
|
9fdf04bc521265994eb46343e086952d8add06f8
|
Java
|
hybin0325/hybin
|
/springcloud/edas-system/edas-system-auth/src/main/java/com/edas/system/auth/configurer/AuthenticationServerConfig.java
|
UTF-8
| 5,910
| 1.875
| 2
|
[] |
no_license
|
package com.edas.system.auth.configurer;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.approval.ApprovalStore;
import org.springframework.security.oauth2.provider.approval.JdbcApprovalStore;
import org.springframework.security.oauth2.provider.code.AuthorizationCodeServices;
import org.springframework.security.oauth2.provider.code.JdbcAuthorizationCodeServices;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;
import com.edas.system.auth.configurer.custom.CustomTokenEnhancer;
import com.edas.system.auth.configurer.custom.CustomerAccessTokenConverter;
import com.edas.system.auth.exception.Oauth2WebResponseExceptionTranslator;
@Configuration
@EnableAuthorizationServer
public class AuthenticationServerConfig extends AuthorizationServerConfigurerAdapter {
@Autowired
@Qualifier("authenticationManagerBean")
private AuthenticationManager authenticationManager;
@Autowired
@Qualifier("userDetailsService")
UserDetailsService userDetailsService;
@Qualifier("dataSource")
@Autowired
DataSource dataSource;
@Autowired
private Oauth2WebResponseExceptionTranslator oauth2WebResponseExceptionTranslator;
/**
* jwt 对称加密密钥
*/
@Value("${spring.security.oauth2.jwt.signingKey}")
private String signingKey;
@Autowired
RedisConnectionFactory redisConnectionFactory;
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.jdbc(dataSource);
}
@SuppressWarnings("unchecked")
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
// endpoints.accessTokenConverter(accessTokenConverter());
// endpoints.tokenStore(tokenStore()).authenticationManager(authenticationManager);
endpoints.tokenStore(tokenStore()).authorizationCodeServices(authorizationCodeServices())
.approvalStore(approvalStore())
.tokenEnhancer(tokenEnhancerChain()).authenticationManager(authenticationManager)
.userDetailsService(userDetailsService)
.reuseRefreshTokens(true).exceptionTranslator(oauth2WebResponseExceptionTranslator);
// 配置TokenServices参数
DefaultTokenServices tokenServices = (DefaultTokenServices) endpoints
.getDefaultAuthorizationServerTokenServices();
tokenServices.setTokenStore(endpoints.getTokenStore());
tokenServices.setSupportRefreshToken(true);
tokenServices.setClientDetailsService(endpoints.getClientDetailsService());
tokenServices.setTokenEnhancer(endpoints.getTokenEnhancer());
tokenServices.setAccessTokenValiditySeconds((int) TimeUnit.DAYS.toSeconds(1)); // 1天
endpoints.tokenServices(tokenServices);
super.configure(endpoints);
}
@Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
// 允许表单认证
oauthServer.allowFormAuthenticationForClients();
//验证获取Token的验证信息 //对获取Token的请求不再拦截
oauthServer.tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()");
}
/**
* 自定义token
*
* @return tokenEnhancerChain
*/
@Bean
public TokenEnhancerChain tokenEnhancerChain() {
TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
tokenEnhancerChain.setTokenEnhancers(Arrays.asList(new CustomTokenEnhancer(), accessTokenConverter()));
return tokenEnhancerChain;
}
// JWT
@Bean
public JwtAccessTokenConverter accessTokenConverter() {
final JwtAccessTokenConverter accessTokenConverter = new JwtAccessTokenConverter();
// 测试用,资源服务使用相同的字符达到一个对称加密的效果,生产时候使用RSA非对称加密方式
accessTokenConverter.setSigningKey(signingKey);
accessTokenConverter.setAccessTokenConverter(new CustomerAccessTokenConverter());
return accessTokenConverter;
}
@Bean
public TokenStore tokenStore() {
RedisTokenStore tokenStore = new RedisTokenStore(redisConnectionFactory);
return tokenStore;
}
/**
* 授权信息持久化实现
*
* @return JdbcApprovalStore
*/
@Bean
public ApprovalStore approvalStore() {
return new JdbcApprovalStore(dataSource);
}
/**
* 授权码模式持久化授权码code
*
* @return JdbcAuthorizationCodeServices
*/
@Bean
protected AuthorizationCodeServices authorizationCodeServices() {
// 授权码存储等处理方式类,使用jdbc,操作oauth_code表
return new JdbcAuthorizationCodeServices(dataSource);
}
}
| true
|
3926fcb4ab622ff39f3c3fd65e7f51379d962a2f
|
Java
|
LHFData/Cg3L
|
/src/LoginCheck/DAO/UserDao.java
|
UTF-8
| 2,768
| 2.90625
| 3
|
[] |
no_license
|
package LoginCheck.DAO;
import LoginCheck.Bean.User;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
/**
* Created by LHF on 2017/6/29.
*/
/**
* DAO层,用于对数据库的访问。
*/
public class UserDao {
//查询数据库是否存在目标用户
private User user=null;
public boolean CheckUserExit(String Username, String Password){
ResultSet Result = null;
Statement stmt=null;
Connection conn=null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/lhf", "root", "as709394");
stmt = conn.createStatement();
String sql = "select * from java where User='" + Username + "' and password='" + Password+"'";
try {
Result = stmt.executeQuery(sql);
} catch (Exception var6) {
var6.printStackTrace();
}
if (Result.next()!=false) {
user=new User(Result.getString("User"),Result.getString("password"),Result.getInt("class"),Result.getString("email"));
Result.close();
stmt.close();
conn.close();
return true;
}
return false;
} catch (Exception var7) {
var7.printStackTrace();
return false;
}
}
//查询用户,并返回一个该用户的User类
public User CheckUser(String Username, String Password){
if(CheckUserExit(Username,Password))
return user;
else return null;
}
//往数据库添加用户,要求四项必填
public boolean AddUser(String Username, String Password, String Permit, String Email){
ResultSet Result = null;
Statement stmt=null;
Connection conn=null;
String sql=null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/lhf", "root", "as709394");
stmt = conn.createStatement();
if (CheckUserExit(Username,Password)) {
Result.close();
conn.close();
stmt.close();
return false;
}
else{
sql="insert into java values('"+Username+"','"+Password+"','"+Permit+ "','"+Email+"')";
System.out.println(Username+Password+Email);
int i=stmt.executeUpdate(sql);
if(i>0)
return true;
}
} catch (Exception var7) {
var7.printStackTrace();
return false;
}
return false;
}
}
| true
|
5c5cbe8bd926da4d5ced6e42b224ceff10e2d75a
|
Java
|
NeelamHimani/test
|
/PortalNotificationForActiveUser.java
|
UTF-8
| 550
| 1.515625
| 2
|
[] |
no_license
|
package Pages;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.Set;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import Test.ConstantVariables;
public class PortalNotificationForActiveUser {
public static void activeNotificationOfUser() throws IOException, InterruptedException {}
}
| true
|
c51570dd82384dca8e7098ef618d6027ed51196a
|
Java
|
ECNU-SEers/AchieveIt-server-cjl
|
/src/main/java/edu/ecnu/sei/group08/mapper/SkillMapper.java
|
UTF-8
| 301
| 1.53125
| 2
|
[] |
no_license
|
package edu.ecnu.sei.group08.mapper;
import org.springframework.stereotype.Repository;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import edu.ecnu.sei.group08.model.SkillDO;
/**
*
* @author chenjialei
*
*/
@Repository
public interface SkillMapper extends BaseMapper<SkillDO> {
}
| true
|
abc7a85d87fa71f7326f9665dce69d96bc881c13
|
Java
|
haris-rizwan/js_test
|
/JavaExercise/src/Practice1/webUrlCheck.java
|
UTF-8
| 1,174
| 3.296875
| 3
|
[] |
no_license
|
package Practice1;
import java.util.Scanner;
public class webUrlCheck {
public static void CheckUrl(String url){
String editUrl = url.substring(4); // getting the Url after www.
int x = editUrl.indexOf("."); // Index of second . from the edited url.
String Domain = editUrl.substring(++x);
switch (Domain){
case "com":
System.out.println(Domain+" Business address");
break;
case "edu":
System.out.println(Domain+" Educational institute address");
break;
case "gov":
System.out.println(Domain+" Government address");
break;
case "org":
System.out.println(Domain+" organisation address");
break;
default:
System.out.println(Domain+" Web address of a different entity");
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a Valid web address");
String webAddress = input.next();
CheckUrl(webAddress);
}
}
| true
|
15dc04a5062cdedf0a39c9e20d1f38dde7ff20a7
|
Java
|
zeeshanz/NHL-INFO
|
/NHL-APP/src/main/java/com/zeeshanz/nhl/mvp/PlayersListModel.java
|
UTF-8
| 2,943
| 2.359375
| 2
|
[] |
no_license
|
package com.zeeshanz.nhl.mvp;
import androidx.annotation.NonNull;
import android.util.Log;
import com.zeeshanz.nhl.model.Player;
import com.zeeshanz.nhl.model.PlayerInfo;
import com.zeeshanz.nhl.model.PlayerInfoResponse;
import com.zeeshanz.nhl.model.PlayersListResponse;
import com.zeeshanz.nhl.network.ApiClient;
import com.zeeshanz.nhl.network.ApiInterface;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class PlayersListModel implements PlayersListContract.Model {
private final String TAG = "PlayersListModel";
/**
* This function will fetch players data
* @param onFinishedListener on finished
*/
@Override
public void getPlayersData(final OnFinishedListener onFinishedListener, int teamId, final String teamName) {
ApiInterface apiService = ApiClient.getNHLClient().create(ApiInterface.class);
Call<PlayersListResponse> call = apiService.getPlayers(teamId);
call.enqueue(new Callback<PlayersListResponse>() {
@Override
public void onResponse(@NonNull Call<PlayersListResponse> call, @NonNull Response<PlayersListResponse> response) {
if (response.body() != null) {
List<Player> players = response.body().getPlayers();
Log.d(TAG, "Number of players received: " + players.size());
onFinishedListener.onFinished(players, teamName);
}
}
@Override
public void onFailure(@NonNull Call<PlayersListResponse> call, @NonNull Throwable t) {
// Log error here since request failed
Log.e(TAG, t.toString());
onFinishedListener.onFailure(t);
}
});
}
/**
* This function will fetch a players info
* @param onFinishedListener on finished
*/
@Override
public void getPlayerInfo(final OnFinishedListener onFinishedListener, int playerId) {
ApiInterface apiService = ApiClient.getNHLClient().create(ApiInterface.class);
Call<PlayerInfoResponse> call = apiService.getPlayerInfo(playerId);
call.enqueue(new Callback<PlayerInfoResponse>() {
@Override
public void onResponse(@NonNull Call<PlayerInfoResponse> call, @NonNull Response<PlayerInfoResponse> response) {
if (response.body() != null) {
PlayerInfo playerInfo = response.body().getPlayerInfo().get(0); // Since there will be only one object
onFinishedListener.onFinished(playerInfo);
}
}
@Override
public void onFailure(@NonNull Call<PlayerInfoResponse> call, @NonNull Throwable t) {
// Log error here since request failed
Log.e(TAG, t.toString());
onFinishedListener.onFailure(t);
}
});
}
}
| true
|
78dddd151aa2c2c05a42c0958fff39a1e9de2db1
|
Java
|
JSQLParser/JSqlParser
|
/src/test/java/net/sf/jsqlparser/util/deparser/StatementDeParserTest.java
|
UTF-8
| 15,413
| 1.898438
| 2
|
[
"Apache-2.0",
"LGPL-2.1-only"
] |
permissive
|
/*-
* #%L
* JSQLParser library
* %%
* Copyright (C) 2004 - 2019 JSQLParser
* %%
* Dual licensed under GNU LGPL 2.1 or Apache License 2.0
* #L%
*/
package net.sf.jsqlparser.util.deparser;
import net.sf.jsqlparser.JSQLParserException;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.LongValue;
import net.sf.jsqlparser.expression.StringValue;
import net.sf.jsqlparser.expression.operators.relational.ExpressionList;
import net.sf.jsqlparser.parser.CCJSqlParserUtil;
import net.sf.jsqlparser.schema.Column;
import net.sf.jsqlparser.schema.Table;
import net.sf.jsqlparser.statement.IfElseStatement;
import net.sf.jsqlparser.statement.SetStatement;
import net.sf.jsqlparser.statement.delete.Delete;
import net.sf.jsqlparser.statement.execute.Execute;
import net.sf.jsqlparser.statement.insert.Insert;
import net.sf.jsqlparser.statement.select.OrderByElement;
import net.sf.jsqlparser.statement.select.ParenthesedSelect;
import net.sf.jsqlparser.statement.select.PlainSelect;
import net.sf.jsqlparser.statement.select.SelectVisitor;
import net.sf.jsqlparser.statement.select.WithItem;
import net.sf.jsqlparser.statement.update.Update;
import net.sf.jsqlparser.statement.update.UpdateSet;
import net.sf.jsqlparser.statement.upsert.Upsert;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
@ExtendWith(MockitoExtension.class)
public class StatementDeParserTest {
@Mock
private ExpressionDeParser expressionDeParser;
@Mock
private SelectDeParser selectDeParser;
private StatementDeParser statementDeParser;
@BeforeEach
public void setUp() {
statementDeParser =
new StatementDeParser(expressionDeParser, selectDeParser, new StringBuilder());
}
@Test
@SuppressWarnings("PMD.JUnitTestsShouldIncludeAssert")
public void shouldUseProvidedDeparsersWhenDeParsingDelete() {
Delete delete = new Delete();
Table table = new Table();
Expression where = mock(Expression.class);
List<OrderByElement> orderByElements = new ArrayList<OrderByElement>();
OrderByElement orderByElement1 = new OrderByElement();
OrderByElement orderByElement2 = new OrderByElement();
Expression orderByElement1Expression = mock(Expression.class);
Expression orderByElement2Expression = mock(Expression.class);
delete.setTable(table);
delete.setWhere(where);
delete.setOrderByElements(orderByElements);
orderByElements.add(orderByElement1);
orderByElements.add(orderByElement2);
orderByElement1.setExpression(orderByElement1Expression);
orderByElement2.setExpression(orderByElement2Expression);
statementDeParser.visit(delete);
then(where).should().accept(expressionDeParser);
then(orderByElement1Expression).should().accept(expressionDeParser);
then(orderByElement2Expression).should().accept(expressionDeParser);
}
@Test
@SuppressWarnings("PMD.JUnitTestsShouldIncludeAssert")
public void shouldUseProvidedDeparsersWhenDeParsingInsert() {
Insert insert = new Insert();
Table table = new Table();
List<UpdateSet> duplicateUpdateSets = new ArrayList<>();
Column duplicateUpdateColumn1 = new Column();
Expression duplicateUpdateExpression1 = mock(Expression.class);
duplicateUpdateSets.add(new UpdateSet(duplicateUpdateColumn1, duplicateUpdateExpression1));
Column duplicateUpdateColumn2 = new Column();
Expression duplicateUpdateExpression2 = mock(Expression.class);
duplicateUpdateSets.add(new UpdateSet(duplicateUpdateColumn2, duplicateUpdateExpression2));
PlainSelect select = mock(PlainSelect.class);
List<WithItem> withItemsList = new ArrayList<WithItem>();
WithItem withItem1 = spy(new WithItem());
WithItem withItem2 = spy(new WithItem());
ParenthesedSelect withItem1SubSelect = mock(ParenthesedSelect.class);
ParenthesedSelect withItem2SubSelect = mock(ParenthesedSelect.class);
select.setWithItemsList(withItemsList);
insert.setSelect(select);
insert.setTable(table);
insert.withDuplicateUpdateSets(duplicateUpdateSets);
withItemsList.add(withItem1);
withItemsList.add(withItem2);
withItem1.setSelect(withItem1SubSelect);
withItem2.setSelect(withItem2SubSelect);
statementDeParser.visit(insert.withWithItemsList(withItemsList));
then(withItem1).should().accept((SelectVisitor) selectDeParser);
then(withItem2).should().accept((SelectVisitor) selectDeParser);
then(select).should().accept(selectDeParser);
then(duplicateUpdateExpression1).should().accept(expressionDeParser);
then(duplicateUpdateExpression1).should().accept(expressionDeParser);
}
@Test
@SuppressWarnings("PMD.JUnitTestsShouldIncludeAssert")
public void shouldUseProvidedDeParsersWhenDeParsingSelect() {
WithItem withItem1 = spy(new WithItem());
withItem1.setSelect(mock(ParenthesedSelect.class));
WithItem withItem2 = spy(new WithItem());
withItem2.setSelect(mock(ParenthesedSelect.class));
List<WithItem> withItemsList = new ArrayList<WithItem>();
withItemsList.add(withItem1);
withItemsList.add(withItem2);
PlainSelect plainSelect = mock(PlainSelect.class);
plainSelect.setWithItemsList(withItemsList);
statementDeParser.visit(plainSelect);
// then(withItem1).should().accept((SelectVisitor) selectDeParser);
// then(withItem2).should().accept((SelectVisitor) selectDeParser);
then(plainSelect).should().accept(selectDeParser);
}
@Test
@SuppressWarnings("PMD.JUnitTestsShouldIncludeAssert")
public void shouldUseProvidedDeParsersWhenDeParsingUpdateNotUsingSelect() {
Update update = new Update();
Expression where = mock(Expression.class);
List<OrderByElement> orderByElements = new ArrayList<OrderByElement>();
Column column1 = new Column();
Column column2 = new Column();
Expression expression1 = mock(Expression.class);
Expression expression2 = mock(Expression.class);
OrderByElement orderByElement1 = new OrderByElement();
OrderByElement orderByElement2 = new OrderByElement();
Expression orderByElement1Expression = mock(Expression.class);
Expression orderByElement2Expression = mock(Expression.class);
update.setWhere(where);
update.setOrderByElements(orderByElements);
update.addUpdateSet(column1, expression1);
update.addUpdateSet(column2, expression2);
orderByElements.add(orderByElement1);
orderByElements.add(orderByElement2);
orderByElement1.setExpression(orderByElement1Expression);
orderByElement2.setExpression(orderByElement2Expression);
statementDeParser.visit(update);
then(expressionDeParser).should().visit(column1);
then(expressionDeParser).should().visit(column2);
then(expression1).should().accept(expressionDeParser);
then(expression2).should().accept(expressionDeParser);
then(where).should().accept(expressionDeParser);
then(orderByElement1Expression).should().accept(expressionDeParser);
then(orderByElement2Expression).should().accept(expressionDeParser);
}
@Test
@SuppressWarnings("PMD.JUnitTestsShouldIncludeAssert")
public void shouldUseProvidedDeParsersWhenDeParsingUpdateUsingSelect() {
Update update = new Update();
List<Column> columns = new ArrayList<Column>();
Expression where = mock(Expression.class);
List<OrderByElement> orderByElements = new ArrayList<OrderByElement>();
Column column1 = new Column();
Column column2 = new Column();
OrderByElement orderByElement1 = new OrderByElement();
OrderByElement orderByElement2 = new OrderByElement();
Expression orderByElement1Expression = mock(Expression.class);
Expression orderByElement2Expression = mock(Expression.class);
update.setWhere(where);
update.setOrderByElements(orderByElements);
UpdateSet updateSet = new UpdateSet();
updateSet.add(column1);
updateSet.add(column2);
update.addUpdateSet(updateSet);
orderByElements.add(orderByElement1);
orderByElements.add(orderByElement2);
orderByElement1.setExpression(orderByElement1Expression);
orderByElement2.setExpression(orderByElement2Expression);
statementDeParser.visit(update);
then(expressionDeParser).should().visit(column1);
then(expressionDeParser).should().visit(column2);
then(where).should().accept(expressionDeParser);
then(orderByElement1Expression).should().accept(expressionDeParser);
then(orderByElement2Expression).should().accept(expressionDeParser);
}
@Test
@SuppressWarnings("PMD.JUnitTestsShouldIncludeAssert")
public void shouldUseProvidedDeParserWhenDeParsingExecute() {
Execute execute = new Execute();
ExpressionList expressions = new ExpressionList();
Expression expression1 = mock(Expression.class);
Expression expression2 = mock(Expression.class);
execute.setExprList(expressions);
expressions.add(expression1);
expressions.add(expression2);
statementDeParser.visit(execute);
then(expression1).should().accept(expressionDeParser);
then(expression2).should().accept(expressionDeParser);
}
@Test
@SuppressWarnings("PMD.JUnitTestsShouldIncludeAssert")
public void shouldUseProvidedDeParserWhenDeParsingSetStatement() {
String name = "name";
Expression expression = mock(Expression.class);
ExpressionList expressions = new ExpressionList();
expressions.add(expression);
SetStatement setStatement = new SetStatement(name, expressions);
statementDeParser.visit(setStatement);
then(expression).should().accept(expressionDeParser);
}
// private Matcher<ReplaceDeParser> replaceDeParserWithDeParsers(final
// Matcher<ExpressionDeParser> expressionDeParserMatcher, final Matcher<SelectDeParser>
// selectDeParserMatcher) {
// Description description = new StringDescription();
// description.appendText("replace de-parser with expression de-parser ");
// expressionDeParserMatcher.describeTo(description);
// description.appendText(" and select de-parser ");
// selectDeParserMatcher.describeTo(description);
// return new CustomTypeSafeMatcher<ReplaceDeParser>(description.toString()) {
// @Override
// public boolean matchesSafely(ReplaceDeParser item) {
// return expressionDeParserMatcher.matches(item.getExpressionVisitor()) &&
// selectDeParserMatcher.matches(item.getSelectVisitor());
// }
// };
// }
@Test
@SuppressWarnings("PMD.JUnitTestsShouldIncludeAssert")
public void shouldUseProvidedDeparsersWhenDeParsingUpsertWithExpressionList() {
Upsert upsert = new Upsert();
Table table = new Table();
List<Column> duplicateUpdateColumns = new ArrayList<Column>();
List<Expression> duplicateUpdateExpressionList = new ArrayList<Expression>();
Column duplicateUpdateColumn1 = new Column();
Column duplicateUpdateColumn2 = new Column();
Expression duplicateUpdateExpression1 = mock(Expression.class);
Expression duplicateUpdateExpression2 = mock(Expression.class);
PlainSelect select = mock(PlainSelect.class);
List<WithItem> withItemsList = new ArrayList<WithItem>();
WithItem withItem1 = spy(new WithItem());
WithItem withItem2 = spy(new WithItem());
ParenthesedSelect withItem1SubSelect = mock(ParenthesedSelect.class);
ParenthesedSelect withItem2SubSelect = mock(ParenthesedSelect.class);
select.setWithItemsList(withItemsList);
upsert.setSelect(select);
upsert.setTable(table);
upsert.setDuplicateUpdateSets(
Arrays.asList(
new UpdateSet(duplicateUpdateColumn1, duplicateUpdateExpression1),
new UpdateSet(duplicateUpdateColumn2, duplicateUpdateExpression2)));
withItemsList.add(withItem1);
withItemsList.add(withItem2);
withItem1.setSelect(withItem1SubSelect);
withItem2.setSelect(withItem2SubSelect);
statementDeParser.visit(upsert);
then(select).should().accept(selectDeParser);
then(duplicateUpdateExpression1).should().accept(expressionDeParser);
then(duplicateUpdateExpression1).should().accept(expressionDeParser);
}
@Test
@SuppressWarnings("PMD.JUnitTestsShouldIncludeAssert")
public void shouldUseProvidedDeparsersWhenDeParsingIfThenStatement()
throws JSQLParserException {
String sqlStr = "IF OBJECT_ID('tOrigin', 'U') IS NOT NULL DROP TABLE tOrigin1";
IfElseStatement ifElseStatement = (IfElseStatement) CCJSqlParserUtil.parse(sqlStr);
statementDeParser.deParse(ifElseStatement);
}
@Test
public void testIssue1500AllColumns() throws JSQLParserException {
String sqlStr = "select count(*) from some_table";
PlainSelect selectBody = (PlainSelect) CCJSqlParserUtil.parse(sqlStr);
selectBody.accept(new SelectDeParser());
}
@Test
public void testIssue1500AllTableColumns() throws JSQLParserException {
String sqlStr = "select count(a.*) from some_table a";
PlainSelect selectBody = (PlainSelect) CCJSqlParserUtil.parse(sqlStr);
selectBody.accept(new SelectDeParser());
}
@Test
public void testIssue1608DeparseValueList() throws JSQLParserException {
String providedSql =
"INSERT INTO example (num, name, address, tel) VALUES (1, 'name', 'test ', '1234-1234')";
String expectedSql = "INSERT INTO example (num, name, address, tel) VALUES (?, ?, ?, ?)";
net.sf.jsqlparser.statement.Statement statement = CCJSqlParserUtil.parse(providedSql);
StringBuilder builder = new StringBuilder();
ExpressionDeParser expressionDeParser = new ExpressionDeParser() {
@Override
public void visit(StringValue stringValue) {
buffer.append("?");
}
@Override
public void visit(LongValue longValue) {
buffer.append("?");
}
};
SelectDeParser selectDeParser = new SelectDeParser(expressionDeParser, builder);
expressionDeParser.setSelectVisitor(selectDeParser);
expressionDeParser.setBuffer(builder);
StatementDeParser statementDeParser =
new StatementDeParser(expressionDeParser, selectDeParser, builder);
statement.accept(statementDeParser);
Assertions.assertEquals(expectedSql, builder.toString());
}
}
| true
|
8a9bc2743cfd7e3d1f1fd5d06c96036774a77825
|
Java
|
todd-fritz/secure-data-service
|
/sli/sif/sif-agent/src/main/java/org/slc/sli/sif/domain/converter/NameConverter.java
|
UTF-8
| 2,775
| 2.171875
| 2
|
[
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0"
] |
permissive
|
/*
* Copyright 2012-2013 inBloom, Inc. and its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.slc.sli.sif.domain.converter;
import java.util.HashSet;
import java.util.Set;
import org.springframework.stereotype.Component;
import org.slc.sli.sif.domain.slientity.Name;
/**
* Converts a SIF Name to an SLI Name
*
* @author jtully
*
*/
@Component
public class NameConverter {
private static final Set<String> SLI_PREFIXES = new HashSet<String>();
private static final Set<String> SLI_SUFFIXES = new HashSet<String>();
static {
SLI_PREFIXES.add("Colonel");
SLI_PREFIXES.add("Dr");
SLI_PREFIXES.add("Mr");
SLI_PREFIXES.add("Mrs");
SLI_PREFIXES.add("Reverend");
SLI_PREFIXES.add("Sr");
SLI_PREFIXES.add("Sister");
SLI_SUFFIXES.add("Jr");
SLI_SUFFIXES.add("Sr");
SLI_SUFFIXES.add("II");
SLI_SUFFIXES.add("III");
SLI_SUFFIXES.add("IV");
SLI_SUFFIXES.add("V");
SLI_SUFFIXES.add("VI");
SLI_SUFFIXES.add("VII");
SLI_SUFFIXES.add("VIII");
}
private static final String DEFAULT_NAME = "Unknown";
public Name convert(openadk.library.common.Name sifName) {
if (sifName == null) {
return null;
}
Name sliName = new Name();
mapSifNameIntoSliName(sifName, sliName);
return sliName;
}
public void mapSifNameIntoSliName(openadk.library.common.Name sifName, Name sliName) {
if (sifName.getFirstName() != null) {
sliName.setFirstName(sifName.getFirstName());
} else {
sliName.setFirstName(DEFAULT_NAME);
}
if (sifName.getLastName() != null) {
sliName.setLastSurname(sifName.getLastName());
} else {
sliName.setLastSurname(DEFAULT_NAME);
}
sliName.setMiddleName(sifName.getMiddleName());
if (sifName.getPrefix() != null && SLI_PREFIXES.contains(sifName.getPrefix())) {
sliName.setPersonalTitlePrefix(sifName.getPrefix());
}
if (sifName.getSuffix() != null && SLI_SUFFIXES.contains(sifName.getSuffix())) {
sliName.setGenerationCodeSuffix(sifName.getSuffix());
}
}
}
| true
|
022df42715c0ecb0d86b949dc80df8cbf3f9f7ae
|
Java
|
chojiyeon/testPro
|
/src/abc/Main.java
|
UHC
| 217
| 1.765625
| 2
|
[] |
no_license
|
package abc;
public class Main {
public static void main(String[] args) {
System.out.println("Ŭ ");
System.out.println("import");
System.out.println("branch");
}
}
| true
|
9d95fda0a960ea7214b6d6013dcad2330ccc10d0
|
Java
|
KhaledSMQ/BDM-Components
|
/collectors/openbus.mqcollector/src/main/java/br/com/produban/openbus/mq/parser/exception/MessageParserNotDefinedException.java
|
UTF-8
| 254
| 1.789063
| 2
|
[
"Apache-2.0"
] |
permissive
|
package br.com.produban.openbus.mq.parser.exception;
public class MessageParserNotDefinedException extends Exception {
private static final long serialVersionUID = 1L;
public MessageParserNotDefinedException(String message) {
super(message);
}
}
| true
|
bfeb43ad781afd371f782e7b9d58bf28d7410b98
|
Java
|
kongodream/bookcrossing
|
/src/main/java/com/dataLayer/entity/Book.java
|
UTF-8
| 2,227
| 2.421875
| 2
|
[] |
no_license
|
package com.dataLayer.entity;
import com.dataLayer.entity.dto.RequestBook;
import javax.persistence.*;
import java.util.List;
@javax.persistence.Entity
@Table(name = "books")
public class Book extends Entity {
@Column
private String name;
@Column
private String author;
@Column
private String genre;
@ManyToOne
private User creator;
@ManyToOne
private User owner;
@Column
private String picture;
@Column
private String description;
@OneToMany(mappedBy = "book",fetch = FetchType.EAGER)
private List<Transfer> transfers;
public Book() {
}
public Book(RequestBook book, User creator) {
this.name = book.getName();
this.author = book.getAuthor();
this.description = book.getDescription();
this.genre = book.getGenre();
this.picture = book.getPicture();
this.creator = creator;
this.owner = creator;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getGenre() {
return genre;
}
public void setGenre(String genre) {
this.genre = genre;
}
public User getCreator() {
return creator;
}
public void setCreator(User creator) {
this.creator = creator;
}
public List<Transfer> getTransfers() {
return transfers;
}
public void setTransfers(List<Transfer> transfers) {
this.transfers = transfers;
}
public String getPicture() {
return picture;
}
public void setPicture(String picture) {
this.picture = picture;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public User getOwner() {
return owner;
}
public void setOwner(User owner) {
this.owner = owner;
}
}
| true
|
21362e281231e34825e3389f74017d392892dbe9
|
Java
|
bus503/java_swing_study
|
/src/java_swing_study/chap13/TimerRunnable.java
|
UTF-8
| 617
| 3.234375
| 3
|
[] |
no_license
|
package java_swing_study.chap13;
import java.awt.Color;
import javax.swing.JLabel;
public class TimerRunnable implements Runnable {
private JLabel leftLable;
public TimerRunnable(JLabel leftLable) {
this.leftLable = leftLable;
}
@Override
public void run() {
int n = 100;
while (true) {
leftLable.setText(Integer.toString(n));
leftLable.setBackground(n%2==0? Color.ORANGE: Color.RED);
n--;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
leftLable.setText("Stop");
return;
}
leftLable.setBackground(Color.BLUE);
}
}
}
| true
|
67abd6113c5035f36ea5a913b4e7929e229baf4f
|
Java
|
timboudreau/netbeans-contrib
|
/j2ee.geronimo2/src/main/java/org/netbeans/modules/j2ee/geronimo2/GeStartRunnable.java
|
UTF-8
| 7,471
| 1.851563
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
* The contents of this file are subject to the terms of the Common Development
* and Distribution License (the License). You may not use this file except in
* compliance with the License.
*
* You can obtain a copy of the License at http://www.netbeans.org/cddl.html
* or http://www.netbeans.org/cddl.txt.
*
* When distributing Covered Code, include this CDDL Header Notice in each file
* and include the License file at http://www.netbeans.org/cddl.txt.
* If applicable, add the following below the CDDL Header, with the fields
* enclosed by brackets [] replaced by your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
* Microsystems, Inc. All Rights Reserved.
*/
package org.netbeans.modules.j2ee.geronimo2;
import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.enterprise.deploy.shared.ActionType;
import javax.enterprise.deploy.shared.CommandType;
import javax.enterprise.deploy.shared.StateType;
import org.netbeans.api.java.platform.JavaPlatform;
import org.netbeans.modules.j2ee.deployment.plugins.api.InstanceProperties;
import org.netbeans.modules.j2ee.geronimo2.util.GeLogger;
import org.openide.execution.NbProcessDescriptor;
import org.openide.filesystems.FileObject;
import org.openide.filesystems.FileUtil;
import org.openide.util.NbBundle;
import org.openide.util.Utilities;
/**
* @author Max Sauer
*/
class GeStartRunnable implements Runnable {
static final String SCRIPT_UNIX = "geronimo.sh"; // NOI18N
static final String SCRIPT_WIN = "geronimo.bat"; // NOI18N
private static final Logger LOGGER = Logger.getLogger(GeStartRunnable.class.getName());
private GeDeploymentManager dm;
private String instanceName;
private GeStartServer startServer;
private InstanceProperties ip;
/**
* The amount of time in milliseconds during which the server should
* start
*/
private static final int TIMEOUT = 120000;
/**
* The amount of time in milliseconds that we should wait between checks
*/
private static final int DELAY = 1000;
public GeStartRunnable(GeDeploymentManager dm, GeStartServer startServer) {
this.dm = dm;
this.ip = dm.getProperties().getInstanceProperties();
this.instanceName = ip.getProperty(InstanceProperties.DISPLAY_NAME_ATTR);
this.startServer = startServer;
}
public void run() {
// Save the current time so that we can deduct that the startup
// Failed due to timeout
long start = System.currentTimeMillis();
Process serverProcess = createProcess();
if (serverProcess == null) {
return;
}
fireStartProgressEvent(StateType.RUNNING, createProgressMessage("MSG_START_SERVER_IN_PROGRESS"));
// create a logger to the server's output stream so that a user
// can observe the progress
GeLogger.getInstance(dm.getUri()).readInputStreams(new InputStream[] {
serverProcess.getInputStream(), serverProcess.getErrorStream()});
// Waiting for server to start
while (System.currentTimeMillis() - start < TIMEOUT) {
// Send the 'completed' event and return when the server is running
if (startServer.isRunning()) {
fireStartProgressEvent(StateType.COMPLETED, createProgressMessage("MSG_SERVER_STARTED")); // NOI18N
return;
}
// Sleep for a little so that we do not make our checks too
// Often
try {
Thread.sleep(DELAY);
} catch (InterruptedException e) {}
}
// If the server did not start in the designated time limits
// We consider the startup as failed and warn the user
fireStartProgressEvent(StateType.FAILED, createProgressMessage("MSG_START_SERVER_FAILED"));
}
private String[] createEnvironment() {
StringBuilder javaOpts = new StringBuilder();
List<String> envp = new ArrayList<String>(3);
String rootDir = ip.getProperty(GePluginProperties.PROPERTY_GE_HOME);
JavaPlatform platform = dm.getProperties().getJavaPlatform();
FileObject fo = (FileObject) platform.getInstallFolders().iterator().next();
String javaHome = FileUtil.toFile(fo).getAbsolutePath();
if(startServer.getMode() == GeStartServer.MODE.DEBUG) {
javaOpts.append(" -classic -Xdebug -Xnoagent -Djava.compiler=NONE -Xrunjdwp:transport=dt_socket,address="). // NOI18N
append(dm.getProperties().getDebugPort()).
append(",server=y,suspend=n"); // NOI18N
}
envp.add("GE_HOME=" + rootDir); // NOI18N
envp.add("JAVA_HOME=" + javaHome); // NOI18N
envp.add("GE_JVM_ARGS=" + javaOpts); // NOI18N
envp.add("VERBOSE=on"); // NOI18N
return (String[]) envp.toArray(new String[envp.size()]);
}
private NbProcessDescriptor createProcessDescriptor() {
final String serverLocation = ip.getProperty(GePluginProperties.PROPERTY_GE_HOME);
final String startScript = serverLocation + File.separator + "bin" + File.separator +
(Utilities.isWindows() ? SCRIPT_WIN : SCRIPT_UNIX); //NOI18N
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.log(Level.FINER, "serverLocation: " + serverLocation + ", startScript: " + startScript);
}
if (!new File(startScript).exists()) {
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.log(Level.FINER, "startScript " + startScript + " doesn't exist");
}
fireStartProgressEvent(StateType.FAILED, createProgressMessage("MSG_START_SERVER_FAILED_FNF")); //NOI18N
return null;
}
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.log(Level.FINER, "EXEC: " + startScript + " run ");
}
return new NbProcessDescriptor(startScript, "run"); //NOI18N
}
private Process createProcess() {
NbProcessDescriptor pd = createProcessDescriptor();
if (pd == null)
return null;
try {
return pd.exec(null, createEnvironment(), true, new File(ip.getProperty(GePluginProperties.PROPERTY_GE_HOME)));
} catch (java.io.IOException ioe) {
LOGGER.log(Level.INFO, null, ioe);
fireStartProgressEvent(StateType.FAILED, createProgressMessage("MSG_START_SERVER_FAILED_PD"));
return null;
}
}
private String createProgressMessage(final String resName) {
return createProgressMessage(resName, null);
}
private String createProgressMessage(final String resName, final String param) {
return NbBundle.getMessage(GeStartRunnable.class, resName, instanceName, param);
}
private void fireStartProgressEvent(StateType stateType, String msg) {
startServer.fireHandleProgressEvent(null, new GeDeploymentStatus(ActionType.EXECUTE, CommandType.START, stateType, msg));
}
}
| true
|
4d9fd9e3ccb1a1c27ecb0eb9cb586e07610b747a
|
Java
|
rosneru/PSim
|
/src/control/GUI_WindowWeights.java
|
UTF-8
| 3,883
| 3.109375
| 3
|
[] |
no_license
|
package control;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
/**
* Diese Klasse stellt ein Fenster zum Eingeben von Gewichten zur Verfügung.
* @author Uwe Rosner
*
*/
public class GUI_WindowWeights extends JFrame {
private static final long serialVersionUID = 1L;
private JTextField[] textFields = null;
ButtonGroup buttonGroup = new ButtonGroup();
private JPanel panel = new JPanel();
private JButton buttOK;
private JButton buttCancel;
/**
* Konstruktor zum Bereitstellen eines Fensters zur numerischen Eingabe von Gewichten.
* @param act ActionListener an den die Events der Schaltflächen "OK" und "Abbrechen" gesendet werden
* @param identifiers Die Bezeichnungen der Gewichte.
* @param weights Die Gewichte.
*/
public GUI_WindowWeights(ActionListener act, String[] identifiers, String[] weights) {
this.setLayout(new BoxLayout(this.getContentPane(), BoxLayout.Y_AXIS));
this.setMinimumSize(new Dimension(480, 50));
this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
this.setTitle("Gewichte für '" + identifiers[0] + "'.");
// auskommentiert: verursacht bei Applets eine Exception
// this.setAlwaysOnTop(true);
panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
buttOK = new JButton("Ok");
buttOK.setActionCommand("WinWeightsOK");
buttOK.addActionListener(act);
buttCancel = new JButton("Cancel");
buttCancel.setActionCommand("WinWeightsCANCEL");
buttCancel.addActionListener(act);
panel.add(Box.createHorizontalStrut(10));
panel.add(buttOK);
panel.add(Box.createHorizontalGlue());
panel.add(buttCancel);
panel.add(Box.createHorizontalStrut(10));
JPanel[] p;
if(identifiers.length < 2) {
p = new JPanel[identifiers.length];
}
else {
p = new JPanel[identifiers.length - 1];
}
if(identifiers.length < 2) { // Es gibt keine veränderbaren Gewichte
p[0] = new JPanel();
p[0].add(new JLabel("No wieghts can be set for this item. Weights only can be set for transitions."));
}
else {
textFields = new JTextField[p.length];
for(int i = 0; i < p.length; i++) {
p[i] = new JPanel();
p[i].setLayout(new BoxLayout(p[i], BoxLayout.X_AXIS));
p[i].add(Box.createHorizontalStrut(10));
p[i].add(new JLabel(identifiers[i + 1]));
p[i].add(Box.createHorizontalStrut(10));
textFields[i] = new JTextField(weights[i]);
p[i].add(textFields[i]);
p[i].add(Box.createHorizontalStrut(10));
}
}
for(int i = 0; i < p.length; i++) {
this.add(Box.createVerticalStrut(10));
this.getContentPane().add(p[i]);
}
this.add(Box.createVerticalStrut(10));
this.getContentPane().add(panel);
this.add(Box.createVerticalStrut(10));
this.pack();
}
/**
* Übergibt die im Gewichtefenster einegebenen Gewichte.
* @return Die eingegebenen Eigenschaften
*/
public String[] getWeights() {
// die Werte in allen Textfeldern in einem String-Array zurückgeben
if(textFields == null) { // Wenn Element keine änderbaren Eigenschaften besitzt
return null; // gib leeres String-Array zurück
}
String[] str = new String[textFields.length];
for(int i = 0; i < textFields.length; i++) {
str[i] = textFields[i].getText();
}
return str;
}
/**
* Schließt das Gewichtefenster
*/
public void closeWindow() {
dispose();
}
}
| true
|
311797d2a1cd3e76ed47b0f78f5f3d2e6398f497
|
Java
|
BruceHurrican/studydemo
|
/libs_src/v4src/api21/android/support/v4/view/ViewParentCompatLollipop.java
|
UTF-8
| 3,926
| 2.015625
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright (C) 2015 The Android Open Source Project
*
* 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 android.support.v4.view;
import android.util.Log;
import android.view.View;
import android.view.ViewParent;
class ViewParentCompatLollipop {
private static final String TAG = "ViewParentCompat";
public static boolean onStartNestedScroll(ViewParent parent, View child, View target,
int nestedScrollAxes) {
try {
return parent.onStartNestedScroll(child, target, nestedScrollAxes);
} catch (AbstractMethodError e) {
Log.e(TAG, "ViewParent " + parent + " does not implement interface " +
"method onStartNestedScroll", e);
return false;
}
}
public static void onNestedScrollAccepted(ViewParent parent, View child, View target,
int nestedScrollAxes) {
try {
parent.onNestedScrollAccepted(child, target, nestedScrollAxes);
} catch (AbstractMethodError e) {
Log.e(TAG, "ViewParent " + parent + " does not implement interface " +
"method onNestedScrollAccepted", e);
}
}
public static void onStopNestedScroll(ViewParent parent, View target) {
try {
parent.onStopNestedScroll(target);
} catch (AbstractMethodError e) {
Log.e(TAG, "ViewParent " + parent + " does not implement interface " +
"method onStopNestedScroll", e);
}
}
public static void onNestedScroll(ViewParent parent, View target, int dxConsumed,
int dyConsumed, int dxUnconsumed, int dyUnconsumed) {
try {
parent.onNestedScroll(target, dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed);
} catch (AbstractMethodError e) {
Log.e(TAG, "ViewParent " + parent + " does not implement interface " +
"method onNestedScroll", e);
}
}
public static void onNestedPreScroll(ViewParent parent, View target, int dx, int dy,
int[] consumed) {
try {
parent.onNestedPreScroll(target, dx, dy, consumed);
} catch (AbstractMethodError e) {
Log.e(TAG, "ViewParent " + parent + " does not implement interface " +
"method onNestedPreScroll", e);
}
}
public static boolean onNestedFling(ViewParent parent, View target, float velocityX,
float velocityY, boolean consumed) {
try {
return parent.onNestedFling(target, velocityX, velocityY, consumed);
} catch (AbstractMethodError e) {
Log.e(TAG, "ViewParent " + parent + " does not implement interface " +
"method onNestedFling", e);
return false;
}
}
public static boolean onNestedPreFling(ViewParent parent, View target, float velocityX,
float velocityY) {
try {
return parent.onNestedPreFling(target, velocityX, velocityY);
} catch (AbstractMethodError e) {
Log.e(TAG, "ViewParent " + parent + " does not implement interface " +
"method onNestedPreFling", e);
return false;
}
}
}
| true
|
3e53d98cc997cd0ea72a0a7af8aac786fb28dbbd
|
Java
|
Amorpheuz/KanbandBoards
|
/src/kanbandboards/impl/BoardColumnDaoImpl.java
|
UTF-8
| 6,236
| 2.640625
| 3
|
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package kanbandboards.impl;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import kanbandboards.dao.BoardColumnDao;
import kanbandboards.entity.BoardColumn;
import kanbandboards.entity.Card;
import kanbandboards.util.DbConnection;
/**
*
* @author Yash
*/
public class BoardColumnDaoImpl implements BoardColumnDao{
@Override
public boolean addBoardColumn(BoardColumn bCol) {
Connection conn = DbConnection.getConnection();
String query = "insert into board_cols(col_name,col_constraints) values(?,?)";
try {
PreparedStatement preparedStatement = conn.prepareStatement(query);
preparedStatement.setString(1, bCol.getColName());
preparedStatement.setString(2, bCol.getColConstraints());
int rec = preparedStatement.executeUpdate();
if (rec == 1){
return true;
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return false;
}
@Override
public ArrayList<BoardColumn> getBoardColumns() {
Connection connection = DbConnection.getConnection();
try {
String query = "Select * from board_cols";
PreparedStatement preparedStatement = connection.prepareStatement(query);
ResultSet bcols = preparedStatement.executeQuery();
ArrayList<BoardColumn> boardCols = new ArrayList<>();
while (bcols.next()){
String subQuery = "Select * from cards where col_id = ?";
PreparedStatement preparedStatementSub = connection.prepareStatement(subQuery);
preparedStatementSub.setInt(1,bcols.getInt(1));
ResultSet crds = preparedStatementSub.executeQuery();
ArrayList<Card> cards = new ArrayList<>();
while(crds.next()){
cards.add(new Card(crds.getInt(1),crds.getInt(2),crds.getInt(3),crds.getInt(4),crds.getString(5),crds.getDate(6).toLocalDate().atStartOfDay()));
}
boardCols.add(new BoardColumn(bcols.getInt(1),bcols.getString(2), bcols.getString(3),cards));
}
if (boardCols.size() > 0){
return boardCols;
}
} catch (SQLException e) {
e.printStackTrace();
}
finally {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return null;
}
@Override
public BoardColumn getBoardColumn(int colId) {
Connection connection = DbConnection.getConnection();
try {
String query = "Select * from board_cols where col_id = ?";
PreparedStatement preparedStatement = connection.prepareStatement(query);
preparedStatement.setInt(1,colId);
ResultSet bcols = preparedStatement.executeQuery();
if (bcols.next()){
String subQuery = "Select * from cards where col_id = ?";
PreparedStatement preparedStatementSub = connection.prepareStatement(subQuery);
preparedStatementSub.setInt(1,bcols.getInt(1));
ResultSet crds = preparedStatementSub.executeQuery();
ArrayList<Card> cards = new ArrayList<>();
while(crds.next()){
cards.add(new Card(crds.getInt(1),crds.getInt(2),crds.getInt(3),crds.getInt(4),crds.getString(5),crds.getObject(4, LocalDateTime.class)));
}
BoardColumn boardCol = new BoardColumn(bcols.getInt(1),bcols.getString(2), bcols.getString(3),cards);
return boardCol;
}
} catch (SQLException e) {
e.printStackTrace();
}
finally {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return null;
}
@Override
public boolean updateBoardColumn(BoardColumn bCol) {
Connection connection = DbConnection.getConnection();
String query = "update board_cols set col_name = ?, col_constraints = ? where col_id = ?";
try {
PreparedStatement preparedStatement = connection.prepareStatement(query);
preparedStatement.setString(1, bCol.getColName());
preparedStatement.setString(2, bCol.getColConstraints());
preparedStatement.setInt(3, bCol.getColId());
int rec = preparedStatement.executeUpdate();
if (rec == 1){
return true;
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return false;
}
@Override
public boolean delBoardColumn(int colId) {
Connection connection = DbConnection.getConnection();
String query = "delete from board_cols where col_id = ?";
try {
PreparedStatement preparedStatement = connection.prepareStatement(query);
preparedStatement.setInt(1, colId);
int rec = preparedStatement.executeUpdate();
if (rec == 1){
return true;
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return false;
}
public int getColumnCount(){
ArrayList<BoardColumn> bCols = getBoardColumns();
return bCols.size();
}
}
| true
|
3e366da440251462e83cc5161d3fe8c69e735556
|
Java
|
Rope-a-dope/QuickFood
|
/onlineOrder/entity/Restaurant.java
|
UTF-8
| 1,578
| 2.140625
| 2
|
[
"MIT"
] |
permissive
|
package com.laioffer.onlineOrder.entity;
import com.fasterxml.jackson.annotation.JsonIgnore;
import javax.persistence.*;
import java.io.Serializable;
import java.util.List;
@Entity
@Table(name = "restaurants")
public class Restaurant implements Serializable {
private static final long serialVersionUID = 2455760938054036111L;
@Id
private int id;
private String address;
private String name;
private String phone;
private String imageUrl;
public List<MenuItem> getMenuItemList() {
return menuItemList;
}
public void setMenuItemList(List<MenuItem> menuItemList) {
this.menuItemList = menuItemList;
}
@OneToMany(mappedBy = "restaurant", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JsonIgnore
private List<MenuItem> menuItemList;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
}
| true
|
91fedccec4bcae5971048fc6bd423f2472360fca
|
Java
|
bndly/bndly-commons
|
/rest/entity-resource/src/main/java/org/bndly/rest/entity/resources/ConstraintViolationExceptionMapper.java
|
UTF-8
| 1,967
| 1.953125
| 2
|
[
"Apache-2.0"
] |
permissive
|
package org.bndly.rest.entity.resources;
/*-
* #%L
* REST Entity Resource
* %%
* Copyright (C) 2013 - 2020 Cybercon GmbH
* %%
* 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.
* #L%
*/
import org.bndly.rest.controller.api.ExceptionMapper;
import org.bndly.rest.controller.api.Response;
import org.bndly.rest.common.beans.error.ErrorRestBean;
import org.bndly.rest.common.beans.util.ExceptionMessageUtil;
import org.bndly.schema.api.exception.ConstraintViolationException;
import org.bndly.schema.model.Attribute;
import org.bndly.schema.model.UniqueConstraint;
import java.util.List;
import org.osgi.service.component.annotations.Component;
@Component(service = ExceptionMapper.class)
public class ConstraintViolationExceptionMapper implements ExceptionMapper<ConstraintViolationException> {
@Override
public Response toResponse(ConstraintViolationException e) {
ErrorRestBean msg = new ErrorRestBean();
msg.setName("ConstraintViolation");
ExceptionMessageUtil.createKeyValue(msg, "constraintType", "unique");
UniqueConstraint constraint = e.getConstraint();
if (constraint != null) {
List<Attribute> atts = constraint.getAttributes();
if (atts != null) {
for (Attribute attribute : atts) {
ExceptionMessageUtil.createKeyValue(msg, "attribute", attribute.getName());
}
}
ExceptionMessageUtil.createKeyValue(msg, "holder", constraint.getHolder().getName());
}
return Response.status(400).entity(msg);
}
}
| true
|
7c7ab32541a29b5c479d903f24722b3b99869cc0
|
Java
|
bipul14/Testing
|
/Workingwithjdbc/src/com/wwjdbc/connection/MysqlDbconnection.java
|
UTF-8
| 222
| 1.789063
| 2
|
[] |
no_license
|
package com.wwjdbc.connection;
import java.sql.Connection;
import java.sql.SQLException;
public interface MysqlDbconnection {
public Connection newConnection() throws ClassNotFoundException, SQLException ;
}
| true
|
4466447021ae4aed5995a1974f5f9ce1b930f28f
|
Java
|
mauriziocescon/zipkin
|
/zipkin-storage/cassandra-v1/src/test/java/zipkin2/storage/cassandra/v1/ITEnsureSchema.java
|
UTF-8
| 4,930
| 1.625
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright 2015-2020 The OpenZipkin Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package zipkin2.storage.cassandra.v1;
import com.datastax.oss.driver.api.core.CqlSession;
import com.datastax.oss.driver.api.core.metadata.schema.KeyspaceMetadata;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInfo;
import zipkin2.CheckResult;
import zipkin2.Span;
import zipkin2.TestObjects;
import zipkin2.storage.ITStorage;
import zipkin2.storage.QueryRequest;
import zipkin2.storage.StorageComponent;
import static java.util.Arrays.asList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static zipkin2.TestObjects.BACKEND;
import static zipkin2.TestObjects.appendSuffix;
import static zipkin2.TestObjects.newTrace;
/** This test is very slow as installing the schema can take 10s per method. */
abstract class ITEnsureSchema extends ITStorage<CassandraStorage> {
@Override protected abstract CassandraStorage.Builder newStorageBuilder(
TestInfo testInfo);
@Override protected void configureStorageForTest(StorageComponent.Builder storage) {
((CassandraStorage.Builder) storage).ensureSchema(false)
.autocompleteKeys(asList("environment"));
}
@Override protected boolean initializeStoragePerTest() {
return true; // We need a different keyspace per test
}
@Override protected void checkStorage() {
// don't check as it requires the keyspace which these tests install
}
abstract CqlSession session();
@Test public void installsKeyspaceWhenMissing() {
Schema.ensureExists(storage.keyspace, session());
KeyspaceMetadata metadata = session().getMetadata().getKeyspace(storage.keyspace).get();
assertThat(metadata).isNotNull();
assertThat(Schema.hasUpgrade1_defaultTtl(metadata)).isTrue();
}
@Test public void installsTablesWhenMissing() {
session().execute("CREATE KEYSPACE " + storage.keyspace
+ " WITH replication = {'class': 'SimpleStrategy', 'replication_factor': '1'};");
Schema.ensureExists(storage.keyspace, session());
KeyspaceMetadata metadata = session().getMetadata().getKeyspace(storage.keyspace).get();
assertThat(metadata).isNotNull();
assertThat(Schema.hasUpgrade1_defaultTtl(metadata)).isTrue();
assertThat(metadata.getTable("autocomplete_tags")).isPresent();
}
@Test public void upgradesOldSchema() {
Schema.applyCqlFile(storage.keyspace, session(), "/cassandra-schema-cql3-original.txt");
Schema.ensureExists(storage.keyspace, session());
KeyspaceMetadata metadata = session().getMetadata().getKeyspace(storage.keyspace).get();
assertThat(metadata).isNotNull();
assertThat(Schema.hasUpgrade1_defaultTtl(metadata)).isTrue();
assertThat(Schema.hasUpgrade2_autocompleteTags(metadata)).isTrue();
}
/** This tests we don't accidentally rely on new indexes such as autocomplete tags */
@Test public void worksWithOldSchem(TestInfo testInfo) throws Exception {
String testSuffix = testSuffix(testInfo);
Schema.applyCqlFile(storage.keyspace, session(), "/cassandra-schema-cql3-original.txt");
// Ensure the storage component is functional before proceeding
CheckResult check = storage.check();
if (!check.ok()) {
throw new AssertionError("Could not connect to storage: "
+ check.error().getMessage(), check.error());
}
List<Span> trace = newTrace(testSuffix);
accept(trace);
assertGetTraceReturns(trace.get(0).traceId(), trace);
assertThat(storage.autocompleteTags().getValues("environment").execute())
.isEmpty(); // instead of an exception
String serviceName = TestObjects.TRACE.get(0).localServiceName();
assertThat(storage.serviceAndSpanNames().getRemoteServiceNames(serviceName).execute())
.isEmpty(); // instead of an exception
QueryRequest request = requestBuilder()
.serviceName(serviceName)
.remoteServiceName(appendSuffix(BACKEND.serviceName(), testSuffix)).build();
// Make sure there's an error if a query will return incorrectly vs returning invalid results
assertThatThrownBy(() -> storage.spanStore().getTraces(request))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("remoteService=" + trace.get(1).remoteServiceName() +
" unsupported due to missing table service_remote_service_name_index");
}
}
| true
|
02273bcc0a9b1c07fc2b5c49a8f47f87e3552508
|
Java
|
IvanCherepica/business-analizer-core
|
/src/main/java/dto/MapPointDTO.java
|
UTF-8
| 1,764
| 2.34375
| 2
|
[] |
no_license
|
package dto;
import model.BizType;
import model.Point;
public class MapPointDTO {
private Long id;
private String name;
private String addres;
private Double longitude;
private Double latitude;
private BizType typeId;
private String type = "Point";
private Double[] coordinates;
public MapPointDTO(Point point) {
this.id = point.getId();
this.name = point.getName();
this.addres = point.getAddres();
this.longitude = point.getLongitude();
this.latitude = point.getLatitude();
this.typeId = point.getBizType();
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddres() {
return addres;
}
public void setAddres(String addres) {
this.addres = addres;
}
public Double getLongitude() {
return longitude;
}
public void setLongitude(Double longitude) {
this.longitude = longitude;
}
public Double getLatitude() {
return latitude;
}
public void setLatitude(Double latitude) {
this.latitude = latitude;
}
public BizType getTypeId() {
return typeId;
}
public void setTypeId(BizType typeId) {
this.typeId = typeId;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Double[] getCoordinates() {
return coordinates;
}
public void setCoordinates(Double[] coordinates) {
this.coordinates = coordinates;
}
}
| true
|
0f3155887a7c82589c60ae67ed03b934d3c27c77
|
Java
|
davidlapu/M07_UF1_P1.6Books
|
/app/src/main/java/cat/itb/m07_uf1_p16books/fragments/BookListFragment.java
|
UTF-8
| 1,886
| 2.078125
| 2
|
[] |
no_license
|
package cat.itb.m07_uf1_p16books.fragments;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.navigation.Navigation;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import cat.itb.m07_uf1_p16books.R;
import cat.itb.m07_uf1_p16books.models.BooksViewModel;
import cat.itb.m07_uf1_p16books.recycler_view.BookAdapter;
public class BookListFragment extends Fragment {
private RecyclerView recyclerView;
private BooksViewModel booksViewModel;
private FloatingActionButton floatingActionButton;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
booksViewModel = new ViewModelProvider(requireActivity()).get(BooksViewModel.class);
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_book_list, container, false);
recyclerView = v.findViewById(R.id.recyclerViewBooks);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
BookAdapter bookAdapter = new BookAdapter(booksViewModel.getBookList());
recyclerView.setAdapter(bookAdapter);
floatingActionButton = v.findViewById(R.id.floatingActionButton);
floatingActionButton.setOnClickListener(v1 ->
Navigation.findNavController(v).navigate(R.id.action_bookListFragment_to_bookInfoFragment));
return v;
}
}
| true
|
15448aa71837865005c7cec2aee52ed789b2f4e1
|
Java
|
KytoDragon/Pokemon_Java
|
/src/sequenze/PokemonBaseStats.java
|
UTF-8
| 821
| 2.078125
| 2
|
[] |
no_license
|
package sequenze;
public class PokemonBaseStats {
int id;
int form;
int gender_ration; // 0-255
int[/*2*/] abbilities;
int catch_rate; // 0-255
int height; // in 0.1 meters
int weight; // in 0.1 kg
char[] internal_name; // english all caps with underscores
XPType xp_type;
Type[/*2*/] types;
int[/*6*/] base_stats;
int[/*6*/] effort_yield;
int[/*2*/] held_item;
int[/*2*/] egg_group;
int escape_rate; // 0-255, for safari zone
int search_color; // for pokedex
int body_style; // for pokedex
boolean asymmtric;
int base_happiness;
int egg_cycles;
// level_up_attacks
// tm_hm_attacks
// evolutions
// egg_moves
public int getUUID() {
assert (form <= 0xFF);
return (id << 8) + form;
}
public static int getUUID(int id, int form) {
assert (form <= 0xFF);
return (id << 8) + form;
}
}
| true
|
6410308d6f93eeaba6351bb8793ff8baeaf8d690
|
Java
|
Rain-1214/leetcode
|
/src/main/java/com/leetcode/algorithm/AlgorithmController241to260.java
|
UTF-8
| 18,304
| 2.984375
| 3
|
[] |
no_license
|
package com.leetcode.algorithm;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Set;
import com.leetcode.entity.TreeNode;
public class AlgorithmController241to260 {
public List<Integer> diffWaysToCompute(String input) {
return diffWaysToCompute(input.toCharArray(), 0, input.length() - 1);
}
public List<Integer> diffWaysToCompute(char[] input, int l, int r) {
List<Integer> res = new ArrayList<>();
int temp = 0;
int i = l;
for (; i <= r; i++) {
if (Character.isDigit(input[i])) {
temp = temp * 10 + (input[i] - '0');
} else {
break;
}
}
if (i == r + 1) {
res.add(temp);
return res;
}
for (; i <= r; i++) {
if (Character.isDigit(input[i])) {
continue;
}
List<Integer> left = diffWaysToCompute(input, l, i - 1);
List<Integer> right = diffWaysToCompute(input, i + 1, r);
for (int lVal : left) {
for (int rVal : right) {
switch (input[i]) {
case '+':
res.add(lVal + rVal);
break;
case '-':
res.add(lVal - rVal);
break;
default:
res.add(lVal * rVal);
}
}
}
}
return res;
}
public boolean isAnagram(String s, String t) {
if (s.length() != t.length()) {
return false;
}
int[] table = new int[26];
for (int i = 0; i < s.length(); i++) {
table[s.charAt(i) - 'a']++;
}
for (int i = 0; i < s.length(); i++) {
table[t.charAt(i) - 'a']--;
if (table[t.charAt(i) - 'a'] < 0) {
return false;
}
}
return true;
}
public boolean isAnagramII(String s, String t) {
if (s.length() != t.length()) {
return false;
}
int[] table = new int[26];
for (int c : s.toCharArray()) {
table[c - 'a']++;
}
for (int c : t.toCharArray()) {
table[c - 'a']--;
if (table[c - 'a'] < 0) {
return false;
}
}
return true;
}
public int shortestDistance(String[] wordsDict, String word1, String word2) {
int distance = Integer.MAX_VALUE;
int i1 = -1;
int i2 = -1;
for (int i = 0; i < wordsDict.length; i++) {
String t = wordsDict[i];
if (t.equals(word1)) {
i1 = i;
} else if (t.equals(word2)) {
i2 = i;
}
if (i1 != -1 && i2 != -1) {
distance = Math.min(Math.abs(i1 - i2), distance);
}
}
return distance;
}
class WordDistance {
public Map<String, Map<String, Integer>> cache = new HashMap<>();
public String[] table;
public WordDistance(String[] wordsDict) {
this.table = wordsDict;
}
public int shortest(String word1, String word2) {
Map<String, Integer> temp = this.cache.getOrDefault(word1, new HashMap<>());
if (temp.containsKey(word2)) {
return temp.get(word2);
}
int min = this.table.length;
for (int i = 0; i < this.table.length; i++) {
if (this.table[i].equals(word1)) {
int j = 1;
while (i - j >= 0 || i + j < this.table.length) {
if (i - j >= 0 && this.table[i - j].equals(word2)
|| i + j < this.table.length && this.table[i + j].equals(word2)) {
break;
}
j++;
}
min = Math.min(min, j);
}
}
temp.put(word2, min);
this.cache.put(word1, temp);
Map<String, Integer> temp2 = this.cache.getOrDefault(word2, new HashMap<>());
temp2.put(word1, min);
this.cache.put(word2, temp2);
return min;
}
}
class WordDistanceII {
public Map<String, ArrayList<Integer>> cache = new HashMap<>();
public WordDistanceII(String[] wordsDict) {
for (int i = 0; i < wordsDict.length; i++) {
this.cache.computeIfAbsent(wordsDict[i], k -> new ArrayList<>()).add(i);
}
}
public int shortest(String word1, String word2) {
int min = Integer.MAX_VALUE;
int i1 = 0, i2 = 0;
ArrayList<Integer> l1 = this.cache.get(word1);
ArrayList<Integer> l2 = this.cache.get(word2);
while (i1 < l1.size() && i2 < l2.size()) {
min = Math.min(min, Math.abs(l1.get(i1) - l2.get(i2)));
if (l1.get(i1) < l2.get(i2)) {
i1++;
} else {
i2++;
}
}
return min;
}
}
public int shortestWordDistance(String[] wordsDict, String word1, String word2) {
int min = wordsDict.length;
for (int i = 0; i < wordsDict.length; i++) {
if (wordsDict[i].equals(word1)) {
int j = 1;
while (i - j >= 0 || i + j < wordsDict.length) {
if (i - j >= 0 && wordsDict[i - j].equals(word2)
|| i + j < wordsDict.length && wordsDict[i + j].equals(word2)) {
break;
}
j++;
}
min = Math.min(min, j);
}
}
return min;
}
public boolean isStrobogrammatic(String num) {
int len = num.length();
int left = len / 2;
int right = len / 2;
if (len % 2 == 0) {
left = len == 1 ? 0 : right - 1;
}
char[] c = num.toCharArray();
Set<Character> unable = new HashSet<>();
unable.add('2');
unable.add('3');
unable.add('4');
unable.add('5');
unable.add('7');
while (left >= 0 && right < len) {
if (unable.contains(c[right])) {
return false;
}
if (c[right] == '0' || c[right] == '1' || c[right] == '8') {
if (c[right] != c[left]) {
return false;
}
}
if (c[right] == '6' && c[left] != '9' || c[right] == '9' && c[left] != '6') {
return false;
}
left--;
right++;
}
return true;
}
public List<String> findStrobogrammatic(int n) {
return findStrobogrammaticHelper(n, n);
}
public List<String> findStrobogrammaticHelper(int n, int m) {
List<String> res = new ArrayList<>();
if (m == 0) {
res.add("");
return res;
}
if (m == 1) {
res.add("1");
res.add("8");
res.add("0");
return res;
}
List<String> temp = findStrobogrammaticHelper(n, m - 2);
for (String s : temp) {
if (m != n) {
res.add("0" + s + "0");
}
res.add("1" + s + "1");
res.add("8" + s + "8");
res.add("6" + s + "9");
res.add("9" + s + "6");
}
return res;
}
public final char[][] strobogrammaticMap = new char[][] { { '0', '0' }, { '1', '1' }, { '6', '9' }, { '8', '8' },
{ '9', '6' } };
public List<String> findStrobogrammaticII(int n) {
List<String> res = new ArrayList<>();
if (n < 1) {
return res;
}
char[] current = new char[n];
findStrobogrammaticII(0, n - 1, current, res);
return res;
}
public void findStrobogrammaticII(int l, int r, char[] current, List<String> res) {
if (l > r) {
if (current.length == 1 || current[0] != '0') {
res.add(String.valueOf(current));
}
return;
}
for (char[] chars : this.strobogrammaticMap) {
if (l == r && chars[0] != chars[1]) {
continue;
}
current[l] = chars[0];
current[r] = chars[1];
findStrobogrammaticII(l + 1, r - 1, current, res);
}
}
public int strobogrammaticNum = 0;
public int strobogrammaticInRange(String low, String high) {
int res = 0;
for (int i = low.length(); i <= high.length(); i++) {
strobogrammaticNum = 0;
char[] chars = new char[i];
findStrobogrammaticIII(0, i - 1, chars, low, high);
res += strobogrammaticNum;
}
return res;
}
public void findStrobogrammaticIII(int l, int r, char[] current, String low, String high) {
if (l > r) {
if (current.length == 1 || current[0] != '0') {
String temp = String.valueOf(current);
if (comparatorStringIsBigger(temp, low) && comparatorStringIsBigger(high, temp)) {
strobogrammaticNum += 1;
}
}
return;
}
for (char[] chars : this.strobogrammaticMap) {
if (l == r && chars[0] != chars[1]) {
continue;
}
current[l] = chars[0];
current[r] = chars[1];
findStrobogrammaticIII(l + 1, r - 1, current, low, high);
}
}
public boolean comparatorStringIsBigger(String s1, String s2) {
if (s1.length() == s2.length()) {
return s1.compareTo(s2) >= 0;
}
return s1.length() > s2.length();
}
public List<List<String>> groupStrings(String[] strings) {
Map<String, ArrayList<String>> table = new HashMap<>();
for (String s : strings) {
StringBuilder sb = new StringBuilder();
if (s.length() == 1) {
ArrayList<String> temp = table.getOrDefault("-1", new ArrayList<>());
temp.add(s);
table.put("-1", temp);
continue;
}
char[] t = s.toCharArray();
for (int i = 1; i < t.length; i++) {
int sub = t[i] - t[i - 1];
if (sub < 0) {
sub += 26;
}
sb.append(sub);
}
String key = sb.toString();
ArrayList<String> temp = table.getOrDefault(key, new ArrayList<>());
temp.add(s);
table.put(sb.toString(), temp);
}
return new ArrayList<List<String>>(table.values());
}
public int countUnivalSubtreesRes = 0;
public int countUnivalSubtrees(TreeNode root) {
countUnivalSubtreesHelper(root);
return countUnivalSubtreesRes;
}
public boolean countUnivalSubtreesHelper(TreeNode root) {
if (root == null) {
return true;
}
boolean left = countUnivalSubtreesHelper(root.left);
boolean right = countUnivalSubtreesHelper(root.right);
if (!left || !right) {
return false;
}
if (root.left == null && root.right == null) {
countUnivalSubtreesRes += 1;
return true;
}
if (root.left == null) {
if (root.val == root.right.val) {
countUnivalSubtreesRes += 1;
return true;
}
return false;
}
if (root.right == null) {
if (root.val == root.left.val) {
countUnivalSubtreesRes += 1;
return true;
}
return false;
}
if (root.val == root.left.val && root.val == root.right.val) {
countUnivalSubtreesRes += 1;
return true;
}
return false;
}
class Vector2D {
Queue<Integer> q = new LinkedList<>();
public Vector2D(int[][] vec) {
for (int i = 0; i < vec.length; i++) {
for (int j = 0; j < vec[i].length; j++) {
q.add(vec[i][j]);
}
}
}
public int next() {
return q.poll();
}
public boolean hasNext() {
return !q.isEmpty();
}
}
class Vector2DII {
int[][] vec;
int innerIndex = 0;
int outIndex = 0;
public Vector2DII(int[][] vec) {
this.vec = vec;
}
public int next() {
if (innerIndex >= vec[outIndex].length) {
innerIndex = 0;
outIndex++;
return this.next();
}
return vec[outIndex][innerIndex++];
}
public boolean hasNext() {
if (outIndex < vec.length && innerIndex >= vec[outIndex].length) {
innerIndex = 0;
outIndex++;
return hasNext();
}
return outIndex < vec.length;
}
}
public boolean canAttendMeetings(int[][] intervals) {
Arrays.sort(intervals, (int[] a, int[] b) -> {
return a[0] - b[0];
});
for (int i = 1; i < intervals.length; i++) {
if (intervals[i][0] < intervals[i - 1][1]) {
return false;
}
}
return true;
}
public int minMeetingRooms(int[][] intervals) {
PriorityQueue<Integer> pq = new PriorityQueue<>(intervals.length, (a, b) -> a - b);
Arrays.sort(intervals, (a, b) -> a[0] - b[0]);
pq.add(intervals[0][1]);
for (int i = 1; i < intervals.length; i++) {
if (intervals[i][0] >= pq.peek()) {
pq.poll();
}
pq.add(intervals[i][1]);
}
return pq.size();
}
public List<List<Integer>> getFactors(int n) {
List<List<Integer>> res = new ArrayList<>();
if (n == 1) {
return res;
}
getFactors(n, new ArrayList<>(), res, (int) Math.sqrt(n));
return res;
}
public void getFactors(int n, List<Integer> currentList, List<List<Integer>> res, int max) {
if (n == 1) {
List<Integer> temp = new ArrayList<>(currentList);
res.add(temp);
return;
}
int start = currentList.isEmpty() ? 2 : currentList.get(currentList.size() - 1);
for (int i = start; i <= max; i++) {
if (n % i == 0) {
currentList.add(i);
getFactors(n / i, currentList, res, max);
currentList.remove(currentList.size() - 1);
}
}
}
public List<List<Integer>> getFactorsII(int n) {
return getFactorsII(2, n);
}
public List<List<Integer>> getFactorsII(int start, int end) {
List<List<Integer>> res = new ArrayList<>();
if (end == 1) {
return res;
}
int max = (int) Math.sqrt(end);
for (int i = start; i <= max; i++) {
if (end % i == 0) {
List<Integer> temp = new ArrayList<>();
temp.add(i);
temp.add(end / i);
res.add(temp);
List<List<Integer>> next = getFactorsII(i, end / i);
for (List<Integer> l : next) {
l.add(i);
res.add(l);
}
}
}
return res;
}
public boolean verifyPreorder(int[] preorder) {
if (preorder.length < 3) {
return true;
}
return verifyPreorder(preorder, 0, preorder.length - 1);
}
public boolean verifyPreorder(int[] preorder, int start, int end) {
if (start >= end) {
return true;
}
int middle = -1;
for (int i = start + 1; i <= end; i++) {
if (preorder[i] > preorder[start] && middle == -1) {
middle = i;
continue;
}
if (middle != -1 && preorder[i] < preorder[start]) {
return false;
}
}
if (middle == -1) {
return verifyPreorder(preorder, start + 1, end);
}
return verifyPreorder(preorder, start + 1, middle - 1) && verifyPreorder(preorder, middle, end);
}
public boolean verifyPreorderII(int[] preorder) {
int[] stack = new int[preorder.length];
int index = -1;
int min = Integer.MIN_VALUE;
for (int num : preorder) {
if (num < min) {
return false;
}
while (index > -1 && num > stack[index]) {
min = stack[index--];
}
stack[++index] = num;
}
return true;
}
public int minCost(int[][] costs) {
int[][] dp = new int[costs.length + 1][3];
dp[0] = new int[] { 0, 0, 0 };
for (int i = 0; i < costs.length; i++) {
int[] temp = new int[3];
temp[0] = Math.min(dp[i][1], dp[i][2]) + costs[i][0];
temp[1] = Math.min(dp[i][0], dp[i][2]) + costs[i][1];
temp[2] = Math.min(dp[i][0], dp[i][1]) + costs[i][2];
dp[i + 1] = temp;
}
return Math.min(Math.min(dp[costs.length][1], dp[costs.length][2]), dp[costs.length][0]);
}
public int minCostII(int[][] costs) {
int dp0 = 0, dp1 = 0, dp2 = 0;
for (int i = 0; i < costs.length; i++) {
int temp0 = Math.min(dp1, dp2) + costs[i][0];
int temp1 = Math.min(dp0, dp2) + costs[i][1];
int temp2 = Math.min(dp0, dp1) + costs[i][2];
dp0 = temp0;
dp1 = temp1;
dp2 = temp2;
}
return Math.min(Math.min(dp0, dp1), dp2);
}
public List<String> binaryTreePaths(TreeNode root) {
List<String> res = new ArrayList<>();
binaryTreePaths(root, res, "");
return res;
}
public void binaryTreePaths(TreeNode root, List<String> res, String s) {
if (root == null) {
return;
}
StringBuilder tempSb = new StringBuilder(s);
tempSb.append(Integer.toString(root.val));
if (root.left == null && root.right == null) {
res.add(tempSb.toString());
} else {
tempSb.append("->");
binaryTreePaths(root.left, res, tempSb.toString());
binaryTreePaths(root.right, res, tempSb.toString());
}
}
public int addDigits(int num) {
if (num < 10) {
return num;
}
int res = 0;
while (num > 0) {
res += num % 10;
num /= 10;
}
return res < 10 ? res : addDigits(res);
}
public int threeSumSmaller(int[] nums, int target) {
Arrays.sort(nums);
int res = 0;
for (int i = 0; i <= nums.length - 3; i++) {
res += twoSumSmaller(nums, i + 1, target - nums[i]);
}
return res;
}
public int twoSumSmaller(int[] nums, int startIndex, int target) {
int left = startIndex;
int right = nums.length - 1;
int res = 0;
while (left < right) {
if (nums[left] + nums[right] < target) {
res += right - left;
left++;
} else {
right--;
}
}
return res;
}
public int threeSumSmallerII(int[] nums, int target) {
if (nums.length < 3) {
return 0;
}
Arrays.sort(nums);
int res = 0;
for (int i = 0; i < nums.length - 2; i++) {
if (nums[i] * 3 >= target) {
break;
}
int temp = target - nums[i];
int left = i + 1;
int right = nums.length - 1;
while (left < right) {
if (nums[left] + nums[right] < temp) {
res += right - left;
left++;
} else {
right--;
}
}
}
return res;
}
public int[] singleNumber(int[] nums) {
Map<Integer, Integer> t = new HashMap<>();
for (int n : nums) {
t.put(n, t.getOrDefault(n, 0) + 1);
}
int[] res = new int[2];
int index = 0;
for (Map.Entry<Integer, Integer> e : t.entrySet()) {
if (e.getValue() == 1) {
res[index++] = e.getKey();
}
}
return res;
}
public int[] singleNumberII(int[] nums) {
int exclusiveOrNum = nums[0];
for (int i = 1; i < nums.length; i++) {
exclusiveOrNum ^= nums[i];
}
int oneBin = 1;
while ((exclusiveOrNum & oneBin) != oneBin) {
oneBin <<= 1;
}
int a = 0, b = 0;
for (int i = 0; i < nums.length; i++) {
if ((nums[i] & oneBin) == oneBin) {
a ^= nums[i];
} else {
b ^= nums[i];
}
}
return new int[] { a, b };
}
}
| true
|
9ed154bbe742987cd5023c216c0f1f16e9526124
|
Java
|
RenatiusvanSander/EffectiveJava
|
/src/main/java/edu/remad/chapter6/item37/Plant.java
|
UTF-8
| 1,093
| 3.78125
| 4
|
[] |
no_license
|
package edu.remad.chapter6.item37;
import java.util.*;
/**
* This handles a plant with a name and LifeCycle enum.
*/
public class Plant {
enum LifeCycle {ANNUAL, PERENIAL, BIENNIAL}
final String name;
final LifeCycle lifeCycle;
Plant(String name, LifeCycle lifeCycle) {
this.name = name;
this.lifeCycle = lifeCycle;
}
@Override
public String toString() {
return name;
}
public static void main(String[] args) {
Plant p1 = new Plant("Pambaum", LifeCycle.ANNUAL);
Plant p2 = new Plant("Pamelablume",LifeCycle.BIENNIAL);
Plant p3 = new Plant("Pamelali", LifeCycle.PERENIAL);
List<Plant> garden = List.of(p1, p2, p3);
Map<Plant.LifeCycle, Set<Plant>> plantsByLifeCycle = new EnumMap<>(Plant.LifeCycle.class);
for(Plant.LifeCycle lc : Plant.LifeCycle.values()) {
plantsByLifeCycle.put(lc, new HashSet<>());
}
for(Plant p: garden) {
plantsByLifeCycle.get(p.lifeCycle).add(p);
}
System.out.println(plantsByLifeCycle);
}
}
| true
|
16fbfefb3b10b4575233beb87507cb8a5730f0c8
|
Java
|
wso2/maven-tools
|
/maven-carbon-ui-plugin/src/main/java/org/wso2/maven/plugin/carbonui/CarbonUIPOMGenMojo.java
|
UTF-8
| 8,702
| 1.570313
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright (c) 2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wso2.maven.plugin.carbonui;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.xml.stream.FactoryConfigurationError;
import org.apache.maven.artifact.factory.ArtifactFactory;
import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.artifact.resolver.ArtifactResolver;
import org.apache.maven.model.Plugin;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.project.MavenProject;
import org.apache.maven.project.MavenProjectHelper;
import org.codehaus.plexus.util.FileUtils;
import org.codehaus.plexus.util.xml.Xpp3Dom;
import org.wso2.maven.capp.bundleartifact.AbstractBundlePOMGenMojo;
import org.wso2.maven.capp.model.Artifact;
import org.wso2.maven.capp.model.BundlesDataInfo;
import org.wso2.maven.capp.mojo.AbstractPOMGenMojo;
import org.wso2.maven.capp.utils.CAppMavenUtils;
import org.wso2.maven.capp.utils.CAppUtils;
import org.wso2.maven.capp.utils.WSO2MavenPluginConstantants;
/**
* This is the Maven Mojo used for generating a pom for a carbon ui artifact
* from the old CApp project structure
*
* @goal pom-gen
*
*/
public class CarbonUIPOMGenMojo extends AbstractBundlePOMGenMojo {
/**
* @parameter default-value="${project}"
*/
public MavenProject project;
/**
* Maven ProjectHelper.
*
* @component
*/
public MavenProjectHelper projectHelper;
/**
* The path of the location to output the pom
*
* @parameter expression="${project.build.directory}/artifacts"
*/
public File outputLocation;
/**
* The resulting extension of the file
*
* @parameter
*/
public File artifactLocation;
/**
* POM location for the module project
*
* @parameter expression="${project.build.directory}/pom.xml"
*/
public File moduleProject;
/**
* Group id to use for the generated pom
*
* @parameter
*/
public String groupId;
/**
* Comma separated list of "artifact_type=extension" to be used when creating dependencies for other capp artifacts
*
* @parameter
*/
public String typeList;
/**
* A list of projects in eclipse workspace which can be referred using maven groupid, artifactid, version
*
* @parameter
*/
private List<String> projects;
/**
* @component
*/
public ArtifactFactory artifactFactory;
/**
* @component
*/
public ArtifactResolver resolver;
/**
* @parameter default-value="${localRepository}"
*/
public ArtifactRepository localRepository;
/**
* @parameter default-value="${project.remoteArtifactRepositories}"
*/
public List<?> remoteRepositories;
private static final String ARTIFACT_TYPE="lib/carbon/ui";
private BundlesDataInfo bundlesDataInfo;
private List<String> artifactProjects;
protected String getArtifactType() {
return ARTIFACT_TYPE;
}
protected List<String> getProjectMapStrings() {
return projects;
}
public ArtifactFactory getArtifactFactory() {
return artifactFactory;
}
public ArtifactResolver getResolver() {
return resolver;
}
public ArtifactRepository getLocalRepository() {
return localRepository;
}
public List<?> getRemoteRepositories() {
return remoteRepositories;
}
protected String getBundleActivatorClass(Artifact artifact) {
return null;
}
protected void addPlugins(MavenProject artifactMavenProject, Artifact artifact) {
Plugin pluginAxis2 =
CAppMavenUtils.createPluginEntry(artifactMavenProject,
"org.wso2.maven",
"maven-carbon-ui-plugin",
WSO2MavenPluginConstantants.MAVEN_CARBON_UI_PLUGIN_VERSION,
true);
// PluginExecution executionAxis2 = new PluginExecution();
// executionAxis2.setId("package-war");
// executionAxis2.setPhase("package");
// List goalsAxis2 = new ArrayList<String>();
// goalsAxis2.add("package-war");
// executionAxis2.setGoals(goalsAxis2);
// pluginAxis2.addExecution(executionAxis2);
Xpp3Dom config = (Xpp3Dom) pluginAxis2.getConfiguration();
Xpp3Dom artifactItems = CAppMavenUtils.createConfigurationNode(config, "artifact");
String relativePath =
org.wso2.developerstudio.eclipse.utils.file.FileUtils.getRelativePath(new File(
artifact.getFile()
.getParentFile()
.getParentFile()
.getParentFile()
.getParentFile()
.getParentFile()
.getPath() +
File.separator +
"target" +
File.separator +
"capp" +
File.separator +
"artifacts" +
File.separator +
artifactMavenProject.getArtifactId()),
artifact.getFile());
artifactItems.setValue(relativePath);
}
protected BundlesDataInfo getBundlesDataInfo(File targetProjectLocation, Artifact artifact)throws FactoryConfigurationError {
if (bundlesDataInfo==null) {
try {
bundlesDataInfo = new BundlesDataInfo();
bundlesDataInfo.setProjects(getProjectMappings());
List<String> artifactProjects = getArtifactProjects();
for (String artifactProject : artifactProjects) {
String[] artifactProjectData = artifactProject.split(":");
if (artifactProjectData.length==2 && artifactProjectData[0].equals(artifact.getName())){
String[] projectNames = artifactProjectData[1].split(",");
for (String projectName : projectNames) {
bundlesDataInfo.addProjectToList(projectName, null);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
return bundlesDataInfo;
}
public List<String> getArtifactProjects() {
if (artifactProjects==null){
artifactProjects=new ArrayList<String>();
}
return artifactProjects;
}
// public void execute() throws MojoExecutionException, MojoFailureException {
// //Nothing to do. No need to generate a pom.
// }
protected MavenProject createMavenProjectForCappArtifact(Artifact artifact,
List<Artifact> artifacts,
File projectLocation)
throws MojoExecutionException {
return null;
}
}
| true
|
d842365260496ae37371c5a7abdfb22e084bf3e1
|
Java
|
gges5110/SQLiteExample
|
/app/src/main/java/com/example/yoga/sqliteexample/Adapter/BillRecyclerViewAdapter.java
|
UTF-8
| 4,730
| 2.296875
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.example.yoga.sqliteexample.Adapter;
import android.app.Activity;
import android.graphics.drawable.GradientDrawable;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.example.yoga.sqliteexample.Model.Bill;
import com.example.yoga.sqliteexample.Model.Person;
import com.example.yoga.sqliteexample.R;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
/**
* Created by YOGA on 11/15/2016.
*/
public class BillRecyclerViewAdapter extends RecyclerView.Adapter<BillRecyclerViewAdapter.ViewHolder> {
private List<Bill> billList;
private List<String> placeList, dateList;
private List<Person> payerList;
private Activity activity;
private int[] colorArr = new int[4];
public interface BillRecyclerInterface {
void setBillDetailFragment(int bill_id);
}
public BillRecyclerViewAdapter(Activity activity, List<Bill> billList, List<Person> payerList) {
this.activity = activity;
this.billList = billList;
this.payerList = payerList;
placeList = new ArrayList<>();
dateList = new ArrayList<>();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault());
for (int i = 0; i < billList.size(); ++i) {
Bill b = billList.get(i);
placeList.add(b.getPlace());
dateList.add(dateFormat.format(b.getDate()));
}
colorArr[0] = activity.getResources().getColor(R.color.roundedLetter1);
colorArr[1] = activity.getResources().getColor(R.color.roundedLetter2);
colorArr[2] = activity.getResources().getColor(R.color.roundedLetter3);
colorArr[3] = activity.getResources().getColor(R.color.roundedLetter4);
}
public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView mTitle;
public TextView textView_line1, textView_line2, textView_line3;
private List<Bill> billList;
private List<Person> payerList;
private Activity activity;
private BillRecyclerInterface mListener;
public ViewHolder(LinearLayout v, Activity activity, List<Bill> billList, List<Person> payerList) {
super(v);
v.setOnClickListener(this);
this.activity = activity;
this.billList = billList;
this.payerList = payerList;
try {
mListener = (BillRecyclerInterface) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement OnArticleSelectedListener");
}
mTitle = (TextView) v.findViewById(R.id.textView_title);
textView_line1 = (TextView) v.findViewById(R.id.textView_line1);
textView_line2 = (TextView) v.findViewById(R.id.textView_line2);
textView_line3 = (TextView) v.findViewById(R.id.textView_line3);
}
@Override
public void onClick(View v) {
// Toast.makeText(activity, "Clicked", Toast.LENGTH_SHORT).show();
mListener.setBillDetailFragment(billList.get(getAdapterPosition()).getId());
}
}
@Override
public BillRecyclerViewAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// create a new view
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.listview_layout, parent, false);
// set the view's size, margins, padding and layout parameters
return new ViewHolder((LinearLayout) v, activity, billList, payerList);
}
@Override
public int getItemCount() {
return billList.size();
}
// Replace the contents of a view (invoked by the layout manager)
@Override
public void onBindViewHolder(BillRecyclerViewAdapter.ViewHolder holder, int position) {
if (!placeList.get(position).equals("")) {
char c = Character.toUpperCase(placeList.get(position).charAt(0));
holder.mTitle.setText(String.valueOf(c));
holder.mTitle.setBackgroundResource(R.drawable.circle);
GradientDrawable drawable = (GradientDrawable) holder.mTitle.getBackground();
drawable.setColor(colorArr[Character.getNumericValue(c) % 4]);
}
holder.textView_line1.setText(placeList.get(position));
holder.textView_line2.setText(dateList.get(position));
holder.textView_line3.setText(payerList.get(position).getName());
}
}
| true
|
56d437e2259dc9ce67fb6fd2025581289ae7a117
|
Java
|
ChaSoojin/Lect_lv9
|
/rpg/src/Controller/FileController.java
|
UTF-8
| 431
| 2.296875
| 2
|
[] |
no_license
|
package Controller;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
public class FileController {
public static FileController instance = new FileController();
private FileWriter fw = null;
private FileReader fr = null;
private BufferedReader br = null;
private File file = null;
public void save() {
}
public void load() {
}
}
| true
|
f61918c8bf5d0d99f573c03014b7f6e95adbd586
|
Java
|
ponta-dev/spring-test
|
/src/test/java/spring/repository/UserDaoImplTest.java
|
UTF-8
| 1,134
| 2.015625
| 2
|
[] |
no_license
|
package spring.repository;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.jdbc.Sql;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.transaction.annotation.Transactional;
@ExtendWith(SpringExtension.class)
@SpringBootTest
@Transactional
public class UserDaoImplTest {
@Autowired
@Qualifier("UserDaoImpl")
private UserDao dao;
@Test
@Sql("/sql/spring/repository/UserDaoImpl/test_count_exp_0count.sql")
public void test_count_exp_0count() {
System.out.println(dao.selectMany());
assertEquals(dao.count(), 0);
}
@Test
@Sql("/sql/spring/repository/UserDaoImpl/test_count_exp_2count.sql")
public void test_count_exp_2count() {
System.out.println(dao.selectMany());
assertEquals(dao.count(), 2);
}
}
| true
|
8d7e61f62863b84b0a425e44453f45697a77cfda
|
Java
|
leoreyes84/ProyectoGrado
|
/PrototipoVAK/PrototipoVAK-ejb/src/java/co/edu/udistrital/prototipovak/entity/Respuesta.java
|
UTF-8
| 4,505
| 1.804688
| 2
|
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package co.edu.udistrital.prototipovak.entity;
import java.io.Serializable;
import java.util.List;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
/**
*
* @author Leonardo
*/
@Entity
@Table(name = "respuesta")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "Respuesta.findAll", query = "SELECT r FROM Respuesta r"),
@NamedQuery(name = "Respuesta.findByRtaId", query = "SELECT r FROM Respuesta r WHERE r.rtaId = :rtaId"),
@NamedQuery(name = "Respuesta.findByRtaRespuesta", query = "SELECT r FROM Respuesta r WHERE r.rtaRespuesta = :rtaRespuesta"),
@NamedQuery(name = "Respuesta.findByRtaTipoRespuesta", query = "SELECT r FROM Respuesta r WHERE r.rtaTipoRespuesta = :rtaTipoRespuesta")})
public class Respuesta implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "rta_id")
private Integer rtaId;
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 250)
@Column(name = "rta_respuesta")
private String rtaRespuesta;
@Basic(optional = false)
@NotNull
@Column(name = "rta_tipo_respuesta")
private Character rtaTipoRespuesta;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "respuesta", fetch = FetchType.LAZY)
private List<UsuarioRespuesta> usuarioRespuestaList;
@JoinColumn(name = "preg_id", referencedColumnName = "preg_id")
@ManyToOne(optional = false, fetch = FetchType.LAZY)
private Pregunta pregId;
public Respuesta() {
}
public Respuesta(Integer rtaId) {
this.rtaId = rtaId;
}
public Respuesta(Integer rtaId, String rtaRespuesta, Character rtaTipoRespuesta) {
this.rtaId = rtaId;
this.rtaRespuesta = rtaRespuesta;
this.rtaTipoRespuesta = rtaTipoRespuesta;
}
public Integer getRtaId() {
return rtaId;
}
public void setRtaId(Integer rtaId) {
this.rtaId = rtaId;
}
public String getRtaRespuesta() {
return rtaRespuesta;
}
public void setRtaRespuesta(String rtaRespuesta) {
this.rtaRespuesta = rtaRespuesta;
}
public Character getRtaTipoRespuesta() {
return rtaTipoRespuesta;
}
public void setRtaTipoRespuesta(Character rtaTipoRespuesta) {
this.rtaTipoRespuesta = rtaTipoRespuesta;
}
@XmlTransient
public List<UsuarioRespuesta> getUsuarioRespuestaList() {
return usuarioRespuestaList;
}
public void setUsuarioRespuestaList(List<UsuarioRespuesta> usuarioRespuestaList) {
this.usuarioRespuestaList = usuarioRespuestaList;
}
public Pregunta getPregId() {
return pregId;
}
public void setPregId(Pregunta pregId) {
this.pregId = pregId;
}
@Override
public int hashCode() {
int hash = 0;
hash += (rtaId != null ? rtaId.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Respuesta)) {
return false;
}
Respuesta other = (Respuesta) object;
if ((this.rtaId == null && other.rtaId != null) || (this.rtaId != null && !this.rtaId.equals(other.rtaId))) {
return false;
}
return true;
}
@Override
public String toString() {
return "co.edu.udistrital.prototipovak.entity.Respuesta[ rtaId=" + rtaId + " ]";
}
}
| true
|
7c173b295e556102feee60a4a1c11c8792acea9a
|
Java
|
mohan08p/java_students
|
/Pratibha/Core JAVA/JDBC/Bank-app/src/com/techlabs/controller/DownloadController.java
|
UTF-8
| 1,809
| 2.109375
| 2
|
[] |
no_license
|
package com.techlabs.controller;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.techlabs.model.Transaction;
import com.techlabs.service.BankService;
import com.techlabs.service.CsvFileWriter;
/**
* Servlet implementation class DownloadCSV
*/
@WebServlet("/DownloadController")
public class DownloadController extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public DownloadController() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
@SuppressWarnings("unchecked")
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("downloadController");
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition",
"attachment;filename=F:\\photo\\images (27).jpg");
CsvFileWriter csv =new CsvFileWriter();
HttpSession session = request.getSession();
List list=(List<Transaction>) session.getAttribute("translist");
csv.writeCsvFile(list);
response.sendRedirect("http://localhost:8080/Bank-app/PassBookController");
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
| true
|
9d4a062753c7ac743ae1dd68bf5b2008b7b6cb60
|
Java
|
freefreesea/tonic
|
/java/eclipse/MyTankGame/src/com/test3/Members.java
|
GB18030
| 2,356
| 3.5
| 4
|
[] |
no_license
|
package com.test3;
import java.util.Vector;
//ը
class Bomb
{
//ը
int x,y;
//ը
int life=9;
boolean isLive = true;
public Bomb(int x,int y)
{
this.x=x;
this.y=y;
}
//ֵ
public void lifeDowm()
{
if(life>0)
{
life--;
}
else
{
this.isLive=false;
}
}
}
//ӵ
class Shot implements Runnable //һʱDZ仯 Կ߳
{
int x,y,direct;
int speed=3;
//Ƿ
boolean isLive=true;
public Shot(int x,int y,int direct)
{
this.x=x;
this.y=y;
this.direct=direct;
}
public void run()
{
while(true)
{
try {
Thread.sleep(50);;
} catch (Exception e) {
e.getStackTrace();
// TODO: handle exception
}
switch (direct) {
case 0:
y-=speed;
break;
case 1:
x+=speed;
break;
case 2:
y+=speed;
break;
case 3:
x-=speed;
break;
}
System.out.println(x+" "+y);
//ӵʱ???
//жϸӵǷԵ
if(x<0||x>400||y<0||y>300)
{
this.isLive=false;
break;
}
}
}
}
class Tank
{
int x=0;//
int y=0;//
//̹˷ 0 1 2 3
int direct = 0;
int color;
public Tank(int x,int y)
{
this.x=x;
this.y=y;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public int getDirect() {
return direct;
}
public void setDirect(int direct) {
this.direct = direct;
}
public int getColor() {
return color;
}
public void setColor(int color) {
this.color = color;
}
}
class EnemyTank extends Tank
{
boolean isLive = true;
public EnemyTank(int x,int y)
{
super(x,y);
}
}
//ҵ̹
class Hero extends Tank
{
//ӵ
Vector<Shot> ss = new Vector<Shot>();
Shot s=null;
public Hero(int x,int y)
{
super(x, y);
}
//
public void shotEnemy()
{
switch(this.direct)
{
case 0:
s=new Shot(x+10, y,0);
ss.add(s);
break;
case 1:
s=new Shot(x+30, y+10,1);
ss.add(s);
break;
case 2:
s=new Shot(x+10, y+30,2);
ss.add(s);
break;
case 3:
s=new Shot(x, y+10,3);
ss.add(s);
break;
}
//ӵ߳
Thread t=new Thread(s);
t.start();
}
}
| true
|
0ea856f0763bddaa76eb8fae8a496fba366f1115
|
Java
|
haoliangsky1/CS61B_DataStructure
|
/proj1b/FailureSequenceChecker.java
|
UTF-8
| 281
| 2.375
| 2
|
[
"Apache-2.0"
] |
permissive
|
public class FailureSequenceChecker {
public static void main(String[] args) {
StudentArrayDeque<Integer> ssld = new StudentArrayDeque<Integer>();
ssld.addLast and get test.;
ssld. Making random calls to addLast(). ;
ssld. Expect 47 but get 0 .;
}
}
| true
|
9631e0dd41a0a1d53e76cadae7887620d53e99cd
|
Java
|
awhawks/jparsec
|
/src/main/java/jparsec/ephem/Target.java
|
UTF-8
| 16,885
| 2.25
| 2
|
[] |
no_license
|
/*
* This file is part of JPARSEC library.
*
* (C) Copyright 2006-2017 by T. Alonso Albi - OAN (Spain).
*
* Project Info: http://conga.oan.es/~alonso/jparsec/jparsec.html
*
* JPARSEC library is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* JPARSEC library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package jparsec.ephem;
import java.util.ArrayList;
import jparsec.ephem.moons.MoonEphem;
import jparsec.graph.DataSet;
import jparsec.observer.ObserverElement;
import jparsec.time.TimeElement;
import jparsec.util.JPARSECException;
import jparsec.util.Logger;
import jparsec.util.Logger.LEVEL;
import jparsec.util.Translate;
import jparsec.util.Translate.LANGUAGE;
/**
* A common place to store target body IDs. This class is updated following new
* IAU resolutions about Pluto.
* <P>
* Size parameters comes from the IAU2009 recommended values. Note that not all
* known natural objects are listed here, but only those whose size or
* rotational parameters are known. Otherwise, ephemeris can also be obtained
* for objects not listed here (see
* {@linkplain MoonEphem#calcAllJPLSatellites(TimeElement, ObserverElement, EphemerisElement)}).
*
* @author T. Alonso Albi - OAN (Spain)
* @version 1.0
*/
public final class Target
{
// private constructor so that this class cannot be instantiated.
private Target() {}
/**
* The set of targets for JPARSEC ephemerides.
*/
public enum TARGET {
// Object name, equatorial radius (km), polar radius (km), relative mass to the Sun (1, >= 1)
// Main Solar System bodies, Sun must be the first
/** The Sun */
SUN (696000.0, 696000.0, 1.0, null, 0),
/** Mercury */
MERCURY (2439.7, 2439.7, 6023600.0, SUN, 1),
/** Venus */
VENUS (6051.8, 6051.8, 408523.71, SUN, 2),
/** Earth */
EARTH (6378.1366, 6356.7519, 332946.050895, SUN, 3),
/** Mars */
MARS (3396.19, 3376.2, 3098708.0, SUN, 5),
/** Jupiter */
JUPITER (71492.0, 66854.0, 1047.3486, SUN, 6),
/** Saturn */
SATURN (60268.0, 54364.0, 3497.898, SUN, 7),
/** Uranus */
URANUS (25559.0, 24973.0, 22902.98, SUN, 8),
/** Neptune */
NEPTUNE (24764.0, 24341.0, 19412.24, SUN, 9),
/** Dwarf planet Pluto */
Pluto (1195.0, 1195.0, 1.352E8, SUN, 10),
/** The Moon */
Moon (1737.4, 1737.4, 2.7068700387534E7, EARTH, 4),
/** Special target for Earth-Moon barycenter */
Earth_Moon_Barycenter (0.0, 0.0, 328900.5614, SUN, 80),
// Generic comet/asteroid
/** Generic comet */
Comet (0.0, 0.0, 0.0, SUN, 74),
/** Generic asteroid */
Asteroid (0.0, 0.0, 0.0, SUN, 73),
/** Generic NEO */
NEO (0.0, 0.0, 0.0, SUN, 1275),
// Special values available in some theories (JPL, Moshier)
/**
* Special target for nutation, only for JPL ephemerides.
*/
Nutation (0, 0, 0, EARTH, 1315),
/**
* Special target for lunar librations, only for Moshier and JPL ephemerides.
*/
Libration (0, 0, 0, SUN, 1316),
/**
* Special target for Solar System barycenter, only for Moshier and JPL ephemerides.
*/
Solar_System_Barycenter (0, 0, 0, SUN, 1317),
// Natural satellites, Phobos must be the first and Proteus the last
/** A satellite of Mars */
Phobos (13.0, 9.1, 0.0, MARS, 82),
/** A satellite of Mars */
Deimos (7.8, 5.1, 0.0, MARS, 83),
/** A satellite of Jupiter */
Io (1829.4, 1815.7, 0.0, JUPITER, 84),
/** A satellite of Jupiter */
Europa (1562.6, 1559.5, 0.0, JUPITER, 85),
/** A satellite of Jupiter */
Ganymede (2631.2, 2631.2, 0.0, JUPITER, 86),
/** A satellite of Jupiter */
Callisto (2410.3, 2410.3, 0.0, JUPITER, 87),
/** A satellite of Saturn */
Mimas (207.8, 190.6, 0.0, SATURN, 88),
/** A satellite of Saturn */
Enceladus (256.6, 248.3, 0.0, SATURN, 89),
/** A satellite of Saturn */
Tethys (538.4, 526.3, 0.0, SATURN, 90),
/** A satellite of Saturn */
Dione (563.4, 559.6, 0.0, SATURN, 91),
/** A satellite of Saturn */
Rhea (765.0, 762.4, 0.0, SATURN, 92),
/** A satellite of Saturn */
Titan (2575.15, 2574.47, 0.0, SATURN, 93),
/** A satellite of Saturn */
Hyperion (180.1, 102.7, 0.0, SATURN, 94),
/** A satellite of Saturn */
Iapetus (745.7, 712.1, 0.0, SATURN, 95),
/** A satellite of Uranus */
Miranda (240.4, 232.9, 0.0, URANUS, 96),
/** A satellite of Uranus */
Ariel (581.1, 577.7, 0.0, URANUS, 97),
/** A satellite of Uranus */
Umbriel (584.7, 584.7, 0.0, URANUS, 98),
/** A satellite of Uranus */
Titania (788.9, 788.9, 0.0, URANUS, 99),
/** A satellite of Uranus */
Oberon (761.4, 761.4, 0.0, URANUS, 100),
/** A satellite of Neptune */
Triton (1352.6, 1352.6, 0.0, NEPTUNE, 101),
/** A satellite of Neptune */
Nereid (170.0, 170.0, 0.0, NEPTUNE, 102),
/** A satellite of Pluto */
Charon (605.0, 605.0, 0.0, Pluto, 103),
/** A satellite of Jupiter */
Amalthea (125.0, 64.0, 0.0, JUPITER, 104),
/** A satellite of Jupiter */
Thebe (58.0, 42.0, 0.0, JUPITER, 105),
/** A satellite of Jupiter */
Adrastea (10.0, 7.0, 0.0, JUPITER, 106),
/** A satellite of Jupiter */
Metis (30.0, 20.0, 0.0, JUPITER, 107),
/** A satellite of Jupiter */
Himalia (85.0, 85.0, 0.0, JUPITER, 127),
/** A satellite of Jupiter */
Elara (40.0, 40.0, 0.0, JUPITER, 128),
/** A satellite of Jupiter */
Pasiphae (18.0, 18.0, 0.0, JUPITER, 129),
/** A satellite of Jupiter */
Sinope (14.0, 14.0, 0.0, JUPITER, 130),
/** A satellite of Jupiter */
Lysithea (12.0, 12.0, 0.0, JUPITER, 131),
/** A satellite of Jupiter */
Carme (15.0, 15.0, 0.0, JUPITER, 132),
/** A satellite of Jupiter */
Ananke (10.0, 10.0, 0.0, JUPITER, 133),
/** A satellite of Jupiter */
Leda (5.0, 5.0, 0.0, JUPITER, 134),
/** A satellite of Saturn */
Atlas (18.5, 13.5, 0.0, SATURN, 108),
/** A satellite of Saturn */
Prometheus (74.0, 34.0, 0.0, SATURN, 109),
/** A satellite of Saturn */
Pandora (55.0, 31.0, 0.0, SATURN, 110),
/** A satellite of Saturn */
Pan (10.0, 10.0, 0.0, SATURN, 111),
/** A satellite of Saturn */
Epimetheus (64.9, 53.1, 0.0, SATURN, 135),
/** A satellite of Saturn */
Janus (101.5, 76.3, 0.0, SATURN, 136),
/** A satellite of Saturn */
Telesto (16.3, 10.0, 0.0, SATURN, 137),
/** A satellite of Saturn */
Calypso (15.1, 7.0, 0.0, SATURN, 138),
/** A satellite of Saturn */
Helene (21.7, 13.0, 0.0, SATURN, 139),
/** A satellite of Saturn */
Phoebe (109.4, 101.8, 0.0, SATURN, 140),
/** A satellite of Uranus */
Cordelia (13.0, 13.0, 0.0, URANUS, 112),
/** A satellite of Uranus */
Ophelia (15.0, 15.0, 0.0, URANUS, 113),
/** A satellite of Uranus */
Cressida (31.0, 31.0, 0.0, URANUS, 114),
/** A satellite of Uranus */
Bianca (21.0, 21.0, 0.0, URANUS, 115),
/** A satellite of Uranus */
Desdemona (27.0, 27.0, 0.0, URANUS, 116),
/** A satellite of Uranus */
Juliet (42.0, 42.0, 0.0, URANUS, 117),
/** A satellite of Uranus */
Portia (54.0, 54.0, 0.0, URANUS, 118),
/** A satellite of Uranus */
Rosalind (27.0, 27.0, 0.0, URANUS, 119),
/** A satellite of Uranus */
Puck (77.0, 77.0, 0.0, URANUS, 120),
/** A satellite of Uranus */
Belinda (33.0, 33.0, 0.0, URANUS, 821),
/** A satellite of Neptune */
Naiad (29.0, 29.0, 0.0, NEPTUNE, 126),
/** A satellite of Neptune */
Thalassa (40.0, 40.0, 0.0, NEPTUNE, 125),
/** A satellite of Neptune */
Despina (74.0, 74.0, 0.0, NEPTUNE, 123),
/** A satellite of Neptune */
Galatea (79.0, 79.0, 0.0, NEPTUNE, 124),
/** A satellite of Neptune */
Larissa (104.0, 89.0, 0.0, NEPTUNE, 122),
/** A satellite of Neptune */
Proteus (218.0, 201.0, 0.0, NEPTUNE, 121),
// Asteroids. Ceres must be the first
/** Dwarf planet */
Ceres (487.3, 454.7, 0.0, SUN, 1307),
/** An asteroid */
Pallas (582.0, 500.0, 0.0, SUN, 1308),
/** An asteroid */
Vesta (289.0, 229.0, 0.0, SUN, 143),
/** An asteroid */
Lutetia (62.0, 46.5, 0.0, SUN, 1309),
/** An asteroid */
Ida (26.8, 7.6, 0.0, SUN, 141),
/** An asteroid */
Eros (17.0, 5.5, 0.0, SUN, 144),
/** An asteroid */
Davida (180.0, 127.0, 0.0, SUN, 1310),
/** An asteroid */
Gaspra (9.1, 4.4, 0.0, SUN, 142),
/** An asteroid */
Steins (3.24, 2.04, 0.0, SUN, 1311),
/** An asteroid */
Itokawa (0.535, 0.209, 0.0, SUN, 1312),
// Comets
/** A comet */
P9_Tempel_1 (3.7, 2.5, 0.0, SUN, 1313),
/** A comet */
P19_Borrelly (3.5, 3.5, 0.0, SUN, 1314),
/**
* ID value for a generic 'not a planet' body, for instance
* a space probe.
*/
NOT_A_PLANET (0, 0, 0, SUN, 81);
// Generic unknown body, must be the last item
/**
* The equatorial radius in km.
*/
public final double equatorialRadius;
/**
* The polar radius in km.
*/
public final double polarRadius;
/**
* The relative mass to the Sun (1), greater or equal to 1. Values
* come from JPL DE405 ephemerides, and are used for correcting for
* light deflection.
*/
public final double relativeMass;
/**
* The central body
*/
public final TARGET centralBody;
/**
* The index of the TARGET name
* It is resolved at run-time to either a Spanish or English name.
*/
private final int nameIndex;
/**
* The id number (index) for a comet or asteroid.
*/
private int id = -1;
TARGET(double eqR, double poR, double rM, TARGET centralBody, int nameIndex) {
this.equatorialRadius = eqR;
this.polarRadius = poR;
this.relativeMass = rM;
this.centralBody = centralBody;
this.nameIndex = nameIndex;
}
/**
* Sets the index of a body, used to select a minor body
* when reading asteroids/comets. Default initial value
* for index is -1.
* @param i The index of the body. Should be >= 0.
*/
public void setIndex(int i) {
id = i;
}
/**
* Returns the index, or -1 if it is not set.
* @return The index.
*/
public int getIndex() {
return id;
}
/**
* Check if the index is indeed a valid index of an object. The check is
* made for main objects suitable for ephemeris calculations, such as the
* Sun, the Moon, any planet except Earth, and Pluto. If the index
* is a valid one but is not an index of a given asteroid or a natural satellite
* (neither the Earth or its barycenter), true will be returned. If the index
* is equal to a generic Comet/Asteroid true will be returned since this is
* valid for that specific kind of calculations.
*
* @return True if it is a valid index, false otherwise.
*/
public boolean isValidObjectButNotASatelliteNeitherAnAsteroid()
{
return
this.ordinal() >= TARGET.SUN.ordinal() &&
this.ordinal() <= TARGET.Asteroid.ordinal() &&
this != TARGET.Earth_Moon_Barycenter && this != TARGET.EARTH;
}
/**
* Check if the index is indeed a valid index of a natural satellite.
*
* @return True if it is a valid satellite, false otherwise. Note this method
* returns false for the Moon.
*/
public boolean isNaturalSatellite()
{
return
this.ordinal() >= TARGET.Phobos.ordinal() &&
this.ordinal() <= TARGET.Proteus.ordinal();
}
/**
* Check if the index is indeed a planet.
*
* @return True if it is a planet or the Sun, false otherwise.
*/
public boolean isPlanet()
{
return
this.ordinal() >= TARGET.SUN.ordinal() &&
this.ordinal() <= TARGET.NEPTUNE.ordinal();
}
/**
* Check if the index is indeed an asteroid (or comet).
*
* @return True if it is an asteroid, false otherwise.
*/
public boolean isAsteroid()
{
// Asteroid or comet !
return
this.ordinal() >= TARGET.Ceres.ordinal() &&
this.ordinal() <= TARGET.NOT_A_PLANET.ordinal();
}
/**
* Obtain the name of an object in the default language.
* The language is either Spanish or English, and is set with {@link Translate#setDefaultLanguage(LANGUAGE) }
*
* @return A string with the name of the object.
*/
public String getName()
{
return getNames()[this.ordinal()];
}
/**
* Obtain the name of an object.
*
* @return A string with the name of the object.
*/
public String getEnglishName()
{
return getNames(LANGUAGE.ENGLISH)[this.ordinal()];
}
private String getNameForLanguage(final LANGUAGE lang)
{
try {
return Translate.getEntry(nameIndex, lang);
} catch (Exception exc) {
exc.printStackTrace();
String message = "Cannot translate body name " + this + " to language " + Translate.getDefaultLanguage() + ". This error should never happen!";
Logger.log(LEVEL.ERROR, message);
throw new RuntimeException(message);
}
}
/**
* Returns flattening factor = (equatorial radius - polar radius ) /
* equatorial radius.
*
* @return Flattening factor. Set to 0 if the object size is unknown.
*/
public double getFlatteningFactor()
{
if (this.equatorialRadius == 0.0) return 0.0;
return (this.equatorialRadius - this.polarRadius) / this.equatorialRadius;
}
/**
* Obtains the central body ID of certain object (natural satellite).
*
* @return The central body or SUN if it is not found.
*/
public TARGET getCentralBody()
{
return this.centralBody == null ? SUN : this.centralBody;
}
}
private static String[] populateStringArrayList(LANGUAGE language)
{
ArrayList<String> vS = new ArrayList<String>();
for (TARGET target : TARGET.values()) {
vS.add(target.getNameForLanguage(language));
}
String data[] = DataSet.arrayListToStringArray(vS);
return data;
}
/**
* Returns the names of all available targets.
* @return All names.
*/
public static String[] getNames()
{
return populateStringArrayList(null);
}
/**
* Returns the names of all available targets for a given
* language.
* @param language The language.
* @return All names.
*/
public static String[] getNames(LANGUAGE language)
{
return populateStringArrayList(language);
}
/**
* Obtain the ID constant of an object.
*
* @param name The name of the object.
* @return Object ID, or the 'not a planet' constant if it is not found.
* @throws JPARSECException If an error occurs, for instance when the object
* is null.
*/
public static TARGET getID(String name) throws JPARSECException
{
if (name == null || name.equals("")) throw new JPARSECException("null/empty String as input planet!");
if (Translate.getDefaultLanguage() == LANGUAGE.ENGLISH) {
try {
TARGET out = TARGET.valueOf(name);
return out;
} catch (Exception exc) {}
}
String names[] = Target.getNames();
int index = DataSet.getIndex(names, name);
//if (index < 0) index = DataSet.getIndexStartingWith(names, name);
if (index >= 0) return TARGET.values()[index];
return TARGET.NOT_A_PLANET;
}
/**
* Obtain the ID constant of an object.
*
* @param name The name of the object in English.
* @return Object ID, or 'not a planet' constant if it is not found.
* @throws JPARSECException If an error occurs, for instance when the object
* is null.
*/
public static TARGET getIDFromEnglishName(String name) throws JPARSECException
{
if (name == null || name.equals("")) throw new JPARSECException("null/empty String as input planet!");
try {
TARGET out = TARGET.valueOf(name);
return out;
} catch (Exception exc) {}
String names[] = Target.getNames(LANGUAGE.ENGLISH);
int index = DataSet.getIndex(names, name);
//if (index < 0) index = DataSet.getIndexStartingWith(names, name);
if (index >= 0) return TARGET.values()[index];
return TARGET.NOT_A_PLANET;
}
/**
* Transforms a given latitude from planetocentric to planetogeodetic.
* @param lat Latitude in radians.
* @param target Target body.
* @return Planetogeodetic latitude.
*/
public static double planetocentricToPlanetogeodeticLatitude(double lat, TARGET target) {
double shape = target.getFlatteningFactor(); // (equatorial - polar radius) / (equatorial radius)
return Math.atan(Math.tan(lat) / Math.pow(1.0 - shape, 2.0));
}
/**
* Transforms a given latitude from planetogeodetic to planetocentric.
* @param lat Latitude in radians.
* @param target Target body.
* @return Planetocentric latitude.
*/
public static double planetogeodeticToPlanetocentricLatitude(double lat, TARGET target) {
double shape = target.getFlatteningFactor(); // (equatorial - polar radius) / (equatorial radius)
return Math.atan(Math.tan(lat) * Math.pow(1.0 - shape, 2.0));
}
}
| true
|
8341241ca88a9db1a2a575d000afcd12bcc52839
|
Java
|
theagos/jcrapi
|
/src/main/java/jcrapi/request/ClanHistoryRequest.java
|
UTF-8
| 1,920
| 2.46875
| 2
|
[] |
no_license
|
package jcrapi.request;
import com.google.common.base.Preconditions;
import java.util.List;
import java.util.Map;
/**
* @author Michael Lieshoff
*/
public class ClanHistoryRequest extends LimitedRequest {
private final String tag;
private final Integer days;
private ClanHistoryRequest(String tag, Integer days, int limit, int max, int page, List<String> excludes, List<String> includes) {
super(limit, max, page, excludes, includes);
Preconditions.checkNotNull(tag, "tag");
Preconditions.checkArgument(tag.length() > 0, "tag");
if (days != null) {
Preconditions.checkArgument(days >= 0, "days");
}
this.tag = tag;
this.days = days;
}
public String getTag() {
return tag;
}
public Integer getDays() {
return days;
}
@Override
public Map<String, String> getQueryParameters() {
Map<String, String> parameters = super.getQueryParameters();
if (days != null) {
parameters.put("days", days.toString());
}
return parameters;
}
public static ClanHistoryRequestBuilder builder(String tag) {
return new ClanHistoryRequestBuilder(tag);
}
public static class ClanHistoryRequestBuilder extends LimitedRequestBuilder<ClanHistoryRequest, ClanHistoryRequestBuilder> {
private final String tag;
private Integer days;
public ClanHistoryRequestBuilder(String tag) {
this.tag = tag;
}
public ClanHistoryRequestBuilder days(Integer days) {
this.days = days;
return getThis();
}
@Override
public ClanHistoryRequest build() {
return new ClanHistoryRequest(tag, days, limit, max, page, excludes, keys);
}
@Override
public ClanHistoryRequestBuilder getThis() {
return this;
}
}
}
| true
|
9714b3ec05f1b94654980f4c6e714670b9541389
|
Java
|
whoareyouwhoami/ProjectShare
|
/src/main/java/com/project/share/service/MessageProjectService.java
|
UTF-8
| 737
| 1.96875
| 2
|
[] |
no_license
|
package com.project.share.service;
import com.project.share.model.MessageProject;
import com.project.share.model.MessageProjectDetail;
import com.project.share.model.Project;
import com.project.share.model.User;
import java.util.Set;
public interface MessageProjectService {
MessageProject createMessageProject(Project project);
MessageProject getMessageProject(Project project);
MessageProject getMessageProjectById(int id);
// Adding user to project group
void addMessageProjectUser(User user, MessageProject messageProject);
void saveMessageProjectDetail(User sender, MessageProject messageProject, String content);
boolean checkMessageProjectUserExist(User user, MessageProject messageProject);
}
| true
|
c1453de44dec8efa16a827bddd4fcfa9547f88ef
|
Java
|
wizacass/DS_Lab3
|
/src/edu/ktu/ds/lab3/petrauskas/HashTest.java
|
UTF-8
| 1,721
| 3.296875
| 3
|
[] |
no_license
|
package edu.ktu.ds.lab3.petrauskas;
import edu.ktu.ds.lab3.utils.HashMap;
import edu.ktu.ds.lab3.utils.Ks;
import java.util.Random;
import java.util.Set;
public class HashTest
{
private HashMap<String, String> hashMap;
private HashMap<String, String> otherMap;
private Random rnd;
public HashTest()
{
hashMap = new HashMap<>();
otherMap = new HashMap<>();
rnd = new Random();
rnd.setSeed(2017);
}
public void run()
{
Ks.oun("Hash Table test starting...");
initialize();
initializeSecond();
Ks.oun("Number of empties: " + hashMap.numberOfEmpties());
var keys = hashMap.keySet();
printKeys(keys);
hashMap.putAll(otherMap);
print("Map after merging:", hashMap);
}
private void initialize()
{
hashMap.put("Petrauskas", "Vytenis");
hashMap.put("Pilinkus", "Martynas");
hashMap.put("Blockis", "Martynas");
hashMap.putIfAbsent("Blockis", "Laurynas");
print("Initial elements:", hashMap);
}
private void initializeSecond()
{
otherMap.put("Petrauskas", "Jonas");
otherMap.put("Jusas", "Vacius");
print("Initial elements:", otherMap);
}
private void print(String header, HashMap<String, String> map)
{
Ks.oun(header);
System.out.println(map.toString());
}
private void printKeys(Set<String> keys)
{
Ks.oun("Keys:");
for (var key :keys)
{
System.out.println(key.toString());
}
}
public static void main(String... args)
{
new HashTest().run();
Ks.oun("Hash Table test complete!");
}
}
| true
|
c3d2ff8fc8f7bfa4ab96a241aa804f99a89541e6
|
Java
|
lukascel/bootcamp
|
/src/main/java/com/bootcamp/bootcamp/Models/Mode.java
|
UTF-8
| 548
| 1.976563
| 2
|
[] |
no_license
|
package com.bootcamp.bootcamp.Models;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.stereotype.Service;
import javax.persistence.*;
import java.util.List;
@Service
@Entity
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Mode {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Column(unique = true)
private String courseMode;
@OneToMany
private List<CourseEdition> modesList;
}
| true
|
08dee5ea2dfe060ba1f1c709a26ae9afbb6ededb
|
Java
|
Vagner-Filho/apsoo-hotel
|
/src/hospedagemhotel/bd/Conexao.java
|
UTF-8
| 6,002
| 2.671875
| 3
|
[] |
no_license
|
package hospedagemhotel.bd;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import hospedagemhotel.entidades.Hospede;
public class Conexao{
private static Connection conexao;
public static boolean conectar(){
try{
String url = "jdbc:sqlite:database.db";
conexao = DriverManager.getConnection(url);
return true;
}catch(SQLException e){
System.err.println(e.getMessage());
return false;
}
}
public static boolean desconectar(){
try {
if(conexao.isClosed() == false){
conexao.close();
}
} catch (SQLException e) {
System.err.println(e.getMessage());
return false;
}
return true;
}
public static Connection getConexao(){
try{
if(conexao == null){
conectar();
}
if(conexao.isClosed()){
conectar();
}
}catch(SQLException e){
System.err.println("getConexao" + " " + e.getMessage());
}
return conexao;
}
public static void InitBD(){
try {
conexao = getConexao();
Statement stm = conexao.createStatement();
stm.executeUpdate("DROP TABLE IF EXISTS pessoa");
stm.executeUpdate("CREATE TABLE pessoa (" +
"cpf varchar (11) NOT NULL PRIMARY KEY," +
"pes_end integer NOT NULL," +
"nome varchar (255) NOT NULL," +
"dataNasc date," +
"telefone varchar(15)," +
"foreign key (pes_end) references endereco(idEnd));");
stm.executeUpdate("DROP TABLE IF EXISTS funcionario");
stm.executeUpdate("CREATE TABLE funcionario (" +
"fcpf varchar (11) NOT NULL primary key," +
"login varchar (255) NOT NULL," +
"senha varchar (15) NOT NULL," +
"salario decimal (10) NOT NULL," +
"cargo varchar (255) NOT NULL," +
"FOREIGN KEY (fcpf) REFERENCES pessoa(cpf))");
stm.executeUpdate("DROP TABLE IF EXISTS hospede");
stm.executeUpdate("CREATE TABLE hospede (" +
"hcpf varchar (11) NOT NULL primary key," +
"hos_res integer NOT NULL," +
"sexo char (1)," +
"codigoConta integer NOT NULL," +
"FOREIGN KEY (hcpf) REFERENCES pessoa(cpf)," +
"FOREIGN KEY (hos_res) REFERENCES reserva(idRes))");
stm.executeUpdate("DROP TABLE IF EXISTS p_telefone");
stm.executeUpdate("CREATE TABLE p_telefone (" +
"pcpf varchar (255) NOT NULL primary key," +
"num_telefone varchar (11)," +
"FOREIGN KEY (pcpf) REFERENCES pessoa(cpf))");
stm.executeUpdate("DROP TABLE IF EXISTS reserva");
stm.executeUpdate("CREATE TABLE reserva (" +
"idRes integer NOT NULL primary key," +
"fcpf varchar (255) NOT NULL," +
"dataInicial date," +
"dataFinal date," +
"pagamento varchar (255)," +
"FOREIGN KEY (fcpf) REFERENCES funcionario (fcpf))"
);
stm.executeUpdate("DROP TABLE IF EXISTS reservaQuarto");
stm.executeUpdate("CREATE TABLE reservaQuarto (" +
"idRes integer NOT NULL," +
"codigoQuarto integer NOT NULL primary key," +
"FOREIGN KEY (idRes) REFERENCES reserva(idRes)," +
"FOREIGN KEY (codigoQuarto) REFERENCES quarto(codigoQuarto))"
);
stm.executeUpdate("DROP TABLE IF EXISTS quarto");
stm.executeUpdate("CREATE TABLE quarto (" +
"codigoQuarto integer NOT NULL primary key," +
"qua_tip_quarto qua_tip_quarto integer NOT NULL," +
"qua_hospedagem integer NOT NULL," +
"localizao varchar (255)," +
"situacao varchar (255)," +
"FOREIGN KEY (qua_hospedagem) REFERENCES hospedagem(idHospedagem)," +
"FOREIGN KEY (qua_tip_quarto) REFERENCES tipoDeQuarto(idTipQuarto))"
);
stm.executeUpdate("DROP TABLE IF EXISTS hospedagem");
stm.executeUpdate("CREATE TABLE hospedagem (" +
"idHospedagem integer NOT NULL primary key," +
"hos_res integer NOT NULL," +
"fcpf varchar (11) NOT NULL," +
"hcpf varchar (11) NOT NULL," +
"hdata date," +
"horario time," +
"FOREIGN KEY (fcpf) REFERENCES funcionario(fcpf)," +
"FOREIGN KEY (hos_res) REFERENCES reserva(idRes)," +
"FOREIGN KEY (hcpf) REFERENCES hospede(hcpf))"
);
stm.executeUpdate("DROP TABLE IF EXISTS endereco");
stm.executeUpdate("CREATE TABLE endereco (" +
"idEnd integer NOT NULL primary key," +
"rua varchar (255)," +
"numero integer (4)," +
"bairro varchar (255)," +
"cep varchar (8) NOT NULL," +
"cidade varchar (255)," +
"estado char (2)," +
"complemento varchar (500))"
);
stm.executeUpdate("DROP TABLE IF EXISTS tipoDeQuarto");
stm.executeUpdate("CREATE TABLE tipoDeQuarto (" +
"idTipQuarto integer NOT NULL primary key," +
"valor integer," +
"descricao varchar (500))"
);
stm.executeUpdate("DROP TABLE IF EXISTS itemServico");
stm.executeUpdate("CREATE TABLE itemServico (" +
"item_ser_hospedagem integer NOT NULL," +
"idTipSer integer NOT NULL primary key," +
"tipo varchar (255)," +
"valor integer," +
"descricao varchar (255)," +
"FOREIGN KEY (item_ser_hospedagem) REFERENCES hospedagem(idHospedagem))"
);
stm.executeUpdate("DROP TABLE IF EXISTS servico");
stm.executeUpdate("CREATE TABLE servico (" +
"codigo integer NOT NULL primary key," +
"ser_tip_ser integer NOT NULL," +
"FOREIGN KEY (ser_tip_ser) REFERENCES itemServico(idTipSer))"
);
stm.close();
//System.out.println("FUNCIONA");
} catch (SQLException e) {
System.err.println("initBD" + " " + e.getMessage());
}
}
public static void alterarBD(String query){
try {
conexao = getConexao();
Statement stm = conexao.createStatement();
stm.executeUpdate(query);
stm.close();
} catch (SQLException e) {
System.err.println(e.getMessage());
}
}
public static String buscarHospede(String cpf){
try{
String query = "select nome from hospede join pessoa on " + cpf + " = pessoa.cpf";
conexao = getConexao();
Statement stm = conexao.createStatement();
return stm.executeQuery(query).getString("nome");
}catch(SQLException e){
return null;
}
}
}
| true
|
0dae4517c6b5510a12cd01a0c589fe7cda9ebb1c
|
Java
|
lanaflonform/Microservices
|
/auth-service/src/main/java/home/project/authservice/repository/impl/UserDetailsRepositoryImpl.java
|
UTF-8
| 7,756
| 2.171875
| 2
|
[
"MIT"
] |
permissive
|
package home.project.authservice.repository.impl;
import home.project.authservice.entity.UserDetailsEntity;
import home.project.authservice.exceptions.DuplicateUserNameException;
import home.project.authservice.exceptions.UserRepositoryException;
import home.project.authservice.repository.UserDetailsRepository;
import home.project.crossserviceapi.auth.entity.FullName;
import home.project.crossserviceapi.auth.entity.UserDetailsPrincipal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Repository;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;
@Repository
public class UserDetailsRepositoryImpl implements UserDetailsRepository {
private static final String SELECT_USER_DETAILS_BY_USER_NAME =
"select * from ( " +
" select * from users_scheme.users " +
" where " +
" username = ? " +
") as selected_username\n" +
"join users_scheme.user_roles\n" +
"on users_scheme.user_roles.username = selected_username.username";
private static final String INSERT_USER =
"insert into users_scheme.users " +
"(username, password, first_name, middle_name, last_name, enabled) " +
"values " +
"(?, ?, ?,?,?, ?) " +
"ON CONFLICT ON CONSTRAINT users_pkey " +
"DO NOTHING ";
private static final String INSERT_AUTHORITIES =
"insert into users_scheme.user_roles " +
"(username, authority) " +
"values " +
"(?, ?)";
public static final String USERNAME = "username";
public static final String PASSWORD = "password";
public static final String AUTHORITY = "authority";
public static final String FIRST_NAME = "first_name";
public static final String MIDDLE_NAME = "middle_name";
public static final String LAST_NAME = "last_name";
public static final String EXTERNAL_DATA = "external_data";
private DataSource dataSource;
private PasswordEncoder passwordEncoder;
@Autowired
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
@Autowired
public void setPasswordEncoder(PasswordEncoder passwordEncoder) {
this.passwordEncoder = passwordEncoder;
}
@Override
public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
try (Connection connection = dataSource.getConnection()) {
PreparedStatement preparedStatement = connection.prepareStatement(SELECT_USER_DETAILS_BY_USER_NAME);
preparedStatement.setString(1, s);
ResultSet resultSet = preparedStatement.executeQuery();
UserDetailsEntity userDetailsEntity = resultSetToUserDetailsEntity(resultSet);
/*
builder
.username(s)
//.password(passwordEncoder.encode(userDetailsEntity.getPassword()))
.password(userDetailsEntity.getPassword())
.authorities(authoritiesListToArray(userDetailsEntity.getAuthorities()))
.build();
*/
List<String> authoritiesAsStringList = userDetailsEntity.getAuthorities();
List<SimpleGrantedAuthority> grantedAuthorities =
authoritiesAsStringList.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());
String username = userDetailsEntity.getUsername();
String password = userDetailsEntity.getPassword();
FullName fullName = userDetailsEntity.getFullName();
String externalData = userDetailsEntity.getExternalData();
return new UserDetailsPrincipal(username, password, grantedAuthorities, externalData, fullName);
} catch (SQLException e) {
e.printStackTrace();
throw new UsernameNotFoundException("SQL Exception");
}
}
@Override
public UserDetailsEntity addUser(UserDetailsEntity userDetailsEntity) throws UserRepositoryException, DuplicateUserNameException {
try (Connection connection = dataSource.getConnection()) {
String username = userDetailsEntity.getUsername();
String password = userDetailsEntity.getPassword();
FullName fullName = userDetailsEntity.getFullName();
boolean enabled = userDetailsEntity.isEnabled();
List<String> authorities = userDetailsEntity.getAuthorities();
connection.setAutoCommit(false);
PreparedStatement insertUserStatement = connection.prepareStatement(INSERT_USER);
PreparedStatement insertAuthorityStatement = connection.prepareStatement(INSERT_AUTHORITIES);
insertUserStatement.setString(1, username);
insertUserStatement.setString(2, password);
insertUserStatement.setString(3, fullName.getFirstName());
insertUserStatement.setString(4, fullName.getMiddleName());
insertUserStatement.setString(5, fullName.getLastName());
insertUserStatement.setBoolean(6, enabled);
int updatedRows = insertUserStatement.executeUpdate();
if (updatedRows == 0) {
throw new DuplicateUserNameException();
}
for (String authority : authorities) {
insertAuthorityStatement.setString(1, username);
insertAuthorityStatement.setString(2, authority);
insertAuthorityStatement.addBatch();
}
insertAuthorityStatement.executeBatch();
connection.commit();
return userDetailsEntity;
} catch (SQLException e) {
e.printStackTrace();
throw new UserRepositoryException(e);
}
}
private UserDetailsEntity resultSetToUserDetailsEntity(ResultSet resultSet) throws SQLException {
if (!resultSet.next()) {
throw new UsernameNotFoundException("No user found");
}
String username = resultSet.getString(USERNAME);
String password = resultSet.getString(PASSWORD);
String firstName = resultSet.getString(FIRST_NAME);
String middleName = resultSet.getString(MIDDLE_NAME);
String lastName = resultSet.getString(LAST_NAME);
String externalData = resultSet.getString(EXTERNAL_DATA);
FullName fullName = new FullName(firstName, middleName, lastName);
List<String> authorities = new LinkedList<>();
authorities.add(resultSet.getString(AUTHORITY));
while (resultSet.next()) {
authorities.add(resultSet.getString(AUTHORITY));
}
UserDetailsEntity userDetailsEntity = new UserDetailsEntity();
userDetailsEntity.setUsername(username);
userDetailsEntity.setPassword(password);
userDetailsEntity.setAuthorities(authorities);
userDetailsEntity.setFullName(fullName);
userDetailsEntity.setExternalData(externalData);
return userDetailsEntity;
}
private String[] authoritiesListToArray(List<String> authorities) {
return authorities.toArray(new String[authorities.size()]);
}
}
| true
|
9c888181420a54f1a5211100c92c00bb130853f5
|
Java
|
pilimeli/EntregaFinalTae_PilarMontes
|
/PilarMontesFinalExam/src/main/java/com/globant/utils/DateUtils.java
|
UTF-8
| 814
| 3.265625
| 3
|
[] |
no_license
|
package com.globant.utils;
import java.time.Duration;
/**
* Class to convert the time to do the duration order
*/
public class DateUtils {
private static String cleanDurationText(String duration) {
return duration.substring(0, duration.indexOf("(")).trim();
}
public static Duration getDuration(String duration) {
String[] elements = cleanDurationText(duration).split(" ");
Duration time = Duration.ZERO;
for (String element : elements) {
if (element.contains("h")) {
time = time.plusHours(Integer.parseInt(element.replace("h", "").trim()));
} else if (element.contains("m")) {
time = time.plusMinutes(Integer.parseInt(element.replace("m", "").trim()));
}
}
return time;
}
}
| true
|
74005dc55026f8e28f7ef2d7cd5743f9309ee3af
|
Java
|
MikuSugar/LeetCode
|
/JavaCode/random_records/N401_500/N468_validate_ip_address.java
|
UTF-8
| 3,116
| 3.46875
| 3
|
[
"Apache-2.0"
] |
permissive
|
package JavaCode.random_records.N401_500;
public class N468_validate_ip_address {
private static String NO="Neither";
private static String I4="IPv4";
private static String I6="IPv6";
public String validIPAddress(String ip) {
if(ip.contains("."))return check0(ip);
else if(ip.contains(":"))return check1(ip);
return NO;
}
private String check1(String ip) {
if(ip.charAt(0)==':'||ip.charAt(ip.length()-1)==':'||ip.contains("-")||ip.contains("+"))return NO;
String[] strs=ip.split(":");
if(strs.length!=8)return NO;
for (String s:strs)
{
if(s==null||s.length()==0||s.length()>4)return NO;
try
{
Integer.parseInt(s,16);
}catch (Exception e)
{
return NO;
}
}
return I6;
}
private String check0(String ip) {
if(ip.charAt(0)=='.'||ip.charAt(ip.length()-1)=='.'||ip.contains("-")||ip.contains("+"))return NO;
String[] strs=ip.split("\\.");
if(strs.length!=4)return NO;
for (String s:strs)
{
if(s==null||s.length()==0||s.length()>3||(s.length()>1&&s.charAt(0)=='0'))return NO;
int n;
try{
n=Integer.parseInt(s);
}
catch (Exception e)
{
return NO;
}
if(n<0||n>255)return NO;
}
return I4;
}
}
/**
* 编写一个函数来验证输入的字符串是否是有效的 IPv4 或 IPv6 地址。
*
* IPv4 地址由十进制数和点来表示,每个地址包含4个十进制数,其范围为 0 - 255, 用(".")分割。比如,172.16.254.1;
*
* 同时,IPv4 地址内的数不会以 0 开头。比如,地址 172.16.254.01 是不合法的。
*
* IPv6 地址由8组16进制的数字来表示,每组表示 16 比特。这些组数字通过 (":")分割。比如, 2001:0db8:85a3:0000:0000:8a2e:0370:7334 是一个有效的地址。而且,我们可以加入一些以 0 开头的数字,字母可以使用大写,也可以是小写。所以, 2001:db8:85a3:0:0:8A2E:0370:7334 也是一个有效的 IPv6 address地址 (即,忽略 0 开头,忽略大小写)。
*
* 然而,我们不能因为某个组的值为 0,而使用一个空的组,以至于出现 (::) 的情况。 比如, 2001:0db8:85a3::8A2E:0370:7334 是无效的 IPv6 地址。
*
* 同时,在 IPv6 地址中,多余的 0 也是不被允许的。比如, 02001:0db8:85a3:0000:0000:8a2e:0370:7334 是无效的。
*
* 说明: 你可以认为给定的字符串里没有空格或者其他特殊字符。
*
* 示例 1:
*
* 输入: "172.16.254.1"
*
* 输出: "IPv4"
*
* 解释: 这是一个有效的 IPv4 地址, 所以返回 "IPv4"。
* 示例 2:
*
* 输入: "2001:0db8:85a3:0:0:8A2E:0370:7334"
*
* 输出: "IPv6"
*
* 解释: 这是一个有效的 IPv6 地址, 所以返回 "IPv6"。
* 示例 3:
*
* 输入: "256.256.256.256"
*
* 输出: "Neither"
*
* 解释: 这个地址既不是 IPv4 也不是 IPv6 地址。
*/
| true
|
68650da656edfedbf395c4fa6fb9139d474e2558
|
Java
|
alemg77/NoticiasArgentina
|
/app/src/main/java/kalitero/software/noticiasargentinas/Vista/NoticiasGenerales/FragmentListaNoticiasCompactoAdapter.java
|
UTF-8
| 6,291
| 2.046875
| 2
|
[] |
no_license
|
package kalitero.software.noticiasargentinas.Vista.NoticiasGenerales;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.squareup.picasso.Picasso;
import java.util.List;
import kalitero.software.noticiasargentinas.modelo.Noticia;
import kalitero.software.noticiasargentinas.R;
import kalitero.software.noticiasargentinas.databinding.CeldaNoticiaBinding;
public class FragmentListaNoticiasCompactoAdapter extends RecyclerView.Adapter {
private List<Noticia> listaDeNoticias;
private AvisoRecyclerViewJava listener;
private String TAG = getClass().toString();
public FragmentListaNoticiasCompactoAdapter(List<Noticia> listaDeNoticias, AvisoRecyclerViewJava listener) {
this.listaDeNoticias = listaDeNoticias;
this.listener = listener;
}
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
CeldaNoticiaBinding celdaNoticiaBinding = CeldaNoticiaBinding.inflate(layoutInflater, parent, false);
FragmentListaNoticiasCompactoAdapter.NoticiaViewHolder viewHolder = new FragmentListaNoticiasCompactoAdapter.NoticiaViewHolder(celdaNoticiaBinding);
return viewHolder;
}
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
((NoticiaViewHolder) holder).cargarNoticia(listaDeNoticias.get(position));
}
@Override
public int getItemCount() {
return listaDeNoticias.size();
}
private class NoticiaViewHolder extends RecyclerView.ViewHolder {
private CeldaNoticiaBinding binding;
private ImageView logo;
private NoticiaViewHolder(@NonNull CeldaNoticiaBinding celdaNoticiaBinding) {
super(celdaNoticiaBinding.getRoot());
binding = celdaNoticiaBinding;
logo = itemView.findViewById(R.id.CeladaNoticiaimageViewLogo);
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
listener.recyclerViewClick(getAdapterPosition());
}
});
}
private void cargarNoticia(Noticia unaNoticia) {
String titulo = unaNoticia.getTitulo();
if (titulo.contains("-")) {
binding.CeldaNoticiaTitulo.setText(titulo.substring(0, titulo.indexOf("-") - 1));
} else {
binding.CeldaNoticiaTitulo.setText(titulo);
}
String urlImagenStorage = unaNoticia.getUrlImagenStorage();
if (urlImagenStorage != null) {
StorageReference child = FirebaseStorage.getInstance().getReference().child(urlImagenStorage);
Glide.with(binding.getRoot()).load(child).into(binding.CeldaNoticiaImagen);
} else if (unaNoticia.getUrlImagen() != null) {
try {
Glide.with(binding.getRoot()).load(unaNoticia.getUrlImagen()).into(binding.CeldaNoticiaImagen);
} catch (Exception e) {
Log.d(TAG, "Problema al cargar imagen:" + e.toString());
}
}
String fuente = unaNoticia.getFuente();
switch (fuente) {
case "La Nacion":
Picasso.get().load(R.drawable.logo_lanacion).into(logo);
break;
case "Tntsports.com":
Picasso.get().load(R.drawable.logo_tntsports).into(logo);
break;
case "Clarin.com":
Picasso.get().load(R.drawable.logo_clarin).into(logo);
break;
case "Eldia.com":
Picasso.get().load(R.drawable.logo_eldia).into(logo);
break;
case "Infobae":
Picasso.get().load(R.drawable.logo_infobae).into(logo);
break;
case "Tycsports.com":
Picasso.get().load(R.drawable.logo_tycsports).into(logo);
break;
case "Ole.com.ar":
Picasso.get().load(R.drawable.logo_ole).into(logo);
break;
case "Mdzol.com":
Picasso.get().load(R.drawable.logo_mdzol).into(logo);
break;
case "Marca":
Picasso.get().load(R.drawable.logo_marca).into(logo);
break;
case "El Mundo":
Picasso.get().load(R.drawable.logo_elmundo).into(logo);
break;
case "Clarín":
Picasso.get().load(R.drawable.clarin).into(logo);
break;
case "ámbito.com":
Picasso.get().load(R.drawable.ambito).into(logo);
break;
case "Computerhoy.com":
Picasso.get().load(R.drawable.logo_computerhoy).into(logo);
break;
case "La Voz del Interior":
Picasso.get().load(R.drawable.logo_la_voz).into(logo);
break;
case "Página 12":
Picasso.get().load(R.drawable.logo_pagina12).into(logo);
break;
case "RT":
Picasso.get().load(R.drawable.logo_rt).into(logo);
break;
case "Diario El Dia. www.eldia.com":
Picasso.get().load(R.drawable.logo_el_dia).into(logo);
break;
default:
Log.d(TAG, "****** FALTA AGREGAR EL LOGO DE:" + fuente + "*****************");
break;
}
}
}
public interface AvisoRecyclerViewJava {
void recyclerViewClick(int posicion);
}
}
| true
|
c6d7e7cb9cd8af9f97eb1bb00db1ed7fc92def8d
|
Java
|
fjh658/bindiff
|
/src_fernflower/com/google/security/zynamics/zylib/gui/JCaret/ICaretListener.java
|
UTF-8
| 195
| 1.648438
| 2
|
[] |
no_license
|
package com.google.security.zynamics.zylib.gui.JCaret;
import com.google.security.zynamics.zylib.gui.JCaret.JCaret;
public interface ICaretListener {
void caretStatusChanged(JCaret var1);
}
| true
|
12f9ccc37de03dfdb027cc834f1b313ddd1a699f
|
Java
|
freqgis/source
|
/app/src/test/java/org/seamcat/function/BinarySearchTest.java
|
UTF-8
| 1,834
| 2.96875
| 3
|
[] |
no_license
|
package org.seamcat.function;
import junit.framework.Assert;
import org.junit.Test;
import static java.util.Arrays.asList;
import static org.seamcat.function.BinarySearch.search;
public class BinarySearchTest {
@Test
public void corner_cases() {
int i = search(null, null);
Assert.assertEquals( 0, i );
i = search(asList(1, 2, 3), new BinarySearch.Filter<Integer>() {
public boolean evaluate(Integer integer, int index) {
return true;
}
});
// predicate true for all elements so expect max
Assert.assertEquals( 2, i );
i = search( asList(1,2,3,4,5,6,7,8,9,10,11,12,13), new BinarySearch.Filter<Integer>() {
public boolean evaluate(Integer integer, int index) {
return true;
}
});
Assert.assertEquals( 12, i );
i = search( asList(1.1,2.2,3.3,3.5), new BinarySearch.Filter<Double>() {
public boolean evaluate(Double d, int index) {
return d * d > 100;
}
});
// predicate false for all elements
Assert.assertEquals( 0, i);
i = search( asList(1.1,2.2,3.3,3.5,3.6,3.7,3.8,3.9,4.0,4.1,4.2,4.3,4.5,4.6,4.7), new BinarySearch.Filter<Double>() {
public boolean evaluate(Double d, int index) {
return d * d > 100;
}
});
// predicate false for all elements
Assert.assertEquals( 0, i);
}
@Test
public void doubleList() {
int i = search( asList(1.1, 2.2, 3.3, 3.5, 4.4, 5.0, 6.1, 7.7, 9.1, 10.2, 11.3, 20.1), new BinarySearch.Filter<Double>() {
public boolean evaluate(Double d, int index) {
return d * d < 100;
}
});
Assert.assertEquals( 9, i);
}
}
| true
|
b89da88bc266c79d203b014a18e6e6c56bddb031
|
Java
|
HemrajRijal/SpringTutorial
|
/SpringDemoAOP/src/com/hemraj/demo/aopdemo/aspect/CloudAnalyticsAspects.java
|
UTF-8
| 570
| 2.109375
| 2
|
[] |
no_license
|
package com.hemraj.demo.aopdemo.aspect;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
/**
* Author: hemraj
* Date: 3/9/18.
*/
@Component
@Aspect
@Order(1)
public class CloudAnalyticsAspects {
@Before("com.hemraj.demo.aopdemo.aspect.AOPExpression.forDAOPackageNoGetterAndSetter()")
public void performCloudAnalytics() {
System.out.println("=====>Performing cloud analytics operation on a async way");
}
}
| true
|
0d9544290a07d4ab0360b65ba09f7bd357fc047f
|
Java
|
pptik/semut-emergency-client-app
|
/app/src/main/java/id/pptik/semut/emergencyreport/firebase/FirebaseNotificationService.java
|
UTF-8
| 683
| 2.140625
| 2
|
[] |
no_license
|
package id.pptik.semut.emergencyreport.firebase;
import android.util.Log;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
public class FirebaseNotificationService extends FirebaseMessagingService {
private final String TAG = this.getClass().getSimpleName();
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.d(TAG, "From: " + remoteMessage.getFrom());
Log.d(TAG, remoteMessage.getCollapseKey());
Log.d(TAG, "payload : "+remoteMessage.getData());
Log.d(TAG, "Notification Message Body: " + remoteMessage.getNotification().getBody());
}
}
| true
|
bc5e799a69bfafcb26f2b9f33de146d649c8041d
|
Java
|
wqf6146/WooSport
|
/app/build/generated/source/apt/release/com/yhrjkf/woyundong/fragment/SetFragment$$ViewBinder.java
|
UTF-8
| 1,427
| 1.585938
| 2
|
[] |
no_license
|
// Generated code from Butter Knife. Do not modify!
package com.yhrjkf.woyundong.fragment;
import android.view.View;
import butterknife.ButterKnife.Finder;
import butterknife.ButterKnife.ViewBinder;
public class SetFragment$$ViewBinder<T extends com.yhrjkf.woyundong.fragment.SetFragment> implements ViewBinder<T> {
@Override public void bind(final Finder finder, final T target, Object source) {
View view;
view = finder.findRequiredView(source, 2131624204, "field 'mImgBack'");
target.mImgBack = finder.castView(view, 2131624204, "field 'mImgBack'");
view = finder.findRequiredView(source, 2131624205, "field 'mRlYyBp'");
target.mRlYyBp = finder.castView(view, 2131624205, "field 'mRlYyBp'");
view = finder.findRequiredView(source, 2131624207, "field 'mTvVoiceReport'");
target.mTvVoiceReport = finder.castView(view, 2131624207, "field 'mTvVoiceReport'");
view = finder.findRequiredView(source, 2131624210, "field 'mBtnAutoPause'");
target.mBtnAutoPause = finder.castView(view, 2131624210, "field 'mBtnAutoPause'");
view = finder.findRequiredView(source, 2131624212, "field 'mTvResetPwd'");
target.mTvResetPwd = finder.castView(view, 2131624212, "field 'mTvResetPwd'");
}
@Override public void unbind(T target) {
target.mImgBack = null;
target.mRlYyBp = null;
target.mTvVoiceReport = null;
target.mBtnAutoPause = null;
target.mTvResetPwd = null;
}
}
| true
|
47752c4ae3605b1e75434c6ac0a24500c1e09279
|
Java
|
better-dev-io/solid_ocp_java_example
|
/src/com/ocp_example/domain/payment/PaymentGateway.java
|
UTF-8
| 253
| 2.125
| 2
|
[] |
no_license
|
package com.ocp_example.domain.payment;
import com.ocp_example.model.PurchaseOrder;
//PaymentGateway used as a common interface for all e-payment providers
public interface PaymentGateway {
String generatePaymentLink(PurchaseOrder purchaseOrder);
}
| true
|