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
1c8833866bfe8a9c4eb50d2b488ff4818ca7342f
Java
AlexJPo/otus-java-2017-11-alexjpo
/Lecture-10/src/main/java/ru/otus/implementation/DBServiceImpl.java
UTF-8
1,071
2.34375
2
[]
no_license
package ru.otus.implementation; import ru.otus.dao.AddressHibernateDAO; import ru.otus.dao.UserDAO; import ru.otus.dataset.AddressDataSet; import ru.otus.dataset.PhoneDataSet; import ru.otus.dataset.UserDataSet; import ru.otus.interfaces.IDBService; import java.sql.Connection; public class DBServiceImpl implements IDBService { private final Connection connection; public DBServiceImpl(Connection connection) { this.connection = connection; } @Override public void save(UserDataSet dataSet) { UserDAO dao = new UserDAO(connection); dao.save(dataSet); } @Override public UserDataSet read(long id) { UserDAO dao = new UserDAO(connection); return dao.read(id); } @Override public void savePhone(PhoneDataSet dataSet) { } @Override public PhoneDataSet readPhone(long id) { return null; } @Override public void saveAddress(AddressDataSet dataSet) { } @Override public AddressDataSet readAddress(long id) { return null; } }
true
fed796a5ed95faf097809672ed71f6b054a597ac
Java
1665886758/Y2
/cesson/EdocManagement/src/main/java/com/fj/mapper/EntryMapper.java
UTF-8
739
2.140625
2
[]
no_license
package com.fj.mapper; import com.fj.pojo.Entry; import org.apache.ibatis.annotations.Param; import java.util.List; public interface EntryMapper { /** * 查询所有文件信息 * @return */ public List<Entry> entryFile(); /** * 根据文件类型categoryId查找信息 */ public List<Entry> list(@Param("categoryId") Integer categoryId); /** * 新增文件信息 */ public int addFiles(Entry entry); /** * 删除文件信息 */ public int delFiles(@Param("id") Integer id); /** * 根据id查找信息 */ public Entry fileInfoById(@Param("id") Integer id); /** * 修改信息 */ public int setFiles(Entry Entry); }
true
1faf05400392ef490a3195be022be45cee15c4be
Java
lihongweimail/MASU
/oldMASUFiles/cfg/src/jp/ac/osaka_u/ist/sel/metricstool/cfg/edge/CFGExceptionEdge.java
UTF-8
1,470
2.453125
2
[]
no_license
package jp.ac.osaka_u.ist.sel.metricstool.cfg.edge; import jp.ac.osaka_u.ist.sel.metricstool.cfg.node.CFGNode; import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.TypeInfo; public class CFGExceptionEdge extends CFGEdge { public CFGExceptionEdge(CFGNode<?> fromNode, final CFGNode<?> toNode, final TypeInfo thrownException) { super(fromNode, toNode); this.thrownException = thrownException; } public TypeInfo getThrownException() { return this.thrownException; } @Override public String getDependenceTypeString() { return "exception"; } @Override public String getDependenceString() { return this.getThrownException().getTypeName(); } @Override public CFGEdge replaceFromNode(final CFGNode<?> newFromNode) { final CFGNode<?> toNode = this.getToNode(); final TypeInfo thrownException = this.getThrownException(); return new CFGExceptionEdge(newFromNode, toNode, thrownException); } @Override public CFGEdge replaceToNode(final CFGNode<?> newToNode) { final CFGNode<?> fromNode = this.getFromNode(); final TypeInfo thrownException = this.getThrownException(); return new CFGExceptionEdge(fromNode, newToNode, thrownException); } @Override public CFGEdge replaceBothNodes(final CFGNode<?> newFromNode, final CFGNode<?> newToNode) { final TypeInfo thrownException = this.getThrownException(); return new CFGExceptionEdge(newFromNode, newToNode, thrownException); } private final TypeInfo thrownException; }
true
0f28a6c24d1ab320d4d807ed414073dcfe9053b2
Java
ashklyarovjr/SeleniumTask3
/src/test/java/tests/FilterByPriceTest.java
UTF-8
383
1.804688
2
[]
no_license
package tests; import org.testng.Assert; import org.testng.annotations.Test; public class FilterByPriceTest extends BaseTest { @Test public void testPriceFilter() throws Exception { mainPageSteps.goToWashersCategory() .selectMinPrice() .selectMaxPrice() .verifyPriceFilterWork() .goToMainPage(); } }
true
96fc2f666ee8b535e34cb400dc80240e5c7d047a
Java
magical2014/magical-music
/app/src/main/java/com/magical/music/MainActivity.java
UTF-8
1,646
2.25
2
[]
no_license
package com.magical.music; import android.content.ComponentName; import android.content.Intent; import android.content.ServiceConnection; import android.os.IBinder; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import com.magical.music.service.MediaPlaybackService; public class MainActivity extends AppCompatActivity { private static final String TAG= "MainActivity"; private IMediaPlaybackService mService = null; private final ServiceConnection mConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName componentName, IBinder iBinder) { mService = IMediaPlaybackService.Stub.asInterface(iBinder); Log.i(TAG, "onServiceConnected()"); } @Override public void onServiceDisconnected(ComponentName componentName) { mService = null; Log.i(TAG, "onServiceDisconnected()"); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Log.i(TAG, "onCreate()"); bindService(); } @Override protected void onDestroy() { super.onDestroy(); Log.i(TAG, "onDestroy()"); unbindService(); } private void bindService() { Intent intent = new Intent(); intent.setClass(this, MediaPlaybackService.class); startService(intent); bindService(intent, mConnection,0); } private void unbindService() { unbindService(mConnection); } }
true
fa1b794e0bf0eb8dc3b40b4148d43c1c4c33c297
Java
marcooos/PCSocialRMIServer
/src/br/com/pcsocial/servidor/daoImp/TemporadaDaoImp.java
UTF-8
2,610
2.578125
3
[]
no_license
package br.com.pcsocial.servidor.daoImp; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.Transaction; import br.com.pcsocial.servidor.dao.TemporadaDao; import br.com.pcsocial.servidor.modelo.Temporada; import br.com.pcsocial.servidor.util.HibernateUtil; public class TemporadaDaoImp implements TemporadaDao { public void save(Temporada temporada) { Session session = HibernateUtil.getSessionFactory().openSession(); Transaction t = session.beginTransaction(); session.save(temporada); t.commit(); } public Temporada getTemporada(long id) { Session session = HibernateUtil.getSessionFactory().openSession(); Temporada temporada = (Temporada) session.load(Temporada.class, id); temporada.toString(); session.flush(); session.close(); return temporada; } @SuppressWarnings({ "rawtypes", "unchecked","unused"}) public List<Temporada> list() { Session session = HibernateUtil.getSessionFactory().openSession(); Transaction t = session.beginTransaction(); List lista = session.createQuery("from Temporada").list(); try { return lista; } finally { session.close(); } } public void remove(Temporada temporada) { Session session = HibernateUtil.getSessionFactory().openSession(); Transaction t = session.beginTransaction(); session.delete(temporada); t.commit(); session.close(); } public void update(Temporada temporada) { Session session = HibernateUtil.getSessionFactory().openSession(); Transaction t = session.beginTransaction(); session.update(temporada); t.commit(); session.close(); } @SuppressWarnings("unchecked") @Override public List<Temporada> list(String text, long valor) { Session session = HibernateUtil.getSessionFactory().openSession(); if (text.equals("")&&(valor == 0)){ Query q = session.createQuery("from Temporada" ); try { return q.list(); } finally { session.close(); } } else if (text.equals("")){ Query q = session.createQuery("from Temporada where id = :valor" ); q.setLong("valor", valor); try { return q.list(); } finally { session.close(); } } if (valor == 0){ Query q = session.createQuery("from Temporada where descricao like :text"); q.setString("text", '%' + text.toLowerCase() + '%'); try { return q.list(); } finally { session.close(); } } return null; } }
true
36023a531d4066a43239ee59861e5e1ecdf3a540
Java
lbrasseur/oxenjavacommons
/ar.com.oxen.commons/src/main/java/ar/com/oxen/commons/dao/api/UpdateDao.java
UTF-8
101
1.609375
2
[]
no_license
package ar.com.oxen.commons.dao.api; public interface UpdateDao<T> { void update(T entity); }
true
69b4a8dc1573e41399f583d5256bf73098314194
Java
alex-asd/Java
/Semester 1/Exercises/Array/GradesTest.java
UTF-8
670
3.203125
3
[]
no_license
public class GradesTest { public static void main(String[] args) { GradesList list = new GradesList(15); list.setGrade(-3, 0); list.setGrade(12, 1); list.setGrade(10, 2); list.setGrade(4, 3); list.setGrade(10, 4); GradesList list2 = new GradesList(15); list2.setGrade(-3, 0); list2.setGrade(12, 1); list2.setGrade(10, 2); list2.setGrade(4, 3); list2.setGrade(10, 4); list2.setGrade(10, 6); System.out.println(list.getNumberOfGrades()); System.out.println(list.getGrade(0)); System.out.println(list.getGrade(4)); System.out.println(list); System.out.println(list.getAverage()); System.out.println(list.equals(list2)); } }
true
3713c247d7c6324d79e25a426873b12f450bd325
Java
svsdigitaltechnologies/hztb
/hztb-servicemanager/src/main/java/com/svs/hztb/sm/ServiceManager.java
UTF-8
2,621
1.914063
2
[]
no_license
package com.svs.hztb.sm; import javax.servlet.ServletContext; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.context.web.SpringBootServletInitializer; import org.springframework.boot.orm.jpa.EntityScan; import org.springframework.context.ApplicationListener; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.PropertySource; import org.springframework.context.annotation.PropertySources; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.web.context.ServletContextAware; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import com.svs.hztb.common.logging.Logger; import com.svs.hztb.common.logging.LoggerFactory; import com.svs.hztb.orchestration.component.service.StartupService; @SpringBootApplication @EnableWebMvc @EnableAsync @EnableJpaRepositories(basePackages = { "com.svs.hztb.repository" }) @ComponentScan({ "com.svs.hztb" }) @EntityScan(basePackages = "com.svs.hztb.entity") @PropertySources({ @PropertySource(value = "classpath:application.properties"), @PropertySource(value = "classpath:restful.client.properties"), @PropertySource(value = "classpath:sm_external_config.properties") }) public class ServiceManager extends SpringBootServletInitializer implements ApplicationListener<ContextRefreshedEvent>, ServletContextAware { private static Logger LOGGER = LoggerFactory.INSTANCE.getLogger(ServiceManager.class); @Autowired private StartupService startupService; public static void main(String[] args) { configureLogging(); SpringApplication.run(ServiceManager.class, args); LOGGER.debug("ServiceManager started succesfully"); } private static void configureLogging() { System.setProperty("log4j.configurationFile", "log4j2.xml"); System.setProperty("Log4jContextSelector", "org.apache.logging.log4j.core.async.AsyncLoggerContextSelector"); } @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(ServiceManager.class); } @Override public void setServletContext(ServletContext servletContext) { } @Override public void onApplicationEvent(ContextRefreshedEvent event) { startupService.start(); } }
true
926e5609f7964cbd05bbfe3d4eb28f18fcb1b700
Java
AboutJoke/MyWorkDemo
/app/src/main/java/com/sylvan/myworkdemo/wiget/TrapezoidView.java
UTF-8
6,323
2.171875
2
[]
no_license
package com.sylvan.myworkdemo.wiget; import android.content.Context; import android.graphics.*; import android.graphics.drawable.Drawable; import android.os.Handler; import android.os.Message; import android.support.annotation.NonNull; import android.support.v7.widget.AppCompatTextView; import android.util.AttributeSet; import android.view.View; import android.widget.TextView; import com.sylvan.myworkdemo.utils.DimenUtils; /** * @ClassName: TrapezoidView * @Author: sylvan * @Date: 19-1-10 上午11:57 */ public class TrapezoidView extends AppCompatTextView { private Paint paint; private Path path; private int mWidth; private int mHeight; private float mIncline;//梯度,即上底与下底长度差 private float mRadius;//圆角半径 int startColor; int endColor; private float[] radiusArray = new float[]{0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f}; public TrapezoidView(Context context) { super(context); init(); } public TrapezoidView(Context context, AttributeSet attrs) { super(context, attrs); init(); } public TrapezoidView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } public void init() { paint = new Paint(); paint.setAntiAlias(true); paint.setStyle(Paint.Style.FILL); path = new Path(); mWidth = DimenUtils.dp2px(56); mHeight = DimenUtils.dp2px(20); startColor = Color.parseColor("#FFFF42A7"); endColor = Color.parseColor("#FFFFAC49"); // Shader mShader = new LinearGradient(0, 0, 0, 0, // new int[]{startColor, endColor}, // null, Shader.TileMode.CLAMP); // paint.setShader(mShader); } // @Override // protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { // super.onMeasure(widthMeasureSpec, heightMeasureSpec); // int widthMode = MeasureSpec.getMode(widthMeasureSpec); // int heightMode = MeasureSpec.getMode(heightMeasureSpec); // int widthSize = MeasureSpec.getSize(widthMeasureSpec); // int heightSize = MeasureSpec.getSize(heightMeasureSpec); // if (widthMode == MeasureSpec.AT_MOST || heightMode == MeasureSpec.AT_MOST) { // setMeasuredDimension((int) mWidth, (int) mHeight); // } else { // setMeasuredDimension(widthSize, heightSize); // } // } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); handler.sendEmptyMessage(0); // path.moveTo(0, 500); // path.lineTo(0,300); // path.lineTo(100,200); // path.lineTo(100, 500); // int width = getWidth(); // int height = getHeight(); // path.moveTo(width, 0); // path.lineTo(0, 0); // path.lineTo(0, height); // path.lineTo(width - DimenUtils.dp2px(3), height); // path.close(); // canvas.drawPath(path, paint); // setBackground(new Drawable() { // @Override // public void draw(@NonNull Canvas canvas) { // // } // // @Override // public void setAlpha(int alpha) { // // } // // @Override // public void setColorFilter(ColorFilter colorFilter) { // // } // // @Override // public int getOpacity() { // return PixelFormat.TRANSLUCENT; // } // }); // setText("sssssssssssssssssssssss"); } private Handler handler = new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); drawBg(); } }; public void drawBg(){ int width = getWidth(); int height = getHeight(); // path.moveTo(500, 0); //rtl // path.lineTo(0,0); // path.lineTo(200,100); // path.lineTo(500, 100); // path.moveTo(500, 0);//ltr // path.lineTo(0,0); // path.lineTo(0,100); // path.lineTo(300, 100); // path.arcTo(); // RectF rectF = new RectF(100,200,500,400); // path.addRoundRect(rectF,radiusArray,Path.Direction.CW); path.addRect(100,200,500,400,Path.Direction.CW); // // Path path1 = new Path(); // path1.addCircle(120,220,18,Path.Direction.CW); // path.op(path1,Path.Op.DIFFERENCE); path.setLastPoint(200, 400); // if (DimenUtils.isLayoutRTL()){ // path.moveTo(width , 0); // path.lineTo(0, 0); // path.lineTo(DimenUtils.dp2px(3), height); // path.lineTo(width, height); // }else { // path.moveTo(width, 0); // path.lineTo(0, 0); // path.lineTo(0, height); // path.lineTo(width - DimenUtils.dp2px(3), height); // // } Shader mShader = new LinearGradient(0, 0, width, height, new int[]{startColor, endColor}, null, Shader.TileMode.CLAMP); paint.setShader(mShader); setBackground(new Drawable() { @Override public void draw(@NonNull Canvas canvas) { path.close(); // canvas.clipPath(path); canvas.drawPath(path, paint); } @Override public void setAlpha(int alpha) { } @Override public void setColorFilter(ColorFilter colorFilter) { } @Override public int getOpacity() { return PixelFormat.TRANSLUCENT; } }); } public void setStartColor(int color){ startColor = color; // invalidate(); } public void setEndColor(int color){ endColor = color; // drawBg(); invalidate(); } public void setRadiusArray(float leftBottom, float rightBottom, float leftTop, float rightTop){ radiusArray[0] = leftTop; radiusArray[1] = leftTop; radiusArray[2] = rightTop; radiusArray[3] = rightTop; radiusArray[4] = rightBottom; radiusArray[5] = rightBottom; radiusArray[6] = leftBottom; radiusArray[7] = leftBottom; // invalidate(); drawBg(); } }
true
e5fd2e06cbd0f30b87694fb3b423f8d3863b391f
Java
darthmanwe/benchpress
/task-reporting/src/main/java/com/palominolabs/benchpress/task/reporting/NoOpTaskProgressClient.java
UTF-8
512
1.9375
2
[ "Apache-2.0" ]
permissive
package com.palominolabs.benchpress.task.reporting; import com.fasterxml.jackson.databind.JsonNode; import java.time.Duration; import java.util.UUID; /** * Stub impl for test use */ public final class NoOpTaskProgressClient implements TaskProgressClient { @Override public void reportFinished(UUID jobId, int sliceId, Duration duration, String url) { // no op } @Override public void reportProgress(UUID jobId, int sliceId, JsonNode data, String url) { // no op } }
true
b7cc7da928ccc2dd6c44d19395d382f8dba32ccf
Java
sumangujja12/Test
/src/main/java/com/multibrand/dto/IRWDTO.java
UTF-8
237
1.898438
2
[]
no_license
package com.multibrand.dto; public class IRWDTO { private String messageName; public String getMessageName() { return messageName; } public void setMessageName(String messageName) { this.messageName = messageName; } }
true
2eae0993b0f2c016a2997492ed9bde539ff3cd94
Java
RosePasta/BugTypeBasedIRBL
/bench4bl/spring/shdp/sources/SHDP_2_1_0/spring-hadoop-core/src/main/java/org/springframework/data/hadoop/mapreduce/JobUtils.java
UTF-8
5,698
1.976563
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2011-2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.data.hadoop.mapreduce; import java.io.IOException; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.mapred.JobClient; import org.apache.hadoop.mapred.JobConf; import org.apache.hadoop.mapred.RunningJob; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.Job.JobState; import org.apache.hadoop.mapreduce.JobID; import org.springframework.data.hadoop.configuration.JobConfUtils; import org.springframework.util.ReflectionUtils; /** * Utilities around Hadoop {@link Job}s. * Mainly used for converting a Job instance to different types. * * @author Costin Leau * @author Mark Pollack * @author Thomas Risberg */ public abstract class JobUtils { /** * Status of a job. The enum tries to reuse as much as possible * the internal Hadoop terminology. * * @author Costin Leau */ public enum JobStatus { /** * The status cannot be determined - either because the job might be invalid * or maybe because of a communication failure. */ UNKNOWN, /** * The job is has been/is being defined or configured. * It has not been submitted to the job tracker. */ DEFINED, /** * The job has been submited to the tracker and its execution * is being prepared. */ PREPARING, /** * The job is actually running. */ RUNNING, /** * The execution has completed successfully. */ SUCCEEDED, /** * The execution has failed. */ FAILED, /** * The execution was cancelled or killed. */ KILLED; public static JobStatus fromRunState(int state) { switch (state) { case 1: return RUNNING; case 2: return SUCCEEDED; case 3: return FAILED; case 4: return PREPARING; case 5: return KILLED; default: return UNKNOWN; } } public static JobStatus fromJobState(JobState jobState) { switch (jobState) { case DEFINE: return DEFINED; case RUNNING: return RUNNING; default: return UNKNOWN; } } public boolean isRunning() { return PREPARING == this || RUNNING == this; } public boolean isFinished() { return SUCCEEDED == this || FAILED == this || KILLED == this; } public boolean isStarted() { return DEFINED != this; } } static Field JOB_INFO; static Field JOB_CLIENT_STATE; static { //TODO: remove the need for this JOB_CLIENT_STATE = ReflectionUtils.findField(Job.class, "state"); ReflectionUtils.makeAccessible(JOB_CLIENT_STATE); } public static RunningJob getRunningJob(Job job) { if (job == null) { return null; } try { Configuration cfg = job.getConfiguration(); JobClient jobClient = null; try { Constructor<JobClient> constr = JobClient.class.getConstructor(Configuration.class); jobClient = constr.newInstance(cfg); } catch (Exception e) { jobClient = new JobClient(); } org.apache.hadoop.mapred.JobID id = getOldJobId(job); if (id != null) { return jobClient.getJob(id); } else { return null; } } catch (IOException e) { return null; } } public static JobID getJobId(Job job) { if (job == null) { return null; } return job.getJobID(); } public static org.apache.hadoop.mapred.JobID getOldJobId(Job job) { if (job == null) { return null; } JobID id = getJobId(job); if (id != null) { return org.apache.hadoop.mapred.JobID.downgrade(id); } return null; } public static JobConf getJobConf(Job job) { if (job == null) { return null; } // we know internally the configuration is a JobConf Configuration configuration = job.getConfiguration(); if (configuration instanceof JobConf) { return (JobConf) configuration; } return JobConfUtils.createFrom(configuration, null); } /** * Returns the status of the given job. May return null indicating accessing the job * caused exceptions. * * @param job the job * @return the job status */ public static JobStatus getStatus(Job job) { if (job == null) { return JobStatus.UNKNOWN; } // attempt to capture the original status JobStatus originalStatus = JobStatus.DEFINED; try { Method getJobState = ReflectionUtils.findMethod(Job.class, "getJobState"); Object state = getJobState.invoke(job); if (state instanceof Enum) { int value = ((Enum<?>)state).ordinal(); originalStatus = JobStatus.fromRunState(value + 1); } } catch (Exception ignore) {} // go for the running info if available RunningJob runningJob = getRunningJob(job); if (runningJob != null) { try { return JobStatus.fromRunState(runningJob.getJobState()); } catch (IOException ex) { return JobStatus.UNKNOWN; } } // no running info found, assume we can use the original status return originalStatus; } }
true
6f3231308ed43c120bab9f2e8a7a63b12451271f
Java
nilvandosantos/ProjetoLabProgr
/src/view/JFatualizaPedido.java
ISO-8859-1
10,004
2.609375
3
[]
no_license
package view; import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import javax.swing.JLabel; import java.awt.Font; import javax.swing.JTextField; import javax.swing.JButton; import control.CadProduto; import control.CoordCaixa; import control.CoordPedido; import codigo.Caixa; import codigo.Pedido; import codigo.Produto; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; public class JFatualizaPedido extends JFrame { private JPanel contentPane; private JTextField textFieldCodPedido; private JTextField textFieldProduto; private JTextField textFieldQtd; /** * Esta classe tem como objetivo criar a interface grafica para adicionar um novo produto ao pedido. *. *@author Marco Lucas,Nayara,Nilvando. *@see JFcadastroPedido *@version 1.0 * */ //CRIAO DA TELA ATUALIZAR PEDIDO public JFatualizaPedido() { JButton btnAtualizar = new JButton("Atualizar"); JButton btnCancelar = new JButton("Cancelar"); setTitle("Atualiza o Pedido"); setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); setBounds(100, 100, 299, 191); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); getRootPane().setDefaultButton(btnAtualizar); JLabel lblCodigoDoPedido = new JLabel("Codigo do pedido:"); lblCodigoDoPedido.setFont(new Font("Times New Roman", Font.PLAIN, 13)); lblCodigoDoPedido.setBounds(10, 25, 107, 14); contentPane.add(lblCodigoDoPedido); textFieldCodPedido = new JTextField(); textFieldCodPedido.setBounds(166, 22, 107, 20); contentPane.add(textFieldCodPedido); textFieldCodPedido.setColumns(10); JLabel lblProduto = new JLabel("Produto:"); lblProduto.setFont(new Font("Times New Roman", Font.PLAIN, 12)); lblProduto.setBounds(10, 50, 64, 14); contentPane.add(lblProduto); textFieldProduto = new JTextField(); textFieldProduto.setBounds(166, 47, 107, 20); contentPane.add(textFieldProduto); textFieldProduto.setColumns(10); textFieldQtd = new JTextField(); textFieldQtd.setBounds(166, 72, 107, 20); contentPane.add(textFieldQtd); textFieldQtd.setColumns(10); JLabel lblQtd = new JLabel("Quantidade"); lblQtd.setFont(new Font("Times New Roman", Font.PLAIN, 12)); lblQtd.setBounds(10, 75, 86, 14); contentPane.add(lblQtd); btnAtualizar.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { int indice_caixa = 0; int indice_pedido = 0; boolean achou = false; // VERIFICA SE OS CAMPOS ESTAO PREENCHIDOS if (textFieldCodPedido.getText().equals("") || textFieldProduto.getText().equals("") || textFieldQtd.getText().equals("")) { JOptionPane.showMessageDialog(JFatualizaPedido.this, "Preencha os campos!", "Erro", JOptionPane.ERROR_MESSAGE); } else { // For-each para varrer a LinkedList de Caixa for (Caixa c : CoordCaixa.retornaCaixas()) { /* For-each para varrer a LinkedList de pedido dentro de um objeto da LinkedList caixa em busca da pedido * com ID fornecido */ for (Pedido d : CoordPedido.retornaPedido(indice_caixa)) { /* Verifica se o pedido tem o indice fornecido pelo * usuario */ try { if (Integer.parseInt(textFieldCodPedido .getText()) <= 0) { JOptionPane.showMessageDialog(null, "Digite um valor valido!", "Entrada invalida", JOptionPane.ERROR_MESSAGE); textFieldCodPedido.setText(""); return; } if (d.getNumero().equals( Integer.parseInt(textFieldCodPedido .getText())) && d.getPedidoAberto()) { achou = true; break; } } catch (NumberFormatException n) { JOptionPane .showMessageDialog( null, "Digite um codigo de pedido valido!", "Entrada invalida", JOptionPane.ERROR_MESSAGE); textFieldCodPedido.setText(""); return; } indice_pedido++; } if (achou) { break; } indice_caixa++; } // Se achou o pedido com ID fornecido if (achou) { Pedido pedido_alterar = CoordPedido.retornaUmPedido( indice_caixa, indice_pedido); int indice_do_produto = 0; boolean achou_produto = false; /* Varre a LinkedList de produtos para verificar se o / produto ja esta na pedido */ for (Produto p : pedido_alterar.retornaProdutos()) { // Verifica se o produto ja estao no pedido try { if (Integer.parseInt(textFieldProduto.getText()) <= 0) { JOptionPane.showMessageDialog(null, "Digite um valor valido!", "Entrada invalida", JOptionPane.ERROR_MESSAGE); textFieldProduto.setText(""); return; } if (p.getCodigo() == Integer .parseInt(textFieldProduto.getText())) { achou_produto = true; break; } } catch (NumberFormatException n) { JOptionPane .showMessageDialog( null, "Digite um codigo de produto valido!", "Entrada invalida", JOptionPane.ERROR_MESSAGE); textFieldProduto.setText(""); return; } indice_do_produto++; } // Se achou o produto no pedido, entra aqui if (achou_produto) { Integer quantidade = 0; quantidade = pedido_alterar .getQtde(indice_do_produto); try { if (Integer.parseInt(textFieldQtd.getText()) < 0) { JOptionPane.showMessageDialog(null, "Digite um valor vlido!", "Entrada invalida", JOptionPane.ERROR_MESSAGE); textFieldQtd.setText(""); return; } quantidade = quantidade + Integer.parseInt(textFieldQtd .getText()); } catch (NumberFormatException n) { JOptionPane.showMessageDialog(null, "Digite uma quantidade vlida!", "Entrada invalida", JOptionPane.ERROR_MESSAGE); textFieldQtd.setText(""); return; } pedido_alterar.alteraQtde(indice_do_produto, quantidade); textFieldCodPedido.setText(""); textFieldProduto.setText(""); textFieldQtd.setText(""); JOptionPane.showMessageDialog( JFatualizaPedido.this, "Produto atualizado.\nPedido [" + pedido_alterar.getNumero() + "] atualizada com sucesso!", "Sucesso", JOptionPane.INFORMATION_MESSAGE); /*Se o produto ainda no estao no pedido, sero adicionado */ } else { Produto produto_a_ser_adicionado = new Produto(); Integer quantidade; int produto = 0; int indice2 = 0; boolean achou_produto2 = false; // Varre a LinkedList de produtos for (Produto a : CadProduto.getProdutos()) { /* * Verifica se o produto com codigo fornecido,pelo usuario estao na LinkeList de produtos */ try { if (Integer.parseInt(textFieldProduto .getText()) <= 0) { JOptionPane.showMessageDialog(null, "Digite um valor vlido!", "Entrada invlida", JOptionPane.ERROR_MESSAGE); textFieldProduto.setText(""); return; } if (a.getCodigo() == Integer .parseInt(textFieldProduto .getText())) { achou_produto2 = true; produto_a_ser_adicionado = a; break; } } catch (NumberFormatException n) { JOptionPane.showMessageDialog(null, "Digite um cdigo vlido!", "Entrada invlida", JOptionPane.ERROR_MESSAGE); textFieldProduto.setText(""); return; } indice2++; } /* Se achou o produto na LinkedList de produtos,adiciona ele no pedido */ if (achou_produto2) { pedido_alterar.adicionaProduto( produto_a_ser_adicionado, Integer .parseInt(textFieldQtd .getText())); textFieldCodPedido.setText(""); textFieldProduto.setText(""); textFieldQtd.setText(""); JOptionPane.showMessageDialog( JFatualizaPedido.this, "Produto adicionado.\nPedido [" + pedido_alterar.getNumero() + "] atualizada com sucesso!", "Sucesso", JOptionPane.INFORMATION_MESSAGE); // Se no, exibe uma mensagem de erro } else { textFieldCodPedido.setText(""); textFieldProduto.setText(""); textFieldQtd.setText(""); JOptionPane.showMessageDialog( JFatualizaPedido.this, "Produto no encontrado!", "Erro", JOptionPane.ERROR_MESSAGE); } }// Fecha o else para produto nao encontrado no pedido // Else para pedido nao econtrado } else { JOptionPane.showMessageDialog(JFatualizaPedido.this, "Pedido no encontrado!", "Erro", JOptionPane.ERROR_MESSAGE); } }// Fecha else para campos preenchidos } }); btnAtualizar.setBounds(10, 112, 107, 23); contentPane.add(btnAtualizar); btnCancelar.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { dispose(); } }); btnCancelar.setBounds(158, 112, 107, 23); contentPane.add(btnCancelar); } }
true
2ed1fca0929582ad91409f564edeba8e273b730f
Java
genemskim/spring-boot-config
/src/main/java/com/example/spring/springbootconfig/SpringBootConfigApplication.java
UTF-8
810
2.15625
2
[]
no_license
package com.example.spring.springbootconfig; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; @SpringBootApplication public class SpringBootConfigApplication { private static Logger log = LoggerFactory.getLogger( SpringBootConfigApplication.class); public static void main(String[] args) { SpringApplication.run(SpringBootConfigApplication.class, args); } @Value("${server.ip}") String serverIp; @Bean CommandLineRunner values() { return args -> { log.info(" > 서버 IP: " + serverIp); }; } }
true
2d09e00a9ed55ae05d3b4bc4c2a124a2ec2ad005
Java
neo3kk/PracticaFinal
/BackEnd/src/main/java/com/rest/vue/repos/ReplyRepository.java
UTF-8
385
1.875
2
[]
no_license
package com.rest.vue.repos; import com.rest.vue.entities.Reply; import com.rest.vue.entities.Topic; import org.springframework.data.repository.CrudRepository; import java.util.List; public interface ReplyRepository extends CrudRepository<Reply, Integer> { List<Reply> findRepliesByTopic(String topic); List<Reply> findRepliesByTopicAndUser(String topic, String user); }
true
ea9b0a8931bba2527872287eb43bb1bae3d55b0e
Java
sestaszak/CS111b
/src/Previous/GuessingProgram.java
UTF-8
5,513
3.46875
3
[]
no_license
package Previous; import java.util.*; public class GuessingProgram { //call and test the (new) NumberGuesser class. public static void main(String args[]){ System.out.println("Play a manual game with user entry"); playManualGame(1, 100); System.out.println("Play manual games until player quits"); playManyManualGames(); System.out.println("Played many games to get average number of guesses"); playRepsGame(1000, 1, 100); playRepsGame(1000, 1, 500); System.out.println("Played the example game in assignment"); playTestGame(); } public static void playTestGame(){ NumberGuesser guesser = new NumberGuesser(1, 100); // test target = 72 System.out.println(guesser.getCurrentGuess()); //50 guesser.higher(); System.out.println(guesser.getCurrentGuess()); //75 guesser.lower(); System.out.println(guesser.getCurrentGuess()); //62 guesser.higher(); System.out.println(guesser.getCurrentGuess()); //68 guesser.higher(); System.out.println(guesser.getCurrentGuess()); //71 guesser.higher(); System.out.println(guesser.getCurrentGuess()); //73 guesser.lower(); System.out.println(guesser.getCurrentGuess()); //72 //this matches correctly } public static void playManualGame(int startLow, int startHigh){ NumberGuesser guesser = new NumberGuesser(startLow, startHigh); int guess = guesser.getCurrentGuess(); //System.out.println("Starting guess: " + guess); boolean matched = false; System.out.println("Guess a number between 1 and 100."); while(!matched) { //System.out.println("Now guessing between " + low + " and " + high); char perf = getUserResponseToGuess(guess); if(perf=='h'){ guesser.higher(); //System.out.println("Call to higher method since response was h"); } else if(perf=='l'){ guesser.lower(); //System.out.println("Call to lower method since response was l"); } else if (perf=='c'){ matched = true; } guess = guesser.getCurrentGuess(); if(guess < startLow | guess > startHigh) { System.out.println("User response results in a guess out of the range. Did you answer truthfully? Exiting game."); matched = true; } //System.out.println("Updated guess: " + guess); } guesser.reset(); } public static char getUserResponseToGuess(int guess) { // prompt user by asking: "is it <guess>? (h/l/c):" // return char (h/l/c) Scanner input = new Scanner(System.in); System.out.print("is it " + guess + "? (h/l/c):"); char response = input.next().charAt(0); //check that response is only h/l/c and return //else ?? ask again? if((response == 'h') || (response == 'l') || (response == 'c')) { return response; } else { System.out.println("Hmm, that's not quite right. Please only respond with h, l, or c."); } return response; } public static boolean shouldPlayAgain() { //ask if play again, read character, return boolean based on character Scanner input = new Scanner(System.in); // can i just have one scanner in main? System.out.print("Great! Do you want to play again? (y/n):"); char response = input.next().charAt(0); boolean playAgain = (response == 'y'); return playAgain; } public static void playManyManualGames(){ do { playManualGame(1, 100); } while (shouldPlayAgain()); } public static void playRepsGame(int reps, int startLow, int startHigh){ Random random = new Random(); NumberGuesser guesser = new NumberGuesser(startLow, startHigh); int totalGuessCount = 0; for (int i = 0; i < reps; i++) { // There is always the initial guess int guessCount = 1; // Generate a random value to look for, from MIN to MAX, inclusive. int targetValue = startLow + random.nextInt(startHigh - startLow + 1); //System.out.println("Random target value is: " + targetValue); // Keep looping until the guesser gets it right while (targetValue != guesser.getCurrentGuess()) { // Adjust the guesser, as needed... //System.out.println("Current guess is: " + guesser.getCurrentGuess()); if (targetValue > guesser.getCurrentGuess()) { guesser.higher(); } else { guesser.lower(); } // That's one more guess, bump up the count guessCount++; } // Keep track of the total number of guesses in all the simulated games totalGuessCount += guessCount; // Return the guesser is in its initial state guesser.reset(); } // Calculate and display the average double averageGuessCount = totalGuessCount / (double) reps; System.out.println("Average number of guesses: " + averageGuessCount + " in " + reps + " games, guessing between " + startLow + " and " + startHigh); } }
true
6a3468a1601b9ca3a019fb07163d935f16394241
Java
shianqi/High-Light-APP
/src/com/High365/HighLight/Bean/SimpleModel.java
UTF-8
474
2.015625
2
[]
no_license
package com.High365.HighLight.Bean; /** * Created by HUPENG on 2016/3/12. */ /** * Created by HUPENG on 2016/3/12. */ public class SimpleModel { private Integer status; private String msg; public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } }
true
3d938a1d033fd9ab9449d02700e63c0192b299b1
Java
MrJiao/JacksonLifecycle
/activityfragmentlifecycle/src/main/java/com/jackson/activityfragmentlifecycle/glide_lifecycle/FragmentLifecycleCallbacks.java
UTF-8
277
1.617188
2
[]
no_license
package com.jackson.activityfragmentlifecycle.glide_lifecycle; /** * Created by Jackson on 2017/5/11. * Version : 1 * Details : */ public interface FragmentLifecycleCallbacks extends ActivityLifecycleCallbacks { void onCreateView(); void onActivityCreated(); }
true
dafb1c734863e3f856d859bde682399378fbf678
Java
pacey/password-gen
/web-api/src/main/java/com/github/pacey/passwordgen/app/PasswordService.java
UTF-8
846
2.390625
2
[]
no_license
package com.github.pacey.passwordgen.app; import com.github.pacey.passwordgen.Configuration; import com.github.pacey.passwordgen.PasswordGenerator; import com.github.pacey.passwordgen.app.provider.RandomProvider; import io.micrometer.core.annotation.Timed; import javax.inject.Inject; import javax.inject.Singleton; @Singleton public class PasswordService { private final RandomProvider randomProvider; @Inject public PasswordService(RandomProvider randomProvider) { this.randomProvider = randomProvider; } @Timed( value = "password.generate", percentiles = { 0.1, 0.5, 0.9 }, description = "Time taken to generate a password" ) public String generatePassword(Configuration configuration) { return new PasswordGenerator(configuration, randomProvider.random()).generate(); } }
true
e28169c860821e0ddcce11c581968ecc83700e6c
Java
jefferyyuan/AlgorithmPractices
/LeetCode-Java/Anagrams.java
UTF-8
1,460
3.453125
3
[]
no_license
public class Solution { public List<String> anagrams(String[] strs) { HashMap<String,String> record = new HashMap<String,String>(); List<String> result = new ArrayList<String>(); for(int i = 0;i < strs.length;i ++) { String tempString = sortString(strs[i]); if(record.containsKey(tempString)) { result.add(strs[i]); if(record.get(tempString) != null) { result.add(record.get(tempString)); record.put(tempString,null); } } else { record.put(tempString, strs[i]); } } return result; } String sortString(String input) { int[] record = new int[26]; for(int i = 0;i < 26;i ++) record[i] = 0; for(int i = 0;i < input.length();i ++) { char c = input.charAt(i); int index = Character.compare(c, 'a'); record[index] = record[index] + 1; } char[] resultArray = new char[input.length()]; int index = 0; for(int i = 0;i < 26;i ++) { char c = (char)(((int)'a') + i); for(int j = 0;j < record[i];j ++) { resultArray[index] = c; index ++; } } return String.valueOf(resultArray); } }
true
ccbe98e0bd1bfe161fb3e6407e5fb5eac51aff5b
Java
HenrikSandberg/ObjektOrientertProgrammeringV2020
/Forelesning1/Arv/Foreleser.java
UTF-8
715
3.125
3
[]
no_license
package Arv; public class Foreleser extends Person implements Ansatt { private String ansattNummer; private String[] emner; public Foreleser(String navn, int alder, String ansattNummer, String[] emner) { super(navn, alder); this.ansattNummer = ansattNummer; this.emner = emner; } public String giAnsattNummer() { return ansattNummer; } @Override public String toString(){ String printStreng = "Foreleser " + navn +"\n\nEmner:\n"; for (int i = 0; i < emner.length; i++) { if (emner[i] != null) { printStreng += " " + emner[i] + "\n"; } } return printStreng; } }
true
1dc48127846ea3ef66ea6c1d26c3018fe674a938
Java
harshalp27/BackupCodesYTPL
/StaticFactoryMethod/src/com/test/TestSpringStaticFactoryMethod.java
UTF-8
654
2.328125
2
[]
no_license
package com.test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class TestSpringStaticFactoryMethod { // @SuppressWarnings("resource") public static void main(String[] args) throws Exception { ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); EmployeeDTO manager = (EmployeeDTO) context.getBean("manager"); System.out.println(manager); EmployeeDTO director = (EmployeeDTO) context.getBean("director"); System.out.println(director); } }
true
6e604e90b0ec5579c3fb7cdd208acae444e11842
Java
BeaterLee/Spring_Annotation
/src/main/java/com/beater/springannotation/condition/MyImportBeanDefinitionRegistrar.java
UTF-8
1,452
2.515625
3
[]
no_license
package com.beater.springannotation.condition; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.beans.factory.support.RootBeanDefinition; import org.springframework.context.annotation.ImportBeanDefinitionRegistrar; import org.springframework.core.type.AnnotationMetadata; import com.beater.springannotation.bean.Rainbow; public class MyImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar { /** * AnnotationMetadata:当前类的注解信息 * BeanDefinitionRegistry:BeanDefinition注册类; * 把所有需要添加到容器中的bean;调用 * BeanDefinitionRegistry.registerBeanDefinition手工注册进来 */ @Override public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) { // TODO Auto-generated method stub boolean definition1 = registry.containsBeanDefinition("com.beater.springannotation.bean.Red"); boolean definition2 = registry.containsBeanDefinition("com.beater.springannotation.bean.Blue"); if (definition1 && definition2) { //指定Bean定义信息;(Bean的类型,Bean的作用域等等) BeanDefinition beanDefinition = new RootBeanDefinition(Rainbow.class); //注册一个Bean,指定bean名 registry.registerBeanDefinition("rainbow", beanDefinition); } } }
true
1f9cb06e8103118bfc83ea3694a0502d832b8c8f
Java
SeungsoonLeee/JAVA
/JSP/May16_1_InputOutput/src/com/kwon/io/main/Output.java
WINDOWS-1252
2,005
2.484375
2
[]
no_license
package com.kwon.io.main; import java.io.IOException; import java.io.PrintWriter; import java.net.URLEncoder; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.oreilly.servlet.MultipartRequest; import com.oreilly.servlet.multipart.DefaultFileRenamePolicy; /** * Servlet implementation class Output */ @WebServlet("/Output") public class Output extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public Output() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse * response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.getWriter().append("Served at: ").append(request.getContextPath()); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setCharacterEncoding("euc-kr"); String path = request.getSession().getServletContext().getRealPath("f"); MultipartRequest mr = new MultipartRequest(request, path, 30 * 1024 * 1024, "euc-kr", new DefaultFileRenamePolicy()); String t = mr.getParameter("t"); String d = mr.getParameter("d").replace("\r\n", "<br>"); String f = mr.getFilesystemName("f"); f = URLEncoder.encode(f, "euc-kr"); f = f.replace("+", " "); PrintWriter out = response.getWriter(); out.print("<html><head><meta charset='euc-kr'></head><body>"); out.printf("<h1>%s</h1>", t); out.printf("%s<p>", d); out.printf("<a href='f/%s'>ٿޱ</a>", f); out.print("</body></html>"); } }
true
d3e450402807396730cfb9a1379010cc634341a2
Java
schullars/CheckApp
/app/src/main/java/com/xunxiaozdh/error/MyError.java
UTF-8
1,288
2.703125
3
[]
no_license
package com.xunxiaozdh.error; import java.util.EnumSet; /** * Author: schullar * Company: Xunxiao * Date: 2017/8/30 0030 10:44 * Mail: schullar@outlook.com * Descrip: */ public class MyError { private static final int SQL_ERROR = 0x10010000; public enum ERROR{ // sql server error Get_Data_From_Sql_Failed(0x0001|SQL_ERROR), Connect_Sql_Failed, Generate_Sql_Cmd_Failed, Insert_To_Sql_Failed, // uart get data error Uart_Invalid_Cmd_Params, Uart_Send_Cmd_Failed, Uart_Receive_Data_Failed, No_Error, UnInit, UnKnown_Error; private final int value; ERROR(){ this(Counter.nextValue); } ERROR(int value){ this.value = value; Counter.nextValue = value + 1; } private static class Counter{ private static int nextValue = 0; } public int getValue(){ return value; } public static ERROR valueOf(int value){ for (ERROR error: EnumSet.allOf(ERROR.class)){ if (error.getValue() == value){ return error; } } return ERROR.UnKnown_Error; } } }
true
a3f1914a0ee2ad7284fbd31bb6ba4ef3e2d57558
Java
Sahak79/leetcode
/src/search_in_array/ConsumerProducer.java
UTF-8
1,563
3.46875
3
[]
no_license
package search_in_array; class ConsumerProducer1 { boolean valueSet = false; public static void main(String[] args) { ConsumerProducer1 consumerProducer1 = new ConsumerProducer1(); Consumer1 consumer1 = new Consumer1(consumerProducer1); Producer1 producer1 = new Producer1(consumerProducer1); } synchronized void consume(){ if (valueSet) { try { this.wait(); } catch (InterruptedException e) {} } System.out.println("consume"); valueSet = true; notify(); } synchronized void produce() { if (!valueSet) { try { this.wait(); } catch (InterruptedException e) {} } System.out.println("produce"); valueSet = false; notify(); } } class Consumer1 implements Runnable { ConsumerProducer1 consumerProducer1; Consumer1(ConsumerProducer1 consumerProducer1) { this.consumerProducer1 = consumerProducer1; new Thread(this, "Consumer1").start(); } @Override public void run() { while (true) { consumerProducer1.consume(); } } } class Producer1 implements Runnable { ConsumerProducer1 consumerProducer1; Producer1(ConsumerProducer1 consumerProducer1) { this.consumerProducer1 = consumerProducer1; new Thread(this, "Producer1").start(); } @Override public void run() { while (true) { consumerProducer1.produce(); } } }
true
6efa4a644f09b0cd5611c358e45cb4c5bba3f215
Java
mattemerson/Nosreme
/algorithm-samples/src/main/java/org/emerson/file/FileSource.java
UTF-8
1,788
3
3
[]
no_license
package org.emerson.file; import java.io.File; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Objects; public class FileSource { public static class PathSourceRef implements FileSourceRef { private Path path; public PathSourceRef(Path path) { this.path = path; } @Override public Path toPath() { return path; } @Override public File toFile() { return path.toFile(); } @Override public String toFilename() { return path.toFile().toString(); } } public static class FileSourceRefImpl implements FileSourceRef { private File file; public FileSourceRefImpl(File file) { this.file = file; } @Override public Path toPath() { return file.toPath(); } @Override public File toFile() { return file; } @Override public String toFilename() { return file.toString(); } } public static class FilenameSourceRef implements FileSourceRef { private String filename; FilenameSourceRef(String filename) { this.filename = filename; } @Override public Path toPath() { return Paths.get(filename); } @Override public File toFile() { return toPath().toFile(); } @Override public String toFilename() { return filename; } } public static FileSourceRef fromPath(Path path) { Objects.requireNonNull(path, "'path' is a required parameter"); return new PathSourceRef(path); } public static FileSourceRef fromFile(File file) { Objects.requireNonNull(file, "file' is a required parameter"); return new FileSourceRefImpl(file); } public static FileSourceRef fromFilename(String filename) { Objects.requireNonNull(filename, "'filename' is a required parameter"); return new FilenameSourceRef(filename); } }
true
8fad6f7a3ec8438949504ba2b3abc88a6c47c7c1
Java
MartinSteffen/pest
/src/Absyn/And_State.java
UTF-8
3,072
2.59375
3
[]
no_license
package absyn; import java.io.Serializable; import java.awt.Rectangle; public class And_State extends State implements Serializable, Cloneable { public StateList substates; public And_State(Statename n, StateList sl) { name = n; rect = null; substates = sl; }; public And_State(Statename n, StateList sl, CRectangle r) { name = n; rect = r; substates = sl; }; public And_State(Statename n, StateList sl, CRectangle r, Location l) { name = n; rect = r; substates = sl; location = l; }; /** * @exception CloneNotSupportedException self-explanatory exception */ public Object clone() throws CloneNotSupportedException { CRectangle rectclone = (rect == null) ? null : (CRectangle)rect.clone(); StateList substatesclone = (substates == null) ? null : (StateList)substates.clone(); Location locationclone = (location == null) ? null : (Location)location.clone(); Statename nameclone = (name == null) ? null : (Statename)name.clone(); return new And_State(nameclone, substatesclone, rectclone, locationclone); }; } //---------------------------------------------------------------------- // Abstract Syntax for PEST Statecharts // ------------------------------------ // // $Id: And_State.java,v 1.15 1999-02-09 13:17:10 swtech00 Exp $ // // $Log: not supported by cvs2svn $ // Revision 1.14 1999/02/09 10:12:40 swtech00 // Null-name f"urs Clonen abgefangen // // Revision 1.13 1999/01/28 10:40:30 swtech00 // Erster Konstruktor-Parameter (name) geklont // // Revision 1.12 1999/01/11 17:23:46 swtech00 // Alle Bestandteile der abstrakten Syntax mit Locations (= nicht-abstrakte // Unterklassen von Absyn) in der Form modifiziert, da"s das Locations-Feld // mit-geklont wird. => // // o Jeweils neuer Kontruktor hinzugef"ugt // o clone-Methode angepa"st // // [Steffen] // // Revision 1.11 1999/01/09 15:47:52 swtech13 // clone() methoden korrigiert (weitere nullpointerabfragen) // // Revision 1.10 1998/12/17 15:47:16 swtech00 // Null-Pointer-Exception nei clone() abgefangen // // Revision 1.9 1998/12/15 16:33:24 swtech00 // Towards new package names. // // Revision 1.8 1998/12/15 13:38:01 swtech00 // exception-tag hinzugefuegt um javadoc sauber durchlaufen zu lassen // // Revision 1.7 1998/12/15 11:30:38 swtech00 // Rectangle durch CRectangle ersetzt // // Revision 1.6 1998/12/15 07:11:06 swtech01 // Added Serialization to all classes // // Revision 1.5 1998/12/11 17:39:18 swtech00 // *** empty log message *** // // Revision 1.4 1998/12/02 12:40:35 swtech19 // Einfuegen der Positionen. // // Revision 1.3 1998/11/30 17:07:40 swtech00 // - Namens-feld entfernt (da es nun in der Oberklasse ist) // - Konventionen vereinfacht ("_s" und "o"-Praefix entfernt) // // (Steffen) // // Revision 1.2 1998/11/26 16:32:10 swtech00 // Id and Log extension // // //----------------------------------------------------------------------
true
a3d43c5d670128f0d081224cbe2a6e866e198a9e
Java
aliceITR/Mobile_App_Basics
/Expense_Tracker/app/src/main/java/airblair/myexpenses/Expenses.java
UTF-8
3,546
2.390625
2
[]
no_license
package airblair.myexpenses; import androidx.room.ColumnInfo; import androidx.room.Entity; import androidx.room.Ignore; import androidx.room.PrimaryKey; import android.content.ContentValues; import android.provider.BaseColumns; @Entity(tableName = Expenses.TABLE_NAME) public class Expenses { private static final int DATABASE_VERSION = 1; private static final String DATABASE_NAME = "expenseTracker.db"; public static final String TABLE_NAME = "Expenses"; public static final String COLUMN_ID = "entryID"; public static final String COLUMN_NAME = "Name"; public static final String COLUMN_CATEGORY = "Category"; public static final String COLUMN_DATE = "Date"; public static final String COLUMN_AMOUNT = "Amount"; public static final String COLUMN_NOTE = "Note"; @ColumnInfo(name = COLUMN_NAME) private String name; @ColumnInfo(name = COLUMN_CATEGORY) private String category; @ColumnInfo(name = COLUMN_DATE) private String date; @ColumnInfo(name = COLUMN_AMOUNT) private double amount; @ColumnInfo(name = COLUMN_NOTE) private String note; @PrimaryKey(autoGenerate = true) @ColumnInfo(index = true, name = COLUMN_ID) private long _id; @Ignore public Expenses(){} // public Expenses(String name, String category, String date, double amount, String note, long id) // { // this.name = name; // this.category = category; // this.date = date; // this.amount = amount; // this.note = note; // _id = id; // } public Expenses(String name, String category, String date, double amount, String note) { this.name = name; this.category = category; this.date = date; this.amount = amount; this.note = note; } public void setName(String name) { this.name = name; } public void setCategory(String category) { this.category = category; } public void setDate(String date) { this.date = date; } public void setName(double amount) { this.amount = amount; } public void setNote(String note) { this.note = note; } public void setId(long id) { _id = id; } public String getName() { return name; } public String getCategory() { return category; } public String getDate() { return date; } public double getAmount() { return amount; } public String getNote() { return note; } public long getId() { return _id; } public static Expenses fromContentValues(ContentValues values) { final Expenses expenseData = new Expenses(); if (values.containsKey(COLUMN_ID)) { expenseData._id = values.getAsLong(COLUMN_ID); } if (values.containsKey(COLUMN_NAME)) { expenseData.name = values.getAsString(COLUMN_NAME); } if (values.containsKey(COLUMN_CATEGORY)) { expenseData.category = values.getAsString(COLUMN_CATEGORY); } if (values.containsKey(COLUMN_DATE)) { expenseData.date = values.getAsString(COLUMN_DATE); } if (values.containsKey(COLUMN_AMOUNT)) { expenseData.amount = values.getAsFloat(COLUMN_AMOUNT); } if (values.containsKey(COLUMN_NOTE)) { expenseData.note = values.getAsString(COLUMN_NOTE); } return expenseData; } }
true
85b2dbaedf561e592d26b89d8abcc3afb0df9628
Java
lhousaine/Project_school_management
/backend/school_ms_schools/src/main/java/com/isma/school_ms_schools/service/iservices/ITrainingService.java
UTF-8
594
2.046875
2
[]
no_license
package com.isma.school_ms_schools.service.iservices; import com.isma.school_ms_schools.core.exceptions.NoDataFoundException; import com.isma.school_ms_schools.data.Dto.TrainingDTO; import java.util.List; public interface ITrainingService extends IAbstractService<Long, TrainingDTO> { public TrainingDTO findTrainingByName(String trainingName) throws NoDataFoundException; public List<TrainingDTO> findTrainingsByEducationLevelName(String eduLevelName) throws NoDataFoundException; public List<TrainingDTO> findTrainingsByEducationLevelId(Long id) throws NoDataFoundException; }
true
32452773782f63f699293b1824052c370b61593c
Java
russnewman/time-tracker-app-backend
/src/main/java/com/example/TimeTracker/dto/LogRequest.java
UTF-8
358
1.765625
2
[]
no_license
package com.example.TimeTracker.dto; import lombok.Getter; import lombok.Setter; import lombok.ToString; import javax.validation.constraints.NotBlank; @Getter @Setter @ToString public class LogRequest { @NotBlank private String browser; @NotBlank private String startDateTime; @NotBlank private String tabName; @NotBlank private String url; }
true
ecad42414bf6b93e73244d57250c5f0eead958c5
Java
kushalsec043/Coding_prep
/Nick_White/Leet12.java
UTF-8
529
3.296875
3
[]
no_license
package Nick_White; public class Leet12 { public static void main(String[] args) { System.out.println(isPalindrome(12321)); } public static boolean isPalindrome(int num) { int n = num; int sum = 0; int r = 0; if(num == 0) { return true; } if(num < 0 || num % 10 == 0) { return false; } while(n > 0) { r = n%10; sum = (sum * 10) + r; n = n/10; } if(sum == num || num == sum/10) { return true; } return false; } }
true
8c81372ed2c5fc6b17548cee277a0b3c47db0d39
Java
ki4wangdy/Encounter4U
/src/com/imrub/shoulder/module/detail/IViewPagerChangeListener.java
UTF-8
194
1.648438
2
[]
no_license
package com.imrub.shoulder.module.detail; public interface IViewPagerChangeListener { public void onPageSelect(int index); public void onPageScrolled(int arg0, float arg1, int arg2); }
true
fd9f288ac59c6637c18883af75f686036c415c9b
Java
MDBrodskiy/COMSC-255
/Assignments/AS09/PigLatin.java
UTF-8
1,219
4.125
4
[ "MIT" ]
permissive
/* * * Written by: Michael Brodskiy * Class: Programming with Java (COMSC-255) * Instructor: Prof. Chern * */ import java.util.Scanner; /** * This program takes in a String input and converts it to Pig Latin * */ public class PigLatin { public static void main(String[] args) { //Create Scanner for keyboard input Scanner keyboard = new Scanner(System.in); //Ask for String input System.out.print("Enter a String and I will convert it to Pig Latin: "); String phrase = keyboard.nextLine(); //Modify phrase to make it readable phrase = phrase.trim(); String[] tokens = phrase.split(" "); //Create a loop control variable byte i = 0; while (i < tokens.length) { if (tokens[i].length() < 2) { //Confirm the String is longer than a character System.out.print(tokens[i].toUpperCase() + "ay "); } else { tokens[i] = tokens[i].substring(1,2).toUpperCase() + tokens[i].substring(2).toLowerCase() + tokens[i].substring(0,1).toLowerCase() + "ay "; System.out.print(tokens[i]); } i++; } } }
true
2aa277f75a7c36c2d34984f95f5569473d3ab566
Java
liuruichao555/blog
/src/main/java/cn/liuruichao/common/StatusCode.java
UTF-8
182
1.828125
2
[]
no_license
package cn.liuruichao.common; /** * StatusCode * * @author liuruichao * @date 15/9/5 下午5:03 */ public interface StatusCode { public static final int ERROR_CODE = -1; }
true
08c53ea16228a3392650b1215df4e8eb948464f0
Java
kamenska/qa_learning
/src/main/java/Flow.java
UTF-8
2,124
3.59375
4
[]
no_license
package main.java; import java.util.Random; public class Flow { public static void main(String[] args) { int score = 0; String name = "Lionss"; String result = "nothing"; String day = "MON"; String scores = ""; String xy = ""; Random r = new Random(); int num = r.nextInt(); //decision-making statements if (num > 0) { System.out.println("The number is positive " + num); } if ("Lions".equals(name)) { //if name equals "Lion" then put 200 score = 200; System.out.println("Score is --> " + score); } else { score = 300; System.out.println("Score is --> " + score); } //ternary operator result = name == "Lionss" ? (xy = "YES") : (xy = "NO"); System.out.println("Name is Lionss? " + xy); if (score == 0) { // we use 'else if' for the conditionals-actions result = "A"; System.out.println("result is " + result + " because name is " + name); } else if (score == 200){ result = "B"; System.out.println("result is " + result + " because name is " + name); } else if (score == 300) { result = "C"; System.out.println("result is " + result + " because name is " + name); } else { System.out.println("result is " + result + " because name is " + name); } switch (day){ // we use 'case' for the testing the value of the variable case "MON": System.out.println("The week just started..."); break; case "TUE": System.out.println("Time to work!!"); break; case "WED": case "THU": case "FRI": System.out.println("Nearly weekend"); break; case "SAT": System.out.println("Weekend!!!"); break; case "SUN": System.out.println("Weekend!!!"); break; default: System.out.println("Invalid day?"); } } }
true
278b0fcc0145b9327e80b05aecec59622a5743e4
Java
binaryboolean/OOD
/src/main/java/com/driku/dao/UserDAOImpl.java
UTF-8
2,500
2.171875
2
[]
no_license
/** * **************************************************************************** * * Copyright (c) 2016, DRIKU Technologies and/or its affiliates. All rights * reserved. * ___________________________________________________________________________________ * * * NOTICE: All information contained herein is, and remains the property of * DRIKU and its suppliers,if any. The intellectual and technical concepts * contained herein are proprietary to DRIKU Technologies. and its suppliers and * may be covered by us and Foreign Patents, patents in process, and are * protected by trade secret or copyright law. Dissemination of this information * or reproduction of this material is strictly forbidden unless prior written * permission is obtained from DRIKU Technologies */ package com.driku.dao; import com.driku.constants.UserConstants; import com.driku.model.User; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Repository; /** * * @author baldeep */ @Repository public class UserDAOImpl implements UserDAO { @Autowired JdbcTemplate jdbcTemplate; @Override public User getUserByMobile(String mobileNumber) { try { return jdbcTemplate.queryForObject(UserConstants.QUERY_SELECT_USER_BY_MOBILE, new UserDAOMapper(), mobileNumber); } catch (EmptyResultDataAccessException e) { System.out.println("User not found"); } return null; } @Override public List<User> getAllUsers() { try { return jdbcTemplate.query(UserConstants.QUERY_SELECT_ALL_USER, new UserDAOMapper()); } catch (EmptyResultDataAccessException e) { } return null; } @Override public User getUserByEmail(String userEmail) { try { return jdbcTemplate.queryForObject(UserConstants.QUERY_SELECT_USER_BY_EMAIL, new UserDAOMapper(), userEmail); } catch (EmptyResultDataAccessException e) { } return null; } @Override public User authenticateUser(String userEmail, String userPassword) { try { return jdbcTemplate.queryForObject(UserConstants.QUERY_AUTHENTICATE_USER, new UserDAOMapper(), userEmail, userPassword); } catch (EmptyResultDataAccessException e) { } return null; } }
true
bda695f3f482971e726ef6528affb1654d9be743
Java
jedrzejowski/aasd-project
/src/main/java/pl/edu/pw/aasd/data/PartnerPromotion.java
UTF-8
1,142
2.484375
2
[]
no_license
package pl.edu.pw.aasd.data; import pl.edu.pw.aasd.Jsonable; import java.util.ArrayList; public class PartnerPromotion extends Jsonable { String id; String description; int maxReservations = 0; ArrayList<String> userIds = new ArrayList<>(); public int getMaxReservations() { return maxReservations; } public void setMaxReservations(int maxReservations) { this.maxReservations = maxReservations; } public int getActualReservations() { return userIds.size(); } public boolean addUserToPromotion(String user) { if (userIds.size() == maxReservations) { return false; } userIds.add(user); return true; } public PartnerPromotion(String id) { this.id = id; } static public PartnerPromotion from(String json) { return gson.fromJson(json, PartnerPromotion.class); } public String getId() { return id; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } }
true
bb5fbf73a4680525c6b77ed6d4b57912bfa637f9
Java
kavishwaramruta/Automation
/Basic Corejava/src/oops/abstractions/AbstractClassExample.java
UTF-8
265
3.25
3
[]
no_license
package oops.abstractions; public abstract class AbstractClassExample { public void nonabstractmethod() { System.out.println("I am a non abstract method"); } public abstract void abstractmethod(); { System.out.println("I am a abstract method"); } }
true
8b64e257e7a9a3563c85fbd4aa478de40147afc5
Java
pxson001/facebook-app
/classes6.dex_source_from_JADX/com/facebook/photos/upload/constants/PhotoProcessingConstantsUtils.java
UTF-8
734
1.796875
2
[]
no_license
package com.facebook.photos.upload.constants; import com.facebook.bitmaps.Dimension; /* compiled from: graph_search_v2_spelling_correction_escape */ public class PhotoProcessingConstantsUtils { public static boolean m21272a(Dimension dimension) { int i = 960; int i2; if (dimension.b >= dimension.a && dimension.b > 960) { i2 = (dimension.a * 960) / dimension.b; } else if (dimension.a < dimension.b || dimension.a <= 960) { i = dimension.b; i2 = dimension.a; } else { i = (dimension.b * 960) / dimension.a; i2 = 960; } if (i < 400 || r0 < 150) { return false; } return true; } }
true
c275238c8e03106468a37d570c0324b25ffa9836
Java
openboy-hub/studymanager
/src/main/java/com/graduationproject/studymanager/bean/Life.java
UTF-8
396
1.757813
2
[]
no_license
package com.graduationproject.studymanager.bean; import com.baomidou.mybatisplus.annotation.TableName; import lombok.Data; import java.util.Date; @Data @TableName("life_circle") public class Life { private Integer id; private User user; private String content; private Date make_date; private String mood;//枚举 private Image image; private Video video; }
true
e31f3425b68d1ecee93b28bdac9ce3c30fa51793
Java
BarracudaX/Pithia
/Pithia/src/test/java/com/omada/pithia/model/xrhstes/XrhsthsTest.java
UTF-8
5,208
2.25
2
[]
no_license
package com.omada.pithia.model.xrhstes; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import org.junit.jupiter.params.provider.ValueSource; import java.time.LocalDate; import java.util.stream.Stream; import static org.junit.jupiter.api.Assertions.*; public class XrhsthsTest { @Test @DisplayName("Πρεπει να πεταξει NullPointerException οταν καποιο απο τα ορισματα του δομητη ειναι null.") public void prepeiNaPetakseiNPEOtanKapoioOrismaDomhthEinaiNull(){ assertThrows(NullPointerException.class, () -> { Xrhsths xrhsths = new Xrhsths(null, "epwnumo", LocalDate.now().minusYears(18), "12345678", "kwdikos121", "email@edu.com"); }); assertThrows(NullPointerException.class, () -> { Xrhsths xrhsths = new Xrhsths("onoma", null, LocalDate.now().minusYears(18), "12345678", "kwdikos121", "email@edu.com"); }); assertThrows(NullPointerException.class, () -> { Xrhsths xrhsths = new Xrhsths("onoma", "epwnumo", null, "12345678", "kwdikos121", "email@edu.com"); }); assertThrows(NullPointerException.class, () -> { Xrhsths xrhsths = new Xrhsths("onoma", "epwnumo", LocalDate.now().minusYears(18), null, "kwdikos121", "email@edu.com"); }); assertThrows(NullPointerException.class, () -> { Xrhsths xrhsths = new Xrhsths("onoma", "epwnumo", LocalDate.now().minusYears(18), "12345678", null, "email@edu.com"); }); assertThrows(NullPointerException.class, () -> { Xrhsths xrhsths = new Xrhsths("onoma", "epwnumo", LocalDate.now().minusYears(18), "12345678", "kwdikos121", null); }); } @Test @DisplayName("Πρεπει να πεταξει IllegalArgumentException οταν το ονομα ειναι κενο.") public void prepeiNaPetakseiIAEOtanToOnomaEinaiKeno(){ assertThrows(IllegalArgumentException.class,()->{ Xrhsths xrhsths = new Xrhsths("", "epwnumo", LocalDate.now().minusYears(18), "12345678", "kwdikos121", "email@edu.com"); }); } @Test @DisplayName("Πρεπει να πεταξει IllegalArgumentException οταν το επωνυμο ειναι κενο.") public void prepeiNaPetakseiIAEOtanToEpwnumoEinaiKeno(){ assertThrows(IllegalArgumentException.class,()->{ Xrhsths xrhsths = new Xrhsths("Μαρια", "", LocalDate.now().minusYears(18), "12345678", "kwdikos121", "email@edu.com"); }); } @Test @DisplayName("Πρεπει να πεταξει IllegalArgumentException οταν ο χρηστης ειναι ανηλικος") public void prepeiNaPetakseiIAEOtanOXrhsthsEinaiAnhlikos(){ assertThrows(IllegalArgumentException.class,()->{ Xrhsths xrhsths = new Xrhsths("Μαρια", "Maria", LocalDate.now().minusYears(17), "12345678", "kwdikos121", "email@edu.com"); }); } @ParameterizedTest @DisplayName("Πρεπει να πεταξει IllegalArgumentException οταν το ονομα χρηστη δεν εχει σωστο μηκος.") @MethodSource("getStringMikroterou8Xarakthrwn") public void prepeiNaPetakseiIAEOtanToOnomaXrhsthDenExeiSwstoMhkos(String lathosOnomaXrhsth){ assertThrows(IllegalArgumentException.class,()->{ Xrhsths xrhsths = new Xrhsths("Μαρια", "Maria", LocalDate.now().minusYears(20), lathosOnomaXrhsth, "kwdikos121", "email@edu.com"); }); } @ParameterizedTest @DisplayName("Πρεπει να πεταξει IllegalArgumentException οταν ο κωδικος δεν εχει σωστο μηκος.") @MethodSource("getStringMikroterou8Xarakthrwn") public void prepeiNaPetakseiIAEOtanOKwdikosDenExeiSwstoMhkos(String lathosKwdikos){ assertThrows(IllegalArgumentException.class,()->{ Xrhsths xrhsths = new Xrhsths("Μαρια", "Maria", LocalDate.now().minusYears(20), "onomaXrhsth12", lathosKwdikos, "email@edu.com"); }); } @ParameterizedTest @DisplayName("Πρεπει να πεταξει IllegalArgumentException οταν το εμαιλ δεν ειναι σωστο.") @MethodSource("getLathosEmail") public void prepeiNaPetakseiIAEOtanToEmailDenKaneiMatchToGenikoPatternTouEmail(String lathosEmail){ assertThrows(IllegalArgumentException.class,()->{ Xrhsths xrhsths = new Xrhsths("Μαρια", "Maria", LocalDate.now().minusYears(20), "onomaXrhsth12", "122334124124", lathosEmail); }); } private static Stream<String> getStringMikroterou8Xarakthrwn(){ return Stream.of(" ","7charac", "6chara", "5char", "4cha", "3ch", "2c", "1", ""); } private static Stream<String> getLathosEmail(){ return Stream.of(""," ","@","@mail.ru","gmail.com","gmail.com@onoma122"); } }
true
88b5dfe776f1827c91840750faf764368803bf08
Java
johnagordon83/RosterReview
/src/main/java/com/rosterreview/entity/PlayerPosition.java
UTF-8
3,515
2.90625
3
[]
no_license
package com.rosterreview.entity; import java.io.Serializable; import java.util.Objects; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.Id; import javax.persistence.Table; import org.apache.commons.lang3.builder.RecursiveToStringStyle; import org.apache.commons.lang3.builder.ReflectionToStringBuilder; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; /** * An {@link Entity} defining a football position played by a specific * {@link Player}. */ @Entity @Table(name="player_position") public class PlayerPosition implements Serializable { private static final long serialVersionUID = 1L; @Id @Column(name="player_id") private String playerId; @Id @Column(name="position") @Enumerated(EnumType.STRING) private Position position; /** * A no-argument {@link PlayerPosition} constructor required by Spring. */ PlayerPosition() {} public PlayerPosition(String playerId, Position position) { this.playerId = playerId; this.position = position; } /** * @return the player's unique identifier */ @JsonIgnore public String getPlayerId() { return playerId; } /** * @param playerId the player's unique identifier */ @JsonProperty public void setPlayerId(String playerId) { this.playerId = playerId; } /** * @return the Position played by the player */ public Position getPosition() { return position; } /** * @param position the Position played by the player */ public void setPosition(Position position) { this.position = position; } /** * Determines if this {@link PlayerPosition} is equivalent to the argument. * <p> * The result is <code>true</code> if and only if the argument is a * non-null instance of PlayerPosition that has equivalent values for * the playerId and position fields. * * @param obj The object to compare this team against * @return <code>true</code> if the argument is equal to this * PlayerPosition object, <code>false</code> otherwise */ @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof PlayerPosition)) { return false; } PlayerPosition arg = (PlayerPosition) obj; return this.playerId.equals(arg.getPlayerId()) && this.position.equals(arg.getPosition()); } /** * Uses {@link Objects#hash(Object...)} to calculate a hash code for this * object based on the playerId and position fields. * * @return A hash code for this object. * @see #equals */ @Override public int hashCode() { return Objects.hash(this.playerId, this.position); } /** * Generates a <code>String</code> representation of this {@link PlayerPosition}. * <p> * Given the use of reflection, consider removing or re-implementing for * production grade code. */ @Override public String toString() { return ReflectionToStringBuilder.toString(this, new RecursiveToStringStyle()); } }
true
23b67723d8e2784dbd3516f10c503c3497fd4ba3
Java
ao3452/ow_on_android
/overlayweaver_for_android_core/src/ow/SessionID/MessageInfo.java
EUC-JP
2,592
2.4375
2
[]
no_license
package ow.SessionID; import java.io.Serializable; import javax.crypto.SecretKey; import ow.id.ID; import ow.messaging.InetMessagingAddress; import ow.messaging.MessagingAddress; public class MessageInfo implements Serializable { /** * SessionIDбդƥơ֥¸(ϰʲ) */ private static final long serialVersionUID = -2781434384383204620L; private MessagingAddress Address;//ΰǤIPɥ쥹 private boolean headderflag;//إå椹Ρɤɤ private boolean receiverflag;//Ԥɤ private boolean senderflag; private SecretKey s_rkey ;//椹붦̸() private SecretKey s_hkey ;//椹붦̸(إå) private ID nextID;//ΰǤID(IPɥ쥹褬ʤäϤǺƸ) private SessionID sid; private int direction; private int target_area; public int getTarget_area() { return target_area; } public void setTarget_area(int targetArea) { target_area = targetArea; } public MessageInfo()// { this.Address=null; this.headderflag=false; this.receiverflag=false; this.senderflag=false; this.s_hkey=null; this.s_rkey=null; this.nextID=null; this.sid = null; this.direction = -1; } public int getDirection() { return direction; } public void setDirection(int direction) { this.direction = direction; } public void SetAddress(MessagingAddress addr){ this.Address = addr; return; } public void SetHeadderflag(boolean flag ){ this.headderflag = flag; return; } public void SetReceiverflag(boolean flag){ this.receiverflag = flag; return; } public void SetSenderflag(boolean flag){ this.senderflag = flag; return; } public void SetSecretRKey(SecretKey key){ this.s_rkey = key; return; } public void SetSecretHKey(SecretKey key){ this.s_hkey = key; return; } public void SetNextID(ID id){ this.nextID=id; return; } public void SetSessionID(SessionID id){ this.sid=id; return; } /// public MessagingAddress getAddress(){ return this.Address; } public boolean getHeadderflag(){ return this.headderflag; } public boolean getReceiverflag(){ return this.receiverflag; } public boolean getSenderflag(){ return this.senderflag; } public SecretKey getSecretRKey(){ return this.s_rkey; } public SecretKey getSecretHKey(){ return this.s_hkey; } public ID getNextID(){ return this.nextID; } public SessionID getSessionID(){ return this.sid; } }
true
f1ff7129caced897f352c89dce029e44a6a13c40
Java
novoda/github-reports
/reports-stats/src/main/java/com/novoda/github/reports/stats/handler/FloatTaskBasedCommandHandler.java
UTF-8
1,833
2.171875
2
[]
no_license
package com.novoda.github.reports.stats.handler; import com.novoda.floatschedule.FloatServiceClient; import com.novoda.github.reports.data.DataLayerException; import com.novoda.github.reports.data.EventDataLayer; import com.novoda.github.reports.data.model.Stats; import com.novoda.github.reports.data.model.UserAssignments; import com.novoda.github.reports.stats.command.FloatTaskBasedOptions; import java.util.Date; import java.util.List; import java.util.Map; abstract class FloatTaskBasedCommandHandler<S extends Stats, O extends FloatTaskBasedOptions> implements CommandHandler<S, O> { private final EventDataLayer eventDataLayer; private final FloatServiceClient floatServiceClient; FloatTaskBasedCommandHandler(EventDataLayer eventDataLayer, FloatServiceClient floatServiceClient) { this.eventDataLayer = eventDataLayer; this.floatServiceClient = floatServiceClient; } @Override public S handle(O options) { Map<String, List<UserAssignments>> usersAssignments = floatServiceClient.getGithubUsersAssignmentsInDateRange( options.getUsers(), options.getFrom(), options.getTo(), options.getTimezone() ); try { return handleUserAssignments(options.getFrom(), options.getTo(), usersAssignments); } catch (DataLayerException e) { e.printStackTrace(); } return null; } protected abstract S handleUserAssignments(Date from, Date to, Map<String, List<UserAssignments>> usersAssignments) throws DataLayerException; EventDataLayer getEventDataLayer() { return eventDataLayer; } }
true
8e672327d70e4837c223a77aa55b00b223df1243
Java
bernardoms/spark-kafka-data-pipeline
/spring-kafka/src/main/java/com/bernardoms/miniclip/service/EventProcessor.java
UTF-8
221
1.703125
2
[]
no_license
package com.bernardoms.miniclip.service; import com.fasterxml.jackson.core.JsonProcessingException; public interface EventProcessor { String type(); void processEvent(String event) throws JsonProcessingException; }
true
d39e201d79b433ea9c9476915ee721c4fcf485eb
Java
subrosa/subrosa
/apps/api/src/main/java/com/subrosagames/subrosa/domain/player/PlayerFactoryImpl.java
UTF-8
5,893
2.09375
2
[ "MIT" ]
permissive
package com.subrosagames.subrosa.domain.player; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.PageRequest; import org.springframework.stereotype.Component; import com.subrosagames.subrosa.api.dto.PlayerDescriptor; import com.subrosagames.subrosa.api.dto.TeamDescriptor; import com.subrosagames.subrosa.domain.BaseDomainObjectFactory; import com.subrosagames.subrosa.domain.account.Account; import com.subrosagames.subrosa.domain.account.AccountFactory; import com.subrosagames.subrosa.domain.account.AddressNotFoundException; import com.subrosagames.subrosa.domain.game.EnrollmentField; import com.subrosagames.subrosa.domain.game.Game; import com.subrosagames.subrosa.domain.image.ImageNotFoundException; import com.subrosagames.subrosa.domain.player.persistence.PlayerAttribute; import com.subrosagames.subrosa.domain.player.persistence.PlayerAttributePk; import com.subrosagames.subrosa.domain.player.persistence.TeamEntity; /** * Factory for game player objects. */ @Component public class PlayerFactoryImpl extends BaseDomainObjectFactory implements PlayerFactory { private static final Logger LOG = LoggerFactory.getLogger(PlayerFactoryImpl.class); @Autowired private PlayerRepository playerRepository; @Autowired private TeamRepository teamRepository; @Autowired private AccountFactory accountFactory; @Override public Player createPlayerForGame(Game game, Account account, PlayerDescriptor playerDescriptor) throws PlayerValidationException, AddressNotFoundException, ImageNotFoundException { TeamEntity teamEntity = new TeamEntity(); teamEntity.setGameId(game.getId()); teamEntity.setName(playerDescriptor.getPlayer().getName()); Player player = new Player(); player.setAccount(account); player.setGame(game); player.setPlayerProfile(playerDescriptor.getPlayer()); player.setTeam(teamEntity); player.setGameRole(GameRole.PLAYER); player.setKillCode(PlayerCodeGenerator.generate()); processPlayerAttributes(player, playerDescriptor); player.assertValid(); teamRepository.save(teamEntity); playerRepository.save(player); injectDependencies(player); return player; } @Override public void processPlayerAttributes(Player player, PlayerDescriptor playerDescriptor) throws ImageNotFoundException, AddressNotFoundException { LOG.debug("Ingesting player attributes: {}", playerDescriptor.getAttributes()); for (EnrollmentField field : playerDescriptor.getEnrollmentFields()) { if (!playerDescriptor.getAttributes().containsKey(field.getFieldId())) { LOG.debug("Could not find enrollment field {} in supplied attributes: {}", field.getFieldId()); continue; } PlayerAttribute playerAttribute = player.getAttributes().get(field.getFieldId()); if (playerAttribute == null) { playerAttribute = field.getType().newForAccount(player.getAccount(), playerDescriptor.getAttribute(field.getFieldId())); LOG.debug("Creating new player attribute ({}) {} => {} for player {}", field.getType().name(), field.getFieldId(), playerAttribute.getValueRef(), player.getId()); playerAttribute.setPrimaryKey(new PlayerAttributePk(player.getId(), field.getFieldId())); playerAttribute.setPlayer(player); playerAttribute.setType(field.getType()); player.setAttribute(field.getFieldId(), playerAttribute); } else { LOG.debug("Updating player attribute ({}) {} => {} for player {}", field.getType().name(), field.getFieldId(), playerAttribute.getValueRef(), player.getId()); field.getType().updateForAccount(player.getAccount(), playerDescriptor.getAttribute(field.getFieldId()), playerAttribute); } } } private Player injectDependencies(Player player) { player.setPlayerFactory(this); // TODO got to be a better way of doing this... accountFactory.injectDependencies(player.getAccount()); return player; } @Override public Player getPlayer(Game game, Integer playerId) throws PlayerNotFoundException { return playerRepository.findByGameAndId(game, playerId) .map(this::injectDependencies) .orElseThrow(() -> new PlayerNotFoundException("No player " + playerId + " in game " + game.getId())); } @Override public List<? extends Player> getPlayers(Game game) { return playerRepository.findByGame(game); } @Override public List<? extends Player> getPlayers(Game game, Integer limit, Integer offset) { int pageNum = offset > 0 && limit > 0 ? offset / limit : 0; return playerRepository.findByGame(game, new PageRequest(pageNum, limit)).getContent(); } @Override public Team createTeamForGame(Game game, TeamDescriptor teamDescriptor) { TeamEntity teamEntity = new TeamEntity(); teamEntity.setGameId(game.getId()); copyProperties(teamDescriptor, teamEntity); teamEntity = teamRepository.save(teamEntity); return teamEntity; } @Override public Team getTeam(Game game, Integer teamId) throws TeamNotFoundException { return teamRepository.findByGameAndId(game, teamId) // .map(this::injectDependencies) .orElseThrow(() -> new TeamNotFoundException("No team " + teamId + " in game " + game.getId())); } @Override public List<? extends Team> getTeams(Game game) { return teamRepository.findByGame(game); } }
true
e3f98deb58839d998fa2dca99abacead60dd003f
Java
hapcaper/race
/src/main/java/cn/springmvc/controller/StudentController.java
UTF-8
9,908
2.21875
2
[]
no_license
package cn.springmvc.controller; import cn.springmvc.constance.Constance; import cn.springmvc.dao.StuProDao; import cn.springmvc.entry.*; import cn.springmvc.entry.result.ResultDO; import cn.springmvc.service.*; import cn.springmvc.util.UploadUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpRequest; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import javax.servlet.MultipartConfigElement; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; /** * Created by 李自豪 on 2017/6/14. */ @Controller @RequestMapping("/student") public class StudentController { @Autowired StudentService studentService; @Autowired ProjectService projectService; @Autowired RaceService raceService; @Autowired TermService termService; @Autowired TeacherService teacherService; // @RequestMapping(value = "/toStudentLogin") // public String toStudentLogin(HttpSession session, HttpServletRequest request) { // // return "student/studentLogin"; // } @RequestMapping(value = "/toIndex") public String toIndex() { return "student/index"; } // @RequestMapping(value = "/studentLogin") // public String studentLogin(@RequestParam("stuNumber") String stuNumber, @RequestParam("password") String password, HttpSession session, HttpServletRequest request, Model model) { // List<Student> studentList = studentService.findByStuNumberAndPassWord(stuNumber, password); // if (studentList.size() <= 0) { // model.addAttribute("errorMsg", "用户名或密码错误"); // return "student/studentLogin"; // } // // ResultDO<List<Term>> termresult = termService.getMaxTerm(); // Term currentTerm = termresult.getResult().get(0); // Student student = studentList.get(0); // session.setAttribute("student", student); // // return "student/studentIndex"; // } @RequestMapping(value = "/toSelectRace") public String toSelectRace(Model model) { model.addAttribute("menuSelected1", Constance.RACE_MANAGE); model.addAttribute("menuSelected2", Constance.APPLY_RACE); return "student/selectRace"; } @RequestMapping(value = "/toAddProject") public String toAddProject(Model model) { model.addAttribute("menuSelected1", Constance.RACE_MANAGE); model.addAttribute("menuSelected2", Constance.ADD_PROJECT); List<Teacher> teacherList = teacherService.findByStatus(1); List<Student> studentList = studentService.findByStatus(1); model.addAttribute("studentList", studentList); model.addAttribute("teacherList", teacherList); return "student/addProject"; } @RequestMapping(value = "/stuAddProject") public String stuAddProject(HttpServletRequest request, Model model, @RequestParam("proname") String proname, HttpSession session, @RequestParam("document") MultipartFile document, @RequestParam("personsId") Integer[] personsId, @RequestParam("tId") Integer tId, @RequestParam("description") String description) { model.addAttribute("menuSelected1", Constance.RACE_MANAGE); model.addAttribute("menuSelected2", Constance.ADD_PROJECT); List<Student> stuList = new ArrayList<Student>(); List<StuPro> stuProList = new ArrayList<StuPro>(); Project project = new Project(); int flag = 1; //判定是否要添加数据库 if (proname != null && !projectService.getProjectByProname(proname).isSuccess()) { project.setProname(proname); } if (document != null) { String docpath = UploadUtil.uploadFile(document, request); project.setDocument(docpath); } ///////////////////// if (personsId != null) { for (Integer pid : personsId) { Student stu = studentService.findById(pid); stuList.add(stu); project.setPersons(stu.getStuName() + ","); System.out.println("pid : " + pid); } } //////// if (tId != null) { System.out.println(tId); } if (description != null) { project.setDescription(description); } // int sign = projectService.insertProject(project); // if(sign!=0){ //添加成功 // // } return "student/index"; } @RequestMapping(value = "/toMyProjectList") public String toMyProjectList(Model model, HttpSession session) { model.addAttribute("menuSelected1", Constance.RACE_MANAGE); model.addAttribute("menuSelected2", Constance.MY_PROJECT_LIST); Student student = (Student) session.getAttribute("student"); List<Teacher> teacherList = new ArrayList<Teacher>(); List<Project> projectList = projectService.findByStuid(student.getId()); for (Project aProjectList : projectList) { Teacher t = teacherService.findByTid(aProjectList.getTid()).get(0); teacherList.add(t); } model.addAttribute("projectlist", projectList); model.addAttribute("teacherList", teacherList); return "student/myProjectList"; } @RequestMapping(value = "/toSoftDesignSelectProject") public String toSoftDesignSelectProject(Model model, HttpServletRequest request, HttpSession session) { model.addAttribute("menuSelected1", Constance.RACE_MANAGE); model.addAttribute("menuSelected2", Constance.APPLY_RACE); Student student = (Student) session.getAttribute("student"); Term term = (Term) session.getAttribute("term"); Race race = new Race(); race.setProname("软件学院软件设计大赛"); race.setKind(9); race.setTerm(term.getTerm()); List<Project> projectList = projectService.findByStuid(student.getId()); model.addAttribute("projectlist", projectList); request.setAttribute("race", race); return "student/softDesignSelectProject"; } @RequestMapping(value = "/toMyRaceList") public String toMyRaceList(Model model, HttpServletRequest request, HttpSession session) { model.addAttribute("menuSelected1", Constance.RACE_MANAGE); model.addAttribute("menuSelected2", Constance.MY_RACE_LIST); Student student = (Student) session.getAttribute("student"); List<Race> raceList = raceService.findByStuId(student.getId()); ResultDO<List<Term>> termresult = termService.getAllTerm(); model.addAttribute("raceList", raceList); request.setAttribute("termlist", termresult.getResult()); return "student/myRaceList"; } @RequestMapping(value = "/toStudentDetail") public String toStudentDetail(Model model, HttpSession session) { model.addAttribute("menuSelected1", Constance.PERSONAL_CENTER); model.addAttribute("menuSelected2", Constance.PERSONAL_MYDATA); Student student = (Student) session.getAttribute("student"); model.addAttribute("stu", student); return "student/studentDetail"; } @RequestMapping(value = "/toUpdatePassword") public String toUpdatePassword(Model model) { model.addAttribute("menuSelected1", Constance.PERSONAL_CENTER); model.addAttribute("menuSelected2", Constance.PERSONAL_UPDATEPASSWD); return "student/updatePassword"; } @RequestMapping(value = "/updatePassword") public String updatePassword(HttpSession session,Model model, @RequestParam("oldPasswd") String oldPasswd, @RequestParam("newPasswd") String newPasswd) { model.addAttribute("menuSelected1", Constance.PERSONAL_CENTER); model.addAttribute("menuSelected2", Constance.PERSONAL_UPDATEPASSWD); int sign = 0 ; //是否可以修改密码的标志 默认0与原密码不一致 不可以改 Student student = (Student) session.getAttribute("student"); if (student.getPassWord().equals(oldPasswd)){ student.setPassWord(newPasswd); studentService.update(student); sign = 1 ; model.addAttribute("sign",sign); session.setAttribute("student",student); return "student/updatePassword"; }else{ model.addAttribute("sign",sign); return "student/updatePassword"; } } @RequestMapping(value = "/toRaceDetail") public String toRaceDetail(Model model, @RequestParam("rid") Integer rid) { model.addAttribute("menuSelected1", Constance.RACE_MANAGE); model.addAttribute("menuSelected2", Constance.MY_RACE_LIST); System.out.println("rid --" + rid); Race race = raceService.getRaceById(rid).getResult().get(0); model.addAttribute("race", race); return "student/raceDetail"; } @RequestMapping(value = "/addProject") public String addProject(Model model, HttpServletRequest request, HttpSession session) { return "redirect:/student/toMyProjectList.do"; } @RequestMapping(value = "/toOtherRace") public String toOtherRace(Model model){ model.addAttribute("menuSelected1", Constance.RACE_MANAGE); model.addAttribute("menuSelected2", Constance.APPLY_RACE); return "student/otherRace"; } }
true
7cc64b3878098035d92435e700173c6cd7402466
Java
yumei2018/GEI-Projects
/mapLite/src/java/gov/ca/water/contours/GridPoint.java
UTF-8
9,218
2.828125
3
[]
no_license
package gov.ca.water.contours; import com.vividsolutions.jts.geom.Coordinate; import gov.ca.water.contours.intervals.ContourIntervals; import gov.ca.water.shapelite.Coord; import gov.ca.water.utils.MissingVertexException; import gov.ca.water.common.io.DataEntry; /** * An extention for {@linkplain Coord} to add properties associated with a Contour * GridPoint. * @author J.G. "Koos" Prins, D.Eng. PE. */ public class GridPoint extends Coordinate { //<editor-fold defaultstate="collapsed" desc="Public Static Constants"> /** * Public constant for the low undefined contour index [{@value}] */ public static final int LO_UNDEFNED = -9999; /** * Public constant for the High undefined contour index [{@value}] */ public static final int HI_UNDEFNED = 9999; //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Private Properties"> /** * The grid points hiContour index */ private Integer hiIndex; /** * The grid points loContour index */ private Integer loIndex; // /** // * A Flag stating whether this point is outside the area-of-interest // * (default = null|false) // */ // private Boolean outsideArea; //</editor-fold> // <editor-fold defaultstate="collapsed" desc="Constructor"> /** * Public Constructor */ public GridPoint() { super(); // this.outsideArea = null; this.reset(); } // /** // * Public Constructor from a Coordinate // * @param other a other Coordinate // * @param outsideArea true if outside area (can be null|false). // */ // public GridPoint(Coordinate other, Boolean outsideArea) { // super(other); // this.outsideArea = outsideArea; // this.reset(); // } /** * Public Constructor from a Coordinate - it reset the z-value and the contour indices. * @param other a other GridPoint */ public GridPoint(Coordinate other) { super(other); // this.outsideArea = (other == null)? null: other.outsideArea; this.reset(); } // // /** // * Public Constructor with x-, y-, z-coordinates // * @param x the x-coordinate // * @param y the y-coordinate // * @param outsideArea true if outside area (can be null|false). // */ // public GridPoint(double x, double y, Boolean outsideArea) { // super(x, y); // // this.outsideArea = outsideArea; // this.reset(); // } // </editor-fold> //<editor-fold defaultstate="collapsed" desc="Public Methods"> /** * Get this GridPoint cloned as a Coordinate * @return new Coordinate(this) */ public Coordinate asCoord() { return new Coordinate(this); } /** * Call to reset the the z-value (NaN) and the contour indices */ public final void reset() { this.setOrdinate(Coordinate.Z, Double.NaN); this.hiIndex = null; this.loIndex = null; } // /** // * Get whether this point is outside the Area-of-Interest // * @return true if outside; false inside // */ // public boolean isOutsideArea() { // return ((this.outsideArea != null) && (this.outsideArea)); // } /** * Get the Low Contour Index * @return the assigned value; {@linkplain GridPoint.LO_UNDEFNED} if undefined. */ public int getLoIndex() { return (this.loIndex == null)? GridPoint.LO_UNDEFNED: this.loIndex; } /** * Get the High Contour Index * @return the assigned value; {@linkplain GridPoint.HI_UNDEFNED} if undefined. */ public int getHiIndex() { return (this.hiIndex == null)? GridPoint.HI_UNDEFNED: this.hiIndex; } /** * Get whether this point is on the specified contour * @param contourIdx the index of the contour * @return true if both indices are assigned and equal to the contourIdx */ public boolean isOnContour(int contourIdx) { return ((this.hiIndex != null) && (this.hiIndex == contourIdx) && (this.loIndex != null) && (this.loIndex == contourIdx)); } /** * Get whether this point is below the specified contour * @param contourIdx the index of the contour * @return true if this.loIndex is defined and (this.loIndex &le; contourIdx) */ public boolean isBelowContour(int contourIdx) { return ((this.loIndex != null) && (this.loIndex < contourIdx)); } /** * Get whether this point is above the specified contour * @param contourIdx the index of the contour * @return true if this.loIndex is defined and (this.loIndex &gt; contourIdx) */ public boolean isAboveContour(int contourIdx) { return ((this.loIndex != null) && (this.loIndex > contourIdx)); } /** * Get whether this point is above the specified contour * @param contourIdx the index of the contour * @return true if this.loIndex is defined and (this.loIndex &ge; contourIdx) */ public boolean isOnOrAboveContour(int contourIdx) { return ((this.loIndex != null) && (this.loIndex >= contourIdx)); } /** * Get whether this point is between the two specified contours. * @param loIndex the low index * @param hiIndex the high index * @return true if this point is above the loIdx and below the low index. It returns * false if loIdx > hiIndex */ public boolean inInterval(int loIndex) { return ((this.loIndex != null) && (this.loIndex == loIndex)); } /** * Get whether the GridPoint's X-Y coordinates are not defined. * @return true if this.X or this.Y = NaN */ public boolean isEmpty() { return ((Double.isNaN(this.getX())) || (Double.isNaN(this.getZ()))); } /** * Get the Coordinate's X-ordinate (default=NaN) * @return return the assigned value */ public double getX() { return this.getOrdinate(Coordinate.X); } /** * Get the Coordinate's Y-ordinate (default=NaN) * @return return the assigned value */ public double getY() { return this.getOrdinate(Coordinate.Y); } /** * Get whether the GridPoint's Z-Value is set * @return true if this.z != NaN. */ public boolean hasZ() { return (!Double.isNaN(this.getOrdinate(Coordinate.Z))); } /** * Get the Coordinate's Z-ordinate (default=NaN) * @return return the assigned value */ public double getZ() { return this.getOrdinate(Coordinate.Z); } /** * <p>Called to initiate the GripPoint's Z-Value and its Low and High Contour Indices. * It resolve the contour indices as follows:</p><ul> * <li><b>If (the z-value &lt; contourLow):</b> - * this.hiIndex=0; this.loIndex=undefined</li> * <li><b>If (the z-value &gt; (contourLow + (numIntervals*contourDz)):</b> - * this.hiIndex=undefined; this.loIndex=numIntervals</li> * <li><b>Else:</b> - locate the Index whether (zValue &ge (contourLow + * (Index*contourDz)) and set this.loIndex=Index. <p> * if (zValue = (contourLow + (Index*contourDz)) set this.hiIndex = Index else * this.hiIndex = (Index + 1).</p></li> * </ul> * @param zValue the point's new z-Value * @param contours the Contour Interval definition. * @throws MissingVertexException if the z-Value is undefined (NaN) * @throws IllegalArgumentException is contours is undefined or empty */ public void setZ(double zValue, ContourIntervals contours) throws MissingVertexException { this.reset(); if ((contours == null) || (contours.isEmpty())) { throw new IllegalArgumentException("The Contour Interval Definition is unassigned" + " or Empty."); } if (Double.isNaN(zValue)) { throw new MissingVertexException("The GridPoint's Z-Value is invalid (NaN)."); } this.setOrdinate(Coordinate.Z, zValue); /** * Set the Default number intervals to 10 is undefined. */ int numContours = contours.getNumContours(); double contourLow = contours.getLoValue(); if (DataEntry.isLT(zValue, contourLow)) { this.hiIndex = 0; } else if (DataEntry.isGT(zValue, contours.getHiValue())) { this.loIndex = numContours-1; } else { for (int iIdx = 0; iIdx < numContours; iIdx++) { contourLow = contours.getContour(iIdx); if (DataEntry.isGE(zValue, contourLow)) { this.loIndex = iIdx; if (DataEntry.isEq(zValue, contourLow)) { this.hiIndex = iIdx; } else if (iIdx < numContours) { this.hiIndex = iIdx + 1; } } else { break; } } } } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Object Overrids"> /** * {@inheritDoc} * <p>OVERRIDE: Get the super Coordinate String and add "; Indices[hi=??;lo=??](; * Outside)". The "Outside" will only be added if this.isOutsideAreas=true. If the * hi- or lo-Indices are not assigned it adds "NA". Undefined indices is set to NaN, * </p> */ @Override public String toString() { String result = super.toString(); result += "; Indices[hi=" + ((this.hiIndex == null)? "NA": this.hiIndex.toString()); result += "; loi=" + ((this.loIndex == null)? "NA": this.loIndex.toString()) + "]"; // if (this.isOutsideArea()) { // result += "; Outside"; // } return result; } //</editor-fold> }
true
d919db1bd396526f1e861952aa2da5a84e9986f8
Java
tansudasli/java-fundamentals
/src/test/java/core/collections/MapX.java
UTF-8
2,642
3.5625
4
[]
no_license
package core.collections; import java.util.*; import static java.util.Arrays.stream; public class MapX { /* * Map (k, v) * * - HashMap: unsorted, unordered, allows NULL value. * - HashTable: synced, thread-safe, unsorted, unordered * - LinkedHashMap: insert-order preserved, (so insertion, deletion a bit slower than HashMap) * - TreeMap: sorted (default natural order) * * */ public static void main(String[] args) { Map<String, Integer> map = Map.of("a01234h", 2, "e5YH778", 4, "ha782",1, "b83h8ihs", 3); Map<String, Integer> hashMap = new HashMap<>(map); System.out.println(map.get("01234h")); System.out.println(map.size()); System.out.println(map); map.forEach((k,v) -> System.out.println(k + ":" + v)); System.out.println(map.containsValue(4)); //Map.of is immutable, so below ain't work // Integer x = map.computeIfPresent("01234h", (k, v) -> v * v) // System.out.println(x); System.out.println(hashMap); hashMap.put("abc567", 67); hashMap.computeIfPresent("01234h", (k, v) -> v * v * v); System.out.println(hashMap); //insert-order preserved LinkedHashMap<String, Integer> linkedHashMap = new LinkedHashMap<>(map); System.out.println(linkedHashMap); //sorted-order TreeMap<String, Integer> treeMap = new TreeMap<>(map); TreeMap<String, Integer> treeMap2 = new TreeMap<>(Comparator.reverseOrder()); //sorts by key ! TreeMap<String, Integer> treeMap3 = new TreeMap<>(Comparator.comparing(String::length).reversed()); treeMap2.putAll(map); treeMap3.putAll(map); System.out.println("treemap: " + treeMap); System.out.println(treeMap2); System.out.println(treeMap3); //some methods specific to maps (comes w/ navigable interface) System.out.println(treeMap.higherKey("e5YH778")); System.out.println(treeMap.ceilingKey("e5YH778")); String line = "This is not me, Me is not me"; Map<Character, Integer> occurrences = new HashMap<>(); for (Character ch: line.toLowerCase(Locale.ROOT).toCharArray()) { var v = occurrences.containsKey(ch) ? occurrences.get(ch) + 1 : 1; occurrences.put(ch, v); // if (occurrences.containsKey(ch)) { // occurrences.put(ch, occurrences.get(ch) + 1); // } else { // occurrences.put(ch, 1); // } } System.out.println(occurrences); } }
true
599182dd5c9618a302575c62b834fc87974ced0a
Java
Padepokan79/BootCampG7
/Tugas/ExamBootcamp/QuizKhairil/QuizKhairil3.java
UTF-8
6,798
3.0625
3
[]
no_license
/* Program : Quiz Creator : Khairil Created At : 29 Mei 2018 09:45 AM Updated By : Update Date : */ import java.util.Scanner; class QuizKhairil3 { public static void main(String[] args) { Scanner inputD = new Scanner(System.in); int jumKeluargaInt, lamaTabunganInt, duit, maxJan, maxFeb, maxMar, maxApr, maxMei, maxJun, maxJul, maxAgus, maxSept, maxOkt, maxNov, maxDes, minKel, maxKel, minLama, maxLama, totalDuit, maxBulan, totalDuitSemuaKeluargaJan, totalDuitSemuaKeluargaFeb, totalDuitSemuaKeluargaMar, totalDuitSemuaKeluargaApr, totalDuitSemuaKeluargaMei, totalDuitSemuaKeluargaJun, totalDuitSemuaKeluargaJul, totalDuitSemuaKeluargaAgus, totalDuitSemuaKeluargaSep, totalDuitSemuaKeluargaOkt, totalDuitSemuaKeluargaNov, totalDuitSemuaKeluargaDes, totalDuitSemuaKeluarga, total; String jumKeluarga, lamaTabungan; Boolean adjustment = false; minKel = 2; maxKel = 6; minLama = 1; maxLama = 12; maxJan = maxMar = maxMei = maxJul = maxAgus = maxOkt = maxDes = 31; maxFeb = 28; maxApr = maxJun = maxSept = maxNov = 30; duit = 32000; totalDuit = 0; maxBulan = 12; total = 0; jumKeluargaInt = lamaTabunganInt = 0; totalDuitSemuaKeluargaJan = 0; totalDuitSemuaKeluargaFeb = 0; totalDuitSemuaKeluargaMar = 0; totalDuitSemuaKeluargaApr = 0; totalDuitSemuaKeluargaMei = 0; totalDuitSemuaKeluargaJun = 0; totalDuitSemuaKeluargaJul = 0; totalDuitSemuaKeluargaAgus = 0; totalDuitSemuaKeluargaSep = 0; totalDuitSemuaKeluargaOkt = 0; totalDuitSemuaKeluargaNov = 0; totalDuitSemuaKeluargaDes = 0; totalDuitSemuaKeluarga = 0; while(adjustment == false) { System.out.print("Masukan Jumlah keluarga : "); jumKeluarga = inputD.next(); if(jumKeluarga.matches("[0-9-]+")) { jumKeluargaInt = Integer.parseInt(jumKeluarga); if(jumKeluargaInt < minKel) { System.out.println("Maaf, Jumlah keluarga Tidak boleh kurang dari 2."); System.out.println("Silahkan input kembali."); adjustment = false; } else if(jumKeluargaInt > maxKel) { System.out.println("Maaf, Jumlah keluarga Tidak boleh lebih dari 6."); System.out.println("Silahkan input kembali."); adjustment = false; } else { adjustment = true; } } else { System.out.println("Maaf, input yang diterima hanya berupa angka."); System.out.println("Silahkan input kembali."); adjustment = false; } System.out.print("Masukan Lama Tabungan : "); lamaTabungan = inputD.next(); if(lamaTabungan.matches("[0-9-]+")) { lamaTabunganInt = Integer.parseInt(lamaTabungan); if(lamaTabunganInt < minLama) { System.out.println("Maaf, Jumlah keluarga Tidak boleh kurang dari 2."); System.out.println("Silahkan input kembali."); adjustment = false; } else if(lamaTabunganInt > maxLama) { System.out.println("Maaf, Jumlah keluarga Tidak boleh lebih dari 6."); System.out.println("Silahkan input kembali."); adjustment = false; } else { adjustment = true; } } else { System.out.println("Maaf, input yang diterima hanya berupa angka."); System.out.println("Silahkan input kembali."); adjustment = false; } } if(lamaTabunganInt == 1) { for(int index1 = 1; index1 <= maxJan; index1++) { duit-=1000; totalDuit = totalDuit + duit; totalDuitSemuaKeluargaJan = totalDuit * jumKeluargaInt; } System.out.println("Total Tabungan Bulan Januari " + totalDuitSemuaKeluargaJan); } if(lamaTabunganInt <= 2) { for(int index1 = 1; index1 <= maxFeb; index1++) { duit-=1000; totalDuit = totalDuit + duit; totalDuitSemuaKeluargaFeb = totalDuit * jumKeluargaInt; } System.out.println("Total Tabungan Bulan Februari " + totalDuitSemuaKeluargaFeb); } if(lamaTabunganInt <= 3) { for(int index1 = 1; index1 <= maxMar; index1++) { duit-=1000; totalDuit = totalDuit + duit; totalDuitSemuaKeluargaMar = totalDuit * jumKeluargaInt; } System.out.println("Total Tabungan Bulan Maret " + totalDuitSemuaKeluargaMar); } if(lamaTabunganInt <= 4) { for(int index1 = 1; index1 <= maxApr; index1++) { duit-=1000; totalDuit = totalDuit + duit; totalDuitSemuaKeluargaApr = totalDuit * jumKeluargaInt; } System.out.println("Total Tabungan Bulan April " + totalDuitSemuaKeluargaApr); } if(lamaTabunganInt <= 5) { for(int index1 = 1; index1 <= maxMei; index1++) { duit-=1000; totalDuit = totalDuit + duit; totalDuitSemuaKeluargaMei = totalDuit * jumKeluargaInt; } System.out.println("Total Tabungan Bulan Mei " + totalDuitSemuaKeluargaMei); } if(lamaTabunganInt <= 6) { for(int index1 = 1; index1 <= maxJun; index1++) { duit-=1000; totalDuit = totalDuit + duit; totalDuitSemuaKeluargaJun = totalDuit * jumKeluargaInt; } System.out.println("Total Tabungan Bulan Juni " + totalDuitSemuaKeluargaJun); } if(lamaTabunganInt <= 7) { for(int index1 = 1; index1 <= maxJul; index1++) { duit-=1000; totalDuit = totalDuit + duit; totalDuitSemuaKeluargaJul = totalDuit * jumKeluargaInt; } System.out.println("Total Tabungan Bulan Juli " + totalDuitSemuaKeluargaJul); } if(lamaTabunganInt <= 8) { for(int index1 = 1; index1 <= maxAgus; index1++) { duit-=1000; totalDuit = totalDuit + duit; totalDuitSemuaKeluargaAgus = totalDuit * jumKeluargaInt; } System.out.println("Total Tabungan Bulan Agustus " + totalDuitSemuaKeluargaAgus); } if(lamaTabunganInt <= 9) { for(int index1 = 1; index1 <= maxSept; index1++) { duit-=1000; totalDuit = totalDuit + duit; totalDuitSemuaKeluargaSep = totalDuit * jumKeluargaInt; } System.out.println("Total Tabungan Bulan September " + totalDuitSemuaKeluargaSep); } if(lamaTabunganInt <= 10) { for(int index1 = 1; index1 <= maxOkt; index1++) { duit-=1000; totalDuit = totalDuit + duit; totalDuitSemuaKeluargaOkt = totalDuit * jumKeluargaInt; } System.out.println("Total Tabungan Bulan Oktober " + totalDuitSemuaKeluargaOkt); } if(lamaTabunganInt <= 11) { for(int index1 = 1; index1 <= maxNov; index1++) { duit-=1000; totalDuit = totalDuit + duit; totalDuitSemuaKeluargaNov = totalDuit * jumKeluargaInt; } System.out.println("Total Tabungan Bulan November " + totalDuitSemuaKeluargaNov); } if(lamaTabunganInt <= 12) { for(int index1 = 1; index1 <= maxDes; index1++) { duit-=1000; totalDuit = totalDuit + duit; totalDuitSemuaKeluargaDes = totalDuit * jumKeluargaInt; } System.out.println("Total Tabungan Bulan Desember " + totalDuitSemuaKeluargaDes); } System.out.println("Total Tabungan Selama " + lamaTabunganInt + " Bulan dengan " + jumKeluargaInt + " anggota keluarga adalah " + totalDuitSemuaKeluarga); } }
true
0031ed8547a18af16589aea029cb26b1b99a79b9
Java
Elter71/Android-Restaurant-Reservations-App
/app/src/main/java/pl/elter/mvp/Main/IMainModel.java
UTF-8
164
1.773438
2
[]
no_license
package pl.elter.mvp.Main; /** * Created by Rodzice on 02.02.2017. */ public interface IMainModel { void saveData(); String readData(); }
true
10882c81ccf7a3cefe2bbad2010a793f177cf46a
Java
171250018/IoT_work
/src/main/java/com/seciii/oasis/po/Parameter.java
UTF-8
1,084
2.140625
2
[]
no_license
package com.seciii.oasis.po; public class Parameter { private int dpid; private String name; private String dataType; private String example; private int isNess; private String description; public int getDpid() { return dpid; } public void setDpid(int dpid) { this.dpid = dpid; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDataType() { return dataType; } public void setDataType(String dataType) { this.dataType = dataType; } public String getExample() { return example; } public void setExample(String example) { this.example = example; } public int getIsNess() { return isNess; } public void setIsNess(int isNess) { this.isNess = isNess; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } }
true
d40d68f5c08d7eabcfad9aee3149c29c2423dd3a
Java
jfseb/csv2parquet2orc
/src/main/java/jfseb/csv2parquet/convert/utils/CSV2ParquetTimestampUtils.java
UTF-8
11,152
2.296875
2
[ "Apache-2.0" ]
permissive
package jfseb.csv2parquet.convert.utils; import java.io.Console; import java.sql.Date; import java.text.DateFormat; import java.text.ParseException; import java.text.ParsePosition; import java.text.SimpleDateFormat; import java.time.Instant; import java.util.TimeZone; import javax.print.attribute.standard.DateTimeAtCompleted; import org.apache.parquet.example.data.simple.Int96Value; import org.apache.parquet.example.data.simple.NanoTime; import org.apache.parquet.io.api.Binary; import org.relaxng.datatype.DatatypeStreamingValidator; public class CSV2ParquetTimestampUtils { public static NanoTime fromDateTimeString(String val) throws ParseException { long micros = parseTimeStampMicros(val, false ); /* DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // , Locale.ENGLISH); df.setTimeZone(java.util.TimeZone.getTimeZone("UTC"));; java.util.Date result = df.parse(val); java.util.TimeZone.setDefault(TimeZone.getTimeZone("UTC")); // try a byte array a la // https://www.programcreek.com/java-api-examples/index.php?source_dir=presto-master/presto-hive/src/test/java/com/facebook/presto/hive/parquet/TestParquetTimestampUtils.java // todo : parse millis long unixSecs = result.getTime() / 1000l; */ long unixSecs = micros / 1000000; int julianDay = getJulianDaysFromUnix(unixSecs); long timeOfDayNanos = getJulianTimeInNanosFromUnix(unixSecs, 0); timeOfDayNanos += 1000l*(micros - (((long) (micros/1000000)) * 1000000)); return new NanoTime(julianDay, timeOfDayNanos); } /* static final long DayInSeconds = 24*60*60; static final long ShiftDate = DayInSeconds / 2; static final long JulianOffsetSeconds = DayInSeconds / 2; // or DayInSeconds / 2; static final double OFFSETJULIAN = 2440587.5; // WE DON'T use 0.5 as some claim that impala does not use it !? .5; */ /* // no offset at all static final long DayInSeconds = 24*60*60; static final long ShiftDate = 0; // DayInSeconds / 2; static final long JulianOffsetSeconds = 0; // DayInSeconds / 2; // or DayInSeconds / 2; static final double OFFSETJULIAN = 2440587f + JulianOffsetSeconds/2.0; // WE DON'T use 0.5 as some claim that impala does not use it !? .5; */ //offset in the date calculation, but time is time from 0:00 static final boolean NanosFromMidnight = true; static final boolean JulianDateAtNoon = false; static final long DayInSeconds = 24*60*60; static final long ShiftDate = 0; // DayInSeconds / 2; static final long JulianNanosOffsetSeconds = NanosFromMidnight ? 0 : DayInSeconds/2; // DayInSeconds / 2; // or DayInSeconds / 2; /* * We try to make this aligned with HIVE, ignoring the standard * see e.g. https://issues.apache.org/jira/browse/HIVE-6394 * Hive converts "1970-01-01 00:00:00.0" to Julian timestamp: (julianDay=2440588, timeOfDayNanos=0) Actually midnight 1970 has 2440587.5 noon 2440588.0 etc. */ static final long OFFSETJULIAN = 2440588; // .0 + (JulianDateAtNoon ? 0.5: 0.0); // WE DON'T use 0.5 as some claim that impala does not use it !? .5; /* static double getJulianFromUnix(double unixSecs) { return ( (unixSecs + 86400 * juliandays) + OFFSETJULIAN ); }*/ static int getJulianDaysFromUnix(long unixSecs) { long secsjulian = unixSecs + OFFSETJULIAN * DayInSeconds; return (int) (secsjulian / DayInSeconds); } /* (juliandays - OFFSETJULIAN)*86400 + nanos / 1000000; -86400 + 0.. 86400 -> 1 return unixSecs 86400 double julianDaysDouble = getJulianFromUnix(unixSecs); return Double.valueOf(Math.floor(julianDaysDouble)).intValue(); } */ static long getJulianTimeInNanosFromUnix(long unixSecs, long days) { long remainder = (long) ((unixSecs + OFFSETJULIAN * DayInSeconds) % DayInSeconds); return remainder * 1000 * 1000 * 1000; } /* static long getJulianTimeInNanosFromUnix2(long unixSecs) { double frac = getJulianFromUnix(unixSecs) - getJulianDaysFromUnix(unixSecs); frac *= 86400.0 * 1000; return Double.valueOf(frac).longValue(); }*/ public static String binaryToDateTimeString(Binary int96b) { NanoTime nt = NanoTime.fromBinary(int96b); int day = nt.getJulianDay(); long nanos = nt.getTimeOfDayNanos(); long unixTimeSecs = (day - OFFSETJULIAN) * DayInSeconds + nanos/ (1000*1000*1000); Date dt = new Date(unixTimeSecs*1000); // milliseconds! DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // , Locale.ENGLISH); df.setTimeZone(TimeZone.getTimeZone("UTC")); return df.format(dt); } public static String parseDateOrIntStrict(String val) { DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); // , Locale.ENGLISH); df.setTimeZone(TimeZone.getTimeZone("UTC")); java.util.Date result; try { result = df.parse(val); return "" + Double.valueOf(Math.floor(result.getTime() / (DayInSeconds * 1000l))).intValue(); } catch (ParseException e) { return "" + Long.parseLong(val); } } public static String parseDateOrIntSloppy(String val) { DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); // , Locale.ENGLISH); df.setTimeZone(TimeZone.getTimeZone("UTC")); java.util.Date result; try { result = df.parse(val); return "" + Double.valueOf(Math.floor(result.getTime() / (DayInSeconds * 1000l))).intValue(); } catch (ParseException e) { if (val != null && (val.length() == "yyyyMMdd".length())) { DateFormat df2 = new SimpleDateFormat("yyyyMMdd"); // , Locale.ENGLISH); df2.setTimeZone(TimeZone.getTimeZone("UTC")); try { result = df2.parse(val); return "" + Double.valueOf(Math.floor(result.getTime() / (DayInSeconds * 1000l))).intValue(); } catch (ParseException e2) { return "" + Long.parseLong(val); } } else { return "" + Long.parseLong(val); } } } public static String formatDate(int value) { long milliseconds = (long) value * (24l * 60 * 60 * 1000); java.util.Date dt = Date.from(Instant.ofEpochMilli(milliseconds)); DateFormat sd = new SimpleDateFormat("yyyy-MM-dd"); sd.setTimeZone(TimeZone.getTimeZone("UTC")); return sd.format(dt); } public static String formatTimeMicros(long value) { long milliseconds = Double.valueOf(value / 1000000).longValue() * 1000; SimpleDateFormat sd = new SimpleDateFormat("HH:mm:ss."); sd.setTimeZone(TimeZone.getTimeZone("UTC")); return sd.format(milliseconds) + String.format("%06d", value % 1000000); } public static String formatTimeMillis(int value) { SimpleDateFormat sd = new SimpleDateFormat("HH:mm:ss.SSS"); sd.setTimeZone(TimeZone.getTimeZone("UTC")); return sd.format(Date.from(Instant.ofEpochMilli(value))); } public static long parseTimeMicros(String val, boolean strict) throws ParseException { DateFormat df = new SimpleDateFormat("zzz yyyy-MM-dd HH:mm:ss"); // , Locale.ENGLISH); java.util.Date result; int micros = 0; try { String dateval = "GMT 1970-01-01 "+ val; ParsePosition pp = new ParsePosition(0); result = df.parse(dateval, pp); if (pp.getErrorIndex() >= 0) { throw new ParseException("error parsing" + val, pp.getErrorIndex()); } int index = pp.getIndex(); if (index < dateval.length() && dateval.charAt(index) == '.') { try { micros = Integer.parseInt(dateval.substring(index+1)); } catch(NumberFormatException e) { // silenlty absorb } } return (result.getTime() * 1000l + micros); } catch (ParseException e) { if (strict) { throw e; } return parseTimeMicrosSloppy(val); } } public static long parseTimeStampMicros(String val, boolean strict) throws ParseException { DateFormat df = new SimpleDateFormat("zzz yyyy-MM-dd HH:mm:ss"); // , Locale.ENGLISH); java.util.Date result; int micros = 0; try { String dateval = "GMT "+ val; ParsePosition pp = new ParsePosition(0); result = df.parse(dateval, pp); if (pp.getErrorIndex() >= 0) { throw new ParseException("error parsing" + val, pp.getErrorIndex()); } int index = pp.getIndex(); if (index < dateval.length() && dateval.charAt(index) == '.') { try { micros = Integer.parseInt(dateval.substring(index+1)); } catch(NumberFormatException e) { // silenlty absorb } } return (result.getTime() * 1000l + micros); } catch (ParseException e) { if (strict) { throw e; } return parseTimestampMicrosSloppy(val); } } public static long parseTimeStampMillis(String val, boolean strict) throws ParseException { DateFormat df = new SimpleDateFormat("zzz yyyy-MM-dd HH:mm:ss.SSS"); // , Locale.ENGLISH); java.util.Date result; try { String dateval = "GMT "+ val; ParsePosition pp = new ParsePosition(0); result = df.parse(dateval, pp); if (pp.getErrorIndex() >= 0) { throw new ParseException("error parsing" + val, pp.getErrorIndex()); } return (result.getTime()); } catch (ParseException e) { if (strict) { throw e; } return parseTimestampMillisSloppy(val); } } public static int parseTimeMillisOrInt(String val) { try { return parseTimeMillisInt(val, false); } catch (ParseException e) { return Integer.parseInt(val); } } public static long parseTimeMicrosSloppy(String val) throws ParseException { DateFormat df = new SimpleDateFormat("zzz yyyy-MM-dd HH:mm:ss"); // , Locale.ENGLISH); java.util.Date result; result = df.parse("GMT 1970-01-01 " + val); long tm = result.getTime() * 1000; return (long) tm; } public static long parseTimestampMicrosSloppy(String val) throws ParseException { DateFormat df = new SimpleDateFormat("zzz yyyy-MM-dd HH:mm:ss"); // , Locale.ENGLISH); java.util.Date result; result = df.parse("GMT " + val); // val); long tm = result.getTime() * 1000; return tm; } public static long parseTimestampMillisSloppy(String val) throws ParseException { return parseTimestampMicrosSloppy(val) / 1000; } public static int parseTimeMillisInt(String val, boolean b) throws ParseException { DateFormat df = new SimpleDateFormat("zzz yyyy-MM-dd HH:mm:ss.SSS"); // , Locale.ENGLISH); java.util.Date result; try { result = df.parse("GMT 1970-01-01 " + val); long a = result.getTime(); int bdd =(int) a; return (int) result.getTime(); } catch (ParseException e) { if (b) throw e; } long parseTimeMicros = parseTimeMicrosSloppy(val); return (int) parseTimeMicros / 1000; } }
true
750b8f8dfbe3206c6b9253454b714d917d731ca5
Java
ITWILL1TEAM/BC
/Project_BC/src/main/java/svc/cartSvc/AddCartService.java
UTF-8
722
2.5
2
[]
no_license
package svc.cartSvc; import static db.JdbcUtil.*; import java.sql.Connection; import dao.BasketDAO; import vo.BasketBean; public class AddCartService { public boolean AddCart(BasketBean basket) { System.out.println("AddCartService - AddCart()"); boolean isInsertSuccess = false; Connection con = getConnection(); BasketDAO dao = BasketDAO.getInstance(); dao.setConnection(con); // BasketDAO 객체의 insertBasket() 메소드를 호출하여 장바구니 테이블에 추가 작업 수행 int insertCount = dao.insertBasket(basket); if(insertCount > 0) { commit(con); isInsertSuccess = true; } else { rollback(con); } close(con); return isInsertSuccess; } }
true
c99c37da00a2767054e70da089f72f57d4334211
Java
thalitagq/UFC
/Programas/Trabalho3/src/trabalho3/Dado.java
UTF-8
1,309
3.296875
3
[]
no_license
package trabalho3; import java.util.ArrayList; /** * * @author thalita */ public class Dado { char id; int timestampRead = 0; int timestampWrite = 0; static ArrayList<Dado> dados = new ArrayList<Dado>(); public Dado(){} public Dado(char id, int timeStamp){ this.id = id; } /** * Verifica se um dado existe no array de dados * @param a * @return */ public boolean verificarDado(ArrayList<Dado> a){ boolean existe = false; for(int i = 0 ; i< a.size(); i++){ if(a.get(i).id == this.id){ existe = true; } } return existe; } static void ImprimirDados(){ System.out.println("\nDados: "); for (int i = 0; i < Dado.dados.size(); i++) { System.out.println("< "+Dado.dados.get(i).id+", "+Dado.dados.get(i).timestampRead+", "+Dado.dados.get(i).timestampWrite+" >"); } } /** * zera os valores dos timestamps dos dados */ static void reinicializarDados(){ for (int i = 0; i < Dado.dados.size(); i++) { Dado.dados.get(i).timestampRead = 0; Dado.dados.get(i).timestampWrite = 0; } } }
true
e93496141c394191228c30a0ec186ccc44b51f7d
Java
KINGDSB/TestProject
/demo/src/main/java/com/dsb/example/demo/utils/DateUtil.java
UTF-8
7,392
2.703125
3
[]
no_license
package com.dsb.example.demo.utils; import org.springframework.util.StringUtils; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; public class DateUtil { private static final ThreadLocal<DateFormat> datetimeFormat = new ThreadLocal<DateFormat>() { @Override protected DateFormat initialValue() { return new SimpleDateFormat("yyyyMMddHHmmss"); } }; private static final ThreadLocal<DateFormat> datetimeFormatByyMdhs = new ThreadLocal<DateFormat>() { @Override protected DateFormat initialValue() { return new SimpleDateFormat("yyyyMMddhhss"); } }; private static final ThreadLocal<DateFormat> dateFormat = new ThreadLocal<DateFormat>() { @Override protected DateFormat initialValue() { return new SimpleDateFormat("yyyyMMdd"); } }; private static final ThreadLocal<DateFormat> dateFormatYM = new ThreadLocal<DateFormat>() { @Override protected DateFormat initialValue() { return new SimpleDateFormat("yyyyMM"); } }; private static final ThreadLocal<DateFormat> dateFormatYMd = new ThreadLocal<DateFormat>() { @Override protected DateFormat initialValue() { return new SimpleDateFormat("yyyy-MM-dd"); } }; private static final ThreadLocal<DateFormat> timeFormat = new ThreadLocal<DateFormat>() { @Override protected DateFormat initialValue() { return new SimpleDateFormat("HH:mm:ss"); } }; private static final ThreadLocal<DateFormat> timeFormatHm = new ThreadLocal<DateFormat>() { @Override protected DateFormat initialValue() { return new SimpleDateFormat("HH:mm"); } }; private static final ThreadLocal<DateFormat> displayFormat = new ThreadLocal<DateFormat>() { @Override protected DateFormat initialValue() { return new SimpleDateFormat("yyyy-MM-dd HH:mm"); } }; private static final ThreadLocal<DateFormat> dateTimeDispalyFormat = new ThreadLocal<DateFormat>() { @Override protected DateFormat initialValue() { return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); } }; private static final ThreadLocal<DateFormat> dateDisplayFormat = new ThreadLocal<DateFormat>() { @Override protected DateFormat initialValue() { return new SimpleDateFormat("yyyy-MM-dd"); } }; private static final DateFormat DATE_FORMAT_TIME2 = new SimpleDateFormat("yyyy-MM-dd"); private static final DateFormat DATE_FORMAT_TIME = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); public static Date parseDateYMD(String dateString) { try { return dateDisplayFormat.get().parse(dateString); } catch (ParseException e) { throw new RuntimeException(e); } } public static Date formatStringDateTime(String datetimeString) { try { return dateTimeDispalyFormat.get().parse(datetimeString); } catch (ParseException e) { throw new RuntimeException(); } } public static String formatDateTimeDispaly(Date date) { return dateTimeDispalyFormat.get().format(date); } public static String formatDisplay(Date date) { return displayFormat.get().format(date); } public static String formatDatetime(Date date) { return datetimeFormat.get().format(date); } public static String formatDateByyMdhs(Date date) { return datetimeFormatByyMdhs.get().format(date); } public static Date parseDatetime(String dateString) { try { return datetimeFormat.get().parse(dateString); } catch (ParseException e) { throw new RuntimeException(e); } } public static Date parseDisplayDatetime(String dateString) { try { return displayFormat.get().parse(dateString); } catch (ParseException e) { throw new RuntimeException(e); } } public static String formatDate(Date date) { return dateFormat.get().format(date); } public static String formatDateYMd(Date date) { return dateFormatYMd.get().format(date); } public static Date stringToDate(String str) { if(StringUtils.isEmpty(str)){ return null; } SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Date date = null; try { date = sdf.parse(str); } catch (ParseException e) { e.printStackTrace(); } return date; } public static Date stringToDateyMdHms(String str) { if(StringUtils.isEmpty(str)){ return null; } SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date = null; try { date = sdf.parse(str); } catch (ParseException e) { e.printStackTrace(); } return date; } public static String formatTime(Date date) { return timeFormat.get().format(date); } public static String formatTimeHm(Date date) { return timeFormatHm.get().format(date); } public static Date parseDate(String dateString) { try { return dateFormat.get().parse(dateString); } catch (ParseException e) { throw new RuntimeException(e); } } public static Date getSysMaxDatetime() { return parseDatetime("21990101000000"); } public static final int SECOND = 0; public static final int MINUTES = 1; public static final int HOUR = 2; public static final int DAY = 3; public static long diffDate(Date date1, Date date2, int field) { long diff = date1.getTime() - date2.getTime(); switch (field) { case SECOND: return diff / 1000; case MINUTES: return diff / (1000 * 60); case HOUR: return diff / (1000 * 60 * 60); case DAY: return diff / (1000 * 60 * 60 * 24); default: return diff; } } /** * 获取本月最后一天 * @param date 本月第一天 * @return String 本月最后一天 */ @SuppressWarnings("static-access") public static String lastDayOrMonth(String date){ if(date.length() != 10){ return null; } String substring = date.substring(0, date.length()-3); Calendar calendar=new GregorianCalendar(); Date resDate = parseDateYMD(substring+"-01"); calendar.setTime(resDate); calendar.roll(Calendar.DATE, -1); return new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime()); } public static int formatDateHour(Date date) { try { String dateString = DATE_FORMAT_TIME.format(date); return Integer.valueOf(dateString.substring(11, 13)); } catch (Exception e) { throw new RuntimeException(e); } } /** * 参数为null 则返回当前时间 * @return 格式 xxxx年xx月xx日 * @param parDate 参数格式为 xxxx-xx-xx */ public static String getNowDate(String parDate){ String date = ""; if(!StringUtils.isEmpty(parDate)){ date = formatDateYMd(new Date()); }else{ date = formatDateYMd(new Date()); } return new StringBuffer(date.substring(0,4)).append("年") .append(date.substring(5,7)).append("月") .append(date.substring(8,10)).append("日") .toString(); } public static int getNowYear() { Date nowdate = getNowDate(); int year = nowdate.getYear() + 1900; return year; } /** * 获取当前时间 * 系统内部获取时间时统一使用这个方法 */ public static Date getNowDate() { return new Date(); } public static String formatDateYM(Date date) { try { if(date == null){ return null; } return dateFormatYM.get().format(date); } catch (Exception e) { throw new RuntimeException(e); } } }
true
9a306c535ce30a8e3a8d2cba8f1f12336da58874
Java
talk2morris/TEST-PROJECT
/omod/src/main/java/org/openmrs/module/patientindextracing/utility/ClinicalIndicatorReports.java
UTF-8
423
1.523438
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.openmrs.module.patientindextracing.utility; import org.openmrs.notification.Note; /** * @author MORRISON.I */ public class ClinicalIndicatorReports { public void doSomething() { Note n = new Note(); // n.set } }
true
603242093c89447b83421139b859bda72fd799f6
Java
sivaprasathm93/AutomationTesting
/src/test/java/selenium/objects/flipkart/ShoesObject.java
UTF-8
1,266
1.804688
2
[]
no_license
package selenium.objects.flipkart; import org.openqa.selenium.By; public interface ShoesObject { By BUTTON_LoginPopupClose=By.xpath("//button[contains(@class,'dH8')]"); By BUTTON_Search=By.xpath("//input[@title='Search for products, brands and more']/parent::div/following-sibling::button"); By BUTTON_BuyNow=By.xpath("//button[contains(.,'BUY NOW')]"); By TEXTBOX_Search=By.xpath("//input[@title='Search for products, brands and more']"); By TEXTBOX_BrandSearch=By.xpath("//div[.='Brand']/parent::section//input[@type='text']"); By LINK_AllResults=By.xpath("//a[.='Home']/../../../../../following-sibling::div//a[string-length(@title)>0]"); By LINK_ShoesSize=By.xpath("//span[contains(@id,'Size')]/following-sibling::ul/li/a"); By TEXT_Brand=By.xpath("//a[.='Home']/../../../../../following-sibling::div//a[string-length(@title)>0]/preceding-sibling::div"); By TEXT_Price=By.xpath("//a[.='Home']/../../../../../following-sibling::div//a/div/div[contains(@class,'_1vC')]"); By TEXT_LoginOrSignUp=By.xpath("//span[.='Login or Signup']"); By CHECKBOX_BrandPuma=By.xpath("//div[@title='Puma']//input[@type='checkbox']"); By DROPDOWN_MaxPrice=By.xpath("(//div[.='Price']/../following-sibling::div//select)[2]"); }
true
ffb0bbd7aab452e9d129edbc89eb3eca071c3028
Java
chetan03tutorial/aem
/src/main/java/com/nataraj/lib/exception/aem/ex/FrameworkErrorResponse.java
UTF-8
1,179
2.171875
2
[]
no_license
package com.nataraj.lib.exception.aem.ex; import jdk.nashorn.internal.objects.annotations.Getter; import jdk.nashorn.internal.objects.annotations.Setter; import java.time.LocalDateTime; public class FrameworkErrorResponse { private int code; private String message; private LocalDateTime timestamp; private int httpStatus; private BaseFrameworkException ex; private String rootCause; public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public int getHttpStatus() { return httpStatus; } public void setHttpStatus(int httpStatus) { this.httpStatus = httpStatus; } public LocalDateTime getTimestamp() { return timestamp; } public void setTimestamp(LocalDateTime timestamp) { this.timestamp = timestamp; } public String getRootCause() { return rootCause; } public void setRootCause(String rootCause) { this.rootCause = rootCause; } }
true
f3c8fab3bec31c5e25f311ec97594a103f4de65a
Java
LintfordPickle/LintfordLib
/src/net/lintford/library/renderers/windows/UiBaseLayoutComponent.java
UTF-8
12,801
1.859375
2
[]
no_license
package net.lintford.library.renderers.windows; import java.util.ArrayList; import java.util.List; import net.lintford.library.ConstantsApp; import net.lintford.library.core.LintfordCore; import net.lintford.library.core.ResourceManager; import net.lintford.library.core.debug.Debug; import net.lintford.library.core.geometry.Rectangle; import net.lintford.library.core.graphics.Color; import net.lintford.library.core.graphics.ColorConstants; import net.lintford.library.core.graphics.batching.SpriteBatch; import net.lintford.library.core.graphics.fonts.FontUnit; import net.lintford.library.core.graphics.sprites.spritesheet.SpriteSheetDefinition; import net.lintford.library.core.graphics.textures.CoreTextureNames; import net.lintford.library.renderers.ZLayers; import net.lintford.library.renderers.windows.components.IScrollBarArea; import net.lintford.library.renderers.windows.components.ScrollBar; import net.lintford.library.renderers.windows.components.ScrollBarContentRectangle; import net.lintford.library.renderers.windows.components.UIWidget; import net.lintford.library.screenmanager.ScreenManagerConstants.FILLTYPE; import net.lintford.library.screenmanager.ScreenManagerConstants.LAYOUT_WIDTH; /** * The dimensions of the BaseLayout are set by the parent screen. */ public class UiBaseLayoutComponent extends UIWidget implements IScrollBarArea { private static final long serialVersionUID = 5742176250891551930L; public static final float USE_HEIGHT_OF_ENTRIES = -1; // -------------------------------------- // Variables // -------------------------------------- protected LAYOUT_WIDTH mLayoutWidth = LAYOUT_WIDTH.THREEQUARTER; protected FILLTYPE mLayoutFillType = FILLTYPE.FILL_CONTAINER; public final Color layoutColor = new Color(ColorConstants.WHITE); protected List<UIWidget> mUiWidgets; protected int mSelectedEntry = 0; protected int mNumberEntries; protected boolean mDrawBackground; protected float mMinWidth; protected float mMaxWidth = -1; // inactive protected float mMinHeight; protected float mForcedHeight; protected float mForcedEntryHeight; private boolean mResourcesLoaded; protected ScrollBarContentRectangle mContentArea; protected ScrollBar mScrollBar; protected float mYScrollPosition; protected float mZScrollAcceleration; protected float mZScrollVelocity; protected boolean mScrollBarsEnabled; protected boolean mScrollBarsEnabled_Internal; protected boolean mEnabled; protected boolean mVisible; // ony affects drawing protected float mEntryOffsetFromTop; // -------------------------------------- // Properties // -------------------------------------- public boolean scrollBarsEnabled() { return mScrollBarsEnabled; } public void scrollBarsEnabled(boolean newValue) { mScrollBarsEnabled = newValue; } public void maxWidth(float newValue) { mMaxWidth = newValue; } public float maxWidth() { return mMaxWidth; } public void setEntryOffsetY(float newValue) { mEntryOffsetFromTop = newValue; } public FILLTYPE layoutFillType() { return mLayoutFillType; } public void layoutFillType(FILLTYPE filltype) { if (filltype == null) return; mLayoutFillType = filltype; } public LAYOUT_WIDTH layoutWidth() { return mLayoutWidth; } public void layoutWidth(LAYOUT_WIDTH playoutWidth) { if (playoutWidth == null) return; mLayoutWidth = playoutWidth; } public void minWidth(float newValue) { mMinWidth = newValue; } public void minHeight(float newValue) { mMinHeight = newValue; } public void setDrawBackground(boolean enabled, Color color) { mDrawBackground = enabled; layoutColor.setFromColor(color); } public boolean isLoaded() { return mResourcesLoaded; } /** @returns A list of menu entries so derived classes can change the menu contents. */ public List<UIWidget> widgets() { return mUiWidgets; } /** Forces the layout to use the height value provided. Use BaseLayout.USE_HEIGHT_OF_ENTRIES value to use the sum of the entry heights. */ public void forceHeight(float pNewHeight) { mForcedHeight = pNewHeight; } /** Forces the layout to use the height value provided for the total height of all the content. Use BaseLayout.USE_HEIGHT_OF_ENTRIES value to use the sum of the entry heights. */ public void forceEntryHeight(float pNewHeight) { mForcedEntryHeight = pNewHeight; } public boolean enabled() { return mEnabled; } public void enabled(boolean pEnabled) { mEnabled = pEnabled; } public boolean visible() { return mVisible; } public void visible(boolean pEnabled) { mVisible = pEnabled; } // -------------------------------------- // Constructor // -------------------------------------- public UiBaseLayoutComponent(UiWindow parentWindow) { super(parentWindow); mUiWidgets = new ArrayList<>(); mEnabled = true; mVisible = true; mMinWidth = 100f; mMinHeight = 10f; mForcedEntryHeight = USE_HEIGHT_OF_ENTRIES; mForcedHeight = USE_HEIGHT_OF_ENTRIES; mScrollBarsEnabled = true; mContentArea = new ScrollBarContentRectangle(this); mScrollBar = new ScrollBar(this, mContentArea); mEntryOffsetFromTop = 10; } // -------------------------------------- // Core-Methods // -------------------------------------- public void initialize() { int lCount = mUiWidgets.size(); for (int i = 0; i < lCount; i++) { mUiWidgets.get(i).initialize(); } // width = getEntryWidth(); mH = getDesiredHeight(); } public void loadResources(ResourceManager resourceManager) { final int lWidgetCount = mUiWidgets.size(); for (int i = 0; i < lWidgetCount; i++) { mUiWidgets.get(i).loadResources(resourceManager); } mResourcesLoaded = true; } public void unloadResources() { final int lWidgetCount = mUiWidgets.size(); for (int i = 0; i < lWidgetCount; i++) { mUiWidgets.get(i).unloadResources(); } mResourcesLoaded = false; } public boolean handleInput(LintfordCore core) { if (widgets() == null || widgets().size() == 0) return false; // nothing to do final var lEntryCount = widgets().size(); for (int i = 0; i < lEntryCount; i++) { final var lMenuEntry = widgets().get(i); if (lMenuEntry.handleInput(core)) { // return true; } } if (intersectsAA(core.HUD().getMouseCameraSpace())) { if (true && core.input().mouse().tryAcquireMouseMiddle((hashCode()))) { mZScrollAcceleration += core.input().mouse().mouseWheelYOffset() * 250.0f; } } if (mScrollBarsEnabled_Internal) { mScrollBar.handleInput(core, mParentWindow.rendererManager()); } return false; } public void update(LintfordCore core) { final int lCount = mUiWidgets.size(); for (int i = 0; i < lCount; i++) { mUiWidgets.get(i).update(core); } if (!mScrollBarsEnabled_Internal) mYScrollPosition = 0; final float lPaddingHorizontal = 5.f; final float lWidthOffset = mScrollBarsEnabled_Internal ? 25.f : lPaddingHorizontal; float xPos = mX + lPaddingHorizontal; float yPos = mY + mYScrollPosition; // Order the child widgets (that's what the bseLayout is for) for (int i = 0; i < lCount; i++) { final var lWidget = mUiWidgets.get(i); if (!lWidget.isVisible()) continue; lWidget.x(xPos); lWidget.y((int) yPos); lWidget.setPosition(xPos, yPos); lWidget.width(mW - lWidthOffset); yPos += lWidget.height(); } mContentArea.set(mX, mY, mW, getEntryHeight()); mScrollBarsEnabled_Internal = mScrollBarsEnabled && mContentArea.height() - mH > 0; if (mScrollBarsEnabled_Internal) { final float lDeltaTime = (float) core.appTime().elapsedTimeMilli() / 1000f; float lScrollSpeedFactor = mYScrollPosition; mZScrollVelocity += mZScrollAcceleration; lScrollSpeedFactor += mZScrollVelocity * lDeltaTime; mZScrollVelocity *= 0.85f; mZScrollAcceleration = 0.0f; mYScrollPosition = lScrollSpeedFactor; // Constrain if (mYScrollPosition > 0) mYScrollPosition = 0; if (mYScrollPosition < -(mContentArea.height() - this.mH)) { mYScrollPosition = -(mContentArea.height() - this.mH); } mScrollBar.update(core); } } public void draw(LintfordCore core, SpriteBatch spriteBatch, SpriteSheetDefinition coreSpritesheet, FontUnit textFont, float componentZDepth) { if (!mEnabled || !mVisible) return; final var lFontUnit = mParentWindow.rendererManager().uiTextFont(); if (mDrawBackground) { if (mH < 64) { spriteBatch.begin(core.HUD()); final float lAlpha = 0.8f; final var lColor = ColorConstants.getColor(0.1f, 0.1f, 0.1f, lAlpha); spriteBatch.draw(coreSpritesheet, CoreTextureNames.TEXTURE_WHITE, mX, mY, mW, mH, componentZDepth, lColor); spriteBatch.end(); } else { final float TILE_SIZE = 32; spriteBatch.begin(core.HUD()); spriteBatch.draw(coreSpritesheet, CoreTextureNames.TEXTURE_PANEL_3X3_00_TOP_LEFT, mX, mY, TILE_SIZE, TILE_SIZE, componentZDepth, layoutColor); spriteBatch.draw(coreSpritesheet, CoreTextureNames.TEXTURE_PANEL_3X3_00_TOP_LEFT, mX + TILE_SIZE, mY, mW - TILE_SIZE * 2, TILE_SIZE, componentZDepth, layoutColor); spriteBatch.draw(coreSpritesheet, CoreTextureNames.TEXTURE_PANEL_3X3_00_TOP_LEFT, mX + mW - TILE_SIZE, mY, TILE_SIZE, TILE_SIZE, componentZDepth, layoutColor); spriteBatch.draw(coreSpritesheet, CoreTextureNames.TEXTURE_PANEL_3X3_00_TOP_LEFT, mX, mY + TILE_SIZE, TILE_SIZE, mH - TILE_SIZE * 2, componentZDepth, layoutColor); spriteBatch.draw(coreSpritesheet, CoreTextureNames.TEXTURE_PANEL_3X3_00_TOP_LEFT, mX + TILE_SIZE, mY + TILE_SIZE, mW - TILE_SIZE * 2, mH - 64, componentZDepth, layoutColor); spriteBatch.draw(coreSpritesheet, CoreTextureNames.TEXTURE_PANEL_3X3_00_TOP_LEFT, mX + mW - TILE_SIZE, mY + TILE_SIZE, TILE_SIZE, mH - TILE_SIZE * 2, componentZDepth, layoutColor); spriteBatch.draw(coreSpritesheet, CoreTextureNames.TEXTURE_PANEL_3X3_00_TOP_LEFT, mX, mY + mH - TILE_SIZE, TILE_SIZE, TILE_SIZE, componentZDepth, layoutColor); spriteBatch.draw(coreSpritesheet, CoreTextureNames.TEXTURE_PANEL_3X3_00_TOP_LEFT, mX + TILE_SIZE, mY + mH - TILE_SIZE, mW - TILE_SIZE * 2, TILE_SIZE, componentZDepth, layoutColor); spriteBatch.draw(coreSpritesheet, CoreTextureNames.TEXTURE_PANEL_3X3_00_TOP_LEFT, mX + mW - TILE_SIZE, mY + mH - TILE_SIZE, TILE_SIZE, TILE_SIZE, componentZDepth, layoutColor); spriteBatch.end(); if (ConstantsApp.getBooleanValueDef("DEBUG_SHOW_UI_OUTLINES", false)) { Debug.debugManager().drawers().drawRectImmediate(core.HUD(), this); } } } if (mScrollBarsEnabled_Internal) { mContentArea.depthPadding(6f); mContentArea.preDraw(core, spriteBatch, coreSpritesheet); } final int lCount = widgets().size(); for (int i = lCount - 1; i >= 0; --i) { final var lWidget = widgets().get(i); if (!lWidget.isVisible()) continue; lWidget.draw(core, spriteBatch, coreSpritesheet, lFontUnit, componentZDepth + .1f); } if (mScrollBarsEnabled_Internal) { mContentArea.postDraw(core); mScrollBar.draw(core, spriteBatch, coreSpritesheet, componentZDepth + .1f, .8f); } if (ConstantsApp.getBooleanValueDef("DEBUG_SHOW_UI_COLLIDABLES", false)) { spriteBatch.begin(core.HUD()); spriteBatch.draw(coreSpritesheet, CoreTextureNames.TEXTURE_WHITE, mX, mY, mW, mH, ZLayers.LAYER_DEBUG, ColorConstants.Debug_Transparent_Magenta); spriteBatch.end(); } } // -------------------------------------- // Methods // -------------------------------------- public boolean hasEntry(int index) { if (index < 0 || index >= widgets().size()) return false; return true; } public float getEntryWidth() { final int lEntryCount = widgets().size(); if (lEntryCount == 0) return 0; // return the widest entry float lResult = 0; for (int i = 0; i < lEntryCount; i++) { float lTemp = widgets().get(i).width(); if (lTemp > lResult) { lResult = lTemp; } } return lResult; } public float getEntryHeight() { if (mForcedEntryHeight != USE_HEIGHT_OF_ENTRIES && mForcedEntryHeight >= 0) return mForcedEntryHeight; final int lEntryCount = widgets().size(); if (lEntryCount == 0) return 0; float lResult = marginTop(); for (int i = 0; i < lEntryCount; i++) { final var lMenuEntry = widgets().get(i); lResult += lMenuEntry.marginTop(); lResult += lMenuEntry.height(); lResult += lMenuEntry.marginBottom(); } return lResult + marginBottom(); } public float getDesiredHeight() { if (mForcedHeight != USE_HEIGHT_OF_ENTRIES && mForcedHeight >= 0) return mForcedHeight; return getEntryHeight(); } // -------------------------------------- // IScrollBarArea Methods // -------------------------------------- @Override public Rectangle contentDisplayArea() { return this; } @Override public ScrollBarContentRectangle fullContentArea() { return mContentArea; } }
true
66f5dfea15c48ba160ae33e1a969537d846f6131
Java
raphaelcohn/java-parsing
/source/java-parsing-application/com/stormmq/java/parsing/application/ConsoleEntryPoint.java
UTF-8
6,647
2.5
2
[ "MIT" ]
permissive
package com.stormmq.java.parsing.application; import com.stormmq.path.Constants; import joptsimple.OptionException; import joptsimple.OptionParser; import joptsimple.OptionSet; import org.jetbrains.annotations.NotNull; import java.io.IOException; import java.nio.charset.Charset; import java.nio.charset.IllegalCharsetNameException; import java.nio.charset.UnsupportedCharsetException; import java.nio.file.InvalidPathException; import java.nio.file.Path; import java.util.*; import static com.stormmq.path.IsSubFolderFilter.IsSubFolder; import static java.lang.String.format; import static java.lang.System.*; import static java.nio.charset.Charset.forName; import static java.nio.file.Files.*; import static java.nio.file.Paths.get; import static java.util.Locale.ENGLISH; public final class ConsoleEntryPoint { private static final String help = "help"; private static final String source = "source"; private static final String destination = "destination"; private static final String imports = "imports"; private static final OptionParser CommandLineArgumentsParser = new OptionParser(); static { CommandLineArgumentsParser.posixlyCorrect(true); CommandLineArgumentsParser.accepts(help, "show help").forHelp(); CommandLineArgumentsParser.accepts(source, "source root path").withRequiredArg().describedAs("/Users/raph/Documents/java-llvm/source").ofType(String.class).defaultsTo(Constants.CurrentFolder); CommandLineArgumentsParser.accepts(imports, "import paths").withRequiredArg().describedAs("/Users/raph/Documents/java-llvm/library").withValuesSeparatedBy(':').ofType(String.class).defaultsTo(Constants.CurrentFolder); CommandLineArgumentsParser.accepts(destination, "destination root path").withRequiredArg().describedAs("/Users/raph/Documents/java-llvm/destination").ofType(String.class); } public static void main(@NotNull final String... commandLineArguments) { final OptionSet arguments; try { arguments = CommandLineArgumentsParser.parse(commandLineArguments); } catch (OptionException e) { err.printf(e.getMessage() + '\n'); printHelp(1); return; } if (arguments.has(help)) { printHelp(2); return; } for (final String argument : requiredArguments(source, destination)) { if (!arguments.has(argument)) { err.printf(format(ENGLISH, "Missing required argument %1$s\n", argument)); printHelp(1); return; } } @NotNull final Path sourceRootPath = extantWritableFolderPathArgument(arguments, source); @NotNull final Path destinationRootPath = creatableFolderPathArgument(arguments, destination); @NotNull final LinkedHashSet<Path> importPaths = extantWritableFolderPathsArgument(arguments, imports); new Application(sourceRootPath, destinationRootPath, importPaths).run(); } @NotNull private static Path extantWritableFolderPathArgument(@NotNull final OptionSet arguments, @NotNull final String argumentName) { final Path potentialWritableFolderPath = pathArgument(arguments, argumentName); extantWritableFolderPath(argumentName, potentialWritableFolderPath); return potentialWritableFolderPath; } private static void extantWritableFolderPath(@NotNull final String argumentName, @NotNull final Path potentialWritableFolderPath) { if (!exists(potentialWritableFolderPath) || !IsSubFolder.accept(potentialWritableFolderPath) || !isWritable(potentialWritableFolderPath)) { err.printf(format(ENGLISH, "Argument --%1$s is not a readable, writable sub-folder path (%2$s)\n", argumentName, potentialWritableFolderPath.toString())); printHelp(1); } } @NotNull private static Path creatableFolderPathArgument(@NotNull final OptionSet arguments, @NotNull final String argumentName) { final Path potentialWritableFolderPath = pathArgument(arguments, argumentName); if (exists(potentialWritableFolderPath)) { if (!IsSubFolder.accept(potentialWritableFolderPath) || !isWritable(potentialWritableFolderPath)) { err.printf(format(ENGLISH, "Argument --%1$s is extant but not a readable, writable sub-folder path (%2$s)\n", argumentName, potentialWritableFolderPath.toString())); printHelp(1); } } else { try { createDirectories(potentialWritableFolderPath); } catch (IOException e) { err.printf(format(ENGLISH, "Argument --%1$s could not be created (%2$s)\n", argumentName, potentialWritableFolderPath.toString())); printHelp(1); } } return potentialWritableFolderPath; } @NotNull private static LinkedHashSet<Path> extantWritableFolderPathsArgument(@NotNull final OptionSet arguments, @NotNull final String argumentName) { @SuppressWarnings("unchecked") final List<String> rawValues = (List<String>) arguments.valuesOf(argumentName); final LinkedHashSet<Path> paths = new LinkedHashSet<>(rawValues.size()); for (String rawValue : rawValues) { final Path path; try { path = get(rawValue).toAbsolutePath(); } catch (InvalidPathException e) { err.printf(format(ENGLISH, "Argument --%1$s is an invalid path (%2$s)\n", argumentName, rawValue)); printHelp(1); throw new IllegalStateException("Should have exited"); } extantWritableFolderPath(argumentName, path); paths.add(path); } return paths; } @NotNull private static Path pathArgument(@NotNull final OptionSet arguments, @NotNull final String argumentName) { final String rawValue = (String) arguments.valueOf(argumentName); try { return get(rawValue).toAbsolutePath(); } catch (InvalidPathException e) { err.printf(format(ENGLISH, "Argument --%1$s is an invalid path (%2$s)\n", argumentName, rawValue)); printHelp(1); throw new IllegalStateException("Should have exited"); } } @NotNull private static Charset charsetArgument(@NotNull final OptionSet arguments, @NotNull final String argumentName) { final String rawValue = (String) arguments.valueOf(argumentName); try { return forName(rawValue); } catch (final IllegalCharsetNameException | UnsupportedCharsetException e) { err.printf(format(ENGLISH, "Argument --%1$s is an invalid charset (%2$s)\n", argumentName, rawValue)); printHelp(1); throw new IllegalStateException("Should have exited"); } } private static void printHelp(final int exitCode) { try { CommandLineArgumentsParser.printHelpOn(out); } catch (IOException e) { err.printf(format(ENGLISH, "Unexpected failure printing help %1$s\n", e.getMessage())); } exit(exitCode); } @NotNull private static String[] requiredArguments(@NotNull final String... requiredArguments) { return requiredArguments; } private ConsoleEntryPoint() { } }
true
524166c31615f0996a556efc18e3356f64458426
Java
liaohuijun/hxsg
/hxsg-admin/src/main/java/com/hxsg/wupin/controller/Cocos2dGiftPackageController.java
UTF-8
1,748
2.09375
2
[]
no_license
package com.hxsg.wupin.controller; import com.hxsg.CommonUtil.CommonUtilAjax; import com.hxsg.wupin.service.Cocos2dGiftPackageService; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; /** * Created by dlf on 2016/9/29. */ @Controller @RequestMapping("Cocos2dGiftPackage") public class Cocos2dGiftPackageController { /********************cocos2d-js服务端代码***************************/ private Logger logger =Logger.getLogger(Cocos2dGiftPackageController.class); @Autowired Cocos2dGiftPackageService cocos2dgiftpackageservice; //加载物品分类 @RequestMapping(value = "/giftPackage", method = { RequestMethod.GET, RequestMethod.POST }) @ResponseBody public String giftPackage( @RequestParam(value = "name", required = false) String name, HttpSession session,HttpServletRequest request,HttpServletResponse response){ try{ Integer roleId= (Integer) session.getAttribute("roleId"); String msg=cocos2dgiftpackageservice.giftPackage(roleId,name); CommonUtilAjax.sendAjaxList("msg",msg,request, response); }catch (Exception e){ logger.error("控制层--Cocos2dGiftPackage/giftPackage:"+e.getMessage()); } return null; } }
true
84b23be41185dffceb4f373f0acbf3ce305235b9
Java
TwoBirdsOnTheTree/MyStudyAndTest
/JavaTest/src/main/java/com/mytest/concurrent/java_concurrency_in_practice/ThisEscapteTest.java
UTF-8
1,436
3.59375
4
[]
no_license
package com.mytest.concurrent.java_concurrency_in_practice; import org.junit.jupiter.api.Test; import java.util.function.Supplier; public class ThisEscapteTest { interface Listener<T> { T doSomething(); } public static void main(String[] args) throws InterruptedException { class Event { Object obj = null; <T> void addListener(Listener<T> t) { obj = t.doSomething(); } } class ThisEscape { ThisEscape(Event event) { // 在构造方法里`发布`ThisEscape实例 event.addListener(() -> this); // 构造方法延时结束 try { Thread.sleep(2000); System.out.println("ThisEscape构造结束!!!"); } catch (Exception e) { e.printStackTrace(); } } } Event event = new Event(); new Thread(() -> { ThisEscape thisEscape = new ThisEscape(event); }).start(); /** * 这个时候`this逸出`了 * ThisEscape构造方法还没直接结束呢 * 外部就可以访问ThisEscape实例了! */ Thread.sleep(1000); // 访问ThisEscape实例 ThisEscape escape = (ThisEscape) event.obj; System.out.println(escape.getClass().getName()); } }
true
ab16485baf158c6c875d7b4b59f2ba1178503e5f
Java
WPI-CS3733-Team2/course_load_scheduler
/src/main/java/org/dselent/course_load_scheduler/client/event_handler/TriggerChangePasswordWindowEventHandler.java
UTF-8
368
1.65625
2
[]
no_license
package org.dselent.course_load_scheduler.client.event_handler; import org.dselent.course_load_scheduler.client.event.TriggerChangePasswordWindowEvent; import com.google.gwt.event.shared.EventHandler; public interface TriggerChangePasswordWindowEventHandler extends EventHandler { public void onTriggerChangePasswordWindow(TriggerChangePasswordWindowEvent evt); }
true
8b19b26c97014563d78e1c767c0f0c1d82f36a60
Java
thorcarpenter/promptopensource
/prompt/src/com/lucyapps/prompt/detail/PromptBroadcastReceiver.java
UTF-8
417
1.726563
2
[]
no_license
/* Copyright 2010 NorseVision LLC, all rights reserved. */ package com.lucyapps.prompt.detail; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; /** * * @author Thor */ public class PromptBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { PromptService.schedulePromptService(context); } }
true
245fb99d347c0a1f62e4285a903e456952fa3e8f
Java
merski007/ExceptionsLab
/src/lab3/NameService.java
UTF-8
1,052
3.890625
4
[]
no_license
package lab3; /** * This class provides various services relating to name manipulation. * No output should be performed here. * * @author Jim Lombardo, jlombardo@wctc.edu * @version 1.00 */ public class NameService { /** * Finds and returns the last name from within a full name. Caution: * No validation is performed. * * @param fullName - a name containing a first name and a last name * @return the last name * @throws YourCustomExceptionName if fullName is null or empty or has * fewer than two parts */ public String extractLastName(String fullName) throws IllegalArgumentException { String lastName = null; // put your code here String[] lastNameArray = fullName.split(" "); if(lastNameArray.length != 2){ throw new FullNameException(); } else if(lastNameArray[1].length() >= 5){ throw new MaximumLengthException(); } lastName = lastNameArray[1]; return lastName; } }
true
1864d8802276c3bdbff1e4a84698fe1f17bf5dcb
Java
Damboooo/OOD
/Code/src/ProjectManagement/Change.java
UTF-8
860
2.328125
2
[]
no_license
package ProjectManagement; import java.awt.List; import java.util.ArrayList; import java.util.Date; import ResourceManagement.*; public class Change { private String discribtion; private Date startTime; private Date endTime; private ArrayList<Resource> resources = new ArrayList<>(); public Date getStartTime() { return startTime; } public void setStartTime(Date startTime) { this.startTime = startTime; } public Date getEndTime() { return endTime; } public void setEndTime(Date endTime) { this.endTime = endTime; } public String getDiscribtion() { return discribtion; } public void setDiscribtion(String discribtion) { this.discribtion = discribtion; } public ArrayList<Resource> getResources() { return resources; } public void setResources(ArrayList<Resource> resources) { this.resources = resources; } }
true
065a4e8d445c51ff0ff0814eea99e4381fcdb5ea
Java
kzn/ml
/src/main/java/TestAdaBoost.java
UTF-8
1,966
2.421875
2
[]
no_license
import java.io.IOException; import java.util.ArrayList; import java.util.List; import name.kazennikov.ml.core.Instance; import cc.mallet.pipe.Pipe; import cc.mallet.pipe.Target2Label; import cc.mallet.types.Alphabet; import cc.mallet.types.FeatureVector; import cc.mallet.types.InstanceList; import ru.iitp.proling.ml.boosting.AdaBoostReal; import ru.iitp.proling.ml.boosting.CappedLinearSVMLearner; import ru.iitp.proling.ml.scorer.Scorer; import ru.iitp.proling.svm.BasicDataset; import ru.iitp.proling.svm.BinaryClassifier; import ru.iitp.proling.svm.ClassifierEval; public class TestAdaBoost { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { String filename = args[0]; BasicDataset ds = BasicDataset.readText(filename); List<Instance> inst = new ArrayList<Instance>(); double[] targets = new double[ds.size()]; Alphabet d = new Alphabet(); for(int i = 0; i != ds.dim() + 1; i++) d.lookupIndex(Integer.valueOf(i)); Pipe p = new Target2Label(); InstanceList il = new InstanceList(p); for(int i = 0; i != ds.size(); i++){ il.addThruPipe(new cc.mallet.types.Instance(new FeatureVector(d, ds.get(i).indexes()), Double.valueOf(ds.target(i)), null, null)); inst.add(ds.get(i)); targets[i] = ds.target(i); } /*AdaBoostTrainer tr = new AdaBoostTrainer(new C45Trainer(2), 20); //C45Trainer tr = new C45Trainer(8, false); AdaBoost c = tr.train(il); System.out.printf("Accuracy: %f%n", c.getAccuracy(il));*/ AdaBoostReal ab = new AdaBoostReal(new CappedLinearSVMLearner(100, 100, 1000), 100); Scorer s = ab.train(inst, targets, 1, 1); ClassifierEval.evalBinaryClassifier(ds, new BinaryClassifier<Double>(s, 1.0, -1.0)); if(args.length == 2){ BasicDataset dtest = BasicDataset.readText(args[1]); ClassifierEval.evalBinaryClassifier(dtest, new BinaryClassifier<Double>(s, 1.0, -1.0)); } } }
true
93b56e5df0ad941987708d1cd3bbcefb5b6a3d34
Java
pennxia/PatientPortalSpringMVCApplication
/PatientPortalMain/src/main/java/com/me/pojo/Person.java
UTF-8
2,125
2.40625
2
[]
no_license
package com.me.pojo; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Inheritance; import javax.persistence.OneToOne; import javax.persistence.Table; import javax.persistence.InheritanceType; @Entity @Table(name="person") @Inheritance(strategy=InheritanceType.JOINED) public class Person { @Id @GeneratedValue @Column(name="personid", unique = true, nullable = false) private int personID; @Column(name="firstname") private String firstName; @Column(name="lastname") private String lastName; @Column(name="address") private String address; @Column(name="emailid") private String emailID; @Column(name="phone") private String phone; @Column(name="gender") private String gender; Person(){} // Person(String firstName,String lastName,String gender,String emailId,String phone,String address) // { // this.firstName = firstName; // this.lastName = lastName; // this.gender = gender; // this.emailID = emailId; // this.phone = phone; // this.address = address; // } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getEmailID() { return emailID; } public void setEmailID(String emailID) { this.emailID = emailID; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public int getPersonID() { return personID; } public void setPersonID(int personID) { this.personID = personID; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } }
true
aad6ca9479a6c7122d5c350d43329dc11a535c0d
Java
shashikanthsb/enggproject
/pgr/pgr-notification/src/test/java/org/egov/pgr/notification/domain/model/EmailRequestTest.java
UTF-8
1,940
2.375
2
[]
no_license
package org.egov.pgr.notification.domain.model; import org.junit.Test; import static org.junit.Assert.*; public class EmailRequestTest { @Test public void test_equality_should_return_true_when_fields_are_same_for_two_instances() { final EmailRequest emailRequest1 = new EmailRequest("subject", "body", "foo@bar.com"); final EmailRequest emailRequest2 = new EmailRequest("subject", "body", "foo@bar.com"); assertTrue(emailRequest1.equals(emailRequest2)); } @Test public void test_hashcode_should_match_when_fields_are_same_for_two_instances() { final EmailRequest emailRequest1 = new EmailRequest("subject", "body", "foo@bar.com"); final EmailRequest emailRequest2 = new EmailRequest("subject", "body", "foo@bar.com"); assertEquals(emailRequest1.hashCode(), emailRequest2.hashCode()); } @Test public void test_hashcode_should_not_match_when_fields_are_different_for_two_instances() { final EmailRequest emailRequest1 = new EmailRequest("subject1", "body1", "foo@bar.com"); final EmailRequest emailRequest2 = new EmailRequest("subject2", "body2", "foo2@bar.com"); assertNotEquals(emailRequest1.hashCode(), emailRequest2.hashCode()); } @Test public void test_equality_should_return_false_when_body_is_different_for_two_instances() { final EmailRequest emailRequest1 = new EmailRequest("subject", "body1", "foo@bar.com"); final EmailRequest emailRequest2 = new EmailRequest("subject", "body2", "foo@bar.com"); assertFalse(emailRequest1.equals(emailRequest2)); } @Test public void test_equality_should_return_false_when_subject_is_different_for_two_instances() { final EmailRequest emailRequest1 = new EmailRequest("subject1", "body", "foo@bar.com"); final EmailRequest emailRequest2 = new EmailRequest("subject2", "body", "foo@bar.com"); assertFalse(emailRequest1.equals(emailRequest2)); } }
true
125f1c26af456a600033666c376b59f4091c42de
Java
soolr/ikAnalyzer
/src/org/wltea/analyzer/dic/DictSegment.java
GB18030
5,278
2.703125
3
[]
no_license
package org.wltea.analyzer.dic; import java.util.Arrays; import java.util.HashMap; import java.util.Map; class DictSegment implements Comparable<DictSegment> { private static final Map<Character, Character> charMap = new HashMap(16, 0.95F); private static final int ARRAY_LENGTH_LIMIT = 3; private Map<Character, DictSegment> childrenMap; private DictSegment[] childrenArray; private Character nodeChar; private int storeSize = 0; private int nodeState = 0; DictSegment(Character nodeChar) { if (nodeChar == null) { throw new IllegalArgumentException("Ϊ쳣ַΪ"); } this.nodeChar = nodeChar; } Character getNodeChar() { return this.nodeChar; } boolean hasNextNode() { return this.storeSize > 0; } Hit match(char[] charArray) { return match(charArray, 0, charArray.length, null); } Hit match(char[] charArray, int begin, int length) { return match(charArray, begin, length, null); } Hit match(char[] charArray, int begin, int length, Hit searchHit) { if (searchHit == null) { searchHit = new Hit(); searchHit.setBegin(begin); } else { searchHit.setUnmatch(); } searchHit.setEnd(begin); Character keyChar = new Character(charArray[begin]); DictSegment ds = null; DictSegment[] segmentArray = this.childrenArray; Map<Character, DictSegment> segmentMap = this.childrenMap; if (segmentArray != null) { DictSegment keySegment = new DictSegment(keyChar); int position = Arrays.binarySearch(segmentArray, 0, this.storeSize, keySegment); if (position >= 0) { ds = segmentArray[position]; } } else if (segmentMap != null) { ds = (DictSegment)segmentMap.get(keyChar); } if (ds != null) { if (length > 1) { return ds.match(charArray, begin + 1, length - 1, searchHit); } if (length == 1) { if (ds.nodeState == 1) { searchHit.setMatch(); } if (ds.hasNextNode()) { searchHit.setPrefix(); searchHit.setMatchedDictSegment(ds); } return searchHit; } } return searchHit; } void fillSegment(char[] charArray) { fillSegment(charArray, 0, charArray.length, 1); } void disableSegment(char[] charArray) { fillSegment(charArray, 0, charArray.length, 0); } private synchronized void fillSegment(char[] charArray, int begin, int length, int enabled) { Character beginChar = new Character(charArray[begin]); Character keyChar = (Character)charMap.get(beginChar); if (keyChar == null) { charMap.put(beginChar, beginChar); keyChar = beginChar; } DictSegment ds = lookforSegment(keyChar, enabled); if (ds != null) { if (length > 1) { ds.fillSegment(charArray, begin + 1, length - 1, enabled); } else if (length == 1) { ds.nodeState = enabled; } } } private DictSegment lookforSegment(Character keyChar, int create) { DictSegment ds = null; if (this.storeSize <= 3) { DictSegment[] segmentArray = getChildrenArray(); DictSegment keySegment = new DictSegment(keyChar); int position = Arrays.binarySearch(segmentArray, 0, this.storeSize, keySegment); if (position >= 0) { ds = segmentArray[position]; } if ((ds == null) && (create == 1)) { ds = keySegment; if (this.storeSize < 3) { segmentArray[this.storeSize] = ds; this.storeSize += 1; Arrays.sort(segmentArray, 0, this.storeSize); } else { Map<Character, DictSegment> segmentMap = getChildrenMap(); migrate(segmentArray, segmentMap); segmentMap.put(keyChar, ds); this.storeSize += 1; this.childrenArray = null; } } } else { Map<Character, DictSegment> segmentMap = getChildrenMap(); ds = (DictSegment)segmentMap.get(keyChar); if ((ds == null) && (create == 1)) { ds = new DictSegment(keyChar); segmentMap.put(keyChar, ds); this.storeSize += 1; } } return ds; } private DictSegment[] getChildrenArray() { if (this.childrenArray == null) { synchronized (this) { if (this.childrenArray == null) { this.childrenArray = new DictSegment[3]; } } } return this.childrenArray; } private Map<Character, DictSegment> getChildrenMap() { if (this.childrenMap == null) { synchronized (this) { if (this.childrenMap == null) { this.childrenMap = new HashMap(6, 0.8F); } } } return this.childrenMap; } private void migrate(DictSegment[] segmentArray, Map<Character, DictSegment> segmentMap) { for (DictSegment segment : segmentArray) { if (segment != null) { segmentMap.put(segment.nodeChar, segment); } } } public int compareTo(DictSegment o) { return this.nodeChar.compareTo(o.nodeChar); } }
true
051d4814d80ba4e356267afa53fa077ce8e37b9f
Java
appsofluna/appsofluna-simpleapps
/src/main/java/com/appsofluna/simpleapps/repository/PermissionRepository.java
UTF-8
1,691
1.921875
2
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
/* * Copyright (c) Charaka Gunatillake / AppsoFluna. (http://www.appsofluna.com) * All rights reserved. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.appsofluna.simpleapps.repository; import com.appsofluna.simpleapps.model.Permission; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.PagingAndSortingRepository; import org.springframework.data.repository.query.Param; import org.springframework.data.rest.core.annotation.RepositoryRestResource; /** * The repository interface for Permission Entity * Spring handles the implementation * @author Charaka Gunatillake <charakajg[at]gmail[dot]com> */ @RepositoryRestResource(collectionResourceRel = "permission", path = "permission") public interface PermissionRepository extends PagingAndSortingRepository<Permission,Long> { //PermissionRepository @Modifying @Query("DELETE Permission o WHERE o.role.id = :roleId") public int deleteAllPermissionsFor(@Param("roleId") long roleId); @Query("SELECT o FROM Permission o WHERE o.role.id = :roleId AND o.item.id = :itemId") public Permission findByRoleAndItem(@Param("roleId") long roleId, @Param("itemId") long itemId); }
true
b4fc6ee9715cc4527d46fbb289b6a7b76bac24c5
Java
Troubniakova/TroubniakovaQA15
/first-selenium-project/src/test/java/homework/OpenFirefoxWikipedia.java
UTF-8
654
2.234375
2
[ "Apache-2.0" ]
permissive
package homework; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import java.util.concurrent.TimeUnit; public class OpenFirefoxWikipedia { WebDriver wd; @BeforeMethod public void setUp(){ wd = new FirefoxDriver(); wd.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS); } @Test public void openSiteTest(){ wd.navigate().to("https://www.wikipedia.org"); } @AfterMethod public void tearDown(){ wd.quit(); } }
true
56050534a9d23b0355a2bc088e09e1ac6f840f46
Java
vikash28/syranew
/src/main/java/syra/etl/app/dto/FoldersDTO.java
UTF-8
454
2.3125
2
[]
no_license
package syra.etl.app.dto; import java.util.List; /** * * JSON serializable DTO containing data concerning a folder search request. * */ public class FoldersDTO { List<FolderDTO> folders; public FoldersDTO(List<FolderDTO> folders) { this.folders = folders; } public List<FolderDTO> getFolders() { return folders; } public void setFolders(List<FolderDTO> folders) { this.folders = folders; } }
true
905e8c723cbce986addbe56427a871393ac945b8
Java
SleepingTalent/Absence-Tracker
/absence-tracker-acceptance-test/src/test/java/com/noveria/cukes/helpers/selenium/WebDriverFactory.java
UTF-8
1,772
2.703125
3
[]
no_license
package com.noveria.cukes.helpers.selenium; import com.noveria.cukes.helpers.selenium.webdriver.ChromeCucumberWebDriver; import com.noveria.cukes.helpers.selenium.webdriver.CucumberWebDriver; import com.noveria.cukes.helpers.selenium.webdriver.FirefoxCucumberWebDriver; import com.noveria.cukes.helpers.selenium.webdriver.PhantomCucumberWebDriver; import java.util.concurrent.TimeUnit; import static org.junit.Assert.fail; public final class WebDriverFactory { public enum Browser { FIREFOX, PHANTOM, CHROME; } public static CucumberWebDriver getWebDriver() { Browser browserType = getBrowser(); CucumberWebDriver webDriver = null; switch (browserType) { case FIREFOX: webDriver = new FirefoxCucumberWebDriver(); break; case PHANTOM: webDriver = new PhantomCucumberWebDriver(); break; case CHROME: webDriver = new ChromeCucumberWebDriver(); } webDriver.getWindowHandle(); webDriver.manage().window().maximize(); webDriver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); return webDriver; } private static Browser getBrowser() { String browserType = System.getProperty("browser"); if("FIREFOX".equalsIgnoreCase(browserType)) { return Browser.FIREFOX; }else if ("PHANTOM".equalsIgnoreCase(browserType)) { return Browser.PHANTOM; }else if ("CHROME".equalsIgnoreCase(browserType)) { return Browser.CHROME; }else { fail("Web Browser not supported : "+browserType); return null; } } }
true
1eaa3ae6175fbf9d43892cac7141687327c032af
Java
Plain-Solutions/tt-core
/src/main/java/org/tt/core/sql/H2Queries.java
UTF-8
12,926
2.375
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2014 Plain Solutions * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.tt.core.sql; /** * H2Queries is an implementation of AbstractQueries interface to help AbstractSQLManager to communicate with H2 database * <p/> * All the query definitions in this class are created specially for H2. Compatibility with other database providers * is not guaranteed. * * @author Vlad Slepukhin * @since 1.0 */ public class H2Queries implements AbstractQueries { public H2Queries() { } /** * Query description. Gets the last id in the given table. * <p/> * The main usage is it get the last added class or datetime and pass it back to * lessons_records * * @return <code>String</code> containing SQL query. * @since 1.0 */ @Override public String getLastID() { return "SELECT MAX(id) FROM %s"; } /** * Query description. Adds department to <code>departments</code> table * * @return <code>String</code> containing SQL query. * @since 1.0 */ @Override public String qAddDepartment() { return "INSERT INTO departments(name,tag, message) VALUES('%s','%s', '%s');"; } /** * Query description. Adds group to <code>groups</code> table, based on department_tag information * * @return <code>String</code> containing SQL query. * @since 1.0 */ @Override public String qAddGroups() { return "INSERT INTO GROUPS(department_id, name) VALUES" + "((SELECT id FROM DEPARTMENTS WHERE tag='%s'),'%s'); "; } /** * Query description. Adds datetime entry to <code>datetimes</code> table to handle all the variations * of lesson parity, sequence of them and day order * * @return <code>String</code> containing SQL query. * @since 1.0 */ @Override public String qAddDateTime() { return "INSERT INTO datetimes(week_id, sequence, day_id) VALUES(%d,%d,%d);"; } /** * Query description. Adds subject entry to <code>subjects</code> table to store them for further use. * * @return <code>String</code> containing SQL query. * @since 1.0 */ @Override public String qAddSubject() { return "INSERT INTO subjects(name) VALUES ('%s');"; } @Override public String qAddTeacher() { return "INSERT INTO teachers(name) VALUES('%s');"; } @Override public String qAddLocation() { return "INSERT INTO locations(building, room) VALUES('%s', '%s');"; } @Override public String qAddSubGroup() { return "INSERT INTO subgroups(group_id, name) VALUES(%d, '%s');"; } /** * Query description. Adds lesson entry to <code>lessons_records</code> table to interconnect group, subject and datetime entries * in respective tables for fetching structured information about group timetable * * @return <code>String</code> containing SQL query. * @since 1.0 */ @Override public String qAddLessonRecord() { return "INSERT INTO lessons (group_id," + " datetime_id," + " activity_id," + " subject_id," + " subgroup_id," + " teacher_id," + " location_id," + " timestamp) VALUES (%d, %d, %d, %d, %d, %d, %d, %d);"; } /** * Query description. Gets map name-tag from <code>departments table</code> * * @return <code>String</code> containing SQL query. * @since 1.0 */ @Override public String qGetDepartments() { return "SELECT name,tag FROM departments ORDER BY NAME;"; } /** * Query description. Exclusively gets tags of departments, because of their wide usage in the whole TT project * * @return <code>String</code> containing SQL query. * @since 1.0 */ @Override public String qGetDepartmentTags() { return "SELECT tag FROM departments;"; } @Override public String qGetDepartmentMessage() { return "SELECT message FROM departments WHERE tag='%s';"; } /** * Query description. Gets all the groups names (displayable) from <code>groups</code> table, based on the * department tag. * * @return <code>String</code> containing SQL query. * @since 1.0 */ @Override public String qGetGroups() { return "SELECT gr.name FROM groups as gr, departments as dp " + "WHERE gr.department_id = dp.id AND dp.tag = '%s';"; } /** * Query description.Gets group id from <code>groups table</code>, based on its name and department tag. * * @return <code>String</code> containing SQL query. * @since 1.0 */ @Override public String qGetGroupID() { return "SELECT gr.id FROM groups as gr, departments as dp " + "WHERE gr.department_id = dp.id AND dp.tag = '%s' AND gr.name = '%s'"; } /** * Query description. Gets group name from <code>groups</code> table, based on its id and department tag. * * @return <code>String</code> containing SQL query. * @since 1.0 */ @Override public String qGetGroupName() { return "SELECT gr.name FROM groups as gr, departments as dp " + "WHERE gr.department_id = dp.id AND dp.tag = '%s' AND gr.id = %d"; } /** * Query description. Gets id of the datetime record from <code>datetimes</code>. * * @return <code>String</code> containing SQL query. * @since 1.0 */ @Override public String qGetDateTimeID() { return "SELECT id FROM datetimes WHERE week_id=%d AND sequence=%d AND day_id=%d;"; } /** * Query description. Gets id of the subject from <code>subjects</code> table. * * @return <code>String</code> containing SQL query. * @since 1.0 */ @Override public String qGetSubjectID() { return "SELECT id FROM subjects WHERE name='%s';"; } /** * Query description. Gets id of the teacher from <code>teachers</code> table. * * @return <code>String</code> containing SQL query. * @since 2.0 */ @Override public String qGetTeacherID() { return "SELECT id FROM teachers WHERE name='%s';"; } /** * Query description. Gets id of the location (building + room) from <code>locations</code> table. * * @return <code>String</code> containing SQL query. * @since 2.0 */ @Override public String qGetLocationID() { return "SELECT id FROM locations WHERE building='%s' AND room='%s';"; } /** * Query description. Gets id of the subgroup from <code>subgroups</code> table. * * @return <code>String</code> containing SQL query. * @since 2.0 */ @Override public String qGetSubGroupID() { return "SELECT id FROM subgroups WHERE group_id=%d AND name='%s';"; } /** * Query description. Gets id of parity state from <code>week_states</code> table. * * @return <code>String</code> containing SQL query. * @since 2.0 */ @Override public String qGetParityID() { return "SELECT id FROM week_states WHERE state='%s';"; } /** * Query description. Gets id of the activity type (lecture and so on) from <code>activities</code> table. * * @return <code>String</code> containing SQL query. * @since 2.0 */ @Override public String qGetActivityID() { return "SELECT id FROM activities WHERE type='%s';"; } /** * Query description. Gets structured information about the whole timetable for the selected group * * @return <code>String</code> containing SQL query. * @since 1.0 */ @Override public String qGetTT() { return "SELECT d.name As dayName, ws.state As parity, " + "ldt.sequence As seq, a.type As activity, s.name As subject, " + "sgrp.name As sub, t.name As teacher, loc.building As locb, loc.room As locr " + "FROM week_states as ws " + "JOIN datetimes as ldt on ldt.week_id=ws.id " + "JOIN days as d on d.id=ldt.day_id " + "JOIN lessons as lr on lr.datetime_id = ldt.id " + "JOIN activities as a on lr.activity_id = a.id " + "JOIN subjects as s on lr.subject_id = s.id " + "JOIN subgroups as sgrp on lr.subgroup_id = sgrp.id " + "JOIN teachers as t on lr.teacher_id = t.id " + "JOIN locations as loc on lr.location_id = loc.id " + "JOIN groups as g on g.id = lr.group_id AND g.id=%d " + "ORDER BY d.id ASC, ldt.sequence ASC
, sgrp.name ASC;"; } @Override public String qGetLessonList() { return "SELECT ldt.sequence As sequence, ws.state As parity, sgrp.name As subgroup," + "a.type As activity, s.name As subject, " + "t.name As teacher, loc.building As building, loc.room As room, lr.timestamp As timestamp " + "FROM week_states as ws " + "JOIN datetimes as ldt on ldt.week_id=ws.id " + "JOIN days as d on d.id=ldt.day_id AND d.id=%d " + "JOIN lessons as lr on lr.datetime_id = ldt.id " + "JOIN activities as a on lr.activity_id = a.id " + "JOIN subjects as s on lr.subject_id = s.id " + "JOIN subgroups as sgrp on lr.subgroup_id = sgrp.id " + "JOIN teachers as t on lr.teacher_id = t.id " + "JOIN locations as loc on lr.location_id = loc.id " + "JOIN groups as g on g.id = lr.group_id AND g.id=%d" + "ORDER BY d.id ASC, ldt.sequence ASC
, sgrp.name ASC;"; } @Override public String qDeleteDepartment() { return "DELETE FROM departments WHERE tag='%s';"; } @Override public String qDeleteGroup() { return "DELETE FROM groups WHERE id=%d;"; } @Override public String qDeleteGroupSubgroups() { return "DELETE FROM subgroups WHERE group_id=%d;"; } @Override public String qDeleteGroupLessons() { return "DELETE FROM lessons WHERE group_id=%d;"; } @Override public String qDeleteLessonEntry() { return "DELETE FROM lessons WHERE group_id=%s AND datetime_id=%d AND activity_id=%d AND subject_id=%d AND " + "subgroup_id = %d AND teacher_id=%d AND location_id=%d; "; } @Override public String qGlobalDelete() { return "DELETE FROM %s;"; } @Override public String qIDRestart() { return "ALTER TABLE %s ALTER COLUMN ID RESTART WITH 1"; } @Override public String qUpdateDepartmentMessage() { return "UPDATE departments SET message='%s' WHERE tag='%s';"; } @Override public String qUpdateDepartmentData() { return "UPDATE departments SET name='%s', tag='%s', message='%s' WHERE tag='%s';"; } /** * Query description. Utility. Gets id of the department to proof its existence. * * @return <code>String</code> containing SQL query. * @since 1.0 */ @Override public String qDepartmentExists() { return "SELECT id FROM departments WHERE tag='%s'"; } /** * Query description. Utility. Gets id of the group to proof its existence. * * @return <code>String</code> containing SQL query. * @since 1.0 */ @Override public String qGroupIDExists() { return "SELECT gr.id FROM groups as gr WHERE id=%d"; } /** * Query description. Utility. Gets id of the subject to proof its existence. * * @return <code>String</code> containing SQL query. * @since 1.0 */ @Override public String qSubjectExists() { return "SELECT group_id FROM lessons WHERE group_id=%d AND datetime_id=%d AND subject_id=%d;"; } /** * Query description. Utility. Checks if any lesson entries belong to selected group. * * @return <code>String</code> containing SQL query. * @since 2.0 */ @Override public String qGroupTTExists() { return "SELECT COUNT(group_id) As result FROM lessons WHERE group_id=%d;"; } }
true
9800d3846a7c967fa20020c414424fe185cd3a78
Java
kontsevych/Animals-
/src/test/java/animals/DogTest.java
UTF-8
345
2.59375
3
[]
no_license
package animals; import org.testng.Assert; import org.testng.annotations.Test; public class DogTest { Dog dog = new Dog(); @Test public void testDogVoice() { Assert.assertEquals(dog.getVoice(), "Гав!"); } @Test public void testDogRun() { Assert.assertEquals(dog.getRun(), "Run"); } }
true
ed5ed655cfe982ebbd5746e39d24be5dbd6ba02d
Java
diegopacheco/istio-pocs
/misc-pocs/spring-web-flux-reactive/src/main/java/com/github/diegopacheo/sandbox/java/spring/tx/dao/PersonDAO.java
UTF-8
292
2.046875
2
[ "Unlicense" ]
permissive
package com.github.diegopacheo.sandbox.java.spring.tx.dao; import com.github.diegopacheo.sandbox.java.spring.tx.domain.model.Person; import reactor.core.publisher.Flux; public interface PersonDAO { public Flux<Person> getAllData(); public Person insertData(String key,Person p); }
true
37d9b04e18d371c9f754407a4de5907201548ebd
Java
polaralex/Gapminder-Data-Analyzer
/src/Model/DatabaseHandler.java
UTF-8
2,455
3.09375
3
[]
no_license
package Model; import java.sql.*; import java.util.ArrayList; public class DatabaseHandler { // Change these according to your database's credentials: private String url = "jdbc:mysql://localhost:3306/databasesProject?useLegacyDatetimeCode=false&serverTimezone=UTC"; private String username = "databasesUser"; private String password = "databasesUserPassword"; private ResultSet resultSet = null; public ArrayList<DataValues> RunQueryForDataValues(String metric, String queryString) { System.out.println("Connecting database..."); try (Connection connection = DriverManager.getConnection(url, username, password)) { Statement statement = connection.createStatement(); resultSet = statement.executeQuery(queryString); return resultToArrayOfDataValues(metric, resultSet); } catch (SQLException e) { throw new IllegalStateException("Cannot connect the database!", e); } } private ArrayList<DataValues> resultToArrayOfDataValues(String metric, ResultSet resultSet) throws SQLException { ArrayList<DataValues> array = new ArrayList<>(); while (resultSet.next()) { String country = resultSet.getString("country"); int year = resultSet.getInt("Year"); float value = resultSet.getFloat("Value"); array.add(new DataValues(metric, country, year, value)); } return array; } public ArrayList<String> RunQueryForListOfStrings(String queryString, String columnLabel) { System.out.println("Connecting database..."); try (Connection connection = DriverManager.getConnection(url, username, password)) { Statement statement = connection.createStatement(); resultSet = statement.executeQuery(queryString); return resultToArrayOfStrings(resultSet, columnLabel); } catch (SQLException e) { throw new IllegalStateException("Cannot connect the database!", e); } } private ArrayList<String> resultToArrayOfStrings(ResultSet resultSet, String columnLabel) throws SQLException { ResultSetMetaData rsmd = resultSet.getMetaData(); ArrayList<String> stringArray = new ArrayList<>(); while (resultSet.next()) { String string = resultSet.getString(columnLabel); stringArray.add(string); } return stringArray; } }
true
2954b5a71dc49995be83d9ba8b7ef5497eb978e5
Java
OneLemonyBoi/Satisforestry
/Render/SFMinerRenderer.java
UTF-8
4,274
1.875
2
[]
no_license
package Reika.Satisforestry.Render; import org.lwjgl.opengl.GL11; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.AxisAlignedBB; import net.minecraftforge.client.MinecraftForgeClient; import net.minecraftforge.common.util.ForgeDirection; import Reika.DragonAPI.Base.DragonAPIMod; import Reika.DragonAPI.Base.TileEntityBase; import Reika.DragonAPI.Base.TileEntityRenderBase; import Reika.DragonAPI.Libraries.ReikaAABBHelper; import Reika.DragonAPI.Libraries.IO.ReikaTextureHelper; import Reika.DragonAPI.Libraries.Java.ReikaGLHelper.BlendMode; import Reika.DragonAPI.Libraries.Rendering.ReikaColorAPI; import Reika.DragonAPI.Libraries.Rendering.ReikaGuiAPI; import Reika.DragonAPI.Libraries.Rendering.ReikaRenderHelper; import Reika.Satisforestry.Satisforestry; import Reika.Satisforestry.Miner.TileNodeHarvester; public class SFMinerRenderer extends TileEntityRenderBase { //private final WavefrontObject model = new WavefrontObject(DirectResourceManager.getResource("Reika/Satisforestry/Render/miner.obj")); private final ModelSFMiner model = new ModelSFMiner("Render/ModelMiner.obj"); @Override public void renderTileEntityAt(TileEntity tile, double par2, double par4, double par6, float ptick) { TileNodeHarvester te = (TileNodeHarvester)tile; GL11.glPushAttrib(GL11.GL_ALL_ATTRIB_BITS); GL11.glPushMatrix(); GL11.glTranslated(par2, par4, par6); GL11.glTranslated(4, 0, 0); GL11.glRotated(180, 0, 1, 0); if (this.doRenderModel(te)) { if (MinecraftForgeClient.getRenderPass() == 0) { this.renderModel(te); } GL11.glPopMatrix(); if (MinecraftForgeClient.getRenderPass() == 1) { GL11.glPushMatrix(); ReikaRenderHelper.disableEntityLighting(); ReikaRenderHelper.disableLighting(); GL11.glEnable(GL11.GL_BLEND); BlendMode.DEFAULT.apply(); AxisAlignedBB box = te.getRenderBoundingBox(); ReikaAABBHelper.renderAABB(box, par2, par4, par6, te.xCoord, te.yCoord, te.zCoord, 255, 64, 64, 32, true); ForgeDirection dir = te.getDirection(); GL11.glDepthMask(false); GL11.glTranslated(par2, par4, par6); double a = 0.5+dir.offsetX*1.5; double b = 6.5; double c = 0.5+dir.offsetZ*1.5; double s = 0.25; if (dir.offsetX == 0) { a += 2.5; } else { c += 2.5; } GL11.glTranslated(a, b, c); //GL11.glRotated(180-RenderManager.instance.playerViewY, 0, 1, 0); //GL11.glRotated(-RenderManager.instance.playerViewX/2D, 1, 0, 0); GL11.glRotated(30, dir.offsetX == 0 ? 1 : 0, 0, dir.offsetZ == 0 ? 1 : 0); if (dir.offsetX != 0) GL11.glScaled(s, -s, 1); else GL11.glScaled(1, -s, s); ReikaGuiAPI.instance.drawCenteredStringNoShadow(this.getFontRenderer(), "Incomplete", 0, 0, 0xffffff); GL11.glRotated(180, 0, 1, 0); GL11.glTranslated(dir.offsetZ*5-dir.offsetX*3, 0, dir.offsetX*5-dir.offsetZ*3); GL11.glRotated(-60, dir.offsetX == 0 ? 1 : 0, 0, dir.offsetZ == 0 ? 1 : 0); ReikaGuiAPI.instance.drawCenteredStringNoShadow(this.getFontRenderer(), "Incomplete", 0, 0, 0xffffff); GL11.glPopMatrix(); } } else { GL11.glPopMatrix(); } GL11.glPopAttrib(); } private void renderModel(TileNodeHarvester te) { ReikaTextureHelper.bindTexture(Satisforestry.class, "Textures/miner.png"); GL11.glPushMatrix(); model.drawChassis(); GL11.glPushMatrix(); GL11.glTranslated(0, -te.getDrillVerticalOffsetScale(0.5, 1.5), 0); GL11.glRotated(te.drillSpinAngle, 0, 1, 0); model.drawDrill(); GL11.glPopMatrix(); GL11.glPushAttrib(GL11.GL_ALL_ATTRIB_BITS); ReikaRenderHelper.disableLighting(); ReikaRenderHelper.disableEntityLighting(); int c = te.getState().color; if (te.getOverclockingStep() > 0) { float f = 0.5F+(float)(0.5*Math.sin(te.getTicksExisted()*0.004)); c = ReikaColorAPI.mixColors(c, 0xffffff, f); } model.drawLightbar(c); GL11.glPopAttrib(); GL11.glPopMatrix(); } @Override protected boolean doRenderModel(TileEntityBase te) { return te.isInWorld() && ((TileNodeHarvester)te).hasStructure(); } @Override public String getTextureFolder() { return "Textures/"; } @Override protected DragonAPIMod getOwnerMod() { return Satisforestry.instance; } @Override protected Class getModClass() { return Satisforestry.class; } }
true
ab336ccf86eed6077875423dd3d04ccf090ef4c4
Java
scv119/USACO
/src/money.java
UTF-8
1,509
2.90625
3
[]
no_license
/* ID: scv1191 LANG: JAVA TASK: money */ import java.io.*; import java.util.Arrays; import java.util.StringTokenizer; public class money { static int N; static int M; static int arr[]; static long dp[][]; public static void main(String args[]) throws IOException{ BufferedReader f = new BufferedReader(new FileReader("money.in")); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("money.out"))); StringTokenizer st = new StringTokenizer(f.readLine()); N = Integer.parseInt(st.nextToken()); M = Integer.parseInt(st.nextToken()); arr = new int[N]; st = new StringTokenizer(f.readLine()); for(int i = 0 ; i < N; i ++){ if(!st.hasMoreTokens()) st = new StringTokenizer(f.readLine()); arr[i]= Integer.parseInt(st.nextToken()); } dp = new long[2][M+1]; out.println(solve()); out.close(); System.exit(0); } static long solve(){ int idx = 0; dp[0][0] = 1; for(int i = 0 ; i < N; i ++){ Arrays.fill(dp[idx^1],0); for(int count = 0; count * arr[i] <= M; count ++){ int value = count * arr[i]; for(int j = 0 ; j <=M; j ++){ if(j+value>M) break; dp[idx^1][j+value]+=dp[idx][j]; } } idx = idx ^ 1; } return dp[idx][M]; } }
true
bd05bff04cc8f79001f1c56cc2caae1d4d4b4b71
Java
haibofaith/SpringInAction2
/src/testXml/TestJava.java
UTF-8
486
1.976563
2
[]
no_license
package testXml; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.support.ClassPathXmlApplicationContext; public class TestJava { @Autowired private CompactDisc cd; @Test public void test() { //基于注解,自动装配2 ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("testXml/applicationContext.xml"); cd = ctx.getBean(CompactDisc.class); cd.play(); ctx.close(); } }
true
1f3ad25055798183f7ef7c199dfdb7371730fa85
Java
spring-projects/spring-data-examples
/rest/uri-customization/src/test/java/example/springdata/rest/uris/WebIntegrationTests.java
UTF-8
1,866
1.789063
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2015-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://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 example.springdata.rest.uris; import static org.hamcrest.CoreMatchers.*; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; /** * Integration tests to make sure the URI customizations are applied. * * @author Oliver Gierke * @author Divya Srivastava * @soundtrack Clueso - Gewinner (Stadtrandlichter Live) */ @SpringBootTest class WebIntegrationTests { @Autowired WebApplicationContext context; private MockMvc mvc; @BeforeEach void setUp() { this.mvc = MockMvcBuilders.webAppContextSetup(context).build(); } @Test void identifiesResourcesUsingUsername() throws Exception { mvc.perform(get("/users/olivergierke")).// andExpect(status().isOk()).// andExpect(jsonPath("$._links.self.href", endsWith("olivergierke"))); } }
true
c836e88e51fe2764ab3a797059d04e7811b74869
Java
lilijiangnan/bigdata
/storm/trident-triton/src/main/java/edu/ucsd/cs/triton/codegen/CodeGenerator.java
UTF-8
1,878
2.328125
2
[]
no_license
package edu.ucsd.cs.triton.codegen; import java.util.List; import edu.ucsd.cs.triton.codegen.language.BlockStatement; import edu.ucsd.cs.triton.codegen.language.JavaProgram; import edu.ucsd.cs.triton.codegen.language.Keyword; import edu.ucsd.cs.triton.codegen.language.MemberFunction; import edu.ucsd.cs.triton.operator.BaseLogicPlan; import edu.ucsd.cs.triton.operator.Start; import edu.ucsd.cs.triton.resources.ResourceManager; public final class CodeGenerator { private final List<BaseLogicPlan> _planList; private final String _className; private TridentProgram _program; public CodeGenerator(List<BaseLogicPlan> planList, final String fileName) { // TODO Auto-generated constructor stub _planList = planList; _program = new TridentProgram(fileName); _className = fileName; } public JavaProgram generate() { generateTopology(); generateDefaultMainEntry(); return _program.toJava(); } private void generateTopology() { System.out.println(_planList); List<BaseLogicPlan> orderedPlanList = Util.tsort(_planList); System.out.println(orderedPlanList); for (BaseLogicPlan logicPlan : orderedPlanList) { StringBuilder sb = new StringBuilder(); Start plan = logicPlan.generatePlan(); plan.dump(""); QueryTranslator translator = new QueryTranslator(logicPlan, _program); translator.visit(plan, sb); _program.addStmtToBuildQuery(sb.toString()); } } // TODO private void generateDefaultMainEntry() { // TODO Auto-generated method stub String classStmt = _className + " " + _className.toLowerCase() + " = " + Keyword.NEW + " " + _className + "()"; BlockStatement mainEntry = new MemberFunction("public static void main(String[] args)") .SimpleStmt(classStmt) .SimpleStmt(_className.toLowerCase() + ".execute(args)"); _program.setDefaultMain((MemberFunction) mainEntry); } }
true
8d7af6ac99efb7d0612c78a9c4436df59d51044b
Java
chengniu/biomedicus
/biomedicus-uima/src/main/java/edu/umn/biomedicus/uima/db/JdbcPagesIterator.java
UTF-8
2,406
2.21875
2
[ "Apache-2.0" ]
permissive
/* * Copyright (c) 2016 Regents of the University of Minnesota. * * 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 edu.umn.biomedicus.uima.db; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Iterator; /** * */ public class JdbcPagesIterator implements Iterator<JdbcResultSetIterator> { private static final Logger LOGGER = LoggerFactory.getLogger(JdbcPagesIterator.class); private final int pageSize; private final int totalResults; private final PreparedStatement statement; private final String analyzerVersion; private final int pages; private int currentPage; public JdbcPagesIterator(int pageSize, int totalResults, PreparedStatement statement, String analyzerVersion) { this.pageSize = pageSize; this.totalResults = totalResults; this.statement = statement; this.analyzerVersion = analyzerVersion; currentPage = 0; pages = totalResults / pageSize + (totalResults % pageSize > 0 ? 1 : 0); } @Override public boolean hasNext() { LOGGER.debug("Checking if there is another page of results"); return currentPage < pages; } @Override public JdbcResultSetIterator next() { LOGGER.debug("Getting next page of results, current page: {}", currentPage); try { statement.clearParameters(); int start = currentPage * pageSize; statement.setInt(1, Math.min(totalResults, start + pageSize)); statement.setInt(2, start + 1); ResultSet resultSet = statement.executeQuery(); currentPage++; return new JdbcResultSetIterator(resultSet, analyzerVersion); } catch (SQLException e) { throw new RuntimeException(e); } } }
true
ccb5c53df9d11fc3ffb3ef3e14c1b632368571d6
Java
recaius/spring-java-translation
/src/main/java/proto/dataset/ArrangedText.java
UTF-8
343
1.789063
2
[ "MIT" ]
permissive
package proto.dataset; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonTypeInfo; import lombok.Data; @Data @JsonTypeInfo(use= JsonTypeInfo.Id.NONE) @JsonIgnoreProperties(ignoreUnknown = true) public class ArrangedText { private String arrangedText; private String srcText; }
true
faba3afc33fd8c3b3e4ce80ba45e7995a21b8b3b
Java
ssh352/OrderBook-5
/src/main/java/baoying/orderbook/connector/FIXQFJDynamicSessionAcceptor.java
UTF-8
4,112
2.265625
2
[ "MIT" ]
permissive
package baoying.orderbook.connector; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import quickfix.*; import quickfix.mina.acceptor.AcceptorSessionProvider; import quickfix.mina.acceptor.DynamicAcceptorSessionProvider; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.util.Iterator; public class FIXQFJDynamicSessionAcceptor { private final static Logger log = LoggerFactory.getLogger(FIXQFJDynamicSessionAcceptor.class); private final String _appConfigInClasspath; private final SessionSettings _settings; private final MessageStoreFactory _storeFactory; private final LogFactory _logFactory; private final Application _msgCallback; private final SocketAcceptor _acceptor; public FIXQFJDynamicSessionAcceptor(String appConfigInClasspath, Application msgCallback) throws Exception { _appConfigInClasspath = appConfigInClasspath; log.info("qfj server begin initializing, with app configuration file in classpath:{}", appConfigInClasspath); _msgCallback = msgCallback; _settings = new SessionSettings(appConfigInClasspath); for (final Iterator<SessionID> i = _settings.sectionIterator(); i.hasNext();) { final SessionID sessionID = i.next(); log.info("session in the configuration :{} ", sessionID); } // It also supports other store factory, e.g. JDBC, memory. Maybe you // could use them in some advanced cases. _storeFactory = new FileStoreFactory(_settings); // It also supports other log factory, e.g. JDBC. But I think SL4J is // good enough. _logFactory = new SLF4JLogFactory(_settings); // This is single thread. For multi-thread, see // quickfix.ThreadedSocketInitiator, and QFJ Advanced. _acceptor = new SocketAcceptor(_msgCallback, _storeFactory, _settings, _logFactory, new DefaultMessageFactory()); setupDynamicSessionProvider(msgCallback , _acceptor); log.info("qfj server initialized, with app configuration file in classpath:{}", appConfigInClasspath); } // start is NOT put in constructor deliberately, to let it pair with // shutdown public void start() throws Exception { log.info("qfj server start, {}", _appConfigInClasspath); _acceptor.start(); log.info("qfj server started, {}", _appConfigInClasspath); } public void stop() throws Exception { log.info("qfj server stop, {}", _appConfigInClasspath); _acceptor.stop(); log.info("qfj server stopped, {}", _appConfigInClasspath); } private void setupDynamicSessionProvider(Application application, SocketAcceptor connectorAsAcc) throws ConfigError, FieldConvertError { for (final Iterator<SessionID> i = _settings.sectionIterator(); i.hasNext();) { final SessionID sessionID = i.next(); boolean isAcceptorTemplateSet = _settings.isSetting(sessionID, "AcceptorTemplate"); if (isAcceptorTemplateSet && _settings.getBool(sessionID, "AcceptorTemplate")) { log.info("dynamic acceptor is configured on {}", sessionID); AcceptorSessionProvider provider = new DynamicAcceptorSessionProvider(_settings, sessionID, application, _storeFactory, _logFactory, new DefaultMessageFactory()); // SocketAcceptAddress // SocketAcceptPort SocketAddress address = new InetSocketAddress(_settings.getString(sessionID, "SocketAcceptAddress"), (int) (_settings.getLong(sessionID, "SocketAcceptPort"))); connectorAsAcc.setSessionProvider(address, provider); // we have to skip setup SessionStateListener, // since the concrete session is not identified yet for // dynamic acceptor. // TODO try to figure out how to setup // SessionStateListener // when the concrete session is created. } } } }
true
5209478407a3b0dd1c355ad58e5b905edc191385
Java
opentree/aionj-hungary
/GameServer/src/main/java/com/aionemu/gameserver/model/alliance/PlayerAlliance.java
UTF-8
8,876
2
2
[]
no_license
/* * This file is part of aion-unique <aion-unique.org>. * * aion-unique 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. * * aion-unique 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 aion-unique. If not, see <http://www.gnu.org/licenses/>. */ package com.aionemu.gameserver.model.alliance; import java.util.ArrayList; import java.util.Collection; import java.util.List; import javolution.util.FastMap; import com.aionemu.gameserver.model.gameobjects.AionObject; import com.aionemu.gameserver.model.gameobjects.player.Player; import com.aionemu.gameserver.model.team.alliance.PlayerAllianceEvent; import com.aionemu.gameserver.network.aion.serverpackets.SM_ALLIANCE_MEMBER_INFO; import com.aionemu.gameserver.network.aion.serverpackets.SM_SYSTEM_MESSAGE; import com.aionemu.gameserver.services.AllianceService; import com.aionemu.gameserver.utils.PacketSendUtility; /** * @author Sarynth * */ public class PlayerAlliance extends AionObject { private int captainObjectId; private final List<Integer> viceCaptainObjectIds = new ArrayList<Integer>(); private final FastMap<Integer, PlayerAllianceMember> allianceMembers = new FastMap<Integer, PlayerAllianceMember>().shared(); private final FastMap<Integer, PlayerAllianceGroup> allianceGroupForMember = new FastMap<Integer, PlayerAllianceGroup>().shared(); private final FastMap<Integer, PlayerAllianceGroup> allianceGroups = new FastMap<Integer, PlayerAllianceGroup>().shared(); public PlayerAlliance(int objectId, int leaderObjectId) { super(objectId); setLeader(leaderObjectId); } public void addMember(Player member) { PlayerAllianceGroup group = getOpenAllianceGroup(); PlayerAllianceMember allianceMember = new PlayerAllianceMember(member); group.addMember(allianceMember); allianceMembers.put(member.getObjectId(), allianceMember); allianceGroupForMember.put(member.getObjectId(), group); member.setPlayerAlliance(this); } /** * @return OpenAllianceGroup */ private PlayerAllianceGroup getOpenAllianceGroup() { for (int i = 1000; i <= 1004; i++) { PlayerAllianceGroup group = allianceGroups.get(i); if (group == null) { group = new PlayerAllianceGroup(this); group.setAllianceId(i); allianceGroups.put(i, group); return group; } if (group.getMembers().size() < 6) return group; } throw new RuntimeException("All Alliance Groups Full."); } /** * @param member */ public void removeMember(int memberObjectId) { allianceGroupForMember.get(memberObjectId).removeMember(memberObjectId); allianceGroupForMember.remove(memberObjectId); allianceMembers.remove(memberObjectId); // Check if Member was a Vice Captain if (viceCaptainObjectIds.contains(memberObjectId)) { viceCaptainObjectIds.remove(viceCaptainObjectIds.indexOf(memberObjectId)); } // Check if Member was Captain if (memberObjectId == this.captainObjectId) { // Check Vice Captain for replacement... if (viceCaptainObjectIds.size() > 0) { int newCaptain = viceCaptainObjectIds.get(0); viceCaptainObjectIds.remove(viceCaptainObjectIds.indexOf(newCaptain)); this.captainObjectId = newCaptain; } else if (allianceMembers.size() != 0) { // Pick first player in map PlayerAllianceMember newCaptain = allianceMembers.values().iterator().next(); this.captainObjectId = newCaptain.getObjectId(); } } AllianceService.getInstance().broadcastAllianceInfo(this, PlayerAllianceEvent.UPDATE); } /** * @param leader */ public void setLeader(int newLeaderObjectId) { if (viceCaptainObjectIds.contains(newLeaderObjectId)) { // If new leader is Vice, set old leader to Vice. viceCaptainObjectIds.remove(viceCaptainObjectIds.indexOf(newLeaderObjectId)); viceCaptainObjectIds.add(this.captainObjectId); } this.captainObjectId = newLeaderObjectId; } /** * @param viceLeader */ public void promoteViceLeader(int viceLeaderObjectId) { viceCaptainObjectIds.add(viceLeaderObjectId); } /** * @param viceLeader */ public void demoteViceLeader(int viceLeaderObjectId) { viceCaptainObjectIds.remove(viceCaptainObjectIds.indexOf(viceLeaderObjectId)); } /** * @return */ public PlayerAllianceMember getCaptain() { return getPlayer(getCaptainObjectId()); } /** * @return captainObjectId */ public int getCaptainObjectId() { return this.captainObjectId; } /** * @return viceCaptainObjectIds */ public List<Integer> getViceCaptainObjectIds() { return this.viceCaptainObjectIds; } /** * @param player * @return */ public int getAllianceIdFor(int playerObjectId) { if (!allianceGroupForMember.containsKey(playerObjectId)) return 0; else return allianceGroupForMember.get(playerObjectId).getAllianceId(); } /** * @param playerObjectId * @return member */ public PlayerAllianceMember getPlayer(int playerObjectId) { return allianceMembers.get(playerObjectId); } /** * @return alliance size */ public int size() { return getMembers().size(); } /** * @return */ public boolean isFull() { return (size() >= 24); } /** * @return */ public Collection<PlayerAllianceMember> getMembers() { return allianceMembers.values(); } /** * @param objectId * @return */ public boolean hasAuthority(int playerObjectId) { return (playerObjectId == captainObjectId || viceCaptainObjectIds.contains(playerObjectId)); } @Override public String getName() { return "Player Alliance"; } /** * @param playerObjectId * @param secondObjectId */ public void swapPlayers(int playerObjectId1, int playerObjectId2) { PlayerAllianceGroup group1 = allianceGroupForMember.get(playerObjectId1); PlayerAllianceGroup group2 = allianceGroupForMember.get(playerObjectId2); PlayerAllianceMember player1 = group1.removeMember(playerObjectId1); PlayerAllianceMember player2 = group2.removeMember(playerObjectId2); group1.addMember(player2); group2.addMember(player1); allianceGroupForMember.put(playerObjectId1, group2); allianceGroupForMember.put(playerObjectId2, group1); } /** * Designed to be able to move members while off-line. * * @param memberObjectId * @param allianceGroupId */ public void setAllianceGroupFor(int memberObjectId, int allianceGroupId) { PlayerAllianceGroup leavingGroup = allianceGroupForMember.get(memberObjectId); PlayerAllianceMember member = leavingGroup.getMemberById(memberObjectId); leavingGroup.removeMember(memberObjectId); PlayerAllianceGroup group = allianceGroups.get(allianceGroupId); if (group == null) { group = new PlayerAllianceGroup(this); group.setAllianceId(allianceGroupId); allianceGroups.put(allianceGroupId, group); } group.addMember(member); allianceGroupForMember.put(memberObjectId, group); } /** * @param objectId * @return */ public PlayerAllianceGroup getPlayerAllianceGroupForMember(int objectId) { return allianceGroupForMember.get(objectId); } /** * @param player */ public void onPlayerLogin(Player player) { allianceMembers.get(player.getObjectId()).onLogin(player); } /** * @param player */ public void onPlayerDisconnect(Player player) { PlayerAllianceMember allianceMember = allianceMembers.get(player.getObjectId()); allianceMember.onDisconnect(); for (PlayerAllianceMember member : allianceMembers.values()) { // Check offline if (member.isOnline()) { PacketSendUtility.sendPacket(member.getPlayer(), SM_SYSTEM_MESSAGE.STR_FORCE_HE_BECOME_OFFLINE(player.getName())); PacketSendUtility.sendPacket(member.getPlayer(), new SM_ALLIANCE_MEMBER_INFO(allianceMember, PlayerAllianceEvent.DISCONNECTED)); } } } /** * @param objectId * @return */ public Collection<PlayerAllianceMember> getMembersForGroup(int playerObjectId) { PlayerAllianceGroup group = allianceGroupForMember.get(playerObjectId); // TODO: This should not be null... if (group == null) return (new FastMap<Integer, PlayerAllianceMember>()).values(); return group.getMembers(); } }
true
cefcc5f571c83ac63dbc677563b7bdb49b456d2d
Java
lor6/tutorials
/axon/src/test/java/com/baeldung/axon/querymodel/OrderQueryServiceIntegrationTest.java
UTF-8
5,018
2.234375
2
[ "MIT" ]
permissive
package com.baeldung.axon.querymodel; import com.baeldung.axon.OrderApplication; import com.baeldung.axon.coreapi.events.OrderConfirmedEvent; import com.baeldung.axon.coreapi.events.OrderShippedEvent; import com.baeldung.axon.coreapi.events.ProductAddedEvent; import com.baeldung.axon.coreapi.events.ProductCountDecrementedEvent; import com.baeldung.axon.coreapi.events.ProductCountIncrementedEvent; import com.baeldung.axon.coreapi.queries.Order; import org.axonframework.eventhandling.gateway.EventGateway; import org.junit.jupiter.api.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import reactor.core.publisher.Flux; import reactor.test.StepVerifier; import java.util.Collections; import java.util.List; import java.util.UUID; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import static org.junit.jupiter.api.Assertions.*; @SpringBootTest(classes = OrderApplication.class) class OrderQueryServiceIntegrationTest { @Autowired OrderQueryService queryService; @Autowired EventGateway eventGateway; @Autowired OrdersEventHandler handler; private String orderId; private final String productId = "Deluxe Chair"; @BeforeEach void setUp() { orderId = UUID.randomUUID() .toString(); Order order = new Order(orderId); handler.reset(Collections.singletonList(order)); } @Test void givenOrderCreatedEventSend_whenCallingAllOrders_thenOneCreatedOrderIsReturned() throws ExecutionException, InterruptedException { List<OrderResponse> result = queryService.findAllOrders() .get(); assertEquals(1, result.size()); OrderResponse response = result.get(0); assertEquals(orderId, response.getOrderId()); assertEquals(OrderStatusResponse.CREATED, response.getOrderStatus()); assertTrue(response.getProducts() .isEmpty()); } @Test void givenOrderCreatedEventSend_whenCallingAllOrdersStreaming_thenOneOrderIsReturned() { Flux<OrderResponse> result = queryService.allOrdersStreaming(); StepVerifier.create(result) .assertNext(order -> assertEquals(orderId, order.getOrderId())) .expectComplete() .verify(); } @Test void givenThreeDeluxeChairsShipped_whenCallingAllShippedChairs_then234PlusTreeIsReturned() { Order order = new Order(orderId); order.getProducts() .put(productId, 3); order.setOrderShipped(); handler.reset(Collections.singletonList(order)); assertEquals(237, queryService.totalShipped(productId)); } @Test void givenOrdersAreUpdated_whenCallingOrderUpdates_thenUpdatesReturned() { ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); executor.schedule(this::addIncrementDecrementConfirmAndShip, 100L, TimeUnit.MILLISECONDS); try { StepVerifier.create(queryService.orderUpdates(orderId)) .assertNext(order -> assertTrue(order.getProducts() .isEmpty())) .assertNext(order -> assertEquals(1, order.getProducts() .get(productId))) .assertNext(order -> assertEquals(2, order.getProducts() .get(productId))) .assertNext(order -> assertEquals(1, order.getProducts() .get(productId))) .assertNext(order -> assertEquals(OrderStatusResponse.CONFIRMED, order.getOrderStatus())) .assertNext(order -> assertEquals(OrderStatusResponse.SHIPPED, order.getOrderStatus())) .thenCancel() .verify(); } finally { executor.shutdown(); } } private void addIncrementDecrementConfirmAndShip() { sendProductAddedEvent(); sendProductCountIncrementEvent(); sendProductCountDecrementEvent(); sendOrderConfirmedEvent(); sendOrderShippedEvent(); } private void sendProductAddedEvent() { ProductAddedEvent event = new ProductAddedEvent(orderId, productId); eventGateway.publish(event); } private void sendProductCountIncrementEvent() { ProductCountIncrementedEvent event = new ProductCountIncrementedEvent(orderId, productId); eventGateway.publish(event); } private void sendProductCountDecrementEvent() { ProductCountDecrementedEvent event = new ProductCountDecrementedEvent(orderId, productId); eventGateway.publish(event); } private void sendOrderConfirmedEvent() { OrderConfirmedEvent event = new OrderConfirmedEvent(orderId); eventGateway.publish(event); } private void sendOrderShippedEvent() { OrderShippedEvent event = new OrderShippedEvent(orderId); eventGateway.publish(event); } }
true
831a3749e7332aae177e5c78477e6d3de8871b3c
Java
juhyund/test
/kepco-model/src/main/java/com/nuri/kepco/mongo/model/ConnectivityStatisticsMonitor.java
UTF-8
1,536
2.09375
2
[]
no_license
package com.nuri.kepco.mongo.model; import java.util.Date; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; import lombok.Data; @Data @Document(collection="ConnectivityStatisticsMonitor") public class ConnectivityStatisticsMonitor { // 최종 통신 데이터만 가지고 있다. // device 별 rowdata는 한개 이다. @Id private String id; private String branchId; // branch id private String branchNm; // branch name private String parentBranchId; // branch id private String parentBranchNm; // branch name private String deviceId; private String deviceSerial; private String deviceStatus; // 단말상태 private String deviceStatusNm; private Integer rsrp; // Radio Signal Strength private Integer rsrq; // Link Quality private String ipAddress; // 모뎀의 IP 주소 (IPv6) private Integer cellId; // Serving Cell ID private Integer smnc; // Serving Mobile Network Code private Integer smcc; // Serving Mobile Country Code private Integer ssnr; // Signal SNR private Integer cpuUsage; // cpu private Integer ramUsage; // ram private String usageTime; // 20200224000000 private String saveTime; // 20200224000000 // 조회조건 private Date sdate; private Date edate; private int page; private int row; private long offset; public void setOffset(long offset) { this.offset = offset; } public long getOffset() { return (this.page - 1) * this.row; } }
true
d939c000eb6cbf0856f3fc477dd1e15e0fb09d54
Java
Izaquiel/ProjetoPOS
/src/main/java/entidades/Cidade.java
UTF-8
1,936
2.484375
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package entidades; import java.io.Serializable; import java.util.Objects; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; /** * * @author Joelanio */ @Entity @NamedQueries({@NamedQuery(name = "listaTodasCidades", query = "Select c From Cidade c"), @NamedQuery(name = "buscaCidadePorId", query = "Select c From Cidade c Where c.id = :id")}) public class Cidade implements Serializable{ @Id @GeneratedValue private long id; private String nomeCidade; public Cidade() { } public Cidade(String nomeCidade) { this.nomeCidade = nomeCidade; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getNomeCidade() { return nomeCidade; } public void setNomeCidade(String nomeCidade) { this.nomeCidade = nomeCidade; } @Override public int hashCode() { int hash = 7; hash = 59 * hash + (int) (this.id ^ (this.id >>> 32)); hash = 59 * hash + Objects.hashCode(this.nomeCidade); return hash; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Cidade other = (Cidade) obj; if (this.id != other.id) { return false; } if (!Objects.equals(this.nomeCidade, other.nomeCidade)) { return false; } return true; } }
true
8264056a7b1a6afeebbe371ab6ee19150845692d
Java
DinizEduardo/curso-kafka-alura
/service-email/src/main/java/br/com/alura/ecommerce/EmailService.java
UTF-8
1,231
2.46875
2
[]
no_license
package br.com.alura.ecommerce; import org.apache.kafka.clients.consumer.ConsumerConfig; import org.apache.kafka.clients.consumer.ConsumerRecord; import org.apache.kafka.common.serialization.StringDeserializer; import java.util.Map; public class EmailService { public static void main(String[] args) throws InterruptedException { var emailService = new br.com.alura.ecommerce.EmailService(); try(var service = new KafkaService(EmailService.class.getSimpleName(), "ECOMMERCE_SEND_EMAIL", emailService::parse, String.class, Map.of(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName()))){ service.run(); } } private void parse(ConsumerRecord<String, String> record) { System.out.println("============================================================="); System.out.println("Sending e-mail"); System.out.println("Key: " + record.key()); System.out.println("Value: " + record.value()); System.out.println("Offset: " + record.offset()); System.out.println("Done"); } }
true
6439b9591e6a9c9d461298a764f3c15325006f37
Java
Zarfoux/login-generator
/src/main/java/geco/PasswordGeneration.java
UTF-8
429
2.703125
3
[]
no_license
package geco; /** * * Class qui permet de generer Un mot de passe Aleatoire */ public class PasswordGeneration { public PasswordGeneration () { } public String RandomGeneration ( int taille ) { String mdp = ""; for ( int i= 0 ; i < taille ;i++ ) { mdp += ""+Math.random(); } return mdp; } }
true
a06e38b946d8b479e634ce2bca9ce0c7531c67c2
Java
pluk1/JavaRushTasks
/1.JavaSyntax/src/com/javarush/task/task09/task0923/Solution.java
UTF-8
1,839
3.8125
4
[]
no_license
package com.javarush.task.task09.task0923; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; /* Гласные и согласные */ public class Solution { public static char[] vowels = new char[]{'а', 'я', 'у', 'ю', 'и', 'ы', 'э', 'е', 'о', 'ё'}; public static void main(String[] args) throws Exception { //напишите тут ваш код BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); String inputStr = reader.readLine(); ArrayList<Character> vowelArr = new ArrayList<>(); ArrayList<Character> notVowelsArr = new ArrayList<>(); String[] wordsArr = inputStr.split("\\s"); for (int i = 0; i < wordsArr.length; i++) { for (int j = 0; j < wordsArr[i].length(); j++) { char tmpChar = wordsArr[i].charAt(j); if (isVowel(tmpChar)) { vowelArr.add(tmpChar); } else if (isVowel(tmpChar) == false && tmpChar != ' ') { notVowelsArr.add(tmpChar); } } } for (Character ch : vowelArr) { System.out.print(ch + " "); } System.out.println(); for (Character ch : notVowelsArr) { System.out.print(ch + " "); } } // метод проверяет, гласная ли буква public static boolean isVowel(char c) { c = Character.toLowerCase(c); // приводим символ в нижний регистр - от заглавных к строчным буквам for (char d : vowels) // ищем среди массива гласных { if (c == d) return true; } return false; } }
true
7651406644366d90d08ca176179f0e0b7d3ad9db
Java
6500gearcats/Tin-Reinforced-Concrete-2020
/src/frc/team6500/trc/sensor/TRCnavXGyro.java
UTF-8
5,192
2.5625
3
[]
no_license
package frc.team6500.trc.sensor; import com.kauailabs.navx.frc.AHRS; import edu.wpi.first.wpilibj.I2C; import edu.wpi.first.wpilibj.SPI; import edu.wpi.first.wpilibj.SerialPort; import edu.wpi.first.wpilibj.interfaces.Gyro; public class TRCnavXGyro extends AHRS implements Gyro { /** * Constructs the AHRS class using SPI communication, overriding the * default update rate with a custom rate which may be from 4 to 200, * representing the number of updates per second sent by the sensor. *<p> * This constructor should be used if communicating via SPI. *<p> * Note that increasing the update rate may increase the * CPU utilization. *<p> * @param spi_port_id SPI Port to use * @param update_rate_hz Custom Update Rate (Hz) */ public TRCnavXGyro(SPI.Port spi_port_id, byte update_rate_hz) { super(spi_port_id, update_rate_hz); } /** * The AHRS class provides an interface to AHRS capabilities * of the KauaiLabs navX Robotics Navigation Sensor via SPI, I2C and * Serial (TTL UART and USB) communications interfaces on the RoboRIO. * * The AHRS class enables access to basic connectivity and state information, * as well as key 6-axis and 9-axis orientation information (yaw, pitch, roll, * compass heading, fused (9-axis) heading and magnetic disturbance detection. * * Additionally, the ARHS class also provides access to extended information * including linear acceleration, motion detection, rotation detection and sensor * temperature. * * If used with the navX Aero, the AHRS class also provides access to * altitude, barometric pressure and pressure sensor temperature data * * This constructor allows the specification of a custom SPI bitrate, in bits/second. * * @param spi_port_id SPI Port to use * @param spi_bitrate SPI bitrate (Maximum: 2,000,000) * @param update_rate_hz Custom Update Rate (Hz) */ public TRCnavXGyro(SPI.Port spi_port_id, int spi_bitrate, byte update_rate_hz) { super(spi_port_id, spi_bitrate, update_rate_hz); } /** * Constructs the AHRS class using I2C communication, overriding the * default update rate with a custom rate which may be from 4 to 200, * representing the number of updates per second sent by the sensor. *<p> * This constructor should be used if communicating via I2C. *<p> * Note that increasing the update rate may increase the * CPU utilization. *<p> * @param i2c_port_id I2C Port to use * @param update_rate_hz Custom Update Rate (Hz) */ public TRCnavXGyro(I2C.Port i2c_port_id, byte update_rate_hz) { super(i2c_port_id, update_rate_hz); } /** * Constructs the AHRS class using serial communication, overriding the * default update rate with a custom rate which may be from 4 to 200, * representing the number of updates per second sent by the sensor. *<p> * This constructor should be used if communicating via either * TTL UART or USB Serial interface. *<p> * Note that the serial interfaces can communicate either * processed data, or raw data, but not both simultaneously. * If simultaneous processed and raw data are needed, use * one of the register-based interfaces (SPI or I2C). *<p> * Note that increasing the update rate may increase the * CPU utilization. *<p> * @param serial_port_id SerialPort to use * @param data_type either kProcessedData or kRawData * @param update_rate_hz Custom Update Rate (Hz) */ public TRCnavXGyro(SerialPort.Port serial_port_id, SerialDataType data_type, byte update_rate_hz) { super(serial_port_id, data_type, update_rate_hz); } /** * Constructs the AHRS class using SPI communication and the default update rate. *<p> * This constructor should be used if communicating via SPI. */ public TRCnavXGyro() { super(); } /** * Constructs the AHRS class using SPI communication and the default update rate. *<p> * This constructor should be used if communicating via SPI. *<p> * @param spi_port_id SPI port to use. */ public TRCnavXGyro(SPI.Port spi_port_id) { super(spi_port_id); } /** * Constructs the AHRS class using I2C communication and the default update rate. *<p> * This constructor should be used if communicating via I2C. *<p> * @param i2c_port_id I2C port to use */ public TRCnavXGyro(I2C.Port i2c_port_id) { super(i2c_port_id); } /** * Constructs the AHRS class using serial communication and the default update rate, * and returning processed (rather than raw) data. *<p> * This constructor should be used if communicating via either * TTL UART or USB Serial interface. *<p> * @param serial_port_id SerialPort to use */ public TRCnavXGyro(SerialPort.Port serial_port_id) { super(serial_port_id); } /** * On navX, the gyro must be calibrated manually. This mearly exists to satisfy Gyro, but will only print * that automated calibration is not supported */ public void calibrate() { System.out.println("Automated calibration not supported on navX."); } }
true
5f2f1ad4fa142d1bcb8a99e55caa95605b86e868
Java
sebastienblanc/jbosstools-forge
/plugins/org.jboss.tools.aesh.core/src/org/jboss/tools/aesh/core/ansi/EraseInLine.java
UTF-8
283
2.140625
2
[]
no_license
package org.jboss.tools.aesh.core.ansi; public class EraseInLine extends ControlSequence { public EraseInLine(String controlSequenceString) { super(controlSequenceString); } @Override public ControlSequenceType getType() { return ControlSequenceType.ERASE_IN_LINE; } }
true
793a3c6c810181593c18ed3b87dc148a5f90df5c
Java
belizwp/android-basic-testing
/app/src/androidTest/java/cc/somkiat/basicunittesting/MainActivityTest.java
UTF-8
4,160
1.960938
2
[]
no_license
package cc.somkiat.basicunittesting; import android.support.test.rule.ActivityTestRule; import android.support.test.runner.AndroidJUnit4; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import static android.support.test.espresso.Espresso.onView; import static android.support.test.espresso.action.ViewActions.click; import static android.support.test.espresso.action.ViewActions.closeSoftKeyboard; import static android.support.test.espresso.action.ViewActions.replaceText; import static android.support.test.espresso.action.ViewActions.scrollTo; import static android.support.test.espresso.assertion.ViewAssertions.matches; import static android.support.test.espresso.matcher.RootMatchers.withDecorView; import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed; import static android.support.test.espresso.matcher.ViewMatchers.withId; import static android.support.test.espresso.matcher.ViewMatchers.withText; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.not; @RunWith(AndroidJUnit4.class) public class MainActivityTest { @Rule public ActivityTestRule<MainActivity> mActivityTestRule = new ActivityTestRule<>(MainActivity.class); @Test public void saveEmptyNameAndEmptyEmail() { onView(withId(R.id.userNameInput)).perform(scrollTo(), replaceText(""), closeSoftKeyboard()); onView(withId(R.id.emailInput)).perform(scrollTo(), replaceText(""), closeSoftKeyboard()); onView(withId(R.id.saveButton)).perform(scrollTo(), click()); checkToastDisplayed("Name is empty"); } @Test public void saveValidNameAndEmptyEmail() { onView(withId(R.id.userNameInput)).perform(scrollTo(), replaceText("Nakarin Kakanumporn"), closeSoftKeyboard()); onView(withId(R.id.emailInput)).perform(scrollTo(), replaceText(""), closeSoftKeyboard()); onView(withId(R.id.saveButton)).perform(scrollTo(), click()); checkToastDisplayed("Email is empty"); } @Test public void saveInvalidNameAndEmptyEmail() { onView(withId(R.id.userNameInput)).perform(scrollTo(), replaceText("[Since1996] Nakarin Kakanumporn"), closeSoftKeyboard()); onView(withId(R.id.emailInput)).perform(scrollTo(), replaceText(""), closeSoftKeyboard()); onView(withId(R.id.saveButton)).perform(scrollTo(), click()); checkToastDisplayed("Name contains non alphabet character"); } @Test public void saveMixLangInNameAndEmptyEmail() { onView(withId(R.id.userNameInput)).perform(scrollTo(), replaceText("Nakarin คัคนัมพร"), closeSoftKeyboard()); onView(withId(R.id.emailInput)).perform(scrollTo(), replaceText(""), closeSoftKeyboard()); onView(withId(R.id.saveButton)).perform(scrollTo(), click()); checkToastDisplayed("Name contains mix language"); } @Test public void saveValidNameAndInvaliEmail() { onView(withId(R.id.userNameInput)).perform(scrollTo(), replaceText("Nakarin Kakanumporn"), closeSoftKeyboard()); onView(withId(R.id.emailInput)).perform(scrollTo(), replaceText("belizwp@live.123"), closeSoftKeyboard()); onView(withId(R.id.saveButton)).perform(scrollTo(), click()); checkToastDisplayed("Email is invalid"); } @Test public void saveValidNameAndValiEmail() { onView(withId(R.id.userNameInput)).perform(scrollTo(), replaceText("Nakarin Kakanumporn"), closeSoftKeyboard()); onView(withId(R.id.emailInput)).perform(scrollTo(), replaceText("belizwp@live.com"), closeSoftKeyboard()); onView(withId(R.id.saveButton)).perform(scrollTo(), click()); checkToastDisplayed("Save"); } @Test public void revert() { onView(withId(R.id.revertButton)).perform(scrollTo(), click()); onView(withId(R.id.userNameInput)).check(matches(withText(""))); onView(withId(R.id.emailInput)).check(matches(withText(""))); checkToastDisplayed("Revert"); } private void checkToastDisplayed(String text) { onView(withText(text)) .inRoot(withDecorView(not(is(mActivityTestRule.getActivity().getWindow().getDecorView())))) .check(matches(isDisplayed())); } }
true
7e8f7a7ee225e789291f506dd9fc2ae88ebf0217
Java
Sahil-Rizvi/LeaveWebApp
/src/main/java/com/sahil/repositories/EmployeeRepository.java
UTF-8
1,120
2.078125
2
[]
no_license
package com.sahil.repositories; import java.util.List; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import com.sahil.entities.DepartmentEntity; import com.sahil.entities.DesignationEntity; import com.sahil.entities.EmployeeEntity; @Repository public interface EmployeeRepository extends JpaRepository<EmployeeEntity,String>{ public List<EmployeeEntity> findByManager(EmployeeEntity manager); public EmployeeEntity findByEmployeeCodeAndPassword(EmployeeEntity employeeEntity,String password); //@Query("from employee_details e where e.departmentEntity.name = :managerCode and l.leaveStatus = :status and l.approvedOn >= :fromDate and l.approvedOn <= :toDate") public Page<EmployeeEntity> findByDepartmentEntity(DepartmentEntity department,Pageable pageable); public List<EmployeeEntity> findByDepartmentEntity(DepartmentEntity department); public List<EmployeeEntity> findByDesignationEntity(DesignationEntity designationEntity); }
true