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
09dd900bd9aa69b1f9387b20b5c90378bba9f997
Java
beerent/limbix_server
/Remind Me/src/com/remindme/reminder/TagManager.java
UTF-8
3,599
2.53125
3
[]
no_license
package com.remindme.reminder; import java.util.ArrayList; import java.util.Scanner; import org.joda.time.DateTime; import com.remindme.database.QueryResult; import com.remindme.server.response.RequestResponse; import com.remindme.user.User; import com.remindme.util.DateUtil; public class TagManager { private ReminderDAO reminder_dao; public TagManager(){ this.reminder_dao = new ReminderDAO(); } public Tag getTag(String tag_str) { QueryResult result = reminder_dao.getTag(tag_str); if(!result.containsData()) return null; return new Tag(Integer.parseInt(result.getElement(0, "tag_id")), result.getElement(0, "tag")); } public int addTag(String tag_str) { return reminder_dao.addTag(tag_str); } public void mapTag(Tag tag, Reminder reminder) { this.reminder_dao.mapTag(tag.getTagId(), reminder.getReminderId()); } public ArrayList<Tag> getTags(User user, DateTime due_date_before, DateTime due_date, DateTime due_date_after, DateTime created_date_before, DateTime created_date, DateTime created_date_after, String complete, String deleted) { DateUtil date_util = new DateUtil(); String due_date_before_str = null; String due_date_str = null; String due_date_after_str = null; String created_date_before_str = null; String created_date_str = null; String created_date_after_str = null; if(due_date_before != null) due_date_before_str = date_util.JodaDateTimeToSQLDateTime(due_date_before); if(due_date != null) due_date_str = date_util.JodaDateTimeToSQLDateTime(due_date); if(due_date_after != null) due_date_after_str = date_util.JodaDateTimeToSQLDateTime(due_date_after); if(created_date_before != null) created_date_before_str = date_util.JodaDateTimeToSQLDateTime(created_date_before); if(created_date != null) created_date_str = date_util.JodaDateTimeToSQLDateTime(created_date); if(created_date_after != null) created_date_after_str = date_util.JodaDateTimeToSQLDateTime(created_date_after); ArrayList<Tag> tags = new ArrayList<Tag>(); QueryResult results = this.reminder_dao.getTags( user.getUserId(), due_date_before_str, due_date_str, due_date_after_str, created_date_before_str, created_date_str, created_date_after_str, complete, deleted ); for(int i = 0; i < results.numRows(); i++) tags.add(new Tag(Integer.parseInt(results.getElement(i, 0)), results.getElement(i, 1))); return tags; } public String getTagsCommaDelimited(ArrayList<String> tags){ if(tags.size() == 0) return null; if(tags.size() == 1) return tags.get(0); String tags_string = tags.get(0); for(int i = 1; i < tags.size(); i++){ tags_string += ", " + tags.get(i); } return tags_string; } /* * scans through a reminder string, storing all tags into an arraylist, * and return the arraylist. */ public ArrayList<String> getTags(String reminder){ ArrayList<String> tags = new ArrayList<String>(); Scanner sc = new Scanner(reminder); String token; while(sc.hasNext()){ token = sc.next(); if(token.charAt(0) == '#' && token.substring(0).matches("^.*[^a-zA-Z0-9 ].*$")) tags.add(token); } sc.close(); return tags; } public ArrayList<String> getStringsFromCommaDeliminatedString(String tags){ if(tags == null || tags.equals("")) return null; String [] tags_array = tags.split(","); ArrayList<String> ret_array = new ArrayList<String>(); for(String s : tags_array){ ret_array.add(s.trim()); } System.out.println("returning: " + ret_array); return ret_array; } }
true
31cb75c946216c6c3a2668e6d5f3927290ce907f
Java
meta-richa-mittal/get2015
/OOP/socialNetwork/Graph.java
UTF-8
3,043
3.828125
4
[]
no_license
package socialNetwork; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; /** * * @author Richa Mittal * Description: This class contains six functions * Function 1: adds node to the nodes list * Function 2: removes node from the nodes list * Function 3: searches nodes by the given name * Function 4: adds connection between two nodes * Function 5: removes connection between two nodes * Function 6: displays all available connections * */ public class Graph { static Set<Node> nodeSet=new HashSet<Node>(); Set<Node> filteredNodeSet=new HashSet<Node>(); Iterator<Node> iterator; static Map<String,Set<Node>> map=new HashMap<String, Set<Node>>(); /** * This function adds node to the nodes list * @param node: node to be added */ public void addNode(Node node) { nodeSet.add(node); } /** * This function removes node from the nodes list * @param node: node to be deleted */ public void removeNode(Node node) { nodeSet.remove(node); } /** * This function searches nodes by the given name * @param name: name to be searched in the nodes list * @return a set of nodes containing information of all available users having given name */ public Set<Node> searchByName(String name) { iterator= nodeSet.iterator(); while(iterator.hasNext()) { Node nodeValue=iterator.next(); if(nodeValue.name.compareToIgnoreCase(name)==0) { filteredNodeSet.add(nodeValue); } } return filteredNodeSet; } /** * This function adds connection between two nodes * @param node1: node requesting for the connection * @param node2: node accepting connection */ void addEdge(Node node1, Node node2) { //System.out.println("-----"+node1.email+"----"); //System.out.println("-----"+node2.email+"----"); node1.nodesSet.add(node2); node2.nodesSet.add(node1); try { map.put(node1.email, node1.nodesSet); map.put(node2.email, node2.nodesSet); } catch(Exception e) { System.out.println(e); } } /** * This function removes connection between two nodes * @param node1: node requesting for the disconnection * @param node2: node accepting disconnection */ void removeEdge(Node node1, Node node2) { map.remove(node2, node2); map.remove(node2, node1); } /** * This function displays all available connections */ public void displayConnections() { if(map.size()==0) { System.out.println("No connections"); } Set<String> keys = map.keySet(); Iterator<String> itr = keys.iterator(); String key; Set<Node> values; while(itr.hasNext()) { key = (String)itr.next(); values =map.get(key); System.out.println("\nFriends of "+ key + " are ---- "); Iterator<Node> i=values.iterator(); while(i.hasNext()) { System.out.println(i.next().email); } } } }
true
d2c2b0853da2d99eed599f2f9418eb8efd2bb604
Java
slowlearnercz/java-basic
/day_6_code/src/com/zhichen/day06/demo05Synchronized2/RunnableImpl.java
UTF-8
994
3.734375
4
[]
no_license
package com.zhichen.day06.demo05Synchronized2; /** * @author Zhichen * @school FZU * @create 2020-08-27 15:09 * * * 解决线程安全问题的第二种方案:使用同步方法 * 使用步骤: * 1.把访问共享数据的代码抽取出来,放入一个方法中 * 2.用synchronized修饰方法 * * 同步方法方案中,锁对象是谁?就是实现类创建的对象,new RunnableImpl() */ public class RunnableImpl implements Runnable { private int ticket = 100; @Override public void run() { while(true){ sellTicket(); } } //定义一个同步方法 public synchronized void sellTicket(){ if(ticket>0){ try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+"正在卖第"+ticket+"张票"); ticket--; } } }
true
e9b4039c0f81286ba309c1b2d545a069134cb34c
Java
fedups/com.obdobion.algebrain
/src/main/java/com/obdobion/algebrain/function/FuncFlatRate.java
UTF-8
1,790
2.515625
3
[ "MIT" ]
permissive
package com.obdobion.algebrain.function; import java.text.ParseException; import com.obdobion.algebrain.Function; import com.obdobion.algebrain.ValueStack; import com.obdobion.algebrain.support.EquationSupport; import com.obdobion.algebrain.token.TokVariable; /** * <p> * FuncFlatRate class. * </p> * * @author Chris DeGreef fedupforone@gmail.com * @since 1.3.9 */ public class FuncFlatRate extends Function { /** * <p> * Constructor for FuncFlatRate. * </p> */ public FuncFlatRate() { super(); } /** * <p> * Constructor for FuncFlatRate. * </p> * * @param var a {@link com.obdobion.algebrain.token.TokVariable} object. */ public FuncFlatRate(final TokVariable var) { super(var); } /** {@inheritDoc} */ @Override public void resolve(final ValueStack values) throws Exception { if (values.size() < getParameterCount()) throw new Exception("missing operands for " + toString()); try { final String tableName = values.popString(); final String[] keys = new String[5]; for (int a = 0; a < getParameterCount() - 1; a++) keys[a] = values.popString(); final EquationSupport model = getEqu().getSupport(); double rate = 0D; rate = model.resolveRate(tableName, getEqu().getBaseDate(), keys[0], keys[1], keys[2], keys[3], keys[4]); values.push(new Double(rate)); } catch (final ParseException e) { e.fillInStackTrace(); throw new Exception(toString() + "; " + e.getMessage(), e); } } /** {@inheritDoc} */ @Override public String toString() { return "function(flatrate)"; } }
true
2e684f7d94bb2c292173c1cf41ea7da7d9ffe7db
Java
ASIAutomation/agent-maintenance
/src/test/java/Automation/AGM/Partner_Information_Update.java
UTF-8
2,579
2.15625
2
[]
no_license
package Automation.AGM; import org.apache.log4j.Logger; import org.testng.annotations.*; import java.text.*; import java.util.*; import Automation.AGM.pages.*; import Automation.AGM.testBase.TestBase; public class Partner_Information_Update extends TestBase { public static final Logger log = Logger.getLogger(Partner_Information_Update.class.getName()); AgentSummary AS; AgentInfo AI; AgentContactInfo AC; PartnerInfo PI; Birthdays BD; Confirmation CF; @DataProvider(name="AGM_Master") public String[][] GetData() { String[][] data = GetData("Update_Partner", "AGM_Master"); return data; } @BeforeTest public void SetUp() { SetLog(); Log("====================================== Starting Update Partner Information Batch ======================================"); InitAGM("Chrome"); AS = new AgentSummary(driver); AI = new AgentInfo(driver); AC = new AgentContactInfo(driver); PI = new PartnerInfo(driver); BD = new Birthdays(driver); CF = new Confirmation(driver); } /** * * @param casenum * @param agentid */ @Test(dataProvider="AGM_Master") public void Run_Link_Global_Agents(String casenum, String agentid, String partnerid, String partnername, String partnertype, String action, String plat, String blue) { Log("\n======= Starting Case: " + casenum + " ======="); GetURL("https://policy.americanstrategic.com/Maintenance/Agents/AgentMaintenance.aspx?agentid=" + agentid); AI.ClickAgentInformationPage(); if (blue.equals("Y")) { AI.CheckBlueAgent(); } AI.ClickNext(); AC.ClickPartnerInformationPage(); Date date = new Date(); SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy"); String strDate = formatter.format(date); PI.TypeDateAppointedPGRPHA(strDate); PI.TypePartnerID(partnerid); PI.SelectPartnerName(partnername); if (partnertype.equals("1")) { PI.SelectPartnerType("Child"); } else { PI.SelectPartnerType("Parent"); } if (action.equals("Add")) { PI.ClickAddPartner(); } if (plat.equals("Y")) { PI.ClickAddPlatinum(); PI.CheckHasPlatinumQuoting("Y"); } PI.ClickNext(); BD.ClickConfirmationPage(); //CF.ClickFinish(); Log("======= Case: " + casenum + " successfully executed ======="); } @AfterTest public void EndBatch() { //QuitBrowser(); Log("\n====================================== End Partner Information Batch ======================================"); } }
true
19fce290e83ce5f4d86d383f05803bd2f6ae36cd
Java
BrunoCarrier/SpringMobileWarsaw
/src/main/java/bruno/mobilewarsaw/spring/SimpleController.java
UTF-8
654
2.46875
2
[]
no_license
package bruno.mobilewarsaw.spring; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; @RestController public class SimpleController { @RequestMapping(value = "/", method = RequestMethod.GET) String home() { return "Hello Mobile Warsaw!"; } @RequestMapping(value = "/{name}", method = RequestMethod.GET) String securityHazard(@PathVariable String name) { return "Hello " + name + "!"; } }
true
dd9411263d8828b2a97b5ea7046e8626759d63c5
Java
rohanshrimal/directorymonitor
/src/main/java/com/directorymonitor/model/ExtendedFileAttributes.java
UTF-8
563
2.140625
2
[]
no_license
package com.directorymonitor.model; import com.fasterxml.jackson.annotation.JsonView; public enum ExtendedFileAttributes { FILE_NAME("name"), FILE_SIZE("size"), CREATION_DATE("creationDate"), LAST_ACCESS_DATE("lastAccessDate"), LAST_MODIFIED_DATE("dateModified"), FILE_PATH("path"), FILE_EXTENSION("extension"), FILE_TOKENS("tokens"); @JsonView(Views.Public.class) private String customName; private ExtendedFileAttributes(String customName) { this.customName = customName; } public String getCustomName() { return this.customName; } }
true
cdabf85a0a0eb8c4758c91109442d2b344a09349
Java
master0022/Mac0321Trabalho
/src/Trabalho/Pokebola.java
UTF-8
148
2.125
2
[]
no_license
package Trabalho; public class Pokebola extends Item { public Pokebola(int Quantidade) { super("Pokebola Simples", Quantidade); } }
true
28ae987dd2ec201ac9746d4c6b2cc5d0aabc1ca9
Java
fracz/refactor-extractor
/results-java/deeplearning4j--deeplearning4j/009986a0b391fbe6f86b47715d06af6ec29f3da1/before/KerasConvolutionLayer.java
UTF-8
1,882
2.296875
2
[]
no_license
package org.deeplearning4j.nn.modelimport.keras.layers; import lombok.extern.slf4j.Slf4j; import org.deeplearning4j.nn.conf.layers.ConvolutionLayer; import org.deeplearning4j.nn.modelimport.keras.InvalidKerasConfigurationException; import org.deeplearning4j.nn.modelimport.keras.KerasLayer; import org.deeplearning4j.nn.modelimport.keras.UnsupportedKerasConfigurationException; import java.util.Map; /** * Created by davekale on 1/5/17. */ @Slf4j public class KerasConvolutionLayer extends KerasLayer { public KerasConvolutionLayer(Map<String,Object> layerConfig) throws InvalidKerasConfigurationException, UnsupportedKerasConfigurationException { this(layerConfig, true); } public KerasConvolutionLayer(Map<String,Object> layerConfig, boolean enforceTrainingConfig) throws InvalidKerasConfigurationException, UnsupportedKerasConfigurationException { super(layerConfig, enforceTrainingConfig); this.dl4jLayer = new ConvolutionLayer.Builder() .name(this.layerName) .nOut(getNOutFromConfig(layerConfig)) .dropOut(getDropoutFromConfig(layerConfig)) .activation(getActivationFromConfig(layerConfig)) .weightInit(getWeightInitFromConfig(layerConfig, enforceTrainingConfig)) .biasInit(0.0) .l1(getWeightL1RegularizationFromConfig(layerConfig, enforceTrainingConfig)) .l2(getWeightL2RegularizationFromConfig(layerConfig, enforceTrainingConfig)) .convolutionMode(getConvolutionModeFromConfig(layerConfig)) .kernelSize(getKernelSizeFromConfig(layerConfig)) .stride(getStrideFromConfig(layerConfig)) .padding(getPaddingFromConfig(layerConfig)) .build(); } public ConvolutionLayer getConvolutionLayer() { return (ConvolutionLayer)this.dl4jLayer; } }
true
23a0e5eda76f5e1ce6ea64264e2bec16d31934b9
Java
arminbeiner/stock-comparison
/src/main/java/ch/ibw/nds/appl2017/model/ComparisonOutput.java
UTF-8
1,213
2.4375
2
[]
no_license
package ch.ibw.nds.appl2017.model; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.List; public class ComparisonOutput { private static final Logger LOGGER = LoggerFactory.getLogger(ComparisonOutput.class); private List<ComparisonOutputElement> comparisonOutputElements; private ComparisonOutput(List<ComparisonOutputElement> comparisonOutputElements) { this.comparisonOutputElements = comparisonOutputElements; LOGGER.debug(this.toString()); } public static ComparisonOutput create(List<ComparisonOutputElement> comparisonOutputElements) { return new ComparisonOutput(comparisonOutputElements); } @Override public String toString() { StringBuilder stringBuilder = new StringBuilder("Comparison-Output: "); stringBuilder.append(this.comparisonOutputElements); return stringBuilder.toString(); } public List<ComparisonOutputElement> getComparisonOutputElements() { return comparisonOutputElements; } public void setComparisonOutputElements(List<ComparisonOutputElement> comparisonOutputElements) { this.comparisonOutputElements = comparisonOutputElements; } }
true
62ddd20aec4c58928c47b24aa907205799bced0e
Java
sinaneski/range-util
/src/test/java/se/range/RangeContainerTest.java
UTF-8
3,187
3.0625
3
[ "MIT" ]
permissive
package se.range; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.util.ArrayList; import java.util.List; import static org.junit.Assert.assertEquals; /** * RangeContainer unit tests with long implementation * @author Sinan Eski */ public class RangeContainerTest { private final RangeContainer<Long, Range<Long>> rangeContainer = new RangeContainer<>(); @Before public void setUp () { rangeContainer.add(new Range<>(2L, 3L)); rangeContainer.add(new Range<>(6L, 9L)); } @After public void tearDown () { rangeContainer.clear(); } @Test public void add_ShouldAddToIndex_1_AsRange_4_5_WhenGivenRange_4_5() throws Exception { Range<Long> newRange = new Range<>(4L, 5L); rangeContainer.add(newRange); assertEquals(3, rangeContainer.size()); assertEquals(newRange, rangeContainer.get(1)); } @Test public void add_ShouldAddToIndex_0_AsRange_0_5_WhenGivenRange_3_5() throws Exception { Range<Long> mergedRange = new Range<>(2L, 5L); rangeContainer.add(new Range<>(3L, 5L)); assertEquals(2, rangeContainer.size()); assertEquals(mergedRange, rangeContainer.get(0)); } @Test public void add_ShouldAddToIndex_0_AsRange_0_1_WhenGivenRange_0_1() throws Exception { Range<Long> newRange = new Range<>(0L, 1L); rangeContainer.add(newRange); assertEquals(3, rangeContainer.size()); assertEquals(newRange, rangeContainer.get(0)); } @Test public void intersect_ShouldChangeList_AsRange_8_9_WhenGivenRange_1_2_and_8_15() throws Exception { RangeContainer<Long, Range<Long>> givenRangeToIntersectList = new RangeContainer<>(); givenRangeToIntersectList.add(new Range<>(1L, 2L)); givenRangeToIntersectList.add(new Range<>(8L, 15L)); Range<Long> firstIndexRange = new Range<>(8L, 9L); RangeContainer<Long, Range<Long>> results = rangeContainer.intersect(givenRangeToIntersectList); assertEquals(1, results.size()); assertEquals(firstIndexRange, results.get(0)); } @Test public void intersect_ShouldChangeList_AsRange_23_and_68_WhenGivenRange_01_24_45_57_78_78_and_1011() throws Exception { RangeContainer<Long, Range<Long>> givenRangeToIntersectList = new RangeContainer<>(); givenRangeToIntersectList.add(new Range<>(0L, 1L)); givenRangeToIntersectList.add(new Range<>(2L, 4L)); givenRangeToIntersectList.add(new Range<>(4L, 5L)); givenRangeToIntersectList.add(new Range<>(5L, 7L)); givenRangeToIntersectList.add(new Range<>(7L, 8L)); givenRangeToIntersectList.add(new Range<>(7L, 8L)); givenRangeToIntersectList.add(new Range<>(10L, 11L)); Range<Long> firstIndexRange = new Range<>(2L, 3L); Range<Long> secondIndexRange = new Range<>(6L, 8L); RangeContainer<Long, Range<Long>> results = rangeContainer.intersect(givenRangeToIntersectList); assertEquals(2, results.size()); assertEquals(firstIndexRange, results.get(0)); assertEquals(secondIndexRange, results.get(1)); } }
true
802e36159ee26734e79ef7f498ff129caa37a770
Java
yulvyou/GooglePlay
/googlePlay2/src/main/java/holder/PictureHolder.java
UTF-8
5,004
2.125
2
[]
no_license
package holder; import java.util.List; import utils.BitmapHelper; import utils.UIUtils; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.support.v4.view.ViewPager.OnPageChangeListener; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.ImageView.ScaleType; import android.widget.LinearLayout; import base.BaseHolder; import com.example.googleplay2.R; import com.lidroid.xutils.ViewUtils; import com.lidroid.xutils.view.annotation.ViewInject; import conf.Constants.URLS; public class PictureHolder extends BaseHolder<List<String>> { @ViewInject(R.id.item_home_picture_pager) ViewPager mViewPager; //小点 @ViewInject(R.id.item_home_picture_container_indicator) LinearLayout mContainerIndicator; //图片名称数组 private List<String> mDatas; @Override public View initHolderView() { View view = View.inflate(UIUtils.getContext(), R.layout.item_home_picture, null); //注入找孩子 ViewUtils.inject(this,view); return view; } @SuppressWarnings("deprecation") @Override public void refreshHolderView(List<String> datas) { mDatas = datas; mViewPager.setAdapter(new PictureAdapter()); //添加小点 for(int i = 0 ; i<datas.size(); i++) { View indicatorView = new View(UIUtils.getContext()); indicatorView.setBackgroundResource(R.drawable.indicator_normal); //设置点的大小 LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(UIUtils.dipToPx(5),UIUtils.dipToPx(5)); //调整点之间的间距 //左边距 params.leftMargin = UIUtils.dipToPx(5); //下边距 params.bottomMargin = UIUtils.dipToPx(5); mContainerIndicator.addView(indicatorView,params); //默认选中效果 if(i==0){ indicatorView.setBackgroundResource(R.drawable.indicator_selected); } }//for //监听滑动事件 mViewPager.setOnPageChangeListener(new OnPageChangeListener() { @Override public void onPageSelected(int position) { position = position%mDatas.size();//为了循环轮播 for (int i = 0; i < mDatas.size(); i++) { //得到孩子 View indicatorView = mContainerIndicator.getChildAt(i); //还原背景 indicatorView.setBackgroundResource(R.drawable.indicator_normal); if(i==position) { indicatorView.setBackgroundResource(R.drawable.indicator_selected); } }//for }//onPageSelected @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { // TODO Auto-generated method stub } @Override public void onPageScrollStateChanged(int state) { // TODO Auto-generated method stub } }); //设置当前的Item为总数的一般count/2 int diff = Integer.MAX_VALUE/2%mDatas.size(); int index = Integer.MAX_VALUE/2; mViewPager.setCurrentItem(index - diff); //自动轮播 final AutoScrollTask autoScrollTask = new AutoScrollTask(); autoScrollTask.start(); //用户触摸的时候移除自动轮播的任务 mViewPager.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: autoScrollTask.stop(); break; case MotionEvent.ACTION_MOVE: break; case MotionEvent.ACTION_UP: autoScrollTask.start(); break; default: break; } return false; } }); }//refreshHolderView class PictureAdapter extends PagerAdapter{ @Override public int getCount() { if(mDatas != null) { return Integer.MAX_VALUE;//为了实现无限轮播修改成Integer.MAX_VALUE //return mDatas.size(); } return 0; } @Override public boolean isViewFromObject(View view, Object object) { return view==object; } @Override public Object instantiateItem(ViewGroup container, int position) { position = position % mDatas.size();//为了循环轮播 ImageView iv = new ImageView(UIUtils.getContext()); iv.setScaleType(ScaleType.FIT_XY); iv.setImageResource(R.drawable.ic_default); BitmapHelper.display(iv, URLS.IMAGEBASEURL+mDatas.get(position)); container.addView(iv); return iv; } @Override public void destroyItem(ViewGroup container, int position, Object object) { container.removeView((View) object); } }//Class.PictureAdapter /**自动轮播任务*/ class AutoScrollTask implements Runnable{ /**开始轮播*/ public void start() { UIUtils.postTaskDelay(this, 2000); } /**停止轮播*/ public void stop() { UIUtils.removeRask(this); } @Override public void run() { int item = mViewPager.getCurrentItem(); item++; mViewPager.setCurrentItem(item); //一轮任务执行完了之后再此开始任务,以实现无限轮播效果 start(); }//run }//Class.AutoScrollTask }//End
true
7ff535dbc0778b33556c4f3ad068dd116166b914
Java
dlchris/dew-common
/src/main/java/com/ecfront/dew/common/HttpHelperFactory.java
UTF-8
848
2.375
2
[ "Apache-2.0" ]
permissive
package com.ecfront.dew.common; public class HttpHelperFactory { static HttpHelper choose() { return choose(200, 20,-1,-1,true); } /** * @param maxTotal 整个连接池最大连接数 * @param maxPerRoute 每个路由(域)的默认最大连接 * @param defaultConnectTimeoutMS 默认连接超时时间 * @param defaultSocketTimeoutMS 默认读取超时时间 * @param retryAble 是否重试 */ static HttpHelper choose(int maxTotal, int maxPerRoute,int defaultConnectTimeoutMS,int defaultSocketTimeoutMS,boolean retryAble) { if (DependencyHelper.hasDependency("org.apache.http.impl.client.CloseableHttpClient")) { return new ApacheHttpHelper(maxTotal, maxPerRoute,defaultConnectTimeoutMS,defaultSocketTimeoutMS,retryAble); } return null; } }
true
5f46476faa281b3f72cf42379c1ca87c45396175
Java
mayurchakalasiya1990/Datastructure-algorithm
/Datastructure & Algo/src/com/dsf/StringProblem/CamelCaseSolution.java
UTF-8
502
3.109375
3
[]
no_license
package com.dsf.StringProblem; public class CamelCaseSolution { // Complete the camelcase function below. static int camelcase(String s) { int result=0; char[] words=s.toCharArray(); for (char c:words) { if(Character.isUpperCase(c)){ ++result; } } return ++result; } public static void main(String[] args) { String s="saveChangesInTheEditor"; System.out.println(camelcase(s)); } }
true
e13041772eb275109be87c2dfde47d7c386db6bb
Java
coops1106/MockitoDemo
/src/test/java/com/lv/demo/EloquentForgottenPasswordAdaptorTest.java
UTF-8
2,400
2.296875
2
[]
no_license
package com.lv.demo; import com.lv.elsewhere.CustomerCommunicationsService; import com.lv.elsewhere.OtherInformationService; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.*; @RunWith(MockitoJUnitRunner.class) public class EloquentForgottenPasswordAdaptorTest { private static final String STUB_EMAIL = "anakin.skywalker@lv.com"; private static final String STUB_LINK = "link"; public static final String INFO_LV_COM = "info@lv.com"; public static final String LV = "LV="; public static final String PASSWORD_RESET = "Password Reset"; public static final String LINK = "link"; public static final String EMAIL_TEXT = "You silly billy, you forgot your password, here's a link {}"; @InjectMocks ForgottenPasswordAdaptor uut; @Mock CustomerCommunicationsService customerCommunicationsService; @Mock OtherInformationService otherInformationService; @Captor //1 ArgumentCaptor<ForgottenPasswordRequest> argumentCaptor; //2 @Before public void setUp() { when(otherInformationService.getLvEmailAddress()).thenReturn(INFO_LV_COM); when(otherInformationService.getLvName()).thenReturn(LV); when(otherInformationService.getForgottenPasswordEmailSubject()).thenReturn(PASSWORD_RESET); String passwordResetText = String.format(EMAIL_TEXT, LINK); when(otherInformationService.getForgottenPasswordEmailText(anyString())).thenReturn(passwordResetText); } @Test public void testSendCommunication() { uut.sendCommunication(STUB_EMAIL, STUB_LINK); verify(customerCommunicationsService, times(1)).sendCustomerCommunication(argumentCaptor.capture()); ForgottenPasswordRequest forgottenPasswordRequest = argumentCaptor.getValue(); assertEquals(INFO_LV_COM, forgottenPasswordRequest.getFromAddress()); assertEquals(LV, forgottenPasswordRequest.getFromName()); assertEquals(PASSWORD_RESET, forgottenPasswordRequest.getSubject()); String passwordResetText = String.format(EMAIL_TEXT, LINK); assertEquals(passwordResetText, forgottenPasswordRequest.getText()); } }
true
76a31829ddfde42cde6d2e9254e35331435384da
Java
Pryanik88/glovo
/src/main/java/com/test/glovo/controller/ExchangeController.java
UTF-8
895
2.171875
2
[]
no_license
package com.test.glovo.controller; import com.test.glovo.service.ExchangeService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.io.IOException; import java.math.BigDecimal; import java.util.List; import java.util.Map; @RestController @RequestMapping("/products") public class ExchangeController { private final ExchangeService service; @Autowired public ExchangeController(ExchangeService service) { this.service = service; } @GetMapping @CrossOrigin(origins = "http://localhost:8088") public List<String> getProducts() throws IOException { return service.getProducts(); } @GetMapping("/{productId}/prices") public Map<String,BigDecimal> getPrice(@PathVariable String productId) throws IOException { return service.getPrices(productId); } }
true
6f002c7c9bd6e57e684ad8fabeef7809d5d7dc5e
Java
sevensource/seven-commons
/seven-commons-web/src/main/java/org/sevensource/commons/web/filter/AbstractOutputBufferingFilter.java
UTF-8
5,106
2.421875
2
[]
no_license
package org.sevensource.commons.web.filter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.sevensource.commons.web.servlet.BufferingHttpResponseWrapper; /** * Base class for ServletFilters, that wish to buffer and optionally change the * response sent to the client * * @author pgaschuetz * */ public abstract class AbstractOutputBufferingFilter implements Filter { private static final String ALREADY_FILTERED_SUFFIX = ".FILTERED"; private FilterConfig filterConfig; private String filterName; private boolean filterOncePerRequest = true; private boolean addContentLengthHeader = true; @Override public void init(FilterConfig filterConfig) throws ServletException { this.filterConfig = filterConfig; this.filterName = this.filterConfig != null ? this.filterConfig.getFilterName() : null; if (this.filterName == null) { this.filterName = getClass().getName(); } } @Override public void destroy() { this.filterConfig = null; } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (!(request instanceof HttpServletRequest) || !(response instanceof HttpServletResponse)) { throw new ServletException(String.format("%s only supports HTTP requests", getClass().getName())); } final HttpServletRequest httpRequest = (HttpServletRequest) request; final HttpServletResponse httpResponse = (HttpServletResponse) response; boolean alreadyFiltered = false; String alreadyFilteredAttributeName = null; if(filterOncePerRequest) { alreadyFilteredAttributeName = getAlreadyFilteredAttributeName(); alreadyFiltered = httpRequest.getAttribute(alreadyFilteredAttributeName) != null; } if (alreadyFiltered || skipExecution(httpRequest, httpResponse)) { // Proceed without invoking this filter... chain.doFilter(request, response); } else { // Do invoke this filter... if(filterOncePerRequest) { httpRequest.setAttribute(alreadyFilteredAttributeName, Boolean.TRUE); } try { final BufferingHttpResponseWrapper responseWrapper = new BufferingHttpResponseWrapper(httpResponse); chain.doFilter(httpRequest, responseWrapper); afterDoFilter(httpRequest, httpResponse, responseWrapper); } finally { // Remove the "already filtered" request attribute for this request. if(filterOncePerRequest) { request.removeAttribute(alreadyFilteredAttributeName); } } } } private void afterDoFilter(HttpServletRequest request, HttpServletResponse response, BufferingHttpResponseWrapper responseWrapper) throws IOException { responseWrapper.flushBuffer(); if(skipHandleResponse(request, responseWrapper)) { writeContentLengthHeader(response, responseWrapper.getBufferSize()); responseWrapper.writeBufferTo(response.getOutputStream()); } else { final InputStream handledResponseInputStream = handleResponse(request, responseWrapper); writeContentLengthHeader(response, responseWrapper.getBufferSize()); final OutputStream os = response.getOutputStream(); final byte[] buffer = new byte[4096]; int n; while (-1 != (n = handledResponseInputStream.read(buffer))) { os.write(buffer, 0, n); } } response.flushBuffer(); } protected String getFilterName() { return filterName; } protected String getAlreadyFilteredAttributeName() { return getFilterName() + ALREADY_FILTERED_SUFFIX; } private void writeContentLengthHeader(HttpServletResponse response, int contentLength) { if(addContentLengthHeader) { response.setContentLength(contentLength); } } /** * Should the execution of this filter be skipped? * * @param request * @param response * @return If true, the request is handed down the chain as usual. */ protected abstract boolean skipExecution(HttpServletRequest request, HttpServletResponse response); /** * Should handling of the response be skipped? * This method is called <b>after</b> the request has been handled by the filter chain * * @param request * @param response * @return if true, the response is immediately committed to the underlying response */ protected abstract boolean skipHandleResponse(HttpServletRequest request, BufferingHttpResponseWrapper response); /** * handle the response, optionally do something with it and return the InputStream which * shall be written to the underlying response * * @param request * @param response * @return the new response, that should be written to the underlying {@link HttpServletResponse} * @throws IOException */ protected abstract InputStream handleResponse(HttpServletRequest request, BufferingHttpResponseWrapper response) throws IOException; }
true
1d32b86790ad383d336b5c56e0950e0a83a36217
Java
estgo201/TheLoopInterview
/src/test/java/Tests/SignUpTests.java
UTF-8
5,009
2.09375
2
[]
no_license
package Tests; import java.io.File; import java.util.Scanner; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.StaleElementReferenceException; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; public class SignUpTests { private WebDriver driver; private Scanner scanner; private static JavascriptExecutor js; @Before public void setUp() { scanner = new Scanner(System.in); // src/test/resources/driver경로에 위치한 chromedriver 설정 File resourcesDirectory = new File("src/test/resources/driver"); System.setProperty("webdriver.chrome.driver", resourcesDirectory + "/chromedriver"); driver = new ChromeDriver(); js = (JavascriptExecutor) driver; // Web Driver를 JavascriptExecutor로 캐스팅 } @After public void tearDown() { driver.quit(); } /* * 계정 이름을 입력받아서 twitter.com에서 그에 해당하는 새 계정을 만드는 테스트 자동화 코드를 작성하세요. */ @Test public void test() { // step1. twitter에 새 계정 만들기 String baseUrl = "https://twitter.com/signup"; driver.get(baseUrl); String inputValue; WebDriverWait wait = new WebDriverWait(driver, 10); wait.until(ExpectedConditions.presenceOfElementLocated(By.name("name"))); // step2. user에게 이름, 전화번호를 입력받아 form에 입력 retryingFindClick(By.name("name")); inputValue = requestInputfromUser("이름"); driver.findElement(By.name("name")).sendKeys(inputValue); inputValue = requestInputfromUser("전화번호"); driver.findElement(By.name("phone_number")).sendKeys(inputValue); By nextXPath = By.xpath("//div[contains(@class,'rn-1oszu61 rn-urgr8i rn-1c1gj4h rn-114ovsg rn-oucylx rn-855088 rn-1bxrh7q rn-waaub4 rn-sqtsar rn-qb5c1y rn-1efd50x rn-14skgim rn-rull8r rn-mm0ijv rn-5kkj8d rn-13l2t4g rn-qklmqi rn-1ljd8xs rn-deolkf rn-1loqt21 rn-6koalj rn-1qe8dj5 rn-1mlwlqe rn-eqz5dr rn-1w2pmg rn-1mnahxq rn-61z16t rn-p1pxzi rn-11wrixw rn-1eg1yxq rn-qb0742 rn-wk8lta rn-1pl8ijs rn-1mdbw0j rn-1wx0zj rn-bnwqim rn-o7ynqc rn-zca6y rn-lrvibr rn-1lgpqti')]"); By registerXPath = By.xpath("//div[contains(@class,'rn-1oszu61 rn-urgr8i rn-1c1gj4h rn-114ovsg rn-oucylx rn-855088 rn-1bxrh7q rn-waaub4 rn-sqtsar rn-qb5c1y rn-1efd50x rn-14skgim rn-rull8r rn-mm0ijv rn-5kkj8d rn-13l2t4g rn-qklmqi rn-1ljd8xs rn-deolkf rn-1loqt21 rn-6koalj rn-1qe8dj5 rn-1mlwlqe rn-eqz5dr rn-1w2pmg rn-61z16t rn-p1pxzi rn-11wrixw rn-m9gq36 rn-it97yl rn-1f3jsut rn-wk8lta rn-1pl8ijs rn-1mdbw0j rn-1wx0zj rn-bnwqim rn-o7ynqc rn-zca6y rn-lrvibr rn-1lgpqti')]"); By confirmXPath = By.xpath("//div[contains(@class,'rn-1oszu61 rn-urgr8i rn-1c1gj4h rn-114ovsg rn-oucylx rn-855088 rn-1bxrh7q rn-waaub4 rn-sqtsar rn-qb5c1y rn-1efd50x rn-14skgim rn-rull8r rn-mm0ijv rn-5kkj8d rn-13l2t4g rn-qklmqi rn-1ljd8xs rn-deolkf rn-1loqt21 rn-6koalj rn-1qe8dj5 rn-1mlwlqe rn-eqz5dr rn-1w2pmg rn-61z16t rn-p1pxzi rn-11wrixw rn-8rf56t rn-it97yl rn-1f3jsut rn-wk8lta rn-1pl8ijs rn-1mdbw0j rn-1wx0zj rn-bnwqim rn-o7ynqc rn-zca6y rn-lrvibr rn-1lgpqti')]"); // step3. 입력받은 정보로 가입시작 waitUntilClickableAndClick(nextXPath); waitUntilClickableAndClick(registerXPath); waitUntilClickableAndClick(confirmXPath); // stpe4. 인증번호 입력요청 후 click inputValue = requestInputfromUser("확인코드"); driver.findElement(By.xpath("//*[@id=\"react-root\"]/div[2]/div/div/div/div[2]/div[2]/div/div/div[2]/div[2]/div/div/div/div[3]/div/div/input")).sendKeys(inputValue); waitUntilClickableAndClick(nextXPath); // step5. 비밀번호 입력요청 후 click inputValue = requestInputfromUser("비밀번호(6자리)"); driver.findElement(By.name("password")).sendKeys(inputValue); waitUntilClickableAndClick(nextXPath); } private String requestInputfromUser(String askTitle) { System.out.print(askTitle + " : "); String inputValue = scanner.nextLine(); System.out.println(inputValue); return inputValue; } private void waitUntilClickableAndClick(By by) { WebDriverWait wait = new WebDriverWait(driver, 10); WebElement element = wait.until(ExpectedConditions.elementToBeClickable(by)); element.click(); } private boolean retryingFindClick(By by) { boolean result = false; int attempts = 0; while(attempts < 2) { try { driver.findElement(by).click(); result = true; break; } catch(StaleElementReferenceException e) { System.out.println("StaleElementReferenceException occurred attempts count : " + attempts); } attempts++; } return result; } }
true
aed4dfebf5eafa98c6c378a79316a1311975150b
Java
RayCiel/Compiler
/src/com/AST/BlockNode.java
UTF-8
1,082
2.796875
3
[]
no_license
package com.AST; import com.FrontEnd.ASTVisitor; import com.Entity.*; import java.util.List; import java.util.LinkedList; public class BlockNode extends StatementNode { protected List<StatementNode> stmts; protected Scope scope; public BlockNode(Location _location, List<StatementNode> _stmts) { super(_location); this.stmts = _stmts; } public static BlockNode wrapBlock(StatementNode _stmtNode) { if (_stmtNode == null) return null; if (_stmtNode instanceof BlockNode) { return (BlockNode) _stmtNode; } else { return new BlockNode(_stmtNode.getLocation(), new LinkedList<StatementNode>() {{add(_stmtNode);}}); } } public void setScope(Scope scope) { this.scope = scope; } public List<StatementNode> getStmts() { return stmts; } public Scope getScope() { return scope; } @Override public <S, E> S accept(ASTVisitor<S, E> visitor) { return visitor.visit(this); } }
true
11662892f49bfe99204fdc6575e6a8c8da5f4de5
Java
DanielDimitrovD/OOPJava
/server/src/serverRMIDefinitions/ServerObjectInterfaceImplementation.java
UTF-8
4,323
2.71875
3
[]
no_license
package serverRMIDefinitions; import DatabaseConnector.DatabaseAPI; import filesOperations.BankCardByCardNumberStream; import filesOperations.BankCardByEncryptionStream; import filesOperations.XMLSerialization; import CypherForEncryption.SubstitutionCard; import userPackage.Privileges; import userPackage.User; import userPackage.Users; import Utilities.Utils; import java.io.File; import java.io.IOException; import java.rmi.RemoteException; import java.rmi.registry.Registry; import java.rmi.server.UnicastRemoteObject; import java.sql.SQLException; import java.util.*; // implementation of the RMI service interface public class ServerObjectInterfaceImplementation extends UnicastRemoteObject implements ServerObjectInterface { private static final int INITIAL_OFFSET = 5; // initial offset for the Cipher private Registry registry; // reference to the object private Map<String, User> userCredentials; // store username and password private XMLSerialization xmlSerialization; // used for reading and writing to XML configuration file private String pathToCredentialsFile; // path to XML file with information about users private TreeMap<String,String> encryptions; // pair ( encryption number) -> ( bank account number) private BankCardByCardNumberStream streamByCard; // used for I/O operations with data sorted by card number private BankCardByEncryptionStream streamByEncryption; // used for I/O operations with data sorted by encryption number private StringBuilder sb; // string builder for manipulation of strings // UPDATE private DatabaseAPI databaseConnection; private SubstitutionCard substitutionCard; private boolean isEmpty; public ServerObjectInterfaceImplementation() throws RemoteException, IOException { streamByCard = new BankCardByCardNumberStream(); // initialize I/O for data sorted by card number streamByEncryption = new BankCardByEncryptionStream(); // initialize I/O for data sorted by encryption number xmlSerialization = new XMLSerialization( pathToCredentialsFile); // initialize xml I/O instance encryptions = new TreeMap<>(); // initialize treeMap // UPDATE databaseConnection = new DatabaseAPI(); substitutionCard = new SubstitutionCard(INITIAL_OFFSET); } @Override public String encryptCardNumber(String username, String cardNumber) throws RemoteException, SQLException { String encryptedCardNumber = substitutionCard.encrypt(cardNumber); if(databaseConnection.insertCardNumberEncryptionInDatabase(username,cardNumber,encryptedCardNumber)) return encryptedCardNumber; else return "User already encrypted this credit card number"; } // decryption of card Number @Override public final String decryptCardNumber(String username, String encryptionNumber) throws RemoteException, SQLException { String result = ""; Privileges privilege = databaseConnection.getUserPrivilegesFromDatabase(username); if (privilege.equals(Privileges.GUEST)) // user doesn't have privileges for decryption method { result = "No permissions for decryption functionality"; return result; // return decrypted card number } return databaseConnection.getCardNumberByEncryptionNumberFromDatabase(username,encryptionNumber); } // validate if a client can continue to the main client functionality @Override public final boolean validateUser(String username, String password) throws RemoteException { try { if(databaseConnection.validateUserLogin(username, password)) return true; else return false; } catch (SQLException e) { e.printStackTrace(); } return false; } // add account to database @Override public final boolean addUser(String username, String password, Privileges privileges) throws RemoteException { try { if(databaseConnection.addUserInDatabase(username, password, privileges)) return true; else return false; } catch (SQLException e) { e.printStackTrace(); } return false; } // method addUser end } // class end
true
a3cb40d6c695f96b1adb8347e7f61ae877855b83
Java
SaloniBhalerao/Enterprise_Sw_Platforms
/Karaf/Final/src/main/java/api/Target.java
UTF-8
1,456
2.21875
2
[]
no_license
package api; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class Target { @SerializedName("id_str") @Expose private String idStr; @SerializedName("id") @Expose private Integer id; @SerializedName("screen_name") @Expose private String screenName; @SerializedName("following") @Expose private Boolean following; @SerializedName("followed_by") @Expose private Boolean followedBy; public String getIdStr() { return idStr; } public void setIdStr(String idStr) { this.idStr = idStr; } public Target withIdStr(String idStr) { this.idStr = idStr; return this; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Target withId(Integer id) { this.id = id; return this; } public String getScreenName() { return screenName; } public void setScreenName(String screenName) { this.screenName = screenName; } public Target withScreenName(String screenName) { this.screenName = screenName; return this; } public Boolean getFollowing() { return following; } public void setFollowing(Boolean following) { this.following = following; } public Target withFollowing(Boolean following) { this.following = following; return this; } public Boolean getFollowedBy() { return followedBy; } public void setFollowedBy(Boolean followedBy) { this.followedBy = followedBy; } public Target withFollowedBy(Boolean followedBy) { this.followedBy = followedBy; return this; } }
true
d3b9bfdb85dec8fc600e1677208574e1dfad9455
Java
muthumkp13/RoverServices
/src/main/java/com/rover/input/request/PatchEnvironmentRequest.java
UTF-8
639
1.929688
2
[]
no_license
package com.rover.input.request; import java.util.List; import com.fasterxml.jackson.annotation.JsonProperty; import com.rover.domain.EnvironmentDomain; import com.rover.model.TerrainType; import lombok.Data; @Data public class PatchEnvironmentRequest { long temperature; long humidity; @JsonProperty("solar-flare") boolean solarFlare; boolean storm; List<List<TerrainType>> areaMap; public EnvironmentDomain toDomain() { return new EnvironmentDomain() .setAreaMap(areaMap) .setHumidity(humidity) .setSolarFlare(solarFlare) .setStorm(storm) .setTemperature(temperature); } }
true
445aea7f8ce24bcf5af449e52f2bca568ac8dae1
Java
lsp10/SimpleRecommderSystem
/collaborativeFiltering/implement/recommeder/UserBasedCFRecommender.java
UTF-8
2,510
2.328125
2
[]
no_license
package collaborativeFiltering.implement.recommeder; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Map.Entry; import collaborativeFiltering.model.Model; import collaborativeFiltering.neighbor.UserNeighborhood; import collaborativeFiltering.recommender.UserBasedCFRecommend; import collaborativeFiltering.similarity.SimilarityMatrix; public class UserBasedCFRecommender implements UserBasedCFRecommend { private List<Integer> itemList; private HashMap<Integer,Double> predict; @Override public List<Integer> getItemReco(int uid, int itemNum,int neiNum, Model m, SimilarityMatrix sm, UserNeighborhood un) throws Exception { // TODO Auto-generated method stub Map<Integer,HashMap<Integer,Double>> prefModel = m.getPrefMap(); Set<Integer> itemSet = m.getItemSet(); List<Integer> neiList = un.getNeiFullMatrix(uid, neiNum, sm.getFullMatrix());//calcu HashMap<Integer,Double> myPref = prefModel.get(uid); HashMap<Integer,Double> mySim = sm.getFullMatrix().get(uid); HashMap<Integer,Double> neiPref = null; this.predict = new HashMap<Integer,Double>();//store prediction this.itemList = new ArrayList<Integer>(); // System.out.println(neiList); for(Integer item: itemSet){ if(myPref.containsKey(item)) continue; double simSum = 0.0; double rankingSum = 0.0; for(Integer nei: neiList){ neiPref = prefModel.get(nei); if(neiPref.containsKey(item)){ simSum += mySim.get(nei); rankingSum += neiPref.get(item) * mySim.get(nei); } } if(simSum > 0) this.predict.put(item, rankingSum/simSum); // System.out.println(item+"-"+rankingSum/simSum); } //form the recommend item list List<Map.Entry<Integer, Double>> hashToList = new ArrayList<Map.Entry<Integer, Double>>(this.predict.entrySet()); Collections.sort(hashToList,new Comparator<Map.Entry<Integer,Double>>(){ @Override public int compare(Entry<Integer, Double> o1, Entry<Integer, Double> o2) { // TODO Auto-generated method stub if(o1.getValue() > o2.getValue()) return -1; return 1; } }); for(int i=0;i<hashToList.size()&&i<itemNum;i++){ this.itemList.add(hashToList.get(i).getKey()); } // for(int j=0;j<hashToList.size();j++){ // System.out.println(uid+"-"+hashToList.get(j).getKey() // +"="+hashToList.get(j).getValue()); // } return this.itemList; } }
true
452933154a6d080a8f89afc1dc8236630b87f6a5
Java
mksmanjit/Java-Practice
/Threading/src/foo/BusyWaitDemo.java
UTF-8
1,112
3.578125
4
[]
no_license
package foo; public class BusyWaitDemo { public static void main(String[] args) { // TODO Auto-generated method stub MySignal m =new MySignal(); BusyWaitRunnable busy = new BusyWaitRunnable(m); Thread t1 = new Thread(busy); t1.setName("Start"); Thread t2 = new Thread(busy); t2.setName("Second"); t1.start(); t2.start(); } } class BusyWaitRunnable implements Runnable{ MySignal m = null; public void run(){ if(Thread.currentThread().getName().equals("Start")){ try { Thread.sleep(2000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } m.setSharedSignal(true); } else{ /** * This is Busy Waiting as Thread is continously busy in checking the status . */ while(!m.isSharedSignal()){ System.out.println("Hello"); } } } public BusyWaitRunnable(MySignal m){ this.m = m; } } class MySignal{ private boolean sharedSignal = false; public boolean isSharedSignal() { return sharedSignal; } public void setSharedSignal(boolean sharedSignal) { this.sharedSignal = sharedSignal; } }
true
2534cd88daf975dd1b06af3b50e1862327650d2a
Java
jleun1403/BOJ_JAVA
/src/BOJ/Q6593.java
UTF-8
2,027
3.109375
3
[]
no_license
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.LinkedList; import java.util.Queue; import java.util.StringTokenizer; public class Q6593 { static int dx[] = { 1, -1, 0, 0, 0, 0 }, dy[] = { 0, 0, 0, 0, 1, -1 }, dz[] = { 0, 0, 1, -1, 0, 0 }; static class Position { int x, y, z; public Position(int x, int y, int z) { this.x = x; this.y = y; this.z = z; } } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); while (true) { StringTokenizer st = new StringTokenizer(br.readLine()); int k = Integer.parseInt(st.nextToken()); int n = Integer.parseInt(st.nextToken()); int m = Integer.parseInt(st.nextToken()); if (k == 0 && n == 0 && m == 0) break; int sx = 0, sy = 0, sz = 0; int ex = 0, ey = 0, ez = 0; char arr[][][] = new char[n][m][k]; int d[][][] = new int[n][m][k]; for (int l = 0; l < k; l++) { for (int i = 0; i < n; i++) { String s = br.readLine(); for (int j = 0; j < m; j++) { arr[i][j][l] =s.charAt(j); if (arr[i][j][l] == 'S') { sx = i; sy = j; sz = l; } else if (arr[i][j][l] == 'E') { ex = i; ey = j; ez = l; } } } br.readLine(); } Queue<Position> q = new LinkedList<>(); q.add(new Position(sx,sy,sz)); d[sx][sy][sz] = 1; while(!q.isEmpty()) { Position p = q.poll(); int x = p.x; int y = p.y; int z = p.z; for(int i=0; i<6; i++) { int nx = x + dx[i]; int ny = y + dy[i]; int nz = z + dz[i]; if(nx>=0 && nx<n && ny>=0 && ny<m && nz>=0 && nz<k &&d[nx][ny][nz] ==0) { if(arr[nx][ny][nz] !='#') { d[nx][ny][nz] = d[x][y][z] +1; q.add(new Position(nx,ny,nz)); } } } } if(d[ex][ey][ez]==0) { System.out.println("Trapped!"); } else { System.out.println("Escaped in "+(d[ex][ey][ez]-1)+" minute(s)."); } } } }
true
327e6dd61066e8be5a9d69c9dcb50f22398dd82d
Java
asakusafw/asakusafw-shafu
/com.asakusafw.shafu.ui/src/com/asakusafw/shafu/internal/ui/preferences/ShafuPreferencePage.java
UTF-8
25,389
1.585938
2
[ "Apache-2.0" ]
permissive
/** * Copyright 2013-2021 Asakusa Framework Team. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.asakusafw.shafu.internal.ui.preferences; import static com.asakusafw.shafu.internal.ui.preferences.ShafuPreferenceConstants.*; import static com.asakusafw.shafu.ui.util.PreferenceUtils.*; import java.io.File; import java.text.MessageFormat; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.jface.layout.GridDataFactory; import org.eclipse.jface.viewers.DoubleClickEvent; import org.eclipse.jface.viewers.IDoubleClickListener; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.IStructuredContentProvider; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.ITableLabelProvider; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.window.Window; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.DirectoryDialog; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.TabFolder; import org.eclipse.swt.widgets.TabItem; import org.eclipse.swt.widgets.TableColumn; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPreferencePage; import com.asakusafw.shafu.internal.ui.Activator; import com.asakusafw.shafu.internal.ui.LogUtil; import com.asakusafw.shafu.internal.ui.dialogs.PropertyEntryInputDialog; import com.asakusafw.shafu.ui.fields.BasicField; import com.asakusafw.shafu.ui.fields.FieldPreferencePage; import com.asakusafw.shafu.ui.fields.PreferenceField; /** * A root preference page for Shafu. */ public class ShafuPreferencePage extends FieldPreferencePage implements IWorkbenchPreferencePage { @Override public void init(IWorkbench workbench) { setPreferenceStore(Activator.getDefault().getPreferenceStore()); } @Override protected Control createContents(Composite parent) { TabFolder folder = new TabFolder(parent, SWT.NONE); folder.setLayoutData(GridDataFactory.fillDefaults() .grab(true, true) .create()); Composite basicTab = new Composite(folder, SWT.NONE); createBasicTab(basicTab); Composite projectTab = new Composite(folder, SWT.NONE); createProjectTab(projectTab); Composite jvmTab = new Composite(folder, SWT.NONE); createJvmTab(jvmTab); createTabItem(folder, basicTab, Messages.ShafuPreferencePage_tabBasic); createTabItem(folder, projectTab, Messages.ShafuPreferencePage_tabProject); createTabItem(folder, jvmTab, Messages.ShafuPreferencePage_tabJvm); applyDialogFont(folder); return folder; } private void createBasicTab(Composite pane) { pane.setLayout(new GridLayout(1, false)); Group loggingGroup = new Group(pane, SWT.NONE); loggingGroup.setText(Messages.ShafuPreferencePage_groupLogging); loggingGroup.setLayoutData(GridDataFactory.swtDefaults() .align(SWT.FILL, SWT.BEGINNING) .grab(true, false) .create()); loggingGroup.setLayout(new GridLayout(2, false)); createComboField(loggingGroup, KEY_LOG_LEVEL, GradleLogLevel.values(), Messages.ShafuPreferencePage_itemLogLevel); createComboField(loggingGroup, KEY_STACK_TRACE, GradleStackTrace.values(), Messages.ShafuPreferencePage_itemStackTrace); Group environmentGroup = new Group(pane, SWT.NONE); environmentGroup.setText(Messages.ShafuPreferencePage_groupEnvironment); environmentGroup.setLayoutData(GridDataFactory.swtDefaults() .align(SWT.FILL, SWT.BEGINNING) .grab(true, false) .create()); environmentGroup.setLayout(new GridLayout(2, false)); createVersionField(environmentGroup, KEY_GRADLE_VERSION, Messages.ShafuPreferencePage_itemGradleVersion, 10, false); createComboField(environmentGroup, KEY_NETWORK_MODE, GradleNetworkMode.values(), Messages.ShafuPreferencePage_itemNetworkMode); createDirectoryField(environmentGroup, KEY_GRADLE_USER_HOME, 2, Messages.ShafuPreferencePage_itemGradleUserHome, false); Group wrapperGroup = new Group(pane, SWT.NONE); wrapperGroup.setText(Messages.ShafuPreferencePage_groupWrapper); wrapperGroup.setLayoutData(GridDataFactory.swtDefaults() .align(SWT.FILL, SWT.BEGINNING) .grab(true, false) .create()); wrapperGroup.setLayout(new GridLayout(2, false)); createCheckboxField(wrapperGroup, KEY_USE_WRAPPER_CONFIGURATION, 2, Messages.ShafuPreferencePage_itemUseWrapperConfiguration); createCommaListField(wrapperGroup, KEY_WRAPPER_CONFIGURATION_PATHS, 2, Messages.ShafuPreferencePage_itemWrapperConfigurationPaths, Messages.ShafuPreferencePage_hintWrapperConfigurationPaths); } private void createProjectTab(Composite pane) { pane.setLayout(new GridLayout(1, false)); createPropertiesField(pane, KEY_PROJECT_PROPERTIES, 1, Messages.ShafuPreferencePage_itemProjectProperties); } private void createJvmTab(Composite pane) { pane.setLayout(new GridLayout(1, false)); createDirectoryField(pane, KEY_JAVA_HOME, 1, Messages.ShafuPreferencePage_itemJavaHome, false); createCheckboxField(pane, KEY_USE_PROJECT_JAVA_HOME, 1, Messages.ShafuPreferencePage_itemUseProjectJavaHome); createPropertiesField(pane, KEY_SYSTEM_PROPERTIES, 1, Messages.ShafuPreferencePage_itemSystemProperties); createPropertiesField(pane, KEY_ENVIRONMENT_VARIABLES, 1, Messages.ShafuPreferencePage_itemEnvironmentVariables); } private void createTabItem(TabFolder folder, Composite content, String label) { TabItem item = new TabItem(folder, SWT.NONE); item.setText(label); item.setControl(content); } private void createVersionField( Composite pane, final String key, String title, int columns, final boolean mandatory) { Label label = new Label(pane, SWT.NONE); label.setText(title + ':'); label.setLayoutData(GridDataFactory.swtDefaults() .align(SWT.FILL, SWT.CENTER) .indent(BasicField.getDecorationWidth(), 0) .create()); final Text text = new Text(pane, SWT.BORDER); text.setLayoutData(GridDataFactory.swtDefaults() .align(SWT.BEGINNING, SWT.CENTER) .indent(convertWidthInCharsToPixels(2) + BasicField.getDecorationWidth(), 0) .hint(convertWidthInCharsToPixels(columns + 1), SWT.DEFAULT) .create()); registerField(new PreferenceField(key, text) { @Override public void refresh() { String current = getPreferenceValue(key); String value = decodeVersion(current); value = value == null ? "" : value; //$NON-NLS-1$ text.setText(value); } @Override protected IStatus getDefaultStatus() { if (mandatory) { return Status.OK_STATUS; } else { return new Status( IStatus.INFO, Activator.PLUGIN_ID, Messages.ShafuPreferencePage_hintOptionalText); } } }); text.addListener(SWT.Modify, new Listener() { @Override public void handleEvent(Event event) { setPreferenceValue(key, encodeVersion(text.getText())); } }); } private void createComboField(Composite pane, final String key, GradleOption[] options, String title) { Label label = new Label(pane, SWT.NONE); label.setText(title + ':'); label.setLayoutData(GridDataFactory.swtDefaults() .align(SWT.FILL, SWT.CENTER) .indent(BasicField.getDecorationWidth(), 0) .create()); final Combo combo = new Combo(pane, SWT.DROP_DOWN | SWT.READ_ONLY); combo.setLayoutData(GridDataFactory.swtDefaults() .align(SWT.BEGINNING, SWT.CENTER) .indent(convertWidthInCharsToPixels(2) + BasicField.getDecorationWidth(), 0) .create()); final List<String> itemLabels = new ArrayList<>(options.length); final List<String> itemValues = new ArrayList<>(options.length); for (GradleOption option : options) { itemLabels.add(option.getDescription()); itemValues.add(option.name()); } combo.setItems(itemLabels.toArray(new String[itemLabels.size()])); registerField(new PreferenceField(key, combo) { @Override public void refresh() { String current = getPreferenceValue(key); int index = itemValues.indexOf(current); if (index < 0) { index = 0; } combo.select(index); } }); combo.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { String itemLabel = combo.getText(); int index = itemLabels.indexOf(itemLabel); if (index < 0) { LogUtil.log(new Status( IStatus.WARNING, Activator.PLUGIN_ID, MessageFormat.format( "[INTERNAL] Missing option value: {0}", //$NON-NLS-1$ itemLabel))); setPreferenceValue(key, null); } else { setPreferenceValue(key, itemValues.get(index)); } } }); } private void createDirectoryField( Composite pane, final String key, int span, final String title, final boolean mandatory) { Composite fieldPane = new Composite(pane, span); fieldPane.setLayoutData(GridDataFactory.swtDefaults() .align(SWT.FILL, SWT.BEGINNING) .span(span, 1) .grab(true, false) .create()); GridLayout layout = new GridLayout(2, false); layout.marginHeight = 0; layout.marginWidth = 0; layout.verticalSpacing = 0; fieldPane.setLayout(layout); Label fieldLabel = new Label(fieldPane, SWT.NONE); fieldLabel.setText(title + ':'); fieldLabel.setLayoutData(GridDataFactory.swtDefaults() .align(SWT.BEGINNING, SWT.END) .span(2, 1) .indent(BasicField.getDecorationWidth(), 0) .create()); final Text fieldText = new Text(fieldPane, SWT.BORDER); fieldText.setLayoutData(GridDataFactory.swtDefaults() .align(SWT.FILL, SWT.CENTER) .grab(true, false) .indent(BasicField.getDecorationWidth(), 0) .create()); Button fieldButton = new Button(fieldPane, SWT.PUSH); fieldButton.setText(Messages.ShafuPreferencePage_buttonDirectorySelection); fieldButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { DirectoryDialog dialog = new DirectoryDialog(getShell()); dialog.setText(Messages.ShafuPreferencePage_dialogDirectorySelection); String current = fieldText.getText(); if (current.isEmpty() == false) { dialog.setFilterPath(current); } String result = dialog.open(); if (result != null) { fieldText.setText(result); } } }); registerField(new PreferenceField(key, fieldText) { @Override public void refresh() { String current = getPreferenceValue(key); fieldText.setText(current); } @Override protected IStatus getDefaultStatus() { if (mandatory) { return Status.OK_STATUS; } else { return new Status( IStatus.INFO, Activator.PLUGIN_ID, Messages.ShafuPreferencePage_hintOptionalText); } } }); fieldText.addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent e) { String value = fieldText.getText(); if (value.isEmpty()) { if (mandatory) { setError(key, MessageFormat.format( Messages.ShafuPreferencePage_errorDirectoryEmpty, title)); } else { setPreferenceValue(key, value); } return; } File file = new File(value); if (file.isDirectory() == false) { setError(key, MessageFormat.format( Messages.ShafuPreferencePage_errorDirectoryMissing, title)); return; } setPreferenceValue(key, value); } }); } private void createPropertiesField( Composite pane, final String key, int span, String title) { Group group = new Group(pane, SWT.NONE); group.setText(title); group.setLayoutData(GridDataFactory.swtDefaults() .align(SWT.FILL, SWT.FILL) .grab(true, true) .span(span, 1) .create()); group.setLayout(new GridLayout(2, false)); final Map<String, String> contents = new LinkedHashMap<>(); final TableViewer viewer = new TableViewer( group, SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER | SWT.FULL_SELECTION); viewer.getControl().setLayoutData(GridDataFactory.fillDefaults() .grab(true, true) .span(1, 3) .indent(BasicField.getDecorationWidth(), 0) .create()); viewer.setContentProvider(new PropertiesContentProvider()); viewer.setLabelProvider(new PropertiesLabelProvider()); viewer.setInput(contents); viewer.getTable().setLinesVisible(true); viewer.getTable().setHeaderVisible(true); TableColumn keyColumn = new TableColumn(viewer.getTable(), SWT.NONE, 0); keyColumn.setResizable(true); keyColumn.setText(Messages.ShafuPreferencePage_propertiesKeyLabel); keyColumn.setWidth(convertWidthInCharsToPixels(20)); TableColumn valueColumn = new TableColumn(viewer.getTable(), SWT.NONE, 1); valueColumn.setResizable(true); valueColumn.setText(Messages.ShafuPreferencePage_propertiesValueLabel); valueColumn.setWidth(convertWidthInCharsToPixels(40)); viewer.addDoubleClickListener(new IDoubleClickListener() { @Override public void doubleClick(DoubleClickEvent event) { ISelection s = event.getSelection(); if (s.isEmpty()) { return; } if ((s instanceof IStructuredSelection) == false) { return; } Map.Entry<?, ?> first = (Map.Entry<?, ?>) ((IStructuredSelection) s).iterator().next(); String oldKey = (String) first.getKey(); String oldValue = (String) first.getValue(); PropertyEntryInputDialog dialog = new PropertyEntryInputDialog(getShell(), contents, oldKey, oldValue); if (dialog.open() != Window.OK) { return; } contents.remove(oldKey); contents.put(dialog.getInputKey(), dialog.getInputValue()); viewer.refresh(); setPreferenceValue(key, encodeMap(contents)); } }); final Button addButton = new Button(group, SWT.PUSH); addButton.setText(Messages.ShafuPreferencePage_propertiesAddLabel); addButton.setLayoutData(GridDataFactory.swtDefaults() .align(SWT.FILL, SWT.BEGINNING) .create()); addButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { PropertyEntryInputDialog dialog = new PropertyEntryInputDialog(getShell(), contents); if (dialog.open() != Window.OK) { return; } contents.put(dialog.getInputKey(), dialog.getInputValue()); viewer.refresh(); setPreferenceValue(key, encodeMap(contents)); } }); final Button removeButton = new Button(group, SWT.PUSH); removeButton.setText(Messages.ShafuPreferencePage_propertiesRemoveLabel); removeButton.setLayoutData(GridDataFactory.swtDefaults() .align(SWT.FILL, SWT.BEGINNING) .create()); removeButton.setEnabled(false); removeButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { ISelection selection = viewer.getSelection(); if (selection instanceof IStructuredSelection) { Iterator<?> iter = ((IStructuredSelection) selection).iterator(); Set<String> keys = new HashSet<>(); while (iter.hasNext()) { Map.Entry<?, ?> entry = (Map.Entry<?, ?>) iter.next(); keys.add((String) entry.getKey()); } contents.keySet().removeAll(keys); viewer.refresh(); setPreferenceValue(key, encodeMap(contents)); } } }); viewer.addSelectionChangedListener(new ISelectionChangedListener() { @Override public void selectionChanged(SelectionChangedEvent event) { removeButton.setEnabled(event.getSelection().isEmpty() == false); } }); registerField(new PreferenceField(key, viewer.getControl()) { @Override public void refresh() { String value = getPreferenceValue(key); Map<String, String> map = decodeToMap(value); contents.clear(); contents.putAll(map); viewer.refresh(); setPreferenceValue(key, encodeMap(contents)); } }); } private void createCheckboxField(Composite parent, final String key, int span, final String title) { final Button button = new Button(parent, SWT.CHECK); button.setText(title); button.setLayoutData(GridDataFactory.swtDefaults() .span(span, 1) .align(SWT.FILL, SWT.CENTER) .grab(true, false) .indent(BasicField.getDecorationWidth(), 0) .create()); registerField(new PreferenceField(key, button) { @Override public void refresh() { String current = getPreferenceValue(key); boolean value = current.equals("true"); //$NON-NLS-1$ button.setSelection(value); } }); button.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { setPreferenceValue(key, String.valueOf(button.getSelection())); } }); } private void createCommaListField( Composite parent, final String key, int span, final String title, final String hint) { Composite pane = new Composite(parent, SWT.NONE); pane.setLayoutData(GridDataFactory.swtDefaults() .align(SWT.FILL, SWT.BEGINNING) .grab(true, false) .span(span, 1) .create()); GridLayout layout = new GridLayout(1, false); layout.marginWidth = 0; layout.marginHeight = 0; layout.verticalSpacing = 0; pane.setLayout(layout); Label label = new Label(pane, SWT.NONE); label.setText(title + ':'); label.setLayoutData(GridDataFactory.swtDefaults() .align(SWT.FILL, SWT.END) .grab(true, false) .create()); final Text text = new Text(pane, SWT.BORDER); text.setLayoutData(GridDataFactory.swtDefaults() .align(SWT.FILL, SWT.END) .grab(true, false) .create()); registerField(new PreferenceField(key, text) { @Override public void refresh() { String current = getPreferenceValue(key); List<String> values = decodeToList(current); StringBuilder buf = new StringBuilder(); for (String s : values) { if (buf.length() != 0) { buf.append(", "); //$NON-NLS-1$ } buf.append(s); } text.setText(buf.toString()); } @Override protected IStatus getDefaultStatus() { if (hint == null) { return Status.OK_STATUS; } else { return new Status(IStatus.INFO, Activator.PLUGIN_ID, hint); } } }); text.addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent event) { String value = text.getText(); List<String> elements = new ArrayList<>(); for (String s : value.split(",")) { //$NON-NLS-1$ String element = s.trim(); if (element.isEmpty()) { continue; } elements.add(element); } setPreferenceValue(key, encodeList(elements)); } }); } private static class PropertiesContentProvider implements IStructuredContentProvider { PropertiesContentProvider() { return; } @Override public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { return; } @Override public Object[] getElements(Object inputElement) { return ((Map<?, ?>) inputElement).entrySet().toArray(); } @Override public void dispose() { return; } } private static class PropertiesLabelProvider extends LabelProvider implements ITableLabelProvider { PropertiesLabelProvider() { return; } @Override public Image getColumnImage(Object element, int columnIndex) { return null; } @Override public String getColumnText(Object element, int columnIndex) { Map.Entry<?, ?> entry = (Entry<?, ?>) element; if (columnIndex == 0) { return String.valueOf(entry.getKey()); } else { return String.valueOf(entry.getValue()); } } } }
true
59cf57a0c9e511c2ddd0cc4fbbb70eb290d2cb0d
Java
Iysha1/FarnellElectronikAutomation
/src/test/java/com/farnell/pages/DashboardPage.java
UTF-8
459
1.953125
2
[]
no_license
package com.farnell.pages; import com.farnell.utilities.Driver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.PageFactory; public class DashboardPage { public DashboardPage(){ PageFactory.initElements(Driver.get(),this);} @FindBy(xpath = "//a[contains(text(),'Register')]") public WebElement register; @FindBy(css = "#loggedInPar") public WebElement loggedIn; }
true
b2d95447b6ccb59e95764db53c0014632655bfe7
Java
543210188/JdbcBuilder
/src/main/java/com/ybchen/build/core/Pages.java
UTF-8
1,333
2.75
3
[]
no_license
package com.ybchen.build.core; import java.util.List; /** * 分页工具 * * @param <T> */ public class Pages<T> { /** * 每一页保存的数据 */ private List<T> list; /** * 总记录条数 */ private int total; /** * 每一页的记录条数 */ private int pageSize; /** * 所有的页数 */ private int totalPages; /** * 当前页数 */ private int currentPage; /** * @param total * @param currentPage * @param pageSize */ public Pages(int total, int currentPage, int pageSize,List list) { this.total = total; this.pageSize = pageSize; this.list=list; this.totalPages = (this.total - 1) / this.pageSize + 1; if (currentPage < 1) { this.currentPage = 1; } else if (currentPage > this.totalPages) { this.currentPage = this.totalPages; } else { this.currentPage = currentPage; } } public List<T> getList() { return list; } public int getTotal() { return total; } public int getPageSize() { return pageSize; } public int getTotalPages() { return totalPages; } public int getCurrentPage() { return currentPage; } }
true
c57af41c95521bfdea3c98b1592b94065ef2241c
Java
sormaz/labimp.extend
/labimp.extend/src/main/java/edu/ohiou/mfgresearch/labimp/draw/ImpObject.java
UTF-8
14,218
2.171875
2
[]
no_license
package edu.ohiou.mfgresearch.labimp.draw; /** * <p>Title: ImpObject Class</p> * <p>Description: ImpObject class is a root class for all process planning * related objects in IMPLAN development. It provides for easy * implementation of applets on any object in IMPLAN development * It provides basic functionality using which any * subclass can be displayed in AnimApplet</p> * <p>Copyright: Dr.D.N.Sormaz, Ohio University Copyright (c) 2002</p> * <p>Company: IMSE Dept, Ohio University</p> * @author Dr.Dusan N.Sormaz * @version 1.0 */ import java.io.OutputStream; import java.io.File; import java.io.Serializable; import java.awt.Color; import java.awt.Graphics2D; import java.io.*; import java.lang.reflect.Constructor; import javax.swing.JPanel; import javax.swing.JLabel; import java.awt.*; import java.awt.geom.*; import java.util.LinkedList; import javax.swing.tree.DefaultMutableTreeNode; //Importing classes required for Java 3D methods import javax.media.j3d.*; import javax.vecmath.Color3f; import javax.vecmath.Vector3d; import com.sun.j3d.utils.geometry.ColorCube; import com.sun.j3d.utils.geometry.Primitive; import com.sun.j3d.utils.geometry.Sphere; import cv97.j3d.loader.VRML97Loader; //Importing classes from Implanner import edu.ohiou.mfgresearch.labimp.basis.ImpXmlWriter; import edu.ohiou.mfgresearch.labimp.basis.ViewObject; import edu.ohiou.mfgresearch.labimp.basis.GUIApplet; import edu.ohiou.mfgresearch.labimp.gtk3d.WorldCS; public abstract class ImpObject extends ViewObject implements DrawableWF, Drawable3D, Serializable { static { loadProperties (ImpObject.class, "labimp.extend"); displayProperties(); } //Root BranchGroup of SceneGraph private BranchGroup objRoot; public ImpObject() { } /** * * Initializes visual components for GUIApplet * */ public void init() { if (needCanvas()) { } if (needPanel()) { panel = new JPanel(); try { if (this.getClass() == Class .forName("edu.ohiou.mfgresearch.labimp.draw.ImpObject")) panel.add(new JLabel("This is instance of " + this.getClass().toString())); else panel.add(new JLabel(this.getClass().toString() + " needs to implement init()")); panel.setSize(new Dimension(640, 100)); } catch (Exception e) { e.printStackTrace(); } } } /** * Sets object's applet to supplied applet * * @param inApplet applet to be assigned */ public void settApplet(GUIApplet inApplet) { applet = inApplet; } /** @todo dsormaz to wf applet */ public void setNeedUpdate(boolean needUpdate) { if (canvas == null) return; if (canvas instanceof DrawableWF) { ((DrawableWF) canvas).setNeedUpdate(needUpdate); } else if (canvas instanceof Drawable3D) { // ( (Drawable3D) canvas).setNeedUpdate(needUpdate); } else { super.setNeedUpdate(needUpdate); } } // Methods for Drawable3D interface /** * Creates a simple rotating color cube as the contentbranch of the default * ImpObject in an Animation Universe * * @return BranchGroup contentBranch of universe */ // public BranchGroup createSceneGraph() { // // Create the root of the branch graph // objRoot = new BranchGroup(); // objRoot.setCapability(BranchGroup.ALLOW_CHILDREN_READ); // objRoot.setCapability(BranchGroup.ALLOW_CHILDREN_WRITE); // // // Create the transform group node and initialize it to the // // identity. Add it to the root of the subgraph. // TransformGroup objSpin = new TransformGroup(); // objSpin.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE); // objRoot.addChild(objSpin); // // // Create a simple shape leaf node, add it to the scene graph. // // ColorCube is a Convenience Utility class // objSpin.addChild(new ColorCube(1 * 0.1)); // // // Create a new Behavior object that will perform the desired // // operation on the specified transform object and add it into // // the scene graph. // Alpha rotationAlpha = new Alpha(-1, 4000); // // RotationInterpolator rotator = new RotationInterpolator( // rotationAlpha, // objSpin); // // // a bounding sphere specifies a region a behavior is active // // create a sphere centered at the origin with radius of 100 // BoundingSphere bounds = new BoundingSphere(); // rotator.setSchedulingBounds(bounds); // objSpin.addChild(rotator); // return objRoot; // } public BranchGroup createSceneGraph() { objRoot = new BranchGroup(); objRoot.setCapability(BranchGroup.ALLOW_CHILDREN_READ); objRoot.setCapability(BranchGroup.ALLOW_CHILDREN_WRITE); // // Create the transform group node and initialize it to the // // identity. Add it to the root of the subgraph. // TransformGroup objSpin = new TransformGroup(); // objSpin.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE); // objRoot.addChild(objSpin); // System.out.println("this.getClass().getName() = "+this.getClass().getName()); String vrmlFileString = properties.getProperty(this.getClass().getName()); if(vrmlFileString != null) { File vrmlFile = new File(vrmlFileString); VRML97Loader vrmlFileLoader = new VRML97Loader(); if (vrmlFile != null) { try { // System.out.println("Inside VRML"); vrmlFileLoader.load(vrmlFile.getCanonicalPath()); BranchGroup vrmlGroup; vrmlGroup = vrmlFileLoader.getBranchGroup(); TransformGroup vrmlTransformGroup = new TransformGroup(); vrmlTransformGroup.addChild(vrmlGroup); objRoot.addChild(vrmlTransformGroup); } catch (Exception ex) { ex.printStackTrace(); } } } else { System.err.println(this.getClass().getName()+" node vrml file does not exist"); Color3f black = new Color3f(0.0f, 0.0f, 0.0f); Shape3D s3d = new Shape3D(); String shapeString = properties.getProperty(this.getClass().getName() +"."+s3d.getClass().getName()); if(shapeString != null) { Class c; try { c = Class.forName(shapeString); Primitive shape = (Primitive) c.newInstance(); Appearance shapeApp = new Appearance(); if (this.toString().toLowerCase().equals(this.toString())) { String sphereColor2 = properties.getProperty(this.getClass().getName()+".shapeColor2."+String.class.getName(), properties.getProperty("defaultShapeColor."+String.class.getName(), "")); Color color2 = new Color(Integer.parseInt(sphereColor2, 16)); shapeApp.setMaterial(new Material(new Color3f(color2), black, new Color3f(color2), black, 80.0f)); } else { String sphereColor = properties.getProperty(this.getClass().getName()+".shapeColor."+String.class.getName(), properties.getProperty("defaultShapeColor."+String.class.getName(), "")); Color color = new Color(Integer.parseInt(sphereColor, 16)); shapeApp.setMaterial(new Material(new Color3f(color), black, new Color3f(color), black, 80.0f)); } shape.setAppearance(shapeApp); TransformGroup shapeTransformGroup = new TransformGroup(); shapeTransformGroup.addChild(shape); objRoot.addChild(shapeTransformGroup); } catch (Exception e) { System.err.print("Class " + shapeString + " can not be loaded"); // e.printStackTrace(); } } else { System.err.println(this.getClass().getName()+" node shape does not exist"); // Color3f black = new Color3f(0.0f, 0.0f, 0.0f); TransformGroup sphereGroup = new TransformGroup(); Appearance sphereApp = new Appearance(); if (this.toString().toLowerCase().equals(this.toString())) { String sphereColor2 = properties.getProperty(this.getClass().getName()+".sphereColor2."+String.class.getName(), properties.getProperty("defaultSphereColor."+String.class.getName(), "")); Color color2 = new Color(Integer.parseInt(sphereColor2, 16)); sphereApp.setMaterial(new Material(new Color3f(color2), black, new Color3f(color2), black, 80.0f)); } else { String sphereColor = properties.getProperty(this.getClass().getName()+".sphereColor."+String.class.getName(), properties.getProperty("defaultSphereColor."+String.class.getName(), "")); Color color = new Color(Integer.parseInt(sphereColor, 16)); sphereApp.setMaterial(new Material(new Color3f(color), black, new Color3f(color), black, 80.0f)); } float sphereRadius = Float.parseFloat(properties.getProperty (this.getClass().getName()+".sphereRadius."+String.class.getName(), properties.getProperty("defaultSphereRadius."+String.class.getName()))); sphereGroup.addChild (new Sphere(sphereRadius, sphereApp)); objRoot.addChild(sphereGroup); } } // // Create a new Behavior object that will perform the desired // // operation on the specified transform object and add it into // // the scene graph. // Alpha rotationAlpha = new Alpha(-1, 4000); // // RotationInterpolator rotator = new RotationInterpolator(rotationAlpha, objSpin); // // // a bounding sphere specifies a region a behavior is active // // create a sphere centered at the origin with radius of 100 // BoundingSphere bounds = new BoundingSphere(); // rotator.setSchedulingBounds(bounds); // objSpin.addChild(rotator); return objRoot; } //Creates an AnimationGraph public BranchGroup createAnimationGraph() { return new BranchGroup(); } //Definition to set the universe view point public void setUniverseViewPoint(Vector3d inVector) { } //Definition to start the animation associated with the scene graph public void startAnimation() { } //Definition to stop the animation associated with the scene graph public void stopAnimation() { } //Definition to change the mode of the 3D object to either Wire frame or Solid mode public void setAppearance(boolean showWireFrame) { } /** * Sets the canvas * * @param inCanvas instance of AnimPanel */ public void settCanvas(AnimPanel inCanvas) { canvas = inCanvas; } public void settCanvas(DrawWFPanel inCanvas) { canvas = inCanvas; } public void paintComponent(Graphics2D g, DrawWFPanel canvas) { this.doNothing("in ivieobj paintcomp"); } /** * Returns the node that can be added to some tree for display * @param noLevels number of levels that this object should be expanded * usually it is reduced by one if it is sent to some members to create * their own nodes. * @return */ public DefaultMutableTreeNode geetTree(int noLevels) { return new DefaultMutableTreeNode(this); } public DefaultMutableTreeNode geetTree() { return new DefaultMutableTreeNode(this); } public String makeSchema() { return new String(); } public void writeXMLFile(File f) throws IOException { FileOutputStream stream = new FileOutputStream(f); writeXMLFile(stream); stream.close(); } public void writeXMLFile(OutputStream stream) throws IOException { OutputStreamWriter writer = new OutputStreamWriter(stream); StringBuffer buffer = new StringBuffer(); writeXMLHeader(buffer); writeXML(buffer, ""); writer.write(buffer.toString()); writer.close(); } public ImpXmlWriter findXMLWriter() { ImpXmlWriter writer = null; String writerName = getProperty("XML_WRITER"); Object[] args = { this }; if (writerName != null && !writerName.equalsIgnoreCase("")) { try { Class handlerClass = Class.forName(writerName); Constructor c = handlerClass.getConstructor(geettXMLWriterArgTypes()); writer =(ImpXmlWriter) c.newInstance(args); // writer = (ImpXmlWriter) handlerClass.newInstance(); } catch (Exception ex) { ex.printStackTrace(); } } else { throw new IllegalArgumentException("XML Writer not specified"); } return writer; } public Class [] geettXMLWriterArgTypes () { Class [] argTypes = new Class [] {}; return argTypes; } public void makeShapeSets (DrawWFPanel canvas) { Color color = this.color; if (color == null) { String propColor = properties.getProperty(this.getClass().getName() + ".color", "000000"); color = new Color(Integer.parseInt(propColor, 16)); } if (canvas instanceof DrawWFPanel) { DrawWFPanel drawPanel = (DrawWFPanel) canvas; drawPanel.addDrawShapes(color, geetShapeList(drawPanel)); } } /** * Generates list of objects to be drawn in WF Canvas. * * @param canvas the <code>DrawWFCanvas</code> on which to draw. * @return the <code>LinkedList</code> of shape object to be drawn * directly on Canvas * @since 1.2 */ public LinkedList geetShapeList(DrawWFPanel canvas) { try { if (this.getClass() == Class .forName("edu.ohiou.mfgresearch.labimp.draw.ImpObject")) { WorldCS cs = new WorldCS(); return cs.geetShapeList(canvas); } else { System.out .println("Method 'public LinkedList getShapeList(DrawWFPanel canvas)' should be implemented in " + this.getClass().toString()); if (panel != null && panel.getComponentCount() < 2) panel .add(new JLabel( this.getClass().toString() + " needs to implement method 'public LinkedList getShapeList(DrawWFPanel canvas)'")); } } catch (Exception e) { e.printStackTrace(); } return new LinkedList(); } public LinkedList geetDrawList() { LinkedList list = new LinkedList(); // list.add(new Line2D.Double(3.2, 4.3, 100.3, 200.5)); list.add(new Ellipse2D.Double (0,0,1,1)); return list; } /** * Main method for testing purposes * This method is implemented in the class to test the class in stand-alone mode * * @param arg array of strings for command line arguments */ public static void main(String[] arg) { } }
true
2228a438e41a2e49b4c77758743e7d5012e930a5
Java
Gooras/ApiFDP
/src/main/java/com/asseco/cm/FDPProxyXMLController.java
UTF-8
13,088
1.859375
2
[]
no_license
package com.asseco.cm; import com.asseco.cm.callback.ClientKeyStorePasswordCallback; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintWriter; import java.net.MalformedURLException; import java.net.URL; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.Map; import lombok.extern.slf4j.Slf4j; import org.apache.cxf.endpoint.Client; import org.apache.cxf.interceptor.LoggingInInterceptor; import org.apache.cxf.interceptor.LoggingOutInterceptor; import org.apache.cxf.ws.security.wss4j.WSS4JInInterceptor; import org.apache.cxf.ws.security.wss4j.WSS4JOutInterceptor; import org.apache.wss4j.dom.WSConstants; import org.apache.wss4j.dom.handler.WSHandlerConstants; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import pl.firstdata.wdx.business.card.AccountManagementRequest; import pl.firstdata.wdx.business.card.CardAccountBindingRequest; import pl.firstdata.wdx.business.card.CardIssuingRequest; import pl.firstdata.wdx.business.card.CardIssuingResponse; import pl.firstdata.wdx.business.card.CardStatusUpdateRequest; import pl.firstdata.wdx.business.card.CrtaResponse; import pl.firstdata.wdx.business.card.ReadCrtaRequest; import pl.firstdata.wdx.business.card.v5.CardService; import pl.firstdata.wdx.business.card.v5.CardService_Service; import pl.firstdata.wdx.business.card.v5.OperationResult; import com.asseco.cm.fdp.client.CmAccountManagementRequest; import com.asseco.cm.fdp.client.CmCardAccountBindingRequest; import com.asseco.cm.fdp.client.CmCardIssuingRequest; import com.asseco.cm.fdp.client.CmCardStatusUpdateRequest; @Slf4j @RestController @RequestMapping("/api/xml") public class FDPProxyXMLController { @Autowired Config conf; @Autowired ClientConfig clientConf; @Autowired CardService cardService; @Autowired Client client; public static URL wsdl_url; private String nl = System.lineSeparator(); CardService_Service cService; @Bean public CardService cardService() throws MalformedURLException { //TODO: zgłosić wyjątek, gdy url nieprawidłowy URL url = new URL(clientConf.getConfFdpWsdlUrl()); //MOCK Michała //url = new File( // "C:/Users/Grzegorz.Gora/Desktop/REST/FDPapi/src/main/resources/CardServiceWSSMock.wsdl") // .toURI().toURL(); //URL url = new URL(conf.getWsAddress()); //url = conf.getWsdl(); log.debug("(Bean) (CardService) WSDL: "+url); CardService_Service service = null; //TODO: zgłosić wyjątek, gdy nie uda się stworzyć serwisu? Da się to jakoś sprawdzić? try { service = new CardService_Service(url); } catch (Exception e) { log.error("(Bean) (CardService) Błąd tworzenia serwisu "+url+e.getLocalizedMessage()); } if (service==null) { log.error("(Bean) (CardService) Błąd tworzenia serwisu "+url); } else log.debug("(Bean) (CardService) Serwis utworzony "+url); log.debug("(Bean) (CardService_Service): "+service.toString()); cardService = service.getCardServicePort(); //CardService cardService = service.getCardServicePort(); //this.cardService = cardService; log.debug("Serwis utworzony: " + cardService.toString()); client = (Client) cardService; log.debug("(Bean) Klient utworzony " + client.toString()); // addInterceptors(client); addInterceptors(); log.debug("(Bean) Klient - interceptory włączone"); //return service.getCardServicePort(); return cardService; } //@Bean /*public Client client(CardService cardService) { Client cli = (Client) cardService; log.debug("(Bean) Klient utworzony " + cli.toString()); //TODO - interceptory do logowania, interceptory do WSS jak włączony parametr //addInterceptors(cli); log.debug("(Bean) Klient - interceptory włączone"); return cli; }*/ //Właściwe metody REST @RequestMapping(value = FDPRestURIConstants.ACC_MNGMT, consumes = MediaType.APPLICATION_XML_VALUE, method = RequestMethod.POST, produces = MediaType.APPLICATION_XML_VALUE) public OperationResult accountManagement(@RequestBody AccountManagementRequest request) { // public OperationResult accountManagement(@RequestBody CmAccountManagementRequest request) { log.debug("Metoda: " + FDPRestURIConstants.ACC_MNGMT); log.debug("Request: " + nl + FDPApiTools.jaxbObjectToXML(request)); OperationResult result = cardService.accountManagement(request); log.debug("Response: " + nl + FDPApiTools.jaxbObjectToXML(result)); return result; } @RequestMapping(value = FDPRestURIConstants.CARD_ISS, consumes = MediaType.APPLICATION_XML_VALUE, method = RequestMethod.POST, produces = MediaType.APPLICATION_XML_VALUE) public OperationResult cardIssuing(@RequestBody CardIssuingRequest request) { // public OperationResult cardIssuing(@RequestBody CmCardIssuingRequest request) { log.debug("Metoda: " + FDPRestURIConstants.CARD_ISS); log.debug("Request (XML): " + nl + FDPApiTools.jaxbObjectToXML(request)); CardIssuingResponse result = cardService.cardIssuing(request); log.debug("Response (XML): " + nl + FDPApiTools.jaxbObjectToXML(result)); return result; } @RequestMapping(value = FDPRestURIConstants.CARD_BIND, consumes = MediaType.APPLICATION_XML_VALUE, method = RequestMethod.POST, produces = MediaType.APPLICATION_XML_VALUE) public OperationResult binding(@RequestBody CardAccountBindingRequest request) { // public OperationResult binding(@RequestBody CmCardAccountBindingRequest request) { log.debug("Metoda: " + FDPRestURIConstants.CARD_BIND); log.debug("Request: " + nl + FDPApiTools.jaxbObjectToXML(request)); OperationResult result = cardService.cardAccountBinding(request); log.debug("Response: " + nl + FDPApiTools.jaxbObjectToXML(result)); return result; } @RequestMapping(value = FDPRestURIConstants.CARD_STATUS, consumes = MediaType.APPLICATION_XML_VALUE, method = RequestMethod.POST, produces = MediaType.APPLICATION_XML_VALUE) public OperationResult cardStatus(@RequestBody CardStatusUpdateRequest request) { // public OperationResult cardStatus(@RequestBody CmCardStatusUpdateRequest request) { log.debug("Metoda: " + FDPRestURIConstants.CARD_STATUS); log.debug("Request: " + nl + FDPApiTools.jaxbObjectToXML(request)); OperationResult result = cardService.updateCardStatus(request); log.debug("Response: " + nl + FDPApiTools.jaxbObjectToXML(result)); return result; } @RequestMapping(value = FDPRestURIConstants.VERSION, consumes = MediaType.ALL_VALUE, method = RequestMethod.GET, produces = MediaType.ALL_VALUE) public String getVersion() { log.debug("Metoda: " + FDPRestURIConstants.VERSION+" ver: "+conf.getAppVersion()); return "ver: "+conf.getAppVersion() + nl + "<br/>logger: "+ log.getClass().getName() + nl + "<br/>conf: "+clientConf.getConfFilename(); } //do testów WSS na MOCKu: @RequestMapping(value = "/testWSScrta", consumes = MediaType.APPLICATION_XML_VALUE, method = RequestMethod.POST, produces = MediaType.APPLICATION_XML_VALUE) public CrtaResponse crta(@RequestBody ReadCrtaRequest request) { log.debug("Metoda: " + "/testWSScrta"); log.debug("Request: " + nl + FDPApiTools.jaxbObjectToXML(request)); log.debug("Serwis: " + cardService.toString()); log.debug("Klient: " + client.toString()); CrtaResponse result = cardService.readCrta(request); log.debug("Response: " + nl + FDPApiTools.jaxbObjectToXML(result)); return result; } // private void addInterceptors(Client cli) { public void addInterceptors() { if (clientConf.getConfWSSEnabled()) { log.debug("interceptory WSS Start - Klient: " + client.toString()); //Incoming Map<String, Object> incomingProps = new HashMap<String, Object>(); incomingProps.put(WSHandlerConstants.ACTION, WSHandlerConstants.TIMESTAMP + " " + WSHandlerConstants.SIGNATURE + " " + WSHandlerConstants.ENCRYPT); incomingProps.put(WSHandlerConstants.SIG_PROP_FILE, "clientKeyStore.properties"); incomingProps.put(WSHandlerConstants.DEC_PROP_FILE, "clientKeyStore.properties");//odpowiednik truststore incomingProps.put(WSHandlerConstants.PW_CALLBACK_CLASS, ClientKeyStorePasswordCallback.class.getName()); incomingProps.put(WSHandlerConstants.ALLOW_RSA15_KEY_TRANSPORT_ALGORITHM, "true"); WSS4JInInterceptor wssIncoming = new WSS4JInInterceptor(incomingProps); System.out.println("FDPProxyXMLController - interceptory do logowania - In: "+wssIncoming.toString()); client.getInInterceptors().add(wssIncoming); //Outgoing Map<String, Object> outgoingProps = new HashMap<String, Object>(); outgoingProps.put(WSHandlerConstants.ACTION, WSHandlerConstants.SIGNATURE + " " + WSHandlerConstants.ENCRYPT); outgoingProps.put(WSHandlerConstants.SIG_PROP_FILE, "clientKeyStore.properties"); outgoingProps.put(WSHandlerConstants.ENC_PROP_FILE, "clientKeyStore.properties"); outgoingProps.put(WSHandlerConstants.PW_CALLBACK_CLASS, ClientKeyStorePasswordCallback.class.getName()); //to dziaĹ‚a z FDP // outgoingProps.put(WSHandlerConstants.USER, "nsb"); //to dziaĹ‚a z mockiem outgoingProps.put(WSHandlerConstants.USER, "fdp"); outgoingProps.put(WSHandlerConstants.ENCRYPTION_USER, "fdp"); outgoingProps.put(WSHandlerConstants.SIGNATURE_PARTS, "{Element}{http://schemas.xmlsoap.org/soap/envelope/}Body"); outgoingProps.put(WSHandlerConstants.ENCRYPTION_PARTS, "{Element}{http://www.w3.org/2000/09/xmldsig#}Signature;{Content}{http://schemas.xmlsoap.org/soap/envelope/}Body"); outgoingProps.put(WSHandlerConstants.ENC_SYM_ALGO, WSConstants.AES_128); // outgoingProps.put(WSHandlerConstants.ALLOW_RSA15_KEY_TRANSPORT_ALGORITHM, "true"); WSS4JOutInterceptor wssOutgoing = new WSS4JOutInterceptor(outgoingProps); client.getOutInterceptors().add(wssOutgoing); log.debug("wssOutgoing: " + String.valueOf(client.getOutInterceptors().contains(wssOutgoing))); } log.debug("interceptory WSS Stop"); /*if (clientConf.isConfLogCXFEnabled()) { if (conf.getLoggingInEnabled()) { log.debug("FDPProxyXMLController - interceptory do logowania - In"); LoggingInInterceptor loggerIn = new LoggingInInterceptor(); PrintWriter writerIn = null; try { writerIn = new PrintWriter(new File("src/main/resources/FDPProxyIn.log")); //writerIn = new PrintWriter(new File("C:/Users/Grzegorz.Gora/Desktop/REST/FDPapi/src/main/resources/FDPProxyIn.log")); } catch (FileNotFoundException e) { log.error(e.getLocalizedMessage()); e.printStackTrace(); } loggerIn.setPrintWriter(writerIn); client.getInInterceptors().add(loggerIn); } if (conf.getLoggingOutEnabled()) { log.debug("FDPProxyXMLController - interceptory do logowania - Out"); PrintWriter writerOut = null; Date date = Calendar.getInstance().getTime(); DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd_hh-mm-ss"); String strDate = dateFormat.format(date); String fileName = conf.getLoggingOutFileName()+"_"+strDate+".log"; try { File file = new File("/logs/"+fileName); log.debug("Path1: "+file.getAbsolutePath()); log.debug("Writer: "+file.getCanonicalPath()); writerOut = new PrintWriter(file); file = new File(fileName); log.debug("Path2: "+file.getAbsolutePath()); log.debug("Writer: "+file.getCanonicalPath()); writerOut = new PrintWriter(file); file = new File("../log/"+fileName); log.debug("Path3: "+file.getAbsolutePath()); log.debug("Writer: "+file.getCanonicalPath()); file = new File("./log/"+fileName); log.debug("Path4: "+file.getAbsolutePath()); log.debug("Writer: "+file.getCanonicalPath()); writerOut = new PrintWriter(file); // writerOut = new PrintWriter(new File("src/main/resources/FDPProxyOut.log")); } catch (FileNotFoundException e) { log.error(e.getLocalizedMessage()); e.printStackTrace(); } catch (IOException e) { log.error(e.getLocalizedMessage()); e.printStackTrace(); } LoggingOutInterceptor loggerOut = new LoggingOutInterceptor(writerOut); //??? // LoggingOutInterceptor loggerOut = new LoggingOutInterceptor((PrintWriter) log); client.getOutInterceptors().add(loggerOut); } }//koniec warunku 1=0 */ } }
true
7ed7d7357beb79652cc07897dac3571c762940d1
Java
muloem/xins
/src/tests/org/xins/tests/common/text/ParseExceptionTests.java
UTF-8
1,832
2.125
2
[ "BSD-2-Clause", "BSD-3-Clause" ]
permissive
/* * $Id$ * * Copyright 2003-2008 Online Breedband B.V. * See the COPYRIGHT file for redistribution and use restrictions. */ package org.xins.tests.common.text; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.xins.logdoc.ExceptionUtils; import org.xins.common.text.ParseException; /** * Tests for class <code>ParseException</code>. * * @version $Revision$ $Date$ * @author <a href="mailto:ernst@ernstdehaan.com">Ernst de Haan</a> */ public class ParseExceptionTests extends TestCase { /** * Constructs a new <code>ParseExceptionTests</code> test suite with * the specified name. The name will be passed to the superconstructor. * * @param name * the name for this test suite. */ public ParseExceptionTests(String name) { super(name); } /** * Returns a test suite with all test cases defined by this class. * * @return * the test suite, never <code>null</code>. */ public static Test suite() { return new TestSuite(ParseExceptionTests.class); } public void testParseException() throws Throwable { ParseException p = new ParseException(); assertEquals(null, p.getMessage()); assertEquals(null, p.getDetail()); assertEquals(null, ExceptionUtils.getCause(p)); p = new ParseException(null, null, null); assertEquals(null, p.getMessage()); assertEquals(null, p.getDetail()); assertEquals(null, ExceptionUtils.getCause(p)); Exception cause = new Exception(); String message = "'nough said."; String detail = "Zoom zoom zoom"; p = new ParseException(message, cause, detail); assertEquals(message, p.getMessage()); assertEquals(detail, p.getDetail()); assertEquals(cause, ExceptionUtils.getCause(p)); } }
true
33b1e4c002f695e7ba9598bd34bb31bf56915c0e
Java
Avik1914/Competitive-Programming
/number-of-restricted-paths-from-first-to-last-node/number-of-restricted-paths-from-first-to-last-node.java
UTF-8
1,453
2.53125
3
[]
no_license
class Solution { int[] dist; Integer[] dp; public int countRestrictedPaths(int n, int[][] edges) { List<int[]>[] graph=new ArrayList[n+1]; dp=new Integer[n+1]; for(int i=1;i<=n;i++) graph[i]=new ArrayList(); for(int[] e:edges){ graph[e[0]].add(new int[]{e[1],e[2]}); graph[e[1]].add(new int[]{e[0],e[2]}); } dist=new int[n+1]; Arrays.fill(dist,Integer.MAX_VALUE); dist[n]=0; PriorityQueue<Integer> pq=new PriorityQueue<>((a,b)->dist[a]-dist[b]); pq.add(n); while(!pq.isEmpty()){ int val=pq.poll(); for(int[] e:graph[val]){ if(dist[e[0]]>e[1]+dist[val]){ dist[e[0]]=e[1]+dist[val]; pq.add(e[0]); } } } return dfs(graph,1,n,dist[1],new boolean[n+1]); } public int dfs(List<int[]>[] graph,int start,int end,int prev,boolean[] visit){ if(start==end) return 1; long val=0; if(dp[start]!=null) return dp[start]; visit[start]=true; for(int[] e:graph[start]){ if(!visit[e[0]] && prev>dist[e[0]]) val+=dfs(graph,e[0],end,dist[e[0]],visit); } visit[start]=false; dp[start]=(int)(val%1000000007); return dp[start]; } }
true
99ba833a631863e2814b7e3f25e3cf26ca70ee53
Java
0jinxing/wechat-apk-source
/com/tencent/ttpic/facedetect/FaceInfo.java
UTF-8
801
1.585938
2
[]
no_license
package com.tencent.ttpic.facedetect; import android.graphics.PointF; import com.tencent.matrix.trace.core.AppMethodBeat; import java.util.List; public class FaceInfo { public float[] angles; public float[] denseFaceModel; public List<PointF> irisPoints; public float pitch; public List<PointF> points; public float roll; public float scale; public float[] transform; public float tx; public float ty; public float yaw; public FaceInfo() { AppMethodBeat.i(81915); this.angles = new float[3]; AppMethodBeat.o(81915); } } /* Location: C:\Users\Lin\Downloads\dex-tools-2.1-SNAPSHOT\dex-tools-2.1-SNAPSHOT\classes7-dex2jar.jar * Qualified Name: com.tencent.ttpic.facedetect.FaceInfo * JD-Core Version: 0.6.2 */
true
d855f38f72284f81acecfa14f966b8ad8ba4fa83
Java
AmirBenAmara/E-commerce-JavaFx-
/src/eshop/interfaces/IComment.java
UTF-8
589
1.765625
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 eshop.interfaces; import eshop.models.Comment; import eshop.models.Customer; import eshop.models.Product; import java.util.ArrayList; /** * * @author Karim SNOUSSI */ public interface IComment extends IService<Comment,Integer> { public ArrayList<Comment> findByProduct(Product produit); public ArrayList<Comment> findByCustomer(Customer customer); }
true
23a8ce9febec371091b9e0e51ef68efa674ef60d
Java
turusbekovdias/real-spring
/src/main/java/com/example/demo/domeins/Customer.java
UTF-8
2,320
2.609375
3
[]
no_license
package com.example.demo.domeins; import javax.persistence.*; @Entity public class Customer { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id", unique = true, nullable = false) private Integer id; private String firstname; private String lastname; private String middlename; private String mobileNumber; private String homeNumber; private String email; public Customer () {} public Customer (Integer id, String firstname, String lastname, String middlename, String mobileNumber, String homeNumber, String email) { this.id = id; this.firstname = firstname; this.lastname = lastname; this.middlename = middlename; this.mobileNumber = mobileNumber; this.homeNumber = homeNumber; this.email = email; } public Customer (String firstname, String lastname, String middlename, String mobileNumber, String homeNumber, String email) { this.firstname = firstname; this.lastname = lastname; this.middlename = middlename; this.mobileNumber = mobileNumber; this.homeNumber = homeNumber; this.email = email; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getFirstname() { return firstname; } public void setFirstname(String firstname) { this.firstname = firstname; } public String getLastname() { return lastname; } public void setLastname(String lastname) { this.lastname = lastname; } public String getMiddlename() { return middlename; } public void setMiddlename(String middlename) { this.middlename = middlename; } public String getMobileNumber() { return mobileNumber; } public void setMobileNumber(String mobileNumber) { this.mobileNumber = mobileNumber; } public String getHomeNumber() { return homeNumber; } public void setHomeNumber(String homeNumber) { this.homeNumber = homeNumber; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } }
true
c1a1015d80bb8cd5b15609d72b9d3e98aac86b6b
Java
360J2ME/360-People-Client-J2ME
/sources/src/com/zyb/nowplus/presentation/view/providers/VirtualListRange.java
UTF-8
5,774
2.1875
2
[]
no_license
/******************************************************************************* * CDDL HEADER START * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at * src/com/vodafone360/people/VODAFONE.LICENSE.txt or * http://github.com/360/360-Engine-for-Android * See the License for the specific language governing permissions and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END * * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved. * Use is subject to license terms. ******************************************************************************/ package com.zyb.nowplus.presentation.view.providers; import de.enough.polish.ui.Canvas; public class VirtualListRange { static int FACTOR_BUFFER = 3; static int FACTOR_LIMIT = 3; int start; int end; int total; final int range; int offset; final int referenceHeight; final int availableHeight; int totalHeight; int listHeight; int maximumY; int minimumY; final int bufferHeight; final int limitHeight; public VirtualListRange(int referenceHeight, int availableHeight, int minimumItems) { //#debug debug System.out.println("initialising range with : referenceHeight : " + referenceHeight + " : availableHeight : " + availableHeight + " : minimumItems : " + minimumItems); this.referenceHeight = referenceHeight; this.availableHeight = availableHeight; this.range = getRange(minimumItems); this.limitHeight = this.range / 5 * this.referenceHeight; this.bufferHeight = this.availableHeight * FACTOR_BUFFER; this.offset = -1; } /** * Sets the minimum and maximum threshold using the given start, * end and total * @param start the start * @param end the end * @param total the total */ void setRange(int start, int end, int total) { //#debug debug System.out.println("updating range : start : " + start + " : end : " + end + " : total : " + total); this.start = start; this.end = end; this.total = total; this.totalHeight = total * this.referenceHeight; this.listHeight = (end - start + 1) * this.referenceHeight; this.minimumY = (start * this.referenceHeight) + getLimitHeight(); this.maximumY = ((start * this.referenceHeight) + this.listHeight) - getLimitHeight(); // handle list start / end / overlapping if (start == 0) { this.minimumY = Integer.MIN_VALUE; } if (end == total - 1) { this.maximumY = Integer.MAX_VALUE; } } /** * Returns true if y is below the minimum threshold * @param y the y offset * @return true if y is below the minimum threshold otherwise false */ public boolean belowRange(long y) { boolean result = y < this.minimumY; //#mdebug debug if (result) { System.out.println("list selection is below range, updating"); } //#enddebug return result; } /** * Returns true if the y offset is over the maximum threshold * @param y the y offset * @return true if y is over the maximum threshold otherwise false */ public boolean overRange(long y) { boolean result = (y + this.availableHeight) > this.maximumY; //#mdebug debug if (result) { System.out.println("list selection is over range, updating"); } //#enddebug return result; } /** * Update the range according to the specified y offset * @param y the y offset * @param direction the direction of the scrolling * @param total the total number of items */ public void update(long y, int direction, int total) { int start = 0; int end = 0; long startY = 0; long endY = 0; if (direction == Canvas.DOWN) { endY = y + this.availableHeight; startY = endY - (this.range * this.referenceHeight); endY += getLimitHeight(); } else { startY = y; endY = startY + this.range * this.referenceHeight; startY -= getLimitHeight(); } start = (int) startY / this.referenceHeight; end = (int) endY / this.referenceHeight; if (start <= 0) { start = 0; } if (end > this.total - 1) { end = this.total - 1; } setRange(start, end, total); } int getRange(int minimum) { int neededRange = getBufferHeight() / this.referenceHeight; if (this.availableHeight % this.referenceHeight > 0) { neededRange++; } if (minimum > neededRange) { //#debug debug System.out.println("setting range to minimum : " + minimum); return minimum; } else { //#debug debug System.out.println("setting range : " + neededRange); return neededRange; } } public void setVisibleOffset(int offset) { this.offset = offset; } public int getOffset() { return this.offset; } public int getStart() { return this.start; } public int getEnd() { return this.end; } public int getTotal() { return this.total; } public int getRange() { return this.range; } public int getReferenceHeight() { return referenceHeight; } public int getAvailableHeight() { return availableHeight; } public int getTotalHeight() { return totalHeight; } public int getListHeight() { return listHeight; } public int getMinimumY() { return maximumY; } public int getMaximumY() { return minimumY; } int getLimitHeight() { return this.limitHeight; } int getBufferHeight() { return this.bufferHeight; } }
true
2298c58bb9ac36f4b0a6d1f65cacb4e0c91ddab6
Java
groverliam/Computer-Science-courses
/MeanAndStdDev copy/src/MyNode.java
UTF-8
612
3.015625
3
[]
no_license
public class MyNode { private double value; private MyNode next; private MyNode prev; public MyNode(double v) { value = v; next = null; } /*public MyNode(double v, MyNode n) { value = v; next = n; }*/ public MyNode(double v, MyNode n, MyNode p) { value = v; next = n; prev = p; } public void setNext(MyNode n) { next = n; } /*public void setPrev(MyNode p) { prev = p; }*/ public void setValue(double v) { value = v; } public MyNode getNext() { return next; } /*public MyNode getPrev() { return next; }*/ public double getValue() { return value; } }
true
23677ac90ce36be603ac26d871d72042c84dadc5
Java
mahisingh002/android-navigation-drawer-example-master
/app/src/main/java/net/simplifiedcoding/navigationdrawerexample/Model/Mis.java
UTF-8
1,515
2.390625
2
[]
no_license
package net.simplifiedcoding.navigationdrawerexample.Model; import java.io.Serializable; /** * Created by vibes on 12/3/17. */ public class Mis implements Serializable { private String image; private String mis_id; private String title; private String file; private String date; private String status; public String getImage() { return image; } public void setImage(String image) { this.image = image; } public String getMis_id() { return mis_id; } public void setMis_id(String mis_id) { this.mis_id = mis_id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getFile() { return file; } public void setFile(String file) { this.file = file; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } @Override public String toString() { return "Mis{" + "image='" + image + '\'' + ", mis_id='" + mis_id + '\'' + ", title='" + title + '\'' + ", file='" + file + '\'' + ", date='" + date + '\'' + ", status='" + status + '\'' + '}'; } }
true
b5b45fe87ad3559f39fef0dff98275acda32c489
Java
jdmr/eliseo-portlet
/src/main/java/mx/edu/um/portlets/eliseo/utils/SesionValidator.java
UTF-8
1,067
2.265625
2
[]
no_license
package mx.edu.um.portlets.eliseo.utils; import mx.edu.um.portlets.eliseo.model.Sesion; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import org.springframework.validation.Errors; import org.springframework.validation.ValidationUtils; import org.springframework.validation.Validator; /** * * @author jdmr */ @Component public class SesionValidator implements Validator { private static final Logger log = LoggerFactory.getLogger(SesionValidator.class); @Override public boolean supports(Class<?> aClass) { return Sesion.class.isAssignableFrom(aClass); } @Override public void validate(Object target, Errors errors) { log.debug("Validando sesion"); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "dia", "sesion.dia.requerido"); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "horaInicial", "sesion.horaInicial.requerido"); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "horaFinal", "sesion.horaFinal.requerido"); } }
true
cbcc3f4a1349ec288d324134a607945c258c0334
Java
vachacz/wot-lambda
/wotJavaRoot/wotLambdaPlayerStatsScheduler/src/main/java/pl/vachacz/mywotstats/Wn8Updater.java
UTF-8
2,710
2.703125
3
[]
no_license
package pl.vachacz.mywotstats; import com.amazonaws.services.dynamodbv2.datamodeling.PaginatedScanList; import pl.vachacz.mywotstats.dynamo.WotDynamo; import pl.vachacz.mywotstats.dynamo.model.PlayerTankStatsEntity; import pl.vachacz.mywotstats.dynamo.model.VehicleEntity; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.Map; public class Wn8Updater { public static void main(String[] args) { WotDynamo wotDynamo = new WotDynamo(); Map<Long, VehicleEntity> vehiclesMap = wotDynamo.getAllVehiclesAsMap(); PaginatedScanList<PlayerTankStatsEntity> allPlayerTankStats = wotDynamo.getAllPlayerTankStats(); System.out.println("Total rows : " + allPlayerTankStats.size()); allPlayerTankStats.forEach(stat -> { if (stat.getWn8() == null && stat.getBattles() > 0) { try { stat.setWn8(scale2(computeWn8(stat, vehiclesMap))); } catch (Exception e) { e.printStackTrace(); } wotDynamo.save(stat); } }); } private static Double computeWn8(PlayerTankStatsEntity tankEntity, Map<Long, VehicleEntity> vehiclesMap) { VehicleEntity vehicle = vehiclesMap.get(tankEntity.getTankId()); if (vehicle == null) { System.out.println("vehicle not found : " + tankEntity.getTankId()); return null; } Double rDAMAGE = tankEntity.getAvgDamageDealt() / vehicle.getExpDamage(); Double rSPOT = tankEntity.getAvgSpotted() / vehicle.getExpSpot(); Double rFRAG = tankEntity.getAvgFrags() / vehicle.getExpFrag(); Double rDEF = tankEntity.getAvgDroppedCapturePoints() / vehicle.getExpDef(); Double rWIN = tankEntity.getWinsRatio() / vehicle.getExpWinRate(); Double rWINc = Math.max(0, (rWIN - 0.71) / (1 - 0.71) ); Double rDAMAGEc = Math.max(0, (rDAMAGE - 0.22) / (1 - 0.22) ); Double rFRAGc = Math.max(0, Math.min(rDAMAGEc + 0.2, (rFRAG - 0.12) / (1 - 0.12))); Double rSPOTc = Math.max(0, Math.min(rDAMAGEc + 0.1, (rSPOT - 0.38) / (1 - 0.38))); Double rDEFc = Math.max(0, Math.min(rDAMAGEc + 0.1, (rDEF - 0.10) / (1 - 0.10))); return 980*rDAMAGEc + 210*rDAMAGEc*rFRAGc + 155*rFRAGc*rSPOTc + 75*rDEFc*rFRAGc + 145 * Math.min(1.8, rWINc); } private static Double scale2(Double toBeTruncated) { if (toBeTruncated == null || Double.isNaN(toBeTruncated)) { return null; } return BigDecimal.valueOf(toBeTruncated).setScale(2, RoundingMode.HALF_UP).doubleValue(); } }
true
0fa2e6d89e950e0d350b32b2478fdc176aca712e
Java
FeanorTheElf/Fractal
/src/simonUtil/complexMath/CMath.java
UTF-8
818
2.75
3
[]
no_license
package simonUtil.complexMath; public class CMath { public static ComplexNumber pow(ComplexNumber base, ComplexNumber exponent){ return ComplexNumber.fromPolar(Math.exp(-exponent.getImaginary() * base.getPhi()) * Math.pow(base.getR(), exponent.getReal()), exponent.getReal() * base.getPhi() + Math.log(base.getR()) * exponent.getImaginary()); } public static ComplexNumber sin(ComplexNumber that){ return ComplexNumber.fromCartesian(Math.sin(that.getReal()) * Math.cosh(that.getImaginary()), Math.cos(that.getReal()) * Math.sinh(that.getImaginary())); } public static ComplexNumber cos(ComplexNumber that){ return ComplexNumber.fromCartesian(Math.cos(that.getReal()) * Math.cosh(that.getImaginary()), -Math.sin(that.getReal()) * Math.sinh(that.getImaginary())); } }
true
ea901dc4b951121d806b2d34503798f3df204192
Java
Saddam-mentor/distill
/src/com/mentor/impl/CircularEntryImpl.java
UTF-8
7,812
2.03125
2
[]
no_license
package com.mentor.impl; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import javax.faces.application.FacesMessage; import javax.faces.context.FacesContext; import javax.faces.model.SelectItem; import com.mentor.action.CircularEntryAction; import com.mentor.datatable.CircularEntryDT; import com.mentor.resource.ConnectionToDataBase; import com.mentor.utility.Utility; public class CircularEntryImpl { public ArrayList getCircularDetail(){ ArrayList list = new ArrayList(); Connection con = null; PreparedStatement ps = null; ResultSet rs = null; String query=""; int i=0; try { query = "SELECT ndate, sn, newstext, type, links, description, category_id, " + " (select type from public.mst_category where category_id=id) as categorytype "+ " FROM public.news where sn not in ('0') order by sn"; con = ConnectionToDataBase.getConnection(); ps = con.prepareStatement(query); rs = ps.executeQuery(); while(rs.next()) { CircularEntryDT dt= new CircularEntryDT(); dt.setSrNo_int(rs.getInt("sn")); dt.setDate(rs.getDate("ndate")); dt.setHeading_str_dt(rs.getString("newstext")); dt.setDiscription_str_dt(rs.getString("description")); dt.setCategory_id(rs.getString("category_id")); dt.setCategory_type(rs.getString("categorytype")); if(rs.getString("links")!=null && rs.getString("links").length()>0) { dt.setPdf_str_dt(rs.getString("links")); }else{ dt.setPdf_str_dt("doc/ExciseUp/PdfHome/NA"); } list.add(dt); } } catch(Exception e) { e.printStackTrace(); } finally { try { if(con!=null)con.close(); if(ps!=null)ps.close(); if(rs!=null)rs.close(); } catch(Exception e) { e.printStackTrace(); } } return list; } public void saveImpl(CircularEntryAction act){ Connection con = null; PreparedStatement ps = null; String query=""; int saveStatus=0; try { ///ON CONFLICT ON CONSTRAINT customers_name_key query = "INSERT INTO public.news(ndate, sn, newstext, type, links, description, category_id ) VALUES (?, ?, ?, ?, ?, ?,?) " + " ON CONFLICT ON CONSTRAINT news_sn DO UPDATE SET ndate=?, newstext=?, links=?, description=? ,category_id=? " + " "; con = ConnectionToDataBase.getConnection(); ps = con.prepareStatement(query); ps.setDate(1, Utility.convertUtilDateToSQLDate(act.getCir_date())); ps.setInt(2, act.getSrNo()); ps.setString(3, act.getHeading_str()); ps.setString(4, "Y"); ps.setString(5, "/doc/ExciseUp/pdf/Circular_"+act.getSrNo()+".pdf"); ps.setString(6, act.getDiscription_str()); ps.setDate(8, Utility.convertUtilDateToSQLDate(act.getCir_date())); ps.setString(9, act.getHeading_str()); ps.setString(10, "/doc/ExciseUp/pdf/Circular_"+act.getSrNo()+".pdf"); ps.setString(11, act.getDiscription_str()); ps.setInt(7, Integer.parseInt(act.getCategory_id())); ps.setInt(12, Integer.parseInt(act.getCategory_id())); saveStatus=ps.executeUpdate(); System.out.println("====saveStatus===="+saveStatus); if(saveStatus>0){ FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Successfully Saved", "Successfully Saved")); }else{ con.rollback(); FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Not Saved !", "Not Saved !")); } } catch(Exception e) { e.printStackTrace(); } finally { try { if(con!=null)con.close(); if(ps!=null)ps.close(); } catch(Exception e) { e.printStackTrace(); } } } public int maxid(CircularEntryAction act){ Connection con = null; PreparedStatement ps = null; ResultSet rs = null; String query=""; int i=0; try { query = "SELECT max(sn) FROM public.news"; con = ConnectionToDataBase.getConnection(); ps = con.prepareStatement(query); System.out.println("==== "+query); rs = ps.executeQuery(); if(rs.next()) { i=rs.getInt(1)+1; } } catch(Exception e) { e.printStackTrace(); } finally { try { if(con!=null)con.close(); if(ps!=null)ps.close(); if(rs!=null)rs.close(); } catch(Exception e) { e.printStackTrace(); } } return i; } public void deleteMethod(int srNo){ Connection con = null; PreparedStatement ps = null; String query=""; int saveStatus=0; try { query = "DELETE FROM public.news WHERE sn="+srNo+" "; con = ConnectionToDataBase.getConnection(); ps = con.prepareStatement(query); saveStatus = ps.executeUpdate(); if(saveStatus>0){ FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Successfully Deleted", "Successfully Deleted")); }else{ FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Not Deleted !", "Not Deleted !")); } } catch(Exception e) { e.printStackTrace(); } finally { try { if(con!=null)con.close(); if(ps!=null)ps.close(); } catch(Exception e) { e.printStackTrace(); } } } public void update(CircularEntryAction act){ act.setModifyFlag(false); Connection con = null; PreparedStatement ps = null; String query=""; int saveStatus=0; System.out.println("sr no=="+act.getSrNo()); try { query = "UPDATE public.news SET ndate=?, sn=?, newstext=?, type=?, links=?, description=? WHERE sn="+ act.getSrNo()+" "; con = ConnectionToDataBase.getConnection(); ps = con.prepareStatement(query); ps.setDate(1, Utility.convertUtilDateToSQLDate(act.getCir_date())); ps.setInt(2, act.getSrNo()); ps.setString(3, act.getHeading_str()); ps.setString(4, "Y"); ps.setString(5, "/doc/ExciseUp/Distillery/NewsPdf/Circular_"+act.getSrNo()); ps.setString(6, act.getDiscription_str()); saveStatus = ps.executeUpdate(); if(saveStatus>0){ System.out.println("Updatee==="); }else{ System.out.println("Not Updatee==="); } } catch(Exception e) { e.printStackTrace(); } finally { try { if(con!=null)con.close(); if(ps!=null)ps.close(); } catch(Exception e) { e.printStackTrace(); } } } public ArrayList getcategorylist() { ArrayList list = new ArrayList(); Connection con = null; PreparedStatement ps = null; ResultSet rs = null; SelectItem item = new SelectItem(); item.setLabel("--Select--"); item.setValue("0"); list.add(item); String SQl = "SELECT id, type FROM public.mst_category "; try { System.out.println("========list=========" + SQl); con = ConnectionToDataBase.getConnection(); ps = con.prepareStatement(SQl); rs = ps.executeQuery(); while (rs.next()) { item = new SelectItem(); item.setLabel(rs.getString("type")); item.setValue(rs.getString("id")); list.add(item); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (con != null) con.close(); if (ps != null) ps.close(); if (rs != null) rs.close(); } catch (Exception e) { e.printStackTrace(); } } return list; } }
true
2a9e99ea6b0e7f7914e2cb08c7aa57f924267f04
Java
MUHAMMAD-SAQIB-2000/OOP-19011519-027
/InternatinalMorseCode/src/com/morse/Runner.java
UTF-8
1,289
3.640625
4
[]
no_license
package com.morse; import java.util.Scanner; import com.morse.decoder.Decoder; import com.morse.encoder.Encoder; public class Runner { static Scanner scan = new Scanner(System.in); public static void main(String[] args) { while(true) { menu(); } } private static void menu() { System.out.println("\n\nMorse Encoder and Decoder\n\n"); System.out.println("Enter Your Choice:"); System.out.println("1. Encode Into Morse Code"); System.out.println("2. Decode Morse Code"); System.out.println("3. Exit"); System.out.print("Choice:->"); char ch = scan.next().charAt(0); switch(ch) { case '1': scan.nextLine(); System.out.print("Enter statement:->"); String lineToBeEncoded = scan.nextLine(); String encodedResult = Encoder.encoder(lineToBeEncoded); System.out.println("Encoded Value is:->" + encodedResult); break; case '2': scan.nextLine(); System.out.print("Enter statement:->"); String lineToBeDecoded = scan.nextLine(); String decodedResult = Decoder.decoder(lineToBeDecoded); System.out.println("Decoded Value is:->" + decodedResult); break; case '3': System.out.println("Process Terminated!!!"); System.exit(0); break; default: System.out.println("Invalid Enter again!!!!!"); break; } } }
true
ed0c5c02dea0d4740fb2d154422d12f8aa462462
Java
CompileIO/compile.io
/Spring_Server/gs-uploading-files-complete/src/main/java/compile_io/docker/JavaBuilder.java
UTF-8
1,957
2.78125
3
[ "MIT" ]
permissive
package compile_io.docker; import java.io.*; import java.util.*; /** * This class builds a Dockerfile that the superclass uses to create a Docker image. */ public class JavaBuilder extends AbstractBuilder { public JavaBuilder(List<File> studentFiles, List<File> professorFiles, String codePath) { super(studentFiles, professorFiles, codePath); } public String getDockerfileData() { StringBuilder dockerfileData = new StringBuilder(); List<File> studentFiles = super.getStudentFiles(); List<File> professorFiles = super.getProfessorFiles(); dockerfileData.append("FROM gradle:4.3-jdk-alpine\n"); dockerfileData.append("WORKDIR " + super.getWorkingDirectory() + "\n"); dockerfileData.append("EXPOSE 8000\n"); dockerfileData.append("USER root\n"); dockerfileData.append("RUN mkdir -p src/main/java\n"); dockerfileData.append("RUN mkdir -p src/test/java\n"); dockerfileData.append("COPY build.gradle build.gradle\n"); for (int i = 0; i < super.getNumStudentFiles(); i++) { dockerfileData.append("COPY " + super.getCodePath() + "/" + studentFiles.get(i).getName() + " " + studentFiles.get(i).getName() + "\n"); dockerfileData.append("RUN mv " + studentFiles.get(i).getName() + " " + "src/main/java/\n"); } for (int i = 0; i < super.getNumProfessorFiles(); i++) { String professorFilePath = super.getCodePath().replaceFirst("student-files", "professor-files"); dockerfileData.append("COPY " + professorFilePath + "/" + professorFiles.get(i).getName() + " " + professorFiles.get(i).getName() + "\n"); dockerfileData.append("RUN mv " + professorFiles.get(i).getName() + " " + "src/test/java/\n"); } dockerfileData.append("CMD export GRADLE_USER_HOME=\"" + super.getWorkingDirectory() + "\" && gradle test\n"); return dockerfileData.toString(); } }
true
171facdcf6a4a76f3efd6702611d28c02a2d6f14
Java
elkattanman/Store-Application
/src/main/java/com/elkattanman/javafxapp/controllers/MainController.java
UTF-8
1,912
2.078125
2
[]
no_license
package com.elkattanman.javafxapp.controllers; import com.elkattanman.javafxapp.controllers.bars.ToolbarController; import com.elkattanman.javafxapp.controllers.basics.BasicsController; import com.elkattanman.javafxapp.controllers.transactions.TransactionsController; import com.jfoenix.controls.JFXDrawer; import com.jfoenix.controls.JFXHamburger; import com.jfoenix.controls.JFXTabPane; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.StackPane; import net.rgielen.fxweaver.core.FxWeaver; import net.rgielen.fxweaver.core.FxmlView; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.net.URL; import java.util.ResourceBundle; import static com.elkattanman.javafxapp.util.AssistantUtil.*; @Component @FxmlView("/FXML/main.fxml") public class MainController implements Initializable { @FXML private StackPane rootPane; @FXML public AnchorPane rootAnchorPane; @FXML public JFXTabPane mainTabPane; @FXML private JFXDrawer drawer; @FXML private JFXHamburger hamburger; @Autowired private FxWeaver fxWeaver; @Override public void initialize(URL url, ResourceBundle rb) { makeDraggable(rootPane); initComponents(); initDrawer(drawer, hamburger, fxWeaver.loadView(ToolbarController.class)); } private void initComponents() { mainTabPane.tabMinWidthProperty().bind(rootAnchorPane.widthProperty().divide(mainTabPane.getTabs().size()).subtract(15)); } @FXML void goToTransactions(ActionEvent event) { loadWindow(getStage(rootPane),fxWeaver.loadView(TransactionsController.class)); } public void goToBasics(ActionEvent actionEvent) { loadWindow(getStage(rootPane),fxWeaver.loadView(BasicsController.class)); } }
true
95396643d8e267fbf441840dce6f8eb4afbaf52a
Java
wdygj/interfaceTest
/src/main/java/reqeust/PostReq.java
UTF-8
6,232
2.453125
2
[]
no_license
package reqeust; import common.requestInf; import data.Data; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.message.BasicHeader; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * @author Guojun * */ public class PostReq { /** * application/x-www.form-urlencoded * */ public void httpClientPost2(String url,Map<String,Object> params) { CloseableHttpClient client = HttpClientBuilder.create().build(); //定义键值对列表,用于存放向url发送post请求的数据。 List<BasicNameValuePair> paramsForList = getPostParam2(params); //定义HttpPost对象并初始化它 HttpPost post = new HttpPost(url); //用UrlEncodedFormEntity对象包装请求体数据 CloseableHttpResponse response = null; try { HttpEntity reqEntity = new UrlEncodedFormEntity(paramsForList); //设置post请求实体 post.setEntity(reqEntity); //发送http请求 response = client.execute(post); int statusCode = response.getStatusLine().getStatusCode(); // 处理http返回码302的情况 HttpEntity entity = response.getEntity(); if ( statusCode== Data.redirect_Code) { //跳转到重定向的url String locationUrl = response.getLastHeader("Location").getValue(); System.out.println(locationUrl); } else { System.out.println(EntityUtils.toString(reqEntity)); //打印http请求返回码 System.out.println(statusCode); //打印出响应内容长度 System.out.println(entity.getContentLength()); //打印出响应实体 System.out.println("the response body is:" + EntityUtils.toString(entity)); } } catch (Exception e) { e.printStackTrace(); }finally { try { response.close(); client.close(); }catch (Exception e) { System.out.println("关闭发生异常"); e.printStackTrace(); } } } /** * Content-type:application/json * */ public requestInf httpClientPost1(String url,Map<String,Object> header , Map<String,Object> params) { requestInf requestInf = null; HttpClient client = HttpClientBuilder.create().build(); //定义一个JSON数据格式对象,用其保存请求主体数据。 JSONObject js = getPostParam1(params); HttpPost post = new HttpPost(url); try { //用StringEntity对象包装请求体数据 StringEntity reqEntity = new StringEntity(js.toString()); //设置请求头数据传输格式 reqEntity.setContentType("application/json"); //设置请求头 post.setHeaders(getHeaders(params)); //设置post请求实体 post.setEntity(reqEntity); //发送http请求 HttpResponse response = client.execute(post); HttpEntity responseEntity = response.getEntity(); requestInf.setReqHeader(header.toString()); System.out.println("the request body is:" + EntityUtils.toString(reqEntity)); //打印出请求实体 System.out.println(EntityUtils.toString(responseEntity)); //打印响应实体 System.out.println(response.getStatusLine().getStatusCode()); //打印http请求返回码 } catch (Exception e) { e.printStackTrace(); } return null; } /** *@Param: *@Return: *@Description:将map参数里的键值对取出用于初始化JSONObject并返回 *@Author:44244 *Date:2018/6/11 */ public JSONObject getPostParam1(Map<String,Object> mapParam) { JSONObject postParams = new JSONObject(); for (Map.Entry<String, Object> entry : mapParam.entrySet()) { //向postParams设置数据 postParams.accumulate(entry.getKey(), String.valueOf(entry.getValue())); } return postParams; } /** *@Param: *@Return: *@Description:将map参数里的键值对取出用于初始化BasicNameValuePair并返回 *@Author:44244 *Date:2018/6/11 */ public ArrayList<BasicNameValuePair> getPostParam2(Map<String,Object> mapParam) { ArrayList<BasicNameValuePair> postParams = new ArrayList<BasicNameValuePair>(); for (Map.Entry<String, Object> entry : mapParam.entrySet()) { postParams.add(new BasicNameValuePair(entry.getKey(), String.valueOf(entry.getValue()))); } return postParams; } /** *@Param: *@Return: *@Description:将map参数里的键值对取出用于初始化Header数组并返回 *@Author:44244 *Date:2018/6/11 */ public Header[] getHeaders(Map<String,Object> mapParam) { ArrayList<Header> postParams = new ArrayList<Header>(); for (Map.Entry<String, Object> entry : mapParam.entrySet()) { postParams.add(new BasicHeader(entry.getKey(), String.valueOf(entry.getValue()))); } return (Header[]) postParams.toArray(); } }
true
3873a8efd21c2e0ca6d63fd1bb77a42873030f69
Java
dither001/SLCC1400-Personal
/Traveller Worlds/version2/TradeGoods.java
UTF-8
754
2.5
2
[]
no_license
public class TradeGoods { String[] goods = { "Basic Electronics", "Basic Machine Parts", "Basic Mfg Goods", "Basic Raw Materials", "Basic Consumables", "Basic Ore", "Adv Electronics", "Adv Machine Parts", "Adv Mfg Goods", "Adv Weapons", "Adv. Vehicles", "Biochemicals", "Crystals and Gems", "Cybernetics", "Live Animals", "Luxury Consumables", "Luxury Goods", "Medical Supplies", "Petrochemicals", "Pharmaceuticals", "Polymers", "Precious Metals", "Radioactives", "Robots", "Spices", "Textiles", "Uncommon Ore", "Uncommon Raw Materials", "Wood", "Vehicles", "Illegal Biochemicals", "Illegal Cybernetics", "Illegal Drugs", "Illegal Luxuries", "Illegal Weapons", "Exotics" }; }
true
c3209e6c965a0ddccf54c55070939f5a3c81be88
Java
Java-Gyan-Mantra/spring-data-auditing
/src/main/java/com/javatechie/spring/auditing/api/controller/EmployeeController.java
UTF-8
1,128
2.1875
2
[]
no_license
package com.javatechie.spring.auditing.api.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import com.javatechie.spring.auditing.api.dto.InputRequest; import com.javatechie.spring.auditing.api.model.Employee; import com.javatechie.spring.auditing.api.service.EmployeeService; @RestController public class EmployeeController { @Autowired private EmployeeService service; @PostMapping("/addEmployee") public String saveEmployee(@RequestBody InputRequest<Employee> request) { return service.saveEmployee(request); } @PutMapping("/updateEmployee/{id}/{salary}") public String updateEmployeeSalary(@PathVariable int id, @PathVariable double salary, @RequestBody InputRequest<Employee> request) { return service.updateEmployee(id, salary, request); } }
true
8ab230bb356b10aeecfb9cc503b3edaab206f817
Java
Neutralizer/Data-Structures
/Tree/src/main/java/treeInterf/TreeInterf.java
UTF-8
215
2.1875
2
[]
no_license
package treeInterf; import treeImpl.ValueNotFoundException; public interface TreeInterf<V> { void addTreeValue(V value); V getTreeValue(V value) throws ValueNotFoundException; boolean isEmpty(); }
true
9a438e4b00989e7080fdda7387a5b721328c3826
Java
prashanthcvvp/p2j
/src/main/java/com/p2j/FileUploadController.java
UTF-8
1,079
1.976563
2
[]
no_license
package com.p2j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.InputStreamResource; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; @Controller public class FileUploadController { @Autowired private PdftoJpg pdfBox; @RequestMapping(value = "/convert", method = RequestMethod.GET) public @ResponseBody String uploadInfo() { return "Website Under Construction for P2J test"; } @RequestMapping(value = "/PDFServlet", method = RequestMethod.POST) public @ResponseBody ResponseEntity<InputStreamResource> handleFileUpload(@RequestParam("name") String name, @RequestParam("file") MultipartFile file) { return pdfBox.process(file); } }
true
c247851271f7fc7f751a68b509ee2b552df460aa
Java
betterfly4202/springboot-vue.js-bbs
/src/main/java/com/talsist/service/BoardService.java
UTF-8
2,902
2.0625
2
[]
no_license
package com.talsist.service; import javax.transaction.Transactional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.domain.Specifications; import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException; import org.springframework.security.core.AuthenticationException; import org.springframework.stereotype.Service; import com.talsist.domain.Board; import com.talsist.repository.BoardRepository; import com.talsist.repository.BoardSpecification; import com.talsist.repository.CommentRepository; import com.talsist.util.Pagination; import com.talsist.util.SecurityContextUtils; @Service public class BoardService { private BoardRepository boardRepo; private CommentRepository commentRepo; public BoardService(BoardRepository boardRepo, CommentRepository commentRepo) { this.boardRepo = boardRepo; this.commentRepo = commentRepo; } public Page<Board> findAll(Pageable pageable, Pagination pagination) { if (pagination.getKeyword() == null) { return boardRepo.findAll(pageable); } Page<Board> list = null; String keyword = pagination.getKeyword(); if (pagination.filterMatcher(Pagination.FilterType.ALL)) { list = boardRepo.findAll(Specifications.where(BoardSpecification.findByAll(keyword)), pageable); } else { list = boardRepo.findAll(Specifications.where(BoardSpecification.findByFilter(pagination)), pageable); } return list; } public void save(Board board) { board.setUser(SecurityContextUtils.getAuthenticatedUser()); boardRepo.save(board); } public void update(Long boardId, Board reqBoard) throws AuthenticationException { Board board = boardRepo.findOne(boardId); permissionCheck(board); board.Update(reqBoard); boardRepo.save(board); } public Board findOneAndHit(Long id) { Board board = boardRepo.findOne(id); board.increaseHit(); boardRepo.save(board); return board; } public Board findOneForMod(Long id) throws AuthenticationException { Board board = boardRepo.findOne(id); permissionCheck(board); return board; } @Transactional public void delete(Long boardId) { Board board = boardRepo.findOne(boardId); permissionCheck(board); commentRepo.delete(board.getComments()); boardRepo.delete(boardId); } private void permissionCheck(Board board) throws AuthenticationException { if (!board.verifyUser(SecurityContextUtils.getAuthenticatedUser().getId())) { throw new AuthenticationCredentialsNotFoundException("권한이 없습니다"); } } }
true
b219cad71f0918b44fffe996d683b764e0f0fb3f
Java
Becia09/ChoinkaJava
/Choinka.java
UTF-8
1,573
3.09375
3
[]
no_license
public class Choinka { public void choinka(int height) { height = height - 1; int baubleFront = 2; int baubleBack = (((height + 1) * 2) - 1) % 10; int longest = 0; String line; int i = 1; int j = 0; int counter = 0; String gap = " "; if (height < 4) { if (height == 2) { longest = 3; } else if (height == 3) { longest = 5; } } else { int level = height / 4; longest = 5 + (2 * level); } for (int k = 0; k < (( longest - 1) / 2); k++) { gap += " "; } System.out.println (gap + "1"); while (height > 0 ) { for (; i < 4 && height > 0; height--, i++, baubleFront++, baubleBack--) { j = i; line = "*"; gap = ""; while ((j + counter) > 1) { line += "**"; j--; } int gapLength = ((longest - line.length()) / 2); while (gapLength > 0) { gap += " "; gapLength--; } if (baubleFront == 10) { baubleFront = 0; } System.out.println (gap + baubleFront + line + baubleBack); if (baubleBack == 0) { baubleBack = 10; } } i = 0; counter++; } } }
true
4b9947714f421cdeaf34a3a2214fa9425fe07a93
Java
MakeThings/MakeThings
/ServiceCommunications/src/test/java/com/makethings/communication/rpc/json/DefaultJsonRpcHandlerTest.java
UTF-8
2,251
2.171875
2
[]
no_license
package com.makethings.communication.rpc.json; import static com.makethings.communication.support.FileHelper.readFromFilename; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.verify; import java.io.IOException; import org.hamcrest.CoreMatchers; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.runners.MockitoJUnitRunner; @RunWith(MockitoJUnitRunner.class) public class DefaultJsonRpcHandlerTest { private JsonServiceRequest request; private DefaultJsonRpcHandler handler; @Mock private TestIdeaService ideaService; private JsonServiceResponse response; @Before public void setUp() { handler = new DefaultJsonRpcHandler(); handler.setService(ideaService); handler.setServiceInterfaceClass(TestIdeaService.class); response = new JsonServiceResponse(); } @Test public void givenJsonRequestWhenHandleThenServiceMethodIsCalled() throws IOException { givenJsonRequest(); whenHandlingRequest(); thenCreateIdeamMethodIsInvoked(); } @Test public void givenResultOfServiceMethodWhenHandlingThenItShouldBeMarshaledIntoJson() throws IOException { givenJsonRequest(); givenServiceMethodResult(); whenHandlingRequest(); thenResultOfMethodCallIsMarshaledIntoJson(); } private void thenResultOfMethodCallIsMarshaledIntoJson() throws IOException { String actualJson = response.getOutputStream().toString(); Assert.assertThat(actualJson, CoreMatchers.equalTo(readFromFilename("/json/createIdeaJsonResponse.txt"))); } private void givenServiceMethodResult() { Mockito.when(ideaService.createNewIdea(eq("foo"))).thenReturn(100); } private void thenCreateIdeamMethodIsInvoked() { verify(ideaService).createNewIdea(eq("foo")); } private void whenHandlingRequest() { handler.handle(request, response); } private void givenJsonRequest() throws IOException { request = new JsonServiceRequest().withMessages(readFromFilename("/json/createIdeaServiceRequest.txt")); } }
true
4a7402061a7e4d77991646e0a288c7eb04190cbc
Java
dtaneja0818/AlgorithmsDSPractice
/DataStructuresPractice/src/LC_Easy/E0038_CountAndSay.java
UTF-8
972
3.84375
4
[]
no_license
package LC_Easy; /** Time Complexity - O(n * 2^n) Reason - n number of iteration and each successive number can have at most twice as many digits as the previous number [21 -> 1211] 2 will become 4 digits hence 2^n Space Complexity - O(2^n) Reason - generaed nth term for a number n can have a length of at most 2n. */ public class E0038_CountAndSay { public String countAndSay(int n) { String s = "1"; for(int i = 1; i < n; i++){ s = countIdx(s); } return s; } public String countIdx(String s){ StringBuilder sb = new StringBuilder(); char c = s.charAt(0); int count = 1; for(int i = 1; i< s.length(); i++){ if(s.charAt(i) == c){ count++; }else{ sb.append(count); sb.append(c); c = s.charAt(i); count = 1; } } return sb.append(count).append(c).toString(); } public static void main(String[] args) { E0038_CountAndSay cl = new E0038_CountAndSay(); System.out.println(cl.countAndSay(3)); } }
true
9ad428dd4a33c9e20e2d87f0781a196f67fa70af
Java
dstmath/OppoR15
/app/src/main/java/java/util/-$Lambda$AdCi8d-cQd1TrFsbt1AeYkjxVJo.java
UTF-8
3,728
2.671875
3
[]
no_license
package java.util; import java.util.function.Consumer; import java.util.function.DoubleConsumer; import java.util.function.IntConsumer; import java.util.function.LongConsumer; final /* synthetic */ class -$Lambda$AdCi8d-cQd1TrFsbt1AeYkjxVJo implements DoubleConsumer { private final /* synthetic */ byte $id; private final /* synthetic */ Object -$f0; /* renamed from: java.util.-$Lambda$AdCi8d-cQd1TrFsbt1AeYkjxVJo$1 */ final /* synthetic */ class AnonymousClass1 implements IntConsumer { private final /* synthetic */ byte $id; private final /* synthetic */ Object -$f0; private final /* synthetic */ void $m$0(int arg0) { ((Consumer) this.-$f0).accept(Integer.valueOf(arg0)); } private final /* synthetic */ void $m$1(int arg0) { ((Consumer) this.-$f0).accept(Integer.valueOf(arg0)); } private final /* synthetic */ void $m$2(int arg0) { ((Consumer) this.-$f0).accept(Integer.valueOf(arg0)); } public /* synthetic */ AnonymousClass1(byte b, Object obj) { this.$id = b; this.-$f0 = obj; } public final void accept(int i) { switch (this.$id) { case (byte) 0: $m$0(i); return; case (byte) 1: $m$1(i); return; case (byte) 2: $m$2(i); return; default: throw new AssertionError(); } } } /* renamed from: java.util.-$Lambda$AdCi8d-cQd1TrFsbt1AeYkjxVJo$2 */ final /* synthetic */ class AnonymousClass2 implements LongConsumer { private final /* synthetic */ byte $id; private final /* synthetic */ Object -$f0; private final /* synthetic */ void $m$0(long arg0) { ((Consumer) this.-$f0).accept(Long.valueOf(arg0)); } private final /* synthetic */ void $m$1(long arg0) { ((Consumer) this.-$f0).accept(Long.valueOf(arg0)); } private final /* synthetic */ void $m$2(long arg0) { ((Consumer) this.-$f0).accept(Long.valueOf(arg0)); } public /* synthetic */ AnonymousClass2(byte b, Object obj) { this.$id = b; this.-$f0 = obj; } public final void accept(long j) { switch (this.$id) { case (byte) 0: $m$0(j); return; case (byte) 1: $m$1(j); return; case (byte) 2: $m$2(j); return; default: throw new AssertionError(); } } } private final /* synthetic */ void $m$0(double arg0) { ((Consumer) this.-$f0).accept(Double.valueOf(arg0)); } private final /* synthetic */ void $m$1(double arg0) { ((Consumer) this.-$f0).accept(Double.valueOf(arg0)); } private final /* synthetic */ void $m$2(double arg0) { ((Consumer) this.-$f0).accept(Double.valueOf(arg0)); } public /* synthetic */ -$Lambda$AdCi8d-cQd1TrFsbt1AeYkjxVJo(byte b, Object obj) { this.$id = b; this.-$f0 = obj; } public final void accept(double d) { switch (this.$id) { case (byte) 0: $m$0(d); return; case (byte) 1: $m$1(d); return; case (byte) 2: $m$2(d); return; default: throw new AssertionError(); } } }
true
ba77ecec8d891ac51e9e75a597ecdf69efa04f66
Java
CarltonYeung/Mashed-Tomatoes
/src/main/java/com/mashedtomatoes/http/ChangeEmailRequest.java
UTF-8
587
2.34375
2
[ "LicenseRef-scancode-public-domain", "CC0-1.0" ]
permissive
package com.mashedtomatoes.http; import javax.validation.constraints.Email; import javax.validation.constraints.NotEmpty; public class ChangeEmailRequest { private String newEmail; private String password; public ChangeEmailRequest() {} @NotEmpty @Email public String getNewEmail() { return newEmail; } public void setNewEmail(String newEmail) { this.newEmail = newEmail; } @NotEmpty public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
true
a6e6912cc5b1bf780bf6c4b4aec5e19727f75040
Java
cagiris/cellco
/CohoService/src/main/java/com/cagiris/coho/service/db/impl/HibernateStatisticsJob.java
UTF-8
1,561
2.171875
2
[]
no_license
/* * Copyright (c) 2015, Cagiris Pvt. Ltd. * All rights reserved. */ package com.cagiris.coho.service.db.impl; import org.hibernate.stat.Statistics; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.scheduling.annotation.Scheduled; import com.cagiris.coho.service.db.api.DatabaseManagerException; import com.cagiris.coho.service.db.api.IDatabaseManager; import com.cagiris.coho.service.exception.JobExecutionException; import com.cagiris.coho.service.jobs.IJob; /** * * @author: ssnk */ public class HibernateStatisticsJob implements IJob { private Logger logger = LoggerFactory.getLogger("statistics"); private IDatabaseManager datbaseManager; public HibernateStatisticsJob(IDatabaseManager databaseManager) { this.datbaseManager = databaseManager; } @Scheduled(fixedDelay = 30 * 1000, initialDelay = 60 * 1000) @Override public void executeJob() throws JobExecutionException { logger.info("Fetching hibernate statistics"); try { Statistics statistics = datbaseManager.getSessionFactory().getStatistics(); logger.info("Second level cache stats"); logger.info(" Fetch count:{}, Hit Count:{}, Miss Count:{}, Put Count", statistics.getEntityFetchCount(), statistics.getSecondLevelCacheHitCount(), statistics.getSecondLevelCacheMissCount(), statistics.getSecondLevelCachePutCount()); } catch (DatabaseManagerException e) { logger.error("Error", e); } } }
true
63db936196966395cbfe00b7fb50e83f20ee91f5
Java
dlutz2/opensextant-utils
/src/org/opensextant/lr/tools/GoogleGramAggregrator.java
UTF-8
3,753
2.6875
3
[ "Apache-2.0" ]
permissive
package org.opensextant.lr.tools; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.util.zip.ZipEntry; import java.util.zip.ZipException; import java.util.zip.ZipFile; public class GoogleGramAggregrator { /** * @param args */ public static void main(String[] args) { File indir = new File(args[0]); File outFile = new File(args[1]); // the basename of the 2009 google n-gram files String fileNameBase = "googlebooks-eng-all-1gram-20090715-"; BufferedWriter out = null; try { out = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(outFile), "UTF-8")); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } catch (FileNotFoundException e1) { e1.printStackTrace(); } String line = ""; long linesRead = 0L; long linesWritten = 0L; String currentGram = "Unigram"; long totalGramCount = 0L; long totalPageCount = 0L; long totalVolumeCount = 0L; int yearCount = 0; // loop over all 10 n-gram files for (int i = 0; i < 10; i++) { File gramFile = new File(indir, fileNameBase + i + ".csv.zip"); BufferedReader buff = null; ZipFile zf = null; try { zf = new ZipFile(gramFile); ZipEntry ze = (ZipEntry) zf.entries().nextElement(); buff = new BufferedReader(new InputStreamReader( zf.getInputStream(ze))); } catch (ZipException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } System.out.println("opening " + gramFile.getName()); // loop over the ngram file while (true) { try { line = buff.readLine(); } catch (IOException e) { e.printStackTrace(); } if (line == null) { break; } linesRead++; // tab separated String[] pieces = line.split("\t"); // gram<tab>year<tab>count<tab>numPages<tab>numVolumes String gram = pieces[0]; // String year = pieces[1]; long gramCount = Long.parseLong(pieces[2]); long pageCount = Long.parseLong(pieces[3]); long volumeCount = Long.parseLong(pieces[4]); if (gram.equals(currentGram)) { // accumulate totalGramCount = totalGramCount + gramCount; totalPageCount = totalPageCount + pageCount; totalVolumeCount = totalVolumeCount + volumeCount; yearCount++; } else { // write if (totalGramCount > 0L) { linesWritten++; try { out.write(currentGram + "\t" + totalGramCount + "\t" + totalPageCount + "\t" + totalVolumeCount + "\t" + yearCount); out.newLine(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }// else{ // System.err.println("Zero count for token " + // currentGram); // } currentGram = gram; totalGramCount = gramCount; totalPageCount = pageCount; totalVolumeCount = volumeCount; yearCount = 0; } }// end read loop try { out.flush(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }// end file set loop try { out.flush(); out.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("Read " + linesRead + ". Wrote " + linesWritten); } }
true
9ecdf5a78cfdc6640536a16c64228fd8e515b795
Java
MihailovJava/DaggerTest
/app/src/main/java/javainside/com/daggertest/di/IDaggerTestComponent.java
UTF-8
461
2.1875
2
[]
no_license
package javainside.com.daggertest.di; import javax.inject.Singleton; import dagger.Component; import javainside.com.daggertest.activity.MainActivity; import javainside.com.daggertest.model.Speaker; @Singleton @Component( modules = { DaggerTestImageModelModule.class, DaggerTestSpeakerModule.class } ) public interface IDaggerTestComponent { void inject(MainActivity mainActivity); Speaker speaker(); }
true
a9596b4804d51be46c98c9777c574def08fa1b5b
Java
ZYF99/RecommendFilm
/app/src/main/java/com/xxx/recommendfilm/ui/release/ReleaseViewModel.java
UTF-8
1,971
2.015625
2
[]
no_license
package com.xxx.recommendfilm.ui.release; import androidx.lifecycle.MutableLiveData; import com.xxx.recommendfilm.BuildConfig; import com.xxx.recommendfilm.model.ResultModel; import com.xxx.recommendfilm.model.UploadImageResultModel; import com.xxx.recommendfilm.model.moment.ReleaseMomentRequestModel; import com.xxx.recommendfilm.ui.base.BaseViewModel; import com.xxx.recommendfilm.util.ApiErrorUtil; import com.xxx.recommendfilm.util.RxUtil; import java.io.File; import io.reactivex.SingleSource; import io.reactivex.functions.Action; import io.reactivex.functions.Consumer; import io.reactivex.functions.Function; import okhttp3.MediaType; import okhttp3.MultipartBody; import okhttp3.RequestBody; import okhttp3.ResponseBody; public class ReleaseViewModel extends BaseViewModel { public MutableLiveData<String> inputContentData = new MutableLiveData(); public MutableLiveData<String> imgUrlLiveData = new MutableLiveData(); public void releaseMoment(Action action) { File file = new File(imgUrlLiveData.getValue()); RequestBody photoRequestBody = RequestBody.create(MediaType.parse("image/png"), file); MultipartBody.Part photo = MultipartBody.Part.createFormData( "imageFile", file.getName(), photoRequestBody ); bindLife( apiService.upLoadImage(photo) .flatMap((Function<ResultModel<UploadImageResultModel>, SingleSource<?>>) result -> apiService.releaseMoment(new ReleaseMomentRequestModel( inputContentData.getValue(), BuildConfig.BASE_URL + "/image/" + result.getData().getImagePath() ))).compose(RxUtil.switchThread()) .compose(ApiErrorUtil.dealError()) .doOnSuccess(o -> action.run()) ); } }
true
d96ff681079ff84e0fe525c11888efa3307fefc7
Java
tnscorcoran/wfswarm
/src/main/java/com/tutorialspoint/model/Book.java
UTF-8
884
2.53125
3
[]
no_license
package com.tutorialspoint.model; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement public class Book { private int id; private String serialNumber, title, author; public Book() { super(); } public Book(int id, String serialNumber, String title, String author) { super(); this.id = id; this.serialNumber = serialNumber; this.title = title; this.author = author; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getSerialNumber() { return serialNumber; } public void setSerialNumber(String serialNumber) { this.serialNumber = serialNumber; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } }
true
fcb74d8daf27256d5fc057c07b98ba2d8bab4e04
Java
noman720/sms
/SMS.Lib/src/main/java/com/csbl/sms/manager/impl/StudentManagerImpl.java
UTF-8
8,094
2.296875
2
[]
no_license
package main.java.com.csbl.sms.manager.impl; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import main.java.com.csbl.sms.bean.StudentBean; import main.java.com.csbl.sms.dao.IDAO; import main.java.com.csbl.sms.exception.SMSDataAccessException; import main.java.com.csbl.sms.manager.StudentManager; import main.java.com.csbl.sms.util.DatabaseConnection; import main.java.com.csbl.sms.util.IdGenerator; import main.java.com.csbl.sms.util.ReportUtil; import main.java.com.csbl.sms.util.TableName; import org.apache.log4j.Logger; public class StudentManagerImpl implements StudentManager { private Logger log = Logger.getLogger(this.getClass()); private IDAO generalDAOSpringJdbc; private IdGenerator idGenerator; private static Map param = new HashMap(); @Override public String saveStudent(StudentBean studentBean) { try { studentBean.setOid(idGenerator.generateOid()); String sqlPersonal = "insert into "+TableName.STD_PERSONALINFO+"(" + "oid, studentID, studentName, " + "fatherName, motherName, presentAddress, " + "permanentAddress, mobileNo, email, " + "gender, bloodGroup, birthDate, " + "pictureurl) " + "values (" + "?, ?, ?, " + "?, ?, ?, " + "?, ?, ?, " + "?, ?, ?, " + "?)"; String sqlAcademic = "insert into "+TableName.STD_ACADEMICINFO+" (" + "oid, classId, studentId, " + "academicYear, studentGroup, studentType, " + "medium, shift, sectionName, " + "classRoll) " + "values (" + "?, ?, ?, " + "?, ?, ?, " + "?, ?, ?, " + "?)"; Object[] objPersonal = new Object[] { studentBean.getOid(), studentBean.getStudentID(), studentBean.getStudentName(), studentBean.getFatherName(), studentBean.getMotherName(),studentBean.getPresentAddress(), studentBean.getPermanentAddress(), studentBean.getMobileNo(), studentBean.getEmail(), studentBean.getGender(), studentBean.getBlooldGroup(), studentBean.getBirthDate(), studentBean.getPictureurl() }; Object[] objAcademic = new Object[] { studentBean.getOid(), studentBean.getClassId(), studentBean.getStudentID(), studentBean.getAcademicYear(), studentBean.getStudentGroup(), studentBean.getStudentType(), studentBean.getMedium(),studentBean.getShift(), studentBean.getSectionName(), studentBean.getClassRoll() }; generalDAOSpringJdbc.save(sqlPersonal, objPersonal); generalDAOSpringJdbc.save(sqlAcademic, objAcademic); }catch(Exception e){ log.error("An Exception occured when save Student: ", e); return "Unable to Save Student"; } return "successful"; } @Override public List<StudentBean> getStudentList(String className, String year) { List<StudentBean> studentList = new ArrayList<>(); try { String sql = "select sp.studentId, classId, classRoll, studentName, mobileNo from "+TableName.STD_PERSONALINFO+" sp, "+TableName.STD_ACADEMICINFO+" sa where sp.studentId = sa.studentId and classId = ? and academicYear = ?"; Object [] object = new Object[]{className, year}; studentList = (List<StudentBean>) generalDAOSpringJdbc.getObjects(sql, StudentBean.class, object); } catch(NumberFormatException | SMSDataAccessException e) { log.error("An Exception occured when get Student List : ", e); return studentList; } return studentList; } @Override public StudentBean getStudentInfo(String classId, String studentId) { StudentBean studentBean = new StudentBean(); try { String sql = "select sp.studentId, studentName, fatherName, motherName, presentAddress, mobileNo, birthDate, academicYear, studentGroup, studentType, medium, shift, sectionName, classRoll from "+TableName.STD_PERSONALINFO+" sp, "+TableName.STD_ACADEMICINFO+" sa where sp.studentId = sa.studentId and classId = ? and sa.studentId = ?"; Object [] object = new Object[]{classId, studentId}; studentBean = (StudentBean) generalDAOSpringJdbc.getObjectBean(sql, StudentBean.class, object); } catch(Exception e) { log.error("An Exception occured when get Student Info : ", e); return studentBean; } return studentBean; } @Override public List<String> getShiftNameList(String classId) { List<String> shiftNameList = new ArrayList<>(); try { String sql = "select shift from "+TableName.SHIFT+" where classId = ? order by oid asc"; Object [] object = new Object[]{classId}; List<StudentBean> list = (List<StudentBean>) generalDAOSpringJdbc.getObjects(sql, StudentBean.class, object); for(StudentBean cb : list) { shiftNameList.add(cb.getShift()); } } catch(Exception e) { //e.printStackTrace(); log.error("An Exception occured when get Shift List : ", e); return shiftNameList; } return shiftNameList; } @Override public List<String> getSectionNameList(String classId) { List<String> shiftNameList = new ArrayList<>(); try { String sql = "select sectionName from "+TableName.SECTION+" where classId = ? order by oid asc"; Object [] object = new Object[]{classId}; List<StudentBean> list = (List<StudentBean>) generalDAOSpringJdbc.getObjects(sql, StudentBean.class, object); for(StudentBean cb : list) { shiftNameList.add(cb.getSectionName()); } } catch(Exception e) { //e.printStackTrace(); log.error("An Exception occured when get Section List : ", e); return shiftNameList; } return shiftNameList; } @Override public void showStudentByClass(String classId, String academicYear) { param.clear(); param.put("classId", classId); param.put("academicYear", academicYear); String fileSource = "report/student/StudentByClass.jasper"; ReportUtil.exportReport(fileSource, DatabaseConnection.getConnection(), param); } @Override public void showStudentInfoById(String classId, String studentId) { param.clear(); param.put("classId", classId); param.put("studentId", studentId); String fileSource = "report/student/StudentInfo.jasper"; ReportUtil.exportReport(fileSource, DatabaseConnection.getConnection(), param); } public IDAO getGeneralDAOSpringJdbc() { return generalDAOSpringJdbc; } public void setGeneralDAOSpringJdbc(IDAO generalDAOSpringJdbc) { this.generalDAOSpringJdbc = generalDAOSpringJdbc; } public IdGenerator getIdGenerator() { return idGenerator; } public void setIdGenerator(IdGenerator idGenerator) { this.idGenerator = idGenerator; } }
true
56e1101f6b163d8cab834aee5e32fa68ae637ab2
Java
cx147258/study
/src/cx/StringTest/MyString.java
UTF-8
4,479
3.796875
4
[]
no_license
package cx.StringTest; public class MyString { public static void main(String[] args){ /** * 字符串 & 字节数组转换 * getBytes */ // String str = "hello world"; // byte date[] = str.getBytes();//字符串转字节数组 // String str2 = new String(date);//字节数组转字符串 // String str3 = new String(date,0,5);//部分字节数组转字符串 // System.out.println(str); // System.out.println(str2); // System.out.println(str3); /** * 字符串比较 * == * equals * equalsIgnoreCase * compareTo */ // String str1 = "hello world"; // String str2 = new String("hello world"); // String str3 = str2; // String str4 = "Hello World"; // System.out.println(str1==str2);// ==比较的是字符串的内存地址 // System.out.println(str1.equals(str2));//equals比较的是字符串的内容,区分大小写 // System.out.println(str2.equals(str3)); // System.out.println(str2.equals(str4)); // System.out.println(str2.equalsIgnoreCase(str4));//equalsIgnoreCase比较字符串的内容,不区分大小写 // System.out.println(str4.compareTo(str3));//依据字符串在字典中的顺序,比较字符串的大小 /** * 字符串查找 * contains * indexOf * lastIndexOf * startsWith * endsWith */ // boolean tmp = str4.contains("llo");//查找指定的子字符串是否存在 // System.out.println(tmp); // int index1 = str4.indexOf("o");//从头查找指定字符串的位置,找不到返回-1 // int index2 = str4.indexOf("ll"); // int index3 = str3.indexOf("q"); // System.out.println(index1); // System.out.println(index2); // System.out.println(index3); // int index1 = str4.indexOf("o",3);//从指定位置向后查找字符串,找不到返回-1 // System.out.println(index1); // int index1 = str4.lastIndexOf("o");//从后向前查找字符串的位置,找不到返回-1 // System.out.println(index1); // int index1 = str4.lastIndexOf("o",5);//从指定位置从后向前查找 // System.out.println(index1); // boolean tmp = str4.startsWith("Hel");//判断是否以指定字符串开头 // System.out.println(tmp); // boolean tmp = str4.startsWith("ll",2);//从指定位置判断是否以指定字符串开头 // System.out.println(tmp); // boolean tmp = str4.endsWith("dp");//判断是否以指定字符串结尾 // System.out.println(tmp); /** * 字符串替换 * replaceAll * replaceFirst */ // String str5 = "Hello World"; // System.out.println(str5); // System.out.println(str5.replaceAll("o","_"));//全部替换 // System.out.println(str5.replaceFirst("o","_"));//替换首个 /** * 字符串截取 * substring */ String str6 = "20013000901"; System.out.println(str6.substring(9));//从指定位置截取到结尾 System.out.println(str6.substring(0,9));//截取指定范围的内容 /** * 字符串拆分 * split */ // String str7 = "Hello World hello world !!!"; // String s[] = str7.split(" ");//按照指定的字符串全拆分 // for(int i = 0; i < s.length; i++){ // System.out.println(s[i]); // } // String s1[] = str7.split(" ",2);//拆分为指定段数 // for(int i = 0; i < s1.length; i++){ // System.out.println(s1[i]); // } /** * 其他方法 * isEmpty 判空 * length 长度 * trim 去空格 * toLowerCase 转小写 * toUpperCase 转大写 */ // String str7 = " Hello World hello world !!! "; // System.out.println(str7); // System.out.println(str7.isEmpty());//判断是否为空字符串 // System.out.println(str7.length());//取得字符串长度 // System.out.println(str7.trim());//去掉左右空格 // System.out.println(str7.toLowerCase());//全部字符串转小写 // System.out.println(str7.toUpperCase());//全部字符串转大写 // System.out.println(str7.concat(" *** "));//字符串连接 } }
true
a2ef1eda785eeb3ec3a00f1cbb7040c56f8d44dd
Java
canislepus/fop
/Übungen/src/hospital/Main.java
UTF-8
310
1.617188
2
[]
no_license
package hospital; import hospital.patients.TestPatientQueue; public class Main { public static void main(String[] args) { TestPatientQueue tester = new TestPatientQueue(); tester.validateGetCatInfo(); tester.validateGetPriority(); tester.validateCompareTo(); tester.validateProcessQueue(); } }
true
ab144e932d4623a925ae554eb7f6c48c73de733c
Java
arthurcordova/pele-medical-center-android
/app/src/main/java/com/mobway/pelemedicalcenter/models/Consult.java
UTF-8
815
2.328125
2
[]
no_license
package com.mobway.pelemedicalcenter.models; import com.google.gson.annotations.SerializedName; import java.io.Serializable; /** * Created by arthur.stapassoli on 29/11/2017. */ public class Consult implements Serializable { @SerializedName("codProd") private String uuid; @SerializedName("descricao") private String description; public Consult() { } public Consult(String uuid, String description) { this.uuid = uuid; this.description = description; } public String getUuid() { return uuid; } public void setUuid(String uuid) { this.uuid = uuid; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } }
true
d049012e5e82dd1170e6855bcd05a81ec0b15983
Java
Android-MI/AndroidFastFrame
/frame/src/main/java/com/fast/library/bean/I_POJO.java
UTF-8
518
2.171875
2
[]
no_license
package com.fast.library.bean; /** * 说明:实体对象模型 * @author xiaomi */ @SuppressWarnings("unchecked") public interface I_POJO { /** * 说明:获取类型 * @return */ String getType(); /** * 说明:json转bean * @param json * @param <T> * @return */ <T extends Object> T toBean(String json); /** * 说明:json转list * @param json * @param <T> * @return */ <T extends Object> T toList(String json); }
true
dbcad059a80a000eb0725cc2515827ec1b8fb6c5
Java
ChristianMarzianGithub/MAEDN-V2
/MAEDN-BusinesLogic/src/main/java/main/Game.java
ISO-8859-1
2,482
3.125
3
[]
no_license
package main; import java.util.ArrayList; public class Game { private ArrayList<Player> playerListe = new ArrayList<Player>(); public Phase phase = Phase.Wuerfeln; private Board board; public Game() { playerListe.add(new Player(Farbe.blau,39)); playerListe.add(new Player(Farbe.rot,39)); playerListe.add(new Player(Farbe.gelb,39)); playerListe.add(new Player(Farbe.gruen,39)); setBoard(new Board()); } public WuerfelResult wuerfeln() { phase = Phase.Setzen; WuerfelResult wr = new WuerfelResult(); wr.setResult((int) (Math.random() * 6 + 1)); return wr; } public ArrayList<Player> getPlayerListe() { return playerListe; } public void setPlayerListe(ArrayList<Player> playerListe) { this.playerListe = playerListe; } public int figurSetzen(int zuWuerfelndeZahl, int indexVonSpielerDerMomentanDranIst, String position) { // TODO Auto-generated method stub Figur f = playerListe.get(indexVonSpielerDerMomentanDranIst).getFigurenListe().get(1); f.setPosition(f.getPosition() + zuWuerfelndeZahl); return getNaechstenSpieler(indexVonSpielerDerMomentanDranIst, zuWuerfelndeZahl); } private int getNaechstenSpieler(int indexVonSpielerDerMomentanDranIst, int zuWuerfelndeZahl) { int naechsterSpieler = indexVonSpielerDerMomentanDranIst; if(zuWuerfelndeZahl != 6) {//bei einer 6 darf man nochmal wuerfeln if(indexVonSpielerDerMomentanDranIst == 3) { naechsterSpieler = 0; }else { naechsterSpieler = indexVonSpielerDerMomentanDranIst + 1; } } return naechsterSpieler; } public void gibPositionenAllerFigurenAus(int gewuerfelteZahl) { System.out.println("gewrfelte Zahl: " + gewuerfelteZahl + " \n"); for(Player player: playerListe) { System.out.println("Player: " + playerListe.indexOf(player)); for(Figur figur: player.getFigurenListe()) { System.out.println("Figur: " + player.getFigurenListe().indexOf(figur)); System.out.println("Position: " + figur.getPosition()); } System.out.println(""); } } public Board getBoard() { return board; } public void setBoard(Board board) { this.board = board; } /* @Override public String toString() { return String.format( "Movie[id='%d', name='%s', genre='%s', bewertung='%s']", id,name,genre,bewertung ); } */ }
true
c7ec093090db8965aa4c655ef8ea2d88b9faa1ab
Java
palava/palava-core
/src/test/java/de/cosmocode/palava/core/inject/PropertiesConverterTest.java
UTF-8
4,356
2.015625
2
[ "Apache-2.0" ]
permissive
/** * Copyright 2010 CosmoCode GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.cosmocode.palava.core.inject; import java.util.Map; import java.util.Properties; import de.cosmocode.palava.core.aop.SuppressInject; import org.junit.Assert; import org.junit.Test; import com.google.common.collect.ImmutableMap; import com.google.inject.Binder; import com.google.inject.Guice; import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.Module; import com.google.inject.TypeLiteral; import com.google.inject.name.Named; import com.google.inject.name.Names; import de.cosmocode.junit.UnitProvider; /** * Tests {@link PropertiesConverter}. * * @author Willi Schoenborn */ @SuppressInject public final class PropertiesConverterTest implements UnitProvider<PropertiesConverter> { private static final TypeLiteral<Properties> LITERAL = TypeLiteral.get(Properties.class); @Override public PropertiesConverter unit() { return new PropertiesConverter(); } /** * Tests {@link PropertiesConverter#convert(String, TypeLiteral)} with a file. */ @Test public void file() { Assert.assertEquals(ImmutableMap.of("key", "value"), unit().convert( "file:src/test/resources/present.properties", LITERAL)); } /** * Tests {@link PropertiesConverter#convert(String, TypeLiteral)} with a classpath resource. */ @Test public void classpath() { Assert.assertEquals(ImmutableMap.of("key", "value"), unit().convert("classpath:present.properties", LITERAL)); } /** * Tests {@link PropertiesConverter#convert(String, TypeLiteral)} with an http url. */ @Test public void http() { final Properties actual = Properties.class.cast(unit().convert( "http://rocoto.googlecode.com/svn/tags/2.0/configuration/src/test/resources/log4j.properties", LITERAL)); Assert.assertEquals("ERROR", actual.getProperty("log4j.logger.java")); } /** * Tests {@link PropertiesConverter#convert(String, TypeLiteral)} with a missing file. */ @Test(expected = RuntimeException.class) public void fileMissing() { unit().convert("file:src/test/resources/missing.properties", LITERAL); } /** * Tests {@link PropertiesConverter#convert(String, TypeLiteral)} with a missing classpath resource. */ @Test(expected = RuntimeException.class) public void classpathMissing() { unit().convert("classpath:missing.properties", LITERAL); } /** * Tests {@link PropertiesConverter#convert(String, TypeLiteral)} with a missing http url. */ @Test(expected = RuntimeException.class) public void httpMissing() { unit().convert("http://lsdkfjslkfjslkfjslfkjsdlfkjsldfjksdoieruwfl.com/missing.properties", LITERAL); } /** * Static injectee class used by {@link PropertiesConverterTest#map()}. * * @since 2.7 * @author Willi Schoenborn */ static final class Injectee { @Inject public Injectee(@Named("file") Map<String, String> map) { Assert.assertTrue("value".equals(map.get("key"))); } } /** * Tests {@link PropertiesConverter} bindings for {@link Map} injection. */ @Test public void map() { final Injector injector = Guice.createInjector( new TypeConverterModule(), new Module() { @Override public void configure(Binder binder) { binder.bind(String.class).annotatedWith(Names.named("file")). toInstance("file:src/test/resources/present.properties"); } } ); injector.getInstance(Injectee.class); } }
true
441954e75281a2dbd7b8a0b8fcdd3dcaff9e6031
Java
goranstack/bluebrim
/FontShared/src/main/java/com/bluebrim/font/impl/server/truetype/CoTrueTypeNameRecord.java
UTF-8
3,066
2.453125
2
[ "Apache-2.0" ]
permissive
package com.bluebrim.font.impl.server.truetype; import java.io.*; import com.bluebrim.base.shared.*; /** * Representation of a record in the true type "name" table, for a string representation for a specific * platform, in a specific character encoding and language. * Creation date: (2001-05-21 16:22:06) * @author Magnus Ihse <magnus.ihse@appeal.se> */ public class CoTrueTypeNameRecord { private int m_platform; private int m_encoding; private int m_language; private int m_nameType; private int m_length; private int m_offset; private byte[] m_nameData; /** * CoTrueTypeNameRecord constructor comment. */ public CoTrueTypeNameRecord(InputStream ttStream) throws IOException { m_platform = CoNativeDataUtil.readUint16(ttStream); m_encoding = CoNativeDataUtil.readUint16(ttStream); m_language = CoNativeDataUtil.readUint16(ttStream); m_nameType = CoNativeDataUtil.readUint16(ttStream); m_length = CoNativeDataUtil.readUint16(ttStream); m_offset = CoNativeDataUtil.readUint16(ttStream); } /** * No_description_given_yet<|> * Creation date: (2001-05-21 16:27:49) * @param * @return * @author Magnus Ihse <magnus.ihse@appeal.se> * * @return int */ public int getEncoding() { return m_encoding; } /** * No_description_given_yet<|> * Creation date: (2001-05-21 16:27:49) * @param * @return * @author Magnus Ihse <magnus.ihse@appeal.se> * * @return int */ public int getLanguage() { return m_language; } /** * No_description_given_yet<|> * Creation date: (2001-05-21 16:27:49) * @param * @return * @author Magnus Ihse <magnus.ihse@appeal.se> * * @return int */ public int getLength() { return m_length; } /** * No_description_given_yet<|> * Creation date: (2001-05-21 16:27:49) * @param * @return * @author Magnus Ihse <magnus.ihse@appeal.se> * * @return int */ public int getNameType() { return m_nameType; } /** * No_description_given_yet<|> * Creation date: (2001-05-21 16:27:49) * @param * @return * @author Magnus Ihse <magnus.ihse@appeal.se> * * @return int */ public int getOffset() { return m_offset; } /** * No_description_given_yet<|> * Creation date: (2001-05-21 16:27:49) * @param * @return * @author Magnus Ihse <magnus.ihse@appeal.se> * * @return int */ public int getPlatform() { return m_platform; } public void setNameDataArea(byte[] nameData) { m_nameData = nameData; } public String toString() { String s = getStringRepresentation(); if (s != null) { return s; } else { return super.toString(); } } /** * Returns String representation, if NameData area has been set. May return null. */ public String getStringRepresentation() { if (m_nameData != null) { if (getPlatform() == 0 || getPlatform() == 3) { // Apple Unicode or Microsoft Unicode return CoNativeDataUtil.readDoubleBytesAsString(m_nameData, getOffset(), getLength()); } else if (getPlatform() == 1) { // Apple 8-bit // FIXME: should really take care of actual Mac encoding. Right now we just fall back to // whatever Java considers to be "platform default". return new String(m_nameData, getOffset(), getLength()); } // Other platforms are unknown and ignored } return null; } }
true
4c4d8450355f6fb94ab6a4cfb020e0b246099d29
Java
Azure/azure-sdk-for-java
/sdk/providerhub/azure-resourcemanager-providerhub/src/main/java/com/azure/resourcemanager/providerhub/models/LightHouseAuthorization.java
UTF-8
2,794
1.929688
2
[ "MIT", "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-unknown-license-reference", "LGPL-2.1-or-later", "CC0-1.0", "BSD-3-Clause", "UPL-1.0", "Apache-2.0", "LicenseRef-scancode-public-domain", "BSD-2-Clause", "LicenseRef-scancode-generic-cla" ]
permissive
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.providerhub.models; import com.azure.core.annotation.Fluent; import com.azure.core.util.logging.ClientLogger; import com.fasterxml.jackson.annotation.JsonProperty; /** The LightHouseAuthorization model. */ @Fluent public final class LightHouseAuthorization { /* * The principalId property. */ @JsonProperty(value = "principalId", required = true) private String principalId; /* * The roleDefinitionId property. */ @JsonProperty(value = "roleDefinitionId", required = true) private String roleDefinitionId; /** Creates an instance of LightHouseAuthorization class. */ public LightHouseAuthorization() { } /** * Get the principalId property: The principalId property. * * @return the principalId value. */ public String principalId() { return this.principalId; } /** * Set the principalId property: The principalId property. * * @param principalId the principalId value to set. * @return the LightHouseAuthorization object itself. */ public LightHouseAuthorization withPrincipalId(String principalId) { this.principalId = principalId; return this; } /** * Get the roleDefinitionId property: The roleDefinitionId property. * * @return the roleDefinitionId value. */ public String roleDefinitionId() { return this.roleDefinitionId; } /** * Set the roleDefinitionId property: The roleDefinitionId property. * * @param roleDefinitionId the roleDefinitionId value to set. * @return the LightHouseAuthorization object itself. */ public LightHouseAuthorization withRoleDefinitionId(String roleDefinitionId) { this.roleDefinitionId = roleDefinitionId; return this; } /** * Validates the instance. * * @throws IllegalArgumentException thrown if the instance is not valid. */ public void validate() { if (principalId() == null) { throw LOGGER .logExceptionAsError( new IllegalArgumentException( "Missing required property principalId in model LightHouseAuthorization")); } if (roleDefinitionId() == null) { throw LOGGER .logExceptionAsError( new IllegalArgumentException( "Missing required property roleDefinitionId in model LightHouseAuthorization")); } } private static final ClientLogger LOGGER = new ClientLogger(LightHouseAuthorization.class); }
true
f6c321a3dd58fc327a1558e047ea602ff3d56d2d
Java
takagotch/java
/api/THIsXxx.java
UTF-8
1,054
3.078125
3
[]
no_license
//public static boolean interrupted() //public boolean isInterrupted() //public final boolean isAlive() //public final void checkAccess() //public static boolean holdsLock(Object obj) //public final boolean isDaemon() public class THIsXxxSample extends Thread { public static void main(String[] args){ THIsXxxSample t = new THIsXxxSample("thread"); System.out.println("getState: " + t.getState().toString()); t.start(); t.join(); System.out.println("getState: " + t.getState().toString()); } public THIsXxxSample(String name){ super(name); } public void run(){ System.out.println("holdsLock: " + Thread.holdsLock(new Obj());); System.out.println("interrupted" + Thread.interrupted()); System.out.println("isAlive: " + isAlive()); System.out.println("isDaemon: " + isDaemon()); System.out.println("isInterrupted: " + isInterrupted()); System.out.println("getState: " + getState().toString()); } } class Obj { private int value = 1; public int getValue(){ return this.value; } }
true
2f6ae70f57e3551c7e2c663052b296497200a2c3
Java
DZYzhong/trpc
/trpc-server/src/main/java/com/github/sofn/trpc/server/netty/TNettyServer.java
UTF-8
4,364
2.15625
2
[ "Apache-2.0" ]
permissive
package com.github.sofn.trpc.server.netty; import com.github.sofn.trpc.core.exception.TRpcException; import com.github.sofn.trpc.core.utils.Threads; import io.netty.bootstrap.ServerBootstrap; import io.netty.buffer.PooledByteBufAllocator; import io.netty.channel.*; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.util.concurrent.DefaultThreadFactory; import org.apache.thrift.server.TServer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; /** * Thrift NIO Server base on Netty. */ public class TNettyServer extends TServer { private static Logger logger = LoggerFactory.getLogger(TNettyServer.class); private NettyServerArgs args; private EventLoopGroup bossGroup; private EventLoopGroup workerGroup; private ExecutorService userThreadPool; private ChannelFuture f; public TNettyServer(NettyServerArgs args) { super(args); this.args = args; } @Override public void serve() { logger.info("Netty Server is starting"); args.validate(); ServerBootstrap b = configServer(); try { // start server if (args.ip != null && args.ip.length() > 0) { f = b.bind(args.ip, args.port).sync(); } else { f = b.bind(args.port).sync(); } logger.info("Netty Server started and listening on " + args.port); setServing(true); // register shutown hook Runtime.getRuntime().addShutdownHook(new ShutdownThread()); } catch (Exception e) { logger.error("Exception happen when start server", e); throw new TRpcException(e); } } /** * blocking to wait for close. */ public void waitForClose() throws InterruptedException { f.channel().closeFuture().sync(); } @Override public void stop() { logger.info("Netty server is stopping"); bossGroup.shutdownGracefully(); Threads.gracefulShutdown(userThreadPool, args.shutdownTimeoutMills, args.shutdownTimeoutMills, TimeUnit.SECONDS); workerGroup.shutdownGracefully(); logger.info("Netty server stoped"); } private ServerBootstrap configServer() { bossGroup = new NioEventLoopGroup(args.bossThreads, new DefaultThreadFactory("NettyBossGroup", true)); workerGroup = new NioEventLoopGroup(args.workerThreads, new DefaultThreadFactory("NettyWorkerGroup", true)); userThreadPool = Executors.newFixedThreadPool(args.userThreads, new DefaultThreadFactory("UserThreads", true)); final ThriftHandler thriftHandler = new ThriftHandler(this.processorFactory_, this.inputProtocolFactory_, this.outputProtocolFactory_, userThreadPool); ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .childOption(ChannelOption.SO_REUSEADDR, true).childOption(ChannelOption.SO_KEEPALIVE, true) .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); if (args.socketTimeoutMills > 0) { b.childOption(ChannelOption.SO_TIMEOUT, args.socketTimeoutMills); } if (args.recvBuff > 0) { b.childOption(ChannelOption.SO_RCVBUF, args.recvBuff); } if (args.sendBuff > 0) { b.childOption(ChannelOption.SO_SNDBUF, args.sendBuff); } b.childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(createThriftFramedDecoder(), createThriftFramedEncoder(), thriftHandler); } }); return b; } private ChannelHandler createThriftFramedDecoder() { return new ThriftFramedDecoder(); } private ChannelHandler createThriftFramedEncoder() { return new ThriftFramedEncoder(); } class ShutdownThread extends Thread { @Override public void run() { TNettyServer.this.stop(); } } }
true
ec9781cd7da8ef1bbfb10fa0fbfe2a0f37a3f116
Java
ercasmo/mikado
/src/cr/tecnoware/sice/DAO/TransaccionEntranteDAO.java
UTF-8
27,658
1.78125
2
[]
no_license
package cr.tecnoware.sice.DAO; import cr.tecnoware.sice.applets.bean.AuditoriaChequeEntrante; import cr.tecnoware.sice.applets.bean.ChequeCorregido; import cr.tecnoware.sice.applets.bean.ChequesDigitalizados; import cr.tecnoware.sice.applets.bean.ConexionRemotaBean; import cr.tecnoware.sice.applets.bean.ParametrosGenerales; import cr.tecnoware.sice.applets.bean.TipoDocumento; import cr.tecnoware.sice.applets.bean.TransaccionEntrante; import cr.tecnoware.sice.applets.constantes.AplicacionConstantes; import cr.tecnoware.sice.applets.constantes.ChequeConstantes; import cr.tecnoware.sice.applets.constantes.ChequeDigitalizadoConstantes; import cr.tecnoware.sice.context.ApplicationParameters; import cr.tecnoware.sice.gestor_archivos.archivos.GestorArchivosFactory; import cr.tecnoware.sice.gestor_archivos.interfaces.GestorArchivos; import cr.tecnoware.sice.interfaz.ProcesarCamaraServices; import cr.tecnoware.sice.services.AsignarFirmasService; import cr.tecnoware.sice.utils.CacheUtils; import cr.tecnoware.sice.utils.DAOUtils; import cr.tecnoware.sice.utils.Utils; import cr.tecnoware.sice.utils.encryption.CryptoUtils; import cr.tecnoware.sice.utils.encryption.CryptoUtilsConstantes; import java.io.PrintStream; import java.sql.Connection; import java.sql.ResultSet; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.apache.log4j.Logger; public class TransaccionEntranteDAO extends DAO implements ProcesarCamaraServices { private final String findByQuerySql = "SELECT codigo_entidad_emisora,codigo_entidad_procesadora,codigo_oficina_cheque,cuenta_cheque,digito_control_cheque,fecha_camara,referencia_ibrn,referencia_imagen,monto_cheque,tipo_cheque,serial_cheque,id, codigo_banco_cheque, codigo_motivo_devolucion, estado, secuencia FROM cheque_entrante "; private final String findByQuerySqlHistorico = "SELECT codigo_entidad_emisora,codigo_entidad_procesadora,codigo_oficina_cheque,cuenta_cheque,digito_control_cheque,fecha_camara,referencia_ibrn,referencia_imagen,monto_cheque,tipo_cheque,serial_cheque,id, codigo_banco_cheque, codigo_motivo_devolucion FROM cheque_entrante_historico "; private final String insertIntoSql = "INSERT INTO cheque_entrante( codigo_banco_cheque, codigo_entidad_emisora, codigo_entidad_procesadora,codigo_moneda, codigo_oficina_cheque, cuenta_cheque, estado, fecha, fecha_camara,ibrn_interno,lote, monto_cheque, posicion_lote, referencia_imagen, secuencia, serial_cheque,tipo_cheque," + "codigo_motivo_devolucion,digito_control_cheque,id_archivo_procesado,referencia_entidad_emisora,referencia_ibrn,proceso_devolucion,tipo_devolucion,estado_lecto02,usuario_revisor) "; private final String updateQuery = " UPDATE CHEQUE_ENTRANTE SET "; public TransaccionEntranteDAO() { super(); } public List<TransaccionEntrante> findAllByQuery(String query) { try { Statement st = super.getConnection().createStatement(); ResultSet rs = st.executeQuery(findByQuerySql + " " + query); List<TransaccionEntrante> listado = new ArrayList<TransaccionEntrante>(); while (rs.next()) { TransaccionEntrante transaccion = new TransaccionEntrante(); transaccion.setEntidadEmisora(rs.getInt(1)); transaccion.setEntidadProcesadora(rs.getInt(2)); transaccion.setCodigoOficina(rs.getInt(3)); transaccion.setCuenta(rs.getString(4)); transaccion.setDigitoChequeo(rs.getInt(5)); transaccion.setFecha(rs.getTimestamp(6)); transaccion.setReferenciaIBRN(rs.getString(7)); transaccion.setImage(rs.getString(8)); transaccion.setMonto(rs.getDouble(9)); transaccion.setTc(rs.getInt(10)); transaccion.setSerial(rs.getString(11)); transaccion.setId(rs.getInt(12)); transaccion.setMotivoDevolucion(rs.getInt(14)); transaccion.setEntidadCheque(rs.getInt(13)); transaccion.setEstado(rs.getInt(14)); transaccion.setSecuencia(rs.getInt("secuencia")); listado.add(transaccion); } return listado; } catch (Exception e) { super.getLogger().error(e); return null; } finally { super.closeConnection(); } } public List<TransaccionEntrante> findAllByQuery2(String query, int limit) { try { String findByQuerySql2 = "SELECT top(" + limit + ") codigo_entidad_emisora,codigo_entidad_procesadora,codigo_oficina_cheque,cuenta_cheque,digito_control_cheque,fecha_camara,referencia_ibrn,referencia_imagen,monto_cheque,tipo_cheque,serial_cheque,id, codigo_banco_cheque, codigo_motivo_devolucion, estado,lote, secuencia FROM cheque_entrante "; // String findByQuerySql2 = // "SELECT codigo_entidad_emisora,codigo_entidad_procesadora,codigo_oficina_cheque,cuenta_cheque,digito_control_cheque,fecha_camara,referencia_ibrn,referencia_imagen,monto_cheque,tipo_cheque,serial_cheque,id, codigo_banco_cheque, codigo_motivo_devolucion, estado,lote, secuencia FROM cheque_entrante "; // "SELECT codigo_entidad_emisora,codigo_entidad_procesadora,codigo_oficina_cheque,cuenta_cheque,digito_control_cheque,fecha_camara,referencia_ibrn,referencia_imagen,monto_cheque,tipo_cheque,serial_cheque,id, codigo_banco_cheque, codigo_motivo_devolucion, estado, lote, secuencia FROM cheque_entrante "; // String findByQuerySql2 = // "SELECT codigo_entidad_emisora,codigo_entidad_procesadora,codigo_oficina_cheque,cuenta_cheque,digito_control_cheque,fecha_camara,referencia_ibrn,referencia_imagen,monto_cheque,tipo_cheque,serial_cheque,id, codigo_banco_cheque, codigo_motivo_devolucion, estado FROM cheque_entrante "; Statement st = super.getConnection().createStatement(); ResultSet rs = st.executeQuery(findByQuerySql2 + " " + query); List<TransaccionEntrante> listado = new ArrayList<TransaccionEntrante>(); while (rs.next()) { TransaccionEntrante transaccion = new TransaccionEntrante(); transaccion.setEntidadEmisora(rs.getInt(1)); transaccion.setEntidadProcesadora(rs.getInt(2)); transaccion.setCodigoOficina(rs.getInt(3)); transaccion.setCuenta(rs.getString(4)); transaccion.setDigitoChequeo(rs.getInt(5)); transaccion.setFecha(rs.getTimestamp(6)); transaccion.setReferenciaIBRN(rs.getString(7)); transaccion.setImage(rs.getString(8)); transaccion.setMonto(rs.getDouble(9)); transaccion.setTc(rs.getInt(10)); transaccion.setSerial(rs.getString(11)); transaccion.setId(rs.getInt(12)); transaccion.setMotivoDevolucion(rs.getInt(14)); transaccion.setEntidadCheque(rs.getInt(13)); transaccion.setEstado(rs.getInt(14)); transaccion.setLote(rs.getInt("lote")); transaccion.setSecuencia(rs.getInt("secuencia")); listado.add(transaccion); } return listado; } catch (Exception e) { super.getLogger().error(e); e.printStackTrace(); return null; } finally { super.closeConnection(); } } public List<TransaccionEntrante> findAllByQueryHistorico(String query) { try { System.out.println(findByQuerySqlHistorico + query); Statement st = super.getConnection().createStatement(); ResultSet rs = st.executeQuery(findByQuerySqlHistorico + " " + query); List<TransaccionEntrante> listado = new ArrayList<TransaccionEntrante>(); while (rs.next()) { TransaccionEntrante transaccion = new TransaccionEntrante(); transaccion.setEntidadEmisora(rs.getInt(1)); transaccion.setEntidadProcesadora(rs.getInt(2)); transaccion.setCodigoOficina(rs.getInt(3)); transaccion.setCuenta(rs.getString(4)); transaccion.setDigitoChequeo(rs.getInt(5)); transaccion.setFecha(rs.getTimestamp(6)); transaccion.setReferenciaIBRN(rs.getString(7)); transaccion.setImage(rs.getString(8)); transaccion.setMonto(rs.getDouble(9)); transaccion.setTc(rs.getInt(10)); transaccion.setSerial(rs.getString(11)); transaccion.setId(rs.getInt(12)); transaccion.setMotivoDevolucion(rs.getInt(14)); transaccion.setEntidadCheque(rs.getInt(13)); listado.add(transaccion); } return listado; } catch (Exception e) { super.getLogger().error(e); return null; } finally { super.closeConnection(); } } public TransaccionEntrante findByQuery(String whereClausele) { try { String query = this.findByQuerySql + " "; Statement st = super.getConnection().createStatement(); ResultSet rs = st.executeQuery(query); if (rs.next()) { TransaccionEntrante transaccion = new TransaccionEntrante(); transaccion.setEntidadEmisora(rs.getInt(1)); transaccion.setEntidadProcesadora(rs.getInt(2)); transaccion.setCodigoOficina(rs.getInt(3)); transaccion.setCuenta(rs.getString(4)); transaccion.setDigitoChequeo(rs.getInt(5)); transaccion.setFecha(rs.getTimestamp(6)); transaccion.setReferenciaIBRN(rs.getString(7)); transaccion.setImage(rs.getString(8)); transaccion.setMonto(rs.getDouble(9)); transaccion.setTc(rs.getInt(10)); transaccion.setSerial(rs.getString(11)); transaccion.setId(rs.getInt(12)); transaccion.setMotivoDevolucion(rs.getInt(14)); transaccion.setEntidadCheque(rs.getInt(13)); return transaccion; } else return null; } catch (Exception e) { super.getLogger().error(e); return null; } finally { super.closeConnection(); } } public boolean updateImage(TransaccionEntrante transaccion) { try { String query = "UPDATE cheque_entrante SET referencia_imagen='" + transaccion.getImage() + "'"; if (transaccion.getEstado() != ChequeConstantes.CHEQUE_ENTRANTE_PENDIENTE_INTERCAMBIO_CCE) query += ",estado=" + ChequeConstantes.CHEQUE_ENTRANTE_PENDIENTE_APLICAR_CORE; query += " WHERE id=" + transaccion.getId(); Statement st = super.getConnection().createStatement(); st.executeUpdate(query); return true; } catch (Exception e) { super.getLogger().error(e); return false; } finally { super.closeConnection(); } } public boolean updateMotivoDevolucion(TransaccionEntrante transaccion) { try { int bit = (transaccion.getMotivoDevolucion() == 0) ? AplicacionConstantes.REVISION_FIRMAS_ESTADO_REVISADO : AplicacionConstantes.CHEQUE_ENTRANTE_FORMA_FIRMA_RECHAZADA; String query = "UPDATE cheque_entrante SET codigo_motivo_devolucion=" + transaccion.getMotivoDevolucion() + " , firma_revisada=" + bit + " WHERE id=" + transaccion.getId(); Statement st = super.getConnection().createStatement(); st.executeUpdate(query); return true; } catch (Exception e) { super.getLogger().error(e); return false; } finally { super.closeConnection(); } } public boolean updateMotivoDevolucionFirma(TransaccionEntrante transaccion) { try { int bit = (transaccion.getMotivoDevolucion() == 0) ? AplicacionConstantes.REVISION_FIRMAS_ESTADO_REVISADO : AplicacionConstantes.CHEQUE_ENTRANTE_FORMA_FIRMA_RECHAZADA; String query = ""; String querySELECT = "SELECT codigo_motivo_devolucion as MOTIVO FROM cheque_entrante where id=" + transaccion.getId(); Statement st = super.getConnection().createStatement(); ResultSet rs = st.executeQuery(querySELECT); int codigoMotivoActual = 0; if (rs.next()) { codigoMotivoActual = rs.getInt("MOTIVO"); } if (codigoMotivoActual > 0) {// Solamente se marca el cheque como // firma revisada query = "UPDATE cheque_entrante SET firma_revisada=" + AplicacionConstantes.REVISION_FIRMAS_ESTADO_REVISADO + " WHERE id=" + transaccion.getId(); } else { if ((transaccion.getTc() == ChequeConstantes.CHEQUE_CAJA || transaccion.getTc() == ChequeConstantes.CHEQUE_CERTIFICADO) && (bit == AplicacionConstantes.CHEQUE_ENTRANTE_FORMA_FIRMA_RECHAZADA)) { query = "UPDATE cheque_entrante SET codigo_motivo_devolucion=" + transaccion.getMotivoDevolucion() + " , firma_revisada=" + bit + ",proceso_devolucion=" + AplicacionConstantes.PROCESO_DEVOLUCION_FIRMA + ",estado=" + ChequeConstantes.CHEQUE_ENTRANTE_RECHAZADO + " WHERE id=" + transaccion.getId(); } else { query = "UPDATE cheque_entrante SET codigo_motivo_devolucion=" + transaccion.getMotivoDevolucion() + " , firma_revisada=" + bit + ",proceso_devolucion=" + AplicacionConstantes.PROCESO_DEVOLUCION_FIRMA + " WHERE id=" + transaccion.getId(); } } st.executeUpdate(query); return true; } catch (Exception e) { super.getLogger().error(e); return false; } finally { super.closeConnection(); } } public boolean updateReferenciasArchivo(TransaccionEntrante transaccion, int idReferenciaCaja, int posicionLote) { try { String query = "UPDATE cheque_entrante SET id_archivador=" + idReferenciaCaja + " , posicion_lote=" + posicionLote + " WHERE id=" + transaccion.getId(); Statement st = super.getConnection().createStatement(); st.executeUpdate(query); return true; } catch (Exception e) { super.getLogger().error(e); return false; } finally { super.closeConnection(); } } public int buscarDuplicados(ChequesDigitalizados cheque, int codigoEntidad) { int salida = 0; try { String query = "select lote,secuencia from cheque_entrante where referencia_ibrn='" + cheque.getReferenciaIbrn() + "'"; Statement st = super.getConnection().createStatement(); ResultSet rs = st.executeQuery(query); boolean enc = false; int lote = -1, secuencia = -1; if (rs.next()) { lote = rs.getInt("lote"); secuencia = rs.getInt("secuencia"); enc = true; } if (enc) { if (lote == cheque.getIdLote() && secuencia == cheque.getPosicionLote()) // se // trata // exactamente // dle // mismo // registro // por // lo // cual // no // se // toma // como // duplicado salida = 1; else salida = 2; } } catch (Exception e) { e.printStackTrace(); } finally { super.closeConnection(); } return salida; } public boolean registrarTransaccionesCorregidas(List<ChequesDigitalizados> transacciones, int codigoEntidad) { try { boolean valido = true; int numeroLoteAplicar=-1; int numeroLote = -1; if (transacciones != null && transacciones.size() > 0) { numeroLoteAplicar=transacciones.get(0).getIdLote(); ConexionRemotaBean miConexion = new ConexionRemotaBean(); GestorArchivos gestor; miConexion = CacheUtils.getConexionRemota(Utils.fillZerosLeft(codigoEntidad + "", 4), AplicacionConstantes.CONEXION_REPOSITORIO_IMAGENES_ENTRANTE); gestor = GestorArchivosFactory.obtenerGestor(miConexion); ChequesDigitalizadosDAO digitalizados = new ChequesDigitalizadosDAO(); ParametrosGenerales parametros = (new ParametrosGeneralesDAO()).obtenerParametrosSistema(); String fechaCamaraStr = parametros.getFechaCamara(); Lecto02DAO dao = new Lecto02DAO(); ArrayList<AuditoriaChequeEntrante> listaAuditorias = new ArrayList<AuditoriaChequeEntrante>(); // Se marcan los cheques certificados y cheques de caja como // recibidos. for (ChequesDigitalizados cheque : transacciones) { TipoDocumento reservado = CacheUtils.getTcs().get(Integer.parseInt(cheque.getCheque().getTipoCheque().trim())); if (!reservado.isBoleta()) { dao.establecerTipoCheque(cheque); cheque.setReferenciaUnica(Utils.construirReferenciaUnica(cheque, AplicacionConstantes.CAMARA_ENTRANTE, fechaCamaraStr)); } } // RevisarComportamiento de boletas AsignarFirmasService servicioAsignarFirmas = new AsignarFirmasService(); servicioAsignarFirmas.asignarFirmas((ArrayList<ChequesDigitalizados>) transacciones); for (ChequesDigitalizados cheque : transacciones) { TipoDocumento reservado = CacheUtils.getTcs().get(Integer.parseInt(cheque.getCheque().getTipoCheque().trim())); if (((cheque.getEstado() >= ChequeDigitalizadoConstantes.CHEQUE_APROBADO && cheque.getEstado() < ChequeDigitalizadoConstantes.CHEQUE_RECHAZADO) || (cheque.getEstado() >= ChequeDigitalizadoConstantes.CHEQUE_NO_EXISTE && cheque.getEstado() <= ChequeDigitalizadoConstantes.CHEQUE_CUENTA_INACTIVA)) && reservado != null && !reservado.isBoleta()) { String referenciaIBRN = Utils.fillZerosLeft("" + cheque.getCheque().getTipoCheque(), 4) + Utils.fillZerosLeft("" + cheque.getCheque().getCodigoBanco(), 4) + cheque.getCheque().getSerial() + cheque.getCheque().getCuenta(); cheque.setReferenciaIbrn(referenciaIBRN); int duplicado = buscarDuplicados(cheque, codigoEntidad); // se crea el query y se sube las imagenes respectivas if (duplicado == 0) { String directorio = Utils.obtenerRutaImagen(cheque); try { int res = 0; res = gestor.subirImagen(directorio, cheque.getReferenciaUnica() + ChequeConstantes.IMAGEN_ANVERSO, CryptoUtils.codificar(cheque.getImagenAnverso(), CryptoUtilsConstantes.METODO_AES)); if (res == 0) { super.getLogger().error("subiendo imagen Anverso " + cheque.getReferenciaUnica()); valido = false; continue; } else { res = gestor.subirImagen(directorio, cheque.getReferenciaUnica() + ChequeConstantes.IMAGEN_REVERSO, CryptoUtils.codificar(cheque.getImagenReverso(), CryptoUtilsConstantes.METODO_AES)); if (res == 0) { super.getLogger().error("subiendo imagen Reverso " + cheque.getReferenciaUnica()); valido = false; continue; } } } catch (Exception ee) { super.getLogger().info("Error subiendo Imagenes ", ee); valido = false; continue; } String query = DAOUtils.createInsertQueryEntrante(cheque, fechaCamaraStr); if (query != null) { query = insertIntoSql + query; try { Statement st = super.getConnection().createStatement(); st.executeUpdate(query); String querySelectAuditoria = "Select id from cheque_entrante WHERE referencia_ibrn='" + cheque.getReferenciaIbrn() + "'"; ResultSet rs = st.executeQuery(querySelectAuditoria); int idCheque = -1; if (rs.next()) { idCheque = rs.getInt("id"); } AuditoriaChequeEntrante auditoria = new AuditoriaChequeEntrante(cheque, AplicacionConstantes.ESTADO_APROBADO); auditoria.setIdTransaccion(idCheque); listaAuditorias.add(auditoria); } catch (Exception e) { e.printStackTrace(); valido = false; continue; } finally { super.closeConnection(); } } } else if (duplicado == 2) { cheque.setEstado(ChequeDigitalizadoConstantes.CHEQUE_DUPLICADO); } } else { numeroLote = cheque.getIdLote(); } if (cheque.getEstado() > ChequeDigitalizadoConstantes.CHEQUE_PENDIENTE_APROBAR && cheque.getEstado() != ChequeDigitalizadoConstantes.CHEQUE_TC_INVALIDO || reservado.isBoleta()) { digitalizados.actualizarChequeDigitalizado(cheque); } } if (numeroLote != -1) { LoteChequeDAO loteDAO = new LoteChequeDAO(); loteDAO.actualizarEstado(numeroLote, AplicacionConstantes.CAMARA_ENTRANTE, AplicacionConstantes.LOTE_ENTRANTE_CUADRADO); } AuditoriaTransaccionDAO daoAuditoria = new AuditoriaTransaccionDAO(); daoAuditoria.registrarListaAuditoriasEntrantes(listaAuditorias); Lecto02DAO lectoDao = new Lecto02DAO(); lectoDao.marcarRegistrosLote(); marcarChequesExcentos(numeroLoteAplicar); } return valido; } catch (Exception e) { System.out.println("registrando transacciones "); if (this.getConn() != null) super.closeConnection(); e.printStackTrace(); return false; } } @Override public boolean actualizarTransaccionesCorregidas(List<ChequesDigitalizados> transacciones, int codigoEntidad) { try { boolean valido = true; if (transacciones != null && transacciones.size() > 0) { ChequesDigitalizadosDAO digitalizados = new ChequesDigitalizadosDAO(); ArrayList<AuditoriaChequeEntrante> listaAuditorias = new ArrayList<AuditoriaChequeEntrante>(); Lecto02DAO dao = new Lecto02DAO(); // Se marcan los cheques certificados y cheques de caja como for (ChequesDigitalizados cheque : transacciones) { TipoDocumento reservado = CacheUtils.getTcs().get(Integer.parseInt(cheque.getCheque().getTipoCheque().trim())); if (!reservado.isBoleta()) { dao.establecerTipoCheque(cheque); } } for (ChequesDigitalizados cheque : transacciones) { TipoDocumento reservado = CacheUtils.getTcs().get(Integer.parseInt(cheque.getCheque().getTipoCheque().trim())); if (((cheque.getEstado() >= ChequeDigitalizadoConstantes.CHEQUE_APROBADO && cheque.getEstado() <= ChequeDigitalizadoConstantes.CHEQUE_RECHAZADO) || (cheque.getEstado() >= ChequeDigitalizadoConstantes.CHEQUE_NO_EXISTE && cheque.getEstado() <= ChequeDigitalizadoConstantes.CHEQUE_CUENTA_INACTIVA)) && reservado != null) { if (!reservado.isBoleta()) { // buscar Registro en maestra, si existe lanzo el // update, si se realiza el update entonces hago la // auditoria Integer id = null; Integer bancoCheque = null; Integer tc = null; String serial = null; String cuenta = null; double monto = 0.00; Integer bancoEmisor = null; Integer oficinaCheque = null; try { Statement st = super.getConnection().createStatement(); String query = "select id,serial_cheque,monto_cheque,cuenta_cheque,codigo_banco_cheque,tipo_cheque,codigo_entidad_emisora,codigo_oficina_cheque from cheque_entrante where lote=" + cheque.getIdLote() + " and secuencia=" + cheque.getPosicionLote(); ResultSet rs = st.executeQuery(query); if (rs.next()) { id = rs.getInt("id"); serial = rs.getString("serial_cheque"); cuenta = rs.getString("cuenta_cheque"); monto = rs.getDouble("monto_cheque"); bancoCheque = rs.getInt("codigo_banco_cheque"); tc = rs.getInt("tipo_cheque"); bancoEmisor = rs.getInt("codigo_entidad_emisora"); oficinaCheque = rs.getInt("codigo_oficina_cheque"); } } catch (Exception e) { System.out.println("Buscando el registro en la maestra de entrantes "); e.printStackTrace(); } finally { super.closeConnection(); } if (id != null) { Integer estado = ChequeConstantes.CHEQUE_SALIENTE_RECIBIDO_REGIONAL; Integer motivo = 0; Integer procesoDevo = 0; if (cheque.getCodigoMotivoDevolucion() != 0) { estado = 2; motivo = procesoDevo = 1; } String query = " serial_cheque='" + Utils.fillZerosLeft(Utils.removeLeadingZeros(cheque.getCheque().getSerial()), 8) + "' "; query += ", monto_cheque=" + cheque.getCheque().getMonto() + " "; query += ", cuenta_cheque='" + cheque.getCheque().getCuenta() + "' "; query += ", estado=" + estado; query += ", codigo_motivo_devolucion=" + motivo; query += ", proceso_devolucion=" + procesoDevo; query += ", tipo_cheque=" + cheque.getCheque().getTipoCheque(); query += ", codigo_entidad_emisora= " + cheque.getCodigoBancoEmisor(); query += ", codigo_oficina_cheque=" + cheque.getCheque().getCodigoOficina().trim(); query += " where id=" + id; if (query != null) { query = updateQuery + query; try { Statement st = super.getConnection().createStatement(); st.executeUpdate(query); AuditoriaChequeEntrante auditoria = new AuditoriaChequeEntrante(cheque, AplicacionConstantes.ESTADO_APROBADO); auditoria.setIdTransaccion(id); String modificado = ""; if (serial.compareToIgnoreCase(Utils.fillZerosLeft(Utils.removeLeadingZeros(cheque.getCheque().getSerial()), 8)) != 0) modificado += "Serial Ant=" + serial + " Act=" + Utils.fillZerosLeft(Utils.removeLeadingZeros(cheque.getCheque().getSerial()), 8); if (cuenta.compareToIgnoreCase(cuenta) != 0) modificado += "Cuenta Ant=" + serial + " Act=" + cheque.getCheque().getCuenta(); if (monto != cheque.getCheque().getMonto()) modificado += "Monto Ant=" + monto + " Act=" + cheque.getCheque().getMonto(); if (bancoCheque != Integer.parseInt(cheque.getCheque().getCodigoBanco())) modificado += "Banco Ant=" + bancoCheque + " Act=" + cheque.getCheque().getCodigoBanco(); if (tc != Integer.parseInt(cheque.getCheque().getTipoCheque())) modificado += "TipoCheque Ant=" + tc + " Act=" + cheque.getCheque().getTipoCheque(); if (bancoEmisor != cheque.getCodigoBancoEmisor()) ; modificado += "Banco Emisor Ant=" + bancoEmisor + " Act=" + cheque.getCodigoBancoEmisor(); if (oficinaCheque != Integer.parseInt(cheque.getCheque().getCodigoOficina())) modificado += "OficinaCheque Ant=" + tc + " Act=" + cheque.getCheque().getCodigoOficina(); auditoria.setDescripcion(modificado); auditoria.setAccion(ChequeConstantes.ACCION_CHEQUE_POST_CORREGIDO); listaAuditorias.add(auditoria); } catch (Exception e) { e.printStackTrace(); valido = false; continue; } finally { super.closeConnection(); } } } } if (cheque.getEstado() > ChequeDigitalizadoConstantes.CHEQUE_PENDIENTE_APROBAR && cheque.getEstado() != ChequeDigitalizadoConstantes.CHEQUE_TC_INVALIDO || reservado.isBoleta()) { digitalizados.actualizarChequeDigitalizado(cheque); } } } AuditoriaTransaccionDAO daoAuditoria = new AuditoriaTransaccionDAO(); daoAuditoria.registrarListaAuditoriasEntrantes(listaAuditorias); } return valido; } catch (Exception e) { System.out.println("actualizando transacciones "); if (this.getConn() != null) super.closeConnection(); e.printStackTrace(); return false; } } public void marcarChequesExcentos(int lote) { try { Statement st = super.getConnection().createStatement(); List<Double> listaMontos = new MontoLiofDAO().obtenerLimites(); int motivoMarca = ApplicationParameters.getInstance().getInt("liof.motivo.proceso.automatico"); if (null != listaMontos && listaMontos.size() > 0) { double limiteInferior = listaMontos.get(0); double limiteSuperior = listaMontos.get(1); String sqlBase = "UPDATE cheque_entrante set motivo_exonerar_impuesto = (Select motivo_asociado from custom_conexLiof where custom_conexLiof.cuenta = cheque_entrante.cuenta_cheque) WHERE cheque_entrante.aplica_impuesto is null "; String sqlAdicional = "UPDATE cheque_entrante set aplica_impuesto=1 WHERE motivo_exonerar_impuesto=" + motivoMarca; if (limiteInferior > 0.0 && limiteSuperior > 0.0) { sqlBase += " and cheque_entrante.monto_cheque between " + Utils.doubleToString(limiteInferior) + " AND " + Utils.doubleToString(limiteSuperior); sqlAdicional += " and monto_cheque between " + Utils.doubleToString(limiteInferior) + " AND " + Utils.doubleToString(limiteSuperior); } else if (limiteInferior > 0.0) { sqlBase += " and cheque_entrante.monto_cheque >=" + Utils.doubleToString(limiteInferior); sqlAdicional += " and monto_cheque >=" + Utils.doubleToString(limiteInferior); } else if (limiteSuperior > 0.0) { sqlBase += " and cheque_entrante.monto_cheque <=" + Utils.doubleToString(limiteSuperior); sqlAdicional += " and monto_cheque <=" + Utils.doubleToString(limiteSuperior); } if (lote > 0) { sqlBase += " and cheque_entrante.lote =" + lote; sqlAdicional += " and lote =" + lote; } System.out.println(sqlBase); System.out.println(sqlAdicional); st.executeUpdate(sqlBase); st.executeUpdate(sqlAdicional); } } catch (Exception e) { super.getLogger().error(e); } finally { super.closeConnection(); } } }
true
972e702442b11a8e44257a8c5614b2605195a550
Java
allysonbarros/Q-Est-gio-
/Projeto - EJB/src/br/edu/ifrn/patterns/PreencherFichaDelegate.java
UTF-8
600
2.140625
2
[]
no_license
package br.edu.ifrn.patterns; import java.util.List; import br.edu.ifrn.beans.FichaVisitaBeanRemote; import br.edu.ifrn.exceptions.ConnectionException; import br.edu.ifrn.exceptions.DatabaseException; import br.edu.ifrn.negocio.Orientacao; public class PreencherFichaDelegate { ServiceLocator locator; FichaVisitaBeanRemote bean; public PreencherFichaDelegate() throws ConnectionException{ locator = ServiceLocator.getInstace(); bean = locator.getFichaVisitaBean(); } public List<Orientacao> listarOrientandos() throws DatabaseException{ return bean.listarOrientados(); } }
true
4fc54a748e6a5689a29197e2c966f64b01392875
Java
LeoChenHere/projects
/ChinaTime2/src/cc/nexdoor/ct/async/DownloadNews.java
UTF-8
406
2.109375
2
[]
no_license
package cc.nexdoor.ct.async; import java.net.URL; import android.os.AsyncTask; public class DownloadNews extends AsyncTask<URL, Integer, Long> { @Override protected Long doInBackground(URL... urls) { // TODO Auto-generated method stub int count = urls.length; long totalSize = 0; for (int i = 0; i < count; i++) { } return totalSize; } }
true
5e67898872a255e89aae044cdb6365acf6911911
Java
naotedigo/HopOnCMUProject
/app/src/main/java/pt/ulisboa/tecnico/cmov/hoponcmuproject/SignUpActivity.java
UTF-8
6,170
2.109375
2
[]
no_license
package pt.ulisboa.tecnico.cmov.hoponcmuproject; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.Spinner; import android.widget.Toast; import org.json.JSONException; import org.json.JSONObject; public class SignUpActivity extends AppCompatActivity { HopOnCMUApplication _hopOnApp; protected Handler _handler; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sign_up); _hopOnApp = (HopOnCMUApplication) getApplicationContext(); Intent intent = getIntent(); if(intent.hasExtra(LoginIntentKey.USERNAME.toString()) && intent.hasExtra(LoginIntentKey.CODE.toString())) { ((EditText) findViewById(R.id.username_txt)).setText(intent.getStringExtra(LoginIntentKey.USERNAME.toString())); ((EditText) findViewById(R.id.code_txt)).setText(intent.getStringExtra(LoginIntentKey.CODE.toString())); } else { SharedPreferences sharedPreferences = getSharedPreferences(SharedPreferenceKey.USERNAME.toString(), Context.MODE_PRIVATE); String username = sharedPreferences.getString(SharedPreferenceKey.USERNAME.toString(), Constant.INVALID_VALUE), password = sharedPreferences.getString(SharedPreferenceKey.CODE.toString(), Constant.INVALID_VALUE); if(username != null && password != null && !username.equals(Constant.INVALID_VALUE) && !password.equals(Constant.INVALID_VALUE)) { ((EditText) findViewById(R.id.new_username_txt)).setText(username); ((EditText) findViewById(R.id.new_code_txt)).setText(password); } } _handler = new Handler(Looper.getMainLooper()){ public void handleMessage(Message message){ ServerReply serverReply = ServerReply.values()[message.what]; System.out.println(message.what); EditText usernameEditText = (EditText) findViewById(R.id.new_username_txt), passwordEditText = (EditText) findViewById(R.id.new_code_txt); String usernameValue = usernameEditText.getText().toString(), passwordValue = passwordEditText.getText().toString(); System.out.println(serverReply); switch (serverReply){ case SUCESS: Toast.makeText(_hopOnApp, "Sign Up sucessfull", Toast.LENGTH_SHORT).show(); Intent intent = new Intent(SignUpActivity.this, LoginActivity.class); intent.putExtra(LoginIntentKey.USERNAME.toString(), usernameValue); intent.putExtra(LoginIntentKey.CODE.toString(), passwordValue); startActivityForResult(intent, ApplicationOperationsCode.LOGIN.ordinal()); break; case INVALID_PASS: Toast.makeText(_hopOnApp, "Code already in use", Toast.LENGTH_SHORT).show(); break; case INVALID_USER: Toast.makeText(_hopOnApp, "Username already in use", Toast.LENGTH_SHORT).show(); break; default: return; } } }; } public void SignUpBtnClicked(View view) throws JSONException { //Get sign up values EditText usernameEditText = (EditText) findViewById(R.id.new_username_txt), passwordEditText = (EditText) findViewById(R.id.new_code_txt); String usernameValue = usernameEditText.getText().toString(), passwordValue = passwordEditText.getText().toString(); Spinner mySpinner = (Spinner) findViewById(R.id.country_id); String usercountry = mySpinner.getSelectedItem().toString(); //Check if values exist if (usernameValue.equals("")){ Toast.makeText(this," Nao colocou username",Toast.LENGTH_SHORT).show(); return; } if (passwordValue.equals("")){ Toast.makeText(this," Nao colocou password",Toast.LENGTH_SHORT).show(); return; } // Request Message UserRequest userRequest = UserRequest.SIGN_UP; JSONObject message = new JSONObject(); message.put(NetworkKey.REQUEST_TYPE.toString(), userRequest.ordinal()); message.put(NetworkKey.USERNAME.toString(), usernameValue); message.put(NetworkKey.PASSWORD.toString(), passwordValue); message.put(NetworkKey.COUNTRY.toString(), usercountry); ClientProxy clientProxy = new ClientProxy(userRequest, _handler , NetworkMsg.SIGN_UP , message); new Thread(clientProxy).start(); //Save login fields SharedPreferences sharedPreferences = getSharedPreferences(SharedPreferenceKey.USERNAME.toString(), Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putString(SharedPreferenceKey.USERNAME.toString(), usernameValue); editor.putString(SharedPreferenceKey.CODE.toString(), passwordValue); editor.apply(); } public void LoginBtnClicked(View view) { Intent intent = new Intent(SignUpActivity.this, LoginActivity.class); startActivity(intent); } @Override protected void onStart() { super.onStart(); } @Override protected void onRestart() { super.onRestart(); } @Override protected void onResume() { super.onResume(); } @Override protected void onPause() { super.onPause(); } @Override protected void onStop() { super.onStop(); } @Override protected void onDestroy() { super.onDestroy(); } }
true
3efd2c62a7cfb2480a5db995d93174c08bdd9a7c
Java
kmoustafa/JCompare
/src/jcompare/JCompare.java
UTF-8
924
2.34375
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 jcompare; import java.text.NumberFormat; import java.text.ParsePosition; import javax.swing.JOptionPane; /** * * @author kareem */ public class JCompare { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here String st= new FileToTokens().convertFileToTokens("/home/kareem/NetBeansProjects/JCompare/src/jcompare/Monitor.java"); //String st= new FileToTokens().convertFileToTokens("/home/kareem/NetBeansProjects/JCompare/src/jcompare/Item.java"); /* Just for Testing and see the string in large line */ JOptionPane.showMessageDialog(null, st); } }
true
57267083f6fa0e1aa139d0e4823929d794b2bed3
Java
AndreyDMokhov/papaya_poc
/src/main/java/com/papaya/model/Validation.java
UTF-8
209
1.851563
2
[]
no_license
package com.papaya.model; import lombok.Builder; import lombok.Data; import java.util.Set; @Data @Builder public class Validation { private Set<String> validationRules; private boolean required; }
true
263e22742cc886dd934e4726b08b863badf0d551
Java
Chrisx0385/wsx
/CGZ_Data/src/de/cgz/data/types/collection/range/SimpleDiscreteRange.java
UTF-8
365
2.21875
2
[]
no_license
package de.cgz.data.types.collection.range; import de.cgz.data.types.collection.range.EndPoint.EndPointType; public class SimpleDiscreteRange<T extends Comparable<T>> extends AbstractDiscreteRange<T> { public SimpleDiscreteRange(T left, EndPointType leftType, T right, EndPointType rightType) { super(left, leftType, right, rightType); } }
true
e040f6434e895acdb74dd652d986a8b7c7323a3f
Java
sanjay-thiyagarajan/Surfs-Up
/app/src/main/java/amcoders/surfup/Activity/ProfileActivity.java
UTF-8
10,751
2.203125
2
[]
no_license
package amcoders.surfup.Activity; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import android.app.DatePickerDialog; import android.content.Intent; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.DatePicker; import android.widget.EditText; import android.widget.RelativeLayout; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.android.material.snackbar.Snackbar; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.HashMap; import java.util.Locale; import amcoders.surfup.R; public class ProfileActivity extends AppCompatActivity { private FirebaseAuth mAuth; private EditText FullnameET, NicknameET; private Button continuebtn; private TextView MaleT, FemaleT, OtherT, DateT; private DatePickerDialog.OnDateSetListener mDateSetListener; boolean maleb,femaleb, otherb; String fullname,nickname,gender,date; String country = ""; int year,month,day; private String uid; private RelativeLayout relativeLayout; private DatabaseReference usersRef; Spinner countryspin; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_profile); mAuth=FirebaseAuth.getInstance(); relativeLayout = (RelativeLayout) findViewById(R.id.profile_relative_layout); MaleT = findViewById(R.id.male_select); FemaleT = findViewById(R.id.female_select); OtherT = findViewById(R.id.other_select); DateT = findViewById(R.id.dob); countryspin = findViewById(R.id.country); Locale[] locales = Locale.getAvailableLocales(); ArrayList<String> countries = new ArrayList<String>(); for (Locale locale : locales) { String country = locale.getDisplayCountry(); if (country.trim().length()>0 && !countries.contains(country)) { countries.add(country); } } Collections.sort(countries); countries.add(0,"Country"); countryspin.setAdapter(new ArrayAdapter<>(ProfileActivity.this, android.R.layout.simple_spinner_dropdown_item,countries)); countryspin.setSelection(0, false); DateT.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Calendar cal = Calendar.getInstance(); year = cal.get(Calendar.YEAR); month = cal.get(Calendar.MONTH); day = cal.get(Calendar.DAY_OF_MONTH); DatePickerDialog dialog = new DatePickerDialog( ProfileActivity.this, android.R.style.Theme_Material_Light_Dialog, mDateSetListener, day,month,year ); dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.LTGRAY)); dialog.show(); } }); mDateSetListener = new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker datePicker, int i, int i1, int i2) { year = i; month = i1+1; day = i2; date = day + "/" + month + "/" + year; DateT.setText(date); } }; MaleT.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { MaleT.setBackgroundColor(getResources().getColor(R.color.blue)); MaleT.setTextColor(getResources().getColor(R.color.white)); OtherT.setTextColor(getResources().getColor(R.color.black)); FemaleT.setTextColor(getResources().getColor(R.color.black)); FemaleT.setBackground(Drawable.createFromPath("@drawable/rounder_field")); OtherT.setBackground(Drawable.createFromPath("@drawable/rounder_field")); maleb = true; femaleb = false; otherb = false; } }); FemaleT.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { MaleT.setBackground(Drawable.createFromPath("@drawable/rounder_field")); FemaleT.setBackgroundColor(getResources().getColor(R.color.blue)); FemaleT.setTextColor(getResources().getColor(R.color.white)); MaleT.setTextColor(getResources().getColor(R.color.black)); OtherT.setTextColor(getResources().getColor(R.color.black)); OtherT.setBackground(Drawable.createFromPath("@drawable/rounder_field")); maleb = false; femaleb = true; otherb = false; } }); OtherT.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { MaleT.setBackground(Drawable.createFromPath("@drawable/rounder_field")); FemaleT.setBackground(Drawable.createFromPath("@drawable/rounder_field")); OtherT.setTextColor(getResources().getColor(R.color.white)); MaleT.setTextColor(getResources().getColor(R.color.black)); FemaleT.setTextColor(getResources().getColor(R.color.black)); OtherT.setBackgroundColor(getResources().getColor(R.color.blue)); maleb = false; femaleb = false; otherb = true; } }); NicknameET = findViewById(R.id.nickname); FullnameET = findViewById(R.id.fullname); continuebtn = findViewById(R.id.continue_button); continuebtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(maleb || femaleb || otherb) { if (maleb) gender = "Male"; if(femaleb) gender = "Female"; if(otherb) gender = "Other"; } fullname = FullnameET.getText().toString(); nickname = NicknameET.getText().toString(); if(TextUtils.isEmpty(country)) { Snackbar snackbar = Snackbar.make(relativeLayout, "Please Select Your Country", Snackbar.LENGTH_SHORT); snackbar.show(); } countryspin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { if(position == 0){ country = ""; Snackbar snackbar = Snackbar.make(relativeLayout, "Please Select Your Country", Snackbar.LENGTH_SHORT); snackbar.show(); }else{ String scountry = parent.getItemAtPosition(position).toString(); country = scountry; } } @Override public void onNothingSelected(AdapterView<?> parent) { } }); if(TextUtils.isEmpty(fullname) || TextUtils.isEmpty(date) || TextUtils.isEmpty(gender) || TextUtils.isEmpty(nickname)) { Snackbar snackbar = Snackbar.make(relativeLayout, "Please fill the details. ", Snackbar.LENGTH_SHORT); snackbar.show(); } if(!(TextUtils.isEmpty(fullname) || TextUtils.isEmpty(date) || TextUtils.isEmpty(gender) || TextUtils.isEmpty(nickname) || TextUtils.isEmpty(country))) { usersRef = FirebaseDatabase.getInstance().getReference("Users"); uid = mAuth.getCurrentUser().getUid(); HashMap<String,Object> result=new HashMap<>(); result.put("FullName",fullname); result.put("DOB",date); result.put("Gender",gender); result.put("NickName",nickname); result.put("Country",country); usersRef.child(uid).updateChildren(result).addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()) { Intent mainIntent = new Intent(ProfileActivity.this, dashboardActivity.class); mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(mainIntent); } else { String message = task.getException().getMessage(); Snackbar snackbar = Snackbar.make(relativeLayout, "Error occurred. "+message, Snackbar.LENGTH_SHORT); snackbar.show(); } } }); /* Snackbar snackbar = Snackbar.make(relativeLayout,fullname+", "+nickname+", "+date+", "+gender+", "+country, Snackbar.LENGTH_SHORT); snackbar.show(); Intent mainIntent = new Intent(ProfileActivity.this, dashboardActivity.class); mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(mainIntent); */ } } }); } }
true
ff8b18fd46248b3541c08225eb8716b7a53fee80
Java
xinyongheng/PJJ
/indoor/src/main/java/com/pjj/xsp/intent/http/ApiService.java
UTF-8
3,646
1.78125
2
[]
no_license
package com.pjj.xsp.intent.http; import com.pjj.xsp.module.parameter.ActivateStatue; import com.pjj.xsp.module.parameter.AppUpload; import com.pjj.xsp.module.parameter.ScreenInfTag; import com.pjj.xsp.module.parameter.ScreenOrderTask; import com.pjj.xsp.module.parameter.ScreenshotsBean; import com.pjj.xsp.module.parameter.UploadTakeScreen; import okhttp3.RequestBody; import okhttp3.ResponseBody; import retrofit2.Call; import retrofit2.http.Body; import retrofit2.http.GET; import retrofit2.http.POST; import retrofit2.http.Path; import retrofit2.http.Query; import retrofit2.http.Streaming; import retrofit2.http.Url; /** * Create by xinheng on 2018/10/12 0012。 * describe:retrofit网络接口 */ public interface ApiService { /** * 任务获取 * * @param screenId * @return */ @POST("screen/queryScreenTask.action") Call<ResponseBody> queryScreenTask(@Body ScreenInfTag screenId); // @POST("screen/getScreenList.action") @POST("screen/getNewMediaScreenList.action") Call<ResponseBody> getScreenList(@Body ScreenInfTag screenId); /** * 根据设备码注册广告屏 * * @param screenId * @return */ // @POST("screen/registerScreen.action") @POST("screen/registerNewMediaScreen.action") Call<ResponseBody> sendScreenTag(@Body ScreenInfTag screenId); /** * 激活广告屏 * * @param activateStatue * @return */ // @POST("screen/activateScreen.action") @POST("screen/activateNewMediaScreen.action") Call<ResponseBody> activateScreen(@Body ActivateStatue activateStatue); @GET Call<ResponseBody> downloadFile(@Url String url); @Streaming //添加这个注解用来下载大文件 @GET Call<ResponseBody> downloadBigFile(@Url String fileUrl); //"http://api.map.baidu.com/telematics/v3/weather?location=" + encodeCityName + "&output=json&ak=90c7c7fcf0337fa1fb8b8ac78172e79b" @GET("telematics/v3/weather?output=json&ak=90c7c7fcf0337fa1fb8b8ac78172e79b") Call<ResponseBody> getDayWeather(@Query("location") String encodeCityName); @GET("{city}.html") Call<ResponseBody> getCarXianXingNum(@Path("city") String city); /** * 广告屏根据订单号查询任务 * * @param screenOrderTask * @return */ @POST("screen/getNewMediaScreenOrderTask.action") Call<ResponseBody> getScreenOrderTask(@Body ScreenOrderTask screenOrderTask); @POST("screen/getAccessKey.action") Call<ResponseBody> getAccessKey(@Body RequestBody body); @POST("screen/getScreenshotsInfo.action") Call<ResponseBody> getScreenshotsInfo(@Body ScreenshotsBean body); @POST("screen/updateScreenVersion.action") Call<ResponseBody> updateScreenVersion(@Body AppUpload body); @POST("/screen/receiveScreenImgInfo.action") Call<ResponseBody> receiveScreenImgInfo(@Body UploadTakeScreen body); @POST("/screen/receiveScreenResponse.action") Call<ResponseBody> receiveScreenImgInfo(@Body RequestBody body); /** * 屏幕确认订单投放 * @param body * @return */ @POST("/screen/ackOrderScreen.action") Call<ResponseBody> ackOrderScreen(@Body RequestBody body); /** * 接收屏幕操作命令反馈 * @param body * @return */ @POST("/screen/updateScreenCommandStatus.action") Call<ResponseBody> updateScreenCommandStatus(@Body RequestBody body); /** * 接收广告屏日志信息 * @param body * @return */ @POST("/screen/insertScreenErrorFile.action") Call<ResponseBody> insertScreenErrorFile(@Body RequestBody body); }
true
561618a9fd7e7744ae0d0c82440d8c2305afdd4a
Java
WellingtonSB/Creg_Ecol
/Ecol/src/main/java/com/Creg/Ecol/Repository/ClienteRepository.java
UTF-8
376
1.859375
2
[ "MIT" ]
permissive
package com.Creg.Ecol.Repository; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import com.Creg.Ecol.Model.Cliente; public interface ClienteRepository extends JpaRepository<Cliente, Long> { public List<Cliente> findAllByNomeContainingIgnoreCase(String nome); public List<Cliente> findAllByCpfContainingIgnoreCase(String cpf); }
true
86e52a7d09fd81d17f315c0d1bc544380b4a7924
Java
dpoulomi/PractiseForInterview
/src/main/java/whatnot/Practise/practiseid/MirrorBinaryTree.java
UTF-8
1,422
3.390625
3
[]
no_license
package whatnot.Practise.practiseid; public class MirrorBinaryTree { public class Node { int data; Node left; Node right; public Node(int value, Node left, Node right) { data = value; this.left = left; this.right = right; } } public static void main(String args[]) { MirrorBinaryTree rll = new MirrorBinaryTree(); Node n1 = rll.createTree1(); rll.printList(n1); System.out.println(); Node n2 = n1; Node mainTree = n1; // Node mirrorTree=new MirrorBinaryTree().new Node(n2.data, n2.right, // n2.left); rll.formMirrorTree(mainTree); rll.printList(n2); System.out.println(); } private void formMirrorTree(Node head) { if (head == null) { return; } if (head.left != null || head.right != null) { Node temp = head.left; head.left = head.right; head.right = temp; formMirrorTree(head.right); formMirrorTree(head.left); } } private void printList(Node n) { if (n != null) { printList(n.left); System.out.print(n.data + "->"); printList(n.right); } } private Node createTree1() { /*Node n9 = new Node(20, null, null); Node n8 = new Node(19, null, n9); Node n7 = new Node(11, n8, null); Node n6 = new Node(9, null, null); Node n5 = new Node(7, null, null); Node n4 = new Node(5, null, null);*/ Node n3 = new Node(10, null, null); Node n2 = new Node(6, null, null); Node n1 = new Node(8, n2, n3); return n1; } }
true
83f35fc42ade1d6d3a196ff8ee6234bf00c9cf62
Java
kousen/java_latest
/src/test/java/com/kousenit/datetime/DateRangeTest.java
UTF-8
889
2.859375
3
[]
no_license
package com.kousenit.datetime; import org.junit.jupiter.api.Test; import java.time.LocalDate; import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; public class DateRangeTest { private DateRange range = new DateRange(); @Test public void dateRange_oneWeekInDays() { LocalDate now = LocalDate.now(); LocalDate then = now.plusWeeks(1); List<LocalDate> dates = range.getDays_java9(now, then); assertEquals(7, dates.size()); assertEquals(dates, range.getDays_java8(now, then)); } @Test public void dateRange_oneYearInMonths() { LocalDate now = LocalDate.now(); LocalDate then = now.plusYears(1); List<LocalDate> dates = range.getMonths_java9(now, then); assertEquals(12, dates.size()); assertEquals(dates, range.getMonths_java8(now, then)); } }
true
eaa5eaeec36c5c406c1844200107010399678ae4
Java
ZYHGOD-1/Aosp11
/packages/services/Car/tests/OccupantAwareness/src/com/android/car/test/OccupantAwarenessUtilsTest.java
UTF-8
6,249
1.890625
2
[]
no_license
/* * Copyright (C) 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.car; import static com.google.common.truth.Truth.assertThat; import android.car.occupantawareness.OccupantAwarenessDetection; import android.car.occupantawareness.SystemStatusEvent; import android.hardware.automotive.occupant_awareness.IOccupantAwareness; import android.hardware.automotive.occupant_awareness.OccupantAwarenessStatus; import android.test.suitebuilder.annotation.MediumTest; import androidx.test.runner.AndroidJUnit4; import junit.framework.TestCase; import org.junit.Test; import org.junit.runner.RunWith; @RunWith(AndroidJUnit4.class) @MediumTest public class OccupantAwarenessUtilsTest extends TestCase { @Test public void test_convertToStatusEvent() { SystemStatusEvent event; event = OccupantAwarenessUtils.convertToStatusEvent( IOccupantAwareness.CAP_NONE, OccupantAwarenessStatus.READY); assertThat(event.systemStatus).isEqualTo(SystemStatusEvent.SYSTEM_STATUS_READY); assertThat(event.detectionType).isEqualTo(SystemStatusEvent.DETECTION_TYPE_NONE); event = OccupantAwarenessUtils.convertToStatusEvent( IOccupantAwareness.CAP_PRESENCE_DETECTION, OccupantAwarenessStatus.NOT_SUPPORTED); assertThat(event.systemStatus).isEqualTo(SystemStatusEvent.SYSTEM_STATUS_NOT_SUPPORTED); assertThat(event.detectionType).isEqualTo(SystemStatusEvent.DETECTION_TYPE_PRESENCE); event = OccupantAwarenessUtils.convertToStatusEvent( IOccupantAwareness.CAP_GAZE_DETECTION, OccupantAwarenessStatus.NOT_INITIALIZED); assertThat(event.systemStatus).isEqualTo(SystemStatusEvent.SYSTEM_STATUS_NOT_READY); assertThat(event.detectionType).isEqualTo(SystemStatusEvent.DETECTION_TYPE_GAZE); event = OccupantAwarenessUtils.convertToStatusEvent( IOccupantAwareness.CAP_DRIVER_MONITORING_DETECTION, OccupantAwarenessStatus.FAILURE); assertThat(event.systemStatus).isEqualTo(SystemStatusEvent.SYSTEM_STATUS_SYSTEM_FAILURE); assertThat(event.detectionType) .isEqualTo(SystemStatusEvent.DETECTION_TYPE_DRIVER_MONITORING); } @Test public void test_convertToConfidenceScore() { assertThat( OccupantAwarenessUtils.convertToConfidenceScore( android.hardware.automotive.occupant_awareness.ConfidenceLevel.MAX)) .isEqualTo(OccupantAwarenessDetection.CONFIDENCE_LEVEL_MAX); assertThat( OccupantAwarenessUtils.convertToConfidenceScore( android.hardware.automotive.occupant_awareness.ConfidenceLevel .HIGH)) .isEqualTo(OccupantAwarenessDetection.CONFIDENCE_LEVEL_HIGH); assertThat( OccupantAwarenessUtils.convertToConfidenceScore( android.hardware.automotive.occupant_awareness.ConfidenceLevel.LOW)) .isEqualTo(OccupantAwarenessDetection.CONFIDENCE_LEVEL_LOW); assertThat( OccupantAwarenessUtils.convertToConfidenceScore( android.hardware.automotive.occupant_awareness.ConfidenceLevel .NONE)) .isEqualTo(OccupantAwarenessDetection.CONFIDENCE_LEVEL_NONE); } @Test public void test_convertToPoint3D() { assertThat(OccupantAwarenessUtils.convertToPoint3D(null)).isNull(); assertThat(OccupantAwarenessUtils.convertToPoint3D(new double[0])).isNull(); assertThat(OccupantAwarenessUtils.convertToPoint3D(new double[2])).isNull(); assertThat(OccupantAwarenessUtils.convertToPoint3D(new double[] {1, 2, 3})).isNotNull(); } @Test public void test_convertToRole() { assertThat( OccupantAwarenessUtils.convertToRole( android.hardware.automotive.occupant_awareness.Role.INVALID)) .isEqualTo(OccupantAwarenessDetection.VEHICLE_OCCUPANT_NONE); assertThat( OccupantAwarenessUtils.convertToRole( android.hardware.automotive.occupant_awareness.Role.UNKNOWN)) .isEqualTo(OccupantAwarenessDetection.VEHICLE_OCCUPANT_NONE); assertThat( OccupantAwarenessUtils.convertToRole( android.hardware.automotive.occupant_awareness.Role.DRIVER | android.hardware.automotive.occupant_awareness.Role .FRONT_PASSENGER | android.hardware.automotive.occupant_awareness.Role .ROW_2_PASSENGER_CENTER)) .isEqualTo( OccupantAwarenessDetection.VEHICLE_OCCUPANT_DRIVER | OccupantAwarenessDetection.VEHICLE_OCCUPANT_FRONT_PASSENGER | OccupantAwarenessDetection .VEHICLE_OCCUPANT_ROW_2_PASSENGER_CENTER); assertThat( OccupantAwarenessUtils.convertToRole( android.hardware.automotive.occupant_awareness.Role.ALL_OCCUPANTS)) .isEqualTo(OccupantAwarenessDetection.VEHICLE_OCCUPANT_ALL_OCCUPANTS); } }
true
cce49dccc7e5f0740e759e0bccab07eb7ab63526
Java
holiday1994/Project
/InventoryApp.java
UTF-8
7,315
3.75
4
[]
no_license
/* author: Stavros Kontzias, Kyle Kim, Matt Bosek, Hunter Whitelock date: 4/3/2018 purpose: Better Buy Prototype Inventory Mangement System Prototype. //Disclaimer: Everyone in this group has distributed work evenly throught the Programming assignment */ package Project; import java.util.ArrayList; import java.util.Scanner; public class InventoryApp { /** * Adds items to inventory and manages inventory. * @param args command line arguments */ public static void main(String[] args) { Scanner kb = new Scanner(System.in); ArrayList<Product> inventoryList = new ArrayList<Product>(); Product p = new Product(); Desktop d = new Desktop(); CellPhones c = new CellPhones(); Laptops l = new Laptops(); int input = 0; //int cpCounter = 0;//Keep tally of how many in stock //int lCounter = 0; //int dCounter = 0; while(input !=9){//loop through menu System.out.printf("%-25s%-25s\n","1.Add Desktop","5.Print Laptop(s)"); System.out.printf("%-25s%-25s\n","2.Add Laptop", "6 Print Cellphone(s)"); System.out.printf("%-25s%-25s\n", "3 Add Cellphone","7.Print All Items"); System.out.printf("%-25s%-25s\n", "4 Print Desktop(s)","8.Profitability Report"); System.out.println("9.Exit System"); input = kb.nextInt(); switch(input){ case 1://Write into desktop { //dCounter++; d.createDesktop(inventoryList); break; } case 2://write into Laptop { //lCounter++; l.createLaptop(inventoryList); break; } case 3://write into CellPhones { //cpCounter++; c.createCellPhone(inventoryList); break; } case 4: { printDesktop(d, inventoryList); break; } case 5: { printLaptop(l, inventoryList); break; } case 6: { printCellPhone(c, inventoryList); break; } case 7://Print all { printDesktop(d, inventoryList); printLaptop(l, inventoryList); printCellPhone(c, inventoryList); break; } case 8: printCompleteReport(d,l,c,inventoryList); } } } /** * Prints desktop price, brand, and cost * @param dCounter the amount of desktops in inventory * @param desk the array of desktops that hold inventory */ public static void printDesktop(Desktop d, ArrayList<Product> desk) { System.out.print("\n" + d.getCount() + " Desktop Computer(s): \n"); System.out.printf("%-15s%-15s%-15s%-20s%-15s%-15s%-15s\n" ,"IDNum","Brand","Cost","Selling Price", "Processor","Ram","Drive Size"); for(Product p: desk){ if(p instanceof Desktop && !(p instanceof Laptops)) System.out.println(p.toString()); } } /** * Prints laptop price, brand, and cost. * @param lCounter the amount of laptops in inventory * @param lap the array of laptops that hold inventory */ public static void printLaptop(Laptops lp, ArrayList<Product> lap) { System.out.print("\n" + lp.getCount() + " Laptop Computer(s): \n"); System.out.printf("%-15s%-15s%-15s%-20s%-15s%-15s%-15s%-15s%-15s%-15s\n" ,"IDNum","Brand","Cost","Selling Price", "Processor","Ram","Drive Size","Screen Size","Backlit","Finger Print Reader"); for (Product p: lap){ if (p instanceof Laptops){ System.out.println(p.toString()); } } } /** * Prints cellphone brand, cost, sale price. * @param cpCounter the amount of cellphones in inventory * @param cp the inventory that holds the cellphones */ public static void printCellPhone(CellPhones cell, ArrayList<Product> cp) { System.out.println("\n" + cell.getCount() + " Cell Phone(s): "); System.out.printf("%-15s%-15s%-15s%-20s%-15s%-15s\n","IDNUM","Brand","Cost","Selling Price","Screen Size" ,"Memory"); for (Product p: cp){ if (p instanceof CellPhones){ System.out.println(p.toString()); } } } public static void printCompleteReport(Desktop d, Laptops l, CellPhones cp ,ArrayList <Product> inventoryList){ System.out.println("====================================="); System.out.println("Complete Report: "); System.out.printf("%-20s%-20s%-20s%-21s%-20s\n" ,"Unique ID","Selling Price","Cost","Capital Gains","Product Type"); for (Product p: inventoryList){ System.out.printf("%-%-20d$%-19.2f$%-19.2f$%-20.2f", p.getUniqueID(), p.getSellPrice(), p.getCost(), p.getSellPrice() - p.getCost()); if (p instanceof Desktop){ System.out.printf("%-20s\n",((Desktop) p).getType()); } else if (p instanceof Laptops){ System.out.printf("%-20s\n",((Laptops) p).getType()); } else if (p instanceof CellPhones){ System.out.printf("%-20s\n",((CellPhones) p).getType()); } } System.out.println(profitReport(d,l,cp,inventoryList)); } /** * Prints the profit report of the store. * * @param d desktop used to get the amount of desktops * @param l laptops used to get the amount of laptops * @param cp cellphones used to geth the amount of cellphones * @param inventoryList the store's current inventory * @return result */ public static String profitReport (Desktop d, Laptops l, CellPhones cp, ArrayList <Product> inventoryList){ double revenue = 0; double cost = 0; double profit; for (Product p: inventoryList){ revenue += p.getSellPrice(); cost += p.getCost(); } profit = revenue - cost; String result = String.format ("\nTotal Revenue: $%-14.2f\nTotal Cost: $%-15.2f\nTotal Profit: $%-15.2f\n", revenue, cost, profit); result += ("Desktops: " + d.getCount() + " Laptops: " + l.getCount() + " Cell Phones: " + cp.getCount()); return result; } }
true
fccec26be889b3c9688f29a146da93ac27f448f9
Java
Cophelio/yCook
/src/main/java/pl/coderslab/ycook/viewModel/RecipeViewModel.java
UTF-8
2,754
2.484375
2
[]
no_license
package pl.coderslab.ycook.viewModel; import pl.coderslab.ycook.entity.Recipe; public class RecipeViewModel { private int id; private String name; private String cuisine; private String type; private String ingredients; private String description; private int kcal; private String other; private String time; private String level; private boolean recommend; private boolean favorite; public RecipeViewModel() { } public RecipeViewModel(Recipe recipe, String cuisine, String type) { this.id = recipe.getId(); this.name = recipe.getName(); this.cuisine = cuisine; this.type = type; this.ingredients = recipe.getIngredients(); this.description = recipe.getDescription(); this.kcal = recipe.getKcal(); this.other = recipe.getOther(); this.time = recipe.getTime(); this.level = recipe.getLevel(); this.recommend = recipe.isRecommend(); this.favorite = recipe.isFavorite(); } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCuisine() { return cuisine; } public void setCuisine(String cuisine) { this.cuisine = cuisine; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getIngredients() { return ingredients; } public void setIngredients(String ingredients) { this.ingredients = ingredients; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public int getKcal() { return kcal; } public void setKcal(int kcal) { this.kcal = kcal; } public String getOther() { return other; } public void setOther(String other) { this.other = other; } public String getTime() { return time; } public void setTime(String time) { this.time = time; } public String getLevel() { return level; } public void setLevel(String level) { this.level = level; } public boolean isRecommend() { return recommend; } public void setRecommend(boolean recommend) { this.recommend = recommend; } public boolean isFavorite() { return favorite; } public void setFavorite(boolean favorite) { this.favorite = favorite; } }
true
3706a73b2971ff1e3a7a29e463b2b2b07dfaae3d
Java
Luxxrom/Socketor
/src/Socketor.java
UTF-8
1,273
3.40625
3
[]
no_license
import java.io.*; public class Socketor { public static void main(String[] args) throws IOException { if (args.length < 3) { System.out.println("Usage:\n" + "java Socketor server 8000 2 / \n" + "java Socketor client 127.0.0.1 8000 45 35"); return; } Socketor socketor = new Socketor(); if (args[0].equals("server")) socketor.runServer(args[1], args[2], args[3]); if (args[0].equals("client")) socketor.runClient(args[1], args[2], args[3], args[4]); } private void runServer(String port, String threadsCount, String operation) throws IOException { int threads = Integer.parseInt(threadsCount); Phone phone = new Phone(port); System.out.println("Started server with " + operation + " on " + port); for (int j = 0; j < threads; j++) new Thread(new ServerPhone(new Phone(phone), operation)).start(); } private void runClient(String ip, String port, String a, String b) throws IOException { Phone phone = new Phone(ip, port); phone.writeLine(a); phone.writeLine(b); String answer = phone.readLine(); System.out.println(answer); phone.close(); } }
true
c950d91623414dbf59eeb287f291e7885c554f1b
Java
avparmar1805/ds-algos
/HackerRank/CheckStringReverse.java
UTF-8
598
3.40625
3
[]
no_license
import java.util.Scanner; public class CheckStringReverse { private static Scanner in; public static void main(String[] args) { in = new Scanner(System.in); String str = in.next(); String inputRevStr = in.next(); String revStr = ReverseString(str, ""); System.out.println(revStr.equals(inputRevStr)); } public static String ReverseString(String str, String revStr) { if (str.length() == 0) { return ""; } char firstChar = str.charAt(0); String rest = str.substring(1); String cRes = ReverseString(rest, revStr); revStr = cRes + firstChar; return revStr; } }
true
f4e88d0c99b2d1e81aed96febaee7b8d0c980d4a
Java
Klykov-TV/job4j
/chapter_001/src/main/java/ru/job4j/condition/SqArea.java
UTF-8
359
3.265625
3
[ "Apache-2.0" ]
permissive
package ru.job4j.condition; /** * Вычисляет площадь прямоугольника */ public class SqArea { /** * @param p периметр * @param k w=kh * @return площадь */ public int square(int p, int k) { int h = p / (2 * k + 2); int w = (p - 2 * h) / 2; return h * w; } }
true
56f31808f9a35bfb011d6ebc3315981ddd94cd95
Java
flebro/Messagerie
/src/com/messagerie/command/EnregistrerHTML.java
UTF-8
403
2.0625
2
[]
no_license
package com.messagerie.command; import com.messagerie.Salon; import com.persister.HTMLPersister; public class EnregistrerHTML implements ICommand<Void> { HTMLPersister htmlPersister; public EnregistrerHTML(HTMLPersister htmlPersister) { this.htmlPersister = htmlPersister; } @Override public void execute(Void param) { htmlPersister.sauvegarder(Salon.getInstance().getMessages()); } }
true
065d9316d67207e4ae6945530c506c3742fedc51
Java
sellsky/utils2
/src/tk/bolovsrol/utils/syncro/ParallelTasks.java
UTF-8
3,847
2.953125
3
[]
no_license
package tk.bolovsrol.utils.syncro; import tk.bolovsrol.utils.StringDumpBuilder; import tk.bolovsrol.utils.function.ThrowingRunnable; import java.util.Collection; import java.util.concurrent.CancellationException; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.function.Consumer; /** * Запускает несколько задач параллельно и ждёт, когда они завершатся. * <p> * Задача может выкинуть исключение, оно будет сохранено. * * @param <R> */ public class ParallelTasks<R extends ThrowingRunnable<? extends Exception>> { /** * Информация об исключениях, выброшенных задачами. * * @param <R> */ public static class Failure<R extends ThrowingRunnable<? extends Exception>> { private final String name; private final R worker; private final Exception exception; private Failure(String name, R worker, Exception exception) { this.name = name; this.worker = worker; this.exception = exception; } public String getName() { return name; } public R getWorker() { return worker; } public Exception getException() { return exception; } @Override public String toString() { return new StringDumpBuilder() .append("name", name) .append("worker", worker) .append("exception", exception) .toString(); } } /** * Класс, предназначенный для запуска нескольких параллельных тредов и ожидания либо завершения их работы, либо */ private final VersionParking vp = new VersionParking(); private final ConcurrentLinkedQueue<Thread> participants = new ConcurrentLinkedQueue<>(); private final ConcurrentLinkedQueue<Failure<R>> failures = new ConcurrentLinkedQueue<>(); private boolean interruptOnFailure = true; public ParallelTasks() { } public ParallelTasks(boolean interruptOnFailure) { this.interruptOnFailure = interruptOnFailure; } public boolean await() throws InterruptedException { vp.parkWhile(() -> !participants.isEmpty()); if (failures.isEmpty()) { return true; } else { if (interruptOnFailure) participants.forEach(Thread::interrupt); return false; } } public Collection<Failure<R>> getFailures() { return failures; } public void forEachFailure(Consumer<Failure<R>> consumer) { failures.forEach(consumer); } public void forEachFailureExceptInterrupted(Consumer<Failure<R>> consumer) { failures.forEach(f -> { if (!(f.exception instanceof InterruptedException)) { consumer.accept(f); } }); } public void launch(String threadName, R worker) { if (!failures.isEmpty()) { failures.add(new Failure<>(threadName, worker, new CancellationException())); } else { Thread thread = new Thread(threadName) { @Override public void run() { try { worker.run(); } catch (Exception e) { failures.add(new Failure<>(threadName, worker, e)); } finally { participants.remove(this); vp.nextVersion(); } } }; participants.add(thread); thread.start(); } } }
true
1451b654f353b3f65d272742004c7f218c1991bc
Java
mateodecu/sugpa
/sugpa/src/com/dgcactysv/controladores/ControladorIngresarVehiculo.java
UTF-8
2,875
2.140625
2
[]
no_license
package com.dgcactysv.controladores; import java.io.IOException; import java.util.GregorianCalendar; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import com.dgcactysv.funciones.Funciones; import com.dgcactysv.modelo.Registro; import com.dgcactysv.negocio.Facade; import com.dgcactysv.negocio.RegistroABM; /** * Servlet implementation class ControladorInicio */ public class ControladorIngresarVehiculo extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doPost(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub HttpSession session= (HttpSession) request.getSession(); request.setAttribute("usuario", (String) session.getAttribute("usuario")); Facade facade=new Facade(); RegistroABM adm= facade.getRegistroABM(); response.setContentType("text/html;charset=UTF-8"); try { String tipo= request.getParameter("tipo"); String dominio= request.getParameter("dominio"); String marca=request.getParameter("marca"); if(marca.compareTo("")==0){ marca=request.getParameter("marcaM"); } String modelo=request.getParameter("modelo"); String motivo=request.getParameter("motivo"); String levantadoEn=request.getParameter("levantadoEn"); String actaC= request.getParameter("actac"); String acta= request.getParameter("acta"); String boleta= request.getParameter("boleta"); String agente= request.getParameter("agente"); String infractor=request.getParameter("infractor"); String chofer=request.getParameter("chofer"); String nChasisNmotor=request.getParameter("chasis")+request.getParameter("motor"); adm.agregar(new GregorianCalendar(), Funciones.traerHora2(new GregorianCalendar()), tipo.toUpperCase(), dominio.toUpperCase(), marca.toUpperCase(), modelo.toUpperCase(), motivo.toUpperCase(), levantadoEn.toUpperCase(), actaC.toUpperCase(), acta,boleta.toUpperCase(), agente.toUpperCase(), infractor.toUpperCase(), "PIZARRO", chofer.toUpperCase(), "SI", nChasisNmotor.toUpperCase()); request.setAttribute("contabilizacion", adm.Contablilizacion()); request.setAttribute("contabilizacionAutos", adm.ContablilizacionAutos()); request.setAttribute("contabilizacionMotos", adm.ContablilizacionMotos()); request.getRequestDispatcher("/jsp/bienvenidoAgente.jsp").forward(request, response); } catch (Exception e2) { request.getRequestDispatcher("/jsp/errorCarga.jsp").forward(request, response); } } }
true
546ecec60d9b258b5295535ea755081cb14b39b4
Java
marijagj/RezerviranjeParking
/app/src/main/java/com/example/rezerviranjeparking/HomeActivity.java
UTF-8
2,699
2.1875
2
[]
no_license
package com.example.rezerviranjeparking; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import androidx.recyclerview.widget.DefaultItemAnimator; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class HomeActivity extends AppCompatActivity { ArrayList<City> arrayList; RecyclerView recyclerView; DBHelper databaseHelper; Intent intent; String user; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_home); intent=getIntent(); user = intent.getStringExtra("User"); androidx.appcompat.widget.Toolbar toolbar= (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setTitle("Листа од градови"); recyclerView = (RecyclerView) findViewById(R.id.list); databaseHelper=new DBHelper(this); databaseHelper.addCities("Велес"); databaseHelper.addCities("Скопје"); databaseHelper.addCities("Охрид"); databaseHelper.addCities("Кавадарци"); databaseHelper.addCities("Прилеп"); displayCities(); } public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main_menu, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { Intent intent = null; switch (item.getItemId()) { case R.id.action_favorite: intent = new Intent(this, ReservableActivity.class); intent.putExtra("User",user); startActivity(intent); return true; default: return super.onOptionsItemSelected(item); } } private void displayCities() { arrayList = new ArrayList<>(databaseHelper.getCities()); recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)); recyclerView.setItemAnimator(new DefaultItemAnimator()); MyTownAdapter adapter = new MyTownAdapter(getApplicationContext(), this, arrayList,intent); recyclerView.setAdapter(adapter); } }
true
5e5011a1bf0769775d1ae6bb11eb6639ea5c30eb
Java
SurfGitHub/BLIZZARD-Replication-Package-ESEC-FSE2018
/Corpus/eclipse.jdt.ui/1578.java
UTF-8
122
2.15625
2
[ "MIT" ]
permissive
package p; class A { private void m(int i, boolean b) { } private void foo() { m(2, true); } }
true
07e8a8713624a135fb0616aabf78889c0961c355
Java
EdilvaCarvalho/sisBancario
/src/java/modelo/ListarAgenciaBo.java
UTF-8
286
1.890625
2
[]
no_license
package modelo; import entidades.Agencia; import fabrica.DaoFactory; import java.util.List; /** * * @author Edilva */ public class ListarAgenciaBo { public List<Agencia> listar(){ return DaoFactory.createFactory(DaoFactory.DAO_BD).criaAgencia().listar(); } }
true
e8140cf18bf71786adb871bf3fa43b96198ad148
Java
tomdev2008/dsj_house
/dsj_house/dsj-system/dsj-system-api/src/main/java/com/dsj/modules/system/vo/RecommendVo.java
UTF-8
389
1.84375
2
[]
no_license
package com.dsj.modules.system.vo; import java.io.Serializable; public class RecommendVo implements Serializable { private long houseId; private Integer type; public long getHouseId() { return houseId; } public void setHouseId(long houseId) { this.houseId = houseId; } public Integer getType() { return type; } public void setType(Integer type) { this.type = type; } }
true
daa79aa0cee57535e3b59d1fbd582e5593ec1a13
Java
P79N6A/icse_20_user_study
/methods/Method_773.java
UTF-8
466
2.0625
2
[]
no_license
public static Class<?> getBuilderClass(Class<?> clazz,JSONType type){ if (clazz != null && clazz.getName().equals("org.springframework.security.web.savedrequest.DefaultSavedRequest")) { return TypeUtils.loadClass("org.springframework.security.web.savedrequest.DefaultSavedRequest$Builder"); } if (type == null) { return null; } Class<?> builderClass=type.builder(); if (builderClass == Void.class) { return null; } return builderClass; }
true
bdb0a6e8e956955fc7bba6f5234180c71be1fbfb
Java
marciosn/Plus-Cinema-TV-Server
/JSON-SERVER07-11/src/com/es/ufc/quixada/teste/TestaInsereFile.java
UTF-8
935
2.53125
3
[]
no_license
package com.es.ufc.quixada.teste; import com.es.ufc.persisntence.FilmeJPADAO; import com.es.ufc.quixada.Filme; public class TestaInsereFile { private static FilmeJPADAO filmeDAO = new FilmeJPADAO(); public static void main(String[] args) { Filme filme = new Filme(); Filme filme2 = new Filme(); filme.setAno("2012"); filme.setGenero("teste"); filme.setNome("Homem de aco"); filme.setNotaMedia("10"); filme.setId(1); filme.setUrl("www.google.com"); filme2.setAno("2012"); filme2.setGenero("romance"); filme2.setNome("Testando"); filme2.setNotaMedia("10"); filme2.setId(2); filme2.setUrl("www.google.com"); try { filmeDAO.beginTransaction(); filmeDAO.save(filme); filmeDAO.commit(); } catch (Exception e) { filmeDAO.rollback(); e.printStackTrace(); } finally{ filmeDAO.close(); } } }
true
ed9ecaa79766c22e07410d6c84b0e752ce8fb952
Java
zhongxingyu/Seer
/Diff-Raw-Data/14/14_348382cfeeef9b97fc08e4323e63bd35b7832ce4/DevFrameworkBootstrap/14_348382cfeeef9b97fc08e4323e63bd35b7832ce4_DevFrameworkBootstrap_t.java
UTF-8
6,785
1.859375
2
[]
no_license
/* * (C) Copyright 2006-2010 Nuxeo SAS (http://nuxeo.com/) and contributors. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 2.1 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * Contributors: * bstefanescu */ package org.nuxeo.runtime.tomcat.dev; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.Timer; import java.util.TimerTask; import org.nuxeo.osgi.application.FrameworkBootstrap; import org.nuxeo.osgi.application.MutableClassLoader; /** * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a> * */ public class DevFrameworkBootstrap extends FrameworkBootstrap { protected File devBundlesFile; protected DevBundle[] devBundles; protected Timer bundlesCheck; protected long lastModified = 0; public DevFrameworkBootstrap(ClassLoader cl, File home) throws IOException { super(cl, home); } public DevFrameworkBootstrap(MutableClassLoader cl, File home) throws IOException { super(cl, home); devBundlesFile = new File(home, "dev.bundles"); } @Override public void start() throws Exception { // check if we have dev. bundles or libs to deploy and add them to the // classpath preloadDevBundles(); // start the framework super.start(); // start dev bundles if any postloadDevBundles(); // start reload timer bundlesCheck = new Timer("Dev Bundles Loader"); bundlesCheck.scheduleAtFixedRate(new TimerTask() { @Override public void run() { try { checkDevBundles(); } catch (Throwable t) { log.error("Error running dev mode timer", t); } } }, 2000, 2000); } @Override public void stop() throws Exception { if (bundlesCheck != null) { bundlesCheck.cancel(); bundlesCheck = null; } super.stop(); } /** * Load the development bundles and libs if any in the classpath before * starting the framework. */ protected void preloadDevBundles() throws IOException { if (devBundlesFile.isFile()) { lastModified = devBundlesFile.lastModified(); devBundles = getDevBundles(); if (devBundles.length == 0) { devBundles = null; return; } // clear dev classloader NuxeoDevWebappClassLoader devLoader = (NuxeoDevWebappClassLoader) loader; devLoader.clear(); URL[] urls = new URL[devBundles.length]; for (int i = 0; i < devBundles.length; i++) { urls[i] = devBundles[i].url(); } devLoader.createLocalClassLoader(urls); } } protected void postloadDevBundles() throws Exception { if (devBundles != null) { for (DevBundle bundle : devBundles) { if (!bundle.isLibrary()) { bundle.name = installBundle(bundle.file); } } } } protected void checkDevBundles() { long tm = devBundlesFile.lastModified(); if (lastModified >= tm) { return; } lastModified = tm; try { reloadDevBundles(getDevBundles()); } catch (Exception e) { log.error("Faied to deploy dev bundles", e); } } protected DevBundle[] getDevBundles() throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader( new FileInputStream(devBundlesFile))); try { ArrayList<DevBundle> urls = new ArrayList<DevBundle>(); String line = reader.readLine(); while (line != null) { line = line.trim(); if (line.length() > 0 && !line.startsWith("#")) { if (line.startsWith("!")) { // a library urls.add(new DevBundle(new File(line.substring(1)), true)); } else { // a bundle urls.add(new DevBundle(new File(line))); } } line = reader.readLine(); } return urls.toArray(new DevBundle[urls.size()]); } finally { reader.close(); } } protected synchronized void reloadDevBundles(DevBundle[] bundles) throws Exception { if (devBundles != null) { // undeploy for (DevBundle bundle : devBundles) { if (!bundle.isLibrary()) { if (bundle.name != null) { uninstallBundle(bundle.name); } } } } devBundles = bundles; // clear dev classloader NuxeoDevWebappClassLoader devLoader = (NuxeoDevWebappClassLoader) loader; devLoader.clear(); System.gc(); URL[] urls = new URL[bundles.length]; for (int i = 0; i < bundles.length; i++) { urls[i] = bundles[i].url(); } devLoader.createLocalClassLoader(urls); // deploy for (DevBundle bundle : devBundles) { if (!bundle.isLibrary()) { bundle.name = installBundle(bundle.file); } } } static class DevBundle { String name; // the bundle symbolic name if not a lib boolean isLibrary; File file; public DevBundle(File file) { this(file, false); } public DevBundle(File file, boolean isLibrary) { this.file = file; this.isLibrary = isLibrary; } public URL url() throws IOException { return file.toURI().toURL(); } public boolean isLibrary() { return isLibrary; } } }
true