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
d40115a7bb0b8c78f349db76c24c1668ece9319f
Java
lukassaul/IBEX-LO-Flight-Pha-GUI
/Chopper.java
UTF-8
989
3.171875
3
[]
no_license
import java.util.Random; public class Chopper { public static int skipLines = 35; public int factor = 10; public Random r; public Chopper(String fn, int factor) { r = new Random(); this.factor = factor; file inFile = new file(fn); file outFile = new file(fn.substring(0,fn.length()-4)+"_choppedBy_"+factor+".txt"); inFile.initRead(); outFile.initWrite(false); String line = ""; for (int i=0; i<skipLines; i++) { line = inFile.readLine(); outFile.write(line+"\n"); } while ((line=inFile.readLine())!=null) { // until end of file int num = r.nextInt(factor); line = inFile.readLine(); if (num==1) outFile.write(line+"\n"); } outFile.closeWrite(); System.out.println("completed chopping by " + factor + " of " + fn); } public static final void main(String[] args) { try { int ff = Integer.parseInt(args[1]); Chopper c = new Chopper(args[0],ff); } catch (Exception e) { e.printStackTrace(); } } }
true
c207e4448594085f8f3e83eb83ff928fe18c86b5
Java
liuyiyou/cn.liuyiyou.dp
/src/main/java/cn/liuyiyou/dp/structural/decorator/StringDisplay.java
UTF-8
639
3.21875
3
[]
no_license
package cn.liuyiyou.dp.structural.decorator; /** * User: liuyiyou * Date: 14-8-11 * Time: 下午3:57 */ public class StringDisplay extends Display { private String string; public StringDisplay(String string) { this.string = string; } @Override int getColumns() { return string.getBytes().length; } @Override int getRows() { return 1; //To change body of implemented methods use File | Settings | File Templates. } @Override String getRowText(int row) { if (row==0){ return string; }else { return null; } } }
true
04af6206c42da853b00b4af076b80fa473e3eb6b
Java
joao-de-melo/xoai
/xoai-data-provider/src/main/java/org/dspace/xoai/dataprovider/util/PartialList.java
UTF-8
2,099
2.390625
2
[ "BSD-3-Clause" ]
permissive
/* * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.xoai.dataprovider.util; import java.util.AbstractCollection; import java.util.Collection; import java.util.Collections; import java.util.Iterator; public class PartialList<T> extends AbstractCollection<T> { public static <T> PartialList<T> middleIncomplete(Collection<T> items, long total, long offset) { return new PartialList<T>(items, total, offset, Type.INCOMPLETE, true); } public static <T> PartialList<T> lastIncomplete(Collection<T> items, long total, long offset) { return new PartialList<T>(items, total, offset, Type.INCOMPLETE, false); } public static <T> PartialList<T> complete(Collection<T> items, long total, long offset) { return new PartialList<T>(items, total, offset, Type.COMPLETE, false); } public static <T> PartialList<T> empty() { return new PartialList<T>(Collections.<T>emptyList(), 0, 0, Type.COMPLETE, false); } private final Collection<T> items; private final long total; private final long offset; private final Type type; private final boolean hasMore; private PartialList(Collection<T> items, long total, long offset, Type type, boolean hasMore) { this.items = items; this.total = total; this.offset = offset; this.type = type; this.hasMore = hasMore; } public Collection<T> getItems() { return items; } public long getTotal() { return total; } public long getOffset() { return offset; } public Type getType() { return type; } public boolean isHasMore() { return hasMore; } @Override public Iterator<T> iterator() { return items.iterator(); } @Override public int size() { return items.size(); } public enum Type { COMPLETE, INCOMPLETE } }
true
9fa4f92cd699047d7ce58da7278abd7271de0020
Java
mio4kon/mio-lyc
/core-sdk/src/main/java/mio/kon/sdk/support/fragment/CoreBaseFragment.java
UTF-8
6,439
2.34375
2
[]
no_license
package mio.kon.sdk.support.fragment; import android.content.Context; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import mio.kon.sdk.support.adapter.BaseRecyclerAdapter; import mio.kon.sdk.util.LogUtils; /** * Created by mio on 15-5-22. * 封装一些用于复用的Fragment */ public class CoreBaseFragment extends Fragment { private Context ctx; private FragmentType mFragmentType; enum FragmentType { COMMON_FRAMENT, //普通的,啥也不做 REFRESH_LIST_FRAGMENT,//带有下拉刷新的Fragment ENDLESS_REFRESH_LIST_FRAMENT //带有下拉刷新 上拉加载更多的Fragment } /** * ~~~~~~~~~~~~~IRefreshListFragment START~~~~~~~~~~~~~~~~ * */ private RecyclerView mRecyclerView; private SwipeRefreshLayout mSwipeRefreshLayout; private RecyclerView.Adapter mAdapter; private LinearLayoutManager mLayoutManager; /** ~~~~~~~~~~~~~IRefreshListFragment END~~~~~~~~~~~~~~~~ **/ /** * ~~~~~~~~~~~~~IEndlessRefreshListFragment START~~~~~~~~~~~~~~~~ * */ private EndlessScrollListner mEndlessScrollListner; private boolean isLoadingMore = false; /** * ~~~~~~~~~~~~~IEndlessRefreshListFragment END~~~~~~~~~~~~~~~~ * */ @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate (savedInstanceState); mFragmentType = FragmentType.COMMON_FRAMENT; if (this instanceof IRefreshListFragment) { mFragmentType = FragmentType.REFRESH_LIST_FRAGMENT; } if (this instanceof IEndlessRefreshListFragment) { mFragmentType = FragmentType.ENDLESS_REFRESH_LIST_FRAMENT; } } @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { ctx = getActivity (); if (mFragmentType == FragmentType.REFRESH_LIST_FRAGMENT || mFragmentType == FragmentType.ENDLESS_REFRESH_LIST_FRAMENT) { mSwipeRefreshLayout = new SwipeRefreshLayout (ctx); mRecyclerView = new RecyclerView (ctx); mRecyclerView.setId (android.R.id.list); mSwipeRefreshLayout.addView (mRecyclerView, new FrameLayout. LayoutParams (ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); mLayoutManager = new LinearLayoutManager (ctx); mRecyclerView.setLayoutManager (mLayoutManager); //设置LayoutManager mSwipeRefreshLayout.setLayoutParams (new ViewGroup. LayoutParams (ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); return mSwipeRefreshLayout; } return super.onCreateView (inflater, container, savedInstanceState); } /** * 提供设置Adapter * <P>确保该Fragment实现了{@link IRefreshListFragment}</P> * * @param adapter */ public void setRecyclerAdapter(RecyclerView.Adapter adapter) { if (mFragmentType == FragmentType.COMMON_FRAMENT) { return; } mAdapter = adapter; if (mRecyclerView == null) { return; } mRecyclerView.setAdapter (mAdapter); if (mFragmentType == FragmentType.ENDLESS_REFRESH_LIST_FRAMENT) { mEndlessScrollListner = new EndlessScrollListner (); mRecyclerView.setOnScrollListener (mEndlessScrollListner); } } /** * 设置是否显示刷新 * <P>确保该Fragment实现了{@link IRefreshListFragment}</P> * * @param refreshing */ public void setRefreshing(boolean refreshing) { mSwipeRefreshLayout.setRefreshing (refreshing); //如何是上拉家在更多时,要还原isLoadingMore isLoadingMore = false; } /** * 设置刷新监听器 * <P>确保该Fragment实现了{@link IRefreshListFragment}</P> * * @param listener */ public void setOnRefreshListener(SwipeRefreshLayout.OnRefreshListener listener) { mSwipeRefreshLayout.setOnRefreshListener (listener); } /** * 设置SwipeRefreshLayout刷新样式 * <P>确保该Fragment实现了{@link IRefreshListFragment}</P> * * @param colorRes1 * @param colorRes2 * @param colorRes3 * @param colorRes4 */ public void setColorSchemeResources(int colorRes1, int colorRes2, int colorRes3, int colorRes4) { mSwipeRefreshLayout.setColorSchemeResources (colorRes1, colorRes2, colorRes3, colorRes4); } /** * 实现item点击事件 * <P>确保该Fragment实现了{@link IRefreshListFragment}</P> * <P>使用之前确保Adapter是继承{@link BaseRecyclerAdapter}</P> */ public void onItemClick(View itemView, int position) { if (mAdapter instanceof BaseRecyclerAdapter) { ((BaseRecyclerAdapter) mAdapter).onItemClick (itemView, position); } } /** 下拉加载更多的滑动监听 **/ class EndlessScrollListner extends RecyclerView.OnScrollListener { @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { super.onScrolled (recyclerView, dx, dy); if (mLayoutManager instanceof LinearLayoutManager) { int lastItemCount = ((LinearLayoutManager) mLayoutManager).findLastVisibleItemPosition (); int totaltemCount = mAdapter.getItemCount (); LogUtils._d ("lastItemCount:" + lastItemCount + "=====totaltemCount:" + totaltemCount); if (totaltemCount - lastItemCount == 1 && dy > 0) { if (isLoadingMore) { //正在加载 LogUtils._d ("正在加载,请不要急啊!"); } else { //加载更多 mSwipeRefreshLayout.setRefreshing (true); ((IEndlessRefreshListFragment)CoreBaseFragment.this).loadMoreData (); } } } } } }
true
19a9dde70fa5dde64d740c7ff603beea60a7308e
Java
streeck/compiladores
/src/AST/IfStatement.java
UTF-8
613
2.609375
3
[]
no_license
/* ------------------------------ Charles David de Moraes RA: 489662 Vitor Kusiaki RA: 408140 ------------------------------ */ package AST; import java.util.ArrayList; public class IfStatement extends Statement { final private ExpressionStatement expression; final private ArrayList<Statement> thenStatements; final private ArrayList<Statement> elseStatements; public IfStatement(ExpressionStatement expression, ArrayList<Statement> thenStatements, ArrayList<Statement> elseStatements) { this.expression = expression; this.thenStatements = thenStatements; this.elseStatements = elseStatements; } }
true
2a269b2986ef5fd0ea18c34c6b8b0a465aea06be
Java
jaceyca/CS122
/src/edu/caltech/nanodb/indexes/IndexUtils.java
UTF-8
16,175
2.640625
3
[]
no_license
package edu.caltech.nanodb.indexes; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import edu.caltech.nanodb.expressions.TupleLiteral; import edu.caltech.nanodb.relations.ColumnRefs; import edu.caltech.nanodb.relations.ColumnInfo; import edu.caltech.nanodb.relations.ColumnType; import edu.caltech.nanodb.relations.ForeignKeyColumnRefs; import edu.caltech.nanodb.relations.ForeignKeyValueChangeOption; import edu.caltech.nanodb.relations.SQLDataType; import edu.caltech.nanodb.relations.Schema; import edu.caltech.nanodb.relations.SchemaNameException; import edu.caltech.nanodb.relations.TableSchema; import edu.caltech.nanodb.relations.Tuple; import edu.caltech.nanodb.storage.FilePointer; import edu.caltech.nanodb.storage.HashedTupleFile; import edu.caltech.nanodb.storage.PageTuple; import edu.caltech.nanodb.storage.SequentialTupleFile; import edu.caltech.nanodb.storage.TupleFile; /** * This class provides a number of very useful utility operations that make it * easier to create and work with indexes. */ public class IndexUtils { /** * This method takes the schema of a table, and a description of an index, * and it builds the schema that the index should have. This includes all * of the columns referenced by the index in the order that the index * references them, and it also includes a <tt>#TUPLE_PTR</tt> column so * the index can reference columns in the table. * * @param tableSchema the schema of the table that the index is for * @param indexDesc a specification of the index * * @return the schema of the index */ public static TableSchema makeIndexSchema(TableSchema tableSchema, ColumnRefs indexDesc) { if (tableSchema == null) throw new IllegalArgumentException("tableSchema cannot be null"); if (indexDesc == null) throw new IllegalArgumentException("indexDesc cannot be null"); // Get the name of the table that the index will be built against. // (And, make sure there is only one table name in the schema...) Set<String> tableNames = tableSchema.getTableNames(); if (tableSchema.getTableNames().size() != 1) { throw new IllegalArgumentException( "Schema must have exactly one table name"); } String tableName = tableNames.iterator().next(); // Add all the referenced columns from the table schema. TableSchema indexSchema = new TableSchema(); for (int iCol : indexDesc.getCols()) indexSchema.addColumnInfo(tableSchema.getColumnInfo(iCol)); // Add a tuple-pointer field for the index as well. ColumnInfo filePtr = new ColumnInfo("#TUPLE_PTR", tableName, new ColumnType(SQLDataType.FILE_POINTER)); indexSchema.addColumnInfo(filePtr); return indexSchema; } /** * This method constructs a <tt>ColumnIndexes</tt> object that includes * the columns named in the input list. Note that this method <u>does * not</u> update the schema stored on disk, or create any other * supporting files. * * @param columnNames a list of column names that are in the index * * @return a new <tt>ColumnIndexes</tt> object with the indexes of the * columns stored in the object * * @throws SchemaNameException if a column-name cannot be found, or if a * column-name is ambiguous (unlikely), or if a column is * specified multiple times in the input list. * / public static ColumnRefs makeIndex(Schema tableSchema, List<String> columnNames) { if (columnNames == null) throw new IllegalArgumentException("columnNames must be specified"); if (columnNames.isEmpty()) { throw new IllegalArgumentException( "columnNames must specify at least one column"); } return new ColumnRefs(tableSchema.getColumnIndexes(columnNames)); } /** * This method constructs a {@code KeyColumnRefs} object that includes the * columns named in the input list. Note that this method <u>does not</u> * update the schema stored on disk, or create any other supporting files. * * @param columnNames a list of column names that are in the key * * @return a new {@code KeyColumnRefs} object with the indexes of the * columns stored in the object * * @throws SchemaNameException if a column-name cannot be found, or if a * column-name is ambiguous (unlikely), or if a column is * specified multiple times in the input list. * / public static KeyColumnRefs makeKey(Schema tableSchema, List<String> columnNames) { if (columnNames == null) throw new IllegalArgumentException("columnNames must be specified"); if (columnNames.isEmpty()) { throw new IllegalArgumentException( "columnNames must specify at least one column"); } int[] colIndexes = tableSchema.getColumnIndexes(columnNames); return new KeyColumnRefs(colIndexes); } */ /** * This method constructs a {@link ForeignKeyColumnRefs} object that * includes the columns named in the input list, as well as the referenced * table and column names. Note that this method <u>does not</u> update * the schema stored on disk, or create any other supporting files. * * @param columnNames a list of column names that are in the key * * @param refTableName the table referenced by this key * * @param refTableSchema the schema of the table referenced by this key * * @param refColumnNames the columns in the referenced table that this * table's columns reference * * @param onDelete the {@link ForeignKeyValueChangeOption} for ON DELETE * * @param onUpdate the {@link ForeignKeyValueChangeOption} for ON UPDATE * * @return a new <tt>ForeignKeyColumns</tt> object with the indexes of the * columns stored in the object * * @throws SchemaNameException if a column-name cannot be found, or if a * column-name is ambiguous (unlikely), or if a column is specified * multiple times in the input list. */ public static ForeignKeyColumnRefs makeForeignKey(TableSchema tableSchema, List<String> columnNames, String refTableName, TableSchema refTableSchema, List<String> refColumnNames, ForeignKeyValueChangeOption onDelete, ForeignKeyValueChangeOption onUpdate) { if (tableSchema == null) throw new IllegalArgumentException("tableSchema must be specified"); if (columnNames == null) throw new IllegalArgumentException("columnNames must be specified"); if (refTableName == null) throw new IllegalArgumentException("refTableName must be specified"); if (refTableSchema == null) throw new IllegalArgumentException("refTableSchema must be specified"); if (refColumnNames == null) throw new IllegalArgumentException("refColumnNames must be specified"); if (columnNames.isEmpty()) { throw new IllegalArgumentException( "columnNames must specify at least one column"); } if (columnNames.size() != refColumnNames.size()) { throw new IllegalArgumentException("columnNames and " + "refColumnNames must specify the same number of columns"); } int[] colIndexes = tableSchema.getColumnIndexes(columnNames); int[] refColIndexes = refTableSchema.getColumnIndexes(refColumnNames); if (!refTableSchema.hasKeyOnColumns(new ColumnRefs(refColIndexes))) { throw new SchemaNameException(String.format("Referenced columns " + "%s in table %s are not a primary or candidate key", refColumnNames, refTableName)); } ArrayList<ColumnInfo> myColInfos = tableSchema.getColumnInfos(colIndexes); ArrayList<ColumnInfo> refColInfos = refTableSchema.getColumnInfos(refColIndexes); // Check if the column relations are the same types for (int i = 0; i < myColInfos.size(); i++) { ColumnType myType = myColInfos.get(i).getType(); ColumnType refType = refColInfos.get(i).getType(); if (!myType.equals(refType)) { throw new IllegalArgumentException("columns in " + "child and parent tables of the foreign key must be " + "of the same type!"); } } // The onDelete and onUpdate values could be null if they are // unspecified in the constructor. They are set to // ForeignKeyValueChangeOption.RESTRICT as a default in this case in // the constructor for ForeignKeyColumnIndexes. return new ForeignKeyColumnRefs(colIndexes, refTableName, refColIndexes, onDelete, onUpdate); } /** * <p> * This helper function creates a {@link TupleLiteral} that holds the * key-values necessary for probing, storing or deleting a tuple in a * table's index. <b>Note that this operation only works for a tuple that * has the same schema as the index's owning table; it is not a general * operation for creating search-keys on a particular index.</b> * </p> * <p> * This method can be used to find a specific tuple in a table by * including a file-pointer to the tuple in the table. (For example, this * is necessary when a tuple is being deleted from a table, so that the * index can be updated to reflect the removal of that specific tuple.) * This functionality requires that the tuple's class implement * {@link Tuple#getExternalReference}. * </p> * <p> * If this specific feature is not required, any kind of {@link Tuple} * can be passed as an argument, as long as it has the same schema as * the table that owns the index. * </p> * * @param columnRefs the columns that the index is built on * * @param tuple the tuple from the original table, that the key will be * created from. * * @param findExactTuple if {@code true}, this method will include the * {@code tuple}'s file-pointer so that the exact tuple can be * found in the index. * * @return a tuple-literal that can be used for storing, looking up, or * deleting the specific tuple {@code ptup}. */ public static TupleLiteral makeTableSearchKey(ColumnRefs columnRefs, Tuple tuple, boolean findExactTuple) { // Build up a new tuple-literal containing the search key. TupleLiteral searchKeyVal = new TupleLiteral(); for (int i = 0; i < columnRefs.size(); i++) searchKeyVal.addValue(tuple.getColumnValue(columnRefs.getCol(i))); if (findExactTuple) { // Include the file-pointer as the last value in the tuple, so // that all key-values are unique in the index. searchKeyVal.addValue(tuple.getExternalReference()); } return searchKeyVal; } /** * Given an index tuple-file and a search key, this method attempts to * find the first tuple in the index that matches the search key. * * @param key the search-key value to probe the index with * * @param idxTupleFile the index to probe with the search-key * * @return the first matching tuple in the index, or {@code null} if * no matching tuple could be found * * @throws IOException if an IO error occurs during the operation */ public static PageTuple findTupleInIndex(Tuple key, TupleFile idxTupleFile) throws IOException { PageTuple idxPageTup; if (idxTupleFile instanceof SequentialTupleFile) { SequentialTupleFile seqTupleFile = (SequentialTupleFile) idxTupleFile; idxPageTup = (PageTuple) seqTupleFile.findFirstTupleEquals(key); } else if (idxTupleFile instanceof HashedTupleFile) { HashedTupleFile hashTupleFile = (HashedTupleFile) idxTupleFile; idxPageTup = (PageTuple) hashTupleFile.findFirstTupleEquals(key); } else { throw new IllegalStateException("Index files must " + "be sequential or hashing tuple files."); } return idxPageTup; } /* public static void setSearchKeyStorageSize(IndexInfo indexInfo, TupleLiteral searchKeyVal) { List<ColumnInfo> colInfos = indexInfo.getIndexSchema(); int storageSize = PageTuple.getTupleStorageSize(colInfos, searchKeyVal); searchKeyVal.setStorageSize(storageSize); } */ /** * This method performs a basic but important verification, that every * tuple in a table is referenced once by the table's index, and no index * entry has a tuple-reference to a non-existent tuple. This * functionality is of course greatly supplemented by tuple-file formats * that implement the {@link edu.caltech.nanodb.storage.TupleFile#verify} * method, which does complete verification of the internal structure of * a particular kind of tuple file. * * @param tableTupleFile the tuple file holding the table data * @param indexTupleFile the tuple file holding the index data * * @return A list of string error messages identified during the * verification scan. This list will be empty if there are no * errors. * * @throws IOException */ public static List<String> verifyIndex(TupleFile tableTupleFile, TupleFile indexTupleFile) throws IOException { ArrayList<String> errors = new ArrayList<>(); HashSet<FilePointer> tableTuples = new HashSet<>(); HashSet<FilePointer> indexTuples = new HashSet<>(); HashSet<FilePointer> referencedTableTuples = new HashSet<>(); Tuple tup; // Scan through all tuples in the table file, and record the file // pointer to each one. tup = tableTupleFile.getFirstTuple(); while (tup != null) { if (!tableTuples.add(tup.getExternalReference())) { // This should never happen. throw new IllegalStateException("The impossible has " + "happened: two tuples had the same external reference!"); } tup = tableTupleFile.getNextTuple(tup); } // Scan through all entries in the index, and record the file pointer // stored in each index record. Schema indexSchema = indexTupleFile.getSchema(); int iCol = indexSchema.getColumnIndex("#TUPLE_PTR"); tup = indexTupleFile.getFirstTuple(); while (tup != null) { FilePointer fptr = (FilePointer) tup.getColumnValue(iCol); if (indexTuples.contains(fptr)) { errors.add("Tuple at location " + fptr + " appears multiple times in the index."); } if (!tableTuples.contains(fptr)) { errors.add( "Index references a nonexistent tuple at location " + fptr + "."); } indexTuples.add(fptr); referencedTableTuples.add(fptr); tup = indexTupleFile.getNextTuple(tup); } HashSet<FilePointer> diff = new HashSet<>(tableTuples); diff.removeAll(referencedTableTuples); if (!diff.isEmpty()) { for (FilePointer fptr : diff) { errors.add("Tuple at location " + fptr + " wasn't referenced by the index."); } } return errors; } }
true
5ee5e3e410afe07e8dad4ad30bac025c7a710129
Java
lilingqian/DELULJQ
/app/src/main/java/com/example/lenovo/de_lu_ljq/presenter/RegPresenter.java
UTF-8
936
2.1875
2
[]
no_license
package com.example.lenovo.de_lu_ljq.presenter; import com.example.lenovo.de_lu_ljq.view.MyView; import com.example.lenovo.de_lu_ljq.bean.RegBean; import com.example.lenovo.de_lu_ljq.model.ModelCallBack; import com.example.lenovo.de_lu_ljq.model.RegModel; public class RegPresenter { RegModel regModel = new RegModel(); MyView.RegView regView; public RegPresenter(MyView.RegView regView) { this.regView = regView; } public void getData(String tel, String pwd) { regModel.getRegData(tel,pwd, new ModelCallBack.RegCallBack() { @Override public void success(RegBean regBean) { regView.sucess(regBean); System.out.println("注册p数据:"+regBean.toString()); } @Override public void failed(Throwable code) { System.out.println("注册p错误:"+code); } }); } }
true
b8d55476bca2c2334fa78120aca38ea3d5ebb395
Java
David-bfg/HospitalWeb-Services
/MayoWS/src/com/mayo/db/StudyRest.java
UTF-8
3,050
2.71875
3
[]
no_license
package com.mayo.db; import java.util.Date; import java.util.List; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; public class StudyRest { SessionFactory session; public static StudyRest instance = null; private StudyRest() { session = HibernateUtil.getSessionFactory(); } public void close() { session.close(); } public static StudyRest getInstance() { if (instance==null) { instance = new StudyRest(); } return instance; } public Study getWithName(String studyName) { Session sess = session.getCurrentSession(); Transaction tx = sess.beginTransaction(); List <Study> pojoList = sess.createQuery("from Study ad where ad.studyName like \'%"+studyName+"%\'").list(); if(pojoList.size()==0) { tx.commit(); return null; } Study returnStudy = pojoList.get(0); tx.commit(); return returnStudy; } public Study get(int id) { Session sess = session.getCurrentSession(); Transaction tx = sess.beginTransaction(); List <Study> pojoList = sess.createQuery("from Study ad where ad.studyID=\'"+id+"\'").list(); Study returnStudy = pojoList.get(0); tx.commit(); return returnStudy; } public List<Study> getAllStudy(int visitID) { Session sess = session.getCurrentSession(); Transaction tx = sess.beginTransaction(); List <Study> pojoList = sess.createQuery("Select t from Study t, PatientStudy pad where pad.studyID=t.studyID and pad.visitID=\'"+visitID+"\' ").list(); tx.commit(); for(Study a: pojoList) { System.out.println(a); } return pojoList; } public void put(String oldName, String newName, int visitID) { Study study= this.getWithName(oldName); if(study!=null) { PatientStudyRest.getInstance().delete(study.getStudyID(), visitID); post(newName, visitID); } } public void post(String studyName, int visitID) { Session sess = session.getCurrentSession(); Transaction tx = sess.beginTransaction(); List <Study> pojoList = sess.createQuery("from Study c where c.studyName=\'"+studyName+"\'").list(); tx.commit(); Study current; if(pojoList.size()==0) { sess = session.getCurrentSession(); tx = sess.beginTransaction(); Study pojo = new Study(); pojo.setStudyName(studyName); sess.save(pojo); tx.commit(); current = pojo; } else current = pojoList.get(0); PatientStudyRest.getInstance().post(visitID, current.getStudyID()); } public void delete(String name, String visitID) { Study adev = this.getWithName(name); Session sess = session.getCurrentSession(); Transaction tx = sess.beginTransaction(); String del = "delete PatientStudy ad where ad.studyID = :oldstudyID and ad.visitID=:oldVisitID"; int deletedEntities = sess.createQuery(del) .setString( "oldstudyID", ""+adev.getStudyID()).setString("oldVisitID", visitID) .executeUpdate(); tx.commit(); } public static void main(String [] arg) { //System.out.println(StudyRest.getInstance().getAllStudy(1)); } }
true
9591056121987674f68e561954d66f064552a695
Java
wuhuiying/Video
/app/src/main/java/quarter/perfect/com/quarternew/util/QuarterViewPage.java
UTF-8
3,062
2.046875
2
[]
no_license
package quarter.perfect.com.quarternew.util; import android.content.Context; import android.os.Handler; import android.os.Message; import android.support.v4.view.ViewPager; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import java.util.ArrayList; import java.util.List; import quarter.perfect.com.quarternew.R; import quarter.perfect.com.quarternew.adapter.QuarterBannerAdapter; import quarter.perfect.com.quarternew.bean.QuarterCarouselBean; /** * Created by Administrator on 2018/4/21. */ public class QuarterViewPage extends RelativeLayout { Handler handler = new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); viewPager.setCurrentItem(viewPager.getCurrentItem()+1); abc(); } }; private ViewPager viewPager; private LinearLayout ly; private static final String TAG = "QuarterViewPage"; public QuarterViewPage(Context context) { this(context,null); } public QuarterViewPage(Context context, AttributeSet attrs) { this(context, attrs,0); } public QuarterViewPage(final Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); View view = LayoutInflater.from(context).inflate(R.layout.activity_page_adapter, this, true); viewPager = view.findViewById(R.id.vp); // ly = view.findViewById(R.id.ly); } public void GetAdapter(final Context context, final List<QuarterCarouselBean.DataBean> list){ QuarterBannerAdapter myAdapter = new QuarterBannerAdapter(context,list); viewPager.setAdapter(myAdapter); final List<ImageView> list1 = new ArrayList<ImageView>(); for (int i = 0; i < list.size(); i++) { ImageView imageView = new ImageView(context); imageView.setImageResource(R.drawable.selects); imageView.setId(i); list1.add(imageView); //ly.addView(imageView); } list1.get(0).setSelected(true); abc(); viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { position = position%list1.size(); for (int i = 0; i < list1.size(); i++) { if(i==position){ list1.get(position).setSelected(true); }else{ list1.get(i).setSelected(false); } } } @Override public void onPageScrollStateChanged(int state) { } }); } public void abc(){ handler.sendEmptyMessageDelayed(0,3000); } }
true
5b68323ea1885325e50f6b6e78fe6e5db4fe12cb
Java
andrewdeberardinis/TV-Program
/TV Program/src/ProgramMaker.java
UTF-8
1,521
3.375
3
[]
no_license
import java.util.ArrayList; public class ProgramMaker { static ArrayList <Program> TVShows = new ArrayList <Program>(); public static void main(String[] args) { addingPrograms(); printList(); } public static void addingPrograms() { TVShows.add(new Program("Soccer Show", "Sports", 3)); TVShows.add(new Program("Finding Bigfoot", "Adventure", 10)); TVShows.add(new Program("Cooking with Andrew", "Food", 24)); TVShows.add(new Program("How to Code", "Educational", 1)); TVShows.add(new Program("Street Outlaws", "Racing", 6)); { } } public static void printList() { System.out.println(TVShows.get(0).getTitle()); System.out.println(TVShows.get(1).getTitle()); System.out.println(TVShows.get(2).getTitle()); System.out.println(TVShows.get(3).getTitle()); System.out.println(TVShows.get(4).getTitle()); System.out.println(TVShows.get(0).getGenre()); System.out.println(TVShows.get(1).getGenre()); System.out.println(TVShows.get(2).getGenre()); System.out.println(TVShows.get(3).getGenre()); System.out.println(TVShows.get(4).getGenre()); System.out.println(TVShows.get(0).getNumberOfSeasonsAired()); System.out.println(TVShows.get(1).getNumberOfSeasonsAired()); System.out.println(TVShows.get(2).getNumberOfSeasonsAired()); System.out.println(TVShows.get(3).getNumberOfSeasonsAired()); System.out.println(TVShows.get(4).getNumberOfSeasonsAired()); } }
true
b3218cb7e5bfc8a856077403351349a154d75fcd
Java
BiswasTanmay/covid-19-cowin-api
/src/main/java/com/tbiswas/covid19/cowin/model/StateListDto.java
UTF-8
259
1.882813
2
[]
no_license
package com.tbiswas.covid19.cowin.model; import lombok.Data; @Data public class StateListDto { public StateDto[] states; public StateDto[] getStates() { return states; } public void setStates(StateDto[] states) { this.states = states; } }
true
dd94f6aecefffe18884035a4358dbc679051ab1c
Java
ZakharchenkoWork/RateOfExchange
/app/src/main/java/com/hast/exchangerate/general/db/DatabaseHelper.java
UTF-8
3,226
2.71875
3
[ "Apache-2.0" ]
permissive
package com.hast.exchangerate.general.db; /** * Created by Konstantyn Zakharchenko on 30.05.2017. */ import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.util.Log; import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper; import com.j256.ormlite.dao.Dao; import com.j256.ormlite.support.ConnectionSource; import com.j256.ormlite.table.TableUtils; import com.hast.exchangerate.general.models.UserData; import com.hast.exchangerate.general.models.WidgetInfo; import java.sql.SQLException; /** * Created by Konstantyn Zakharchenko on 07.01.2017. */ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { private static final String DATABASE_NAME = "app.db"; private static final int DATABASE_VERSION = 1; private Dao<UserData, String> userDao = null; private Dao<WidgetInfo, String> widgetsDao = null; public DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } /** * This is called when the database is first created. Call createTable statements here to create * the tables that will store data. */ @Override public void onCreate(SQLiteDatabase db, ConnectionSource connectionSource) { try { TableUtils.createTable(connectionSource, UserData.class); TableUtils.createTable(connectionSource, WidgetInfo.class); } catch (SQLException e) { Log.e(DatabaseHelper.class.getName(), "Can't create database", e); throw new RuntimeException(e); } } /** * This is called when application is upgraded and it has a higher version number. This allows you to adjust * the various data to match the new version number. */ @Override public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource, int oldVersion, int newVersion) { try { Log.i(DatabaseHelper.class.getName(), "onUpgrade"); TableUtils.dropTable(connectionSource, UserData.class, true); TableUtils.dropTable(connectionSource, WidgetInfo.class, true); // after we drop the old databases, we create the new ones onCreate(db, connectionSource); } catch (SQLException e) { Log.e(DatabaseHelper.class.getName(), "Can't drop databases", e); throw new RuntimeException(e); } } /** * Returns the Database Access Object (DAO) for our UserData class. It will create it or just give the cached * value. */ Dao<UserData, String> getUserDao() throws SQLException { if (userDao == null) { userDao = getDao(UserData.class); } return userDao; } /** * Returns the Database Access Object (DAO) for our WidgetInfo class. It will create it or just give the cached * value. */ Dao<WidgetInfo, String> getWidgetsDao() throws SQLException { if (widgetsDao == null) { widgetsDao = getDao(WidgetInfo.class); } return widgetsDao; } /** * Close the database connections and clear any cached DAOs. */ @Override public void close() { super.close(); userDao = null; widgetsDao = null; } }
true
0ae1e7625b9a07d3809fa87b20b269ce9d4f61d3
Java
slevental/nlp
/core/src/main/java/org/slevental/anaphora/core/serial/JsonProvider.java
UTF-8
6,174
2.1875
2
[]
no_license
package org.slevental.anaphora.core.serial; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonToken; import com.fasterxml.jackson.core.util.DefaultPrettyPrinter; import org.slevental.anaphora.core.txt.*; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Map; public class JsonProvider implements TextProvider { public static final String JSON = "json"; static { TextProviders.register(JSON, JsonProvider.class); } private final JsonFactory factory = new JsonFactory(); public JsonProvider(){ } @Override public Text deserialize(InputStream stream) throws IOException { JsonParser parser = factory.createParser(stream); Text.Builder builder = Text.builder(); JsonToken token = null; String currentName = null; while ((token = parser.nextToken()) != JsonToken.END_OBJECT) { currentName = parser.getCurrentName(); switch (token) { case VALUE_STRING: if ("txt".equals(currentName)) { builder.setText(parser.getText()); } else if ("name".equals(currentName)) { builder.setName(parser.getText()); } else { throw new IllegalArgumentException("Unknown text's string field: " + currentName); } break; case START_OBJECT: if ( "annotations".equals(currentName)) { deserializeAnnotations(parser, builder); } break; default: } } return builder.build(); } private void deserializeAnnotations(JsonParser parser, Text.Builder builder) throws IOException { JsonToken token; while ((token = parser.nextToken()) != JsonToken.END_OBJECT) { switch (token) { case FIELD_NAME: builder.setAnnotationSetName(parser.getText()); break; case START_OBJECT: Annotation.Builder annBuilder = Annotation.builder(); deserializeAnnotation(parser, annBuilder); builder.addAnnotation(annBuilder.build()); break; default: } } } private void deserializeAnnotation(JsonParser parser, Annotation.Builder builder) throws IOException { JsonToken token; String currentName = null; while ((token = parser.nextToken()) != JsonToken.END_OBJECT) { currentName = parser.getCurrentName(); switch (token) { case VALUE_NUMBER_INT: if ("lo".equals(currentName)){ builder.from(parser.getIntValue()); } else if ("hi".equals(currentName)){ builder.to(parser.getIntValue()); } else if ("id".equals(currentName)){ builder.id(parser.getIntValue()); } else { throw new IllegalArgumentException("Unknown annotation's field: " + currentName);} break; case VALUE_STRING: if ("type".equals(currentName)){ builder.type(AnnotationType.valueOf(parser.getValueAsString())); } else { throw new IllegalArgumentException("Unknown annotation's field: " + currentName);} break; case START_OBJECT: deserializeFeatures(parser, builder); break; default: } } } private void deserializeFeatures(JsonParser parser, Annotation.Builder builder) throws IOException { JsonToken token; String currentName; while ((token = parser.nextToken()) != JsonToken.END_OBJECT) { currentName = parser.getCurrentName(); switch (token) { case VALUE_STRING: StaticFeature feature = StaticFeature.of(currentName); builder.feature(feature == null ? new RawFeature(currentName) : feature, parser.getValueAsString()); default: } } } @Override public void serialize(Text txt, OutputStream stream) throws IOException { JsonGenerator generator = factory.createGenerator(stream); generator.writeStartObject(); generator.setPrettyPrinter(new DefaultPrettyPrinter()); /** * Write text name */ generator.writeStringField("name", txt.getName()); /** * Write text itself */ generator.writeStringField("txt", txt.getText()); /** * Write annotations block */ generator.writeObjectFieldStart("annotations"); /** * For each annotation set */ for (Map.Entry<String, IntervalCollection<Annotation>> each : txt.getAll().entrySet()) { generator.writeArrayFieldStart(each.getKey()); for (Annotation ann : each.getValue()) { generator.writeStartObject(); generator.writeStringField("type", ann.getType().name()); generator.writeNumberField("id", ann.getId()); generator.writeNumberField("lo", ann.getLo()); generator.writeNumberField("hi", ann.getHi()); /** * Write features */ generator.writeObjectFieldStart("features"); for (Map.Entry<Feature, Object> feature : ann.getFeatures().entrySet()) { generator.writeStringField(feature.getKey().getName(), String.valueOf(feature.getValue())); } generator.writeEndObject(); // end of features object generator.writeEndObject(); // end of annotation object } generator.writeEndArray(); // end of annotation set } generator.writeEndObject(); // end of annotations generator.writeEndObject(); // end generator.close(); } }
true
8bd8921bfe73d406f54b68e4b3dc78c023fa7fdd
Java
timandy/linq
/src/main/java/com/bestvike/linq/debug/Debugger.java
UTF-8
6,759
2.625
3
[ "Apache-2.0" ]
permissive
package com.bestvike.linq.debug; import com.bestvike.collections.generic.ICollection; import com.bestvike.linq.IEnumerable; import com.bestvike.linq.Linq; import com.bestvike.linq.exception.InvalidOperationException; import com.bestvike.out; import java.lang.reflect.Array; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.Parameter; import java.util.Collection; import java.util.Map; /** * Created by 许崇雷 on 2019-12-06. */ final class Debugger { private Debugger() { } static String getDebuggerDisplayText(Object obj) { // Get the DebuggerDisplay for obj Class<?> objType = obj.getClass(); DebuggerDisplay debuggerDisplay = objType.getAnnotation(DebuggerDisplay.class); if (debuggerDisplay == null) { if (objType.isArray()) return "Count = " + Array.getLength(obj); if (obj instanceof Collection) return "Count = " + ((Collection<?>) obj).size(); if (obj instanceof Map) return "Count = " + ((Map<?, ?>) obj).size(); if (obj instanceof ICollection) return "Count = " + ((ICollection<?>) obj)._getCount(); return objType.getName(); } // Get the text of the DebuggerDisplay String attrText = debuggerDisplay.value(); String[] segments = Linq.split(attrText, '{', '}').toArray(String.class); if (segments.length % 2 == 0) throw new InvalidOperationException(String.format("The DebuggerDisplay for %s lacks a closing brace.", objType)); StringBuilder sb = new StringBuilder(); for (int i = 0; i < segments.length; i += 2) { String literal = segments[i]; sb.append(literal); if (i + 1 < segments.length) { String reference = segments[i + 1]; boolean noQuotes = reference.endsWith(",nq"); if (noQuotes) reference = reference.substring(0, reference.length() - 3); // Evaluate the reference. out<Object> memberRef = out.init(); if (!tryEvaluateReference(obj, reference, memberRef)) throw new InvalidOperationException(String.format("The DebuggerDisplay for %s contains the expression \"%s\".", objType, reference)); String memberString = getDebuggerMemberString(memberRef.value, noQuotes); sb.append(memberString); } } return sb.toString(); } private static String getDebuggerMemberString(Object member, boolean noQuotes) { if (member == null) return "null"; if (member instanceof String) return noQuotes ? (String) member : '"' + (String) member + '"'; if (isPrimitiveType(member)) return member.toString(); return '{' + member.toString() + '}'; } private static boolean isPrimitiveType(Object obj) { Class<?> clazz = obj.getClass(); return clazz.isPrimitive() || clazz == Boolean.class || clazz == Byte.class || clazz == Short.class || clazz == Integer.class || clazz == Long.class || clazz == Character.class || clazz == Float.class || clazz == Double.class; } private static boolean tryEvaluateReference(Object obj, String reference, out<Object> memberRef) { if (reference.endsWith("()")) { Method method = getMethod(obj, reference.substring(0, reference.length() - 2)); if (method != null) { try { memberRef.value = Modifier.isStatic(method.getModifiers()) ? method.invoke(null) : method.invoke(obj); return true; } catch (Exception e) { throw new RuntimeException(e); } } } else { Field field = getField(obj, reference); if (field != null) { try { memberRef.value = Modifier.isStatic(field.getModifiers()) ? field.get(null) : field.get(obj); return true; } catch (Exception e) { throw new RuntimeException(e); } } } memberRef.value = null; return false; } private static Field getField(Object obj, String fieldName) { for (Class<?> t = obj.getClass(); t != null; t = t.getSuperclass()) { try { Field field = t.getDeclaredField(fieldName); field.setAccessible(true); return field; } catch (NoSuchFieldException ignored) { } } return null; } private static Method getMethod(Object obj, String propertyName) { for (Class<?> t = obj.getClass(); t != null; t = t.getSuperclass()) { try { Method method = t.getDeclaredMethod(propertyName); method.setAccessible(true); return method; } catch (NoSuchMethodException ignored) { } } return null; } static IDebugView getDebugView(Object obj) { Class<?> objType = obj.getClass(); Class<? extends IDebugView> proxyType = getProxyType(objType); for (Constructor<?> constructor : proxyType.getDeclaredConstructors()) { Parameter[] parameters = constructor.getParameters(); if (parameters.length == 1 && parameters[0].getType().isAssignableFrom(objType)) { try { constructor.setAccessible(true); return (IDebugView) constructor.newInstance(obj); } catch (Exception ignored) { } } } throw new InvalidOperationException(String.format("The DebuggerTypeProxy for %s reference invalid proxyType %s", objType, proxyType)); } private static Class<? extends IDebugView> getProxyType(Class<?> type) { // Get the DebuggerTypeProxy for obj DebuggerTypeProxy debuggerTypeProxy = type.getAnnotation(DebuggerTypeProxy.class); if (debuggerTypeProxy != null) return debuggerTypeProxy.value(); if (IEnumerable.class.isAssignableFrom(type)) return EnumerableDebugView.class; if (Collection.class.isAssignableFrom(type)) return CollectionDebugView.class; if (Map.class.isAssignableFrom(type)) return MapDebugView.class; if (Iterable.class.isAssignableFrom(type)) return IterableDebugView.class; return ObjectDebugView.class; } }
true
f5b2a1639297936e63e43996f04e9e1cc69d498a
Java
alenafdr/ProjectManagementSystemHibernate
/src/main/java/service/DeveloperService.java
UTF-8
976
2.453125
2
[]
no_license
package service; import model.Developer; import service.DAO.HibernateDeveloperDAO; import java.util.List; public class DeveloperService implements GenericService<Developer, Integer> { HibernateDeveloperDAO jdbcDeveloperDAO = new HibernateDeveloperDAO(); @Override public boolean save(Developer developer) { return jdbcDeveloperDAO.save(developer); } @Override public Developer getById(Integer integer) { return jdbcDeveloperDAO.getById(integer); } @Override public List<Developer> getAll() { return jdbcDeveloperDAO.getAll(); } @Override public boolean update(Integer integer, Developer developer) { return jdbcDeveloperDAO.update(integer, developer); } @Override public boolean remove(Developer developer) { return jdbcDeveloperDAO.remove(developer); } @Override public void stopSessionFactory() { jdbcDeveloperDAO.stopSessionFactory(); } }
true
17b6ed817b72b0d7740d61ac72b87591b6b5342b
Java
benoitantelme/javastuff
/src/com/java/stuff/datastructures/heap/MaxHeap.java
UTF-8
1,406
3.9375
4
[]
no_license
package com.java.stuff.datastructures.heap; import java.util.Arrays; public class MaxHeap { public void sort(int arr[]) { int n = arr.length; // Build heap for (int i = n / 2 - 1; i >= 0; i--) heapify(arr, n, i); for (int i = n - 1; i >= 0; i--) { // Move root to the end int temp = arr[0]; arr[0] = arr[i]; arr[i] = temp; // heapify the reduced heap heapify(arr, i, 0); } } private void heapify(int arr[], int heapSize, int rootIndex) { int largest = rootIndex; int l = 2*rootIndex + 1; int r = 2*rootIndex + 2; if (l < heapSize && arr[l] > arr[largest]) largest = l; if (r < heapSize && arr[r] > arr[largest]) largest = r; if (largest != rootIndex) { int swap = arr[rootIndex]; arr[rootIndex] = arr[largest]; arr[largest] = swap; // Recursively heapify the affected sub-tree heapify(arr, heapSize, largest); } } public static void main(String[] args) { int arr[] = {12, 11, 5, 13, 6, 7}; System.out.println("Array is: " + Arrays.toString(arr)); MaxHeap mh = new MaxHeap(); mh.sort(arr); System.out.println("Sorted array is: " + Arrays.toString(arr)); } }
true
f5f7705ce6745a058bf330ba533aa23f4d71fb51
Java
RenJie233/TestDemo
/app/src/main/java/com/example/dllo/testdemo/MainActivity.java
UTF-8
639
2.03125
2
[]
no_license
package com.example.dllo.testdemo; import android.view.View; import android.widget.TextView; import com.example.dllo.testdemo.base.BaseAty; public class MainActivity extends BaseAty implements View.OnClickListener { private TextView mainTv; @Override protected int getLayout() { return R.layout.activity_main; } @Override protected void initViews() { // mainTv = (TextView) findViewById(R.id.main_tv); mainTv = bindView(R.id.main_tv); setClick(this, mainTv); } @Override protected void initDatas() { } @Override public void onClick(View v) { } }
true
67b15a3c9d20d464c138e35d1925a65351a4d99d
Java
jperiapandi/and-thirukkural
/app/src/main/java/com/jpp/and/thirukkural/model/Part.java
UTF-8
929
2.515625
3
[]
no_license
package com.jpp.and.thirukkural.model; /** * Created by jperiapandi on 05-07-2016. */ public class Part implements ListItem { private int _id; private String title; private int sectionId; private int numOfChapters = 0; public int get_id() { return _id; } public void set_id(int _id) { this._id = _id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public int getSectionId() { return sectionId; } public void setSectionId(int sectionId) { this.sectionId = sectionId; } public int getNumOfChapters() { return numOfChapters; } public void setNumOfChapters(int numOfChapters) { this.numOfChapters = numOfChapters; } @Override public ListItemType getListItemType() { return ListItemType.PART; } }
true
fa6fabab80c764c4cfde61395894bf60bb728051
Java
archyoshi/CashRegister
/src/main/java/cashregister/ItemReference.java
UTF-8
1,120
3.125
3
[ "MIT" ]
permissive
package cashregister; class ItemReference { private final String itemCode; private final Price unitPrice; private ItemReference(String itemCode, Price unitPrice) { this.itemCode = itemCode; this.unitPrice = unitPrice; } static Builder aReference() { return new Builder(); } boolean matchesSoughtItemCode(String itemCode) { return this.itemCode.equals(itemCode); } Price getUnitPrice() { return unitPrice; } static final class Builder { private String itemCode; private Price unitPrice; private Builder() {} Builder withItemCode(String itemCode) { this.itemCode = itemCode; return this; } Builder withUnitPrice(Price unitPrice) { this.unitPrice = unitPrice; return this; } Builder withUnitPrice(double unitPrice) { this.unitPrice = Price.valueOf(unitPrice); return this; } ItemReference build() { return new ItemReference(itemCode, unitPrice); } } }
true
5e297eaefedf34a28b4f03f246aa35d6b39655b9
Java
kodaji/doitfive
/admin/src/main/java/com/ckstack/ckpush/common/validator/ByteSize.java
UTF-8
891
2.1875
2
[]
no_license
package com.ckstack.ckpush.common.validator; import javax.validation.Constraint; import javax.validation.Payload; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Created by dhkim94 on 15. 4. 9.. * Size annotation 은 글자 길이만 체크 하기 때문에 byte 길이 체크 하는 * ByteSize annotation 을 추가 한다. */ @Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE}) @Retention(RetentionPolicy.RUNTIME) @Constraint(validatedBy=ByteSizeValidator.class) public @interface ByteSize { String message() default "{com.ckstack.ckpush.common.validator.ByteSize.message}"; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; int min() default 0; int max() default Integer.MAX_VALUE; }
true
1580b6bcdfa4813d75de462cbb974e8e967e861e
Java
ersalye/TripTracker
/core/src/main/java/com/antonchaynikov/core/data/model/Trip.java
UTF-8
1,945
2.8125
3
[]
no_license
package com.antonchaynikov.core.data.model; import androidx.annotation.Keep; import com.google.firebase.firestore.PropertyName; import java.util.Objects; @Keep public class Trip { public static final String FIELD_NAME_START_DATE = "startDate"; private static final String FIELD_NAME_END_DATE = "endDate"; private static final String FIELD_NAME_DISTANCE = "distance"; private static final String FIELD_NAME_SPEED = "speed"; @PropertyName(FIELD_NAME_START_DATE) private long startDate; @PropertyName(FIELD_NAME_END_DATE) private long endDate; // In meters @PropertyName(FIELD_NAME_DISTANCE) private double distance; // Speed in meters per second @PropertyName(FIELD_NAME_SPEED) private double speed; public Trip() { } public Trip(long startDate) { this.startDate = startDate; } public Trip updateStatistics(double distance, double speed) { this.distance = distance; this.speed = speed; return this; } public long getStartDate() { return startDate; } public void setStartDate(long startDate) { this.startDate = startDate; } public long getEndDate() { return endDate; } public void setEndDate(long endDate) { this.endDate = endDate; } public double getDistance() { return distance; } public double getSpeed() { return speed; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Trip)) return false; Trip trip = (Trip) o; return startDate == trip.startDate && endDate == trip.endDate && Double.compare(trip.distance, distance) == 0 && Double.compare(trip.speed, speed) == 0; } @Override public int hashCode() { return Objects.hash(startDate, endDate, distance, speed); } }
true
19f7c56573052814e0428d4f823ef152ed8a1fbf
Java
nirvdrum/tapestry5
/tapestry-core/src/main/java/org/apache/tapestry5/internal/test/ComponentEventInvoker.java
UTF-8
3,933
1.96875
2
[ "LGPL-2.0-or-later", "LicenseRef-scancode-proprietary-license", "MPL-1.0", "MIT", "Apache-2.0", "MIT-0", "LicenseRef-scancode-unknown-license-reference", "LGPL-2.1-or-later", "GPL-1.0-or-later", "MPL-1.1", "CC-BY-2.5" ]
permissive
// Copyright 2006, 2007, 2008 The Apache Software Foundation // // 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.apache.tapestry5.internal.test; import org.apache.tapestry5.Link; import org.apache.tapestry5.dom.Document; import org.apache.tapestry5.internal.services.ComponentEventTarget; import org.apache.tapestry5.internal.services.ComponentInvocation; import org.apache.tapestry5.internal.services.ComponentInvocationMap; import org.apache.tapestry5.internal.services.InvocationTarget; import org.apache.tapestry5.ioc.Registry; import org.apache.tapestry5.ioc.internal.util.Defense; import org.apache.tapestry5.services.ComponentEventRequestHandler; import org.apache.tapestry5.services.ComponentEventRequestParameters; import java.io.IOException; /** * Simulates a click on an component event invocation link. */ public class ComponentEventInvoker implements ComponentInvoker { private final Registry registry; private final ComponentInvoker followupInvoker; private final ComponentEventRequestHandler componentEventRequestHandler; private final ComponentInvocationMap componentInvocationMap; private final TestableResponse response; public ComponentEventInvoker(Registry registry, ComponentInvoker followupInvoker, ComponentInvocationMap componentInvocationMap) { this.registry = registry; this.followupInvoker = followupInvoker; this.componentInvocationMap = componentInvocationMap; componentEventRequestHandler = registry.getService("ComponentEventRequestHandler", ComponentEventRequestHandler.class); response = registry.getObject(TestableResponse.class, null); } /** * Click on the action link and get another link in return. Then follow up the link with another {@link * ComponentInvoker}. * * @param invocation The ComponentInvocation object corresponding to the action link. * @return The DOM created. Typically you will assert against it. */ public Document invoke(ComponentInvocation invocation) { click(invocation); Link link = response.getRedirectLink(); response.clear(); if (link == null) throw new RuntimeException("Action did not set a redirect link."); ComponentInvocation followup = componentInvocationMap.get(link); return followupInvoker.invoke(followup); } private void click(ComponentInvocation invocation) { try { InvocationTarget target = invocation.getTarget(); ComponentEventTarget componentEventTarget = Defense.cast(target, ComponentEventTarget.class, "target"); ComponentEventRequestParameters parameters = new ComponentEventRequestParameters( componentEventTarget.getPageName(), componentEventTarget.getPageName(), componentEventTarget.getComponentNestedId(), componentEventTarget.getEventType(), invocation.getPageActivationContext(), invocation.getEventContext()); componentEventRequestHandler.handle(parameters); } catch (IOException e) { throw new RuntimeException(e); } finally { registry.cleanupThread(); } } }
true
a3f297d075a9f817338e460d6fa692d3b0854050
Java
esaycode/distributed_sequence
/com.easy.code.sequence.service.impl/src/main/java/com/easy/code/sequence/service/impl/IdSequenceServiceImpl.java
UTF-8
1,059
2.234375
2
[]
no_license
package com.easy.code.sequence.service.impl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.easy.code.sequence.dao.IdSequenceDao; import com.easy.code.sequence.dao.model.IdSequenceModel; import com.easy.code.sequence.service.IdSequenceService; @Service public class IdSequenceServiceImpl implements IdSequenceService { @Autowired IdSequenceDao idSequenceDao; @Override public Long next(String sys, String subSys, String module, String tableName) { Long nextId = null; // 三次尝试机会 for (int i = 0; i < 3; i++) { IdSequenceModel idSequenceModel = idSequenceDao.findBySysAndSubSysAndModuleAndTableName(sys, subSys, module, tableName); if (idSequenceModel == null) { throw new RuntimeException("the database is not init"); } if (idSequenceDao.updateByIdAndUtime(idSequenceModel.getId(), idSequenceModel.getIdSeed()) > 0) { nextId = idSequenceModel.getIdSeed() + 1; break; } } System.out.println(nextId); return nextId; } }
true
d8febb3009d63cb6959e7cb9f58336c66dc931f7
Java
riverwall/rele2
/src/main/java/sk/hlavco/rele/OvladanieRele.java
UTF-8
4,667
2.453125
2
[]
no_license
package sk.hlavco.rele; import by.creepid.jusbrelay.*; import sk.hlavco.clock.Delegator; import sk.hlavco.clock.DigitalClock; import java.util.logging.Level; import java.util.logging.Logger; public class OvladanieRele{ static final Logger LOGGER = Logger.getLogger( DigitalClock.class.getName() ); static Delegator dlg = new Delegator(); public UsbRelayDeviceHandler openDevice() { UsbRelayManager manager = NativeUsbRelayManager.getInstance(); try { //init manager manager.relayInit(); //enumerate devices UsbRelayDeviceInfo[] devices = manager.deviceEnumerate(); if (devices == null || devices.length <= 0) { return null; } UsbRelayDeviceInfo usbRelayDeviceInfo = devices[0]; //retrieve device handler UsbRelayDeviceHandler handler = manager.deviceOpen(usbRelayDeviceInfo.getSerialNumber()); return handler; } catch (UsbRelayException ex) { ex.printStackTrace(); return null; } } public void closeDevice(UsbRelayDeviceHandler handler){ UsbRelayManager manager = NativeUsbRelayManager.getInstance(); try { //init manager manager.relayInit(); manager.closeRelay(handler); manager.relayExit(); } catch (UsbRelayException ex) { ex.printStackTrace(); } } public void impulzSInicializaciou() { UsbRelayDeviceHandler handler = null; handler = openDevice(); int indexRele = 9; indexRele = dlg.getPropertyFile().readPosledneReleFromPropertiesFile(); if(indexRele == 0){ indexRele = 1; } else if (indexRele == 1){ indexRele = 0; } else { LOGGER.log(Level.INFO, "chyba v indexe rele"); throw new IndexOutOfBoundsException(); } boolean uspesnyImpulz = dlg.getOvladanieRele().impulz(handler, indexRele); if(uspesnyImpulz) { dlg.getPropertyFile().savePosledneReleToPropsFile(indexRele); } dlg.getOvladanieRele().closeDevice(handler); } public boolean impulz(UsbRelayDeviceHandler handler, int indexRele){ UsbRelayManager manager = NativeUsbRelayManager.getInstance(); try { manager.openRelayChannel(handler, indexRele); Thread.sleep(100); manager.closeRelayChannel(handler, indexRele); } catch (UsbRelayException e) { e.printStackTrace(); return false; } catch (InterruptedException e) { e.printStackTrace(); return false; } return true; } // public void stukajRelatkami () { // // UsbRelayManager manager = NativeUsbRelayManager.getInstance(); // try { // //init manager // manager.relayInit(); // //enumerate devices // UsbRelayDeviceInfo[] devices = manager.deviceEnumerate(); // // for (int i = 0; i < devices.length; i++) { // UsbRelayDeviceInfo usbRelayDeviceInfo = devices[i]; // //retrieve device handler // UsbRelayDeviceHandler handler = manager.deviceOpen(usbRelayDeviceInfo.getSerialNumber()); // //change relay status // //turning on the relay, index - channel number // //Get device status // UsbRelayStatus[] statuses = manager.getStatus(usbRelayDeviceInfo.getSerialNumber(), handler); // // //MAJO // for (int j = 0; j < 10; j++) { // // // manager.openRelayChannel(handler, 0); // // Thread.sleep(100); // // manager.closeRelayChannel(handler, 0); // // // Thread.sleep(400); // // manager.openRelayChannel(handler, 1); // // // Thread.sleep(100); // // manager.closeRelayChannel(handler, 1); // // Thread.sleep(400); // } // // //MAJO // // //close relay // manager.closeRelay(handler); // } // } catch (UsbRelayException ex) { // //catch exceptions // } catch (InterruptedException e) { // e.printStackTrace(); // } finally { // //close manager // try { // manager.relayExit(); // } catch (UsbRelayException e) { // e.printStackTrace(); // } // } // // } }
true
f51ad2e4881a359a315e4d44ea80789ab79b6442
Java
VincenzoSalvati/SE_Team17_Delivery2
/src/JAVA/SpecificationsEWO.java
UTF-8
3,553
2.484375
2
[]
no_license
package JAVA; import java.sql.Connection; import java.sql.PreparedStatement; @SuppressWarnings("SqlResolve") public class SpecificationsEWO { private final Connection con; public int dbOperationStatusCode; public String dbOperationMessage; private int id; private int new_estimate_tr; private String new_int_des; private int week; private int ewo; public SpecificationsEWO(MySqlDbConnection db, int id) { this.con = db.connect(); this.id = id; } public int getId() { return id; } public void setId(int id) { this.id = id; } public int getWeek() { return week; } public void setWeek(int week) { this.week = week; } public int getEwo() { return ewo; } public void setEwo(int ewo) { this.ewo = ewo; } public int getNew_estimate_tr() { return new_estimate_tr; } public void setNew_estimated_rt(int new_estimate_tr) { this.new_estimate_tr = new_estimate_tr; } public String getNew_int_des() { return new_int_des; } public void setNew_int_des(String new_int_des) { this.new_int_des = new_int_des; } public int getDbOperationStatusCode() { return dbOperationStatusCode; } public String getDbOperationMessageEstimateTr() { String specificationsEWOBrowseJSONFormat = "{\"id\":\"{ID}\",\"estimate_tr\":\"{ESTIMATE_TR}\"}"; String JSONRow = specificationsEWOBrowseJSONFormat.replace("{ID}", Util.utf8Encode(String.valueOf(this.getId()))); JSONRow = JSONRow.replace("{ESTIMATE_TR}", Util.utf8Encode(String.valueOf(this.getNew_estimate_tr()))); return "[" + JSONRow + "]"; } public String getDbOperationMessageIntDes() { String specificationsEWOBrowseJSONFormat = "{\"id\":\"{ID}\",\"int_des\":\"{INT_DES}\"}"; String JSONRow = specificationsEWOBrowseJSONFormat.replace("{ID}", Util.utf8Encode(String.valueOf(this.getId()))); JSONRow = JSONRow.replace("{INT_DES}", Util.utf8Encode(this.getNew_int_des())); return "[" + JSONRow + "]"; } public void updateEstimateTr() { try { String query = "UPDATE activity SET " + "estim_time = ? WHERE id= ? and week= ? and ewo= ?"; PreparedStatement preparedStmt = this.con.prepareStatement(query); preparedStmt.setInt(1, this.new_estimate_tr); preparedStmt.setInt(2, this.id); preparedStmt.setInt(3, this.week); preparedStmt.setInt(4, this.ewo); preparedStmt.execute(); this.dbOperationStatusCode = 0; this.dbOperationMessage = "Record updated"; } catch (Exception e) { this.dbOperationStatusCode = 1; this.dbOperationMessage = "Record not updated: " + e.getMessage(); } } public void updateIntDes() { try { String query = "UPDATE specifications SET " + "int_des = ? WHERE id= ?"; PreparedStatement preparedStmt = this.con.prepareStatement(query); preparedStmt.setString(1, this.new_int_des); preparedStmt.setInt(2, this.id); preparedStmt.execute(); this.dbOperationStatusCode = 0; this.dbOperationMessage = "Record updated"; } catch (Exception e) { this.dbOperationStatusCode = 1; this.dbOperationMessage = "Record not updated: " + e.getMessage(); } } }
true
0bc484aefe1ab6d4887fa29569343b70979c5961
Java
qq443672581/dubbo
/world/src/main/java/cn/dlj1/world/DynamicProxy.java
UTF-8
651
3.0625
3
[]
no_license
package cn.dlj1.world; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; public class DynamicProxy { interface S { void eat(); } static class Handler implements InvocationHandler{ public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { return "123"; } } public static void main(String[] args) { synchronized (S.class){ } S s = (S) Proxy.newProxyInstance(S.class.getClassLoader(),new Class[]{S.class},new Handler()); s.eat(); System.out.println(s); } }
true
831d08d0cd42e883a6d6db59aee0d96855595ade
Java
emistoolbox/emistoolbox
/core/src/com/emistoolbox/common/model/analysis/impl/AggregatorList.java
UTF-8
3,440
2.203125
2
[ "Apache-2.0" ]
permissive
package com.emistoolbox.common.model.analysis.impl; import java.io.Serializable; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import com.emistoolbox.common.model.analysis.EmisAggregatorDef; import com.emistoolbox.common.model.analysis.EmisAggregatorList; import com.emistoolbox.common.model.analysis.EmisSampleAggregatorDef; import com.emistoolbox.common.model.meta.EmisMetaDateEnum; import com.emistoolbox.common.model.meta.EmisMetaEntity; import com.emistoolbox.common.model.meta.EmisMetaHierarchy; import com.emistoolbox.common.util.NamedIndexList; import com.emistoolbox.common.util.NamedUtil; public class AggregatorList implements EmisAggregatorList, Serializable { private String[] aggregatorNames; private Map<String, EmisAggregatorDef> aggregators = new HashMap<String, EmisAggregatorDef>(); public AggregatorList() {} public AggregatorList(String[] names) { this.aggregatorNames = names; } @Override public String[] getAggregatorNames() { return this.aggregatorNames; } @Override public Map<String, EmisAggregatorDef> getAggregators() { return this.aggregators; } @Override public EmisAggregatorDef getAggregator(String name) { return (EmisAggregatorDef) this.aggregators.get(name); } @Override public void setAggregator(String name, EmisAggregatorDef aggregator) { if (!validAggregatorName(name)) throw new IllegalArgumentException("Aggregator '" + name + "' not allowed."); this.aggregators.put(name, aggregator); } @Override public void setAggregators(Map<String, EmisAggregatorDef> aggregators) { this.aggregators = aggregators; } private boolean validAggregatorName(String name) { if (this.aggregatorNames == null) { return true; } for (String tmp : this.aggregatorNames) { if (tmp.equals(name)) return true; } return false; } public EmisMetaEntity getSeniorEntity(EmisMetaHierarchy hierarchy) { NamedIndexList entities = hierarchy.getEntityOrder(); int result = -1; for (EmisAggregatorDef aggregator : getAggregators().values()) { EmisMetaEntity entity = aggregator.getSeniorEntity(hierarchy); if (entity == null) entity = aggregator.getEntity(); if (entity == null) continue; int index = NamedUtil.findIndex(entity, entities); if (result == -1 || result > index) result = index; } if (result == -1) return null; return (EmisMetaEntity) entities.get(result); } @Override public Set<EmisMetaDateEnum> getUsedDateTypes() { Set<EmisMetaDateEnum> result = new HashSet<EmisMetaDateEnum>(); for (EmisAggregatorDef aggr : getAggregators().values()) result.addAll(aggr.getUsedDateTypes()); return result; } @Override public EmisMetaDateEnum getSeniorDateEnum() { EmisMetaDateEnum result = null; for (EmisMetaDateEnum dateType : getUsedDateTypes()) { if (result == null || result.getDimensions() > dateType.getDimensions()) result = dateType; } return result; } }
true
aeb087bf93d0c9a9d94331dc842e373e028c8038
Java
laodiaoyale/mans
/src/main/java/com/bns/model/contract/ContractInfo.java
UTF-8
1,371
2.265625
2
[]
no_license
package com.bns.model.contract; public class ContractInfo { //合同编号 private String contractNo; //贷款发布日期 private String fundDate; //贷款到期日期 private String endDate; //贷款状态 private String loanStatus; //贷款余额 private String loanBalance; //当前贷款期次 private String curLoanPeriod; public String getContractNo() { return contractNo; } public void setContractNo(String contractNo) { this.contractNo = contractNo; } public String getFundDate() { return fundDate; } public void setFundDate(String fundDate) { this.fundDate = fundDate; } public String getEndDate() { return endDate; } public void setEndDate(String endDate) { this.endDate = endDate; } public String getLoanStatus() { return loanStatus; } public void setLoanStatus(String loanStatus) { this.loanStatus = loanStatus; } public String getLoanBalance() { return loanBalance; } public void setLoanBalance(String loanBalance) { this.loanBalance = loanBalance; } public String getCurLoanPeriod() { return curLoanPeriod; } public void setCurLoanPeriod(String curLoanPeriod) { this.curLoanPeriod = curLoanPeriod; } }
true
e3e9704d801070d517c468d34ee4d22aaeefd492
Java
mazingHins/yogu_server
/services/xcloud/src/test/java/com/mazing/core/test/AcceptPermitInterceprotTest.java
UTF-8
833
1.875
2
[]
no_license
/** * */ package com.mazing.core.test; import org.junit.Test; import com.yogu.core.test.ApiReq; import com.yogu.core.test.HttpResourceTest; import com.yogu.core.web.RestResult; /** * 测试AcceptSeconds注解和拦截器 <br> * * <br> * JFan - 2015年6月16日 下午5:08:35 */ public class AcceptPermitInterceprotTest extends HttpResourceTest { public AcceptPermitInterceprotTest() { host = "http://localhost:8080"; } @Test public void test() { ApiReq<RestResult<?>> req = build("p/v1/permit/not"); RestResult<?> result = req.doGet(); Long time = assertObject(result); assertNotNull(time); } @Test public void testLogin() { ApiReq<RestResult<?>> req = build("a/v1/permit/login"); req.login(); RestResult<?> result = req.doGet(); Long time = assertObject(result); assertNotNull(time); } }
true
7a3e0dcb9be08e650693e44e39b5d83e732a84c8
Java
binyuanchen/CorfuDB
/src/main/java/org/corfudb/runtime/CorfuDBRuntime.java
UTF-8
16,532
1.984375
2
[ "Apache-2.0" ]
permissive
/** * * 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.corfudb.runtime; import org.corfudb.runtime.exceptions.NetworkException; import org.corfudb.runtime.exceptions.RemoteException; import org.corfudb.runtime.protocols.configmasters.MemoryConfigMasterProtocol; import org.corfudb.runtime.view.*; import org.corfudb.util.GitRepositoryState; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.json.JsonReader; import javax.json.Json; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.time.LocalDateTime; import java.time.temporal.ChronoUnit; import java.util.*; import org.corfudb.runtime.protocols.configmasters.IConfigMaster; /** * Note, the following imports require Java 8 */ import java.util.concurrent.locks.StampedLock; /** * This class is used by clients to access the CorfuDB infrastructure. * It is responsible for constructing client views, and returning * interfaces which clients use to access the CorfuDB infrastructure. * * @author Michael Wei <mwei@cs.ucsd.edu> */ public class CorfuDBRuntime implements AutoCloseable { private String configurationString; private StampedLock viewLock; private Thread viewManagerThread; private org.corfudb.runtime.view.CorfuDBView currentView; private BooleanLock viewUpdatePending; private Boolean closed = false; private UUID localID = null; private org.corfudb.runtime.view.RemoteLogView remoteView; private LocalDateTime lastInvalidation; private LocalDateTime backOffTime; private long backOff = 0; private static final HashMap<String, CorfuDBRuntime> s_rts = new HashMap(); private ICorfuDBInstance localInstance; private static final Logger log = LoggerFactory.getLogger(CorfuDBRuntime.class); private class BooleanLock { public boolean lock; public BooleanLock() { lock = false; } } /** * Suppressed default constructor. */ private CorfuDBRuntime() {} /** * Constructor. Generates an instance of a CorfuDB client, which * manages views of the CorfuDB infrastructure and provides interfaces * for clients to access. * * @param configurationString A configuration string which describes how to reach the * CorfuDB instance. This is usually a http address for a * configuration master. * The string "memory" is also acceptable, it will generate * a local in memory instance of CorfuDB with a single * stream unit and sequencer. */ public CorfuDBRuntime(String configurationString) { this.configurationString = configurationString; viewLock = new StampedLock(); remoteView = new org.corfudb.runtime.view.RemoteLogView(); viewUpdatePending = new BooleanLock(); viewUpdatePending.lock = true; viewManagerThread = getViewManagerThread(); viewManagerThread.setDaemon(true); try { localInstance = new LocalCorfuDBInstance(this); } catch (Exception e) { log.error("Exception creating local instance", e); } startViewManager(); } /** * Get the version of this client binding. * @return A string describing the version of this client binding. */ public String getVersion() { return GitRepositoryState.getRepositoryState().describe; } /** * interface for acquiring singleton runtime. * @param configurationString * @return */ public static CorfuDBRuntime getRuntime(String configurationString) { synchronized (s_rts) { CorfuDBRuntime rt = s_rts.getOrDefault(configurationString, null); if(rt == null) { rt = new CorfuDBRuntime(configurationString); s_rts.put(configurationString, rt); } return rt; } } /** * API for acquiring a runtime object. Generally, CorfuDBRuntime should * be a singleton, and getRuntime is the way to get a reference to said * singleton. However, there are scenarios (e.g. tests) where forcing the * creation of a fresh runtime object is actually the right thing to do. * TODO: refactor to discourage use of this API by user code. * @param configurationString * @return */ public static CorfuDBRuntime createRuntime(String configurationString) { synchronized (s_rts) { CorfuDBRuntime rt = new CorfuDBRuntime(configurationString); s_rts.put(configurationString, rt); return rt; } } /** * Starts the view manager thread. The view manager retrieves the view * and manages view changes. This thread will be automatically started * when any requests are made, but this method allows the view manager * to load the initial view during application load. */ public void startViewManager() { if (!viewManagerThread.isAlive()) { log.debug("Starting view manager thread."); viewManagerThread.start(); } } public ICorfuDBInstance getLocalInstance() { return localInstance; } /** * Retrieves the CorfuDBView from a configuration string. The view manager * uses this method to fetch the most recent view. */ public static org.corfudb.runtime.view.CorfuDBView retrieveView(String configString) throws IOException { if (configString.equals("custom")) { if (MemoryConfigMasterProtocol.memoryConfigMasters.get(0) != null) { return MemoryConfigMasterProtocol.memoryConfigMasters.get(0).getView(); } } else if (configString.equals("memory")) { if (MemoryConfigMasterProtocol.memoryConfigMasters.get(0) != null) { return MemoryConfigMasterProtocol.memoryConfigMasters.get(0).getView(); } //this is an in-memory request. HashMap<String, Object> MemoryView = new HashMap<String, Object>(); MemoryView.put("epoch", 0L); MemoryView.put("logid", UUID.randomUUID().toString()); MemoryView.put("pagesize", 4096); LinkedList<String> configMasters = new LinkedList<String>(); configMasters.push("mcm://localhost:0"); MemoryView.put("configmasters", configMasters); LinkedList<String> sequencers = new LinkedList<String>(); sequencers.push("ms://localhost:0"); MemoryView.put("sequencers", sequencers); HashMap<String,Object> layout = new HashMap<String,Object>(); LinkedList<HashMap<String,Object>> segments = new LinkedList<HashMap<String,Object>>(); HashMap<String,Object> segment = new HashMap<String,Object>(); segment.put("replication", "cdbcr"); segment.put("start", 0L); segment.put("sealed", 0L); LinkedList<HashMap<String,Object>> groups = new LinkedList<HashMap<String,Object>>(); HashMap<String,Object> group0 = new HashMap<String,Object>(); LinkedList<String> group0nodes = new LinkedList<String>(); group0nodes.add("mlu://localhost:0"); group0.put("nodes", group0nodes); groups.add(group0); segment.put("groups", groups); segments.add(segment); layout.put("segments", segments); MemoryView.put("layout", layout); CorfuDBView newView = new CorfuDBView(MemoryView); MemoryConfigMasterProtocol.memoryConfigMasters.get(0).setInitialView(newView); return MemoryConfigMasterProtocol.memoryConfigMasters.get(0).getView(); } URL url = new URL(configString); HttpURLConnection huc = (HttpURLConnection) url.openConnection(); huc.setRequestProperty("Content-Type", "application/json"); huc.connect(); try (InputStream is = (InputStream) huc.getContent()) { try (JsonReader jr = Json.createReader(new BufferedReader(new InputStreamReader(is)))) { return new org.corfudb.runtime.view.CorfuDBView(jr.readObject()); } } } /** * Invalidate the current view and wait for a new view. */ public void invalidateViewAndWait(NetworkException e) { log.warn("Client requested invalidation of current view, backoff level=" + backOff); lastInvalidation = LocalDateTime.now(); if (backOffTime != null) { if (backOffTime.compareTo(lastInvalidation) > 0) { //backoff! try { Thread.sleep((long) Math.pow(2, backOff) * 1000); } catch (Exception ex) {} //increment backoff backOff++; backOffTime = LocalDateTime.now().plus((long)Math.pow(2, backOff), ChronoUnit.SECONDS); } else { //no need to backoff backOff = 0; } } else { backOff++; backOffTime = LocalDateTime.now().plus((long)Math.pow(2, backOff), ChronoUnit.SECONDS); } if (currentView != null) { currentView.invalidate(); IConfigurationMaster cm = new ConfigurationMaster(this); cm.requestReconfiguration(e); } synchronized(viewUpdatePending) { viewUpdatePending.lock = true; viewUpdatePending.notify(); while (viewUpdatePending.lock) { try { viewUpdatePending.wait(); } catch (InterruptedException ie) {} } } } /** * Synchronously block until a valid view is installed. */ public void waitForViewReady() { synchronized(viewUpdatePending) { while (viewUpdatePending.lock) { try { viewUpdatePending.wait(); } catch (InterruptedException ie) {} } } } /** * Get the view for a remote stream. * * @param logID The UUID of the remote stream to retrieve the view for. * * @return A CorfuDBView, if the remote stream can be retrieved, or * null, if the UUID cannot be resolved. */ public org.corfudb.runtime.view.CorfuDBView getView(UUID logID) throws RemoteException { if (logID == null) {return getView();} if (logID.equals(localID)) { return getView(); } /** Go to the current view, and communicate with the local configuration * master to resolve the stream. */ try{ return remoteView.getLog(logID); } catch (RemoteException re) { IConfigMaster cm = (IConfigMaster) getView().getConfigMasters().get(0); String remoteLog = cm.getLog(logID); /** Go to the remote stream, communicate with the remote configuration master * and resolve the remote configuration. */ remoteLog = remoteLog.replace("cdbcm", "http"); remoteView.addLog(logID, remoteLog); return remoteView.getLog(logID); } } /** * Get the current view. This method optimisically acquires the * current view. */ public org.corfudb.runtime.view.CorfuDBView getView() { if (viewManagerThread == null || currentView == null || !currentView.isValid()) { if (viewManagerThread == null) { startViewManager(); } synchronized(viewUpdatePending) { while (viewUpdatePending.lock) { try { viewUpdatePending.wait(); } catch (InterruptedException ie) {} } } } long stamp = viewLock.tryOptimisticRead(); org.corfudb.runtime.view.CorfuDBView view = currentView; if (!viewLock.validate(stamp)) { //We should only get here if the view is being updated. stamp = viewLock.readLock(); view = currentView; viewLock.unlock(stamp); } return currentView; } public void close() { closed = true; viewManagerThread.interrupt(); } /** * Retrieves a runnable that provides a view manager thread. The view * manager retrieves the view and manages view changes. */ private Thread getViewManagerThread() { return new Thread(new Runnable() { @Override public void run() { log.debug("View manager thread started."); while (!closed) { synchronized(viewUpdatePending) { if (viewUpdatePending.lock) { log.debug("View manager retrieving view..."); //lock, preventing old view from being read. long stamp = viewLock.writeLock(); try { org.corfudb.runtime.view.CorfuDBView newView = retrieveView(configurationString); if (currentView == null || newView.getEpoch() > currentView.getEpoch()) { String oldEpoch = (currentView == null) ? "null" : Long.toString(currentView.getEpoch()); log.info("New view epoch " + newView.getEpoch() + " greater than old view epoch " + oldEpoch + ", changing views"); currentView = newView; localID = currentView.getUUID(); viewUpdatePending.lock = false; viewUpdatePending.notifyAll(); } else { log.info("New view epoch " + newView.getEpoch() + " is the same as previous..."); currentView.revalidate(); viewUpdatePending.lock = false; viewUpdatePending.notifyAll(); } } catch (IOException ie) { log.warn("Error retrieving view at " + configurationString + ": " + ie.getMessage()); if (currentView != null) {currentView.invalidate();} } finally { viewLock.unlock(stamp); } } else { while (!viewUpdatePending.lock) { try { viewUpdatePending.wait(); } catch (InterruptedException ie){ if (closed) { return; } } } } } } } }); } }
true
eb1f753f3da5270270ba2f2d279d1ec77106bbae
Java
brokenq/itsnow
/backend/msc-services/mutable-account-service/src/test/java/dnt/itsnow/config/MutableAccountsControllerConfig.java
UTF-8
1,500
2.25
2
[]
no_license
/** * xiongjie on 14-8-6. */ package dnt.itsnow.config; import dnt.itsnow.service.CommonUserService; import dnt.itsnow.service.MutableAccountService; import dnt.itsnow.test.config.ApplicationControllerConfig; import dnt.itsnow.web.controller.PublicAccountsController; import dnt.itsnow.web.controller.MutableAccountsController; import org.easymock.EasyMock; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * <h1>针对 Mutable Accounts Controller的测试所提供的控制器运行环境</h1> */ @Configuration public class MutableAccountsControllerConfig extends ApplicationControllerConfig { // Mocked service beans @Bean public MutableAccountService mutableAccountService(){ return EasyMock.createMock(MutableAccountService.class); } @Bean @Qualifier("plainUserService") public CommonUserService commonUserService(){ return EasyMock.createMock(CommonUserService.class); } //这个也不用scanner, // 因为在测试环境下,classpath没有隔离, // 会在dnt.itsnow.web.controller包种scan出许多其他控制器实例 @Bean public MutableAccountsController mutableAccountsController(){ return new MutableAccountsController(); } @Bean public PublicAccountsController accountsSignupController(){ return new PublicAccountsController(); } }
true
2c700596d7ff7d4f994ae7521c13bd7d432b1b5a
Java
Israel-E/Patos
/src/main/java/FlyRocketPowered.java
UTF-8
163
2.5625
3
[]
no_license
public class FlyRocketPowered implements FlyBehavior { @Override public void fly() { System.out.println("¡Estoy volando con un cohete!"); } }
true
a5b1a4f981518d0da1553dc5b2e075bbf2f04169
Java
zhiyuazo/basicJava
/basic_Swing/src/test/hero.java
UTF-8
89
2.046875
2
[]
no_license
package test; public class hero { String name ; hero(String n){ this.name = n; } }
true
376b4eaf11b5aab563fb55b93c29da0b4b6e6d74
Java
Kerbach/EstruturaDeDados
/src/aula8/TestSetMap.java
UTF-8
867
3.25
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package aula8; /** * * @author wrkerber */ import java.util.*; public class TestSetMap { public static void main(String[] args) throws Exception { HashSet <Integer> ts = new HashSet <Integer>(); ts.add(37); ts.add(68); ts.add(14); for (int e : ts) { System.out.println(e); } TreeMap <Integer,String> hm = new TreeMap <Integer,String>(); hm.put(37, "yesterday"); hm.put(68, "today"); hm.put(14, "tomorrow"); for (int k : hm.keySet()) { System.out.println(hm.get(k)); } } }
true
3a8d40c30bbce0f91def464bb65e03d47df57cec
Java
xiewen0303/jupiter-neo4j
/neo4j/src/main/java/com/neo4j/demo/entity/UserNode.java
UTF-8
752
2.296875
2
[]
no_license
package com.neo4j.demo.entity; import lombok.Data; import org.neo4j.ogm.annotation.GraphId; import org.neo4j.ogm.annotation.NodeEntity; import org.neo4j.ogm.annotation.Property; import java.io.Serializable; @Data @NodeEntity(label = "user") public class UserNode implements Serializable { @GraphId private Long id; //如何不设置@graphId字段的值,可以创建成功节点,但是如果认为设置@graphId字段的值,则不能成功创建节点 @Property(name = "name") private String name; @Property(name = "age") private int age; // @Property(name = "address") private String address; @Property(name = "sex") private String sex; @Property(name = "job") private String job; }
true
f896736e9402385d61a3e6f56225c49821f09473
Java
kvtoraman/Funny-Chemmy
/src/Element.java
UTF-8
1,391
3.171875
3
[]
no_license
public class Element { int atomNo; String name; String symbol; int valenceNumber; double atomicWeight; //this property must considered double electroNeg; static private int valenceArray[]= {-1,0,1,2,3,-4,-3,-2,-1,0,1,2,3,4,-3,-2,-1,0,1,2}; //coordinates of this element - used in DragGame int x; int y; public Element( int aNo, String aSymbol, String aName, String aNeg) { atomNo = aNo; name = aName; symbol = aSymbol; electroNeg = Double.parseDouble(aNeg); valenceNumber = valenceArray[aNo - 1]; } public Element(String elementName, int atomNumber, String atomicSymbol, double atomicWeight) { atomNo = atomNumber; symbol = atomicSymbol; this.atomicWeight = atomicWeight; name = elementName; } public Element() { } public Element(Element e) { atomNo = e.atomNo; name = e.name; symbol = e.symbol; electroNeg = e.electroNeg; valenceNumber = valenceArray[atomNo - 1]; } public boolean compareEN(Element a) { return electroNeg < a.electroNeg; } public String toString() { return "AtomNo:" + atomNo + " Name:" + name + " Valence: " + valenceNumber + " ElectroNegativity:" + electroNeg; } String getDescription() { String description; description = name + "\n" + "Atomic Number : " + atomNo + "\n" +"Atomic Symbol : " + symbol + "\n" + "Atomic Weight : " + atomicWeight; return(description); } }
true
ec715867689d225244350954c30b49a01e0b9619
Java
DDachev/SwiftAcad_HW_Lecture_06
/Ex05/Person.java
UTF-8
1,480
3.390625
3
[]
no_license
package bg.swift.HW06.ex05; import java.time.LocalDate; public class Person { private String firstName; private String lastName; private char gender; private LocalDate dateOfBirth; private short height; public SecondaryEducation se; public Person(String firstName, String lastName, char gender, LocalDate dateOfBirth, short height, String institutionName, LocalDate enrollmentDate, LocalDate graduationDate, double finalGrade) { this.firstName = firstName; this.lastName = lastName; this.gender = gender; this.dateOfBirth = dateOfBirth; this.height = height; this.se = new SecondaryEducation(institutionName, enrollmentDate, graduationDate, finalGrade); } public boolean isUnderAge(LocalDate dateOfBirth) { LocalDate dateNow = LocalDate.now(); if (dateNow.minusYears(18).compareTo(dateOfBirth) >= 0) { return true; } return false; } public int getAgeOfPerson() { LocalDate dateNow = LocalDate.now(); int ageOfPerson = dateNow.compareTo(this.dateOfBirth); boolean yearIsAfter = this.dateOfBirth.plusYears(dateNow.getYear() - this.dateOfBirth.getYear()) .isAfter(dateNow); if (yearIsAfter) { return ageOfPerson - 1; } return ageOfPerson; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public char getGender() { return gender; } public LocalDate getDateOfBirth() { return dateOfBirth; } public short getHeight() { return height; } }
true
6592b52350542338b6d404f0074493fddb793dba
Java
Aimintao/SSM-dpb
/src/main/java/com/dpb/base/controller/DepartmentController.java
UTF-8
649
1.929688
2
[]
no_license
package com.dpb.base.controller; import java.util.List; import javax.annotation.Resource; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.dpb.base.model.DeptBean; import com.dpb.base.service.IDeptService; @Controller @RequestMapping("/sys/dept") public class DepartmentController { @Resource private IDeptService deptService; @RequestMapping("/queryAll") @ResponseBody public List<DeptBean> queryAll(){ List<DeptBean> list = deptService.queryAll(null); return list; } }
true
d5b195ef15e09363aa135200ae67e542675e9b50
Java
dev-hui/java_study
/Java_dev/src/july_16th_oop04/Point2D.java
UTF-8
729
3.9375
4
[]
no_license
package july_16th_oop04; public class Point2D { int x; int y; public Point2D() { this(1,1); System.out.println("Point2D() 생성자 수행"); } // 1. public Point2D(){} << 디폴트 생성자. 다른 생성자가 없을 경우 (눈에는 안보이지만) 이런 거 만들어 줌! // 3. 따라서 디폴트 생성자를 별개로 만들어 주어야 error가 나지 않게 된다. @Override public String toString() { return "Point2D [x=" + x + ", y=" + y + "]"; } public Point2D(int x, int y) { // 2. 새로운 생성자 만든 것. 이 경우 디폴트 생성자가 사라짐 -> 잘 되던 기존 코드에 error this.x = x; this.y = y; System.out.println("Point2D(x, y) 생성자 수행"); } }
true
1975df70fd1ff524cc8496cad2d26a9f907da247
Java
Kaleakash/beljavadesignpattern
/JEE/ServiceLocator/src/com/JMSService.java
UTF-8
295
2.296875
2
[]
no_license
package com; public class JMSService implements Service{ @Override public void execute() { // TODO Auto-generated method stub System.out.println("Executing JMS Service"); } @Override public String getName() { // TODO Auto-generated method stub return "JMS Service Object"; } }
true
6f64fa46983a1f5e86025a7d46e0afedad9d1291
Java
lordaronwd/logsmonitor
/Backend/LogsMonitor/impl/src/main/java/com/monitor/impl/config/MonitorApplication.java
UTF-8
1,837
2.09375
2
[]
no_license
package com.monitor.impl.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; /** * Starts the application and sets up the basic configuration. * * @author lazar.agatonovic */ @Configuration @EnableAutoConfiguration @ComponentScan("com.monitor") public class MonitorApplication { @Autowired private Environment environment; @Bean public ConfigProperties configProperties() { final String defaultMonitoringInterval = environment.getProperty("monitoring.interval.seconds"); final String logFileLocation = environment.getProperty("log.file.location"); final String maximumLogEntryAge = environment.getProperty("max.log.entry.age.hours"); return new ConfigProperties(logFileLocation, defaultMonitoringInterval, maximumLogEntryAge); } @Bean public WebMvcConfigurer corsConfigurer() { return new WebMvcConfigurerAdapter() { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**"); } }; } public static void main(String[] args) { SpringApplication.run(MonitorApplication.class, args); } }
true
2b4981b8c3db86b74d90cd67c96bcdb992c819de
Java
eloyreinaga/hospital
/src/main/java/org/ayaic/web/administrarempresas/ConfirmarEmpresaControlador.java
UTF-8
9,787
1.953125
2
[]
no_license
package org.ayaic.web.administrarempresas; import java.util.HashMap; import java.util.Map; import java.util.List; import java.util.Date; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.ayaic.domain.Clientes; import org.ayaic.domain.Detalle; import org.ayaic.domain.Empresas; import org.ayaic.domain.Pacientes; import org.ayaic.domain.logic.MiFacade; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; @Controller public class ConfirmarEmpresaControlador { private final MiFacade mi; public ConfirmarEmpresaControlador(MiFacade mi) { this.mi = mi; } @RequestMapping("/ConfirmarEmpresa.do") public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) { Map modelo = new HashMap(); Clientes cliente = (Clientes) request.getSession().getAttribute("__sess_cliente"); String accion = request.getParameter("accion"); String accionq = request.getParameter("accionp"); String accion1 = request.getParameter("accion1"); String id_empresa = request.getParameter("id_empresa"); String id_carpeta = request.getParameter("id_carpeta"); String empresa = request.getParameter("empresa"); String nit = request.getParameter("nit"); String direccion = request.getParameter("direccion"); String telefonos = request.getParameter("telefonos"); String responsable = request.getParameter("responsable"); String id_estado = request.getParameter("id_estado"); String anio = request.getParameter("anio"); String mes = request.getParameter("mes"); String num_cladoc = request.getParameter("num_cladoc"); String codpatronal = request.getParameter("codpatronal"); Date fecha1 = new Date(); Empresas pai = new Empresas(); if ("Adicionar".equals(accion)) { // pai.setId_empresa(Integer.parseInt(id_empresa)) ; pai.setEmpresa(empresa); pai.setNit(nit); pai.setDireccion(direccion); pai.setTelefonos(telefonos); pai.setResponsable(responsable); modelo.put("dato", pai); modelo.put("accion", accion); modelo.put("accion1", accion1); } if ("Pagos".equals(accion)) { String accionp = request.getParameter("accionp"); String accionpago[] = request.getParameterValues("pago"); modelo.put("empresa", empresa); modelo.put("id_empresa", id_empresa); modelo.put("nit", nit); modelo.put("sw", request.getParameter("sw")); Pacientes paciente = new Pacientes(); paciente.setId_empresa(Integer.parseInt(id_empresa)); paciente.setTipo("F"); List listarPaises = this.mi.getListarPacientesEmp(paciente); if (listarPaises.size() > 0) { Pacientes Pacie = (Pacientes) listarPaises.get(0); id_carpeta = Integer.toString(Pacie.getId_carpeta()); modelo.put("id_carpeta", id_carpeta); } modelo.put("listaPacientes", listarPaises); modelo.put("accion", accion); modelo.put("accion1", accion1); return new ModelAndView("administrarempresas/ListarPacienteEmpresa", modelo); } if ("Ver Pagos".equals(accion)) { String accionp = request.getParameter("accionp"); String accionpago[] = request.getParameterValues("pago"); modelo.put("empresa", empresa); modelo.put("direccion", direccion); modelo.put("id_empresa", id_empresa); modelo.put("nit", nit); modelo.put("sw", request.getParameter("sw")); Pacientes paciente = new Pacientes(); paciente.setId_empresa(Integer.parseInt(id_empresa)); paciente.setTipo("F"); List listarPaises = this.mi.getListarPacientesEmp(paciente); if (listarPaises.size() > 0) { Pacientes Pacie = (Pacientes) listarPaises.get(0); id_carpeta = Integer.toString(Pacie.getId_carpeta()); modelo.put("id_carpeta", id_carpeta); } modelo.put("listaPacientes", listarPaises); Detalle detalle = new Detalle(); detalle.setId_pedido(1); detalle.setCod_esta(cliente.getCod_esta()); List listarPagos = this.mi.getListarDetallePago(detalle); modelo.put("listarpagos", listarPagos); modelo.put("accion", accion); modelo.put("accion1", accion1); return new ModelAndView("administrarempresas/ListarPacienteEmpresaP", modelo); } if ("Grabar Datos".equals(accion)) { String empresa2 = request.getParameter("empresa"); String id_empresa2 = request.getParameter("id_empresa"); String nit2 = request.getParameter("nit"); String anio2 = request.getParameter("anio"); String mes2 = request.getParameter("mes"); modelo.put("empresa", empresa2); modelo.put("id_empresa", id_empresa2); modelo.put("id_carpeta", id_carpeta); modelo.put("nit", nit2); modelo.put("anio", anio2); modelo.put("mes", mes2); Pacientes paciente = new Pacientes(); paciente.setId_empresa(Integer.parseInt(id_empresa)); paciente.setTipo("F"); List listarPac = this.mi.getListarPacientesEmp(paciente); modelo.put("numempleados", Integer.toString(listarPac.size())); Detalle detalle = new Detalle(); detalle.setId_pedido(1); detalle.setCod_esta(cliente.getCod_esta()); List listarPagos = this.mi.getListarDetallePago(detalle); modelo.put("listarpagos", listarPagos); return new ModelAndView("administrarempresas/ListarPagoEmpresa", modelo); } if ("Grabar".equals(accion)) { String empresa2 = request.getParameter("empresa"); String id_empresa2 = request.getParameter("id_empresa"); String nit2 = request.getParameter("nit"); String gestion = request.getParameter("anio"); String mes2 = request.getParameter("mes"); String costo_unit = request.getParameter("precio"); String id_pedido = request.getParameter("id_pedido"); Pacientes paciente = new Pacientes(); paciente.setId_empresa(Integer.parseInt(id_empresa)); paciente.setTipo("F"); List listarPac = this.mi.getListarPacientesEmp(paciente); modelo.put("numempleados", Integer.toString(listarPac.size())); paciente.setCod_esta(cliente.getCod_esta()); num_cladoc = Long.toString(this.mi.getNumClaDoc(paciente)); Pacientes dato = new Pacientes(); dato.setNombres(empresa); dato.setPrecio_total(Float.parseFloat(costo_unit)); dato.setId_paciente(0); dato.setId_estado("C"); dato.setNum_cladoc(num_cladoc); dato.setNit(nit2); //dato.setId_costo(9999) ; dato.setId_rubro(999); dato.setId_persona(cliente.getId_usuario()); dato.setId_carpeta(Integer.parseInt(id_carpeta)); dato.setId_paciente(Integer.parseInt(id_empresa)); dato.setTipo("C"); dato.setId_factura(0);/////0 sin factura, 1 con factura, 2, 3, 4, para num correlativo, entradas, ajuste+ y ajuste- dato.setFec_registro(fecha1); dato.setCod_esta(cliente.getCod_esta()); this.mi.setCrearPeedido(dato); id_pedido = Integer.toString(this.mi.getNumPedido(dato)); Detalle detalle = new Detalle(); detalle.setEntrada(Float.parseFloat(costo_unit)); detalle.setId_carpeta(Integer.parseInt(id_carpeta)); detalle.setId_empresa(Integer.parseInt(id_empresa)); detalle.setId_pedido(Integer.parseInt(id_pedido)); detalle.setMes(Integer.parseInt(mes)); detalle.setGestion(Integer.parseInt(gestion)); detalle.setId_rubro(999); detalle.setUlt_usuario(cliente.getId_usuario()); this.mi.setCrearDetallePago(detalle); return new ModelAndView("Aviso", "mensaje", "Los datos se grabaron correctamente"); } if ("Modificar".equals(accion)) { pai.setId_empresa(Integer.parseInt(id_empresa)); pai.setEmpresa(empresa); pai.setNit(nit); pai.setDireccion(direccion); pai.setTelefonos(telefonos); pai.setResponsable(responsable); pai.setCod_patronal(Long.parseLong(codpatronal)); ///pai.setId_estado(id_estado); pai.setId_estado("A"); modelo.put("dato", pai); modelo.put("codpatronal", codpatronal); modelo.put("sw", request.getParameter("sw")); modelo.put("accion", accion); modelo.put("accion1", accion1); } if ("Eliminar".equals(accion)) { Empresas buscarempresa = this.mi.getDatosEmpresa(Integer.parseInt(id_empresa)); // saca un registro a ser modificadoEmpresas buscarempresa modelo.put("dato", buscarempresa); modelo.put("accion", accion); modelo.put("sw1", request.getParameter("sw1")); modelo.put("id_parentesco", id_empresa); } return new ModelAndView("administrarempresas/ConfirmarEmpresa", modelo); } }
true
532255dcddf718b8904af9485623ae13e1c09c1c
Java
margmelo/The-Fundamentals-Of-Java
/hw7_Vehicles/Main.java
UTF-8
1,609
3.59375
4
[]
no_license
package pkg_hw7; /** * * @author https://www.linkedin.com/in/margmelo/ */ public class Main { public static void main(String[] args) { Cars a = new Cars("Opel", "Corsa", 1990, 870); //We set this car for 56 trips for (int i = 0; i < 56; i++) { a.drive(); a.stop(); } Cars b = new Cars("Wolkswagen", "Golf", 2010, 1239); //We set this car to 105 trips for (int i = 0; i < 105; i++) { b.drive(); b.stop(); } Cars c = new Cars("Renault", "Megane", 2020, 1392); // We set this car to 108 trips for (int i = 0; i < 108; i++) { c.drive(); c.stop(); } c.repair(); Planes d = new Planes("Boeing", "747", 2009, 183500); // We set this plane to 23 flights for (int i = 0; i < 23; i++) { d.flying(); d.landing(); } Planes e = new Planes("Airbus", "A300", 2002, 171700); //we fly 103 times. We check plane2 if it can fly //if it is not then it is in repair for (int i = 0; i < 103; i++) { e.flying(); if (!e.isFlying()) { break; } e.landing(); } Vehicle[] list = new Vehicle[5]; list[0] = a; list[1] = b; list[2] = c; list[3] = d; list[4] = e; for (int i =0; i< list.length; i++) { list[i].Print(); } } }
true
64a330a5fe6c6b53e5d1343a50398f46085bb646
Java
makewheels/AnalyzeBusDex
/src/main/java/com/alipay/security/mobile/module/p012b/C0164b.java
UTF-8
496
1.773438
2
[]
no_license
package com.alipay.security.mobile.module.p012b; import java.io.File; import java.io.FileFilter; import java.util.regex.Pattern; /* renamed from: com.alipay.security.mobile.module.b.b */ final class C0164b implements FileFilter { /* renamed from: a */ final /* synthetic */ C0163a f484a; C0164b(C0163a c0163a) { this.f484a = c0163a; } public final boolean accept(File file) { return Pattern.matches("cpu[0-9]+", file.getName()); } }
true
12b3afdc78bf6cf674e18ef949378efda2ee8ed3
Java
tfriedrichs/dicebot
/src/main/java/io/github/tfriedrichs/dicebot/expression/DiceRollExpression.java
UTF-8
4,965
3.21875
3
[ "MIT" ]
permissive
package io.github.tfriedrichs.dicebot.expression; import io.github.tfriedrichs.dicebot.evaluator.DiceRollEvaluator; import io.github.tfriedrichs.dicebot.evaluator.SumEvaluator; import io.github.tfriedrichs.dicebot.modifier.DiceRollModifier; import io.github.tfriedrichs.dicebot.result.DiceResult; import io.github.tfriedrichs.dicebot.result.DiceRoll; import io.github.tfriedrichs.dicebot.result.DiceRollResult; import io.github.tfriedrichs.dicebot.source.Die; import java.util.ArrayList; import java.util.List; /** * {@link DiceExpression} for representing the roll of a die or dice pool. It consists of a number of dice to roll, * the type of die to roll, a number of modifiers and an evaluator. * <p> * To calculate the result of a {@link #roll()} the expression uses the given die instance to assign values to each rolled die. * Then the modifiers are applied in order. */ public class DiceRollExpression implements DiceExpression { private final DiceExpression numberOfDice; private final Die die; private final List<DiceRollModifier> modifiers; private final DiceRollEvaluator evaluator; /** * Constructor. * * @param numberOfDice a dice expression which evaluates to the number of dice to roll. * @param die the type of die to roll * @param modifiers a list of modifiers * @param evaluator the evaluator */ public DiceRollExpression(DiceExpression numberOfDice, Die die, List<DiceRollModifier> modifiers, DiceRollEvaluator evaluator) { this.numberOfDice = numberOfDice; this.die = die; this.modifiers = modifiers; this.evaluator = evaluator; } @Override public DiceResult roll() { int numberOfDiceToRoll = this.numberOfDice.roll().getValue(); if (numberOfDiceToRoll < 0) { throw new IllegalArgumentException("Number of dice must not be negative"); } int[] rolls = die.roll(numberOfDiceToRoll).toArray(); DiceRoll result = new DiceRoll(rolls); for (DiceRollModifier modifier : modifiers) { result = modifier.modifyRoll(result, die); } return new DiceRollResult(evaluator.evaluate(result), result); } /** * Fluent interface builder for easier construction of {@link DiceRollExpression} instances. * <p> * It provides sensible default values for each unset attribute: * <ul> * <li>Number of dice: 1</li> * <li>Die type: D6</li> * <li>No modifiers</li> * <li>Sum evaluator</li> * </ul> */ public static class Builder { private DiceExpression numberOfDice = new NumberExpression(1); private Die die = Die.D6; private final List<DiceRollModifier> modifiers = new ArrayList<>(); private DiceRollEvaluator evaluator = new SumEvaluator(); /** * Sets the number of dice to roll to a {@link DiceExpression}. * * @param numberOfDice the expression representing the number of dice * @return the builder instance for chaining */ public Builder withNumberOfDice(DiceExpression numberOfDice) { this.numberOfDice = numberOfDice; return this; } /** * Sets the number of dice to a given number. * * @param numberOfDice the number of dice * @return the builder instance for chaining */ public Builder withNumberOfDice(int numberOfDice) { this.numberOfDice = new NumberExpression(numberOfDice); return this; } /** * Sets the die type. * * @param die the die type * @return the builder instance for chaining */ public Builder withDie(Die die) { this.die = die; return this; } /** * Adds a single modifier to the modifiers. * Successive calls to this method append the modifier to the end of the modifier list. * * @param modifier the modifier to add * @return the builder instance for chaining */ public Builder withModifier(DiceRollModifier modifier) { this.modifiers.add(modifier); return this; } /** * Sets the evaluator. * * @param evaluator the evaluator * @return the builder instance for chaining */ public Builder withEvaluator(DiceRollEvaluator evaluator) { this.evaluator = evaluator; return this; } /** * Constructs the expression. * * @return the constructed expression */ public DiceRollExpression build() { return new DiceRollExpression(numberOfDice, die, modifiers, evaluator); } } }
true
d719d46dc6637db00417caecfeb5c4c915a81433
Java
12chakram/personinfo
/src/com/persinfo/dao/UserDAO.java
UTF-8
2,946
2.625
3
[]
no_license
/** * */ package com.persinfo.dao; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.Query; import com.persinfo.data.User; import com.persinfo.utilities.EMF; /** * @author deva * */ public class UserDAO { public void addUser(User user){ EntityManager em = EMF.get().createEntityManager(); em.getTransaction().begin(); em.persist(user); em.getTransaction().commit(); em.close(); } public void updateUserInfo(User u){ EntityManager em = EMF.get().createEntityManager(); em.getTransaction().begin(); User user = em.find(User.class, u.getKey()); u.setKey(user.getKey()); em.persist(u); em.getTransaction().commit(); em.close(); } public User retrieveUserByUserNameAndPassword(String uname, String password){ EntityManager em = EMF.get().createEntityManager(); em.getTransaction().begin(); Query q = em.createQuery("select u from User u where u.uname='"+uname+"' and u.password='"+password+"' and u.active=True"); List<User> user= q.getResultList(); em.getTransaction().commit(); if(user.isEmpty()) return null; else return user.get(0); } public User retrieveUserByUserName(String uname){ EntityManager em = EMF.get().createEntityManager(); em.getTransaction().begin(); Query q = em.createQuery("select u from User u where u.uname='"+uname+"'"); List<User> user= q.getResultList(); em.getTransaction().commit(); if(user.isEmpty()) return null; else return user.get(0); } public User retrieveUserByEmail(String email){ EntityManager em = EMF.get().createEntityManager(); em.getTransaction().begin(); Query q = em.createQuery("select u from User u where u.email='"+email+"'"); List<User> user= q.getResultList(); em.getTransaction().commit(); if(user.isEmpty()) return null; else return user.get(0); } public List<User> retrieveAllActiveUsers(){ EntityManager em = EMF.get().createEntityManager(); em.getTransaction().begin(); Query q = em.createQuery("select u from User u where u.active=True"); List<User> users= q.getResultList(); em.getTransaction().commit(); if(users.isEmpty()) return null; else return users; } public void updateUser(User u){ EntityManager em = EMF.get().createEntityManager(); em.getTransaction().begin(); User user = em.find(User.class, u.getKey()); user.setActive(true); em.getTransaction().commit(); em.close(); } public User retrievePasswordByUsernameOrEmail(String input){ EntityManager em = EMF.get().createEntityManager(); em.getTransaction().begin(); Query q = em.createQuery("select u from User u where u.email='"+input+"'"); List<User> user= q.getResultList(); if(user.isEmpty()){ q = em.createQuery("select u from User u where u.uname='"+input+"'"); user= q.getResultList(); } em.getTransaction().commit(); if(user.isEmpty()) return null; else return user.get(0); } }
true
b8f92763bee9c7679cf681e1916c02d7be900092
Java
timur-sh/queryman-builder
/queryman-builder/src/test/java/org/queryman/builder/FlywayManager.java
UTF-8
552
1.921875
2
[ "MIT" ]
permissive
/* * Queryman. Java tools for working with queries of PostgreSQL database. * * License: MIT License. * To see license follow by http://queryman.org/license.txt */ package org.queryman.builder; import org.flywaydb.core.Flyway; /** * @author Timur Shaidullin */ public final class FlywayManager { public Flyway flyway = new Flyway(); public void init() { flyway.setDataSource(Bootstrap.BOOT.getDataSource()); } public void migrate() { flyway.migrate(); } public void clean() { flyway.clean(); } }
true
cd198e78ca9d11cb6cab8f86cfb52f8543c82060
Java
whizzosoftware/hobson-hub-dsc-it100
/src/test/java/com/whizzosoftware/hobson/dsc/api/command/PartitionArmControlWithCodeTest.java
UTF-8
1,156
2.46875
2
[]
no_license
package com.whizzosoftware.hobson.dsc.api.command; import com.whizzosoftware.hobson.api.HobsonInvalidRequestException; import org.junit.Test; import static org.junit.Assert.*; public class PartitionArmControlWithCodeTest { @Test public void testGetDataString() { // 6 character code PartitionArmControlWithCode pacwc = new PartitionArmControlWithCode(1, "123456"); assertEquals("1123456", pacwc.getDataString()); // 4 character code pacwc = new PartitionArmControlWithCode(1, "1234"); assertEquals("1123400", pacwc.getDataString()); // partition 8 pacwc = new PartitionArmControlWithCode(8, "432101"); assertEquals("8432101", pacwc.getDataString()); // invalid partition 0 try { new PartitionArmControlWithCode(0, "432101"); fail("Should have thrown exception"); } catch (HobsonInvalidRequestException e) {} // invalid partition 9 try { new PartitionArmControlWithCode(9, "432101"); fail("Should have thrown exception"); } catch (HobsonInvalidRequestException e) {} } }
true
91e04853722a76618da9b6688721195f9bf37541
Java
paddy235/my_sre_story
/java/notes/Backup2019.10.11/15.OverloadTest/OverloadTest01.java
GB18030
1,637
4.3125
4
[]
no_license
/* ´벻ʹáػơoverloadڵȱ㣿 1.sumIntsumLongsumDoubleȻܲͬǹƣ͡ ³УƵķֱ֣ͬԳԱ˵ ÷ʱ򲻷㣬ԱҪķɵá㡿 2.벻 ûһֻƣ ȻͬǡơʱûһֻƣóԱʹЩ ʱʹһһԱдdz㣬 ҲҪķҲۡ ֻƽػ ֵעǣ */ public class OverloadTest01{ public static void main(String[] args){ //÷ int result1=sumInt(1,2); System.out.println(result1); double result2=sumDouble(1.0,2.0); System.out.println(result2); long result3=sumLong(1L,2L); System.out.println(result3); } //Զ巽 //intݺ public static int sumInt(int a,int b){ return a+b; } //doubleݺ public static double sumDouble(double a,double b){ return a+b; } //longݺ public static long sumLong(long a,long b){ return a+b; } //ϣﵽԱʹƵķһһ //Javaֻ֧ơЩԲ֧֣Ժѧϰjavascript }
true
27ac4caab3ba0c1b8268b663d89a9b4d23d5ac48
Java
Draywer/NetologyJava
/JavaBase/src/main/java/ru/idcore/basejava/task0332/accounts/Account.java
UTF-8
1,970
3.5
4
[]
no_license
package ru.idcore.basejava.task0332.accounts; public abstract class Account { protected AccountType accountType; protected int accountNumber; protected int balance; protected Account() { this.balance = 0; } public AccountType getAccountType() { return accountType; } public int getBalance() { return balance; } public int getAccountNumber() { return accountNumber; } public void setAccountType(AccountType accountType) { this.accountType = accountType; } public void setBalance(int balance) { this.balance = balance; } public void setAccountNumber(int accountNumber) { this.accountNumber = accountNumber; } @Override public boolean equals(Object object) { if (this == object) return true; if (object == null || getClass() != object.getClass()) return false; Account account = (Account) object; return accountType.equals(account.accountType) && balance == account.balance; } @Override public String toString() { return "\nНомер счета: " + accountNumber + "\nТип счета: " + accountType + "\nБаланс счета: " + balance; } //оплатить со счета public void pay(int amount) { balance -= amount; System.out.println("Платеж выполнен успешно"); } //перевести между счетами public void transfer(Account accountDestination, int amount) { balance -= amount; accountDestination.addMoney(amount); System.out.println("Операция списания выполнена успешно"); } //пополнить счет public void addMoney(int amount) { balance += amount; System.out.println("Операция пополнения выполнена успешно"); } }
true
d37f15f25dbbb3a5e59ded03514d7f830ec573a2
Java
cepprice/maps
/app/src/main/java/ru/cepprice/maps/data/model/mapstate/Downloaded.java
UTF-8
1,554
1.9375
2
[]
no_license
package ru.cepprice.maps.data.model.mapstate; import android.content.Context; import android.graphics.ColorFilter; import android.graphics.PorterDuff; import android.graphics.drawable.Drawable; import android.os.Parcel; import android.os.Parcelable; import android.util.Log; import androidx.core.content.ContextCompat; import ru.cepprice.maps.R; import ru.cepprice.maps.data.model.Region; import ru.cepprice.maps.ui.adapter.RegionListAdapter; import ru.cepprice.maps.data.remote.MapsDownloadManager; public class Downloaded extends MapState { public static final Parcelable.Creator<Downloaded> CREATOR = new Parcelable.Creator<Downloaded>() { @Override public Downloaded createFromParcel(Parcel source) { return new Downloaded(source); } @Override public Downloaded[] newArray(int size) { return new Downloaded[size]; } }; public Downloaded() {} protected Downloaded(Parcel in) { super(in); } @Override public void onImageButtonClick( Region region, RegionListAdapter.RegionViewHolder holder, MapsDownloadManager downloadManager ) { // Do nothing Log.d("M_Downloaded", "Do nothing"); } @Override public void renderViewHolder(RegionListAdapter.RegionViewHolder holder, int progress) { Context context = holder.getIvMap().getContext(); setImageDrawable(holder.getIvMap(), getColoredMapDrawable(context)); setImageDrawable(holder.getIvAction(), null); } }
true
3b3227c9686779415aee8ab78950e49dd955befe
Java
P79N6A/icse_20_user_study
/methods/Method_34375.java
UTF-8
759
2.40625
2
[]
no_license
public OAuth2Authentication readAuthentication(String token){ OAuth2Authentication authentication=null; try { authentication=jdbcTemplate.queryForObject(selectAccessTokenAuthenticationSql,new RowMapper<OAuth2Authentication>(){ public OAuth2Authentication mapRow( ResultSet rs, int rowNum) throws SQLException { return deserializeAuthentication(rs.getBytes(2)); } } ,extractTokenKey(token)); } catch ( EmptyResultDataAccessException e) { if (LOG.isInfoEnabled()) { LOG.info("Failed to find access token for token " + token); } } catch ( IllegalArgumentException e) { LOG.warn("Failed to deserialize authentication for " + token,e); removeAccessToken(token); } return authentication; }
true
9f8ab64d66bd63a86605f5d269fddb3a2e25e2d2
Java
LARGH/Ejercicio-EJB-BD-Sistemas-Distribuidos
/DemoApp/build/generated-sources/ap-source-output/com/ipn/mx/model/Carrera_.java
UTF-8
751
1.640625
2
[]
no_license
package com.ipn.mx.model; import com.ipn.mx.model.Alumno; import javax.annotation.Generated; import javax.persistence.metamodel.ListAttribute; import javax.persistence.metamodel.SingularAttribute; import javax.persistence.metamodel.StaticMetamodel; @Generated(value="EclipseLink-2.5.2.v20140319-rNA", date="2017-12-11T14:20:24") @StaticMetamodel(Carrera.class) public class Carrera_ { public static volatile SingularAttribute<Carrera, String> descripcion; public static volatile SingularAttribute<Carrera, Integer> idCarrera; public static volatile ListAttribute<Carrera, Alumno> alumnoList; public static volatile SingularAttribute<Carrera, String> nombre; public static volatile SingularAttribute<Carrera, Boolean> status; }
true
3a96469b5f23043382397e7acc4318124be4d63f
Java
javaGuruBY/java-free-stream-5
/homeWork_01/ex1_ObjectsAroundUs/Vladimir_Petranovski/src/com/exemple/HW1_task1/App.java
UTF-8
5,054
3.46875
3
[]
no_license
package com.exemple.HW1_task1; //делаю домашку первую задачу public class App { public static void main(String[] args) { App app = new App(); } public App() { fan(); spoon(); paper(); cup(); glove(); column(); postcard(); folder(); scissors(); chair(); } public void fan() { System.out.println("1. Вентилятор\n" + "\n" + "Состояние:\n" + "-вкл/выкл\n" + "-раздвинут/сдвинут\n" + "-разобран/собран\n" + "Поведение:\n" + "-дует/не дует\n" + "-можно поставить в др. место\n"); } public void spoon() { System.out.println("2. Ложка\n" + "\n" + "Состояние:\n" + "-не ржавая\n" + "-лежит\n" + "-грязная\n" + "Поведение:\n" + "-находится в состоянии пооя\n" + "-можно поднести ко рту\n"); } public void paper() { System.out.println("3. Лист бумаги\n" + "\n" + "Состояние:\n" + "-чистый\n" + "-расписанный\n" + "-помят\n" + "Поведение:\n" + "-находится в папке\n" + "-находится в руке\n" + "-мнется руками\n"); } public void cup() { System.out.println("4. Кружка\n" + "\n" + "Состояние:\n" + "-наполнена водой\n" + "-пустая\n" + "-стоит на столе\n" + "Поведение:\n" + "-разбивается\n" + "-переносится с места на место\n" + "-передвигается вверх вниз\n"); } public void glove() { System.out.println("5. Перчатка\n" + "\n" + "Состояние:\n" + "-старая\n" + "-теплая\n" + "-находится в покое\n" + "Поведение:\n" + "-носится на руке\n" + "-греет\n" + "-защищает от мокрого снега\n"); } public void column() { System.out.println("6. Колонка\n" + "\n" + "Состояние:\n" + "-вкл/выкл\n" + "-теплая\n" + "-воспроизводит звук\n" + "Поведение:\n" + "-стоит на полу\n" + "-дребежжит\n" + "-моргает\n"); } public void postcard() { System.out.println("7. Открытка\n" + "\n" + "Состояние:\n" + "-ровная\n" + "-раскрыта\n" + "-твердая\n" + "Поведение:\n" + "-приносит радость\n" + "-удивляет\n" + "-стоит на полке\n"); } public void folder() { System.out.println("8. Папка\n" + "\n" + "Состояние:\n" + "-помята\n" + "-твердая\n" + "-заполнена\n" + "Поведение:\n" + "-лежит в шкафу\n" + "-мозолит глаз\n" + "-находится в покое\n"); } public void scissors() { System.out.println("9. Ножницы\n" + "\n" + "Состояние:\n" + "-холодные\n" + "-твердые\n" + "-острые\n" + "Поведение:\n" + "-носятся в руке\n" + "-режут\n" + "-ровняют\n"); } public void chair() { System.out.println("10. Стул\n" + "\n" + "Состояние:\n" + "-крепкий\n" + "-обтянут кожей\n" + "-на высокой ножке\n" + "Поведение:\n" + "-крутится вокруг своей оси\n" + "-спинка наклоняется\n" + "-поддерживает осанку"); } }
true
e839b01cde275afa9b6ae1e7a37b57ebcf7eb8d2
Java
psheemas/kodilla-course-master
/kodilla-good-patterns/src/main/java/com/kodilla/good/patterns/challenges/OrderedItems.java
UTF-8
222
2.46875
2
[]
no_license
package com.kodilla.good.patterns.challenges; public class OrderedItems { public boolean buyNow(User user, Item item) { System.out.println("VegetablesAndFruits marked as bought"); return true; } }
true
f5fc655556021ab438ac1424a46ed05f2cfbed7d
Java
d5nguyenvan/structr
/structr/structr-core-ui/src/main/java/org/structr/ui/page/admin/EditCsvFile.java
UTF-8
2,850
2.25
2
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.structr.ui.page.admin; import java.util.Map; import java.util.Set; import org.apache.click.control.FieldSet; import org.apache.click.control.Form; import org.apache.click.control.HiddenField; import org.apache.click.control.Label; import org.apache.click.control.Option; import org.apache.click.control.Select; import org.apache.click.control.Submit; import org.structr.core.Services; import org.structr.core.agent.ConversionTask; import org.structr.core.agent.ProcessTaskCommand; import org.structr.core.entity.CsvFile; import org.structr.core.entity.AbstractNode; import org.structr.core.module.GetEntitiesCommand; import org.structr.core.module.GetEntityClassCommand; /** * * @author amorgner */ public class EditCsvFile extends EditFile { protected Submit createNodeListSubmit = new Submit("Create Node List", this, "onCreateNodeList"); protected Form editContentForm = new Form("editContentForm"); protected FieldSet conversionFields = new FieldSet("File Conversion"); protected Select nodeTypeField = new Select(AbstractNode.TYPE_KEY, "Select Node Type", true); protected CsvFile csvNode; public EditCsvFile() { super(); conversionFields.add(new Label("A CSV file can be converted to a node list. The columns have to match exactly the node properties of the selected node type!")); nodeTypeField.add(new Option("", "--- Select Node Type ---")); Set<String> nodeTypes = ((Map<String, Class>) Services.command(GetEntitiesCommand.class).execute()).keySet(); for (String className : nodeTypes) { Option o = new Option(className); nodeTypeField.add(o); } conversionFields.add(nodeTypeField); conversionFields.add(createNodeListSubmit); editContentForm.add(conversionFields); } @Override public void onInit() { super.onInit(); if (node != null) { editContentForm.add(new HiddenField(AbstractNode.NODE_ID_KEY, getNodeId())); csvNode = (CsvFile) node; } addControl(editContentForm); } public boolean onCreateNodeList() { if (csvNode == null) { return true; } if (editContentForm.isValid()) { String className = nodeTypeField.getValue(); if (className == null) { return true; } Class nodeClass = (Class) Services.command(GetEntityClassCommand.class).execute(className); Services.command(ProcessTaskCommand.class).execute(new ConversionTask(user, csvNode, nodeClass)); // Services.command(ConvertCsvToNodeListCommand.class).execute(user, csvNode, nodeClass); } return false; } }
true
8286408bac210d6388881c6359c4de9c0621d548
Java
chenJz1012/os-app
/os-common/src/main/java/com/orangeside/common/utils/PropertiesUtil.java
UTF-8
767
2
2
[]
no_license
package com.orangeside.common.utils; import org.springframework.core.io.Resource; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.support.PropertiesLoaderUtils; import java.io.IOException; import java.util.Properties; /** * 工程:os-app 创建人 : ChenGJ 创建时间: 2015/9/7 说明: */ public class PropertiesUtil { public static String get(String properties, String key) { try { //Properties props = PropertiesLoaderUtils.loadAllProperties("jdbc.properties"); return PropertiesLoaderUtils.loadAllProperties(properties).getProperty(key, "未识别的业务异常"); } catch (IOException e) { e.printStackTrace(); return ""; } } }
true
cc10b877110ca58db32f531f4ca3cfeadf7a77c0
Java
zeng233/rejdk
/src/test/java/ajava/util/concurrent/adouglea/functionality/Mutex100M.java
UTF-8
2,367
3.0625
3
[ "Apache-2.0" ]
permissive
package ajava.util.concurrent.adouglea.functionality; /* * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/publicdomain/zero/1.0/ */ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.*; import java.util.concurrent.locks.*; import ajava.util.concurrent.*; class Mutex100M { public static void main(String[] args) throws Exception { int x = loop((int) System.nanoTime(), 100000); x = loop(x, 100000); x = loop(x, 100000); long start = System.nanoTime(); x = loop(x, 100000000); if (x == 0) System.out.print(" "); long time = System.nanoTime() - start; double secs = (double) time / 1000000000.0; System.out.println("time: " + secs); start = System.nanoTime(); x = loop(x, 100000000); if (x == 0) System.out.print(" "); time = System.nanoTime() - start; secs = (double) time / 1000000000.0; System.out.println("time: " + secs); } static final Mutex100M.Mutex lock = new Mutex100M.Mutex(); static int loop(int x, int iters) { final Mutex100M.Mutex l = lock; for (int i = iters; i > 0; --i) { l.lock(); x = x * 134775813 + 1; l.unlock(); } return x; } static final class Mutex extends AbstractQueuedSynchronizer { public boolean isHeldExclusively() { return getState() == 1; } public boolean tryAcquire(int acquires) { return getState() == 0 && compareAndSetState(0, 1); } public boolean tryRelease(int releases) { setState(0); return true; } public Condition newCondition() { return new ConditionObject(); } public void lock() { if (!compareAndSetState(0, 1)) acquire(1); } public boolean tryLock() { return tryAcquire(1); } public void lockInterruptibly() throws InterruptedException { acquireInterruptibly(1); } public boolean tryLock(long timeout, TimeUnit unit) throws InterruptedException { return tryAcquireNanos(1, unit.toNanos(timeout)); } public void unlock() { release(1); } } }
true
40c1021bc0355e716a66632d44d60b20e4ebd44b
Java
captn3m0/mygov.aadhaar.ekyc
/enjarify/mygov/aadhaar/ekyc/firebase/MyFirebaseInstanceIDService.java
UTF-8
666
1.65625
2
[]
no_license
package mygov.aadhaar.ekyc.firebase; import android.util.Log; import com.google.firebase.iid.FirebaseInstanceId; import com.google.firebase.iid.FirebaseInstanceIdService; public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService { public final void a() { String str = FirebaseInstanceId.a().b(); StringBuilder localStringBuilder = new java/lang/StringBuilder; localStringBuilder.<init>("Refreshed token: "); str = str; Log.d("MyFirebaseIIDService", str); } } /* Location: mygov/aadhaar/ekyc/firebase/MyFirebaseInstanceIDService.class * Java compiler version: 5 (49.0) * JD-Core Version: 0.7.1 */
true
201e9e5046e3f231083d9a868947da96bab3379d
Java
ahmedHasn/micro-services-spring-boot
/PhotoAppApiUsers/src/main/java/com/photoappuser/payload/response/AlbumResponse.java
UTF-8
309
1.648438
2
[]
no_license
package com.photoappuser.payload.response; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @NoArgsConstructor @AllArgsConstructor public class AlbumResponse { private String albumId; private String userId; private String name; private String describtion; }
true
fb257d0070f317ae8de7c919cb4ed041aa35cb7e
Java
lizhieffe/EPI
/src/Chap14/Q01.java
UTF-8
1,630
3.53125
4
[]
no_license
package Chap14; import java.util.ArrayList; public class Q01 { int[] findSame(int[] a, int[] b) { if (a == null || a.length == 0 || b == null || b.length == 0) return new int[0]; else if (a.length / b.length > 10 || b.length / a.length > 10) return notSimilarLength(a, b); else return similarLength(a, b); } private int[] notSimilarLength(int[] a, int[] b) { if (a.length < b.length) { int[] tmp = a; a = b; b = tmp; } ArrayList<Integer> resultList = new ArrayList<Integer>(); BinarySearch bs = new BinarySearch(a); for (int i = 0; i < b.length; i ++) { int tmp = bs.find(b[i]); if (tmp != -1) resultList.add(a[tmp]); } int[] result = new int[resultList.size()]; for (int i = 0; i < resultList.size(); i ++) result[i] = resultList.get(i); return result; } private int[] similarLength(int[] a, int[] b) { int lengthA = a.length; int lengthB = b.length; int i = 0; int j = 0; ArrayList<Integer> resultList = new ArrayList<Integer>(); while (i < lengthA && j < lengthB) { if (a[i] == b[j]) { resultList.add(a[i]); i ++; j ++; } else if (a[i] < b[j]) i ++; else j ++; } int[] result = new int[resultList.size()]; for (i = 0; i < resultList.size(); i ++) result[i] = resultList.get(i); return result; } public static void main(String[] args) { int[] a = {1, 5, 11, 15, 21, 25, 31, 35, 41, 45, 51, 55, 61, 65, 71, 75}; // int[] b = {-1, 3, 11, 13, 64, 72, 75}; int[] b = {11}; Q01 service = new Q01(); int[] same = service.findSame(a, b); System.out.println(same); } }
true
821dbff5323613265e890e5f0350ad94c607c926
Java
lucky-lanes/Lucky-Lanes
/src/main/formObjects/YBalance.java
UTF-8
19,284
2.703125
3
[ "Apache-2.0" ]
permissive
package main.formObjects; import main.java.Database; /** * YBalance Object. * <p> * It represents the form used for the YBalance test. */ public class YBalance { /** * Right limb length in centimeters (cm) */ private double rightLimbLength; /** * Average of the three measurements for the anterior with the right. Unit is centimeters (cm) */ private double antRightMean; /** * Average of the three measurements for the anterior with the left. Unit is centimeters (cm) */ private double antLeftMean; /** * Average of the three measurements for the posteromedial with the right. Unit is centimeters (cm) */ private double pmRightMean; /** * Average of the three measurements for the posteromedial with the left. Unit is centimeters (cm) */ private double pmLeftMean; /** * Average of the three measurements for the posterolateral with the right. Unit is centimeters (cm) */ private double plRightMean; /** * Average of the three measurements for the posterolateral with the left. Unit is centimeters (cm) */ private double plLeftMean; /** * First measurement, in centimeters (cm), for the right anterior */ private double antR1; /** * Second measurement, in centimeters (cm), for the right anterior */ private double antR2; /** * Third measurement, in centimeters (cm), for the right anterior */ private double antR3; /** * First measurement, in centimeters (cm), for the left anterior */ private double antL1; /** * Second measurement, in centimeters (cm), for the left anterior */ private double antL2; /** * Third measurement, in centimeters (cm), for the left anterior */ private double antL3; /** * First measurement, in centimeters (cm), for the right posteromedial */ private double pmR1; /** * Second measurement, in centimeters (cm), for the right posteromedial */ private double pmR2; /** * Third measurement, in centimeters (cm), for the right posteromedial */ private double pmR3; /** * First measurement, in centimeters (cm), for the left posteromedial */ private double pmL1; /** * Second measurement, in centimeters (cm), for the left posteromedial */ private double pmL2; /** * Third measurement, in centimeters (cm), for the left posteromedial */ private double pmL3; /** * First measurement, in centimeters (cm), for the right posterolateral */ private double plR1; /** * Second measurement, in centimeters (cm), for the right posterolateral */ private double plR2; /** * Third measurement, in centimeters (cm), for the right posterolateral */ private double plR3; /** * First measurement, in centimeters (cm), for the left posterolateral */ private double plL1; /** * Second measurement, in centimeters (cm), for the left posterolateral */ private double plL2; /** * Third measurement, in centimeters (cm), for the left posterolateral */ private double plL3; private double compositeLeft; private double compositeRight; /** * Constructor that takes in all required fields. * * @param rightLimbLength Right limb length in centimeters (cm) * @param antR1 First measurement, in centimeters (cm), for the right anterior * @param antR2 Second measurement, in centimeters (cm), for the right anterior * @param antR3 Third measurement, in centimeters (cm), for the right anterior * @param antL1 First measurement, in centimeters (cm), for the left anterior * @param antL2 Second measurement, in centimeters (cm), for the left anterior * @param antL3 Third measurement, in centimeters (cm), for the left anterior * @param pmR1 First measurement, in centimeters (cm), for the right posteromedial * @param pmR2 Second measurement, in centimeters (cm), for the right posteromedial * @param pmR3 Third measurement, in centimeters (cm), for the right posteromedial * @param pmL1 First measurement, in centimeters (cm), for the left posteromedial * @param pmL2 Second measurement, in centimeters (cm), for the left posteromedial * @param pmL3 Third measurement, in centimeters (cm), for the left posteromedial * @param plR1 First measurement, in centimeters (cm), for the right posterolateral * @param plR2 Second measurement, in centimeters (cm), for the right posterolateral * @param plR3 Third measurement, in centimeters (cm), for the right posterolateral * @param plL1 First measurement, in centimeters (cm), for the left posterolateral * @param plL2 Second measurement, in centimeters (cm), for the left posterolateral * @param plL3 Third measurement, in centimeters (cm), for the left posterolateral */ public YBalance(double rightLimbLength, double antR1, double antR2, double antR3, double antL1, double antL2, double antL3, double pmR1, double pmR2, double pmR3, double pmL1, double pmL2, double pmL3, double plR1, double plR2, double plR3, double plL1, double plL2, double plL3) { this.pmL1 = pmL1; this.pmL2 = pmL2; this.pmL3 = pmL3; this.pmR1 = pmR1; this.pmR2 = pmR2; this.pmR3 = pmR3; this.plL1 = pmL1; this.plL2 = pmL2; this.plL3 = pmL3; this.plR1 = pmR1; this.plR2 = pmR2; this.plR3 = pmR3; this.antL1 = antL1; this.antL2 = antL2; this.antL3 = antL3; this.antR1 = antR1; this.antR2 = antR2; this.antR3 = antR3; this.rightLimbLength = rightLimbLength; this.antRightMean = Math.max(Math.max(antR1, antR2), antR3); this.antLeftMean = Math.max(Math.max(antL1, antL2), antL3); this.pmRightMean = Math.max(Math.max(pmR1, pmR2), pmR3); this.pmLeftMean = Math.max(Math.max(pmL1, pmL2), pmL3); this.plRightMean = Math.max(Math.max(plR1, plR2), plR3); this.plLeftMean = Math.max(Math.max(plL1, plL2), plL3); this.compositeLeft = ((this.antLeftMean + this.pmLeftMean + this.plLeftMean) / (3 * this.rightLimbLength)) * 100; this.compositeRight = ((this.antRightMean + this.pmRightMean + this.plRightMean) / (3 * this.rightLimbLength)) * 100; } /** * Creates an html table representation of the YBalance object * * @return String with the HTML table representation of the YBalance object. */ public String toHTML() { String rowStart = "<tr><td>"; String rowMid = "</td><td>"; String rowEnd = "</td></tr>"; String html = "</br></br></br><table><tr><th>Y-Balance</th><th></th></tr>"; html += rowStart + "Left Posteromedial 1" + rowMid + this.pmL1 + rowEnd + rowStart + "Left Posteromedial 2" + rowMid + this.pmL2 + rowEnd + rowStart + "Left Posteromedial 3" + rowMid + this.pmL3 + rowEnd + rowStart + "Right Posteromedial 1" + rowMid + this.pmR1 + rowEnd + rowStart + "Right Posteromedial 2" + rowMid + this.pmR2 + rowEnd + rowStart + "Right Posteromedial 3" + rowMid + this.pmR3 + rowEnd + rowStart + "Left Posterolateral 1" + rowMid + this.plL1 + rowEnd + rowStart + "Left Posterolateral 2" + rowMid + this.plL2 + rowEnd + rowStart + "Left Posterolateral 3" + rowMid + this.plL3 + rowEnd + rowStart + "Right Posterolateral 1" + rowMid + this.plR1 + rowEnd + rowStart + "Right Posterolateral 2" + rowMid + this.plR2 + rowEnd + rowStart + "Right Posterolateral 3" + rowMid + this.plR3 + rowEnd + rowStart + "Left Anterior 1" + rowMid + this.antL1 + rowEnd + rowStart + "Left Anterior 2" + rowMid + this.antL2 + rowEnd + rowStart + "Left Anterior 3" + rowMid + this.antL3 + rowEnd + rowStart + "Right Anterior 1" + rowMid + this.antR1 + rowEnd + rowStart + "Right Anterior 2" + rowMid + this.antR2 + rowEnd + rowStart + "Right Anterior 3" + rowMid + this.antR3 + rowEnd + rowStart + "Right Limb Length" + rowMid + this.rightLimbLength + rowEnd + rowStart + "Right Anterior Mean " + rowMid + this.antRightMean + rowEnd + rowStart + "Left Anterior Mean " + rowMid + this.antLeftMean + rowEnd + rowStart + "Left Posteromedial Mean" + rowMid + this.pmLeftMean + rowEnd + rowStart + "Right Posteromedial Mean" + rowMid + this.pmRightMean + rowEnd + rowStart + "Left Posterolateral Mean" + rowMid + this.plLeftMean + rowEnd + rowStart + "Right Posterolateral Mean" + rowMid + this.plRightMean + rowEnd + "</table>"; return html; } /** * Method to generate a string representation of the YBalance for use in generating a pdf report on the athlete. * * @return A string containing all of the information of the YBalance test. Each field is separated by a "|" character */ public String toPDF() { String pdf = "Y-Balance|" + this.pmL1 + "|" + this.pmL2 + "|" + this.pmL3 + "|" + this.pmR1 + "|" + this.pmR2 + "|" + this.pmR3 + "|" + this.plL1 + "|" + this.plL2 + "|" + this.plL3 + "|" + this.plR1 + "|" + this.plR2 + "|" + this.plR3 + "|" + this.antL1 + "|" + this.antL2 + "|" + this.antL3 + "|" + this.antR1 + "|" + this.antR2 + "|" + this.antR3 + "|" + this.rightLimbLength + "|" + this.antRightMean + "|" + this.antLeftMean + "|" + this.pmLeftMean + "|" + this.pmRightMean + "|" + this.plLeftMean + "|" + this.plRightMean; return pdf; } /** * Empty constructor */ public YBalance() { } /** * Sets the rightLimbLength in cm * * @param rightLimbLength Right limb length in centimeters (cm) */ public void setRightLimbLength(double rightLimbLength) { this.rightLimbLength = rightLimbLength; } /** * Takes in three measurements for right anterior and sets antRightMean to the average of the 3 * * @param ant1 1st measurement for the right anterior in centimeters (cm) * @param ant2 2nd measurement for the right anterior in centimeters (cm) * @param ant3 3rd measurement for the right anterior in centimeters (cm) */ public void setRightAntMean(double ant1, double ant2, double ant3) { this.antRightMean = (ant1 + ant2 + ant3) / 3.0; } /** * Takes in three measurements for left anterior and sets antLeftMean to the average of the 3 * * @param ant1 1st measurement for the left anterior in centimeters (cm) * @param ant2 2nd measurement for the left anterior in centimeters (cm) * @param ant3 3rd measurement for the left anterior in centimeters (cm) */ public void setLeftAntMean(double ant1, double ant2, double ant3) { this.antLeftMean = (ant1 + ant2 + ant3) / 3.0; } /** * Takes in 3 measurements for right posteromedial and sets pmRightMean to the average of the 3 * * @param num1 1st measurement for the right posteromedial in centimeters (cm) * @param num2 2nd measurement for the right posteromedial in centimeters (cm) * @param num3 3rd measurement for the right posteromedial in centimeters (cm) */ public void setPmRightMean(double num1, double num2, double num3) { this.pmRightMean = (num1 + num2 + num3) / 3.0; } /** * Takes in 3 measurements for left posteromedial and sets pmLeftMean to the average of the 3 * * @param num1 1st measurement for the left posteromedial in centimeters (cm) * @param num2 2nd measurement for the left posteromedial in centimeters (cm) * @param num3 3rd measurement for the left posteromedial in centimeters (cm) */ public void setPmLeftMean(double num1, double num2, double num3) { this.pmLeftMean = (num1 + num2 + num3) / 3.0; } /** * Takes in 3 measurements for right posterolateral and sets pmRightMean to the average of the 3 * * @param num1 1st measurement for the right posterolateral in centimeters (cm) * @param num2 2nd measurement for the right posterolateral in centimeters (cm) * @param num3 3rd measurement for the right posterolateral in centimeters (cm) */ public void setPLRightMean(double num1, double num2, double num3) { this.plRightMean = (num1 + num2 + num3) / 3.0; } /** * Takes in 3 measurements for left posterolateral and sets pmLeftMean to the average of the 3 * * @param num1 1st measurement for the left posterolateral in centimeters (cm) * @param num2 2nd measurement for the left posterolateral in centimeters (cm) * @param num3 3rd measurement for the left posterolateral in centimeters (cm) */ public void setPLLeftMean(double num1, double num2, double num3) { this.plLeftMean = (num1 + num2 + num3) / 3.0; } /** * Calculates the difference between the averages for the left and right for anterior * * @return The difference between the averages for the left and right for anterior */ public double getAntDiff() { return this.antRightMean - this.antLeftMean; } /** * Calculates the difference between the averages for the left and right for posteromedial * * @return The difference between the averages for the left and right for posteromedial */ public double getPmDiff() { return this.pmRightMean - this.pmLeftMean; } /** * Calculates the difference between the averages for the left and right for posterolateral * * @return The difference between the averages for the left and right for posterolateral */ public double getPlDiff() { return this.plRightMean - this.plLeftMean; } /** * Calculates the composite score for the right * * @return The composite score for the right */ public double getRightScore() { return this.pmRightMean + this.plRightMean + this.antRightMean; } /** * Calculates the composite score for the left * * @return The composite score for the left */ public double getLeftScore() { return this.pmLeftMean + this.plLeftMean + this.antLeftMean; } /** * Getter method for the right limb length * * @return The right limb length in centimeters (cm) */ public double getRightLimbLength() { return rightLimbLength; } /** * Getter method for the average of the right anterior measurements * * @return The average of the right anterior measurements. Unit is centimeters */ public double getAntRightMean() { return antRightMean; } /** * Getter method for the average of the left anterior measurements * * @return The average of the left anterior measurements. Unit is centimeters */ public double getAntLeftMean() { return antLeftMean; } /** * Getter method for the average of the right posteromedial measurements * * @return The average of the right posteromedial measurements. Unit is centimeters */ public double getPmRightMean() { return pmRightMean; } /** * Getter method for the average of the left posteromedial measurements * * @return The average of the left posteromedial measurements. Unit is centimeters */ public double getPmLeftMean() { return pmLeftMean; } /** * Getter method for the average of the right posterolateral measurements * * @return The average of the right posterolateral measurements. Unit is centimeters */ public double getPlRightMean() { return plRightMean; } /** * Getter method for the average of the left posterolateral measurements * * @return The average of the left posterolateral measurements. Unit is centimeters */ public double getPlLeftMean() { return plLeftMean; } /** * Adds a row to the database class. * It is used in conjunction with the other forms, since the value for each table is autoincremented. * * @param viewInfo Boolean value for if you should insert the data into the database (false), or if * you should update the athlete in the database (true) * @param DBindex Index of the athlete in the database. The Athlete's ID. Used when updating the athlete * in teh database (when the viewInfo param holds value of true) */ public void addRow(boolean viewInfo, String DBindex) { if (viewInfo == false) { String sql; sql = "INSERT INTO YBALANCE VALUES (" + "null," + rightLimbLength + "," + antRightMean + "," + antLeftMean + "," + pmRightMean + "," + pmLeftMean + "," + plRightMean + "," + plLeftMean + "," + antR1 + "," + antR2 + "," + antR3 + "," + antL1 + "," + antL2 + "," + antL3 + "," + pmR1 + "," + pmR2 + "," + pmR3 + "," + pmL1 + "," + pmL2 + "," + pmL3 + "," + plR1 + "," + plR2 + "," + plR3 + "," + plL1 + "," + plL2 + "," + plL3 + "," + compositeLeft + "," + compositeRight + ");"; Database.executeUpdate(sql); } if (viewInfo == true) { String sql; sql = "UPDATE YBALANCE SET" + " rightLimbLength = " + rightLimbLength + "," + " antRightMean = " + antRightMean + "," + " antLeftMean = " + antLeftMean + "," + " pmRightMean = " + pmRightMean + "," + " pmLeftMean = " + pmLeftMean + "," + " plRightMean = " + plRightMean + "," + " plLeftMean = " + plLeftMean + "," + " antR1 = " + antR1 + "," + " antR2 = " + antR2 + "," + " antR3 = " + antR3 + "," + " antL1 = " + antL1 + "," + " antL2 = " + antL2 + "," + " antL3 = " + antL3 + "," + " pmR1 = " + pmR1 + "," + " pmR2 = " + pmR2 + "," + " pmR3 = " + pmR3 + "," + " plR1 = " + plR1 + "," + " plR2 = " + plR2 + "," + " plR3 = " + plR3 + "," + " plL1 = " + plL1 + "," + " plL2 = " + plL2 + "," + " plL3 = " + plL3 + "," + " compositeLeft = " + compositeLeft + "," + " compositeRight = " + compositeRight + " WHERE ID = " + DBindex + ";"; Database.executeUpdate(sql); } } }
true
a9b886ab33017d599bfff95dae0936a0e519f1f7
Java
tbackus127/SyzygyA100
/sim/src/com/rath/syzbgui/ComponentPanel.java
UTF-8
1,490
2.4375
2
[]
no_license
package com.rath.syzbgui; import java.awt.BorderLayout; import java.awt.Dimension; import javax.swing.JPanel; import com.rath.syzbbck.SyzInternals; public class ComponentPanel extends JPanel { private static final long serialVersionUID = 1L; private static final int MARGIN_BOTTOM = 14; private final SyzInternals internals; private final Dimension size; private final RegisterPanel regPanel; private final ControlPanel ctrlPanel; public ComponentPanel(final Dimension size, final SyzInternals si) { super(); this.size = size; setSize(getPreferredSize()); this.internals = si; final int subPanelWidth = (int) (this.size.getWidth() - SimPanel.MARGIN_PANEL); final int sepLocation = (int) (this.size.getHeight() * 0.8D); final Dimension regPanelSize = new Dimension(subPanelWidth, sepLocation); final Dimension ctrlPanelSize = new Dimension(subPanelWidth, (int) (this.size.getHeight() - sepLocation - MARGIN_BOTTOM)); this.regPanel = new RegisterPanel(regPanelSize, this.internals); add(this.regPanel, BorderLayout.NORTH); this.ctrlPanel = new ControlPanel(ctrlPanelSize, this.internals); add(this.ctrlPanel, BorderLayout.SOUTH); } @Override public Dimension getPreferredSize() { return this.size; } @Override public Dimension getMinimumSize() { return getPreferredSize(); } @Override public Dimension getMaximumSize() { return getPreferredSize(); } }
true
4c6136290992e0fd2888a69a51947901539e286d
Java
mathiasyeremiaaryadi/Sewa-Mobil-Android
/Arphat_App/app/src/main/java/com/path_studio/arphatapp/Adapter/slider_adapter_choose_car.java
UTF-8
3,600
2.28125
2
[]
no_license
package com.path_studio.arphatapp.Adapter; import android.content.Context; import android.content.SharedPreferences; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CompoundButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import androidx.core.content.ContextCompat; import androidx.viewpager.widget.PagerAdapter; import com.path_studio.arphatapp.R; public class slider_adapter_choose_car extends PagerAdapter{ Context context; LayoutInflater layoutInflater; public int [] mobil = { R.drawable.mobil_alya, R.drawable.mobil_yaris, R.drawable.mobil_avanza, R.drawable.mobil_calya, R.drawable.mobil_inova, R.drawable.mobil_xenia, R.drawable.mobil_mobilio, R.drawable.mobil_elf, R.drawable.mobil_hiace }; public String[] merek_mobil = { "Daihatsu Alya", "Toyota Yaris", "Toyota Avanza", "Toyota Calya", "Toyota Kijang Inova", "Daihatsu Xenia", "Honda Mobilio", "Isuzu Elf", "Toyota Hiace" }; public int[] jml_kapasitas = {7,5,7,7,7,7,6,12,16}; private String[] tipe_mobil = {"Small","Medium","Large"}; public slider_adapter_choose_car(Context context){ this.context = context; } @Override public int getCount() { return mobil.length; } @Override public boolean isViewFromObject(View view, Object o) { return view == (LinearLayout) o; } @Override public Object instantiateItem(ViewGroup container, int position){ layoutInflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE); View view = layoutInflater.inflate(R.layout.template_slider_choose_car, container, false); //set gambar dan tulisan sesuai dengan database ImageView slideImageView = (ImageView) view.findViewById(R.id.gambar_mobil); slideImageView.setImageResource(mobil[position]); TextView merek = (TextView) view.findViewById(R.id.merek_mobil); merek.setText(merek_mobil[position]); TextView kapasitas = (TextView) view.findViewById(R.id.kapasitas_penumpang); kapasitas.setText(jml_kapasitas[position] + " person"); RelativeLayout capasity = (RelativeLayout) view.findViewById(R.id.car_capasity); TextView teks_kapasitas = (TextView) view.findViewById(R.id.text_capasity); if((jml_kapasitas[position])>0 && (jml_kapasitas[position])<=5){ //small capasity.setBackground(ContextCompat.getDrawable(context,R.drawable.car_type_green)); teks_kapasitas.setText(tipe_mobil[0]); }else if((jml_kapasitas[position])>5 && (jml_kapasitas[position])<=10){ //medium capasity.setBackground(ContextCompat.getDrawable(context,R.drawable.car_type_orange)); teks_kapasitas.setText(tipe_mobil[1]); }else if((jml_kapasitas[position])>10 && (jml_kapasitas[position])<=20){ //large capasity.setBackground(ContextCompat.getDrawable(context,R.drawable.car_type_red)); teks_kapasitas.setText(tipe_mobil[2]); } container.addView(view); return view; } @Override public void destroyItem(ViewGroup container, int position, Object object){ container.removeView((LinearLayout)object); } }
true
e16aceeba0cea7b754e2843189646277cd6375c9
Java
DokterPhill/java3-nieuw
/restaurantV1/src/restaurant/Server.java
UTF-8
996
2.96875
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package restaurant; import java.util.Map; import static restaurant.Utils.printSeparator; /** * * @author Jazz */ public class Server implements Runnable { private Restaurant rest; public Server(Restaurant rest) { this.rest = rest; } public void serveReadyMeals() { printSeparator("Pleased to serve your meals"); while (rest.hasMeals()) { Meal meal = rest.getNextMeal(); Map<Integer, Recipe> recipes = rest.getRecipes(); rest.increaseTurnover(recipes.get(meal.getNumber()).getPrice()); System.out.println(rest.getCustomer().serveTo(meal)); } printSeparator("Bon appetit"); } @Override public void run() { this.serveReadyMeals(); } }
true
79189f1d3f5266fcbd249fb96e2d84f435afe6a9
Java
TheComplexMC/ComplexLife
/src/main/java/net/thecomplex/complexlife/block/BlockElectricLight.java
UTF-8
1,853
2.3125
2
[]
no_license
package net.thecomplex.complexlife.block; import net.minecraft.block.Block; import net.minecraft.block.BlockState; import net.minecraft.block.SoundType; import net.minecraft.block.material.Material; import net.minecraft.state.BooleanProperty; import net.minecraft.state.IntegerProperty; import net.minecraft.state.StateContainer; import net.minecraft.state.properties.BlockStateProperties; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.Direction; import net.minecraft.util.math.BlockPos; import net.minecraft.world.IBlockReader; import net.minecraftforge.common.ToolType; import net.thecomplex.complexlife.entity.tileentity.TileEntityElectricLight; import net.thecomplex.complexlife.misc.energy.EnergyBlockSocket; import javax.annotation.Nullable; public class BlockElectricLight extends EnergyComponentBlock { public static final IntegerProperty POWER = BlockStateProperties.POWER; public static final BooleanProperty POWERED = BlockStateProperties.POWERED; public BlockElectricLight() { super(Properties.of(Material.GLASS).strength(0.3f).sound(SoundType.GLASS).harvestTool(ToolType.PICKAXE), new EnergyBlockSocket(0, Direction.UP, 8, 8)); this.registerDefaultState(this.getStateDefinition().any().setValue(POWER, 0).setValue(POWERED, false)); } @Nullable @Override public TileEntity createTileEntity(BlockState state, IBlockReader world) { return new TileEntityElectricLight(); } @Override public int getLightValue(BlockState state, IBlockReader world, BlockPos pos) { if(state.getValue(POWERED)) return state.getValue(POWER); else return 0; } @Override protected void createBlockStateDefinition(StateContainer.Builder<Block, BlockState> stateBuilder) { stateBuilder.add(POWER, POWERED); } }
true
98749cc44168d13b4494ba4de3280318e8bbccc1
Java
dannybanko/SudokuSolver
/src/Main.java
UTF-8
385
2.1875
2
[]
no_license
import java.io.FileNotFoundException; public class Main { public static void main(String[] args) throws FileNotFoundException { Board sdkSolver = new Board("src/board.sdk"); System.out.println(sdkSolver); Board ssSolver = new Board("src/board.ss"); System.out.println(ssSolver); System.out.println(sdkSolver.solve(sdkSolver)); } }
true
1c9afbb7bd1f779f0c0cd479a2a35212633e1bea
Java
github/codeql
/java/ql/src/Security/CWE/CWE-614/InsecureCookie.java
UTF-8
359
2.46875
2
[ "MIT" ]
permissive
public static void test(HttpServletRequest request, HttpServletResponse response) { { Cookie cookie = new Cookie("secret", "fakesecret"); // BAD: 'secure' flag not set response.addCookie(cookie); } { Cookie cookie = new Cookie("secret", "fakesecret"); // GOOD: set 'secure' flag cookie.setSecure(true); response.addCookie(cookie); } }
true
106f3b950e614e89cc9f8224236eeef66e42007c
Java
unibo-oop-projects/Student-Project-OOP15-Ghinelli-Magnani-ClassScheduleManager
/src/controller/DataManegerImpl.java
UTF-8
4,344
2.546875
3
[]
no_license
package controller; import model.SchedulesModel; import model.interfaces.ISchedulesModel; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.Row; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; import javax.swing.JTable; public class DataManegerImpl implements IDataManager { @Override public void readConfig(final ISchedulesModel model) throws IOException { String path = System.getProperty("user.home") + System.getProperty("file.separator") + "Class Schedules Manager"; System.out.print(path); File theDir = new File(path); if (!theDir.exists()) { try { theDir.mkdir(); } catch (SecurityException se) { } } final Path configPath = FileSystems.getDefault().getPath(path, "config.yml"); File configFile = new File(configPath.toString()); System.out.print(configPath.toString()); if (!configFile.exists()) { try { InputStream in = ClassLoader.getSystemResourceAsStream("config.yml"); BufferedReader file = new BufferedReader(new InputStreamReader(in)); final List<String> content = new ArrayList<>(); String line; while((line=file.readLine())!=null) { content.add(line); } file.close(); OutputStream out = new FileOutputStream(configPath.toString()); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out)); for(final String s : content) { writer.write(s + "\r\n"); } writer.close(); } catch (SecurityException se) { } } try { final List<String> contentFile = Files.readAllLines(configPath); for (final String s : contentFile) { final StringTokenizer st = new StringTokenizer(s, ":"); if (st.countTokens() == 2) { final String temp = st.nextToken(); if ("aula".equals(temp)) { model.addClassroom(st.nextToken()); } /*if ("anno".equals(temp)) { model.addYears(st.nextToken()); } if ("prof".equals(temp)) { model.addProfessor(st.nextToken()); }*/ } } } catch (IOException e) { throw new IOException("Illegal configuration file format"); } } @Override public void saveFile(final String fileName, final ISchedulesModel model) throws IOException { final ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(fileName)); oos.writeObject(model); oos.close(); } @Override public SchedulesModel openFile(final String fileName) throws IOException, ClassNotFoundException { try { final ObjectInputStream ois = new ObjectInputStream(new FileInputStream(fileName)); final SchedulesModel model = (SchedulesModel) ois.readObject(); ois.close(); return model; } catch (IOException e) { throw new IOException("Illegal file format"); } } @Override public void exportInExcel(final HSSFWorkbook workbook) { try (final FileOutputStream out = new FileOutputStream(new File(System.getProperty("user.home") + File.separator + "Lessons.xls"))) { workbook.write(out); workbook.close(); Controller.getController().errorMessage("Successful export!"); } catch (FileNotFoundException e) { Controller.getController().errorMessage("File not found!"); } catch (IOException e) { Controller.getController().errorMessage("IO errors!"); } } }
true
9c1bdd195c95f7a50fd7f2e95818200931517fc6
Java
Nas2meetu/tp-nach-richard
/P5/src/tp/pr5/console/ConsoleController.java
UTF-8
1,497
3.25
3
[]
no_license
package tp.pr5.console; import static tp.pr5.Constants.PROMPT; import java.util.Scanner; import tp.pr5.Controller; import tp.pr5.Interpreter; import tp.pr5.RobotEngine; import tp.pr5.instructions.Instruction; import tp.pr5.instructions.exceptions.WrongInstructionFormatException; /** * * @author Ignacio Cerda Sanchez * @author Ricardo Eugui Fernandez * @version 5 * * The controller employed when the application is configured as a * console application. It contains the simulation loop that executes * the instructions written by the user on the console. */ public class ConsoleController extends Controller { public ConsoleController(RobotEngine robot) { super(robot); } /** * Constructor of the controller. It receives the model main class. * * @param game * Game that is being played. */ public void startController() { super.startController(); startEngine(); } public void startEngine() { Scanner reader = new Scanner(System.in); Instruction instruction = null; while (!robot.isOver()) { robot.saySomething(PROMPT); String input = reader.nextLine(); try { instruction = Interpreter.generateInstruction(input); try { robot.communicateRobot(instruction); } catch (Exception e) { robot.requestError(e.getMessage()); } } catch (WrongInstructionFormatException e) { robot.requestError(e.getMessage()); } } reader.close(); } }
true
55b6fde698997fd2fdc5f9d2bcd6069c7b915e8d
Java
nacereddinebenbouta/first-java-project
/TP MSR/Methodes.java
UTF-8
5,259
3.34375
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.mycompany.chainemarkov; import java.util.Arrays; import java.util.Random; import java.util.Scanner; /** * * @author benbouta nacereddine */ public class Methodes { //this methode reads the matrice public double[][] readMatrice(int rows, int columns) { Scanner clavier = new Scanner(System.in); System.out.println(); System.out.println("You have entred: "); System.out.println("Matrice Rows= " + rows); System.out.println("Matrice Columns= " + rows); System.out.println(); //declaration of a matrice [lines][colones] double Matrice[][] = new double[rows][columns]; for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { System.out.println("Enter element for Matrice = [" + (i + 1) + "][" + (j + 1) + "] :"); Matrice[i][j] = clavier.nextDouble(); } } return Matrice; } //this methode will show (ouput) the matrice public void showMatrice(double matrice[][]) { for (int i = 0; i < matrice.length; i++) { for (int j = 0; j < matrice[i].length; j++) { System.out.format("%.2f ", matrice[i][j]); } System.out.println(); } } //this methode checks if the matrice is stochastic or not public boolean checkStochastic(double matrice[][]) { //i<nbr of rows for (int i = 0; i < matrice.length; i++) { double sumVector = 0; //j< nbr of columns for (int j = 0; j < matrice[i].length; j++) { sumVector = sumVector + matrice[i][j]; } if (sumVector != 1) { return false; } } return true; } //Genrate a random value between 0-1 public float randValue() { Random random = new Random(); double randNumbr = random.nextFloat(); System.out.println(); System.out.println("randNumbr= " + randNumbr); randNumbr = randNumbr * 10; System.out.println("randNumbr*10 = " + randNumbr); int intCasted = (int) randNumbr; System.out.println("intCasted= " + intCasted); float R = (float) intCasted / 10; System.out.println("R = intCasted/10= " + R); System.out.println(); return R; } //calculates sum of matrice[i]+matrice[i+1] of row [i] and compare it with R //if R<Sum return the index of the row public int retRowIndice(double A[], float r, double Matrice[][]) { double SUM = 0; for (int i = 0; i < Matrice[0].length; i++) { System.out.println(); System.out.format("SUM = %.3f", SUM); System.out.format(" + %.3f", A[i]); SUM = SUM + A[i]; System.out.format(" = %.3f", SUM); System.out.println(); System.out.format("SUM = " + "SUM" + " + " + "Vector" + "[" + i + "]" + " = " + "%.3f", +SUM); System.out.println(); if (SUM < r && i == Matrice.length - 1) { //code will go here } else if (SUM > r) { System.out.println(); System.out.println("SUM > R <===> " + SUM + ">" + r); if ((SUM == 1.0) | (SUM == 0.99)) { System.out.println("Echeck du calcule chaine de markove descret"); } return i; } } return Matrice.length-1; } //return the row number that willmultiplied with the matrice public int eteration(double A[], double Matrice[][]) { Methodes meth = new Methodes(); float randNumber = meth.randValue(); System.out.println("R= " + randNumber); System.out.println(); System.out.println("Vector[R]= " + Arrays.toString(A)); System.out.println(); int rowNumber = meth.retRowIndice(A, randNumber, Matrice); System.out.println(); System.out.println("Index of Vector[row] is= " + rowNumber); System.out.println("Vector[" + rowNumber + "]= " + Arrays.toString(Matrice[rowNumber])); System.out.println(); return rowNumber; } //return the Vector[i] public void getVictor(double matrice[], double vec[]) { for (int i = 0; i < matrice.length; i++) { vec[i] = matrice[i]; } } //multiplication Vector[i]*Matrice[i][j] public void multiple(double vec[], double A[][], int rowIndice, double c[]) { for (int test = 0; test < rowIndice; test++) { double sum = 0; int z = 0; for (int j = 0; j < A.length; j++) { for (int i = 0; i < A.length; i++) { sum = vec[z] * A[i][j] + sum; z++; } z = 0; c[j] = sum; sum = 0; } } } }
true
9079a51959d80cf4426ed48b478fe357608c3b17
Java
avitalze/Football-system-project
/Client_side/src/Presentation/ReportOfMatchController.java
UTF-8
5,485
2.15625
2
[]
no_license
package Presentation; //import Service.RefereeApplication; import javafx.application.Platform; import javafx.beans.property.ReadOnlyObjectWrapper; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.Node; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.*; import javafx.scene.input.MouseEvent; import javafx.stage.Stage; import java.io.IOException; import java.text.ParseException; import java.util.Arrays; import java.util.LinkedList; import java.util.List; public class ReportOfMatchController { @FXML public ComboBox<String> idMatches; @FXML public Label lblScore; @FXML public TableView reportTable; @FXML //private RefereeApplication refereeApplication = new RefereeApplication(); private String userName; private List<String> matches; public void initPage(String userName, List<String> matches) { this.userName = userName; this.matches = matches; lblScore.setVisible(false); reportTable.setVisible(false); } @FXML public void BackToReferee(ActionEvent actionEvent) throws IOException { Stage stageTheEventSourceNodeBelongs = (Stage) ((Node)actionEvent.getSource()).getScene().getWindow(); FXMLLoader loader = new FXMLLoader(getClass().getResource("RefereePage.fxml")); Parent root = loader.load(); Scene scene = new Scene(root); //scene.getStylesheets().add(getClass().getResource("Style.css").toExternalForm()); RefereePageController controller = loader.getController(); controller.initUser(userName,"Referee"); stageTheEventSourceNodeBelongs.setScene(scene); } @FXML public void chooseMatchBtn(MouseEvent event) { ObservableList<String> elements = FXCollections.observableArrayList(this.matches); idMatches.setItems(elements); idMatches.getSelectionModel().selectFirst(); } @FXML public void createReportInline() { reportTable.setVisible(true); String match = idMatches.getSelectionModel().getSelectedItem(); if(idMatches.getSelectionModel().getSelectedIndex()==-1){ Alert chooseFile = new Alert(Alert.AlertType.ERROR); chooseFile.setHeaderText("Error"); chooseFile.setContentText("No match selected. please try again"); chooseFile.show(); } else{ //String reportStr = this.refereeApplication.createReportOfMatch(match,userName); String reportStr = ClientController.connectToServer("RefereeApplication", "createReportOfMatch", match, userName); //check for error if(reportStr.contains("error")){ Alert chooseFile = new Alert(Alert.AlertType.ERROR); chooseFile.setHeaderText("Error"); chooseFile.setContentText(reportStr); chooseFile.show(); } else{//else no problem String matchScore = ClientController.connectToServer("RefereeApplication", "getMatchScore", match, userName); if(matchScore.contains("Error")){ Alert chooseFile = new Alert(Alert.AlertType.ERROR); chooseFile.setHeaderText("error"); chooseFile.setContentText(matchScore); chooseFile.show(); } else { lblScore.setVisible(true); lblScore.setText(matchScore); List<String> report = Arrays.asList(reportStr.split(";")); LinkedList<String> list = new LinkedList<String>(); list.addAll(report); reportTable.getItems().addAll(list); TableColumn<String, String> column1 = new TableColumn<>("Events in match"); column1.setCellValueFactory(param -> new ReadOnlyObjectWrapper<>(param.getValue())); reportTable.getColumns().setAll(column1); } } } } public void closeHandling(MouseEvent mouseEvent) throws IOException { FXMLLoader loader = new FXMLLoader(getClass().getResource("HomePage.fxml")); Parent calcRoot = loader.load(); HomePageController controller = loader.getController(); controller.initHomePage(userName,"Referee"); controller.closeHandling(mouseEvent); } // @FXML // public void startCreatReport() throws Exception { // String match = idMatches.getSelectionModel().getSelectedItem(); // LinkedList<String> report = this.RefereeApplication.createReportOfMatch(match,userName); // // TableView<String> tableView = new TableView<>(); // Stage stage = new Stage(); // Scene scene = new Scene(new Group()); // stage.setTitle("Match Report"); // stage.setWidth(300); // stage.setHeight(500); // // tableView.getItems().addAll(report); // // TableColumn<String,String> column1= new TableColumn<>("EventsAdapter"); // column1.setCellValueFactory(param -> new ReadOnlyObjectWrapper<>(param.getValue())); // // tableView.getColumns().setAll(column1); // // ((Group)scene.getRoot()).getChildren().addAll(tableView); // // stage.setScene(scene); // stage.show(); // } }
true
40e4521cfcd305b03b244934e5425f5364d01fb0
Java
trandreluis/dac
/jpa4/src/main/java/br/edu/ifpb/mt/dac/entidades/f/bidirecional/MainBiSave.java
UTF-8
1,933
2.703125
3
[]
no_license
package br.edu.ifpb.mt.dac.entidades.f.bidirecional; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import br.edu.ifpb.mt.dac.dao.f.bidirecional.ColaboradorDAO; import br.edu.ifpb.mt.dac.dao.f.bidirecional.ProjetoDAO; public class MainBiSave { public static void main(String[] args) { ProjetoDAO daoProjeto = new ProjetoDAO(); ColaboradorDAO daoColcaborador = new ColaboradorDAO(); try { Projeto projeto = new Projeto(); projeto.setDuracao(10); projeto.setNome("Negócio Nordeste"); projeto.setIntegrantes(new ArrayList<Colaborador>()); Colaborador colaborador = new Colaborador(); colaborador.setNome("Andre"); colaborador.setSobreNome("Luis"); colaborador.setSalario(new BigDecimal(10000)); colaborador.setDataNascimento(new Date()); colaborador.setProjetos(new ArrayList<Projeto>()); // Colaborador colaborador2 = new Colaborador(); // colaborador2.setNome("Fulano"); // colaborador2.setSobreNome("Xavier"); // colaborador2.setSalario(new BigDecimal(1000)); // colaborador2.setDataNascimento(new Date()); // // Colaborador colaborador3 = new Colaborador(); // colaborador3.setNome("Sicrano"); // colaborador3.setSobreNome("Sousa"); // colaborador3.setSalario(new BigDecimal(100)); // colaborador3.setDataNascimento(new Date()); List<Colaborador> colcaboradores = Arrays.asList(colaborador); List<Projeto> projetos = Arrays.asList(projeto); System.out.println(projeto); System.out.println(colaborador); daoProjeto.save(projeto); daoColcaborador.save(colaborador); System.out.println(projeto); System.out.println(colaborador); projeto.setIntegrantes(colcaboradores); colaborador.setProjetos(projetos); daoProjeto.update(projeto); System.out.println(projeto); System.out.println(colaborador); } finally { daoProjeto.close(); } } }
true
1bc5b81c232ac21a3970723f2f7fb8cb82d50fa8
Java
dividio/PorraOnline
/PorraOnline/src/main/java/com/aap/rest/server/MensajesRS.java
UTF-8
4,368
2.203125
2
[]
no_license
package com.aap.rest.server; import java.util.Date; import java.util.List; import javax.annotation.security.PermitAll; import javax.annotation.security.RolesAllowed; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.Response.Status; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.criterion.Order; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.aap.dto.Mensajes; import com.aap.dto.Partidas; import com.aap.dto.Usuarios; import com.aap.rest.exception.RestCustomException; @Path("/mensajes") public class MensajesRS extends AbstractFacade<Mensajes> { private static final Logger log = LoggerFactory.getLogger(MensajesRS.class); public MensajesRS() { super(Mensajes.class); } @Context private HttpServletRequest request; @PermitAll @POST @Path("partida/{id}") @Consumes({ "application/json" }) @Produces({ "application/json" }) public Mensajes create(@PathParam("id") Long id, Mensajes entity) { Usuarios usuario = (Usuarios) request.getSession().getAttribute("usuario"); if(validaGuardarMensaje(id, usuario, entity)) { Partidas partida = (Partidas) getSession().get(Partidas.class, id); entity.setMe_usu_id(usuario); entity.setMe_pa_id(partida); entity.setMe_fecha(new Date()); return super.create(entity); } return null; } private boolean validaGuardarMensaje(Long idPartida, Usuarios usuario, Mensajes mensaje) { if(!suscritoPartida(idPartida, usuario)) { throw new RestCustomException("Hace falta estar suscrito a la partida para escribir mensajes.", "Prohibido", Status.FORBIDDEN, RestCustomException.ERROR); } if(mensaje == null || mensaje.getMe_texto() == null || mensaje.getMe_texto().isEmpty()) { throw new RestCustomException("Hace falta indicar el texto del mensaje.", "Incorrecto", Status.BAD_REQUEST, RestCustomException.ERROR); } return true; } private boolean suscritoPartida(Long idPartida, Usuarios usuario) { if(idPartida != null && usuario != null && usuario.getUsu_id() != null) { String hql = "select count(*) " + "from Partidas PA " + "join PA.usuarios USU " + "where USU.usu_id = :ID_USUARIO " + "and PA.pa_id = :ID_PARTIDA "; Query hqlQ = getSession().createQuery(hql); hqlQ.setLong("ID_USUARIO", usuario.getUsu_id()); hqlQ.setLong("ID_PARTIDA", idPartida); Long cont = (Long) hqlQ.uniqueResult(); return (cont.compareTo(Long.valueOf(0)) != 0); } return false; } @PUT @Override @Consumes({ "application/json" }) public void edit(Mensajes entity) { super.edit(entity); } @RolesAllowed("ADMIN") @DELETE @Path("{id}") public void remove(@PathParam("id") Long id) { super.remove(find(id)); } @PermitAll @GET @Path("{id}") @Produces({ "application/json" }) public Mensajes find(@PathParam("id") Long id) { String hql = "select ME " + "from Mensajes ME " + "where ME.me_id = :MENSAJE"; Query hqlQ = getSession().createQuery(hql); hqlQ.setLong("MENSAJE", id); Mensajes elemento = (Mensajes) hqlQ.uniqueResult(); if(elemento == null) { throw new RestCustomException("Elemento no encontrado", "Elemento no encontrado", Status.NOT_FOUND, RestCustomException.ERROR); } return elemento; } @PermitAll @GET @Produces({ "application/json" }) public List<Mensajes> findAll() { return getSession().createCriteria(Mensajes.class) .addOrder(Order.desc("me_fecha")) .list(); } @PermitAll @GET @Path("partida/{id}") @Produces({ "application/json" }) public List<Mensajes> mensajesPartida(@PathParam("id") Long id) { String hql = "select ME " + "from Mensajes ME " + "join ME.me_pa_id PA " + "where PA.pa_id = :ID_PARTIDA " + "order by ME.me_fecha desc"; Query hqlQ = getSession().createQuery(hql); hqlQ.setLong("ID_PARTIDA", id); return hqlQ.list(); } @Override protected Session getSession() { return (Session) request.getAttribute("session"); } }
true
346b4925c09ac84606720ddbd6346ecc33da783e
Java
rommeldongre/FrrndLease-webapp
/src/pojos/GetRecentWishesResObj.java
UTF-8
578
2.265625
2
[]
no_license
package pojos; import java.util.ArrayList; import java.util.List; public class GetRecentWishesResObj extends ResObj{ String message; int code; List<String> wishes = new ArrayList<>(); public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public int getCode() { return code; } public void setCode(int code) { this.code = code; } public List<String> getWishes() { return wishes; } public void setWishes(List<String> wishes) { this.wishes = wishes; } }
true
f43b72f2fb08a5e5556ad424621312cb456d3cfb
Java
bergusman/pdef
/java/src/main/java/io/pdef/descriptors/GeneratedMethodDescriptor.java
UTF-8
5,072
2.21875
2
[]
no_license
package io.pdef.descriptors; import com.google.common.base.Objects; import static com.google.common.base.Preconditions.*; import com.google.common.base.Supplier; import com.google.common.base.Throwables; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Maps; import io.pdef.Invocation; import io.pdef.rpc.RpcCall; import io.pdef.rpc.RpcError; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Map; /** Abstract class for a generated method descriptor. */ public class GeneratedMethodDescriptor implements MethodDescriptor { private final InterfaceDescriptor<?> iface; private final String name; private final Map<String, Descriptor<?>> args; private final Descriptor<?> result; private final Descriptor<?> exc; private final Supplier<InterfaceDescriptor<?>> next; private final Method method; GeneratedMethodDescriptor(final Builder builder) { iface = checkNotNull(builder.iface); name = checkNotNull(builder.name); args = ImmutableMap.copyOf(builder.args); result = builder.result; exc = builder.exc; next = builder.next; method = GeneratedInterfaceDescriptor.getMethodByName(iface.getJavaClass(), name); checkArgument((result != null ? 1 : 0) + (next != null ? 1 : 0) == 1, "either result or next must be defined"); } @Override public String toString() { return Objects.toStringHelper(this) .addValue(iface.getJavaClass().getSimpleName() + "." + name) .toString(); } @Override public String getName() { return name; } @Override public Map<String, Descriptor<?>> getArgs() { return args; } @Override public boolean isRemote() { return result != null; } @Override public Descriptor<?> getResult() { return result; } @Override public Descriptor<?> getExc() { return exc; } @Override public InterfaceDescriptor<?> getNext() { return next.get(); } @Override public Invocation capture(final Invocation parent, final Object... args) { checkNotNull(parent); checkNotNull(args); checkArgument(this.args.size() == args.length, "wrong number of arguments"); return parent.next(this, args); } @Override public Object invoke(final Object object, final Object... args) { checkNotNull(object, "tried to invoke a method on a null object, %s", this); checkArgument(args.length == this.args.size(), "wrong number of arguments"); Object[] array = new Object[this.args.size()]; int i = 0; for (Descriptor<?> descriptor : this.args.values()) { Object arg = args[i]; array[i++] = arg == null ? descriptor.getDefault() : arg; } try { return method.invoke(object, array); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw Throwables.propagate(e.getCause()); } } @SuppressWarnings("unchecked") @Override public RpcCall serialize(final Object... args) { checkArgument(args.length == this.args.size(), "wrong number of args"); ImmutableMap.Builder<String, Object> builder = ImmutableMap.builder(); int i = 0; for (Map.Entry<String, Descriptor<?>> entry : this.args.entrySet()) { String key = entry.getKey(); Descriptor descriptor = entry.getValue(); Object arg = descriptor.serialize(args[i++]); if (arg == null) continue; builder.put(key, arg); } return RpcCall.builder() .setMethod(name) .setArgs(builder.build()) .build(); } @Override public Invocation parse(final Invocation parent, final Map<String, Object> args) throws RpcError { checkNotNull(parent); checkNotNull(args); Object[] array = new Object[this.args.size()]; int i = 0; for (Map.Entry<String, Descriptor<?>> entry : this.args.entrySet()) { String key = entry.getKey(); Descriptor<?> descriptor = entry.getValue(); array[i++] = descriptor.parse(args.get(key)); } return parent.next(this, array); } public static Builder builder(final InterfaceDescriptor<?> iface, final String name) { return new Builder(iface, name); } public static class Builder { private final InterfaceDescriptor<?> iface; private final String name; private final Map<String, Descriptor<?>> args; private Descriptor<?> result; private Descriptor<?> exc; private Supplier<InterfaceDescriptor<?>> next; private Builder(final InterfaceDescriptor<?> iface, final String name) { this.iface = checkNotNull(iface); this.name = checkNotNull(name); args = Maps.newLinkedHashMap(); } public Builder arg(final String name, final Descriptor<?> descriptor) { args.put(checkNotNull(name), checkNotNull(descriptor)); return this; } public Builder result(final Descriptor<?> result) { this.result = checkNotNull(result); return this; } public Builder exc(final Descriptor<?> exc) { this.exc = checkNotNull(exc); return this; } public Builder next(final Supplier<InterfaceDescriptor<?>> next) { this.next = checkNotNull(next); return this; } public MethodDescriptor build() { return new GeneratedMethodDescriptor(this); } } }
true
b27127d8b2277508f363e4483ede32454c56dbf0
Java
google-code/agiledoc
/src/sourceagile/development/client/serverCalls/SaveComment.java
UTF-8
615
2.203125
2
[]
no_license
package sourceagile.development.client.serverCalls; import sourceagile.shared.entities.Comments; import com.google.gwt.core.client.GWT; import com.google.gwt.user.client.rpc.AsyncCallback; public class SaveComment { final CommentsServerCallsAsync commentsServerCalls = GWT .create(CommentsServerCalls.class); public SaveComment(Comments comment) { commentsServerCalls.saveComment(comment, new AsyncCallback<Void>() { public void onSuccess(Void result) { } public void onFailure(Throwable caught) { // Show the RPC error message to the user } }); } }
true
5afed8aaf775a3d74fb6a3cf023f50d8c1f0846f
Java
jinhee-han/employ24
/src/main/java/com/vtw/employ/emea/repository/EmeaBplcRepository.java
UTF-8
295
1.828125
2
[]
no_license
package com.vtw.employ.emea.repository; import com.vtw.employ.emea.EmeaBplc; import org.springframework.data.jpa.repository.JpaRepository; import java.util.Optional; public interface EmeaBplcRepository extends JpaRepository<EmeaBplc, Long> { Optional<EmeaBplc> findByBcno(String bcno); }
true
a1e2edbb43b9e05bd55d7e9dd0d1e83fef2fb958
Java
Clarar/Ahorcado
/src/hangman/ControllerHangman.java
MacCentralEurope
14,306
2.515625
3
[]
no_license
package hangman; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.io.File; import java.util.Timer; import java.util.TimerTask; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JOptionPane; import drawAhorcado.*; public class ControllerHangman implements ActionListener, KeyListener { private ModelHangman model; private ViewHangman view; private boolean hangmanWinner; private ModelHangmanDictionary modelDictionary; private boolean dictionary; private ImageIcon imageWinner; private ImageIcon imageLoser; public ControllerHangman( ViewHangman view ){ this.model = new ModelHangman(); this.view = view; this.hangmanWinner = false; this.dictionary = false; this.imageWinner = new ImageIcon("image/enhorabuena.jpg"); this.imageLoser = new ImageIcon("image/loser.jpg"); } public void youWin(String word){ for (int i = 0; i < model.getWord().length(); i++) { if (model.getWord().length() != word.length() || word.toLowerCase().charAt(i) != model.getWord().toLowerCase().charAt(i)) { view.setTextEnd(imageLoser); view.drawHangman(6); }else{ if (i == model.getWord().length()-1) { hangmanWinner = true; } } model.setChar(i, model.getWord().charAt(i)); } if (hangmanWinner) { view.setTextEnd(imageWinner); } view.panelCenter.getJlbl_maskWord().setText(model.getMaskWord()); } public void processLetter(){ char letter; letter = view.panelCenter.getJtxt_letra().getText().charAt(0); if (isRepeatedLetter(letter)) { view.setTextError("La letra ya esta introducida."); }else{ if (checkLetter(letter)) { if (isWordCompleted()) { hangmanWinner = true; view.setTextEnd(imageWinner); view.panelCenter.getJlbl_maskWord().setText(model.getMaskWord()); //newGame(); }else{ view.panelCenter.getJlbl_maskWord().setText(model.getMaskWord()); view.panelCenter.getJlbl_introduced().setText(model.getIntroduced()); view.panelCenter.getJlbl_attempts().setText(model.getAttempts()+"/6"); } }else{ model.incrementmMistake(); view.panelCenter.getJlbl_attempts().setText(model.getAttempts()+"/6"); view.panelCenter.getJlbl_introduced().setText(model.getIntroduced()); view.setTextError("Has fallado"); drawHangman(); } } } public boolean isRepeatedLetter(char letter){ if (model.getIntroduced().indexOf(letter) == -1) { return false; }else{ return true; } } public boolean isWordCompleted(){ for (int i = 0; i < model.getWord().length(); i++) { if (model.getChar(i) == '_' ) { return false; } } return true; } public boolean checkLetter(char letter){ String word = model.getWord(); boolean isInWord = false; for (int i = 0; i < word.length(); i++) { if ( Character .toLowerCase(letter) == word.toLowerCase().charAt(i) ) { model.setChar(i, word.charAt(i)); isInWord = true; } } if ( isInWord ) { model.SetIntroduced(letter); return true; }else{ model.SetIntroduced(letter); return false; } } public boolean notAttempts(){ if (model.getAttempts() == 0) { return true; } return false; } public boolean setDictionary( String word ) { String dictionary = this.selectDictionary(word); File wd = new File(dictionary); try { this.setWord(wd); return true; } catch (Exception e) { return false; } } public String selectDictionary( String word ){ String dictionary = ""; if (word.toLowerCase().indexOf("spa") != -1) { dictionary = "dictionaryES.txt"; }else if (word.toLowerCase().indexOf("ngl") != -1) { dictionary = "dictionaryEN.txt"; } return dictionary; } public void setWord(File wd) throws Exception { String wordRandom; modelDictionary = new ModelHangmanDictionary(wd); wordRandom = modelDictionary.getWordRandom(); model.setWord(wordRandom); } private boolean getIntroduced(){ if (model.getIntroduced().length() > 0) { return true; }else{ return false; } } private boolean validateDictionary(String dictionary){ if (dictionary != "Elija un idioma...") { if (!setDictionary(dictionary)) { view.setTextError("El dic. "+dictionary+" no est disponible"); return false; }else{ return true; } }else{ view.setTextError("Elija un lenguaje"); return false; } } private boolean isLetter(){ if (view.panelCenter.getJtxt_letra().getText().length() == 1 && !Character.isDigit((view.panelCenter.getJtxt_letra().getText()).charAt(0)) ) { return true; } view.setTextError("Introduce una letra"); return false; } public void drawHangman(){ view.drawHangman(model.getMistake()); } public void solveWord(){ for (int i = 0; i < model.getWord().length(); i++) { model.setChar(i, model.getWord().charAt(i)); } } public void newGame(){ if(view.newGame() == 0 ){ // si el usuario quiere iniciar la partida. }else{ System.exit(0); //si el usuario no quiere iniciar sesion cierra la ventana. } } @Override public void actionPerformed(ActionEvent e) { if (((JButton)e.getSource()).getName() == "start") { String dictionary = (String)view.panelHead.getLanguage().getSelectedItem(); if (validateDictionary(dictionary)) { view.startButtonVisible(false); view.setTextError(" "); view.panelHead.getLanguage().setEnabled(false); view.panelCenter.getJlbl_maskWord().setText(model.getMaskWord()); view.panelCenter.getJlbl_attempts().setText(model.getAttempts()+"/6"); view.panelCenter.getJlbl_introduced().setText(model.getIntroduced()); this.dictionary = true; } } if (((JButton)e.getSource()).getName() == "comprobar" ) { if (getIntroduced()) { view.panelCenter.getJbtn_palabra().setEnabled(true); view.panelCenter.getJtxt_palabra().setEnabled(true); view.panelCenter.getJbtn_pista().setEnabled(true); } view.setTextError(" "); if (notAttempts()) { view.setTextError("Sin intentos"); view.setTextEnd(imageLoser); solveWord(); view.panelCenter.getJlbl_maskWord().setText(model.getMaskWord()); //newGame(); }else{ if (isLetter()) { processLetter(); } } drawHangman(); } if (((JButton)e.getSource()).getName() == "pista") { view.setTextError(" "); if (notAttempts()) { view.setTextError("Sin intentos"); view.setTextEnd(imageLoser); solveWord(); view.panelCenter.getJlbl_maskWord().setText(model.getMaskWord()); //newGame(); }else{ int random; char letter; do { random = (int)(Math.random()*model.getWord().length()); letter = model.getWord().charAt(random); } while (isRepeatedLetter(letter)); if (this.checkLetter(letter)) { if (isWordCompleted()) { hangmanWinner = true; view.setTextEnd(imageWinner); view.panelCenter.getJlbl_maskWord().setText(model.getMaskWord()); //newGame(); } model.incrementmMistake(); } view.panelCenter.getJlbl_maskWord().setText(model.getMaskWord()); view.panelCenter.getJlbl_attempts().setText(model.getAttempts()+"/6"); } drawHangman(); } if (((JButton)e.getSource()).getName() == "resolver") { youWin(view.panelCenter.getJtxt_palabra().getText()); //newGame(); } /*for (int i = 0; i < 26; i++) { if (((JButton)e.getSource()).getName() == (""+(char)(i+(int)a))) { view.panelCenter.getJtxt_letra().setText(((JButton)e.getSource()).getName()); } //JOptionPane.showMessageDialog(null, ((JButton)e.getSource()).getName()+(" "+(char)(i+(int)a))); }*/ if (((JButton)e.getSource()).getName() == "A") { view.panelCenter.getJtxt_letra().setText(((JButton)e.getSource()).getName()); } if (((JButton)e.getSource()).getName() == "B") { view.panelCenter.getJtxt_letra().setText(((JButton)e.getSource()).getName()); } if (((JButton)e.getSource()).getName() == "C") { view.panelCenter.getJtxt_letra().setText(((JButton)e.getSource()).getName()); } if (((JButton)e.getSource()).getName() == "D") { view.panelCenter.getJtxt_letra().setText(((JButton)e.getSource()).getName()); } if (((JButton)e.getSource()).getName() == "E") { view.panelCenter.getJtxt_letra().setText(((JButton)e.getSource()).getName()); } if (((JButton)e.getSource()).getName() == "F") { view.panelCenter.getJtxt_letra().setText(((JButton)e.getSource()).getName()); } if (((JButton)e.getSource()).getName() == "G") { view.panelCenter.getJtxt_letra().setText(((JButton)e.getSource()).getName()); } if (((JButton)e.getSource()).getName() == "H") { view.panelCenter.getJtxt_letra().setText(((JButton)e.getSource()).getName()); } if (((JButton)e.getSource()).getName() == "I") { view.panelCenter.getJtxt_letra().setText(((JButton)e.getSource()).getName()); } if (((JButton)e.getSource()).getName() == "J") { view.panelCenter.getJtxt_letra().setText(((JButton)e.getSource()).getName()); } if (((JButton)e.getSource()).getName() == "K") { view.panelCenter.getJtxt_letra().setText(((JButton)e.getSource()).getName()); } if (((JButton)e.getSource()).getName() == "L") { view.panelCenter.getJtxt_letra().setText(((JButton)e.getSource()).getName()); } if (((JButton)e.getSource()).getName() == "M") { view.panelCenter.getJtxt_letra().setText(((JButton)e.getSource()).getName()); } if (((JButton)e.getSource()).getName() == "N") { view.panelCenter.getJtxt_letra().setText(((JButton)e.getSource()).getName()); } if (((JButton)e.getSource()).getName() == "") { view.panelCenter.getJtxt_letra().setText(((JButton)e.getSource()).getName()); } if (((JButton)e.getSource()).getName() == "O") { view.panelCenter.getJtxt_letra().setText(((JButton)e.getSource()).getName()); } if (((JButton)e.getSource()).getName() == "P") { view.panelCenter.getJtxt_letra().setText(((JButton)e.getSource()).getName()); } if (((JButton)e.getSource()).getName() == "Q") { view.panelCenter.getJtxt_letra().setText(((JButton)e.getSource()).getName()); } if (((JButton)e.getSource()).getName() == "R") { view.panelCenter.getJtxt_letra().setText(((JButton)e.getSource()).getName()); } if (((JButton)e.getSource()).getName() == "S") { view.panelCenter.getJtxt_letra().setText(((JButton)e.getSource()).getName()); } if (((JButton)e.getSource()).getName() == "T") { view.panelCenter.getJtxt_letra().setText(((JButton)e.getSource()).getName()); } if (((JButton)e.getSource()).getName() == "U") { view.panelCenter.getJtxt_letra().setText(((JButton)e.getSource()).getName()); } if (((JButton)e.getSource()).getName() == "V") { view.panelCenter.getJtxt_letra().setText(((JButton)e.getSource()).getName()); } if (((JButton)e.getSource()).getName() == "W") { view.panelCenter.getJtxt_letra().setText(((JButton)e.getSource()).getName()); } if (((JButton)e.getSource()).getName() == "X") { view.panelCenter.getJtxt_letra().setText(((JButton)e.getSource()).getName()); } if (((JButton)e.getSource()).getName() == "Y") { view.panelCenter.getJtxt_letra().setText(((JButton)e.getSource()).getName()); } if (((JButton)e.getSource()).getName() == "Z") { view.panelCenter.getJtxt_letra().setText(((JButton)e.getSource()).getName()); } if (((JButton)e.getSource()).getName() == "Enter") { if (getIntroduced()) { view.panelCenter.getJbtn_palabra().setEnabled(true); view.panelCenter.getJtxt_palabra().setEnabled(true); view.panelCenter.getJbtn_pista().setEnabled(true); } if (notAttempts()) { view.setTextError("Sin intentos"); view.setTextEnd(imageLoser); drawHangman(); solveWord(); view.panelCenter.getJlbl_maskWord().setText(model.getMaskWord()); //newGame(); }else{ if (view.panelCenter.getJtxt_letra().getText().length() > 0) { view.setTextError(" "); processLetter(); } if (view.panelCenter.getJtxt_palabra().getText().length() > 0) { youWin(view.panelCenter.getJtxt_palabra().getText()); view.panelCenter.getJlbl_maskWord().setText(model.getMaskWord()); //newGame(); } } } view.panelCenter.getJlbl_maskWord().setText(model.getMaskWord()); if (dictionary) { view.panelCenter.getJlbl_attempts().setText(model.getAttempts()+"/6"); } view.panelCenter.getJlbl_introduced().setText(model.getIntroduced()); } @Override public void keyPressed(KeyEvent e) { if (getIntroduced()) { view.panelCenter.getJbtn_palabra().setEnabled(true); view.panelCenter.getJtxt_palabra().setEnabled(true); view.panelCenter.getJbtn_pista().setEnabled(true); } view.setTextError(" "); if (e.VK_ENTER == e.getKeyCode()){ if (view.panelCenter.getJtxt_letra().getText().length() > 0) { view.setTextError(" "); processLetter(); if (notAttempts()) { view.setTextError("Sin intentos"); view.setTextEnd(imageLoser); drawHangman(); solveWord(); view.panelCenter.getJlbl_maskWord().setText(model.getMaskWord()); //newGame(); } } if (view.panelCenter.getJtxt_palabra().getText().length() > 0) { youWin(view.panelCenter.getJtxt_palabra().getText()); view.panelCenter.getJlbl_maskWord().setText(model.getMaskWord()); //newGame(); } } view.panelCenter.getJlbl_maskWord().setText(model.getMaskWord()); if (dictionary) { view.panelCenter.getJlbl_attempts().setText(model.getAttempts()+"/6"); } view.panelCenter.getJlbl_introduced().setText(model.getIntroduced()); drawHangman(); } @Override public void keyReleased(KeyEvent e) { // TODO Auto-generated method stub } @Override public void keyTyped(KeyEvent e) { // TODO Auto-generated method stub } }
true
1e32c4f56150c48c4816d327a2c63ba8bd65c1e0
Java
wso2/carbon-transports
/http/org.wso2.carbon.transport.http.netty/src/test/java/org/wso2/carbon/transport/http/netty/websocket/WebSocketPassthroughServerConnectorListener.java
UTF-8
5,841
1.875
2
[ "Apache-2.0" ]
permissive
/* * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.wso2.carbon.transport.http.netty.websocket; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.Assert; import org.wso2.carbon.transport.http.netty.contract.HttpWsConnectorFactory; import org.wso2.carbon.transport.http.netty.contract.websocket.HandshakeFuture; import org.wso2.carbon.transport.http.netty.contract.websocket.HandshakeListener; import org.wso2.carbon.transport.http.netty.contract.websocket.WebSocketBinaryMessage; import org.wso2.carbon.transport.http.netty.contract.websocket.WebSocketClientConnector; import org.wso2.carbon.transport.http.netty.contract.websocket.WebSocketCloseMessage; import org.wso2.carbon.transport.http.netty.contract.websocket.WebSocketConnectorListener; import org.wso2.carbon.transport.http.netty.contract.websocket.WebSocketControlMessage; import org.wso2.carbon.transport.http.netty.contract.websocket.WebSocketInitMessage; import org.wso2.carbon.transport.http.netty.contract.websocket.WebSocketTextMessage; import org.wso2.carbon.transport.http.netty.contract.websocket.WsClientConnectorConfig; import org.wso2.carbon.transport.http.netty.contractimpl.HttpWsConnectorFactoryImpl; import org.wso2.carbon.transport.http.netty.util.TestUtil; import java.io.IOException; import javax.websocket.Session; /** * Server Connector Listener to check WebSocket pass-through scenarios. */ public class WebSocketPassthroughServerConnectorListener implements WebSocketConnectorListener { private static final Logger logger = LoggerFactory.getLogger(WebSocketPassthroughServerConnectorListener.class); private final HttpWsConnectorFactory connectorFactory = new HttpWsConnectorFactoryImpl(); @Override public void onMessage(WebSocketInitMessage initMessage) { String remoteUrl = String.format("ws://%s:%d/%s", "localhost", TestUtil.TEST_REMOTE_WS_SERVER_PORT, "websocket"); WsClientConnectorConfig configuration = new WsClientConnectorConfig(remoteUrl); configuration.setTarget("myService"); WebSocketClientConnector clientConnector = connectorFactory.createWsClientConnector(configuration); WebSocketConnectorListener clientConnectorListener = new WebSocketPassthroughClientConnectorListener(); try { clientConnector.connect(clientConnectorListener).setHandshakeListener(new HandshakeListener() { @Override public void onSuccess(Session clientSession) { HandshakeFuture serverFuture = initMessage.handshake(); serverFuture.setHandshakeListener(new HandshakeListener() { @Override public void onSuccess(Session serverSession) { WebSocketPassThroughTestSessionManager.getInstance(). interRelateSessions(serverSession, clientSession); } @Override public void onError(Throwable t) { logger.error(t.getMessage()); Assert.assertTrue(false, "Error: " + t.getMessage()); } }); } @Override public void onError(Throwable t) { Assert.assertTrue(false, t.getMessage()); } }).sync(); } catch (InterruptedException e) { Assert.assertTrue(false, e.getMessage()); } } @Override public void onMessage(WebSocketTextMessage textMessage) { try { Session clientSession = WebSocketPassThroughTestSessionManager.getInstance(). getClientSession(textMessage.getChannelSession()); clientSession.getBasicRemote().sendText(textMessage.getText()); } catch (IOException e) { logger.error("IO error when sending message: " + e.getMessage()); } } @Override public void onMessage(WebSocketBinaryMessage binaryMessage) { try { Session clientSession = WebSocketPassThroughTestSessionManager.getInstance() .getClientSession(binaryMessage.getChannelSession()); clientSession.getBasicRemote().sendBinary(binaryMessage.getByteBuffer()); } catch (IOException e) { logger.error("IO error when sending message: " + e.getMessage()); } } @Override public void onMessage(WebSocketControlMessage controlMessage) { // Do nothing. } @Override public void onMessage(WebSocketCloseMessage closeMessage) { try { Session clientSession = WebSocketPassThroughTestSessionManager.getInstance() .getClientSession(closeMessage.getChannelSession()); clientSession.close(); } catch (IOException e) { logger.error("IO error when sending message: " + e.getMessage()); } } @Override public void onError(Throwable throwable) { } @Override public void onIdleTimeout(WebSocketControlMessage controlMessage) { } }
true
181efc38d5209b7a8c0c1dd6fedeb36834d1073d
Java
dmitrymoor/MechanismDesignPrimitives
/MechanismDesignPrimitives/src/main/java/ch/uzh/ifi/MechanismDesignPrimitives/MultiUnitAtom.java
UTF-8
2,766
2.828125
3
[]
no_license
package ch.uzh.ifi.MechanismDesignPrimitives; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; public class MultiUnitAtom extends AtomicBid { /** * Constructor * @param agentId - agent's id * @param items - the list of items * @param units - list of units of each kind of items * @param value - the value of the bundle * @throws Exception */ public MultiUnitAtom(int agentId, List<Integer> items, List<Integer> units, double value) throws Exception { super(agentId, items, value); if(items.size() != units.size()) throw new Exception("The number of units should match the number of items"); _units = units; } /** * Constructor * @param agentId - agent's id * @param items - the set of items * @param units - list of units of each kind of items * @param value - the value of the bundle * @throws Exception */ public MultiUnitAtom(int agentId, Set<Integer> items, List<Integer> units, double value) throws Exception { super(agentId, items, value); if(items.size() != units.size()) throw new Exception("The number of units should match the number of items"); _units = units; } /** * (non-Javadoc) * @see ch.uzh.ifi.MechanismDesignPrimitives.AtomicBid#copyIt() */ @Override public AtomicBid copyIt() { AtomicBid bid; try { bid = new MultiUnitAtom(_agentId, _items, _units, _type.get(AtomicBid.Value) ); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("Can't copy the bid " + this.toString()); } Iterator<Entry<String, Double> > it = _type.entrySet().iterator(); while( it.hasNext() ) { Map.Entry<String, Double> pair = (Map.Entry<String, Double>)it.next(); bid.setTypeComponent(pair.getKey(), pair.getValue()); } return bid; } /** * (non-Javadoc) * @see ch.uzh.ifi.MechanismDesignPrimitives.AtomicBid#toString() */ @Override public String toString() { String str = "( AgentId=" + _agentId + ", Items=" + _items + ", units=" + _units + ", " ; for(Map.Entry<String, Double> component : _type.entrySet()) str += component.getKey() + "=" + component.getValue() + "; "; str += ")"; return str; } /** * (non-Javadoc) * @see ch.uzh.ifi.MechanismDesignPrimitives.AtomicBid#getNumberOfUnitsByItemId(int) */ @Override public int getNumberOfUnitsByItemId(int itemId) { int idx = 0; for(Integer item : _items) { if(itemId == item) return _units.get(idx); idx += 1; } throw new RuntimeException("No such itemId " + itemId); } private List<Integer> _units; //The list of numbers of units for every item }
true
840ef2713efff4f68143e1ba2ac18d1d1547555f
Java
aplicacionmoviltesis/FindJobsRDv0
/app/src/main/java/com/example/findjobsrdv0/Pantallas_CurriculosCompleto/cPantallaReferenciasCurriculo.java
UTF-8
9,484
1.828125
2
[]
no_license
package com.example.findjobsrdv0.Pantallas_CurriculosCompleto; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.graphics.Typeface; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import com.example.findjobsrdv0.GeneralesApp.ItemClickListener; import com.example.findjobsrdv0.R; import com.example.findjobsrdv0.Adaptadores_Curriculo_Buscador.Referencias; import com.example.findjobsrdv0.Adaptadores_Curriculo_Buscador.DetalleReferenciaViewHolder; import com.firebase.ui.database.FirebaseRecyclerAdapter; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.Query; import com.google.firebase.database.ValueEventListener; public class cPantallaReferenciasCurriculo extends AppCompatActivity { private EditText etNombre, etCargoOcupado, etInstitucion, etTelefono; private String rBuscadorId, rNombreC, rCargoOcupadoC, rInstitucionC, rTelefonoC; private Button BtnRegistrarReferencia, btnActualizarReferencia; private DatabaseReference mDatabase; FirebaseRecyclerAdapter<Referencias, DetalleReferenciaViewHolder> adapter; private RecyclerView recycler_referencia; private RecyclerView.LayoutManager layoutManager; private String detallereferencias = ""; private String IdReferenciasss; private DatabaseReference databaseReferenceCurriloAct; private FirebaseDatabase databaseCurriculoAct; private String id; private String Ukey; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate( savedInstanceState ); setContentView( R.layout.activity_c_pantalla_referencias_curriculo ); TextView titulo = findViewById( R.id.xmlTituloReferencia ); Typeface face = Typeface.createFromAsset( getAssets(), "fonts/robotoslab.bold.ttf" ); titulo.setTypeface( face ); recycler_referencia = (RecyclerView) findViewById( R.id.recyclerViewReferenciaInsert ); recycler_referencia.setHasFixedSize( true ); layoutManager = new LinearLayoutManager( this ); recycler_referencia.setLayoutManager( layoutManager ); Ukey = FirebaseAuth.getInstance().getCurrentUser().getUid(); databaseCurriculoAct = FirebaseDatabase.getInstance(); databaseReferenceCurriloAct = databaseCurriculoAct.getReference(getResources().getString(R.string.Ref_Curriculos)); Query query = databaseReferenceCurriloAct.orderByChild( "sIdCurriculo" ).equalTo( Ukey ); query.addValueEventListener( new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { for (DataSnapshot FavdataSnapshot : dataSnapshot.getChildren()) { id = FavdataSnapshot.child( "sIdCurriculo" ).getValue( String.class ); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } } ); mDatabase = FirebaseDatabase.getInstance().getReference( "Referencia" ); etNombre = (EditText) findViewById( R.id.xmlbeditRegistrarEmpresaEL ); etCargoOcupado = (EditText) findViewById( R.id.xmlbeditRegistrarCargoEL ); etInstitucion = (EditText) findViewById( R.id.xmlbeditRegistrarinstitucionEL ); etTelefono = (EditText) findViewById( R.id.xmlbeditRegistrarTelefonoEL ); BtnRegistrarReferencia = (Button) findViewById( R.id.xmlBtnregistrarReferencia ); BtnRegistrarReferencia.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View view) { RegistrarReferencia( id ); } } ); btnActualizarReferencia = (Button) findViewById( R.id.xmlBtnAtualizarReferencia ); btnActualizarReferencia.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View view) { ActualizarReferencias( IdReferenciasss, id ); } } ); // if (getIntent() != null) // detallereferencias = getIntent().getStringExtra( "DetalleReferenciasID" ); // // if (!detallereferencias.isEmpty()) { // RegistrarReferencia( detallereferencias ); // } loadReferencias( Ukey ); } private void loadReferencias(String Ukey) { adapter = new FirebaseRecyclerAdapter<Referencias, DetalleReferenciaViewHolder>( Referencias.class, R.layout.cardview_detalle_referencia, DetalleReferenciaViewHolder.class, mDatabase.orderByChild( "sIdCurriculorRef" ).equalTo( Ukey ) ) { @Override protected void populateViewHolder(DetalleReferenciaViewHolder ViewHolder, Referencias model, int position) { ViewHolder.txtInstitucion.setText( model.getsInstitucionRef() ); ViewHolder.txtTelefono.setText( model.getsTelefonoRef() ); ViewHolder.txtCargoOcupado.setText( model.getsCargoOcupadoRef() ); ViewHolder.txtNombre.setText( model.getsNombrePersonaRef() ); final Referencias clickItem = model; ViewHolder.setItemClickListener( new ItemClickListener() { @Override public void onClick(View view, int position, boolean isLongClick) { IdReferenciasss = adapter.getRef( position ).getKey(); goActualizarReferencia( IdReferenciasss ); } } ); } }; recycler_referencia.setAdapter( adapter ); } private void goActualizarReferencia(String Referencia) { mDatabase.child( Referencia ).addValueEventListener( new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { Referencias referencias = dataSnapshot.getValue( Referencias.class ); etNombre.setText( referencias.getsNombrePersonaRef() ); etCargoOcupado.setText( referencias.getsCargoOcupadoRef() ); etInstitucion.setText( referencias.getsInstitucionRef() ); etTelefono.setText( referencias.getsTelefonoRef() ); } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } } ); } public void limpiarCampor() { etInstitucion.setText( "" ); etCargoOcupado.setText( "" ); etNombre.setText( "" ); etTelefono.setText( "" ); } public void RegistrarReferencia(String id) { rNombreC = etNombre.getText().toString(); rCargoOcupadoC = etCargoOcupado.getText().toString(); rInstitucionC = etInstitucion.getText().toString(); rTelefonoC = etTelefono.getText().toString(); rBuscadorId = id; if (TextUtils.isEmpty( rNombreC )) { etNombre.setError( "Campo vacío, por favor escriba el nombre " ); return; } if (TextUtils.isEmpty( rInstitucionC )) { etInstitucion.setError( "Campo vacío, por favor escriba la institucion" ); return; } if (TextUtils.isEmpty( rCargoOcupadoC )) { etCargoOcupado.setError( "Campo vacío, por favor escriba el Cargo Ocupado" ); return; } if (TextUtils.isEmpty( rTelefonoC )) { etTelefono.setError( "Campo vacío, por favor escriba el telefono" ); return; } String IdReferencia = mDatabase.push().getKey(); Referencias referencias = new Referencias( IdReferencia, Ukey, rNombreC, rCargoOcupadoC, rInstitucionC, rTelefonoC ); mDatabase.child( IdReferencia ).setValue( referencias ); limpiarCampor(); } private void ActualizarReferencias(String IdReferenciasss, String id) { rNombreC = etNombre.getText().toString(); rCargoOcupadoC = etCargoOcupado.getText().toString(); rInstitucionC = etInstitucion.getText().toString(); rTelefonoC = etTelefono.getText().toString(); rBuscadorId = id; if (TextUtils.isEmpty( rNombreC )) { etNombre.setError( "Campo vacío, por favor escriba el nombre " ); return; } if (TextUtils.isEmpty( rInstitucionC )) { etInstitucion.setError( "Campo vacío, por favor escriba la institucion" ); return; } if (TextUtils.isEmpty( rCargoOcupadoC )) { etCargoOcupado.setError( "Campo vacío, por favor escriba el Cargo Ocupado" ); return; } if (TextUtils.isEmpty( rTelefonoC )) { etTelefono.setError( "Campo vacío, por favor escriba el telefono" ); return; } String IdReferencia = IdReferenciasss; Referencias referencias = new Referencias( IdReferencia, Ukey, rNombreC, rCargoOcupadoC, rInstitucionC, rTelefonoC ); mDatabase.child( IdReferencia ).setValue( referencias ); } }
true
09ed67ca3a3a58bc4ff1cd254a10e0f1ed9cb767
Java
alzaji/rScout39
/Scout39-web/src/main/java/org/siliconvalley/scout39/vista/beanPerfil.java
UTF-8
4,489
1.757813
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.siliconvalley.scout39.vista; import java.io.Serializable; import org.siliconvalley.scout39.modelo.*; import org.siliconvalley.scout39.negocio.*; import java.util.List; import javax.annotation.ManagedBean; import javax.ejb.EJB; import javax.enterprise.context.RequestScoped; import javax.faces.context.FacesContext; import javax.inject.Inject; import javax.inject.Named; import javax.servlet.http.HttpServletRequest; /** * * @author pasantru */ @Named(value = "beanPerfil") @ManagedBean @RequestScoped public class beanPerfil implements Serializable { private AccesoGrupo promesa; private Archivo requeridos; private Usuario usuario; private Archivo archivo; private List<Archivo> listaArchivos; protected String pal; protected boolean update = false; @Inject private ControlAutorizacion ctrl; @EJB private NegocioGestorDocumentalLocal gestorArchivos; @EJB private NegocioUsuarioLocal user; public Archivo getRequeridos() { return requeridos; } public void setRequeridos(Archivo requeridos) { this.requeridos = requeridos; } public beanPerfil() { } public List<Archivo> getListaArchivos() { return listaArchivos; } public void setListaArchivos(List<Archivo> listaArchivos) { this.listaArchivos = listaArchivos; } public void listarEstadoArchivo() { listaArchivos = gestorArchivos.obtenerArchivos(ctrl.getGrupo()); } public AccesoGrupo getPromesa() { return promesa; } public void setPromesa(AccesoGrupo promesa) { this.promesa = promesa; } public String getPal() { return pal; } public void setPal(String pal) { this.pal = pal; } public List<Archivo> getUserFiles(Usuario u) { return gestorArchivos.buscarArchivos(u); } public String getRutadeUsuario(Usuario u, String ruta){ return FacesContext.getCurrentInstance().getExternalContext().getRequestContextPath() + gestorArchivos.buscarPath(u, ruta); } // Para Coordinador. public List<Archivo> listarArchivos() { if (update) { return listarArchivosAJAX(); } return gestorArchivos.listarArchivos(); } public void searchListFiles() { update = true; listarArchivos(); } public List<Archivo> listarArchivosAJAX() { return gestorArchivos.listaArchivosAJAX(pal); } // Para Educando public List<Archivo> listarArchivosNombre() { if (update) { return listarArchivosAJAXNombre(); } return gestorArchivos.buscarArchivos(ctrl.getUsuario()); } // Para Scouter public List<Archivo> listarArchivosScouter() { if (update) { return listarArchivosAJAXScouter(); } return gestorArchivos.listarArchivosScouter(ctrl.getGrupo()); } public void searchListFilesNombre() { update = true; listarArchivosNombre(); } public void searchListFilesScouter() { update = true; listarArchivosScouter(); } public List<Archivo> listarArchivosAJAXNombre() { return gestorArchivos.listaArchivosNombreAJAX(pal); } public List<Archivo> listarArchivosAJAXScouter() { return gestorArchivos.listaArchivosNombreAJAXScouter(ctrl.getGrupo(), pal); } public void validarArchivo(Archivo ar) { gestorArchivos.validarArchivo(ar); } public String checkEstadoArchivo(Archivo ar) { return gestorArchivos.getEstadoArchivo(ar); } public String checkRutaArchivo(Archivo ar) { return gestorArchivos.getRuta(ar); } public void nuevaPromesa() { HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest(); String nPromesa = request.getParameter("cambiarPromesa:promesa"); user.cambiarPromesa(ctrl.getUsuario(), nPromesa); } public List<AccesoGrupo> listarPromesas() { return user.listaPromesas(ctrl.getUsuario()); } public Archivo getArchivo() { return archivo; } public void setArchivo(Archivo archivo) { this.archivo = archivo; } }
true
216bf8d731e72e294f8c7dd46c9983c558f7e346
Java
pangyuworld/Java-learning
/design patterns/src/main/java/com/pang/template/Coffee.java
UTF-8
458
2.71875
3
[]
no_license
package com.pang.template; /** * @author pang * @version V1.0 * @ClassName: Coffee * @Package com.pang.template * @description: 咖啡 * @date 2019/10/15 10:32 */ public class Coffee extends Drink { public Coffee() { super("咖啡"); } @Override protected void prepareDrink() { System.out.println("准备咖啡豆"); } @Override protected void mix() { System.out.println("搅拌均匀"); } }
true
c5502f4083ea2c2dd79e17cca3781254e3e3d5a6
Java
JoyPanda/wangxian_server
/gateway/src/com/fy/gamegateway/mieshi/resource/manager/ResourceData.java
UTF-8
1,632
2.78125
3
[]
no_license
package com.fy.gamegateway.mieshi.resource.manager; import java.util.Enumeration; import java.util.HashMap; import java.util.Hashtable; public class ResourceData { public ResourceData(){ } private String path; //路径 private int version; //版本 private int fileType; //资源类型,主要是根据后缀区分 private Hashtable<String, String> typeMD5; //不同类型资源的MD5 //文件的大小 public int fileSize; public void setPath(String path) { this.path = path; } public String getPath() { return path; } public void setVersion(int version) { this.version = version; } public int getVersion() { return version; } public void setFileType(int fileType) { this.fileType = fileType; } public int getFileType() { return fileType; } public void setTypeMD5(Hashtable<String, String> typeMD5) { this.typeMD5 = typeMD5; } public Hashtable<String, String> getTypeMD5() { return typeMD5; } public void addTypeMD5(String type, String MD5){ typeMD5.put(type, MD5); } public String toXmlString(){ StringBuffer buff = new StringBuffer(""); buff.append(" <files filepath=\"").append(path).append("\" ") .append("version=\"").append(version).append("\" ") .append("filetype=\"").append(fileType).append("\" "); buff.append(" filesize=\""+this.fileSize+"\" "); for (Enumeration<String> keys = typeMD5.keys(); keys.hasMoreElements(); ) { String key = keys.nextElement(); String value = typeMD5.get(key); buff.append(key).append("MD5=\"").append(value).append("\" "); } buff.append("/>\n"); return buff.toString(); } }
true
42bda52cb5eba8bf94cccefd0709e891444e5ddc
Java
Straianaidas/MHFC
/src/main/java/mhfc/net/common/weapon/range/bow/ItemBow.java
UTF-8
4,674
2.140625
2
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
package mhfc.net.common.weapon.range.bow; import java.util.Random; import java.util.function.Consumer; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import mhfc.net.common.core.registry.MHFCItemRegistry; import mhfc.net.common.helper.MHFCWeaponClassingHelper; import mhfc.net.common.weapon.ItemWeapon; import mhfc.net.common.weapon.range.bow.BowWeaponStats.BowWeaponStatsBuilder; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.projectile.EntityArrow; import net.minecraft.item.EnumAction; import net.minecraft.item.ItemStack; import net.minecraft.util.IIcon; import net.minecraft.world.World; public class ItemBow extends ItemWeapon<BowWeaponStats> { public static ItemBow build(Consumer<BowWeaponStatsBuilder> config) { BowWeaponStatsBuilder builder = new BowWeaponStatsBuilder(); config.accept(builder); return new ItemBow(builder.build()); } public static final String[] ItemNameArray = new String[] { "bow", "bow1", "bow2", "bow3" }; protected double defaultArrowDamage; @SideOnly(Side.CLIENT) public IIcon[] IconArray; public ItemBow(BowWeaponStats stats) { super(stats); this.maxStackSize = 1; this.setMaxDamage(1000); } @Override public String getWeaponClassUnlocalized() { return MHFCWeaponClassingHelper.bowname; } @Override public IIcon getIcon(ItemStack stack, int renderPass, EntityPlayer player, ItemStack usingItem, int useRemaining) { if (stack != usingItem) { return IconArray[0]; } if (useRemaining > 21) { return IconArray[3]; } else if (useRemaining > 14) { return IconArray[2]; } else if (useRemaining > 7) { return IconArray[1]; } return IconArray[0]; } @Override public IIcon getIconFromDamage(int par1) { return this.IconArray[0]; } /** * returns the action that specifies what animation to play when the items is being used */ @Override public EnumAction getItemUseAction(ItemStack par1ItemStack) { return EnumAction.bow; } /** * How long it takes to use or consume an item */ @Override public int getMaxItemUseDuration(ItemStack par1ItemStack) { return 72000; } @Override public boolean getShareTag() { return true; } @Override public ItemStack onEaten(ItemStack par1ItemStack, World par2World, EntityPlayer par3EntityPlayer) { return par1ItemStack; } /** * Called whenever this item is equipped and the right mouse button is pressed. Args: itemStack, world, entityPlayer */ @Override public ItemStack onItemRightClick(ItemStack par1ItemStack, World par2World, EntityPlayer player) { player.setItemInUse(par1ItemStack, this.getMaxItemUseDuration(par1ItemStack)); return par1ItemStack; } @Override public void onPlayerStoppedUsing(ItemStack stack, World world, EntityPlayer player, int itemInUseCount) { super.onPlayerStoppedUsing(stack, world, player, itemInUseCount); int ticksUsed = getMaxItemUseDuration(stack) - itemInUseCount; boolean isCreative = (player.capabilities.isCreativeMode); if (!player.inventory.hasItem(MHFCItemRegistry.mhfcitemarrow) && !isCreative) { return; } float timeUsed = ticksUsed / 20.0F; timeUsed = ((timeUsed * timeUsed) + (timeUsed * 2.0F)) / 3.0F; if (timeUsed < 0.5d) { return; } EntityArrow entityarrow = new EntityArrow(world, player, timeUsed * 2.0F); boolean crit = new Random().nextInt(10) == 0 ? true : false; entityarrow.setIsCritical(crit); if (timeUsed >= 1.0F && timeUsed < 1.5F) { entityarrow.setIsCritical(true); } if (timeUsed > 1.0F) { timeUsed = 1.0F; } entityarrow.setDamage(entityarrow.getDamage() + this.stats.getAttack(1f)); if (isCreative) { entityarrow.canBePickedUp = 2; } else { player.inventory.consumeInventoryItem(MHFCItemRegistry.mhfcitemarrow); } if (!world.isRemote) { world.spawnEntityInWorld(entityarrow); } float pitch = 1.0F / (itemRand.nextFloat() * 0.4F + 1.2F) + timeUsed * 0.5F; world.playSoundAtEntity(player, "random.bow", 1.0F, pitch); } @Override public void onUsingTick(ItemStack stack, EntityPlayer player, int count) { player.setItemInUse(stack, count); } @Override public void registerIcons(IIconRegister par1IconRegister) { this.IconArray = new IIcon[ItemNameArray.length]; for (int i = 0; i < this.IconArray.length; ++i) { String prefix = "mhfc:"; this.IconArray[i] = par1IconRegister.registerIcon(prefix + ItemNameArray[i]); } this.itemIcon = this.IconArray[0]; } }
true
d621395e042043c9c723efb6b5dbb60a69f5be73
Java
ccOranger/springbootDemo
/demo-rabbitmq/src/main/java/com/licc/rabbitmq/config/RabbitConfig.java
UTF-8
3,730
2.578125
3
[]
no_license
package com.licc.rabbitmq.config; import lombok.extern.slf4j.Slf4j; import org.springframework.amqp.core.Binding; import org.springframework.amqp.core.BindingBuilder; import org.springframework.amqp.core.Queue; import org.springframework.amqp.core.TopicExchange; import org.springframework.amqp.rabbit.connection.CachingConnectionFactory; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Slf4j @Configuration public class RabbitConfig { @Autowired private CachingConnectionFactory connectionFactory; @Bean public RabbitTemplate rabbitTemplate() { RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory); rabbitTemplate.setMessageConverter(converter()); // 消息是否成功发送到Exchange rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> { if (ack) { log.info("消息成功发送到Exchange"); // String msgId = correlationData.getId(); } else { log.info("消息发送到Exchange失败, {}, cause: {}", correlationData, cause); } }); // 触发setReturnCallback回调必须设置mandatory=true, 否则Exchange没有找到Queue就会丢弃掉消息, 而不会触发回调 rabbitTemplate.setMandatory(true); // 消息是否从Exchange路由到Queue, 注意: 这是一个失败回调, 只有消息从Exchange路由到Queue失败才会回调这个方法 rabbitTemplate.setReturnCallback((message, replyCode, replyText, exchange, routingKey) -> { log.info("消息从Exchange路由到Queue失败: exchange: {}, route: {}, replyCode: {}, replyText: {}, message: {}", exchange, routingKey, replyCode, replyText, message); }); return rabbitTemplate; } @Bean public Jackson2JsonMessageConverter converter() { return new Jackson2JsonMessageConverter(); } @Bean public Queue apiLog() { return new Queue(MqConstants.QUEUE_API_LOG); } @Bean public Queue a() { return new Queue(MqConstants.QUEUE_API_A); } @Bean public Queue b() { return new Queue(MqConstants.QUEUE_API_B); } //Direct交换机 起名:exchange @Bean TopicExchange topicExchange() { return new TopicExchange(MqConstants.TOPIC_EXCHANGE); } @Bean Binding bindingExchangeMessage3() { return BindingBuilder.bind(apiLog()).to(topicExchange()).with(MqConstants.QUEUE_API_LOG); } /** * 解耦,一对多 */ @Bean Binding bindingExchangeMessage4() { return BindingBuilder.bind(a()).to(topicExchange()).with(MqConstants.QUEUE_API_); } /** * 解耦,一对多 */ @Bean Binding bindingExchangeMessage5() { return BindingBuilder.bind(b()).to(topicExchange()).with(MqConstants.QUEUE_API_); } //路由键必须是一串字符,用句号(.) 隔开,比如说 agreements.us,或者 agreements.eu.stockholm 等。 //路由模式必须包含一个 星号(*),主要用于匹配路由键指定位置的一个单词, // 比如说,一个路由模式是这样子:agreements..b.*,那么就只能匹配路由键是这样子的:第一个单词是 agreements,第四个单词是 b。 井号(#)就表示相当于一个或者多个单词,例如一个匹配模式是agreements.eu.berlin.#,那么,以agreements.eu.berlin开头的路由键都是可以的。 }
true
c78011eddc280c8f728e5a67c17c62082ac0b596
Java
hvivani/Java
/TestJCE.java
UTF-8
482
2.5
2
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
import javax.crypto.Cipher; import java.security.*; import javax.crypto.*; class TestJCE { public static void main(String[] args) { boolean JCESupported = false; try { KeyGenerator kgen = KeyGenerator.getInstance("AES", "SunJCE"); kgen.init(256); JCESupported = true; } catch (NoSuchAlgorithmException e) { JCESupported = false; } catch (NoSuchProviderException e) { JCESupported = false; } System.out.println("JCE Supported=" + JCESupported); } }
true
4b421c4d1a4a08da86b4286bd8a948be9d770e1f
Java
git-xiaoQ/refactor-bootcamp-202002
/src/test/java/cc/xpbootcamp/warmup/cashier/OrderReceiptTest.java
UTF-8
2,776
2.75
3
[]
no_license
package cc.xpbootcamp.warmup.cashier; import org.junit.Assert; import org.junit.jupiter.api.Test; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; class OrderReceiptTest { @Test void shouldPrintCustomerInformationOnOrder() { Customer customer = new Customer("Mr X", "Chicago, 60601"); Order order = new Order(customer, new ArrayList<>()); OrderReceipt receipt = new OrderReceipt(order); String output = receipt.printReceipt(); assertThat(output, containsString("Mr X")); assertThat(output, containsString("Chicago, 60601")); } @Test void shouldPrintItemNotWithDiscountPriceWhenDateNotTuesday() throws ParseException { List<LineItem> lineItems = new ArrayList<LineItem>() {{ add(new LineItem("巧克力", 21.5, 2)); add(new LineItem("小白菜", 10.00, 1)); }}; SimpleDateFormat formatter = new SimpleDateFormat("yyyy-M-d"); Date date = formatter.parse("2020-2-17"); Time time = new Time(date); OrderReceipt receipt = new OrderReceipt(new Order(null, lineItems, time)); String result = receipt.printReceipt(); String except = "======老王超市,值得信赖======\n" + "2020年2月17日,星期一\n" + "巧克力, 21.50 x 2, 43.00\n" + "小白菜, 10.00 x 1, 10.00\n" + "-----------------------------------\n" + "税额:5.30\n" + "总价:58.30"; Assert.assertEquals(except, result); } @Test void shouldPrintItemNotWithDiscountPriceWhenDateIsWednesday() throws ParseException { List<LineItem> lineItems = new ArrayList<LineItem>() {{ add(new LineItem("巧克力", 21.5, 2)); add(new LineItem("小白菜", 10.00, 1)); }}; SimpleDateFormat formatter = new SimpleDateFormat("yyyy-M-d"); Date date = formatter.parse("2020-2-19"); Time time = new Time(date); OrderReceipt receipt = new OrderReceipt(new Order(null, lineItems, time)); String result = receipt.printReceipt(); String except = "======老王超市,值得信赖======\n" + "2020年2月19日,星期三\n" + "巧克力, 21.50 x 2, 43.00\n" + "小白菜, 10.00 x 1, 10.00\n" + "-----------------------------------\n" + "税额:5.30\n" + "折扣:1.17\n" + "总价:57.13"; Assert.assertEquals(except, result); } }
true
ca1513043a6d0ebcb72c1b3850cc45b491c78237
Java
AneliaDoychinova/Java-Advanced
/04. Data representation and manipulation/Lab/Sorting.java
UTF-8
1,422
3.828125
4
[ "MIT" ]
permissive
import java.util.Arrays; import java.util.Scanner; public class Sorting { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); Integer[] nums = Arrays.stream(scanner.nextLine().split("\\s+")).map(Integer::parseInt).toArray(Integer[]::new); //bubbleSort(nums); selectionSort(nums); printArray(nums); } private static void printArray(Integer[] nums) { for (int i = 0; i < nums.length; i++) { System.out.printf(nums[i]+ " "); } } private static void selectionSort(Integer[] nums) { for (int i = 0; i < nums.length; i++) { int min = i; for (int j = i+1; j < nums.length ; j++) { if (nums[j] < nums[min]){ min = j; } } swap(nums, min, i); } } private static void swap(Integer[] nums, int min, int index) { int temp = nums[min]; nums[min] = nums[index]; nums[index] = temp; } private static void bubbleSort(Integer[] nums) { boolean swapped = true; do { swapped = false; for (int i = 1; i < nums.length; i++) { if (nums[i]< nums[i-1]){ swap(nums, i, i-1); swapped = true; } } } while (swapped); } }
true
68dc8d3baf78e1f40f6eb4a51d40da3fe473e5a2
Java
moutainhigh/link_xf_server
/src/main/java/com/weds/xf/service/AccessVerifyService.java
UTF-8
8,379
2.0625
2
[]
no_license
package com.weds.xf.service; import com.weds.core.base.BaseService; import com.weds.core.resp.JsonResult; import com.weds.xf.entity.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.math.BigDecimal; import java.text.SimpleDateFormat; import java.util.Date; /** * @Author * @Description 权限判断 * @Date 2020-03-05 */ @Service public class AccessVerifyService extends BaseService { @Autowired DtAcDepUserService dtAcDepUserService; @Autowired DtAcTypeService dtAcTypeService; @Autowired OnlineXfAcDepService onlineXfAcDepService; @Autowired XfAcTimeService xfAcTimeService; @Autowired XfTimeService xfTimeService; @Autowired XfUserTimeService xfUserTimeService; public JsonResult<TradEntity> accessVerify(TradReqEntity tradReqEntity, TradEntity tradEntity) throws Exception{ String userPassword = tradReqEntity.getUserPassword(); String dbUserPassword = tradEntity.getDbUserPassword(); boolean bRes = userPasswordVerify(dbUserPassword, userPassword); if (!bRes) { return failMsg("密码错误"); } short userType = tradEntity.getUserType(); bRes = userStateVerify(userType); if (!bRes) { return failMsg("人员状态错误"); } Integer cardType = tradEntity.getCardType(); bRes = cardStateVerify(cardType); if (!bRes) { return failMsg("卡状态错误"); } Long userSerial = tradEntity.getUserSerial(); String devSerial = tradReqEntity.getDevSerial(); Integer userDep = tradEntity.getUserDep(); Long acDepSerial = tradEntity.getAcDepSerial(); bRes = acDepVerify(userSerial, devSerial, userDep, acDepSerial); if (!bRes) { return failMsg("没有场所权限"); } JsonResult<TradEntity> jRes = limitVerify(tradReqEntity, tradEntity); return jRes; } private boolean userPasswordVerify(String dbUserPassword, String userPassword) { if (!userPassword.equals("")) { return userPassword.equals(dbUserPassword); } return true; } private boolean userStateVerify(Short userType) { return userType > 50 ? false : true; } private boolean cardStateVerify(Integer cardType) { return cardType == 0 ? true : false; } private boolean acDepVerify(Long userSerial, String devSerial, Integer userDep, Long acDepSerial) { DtAcDepUserEntity dtAcDepUserEntity = dtAcDepUserService.selectByPrimaryKey(userSerial, devSerial); if (null != dtAcDepUserEntity) { return true; } OnlineXfAcDepEntity onlineXfAcDepEntity = onlineXfAcDepService.selectByPrimaryKey(userDep, acDepSerial); if (null != onlineXfAcDepEntity) { return true; } return false; } private JsonResult<TradEntity> limitVerify(TradReqEntity tradReqEntity, TradEntity tradEntity) { DtAcTypeEntity dtAcTypeEntity = dtAcTypeService.selectByPrimaryKey(tradEntity.getAcType()); if (null == dtAcTypeEntity) { return failMsg("未找到账户类型信息"); } BigDecimal daySubAmt = tradEntity.getEnableSub() == 1 ? dtAcTypeEntity.getAcTimeDay() : BigDecimal.valueOf(0); tradEntity.setDaySubAmt(daySubAmt); XfTimeEntity xfTimeEntity = xfTimeService.selectByNowTime(); if (null == xfTimeEntity) { tradEntity.setIsInTime(0); // 是否允许时段外消费 Integer acTimeState = dtAcTypeEntity.getAcTimeState(); if (acTimeState == 0) { return failMsg("非消费时段"); } // 非时段编号 tradEntity.setTimeNo("0000000000000000"); tradEntity.setRate(Integer.parseInt(dtAcTypeEntity.getDiscountRate())); } else { tradEntity.setTimeBegin(xfTimeEntity.getKssj()); tradEntity.setTimeEnd(xfTimeEntity.getJssj()); tradEntity.setIsInTime(1); tradEntity.setTimeNo(xfTimeEntity.getBh()); } XfAcTimeEntity xfAcTimeEntity = xfAcTimeService.selectByAcDepAndTimeNo(tradEntity.getAcDepSerial(), tradEntity.getTimeNo()); if (null == xfAcTimeEntity) { return failMsg("未找到场所时段信息"); } xfAcTimeEntity = xfAcTimeService.selectByAcTypeAndTimeNo(tradEntity.getAcType(), tradEntity.getTimeNo()); if (null == xfAcTimeEntity) { return failMsg("未找到账户时段信息"); } Integer xfAcTimeXh = xfAcTimeEntity.getXh(); BigDecimal mealLimitAmt = xfAcTimeEntity.getTimeMaxM(); Integer mealLimitTimes = xfAcTimeEntity.getTimeMaxT(); BigDecimal realMoney = tradReqEntity.getMoney().multiply(BigDecimal.valueOf(tradEntity.getRate()).divide(BigDecimal.valueOf(100)); tradEntity.setRealMoney(realMoney); tradEntity.setXfAcTimeXh(xfAcTimeXh); BigDecimal mealSubAmt = xfAcTimeEntity.getTimeSub(); if (tradEntity.getEnableSub() == 1) { if (tradEntity.getEnableFreeMealSub() == 1) { if (mealSubAmt.intValue() > 0) { mealSubAmt = realMoney.intValue() > mealSubAmt.intValue() ? mealSubAmt : realMoney; } } } else { mealSubAmt = BigDecimal.valueOf(0); } tradEntity.setMealSubAmt(mealSubAmt); tradEntity.setMealSubEach(xfAcTimeEntity.getTimeEachsub()); tradEntity.setRate(xfAcTimeEntity.getDiscountRate()); BigDecimal dayLimitAmt = dtAcTypeEntity.getDayMaxM(); Integer dayLimitTimes = dtAcTypeEntity.getDayMaxT(); Integer dayLimitEach = dtAcTypeEntity.getAcTimeeachDay(); BigDecimal everyLimitAmt = dtAcTypeEntity.getTimeMaxM(); tradEntity.setDaySubAmt(dtAcTypeEntity.getAcSubsidy()); XfUserTimeEntity xfUserTimeEntity = xfUserTimeService.selectByPrimaryKey(tradEntity.getUserSerial()); Date date = new Date(); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); String curDate = dateFormat.format(date); if (null != xfUserTimeEntity && xfUserTimeEntity.getRq().toString().equals(curDate) && xfUserTimeEntity.getTimeNo().equals(tradEntity.getTimeNo())) { Integer dayTimes = xfUserTimeEntity.getDayCount(); BigDecimal dayAmt = xfUserTimeEntity.getDayMoney(); Integer dayEach = xfUserTimeEntity.getEachDay(); Integer mealTimes = xfUserTimeEntity.getXfCount(); BigDecimal mealAmt = xfUserTimeEntity.getXfMoney(); if (xfUserTimeEntity.getSubDay() == 1) { tradEntity.setDaySubAmt(BigDecimal.valueOf(0)); } if (xfUserTimeEntity.getEachDay() == 1) { tradEntity.setDaySubEach(0); } if (xfUserTimeEntity.getSubHour() == 1) { tradEntity.setMealSubAmt(BigDecimal.valueOf(0)); } if (xfUserTimeEntity.getEachHour() == 1) { tradEntity.setMealSubEach(0); } if ((dayLimitTimes > 0) && (dayTimes + 1 > dayLimitTimes)) { return failMsg("超日限次"); } if (everyLimitAmt.intValue() > 0 && realMoney.intValue() > everyLimitAmt.intValue()) { return failMsg("超单次限额"); } if ((tradReqEntity.getTradType() == 1) && (dayLimitAmt.intValue() > 0) && (dayAmt.add(realMoney).intValue() > dayLimitAmt.intValue())) { return failMsg("超日限额"); } else if ((tradReqEntity.getTradType() == 41) && (dayLimitEach > 0) && (dayEach + 1 > dayLimitEach)) { return failMsg("超日限额"); } if ((tradReqEntity.getTradType() == 1) && (mealLimitAmt.intValue() > 0) && (mealAmt.add(realMoney).intValue() > mealLimitAmt.intValue())) { return failMsg("超餐限额"); } else if ((tradReqEntity.getTradType() == 41) && (mealLimitTimes > 0) && (mealTimes + 1 > mealLimitTimes)) { return failMsg("超餐限额"); } } return succMsgData(tradEntity); } }
true
95b019369b5a6bd693838d2ff79b5aef97216bb7
Java
slcasner/BlinkenBone
/projects/09_javapanelsim/src/blinkenbone/panelsim/DimmableLightbulbControlSliceVisualization.java
UTF-8
9,926
2.609375
3
[ "MIT" ]
permissive
/* DimmableLightbulbControlSliceVisualization.java: a light blub, brightness coupled with color temperature. Copyright (c) 2016-2016, Joerg Hoppe j_hoppe@t-online.de, www.retrocmp.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 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 JOERG HOPPE 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. 09-Feb-2016 JH created A Lightbulb loads 16x the same unscaled image from image file, then makes 16 states with decreasing brightness from it. Color temperatur changed with brightness. Brightness maybe realized with as much transparency as possible. */ package blinkenbone.panelsim; import java.awt.AlphaComposite; import java.awt.Color; import java.awt.image.BufferedImage; import java.awt.image.DataBufferByte; import java.awt.image.RescaleOp; import blinkenbone.blinkenlight_api.Control; public class DimmableLightbulbControlSliceVisualization extends ControlSliceVisualization { static final int brightnessLevels = 16; String imageFilename; boolean useTransparency; // after load a image from disk, these Rescaleop Params are applied // this allows to modify brightness & contrast. // Here static defaults for all new visualizations public static float defaultImageRescaleopScale = 1 ; public static float defaultImageRescaleopOffset = 0 ; public DimmableLightbulbControlSliceVisualization(String imageFilename, PanelControl panelControl, Control c, int bitpos, boolean useTransparency) { super(c.name + "." + bitpos, panelControl, c, bitpos); // take image parameters from class imageRescaleopScale = defaultImageRescaleopScale ; imageRescaleopOffset = defaultImageRescaleopOffset ; this.imageFilename = imageFilename; // single file for all // brightness states this.useTransparency = useTransparency; } @Override public void loadStateImages() { // 8 states: // load a LED only once as state 0, then clone it 'brightnessLevels' // times this.addStateImage(imageFilename, 0); for (int state = 1; state < brightnessLevels; state++) { this.addStateImage(this.getStateImage(0), state); } } /* * Redshift measured for a DEC PDP-10 panel light bulb. * Measured where 16 power levels (voltage * current). * Nominal driven with +15V = 16/16 = 100% brightness. * 100% color temperature is 2350K. * * Compare to http://www.tannerhelland.com/4435/convert-temperature-rgb-algorithm-code/ */ private static final Color[] redshiftTable = new Color[] { // (r,g,b) new Color(0, 0, 0), // level = 0/16 new Color(1, 0, 0), // level = 1/16 new Color(10, 1, 1), // level = 2/16 new Color(42, 14, 6), // level = 3/16 new Color(82, 32, 13), // level = 4/16 new Color(117, 52, 23), // level = 5/16 new Color(171, 82, 41), // level = 6/16 new Color(207, 106, 56), // level = 7/16 new Color(233, 126, 69), // level = 8/16 new Color(249, 145, 82), // level = 9/16 new Color(252, 166, 100), // level = 10/16 new Color(254, 187, 122), // level = 11/16 new Color(254, 200, 142), // level = 12/16 new Color(254, 210, 161), // level = 13/16 new Color(254, 218, 174), // level = 14/16 new Color(254, 224, 185), // level = 15/16 new Color(254, 231, 194) // level = 16/16 }; /* * return the max of R|G|B for whole image * Fast linear access .... see * http://stackoverflow.com/questions/6524196/java-get-pixel-array-from-image */ private Color getBrightestColorComponent(BufferedImage image) { final byte[] pixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData(); final boolean hasAlphaChannel = image.getAlphaRaster() != null; int maxR, maxG, maxB; int r, g, b; maxR = maxG = maxB = 0; if (hasAlphaChannel) { final int pixelLength = 4; for (int pixel = 0; pixel < pixels.length; pixel += pixelLength) { // argb += (((int) pixels[pixel] & 0xff) << 24); // alpha b = (int) pixels[pixel + 1] & 0xff; // blue if (b > maxB) maxB = b; g = (int) pixels[pixel + 2] & 0xff; // green if (g > maxG) maxG = g; r = (int) pixels[pixel + 3] & 0xff; // red if (r > maxR) maxR = r; } } else { final int pixelLength = 3; for (int pixel = 0; pixel < pixels.length; pixel += pixelLength) { b = (int) pixels[pixel] & 0xff; // blue if (b > maxB) maxB = b; g = (int) pixels[pixel + 1] & 0xff; // green if (g > maxG) maxG = g; r = (int) pixels[pixel + 2] & 0xff; // red if (r > maxR) maxR = r; } } return new Color(maxR, maxG, maxB); } // scale every color channel differently private void scaleColorComponents(BufferedImage image, float scaleR, float scaleG, float scaleB) { final byte[] pixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData(); final boolean hasAlphaChannel = image.getAlphaRaster() != null; int r, g, b; if (hasAlphaChannel) { final int pixelLength = 4; for (int pixel = 0; pixel < pixels.length; pixel += pixelLength) { // argb += (((int) pixels[pixel] & 0xff) << 24); // alpha b = (int) pixels[pixel + 1] & 0xff; // blue b = Math.round(b * scaleB); if (b > 255) b = 255; pixels[pixel + 1] = (byte) b; g = (int) pixels[pixel + 2] & 0xff; // green g = Math.round(g * scaleG); if (g > 255) g = 255; pixels[pixel + 2] = (byte) g; r = (int) pixels[pixel + 3] & 0xff; // red r = Math.round(r * scaleR); if (r > 255) r = 255; pixels[pixel + 3] = (byte) r; } } else { final int pixelLength = 3; for (int pixel = 0; pixel < pixels.length; pixel += pixelLength) { b = (int) pixels[pixel] & 0xff; // blue b = Math.round(b * scaleB); if (b > 255) b = 255; pixels[pixel] = (byte) b; g = (int) pixels[pixel + 1] & 0xff; // green g = Math.round(g * scaleG); if (g > 255) g = 255; pixels[pixel + 1] = (byte) g; r = (int) pixels[pixel + 2] & 0xff; // red r = Math.round(r * scaleR); if (r > 255) r = 255; pixels[pixel + 2] = (byte) r; } } } @Override /* * give each state image a different brightness and a different red shift. * * If "transparency" is used, brightness is implemented with alpha * transparency as much as possible (opact = bright light, transparent = * dark light). * * (non-Javadoc) * * @see blinkenbone.panelsim.ControlSliceVisualization#fixupStateImages() */ // // state 0 = OFF // Alternative: use image transparency // see public void fixupStateImages() { for (int state = 0; state < brightnessLevels; state++) { ControlSliceStateImage cssi = this.getStateImage(state); /* encode levels as brightness */ // state 0 => 0; state "brightness_levels-1" -> 1.0 // float brightness = state * (1f / (brightnessLevels - 1)); // 1): adjust image pixel colors and brightness according to // red-shift table. // brigntesslevelRGB := table[brigntesslevel]/ table[100%]RGB * // unscaledRGB ; float brightnessR = (float) redshiftTable[state].getRed() / redshiftTable[16].getRed(); float brightnessG = (float) redshiftTable[state].getGreen() / redshiftTable[16].getGreen(); float brightnessB = (float) redshiftTable[state].getBlue() / redshiftTable[16].getBlue(); if (useTransparency) { /* * Produce reduced brightness with as much transparency as * possible. This makes the "lamp windows" on the acryl visible if lamp is * dim. * Alpha: 0 = invisible, 1.0 = opaque. */ // 1. determine max color brightness of dimmed image // 2. enhance base brightness to max color value == 255. // (normalized to max(R|G|B = 255) // and set transparency, so transparency(255) = original // brightness. // 3.after Display, image is as dark as before. Color maxRGB = getBrightestColorComponent(cssi.scaledStateImage); float maxDimmedChannelVal = Math.max(brightnessR * maxRGB.getRed(), brightnessG * maxRGB.getGreen()); maxDimmedChannelVal = Math.max(maxDimmedChannelVal, brightnessB * maxRGB.getBlue()); float alpha = maxDimmedChannelVal / 255; // alpha < 1 makes intensity 255 visible as brightness // 'maxChannelVal' if (alpha > 0) { // lamp image not totally black: // adjust brightness of base image, so // alpha * 255 == max color component brightness brightnessR /= alpha; brightnessG /= alpha; brightnessB /= alpha; scaleColorComponents(cssi.scaledStateImage, brightnessR, brightnessG, brightnessB); } // float alpha = 0.1f + state * (0.9f / (brightnessLevels - 1)); // https://www.teialehrbuch.de/Kostenlose-Kurse/JAVA/6693-Transparenz-in-Java2D.html // "AlphaComposite" // alpha = 0.5f ; // alpha = (float) state / (brightness_levels - 1); cssi.alphaComposite = AlphaComposite .getInstance(AlphaComposite.SRC_OVER, alpha); } else { // no transparency: just use the dim value from the table scaleColorComponents(cssi.scaledStateImage, brightnessR, brightnessG, brightnessB); } } } }
true
4026d15764a1860dd8c39fb438c2308bfd68d361
Java
vaibhavim/salesNotification
/src/main/java/com/sales/notification/app/SalesNotificationController.java
UTF-8
1,897
2.40625
2
[]
no_license
package com.sales.notification.app; import javax.jms.Queue; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jms.core.JmsTemplate; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.sales.notification.app.domain.SaleMessage; import com.sales.notification.app.service.SalesService; /** * @author Vaibhavi * This class is controller class and methods are exposed to * outside world * */ @RestController @RequestMapping("/rest") public class SalesNotificationController { @Autowired private Queue queue; @Autowired private JmsTemplate jmstemplate; @Autowired private SalesService salesService; /** * This rest call receives different types of SaleMessages and send message to * queue * {@link SalesConfigurations#queue() bean } * * @param saleMessage * @return String */ @PostMapping("/publish") public String publish(@RequestBody SaleMessage saleMessage) { jmstemplate.convertAndSend(queue, saleMessage); return "Published Succesfully"; } /** * This rest call is used to pause the Salesnotification service when message * count is {@link SalesConfigurationProperties#getPauseInterval()} * * @return String */ @GetMapping("/pauseSalesNotificationService") public String pauseSalesNotificationService() { return salesService.pauseSalesNotificationService(); } /** * This rest call is used to restart the Salesnotification service * * * @return String */ @GetMapping("/resumeSalesNotificationService") public String resumeSalesNotificationService() { return salesService.resumeSalesNotificationService(); } }
true
44e6247db406d4edcc8061e375544ca2c27d1dfc
Java
march1cat/EcDevelopeLib
/src/ec/wraper/elk/JsonQueryCondition.java
UTF-8
519
2.171875
2
[]
no_license
package ec.wraper.elk; import java.util.Map; import ec.system.Basis; public abstract class JsonQueryCondition extends Basis{ public enum ConditionType { RANGE,EQUAL } private Object type = null; private String colName = null; public JsonQueryCondition(Object type){ this.type = type; } public String getColName() { return colName; } public void setColName(String colName) { this.colName = colName; } public abstract Map toQueryExpressMap(); public abstract String QueryMethodText(); }
true
2628d3bfad4e6cac13911bc3eaf251833b8a2afd
Java
megavork/homeworks-base
/src/main/java/Denis_Belski/inheritance/Transport.java
UTF-8
643
3.484375
3
[]
no_license
package Denis_Belski.inheritance; public class Transport { int power = 0; int maxSpeed = 0; int mass = 0; String brand = ""; Transport(int power, int maxSpeed, int mass, String brand) { this.power = power; this.maxSpeed = maxSpeed; this.mass = mass; this.brand = brand; } public void showAll() { System.out.println("Brand: "+this.brand); System.out.println("Max speed km/h: "+this.maxSpeed); System.out.println("Power h/p: "+this.power); System.out.println("Power kW: "+this.power*0.74); System.out.println("Mass kg: "+this.mass); } }
true
39e2e5f7dae8901b1595f4798dd05c44ae8990ef
Java
tusharchopratech/task_manager_csc
/src/Ajax/AjaxServletProjectIdToTasks.java
UTF-8
3,771
2.203125
2
[]
no_license
package Ajax; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; 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 model.BeanProject; import model.BeanTask; import daoProject.ProjectService; import daoTask.TaskService; /** * Servlet implementation class AjaxServlet */ @WebServlet("/AjaxServletProjectIdToTasks") public class AjaxServletProjectIdToTasks extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse * response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub PrintWriter out = response.getWriter(); response.setContentType("application/xml"); String projectId = request.getParameter("projectId"); System.out.println(projectId); TaskService taskService = new TaskService(); ArrayList<BeanTask> beanTaskList = taskService .searchTasksByProjectId(projectId); String msg = taskArrayToXML(beanTaskList); out.print(msg); System.out.println(msg.toString()); out.close(); } private String taskArrayToXML(ArrayList<BeanTask> beanTaskList) { StringBuffer msg = new StringBuffer(50); msg.append("<task-info>"); for (int i = 0; i < beanTaskList.size(); i++) { msg.append("<task-id>" + beanTaskList.get(i).getId() + "</task-id>"); msg.append("<task-taskId>" + beanTaskList.get(i).getTaskId() + "</task-taskId>"); msg.append("<task-name>" + beanTaskList.get(i).getTaskName() + "</task-name>"); msg.append("<task-complete>" + beanTaskList.get(i).getCompleteY_N() + "</task-complete>"); msg.append("<task-description>" + beanTaskList.get(i).getTaskDescription() + "</task-description>"); msg.append("<task-startDate>" + beanTaskList.get(i).getStartDate() + "</task-startDate>"); msg.append("<task-finishDate>" + beanTaskList.get(i).getFinishDate() + "</task-finishDate>"); msg.append("<task-initialEstimate>" + beanTaskList.get(i).getInitialEstimate() + "</task-initialEstimate>"); msg.append("<task-revisedEstimate>" + beanTaskList.get(i).getRevisedEstimate() + "</task-revisedEstimate>"); // System.out.println("\n\n\n\n\n\n actual work complete"+beanTaskList.get(i).getActualWorkComplete()); msg.append("<task-actualWorkComplete>" + beanTaskList.get(i).getActualWorkComplete() + "</task-actualWorkComplete>"); msg.append("<task-actualStartDate>" + beanTaskList.get(i).getActualStartDate() + "</task-actualStartDate>"); msg.append("<task-actualCompletionDate>" + beanTaskList.get(i).getActualCompletionDate() + "</task-actualCompletionDate>"); msg.append("<task-assignedTo>" + beanTaskList.get(i).getAssignedTo() + "</task-assignedTo>"); msg.append("<task-deleted>" + beanTaskList.get(i).getDeleted() + "</task-deleted>"); msg.append("<task-buildId>" + beanTaskList.get(i).getBuildId() + "</task-buildId>"); msg.append("<task-releaseId>" + beanTaskList.get(i).getReleaseId() + "</task-releaseId>"); msg.append("<task-projectId>" + beanTaskList.get(i).getProjectId() + "</task-projectId>"); } msg.append("</task-info>"); return msg.toString(); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub } }
true
bf1095a64b8608b3989e9d619b34077f819cff27
Java
nanourafou/MiniProjectCE-2018
/src/unitTest/CameraTest.java
UTF-8
1,643
2.953125
3
[]
no_license
package unitTest; import elements.Camera; import org.junit.jupiter.api.Test; import primitives.Point3D; import primitives.Ray; import primitives.Vector; import static org.junit.jupiter.api.Assertions.*; public class CameraTest { Point3D p1=new Point3D(0,0,0); Point3D p2=new Point3D(-3,3,-3); Ray r11=new Ray(p1,new Vector(1/Math.sqrt(6),1/Math.sqrt(6),-Math.sqrt(2)/Math.sqrt(3))); Ray r12=new Ray(p1,new Vector(-1/Math.sqrt(6),-1/Math.sqrt(6),-Math.sqrt(2)/Math.sqrt(3))); Ray r13=new Ray(p1,new Vector(-1/Math.sqrt(6),1/Math.sqrt(6),-Math.sqrt(2)/Math.sqrt(3))); Ray r14=new Ray(p1,new Vector(1/Math.sqrt(6),-1/Math.sqrt(6),-Math.sqrt(2)/Math.sqrt(3))); Ray r15=new Ray(p1,new Vector(0,0,-1)); @Test public void constructRayThoughPixelTest(){ Camera c1 = new Camera(new Point3D(0,0,0),new Vector(0,0,-1),new Vector(0,-1,0)); //Vous ne savez pas calculer un signe assertEquals(c1.constructRayThoughPixel(3, 3, 3, 3, 100, 150, 150),r11); assertEquals(c1.constructRayThoughPixel(3, 3, 1, 1, 100, 150, 150),r12); assertEquals(c1.constructRayThoughPixel(3, 3, 1, 3, 100, 150, 150),r13); assertEquals(c1.constructRayThoughPixel(3, 3, 3, 1, 100, 150, 150),r14); assertEquals(c1.constructRayThoughPixel(3, 3, 2, 2, 100, 150, 150),r15); } @Test public void cameraTest(){ Camera c = new Camera(new Point3D(0,0,0),new Vector(0,0,-1),new Vector(0,-1,0)); Ray t = c.constructRayThoughPixel(3,3,3,3,100,150,150); Ray r = new Ray(new Point3D(0,0,0),(new Vector(50,50,-100)).normalize()); assertEquals(r,t); } }
true
f517ba93144b95b23ff149d02a1f293dce90a01c
Java
djsong/AlkkaGo
/app/src/main/java/com/djsong/alkkago/SingleAlkkagiMatch.java
UTF-8
8,684
2.78125
3
[]
no_license
package com.djsong.alkkago; import android.content.Context; import android.widget.Toast; import java.util.ArrayList; /** * Created by DJSong on 2016-03-25. * More or less manages the rule of game. A match is composed of multiple turns. */ public class SingleAlkkagiMatch { AKGPlayWorld mPlayWorld = null; AlkkagiActivity mAlkkagiActivity = null; /** Created for each turn */ SingleAlkkagiTurn mCurrentTurn = null; /** Comes from PlayWorld. */ private ArrayList<AKGStone> mBlackStones = null; private ArrayList<AKGStone> mWhiteStones = null; /** Definition of player type */ public static final int ALKKAGI_PLAYER_UNKNOWN = 0; public static final int ALKKAGI_PLAYER_HUMAN = 1; public static final int ALKKAGI_PLAYER_AI = 2; /** It will define play type.. */ private int mBlackStonePlayerType = ALKKAGI_PLAYER_HUMAN; public int GetBlackStonePlayerType() {return mBlackStonePlayerType;} private int mWhiteStonePlayerType = ALKKAGI_PLAYER_AI; public int GetWhiteStonePlayerType() {return mWhiteStonePlayerType;} /** Current turn is for black if true, white if false. */ private boolean mbCurrentTurnBlack = true; private boolean mbMatchStarted = false; public boolean IsMatchStarted() {return mbMatchStarted;} private boolean mbMatchCompleted = false; public boolean IsMatchCompleted() {return mbMatchCompleted;} private boolean mbAllBlackStonesAreDead = false; private boolean mbAllWhiteStonesAreDead = false; public boolean IsBlackWon(){ // Is match completed and beat the white return (mbMatchCompleted && !mbAllBlackStonesAreDead && mbAllWhiteStonesAreDead); } public boolean IsWhiteWon(){ // Is match completed and beat the black return (mbMatchCompleted && mbAllBlackStonesAreDead && !mbAllWhiteStonesAreDead); } public boolean IsTied(){ // Is match completed and nobody won.. return (mbMatchCompleted && mbAllBlackStonesAreDead && mbAllWhiteStonesAreDead); } private boolean mbIsAITrainingMatch = false; // Almost for Deep shitting AI training. public boolean IsAITrainingMatch() {return mbIsAITrainingMatch;} public SingleAlkkagiMatch(AKGPlayWorld InPlayWorld, AlkkagiActivity InActivity, int BlackPlayerType, int WhitePlayerType, ArrayList<AKGStone> BlackStoneList, ArrayList<AKGStone> WhiteStoneList){ mPlayWorld = InPlayWorld; mAlkkagiActivity = InActivity; mBlackStonePlayerType = BlackPlayerType; mWhiteStonePlayerType = WhitePlayerType; mBlackStones = BlackStoneList; mWhiteStones = WhiteStoneList; } public void StartMatch(boolean bInAITrainingMatch){ if(mPlayWorld == null || mBlackStones == null || mWhiteStones == null){ return; // Cannot start.. } mbMatchStarted = true; mbMatchCompleted = false; mbIsAITrainingMatch = bInAITrainingMatch; // Logs will be suppressed for this. // Give some random placement for AI training. mPlayWorld.SetStonesAtStartingPosition(mbIsAITrainingMatch ? mPlayWorld.AITrainingModeRandomPlacement : 0.0f); StartBlackTurn(); // Black is the first anyway. } private synchronized void StartBlackTurn(){ mbCurrentTurnBlack = true; mCurrentTurn = new SingleAlkkagiTurn(mBlackStonePlayerType, mbCurrentTurnBlack, mBlackStones, mWhiteStones); mPlayWorld.NotifyTurnBegin(mCurrentTurn); } private synchronized void StartWhiteTurn(){ mbCurrentTurnBlack = false; mCurrentTurn = new SingleAlkkagiTurn(mWhiteStonePlayerType, mbCurrentTurnBlack, mWhiteStones, mBlackStones); mPlayWorld.NotifyTurnBegin(mCurrentTurn); } public boolean IsCurrentlyHumanTurn(){ return ( (mbCurrentTurnBlack && mBlackStonePlayerType == ALKKAGI_PLAYER_HUMAN) || (!mbCurrentTurnBlack && mWhiteStonePlayerType == ALKKAGI_PLAYER_HUMAN) ); } public boolean IsCurrentlyAITurn(){ return ( (mbCurrentTurnBlack && mBlackStonePlayerType == ALKKAGI_PLAYER_AI) || (!mbCurrentTurnBlack && mWhiteStonePlayerType == ALKKAGI_PLAYER_AI) ); } /** It will return valid array only if human player exists and currently human turn. */ public synchronized ArrayList<AKGStone> GetHumanStonesIfCurrentHumanTurn(){ if(mbCurrentTurnBlack && mBlackStonePlayerType == ALKKAGI_PLAYER_HUMAN){ return mBlackStones; } else if(!mbCurrentTurnBlack && mWhiteStonePlayerType == ALKKAGI_PLAYER_HUMAN){ return mWhiteStones; } return null; } /** It will return valid array only if AI player exists and currently AI turn. */ public synchronized ArrayList<AKGStone> GetAIStonesIfCurrentAITurn(){ if(mbCurrentTurnBlack && mBlackStonePlayerType == ALKKAGI_PLAYER_AI){ return mBlackStones; } else if(!mbCurrentTurnBlack && mWhiteStonePlayerType == ALKKAGI_PLAYER_AI){ return mWhiteStones; } return null; } /** Get stones list which is not for this turn, no matter human or AI. */ public ArrayList<AKGStone> GetStonesForOtherTurn(){ return mbCurrentTurnBlack ? mWhiteStones : mBlackStones; } public synchronized boolean IsWaitingForKickingThisTurn(){ return (mCurrentTurn != null && mCurrentTurn.IsThisTurnWaitingForKicking()); } /** Notification of stone kicking. AI kicking is expected to send the target information too. */ public void NotifyKickedAStone(AKGStone KickedStone,AKGStone TargetIfAI){ // Notify to turn, too. if(mCurrentTurn != null){ mCurrentTurn.NotifyKickedAStoneForThisTurn(KickedStone, TargetIfAI); } } public void PhysicsThread_CheckMatch() { // Check if current turn is end, then switch turn if(mCurrentTurn != null && !mbMatchCompleted){ if(mCurrentTurn.PhysicsThread_CheckTurnEnd()){ // Turn check. // Before start the new turn, send play world some notification. mPlayWorld.NotifyTurnEnd(mCurrentTurn); // I would like to signal main thread to start turn is there some way? if (mbCurrentTurnBlack) { StartWhiteTurn(); /*if(!mbIsAITrainingMatch) { mAlkkagiActivity.runOnUiThread(new Runnable() { public void run() { Toast.makeText(mAlkkagiActivity, "White Turn", Toast.LENGTH_SHORT).show(); } }); }*/ } else { StartBlackTurn(); /*if(!mbIsAITrainingMatch) { mAlkkagiActivity.runOnUiThread(new Runnable() { public void run() { Toast.makeText(mAlkkagiActivity, "Black Turn", Toast.LENGTH_SHORT).show(); } }); }*/ } } } // Also check if all stones of one side are dead, then the match end.. if(!mbMatchCompleted) { boolean bBlackStillActive = false; for (int SI = 0; SI < mBlackStones.size(); ++SI) { if (mBlackStones.get(SI).IsAlive()) { bBlackStillActive = true; break; } } mbAllBlackStonesAreDead = !bBlackStillActive; boolean bWhiteStillActive = false; for (int SI = 0; SI < mWhiteStones.size(); ++SI) { if (mWhiteStones.get(SI).IsAlive()) { bWhiteStillActive = true; break; } } mbAllWhiteStonesAreDead = !bWhiteStillActive; // In some occasion, both black and white might dead at the same time. if (mbAllBlackStonesAreDead || mbAllWhiteStonesAreDead) { mbMatchCompleted = true; if(!mbIsAITrainingMatch) { mAlkkagiActivity.runOnUiThread(new Runnable() { public void run() { Toast.makeText(mAlkkagiActivity, "Match Completed! " + (IsBlackWon() ? "Black Won" : (IsWhiteWon() ? "White Won" : "Tied")), Toast.LENGTH_LONG).show(); } }); } } } } }
true
a54203f260560499492424ab449a0234523fa2c2
Java
shekabhias/ctci
/ctci/src/threads/MyClass.java
UTF-8
1,200
4.09375
4
[]
no_license
package threads; public class MyClass extends Thread{ private String name; private MyObject myObj; public MyClass(String name, MyObject myObj) { super(); this.name = name; this.myObj = myObj; } public void run() { if(name.equals("1")) MyObject.foo(name); else if (name.equals("2")) MyObject.bar(name); } public static void main(String[] args) { MyObject obj1 = new MyObject(); MyObject obj2 = new MyObject(); MyClass thread1 = new MyClass("1", obj1); MyClass thread2 = new MyClass("2", obj2); thread1.start(); thread2.start(); } } class MyObject { public static synchronized void foo(String name) { System.out.println("Thread " + name + ".foo(): starting"); try { Thread.sleep(3000); } catch (InterruptedException e) { System.out.println("Thread " + name + "interrupted."); } System.out.println("Thread " + name + ".foo(): ending"); } public static synchronized void bar(String name) { System.out.println("Thread " + name + ".bar(): starting"); try { Thread.sleep(3000); } catch (InterruptedException e) { System.out.println("Thread " + name + "interrupted."); } System.out.println("Thread " + name + ".bar(): ending"); } }
true
beed504cfb7c0a5fc0b5edab26cd115d0252526f
Java
nikosciatore/byob-v1
/src/application/Main.java
UTF-8
2,255
2.953125
3
[]
no_license
package application; import control.client.Bot; import control.server.BotServer; import javafx.application.Application; import javafx.stage.Stage; import javafx.scene.Scene; import javafx.scene.layout.VBox; import javafx.fxml.FXMLLoader; /** * La classe Main è responsabile dell'avvio dell'applicazione * Attraverso il metodo main è possibile avviare il Bot oppure il Server C&C * sulla base del parametro in ingresso */ public class Main extends Application { public static boolean SERVER; public static BotServer botServer; public static Bot bot; public static Stage stage; public static UserInterfaceController uiController; private VBox root; private Scene scene; /** * Il metodo main in base al parametro in ingresso avvia il bot oppure * il serverC&C. * @param args gli unici valori possibili sono "client" o "server" */ public static void main(String[] args) { if(args.length==0){ System.out.println("Enter parameter 'client' or 'server'"); return; }else{ if(args[0].equals("server")){ SERVER = true; botServer = new BotServer(); botServer.init(); launch(args); /*avvio dell'interfaccia grafica*/ }else if (args[0].equals("client")){ SERVER = false; bot = new Bot(); bot.init(); bot.start(); /*avvio delle richieste http*/ }else{ System.out.println("Only valid parameter are 'server' and 'client'"); return; } } } /** * Metodo che viene chiamato all'avvio dell'applicazione */ @Override public void start(Stage primaryStage) throws Exception{ stage = primaryStage; FXMLLoader loader = new FXMLLoader(getClass().getResource("user_interface.fxml")); root = (VBox)loader.load(); uiController = loader.getController(); scene = new Scene(root); scene.getStylesheets().add(getClass().getResource("user_interface.css").toExternalForm()); primaryStage.setTitle("BYOBv1"); primaryStage.setScene(scene); primaryStage.show(); } /** * Metodo che viene chiamato alla chiusura dell'applicazione */ @Override public void stop() throws Exception { if(SERVER){ botServer.close(); }else{ bot.close(); } super.stop(); } public static UserInterfaceController getUiController() { return uiController; } }
true