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
8053021960bbe4813a901f157fd0c7a334680222
Java
ymzdb7/test2
/canteen/src/main/java/com/winhands/modules/restaurant/service/impl/OderAdvanceDishesServiceImpl.java
UTF-8
1,783
1.773438
2
[]
no_license
package com.winhands.modules.restaurant.service.impl; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.winhands.modules.restaurant.dao.OrderAdvanceDishesDao; import com.winhands.modules.restaurant.entity.AdDishesHeEntity; import com.winhands.modules.restaurant.entity.OrderAdvanceDishesEntity; import com.winhands.modules.restaurant.service.OrderAdvanceDishesService; /** * 菜品类型管理 */ @Service("OrderAdvanceDishesService") public class OderAdvanceDishesServiceImpl implements OrderAdvanceDishesService { @Autowired private OrderAdvanceDishesDao orderAdvanceDishesDao; @Override public List<OrderAdvanceDishesEntity> queryList(Map<String, Object> map) { return orderAdvanceDishesDao.queryList(map); } @Override public int queryTotal(Map<String, Object> map) { return orderAdvanceDishesDao.queryTotal(map); } @Override public void save(OrderAdvanceDishesEntity orderAdvanceDishes) { orderAdvanceDishesDao.save(orderAdvanceDishes); } @Override public void update(OrderAdvanceDishesEntity orderAdvanceDishes) { orderAdvanceDishesDao.update(orderAdvanceDishes); } @Override public void deleteBatch(Long[] ids) { orderAdvanceDishesDao.deleteBatch(ids); } @Override public OrderAdvanceDishesEntity queryObject(Long id) { return orderAdvanceDishesDao.queryObject(id); } @Override public OrderAdvanceDishesEntity queryObject(Map<String, Object> map) { // TODO Auto-generated method stub return orderAdvanceDishesDao.queryObject(map); } @Override public List<AdDishesHeEntity> queryListG(Map<String, Object> map) { // TODO Auto-generated method stub return orderAdvanceDishesDao.queryListG(map); } }
true
1c6d1fa2c0fc3b92724bbec9c3452655ce11b6d4
Java
181182/INF142-Computer-Networks
/Oblig1/src/Oppgave2/K.java
UTF-8
3,141
3.46875
3
[]
no_license
package Oppgave2; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; import java.net.UnknownHostException; /** * Dette er en klient til applikasjonprotokolen mellom klient og en web proxy * server. * * @author Magnus Ødegård Bergersen (huh007) og Jacob Ås (jaa093) * */ public class K { public static void main(String args[]) { /** * Her initialiserer vi alle hjelpeklassene som blir brukt i klassen. */ DatagramSocket klientSocket = null; InetAddress IPaddresse = null; /** * Setter hvor mange bytes vi skal reservere til å sende og motta pakker */ byte[] motattData = new byte[10240]; byte[] sendData = new byte[10240]; /** * Vi setter IP og Port til WPS. Setter hvilken url som skal sendes til WPS. */ String IP = "10.0.0.135"; int Port = 8887; String URL = "https://example.com"; /** * Her fører du inn IP-addresse til WPS. Tester om IP'en er en gyldig addresse */ try { IPaddresse = InetAddress.getByName(IP); } catch (UnknownHostException e1) { System.out.println("Ugyldig IP-addresse"); Thread.currentThread().interrupt(); return; } /** * Oppretting av DatagramSocket, og kobler til WPS med tilhørende IP og Port. * Her velger vi å bruke samme port som WPS. Connect-metoden kobler seg til WPS * serveren og gjør det slik at K ikke kan motta data fra andre uønskede * enheter. * */ try { klientSocket = new DatagramSocket(Port); } catch (SocketException e1) { System.out.println("Det oppstod en feil ved oppretting av DatagramSocket"); Thread.currentThread().interrupt(); return; } klientSocket.connect(IPaddresse, Port); /** * Gjør URL strengen om til bytes. sendPacket pakker inn data den skal sende * samt IP og Port slik at pakken kan ankomme rett enhet. Sender URL i bytes med * eventuelt stinavn til WPSen med UDP sockets. */ try { sendData = URL.getBytes(); DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPaddresse, Port); klientSocket.send(sendPacket); } catch (IOException e) { System.out.println("Klarte ikke å sende pakken. Har du brukt ugyldig port?"); klientSocket.close(); Thread.currentThread().interrupt(); return; } /** * Mottar vi pakke fra WPS som skal inneholde headerinformasjonen til URL vi * sendte. Til slutt printer vi ut det vi har fått fra WPS Vi gir WPS 10 * sekunder på å sende en pakke tilbake, dette vil forhindre at hvis pakketap * oppstår vil K ikke vente for alltid * */ DatagramPacket mottaPakke = new DatagramPacket(motattData, motattData.length); System.out.println("Venter på pakke"); try { klientSocket.setSoTimeout(10000); klientSocket.receive(mottaPakke); String setning = new String(mottaPakke.getData()); System.out.println(setning); } catch (IOException e) { System.out.println("Mottok ingen pakke fra " + IPaddresse); klientSocket.close(); Thread.currentThread().interrupt(); return; } klientSocket.close(); // Her lukker vi Socket } }
true
77f5a81fd041b2f9af8a0eed84911a2ff24ecb2d
Java
DroidSingh89/MAC_Training
/8.28/Week 4/FIrebase/app/src/main/java/com/example/user/firebase/view/MovieActivity.java
UTF-8
5,186
2.28125
2
[]
no_license
package com.example.user.firebase.view; import android.content.Intent; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.View; import android.widget.EditText; import android.widget.Toast; import com.example.user.firebase.R; import com.example.user.firebase.model.Movie; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import java.util.ArrayList; import java.util.List; public class MovieActivity extends AppCompatActivity { private static final String TAG = "MovieActivityTag"; private String uid; private FirebaseDatabase database; private DatabaseReference myRefUsers; private EditText etMovieName; private EditText etMovieYear; private EditText etMovieDirector; private FirebaseUser user; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_movie); etMovieName = (EditText) findViewById(R.id.etMovieName); etMovieYear = (EditText) findViewById(R.id.etMovieYear); etMovieDirector = (EditText) findViewById(R.id.etMovieDirector); user = FirebaseAuth.getInstance().getCurrentUser(); if (user != null) { // The user's ID, unique to the Firebase project. Do NOT use this value to // authenticate with your backend server, if you have one. Use // FirebaseUser.getToken() instead. uid = user.getUid(); } database = FirebaseDatabase.getInstance(); myRefUsers = database.getReference("users"); } public void addMovie(View view) { String movieName = etMovieName.getText().toString(); String movieDirector = etMovieDirector.getText().toString(); String movieYear = etMovieYear.getText().toString(); Movie movie = new Movie(movieName, movieDirector, movieYear); myRefUsers .child(uid) .child("movies") .push() .setValue(movie) .addOnSuccessListener(this, new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { Toast.makeText(MovieActivity.this, "Movie was added", Toast.LENGTH_SHORT).show(); } }) .addOnFailureListener(this, new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Toast.makeText(MovieActivity.this, "Not added, check logs", Toast.LENGTH_SHORT).show(); Log.d(TAG, "onFailure: " + e.toString()); } }); } public void signOut(View view) { FirebaseAuth.getInstance().signOut(); user = FirebaseAuth.getInstance().getCurrentUser(); if (user != null) { Toast.makeText(this, "User not signed out", Toast.LENGTH_SHORT).show(); } else { Intent intent = new Intent(this, MainActivity.class); startActivity(intent); } } public void getMovies(View view) { final List<Movie> movies = new ArrayList<>(); myRefUsers = database.getReference("users"); // Read from the database myRefUsers.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { // This method is called once with the initial value and again // whenever data at this location is updated. boolean hasChildren = dataSnapshot .child(uid) .child("movies") .hasChildren(); if (hasChildren) { Log.d(TAG, "onDataChange: " + dataSnapshot.getChildrenCount()); for (DataSnapshot snapshot : dataSnapshot .child(uid) .child("movies") .getChildren()) { Movie movie = snapshot.getValue(Movie.class); Log.d(TAG, "onDataChange: " + movie.toString()); movies.add(movie); } } } @Override public void onCancelled(DatabaseError error) { // Failed to read value Log.w(TAG, "Failed to read value.", error.toException()); } }); Log.d(TAG, "getMovies: "+ movies.size()); } }
true
8eb7db987f8465fdf49842377741516b8c0429c6
Java
parang0626/intern.sns
/src/main/java/sns/platform/comm/util/ShowMapUtil.java
UTF-8
619
2.53125
3
[]
no_license
package sns.platform.comm.util; import java.util.Iterator; import java.util.Map; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ShowMapUtil { private static final Logger LOG = LoggerFactory.getLogger(ShowMapUtil.class); public static void show(Map<String,Object> map){ LOG.info("=========ShowMapUtil Start=========="); Set keySet = map.keySet(); Iterator<String> it = keySet.iterator(); String key; while(it.hasNext()){ key = it.next(); LOG.info("= "+key+" : "+map.get(key).toString()); } LOG.info("=========ShowMapUtil End============"); } }
true
50ad99b9b461111feefa6a7eccc60df9e5f67aaa
Java
dhatric/SDE
/src/com/dhatric/trees/CloneTargetRecurive.java
UTF-8
584
3.203125
3
[]
no_license
package com.dhatric.trees; public class CloneTargetRecurive { public final TreeNode getTargetCopy(final TreeNode original, final TreeNode cloned, final TreeNode target) { return getNode(cloned, target); } TreeNode getNode(TreeNode node, TreeNode target) { TreeNode clonedTarget = null; if (node.val == target.val) { clonedTarget = node; } else { if (node.left != null) { clonedTarget = getNode(node.left, target); } if (clonedTarget == null && node.right != null) { clonedTarget = getNode(node.right, target); } } return clonedTarget; } }
true
750c45cf4c6fa6e7f9e552984053c7b3bce2acab
Java
EMResearch/EMB
/jdk_8_maven/cs/rest-gui/genome-nexus/web/src/main/java/org/cbioportal/genome_nexus/web/mixin/ExonMixin.java
UTF-8
896
1.960938
2
[ "Apache-2.0", "GPL-1.0-or-later", "LGPL-2.0-or-later", "MIT" ]
permissive
package org.cbioportal.genome_nexus.web.mixin; import com.fasterxml.jackson.annotation.JsonInclude; import io.swagger.annotations.ApiModelProperty; @JsonInclude(JsonInclude.Include.NON_NULL) public class ExonMixin { @ApiModelProperty(value = "Exon id", position=1, required = true) private String exonId; @ApiModelProperty(value = "Start position of exon", position=2, required = true) private String exonStart; @ApiModelProperty(value = "End position of exon", position=3, required = true) private String exonEnd; @ApiModelProperty(value = "Number of exon in transcript", position=4, required = true) private String rank; @ApiModelProperty(value = "Strand exon is on, -1 for - and 1 for +", position=5, required = true) private String strand; @ApiModelProperty(value = "Exon version", position=6, required = true) private String version; }
true
f9927fb3ab68dc94ae58fd7f172d124ea3da9e5c
Java
tomdev2008/RestyPass
/demo/src/main/java/com/github/df/restypass/testclient/entity/Response.java
UTF-8
773
2.171875
2
[ "Apache-2.0" ]
permissive
package com.github.df.restypass.testclient.entity; /** * Created by darrenfu on 17-4-1. * * @param <T> the type parameter */ public class Response<T> { /** * The Info. */ T info; /** * Gets info. * * @return the info */ public T getInfo() { return info; } /** * Sets info. * * @param info the info */ public void setInfo(T info) { this.info = info; } /** * Gets code. * * @return the code */ public String getCode() { return code; } /** * Sets code. * * @param code the code */ public void setCode(String code) { this.code = code; } /** * The Code. */ String code; }
true
7864963e0b13b719cdf18fd10b0535cfa1e84087
Java
margge/github-jobs
/android-app/src/com/github/jobs/ui/fragment/SOUserFetcherReceiver.java
UTF-8
3,329
1.921875
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2012 CodeSlap * * 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.github.jobs.ui.fragment; import android.content.Context; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.util.Log; import android.view.inputmethod.InputMethodManager; import android.widget.Toast; import com.actionbarsherlock.app.SherlockFragmentActivity; import com.codeslap.groundy.ReceiverFragment; import com.github.jobs.R; import com.github.jobs.bean.SOUser; import com.github.jobs.resolver.StackOverflowUserResolver; import com.github.jobs.utils.AppUtils; import java.util.ArrayList; public class SOUserFetcherReceiver extends ReceiverFragment { @Override protected void onError(Bundle resultData) { super.onError(resultData); FragmentActivity activity = getActivity(); if (activity == null || !isAdded()) { return; } if (!AppUtils.isOnline(activity)) { Toast.makeText(activity, R.string.error_fetching_search_result_network, Toast.LENGTH_LONG).show(); } else { Toast.makeText(activity, R.string.error_fetching_search_result, Toast.LENGTH_LONG).show(); } } @Override protected void onFinished(Bundle resultData) { super.onFinished(resultData); FragmentManager fragmentManager = getFragmentManager(); Fragment fragment = fragmentManager.findFragmentById(R.id.base_container); if (fragment instanceof SOUserPickerFragment) { SOUserPickerFragment soUserPickerFragment = (SOUserPickerFragment) fragment; ArrayList<SOUser> users = resultData.getParcelableArrayList(StackOverflowUserResolver.RESULT_USERS); soUserPickerFragment.updateItems(users); } else { Log.wtf("FragmentReceiver", "The fragment isn't an instance of SOUserFetcherReceiver"); } } @Override protected void onProgressChanged(boolean running) { FragmentActivity activity = getActivity(); if (activity == null) { return; } ((SherlockFragmentActivity) activity).setSupportProgressBarIndeterminateVisibility(running); InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE); if (running) { FragmentManager manager = getFragmentManager(); Fragment fragmentById = manager.findFragmentById(R.id.base_container); if (fragmentById instanceof SOUserPickerFragment) { SOUserPickerFragment pickerFragment = (SOUserPickerFragment) fragmentById; imm.hideSoftInputFromWindow(pickerFragment.getWindowToken(), 0); } } } }
true
736c5912dd95c2d53d3ffbccae32f55968e906b6
Java
imqinbao/javabb-security
/src/main/java/cn/javabb/sys/service/impl/DictionaryDataServiceImpl.java
UTF-8
1,618
1.984375
2
[]
no_license
package cn.javabb.sys.service.impl; import cn.javabb.common.web.PageParam; import cn.javabb.sys.entity.DictionaryDataDO; import cn.javabb.sys.mapper.DictionaryDataMapper; import cn.javabb.sys.service.DictionaryDataService; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import org.springframework.stereotype.Service; import java.util.List; import java.util.Map; /** * 字典项服务实现类 */ @Service public class DictionaryDataServiceImpl extends ServiceImpl<DictionaryDataMapper, DictionaryDataDO> implements DictionaryDataService { @Override public List<DictionaryDataDO> listPage(PageParam<DictionaryDataDO> page) { return baseMapper.listPage(page); } @Override public List<DictionaryDataDO> listAll(Map<String, Object> page) { return baseMapper.listAll(page); } @Override public List<DictionaryDataDO> listByDictCode(String dictCode) { PageParam<DictionaryDataDO> pageParam = new PageParam<>(); pageParam.put("dictCode", dictCode).setDefaultOrder(new String[]{"sort_number"}, null); List<DictionaryDataDO> records = baseMapper.listAll(pageParam.getNoPageParam()); return pageParam.sortRecords(records); } @Override public DictionaryDataDO listByDictCodeAndName(String dictCode, String dictDataName) { PageParam<DictionaryDataDO> pageParam = new PageParam<>(); pageParam.put("dictCode", dictCode).put("dictDataName", dictDataName); List<DictionaryDataDO> records = baseMapper.listAll(pageParam.getNoPageParam()); return pageParam.getOne(records); } }
true
354e8c5d12b59e8ec6fb4afb3ead9643bed70161
Java
josedab/code-miscellaneous
/video-service/video-service-app/src/main/java/com/josedab/video/domain/Video.java
UTF-8
1,154
2.25
2
[ "MIT" ]
permissive
package com.josedab.video.domain; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity public class Video { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String title; private String description; private String provider; private String identifier; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getProvider() { return provider; } public void setProvider(String provider) { this.provider = provider; } public String getIdentifier() { return identifier; } public void setIdentifier(String identifier) { this.identifier = identifier; } }
true
a0363ef4cd9f54a0499e8805fd67229f9b05013c
Java
WigerCheng/Dagger
/src/main/java/dagger/UserCommandsRouter.java
UTF-8
422
1.84375
2
[]
no_license
package dagger; @PerSession @Subcomponent(modules = {UserCommandsModule.class, AmountsModule.class, AccountModule.class}) public interface UserCommandsRouter { CommandRouter router(); @Subcomponent.Factory interface Factory { UserCommandsRouter create(@BindsInstance @Username String username); } @Module(subcomponents = UserCommandsRouter.class) interface InstallationModule { } }
true
6a81af389175d0df8519003d806c01e11d496829
Java
netikras/StudentBuddy
/api/api-private/src/main/java/com/netikras/studies/studentbuddy/api/aop/pointcuts/AuthorizableActions.java
UTF-8
631
1.773438
2
[]
no_license
package com.netikras.studies.studentbuddy.api.aop.pointcuts; import com.netikras.studies.studentbuddy.core.data.meta.annotations.Authorizable; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; import org.springframework.stereotype.Component; @Aspect @Component public class AuthorizableActions { // @Pointcut("execution(public * com.netikras.studies.studentbuddy..*.*(..)) && @annotation(authorizable)") @Pointcut("execution(* com.netikras.studies.studentbuddy..*.*(..)) && @annotation(authorizable)") public void authorizableMethods(final Authorizable authorizable) { } }
true
3142fd09d782c8ed7feaebbef65935cf24ae4304
Java
ufochuxian/PoupoLayer
/poplayer/src/main/java/com/github/codesniper/poplayer/webview/impl/HybirdImpl.java
UTF-8
3,414
2.21875
2
[ "MIT", "Apache-2.0" ]
permissive
package com.github.codesniper.poplayer.webview.impl; import android.content.Context; import android.net.Uri; import android.text.TextUtils; import android.util.Log; import android.webkit.WebView; import android.widget.Toast; import com.github.codesniper.poplayer.custom.PopWebView; import com.github.codesniper.poplayer.util.PopUtils; import com.github.codesniper.poplayer.webview.inter.HybirdManager; import com.github.codesniper.poplayer.webview.service.PopWebViewService; import org.json.JSONObject; import java.lang.reflect.Method; import java.net.URI; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.regex.Pattern; import static com.github.codesniper.poplayer.config.LayerConfig.POP_TAG; /** * Poplayer默认的交互机制 */ public class HybirdImpl implements HybirdManager { private Context mContext; @Override public void injectJsBridge(WebView webView,String JsName) { webView.loadUrl("javascript:" + PopUtils.getJsCode(webView.getContext(),JsName)); mContext=webView.getContext(); Log.d(POP_TAG,"注入JSBrige成功"); } /** * 进来的入口 3个 1.原生2.jsprompt 3.post请求拦截 * @param instruction */ @Override public void invokeAppServices(String instruction) { //如果格式为路由形式 Uri uri=Uri.parse(instruction); //{"invokeId":"name_2_1549953808581","methodName":"name","methodParams":"123"} //解析 //hrzapi.invoke("printService",{'name':'123','param1':'123'}); if(TextUtils.isEmpty(instruction)){ return; } Log.d(POP_TAG,"接收到指令"+instruction); Toast.makeText(mContext,"指令:"+instruction,Toast.LENGTH_SHORT).show(); try{ PopWebViewService popWebViewService=null; JSONObject jsonObject = new JSONObject(instruction.substring(instruction.indexOf("{"), instruction.lastIndexOf("}") + 1)); String invokeId=jsonObject.getString("invokeId"); String methodName = jsonObject.getString("methodName"); // String android_methodName = methodName.split(Pattern.quote("."))[1]; JSONObject paramObject = jsonObject.getJSONObject("methodParams"); Iterator iterator = paramObject.keys(); Map map = new HashMap(); while (iterator.hasNext()) { String key = (String) iterator.next(); map.put(key, paramObject.getString(key)); } map.put("invokeId",invokeId); // map.put("context", BrowserActivity.this); // map.put("webview",webView); //前端调原生 方法集合类 Class<PopWebViewService> invokeMethodObject = (Class<PopWebViewService>) Class.forName(PopWebViewService.class.getName()); if (invokeMethodObject != null) { popWebViewService = invokeMethodObject.newInstance(); } if (invokeMethodObject != null) { Method repay1 = invokeMethodObject.getDeclaredMethod(methodName, Map.class); if (repay1 != null&& popWebViewService!=null) { repay1.setAccessible(true); repay1.invoke(popWebViewService, map); } } }catch (Exception e){ e.printStackTrace(); } } }
true
ac6777e9cd0b24a3cbc8cd6885a6c82fcfbc2701
Java
sachin-kumbhar-jiem/saiten_test
/WEB-INF/src/com/saiten/action/ConfirmScoreAction.java
UTF-8
7,233
1.875
2
[]
no_license
package com.saiten.action; import java.util.Date; import java.util.LinkedHashMap; import java.util.Map; import org.apache.log4j.Logger; import org.apache.struts2.interceptor.SessionAware; import com.opensymphony.xwork2.ActionSupport; import com.saiten.exception.SaitenRuntimeException; import com.saiten.info.AnswerInfo; import com.saiten.info.GradeInfo; import com.saiten.info.MstScorerInfo; import com.saiten.info.QuestionInfo; import com.saiten.info.TranDescScoreInfo; import com.saiten.service.ConfirmScoreService; import com.saiten.util.ErrorCode; import com.saiten.util.SaitenUtil; import com.saiten.util.WebAppConst; /** * @author sachin * @version 1.0 * @created 13-Dec-2012 11:53:11 AM */ public class ConfirmScoreAction extends ActionSupport implements SessionAware { private static Logger log = Logger .getLogger(ConfirmScoreAction.class); /** * */ private static final long serialVersionUID = 1L; private String checkPoint; private String scorerComment; private ConfirmScoreService confirmScoreService; private Map<String, Object> session; private Map<String, Object> result; private boolean bookMarkFlag; private String approveOrDeny; private boolean qualityCheckFlag; private Integer denyCategorySeq; public String confirmScore() { try { if (session.get("scorerInfo") == null) { // Return statusCode as a JSON response for invalid session result = SaitenUtil.getAjaxCallStatusCode(session); return SUCCESS; } // Calculate bitValue from selected check points int bitValue = confirmScoreService.calculateBitValue(checkPoint); QuestionInfo questionInfo = (QuestionInfo) session .get("questionInfo"); Integer questionSeq = null; String menuId = questionInfo.getMenuId(); TranDescScoreInfo tranDescScoreInfo = (TranDescScoreInfo) session .get("tranDescScoreInfo"); Integer historySeq = tranDescScoreInfo.getAnswerInfo() .getHistorySeq(); if ((menuId .equals(WebAppConst.SPECIAL_SCORING_OMR_READ_FAIL_MENU_ID) || menuId .equals(WebAppConst.SPECIAL_SCORING_ENLARGE_TYPE_MENU_ID)) && (historySeq != null)) { questionSeq = tranDescScoreInfo.getAnswerInfo() .getQuestionSeq(); } else { questionSeq = questionInfo.getQuestionSeq(); } // Find grade and result from calculated bitValue and questionSeq GradeInfo gradeInfo = confirmScoreService.findGradeAndResult( bitValue, questionSeq); // build GradeInfo result to be returned buildGradeResultMap(gradeInfo); // put GradeInfo object, scorerComment and bitValue in session buildSessionInfo(gradeInfo, bitValue, menuId); } catch (SaitenRuntimeException we) { MstScorerInfo scorerInfo = ((MstScorerInfo) session .get("scorerInfo")); QuestionInfo questionInfo = (QuestionInfo) session .get("questionInfo"); TranDescScoreInfo tranDescScoreInfo = (TranDescScoreInfo) session .get("tranDescScoreInfo"); log.error(scorerInfo.getScorerId()+"-"+questionInfo.getMenuId()+"-"+"\n"+"TranDescScoreInfo: "+tranDescScoreInfo + we); throw we; } catch (Exception e) { MstScorerInfo scorerInfo = ((MstScorerInfo) session .get("scorerInfo")); QuestionInfo questionInfo = (QuestionInfo) session .get("questionInfo"); TranDescScoreInfo tranDescScoreInfo = (TranDescScoreInfo) session .get("tranDescScoreInfo"); log.error(scorerInfo.getScorerId()+"-"+questionInfo.getMenuId()+"-"+"\n"+"TranDescScoreInfo: "+tranDescScoreInfo); throw new SaitenRuntimeException( ErrorCode.CONFIRM_SCORE_ACTION_EXCEPTION, e); } return SUCCESS; } /** * * @param gradeInfo */ private void buildGradeResultMap(GradeInfo gradeInfo) { result = new LinkedHashMap<String, Object>(); Map<String, Object> root = new LinkedHashMap<String, Object>(); root.put("gradeNum", gradeInfo.getGradeNum()); root.put("gradeResult", gradeInfo.getResult()); root.put("approveOrDeny", approveOrDeny); result.put("result", root); } /** * * @param gradeInfo * @param bitValue */ private void buildSessionInfo(GradeInfo gradeInfo, int bitValue, String menuId) { session.put("gradeInfo", gradeInfo); log.info(menuId + "-" + "Grade Info in session" + "-{ "+ gradeInfo.getGradeSeq() +", Grade Num: " + gradeInfo.getGradeNum() +", Bit Value calculated by checkpoints: " + bitValue + ", Timestamp: "+new Date().getTime()+"}"); TranDescScoreInfo tranDescScoreInfo = (TranDescScoreInfo) session .get("tranDescScoreInfo"); AnswerInfo answerInfo = tranDescScoreInfo.getAnswerInfo(); answerInfo .setBookMarkFlag(bookMarkFlag == WebAppConst.TRUE ? WebAppConst.BOOKMARK_FLAG_TRUE : WebAppConst.BOOKMARK_FLAG_FALSE); if (menuId.equals(WebAppConst.FIRST_SCORING_QUALITY_CHECK_MENU_ID) || menuId.equals(WebAppConst.FORCED_MENU_ID)) { answerInfo .setQualityCheckFlag(qualityCheckFlag == WebAppConst.TRUE ? WebAppConst.QUALITY_MARK_FLAG_TRUE : WebAppConst.QUALITY_MARK_FLAG_FALSE); } answerInfo.setScorerComment(scorerComment); answerInfo.setBitValue((double) bitValue); tranDescScoreInfo.setAnswerInfo(answerInfo); session.put("tranDescScoreInfo", tranDescScoreInfo); session.put("approveOrDeny", approveOrDeny); } public String getScorerComment() { return scorerComment; } /** * * @param scorerComment */ public void setScorerComment(String scorerComment) { this.scorerComment = scorerComment; } public boolean isBookMarkFlag() { return bookMarkFlag; } /** * * @param bookMarkFlag */ public void setBookMarkFlag(boolean bookMarkFlag) { this.bookMarkFlag = bookMarkFlag; } public Map<String, Object> getResult() { return result; } /** * * @param result */ public void setResult(Map<String, Object> result) { this.result = result; } public String getCheckPoint() { return checkPoint; } /** * * @param checkPoint */ public void setCheckPoint(String checkPoint) { this.checkPoint = checkPoint; } /** * * @param confirmScoreService */ public void setConfirmScoreService(ConfirmScoreService confirmScoreService) { this.confirmScoreService = confirmScoreService; } /** * * @param session */ @Override public void setSession(Map<String, Object> session) { this.session = session; } public String getApproveOrDeny() { return approveOrDeny; } /** * @param approveOrDeny */ public void setApproveOrDeny(String approveOrDeny) { this.approveOrDeny = approveOrDeny; } /** * @return the qualityCheckFlag */ public boolean isQualityCheckFlag() { return qualityCheckFlag; } /** * @param qualityCheckFlag * the qualityCheckFlag to set */ public void setQualityCheckFlag(boolean qualityCheckFlag) { this.qualityCheckFlag = qualityCheckFlag; } public Integer getDenyCategorySeq() { return denyCategorySeq; } public void setDenyCategorySeq(Integer denyCategorySeq) { this.denyCategorySeq = denyCategorySeq; } }
true
0e8ef9d0d7aaafae2a841acdd29bf14f590c6e34
Java
danielavillamar/AlgoritmosProyecto2
/Controllers/LoginInController.java
UTF-8
3,764
2.46875
2
[]
no_license
package Controllers; import javafx.scene.Node; import javafx.stage.Stage; import javafx.scene.Scene; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import java.io.IOException; import java.util.Map; import org.neo4j.graphdb.Result; import org.neo4j.graphdb.Transaction; import javafx.scene.control.Alert; import java.io.File; import org.neo4j.graphdb.factory.GraphDatabaseFactory; import javafx.event.ActionEvent; import org.neo4j.graphdb.GraphDatabaseService; import javafx.scene.control.TextField; import javafx.fxml.FXML; public class LoginInController { @FXML private Controllers.Main main; @FXML private TextField nameTextField; @FXML private TextField passwordTextField; private String name; private String password; private static void registerShutdownHook(final GraphDatabaseService graphDb) { Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { graphDb.shutdown(); } }); } public void login(final ActionEvent event) throws IOException { final Boolean verificado = this.verificarDatos(); if (verificado) { final GraphDatabaseService db = new GraphDatabaseFactory().newEmbeddedDatabase(new File("./moviesDb/")); registerShutdownHook(db); final Transaction tx = db.beginTx(); String userName = ""; try { final Result result = db.execute("MATCH (u:User)WHERE u.name='" + this.name + "' and u.password='" + this.password + "'" + "RETURN u.name"); tx.success(); if (result.hasNext()) { final Map<String, Object> user = (Map<String, Object>)result.next(); this.main = new Controllers.Main(); userName = user.get("u.name"); } else { final Alert alert = new Alert(Alert.AlertType.ERROR); alert.setTitle("Error"); alert.setHeaderText("Error al iniciar sesion"); alert.setContentText("Verifica que los datos esten correctos"); alert.showAndWait(); } } finally { tx.close(); db.shutdown(); if (this.main != null) { this.main.changeToUserEdit(userName); } } tx.close(); db.shutdown(); if (this.main != null) { this.main.changeToUserEdit(userName); } } else if (!verificado) { final Alert alert2 = new Alert(Alert.AlertType.ERROR); alert2.setTitle("Error"); alert2.setHeaderText("Error en datos ingresado"); alert2.setContentText("Verifica tus datos ingresados"); alert2.showAndWait(); } } public Boolean verificarDatos() { try { this.name = this.nameTextField.getText(); if (this.name == null) { return false; } this.password = this.passwordTextField.getText(); if (this.password == null) { return false; } return true; } catch (Exception e) { return false; } } public void crearCuenta(final ActionEvent event) throws IOException { final Parent newScene = (Parent)FXMLLoader.load(this.getClass().getResource("/Views/SignIn.fxml")); final Scene scene = new Scene(newScene, 400.0, 550.0); final Stage window = (Stage)((Node)event.getSource()).getScene().getWindow(); window.setScene(scene); window.show(); } }
true
e0563e8ec0eca56a19870b49bf36c0fd74441f21
Java
210128/Tomasz_Zalejski-kodilla
/kodilla-collections-advanced/src/test/java/com/kodilla/collections/adv/immutable/BookTestSuite.java
UTF-8
630
2.703125
3
[]
no_license
package com.kodilla.collections.adv.immutable; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; class BookTestSuite { @Test public void shouldGetAuthor(){ //Given Book book = new Book("Stephen King", "The Shining"); //When String result = book.getAuthor(); //Then assertEquals(result, "Stephen King"); } @Test public void shouldGetTitle(){ //Given Book book = new Book("Stephen King", "The Shining"); //When String result = book.getTitle(); //Then assertEquals(result, "The Shining"); } }
true
81c15deaa5fb84a6841e393ffb2c5a82a16fc157
Java
rakibhasansabbir/JasperReportWithSpringBoot
/src/main/java/com/example/JasperReportWithSpringBoot/repository/StudentRepository.java
UTF-8
360
2.046875
2
[]
no_license
package com.example.JasperReportWithSpringBoot.repository; import com.example.JasperReportWithSpringBoot.model.Student; import org.springframework.data.jpa.repository.JpaRepository; import java.util.Date; import java.util.List; public interface StudentRepository extends JpaRepository<Student,Integer> { public List<Student> findAllByDate(Date date); }
true
d604ff74e79a8eba7880fc41828c75bade0e25db
Java
SvenPfiffner/AlgorithmsDatastructuresAndProbability
/AlgorithmsDatastructuresAndProbability/src/misc/PrimeFactorization.java
UTF-8
969
4.1875
4
[ "MIT" ]
permissive
package misc; import java.util.LinkedList; /** * This class implements a factorization algorithm which finds the prime factorization of a given number * @author Sven Pfiffner */ public class PrimeFactorization { /** * Performs a prime factorization on a given integer * @param value to factor * @return LinkedList with all prime factors */ public static LinkedList<Integer> getPrimeFac(int value) { LinkedList<Integer> factors = new LinkedList<Integer>(); //Divide by two while possible while(value % 2 == 0) { factors.add(2); value/=2; } //Loop through all odd numbers <= square root of value and check if they are in prime factorization for(int i = 3; i<= Math.sqrt(value); i+=2) { while(value % i == 0) { factors.add(i); value /= i; } } if(value > 1) { //If value is not one, rest is prime factors.add(value); //So add to factorization } return factors; } }
true
232a539718b3e4a2c35e8d2fad9dcdbec47872af
Java
rizhnitsyn/hibernate1
/src/test/java/by/academy/ChatTest.java
UTF-8
799
2.234375
2
[]
no_license
package by.academy; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import org.junit.AfterClass; import org.junit.Assert; import org.junit.Test; /** * Created by user on 18.01.2018. */ public class ChatTest { private static final SessionFactory SESSION_FACTORY = new Configuration().configure().buildSessionFactory(); @Test public void testSaveToDb() { Session session = SESSION_FACTORY.openSession(); Chat chat = new Chat("new test"); session.save(chat); Chat foundChat = session.find(Chat.class, 1L); Assert.assertEquals("new test", foundChat.getText()); session.close(); } @AfterClass public static void finish() { SESSION_FACTORY.close(); } }
true
895e428facbe2785236a2974f25ae44bf5691d51
Java
YuTaeKyung/HelloJavaFX
/src/main/java/teamproject/taekung/VO/UserVO.java
UTF-8
1,388
2.3125
2
[]
no_license
package teamproject.taekung.VO; /** * Created by taeku on 2016-09-14. */ public class UserVO { private String id=""; private String pwd=""; private String email=""; private String phone=""; private String address=""; private String storename=""; public UserVO(String id, String pwd, String email, String phone, String address, String storename) { this.id = id; this.pwd = pwd; this.email = email; this.phone = phone; this.address = address; this.storename = storename; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getStorename() { return storename; } public void setStorename(String storename) { this.storename = storename; } }
true
14412d764314bfcebe1803ea65181d3d14a37422
Java
rajalakshmicogniseer/MobileApp
/app/src/main/java/com/ignovate/lectrefymob/login/ValidateOtpActivity.java
UTF-8
7,689
2.046875
2
[]
no_license
package com.ignovate.lectrefymob.login; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.AppCompatEditText; import android.support.v7.widget.AppCompatTextView; import android.util.Log; import android.view.View; import android.widget.LinearLayout; import com.basgeekball.awesomevalidation.AwesomeValidation; import com.basgeekball.awesomevalidation.ValidationStyle; import com.basgeekball.awesomevalidation.utility.RegexTemplate; import com.ignovate.lectrefymob.R; import com.ignovate.lectrefymob.interfaces.ApiInterface; import com.ignovate.lectrefymob.model.Forget; import com.ignovate.lectrefymob.model.Otp; import com.ignovate.lectrefymob.model.RegisterReqModel; import com.ignovate.lectrefymob.model.Success; import com.ignovate.lectrefymob.utils.LoadingIndicator; import com.ignovate.lectrefymob.webservice.API; import com.ignovate.lectrefymob.webservice.ConnectivityReceiver; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class ValidateOtpActivity extends AppCompatActivity implements View.OnClickListener { private static final String TAG = "ValidateOtpActivity"; private ApiInterface apiInterface; private AwesomeValidation aV; private AppCompatEditText mOtp; private AppCompatTextView mResend; private LinearLayout mSubmit; private String nOtp; private Intent intent; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); try { setContentView(R.layout.activity_validate_otp); apiInterface = API.getClient().create(ApiInterface.class); aV = new AwesomeValidation(ValidationStyle.BASIC); // aV.setColor(getResources().getColor(R.color.red)); initialView(); addValidationToViews(); intent = getIntent(); } catch (Exception e) { Log.d(TAG, e.getMessage()); } } private void addValidationToViews() { aV.addValidation(this, R.id.otp_id, RegexTemplate.NOT_EMPTY, R.string.invalid_otp); } private void initialView() { mOtp = (AppCompatEditText) findViewById(R.id.otp_id); mResend = (AppCompatTextView) findViewById(R.id.resend); mSubmit = (LinearLayout) findViewById(R.id.submit); mSubmit.setOnClickListener(this); mResend.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.submit: submitValidate(); break; case R.id.resend: resendOtp(); break; } } private void resendOtp() { try { String phone = intent.getStringExtra("PHONE"); String email = intent.getStringExtra("EMAIL"); Forget fm = new Forget(); fm.setPhone(phone); fm.setEmail(email); fm.setRefNo(phone); LoadingIndicator.dismissLoading(); LoadingIndicator.showLoading(ValidateOtpActivity.this, getString(R.string.please_wait)); Call<Success> otp = apiInterface.otpGenerate(fm); otp.enqueue(new Callback<Success>() { @Override public void onResponse(Call<Success> call, Response<Success> response) { if (response.isSuccessful() && response.body().code.equals("SUCCESS")) { LoadingIndicator.dismissLoading(); } } @Override public void onFailure(Call<Success> call, Throwable t) { LoadingIndicator.dismissLoading(); } }); } catch (Exception e) { Log.e("Error", e.getMessage()); } } private void submitValidate() { try { if (ConnectivityReceiver.isConnected()) { if (aV.validate()) { String phone = intent.getStringExtra("PHONE"); Otp otp = new Otp(); otp.setOtp(mOtp.getText().toString().trim()); otp.setRefNo(phone); LoadingIndicator.dismissLoading(); LoadingIndicator.showLoading(ValidateOtpActivity.this, getString(R.string.please_wait)); Call<Success> call = apiInterface.validateOTP(otp); call.enqueue(new Callback<Success>() { @Override public void onResponse(Call<Success> call, Response<Success> response) { if (response.isSuccessful() && response.body().message.equals("SUCCESS")) { boolean re = intent.getBooleanExtra("BOOL", false); if (re) { RegisterReqModel ob = (RegisterReqModel) intent.getSerializableExtra("OBJECT"); if (ob != null) { Call<RegisterReqModel> calls = apiInterface.createUser(ob); calls.enqueue(new Callback<RegisterReqModel>() { @Override public void onResponse(Call<RegisterReqModel> call, Response<RegisterReqModel> responses) { Log.e("Response code", responses.body() + ""); LoadingIndicator.dismissLoading(); if (responses.isSuccessful()) { Intent intent1 = new Intent(ValidateOtpActivity.this, LoginActivity.class); startActivity(intent1); finish(); } } @Override public void onFailure(Call<RegisterReqModel> call, Throwable t) { Log.e("Response", t.getMessage()); } }); } } else { LoadingIndicator.dismissLoading(); String user_id = intent.getStringExtra("USERID"); Intent intent1 = new Intent(ValidateOtpActivity.this, ResetActivity.class); intent1.putExtra("USERID", user_id); startActivity(intent1); } } else { LoadingIndicator.dismissLoading(); mOtp.setError(getString(R.string.otp_wrong)); mOtp.requestFocus(); } } @Override public void onFailure(Call<Success> call, Throwable t) { LoadingIndicator.dismissLoading(); } }); } } else { LoadingIndicator.alertDialog(ValidateOtpActivity.this, ConnectivityReceiver.isConnected()); } } catch (Exception e) { Log.d(TAG, e.getMessage()); } } }
true
3cdd07b523993443d1000f825b23afc8624bdb4b
Java
nekkantiravi/Testcucumber
/Stores/STAT/src/main/java/com/macys/sdt/projects/Stores/STAT/steps/website/StatSteps.java
UTF-8
11,376
2.0625
2
[]
no_license
package com.macys.sdt.projects.Stores.STAT.steps.website; import com.macys.sdt.framework.interactions.Clicks; import com.macys.sdt.framework.interactions.Elements; import com.macys.sdt.framework.interactions.Navigate; import com.macys.sdt.framework.interactions.Wait; import com.macys.sdt.framework.utils.StepUtils; import com.thoughtworks.selenium.webdriven.commands.Click; import cucumber.api.PendingException; import cucumber.api.java.en.And; import cucumber.api.java.en.Given; import cucumber.api.java.en.Then; import cucumber.api.java.en.When; import org.junit.Assert; import static com.macys.sdt.projects.Stores.STAT.utils.STATUtils.typeTextNTab; public class StatSteps extends StepUtils { @Given("^I am on Gift$") public void iAmOnGift() throws Throwable { Navigate.visit("Gift"); Elements.elementShouldBePresent("gift.verify_page"); String GiftTitle = Elements.findElement("gift.verify_page").getText(); Assert.assertEquals("Gift Registry", GiftTitle); } @When("^I login$") public void iLogin() throws Throwable { Elements.elementShouldBePresent("gift.associate_number"); Elements.elementShouldBePresent("gift.associate_password"); Elements.elementShouldBePresent("gift.sign_in"); typeTextNTab("gift.associate_number", "M-Gift_CAdvisor_DEV"); typeTextNTab("gift.associate_password", "3r!TenaSPAw-"); Clicks.click("gift.sign_in"); } @Then("^I can see the Gift Home Page$") public void iCanSeeTheGiftHomePage() throws Throwable { Elements.elementShouldBePresent("gift.hamburger_menu"); } @Then("^I can see the Link$") public void iCanSeeTheLink() throws Throwable { Elements.elementShouldBePresent("gift.vendor_bonus"); } @Then("^I \"([^\"]*)\" see the Link$") public void iTheLink(String Result) throws Throwable { Thread.sleep(1000); switch (Result) { case "Do": Wait.untilElementPresent("gift.vendor_bonus"); Elements.elementShouldBePresent("gift.vendor_bonus"); String VendorBonus = Elements.findElement("gift.vendor_bonus").getText(); Assert.assertEquals("Vendor Bonus Program", VendorBonus); break; case "DoNot": Wait.secondsUntilElementNotPresent("gift.vendor_bonus", 3); if (Elements.elementPresent("gift.vendor_bonus")) { Assert.fail("The Vendor Bonus Link Displayed.... This User should not see the Vendor_Bonus Link."); } break; } } @Given("^I am in the Gift website$") public void iAmInTheGiftWebsite () throws Throwable { Navigate.visit("Gift"); Elements.elementShouldBePresent("gift.verify_page"); String GiftTitle = Elements.findElement("gift.verify_page").getText(); Assert.assertEquals("Gift Registry", GiftTitle); } @When("^I log in as an Advisor$") public void iLogInAsAnAdvisor () throws Throwable { Elements.elementShouldBePresent("gift.associate_number"); Elements.elementShouldBePresent("gift.associate_password"); Elements.elementShouldBePresent("gift.sign_in"); typeTextNTab("gift.associate_number", "M-Gift_CAdvisor_DEV"); typeTextNTab("gift.associate_password", "3r!TenaSPAw-"); Clicks.click("gift.sign_in"); } @Then("^I see the hamburger/main menu$") public void iSeeTheHamburgerMainMenu () throws Throwable { Elements.elementShouldBePresent("gift.hamburger_menu"); } @When("^I click the hamburger/main menu$") public void iClickTheHamburgerMainMenu () throws Throwable { Clicks.click("gift.hamburger_menu"); } @Then("^I see the Vendor Bonus Program link$") public void iSeeTheVendorBonusProgramLink () throws Throwable { Elements.elementShouldBePresent("gift.vendor_bonus_link"); } @When("^I log in as a Support$") public void iLogInAsASupport () throws Throwable { Elements.elementShouldBePresent("gift.associate_number"); Elements.elementShouldBePresent("gift.associate_password"); Elements.elementShouldBePresent("gift.sign_in"); typeTextNTab("gift.associate_number", "M-Gift_Support_DEV"); typeTextNTab("gift.associate_password", "hA8U-Aju&per"); Clicks.click("gift.sign_in"); } @When("^I log in as an Admin$") public void iLogInAsAnAdmin () throws Throwable { Elements.elementShouldBePresent("gift.associate_number"); Elements.elementShouldBePresent("gift.associate_password"); Elements.elementShouldBePresent("gift.sign_in"); typeTextNTab("gift.associate_number", "M-Gift_CorpAdmin_DEV"); typeTextNTab("gift.associate_password", "tHa-UGAdr4wU"); Clicks.click("gift.sign_in"); } @When("^I log in as a Director$") public void iLogInAsADirector () throws Throwable { Elements.elementShouldBePresent("gift.associate_number"); Elements.elementShouldBePresent("gift.associate_password"); Elements.elementShouldBePresent("gift.sign_in"); typeTextNTab("gift.associate_number", "M-Gift_Director_DEV"); typeTextNTab("gift.associate_password", "p+?4a2uJenes"); Clicks.click("gift.sign_in"); } @Then("^I do not see the Vendor Bonus Program link$") public void iDoNotSeeTheVendorBonusProgramLink () throws Throwable { Wait.untilElementNotPresent("gift.vendor_bonus_link"); } @When("^I log in as a General$") public void iLogInAsAGeneral () throws Throwable { Elements.elementShouldBePresent("gift.associate_number"); Elements.elementShouldBePresent("gift.associate_password"); Elements.elementShouldBePresent("gift.sign_in"); typeTextNTab("gift.associate_number", "M-Gift_MCCS_DEV"); typeTextNTab("gift.associate_password", "s!awam5Dupha"); Clicks.click("gift.sign_in"); } @When("^I click the Vendor Bonus Program link$") public void iClickTheVendorBonusProgramLink () throws Throwable { Clicks.click("gift.vendor_bonus_link"); } @Then("^I am on the Vendor Bonus Program page$") public void iAmOnTheVendorBonusProgramPage () throws Throwable { Elements.elementShouldBePresent("gift.verify_page"); String GiftTitle = Elements.findElement("gift.verify_page").getText(); Assert.assertEquals("Macy's Gift Registry", GiftTitle); } @And("^I see the Search icon$") public void iSeeTheSearchIcon () throws Throwable { Elements.elementShouldBePresent("gift.search_icon"); } @When("^I login as an \"([^\"]*)\"$") public void iLoginAsAn (String AssociateRole) throws Throwable { switch (AssociateRole) { case "Adviser": Wait.untilElementPresent("gift.associate_number"); Elements.elementShouldBePresent("gift.associate_number"); Elements.elementShouldBePresent("gift.associate_password"); Elements.elementShouldBePresent("gift.sign_in"); typeTextNTab("gift.associate_number", "M-Gift_CAdvisor_DEV"); typeTextNTab("gift.associate_password", "3r!TenaSPAw-"); Clicks.click("gift.sign_in"); break; case "Director": Wait.untilElementPresent("gift.associate_number"); Elements.elementShouldBePresent("gift.associate_number"); Elements.elementShouldBePresent("gift.associate_password"); Elements.elementShouldBePresent("gift.sign_in"); typeTextNTab("gift.associate_number", "M-Gift_Director_DEV"); typeTextNTab("gift.associate_password", "p+?4a2uJenes"); Clicks.click("gift.sign_in"); break; case "Support": Wait.untilElementPresent("gift.associate_number"); Elements.elementShouldBePresent("gift.associate_number"); Elements.elementShouldBePresent("gift.associate_password"); Elements.elementShouldBePresent("gift.sign_in"); typeTextNTab("gift.associate_number", "M-Gift_Support_DEV"); typeTextNTab("gift.associate_password", "hA8U-Aju&per"); Clicks.click("gift.sign_in"); break; case "CorpAdmin": Wait.untilElementPresent("gift.associate_number"); Elements.elementShouldBePresent("gift.associate_number"); Elements.elementShouldBePresent("gift.associate_password"); Elements.elementShouldBePresent("gift.sign_in"); typeTextNTab("gift.associate_number", "M-Gift_CorpAdmin_DEV"); typeTextNTab("gift.associate_password", "tHa-UGAdr4wU"); Clicks.click("gift.sign_in"); break; case "MCCS_DEV": Wait.untilElementPresent("gift.associate_number"); Elements.elementShouldBePresent("gift.associate_number"); Elements.elementShouldBePresent("gift.associate_password"); Elements.elementShouldBePresent("gift.sign_in"); typeTextNTab("gift.associate_number", "M-Gift_MCCS_DEV"); typeTextNTab("gift.associate_password", "s!awam5Dupha"); Clicks.click("gift.sign_in"); break; case "HSAssoc": Wait.untilElementPresent("gift.associate_number"); Elements.elementShouldBePresent("gift.associate_number"); Elements.elementShouldBePresent("gift.associate_password"); Elements.elementShouldBePresent("gift.sign_in"); typeTextNTab("gift.associate_number", "M-Gift_HSAssoc_DEV"); typeTextNTab("gift.associate_password", "Sefruguw-w6g"); Clicks.click("gift.sign_in"); break; } } @And("^I see the Application Title$") public void iSeeTheApplicationTitle () throws Throwable { Elements.elementShouldBePresent("gift.verify_page"); } @And("^I see the Welcome Info$") public void iSeeTheWelcomeInfo () throws Throwable { Elements.elementShouldBePresent("gift.associate_header"); } @And("^I see Create Icon$") public void iSeeCreateIcon () throws Throwable { Elements.elementShouldBePresent("gift.create_icon"); } @And("^I see the title Vendor Bonus Program$") public void iSeeTheTitleVendorBonusProgram () throws Throwable { Elements.elementShouldBePresent("gift.vendor_bonus_title"); } @Then("^I see the Create Request Link$") public void iSeeTheCreateRequestLink () throws Throwable { Elements.elementShouldBePresent("gift.create_vendor_bonus"); } @When("^I click on the Create Request Link$") public void iClickOnTheCreateRequestLink() throws Throwable { Elements.elementShouldBePresent("giftvendorbonus.create_request_link"); Clicks.click("giftvendorbonus.create_request_link"); } @Then("^I am on the Vendor Bonus Request Page$") public void iAmOnTheVendorBonusRequestPage() throws Throwable { Elements.elementShouldBePresent("giftvendorbonus.vendorBonusRequestTitle"); } }
true
15daa763475085d904ce19d17a6870114130667d
Java
GpGardner/FTCI_Notes
/ECommerce/src/main/java/com/tts/ECommerce/Controllers/MainController.java
UTF-8
3,018
2.703125
3
[]
no_license
package com.tts.ECommerce.Controllers; import java.util.List; import java.util.ArrayList; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestParam; import com.tts.ECommerce.Models.Product; import com.tts.ECommerce.Services.ProductService; @Controller @ControllerAdvice // This makes the `@ModelAttribute`s of this controller available to all // controllers, for the navbar. public class MainController { @Autowired ProductService productService; // public Product(int quantity, float price, String description, // String name, String brand, String category,String image) { public void addNew() { List<Product> allProducts = productService.findAll(); if (allProducts.isEmpty()) { List<Product> newProducts = new ArrayList<Product>(); newProducts.add(new Product(4, (float) 1500.00, "Apple MacBook Pro", "MacBook Pro", "Apple", "computer", "images/apple_mlh32ll_a_15_4_macbook_pro_with_1293726.jpg")); newProducts.add(new Product(3, (float) 1000.00, "C7 ST Desktop Front Edit", "Desktop", "Dell", "computer", "images/C7_ST_Desktop_Front.jpg")); newProducts.add(new Product(12, (float) 800.00, "New iPhone 8, Silver", "IPhone 8", "Apple", "phone", "images/iphone8-silver-select-2017.jpg")); newProducts.add(new Product(7, (float) 700.00, "New iPhone", "IPhone", "IPhone", "phone", "images/iphonexfrontback-800x573.jpg")); for (Product product : newProducts) { productService.save(product); } } else { System.out.println("You don't need more items!"); } } @GetMapping("/") public String main() { addNew(); return "main"; } @ModelAttribute("products") public List<Product> products() { return productService.findAll(); } @ModelAttribute("categories") public List<String> categories() { return productService.findDistinctCategories(); } @ModelAttribute("brands") public List<String> brands() { return productService.findDistinctBrands(); } @GetMapping("/filter") public String filter(@RequestParam(required = false) String category, @RequestParam(required = false) String brand, Model model) { List<Product> filtered = productService.findByBrandAndOrCategory(brand, category); model.addAttribute("products", filtered); // Overrides the @ModelAttribute above. return "main"; } @GetMapping("/about") public String about() { return "about"; } }
true
a54c55350f082003b0a51389926e2f393ad63bb1
Java
fselker/Robotik
/src/mapping/Param.java
UTF-8
83
1.59375
2
[]
no_license
package mapping; public class Param { int x, y, dx, dy, vx, vy; Param() { } }
true
532565a361994200af819d0838f80759212ca175
Java
briangohjw/Facebook-Farmville-Java-App
/src/main/java/daos/StealDAO.java
UTF-8
6,363
3.234375
3
[]
no_license
package daos; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.List; import entities.Plot; import entities.User; /** * The StealDAO class provides access to the steal_plot table in the database. * * @version 1.0 04 Apr 2020 * @author Brian Goh */ public class StealDAO extends DAO { /** * Add a specified thief to a specified plot * * @param plot plot to add thief too * @param thief thief to add * @return true upon successful addition, false otherwise */ public boolean addThief(Plot plot, User thief) { Connection conn = null; PreparedStatement preparedStmt = null; int addSuccess = 0; try { // Create the SQL database connection conn = getConnection(); // Create the SQL insert statement String query = "INSERT INTO STEAL_PLOT (plot_id, thief_username) VALUES (?, ?)"; // Create the prepared statement from query preparedStmt = conn.prepareStatement(query); // Get required fields for query int plotId = plot.getPlotId(); String thiefUsername = thief.getUsername(); // Set prepared statement placeholder values preparedStmt.setInt(1, plotId); preparedStmt.setString(2, thiefUsername); // Execute the prepared statement addSuccess = preparedStmt.executeUpdate(); } catch (Exception e) { System.err.println("Error when adding thief:"); System.err.println(e.getMessage()); } finally { // Close connection, prepared statement and/or result set try { if(conn != null) { conn.close(); } if(preparedStmt != null) { preparedStmt.close(); } } catch(Exception e) { System.err.println("Error when closing:"); System.err.println(e.getMessage()); } } return (addSuccess != 0); } /** * Return thieves of a specified plot * * @param plot plot to retrieve thieves from * @return list of thieves of specified plot */ public List<User> getThieves(Plot plot) { Connection conn = null; PreparedStatement preparedStmt = null; ResultSet rs = null; UserDAO userDAO = new UserDAO(); List<User> thieves = new ArrayList<>(); try { // Create the SQL database connection conn = getConnection(); // Create the SQL select statement String query = "SELECT * FROM STEAL_PLOT WHERE plot_id=?"; // Create the prepared statement from query preparedStmt = conn.prepareStatement(query); // Get required fields for query int plotId = plot.getPlotId(); // Set prepared statement placeholder values preparedStmt.setInt(1, plotId); // Execute the prepared statement rs = preparedStmt.executeQuery(); // Get results from result set while(rs.next()) { String thiefUsername = rs.getString("thief_username"); thieves.add(userDAO.getUser(thiefUsername)); } } catch (Exception e) { System.err.println("Error when getting thieves:"); System.err.println(e.getMessage()); } finally { // Close connection, prepared statement and/or result set try { if(conn != null) { conn.close(); } if(preparedStmt != null) { preparedStmt.close(); } if(rs != null) { rs.close(); } } catch(Exception e) { System.err.println("Error when closing:"); System.err.println(e.getMessage()); } } return thieves; } /** * Remove all thieves from a specified plot * * @param plot plot to remove thieves from * @return true upon successful reset, false otherwise */ public boolean resetThieves(Plot plot) { Connection conn = null; PreparedStatement preparedStmt = null; int deleteSuccess = 0; try { // Create the SQL database connection conn = getConnection(); // Create the SQL delete statement String query = "DELETE FROM STEAL_PLOT WHERE plot_id=?"; // Create the prepared statement from query preparedStmt = conn.prepareStatement(query); // Get required fields for query int plotId = plot.getPlotId(); // Set prepared statement placeholder values preparedStmt.setInt(1, plotId); // Execute the prepared statement deleteSuccess = preparedStmt.executeUpdate(); } catch (Exception e) { System.err.println("Error when resetting thieves:"); System.err.println(e.getMessage()); } finally { // Close connection, prepared statement and/or result set try { if(conn != null) { conn.close(); } if(preparedStmt != null) { preparedStmt.close(); } } catch(Exception e) { System.err.println("Error when closing:"); System.err.println(e.getMessage()); } } return (deleteSuccess != 0); } /** * Checks if specified user has stolen from a specified plot * * @param suspect user to check stolen status * @param plot plot to check if stolen from * @return true if user has stolen from plot before, false otherwise */ public boolean hasStolen(User suspect, Plot plot) { Connection conn = null; PreparedStatement preparedStmt = null; ResultSet rs = null; boolean hasStolen = false; try { // Create the SQL database connection conn = getConnection(); // Create the SQL select statement String query = "SELECT * FROM STEAL_PLOT WHERE plot_id=? AND thief_username=?"; // Create the prepared statement from query preparedStmt = conn.prepareStatement(query); // Get required fields for query int plotId = plot.getPlotId(); String thiefUsername = suspect.getUsername(); // Set prepared statement placeholder values preparedStmt.setInt(1, plotId); preparedStmt.setString(2, thiefUsername); // Execute the prepared statement rs = preparedStmt.executeQuery(); // If there are row(s) returned if (rs.isBeforeFirst() ) { rs.next(); hasStolen = true; } } catch (Exception e) { System.err.println("Error when checking if user has stolen from a plot:"); System.err.println(e.getMessage()); } finally { // Close connection, prepared statement and/or result set try { if(conn != null) { conn.close(); } if(preparedStmt != null) { preparedStmt.close(); } if(rs != null) { rs.close(); } } catch(Exception e) { System.err.println("Error when closing:"); System.err.println(e.getMessage()); } } return hasStolen; } }
true
cdf3d77b1c6f869eb10f2a250b19c8d4f88cab63
Java
dohungquan/java-bai-tap
/BT5/Date.java
UTF-8
647
3.3125
3
[]
no_license
package BT5; import java.text.SimpleDateFormat; import java.util.Calendar; public class Date extends Person{ Date(String firstName, String lastName, int day, int month, int year) { super(firstName, lastName, day, month, year); } public String daysOfWeek() { Calendar cal = Calendar.getInstance(); cal.set(Calendar.DAY_OF_MONTH, getDay()); cal.set(Calendar.MONTH, getMonth() - 1); cal.set(Calendar.YEAR, getYear()); java.util.Date myBirth = cal.getTime(); String daysinWeek = new SimpleDateFormat("EEEE").format(myBirth); return "(" + daysinWeek + ")"; } }
true
d4336396900b043f631c0ad8effc572e337a7ded
Java
eduardoramirez7/Taller-Kata-Cuenta-Bancaria
/src/main/java/com/logica/Account.java
UTF-8
1,995
3.3125
3
[]
no_license
package com.logica; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.ArrayList; public class Account { private long saldo; private long balanceTotal = 0; private LocalDate fecha; ArrayList<Account> mov = new ArrayList<>(); public long obtenerSaldo() { return saldo; } public void recibirSaldo(long saldo) { this.saldo = saldo; } public LocalDate obtenerFecha() { return fecha; } public void definirFechaMovimiento(LocalDate fecha) { this.fecha = fecha; } public long obtenerBalanceTotal() { return balanceTotal; } public void definirBalanceTotal(long balanceTotal) { this.balanceTotal = balanceTotal; } public Account() { } public void deposito(long monto, String fechaDeposito) { Account c = new Account(); c.recibirSaldo(monto); c.definirFechaMovimiento(formatoFecha(fechaDeposito)); c.definirBalanceTotal(this.balanceTotal+=monto); mov.add(c); } public void retiro(int montoRetiro, String fechaRetiro){ if (saldoTotal(montoRetiro) == true) deposito(-(montoRetiro), fechaRetiro); } public void extractoBancario() { System.out.println(" Fecha Movimiento Balance"); for(int i = 0; i< mov.size(); i++) { this.saldo += mov.get(i).obtenerSaldo(); System.out.println(mov.get(i).obtenerFecha() + " " + mov.get(i).obtenerSaldo()+" "+mov.get(i).obtenerBalanceTotal()); } } public LocalDate formatoFecha(String fecha){ DateTimeFormatter df = DateTimeFormatter.ofPattern("dd/MM/yyyy"); LocalDate fechaLocal = LocalDate.parse(fecha,df); return fechaLocal; } private boolean saldoTotal(long monto){ long balance = this.balanceTotal - monto; if(balance >= 0) return true; return false; } }
true
0e5b6058c22c2cb490e24c1c9a87e610a577ea5f
Java
vladshvydun/Java_Start
/HomeWork1/src/exercise3/Main.java
UTF-8
374
3.65625
4
[]
no_license
package exercise3; import java.util.*; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Input radius of a circle: "); double r = scanner.nextDouble(); double c = Math.PI * 2.0 * r; System.out.println("Circumference of a circle is: " + c); scanner.close(); } }
true
9864576e039edbc99dd105b2739bd5987eef3f70
Java
MurodDevUzb/Spring
/apelsin/src/main/java/uz/dev/apelsin/model/Order.java
UTF-8
701
1.992188
2
[]
no_license
package uz.dev.apelsin.model; import com.fasterxml.jackson.annotation.*; import lombok.Data; import javax.persistence.*; import java.sql.Date; import java.util.List; @Data @Entity @Table(name = "order_table") public class Order { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private Date date; @ManyToOne(fetch = FetchType.EAGER) @JsonBackReference private Customer customer; @OneToMany(cascade = CascadeType.REFRESH,fetch = FetchType.LAZY, mappedBy = "order", orphanRemoval = true) @JsonManagedReference private List<Detail> details ; @OneToOne(mappedBy = "order") @JsonBackReference private Invoice invoice; }
true
0bc0591ee6d53bb55ef2bd598860f5647f8db43c
Java
2018shiji/elkclient
/src/main/java/com/module/es/ESOperator.java
UTF-8
7,150
2.125
2
[]
no_license
package com.module.es; import com.alibaba.fastjson.JSON; import org.elasticsearch.action.bulk.BulkRequest; import org.elasticsearch.action.bulk.BulkResponse; import org.elasticsearch.action.delete.DeleteRequest; import org.elasticsearch.action.delete.DeleteResponse; import org.elasticsearch.action.get.GetRequest; import org.elasticsearch.action.get.GetResponse; import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.action.index.IndexResponse; import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.update.UpdateRequest; import org.elasticsearch.action.update.UpdateResponse; import org.elasticsearch.client.indices.DeleteAliasRequest; import org.elasticsearch.client.RequestOptions; import org.elasticsearch.client.RestHighLevelClient; import org.elasticsearch.client.core.AcknowledgedResponse; import org.elasticsearch.client.indices.CreateIndexRequest; import org.elasticsearch.client.indices.CreateIndexResponse; import org.elasticsearch.client.indices.GetIndexRequest; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.common.xcontent.XContentType; import org.elasticsearch.index.query.MatchQueryBuilder; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.search.builder.SearchSourceBuilder; import org.elasticsearch.search.fetch.subphase.FetchSourceContext; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Component; import java.io.IOException; import java.util.ArrayList; import java.util.concurrent.TimeUnit; @Component public class ESOperator { @Autowired @Qualifier("restHighLevelClient") private RestHighLevelClient client; private static final String ES_INDEX = "index"; //创建索引 == 创建数据库 public void createIndex() throws IOException { // 1. 创建索引 CreateIndexRequest index = new CreateIndexRequest(ES_INDEX); // 2. 客户端执行请求, 请求后获得响应 CreateIndexResponse response = client.indices().create(index, RequestOptions.DEFAULT); // 3. 打印结果 System.out.println("创建索引的结果: " + response.toString()); } //测试索引是否存在 == 测试数据库是否存在 public void exitIndex() throws IOException { GetIndexRequest request = new GetIndexRequest(ES_INDEX); boolean exist = client.indices().exists(request, RequestOptions.DEFAULT); System.out.println("索引是否存在: " + exist); } //删除索引 == 删除数据库 public void deleteIndex() throws IOException { DeleteAliasRequest request = new DeleteAliasRequest(ES_INDEX, "alias"); AcknowledgedResponse response = client.indices().deleteAlias(request, RequestOptions.DEFAULT); System.out.println("索引是否删除: " + response); } //创建文档 == 创建一行数据 public void createDocument() throws IOException { //创建对象 UserInfo userInfo = new UserInfo("张三", 12); //创建请求 IndexRequest request = new IndexRequest(ES_INDEX); //规则 request.id("1").timeout(TimeValue.timeValueSeconds(1)); //将数据放到请求中 request.source(JSON.toJSONString(userInfo), XContentType.JSON); //客户端发送请求, 获取响应结果 IndexResponse response = client.index(request, RequestOptions.DEFAULT); System.out.println("创建文档的结果: " + response.toString()); System.out.println(response.status()); } //判断文档是否存在 == 判断行数据是否存在 public void exitDocument() throws IOException { GetRequest request = new GetRequest(ES_INDEX, "1"); request.fetchSourceContext(new FetchSourceContext(false)); request.storedFields("_none"); boolean exist = client.exists(request, RequestOptions.DEFAULT); System.out.println("文档是否存在: " + exist); } //获取文档信息 == 获取行数据 public void getDocument() throws IOException { GetRequest request = new GetRequest(ES_INDEX, "1"); GetResponse response = client.get(request, RequestOptions.DEFAULT); System.out.println("获取到的结果: " + response.getSourceAsString()); } //更新文档 == 更新行数据 public void updateDocument() throws IOException { UserInfo userInfo = new UserInfo("李四", 12); UpdateRequest request = new UpdateRequest(ES_INDEX, "1"); request.timeout("1s"); request.doc(JSON.toJSONString(userInfo), XContentType.JSON); UpdateResponse response = client.update(request, RequestOptions.DEFAULT); System.out.println("更新的结果: " + response.status()); } //删除文档 == 删除行数据 public void deleteDocument() throws IOException { DeleteRequest request = new DeleteRequest(ES_INDEX, "1"); request.timeout("1s"); DeleteResponse response = client.delete(request, RequestOptions.DEFAULT); System.out.println("删除的结果: " + response.status()); } //批量添加 == 批量添加行数据 public void bulkDocument() throws IOException { BulkRequest request = new BulkRequest(); request.timeout("10s"); ArrayList<UserInfo> userInfos = new ArrayList(); userInfos.add(new UserInfo("李四",1)); userInfos.add(new UserInfo("李四",2)); userInfos.add(new UserInfo("李四",3)); userInfos.add(new UserInfo("李四",4)); userInfos.add(new UserInfo("李四",5)); userInfos.add(new UserInfo("李四",6)); userInfos.add(new UserInfo("李四",7)); //进行批处理请求 for(int i = 0; i < userInfos.size(); i++){ request.add( new IndexRequest(ES_INDEX) .id("" + (i+1)) .source(JSON.toJSONString(userInfos.get(i)), XContentType.JSON) ); } BulkResponse response = client.bulk(request, RequestOptions.DEFAULT); System.out.println("批量插入的结果: " + response.hasFailures()); } //查询 == 查询行数据 public void searchDocument() throws IOException { SearchRequest request = new SearchRequest(ES_INDEX); //构建搜索条件 SearchSourceBuilder searchBuilder = new SearchSourceBuilder(); //查询条件使用QueryBuilders工具来实现 //QueryBuilders.termQuery 精准查询 //QueryBuilders.matchAllQuery() 匹配全部 MatchQueryBuilder matchQuery = QueryBuilders.matchQuery("name", "李四"); searchBuilder.query(matchQuery); searchBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS)); request.source(searchBuilder); SearchResponse response = client.search(request, RequestOptions.DEFAULT); System.out.println("查询出的结果: " + JSON.toJSONString(response.getHits())); } }
true
c35661ae4f2f8f3c0e89c9b4ba8a9a00e45e1510
Java
NikMatkovic92/flight-advisor
/src/main/java/com/htec/services/impl/CommentRepository.java
UTF-8
247
1.507813
2
[]
no_license
package com.htec.services.impl; import com.htec.services.entities.CommentEntity; import org.springframework.data.jpa.repository.JpaRepository; /** * @author Nikola Matkovic */ interface CommentRepository extends JpaRepository<CommentEntity, Long> { }
true
fad50eaafd179449b0e9c2356d198bcb0351e03b
Java
Sunayanams/Tutorial
/musicmaineeBackend/src/main/java/com/niit/musicmainee/Dao/CorderDao.java
UTF-8
321
1.875
2
[]
no_license
package com.niit.musicmainee.Dao; import java.util.List; import com.niit.musicmainee.entity.Cart; import com.niit.musicmainee.entity.Corder; public interface CorderDao { public boolean save(Corder corder); public boolean delete(String user_id); public Corder get(String user_id); public List<Corder> list(); }
true
ca7de6309c5277e61e867d20be3f4a683f3be0e5
Java
subhamdash/OOPS
/JAVA_and_OOPS/OOPS/03-PolyMorphism_Cohesion.java
UTF-8
1,381
2.96875
3
[]
no_license
public class oop3 { //overiding concept is applicable for methods not for varaibles //varible resolution takes care by compile based on reference type irrestpective of whether // the varibale is staic or non static //Over-riding concept applicable for method but not for varibels, it is taken care by compiler //polmorphism -overloading and over-riding //Coupling - If more dependcy is more then it is consider as tightly coupling, // if dependency is less then it is consider as lossely coupling. /* Enhancement will become difficult. Reuseability will help in more. Maintainability of the code will help. Depednecy of components is more. It suprasses re-usability It reduces maintainability of the application. Cohesion - For every of component a clear well define functionality said is to be followed a high-cohesion. It doesn't have like login --validation ---inbox rather all are indepented Ex:- IF I have servelet program which contains 100 of functionalities and even I have to modify one then whole servlet needs to be redesigned. //Maintain a sepreated one for each component and it can be imported and can be used in multiple area */ public static int m1() { return 10; } } class B { static int j=oop3.m1(); //Dependent on A } class A { static int i=B.j; //Dependent on B }
true
f325de55476e324922a5f6bef0ae401821c61725
Java
keauw/pocCloudFoundry
/pocCloudFoundryCarServiceEngine/src/main/java/com/poc/service/engine/rest/EngineController.java
UTF-8
559
1.890625
2
[]
no_license
package com.poc.service.engine.rest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import com.poc.service.engine.config.AppProperties; @RestController public class EngineController { @Autowired private AppProperties prop; @GetMapping("/helloworld") public String helloWorld() { return "Hello Engine!"; } @GetMapping("/greeting") public String greeting() { return prop.getHelloMessage(); } }
true
662e220f98787ac805437dbad04df37bb70de24d
Java
nickman/wiex
/wiex-server/src/main/java/com/heliosapm/wiex/server/collectors/jdbc/CheckedDriverManagerJDBCConnectionFactory.java
UTF-8
9,089
2.40625
2
[]
no_license
/** * */ package com.heliosapm.wiex.server.collectors.jdbc; import java.io.PrintWriter; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.sql.Connection; import java.sql.DriverManager; import java.util.Date; import java.util.Properties; import com.heliosapm.wiex.tracing.tracing.ITracer; import com.heliosapm.wiex.tracing.tracing.TracerFactory; /** * <p>Title: CheckedDriverManagerJDBCConnectionFactory</p> * <p>Description: DriverManager Connection Factory that is checked by a timeout thread to alert if a connection request stalls indefinitely. * The timeout should be defined in the configuration properties under the key <code>check.connect.timeout</code> or will default to 10,000 ms. * If the connection request times out, an interval incident will be traced to the metric name <code>Connection Timeout</code> under the segment * defined by the config property <code>check.connect.tracing.segment</code>. The segment should be specified in comma separated subsegments. * e.g. <code>Oracle,TelProd,Connections</code></p> * <p>Copyright: Copyright (c) 2007</p> * <p>Company: Helios Development Group</p> * @author Whitehead * @version $Revision: 1.1 $ */ public class CheckedDriverManagerJDBCConnectionFactory extends DriverManagerJDBCConnectionFactory implements Thread.UncaughtExceptionHandler { /** Property key for time out */ public static final String JDBC_CHECK_TIMEOUT = "check.connect.timeout"; /** Property key for connector interrupt */ public static final String JDBC_CONNECTOR_INTERRUPT = "check.connect.interrupt"; /** Property key for connector debug */ public static final String JDBC_CONNECTOR_DEBUG = "check.connect.debug"; /** Property key for tracing segment name */ public static final String CHECK_CONNECT_TRACING_SEGMENT = "check.connect.tracing.segment"; /** Property key for tracing segment name */ public static final String JDBC_CHECK_TIMEOUT_DEFAULT = "10000"; /** Turns on some additional logging to System.out when set to true */ protected boolean DEBUG = false; /** The check thread time out */ protected long timeOut = 0L; /** The tracing segment */ protected String tracingSegment = null; /** The tracer */ protected ITracer tracer = null; /** If true, then interrupt the connecting thread on timeout */ protected boolean interruptConnector = false; /** * Simple constructor. Calls super and then configures the tracer. */ public CheckedDriverManagerJDBCConnectionFactory() { super(); tracer = TracerFactory.getInstance(); } /** * Acquires and returns a JDBC connection from the <code>java.sql.DriverManager</code>. * A time thread is started to check that the connection is made within the timeout period. * @return A JDBC Connection * @throws JDBCConnectionFactoryException * @see com.heliosapm.wiex.server.collectors.jdbc.JDBCConnectionFactory#getJDBCConnection() */ public Connection getJDBCConnection() throws JDBCConnectionFactoryException, JDBCConnectionFactoryTimeOutException { if(!isRegistered) { try { Class.forName(jdbcDriver); DriverManager.setLoginTimeout((int)timeOut/1000); isRegistered = true; } catch (Exception e) { throw new JDBCConnectionFactoryException("Failed to load driver:" + jdbcDriver, e); } } try { ConnectionCheckThread cct = new ConnectionCheckThread(timeOut, this, Thread.currentThread(), interruptConnector); cct.start(); Connection conn = DriverManager.getConnection(jdbcUrl, connectionProperties); tracer.recordIntervalIncident(tracingSegment, "Connection Acquired"); if(!cct.isSleeping()) { throw new JDBCConnectionFactoryTimeOutException(); } cct.setComplete(true); cct.interrupt(); return conn; } catch (Throwable e) { if(DEBUG) e.printStackTrace(); String errSeg = tracer.buildSegment(tracingSegment, false, "Errors"); tracer.recordIntervalIncident(errSeg, e.getMessage()); if(Thread.currentThread().isInterrupted()) { String traceSeg = tracer.buildSegment(tracingSegment, false, "Interrupted"); tracer.recordIntervalIncident(traceSeg, "Connection Timeout"); tracer.recordCounterMetric(tracingSegment, "Availability", 0); tracer.recordCounterMetric(tracingSegment, "Connection Time", -1L); tracer.recordCounterMetric(tracingSegment, "Query Time", -1L); } throw new JDBCConnectionFactoryException("Failed to acquire connection", e); } } /** * Sets the factories properties using the super implementation, then configures the time out and tracing segment. * @param properties * @see com.heliosapm.wiex.server.collectors.jdbc.DriverManagerJDBCConnectionFactory#setProperties(java.util.Properties) */ @Override public void setProperties(Properties properties) { super.setProperties(properties); String to = connectionProperties.getProperty(JDBC_CHECK_TIMEOUT, JDBC_CHECK_TIMEOUT_DEFAULT); timeOut = Long.parseLong(to); interruptConnector = properties.getProperty(JDBC_CONNECTOR_INTERRUPT, "false").equalsIgnoreCase("true"); DEBUG = properties.getProperty(JDBC_CONNECTOR_DEBUG, "false").equalsIgnoreCase("true"); String[] fragments = connectionProperties.getProperty(CHECK_CONNECT_TRACING_SEGMENT).split(","); if(fragments==null || fragments.length < 1) fragments = new String[]{"Connection Testing", jdbcUrl}; tracingSegment = tracer.buildSegment(fragments); } /** * Thrown when the connection timeout check thread expires. * @param t * @param e * @see java.lang.Thread$UncaughtExceptionHandler#uncaughtException(java.lang.Thread, java.lang.Throwable) */ public void uncaughtException(Thread t, Throwable e) { if(e instanceof ConnectionTimeOutException) { ConnectionTimeOutException ctoe = (ConnectionTimeOutException)e; String traceSeg = tracer.buildSegment(tracingSegment, false, ctoe.getConnectingThread().getState().toString()); tracer.recordIntervalIncident(traceSeg, "Connection Timeout"); if(DEBUG) { // ======================================= // For testing only // ======================================= StringBuilder buff = new StringBuilder(); buff.append("\nConnection Timeout Detected."); buff.append("\n\tURL:").append(jdbcUrl); buff.append("\n\tTimeout:").append(timeOut); buff.append("\n\tThread State:").append(ctoe.getConnectingThread().getState()); buff.append("\n\tCurrent Thread:").append(Thread.currentThread().getName()); buff.append("\n\tInterrupt Connector:").append(interruptConnector); buff.append("\n\tConnecting Thread:").append(ctoe.getConnectingThread().getName()); buff.append("\n\tTracing Segment:").append(traceSeg); log(buff.toString()); } // ======================================= // ctoe.getConnectingThread().interrupt(); } else { // some other exception occured that we did not expect. tracer.recordIntervalIncident(tracingSegment, "Exception"); if(DEBUG) { // ======================================= // For testing only // ======================================= StringBuilder buff = new StringBuilder(); buff.append("\nConnection Timeout Exception Detected."); buff.append("\n\tURL:").append(jdbcUrl); buff.append("\n\tTimeout:").append(timeOut); buff.append("\n\tTracing Segment:").append(tracingSegment); buff.append("\n\tException:").append(e); log(buff.toString()); } // ======================================= } } public static void log(Object message) { System.out.println("[" + new Date() + "]:" + message); } /** * Parameterles main to run a command line test of the class. * @param args * @throws Exception */ public static void main(String[] args) throws Exception { log("Test CheckedDriverManagerJDBCConnectionFactory"); Properties p = new Properties(); //p.put(JDBC_DRIVER, CatatonicJDBCDriver.class.getName()); p.put(JDBC_DRIVER, CatatonicJDBCSocketDriver.class.getName()); p.put(JDBC_URL, "catatonic://sleep.for.a.long.time"); p.put(JDBC_USER, ""); p.put(JDBC_PASSWORD, ""); p.put(JDBC_CHECK_TIMEOUT, "5000"); p.put("sleep.time", "7000"); p.put(CHECK_CONNECT_TRACING_SEGMENT, "Catatonic,Connection Test"); DriverManager.registerDriver(CatatonicJDBCSocketDriver.class.newInstance()); DriverManager.setLogWriter(new PrintWriter(System.out)); CheckedDriverManagerJDBCConnectionFactory factory = new CheckedDriverManagerJDBCConnectionFactory(); factory.DEBUG=true; factory.setProperties(p); ServerSocket socket = new ServerSocket(); InetSocketAddress address = new InetSocketAddress("localhost", 9950); socket.bind(address); log("Factory Created"); try { log("Issuing Connection Request"); factory.getJDBCConnection(); log("Connection Request Complete"); } catch (Exception e) { log("Connection Acquisition Failure"); e.printStackTrace(); } } }
true
46d99fc1cc5981c0906a1816ca5921da6e1bc972
Java
whvixd/study
/demo/src/main/java/com/github/whvixd/demo/algorithm/leetcode/easy/Q1389.java
UTF-8
2,684
3.390625
3
[]
no_license
package com.github.whvixd.demo.algorithm.leetcode.easy; import java.util.ArrayList; import java.util.List; import static com.github.whvixd.util.SystemUtil.print; /** * 给你两个整数数组 nums 和 index。你需要按照以下规则创建目标数组: 目标数组 target 最初为空。 按从左到右的顺序依次读取 nums[i] 和 index[i],在 target 数组中的下标 index[i] 处插入值 nums[i] 。 重复上一步,直到在 nums 和 index 中都没有要读取的元素。 请你返回目标数组。 题目保证数字插入位置总是存在。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/create-target-array-in-the-given-order 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 * * Created by wangzhx on 2020/5/26. */ public enum Q1389 { instance; public int[] createTargetArray(int[] nums, int[] index) { int[] target=new int[nums.length]; for(int i=0;i<target.length;i++){ target[i]=-1; } for (int i=0;i<nums.length;i++){ if(target[i]==-1){ move(index[i],target); } target[index[i]]=nums[i]; } return target; } private void move(int point,int[] target) { for (int i=target.length-1;i>point;i--){ if(target[i]!=target[i-1]){ target[i]=target[i-1]; } } } public int[] createTargetArray1(int[] nums, int[] index) { int l=nums.length; List<Integer> list=new ArrayList<>(l); for(int i=0;i<l;i++){ list.add(index[i],nums[i]); } int[] target=new int[l]; for(int i=0;i<l;i++){ target[i]=list.get(i); } return target; } public static void main(String[] args) { int[] a = new int[]{3,2,3,4}; Q1389.instance.move(1,a); print(a,false); // assert [0,4,1,3,2] print(Q1389.instance.createTargetArray(new int[]{0,1,2,3,4},new int[]{0,1,2,2,1})); // assert [0,1,2,3,4] print(Q1389.instance.createTargetArray(new int[]{1,2,3,4,0},new int[]{0,1,2,3,0})); // assert [1] print(Q1389.instance.createTargetArray(new int[]{1},new int[]{0})); // assert [2,2,4,4,3] print(Q1389.instance.createTargetArray(new int[]{4,2,4,3,2},new int[]{0,0,1,3,1})); // assert [7,5,4,5,5,6,5,5] print(Q1389.instance.createTargetArray(new int[]{7,6,5,5,5,4,5,5},new int[]{0,1,1,2,4,2,3,6})); print(Q1389.instance.createTargetArray1(new int[]{7,6,5,5,5,4,5,5},new int[]{0,1,1,2,4,2,3,6})); } }
true
bbc6e2503fa777c5fa99a3fa8f1a28fa42e68aa9
Java
aakashalurkar/online_hackathon
/server/online-hackathon-project/src/main/java/com/openHack/io/repository/TeamRepository.java
UTF-8
1,462
2.03125
2
[]
no_license
package com.openHack.io.repository; import com.openHack.io.entity.TeamEntity; import com.openHack.io.entity.TeamMemberEntity; import com.openHack.ui.model.request.TeamDetailsRequestModel; import java.util.ArrayList; import javax.transaction.Transactional; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; @Repository @Transactional public interface TeamRepository extends CrudRepository<TeamEntity, Long>{ TeamEntity findById(long id); @Query(value="SELECT * FROM teams t where t.hackathon_id =?1", nativeQuery = true) ArrayList<TeamEntity> getTeamsByHackathonId(long id); @Modifying @Transactional @Query(value="Update teams set grade=?1 where id =?2", nativeQuery = true) void gradeTeam(double grade, long id); @Modifying @Transactional @Query(value="Update teams set grade=?1 where team_name like ?2 and hackathon_id=?3", nativeQuery = true) void gradeTeam(double grade, String teamName, long hackathonId); @Query(value="SELECT * FROM teams where hackathon_id =?1 order by grade desc limit 3", nativeQuery = true) ArrayList<TeamEntity> getWinnerTeamsByHackathonId(long id); @Query(value="SELECT * FROM teams where hackathon_id =?1 order by grade desc limit 3, 9518676", nativeQuery = true) ArrayList<TeamEntity> getParticipantTeamsByHackathonId(long id); }
true
2e9e95927cad7b749399c87ab092fd4a7be4ed1c
Java
omarbek/kz.halyqsoft.univercity
/src/main/java/kz/halyqsoft/univercity/entity/beans/univercity/catalog/ACADEMIC_CALENDAR_ITEM.java
UTF-8
2,269
1.96875
2
[]
no_license
package kz.halyqsoft.univercity.entity.beans.univercity.catalog; import org.r3a.common.entity.AbstractEntity; import org.r3a.common.entity.EFieldType; import org.r3a.common.entity.FieldInfo; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.JoinColumn; import javax.persistence.JoinColumns; import javax.persistence.ManyToOne; /** * @author Omarbek * Created Oct 22, 2016 1:42:07 PM */ @Entity public class ACADEMIC_CALENDAR_ITEM extends AbstractEntity { private static final long serialVersionUID = 4004720332675119342L; @FieldInfo(type = EFieldType.FK_COMBO) @ManyToOne @JoinColumns({ @JoinColumn(name = "FACULTY_ID", referencedColumnName = "ID")}) private ACADEMIC_CALENDAR_FACULTY faculty; @FieldInfo(type = EFieldType.FK_COMBO, order = 2) @ManyToOne @JoinColumns({ @JoinColumn(name = "SEMESTER_PERIOD_ID", referencedColumnName = "ID")}) private SEMESTER_PERIOD semesterPeriod; @FieldInfo(type = EFieldType.TEXT, max = 256, order = 3) @Column(name = "ITEM_NAME", nullable = false) private String itemName; @FieldInfo(type = EFieldType.TEXT, max = 256, order = 4) @Column(name = "ITEM_TYPE", nullable = false) private String itemType; @FieldInfo(type = EFieldType.BOOLEAN, order = 6, required = false, inEdit = false, inGrid = false, inView = false) @Column(name = "DELETED", nullable = false) private boolean deleted; public ACADEMIC_CALENDAR_ITEM() { } public ACADEMIC_CALENDAR_FACULTY getFaculty() { return faculty; } public void setFaculty(ACADEMIC_CALENDAR_FACULTY faculty) { this.faculty = faculty; } public SEMESTER_PERIOD getSemesterPeriod() { return semesterPeriod; } public void setSemesterPeriod(SEMESTER_PERIOD semesterPeriod) { this.semesterPeriod = semesterPeriod; } public String getItemName() { return itemName; } public void setItemName(String itemName) { this.itemName = itemName; } public String getItemType() { return itemType; } public void setItemType(String itemType) { this.itemType = itemType; } public boolean isDeleted() { return deleted; } public void setDeleted(boolean deleted) { this.deleted = deleted; } @Override public String toString() { return itemName; } }
true
eb5687b39a162e0b1d0de05d003dc24f27af84a2
Java
DraganKal/jwd40-zavrsni
/zavrsniTestDraganKalakovic/src/main/java/jwd/wafepa/support/ZadatakToDTO.java
UTF-8
1,091
2.5625
3
[]
no_license
package jwd.wafepa.support; import java.util.ArrayList; import java.util.List; import org.springframework.core.convert.converter.Converter; import org.springframework.stereotype.Component; import jwd.wafepa.model.Zadatak; import jwd.wafepa.web.dto.ZadatakDTO; // Konvertor koji konvertuje Zadatak u ZadatakDTO @Component public class ZadatakToDTO implements Converter<Zadatak, ZadatakDTO>{ @Override public ZadatakDTO convert(Zadatak zadatak) { ZadatakDTO retValue = new ZadatakDTO(); retValue.setBodovi(zadatak.getBodovi()); retValue.setId(zadatak.getId()); retValue.setIme(zadatak.getIme()); retValue.setSprintId(zadatak.getSprint().getId()); retValue.setSprintNaziv(zadatak.getSprint().getIme()); retValue.setStanjeId(zadatak.getStanje().getId()); retValue.setStanjeNaziv(zadatak.getStanje().getIme()); retValue.setZaduzeni(zadatak.getZaduzeni()); return retValue; } public List<ZadatakDTO> convert(List<Zadatak> list){ List<ZadatakDTO> ret = new ArrayList<>(); for(Zadatak it : list){ ret.add(convert(it)); } return ret; } }
true
a8e42a2d4003f4f3fedaa11021d6d396eb9bad5b
Java
gandralf/scenery-manager
/scenery-manager/src/test/java/br/com/devx/scenery/WrapperTestTarget.java
UTF-8
1,702
2.5
2
[]
no_license
package br.com.devx.scenery; import java.util.Date; public class WrapperTestTarget extends WrapperTestTargetBase { private Date m_dateValue; private boolean m_booleanValue; public WrapperTestTarget() { } public WrapperTestTarget(int intValue, String stringValue, Date dateValue, boolean booleanValue) { m_intValue = intValue; m_stringValue = stringValue; m_dateValue = dateValue; m_booleanValue = booleanValue; } public Date getDateValue() { return m_dateValue; } public boolean getBooleanValue() { return m_booleanValue; } public void setDateValue(Date dateValue) { m_dateValue = dateValue; } public void setBooleanValue(boolean booleanValue) { m_booleanValue = booleanValue; } public String message() { return "Message: \"" + getStringValue() + "\""; } public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof WrapperTestTarget)) return false; if (!super.equals(o)) return false; final WrapperTestTarget wrapperTestTarget = (WrapperTestTarget) o; if (m_booleanValue != wrapperTestTarget.m_booleanValue) return false; if (m_dateValue != null ? !m_dateValue.equals(wrapperTestTarget.m_dateValue) : wrapperTestTarget.m_dateValue != null) return false; return true; } public int hashCode() { int result = super.hashCode(); result = 29 * result + (m_dateValue != null ? m_dateValue.hashCode() : 0); result = 29 * result + (m_booleanValue ? 1 : 0); return result; } }
true
9b2de29ebc685495725fa5403901928d0477cf6e
Java
ats-jp/dexter.plugin
/src/jp/ats/dexter/plugin/Type.java
UTF-8
939
2.375
2
[]
no_license
package jp.ats.dexter.plugin; import java.math.BigDecimal; import java.time.LocalDate; import java.time.LocalTime; import jp.ats.substrate.U; enum Type { String("type-string", String.class), Int("type-int", int.class), Long("type-long", long.class), Boolean("type-boolean", boolean.class), Decimal("type-decimal", BigDecimal.class), Date("type-date", LocalDate.class), Time("type-time", LocalTime.class); final String expression; final Class<?> clazz; private Type(String expression, Class<?> clazz) { this.expression = expression; this.clazz = clazz; } String getWrapperName() { return U.convertPrimitiveClassToWrapperClass(clazz).getSimpleName(); } String getConverterName() { return "to" + name(); } boolean needsImport() { return !clazz.isPrimitive() && !Object.class.getPackage().equals(clazz.getPackage()); } String getImportString() { return "import " + clazz.getName() + ";"; } }
true
241a8c7f1fde119c871be3ab2862a961e009a2d0
Java
ygchen/mystu-restful-api
/src/edu/stu/exception/StuException.java
UTF-8
356
2.171875
2
[]
no_license
package edu.stu.exception; public class StuException extends Exception{ /** * */ private static final long serialVersionUID = -6711316754808360484L; public StuException(){} public StuException(String msg){ super(msg); } public StuException(Throwable t){ super(t); } public StuException(String msg,Throwable t){ super(msg,t); } }
true
a4e4a21d2a2b10cd1e36525a3a89673aaca8144e
Java
Wojtasny/AoC2018
/src/day2/InventoryManagementSystem.java
UTF-8
1,055
3.234375
3
[]
no_license
package day2; import java.util.*; import java.util.function.Function; import java.util.stream.Collectors; public class InventoryManagementSystem { private Set<BoxIDDistribution> boxIDs = new HashSet<>(); private class BoxIDDistribution { private Map<Character, Long> distribution; public BoxIDDistribution(String boxID) { this.distribution = createDistribution(boxID); } private Map<Character, Long> createDistribution(String boxID) { return boxID.chars().mapToObj(c -> (char) c).collect(Collectors.groupingBy(Function.identity(), Collectors.counting())); } } public void parseID(String str) { boxIDs.add(new BoxIDDistribution(str)); } public Long countChecksum() { long twos = boxIDs.stream().filter(boxIDDistribution -> boxIDDistribution.distribution.containsValue(2L)).count(); long threes = boxIDs.stream().filter(boxIDDistribution -> boxIDDistribution.distribution.containsValue(3L)).count(); return twos * threes; } }
true
47d4098275cf51c43ec9e69b87bd3b07b58af27c
Java
s21272/9lab_2
/Animal.java
UTF-8
254
3.171875
3
[]
no_license
public class Animal { public void sleep (){ System.out.println("is sleeping"); } public void makeNoise(){ System.out.println("is making noises"); } public void roam(){ System.out.println("is roaming"); } }
true
33a658b21346457f386b5301bd63d5dbe51d16a7
Java
DataFabricRus/rya-beam-pipelines
/src/main/java/cc/datafabric/pipelines/io/AccumuloSingleTableWrite.java
UTF-8
2,318
2.109375
2
[ "MIT" ]
permissive
package cc.datafabric.pipelines.io; import org.apache.accumulo.core.client.*; import org.apache.accumulo.core.client.security.tokens.PasswordToken; import org.apache.accumulo.core.data.Mutation; import org.apache.beam.sdk.transforms.DoFn; import org.apache.beam.sdk.transforms.PTransform; import org.apache.beam.sdk.transforms.ParDo; import org.apache.beam.sdk.values.PCollection; public class AccumuloSingleTableWrite extends PTransform<PCollection<Iterable<Mutation>>, PCollection<Boolean>> { private final String instanceName; private final String zookeepers; private final String username; private final String password; private final String tableName; public AccumuloSingleTableWrite(String instanceName, String zookeeperServers, String username, String password, String tableName) { this.instanceName = instanceName; this.zookeepers = zookeeperServers; this.username = username; this.password = password; this.tableName = tableName; } @Override public PCollection<Boolean> expand(PCollection<Iterable<Mutation>> input) { return input.apply(ParDo.of(new WriterDoFn())); } private class WriterDoFn extends DoFn<Iterable<Mutation>, Boolean> { private transient Connector connector; private transient BatchWriter writer; @Setup public void setup() throws AccumuloSecurityException, AccumuloException, TableNotFoundException { final Instance instance = new ZooKeeperInstance(instanceName, zookeepers); this.connector = instance.getConnector(username, new PasswordToken(password)); BatchWriterConfig writerConfig = new BatchWriterConfig(); this.writer = this.connector.createBatchWriter(tableName, writerConfig); } @ProcessElement public void processElement(@Element Iterable<Mutation> mutations, OutputReceiver<Boolean> out) throws AccumuloException { this.writer.addMutations(mutations); this.writer.flush(); out.output(true); } @Teardown public void tearDown() throws MutationsRejectedException { this.writer.flush(); this.writer.close(); } } }
true
49e53a9553aeabe96c939862c6c590bf2f84f099
Java
mariah-crawford/sps-team-37
/src/main/java/com/google/sps/data/Journal.java
UTF-8
737
2.484375
2
[]
no_license
package com.google.sps.data; /** A Journal object containing the text, mood value, song, artist, emoji, time, and email. */ public final class Journal { private final String textEntry; private final long moodValue; private final String songTitle; private final String artistName; private final String emoji; private final long timestamp; private final String email; public Journal( String textEntry, long moodValue, String songTitle, String artistName, String emoji, long timestamp, String email) { this.textEntry = textEntry; this.moodValue = moodValue; this.songTitle = songTitle; this.artistName = artistName; this.emoji = emoji; this.timestamp = timestamp; this.email = email; } }
true
38a4d5c2b698bbd7df1b8e208ab76be97066880d
Java
brjannc/TimerSigns
/src/main/java/me/brjannc/plugins/timersigns/TimerSigns.java
UTF-8
4,196
2.421875
2
[]
no_license
/* * Copyright (C) 2012 brjannc <brjannc at gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package me.brjannc.plugins.timersigns; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Scanner; import java.util.logging.Logger; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.block.Block; import org.bukkit.configuration.Configuration; import org.bukkit.event.Listener; import org.bukkit.plugin.java.JavaPlugin; public class TimerSigns extends JavaPlugin implements Listener { private static final Logger log = Logger.getLogger("Minecraft.TimerSigns"); private Map<Location, TimerSign> timerSigns; @Override public void onEnable() { timerSigns = new HashMap<Location, TimerSign>(); startup(); getServer().getPluginManager().registerEvents(new SignListener(this), this); log.info(this + " is now enabled"); } @Override public void onDisable() { shutdown(); log.info(this + " is now disabled"); } private void startup() { Configuration config = getConfig(); if (config.getKeys(true).isEmpty()) { config.options().copyDefaults(true); } loadSigns(); } private void shutdown() { saveSigns(); saveConfig(); } private void loadSigns() { try { File file = new File(this.getDataFolder(), "signs.csv"); if (!file.exists()) { return; } Scanner scanner = new Scanner(file); while (scanner.hasNextLine()) { String line = scanner.nextLine().trim(); String[] tokens = line.split(","); // world,x,y,z,onTicks,offTicks World world = getServer().getWorld(tokens[0]); int x = Integer.valueOf(tokens[1]); int y = Integer.valueOf(tokens[2]); int z = Integer.valueOf(tokens[3]); long onTicks = Long.valueOf(tokens[4]); long offTicks = Long.valueOf(tokens[5]); Block signBlock = world.getBlockAt(x, y, z); createTimerSign(signBlock, onTicks, offTicks); } scanner.close(); } catch (IOException e) { log.warning("[TimerSigns] Error loading signs.csv: " + e); } } private void saveSigns() { try { File file = new File(this.getDataFolder(), "signs.csv"); BufferedWriter writer = new BufferedWriter(new FileWriter(file)); for (TimerSign timerSign : timerSigns.values()) { writer.append(timerSign.toString()); writer.newLine(); } writer.close(); } catch (IOException e) { log.warning("[TimerSigns] Error saving signs.csv: " + e); } } public void createTimerSign(Block signBlock, long onTicks, long offTicks) { timerSigns.put(signBlock.getLocation(), new TimerSign(this, signBlock, onTicks, offTicks)); } public boolean isTimerSign(Block block) { return timerSigns.containsKey(block.getLocation()); } public void destroyTimerSign(Block block) { TimerSign timerSign = getTimerSign(block); timerSign.cancelTask(); timerSigns.remove(block.getLocation()); } public TimerSign getTimerSign(Block block) { return timerSigns.get(block.getLocation()); } }
true
566b54de8b5871df9c0dc5fae00380ab18ce4eeb
Java
TlatoaniHJ/Kosmos
/src/us/tlatoani/kosmos/border/event/ExprBorderMovingValue.java
UTF-8
2,199
2.578125
3
[ "MIT" ]
permissive
package us.tlatoani.kosmos.border.event; import ch.njol.skript.Skript; import ch.njol.skript.lang.Expression; import ch.njol.skript.lang.SkriptParser.ParseResult; import ch.njol.skript.lang.util.SimpleExpression; import ch.njol.util.Kleenean; import org.bukkit.World; import org.bukkit.event.Event; import java.util.function.Function; public class ExprBorderMovingValue extends SimpleExpression<Number>{ private Expression<World> worldExpression; private Type type; public enum Type { ORIGINAL_DIAMETER("original diameter", WorldBorderImpl::getOriginalDiameter), EVENTUAL_DIAMETER("eventual diameter", WorldBorderImpl::getEventualDiameter), REMAINING_DISTANCE("remaining distance", WorldBorderImpl::getRemainingDistance); public final String syntax; public final Function<WorldBorderImpl, Double> function; Type(String syntax, Function<WorldBorderImpl, Double> function) { this.syntax = syntax; this.function = function; } public Double getValue(WorldBorderImpl border) { return function.apply(border); } } @Override public Class<? extends Number> getReturnType() { return Number.class; } @Override public boolean isSingle() { return true; } @Override public boolean init(Expression<?>[] expr, int matchedPattern, Kleenean arg2, ParseResult parseResult) { worldExpression = (Expression<World>) expr[0]; if ((parseResult.mark & 0b1000) == 0b1000) { /*if (Config.DISABLE_SIZE_SYNTAX.getCurrentValue()) { return false; }*/ Skript.warning("Use of the 'size' alias for border diameter is discouraged. Please use 'diameter' instead."); } type = Type.values()[parseResult.mark & 0b0111]; return true; } @Override public String toString(Event event, boolean arg1) { return type.syntax + " of " + worldExpression; } @Override protected Number[] get(Event event) { World world = worldExpression.getSingle(event); if (world.getWorldBorder() instanceof WorldBorderImpl) { WorldBorderImpl border = (WorldBorderImpl) world.getWorldBorder(); return new Number[]{type.getValue(border)}; } return new Number[0]; } }
true
b2843cb4451cd70810abebfd43359e36687d56a2
Java
doytsujin/webfx
/mongoose/mongoose-shared/mongoose-shared-entities/src/main/java/mongoose/shared/entities/impl/EventImpl.java
UTF-8
1,602
2.28125
2
[]
no_license
package mongoose.shared.entities.impl; import mongoose.shared.entities.Event; import mongoose.shared.businessdata.time.DateTimeRange; import webfx.framework.shared.orm.entity.EntityId; import webfx.framework.shared.orm.entity.EntityStore; import webfx.framework.shared.orm.entity.impl.DynamicEntity; import webfx.framework.shared.orm.entity.impl.EntityFactoryProviderImpl; /** * @author Bruno Salmon */ public final class EventImpl extends DynamicEntity implements Event { public EventImpl(EntityId id, EntityStore store) { super(id, store); } private DateTimeRange parsedDateTimeRange; @Override public DateTimeRange getParsedDateTimeRange() { if (parsedDateTimeRange == null) parsedDateTimeRange = DateTimeRange.parse(getDateTimeRange()); return parsedDateTimeRange; } private DateTimeRange parsedMinDateTimeRange; @Override public DateTimeRange getParsedMinDateTimeRange() { if (parsedMinDateTimeRange == null) parsedMinDateTimeRange = DateTimeRange.parse(getMinDateTimeRange()); return parsedMinDateTimeRange; } private DateTimeRange parsedMaxDateTimeRange; @Override public DateTimeRange getParsedMaxDateTimeRange() { if (parsedMaxDateTimeRange == null) parsedMaxDateTimeRange = DateTimeRange.parse(getMaxDateTimeRange()); return parsedMaxDateTimeRange; } public static final class ProvidedFactory extends EntityFactoryProviderImpl<Event> { public ProvidedFactory() { super(Event.class, EventImpl::new); } } }
true
4cd25b72c364960041cf4228443804acc18e7754
Java
posixrfc/JavaEE
/test/Hibernate_day2_1/src/cn/itcast/h3/qbc/user/XMLQueryApp.java
UTF-8
769
2.09375
2
[ "MIT" ]
permissive
package cn.itcast.h3.qbc.user; import org.hibernate.Query; import org.hibernate.SQLQuery; import org.hibernate.Session; import org.junit.Test; import cn.itcast.h3.util.H3Util; public class XMLQueryApp { @Test //将HQL语句配置到hbm.xml文件中 //<query name="getAll">from UserModel</query> public void test1(){ Session s = H3Util.getSession(); Query q = s.getNamedQuery("getAll"); System.out.println(q.list()); s.close(); } @Test //将SQL语句配置到hbm.xml文件中 //<sql-query name="getAll2">select * from tbl_user where uuid = ?</sql-query> public void test2(){ Session s = H3Util.getSession(); Query q = s.getNamedQuery("getAll2"); q.setLong(0, 1L); System.out.println(q.list()); s.close(); } }
true
cb668e8754893406c2c20bb5a427a28a71233d1f
Java
BigKam/Learnings
/OtherProjects/netty01/src/main/java/nettyServer01/TcpServerHandler.java
UTF-8
747
2.65625
3
[]
no_license
package nettyServer01; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; /** * Created by jin.lei on 2017/9/20. */ public class TcpServerHandler extends SimpleChannelInboundHandler<Object> { @Override protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception { System.out.println("server get msg = " + msg); Thread.sleep(5); ctx.channel().writeAndFlush("yes, server is accepted you ,nice !"+msg); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { System.out.println("wrong: " + cause); ctx.close(); } }
true
1920431bca3a3ef76475b6ed60c3890b18477a28
Java
Finkky/sy-clappin
/src/main/java/cz/cvut/fit/culkajac/dp/services/store/impl/StoreSelectionServiceRules.java
UTF-8
513
1.789063
2
[]
no_license
package cz.cvut.fit.culkajac.dp.services.store.impl; import org.switchyard.component.rules.Execute; import org.switchyard.component.rules.Rules; import cz.cvut.fit.culkajac.dp.dto.FileDTO; import cz.cvut.fit.culkajac.dp.services.store.StoreSelectionService; @Rules(value = StoreSelectionService.class, resources = { "/cz/cvut/fit/culkajac/dp/services/store/storeRules.drl" }) public interface StoreSelectionServiceRules extends StoreSelectionService { @Override @Execute public void process(FileDTO file); }
true
a88b4e098218fbfb2c86648603a8a8b0ec540817
Java
ampratt/MBPeT
/MBPeT/src/com/aaron/mbpet/views/tabs/parameterstab/ParametersAceEditorLayout.java
UTF-8
14,865
1.671875
2
[ "Apache-2.0" ]
permissive
package com.aaron.mbpet.views.tabs.parameterstab; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.List; import java.util.Scanner; import org.vaadin.aceeditor.AceEditor; import org.vaadin.aceeditor.AceMode; import com.aaron.mbpet.MbpetUI; import com.aaron.mbpet.domain.Parameters; import com.aaron.mbpet.domain.TestSession; import com.aaron.mbpet.services.AceUtils; import com.aaron.mbpet.services.FileSystemUtils; import com.aaron.mbpet.services.ParametersUtils; import com.aaron.mbpet.views.MainView; import com.aaron.mbpet.views.parameters.ParametersEditor; import com.vaadin.addon.jpacontainer.JPAContainer; import com.vaadin.data.Property; import com.vaadin.data.Property.ValueChangeListener; import com.vaadin.data.util.BeanItem; import com.vaadin.event.FieldEvents.TextChangeEvent; import com.vaadin.event.FieldEvents.TextChangeListener; import com.vaadin.server.FontAwesome; import com.vaadin.shared.ui.combobox.FilteringMode; import com.vaadin.ui.Alignment; import com.vaadin.ui.Button; import com.vaadin.ui.ComboBox; import com.vaadin.ui.Component; import com.vaadin.ui.HorizontalLayout; import com.vaadin.ui.Notification; import com.vaadin.ui.Table; import com.vaadin.ui.UI; import com.vaadin.ui.VerticalLayout; import com.vaadin.ui.Button.ClickEvent; public class ParametersAceEditorLayout extends VerticalLayout implements Button.ClickListener{ AceEditor editor;// = new AceEditor(); ComboBox themeBox; ComboBox modeBox; Button saveButton; Button loadButton; String fileFormat = "python"; List<String> modeList; String[] modes = {"python", "dot", "gv"}; List<String> themeList; String[] themes = {"ambiance", "chrome", "clouds", "cobalt", "dreamweaver", "eclipse", "github", "terminal", "twilight", "xcode"}; // String testDir = "C:/dev/git/alternate/mbpet/MBPeT/WebContent/META-INF/output/settings.py"; // String basepath = "C:/dev/git/alternate/mbpet/MBPeT/WebContent"; //VaadinService.getCurrent().getBaseDirectory().getAbsolutePath(); String basepath = ((MbpetUI) UI.getCurrent()).getWebContent(); String defaultsettingsfile = basepath + "/WEB-INF/tmp/settings.py"; String prevModelsFolder; String prevReportsFolder; TestSession currsession; Parameters currentparams; JPAContainer<Parameters> parameters = ((MbpetUI) UI.getCurrent()).getParameterscontainer(); BeanItem<Parameters> beanItem; ParametersFormAceView formAceView; public ParametersAceEditorLayout(AceEditor editor, String fileFormat, BeanItem<Parameters> beanItem, TestSession currsession, ParametersFormAceView formAceView) { // TestSession currsession setSizeFull(); setMargin(false); //(new MarginInfo(false, true, false, true)); // setMargin(true); // setSpacing(true); this.editor = editor; //= new AceEditor() this.fileFormat = fileFormat; this.currsession = currsession; this.currentparams = currsession.getParameters();//parameters.getItem(currsession.getParameters().getId()).getEntity(); //currsession.getParameters(); this.beanItem = beanItem; this.formAceView = formAceView; this.prevModelsFolder = currentparams.getModels_folder(); this.prevReportsFolder = currentparams.getTest_report_folder(); // Notification.show("prevModelsFolder is:" + prevModelsFolder); // addComponent(new Label("<h3>Give Test Parameters in settings.py file</h3>", ContentMode.HTML)); addComponent(buildButtons()); addComponent(buildAceEditor()); // toggleEditorFields(false); } private Component buildButtons() { // Horizontal Layout HorizontalLayout h = new HorizontalLayout(); h.setWidth("100%"); h.setSpacing(true); themeList = Arrays.asList(themes); themeBox = new ComboBox("editor theme:", themeList); // modeBox.setContainerDataSource(modeList); // modeBox.setWidth(100.0f, Unit.PERCENTAGE); themeBox.setWidth(9, Unit.EM); themeBox.addStyleName("tiny"); // themeBox.setInputPrompt("No style selected"); themeBox.setFilteringMode(FilteringMode.CONTAINS); themeBox.setImmediate(true); themeBox.setNullSelectionAllowed(false); themeBox.setValue(themeList.get(1)); themeBox.addValueChangeListener(new ValueChangeListener() { @Override public void valueChange(Property.ValueChangeEvent event) { AceUtils.setAceTheme(editor, event.getProperty().getValue().toString()); } }); modeList = Arrays.asList(modes); modeBox = new ComboBox("code style:", modeList); // modeBox.setContainerDataSource(modeList); // modeBox.setWidth(100.0f, Unit.PERCENTAGE); modeBox.setWidth(7, Unit.EM); modeBox.addStyleName("tiny"); modeBox.setInputPrompt("No style selected"); modeBox.setFilteringMode(FilteringMode.CONTAINS); modeBox.setImmediate(true); modeBox.setNullSelectionAllowed(false); modeBox.setValue(modeList.get(0)); modeBox.addValueChangeListener(new ValueChangeListener() { @Override public void valueChange(Property.ValueChangeEvent event) { // Notification.show("mode changed to: " + event.getProperty().getValue().toString()); setEditorMode(event.getProperty().getValue().toString()); } }); saveButton = new Button("Save", this); saveButton.setIcon(FontAwesome.SAVE); // saveButton.addStyleName("borderless-colored"); //borderless- saveButton.addStyleName("tiny"); saveButton.addStyleName("primary"); // saveButton.addStyleName("icon-only"); saveButton.setDescription("save model"); saveButton.setEnabled(false); h.addComponents(themeBox, saveButton); // modeBox h.setComponentAlignment(themeBox, Alignment.BOTTOM_LEFT); h.setComponentAlignment(saveButton, Alignment.BOTTOM_RIGHT); h.setExpandRatio(saveButton, 1); return h; } private AceEditor buildAceEditor() { //System.out.println("SETTINGS FILE : " + defaultsettingsfile); // Ace Editor try { if (currentparams.getSettings_file() == null) { loadExampleSettings(); // editor.setValue("Fill in parameters for Test Session '" + currsession.getTitle() + "'"); //("Hello world!\nif:\n\tthen \ndo that\n..."); } else { editor.setValue(currentparams.getSettings_file()); } } catch (NullPointerException e1) { e1.printStackTrace(); loadExampleSettings(); // editor.setValue("Fill in parameters for Test Session '" + currsession.getTitle() + "'"); //("Hello world!\nif:\n\tthen \ndo that\n..."); } // use static hosted files for theme, mode, worker // editor.setThemePath("/static/ace"); // editor.setModePath("/static/ace"); // editor.setWorkerPath("/static/ace"); editor.setWidth("100%"); editor.setHeight("800px"); editor.setReadOnly(false); // setEditorMode(fileFormat); editor.setMode(AceMode.python); // editor.setUseWorker(true); // editor.setTheme(AceTheme.twilight); // editor.setWordWrap(false); // editor.setShowInvisibles(false); // System.out.println(editor.getValue()); // Use worker (if available for the current mode) //editor.setUseWorker(true); editor.addTextChangeListener(new TextChangeListener() { @Override public void textChange(TextChangeEvent event) { // Notification.show("Text: " + event.getText()); saveButton.setEnabled(true); } }); // new SuggestionExtension(new MySuggester()).extend(editor); return editor; } public void buttonClick(ClickEvent event) { if (event.getButton() == saveButton) { // String s = editor.getValue(); // saveToFile(s, testDir); //+aceOutFileField.getValue()); // commit settings file from Ace new ParametersEditor(currentparams, currsession, editor.getValue()); currentparams = parameters.getItem(currentparams.getId()).getEntity(); // commit individual field, parsed from ace ParametersUtils.commitAceParamData(currentparams, editor.getValue()); // update Form view formAceView.bindFormtoBean(currentparams); // for (Object pid : beanItem.getItemPropertyIds()) {beanItem.getItemProperty(pid).setValue(currParameters)} formAceView.wireupTRTTable(); saveButton.setEnabled(false); // edit models directory name FileSystemUtils fileUtils = new FileSystemUtils(); //System.out.println("prevModelsFolder->" + prevModelsFolder + " and current folder->" +currentparams.getModels_folder()); if (!prevModelsFolder.equals(currentparams.getModels_folder())) { fileUtils.renameModelsDir( //username, sut, session, prevModelsDir, newModelsDir) currsession.getParentcase().getOwner().getUsername(), currsession.getParentcase().getTitle(), currsession.getTitle(), prevModelsFolder, currentparams.getModels_folder()); // Notification.show("Previous->new folder: " + prevModelsFolder +"->"+currentparams.getModels_folder()); prevModelsFolder = currentparams.getModels_folder(); } // edit reports directory name //System.out.println("prevReportsFolder->" + prevReportsFolder + " and current folder->" +currentparams.getTest_report_folder()); if (!prevReportsFolder.equals(currentparams.getTest_report_folder())) { fileUtils.renameModelsDir( //username, sut, session, prevModelsDir, newModelsDir) currsession.getParentcase().getOwner().getUsername(), currsession.getParentcase().getTitle(), currsession.getTitle(), prevReportsFolder, currentparams.getTest_report_folder()); // Notification.show("Previous->new folder: " + prevReportsFolder +"->"+currentparams.getTest_report_folder()); prevReportsFolder = currentparams.getTest_report_folder(); } // write settings file to disk fileUtils.writeSettingsToDisk( //username, sut, session, settings_file) currsession.getParentcase().getOwner().getUsername(), currsession.getParentcase().getTitle(), currsession.getTitle(), currentparams.getSettings_file()); // Notification.show(s, Type.WARNING_MESSAGE); // UI.getCurrent().getNavigator() // .navigateTo(MainView.NAME + "/" + // currsession.getParentcase().getTitle() + "/" + // currsession.getTitle() + "-id=" + currsession.getId()); } } public void saveToFile(String output, String fileName) { // create file // String fileName = "C:/dev/output/ace-editor-output.dot"; File file = new File(fileName); PrintWriter writer = null; try { writer = new PrintWriter(file); } catch (FileNotFoundException e) { e.printStackTrace(); } writer.println( output ); writer.close(); //show confirmation to user Notification.show("dot file was saved at: " + fileName, Notification.Type.TRAY_NOTIFICATION);; } public void setEditorMode(String mode) { // String file = filename.replace("C:/", ""); // file = file.replace("/", "\\"); if (mode.equals("dot")) { editor.setMode(AceMode.dot); modeBox.setValue(modeList.get(1)); // System.out.println("Mode changed to dot"); } else if (mode.equals("gv")){ editor.setMode(AceMode.dot); modeBox.setValue(modeList.get(2)); // System.out.println("Mode changed to dot"); } else if (mode.equals("py") || mode.equals("python")) { editor.setMode(AceMode.python); modeBox.setValue(modeList.get(0)); // System.out.println("Mode changed to python"); } } // private void setAceTheme(String theme) { // // switch (theme) { // case "ambiance": // editor.setTheme(AceTheme.ambiance); // break; // case "chrome": // editor.setTheme(AceTheme.chrome); // break; // case "clouds": // editor.setTheme(AceTheme.clouds); // break; // case "cobalt": // editor.setTheme(AceTheme.cobalt); // break; // case "dreamweaver": // editor.setTheme(AceTheme.dreamweaver); // break; // case "eclipse": // editor.setTheme(AceTheme.eclipse); // break; // case "github": // editor.setTheme(AceTheme.github); // break; // case "terminal": // editor.setTheme(AceTheme.terminal); // break; // case "twilight": // editor.setTheme(AceTheme.twilight); // break; // case "xcode": // editor.setTheme(AceTheme.xcode); // break; // // default: // editor.setTheme(AceTheme.clouds); // } // // } public void toggleEditorFields(boolean b) { themeBox.setEnabled(b); modeBox.setEnabled(b); saveButton.setEnabled(b); // editor.setEnabled(b); editor.focus(); } public void setEditorValue(String settings) { editor.setValue(settings); } public String getEditorValue() { return editor.getValue(); } public void setPrevModelsFolder(String modelsFolder){ prevModelsFolder = modelsFolder; } public void setPrevReportsFolder(String reportsFolder) { prevReportsFolder = reportsFolder; } // public void setFieldsDataSource(Parameters currparams) { // if (currmodel==null) { // binder.clear(); //// titleField.setValue(""); // editor.setValue(""); // } else { // this.currParameters = currparams; // // binder = new FieldGroup(); // modelBeanItem = new BeanItem<Model>(currmodel); // takes item as argument // binder.setItemDataSource(modelBeanItem); // binder.bind(editor, "dotschema"); // // // // titleField.setValue(currmodel.getTitle()); // // editor.setValue(currmodel.getDotschema()); // // saveButton.setEnabled(false); // // titleField.setPropertyDataSource(this.currmodel.getTitle()); // // editor.setPropertyDataSource(this.currmodel.getDotschema()); // } // } private void loadExampleSettings() { //System.out.println("SETTINGS FILE : " + defaultsettingsfile); StringBuilder builder = new StringBuilder(); Scanner scan = null; try { scan = new Scanner(new FileReader(defaultsettingsfile)); while (scan.hasNextLine()) { builder.append(scan.nextLine()).append(System.getProperty("line.separator")); } //System.out.println(builder.toString()); editor.setValue(builder.toString()); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
true
29d81e62d8060886a6789748dc9da72e9f1f53bc
Java
wushbin/GatherApp
/DukeGatherApllication/app/src/main/java/com/example/wushbin/dukegatherapllication/InGroupActivity.java
UTF-8
16,782
1.828125
2
[]
no_license
package com.example.wushbin.dukegatherapllication; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.text.Editable; import android.text.InputFilter; import android.text.TextWatcher; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ListView; import android.widget.Toast; import com.google.android.gms.tasks.OnSuccessListener; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.database.ChildEventListener; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.Query; import com.google.firebase.database.ValueEventListener; import com.google.firebase.remoteconfig.FirebaseRemoteConfig; import com.google.firebase.storage.FirebaseStorage; import com.google.firebase.storage.StorageReference; import com.google.firebase.storage.UploadTask; import java.security.acl.Owner; import java.util.ArrayList; import java.util.List; import static android.R.attr.data; /** * Created by wushbin on 3/2/17. */ public class InGroupActivity extends AppCompatActivity{ public static final String ANONYMOUS = "anonymous"; private static final String TAG = "InGroupActivity"; public static final int DEFAULT_MSG_LENGTH_LIMIT = 140; private static final int RC_PHOTO_PICKER = 2; private static final int RC_EDIT_POST =3; private static final int RC_MEMBER_INFO =4; private ListView mMessageListView; private MessageAdapter mMessageAdapter; private EditText mMessageEditText; private Button mSendButton; private ImageButton mPhotoPickerButton; private boolean existStatus; private String postKey; private String mUsername; private String mUserEmail; private Uri mUserPhotoUri; private String mUserUniqID; private FirebaseAuth mFirebaseAuth; private FirebaseDatabase mFirebaseDatabase; // a fire base database instance private DatabaseReference mMessagesDatabaseReference; // a database reference private ChildEventListener mChildEventListener; private FirebaseStorage mFirebaseStorage; private StorageReference mChatPhotosStorageReference; private FirebaseRemoteConfig mFirebaseRemoteConfig; private String OwnerId; // the onCreate to initialize this interface @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.message_list); mFirebaseAuth = FirebaseAuth.getInstance(); FirebaseUser user = mFirebaseAuth.getCurrentUser(); mUsername = user.getDisplayName(); mUserEmail = user.getEmail(); mUserPhotoUri = user.getPhotoUrl(); mUserUniqID = user.getUid(); postKey = getIntent().getExtras().getString("postKey"); existStatus = getIntent().getExtras().getBoolean("existStatus"); //Toast.makeText(InGroupActivity.this,String.valueOf(postKey), Toast.LENGTH_SHORT).show(); mFirebaseDatabase = FirebaseDatabase.getInstance(); mMessagesDatabaseReference = mFirebaseDatabase.getReference().child("post").child(postKey); if(existStatus == false){ User currentUser; if(mUserPhotoUri == null){ String tempPhotoUrl = ""; currentUser = new User (mUsername, mUserEmail, tempPhotoUrl, mUserUniqID); }else{ currentUser = new User(mUsername, mUserEmail, mUserPhotoUri.toString(),mUserUniqID); } String currentUserKey = mMessagesDatabaseReference.child("User").push().getKey(); mMessagesDatabaseReference.child("User").child(currentUserKey).setValue(currentUser); existStatus = true; } mFirebaseStorage = FirebaseStorage.getInstance(); mChatPhotosStorageReference = mFirebaseStorage.getReference().child("chat_photos"); mFirebaseRemoteConfig = FirebaseRemoteConfig.getInstance(); mMessageListView = (ListView) findViewById(R.id.message_list); mPhotoPickerButton = (ImageButton) findViewById(R.id.photoPickerButton); mSendButton = (Button) findViewById(R.id.message_send); mMessageEditText = (EditText) findViewById(R.id.message_content); List<Message> messages = new ArrayList<>(); mMessageAdapter = new MessageAdapter(this, R.layout.message_item, messages); mMessageListView.setAdapter(mMessageAdapter); // ImagePickerButton mPhotoPickerButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(Intent.ACTION_GET_CONTENT); intent.setType("image/jpeg"); intent.putExtra(Intent.EXTRA_LOCAL_ONLY,true); startActivityForResult(intent.createChooser(intent,"Complete action using"), RC_PHOTO_PICKER); } }); // Enable Send button mMessageEditText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { if (charSequence.toString().trim().length() > 0) { mSendButton.setEnabled(true); } else { mSendButton.setEnabled(false); } } @Override public void afterTextChanged(Editable editable) { } }); mMessageEditText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(DEFAULT_MSG_LENGTH_LIMIT)}); // Send button sends a message and clears the EditText mSendButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // Clear input box Message chatMessage = new Message(mUsername,mMessageEditText.getText().toString(), null); mMessagesDatabaseReference.child("message").push().setValue(chatMessage); mMessageEditText.setText(""); } }); mChildEventListener = new ChildEventListener() { @Override public void onChildAdded(DataSnapshot dataSnapshot, String s) { Message chatMessage = dataSnapshot.getValue(Message.class); mMessageAdapter.add(chatMessage); } @Override public void onChildChanged(DataSnapshot dataSnapshot, String s) {} @Override public void onChildRemoved(DataSnapshot dataSnapshot) {} @Override public void onChildMoved(DataSnapshot dataSnapshot, String s) {} @Override public void onCancelled(DatabaseError databaseError) {} }; mMessagesDatabaseReference.child("message").addChildEventListener(mChildEventListener); ValueEventListener OwnerListener = new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { OwnerId = dataSnapshot.getValue(String.class); } @Override public void onCancelled(DatabaseError databaseError) { } }; mMessagesDatabaseReference.child("userUId").addValueEventListener(OwnerListener); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == RC_PHOTO_PICKER && resultCode == RESULT_OK){ Uri selectedImageUri = data.getData(); StorageReference photoRef = mChatPhotosStorageReference.child(selectedImageUri.getLastPathSegment()); // it upload file and add an listener photoRef.putFile(selectedImageUri).addOnSuccessListener (this, new OnSuccessListener<UploadTask.TaskSnapshot>() { public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) { @SuppressWarnings("VisibleForTests") Uri downloadUrl = taskSnapshot.getDownloadUrl(); Toast.makeText(InGroupActivity.this,"photo uploaded", Toast.LENGTH_SHORT).show(); Log.v("photo message","photo uploading"); Message chatMessage = new Message(mUsername, null, downloadUrl.toString()); mMessagesDatabaseReference.child("message").push().setValue(chatMessage); } }); } } // Inflate the menu options from the res/menu/action_bar.xml file. @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.action_bar, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_edit: // User chose the "Settings" item, show the app settings UI... editPostInformation(); return true; case R.id.action_members: // User chose the "members" item showMemberInformation(); return true; case R.id.action_quit: quitGroupPreChecking(); return true; case R.id.action_delete: deleteGroup(); return true; case R.id.action_post_detail: showPostInformation(); return true; case android.R.id.home: Intent intent = new Intent(InGroupActivity.this, MainActivity.class); Intent_Constants.fromSearch = 0; startActivity(intent); return true; } return super.onOptionsItemSelected(item); } /** * quite from group */ //show quit group dialogue public void quitGroupPreChecking(){ if(OwnerId.equals(mUserUniqID)){ Toast.makeText(InGroupActivity.this, "You're not the Owner. You can only delete.", Toast.LENGTH_LONG).show(); }else{ showQuitConfirmationDialog(); } } public void showQuitConfirmationDialog( ) { // Create an AlertDialog.Builder and set the message, and click listeners // for the positive and negative buttons on the dialog. AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(R.string.quit_the_group); builder.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { quitFromGroup(); existStatus = false; finish(); } }); builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { //deleteThisGroup(); if (dialog != null) { dialog.dismiss(); } } }); AlertDialog alertDialog = builder.create(); alertDialog.show(); } private void quitFromGroup(){ Query userRef = mMessagesDatabaseReference.child("User").orderByChild("userName").equalTo(mUsername); userRef.addChildEventListener(new ChildEventListener() { @Override public void onChildAdded(DataSnapshot dataSnapshot, String s) { dataSnapshot.getRef().removeValue(); } @Override public void onChildChanged(DataSnapshot dataSnapshot, String s) { } @Override public void onChildRemoved(DataSnapshot dataSnapshot) { } @Override public void onChildMoved(DataSnapshot dataSnapshot, String s) { } @Override public void onCancelled(DatabaseError databaseError) { } }); } /** * show information */ public void showMemberInformation(){ Intent groupInfoIntent = new Intent(InGroupActivity.this, GroupInfoActivity.class); groupInfoIntent.putExtra("postKey",postKey); groupInfoIntent.putExtra("existStatus",existStatus); startActivityForResult(groupInfoIntent,RC_MEMBER_INFO); } /** * Update Post */ public void editPostInformation(){ if(! OwnerId.equals(mUserUniqID)){ Toast.makeText(InGroupActivity.this, "You're not the Owner of this group.", Toast.LENGTH_LONG).show(); }else{ Toast.makeText(InGroupActivity.this, "Edit The Post.", Toast.LENGTH_LONG).show(); Intent editInfoIntent = new Intent(InGroupActivity.this, EditPostActivity.class); editInfoIntent.putExtra("postKey",postKey); editInfoIntent.putExtra("existStatus",existStatus); startActivityForResult(editInfoIntent, RC_EDIT_POST); } } /** * delete group */ public void deleteGroup(){ //Log.v(TAG, Owner); if(! OwnerId.equals(mUserUniqID)){ Toast.makeText(InGroupActivity.this, "You're not the Owner of this group.", Toast.LENGTH_LONG).show(); }else{ showDeleteConfirmationDialog(); } } //show delete group dialogue public void showDeleteConfirmationDialog( ) { // Create an AlertDialog.Builder and set the message, and click listeners // for the positive and negative buttons on the dialog. AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(R.string.delete_the_group); builder.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { deleteThisGroup(); finish(); } }); builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { //deleteThisGroup(); if (dialog != null) { dialog.dismiss(); } } }); AlertDialog alertDialog = builder.create(); alertDialog.show(); } private void deleteThisGroup(){ mMessagesDatabaseReference.removeValue(); } /** * close the group */ public void showCloseConfirmationDialog( ) { // Create an AlertDialog.Builder and set the message, and click listeners // for the positive and negative buttons on the dialog. AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(R.string.close_the_group); builder.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { closeTheGroup(); //finish(); } }); builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { //deleteThisGroup(); if (dialog != null) { dialog.dismiss(); } } }); AlertDialog alertDialog = builder.create(); alertDialog.show(); } public void closeTheGroup(){ mMessagesDatabaseReference.child("openStatus").setValue(false); } /** * Open the group */ public void openTheGroup(){ mMessagesDatabaseReference.child("openStatus").setValue(true); } /** * show post detail information */ public void showPostInformation(){ Intent showPostInfoIntent = new Intent(InGroupActivity.this, EditPostActivity.class); showPostInfoIntent.putExtra("postKey",postKey); showPostInfoIntent.putExtra("existStatus",existStatus); showPostInfoIntent.putExtra("onlyShow",true); startActivity(showPostInfoIntent); } }
true
35e7116af513a6ac7254556ddf7d845feeebe702
Java
nendraharyo/presensimahasiswa-sourcecode
/com/google/android/gms/common/internal/zzm.java
UTF-8
7,855
1.734375
2
[]
no_license
package com.google.android.gms.common.internal; import android.content.ComponentName; import android.content.Context; import android.content.ServiceConnection; import android.os.Handler; import android.os.Handler.Callback; import android.os.IBinder; import android.os.Looper; import android.os.Message; import com.google.android.gms.common.stats.zzb; import java.util.HashMap; final class zzm extends zzl implements Handler.Callback { private final Handler mHandler; private final HashMap zzalZ; private final zzb zzama; private final long zzamb; private final Context zzsa; zzm(Context paramContext) { Object localObject = new java/util/HashMap; ((HashMap)localObject).<init>(); this.zzalZ = ((HashMap)localObject); localObject = paramContext.getApplicationContext(); this.zzsa = ((Context)localObject); localObject = new android/os/Handler; Looper localLooper = paramContext.getMainLooper(); ((Handler)localObject).<init>(localLooper, this); this.mHandler = ((Handler)localObject); localObject = zzb.zzrP(); this.zzama = ((zzb)localObject); this.zzamb = 5000L; } private boolean zza(zzm.zza paramzza, ServiceConnection paramServiceConnection, String paramString) { Object localObject1 = "ServiceConnection must not be null"; zzx.zzb(paramServiceConnection, localObject1); for (;;) { Object localObject3; Object localObject4; synchronized (this.zzalZ) { localObject1 = this.zzalZ; localObject1 = ((HashMap)localObject1).get(paramzza); localObject1 = (zzm.zzb)localObject1; if (localObject1 == null) { localObject1 = new com/google/android/gms/common/internal/zzm$zzb; ((zzm.zzb)localObject1).<init>(this, paramzza); ((zzm.zzb)localObject1).zza(paramServiceConnection, paramString); ((zzm.zzb)localObject1).zzcH(paramString); localObject3 = this.zzalZ; ((HashMap)localObject3).put(paramzza, localObject1); boolean bool1 = ((zzm.zzb)localObject1).isBound(); return bool1; } localObject3 = this.mHandler; localObject4 = null; ((Handler)localObject3).removeMessages(0, localObject1); boolean bool2 = ((zzm.zzb)localObject1).zza(paramServiceConnection); if (bool2) { localObject1 = new java/lang/IllegalStateException; localObject3 = new java/lang/StringBuilder; ((StringBuilder)localObject3).<init>(); localObject4 = "Trying to bind a GmsServiceConnection that was already connected before. config="; localObject3 = ((StringBuilder)localObject3).append((String)localObject4); localObject3 = ((StringBuilder)localObject3).append(paramzza); localObject3 = ((StringBuilder)localObject3).toString(); ((IllegalStateException)localObject1).<init>((String)localObject3); throw ((Throwable)localObject1); } } ((zzm.zzb)localObject2).zza(paramServiceConnection, paramString); int i = ((zzm.zzb)localObject2).getState(); switch (i) { default: break; case 1: localObject3 = ((zzm.zzb)localObject2).getComponentName(); localObject4 = ((zzm.zzb)localObject2).getBinder(); paramServiceConnection.onServiceConnected((ComponentName)localObject3, (IBinder)localObject4); break; case 2: ((zzm.zzb)localObject2).zzcH(paramString); } } } private void zzb(zzm.zza paramzza, ServiceConnection paramServiceConnection, String paramString) { Object localObject1 = "ServiceConnection must not be null"; zzx.zzb(paramServiceConnection, localObject1); Object localObject4; String str; synchronized (this.zzalZ) { localObject1 = this.zzalZ; localObject1 = ((HashMap)localObject1).get(paramzza); localObject1 = (zzm.zzb)localObject1; if (localObject1 == null) { localObject1 = new java/lang/IllegalStateException; localObject4 = new java/lang/StringBuilder; ((StringBuilder)localObject4).<init>(); str = "Nonexistent connection status for service config: "; localObject4 = ((StringBuilder)localObject4).append(str); localObject4 = ((StringBuilder)localObject4).append(paramzza); localObject4 = ((StringBuilder)localObject4).toString(); ((IllegalStateException)localObject1).<init>((String)localObject4); throw ((Throwable)localObject1); } } boolean bool = ((zzm.zzb)localObject2).zza(paramServiceConnection); Object localObject3; if (!bool) { localObject3 = new java/lang/IllegalStateException; localObject4 = new java/lang/StringBuilder; ((StringBuilder)localObject4).<init>(); str = "Trying to unbind a GmsServiceConnection that was not bound before. config="; localObject4 = ((StringBuilder)localObject4).append(str); localObject4 = ((StringBuilder)localObject4).append(paramzza); localObject4 = ((StringBuilder)localObject4).toString(); ((IllegalStateException)localObject3).<init>((String)localObject4); throw ((Throwable)localObject3); } ((zzm.zzb)localObject3).zzb(paramServiceConnection, paramString); bool = ((zzm.zzb)localObject3).zzqT(); if (bool) { localObject4 = this.mHandler; str = null; localObject3 = ((Handler)localObject4).obtainMessage(0, localObject3); localObject4 = this.mHandler; long l = this.zzamb; ((Handler)localObject4).sendMessageDelayed((Message)localObject3, l); } } public boolean handleMessage(Message paramMessage) { int i = paramMessage.what; Object localObject1; switch (i) { default: i = 0; localObject1 = null; } for (;;) { return i; localObject1 = (zzm.zzb)paramMessage.obj; synchronized (this.zzalZ) { boolean bool = ((zzm.zzb)localObject1).zzqT(); if (bool) { bool = ((zzm.zzb)localObject1).isBound(); if (bool) { localObject3 = "GmsClientSupervisor"; ((zzm.zzb)localObject1).zzcI((String)localObject3); } Object localObject3 = this.zzalZ; localObject1 = zzm.zzb.zza((zzm.zzb)localObject1); ((HashMap)localObject3).remove(localObject1); } int j = 1; } } } public boolean zza(ComponentName paramComponentName, ServiceConnection paramServiceConnection, String paramString) { zzm.zza localzza = new com/google/android/gms/common/internal/zzm$zza; localzza.<init>(paramComponentName); return zza(localzza, paramServiceConnection, paramString); } public boolean zza(String paramString1, ServiceConnection paramServiceConnection, String paramString2) { zzm.zza localzza = new com/google/android/gms/common/internal/zzm$zza; localzza.<init>(paramString1); return zza(localzza, paramServiceConnection, paramString2); } public void zzb(ComponentName paramComponentName, ServiceConnection paramServiceConnection, String paramString) { zzm.zza localzza = new com/google/android/gms/common/internal/zzm$zza; localzza.<init>(paramComponentName); zzb(localzza, paramServiceConnection, paramString); } public void zzb(String paramString1, ServiceConnection paramServiceConnection, String paramString2) { zzm.zza localzza = new com/google/android/gms/common/internal/zzm$zza; localzza.<init>(paramString1); zzb(localzza, paramServiceConnection, paramString2); } } /* Location: C:\Users\haryo\Desktop\enjarify-master\presensi-enjarify.jar!\com\google\android\gms\common\internal\zzm.class * Java compiler version: 5 (49.0) * JD-Core Version: 0.7.1 */
true
58dc8fabba23d0e1ddb3229b503fdbe00e0d3c1d
Java
yhsiashen/algorithm-exercise
/src/main/java/org/yuhang/algorithm/leetcode/backtracealgo/ProblemExpressionAddOperators.java
UTF-8
493
2.75
3
[]
no_license
package org.yuhang.algorithm.leetcode.backtracealgo; import java.util.ArrayList; import java.util.List; /** * 给表达式加运算符 LC282 * TODO */ public class ProblemExpressionAddOperators { public List<String> addOperators(String num, int target) { List<String> res = new ArrayList<>(); if("".equals(num)) return res; backtrace(num,target,res); return res; } private void backtrace(String num, int target, List<String> res) { } }
true
3ac7b975abb224a6999b732af9f4e572bc332bbb
Java
smartdevicelink/rpc_builder_app_android
/RPCBuilder/app/src/main/java/com/smartdevicelink/rpcbuilder/Views/RBStructParamView.java
UTF-8
201
1.554688
2
[]
permissive
package com.smartdevicelink.rpcbuilder.Views; import android.content.Context; public class RBStructParamView extends RBParamView { public RBStructParamView(Context context) { super(context); } }
true
02cdbadb36e4a69447b8645107433d2990057ea3
Java
guapihao/wrwe
/app/src/main/java/com/example/search/FourthActivity.java
UTF-8
790
2.03125
2
[]
no_license
package com.example.search; import android.widget.Button; import android.view.View; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; public class FourthActivity extends AppCompatActivity { private Button btn4; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_fourth); btn4 = (Button) findViewById(R.id.button4); btn4.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v){ Intent i = new Intent(FourthActivity.this , FifthActivity.class); ////启动 startActivity(i); } }); } }
true
9d6fd6596c387d8946bc7cc6b4c9fdda1c151a1c
Java
Wolfgang-Schuetzelhofer/jcypher-server
/src/main/java/iot/jcypher/server/config/DBAccessConfig.java
UTF-8
3,061
1.914063
2
[ "Apache-2.0" ]
permissive
/************************************************************************ * Copyright (c) 2016 IoT-Solutions e.U. * * 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 iot.jcypher.server.config; import java.util.HashMap; import java.util.Map; import java.util.Properties; import com.fasterxml.jackson.annotation.JsonProperty; import iot.jcypher.database.DBAccessFactory; import iot.jcypher.database.DBProperties; import iot.jcypher.database.DBType; import iot.jcypher.database.IDBAccess; import iot.jcypher.domain.IDomainAccessFactory; import iot.jcypher.domain.IGenericDomainAccess; import iot.jcypher.server.resources.Neo4jDBInfo; public class DBAccessConfig { private String name; private String url; private String userId; private String password; private IDBAccess dbAccess; private Map<String, IGenericDomainAccess> domainAccessMap; @JsonProperty public String getName() { return name; } @JsonProperty public void setName(String name) { this.name = name; } @JsonProperty public String getUrl() { return url; } @JsonProperty public void setUrl(String url) { this.url = url; } @JsonProperty public String getUserId() { return userId; } @JsonProperty public void setUserId(String userId) { this.userId = userId; } @JsonProperty public String getPassword() { return password; } @JsonProperty public void setPassword(String password) { this.password = password; } public IDBAccess getDBAccess() { if (this.dbAccess == null) { Properties props = new Properties(); props.setProperty(DBProperties.SERVER_ROOT_URI, getUrl()); if (this.userId != null && this.password != null) dbAccess = DBAccessFactory.createDBAccess(DBType.REMOTE, props, userId, password); else dbAccess = DBAccessFactory.createDBAccess(DBType.REMOTE, props); } return dbAccess; } public IGenericDomainAccess getDomainAccess(String domainName) { if (this.domainAccessMap == null) this.domainAccessMap = new HashMap<String, IGenericDomainAccess>(); IGenericDomainAccess da = this.domainAccessMap.get(domainName); if (da == null) { da = IDomainAccessFactory.INSTANCE.createGenericDomainAccess(getDBAccess(), domainName); this.domainAccessMap.put(domainName, da); } return da; } public void clearDomainCache() { this.domainAccessMap = null; } public Neo4jDBInfo getDBInfo() { Neo4jDBInfo ret = new Neo4jDBInfo(); ret.setName(name); ret.setUrl(url); return ret; } }
true
8196badbb2d8f2934248d48b7f617f4701786816
Java
POPO-J-E/SMA_Puzzle
/src/simulation/puzzle/MySimulationModel.java
UTF-8
2,855
3.046875
3
[]
no_license
package simulation.puzzle; import madkit.kernel.AbstractAgent; import java.awt.*; import java.util.ArrayList; import java.util.List; import java.util.Random; /** * * * #jws simulation.puzzle.MySimulationModel jws# * * It is time to display something !! The only purpose of this class is to show an example of what could be a launching * sequence. The display work is done in {@link Viewer} */ public class MySimulationModel extends AbstractAgent { // Organizational constants public static final String MY_COMMUNITY = "simu"; public static final String SIMU_GROUP = "simu"; public static final String AGENT_ROLE = "agent"; public static final String ENV_ROLE = "environment"; public static final String SCH_ROLE = "scheduler"; public static final String VIEWER_ROLE = "viewer"; public static final int AGENT_NUMBER = 23; public static final int WIDTH = 5; public static final int HEIGHT = 5; @Override protected void activate() { // 1 : create the simulation group createGroup(MY_COMMUNITY, SIMU_GROUP); // 2 : create the environment EnvironmentAgent environment = new EnvironmentAgent(WIDTH, HEIGHT); launchAgent(environment); List<Dimension> starts = new ArrayList<>(WIDTH*HEIGHT); List<Dimension> targets = new ArrayList<>(WIDTH*HEIGHT); List<Integer> agents = new ArrayList<>(WIDTH*HEIGHT); fillList(starts,environment.getDimension()); fillList(targets,environment.getDimension()); fillAgentList(agents,environment.getDimension()); Random rand = new Random(); // 4 : launch some simulated agents for (int i = 0; i < AGENT_NUMBER; i++) { int start = rand.nextInt(starts.size()-1); int agentNumber = rand.nextInt(agents.size()-1); int target = agents.remove(agentNumber); AbstractAgent agent1 = new SituatedAgent(starts.remove(start), targets.get(target), target+1); launchAgent(agent1); } environment.initWhites(); // 5 : create the scheduler MyScheduler scheduler = new MyScheduler(); launchAgent(scheduler, true); // 3 : create the viewer Viewer viewer = new Viewer(); launchAgent(viewer, true); } private void fillList(List<Dimension> dims, Dimension dimension) { for (int j=0; j<dimension.getHeight(); j++) { for (int i=0; i<dimension.getWidth(); i++){ dims.add(new Dimension(i,j)); } } } private void fillAgentList(List<Integer> agents, Dimension dimension) { for (int i=0; i<dimension.width*dimension.height; i++){ agents.add(i); } } public static void main(String[] args) { executeThisAgent(1, false); // no gui for me } }
true
27e6d892dbba99df140647b023d5122f458b2904
Java
Guiedo/Mambo
/mambo-protocol/src/main/java/org/mambo/protocol/messages/QuestStepInfoMessage.java
UTF-8
933
2
2
[]
no_license
// Generated on 05/08/2013 19:37:50 package org.mambo.protocol.messages; import java.util.*; import org.mambo.protocol.types.*; import org.mambo.protocol.enums.*; import org.mambo.protocol.*; import org.mambo.core.io.*; public class QuestStepInfoMessage extends NetworkMessage { public static final int MESSAGE_ID = 5625; @Override public int getNetworkMessageId() { return MESSAGE_ID; } public QuestActiveInformations infos; public QuestStepInfoMessage() { } public QuestStepInfoMessage(QuestActiveInformations infos) { this.infos = infos; } @Override public void serialize(Buffer buf) { buf.writeShort(infos.getTypeId()); infos.serialize(buf); } @Override public void deserialize(Buffer buf) { infos = ProtocolTypeManager.getInstance().build(buf.readShort()); infos.deserialize(buf); } }
true
094c7ffab198a89deb547a37b8f23dddf5d51396
Java
ganigemilar/tugas1_apap_1606954810
/src/main/java/com/example/tugas1/dao/MahasiswaMapper.java
UTF-8
3,274
2.0625
2
[]
no_license
package com.example.tugas1.dao; import java.util.List; import org.apache.ibatis.annotations.Delete; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Result; import org.apache.ibatis.annotations.Results; import org.apache.ibatis.annotations.Select; import org.apache.ibatis.annotations.Update; import com.example.tugas1.model.MahasiswaModel; @Mapper public interface MahasiswaMapper { @Select("SELECT * FROM mahasiswa WHERE id=#{id}") @Results({ @Result(property = "tempatLahir", column = "tempat_lahir"), @Result(property = "tanggalLahir", column = "tanggal_lahir"), @Result(property = "jenisKelamin", column = "jenis_kelamin"), @Result(property = "golonganDarah", column = "golongan_darah"), @Result(property = "tahunMasuk", column = "tahun_masuk"), @Result(property = "jalurMasuk", column = "jalur_masuk"), @Result(property = "idProdi", column = "id_prodi") }) MahasiswaModel selectMahasiswa(@Param("id") int id); @Select("SELECT * FROM mahasiswa WHERE npm=#{npm}") @Results({ @Result(property = "tempatLahir", column = "tempat_lahir"), @Result(property = "tanggalLahir", column = "tanggal_lahir"), @Result(property = "jenisKelamin", column = "jenis_kelamin"), @Result(property = "golonganDarah", column = "golongan_darah"), @Result(property = "tahunMasuk", column = "tahun_masuk"), @Result(property = "jalurMasuk", column = "jalur_masuk"), @Result(property = "idProdi", column = "id_prodi") }) MahasiswaModel selectMahasiswaByNPM(@Param("npm") String npm); @Select("SELECT * FROM mahasiswa") @Results({ @Result(property = "tempatLahir", column = "tempat_lahir"), @Result(property = "tanggalLahir", column = "tanggal_lahir"), @Result(property = "jenisKelamin", column = "jenis_kelamin"), @Result(property = "golonganDarah", column = "golongan_darah"), @Result(property = "tahunMasuk", column = "tahun_masuk"), @Result(property = "jalurMasuk", column = "jalur_masuk"), @Result(property = "idProdi", column = "id_prodi") }) List<MahasiswaModel> selectAllMahasiswa(); @Insert("INSERT INTO mahasiswa VALUES (" + "#{mahasiswa.npm}," + "#{mahasiswa.nama}," + "#{mahasiswa.tempatLahir}," + "#{mahasiswa.tanggalLahir}," + "#{mahasiswa.jenisKelamin}," + "#{mahasiswa.agama}," + "#{mahasiswa.golonganDarah}," + "#{mahasiswa.status}," + "#{mahasiswa.tahunMasuk}," + "#{mahasiswa.jalurMasuk}," + "#{mahasiswa.idProdi})") void insertMahasiwa(@Param("mahasiwa") MahasiswaModel mahasiswa); @Update("UPDATE mahasiswa SET " + "npm=#{mahasiswa.npm}," + "nama=#{mahasiswa.nama}," + "tempat_lahir=#{mahasiswa.tempatLahir}," + "tanggal_lahir=#{mahasiswa.tanggalLahir}," + "jenis_kelamin=#{mahasiswa.jenisKelamin}," + "agama=#{mahasiswa.agama}," + "golongan_darah=#{mahasiswa.golonganDarah}," + "status=#{mahasiswa.status}," + "tahun_masuk=#{mahasiswa.tahunMasuk}," + "jalur_masuk=#{mahasiswa.jalurMasuk}," + "id_prodi=#{mahasiswa.idProdi}" + " WHERE id=#{mahasiswa.id}") void updateMahasiswa(@Param("mahasiwa") MahasiswaModel mahasiswa); @Delete("DELETE FROM mahasiwa WHERE id=#{id}") void deleteMahasiswa(@Param("id") int id); }
true
708c39ee437f9813552491b6bacd211b16d98177
Java
zhongxingyu/Seer
/Diff-Raw-Data/34/34_ab26a2caa0cf05715fc7c50cdeb57cbbd079ba02/IHarvest/34_ab26a2caa0cf05715fc7c50cdeb57cbbd079ba02_IHarvest_s.java
UTF-8
4,369
2.265625
2
[]
no_license
/* This file is part of opensearch. Copyright © 2009, Dansk Bibliotekscenter a/s, Tempovej 7-11, DK-2750 Ballerup, Denmark. CVR: 15149043 opensearch is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. opensearch is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with opensearch. If not, see <http://www.gnu.org/licenses/>. */ package dk.dbc.opensearch.components.harvest; import dk.dbc.opensearch.common.types.IJob; import dk.dbc.opensearch.common.types.IIdentifier; import java.util.List; /** * Interface that defines the operations of a data-harvester The * development goals of the harvester application is to make it a * service. Implementations should consider this and aim at modelling * towards this. */ public interface IHarvest { /** * The start method. This method initiates the service after an * instance has been constructed. */ void start() throws HarvesterIOException; /** * The shutdown method. Should be used to shutdown the harvester * completely and not after each request. */ void shutdown() throws HarvesterIOException; /** * This method delivers information about which jobs the requestor * can recieve. A {@link IJob} should contain * information on how the requestor can or must obtain data from * the harvester. * * @param maxAmount specifies the maximum amount of jobs to be written to the {@link List} * @return an {@link IJob} containing information about jobs that the requestor can obtain. */ List<IJob> getJobs( int maxAmount ) throws HarvesterIOException, HarvesterInvalidStatusChangeException; /** * Given an {@link IIdentifier} the requestor can obtain the data * associated with the {@code jobId}. {@code jobId} is usually * obtained from a {@link IJob}, which in turn can be obtained * from {@link #getJobs(int)}. * * @param jobId an {@link IIdentifier} that uniquely identifies a job with in the {@link IHarvester} * @return a byte[] containing the data identified by the {@code jobId} * * @throws UnknownIdentifierException if the {@link IIdentifier} is not known to the {@link IHarvester}. I.e. if the jobId can not be found */ byte[] getData( IIdentifier jobId ) throws HarvesterUnknownIdentifierException, HarvesterIOException; /** * This method lets the requestor/client set the status of a job * identified by {@code jobId}. A status can only be set once for * a given job; a {@link Job} that has not had its status set, * will be unset. Trying to set a status more than once will * result in an error condition (signalled by an * {@link HarvesterInvalidStatusChangeException}). * * @see JobStatus for more information on the states of jobs in the {@link IHarvester} * * @param jobId an {@link IIdentifier} that uniquely identifies a job with in the {@link IHarvester} * * @throws UnknownIdentifierException if the {@code jobId} could not be found in the {@link IHarvester} * @throws HarvesterInvalidStatusChangeException if the client tries to set the status more than once on a given {@code jobId} */ // void setStatus( IIdentifier jobId, JobStatus status ) throws HarvesterUnknownIdentifierException, HarvesterInvalidStatusChangeException, HarvesterIOException; void setStatusFailure( IIdentifier jobId, String failureDiagnostic ) throws HarvesterUnknownIdentifierException, HarvesterInvalidStatusChangeException, HarvesterIOException; void setStatusSuccess( IIdentifier jobId, String PID ) throws HarvesterUnknownIdentifierException, HarvesterInvalidStatusChangeException, HarvesterIOException; void setStatusRetry( IIdentifier jobId ) throws HarvesterUnknownIdentifierException, HarvesterInvalidStatusChangeException, HarvesterIOException; }
true
3f74f9dc81a96399ae6ad7204cd3c2412a24f8a8
Java
15701266382/dubbo-common-parent
/dubbo-web-shiro/src/main/java/com/zml/web/shiro/cache/RedisCache.java
UTF-8
2,696
2.453125
2
[]
no_license
package com.zml.web.shiro.cache; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Set; import org.apache.commons.collections.CollectionUtils; import org.apache.shiro.cache.Cache; import org.apache.shiro.cache.CacheException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.zml.common.constant.CacheConstant; import com.zml.common.utils.cache.redis.RedisUtil; import com.zml.common.utils.cache.redis.SerializeUtils; public class RedisCache<K,V> implements Cache<K,V> { private Logger logger = LoggerFactory.getLogger(this.getClass()); private RedisUtil<V> redisUtil; public RedisCache(RedisUtil<V> redisUtil) { this.redisUtil = redisUtil; } public V get(K key) throws CacheException { logger.debug("根据key获取,key=" + key + " RedisCacheKey: " + this.getRedisCacheKey(key)); V value = this.redisUtil.getCacheObject(this.getRedisCacheKey(key)); return value; } public V put(K key, V value) throws CacheException { logger.debug("根据key存储value,key=" + key + " RedisCacheKey: " + this.getRedisCacheKey(key) + "value: " + value); this.redisUtil.setCacheObject(this.getRedisCacheKey(key), value); return value; } public V remove(K key) throws CacheException { logger.debug("根据key删除,key=" + key + " RedisCacheKey: " + this.getRedisCacheKey(key)); this.redisUtil.delete(this.getRedisCacheKey(key)); return null; } /** * 数据量大的时候慎用,线上慎用 */ public void clear() throws CacheException { this.redisUtil.deleteByPrex(CacheConstant.SHIRO_REDIS_CACHE); } public int size() { Set<String> set = this.redisUtil.keys(CacheConstant.SHIRO_REDIS_CACHE); if(CollectionUtils.isNotEmpty(set)) { return set.size(); } else { return 0; } } @SuppressWarnings("unchecked") public Set<K> keys() { Set<String> set = this.redisUtil.keys(CacheConstant.SHIRO_REDIS_CACHE); if(CollectionUtils.isNotEmpty(set)) { return (Set<K>) set; } else { return Collections.emptySet(); } } public Collection<V> values() { Set<K> keys = this.keys(); List<V> values = new ArrayList<V>(keys.size()); for(K key : keys) { V value = get(key); if (value != null) { values.add(value); } } return Collections.unmodifiableList(values); } private String getRedisCacheKey(K key) { if(key instanceof String) { return CacheConstant.SHIRO_REDIS_CACHE + key; } else { return CacheConstant.SHIRO_REDIS_CACHE + new SerializeUtils().seriazileAsString(key); } } }
true
83714a296e19a4ba4d41e98ef6f74ebc8ba8bc14
Java
Artsysa/struct
/src/main/java/nio/chart/GroupServer.java
UTF-8
5,024
2.75
3
[]
no_license
package nio.chart; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.*; import java.util.Iterator; import java.util.Scanner; import java.util.Set; /* * @breif: * @Author: lyq * @Date: 2020/7/15 14:45 * @Month:07 */ public class GroupServer { private ServerSocketChannel serverSocketChannel; private String host="127.0.0.1"; private int port=9000; private Selector selector; GroupServer(){ try { selector = Selector.open(); serverSocketChannel = ServerSocketChannel.open(); serverSocketChannel.socket().bind(new InetSocketAddress(host,port)); serverSocketChannel.configureBlocking(false); serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT); } catch (Exception e) { e.printStackTrace(); } } private void listen(){ while(true){ String ip=""; try { int select = selector.select(); if(select>0){ Set<SelectionKey> selectionKeys = selector.selectedKeys(); Iterator<SelectionKey> it = selectionKeys.iterator(); while (it.hasNext()){ SelectionKey next = it.next(); if(next.isAcceptable()){ SocketChannel accept = serverSocketChannel.accept(); accept.configureBlocking(false); accept.register(selector,SelectionKey.OP_READ); ip=accept.getLocalAddress().toString(); System.out.println(accept.getLocalAddress()+"-上线了"); } if(next.isReadable()){ SocketChannel channel = (SocketChannel) next.channel(); ByteBuffer b = ByteBuffer.allocate(1024); channel.read(b); //System.out.println(); // sendInfoToOtherClients(new String(b.array()),channel); dispatch(b,channel); } it.remove(); } } } catch (Exception e) { System.out.println(ip+"关闭了客户端"); } } } /** * 分发到其他客户端 * @param b */ private void dispatch(ByteBuffer b,Channel se){ for(SelectionKey key:selector.keys()){ Channel channel=key.channel(); if (channel instanceof SocketChannel ) { //转型 SocketChannel dest = (SocketChannel) channel; //将msg 存储到buffer b.flip(); //ByteBuffer buffer = ByteBuffer.wrap(b.getBytes()); //将buffer 的数据写入 通道 try { dest.write(b); } catch (Exception e) { e.printStackTrace(); } } } // //System.out.println("转发信息"); // Set<SelectionKey> keys = selector.keys(); // // System.out.println(keys.size()); // Iterator<SelectionKey> it = keys.iterator(); // // int count=0; // while(it.hasNext()){ // SelectionKey next = it.next(); // SelectableChannel channel1 = next.channel(); // if(channel1 instanceof SocketChannel&&channel1!=se){ // // count++; // SocketChannel channel = (SocketChannel) channel1; // try { // channel.write(b); // } catch (Exception e) { // e.printStackTrace(); // } // } // // } } //转发消息给其它客户(通道) private void sendInfoToOtherClients(String msg, SocketChannel self ) throws IOException { System.out.println("服务器转发消息中..."); System.out.println("服务器转发数据给客户端线程: " + Thread.currentThread().getName()); //遍历 所有注册到selector 上的 SocketChannel,并排除 self for (SelectionKey key : selector.keys()) { //通过 key 取出对应的 SocketChannel Channel targetChannel = key.channel(); //排除自己 if (targetChannel instanceof SocketChannel && targetChannel != self) { //转型 SocketChannel dest = (SocketChannel) targetChannel; //将msg 存储到buffer ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes()); //将buffer 的数据写入 通道 dest.write(buffer); } } } public static void main(String[] args) throws IOException { GroupServer groupServer = new GroupServer(); new Thread(()->{ groupServer.listen(); }).start(); } }
true
809d80d808ace9fb9c11c8135c3a3cbab262f2f7
Java
jimmitry/mentdb_weak
/src/re/jpayet/mentdb/ext/parameter/ParamCache.java
UTF-8
163
1.78125
2
[]
no_license
package re.jpayet.mentdb.ext.parameter; public class ParamCache { public String value = null; public ParamCache(String value) { this.value = value; } }
true
0321112b4be21dc5df9d0d3949ca7d330da5c38d
Java
Lo1s/JavaIntroduction
/src/chapter18/PE1818_NationalFlags.java
UTF-8
2,948
2.875
3
[]
no_license
/** * */ package chapter18; import java.applet.AudioClip; import java.awt.BorderLayout; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.ImageIcon; import javax.swing.JApplet; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextArea; import javax.swing.Timer; /** * @author jslapnicka * @Date & @Time 21. 10. 2014 2014 8:08:05 */ @SuppressWarnings("serial") public class PE1818_NationalFlags extends JApplet { private int numberOfCountries; private String[] titles; private String[] descriptions; private ImageIcon[] flags; private AudioClip[] audioClips; private Timer timer; private int count = 0; JLabel jlblFlag = new JLabel(); JLabel jlblTitle = new JLabel(); JTextArea jtaDescription = new JTextArea(); public PE1818_NationalFlags() { // TODO Auto-generated constructor stub } @Override public void init() { setSize(450, 200); // Getting the paramaters from the XML file numberOfCountries = Integer.parseInt(getParameter("numberOfCountries")); titles = new String[numberOfCountries]; flags = new ImageIcon[numberOfCountries]; audioClips = new AudioClip[numberOfCountries]; descriptions = new String[numberOfCountries]; for (int i = 0; i < numberOfCountries; i++) { titles[i] = getParameter("name" + i); descriptions[i] = getParameter("description" + i); flags[i] = new ImageIcon(getClass().getResource("image/flag" + i + ".gif")); audioClips[i] = getAudioClip(getClass().getResource("audio/anthem" + i + ".mid")); } // Setting up the UI timer = new Timer(10000, new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { // TODO Auto-generated method stub jtaDescription.setText(descriptions[count]); jlblFlag.setIcon(flags[count]); jlblTitle.setText(titles[count]); audioClips[count].play(); if (count != 0) audioClips[count - 1].stop(); count++; if (count == 7) count = 0; } }); timer.start(); jlblFlag.setHorizontalAlignment(JLabel.CENTER); jlblTitle.setHorizontalAlignment(JLabel.CENTER); jlblTitle.setHorizontalTextPosition(JLabel.CENTER); JPanel panel = new JPanel(new BorderLayout()); panel.add(jlblFlag, BorderLayout.CENTER); panel.add(jlblTitle, BorderLayout.SOUTH); setLayout(new GridLayout(1, 2)); add(panel); add(jtaDescription); } @Override public void start() { } @Override public void stop() { } @Override public void destroy() { } public static void main(String[] args) { // TODO Auto-generated method stub PE1818_NationalFlags applet = new PE1818_NationalFlags(); JFrame frame = new JFrame(); applet.init(); frame.add(applet); frame.setTitle("Exercise18_08"); frame.pack(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLocationRelativeTo(null); frame.setVisible(true); } }
true
35591c11bd95511dc94bb9a9d12deda9a5fed73f
Java
fcv/wiquery-test
/src/main/java/br/fcv/wiquery_test/support/wicket/JQueryPjaxJavaScriptReference.java
UTF-8
583
1.851563
2
[]
no_license
package br.fcv.wiquery_test.support.wicket; import org.apache.wicket.request.resource.SharedResourceReference; import br.fcv.wiquery_test.WicketApplication; public class JQueryPjaxJavaScriptReference extends SharedResourceReference { private static final JQueryPjaxJavaScriptReference INSTANCE = new JQueryPjaxJavaScriptReference(); public static final JQueryPjaxJavaScriptReference getInstance() { return INSTANCE; } public JQueryPjaxJavaScriptReference() { super(WicketApplication.class, "jquery.pjax.js"); } }
true
7990ea0cac73476146d8c72b361b0e71eecaf276
Java
minthubk/androidChatPro
/src/com/example/chatsignalrclient/views/MessageActivity.java
UTF-8
7,789
1.976563
2
[]
no_license
package com.example.chatsignalrclient.views; import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import com.example.chatsignalrclient.R; import com.example.chatsignalrclient.R.id; import com.example.chatsignalrclient.R.layout; import com.example.chatsignalrclient.model.APIHandling; import android.app.Activity; import android.content.Intent; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.media.ThumbnailUtils; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.provider.MediaStore; import android.provider.MediaStore.Video.Thumbnails; import android.view.View; import android.view.View.OnClickListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.Toast; public class MessageActivity extends Activity{ // -------------------------------- Java Instance Variable APIHandling uniqueMA = APIHandling.getInstance(); public static String userTo = ""; private String userFrom = ""; public static ArrayAdapter<MessageBean> mAdapter; private static ArrayList<MessageBean> mStrings = new ArrayList<MessageBean>(); private static final int SELECT_PHOTO = 100; // -------------------------------- Java Instance Variable // -------------------------------- Android Instance Variable private EditText editText_Message; private Button button_Submit; private Button button_Share; public static ListView listView_Message; public static Handler handler; // -------------------------------- Android Instance Variable @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_msg); handler = new Handler(); setContents(); setHandlers(); } private void setContents(){ listView_Message = (ListView)findViewById(R.id.list_Msg_User); editText_Message = (EditText)findViewById(R.id.editText_Messages); button_Submit = (Button)findViewById(R.id.button_Submit); button_Share = (Button)findViewById(R.id.button_Share); mAdapter = new MessageAdapter(MessageActivity.this, R.layout.msg_row, mStrings); listView_Message.setAdapter(mAdapter); mAdapter.notifyDataSetChanged(); } private void setHandlers(){ if(getIntent().getExtras().getString("SOrG").equalsIgnoreCase("SINGLE")){ userTo = getIntent().getExtras().getString("USER_TO"); } else if(getIntent().getExtras().getString("SOrG").equalsIgnoreCase("GROUP")){ userTo = getIntent().getExtras().getString("USER_TO"); } userFrom = uniqueMA.userName; // Code that executes on the pressing of the send button......... By Kumar Vivek Mitra 26-5-2014 button_Submit.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if(!editText_Message.getText().toString().trim().equalsIgnoreCase("")){ String msg = editText_Message.getText().toString().trim(); if (getIntent().getExtras().getString("SOrG").equalsIgnoreCase("SINGLE")) { uniqueMA.hub.invoke("EntryPoint", "SendToClient",userFrom, msg, userTo, ""); mAdapter.add(new MessageBean(msg, null, null)); editText_Message.setText(""); } else if(getIntent().getExtras().getString("SOrG").equalsIgnoreCase("GROUP")){ System.out.println("I AM IN GROUP"); Toast.makeText(MessageActivity.this,"I AM IN GROUP",Toast.LENGTH_SHORT).show(); uniqueMA.hub.invoke("EntryPoint", "GroupMessage",userFrom, msg, "",userTo); mAdapter.add(new MessageBean(msg, null, null)); editText_Message.setText(""); } } } }); // Code to handle the upload of the media files......... By Kumar Vivek Mitra 29-5-2014 button_Share.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent photoPickerIntent = new Intent(Intent.ACTION_PICK); photoPickerIntent.setType("image/* video/*"); startActivityForResult(photoPickerIntent, SELECT_PHOTO); } }); } // static method to handle the message from the user......... By Kumar Vivek Mitra 27-5-2014 public static void receiveText(final String msgFromUser) { new Thread(new Runnable() { @Override public void run() { handler.post(new Runnable() { @Override public void run() { mAdapter.add(new MessageBean(msgFromUser, null, null)); mAdapter.notifyDataSetChanged(); listView_Message.invalidateViews(); } }); } }).start(); } // static method to handle the media file from the user.......... By Kumar Vivek Mitra 30-5-2014 public static void receiveFile(final String fileFromUser) { new Thread(new Runnable() { @Override public void run() { handler.post(new Runnable() { @Override public void run() { Uri externalFile = Uri.fromFile(new File(fileFromUser)); if(fileFromUser.endsWith(".jpg") || fileFromUser.endsWith(".png") || fileFromUser.endsWith(".JPG") || fileFromUser.endsWith(".PNG")){ mAdapter.add(new MessageBean("", externalFile, null)); mAdapter.notifyDataSetChanged(); listView_Message.invalidateViews(); } else if(fileFromUser.endsWith(".3gp") || fileFromUser.endsWith(".3GP") || fileFromUser.endsWith(".mp4") || fileFromUser.endsWith(".MP4") || fileFromUser.endsWith(".avi") || fileFromUser.endsWith(".AVI")){ mAdapter.add(new MessageBean("", null, externalFile)); mAdapter.notifyDataSetChanged(); listView_Message.invalidateViews(); } } }); } }).start(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) { super.onActivityResult(requestCode, resultCode, imageReturnedIntent); System.out.println("I AM HERE JUST OUTSIDE SELECT_1"); switch(requestCode) { case SELECT_PHOTO: System.out.println("I AM HERE JUST INSIDE SELECT_2"); if(resultCode == RESULT_OK){ System.out.println("I AM HERE JUST INSIDE SELECT_3"); Uri selectedImage = imageReturnedIntent.getData(); File fx = new File(getRealPathFromURI(selectedImage)); String filePath = fx.getAbsolutePath().toString().trim(); if(filePath.endsWith(".jpg") || filePath.endsWith(".png") || filePath.endsWith(".JPG") || filePath.endsWith(".PNG")){ mAdapter.add(new MessageBean("",selectedImage, null)); } else if(filePath.endsWith(".3gp") || filePath.endsWith(".3GP") || filePath.endsWith(".mp4") || filePath.endsWith(".MP4") || filePath.endsWith(".avi") || filePath.endsWith(".AVI")){ mAdapter.add(new MessageBean("", null, selectedImage)); } // Uploading Invoked uniqueMA.uploadFile(uniqueMA.userName, filePath); } else{ } } } // Method to convert Uri to File Path private String getRealPathFromURI(Uri contentURI) { String result; Cursor cursor = getContentResolver().query(contentURI, null, null, null, null); if (cursor == null) { // Source is Dropbox or other similar local file path result = contentURI.getPath(); } else { cursor.moveToFirst(); int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA); result = cursor.getString(idx); cursor.close(); } return result; } }
true
f9a987ebd70cd2f3984d8ae2306a18d2056b7df9
Java
wolf3d2/MWbrowser
/src/com/jbak/superbrowser/ui/LoadBitmapCache.java
UTF-8
891
2.265625
2
[]
no_license
package com.jbak.superbrowser.ui; import java.util.ArrayList; import ru.mail.mailnews.st; import ru.mail.mailnews.st.UniObserver; @SuppressWarnings("serial") public class LoadBitmapCache extends ArrayList<LoadBitmapInfo> { public final void addCache(LoadBitmapInfo li) { add(li); if(size()>50) remove(0); } public final LoadBitmapInfo getCache(Object param) { for(LoadBitmapInfo li:this) { if(li==null) continue; if(li.param==param||li.param.equals(param)) return li; } return null; } public final void clearAndRecycleSync() throws Throwable { Thread.sleep(3000); for(LoadBitmapInfo li:this) { if(li!=null) { li.recycleBitmaps(); } } clear(); } public void clearAndRecycle() { new st.SyncAsycOper() { @Override public void makeOper(UniObserver obs) throws Throwable { clearAndRecycleSync(); } }; } }
true
3b30cebd32c2347e577add0cccfad342047f71ea
Java
ajmera25/2019MO
/src/test/java/utils/APIUtils.java
UTF-8
1,587
2.6875
3
[]
no_license
package utils; import java.io.File; import org.json.JSONObject; import okhttp3.HttpUrl; import okhttp3.MediaType; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; public class APIUtils { public static String fetchVideoName(){ String videoName = null; try { int rand = ((int) (Math.random()*(11 - 1))) + 1; OkHttpClient client = new OkHttpClient(); HttpUrl url = new HttpUrl.Builder() .scheme("https") .host("fd308454.ngrok.io") .addPathSegments("video/" + rand) .build(); Request request = new Request.Builder() .url(url) .build(); Response response = client.newCall(request).execute(); JSONObject object = new JSONObject(response.body().string()); videoName = (String) object.get("name"); }catch(Exception e){ e.printStackTrace(); } return videoName; } public static void postJsonfile(String url){ try{ OkHttpClient client = new OkHttpClient(); // Create upload file content mime type. MediaType fileContentType = MediaType.parse("File/*"); String uploadFileRealPath = "test.json"; // Create file object. File file = new File(uploadFileRealPath); // Create request body. RequestBody requestBody = RequestBody.create(fileContentType, file); Request request = new Request.Builder().url("https/c39ae9a5.ngrok.io/upload") .post(requestBody).build(); Response response = client.newCall(request).execute(); }catch(Exception e){ e.printStackTrace(); } } }
true
1471ae59cd04ce8e2a4828dc62b036cf3f4b7ca4
Java
marcoFuschini/ISLT2013gruppo14
/FanDeviceSystemTESTS/src/it/unibo/IngSW/Tests/Viewer/ViewerTest.java
UTF-8
2,599
2.53125
3
[ "MIT" ]
permissive
package it.unibo.IngSW.Tests.Viewer; import static org.junit.Assert.*; import it.unibo.IngSW.Viewer.Viewer; import it.unibo.IngSW.common.Display; import it.unibo.IngSW.common.SensorData; import it.unibo.IngSW.common.interfaces.IDisplay; import it.unibo.IngSW.common.interfaces.IElementDisplay; import it.unibo.IngSW.common.interfaces.ISensorData; import it.unibo.IngSW.utils.JSONConverter; import it.unibo.IngSWBasicComponents.Communicator; import org.junit.BeforeClass; import org.junit.Test; public class ViewerTest { private final int SERVERPORT=10001; private String el1value = ""; private String el2value = ""; private Communicator server=new Communicator(); private IElementDisplay el1 = new IElementDisplay() { String s=""; @Override public void setValue(String value) { s=value; } @Override public void refresh() { el1value=s; } @Override public String getName() { return "el1"; } }; private IElementDisplay el2 = new IElementDisplay() { String s=""; @Override public void setValue(String value) { s=value; } @Override public void refresh() { el2value=s; } @Override public String getName() { return "el2"; } }; private IDisplay display = new Display(new IElementDisplay[] { el1, el2 }); private Thread t = new Thread(new Runnable() { @Override public void run() { String s; try { server.connect("server", SERVERPORT); Thread.sleep(2000); server.write(0, JSONConverter.SensorDataToJSON(new SensorData[]{new SensorData("el1", "val3"),new SensorData("el2","val3")})); server.disconnect(0); } catch (Exception e) { e.printStackTrace(); } } }); @Test public void testViewer() { Viewer v = new Viewer(display); v.updateData(new SensorData[]{new SensorData("el1", "val1"),new SensorData("el2","val1")}); assertTrue("val1".equals(el1value)); assertTrue("val1".equals(el2value)); v.updateData(new SensorData[]{new SensorData("el1", "val2")}); assertTrue("val2".equals(el1value)); assertTrue("val1".equals(el2value)); t.start(); ISensorData[] data; try { v.connect("127.0.0.1",SERVERPORT); data=v.receiveData(); v.updateData(data); assertTrue("val3".equals(el1value)); assertTrue("val3".equals(el2value)); } catch (Exception e) { fail("errore di comunicazione"); e.printStackTrace(); } try { data=v.receiveData(); fail("receiveData errato"); } catch (Exception e) { //e.printStackTrace(); } } }
true
4c89949cd597aa16ce004597ee446b74ca836f8c
Java
yq1012/finereport
/designer_base/src/com/fr/design/mainframe/backgroundpane/BackgroundSettingPane.java
UTF-8
811
2.484375
2
[]
no_license
package com.fr.design.mainframe.backgroundpane; import com.fr.design.beans.BasicBeanPane; import com.fr.design.event.UIObserver; import com.fr.general.Background; /** * @author zhou * @since 2012-5-29下午1:12:28 */ public abstract class BackgroundSettingPane extends BasicBeanPane<Background> implements UIObserver { public abstract boolean accept(Background background); @Override public abstract void populateBean(Background background); @Override public abstract Background updateBean(); @Override public abstract String title4PopupWindow(); /** * 组件是否需要响应添加的观察者事件 * * @return 如果需要响应观察者事件则返回true,否则返回false */ public boolean shouldResponseChangeListener() { return true; } }
true
6cbb57de3551993ae5fb89631cb32ef3c3536948
Java
Dewey-Ding/LeetCode
/src/main/java/medium/MaximumProductSubarray_152.java
UTF-8
2,660
3.609375
4
[]
no_license
package medium; public class MaximumProductSubarray_152 { public static void main(String[] args) { int[] nums = new int[]{2,-5,-2,-4,3}; System.out.println(maxProduct(nums)); } public static int maxProduct(int[] nums) { if(nums.length==0){ return 0; } int maxPositive=Integer.MIN_VALUE,maxNegative=Integer.MAX_VALUE,max = Integer.MIN_VALUE; for (int i = 0; i < nums.length; i++) { if(max == Integer.MIN_VALUE){ max = nums[i]; }else { max = max * nums[i]; } if( max > 0){ maxPositive = Math.max(maxPositive,max); }else if(max < 0 ){ if(maxNegative<0){ max = maxNegative * max; maxPositive = Math.max(max,maxPositive); maxNegative = Integer.MAX_VALUE; }else { maxNegative = Math.min(maxNegative,max); max = Integer.MIN_VALUE; } }else{ maxPositive = Math.max(max,maxPositive); maxNegative = Integer.MAX_VALUE; max = Integer.MIN_VALUE; } } max = Math.max(max,maxPositive); if(maxNegative!=Integer.MAX_VALUE) { max = Math.max(max, maxNegative); } return Math.max(max,maxRight(nums)); } public static int maxRight(int[] nums){ if(nums.length==0){ return 0; } int maxPositive=Integer.MIN_VALUE,maxNegative=Integer.MAX_VALUE,max = Integer.MIN_VALUE; for (int i = nums.length-1; i >= 0; i--) { if(max == Integer.MIN_VALUE){ max = nums[i]; }else { max = max * nums[i]; } if( max > 0){ maxPositive = Math.max(maxPositive,max); }else if(max < 0 ){ if(maxNegative<0){ max = maxNegative * max; maxPositive = Math.max(max,maxPositive); maxNegative = Integer.MAX_VALUE; }else { maxNegative = Math.min(maxNegative,max); max = Integer.MIN_VALUE; } }else{ maxPositive = Math.max(max,maxPositive); maxNegative = Integer.MAX_VALUE; max = Integer.MIN_VALUE; } } max = Math.max(max,maxPositive); if(maxNegative!=Integer.MAX_VALUE) { return Math.max(max, maxNegative); } return max; } }
true
a02f794bc8bfb9d572c6211fffa6882ca8897093
Java
KJHIU0437/LexicalParser
/src/Utils/KeyWordChecker.java
UTF-8
829
3.03125
3
[ "MIT" ]
permissive
/** * This class is used to track keywords. * @author Miao Cai * @since 15/12/2019 9:32 PM */ package Utils; import javax.json.Json; import javax.json.JsonArray; import javax.json.JsonReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; public class KeyWordChecker { // Variables declaration private JsonArray keyWordArray; /* Initialization */ public KeyWordChecker (){ InputStream fis = KeyWordChecker.class.getResourceAsStream("/Database/keywords.json"); JsonReader reader = Json.createReader(fis); keyWordArray = reader.readArray(); } /** * This method is used to get the keyword list. * @return return a JsonArray as keyword list. */ public JsonArray getKeyWordArray(){ return keyWordArray; } }
true
a82c3a15df450179db3eb3427192cfb4335704e5
Java
ennioVisco/MoonLight
/core/src/main/java/eu/quanticol/moonlight/signal/TimeSequence.java
UTF-8
2,527
3.203125
3
[ "Apache-2.0" ]
permissive
/** * */ package eu.quanticol.moonlight.signal; import java.util.Iterator; import java.util.LinkedList; /** * @author loreti * */ public class TimeSequence { protected final LinkedList<Double> steps; public TimeSequence() { this( new LinkedList<>() ); } private TimeSequence(LinkedList<Double> steps) { this.steps = steps; } public void add( double t ) { if (!steps.isEmpty()&&(steps.peekLast()>= t)) { throw new IllegalArgumentException("A value greater than "+steps.peekLast()+" is expected! While "+t+" is used."); } this.steps.add(t); } public void addBefore( double t ) { if (!steps.isEmpty()&&(steps.peekFirst()<= t)) { throw new IllegalArgumentException("A value less than "+steps.peekLast()+" is expected! While "+t+" is used."); } this.steps.add(t); } public static TimeSequence merge(TimeSequence steps1, TimeSequence steps2) { return new TimeSequenceMerger(steps1 , steps2 ).merge(); } public boolean isEmpty() { return steps.isEmpty(); } private static class TimeSequenceMerger { private final Iterator<Double> iterator1; private final Iterator<Double> iterator2; private final TimeSequence result; private double time1 = Double.NaN; private double time2 = Double.NaN; public TimeSequenceMerger(TimeSequence sequence1, TimeSequence sequence2) { this.iterator1 = sequence1.steps.iterator(); this.iterator2 = sequence2.steps.iterator(); this.result = new TimeSequence(); stepIterator1(); stepIterator2(); } private void stepIterator1() { this.time1 = (iterator1.hasNext()?iterator1.next():Double.NaN); } private void stepIterator2() { this.time2 = (iterator2.hasNext()?iterator2.next():Double.NaN); } public TimeSequence merge() { while( !Double.isNaN(time1)&&!Double.isNaN(time2)) { int code = mergeStep(); if ((code == 0)||(code == 1)) { stepIterator1(); } if ((code == 0)||(code == 2)) { stepIterator2(); } } if (!Double.isNaN(time1)) { addAll( time1, iterator1 ); } if (!Double.isNaN(time2)) { addAll( time2, iterator2 ); } return result; } private void addAll(double time, Iterator<Double> iterator) { result.add(time); while (iterator.hasNext()) { result.add(iterator.next()); } } private int mergeStep() { if (time1==time2) { result.add(time1); return 0; } if (time1<time2) { result.add(time1); return 1; } else { result.add(time2); return 2; } } } }
true
3e09c8d0e4843d5c97e3ea5c19bdf2124731353c
Java
bxczp/exam
/src/Web/StudentAction.java
UTF-8
5,330
2.15625
2
[]
no_license
package Web; import java.util.ArrayList; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.apache.struts2.ServletActionContext; import org.apache.struts2.interceptor.ServletRequestAware; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionSupport; import Dao.StudentDao; import Model.PageBean; import Model.Student; import Util.DateUtil; import Util.PageUtil; import Util.PropertyUtil; import Util.ResponseUtil; import Util.StringUtil; import net.sf.json.JSONObject; /** * @date 2016年3月14日 StudentAction.java * @author CZP * @parameter */ public class StudentAction extends ActionSupport implements ServletRequestAware { /** * */ private static final long serialVersionUID = 1L; private HttpServletRequest req; private StudentDao studentDao = new StudentDao(); private Student student = new Student(); private String error; private String mainPage; private String studentId; private List<Student> studentList = new ArrayList<>(); private Student s_student = new Student(); private String page; private String pageCode; private String title; public String preUpdate() { mainPage = "/student/updatePassword.jsp"; return SUCCESS; } public String modifyPassword() { try { Student s = studentDao.getStduentById(student.getId()); s.setPassword(student.getPassword()); studentDao.saveStudent(s); } catch (Exception e) { e.printStackTrace(); } mainPage = "/student/updateSuccess.jsp"; return SUCCESS; } public String logout() { HttpSession session = req.getSession(); session.removeAttribute("currentStudent"); session.invalidate(); return "logout"; } public String list() { if (StringUtil.isEmpty(page)) { page = "1"; } int total = 0; PageBean pageBean = new PageBean(Integer.parseInt(page), Integer.parseInt(PropertyUtil.getValue("pageSize"))); if (s_student != null) { studentList = studentDao.getStudentList(s_student, pageBean); total = studentDao.getStudentCount(s_student); } else { studentList = studentDao.getStudentList(new Student(), pageBean); total = studentDao.getStudentCount(new Student()); } mainPage = "student/studentList.jsp"; String id = s_student.getId(); String name = s_student.getName(); pageCode = PageUtil.genPagination( req.getContextPath() + "/student!list?s_student.id=" + id + "&s_student.name=" + name, total, Integer.parseInt(page), Integer.parseInt(PropertyUtil.getValue("pageSize"))); return "success"; } public Student getStudent() { return student; } public String preSave() { if (StringUtil.isEmpty(student.getId())) { title = "添加学生信息"; } else { try { student = studentDao.getStduentById(student.getId()); } catch (Exception e) { e.printStackTrace(); } title = "更新学生信息"; } mainPage = "student/studentSave.jsp"; return SUCCESS; } public String delete() { JSONObject jsonObject = new JSONObject(); try { student = studentDao.getStduentById(student.getId()); studentDao.studentDelete(student); jsonObject.put("success", true); } catch (Exception e) { e.printStackTrace(); } try { ResponseUtil.write(ServletActionContext.getResponse(), jsonObject); } catch (Exception e) { e.printStackTrace(); } return null; } public String saveStudent() { try { // 学生的id要自己生成 if (StringUtil.isNotEmpty(student.getId())) { // 更新操作 studentDao.saveStudent(student); } else { // 添加操作 student.setId("JS" + DateUtil.getCurrentdateString()); studentDao.saveStudent(student); } } catch (Exception e) { e.printStackTrace(); } return "saveStudent"; } public void setStudent(Student student) { this.student = student; } public String getError() { return error; } public void setError(String error) { this.error = error; } public String login() { HttpSession session = req.getSession(); try { Student currentStudent = studentDao.login(student); if (currentStudent != null) { session.setAttribute("currentStudent", currentStudent); } else { error = "用户不存在"; return ERROR; } } catch (Exception e) { e.printStackTrace(); } return SUCCESS; } @Override public void setServletRequest(HttpServletRequest request) { this.req = request; } public String getMainPage() { return mainPage; } public void setMainPage(String mainPage) { this.mainPage = mainPage; } public String getStudentId() { return studentId; } public void setStudentId(String studentId) { this.studentId = studentId; } public List<Student> getStudentList() { return studentList; } public void setStudentList(List<Student> studentList) { this.studentList = studentList; } public Student getS_student() { return s_student; } public void setS_student(Student s_student) { this.s_student = s_student; } public String getPage() { return page; } public void setPage(String page) { this.page = page; } public String getPageCode() { return pageCode; } public void setPageCode(String pageCode) { this.pageCode = pageCode; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } }
true
b6402495c10231c5fdc951b384e67287461fed56
Java
Angel-Garcia033/Proyecto_ceros
/Proyecto_ceros/src/main/java/com/proyecto/ceros/service/VentaService.java
UTF-8
292
1.9375
2
[]
no_license
package com.proyecto.ceros.service; import java.util.Optional; import com.proyecto.ceros.model.Venta; public interface VentaService { public Iterable<Venta> findAll (); public Optional<Venta> findById (Long codigo); public Venta save (Venta venta); public void delete (Long codigo); }
true
267fcf94e97e3478c0946f2f1bb08ddaa9858eb6
Java
LucasPerrault/Architecture_Programmation_Distribue_TP2
/RMI_Matrix_Project/src/MatrixServer.java
UTF-8
534
2.625
3
[]
no_license
import interfaces.MatrixCalculator; import java.rmi.Naming; public class MatrixServer { public static void main(String args[]) { try { MatrixCalculator c = new MatrixService(); java.rmi.registry.LocateRegistry.createRegistry(10000); Naming.rebind("rmi://localhost:10000/CalculatorService", c); System.out.println("Matrix Calculator Server is ready ! \n"); } catch (Exception e) { System.out.println("Oops we found a trouble : \n" + e); } } }
true
92aa450e899395e2140f62ebbf8ff388ee400ac2
Java
KevinChevez/MVProjectED-Parcial1
/src/main/java/modelo/Paciente.java
UTF-8
2,232
2.671875
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package modelo; /** * * @author Kevin Chevez pc */ public class Paciente extends Usuario{ private int edad; private String genero; private String sintoma; private int prioridad; private String turno; private Puesto puesto; public Paciente(int edad, String genero, String sintoma, int prioridad, String turno, Puesto puesto, String nombre, String apellido) { super(nombre, apellido); this.edad = edad; this.genero = genero; this.sintoma = sintoma; this.prioridad = prioridad; this.turno = turno; this.puesto = puesto; } public Paciente(Puesto puesto, String nombre, String apellido) { super(nombre, apellido); this.puesto = puesto; this.edad = 18; this.genero = "Masculino"; this.sintoma = "fiebre"; this.prioridad = 3; this.turno = "A2"; } public int getEdad() { return edad; } public void setEdad(int edad) { this.edad = edad; } public String getGenero() { return genero; } public void setGenero(String genero) { this.genero = genero; } public String getSintoma() { return sintoma; } public void setSintoma(String sintoma) { this.sintoma = sintoma; } public int getPrioridad() { return prioridad; } public void setPrioridad(int prioridad) { this.prioridad = prioridad; } public String getTurno() { return turno; } public void setTurno(String turno) { this.turno = turno; } public Puesto getPuesto() { return puesto; } public void setPuesto(Puesto puesto) { this.puesto = puesto; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public String getApellido() { return apellido; } public void setApellido(String apellido) { this.apellido = apellido; } }
true
18c641b093c1471eb651cdc02f459fb2f5725790
Java
joaobispo/ancora-toolbox
/src/shared-library/org/ancora/SharedLibrary/AppBase/SimpleGui/AppFilePanel.java
UTF-8
4,502
2.0625
2
[]
no_license
/* * Copyright 2010 SPeCS Research Group. * * 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. * under the License. */ package org.ancora.SharedLibrary.AppBase.SimpleGui; import java.awt.LayoutManager; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.swing.BoxLayout; import javax.swing.JPanel; import org.ancora.SharedLibrary.AppBase.AppOption.AppOptionEnum; import org.ancora.SharedLibrary.AppBase.AppOptionFile.AppOptionFile; import org.ancora.SharedLibrary.AppBase.AppOptionFile.Entry; import org.ancora.SharedLibrary.AppBase.AppOptionFile.OptionFileUtils; import org.ancora.SharedLibrary.AppBase.AppUtils; import org.ancora.SharedLibrary.AppBase.AppValue; import org.ancora.SharedLibrary.AppBase.SimpleGui.Panels.AppOptionPanel; import org.ancora.SharedLibrary.LoggingUtils; import org.ancora.SharedLibrary.ProcessUtils; /** * Panel which will contain the options * * @author Joao Bispo */ public class AppFilePanel extends JPanel { public AppFilePanel(Class appOptionEnum) { panels = new HashMap<String, AppOptionPanel>(); // Extract the enum values AppOptionEnum[] values = AppUtils.getEnumValues(appOptionEnum); LayoutManager layout = new BoxLayout(this, BoxLayout.Y_AXIS); setLayout(layout); //JPanel options = new JPanel(); // Add panels, in alphabetical order //List<String> keyList = new ArrayList<String>(appOptionEnum.keySet()); //Collections.sort(keyList); //for(String key : keyList) { for(int i=0; i<values.length; i++) { //AppOptionPanel panel = PanelUtils.newPanel(appOptionEnum.get(key)); AppOptionPanel panel = PanelUtils.newPanel(values[i]); if(panel == null) { continue; } add(panel); panels.put(AppUtils.buildEnumName(values[i]), panel); } //add(Box.createVerticalGlue()); // Make the panel scrollable /* JScrollPane scrollPane = new JScrollPane(); scrollPane.setPreferredSize(new Dimension(AppFrame.PREFERRED_WIDTH + 10, AppFrame.PREFERRED_HEIGHT + 10)); scrollPane.setViewportView(options); */ } public Map<String, AppOptionPanel> getPanels() { return panels; } public void loadValues(AppOptionFile optionFile) { Map<String, AppValue> map = optionFile.getMap(); Map<String, Entry> entries = optionFile.getEntryList().getEntriesMapping(); for (String key : optionFile.getMap().keySet()) { AppValue value = map.get(key); // Get panel //JPanel panel = panels.get(key); AppOptionPanel panel = panels.get(key); PanelUtils.updatePanel(panel, value); // Get comments updateTooltipText(panel, entries.get(key).getComments()); } } private void updateTooltipText(final JPanel panel, List<String> comments) { final String commentString = OptionFileUtils.parseComments(comments); ProcessUtils.runOnSwing(new Runnable() { @Override public void run() { panel.setToolTipText(commentString); } }); } /** * Collects information in all the panels and returns a map with the information. * * @return */ public Map<String, AppValue> getMapWithValues() { Map<String, AppValue> updatedMap = new HashMap<String, AppValue>(); for(String key : panels.keySet()) { JPanel panel = panels.get(key); AppValue value = PanelUtils.getAppValue((AppOptionPanel)panel); if(value == null) { LoggingUtils.getLogger(). warning("value is null."); // No valid value for the table continue; } updatedMap.put(key, value); } return updatedMap; } private Map<String, AppOptionPanel> panels; }
true
ad9315fd6efb239a53bdef680eb98652beafd336
Java
shiyou/upsweb_version1
/src/com/eshore/upsweb/dao/CwSysUserDAO.java
UTF-8
179
1.742188
2
[]
no_license
package com.eshore.upsweb.dao; import java.util.List; import com.eshore.upsweb.model.CwSysUser; public interface CwSysUserDAO { List<CwSysUser> findUsers(CwSysUser user); }
true
a806d718f2e7f7b936297dde736a4d1a3c58ed19
Java
ALRubinger/capedwarf-blue
/datastore/src/main/java/org/jboss/capedwarf/datastore/AbstractDatastoreService.java
UTF-8
5,451
1.65625
2
[]
no_license
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.capedwarf.datastore; import java.util.Collection; import java.util.NoSuchElementException; import java.util.concurrent.TimeUnit; import java.util.logging.Logger; import com.google.appengine.api.datastore.BaseDatastoreService; import com.google.appengine.api.datastore.DatastoreServiceConfig; import com.google.appengine.api.datastore.Entity; import com.google.appengine.api.datastore.Key; import com.google.appengine.api.datastore.PreparedQuery; import com.google.appengine.api.datastore.Query; import com.google.appengine.api.datastore.Transaction; import com.google.apphosting.api.ApiProxy; import org.hibernate.search.query.engine.spi.TimeoutExceptionFactory; import org.infinispan.Cache; import org.infinispan.query.CacheQuery; import org.infinispan.query.Search; import org.infinispan.query.SearchManager; import org.jboss.capedwarf.common.app.Application; import org.jboss.capedwarf.common.infinispan.CacheName; import org.jboss.capedwarf.common.infinispan.InfinispanUtils; import org.jboss.capedwarf.datastore.query.PreparedQueryImpl; import org.jboss.capedwarf.datastore.query.QueryConverter; /** * Base Datastore service. * * @author <a href="mailto:ales.justin@jboss.org">Ales Justin</a> * @author <a href="mailto:marko.luksa@gmail.com">Marko Luksa</a> */ public class AbstractDatastoreService implements BaseDatastoreService { protected final Logger log = Logger.getLogger(getClass().getName()); protected final Cache<Key, Entity> store; protected final SearchManager searchManager; private final QueryConverter queryConverter; private DatastoreServiceConfig config; public AbstractDatastoreService() { this(null); } public AbstractDatastoreService(DatastoreServiceConfig config) { this.config = config; ClassLoader classLoader = Application.getAppClassloader(); this.store = createStore().getAdvancedCache().with(classLoader); this.searchManager = Search.getSearchManager(store); this.searchManager.setTimeoutExceptionFactory(new TimeoutExceptionFactory() { public RuntimeException createTimeoutException(String message, org.apache.lucene.search.Query query) { return new ApiProxy.ApiDeadlineExceededException("datastore", "RunQuery"); } }); this.queryConverter = new QueryConverter(searchManager); } protected Cache<Key, Entity> createStore() { return InfinispanUtils.getCache(CacheName.DEFAULT); } public PreparedQuery prepare(Query query) { return prepare(null, query); } public PreparedQuery prepare(Transaction tx, Query query) { if (tx != null && query.getAncestor() == null) { throw new IllegalArgumentException("Only ancestor queries are allowed inside transactions."); } javax.transaction.Transaction transaction = beforeTx(tx); try { CacheQuery cacheQuery = queryConverter.convert(query); Double deadlineSeconds = getConfig().getDeadline(); if (deadlineSeconds != null) { long deadlineMicroseconds = (long) (deadlineSeconds * 1000000); cacheQuery.timeout(deadlineMicroseconds, TimeUnit.MICROSECONDS); } return new PreparedQueryImpl(query, cacheQuery, tx != null); } finally { afterTx(transaction); } } public Transaction getCurrentTransaction() { Transaction tx = JBossTransaction.currentTransaction(); if (tx == null) throw new NoSuchElementException("No current transaction."); return tx; } public Transaction getCurrentTransaction(Transaction transaction) { Transaction tx = JBossTransaction.currentTransaction(); return (tx != null) ? tx : transaction; } public Collection<Transaction> getActiveTransactions() { return JBossTransaction.getTransactions(); } static javax.transaction.Transaction beforeTx(Transaction tx) { // if tx is null, explicitly suspend current tx return (tx == null) ? JBossTransaction.suspendTx() : null; } static void afterTx(javax.transaction.Transaction transaction) { if (transaction != null) { JBossTransaction.resumeTx(transaction); } } public DatastoreServiceConfig getConfig() { return config == null ? DatastoreServiceConfig.Builder.withDefaults() : config; } }
true
52d2b78bad44c8db453e20d11c89a3dda9c1198d
Java
iantal/AndroidPermissions
/apks/malware/app79/source/com/hzpz/pay/jsoup/nodes/FormElement.java
UTF-8
550
2.1875
2
[ "Apache-2.0" ]
permissive
package com.hzpz.pay.jsoup.nodes; import com.hzpz.pay.jsoup.parser.Tag; import com.hzpz.pay.jsoup.select.Elements; public class FormElement extends Element { private final Elements f = new Elements(); public FormElement(Tag paramTag, String paramString, Attributes paramAttributes) { super(paramTag, paramString, paramAttributes); } public FormElement b(Element paramElement) { this.f.add(paramElement); return this; } public boolean equals(Object paramObject) { return super.equals(paramObject); } }
true
c3a3c311040bd860f2586b7e523ce5f79a4aa85e
Java
cloudiator/orchestration
/node-agent/src/main/java/org/cloudiator/iaas/node/ByonNodeDeletionStrategy.java
UTF-8
4,273
2
2
[]
no_license
package org.cloudiator.iaas.node; import static jersey.repackaged.com.google.common.base.Preconditions.checkState; import com.google.inject.Inject; import io.github.cloudiator.domain.ByonNode; import io.github.cloudiator.domain.Node; import io.github.cloudiator.domain.NodeBuilder; import io.github.cloudiator.domain.NodeProperties; import io.github.cloudiator.domain.NodePropertiesBuilder; import io.github.cloudiator.domain.NodeState; import io.github.cloudiator.domain.NodeType; import io.github.cloudiator.messaging.ByonToByonMessageConverter; import io.github.cloudiator.messaging.NodePropertiesMessageToNodePropertiesConverter; import java.util.concurrent.ExecutionException; import org.cloudiator.messages.Byon.ByonNodeDeleteRequestMessage; import org.cloudiator.messages.Byon.ByonNodeDeletedResponse; import org.cloudiator.messaging.SettableFutureResponseCallback; import org.cloudiator.messaging.services.ByonService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ByonNodeDeletionStrategy implements NodeDeletionStrategy { private static final Logger LOGGER = LoggerFactory .getLogger(ByonNodeDeletionStrategy.class); private final ByonService byonService; private static final NodePropertiesMessageToNodePropertiesConverter NODE_PROPERTIES_CONVERTER = new NodePropertiesMessageToNodePropertiesConverter(); @Inject public ByonNodeDeletionStrategy( ByonService byonService) { this.byonService = byonService; } @Override public boolean supportsNode(Node node) { return node.type().equals(NodeType.BYON); } @Override public boolean deleteNode(Node node) { Node deletedNode = setDeleted(node); ByonNodeDeleteRequestMessage byonNodeDeleteRequestMessage = ByonNodeDeleteRequestMessage .newBuilder().setUserId(deletedNode.userId()) .setByonId(node.originId().get()) .build(); final SettableFutureResponseCallback<ByonNodeDeletedResponse, ByonNodeDeletedResponse> byonFuture = SettableFutureResponseCallback.create(); checkState(deletedNode.id() != null, "No id is present on byon. Can not delete"); byonService.createByonPersistDelAsync(byonNodeDeleteRequestMessage, byonFuture); try { ByonNodeDeletedResponse response = byonFuture.get(); final ByonNode deletedNodeResponded = ByonToByonMessageConverter.INSTANCE .applyBack(response.getNode()); if (!consistencyCheck(deletedNode, deletedNodeResponded)) { return false; } return true; } catch (InterruptedException e) { LOGGER.error(String.format("%s got interrupted while waiting for response.", this)); return false; } catch (ExecutionException e) { LOGGER.error(String .format("Deletion of byon %s failed, as byon delete request failed with %s.", node, e.getCause().getMessage()), e); return false; } } private static boolean consistencyCheck(Node deletedNode, ByonNode deletedNodeResponded) { if (deletedNode.equals(deletedNodeResponded)) { return true; } return false; } private Node setDeleted(Node node) { return NodeBuilder.newBuilder() .name(node.name()) .nodeType(node.type()) .originId(node.originId().orElse(null)) // set deleted .state(NodeState.DELETED) .userId(node.userId()) .diagnostic(node.diagnostic().orElse(null)) .id(node.id()) .ipAddresses(node.ipAddresses()) .nodeCandidate(node.nodeCandidate().orElse(null)) .loginCredential(node.loginCredential().orElse(null)) .reason(node.reason().orElse(null)) .nodeProperties(node.nodeProperties()) .build(); } private NodeProperties buildProperties(Node deletedNode) { return NodePropertiesBuilder.newBuilder() .providerId(deletedNode.nodeProperties().providerId()) .numberOfCores(deletedNode.nodeProperties().numberOfCores().orElse(null)) .memory(deletedNode.nodeProperties().memory().orElse(null)) .disk(deletedNode.nodeProperties().disk().orElse(null)) .os(deletedNode.nodeProperties().operatingSystem().orElse(null)) .geoLocation(deletedNode.nodeProperties().geoLocation().orElse(null)) .build(); } }
true
1eaa59d904cf1dba3c63cb1f6eebd16cb7e53708
Java
freeserverproject/uno
/src/main/java/io/github/tererun/plugin/uno/uno/cards/Card.java
UTF-8
1,682
2.875
3
[]
no_license
package io.github.tererun.plugin.uno.uno.cards; import org.bukkit.Material; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import java.util.Arrays; public class Card { private CardNumber cardNumber; private CardColor cardColor; public Card(CardNumber cardNumber, CardColor cardColor) { this.cardNumber = cardNumber; this.cardColor = cardColor; } public ItemStack getCardItemStack() { ItemStack itemStack = new ItemStack(Material.PAPER, 1); ItemMeta itemMeta = itemStack.getItemMeta(); itemMeta.setDisplayName(cardColor.getCardColor() + cardColor.getCardColorString() + " | " + cardNumber.getNumber()); itemMeta.setLore(Arrays.asList("UNO Cards")); itemStack.setItemMeta(itemMeta); return itemStack; } public static boolean isUNOCards(ItemStack itemStack) { if (itemStack.getItemMeta() == null) return false; if (itemStack.getItemMeta().getLore().get(0).equalsIgnoreCase("UNO Cards")) { return true; } else { return false; } } public static Card getCard(ItemStack itemStack) { String str = itemStack.getItemMeta().getDisplayName(); int index = str.indexOf(" | "); int index2 = str.indexOf(" | "); index += " | ".length(); Card card = new Card(CardNumber.valueOf(str.substring(index)), CardColor.valueOf(str.substring(index2))); return card; } public static CardColor getCardColor(Card card) { return card.cardColor; } public static CardNumber getCardNumber(Card card) { return card.cardNumber; } }
true
cdcd1651e97be5d0d6fc9a56970bbcffba13e0e2
Java
VaniMar/myFirstProgram
/Pizzeria.java
UTF-8
580
2.8125
3
[]
no_license
import java.util.*; /** * Write a description of class Pizzeria here. * * @author (your name) * @version (a version number or a date) */ public class Pizzeria { private List<Pizza> pizzas; /** * Usuario podra ver el menu de la pizzeria para hacer su pedido */ public void getMenu() {} /** * Para hacer pedido de que pizzas quiere comer el ususario */ public void hacerPedido(){ } /** * En caso que la pizeria tenga una promo disponible * como caso miercoles 2*1 */ public void getPromo() {} }
true
dd5070982ef8301cee9608534a5dc299a3edb056
Java
ArtAmb/Jackpot
/src/main/java/jackpot/entity/Invoice.java
UTF-8
365
2.15625
2
[]
no_license
package jackpot.entity; import lombok.Builder; import lombok.Data; import lombok.Value; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.ManyToMany; import java.util.List; @Entity @Value @Builder public class Invoice { @Id Integer id; String invoiceNumber; @ManyToMany List<Product> invoiceProducts; }
true
1f15f1e22f6cbf9f2e515e6bce4ef95a0f6d1d09
Java
PSN123/javacodes
/NetBeansProjects/copyonwritedemo4/src/copyonwritedemo4/Copyonwritedemo4.java
UTF-8
437
2.921875
3
[]
no_license
package copyonwritedemo4; import java.util.concurrent.CopyOnWriteArrayList; import java.util.*; public class Copyonwritedemo4 { public static void main(String[] args) { CopyOnWriteArrayList l=new CopyOnWriteArrayList(); l.add("A"); l.add("B"); l.add("C"); Iterator itr=l.iterator(); l.add("D"); while(itr.hasNext()){ String s=(String)itr.next(); System.out.println(s); } } }
true
607eee89c9a17ddc6f737b8707dd8c49d1037703
Java
amplia-iiot/oda
/oda-comms/mqtt/src/test/java/es/amplia/oda/comms/mqtt/api/MqttMessageTest.java
UTF-8
4,139
2.765625
3
[ "Apache-2.0" ]
permissive
package es.amplia.oda.comms.mqtt.api; import org.junit.Test; import static org.junit.Assert.*; public class MqttMessageTest { private final byte[] TEST_PAYLOAD = { 0x1, 0x2, 0x3, 0x4 }; private final int TEST_QOS = 2; private final boolean TEST_RETAINED = true; private final MqttMessage TEST_MESSAGE = MqttMessage.newInstance(TEST_PAYLOAD, TEST_QOS, TEST_RETAINED); @Test public void testNewInstanceWithDefaultParams() { MqttMessage message = MqttMessage.newInstance(TEST_PAYLOAD); assertArrayEquals(TEST_PAYLOAD, message.getPayload()); assertEquals(MqttMessage.DEFAULT_QOS, message.getQos()); assertEquals(MqttMessage.DEFAULT_RETAINED, message.isRetained()); } @Test public void testNewInstanceWithAllParams() { int testQos = 1; MqttMessage message = MqttMessage.newInstance(TEST_PAYLOAD, testQos, true); assertArrayEquals(TEST_PAYLOAD, message.getPayload()); assertEquals(testQos, message.getQos()); assertTrue(message.isRetained()); } @Test public void testMqttMessageIsEffectivelyImmutableChangingPayloadPassedInConstructor() { byte[] payloadToChange = TEST_PAYLOAD.clone(); MqttMessage message = MqttMessage.newInstance(payloadToChange); payloadToChange[2] = 0; assertArrayEquals(TEST_PAYLOAD, message.getPayload()); } @Test public void tetMqttMessageIsEffectivelyImmutableChangingPayloadReturnedInGet() { MqttMessage message = MqttMessage.newInstance(TEST_PAYLOAD); byte[] payloadToChange = message.getPayload(); payloadToChange[2] = 0; assertArrayEquals(TEST_PAYLOAD, message.getPayload()); } @Test public void testEqualsWithThis() { assertEquals(TEST_MESSAGE, TEST_MESSAGE); } @Test @SuppressWarnings({"ObjectEqualsNull", "ConstantConditions"}) public void testEqualsWithNullObject() { boolean equals = TEST_MESSAGE.equals(null); assertFalse(equals); } @Test public void testEqualsWithNullOtherClass() { boolean equals = TEST_MESSAGE.equals(new Object()); assertFalse(equals); } @Test public void testEqualsWithEqualObject() { MqttMessage message2 = MqttMessage.newInstance(TEST_PAYLOAD, TEST_QOS, TEST_RETAINED); boolean equals = TEST_MESSAGE.equals(message2); assertTrue(equals); } @Test public void testEqualsWithDifferentPayloadObject() { MqttMessage message2 = MqttMessage.newInstance(new byte[] {5,6,7,8}, TEST_QOS, TEST_RETAINED); boolean equals = TEST_MESSAGE.equals(message2); assertFalse(equals); } @Test public void testEqualsWithDifferentQosObject() { MqttMessage message2 = MqttMessage.newInstance(TEST_PAYLOAD, 1, TEST_RETAINED); boolean equals = TEST_MESSAGE.equals(message2); assertFalse(equals); } @Test public void testEqualsWithDifferentRetainedObject() { MqttMessage message2 = MqttMessage.newInstance(TEST_PAYLOAD, TEST_QOS, false); boolean equals = TEST_MESSAGE.equals(message2); assertFalse(equals); } @Test public void testHashCodeWithEqualObject() { MqttMessage message2 = MqttMessage.newInstance(TEST_PAYLOAD, TEST_QOS, TEST_RETAINED); assertEquals(TEST_MESSAGE.hashCode(), message2.hashCode()); } @Test public void testHashCodeWithDifferentPayloadObject() { MqttMessage message2 = MqttMessage.newInstance(new byte[] {5,6,7,8}, TEST_QOS, TEST_RETAINED); assertNotEquals(TEST_MESSAGE.hashCode(), message2.hashCode()); } @Test public void testHashCodeWithDifferentQosObject() { MqttMessage message2 = MqttMessage.newInstance(TEST_PAYLOAD, 1, TEST_RETAINED); assertNotEquals(TEST_MESSAGE.hashCode(), message2.hashCode()); } @Test public void testHashCodeWithDifferentRetainedObject() { MqttMessage message2 = MqttMessage.newInstance(TEST_PAYLOAD, TEST_QOS, false); assertNotEquals(TEST_MESSAGE.hashCode(), message2.hashCode()); } }
true
6e29b8e3f9eb0a3fbfca41691f9f58ba8a4f21cf
Java
mohitrajvardhan17/java1.8.0_151
/sun/text/CompactByteArray.java
UTF-8
5,690
2.5
2
[]
no_license
package sun.text; public final class CompactByteArray implements Cloneable { public static final int UNICODECOUNT = 65536; private static final int BLOCKSHIFT = 7; private static final int BLOCKCOUNT = 128; private static final int INDEXSHIFT = 9; private static final int INDEXCOUNT = 512; private static final int BLOCKMASK = 127; private byte[] values; private short[] indices; private boolean isCompact; private int[] hashes; public CompactByteArray(byte paramByte) { values = new byte[65536]; indices = new short['Ȁ']; hashes = new int['Ȁ']; for (int i = 0; i < 65536; i++) { values[i] = paramByte; } for (i = 0; i < 512; i++) { indices[i] = ((short)(i << 7)); hashes[i] = 0; } isCompact = false; } public CompactByteArray(short[] paramArrayOfShort, byte[] paramArrayOfByte) { if (paramArrayOfShort.length != 512) { throw new IllegalArgumentException("Index out of bounds!"); } for (int i = 0; i < 512; i++) { int j = paramArrayOfShort[i]; if ((j < 0) || (j >= paramArrayOfByte.length + 128)) { throw new IllegalArgumentException("Index out of bounds!"); } } indices = paramArrayOfShort; values = paramArrayOfByte; isCompact = true; } public byte elementAt(char paramChar) { return values[((indices[(paramChar >> '\007')] & 0xFFFF) + (paramChar & 0x7F))]; } public void setElementAt(char paramChar, byte paramByte) { if (isCompact) { expand(); } values[paramChar] = paramByte; touchBlock(paramChar >> '\007', paramByte); } public void setElementAt(char paramChar1, char paramChar2, byte paramByte) { if (isCompact) { expand(); } for (char c = paramChar1; c <= paramChar2; c++) { values[c] = paramByte; touchBlock(c >> '\007', paramByte); } } public void compact() { if (!isCompact) { int i = 0; int j = 0; int k = -1; int m = 0; while (m < indices.length) { indices[m] = -1; boolean bool = blockTouched(m); if ((!bool) && (k != -1)) { indices[m] = k; } else { int n = 0; int i1 = 0; i1 = 0; while (i1 < i) { if ((hashes[m] == hashes[i1]) && (arrayRegionMatches(values, j, values, n, 128))) { indices[m] = ((short)n); break; } i1++; n += 128; } if (indices[m] == -1) { System.arraycopy(values, j, values, n, 128); indices[m] = ((short)n); hashes[i1] = hashes[m]; i++; if (!bool) { k = (short)n; } } } m++; j += 128; } m = i * 128; byte[] arrayOfByte = new byte[m]; System.arraycopy(values, 0, arrayOfByte, 0, m); values = arrayOfByte; isCompact = true; hashes = null; } } static final boolean arrayRegionMatches(byte[] paramArrayOfByte1, int paramInt1, byte[] paramArrayOfByte2, int paramInt2, int paramInt3) { int i = paramInt1 + paramInt3; int j = paramInt2 - paramInt1; for (int k = paramInt1; k < i; k++) { if (paramArrayOfByte1[k] != paramArrayOfByte2[(k + j)]) { return false; } } return true; } private final void touchBlock(int paramInt1, int paramInt2) { hashes[paramInt1] = (hashes[paramInt1] + (paramInt2 << 1) | 0x1); } private final boolean blockTouched(int paramInt) { return hashes[paramInt] != 0; } public short[] getIndexArray() { return indices; } public byte[] getStringArray() { return values; } public Object clone() { try { CompactByteArray localCompactByteArray = (CompactByteArray)super.clone(); values = ((byte[])values.clone()); indices = ((short[])indices.clone()); if (hashes != null) { hashes = ((int[])hashes.clone()); } return localCompactByteArray; } catch (CloneNotSupportedException localCloneNotSupportedException) { throw new InternalError(localCloneNotSupportedException); } } public boolean equals(Object paramObject) { if (paramObject == null) { return false; } if (this == paramObject) { return true; } if (getClass() != paramObject.getClass()) { return false; } CompactByteArray localCompactByteArray = (CompactByteArray)paramObject; for (int i = 0; i < 65536; i++) { if (elementAt((char)i) != localCompactByteArray.elementAt((char)i)) { return false; } } return true; } public int hashCode() { int i = 0; int j = Math.min(3, values.length / 16); int k = 0; while (k < values.length) { i = i * 37 + values[k]; k += j; } return i; } private void expand() { if (isCompact) { hashes = new int['Ȁ']; byte[] arrayOfByte = new byte[65536]; for (int i = 0; i < 65536; i++) { int j = elementAt((char)i); arrayOfByte[i] = j; touchBlock(i >> 7, j); } for (i = 0; i < 512; i++) { indices[i] = ((short)(i << 7)); } values = null; values = arrayOfByte; isCompact = false; } } private byte[] getArray() { return values; } } /* Location: C:\Program Files (x86)\Java\jre1.8.0_151\lib\rt.jar!\sun\text\CompactByteArray.class * Java compiler version: 8 (52.0) * JD-Core Version: 0.7.1 */
true
fdfad6ea59d3feb2e80b1d9517d4569d3951fdb3
Java
huijiewei/agile-boot
/agile-engine/src/main/java/com/huijiewei/agile/core/consts/ApiPageable.java
UTF-8
1,189
1.976563
2
[ "MIT" ]
permissive
package com.huijiewei.agile.core.consts; import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.enums.ParameterIn; import io.swagger.v3.oas.annotations.media.Schema; import org.springframework.beans.factory.annotation.Value; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE}) @Retention(RetentionPolicy.RUNTIME) @Parameter(in = ParameterIn.QUERY, name = "page", schema = @Schema(type = "integer", defaultValue = "0")) @Parameter(in = ParameterIn.QUERY, name = "size", schema = @Schema(type = "integer", defaultValue = "20")) public @interface ApiPageable { @Value("${spring.data.web.pageable.size-parameter}") String pageableSizeParameter = "size"; @Value("${spring.data.web.pageable.page-parameter}") String pageablePageParameter = "page"; @Value("${spring.data.web.pageable.one-indexed-parameters}") Boolean pageableOneIndexedParameter = false; @Value("${spring.data.web.pageable.default-page-size}") Integer pageableDefaultPageSizeParameter = 20; }
true
35dcf376cee7543e09ef1bd582e1fb02d6d87334
Java
jcg0727/FinalProject
/HS_System/src/main/java/kr/ac/hs/dao/AcademicFreshmenDAO.java
UTF-8
1,587
2.171875
2
[]
no_license
package kr.ac.hs.dao; import java.sql.SQLException; import java.util.List; import java.util.Map; import kr.ac.hs.command.Criteria; import kr.ac.hs.command.SearchCriteria; import kr.ac.hs.dto.AcademicFreshmenVO; public interface AcademicFreshmenDAO { // 로그인 조교의 학과명 출력 String SelectDept_nmByStaff_no(String staff_no)throws SQLException; // 로그인 조교 학과의 신입생 목록 출력 List<AcademicFreshmenVO> SelectItemsByStaff_no(String staff_no)throws SQLException; List<AcademicFreshmenVO> SelectItemsByStaff_no(String staff_no, Criteria cri)throws SQLException; List<AcademicFreshmenVO> SelectItemsByStaff_no(String staff_no, SearchCriteria cri)throws SQLException; int selectSearchItemsByStaff_noCount(String staff_no, SearchCriteria cri)throws SQLException; // 신입생 상세보기 List<AcademicFreshmenVO> SelectDetailByStudent_no(String student_no)throws SQLException; // 학과별 교수리스트(parameter : 학과명) List<AcademicFreshmenVO> SelectProfessorListByDept_nm(String dept_nm)throws SQLException; List<AcademicFreshmenVO> SelectProfessorListByDept_nm(String dept_nm, Criteria cri)throws SQLException; List<AcademicFreshmenVO> SelectProfessorListByDept_nm(String dept_nm, SearchCriteria cri)throws SQLException; int selectCountProfessorListByDept_nm(String dept_nm, SearchCriteria cri)throws SQLException; // 지도교수 변경 void updateAdvisor(String pro_no, String student_no)throws SQLException; // 지도교수 등록 void insertAdvisor(String pro_no, String student_no)throws SQLException; }
true
aa65614b2b79a73c14c7c76f06ba6dd719c5bca6
Java
aaronamjid2608/mobileplatformdevelopmentCW
/app/src/main/java/org/me/gcu/equakestartercode/DetailFragment.java
UTF-8
2,023
2.53125
3
[]
no_license
package org.me.gcu.equakestartercode; //Aaron Amjid S1626987 import android.os.Bundle; import androidx.fragment.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; /* DetailFragment class Fragment class designed to display the details of a specified earthquake, uses a public setter method to get the quake data. */ public class DetailFragment extends Fragment { TextView title; TextView description; TextView link; TextView category; TextView coordinates; QuakeData quakedatatodisplay = new QuakeData(); public DetailFragment() { } public static DetailFragment newInstance() { DetailFragment fragment = new DetailFragment(); return fragment; } public void setQuakeDataToDisplay(QuakeData q){ quakedatatodisplay = q; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_detail, container, false); title = (TextView)view.findViewById(R.id.earthquaketitle); description = (TextView)view.findViewById(R.id.description); link = (TextView)view.findViewById(R.id.link); category = (TextView)view.findViewById(R.id.category); coordinates = (TextView)view.findViewById(R.id.coordinates); title.setText("Title: "+ quakedatatodisplay.getTitle()); //Set text for details fragment description.setText("Description: " + quakedatatodisplay.getDescription()); link.setText("Weblink: " + quakedatatodisplay.getLink()); category.setText("Category: " + quakedatatodisplay.getCategory()); coordinates.setText("Co-ordinates: "+ quakedatatodisplay.getGeoLat() + "," + quakedatatodisplay.getGeoLong() ); return view; } }
true
c45295826074aaf410a8dfc7459fa4bc44fc7ad8
Java
Dean4iq/homework
/src/main/java/ua/den/model/annotations/validators/NameValidator.java
UTF-8
877
2.625
3
[]
no_license
package ua.den.model.annotations.validators; import ua.den.model.annotations.ValidName; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; import java.util.regex.Matcher; import java.util.regex.Pattern; public class NameValidator implements ConstraintValidator<ValidName, String> { private Pattern pattern; private Matcher matcher; private static final String NAME_PATTERN = "^[A-Z]{1}[a-z]{1,44}$"; @Override public void initialize(ValidName constraintAnnotation) { } @Override public boolean isValid(String name, ConstraintValidatorContext constraintValidatorContext) { return validateName(name); } private boolean validateName(String name) { pattern = Pattern.compile(NAME_PATTERN); matcher = pattern.matcher(name); return matcher.matches(); } }
true
20dafdc397d86359fd7363dadf3de79717ab6092
Java
Fastrun/fling_sdk_android
/src/tv/matchstick/server/common/images/WebImageCreator.java
UTF-8
2,248
2.28125
2
[]
no_license
package tv.matchstick.server.common.images; import tv.matchstick.server.common.exception.FlingRuntimeException; import tv.matchstick.server.common.internal.safeparcel.ParcelReader; import tv.matchstick.server.common.internal.safeparcel.ParcelWritter; import android.net.Uri; import android.os.Parcel; public final class WebImageCreator implements android.os.Parcelable.Creator { public WebImageCreator() { } public static void a(WebImage webimage, Parcel parcel, int i) { int j = ParcelWritter.a(parcel, 20293); ParcelWritter.b(parcel, 1, webimage.getVersionCode()); ParcelWritter.a(parcel, 2, webimage.getUrl(), i, false); ParcelWritter.b(parcel, 3, webimage.getWidth()); ParcelWritter.b(parcel, 4, webimage.getHeight()); ParcelWritter.b(parcel, j); } public final Object createFromParcel(Parcel parcel) { int i = ParcelReader.a(parcel); int j = 0; Uri uri = null; int k = 0; int l = 0; do if (parcel.dataPosition() < i) { int i1 = parcel.readInt(); switch (0xffff & i1) { default: ParcelReader.b(parcel, i1); break; case 1: // '\001' k = ParcelReader.f(parcel, i1); break; case 2: // '\002' uri = (Uri) ParcelReader.a(parcel, i1, Uri.CREATOR); break; case 3: // '\003' j = ParcelReader.f(parcel, i1); break; case 4: // '\004' l = ParcelReader.f(parcel, i1); break; } } else if (parcel.dataPosition() != i) throw new FlingRuntimeException( (new StringBuilder("Overread allowed size end=")).append(i).toString(), parcel); else return new WebImage(k, uri, j, l); while (true); } public final Object[] newArray(int i) { return new WebImage[i]; } }
true
53fc6fe1564330a077ab3294e96463b9c98c3d09
Java
raymicxin/ssexxe
/ssexxe/src/bugfind/utils/pmdadapters/MethodArgument.java
UTF-8
1,527
2.734375
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package bugfind.utils.pmdadapters; import java.util.List; /** * * @author Mikosh */ public class MethodArgument { String argumentValue; String argumentType; public MethodArgument(String argumentValue, String argumentType) { this.argumentValue = argumentValue; this.argumentType = argumentType; } public String getArgumentValue() { return argumentValue; } public String getArgumentType() { return argumentType; } @Override public boolean equals(Object obj) { if (obj instanceof MethodArgument) { MethodArgument ma = (MethodArgument) obj; return (this.getArgumentValue().equals(ma.getArgumentValue()) && this.getArgumentType().equals(ma.getArgumentType())); } else { return super.equals(obj); //To change body of generated methods, choose Tools | Templates. } } public static boolean areArgumentsEqual(List<MethodArgument> lma1, List<MethodArgument> lma2) { if (lma1.size() != lma2.size()) return false; else { for (int i=0; i<lma1.size(); ++i) { if (!lma1.get(i).equals(lma2.get(i))) { return false; } } } return true; } }
true
971e8dad3e145df09b3047a9e8f71dbb39b74ffb
Java
aarantes23/save-saulo
/src/java/dao/PhoneDao.java
UTF-8
2,557
2.75
3
[]
no_license
/* * Developed by Arthur Arantes Faria * Graduating in Computer Science on UNIFOR-MG BRASIL * arthurarantes23@hotmail.com */ package dao; import java.util.List; import model.Phone; import org.hibernate.Session; import util.HibernateUtil; /** * * @author Arthur Arantes Faria <arthurarantes23@hotmail.com> */ public class PhoneDao { public PhoneDao() { } public List<Phone> list() { Session session = HibernateUtil.getSessionFactory().getCurrentSession(); session.beginTransaction(); try { List<Phone> list = session.createQuery("from Phone order by id").list(); session.getTransaction().commit(); return list; } catch (Exception e) { session.getTransaction().rollback(); return null; } } public Phone search(int idPhone) { Session session = HibernateUtil.getSessionFactory().getCurrentSession(); session.beginTransaction(); try { Phone phone = (Phone) session.createQuery("from Phone where id = " + idPhone).uniqueResult(); session.getTransaction().commit(); return phone; } catch (Exception e) { session.getTransaction().rollback(); return null; } } public boolean insert(Phone phone) { Session session = HibernateUtil.getSessionFactory().getCurrentSession(); session.beginTransaction(); try { session.save(phone); session.getTransaction().commit(); return true; } catch (Exception e) { e.printStackTrace(); session.getTransaction().rollback(); return false; } } public boolean change(Phone phone) { Session session = HibernateUtil.getSessionFactory().getCurrentSession(); session.beginTransaction(); try { session.update(phone); session.getTransaction().commit(); return true; } catch (Exception e) { session.getTransaction().rollback(); return false; } } public boolean delete(Phone phone) { Session session = HibernateUtil.getSessionFactory().getCurrentSession(); session.beginTransaction(); try { session.delete(phone); session.getTransaction().commit(); return true; } catch (Exception e) { session.getTransaction().rollback(); return false; } } }
true
eab2dbdb29a120f6227484ab59812ab6fe53ffdb
Java
dibyendughosh18/PageSlammer
/src/main/java/com/pageSlammer/application/serviceImpl/UserRegistrationServiceImpl.java
UTF-8
1,370
2.28125
2
[]
no_license
package com.pageSlammer.application.serviceImpl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.pageSlammer.application.model.UserMaster; import com.pageSlammer.application.repository.UserMasterRepository; import com.pageSlammer.application.service.UserRegistrationService; @Service("userRegistrationService") public class UserRegistrationServiceImpl implements UserRegistrationService{ @Autowired private UserMasterRepository userMasterRepository; @Override public UserMaster isUserExist(String emailId) { UserMaster um = userMasterRepository.findByEmailId(emailId); if(um != null) { return um; }else { return um; } } @Override public UserMaster registerUser(UserMaster um) { System.out.println("um = "+um); UserMaster res = userMasterRepository.save(um); if(res != null) { return res; }else { return res; } } @Override public Boolean facebookRegistration(UserMaster um) { UserMaster res = userMasterRepository.save(um); if(res != null) { return true; }else { return false; } } @Override public Boolean updateWithFacebook(String facebookId, String picUrl, String emailId) { int row = userMasterRepository.updateUserWithFacebook(facebookId, picUrl, emailId); if(row > 0) { return true; }else { return false; } } }
true
29a64c4710c830939e2eb27a067ff054754af5a6
Java
gyanendrachandrawat/practice-java-sts-workspace
/SB_HB_OTO/src/main/java/com/practice/controller/InstructorController.java
UTF-8
2,753
2.328125
2
[]
no_license
package com.practice.controller; import java.util.List; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.practice.beans.Instructor; import com.practice.service.InstructorService; @RestController @RequestMapping("/inst") public class InstructorController { @Autowired private InstructorService instructorService; // private InstructorRepository instructorRepository; @GetMapping("/instructors/all") public List<Instructor> getInstructors() { return instructorService.getInstructors(); // return instructorRepository.findAll(); } @GetMapping("/instructors/{id}") public ResponseEntity<Instructor> getInstructorById(@PathVariable(value = "id") Long instructorId) { return instructorService.getInstructorById(instructorId); // Instructor instructor=instructorRepository.findById(instructorId).orElse(null); // return ResponseEntity.ok().body(instructor); } @PostMapping("/instructors/create") public Instructor createInstructor(@RequestBody Instructor instructor) { return instructorService.createInstructor(instructor); // InstructorDetail instructorDetail1=new InstructorDetail(instructor.getInstructorDetail().getYoutubeChannel(),instructor.getInstructorDetail().getHobby()); // instructor.setInstructorDetail(instructorDetail1); // instructorRepository.save(instructor); // return instructor; } @PutMapping("/instructors/update/{id}") public ResponseEntity<Instructor> updateInstructor(@PathVariable(value = "id") Long instructorId, @Valid @RequestBody Instructor instructorDetails) { return instructorService.updateInstructor(instructorId, instructorDetails); // Instructor instructor=instructorRepository.findById(instructorId).orElse(null); // instructor.setEmail(instructorDetails.getEmail()); // Instructor newInstructor=instructorRepository.save(instructor); // return ResponseEntity.ok().body(newInstructor); } @DeleteMapping("/instructors/{id}") public String deleteInstructor(@PathVariable(value = "id") Long instructorId) { return instructorService.deleteInstructor(instructorId); // Instructor instructor=instructorRepository.getOne(instructorId); // instructorRepository.delete(instructor); } }
true