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
00088c3263d18dc8e459652c0b35e60d7f0d4a68
Java
victor-gpaje/OkapiBarcode
/src/main/java/uk/org/okapibarcode/gui/SaveImage.java
UTF-8
2,454
2.09375
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2014 Robin Stuart and Robert Elliott * * 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 uk.org.okapibarcode.gui; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import javax.swing.JPanel; import uk.org.okapibarcode.output.PostScript; import uk.org.okapibarcode.output.ScalableVectorGraphics; /** * Save bar code image to image file * * @author <a href="mailto:jakel2006@me.com">Robert Elliott</a> */ public class SaveImage { public void saveImage(File file, JPanel panel) throws IOException { String extension = ""; int i = file.getName().lastIndexOf('.'); if (i > 0) { extension = file.getName().substring(i + 1); } BufferedImage img = new BufferedImage(panel.getWidth(), panel.getHeight(), BufferedImage.TYPE_INT_RGB); panel.paint(img.getGraphics()); switch (extension) { case "png": case "gif": case "jpg": case "bmp": ImageIO.write(img, extension, file); break; case "svg": ScalableVectorGraphics svg = new ScalableVectorGraphics(); svg.setShapes(OkapiUI.symbol.rect, OkapiUI.symbol.txt, OkapiUI.symbol.hex, OkapiUI.symbol.target); svg.setValues(OkapiUI.dataInput, OkapiUI.symbol.getWidth(), OkapiUI.symbol.getHeight()); svg.write(file); break; case "eps": PostScript eps = new PostScript(); eps.setShapes(OkapiUI.symbol.rect, OkapiUI.symbol.txt, OkapiUI.symbol.hex, OkapiUI.symbol.target); eps.setValues(OkapiUI.dataInput, OkapiUI.symbol.getWidth(), OkapiUI.symbol.getHeight()); eps.write(file); break; default: System.out.println("Unsupported output format"); break; } } }
true
b210cd342fa90966fe673c4e70aab370b4329a3f
Java
darkcross174/Vk
/src/main/java/domain/LikesInfo.java
UTF-8
219
1.53125
2
[]
no_license
package domain; public class LikesInfo { private int count; private boolean canLikes; private boolean canPublish; private boolean userLikes; // + get/set на все поля }
true
97be032ab83212aac2ace4259977535bd03064de
Java
malakeel/jetspeed-portal
/jetspeed-api/src/main/java/org/apache/jetspeed/components/persistence/store/PersistenceStore.java
UTF-8
4,140
1.929688
2
[ "CC-BY-SA-2.5", "AFL-2.1", "LicenseRef-scancode-unknown-license-reference", "MIT", "BSD-3-Clause", "Apache-2.0", "LicenseRef-scancode-other-copyleft", "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-proprietary-license" ]
permissive
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.jetspeed.components.persistence.store; import java.util.Collection; import java.util.Iterator; import org.apache.jetspeed.components.persistence.store.LockFailedException; /** * <p> * PersistenceStore * </p> * * <p> * The persistence store allows access to the persistent * storage mechanism within the application. * <br/> * PersistenceStore instances <strong>ARE NOT</strong> * thread safe. The best practices approach for using * the persistence store is to use * <code>PersistenceStoreContainer.getStoreForThread()</code> * any time the store is to be accessed. * * </p> * * @ * @author <a href="mailto:weaver@apache.org">Scott T. Weaver</a> * @version $ $ * */ public interface PersistenceStore { /** * No lock at all aka the object is read only changes WILL NOT be persisted * at checkPoints or commits. */ int LOCK_NO_LOCK = 0; /** * changes to the object will be written to the database, in this case the lock * will be automatically upgraded to the write lock on transaction */ int LOCK_READ = 1; /** * changes to the object will be written to the database. */ int LOCK_PESSIMISTIC = 2; void addEventListener(PersistenceStoreEventListener listener); void close(); void deletePersistent(Object obj) throws LockFailedException; void deleteAll(Object query) throws LockFailedException; Collection getCollectionByQuery(Object query); Collection getCollectionByQuery(Object query, int lockLevel); Object getObjectByQuery(Object query); Object getObjectByQuery(Object query, int lockLevel); Object getObjectByIdentity(Object object) throws LockFailedException; Object getObjectByIdentity(Object object, int lockLevel) throws LockFailedException; int getCount(Object query); Iterator getIteratorByQuery(Object query) ; Iterator getIteratorByQuery(Object query, int lockLevel); /** * * <p> * isClosed * </p> * <p> * indicates whether or not this <code>PersistenceStore</code> * instance has been closed. A closed store will generally * throw exceptions when any operation is performed upon it. * </p> * * @return * */ boolean isClosed(); /** * * <p> * getTransaction * </p> * <p> * Returns the current <code>Transaction</code> for thsis * <code>PersistenceStore</code> instance. The transaction * will always be the same for the lifetime of the * <code>PersistenceStore</code> instance. * </p> * * @return <code>Transaction</code> for this * <code>PersistenceStore</code> * */ Transaction getTransaction(); void invalidate(Object obj) throws LockFailedException; void invalidateAll() throws LockFailedException; void invalidateExtent(Class clazz) throws LockFailedException; void invalidateByQuery(Object query) throws LockFailedException; void lockForWrite(Object obj) throws LockFailedException; void makePersistent(Object obj) throws LockFailedException; Filter newFilter(); Object newQuery(Class clazz, Filter filter); Collection getExtent(Class clazz); Collection getExtent(Class clazz, int lockLevel); }
true
cd190893ec50989b7a8e3bb7965b0d8934558aef
Java
eishub/blocksworld
/src/main/java/environment/Square3D.java
UTF-8
3,293
3.234375
3
[]
no_license
package environment; /** BlocksWorld.java, version 1.11, December 9, 1998. Applet for interactive blocks world. Copyright 1998 by Rick Wagner, all rights reserved. Downloaded from http://rjwagner49.com/Science/ComputerScience/CS480/java/blocks/blocks.htm * Java source code is for educational purposes only. Viewing or downloading the * source implies your consent to obey the restrictions: * <p> * <ol> * <li>Use the source code for educational purposes only. * <li>Give appropriate attribution in all executables and listings. * <li>Reproduce these restrictions and conditions. * </ol> * @author Rick Wagner 1998 * @author W.Pasman cleanup and modifications separating model from renderer */ /** * A square in 3D is built up out of four corner points going around * counterclockwise as you look at the square from the outside of a solid it * might be a face of. A square can have any position and orientation in * 3-space. The center point of the square is used to compute average distance * for the perspective rendering painter's algorithm and is itself computed as * the average of its corner points. */ public class Square3D { private final Point3D V[]; // Vertex array, zeroeth element is the average public Square3D() { this.V = new Point3D[5]; this.V[0] = new Point3D(0, 0, 0); // Centered at the origin this.V[1] = new Point3D(50, 50, 0); this.V[2] = new Point3D(-50, 50, 0); this.V[3] = new Point3D(-50, -50, 0); this.V[4] = new Point3D(50, -50, 0); } public Square3D(final Point3D a, final Point3D b, final Point3D c, final Point3D d) { // Average x final float x = (a.getX() + b.getX() + c.getX() + d.getX()) / 4; // Average y final float y = (a.getY() + b.getY() + c.getY() + d.getY()) / 4; // Average z final float z = (a.getZ() + b.getZ() + c.getZ() + d.getZ()) / 4; this.V = new Point3D[5]; this.V[0] = new Point3D(x, y, z); this.V[1] = new Point3D(a); this.V[2] = new Point3D(b); this.V[3] = new Point3D(c); this.V[4] = new Point3D(d); } public Square3D(final Point3D a[]) { // Average x final float x = (a[1].getX() + a[2].getX() + a[3].getX() + a[4].getX()) / 4; // Average y final float y = (a[1].getY() + a[2].getY() + a[3].getY() + a[4].getY()) / 4; // Average z final float z = (a[1].getZ() + a[2].getZ() + a[3].getZ() + a[4].getZ()) / 4; this.V = new Point3D[5]; this.V[0] = new Point3D(x, y, z); this.V[1] = new Point3D(a[1]); this.V[2] = new Point3D(a[2]); this.V[3] = new Point3D(a[3]); this.V[4] = new Point3D(a[4]); } public Square3D(final Square3D s) { this.V = new Point3D[5]; this.V[0] = new Point3D(s.V[0]); this.V[1] = new Point3D(s.V[1]); this.V[2] = new Point3D(s.V[2]); this.V[3] = new Point3D(s.V[3]); this.V[4] = new Point3D(s.V[4]); } public Point3D getPoint(final int i) { return new Point3D(this.V[i]); // Makes a copy of the point } public void transform(final HMatrix3D m) { for (int i = 0; i <= 4; i++) { this.V[i].transform(m); // Transform all the points in the square } } public float getDSquared(final Point3D p) { return (this.V[0].getX() - p.getX()) * (this.V[0].getX() - p.getX()) + (this.V[0].getY() - p.getY()) * (this.V[0].getY() - p.getY()) + (this.V[0].getZ() - p.getZ()) * (this.V[0].getZ() - p.getZ()); } }
true
5a01e3c043b594bf61362c8fe205b733dfeddad1
Java
xuanzhiqiang/ActionOta
/app/src/main/java/com/linkplay/actionota/ble/MultipleBle/BleConfig.java
UTF-8
1,027
2.015625
2
[]
no_license
package com.linkplay.actionota.ble.MultipleBle; /** * This class sets various static property values for Bluetooth * Created by YeZhongJi on 2017/10/25. */ public class BleConfig { @SuppressWarnings("FieldCanBeLocal") public static String instruction_service_uuid = "0000ffc0-0000-1000-8000-00805F9B34FB"; public static String instruction_notifys_uuid = "0000ffc2-0000-1000-8000-00805F9B34FB"; public static String instruction_writes_uuid = "0000ffc1-0000-1000-8000-00805F9B34FB"; public static String jl_ota_service_uuid = "0000ae00-0000-1000-8000-00805F9B34FB"; public static String jl_ota_writes_uuid = "0000ae01-0000-1000-8000-00805F9B34FB"; public static String jl_ota_notifys_uuid = "0000ae02-0000-1000-8000-00805F9B34FB"; public static String jl_ota_service_uuid_1 = "00001812-0000-1000-8000-00805f9b34fb"; public static String[] support_service_uuid = { instruction_service_uuid, jl_ota_service_uuid, jl_ota_service_uuid_1 }; }
true
ade1b6b5a2c383e0ce48c82dfe7e4d82d3fff4a9
Java
kwjinwoo/datastructure-algorithm
/src/chap1_pr/chap1_Q16.java
UTF-8
542
2.828125
3
[]
no_license
package chap1_pr; import java.util.Scanner; public class chap1_Q16 { static void spira(int n) { for (int i = 0; i < n; i++) { for (int s = 0; s < n-1-i; s++) System.out.print(" "); for (int s = 0; s < (2*i)+1; s++) System.out.print("*"); for (int s = 0; s < n-1-i; s++) System.out.print(" "); System.out.println(); } } public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("enter the n : "); int n = sc.nextInt(); spira(n); } }
true
3db7da895bc361de18b7ec11d7828cf3031a7cb7
Java
VijayEluri/sandbox
/java/src/main/java/sandbox/SocketBacklog.java
UTF-8
434
2.59375
3
[]
no_license
package sandbox; import java.net.ServerSocket; import java.net.Socket; public class SocketBacklog { public static void main(String[] args) throws Exception { ServerSocket ss = new ServerSocket(33322, 1); for (int i = 0; i < 5; i++) { new Socket("localhost", 33322); } try { Thread.sleep(Long.MAX_VALUE); } catch (InterruptedException ignore) { } } }
true
3c86d93f77a58c178581e571f71352e0e8f0c59a
Java
Juanrubco/lapiara
/src/main/java/servlet/ConexionDB.java
UTF-8
1,422
2.90625
3
[]
no_license
package servlet; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.logging.Level; import java.util.logging.Logger; public class ConexionDB { private final String url; private Connection conn; public ConexionDB() { this.url ="jdbc:postgresql://ec2-52-86-73-86.compute-1.amazonaws.com:5432/d3conrtm1v0fbo?user=qcqumfeftmdbrg&password=d44dd5070d5f1d6598eb39e351045b04df87f889b8a3730ac9a7b81a34204ff4"; try { Class.forName("org.postgresql.Driver").newInstance(); this.conn = DriverManager.getConnection(url); if(this.conn!=null) System.out.println("Todo bien..estamos conectados..!!"); } catch (SQLException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } public Connection getConn() { return conn; } public void cierraConexion() { try { this.conn.close(); } catch(SQLException ex) { Logger.getLogger(ConexionDB.class.getName()).log(Level.SEVERE,null,ex); } } }
true
d476f19885230a1627cc196639e6508a7bdc0366
Java
linhaibin961/base
/src/main/java/com/hy/common/IGenericService.java
UTF-8
1,083
2.09375
2
[]
no_license
package com.hy.common; import com.github.pagehelper.PageInfo; import java.io.Serializable; import java.util.List; /** * Created by 2507868527@qq.com on 2016/3/24 15:20 . */ public interface IGenericService<T,ID extends Serializable> { void setMapper(IGenericMapper<T,ID> iGenericMapper); /** * 新增 * @param t 对象 */ boolean insert(T t); /** * 批量新增 * @param ts 对象集合 */ boolean batchInsert(List<T> ts); /** * 更新 * @param t 对象 */ boolean update(T t); /** * 删除 * @param id 主键 */ boolean delete(ID id); /** * 批量删除 * @param ids 主键集合 */ boolean batchDelete(List<ID> ids); /** * 获取记录(单条) * @param id 唯一主键 * @return */ T selectOne(ID id); /** * 获取多条 * @param t 对象 * @return */ List<T> selectAll(T t); /** * 分页查询 * @param t 对象 * @return */ PageInfo<T> selectWithPage(T t,Page page); }
true
c750c57cfb2b430b3a6b848f182b1746e8a2389f
Java
blackducksoftware/synopsys-detect
/detectable/src/test/java/com/synopsys/integration/detectable/detectables/git/parsing/model/GitConfigNodeTransformerTest.java
UTF-8
3,349
2.234375
2
[ "Apache-2.0" ]
permissive
package com.synopsys.integration.detectable.detectables.git.parsing.model; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import com.synopsys.integration.detectable.detectables.git.parsing.parse.GitConfigNodeTransformer; class GitConfigNodeTransformerTest { @Test void createGitConfig() { //#region Create GitConfigNodes // The core node should be ignored by the transformation. Map<String, String> coreProperties = new HashMap<>(); coreProperties.put("repositoryformatversion", "0"); coreProperties.put("filemode", "true"); GitConfigNode coreNode = new GitConfigNode("core", coreProperties); Map<String, String> remoteProperties = new HashMap<>(); remoteProperties.put("url", "https://github.com/blackducksoftware/synopsys-detect.git"); remoteProperties.put("fetch", "+refs/heads/*:refs/remotes/origin/"); GitConfigNode remoteNode = new GitConfigNode("remote", "origin", remoteProperties); Map<String, String> branchProperties = new HashMap<>(); branchProperties.put("remote", "origin"); branchProperties.put("merge", "refs/heads/master"); GitConfigNode branchNode = new GitConfigNode("branch", "master", branchProperties); Map<String, String> anotherBranchProperties = new HashMap<>(); anotherBranchProperties.put("remote", "origin"); anotherBranchProperties.put("merge", "refs/heads/another-branch"); GitConfigNode anotherBranch = new GitConfigNode("branch", "another-branch", anotherBranchProperties); List<GitConfigNode> gitConfigNodes = new ArrayList<>(); gitConfigNodes.add(coreNode); gitConfigNodes.add(remoteNode); gitConfigNodes.add(branchNode); gitConfigNodes.add(anotherBranch); //#endregion Create GitConfigNodes GitConfigNodeTransformer gitConfigNodeTransformer = new GitConfigNodeTransformer(); GitConfig gitConfig = gitConfigNodeTransformer.createGitConfig(gitConfigNodes); Assertions.assertEquals(1, gitConfig.getGitConfigRemotes().size()); GitConfigRemote gitConfigRemote = gitConfig.getGitConfigRemotes().get(0); Assertions.assertEquals("origin", gitConfigRemote.getName()); Assertions.assertEquals("https://github.com/blackducksoftware/synopsys-detect.git", gitConfigRemote.getUrl()); Assertions.assertEquals("+refs/heads/*:refs/remotes/origin/", gitConfigRemote.getFetch()); Assertions.assertEquals(2, gitConfig.getGitConfigBranches().size()); GitConfigBranch gitConfigBranch1 = gitConfig.getGitConfigBranches().get(0); Assertions.assertEquals("master", gitConfigBranch1.getName()); Assertions.assertEquals("origin", gitConfigBranch1.getRemoteName()); Assertions.assertEquals("refs/heads/master", gitConfigBranch1.getMerge()); GitConfigBranch gitConfigAnotherBranch = gitConfig.getGitConfigBranches().get(1); Assertions.assertEquals("another-branch", gitConfigAnotherBranch.getName()); Assertions.assertEquals("origin", gitConfigAnotherBranch.getRemoteName()); Assertions.assertEquals("refs/heads/another-branch", gitConfigAnotherBranch.getMerge()); } }
true
97d2b09a585960c22966208cf5e3f2fab5753e0c
Java
karthiknom7/data-structures-and-algorithms
/src/main/java/com/kk/learning/datastructuresandalgorithms/logical/array/EncodeString.java
UTF-8
753
3.546875
4
[]
no_license
package com.kk.learning.datastructuresandalgorithms.logical.array; public class EncodeString { public static String collapseString(String inputString) { System.out.println(inputString); if(inputString.isEmpty()) return inputString; int currentCharCount =1; String encodedString = ""; char[] chars = inputString.toCharArray(); for(int i=0; i < chars.length-1; i++){ if(chars[i] != chars[i+1]){ encodedString+= currentCharCount + "" + chars[i]; currentCharCount =1; }else { currentCharCount+=1; } } encodedString+= currentCharCount + "" + chars[chars.length-1]; return encodedString; } }
true
ed74555f51ed6d29ec21db84d2ca67d47c8f2b6b
Java
windtrack/jellylive
/JellyLive/app/src/main/java/com/oo58/jelly/adapter/FollowsAdapter.java
UTF-8
3,008
2.09375
2
[]
no_license
package com.oo58.jelly.adapter; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.nostra13.universalimageloader.core.DisplayImageOptions; import com.oo58.jelly.R; import com.oo58.jelly.entity.UserVo; import com.oo58.jelly.util.FollowListener; import com.oo58.jelly.manager.GlobalData; import com.oo58.jelly.manager.LocalImageManager; import com.oo58.jelly.util.Util; import com.oo58.jelly.view.CircleImageView; import java.util.List; /** * Desc: * Created by sunjinfang on 2016/6/21 9:09. */ public class FollowsAdapter extends BaseAdapter { private List<UserVo> list ; private Context context ; public DisplayImageOptions mOptions; public FollowsAdapter(Context context,List<UserVo> list){ this.context = context; this.list = list ; mOptions = new DisplayImageOptions.Builder() .showStubImage(R.mipmap.testpic).cacheInMemory() .showImageOnFail(R.mipmap.testpic) .showImageForEmptyUri(R.mipmap.testpic) .showImageOnLoading(R.mipmap.testpic) .cacheOnDisc().build(); } @Override public int getCount() { return list.size(); } @Override public Object getItem(int position) { return list.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { if(convertView == null){ //sear_item convertView = LayoutInflater.from(context).inflate(R.layout.sear_item,null); } CircleImageView img = (CircleImageView) convertView.findViewById(R.id.face); TextView name = (TextView) convertView.findViewById(R.id.name); final Button followBtn = (Button) convertView.findViewById(R.id.follow_btn); ImageView sexIcon = (ImageView) convertView.findViewById(R.id.sex); ImageView labelIcon = (ImageView) convertView.findViewById(R.id.label_icon); LinearLayout con = (LinearLayout) convertView.findViewById(R.id.content); final UserVo user = (UserVo)getItem(position) ; if(!Util.isEmpty(user.getIcon())){ GlobalData.getmImageLoader(context).displayImage(user.getIcon(),img,mOptions); } name.setText(user.getName()); LocalImageManager.setGender(context,sexIcon,user.getGender()); LocalImageManager.setWealthLev(context,labelIcon,user.getViplev()); followBtn.setOnClickListener(new FollowListener(context,user,list,followBtn,0)); con.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { } }); return convertView; } }
true
d90150e3c5314b55834f1c7c4b9cfca1dcaea89f
Java
flcat/baekjoon_test
/src/t2523.java
UTF-8
720
3.21875
3
[]
no_license
import java.io.*; public class t2523 { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); int n = Integer.parseInt(br.readLine()); for(int i = 1 ; i <= n ; i++){ for(int j = 1 ; j <= i ; j++){ bw.write("*"); } bw.write("\n"); } for(int k = n ; k >= 1 ; k--){ for(int l = k-1 ; l >= 1 ; l--){ bw.write("*"); } bw.write("\n"); } br.close(); bw.flush(); bw.close(); } }
true
40bd6e1a1e683293cc8c38e406f08269a571b2f7
Java
alextriplekill/TestWork
/src/test/java/TestWork/tests/Base/BaseTest.java
UTF-8
1,460
2.03125
2
[]
no_license
package TestWork.tests.Base; import TestWork.pages.Base_Page; import TestWork.pages.Filmix_Film_Page; import TestWork.pages.Filmix_Login_Form; import TestWork.pages.Filmix_Search_Page; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import java.util.concurrent.TimeUnit; public class BaseTest { static WebDriver driver; protected Base_Page testPage; protected Filmix_Login_Form filmix_login_form; protected Filmix_Search_Page filmix_search_page; protected Filmix_Film_Page filmix_film_page; @BeforeClass public static void init() { System.setProperty("webdriver.chrome.driver", "C:/chromedriver.exe"); } @Before public void openBasePage() { driver = new ChromeDriver(); driver.manage().window().maximize(); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); testPage = new Base_Page(driver); filmix_login_form = new Filmix_Login_Form(driver); filmix_search_page = new Filmix_Search_Page(driver); filmix_film_page = new Filmix_Film_Page(driver); testPage.openUrl("http://filmixme.net"); } @After public void closeTestWindow() { driver.close(); } @AfterClass public static void exitTestEnvironment() { driver.quit(); } }
true
3f0d79ebc5ade4c6be5e28bcb67464e8de3d96ea
Java
o2p-asiainfo/o2p-common
/src/main/java/com/ailk/eaap/o2p/common/util/LocalUtils.java
UTF-8
5,176
2.46875
2
[]
no_license
/** * Project Name:o2p-common * File Name:LocalUtils.java * Package Name:com.ailk.eaap.o2p.common.util * Date:2015年2月2日上午11:46:53 * Copyright (c) 2015, www.asiainfo.com All Rights Reserved. * */ package com.ailk.eaap.o2p.common.util; import java.io.File; import java.io.IOException; import java.net.Inet4Address; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.net.UnknownHostException; import java.util.Enumeration; import java.util.Iterator; import java.util.List; import org.apache.commons.io.FileUtils; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.springframework.util.StringUtils; import com.asiainfo.foundation.log.Logger; /** * ClassName:LocalUtils * Function: TODO ADD FUNCTION. * Reason: TODO ADD REASON. * Date: 2015年2月2日 上午11:46:53 * * @author zhongming * @version * @since JDK 1.6 * */ public class LocalUtils { private static final Logger log = Logger.getLog(CacheUtil.class); /** * 获取本地IP getLocalIp:(这里用一句话描述这个方法的作用). * TODO(这里描述这个方法适用条件 – 可选). * TODO(这里描述这个方法的执行流程 – 可选). * TODO(这里描述这个方法的使用方法 – 可选). * TODO(这里描述这个方法的注意事项 – 可选). * * @author zhongming * @return * @throws UnknownHostException * @since JDK 1.6 */ public static String getLocalIp() throws UnknownHostException { return InetAddress.getLocalHost().getHostAddress(); } /** * 获取本地IPV4 IP, 在linux和windows下适用 * @return * @throws UnknownHostException * @throws SocketException */ public static String getLocalRealIp() { try { Enumeration<NetworkInterface> allNetInterfaces; allNetInterfaces = NetworkInterface.getNetworkInterfaces(); InetAddress ip = null; String networkCardName = System.getProperty("networkCardName"); if(StringUtils.hasText(networkCardName)) { NetworkInterface netInterface = NetworkInterface.getByName(networkCardName); if(netInterface == null) { log.warn("no find networkcard of name {0}, use the default one", networkCardName); } else { Enumeration<InetAddress> addresses = netInterface .getInetAddresses(); while (addresses.hasMoreElements()) { ip = addresses.nextElement(); if (ip != null && (ip instanceof Inet4Address) && (!"127.0.0.1".equals(ip.getHostAddress()))) { return ip.getHostAddress(); } } log.warn("no find right ip address of the networkcard {0}, use the default one", networkCardName); } } else { log.warn("no find networkcard name in the system variable, use the default one"); } while (allNetInterfaces.hasMoreElements()) { NetworkInterface netInterface = allNetInterfaces.nextElement(); Enumeration<InetAddress> addresses = netInterface .getInetAddresses(); while (addresses.hasMoreElements()) { ip = addresses.nextElement(); if (ip != null && (ip instanceof Inet4Address) && (!"127.0.0.1".equals(ip.getHostAddress()))) { return ip.getHostAddress(); } } } return getLocalIp(); } catch (SocketException e) { return "127.0.0.1"; } catch (UnknownHostException e) { return "127.0.0.1"; } } // 获取服务器端口 public static String getLocalByWebPort(String type, String url) { return ""; } // 获取Tomcat端口 @SuppressWarnings("unchecked") public static String getLocalTomcatPort(String url) throws DocumentException, IOException { File file = new File(url); Document doc = DocumentHelper.parseText(FileUtils .readFileToString(file)); List<Element> list = doc .selectNodes("//Connector[@protocol='HTTP/1.1']"); if (list.size() == 0) { list = doc.selectNodes("//Connector[@protocol='org.apache.coyote.http11.Http11NioProtocol']"); } if (list.size() == 0) { return ""; } Element e = list.get(0); return e.attributeValue("port"); } // 获取WebLogic端口 @SuppressWarnings("unchecked") public static String getLocalWebLogicPort(String url) throws DocumentException, IOException { File file = new File(url); Document doc = DocumentHelper.parseText(FileUtils .readFileToString(file)); Iterator<Element> itRoot = doc.getRootElement().elementIterator(); while (itRoot.hasNext()) { Element element = itRoot.next(); if (element.getName().equals("server")) { return element.element("ssl").element("listen-port").getText(); } } return ""; } public static String getSystemVariable(String key) { try { String value = System.getProperty(key); if (value == null) { value = System.getenv(key); } return value; } catch (Exception ex) { if (log.isDebugEnabled()) { log.debug("Could not access system property '" + key + "': " + ex); } return null; } } // 获取Jboss端口 public static String getLocalJbossPort(String url) { return ""; } // 获取WebSphere public static String getLocalWebSpherePort(String url) { return ""; } }
true
047883b0f7c42cc0951589780f87edc421884cd8
Java
buzhidaoGH/community_ssm
/src/main/java/com/community/service/CommunityService.java
UTF-8
638
1.617188
2
[]
no_license
package com.community.service; import com.community.domain.Community; import com.community.domain.News; import java.util.List; public interface CommunityService { Community findOneCommunityData(String cnumber); Community findOneCommunityByCnumber(String cnumber); Integer findAllCountCommunity(); List<Community> findAllCommunityList(int page, int size, String cname); void changeCommunityNoticeIntroduction(String cnumber, String notice, String introduction); void changeCommunityImage(String cnumber); void createCommunity(Community community); void deleteCommunityBycnumber(String cnumber); }
true
4408f00d5187c6647300916480f66680aabbf9ac
Java
ShinMinHong/fems_admin
/fems-master/src/com/firealarm/admin/common/dao/DemonLogDAO.java
UTF-8
665
1.882813
2
[]
no_license
package com.firealarm.admin.common.dao; import java.util.HashMap; import java.util.List; import org.springframework.stereotype.Repository; import com.firealarm.admin.common.support.DAOSupport; import com.firealarm.admin.common.vo.IotDemonLogDT; import framework.util.AbleUtil; @Repository public class DemonLogDAO extends DAOSupport { /** * 처리하지 않은 Iot 로그 기록 조회 */ public List<IotDemonLogDT> getRecentNotConfirmList(int limtCount) { HashMap<String, Object> param = new HashMap<String, Object>(); param.put("limtCount", limtCount); return sqlSession.selectList(mapperNamespace + AbleUtil.getCurrentMethodName(), param); } }
true
a64e28936395665f2e6e018843f5c381f6ca815b
Java
angelomedina/MiniC-Sharp
/src/Checker/Analizadores/AC_Llamadas_Funciones.java
UTF-8
21,480
2.859375
3
[]
no_license
package Checker.Analizadores; import Antlr.MyParser; import Antlr.MyParserBaseVisitor; import Checker.TypeSymbol.*; import org.antlr.v4.runtime.Token; import java.util.LinkedList; import java.util.List; public class AC_Llamadas_Funciones extends MyParserBaseVisitor { private int numErrors; public SymbolTable tableS; private String error = ""; private boolean debeTenerRetorno = false; private boolean en_funcion = false; private String funcion_actual = ""; public LinkedList<String> listaErrores = new LinkedList<String>(); public int getNumErrors() { return numErrors; } public AC_Llamadas_Funciones(SymbolTable tablaS){ this.tableS = tablaS; this.numErrors=0; } public String imprimir(){ return tableS.toString(); } public boolean hasErrors(){ if (this.numErrors==0) return false; else return true; } // Program AST @Override public Object visitProgramAST(MyParser.ProgramASTContext ctx) { this.numErrors = 0; for (MyParser.MethodDeclContext e : ctx.methodDecl()){ visit(e); } // this.tableF.closeScope(); return null; } @Override public Object visitMethodTypeDeclAST(MyParser.MethodTypeDeclASTContext ctx) { debeTenerRetorno = true; return null; } // Method Declaration @Override public Object visitMethodDeclAST(MyParser.MethodDeclASTContext ctx) { en_funcion = true; funcion_actual = ctx.IDENT().getText(); // System.out.println("Ret 1 "+debeTenerRetorno); visit(ctx.optionMethodDecl()); // System.out.println("Ret 2 "+debeTenerRetorno); visit(ctx.block()); // System.out.println("Retorno despues "+debeTenerRetorno); if(debeTenerRetorno){ numErrors++; error = "Error, la funcion "+ funcion_actual+ " debe tener un valor de retorno."; listaErrores.push(error); } return null; } // Block @Override public Object visitBlockAST(MyParser.BlockASTContext ctx) { for (MyParser.StatementContext e: ctx.statement()) { visit(e); } return null; } // statementIgSTAST @Override public Object visitStatementIgSTAST(MyParser.StatementIgSTASTContext ctx) { Symbol existDesignator = tableS.retrieve(ctx.designator().getText()); Symbol existExpre = tableS.retrieve(ctx.expr().getText()); if( existExpre != null && existDesignator != null) { if(existDesignator.equals("int")){ if(!existDesignator.equals("int")) { numErrors++; error = "Semantic Error Incompatible types in StatementIgSTAST between " + existDesignator.getName() + " and " + existExpre.getName() ; listaErrores.push(error); } } if(existDesignator.equals("char")){ if(!existDesignator.equals("char")) { numErrors++; error = "Semantic Error Incompatible types in StatementIgSTAST between " + existDesignator.getName() + " and " + existExpre.getName() ; listaErrores.push(error); } } } visit(ctx.designator()); visit(ctx.expr()); return null; } @Override public Object visitStatementMetSTAST(MyParser.StatementMetSTASTContext ctx) { Symbol elemento = tableS.retrieve(ctx.designator().getText()); if (elemento != null) { if(elemento.getIdSimbolo().equals("Funcion") ){ // Si es una funcion verificar_elementos((Funcion)elemento,ctx.actPars()); } } else { numErrors++; error = "Error el elemento "+ctx.designator().getText() +" no existe."; listaErrores.push(error); } // } //System.out.println("Funcion params -> "+ctx.actPars()); return null; } @Override public Object visitStatementIncSTAST(MyParser.StatementIncSTASTContext ctx) { visit(ctx.designator()); return null; } @Override public Object visitStatementDecSTAST(MyParser.StatementDecSTASTContext ctx) { visit(ctx.designator()); return null; } @Override public Object visitDesignatorAST(MyParser.DesignatorASTContext ctx) { for (MyParser.DesignatorExpContext e: ctx.designatorExp()) { visit(e); } return null; } @Override public Object visitDesignatorCorcsAST(MyParser.DesignatorCorcsASTContext ctx) { visit(ctx.expr()); return null; } @Override public Object visitIfSTAST(MyParser.IfSTASTContext ctx) { visit(ctx.condition()); visit(ctx.statement(0)); visit(ctx.statement(1)); return null; } @Override public Object visitForSTAST(MyParser.ForSTASTContext ctx) { visit(ctx.expr()); visit(ctx.condition()); visit(ctx.statement(0)); visit(ctx.statement(1)); return null; } @Override public Object visitWhileSTAST(MyParser.WhileSTASTContext ctx) { visit(ctx.condition()); visit(ctx.statement()); return null; } public static boolean isNumeric(String cadena) { boolean resultado; try { Integer.parseInt(cadena); resultado = true; } catch (NumberFormatException excepcion) { resultado = false; } return resultado; } public String obtenerNombreElemento(String elemento){ String nombre = ""; for(int i = 0; i<elemento.length(); i++){ if(elemento.charAt(i) == '(' || elemento.charAt(i) == '['){ return nombre; }else{ nombre+=elemento.charAt(i); } } return nombre; } @Override public Object visitReturnSTAST(MyParser.ReturnSTASTContext ctx) { Symbol elementoFuncion = tableS.retrieve(funcion_actual); Symbol elemento,elementoAUX; //System.out.println("En return "+ctx.expr().getText()); if(ctx.expr()!= null) { visit(ctx.expr()); } if(en_funcion && !elementoFuncion.getType().equals("void")) { if (ctx.expr() == null) { numErrors++; error = "Error se debe retornar un valor."; listaErrores.push(error); } else { if (isNumeric(ctx.expr().getText())) { // Si el retorno es un numero if(!elementoFuncion.getType().equals("int")){ // y el tipo de retorno no es un numero numErrors++; error = "Error, el tipo de valor retornado por la funcion no debe ser int"; listaErrores.push(error); } } else if(ctx.expr().getText().equals("true") || ctx.expr().getText().equals("false")) { // Si el retorno es un valor booleano if(!elementoFuncion.getType().equals("bool")){ // y el tipo retorno no es un booleano numErrors++; error = "Error, el tipo de valor retornado por la funcion no debe ser booleano"; listaErrores.push(error); } } else if(ctx.expr().getText().contains("(") || ctx.expr().getText().contains("[")){// Si es la llamada a una funcion o un arreglo String nombreE = obtenerNombreElemento(ctx.expr().getText()); if(!nombreE.equals("")){ elementoAUX = tableS.retrieve(nombreE); if(elementoAUX != null){ if(!elementoAUX.getType().equals(elementoFuncion.getType())){ numErrors++; error = "El tipo de retorno del elemento "+elementoAUX.getName()+ " es "+elementoAUX.getType()+" . Sin embargo, deben ser "+elementoFuncion.getType(); listaErrores.push(error); } } } else{ // FALTA DE VALIDAR EXPRESION COMPLEJA } } else { elemento = tableS.retrieve(ctx.expr().getText()); if (elemento != null) { if (!elementoFuncion.getType().equals(elemento.getType())) { numErrors++; error = "Error, el tipo de valor retornado es " + elemento.getType() + ", pero debe ser " + elementoFuncion.getType() + " ."; listaErrores.push(error); } //System.out.println("Lo que estoy retornando "+ctx.expr().getText()); //System.out.println("Lo que debo retornar "+elementoFuncion.getType()); } else { numErrors++; error = "Error, el elemento "+ctx.expr().getText()+ " no existe."; listaErrores.push(error); } } } }else { // Si no estoy dentro de una funcion numErrors++; error = "La funcion no retorna valores"; listaErrores.push(error); } funcion_actual = ""; en_funcion = false; debeTenerRetorno = false; // Si encontro el retorno return null; } @Override public Object visitReadSTAT(MyParser.ReadSTATContext ctx) { visit(ctx.designator()); return null; } @Override public Object visitWriteSTAST(MyParser.WriteSTASTContext ctx) { /* visit(ctx.expr()); visit(ctx.writeType()); return null; */ return super.visitWriteSTAST(ctx); } @Override public Object visitBlockSTAST(MyParser.BlockSTASTContext ctx) { return super.visitBlockSTAST(ctx); } @Override public Object visitWriteTypeNumIntSTAST(MyParser.WriteTypeNumIntSTASTContext ctx) { return super.visitWriteTypeNumIntSTAST(ctx); } @Override public Object visitWriteTypeNumIntZSTAST(MyParser.WriteTypeNumIntZSTASTContext ctx) { return super.visitWriteTypeNumIntZSTAST(ctx); } @Override public Object visitWriteTypeNumFloatSTAST(MyParser.WriteTypeNumFloatSTASTContext ctx) { return super.visitWriteTypeNumFloatSTAST(ctx); } @Override public Object visitExprAST(MyParser.ExprASTContext ctx) { //System.out.println("En expr"); for (MyParser.TermContext e: ctx.term()) { visit(e); } return null; } @Override public Object visitTermAST(MyParser.TermASTContext ctx) { // System.out.println("En temr"); for (MyParser.FactorContext e: ctx.factor()) { //System.out.println("Visitando factors"); visit(e); } return null; } @Override public Object visitFactorFAST(MyParser.FactorFASTContext ctx) { Symbol elemento = tableS.retrieve(ctx.designator().getText()); if (elemento != null) { if (elemento.getIdSimbolo().equals("Funcion")) { // Si es una funcion verificar_elementos((Funcion) elemento, ctx.actPars()); }else{ if(ctx.actPars() != null){ numErrors++; error = "Error el elemento " + ctx.designator().getText()+ " no es una funcion."; listaErrores.push(error); } } } else { numErrors++; error = "Error el elemento "+ctx.designator().getText() +" no existe."; listaErrores.push(error); } // } //System.out.println("Funcion params -> "+ctx.actPars()); return null; } public boolean esFuncion(String elemento){ if(elemento.contains("(") || elemento.contains(")")){ System.out.println("FALSE"); return false; } System.out.println("TRUE"); return true; } private void verificar_elementos(Funcion elemento, MyParser.ActParsContext actPars) { // System.out.println("EEEEEEEEEEEEEEEEE "+elemento.getName()); List<String> parametros_recibidos = new LinkedList<>(); FuncionSpecial funcionSpecial = null; FuncionNormal funcionNormal = null; // Verifico la cantidad de parametros if((actPars == null && elemento.getnParams() > 0)){ // Si la llamada no tiene parametros, pero la funcion recibe. numErrors++; error = "Error el numero de parametros recibidos es incorrecto"; listaErrores.push(error); } if(actPars != null){ for (int d = 0; d<actPars.getChildCount();d++) { if(!actPars.getChild(d).getText().equals(",")) { parametros_recibidos.add(actPars.getChild(d).getText()); //System.out.println("H "+ctx.actPars().getChild(d).getText()); } } if(parametros_recibidos.size() != elemento.getnParams()){ numErrors++; error = "Error el numero de parametros recibidos en la funcion "+elemento.getName()+" es incorrecto"; listaErrores.push(error); } else { //System.out.println("NA "+tableS.actuaLevel); for (int x = 0; x < parametros_recibidos.size(); x++) { Symbol elem = tableS.retrieve(parametros_recibidos.get(x)); if (elem == null) { //System.out.println("PR - " + parametros_recibidos.get(x)); // if (esFuncion(parametros_recibidos.get(x))) { numErrors++; error = "Error el elemento " + parametros_recibidos.get(x) + " no existe."; listaErrores.push(error); break; //} /*else { System.out.println("Funcion como parametro FALTA"); }*/ } else { if(elemento.getName().equals("len") || elemento.getName().equals("ord") || elemento.getName().equals("chr")){ //System.out.println("Funcion special "+elemento.getName()); // Convierto a una funcion especial funcionSpecial = (FuncionSpecial) elemento; if(elemento.getName().equals("len")){// Si la funcion es len, verifico si la variable es un arreglo // System.out.println("->> Elemento "+elem.getIdSimbolo()+ " <<-"); if(elem.getIdSimbolo().equals("Variable")){ // Si no es un arreglo numErrors++; error = "Error el elemento "+elem.getName()+" no es un arreglo"; listaErrores.push(error); } } else { if (!elem.getType().equals(funcionSpecial.getType())) { numErrors++; error = "Error el elemento " + parametros_recibidos.get(x) + " debe ser de tipo " + funcionSpecial.getType() + " ."; listaErrores.push(error); } } } else { // Convierto la funcion a una funcion normal funcionNormal = (FuncionNormal) elemento; if (!elem.getType().equals(funcionNormal.getParamsType().get(x))) { numErrors++; error = "Error el elemento " + parametros_recibidos.get(x) + " debe ser de tipo " + funcionNormal.getParamsType().get(x); listaErrores.push(error); } } } } } } } // public boolean alcance (){ //} @Override public Object visitExpresionFAST(MyParser.ExpresionFASTContext ctx) { visit(ctx.expr()); return null; } @Override public Object visitActParsAST(MyParser.ActParsASTContext ctx) { //System.out.println("En actpars"); for (MyParser.ExprContext e : ctx.expr()) { Token elemento = (Token) visit(e); //params.add(elemento.getText()); System.out.println(elemento.getText()); } return null; } @Override public Object visitConditionAST(MyParser.ConditionASTContext ctx) { for (MyParser.CondTermContext e: ctx.condTerm()) { visit(e); } return null; } @Override public Object visitCondTermAST(MyParser.CondTermASTContext ctx) { for (MyParser.CondFactContext e: ctx.condFact()) { visit(e); } return null; } public boolean isInteger(String numero){ try{ Integer.parseInt(numero); return true; }catch(NumberFormatException e){ return false; } } @Override public Object visitCondFactAST(MyParser.CondFactASTContext ctx) { // 1. Verifico si ambos son id: a<b if(isInteger(ctx.expr(0).getText()) != true && isInteger(ctx.expr(1).getText()) != true) { Symbol existExpreI = tableS.retrieve(ctx.expr(0).getText()); Symbol existExpreII = tableS.retrieve(ctx.expr(1).getText()); if(!existExpreI.getType().equals("int") || !existExpreII.getType().equals("int")) { numErrors++; error = "Semantic Error Incompatible types in CondFactAST between " + existExpreI.getType() + " and " + existExpreII.getType(); listaErrores.push(error); }else{ visit(ctx.expr(0)); visit(ctx.relop()); visit(ctx.expr(1)); return null; } } // 2. verifico: a < 10 if(isInteger(ctx.expr(0).getText()) != true){ Symbol existExpreI = tableS.retrieve(ctx.expr(0).getText()); if(existExpreI != null && isInteger(ctx.expr(1).getText()) == true){ if(!existExpreI.getType().equals("int")) { numErrors++; error = "Semantic Error Incompatible types in CondFactAST between " + existExpreI.getName() + " and " + ctx.expr(1).getText(); listaErrores.push(error); }else{ visit(ctx.expr(0)); visit(ctx.relop()); visit(ctx.expr(1)); return null; } }else{ numErrors++; error = "Semantic Error Incompatible types in CondFactAST between " + existExpreI.getName() + " and " + ctx.expr(1).getText(); listaErrores.push(error); } } // 2. verifico: 10 < a if(isInteger(ctx.expr(1).getText()) != true){ Symbol existExpreI = tableS.retrieve(ctx.expr(1).getText()); if(existExpreI != null && isInteger(ctx.expr(0).getText()) == true){ if(!existExpreI.getType().equals("int")) { numErrors++; error = "Semantic Error Incompatible types in CondFactAST between " + existExpreI.getName() + " and " + ctx.expr(0).getText(); listaErrores.push(error); }else{ visit(ctx.expr(0)); visit(ctx.relop()); visit(ctx.expr(1)); return null; } }else{ numErrors++; error = "Semantic Error Incompatible types in CondFactAST between " + existExpreI.getName() + " and " + ctx.expr(0).getText(); listaErrores.push(error); } } visit(ctx.expr(0)); visit(ctx.relop()); visit(ctx.expr(1)); return null; } }
true
30f3cda69e1998ca8a8fcbff5f0251e291a29146
Java
Mattsteban/andevcon-2016-hackathon
/app/src/main/java/com/mattsteban/checkyoself/views/FiveStarRatingView.java
UTF-8
3,324
2.578125
3
[]
no_license
package com.mattsteban.checkyoself.views; import android.content.Context; import android.content.res.TypedArray; import android.util.AttributeSet; import android.view.LayoutInflater; import android.widget.ImageView; import android.widget.LinearLayout; import com.mattsteban.checkyoself.R; /** * Created by matt on 8/1/16. */ public class FiveStarRatingView extends LinearLayout { public ImageView star1; public ImageView star2; public ImageView star3; public ImageView star4; public ImageView star5; private int totalStars = 0; public FiveStarRatingView(Context context, AttributeSet attrs){ super(context,attrs); LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); inflater.inflate(R.layout.inflatable_five_star_layout, this, true); handleItBaby(context,attrs); } public FiveStarRatingView(Context context, AttributeSet attrs,int totalStars){ super(context,attrs); LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); inflater.inflate(R.layout.inflatable_five_star_layout, this, true); this.totalStars = totalStars; handleItBaby(context,attrs); } private void handleItBaby(Context context , AttributeSet attrs){ bindViews(); handleAttrs(context,attrs); updateStars(totalStars); } private void handleAttrs(Context context,AttributeSet attrs){ TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.rating_view); this.totalStars = a.getInt(R.styleable.rating_view_stars,0); } public void updateStars(int totalStars){ reset(); switch (totalStars){ case 5: star5.setBackground(getResources().getDrawable(R.drawable.filled_star)); case 4: star4.setBackground(getResources().getDrawable(R.drawable.filled_star)); case 3: star3.setBackground(getResources().getDrawable(R.drawable.filled_star)); case 2: star2.setBackground(getResources().getDrawable(R.drawable.filled_star)); case 1: star1.setBackground(getResources().getDrawable(R.drawable.filled_star)); case 0: break; } } public void reset(){ star1.setBackground(getResources().getDrawable(R.drawable.empty_star)); star2.setBackground(getResources().getDrawable(R.drawable.empty_star)); star3.setBackground(getResources().getDrawable(R.drawable.empty_star)); star4.setBackground(getResources().getDrawable(R.drawable.empty_star)); star5.setBackground(getResources().getDrawable(R.drawable.empty_star)); } public void setTotalStars(int stars){ totalStars = stars; updateStars(totalStars); } public int getTotalStars(){ return totalStars; } private void bindViews(){ star1 = (ImageView) findViewById(R.id.star1); star2 = (ImageView)findViewById(R.id.star2); star3 = (ImageView)findViewById(R.id.star3); star4 = (ImageView)findViewById(R.id.star4); star5 = (ImageView)findViewById(R.id.star5); } }
true
c02558ec36c7ffdf55434d7a58fa739fbe159caf
Java
fiorentinogiuseppe/Projetos_UFRPE
/2018.2/IA/Projeto/weka_source_from_jdcore/weka/classifiers/bayes/HNB.java
UTF-8
8,386
2.125
2
[]
no_license
package weka.classifiers.bayes; import weka.classifiers.Classifier; import weka.core.Attribute; import weka.core.Capabilities; import weka.core.Capabilities.Capability; import weka.core.Instance; import weka.core.Instances; import weka.core.RevisionUtils; import weka.core.TechnicalInformation; import weka.core.TechnicalInformation.Field; import weka.core.TechnicalInformation.Type; import weka.core.TechnicalInformationHandler; import weka.core.Utils; public class HNB extends Classifier implements TechnicalInformationHandler { static final long serialVersionUID = -4503874444306113214L; private double[] m_ClassCounts; private double[][][] m_ClassAttAttCounts; private int[] m_NumAttValues; private int m_TotalAttValues; private int m_NumClasses; private int m_NumAttributes; private int m_NumInstances; private int m_ClassIndex; private int[] m_StartAttIndex; private double[][] m_condiMutualInfo; public HNB() {} public String globalInfo() { return "Contructs Hidden Naive Bayes classification model with high classification accuracy and AUC.\n\nFor more information refer to:\n\n" + getTechnicalInformation().toString(); } public TechnicalInformation getTechnicalInformation() { TechnicalInformation result = new TechnicalInformation(TechnicalInformation.Type.INPROCEEDINGS); result.setValue(TechnicalInformation.Field.AUTHOR, "H. Zhang and L. Jiang and J. Su"); result.setValue(TechnicalInformation.Field.TITLE, "Hidden Naive Bayes"); result.setValue(TechnicalInformation.Field.BOOKTITLE, "Twentieth National Conference on Artificial Intelligence"); result.setValue(TechnicalInformation.Field.YEAR, "2005"); result.setValue(TechnicalInformation.Field.PAGES, "919-924"); result.setValue(TechnicalInformation.Field.PUBLISHER, "AAAI Press"); return result; } public Capabilities getCapabilities() { Capabilities result = super.getCapabilities(); result.disableAll(); result.enable(Capabilities.Capability.NOMINAL_ATTRIBUTES); result.enable(Capabilities.Capability.NOMINAL_CLASS); result.enable(Capabilities.Capability.MISSING_CLASS_VALUES); return result; } public void buildClassifier(Instances instances) throws Exception { getCapabilities().testWithFail(instances); instances = new Instances(instances); instances.deleteWithMissingClass(); m_NumClasses = instances.numClasses(); m_ClassIndex = instances.classIndex(); m_NumAttributes = instances.numAttributes(); m_NumInstances = instances.numInstances(); m_TotalAttValues = 0; m_StartAttIndex = new int[m_NumAttributes]; m_NumAttValues = new int[m_NumAttributes]; for (int i = 0; i < m_NumAttributes; i++) { if (i != m_ClassIndex) { m_StartAttIndex[i] = m_TotalAttValues; m_NumAttValues[i] = instances.attribute(i).numValues(); m_TotalAttValues += m_NumAttValues[i]; } else { m_StartAttIndex[i] = -1; m_NumAttValues[i] = m_NumClasses; } } m_ClassCounts = new double[m_NumClasses]; m_ClassAttAttCounts = new double[m_NumClasses][m_TotalAttValues][m_TotalAttValues]; for (int k = 0; k < m_NumInstances; k++) { int classVal = (int)instances.instance(k).classValue(); m_ClassCounts[classVal] += 1.0D; int[] attIndex = new int[m_NumAttributes]; for (int i = 0; i < m_NumAttributes; i++) { if (i == m_ClassIndex) { attIndex[i] = -1; } else attIndex[i] = (m_StartAttIndex[i] + (int)instances.instance(k).value(i)); } for (int Att1 = 0; Att1 < m_NumAttributes; Att1++) { if (attIndex[Att1] != -1) { for (int Att2 = 0; Att2 < m_NumAttributes; Att2++) { if (attIndex[Att2] != -1) { m_ClassAttAttCounts[classVal][attIndex[Att1]][attIndex[Att2]] += 1.0D; } } } } } m_condiMutualInfo = new double[m_NumAttributes][m_NumAttributes]; for (int son = 0; son < m_NumAttributes; son++) { if (son != m_ClassIndex) { for (int parent = 0; parent < m_NumAttributes; parent++) { if ((parent != m_ClassIndex) && (son != parent)) { m_condiMutualInfo[son][parent] = conditionalMutualInfo(son, parent); } } } } } private double conditionalMutualInfo(int son, int parent) throws Exception { double CondiMutualInfo = 0.0D; int sIndex = m_StartAttIndex[son]; int pIndex = m_StartAttIndex[parent]; double[] PriorsClass = new double[m_NumClasses]; double[][] PriorsClassSon = new double[m_NumClasses][m_NumAttValues[son]]; double[][] PriorsClassParent = new double[m_NumClasses][m_NumAttValues[parent]]; double[][][] PriorsClassParentSon = new double[m_NumClasses][m_NumAttValues[parent]][m_NumAttValues[son]]; for (int i = 0; i < m_NumClasses; i++) { PriorsClass[i] = (m_ClassCounts[i] / m_NumInstances); } for (int i = 0; i < m_NumClasses; i++) { for (int j = 0; j < m_NumAttValues[son]; j++) { PriorsClassSon[i][j] = (m_ClassAttAttCounts[i][(sIndex + j)][(sIndex + j)] / m_NumInstances); } } for (int i = 0; i < m_NumClasses; i++) { for (int j = 0; j < m_NumAttValues[parent]; j++) { PriorsClassParent[i][j] = (m_ClassAttAttCounts[i][(pIndex + j)][(pIndex + j)] / m_NumInstances); } } for (int i = 0; i < m_NumClasses; i++) { for (int j = 0; j < m_NumAttValues[parent]; j++) { for (int k = 0; k < m_NumAttValues[son]; k++) { PriorsClassParentSon[i][j][k] = (m_ClassAttAttCounts[i][(pIndex + j)][(sIndex + k)] / m_NumInstances); } } } for (int i = 0; i < m_NumClasses; i++) { for (int j = 0; j < m_NumAttValues[parent]; j++) { for (int k = 0; k < m_NumAttValues[son]; k++) { CondiMutualInfo += PriorsClassParentSon[i][j][k] * log2(PriorsClassParentSon[i][j][k] * PriorsClass[i], PriorsClassParent[i][j] * PriorsClassSon[i][k]); } } } return CondiMutualInfo; } private double log2(double x, double y) { if ((x < 1.0E-6D) || (y < 1.0E-6D)) { return 0.0D; } return Math.log(x / y) / Math.log(2.0D); } public double[] distributionForInstance(Instance instance) throws Exception { double[] probs = new double[m_NumClasses]; int[] attIndex = new int[m_NumAttributes]; for (int att = 0; att < m_NumAttributes; att++) { if (att == m_ClassIndex) { attIndex[att] = -1; } else { attIndex[att] = (m_StartAttIndex[att] + (int)instance.value(att)); } } for (int classVal = 0; classVal < m_NumClasses; classVal++) { probs[classVal] = ((m_ClassCounts[classVal] + 1.0D / m_NumClasses) / (m_NumInstances + 1.0D)); for (int son = 0; son < m_NumAttributes; son++) if (attIndex[son] != -1) { int sIndex = attIndex[son]; attIndex[son] = -1; double prob = 0.0D; double condiMutualInfoSum = 0.0D; for (int parent = 0; parent < m_NumAttributes; parent++) if (attIndex[parent] != -1) { condiMutualInfoSum += m_condiMutualInfo[son][parent]; prob += m_condiMutualInfo[son][parent] * (m_ClassAttAttCounts[classVal][attIndex[parent]][sIndex] + 1.0D / m_NumAttValues[son]) / (m_ClassAttAttCounts[classVal][attIndex[parent]][attIndex[parent]] + 1.0D); } if (condiMutualInfoSum > 0.0D) { prob /= condiMutualInfoSum; probs[classVal] *= prob; } else { prob = (m_ClassAttAttCounts[classVal][sIndex][sIndex] + 1.0D / m_NumAttValues[son]) / (m_ClassCounts[classVal] + 1.0D); probs[classVal] *= prob; } attIndex[son] = sIndex; } } Utils.normalize(probs); return probs; } public String toString() { return "HNB (Hidden Naive Bayes)"; } public String getRevision() { return RevisionUtils.extract("$Revision: 5516 $"); } public static void main(String[] args) { runClassifier(new HNB(), args); } }
true
df1d3aea6626cab1f41702cce058aab9eb368089
Java
helloworld404/designPattern
/src/com/fighting/pattern/template/TemplateTest.java
UTF-8
331
2.671875
3
[]
no_license
package com.fighting.pattern.template; /** * @Description 模板模式测试 * @Author: LiuXing * @Date: 2020/5/28 21:32 */ public class TemplateTest { public static void main(String[] args) { Person ordinary = new Ordinary(); ordinary.daily(); Person owl = new OWL(); owl.daily(); } }
true
375338a1d83607b6303bdae8a2e841a746aba95d
Java
KipRashon/workspace-_eclipse
/General/src/readFile.java
UTF-8
742
2.9375
3
[]
no_license
import java.io.*; public class readFile{ public static void main(String args[]) throws Exception { File f= new File("C:\\Users\\Rashon\\Documents\\study\\material_science.txt"); //File f= new File("F:\\Kapkenda.docx"); FileReader st= new FileReader(f); BufferedReader br=new BufferedReader(st); String line; while((line=br.readLine())!=null) { animate(line); System.out.println(); Thread.sleep(1000); } } public static void animate(String line) { String splitted[]=line.split(" "); for(int i=0;i<splitted.length;i++) { System.out.print(splitted[i]+" "); try { Thread.sleep(400); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
true
991b8657b021f41861a1d97752e983444f197830
Java
zzoeliu/leetcode_java
/src/string/DecompressString.java
UTF-8
627
3.265625
3
[]
no_license
package string; import java.util.HashMap; import java.util.Map; /** * Created by ZoeLiu on 9/22/15. */ public class DecompressString { public String decompress(String input){ if (input == null || input.length() == 0){ return input; } StringBuilder result = new StringBuilder(); for (int i = 0; i < input.length() - 1; i+=2){ char tempChar = input.charAt(i); int occ = input.charAt(i+1) - '0'; while(occ > 0){ result.append(tempChar); occ--; } } return result.toString(); } }
true
b272710e1825fdd68070267170b304b25aaa5666
Java
linqinyun/JavaCode
/ObjectProj/src/com/imooc/school/Subject.java
UTF-8
2,145
3.359375
3
[]
no_license
package com.imooc.school; /** * 专业类 * @author ZHR * */ public class Subject { //成员属性:学科名称,学科编号,学制年限、报名选修的学生信息、报名选修的学生个数 private String subjectName; private String subjectNo; private int subjectLife; private Student[] myStudents; private int studentNum; //无参 public Subject() { } //带参--学科名称、编号、学制年限赋值 public Subject(String subjectName, String subjectNo, int subjectLife) { this.setSubjectName(subjectName); this.setSubjectNo(subjectNo); this.setSubjectLife(subjectLife); } public Subject(String subjectName, String subjectNo, int subjectLife, Student[] myStudents) { this.setSubjectName(subjectName); this.setSubjectNo(subjectNo); this.setSubjectLife(subjectLife); this.setMyStudents(myStudents); } public String getSubjectName() { return subjectName; } public void setSubjectName(String subjectName) { this.subjectName = subjectName; } public String getSubjectNo() { return subjectNo; } public void setSubjectNo(String subjectNo) { this.subjectNo = subjectNo; } public int getSubjectLife() { return subjectLife; } public void setSubjectLife(int subjectLife) { if(subjectLife<=0) { return; } this.subjectLife = subjectLife; } public Student[] getMyStudents() { if(this.myStudents == null) this.myStudents = new Student[200]; return myStudents; } public void setMyStudents(Student[] myStudents) { this.myStudents = myStudents; } public int getStudentNum() { return studentNum; } public void setStudentNum(int studentNum) { this.studentNum = studentNum; } /** * * @return */ public String info() { String str="专业信息如下::\n专业名称:"+this.getSubjectName()+"\n专业编号:"+this.getSubjectNo()+"\n学制年限:"+this.getSubjectLife(); return str; } public void addStudent(Student stu) { for(int i=0;i<this.getMyStudents().length;i++) { if(this.getMyStudents()[i]==null) { stu.setStudentSubject(this); this.getMyStudents()[i] = stu; this.setStudentNum(i+1); return; } } } }
true
5904d35c6766b25ede052abc22d0c3736bc6dbd1
Java
easimon/gasmeter
/src/main/java/org/homenet/easimon/gasmeter/domain/GasRecordQuantizer.java
UTF-8
2,241
2.84375
3
[]
no_license
package org.homenet.easimon.gasmeter.domain; import java.time.Instant; import java.time.ZoneId; import java.time.temporal.TemporalUnit; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Locale; import org.apache.commons.lang3.builder.ToStringBuilder; import org.homenet.easimon.util.ZonedDateTimeTruncator; public class GasRecordQuantizer { private static final class QuantizedGasRecord implements GasRecord { private final Instant start; private long amount; public QuantizedGasRecord(final Instant start) { this.start = start; this.amount = 0; } @Override public long getAmount() { return amount; } @Override public Instant getTimestamp() { return start; } @Override public GasRecordType getType() { return GasRecordType.QUANTIZED; } public void add(long amount) { this.amount += amount; } @Override public String toString() { return new ToStringBuilder(this) // .append("instant", start) // .append("amount", amount) // .toString(); } } private static final Comparator<GasRecord> BY_TIMESTAMP = (g1, g2) -> g1.getTimestamp() .compareTo(g2.getTimestamp()); public static List<GasRecord> quantize(final List<GasRecord> records, final TemporalUnit unit, final ZoneId timezone, final Locale locale) { if (records.isEmpty()) return Collections.emptyList(); final List<GasRecord> result = new ArrayList<>(); final List<GasRecord> sortedRecords = records;// .stream().sorted(BY_TIMESTAMP).collect(Collectors.toList()); Instant start = ZonedDateTimeTruncator .truncate( // records.get(0).getTimestamp().atZone(timezone), // unit, // locale) // .toInstant(); Instant next = start.atZone(timezone).plus(1, unit).toInstant(); QuantizedGasRecord quantized = new QuantizedGasRecord(start); for (GasRecord record : sortedRecords) { while (!next.isAfter(record.getTimestamp())) { result.add(quantized); start = next; next = start.atZone(timezone).plus(1, unit).toInstant(); quantized = new QuantizedGasRecord(start); } quantized.add(record.getAmount()); } result.add(quantized); return result; } }
true
5f05ef46696e19febd9bd61b61113b3417fef013
Java
bugminer/bugminer
/bugminer-server/src/main/java/de/unistuttgart/iste/rss/bugminer/computing/InvalidSshConfigException.java
UTF-8
488
1.945313
2
[ "MIT" ]
permissive
package de.unistuttgart.iste.rss.bugminer.computing; public class InvalidSshConfigException extends RuntimeException { private static final long serialVersionUID = 6795496222100026267L; public InvalidSshConfigException() { super(); } public InvalidSshConfigException(String message) { super(message); } public InvalidSshConfigException(Throwable cause) { super(cause); } public InvalidSshConfigException(String message, Throwable cause) { super(message, cause); } }
true
52cf782a4f000c8c9dc8c69739ee0071a6cfd5be
Java
mahfuzsust/vertx
/src/main/java/com/example/vertx/repository/impl/MongoRepository.java
UTF-8
477
2.1875
2
[]
no_license
package com.example.vertx.repository.impl; import com.example.vertx.util.MongoConnection; import com.example.vertx.util.MongoAdapterUtil; public class MongoRepository<T, I> { protected final MongoAdapterUtil<T, I> util; protected final String COLLECTION; public MongoRepository() { this(""); } public MongoRepository(String collection) { this.COLLECTION = collection; this.util = new MongoAdapterUtil<>(COLLECTION, MongoConnection.getClient()); } }
true
c993feb92ca90bf19c0d5c5614e1f923e978e535
Java
JasnaMRB/CodeEval
/moderate/ColumnNames.java
UTF-8
2,210
2.984375
3
[]
no_license
package moderate; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.HashMap; import java.util.Map; /* @author jasnamrb Challenge 197: https://www.codeeval.com/open_challenges/197/ Test cases: 52 -> AZ 3702 -> ELJ */ public class ColumnNames { public static void main(String[] args) throws IOException { long initialCount = 1; Map<Long, String> initial = new HashMap<>(); while (initialCount <= 26) { for (char alphabet = 'A'; alphabet <= 'Z'; alphabet++) { initial.put(initialCount, alphabet + ""); initialCount++; } } Map<Long, String> full = new HashMap<>(); full.putAll(initial); long count = 27; initialCount = 1; long nextCount = 1; long tensCount = 0; while (!full.containsValue("ZZZ")) { for (long i = 1; i <= 26; i++) { if (full.containsValue("ZZ")) { full.put(count, initial.get(nextCount) + initial.get(initialCount) + initial.get(i)); } else { full.put(count, initial.get(initialCount) + initial.get(i)); } count++; } initialCount++; if (full.containsValue("ZZ")) { if (initialCount == 27) { initialCount = 1; tensCount++; } if (tensCount == 2) { nextCount++; tensCount = 1; } } } File file = new File(args[0]); BufferedReader buffer = new BufferedReader(new FileReader(file)); String line; while ((line = buffer.readLine()) != null) { line = line.trim(); System.out.println(full.get(Long.parseLong(line))); } } }
true
61023edbdfbf3fb62236cd8ca126994231c58dbe
Java
210419-USF-BSN-Java/James-Martinez
/Project_0_James_Martinez/radioactive_reptiles_app/src/main/java/com/revature/models/Customer.java
UTF-8
1,456
2.890625
3
[]
no_license
package com.revature.models; public class Customer extends Person{ /** * */ private static final long serialVersionUID = 1L; private String location; private int custId; public Customer() { super(); } public Customer(String name, String email, String password, String location, int custId) { super(name, email, password); this.location = location; this.custId = custId; } public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } public int getCustid() { return custId; } public void setCustid(int custId) { this.custId = custId; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + custId; result = prime * result + ((location == null) ? 0 : location.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; Customer other = (Customer) obj; if (custId != other.custId) return false; if (location == null) { if (other.location != null) return false; } else if (!location.equals(other.location)) return false; return true; } @Override public String toString() { return String.format("%-8d", custId)+super.toString()+ String.format("%-25s", "Location: "+location); } }
true
92c124527d96119f1be82af54f04be5fd61488e8
Java
gufengwyx8/jfireframework
/jfire-litl/src/main/java/com/jfireframework/litl/function/FunctionRegister.java
UTF-8
1,350
2.671875
3
[]
no_license
package com.jfireframework.litl.function; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import com.jfireframework.baseutil.exception.JustThrowException; import com.jfireframework.baseutil.exception.UnSupportException; import com.jfireframework.litl.template.LineInfo; import com.jfireframework.litl.template.Template; public class FunctionRegister { private static Map<String, Class<? extends Function>> funcs = new ConcurrentHashMap<String, Class<? extends Function>>(); public static void register(String functionName, Class<? extends Function> type) { funcs.put(functionName, type); } public static Function get(String name, Object[] params, LineInfo info, Template template) { Class<? extends Function> constructor = funcs.get(name); if (constructor == null) { throw new UnSupportException("方法" + name + "不存在,请检查"); } else { try { Function function = constructor.newInstance(); function.init(params, info, template); return function; } catch (Exception e) { throw new JustThrowException(e); } } } }
true
6863efa35febc63bb5177a521134706982d8fa24
Java
vishal123rana/nestedJsonParse
/src/main/java/com/example/nestedJsonParse/DAO/CustomerDAO.java
UTF-8
300
1.726563
2
[]
no_license
package com.example.nestedJsonParse.DAO; import com.example.nestedJsonParse.Entity.Customer; import org.springframework.data.mongodb.repository.MongoRepository; import org.springframework.stereotype.Repository; @Repository public interface CustomerDAO extends MongoRepository<Customer,Integer> { }
true
d7346c8bfa0b098e866f2817546fa61218848343
Java
luckyflower666/webapps
/s2w/WEB-INF/classes/uk/ac/surrey/ee/ccsr/s2w/model/iota/restlet/RestReqApplication.java
UTF-8
4,429
1.96875
2
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package uk.ac.surrey.ee.ccsr.s2w.model.iota.restlet; import uk.ac.surrey.ee.ccsr.s2w.model.iota.restlet.resource.DeleteDescription; import uk.ac.surrey.ee.ccsr.s2w.model.iota.restlet.resource.RegisterDescription; import uk.ac.surrey.ee.ccsr.s2w.model.iota.restlet.resource.QueryDescription; import uk.ac.surrey.ee.ccsr.s2w.model.iota.restlet.resource.SanityCheck; import uk.ac.surrey.ee.ccsr.s2w.model.iota.restlet.resource.UpdateDescription; import uk.ac.surrey.ee.ccsr.s2w.model.iota.restlet.resource.DiscoverDescription; import uk.ac.surrey.ee.ccsr.s2w.model.iota.restlet.resource.LookupDescription; import org.restlet.Application; import org.restlet.Restlet; import org.restlet.routing.Router; import uk.ac.surrey.ee.ccsr.s2w.config.EntityConfigParams; import uk.ac.surrey.ee.ccsr.s2w.config.ResourceConfigParams; import uk.ac.surrey.ee.ccsr.s2w.config.ServiceConfigParams; import uk.ac.surrey.ee.ccsr.s2w.model.iota.restlet.resource.RegisterMultiple; public class RestReqApplication extends Application { /** * Creates a root Restlet that will receive all incoming calls. */ public static final String restletPath = "/repository"; public static final String registerPrefix = "/register"; public static final String lookupPrefix = "/lookup"; public static final String updatePrefix = "/update"; public static final String deletePrefix = "/delete"; public static final String queryPrefix = "/query/sparql"; public static final String discoverPrefix = "/discover"; @Override public synchronized Restlet createInboundRoot() { // Create a router Restlet that routes each call to a new instance of HelloWorldResource. Router router = new Router(getContext()); router.attach("/getVersion", SanityCheck.class); router.attach(registerPrefix+ResourceConfigParams.descTypeLinkSuffix, RegisterMultiple.class); router.attach(registerPrefix+EntityConfigParams.descTypeLinkSuffix, RegisterMultiple.class); router.attach(registerPrefix+ServiceConfigParams.descTypeLinkSuffix, RegisterMultiple.class); router.attach(registerPrefix+ResourceConfigParams.descTypeLinkSuffix+"/{objectID}", RegisterDescription.class); router.attach(registerPrefix+EntityConfigParams.descTypeLinkSuffix+"/{objectID}", RegisterDescription.class); router.attach(registerPrefix+ServiceConfigParams.descTypeLinkSuffix+"/{objectID}", RegisterDescription.class); router.attach(lookupPrefix+ResourceConfigParams.descTypeLinkSuffix+"/{objectID}", LookupDescription.class); router.attach(lookupPrefix+EntityConfigParams.descTypeLinkSuffix+"/{objectID}", LookupDescription.class); router.attach(lookupPrefix+ServiceConfigParams.descTypeLinkSuffix+"/{objectID}", LookupDescription.class); router.attach(updatePrefix+ResourceConfigParams.descTypeLinkSuffix+"/{objectID}", UpdateDescription.class); router.attach(updatePrefix+EntityConfigParams.descTypeLinkSuffix+"/{objectID}", UpdateDescription.class); router.attach(updatePrefix+ServiceConfigParams.descTypeLinkSuffix+"/{objectID}", UpdateDescription.class); router.attach(deletePrefix+ResourceConfigParams.descTypeLinkSuffix+"/{objectID}", DeleteDescription.class); router.attach(deletePrefix+EntityConfigParams.descTypeLinkSuffix+"/{objectID}", DeleteDescription.class); router.attach(deletePrefix+ServiceConfigParams.descTypeLinkSuffix+"/{objectID}", DeleteDescription.class); router.attach(queryPrefix+ResourceConfigParams.descTypeLinkSuffix, QueryDescription.class); router.attach(queryPrefix+EntityConfigParams.descTypeLinkSuffix, QueryDescription.class); router.attach(queryPrefix+ServiceConfigParams.descTypeLinkSuffix, QueryDescription.class); router.attach(discoverPrefix+ResourceConfigParams.descTypeLinkSuffix, DiscoverDescription.class); router.attach(discoverPrefix+EntityConfigParams.descTypeLinkSuffix, DiscoverDescription.class); router.attach(discoverPrefix+ServiceConfigParams.descTypeLinkSuffix, DiscoverDescription.class); router.attach(discoverPrefix+"/status", DiscoverDescription.class); return router; } }
true
b59a998b7d13a481b198fd7e5ee6a27d7d64cebd
Java
SomayNakhal/checkoutsystem
/src/main/java/com/checkoutsystem/offer/Offer.java
UTF-8
175
2.046875
2
[]
no_license
package com.checkoutsystem.offer; import java.util.List; public interface Offer { public List<OfferPrerequisite> getOfferPrerequisites(); public int getOfferAmount(); }
true
2c49f24042b2db93ea3fcf969584c74b0fe48adf
Java
chexov/vgweb
/src/main/java/com/vg/web/auth/IUser.java
UTF-8
76
1.65625
2
[]
no_license
package com.vg.web.auth; public interface IUser { Object toUIJson(); }
true
c91200bcbf6cb0ccca7818e68591cbfa153ad061
Java
sixshot626/h2o
/h2o-common/src/main/java/h2o/jenkov/container/impl/factory/FieldFactory.java
UTF-8
1,648
2.515625
3
[ "BSD-2-Clause" ]
permissive
package h2o.jenkov.container.impl.factory; import h2o.jenkov.container.itf.factory.FactoryException; import h2o.jenkov.container.itf.factory.ILocalFactory; import java.lang.reflect.Field; /** * @author Jakob Jenkov - Copyright 2005 Jenkov Development */ public class FieldFactory extends LocalFactoryBase implements ILocalFactory { protected Field field = null; protected Object fieldOwner = null; protected ILocalFactory fieldOwnerFactory = null; public FieldFactory(Field method) { this.field = method; } public FieldFactory(Field field, Object fieldOwner) { this.field = field; this.fieldOwner = fieldOwner; } public FieldFactory(Field field, ILocalFactory fieldOwnerFactory) { this.field = field; this.fieldOwnerFactory = fieldOwnerFactory; } public Class getReturnType() { return this.field.getType(); } public Object instance(Object[] parameters, Object[] localProducts) { try { if(this.fieldOwnerFactory != null){ return this.field.get(this.fieldOwnerFactory.instance(parameters, localProducts)); } return this.field.get(this.fieldOwner); } catch (IllegalAccessException e) { throw new FactoryException( "FieldFactory", "ERROR_ACCESSING_FIELD", "Error accessing field " + field, e); } } public String toString() { StringBuilder builder = new StringBuilder(); builder.append("field: "); builder.append(field); return builder.toString(); } }
true
14db9a33a312df89000efea1fcde3ea40f606483
Java
unreal0/java2dart
/com.google.dart.engine/src/com/google/dart/engine/internal/html/angular/NgDecoratorElementProcessor.java
UTF-8
3,679
1.65625
2
[]
no_license
/* * Copyright (c) 2014, the Dart project authors. * * Licensed under the Eclipse Public License v1.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.eclipse.org/legal/epl-v10.html * * 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.google.dart.engine.internal.html.angular; import com.google.dart.engine.element.angular.AngularDecoratorElement; import com.google.dart.engine.element.angular.AngularPropertyElement; import com.google.dart.engine.element.angular.AngularPropertyKind; import com.google.dart.engine.element.angular.AngularSelectorElement; import com.google.dart.engine.html.ast.XmlAttributeNode; import com.google.dart.engine.html.ast.XmlTagNode; import com.google.dart.engine.internal.element.angular.HasAttributeSelectorElementImpl; import com.google.dart.engine.type.Type; /** * {@link NgDecoratorElementProcessor} applies {@link AngularDecoratorElement} by parsing mapped * attributes as expressions. */ class NgDecoratorElementProcessor extends NgDirectiveProcessor { private final AngularDecoratorElement element; public NgDecoratorElementProcessor(AngularDecoratorElement element) { this.element = element; } @Override public void apply(AngularHtmlUnitResolver resolver, XmlTagNode node) { String selectorAttributeName = null; { AngularSelectorElement selector = element.getSelector(); if (selector instanceof HasAttributeSelectorElementImpl) { selectorAttributeName = ((HasAttributeSelectorElementImpl) selector).getName(); // resolve attribute expression XmlAttributeNode attribute = node.getAttribute(selectorAttributeName); if (attribute != null) { attribute.setElement(selector); } } } // for (AngularPropertyElement property : element.getProperties()) { // prepare attribute name String name = property.getName(); if (name.equals(".")) { name = selectorAttributeName; } // prepare attribute XmlAttributeNode attribute = node.getAttribute(name); if (attribute == null) { continue; } // if not resolved as the selector, resolve as a property if (!name.equals(selectorAttributeName)) { attribute.setElement(property); } // skip if attribute has no value if (!hasValue(attribute)) { continue; } // resolve if binding if (property.getPropertyKind() != AngularPropertyKind.ATTR) { resolver.pushNameScope(); try { onNgEventDirective(resolver); AngularExpression expression = parseAngularExpression(resolver, attribute); resolver.resolveExpression(expression); setAngularExpression(attribute, expression); } finally { resolver.popNameScope(); } } } } @Override public boolean canApply(XmlTagNode node) { return element.getSelector().apply(node); } /** * Support for <code>$event</code> variable in <code>NgEventDirective</code>. */ private void onNgEventDirective(AngularHtmlUnitResolver resolver) { if (element.isClass("NgEventDirective")) { Type dynamicType = resolver.getTypeProvider().getDynamicType(); resolver.defineVariable(resolver.createLocalVariableWithName(dynamicType, "$event")); } } }
true
609360fa82d0f8be6eb3de5a86c8f52af2e42c86
Java
Xiavic/XiavicParent
/XiavicLib/src/main/java/com/github/xiavic/lib/economy/api/Transaction.java
UTF-8
2,281
3.1875
3
[]
no_license
package com.github.xiavic.lib.economy.api; import java.util.Objects; import java.util.UUID; /** * Represents a transaction between two {@link CreditHolder}s. */ public class Transaction { public final UUID invoker; private final CreditHolder invokingCreditHolder, targetCreditHolder; private double sum; public Transaction(UUID invoker, CreditHolder invokingCreditHolder, CreditHolder targetCreditHolder) { this.invoker = Objects.requireNonNull(invoker); this.invokingCreditHolder = Objects.requireNonNull(invokingCreditHolder); this.targetCreditHolder = Objects.requireNonNull(targetCreditHolder); } public Transaction setSum(double sum) { this.sum = sum; return this; } public UUID getInvoker() { return invoker; } public CreditHolder getTargetCreditHolder() { return targetCreditHolder; } public CreditHolder getInvokingCreditHolder() { return invokingCreditHolder; } public double getSum() { return sum; } /** * Executes this transaction by the order of, * invoker first, receiver next. * * @return Returns whether the transaction was successfully processed. * @throws IllegalStateException Thrown if an account was frozen whilst a transaction was in progress. */ public boolean execute() throws IllegalStateException { if (!invokingCreditHolder.getBackingExecutor().handleTransaction(this)) { return false; } if (!targetCreditHolder.getBackingExecutor().handleTransaction(this)) { invokingCreditHolder.getBackingExecutor().callBack(this); return false; } return true; } /* * Execute and create an EconomyResponse. * * @return Returns an economy response representing the state of the transaction. /* public EconomyResponse executeVault() { boolean success = execute(); //Try to execute the transaction. return new EconomyResponse(sum, invokingCreditHolder.getCurrentBalance(), success ? EconomyResponse.ResponseType.SUCCESS : EconomyResponse.ResponseType.FAILURE, "&c&l (!) Transaction Failed."); //TODO Make config toggleable. } */ }
true
ecfa3508fdc70d98a45608db9a8a2b51ad2c4726
Java
lorenzobilli/LPO-project
/src/typechecker/TypeChecker.java
UTF-8
6,220
3.015625
3
[]
no_license
/* * LPO 2016/2017 - Final Project * Author: Lorenzo Billi (S3930391) * * File: typechecker.TypeChecker.java * */ package typechecker; import common.Environment; import common.Visitor; import common.ast.*; import static typechecker.PrimitiveType.BOOL; import static typechecker.PrimitiveType.INT; /** * TypeChecker class */ public class TypeChecker implements Visitor<Type> { private final Environment<Type> staticEnvironment = new Environment<>(); @Override public Type visitProgram(StatementSequence statementSequence) { statementSequence.accept(this); return null; } @Override public Type visitMoreStatement(Statement first, StatementSequence rest) { first.accept(this); rest.accept(this); return null; } @Override public Type visitSingleStatement(Statement statement) { statement.accept(this); return null; } @Override public Type visitMoreExpression(Expression first, ExpressionSequence rest) { Type expected = first.accept(this); return rest.accept(this).checkEqual(expected); } @Override public Type visitSingleExpression(Expression expression) { return expression.accept(this); } @Override public Type visitOr(Expression left, Expression right) { checkBinaryOperator(left, right, BOOL); return BOOL; } @Override public Type visitAnd(Expression left, Expression right) { checkBinaryOperator(left, right, BOOL); return BOOL; } @Override public Type visitEqual(Expression left, Expression right) { Type expected = left.accept(this); right.accept(this).checkEqual(expected); return BOOL; } @Override public Type visitLessThan(Expression left, Expression right) { checkBinaryOperator(left, right, INT); return BOOL; } @Override public Type visitConcatenate(Expression left, Expression right) { return right.accept(this).checkEqual(left.accept(this)); } @Override public Type visitAdd(Expression left, Expression right) { checkBinaryOperator(left, right, INT); return INT; } @Override public Type visitSubtract(Expression left, Expression right) { checkBinaryOperator(left, right, INT); return INT; } @Override public Type visitMultiply(Expression left, Expression right) { checkBinaryOperator(left, right, INT); return INT; } @Override public Type visitDivide(Expression left, Expression right) { checkBinaryOperator(left, right, INT); return INT; } @Override public Type visitIntegerLiteral(int value) { return INT; } @Override public Type visitBooleanLiteral(boolean value) { return BOOL; } @Override public Type visitIdentity(String name) { return staticEnvironment.lookup(new SimpleIdentity(name)); } @Override public Type visitNot(Expression expression) { return expression.accept(this).checkEqual(BOOL); } @Override public Type visitSign(Expression expression) { return expression.accept(this).checkEqual(INT); } @Override public Type visitTop(Expression expression) { return expression.accept(this).checkList(); } @Override public Type visitPop(Expression expression) { Type type = expression.accept(this); type.checkList(); return type; } @Override public Type visitPush(Expression left, Expression right) { Type type = left.accept(this); return right.accept(this).checkEqual(new ListType(type)); } @Override public Type visitLength(Expression expression) { Type type = expression.accept(this); type.checkList(); return INT; } @Override public Type visitPair(Expression left, Expression right) { return new CoupleType(left.accept(this), right.accept(this)); } @Override public Type visitFst(Expression expression) { return expression.accept(this).checkCouple(); } @Override public Type visitSnd(Expression expression) { return expression.accept(this).checkCouple(); } @Override public Type visitListLiteral(ExpressionSequence expressionSequence) { return new ListType(expressionSequence.accept(this)); } @Override public Type visitPrintStatement(Expression expression) { expression.accept(this); return null; } @Override public Type visitVarStatement(Identity identity, Expression expression) { staticEnvironment.newFresh(identity, expression.accept(this)); return null; } @Override public Type visitAssignStatement(Identity identity, Expression expression) { Type expected = staticEnvironment.lookup(identity); expression.accept(this).checkEqual(expected); return null; } @Override public Type visitForEachStatement(Identity identity, Expression expression, StatementSequence block) { Type type = expression.accept(this).checkList(); staticEnvironment.enterScope(); staticEnvironment.newFresh(identity, type); block.accept(this); staticEnvironment.exitScope(); return null; } @Override public Type visitIfStatement(Expression expression, StatementSequence ifBlock, StatementSequence elseBlock) { staticEnvironment.enterScope(); ifBlock.accept(this); staticEnvironment.exitScope(); staticEnvironment.enterScope(); elseBlock.accept(this); staticEnvironment.exitScope(); return null; } @Override public Type visitWhileStatement(Expression expression, StatementSequence block) { expression.accept(this).checkEqual(BOOL); staticEnvironment.enterScope(); block.accept(this); staticEnvironment.exitScope(); return null; } private void checkBinaryOperator(Expression left, Expression right, Type type) { left.accept(this).checkEqual(type); right.accept(this).checkEqual(type); } }
true
93419227585fa1a676b0c93bf930051566f3ff05
Java
tamyuti/TwitterRestAutomation
/TwitterAutomationFramework/src/util/RestUtil.java
UTF-8
2,639
2.40625
2
[]
no_license
package util; import java.io.IOException; import java.io.UnsupportedEncodingException; import org.apache.http.HttpHeaders; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.HttpClientBuilder; import oauth.signpost.OAuthConsumer; import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer; import oauth.signpost.exception.OAuthCommunicationException; import oauth.signpost.exception.OAuthExpectationFailedException; import oauth.signpost.exception.OAuthMessageSignerException; import pojo.MyPojo; import pojo.User; public class RestUtil { HttpClient client; HttpUriRequest request; HttpResponse response; String URI = Configuration.URI; String ConsumerKey=Configuration.CONSUMER_KEY; String ConsumerSecret=Configuration.CONSUMER_SECRET; String Token=Configuration.TOKEN; String TokenSecret=Configuration.TOKEN_SECRET; private MyPojo twitterUser; public MyPojo getTwitterUser() { return twitterUser; } public void setTwitterUser(MyPojo twitterUser) { this.twitterUser = twitterUser; } public void addAuthentication() throws OAuthMessageSignerException, OAuthExpectationFailedException, OAuthCommunicationException{ OAuthConsumer consumer=new CommonsHttpOAuthConsumer(ConsumerKey, ConsumerSecret); consumer.setTokenWithSecret(Token, TokenSecret); consumer.sign(request); } public void getRequest(String resourceUrn,String screenName,String count) throws OAuthMessageSignerException, OAuthExpectationFailedException, OAuthCommunicationException{ client = HttpClientBuilder.create().build(); request=new HttpGet(URI+resourceUrn+"screen_name=" +screenName +"&count=" +count); request.addHeader(HttpHeaders.CONTENT_TYPE,"application/json"); addAuthentication(); try { response=client.execute(request); if(response!=null){ setTwitterUser(ResourceUtil.retrieveResource(response, MyPojo.class)); } else{ System.out.println("Error" +response); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public String id(){ return twitterUser.getId(); } public int statusCode(){ return response.getStatusLine().getStatusCode(); } public String text(){ return twitterUser.getText(); } }
true
abb6a981a71680bcc1f452bc921efdaa27ec962f
Java
thombergs/code-examples
/spring-security/getting-started/SecureApplication/src/main/java/com/reflectoring/security/exception/UserForbiddenErrorHandler.java
UTF-8
991
2.25
2
[ "MIT" ]
permissive
package com.reflectoring.security.exception; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.web.access.AccessDeniedHandler; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class UserForbiddenErrorHandler implements AccessDeniedHandler { private final ObjectMapper objectMapper; public UserForbiddenErrorHandler() { this.objectMapper = new ObjectMapper(); } @Override public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException ex) throws IOException { response.setContentType("application/json"); response.setStatus(HttpServletResponse.SC_FORBIDDEN); response.getOutputStream().println(objectMapper.writeValueAsString(CommonException.forbidden())); } }
true
35d60fdb1ce9c02051e49c52b19eb2d58746c59f
Java
YouyuanDev/prweb
/src/main/java/com/prweb/controller/ServiceTypeController.java
UTF-8
2,492
1.90625
2
[]
no_license
package com.prweb.controller; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.prweb.dao.ServiceTypeDao; import com.prweb.entity.Role; import com.prweb.entity.ServiceType; import com.prweb.service.ServiceTypeService; import com.prweb.util.ResponseUtil; import org.omg.PortableInterceptor.INACTIVE; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.HashMap; import java.util.List; import java.util.Map; @Controller @RequestMapping("/ServiceType") public class ServiceTypeController { @Autowired private ServiceTypeService serviceTypeService; //得到所有的ServiceType @RequestMapping(value ="/getAllServiceType",produces = "text/plain;charset=utf-8") @ResponseBody public String getAllServiceType(HttpServletRequest request){ return serviceTypeService.getAllServiceType(); } //获取所有ServiceType列表 @RequestMapping("getServiceTypeByLike") @ResponseBody public String getServiceTypeByLike(@RequestParam(value = "service_type_name",required = false)String service_type_name, HttpServletRequest request){ String page= request.getParameter("page"); String rows= request.getParameter("rows"); if(page==null){ page="1"; } if(rows==null){ rows="20"; } int start=(Integer.parseInt(page)-1)*Integer.parseInt(rows); return serviceTypeService.getServiceTypeByLike(service_type_name,start, Integer.parseInt(rows)); } //保存ServiceType @RequestMapping(value ="/saveServiceType",produces = "text/plain;charset=utf-8") @ResponseBody public String saveServiceType(ServiceType serviceType, HttpServletResponse response){ System.out.print("saveServiceType"); return serviceTypeService.saveServiceType(serviceType); } //删除serviceType信息 @RequestMapping("/delServiceType") @ResponseBody public String delServiceType(@RequestParam(value = "hlparam")String hlparam,HttpServletResponse response)throws Exception{ return serviceTypeService.delServiceType(hlparam); } }
true
938dda579b4b969072dea1f56502aa3e42c95bf8
Java
losmochos/EyesInTheDarkness
/src/main/java/gigaherz/eyes/client/ClientEvents.java
UTF-8
1,074
1.882813
2
[ "BSD-3-Clause" ]
permissive
package gigaherz.eyes.client; import gigaherz.eyes.EyesInTheDarkness; import gigaherz.eyes.entity.EyesEntity; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.client.registry.RenderingRegistry; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent; @Mod.EventBusSubscriber(value= Dist.CLIENT, modid = EyesInTheDarkness.MODID, bus = Mod.EventBusSubscriber.Bus.MOD) public class ClientEvents { @SubscribeEvent public static void registerEntityRenders(final FMLClientSetupEvent event) { RenderingRegistry.registerEntityRenderingHandler(EyesEntity.class, EyesRenderer::new); } /* *-/ @SubscribeEvent public static void debug_inputEvent(InputEvent.KeyInputEvent event) { if (Keyboard.isKeyDown(Keyboard.KEY_P)) { Minecraft mc = Minecraft.getMinecraft(); JumpscareOverlay.INSTANCE.show(mc.player.posX,mc.player.posY,mc.player.posZ); } } /**/ }
true
55910cb197a88b6a68ee93486b65480a4546201d
Java
ITfan0322/food
/src/com/xbboom/utils/SmsUtil.java
UTF-8
762
1.625
2
[]
no_license
package com.xbboom.utils; import com.aliyuncs.CommonRequest; import com.aliyuncs.CommonResponse; import com.aliyuncs.DefaultAcsClient; import com.aliyuncs.IAcsClient; import com.aliyuncs.exceptions.ClientException; import com.aliyuncs.exceptions.ServerException; import com.aliyuncs.http.MethodType; import com.aliyuncs.profile.DefaultProfile; public class SmsUtil { /* pom.xml <dependency> <groupId>com.aliyun</groupId> <artifactId>aliyun-java-sdk-core</artifactId> <version>4.0.3</version> </dependency> */ public static void main(String[] args) { // try { // //SmsDemo.sendSms(); // } catch (ClientException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } } }
true
2c461b71d83c6b7a57a3b6f9de320625999c074c
Java
gilcu2/GridPageViewer2
/wear/src/main/java/com/gilcu2/gridpageviewer2/SimpleGridActivity.java
UTF-8
1,251
2.140625
2
[]
no_license
package com.gilcu2.gridpageviewer2; /** * Created by gilcu2 on 2/27/17. */ import android.app.Activity; import android.content.res.Resources; import android.os.Bundle; import android.support.wearable.view.DotsPageIndicator; import android.support.wearable.view.GridViewPager; import com.learnandroidwear.simplegridview.R; public class SimpleGridActivity extends Activity { private Resources res; private GridViewPager mPager; private int[] mImages = {R.drawable.ic_brightness_4_black_24dp, R.drawable.ic_brightness_5_black_24dp, R.drawable.ic_brightness_6_black_24dp, R.drawable.ic_filter_1_black_24dp, R.drawable.ic_filter_2_black_24dp }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); res = getResources(); mPager = (GridViewPager) findViewById(R.id.pager); //---Assigns an adapter to provide the content for this pager--- mPager.setAdapter(new MyGridAdapter(this, mImages)); DotsPageIndicator dotsPageIndicator = (DotsPageIndicator) findViewById(R.id.page_indicator); dotsPageIndicator.setPager(mPager); } }
true
39c2f03def5490a75e0f6c7d9a69db2bdcada268
Java
khomiakovkevin/tsuro
/Tsuro/4/CommandValidator.java
UTF-8
11,696
3.296875
3
[]
no_license
import java.util.function.Function; import java.util.function.Predicate; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonPrimitive; /** * A validator for potential commands. */ public class CommandValidator { /** * Determines whether the passed JsonElement represents a valid command. * @param commandElement The JsonElement to be queried. * @return True if the JsonElement represents a valid command. */ public static boolean validCommand(JsonElement commandElement) { try { JsonArray command = getAsJsonArray(commandElement); return validInitialPlacementCommand(command) || validIntermediatePlacementCommand(command) || validTurnSpecificationCommand(command); } catch (IllegalArgumentException ex) { System.out.println(ex.getMessage()); return false; } } /** * Converts a JsonElement into an integer. * @param element The JsonElement to be converted. * @return The integer that the passed JsonElement represents. * @throws IllegalArgumentException if the passed JsonElement cannot be * converted to an integer. */ private static int getAsInt(JsonElement element) throws IllegalArgumentException { return getAsPrimitiveType(element, JsonPrimitive::isNumber, JsonPrimitive::getAsInt, "n int"); } // TODO: Move above /** * Converts a JsonElement into a JsonArray. * @param element The JsonElement to be converted. * @return The converted JsonElement, now a JsonArray. * @throws IllegalArgumentException if element cannot be parsed as an array. */ public static JsonArray getAsJsonArray(JsonElement element) throws IllegalArgumentException { if (element.isJsonArray()) { return element.getAsJsonArray(); } else { throw new IllegalArgumentException("Cannot get the JsonElement " + element.toString() + " as a JsonArray."); } } /** * Converts a JsonElement into a String. * @param element The JsonElement to be converted. * @return The converted form of element into the String type. * @throws IllegalArgumentException if element cannot be parsed as a String. */ private static String getAsString(JsonElement element) throws IllegalArgumentException{ return getAsPrimitiveType(element, JsonPrimitive::isString, JsonPrimitive::getAsString, " String"); } /** * Converts a JsonElement into a given primitive Java type. * @param element The JsonElement to be converted. * @param typePredicate A function that determines whether a JsonPrimitive is * of the correct target type. * @param typeConverter A function that converts a JsonPrimitive to the * correct target type. * @param typeName A String representing the name of the target type, preceded * by a space and perhaps an n, in case the type begins with a * vowel. * @param <T> The target type. * @return The converted form of element into the target type. * @throws IllegalArgumentException if element cannot be parsed as a member of * the target type. */ private static <T> T getAsPrimitiveType(JsonElement element, Predicate<JsonPrimitive> typePredicate, Function<JsonPrimitive, T> typeConverter, String typeName) throws IllegalArgumentException { if (element.isJsonPrimitive()) { JsonPrimitive primitive = element.getAsJsonPrimitive(); if (typePredicate.test(primitive)) { return typeConverter.apply(primitive); } } throw new IllegalArgumentException("Cannot get the JsonElement " + element.toString() + " as a" + typeName + "."); } /** * Determines whether the passed JsonElement represents a value inside the * specified closed interval. * @param queryElement The JsonElement to be queried. * @param lowerBound The inclusive lower bound of the interval. * @param upperBound The inclusive upper bound of the interval. * @return True if queryElement represents a value inside the specified closed * interval. * @throws IllegalArgumentException if queryElement cannot be parsed as an * integer. */ private static boolean liesInClosedInterval(JsonElement queryElement, int lowerBound, int upperBound) throws IllegalArgumentException { int query = getAsInt(queryElement); return lowerBound <= query && query <= upperBound; } /** * Determines whether the passed JsonElement represents a valid position on * the Board. * @param boardPositionElement The JsonElement to be queried. * @return True if boardPositionElement represents a valid position on the * Board. * @throws IllegalArgumentException if boardPositionElement cannot be parsed * as an integer. */ private static boolean validBoardPosition(JsonElement boardPositionElement) throws IllegalArgumentException { return liesInClosedInterval(boardPositionElement, 0, 9); } /** * Determines whether the passed JsonElement represents a valid color String. * @param colorStringElement The JsonElement to be queried. * @return True if colorStringElement represents a valid color String. * @throws IllegalArgumentException if colorStringElement cannot be parsed as * a String. */ private static boolean validColorString(JsonElement colorStringElement) throws IllegalArgumentException { String colorString = getAsString(colorStringElement); switch (colorString) { case "white": case "black": case "red": case "green": case "blue": return true; default: return false; } } /** * Determines whether the passed JsonArray represents a valid initial * placement command. * @param command The JsonArray to be queried. * @return True if command does in fact represent a valid initial placement * command. * @throws IllegalArgumentException if one of the entries of the command is * malformed. */ private static boolean validInitialPlacementCommand(JsonArray command) throws IllegalArgumentException { if (command.size() == 6) { boolean validTileIndex = validTileIndex(command.get(0)); boolean validRotationAngle = validRotationAngle(command.get(1)); boolean validColorString = validColorString(command.get(2)); boolean validPortName = validPortName(command.get(3)); boolean validXPosition = validBoardPosition(command.get(4)); boolean validYPosition = validBoardPosition(command.get(5)); return validTileIndex && validRotationAngle && validColorString && validPortName && validXPosition && validYPosition; } else { return false; } } /** * Determines whether the passed JsonArray represents a valid intermediate * placement command. * @param command The JsonArray to be queried. * @return True if command does in fact represent a valid intermediate * placement command. * @throws IllegalArgumentException if one of the entries of the command is * malformed. */ private static boolean validIntermediatePlacementCommand(JsonArray command) throws IllegalArgumentException { if (command.size() == 5) { boolean validColorString = validColorString(command.get(0)); boolean validTileIndex = validTileIndex(command.get(1)); boolean validRotationAngle = validRotationAngle(command.get(2)); return validColorString && validTileIndex && validRotationAngle; } else { return false; } } /** * Determines whether the passed JsonElement represents a valid intermediate * placement command. * @param commandElement The JsonElement to be queried. * @return True if command does in fact represent a valid intermediate * placement command. * @throws IllegalArgumentException if either commandElement cannot be parsed * as a JsonArray, or if the resulting command itself is malformed. */ private static boolean validIntermediatePlacementCommand(JsonElement commandElement) throws IllegalArgumentException { JsonArray command = getAsJsonArray(commandElement); return validIntermediatePlacementCommand(command); } /** * Determines whether the passed JsonElement represents a valid Port name. * @param portNameElement The JsonElement to be queried. * @return True if portNameElement represents a valid Port name. * @throws IllegalArgumentException if portNameElement cannot be parsed as a * String. */ private static boolean validPortName(JsonElement portNameElement) throws IllegalArgumentException { String portName = getAsString(portNameElement); switch (portName) { case "A": case "B": case "C": case "D": case "E": case "F": case "G": case "H": return true; default: return false; } } /** * Determines whether the passed JsonElement represents a valid rotation angle * value (i.e. one of 0, 90, 180, 270). * @param rotationAngleElement The JsonElement to be queried. * @return True if rotationAngleElement represents a valid rotation angle. * @throws IllegalArgumentException if rotationAngleElement cannot be parsed * as an integer. */ private static boolean validRotationAngle(JsonElement rotationAngleElement) throws IllegalArgumentException { int rotationAngle = getAsInt(rotationAngleElement); return (rotationAngle == 0) || (rotationAngle == 90) || (rotationAngle == 180) || (rotationAngle == 270); } /** * Determines whether the passed JsonElement represents a valid Tile index. * @param tileIndexElement The JsonElement to be queried. * @return True if tileIndexElement represents a valid Tile index * (0 <= ii <= 34). * @throws IllegalArgumentException if tileIndexElement cannot be parsed as an * integer. */ private static boolean validTileIndex(JsonElement tileIndexElement) throws IllegalArgumentException { return liesInClosedInterval(tileIndexElement, -1, 34); } /** * Determines whether the passed JsonArray represents a valid turn * specification command. * @param command The JsonArray to be queried. * @return True if command represents a valid turn specification command. * @throws IllegalArgumentException if one of the entries of the command is * malformed. */ private static boolean validTurnSpecificationCommand(JsonArray command) throws IllegalArgumentException { if (command.size() == 3) { boolean validIntermediatePlacementCommand = validIntermediatePlacementCommand(command.get(0)); boolean validTileIndex1 = validTileIndex(command.get(1)); boolean validTileIndex2 = validTileIndex(command.get(2)); return validIntermediatePlacementCommand && validTileIndex1 && validTileIndex2; } else { return false; } } }
true
aa2b435c4bd0dc5f7c2770a1ef8de0091790f6d6
Java
Stargator/koskela_sourcecode
/src/test/java/com/tddinaction/time/logging/TestHttpRequestLogFormatter.java
UTF-8
2,234
2.5
2
[]
no_license
package com.tddinaction.time.logging; import static org.easymock.EasyMock.createMock; import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.replay; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.text.DateFormat; import javax.servlet.http.HttpServletRequest; import org.junit.After; import org.junit.Test; import com.tddinaction.time.abstraction.SystemTime; import com.tddinaction.time.abstraction.TimeSource; public class TestHttpRequestLogFormatter { @After public void resetSystemTime() { SystemTime.reset(); } @Test public void testCommonLogFormat() throws Exception { final long time = SystemTime.asMillis(); SystemTime.setTimeSource(new TimeSource() { public long millis() { return time; } }); DateFormat dateFormat = HttpRequestLogFormatter.dateFormat; String timestamp = dateFormat.format(SystemTime.asDate()); String expected = "1.2.3.4 - bob [" + timestamp + "] \"GET /ctx/path/resource HTTP/1.1\" 200 2326"; HttpServletRequest request = createMock(HttpServletRequest.class); expect(request.getRemoteAddr()).andReturn("1.2.3.4"); expect(request.getRemoteUser()).andReturn("bob"); expect(request.getMethod()).andReturn("GET"); expect(request.getRequestURI()).andReturn( "/ctx/path/resource"); expect(request.getProtocol()).andReturn("HTTP/1.1"); replay(request); HttpRequestLogFormatter formatter = new HttpRequestLogFormatter(); assertEquals(expected, formatter.format(request, 200, 2326)); } @Test public void testTimestampFormat() throws Exception { String date = "\\d{2}/\\w{3}/\\d{4}"; String time = "\\d{2}:\\d{2}:\\d{2}"; String timezone = "(-|\\+)\\d{4}"; String regex = date + ":" + time + " " + timezone; DateFormat dateFormat = HttpRequestLogFormatter.dateFormat; String timestamp = dateFormat.format(SystemTime.asDate()); assertTrue("DateFormat should be \"dd/mon/yyyy:HH:mm:ss Z\"", timestamp.matches(regex)); } }
true
8d3f02478604a8d1fac62426f92249b38c012593
Java
emmschuster/ObserverPattern_Newsletter
/src/Andrea.java
UTF-8
165
2.75
3
[]
no_license
public class Andrea implements Subscriber{ @Override public void benachrichtigung(Ausgabe a) { System.out.println("Andrea hat "+a.getTitel()+" erhalten"); } }
true
38761397e2ce8d4e4917832023808947449e1a29
Java
vandungitars/DemoJava_SpringBoot_Arsenal.com
/src/main/java/com/vandung/service/PractiseServiceImp.java
UTF-8
661
2.1875
2
[]
no_license
package com.vandung.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.vandung.model.Practise; import com.vandung.repository.PractiseRepository; @Service("PractiseService") @Transactional public class PractiseServiceImp implements PractiseService{ @Autowired private PractiseRepository practiseRepository; @Override public Practise findById(Long id_practise) { return practiseRepository.getOne(id_practise); } @Override public void save(Practise practise) { practiseRepository.save(practise); } }
true
52ae11b8fdd92b661667b4ee5f99946318d9e605
Java
satyapavan/spring
/SpringMaven-IBM-MUM/Demo_day1/src/exception/ExceptionMain1.java
UTF-8
475
3.296875
3
[]
no_license
package exception; public class ExceptionMain1 { public static void main(String[] args) { try{ int a=10; int b=10; double c= a/b; String[] data = new String[10]; //data[0]="Shantanu"; data[0].length(); System.out.println("No Exception..."); } catch (Exception e) { System.out.println("Excetion raised is "+e.getMessage()); } finally{ System.out.println("Finally executes..."); } System.out.println("Normal execution continues..."); } }
true
d6c55483efccecd6a3eb6979636faf97502bee9c
Java
dnjsrud3407/TeemProject
/TeamProject/src/member/account/action/FindPassProAction.java
UTF-8
1,268
2.296875
2
[]
no_license
package member.account.action; import java.util.HashMap; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import action.Action; import member.account.svc.FindPassProService; import vo.ActionForward; public class FindPassProAction implements Action { @Override public ActionForward execute(HttpServletRequest request, HttpServletResponse response) throws Exception { ActionForward forward = null; System.out.println("FindPassProAction"); String uID = request.getParameter("uID"); String phone_num = request.getParameter("Phone_num"); System.out.println(uID + ", " + phone_num ); HashMap hash = new HashMap(); hash.put("uID", uID); hash.put("phone_num",phone_num); FindPassProService findPassProService = new FindPassProService(); String findPass = findPassProService.findPass(hash); System.out.println(findPass); int passOk = 0; if(findPass != null) { passOk = 1; } else { passOk = -1; } request.setAttribute("findPass", findPass); request.setAttribute("uID", uID); request.setAttribute("passOk", passOk); forward = new ActionForward(); forward.setPath("/member/findPass.jsp"); return forward; } }
true
8701b7d66bed2e02171ec5aaa802d91a5f304a25
Java
RafaSaenz/CienciasBasicas
/src/java/business/Resource.java
UTF-8
4,708
2.328125
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 business; import java.util.Date; /** * * @author gerar */ public class Resource { private String id; private String title; private String description; private ResourceType type; private Subtopic subtopic; private Area area; private Topic topic; private String level; private String filePath; private String link; private Instructor instructor; private String references; private int review; private int status; private Date addedDate; public Resource(){ } public Resource(String id) { this.id = id; } /** * @return the id */ public String getId() { return id; } /** * @param id the id to set */ public void setId(String id) { this.id = id; } /** * @return the title */ public String getTitle() { return title; } /** * @param title the title to set */ public void setTitle(String title) { this.title = title; } /** * @return the description */ public String getDescription() { return description; } /** * @param description the description to set */ public void setDescription(String description) { this.description = description; } /** * @return the type */ public ResourceType getType() { return type; } /** * @param type the type to set */ public void setType(ResourceType type) { this.type = type; } /** * @return the subtopic */ public Subtopic getSubtopic() { return subtopic; } /** * @param subtopic the subtopic to set */ public void setSubtopic(Subtopic subtopic) { this.subtopic = subtopic; } /** * @return the level */ public String getLevel() { return level; } /** * @param level the level to set */ public void setLevel(String level) { this.level = level; } /** * @return the filePath */ public String getFilePath() { return filePath; } /** * @param filePath the filePath to set */ public void setFilePath(String filePath) { this.filePath = filePath; } /** * @return the link */ public String getLink() { return link; } /** * @param link the link to set */ public void setLink(String link) { this.link = link; } /** * @return the instructor */ public Instructor getInstructor() { return instructor; } /** * @param instructor the instructor to set */ public void setInstructor(Instructor instructor) { this.instructor = instructor; } /** * @return the references */ public String getReferences() { return references; } /** * @param references the references to set */ public void setReferences(String references) { this.references = references; } /** * @return the review */ public int getReview() { return review; } /** * @param review the review to set */ public void setReview(int review) { this.review = review; } /** * @return the addedDate */ public Date getAddedDate() { return addedDate; } /** * @param addedDate the addedDate to set */ public void setAddedDate(Date addedDate) { this.addedDate = addedDate; } /** * @return the area */ public Area getArea() { return area; } /** * @param area the area to set */ public void setArea(Area area) { this.area = area; } /** * @return the topic */ public Topic getTopic() { return topic; } /** * @param topic the topic to set */ public void setTopic(Topic topic) { this.topic = topic; } /** * @return the status */ public int getStatus() { return status; } /** * @param status the status to set */ public void setStatus(int status) { this.status = status; } }
true
547d3b83840fd0546a7eb066c2a38a6b30900764
Java
afugit/CommonLIbraries
/src/com/vonexus/Utility.java
UTF-8
3,441
2.78125
3
[]
no_license
/** * Miscellaneous utilities that are commonly used. Though shortcuts, these * methods should never be used in writing a formal class. Every class should * be independant of one another, so no relying on this. SHould only be * utilized in main(). * * @author Anthony M. Fugit * @version 0.1.20171019 */ package com.vonexus; import com.vonexus.objects.EmailObj; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import java.util.Properties; import java.util.Scanner; import java.util.logging.Level; import java.util.logging.Logger; public class Utility { /** * Start logger */ private static final Logger LOGGER = Logger.getLogger(Utility.class.getName()); /** * When not using a public constructor, create a private one: */ private Utility() { throw new IllegalStateException("Utility class"); } /** * Get user input on CLI * * @param prompt String to display to user * @return user response */ public static String getInput(String prompt) { Scanner reader = new Scanner(System.in); System.out.printf(prompt); return reader.next(); } public static void echo(String output) { System.out.print(output); } /** * Overloaded method to send mails with optional SMTP, CC, and BCC. * * @param to e-mail recipient * @param from e-mail sender * @param subject e-mail subject * @param body e-mail body * @param smtp SMTP server if available * @param cc carbon copy * @param bcc blind carbon copy */ /* think smtp server is required, localhost didn't work in testing public static void sendMail(String to, String from, String subject, String body) { sendMail(to, from, subject, body, "localhost"); } */ public static void sendMail(String to, String from, String subject, String body, String smtp) { sendMail(to, from, subject, body, smtp, null, null); } public static void sendMail(String to, String from, String subject, String body, String smtp, String cc, String bcc) { EmailObj eObj = new EmailObj(to, from, subject, body, smtp, cc, bcc); try { Properties properties = System.getProperties(); properties.setProperty("mail.smtp.host", eObj.getSmtp()); // get default session object Session session = Session.getDefaultInstance(properties); MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(eObj.getFrom())); message.addRecipient(Message.RecipientType.TO, new InternetAddress(eObj.getTo())); if (!eObj.getCc().isEmpty()) { message.addRecipients(Message.RecipientType.CC, String.valueOf(new InternetAddress(eObj.getCc()))); } if (!eObj.getBcc().isEmpty()) { message.addRecipients(Message.RecipientType.BCC, String.valueOf(new InternetAddress(eObj.getBcc()))); } message.setSubject(eObj.getSubject()); message.setText(eObj.getBody()); Transport.send(message); } catch (MessagingException e) { LOGGER.log(Level.WARNING, e.getLocalizedMessage()); } } }
true
b6b8117b19e23517d596435b75f8f7ee8d542b9e
Java
ashuaraut21/EventManagement
/app/src/main/java/com/example/eventmanagment/admin.java
UTF-8
1,829
2.03125
2
[]
no_license
package com.example.eventmanagment; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; public class admin extends AppCompatActivity { Button add_location,update_location,view_location,delete_location; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_admin); add_location=(Button)findViewById(R.id.add_Location); update_location=(Button)findViewById(R.id.update_location); view_location=(Button)findViewById(R.id.view_location); delete_location=(Button)findViewById(R.id.delete_location); add_location.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i1=new Intent(admin.this,add_location.class); startActivity(i1); } }); update_location.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i1=new Intent(admin.this,location_update_show.class); startActivity(i1); } }); view_location.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i1=new Intent(admin.this,location_view.class); startActivity(i1); } }); delete_location.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i1=new Intent(admin.this,location_delete_show.class); startActivity(i1); } }); } }
true
bae1a063cc6c17169889e84c83c6b691bb927ef1
Java
dhung6322/classwork
/DavidHung/src/caveExplorer/NPC.java
UTF-8
2,344
3.40625
3
[]
no_license
package caveExplorer; public class NPC { //fields needed to program navigation private CaveRoom[][] floor; //area where NPC roams private int currentRow; private int currentCol; private NPCRoom currentRoom; //these fields are about interaction with NPC private boolean active; private String activeDescription; private String inactiveDescription; //you might later add fields to make your NPC behave like a chatbot //default public NPC() { this.floor = CaveExplorer.caves; this.activeDescription = "There is a person standing in the room " + "waiting to talk to you. Press 'e' to talk."; this.inactiveDescription = "The person you spoke to earlier is " + "standing here."; //by default, NPC does not have a position, //to indicate this, use coordinates -1, -1 this.currentCol = -1; this.currentRow = -1; currentRoom = null; active = true; } public boolean isActive() { return active; } public void interact() { CaveExplorer.print("Let's interact! Type 'bye' to stop."); String s = CaveExplorer.in.nextLine(); while(!s.equalsIgnoreCase("bye")) { CaveExplorer.print("Yeah... I don't do a whole lot."); s = CaveExplorer.in.nextLine(); } CaveExplorer.print("Later, friend!"); active = false; } public String getDescription() { return activeDescription; } public String getInactiveDescription() { return inactiveDescription; } public String getSymbol() { // TODO Auto-generated method stub return "P"; } public void setPosition(int row, int col) { //check to avoid ArrayIndexOutOfBoundsException if(row >= 0 && row < floor.length && col >= 0 && col < floor[row].length && floor[row][col] instanceof NPCRoom) { if(currentRoom != null) { currentRoom.leaveNPC(); } currentRow = row; currentCol = col; //cast the CaveRoom to NPCRoom currentRoom = (NPCRoom)floor[row][col]; currentRoom.enterNPC(this); } } public void autoMove() { if(active) { int[] move = calculateMove(); int newRow = currentRow + move[0]; int newCol = currentCol + move[1]; setPosition(newRow, newCol); } } private int[] calculateMove() { int[][] possibleMoves = {{-1,0},{0,1},{1,0},{0,-1}}; int index = 0; return index; } }
true
9295b57760aa6bd355262e2a3cb5018279262947
Java
Bathula-Rakesh/Coffee_Shop_
/app/src/main/java/com/example/coffeeshop/CoffeeModel.java
UTF-8
1,020
3.015625
3
[]
no_license
package com.example.coffeeshop; import java.util.Iterator; public class CoffeeModel { int minus,plus,image; String cost,name; public CoffeeModel(int minus, int plus, int image, String cost, String name) { this.minus = minus; this.plus = plus; this.image = image; this.cost = cost; this.name = name; } public int getMinus() { return minus; } public void setMinus(int minus) { this.minus = minus; } public int getPlus() { return plus; } public void setPlus(int plus) { this.plus = plus; } public int getImage() { return image; } public void setImage(int image) { this.image = image; } public String getCost() { return cost; } public void setCost(String cost) { this.cost = cost; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
true
df8e9b69da278bc6f932f07c524db8c59a6480ba
Java
shivamjj65/Java-Programs
/P34_AccessModifiers.java
UTF-8
1,613
4.03125
4
[]
no_license
package com.programs; class C1{ public int x=5; protected int y=45; int z=6; private int a = 12; public void meth1(){ System.out.println("This is meth1() from class c1 which has values of x,y,z,a defined int it and all are accessible."); System.out.println("\nx is public and its value is: "+x); System.out.println("y is protected and its value is: "+y); System.out.println("z is default and its value is: "+z); System.out.println("a is private and its value is: "+a); } } class C2{ } public class P34_AccessModifiers { public static void main(String[] args) { System.out.println("Access modifiers determine whether other classes can use a particular field or invoke a particular method. Can be public, private, protected or default(no modifier)"); System.out.println("This table shows which modifier can be used where:"); System.out.println("Modifier\t\tClass\t\tPackage\t\tSubclass\t\tWorld"); System.out.println("--------------------------------------------------------------"); System.out.println("Public\t\t\tY\t\t\tY\t\t\tY\t\t\t\tY"); System.out.println("Protected\t\tY\t\t\tY\t\t\tY\t\t\t\tN"); System.out.println("Default\t\t\tY\t\t\tY\t\t\tN\t\t\t\tN"); System.out.println("Private\t\t\tY\t\t\tN\t\t\tN\t\t\t\tN"); C1 c1 = new C1(); c1.meth1(); System.out.println("showing public x = "+c1.x+", protected y = "+c1.y+" and default z = "+c1.z+", but a is private hence not accessible inside a package"); } }
true
9d37cfc0635131b202260593158a06549457d4b7
Java
theRichu/zc-pert
/src/com/autopertdiagram/action/ReadProjectActionBean.java
UTF-8
3,701
2.21875
2
[]
no_license
package com.autopertdiagram.action; import com.autopertdiagram.dao.ProjectDAO; import com.autopertdiagram.pojo.Project; import com.autopertdiagram.util.Utils; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import net.sourceforge.stripes.action.Resolution; import net.sourceforge.stripes.action.StreamingResolution; import net.sourceforge.stripes.action.UrlBinding; import java.io.StringReader; import java.text.DateFormat; import java.util.List; /** * User: ZisCloud Date: 2009-4-12 Time: 15:54:17 */ @UrlBinding("/project/readProject") public class ReadProjectActionBean extends DefaultActionBean { private Project project; public Project getProject() { return project; } public void setProject(Project project) { this.project = project; } public Resolution readAllProjects() { List<Project> projectList = new ProjectDAO().findAll(); StringBuilder sb = new StringBuilder("["); for (Project p : projectList) { sb.append("["); sb.append(p.getId()); sb.append(","); sb.append("'" + p.getName() + "'"); sb.append(","); sb.append(p.getPlanPeriod()); sb.append(","); sb.append("'" + DateFormat.getDateInstance().format(p.getPlanStartDate()) + "'"); sb.append(","); sb.append(p.getPlanCost()); sb.append(","); sb.append("'" + p.getContractor() + "'"); sb.append("],"); } sb.replace(sb.length() - 1, sb.length(), "]"); return new StreamingResolution("text", new StringReader(sb.toString())); } public Resolution readAllProject() { List<Project> projectList = new ProjectDAO().findAll(); JSONArray itemList = new JSONArray(); for (Project prjct : projectList) { JSONObject item = new JSONObject(); item.put("cls", "file"); item.put("id", prjct.getId()); item.put("leaf", true); item.put("iconCls", "new-process-icon"); item.put("children", null); item.put("text", prjct.getName()); itemList.add(item); } System.out.println(itemList); return new StreamingResolution("text", itemList.toString()); } public Resolution readProjectById() { Project prjct = new ProjectDAO().findById(project.getId()); if (null == prjct) { return new StreamingResolution("text", "error"); } else { JSONObject info = new JSONObject(); info.put("工程ID(只读)", prjct.getId()); info.put("项目名称", prjct.getName()); info.put("工序编号前缀(只读)", prjct.getPreSymbol()); info.put("计划工期", prjct.getPlanPeriod()); info.put("实际工期", null == prjct.getActualPeriod() ? "未知": prjct.getActualPeriod()); info.put("预算资金", prjct.getPlanCost()); info.put("实际资金", null == prjct.getActualCost() ? "未知": prjct.getActualCost()); info.put("计划开工时间", Utils.formatDate(prjct.getPlanStartDate())); info.put("实际开工时间", Utils.formatDate(prjct.getActualStartDate())); info.put("计划完工时间(只读)", Utils.formatDate(prjct.getPlanEndDate())); info.put("实际完工时间(只读)", Utils.formatDate(prjct.getActualEndDate())); info.put("施工单位", prjct.getContractor()); return new StreamingResolution("text", info.toString()); } } }
true
6e1831023df728853b46c7560a2b0d25b2926699
Java
hymer/security.s3h4
/src/com/epic/core/BaseEntity.java
UTF-8
633
2.046875
2
[]
no_license
package com.epic.core; import java.util.Date; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.MappedSuperclass; @MappedSuperclass public abstract class BaseEntity implements java.io.Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue private Long id; public Long getId() { return id; } public void setId(Long id) { this.id = id; } private Date createTime; public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } }
true
334678dc75a84e30dcc259dcac7e0df5a96e3fd9
Java
fugeritaetas/morozko-lib
/java14-morozko/org.morozko.java.mod.db/src/org/morozko/java/mod/db/connect/pool/ConnectionFactoryPool.java
UTF-8
5,505
2.203125
2
[ "Apache-2.0" ]
permissive
/***************************************************************** <copyright> Morozko Java Library Copyright (c) 2007 Morozko All rights reserved. This program and the accompanying materials are made available under the terms of the Apache License v2.0 which accompanies this distribution, and is available at http://www.apache.org/licenses/ (txt version : http://www.apache.org/licenses/LICENSE-2.0.txt html version : http://www.apache.org/licenses/LICENSE-2.0.html) This product includes software developed at The Apache Software Foundation (http://www.apache.org/). </copyright> *****************************************************************/ /* * @(#)ConnectionFactoryPool.java * * @project : org.morozko.java.mod.db * @package : org.morozko.java.mod.db.connect.pool * @creation : 21/nov/07 * @release : xxxx.xx.xx */ package org.morozko.java.mod.db.connect.pool; import java.sql.Connection; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import org.morozko.java.mod.db.connect.ConnectionFacadeWrapper; import org.morozko.java.mod.db.connect.ConnectionFactory; import org.morozko.java.mod.db.dao.DAOException; import org.morozko.java.mod.db.sql.wrapper.ConnectionWrapper; /** * <p>/p> * * @author Morozko * */ public class ConnectionFactoryPool extends ConnectionFacadeWrapper { public static final int DEFAULT_MAX_CONNECTIONS = 30; public static final int DEFAULT_IDLE_CONNECTIONS = 10; public static final int DEFAULT_MIN_CONNECTIONS = 5; public static ConnectionFactory newFactory( ConnectionFactory cf ) throws DAOException { return newFactory( cf, DEFAULT_MIN_CONNECTIONS, DEFAULT_MAX_CONNECTIONS, DEFAULT_IDLE_CONNECTIONS ); } public static ConnectionFactory newFactory( ConnectionFactory cf, int minConnection, int maxConnection, int idlConnection ) throws DAOException { return new ConnectionFactoryPool( cf, minConnection, maxConnection, idlConnection ); } /** * @param wrapperConnectionFactory * @throws DAOException */ private ConnectionFactoryPool(ConnectionFactory wrapperConnectionFactory, int minConnection, int maxConnection, int idlConnection ) throws DAOException { super(wrapperConnectionFactory); this.minConnection = minConnection; this.maxConnection = maxConnection; this.idlConnection = idlConnection; this.connList = new ArrayList(); this.lendList = new ArrayList(); this.released = false; for ( int k=0; k<this.minConnection; k++ ) { this.connList.add( this.getWrapperConnectionFactory().getConnection() ); } } private int maxConnection; private int minConnection; private int idlConnection; private ConnectionFactory wrapped; private List connList; private List lendList; private boolean released; private int totalOpenedConnections() { return this.connList.size()+this.lendList.size(); } private ConnectionWrapperPool getOne() { Connection conn = (Connection) this.connList.remove( 0 ); this.lendList.add( conn ); return new ConnectionWrapperPool( conn, this ); } /* (non-Javadoc) * @see org.morozko.java.mod.db.connect.ConnectionFactory#getConnection() */ public Connection getConnection() throws DAOException { Connection conn = null; if ( released ) { throw ( new DAOException ( "This pool has been released" ) ); } else { if ( !this.connList.isEmpty() ) { conn = getOne(); } else { if ( this.totalOpenedConnections()<this.maxConnection ) { this.connList.add( this.wrapped.getConnection() ); conn = this.getOne(); } else { throw ( new DAOException( "Maximum connections limit reached" ) ); } } } return conn; } /* (non-Javadoc) * @see org.morozko.java.mod.db.connect.ConnectionFactory#release() */ public void release() throws DAOException { this.wrapped.release(); this.released = true; this.maxConnection = 0; this.minConnection = 0; this.idlConnection = 0; List list = new ArrayList(); list.addAll( this.connList ); this.connList.clear(); this.connList = null; list.addAll( this.lendList ); this.lendList.clear(); this.lendList = null; for ( int k=0; k<list.size(); k++ ) { try { ((Connection)list.get(k)).close(); } catch (SQLException e) { e.printStackTrace(); } } } private void give( Connection conn ) throws SQLException { if ( this.lendList.remove( conn ) ) { this.connList.add( conn ); } else { throw ( new SQLException( "Connection is not part of this pool" ) ); } } /** * <p>ConnectionFactoryPool : Inner class for handling a connection of the connection pool</p> * * @author Morozko * */ class ConnectionWrapperPool extends ConnectionWrapper { private ConnectionFactoryPool factory; /** * @param wrappedConnection */ public ConnectionWrapperPool(Connection wrappedConnection, ConnectionFactoryPool factory) { super(wrappedConnection); this.factory = factory; } /* (non-Javadoc) * @see java.sql.Connection#close() */ public void close() throws SQLException { this.factory.give( this.getWrappedConnection() ); } } public int getMaxConnection() { return maxConnection; } public int getMinConnection() { return minConnection; } public int getIdlConnection() { return idlConnection; } }
true
93eff665b3c8a3be39a705da947aebedc9aab658
Java
satyamramani/Tame-Of-Thrones
/src/test/java/com/tameofthrones/create/CreateKingdomTest.java
UTF-8
2,054
2.671875
3
[]
no_license
package com.tameofthrones.create; import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import com.tameofthrones.dto.Kingdom; import org.junit.jupiter.api.Test; public class CreateKingdomTest { @Test public void getKingdomNameTest() throws IOException { // for kingdom names List<String> kingdomNames = new ArrayList<String>(); CreateKingdoms createKingdoms = new CreateKingdomsImp(); List<Kingdom> kingdoms = createKingdoms.getKingdoms(); for (Kingdom kingdom : kingdoms) { kingdomNames.add(kingdom.getKingdomName()); } Collections.sort(kingdomNames); //for expected list of kingdoms List<String> expectedKingdoms = new ArrayList<String>(); expectedKingdoms.add("SPACE"); expectedKingdoms.add("LAND"); expectedKingdoms.add("WATER"); expectedKingdoms.add("ICE"); expectedKingdoms.add("AIR"); expectedKingdoms.add("FIRE"); Collections.sort(expectedKingdoms); assertEquals(6, kingdoms.size()); assertEquals(expectedKingdoms,kingdomNames); } @Test public void getKingdomEmblemTest() throws IOException { // for kingdom emblem test List<String> kingdomEmblem = new ArrayList<String>(); CreateKingdoms createKingdoms = new CreateKingdomsImp(); List<Kingdom> kingdoms = createKingdoms.getKingdoms(); for (Kingdom kingdom : kingdoms) { kingdomEmblem.add(kingdom.getEmblem()); } Collections.sort(kingdomEmblem); //for expected list of kingdoms List<String> expectedKingdomEmblem = new ArrayList<String>(); expectedKingdomEmblem.add("GORILLA"); expectedKingdomEmblem.add("PANDA"); expectedKingdomEmblem.add("MAMMOTH"); expectedKingdomEmblem.add("OCTOPUS"); expectedKingdomEmblem.add("OWL"); expectedKingdomEmblem.add("DRAGON"); Collections.sort(expectedKingdomEmblem); assertEquals(6, kingdoms.size()); assertEquals(expectedKingdomEmblem,kingdomEmblem); } }
true
0311d87082f11e9f996a151766f992a1ffeb826c
Java
TECH-NOX/Cucumber_CRMPRO_TestSuite
/src/test/java/testRunner/LoginTestRunner.java
UTF-8
700
1.757813
2
[]
no_license
package testRunner; import org.junit.After; import org.junit.runner.RunWith; import cucumber.api.CucumberOptions; import cucumber.api.junit.Cucumber; import com.cucumber.listener.Reporter; @RunWith(Cucumber.class) @CucumberOptions( features = {"src/test/resources/feats/Login.feature"}, glue = {"stepDefs" }, dryRun = false, monochrome = true, plugin = {"pretty", "html:target/HtmlReport", "com.cucumber.listener.ExtentCucumberFormatter:target/cucumber-reports/LoginFeaturereport.html" }) public class LoginTestRunner { @After public void generateExtentReports() { Reporter.loadXMLConfig(System.getProperty("user.dir") + "/src/main/java/config/extentReports.xml"); } }
true
13de26b9f15cc6869d6807acaa78df372d652af1
Java
rmilbradt/P14_cenarios
/src/br/ufsm/csi/p14/model/Custos.java
UTF-8
2,857
2.328125
2
[]
no_license
package br.ufsm.csi.p14.model; import org.springframework.format.annotation.NumberFormat; import javax.persistence.*; /** * Created by politecnico on 03/07/2015. */ @Entity @Table public class Custos { @Id private Long id; @NumberFormat(pattern = "0.00") private Float pis; @NumberFormat(pattern = "0.00") private Float cofins; @NumberFormat(pattern = "#0.#") private Float icmsMenos500; @NumberFormat(pattern = "#0.#") private Float icmsMais500; @NumberFormat(pattern = "#0.0000") private Float custoKWhVerde; @NumberFormat(pattern = "#0.0000") private Float custoKWhAmarela; @NumberFormat(pattern = "#0.0000") private Float custoKWhVermelha; public Float getCustoKWh(BandeiraTarifaria bandeiraTarifaria) { if (bandeiraTarifaria == BandeiraTarifaria.VERDE) { return getCustoKWhVerde(); } else if (bandeiraTarifaria == BandeiraTarifaria.AMARELA) { return getCustoKWhAmarela(); } else { return getCustoKWhVermelha(); } } public Float getCustoKWhVerde() { return custoKWhVerde; } public void setCustoKWhVerde(Float custoKWhVerde) { this.custoKWhVerde = custoKWhVerde; } public Float getCustoKWhAmarela() { return custoKWhAmarela; } public void setCustoKWhAmarela(Float custoKWhAmarela) { this.custoKWhAmarela = custoKWhAmarela; } public Float getCustoKWhVermelha() { return custoKWhVermelha; } public void setCustoKWhVermelha(Float custoKWhVermelha) { this.custoKWhVermelha = custoKWhVermelha; } public enum BandeiraTarifaria { VERDE, AMARELA, VERMELHA } @Transient public Float getCustoKWhPrimeiros500(BandeiraTarifaria bandeiraTarifaria) { return (getCustoKWh(bandeiraTarifaria) / ((100-(getPis() + getCofins() + getIcmsMenos500())) / 100)); } @Transient public Float getCustoKWhAcima500(BandeiraTarifaria bandeiraTarifaria) { return (getCustoKWh(bandeiraTarifaria) / ((100-(getPis() + getCofins() + getIcmsMais500())) / 100)); } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Float getPis() { return pis; } public void setPis(Float pis) { this.pis = pis; } public Float getCofins() { return cofins; } public void setCofins(Float cofins) { this.cofins = cofins; } public Float getIcmsMenos500() { return icmsMenos500; } public void setIcmsMenos500(Float icmsMenos500) { this.icmsMenos500 = icmsMenos500; } public Float getIcmsMais500() { return icmsMais500; } public void setIcmsMais500(Float icmsMais500) { this.icmsMais500 = icmsMais500; } }
true
743a600a5b5c3fd9eb81f9836df582d05d1fae7e
Java
ScaleUnlimited/cascading.cuke
/src/main/java/com/scaleunlimited/cascading/cuke/WorkFlowStepDefinitions.java
UTF-8
15,762
2.078125
2
[ "Apache-2.0" ]
permissive
package com.scaleunlimited.cascading.cuke; import java.io.File; import java.io.IOException; import java.util.List; import java.util.Map; import java.util.Random; import org.apache.commons.io.FileUtils; import org.apache.hadoop.fs.PathNotFoundException; import cascading.flow.Flow; import cascading.flow.hadoop.HadoopFlowProcess; import cascading.flow.planner.PlannerException; import cascading.tap.SinkMode; import cascading.tap.Tap; import cascading.tap.hadoop.Hfs; import cascading.tuple.Tuple; import cascading.tuple.TupleEntry; import cascading.tuple.TupleEntryCollector; import cascading.tuple.TupleEntryIterator; import com.scaleunlimited.cascading.FlowResult; import com.scaleunlimited.cascading.FlowRunner; import cucumber.api.DataTable; import cucumber.api.java.en.Given; import cucumber.api.java.en.Then; import cucumber.api.java.en.When; @SuppressWarnings("unchecked") public class WorkFlowStepDefinitions { @Given("^the (.+) package contains the (.+) (?:workflow|tool)$") public void the_package_contains_the_workflow(String packageName, String workflowName) throws Throwable { Class<?> clazz = Class.forName(packageName + "." + workflowName); WorkflowContext.registerWorkflow(workflowName, clazz); } @Given("^the (?:workflow|tool) will be run (locally| on a cluster) with test directory \"(.+)\"$") public void the_workflow_will_be_run_xxx_with_test_directory_yyy(String platformName, String testDir) throws Throwable { String workflowName = WorkflowContext.getCurrentWorkflowName(); WorkflowContext.getContext(workflowName).setDefaultPlatform(WorkflowUtils.getPlatform(workflowName, platformName)); WorkflowContext.getCurrentContext().setTestDir(testDir); // TODO figure out if we need to support a deferred deletion of the directory, so that callers can // tell us that we shouldn't clear out the test directory. the_workflow_test_directory_is_empty(); } @SuppressWarnings("rawtypes") @Given("^the (?:workflow|tool) test directory is empty") public void the_workflow_test_directory_is_empty() throws Throwable { WorkflowPlatform platform = WorkflowContext.getCurrentPlatform(); if (platform == WorkflowPlatform.DISTRIBUTED) { Tap tap = new Hfs(new cascading.scheme.hadoop.TextLine(), WorkflowContext.getCurrentContext().getTestDir(), SinkMode.REPLACE); tap.deleteResource(new HadoopFlowProcess()); } else if (platform == WorkflowPlatform.LOCAL) { // We can't use a FileTap to get rid of this directory, as that only tries to delete a file if you call tap.deleteResource File f = new File(WorkflowContext.getCurrentContext().getTestDir()); if (f.isDirectory()) { FileUtils.deleteDirectory(f); } else { f.delete(); } } else { throw new RuntimeException("Unknown Workflow platform " + platform); } } @Given("^these parameters for the (?:workflow|tool):$") public void these_parameters_for_the_workflow(List<List<String>> parameters) throws Throwable { WorkflowContext context = WorkflowContext.getCurrentContext(); // We get one entry (list) for each row, with the first element being the // parameter name, and the second element being the parameter value. // We want to support expansion of ${testdir} for paths. for (List<String> parameter : parameters) { if (parameter.size() == 2) { context.addParameter(parameter.get(0), WorkflowUtils.expandMacros(context, parameter.get(1))); } else { throw new IllegalArgumentException("Workflow parameters must be two column format (| name | value |)"); } } } @Given("^the (?:workflow|tool) parameter \"(.+?)\" is \"(.+)\"$") public void the_workflow_parameter_xxx_is_yyy(String paramName, String paramValue) throws Throwable { WorkflowContext context = WorkflowContext.getCurrentContext(); context.addParameter(paramName, WorkflowUtils.expandMacros(context, paramValue)); } @SuppressWarnings("rawtypes") @When("^the workflow run is attempted$") public void the_workflow_run_is_attempted() throws Throwable { WorkflowContext context = WorkflowContext.getCurrentContext(); try { WorkflowInterface workflow = context.getWorkflow(); Flow flow = workflow.createFlow(context); FlowResult result = FlowRunner.run(flow); context.addResult(result.getCounters()); } catch (PlannerException e) { throw new AssertionError(String.format("Workflow run step failed: the plan for workflow %s is invalid: %s", context.getWorkflowName(), e.getMessage())); } catch (ClassNotFoundException e) { throw new AssertionError(String.format("Workflow run step failed: the workflow class %s doesn't exist", context.getWorkflowName())); } catch (Exception e) { context.addFailure(e); } } @SuppressWarnings("rawtypes") @When("^the workflow is run$") public void the_workflow_is_run() throws Throwable { WorkflowContext context = WorkflowContext.getCurrentContext(); WorkflowInterface workflow = context.getWorkflow(); Flow flow = workflow.createFlow(context); FlowResult result = FlowRunner.run(flow); context.addResult(result.getCounters()); } @SuppressWarnings("rawtypes") @When("^the workflow is run with these additional parameters:$") public void the_workflow_is_run_with_these_additional_parameters(List<List<String>> parameters) throws Throwable { WorkflowContext context = WorkflowContext.getCurrentContext(); WorkflowParams before = addParameters(context, parameters); WorkflowInterface workflow = context.getWorkflow(); Flow flow = workflow.createFlow(context); FlowResult result = FlowRunner.run(flow); context.addResult(result.getCounters()); context.resetParameters(before); } @When("^the tool is run$") public void the_tool_is_run() throws Throwable { WorkflowContext context = WorkflowContext.getCurrentContext(); WorkflowInterface workflow = context.getWorkflow(); Map<String, Long> result = workflow.runTool(context); context.addResult(result); } @When("^the tool is run with these additional parameters:$") public void the_tool_is_run_with_these_additional_parameters(List<List<String>> parameters) throws Throwable { WorkflowContext context = WorkflowContext.getCurrentContext(); WorkflowParams before = addParameters(context, parameters); // Now run the tool WorkflowInterface workflow = context.getWorkflow(); Map<String, Long> result = workflow.runTool(context); context.addResult(result); context.resetParameters(before); } @When("^the tool run is attempted$") public void the_tool_run_is_attempted() throws Throwable { WorkflowContext context = WorkflowContext.getCurrentContext(); WorkflowInterface workflow = context.getWorkflow(); try { Map<String, Long> result = workflow.runTool(context); context.addResult(result); } catch (Exception e) { context.addFailure(e); } } private WorkflowParams addParameters(WorkflowContext context, List<List<String>> parameters) throws IOException { WorkflowParams before = context.getParams(); // We get one entry (list) for each row, with the first element being the // parameter name, and the second element being the parameter value. // We want to support expansion of ${testdir} for paths. for (List<String> parameter : parameters) { if (parameter.size() == 2) { context.addParameter(parameter.get(0), WorkflowUtils.expandMacros(context, parameter.get(1))); } else { throw new IllegalArgumentException("Workflow parameters must be two column format (| name | value |)"); } } return before; } @Then("^the (?:workflow|tool) should fail$") public void the_workflow_should_fail() throws Throwable { WorkflowContext context = WorkflowContext.getCurrentContext(); if (context.getFailure() == null) { throw new AssertionError(String.format("The workflow %s ran without an error", WorkflowContext.getCurrentWorkflowName())); } } @Given("^these text records in the (?:workflow|tool) \"(.*?)\" directory:$") public void these_text_records_in_the_workflow_xxx_directory(String directoryName, List<String> textLines) throws Throwable { WorkflowContext context = WorkflowContext.getCurrentContext(); TupleEntryCollector writer = context.getWorkflow().openTextForWrite(context, directoryName); try { for (String line : textLines) { writer.add(new Tuple(line)); } } finally { writer.close(); } } @Given("^these \"(.+?)\" records in the (?:workflow|tool) \"(.*?)\" directory:$") public void these_xxx_records_in_the_workflow_yyy_directory(String recordName, String directoryName, List<Map<String, String>> sourceValues) throws Throwable { WorkflowContext context = WorkflowContext.getCurrentContext(); WorkflowInterface workflow = context.getWorkflow(); TupleEntryCollector writer = workflow.openBinaryForWrite(context, directoryName, recordName); // We need to create records that we write out. for (Map<String, String> tupleValues : sourceValues) { writer.add(workflow.createTuple(context, recordName, new TupleValues(tupleValues))); } writer.close(); } @Given("^(\\d+) \"(.*?)\" records in the (?:workflow|tool) \"(.*?)\" directory:$") public void xxx_records_in_the_workflow_xxx_directory(int numRecords, String recordName, String directoryName, List<Map<String, String>> sourceValues) throws Throwable { WorkflowContext context = WorkflowContext.getCurrentContext(); WorkflowInterface workflow = context.getWorkflow(); TupleEntryCollector writer = workflow.openBinaryForWrite(context, directoryName, recordName); // TODO set the caller set the random seed Random rand = new Random(1L); for (int i = 0; i < numRecords; i++) { // Pick a random value to use. // We have to clone, so that the createTuple() method can remove values to check for unsupported // TODO make this more efficient? Do single check once to see if fields match up Map<String, String> tupleValues = sourceValues.get(rand.nextInt(sourceValues.size())); writer.add(workflow.createTuple(context, recordName, new TupleValues(tupleValues))); } writer.close(); } @Then("^the (?:workflow|tool) \"(.*?)\" (?:result|results|output|file|directory) should have a record where:$") public void the_workflow__xxx_results_should_have_a_record_where(String directoryName, DataTable targetValues) throws Throwable { WorkflowContext context = WorkflowContext.getCurrentContext(); WorkflowInterface workflow = context.getWorkflow(); TupleEntryIterator iter = WorkflowUtils.openForRead(context, workflow, directoryName); while (iter.hasNext()) { TupleEntry te = iter.next(); if (WorkflowUtils.tupleMatchesTarget(workflow, te, targetValues.asMap(String.class, String.class))) { return; } } throw new AssertionError(String.format("No record found for workflow %s in results \"%s\" that matched the target value", WorkflowContext.getCurrentWorkflowName(), directoryName)); } @Then("^the (?:workflow|tool) \"(.*?)\" (?:result|results|output|file|directory) should have no records$") public void the_workflow__xxx_results_should_have_no_records(String directoryName) throws Throwable { WorkflowContext context = WorkflowContext.getCurrentContext(); WorkflowInterface workflow = context.getWorkflow(); TupleEntryIterator iter = null; try { iter = WorkflowUtils.openForRead(context, workflow, directoryName); } catch (PathNotFoundException e) { // no records can mean the dir doesn't exist, or it does but contains no records // openBinaryForRead throws PathNotFoundException when the dir exists, // so we catch it here and don't complain since it's alright. } int records = 0; if (iter != null) { while (iter.hasNext()) { iter.next(); records++; } } if (records > 0) throw new AssertionError(String.format(records + " record(s) found for workflow %s in results \"%s\". Expected none.", WorkflowContext.getCurrentWorkflowName(), directoryName)); } @Then("^the (?:workflow|tool) \"(.*?)\" (?:result|results|output|file) should have records where:$") public void the_workflow_results_should_have_records_where(String directoryName, DataTable targetValues) throws Throwable { WorkflowUtils.matchResults(directoryName, targetValues, true); } @Then("^the (?:workflow|tool) \"(.*?)\" (?:result|results|output|file) should only have records where:$") public void the_workflow_result_should_only_have_records_where(String directoryName, DataTable targetValues) throws Throwable { WorkflowUtils.matchResults(directoryName, targetValues, false); } @Then("^the (?:workflow|tool) \"(.*?)\" (?:result|results|output|file) should not have records where:$") public void the_workflow_xxx_result_should_not_have_records_where(String directoryName, DataTable excludedValues) throws Throwable { WorkflowUtils.dontMatchResults(directoryName, excludedValues); } @Then("^the (?:workflow|tool) \"(.*?)\" (?:counter|counter value) should be (\\d+)$") public void the_workflow_counter_should_be(String counterName, long value) throws Throwable { WorkflowUtils.checkCounter(counterName, value, value); } @Then("^the (?:workflow|tool) \"(.*?)\" (?:counter|counter value) should be (?:more than|greater than|>) (\\d+)$") public void the_workflow_counter_should_be_more_than(String counterName, long value) throws Throwable { WorkflowUtils.checkCounter(counterName, value + 1, Long.MAX_VALUE); } @Then("^the (?:workflow|tool) \"(.*?)\" (?:counter|counter value) should be (?:at least|>=) (\\d+)$") public void the_workflow_counter_should_be_at_least(String counterName, long value) throws Throwable { WorkflowUtils.checkCounter(counterName, value, Long.MAX_VALUE); } @Then("^the (?:workflow|tool) \"(.*?)\" (?:counter|counter value) should be (?:less than|<) (\\d+)$") public void the_workflow_counter_should_be_less_than(String counterName, long value) throws Throwable { WorkflowUtils.checkCounter(counterName, Long.MIN_VALUE, value + 1); } @Then("^the (?:workflow|tool) \"(.*?)\" (?:counter|counter value) should be (?:at most|<=) (\\d+)$") public void the_workflow_counter_should_be_at_most(String counterName, long value) throws Throwable { WorkflowUtils.checkCounter(counterName, Long.MIN_VALUE, value); } @Then("^the (?:workflow|tool) result should have counters where:$") public void the_workflow_result_should_have_counters_where(List<List<String>> targetValues) throws Throwable { for (List<String> counterAndValue : targetValues) { long targetCount = Long.parseLong(counterAndValue.get(1)); WorkflowUtils.checkCounter(counterAndValue.get(0), targetCount, targetCount); } } }
true
72e07d4eab4e47eed40ea8bc507d3f149d276ba5
Java
mahmoudbakar/GoDuettoCompanion
/app/src/main/java/com/undecode/goduettocompanion/models/LanguageModel.java
UTF-8
722
2.390625
2
[]
no_license
package com.undecode.goduettocompanion.models; import javax.annotation.Generated; import com.google.gson.annotations.SerializedName; @Generated("com.robohorse.robopojogenerator") public class LanguageModel{ @SerializedName("LanguageName") private String languageName; @SerializedName("ID") private String iD; public void setLanguageName(String languageName){ this.languageName = languageName; } public String getLanguageName(){ return languageName; } public void setID(String iD){ this.iD = iD; } public String getID(){ return iD; } @Override public String toString(){ return "LanguageModel{" + "languageName = '" + languageName + '\'' + ",iD = '" + iD + '\'' + "}"; } }
true
93a9e850501e6eff31a8bb71f9bbdacfd54e970c
Java
teja5652/SpringController
/src/com/package1/Implementation.java
UTF-8
976
2.390625
2
[]
no_license
package com.package1; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import com.package1.service.EmployeeService; public class Implementation { public static void main(String[] args) { AnnotationConfigApplicationContext apc = new AnnotationConfigApplicationContext(ConfigurationClass.class); Employee e = (Employee)apc.getBean(Employee.class); System.out.println(e.getEid()); // System.out.println(e.getAddress().getHouseNO()); Address a = (Address)apc.getBean(Address.class); System.out.println(a.getHouseNO()); EmployeeService s = (EmployeeService)apc.getBean(EmployeeService.class); System.out.println(s.getEmployee(100).getEname()); /* * EmployeeService ese = (EmployeeService)apc.getBean("service"); Employee e1 = * ese.getEmployee(100); System.out.println(e1.getEname()); * System.out.println(e1.getEpay()); */ } }
true
0f898600d579753f7812c07eb08418f1cb0f024b
Java
YoonSung/SpringGradlePractice
/domain/src/main/java/architree/yoon/util/Constant.java
UTF-8
834
1.882813
2
[]
no_license
package architree.yoon.util; /** * Created by yoon on 15. 3. 25.. */ public class Constant { public static final String PROPERTY_KEY_DB_DRIVERCLASSNAME = "database.driverClassName"; public static final String PROPERTY_KEY_DB_URL = "database.url"; public static final String PROPERTY_KEY_DB_USERNAME = "database.username"; public static final String PROPERTY_KEY_DB_PASSWORD = "database.password"; public static final String PROPERTY_KEY_JPA_DIALECT = "hibernate.dialect"; public static final String PROPERTY_KEY_DB_FORMATSQL = "hibernate.format_sql"; public static final String PROPERTY_KEY_DB_NAMING_STRATEGY = "hibernate.ejb.naming_strategy"; public static final String PROPERTY_KEY_DB_SHOWSQL = "hibernate.show_sql"; public static final String PROPERTY_KEY_DB_JPATODDL = "hibernate.hbm2ddl.auto"; }
true
326fd000b7410398e2421ff9a084c6e9503e9d59
Java
GusDel92/myUber3
/MyUber3/src/myUberCar/BerlineCar.java
UTF-8
540
2.5625
3
[]
no_license
package myUberCar; import myUberDriver.Driver; import myUberRide.Request; public class BerlineCar extends Car { private static int berlineID = 0; public BerlineCar(String type, Driver owner) { super(type, owner); berlineID++; this.setCarID("berline"+berlineID); setTotalSeats(4); this.possibleTypesOfRide.add("uberX"); this.possibleTypesOfRide.add("uberBlack"); this.possibleTypesOfRide.add("uberPool"); } @Override public void accept(Request visitor) { visitor.visit(this); } }
true
582057610e8beaeb2ced54f98a5c591910616b44
Java
lichao20000/WEB
/src/main/java/com/linkage/liposs/buss/util/CorbaUtil.java
UTF-8
5,760
2.328125
2
[]
no_license
package com.linkage.liposs.buss.util; import java.util.List; import java.util.Map; import java.util.Properties; import javax.sql.DataSource; import org.omg.CosNaming.NameComponent; import org.omg.CosNaming.NamingContext; import org.omg.CosNaming.NamingContextHelper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.jdbc.core.JdbcTemplate; import com.linkage.commons.db.PrepareSQL; /** * 该类主要提供corba的总线访问功能 * * @author 王志猛(5194) tel:13701409234 * @version 1.0 * @since 2007-09-17 * @category Corba * * @version 2.0 增加对单进程和多进程的支持 modify by 陈仲民(5243) */ public class CorbaUtil { private JdbcTemplate jt;// spring的jdbc模版 private static Logger log = LoggerFactory.getLogger(CorbaUtil.class); private NamingContext namingContext = null; private int default_port = 20000;// 大客户默认corba接口 /** * orb初始化类,该对象全局保证只有一个。否则会将系统的socket连接占满 * * @return true: */ private boolean selfInit() { Properties props = new Properties(); props.put("org.omg.CORBA.ORBInitialPort", default_port); String[] args = null; org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init(args, props); PrepareSQL psql = new PrepareSQL("select ior from tab_ior where object_name='NameService' and object_poa='/rootPoa' and object_port=0"); List<Map> res = jt.queryForList(psql.getSQL()); if (res.size() == 0) { log.error("获取corba总线出错,从数据库中查取ior总数为零"); return false; } String names = res.get(0).get("ior").toString().trim(); org.omg.CORBA.Object objRef = orb.string_to_object(names); namingContext = NamingContextHelper.narrow(objRef); return true; } /** * 根据采集点和程序的名称获取对应的对象引用(单进程使用) * * @param gather_id * 采集点 * @param ProcessName * 进程的名称 * @return corba中的引用对象 * @throws Exception * 数据库和corba异常 */ public org.omg.CORBA.Object getProcessObject(String gather_id, String ProcessName) throws Exception { return getProcessObject(gather_id, ProcessName, 0); } /** * 根据采集点和程序的名称获取对应的对象引用(支持多进程,单进程情况下processNum为0) * * @param gather_id * 采集点 * @param ProcessName * 进程的名称 * @param processNum * 进程编号 * @return corba中的引用对象 * * @author 陈仲民(5243) * @throws Exception */ public org.omg.CORBA.Object getProcessObject(String gather_id, String ProcessName, int processIndex) throws Exception { // namingContext为空时初始化 if (namingContext == null) { selfInit(); } // 查询对应接口的配置信息 String poa_name = getPoaName(gather_id, ProcessName, processIndex); String object_name = getObjName(gather_id, ProcessName, processIndex); // 表中没有配置信息则直接返回空 if (poa_name == null || object_name == null) { return null; } NameComponent path[] = { new NameComponent(poa_name, "PoaName"), new NameComponent(object_name, "ObjectName") }; org.omg.CORBA.Object envObj = namingContext.resolve(path); return envObj; } /** * 根据指定的poa_name和object_name名称取得对应的对象引用(适用于表里没有poa信息的接口) * * @param poa_name * @param object_name * @return corba中的引用对象 * * @author 陈仲民(5243) * @throws Exception */ public org.omg.CORBA.Object getProcess_byName(String poa_name, String object_name) throws Exception { // namingContext为空时初始化 if (namingContext == null) { selfInit(); } NameComponent path[] = { new NameComponent(poa_name, "PoaName"), new NameComponent(object_name, "ObjectName") }; org.omg.CORBA.Object envObj = namingContext.resolve(path); return envObj; } /** * 查询接口的poa_name * * @param gather_id * 采集点 * @param ProcessName * 进程名 * @return 接口的poa_name * * @author 陈仲民(5243) */ private String getPoaName(String gather_id, String ProcessName, int processIndex) { // 初始化 String poaName = null; String getPoa = "select para_context from tab_process_config where gather_id='" + gather_id + "' and process_name='" + ProcessName + "' and location='" + processIndex + "' and para_item='LocalPoaName'"; log.debug("getPoaName:" + getPoa); // 查询进程配置 PrepareSQL psql = new PrepareSQL(getPoa); List<Map> poas = jt.queryForList(psql.getSQL()); if (poas.size() > 0) { poaName = poas.get(0).get("para_context").toString(); } return poaName; } /** * 查询设备的object_name * * @param gather_id * 采集点 * @param ProcessName * 进程名 * @return 接口的object_name * * @author 陈仲民(5243) */ private String getObjName(String gather_id, String ProcessName, int processIndex) { // 初始化 String objName = null; String getObjects = "select para_context from tab_process_config where gather_id='" + gather_id + "' and process_name='" + ProcessName + "' and location='" + processIndex + "' and para_item='LocalName'"; log.debug("getObjName:" + getObjects); // 查询进程配置 PrepareSQL psql = new PrepareSQL(getObjects); List<Map> objects = jt.queryForList(psql.getSQL()); if (objects.size() > 0) { objName = objects.get(0).get("para_context").toString(); } return objName; } public void setDao(DataSource dao) { jt = new JdbcTemplate(dao); } }
true
1f35abcc11b95068fe56e919695c11a50a17594c
Java
Nazeer-spec/Java-Basic-Practice
/static&non_static/Non_static.java
UTF-8
310
2.84375
3
[]
no_license
class Non_static { long k=9876543210l; static int v=1234; public void count() { System.out.println("This is Count()"); System.out.println("k ="+k); System.out.println("v ="+v); } public static void main(String[] args) { System.out.println(new Non_static().k); new Non_static().count(); } }
true
7be0df4c8540b308bdebce07ab280f8c4df70808
Java
borisrperezg/rebel
/rebel_chatlogs/src-gen/rebel_chatlogs/MessageLog.java
UTF-8
3,950
2.0625
2
[]
no_license
/** */ package rebel_chatlogs; import java.util.Date; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EObject; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>Message Log</b></em>'. * <!-- end-user-doc --> * * <p> * The following features are supported: * </p> * <ul> * <li>{@link rebel_chatlogs.MessageLog#getMessages <em>Messages</em>}</li> * <li>{@link rebel_chatlogs.MessageLog#getType <em>Type</em>}</li> * <li>{@link rebel_chatlogs.MessageLog#getCreation <em>Creation</em>}</li> * <li>{@link rebel_chatlogs.MessageLog#getTitle <em>Title</em>}</li> * <li>{@link rebel_chatlogs.MessageLog#getId <em>Id</em>}</li> * </ul> * * @see rebel_chatlogs.Rebel_chatlogsPackage#getMessageLog() * @model * @generated */ public interface MessageLog extends EObject { /** * Returns the value of the '<em><b>Messages</b></em>' containment reference list. * The list contents are of type {@link rebel_chatlogs.Message}. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the value of the '<em>Messages</em>' containment reference list. * @see rebel_chatlogs.Rebel_chatlogsPackage#getMessageLog_Messages() * @model containment="true" * @generated */ EList<Message> getMessages(); /** * Returns the value of the '<em><b>Type</b></em>' attribute. * The literals are from the enumeration {@link rebel_chatlogs.MessageLogType}. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the value of the '<em>Type</em>' attribute. * @see rebel_chatlogs.MessageLogType * @see #setType(MessageLogType) * @see rebel_chatlogs.Rebel_chatlogsPackage#getMessageLog_Type() * @model * @generated */ MessageLogType getType(); /** * Sets the value of the '{@link rebel_chatlogs.MessageLog#getType <em>Type</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Type</em>' attribute. * @see rebel_chatlogs.MessageLogType * @see #getType() * @generated */ void setType(MessageLogType value); /** * Returns the value of the '<em><b>Creation</b></em>' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the value of the '<em>Creation</em>' attribute. * @see #setCreation(Date) * @see rebel_chatlogs.Rebel_chatlogsPackage#getMessageLog_Creation() * @model * @generated */ Date getCreation(); /** * Sets the value of the '{@link rebel_chatlogs.MessageLog#getCreation <em>Creation</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Creation</em>' attribute. * @see #getCreation() * @generated */ void setCreation(Date value); /** * Returns the value of the '<em><b>Title</b></em>' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the value of the '<em>Title</em>' attribute. * @see #setTitle(String) * @see rebel_chatlogs.Rebel_chatlogsPackage#getMessageLog_Title() * @model * @generated */ String getTitle(); /** * Sets the value of the '{@link rebel_chatlogs.MessageLog#getTitle <em>Title</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Title</em>' attribute. * @see #getTitle() * @generated */ void setTitle(String value); /** * Returns the value of the '<em><b>Id</b></em>' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the value of the '<em>Id</em>' attribute. * @see #setId(String) * @see rebel_chatlogs.Rebel_chatlogsPackage#getMessageLog_Id() * @model * @generated */ String getId(); /** * Sets the value of the '{@link rebel_chatlogs.MessageLog#getId <em>Id</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Id</em>' attribute. * @see #getId() * @generated */ void setId(String value); } // MessageLog
true
703bf94ff1700412341499b8d441b4657a25103c
Java
ducdh1210/Interview_Prep
/src/Design_Pattern/Pattern_Decorator/Pizza.java
UTF-8
238
2.5625
3
[]
no_license
package Design_Pattern.Pattern_Decorator; /** * Created by ducdh1210 on 10/17/14. */ /** Blueprint for classes that will have decorators */ public interface Pizza { public String getDescription(); public double getCost(); }
true
5983de84957d9c11459135a1ece25bd8f65b4fb8
Java
ZoranLi/thunder
/anet/channel/security/ISecurityFactory.java
UTF-8
186
1.726563
2
[]
no_license
package anet.channel.security; /* compiled from: Taobao */ public interface ISecurityFactory { ISecurity createNonSecurity(String str); ISecurity createSecurity(String str); }
true
8373fe5a54e8b6ccbbcef2fea7ef5a054911d304
Java
srikanth1998/FindingHospitalsHackathon
/src/test/java/com/team/findinghospital/qa/testcases/CorporateWellnessPageTest.java
UTF-8
3,438
2.15625
2
[]
no_license
package com.team.findinghospital.qa.testcases; import java.util.ArrayList; import java.util.List; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import com.team.findinghospital.base.TestBase; import com.team.findinghospital.pages.CorporateWellnessPage; import com.team.findinghospital.pages.DiagnosticPage; import com.team.findinghospital.pages.LandingPage; import com.team.findinghospital.pages.SearchFilters; import com.team.findinghospital.util.CaptureScreen; import com.team.findinghospital.util.ExcelData; /* * This class used To check Corporate Wellness, To schedule & capture the warning message from the alert by giving invalid data */ public class CorporateWellnessPageTest extends TestBase{ CorporateWellnessPage corporateWellnessPage; DiagnosticPage diagnosticPage; SearchFilters searchFilters; String name,organisation,Email, number ; public CorporateWellnessPageTest() { super(); } /* * Method to access Excel sheet */ @BeforeMethod public void setup() { try { initialization(); corporateWellnessPage = new CorporateWellnessPage(); diagnosticPage = new DiagnosticPage(); searchFilters = new SearchFilters(); ExcelData excelData = new ExcelData(); FormDetails = ExcelData.readExcel(); } catch(Exception e) { e.printStackTrace(); } } /* * To schedule Demo by giving name, Organisation name, Email, number correct or not */ @Test(groups={"regression"}) public void scheduleDem1() { try { logger = report.createTest("scheduleDem1" ); diagnosticPage.CorparateWellness(logger); corporateWellnessPage.scheduleDemo(FormDetails[2],FormDetails[3],FormDetails[4],FormDetails[5],logger ); } catch(Exception e) { e.printStackTrace(); } } /* * To schedule Demo by giving name, Organisation name, Email, number correct or not */ @Test(groups={"regression"}) public void scheduleDemo2() { try { logger = report.createTest("scheduleDemo2" ); diagnosticPage.CorparateWellness(logger); corporateWellnessPage.scheduleDemo(FormDetails[6],FormDetails[7],FormDetails[8],FormDetails[9],logger ); } catch(Exception e) { e.printStackTrace(); } } /* * To schedule Demo by giving name, Organisation name, Email, number correct or not */ @Test(groups={"regression"}) public void scheduleDemo3() { try { logger = report.createTest("scheduleDemo3" ); diagnosticPage.CorparateWellness(logger); corporateWellnessPage.scheduleDemo(FormDetails[10],FormDetails[11],FormDetails[12],FormDetails[13],logger ); } catch(Exception e) { e.printStackTrace(); } } /* * To schedule Demo by giving name, Organisation name, Email, number correct or not */ @Test(groups={"regression"}) public void scheduleDemo4() { try { logger = report.createTest("scheduleDemo4" ); diagnosticPage.CorparateWellness(logger); corporateWellnessPage.scheduleDemo(FormDetails[14],FormDetails[15],FormDetails[16],FormDetails[17],logger ); } catch(Exception e) { e.printStackTrace(); } } @AfterMethod public void close(){ try { CaptureScreen.screenShot(); //corporateWellnessPage.sleep(); driver.quit(); report.flush(); } catch(Exception e) { e.printStackTrace(); } } }
true
bfa71f9d508069db86f6ebfb66bcf1c6ba442d52
Java
akshunyaautomation/KalagatoAPIautomation
/src/main/java/kalagato/userAPI/ForgetPasswordRequest.java
UTF-8
748
2
2
[]
no_license
package kalagato.userAPI; import static io.restassured.RestAssured.given; import files.payload; import io.restassured.path.json.JsonPath; public class ForgetPasswordRequest { public String forgetPasswordRequestResponse; public static String forgetPasswordRequestMessage; public void forget_password_request() { forgetPasswordRequestResponse=given().log().all().header("Content-Type","application/json") .body(payload.forgetPasswordRequestBody()) .when().post("/api/v1/user/password/reset-request").then() .assertThat().statusCode(200).extract().response().asString(); JsonPath js1= new JsonPath(forgetPasswordRequestResponse); //for parsing jason forgetPasswordRequestMessage=js1.getString("message"); } }
true
c060623513816358a0ca1b85e84a644a950d6382
Java
guxi/CourseDemo
/CourseDemo/src/edu/wust/array/arrTest.java
GB18030
2,150
2.984375
3
[]
no_license
package edu.wust.array; import java.util.ArrayList; public class arrTest { private int[] arr=new int[3]; private int[][] arr2D=new int[2][2]; private score[] S=new score[3]; void get(){ /*for(int i=0;i<arr.length;i++){ System.out.println(i+":"+arr[i]); }*/ for(score s:S){ System.out.println(s.getCourseNo()+s.getScore()+s.getStuNo()); } } /*void set(){ for(int i=0;i<arr.length;i++){ arr[i]=i+3; } }*/ void SecForTest(score[] scRef,int[][] Arr2D ){ System.out.println("-------------"); int i=0; for(int z:arr){ //൱int z=arr[i]; z=6; System.out.println(z); System.out.println(arr[i]); } System.out.println("-------2DArr------"); int j=0; for(int[] z:Arr2D){ //൱int[] z=Arr2D[i][j]; z[0]=6; System.out.println(z[0]); System.out.println(Arr2D[j][0]); } System.out.println("-------reference------"); int k=0; for(score s:scRef){ //൱score s=scRef[i]; s.setScore(6); System.out.println(s.getScore()); System.out.println(scRef[k].getScore()); i++; } } void sett(score[] sc){ System.out.println("-------------"); int j=0; for(int z:arr){ //൱int z=arr[i]; z=6; System.out.println(z); System.out.println(arr[j]); } System.out.println("-------reference------"); //for(score s:sc){ // System.out.println(s.getScore()); //} int i=0; for(score s:sc){ //൱score s=sc[i]; s.setScore(4); System.out.println(s.getScore()); System.out.println(sc[i].getScore()); i++; //System.out.println("-----after"+i+"---------"); //System.out.println(sc[i].getScore()); //sc[i].setScore(1.0); //System.out.println(sc[i].getScore()); } } public static void main(String[] args) { arrTest t=new arrTest(); t.S[0]=new score(1,1.0,1); t.S[1]=new score(2,2.0,2); t.S[2]=new score(3,3.0,3); t.sett(t.S); //int i=0; System.out.println("-----after---------"); for(score s:t.S){ System.out.println(s.getScore()); //i++; } } }
true
af47e5ec0d97ebd9ba6479835043613d60a5df7c
Java
swlee93/whatsysup
/whatsysup-server/src/main/java/whatsysup/polls/model/Poll.java
UTF-8
2,400
2.140625
2
[]
no_license
package whatsysup.polls.model; import java.time.Instant; import java.util.ArrayList; import java.util.List; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import org.hibernate.annotations.BatchSize; import org.hibernate.annotations.Fetch; import org.hibernate.annotations.FetchMode; import whatsysup.polls.model.audit.UserDateAudit; @Entity @Table(name="polls") public class Poll extends UserDateAudit { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private Long id; @NotBlank @Size(max=10000) private String question; @OneToMany(mappedBy="poll", cascade={javax.persistence.CascadeType.ALL}, fetch=FetchType.EAGER, orphanRemoval=true) @Size(min=2, max=6) @Fetch(FetchMode.SELECT) @BatchSize(size=1000) private List<Choice> choices = new ArrayList(); @NotNull private Instant expirationDateTime; @NotNull private Integer check_interval; @NotBlank @Size(max=500) private String tags; public Poll() {} public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getQuestion() { return question; } public void setQuestion(String question) { this.question = question; } public List<Choice> getChoices() { return choices; } public void setChoices(List<Choice> choices) { this.choices = choices; } public Instant getExpirationDateTime() { return expirationDateTime; } public void setExpirationDateTime(Instant expirationDateTime) { this.expirationDateTime = expirationDateTime; } public void addChoice(Choice choice) { choices.add(choice); choice.setPoll(this); } public void removeChoice(Choice choice) { choices.remove(choice); choice.setPoll(null); } public Integer getCheck_interval() { return check_interval; } public void setCheck_interval(Integer check_interval) { this.check_interval = check_interval; } public String getTags() { return tags; } public void setTags(String tags) { this.tags = tags; } }
true
73b86bbc5674f56ea88c4dbc971784e62ebc1e3a
Java
bfitzpat/tools
/eclipse/plugins/org.switchyard.tools.models.switchyard1_0/src/org/switchyard/tools/models/switchyard1_0/rules/impl/ManifestTypeImpl.java
UTF-8
13,469
1.515625
2
[]
no_license
/** */ package org.switchyard.tools.models.switchyard1_0.rules.impl; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.notify.NotificationChain; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.impl.ENotificationImpl; import org.eclipse.soa.sca.sca1_1.model.sca.impl.CommonExtensionBaseImpl; import org.switchyard.tools.models.switchyard1_0.rules.ContainerType; import org.switchyard.tools.models.switchyard1_0.rules.ManifestType; import org.switchyard.tools.models.switchyard1_0.rules.RemoteJmsType; import org.switchyard.tools.models.switchyard1_0.rules.RemoteRestType; import org.switchyard.tools.models.switchyard1_0.rules.ResourcesType; import org.switchyard.tools.models.switchyard1_0.rules.RulesPackage; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Manifest Type</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * <ul> * <li>{@link org.switchyard.tools.models.switchyard1_0.rules.impl.ManifestTypeImpl#getContainer <em>Container</em>}</li> * <li>{@link org.switchyard.tools.models.switchyard1_0.rules.impl.ManifestTypeImpl#getResources <em>Resources</em>}</li> * <li>{@link org.switchyard.tools.models.switchyard1_0.rules.impl.ManifestTypeImpl#getRemoteJms <em>Remote Jms</em>}</li> * <li>{@link org.switchyard.tools.models.switchyard1_0.rules.impl.ManifestTypeImpl#getRemoteRest <em>Remote Rest</em>}</li> * </ul> * </p> * * @generated */ public class ManifestTypeImpl extends CommonExtensionBaseImpl implements ManifestType { /** * The cached value of the '{@link #getContainer() <em>Container</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getContainer() * @generated * @ordered */ protected ContainerType container; /** * The cached value of the '{@link #getResources() <em>Resources</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getResources() * @generated * @ordered */ protected ResourcesType resources; /** * The cached value of the '{@link #getRemoteJms() <em>Remote Jms</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getRemoteJms() * @generated * @ordered */ protected RemoteJmsType remoteJms; /** * The cached value of the '{@link #getRemoteRest() <em>Remote Rest</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getRemoteRest() * @generated * @ordered */ protected RemoteRestType remoteRest; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected ManifestTypeImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return RulesPackage.Literals.MANIFEST_TYPE; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public ContainerType getContainer() { return container; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetContainer(ContainerType newContainer, NotificationChain msgs) { ContainerType oldContainer = container; container = newContainer; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, RulesPackage.MANIFEST_TYPE__CONTAINER, oldContainer, newContainer); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setContainer(ContainerType newContainer) { if (newContainer != container) { NotificationChain msgs = null; if (container != null) msgs = ((InternalEObject)container).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - RulesPackage.MANIFEST_TYPE__CONTAINER, null, msgs); if (newContainer != null) msgs = ((InternalEObject)newContainer).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - RulesPackage.MANIFEST_TYPE__CONTAINER, null, msgs); msgs = basicSetContainer(newContainer, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, RulesPackage.MANIFEST_TYPE__CONTAINER, newContainer, newContainer)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public ResourcesType getResources() { return resources; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetResources(ResourcesType newResources, NotificationChain msgs) { ResourcesType oldResources = resources; resources = newResources; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, RulesPackage.MANIFEST_TYPE__RESOURCES, oldResources, newResources); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setResources(ResourcesType newResources) { if (newResources != resources) { NotificationChain msgs = null; if (resources != null) msgs = ((InternalEObject)resources).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - RulesPackage.MANIFEST_TYPE__RESOURCES, null, msgs); if (newResources != null) msgs = ((InternalEObject)newResources).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - RulesPackage.MANIFEST_TYPE__RESOURCES, null, msgs); msgs = basicSetResources(newResources, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, RulesPackage.MANIFEST_TYPE__RESOURCES, newResources, newResources)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public RemoteJmsType getRemoteJms() { return remoteJms; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetRemoteJms(RemoteJmsType newRemoteJms, NotificationChain msgs) { RemoteJmsType oldRemoteJms = remoteJms; remoteJms = newRemoteJms; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, RulesPackage.MANIFEST_TYPE__REMOTE_JMS, oldRemoteJms, newRemoteJms); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setRemoteJms(RemoteJmsType newRemoteJms) { if (newRemoteJms != remoteJms) { NotificationChain msgs = null; if (remoteJms != null) msgs = ((InternalEObject)remoteJms).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - RulesPackage.MANIFEST_TYPE__REMOTE_JMS, null, msgs); if (newRemoteJms != null) msgs = ((InternalEObject)newRemoteJms).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - RulesPackage.MANIFEST_TYPE__REMOTE_JMS, null, msgs); msgs = basicSetRemoteJms(newRemoteJms, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, RulesPackage.MANIFEST_TYPE__REMOTE_JMS, newRemoteJms, newRemoteJms)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public RemoteRestType getRemoteRest() { return remoteRest; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetRemoteRest(RemoteRestType newRemoteRest, NotificationChain msgs) { RemoteRestType oldRemoteRest = remoteRest; remoteRest = newRemoteRest; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, RulesPackage.MANIFEST_TYPE__REMOTE_REST, oldRemoteRest, newRemoteRest); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setRemoteRest(RemoteRestType newRemoteRest) { if (newRemoteRest != remoteRest) { NotificationChain msgs = null; if (remoteRest != null) msgs = ((InternalEObject)remoteRest).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - RulesPackage.MANIFEST_TYPE__REMOTE_REST, null, msgs); if (newRemoteRest != null) msgs = ((InternalEObject)newRemoteRest).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - RulesPackage.MANIFEST_TYPE__REMOTE_REST, null, msgs); msgs = basicSetRemoteRest(newRemoteRest, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, RulesPackage.MANIFEST_TYPE__REMOTE_REST, newRemoteRest, newRemoteRest)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case RulesPackage.MANIFEST_TYPE__CONTAINER: return basicSetContainer(null, msgs); case RulesPackage.MANIFEST_TYPE__RESOURCES: return basicSetResources(null, msgs); case RulesPackage.MANIFEST_TYPE__REMOTE_JMS: return basicSetRemoteJms(null, msgs); case RulesPackage.MANIFEST_TYPE__REMOTE_REST: return basicSetRemoteRest(null, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case RulesPackage.MANIFEST_TYPE__CONTAINER: return getContainer(); case RulesPackage.MANIFEST_TYPE__RESOURCES: return getResources(); case RulesPackage.MANIFEST_TYPE__REMOTE_JMS: return getRemoteJms(); case RulesPackage.MANIFEST_TYPE__REMOTE_REST: return getRemoteRest(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case RulesPackage.MANIFEST_TYPE__CONTAINER: setContainer((ContainerType)newValue); return; case RulesPackage.MANIFEST_TYPE__RESOURCES: setResources((ResourcesType)newValue); return; case RulesPackage.MANIFEST_TYPE__REMOTE_JMS: setRemoteJms((RemoteJmsType)newValue); return; case RulesPackage.MANIFEST_TYPE__REMOTE_REST: setRemoteRest((RemoteRestType)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case RulesPackage.MANIFEST_TYPE__CONTAINER: setContainer((ContainerType)null); return; case RulesPackage.MANIFEST_TYPE__RESOURCES: setResources((ResourcesType)null); return; case RulesPackage.MANIFEST_TYPE__REMOTE_JMS: setRemoteJms((RemoteJmsType)null); return; case RulesPackage.MANIFEST_TYPE__REMOTE_REST: setRemoteRest((RemoteRestType)null); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case RulesPackage.MANIFEST_TYPE__CONTAINER: return container != null; case RulesPackage.MANIFEST_TYPE__RESOURCES: return resources != null; case RulesPackage.MANIFEST_TYPE__REMOTE_JMS: return remoteJms != null; case RulesPackage.MANIFEST_TYPE__REMOTE_REST: return remoteRest != null; } return super.eIsSet(featureID); } } //ManifestTypeImpl
true
51e40350ed2f6fa8be64523d4c14b58cb9cefaa8
Java
nafiu1994/Assignment3_10522782
/src/ProgByDoing/GettingIndividualDigits.java
UTF-8
718
3.171875
3
[]
no_license
package ProgByDoing; /** * * @author Lawal Nafiu */ public class GettingIndividualDigits { public static void main(String[] args) throws Exception { int sum; for(int j = 10; j < 100; j++) { System.out.print(j + ", "); sum = 0; for (int i = 0; i < 2; i++) { if( i == 0) { sum += j / 10; System.out.print(sum + "+"); } else { sum += j % 10; } } System.out.println(j%10 + " = " + sum); } } }
true
bafb7be5bca6cd21dde3fe34bbb8e95fe939dfe7
Java
frzhao99/frzhao01
/LOTTERY_MEMBER_1.2/src/com/symbio/dao/hibernate/GenericDao.java
UTF-8
4,559
2.671875
3
[]
no_license
package com.symbio.dao.hibernate; import java.io.Serializable; import java.util.List; import java.util.Map; import com.symbio.commons.Compositor; import com.symbio.commons.Filtration; import com.symbio.commons.Page; /** * * dao基类. 1:该类封装了最常见数据库操作的方法,不同的ORM映射框架可以实现该接口,实现项目通用Dao * 2:当你有多个sessionFactory时,你也可以在你的子类中重写setSessionFactory()方法 * * @author Fred * @param <T> * */ public interface GenericDao<T, PK extends Serializable> { /** * 新增对象. */ public void save(T entity); /** * 修改对象. */ public void update(T entity); /** * 删除对象. */ public void delete(T entity); /** * 删除对象. */ public void delete(PK id); /** * 根据主键ID获取对象,用hibernate的get方法加载 * @param id * @return */ public T get(PK id); public T getSyn(PK id); /** * 根据主键ID获取对象,用hibernate的load方法加载 */ public T find(PK id); /** * * 按属性查找唯一对象,匹配方式为相等. * @param fieldName 实体字段名 * @param fieldValue 实体属性值 * @return 如果匹配到则返回匹配到的实体,反之返回空 */ public T findByField(String fieldName, Object fieldValue); public T findByFieldSyn(String sql); /** * 按属性查找对象列表,匹配方式为相等. * @param fieldName 实体字段名 * @param fieldValue 实体字段要匹配的值 * @return 与该实体值相等的实体列表 */ public List<T> findList(String fieldName, Object fieldValue); /** * 按照过滤条件对象查找对象列表. */ public List<T> findList(Filtration... filtrations); /** * 按照过滤条件对象查找对象列表. */ public List<T> findList(List<Filtration> filtrationList); /** * 按照过滤条件对象查找对象列表,支持排序. */ public List<T> findList(Compositor compositor, Filtration... filtrations); /** * 按照过滤条件对象查找对象列表,支持排序. */ public List<T> findList(Compositor compositor, List<Filtration> filtrationList); /** * 获取全部对象. */ public List<T> findAll(); /** * 获取全部对象,支持排序. * * @param compositor * 排序条件 * @return */ public List<T> findAll(Compositor compositor); /** * 分页查询. */ public Page<T> find(Page<T> pageData); /** * 按id列表获取对象. */ public List<T> findListByIds(List<PK> idList); // -------------------------------------------------------------------------------------------------- /** * 按HQL查询唯一对象. * * @param hql * "from Users where name=? and password=?" * @param values * 数量可变的参数,按顺序绑定. * @return */ public <X> X find(String hql, Object... values); /** * 按HQL查询唯一对象. * * @param hql * "from Users where name=:name and password=:password" * @param values * 命名参数,按名称绑定. * @return */ public <X> X find(String hql, Map<String, ?> values); /** * 按HQL查询对象列表. * * @param hql * "from Users where name=? and password=?" * @param values * 数量可变的参数,按顺序绑定. * @return */ public <X> List<X> findList(String hql, Object... values); /** * 按HQL查询对象列表. * * @param hql * "from Users where name=:name and password=:password" * @param values * 命名参数,按名称绑定. * @return */ public <X> List<X> findList(String hql, Map<String, ?> values); /** * 执行HQL进行批量修改/删除操作. * * @return 更新记录数. */ public int batchExecute(String hql, Object... values); /** * 执行HQL进行批量修改/删除操作. * * @return 更新记录数. */ public int batchExecute(String hql, Map<String, ?> values); // -------------------------------------------------------------------------------------------------- /** * 本地SQL进行修改/删除操作. * * @return 更新记录数. */ public List find(String sql); /** * 刷新当前事物,提交数据 */ public void flush(); <X> List<X> findList(String list, String hql, Object[] values); }
true
ace1d96836940408895f3cfb351da28c5957a497
Java
jboss-modules/jboss-modules
/src/main/java/org/jboss/modules/ref/StrongReference.java
UTF-8
1,667
2.296875
2
[ "Apache-2.0", "LicenseRef-scancode-indiana-extreme" ]
permissive
/* * JBoss, Home of Professional Open Source. * Copyright 2014 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.modules.ref; /** * A strong reference with an attachment. Since strong references are always reachable, a reaper may not be used. * * @param <T> the reference value type * @param <A> the attachment type * * @author <a href="mailto:david.lloyd@redhat.com">David M. Lloyd</a> */ public class StrongReference<T, A> implements Reference<T, A> { private volatile T value; private final A attachment; public StrongReference(final T value, final A attachment) { this.value = value; this.attachment = attachment; } public StrongReference(final T value) { this(value, null); } public T get() { return value; } public void clear() { value = null; } public A getAttachment() { return attachment; } public Type getType() { return Type.STRONG; } public String toString() { return "strong reference to " + String.valueOf(get()); } }
true
2e44f594ab62a267fea8d61b5c5fc8b234ea3228
Java
pluskot/ShoppingListClient
/app/src/main/java/com/example/patryk/shoppinglist/activities/LandingPageActivity.java
UTF-8
1,173
2.0625
2
[]
no_license
package com.example.patryk.shoppinglist.activities; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import com.example.patryk.shoppinglist.R; public class LandingPageActivity extends AppCompatActivity { Button loginButton, registerButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_landing_page); initComponents(); } private void initComponents() { loginButton = findViewById(R.id.login_button); loginButton.setOnClickListener(v -> onLoginButtonClick()); registerButton = findViewById(R.id.register_button); registerButton.setOnClickListener(v -> onRegisterButtonClick()); } private void onLoginButtonClick() { Intent loginView = new Intent(this, LoginActivity.class); startActivity(loginView); } private void onRegisterButtonClick() { Intent registerView = new Intent(this, RegisterActivity.class); startActivity(registerView); } }
true
c6c19a58bf66c2a5b71e9ba00328fff82f69d8fb
Java
coypanglei/zongzhi
/app/src/main/java/com/weique/overhaul/v2/di/module/BusinessInterviewModule.java
UTF-8
977
1.898438
2
[ "Apache-2.0" ]
permissive
package com.weique.overhaul.v2.di.module; import com.jess.arms.di.scope.ActivityScope; import dagger.Binds; import dagger.Module; import dagger.Provides; import com.weique.overhaul.v2.mvp.contract.BusinessInterviewContract; import com.weique.overhaul.v2.mvp.model.BusinessInterviewModel; /** * ================================================ * Description: * <p> * Created by MVPArmsTemplate on 03/10/2020 17:58 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a> * <a href="https://github.com/JessYanCoding">Follow me</a> * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a> * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a> * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a> * ================================================ */ @Module public abstract class BusinessInterviewModule { @Binds abstract BusinessInterviewContract.Model bindBusinessInterviewModel(BusinessInterviewModel model); }
true
5e433a622b6893024d133bea730cdb52f1733779
Java
unidev-polydata/polydata-storage-mongodb
/polydata-storage-mongodb-core/src/main/java/com/unidev/polydata/AbstractPolyStorage.java
UTF-8
2,497
2.3125
2
[ "Apache-2.0" ]
permissive
package com.unidev.polydata; import static com.mongodb.client.model.Filters.eq; import com.mongodb.MongoClient; import com.mongodb.client.MongoCollection; import com.mongodb.client.result.DeleteResult; import com.unidev.polydata.domain.BasicPoly; import java.util.Optional; import org.bson.Document; /** * Abstract storage for polydata information. */ public abstract class AbstractPolyStorage { protected MongoClient mongoClient; protected String mongoDatabase; public AbstractPolyStorage(MongoClient mongoClient, String mongoDatabase) { this.mongoClient = mongoClient; this.mongoDatabase = mongoDatabase; } protected abstract void migrate(String poly); protected boolean exist(MongoCollection<Document> collection, String id) { long count = collection.count(eq("_id", id)); return count != 0; } protected BasicPoly save(MongoCollection<Document> collection, BasicPoly basicPoly) { Document document = new Document(basicPoly); collection.insertOne(document); return basicPoly; } protected BasicPoly update(MongoCollection<Document> collection, BasicPoly basicPoly) { Document document = new Document(basicPoly); collection.updateOne(eq("_id", basicPoly._id()), new Document("$set", document)); return basicPoly; } protected BasicPoly saveOrUpdate(MongoCollection<Document> collection, BasicPoly basicPoly) { if (exist(collection, basicPoly._id())) { return update(collection, basicPoly); } return save(collection, basicPoly); } protected Optional<BasicPoly> fetchPoly(MongoCollection<Document> collection, String id) { Document document = collection.find(eq("_id", id)).first(); if (document == null) { return Optional.empty(); } BasicPoly basicPoly = new BasicPoly(); basicPoly.putAll(document); return Optional.of(basicPoly); } protected Optional<Document> fetchRawDocument(MongoCollection<Document> collection, String id) { Document document = collection.find(eq("_id", id)).first(); return Optional.ofNullable(document); } protected boolean removePoly(MongoCollection<Document> collection, String id) { if (!exist(collection, id)) { return false; } DeleteResult deleteResult = collection.deleteOne(eq("_id", id)); return deleteResult.getDeletedCount() == 1L; } }
true
605e2e7083fb1eb3b655151b689a0919fe8f4546
Java
Lrchfox3/Lrchfox3Soft
/src/com/gmail/lrchfox3/paint/InterfaceArrastrarRaton.java
UTF-8
2,104
3.09375
3
[]
no_license
/** * Javier Abell�n, 24 Mayo 2006 * Interface para las clases encargadas de hacer algo cuando se arrastre el * rat�n. */ package com.gmail.lrchfox3.paint; // <editor-fold defaultstate="collapsed" desc=" Librerias "> import java.awt.event.MouseEvent; import java.awt.geom.Point2D; // </editor-fold> /** * Interface para las clases encargadas de hacer algo cuando se arrastre el * rat�n. * @author Chuidiang * */ public interface InterfaceArrastrarRaton { /** * Se llama a este m�todo cuando se empieza a arrastrar el rat�n. * @param x del rat�n. * @param y del rat�n. */ public void comienzaArrastra(int x, int y); /** * Se llama a este m�todo cada vez que se arrastra el rat�n. * @param xAntigua x del rat�n antes del arrastre * @param yAntigua y del rat�n antes del arrastre * @param xNueva x actual del rat�n * @param yNueva y actual del rat�n */ public void arrastra(int xAntigua, int yAntigua, int xNueva, int yNueva); /** * Se llama a este método cuando se termina de arrastrar el rat�n. * @param x del ratón. * @param y del ratón. */ public void finalizaArrastra(int x, int y); /* Opción Mano Alzada*/ public void manoAlzada(MouseEvent e); public void soltarManoAlzada(); /* Opción Línea*/ public void simularLinea(MouseEvent e); public void crearLinea(); /* Opción Rectángulo*/ public void simularRectangulo(MouseEvent e); public void crearRectangulo(); /* Opción Rectángulo Redondo*/ public void simularRectanguloRedondo(MouseEvent e); public void crearRectanguloRedondo(); /* Opción Ovalo*/ public void simularOvalo(MouseEvent e); public void crearOvalo(); public void setShapeMaker(); public int getOpcionDibujo(); public boolean isModoArrastrar(); public int[] trazoActual(Point2D p); public void actualizarTrazo(int[] current, Point2D eventPoint); public void Alejar(); }
true
fb28c2e72ed183bb317f23dd6444e1e0d976a477
Java
ildar66/WSAD_NRI
/2005/webcommon/com/hps/july/security/service/JulySecurityService.java
UTF-8
220
1.84375
2
[]
no_license
package com.hps.july.security.service; /** * @author dkrivenko */ public interface JulySecurityService { /** * @param operatorLogin */ void switchOperator(String operatorLogin) throws JulySecurityException; }
true
55c999716d5830ceb7b88bb0ec9f3b4998cda1ee
Java
Rkato1/Spring
/05_Spring_Mybatis/src/main/java/com/kim/common/MemberPwEnc.java
UTF-8
1,222
2.265625
2
[]
no_license
package com.kim.common; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Pointcut; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.kim.member.model.vo.Member; @Component @Aspect public class MemberPwEnc { //회원 가입, 로그인, 업데이트 포인트 컷으로 만들고 //aop 적용 후 패스워드 암호화 //비밀번호 암호화 로직을 Advice로 만들고 //어느 시점에 적용할지 선정하여 적용 @Autowired SHA256Util enc; @Pointcut("execution(* com.kim.member.model.service.MemberService.*Member(com.kim.member.model.vo.Member))") public void encPw() {} //OOP의 특이점(얉은 복사에 의한 변경으로 적용) @Before("encPw()") public void encPassword(JoinPoint jp) throws Throwable{ Object[] args = jp.getArgs(); Member m = (Member)args[0]; String memPw = m.getMemPw(); if(memPw!=null) { String encPw = enc.encPw(memPw); //System.out.println(encPw); m.setMemPw(encPw); } } }
true
b982649ad853d950f73f74782454c4d7a430c400
Java
liaohao1986/helloworld
/src/main/java/com/huoli/checkin/design/pattern/rpc/RpcProvider.java
UTF-8
546
2.1875
2
[]
no_license
/** * */ package com.huoli.checkin.design.pattern.rpc; /** * TODO:简单描述这个类的含义 <br> * 版权:Copyright (c) 2011-2017<br> * 公司:北京活力天汇<br> * 版本:1.0<br> * 作者:廖浩<br> * 创建日期:2017年4月1日<br> */ /** * RpcProvider * * @author william.liangf */ public class RpcProvider { public static void main(String[] args) throws Exception { HelloService service = new HelloServiceImpl(); RpcFramework.export(service, 1234); } }
true
9f6f86e8236357a74eac2016e8100877d40f5fcc
Java
luciano/studying_android
/SemFogo/app/src/main/java/br/com/liugsilva/semfogo/Empresa.java
UTF-8
1,612
2.5
2
[ "MIT" ]
permissive
package br.com.liugsilva.semfogo; import java.io.Serializable; /** * Created by Luciano on 15/02/2016. */ public class Empresa implements Serializable { public static final String NOME = "nome"; public static final String EMAIL = "email"; public static final String TELEFONE = "telefone"; public static final String ENDERECO = "cidade"; public static final String MENSAGEM = "mensagem"; private String nome; private String email; private String telefone; private String endereco; private String mensagem; public Empresa(String nome, String email, String telefone, String endereco, String mensagem) { this.nome = nome; this.email = email; this.telefone = telefone; this.endereco = endereco; this.mensagem = mensagem; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getTelefone() { return telefone; } public void setTelefone(String telefone) { this.telefone = telefone; } public String getEndereco() { return endereco; } public void setEndereco(String endereco) { this.endereco = endereco; } public String getMensagem() { return mensagem; } public void setMensagem(String mensagem) { this.mensagem = mensagem; } }
true
c44ffbb0290fd91e2d2655f5a0d20fc8a1d14bac
Java
hoangson13/Monster-Life
/Moster Life/src/dev/game/entities/combattroop/EnemyTroop.java
UTF-8
4,188
2.421875
2
[]
no_license
package dev.game.entities.combattroop; import dev.game.Handler; import dev.game.entities.Entity; import dev.game.entities.EntityManager; import dev.game.entities.ID; import dev.game.entities.bullet.EnemyBullet; import dev.game.entities.bullet.EnemySmartBullet; import dev.game.entities.bullet.PlayerBullet; import dev.game.entities.ship.PlayerShip; import dev.game.gfx.Animation; import dev.game.gfx.Asset; import java.awt.Color; import java.awt.Graphics; public class EnemyTroop extends CombatTroop { private final float inital; private final float se; private int count = 0; private int[][] MonIndex; private int MonNumber; private Animation Anitemp; public EnemyTroop(int[][] MonIndex, int MonNumber, EntityManager entitymanager, Handler handler, float x, float y, ID id) { super(entitymanager, handler, x, y, id); this.MonIndex = MonIndex; this.MonNumber = MonNumber; inital = x; setMaxhealth(MonIndex[MonNumber][3]); setHealth(maxhealth); setAtk(MonIndex[MonNumber][4]); setDef((float) MonIndex[MonNumber][5] / 100); setSpeed(MonIndex[MonNumber][6]); se = 200.0f / maxhealth; if (MonIndex[MonNumber][2] == 1) { Anitemp = new Animation(500, Asset.enemy1); } else if (MonIndex[MonNumber][2] == 2) { Anitemp = new Animation(500, Asset.enemy2); } else if (MonIndex[MonNumber][2] == 3) { Anitemp = new Animation(500, Asset.enemy3); } else { Anitemp = new Animation(500, Asset.enemy4); } } @Override public void tick() { Anitemp.tick(); x += speed; if (x <= inital - 150 || x >= inital + 150) { speed *= -1; //lock vị trí cách 80px } count++; if (count % MonIndex[MonNumber][7] == 0) { entitymanager.addEntity(new EnemyBullet(entitymanager, handler, x + width / 2, y + height, ID.EnemyBullet, atk, MonIndex[MonNumber][9])); } if (count % MonIndex[MonNumber][8] == 0) { entitymanager.addEntity(new EnemySmartBullet(entitymanager, handler, x + width / 2, y + height, ID.SmartEnemyBullet, atk, MonIndex[MonNumber][9])); } Entity e = checkEntityCollisions(0f, 0f); if (e != null && e.getID() == ID.PlayerBullet) { PlayerBullet bullet = (PlayerBullet) e; hurt((int) (bullet.getAtk() * def)); bullet.setActive(false); } } @Override public void render(Graphics g) { g.drawImage(Anitemp.getCurrentFrame(), (int) (x), (int) (y), width, height, null); //Enemy health bar g.setColor(Color.decode("#FF304F")); g.fillRect(650, 30, 200, 20); g.setColor(Color.black); g.drawRect(650, 30, 200, 20); g.setColor(Color.decode("#28C7FA")); g.fillRect(650, 30, (int) (health * se), 20); if (health <= 0) { g.drawString("Enemy's HP :" + 0, 650, 20); } else { g.drawString("Enemy's HP :" + health, 650, 20); } } @Override public void die() { for (Entity e : handler.getWorld().getEntityManager().getEntities()) { if (e.getID() == ID.PlayerTroop) { PlayerTroop playertroop = (PlayerTroop) e; for (Entity e1 : handler.getWorld().getEntityManager().getEntities()) { if (e1.getID() == ID.Player) { PlayerShip playerShip = (PlayerShip) e1; playerShip.setHealth(playertroop.health); playerShip.setAtk(playertroop.atk); playerShip.setDef(playertroop.def); break; } } for (Entity e2 : handler.getWorld().getEntityManager().getEntities()) { if (e2.getID() != ID.Player && e2.getID() != ID.Enemy) { e2.setActive(false); } } } } } }
true
9c39d505f06c4010b8801dc2d0cfa9790ff75b4a
Java
sanioglusena/CustomerApplication
/src/main/java/com/delivery/customer/mapper/CustomerMapper.java
UTF-8
815
2.46875
2
[]
no_license
package com.delivery.customer.mapper; import com.delivery.customer.entity.Customer; import com.delivery.customer.response.AddressDto; import com.delivery.customer.response.CustomerDto; import java.util.List; import java.util.stream.Collectors; public class CustomerMapper { public static CustomerDto map(Customer customer) { List<AddressDto> addresses = customer.getAddresses() .stream() .map(AddressMapper::map) .collect(Collectors.toList()); return CustomerDto.builder() .id(customer.getId()) .firstName(customer.getFirstName()) .lastName(customer.getLastName()) .phoneNumber(customer.getPhoneNumber()) .addresses(addresses) .build(); } }
true
6df2cdd0b0f895316f55fe2be18a4d37ba886dd2
Java
lingxfeng/seafood
/frame/src/shop/src/main/java/com/eastinno/otransos/shop/promotions/query/RushPayRecordQuery.java
UTF-8
1,829
2.15625
2
[]
no_license
package com.eastinno.otransos.shop.promotions.query; import java.util.Date; import com.eastinno.otransos.core.support.query.QueryObject; public class RushPayRecordQuery extends QueryObject{ private static final long serialVersionUID = 1L; private Date startDate; private Date endDate; private String regularName; private String regularCode; private String proName; private String proId; public Date getStartDate() { return startDate; } public void setStartDate(Date startDate) { this.startDate = startDate; } public Date getEndDate() { return endDate; } public void setEndDate(Date endDate) { this.endDate = endDate; } public String getRegularName() { return regularName; } public void setRegularName(String regularName) { this.regularName = regularName; } public String getRegularCode() { return regularCode; } public void setRegularCode(String regularCode) { this.regularCode = regularCode; } public String getProName() { return proName; } public void setProName(String proName) { this.proName = proName; } public String getProId() { return proId; } public void setProId(String proId) { this.proId = proId; } @Override public void customizeQuery(){ if(this.startDate != null){ this.addQuery("obj.createDate", this.startDate, ">="); } if(this.endDate != null){ this.addQuery("obj.createDate", this.endDate, "<="); } if(this.proId != null){ this.addQuery("obj.pro.id", this.proId, "="); } if(this.proName != null){ this.addQuery("obj.pro.name", "%"+this.proName+"%", "like"); } if(this.regularCode != null){ this.addQuery("obj.regular.code", "%"+this.regularCode+"%", "like"); } if(this.regularName != null){ this.addQuery("obj.regular.name", "%"+this.regularName+"%", "like"); } super.customizeQuery(); } }
true
35f71c1db068148092c848bcea97a3415c3e82e8
Java
thakur03/DemoHibernate
/src/com/grailsbrains/actions/RetrieveAction.java
UTF-8
1,215
2.09375
2
[]
no_license
package com.grailsbrains.actions; import com.grailsbrains.manage.Output; import com.grailsbrains.manage.POManage; import com.grailsbrains.persistence.PurchaseOrder; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; /** * Created by Ajeet on 5/9/2017. */ public class RetrieveAction extends Action { public static int count=0; @Override public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { POManage poManage = new POManage(); List<Output> orderList = poManage.viewOrders(); for(Output o: orderList){ System.out.println(o.getPoNumber()); System.out.println(o.getDueDate()); System.out.println(o.getStatus()); } request.setAttribute("finalList", orderList); return mapping.findForward("success"); } }
true
9dd749e02fff1751fa5843837f3f5623ef129ea0
Java
mariabarburescu/Sistem-de-facturi-fiscale
/Login.java
UTF-8
1,461
2.578125
3
[]
no_license
package SistemDeFacturiFiscale; import javax.swing.JPanel; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JTextField; import javax.swing.JPasswordField; import java.awt.CardLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; public class Login extends JPanel { private JTextField textField; private JPasswordField passwordField; public Login(CardLayout layout, JPanel contentPane) { setLayout(null); JLabel lblUsername = new JLabel("username"); lblUsername.setBounds(96, 107, 89, 40); add(lblUsername); JLabel lblPassword = new JLabel("password"); lblPassword.setBounds(96, 170, 70, 40); add(lblPassword); textField = new JTextField(); textField.setBounds(310, 118, 114, 19); add(textField); textField.setColumns(10); passwordField = new JPasswordField(); passwordField.setBounds(310, 181, 114, 19); add(passwordField); JButton btnLogin = new JButton("Login"); btnLogin.setBounds(202, 298, 117, 25); add(btnLogin); btnLogin.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { String password = passwordField.getText(); String username = textField.getText(); if (password.equals("aris") && username.equals("mada")) { layout.show(contentPane, "choice"); } else JOptionPane.showMessageDialog(null,"Try again!"); } }); } }
true
91dc0007d6d683609d54350872a43148fe614b17
Java
lilleswing/Google-Code-Jam
/java-gcj/src/main/java/lilleswing/gcj/a2013/qualification/fairsquare/Dataset.java
UTF-8
226
2.09375
2
[]
no_license
package lilleswing.gcj.a2013.qualification.fairsquare; class Dataset { private int lower; private int upper; public Dataset(int lower, int upper) { this.lower = lower; this.upper = upper; } }
true
996067a02f0adafd7d8a1d3ea6d58cd66367ddfb
Java
ict20215/ict
/pra03/src/work/Company.java
UTF-8
505
2.1875
2
[]
no_license
package work; import java.io.Serializable; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; /** * Servlet implementation class Company */ @WebServlet(name = "Companyname", urlPatterns = { "/Companynamemap" }) public class Company extends HttpServlet implements Serializable { private String companyname = null ; public String getCompanyname() { return companyname; } public void setCompanyname(String companyname) { this.companyname = companyname; } }
true
cdb56bf0173bbec5dcb0be971d0406cb44a39df4
Java
MegaTuks/GodRace
/src/godrace/Game.java
UTF-8
13,073
2.46875
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 godrace; import java.awt.Graphics; import java.awt.Image; import java.awt.Toolkit; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.JFrame; /** * * @author Ovidio */ public class Game extends JFrame implements Runnable, MouseListener, KeyListener { private static final long serialVersionUID = 1L; //variables private boolean izquierda; private boolean izquierda2; private boolean derecha; private boolean derecha2; private boolean arriba; private boolean arriba2; private boolean abajo; private boolean abajo2; private boolean pausa; private boolean instrucciones; private boolean start; private boolean gameover; private boolean pausaCharSelect; private boolean pausaMapSelect; private boolean rainbow; private Graphics dbg; private Image dbImage; private Image startScreen; private Image instructionScreen; private Image characterSelect; private Image mapSelect; private Image RainbowRoad; private Image creditScreen; private BasePersonajes P1; private BasePersonajes P2; //Variables control de tiempo de animacion private long tiempoActual; private long tiempoInicial; public Game() { init(); start(); } public void init() { setSize(1200,720); izquierda = false; izquierda2 = false; derecha = false; derecha2 = false; arriba = false; arriba2 = false; abajo = false; abajo2 = false; pausa = false; instrucciones = false; start = false; pausaCharSelect = false; pausaMapSelect = false; rainbow = false; gameover = false; startScreen = Toolkit.getDefaultToolkit().getImage(this.getClass().getResource("/images/BioForge_TitleScreen.png")); instructionScreen = Toolkit.getDefaultToolkit().getImage(this.getClass().getResource("/images/BioForge_Instructions.png")); characterSelect = Toolkit.getDefaultToolkit().getImage(this.getClass().getResource("/images/BioForge_CharacterSelect.png")); mapSelect = Toolkit.getDefaultToolkit().getImage(this.getClass().getResource("/images/BioForge_MapSelect.png")); RainbowRoad = Toolkit.getDefaultToolkit().getImage(this.getClass().getResource("/images/BioForge_Map2_RainbowRoadNoSeparado.png")); creditScreen = Toolkit.getDefaultToolkit().getImage(this.getClass().getResource("/images/CREDITS.png")); P1 = new BasePersonajes(); P2 = new BasePersonajes(); addKeyListener(this); } /** * Metodo <I>start</I> sobrescrito de la clase <code>Applet</code>.<P> * En este metodo se crea e inicializa el hilo * para la animacion este metodo es llamado despues del init o * cuando el usuario visita otra pagina y luego regresa a la pagina * en donde esta este <code>Applet</code> * */ public void start () { // Declaras un hilo Thread th = new Thread (this); // Empieza el hilo th.start (); } /** * Metodo <I>stop</I> sobrescrito de la clase <code>Applet</code>.<P> * En este metodo se pueden tomar acciones para cuando se termina * de usar el <code>Applet</code>. Usualmente cuando el usuario sale de la pagina * en donde esta este <code>Applet</code>. */ public void stop() { } /** * Metodo <I>destroy</I> sobrescrito de la clase <code>Applet</code>.<P> * En este metodo se toman las acciones necesarias para cuando * el <code>Applet</code> ya no va a ser usado. Usualmente cuando el usuario * cierra el navegador. */ public void destroy() { } /** * Metodo <I>run</I> sobrescrito de la clase <code>Thread</code>.<P> * En este metodo se ejecuta el hilo, es un ciclo indefinido donde se incrementa * la posicion en x o y dependiendo de la direccion, finalmente * se repinta el <code>Applet</code> y luego manda a dormir el hilo. * */ public void run () { //Guarda el tiempo actual del sistema tiempoActual = System.currentTimeMillis(); while (true) { actualiza(); checaColision(); repaint(); // Se actualiza el <code>Applet</code> repintando el contenido. try { // El thread se duerme. Thread.sleep (30); } catch (InterruptedException ex) { System.out.println("Error en " + ex.toString()); } } } /** * Metodo <I>actualiza</I> * Este metodo actualiza a los personajes en el applet en sus movimientos */ public void actualiza() { while (!pausa) { } } /** * Metodo <I>checaColision</I> * Este metodo checa la colision entre los personajes, * la colision de los malos con la parte inferior del applet y * la colision del bueno con los extremos del applet */ public void checaColision() { while (!pausa) { } } /** * Metodo <I>paint</I> sobrescrito de la clase <code>Applet</code>, * heredado de la clase Container.<P> * En este metodo se dibuja la imagen con la posicion actualizada, * ademas que cuando la imagen es cargada te despliega una advertencia. * @param g es el <code>objeto grafico</code> usado para dibujar. */ public void paint(Graphics g) { //Inicializa el DoubleBuffer if (dbImage == null){ dbImage = createImage(this.getSize().width, this.getSize().height); dbg = dbImage.getGraphics(); } //Actualiza la imagen de fondo dbg.setColor(getBackground()); dbg.fillRect(0, 0, this.getSize().width, this.getSize().height); //Actualiza el Foreground dbg.setColor(getForeground()); paint1(dbg); //Dibuja la imagen actualizada g.drawImage(dbImage, 0, 0, this); } public void paint1(Graphics g) { while (!pausa) { if (!start) g.drawImage(startScreen, 0, 0, this); if (!start && instrucciones) g.drawImage(instructionScreen, 0, 0, this); if (start && !pausaCharSelect) g.drawImage(characterSelect, 0, 0, this); if (start && pausaCharSelect && !pausaMapSelect) g.drawImage(mapSelect, 0, 0, this); if (start && pausaCharSelect && pausaMapSelect && rainbow) g.drawImage(RainbowRoad, 0, 0, this); if (gameover) g.drawImage(creditScreen, 0, 0, this); } } /** * Metodo mouseClicked sobrescrito de la interface MouseListener. * En este metodo maneja el evento que se genera al hacer click con el mouse * sobre algun componente. * e es el evento generado al hacer click con el mouse. */ public void mouseClicked(MouseEvent e) { } /** * Metodo mousePressed sobrescrito de la interface MouseListener. * En este metodo maneja el evento que se genera al presionar un botón * del mouse sobre algun componente. * e es el evento generado al presionar un botón del mouse sobre algun componente. */ public void mousePressed(MouseEvent e) { } /** * Metodo mouseReleased sobrescrito de la interface MouseListener. * En este metodo maneja el evento que se genera al soltar un botón * del mouse sobre algun componente. * e es el evento generado al soltar un botón del mouse sobre algun componente. */ public void mouseReleased(MouseEvent e) { } /** * Metodo mouseEntered sobrescrito de la interface MouseListener. * En este metodo maneja el evento que se genera cuando el mouse * entra en algun componente. * e es el evento generado cuando el mouse entra en algun componente. */ public void mouseEntered(MouseEvent e) { } /** * Metodo mouseExited sobrescrito de la interface MouseListener. * En este metodo maneja el evento que se genera cuando el mouse * sale de algun componente. * e es el evento generado cuando el mouse sale de algun componente. */ public void mouseExited(MouseEvent e) { } /** * Metodo <I>keyPressed</I> sobrescrito de la interface <code>KeyListener</code>.<P> * En este metodo maneja el evento que se genera al presionar cualquier la tecla. * @param e es el <code>evento</code> generado al presionar las teclas. */ public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_ENTER) { if (start && pausaCharSelect && pausaMapSelect && rainbow) { rainbow = false; gameover = true; } if (start && pausaCharSelect && !pausaMapSelect) { pausaMapSelect = true; rainbow = true; } if (start && !pausaCharSelect) pausaCharSelect = true; if (!start) start = true; } if (e.getKeyCode() == KeyEvent.VK_I) { if (!start) { instrucciones = !instrucciones; } } if (e.getKeyCode() == KeyEvent.VK_P) { pausa = !pausa; } if (e.getKeyCode() == KeyEvent.VK_LEFT) { izquierda = true; } if (e.getKeyCode() == KeyEvent.VK_RIGHT) { derecha = true; } if (e.getKeyCode() == KeyEvent.VK_UP) { arriba = true; } if (e.getKeyCode() == KeyEvent.VK_DOWN) { abajo = true; } if (e.getKeyCode() == KeyEvent.VK_A) { izquierda2 = true; } if (e.getKeyCode() == KeyEvent.VK_D) { derecha2 = true; } if (e.getKeyCode() == KeyEvent.VK_W) { arriba2 = true; } if (e.getKeyCode() == KeyEvent.VK_S) { abajo2 = true; } } /** * Metodo <I>keyTyped</I> sobrescrito de la interface <code>KeyListener</code>.<P> * En este metodo maneja el evento que se genera al presionar una tecla que no es de accion. * @param e es el <code>evento</code> que se genera en al presionar las teclas. */ public void keyTyped(KeyEvent e){ } /** * Metodo <I>keyReleased</I> sobrescrito de la interface <code>KeyListener</code>.<P> * En este metodo maneja el evento que se genera al soltar la tecla presionada. * @param e es el <code>evento</code> que se genera en al soltar las teclas. */ public void keyReleased(KeyEvent e){ if (e.getKeyCode() == KeyEvent.VK_LEFT) { izquierda = false; } if (e.getKeyCode() == KeyEvent.VK_RIGHT) { derecha = false; } if (e.getKeyCode() == KeyEvent.VK_UP) { arriba = false; } if (e.getKeyCode() == KeyEvent.VK_DOWN) { abajo = false; } if (e.getKeyCode() == KeyEvent.VK_A) { izquierda2 = false; } if (e.getKeyCode() == KeyEvent.VK_D) { derecha2 = false; } if (e.getKeyCode() == KeyEvent.VK_W) { arriba2 = false; } if (e.getKeyCode() == KeyEvent.VK_S) { abajo2 = false; } } }
true
7acecc6d118157c12b49b9718d9ee058df37a95c
Java
milkyway0308/Horizon-Essentials
/Horizon Essentials/src/Commands/CommandWhisper.java
UHC
2,692
2.28125
2
[]
no_license
package Commands; import java.util.Arrays; import org.bukkit.Bukkit; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import DataUtil.DoubleString; import DataUtil.PermissionType; import Horizon_Essentials.DataManager; import Utility.PlayerUtil; public class CommandWhisper extends CommandsRegistry implements CommandExecutor{ @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { if(sender.isOp() || PlayerUtil.hasPermission(sender, PermissionType.CommandWhisper)) { if(args.length <= 1) super.m.sendMessage(sender,"ɾ ",new DoubleString("[]","/" + label + " [÷̾] []")); else{ if(Bukkit.getPlayer(args[0]) == null) super.m.sendMessage(sender, " ÷̾ ",new DoubleString("[]",args[0])); else{ if(sender instanceof Player){ Player p = Bukkit.getPlayer(args[0]); if(DataManager.players.get(p).FullyIgnore.contains(sender.getName().toLowerCase()) || DataManager.players.get(p).whisperIgnore.contains(sender.getName())){ super.m.sendMessage(sender, "ӼӸ ܵ",new DoubleString("[]",args[0])); return false; } StringBuilder b = new StringBuilder(args[1]); for(int i = 2;i < args.length;i++) b.append(" " + args[i]); super.m.sendMessage(Bukkit.getPlayer(args[0]), "ӼӸ",Arrays.asList(new DoubleString("[]",DataManager.getName(sender.getName())),new DoubleString("[]",DataManager.getName(args[0])),new DoubleString("[]",b.toString()))); super.m.sendMessage(sender, "ӼӸ",Arrays.asList(new DoubleString("[]",DataManager.getName(sender.getName())),new DoubleString("[]",DataManager.getName(args[0])),new DoubleString("[]",b.toString()))); }else{ StringBuilder b = new StringBuilder(args[1]); for(int i = 2;i < args.length;i++) b.append(" " + args[i]); super.m.sendMessage(Bukkit.getPlayer(args[0]), "ӼӸ",Arrays.asList(new DoubleString("[]","ܼ"),new DoubleString("[]",DataManager.getName(args[0])),new DoubleString("[]",b.toString()))); super.m.sendMessage(sender, "ӼӸ",Arrays.asList(new DoubleString("[]","ܼ"),new DoubleString("[]",DataManager.getName(args[0])),new DoubleString("[]",b.toString()))); } } } }else super.m.sendMessage(sender, "ɾ "); return false; } }
true
24b28e488f5fd80de8d84443a30bd9c886d1f0c7
Java
1203992808/leetcode
/src/main/java/Coin_Charge.java
UTF-8
923
3.125
3
[]
no_license
/** * @author syz * @date 2018-12-13 22:10 */ /** * leetcode 322 * 现存在一堆面值为 1,2,5,11,20,50 面值的硬币,问最少需要多少个硬币才能找出总值为 N个单位的零钱 * * */ public class Coin_Charge { public static int f1(int[] arr ,int target) { int[] dp = new int[target +1]; int max = Integer.MAX_VALUE; int min = Integer.MIN_VALUE; for (int i = 0; i <=target; i++) { dp[i] = max; } dp[0] = 0; for (int i = 1; i <= target; i++) { for (int j = 0; j <arr.length ; j++) { if (i - arr[j]>= 0 && dp[i - arr[j]] != max) { dp[i] = Math.min(dp[i],1+ dp[i - arr[j]]); } } } return dp[target]; } public static void main(String[] args) { int[] arr = {1,2,5,7,10}; System.out.println(f1(arr,12)); } }
true
f9d373c725d9c4e066c319635879dac8f3fabb36
Java
KhaledAKassem/V2HiMamyDad
/app/src/main/java/medic/esy/es/mamyapp/Activites/staff/Signupforstaff.java
UTF-8
2,788
2.21875
2
[]
no_license
package medic.esy.es.mamyapp.Activites.staff; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.EditText; import android.widget.Toast; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.FirebaseDatabase; import medic.esy.es.mamyapp.Activites.model.staff; import medic.esy.es.mamyapp.R; public class Signupforstaff extends AppCompatActivity { private EditText one,two,three,four,five,six,seven; private FirebaseAuth auth; private FirebaseDatabase db; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_signupforstaff); one=(EditText)findViewById(R.id.editText); two=(EditText)findViewById(R.id.editText2); three=(EditText)findViewById(R.id.editText3); four=(EditText)findViewById(R.id.editText4); five=(EditText)findViewById(R.id.editText5); six=(EditText)findViewById(R.id.editText6); seven=(EditText)findViewById(R.id.editText7); auth=FirebaseAuth.getInstance(); ///////////////////////////////////////////////////////////////// } public void signupforstaff(View view) { String email=five.getText().toString().trim(); String password=seven.getText().toString().trim(); ////////////////////////////////////////////////// final String staffname=one.getText().toString().trim(); final String gender=two.getText().toString().trim(); final String homePhone=three.getText().toString().trim(); final String workphone=four.getText().toString().trim(); final String address=six.getText().toString().trim(); auth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if(task.isSuccessful()){ ////Hint that cell phone must be upgrade staff staff = new staff( staffname,gender,homePhone,workphone,address,address ); FirebaseDatabase.getInstance().getReference("staff").child(FirebaseAuth.getInstance().getCurrentUser().getUid()).setValue(staff); Toast.makeText(Signupforstaff.this, "Staff add Successfully", Toast.LENGTH_SHORT).show(); }else{ Toast.makeText(Signupforstaff.this, "Faild !!", Toast.LENGTH_SHORT).show(); } } }); } }
true
1eca0bbed3cec90ce2167a846e58bb7438744788
Java
sukharebskaya/HomeWork
/Homework/src/InheritanceHomeWork/GroundTransport.java
UTF-8
4,306
3.203125
3
[]
no_license
package InheritanceHomeWork; import java.util.Objects; public abstract class GroundTransport extends Transport{ private int wheelNum; private double fuelConsRate; //litre/100 km public int getWheelNum() { return wheelNum; } public void setWheelNum(int wheelNum) { this.wheelNum = wheelNum; } public double getFuelConsRate() { return fuelConsRate; } public void setFuelConsRate(double fuelConsRate) { this.fuelConsRate = fuelConsRate; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (!super.equals(o)) return false; GroundTransport that = (GroundTransport) o; return wheelNum == that.wheelNum && Double.compare(that.fuelConsRate, fuelConsRate) == 0; } @Override public int hashCode() { return Objects.hash(super.hashCode(), wheelNum, fuelConsRate); } @Override public String toString() { return " wheels Number =" + wheelNum + ", fuel Consumption Rate=" + fuelConsRate + super.toString(); } } class Car extends GroundTransport{ private String bodyType; private int passengerNum; private int time; public String getBodyType() { return bodyType; } public void setBodyType(String bodyType) { this.bodyType = bodyType; } public int getPassengerNum() { return passengerNum; } public void setPassengerNum(int passengerNum) { this.passengerNum = passengerNum; } public int getTime() { return time; } public void setTime(int time) { this.time = time; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (!super.equals(o)) return false; Car car = (Car) o; return passengerNum == car.passengerNum && Objects.equals(bodyType, car.bodyType); } @Override public int hashCode() { return Objects.hash(super.hashCode(), bodyType, passengerNum); } @Override public double capacityCountKLWatt() { double result = getCapacityHP()*0.74; return result; } public void rangeOnMaxSpeed(int time){ int range = getMaxSpeed()*time; double fuelAmount = fuelAmountCount(range); System.out.println("За время "+getTime()+" часа(-ов), автомобиль "+this.getBrand()+", двигаясь с максимальной скоростью "+this.getMaxSpeed()+" км/ч, проедет " +range+" км. и израсходует "+this.fuelAmountCount(range)+" литра(-ов) топлива"); } private double fuelAmountCount(int range){ double amount = range*this.getFuelConsRate()/100; return amount; } @Override public String toString() { return "body Type = " + bodyType + ", passenger Number = " + passengerNum + super.toString(); } } class Cargo extends GroundTransport{ private int loadCapacity; //tonne public int getLoadCapacity() { return loadCapacity; } public void setLoadCapacity(int loadCapacity) { this.loadCapacity = loadCapacity; } public void checkLoadCapacity(int loadWeight){ if(loadWeight>this.loadCapacity) System.out.println("Вам нужен грузовик побольше"); else System.out.println("Грузовик загружен"); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (!super.equals(o)) return false; Cargo cargo = (Cargo) o; return loadCapacity == cargo.loadCapacity; } @Override public int hashCode() { return Objects.hash(super.hashCode(), loadCapacity); } @Override public String toString() { return "load capacity = " + loadCapacity + super.toString(); } @Override public double capacityCountKLWatt() { double result = getCapacityHP()*0.74; return result; } }
true