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
e33c223700c2836946c231a05ad29475b516b282
Java
Hamedamz/AP_3
/src/models/GameLogic/utills/StringUtils.java
UTF-8
366
2.578125
3
[]
no_license
package models.GameLogic.utills; public class StringUtils { public static String stringSeparator(String old) { String[] split = old.split("(?=\\p{Upper})"); StringBuilder separated = new StringBuilder(); for (String s : split) { separated.append(s).append("\n"); } return separated.toString().trim(); } }
true
59bfed4cd11ee44482bc4a8fc03bbc4bb1a02383
Java
cha63506/CompSecurity
/GoogleWallet_source/src/com/google/android/apps/wallet/kyc/api/KycClient.java
UTF-8
5,232
1.890625
2
[]
no_license
// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.geocities.com/kpdus/jad.html // Decompiler options: braces fieldsfirst space lnc package com.google.android.apps.wallet.kyc.api; import com.google.android.apps.wallet.callstatus.CallErrorException; import com.google.android.apps.wallet.logging.WLog; import com.google.android.apps.wallet.rpc.RpcCaller; import com.google.android.apps.wallet.rpc.RpcException; import com.google.common.base.Preconditions; public class KycClient { private static final String TAG = com/google/android/apps/wallet/kyc/api/KycClient.getSimpleName(); private final RpcCaller rpcCaller; KycClient(RpcCaller rpccaller) { rpcCaller = (RpcCaller)Preconditions.checkNotNull(rpccaller); } public static int getKycStatus(com.google.wallet.proto.NanoWalletEntities.KycStatus kycstatus) { if (kycstatus != null && kycstatus.status != null) { return kycstatus.status.intValue(); } else { return 0; } } public final com.google.wallet.proto.api.NanoWalletKyc.AcceptKycTosResponse acceptKycTos(com.google.wallet.proto.api.NanoWalletKyc.AcceptKycTosRequest acceptkyctosrequest) throws RpcException { return (com.google.wallet.proto.api.NanoWalletKyc.AcceptKycTosResponse)rpcCaller.call("b/kyc/acceptKycTos", acceptkyctosrequest, new com.google.wallet.proto.api.NanoWalletKyc.AcceptKycTosResponse()); } public final com.google.wallet.proto.api.NanoWalletKyc.GetKycStatusResponse getGetKycStatusResponse() throws RpcException, CallErrorException { com.google.wallet.proto.api.NanoWalletKyc.GetKycStatusResponse getkycstatusresponse = (com.google.wallet.proto.api.NanoWalletKyc.GetKycStatusResponse)rpcCaller.call("b/kyc/getKycStatus", new com.google.wallet.proto.api.NanoWalletKyc.GetKycStatusRequest(), new com.google.wallet.proto.api.NanoWalletKyc.GetKycStatusResponse()); if (getkycstatusresponse.callError != null) { throw new CallErrorException(getkycstatusresponse.callError); } boolean flag; if (getkycstatusresponse.kycStatus != null) { flag = true; } else { flag = false; } Preconditions.checkState(flag, "GetKycStatusResponse is missing KycStatus"); WLog.dfmt(TAG, "KycStatus: %s", new Object[] { getkycstatusresponse.kycStatus }); return getkycstatusresponse; } public final com.google.wallet.proto.api.NanoWalletKyc.GetKycDataResponse getKycData() throws RpcException, CallErrorException { com.google.wallet.proto.api.NanoWalletKyc.GetKycDataResponse getkycdataresponse = (com.google.wallet.proto.api.NanoWalletKyc.GetKycDataResponse)rpcCaller.call("b/kyc/getKycData", new com.google.wallet.proto.api.NanoWalletKyc.GetKycDataRequest(), new com.google.wallet.proto.api.NanoWalletKyc.GetKycDataResponse()); if (getkycdataresponse.callError != null) { throw new CallErrorException(getkycdataresponse.callError); } else { return getkycdataresponse; } } public final int getKycStatus() throws RpcException, CallErrorException { return getKycStatus(getGetKycStatusResponse().kycStatus); } public final com.google.wallet.proto.api.NanoWalletKyc.SubmitAnswersResponse submitAnswers(com.google.wallet.proto.api.NanoWalletKyc.SubmitAnswersRequest submitanswersrequest) throws RpcException { return (com.google.wallet.proto.api.NanoWalletKyc.SubmitAnswersResponse)rpcCaller.call("b/kyc/submitOowAnswers", submitanswersrequest, new com.google.wallet.proto.api.NanoWalletKyc.SubmitAnswersResponse()); } public final com.google.wallet.proto.api.NanoWalletKyc.SubmitFullSsnResponse submitFullSsn(com.google.wallet.proto.api.NanoWalletKyc.SubmitFullSsnRequest submitfullssnrequest) throws RpcException { return (com.google.wallet.proto.api.NanoWalletKyc.SubmitFullSsnResponse)rpcCaller.call("b/kyc/submitFullSsn", submitfullssnrequest, new com.google.wallet.proto.api.NanoWalletKyc.SubmitFullSsnResponse()); } public final com.google.wallet.proto.api.NanoWalletKyc.SubmitVerificationDocumentResponse submitVerificationDocument(com.google.wallet.proto.api.NanoWalletKyc.SubmitVerificationDocumentRequest submitverificationdocumentrequest) throws RpcException { return (com.google.wallet.proto.api.NanoWalletKyc.SubmitVerificationDocumentResponse)rpcCaller.call("b/kyc/submitVerificationDocument", submitverificationdocumentrequest, new com.google.wallet.proto.api.NanoWalletKyc.SubmitVerificationDocumentResponse()); } public final com.google.wallet.proto.api.NanoWalletKyc.VerifyIdentityResponse verifyIdentity(com.google.wallet.proto.api.NanoWalletKyc.VerifyIdentityRequest verifyidentityrequest) throws RpcException { return (com.google.wallet.proto.api.NanoWalletKyc.VerifyIdentityResponse)rpcCaller.call("b/kyc/verifyIdentity", verifyidentityrequest, new com.google.wallet.proto.api.NanoWalletKyc.VerifyIdentityResponse()); } }
true
3213ff6062de66b00668c9407d34b30476a5149d
Java
tongcrane/gzzhwl
/gzzhwl/service/src/main/java/com/gzzhwl/api/account/vo/AccountInfoVO.java
UTF-8
422
1.601563
2
[]
no_license
package com.gzzhwl.api.account.vo; import lombok.Data; import lombok.ToString; @Data @ToString public class AccountInfoVO { private String realName; // 真实姓名 private String idno; // 身份证号 private String idFImageRefId; // 身份照片(正) private String idBImageRefId; // 身份照片(反) private String busImageRefId; // 营业执照照片 private String agentType;// 账户类型 }
true
0543f9c3b2544e9bb1d49feeb15faa09185bd38d
Java
leider/mcbApp
/MCB/src/main/java/mcb/persistenz/json/AdresseFactory.java
UTF-8
656
2.296875
2
[]
no_license
package mcb.persistenz.json; import java.lang.reflect.Type; import mcb.model.Adresse; import mcb.model.Besuch; import flexjson.ObjectBinder; import flexjson.ObjectFactory; import flexjson.factories.BeanObjectFactory; public class AdresseFactory implements ObjectFactory { @SuppressWarnings("rawtypes") @Override public Object instantiate(ObjectBinder context, Object value, Type targetType, Class targetClass) { Adresse adresse = (Adresse) new BeanObjectFactory().instantiate(context, value, targetType, targetClass); for (Besuch besuch : adresse.getBesuchteTreffen()) { besuch.setAdresse(adresse); } return adresse; } }
true
4d6b2b1517f7a3936d48a917fe64055b2d60723d
Java
SilviuNed/CollaborativeFiltering
/src/com/silviuned/model/UserRating.java
UTF-8
400
2.5625
3
[]
no_license
package com.silviuned.model; public class UserRating { private int userId; private short rating; private String date; public UserRating(int userId, short rating, String date) { this.userId = userId; this.rating = rating; this.date = date; } public int getUserId() { return userId; } public short getRating() { return rating; } public String getDate() { return date; } }
true
ab5d18dc02e284ae8df39395a70e4f937f46d5f8
Java
Ocelot5836/MinecraftModdingTutorials
/Tutorial 2/src/main/java/com/ocelot/mod/registry/Registry.java
UTF-8
999
2.203125
2
[]
no_license
package com.ocelot.mod.registry; import static com.ocelot.mod.init.RenderHandler.registerModel; import com.ocelot.mod.init.ModItems; import com.ocelot.mod.init.RenderHandler; import net.minecraft.item.Item; import net.minecraftforge.client.event.ModelRegistryEvent; import net.minecraftforge.event.RegistryEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; /** * <em><b>Copyright (c) 2018 Ocelot5836.</b></em> * * <br> * </br> * * Handles all the registry in the mod. * * @author Ocelot5836 */ public class Registry { @SubscribeEvent public void registerItems(RegistryEvent.Register<Item> event) { event.getRegistry().registerAll(ModItems.getItems()); } @SubscribeEvent public void registerRenders(ModelRegistryEvent event) { RenderHandler.registerMetaItemRenders(); for (int i = 0; i < ModItems.getItems().length; i++) { Item item = ModItems.getItems()[i]; if (item != null && !item.getHasSubtypes()) { registerModel(item); } } } }
true
326a5a18b610f0252ea91d270665e2b754c6f954
Java
harrl7/Example-Work
/Quiz/Mobile/app/src/main/java/a/quiz/QuestionActivity.java
UTF-8
5,321
2.421875
2
[]
no_license
package a.quiz; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.support.v4.content.res.ResourcesCompat; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.JsonReader; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; public class QuestionActivity extends AppCompatActivity { // Layout TextView tvQuestion; Button[] btnAns; Button btnNext; ImageView[] ivMark; // Questions JSON JSONArray questionJson; String jsonString; // Question Question question; int questionIndex; int correctAnswerIndex; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_question); jsonString = getIntent().getStringExtra("json"); //JSONArray questionJson = JSONArray(); // Question TextView tvQuestion = (TextView) findViewById(R.id.tvQuestion); // Answer Buttons btnAns = new Button[4]; btnAns[0] = (Button) findViewById(R.id.btnAns0); btnAns[1] = (Button) findViewById(R.id.btnAns1); btnAns[2] = (Button) findViewById(R.id.btnAns2); btnAns[3] = (Button) findViewById(R.id.btnAns3); btnAns[0].setOnClickListener(new AnswerButtonClickHandler()); btnAns[1].setOnClickListener(new AnswerButtonClickHandler()); btnAns[2].setOnClickListener(new AnswerButtonClickHandler()); btnAns[3].setOnClickListener(new AnswerButtonClickHandler()); // Marking image ivMark = new ImageView[4]; ivMark[0] = findViewById(R.id.ivMark0); ivMark[1] = findViewById(R.id.ivMark1); ivMark[2] = findViewById(R.id.ivMark2); ivMark[3] = findViewById(R.id.ivMark3); // Next button btnNext = findViewById(R.id.btnNext); btnNext.setOnClickListener(new NextQuestionButtonClickHandler()); btnNext.callOnClick(); // question = nextQuestion(); // displayQuestion(); } // Answer Button click handler public class AnswerButtonClickHandler implements View.OnClickListener { @Override public void onClick(View view) { // Find index of users selected answer int selectionIndex = -1; if(view.equals(btnAns[0])) selectionIndex = 0; if(view.equals(btnAns[1])) selectionIndex = 1; if(view.equals(btnAns[2])) selectionIndex = 2; if(view.equals(btnAns[3])) selectionIndex = 3; // disable answer buttons // Show next button btnNext.setVisibility(View.VISIBLE); // Mark image user selection ivMark[selectionIndex].setVisibility(View.VISIBLE); ivMark[selectionIndex].setImageDrawable(ResourcesCompat.getDrawable(getResources(), R.drawable.wrong, null)); // Mark image correct answer ivMark[correctAnswerIndex].setVisibility(View.VISIBLE); ivMark[correctAnswerIndex].setImageDrawable(ResourcesCompat.getDrawable(getResources(), R.drawable.correct, null)); } } // Next question Button click handler public class NextQuestionButtonClickHandler implements View.OnClickListener { @Override public void onClick(View view) { // Load next question question = nextQuestion(); // End after final question if(question == null) { finish(); } else { displayQuestion(); } } } // Load next question private Question nextQuestion() { // Extract Question from JSOn try { JSONArray jsonArray = new JSONArray(jsonString); Question question = Question.FromJson(jsonArray.getJSONObject(questionIndex++)); return question; } catch (JSONException e) { e.printStackTrace(); } catch (NullPointerException e) { e.printStackTrace(); } return null; } // Display question and answers on layout private void displayQuestion() { correctAnswerIndex = (int) (Math.random() * 4); //correctAnswerIndex = 2; // Question tvQuestion.setText(question.question); // Answer buttons int ansTick = correctAnswerIndex; btnAns[ansTick++ % 4].setText(question.correct_answer); btnAns[ansTick++ % 4].setText(question.incorrect_answers[0]); btnAns[ansTick++ % 4].setText(question.incorrect_answers[1]); btnAns[ansTick++ % 4].setText(question.incorrect_answers[2]); // Enable buttons // Hide next button btnNext.setVisibility(View.INVISIBLE); // Hide mark image ivMark[0].setVisibility(View.INVISIBLE); ivMark[1].setVisibility(View.INVISIBLE); ivMark[2].setVisibility(View.INVISIBLE); ivMark[3].setVisibility(View.INVISIBLE); } }
true
3b4376a2a2c0f8bfb0e8149000215b99951cad13
Java
bazaarvoice/bv-android-sdk
/bvcommon/src/main/java/com/bazaarvoice/bvandroidsdk/BVProduct.java
UTF-8
3,239
2.09375
2
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
/** * Copyright 2016 Bazaarvoice Inc. All rights reserved. */ package com.bazaarvoice.bvandroidsdk; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.google.gson.annotations.SerializedName; import java.util.List; /** * Bazaarvoice Product */ public class BVProduct implements BVDisplayableProductContent{ protected boolean impressed = false; @SerializedName("product") private String productId; @SerializedName("num_reviews") private int numReviews; @SerializedName("avg_rating") private float averageRating; @SerializedName("image_url") private String imageUrl; @SerializedName("product_page_url") private String productPageUrl; @SerializedName("name") private String productName; @SerializedName("CategoryId") private String categoryId; @SerializedName("category_ids") private List<String> categoryIds; public boolean isImpressed() { return impressed; } public List<String> getCategoryIds() { return categoryIds; } private boolean sponsored; private BVReview review; @SerializedName("RS") private String rs; private RecommendationStats recommendationStats; @Deprecated //Use getId public String getProductId() { return productId; } public int getNumReviews() { return numReviews; } @Deprecated //Use getDisplayImageUrl public String getImageUrl() { return imageUrl; } public String getProductPageUrl() { return productPageUrl; } @Deprecated //Use getDisplayName public String getProductName() { return productName; } public boolean isSponsored() { return sponsored; } public BVReview getReview() { return review; } public String getRs() { return rs; } public String getCategoryId() { return categoryId; } void mergeRecommendationStats(RecommendationStats recommendationStats) { this.recommendationStats = recommendationStats; } RecommendationStats getRecommendationStats() { return recommendationStats; } @Override public String toString() { return "BVProduct{" + ", productId='" + productId + '\'' + ", numReviews=" + numReviews + ", averageRating=" + averageRating + ", imageUrl='" + imageUrl + '\'' + ", productPageUrl='" + productPageUrl + '\'' + ", productName='" + productName + '\'' + ", sponsored=" + sponsored + ", review=" + review + ", rs=" + rs + '}'; } @Override @NonNull public String getId() { return productId; } @Override @Nullable public String getDisplayName() { return productName; } @Override @Nullable public String getDisplayImageUrl() { return imageUrl; } @Override public float getAverageRating() { return averageRating; } }
true
5f2de13952565edd19e560426ee995bc60354b54
Java
lbrackspace/atlas-lb
/common/util/src/main/java/org/openstack/atlas/util/ip/exception/IPStringConversionException.java
UTF-8
437
2.0625
2
[]
no_license
package org.openstack.atlas.util.ip.exception; public class IPStringConversionException extends IPException { public IPStringConversionException() { super(); } public IPStringConversionException(String msg) { super(msg); } public IPStringConversionException(String msg,Throwable th) { super(msg,th); } public IPStringConversionException(Throwable th) { super(th); } }
true
4faf2783deb61723905a121428ebfc75ce12907c
Java
victorhaggqvist/android-food
/app/src/main/java/com/snilius/foodlife/App.java
UTF-8
1,321
2.140625
2
[]
no_license
package com.snilius.foodlife; import android.app.Application; import com.facebook.stetho.Stetho; import com.snilius.foodlife.di.ActivityComponent; import com.snilius.foodlife.di.AndroidModule; import com.snilius.foodlife.di.BaseComponent; import com.snilius.foodlife.di.DaggerActivityComponent; import com.snilius.foodlife.di.DaggerBaseComponent; import com.snilius.foodlife.di.NetworkModule; import com.snilius.foodlife.di.StorageModule; import timber.log.Timber; /** * @author Victor Häggqvist * @since 2/15/16 */ public class App extends Application { private ActivityComponent activityComponent; @Override public void onCreate() { super.onCreate(); if (BuildConfig.DEBUG) { Timber.plant(new Timber.DebugTree()); Stetho.initializeWithDefaults(this); } BaseComponent baseComponent = DaggerBaseComponent.builder() .androidModule(new AndroidModule(this)) .networkModule(new NetworkModule(BuildConfig.API_TOKEN)) .storageModule(new StorageModule()) .build(); activityComponent = DaggerActivityComponent.builder() .baseComponent(baseComponent) .build(); } public ActivityComponent getComponent() { return activityComponent; } }
true
81c7af24fe4a846fe2b552d0ffca3d93ca39e7d3
Java
ThePurplePeople/enough
/app/src/main/java/lematthe/calpoly/edu/enough/MessageDetailActivity.java
UTF-8
1,841
2.28125
2
[]
no_license
package lematthe.calpoly.edu.enough; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v4.app.FragmentManager; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.KeyEvent; import android.view.View; /** * Created by laurenmatthews on 11/16/16. */ public class MessageDetailActivity extends AppCompatActivity { //inflate the Message_Detail_Fragment @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_message_detail); // savedInstanceState is non-null when there is fragment state // saved from previous configurations of this activity // (e.g. when rotating the screen from portrait to landscape). // In this case, the fragment will automatically be re-added // to its container so we don't need to manually add it. // For more information, see the Fragments API guide at: // // http://developer.android.com/guide/components/fragments.html // if (savedInstanceState == null) { // Create the detail fragment and add it to the activity // using a fragment transaction. MessageDetailFragment fragment = new MessageDetailFragment(); getSupportFragmentManager().beginTransaction().add(R.id.message_frag_container, fragment).commit(); } } @Override public boolean onKeyDown (int keyCode, KeyEvent event) { if ((keyCode == KeyEvent.KEYCODE_BACK)) { finish(); } return super.onKeyDown(keyCode, event); } }
true
2f9d2ed2729df85341a5d874149718026b5722af
Java
SlavSlavchev/TestHomeworkJava
/src/Problem3_PointsInsideAFigure/P3_PoinsInsideAFigure.java
UTF-8
755
3.328125
3
[]
no_license
package Problem3_PointsInsideAFigure; import java.util.Scanner; public class P3_PoinsInsideAFigure { public static void main(String[] args) { // TODO Auto-generated method stub Scanner input = new Scanner(System.in); String[] inputLine = input.nextLine().split(" "); double x = Double.parseDouble(inputLine[0]); double y = Double.parseDouble(inputLine[1]); if(x >= 12.5 && x <= 22.5){ if(x > 17.5 && x < 20 ){ if(y >= 6 && y <= 8.5){ System.out.println("Inside"); } else{ System.out.println("Outside"); } } else{ if(y >= 6 && y <= 13.5){ System.out.println("Inside"); } else{ System.out.println("Outside"); } } } else{ System.out.println("Outside"); } } }
true
c1b863db599748223abb0659f871a3567839da25
Java
xeraph/kraken
/network/kraken-ice/src/main/java/IceInternal/Instance.java
UTF-8
33,935
1.5
2
[]
no_license
// ********************************************************************** // // Copyright (c) 2003-2010 ZeroC, Inc. All rights reserved. // // This copy of Ice is licensed to you under the terms described in the // ICE_LICENSE file included in this distribution. // // ********************************************************************** package IceInternal; public final class Instance { public Ice.InitializationData initializationData() { // // No check for destruction. It must be possible to access the // initialization data after destruction. // // No mutex lock, immutable. // return _initData; } public TraceLevels traceLevels() { // No mutex lock, immutable. assert(_traceLevels != null); return _traceLevels; } public DefaultsAndOverrides defaultsAndOverrides() { // No mutex lock, immutable. assert(_defaultsAndOverrides != null); return _defaultsAndOverrides; } public synchronized RouterManager routerManager() { if(_state == StateDestroyed) { throw new Ice.CommunicatorDestroyedException(); } assert(_routerManager != null); return _routerManager; } public synchronized LocatorManager locatorManager() { if(_state == StateDestroyed) { throw new Ice.CommunicatorDestroyedException(); } assert(_locatorManager != null); return _locatorManager; } public synchronized ReferenceFactory referenceFactory() { if(_state == StateDestroyed) { throw new Ice.CommunicatorDestroyedException(); } assert(_referenceFactory != null); return _referenceFactory; } public synchronized ProxyFactory proxyFactory() { if(_state == StateDestroyed) { throw new Ice.CommunicatorDestroyedException(); } assert(_proxyFactory != null); return _proxyFactory; } public synchronized OutgoingConnectionFactory outgoingConnectionFactory() { if(_state == StateDestroyed) { throw new Ice.CommunicatorDestroyedException(); } assert(_outgoingConnectionFactory != null); return _outgoingConnectionFactory; } public synchronized ConnectionMonitor connectionMonitor() { if(_state == StateDestroyed) { throw new Ice.CommunicatorDestroyedException(); } assert(_connectionMonitor != null); return _connectionMonitor; } public synchronized ObjectFactoryManager servantFactoryManager() { if(_state == StateDestroyed) { throw new Ice.CommunicatorDestroyedException(); } assert(_servantFactoryManager != null); return _servantFactoryManager; } public synchronized ObjectAdapterFactory objectAdapterFactory() { if(_state == StateDestroyed) { throw new Ice.CommunicatorDestroyedException(); } assert(_objectAdapterFactory != null); return _objectAdapterFactory; } public synchronized int protocolSupport() { if(_state == StateDestroyed) { throw new Ice.CommunicatorDestroyedException(); } return _protocolSupport; } public synchronized ThreadPool clientThreadPool() { if(_state == StateDestroyed) { throw new Ice.CommunicatorDestroyedException(); } assert(_clientThreadPool != null); return _clientThreadPool; } public synchronized ThreadPool serverThreadPool() { if(_state == StateDestroyed) { throw new Ice.CommunicatorDestroyedException(); } if(_serverThreadPool == null) // Lazy initialization. { int timeout = _initData.properties.getPropertyAsInt("Ice.ServerIdleTime"); _serverThreadPool = new ThreadPool(this, "Ice.ThreadPool.Server", timeout); } return _serverThreadPool; } public synchronized EndpointHostResolver endpointHostResolver() { if(_state == StateDestroyed) { throw new Ice.CommunicatorDestroyedException(); } assert(_endpointHostResolver != null); return _endpointHostResolver; } synchronized public RetryQueue retryQueue() { if(_state == StateDestroyed) { throw new Ice.CommunicatorDestroyedException(); } assert(_retryQueue != null); return _retryQueue; } synchronized public Timer timer() { if(_state == StateDestroyed) { throw new Ice.CommunicatorDestroyedException(); } assert(_timer != null); return _timer; } public synchronized EndpointFactoryManager endpointFactoryManager() { if(_state == StateDestroyed) { throw new Ice.CommunicatorDestroyedException(); } assert(_endpointFactoryManager != null); return _endpointFactoryManager; } public synchronized Ice.PluginManager pluginManager() { if(_state == StateDestroyed) { throw new Ice.CommunicatorDestroyedException(); } assert(_pluginManager != null); return _pluginManager; } public int messageSizeMax() { // No mutex lock, immutable. return _messageSizeMax; } public int cacheMessageBuffers() { // No mutex lock, immutable. return _cacheMessageBuffers; } public int clientACM() { // No mutex lock, immutable. return _clientACM; } public int serverACM() { // No mutex lock, immutable. return _serverACM; } public Ice.ImplicitContextI getImplicitContext() { return _implicitContext; } public Ice.Identity stringToIdentity(String s) { return Ice.Util.stringToIdentity(s); } public String identityToString(Ice.Identity ident) { return Ice.Util.identityToString(ident); } public Ice.ObjectPrx getAdmin() { Ice.ObjectAdapter adapter = null; String serverId = null; Ice.LocatorPrx defaultLocator = null; synchronized(this) { if(_state == StateDestroyed) { throw new Ice.CommunicatorDestroyedException(); } final String adminOA = "Ice.Admin"; if(_adminAdapter != null) { return _adminAdapter.createProxy(_adminIdentity); } else if(_initData.properties.getProperty(adminOA + ".Endpoints").length() == 0) { return null; } else { serverId = _initData.properties.getProperty("Ice.Admin.ServerId"); String instanceName = _initData.properties.getProperty("Ice.Admin.InstanceName"); defaultLocator = _referenceFactory.getDefaultLocator(); if((defaultLocator != null && serverId.length() > 0) || instanceName.length() > 0) { if(_adminIdentity == null) { if(instanceName.length() == 0) { instanceName = java.util.UUID.randomUUID().toString(); } _adminIdentity = new Ice.Identity("admin", instanceName); // // Afterwards, _adminIdentity is read-only // } // // Create OA // _adminAdapter = _objectAdapterFactory.createObjectAdapter(adminOA, null); // // Add all facets to OA // java.util.Map<String, Ice.Object> filteredFacets = new java.util.HashMap<String, Ice.Object>(); for(java.util.Map.Entry<String, Ice.Object> p : _adminFacets.entrySet()) { if(_adminFacetFilter.isEmpty() || _adminFacetFilter.contains(p.getKey())) { _adminAdapter.addFacet(p.getValue(), _adminIdentity, p.getKey()); } else { filteredFacets.put(p.getKey(), p.getValue()); } } _adminFacets = filteredFacets; adapter = _adminAdapter; } } } if(adapter == null) { return null; } else { try { adapter.activate(); } catch(Ice.LocalException ex) { // // We cleanup _adminAdapter, however this error is not recoverable // (can't call again getAdmin() after fixing the problem) // since all the facets (servants) in the adapter are lost // adapter.destroy(); synchronized(this) { _adminAdapter = null; } throw ex; } Ice.ObjectPrx admin = adapter.createProxy(_adminIdentity); if(defaultLocator != null && serverId.length() > 0) { Ice.ProcessPrx process = Ice.ProcessPrxHelper.uncheckedCast(admin.ice_facet("Process")); try { // // Note that as soon as the process proxy is registered, the communicator might be // shutdown by a remote client and admin facets might start receiving calls. // defaultLocator.getRegistry().setServerProcessProxy(serverId, process); } catch(Ice.ServerNotFoundException ex) { if(_traceLevels.location >= 1) { StringBuilder s = new StringBuilder(128); s.append("couldn't register server `"); s.append(serverId); s.append("' with the locator registry:\n"); s.append("the server is not known to the locator registry"); _initData.logger.trace(_traceLevels.locationCat, s.toString()); } throw new Ice.InitializationException("Locator knows nothing about server '" + serverId + "'"); } catch(Ice.LocalException ex) { if(_traceLevels.location >= 1) { StringBuilder s = new StringBuilder(128); s.append("couldn't register server `"); s.append(serverId); s.append("' with the locator registry:\n"); s.append(ex.toString()); _initData.logger.trace(_traceLevels.locationCat, s.toString()); } throw ex; } if(_traceLevels.location >= 1) { StringBuilder s = new StringBuilder(128); s.append("registered server `"); s.append(serverId); s.append("' with the locator registry"); _initData.logger.trace(_traceLevels.locationCat, s.toString()); } } return admin; } } public synchronized void addAdminFacet(Ice.Object servant, String facet) { if(_state == StateDestroyed) { throw new Ice.CommunicatorDestroyedException(); } if(_adminAdapter == null || (!_adminFacetFilter.isEmpty() && !_adminFacetFilter.contains(facet))) { if(_adminFacets.get(facet) != null) { throw new Ice.AlreadyRegisteredException("facet", facet); } _adminFacets.put(facet, servant); } else { _adminAdapter.addFacet(servant, _adminIdentity, facet); } } public synchronized Ice.Object removeAdminFacet(String facet) { if(_state == StateDestroyed) { throw new Ice.CommunicatorDestroyedException(); } Ice.Object result = null; if(_adminAdapter == null || (!_adminFacetFilter.isEmpty() && !_adminFacetFilter.contains(facet))) { result = _adminFacets.remove(facet); if(result == null) { throw new Ice.NotRegisteredException("facet", facet); } } else { result = _adminAdapter.removeFacet(_adminIdentity, facet); } return result; } public synchronized void setDefaultLocator(Ice.LocatorPrx locator) { if(_state == StateDestroyed) { throw new Ice.CommunicatorDestroyedException(); } _referenceFactory = _referenceFactory.setDefaultLocator(locator); } public synchronized void setDefaultRouter(Ice.RouterPrx router) { if(_state == StateDestroyed) { throw new Ice.CommunicatorDestroyedException(); } _referenceFactory = _referenceFactory.setDefaultRouter(router); } public void setLogger(Ice.Logger logger) { // // No locking, as it can only be called during plug-in loading // _initData.logger = logger; } public void setThreadHook(Ice.ThreadNotification threadHook) { // // No locking, as it can only be called during plug-in loading // _initData.threadHook = threadHook; } public Class<?> findClass(String className) { return Util.findClass(className, _initData.classLoader); } // // Only for use by Ice.CommunicatorI // public Instance(Ice.Communicator communicator, Ice.InitializationData initData) { _state = StateActive; _initData = initData; try { if(_initData.properties == null) { _initData.properties = Ice.Util.createProperties(); } synchronized(Instance.class) { if(!_oneOffDone) { String stdOut = _initData.properties.getProperty("Ice.StdOut"); String stdErr = _initData.properties.getProperty("Ice.StdErr"); java.io.PrintStream outStream = null; if(stdOut.length() > 0) { // // We need to close the existing stdout for JVM thread dump to go // to the new file // System.out.close(); try { outStream = new java.io.PrintStream(new java.io.FileOutputStream(stdOut, true)); } catch(java.io.FileNotFoundException ex) { Ice.FileException fe = new Ice.FileException(); fe.path = stdOut; fe.initCause(ex); throw fe; } System.setOut(outStream); } if(stdErr.length() > 0) { // // close for consistency with stdout // System.err.close(); if(stdErr.equals(stdOut)) { System.setErr(outStream); } else { try { System.setErr(new java.io.PrintStream(new java.io.FileOutputStream(stdErr, true))); } catch(java.io.FileNotFoundException ex) { Ice.FileException fe = new Ice.FileException(); fe.path = stdErr; fe.initCause(ex); throw fe; } } } _oneOffDone = true; } } if(_initData.logger == null) { String logfile = _initData.properties.getProperty("Ice.LogFile"); if(_initData.properties.getPropertyAsInt("Ice.UseSyslog") > 0) { if(logfile.length() != 0) { throw new Ice.InitializationException("Both syslog and file logger cannot be enabled."); } _initData.logger = new Ice.SysLoggerI(_initData.properties.getProperty("Ice.ProgramName"), _initData.properties.getPropertyWithDefault("Ice.SyslogFacility", "LOG_USER")); } else if(logfile.length() != 0) { _initData.logger = new Ice.LoggerI(_initData.properties.getProperty("Ice.ProgramName"), logfile); } else { _initData.logger = Ice.Util.getProcessLogger(); } } validatePackages(); _traceLevels = new TraceLevels(_initData.properties); _defaultsAndOverrides = new DefaultsAndOverrides(_initData.properties); { final int defaultMessageSizeMax = 1024; int num = _initData.properties.getPropertyAsIntWithDefault("Ice.MessageSizeMax", defaultMessageSizeMax); if(num < 1) { _messageSizeMax = defaultMessageSizeMax * 1024; // Ignore non-sensical values. } else if(num > 0x7fffffff / 1024) { _messageSizeMax = 0x7fffffff; } else { _messageSizeMax = num * 1024; // Property is in kilobytes, _messageSizeMax in bytes } } _cacheMessageBuffers = _initData.properties.getPropertyAsIntWithDefault("Ice.CacheMessageBuffers", 2); // // Client ACM enabled by default. Server ACM disabled by default. // _clientACM = _initData.properties.getPropertyAsIntWithDefault("Ice.ACM.Client", 60); _serverACM = _initData.properties.getPropertyAsInt("Ice.ACM.Server"); _implicitContext = Ice.ImplicitContextI.create(_initData.properties.getProperty("Ice.ImplicitContext")); _routerManager = new RouterManager(); _locatorManager = new LocatorManager(_initData.properties); _referenceFactory = new ReferenceFactory(this, communicator); _proxyFactory = new ProxyFactory(this); boolean ipv4 = _initData.properties.getPropertyAsIntWithDefault("Ice.IPv4", 1) > 0; boolean ipv6 = _initData.properties.getPropertyAsIntWithDefault("Ice.IPv6", 0) > 0; if(!ipv4 && !ipv6) { throw new Ice.InitializationException("Both IPV4 and IPv6 support cannot be disabled."); } else if(ipv4 && ipv6) { _protocolSupport = Network.EnableBoth; } else if(ipv4) { _protocolSupport = Network.EnableIPv4; } else { _protocolSupport = Network.EnableIPv6; } _endpointFactoryManager = new EndpointFactoryManager(this); EndpointFactory tcpEndpointFactory = new TcpEndpointFactory(this); _endpointFactoryManager.add(tcpEndpointFactory); EndpointFactory udpEndpointFactory = new UdpEndpointFactory(this); _endpointFactoryManager.add(udpEndpointFactory); _pluginManager = new Ice.PluginManagerI(communicator); _outgoingConnectionFactory = new OutgoingConnectionFactory(this); _servantFactoryManager = new ObjectFactoryManager(); _objectAdapterFactory = new ObjectAdapterFactory(this, communicator); _retryQueue = new RetryQueue(this); // // Add Process and Properties facets // String[] facetFilter = _initData.properties.getPropertyAsList("Ice.Admin.Facets"); if(facetFilter.length > 0) { _adminFacetFilter.addAll(java.util.Arrays.asList(facetFilter)); } _adminFacets.put("Properties", new PropertiesAdminI(_initData.properties)); _adminFacets.put("Process", new ProcessI(communicator)); } catch(Ice.LocalException ex) { destroy(); throw ex; } } protected synchronized void finalize() throws Throwable { IceUtilInternal.Assert.FinalizerAssert(_state == StateDestroyed); IceUtilInternal.Assert.FinalizerAssert(_referenceFactory == null); IceUtilInternal.Assert.FinalizerAssert(_proxyFactory == null); IceUtilInternal.Assert.FinalizerAssert(_outgoingConnectionFactory == null); IceUtilInternal.Assert.FinalizerAssert(_connectionMonitor == null); IceUtilInternal.Assert.FinalizerAssert(_servantFactoryManager == null); IceUtilInternal.Assert.FinalizerAssert(_objectAdapterFactory == null); IceUtilInternal.Assert.FinalizerAssert(_clientThreadPool == null); IceUtilInternal.Assert.FinalizerAssert(_serverThreadPool == null); IceUtilInternal.Assert.FinalizerAssert(_endpointHostResolver == null); IceUtilInternal.Assert.FinalizerAssert(_timer == null); IceUtilInternal.Assert.FinalizerAssert(_routerManager == null); IceUtilInternal.Assert.FinalizerAssert(_locatorManager == null); IceUtilInternal.Assert.FinalizerAssert(_endpointFactoryManager == null); IceUtilInternal.Assert.FinalizerAssert(_pluginManager == null); IceUtilInternal.Assert.FinalizerAssert(_retryQueue == null); super.finalize(); } public void finishSetup(Ice.StringSeqHolder args) { // // Load plug-ins. // assert(_serverThreadPool == null); Ice.PluginManagerI pluginManagerImpl = (Ice.PluginManagerI)_pluginManager; pluginManagerImpl.loadPlugins(args); // // Create threads. // try { _timer = new Timer(this); if(initializationData().properties.getProperty("Ice.ThreadPriority").length() > 0) { _timer.setPriority(Util.getThreadPriorityProperty(initializationData().properties, "Ice")); } } catch(RuntimeException ex) { String s = "cannot create thread for timer:\n" + Ex.toString(ex); _initData.logger.error(s); throw ex; } try { _endpointHostResolver = new EndpointHostResolver(this); } catch(RuntimeException ex) { String s = "cannot create thread for endpoint host resolver:\n" + Ex.toString(ex); _initData.logger.error(s); throw ex; } _clientThreadPool = new ThreadPool(this, "Ice.ThreadPool.Client", 0); // // Get default router and locator proxies. Don't move this // initialization before the plug-in initialization!!! The proxies // might depend on endpoint factories to be installed by plug-ins. // Ice.RouterPrx router = Ice.RouterPrxHelper.uncheckedCast(_proxyFactory.propertyToProxy("Ice.Default.Router")); if(router != null) { _referenceFactory = _referenceFactory.setDefaultRouter(router); } Ice.LocatorPrx loc = Ice.LocatorPrxHelper.uncheckedCast(_proxyFactory.propertyToProxy("Ice.Default.Locator")); if(loc != null) { _referenceFactory = _referenceFactory.setDefaultLocator(loc); } // // Create the connection monitor and ensure the interval for // monitoring connections is appropriate for client & server // ACM. // int interval = _initData.properties.getPropertyAsInt("Ice.MonitorConnections"); _connectionMonitor = new ConnectionMonitor(this, interval); _connectionMonitor.checkIntervalForACM(_clientACM); _connectionMonitor.checkIntervalForACM(_serverACM); // // Server thread pool initialization is lazy in serverThreadPool(). // // // An application can set Ice.InitPlugins=0 if it wants to postpone // initialization until after it has interacted directly with the // plug-ins. // if(_initData.properties.getPropertyAsIntWithDefault("Ice.InitPlugins", 1) > 0) { pluginManagerImpl.initializePlugins(); } // // This must be done last as this call creates the Ice.Admin object adapter // and eventually registers a process proxy with the Ice locator (allowing // remote clients to invoke on Ice.Admin facets as soon as it's registered). // if(_initData.properties.getPropertyAsIntWithDefault("Ice.Admin.DelayCreation", 0) <= 0) { getAdmin(); } } // // Only for use by Ice.CommunicatorI // public void destroy() { synchronized(this) { // // If the _state is not StateActive then the instance is // either being destroyed, or has already been destroyed. // if(_state != StateActive) { return; } // // We cannot set state to StateDestroyed otherwise instance // methods called during the destroy process (such as // outgoingConnectionFactory() from // ObjectAdapterI::deactivate() will cause an exception. // _state = StateDestroyInProgress; } if(_objectAdapterFactory != null) { _objectAdapterFactory.shutdown(); } if(_outgoingConnectionFactory != null) { _outgoingConnectionFactory.destroy(); } if(_objectAdapterFactory != null) { _objectAdapterFactory.destroy(); } if(_outgoingConnectionFactory != null) { _outgoingConnectionFactory.waitUntilFinished(); } if(_retryQueue != null) { _retryQueue.destroy(); } ThreadPool serverThreadPool = null; ThreadPool clientThreadPool = null; EndpointHostResolver endpointHostResolver = null; synchronized(this) { _objectAdapterFactory = null; _outgoingConnectionFactory = null; _retryQueue = null; if(_connectionMonitor != null) { _connectionMonitor.destroy(); _connectionMonitor = null; } if(_serverThreadPool != null) { _serverThreadPool.destroy(); serverThreadPool = _serverThreadPool; _serverThreadPool = null; } if(_clientThreadPool != null) { _clientThreadPool.destroy(); clientThreadPool = _clientThreadPool; _clientThreadPool = null; } if(_endpointHostResolver != null) { _endpointHostResolver.destroy(); endpointHostResolver = _endpointHostResolver; _endpointHostResolver = null; } if(_timer != null) { _timer._destroy(); _timer = null; } if(_servantFactoryManager != null) { _servantFactoryManager.destroy(); _servantFactoryManager = null; } if(_referenceFactory != null) { _referenceFactory.destroy(); _referenceFactory = null; } // _proxyFactory.destroy(); // No destroy function defined. _proxyFactory = null; if(_routerManager != null) { _routerManager.destroy(); _routerManager = null; } if(_locatorManager != null) { _locatorManager.destroy(); _locatorManager = null; } if(_endpointFactoryManager != null) { _endpointFactoryManager.destroy(); _endpointFactoryManager = null; } if(_pluginManager != null) { _pluginManager.destroy(); _pluginManager = null; } _adminAdapter = null; _adminFacets.clear(); _state = StateDestroyed; } // // Join with threads outside the synchronization. // if(clientThreadPool != null) { clientThreadPool.joinWithAllThreads(); } if(serverThreadPool != null) { serverThreadPool.joinWithAllThreads(); } if(endpointHostResolver != null) { endpointHostResolver.joinWithThread(); } if(_initData.properties.getPropertyAsInt("Ice.Warn.UnusedProperties") > 0) { java.util.List<String> unusedProperties = ((Ice.PropertiesI)_initData.properties).getUnusedProperties(); if(unusedProperties.size() != 0) { StringBuffer message = new StringBuffer("The following properties were set but never read:"); for(String p : unusedProperties) { message.append("\n "); message.append(p); } _initData.logger.warning(message.toString()); } } } private void validatePackages() { final String prefix = "Ice.Package."; java.util.Map<String, String> map = _initData.properties.getPropertiesForPrefix(prefix); for(java.util.Map.Entry<String, String> p : map.entrySet()) { String key = p.getKey(); String pkg = p.getValue(); if(key.length() == prefix.length()) { _initData.logger.warning("ignoring invalid property: " + key + "=" + pkg); } String module = key.substring(prefix.length()); String className = pkg + "." + module + "._Marker"; Class<?> cls = null; try { cls = findClass(className); } catch(java.lang.Exception ex) { } if(cls == null) { _initData.logger.warning("unable to validate package: " + key + "=" + pkg); } } } private static final int StateActive = 0; private static final int StateDestroyInProgress = 1; private static final int StateDestroyed = 2; private int _state; private final Ice.InitializationData _initData; // Immutable, not reset by destroy(). private final TraceLevels _traceLevels; // Immutable, not reset by destroy(). private final DefaultsAndOverrides _defaultsAndOverrides; // Immutable, not reset by destroy(). private final int _messageSizeMax; // Immutable, not reset by destroy(). private final int _cacheMessageBuffers; // Immutable, not reset by destroy(). private final int _clientACM; // Immutable, not reset by destroy(). private final int _serverACM; // Immutable, not reset by destroy(). private final Ice.ImplicitContextI _implicitContext; private RouterManager _routerManager; private LocatorManager _locatorManager; private ReferenceFactory _referenceFactory; private ProxyFactory _proxyFactory; private OutgoingConnectionFactory _outgoingConnectionFactory; private ConnectionMonitor _connectionMonitor; private ObjectFactoryManager _servantFactoryManager; private ObjectAdapterFactory _objectAdapterFactory; private int _protocolSupport; private ThreadPool _clientThreadPool; private ThreadPool _serverThreadPool; private EndpointHostResolver _endpointHostResolver; private RetryQueue _retryQueue; private Timer _timer; private EndpointFactoryManager _endpointFactoryManager; private Ice.PluginManager _pluginManager; private Ice.ObjectAdapter _adminAdapter; private java.util.Map<String, Ice.Object> _adminFacets = new java.util.HashMap<String, Ice.Object>(); private java.util.Set<String> _adminFacetFilter = new java.util.HashSet<String>(); private Ice.Identity _adminIdentity; private static boolean _oneOffDone = false; }
true
2793b24b24d57df9839f37863f5a1023a864f69b
Java
FabienneMarquis/TP3_FM_GP_POO4
/src/main/java/controle/ControllerDriver.java
UTF-8
2,122
2.3125
2
[]
no_license
package controle; import JAXB.Chauffeur; import SAX.ChauffeurReader; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Button; import javafx.scene.control.ChoiceBox; import javafx.scene.control.TextField; import javafx.util.StringConverter; import java.net.URL; import java.util.ResourceBundle; /** * @author Fabienne et Gabriel on 2016-02-04. */ public class ControllerDriver implements Initializable{ @FXML private ChoiceBox<Chauffeur> listOfDrivers; @FXML private Button btnOkChoiceDriver; @FXML private TextField txtFieldNomChauffeur; @FXML private TextField txtFieldPrenomChauffeur; @FXML private TextField txtFieldTelephoneChauffeur; @FXML private TextField txtFieldNumeroPermisChauffeur; @FXML private TextField txtFieldReferencevehiculeChauffeur; @FXML void showDriver(ActionEvent event) { txtFieldNomChauffeur.setText(listOfDrivers.getValue().getNom()); txtFieldPrenomChauffeur.setText(listOfDrivers.getValue().getPrenom()); txtFieldTelephoneChauffeur.setText(listOfDrivers.getValue().getTelephone()); txtFieldNumeroPermisChauffeur.setText(listOfDrivers.getValue().getPermis()); txtFieldReferencevehiculeChauffeur.setText(listOfDrivers.getValue().getRefVehicule()); } ObservableList<Chauffeur> chauffeurs = FXCollections.observableArrayList(); @Override public void initialize(URL location, ResourceBundle resources) { listOfDrivers.setConverter(new StringConverter<Chauffeur>() { @Override public String toString(Chauffeur object) { return object.getNom(); } @Override public Chauffeur fromString(String string) { return null; } }); ChauffeurReader chauffeurReader = new ChauffeurReader(); chauffeurs.setAll(chauffeurReader.read("chauffeurs.xml")); listOfDrivers.setItems(chauffeurs); } }
true
9343278b0d88cb79ff7a3e60df5f3ad2ffaea100
Java
a404318964/ZwjUtils
/src/main/java/com/github/a404318964/zwjutils/DecriptTools.java
UTF-8
7,309
2.875
3
[]
no_license
package com.github.a404318964.zwjutils; import org.apache.commons.codec.binary.Base64; import org.apache.shiro.crypto.SecureRandomNumberGenerator; import org.apache.shiro.crypto.hash.SimpleHash; import sun.misc.BASE64Decoder; import sun.misc.BASE64Encoder; import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; /** * Created by linxiaojun on 16/11/10. */ public class DecriptTools { /** * Base64位加密(支持中文不乱码) * * @param source * @return */ public static String base64(String source) { String result = null; try { byte[] encodeBase64 = Base64.encodeBase64(source.getBytes("UTF-8")); result = new String(encodeBase64); System.out.println("RESULT: " + result); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return result; } public static String SHA1(String decript) { return SHA(decript, "SHA-1"); } public static String SHA(String decript, String shaType) { MessageDigest messageDigest; String encodeStr = ""; try { messageDigest = MessageDigest.getInstance(shaType); messageDigest.update(decript.getBytes("UTF-8")); encodeStr = bytes2Hex(messageDigest.digest()); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return encodeStr; } /** * 利用java原生的摘要实现SHA256加密 * * @param str 加密后的报文 */ public static String getSHA256StrJava(String str) { return SHA(str, "SHA-256"); } public static String MD5(String input) { try { // 获得MD5摘要算法的 MessageDigest 对象 MessageDigest mdInst = MessageDigest.getInstance("MD5"); // 使用指定的字节更新摘要 mdInst.update(input.getBytes()); // 获得密文 byte[] md = mdInst.digest(); // 把密文转换成十六进制的字符串形式 StringBuffer hexString = new StringBuffer(); // 字节数组转换为 十六进制 数 for (int i = 0; i < md.length; i++) { String shaHex = Integer.toHexString(md[i] & 0xFF); if (shaHex.length() < 2) { hexString.append(0); } hexString.append(shaHex); } return hexString.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return ""; } // public static String encrypt4Mall(String content, String password) throws Exception { // Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); // byte[] raw = password.getBytes(); // SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); // IvParameterSpec iv = new IvParameterSpec(password.getBytes());// 使用CBC模式,需要一个向量iv,可增加加密算法的强度 // cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv); // byte[] encrypted = cipher.doFinal(content.getBytes("utf-8")); // return Base64Utils.encodeToString(encrypted);// 此处使用BASE64做转码。 // } // 加密 public static String encryptAES(String content, String password) throws Exception { Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); byte[] raw = password.getBytes(); SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); IvParameterSpec iv = new IvParameterSpec(password.getBytes());// 使用CBC模式,需要一个向量iv,可增加加密算法的强度 cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv); byte[] encrypted = cipher.doFinal(content.getBytes("utf-8")); return new BASE64Encoder().encode(encrypted);// 此处使用BASE64做转码。 } // 解密 public static String decryptAES(String content, String password) throws Exception { try { byte[] raw = password.getBytes("ASCII"); SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); IvParameterSpec iv = new IvParameterSpec(password.getBytes()); cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv); byte[] encrypted1 = new BASE64Decoder().decodeBuffer(content);// 先用base64解密 byte[] original = cipher.doFinal(encrypted1); String originalString = new String(original, "utf-8"); return originalString; } catch (Exception ex) { return null; } } /** * 将密码和盐以MD5散列算法进行两次迭代,返回哈希值作为密码 * * @param password * @param salt * @return */ public static String generatePassword(String password, String salt) { String algorithmName = "md5"; int hashIterations = 2; SimpleHash hash = new SimpleHash(algorithmName, password, salt, hashIterations); return hash.toHex(); } /** * 根据注册的用户名生成pwdSalt * acount + 随机数 * * @param account * @return */ public static String generatePasswordSalt(String account) { return account + new SecureRandomNumberGenerator().nextBytes().toHex(); } // 签名 public static String sign(String str, String type) { String s = Encrypt(str, type); return s; } public static String Encrypt(String strSrc, String encName) { MessageDigest md = null; String strDes = null; byte[] bt = strSrc.getBytes(); try { md = MessageDigest.getInstance(encName); md.update(bt); strDes = bytes2Hex(md.digest()); // to HexString } catch (NoSuchAlgorithmException e) { System.out.println("签名失败!"); return null; } return strDes; } public static String bytes2Hex(byte[] bts) { StringBuilder hexString = new StringBuilder(); // 字节数组转换为 十六进制 数 for (int i = 0; i < bts.length; i++) { String shaHex = Integer.toHexString(bts[i] & 0xFF); if (shaHex.length() == 1) { hexString.append(0); } hexString.append(shaHex); } return hexString.toString(); } /** * 将16进制转换为二进制 * * @param hexStr * @return */ public static byte[] parseHexStr2Byte(String hexStr) { if (hexStr.length() < 1) return null; byte[] result = new byte[hexStr.length() / 2]; for (int i = 0; i < hexStr.length() / 2; i++) { int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16); int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16); result[i] = (byte) (high * 16 + low); } return result; } }
true
0fa57956b97e578f8b94acd9e5a57ed5601b9565
Java
CloudyMQ/SberBank
/src/main/java/com/example/demo2/controller/RemittanceManager.java
UTF-8
2,605
2.4375
2
[]
no_license
package com.example.demo2.controller; import com.example.demo2.entity.Accounts; import com.example.demo2.model.RemittanceModel; import com.example.demo2.repository.AccountsRepository; import com.example.demo2.service.AccountsService; import com.example.demo2.service.RemittanceService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PostMapping; import javax.validation.Valid; import org.springframework.validation.BindingResult; import org.springframework.web.servlet.ModelAndView; import java.util.ArrayList; import java.util.List; @Controller public class RemittanceManager { @Autowired AccountsRepository accountsRepository; @Autowired AccountsService accountsService; @Autowired RemittanceService remittanceService; @GetMapping("/remittance") public String remittance(Model model){ Accounts accounts = accountsRepository.getOne(1); RemittanceModel remittanceModel = new RemittanceModel(); model.addAttribute("remittanceModel", remittanceModel); return "remittance"; } @PostMapping("/remittance") public ModelAndView remittance(@Valid @ModelAttribute RemittanceModel remittanceModel, BindingResult bindingResult, ModelAndView modelAndView) { List<String> messages = new ArrayList<>(); Accounts fromAccounts = accountsRepository.getByAccount(remittanceModel.getRemitter()); if (bindingResult.hasErrors()) { return modelAndView; } else if (!accountsService.isExist(remittanceModel.getRemitter())) { messages.add("Отправителя с таким счетом не существует!"); if (!accountsService.isExist(remittanceModel.getRecipient())){ messages.add("Получателя с таким счетом не существует!"); } } else if(remittanceModel.getAmount().compareTo(fromAccounts.getAmount())>0){ messages.add("Недостаточно средств!"); } else { remittanceService.remittance(remittanceModel); messages.add("Перевод выполнен успешно!"); } modelAndView.setViewName("remittance"); modelAndView.addObject("messages", messages); return modelAndView; } }
true
9a6b78b1e70ec5a5199fcc16e67a62ba9379c23a
Java
Flumdy/Seng201-Game
/src/items/SpacePlagueCure.java
UTF-8
620
2.9375
3
[]
no_license
package items; import supers.ConsumableItem; /** * SpacePlagueCure is a consumable item * which cures the space plague with no additional bonus effects. * * @author Michael Freeman (mjf145) * @author Finn McCartney (fwm16) */ public class SpacePlagueCure extends ConsumableItem{ /** * Constructor for space plague item. */ public SpacePlagueCure() { super.bonusType = "spaceplaguecure"; super.name = "Space Plague Cure"; } /** * Overrides 'toString' method from ConsumableItems superclass to include a description. */ @Override public String toString() { return this.name + ", cures the space plague"; } }
true
5bcde89e54f9d550f891f2963d11fcbf9e952aeb
Java
ozzwoy/OOP-Course
/Lab2/src/main/java/cyb/oop/service/PeriodicalService.java
UTF-8
1,475
2.375
2
[]
no_license
package cyb.oop.service; import java.util.ArrayList; import java.util.List; import java.util.Optional; import cyb.oop.converter.PeriodicalConverter; import cyb.oop.dto.PeriodicalDTO; import cyb.oop.entity.Periodical; import cyb.oop.repository.PeriodicalRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service public class PeriodicalService { private final PeriodicalRepository periodicalRepository; private final PeriodicalConverter periodicalConverter; @Autowired public PeriodicalService(PeriodicalRepository periodicalRepository, PeriodicalConverter periodicalConverter) { this.periodicalRepository = periodicalRepository; this.periodicalConverter = periodicalConverter; } public List<Periodical> findAll() { return periodicalRepository.findAll(); } public Optional<Periodical> findById(long id) { return periodicalRepository.findById(id); } public List<Periodical> findByName(String name) { return periodicalRepository.findByName(name); } @Transactional public void changePeriodicalAvailability(long id, boolean available) { Optional<Periodical> periodical = findById(id); periodical.ifPresent(value -> { value.setAvailable(available); periodicalRepository.save(value); }); } }
true
01bb3a3134ad9b906f5ccc35b822e9acf94d62a7
Java
chencj29/brytrms
/src/main/java/com/thinkgem/jeesite/modules/rms/entity/WarnRemindConfigItem.java
UTF-8
2,858
2.015625
2
[]
no_license
/** * Copyright &copy; 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved. */ package com.thinkgem.jeesite.modules.rms.entity; import com.thinkgem.jeesite.common.persistence.DataEntity; import org.hibernate.validator.constraints.Length; import javax.validation.constraints.NotNull; /** * 预警提醒Entity * @author xiaowu * @version 2016-01-19 */ public class WarnRemindConfigItem extends DataEntity<WarnRemindConfigItem> { private static final long serialVersionUID = 1L; private WarnRemindConfig config; // 主表主键 父类 private String fieldName; // 字段描述 private String fieldCode; // 字段代码 private String conditionName; // 条件描述 private String conditionCode; // 条件代码 private String thresholdValue; // 条件阀值 private Long itemPriority; // 优先级 private Long itemAvailable; // 是否可用 public WarnRemindConfigItem() { super(); } public WarnRemindConfigItem(String id){ super(id); } public WarnRemindConfigItem(WarnRemindConfig config){ this.config = config; } @NotNull(message="主表主键不能为空") public WarnRemindConfig getConfig() { return config; } public void setConfig(WarnRemindConfig config) { this.config = config; } @Length(min=1, max=100, message="字段描述长度必须介于 1 和 100 之间") public String getFieldName() { return fieldName; } public void setFieldName(String fieldName) { this.fieldName = fieldName; } @Length(min=1, max=88, message="字段代码长度必须介于 1 和 88 之间") public String getFieldCode() { return fieldCode; } public void setFieldCode(String fieldCode) { this.fieldCode = fieldCode; } @Length(min=0, max=100, message="条件描述长度必须介于 0 和 100 之间") public String getConditionName() { return conditionName; } public void setConditionName(String conditionName) { this.conditionName = conditionName; } @Length(min=0, max=100, message="条件代码长度必须介于 0 和 100 之间") public String getConditionCode() { return conditionCode; } public void setConditionCode(String conditionCode) { this.conditionCode = conditionCode; } @Length(min=0, max=200, message="条件阀值长度必须介于 0 和 200 之间") public String getThresholdValue() { return thresholdValue; } public void setThresholdValue(String thresholdValue) { this.thresholdValue = thresholdValue; } @NotNull(message="优先级不能为空") public Long getItemPriority() { return itemPriority; } public void setItemPriority(Long itemPriority) { this.itemPriority = itemPriority; } @NotNull(message="是否可用不能为空") public Long getItemAvailable() { return itemAvailable; } public void setItemAvailable(Long itemAvailable) { this.itemAvailable = itemAvailable; } }
true
12016dba31bbec3c34bb4131768bca1c6792deee
Java
fredsilva/sistema
/02_FONTES/core/arrecadacao-core/src/main/java/br/gov/to/sefaz/arr/processamento/ProcessArquivo.java
UTF-8
855
2.734375
3
[]
no_license
package br.gov.to.sefaz.arr.processamento; import java.io.FileInputStream; import java.io.IOException; import java.text.ParseException; /** * Serviço de processamento (leitura, converção, validação, persistência) de um arquivo. * * @author <a href="mailto:breno.hoffmeister@ntconsult.com.br">breno.hoffmeister</a> * @since 07/07/2016 09:28:00 */ public interface ProcessArquivo { /** * Processa (leitura, converção, validação, persistência) um arquivo. * * @param file {@link FileInputStream} arquivo lido a ser processado * @param fileName nome do arquivo * @throws IOException Lança exceção de entrada/saída na leitura do arquivo * @throws ParseException Lança exceção de formatação ao converter os dados */ void processFile(FileInputStream file, String fileName) throws IOException, ParseException; }
true
01cca962f02e4dc8b7810f6ea9bdf69cc761054f
Java
vamshi57/jsonplaceholder-api
/proj-jsonplaceholder/src/main/java/com/vamshi/proj/repo/PostRepo.java
UTF-8
264
1.601563
2
[]
no_license
package com.vamshi.proj.repo; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import com.vamshi.proj.model.Post; @Repository public interface PostRepo extends JpaRepository<Post, Long>{ }
true
0f8286ee8f263c1497f65783ea7ddd680910e9eb
Java
lang61301/gencode
/src/main/java/me/paddingdun/gen/code/config/PropertiesBeanPostProcessor.java
UTF-8
2,189
2.25
2
[]
no_license
/** * */ package me.paddingdun.gen.code.config; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import org.apache.commons.lang.StringUtils; import org.springframework.beans.BeansException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessorAdapter; import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Component; import org.springframework.util.ReflectionUtils; import me.paddingdun.gen.code.annotation.Value1; import me.paddingdun.gen.code.extend.spring.ExtendPropertyPlaceholderConfigurer; import me.paddingdun.gen.code.util.TypesHelper; /** * 自动将绑定@Value1注释的属性注入资源文件中的值; * @author paddingdun * * 2016年4月29日 * @since 1.0 * @version 2.0 */ @Component @Lazy(false) public class PropertiesBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter { @Autowired private ExtendPropertyPlaceholderConfigurer eppc; @Override public Object postProcessAfterInitialization(final Object bean, String beanName) throws BeansException { ReflectionUtils.doWithFields(bean.getClass(), new ReflectionUtils.FieldCallback() { public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException { Value1 v1 = field.getAnnotation(Value1.class); String key = v1.value(); String def = v1.def(); String keyName = field.getName(); if(StringUtils.isNotBlank(key)){ keyName = key.trim(); } String def1 = eppc.getProperty(keyName); if(StringUtils.isBlank(def) && def1 == null){ return; } if(def1 != null){ def = def1; } ReflectionUtils.makeAccessible(field); field.set(bean, TypesHelper.convertBasic(field.getType(), def)); } }, new ReflectionUtils.FieldFilter() { public boolean matches(Field field) { Value1 v1 = field.getAnnotation(Value1.class); if(v1 != null){ return !Modifier.isStatic(field.getModifiers()); } return false; } }); return bean; } }
true
119f75aaf0021e066fa3df2cd51dfda8e6750423
Java
Esgrima/CSCI230
/src/edu/cofc/csci230/BinaryNode2.java
UTF-8
1,877
3.25
3
[]
no_license
//package edu.cofc.csci230; // //public class BinaryNode<Integer extends Comparable<Integer>> { // // protected Integer data; // protected BinaryNode<Integer> left; // protected BinaryNode<Integer> right; // protected BinaryNode<Integer> parent; // // /** // * // * @param data // */ // public BinaryNode(Integer data, BinaryNode<Integer> left, BinaryNode<Integer> right) { // this.data = data; // this.left = left; // this.right = right; // } // // public BinaryNode(Integer data) { // this.data = data; // this.left = null; // this.right = null; // } // // public BinaryNode() { // this.data = null; // this.left = null; // this.right = null; // } // // /** // * // * @param left // */ // public void setLeftChild(BinaryNode<Integer> left){ // this.left = left; // } // // /** // * // * @param right // */ // public void setRightChild(BinaryNode<Integer> right){ // this.right = right; // } // // /** // * // * @param parent // */ // public void setParent(BinaryNode<Integer> parent){ // this.parent = parent; // } // // /** // * // * @return left child // */ // public BinaryNode<Integer> getLeft(){ // return this.left; // } // // /** // * // * @return right child // */ // public BinaryNode<Integer> getRight(){ // return this.right; // } // // /** // * // * @return parent // */ // public BinaryNode<Integer> getParent(){ // return this.parent; // } // // public boolean isLeaf() { // return (this.left == null) && (this.right == null); // } // // public boolean isEmpty() { // // return (this.data == null); // } // // public String toString() // { // return this.getData().toString(); // } // // public Integer getData() { // return this.data; // } // // public void setData(Integer data) { // this.data = data; // } // // //}
true
3e207c7c984f89ebd8193691fb341f5060cc81ba
Java
wuxinda/bis_app
/src/com/bluemobi/serviceimpl/device/util/modbus/ModbusResult.java
UTF-8
774
2.21875
2
[]
no_license
package com.bluemobi.serviceimpl.device.util.modbus; /** * <p> * Title: 基类 * </p> * <p> * Description: * </p> * <p> * Copyright: Copyright (c) 2014 * </p> * <p> * Company: BAYI * </p> * * @author jianghaidong * @version 1.0 * @date 2014-10-17 */ public class ModbusResult { private String ResultCode; //结果代码1001 - 成功,其它失败 private String ErrorInfo; //错误信息 public String getResultCode() { return ResultCode; } public void setResultCode(String resultCode) { ResultCode = resultCode; } public String getErrorInfo() { return ErrorInfo; } public void setErrorInfo(String errorInfo) { ErrorInfo = errorInfo; } public boolean isSuccess(){ return ModbusError.SUCCESS.equals(this.getResultCode()); } }
true
34a4df4662a34fb69c364476bd9b17c982b8a0ad
Java
DominikGazda/LibraryApp
/api/src/main/java/pl/library/components/publisher/PublisherMapper.java
UTF-8
557
2.3125
2
[]
no_license
package pl.library.components.publisher; public class PublisherMapper { public static PublisherDto toDto (Publisher entity){ PublisherDto dto = new PublisherDto(); dto.setPublisherId(entity.getPublisherId()); dto.setPublisherName(entity.getPublisherName()); return dto; } public static Publisher toEntity (PublisherDto dto){ Publisher entity = new Publisher(); entity.setPublisherId(dto.getPublisherId()); entity.setPublisherName(dto.getPublisherName()); return entity; } }
true
e788d1c9dc7231565a1fc89432c1e6f96877bf90
Java
JUCMNAV/projetseg
/jAoUrnToRam/aourn/grl/impl/ActorRefImpl.java
UTF-8
26,004
1.617188
2
[]
no_license
/** * <copyright> * </copyright> * * $Id$ */ package grl.impl; import grl.ActorRef; import grl.GrlPackage; import java.util.Collection; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.notify.NotificationChain; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.impl.ENotificationImpl; import org.eclipse.emf.ecore.util.EObjectWithInverseResolvingEList; import org.eclipse.emf.ecore.util.EcoreUtil; import org.eclipse.emf.ecore.util.InternalEList; import urncore.ComponentLabel; import urncore.IURNContainer; import urncore.IURNContainerRef; import urncore.IURNDiagram; import urncore.IURNNode; import urncore.UrncorePackage; import urncore.impl.GRLmodelElementImpl; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Actor Ref</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * <ul> * <li>{@link grl.impl.ActorRefImpl#getX <em>X</em>}</li> * <li>{@link grl.impl.ActorRefImpl#getY <em>Y</em>}</li> * <li>{@link grl.impl.ActorRefImpl#getWidth <em>Width</em>}</li> * <li>{@link grl.impl.ActorRefImpl#getHeight <em>Height</em>}</li> * <li>{@link grl.impl.ActorRefImpl#isFixed <em>Fixed</em>}</li> * <li>{@link grl.impl.ActorRefImpl#getDiagram <em>Diagram</em>}</li> * <li>{@link grl.impl.ActorRefImpl#getContDef <em>Cont Def</em>}</li> * <li>{@link grl.impl.ActorRefImpl#getNodes <em>Nodes</em>}</li> * <li>{@link grl.impl.ActorRefImpl#getLabel <em>Label</em>}</li> * <li>{@link grl.impl.ActorRefImpl#getParent <em>Parent</em>}</li> * <li>{@link grl.impl.ActorRefImpl#getChildren <em>Children</em>}</li> * </ul> * </p> * * @generated */ public class ActorRefImpl extends GRLmodelElementImpl implements ActorRef { /** * The default value of the '{@link #getX() <em>X</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getX() * @generated * @ordered */ protected static final int X_EDEFAULT = 0; /** * The cached value of the '{@link #getX() <em>X</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getX() * @generated * @ordered */ protected int x = X_EDEFAULT; /** * The default value of the '{@link #getY() <em>Y</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getY() * @generated * @ordered */ protected static final int Y_EDEFAULT = 0; /** * The cached value of the '{@link #getY() <em>Y</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getY() * @generated * @ordered */ protected int y = Y_EDEFAULT; /** * The default value of the '{@link #getWidth() <em>Width</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getWidth() * @generated * @ordered */ protected static final int WIDTH_EDEFAULT = 0; /** * The cached value of the '{@link #getWidth() <em>Width</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getWidth() * @generated * @ordered */ protected int width = WIDTH_EDEFAULT; /** * The default value of the '{@link #getHeight() <em>Height</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getHeight() * @generated * @ordered */ protected static final int HEIGHT_EDEFAULT = 0; /** * The cached value of the '{@link #getHeight() <em>Height</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getHeight() * @generated * @ordered */ protected int height = HEIGHT_EDEFAULT; /** * The default value of the '{@link #isFixed() <em>Fixed</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #isFixed() * @generated * @ordered */ protected static final boolean FIXED_EDEFAULT = false; /** * The cached value of the '{@link #isFixed() <em>Fixed</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #isFixed() * @generated * @ordered */ protected boolean fixed = FIXED_EDEFAULT; /** * The cached value of the '{@link #getContDef() <em>Cont Def</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getContDef() * @generated * @ordered */ protected IURNContainer contDef; /** * The cached value of the '{@link #getNodes() <em>Nodes</em>}' reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getNodes() * @generated * @ordered */ protected EList<IURNNode> nodes; /** * The cached value of the '{@link #getLabel() <em>Label</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getLabel() * @generated * @ordered */ protected ComponentLabel label; /** * The cached value of the '{@link #getParent() <em>Parent</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getParent() * @generated * @ordered */ protected IURNContainerRef parent; /** * The cached value of the '{@link #getChildren() <em>Children</em>}' reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getChildren() * @generated * @ordered */ protected EList<IURNContainerRef> children; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected ActorRefImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return GrlPackage.Literals.ACTOR_REF; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public int getX() { return x; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setX(int newX) { int oldX = x; x = newX; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, GrlPackage.ACTOR_REF__X, oldX, x)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public int getY() { return y; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setY(int newY) { int oldY = y; y = newY; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, GrlPackage.ACTOR_REF__Y, oldY, y)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public int getWidth() { return width; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setWidth(int newWidth) { int oldWidth = width; width = newWidth; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, GrlPackage.ACTOR_REF__WIDTH, oldWidth, width)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public int getHeight() { return height; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setHeight(int newHeight) { int oldHeight = height; height = newHeight; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, GrlPackage.ACTOR_REF__HEIGHT, oldHeight, height)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public boolean isFixed() { return fixed; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setFixed(boolean newFixed) { boolean oldFixed = fixed; fixed = newFixed; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, GrlPackage.ACTOR_REF__FIXED, oldFixed, fixed)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public IURNDiagram getDiagram() { if (eContainerFeatureID() != GrlPackage.ACTOR_REF__DIAGRAM) return null; return (IURNDiagram)eContainer(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetDiagram(IURNDiagram newDiagram, NotificationChain msgs) { msgs = eBasicSetContainer((InternalEObject)newDiagram, GrlPackage.ACTOR_REF__DIAGRAM, msgs); return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setDiagram(IURNDiagram newDiagram) { if (newDiagram != eInternalContainer() || (eContainerFeatureID() != GrlPackage.ACTOR_REF__DIAGRAM && newDiagram != null)) { if (EcoreUtil.isAncestor(this, newDiagram)) throw new IllegalArgumentException("Recursive containment not allowed for " + toString()); NotificationChain msgs = null; if (eInternalContainer() != null) msgs = eBasicRemoveFromContainer(msgs); if (newDiagram != null) msgs = ((InternalEObject)newDiagram).eInverseAdd(this, UrncorePackage.IURN_DIAGRAM__CONT_REFS, IURNDiagram.class, msgs); msgs = basicSetDiagram(newDiagram, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, GrlPackage.ACTOR_REF__DIAGRAM, newDiagram, newDiagram)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public IURNContainer getContDef() { if (contDef != null && contDef.eIsProxy()) { InternalEObject oldContDef = (InternalEObject)contDef; contDef = (IURNContainer)eResolveProxy(oldContDef); if (contDef != oldContDef) { if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.RESOLVE, GrlPackage.ACTOR_REF__CONT_DEF, oldContDef, contDef)); } } return contDef; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public IURNContainer basicGetContDef() { return contDef; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetContDef(IURNContainer newContDef, NotificationChain msgs) { IURNContainer oldContDef = contDef; contDef = newContDef; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, GrlPackage.ACTOR_REF__CONT_DEF, oldContDef, newContDef); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setContDef(IURNContainer newContDef) { if (newContDef != contDef) { NotificationChain msgs = null; if (contDef != null) msgs = ((InternalEObject)contDef).eInverseRemove(this, UrncorePackage.IURN_CONTAINER__CONT_REFS, IURNContainer.class, msgs); if (newContDef != null) msgs = ((InternalEObject)newContDef).eInverseAdd(this, UrncorePackage.IURN_CONTAINER__CONT_REFS, IURNContainer.class, msgs); msgs = basicSetContDef(newContDef, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, GrlPackage.ACTOR_REF__CONT_DEF, newContDef, newContDef)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<IURNNode> getNodes() { if (nodes == null) { nodes = new EObjectWithInverseResolvingEList<IURNNode>(IURNNode.class, this, GrlPackage.ACTOR_REF__NODES, UrncorePackage.IURN_NODE__CONT_REF); } return nodes; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public ComponentLabel getLabel() { return label; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetLabel(ComponentLabel newLabel, NotificationChain msgs) { ComponentLabel oldLabel = label; label = newLabel; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, GrlPackage.ACTOR_REF__LABEL, oldLabel, newLabel); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setLabel(ComponentLabel newLabel) { if (newLabel != label) { NotificationChain msgs = null; if (label != null) msgs = ((InternalEObject)label).eInverseRemove(this, UrncorePackage.COMPONENT_LABEL__CONT_REF, ComponentLabel.class, msgs); if (newLabel != null) msgs = ((InternalEObject)newLabel).eInverseAdd(this, UrncorePackage.COMPONENT_LABEL__CONT_REF, ComponentLabel.class, msgs); msgs = basicSetLabel(newLabel, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, GrlPackage.ACTOR_REF__LABEL, newLabel, newLabel)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public IURNContainerRef getParent() { if (parent != null && parent.eIsProxy()) { InternalEObject oldParent = (InternalEObject)parent; parent = (IURNContainerRef)eResolveProxy(oldParent); if (parent != oldParent) { if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.RESOLVE, GrlPackage.ACTOR_REF__PARENT, oldParent, parent)); } } return parent; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public IURNContainerRef basicGetParent() { return parent; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetParent(IURNContainerRef newParent, NotificationChain msgs) { IURNContainerRef oldParent = parent; parent = newParent; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, GrlPackage.ACTOR_REF__PARENT, oldParent, newParent); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setParent(IURNContainerRef newParent) { if (newParent != parent) { NotificationChain msgs = null; if (parent != null) msgs = ((InternalEObject)parent).eInverseRemove(this, UrncorePackage.IURN_CONTAINER_REF__CHILDREN, IURNContainerRef.class, msgs); if (newParent != null) msgs = ((InternalEObject)newParent).eInverseAdd(this, UrncorePackage.IURN_CONTAINER_REF__CHILDREN, IURNContainerRef.class, msgs); msgs = basicSetParent(newParent, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, GrlPackage.ACTOR_REF__PARENT, newParent, newParent)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<IURNContainerRef> getChildren() { if (children == null) { children = new EObjectWithInverseResolvingEList<IURNContainerRef>(IURNContainerRef.class, this, GrlPackage.ACTOR_REF__CHILDREN, UrncorePackage.IURN_CONTAINER_REF__PARENT); } return children; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @SuppressWarnings("unchecked") @Override public NotificationChain eInverseAdd(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case GrlPackage.ACTOR_REF__DIAGRAM: if (eInternalContainer() != null) msgs = eBasicRemoveFromContainer(msgs); return basicSetDiagram((IURNDiagram)otherEnd, msgs); case GrlPackage.ACTOR_REF__CONT_DEF: if (contDef != null) msgs = ((InternalEObject)contDef).eInverseRemove(this, UrncorePackage.IURN_CONTAINER__CONT_REFS, IURNContainer.class, msgs); return basicSetContDef((IURNContainer)otherEnd, msgs); case GrlPackage.ACTOR_REF__NODES: return ((InternalEList<InternalEObject>)(InternalEList<?>)getNodes()).basicAdd(otherEnd, msgs); case GrlPackage.ACTOR_REF__LABEL: if (label != null) msgs = ((InternalEObject)label).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - GrlPackage.ACTOR_REF__LABEL, null, msgs); return basicSetLabel((ComponentLabel)otherEnd, msgs); case GrlPackage.ACTOR_REF__PARENT: if (parent != null) msgs = ((InternalEObject)parent).eInverseRemove(this, UrncorePackage.IURN_CONTAINER_REF__CHILDREN, IURNContainerRef.class, msgs); return basicSetParent((IURNContainerRef)otherEnd, msgs); case GrlPackage.ACTOR_REF__CHILDREN: return ((InternalEList<InternalEObject>)(InternalEList<?>)getChildren()).basicAdd(otherEnd, msgs); } return super.eInverseAdd(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case GrlPackage.ACTOR_REF__DIAGRAM: return basicSetDiagram(null, msgs); case GrlPackage.ACTOR_REF__CONT_DEF: return basicSetContDef(null, msgs); case GrlPackage.ACTOR_REF__NODES: return ((InternalEList<?>)getNodes()).basicRemove(otherEnd, msgs); case GrlPackage.ACTOR_REF__LABEL: return basicSetLabel(null, msgs); case GrlPackage.ACTOR_REF__PARENT: return basicSetParent(null, msgs); case GrlPackage.ACTOR_REF__CHILDREN: return ((InternalEList<?>)getChildren()).basicRemove(otherEnd, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eBasicRemoveFromContainerFeature(NotificationChain msgs) { switch (eContainerFeatureID()) { case GrlPackage.ACTOR_REF__DIAGRAM: return eInternalContainer().eInverseRemove(this, UrncorePackage.IURN_DIAGRAM__CONT_REFS, IURNDiagram.class, msgs); } return super.eBasicRemoveFromContainerFeature(msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case GrlPackage.ACTOR_REF__X: return getX(); case GrlPackage.ACTOR_REF__Y: return getY(); case GrlPackage.ACTOR_REF__WIDTH: return getWidth(); case GrlPackage.ACTOR_REF__HEIGHT: return getHeight(); case GrlPackage.ACTOR_REF__FIXED: return isFixed(); case GrlPackage.ACTOR_REF__DIAGRAM: return getDiagram(); case GrlPackage.ACTOR_REF__CONT_DEF: if (resolve) return getContDef(); return basicGetContDef(); case GrlPackage.ACTOR_REF__NODES: return getNodes(); case GrlPackage.ACTOR_REF__LABEL: return getLabel(); case GrlPackage.ACTOR_REF__PARENT: if (resolve) return getParent(); return basicGetParent(); case GrlPackage.ACTOR_REF__CHILDREN: return getChildren(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case GrlPackage.ACTOR_REF__X: setX((Integer)newValue); return; case GrlPackage.ACTOR_REF__Y: setY((Integer)newValue); return; case GrlPackage.ACTOR_REF__WIDTH: setWidth((Integer)newValue); return; case GrlPackage.ACTOR_REF__HEIGHT: setHeight((Integer)newValue); return; case GrlPackage.ACTOR_REF__FIXED: setFixed((Boolean)newValue); return; case GrlPackage.ACTOR_REF__DIAGRAM: setDiagram((IURNDiagram)newValue); return; case GrlPackage.ACTOR_REF__CONT_DEF: setContDef((IURNContainer)newValue); return; case GrlPackage.ACTOR_REF__NODES: getNodes().clear(); getNodes().addAll((Collection<? extends IURNNode>)newValue); return; case GrlPackage.ACTOR_REF__LABEL: setLabel((ComponentLabel)newValue); return; case GrlPackage.ACTOR_REF__PARENT: setParent((IURNContainerRef)newValue); return; case GrlPackage.ACTOR_REF__CHILDREN: getChildren().clear(); getChildren().addAll((Collection<? extends IURNContainerRef>)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case GrlPackage.ACTOR_REF__X: setX(X_EDEFAULT); return; case GrlPackage.ACTOR_REF__Y: setY(Y_EDEFAULT); return; case GrlPackage.ACTOR_REF__WIDTH: setWidth(WIDTH_EDEFAULT); return; case GrlPackage.ACTOR_REF__HEIGHT: setHeight(HEIGHT_EDEFAULT); return; case GrlPackage.ACTOR_REF__FIXED: setFixed(FIXED_EDEFAULT); return; case GrlPackage.ACTOR_REF__DIAGRAM: setDiagram((IURNDiagram)null); return; case GrlPackage.ACTOR_REF__CONT_DEF: setContDef((IURNContainer)null); return; case GrlPackage.ACTOR_REF__NODES: getNodes().clear(); return; case GrlPackage.ACTOR_REF__LABEL: setLabel((ComponentLabel)null); return; case GrlPackage.ACTOR_REF__PARENT: setParent((IURNContainerRef)null); return; case GrlPackage.ACTOR_REF__CHILDREN: getChildren().clear(); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case GrlPackage.ACTOR_REF__X: return x != X_EDEFAULT; case GrlPackage.ACTOR_REF__Y: return y != Y_EDEFAULT; case GrlPackage.ACTOR_REF__WIDTH: return width != WIDTH_EDEFAULT; case GrlPackage.ACTOR_REF__HEIGHT: return height != HEIGHT_EDEFAULT; case GrlPackage.ACTOR_REF__FIXED: return fixed != FIXED_EDEFAULT; case GrlPackage.ACTOR_REF__DIAGRAM: return getDiagram() != null; case GrlPackage.ACTOR_REF__CONT_DEF: return contDef != null; case GrlPackage.ACTOR_REF__NODES: return nodes != null && !nodes.isEmpty(); case GrlPackage.ACTOR_REF__LABEL: return label != null; case GrlPackage.ACTOR_REF__PARENT: return parent != null; case GrlPackage.ACTOR_REF__CHILDREN: return children != null && !children.isEmpty(); } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public int eBaseStructuralFeatureID(int derivedFeatureID, Class<?> baseClass) { if (baseClass == IURNContainerRef.class) { switch (derivedFeatureID) { case GrlPackage.ACTOR_REF__X: return UrncorePackage.IURN_CONTAINER_REF__X; case GrlPackage.ACTOR_REF__Y: return UrncorePackage.IURN_CONTAINER_REF__Y; case GrlPackage.ACTOR_REF__WIDTH: return UrncorePackage.IURN_CONTAINER_REF__WIDTH; case GrlPackage.ACTOR_REF__HEIGHT: return UrncorePackage.IURN_CONTAINER_REF__HEIGHT; case GrlPackage.ACTOR_REF__FIXED: return UrncorePackage.IURN_CONTAINER_REF__FIXED; case GrlPackage.ACTOR_REF__DIAGRAM: return UrncorePackage.IURN_CONTAINER_REF__DIAGRAM; case GrlPackage.ACTOR_REF__CONT_DEF: return UrncorePackage.IURN_CONTAINER_REF__CONT_DEF; case GrlPackage.ACTOR_REF__NODES: return UrncorePackage.IURN_CONTAINER_REF__NODES; case GrlPackage.ACTOR_REF__LABEL: return UrncorePackage.IURN_CONTAINER_REF__LABEL; case GrlPackage.ACTOR_REF__PARENT: return UrncorePackage.IURN_CONTAINER_REF__PARENT; case GrlPackage.ACTOR_REF__CHILDREN: return UrncorePackage.IURN_CONTAINER_REF__CHILDREN; default: return -1; } } return super.eBaseStructuralFeatureID(derivedFeatureID, baseClass); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public int eDerivedStructuralFeatureID(int baseFeatureID, Class<?> baseClass) { if (baseClass == IURNContainerRef.class) { switch (baseFeatureID) { case UrncorePackage.IURN_CONTAINER_REF__X: return GrlPackage.ACTOR_REF__X; case UrncorePackage.IURN_CONTAINER_REF__Y: return GrlPackage.ACTOR_REF__Y; case UrncorePackage.IURN_CONTAINER_REF__WIDTH: return GrlPackage.ACTOR_REF__WIDTH; case UrncorePackage.IURN_CONTAINER_REF__HEIGHT: return GrlPackage.ACTOR_REF__HEIGHT; case UrncorePackage.IURN_CONTAINER_REF__FIXED: return GrlPackage.ACTOR_REF__FIXED; case UrncorePackage.IURN_CONTAINER_REF__DIAGRAM: return GrlPackage.ACTOR_REF__DIAGRAM; case UrncorePackage.IURN_CONTAINER_REF__CONT_DEF: return GrlPackage.ACTOR_REF__CONT_DEF; case UrncorePackage.IURN_CONTAINER_REF__NODES: return GrlPackage.ACTOR_REF__NODES; case UrncorePackage.IURN_CONTAINER_REF__LABEL: return GrlPackage.ACTOR_REF__LABEL; case UrncorePackage.IURN_CONTAINER_REF__PARENT: return GrlPackage.ACTOR_REF__PARENT; case UrncorePackage.IURN_CONTAINER_REF__CHILDREN: return GrlPackage.ACTOR_REF__CHILDREN; default: return -1; } } return super.eDerivedStructuralFeatureID(baseFeatureID, baseClass); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (x: "); result.append(x); result.append(", y: "); result.append(y); result.append(", width: "); result.append(width); result.append(", height: "); result.append(height); result.append(", fixed: "); result.append(fixed); result.append(')'); return result.toString(); } } //ActorRefImpl
true
c113bec045b3b287f5c9cc3316779b4bd03bd2fa
Java
pablolfbs/javaWeb
/Teste/src/com/pablo/teste/Teste10.java
UTF-8
374
2.6875
3
[]
no_license
package com.pablo.teste; import java.util.Arrays; import java.util.List; public class Teste10 { public static void main(String[] args) { List<String> asList = Arrays.asList("Pablo", "Ingrid", "Alice"); System.out.println(asList.toString().substring(1, asList.toString().length() - 1)); String data = "202104"; System.out.println(data.substring(4)); } }
true
0d80e2e519a9522efcec536d1409c5aa780b780f
Java
shraddhabagoji0/sample
/src/javamockpractice/Demo3.java
UTF-8
408
3.328125
3
[]
no_license
package javamockpractice; public class Demo3 { public static void primeNo(int n) { boolean flag=true; for(int i=2;i<n;i++) { if(n%i==0) { flag=false; break; } } if(flag==true) { System.out.println("it is a prime number"); }else { System.out.println("it is not a prime number"); } } public static void main(String[] args) { primeNo(13); } }
true
0fbe9af68d4e4f4656315d7491f44633fd8eb1a5
Java
lruklic/codex-school-quiz-app
/app/controllers/ProfileController.java
UTF-8
702
2.046875
2
[]
no_license
package controllers; import models.User; import be.objectify.deadbolt.java.actions.SubjectPresent; import com.google.inject.Inject; import play.db.jpa.Transactional; import play.mvc.Controller; import play.mvc.Result; import services.model.UserService; import session.Session; import views.html.profile.profile; /** * Controller that handles user profile page. * * @author Luka Ruklic * */ @Transactional public class ProfileController extends Controller { @Inject public static UserService userService; @SubjectPresent public static Result profileHome() { User currentUser = userService.findByUsernameOrEmail(Session.getUsername()); return ok(profile.render(currentUser)); } }
true
7621c23058f3083280622a9dabf506e508fef548
Java
azureblue/lichess-bot
/src/kk/lichess/LichessBot.java
UTF-8
5,417
2.3125
2
[]
no_license
package kk.lichess; import com.fasterxml.jackson.databind.JsonNode; import kk.lichess.bots.api.ChessPlayer; import kk.lichess.net.LichessHTTP; import kk.lichess.net.LichessHTTPException; import kk.lichess.net.LichessStream; import kk.lichess.net.pojo.Challenge; import java.io.IOException; import java.lang.invoke.VarHandle; import java.util.Optional; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Consumer; import java.util.function.Predicate; import java.util.function.Supplier; public class LichessBot { private final String botId; private final Supplier<ChessPlayer> chessPlayerSupplier; private final Predicate<GameRequest> acceptGamePredicate; private final LichessHTTP lichessHTTP; private LichessGames lichessGames; private LichessStream eventStream; private AtomicBoolean run = new AtomicBoolean(true); private boolean started = false; public LichessBot(String botId, String authToken, Supplier<ChessPlayer> chessPlayerSupplier, Predicate<GameRequest> acceptGamePredicate) { this.botId = botId; this.chessPlayerSupplier = chessPlayerSupplier; this.acceptGamePredicate = acceptGamePredicate; this.lichessHTTP = new LichessHTTP(authToken); } private void init() { JsonNode user = lichessHTTP.get("https://lichess.org/api/account").toJson(); if (user.has("error")) throw new IllegalStateException("error: " + user.get("error")); } private GameRequest gameRequestFromChallenge(Challenge challenge) { GameRequest.Side side; if (challenge.getColor().equals("white")) side = GameRequest.Side.White; else if (challenge.getColor().equals("black")) side = GameRequest.Side.Black; else if (challenge.getColor().equals("random")) side = GameRequest.Side.Random; else throw new IllegalArgumentException("invalid side: " + challenge.getColor()); return new GameRequest( challenge.getChallenger().getId(), challenge.getChallenger().getRating(), Optional.ofNullable(challenge.getTimeControl().getLimit()).orElse(Integer.MAX_VALUE), Optional.ofNullable(challenge.getTimeControl().getIncrement()).orElse(0), side, challenge.isRated() ); } public void start() { if (started) throw new IllegalStateException("lichess bot instance can by started only once"); started = true; new Thread(() -> { init(); lichessGames = new LichessGames(lichessHTTP, botId, this.chessPlayerSupplier); Consumer<Challenge> challengeHandler = challenge -> { Log.v("handling challenge: " + challenge.getId()); GameRequest gameRequest = gameRequestFromChallenge(challenge); boolean challengeAccepted = this.acceptGamePredicate.and(ignore -> lichessGames.size() < 4).test(gameRequest) && (challenge.getVariant().getKey().equals("standard") || challenge.getVariant().getShortName().equals("FEN")); String challengeAcceptString = challengeAccepted ? "accept" : "decline"; Log.d("challenge from " + challenge.getChallenger().getId() + ": sending " + challengeAcceptString); LichessHTTP.LichessResponse response = lichessHTTP.post("https://lichess.org/api/challenge/" + challenge.getId() + "/" + challengeAcceptString); if (response.getStatusCode() != 200) { Log.e("lichess error: error while answering challenge: " + response.getContent()); } Log.d("challenge from " + challenge.getChallenger().getId() + ": sent " + challengeAcceptString); }; Consumer<String> gameStartHandler = game -> { Log.i("starting game: " + game); lichessGames.startGame(game); }; try { while (run.get()) { eventStream = lichessHTTP.eventStream( (stre, result) -> Log.i("event stream ended: " + result.getResultStatus()), challengeHandler, gameStartHandler); try { Log.i("opening event stream"); eventStream.start(); eventStream.sync(); } catch (IOException | LichessHTTPException e) { Log.e("event stream error", e); } catch (InterruptedException e) { Log.d("lichess event thread interrupted"); eventStream.stop(); break; } if (run.get()) Thread.sleep(5000); } } catch (InterruptedException e) { Log.d("lichess thread interrupted"); } }).start(); } public void restartEventStream() { eventStream.stop(); } public void stop() { run.set(false); eventStream.stop(); } public void stopGames() { lichessGames.stopAll(); } public int getNumberOfGamesInProgress() { return lichessGames.size(); } }
true
c1c68bb5146e75b362a16840b12352c3870ef8c0
Java
ppqqhhjj/Skyproc-Libaray
/MyPatcher/src/com/mypatcher/action/RemoveFantasticItemsAction.java
UTF-8
2,570
2.328125
2
[]
no_license
package com.mypatcher.action; import java.util.ArrayList; import java.util.List; import skyproc.ARMO; import skyproc.FormID; import skyproc.GRUP; import skyproc.GRUP_TYPE; import skyproc.KYWD; import skyproc.KeywordSet; import skyproc.LVLI; import skyproc.LeveledEntry; import skyproc.MajorRecord; import skyproc.Record; import skyproc.WEAP; import com.mypatcher.Context; import com.mypatcher.utility.Log; public class RemoveFantasticItemsAction extends Action { public RemoveFantasticItemsAction(Context context) { super(context); } @Override public void doAction() { this.remove(); } public void remove() { List<FormID> needRemoveItems = this.getNeedRemoveItems(); GRUP<LVLI> leveledItems = this.merger.getLeveledItems(); for (LVLI lItems : leveledItems) { for (FormID item : needRemoveItems) { if (lItems.getEntryForms().contains(item)) { Log.console("processing Leveled item: " + lItems.getEDID()); lItems.removeAllEntries(item); this.patch.addRecord(lItems); Log.console("remove item: " + item); } } } } private List<FormID> getNeedRemoveMeterial() { List<FormID> meterialformIDs = new ArrayList<>(); List<String> meterialList = new ArrayList<>(); meterialList.add("ArmorMaterialGlass"); meterialList.add("ArmorMaterialDwarven"); meterialList.add("ArmorMaterialEbony"); meterialList.add("ArmorMaterialOrcish"); for (String meterial : meterialList) { MajorRecord record = this.merger.getMajor(meterial, GRUP_TYPE.KYWD); meterialformIDs.add(record.getForm()); } return meterialformIDs; } private List<FormID> getNeedRemoveItems() { List<FormID> needRemoveItems = new ArrayList<>(); List<FormID> meterialformIDs = this.getNeedRemoveMeterial(); GRUP<ARMO> armors = this.merger.getArmors(); for (ARMO armor : armors.getRecords()) { for (FormID key : armor.getKeywordSet().getKeywordRefs()) { if (meterialformIDs.contains(key)) { needRemoveItems.add(armor.getForm()); Log.console("need remove item: " + armor.getForm() + ": " + armor.getName()); } } } GRUP<WEAP> weapons = this.merger.getWeapons(); for (WEAP weapon : weapons.getRecords()) { for (FormID key : weapon.getKeywordSet().getKeywordRefs()) { if (meterialformIDs.contains(key)) { needRemoveItems.add(weapon.getForm()); Log.console("need remove item: " + weapon.getForm() + ": " + weapon.getName()); } } } return needRemoveItems; } }
true
5b1a1ede2247925a7e61c81e78dcd4b82ad127c4
Java
tahaShaheen/tdf02-145_remote_sharable
/app/src/main/java/com/example/choturemote/ui/main/SpeakingFragment.java
UTF-8
9,246
2.65625
3
[ "MIT" ]
permissive
package com.example.choturemote.ui.main; import android.os.Bundle; import android.support.annotation.MainThread; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.EditText; import android.widget.GridView; import android.widget.ImageButton; import android.widget.SeekBar; import android.widget.TextView; import android.widget.Toast; import com.example.choturemote.MainActivity; import com.example.choturemote.R; import java.util.ArrayList; /** * @file SpeakingFragment.java * @brief Extends Fragment * @details * @li A Fragment is a piece of an application's user interface or behavior that can be placed in an Activity. * @li This one deals with the Speaking aspect */ /** * @brief Speaking Fragment * @details * @li A Fragment is a piece of an application's user interface or behavior that can be placed in an Activity. * @li This one deals with the Speaking aspect */ public class SpeakingFragment extends Fragment { /** * @var PITCH_FACTOR * @brief Fixed value * @details Dividing the actual pitch value * * @var DEFAULT_PITCH * @brief Default Pitch * @details Default Pitch as a float * * @var myPitch * @brief Float to hold current pitch * @details Holds the current pitch so tp display in the slider * * @var defaultPercentage * @brief Pitch is displayed as a percentage * @details DEFAULT_PITCH/PITCH_FACTOR is how the default pitch percentage is calculated * */ private static float PITCH_FACTOR = 0.025f; private static float DEFAULT_PITCH = 1.0f; //is actually 0.01 * 100% // private static float myPitch; int defaultPercentage; /** * @brief Constructor * @details Required empty public constructor */ public SpeakingFragment() { } /** * @brief Called to have the fragment instantiate its user interface view * @details * @li This fragment has a View inflated from the speaking_view.xml file * @li This View has a GridView with the resourceID "grid"; an EditText; a few buttons; a TextView for percentage display; and a seekBar * @li This GridView is associated with an Adapter which is an ExpressionsWordAdapter object * @li The ExpressionsWordAdapter object returns custom itemView object to populate the GridView * @li The EditView works with the speakNowButton to send custom text to be spoken * @li The SeekBar works with two buttons to handle pitch settings * @param inflater The LayoutInflater object that can be used to inflate any views in the fragment * @param container This is the parent view that the fragment's UI should be attached to * @param savedInstanceState If non-null, this fragment is being re-constructed from a previous saved state as given here * @return The View for the fragment's UI, or null. */ @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflating speaking_view.xml (modified grid_view.xml) // View rootView = inflater.inflate(R.layout.speaking_view, container, false); // Entering custom text for speaking option // final EditText editText = rootView.findViewById(R.id.editText); ImageButton speakNowButton = rootView.findViewById(R.id.speak_now); // A SeekBar for changing pitch// final SeekBar pitchBar = rootView.findViewById(R.id.pitch_bar); final TextView pitchPercentage = rootView.findViewById(R.id.pitch_percentage); // Resetting and saving pitch settings // ImageButton resetPitch = rootView.findViewById(R.id.reset_pitch); ImageButton setDefaultPitch = rootView.findViewById(R.id.set_default_pitch); // A list of Word objects // final ArrayList<Word> words = new ArrayList<Word>(); words.add(new Word(R.string.HI, R.drawable.speech_bubble)); words.add(new Word(R.string.HELLO, R.drawable.speech_bubble)); words.add(new Word(R.string.HOW_ARE_YOU, R.drawable.speech_bubble)); words.add(new Word(R.string.WHATS_YOUR_NAME, R.drawable.speech_bubble)); words.add(new Word(R.string.MY_NAME_IS, R.drawable.speech_bubble)); words.add(new Word(R.string.IM_YOUR_FRIEND, R.drawable.speech_bubble)); words.add(new Word(R.string.THANK_YOU,R.drawable.speech_bubble)); words.add(new Word(R.string.YOU_ARE_WELCOME,R.drawable.speech_bubble)); words.add(new Word(R.string.GOOD_JOB,R.drawable.speech_bubble)); words.add(new Word(R.string.VERY_GOOD,R.drawable.speech_bubble)); words.add(new Word(R.string.WOW,R.drawable.speech_bubble)); words.add(new Word(R.string.BYE, R.drawable.speech_bubble)); words.add(new Word(R.string.FINISH,R.drawable.speech_bubble)); words.add(new Word(R.string.YES, R.drawable.speech_bubble)); words.add(new Word(R.string.NO, R.drawable.speech_bubble)); // Command String variables and calculations for expressions // myPitch = DEFAULT_PITCH; defaultPercentage = (int) (DEFAULT_PITCH/PITCH_FACTOR); pitchBar.setProgress(defaultPercentage); pitchPercentage.setText(getString(R.string.PITCH_SLIDER_INFO) + ": " + defaultPercentage + "%"); final String SPEAK_OUT_CLASSIFIER = getString(R.string.SPEAK_OUT_CLASSIFIER); // An ExpressionsWordAdapter whose data source is a list of Words // // The adapter knows how to create custom itemViews for each item in the list // ExpressionsWordAdapter adapter = new ExpressionsWordAdapter(getActivity(), words, R.color.category_expressions); // Find the GridView view hierarchy of the Activity with the ID "grid" // GridView gridView = rootView.findViewById(R.id.grid); // Number of columns in the gridView // gridView.setNumColumns(1); // Make gridView use the SpeakingWordAdapter object we created above, so that the gridView will display items for each Word in the list. gridView.setAdapter(adapter); // Set a click listener to send command String when the list item is clicked // gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) { Word word = words.get(position); MainActivity.writeToBluetooth(SPEAK_OUT_CLASSIFIER, getString(word.getStringResourceId()), String.valueOf(myPitch)); } }); // Set a click listener to send command String when the speakNowButton is clicked // speakNowButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { MainActivity.writeToBluetooth(SPEAK_OUT_CLASSIFIER, editText.getText().toString(), String.valueOf(myPitch)); //editText.getText().clear(); } }); // Set a click listener to reset pitch // resetPitch.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { pitchBar.setProgress(defaultPercentage); Toast.makeText(getContext(), "Pitch reset",Toast.LENGTH_SHORT).show(); } }); // Set a long click listener to reset pitch to default if updated // resetPitch.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View view) { defaultPercentage = (int) (DEFAULT_PITCH/PITCH_FACTOR); pitchBar.setProgress(defaultPercentage); Toast.makeText(getContext(), "Default pitch set to "+ defaultPercentage + "%",Toast.LENGTH_SHORT).show(); return true; } }); // Set a long click listener to update default pitch // setDefaultPitch.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View view) { defaultPercentage = pitchBar.getProgress(); Toast.makeText(getContext(), "Default pitch set to "+ defaultPercentage + "%", Toast.LENGTH_SHORT).show(); return true; } }); // Set a listener to update when seekBar updated by user// pitchBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { if (progress == 0) progress = 1; myPitch = progress * PITCH_FACTOR; pitchPercentage.setText(getString(R.string.PITCH_SLIDER_INFO) + ": " + progress + "%"); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); return rootView; } }
true
be843a205f6a27af742a06f7445fb2ce8279863a
Java
plipka7/MessageAppServer
/src/main/java/hello/UserRepository.java
UTF-8
569
2.1875
2
[]
no_license
package hello; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import hello.User; // This will be AUTO IMPLEMENTED by Spring into a Bean called userRepository // CRUD refers Create, Read, Update, Delete public interface UserRepository extends JpaRepository<User, String> { @Query("select u.username from User u where u.username != :username") public List<String> getOtherUsers(@Param("username") String username); }
true
36e020f8b608c69ea9f9bde0f58aa1db823a0407
Java
sai486/MusicAlbum
/src/com/model/MusicMaster.java
UTF-8
1,224
2.484375
2
[]
no_license
package com.model; public class MusicMaster { private int music_id; private int album_id; private int title_id; private int artist_id; private int genre_id; public int getMusic_id() { return music_id; } public void setMusic_id(int music_id) { this.music_id = music_id; } public int getAlbum_id() { return album_id; } public void setAlbum_id(int album_id) { this.album_id = album_id; } public int getTitle_id() { return title_id; } public void setTitle_id(int title_id) { this.title_id = title_id; } public int getArtist_id() { return artist_id; } public void setArtist_id(int artist_id) { this.artist_id = artist_id; } public int getGenre_id() { return genre_id; } public void setGenre_id(int genre_id) { this.genre_id = genre_id; } public MusicMaster(int music_id, int album_id, int title_id, int artist_id, int genre_id) { super(); this.music_id = music_id; this.album_id = album_id; this.title_id = title_id; this.artist_id = artist_id; this.genre_id = genre_id; } @Override public String toString() { return "MusicMaster [music_id=" + music_id + ", album_id=" + album_id + ", title_id=" + title_id + ", artist_id=" + artist_id + ", genre_id=" + genre_id + "]"; } public MusicMaster(){ } }
true
e4e0aacc4d6fab67ba0760c07b98d0a8556bf0e0
Java
TheDarkTrumpet/WifiRoomIdentification
/src/com/TDT/room_identification/RangeStruct.java
UTF-8
2,962
2.609375
3
[]
no_license
package com.TDT.room_identification; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import android.content.Context; import android.os.Environment; import android.util.Log; import au.com.bytecode.opencsv.*; public class RangeStruct { Map<String, Object> ranges = new HashMap<String, Object>(); private Context context; private void addToHash(String room, String wifi, int low, int high) { if(!ranges.containsKey(room)) { ranges.put(room, new HashMap<Object, Object>()); } HashMap<String, int[]> hashMap = (HashMap<String, int[]>) ranges.get(room); HashMap<String, int[]> room_struct = hashMap; int[] ranges = {low,high}; room_struct.put(wifi, ranges); } private int countOverlapsInRoom(ArrayList<String[]> cur_strength, HashMap signal_strengths) { int overlaps = 0; for(String[] i : cur_strength) { String our_mac_address = i[0]; int strength = Math.abs(Integer.valueOf(i[1])); Iterator wifi_iterator = signal_strengths.entrySet().iterator(); while(wifi_iterator.hasNext()) { Map.Entry pairs = (Map.Entry)wifi_iterator.next(); String mac_addr = pairs.getKey().toString(); int[] levels = (int[]) pairs.getValue(); if(mac_addr.equals(our_mac_address) && strength >= levels[0] && strength <= levels[1]) overlaps++; } } return overlaps; } public String classifyLocation(ArrayList<String[]> cur_values) { Iterator room_iterator = ranges.entrySet().iterator(); String max_room = "Unknown"; int highest_overlaps = 0; while (room_iterator.hasNext()) { Map.Entry pairs = (Map.Entry)room_iterator.next(); String room = pairs.getKey().toString(); int num_in_bucket = 0; HashMap wifi_map = (HashMap) pairs.getValue(); num_in_bucket = countOverlapsInRoom(cur_values, wifi_map); if(num_in_bucket > highest_overlaps) { max_room = room; highest_overlaps = num_in_bucket; } } return max_room; } public boolean loadFile () { CSVReader reader; String Room; // index 0 String wifi; // index 1 int low, high; // index 2,3 ranges.clear(); try { reader = new CSVReader(new FileReader(Environment.getExternalStorageDirectory().toString() + File.separator + "ranges.csv"), ','); String [] nextLine; while ((nextLine = reader.readNext()) != null) { Room = nextLine[0]; wifi = nextLine[1]; low = Integer.valueOf(nextLine[2]); high = Integer.valueOf(nextLine[3]); addToHash(Room,wifi,low,high); } reader.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return true; } }
true
151800ec9ec24b17120125e03dad284a555df3a2
Java
alexmoitta/showphotos
/app/src/main/java/com/yourdomain/showphotos/ImageDownloader.java
UTF-8
1,468
2.28125
2
[]
no_license
package com.yourdomain.showphotos; import android.annotation.SuppressLint; import android.os.Handler; import android.os.HandlerThread; import android.os.Message; import android.util.Log; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; //import android.graphics.Bitmap; //import android.graphics.BitmapFactory; /** * Created by asantos on 01/08/15. */ public class ImageDownloader<Token> extends HandlerThread { private static final String TAG = "ImageDownloader"; private static final int MESSAGE_DOWNLOAD = 0; Handler handler; private ConcurrentMap<Token,String> requestMap = new ConcurrentHashMap<>(); public ImageDownloader() { super(TAG); } @SuppressLint("HandlerLeak") @Override protected void onLooperPrepared() { handler = new Handler() { @Override public void handleMessage(Message msg) { if (msg.what == MESSAGE_DOWNLOAD) { @SuppressWarnings("unchecked") Token token = (Token) msg.obj; Log.i(TAG, "Got a request for url: " + requestMap.get(token)); //handleRequest(token); //falta fazer isso - seguir exemplo da página 444 } } }; } public void queueImage(Token token, String url) { Log.i(TAG, "URL:" + url); } }
true
82729902ac922784d4b12bc7a445bc99f671ad3f
Java
Elia-Y/cs349-User-Interface
/a4/app/src/main/java/ca/uwaterloo/cs349/a4/MainActivity.java
UTF-8
1,734
2.359375
2
[]
no_license
package ca.uwaterloo.cs349.a4; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.view.View; import android.widget.Button; import android.widget.EditText; public class MainActivity extends AppCompatActivity { private Button next; private EditText inputText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); inputText = (EditText)findViewById(R.id.inputName); next = (Button) findViewById(R.id.go_next); inputText.addTextChangedListener(new TextWatcher() { @Override public void afterTextChanged(Editable s) {} @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if (count == 0) { next.setEnabled(false); } else { next.setEnabled(true); } } }); next.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String userName = inputText.getText().toString(); userModel.setName(userName); Intent intent = new Intent(MainActivity.this, TopicSelectionActivity.class); startActivity(intent); } }); } }
true
a964e95d4bd1b09ab3af9990b49d1f16dabaaecc
Java
vatsank/JavaDesignPatterns
/BehaviouralPatterns/src/com/training/command/MyCommand.java
UTF-8
131
1.945313
2
[]
no_license
package com.training.command; /* the command interface */ public interface MyCommand { public void execute(); }
true
886adf2e6d11dcaa8087c91e6c05ad243b24cca6
Java
ciec20151104703/NetWork_Graduation2015_Real
/20151104703_liuyan/20151104703_liuyan_FEPFUS/src/com/imnu/po/Infm.java
UTF-8
1,131
2
2
[]
no_license
package com.imnu.po; public class Infm { private Integer u_id; private String u_name; private String u_email; private String u_phone; private String p_img; private String p_dirpath; private String u_message; public Integer getU_id() { return u_id; } public void setU_id(Integer u_id) { this.u_id = u_id; } public String getU_name() { return u_name; } public void setU_name(String u_name) { this.u_name = u_name; } public String getU_email() { return u_email; } public void setU_email(String u_email) { this.u_email = u_email; } public String getU_phone() { return u_phone; } public void setU_phone(String u_phone) { this.u_phone = u_phone; } public String getP_img() { return p_img; } public void setP_img(String p_img) { this.p_img = p_img; } public String getP_dirpath() { return p_dirpath; } public void setP_dirpath(String p_dirpath) { this.p_dirpath = p_dirpath; } public String getU_message() { return u_message; } public void setU_message(String u_message) { this.u_message = u_message; } }
true
fa81d9ae6c675b4dee5577b39bd435bb82e661c1
Java
NucleusPowered/Nucleus
/nucleus-modules/src/main/java/io/github/nucleuspowered/nucleus/modules/world/config/WorldConfig.java
UTF-8
1,405
2.015625
2
[ "Apache-2.0", "MIT" ]
permissive
/* * This file is part of Nucleus, licensed under the MIT License (MIT). See the LICENSE.txt file * at the root of this project for more details. */ package io.github.nucleuspowered.nucleus.modules.world.config; import io.github.nucleuspowered.nucleus.core.services.interfaces.annotation.configuratehelper.LocalisedComment; import org.spongepowered.configurate.objectmapping.ConfigSerializable; import org.spongepowered.configurate.objectmapping.meta.Setting; import java.util.Optional; @ConfigSerializable public class WorldConfig { @Setting(value = "default-world-border-diameter") @LocalisedComment("config.world.defaultborder") private long worldBorderDefault = 0; @Setting(value = "separate-permissions") @LocalisedComment("config.worlds.separate") private boolean separatePermissions = false; @Setting(value = "enforce-gamemode-on-world-change") @LocalisedComment("config.worlds.gamemode") private boolean enforceGamemodeOnWorldChange = false; public boolean isEnforceGamemodeOnWorldChange() { return this.enforceGamemodeOnWorldChange; } public Optional<Long> getWorldBorderDefault() { if (this.worldBorderDefault < 1) { return Optional.empty(); } return Optional.of(this.worldBorderDefault); } public boolean isSeparatePermissions() { return this.separatePermissions; } }
true
cfd53131c1ac65099673737b16f898f7d02e72d5
Java
15271091213/aliyun-openapi-java-sdk
/aliyun-java-sdk-domain/src/main/java/com/aliyuncs/domain/transform/v20180208/QueryAuctionDetailResponseUnmarshaller.java
UTF-8
3,693
1.648438
2
[ "Apache-2.0" ]
permissive
/* * 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. */ package com.aliyuncs.domain.transform.v20180208; import com.aliyuncs.domain.model.v20180208.QueryAuctionDetailResponse; import com.aliyuncs.transform.UnmarshallerContext; public class QueryAuctionDetailResponseUnmarshaller { public static QueryAuctionDetailResponse unmarshall(QueryAuctionDetailResponse queryAuctionDetailResponse, UnmarshallerContext context) { queryAuctionDetailResponse.setRequestId(context.stringValue("QueryAuctionDetailResponse.RequestId")); queryAuctionDetailResponse.setDomainName(context.stringValue("QueryAuctionDetailResponse.DomainName")); queryAuctionDetailResponse.setAuctionId(context.stringValue("QueryAuctionDetailResponse.AuctionId")); queryAuctionDetailResponse.setDomainType(context.stringValue("QueryAuctionDetailResponse.DomainType")); queryAuctionDetailResponse.setBookedPartner(context.stringValue("QueryAuctionDetailResponse.BookedPartner")); queryAuctionDetailResponse.setPartnerType(context.stringValue("QueryAuctionDetailResponse.PartnerType")); queryAuctionDetailResponse.setCurrency(context.stringValue("QueryAuctionDetailResponse.Currency")); queryAuctionDetailResponse.setYourCurrentBid(context.floatValue("QueryAuctionDetailResponse.YourCurrentBid")); queryAuctionDetailResponse.setYourMaxBid(context.floatValue("QueryAuctionDetailResponse.YourMaxBid")); queryAuctionDetailResponse.setHighBid(context.floatValue("QueryAuctionDetailResponse.HighBid")); queryAuctionDetailResponse.setNextValidBid(context.floatValue("QueryAuctionDetailResponse.NextValidBid")); queryAuctionDetailResponse.setReserveMet(context.booleanValue("QueryAuctionDetailResponse.ReserveMet")); queryAuctionDetailResponse.setTransferInPrice(context.floatValue("QueryAuctionDetailResponse.TransferInPrice")); queryAuctionDetailResponse.setPayPrice(context.floatValue("QueryAuctionDetailResponse.PayPrice")); queryAuctionDetailResponse.setHighBidder(context.stringValue("QueryAuctionDetailResponse.HighBidder")); queryAuctionDetailResponse.setStatus(context.stringValue("QueryAuctionDetailResponse.Status")); queryAuctionDetailResponse.setPayStatus(context.stringValue("QueryAuctionDetailResponse.PayStatus")); queryAuctionDetailResponse.setProduceStatus(context.stringValue("QueryAuctionDetailResponse.ProduceStatus")); queryAuctionDetailResponse.setAuctionEndTime(context.longValue("QueryAuctionDetailResponse.AuctionEndTime")); queryAuctionDetailResponse.setBookEndTime(context.longValue("QueryAuctionDetailResponse.BookEndTime")); queryAuctionDetailResponse.setPayEndTime(context.longValue("QueryAuctionDetailResponse.PayEndTime")); queryAuctionDetailResponse.setDeliveryTime(context.longValue("QueryAuctionDetailResponse.DeliveryTime")); queryAuctionDetailResponse.setFailCode(context.stringValue("QueryAuctionDetailResponse.FailCode")); return queryAuctionDetailResponse; } }
true
f6013bb80cd1c29c27a9cd67a7007ed91be7cac9
Java
nursa-reactome/gsea-desktop
/src/edu/mit/broad/genome/objects/TemplateImpl.java
UTF-8
23,094
2.53125
3
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
/******************************************************************************* * Copyright (c) 2003-2016 Broad Institute, Inc., Massachusetts Institute of Technology, and Regents of the University of California. All rights reserved. *******************************************************************************/ package edu.mit.broad.genome.objects; import edu.mit.broad.genome.Printf; import edu.mit.broad.genome.utils.ColorUtils; import edu.mit.broad.genome.utils.ImmutedException; import gnu.trove.TIntObjectHashMap; import java.awt.*; import java.util.*; import java.util.List; import org.apache.commons.lang3.StringUtils; /** * IMP IMP: algorithms etc should not rely on the aux business - they should simpley work on the * specified template * <p/> * A Template Object. * <p/> * A Template is made up of a collection of TemplateItem's. * A TemplateItem can belong to one or more Template.Class, * but must belong to at least one Template.Class. * <p/> * <bold> Implementation Notes </bold><br> * Different from genecluster Template - The class labels in this template can * be accessed through <code>getClass(i).getName()</code> rather than directly * through this class. * * @author Michael Angelo * @author Aravind Subramanian (extensively re-engineered) * @version %I%, %G% */ public class TemplateImpl extends AbstractTemplate { /** * IMP IMP IMP IMP * <p/> * If adding any class vars make sure to check clone/factory methods here and in * TemplateFactory * <p/> * Elements are Template.Class objects - the classes that TemplateItems belong to * <p/> * <p/> * Elements are Template.Class objects - the classes that TemplateItems belong to */ /** * Elements are Template.Class objects - the classes that TemplateItems belong to */ private ArrayList fClasses; /** * Elements are Template.Item objects -> List of TemplateItems */ private ArrayList fItems; /** * Flag for whether this Template is continuous or not */ private boolean fContinuous; /** * Flag for whether this Template can be changed or not */ private boolean fImmutable = false; /* By Default the Class of interest is the first one */ private int fCoi = 0; private boolean fAux; /** * Class Constructor. * Creates a new Template. */ protected TemplateImpl(final String name) { super(name); fClasses = new ArrayList(); fItems = new ArrayList(); } /** * Dummy constructor. Subclasses must take care to fill as needed */ protected TemplateImpl() { } protected Template.Item _getItemAsIs(final int itemIndex) { return (Template.Item) fItems.get(itemIndex); } protected Template.Item[] _getItems() { return (Item[]) fItems.toArray(new Item[fItems.size()]); } /** * Label of the class at specified location */ public String getClassName(final int i) { return ((Template.Class) fClasses.get(i)).getName(); } /** * @return * @maint Might need updating if class vars are added * deep clones this Template */ public Template cloneDeep(final String newName) { final TemplateImpl newt = new TemplateImpl(newName); newt.fImmutable = false; // IMP notice - we do this as often the cloned template is used in a diff way newt.fContinuous = this.fContinuous; for (int i = 0; i < this.getNumClasses(); i++) { Class cl = this.getClass(i); ClassImpl newcl = new ClassImpl(cl.getName()); newt.add(newcl); for (int j = 0; j < cl.getSize(); j++) { Item newitem = cl.getItem(j).cloneDeep(); newcl.add(newitem); newt.add(newitem); } } newt.fCoi = this.fCoi; return newt; } /** * coi -> the class we are interested in finding markers for * * @return */ public int getClassOfInterestIndex() { return fCoi; } public boolean isContinuous() { return fContinuous; } public boolean isCategorical() { return !fContinuous; } public Template.Class getClass(final int classIndex) { return (Template.Class) fClasses.get(classIndex); } public boolean isMemberClass(final Template.Class cl) { int index = fClasses.indexOf(cl); return index != -1; } public int getClassIndex(final Template.Class cl) { return fClasses.indexOf(cl); } public int getNumItems() { return fItems.size(); } public int getNumClasses() { return fClasses.size(); } protected void setAux(final boolean aux) { // sanity checks if (aux) { if (!StringUtils.contains(getName(), "#")) { throw new IllegalStateException("Cannot make aux as the name has no # in it. Name: " + getName()); } } else { if (StringUtils.contains(getName(), "#")) { throw new IllegalStateException("Non-aux template cannot have # in its name. Name: " + getName()); } } this.fAux = aux; } public boolean isAux() { if (getName().indexOf('#') != -1) { return true; } return fAux; } // imp that it is protected (but cant as in interface - @todo improve) public void setClassOfInterestIndex(final int coi) { checkImmutable(); this.fCoi = coi; } public String getClassOfInterestName() { return getClass(fCoi).getName(); } /** * Add specified Class to this Template. * Class names must be unique */ protected void add(final Class cl) { if (cl == null) { throw new IllegalArgumentException("Param cl cannot be null"); } checkImmutable(); // unique class name check for (int i = 0; i < getNumClasses(); i++) { if (getClass(i).getName().equals(cl.getName())) { throw new IllegalArgumentException("Class with this name already exists: " + cl.getName() + " . The Classes in a Template must be unique"); } } fClasses.add(cl); } /** * Add specified Template.Item to this Template */ protected void add(final Template.Item aItem) { if (aItem == null) { throw new IllegalArgumentException("Param aItem cannot be null"); } checkImmutable(); if (isContinuous()) { try { Float.parseFloat(aItem.getId()); } catch (NumberFormatException e) { throw new NumberFormatException("Template is numeric but Template.Item asked to be added was not Float-parsable " + e.toString()); } } fItems.add(aItem); } /** * Only valid if there is a collection of Template.Class's associated with this Template. * <p/> * The method cycles (in order of addition) through all its member TemplateItems. * In the first progress run, a list of unique TemplateItem Id's. * is generated. The size of this list must correspond to the * size of the Template.Class collection. * <p/> * Each Id is then assigned to one Template.Class (again, in order). * <p/> * The member TemplateItems are then again cycled through, and assigned to * a Template.Class (based on the Id - Template.Class map produced in the previous run). * <p/> * Thus, the result, is that each Template.Class is now associated with a collection of TemplateItem's. * <p/> * The Template.Class does NOT have to be the same as the TemplateItems id. * <p/> * IMP: * DONT call this method if you dont want automatic id-class assignments * Instead do a custom impl of addition of items to classes * Example: Template with items: 1 1 0 0 1 0 gets the first class with items with Id 1 * and Template with items: 0 1 1 0 1 gets the first class with items with Id 0 * Might want to do a custom assignment to avoid this. */ static boolean warned = false; private boolean checked; protected void runChecks() { if (!checked) { runChecksInit(); runChecksPost(); checked = true; } } protected ArrayList runChecksInit() { if (this.fClasses == null) { throw new RuntimeException("Cannot call method as Template has no associated Template.Class's"); } if (this.fItems == null) { throw new RuntimeException("Cannot call method as Template has no associated Template.Items's"); } // Check 1: check to make sure profile pos in template hasnt been reused (i.e each item needs a uniq profile pos) final List ual = new ArrayList(getNumItems()); for (int i = 0; i < getNumItems(); i++) { Template.Item item = (Template.Item) fItems.get(i); Integer primPos = new Integer(item.getProfilePosition()); //log.debug("item = " + item); if (ual.contains(primPos)) { throw new RuntimeException("ProfilePosition has been reused! Position = " + primPos + " by Item: " + Printf.outs(item)); } else { ual.add(primPos); } } // Check 2: unique Item id's final ArrayList unique_item_ids_ordered_by_profile_pos = new ArrayList(); final Template.Item[] items_ordered = getItemsOrderedByProfilePos(); for (int i = 0; i < items_ordered.length; i++) { if (!unique_item_ids_ordered_by_profile_pos.contains(items_ordered[i].getId())) { unique_item_ids_ordered_by_profile_pos.add(items_ordered[i].getId()); } } // could barf for continuous templates if (isContinuous() == false && unique_item_ids_ordered_by_profile_pos.size() != fClasses.size()) { StringBuffer err = new StringBuffer("Mismatched numbers between unique item id's: ").append(unique_item_ids_ordered_by_profile_pos.size()); err.append(' ').append(unique_item_ids_ordered_by_profile_pos).append(" and number of Template.Class's: ").append(fClasses.size()).append('\n'); for (int c = 0; c < fClasses.size(); c++) { err.append(((Class) fClasses.get(c)).getName()).append(' '); } throw new IllegalArgumentException(err.toString()); } return unique_item_ids_ordered_by_profile_pos; } protected void runChecksPost() { Set classNames = new HashSet(); // check: final (after adding items): Obvious error such as 2 classes and items swapped names for (int c = 0; c < fClasses.size(); c++) { Class cl = (Class) fClasses.get(c); if (classNames.contains(cl.getName())) { throw new IllegalArgumentException("Duplicate class names: " + cl.getName() + "\n" + classNames); } else { classNames.add(cl.getName()); } if (cl.getSize() == 0) { throw new IllegalStateException("Empty class: " + cl.getName() + " " + cl.getSize() + " total # items: " + getNumItems()); } Item item = cl.getItem(0); // some item from this class for (int r = 0; r < fClasses.size(); r++) { Class clr = (Class) fClasses.get(r); if (clr.getName().equals(item.getId())) { if (r != c) { throw new IllegalStateException("Something obviously wrong items and classes mismatched: \n" + Printf.outs(this)); } } } } } protected void assignItems2ClassInOrder() { // Check3: ensure that class-item assignment has not already been done for (int i = 0; i < fClasses.size(); i++) { if (getClass(i).getSize() != 0) { throw new RuntimeException("Items already seem to be assigned to class: " + getClass(i).getName()); } } final ArrayList unique_item_ids_ordered_by_profile_pos = runChecksInit(); // Check 4: Make sure the profile order of items is the same as the order of classes // ok, all looks good, associate ids and classes // @note Here is where the first id is automatically (and blindly) associated with the first class // This may not be what you want always!! final Hashtable idClassHash = new Hashtable(); for (int i = 0; i < unique_item_ids_ordered_by_profile_pos.size(); i++) { idClassHash.put(unique_item_ids_ordered_by_profile_pos.get(i), fClasses.get(i)); } // finally (whew), the actual assignment for (int i = 0; i < getNumItems(); i++) { final Template.Item item = (Template.Item) fItems.get(i); final ClassImpl cl = (ClassImpl) idClassHash.get(item.getId()); cl.add(item); } runChecksPost(); } /** * Set this Template as continuous. * Continuous templates are for instance a gene's expression profile. * There should be as many classes as items in continuous templates. */ protected void setContinuous(final boolean cont) { checkImmutable(); this.fContinuous = cont; if (!cont) { } else { // check if (getNumItems() != getNumClasses()) { throw new IllegalStateException("Cannot make template continuous. # items: " + getNumItems() + " is not equal to # classes: " + getNumClasses()); } // check to ensure that all items are numeric Item it = null; try { // try block for mor einformative of error messages for (int i = 0; i < getNumItems(); i++) { it = _getItemAsIs(i); it.floatValue(); // a check } } catch (NumberFormatException e) { throw new IllegalStateException("Item: " + it.getId() + " at pos: " + it.getProfilePosition() + " is not numeric. The Template cannot be set as continuous"); } } } private boolean fSampleNamesFromDataset; protected void setSampleNamesFromDataset(final boolean set) { this.fSampleNamesFromDataset = set; } /** * all public mut methods in this class mustt check * as must all factory methods */ public void makeImmutable() { fImmutable = true; runChecks(); } private void checkImmutable() { if (fImmutable) { throw new ImmutedException(); } } /** * A Template.Class is the replacement for ma's ClusterData. * <p/> * Accessor methods are public * Modifier methods are private/protected */ public static class ClassImpl implements Template.Class { /** * The name of this Template class */ protected String fName; /** * list of Template.Items */ protected ArrayList fItems; /** * Classs constructor */ public ClassImpl(final String className) { this.fName = className; fItems = new ArrayList(); } /** * The name of this Template.Class */ public String getName() { return fName; } public Template.Item getItem(int i) { return (Template.Item) fItems.get(i); } public Template.Item[] getItemsOrderedByProfilePos() { final Item[] items = (Item[]) fItems.toArray(new Item[fItems.size()]); final TIntObjectHashMap map = hashProfilePosItemMap(items); final int[] pp = getProfilePositionsSorted(map); final Item[] ret = new Item[pp.length]; for (int i = 0; i < pp.length; i++) { ret[i] = (Item) map.get(pp[i]); } return ret; } /** * Number of TemplateItems that are members */ public int getSize() { return fItems.size(); } public int hashCode() { return fName.hashCode(); } public String getMembershipInfo() { StringBuffer buf = new StringBuffer("Class: ").append(this.getName()).append('\n'); buf.append("Members: \t"); for (int i = 0; i < this.getSize(); i++) { int profile_pos = this.getItem(i).getProfilePosition(); if (profile_pos != -1) { buf.append(this.getItem(i).getId()).append('[').append(i).append(',').append(profile_pos).append(']'); } else { buf.append(this.getItem(i).getId()).append('[').append(this.getItem(i). getProfilePosition()).append(']'); } if (i != this.getSize() - 1) { buf.append(','); } } return buf.toString(); } // IMP: Intentionally protected protected void add(final Template.Item item) { if (item == null) { throw new IllegalArgumentException("item cannot be null"); } this.fItems.add(item); } } // End Template.Class /** * Class Item * * @author Aravind Subramanian * @version %I%, %G% */ public static class ItemImpl implements Template.Item { /** * Identifier for this Item */ private String fId; /** * Position of this item in the Template vector * As a debugging aid, magic marker of -999 means its not been initialized */ protected int fProfilePos = -999; /** * Class Constructor. */ private ItemImpl(final String id, final int profilePos) { init(id, profilePos); } public static ItemImpl createItem(final String id, final int profilePos) { return new ItemImpl(id, profilePos); } private void init(final String id, final int profilePos) { this.fId = id; this.fProfilePos = profilePos; } // aka clone deep public Item cloneDeep() { return new ItemImpl(this.fId, this.fProfilePos); } public String getId() { return fId; } public int getProfilePosition() { return fProfilePos; } /** * Obviously works only if numeric * * @return Float value of this Item * @throws NumberFormatException */ public float floatValue() throws NumberFormatException { return Float.parseFloat(fId); } public boolean equals(final Object obj) { if (obj instanceof Item) { final Item io = (Item) obj; if (io.getId().equals(fId) && io.getProfilePosition() == fProfilePos) { return true; } } return false; } } // End Item private static final Color DEFAULT_CLASS0_COLOR = Color.LIGHT_GRAY; private static final Color DEFAULT_CLASS1_COLOR = Color.ORANGE; private static final Color[] DEFAULT_COLORS = new Color[]{DEFAULT_CLASS0_COLOR, DEFAULT_CLASS1_COLOR, Color.YELLOW, Color.MAGENTA, Color.GREEN, Color.CYAN, Color.PINK}; private TIntObjectHashMap fItemProfilePosColorScheme; public Color getItemColor(final int itemProfilePos) { if (fItemProfilePosColorScheme == null) { makeAutoColors(); } Object obj = fItemProfilePosColorScheme.get(itemProfilePos); if (obj == null) { //TraceUtils.showTrace(); log.warn("No color for item at profile pos: " + itemProfilePos + " existing pos-color scheme size: " + Printf.outs(fItemProfilePosColorScheme)); //throw new IllegalArgumentException("No color for item at profile pos: " + itemProfilePos + " existing pos-color map: " + Printf.outs(fItemProfilePosColorMap)); return Color.WHITE; } return (Color) obj; } private void makeAutoColors() { this.fItemProfilePosColorScheme = new TIntObjectHashMap(); if (getNumClasses() == 1 || isContinuous()) { // for 1 class templates and continuous templates, dont color for (int i = 0; i < getNumItems(); i++) { fItemProfilePosColorScheme.put(_getItemAsIs(i).getProfilePosition(), Color.WHITE); } } else if (getNumClasses() == 2) { Class c0 = getClass(0); for (int i = 0; i < c0.getSize(); i++) { fItemProfilePosColorScheme.put(c0.getItem(i).getProfilePosition(), DEFAULT_CLASS0_COLOR); } Class c1 = getClass(1); for (int i = 0; i < c1.getSize(); i++) { fItemProfilePosColorScheme.put(c1.getItem(i).getProfilePosition(), DEFAULT_CLASS1_COLOR); } //log.debug("## doing 2 class color fill: " + c0.getSize() + " " + c1.getSize()); } else { //log.debug("## doing multi class color fill: " + getNumClasses()); // first try using standard colors, before generating random ones Color[] colors = ColorUtils.pickRandomColors(getNumClasses(), DEFAULT_COLORS); for (int c = 0; c < getNumClasses(); c++) { Class cl = getClass(c); //log.debug("class: " + cl.getName() + " " + cl.getSize()); for (int i = 0; i < cl.getSize(); i++) { fItemProfilePosColorScheme.put(cl.getItem(i).getProfilePosition(), colors[c]); } } } //log.debug(Printf.outs(fItemProfilePosColorScheme)); } } // End Template /*--- Formatted in Sun Java Convention Style on Fri, Sep 27, '02 ---*/
true
f789acd2a2bb6ac7021b27c97827bd43689090b5
Java
deebee99/DSAProblemSolvingJava
/src/LeetCode/NumbersAtMostNGivenDigitSet.java
UTF-8
2,187
3.296875
3
[]
no_license
package LeetCode; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Map; /** * Digit DP Solution (TLE since 1<=n<=10^9) */ public class NumbersAtMostNGivenDigitSet { private ArrayList<Integer> nums = new ArrayList<>(); private ArrayList<Integer> intDigits = new ArrayList<>(); private Map<String, Integer> map = new HashMap<>(); public int atMostNGivenDigitSet(String[] digits, int n) { intDigits.add(0); for (String s : digits) intDigits.add(Integer.parseInt(s)); // Collections.sort(intDigits); while (n > 0) { nums.add(n % 10); n = n / 10; } Collections.reverse(nums); return atMostNGivenDigitSetHelper(0, 0, 1) - 1; } private int atMostNGivenDigitSetHelper(int n, int index, int flag) { if (index >= nums.size()) { return 1; } String s = n + " " + index + " " + flag; if (map.containsKey(s)) return map.get(s); int limit = intDigits.get(intDigits.size() - 1), ans = 0; if (flag == 1) limit = nums.get(index); for (int i : intDigits) { if (i == 0 && n > 0) continue; if (i > limit) break; int newFlag = flag; if (newFlag == 1 && i < limit) newFlag = 0; ans += atMostNGivenDigitSetHelper(n * 10 + i, index + 1, newFlag); } map.put(s, ans); return ans; } /** * Mathematical approach coupled with dp */ public int atMostNGivenDigitSet2(String[] D, int N) { String S = String.valueOf(N); int K = S.length(); int[] dp = new int[K+1]; dp[K] = 1; for (int i = K-1; i >= 0; --i) { // compute dp[i] int Si = S.charAt(i) - '0'; for (String d: D) { if (Integer.parseInt(d) < Si) dp[i] += Math.pow(D.length, K-i-1); else if (Integer.parseInt(d) == Si) dp[i] += dp[i+1]; } } for (int i = 1; i < K; ++i) dp[0] += Math.pow(D.length, i); return dp[0]; } }
true
81b2fee2008adeb0ac8e6dca6b2ec12fa84f43b1
Java
YangLiuQing-star/design-pattern
/src/template/PureSoyMilk.java
UTF-8
164
2.0625
2
[]
no_license
package template; /** * @author YangLiuQing * @date 2020/6/16 21:41 */ public class PureSoyMilk extends SoyMilk{ @Override public void add() { } }
true
0cffe69c2f65bea95c320a8792e08610b376fb40
Java
hvnedward/music_app
/simple_app/app/src/main/java/com/example/mymvvm/adapter/SingerAdapter.java
UTF-8
2,845
2.375
2
[]
no_license
package com.example.mymvvm.adapter; import static com.example.mymvvm.Constants.NULL_STRING; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.cardview.widget.CardView; import androidx.recyclerview.widget.RecyclerView; import com.example.mymvvm.Interface.IAlbumClick; import com.example.mymvvm.Interface.ISingerClick; import com.example.mymvvm.R; import com.example.mymvvm.model.Album; import com.example.mymvvm.model.Singer; import java.util.List; public class SingerAdapter extends RecyclerView.Adapter<SingerAdapter.SingerAdapterViewHolder>{ List<Singer> singer; private ISingerClick iSingerClick; public SingerAdapter(ISingerClick listener) { this.iSingerClick = listener; } public void setSinger(List<Singer> data){ this.singer = data; notifyDataSetChanged(); } @NonNull @Override public SingerAdapterViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_song, parent, false); return new SingerAdapterViewHolder(view); } @Override public void onBindViewHolder(@NonNull SingerAdapterViewHolder holder, int position) { Singer s = singer.get(position); if(singer!=null){ holder.tvAlbumName.setText(s.getName()); holder.tvNumber.setText(String.valueOf(s.getAmount())); holder.imageView.setImageResource(R.drawable.singer); holder.cardView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { iSingerClick.onClick(s); } }); } else{ holder.cardView.setVisibility(View.GONE); holder.tvAlbumName.setText(NULL_STRING); holder.tvNumber.setText(NULL_STRING); holder.imageView.setVisibility(View.INVISIBLE); } } @Override public int getItemCount() { if(singer!=null){ return singer.size(); } return 0; } public class SingerAdapterViewHolder extends RecyclerView.ViewHolder{ private ImageView imageView; private TextView tvAlbumName; private TextView tvNumber; private CardView cardView; public SingerAdapterViewHolder(@NonNull View itemView) { super(itemView); imageView = itemView.findViewById(R.id.img_song); tvAlbumName =itemView.findViewById(R.id.title_song); tvNumber = itemView.findViewById(R.id.singer_song); cardView = itemView.findViewById(R.id.card_item); } } }
true
98756c7d5ae211af607455196034210fcde1683a
Java
nivance/Ostrich
/Ostrichapi/src/main/java/org/ostrich/nio/api/framework/exception/InsufficientConnectoinException.java
UTF-8
531
2
2
[]
no_license
package org.ostrich.nio.api.framework.exception; public class InsufficientConnectoinException extends RouterException{ /** * */ private static final long serialVersionUID = 1665068546914716898L; public InsufficientConnectoinException() { super(); } public InsufficientConnectoinException(String message, Throwable cause) { super(message, cause); } public InsufficientConnectoinException(String message) { super(message); } public InsufficientConnectoinException(Throwable cause) { super(cause); } }
true
9e387b6c136dfe827e1ebdb82f54dd15006bef80
Java
jyyconrad/wx-api
/src/main/java/com/github/jconrad/modules/wx/service/WxTagService.java
UTF-8
544
1.515625
2
[ "Apache-2.0" ]
permissive
package com.github.jconrad.modules.wx.service; import com.baomidou.mybatisplus.extension.service.IService; import com.github.jconrad.common.utils.PageUtils; import com.github.jconrad.modules.wx.entity.WxTagEntity; import com.github.jconrad.modules.wx.form.WxTagUsers; import java.util.Map; /** * * * @author jyyconrad * @email jyy3638@126.com * @date 2020-03-04 15:08:56 */ public interface WxTagService extends IService<WxTagEntity> { PageUtils queryPage(Map<String, Object> params); void batchSetUsers(WxTagUsers wxTagUsers); }
true
98b105fad4d87d4fa2d183e76832df16c8ae09a4
Java
gormac23/Java
/Udemy/JavaMasterclass/3.FirstSteps/src/com/gormac23/LogicalOperators.java
UTF-8
1,736
4.03125
4
[]
no_license
package com.gormac23; public class LogicalOperators { public static void main(String[] args) { int topScore = 100; // Equal Operator if (topScore == 100) { System.out.println("You have the high-score"); } // Not Operator if (topScore != 100) { System.out.println("You do NOT have the high-score"); } boolean isTopScore = false; if (isTopScore == false) { System.out.println("Not the top score"); } // This is a better way to write the above code if (!isTopScore) { System.out.println("Not the top score"); } // You can shorten boolean expressions by using the variable name itself as the comparrison // this works for true and false... // instead of using isTopScore == true or false etc. // just use isTopScore or !isTopScore, as seen above // Greater-than Operator int newScore = 150; if (newScore > 100) { System.out.println("You beat the high-score"); } // Less-than Operator int badScore = 10; if (badScore < 100) { System.out.println("You didn't beat the high-score"); } // AND Operator ... Both sides need to be TRUE int secondScore = 50; if ((secondScore > badScore) && (secondScore < topScore)) { System.out.println("Beat the lowest but less than the high-score"); } // OR Operator ... Only one side need to be TRUE if ((secondScore > badScore) || (secondScore > topScore)) { System.out.println("Beat the lowest OR you score was less than the high-score"); } } }
true
2be8299ec9df7fa9ac49d1e307d0a676da61ceb6
Java
JasonLimonB/interceptoresSpringboot
/src/main/java/com/limon/code/controllers/Index.java
UTF-8
538
2.15625
2
[]
no_license
package com.limon.code.controllers; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @Controller public class Index { String txt = "Si puedes leer este texto es que se cumplio la candición"; @RequestMapping( value = "/", method = RequestMethod.GET) public String index(Model model){ model.addAttribute("texto", txt); return "index"; } }
true
0f86f4631190498788243b959219473d951fab49
Java
bltn/GeoMood
/app/repositories/DBEnvironment.java
UTF-8
79
1.609375
2
[]
no_license
package repositories; public enum DBEnvironment { TEST, DEV, PRODUCTION }
true
9ec4bb8773fc7599e2bd080fc72ac2c43a4cdccc
Java
pawanpatidar/DefineProject
/app/src/main/java/com/patidar/pawan/definelabs/DBHelper.java
UTF-8
3,663
2.421875
2
[]
no_license
package com.patidar.pawan.definelabs; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import com.patidar.pawan.definelabs.ui.AllMatches.MatchesModel; import java.util.ArrayList; import java.util.HashMap; public class DBHelper extends SQLiteOpenHelper { private static Context mContext; private static final int DATABASE_VERSION = 1; private static final String DATABASE_NAME = "vanues_db"; private static DBHelper mInstance = null; private static final String TABLE_VANUE = "vanue_table"; private static final String COLUMN_VANUE_NAME = "vanueName"; private static final String COLUMN_VANUE_ADDRESS = "vanueAddress"; private static final String VANUE_ID = "id"; public static DBHelper getmInstance(Context context){ mContext =context; if(mInstance==null){ mInstance = new DBHelper(); } return mInstance; } public DBHelper(){ super(mContext, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { String CREATE_VANUE_TABLE = "CREATE TABLE " + TABLE_VANUE + "(" + VANUE_ID + " TEXT PRIMARY KEY," + COLUMN_VANUE_NAME + " TEXT," + COLUMN_VANUE_ADDRESS + " TEXT" + ")"; db.execSQL(CREATE_VANUE_TABLE); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS " + TABLE_VANUE); } public void DeleteAll(){ SQLiteDatabase db = this.getWritableDatabase(); db.delete(TABLE_VANUE,null, null); } ////======================= public boolean AddMatch(MatchesModel matchesModel){ boolean response = false; try { SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(VANUE_ID, matchesModel.getId()); values.put(COLUMN_VANUE_NAME, matchesModel.getVanue()); values.put(COLUMN_VANUE_ADDRESS, matchesModel.getAddress()); long mlon = db.insert(TABLE_VANUE, null, values); if (mlon > 0) { response = true; } else { response = false; } }catch (Exception e){ e.printStackTrace(); } return response; } public HashMap<String, String> getMatches() { HashMap<String ,String> matchHash = new HashMap<>(); try { String selectQuery = ""; selectQuery = "SELECT * FROM " + TABLE_VANUE; SQLiteDatabase db = this.getWritableDatabase(); Cursor cursor = db.rawQuery(selectQuery, null); if (cursor.moveToFirst()) { do { try { matchHash.put(cursor.getString(cursor.getColumnIndex(VANUE_ID)),cursor.getString(cursor.getColumnIndex(COLUMN_VANUE_NAME))); } catch (Exception e) { e.printStackTrace(); } } while (cursor.moveToNext()); } cursor.close(); db.close(); }catch (Exception e){ e.printStackTrace(); } return matchHash; } public boolean deleteMatch(String id) { SQLiteDatabase db = this.getWritableDatabase(); boolean isdeleted= db.delete(TABLE_VANUE, VANUE_ID + "= '" + id+"'", null ) > 0; return isdeleted; } }
true
65b7ab03dcb2243234ef72d4106ce520626d8d23
Java
hoswey/java-design-patterns
/singleton/src/test/java/com/iluwatar/singleton/EnumIvoryTowerTest.java
UTF-8
336
2.265625
2
[ "MIT" ]
permissive
package com.iluwatar.singleton; /** * Date: 12/29/15 - 19:20 PM * * @author Jeroen Meulemeester */ public class EnumIvoryTowerTest extends SingletonTest<EnumIvoryTower> { /** * Create a new singleton test instance using the given 'getInstance' method */ public EnumIvoryTowerTest() { super(() -> EnumIvoryTower.INSTANCE); } }
true
5391c6f0cbabbda3255d7944d8b0c9a957a430c5
Java
wangqingshan/smart-sample
/src/main/java/org/smart4j/wqs/day001/Test.java
UTF-8
709
3.375
3
[]
no_license
package org.smart4j.wqs.day001; /** * author 90 * description 测试成员变量 * date 2019/6/15 */ public class Test { private int a; public static void main(String[] args) { int b; System.out.println(new Test().a); //System.out.println(b); 注意局部变量不能这样用 //即使在初始化阶段程序员没有为类变量赋值也没有关系,类变量仍然具有一个确定的初始值。但局部 //变量就不一样,如果一个局部变量定义了但没有赋初始值是不能使用的,不要认为java中任何情况下 //都存在诸如整型变量默认为0,布尔变量默认为false等这样的默认值。 } }
true
2b6947bdbda3f873f25d32c767d90f5af71dfe34
Java
nate-getch/WAA-Labs
/FinalExam_JPA/src/main/java/com/packt/webstore/controller/EmployeeController.java
UTF-8
2,041
2.375
2
[]
no_license
package com.packt.webstore.controller; import javax.servlet.http.HttpServletRequest; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import com.packt.webstore.domain.Employee; import com.packt.webstore.domain.Address; import com.packt.webstore.service.AddressService; import com.packt.webstore.service.EmployeeService; @Controller @RequestMapping({ "/employees" }) public class EmployeeController { @Autowired EmployeeService employeeService; @Autowired AddressService addressService; @RequestMapping(value = { "", "/list" }) public String listEmployees(Model model) { model.addAttribute("employees", employeeService.findAll()); return "employees"; } @RequestMapping("/employee") public String getEmployeeByNumber(Model model, @RequestParam("id") String employeeId) { Employee employee = null; try { Long empId = Long.valueOf(employeeId); if( empId instanceof Long ) { employee = employeeService.findOne(empId); } } catch(NumberFormatException e) { System.out.println(e); } model.addAttribute("employee", employee); return "employee"; } @RequestMapping(value = "/add", method = RequestMethod.GET) public String addNewEmployee(@ModelAttribute("newEmployee") Employee newEmployee) { return "addEmployee"; } @RequestMapping(value = "/add", method = RequestMethod.POST) public String processAddNewEmployee(@Valid @ModelAttribute("newEmployee") Employee employeeToBeAdded, BindingResult result) { if(result.hasErrors()) { return "addEmployee"; } employeeService.save(employeeToBeAdded); return "redirect:/employees/list"; } }
true
ca5b4df5c620cd0531d8fdcddb6665e5c289a5f1
Java
liunana1993/FrameworkDemo
/baselib/src/main/java/com/mico/framework/baselib/constants/PageUrl.java
UTF-8
565
1.617188
2
[]
no_license
package com.mico.framework.baselib.constants; /** * Created by LiuNana on 2017/3/17. * define a url for every Activity,then {@link com.alibaba.android.arouter.launcher.ARouter} navigation * to the activity buy using this url */ public class PageUrl { //dagger module public static final String DAGGER_PROFILE = "/dagger/profile"; public static final String DAGGER_BOOK_LIST = "/dagger/book_list"; public static final String DAGGER_BOOK_DETAIL = "/dagger/book_detail"; private PageUrl() { //to hide the public constructor } }
true
b84ea7539eaf7cd8be310d943ba8edd89cf7f969
Java
Paladin1412/house
/java/classes/android/support/transition/aq.java
UTF-8
680
1.710938
2
[ "Apache-2.0" ]
permissive
package android.support.transition; import android.graphics.drawable.Drawable; import android.view.View; import android.view.ViewOverlay; class aq implements ar { private final ViewOverlay a; aq(View paramView) { this.a = paramView.getOverlay(); } public void add(Drawable paramDrawable) { this.a.add(paramDrawable); } public void clear() { this.a.clear(); } public void remove(Drawable paramDrawable) { this.a.remove(paramDrawable); } } /* Location: /Users/gaoht/Downloads/zirom/classes-dex2jar.jar!/android/support/transition/aq.class * Java compiler version: 6 (50.0) * JD-Core Version: 0.7.1 */
true
3f29515d5097f841581203cf8fd09b958f529830
Java
a2en/Zenly_re
/src/app.zenly.locator_4.8.0_base_source_from_JADX/sources/com/mapbox/android/telemetry/FeedbackData.java
UTF-8
1,327
1.851563
2
[]
no_license
package com.mapbox.android.telemetry; import android.os.Parcel; import android.os.Parcelable; import android.os.Parcelable.Creator; public class FeedbackData implements Parcelable { public static final Creator<FeedbackData> CREATOR = new C11301a(); /* renamed from: e */ private String f29229e; /* renamed from: f */ private String f29230f; /* renamed from: com.mapbox.android.telemetry.FeedbackData$a */ static class C11301a implements Creator<FeedbackData> { C11301a() { } public FeedbackData createFromParcel(Parcel parcel) { return new FeedbackData(parcel, null); } public FeedbackData[] newArray(int i) { return new FeedbackData[i]; } } /* synthetic */ FeedbackData(Parcel parcel, C11301a aVar) { this(parcel); } public int describeContents() { return 0; } public void writeToParcel(Parcel parcel, int i) { parcel.writeString(this.f29229e); parcel.writeString(this.f29230f); } public FeedbackData() { this.f29230f = null; this.f29229e = C11330b1.m29171b(); } private FeedbackData(Parcel parcel) { this.f29230f = null; this.f29229e = parcel.readString(); this.f29230f = parcel.readString(); } }
true
67fdb21234fae7f7802a4850b578878844b81da3
Java
DaianaBarb/springSecurity-oauth2-thymeleaf-jpa
/src/main/java/com/Test/Controls/LoginController.java
UTF-8
5,041
2.1875
2
[]
no_license
package com.Test.Controls; import java.util.ArrayList; import java.util.List; import javax.security.auth.message.callback.PrivateKeyCallback.Request; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import com.Test.Entities.CadastroEntity; import com.Test.Entities.LoginEntity; import com.Test.Services.LoginService; @Controller public class LoginController { @Autowired private LoginService service; @RequestMapping({"/login","/Login"}) public String login() { return "login"; } @RequestMapping("/deslog") public String deslogar() { String usu = SecurityContextHolder.getContext().getAuthentication().getName().toString(); LoginEntity entity=service.FindByLogin(usu); entity.setLogado(false); service.salvar(entity); return "redirect:/logout"; } @RequestMapping("/cadastro") public String cadastro() { return "Cadastro"; } @RequestMapping("/cadastro-tela-home") public String cadastroHome() { return "cadastro-tela-home"; } @RequestMapping("/autorizar") @PreAuthorize("hasRole('ADMIN')") public String autorizar(ModelMap model) { String usu = SecurityContextHolder.getContext().getAuthentication().getName(); model.addAttribute("ms", "Bem-vindo " + usu); model.addAttribute("logins", service.RetornaTodos()); return "autorizar"; } @RequestMapping("/excluirlogin/{id}") @PreAuthorize("hasRole('ADMIN')") public String excluirlogin(@PathVariable("id") Long id, RedirectAttributes attr) { service.Excluir(id); attr.addFlashAttribute("msg", " Excluido com Sucesso"); return "redirect:/home"; // usar redirect para n aparecer o id na tela } @RequestMapping(value = "/cadastrarhome", method = RequestMethod.POST) public String cadastrarhome(LoginEntity login, RedirectAttributes re, @RequestParam("confirma") String senha) { LoginEntity log = service.FindByLogin(login.getLogin()); // login.setLogado(false); if (log != null) { re.addFlashAttribute("msg", "Usuário já Existente, Porfavor recupere a senha. Se n for você, Crie um novo Login"); return "redirect:/cadastro-tela-home"; } if (!(login.getSenha().equals(senha))) { re.addFlashAttribute("msg", "As senhas devem ser identicas!"); return "redirect:/cadastro-tela-home"; } login.setSenha(new BCryptPasswordEncoder().encode(login.getSenha())); service.salvar(login); re.addFlashAttribute("msg", service.getErro()); return "redirect:/cadastro-tela-home"; } @RequestMapping(value = "/cadastrar", method = RequestMethod.POST) public String cadastrar(LoginEntity login, RedirectAttributes re, @RequestParam("confirma") String senha) { LoginEntity log = service.FindByLogin(login.getLogin()); // login.setLogado(false); if (log != null) { re.addFlashAttribute("msg", "Usuário já Existente, Porfavor recupere a senha. Se n for você, Crie um novo Login"); return "redirect:/cadastro"; } if (!(login.getSenha().equals(senha))) { re.addFlashAttribute("msg", "As senhas devem ser identicas!"); return "redirect:/cadastro"; } login.setSenha(new BCryptPasswordEncoder().encode(login.getSenha())); service.salvar(login); re.addFlashAttribute("msg", service.getErro()); return "redirect:/cadastro"; } @RequestMapping("/editaresalvarlogin") public String salvareEditarlogin( @RequestParam("senha") String senha,LoginEntity login, RedirectAttributes attr) { //login.setSenha(new BCryptPasswordEncoder().encode(login.getSenha())); LoginEntity entity=service.FindByLogin(login.getLogin()); if(!(login.getSenha().equals(entity.getSenha()))) { login.setSenha(new BCryptPasswordEncoder().encode(login.getSenha())); service.Salvar(login);} else { service.Salvar(login); } attr.addFlashAttribute("msg", " Editado com Sucesso"); return "redirect:/autorizar"; } @RequestMapping("/editarlogin/{id}") public String preEditarlogin(@PathVariable("id") Long id, ModelMap model) { // recuperando o path id model.addAttribute("login", service.Editar(id)); String usu = SecurityContextHolder.getContext().getAuthentication().getName(); model.addAttribute("ms", "Bem-vindo " + usu);// cria uma variavel e coloca a busca dentro ddela para ser // enviado para a outra pagina return "editarlogin"; } }
true
60339f4659acdb116b37dbba1925bfdfcdba8b83
Java
zuliaio/zuliaui
/zulia-ui/src/main/java/io/zulia/ui/client/views/home/HomeComponent.java
UTF-8
4,231
1.929688
2
[]
no_license
package io.zulia.ui.client.views.home; import com.axellience.vuegwt.core.annotations.component.Component; import com.axellience.vuegwt.core.annotations.component.Data; import com.axellience.vuegwt.core.client.component.IsVueComponent; import com.axellience.vuegwt.core.client.component.hooks.HasBeforeMount; import com.google.gwt.core.client.Scheduler; import com.google.gwt.i18n.client.NumberFormat; import elemental2.core.JsArray; import elemental2.core.JsDate; import io.zulia.ui.client.dto.MemberDTO; import io.zulia.ui.client.services.ServiceProvider; import io.zulia.ui.client.util.NotifyUtil; import us.ascendtech.highcharts.client.ChartOptions; import us.ascendtech.highcharts.client.Highcharts; import us.ascendtech.highcharts.client.chartoptions.Title; import us.ascendtech.highcharts.client.chartoptions.axis.Axis; import us.ascendtech.highcharts.client.chartoptions.axis.AxisPlotLine; import us.ascendtech.highcharts.client.chartoptions.axis.AxisTitle; import us.ascendtech.highcharts.client.chartoptions.axis.XAxis; import us.ascendtech.highcharts.client.chartoptions.axis.YAxis; import us.ascendtech.highcharts.client.chartoptions.chart.Chart; import us.ascendtech.highcharts.client.chartoptions.chart.ChartEvents; import us.ascendtech.highcharts.client.chartoptions.chart.functions.Load; import us.ascendtech.highcharts.client.chartoptions.series.Series; import us.ascendtech.highcharts.client.chartoptions.series.SeriesData; import us.ascendtech.highcharts.client.chartoptions.shared.SeriesTypes; @Component(components = { MemberCardComponent.class }) public class HomeComponent implements IsVueComponent, HasBeforeMount { private NumberFormat numberFormat = NumberFormat.getDecimalFormat().overrideFractionDigits(2); private Highcharts splineChart; @Data ChartOptions splineChartOptions; @Data JsArray<MemberDTO> members; @Data String usedDataDirSpaceGBFormatted; @Data String freeDataDirSpaceGBFormatted; @Data String totalDataDirSpaceGBFormatted; @Override public void beforeMount() { ServiceProvider.get().getService().getStats(statsDTO -> { splineChartOptions = new ChartOptions(); Load load = () -> Scheduler.get().scheduleFixedDelay(() -> { ServiceProvider.get().getService().getStats(statsDTO1 -> { Double value = statsDTO1.getJvmUsedMemoryMB(); Series series = splineChart.getSeries().getAt(0); JsArray<Object> data = new JsArray<>(JsDate.now(), value); if (series.getData().length == 30) { series.addPoint(data, true, true, true, false); } else { series.addPoint(data, true, false, true, false); } }, NotifyUtil::handleError); return true; }, 1500); ChartEvents chartEvents = new ChartEvents(); chartEvents.setLoad(load); splineChartOptions.setChart(new Chart().setType(SeriesTypes.SPLINE.getSeriesType()).setEvents(chartEvents)); Axis xAxis = new XAxis().setType("datetime").setTickPixelInterval(150); splineChartOptions.setxAxis((XAxis) xAxis); JsArray<AxisPlotLine> plotLines = new JsArray<>(); plotLines.push(new AxisPlotLine().setValue(0).setWidth(1).setColor("#808080")); Axis yAxis = new YAxis().setTitle(new AxisTitle().setText("Memory Usage")).setPlotLines(plotLines); splineChartOptions.setyAxis((YAxis) yAxis); Series splineSeries = new Series(); JsArray<Object> splineData = new JsArray<>(); splineSeries.setName("Memory Usage MB"); splineData.push(new SeriesData().setX(JsDate.now()).setY(statsDTO.getJvmUsedMemoryMB())); splineChartOptions.setSeries(new JsArray<>(splineSeries)); splineChartOptions.setTitle(new Title().setText("Memory Usage MB")); splineSeries.setData(splineData); splineChart = Highcharts.chart("memoryPieChart", splineChartOptions); usedDataDirSpaceGBFormatted = numberFormat.format(statsDTO.getUsedDataDirSpaceGB()) + "GB"; freeDataDirSpaceGBFormatted = numberFormat.format(statsDTO.getFreeDataDirSpaceGB()) + "GB"; totalDataDirSpaceGBFormatted = numberFormat.format(statsDTO.getTotalDataDirSpaceGB()) + "GB"; }, NotifyUtil::handleError); members = new JsArray<>(); ServiceProvider.get().getService().getMembers(members -> { this.members = members.getMembers(); }, NotifyUtil::handleError); } }
true
3813ca9b67a9a730145bfdc80540618ac885404c
Java
Zegdon/stc-main
/backend/course-service/src/main/java/hu/me/iit/malus/thesis/course/service/impl/CourseServiceImpl.java
UTF-8
8,051
1.96875
2
[]
no_license
package hu.me.iit.malus.thesis.course.service.impl; import hu.me.iit.malus.thesis.course.client.*; import hu.me.iit.malus.thesis.course.client.dto.Mail; import hu.me.iit.malus.thesis.course.model.Course; import hu.me.iit.malus.thesis.course.model.Invitation; import hu.me.iit.malus.thesis.course.model.exception.ForbiddenCourseEdit; import hu.me.iit.malus.thesis.course.repository.CourseRepository; import hu.me.iit.malus.thesis.course.repository.InvitationRepository; import hu.me.iit.malus.thesis.course.service.CourseService; import hu.me.iit.malus.thesis.course.service.exception.CourseNotFoundException; import hu.me.iit.malus.thesis.course.service.exception.InvitationNotFoundException; import hu.me.iit.malus.thesis.course.service.impl.config.InvitationConfig; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.time.Instant; import java.util.*; /** * Default implementation for Course service. * * @author Attila Szőke */ @Service @Slf4j public class CourseServiceImpl implements CourseService { private CourseRepository courseRepository; private InvitationRepository invitationRepository; private TaskClient taskClient; private FeedbackClient feedbackClient; private UserClient userClient; private FileManagementClient fileManagementClient; private EmailClient emailClient; private InvitationConfig invitationConfig; /** * Instantiates a new Course service. * @param courseRepository the course repository * @param invitationRepository the invitation repository * @param taskClient the task client * @param feedbackClient the feedback client * @param userClient the user client * @param fileManagementClient the fileManagement client * @param emailClient the email client * @param invitationConfig configuration for sending invitations */ @Autowired public CourseServiceImpl(CourseRepository courseRepository, InvitationRepository invitationRepository, TaskClient taskClient, FeedbackClient feedbackClient, UserClient userClient, FileManagementClient fileManagementClient, EmailClient emailClient, InvitationConfig invitationConfig) { this.courseRepository = courseRepository; this.invitationRepository = invitationRepository; this.taskClient = taskClient; this.feedbackClient = feedbackClient; this.userClient = userClient; this.fileManagementClient = fileManagementClient; this.emailClient = emailClient; this.invitationConfig = invitationConfig; } /** * {@inheritDoc} */ @Override public Course create(Course course, String creatorsEmail) { course.setCreationDate(Date.from(Instant.now())); Course newCourse = courseRepository.save(course); userClient.saveCourseCreation(newCourse.getId()); log.info("Created course: {}", newCourse.getId()); return newCourse; } /** * {@inheritDoc} */ @Override public Course edit(Course course, String editorsEmail) { Course oldCourse = courseRepository.getOne(course.getId()); if (!oldCourse.getCreator().getEmail().equals(editorsEmail)) { throw new ForbiddenCourseEdit(); } log.info("Modified course: {}", course.getId()); return courseRepository.save(course); } /** * {@inheritDoc} */ @Override public Course get(Long courseId, String userEmail) throws CourseNotFoundException { Optional<Course> optCourse = courseRepository.findById(courseId); if (optCourse.isPresent()) { Course course = optCourse.get(); if (!userClient.isRelated(course.getId())) { throw new CourseNotFoundException(); } //TODO: We should find a way to fire these as async requests course.setCreator(userClient.getTeacherByCreatedCourseId(courseId)); course.setStudents(userClient.getStudentsByAssignedCourseId(courseId)); course.setTasks(taskClient.getAllTasks(courseId)); course.setFiles(fileManagementClient.getAllFilesByTagId(hu.me.iit.malus.thesis.course.client.dto.Service.COURSE, courseId).getBody()); course.setComments(feedbackClient.getAllCourseComments(courseId)); log.info("Course found: {}", courseId); return course; } else { log.warn("No course found with this id: {}", courseId); throw new CourseNotFoundException(); } } /** * {@inheritDoc} */ @Override public Set<Course> getAll(String userEmail) { Set<Long> relatedCourseIds = userClient.getRelatedCourseIds(); Set<Course> relatedCourses = courseRepository.findAllByIdIsIn(relatedCourseIds); for (Course course : relatedCourses) { course.setCreator(userClient.getTeacherByCreatedCourseId(course.getId())); } log.info("Get all courses done, total number of courses is {}", relatedCourses.size()); return relatedCourses; } /** * {@inheritDoc} */ @Override public void invite(Long courseId, String studentEmail) { String invitationUuid = UUID.randomUUID().toString(); sendInvitationEmail(invitationUuid, studentEmail); invitationRepository.save(Invitation.of(invitationUuid, studentEmail, courseId)); log.info("Invitation saved to database and e-mail sent - courseId: {}, studentEmail{}", courseId, studentEmail); } /** * {@inheritDoc} */ @Override public void invite(Long courseId, List<String> studentEmails) { List<Invitation> invitations = new ArrayList<>(); for (String studentId : studentEmails) { String uuid = UUID.randomUUID().toString(); invitations.add(Invitation.of(uuid, studentId, courseId)); sendInvitationEmail(uuid, studentId); } invitationRepository.saveAll(invitations); log.info("Invitations saved to database and e-mails sent - courseId: {}, studentId{}", courseId, studentEmails); } /** * {@inheritDoc} */ @Transactional @Override public void acceptInvite(String inviteUUID) throws InvitationNotFoundException { Optional<Invitation> opt = invitationRepository.findById(inviteUUID); if (opt.isPresent()) { Invitation invitation = opt.get(); userClient.saveCourseAssign(invitation.getCourseId()); log.info("Invitation accepted: {}", invitation); if (invitationRepository.existsById(invitation.getInvitationUuid())) { invitationRepository.delete(invitation); } } else { log.warn("Invitation not found: {}", inviteUUID); throw new InvitationNotFoundException(); } } /** * Sends an invitation email to a student, which contains the correct link to accept the course invitation. * @param invitationUuid Id of the invitation * @param studentEmail Email address of the student */ private void sendInvitationEmail(String invitationUuid, String studentEmail) { String subject = "Registration Confirmation - " + invitationConfig.getApplicationName(); String confirmationUrl = invitationConfig.getApplicationURL() + "/api/course/acceptInvitation/" + invitationUuid; // This can be externalized via MessageSource, and get messages for different locales String message = "You can accept your course invitation via the following link: "; Mail email = new Mail(); email.setTo(Collections.singletonList(studentEmail)); email.setSubject(subject); email.setText(message + confirmationUrl); emailClient.sendMail(email); } }
true
360be87525180ef02ad1bb29e316dc888fa458dc
Java
RahulSale142/ALLDP
/Decorator-WrapperDP/src/com/rahul/decorator/DryFruitIceCreamDecorator.java
UTF-8
428
2.578125
3
[]
no_license
package com.rahul.decorator; import com.rahul.component.Icecream; public class DryFruitIceCreamDecorator extends IcecreamDecorator { public DryFruitIceCreamDecorator(Icecream icecream) { super(icecream); } private void addDryFruit() { System.out.println("Adding DryFruit"); } @Override public void prepare() { // TODO Auto-generated method stub super.prepare(); addDryFruit(); } }
true
5f53deb3dcc408c01679a54a26646d0b6a6d6ef1
Java
Abelarm/WebServices-in-Java
/TravelOnline/src/it/unisa/data/Cliente.java
UTF-8
1,113
2.71875
3
[]
no_license
package it.unisa.data; import java.io.Serializable; public class Cliente implements Serializable{ /** * */ private static final long serialVersionUID = 1L; private String nome, cognome, email, login; public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public Cliente(String nome, String cognome, String email, String login) { this.nome = nome; this.cognome = cognome; this.email = email; this.login = login; } public Cliente() { this(null, null, null, null); } @Override public String toString() { return "Cliente [nome=" + nome + ", cognome=" + cognome + ", email=" + email + ", login=" + login + "]"; } public String getCognome() { return cognome; } public void setCognome(String cognome) { this.cognome = cognome; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getLogin() { return login; } public void setLogin(String login) { this.login = login; } }
true
4e765b80dfde7d51ad91219e078aaafae77999f2
Java
spacechina-com/sc.service
/src/main/java/com/sc/service/service/IMenuService.java
UTF-8
212
1.632813
2
[]
no_license
package com.sc.service.service; import java.util.List; import com.sc.api.model.Menu; import com.sc.api.model.Pd; public interface IMenuService { List<Menu> listRoleMenu(Pd pd) throws Exception; }
true
2a31d60c9ec24c4ddb853460ad172d1e8d8c2244
Java
LyskaL/GitLabTool
/src/main/java/com/lgc/gitlabtool/git/jgit/ChangedFileStatus.java
UTF-8
1,095
2.34375
2
[]
no_license
package com.lgc.gitlabtool.git.jgit; /** * Status for {@link ChangedFile}. * * It shows us file state: removed, added, it was added to the staging or not. * * @author Lyudmila Lysk */ public enum ChangedFileStatus { CONFLICTING { @Override public String toString() { return "has conflicts"; } }, UNTRACKED { @Override public String toString() { return "untracked"; } }, MODIFIED { @Override public String toString() { return "modified"; } }, MISSING { @Override public String toString() { return "missing"; } }, ADDED { @Override public String toString() { return "added"; } }, REMOVED { @Override public String toString() { return "removed"; } }, CHANGED { @Override public String toString() { return "changed"; } }; }
true
468f242bcb6bd8e6625d302f7acb8cf8fbbfe698
Java
maupaz92/MH
/CapaServicioMH/src/main/java/servicio/accesos/RegistroRESTServices.java
UTF-8
710
2.3125
2
[]
no_license
package servicio.accesos; import java.util.HashSet; import java.util.Set; import servicio.accesos.EquiposRESTService; import servicio.accesos.TorneosRESTService; import javax.ws.rs.core.Application; public class RegistroRESTServices extends Application { //contiene las clase estilo singleton que recibiran request private Set<Object> singletons = new HashSet<Object>(); public RegistroRESTServices(){ singletons.add(new TorneosRESTService()); singletons.add(new EquiposRESTService()); singletons.add(new JugadoresRESTService()); singletons.add(new EstadisticasRESTService()); } @Override public Set<Object> getSingletons() { return singletons; } }
true
ecba7e5ffb5b6e4368ab854ad2b2efc8b667981c
Java
parth1493/JavaSerivce
/app/src/main/java/com/tr1/javaserivce/MyIntentService.java
UTF-8
1,426
2.328125
2
[]
no_license
package com.tr1.javaserivce; import android.app.IntentService; import android.content.Intent; import android.os.Bundle; import android.os.ResultReceiver; import android.util.Log; import androidx.annotation.Nullable; public class MyIntentService extends IntentService { private static final String TAG = "MyIntentService"; public MyIntentService() { super("MyWorkerThread"); } @Override public void onCreate() { super.onCreate(); Log.i(TAG, "onCreate: "+Thread.currentThread().getName()); } @Override protected void onHandleIntent(@Nullable Intent intent) { Log.i(TAG, "onHandleIntent: "+Thread.currentThread().getName()); int sleepTime = intent.getIntExtra("sleepTime",1); ResultReceiver myrResultReceiver = intent.getParcelableExtra("receiver"); int ctr = 1; while (ctr <= sleepTime) { try { Log.i(TAG, "Value:"+ ctr+""); Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } ctr++; } Bundle bundle = new Bundle(); bundle.putString("resultIntentService","Counter stopped"+ctr); myrResultReceiver.send(18,bundle); } @Override public void onDestroy() { super.onDestroy(); Log.i(TAG, "onDestroy: "+Thread.currentThread().getName()); } }
true
9a322cd7e8a1b93a8a69b3c062aec226029b5b36
Java
hareesh996/HotelSearchApplicationAPI
/src/main/java/com/strikers/hotel/dao/entity/HotelLikes.java
UTF-8
688
2.34375
2
[]
no_license
package com.strikers.hotel.dao.entity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; @Entity(name="thotel_likes") public class HotelLikes { @Id @Column(name="likes_id") private Long id; @Column(name="up_likes") private int upLikes; @Column(name="down_likes") private int downLikes; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public int getUpLikes() { return upLikes; } public void setUpLikes(int upLikes) { this.upLikes = upLikes; } public int getDownLikes() { return downLikes; } public void setDownLikes(int downLikes) { this.downLikes = downLikes; } }
true
89a616b06786e5cb490745127223bd8a720dae93
Java
jpretel/sys.core
/sys.dao/src/core/entity/Requerimiento.java
UTF-8
2,740
1.992188
2
[]
no_license
package core.entity; import java.io.Serializable; import javax.persistence.*; /** * Entity implementation class for Entity: Requerimiento * */ @Entity public class Requerimiento implements Serializable { private static final long serialVersionUID = 1L; @Id private long idrequerimiento; @Column(length = 4) private String serie; @Column private int numero; @Column private int fecha; @Column private int anio; @Column private int mes; @Column private int dia; @Column(length = 200) private String glosa; @ManyToOne @JoinColumn(name = "idsucursal", referencedColumnName = "idsucursal") private Sucursal sucursal; @ManyToOne @JoinColumns({ @JoinColumn(name = "idsucursal", referencedColumnName = "idsucursal", insertable = false, updatable = false), @JoinColumn(name = "idalmacen", referencedColumnName = "idalmacen") }) private Almacen almacen; @ManyToOne @JoinColumn(name = "idresponsable", referencedColumnName = "idresponsable") private Responsable responsable; @ManyToOne @JoinColumn(name = "idflujo", referencedColumnName = "idflujo") private Flujo flujo; public Requerimiento() { super(); } public long getIdrequerimiento() { return idrequerimiento; } public void setIdrequerimiento(long idrequerimiento) { this.idrequerimiento = idrequerimiento; } public String getSerie() { return serie; } public void setSerie(String serie) { this.serie = serie; } public int getNumero() { return numero; } public void setNumero(int numero) { this.numero = numero; } public int getFecha() { return fecha; } public void setFecha(int fecha) { this.fecha = fecha; } public int getAnio() { return anio; } public void setAnio(int anio) { this.anio = anio; } public int getMes() { return mes; } public void setMes(int mes) { this.mes = mes; } public int getDia() { return dia; } public void setDia(int dia) { this.dia = dia; } public Sucursal getSucursal() { return sucursal; } public void setSucursal(Sucursal sucursal) { this.sucursal = sucursal; } public Almacen getAlmacen() { return almacen; } public void setAlmacen(Almacen almacen) { this.almacen = almacen; } public Responsable getResponsable() { return responsable; } public void setResponsable(Responsable responsable) { this.responsable = responsable; } public String getGlosa() { return glosa; } public void setGlosa(String glosa) { this.glosa = glosa; } public Flujo getFlujo() { return flujo; } public void setFlujo(Flujo flujo) { this.flujo = flujo; } }
true
ffa13017bbea1a0082acd5d17364d652ed9f446d
Java
zwht/workflow
/cfmy-dao/src/main/java/com/zw/dao/entity/File.java
UTF-8
1,051
2.046875
2
[]
no_license
package com.zw.dao.entity; public class File { private Long id; private String url; private Short state; private Long userId; private Long corporationId; private Short type; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url == null ? null : url.trim(); } public Short getState() { return state; } public void setState(Short state) { this.state = state; } public Long getUserId() { return userId; } public void setUserId(Long userId) { this.userId = userId; } public Long getCorporationId() { return corporationId; } public void setCorporationId(Long corporationId) { this.corporationId = corporationId; } public Short getType() { return type; } public void setType(Short type) { this.type = type; } }
true
34bfe585b985619b94278abc6b0258ef977def98
Java
Pintorsmia/ClientJSP-Maven
/src/main/java/com/servlets/ServletTrain.java
UTF-8
9,584
2.5625
3
[]
no_license
package com.servlets; import calcul.DistanceService; import org.json.JSONObject; 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 java.io.*; import java.math.RoundingMode; import java.net.HttpURLConnection; import java.net.URL; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import com.objets.Trajet; @WebServlet( name = "ServletTrain", urlPatterns = {"/ServletTrain"} ) public class ServletTrain extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); //Methode pour arrondir DecimalFormat df = new DecimalFormat("#.##"); df.setRoundingMode(RoundingMode.HALF_UP); //Token pour api SNCF String TokenSNCF = "7d5b4417-f093-461b-b50b-b95d06cc06af"; String devise = request.getParameter("devise"); String villeDpt = request.getParameter("villeDpt"); String villeDst = request.getParameter("villeDst"); //Récupération des coordonées avec la fonction juste en dessous (utilisation de l'api SNCF) double [] coordDpt = this.getCoord(villeDpt,out); double [] coordDst = this.getCoord(villeDst,out); double latA = coordDpt[0]; double lonA = coordDpt[1]; double latB = coordDst[0]; double lonB = coordDst[1]; //Calcul de la distance avec soap calcul.Distance service = new DistanceService().getDistancePort(); double distance = service.distance(latA,lonA,latB,lonB); out.print("Resultat = "+df.format(distance)+" km"); //Requetes REST vers mon services de calcul des prix if (distance !=0) { StringBuilder SB = new StringBuilder(); URL url = new URL("https://api-py-train-bourget.herokuapp.com/API/calcul/" + distance + "/" + devise); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line, toprint; while ((line = rd.readLine()) != null) { SB.append(line); } rd.close(); JSONObject json = new JSONObject(SB.toString()); System.out.println(json); //verif qu'il y'a une gare dans la ville indique if (json.getInt("message") == 0) { double prixAPI = Double.parseDouble(json.get("prix").toString()); String deviseAPI = json.get("devise").toString(); toprint = " Prix : " + prixAPI + " " + deviseAPI; }else{ toprint = " Erreur avec l'api calcul prix"; } //out.write(df.format(SB.toString())); out.write(toprint); //Il faut modifier le service afin qu'il fasse l'arrondi avant de l'envoyer } //Partie recuperation des trajets //On recupere les UIC des 2 villes int UICA = this.getUIC(villeDpt); int UICB = this.getUIC(villeDst); //On recupere les 5 prochains trajets dans un arraylist ArrayList Trajets = this.getTrajet(UICA,UICB,TokenSNCF); Iterator it = Trajets.iterator(); String affichage = ""; while (it.hasNext()){ com.objets.Trajet tmptrajet = (com.objets.Trajet) it.next(); String message = tmptrajet.toString(); affichage += "<br>" + message; } out.write(affichage); /* if(pass.equals("pass")) { RequestDispatcher rd=request.getRequestDispatcher("servlet2"); rd.forward(request, response); } else { out.print("Sorry UserName or Password Error!"); RequestDispatcher rd=request.getRequestDispatcher("/index.jsp"); rd.include(request, response); */ } protected void doGet(HttpServletRequest request, HttpServletResponse response) { } public double[] getCoord(String ville, PrintWriter out) throws IOException { StringBuilder result = new StringBuilder(); double[] coords = new double[2]; URL url = new URL("https://data.sncf.com/api/records/1.0/search//?dataset=referentiel-gares-voyageurs&q="+ville+"&lang=FR"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); InputStream in = new BufferedInputStream(conn.getInputStream()); BufferedReader r = new BufferedReader(new InputStreamReader(in), 1000); for (String line = r.readLine(); line != null; line = r.readLine()) { result.append(line); } in.close(); r.close(); JSONObject json = new JSONObject(result.toString()); System.out.println(json); //verif qu'il y'a une gare dans la ville indique if (json.getInt("nhits") > 0) { double coordA = Double.parseDouble(json.getJSONArray("records").getJSONObject(0).getJSONObject("geometry").getJSONArray("coordinates").get(0).toString()); double coordB = Double.parseDouble(json.getJSONArray("records").getJSONObject(0).getJSONObject("geometry").getJSONArray("coordinates").get(1).toString()); coords[1] = coordA; coords[0] = coordB; } else { System.out.println("Pas de gares dans cette ville"); } System.out.println(Arrays.toString(coords)); conn.disconnect(); return coords; } public int getUIC(String ville) throws IOException { StringBuilder result = new StringBuilder(); int UIC = -1; URL url = new URL("https://data.sncf.com/api/records/1.0/search//?dataset=referentiel-gares-voyageurs&q=" + ville + "&lang=FR"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); try { InputStream in = new BufferedInputStream(conn.getInputStream()); BufferedReader r = new BufferedReader(new InputStreamReader(in), 1000); for (String line = r.readLine(); line != null; line = r.readLine()) { result.append(line); } in.close(); JSONObject json = new JSONObject(result.toString()); System.out.println(json); //verif qu'il y'a une gare dans la ville indique if (json.getInt("nhits") > 0) { UIC = Integer.parseInt(json.getJSONArray("records").getJSONObject(0).getJSONObject("fields").get("pltf_uic_code").toString()); System.out.println(UIC); } else { System.out.println("Pas de gares dans cette ville"); } } finally { conn.disconnect(); return UIC; } } public ArrayList getTrajet (int UICA, int UICB, String token) throws IOException { StringBuilder result = new StringBuilder(); ArrayList Trajets = new ArrayList(); URL url = new URL("https://api.sncf.com/v1/coverage/sncf/journeys?from=stop_area:OCE:SA:"+UICA+"&to=stop_area:OCE:SA:"+UICB+"&min_nb_journeys=5&key="+token); System.out.println(url); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); /*int responseCode = conn.getResponseCode(); System.out.println("GET Response Code :: " + responseCode);*/ try { InputStream in = new BufferedInputStream(conn.getInputStream()); BufferedReader r = new BufferedReader(new InputStreamReader(in), 1000); for (String line = r.readLine(); line != null; line = r.readLine()) { result.append(line); } in.close(); JSONObject json = new JSONObject(result.toString()); System.out.println(json); System.out.println((String) json.getJSONArray("journeys").getJSONObject(0).get("departure_date_time")); System.out.println(json.getJSONArray("journeys").length()); //verif qu'il y'a au moins 1 voyage if (json.getJSONArray("journeys").length() > 2) { for (int nbvoyage = 0; nbvoyage < json.getJSONArray("journeys").length() ; nbvoyage++) { System.out.println("journey " + nbvoyage); Trajets.add(new Trajet( (String) json.getJSONArray("journeys").getJSONObject(nbvoyage).get("departure_date_time"), (String) json.getJSONArray("journeys").getJSONObject(nbvoyage).get("arrival_date_time"), Integer.parseInt(json.getJSONArray("journeys").getJSONObject(nbvoyage).get("duration").toString()), (String) json.getJSONArray("journeys").getJSONObject(nbvoyage).getJSONArray("sections").getJSONObject(1).getJSONObject("display_informations").get("physical_mode") )); } } else { System.out.println("Pas de voyage disponible"); } } finally { conn.disconnect(); // System.out.println(Trajets[0].toString()); return Trajets; } } }
true
f4b41159778eabc4f784404017ddf734b8432de9
Java
RyanTech/RecipeOfTheDay
/src/com/mobilitea/recipes/controller/DataController.java
UTF-8
7,902
2.4375
2
[]
no_license
package com.mobilitea.recipes.controller; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.StreamCorruptedException; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Date; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.app.Activity; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.graphics.drawable.BitmapDrawable; import com.mobilitea.recipes.model.Recipe; /** * The main class which handles querying the server and generating models of recipes * @author jlgosse */ public class DataController { private static final String RECIPE_CACHE_TXT = "RecipeCache.txt"; // recipe of the day server private static final String SERVER = "http://recipeday.appspot.com/"; // api endpoint private static final String ENDPOINT_API = SERVER + "api/"; // get the last twenty recipes private static final String ENDPOINT_RECIPES = ENDPOINT_API + "recipe"; // share the current recipe private static final String ENDPOINT_SHARE = ENDPOINT_API + "share"; // the preference key used to determine if the latest recipe has been downloaded private static final String PREF_LATEST_RECIPE = "PREF_LATEST_RECIPE"; private static DataController instance; private SharedPreferences cache; private Activity activity; private ArrayList<Recipe> recipeList; private DataController(Activity activity) { this.activity = activity; this.cache = activity.getSharedPreferences("Recipes", 0); } /** * Get the instance of the DataController * @param activity A reference to the activity * @return */ public static DataController getInstance(Activity activity) { if (instance == null) { instance = new DataController(activity); } return instance; } /** * Check to see if the user already has the latest recipe * @return true if today's recipe has been downloaded */ public boolean hasTodaysRecipe() { long lastUpdatedTime = cache.getLong(PREF_LATEST_RECIPE, 0); long currentTime = System.currentTimeMillis(); int offset = new Date(currentTime).getTimezoneOffset() * 60 * 1000; currentTime -= offset; if (lastUpdatedTime < currentTime) { return false; } return true; } /** * Get an ArrayList of recipes from the AppEngine endpoint, or the cache, if available * @param useCache whether or not we should use the cache * @return The recipe list as an ArrayList */ public ArrayList<Recipe> getRecipeList(boolean useCache) { if (useCache) { ArrayList<Recipe> recipeList = getRecipesFromCache(); if (recipeList.size() == 3) { return getRecipeList(false); } return recipeList; } else { String recipeResponse = RestClient.executeGet(ENDPOINT_RECIPES); recipeList = getRecipeArrayList(recipeResponse); saveRecipesToDevice(); if (recipeList != null && recipeList.size() > 0) { Recipe recipe = recipeList.get(recipeList.size() - 1); long time = recipe.getShowingDate().getTime(); Editor edit = cache.edit(); edit.putLong(PREF_LATEST_RECIPE, time); edit.commit(); return recipeList; } return new ArrayList<Recipe>(); } } /** * Store the currently downloaded recipes on the device */ private void saveRecipesToDevice() { ObjectOutputStream os = null; try { FileOutputStream fOut = activity.openFileOutput(RECIPE_CACHE_TXT, Activity.MODE_PRIVATE); os = new ObjectOutputStream(fOut); os.writeObject(recipeList); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { os.close(); } catch (IOException e) { e.printStackTrace(); } } } /** * Get any currently downloaded recipes from the cache * @return An arraylist of recipe objects */ private ArrayList<Recipe> getRecipesFromCache() { String[] fileNameArray = activity.fileList(); ArrayList<Recipe> serializedData = new ArrayList<Recipe>(); for (int i=0; i<fileNameArray.length; i++) { String fileName = fileNameArray[i]; if (fileName.equalsIgnoreCase(RECIPE_CACHE_TXT)) { try { FileInputStream fIn = activity.openFileInput(fileName); ObjectInputStream is = new ObjectInputStream(fIn); serializedData = (ArrayList<Recipe>) is.readObject(); is.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (StreamCorruptedException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } } return serializedData; } /** * Given a JSON response, generate the ArrayList of recipe objects * @param recipeResponse The JSON to parse * @return an ArrayList of Recipe objects */ private ArrayList<Recipe> getRecipeArrayList(String recipeResponse) { ArrayList<Recipe> recipeArrayList = new ArrayList<Recipe>(); try { JSONArray recipeList = new JSONArray(recipeResponse); for (int i = 0; i < recipeList.length(); i++) { JSONObject recipe = recipeList.getJSONObject(i); Recipe recipeFromJSONObject = getRecipeFromJSONObject(recipe); recipeArrayList.add(recipeFromJSONObject); } } catch (JSONException e) { e.printStackTrace(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return recipeArrayList; } /** * Create a Recipe object from a JSONObject * @param recipeObject The JSON object * @return a Recipe * @throws JSONException * @throws IOException */ private Recipe getRecipeFromJSONObject(JSONObject recipeObject) throws JSONException, IOException { Recipe recipe = new Recipe(); recipe.setKey(recipeObject.getString(Recipe.KEY_KEY)); recipe.setAuthor(recipeObject.getString(Recipe.KEY_AUTHOR).trim()); recipe.setRecipeName(recipeObject.getString(Recipe.KEY_RECIPE_NAME).trim()); recipe.setIngredients(recipeObject.getString(Recipe.KEY_INGREDIENTS).trim()); recipe.setDirections(recipeObject.getString(Recipe.KEY_DIRECTIONS).trim()); recipe.setVotes(recipeObject.getInt(Recipe.KEY_VOTES)); URL url = new URL(SERVER + recipeObject.getString(Recipe.KEY_IMAGE)); recipe.setImage(url.toString()); // forced to add one day to the display date to support shitty python date manipulation recipe.setShowingDate(new Date(recipeObject.getLong(Recipe.KEY_SHOWING_DATE) * 1000 + 24 * 60 * 60 * 1000)); return recipe; } /** * Get an image from a particular URL * @param url * @return */ public static BitmapDrawable getImageFromURL(URL url) { try { InputStream stream = (InputStream) url.getContent(); return new BitmapDrawable(stream); }catch (Exception e) { System.out.println("Exc="+e); return null; } } /** * Send the currently opened recipe to a friend via email * @param recipe The recipe to send * @param usersName The name of the user to send it to * @param emailTo The users email * @throws UnsupportedEncodingException */ public void shareRecipe(Recipe recipe, String usersName, String emailTo) throws UnsupportedEncodingException { final String data = "?name=" + usersName.replace(" ", "%20") + "&to=" + emailTo + "&recipeName=" + URLEncoder.encode(recipe.getRecipeName(), "UTF-8") + "&ingredients=" + URLEncoder.encode(recipe.getIngredients(), "UTF-8") + "&directions=" + URLEncoder.encode(recipe.getDirections(), "UTF-8"); Thread thread = new Thread() { public void run() { RestClient.executeGet(ENDPOINT_SHARE + data); } }; thread.start(); } }
true
f93929136b7b4e323d2cfe1b6bf7ae4ca5934362
Java
YoungsAppWorkshop/coding-practice-archive
/java-practice/src/javaLesson/SimpleClient.java
UTF-8
2,694
3.140625
3
[]
no_license
package javaLesson; import java.awt.BorderLayout; import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.Socket; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JTextArea; import javax.swing.JTextField; public class SimpleClient extends Thread implements ActionListener { JTextArea ta; JTextField tf, tf2; JDialog dialog; String host; Socket s1; DataInputStream din; DataOutputStream dout; boolean stop; SimpleClient() { launchFrame(); } public static void main(String[] args) { new SimpleClient(); } public void launchFrame() { JFrame frame = new JFrame("yoon chatting"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); ta = new JTextArea(); tf = new JTextField(); tf.addActionListener(this); frame.setBackground(Color.lightGray); ta.setEditable(false); frame.add(ta, BorderLayout.CENTER); frame.add(tf, BorderLayout.SOUTH); frame.setSize(500, 300); frame.setVisible(true); dialog = new JDialog(frame, "접속IP주소", true); JLabel label = new JLabel("접속할 서버 IP를 입력하세요 "); tf2 = new JTextField("192.168.219.104", 15); tf2.addActionListener(this); dialog.add(label, BorderLayout.NORTH); dialog.add(tf2, BorderLayout.CENTER); dialog.pack(); dialog.setVisible(true); service(); } public void service() { try { s1 = new Socket(host, 5432); din = new DataInputStream(s1.getInputStream()); dout = new DataOutputStream(s1.getOutputStream()); ta.append(host + " 접속완료\n"); this.start(); } catch (IOException e) { System.out.println("접속이 되지 않습니다...."); System.exit(0); } } @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == tf) { try { String msg = tf.getText(); ta.append("me: " + msg + "\n"); dout.writeUTF(s1.getInetAddress() + ": " + msg); tf.setText(""); if (msg.equals("exit")) { // dout.writeUTF(msg); // ta.append("bye"); stop = true; dout.close(); s1.close(); System.exit(0); } else { } } catch (IOException e1) { ta.append(e1.getMessage()); } } else { host = tf2.getText().trim(); if (host.equals("")) host = "localhost"; dialog.dispose(); } } @Override public void run() { System.out.println("Thread started ...."); try { while (!stop) { ta.append(din.readUTF() + "\n"); } din.close(); s1.close(); System.exit(0); } catch (IOException e) { ta.append(e.getMessage()); } } }
true
d3d511606d83a34f7122ee92bc8d33de7759926f
Java
Natborks/java-projects
/CalenderApp/src/models/Entry.java
UTF-8
952
3.28125
3
[]
no_license
package models; import DateTimeUtils.CustomDate; import DateTimeUtils.CustomTime; public abstract class Entry { private CustomDate date; private CustomTime time; private boolean isRepeating; public Entry(CustomDate date, CustomTime time, boolean isRepeating){ this.date = date; this.time = time; this.isRepeating = isRepeating; } //EFFECTS: Returns the custom date in the format DD/MM/YYYY public String getDate() { return date.getDate(); } //SETTER public void setDate(CustomDate date) { this.date = date; } //GETTER public CustomTime getTime() { return time; } //SETTER public void setTime(CustomTime time) { this.time = time; } //GETTER public boolean isRepeating() { return isRepeating; } //SETTER public void setRepeating(boolean repeating) { isRepeating = repeating; } }
true
d6d75cd3ae4f3afa4cd5495e850af0b985026ed0
Java
rafaZIINN/prova-calculadora-adapter
/Calculador5.0/src/CalculaBinario.java
UTF-8
427
2.453125
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. */ /** * * @author Rafael */ public class CalculaBinario extends Calculadora{ public void binario (Double resultado){ System.out.println(Integer.toBinaryString(Double.valueOf(resultado).intValue())); } }
true
bfef3bbf88981f59b2a4d93c5ce8b9acc6c480b1
Java
codigoferoz/java_basico
/sesiones_4_5_6/ob-poo/src/poo/clases/Motor.java
UTF-8
436
2.703125
3
[]
no_license
package poo.clases; public class Motor { // 1. atributos String modelo; int caballos; double parNm; int numCilindros; // 2. constructores public Motor(){ } public Motor(String modelo, int caballos, double parNm, int numCilindros) { this.modelo = modelo; this.caballos = caballos; this.parNm = parNm; this.numCilindros = numCilindros; } // 3. métodos }
true
daa65b2da46827a1db235d73a3d5b304272d1303
Java
Sivaranjane29/kitchen-inventory
/app/src/main/java/com/example/kitcheninventory/adaptor/Re_ROL_Adapter.java
UTF-8
4,035
1.929688
2
[]
no_license
/* * Copyright (c) 2021. */ package com.example.kitcheninventory.adaptor; import android.content.Context; import android.os.AsyncTask; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.example.kitcheninventory.R; import com.example.kitcheninventory.activity.report.RolReport; import com.example.kitcheninventory.db.DatabaseClient; import com.example.kitcheninventory.db.cart.MCart; import com.example.kitcheninventory.db.master.MItem; import com.example.kitcheninventory.model.QuantityDetails; import com.example.kitcheninventory.model.StockRowList; import com.example.kitcheninventory.utils.CommonUtils; import com.google.android.material.textview.MaterialTextView; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.List; public class Re_ROL_Adapter extends RecyclerView.Adapter<Re_ROL_Adapter.RolViewHolder> { Context mContext; List<MItem> mItemList; CommonUtils mUtils; MCart mCart; public Re_ROL_Adapter(RolReport rolReport, List<MItem> mItemList) { this.mContext = rolReport; this.mItemList = mItemList; mUtils = new CommonUtils(mContext); } @NonNull @Override public RolViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(mContext).inflate(R.layout.row_rol, parent, false); return new RolViewHolder(view); } @Override public void onBindViewHolder(@NonNull RolViewHolder holder, int position) { MItem mRow = mItemList.get(position); holder.txtCalorie.setText("Calorie : " + mRow.getCalorie()); holder.txtQty.setText("Qty : " + mRow.getCurrentStock()); holder.txtRol.setText("ROL : " + mRow.getROL()); holder.txtName.setText(mRow.getItemName()); holder.txtAddCart.setVisibility(View.GONE); holder.txtAddCart.setOnClickListener(v -> { // new saveCart(mRow).execute(); }); } @Override public int getItemCount() { return mItemList.size(); } class saveCart extends AsyncTask<Void, Void, Void> { MItem mRow; public saveCart(MItem mRow) { this.mRow = mRow; } @Override protected Void doInBackground(Void... voids) { try { mCart = DatabaseClient .getInstance(mContext) .getAppDatabase() .mCart_dao() .getRowById(mRow.getItemName()); if (mCart == null) { mCart = new MCart(); mCart.setItemName(mRow.getItemName()); DatabaseClient .getInstance(mContext) .getAppDatabase() .mCart_dao() .insert(mCart); } } catch (Exception e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(Void aVoid) { super.onPostExecute(aVoid); mUtils.showSuccess("Added to cart"); } } class RolViewHolder extends RecyclerView.ViewHolder { TextView txtName, txtCalorie, txtQty, txtUnitName, txtExpiryDate, txtRol, txtAddCart; public RolViewHolder(View itemView) { super(itemView); txtName = itemView.findViewById(R.id.txtName); txtCalorie = itemView.findViewById(R.id.txtCalorie); txtQty = itemView.findViewById(R.id.txtQty); txtUnitName = itemView.findViewById(R.id.txtUnitName); txtExpiryDate = itemView.findViewById(R.id.txtExpiryDate); txtRol = itemView.findViewById(R.id.txtRol); txtAddCart = itemView.findViewById(R.id.txtAddCart); } } }
true
293f91ab4d94d971a3aea9ab6df4669d088bc569
Java
mash-up-kr/feedget-android
/ProjectFeedget/app/src/main/java/kr/mashup/feedget/ui/main/feed/FeedPresenter.java
UTF-8
2,756
2.09375
2
[ "Apache-2.0" ]
permissive
package kr.mashup.feedget.ui.main.feed; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.view.ViewPager; import android.widget.ArrayAdapter; import android.widget.Spinner; import kr.mashup.feedget.R; import kr.mashup.feedget.ui.main.feed.tabs.creation.CreationFragment; import kr.mashup.feedget.ui.main.feed.tabs.creation.FeedPagerAdapter; public class FeedPresenter implements Contract.Presenter { protected Contract.View view; private final String[] TEST_CATEGORIES = { "전체", "디자인", "회화", "공예", "글", "기타" }; private FeedPagerAdapter pagerAdapter; public FeedPresenter(Contract.View view) { this.view = view; } @Override public void initTabPager(ViewPager pager, TabLayout tabLayout) { pagerAdapter = new FeedPagerAdapter(view.getSupportFragmentManager()); String[] categories = getCategories(); Fragment[] fragments = new Fragment[categories.length]; for (int i = 0; i < categories.length; i++) { String category = categories[i]; tabLayout.addTab(tabLayout.newTab().setText(category)); fragments[i] = new CreationFragment().setCategory(category); } pagerAdapter.setFragments(fragments); pager.setAdapter(pagerAdapter); pager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout)); tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { @Override public void onTabSelected(TabLayout.Tab tab) { pager.setCurrentItem(tab.getPosition()); } @Override public void onTabUnselected(TabLayout.Tab tab) { } @Override public void onTabReselected(TabLayout.Tab tab) { } }); } @Override public void initSpinnerSort(Spinner spinnerViewType) { ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(view.getContext(), R.array.main_type, android.R.layout.simple_spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinnerViewType.setAdapter(adapter); } @Override public void initSpinnerViewType(Spinner spinnerSort) { ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(view.getContext(), R.array.main_sort, android.R.layout.simple_spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinnerSort.setAdapter(adapter); } private String[] getCategories() { return TEST_CATEGORIES; } }
true
423922a97de487e3d0deaaf72d2497b8188b6b2d
Java
jinhuizxc/GuokrChoice
/app/src/main/java/com/example/jh/guokrchoice/support/Constants.java
UTF-8
577
1.75
2
[]
no_license
package com.example.jh.guokrchoice.support; /** * Created by Dazz on 2016/4/3. */ public final class Constants { public interface Url{ String HANDPICK_OPEN_SCREEN_PAGE = "http://apis.guokr.com/flowingboard/item/handpick_open_screen_page.json"; String HANDPICK_CAROUSEL = "http://apis.guokr.com/flowingboard/item/handpick_carousel.json"; String ARTICLE = "http://apis.guokr.com/handpick/article.json"; String ARTICLE_LINK = "http://jingxuan.guokr.com/pick/"; String ARTICLE_LINK_V2 = "http://jingxuan.guokr.com/pick/v2/"; } }
true
6574892e378c163e0e5d2403d87004970497bcd9
Java
gy121681/Share
/customer/src/main/java/com/shareshenghuo/app/user/MentionAmountActivity.java
UTF-8
678
1.757813
2
[]
no_license
package com.shareshenghuo.app.user; import com.shareshenghuo.app.user.R; import com.shareshenghuo.app.user.widget.CircleProgressView; import android.os.Bundle; public class MentionAmountActivity extends BaseTopActivity{ private CircleProgressView circleProgressbar; @Override protected void onCreate(Bundle arg0) { // TODO Auto-generated method stub super.onCreate(arg0); setContentView(R.layout.mention_amount_activity); initview(); } private void initview() { // TODO Auto-generated method stub initTopBar("我的额度"); circleProgressbar = (CircleProgressView) findViewById(R.id.circleProgressbar); circleProgressbar.setProgress(80); } }
true
3b4cb8d6b9149f6158636dd0a16dce1b6f7e07dd
Java
birkh8792/hip-message-server
/hip-message-server-core/src/main/java/com/djhu/hiup/message/server/core/model/Doc.java
UTF-8
10,205
1.617188
2
[]
no_license
package com.djhu.hiup.message.server.core.model; import java.math.BigDecimal; import java.util.Date; /** * 文档 */ public class Doc { private BigDecimal pk; private String msgId; private String msgCreationTime; private String receiveId; private String sendId; private String docFlowNo; private String docTypeId; private String docTypeDepict; private String docCreationTime; private String docSecrecyLevelId; private String docSecrecyLevelDepict; private String docVersionNo; private BigDecimal systemDirPk; private String docPath; private String patientId; private String inpatientNo; private String outpatientNo; private String patientVisitTime; private String identityNo; private String name; private String hospitalCode; private String hospitalName; private String deptCode; private String authorCode; private String authorName; private String docStorageUnitCode; private String docStorageUnitName; private Date createTime; private Date updateTime; private String hiupStatus; private String hiupInfo; private String docBase64Content; private String healthCardId; private String serverOrganization; private String episodeId; private String inTime; private String outTime; private String admissionDepart; private String admissionType; private String admissionDoctor; private String diagnosisResult; private String repositoryUniqueId; private String docUrl; //2018-11-23 private String docType; private String documentId; public String getHealthCardId() { return healthCardId; } public void setHealthCardId(String healthCardId) { this.healthCardId = healthCardId; } public String getServerOrganization() { return serverOrganization; } public void setServerOrganization(String serverOrganization) { this.serverOrganization = serverOrganization; } public String getEpisodeId() { return episodeId; } public void setEpisodeId(String episodeId) { this.episodeId = episodeId; } public String getInTime() { return inTime; } public void setInTime(String inTime) { this.inTime = inTime; } public String getOutTime() { return outTime; } public void setOutTime(String outTime) { this.outTime = outTime; } public String getAdmissionDepart() { return admissionDepart; } public void setAdmissionDepart(String admissionDepart) { this.admissionDepart = admissionDepart; } public String getAdmissionType() { return admissionType; } public void setAdmissionType(String admissionType) { this.admissionType = admissionType; } public String getDiagnosisResult() { return diagnosisResult; } public void setDiagnosisResult(String diagnosisResult) { this.diagnosisResult = diagnosisResult; } public String getRepositoryUniqueId() { return repositoryUniqueId; } public void setRepositoryUniqueId(String repositoryUniqueId) { this.repositoryUniqueId = repositoryUniqueId; } public BigDecimal getPk() { return pk; } public void setPk(BigDecimal pk) { this.pk = pk; } public String getMsgId() { return msgId; } public void setMsgId(String msgId) { this.msgId = msgId == null ? null : msgId.trim(); } public String getMsgCreationTime() { return msgCreationTime; } public void setMsgCreationTime(String msgCreationTime) { this.msgCreationTime = msgCreationTime == null ? null : msgCreationTime.trim(); } public String getReceiveId() { return receiveId; } public void setReceiveId(String receiveId) { this.receiveId = receiveId == null ? null : receiveId.trim(); } public String getSendId() { return sendId; } public void setSendId(String sendId) { this.sendId = sendId == null ? null : sendId.trim(); } public String getDocFlowNo() { return docFlowNo; } public void setDocFlowNo(String docFlowNo) { this.docFlowNo = docFlowNo == null ? null : docFlowNo.trim(); } public String getDocTypeId() { return docTypeId; } public void setDocTypeId(String docTypeId) { this.docTypeId = docTypeId == null ? null : docTypeId.trim(); } public String getDocTypeDepict() { return docTypeDepict; } public void setDocTypeDepict(String docTypeDepict) { this.docTypeDepict = docTypeDepict == null ? null : docTypeDepict.trim(); } public String getDocCreationTime() { return docCreationTime; } public void setDocCreationTime(String docCreationTime) { this.docCreationTime = docCreationTime == null ? null : docCreationTime.trim(); } public String getDocSecrecyLevelId() { return docSecrecyLevelId; } public void setDocSecrecyLevelId(String docSecrecyLevelId) { this.docSecrecyLevelId = docSecrecyLevelId == null ? null : docSecrecyLevelId.trim(); } public String getDocSecrecyLevelDepict() { return docSecrecyLevelDepict; } public void setDocSecrecyLevelDepict(String docSecrecyLevelDepict) { this.docSecrecyLevelDepict = docSecrecyLevelDepict == null ? null : docSecrecyLevelDepict.trim(); } public String getDocVersionNo() { return docVersionNo; } public void setDocVersionNo(String docVersionNo) { this.docVersionNo = docVersionNo == null ? null : docVersionNo.trim(); } public BigDecimal getSystemDirPk() { return systemDirPk; } public void setSystemDirPk(BigDecimal systemDirPk) { this.systemDirPk = systemDirPk; } public String getDocPath() { return docPath; } public void setDocPath(String docPath) { this.docPath = docPath == null ? null : docPath.trim(); } public String getPatientId() { return patientId; } public void setPatientId(String patientId) { this.patientId = patientId == null ? null : patientId.trim(); } public String getInpatientNo() { return inpatientNo; } public void setInpatientNo(String inpatientNo) { this.inpatientNo = inpatientNo == null ? null : inpatientNo.trim(); } public String getOutpatientNo() { return outpatientNo; } public void setOutpatientNo(String outpatientNo) { this.outpatientNo = outpatientNo == null ? null : outpatientNo.trim(); } public String getPatientVisitTime() { return patientVisitTime; } public void setPatientVisitTime(String patientVisitTime) { this.patientVisitTime = patientVisitTime == null ? null : patientVisitTime.trim(); } public String getIdentityNo() { return identityNo; } public void setIdentityNo(String identityNo) { this.identityNo = identityNo == null ? null : identityNo.trim(); } public String getName() { return name; } public void setName(String name) { this.name = name == null ? null : name.trim(); } public String getHospitalCode() { return hospitalCode; } public void setHospitalCode(String hospitalCode) { this.hospitalCode = hospitalCode == null ? null : hospitalCode.trim(); } public String getHospitalName() { return hospitalName; } public void setHospitalName(String hospitalName) { this.hospitalName = hospitalName == null ? null : hospitalName.trim(); } public String getDeptCode() { return deptCode; } public void setDeptCode(String deptCode) { this.deptCode = deptCode == null ? null : deptCode.trim(); } public String getAuthorCode() { return authorCode; } public void setAuthorCode(String authorCode) { this.authorCode = authorCode == null ? null : authorCode.trim(); } public String getAuthorName() { return authorName; } public void setAuthorName(String authorName) { this.authorName = authorName == null ? null : authorName.trim(); } public String getDocStorageUnitCode() { return docStorageUnitCode; } public void setDocStorageUnitCode(String docStorageUnitCode) { this.docStorageUnitCode = docStorageUnitCode == null ? null : docStorageUnitCode.trim(); } public String getDocStorageUnitName() { return docStorageUnitName; } public void setDocStorageUnitName(String docStorageUnitName) { this.docStorageUnitName = docStorageUnitName == null ? null : docStorageUnitName.trim(); } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } public String getHiupStatus() { return hiupStatus; } public void setHiupStatus(String hiupStatus) { this.hiupStatus = hiupStatus == null ? null : hiupStatus.trim(); } public String getHiupInfo() { return hiupInfo; } public void setHiupInfo(String hiupInfo) { this.hiupInfo = hiupInfo == null ? null : hiupInfo.trim(); } public String getDocBase64Content() { return docBase64Content; } public void setDocBase64Content(String docBase64Content) { this.docBase64Content = docBase64Content; } public String getDocUrl() { return docUrl; } public void setDocUrl(String docUrl) { this.docUrl = docUrl; } public String getAdmissionDoctor() { return admissionDoctor; } public void setAdmissionDoctor(String admissionDoctor) { this.admissionDoctor = admissionDoctor; } public String getDocType() { return docType; } public void setDocType(String docType) { this.docType = docType; } public String getDocumentId() { return documentId; } public void setDocumentId(String documentId) { this.documentId = documentId; } }
true
7a4be0115f037a2e93e88c0af6f3b3d92843346b
Java
ghribacki/ludumdare24
/src/net/ghribacki/ld24/world/Tesselator.java
UTF-8
7,453
3.15625
3
[ "MIT" ]
permissive
package net.ghribacki.ld24.world; import java.util.ArrayList; import java.util.List; import java.util.Random; public class Tesselator { private float red; private float green; private float blue; public Tesselator() { // Decide planet's color! Random random = new Random(); this.red = 0.0f; this.green = 0.0f; this.blue = 0.0f; switch (random.nextInt(6)) { case 0: this.red += 0.2f; break; case 1: this.green += 0.2f; break; case 2: this.blue += 0.2f; break; case 3: this.red += 0.2f; this.green += 0.2f; break; case 4: this.red += 0.2f; this.blue += 0.2f; break; case 5: this.green += 0.2f; this.blue += 0.2f; break; } } /** Vertices **/ public List<Float> getPoint(float x, float y, float z) { ArrayList<Float> point = new ArrayList<Float>(); point.add(new Float(x)); // top right point.add(new Float(y)); point.add(new Float(z)); return point; } public List<Float> getPlain(float x0, float y0, float z0, float x1, float y1, float z1) { ArrayList<Float> quad = new ArrayList<Float>(); quad.addAll(this.getPoint(x1, y0, z0)); quad.addAll(this.getPoint(x0, y0, z0)); quad.addAll(this.getPoint(x0, y1, z1)); quad.addAll(this.getPoint(x1, y1, z1)); return quad; } public List<Float> getNorthSlope(int x, int y, float z0, float z1) { ArrayList<Float> quad = new ArrayList<Float>(); quad.addAll(this.getPoint(x, z0, y)); quad.addAll(this.getPoint(x, z0, y+1.0f)); quad.addAll(this.getPoint(x+0.1f, z1, y+0.9f)); quad.addAll(this.getPoint(x+0.1f, z1, y+0.1f)); return quad; } public List<Float> getEastSlope(int x, int y, float z0, float z1) { ArrayList<Float> quad = new ArrayList<Float>(); quad.addAll(this.getPoint(x, z0, y+1.0f)); quad.addAll(this.getPoint(x+1.0f, z0, y+1.0f)); quad.addAll(this.getPoint(x+0.9f, z1, y+0.9f)); quad.addAll(this.getPoint(x+0.1f, z1, y+0.9f)); return quad; } public List<Float> getSouthSlope(int x, int y, float z0, float z1) { ArrayList<Float> quad = new ArrayList<Float>(); quad.addAll(this.getPoint(x+1.0f, z0, y+1.0f)); quad.addAll(this.getPoint(x+1.0f, z0, y)); quad.addAll(this.getPoint(x+0.9f, z1, y+0.1f)); quad.addAll(this.getPoint(x+0.9f, z1, y+0.9f)); return quad; } public List<Float> getWestSlope(int x, int y, float z0, float z1) { ArrayList<Float> quad = new ArrayList<Float>(); quad.addAll(this.getPoint(x+1.0f, z0, y)); quad.addAll(this.getPoint(x, z0, y)); quad.addAll(this.getPoint(x+0.1f, z1, y+0.1f)); quad.addAll(this.getPoint(x+0.9f, z1, y+0.1f)); return quad; } public List<Float> getVertices(int type, int x, int y) { switch (type) { case 0: return getVerticesPlain(x, y); case 1: return getVerticesMountain(x, y); case 2: return getVerticesMountain(x, y); //return getVerticesWater(x, y); } return null; } private List<Float> getVerticesPlain(int x, int y) { ArrayList<Float> quad = new ArrayList<Float>(); quad.addAll(this.getPlain(x, 0.0f, y, 1.0f + x, 0.0f, 1.0f + y)); return quad; } private List<Float> getVerticesMountain(int x, int y) { ArrayList<Float> quad = new ArrayList<Float>(); quad.addAll(this.getPlain(x+0.1f, 0.4f, y+0.1f, 0.9f + x, 0.4f, 0.9f + y)); quad.addAll(this.getNorthSlope(x, y, 0.0f, 0.4f)); quad.addAll(this.getEastSlope(x, y, 0.0f, 0.4f)); quad.addAll(this.getSouthSlope(x, y, 0.0f, 0.4f)); quad.addAll(this.getWestSlope(x, y, 0.0f, 0.4f)); return quad; } /*private List<Float> getVerticesWater(int x, int y) { ArrayList<Float> quad = new ArrayList<Float>(); quad.addAll(this.getPlain(x+0.1f, -0.2f, y+0.1f, 0.9f + x, -0.2f, 0.9f + y)); quad.addAll(this.getNorthSlope(x, y, 0.0f, -0.2f)); quad.addAll(this.getEastSlope(x, y, 0.0f, -0.2f)); quad.addAll(this.getSouthSlope(x, y, 0.0f, -0.2f)); quad.addAll(this.getWestSlope(x, y, 0.0f, -0.2f)); return quad; }*/ /** Textures **/ /*public List<Float> getTextures(int type) { switch (type) { case 0: return getTexturesPlain(); case 1: return getTexturesMountain(); case 2: return getTexturesWater(); } return null; } private List<Float> getTexturesPlain() { ArrayList<Float> textures = new ArrayList<Float>(); // TODO Texture mapping... return textures; } private List<Float> getTexturesMountain() { ArrayList<Float> textures = new ArrayList<Float>(); // TODO Texture mapping... return textures; } private List<Float> getTexturesWater() { ArrayList<Float> textures = new ArrayList<Float>(); // TODO Texture mapping... return textures; }*/ /** Colors **/ public List<Float> getVertexColor(float red, float green, float blue) { ArrayList<Float> colors = new ArrayList<Float>(); colors.add(red); colors.add(green); colors.add(blue); colors.add(red); colors.add(green); colors.add(blue); colors.add(red); colors.add(green); colors.add(blue); colors.add(red); colors.add(green); colors.add(blue); return colors; } public List<Float> getColors(int type) { switch (type) { case 0: return getColorsPlain(); case 1: return getColorsMountain(); case 2: return getColorsMountainTurret(); //return getColorsWater(); } return null; } private List<Float> getColorsPlain() { ArrayList<Float> colors = new ArrayList<Float>(); Random random = new Random(); float rand = (random.nextFloat() / 10.0f) + 0.25f; //float rand = 2.0f / 10.0f; float red = rand + (this.red*2); float green = rand + this.green; float blue = rand + this.blue; colors.addAll(this.getVertexColor(red, green, blue)); return colors; } private List<Float> getColorsMountain() { ArrayList<Float> colors = new ArrayList<Float>(); Random random = new Random(); float rand = random.nextFloat() / 10.0f; //float rand = 1.0f / 10.0f; float red = rand + this.red; float green = rand + this.green; float blue = rand + this.blue; colors.addAll(this.getVertexColor(red+0.075f, green, blue)); colors.addAll(this.getVertexColor(red+0.05f, green, blue)); colors.addAll(this.getVertexColor(red+0.025f, green, blue)); colors.addAll(this.getVertexColor(red+0.05f, green, blue)); colors.addAll(this.getVertexColor(red+0.025f, green, blue)); return colors; } private List<Float> getColorsMountainTurret() { ArrayList<Float> colors = new ArrayList<Float>(); float red = 0.5f; float green = 0.1f; float blue = 0.1f; colors.addAll(this.getVertexColor(red+0.075f, green, blue)); colors.addAll(this.getVertexColor(red+0.05f, green, blue)); colors.addAll(this.getVertexColor(red+0.025f, green, blue)); colors.addAll(this.getVertexColor(red+0.05f, green, blue)); colors.addAll(this.getVertexColor(red+0.025f, green, blue)); return colors; } /*private List<Float> getColorsWater() { ArrayList<Float> colors = new ArrayList<Float>(); Random random = new Random(); float rand = random.nextFloat() / 10.0f; float red = rand; float green = rand; float blue = rand + 0.4f; colors.addAll(this.getVertexColor(red+0.075f, green, blue)); colors.addAll(this.getVertexColor(red+0.05f, green, blue)); colors.addAll(this.getVertexColor(red+0.025f, green, blue)); colors.addAll(this.getVertexColor(red+0.05f, green, blue)); colors.addAll(this.getVertexColor(red+0.025f, green, blue)); return colors; }*/ }
true
e06cb3508186d1da0323aef57f2a704e22159ab8
Java
MochHudda-TI-A-A2-1900106/TI-IA-Pert9-A2.1900106-MochHudda
/src/Latihan6/Mamalia.java
UTF-8
178
1.570313
2
[]
no_license
package Latihan6; /*Mochammad Hudda *TI-IA *STMIK Sumedang */ public class Mamalia { //variable jumlah kambing dideklarasikan sebagai statik public static int jumlahKambing; }
true
b92861b85961ca03decd7b4a4d4cc07c5a46ec74
Java
mohamedtaha251/FixStore
/app/src/main/java/nti/com/fixstore11/presenter/presenterImpl/signUpHandymanPresenterImp.java
UTF-8
517
2.234375
2
[]
no_license
package nti.com.fixstore11.presenter.presenterImpl; import nti.com.fixstore11.model.entities.HandyMan; import nti.com.fixstore11.model.remote.FireBase; import nti.com.fixstore11.presenter.presenter.MainPresenter; import nti.com.fixstore11.presenter.presenter.SignUpHandymanPresenter; public class signUpHandymanPresenterImp implements SignUpHandymanPresenter { @Override public void addHandyman(HandyMan handyMan) { FireBase fireBase=new FireBase(); fireBase.addHandyMan(handyMan); } }
true
64f5a187e4926079bc307fa0cbb27d6f6ea36eba
Java
johnsevillano/babylon
/services/java/Babylon.Services/Babylon.Services.Model/src/Babylon/Services/Repositories/NewsRepository.java
UTF-8
2,467
2.640625
3
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Babylon.Services.Repositories; import java.util.List; import java.util.ArrayList; import java.util.Iterator; import org.hibernate.Session; import org.hibernate.Query; import org.hibernate.Transaction; import Babylon.Services.Filters.NewsItemFilter; import Babylon.Services.Model.NewsItem; /** * * @author guille */ public class NewsRepository implements INewsRepository { public String add(NewsItem item) { Session session = HibernateUtil.getSessionFactory().openSession(); Transaction transaction = session.beginTransaction(); session.save(item); transaction.commit(); session.close(); return item.getId(); } public void update(NewsItem item) { Session session = HibernateUtil.getSessionFactory().openSession(); Transaction transaction = session.beginTransaction(); session.update(item); transaction.commit(); session.close(); } public void remove(NewsItem item) { Session session = HibernateUtil.getSessionFactory().openSession(); Transaction transaction = session.beginTransaction(); session.delete(item); transaction.commit(); session.close(); } public NewsItem getNewsItemByID(String id) { Session session = HibernateUtil.getSessionFactory().openSession(); Transaction transaction = session.beginTransaction(); NewsItem item = (NewsItem)session.get(NewsItem.class, id); transaction.commit(); session.close(); return item; } public List<NewsItem> getLatestNews(int count) { List<NewsItem> news = new ArrayList<NewsItem>(); Session session = HibernateUtil.getSessionFactory().openSession(); Transaction transaction = session.beginTransaction(); Query query = session.createQuery("from NewsItem ni order by ni.reportedOn desc"); query.setMaxResults(count); Iterator objects = query.list().iterator(); while (objects.hasNext()) { NewsItem item = (NewsItem)objects.next(); news.add(item); } transaction.commit(); session.close(); return news; } public List<NewsItem> searchNews(NewsItemFilter filter) { throw new UnsupportedOperationException("Not supported yet."); } }
true
ac359889593c4ce820611286fbf5a87358f9c8d5
Java
wjprakash/twproto
/src/com/nayaware/twproto/nodes/TwWorkspaceDirChildren.java
UTF-8
1,544
2.640625
3
[]
no_license
/* * TwWorkspaceDirChildren.java * Author - Winston Prakash */ package com.nayaware.twproto.nodes; import java.util.*; import java.io.*; import org.openide.nodes.*; public class TwWorkspaceDirChildren extends Children.Array { protected TwWorkspaceDirNode dirNode; protected boolean isExplored = false; public TwWorkspaceDirChildren() { } public void setWorkspaceDirNode(TwWorkspaceDirNode dNode) { dirNode = dNode; } protected void addNotify() { System.out.println("Add Notify Called"); if (!isExplored) { int i = 0; File dir = dirNode.getFile(); File[] files = dir.listFiles(); if (files != null) { HashSet children = new HashSet(); for (i = 0; i < files.length; i++) { if (files[i].isDirectory()) { if (!filterChild(files[i])) { children.add(new TwWorkspaceDirNode(dirNode .getWorkspace(), files[i].getAbsolutePath())); } } else { children.add(new TwFileNode(files[i].getAbsolutePath())); } } Node[] nodes = new Node[children.size()]; Iterator iter = children.iterator(); i = 0; while (iter.hasNext()) { nodes[i++] = (Node) iter.next(); } this.add(nodes); } } } protected boolean filterChild(File file) { String fileName = file.getName(); if (fileName.equals("Codemgr_wsdata")) return true; if (fileName.equals("SCCS")) return true; return false; } protected void removeNotify() { System.out.println("Remove Notify Called"); } }
true
2dd02c398f1a7fce50a99a478852f112252e3184
Java
mangohero1985/KGBuildFromJapaneseReview
/src/CombineSameElement/ExactHiragana.java
UTF-8
767
2.4375
2
[]
no_license
/** * */ package CombineSameElement; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import jp.uclab.io.IOhandle; /** * @author mangohero1985 * @create-time Aug 21, 2014 11:37:01 AM */ public class ExactHiragana { public void Exact(String inputString,String outputString ) throws IOException{ BufferedReader br = new IOhandle().FileReader(inputString); BufferedWriter bw = new IOhandle().FileWriter(outputString); String readStr = null; while((readStr= br.readLine())!=null){ String[] StrSplite = readStr.split("\t"); bw.write(StrSplite[1]); bw.newLine(); bw.flush(); } br.close(); bw.close(); } }
true
492f6d57fb7940794d62edd912af2bdcb4f3c387
Java
hadoop168/Contacts
/app/src/main/java/com/moriarty/user/contacts/Activity/MainView.java
UTF-8
250
1.664063
2
[]
no_license
package com.moriarty.user.contacts.Activity; /** * Created by user on 17-2-23. */ public interface MainView { void showToast(String s); void invalidate(); void enduePermission(String[] permission); void setCurrentItem(int flag); }
true
9b13789ac567fa00da4831bf17943be3e99596e0
Java
domhanak/AndroidProjectApp
/app/src/main/java/cz/muni/fi/pv256/movio/uco410430/network/Responses.java
UTF-8
962
2.328125
2
[]
no_license
package cz.muni.fi.pv256.movio.uco410430.network; import com.google.gson.annotations.SerializedName; import java.util.List; import cz.muni.fi.pv256.movio.uco410430.domain.Cast; import cz.muni.fi.pv256.movio.uco410430.domain.Movie; /** * Class defining responses for movies. * * Created by dhanak on 11/30/15. */ public class Responses { private Responses() {} public static class LoadMovieResponse { @SerializedName("results") public List<Movie> mMovies; public LoadMovieResponse(final List<Movie> movies) { mMovies = movies; } public List<Movie> getMovies() { return mMovies; } } public static class LoadCastResponse { @SerializedName("cast") public List<Cast> mCast; public LoadCastResponse(final List<Cast> cast) { mCast = cast; } public List<Cast> getCast() { return mCast; } } }
true
dbd1eaf40f0c694cb4ec4cd932bd0f8eb8c1a1be
Java
linkedin/rest.li
/d2/src/test/java/com/linkedin/d2/discovery/stores/zk/ZkConnectionBuilderTest.java
UTF-8
2,317
1.859375
2
[ "Apache-2.0" ]
permissive
/* Copyright (c) 2018 LinkedIn Corp. 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 com.linkedin.d2.discovery.stores.zk; import java.util.HashSet; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import org.testng.Assert; import org.testng.annotations.Test; public class ZkConnectionBuilderTest { @Test public void testBuilderEquality() { ZKConnectionBuilder builder1 = new ZKConnectionBuilder("localhost:2121"); ZKConnectionBuilder builder2 = new ZKConnectionBuilder("localhost:2121"); ZKConnectionBuilder builder3 = new ZKConnectionBuilder("localhost:2121"); ZKConnectionBuilder builder4 = new ZKConnectionBuilder("localhost:2121"); builder1.setInitInterval(20); builder1.setRetryLimit(10); builder1.setTimeout(100); builder1.setExponentialBackoff(true); builder1.setIsSymlinkAware(true); builder1.setShutdownAsynchronously(true); builder2.setInitInterval(20); builder2.setRetryLimit(10); builder2.setTimeout(100); builder2.setExponentialBackoff(true); builder2.setIsSymlinkAware(true); builder2.setShutdownAsynchronously(true); builder3.setInitInterval(20); builder3.setRetryLimit(10); builder3.setTimeout(100); builder3.setExponentialBackoff(true); builder3.setIsSymlinkAware(false); builder3.setShutdownAsynchronously(true); builder4.setInitInterval(20); builder4.setRetryLimit(10); builder4.setTimeout(100); builder4.setExponentialBackoff(false); builder4.setIsSymlinkAware(true); builder4.setShutdownAsynchronously(true); Set<ZKConnectionBuilder> set = new HashSet<>(); set.add(builder1); Assert.assertTrue(set.contains(builder2)); Assert.assertTrue(!set.contains(builder3)); Assert.assertTrue(!set.contains(builder4)); } }
true
075b3d4ae68922e750bd92d9142cacf8db750cdb
Java
Salvatore11/Java
/Esercizio 12/src/it/unip/informatica/esercizio12/database/DatabaseUtente.java
UTF-8
381
2.640625
3
[]
no_license
package it.unip.informatica.esercizio12.database; import it.unipr.informatica.esercizio12.modello.Utente; public class DatabaseUtente implements Utente{ String nome; public DatabaseUtente(String nome) { if(nome == null || "".equals(nome)) throw new IllegalArgumentException(); this.nome= nome; } @Override public String getNome() { return nome; } }
true
75393367ad2f5c7cb061ced775fc896ef4d4ed41
Java
natsu6991/je-re-decouvreMaLangue
/app/app/src/main/java/jrml/supinternet/com/jeredecouvremalangue/feature/word/WordAdapter.java
UTF-8
6,318
2.421875
2
[]
no_license
package jrml.supinternet.com.jeredecouvremalangue.feature.word; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.TextView; import java.util.ArrayList; import jrml.supinternet.com.jeredecouvremalangue.R; public class WordAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { private Word word; private String mCitationTextPlaceholder; private boolean isCitationVisible = false; private ArrayList<CitationViewHolder> mCitationViewHolders = new ArrayList<>(); // Provide a reference to the views for each data item // Complex data items may need more than one view per item, and // you provide access to all the views for a data item in a view holder public static class CitationViewHolder extends RecyclerView.ViewHolder { // each data item is just a string in this case public TextView citationText; public CitationViewHolder(View v) { super(v); citationText = v.findViewById(R.id.citationText); } public void hideCitations(){ int resId = R.anim.item_animation_walk_up; Animation animation = AnimationUtils.loadAnimation(this.itemView.getContext(), resId); this.itemView.setAnimation(animation); this.itemView.setVisibility(View.INVISIBLE); } public void hideCitations(Boolean withAnim){ if (withAnim){ int resId = R.anim.item_animation_walk_up; Animation animation = AnimationUtils.loadAnimation(this.itemView.getContext(), resId); this.itemView.setAnimation(animation); } this.itemView.setVisibility(View.INVISIBLE); } public void showCitations(){ int resId = R.anim.item_animation_fall_down; Animation animation = AnimationUtils.loadAnimation(this.itemView.getContext(), resId); this.itemView.setAnimation(animation); this.itemView.setVisibility(View.VISIBLE); } } // Provide a reference to the views for each data item // Complex data items may need more than one view per item, and // you provide access to all the views for a data item in a view holder public static class MainWordContentViewHolder extends RecyclerView.ViewHolder { private TextView nameText; private TextView descriptionText; private TextView switchCitation; // each data item is just a string in this case public MainWordContentViewHolder(View v) { super(v); setAttribute(v); //do some other things } private void setAttribute(View v){ nameText = v.findViewById(R.id.name); descriptionText = v.findViewById(R.id.description); switchCitation = v.findViewById(R.id.some_citation_link); } private void updateView(Word word){ nameText.setText(word.getName()); descriptionText.setText(word.getDescription()); } } // Provide a suitable constructor (depends on the kind of dataset) public WordAdapter(Word word, String citationTextPlaceholder) { this.word = word; mCitationTextPlaceholder = citationTextPlaceholder; } //invoked to get int viewType @Override public int getItemViewType(int position){ return position; } // Create new views (invoked by the layout manager) @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View v; if (viewType == 0){ // create a new view v = LayoutInflater.from(parent.getContext()) .inflate(R.layout.word_main_content, parent, false); // set the view's size, margins, paddings and layout parameters return new MainWordContentViewHolder(v); } // create a new view v = LayoutInflater.from(parent.getContext()) .inflate(R.layout.my_citation_view, parent, false); // set the view's size, margins, paddings and layout parameters return new CitationViewHolder(v); } // Replace the contents of a view (invoked by the layout manager) @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) { // - get element from your dataset at this position // - replace the contents of the view with that element if (holder.getItemViewType() == 0){ MainWordContentViewHolder currentViewHolder = (MainWordContentViewHolder) holder; currentViewHolder.updateView(word); currentViewHolder.switchCitation.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { isCitationVisible = !isCitationVisible; if (isCitationVisible){ for (CitationViewHolder mCitationViewHolder : mCitationViewHolders){ mCitationViewHolder.showCitations(); } }else{ for (CitationViewHolder mCitationViewHolder : mCitationViewHolders){ mCitationViewHolder.hideCitations(); } } } }); }else{ CitationViewHolder currentViewHolder = (CitationViewHolder) holder; currentViewHolder.citationText.setText(String.format(mCitationTextPlaceholder, word.getCitation().get(position - 1))); currentViewHolder.hideCitations(false); mCitationViewHolders.add(currentViewHolder); } } // Return the size of your dataset (invoked by the layout manager) @Override public int getItemCount() { return word.getCitation().size() + 1; } }
true
47d1ee3bbb0bd0c9969bca83063579b45b5d0fca
Java
AbhayaAdarsh/TY_CG_HTD_BANGLORENOVEMBER_JFS_ABHAYAADARSH
/Back End/Java1/hashset/src/HashSet2.java
UTF-8
430
3.46875
3
[]
no_license
import java.util.HashSet; import hashset.Student; public class HashSet2 { public static void main(String[] args) { HashSet<Student> hs=new HashSet<Student>(); hs.add(new Student(52,"Joey")); hs.add(new Student(50,"Chandler")); hs.add(new Student(52,"Joey")); hs.add(new Student(50,"Chandler")); for (Student s1 : hs) { System.out.println(s1.getName() + " and age is " +s1.getAge()); } } }
true
0804ea09017aaa83fdf9e3734d9eb46215de7330
Java
yysoft/yy-auth
/auth-dashboard/src/main/java/net/caiban/auth/dashboard/domain/staff/Staff.java
UTF-8
5,099
2.203125
2
[ "MIT" ]
permissive
/** * */ package net.caiban.auth.dashboard.domain.staff; import java.io.Serializable; import java.util.Date; /** * @author root * */ public class Staff implements Serializable { /** * 员工 */ private static final long serialVersionUID = 1L; private Integer id; private String account; private String staffNo;// 工作号 private String deptCode; private String name; private String email; private String sex;// 性别 private String avatar;// 图像 private Date birthday; private String jobs; private String status; private Date gmtEntry; private Date gmtLeft; private String note; private Date gmtCreated; private Date gmtModified; /** * */ public Staff() { super(); } /** * @param id * @param account * @param staffNo * @param deptCode * @param name * @param email * @param sex * @param avatar * @param birthday * @param jobs * @param status * @param gmtEntry * @param gmtLeft * @param note * @param gmtCreated * @param gmtModified */ public Staff(Integer id, String account, String staffNo, String deptCode, String name, String email, String sex, String avatar, Date birthday, String jobs, String status, Date gmtEntry, Date gmtLeft, String note, Date gmtCreated, Date gmtModified) { super(); this.id = id; this.account = account; this.staffNo = staffNo; this.deptCode = deptCode; this.name = name; this.email = email; this.sex = sex; this.avatar = avatar; this.birthday = birthday; this.jobs = jobs; this.status = status; this.gmtEntry = gmtEntry; this.gmtLeft = gmtLeft; this.note = note; this.gmtCreated = gmtCreated; this.gmtModified = gmtModified; } /** * @return the id */ public Integer getId() { return id; } /** * @param id * the id to set */ public void setId(Integer id) { this.id = id; } /** * @return the account */ public String getAccount() { return account; } /** * @param account * the account to set */ public void setAccount(String account) { this.account = account; } /** * @return the staffNo */ public String getStaffNo() { return staffNo; } /** * @param staffNo * the staffNo to set */ public void setStaffNo(String staffNo) { this.staffNo = staffNo; } /** * @return the deptCode */ public String getDeptCode() { return deptCode; } /** * @param deptCode * the deptCode to set */ public void setDeptCode(String deptCode) { this.deptCode = deptCode; } /** * @return the name */ public String getName() { return name; } /** * @param name * the name to set */ public void setName(String name) { this.name = name; } /** * @return the email */ public String getEmail() { return email; } /** * @param email * the email to set */ public void setEmail(String email) { this.email = email; } /** * @return the sex */ public String getSex() { return sex; } /** * @param sex * the sex to set */ public void setSex(String sex) { this.sex = sex; } /** * @return the avatar */ public String getAvatar() { return avatar; } /** * @param avatar * the avatar to set */ public void setAvatar(String avatar) { this.avatar = avatar; } /** * @return the birthday */ public Date getBirthday() { return birthday; } /** * @param birthday * the birthday to set */ public void setBirthday(Date birthday) { this.birthday = birthday; } /** * @return the jobs */ public String getJobs() { return jobs; } /** * @param jobs * the jobs to set */ public void setJobs(String jobs) { this.jobs = jobs; } /** * @return the status */ public String getStatus() { return status; } /** * @param status * the status to set */ public void setStatus(String status) { this.status = status; } /** * @return the gmtEntry */ public Date getGmtEntry() { return gmtEntry; } /** * @param gmtEntry * the gmtEntry to set */ public void setGmtEntry(Date gmtEntry) { this.gmtEntry = gmtEntry; } /** * @return the gmtLeft */ public Date getGmtLeft() { return gmtLeft; } /** * @param gmtLeft * the gmtLeft to set */ public void setGmtLeft(Date gmtLeft) { this.gmtLeft = gmtLeft; } /** * @return the note */ public String getNote() { return note; } /** * @param note * the note to set */ public void setNote(String note) { this.note = note; } /** * @return the gmtCreated */ public Date getGmtCreated() { return gmtCreated; } /** * @param gmtCreated * the gmtCreated to set */ public void setGmtCreated(Date gmtCreated) { this.gmtCreated = gmtCreated; } /** * @return the gmtModified */ public Date getGmtModified() { return gmtModified; } /** * @param gmtModified * the gmtModified to set */ public void setGmtModified(Date gmtModified) { this.gmtModified = gmtModified; } }
true
45adb7826088e8e68c6843f37e4fc714661fcad8
Java
cepardov/cms-be
/src/main/java/com/cepardov/cms/annotation/TimeExecutionMeasuring.java
UTF-8
309
1.867188
2
[]
no_license
package com.cepardov.cms.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface TimeExecutionMeasuring { }
true
2437773a021df541afef751ece956903b6972c2f
Java
senritsu/sRPG
/src/com/behindthemirrors/minecraft/sRPG/listeners/SpawnEventListener.java
UTF-8
2,487
2.359375
2
[]
no_license
package com.behindthemirrors.minecraft.sRPG.listeners; import java.util.ArrayList; import org.bukkit.World; import org.bukkit.entity.CreatureType; import org.bukkit.entity.Entity; import org.bukkit.entity.LivingEntity; import org.bukkit.event.entity.CreatureSpawnEvent; import org.bukkit.event.entity.EntityListener; import org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason; import com.behindthemirrors.minecraft.sRPG.SRPG; import com.behindthemirrors.minecraft.sRPG.Settings; import com.behindthemirrors.minecraft.sRPG.MiscBukkit; import com.behindthemirrors.minecraft.sRPG.dataStructures.EffectDescriptor; import com.behindthemirrors.minecraft.sRPG.dataStructures.ProfileNPC; public class SpawnEventListener extends EntityListener { // for testing static boolean spawnInvincible = false; public static ArrayList<int[]> depthTiers; public static boolean dangerousDepths; public void addExistingCreatures() { for (World world : SRPG.plugin.getServer().getWorlds()) { if (Settings.worldBlacklist.contains(world)) { continue; } for (Entity entity : world.getEntities()) { if (entity instanceof LivingEntity) { onCreatureSpawn(new CreatureSpawnEvent(entity,CreatureType.CHICKEN,entity.getLocation(), SpawnReason.NATURAL)); } } } } public void onCreatureSpawn(CreatureSpawnEvent event) { if (Settings.worldBlacklist.contains(event.getLocation().getWorld())) { return; } String creature = MiscBukkit.getEntityName(event.getEntity()); LivingEntity entity = (LivingEntity)event.getEntity(); // for testing if (Settings.mobs.containsKey(creature)) { ProfileNPC profile = SRPG.profileManager.get(entity); profile.currentJob = Settings.mobs.get(creature); if (profile.currentJob == null) { profile.currentJob = Settings.mobs.get("default"); SRPG.dout("Warning: could not find fitting job for "+creature); } profile.jobLevels.put(profile.currentJob, 1); // depth modifier if (dangerousDepths) { for (int[] data : SpawnEventListener.depthTiers) { if (entity.getLocation().getY() < (double)data[0]) { profile.jobLevels.put(profile.currentJob, 1+data[1]); } } } profile.recalculate(); entity.setHealth((int) profile.getStat("health")); } else { SRPG.output("Warning: spawned "+creature+", job not available"); } if (spawnInvincible) { SRPG.profileManager.get(entity).addEffect(Settings.passives.get("invincibility"), new EffectDescriptor(10)); } } }
true
3c10e97c6c86f02319296c9177579a393de7ba77
Java
Sorumi/Samurai
/src/view/TransitionPanel.java
UTF-8
478
2.78125
3
[]
no_license
package view; import javafx.animation.FadeTransition; import javafx.scene.layout.Pane; import javafx.util.Duration; public class TransitionPanel extends Pane { public TransitionPanel(){ this.setOpacity(0); } public void transitionAnimation(boolean isAppear){ FadeTransition ft = new FadeTransition(Duration.millis(200), this); if (isAppear){ ft.setFromValue(0); ft.setToValue(1); }else{ ft.setFromValue(1); ft.setToValue(0); } ft.play(); } }
true
2fa05a167ccf1760e74b5530cf66f75bd762d45d
Java
Yan-Song/burdakovd
/contests/Зимняя школа/F_1.java
UTF-8
1,877
3.21875
3
[]
no_license
import java.util.*; import java.io.FileReader; import java.io.FileWriter; import java.io.PrintWriter; import java.math.*; public class F_1 { static BigInteger binSqrt(BigInteger a){ BigInteger left = BigInteger.ONE; BigInteger right = a; while( right.subtract(left).compareTo(BigInteger.ONE) == 1 ) { BigInteger m = left.add(right).divide(new BigInteger("2")); BigInteger q = m.multiply(m); if(q.compareTo(a) == -1) { left = m; } else if(q.compareTo(a) == 1) { right = m; } else return m; } return new BigInteger("-1"); } static boolean ok(BigInteger a){ if(a.isProbablePrime(30)) return true; BigInteger b = binSqrt(a); // out.println(b); // out.flush(); if( (!b.equals(new BigInteger("-1"))) && (!b.equals(new BigInteger("2"))) && (b.isProbablePrime(30) == true)) return true; long ai = Long.parseLong(a.toString()); for(int i = 2; i < 1000000; ++i) if(ai % i == 0){ if(i == 2) return false; while(ai % i == 0 && ai != 1) ai /= i; return ai == 1; } return false; } static Scanner in; static PrintWriter out; public static void main(String[] args) throws Exception { in = new Scanner(new FileReader("f1.in")); out = new PrintWriter(new FileWriter("f1.out")); BigInteger a = in.nextBigInteger(); BigInteger orig = a; if(a.compareTo(new BigInteger("7")) == -1) { out.print(a.subtract(BigInteger.ONE)); out.close(); return; } if(a.mod(new BigInteger("2")).compareTo(new BigInteger("0"))==0){ a = a.divide(new BigInteger("2")); } if(ok(a)) out.print(orig.subtract(BigInteger.ONE)); else out.print("1"); out.flush(); out.close(); } }
true
75ddbe4e62aea20e46e807818135f83c198c8e56
Java
stephenh/jtty
/src/main/java/Jtty.java
UTF-8
3,061
2.46875
2
[ "Apache-2.0" ]
permissive
import java.util.HashSet; import javax.servlet.SessionTrackingMode; import org.eclipse.jetty.security.HashLoginService; import org.eclipse.jetty.server.Connector; import org.eclipse.jetty.server.HttpConfiguration; import org.eclipse.jetty.server.HttpConnectionFactory; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.ServerConnector; import org.eclipse.jetty.server.handler.ContextHandlerCollection; import org.eclipse.jetty.util.BlockingArrayQueue; import org.eclipse.jetty.util.thread.QueuedThreadPool; import org.eclipse.jetty.util.thread.ThreadPool; import org.eclipse.jetty.webapp.WebAppContext; /** A simple class for booting Jetty by pointing it at a war, with sane defaults. */ public class Jtty { public static void main(String[] args) throws Exception { if (args.length < 2) { System.err.println("Usage: java -jar jtty.jar <port> <locations>..."); System.err.println(" location = path/to/war | contextPath,path/to/war | virtualHost,contextPath,path/to/war"); return; } // I don't like sessions, but realistically most people probably use it boolean sessions = Boolean.valueOf(System.getProperty("jtty.sessions", "true")); ContextHandlerCollection handlers = new ContextHandlerCollection(); for (int i = 1; i < args.length; i++) { WebAppContext app = new WebAppContext(); String[] parts = args[i].split(","); if (parts.length == 1) { // just path/to/war, so assume root / app.setContextPath("/"); app.setWar(parts[0]); } else if (parts.length == 2) { // contextPath,path/to/war app.setContextPath(parts[0]); app.setWar(parts[1]); } else if (parts.length == 3) { // virtualHost,contextPath,path/to/war app.setVirtualHosts(new String[] { parts[0] }); app.setContextPath(parts[1]); app.setWar(parts[2]); } app.setMaxFormKeys(200); app.setMaxFormContentSize(10485760); // for large POST requests, 10mb app.getSecurityHandler().setLoginService(new HashLoginService()); app.setInitParameter("org.eclipse.jetty.servlet.Default.dirAllowed", "false"); app.setInitParameter("org.eclipse.jetty.servlet.Default.welcomeServlets", "true"); if (!sessions) { app.getSessionHandler().getSessionManager().setSessionTrackingModes(new HashSet<SessionTrackingMode>()); } handlers.addHandler(app); } ThreadPool pool = new QueuedThreadPool(// 200, // max threads 2, // min threads 60000, // idle time new BlockingArrayQueue<Runnable>(500)); // fixed queue size Server server = new Server(pool); HttpConfiguration config = new HttpConfiguration(); config.setSendServerVersion(false); ServerConnector connector = new ServerConnector(server, new HttpConnectionFactory(config)); connector.setPort(Integer.parseInt(args[0])); server.setConnectors(new Connector[] { connector }); server.setStopAtShutdown(true); server.setHandler(handlers); server.start(); } }
true
6e67c5fc602d58998a08f8e29cc2eaa0da9b4f9f
Java
ythalorossy/learning
/spring-dataflow/stream-functional/src/main/java/io/spring/stream/sample/streamfunctional/StreamFunctionalApplication.java
UTF-8
843
2.359375
2
[]
no_license
package io.spring.stream.sample.streamfunctional; import java.util.function.Consumer; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; @SpringBootApplication public class StreamFunctionalApplication { public static void main(String[] args) { SpringApplication.run(StreamFunctionalApplication.class, // "--spring.cloud.stream.function.routing.enabled=true", "--spring.cloud.function.routing-expression=T(java.lang.System).currentTimeMillis() % 2 == 0 ? 'even' : 'odd'"); } @Bean public Consumer<String> even() { return value -> { System.out.println("EVEN: " + value); }; } @Bean public Consumer<String> odd() { return value -> { System.out.println("ODD: " + value); }; } }
true
28897064152e2b37aacbf12cb54a748357ed92c2
Java
taseal/ZzFragmentTabHost
/app/src/main/java/me/zhouzhuo/zzfragmenttabhostdemo/MainActivity.java
UTF-8
2,304
1.898438
2
[]
no_license
package me.zhouzhuo.zzfragmenttabhostdemo; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import me.zhouzhuo.zzfragmenttabhost.ZzFragmentTabHost; import me.zhouzhuo.zzfragmenttabhost.ZzTab; public class MainActivity extends AppCompatActivity { private ZzFragmentTabHost zth; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); zth = (ZzFragmentTabHost) findViewById(R.id.zft); zth.initTabsWithCount(4); zth.setOnTabClickListener(new ZzFragmentTabHost.OnTabClickListener() { @Override public void onTabClick(ZzTab tab, boolean changed, int position) { Log.e("eee", changed + "," + position); } }); zth.setSelection(0); } public void orderPic(View v) { zth.setImagePressIds(R.drawable.mainicon_checked, R.drawable.mainicon_checked, R.drawable.mainicon_checked, R.drawable.mainicon_checked); zth.setImageNormalIds(R.drawable.mainicon_normal, R.drawable.mainicon_normal, R.drawable.mainicon_normal, R.drawable.mainicon_normal); } public void reorderPic(View v) { zth.setImageNormalIds(R.drawable.mainicon_checked, R.drawable.mainicon_checked, R.drawable.mainicon_checked, R.drawable.mainicon_checked); zth.setImagePressIds(R.drawable.mainicon_normal, R.drawable.mainicon_normal, R.drawable.mainicon_normal, R.drawable.mainicon_normal); } public void updateName(View v) { zth.setTabNameWithResId(R.array.tab_names); } public void showMark(View v) { zth.showMarkAll(); } public void hideMark(View v) { zth.hideMarkAll(); } public void hideMarkOne(View v) { zth.hideMarkAt(0); } public void changeMarkValue(View v) { zth.setMarkNumberAll(99); } public void changeMarkValueOne(View v) { zth.setMarkNumberAt(1, 100); } public void fgm(View v) { Intent intent = new Intent(MainActivity.this, SecondActivity.class); startActivity(intent); } }
true