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
f38208b88fde66f5dda5959e73aee9ebcb2747b6
Java
ulno/SAStudyRightByHand
/src/test/java/net/ulno/sr/UniversityTest1.java
UTF-8
1,532
2.71875
3
[]
no_license
package net.ulno.sr; import org.junit.Test; import static org.junit.Assert.*; /** * Created by ulno on 2/16/17. */ public class UniversityTest1 { University uni; Student karli; Course mathCourse, calculusCourse; LectureHall mathLectureHall, calcLectureHall; @Test public void testKarliInUniversity() throws Exception { University u = new University(); Student karli = new Student(); karli.setName("Karli"); u.addStudent(karli); assertTrue(u.getStudents().contains(karli)); } private void preCondition(){ uni = new University(); karli = new Student(); mathCourse = new Course(); calculusCourse = new Course(); mathLectureHall = new LectureHall(); calcLectureHall = new LectureHall(); uni.addStudent(karli.withName("Karli")); mathLectureHall.setCourse(mathCourse); // could use with for mathCourse calcLectureHall.setCourse(calculusCourse); } @Test public void karliEntersFirstClassMovesOnToSecond(){ preCondition(); mathCourse.addStudent(karli); calculusCourse.addStudent(karli); // math doesn't contain karli assertTrue("karli should have left math lecture hall", !mathLectureHall.getCourse().getStudents().contains(karli)); //calc contains karli assertTrue("karli should have joined calc lecture hall", calcLectureHall.getCourse().getStudents().contains(karli)); } }
true
4afa02b09678b160eae5795ebbd08c2894115466
Java
Yotamsh2/SecureVault2019
/app/src/main/java/local_database/dao/DaoUser.java
UTF-8
1,030
2.171875
2
[]
no_license
package local_database.dao; import androidx.lifecycle.LiveData; import androidx.room.Dao; import androidx.room.Insert; import androidx.room.Query; import androidx.room.Update; import com.securevault19.securevault2019.user.User; import java.util.List; @Dao public interface DaoUser { @Insert void insert(User user); @Update void update(User user); @Query("SELECT * FROM user_table ORDER BY first_name DESC") LiveData<List<User>> getAllUsers(); // check if LogIn is ok @Query("SELECT * FROM user_table WHERE email = :email AND master_Password = :masterPassword") User LogInConfirmation(String email,String masterPassword); // getting the userName name for check if one all ready exists. @Query("SELECT email from user_table WHERE email = :email") String CheckForUserName(String email); // updating User Details @Query("UPDATE user_table SET secureLevel = :newSecureLevel WHERE email = :email") void updateSecureLevel(String newSecureLevel, String email); }
true
5d4d728aa0c1fe4304387f8d5651d8a0c07c83a2
Java
szySunzhouyu/java
/方剂查询系统/cmfSystem/src/cn/edu/hbtcm/pre/dao/AdminDao.java
GB18030
455
2.109375
2
[]
no_license
package cn.edu.hbtcm.pre.dao; import org.bson.types.ObjectId; import cn.edu.hbtcm.pre.common.dao.BaseDao; import cn.edu.hbtcm.pre.domain.Admin; import com.google.code.morphia.dao.DAO; public interface AdminDao extends BaseDao<Admin, ObjectId>{ //ӹԱɹ1ʧܷ0 public int addAdmin(Admin admin); //ֲҹԱ public Admin findByName(String username); public Admin findByNameAndPass(Admin user); }
true
85302a9740fadd5081c5f7c4f9b665129da32ca2
Java
albrtstr/kingdomAnimalia
/app/src/main/java/com/example/kingdomanimalia/hal31_regenerasi_dugesia.java
UTF-8
4,327
2.046875
2
[]
no_license
package com.example.kingdomanimalia; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.media.MediaPlayer; import android.os.Bundle; import android.view.MotionEvent; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.ImageView; import android.widget.Toast; import com.example.kingdomanimalia.h_platyhelminthes.hal25_filum_platyhelminthes; import com.example.kingdomanimalia.h_platyhelminthes.hal27_kelas_platyhelminthes; import com.example.kingdomanimalia.h_platyhelminthes.hal29_kelas_platyhelminthes_2_trematoda; import com.example.kingdomanimalia.h_platyhelminthes.hal30_kelas_platyhelminthes_3_cestoda; import com.example.kingdomanimalia.h_platyhelminthes.hal33_daurfasciola_2; public class hal31_regenerasi_dugesia extends AppCompatActivity { float x1,x2,y1,y2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_hal31_regenerasi_dugesia); ImageView home = findViewById(R.id.btnhome); ImageView back = findViewById(R.id.btnback); home.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { MediaPlayer mp = MediaPlayer.create(hal31_regenerasi_dugesia.this,R.raw.klik); mp.start(); startActivity(new Intent(hal31_regenerasi_dugesia.this, hal4_menu_screen.class)); finish(); } }); back.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { MediaPlayer mp = MediaPlayer.create(hal31_regenerasi_dugesia.this,R.raw.klik); mp.start(); startActivity(new Intent(hal31_regenerasi_dugesia.this, hal7_menu_jelajah_filum.class)); finish(); } }); //animasi Animation knifeAnimasi = AnimationUtils.loadAnimation(this,R.anim.knife); //animasi pisau ImageView knife1 = findViewById(R.id.knife1); ImageView knife2 = findViewById(R.id.knife2); knife1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { MediaPlayer mp = MediaPlayer.create(hal31_regenerasi_dugesia.this,R.raw.klik); mp.start(); knife1.startAnimation(knifeAnimasi); Toast.makeText(hal31_regenerasi_dugesia.this, "Jika kepala dipotong, kepalanya akan bertambah 1", Toast.LENGTH_SHORT).show(); } }); knife2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { MediaPlayer mp = MediaPlayer.create(hal31_regenerasi_dugesia.this,R.raw.klik); mp.start(); knife2.startAnimation(knifeAnimasi); Toast.makeText(hal31_regenerasi_dugesia.this, "Jika tubuh dipotong akan membuat tumbuh kepala di bagian bawah", Toast.LENGTH_SHORT).show(); } }); } public boolean onTouchEvent(MotionEvent touchEvent) { switch(touchEvent.getAction()){ case MotionEvent.ACTION_DOWN: x1 = touchEvent.getX(); y1 = touchEvent.getY(); break; case MotionEvent.ACTION_UP: x2 = touchEvent.getX(); y2 = touchEvent.getY(); if(x1 > x2){ MediaPlayer mp = MediaPlayer.create(hal31_regenerasi_dugesia.this,R.raw.sipe); mp.start(); Intent i = new Intent(hal31_regenerasi_dugesia.this, hal32_daur_fasciola.class); startActivity(i); finish(); } else if(x1 < x2){ MediaPlayer mp = MediaPlayer.create(hal31_regenerasi_dugesia.this,R.raw.sipe); mp.start(); Intent i = new Intent(hal31_regenerasi_dugesia.this, hal27_kelas_platyhelminthes.class); startActivity(i); finish(); } break; } return false; } }
true
201d79bafe22ae5516873f503d6a52b75aef255b
Java
hwjworld/FZWFramework
/src/test/Test.java
UTF-8
8,789
2.09375
2
[]
no_license
package test; import java.lang.reflect.Type; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import net.sf.ehcache.CacheManager; import org.apache.commons.collections.ListUtils; import org.apache.commons.collections.comparators.ComparatorChain; import org.apache.commons.configuration.ConfigurationException; import org.apache.commons.configuration.HierarchicalConfiguration; import org.apache.commons.configuration.XMLConfiguration; import org.apache.commons.lang.ArrayUtils; import com.fzw.utils.LogUtils; import com.google.gson.ExclusionStrategy; import com.google.gson.FieldAttributes; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonArray; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonPrimitive; import com.legaldaily.estension.ecard.model.law.LawCategory; public class Test { // enum day{ // sun,mon // } // static{ // // try { // XMLConfiguration xmlConfiguration = new XMLConfiguration("extensions.xml"); // List extensionList = xmlConfiguration.configurationsAt("extension"); // for (Object object : extensionList) { // HierarchicalConfiguration extension = (HierarchicalConfiguration) object; // String name = extension.getString("name"); // String init = extension.getString("init"); // System.out.println(name+" "+init); // } // } catch (ConfigurationException e) { // LogUtils.error("no ecommands.xml found"); // System.exit(0); // } // // } public static void main(String[] args) { // System.out.println(day.mon.name()); // // System.out.println(ArrayUtils.contains(new String[]{"wait","publish","a"}, null)); // CacheManager manager1 = new CacheManager(); // CacheManager manager2 = new CacheManager(); // manager1.addCache("abc"); // manager2.getCache("abc"); // System.out.println(manager1.getCache("abc")); // System.out.println(manager2.getCache("abc")); // String // aString="0101101010001010110101011001101011010100010101101010110011010110101000101011010101100110101110110101010101010101011111111000111111"; // String // bString="1101101010001010110101011001101011010100010101101010110011010110101000101011010101100110101110110101010101010101011111111000111110"; // BigInt bigInt = new BigInt(1); // bigInt. // byte [] b = bString.getBytes(); // System.out.println(Integer.valueOf(""+'1', 2) // &Integer.valueOf(""+'1', 2)); // for (int i = 0; i < b.length; i++) { // System.out.print(a[i] & b[i]); // } //------------------------------- // Gson gson = new GsonBuilder().registerTypeAdapter(Object.class, // new NaturalDeserializer()).create(); // try { // // Map map = gson.fromJson( // FileUtils.readFileToString(new File("/tmp/11.txt")), // HashMap.class); // System.out.println(map.keySet().iterator().next()); // } catch (JsonSyntaxException e) { // e.printStackTrace(); // } catch (IOException e) { // e.printStackTrace(); // } //------------------------------- // List<String> strings = new ArrayList<String>(); // strings.add("5"); // strings.add("12"); // strings.add("88"); // strings.add("44"); // strings.add("3355"); // strings.add("5"); //// Object object = Collections.max(strings, Comparators.STRING_COMPARATOR_DESC_INTEGER); //// System.out.println(object); // System.out.println(strings.size()); // com.fzw.utils.ListUtils.subList(strings, 0, 2); // System.out.println(strings.size()); // int id[] = new int[]{1,3,5,76,2}; // id = ArrayUtils.removeElement(id, 1); // System.out.println(StringUtils.join(ArrayUtils.toObject(id),",")); // Calendar calendar = Calendar.getInstance(); // System.out.println(calendar.getTime()); // calendar.set(Calendar.DAY_OF_MONTH, calendar.get(Calendar.DAY_OF_MONTH)-1); // System.out.println(calendar.getTime()); LawCategory lawCategory = new LawCategory(); System.out.println( lawCategory.getCatId()); } private static <T> T[] GetLongAction(List<T> list) { T t = null; Object[] object = list.toArray(); Object[] oo = new Object[list.size()]; for (int i = 0; i < object.length; i++) { oo[i] = (T) object[i]; } return (T[]) oo; } public static void mianTest() { new ArrayList<String>().addAll(null); ListUtils.union(new ArrayList<String>(), new ArrayList<String>()); System.out.println(new Date(0)); Gson gson = new GsonBuilder().addSerializationExclusionStrategy( new ExclusionStrategy() { @Override public boolean shouldSkipField(FieldAttributes f) { // System.out.println("field--"+f.getDeclaredClass().getName()); System.out.println(f.getName() + "--" + f.getDeclaringClass().getName()); // if(f.getDeclaredClass().getName().equals("test.B")) // return true; return false; } @Override public boolean shouldSkipClass(Class<?> clazz) { // if(clazz.getSimpleName().equals("B")) // //System.out.println("clazz--"+clazz.getSimpleName()); // return true; return false; } }).create(); A a = new A(); a.t = "a"; B b = new B(); b.tt = "b"; a.b = b; // b.a = a; System.out.println(gson.toJson(a)); ComparatorChain cc = new ComparatorChain(); cc.addComparator(new Comparator<Ct>() { @Override public int compare(Ct o1, Ct o2) { if (o1.getA() > o2.getA()) { return -1; } else if (o1.getA() == o2.getA()) { return 0; } else { return 1; } } }); cc.addComparator(new Comparator<Ct>() { @Override public int compare(Ct o1, Ct o2) { if (o1.getB() > o2.getB()) { return -1; } else if (o1.getB() == o2.getB()) { return 0; } else { return 1; } } }); Ct ct1 = new Ct(); ct1.setA(1); ct1.setB(5); Ct ct2 = new Ct(); ct2.setA(1); ct2.setB(3); Ct ct3 = new Ct(); ct3.setA(2); ct3.setB(4); Ct[] cccCts = new Ct[] { ct1, ct2, ct3 }; Arrays.sort(cccCts, cc); for (Ct string : cccCts) { System.out.println(string); } } } class A { String t; B b; public String getT() { return t; } public void setT(String t) { this.t = t; } public B getA() { return b; } public void setA(B a) { this.b = a; } } class B { String tt; A a; public String getTt() { return tt; } public void setTt(String tt) { this.tt = tt; } public A getA() { return a; } public void setA(A a) { this.a = a; } } class Ct { int a, b; public int getA() { return a; } public void setA(int a) { this.a = a; } public int getB() { return b; } public void setB(int b) { this.b = b; } @Override public String toString() { return a + "--" + b; } } abstract class C { protected static Object object = null; protected void doo() { System.out.println("cccc"); } } class D extends C { private int sid; @Override protected void doo() { System.out.println("ddd"); super.doo(); } public int getSid() { return sid; } public void setSid(int sid) { this.sid = sid; } } class NaturalDeserializer implements JsonDeserializer<Object> { public Object deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) { if (json.isJsonNull()) return null; else if (json.isJsonPrimitive()) return handlePrimitive(json.getAsJsonPrimitive()); else if (json.isJsonArray()) return handleArray(json.getAsJsonArray(), context); else return handleObject(json.getAsJsonObject(), context); } private Object handlePrimitive(JsonPrimitive json) { if (json.isBoolean()) return json.getAsBoolean(); else if (json.isString()) return json.getAsString(); else { BigDecimal bigDec = json.getAsBigDecimal(); // Find out if it is an int type try { bigDec.toBigIntegerExact(); try { return bigDec.intValueExact(); } catch (ArithmeticException e) { } return bigDec.longValue(); } catch (ArithmeticException e) { } // Just return it as a double return bigDec.doubleValue(); } } private Object handleArray(JsonArray json, JsonDeserializationContext context) { Object[] array = new Object[json.size()]; for (int i = 0; i < array.length; i++) array[i] = context.deserialize(json.get(i), Object.class); return array; } private Object handleObject(JsonObject json, JsonDeserializationContext context) { Map<String, Object> map = new HashMap<String, Object>(); for (Map.Entry<String, JsonElement> entry : json.entrySet()) map.put(entry.getKey(), context.deserialize(entry.getValue(), Object.class)); return map; } }
true
7ffe5c65da37e29eab4f4f4db402b07da2522feb
Java
Thata93/YooFormatter
/src/yoo/app/models/Block.java
UTF-8
145
1.835938
2
[]
no_license
package yoo.app.models; /** {@code Block} é um bloco (espaço) dentro do 'corpo' do tópico contendo informações. */ public interface Block{}
true
31014af4c3a9d8d8a480dc9a7334ff6db13b1a97
Java
trishagee/RefactoringDemo
/src/com/jetbrains/DemoLocalHistory.java
UTF-8
968
3
3
[]
no_license
package com.jetbrains; import java.text.SimpleDateFormat; import java.util.*; public class DemoLocalHistory { private final Map<Integer, List<String>> integerStringMap = new HashMap<>(); { integerStringMap.put(12, List.of("Sun", "Mon", "Tue")); } String getFormattedDate(Date date) { SimpleDateFormat formatter = new SimpleDateFormat("YYYY-MM-dd"); return formatter.format(date); } List<Object> createList() { List<Object> list = new ArrayList<>(); list.add("Hello"); list.add(list); return list; } public static boolean binaryStrings(String b) { Stack s = new Stack(); for (char c : b.toCharArray()) if (s.empty() || !s.peek().equals(c)) s.push(c); else s.pop(); return s.empty(); } public static boolean beautifulBinaryStrings(String s) { while (s != (s = s.replaceAll("AA|BB", ""))); return s.isEmpty(); } }
true
a9bbd99a76e1f298a238f263fa6e35668710e0f7
Java
basilevs/RED
/src/RobotFrameworkCore/org.robotframework.ide.core-functions/src/main/java/org/rf/ide/core/testdata/text/write/tables/settings/ResourceImportDumper.java
UTF-8
2,049
1.9375
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2016 Nokia Solutions and Networks * Licensed under the Apache License, Version 2.0, * see license.txt file for details. */ package org.rf.ide.core.testdata.text.write.tables.settings; import java.util.ArrayList; import java.util.List; import org.rf.ide.core.testdata.model.AModelElement; import org.rf.ide.core.testdata.model.ModelType; import org.rf.ide.core.testdata.model.table.RobotElementsComparatorWithPositionChangedPresave; import org.rf.ide.core.testdata.model.table.SettingTable; import org.rf.ide.core.testdata.model.table.setting.ResourceImport; import org.rf.ide.core.testdata.text.read.recognizer.RobotToken; import org.rf.ide.core.testdata.text.read.recognizer.RobotTokenType; import org.rf.ide.core.testdata.text.write.DumperHelper; import org.rf.ide.core.testdata.text.write.tables.ANotExecutableTableElementDumper; public class ResourceImportDumper extends ANotExecutableTableElementDumper<SettingTable> { public ResourceImportDumper(final DumperHelper helper) { super(helper, ModelType.RESOURCE_IMPORT_SETTING); } @Override public RobotElementsComparatorWithPositionChangedPresave getSorter( final AModelElement<SettingTable> currentElement) { final ResourceImport resource = (ResourceImport) currentElement; final List<RobotToken> resourcePaths = new ArrayList<>(0); if (resource.getPathOrName() != null) { resourcePaths.add(resource.getPathOrName()); } final RobotElementsComparatorWithPositionChangedPresave sorter = new RobotElementsComparatorWithPositionChangedPresave(); sorter.addPresaveSequenceForType(RobotTokenType.SETTING_RESOURCE_FILE_NAME, 1, resourcePaths); sorter.addPresaveSequenceForType(RobotTokenType.SETTING_RESOURCE_UNWANTED_ARGUMENT, 2, resource.getUnexpectedTrashArguments()); sorter.addPresaveSequenceForType(RobotTokenType.COMMENT, 3, elemUtility.filter(resource.getComment(), RobotTokenType.COMMENT)); return sorter; } }
true
1b26fb8c9a437ca755fcd32c049eb4bc58f34cfa
Java
kunalkalbande/SQLcompliance
/development/Web UI/sqlcm/src/main/java/com/idera/sqlcm/wizard/WizardStepManagerImport.java
UTF-8
5,438
2.40625
2
[]
no_license
/***Start SQLCm 5.4***/ /*Requirement 4.1.4.1*/ package com.idera.sqlcm.wizard; import org.apache.log4j.Logger; import org.zkoss.zk.ui.Component; import org.zkoss.zk.ui.Executions; import org.zkoss.zul.Panelchildren; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.NoSuchElementException; public class WizardStepManagerImport { private static final Logger logger = Logger.getLogger(WizardStepManagerImport.class); public static final String STEP_VM_ID = "step_vm"; private ImportWizardViewModel mParentWizardViewModel; private LinkedList<IStepImport> mStepsStack; // used to handle back button. private HashMap<String, IStepImport> mRegisteredSteps; private List<String> mZulStepList = new ArrayList<>(10); WizardStepManagerImport(ImportWizardViewModel parentWizardViewModel) { if (parentWizardViewModel == null) { throw new IllegalArgumentException(" Parent parentWizardViewModel must not be null "); } mParentWizardViewModel = parentWizardViewModel; mRegisteredSteps = new HashMap<>(initialStepCapacity()); mStepsStack = new LinkedList<>(); } protected int initialStepCapacity() { return 10; } public WizardStepManagerImport registerStep(String zulPath) { if (zulPath == null) { logger.info(" zulPath is null "); return this; } mZulStepList.add(zulPath); return this; } void initSteps(Panelchildren mainPanelChildren) { Component stepRootComponent; for (String zulPath: mZulStepList) { stepRootComponent = Executions.createComponents(zulPath, mainPanelChildren, null); Object viewModelStepObj = stepRootComponent.getAttribute(STEP_VM_ID); if (viewModelStepObj == null) { throw new RuntimeException( String.format(" Root component of wizard step file '%s' must contain viewModel with id '%s' ", zulPath, STEP_VM_ID)); } IStepImport stepViewModel; try { stepViewModel = (IStepImport) viewModelStepObj; } catch (ClassCastException e) { throw new RuntimeException( String.format(" Step viewModel class in '%s' must be heir of '%s' ", zulPath, IStepImport.class.getName())); } stepViewModel.init(mParentWizardViewModel, stepRootComponent); mRegisteredSteps.put(zulPath, stepViewModel); // add step to stack if it first if (stepViewModel.isFirst()) { if (mStepsStack.size() == 0) { mStepsStack.addFirst(stepViewModel); } else { throw new RuntimeException(" Must be only one first step! "); } stepRootComponent.setVisible(true); } else { stepRootComponent.setVisible(false); } } if(mStepsStack.size() == 0) { throw new RuntimeException(" First step does not exist! "); } } IStepImport getFirst() { return mStepsStack.peekFirst(); } IStepImport next(boolean removeCurrentStepFromStack) { // get current step. must not be null. IStepImport currentStep = mStepsStack.peekFirst(); String nextStepZul = currentStep.getNextStepZul(); if (nextStepZul != null) { if (removeCurrentStepFromStack) { mStepsStack.removeFirst(); } // visibility = false for current step component currentStep.setVisible(false); // get next step class if not null. IF null return // add new step to stack. visibility = true IStepImport stepToDisplay = mRegisteredSteps.get(nextStepZul); if (stepToDisplay == null) { throw new RuntimeException(String.format(" Step Zul with path %s is not registered ", nextStepZul)); } stepToDisplay.setVisible(true); mStepsStack.addFirst(stepToDisplay); return stepToDisplay; } return null; } IStepImport next() { return next(false); } IStepImport prev() { // get current step. must not be null. if (mStepsStack.size() > 1) { // do mStepsStack.poll() to get current and remove from stack. IStepImport currentStep = mStepsStack.poll(); // set component visibility = false of polled step currentStep.setVisible(false); // do peek first to get component. set visibility to true. IStepImport stepToDisplay = mStepsStack.peekFirst(); stepToDisplay.setVisible(true); return stepToDisplay; } return null; } IStepImport getCurrentStep() { return mStepsStack.peekFirst(); } IStepImport getStepOrException(Class<? extends IStepImport> stepClass) throws NoSuchElementException { IStepImport result = mRegisteredSteps.get(stepClass); if (result == null) { throw new NoSuchElementException(String.format(" Step with class name '%s' not found ", stepClass.getName())); } return result; } } /***End SQLCm 5.4***/
true
e275de85d41bf2b22bb51bd5a745c53690ec2424
Java
skydh/algorithm-learn
/src/com/dh/lettcode5/LastStoneWeightII.java
UTF-8
1,892
3.90625
4
[]
no_license
package com.dh.lettcode5; /** * 有一堆石头,每块石头的重量都是正整数。 * * 每一回合,从中选出任意两块石头,然后将它们一起粉碎。假设石头的重量分别为 x 和 y,且 x <= y。那么粉碎的可能结果如下: * * 如果 x == y,那么两块石头都会被完全粉碎; 如果 x != y,那么重量为 x 的石头将会完全粉碎,而重量为 y 的石头新重量为 y-x。 * 最后,最多只会剩下一块石头。返回此石头最小的可能重量。如果没有石头剩下,就返回 0。 * * 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/last-stone-weight-ii * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 * * @author Lenovo * */ public class LastStoneWeightII { /** * 很简单,先求和,除二,然后找出最接近这个值的组合,然后用剩余的减去这个值即可 * * @param stones * @return */ public int lastStoneWeightII(int[] stones) { int sum = 0; for (int i = 0; i < stones.length; i++) { sum = sum + stones[i]; } int ave = sum / 2; boolean[][] dp = new boolean[stones.length][ave + 1]; if (stones[0] <= ave) dp[0][stones[0]] = true; dp[0][0] = true; for (int i = 1; i < stones.length; i++) { for (int j = 0; j <= ave; j++) { if (dp[i - 1][j]) { dp[i][j] = true; if (j <= ave - stones[i]) dp[i][j + stones[i]] = true; } } } int min = dp[0].length - 1; for (; min >= 0; min--) { if (dp[stones.length - 1][min]) break; } return sum - min * 2; } public static void main(String[] args) { LastStoneWeightII s = new LastStoneWeightII(); int[] data = { 31, 26, 33, 21, 40 }; System.out.println(s.lastStoneWeightII(data)); } }
true
bd58c00cb0e68776b45d20fc63e20abc1c4e1469
Java
wizardly1985/lfire
/src/main/src/com/lfire/host/service/DeptService.java
UTF-8
162
1.640625
2
[]
no_license
package com.lfire.host.service; import java.util.List; import com.lfire.host.entity.demo.Dept; public interface DeptService { public List<Dept> findAll(); }
true
e2ad21beadd9395ea7d12a1d266a5765c83e3014
Java
katchi7/userService
/src/main/java/ma/tna/ebanking/userservice/dtos/T24ProfileDto.java
UTF-8
551
2.0625
2
[]
no_license
package ma.tna.ebanking.userservice.dtos; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import ma.tna.ebanking.userservice.model.Profile; @Data @AllArgsConstructor @NoArgsConstructor public class T24ProfileDto { private String id; private String name; private String adresse; private String pays; private String ville; private String postCode; private String sector; public Profile asProfile(){ return new Profile(id,name,adresse,pays,ville,postCode,sector); } }
true
149907f62479db4a3fbfede4c47c71b984d27520
Java
agricultureY/wechat-develop
/wechat-develop/src/main/java/com/ycn/wechat/baidufanyi/TransApi.java
UTF-8
2,102
2.515625
3
[]
no_license
package com.ycn.wechat.baidufanyi; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.ycn.wechat.util.MD5; import java.util.HashMap; import java.util.List; import java.util.Map; /** * 百度翻译接口 */ public class TransApi { private static final String TRANS_API_HOST = "http://api.fanyi.baidu.com/api/trans/vip/translate"; private static final String APP_ID = "Your baidu fanyi appid"; private static final String SECURITY_KEY = "Your baidu fanyi app security"; //翻译源自动识别 private static final String FROM = "auto"; //翻译结果语言 自动识别 private static final String TO ="auto"; /** * 获取翻译结果 * @param query * @return */ public static String getTransResult(String query) { Map<String, String> params = buildParams(query); String resultMap = HttpGet.get(TRANS_API_HOST, params); JSONObject json = JSON.parseObject(resultMap); StringBuffer buffer = new StringBuffer(); //保存翻译后的结果 List<Map> list = (List<Map>) json.get("trans_result"); for (int i = 0; i < list.size(); i++) { buffer.append(list.get(i).get("dst")); } return buffer.toString(); } private static Map<String, String> buildParams(String query) { Map<String, String> params = new HashMap<String, String>(); params.put("q", query); params.put("from", FROM); params.put("to", TO); params.put("appid", APP_ID); // 随机数 String salt = String.valueOf(System.currentTimeMillis()); params.put("salt", salt); // 签名 String src = APP_ID + query + salt + SECURITY_KEY; // 加密前的原文 params.put("sign", MD5.md5(src)); return params; } public static void main(String[] args) { String query = "苹果手机"; String query1 = "Hello world"; System.out.println(TransApi.getTransResult(query)); System.out.println(TransApi.getTransResult(query1)); } }
true
f1990812d57799657f08b3cc8dfb7dea31b2e099
Java
mayankkumar0078/UserService
/src/main/java/com/userservice/crypto/service/KeystoreServiceImpl.java
UTF-8
799
2.03125
2
[]
no_license
package com.userservice.crypto.service; import java.security.PrivateKey; import java.security.PublicKey; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.userservice.config.crypto.CryptoProperties; import com.userservice.crypto.interfaces.KeystoreService; @Service("keystoreService") public class KeystoreServiceImpl implements InitializingBean, KeystoreService { @Autowired private CryptoProperties cryptoProperties; private PrivateKey privateKey; private PublicKey publicKey; public void afterPropertiesSet() throws Exception { } public PrivateKey getPrivateKey() { return privateKey; } public PublicKey getPublicKey() { return publicKey; } }
true
0b354f275f83b8dc3b76b3612fb43cd3cbdfe247
Java
calvlinzx/Dungeon
/src/unsw/dungeon/DungeonLoader.java
UTF-8
7,816
2.828125
3
[]
no_license
package unsw.dungeon; import java.io.FileNotFoundException; import java.io.FileReader; import org.json.JSONArray; import org.json.JSONObject; import org.json.JSONTokener; /** * Loads a dungeon from a .json file. * * By extending this class, a subclass can hook into entity creation. This is * useful for creating UI elements with corresponding entities. * * @author Robert Clifton-Everest * */ public abstract class DungeonLoader { private JSONObject json; public DungeonLoader(String filename) throws FileNotFoundException { json = new JSONObject(new JSONTokener(new FileReader("dungeons/" + filename))); } /** * Parses the JSON to create a dungeon. * @return */ public Dungeon load() { int width = json.getInt("width"); int height = json.getInt("height"); Dungeon dungeon = new Dungeon(width, height); JSONArray jsonEntities = json.getJSONArray("entities"); for (int i = 0; i < jsonEntities.length(); i++) { loadEntity(dungeon, jsonEntities.getJSONObject(i)); } JSONObject goals = json.getJSONObject("goal-condition"); dungeon.addGoal(setUpGoals(dungeon, goals)); return dungeon; } private GoalComponent setUpGoals(Dungeon dungeon, JSONObject json) { String firstLine = json.getString("goal"); GoalComposite finalGoal = new GoalComposite("main goal", dungeon); if (! firstLine.equals("AND") && !firstLine.equals("OR")) { finalGoal.add(makeLeaf(firstLine, dungeon)); }else { if (firstLine.equals("AND")) { JSONArray subgoals = json.getJSONArray("subgoals"); finalGoal.add(makeAndGoal(dungeon, subgoals)); }else if (firstLine.equals("OR")) { JSONArray subgoals = json.getJSONArray("subgoals"); finalGoal.add(makeOrGoal(dungeon, subgoals)); } } return finalGoal; } private GoalComposite makeAndGoal(Dungeon dungeon, JSONArray subgoals) { GoalComposite subcomposite = new GoalComposite("and", dungeon); for (int i = 0; i < subgoals.length(); i++) { JSONObject goal = subgoals.getJSONObject(i); String firstLine = goal.getString("goal"); if (!firstLine.equals("AND") && !firstLine.equals("OR")) { subcomposite.add(makeLeaf(firstLine, dungeon)); }else { if (firstLine.equals("AND")) { JSONArray andsubs = goal.getJSONArray("subgoals"); subcomposite.add(makeAndGoal(dungeon, andsubs)); }else if (firstLine.equals("OR")) { JSONArray orsubs = goal.getJSONArray("subgoals"); subcomposite.add(makeOrGoal(dungeon, orsubs)); } } } return subcomposite; } private GoalComposite makeOrGoal(Dungeon dungeon, JSONArray subgoals) { GoalComposite subcomposite = new GoalComposite("or", dungeon); for (int i = 0; i < subgoals.length(); i++) { JSONObject goal = subgoals.getJSONObject(i); String firstLine = goal.getString("goal"); if (!firstLine.equals("AND") && !firstLine.equals("OR")) { subcomposite.add(makeLeaf(firstLine, dungeon)); }else { if (firstLine.equals("AND")) { JSONArray andsubs = goal.getJSONArray("subgoals"); subcomposite.add(makeAndGoal(dungeon, andsubs)); }else if (firstLine.equals("OR")) { JSONArray orsubs = goal.getJSONArray("subgoals"); subcomposite.add(makeOrGoal(dungeon, orsubs)); } } } return subcomposite; } private GoalComponent makeLeaf(String goal, Dungeon dungeon) { GoalComponent leaf = null; switch (goal) { case "exit": leaf = createExitGoal(dungeon); break; case "enemies": leaf = createEnemyGoal(dungeon); break; case "boulders": leaf = createBoulderGoal(dungeon); break; case "treasure": leaf = createTreasureGoal(dungeon); break; } return leaf; //return new GoalLeaf(goal, dungeon); } private GoalExit createExitGoal(Dungeon dungeon) { Exit exit = dungeon.getExit(); Player player = dungeon.getPlayer(); GoalExit eg = new GoalExit(player, exit); return eg; } private GoalEnemy createEnemyGoal(Dungeon dungeon) { int count = dungeon.getEnemyCount(); GoalEnemy eg = new GoalEnemy(count); dungeon.setObserverEnemyGoal(eg); return eg; } private GoalBoulder createBoulderGoal(Dungeon dungeon) { //int count = dungeon.getBoulderCount(); GoalBoulder sg = new GoalBoulder(dungeon); //dungeon.setObserverBoulderGoal(sg); return sg; } private GoalTreasure createTreasureGoal(Dungeon dungeon) { int count = dungeon.getTreasureCount(); GoalTreasure tg = new GoalTreasure(count); dungeon.setObserverTreasureGoal(tg); return tg; } private void loadEntity(Dungeon dungeon, JSONObject json) { String type = json.getString("type"); int x = json.getInt("x"); int y = json.getInt("y"); Entity entity = null; switch (type) { case "player": Player player = new Player(dungeon, x, y); dungeon.setPlayer(player); onLoad(player); entity = player; break; case "wall": Wall wall = new Wall(x, y); onLoad(wall); entity = wall; break; // TODO Handle other possible entities case "switch": FloorSwitch floorswitch = new FloorSwitch(x, y); onLoad(floorswitch); entity = floorswitch; break; case "boulder": Boulder boulder = new Boulder(x, y); onLoad(boulder); entity = boulder; break; case "exit": Exit exit = new Exit(x, y); onLoad(exit); entity = exit; break; case "enemy": Enemy enemy = new Enemy(dungeon, x, y); onLoad(enemy); entity = enemy; break; case "key": int keyId = json.getInt("id"); Key key = new Key(x, y, keyId); //int key_id = json.getInt("ID"); onLoad(key); entity = key; break; case "portal": int portalId = json.getInt("id"); Portal portal = new Portal(x, y, portalId); onLoad(portal); entity = portal; break; case "sword": Sword sword = new Sword(x, y); onLoad(sword); entity = sword; break; case "treasure": Treasure treasure = new Treasure(x, y); onLoad(treasure); entity = treasure; break; case "invincibility": Invincibility invincibility = new Invincibility(x, y); onLoad(invincibility); entity = invincibility; break; case "door": int doorId = json.getInt("id"); Door door = new Door(x, y, doorId); //int door_id = json.getInt("ID"); onLoad(door); entity = door; break; } dungeon.addEntity(entity); } public abstract void onLoad(Entity player); public abstract void onLoad(Wall wall); public abstract void onLoad(FloorSwitch floorswitch); public abstract void onLoad(Boulder boulder); public abstract void onLoad(Exit exit); // TODO Create additional abstract methods for the other entities public abstract void onLoad(Enemy enemy); public abstract void onLoad(Key key); public abstract void onLoad(Portal portal); public abstract void onLoad(Sword sword); public abstract void onLoad(Treasure treasure); public abstract void onLoad(Invincibility invincibility); public abstract void onLoad(Door door); }
true
18089ca6baadd0a6f681d61f407f3b898a0e9257
Java
yanghuixin/MyOnetext
/app/src/main/java/com/example/administrator/myonetext/bean/PPaymoneyOrdeDataRes.java
UTF-8
9,584
2.0625
2
[]
no_license
package com.example.administrator.myonetext.bean; import java.util.List; /** * Created by Administrator on 2018/1/3. */ public class PPaymoneyOrdeDataRes { /** * Status : 1 * Msg : [{"orderId":31507,"orderNumber":"ZXB1801030001","orderPirce":420,"orderPayInt":0,"orderState":3,"orderPay":"http://app.tealg.com/wap/NewPayStap1.aspx?order_no=ZXB1801030001","orderReturn":"","ordersMsg":[{"ordersId":35556,"ordersNumber":"ZXS1801030001","ordersState":3,"ordersBusinessId":11363,"ordersBusinessName":"云南张顺翔茶叶","ordersWuLiu":"","orderReturnStatus":"","ordersProducts":[{"productId":43693,"detailsId":53363,"productComment":0,"productName":"贺开山古茶树 普洱生茶 黄片","productPic":"http://img1.tealg.com/Product/Main/220X220/201604/43d4212d-bf7b-47ff-817f-b897ba1642f0.jpg","productPrice":420,"productNumber":1,"ordersCommentAdd":""}]}]}] */ private int Status; private List<MsgBean> Msg; public int getStatus() { return Status; } public void setStatus(int Status) { this.Status = Status; } public List<MsgBean> getMsg() { return Msg; } public void setMsg(List<MsgBean> Msg) { this.Msg = Msg; } public static class MsgBean { /** * orderId : 31507 * orderNumber : ZXB1801030001 * orderPirce : 420.0 * orderPayInt : 0 * orderState : 3 * orderPay : http://app.tealg.com/wap/NewPayStap1.aspx?order_no=ZXB1801030001 * orderReturn : * ordersMsg : [{"ordersId":35556,"ordersNumber":"ZXS1801030001","ordersState":3,"ordersBusinessId":11363,"ordersBusinessName":"云南张顺翔茶叶","ordersWuLiu":"","orderReturnStatus":"","ordersProducts":[{"productId":43693,"detailsId":53363,"productComment":0,"productName":"贺开山古茶树 普洱生茶 黄片","productPic":"http://img1.tealg.com/Product/Main/220X220/201604/43d4212d-bf7b-47ff-817f-b897ba1642f0.jpg","productPrice":420,"productNumber":1,"ordersCommentAdd":""}]}] */ private int orderId; private String orderNumber; private double orderPirce; private int orderPayInt; private int orderState; private String orderPay; private String orderReturn; private List<OrdersMsgBean> ordersMsg; public int getOrderId() { return orderId; } public void setOrderId(int orderId) { this.orderId = orderId; } public String getOrderNumber() { return orderNumber; } public void setOrderNumber(String orderNumber) { this.orderNumber = orderNumber; } public double getOrderPirce() { return orderPirce; } public void setOrderPirce(double orderPirce) { this.orderPirce = orderPirce; } public int getOrderPayInt() { return orderPayInt; } public void setOrderPayInt(int orderPayInt) { this.orderPayInt = orderPayInt; } public int getOrderState() { return orderState; } public void setOrderState(int orderState) { this.orderState = orderState; } public String getOrderPay() { return orderPay; } public void setOrderPay(String orderPay) { this.orderPay = orderPay; } public String getOrderReturn() { return orderReturn; } public void setOrderReturn(String orderReturn) { this.orderReturn = orderReturn; } public List<OrdersMsgBean> getOrdersMsg() { return ordersMsg; } public void setOrdersMsg(List<OrdersMsgBean> ordersMsg) { this.ordersMsg = ordersMsg; } public static class OrdersMsgBean { /** * ordersId : 35556 * ordersNumber : ZXS1801030001 * ordersState : 3 * ordersBusinessId : 11363 * ordersBusinessName : 云南张顺翔茶叶 * ordersWuLiu : * orderReturnStatus : * ordersProducts : [{"productId":43693,"detailsId":53363,"productComment":0,"productName":"贺开山古茶树 普洱生茶 黄片","productPic":"http://img1.tealg.com/Product/Main/220X220/201604/43d4212d-bf7b-47ff-817f-b897ba1642f0.jpg","productPrice":420,"productNumber":1,"ordersCommentAdd":""}] */ private int ordersId; private String ordersNumber; private int ordersState; private int ordersBusinessId; private String ordersBusinessName; private String ordersWuLiu; private String orderReturnStatus; private List<OrdersProductsBean> ordersProducts; public int getOrdersId() { return ordersId; } public void setOrdersId(int ordersId) { this.ordersId = ordersId; } public String getOrdersNumber() { return ordersNumber; } public void setOrdersNumber(String ordersNumber) { this.ordersNumber = ordersNumber; } public int getOrdersState() { return ordersState; } public void setOrdersState(int ordersState) { this.ordersState = ordersState; } public int getOrdersBusinessId() { return ordersBusinessId; } public void setOrdersBusinessId(int ordersBusinessId) { this.ordersBusinessId = ordersBusinessId; } public String getOrdersBusinessName() { return ordersBusinessName; } public void setOrdersBusinessName(String ordersBusinessName) { this.ordersBusinessName = ordersBusinessName; } public String getOrdersWuLiu() { return ordersWuLiu; } public void setOrdersWuLiu(String ordersWuLiu) { this.ordersWuLiu = ordersWuLiu; } public String getOrderReturnStatus() { return orderReturnStatus; } public void setOrderReturnStatus(String orderReturnStatus) { this.orderReturnStatus = orderReturnStatus; } public List<OrdersProductsBean> getOrdersProducts() { return ordersProducts; } public void setOrdersProducts(List<OrdersProductsBean> ordersProducts) { this.ordersProducts = ordersProducts; } public static class OrdersProductsBean { /** * productId : 43693 * detailsId : 53363 * productComment : 0 * productName : 贺开山古茶树 普洱生茶 黄片 * productPic : http://img1.tealg.com/Product/Main/220X220/201604/43d4212d-bf7b-47ff-817f-b897ba1642f0.jpg * productPrice : 420.0 * productNumber : 1 * ordersCommentAdd : */ private int productId; private int detailsId; private int productComment; private String productName; private String productPic; private double productPrice; private int productNumber; private String ordersCommentAdd; public int getProductId() { return productId; } public void setProductId(int productId) { this.productId = productId; } public int getDetailsId() { return detailsId; } public void setDetailsId(int detailsId) { this.detailsId = detailsId; } public int getProductComment() { return productComment; } public void setProductComment(int productComment) { this.productComment = productComment; } public String getProductName() { return productName; } public void setProductName(String productName) { this.productName = productName; } public String getProductPic() { return productPic; } public void setProductPic(String productPic) { this.productPic = productPic; } public double getProductPrice() { return productPrice; } public void setProductPrice(double productPrice) { this.productPrice = productPrice; } public int getProductNumber() { return productNumber; } public void setProductNumber(int productNumber) { this.productNumber = productNumber; } public String getOrdersCommentAdd() { return ordersCommentAdd; } public void setOrdersCommentAdd(String ordersCommentAdd) { this.ordersCommentAdd = ordersCommentAdd; } } } } }
true
36b6a6aca5bdbcb3471239533aeb3a348c29834f
Java
black-ant/expengine
/engine-core/src/main/java/com/gang/etl/engine/web/controller/SyncSettingController.java
UTF-8
1,095
1.890625
2
[]
no_license
package com.gang.etl.engine.web.controller; import com.gang.common.lib.to.ResponseModel; import com.gang.etl.datacenter.entity.SyncSetting; import com.gang.etl.datacenter.service.impl.SyncSettingServiceImpl; import com.gang.etl.engine.web.logic.SyncSettingLogic; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; /** * @Classname SyncSettingController * @Description TODO * @Date 2020/1/15 23:06 * @Created by zengzg */ @RestController @RequestMapping("sync/setting") public class SyncSettingController extends AbstratController<SyncSettingServiceImpl, SyncSetting> { @Autowired private SyncSettingLogic syncSettingLogic; @GetMapping("getcfgto") public ResponseModel<SyncSetting> getTO(@RequestParam("code") String code) { return ResponseModel.commonResponse(syncSettingLogic.getConfig(code)); } }
true
952e018eea34865f0988eef5296561e131f8fb9d
Java
xMalware/BadBlock-GameAPI
/src/fr/badblock/game/core18R3/players/data/ChatData.java
UTF-8
195
1.664063
2
[]
no_license
package fr.badblock.game.core18R3.players.data; import lombok.AllArgsConstructor; @AllArgsConstructor public class ChatData { public String playerName; public String message; }
true
e388d9f50da7cb36fc3f3de7de4d75869a79d2cb
Java
francoisschwarzentruber/openmusicwriter
/src/musicwriter/gui/PoigneeCurseur.java
UTF-8
2,338
2.796875
3
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package musicwriter.gui; import java.awt.Cursor; import musicwriter.controller.Controller; import musicwriter.donnees.Curseur; import musicwriter.donnees.ElementMusical; import musicwriter.donnees.ElementMusicalMultiCurseurs; import musicwriter.donnees.Histoire; import musicwriter.donnees.actions.PartitionActionElementMusicalMultiCurseursCurseurModifier; import musicwriter.gui.partitionaffichage.Systeme; /** * Une poignée pour contrôler un élément musical avec plusieurs curseurs comme : * - une courbe ; * - une ligne ; * - une arpège ; * - un crescendo etc. * @author Ancmin */ public class PoigneeCurseur extends Poignee { private final int numeroCurseur; private final ElementMusicalMultiCurseurs elementMusical; private ElementMusicalMultiCurseurs elementMusicalCopie; /** * crée une poignée qui contrôle le curseur numéro numeroCurseur de l'élement musical * elementMusical * @param systeme * @param elementMusical * @param numeroCurseur */ public PoigneeCurseur(Systeme systeme, ElementMusicalMultiCurseurs elementMusical, int numeroCurseur) { super(systeme, elementMusical.getCurseur(numeroCurseur)); this.numeroCurseur = numeroCurseur; this.elementMusical = elementMusical; this.elementMusicalCopie = elementMusical; } private ElementMusicalMultiCurseurs getElementMusicalMultiCurseurs() { return elementMusical; } @Override public void mouseDrag(Curseur newCurseur, Controller panel) { elementMusicalCopie = (ElementMusicalMultiCurseurs) elementMusical.clone(); elementMusicalCopie.setCurseur(numeroCurseur, newCurseur); } @Override public void mouseFinish(Curseur newCurseur, Histoire histoire) { histoire.executer( new PartitionActionElementMusicalMultiCurseursCurseurModifier( getElementMusicalMultiCurseurs(), numeroCurseur, newCurseur)); } @Override public ElementMusical getElementMusicalResultat() { return elementMusicalCopie; } @Override public Cursor getCursor() { return Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR); } }
true
62f67148ebb69f1b10b437801850ec4ce9cad242
Java
mdnazmulkarim/cqf-ruler
/dstu3/src/main/java/org/opencds/cqf/dstu3/builders/StructuredMapStructureBuilder.java
UTF-8
1,043
2.0625
2
[ "Apache-2.0" ]
permissive
package org.opencds.cqf.dstu3.builders;//package org.opencds.cqf.dstu3.builders; import org.opencds.cqf.common.builders.BaseBuilder; import org.hl7.fhir.dstu3.model.StructureMap; public class StructuredMapStructureBuilder extends BaseBuilder<StructureMap.StructureMapStructureComponent> { // TODO public StructuredMapStructureBuilder() { this(new StructureMap.StructureMapStructureComponent()); } public StructuredMapStructureBuilder(StructureMap.StructureMapStructureComponent complexProperty) { super(complexProperty); } // public StructuredMapStructureBuilder buildSource(String s) { // complexProperty.setUrl("someUrl"); // complexProperty.setMode( StructureMap.StructureMapModelMode.SOURCE); // return this; // } // // public StructuredMapStructureBuilder buildTarget(String s) { // complexProperty.setUrl("someUrl"); // complexProperty.setMode( StructureMap.StructureMapModelMode.SOURCE); // return this; // } }
true
57553d64b511fd3256607457a55786f08e8baefc
Java
ForhadIsrafil/my-weather-app
/app/src/main/java/com/example/myweather/Countries.java
UTF-8
562
2.265625
2
[]
no_license
package com.example.myweather; import androidx.annotation.NonNull; import androidx.room.Entity; import androidx.room.PrimaryKey; @Entity public class Countries { @NonNull @PrimaryKey(autoGenerate = true) int id; String name; // public Countries(String name) { // this.name = name; // } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
true
7aa50d20cb470238628e255248521341196db211
Java
yaoao333/spring-study
/spring-04-autowired/src/main/java/com/yao/pojo/Person.java
UTF-8
1,073
2.609375
3
[]
no_license
package com.yao.pojo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Component("person") public class Person { @Value("yaoao") private String name; @Autowired @Qualifier("cat") private Cat myCat; @Autowired @Qualifier("dog") private Dog myDog; public String getName() { return name; } public Cat getMyCat() { return myCat; } public Dog getMyDog() { return myDog; } public void setName(String name) { this.name = name; } public void setMyCat(Cat myCat) { this.myCat = myCat; } public void setMyDog(Dog myDog) { this.myDog = myDog; } @Override public String toString() { return "Person{" + "name='" + name + '\'' + ", myCat=" + myCat + ", myDog=" + myDog + '}'; } }
true
f1787365368719fd43cca7c7eaa6cbd5e505e816
Java
bruce-shi/PCBrowser
/browser/src/main/java/com/jupiter/pcbrowser/MainActivity.java
UTF-8
11,773
1.867188
2
[]
no_license
package com.jupiter.pcbrowser; import android.app.*; import android.content.*; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.content.res.Configuration; import android.content.res.TypedArray; import android.os.IBinder; import android.os.RemoteException; import android.preference.PreferenceManager; import android.support.v4.widget.DrawerLayout; import android.os.Bundle; import android.support.v7.app.ActionBarDrawerToggle; import android.util.Log; import android.view.*; import android.widget.AdapterView; import android.widget.ListView; import com.jupiter.Adapter.NavDrawerListAdapter; import com.jupiter.Helper.Helper; import com.jupiter.Service.NewsPullService; import com.jupiter.model.CachedNews; import com.jupiter.model.NavDrawerItem; import com.orm.SugarRecord; import org.apache.http.message.HeaderValueParser; import java.util.*; public class MainActivity extends Activity implements ListFragment.OnFragmentInteractionListener { private DrawerLayout mDrawerLayout; private ListView mDrawerList; private ActionBarDrawerToggle mDrawerToggle; // nav drawer title private CharSequence mDrawerTitle; // application title private CharSequence mAppTitle; //nav slide menu items private String[] navMenuTitles; //Icons for slide menu private TypedArray navMenuIcons; private String[] navMenuCategory; private ArrayList<NavDrawerItem> navDrawerItems; private NavDrawerListAdapter adapter; //private ArrayList<NewsListItem> listItems; private int currentNavPosition; private ListFragment fragment; private static final int SETTING_ACTIVITY_REQUEST_CODE = 101; public static String PREFERENCE_CHANGED = "preference_changed"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mAppTitle = mDrawerTitle = getTitle(); navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items); navMenuCategory = getResources().getStringArray(R.array.nav_drawer_catogory); navMenuIcons = getResources().obtainTypedArray(R.array.nav_drawer_icons); mDrawerLayout = (DrawerLayout) findViewById(R.id.container); mDrawerList = (ListView) findViewById(R.id.list_slidermenu); navDrawerItems = new ArrayList<NavDrawerItem>(); // Home navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuCategory[0],navMenuIcons.getResourceId(0, 0))); // Sports navDrawerItems.add(new NavDrawerItem(navMenuTitles[1],navMenuCategory[1], navMenuIcons.getResourceId(1, 0))); // Entertainment navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuCategory[2],navMenuIcons.getResourceId(2, 0))); // Technologies navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuCategory[3],navMenuIcons.getResourceId(3, 0))); // Politics navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuCategory[4], navMenuIcons.getResourceId(4, 0))); // My Favorite navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuCategory[5], navMenuIcons.getResourceId(5, 0))); navDrawerItems.add(new NavDrawerItem(navMenuTitles[6], navMenuCategory[6], navMenuIcons.getResourceId(6, 0))); navMenuIcons.recycle(); adapter = new NavDrawerListAdapter(getApplicationContext(),navDrawerItems); mDrawerList.setAdapter(adapter); getActionBar().setDisplayHomeAsUpEnabled(true); getActionBar().setHomeButtonEnabled(true); mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.app_name, R.string.app_name ){ public void onDrawerClosed(View view) { getActionBar().setTitle(mAppTitle); // calling onPrepareOptionsMenu() to show action bar icons invalidateOptionsMenu(); } public void onDrawerOpened(View drawerView) { getActionBar().setTitle(mDrawerTitle); // calling onPrepareOptionsMenu() to hide action bar icons invalidateOptionsMenu(); } }; mDrawerLayout.setDrawerListener(mDrawerToggle); mDrawerList.setOnItemClickListener(new SlideMenuClickListener()); fragment = new ListFragment(); if (savedInstanceState == null) { // on first time display view for first nav item FragmentManager fragmentManager = getFragmentManager(); fragmentManager.beginTransaction() .replace(R.id.frame_container, fragment).commit(); displayFragment(0); } final Intent mServiceIntent = new Intent(this,NewsPullService.class); startService(mServiceIntent); mServiceIntent.setAction("com.jupiter.pcbrowser.NewsPullService"); //final Intent eintent = new Intent(Helper.createExplicitFromImplicitIntent(this, mServiceIntent)); // mServiceIntent.setPackage(getPackageName()); bindService(mServiceIntent, mConnection, Context.BIND_AUTO_CREATE); //set the default pref file and mode for preference PreferenceManager.setDefaultValues(getApplicationContext(), getString(R.string.sharedpref), Context.MODE_MULTI_PROCESS, R.xml.pref_general, false); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. if(mDrawerToggle.onOptionsItemSelected(item)){ return true; } int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { Intent intent = new Intent(this, SettingsActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); this.startActivityForResult(intent, SETTING_ACTIVITY_REQUEST_CODE); return true; } if(id == R.id.action_logout){ SharedPreferences sp = getSharedPreferences(getString(R.string.sharedpref),Context.MODE_MULTI_PROCESS); SharedPreferences.Editor editor= sp.edit(); editor.putString(getString(R.string.appkey), ""); editor.putBoolean(getString(R.string.islogin),false); editor.commit(); Intent login = new Intent(this,LoginActivity.class); this.startActivity(login); this.finish(); } if(id == R.id.action_delete_test){ CachedNews.executeQuery("delete from "+ SugarRecord.getTableName(CachedNews.class)+" where title like 'Fake%'"); } if(id == R.id.action_delete_all_cache){ CachedNews.executeQuery("delete from "+ SugarRecord.getTableName(CachedNews.class)); } return super.onOptionsItemSelected(item); } @Override public void setTitle(CharSequence title){ mAppTitle = title; getActionBar().setTitle(title); } @Override public boolean onPrepareOptionsMenu(Menu menu){ //hide the action menu if drawer is opened boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList); menu.findItem(R.id.action_settings).setVisible(!drawerOpen); return super.onPrepareOptionsMenu(menu); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); // Sync the toggle state after onRestoreInstanceState has occurred. mDrawerToggle.syncState(); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); // Pass any configuration change to the drawer toggls mDrawerToggle.onConfigurationChanged(newConfig); } @Override public void onItemClick(Bundle param){ Intent intent = new Intent(this, NewsContentActivity.class); //intent.putExtra(PCConstant.NEWS_TITLE,message); //intent.putExtra(PCConstant.NEWS_ID, currentItem.getId()); intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); intent.putExtras(param); startActivity(intent); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch(requestCode) { case SETTING_ACTIVITY_REQUEST_CODE : { if (resultCode == Activity.RESULT_OK && data.getBooleanExtra(PREFERENCE_CHANGED,false)) { try { mService.restartServer(); }catch(RemoteException re){ re.printStackTrace(); } } break; } } } @Override public void finish(){ unbindService(mConnection); super.finish(); } private void displayFragment(int position){ if(fragment !=null){ fragment.setCategory(navMenuCategory[position]); // update selected item and title, then close the drawer //loadNewsList(navMenuCategory[position], fragment); mDrawerList.setItemChecked(position, true); mDrawerList.setSelection(position); setTitle(navMenuTitles[position]); mDrawerLayout.closeDrawer(mDrawerList); } else { // error in creating fragment Log.e("MainActivity", "Error in creating fragment"); } } private class SlideMenuClickListener implements android.widget.AdapterView.OnItemClickListener { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // display view for selected nav drawer item displayFragment(position); } } /*************************************************************** * code to communicate with the server * * ***************************************************************/ ILocalService mService = null; private ServiceConnection mConnection = new ServiceConnection() { public void onServiceConnected(ComponentName className, IBinder service) { // This is called when the connection with the service has been // established, giving us the service object we can use to // interact with the service. We are communicating with our // service through an IDL interface, so get a client-side // representation of that from the raw service object. mService = ILocalService.Stub.asInterface(service); try { mService.startServer(); }catch (RemoteException re){ re.printStackTrace(); } Log.d(this.getClass().toString(),"Server Disconnect"); } public void onServiceDisconnected(ComponentName className) { // This is called when the connection with the service has been // unexpectedly disconnected -- that is, its process crashed. mService = null; Log.d(this.getClass().toString(),"Server Disconnect"); } }; }
true
4bdad6c9f617c87f2952974c9ee2525fbc92eea4
Java
haidong94/WaveFindYourFriend-1
/app/src/main/java/vinsoft/com/wavefindyourfriend/untils/StringFormatUntil.java
UTF-8
393
1.6875
2
[]
no_license
package vinsoft.com.wavefindyourfriend.untils; /** * Created by kienmit95 on 2/04/17. */ public class StringFormatUntil { //datetime format public static String DATE_FORMAT = "dd-MM-yyyy"; public static String DAY_FORMAT = "HH:mm:ss"; //Firebase name public static String REF_MESSAGE_NAME = "Messages"; public static String DATA_OFFLINE_NAME = "MessageOffline"; }
true
57d083d51660fee9e75f3b5f19a85cdc0425c302
Java
shinobig/databaseRecipeList
/src/sample/Controller.java
UTF-8
2,382
2.59375
3
[]
no_license
package sample; import javafx.fxml.FXML; import javafx.fxml.*; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.PasswordField; import javafx.scene.control.TextField; import javafx.stage.Modality; import javafx.stage.Stage; import javafx.stage.StageStyle; import sample.model.DataSource; import sample.view.recipesView.Recipe; import sample.view.recipesView.RecipesViewController; import java.io.IOException; import java.util.ArrayList; public class Controller { private DataSource dataSource; @FXML private TextField usernameTextArea; @FXML private PasswordField passwordArea; @FXML private Button loginBtn; public void initialize() { dataSource = new DataSource(); if (!dataSource.open()) { System.out.println("Can't open datasource"); } } @FXML private void handleLogin() { if (checkLogin()) { String username = usernameTextArea.getText().trim(); showRecipesView(getUserId(username)); } else { System.out.println("Please insert new username or ps"); } } @FXML private void showRecipesView(int userId) { dataSource.close(); try { FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("view/recipesView/recipesView.fxml")); Parent root1 = fxmlLoader.load(); Stage stage = new Stage(); stage.setTitle("Welcome!"); Scene scene = new Scene(root1, 900, 500); RecipesViewController recipesViewController = fxmlLoader.getController(); recipesViewController.initialize(userId); stage.setScene(scene); stage.show(); } catch (IOException e) { e.printStackTrace(); } } private boolean checkLogin() { String username = usernameTextArea.getText().trim(); String password = passwordArea.getText().trim(); int storedUserId = getUserId(username); String storedPassword = dataSource.getPassword(storedUserId); if (storedPassword != null) { if (password.equals(storedPassword)) { return true; } System.out.println("Wrong password"); return false; } System.out.println("No user found"); return false; } private int getUserId (String username){ return dataSource.getUsername(username); } // Testing methods public void showRecipesViewTest (){ showRecipesView(0); } }
true
b0f374fbefee1f57c3d0ed5b5429c9aed43bba3c
Java
vesna1010/spring_boot_java2
/college/src/main/java/com/vesna1010/college/services/ExamService.java
UTF-8
727
1.945313
2
[]
no_license
package com.vesna1010.college.services; import java.time.LocalDate; import java.util.List; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import com.vesna1010.college.models.Exam; import com.vesna1010.college.models.Professor; import com.vesna1010.college.models.StudentSubjectId; import com.vesna1010.college.models.Subject; public interface ExamService { List<Exam> findAllExamsByProfessorAndSubjectAndDate(Professor professor, Subject subject, LocalDate date); Page<Exam> findAllExamsByStudyProgramId(Long id, Pageable pageable); Exam findExamById(StudentSubjectId id); Exam saveExam(Exam exam); void deleteExamById(StudentSubjectId id); }
true
ccfbbc74cf45369548de6d46e8659c2452d6ce88
Java
jmlon/java_fundamentals
/07 matrices/Matriz.java
UTF-8
632
3.28125
3
[]
no_license
public class Matriz{ public static void main(String[] args) { double matriz[][];//Declaración matriz = new double[3][5]; matriz[0][0] = 1; matriz[0][1] = 1; matriz[0][2] = 1; matriz[0][3] = 1; matriz[0][4] = 1; matriz[1][0] = 2; matriz[1][1] = 2; matriz[1][2] = 2; matriz[1][3] = 2; matriz[1][4] = 2; matriz[2][0] = 3; matriz[2][1] = 3; matriz[2][2] = 3; matriz[2][3] = 3; matriz[2][4] = 3; for (int i=0; i<matriz.length; i++ ) { for (int j=0; j<matriz[0].length ; j++ ) { System.out.print(matriz[i][j]+" "); } System.out.println(); } } }
true
b3fbd122ac37682baffb567f9753292039019fa1
Java
Mel-Github/microservice-feign
/eureka-client-receiver/src/main/java/com/eureka/service/Impl/ChildEventServiceImpl.java
UTF-8
507
2.09375
2
[]
no_license
package com.eureka.service.Impl; import com.eureka.domain.ChildEvent; import com.eureka.repository.ChildEventRepository; import com.eureka.service.ChildEventService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class ChildEventServiceImpl implements ChildEventService { @Autowired ChildEventRepository childEventRepository; public void save(ChildEvent event){ childEventRepository.save(event); } }
true
0c58cfd3516c1d95646ccee24ee62fd6d698cdb1
Java
eliran98/Repository
/myTestProject/TestProject/src/com/algorithms/framework/questions/BackTracking.java
UTF-8
772
3.359375
3
[]
no_license
package com.algorithms.framework.questions; public class BackTracking { public static void printPermutations(String str){ if(str == null){ return; } permutations(str.toCharArray(),0,str.length()-1); } private static void permutations(char[] arr,int startIndex,int lastIndex){ if(startIndex == lastIndex){ System.out.println(String.valueOf(arr)); }else{ for (int i = startIndex; i <= lastIndex; i++) { swap(arr,startIndex,i); permutations(arr,startIndex+1,lastIndex); swap(arr,startIndex,i); /*return back - backtrack*/ } } } private static void swap(char[] arr,int indexA,int indexB){ char temp = arr[indexA]; arr[indexA] = arr[indexB]; arr[indexB] = temp; } }
true
f446ce798d52ec7af951485ca661a3f2ec56755b
Java
mlieshoff/learner
/learner-system/src/main/java/org/mili/learner/system/SwingClient.java
UTF-8
4,906
2.84375
3
[]
no_license
package org.mili.learner.system; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.IOException; import java.util.ArrayList; import java.util.Locale; /** * Created with IntelliJ IDEA. * User: micha * Date: 16.09.13 * Time: 15:41 * To change this template use File | Settings | File Templates. */ public class SwingClient implements EngineListener { private Engine engine; private JFrame frame; private StartPanel startPanel; private GamePanel gamePanel; private SwingClient() throws IOException { engine = new Engine(); engine.setEngineListener(this); startPanel = new StartPanel(); gamePanel = new GamePanel(); frame = new JFrame("Learner"); frame.setSize(640, 480); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLayout(new BorderLayout()); frame.add(BorderLayout.CENTER, startPanel); } @Override public void onGameStart() { frame.remove(startPanel); frame.add(BorderLayout.CENTER, gamePanel); frame.revalidate(); } @Override public void onNewRound(RoundObject roundObject) { gamePanel.updateRound(roundObject); } @Override public void onRightAnswer() { gamePanel.onWin(); } @Override public void onWrongAnswer() { gamePanel.onLoose(); } private class StartPanel extends JPanel { private StartPanel() throws IOException { java.util.List<String> list = engine.getLanguages(); String[] locales = new String[list.size()]; for (int i = 0, n = list.size(); i < n; i ++) { locales[i] = list.get(i); } final JComboBox<String> from = new JComboBox<String>(locales); final JComboBox<String> to = new JComboBox<String>(locales); JButton startButton = new JButton("Start"); startButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { engine.start((String) from.getSelectedItem(), (String) to.getSelectedItem()); } catch (IOException e1) { e1.printStackTrace(); } } }); add(from); add(to); add(startButton); } } private class GamePanel extends JPanel { private JLabel question = new JLabel(); private java.util.List<JButton> buttons = new ArrayList<JButton>(); private Font font = new Font("Verdana", Font.BOLD, 24); private GamePanel() { question.setForeground(Color.BLACK); question.setFont(font); question.setHorizontalAlignment(JLabel.CENTER); setLayout(new BorderLayout()); add(BorderLayout.CENTER, question); JPanel buttonsPanel = new JPanel(new GridLayout(2, 2)); for (int i = 0; i < 4; i ++) { final JButton button = new JButton(); button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { engine.answer(button.getText()); } }); buttons.add(button); buttonsPanel.add(button); } add(BorderLayout.SOUTH, buttonsPanel); } private void updateRound(RoundObject roundObject) { question.setForeground(Color.BLACK); question.setText(roundObject.getQuestion()); java.util.List<String> answers = roundObject.getAnswers(); for (int i = 0, n = buttons.size(); i < n; i ++) { JButton button = buttons.get(i); button.setText(answers.get(i)); } } private void onWin() { question.setForeground(Color.GREEN); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } private void onLoose() { question.setForeground(Color.RED); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { try { new SwingClient(); } catch (IOException e) { e.printStackTrace(); System.exit(-1); } } }); } }
true
fa5ed672ffc14470e0d50e8d78090961fe2e5467
Java
SamRocK1030/HW3
/src/SeatFinderTest.java
UTF-8
2,354
2.765625
3
[]
no_license
import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; public class SeatFinderTest { Flight[] flights; SeatFinder sf; @Before public void setUp() throws Exception { // initialize a new FlightFinder object before EVERY test flights = Flight.allFlights(); sf = new SeatFinder(); } @Test public void test_1() { // test null plane int actual = sf.numSeats(null, true, true, true, 2); assertEquals(-1, actual); } @Test public void test_2() { // test plane less than 2 byte[] plane = new byte[1]; int actual = sf.numSeats(plane, true, true, true, 2); assertEquals(-1, actual); } @Test public void test_3() { //test max row less than 1 byte[] plane = new byte[3]; int actual = sf.numSeats(plane, true, true, true, -1); assertEquals(0, actual); } @Test public void test_4() { //test middle byte[] plane = new byte[]{(byte)0, (byte)0x39}; int actual = sf.numSeats(plane, false, false, true, 2); assertEquals(1, actual); } @Test public void test_5() { //test window byte[] plane = new byte[]{(byte)0, (byte)0x39}; int actual = sf.numSeats(plane, true, false, false, 2); assertEquals(3, actual); } @Test public void test_6() { //test aisle byte[] plane = new byte[]{(byte)0, (byte)0x39}; int actual = sf.numSeats(plane, false, true, false, 2); assertEquals(6, actual); } @Test public void test_7() { //test empty plane, window, aisle, middle all ok byte[] plane = new byte[]{(byte)0, (byte)0, (byte)0}; int actual = sf.numSeats(plane, true, true, true, 2); assertEquals(14, actual); } @Test public void test_8() { //test empty plane, window, aisle, middle all not ok byte[] plane = new byte[]{(byte)0, (byte)0, (byte)0}; int actual = sf.numSeats(plane, false, false, false, 2); assertEquals(0, actual); } @Test public void test_9() { //test full plane, window, aisle, middle all ok byte[] plane = new byte[]{(byte)0x7F, (byte)0x7F, (byte)0x7F}; int actual = sf.numSeats(plane, true, true, true, 2); assertEquals(0, actual); } @Test public void test_10() { //test full plane, max row less than plane byte[] plane = new byte[]{(byte)0x7F, (byte)0x7F, (byte)0x7F, (byte)0x7F, (byte)0x39}; int actual = sf.numSeats(plane, true, true, true, 2); assertEquals(0, actual); } }
true
8cd2554cf2498604e8da2b56dc349ead46e15d10
Java
hotpot0525/DDD_STUDY
/src/product/game/charactor/parameter/vo/Level.java
UTF-8
310
2.4375
2
[]
no_license
package product.game.charactor.parameter.vo; public class Level implements CharactorParameter{ private final int level; public Level(int level) { this.level = level; } @Override public int getValue() { return level; } @Override public String toString() { return "レベル:"+level; } }
true
4274b37a564a78eb0e5ce8383facd926061c549d
Java
Vinnakotarohith/java
/s.java
UTF-8
278
2.828125
3
[]
no_license
import java.util.*; // Random number class s { public static void main(String [] args){ int max=5000,min=1000; System.out.println("max : "+max+" min : "+min); int b=(int)(Math.random()*(max-min+1)+min); System.out.println(b); } }
true
8249f97a71ad9e96427e63da779bebf0f641738e
Java
Sierou-Java/Spring-Family
/Spring-Family-Test/src/main/java/org/sierou/aop/common/CglibTarget.java
UTF-8
237
1.53125
2
[]
no_license
package org.sierou.aop.common; /** * @Author 王洪悦.{javayue@yeah.net} * @Create 2017-08-13 下午9:00 */ public interface CglibTarget { void hello(); // public void hello(){ // System.out.println("hello world!"); // } }
true
24ba0f6750ed76aecbc624b9c01b521ab2ab7a16
Java
chesmara/Zadatak17
/app/src/main/java/com/example/sninkovic_ns/zadatak15/activities/fragments/DetailFragment.java
UTF-8
5,562
2.09375
2
[]
no_license
package com.example.sninkovic_ns.zadatak15.activities.fragments; import android.app.Fragment; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.ListView; import android.widget.Spinner; import android.widget.TextView; import com.example.sninkovic_ns.zadatak15.R; import com.example.sninkovic_ns.zadatak15.activities.provider.JeloProvajder; import com.example.sninkovic_ns.zadatak15.activities.provider.KategorijaProvajder; import java.io.IOException; import java.io.InputStream; import java.util.List; public class DetailFragment extends Fragment { private int position = 0; //------------------------------------------------------- public void onCreate(Bundle savedInstaceState){ super.onCreate(savedInstaceState); } //-------------------------------------------------------------- public void onActivityCreated(Bundle savedInstanceState){ super.onActivityCreated(savedInstanceState); if(savedInstanceState !=null){ position= savedInstanceState.getInt("position", 0); } //--------------------------------------image--------------------------------- ImageView ivImage = (ImageView) getView().findViewById(R.id.iv_image); InputStream is=null; try { is=getActivity().getAssets().open(JeloProvajder.getJeloById(position).getSlika()); Drawable drawable=Drawable.createFromStream(is, null); ivImage.setImageDrawable(drawable); } catch (IOException e) { e.printStackTrace(); } //----------------------------------------------------------------------------------------- TextView tvNaziv = (TextView) getView().findViewById(R.id.tv_naziv); tvNaziv.setText(JeloProvajder.getJeloById(position).getNaziv()); //---------------------------------------------------------------------------------------- TextView tvOpis = (TextView) getView().findViewById(R.id.tv_opis); tvOpis.setText(JeloProvajder.getJeloById(position).getOpis()); //---------------------------------------------------------------------------------------- Spinner kategorija = (Spinner) getView().findViewById(R.id.sp_kategorija); List<String> kategorije= KategorijaProvajder.getKategorijaNazivi(); ArrayAdapter<String> adapter=new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, kategorije); kategorija.setAdapter(adapter); kategorija.setSelection(JeloProvajder.getJeloById(position).getKategorija().getId()); //------------------------------------------------------------------------------------------------ TextView tvKalorije = (TextView) getView().findViewById(R.id.tv_kalorije); tvKalorije.setText(JeloProvajder.getJeloById(position).getOpis()); //---------------------------------------------------------------------------------------------------- TextView tvCena = (TextView) getView().findViewById(R.id.tv_cena); tvCena.setText(JeloProvajder.getJeloById(position).getOpis()); } //-------------------------------------------------------------------------------------------- public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_detail, container, false); return view; } //--------------------------------------------------------------------------------------------------- public void onSaveInstanceState(Bundle savedInstanceState){ super.onSaveInstanceState( savedInstanceState ); savedInstanceState.putInt( "position", position ); } //------------------------------------------------------------------------------------------------- public void setContent(final int position){ this.position=position; } //------------------------------------------------------------------------------------------------ public void updateContent(final int position){ this.position=position; ImageView ivImage = (ImageView) getView().findViewById(R.id.iv_image); InputStream is=null; try { is=getActivity().getAssets().open(JeloProvajder.getJeloById(position).getSlika()); Drawable drawable=Drawable.createFromStream(is, null); ivImage.setImageDrawable(drawable); } catch (IOException e) { e.printStackTrace(); } TextView tvNaziv = (TextView) getView().findViewById(R.id.tv_naziv); tvNaziv.setText(JeloProvajder.getJeloById(position).getNaziv()); //---------------------------------------------------------------------------------------- TextView tvOpis = (TextView) getView().findViewById(R.id.tv_opis); tvOpis.setText(JeloProvajder.getJeloById(position).getOpis()); //---------------------------------------------------------------------------------------- Spinner kategorija = (Spinner) getView().findViewById(R.id.sp_kategorija); List<String> kategorije= KategorijaProvajder.getKategorijaNazivi(); ArrayAdapter<String> adapter=new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, kategorije); kategorija.setAdapter(adapter); kategorija.setSelection(JeloProvajder.getJeloById(position).getKategorija().getId()); } }
true
4427f230d4b364505b31c5a519cb42df5308bd46
Java
tudorsirbu/ecommerce
/src/com/sheffield/ecommerce/servlets/articles/ArticlesList.java
UTF-8
1,420
2.421875
2
[]
no_license
package com.sheffield.ecommerce.servlets.articles; import java.io.IOException; import java.util.List; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import com.sheffield.ecommerce.dao.ArticleDao; import com.sheffield.ecommerce.models.User; import com.sheffield.ecommerce.models.Article; public class ArticlesList extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //Attempt to get the current user HttpSession httpSession = request.getSession(true); User currentUser = (httpSession != null) ? (User) httpSession.getAttribute("currentUser") : null; //If a user is logged in show the homepage, otherwise direct them to the login page if (currentUser != null) { // get the articles for the current user List<Article> articles = ArticleDao.getArticlesForUser(currentUser); request.setAttribute("articles", articles); RequestDispatcher requestDispatcher = request.getRequestDispatcher("jsp/articles/list.jsp"); requestDispatcher.forward(request, response); } else { response.sendRedirect(request.getContextPath() + "/Login"); } } }
true
1f34bd6839e39c026c68d62a6196c5931a37bce7
Java
hungleee99/Point_Service
/src/main/java/com/vti/pointserver/entity/GroupUser.java
UTF-8
1,381
2.0625
2
[]
no_license
package com.vti.pointserver.entity; import java.io.Serializable; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import com.fasterxml.jackson.annotation.JsonIgnore; @Entity @Table(name = "group_user") public class GroupUser implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Basic(optional = false) @Column(name = "id", unique = true, nullable = false) private Integer id; @JoinColumn(name = "userId", referencedColumnName = "id", nullable = false) @ManyToOne(optional = false) @JsonIgnore private User userId; @JoinColumn(name = "groupId", referencedColumnName = "id", nullable = false) @ManyToOne(optional = false) @JsonIgnore private Group groupId; public GroupUser() { } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public User getUserId() { return userId; } public void setUserId(User userId) { this.userId = userId; } public Group getGroupId() { return groupId; } public void setGroupId(Group groupId) { this.groupId = groupId; } }
true
f64cba5721d91c1f5295274a2d796be09bd71948
Java
pfeif11/JavaBasics
/src/com/syntax/repls/Repl67.java
UTF-8
437
3.15625
3
[]
no_license
package com.syntax.repls; public class Repl67 { public static void main(String[] args) { // Write a program to print out the pattern: // // 1 2 3 4 5 6 7 8 9 10 // 2 4 6 8 10 12 14 16 18 20 // 3 6 9 12 15 18 21 24 27 30 // 4 8 12 16 20 24 28 32 36 40 // 5 10 15 20 25 30 35 40 45 50 for(int y=1;y<=5;y++) { for(int x=1;x<=10;x++) { System.out.print(y*x+" "); } System.out.println(); } } }
true
1cf93889916938104abe8e1fd88057c2c523a5e0
Java
stefanadranca/hiringApp
/src/Job.java
UTF-8
2,404
3.078125
3
[]
no_license
import java.util.ArrayList; public class Job { public String jobName; public Company company; public Boolean flag; Constraint graduationConstraint; Constraint experienceConstraint; Constraint GPAConstraint; private ArrayList<User> candidates; private int numberNeeded; private Double salary; Job(String jobName, Company company, int number, Double salary) { this.jobName = jobName; this.company = company; this.flag = true; this.numberNeeded = number; this.salary = salary; candidates = new ArrayList<>(); } public void setFlag(Boolean flag) { this.flag = flag; } public Boolean getFlag() { return flag; } public void setNumberNeeded(int nr) { numberNeeded = nr; } public Double getSalary() { return salary; } public void setGraduationConstraint(Constraint graduationConstraint) { this.graduationConstraint = graduationConstraint; } public void setExperienceConstraint(Constraint experienceConstraint) { this.experienceConstraint = experienceConstraint; } public int getNumberNeeded() { return numberNeeded; } public void setGPAConstraint(Constraint GPAConstraint) { this.GPAConstraint = GPAConstraint; } public void apply(User user) { if (this.getFlag()) { Recruiter recruiter = this.company.getRecruiter(user); double score = recruiter.evaluate(this, user); candidates.add(user); } } public boolean meetsRequirments(User user){ if (graduationConstraint != null) { if (user.getGraduationYear() != null) { if (user.getGraduationYear() < graduationConstraint.inferiorLimit || user.getGraduationYear() > graduationConstraint.superiorLimit) return false; } } if (experienceConstraint != null) { if (user.getResume().getYearsOfExperience() < experienceConstraint.inferiorLimit || user.getResume().getYearsOfExperience() > experienceConstraint.superiorLimit) return false; } if (GPAConstraint != null) { if (user.meanGPA() < GPAConstraint.inferiorLimit || user.meanGPA() > GPAConstraint.superiorLimit) return false; } return true; } }
true
20eae6e92919394cd53a98c5e712b5c7af47a680
Java
404V5/family168
/core/src/it/functional/src/test/java/com/family168/core/struts2/ExtActionTest.java
UTF-8
1,562
2.015625
2
[]
no_license
package com.family168.core.struts2; import com.family168.security.domain.User; import junit.framework.*; public class ExtActionTest extends TestCase { protected ExtAction action = new UserAction(); public void testDefault() { assertNotNull(action); } public void testPagedQuery() throws Exception { try { action.setStart(0); action.setLimit(15); action.setSort(null); action.setDir(null); action.setFilterTxt(null); action.setFilterValue(null); action.pagedQuery(); } catch (Exception ex) { } } public void testSave() throws Exception { try { action.save(); } catch (Exception ex) { } } public void testLoadData() throws Exception { try { action.setId(1L); action.loadData(); } catch (Exception ex) { } } public void testRemove() throws Exception { try { action.setIds("1,2"); action.remove(); } catch (Exception ex) { } } public void testValidate() throws Exception { action.beforeSave(null); action.validate(); } public void testEtc() throws Exception { action.setRemovedIds(null); action.setData(null); } class UserAction extends ExtAction<User> { public UserAction() { //entityDao = new UserDao(); } } }
true
f72c3fb42bcf730002e546cd42f6c6b5e47e7d7d
Java
acientstarlight/java_study
/src/Java_Base/LogicalOperator.java
UTF-8
775
3.90625
4
[]
no_license
package Java_Base; /** * 逻辑运算符 */ public class LogicalOperator { public static void main(String[] args) { boolean a = true; boolean b = false; boolean c = true; boolean d = false; //都为true为true System.out.println(""+(a&&b)); //其中一个以上为true为true System.out.println(""+(a||b)); //取结果的反数,如果条件为true,则为false System.out.println(""+!(a&&b)); int e = 5; int f = 10; int h = 20; //因为e<1为false,&&运算符后面的不执行 boolean g = (e<1)&&(f++>5); boolean i = (e>1)&&(h++>5); System.out.println(e); System.out.println(f); System.out.println(h); } }
true
0720b9513487a4de82164da10e83db61a1bbcc3c
Java
ebruersoy/employeeService
/src/main/java/com/myway/services/DepartmentService.java
UTF-8
1,218
2.59375
3
[]
no_license
package com.myway.services; import com.myway.entity.Department; import com.myway.exception.InvalidRequestException; import com.myway.repository.DepartmentRepository; import org.springframework.stereotype.Component; /** * @author Ebru Göksal */ @Component public class DepartmentService { private DepartmentRepository departmentRepository; public DepartmentService(DepartmentRepository departmentRepository) { this.departmentRepository = departmentRepository; } public Department save(Department department){ if(department.getName() == null){ throw new InvalidRequestException("departmentName","null","not null"); } if(department.getName().isEmpty()){ throw new InvalidRequestException("departmentName","empty","not empty"); } Department departmentByName = departmentRepository.findByName(department.getName()); if(departmentByName != null){ throw new InvalidRequestException("department",department.getName(),"not exists"); } return departmentRepository.save(department); } public Department findById(Long id) { return departmentRepository.findById(id).orElse(null); } }
true
2dd5269535668910a3a288bded480f3ed64fdc80
Java
suhuangqiang/Tooth
/Tooth2/app/src/main/java/com/example/tooth/Message/AddressListMessage.java
UTF-8
373
2.03125
2
[]
no_license
package com.example.tooth.Message; import com.example.tooth.Entity.Address; import java.util.List; /** * Created by shq1 on 2016/11/2. */ public class AddressListMessage extends Message { private List<Address> data; public List<Address> getData() { return data; } public void setData(List<Address> data) { this.data = data; } }
true
388310345ec44083a749446c6dd7241b1537e4d0
Java
jamesmmorin/KoboldCamp
/KoboldCamp/src/test/java/com/swcguild/koboldcamp/KoboldCampDaoTest.java
UTF-8
6,977
2.0625
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 com.swcguild.koboldcamp; import com.swcguild.koboldcamp.dao.DAO; import com.swcguild.koboldcamp.model.Asset; import com.swcguild.koboldcamp.model.User; import java.util.List; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.jdbc.core.JdbcTemplate; /** * * @author apprentice */ public class KoboldCampDaoTest { private DAO dao; public KoboldCampDaoTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { ApplicationContext ctx = new ClassPathXmlApplicationContext("test-applicationContext.xml"); dao = ctx.getBean("DAO", DAO.class); JdbcTemplate cleaner = ctx.getBean("jdbcTemplate", JdbcTemplate.class); cleaner.execute("DELETE FROM KoboldCamp_Test.asset_records WHERE 1 = 1"); cleaner.execute("DELETE FROM KoboldCamp_Test.asset_statuses WHERE 1 = 1"); cleaner.execute("DELETE FROM KoboldCamp_Test.assets WHERE 1 = 1"); cleaner.execute("DELETE FROM KoboldCamp_Test.authorities WHERE 1 = 1"); cleaner.execute("DELETE FROM KoboldCamp_Test.categories WHERE 1 = 1"); cleaner.execute("DELETE FROM KoboldCamp_Test.user_profiles WHERE 1 = 1"); cleaner.execute("DELETE FROM KoboldCamp_Test.users WHERE 1 = 1"); cleaner.execute("INSERT INTO `users` (`user_id`, `username`, `password`, `enabled`) VALUES\n" + " (1, \"test_admin\", \"password\", 1),\n" + " (2, \"test_employee\", \"password\", 1),\n" + " (3, \"test_user\", \"password\", 1)"); cleaner.execute("INSERT INTO `authorities` (`username`, `authority`) VALUES ('test_admin', 'ROLE_ADMIN'),('test_admin', 'ROLE_EMPLOYEE'),('test_admin', 'ROLE_USER'),('test_employee', 'ROLE_EMPLOYEE'),('test_employee', 'ROLE_USER'),('test_user', 'ROLE_USER')"); cleaner.execute("INSERT INTO `categories` (`category_id`, `name`) VALUES(1, 'Backpacks'),(2, 'Sleeping Bags'),(3, 'Camping Stoves'),(4, 'Paddling Gear'),(5, 'Tents')"); cleaner.execute("INSERT INTO `asset_statuses` (`status_id`, `status`) VALUES (1, 'AVAILABLE'),(2, 'CHECKED OUT'),(3, 'BROKEN'),(4, 'LOST'),(5, 'UNDER REPAIRS')"); } @After public void tearDown() { ApplicationContext ctx = new ClassPathXmlApplicationContext("test-applicationContext.xml"); JdbcTemplate cleaner = ctx.getBean("jdbcTemplate", JdbcTemplate.class); cleaner.execute("DELETE FROM KoboldCamp_Test.asset_records WHERE 1 = 1"); cleaner.execute("DELETE FROM KoboldCamp_Test.asset_statuses WHERE 1 = 1"); cleaner.execute("DELETE FROM KoboldCamp_Test.assets WHERE 1 = 1"); cleaner.execute("DELETE FROM KoboldCamp_Test.authorities WHERE 1 = 1"); cleaner.execute("DELETE FROM KoboldCamp_Test.categories WHERE 1 = 1"); cleaner.execute("DELETE FROM KoboldCamp_Test.user_profiles WHERE 1 = 1"); cleaner.execute("DELETE FROM KoboldCamp_Test.users WHERE 1 = 1"); } @Test public void addDeleteAsset() { Asset na = new Asset(); na.setCategory_id(1); na.setName("Mike Spike"); na.setBrand("Kifaru"); na.setDescription("I LOVE JUnits (pronounced joo-nits)"); na.setStatus_id(1); na.setEmployee_id(1); na.setMember_id(1); na.setNote("Why do I have to write these (in best whiney voice)"); na.setRecord_date("1/2016"); dao.addAsset(na); dao.deleteAsset(na.getAsset_id()); } @Test public void getAllAssets() { Asset na1 = new Asset(); na1.setCategory_id(1); na1.setName("Mike Spike"); na1.setBrand("Kifaru"); na1.setDescription("I LOVE JUnits (pronounced joo-nits)"); na1.setStatus_id(1); na1.setEmployee_id(2); na1.setMember_id(2); na1.setNote("Why do I have to write these (in best whiney voice)"); na1.setRecord_date("1/2016"); Asset na2 = new Asset(); na2.setCategory_id(2); na2.setName("Fred Fry"); na2.setBrand("Coleman"); na2.setDescription("I LOVE JUnits (pronounced joo-nits)"); na2.setStatus_id(1); na2.setEmployee_id(2); na2.setMember_id(2); na2.setNote("Why do I have to write these (in best whiney voice)"); na2.setRecord_date("1/2016"); dao.addAsset(na1); dao.addAsset(na2); List<Asset> aList = dao.getAllAssets(); assertEquals(2, aList.size()); // assertTrue(aList.contains(na1)); // assertTrue(aList.contains(na2)); } @Test public void addDisableEnableUser() { User nu = new User(); nu.setUser_id(4); nu.setUsername("MadMen"); nu.setPassword("Password"); nu.setFirst_name("Jimmy"); nu.setLast_name("John"); nu.setEmail("callmecrazy@calls.com"); nu.setPhone("123-456-789"); nu.setEnabled(1); nu.setAuthority("ROLE_ADMIN"); dao.addUser(nu); dao.disableUser(nu.getUser_id()); dao.enableUser(nu.getUser_id()); } @Test public void getAllEditUsersResetUpdatePassword() { User nu1 = new User(); nu1.setUser_id(1); nu1.setUsername("SeesFar"); nu1.setPassword("CrazyMan"); nu1.setFirst_name("John"); nu1.setLast_name("Johnson"); nu1.setEmail("callmeJohn@calls.com"); nu1.setPhone("123456789"); nu1.setEnabled(1); nu1.setAuthority("ROLE_ADMIN"); User nu2 = new User(); nu2.setUser_id(2); nu2.setUsername("CrazyWild"); nu2.setPassword("Wild-Horse"); nu2.setFirst_name("Jill"); nu2.setLast_name("Jorsen"); nu2.setEmail("callmebabyjill@calls.com"); nu2.setPhone("123-456-789"); nu2.setEnabled(1); nu2.setAuthority("ROLE_USER"); dao.addUser(nu1); dao.addUser(nu2); User nu3 = new User(); nu3.setUsername("FastGuy"); nu3.setFirst_name("Jill"); nu3.setLast_name("Jordan"); nu3.setEmail("callme@calls.com"); nu3.setPhone("123456789"); nu3.setUser_id(2); User nu4 = new User(); nu4.setPassword("cool"); nu4.setUser_id(1); dao.editUser(nu3); dao.resetPassword(2); dao.updatePassword(nu4); List<User> uList = dao.getAllUsers(); assertEquals(4, uList.size()); // assertTrue(uList.contains(nu1)); // assertTrue(uList.contains(nu2)); } }
true
a16e8ad55a920dd2ede9611dd17b02d1d1538b34
Java
ahussan/Problem-Solving-in-Java
/src/main/java/Logical/FindFactorial.java
UTF-8
1,076
3.8125
4
[]
no_license
package Logical; /** * Created by anjalhussan on 10/25/16. */ /* Using the Java language, have the function FirstFactorial(num) take the num parameter being passed and return the Logical of it (e.g. if num = 4, return (4 * 3 * 2 * 1)). For the test cases, the range will be between 1 and 10. Sample Test Cases Input:4 Output:24 Input:8 Output:40320 */ public class FindFactorial { public static void main(String[]args){ System.out.println(firstFactorial(4)); System.out.println(firstFactorial(8)); System.out.println(firstFactorial(-5)); System.out.println(firstFactorial(0)); System.out.println(firstFactorial(10)); } public static int firstFactorial(int num) { int result=0; if (num<0){ System.out.println("Input should be a positive Number"); } else if (num==0) { return result; } else if (num>0) { result=num; for (int i = 1; i <num ; i++) { result = result*i; } } return result; } }
true
3770a0e409897ca872d56ed33259542176edef66
Java
liufangri/ProjectNX
/src/java/com/teamnx/util/CSVToDateBase.java
UTF-8
4,959
2.5625
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.teamnx.util; import com.teamnx.model.Course; import com.teamnx.model.Department; import com.teamnx.model.StudentCourse; import com.teamnx.model.TeacherCourse; import com.teamnx.model.User; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVParser; import org.apache.commons.csv.CSVRecord; /** * * @author Y400 */ public class CSVToDateBase { public static final int USER = 1; public static final int DEPARTMENT = 2; public static final int COURSE = 3; public static final int STUDENT_COURSE = 4; public static final int TEACHER_COURSE = 5; //CSV文件头 private String[] file_header; /** * @param fileName * @param type * @return */ public List readCsvFile(String fileName, int type) { FileReader fileReader = null; CSVParser csvFileParser = null; List list = null; //创建CSVFormat(header mapping) CSVFormat csvFileFormat = CSVFormat.DEFAULT.withHeader(file_header); try { //初始化FileReader object fileReader = new FileReader(fileName); //初始化 CSVParser object csvFileParser = new CSVParser(fileReader, csvFileFormat); //CSV文件records List<CSVRecord> csvRecords = csvFileParser.getRecords(); // CSV switch (type) { case USER: List<User> userList = new ArrayList<User>(); for (int i = 1; i < csvRecords.size(); i++) { CSVRecord record = csvRecords.get(i); //创建用户对象填入数据 User user = new User(); user.setId(record.get("id")); user.setName(record.get("name")); user.setPassword(record.get("password")); user.setDepartment_id(Integer.parseInt(record.get("department_id"))); user.setCharacter(Integer.parseInt(record.get("character"))); user.setClass_id(record.get("class_id")); user.setDepartment_name(record.get("department_name")); userList.add(user); } list = userList; break; case DEPARTMENT: List<Department> departmentList = new ArrayList<Department>(); for (int i = 1; i < csvRecords.size(); i++) { CSVRecord record = csvRecords.get(i); //创建用户对象填入数据 Department department = new Department(); department.setId(Integer.parseInt(record.get("id"))); department.setName(record.get("name")); departmentList.add(department); } list = departmentList; break; case COURSE: List<Course> courseList = new ArrayList<Course>(); for (int i = 1; i < csvRecords.size(); i++) { CSVRecord record = csvRecords.get(i); //创建用户对象填入数据 Course course = new Course(); course.setId(record.get("id")); course.setName(record.get("name")); course.setDepartment_id(Integer.parseInt(record.get("department_id"))); course.setStart_time(Integer.parseInt(record.get("start_time"))); course.setEnd_time(Integer.parseInt(record.get("end_time"))); course.setPosition(record.get("position")); course.setSchedule(record.get("schedule")); course.setYear(Integer.parseInt(record.get("year"))); course.setSemester(Integer.parseInt(record.get("semester"))); int j = Integer.parseInt(record.get("category")); course.setCategory(j == 1 ? true : false); course.setMax_member(Integer.parseInt(record.get("max_member"))); courseList.add(course); } list = courseList; break; case STUDENT_COURSE: List<StudentCourse> studentCourseList = new ArrayList<StudentCourse>(); for (int i = 1; i < csvRecords.size(); i++) { CSVRecord record = csvRecords.get(i); StudentCourse studentCourse = new StudentCourse(); studentCourse.setId(record.get("id")); studentCourse.setCourseId(record.get("course_id")); studentCourse.setStudentId(record.get("student_id")); studentCourseList.add(studentCourse); } list = studentCourseList; break; case TEACHER_COURSE: List<TeacherCourse> teacherCourseList = new ArrayList<TeacherCourse>(); for (int i = 1; i < csvRecords.size(); i++) { CSVRecord record = csvRecords.get(i); TeacherCourse teacherCourse = new TeacherCourse(); teacherCourse.setId(record.get("id")); teacherCourse.setTeacherId(record.get("teacher_id")); teacherCourse.setCourseId(record.get("course_id")); teacherCourseList.add(teacherCourse); } list = teacherCourseList; break; } } catch (Exception e) { e.printStackTrace(); } finally { try { fileReader.close(); csvFileParser.close(); } catch (IOException e) { e.printStackTrace(); } finally { return list; } } } public void setFile_header(String[] file_header) { this.file_header = file_header; } }
true
729fadae30cb55c373433a7fd2a6b224940dbe8d
Java
peymand/spring5webapp
/src/test/java/com/peyman/spring5webapp/controllers/PropertyInjectedControllerTest.java
UTF-8
854
2.265625
2
[]
no_license
package com.peyman.spring5webapp.controllers; import com.peyman.spring5webapp.controllers.di.PropertyInjectedController; import com.peyman.spring5webapp.services.di.GreetingServiceImpl; import junit.framework.Assert; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; /** * Created by Peyman on 12/10/2017. */ public class PropertyInjectedControllerTest { private PropertyInjectedController propertyInjectedController; @Before public void setUp() throws Exception{ this.propertyInjectedController = new PropertyInjectedController(); this.propertyInjectedController.greetingService = new GreetingServiceImpl(); } @Test public void testGreeting() throws Exception{ assertEquals(GreetingServiceImpl.HELLO_GURUS,propertyInjectedController.sayHello()); } }
true
e833ec0238c15f603bd65458be3584716e381212
Java
WclWannaRich/SpringBootCommunity
/src/main/java/com/wclspringboot/community/interceptor/WebConfig.java
UTF-8
1,064
2.015625
2
[]
no_license
/** * Copyright (C), 2015-2019, XXX有限公司 * FileName: WebConfig * Author: Administrator * Date: 19-10-16, 0016 下午 07:12 * Description: * History: * <author> <time> <version> <desc> * 作者姓名 修改时间 版本号 描述 */ package com.wclspringboot.community.interceptor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; /** * 〈一句话功能简述〉<br> * 〈〉 * * @author Administrator * @create 19-10-16, 0016 * @since 1.0.0 */ @Configuration //@EnableWebMvc public class WebConfig implements WebMvcConfigurer { @Autowired private SessionInterceptor sessionInterceptor; public void addInterceptors(InterceptorRegistry registry){ registry.addInterceptor(sessionInterceptor).addPathPatterns("/**"); } }
true
cc9059d43b18a30ef446d40807a0a066f18f7050
Java
sandrocheng/sandro
/project/graphicsExample/src/com/sandro/example/MeshView.java
UTF-8
792
2.296875
2
[]
no_license
package com.sandro.example; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.util.AttributeSet; import android.view.View; public class MeshView extends View{ private Bitmap mBitmap; public MeshView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(context); } public MeshView(Context context, AttributeSet attrs) { super(context, attrs); init(context); } public MeshView(Context context) { super(context); init(context); } private void init(Context context){ mBitmap= BitmapFactory.decodeResource(context.getResources(), R.drawable.rocket_fire); } @Override protected void onDraw(Canvas canvas){ } }
true
431d12a299ee6af79d8a827dc4cf7c05c0381574
Java
codinglzc/JavaProjects
/SpringNotes/src/main/java/com/lzc/annotation/scan/CustomizeComponent.java
UTF-8
282
1.851563
2
[]
no_license
package com.lzc.annotation.scan; import java.lang.annotation.*; /** * <p> * * </p> * * @author Liu Cong * @since 2018-08-08 */ @Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface CustomizeComponent { String value() default ""; }
true
ab4aae18f4b003078c143e744b19e41696bd0776
Java
karls0ns/Java_Project_5
/src/MatrFun2.java
UTF-8
492
2.953125
3
[]
no_license
public class MatrFun2 { public void printRow(int Row, int M[] []){ int i = 0; System.out.println(" "); System.out.print("Row: "); System.out.print(Row); System.out.print(" "); while( i <= M.length-1){ System.out.print(M[Row][i]); System.out.print(" "); i++; try { Thread.sleep(0); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
true
4ffc6fee94e2cce74bbd2ffb122d68b9489cbc53
Java
juanHerrera-Dev/Grupo_15_Tp_Integrador
/test/zonaDeEstacionamiento/TestCaseZonaDeEstacionamiento.java
UTF-8
1,268
2.625
3
[]
no_license
package zonaDeEstacionamiento; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.mock; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import ventas.PuntoDeVenta; class TestCaseZonaDeEstacionamiento { ZonaDeEstacionamiento zonaX; Inspector inspectorDeZonaX; PuntoDeVenta puntoDeVentaX; @BeforeEach void setUp() throws Exception { inspectorDeZonaX=mock(Inspector.class); puntoDeVentaX=mock(PuntoDeVenta.class); zonaX= new ZonaDeEstacionamiento(1,inspectorDeZonaX); } @Test void testCuandoUnaZonaDeEstacionamientoEsCreadaNoTieneNingunPuntoDeVentaPeroSiTieneAsignadoUnInspector() { assertEquals(1,zonaX.getId()); assertEquals(inspectorDeZonaX,zonaX.getInspector()); assertEquals(0,zonaX.getPuntosDeVentas().size()); } @Test void testUnaZonaDeEstacionamientoPuedeRegistrarUnPuntoDeVenta() { zonaX.registrarPuntoDeVenta(puntoDeVentaX); assertEquals(1,zonaX.getPuntosDeVentas().size()); } @Test void testUnaZonaDeEstacionamientoNoPuedeRegistrarUnPuntoDeVentaSiEsteExistePreviamente() { zonaX.registrarPuntoDeVenta(puntoDeVentaX); assertThrows(IllegalArgumentException.class, () -> zonaX.registrarPuntoDeVenta(puntoDeVentaX)); } }
true
d8be96732c6a48d48eb405a67e7b3598fa8bde52
Java
phanibuddi9/SpringBootHazelcastSpring
/src/test/java/com/cav/spring/service/bank/repository/BankRepositoryTest.java
UTF-8
3,251
2.046875
2
[]
no_license
package com.cav.spring.service.bank.repository; import java.math.BigDecimal; import java.sql.Timestamp; import java.time.LocalDate; import java.time.LocalDateTime; import java.util.Date; import java.util.Iterator; import java.util.List; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringRunner; import com.cav.spring.service.bank.entity.Account; import com.cav.spring.service.bank.entity.Bank; import com.cav.spring.service.bank.entity.Fund; import com.cav.spring.service.bank.model.accounts.AccountId; import com.cav.spring.service.bank.model.accounts.AccountPOJO; import com.cav.spring.service.bank.model.accounts.Accounts; import com.cav.spring.service.bank.model.banks.BankId; import com.cav.spring.service.bank.model.banks.BankPOJO; import com.cav.spring.service.bank.model.banks.BankRequest; import com.cav.spring.service.bank.model.banks.Banks; import com.cav.spring.service.bank.model.funds.FundId; import com.cav.spring.service.bank.model.funds.Funds; import com.cav.spring.service.bank.service.BankService; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class BankRepositoryTest extends AbstractRepositoryTest { @Before public void setUp(){ super.setUp(); } @After public void cleanUp(){ super.cleanUp(); } @Test public void testCreateBank(){ Banks banks = bankRepository.listBanks(createBankIds(DEFAULT_BANK_ID)); assertEquals(DEFAULT_BANK_ID,banks.getBankList().iterator().next().getBankId()); } @Test public void testUpdateBank(){ BankPOJO bank = createBank(DEFAULT_BANK_ID); bank.setBankName("UpDatedBankName"); Banks banks = new Banks(); banks.getBankList().add(bank); bankRepository.updateBanks(banks.getBankList()); banks = bankRepository.listBanks(createBankIds(DEFAULT_BANK_ID)); bank = banks.getBankList().iterator().next(); assertEquals(DEFAULT_BANK_ID,bank.getBankId()); assertEquals("UpDatedBankName",bank.getBankName()); } @Test public void addSecondAccountToBank(){ List<BankPOJO> bankList = createNewAccount(DEFAULT_BANK_ID,NEW_ACCOUNT_ID); Banks banks = new Banks(); banks.setBankList(bankList); bankRepository.updateBanks(banks.getBankList()); banks = bankRepository.listBanks(createBankIds(DEFAULT_BANK_ID)); BankPOJO bank = banks.getBankList().iterator().next(); assertEquals(DEFAULT_BANK_ID,bank.getBankId()); List <AccountPOJO> accountList= bank.getAccounts().getAccountsList(); assertEquals(2 , accountList.size()); } @Test public void removeAccountFromBank(){ bankRepository.removeAccounts(createBankAccountIds(DEFAULT_BANK_ID, DEFAULT_ACCOUNT_ID)); Banks banks = bankRepository.listBanks(createBankIds(DEFAULT_BANK_ID)); BankPOJO bank = banks.getBankList().iterator().next(); assertEquals(DEFAULT_BANK_ID,bank.getBankId()); assertTrue(bank.getAccounts().getAccountsList().isEmpty()); } }
true
95f4fda4dadb113afef34ef55223ca9f517abf21
Java
oteplova/AT_Bootcamp
/src/main/java/net/comments/sample/App.java
UTF-8
2,852
3.78125
4
[]
no_license
package net.comments.sample; import java.util.ArrayList; import java.util.List; public class App { public static void main(String[] args) { // Arrays with student's and teacher's names String[] studentNamesAttentive = {"Andrey", "Nastya", "Dima", "Kolya"}; String[] studentNamesBad = {"Anya", "Vova", "Zina"}; String[] teacherNames = {"Ivan", "Petro"}; List<Student> studentList = new ArrayList(); List<Teacher> teacherList = new ArrayList(); Subject gitSubject = new TechSubject(); Subject cookingSubject = new CookerySubject(); Room limitedRoom = new TrainingRoomLimited(6); Room unlimitedRoom = new TrainingRoomUnlimited(); // Fill collection with Student's objects for (String studentName : studentNamesAttentive) { studentList.add(new AttentiveStudent(studentName)); } // Fill collection with Student's objects for (String studentName : studentNamesBad) { studentList.add(new BadStudent(studentName)); } // Fill collection with Teacher's objects for (String teacherName : teacherNames) { teacherList.add(new MultiTeacher(teacherName)); } // Allows Persons (Students, Teachers) to come into the room to study/teach the subgect enterInToRoom(studentList, teacherList, limitedRoom, gitSubject); enterInToRoom(studentList, teacherList, unlimitedRoom, cookingSubject); } private static void go(Student someone, Subject someSubject) { System.out.println(String.format("There is %s in the room!", someone.getName())); someone.learn(someSubject); } private static void say(Teacher someone, Subject someSubject) { System.out.println(String.format("There is the teacher %s in the room!", someone.getName())); someone.teach(someSubject); } private static void enterInToRoom(List<Student> someStudent, List<Teacher> someTeacher, Room someRoom, Subject someSubject) { for (Student student : someStudent) { someRoom.accept(student); System.out.println("--------------------------------------"); } for (Teacher teacher : someTeacher) { someRoom.accept(teacher); System.out.println("--------------------------------------"); } for (Person somePerson : someRoom.getEnteredPerson()) { if (somePerson instanceof Student) { go((Student) somePerson, someSubject); System.out.println("--------------------------------------"); } else if (somePerson instanceof Teacher) { say((Teacher) somePerson, someSubject); System.out.println("--------------------------------------"); } } } }
true
1ccf8016cc9057a9028b9bcf2555d2f3917c1600
Java
fengqsqd/Parent
/violetproduct-swing/src/main/java/com/horstmann/violet/application/StepFourTestCase/TestCaseMatrixPanel.java
GB18030
4,638
2.4375
2
[]
no_license
package com.horstmann.violet.application.StepFourTestCase; import java.awt.BasicStroke; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GridBagLayout; import java.awt.GridLayout; import java.awt.Stroke; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.ImageIcon; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTable; import org.junit.Test.None; import com.horstmann.violet.application.gui.GBC; import com.horstmann.violet.application.gui.MainFrame; public class TestCaseMatrixPanel extends JPanel{ private JPanel titlePanel; private JPanel titleTabel; private JPanel gapPanel; private JLabel reduceTabel; private JPanel panel; private JPanel tabelPanel; private JLabel Predict; private TestCaseTabelPanel titleCaseTabelPanel; private TestCaseTabelPanel testCaseTabelPanel; private MainFrame mainFrame; public TestCaseMatrixPanel(MainFrame mainFrame) { this.mainFrame = mainFrame; initComponent(); // this.setBackground(Color.green); this.setLayout(new GridBagLayout()); this.add(titlePanel, new GBC(0, 0).setFill(GBC.BOTH).setWeight(1, 0)); this.add(panel, new GBC(0, 1).setFill(GBC.BOTH).setWeight(1, 1).setInsets(10, 0, 0, 0)); this.setBackground(Color.white); } private void initComponent() { Predict = new JLabel("ִн:"); Predict.setFont(new Font("΢ź", Font.BOLD, 16)); titlePanel = new JPanel() { public void paint(Graphics g) { super.paint(g); java.awt.Rectangle rect = this.getBounds(); int width = (int) rect.getWidth() - 1; int height = (int) rect.getHeight() - 1; Graphics2D g2 = (Graphics2D)g; g2.setStroke(new BasicStroke(3f)); g2.setColor(new Color(188,188,188)); Stroke dash = new BasicStroke(2.5f,BasicStroke.CAP_BUTT,BasicStroke.JOIN_ROUND, 3.5f,new float[]{15,10,},0f); g2.setStroke(dash); g2.drawLine(0, height, width, height); } }; gapPanel = new JPanel(); titleTabel = new JPanel(); titleTabel.setLayout(new BorderLayout()); reduceTabel = new JLabel(); reduceTabel.setFont(new Font("", Font.PLAIN, 18)); tabelPanel = new JPanel(); tabelPanel.setLayout(new BorderLayout()); JPanel panel1 = new JPanel(); panel1.setBackground(Color.white); panel = new JPanel(); panel.setLayout(new GridBagLayout()); panel.add(Predict,new GBC(0, 0,1,1).setFill(GBC.BOTH).setWeight(0, 0).setInsets(0, 5, 8, 0)); panel.add(panel1,new GBC(1, 0,1,1).setFill(GBC.BOTH).setWeight(1, 0)); panel.add(tabelPanel, new GBC(0, 1,2,1).setFill(GBC.BOTH).setWeight(1, 1)); panel.setBackground(Color.white); panel.setVisible(false); reduceTabel.setIcon(new ImageIcon("resources/icons/16x16/smallDown.png")); reduceTabel.setMinimumSize(new Dimension(13, 13)); reduceTabel.setMaximumSize(new Dimension(13, 13)); reduceTabel.setPreferredSize(new Dimension(13, 13)); reduceTabel.setBackground(Color.red); reduceTabel.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { // TODO Auto-generated method stub if(panel.isVisible()) { panel.setVisible(false); } else { panel.setVisible(true); } mainFrame.renewPanel(); } }); titlePanel.setLayout(new GridBagLayout()); titlePanel.add(titleTabel,new GBC(0, 0).setFill(GBC.BOTH).setWeight(1, 0).setInsets(5)); titlePanel.add(reduceTabel,new GBC(1, 0).setFill(GBC.NONE).setWeight(0, 1).setInsets(5)); } public JPanel getTitleTabel() { return titleTabel; } public JPanel getTabelPanel() { return tabelPanel; } public TestCaseTabelPanel getTitleCaseTabelPanel() { return titleCaseTabelPanel; } public void setTitleCaseTabelPanel(TestCaseTabelPanel titleCaseTabelPanel) { this.titleCaseTabelPanel = titleCaseTabelPanel; } public TestCaseTabelPanel getTestCaseTabelPanel() { return testCaseTabelPanel; } public void setTestCaseTabelPanel(TestCaseTabelPanel testCaseTabelPanel) { this.testCaseTabelPanel = testCaseTabelPanel; } public JLabel getPredict() { return Predict; } }
true
a72ef3b97dd1008b2ef3a3ccb6dc9e14d046d4b6
Java
shukdebp/webrtc
/src/main/java/com/pwc/r2p2/ui/controller/BPMRestController.java
UTF-8
5,764
1.828125
2
[]
no_license
package com.pwc.r2p2.ui.controller; import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.camunda.bpm.engine.HistoryService; import org.camunda.bpm.engine.ManagementService; import org.camunda.bpm.engine.ProcessEngine; import org.camunda.bpm.engine.ProcessEngines; import org.camunda.bpm.engine.RuntimeService; import org.camunda.bpm.engine.TaskService; import org.camunda.bpm.engine.history.HistoricTaskInstance; import org.camunda.bpm.engine.history.HistoricTaskInstanceQuery; import org.camunda.bpm.engine.task.TaskQuery; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.pwc.r2p2.pojo.R2P2Task; import com.pwc.r2p2.pojo.RequestDetails; @Controller @RequestMapping("/bpm") public class BPMRestController implements ApplicationContextAware { private static final Logger log = LogManager.getLogger(BPMRestController.class.getName()); private ApplicationContext applicationContext; @RequestMapping(value = "/fetchHistoryTask", method = RequestMethod.POST, produces = "application/json") public @ResponseBody ServiceResponse fetchHistoryTask(@RequestBody RequestDetails requestDetails, HttpServletRequest request) { if (log.isDebugEnabled()) { log.debug("Start method: BPMRestController.fetchHistoryTask()"); } ServiceResponse res = null; System.out.println("test"); ProcessEngine processEngine = null; TaskService taskService = null; RuntimeService runtimeService = null; TaskQuery createTaskQuery = null; try { String tertiaryCategoryId = requestDetails.getTertiaryCategoryId(); String requestId = requestDetails.getRequestId(); String requester = requestDetails.getRequester(); String taskName = requestDetails.getTaskName(); processEngine = ProcessEngines.getDefaultProcessEngine(); runtimeService = processEngine.getRuntimeService(); ManagementService managementService = processEngine.getManagementService(); taskService = processEngine.getTaskService(); createTaskQuery = taskService.createTaskQuery(); HistoryService historyService = processEngine.getHistoryService(); HistoricTaskInstanceQuery finished = historyService.createHistoricTaskInstanceQuery().finished(); // HistoricTaskInstanceQuery processInstanceBusinessKey = // finished.processInstanceBusinessKey("requestId"); List<HistoricTaskInstance> historicProcessInstance = finished .processVariableValueEquals("requester", requester).taskName(taskName).list(); ArrayList<R2P2Task> taskArr = new ArrayList<>(); for (int i = 0; i < historicProcessInstance.size(); i++) { R2P2Task task = new R2P2Task(); HistoricTaskInstance historicTaskInstance = historicProcessInstance.get(i); String id = historicTaskInstance.getId(); String name = historicTaskInstance.getName(); String assignee = historicTaskInstance.getAssignee(); task.setId(id); task.setName(name); task.setAssignee(assignee); System.out.println(historicTaskInstance); System.out.println("Variable for this instance+++++++++++++"); // List<HistoricVariableInstance> HistoricVariableInstance = // historyService // .createHistoricVariableInstanceQuery() // .processInstanceId(historicTaskInstance.getProcessInstanceId()).orderByVariableName().desc().list(); String isJBR = historyService.createHistoricVariableInstanceQuery() .processInstanceId(historicTaskInstance.getProcessInstanceId()).variableName("isJBR") .singleResult().getValue().toString(); String isNIS = historyService.createHistoricVariableInstanceQuery() .processInstanceId(historicTaskInstance.getProcessInstanceId()).variableName("isNIS") .singleResult().getValue().toString(); String sortValue = historyService.createHistoricVariableInstanceQuery() .processInstanceId(historicTaskInstance.getProcessInstanceId()).variableName("sortValue") .singleResult().getValue().toString(); task.setIsJBR(isJBR); task.setIsNIS(isNIS); task.setSortValue(sortValue); // for (int j = 0; j < HistoricVariableInstance.size(); j++) { // System.out.println(HistoricVariableInstance.get(j)); // } taskArr.add(task); } Collections.sort(taskArr); System.out.println("Sorted:"); for (int i = 0; i < taskArr.size(); i++) { R2P2Task task1 = new R2P2Task(); task1 = (R2P2Task) taskArr.get(i); System.out.println(task1.getSortValue()); } res = new ServiceResponse("success", null, taskArr); } catch (Exception e) { log.error("Exception occured during fetchHistoryTask -- ", e); res = new ServiceResponse("success", null, "Exception occured during fetchHistoryTask as "+ e.getMessage()); e.printStackTrace(); } if (log.isDebugEnabled()) { log.debug("End method: BPMRestController.fetchHistoryTask()"); } return res; } @Override public void setApplicationContext(ApplicationContext appContext) throws BeansException { this.applicationContext = appContext; } public ApplicationContext getApplicationContext() throws BeansException { return this.applicationContext; } }
true
436603773498536589b4616ad297ccdd78b83603
Java
njustesen/tbsc
/src/main/java/tbsc/shared/model/game/GameStatus.java
UTF-8
98
1.65625
2
[ "MIT" ]
permissive
package tbsc.shared.model.game; public enum GameStatus { CREATED, STARTED, OVER, DECLINED; }
true
2761a23b60ddb82631b2712a321aabf14b32ac60
Java
ermakovmaxim/aQute
/aQute.libsync/src/aQute/impl/library/LibraryImporterImpl.java
UTF-8
4,509
1.953125
2
[]
no_license
package aQute.impl.library; import java.io.*; import java.net.*; import java.util.concurrent.*; import java.util.regex.*; import aQute.impl.library.LibraryImpl.ProgramImpl; import aQute.impl.library.LibraryImpl.RevisionImpl; import aQute.lib.data.*; import aQute.lib.io.*; import aQute.libg.cryptography.*; import aQute.libg.reporter.Messages.ERROR; import aQute.libg.reporter.Messages.WARNING; import aQute.libg.reporter.*; import aQute.service.library.*; import aQute.service.library.Library.Importer; import aQute.service.library.Library.Revision; import aQute.service.library.Library.RevisionRef; import aQute.service.reporter.*; public class LibraryImporterImpl extends ReporterAdapter implements Library.Importer { final LibraryImpl parent; String uniqueId; Callable<InputStream> getter; boolean existed; String path; final URI url; File file; interface ImporterMessages { ERROR CouldNotImport_(String uniqueId); ERROR AlreadyImported_(String uniqueId); ERROR Revision__ExistsAsMaster(String bsn, String version); ERROR Revision_EqualsSameVersion_AsAlreadyImportedFrom_(String bsn, String version, String url); ERROR Revision_OlderVersion_AsAlreadyImportedFrom_(String bsn, String version, URL url); WARNING AlreadyImported_(URI url); ERROR RequiredField_IsNull(String name); ERROR InvalidField_Value_(String name, Object field); } final ImporterMessages messages = ReporterMessages.base(this, ImporterMessages.class); String owner; String message; public LibraryImporterImpl(LibraryImpl parent, URI url) { this.parent = parent; this.url = url; } public Revision fetch() throws Exception { File file = getFile(); String sha = digest(file); RevisionImpl revision = parent.revisions.find("_id=%s", sha).one(); if (revision != null) { messages.AlreadyImported_(url); return revision; } revision = new RevisionImpl(); revision._id = sha; revision.url = url; revision.owner = owner; revision.message = message; for (MetadataProvider md : parent.mdps) { trace("parsing %s with %s", revision.url, md); Report report = md.parser(LibraryImporterImpl.this, revision); getInfo(report); } verify(revision); if (!isOk()) return null; // TODO classifier RevisionImpl previous = parent.revisions .find("&(bsn=%s)(version.base=%s)", revision.bsn, revision.version.base).one(); if (previous != null && previous.master) { messages.Revision__ExistsAsMaster(revision.bsn, revision.version.base); return null; } parent.revisions.insert(revision); ProgramImpl program = parent.programs.find("_id=%s", revision.bsn).one(); RevisionRef reference = new RevisionRef(revision); if (program == null) { program = new ProgramImpl(); program._id = revision.bsn; data.assignIfNotSet(revision, program, "docUrl", "vendor", "description", "icon"); program.revisions.add(reference); parent.programs.insert(program); } else { program.revisions.remove(reference); program.revisions.add(0, reference); program.lastImport = reference.revision; int n = parent.programs // .find(program) // .set("revisions", program.revisions) // .set("lastImport", program.lastImport) // .update(); if (n != 1) error("Could not update program %s in database, count was %d", program._id, n); } return revision; } private String digest(File file) throws Exception { Digester<SHA1> digester = SHA1.getDigester(); IO.copy(file, digester); return digester.digest().asHex(); } public File getFile() throws Exception { return parent.fileCache.get(url.toString(), url); } /** * Verify that all necessary fields are set, have the proper format etc. * * @param rev */ private void verify(Revision rev) { check(rev.bsn, "bsn", aQute.lib.osgi.Verifier.SYMBOLICNAME); if (rev.version == null) { messages.RequiredField_IsNull("version"); return; } check(rev.version.base, "version.base", aQute.lib.osgi.Verifier.VERSION); } private void check(Object field, String name, Pattern pattern) { if (field == null) { messages.RequiredField_IsNull(name); } if (pattern.matcher(name.toString()).matches()) return; messages.InvalidField_Value_(name, field); } @Override public Importer owner(String email) { owner = email; return this; } @Override public Importer message(String message) { this.message = message; return this; } @Override public URI getURL() { return url; } }
true
1e4ea740e5256d623d48a5130fb7f97b59454492
Java
sureshrmdec/Algorithm-Java
/src/combinationSum4.java
UTF-8
724
3.015625
3
[]
no_license
import java.util.Arrays; /** * Created by xhu on 11/17/16. */ public class combinationSum4 { int count =0; public int combinationSum4(int[] nums, int target) { if (nums == null || nums.length == 0) { return 0; } int[] sum = new int[target + 1]; // sum[i] means the total number of combinatation which sum equal to i sum[0] = 1; for (int i = 1; i <= target; i++) { int count = 0; for(int j = 0; j<nums.length;j++){ if(i-nums[j]>=0){ count = count + sum[i-nums[j]]; } } sum[i] = count; } return sum[target]; } }
true
6b29e9f5d54342cac9603db12a77ce23f9235c28
Java
yuzhijia88/yes-cart
/web/support/src/main/java/org/yes/cart/cluster/service/impl/BackdoorServiceImpl.java
UTF-8
14,674
1.703125
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2009 Denys Pavlov, Igor Azarnyi * * 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.yes.cart.cluster.service.impl; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.math.NumberUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.yes.cart.cache.CacheBundleHelper; import org.yes.cart.cluster.node.NodeService; import org.yes.cart.cluster.service.BackdoorService; import org.yes.cart.cluster.service.WarmUpService; import org.yes.cart.config.ConfigurationListener; import org.yes.cart.constants.AttributeNamesKeys; import org.yes.cart.dao.GenericFTSCapableDAO; import org.yes.cart.domain.entity.Product; import org.yes.cart.search.dao.IndexBuilder; import org.yes.cart.service.domain.ProductService; import org.yes.cart.service.domain.SystemService; import org.yes.cart.util.DateUtils; import org.yes.cart.utils.impl.ObjectUtil; import java.io.Serializable; import java.time.Instant; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * User: Igor Azarny iazarny@yahoo.com * Date: 1/28/12 * Time: 10:02 AM */ public class BackdoorServiceImpl implements BackdoorService { private static final long serialVersionUID = 20130820L; private static final Logger LOG = LoggerFactory.getLogger(BackdoorServiceImpl.class); private static final String INDEX_DONE_STATUS = "DONE"; private static final String INDEX_RUNNING_STATUS = "RUNNING"; private static final Object[] INDEX_DISABLED_STATUS = new Object[] { INDEX_DONE_STATUS, 0 }; private ProductService productService; private SystemService systemService; private CacheBundleHelper productIndexCaches; private WarmUpService warmUpService; private NodeService nodeService; private List<ConfigurationListener> configurationListeners; /* * Once a product is reindexed we need to flush all cached information * to enforce changes to take immediate effect on the storefront. */ private void flushCache() { productIndexCaches.flushBundleCaches(); } /** * {@inheritDoc} */ @Override public boolean ping() { return true; } /** * {@inheritDoc} */ @Override public void warmUp() { warmUpService.warmUp(); } Boolean isLuceneIndexDisabled() { return nodeService.getCurrentNode().isFtIndexDisabled(); } /** * {@inheritDoc} */ @Override public Object[] getProductReindexingState() { if (isLuceneIndexDisabled()) { return INDEX_DISABLED_STATUS; } final IndexBuilder.FTIndexState state = productService.getProductsFullTextIndexState(); if (state.isFullTextSearchReindexCompleted()) { flushCache(); return new Object[] { INDEX_DONE_STATUS, state.getLastIndexCount() }; } return new Object[] { INDEX_RUNNING_STATUS, state.getLastIndexCount() }; } /** * {@inheritDoc} */ @Override public Object[] getProductSkuReindexingState() { if (isLuceneIndexDisabled()) { return INDEX_DISABLED_STATUS; } final IndexBuilder.FTIndexState state = productService.getProductsSkuFullTextIndexState(); if (state.isFullTextSearchReindexCompleted()) { flushCache(); return new Object[] { INDEX_DONE_STATUS, state.getLastIndexCount() }; } return new Object[] { INDEX_RUNNING_STATUS, state.getLastIndexCount() }; } /** * {@inheritDoc} */ @Override public void reindexAllProducts() { if (!isLuceneIndexDisabled()) { try { final Instant now = Instant.now(); final String inventoryChangeLastKey = "JOB_PRODINVUP_LR_" + nodeService.getCurrentNodeId(); final String lastRun = systemService.getAttributeValue(inventoryChangeLastKey); if (StringUtils.isBlank(lastRun) || DateUtils.iParseSDT(lastRun).isBefore(now)) { // Ensure that product inventory changes have last date which corresponds to indexing start time systemService.updateAttributeValue(inventoryChangeLastKey, DateUtils.formatSDT(now)); } } catch (Exception exp) { LOG.error("Unable to update JOB_PRODINVUP_LR_X: " + exp.getMessage(), exp); } productService.reindexProducts(getProductIndexBatchSize()); } } /** * {@inheritDoc} */ @Override public void reindexAllProductsSku() { if (!isLuceneIndexDisabled()) { productService.reindexProductsSku(getProductIndexBatchSize()); } } /** * {@inheritDoc} */ @Override public void reindexShopProducts(final long shopPk) { if (!isLuceneIndexDisabled()) { productService.reindexProducts(shopPk, getProductIndexBatchSize()); } } /** * {@inheritDoc} */ @Override public void reindexShopProductsSku(final long shopPk) { if (!isLuceneIndexDisabled()) { productService.reindexProductsSku(shopPk, getProductIndexBatchSize()); } } /** * {@inheritDoc} */ @Override public void reindexProduct(final long productPk) { if (!isLuceneIndexDisabled()) { productService.reindexProduct(productPk); } } /** * {@inheritDoc} */ @Override public void reindexProductSku(final long productPk) { if (!isLuceneIndexDisabled()) { productService.reindexProductSku(productPk); } } /** * {@inheritDoc} */ @Override public void reindexProductSkuCode(final String productCode) { if (!isLuceneIndexDisabled()) { productService.reindexProductSku(productCode); } } /** * {@inheritDoc} */ @Override public void reindexProducts(final long[] productPks) { if (!isLuceneIndexDisabled()) { for (long pk : productPks) { productService.reindexProduct(pk); } } } /** * {@inheritDoc} */ @Override public List<Object[]> sqlQuery(final String query) { if (StringUtils.isNotBlank(query)) { if (query.toLowerCase().contains("select ")) { return ObjectUtil.transformTypedResultListToArrayList(getGenericDao().executeNativeQuery(query)); } else { return Collections.singletonList(ObjectUtil.escapeXml(getGenericDao().executeNativeUpdate(query))); } } return Collections.EMPTY_LIST; } /** * {@inheritDoc} */ @Override public List<Object[]> hsqlQuery(final String query) { if (StringUtils.isNotBlank(query)) { if (query.toLowerCase().contains("select ")) { final List queryRez = getGenericDao().executeHsqlQuery(query); return ObjectUtil.transformTypedResultListToArrayList(queryRez); } else { return ObjectUtil.transformTypedResultListToArrayList(getGenericDao().executeHsqlQuery(query)); } } return Collections.emptyList(); } /** * {@inheritDoc} */ @Override public List<Object[]> ftQuery(final String query) { if (!isLuceneIndexDisabled()) { return ObjectUtil.transformTypedResultListToArrayList(getGenericDao().fullTextSearchRaw(query)); } return new ArrayList<>(Collections.singletonList(new String[] { "FT is disabled on this node ..." })); } /** * {@inheritDoc} */ @Override public void reloadConfigurations() { if (CollectionUtils.isNotEmpty(this.configurationListeners)) { for (final ConfigurationListener listener : this.configurationListeners) { listener.reload(); } } } /** * IoC. node service * * @param nodeService node service to use */ public void setNodeService(final NodeService nodeService) { this.nodeService = nodeService; this.nodeService.subscribe("BackdoorService.ping", message -> { BackdoorServiceImpl.this.ping(); return "OK"; }); this.nodeService.subscribe("BackdoorService.warmUp", message -> { BackdoorServiceImpl.this.warmUp(); return "OK"; }); this.nodeService.subscribe("BackdoorService.getProductReindexingState", message -> BackdoorServiceImpl.this.getProductReindexingState()); this.nodeService.subscribe("BackdoorService.getProductSkuReindexingState", message -> BackdoorServiceImpl.this.getProductSkuReindexingState()); this.nodeService.subscribe("BackdoorService.reindexAllProducts", message -> { BackdoorServiceImpl.this.reindexAllProducts(); return "OK"; }); this.nodeService.subscribe("BackdoorService.reindexAllProductsSku", message -> { BackdoorServiceImpl.this.reindexAllProductsSku(); return "OK"; }); this.nodeService.subscribe("BackdoorService.reindexShopProducts", message -> { BackdoorServiceImpl.this.reindexShopProducts((Long) message.getPayload()); return "OK"; }); this.nodeService.subscribe("BackdoorService.reindexShopProductsSku", message -> { BackdoorServiceImpl.this.reindexShopProductsSku((Long) message.getPayload()); return "OK"; }); this.nodeService.subscribe("BackdoorService.reindexProduct", message -> { BackdoorServiceImpl.this.reindexProduct((Long) message.getPayload()); return "OK"; }); this.nodeService.subscribe("BackdoorService.reindexProductSku", message -> { BackdoorServiceImpl.this.reindexProductSku((Long) message.getPayload()); return "OK"; }); this.nodeService.subscribe("BackdoorService.reindexProductSkuCode", message -> { BackdoorServiceImpl.this.reindexProductSkuCode((String) message.getPayload()); return "OK"; }); this.nodeService.subscribe("BackdoorService.reindexProducts", message -> { BackdoorServiceImpl.this.reindexProducts((long[]) message.getPayload()); return "OK"; }); this.nodeService.subscribe("BackdoorService.sqlQuery", message -> { try { return new ArrayList<Serializable[]>((List) self().sqlQuery((String) message.getPayload())); } catch (Exception e) { final String msg = "Cant parse SQL query : " + message.getPayload() + " Error : " + e.getMessage(); LOG.warn(msg); return new ArrayList<>(Collections.singletonList(new Serializable[]{e.getMessage()})); } }); this.nodeService.subscribe("BackdoorService.hsqlQuery", message -> { try { return new ArrayList<Serializable[]>((List) self().hsqlQuery((String) message.getPayload())); } catch (Exception e) { final String msg = "Cant parse HQL query : " + message.getPayload() + " Error : " + e.getMessage(); LOG.warn(msg); return new ArrayList<>(Collections.singletonList(new Serializable[]{e.getMessage()})); } }); this.nodeService.subscribe("BackdoorService.ftQuery", message -> { try { return new ArrayList<Serializable[]>((List) self().ftQuery((String) message.getPayload())); } catch (Exception e) { final String msg = "Cant parse FT query : " + message.getPayload() + " Error : " + e.getMessage(); LOG.warn(msg); return new ArrayList<>(Collections.singletonList(new Serializable[]{e.getMessage()})); } }); this.nodeService.subscribe("BackdoorService.reloadConfigurations", message -> { BackdoorServiceImpl.this.reloadConfigurations(); return "OK"; }); } /** * IoC. Set warn up service. * * @param warmUpService warm up service to use. */ public void setWarmUpService(final WarmUpService warmUpService) { this.warmUpService = warmUpService; } /** * IoC. Set product service. * * @param productService product service to use. */ public void setProductService(final ProductService productService) { this.productService = productService; } /** * IoC. Set product service. * * @param systemService service to use. */ public void setSystemService(final SystemService systemService) { this.systemService = systemService; } /** * IoC. Product index bundle helper * * @param productIndexCaches product index bundle helper */ public void setProductIndexCaches(final CacheBundleHelper productIndexCaches) { this.productIndexCaches = productIndexCaches; } /** * IoC. Set configuration listener. * * @param configurationListeners configuration listener. */ public void setConfigurationListeners(final List<ConfigurationListener> configurationListeners) { this.configurationListeners = configurationListeners; } @SuppressWarnings("unchecked") private GenericFTSCapableDAO<Product, Long, Object> getGenericDao() { return (GenericFTSCapableDAO) productService.getGenericDao(); } private int getProductIndexBatchSize() { return NumberUtils.toInt(systemService.getAttributeValue(AttributeNamesKeys.System.JOB_REINDEX_PRODUCT_BATCH_SIZE), 100); } private BackdoorService self; private BackdoorService self() { if (self == null) { self = getSelf(); } return self; } /** * Spring IoC. * * @return spring look up */ public BackdoorService getSelf() { return null; } }
true
424ef8612a273f1f9028abff877a0aba190775a3
Java
jhump/arquebus
/core/src/main/java/com/bluegosling/arquebus/core/controller/VehicleController.java
UTF-8
2,957
2.515625
3
[ "Apache-2.0" ]
permissive
package com.bluegosling.arquebus.core.controller; import com.bluegosling.arquebus.core.model.VehicleModel; import com.bluegosling.arquebus.core.view.GameView; import playn.core.Keyboard; import playn.core.Keyboard.KeyEvent; import playn.core.Mouse; import playn.core.Mouse.ButtonEvent; import playn.core.Mouse.Event; import playn.core.Mouse.MotionEvent; import playn.core.Platform; import react.SignalView.Listener; public class VehicleController { public VehicleController(Platform plat, final VehicleModel vehicle, final GameView gameView) { // TODO: no hardware keyboard? touch buttons instead // TODO: analog controls of some sort? plat.input().keyboardEvents.connect(new Keyboard.KeySlot() { private boolean forward = false; private boolean back = false; @Override public void onEmit(KeyEvent event) { if (event.down) { switch (event.key) { case W: case D: case RIGHT: forward = true; vehicle.setThrottle(1); break; case S: case A: case LEFT: back = true; vehicle.setThrottle(-1); break; case R: vehicle.reset(); default: // nothing } } else { switch (event.key) { case W: case D: case RIGHT: forward = false; vehicle.setThrottle(back ? -1 : 0); break; case S: case A: case LEFT: back = false; vehicle.setThrottle(forward ? 1 : 0); break; default: // nothing } } } }); // TODO: use mouse for turret to track cursor location and for clicking (shooting) plat.input().mouseEvents.connect(new Listener<Mouse.Event>() { @Override public void onEmit(Event event) { if (event instanceof ButtonEvent) { ButtonEvent e = (ButtonEvent) event; switch (e.button) { case LEFT: vehicle.setMainFiring(e.down); break; case RIGHT: vehicle.setAlternateFiring(e.down); break; default: } } else if (event instanceof MotionEvent) { gameView.setPointerViewPosition(event.x(), event.y()); } } }); // TODO: use touch for shooting (when no mouse) // TODO: use touch buttons for forward/backward (when no keyboard) //plat.input().touchEvents.connect(...); // TODO: use pointer for updating turret location when shooting (when no mouse) //new Pointer(plat).events.connect(...); } }
true
9d97420d4469028c4f931b86e457f05683106094
Java
Yuanyang-Che/CSCI-201-FP
/src/main/java/edu/usc/csci/boneapptheteeth/mvc/LoginRegisterController.java
UTF-8
2,814
2.328125
2
[]
no_license
package edu.usc.csci.boneapptheteeth.mvc; import edu.usc.csci.boneapptheteeth.model.UserInfo; import edu.usc.csci.boneapptheteeth.model.UserInfoRepository; import edu.usc.csci.boneapptheteeth.mvc.dto.LoginForm; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import java.util.Optional; @Controller public class LoginRegisterController { @Autowired UserInfoRepository userInfoRepository; @RequestMapping("/") public String index() { return "login"; } //to get login page @RequestMapping(value = "/login", method = RequestMethod.GET) public String getLoginForm() { return "login"; } //checking for login credentials @RequestMapping(value = "/login", method = RequestMethod.POST) public String login(@ModelAttribute("loginForm") LoginForm loginForm, Model model) { String email = loginForm.getEmail(); String password = loginForm.getPassword(); Optional<UserInfo> userInfo = userInfoRepository.findById(email); if (!userInfo.isPresent()) { //not found model.addAttribute("invalidCredentials", true); return "login"; } else { UserInfo user = userInfo.get(); String correct_pw = user.getPassword(); if (correct_pw.equalsIgnoreCase(password)) { return "home"; } else { model.addAttribute("invalidCredentials", true); return "login"; } } } @RequestMapping(value = "/register", method = RequestMethod.GET) public String getRegisterForm() { return "register"; } @RequestMapping(value = "/register", method = RequestMethod.POST) public String register(@ModelAttribute("registerForm") UserInfo createdUser, Model model) { String email = createdUser.getEmail(); String userName = createdUser.getUserName(); String password = createdUser.getPassword(); Optional<UserInfo> userInfo = userInfoRepository.findById(email); if (userInfo.isPresent()) { //already exists model.addAttribute("invalidCredentials", true); return "register"; } else { UserInfo user = new UserInfo(email, userName, password); userInfoRepository.save(user); return "home"; } } @RequestMapping(value = "/guest", method = RequestMethod.GET) public String getGuest() { return "homeGuest"; } }
true
427c0032c9be431471a35261eb710c81777adca5
Java
guybitan100/java-xtt
/com/mobixell/xtt/RemoteXTTClient.java
UTF-8
19,767
2.15625
2
[]
no_license
package com.mobixell.xtt; import java.io.PrintStream; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.IOException; import java.net.Socket; import java.net.SocketException; import java.net.ConnectException; import java.net.SocketTimeoutException; import java.net.InetSocketAddress; import java.util.Vector; import java.util.LinkedHashMap; import org.jdom.Document; import org.jdom.Element; public class RemoteXTTClient { private final static String CRLF="\r\n"; protected static RemoteXTTPacket executeRemoteCommand(String command, int timeout, InetSocketAddress address) { Element requestTag = new Element("request"); Element executeTag = new Element("execute"); Element commandTag = new Element("command"); commandTag.addContent(command); executeTag.addContent(commandTag); if(timeout >= 0) { Element timeoutTag = new Element("timeout"); timeoutTag.addContent(""+timeout); executeTag.addContent(timeoutTag); } requestTag.addContent(executeTag); Document requestXML = new Document(new Element("remote")); requestXML.getRootElement().addContent(requestTag); return sendToRemoteXTT(requestXML,address); } protected static RemoteXTTPacket executeRemoteCommand(String command, int timeout, InetSocketAddress address, boolean stealtMode) { Element requestTag = new Element("request"); Element executeTag = new Element("execute"); Element commandTag = new Element("command"); commandTag.addContent(command); executeTag.addContent(commandTag); if(timeout >= 0) { Element timeoutTag = new Element("timeout"); timeoutTag.addContent(""+timeout); executeTag.addContent(timeoutTag); } requestTag.addContent(executeTag); Document requestXML = new Document(new Element("remote")); requestXML.getRootElement().addContent(requestTag); return sendToRemoteXTT(requestXML,address,stealtMode); } protected static RemoteXTTPacket getRemoteSystemTime(InetSocketAddress address) { Element requestTag = new Element("request"); Element executeTag = new Element("getTime"); requestTag.addContent(executeTag); Document requestXML = new Document(new Element("remote")); requestXML.getRootElement().addContent(requestTag); return sendToRemoteXTT(requestXML,address); } protected static RemoteXTTPacket listRemoteProducts(InetSocketAddress address) { Element requestTag = new Element("request"); Element listTag = new Element("listProducts"); requestTag.addContent(listTag); Document requestXML = new Document(new Element("remote")); requestXML.getRootElement().addContent(requestTag); return sendToRemoteXTT(requestXML,address); } public static RemoteXTTPacket getStatus(InetSocketAddress address, boolean stealtMode) { Element requestTag = new Element("request"); Element statusTag = new Element("getStatus"); requestTag.addContent(statusTag); Document requestXML = new Document(new Element("remote")); requestXML.getRootElement().addContent(requestTag); return sendToRemoteXTT(requestXML,address,stealtMode,-1); } protected static RemoteXTTPacket setRemoteTotalTests(InetSocketAddress address, int totaltests) { Element requestTag = new Element("request"); Element statusTag = new Element("getStatus"); requestTag.addContent(statusTag); Document requestXML = new Document(new Element("remote")); requestXML.getRootElement().addContent(requestTag); return sendToRemoteXTT(requestXML,address,false,totaltests); } protected static RemoteXTTPacket writeRemoteFile(String fileName, String fileContent, String fileHash, InetSocketAddress address) { XTTProperties.printInfo("writeRemoteFile: Writing File: " + fileName); Element requestTag = new Element("request"); Element fileTag = new Element("writeFile"); Element fileNameTag = new Element("fileName"); fileNameTag.addContent(fileName); fileTag.addContent(fileNameTag); Element fileDigestTag = new Element("fileMd5Digest"); fileDigestTag.addContent(fileHash); fileTag.addContent(fileDigestTag); requestTag.addContent(fileTag); Document requestXML = new Document(new Element("remote")); requestXML.getRootElement().addContent(requestTag); RemoteXTTPacket responsePacket = sendToRemoteXTT(requestXML,address); if(responsePacket.getReturnCode() == 0) { XTTProperties.printInfo("writeRemoteFile: The same file already existed on the remote machine, not re-sending"); } else { Element fileContentTag = new Element("fileContent"); fileContentTag.addContent(fileContent); fileTag.addContent(fileContentTag); responsePacket = sendToRemoteXTT(requestXML,address); if(responsePacket.getReturnCode() != 0) { XTTProperties.printFail("writeRemoteFile: Error writing file"); XTTProperties.setTestStatus(XTTProperties.FAILED); } } return responsePacket; } protected static RemoteXTTPacket readRemoteFile(String fileName, InetSocketAddress address) { Element requestTag = new Element("request"); Element fileTag = new Element("readFile"); Element fileNameTag = new Element("fileName"); fileNameTag.addContent(fileName); fileTag.addContent(fileNameTag); requestTag.addContent(fileTag); Document requestXML = new Document(new Element("remote")); requestXML.getRootElement().addContent(requestTag); RemoteXTTPacket dataResponse = sendToRemoteXTT(requestXML,address); return dataResponse; } protected static RemoteXTTPacket getNewestFile(String directoryName, String filter, InetSocketAddress address) { Element requestTag = new Element("request"); Element getNewestFileTag = new Element("getnewestfile"); Element directoryTag = new Element("directory"); Element filterTag = new Element("filter"); directoryTag.addContent(directoryName); getNewestFileTag.addContent(directoryTag); if(filter != null) { filterTag.addContent(filter); getNewestFileTag.addContent(filterTag); } requestTag.addContent(getNewestFileTag); Document requestXML = new Document(new Element("remote")); requestXML.getRootElement().addContent(requestTag); RemoteXTTPacket dataResponse = sendToRemoteXTT(requestXML,address); return dataResponse; } protected static RemoteXTTPacket whereAmI(InetSocketAddress address) { Element requestTag = new Element("request"); Element whereAmITag = new Element("whereAmI"); requestTag.addContent(whereAmITag); Document requestXML = new Document(new Element("remote")); requestXML.getRootElement().addContent(requestTag); RemoteXTTPacket dataResponse = sendToRemoteXTT(requestXML,address); return dataResponse; } protected static RemoteXTTPacket stopRemoteXTT(InetSocketAddress address) { Element requestTag = new Element("request"); Element stopRemoteXTTTag = new Element("stopRemoteXTT"); requestTag.addContent(stopRemoteXTTTag); Document requestXML = new Document(new Element("remote")); requestXML.getRootElement().addContent(requestTag); RemoteXTTPacket dataResponse = sendToRemoteXTT(requestXML,address); return dataResponse; } /* * Takes a String then wraps it in the XML needed for transfer to Remote XTT */ protected static RemoteXTTPacket sendToRemoteXTT(String data, InetSocketAddress address) { Element requestTag = new Element("request"); Element dataTag = new Element("data"); dataTag.addContent(data); requestTag.addContent(dataTag); Document requestXML = new Document(new Element("remote")); requestXML.getRootElement().addContent(requestTag); return sendToRemoteXTT(requestXML,address); } /* * Expects an XML document properly formatted for transfer to Remote XTT */ protected static RemoteXTTPacket sendToRemoteXTT(Document data, InetSocketAddress address,boolean stealtMode) { return sendToRemoteXTT(data, address, stealtMode,-1); } /* * Expects an XML document properly formatted for transfer to Remote XTT */ protected static RemoteXTTPacket sendToRemoteXTT(Document data, InetSocketAddress address) { return sendToRemoteXTT(data, address, false,-1); } protected static RemoteXTTPacket sendToRemoteXTT(Document data, InetSocketAddress address, boolean stealtMode, int expectedTests) { PrintStream out = null; BufferedInputStream in = null; Socket sock = null; Document dataResponse = null; RemoteXTTPacket responsePacket=new RemoteXTTPacket(null); // Info elements added normaly when not in stealth mode if(!stealtMode) { Element infoTag = new Element("info"); Element nameTag = new Element("name"); nameTag.addContent(XTTProperties.getCurrentTestName()); infoTag.addContent(nameTag); Element totalTestTag = new Element("totaltests"); int totaltests=XTTProperties.getNumberOfTests(); if(totaltests==0)totaltests=1; totalTestTag.addContent(""+totaltests); infoTag.addContent(totalTestTag); if(expectedTests>=0) { Element expectedTestsTag = new Element("expectedtests"); expectedTestsTag.addContent(""+expectedTests); infoTag.addContent(expectedTestsTag); } Element currentTestTag = new Element("currentest"); int currenttests=XTTProperties.getCurrentTestNumber(); currenttests++; currentTestTag.addContent(""+currenttests); infoTag.addContent(currentTestTag); data.getRootElement().addContent(infoTag); } try { sock = new Socket(); sock.setKeepAlive(true); sock.connect(address); sock.setTcpNoDelay(true); if(stealtMode) { //stealth mode is used by the guy, we do not want to keep hanging in case remotextt doesn't answer sock.setSoTimeout(30000); } if(!stealtMode)XTTProperties.printDebug("Remote connection: "+sock.getLocalAddress()+":"+sock.getLocalPort()+"->"+sock.getInetAddress()+":"+sock.getPort()); out = new PrintStream(sock.getOutputStream()); in = new BufferedInputStream(sock.getInputStream()); //XTT helper function to stream an XML document to a given stream byte[] dataToSend=ConvertLib.createBytes(XTTXML.stringXML(data)); StringBuffer headers=new StringBuffer(); headers.append("POST /remoteXTT HTTP/1.0"+CRLF); headers.append("date: "+HTTPHelper.createHTTPDate()+CRLF); headers.append("connection: close"+CRLF); headers.append("accept: text/xml"+CRLF); headers.append("user-agent: XTT/"+XTTProperties.getXTTBuildVersion() +" (testing; Java/"+System.getProperties().getProperty("java.vm.version")+"; " +System.getProperties().getProperty("os.name")+" " +System.getProperties().getProperty("os.arch")+" " +System.getProperties().getProperty("os.version")+"; " +System.getProperties().getProperty("user.name")+"; " +"RemoteXTT"+"; " +"$Revision: 1.11 $" +")"+CRLF); headers.append("content-type: text/xml"+CRLF); headers.append("content-length: "+dataToSend.length+CRLF); headers.append(CRLF); byte[] headerToSend=ConvertLib.createBytes(headers.toString()); out.write(headerToSend); out.write(dataToSend); out.flush(); org.jdom.input.SAXBuilder parser = new org.jdom.input.SAXBuilder(); byte[] buf = new byte[0]; try { LinkedHashMap<String,Vector<String>> header=HTTPHelper.readHTTPStreamHeaders(null,in); //End fo stream so break or invaild if(header.get(null)==null) throw new IOException("Invalid Protocol found"); try { } catch(Exception ex){} if(header.get("transfer-encoding")!=null) { if(header.get("transfer-encoding").get(0).equalsIgnoreCase("chunked")) { buf=HTTPHelper.readChunkedBody(null,in,header); } } else { Vector<String> contentlengthVector=header.get("content-length"); if(contentlengthVector!=null) { int contentlength=Integer.parseInt((String)contentlengthVector.get(0)); buf=new byte[contentlength]; HTTPHelper.readBytes(in,buf); } else { throw new IOException("Invalid Protocol, content-length not found"); } } dataResponse = parser.build(new ByteArrayInputStream(buf)); checkResponseVersion(dataResponse); } catch(IOException ioe) { if(!stealtMode) { XTTProperties.printFail("RemoteXTT didn't respond properly"); XTTProperties.setTestStatus(XTTProperties.FAILED); if(XTTProperties.printDebug(null)) { XTTProperties.printException(ioe); } } responsePacket.setException(ioe); } catch(org.jdom.JDOMException je) { if(!stealtMode) { XTTProperties.printFail("RemoteXTT didn't respond properly"); XTTProperties.setTestStatus(XTTProperties.FAILED); if(XTTProperties.printDebug(null)) { XTTProperties.printException(je); } } responsePacket.setException(je); } if(!stealtMode)XTTProperties.printDebug("Remote Command Response:\n"+XTTXML.stringXML(dataResponse)+"\nEND of response"); } catch (SocketTimeoutException ste) //Error if a connection can't be made { if(!stealtMode) { XTTProperties.printFail("RemoteXTT: Timeout on RemoteXTT connection!"); XTTProperties.setTestStatus(XTTProperties.FAILED); } responsePacket.setException(ste); } catch (ConnectException ce) //Error if a connection can't be made { if(!stealtMode) { XTTProperties.printFail("RemoteXTT: Remote XTT isn't running"); XTTProperties.setTestStatus(XTTProperties.FAILED); } responsePacket.setException(ce); } catch (SocketException se) //Parent of ConnectException, used here to see that connection was denied { if(!stealtMode) { XTTProperties.printFail("RemoteXTT: Remote XTT denied your IP"); XTTProperties.setTestStatus(XTTProperties.FAILED); XTTProperties.printException(se); } responsePacket.setException(se); } catch (Exception e) //Lastly something else went wrong { if(!stealtMode) { XTTProperties.printFail("RemoteXTT: Couldn't Test Launcher remotely"); if (XTTProperties.printDebug(null)) { XTTProperties.printException(e); } XTTProperties.setTestStatus(XTTProperties.FAILED); } responsePacket.setException(e); } finally { try { if(!stealtMode)XTTProperties.printDebug("SendToRemoteXTT: Trying to clean up sockets."); in.close(); out.close(); sock.close(); } catch(Exception e) { } } responsePacket.setDocument(dataResponse); return responsePacket; } protected synchronized static boolean isRemoteXTTRunning(InetSocketAddress address) { PrintStream out = null; Socket sock = null; Element requestTag = new Element("request"); Element statusTag = new Element("watchDog"); requestTag.addContent(statusTag); Document data = new Document(new Element("remote")); data.getRootElement().addContent(requestTag); byte[] dataToSend=ConvertLib.createBytes(XTTXML.stringXML(data)); StringBuffer headers=new StringBuffer(); headers.append("POST /remoteXTT HTTP/1.0"+CRLF); headers.append("date: "+HTTPHelper.createHTTPDate()+CRLF); headers.append("connection: close"+CRLF); headers.append("accept: text/xml"+CRLF); headers.append("user-agent: XTT/"+XTTProperties.getXTTBuildVersion() +" (testing; Java/"+System.getProperties().getProperty("java.vm.version")+"; " +System.getProperties().getProperty("os.name")+" " +System.getProperties().getProperty("os.arch")+" " +System.getProperties().getProperty("os.version")+"; " +System.getProperties().getProperty("user.name")+"; " +"RemoteXTT"+"; " +"$Revision: 1.11 $" +")"+CRLF); headers.append("content-type: text/xml"+CRLF); headers.append("content-length: "+dataToSend.length+CRLF); headers.append(CRLF); byte[] headerToSend=ConvertLib.createBytes(headers.toString()); try { sock = new Socket(); sock.setKeepAlive(true); sock.connect(address); sock.setTcpNoDelay(true); out = new PrintStream(sock.getOutputStream()); out.write(headerToSend); out.write(dataToSend); out.flush(); } catch (IOException ioe) { try { out.close(); sock.close(); } catch (Exception e) { } return false; } try { out.close(); sock.close(); } catch (Exception e) { return false; } return true; } private static void checkResponseVersion(Document dataResponse) throws Exception { String result = XTTXML.getElement("response/version",dataResponse.getDocument()).getText(); if(result.equals(XTTProperties.PRIVATEVERSION))return; String[] resultS = result.split("\\."); int version=Integer.parseInt(resultS[0])*100000+Integer.parseInt(resultS[1])*10000+Integer.parseInt(resultS[2]); if(version<200176)throw new java.lang.UnsupportedOperationException("This version of RemoteXTT is no longer supported (<2.0.0176)!"); } }
true
8f8e2be99b072beb95b46867b1b55ed4de7047a7
Java
JSJBDEV/LostThaumaturgy
/src/main/java/com/pengu/lostthaumaturgy/client/TextureAtlasSpriteFull.java
UTF-8
602
2.359375
2
[]
no_license
package com.pengu.lostthaumaturgy.client; import net.minecraft.client.renderer.texture.TextureAtlasSprite; public class TextureAtlasSpriteFull extends TextureAtlasSprite { public static final TextureAtlasSpriteFull sprite = new TextureAtlasSpriteFull("full"); protected TextureAtlasSpriteFull(String spriteName) { super(spriteName); } @Override public float getMinU() { return 0; } @Override public float getMinV() { return 0; } @Override public float getMaxU() { return 1; } @Override public float getMaxV() { return 1; } }
true
7f1d19e810ea49f62df4308b9723ce4eaf769df1
Java
evandor/skysail
/skysail.server.app.notes/src/io/skysail/server/app/notes/Category.java
UTF-8
596
2.296875
2
[ "Apache-2.0" ]
permissive
package io.skysail.server.app.notes; import io.skysail.domain.Entity; import io.skysail.domain.html.Field; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; @Getter @AllArgsConstructor @NoArgsConstructor public class Category implements Entity, Comparable<Category> { @Setter private String id; @Field private String name; @Override public int compareTo(Category o) { if (getName() == null) { return -1; } if (o == null || o.getName() == null) { return 1; } return getName().compareTo(o.getName()); } }
true
9e95f41c420d3708c50a90f288b53fd4ae4347e3
Java
ashishbharg/DS_Algo
/src/main/java/edu/ashish/util/PrintingUtil.java
UTF-8
2,887
3.46875
3
[]
no_license
package edu.ashish.util; import edu.ashish.model.BalanceTreeNode; import edu.ashish.model.TreeNode; import java.util.Arrays; public class PrintingUtil { public static void print1DArray(int[] arr) { System.out.println(Arrays.toString(arr)); System.out.println(); } public static void print1DArray(double[] arr) { System.out.println(Arrays.toString(arr)); System.out.println(); } public static void print1DArray(String[] arr) { System.out.println(Arrays.toString(arr)); System.out.println(); } public static void print1DArray(Object[] arr) { System.out.println(Arrays.toString(arr)); System.out.println(); } public static void print1DArray(char[] characters) { for (int i = 0; i < characters.length; i++) { System.out.print(characters[i]); } System.out.println(); } public static void printTree(TreeNode root) { int height = heightOfTree(root); for (int i=1; i <= height; i++) { printTree(root, i); System.out.println(); } } public static void printBalanceTree(BalanceTreeNode root) { int height = heightOfBalanceTree(root); for (int i=1; i <= height; i++) { printBalanceTree(root, i); System.out.println(); } } private static void printBalanceTree(BalanceTreeNode root, int height) { if(root == null) { return; } if (height == 1) { System.out.print(root.data + "\t"); } else { printBalanceTree(root.left, height - 1); printBalanceTree(root.right, height - 1); } } private static int heightOfBalanceTree(BalanceTreeNode root) { if (root == null) { return 0; } int lHeight = heightOfBalanceTree(root.left); int rHeight = heightOfBalanceTree(root.right); return 1 + Integer.max(lHeight, rHeight); } private static void printTree(TreeNode root, int height) { if(root == null) { return; } if (height == 1) { System.out.print(root.data + "\t"); } else { printTree(root.left, height - 1); printTree(root.right, height - 1); } } private static int heightOfTree(TreeNode root) { if (root == null) { return 0; } int lHeight = heightOfTree(root.left); int rHeight = heightOfTree(root.right); return 1 + Integer.max(lHeight, rHeight); } public static void print2DArray(int[][] arr) { for (int i = 0; i < arr.length; i++) { for (int j = 0; j < arr[0].length; j++) { System.out.print(arr[i][j] + " "); } System.out.println(); } } }
true
e234602d22f3a43144706828af5e53088a6a7ff7
Java
KHikami/ProjectFiCallingDeciphered
/DialerJADXDecompile/beb.java
UTF-8
2,346
1.640625
2
[]
no_license
import android.graphics.Bitmap; import android.location.Address; import android.provider.ContactsContract.CommonDataKinds.Phone; import java.util.List; import java.util.Set; /* compiled from: PG */ public class beb implements bej, bek { public final String a; public final /* synthetic */ bbc b; public void a(Address address, List list) { bbe bbe = (bbe) this.b.c.get(this.a); if (bbe == null) { bdf.c((Object) this, "Contact context received for empty search entry."); this.b.a(this.a); return; } bbe.i = false; bdf.b(this.b, "Setting contact interactions for entry: ", bbe); bbe.m = address; bbe.n = list; bbc bbc = this.b; String str = this.a; Set<bbf> set = (Set) bbc.d.get(str); if (set != null) { for (bbf c : set) { c.c(str, bbe); } } if (!bbe.h) { this.b.a(this.a); } } public beb(bbc bbc, String str) { this.b = bbc; this.a = str; } public void a(bel bel) { if (bel == null) { bdf.a(bbc.a, "Contact lookup done. Remote contact not found."); this.b.a(this.a); return; } bbe bbe = new bbe(); bbe.a = bel.a(); bbe.c = bel.b(); bbe.o = bel.h(); int c = bel.c(); CharSequence d = bel.d(); if (c == 0) { bbe.e = d; } else { CharSequence typeLabel = Phone.getTypeLabel(this.b.b.getResources(), c, d); bbe.e = typeLabel == null ? null : typeLabel.toString(); } bbe bbe2 = (bbe) this.b.c.get(this.a); if (bbe2 != null) { bbe.d = bbe2.d; bbe.q = bbe2.q; } if (bel.e() == null && bel.g()) { bdf.a(bbc.a, "Business has no image. Using default."); bbe.f = this.b.b.getResources().getDrawable(buf.kD); } this.b.c.put(this.a, bbe); this.b.a(this.a, bbe); if (this.b.e != null) { bbe.i = this.b.e.a(bel.f(), this); } bbe.h = bel.e() != null; if (!bbe.h && !bbe.i) { this.b.a(this.a); } } public void a(Bitmap bitmap) { this.b.a(null, bitmap, this.a); } }
true
39f8d791448b502aa251822dc6105c33b4518e18
Java
NoSequel/HCF
/src/main/java/rip/vapor/hcf/listeners/EnchantmentLimiterListener.java
UTF-8
2,488
2.40625
2
[]
no_license
package rip.vapor.hcf.listeners; import org.bukkit.enchantments.Enchantment; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.enchantment.EnchantItemEvent; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.inventory.InventoryType; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import rip.vapor.hcf.VaporConstants; import java.util.Map; public class EnchantmentLimiterListener implements Listener { @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGH) public void onEnchantItem(EnchantItemEvent event) { final Map<Enchantment, Integer> enchantments = event.getEnchantsToAdd(); enchantments.forEach(((enchantment, level) -> { if (VaporConstants.ENCHANTMENT_LIMITS.containsKey(enchantment)) { final int maxLevel = VaporConstants.ENCHANTMENT_LIMITS.get(enchantment); if (level > maxLevel) { enchantments.put(enchantment, maxLevel); } } })); } @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGH) public void onInventoryClickEvent(InventoryClickEvent event) { final Player player = (Player) event.getWhoClicked(); final Inventory inventory = event.getInventory(); if (inventory.getType().equals(InventoryType.ANVIL) && event.getRawSlot() == 2) { final ItemStack result = inventory.getItem(2); if (result != null) { event.setCancelled(true); result.getEnchantments().forEach(((enchantment, level) -> { if (VaporConstants.ENCHANTMENT_LIMITS.containsKey(enchantment)) { final int maxLevel = VaporConstants.ENCHANTMENT_LIMITS.get(enchantment); if (level > maxLevel) { result.removeEnchantment(enchantment); result.addEnchantment(enchantment, maxLevel); } } })); player.updateInventory(); inventory.clear(); if (event.getClick().isShiftClick()) { player.getInventory().addItem(result); } else { event.setCursor(result); } } } } }
true
d0ef2cfc640f00fdea830c801af9aff5fa31ce98
Java
yinabameguru/BookStore
/src/com/jza_lbz/service/CategoryService.java
UTF-8
531
2.125
2
[]
no_license
package com.jza_lbz.service; import java.sql.SQLException; import java.util.List; import com.jza_lbz.domain.Category; import com.jza_lbz.domain.CategoryPageBook; public interface CategoryService { /** * 分类&查询 * @return * @throws SQLException */ public List<Category> category() throws SQLException; /** * 按分类查询每页书籍 * @param categoryPageBook * @return * @throws SQLException */ public CategoryPageBook findCategoryPageBook(CategoryPageBook categoryPageBook) throws SQLException; }
true
17b692b93281df2e7ea7eb556a00c15db05c4386
Java
nowimwrok/zd_ztpor
/src/main/java/com/thinkgem/jeesite/modules/sys/listener/WebAppContextListener.java
UTF-8
3,128
1.851563
2
[ "Apache-2.0" ]
permissive
package com.thinkgem.jeesite.modules.sys.listener; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import com.thinkgem.jeesite.common.utils.Const; import org.springframework.web.context.support.WebApplicationContextUtils; /** * * 类名称:WebAppContextListener.java * 类描述: * 作者单位: * 联系方式: * @version 1.0 */ public class WebAppContextListener implements ServletContextListener { public void contextDestroyed(ServletContextEvent event) { // TODO Auto-generated method stub } /* (非 Javadoc) * @see javax.servlet.ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent) */ public void contextInitialized(ServletContextEvent event) { // TODO Auto-generated method stub Const.WEB_APP_CONTEXT = WebApplicationContextUtils.getWebApplicationContext(event.getServletContext()); //System.out.println("========获取Spring WebApplicationContext"); try { //友情链接 /*FriendlyLinkService friendlyService=ServiceHelper.getFriendlylinkService(); PageData condition=new PageData(); condition.put("MODULE", "1"); List<PageData> wlptFriendlyList=friendlyService.findByCondition(condition); event.getServletContext().setAttribute("WlptFriendlyList", wlptFriendlyList); condition=new PageData(); condition.put("MODULE", "0"); List<PageData> commonFriendlyList=friendlyService.findByCondition(condition); event.getServletContext().setAttribute("CommonFriendlyList", commonFriendlyList); //wlpt首页统计数据 StatisticsChinaAreaService statisticsChinaAreaService=ServiceHelper.getStatisticsChinaAreaService(); List<PageData> statisticsChinaAreaList=statisticsChinaAreaService.listAll(null); event.getServletContext().setAttribute("StatisticsChinaAreaList", statisticsChinaAreaList); //系统配置 InterfaceconfigService interfaceconfigService=ServiceHelper.getInterfaceconfigService(); List<PageData> interfaceconfigList=interfaceconfigService.listAll(null); event.getServletContext().setAttribute("InterfaceconfigList", interfaceconfigList); //app版本 *//*AppVersionService appVersionService=ServiceHelper.getAppVersionService(); PageData version=appVersionService.findLastedVersion(); event.getServletContext().setAttribute(Const.SESSION_APP_VERSION, version); //app下载链接地址 String url = Tools.readTxtFile(Const.WLPT_DOMAIN) + "/" + Const.FILEPATHAPPFILE + version.getString("NAME"); event.getServletContext().setAttribute("appVersion", url);*//* //获取logo AdvertisementService advertisementService=ServiceHelper.getAdvertisementService(); PageData logoPd=new PageData(); logoPd.put("NAMES", "zd_logo"); logoPd.put("ISDELETE", 0); logoPd.put("TYPE", "1"); Page logopg=new Page(); logopg.setPd(logoPd); if(advertisementService.list(logopg).size()>0){ logoPd=advertisementService.list(logopg).get(0); } event.getServletContext().setAttribute("logoPd", logoPd);*/ } catch (Exception e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } } }
true
747fb69b4ad9375d1ce7aa56c0313dd2ab3838de
Java
NinaMNina/food-DrinksOnline
/src/jsonData/Data.java
UTF-8
5,223
2.515625
3
[]
no_license
package jsonData; import java.io.Serializable; import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.PriorityQueue; import DTO.ArtikalDTO; import bean.Jelo; import bean.Korisnik; import bean.Pice; import bean.Porudzbina; import bean.Restoran; import bean.Stavka; import bean.Vozilo; import bean.enums.StatusPorudzbine; import com.fasterxml.jackson.annotation.JsonIgnore; public class Data implements Serializable{ private ArrayList<Korisnik> korisnici; private ArrayList<Restoran> restorani; private ArrayList<Vozilo> vozila; private static Data data=null; public static Data getInstance(){ if(data==null){ data = JsonSerializer.loadData(); } return data; } public ArrayList<Korisnik> getKorisnici() { return korisnici; } public ArrayList<Restoran> getRestorani() { return restorani; } public ArrayList<Vozilo> getVozila() { return vozila; } public void setKorisnici(ArrayList<Korisnik> korisnici) { this.korisnici = korisnici; } public void setRestorani(ArrayList<Restoran> restorani) { this.restorani = restorani; } public void setVozila(ArrayList<Vozilo> vozila) { this.vozila = vozila; } public Data() { } @JsonIgnore public int getJelaLength() { return getFinalLength(); } @JsonIgnore public int getPicaLength() { return getFinalLength(); } @JsonIgnore public int getFinalLength() { int retVal=0; for(Restoran r0 : restorani){ retVal+=r0.getPica().size(); retVal+=r0.getJela().size(); } return retVal; } @JsonIgnore public void addJelo(Jelo j) { for(Restoran r0 : restorani){ if(r0.getId()==j.getIdRestorana()){ r0.getJela().add(j); } } } @JsonIgnore public void addPice(Pice j) { for(Restoran r0 : restorani){ if(r0.getId()==j.getIdRestorana()){ r0.getPica().add(j); } } } @JsonIgnore public int getPorudzbinaLength() { int retVal=0; for(Korisnik k0 : korisnici){ retVal+=k0.getPorudzbine().size(); } return retVal; } @JsonIgnore public Porudzbina getObavljamPorudzbinu(String un) { Porudzbina ret = null; for(Korisnik k : korisnici){ for(Porudzbina p0 : k.getPorudzbine()){ if(p0.getDostavljac().equals(un) && p0.getStatus().equals(StatusPorudzbine.UTOKU)); return p0; } } return ret; } @JsonIgnore public List<ArtikalDTO> getTop() { List<ArtikalDTO> svi = new ArrayList<>(); List<ArtikalDTO> top = new ArrayList<>(); HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>(); for(Korisnik k0: korisnici){ for(Porudzbina p0: k0.getPorudzbine()){ for(Stavka s0 : p0.getStavke()){ if(hm.containsKey(s0.getIdArtikla())){ int value = hm.get(s0.getIdArtikla()); hm.put(s0.getIdArtikla(), ++value); // System.out.println("dodejm "+s0.getIdArtikla()+"-->" + value); } else{ hm.put(s0.getIdArtikla(), 1); // System.out.println("pravim..."+s0.getIdArtikla()); } } } } List<Entry<Integer, Integer>> greatest = findGreatest(hm, 10); ArrayList<Integer> ids = new ArrayList(); for(Entry<Integer, Integer> entry : greatest){ ids.add(entry.getKey()); } int count = 1; for(Restoran r0: restorani){ for(Jelo j0 : r0.getJela()){ if(ids.contains(j0.getId())){ top.add(toAtrikalDTO(r0, j0)); // System.out.println(count +". - "+ j0.getNaziv()+"["+j0.getId()+"]" + "-->" + hm.get(j0.getId())); count++; } } for(Pice p0 : r0.getPica()){ if(ids.contains(p0.getId())){ top.add(toAtrikalDTO(r0, p0)); // System.out.println(count +". - "+ p0.getNaziv()+"["+p0.getId()+"]" +"-->" + hm.get(p0.getId())); count++; } } } return top; } @JsonIgnore private ArtikalDTO toAtrikalDTO(Restoran r0, Jelo j0) { ArtikalDTO a = new ArtikalDTO(); a.setCena(j0.getCena()); a.setKolicina(j0.getGrama()); a.setMera("g"); a.setNaziv(j0.getNaziv()); a.setOpis(j0.getOpis()); a.setrAdresa(r0.getAdresa()); a.setrNaziv(r0.getNaziv()); return a; } @JsonIgnore private ArtikalDTO toAtrikalDTO(Restoran r0, Pice j0) { ArtikalDTO a = new ArtikalDTO(); a.setCena(j0.getCena()); a.setKolicina(j0.getMililitara()); a.setMera("ml"); a.setNaziv(j0.getNaziv()); a.setOpis(j0.getOpis()); a.setrAdresa(r0.getAdresa()); a.setrNaziv(r0.getNaziv()); return a; } @JsonIgnore private static <K, V extends Comparable<? super V>> List<Entry<K, V>> findGreatest(Map<K, V> map, int n){ Comparator<? super Entry<K, V>> comparator = new Comparator<Entry<K, V>>(){ @Override public int compare(Entry<K, V> e0, Entry<K, V> e1){ V v0 = e0.getValue(); V v1 = e1.getValue(); return v0.compareTo(v1); } }; PriorityQueue<Entry<K, V>> highest = new PriorityQueue<Entry<K,V>>(n, comparator); for (Entry<K, V> entry : map.entrySet()){ highest.offer(entry); while (highest.size() > n){ highest.poll(); } } List<Entry<K, V>> result = new ArrayList<Map.Entry<K,V>>(); while (highest.size() > 0){ result.add(highest.poll()); } return result; } }
true
f4b383f12c62bdf7d17651cbba43386557662aa3
Java
tulasiqa/hybridFrameWork
/SRC/vibe/contacts3/tests/BusinessContactsMethods.java
UTF-8
122,723
1.648438
2
[]
no_license
package vibe.contacts3.tests; import java.util.List; import java.util.Set; import java.awt.AWTException; import java.awt.Robot; import java.awt.event.KeyEvent; import java.io.File; import java.io.IOException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import org.apache.log4j.Logger; import org.openqa.selenium.Keys; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.Select; import org.openqa.selenium.By; import org.testng.Assert; import vibe.calendar2.tests.CalendarMethods; import vibe.ecards.tests.EcardMethods; import vibe.inbox.tests.InboxMethods; import vibe.mycommunity.tests.CommunityMethods; import vibe.tasks.tests.TaskMethods; import common.TestBase; import common.EnvProperties; public class BusinessContactsMethods extends TestBase { Logger logger = Logger.getLogger(BusinessContactsMethods.class); // public static String vibeRecipient_text = getEmail(adminUser_text,appUrl); EnvProperties prop = new EnvProperties(); CommunityMethods cm = new CommunityMethods(); TaskMethods tm = new TaskMethods(); EcardMethods em = new EcardMethods(); public void go2ContactsPage() throws Exception{ logInfo("inside go2ContactsPage() method."); driver().navigate().to(appUrl + "crm/v2/contacts/all"); Thread.sleep(5000); } public void selectContactsCategoryList(String listName) throws Exception{ logInfo("inside selectContactsCategoryList() method."); switch(listName){ case "Recent Contacts": waitOnElement("partialLinkText",prop.getLocatorForEnvironment(appUrl,"lnkRecentContacts")); clickOnElement("partialLinkText",prop.getLocatorForEnvironment(appUrl,"lnkRecentContacts")); Thread.sleep(4000); break; case "Recent Leads": waitOnElement("partialLinkText","Recent Leads ("); clickOnElement("partialLinkText","Recent Leads ("); Thread.sleep(4000); break; case "Contacts": waitOnElement("partialLinkText","Contacts ("); clickOnElement("partialLinkText","Contacts ("); Thread.sleep(4000); break; case "Team Contacts": waitOnElement("partialLinkText","Team Contacts ("); clickOnElement("partialLinkText","Team Contacts ("); Thread.sleep(4000); break; case "Notes Added in Last 7 days": waitOnElement("partialLinkText","Notes Added in Last 7 days ("); clickOnElement("partialLinkText","Notes Added in Last 7 days ("); Thread.sleep(4000); break; case "Project Simplify Participants": waitOnElement("partialLinkText","Project Simplify Participants ("); clickOnElement("partialLinkText","Project Simplify Participants ("); Thread.sleep(4000); break; case "Assigned": waitOnElement("partialLinkText","Assigned ("); clickOnElement("partialLinkText","Assigned ("); Thread.sleep(4000); break; case "Unassigned": waitOnElement("partialLinkText","Unassigned ("); clickOnElement("partialLinkText","Unassigned ("); Thread.sleep(4000); break; case "Registered": waitOnElement("partialLinkText","Registered ("); clickOnElement("partialLinkText","Registered ("); Thread.sleep(4000); break; } } public void go2adminPage() throws Exception{ logInfo("inside go2adminPage() method. "); driver().navigate().to(appUrl + "pyr_core/pyr_admin/dashboard"); } public void go2CallScriptPage() throws Exception{ logInfo("inside go2adminPage() method. "); driver().navigate().to(appUrl + "pyr_core/pyr_admin/dashboard"); verifyLinkPresent("Marketing"); clickOnLink("linkText", "Marketing"); verifyLinkPresent("Call Scripts"); clickOnLink("linkText", "Call Scripts"); } public void addBusinessContacts(String fName, String lName, String email) throws Exception{ logInfo("inside addBusinessContacts() method. "); System.out.println("inside addBusinessContacts() method. "); go2ContactsPage(); waitOnElement("xpath","//div[@class='topbar']/div[1]/a/span"); clickOnElement("xpath", "//div[@class='topbar']/div[1]/a/span"); Thread.sleep(10000); waitOnElement("cssSelector",inputContactFirstName); inputText("cssSelector",inputContactFirstName,fName); inputText("cssSelector",inputContactLastName,lName); inputText("cssSelector",inputContactEmail,email); selectFromDropdown("cssSelector","#pyr_crm_contact_contact_phone_numbers_attributes_0_dialing_code","byVisibleText","IN-91"); inputTextClear("cssSelector","#phone_number"); inputText("cssSelector","#phone_number",prop.getLocatorForEnvironment(appUrl, "txtPhNumber")); // contactPhone_text selectFromDropdown("cssSelector","#pyr_crm_contact_contact_phone_numbers_attributes_0_label","byIndex",1); /*WebElement element = driver().findElement(By.cssSelector(drpdnContactPhoneType)); Select select = new Select(element); List<WebElement> allItems =select.getOptions(); int size = allItems.size(); // System.out.println("count of items =" +size); select.selectByIndex(size-1);*/ selectFromDropdown("cssSelector",drpdnContactType,"byVisibleText",contactType_text); selectFromDropdown("cssSelector",drpdnContactInterestLevel,"byVisibleText",contactInterestLevel_text); inputText("cssSelector",inputContactAddr1,contactAddr1_text); inputText("cssSelector",inputContactAddr2,contactAddr2_text); inputText("cssSelector",inputContactCity,contactCity_text); inputText("cssSelector",inputContactPostalCode,contactPostalCode_text); selectFromDropdown("cssSelector",drpdnContactCntry,"byVisibleText",contactCntry_text); selectFromDropdown("cssSelector",drpdnContactState,"byVisibleText",contactState_text); inputText("cssSelector",inputContactGenInfo,contactGenInfo_text); logInfo("Entered all the fields in Business -> AddContact page."); scrollDown("xpath",btnUpdateContact); clickOnButton("xpath",btnUpdateContact); Thread.sleep(6000); } public boolean verifyBusinessContact(String fName, String lName) throws Exception{ logInfo("inside verifyBusinessContact() method."); System.out.println("inside verifyBusinessContact() method1."); String expVal = fName + " " + lName; expVal = expVal.trim(); boolean isContactFound = false; waitOnElement("cssSelector","div.contacts-index-list.actions.summary > div#index-contacts-list > div#contacts_selected"); WebElement panel = driver().findElement(By.cssSelector("div.contacts-index-list.actions.summary > div#index-contacts-list > div#contacts_selected")); List allContacts = panel.findElements(By.cssSelector("div.contact-list-item.list-result.media")); System.out.println("Total Business Contacts =" + allContacts.size()); if(allContacts.size()>0) { String before_contactName = "//div[@class='contacts-index-list actions summary']/div[@id='index-contacts-list']/div[@id='contacts_selected']/div["; String after_contactName = "]/div/div/div[2]/div[1]/a/span[2]"; for(int i=1;i<=allContacts.size();i++){ WebElement e = driver().findElement(By.xpath(before_contactName+i+after_contactName)); String actText = e.getText().trim(); // System.out.println("actText =" +actText); if(actText.equalsIgnoreCase(expVal)){ System.out.println("Verify Busniess contact match found =" +actText); System.out.println("expVal =" +expVal); isContactFound = true; logInfo(expVal + " contact match found."); break; } } } return isContactFound; } public boolean verifyBusinessContact(String email) throws Exception{ logInfo("inside verifyBusinessContact() method."); System.out.println("inside verifyBusinessContact() method2."); boolean isContactFound = false; waitOnElement("cssSelector","div.contacts-index-list.actions.summary > div#index-contacts-list > div#contacts_selected"); WebElement panel = driver().findElement(By.cssSelector("div.contacts-index-list.actions.summary > div#index-contacts-list > div#contacts_selected")); List allContacts = panel.findElements(By.cssSelector("div.contact-list-item.list-result.media")); System.out.println("Total Business Contacts =" + allContacts.size()); if(allContacts.size()>0) { String before_contactEmail = "//div[@class='contacts-index-list actions summary']/div[@id='index-contacts-list']/div[@id='contacts_selected']/div["; String after_contactEmail = "]/div/div/div[2]/div[2]"; for(int i=1;i<=allContacts.size();i++){ WebElement e = driver().findElement(By.xpath(before_contactEmail+i+after_contactEmail)); String actEmail = e.getText().trim(); if(actEmail.equalsIgnoreCase(email)){ System.out.println("contact matched actText =" +actEmail + "email =" +email); // System.out.println("email =" +email); isContactFound = true; logInfo(email + " business contact match found."); break; } } } return isContactFound; } public void searchContact(String fName, String lName) throws Exception{ logInfo("inside searchContact() method. "); System.out.println("inside searchContact() method. "); String expVal = fName + " " + lName; waitOnElement("cssSelector","div.search.input-group > input"); inputTextClear("cssSelector","div.search.input-group > input"); inputText("cssSelector","div.search.input-group > input", expVal.trim()); clickOnElement("cssSelector","div.search.input-group > a"); Thread.sleep(10000); } public void searchContact(String Name) throws Exception{ logInfo("inside searchContact() method. "); System.out.println("inside searchContact() method. "); waitOnElement("cssSelector","div.search.input-group > input"); inputTextClear("cssSelector","div.search.input-group > input"); inputText("cssSelector","div.search.input-group > input", Name.trim()); clickOnElement("cssSelector","div.search.input-group > a"); Thread.sleep(10000); } public void selectBusinessContact(String fName, String lName) throws Exception{ logInfo("inside selectBusinessContact() method."); System.out.println("inside selectBusinessContact() method"); String expVal = fName + " " + lName; expVal = expVal.trim(); boolean isContactFound = false; waitOnElement("cssSelector","div.contacts-index-list.actions.summary > div#index-contacts-list > div#contacts_selected"); WebElement panel = driver().findElement(By.cssSelector("div.contacts-index-list.actions.summary > div#index-contacts-list > div#contacts_selected")); List allContacts = panel.findElements(By.cssSelector("div.contact-list-item.list-result.media")); System.out.println("Total Business Contacts =" + allContacts.size()); if(allContacts.size()>0) { String before_contactName = "//div[@class='contacts-index-list actions summary']/div[@id='index-contacts-list']/div[@id='contacts_selected']/div["; String after_contactName = "]/div/div/div[2]/div[1]/a/span[2]"; for(int i=1;i<=allContacts.size();i++){ WebElement e = driver().findElement(By.xpath(before_contactName+i+after_contactName)); String actText = e.getText().trim(); // System.out.println("actText =" +actText); if(actText.equalsIgnoreCase(expVal)){ System.out.println("Select Busniess contact match found =" +actText); isContactFound = true; e.click(); logInfo(expVal + " business contact match found to select."); break; } } } } public void deleteBusinessContact(String fName, String lName) throws Exception{ logInfo("inside deleteBusinessContact() method."); System.out.println("inside deleteBusinessContact() method."); go2ContactsPage(); selectContactsCategoryList("Recent Contacts"); selectBusinessContact(contactFirstName_text,contactLastName_text); waitOnElement("linkText","Delete"); clickOnLink("linkText", "Delete"); System.out.println("clicked delete contact button"); Thread.sleep(5000); (new Robot()).keyPress(java.awt.event.KeyEvent.VK_ENTER); (new Robot()).keyRelease(java.awt.event.KeyEvent.VK_ENTER); System.out.println("clicked confirm delete button"); logInfo("clicked on confirm delete button."); // Thread.sleep(5000); confirmationMessage("Contact Deleted."); String contactsPanel = "//*[@id='all-contacts-list']/div[1]/form"; waitOnElement("xpath",contactsPanel); } /* public void createCallScript(String scriptName) throws Exception{ go2adminPage(); go2CallScriptPage(); clickOnLink("linkText","Add New Script"); verifyElementPresent("xpath",inputCallScriptName); inputText("xpath",inputCallScriptName,scriptName); selectFromDropdown("xpath",drpdnCallScriptStatus,"byVisibleText",callScriptStatus_text); // composeTextOnCallScript(); composeText("xpath",composeBody,composeBodyText); clickOnElement("xpath",divCallScriptMarketLang); WebElement chkAll = driver().findElement(By.xpath(inputMarketAll)); if(!chkAll.isSelected()){ chkAll.click(); } DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy h:mm a"); Calendar cal = Calendar.getInstance(); String dd = dateFormat.format(cal.getTime()); publishedOn_text = dd.trim(); publishedOn_text = "01/01/2016 12:00 PM"; publishedEndDate_text = "10/10/2020 12:00 PM"; System.out.println("Pulish start date: " +publishedOn_text); System.out.println("Pulish end date: " +publishedEndDate_text); inputTextClear("xpath",inputPublishedOn); inputText("xpath",inputPublishedOn,publishedOn_text); inputTextClear("xpath",inputPublishedEndDate); inputText("xpath",inputPublishedEndDate,publishedEndDate_text); // saveAndProceed(); clickOnButton("cssSelector",btnSubmitCallscript); // waitOnElement("linkText","Back To Call Scripts"); Thread.sleep(5000); waitOnElement("linkText","back to office"); clickOnLink("linkText","back to office"); Thread.sleep(5000); } */ public void createCallScript(String scriptName, String status, String[] markets, String startDate, String endDate) throws Exception{ go2adminPage(); go2CallScriptPage(); clickOnLink("linkText","Add New Script"); inputTextClear("xpath",inputCallScriptName); inputText("xpath",inputCallScriptName,scriptName); selectFromDropdown("xpath",drpdnCallScriptStatus,"byVisibleText",status); switch(status){ case "Active": composeText("xpath",callScriptComposebody,composeBodyText); case "Pending": composeText("xpath",callScriptComposebody,composeBodyText); } WebElement chkAll = driver().findElement(By.xpath(inputMarketAll)); if(!chkAll.isSelected()){ chkAll.click(); } // Click Publish On icon clickOnElement("cssSelector","div.form-group.datetime_picker.required.pyr_crm_call_script_publish_on > div.input-group > span > button > span"); clickOnElement("cssSelector"," a > span.glyphicon.glyphicon-remove"); // Close link clickOnElement("xpath",inputPublishedEndDate); inputTextClear("xpath",inputPublishedEndDate); inputText("xpath",inputPublishedEndDate,endDate); clickOnButton("cssSelector",btnSubmitCallscript); Thread.sleep(10000); // confirmationMessage("Call Script is created"); } public void deleteCallScript(String scriptName) throws Exception{ logInfo("inside deleteCallScript() method."); go2adminPage(); go2CallScriptPage(); waitOnElement("xpath","//*[@id='call_scripts_list']/tbody"); WebElement ecallscripttbl = driver().findElement(By.xpath("//*[@id='call_scripts_list']/tbody")); List allRows = ecallscripttbl.findElements(By.tagName("tr")); String before_name = "//*[@id='call_scripts_list']/tbody/tr["; String after_name = "]/td[1]/a"; String before_delete = "//*[@id='call_scripts_list']/tbody/tr["; String after_delete = "]/td[6]/a[2]"; for(int i=1;i<=allRows.size();i++){ WebElement e = driver().findElement(By.xpath(before_name+i+after_name)); String strCallscriptName = e.getText().trim(); if(scriptName.equalsIgnoreCase(strCallscriptName)){ WebElement delete = driver().findElement(By.xpath(before_delete+i+after_delete)); delete.click(); confirmOK(); Thread.sleep(5000); break; } } } public boolean verifyCallScriptFound(String scriptName) throws Exception{ logInfo("inside verifyCallScriptFound() method."); go2adminPage(); go2CallScriptPage(); // verify for zero rows boolean isCallScriptFound = false; WebElement zeroRows = driver().findElement(By.xpath("//*[@id='call_scripts_list']/tbody/tr")); List allColumns = zeroRows.findElements(By.tagName("td")); if(allColumns.size()<=1){ logInfo( scriptName + " call script match found.Table has no rows."); isCallScriptFound = false; } else { waitOnElement("xpath","//*[@id='call_scripts_list']/tbody"); WebElement ecallscripttbl = driver().findElement(By.xpath("//*[@id='call_scripts_list']/tbody")); List allRows = ecallscripttbl.findElements(By.tagName("tr")); String before_name = "//*[@id='call_scripts_list']/tbody/tr["; String after_name = "]/td[1]/a"; for(int i=1;i<=allRows.size();i++){ WebElement e = driver().findElement(By.xpath(before_name+i+after_name)); String strCallscriptName = e.getText().trim(); if(scriptName.equalsIgnoreCase(strCallscriptName)){ isCallScriptFound=true; logInfo( scriptName + "call script match found in admin page"); break; } } } return isCallScriptFound; } public void submitCallScript(String scriptName, String scriptNotes) throws Exception { logInfo("inside submitCallScript() method."); System.out.println("inside submitCallScript() method."); Thread.sleep(4000); waitOnElement("cssSelector",drpdnPhoneScript); selectFromDropdown("cssSelector",drpdnPhoneScript,"byVisibleText",scriptName); Thread.sleep(4000); inputText("cssSelector",textareaPhoneScriptNotes,scriptNotes); selectRadioOrCheckbox("cssSelector",radioPhoneScriptInterest); clickOnButton("cssSelector",inputSubmitCallscript); Thread.sleep(5000); System.out.println("clicked save call script button"); } public void addNotes2Contacts(String fName, String lName, String notes) throws Exception{ logInfo("inside addNotes2Contacts() method."); System.out.println("inside addNotes2Contacts() method."); waitOnElement("linkText","New Note"); clickOnLink("linkText","New Note"); waitOnElement("cssSelector",inputAddContactNotes); inputTextClear("cssSelector",inputAddContactNotes); inputText("cssSelector",inputAddContactNotes, addContactNotes_text); clickOnButton("cssSelector",btnCreateContactNote); Thread.sleep(5000); logInfo("clicked on create note button."); } public boolean verifyNotesIsPresent(String notes) throws Exception{ logInfo("inside verifyNotesIsPresent() method."); System.out.println("inside verifyNotesIsPresent() method."); waitOnElement("xpath","//div[@class='contact-details-notes']"); WebElement notesPane = driver().findElement(By.xpath("//div[@class='contact-details-notes']/div[@id='notes-list']")); // List allRows = notesPane.findElements(By.className("row")); List allRows = notesPane.findElements(By.cssSelector("div.contact-note.row")); int all_rows = allRows.size(); System.out.println("Total Rows = " +all_rows); String before_text = "//div[@class='contact-details-notes']/div[@id='notes-list']/div["; String after_text = "]/div[3]/div"; boolean isMatchFound = false; if(all_rows>=0){ for(int i=1;i<=all_rows;i++){ WebElement x = driver().findElement(By.xpath(before_text+i+after_text)); String strNotes = x.getText().trim(); System.out.println(strNotes); if(strNotes.equalsIgnoreCase(notes)){ logInfo(strNotes + " notes match found."); isMatchFound = true; break; } } } return isMatchFound; } public void manageContactNotes(String notes, String mode) throws Exception{ logInfo("inside deleteContactNotes() method."); System.out.println("inside deleteContactNotes() method."); clickOnElement("cssSelector",lnkNotes); waitOnElement("xpath","//div[@class='contact-details-notes']"); WebElement notesPane = driver().findElement(By.xpath("//div[@class='contact-details-notes']/div[@id='notes-list']")); List allRows = notesPane.findElements(By.cssSelector("div.contact-note.row")); int all_rows = allRows.size(); System.out.println("Total Rows = " +all_rows); String before_text = "//div[@class='contact-details-notes']/div[@id='notes-list']/div["; String after_text = "]/div[3]/div"; String before_delete = "//div[@class='contact-details-notes']/div[@id='notes-list']/div["; String after_delete = "]/div[2]/a[2]"; String before_edit = "//div[@class='contact-details-notes']/div[@id='notes-list']/div["; String after_edit = "]/div[2]/a[1]"; boolean isMatchFound = false; if(all_rows>=0){ for(int i=1;i<=all_rows;i++){ WebElement x = driver().findElement(By.xpath(before_text+i+after_text)); String contactNotes = x.getText().trim(); System.out.println(contactNotes); if(contactNotes.equalsIgnoreCase(notes)){ logInfo(notes + " contact notes match found."); isMatchFound = true; switch(mode){ case "Delete": WebElement delete = driver().findElement(By.xpath(before_delete+i+after_delete)); delete.click(); // confirmEventDeleteModal(); confirmOK(); break; case "Edit": WebElement edit = driver().findElement(By.xpath(before_edit+i+after_edit)); edit.click(); break; } break; } } } } public void sendMessage2Contacts(String fName, String lName, String recepients) throws Exception{ logInfo("inside sendMessage2Contacts() method."); System.out.println("inside sendMessage2Contacts() method."); /* go2ContactsPage(); selectContactsCategoryList("Recent Contacts"); selectBusinessContact(contactFirstName_text,contactLastName_text); selectContactAction("Send Message"); */ waitOnElement("cssSelector",recipientsTo); clickOnElement("cssSelector",recipientsTo); inputText("cssSelector",recipientsTo, recepients); inputText("cssSelector",subject_Mail, inputSendMessageSubject_text); composeText("xpath","//iframe[contains(@title,'Rich Text Editor')]","This is a new Message to Contacts"); clickOnLink("linkText", "Send"); } public void sendMessage2GroupContacts() throws Exception{ logInfo("inside sendMessage2GroupContacts() method."); System.out.println("inside sendMessage2GroupContacts() method."); inputText("cssSelector",subject_Mail, "messages 2 group"); composeText("xpath","//iframe[contains(@title,'Rich Text Editor')]","This is a new message to Group Contacts"); clickOnLink("linkText", "Send"); } public void setAppointmentWithContacts(String eventName) throws Exception{ logInfo("inside setAppointmentWithContacts() method."); System.out.println("inside setAppointmentWithContacts() method."); try{ waitOnElement("xpath",inputEventName); inputTextClear("xpath",inputEventName); inputText("xpath",inputEventName,eventName); //selectFromDropdown("xpath", dpdnEventType, "byIndex", 1); selectFromDropdown("xpath", dpdnCalendarType, "byIndex", 1); //inputTextClear("xpath",inputEventStartDate); //inputText("xpath",inputEventStartDate,newEventStartdate_text); //inputTextClear("cssSelector","#pyr_crm_event_start_time_field"); // Start Time //inputText("cssSelector","#pyr_crm_event_start_time_field","01:00 AM"); //inputTextClear("xpath",inputEventEndDate); //inputText("xpath",inputEventEndDate, newEventEnddate_text); //inputTextClear("cssSelector","#pyr_crm_event_end_time_field"); // End Time //inputText("cssSelector","#pyr_crm_event_end_time_field","11:00 PM"); /*clickOnElement("xpath", newEventMoreotions); inputText("xpath",inputEventDescription,calendarEventDescription_text); inputText("xpath",inputEventLoc, calendarEventLocation_text); inputText("xpath",inputEventAddr1, calendarEventAddr1_text);*/ scrollDown("xpath","//*[@id='submit-form']"); clickOnElement("xpath","//*[@id='submit-form']"); } catch(Exception ex){ logInfo("Unable to create an event."); Assert.assertTrue(false, eventName + " Unable to create an event"); } } public void createTaskFromContacts(String taskName) throws Exception{ logInfo("inside createTaskFromContacts() method."); System.out.println("inside createTaskFromContacts() method."); waitOnElement("xpath",taskTitle ); inputTextClear("xpath",taskTitle ); inputText("xpath",taskTitle ,contactTaskDesc_text); inputTextClear("xpath",inputTaskDuedate); inputText("xpath",inputTaskDuedate,taskDuedate_text); selectFromDropdown("xpath",drpdnTaskPriority,"byVisibleText",taskPriority_text); composeText("xpath","//iframe[contains(@title,'Rich Text Editor')]","This is a new task"); // composeTextOnElement(); clickOnButton("xpath",inputAddTask); logInfo("clicked on Add Task button in Contacts page."); } // Groups related methods. public void go2Groups() throws Exception{ logInfo("inside go2Groups() method."); driver().navigate().to(appUrl + "crm/v2/contacts/all"); Thread.sleep(5000); } public void selectGroupPanel(String panelItemName) throws Exception { logInfo("inside selectGroupPanel() method."); waitOnElement("xpath","//div[@id='list-results']"); WebElement panel = driver().findElement(By.xpath("//div[@id='list-results']")); List allItems = panel.findElements(By.className("list-result")); System.out.println("Total Group Items =" +allItems.size()); String before_grp = "//div[@id='list-results']/div["; String after_grp = "]/a/span[2]"; boolean isMatchFound = false; for(int i=1;i<=allItems.size();i++) { WebElement grp = driver().findElement(By.xpath(before_grp+i+after_grp)); String item = grp.getText().trim(); System.out.println("item = " +item); if(item.contains(panelItemName)) { logInfo(panelItemName + " item found in the Group Panel"); isMatchFound = true; grp.click(); Thread.sleep(5000); break; } } if(isMatchFound==false) { logInfo(panelItemName + " item not found in the Group Panel"); Assert.assertTrue(isMatchFound, panelItemName + " item not found in the Group Panel"); } } public void closeManageGroupsDialog() throws Exception{ logInfo("inside closeManageGroupsDialog() method."); System.out.println("inside closeManageGroupsDialog() method."); clickOnElement("cssSelector",btnCloseGroup); } public void addGroup(String groupName) throws Exception{ logInfo("inside addGroup() method."); System.out.println("inside addGroup() method."); // selectGroupPanel("Groups"); boolean isGroupAdded = false; waitOnElement("cssSelector","div.col-md-4.col-xs-4.landing-action:nth-child(2) > a > span"); // Add New Group clickOnElement("cssSelector","div.col-md-4.col-xs-4.landing-action:nth-child(2) > a > span"); Thread.sleep(5000); inputTextClear("cssSelector", "div.modal-content > div.modal-body > div > div > div > form > div.form-group.string.required.pyr_crm_contact_category_category_name > input"); // inputGroupName inputText("cssSelector", "div.modal-content > div.modal-body > div > div > div > form > div.form-group.string.required.pyr_crm_contact_category_category_name > input",groupName); clickOnElement("cssSelector","div.modal-content > div.modal-body > div > div > div > form > div.add-contact-btn > input"); Thread.sleep(5000); WebElement x = driver().findElement(By.cssSelector("div.panel-column.panel-main-body.col-md-3.scrollable > div:nth-child(1) > div:nth-child(2)")); String actGroupName = x.getText().trim(); System.out.println("groupName = " +groupName); System.out.println("actGroupName = " +actGroupName); if(actGroupName.contains(groupName)) { logInfo(groupName + " Group is created"); isGroupAdded = true; } else { logInfo(groupName + " Group is not created"); // Assert.assertTrue(isGroupAdded, groupName + " Group is not created"); } } // Veriy group is present. public boolean verifyGroupIsPresent(String grpName) throws Exception{ logInfo("inside verifyGroupIsPresent() method."); System.out.println("inside verifyGroupIsPresent() method."); go2ContactsPage(); selectGroupPanel("Groups ("); boolean isMatchFound = false; waitOnElement("cssSelector","div#group-manager-list"); WebElement tblGroup = driver().findElement(By.cssSelector("div#group-manager-list")); List allGroups = tblGroup.findElements(By.cssSelector("div.group-list-item.clearfix")); int total_groups = allGroups.size(); System.out.println("Total groups = " +total_groups); String before_group = "//div[@id='group-manager-list']/div["; String after_group = "]/div/div/div[2]/div[1]/a"; System.out.println("grpName =" +grpName); // for(int i=2;i<=total_groups*2;i=i+2){ for(int i=total_groups*2;i>=2;i=i-2){ WebElement grp = driver().findElement(By.xpath(before_group+i+after_group)); String groupName = grp.getText().trim(); System.out.println("Group Name = " +groupName); if(groupName.equalsIgnoreCase(grpName)){ isMatchFound = true; logInfo(grpName + " group found in Manage Groups."); break; } } if(isMatchFound==false){ logInfo(grpName + " group not found in Manage Groups."); } return isMatchFound; } public void addContact2Group(String grpName, String contact) throws Exception{ logInfo("inside addContact2Group() method."); System.out.println("inside addContact2Group() method."); go2ContactsPage(); selectContactsCategoryList("Recent Contacts"); selectBusinessContact(contactFirstName_text,contactLastName_text); /*Thread.sleep(5000); waitOnElement("xpath",lnkAdd2Group); clickOnElement("xpath",lnkAdd2Group); */ // selectContactAction("Add To Group"); selectContactAction(prop.getLocatorForEnvironment(appUrl,"addtoGrp")); selectGroup2Add(groupName_text); } public void selectGroup2Add(String grpName) throws Exception{ logInfo("inside selectGroup2Add() method."); System.out.println("inside selectGroup2Add() method."); waitOnElement("xpath","//*[@id='contact-details-panel']/div[@id='groups-list']"); WebElement grpPanel = driver().findElement(By.xpath("//*[@id='contact-details-panel']/div[@id='groups-list']")); List allGrps = grpPanel.findElements(By.className("group-list-item")); // List allGrps = grpPanel.findElements(By.cssSelector(".group-list-item")); System.out.println("Total Groups = " +allGrps.size()); String before_grpName = "//*[@id='contact-details-panel']/div[@id='groups-list']/div["; String after_grpName = "]/div[1]/span[2]"; String before_grpAdd = "//*[@id='contact-details-panel']/div[@id='groups-list']/div["; String after_grpAdd = "]/div[2]/form/a[1]"; boolean isGrpFound = false; System.out.println("expGrpName =" + grpName.trim()); for(int i=1;i<=allGrps.size();i++){ WebElement eName = driver().findElement(By.xpath(before_grpName+i+after_grpName)); WebElement addGrp = driver().findElement(By.xpath(before_grpAdd+i+after_grpAdd)); String actGrpName = eName.getText().trim(); System.out.println("actGrpName =" + actGrpName); if(actGrpName.contains(grpName)){ // eName.click(); addGrp.click(); isGrpFound = true; System.out.println(grpName + " group match found to add."); WebElement add = driver().findElement(By.xpath(before_grpAdd+i+after_grpAdd)); add.click(); break; } } } /* public void selectGroupAndMoreOption(String groupName, String moreOption) throws Exception{ logInfo("Select particular Group under Manage Group and click 'More' to import"); WebElement more; go2ContactsPage(); selectGroupPanel("Groups ("); boolean isGroupFound = false; Thread.sleep(2000); List <WebElement> gr = driver().findElements(By.cssSelector(groupList)); System.out.println("Manage Size is "+ gr.size()); String beforeGrpName ="div#group-manager-list > div:nth-child(" ; String afterGrpName =") > div.col-md-9 > div > a"; String beforeGrpRename = "div#group-manager-list > div:nth-child(" ; String afterGrpRename = ") > div.view-tools.col-md-3 > a:nth-child(1)"; String beforeGrpDelete = "div#group-manager-list > div:nth-child(" ; String afterGrpDelete = ") > div.view-tools.col-md-3 > a:nth-child(2)"; String beforeGrpMore ="div#group-manager-list > div:nth-child(" ; String afterGrpMore =") > div.view-tools.col-md-3 > a:nth-child(3)"; String beforeGrp_Import2Groups ="div#group-manager-list > div:nth-child(" ; String afterGrp_Import2Groups =") > div.view-tools.col-md-3 > ul > li:nth-child(1) > a"; String beforeGrp_PrintLbls ="div#group-manager-list > div:nth-child(" ; String afterGrp_PrintLbls =") > div.view-tools.col-md-3 > ul > li:nth-child(2) > a"; String beforeGrp_exportCSV ="div#group-manager-list > div:nth-child(" ; String afterGrp_exportCSV =") > div.view-tools.col-md-3 > ul > li:nth-child(3) > a"; String beforeGrp_exportExcel ="div#group-manager-list > div:nth-child(" ; String afterGrp_exportExcel =") > div.view-tools.col-md-3 > ul > li:nth-child(4) > a"; for (int i=2; i<=gr.size(); i+=2){ System.out.println("i =" +i); WebElement gpName = driver().findElement(By.cssSelector(beforeGrpName+i+afterGrpName)); String actGrp = gpName.getText().trim(); System.out.println("Group names "+ actGrp); if (actGrp.contains(groupName)){ isGroupFound = true; switch(moreOption){ case "Import Into Group" : more = driver().findElement(By.cssSelector(beforeGrpMore+i+afterGrpMore)); more.click(); WebElement import2grp = driver().findElement(By.cssSelector(beforeGrp_Import2Groups+i+afterGrp_Import2Groups)); import2grp.click(); break; case "Print Labels" : more = driver().findElement(By.cssSelector(beforeGrpMore+i+afterGrpMore)); more.click(); WebElement printlbl = driver().findElement(By.cssSelector(beforeGrp_PrintLbls+i+afterGrp_PrintLbls)); printlbl.click(); Thread.sleep(5000); //handlePDFWindow(); break; case "Export Csv" : more = driver().findElement(By.cssSelector(beforeGrpMore+i+afterGrpMore)); more.click(); WebElement exportcsv = driver().findElement(By.cssSelector(beforeGrp_exportCSV+i+afterGrp_exportCSV)); exportcsv.click(); break; case "Export Excel" : more = driver().findElement(By.cssSelector(beforeGrpMore+i+afterGrpMore)); more.click(); WebElement exportexcel = driver().findElement(By.cssSelector(beforeGrp_exportExcel+i+afterGrp_exportExcel)); exportexcel.click(); break; } } } if (isGroupFound==false){ Assert.assertTrue(isGroupFound, groupName + " is not found in the lis of Manage Groups."); } } */ public void performGroupAction(String groupName, String actionName) throws Exception{ logInfo("inside deleteGroup() method"); go2ContactsPage(); selectGroupPanel("Groups ("); boolean isMatchFound = false; waitOnElement("cssSelector","div#group-manager-list"); WebElement tblGroup = driver().findElement(By.cssSelector("div#group-manager-list")); List allGroups = tblGroup.findElements(By.cssSelector("div.group-list-item.clearfix")); int total_groups = allGroups.size(); System.out.println("Total groups = " +total_groups); String before_group = "//div[@id='group-manager-list']/div["; String after_group = "]/div/div/div[2]/div[1]/a"; String after_grpIcon = "]/div/div/div[2]/div[3]/a[2]/i"; String after_grpPanel = "]/div/div/div[2]/div[3]/ul"; String mid_li = "]/div/div/div[2]/div[3]/ul/li["; String after_li = "]/a"; for(int i=total_groups*2;i>=2;i=i-2){ WebElement grp = driver().findElement(By.xpath(before_group+i+after_group)); String actGroupName = grp.getText().trim(); System.out.println("actGroupName = " +actGroupName); if(groupName.equalsIgnoreCase(actGroupName)){ isMatchFound = true; logInfo(actGroupName + " group found in Manage Groups."); scrollDown("xpath",before_group+i+after_grpIcon); WebElement btn = driver().findElement(By.xpath(before_group+i+after_grpIcon)); scrollDown("xpath",before_group+i+after_grpIcon); btn.click(); Thread.sleep(3000); WebElement panel = driver().findElement(By.xpath(before_group+i+after_grpPanel)); List allItems = panel.findElements(By.tagName("li")); for(int j=1;j<=allItems.size();j++) { WebElement x = driver().findElement(By.xpath(before_group+i+mid_li+j+after_li)); String item = x.getText().trim(); if(item.equalsIgnoreCase(actionName)) { x.click(); if(actionName.equalsIgnoreCase("Delete")) { Thread.sleep(3000); confirmOK(); } break; } } break; } } if(isMatchFound==false){ logInfo(groupName + " group not found in Manage Groups."); } } public void renameGroup(String groupName) throws Exception{ logInfo("inside renameGroup() method"); System.out.println("inside renameGroup() method"); String renameGroup_text = groupName+"Updated"; waitOnElement("cssSelector","div.panel-column.panel-main-body.col-md-3.scrollable > div:nth-child(1) > div.row > a:nth-child(1) > i"); clickOnElement("cssSelector","div.panel-column.panel-main-body.col-md-3.scrollable > div:nth-child(1) > div.row > a:nth-child(1) > i"); Thread.sleep(2000); inputTextClear("cssSelector","#pyr_crm_contact_category_category_name"); inputText("cssSelector","#pyr_crm_contact_category_category_name",renameGroup_text); clickOnElement("xpath","//*[@id='new_pyr_crm_contact_category']/div[3]/input[@value='Update']"); Thread.sleep(5000); } public void selectGroup(String grpName) throws Exception{ logInfo("inside selectGroup() method"); WebElement grpCategory = driver().findElement(By.cssSelector("div#group-manager-list ")); List <WebElement> allGroups = grpCategory.findElements(By.cssSelector("div.group-list-item.clearfix")); System.out.println("Manage Size is "+ allGroups.size()); boolean isGroupFound = false; String beforeGpLi ="//div[@id='group-manager-list']/div[" ; String afterGpLi ="]/div[@class='media-body']/div/div[2]/div[1]/a"; int all_groups = allGroups.size()*2; for (int i=2; i<=all_groups; i=i+2){ WebElement gpList = driver().findElement(By.xpath(beforeGpLi+i+afterGpLi)); String actGrp = gpList.getText().trim(); System.out.println("Group names "+ actGrp); if (actGrp.equalsIgnoreCase(grpName)){ isGroupFound = true; logInfo(grpName + " group found"); gpList.click(); Thread.sleep(5000); logInfo("clicked on group " + grpName); break; } } if (isGroupFound==false){ Assert.assertTrue(isGroupFound, grpName + " not found in Manage Groups."); } } public void selectContactFromGroupList(String fName, String lName) throws Exception { logInfo("inside selectContactFromGroupList() method"); waitOnElement("xpath","//div[@id='contacts_selected']"); WebElement contactsPanel = driver().findElement(By.xpath("//*[@id='contacts_selected']")); List allContacts = contactsPanel.findElements(By.cssSelector("div.contact-list-item.list-result.media")); boolean isMatchFound = false; String before_contact = "//*[@id='contacts_selected']/div["; String after_contact = "]/div/div/div[2]/div[1]/a/span[2]"; String before_input = "//*[@id='contacts_selected']/div["; String after_input = "]/div/div/div[3]/input"; if(allContacts.size()>0) { for(int i=1;i<=allContacts.size();i++) { WebElement e = driver().findElement(By.xpath(before_contact+i+after_contact)); String name = e.getText().trim(); if(name.equalsIgnoreCase(fName+" "+lName)) { WebElement input = driver().findElement(By.xpath(before_input+i+after_input)); input.click(); isMatchFound = true; break; } } } if(isMatchFound==false) { logInfo(fName+" "+lName + " contact not found."); Assert.assertTrue(isMatchFound, fName+" "+lName + " contact not found."); } } public void selectActionFromActionbar(String actionName) throws Exception { logInfo("inside selectActionFromActionbar() method"); waitOnElement("xpath","//*[@id='contacts-bulk-actions-bar']/div[2]"); WebElement actionbar = driver().findElement(By.xpath("//*[@id='contacts-bulk-actions-bar']/div[2]/ul")); List allActions = actionbar.findElements(By.tagName("li")); String before_action = "//*[@id='contacts-bulk-actions-bar']/div[2]/ul/li["; String after_action = "]/a"; for(int i=1;i<=allActions.size();i++) { WebElement action = driver().findElement(By.xpath(before_action+i+after_action)); String actAction = action.getText().trim(); System.out.println("actAction = " +actAction); if(actAction.equalsIgnoreCase(actionName)) { action.click(); Thread.sleep(3000); if(actionName.equalsIgnoreCase("Remove From Group")) { Robot rb = new Robot(); rb.keyPress(KeyEvent.VK_ENTER); rb.keyRelease(KeyEvent.VK_ENTER); Thread.sleep(3000); } break; } } } public boolean verifyFileExistsOnDisk(String filepath){ logInfo("inside verifyFileExistsOnDisk() method"); File file = new File(filepath); boolean isFileExists = false; System.out.println("filepath =" + filepath); if(file.exists()) { logInfo("File exists"); isFileExists= true; } else { logInfo("File does not exists"); isFileExists= false; Assert.assertTrue(isFileExists,"File does not exists"); } return isFileExists; } public void searchContactsInGroup(String contactName, String grpName) throws Exception{ logInfo("inside searchContactsInGroup() method"); go2ContactsPage(); selectGroupPanel("Groups ("); boolean isGroupFound = false; Thread.sleep(2000); List <WebElement> gr = driver().findElements(By.cssSelector(groupList)); System.out.println("Manage Size is "+ gr.size()); String beforeGpLi ="div#group-manager-list > div:nth-child(" ; String afterGpLi =") > div:nth-child(1)"; // remove > div > a for (int i=1; i<=gr.size(); i++){ WebElement eleGroup = driver().findElement(By.cssSelector(beforeGpLi+i+afterGpLi)); String actGrp = eleGroup.getText().trim(); System.out.println("Group names "+ actGrp); if (actGrp.contains(grpName)){ logInfo(actGrp + " group match found in the groups table."); isGroupFound = true; String afterGpLia =") > div:nth-child(1) > div > a"; WebElement lnk = driver().findElement(By.cssSelector(beforeGpLi+i+afterGpLia)); lnk.click(); break; } } } // Select contact from contacts list public void selectMultipleContacts(String contactNames, String actionName) throws Exception{ logInfo("inside selectMultipleContacts() methods"); System.out.println("inside selectMultipleContacts() methods"); boolean isContactMatchFound = false; waitOnElement("cssSelector","div.contacts-index-list.actions.summary > div#index-contacts-list > div#contacts_selected"); WebElement panel = driver().findElement(By.cssSelector("div.contacts-index-list.actions.summary > div#index-contacts-list > div#contacts_selected")); List allContacts = panel.findElements(By.cssSelector("div.contact-list-item.list-result.media")); System.out.println("Total Business Contacts =" + allContacts.size()); String before_contactName = "//div[@class='contacts-index-list actions summary']/div[@id='index-contacts-list']/div[@id='contacts_selected']/div["; String after_contactName = "]/div/div/div[2]/div[1]/a/span[2]"; //String before_contactEmail = "//div[@class='contacts-index-list actions summary']/div[@id='index-contacts-list']/div[@id='contacts_selected']/div["; //String after_contactEmail = "]/div/div/div[2]/div[2]"; String before_contactInput = "//div[@class='contacts-index-list actions summary']/div[@id='index-contacts-list']/div[@id='contacts_selected']/div["; String after_contactInput = "]/div/div/div[3]/input"; String before_contactsAction = "#contacts-bulk-actions-bar > div.col-md-7 > ul > li:nth-child("; String after_contactsAction = ") > a"; if(allContacts.size()<=0){ System.out.println("No contacts match found"); // WebElement eNoContacts = driver().findElement(By.xpath("//*[@id='all-contacts-list']/div[@id='list-body']/form/div[@class='alert alert-danger']")); //System.out.println("is NoContactsFound =" +eNoContacts.isDisplayed()); } if(allContacts.size()>0) { for(int i=1;i<=allContacts.size();i++){ WebElement eName = driver().findElement(By.xpath(before_contactName+i+after_contactName)); String actContact = eName.getText().trim(); if(actContact.equalsIgnoreCase(contactNames)){ System.out.println("contact matched..."); isContactMatchFound = true; WebElement eInput = driver().findElement(By.xpath(before_contactInput+i+after_contactInput)); eInput.click(); System.out.println("selected contact"); } } // toggle action WebElement contactActions = driver().findElement(By.cssSelector("#contacts-bulk-actions-bar > div.col-md-7 > ul")); List allActions = contactActions.findElements(By.tagName("li")); for(int k=1; k<=allActions.size();k++){ String before_ActionName = "//div[@id='contacts-bulk-actions-bar']/div[@class='col-md-7']/ul/li["; String after_ActionName = "]/a"; WebElement action = driver().findElement(By.xpath(before_ActionName+k+after_ActionName)); String actActionName = action.getText().trim(); if(actActionName.equalsIgnoreCase(actionName)){ action.click(); break; } } } } // Verify Contact History public void verifyContactHistory(String category, String subject) throws Exception { logInfo("inside verifyTaskInContactHistory() method"); boolean isSubjectFound = false; waitOnElement("xpath","//*[@id='history-items']"); WebElement e = driver().findElement(By.xpath("//*[@id='history-items']")); List allRows = e.findElements(By.className("row")); if(allRows.size()==1) { logInfo("No subject found"); } if(allRows.size()>1) { String before_histsubj = "//*[@id='history-items']/div["; String after_event_task_histsubj = "]/div[2]/a"; String after_histsubj = "]/div[2]"; for(int i=2;i<=allRows.size(); i++) { if(category.equalsIgnoreCase("Task") || category.equalsIgnoreCase("Event") ) { WebElement x = driver().findElement(By.xpath(before_histsubj+i+after_event_task_histsubj)); String actsubj = x.getText().trim(); if(actsubj.equalsIgnoreCase(subject)) { logInfo(subject + " subject found in contact history."); isSubjectFound = true; break; } } else { WebElement x = driver().findElement(By.xpath(before_histsubj+i+after_histsubj)); String actsubj = x.getText().trim(); if(actsubj.equalsIgnoreCase(subject)) { logInfo(subject + " subject found in contact history."); isSubjectFound = true; break; } } } if(isSubjectFound==false) { logInfo(subject + " history match not found"); Assert.assertTrue(isSubjectFound, subject + " history match not found"); } } //return isSubjectFound; } // Select task from contact history. public void selectTaskInContactHistory(String subject) throws Exception { logInfo("inside verifyTaskInContactHistory() method"); boolean isSubjectFound = false; waitOnElement("xpath","//*[@id='history-items']"); WebElement e = driver().findElement(By.xpath("//*[@id='history-items']")); List allRows = e.findElements(By.className("row")); if(allRows.size()==1) { logInfo("No subject found"); } if(allRows.size()>1) { String before_subj = "//*[@id='history-items']/div["; String after_subj = "]/div[2]/a"; for(int i=2;i<=allRows.size(); i++) { WebElement subj = driver().findElement(By.xpath(before_subj+i+after_subj)); String act_subject = subj.getText().trim(); if(act_subject.equalsIgnoreCase(subject)) { logInfo(subject + " subject found in contact history."); clickOnElement("xpath",before_subj+i+after_subj); Thread.sleep(3000); waitOnElement("xpath","//a[contains(text(),'Delete Task')]"); clickOnElement("xpath","//a[contains(text(),'Delete Task')]"); Thread.sleep(3000); confirmOK(); Thread.sleep(3000); logInfo("clicked on Delete Task button"); break; } } } } // Verify Action Items /*public boolean takeActionOnContactEvents(String actionName, String actionType) throws Exception{ logInfo("inside takeActionOnContactEvents() method"); boolean isContactMatchFound = false; waitOnElement("xpath","//div[@id='actionable-list']/div[@id='actionable-list-items']"); WebElement e = driver().findElement(By.xpath("//div[@id='actionable-list']/div[@id='actionable-list-items']")); WebElement eActiontbl = driver().findElement(By.xpath("//div[@id='actionable-list']/div[@id='actionable-list-items']")); List allActions = eActiontbl.findElements(By.cssSelector(".row.list-item")); int all_actions = allActions.size(); String before_contactName = "//div[@id='actionable-list-items']/div["; String before_actionName = "//div[@id='actionable-list-items']/div["; String before_actionType = "//div[@id='actionable-list-items']/div["; if(all_actions>0){ for(int i=1;i<=all_actions;i++){ WebElement eactionName = driver().findElement(By.xpath(before_actionName+i+"]/div[2]/span[1]")); // after_actionName String actActionName = eactionName.getText().trim(); if(actActionName.equalsIgnoreCase(actionName)){ isContactMatchFound = true; logInfo(contactName + " match found in contact home page"); selectFromDropdown("xpath",before_actionType+i+"]/div[3]/form/select","byVisibleText",actionType); // after_actionType if(actionType.equalsIgnoreCase("Delete")) { confirmOK(); } Thread.sleep(3000); logInfo("performed action " +actionType); break; } } } // } if(isContactMatchFound==false){ logInfo(contactName + " match not found in contact home page"); } return isContactMatchFound; }*/ public void viewPersonalProfilePage() throws Exception{ logInfo("inside viewPersonalProfilePage() method"); waitOnElement("linkText","View Personal Profile"); clickOnElement("linkText","View Personal Profile"); waitOnElement("cssSelector","div.modal-content > div.modal-header.clearfix > h1#label-for-consultant-details-modal"); WebElement header = driver().findElement(By.cssSelector("div.modal-content > div.modal-header.clearfix > h1#label-for-consultant-details-modal")); String expHeader = header.getText().trim(); System.out.println("expHeader = " + expHeader); if(expHeader.equalsIgnoreCase("Representative Details")){ logInfo(expHeader + " page title matched"); verifyConsultantDetailsTabs("Business Dashboard"); verifyConsultantDetailsTabs("Sales Performance"); verifyConsultantDetailsTabs("Inquiry"); verifyConsultantDetailsTabs("Leadership History"); verifyConsultantDetailsTabs("Closed Camp Comp"); verifyConsultantDetailsTabs("Reports"); verifyConsultantDetailsTabs("Notes"); verifyConsultantDetailsTabs("Profile"); waitOnElement("xpath","//*[@id='consultant-details-modal']/div/div[1]/div[1]/button[@class='close']/i"); clickOnElement("xpath","//*[@id='consultant-details-modal']/div/div[1]/div[1]/button[@class='close']/i"); } else { logInfo(expHeader + " page title could not be matched"); Assert.assertTrue(expHeader.equalsIgnoreCase("Representative Details"), expHeader + " page title could not be matched"); } } public void verifyConsultantDetailsTabs(String tabName) throws Exception{ logInfo("inside verifyConsultantDetailsTabs() method"); WebElement eTitle; String expTitle; switch(tabName){ case "Business Dashboard": clickOnElement("linkText","Business Dashboard"); waitOnElement("xpath","//*[@class='panel panel-widget kpi-widget']/div[1]/div[1]"); eTitle = driver().findElement(By.xpath("//*[@class='panel panel-widget kpi-widget']/div[1]/div[1]")); expTitle = eTitle.getText().trim(); if(expTitle.equalsIgnoreCase("Business Dashboard")){ logInfo("Business Dashboard title matched"); } else { logInfo("Business Dashboard title could not be matched"); Assert.assertTrue(expTitle.equalsIgnoreCase("Business Dashboard"), "Business Dashboard title could not be matched"); } break; case "Sales Performance": clickOnElement("linkText","Sales Performance"); waitOnElement("xpath","//*[@id='tab-performance']/div[1]/div[1]/div[1]/table/tbody/tr[1]/th[2]"); eTitle = driver().findElement(By.xpath("//*[@id='tab-performance']/div[1]/div[1]/div[1]/table/tbody/tr[1]/th[2]")); expTitle = eTitle.getText().trim(); if(expTitle.equalsIgnoreCase("Current Balance")){ logInfo("Current Balance element found"); } else { logInfo("Current Balance element could not be found"); Assert.assertTrue(expTitle.equalsIgnoreCase("Current Balance"), "Current Balance element could not be found"); } break; case "Inquiry": clickOnElement("linkText","Inquiry"); waitOnElement("xpath","//*[@id='tab-inquiry']/div/div/div"); eTitle = driver().findElement(By.xpath("//*[@id='tab-inquiry']/div/div/div")); expTitle = eTitle.getText().trim(); System.out.println("Inquiry : " + expTitle); //Assert.assertNotEquals(expTitle,"Information is being retrieved - Please standby."); break; case "Leadership History": clickOnElement("linkText","Leadership History"); waitOnElement("xpath","//*[@id='tab-leadership']/div[1]/div[1]/table/thead/tr/th"); eTitle = driver().findElement(By.xpath("//*[@id='tab-leadership']/div[1]/div[1]/table/thead/tr/th")); expTitle = eTitle.getText().trim(); if(expTitle.equalsIgnoreCase("Leadership")){ logInfo("Leadership element found"); } else { logInfo("Leadership element could not be found"); Assert.assertTrue(expTitle.equalsIgnoreCase("Leadership"), "Leadership element could not be found"); } break; case "Closed Camp Comp": clickOnElement("linkText","Closed Camp Comp"); waitOnElement("xpath","//*[@id='tab-comparison']/div/div[1]/div[1]"); eTitle = driver().findElement(By.xpath("//*[@id='tab-comparison']/div/div[1]/div[1]")); expTitle = eTitle.getText().trim(); if(expTitle.equalsIgnoreCase("Closed Campaign Comparison")){ logInfo("Closed Campaign Comparison element found"); } else { logInfo("Closed Campaign Comparison element could not be found"); Assert.assertTrue(expTitle.equalsIgnoreCase("Closed Campaign Comparison"), "Closed Campaign Comparison element could not be found"); } break; case "Reports": waitOnElement("xpath","//*[@id='consultant-details-tab-links']/li[7]/a"); clickOnElement("xpath","//*[@id='consultant-details-tab-links']/li[7]/a"); break; case "Notes": waitOnElement("xpath","//*[@id='consultant-details-tab-links']/li[8]/a"); clickOnElement("xpath","//*[@id='consultant-details-tab-links']/li[8]/a"); waitOnElement("xpath","//*[@id='tab-notes']/div[1]/div[1]"); Thread.sleep(5000); eTitle = driver().findElement(By.xpath("//*[@id='tab-notes']/div[1]/div[1]")); expTitle = eTitle.getText().trim(); if(expTitle.equalsIgnoreCase("Notes")){ logInfo("Notes element found"); } else { logInfo("Notes element could not be found"); Assert.assertTrue(expTitle.equalsIgnoreCase("Notes"), "Notes element could not be found"); } break; case "Profile": clickOnElement("linkText","Profile"); waitOnElement("xpath","//*[@id='tab-profile']/div[1]/div[1]/table/thead/tr/th"); eTitle = driver().findElement(By.xpath("//*[@id='tab-profile']/div[1]/div[1]/table/thead/tr/th")); expTitle = eTitle.getText().trim(); if(expTitle.equalsIgnoreCase("Location Information")){ logInfo("Location Information element found"); } else { logInfo("Location Information element could not be found"); Assert.assertTrue(expTitle.equalsIgnoreCase("Location Information"), "Location Information element could not be found"); } break; } } public void selectGroupActions(String actionName) throws Exception{ logInfo("inside selectGroupActions() method."); waitOnElement("xpath","//*[@id='contacts_select_all']"); clickOnElement("xpath","//*[@id='contacts_select_all']"); //waitOnElement("xpath","//*[@id='contacts-bulk-action-dropdown']/button"); clickOnElement("xpath","//*[@id='contacts-bulk-action-dropdown']/button"); WebElement grpActions = driver().findElement(By.xpath("//ul[@id='contact-dropdown-actions']")); List allItems = grpActions.findElements(By.tagName("li")); String before_li = "//ul[@id='contact-dropdown-actions']/li["; String after_li = "]/a"; if(allItems.size() >0){ for(int i=1;i<=allItems.size();i++){ WebElement eActionName = driver().findElement(By.xpath(before_li+i+after_li)); String actAction = eActionName.getText().trim(); if(actAction.equalsIgnoreCase(actionName)){ logInfo(actionName + " action match found."); eActionName.click(); Thread.sleep(5000); break; } } } } public void selectGroupsForAdd2Groups(String groupName) throws Exception{ logInfo("inside selectGroupsForAdd2Groups() method. "); waitOnElement("xpath","//table[@id='listContactGroups']"); WebElement selectGrpTbl = driver().findElement(By.xpath("//table[@id='listContactGroups']/tbody")); List allRows = selectGrpTbl.findElements(By.tagName("tr")); String before_grpName = "//table[@id='listContactGroups']/tbody/tr["; String after_grpName = "]/td[2]"; String before_grpInput = "//table[@id='listContactGroups']/tbody/tr["; String after_grpInput = "]/td[1]/input"; if(allRows.size() >0){ for(int i=1;i<=allRows.size();i++){ WebElement eGrp = driver().findElement(By.xpath(before_grpName+i+after_grpName)); String actGrp = eGrp.getText().trim(); if(actGrp.equalsIgnoreCase(groupName)){ WebElement input = driver().findElement(By.xpath(before_grpInput+i+after_grpInput)); input.click(); break; } } } scrollDown("xpath","//*[@id='add_to_group']"); clickOnElement("xpath","//*[@id='add_to_group']"); } // **************************************************************************************************************************************************** // ******************** RAVI's METHODS **************************************************************************************************************** public void addBussinesscontactwithoutInfo(String fName, String lName) throws Exception{ logInfo("inside contactwithNoInfomation() method. "); go2ContactsPage(); selectContactsCategoryList("Recent Contacts"); waitOnElement("cssSelector","#add-a-contact>a"); clickOnLink("cssSelector", "#add-a-contact>a"); Thread.sleep(5000); waitOnElement("cssSelector",inputContactFirstName); inputText("cssSelector",inputContactFirstName,fName); // contactFirstName_text inputText("cssSelector",inputContactLastName,lName); // contactLastName_text logInfo("Entered all the fields in Business -> AddContact page."); clickOnButton("cssSelector",btnUpdateContact); Thread.sleep(5000); } public void verifyGroupNdDelete(String groupName) throws Exception{ logInfo("inside verifyGroupNdDelete method"); go2ContactsPage(); selectGroupPanel("Groups ("); clickOnLink("linkText", "Manage Groups"); boolean isGroupFound = false; Thread.sleep(2000); List <WebElement> gr = driver().findElements(By.cssSelector(groupList)); System.out.println("Manage Size is "+ gr.size()); String beforeGpLi ="div#group-manager-list > div:nth-child(" ; String afterGpLi =") > div:nth-child(1)"; String afterdel = ") > div:nth-child(2) > a:nth-child(2)"; for (int i=1; i<=gr.size(); i++){ WebElement gpList = driver().findElement(By.cssSelector(beforeGpLi+i+afterGpLi)); String actGrp = gpList.getText().trim(); System.out.println("Group names "+ actGrp); if (actGrp.contains(groupName)){ isGroupFound = true; WebElement grpMoreSelect = driver().findElement(By.cssSelector(beforeGpLi+i+afterdel)); grpMoreSelect.click(); tm.deleteConfirm(); /* confirmEventDeleteModal();*/ confirmationMessage("Group Deleted."); break; } } if (isGroupFound==false){ Assert.assertTrue(isGroupFound, groupName + " is not found in the list of Manage Groups."); } } public void reverifyGroup(String groupName) throws Exception{ logInfo("inside reverifyGroup method"); clickOnLink("linkText", "Manage Groups"); boolean isGroupFound = false; Thread.sleep(2000); List <WebElement> gr = driver().findElements(By.cssSelector(groupList)); System.out.println("Manage Size is "+ gr.size()); String beforeGpLi ="div#group-manager-list > div:nth-child(" ; String afterGpLi =") > div:nth-child(1)"; for (int i=1; i<=gr.size(); i++){ WebElement gpList = driver().findElement(By.cssSelector(beforeGpLi+i+afterGpLi)); String actGrp = gpList.getText().trim(); System.out.println("Group names "+ actGrp); if (actGrp.contains(groupName)){ isGroupFound = false; Assert.assertEquals(isGroupFound, groupName + " - Groupp is found"); } } if (isGroupFound==true){ System.out.println("Group is not found"); } } public void addToGroupsList(String grpName) throws Exception{ logInfo("addToGroupsList(String grpName method "); boolean isGrpPresent = false; List <WebElement> grp = driver().findElements(By.cssSelector(grpList)); System.out.println("Size of groups "+ grp.size()); Thread.sleep(2000); for (int i=1; i<=grp.size();i++){ WebElement grps = driver().findElement(By.cssSelector(grpList1+i+grpList2)); System.out.println("name are "+grps.getText().trim()); if (grps.getText().trim().equalsIgnoreCase(grpName)){ isGrpPresent= true; WebElement cb = driver().findElement(By.cssSelector(grpList1+i+grpCheckbox2)) ; cb.click(); clickOnButton("cssSelector", addGrpBtn); break; } }if (isGrpPresent==false){ Assert.assertTrue(isGrpPresent, grpName + " is not found" ); } } public void sendMessage2PrefferedContacts(String subject) throws Exception{ logInfo("inside sendMessage2PrefferedContacts() method."); System.out.println("inside sendMessage2PrefferedContacts() method."); clickOnElement("xpath",lnkSendMesg); Thread.sleep(3000); waitOnElement("cssSelector",subject_Mail); inputText("cssSelector",subject_Mail,subject ); composeText("xpath","//iframe[contains(@title,'Rich Text Editor, pyr_core_user_task_description')]",subject + " description."); clickOnLink("linkText", "Send"); Thread.sleep(5000); } public void sendMessage2Contacts(String fName, String lName, String recepients,String subject) throws Exception{ logInfo("inside sendMessage2Contacts() method."); System.out.println("inside sendMessage2Contacts() method."); /*go2ContactsPage(); selectContactsCategoryList("Recent Contacts"); selectBusinessContact(contactFirstName_text,contactLastName_text); selectContactAction("Send Message"); */ waitOnElement("cssSelector",recipientsTo); clickOnElement("cssSelector",recipientsTo); inputText("cssSelector",recipientsTo, recepients); inputText("cssSelector",subject_Mail,subject ); composeText("xpath","//iframe[contains(@title,'Rich Text Editor')]","sending message to a contact"); clickOnLink("linkText", "Send"); Thread.sleep(10000); } public void selectContactActions(String contactAction) throws InterruptedException{ logInfo("Inside selectContactActions method"); String B4rAct = "//*[@id='contact-actions']/div["; String A4rAct = "]/a/span[2]"; boolean isActionFound = false; List<WebElement> act = driver().findElements(By.xpath(allActions)); System.out.println(act.size()); Thread.sleep(2000); for (int i = 1; i<=act.size(); i++){ WebElement actions = driver().findElement(By.xpath(B4rAct+i+A4rAct)); String conatActions = actions.getText(); System.out.println(conatActions); if (conatActions.contains(contactAction)){ isActionFound = true; actions.click(); break; } }if (isActionFound){ Assert.assertTrue(isActionFound,contactAction + " item is not found in the Conatct Actions" ); } } public void selectSocialNetwork(String socialNetwork){ logInfo("Inside selectSocialNetwork method"); List <WebElement> soc = driver().findElements(By.cssSelector(socialList)); System.out.println(soc.size()); for(WebElement social :soc){ System.out.println(social.getText()); if (social.getText().equalsIgnoreCase(socialNetwork)){ social.click(); break; } } } public void gmailContacts(String gmail, String passwd) throws Exception{ logInfo ("Inside gmailContacts method"); logInfo("Enter Gmail credentials and Import all contacts"); String wndBeforeWindow = driver().getWindowHandle(); for(String w : driver().getWindowHandles()){ if(!w.equalsIgnoreCase(wndBeforeWindow)){ driver().switchTo().window(w); Thread.sleep(3000); inputTextClear("cssSelector",inputGmail); inputText("cssSelector",inputGmail, gmail); clickOnButton("cssSelector", btnGmailNext); WebElement staysigned = driver().findElement(By.xpath(chkStaySignedIn)); String isChecked = staysigned.getAttribute("checked").trim(); if(isChecked.equalsIgnoreCase("checked")){ staysigned.click(); } inputText("cssSelector",inputGmailPasswd, passwd); clickOnButton("cssSelector", btnSignIn); Thread.sleep(6000); clickOnButton("xpath", "//*[@id='submit_approve_access']"); Thread.sleep(4000); WebElement gText = driver().findElement(By.cssSelector(gmailText)); String actImportMsg = gText.getText().trim(); String expImportMsg = "Close this window and see the import status in bell alerts."; String errImportMsg ="There was a problem importing contacts, please try again later or contact Customer Service."; System.out.println("actImportMsg = " + actImportMsg); driver().close(); driver().switchTo().window(wndBeforeWindow); /*if(actImportMsg!=expImportMsg){ Assert.assertFalse(actImportMsg!=expImportMsg, "Import Unsuccessful"); }*/ break; } } } public void YahooContacts(String yahoo, String passwd) throws Exception{ logInfo("Inside YahooContacts method"); logInfo("Enter Yahoo credentials and Import all contacts"); String wndBeforeWindow = driver().getWindowHandle(); for(String w : driver().getWindowHandles()){ if(!w.equalsIgnoreCase(wndBeforeWindow)){ driver().switchTo().window(w); Thread.sleep(3000); // check if email and pwd are visible. else switch to main window WebElement e = driver().findElement(By.xpath(yaEmail)); if(!e.isDisplayed()){ driver().switchTo().defaultContent(); logInfo("switching back to main window." + yaEmail + " element not found."); Assert.assertTrue(e.isDisplayed()); } inputTextClear("xpath",yaEmail); inputText("xpath",yaEmail, yahoo); clickOnButton("xpath", yaNext); Thread.sleep(3000); inputText("xpath",yaPwd, passwd); clickOnButton("xpath", yaNext); Thread.sleep(3000); clickOnButton("cssSelector", yahooAgree); Thread.sleep(6000); driver().close(); driver().switchTo().window(wndBeforeWindow); break; } } } public void hotmailContacts(String hotmail, String passwd) throws Exception{ logInfo("Inside hotmailContacts method"); logInfo("Enter hotmail credentials and Import all contacts"); String wndBeforeWindow = driver().getWindowHandle(); for(String w : driver().getWindowHandles()){ if(!w.equalsIgnoreCase(wndBeforeWindow)){ driver().switchTo().window(w); Thread.sleep(3000); inputTextClear("cssSelector",hotEmail); inputText("cssSelector",hotEmail, hotmail); inputText("cssSelector",hotPwd, passwd); clickOnElement("cssSelector", hotPwd); Thread.sleep(3000); clickOnButton("cssSelector", hotSign); String hotExpText= "Close this window and see the import status in bell alerts."; WebElement alertMsg = driver().findElement(By.cssSelector(hotActText)); Assert.assertEquals(alertMsg.getText(), hotExpText); Thread.sleep(6000); driver().close(); driver().switchTo().window(wndBeforeWindow); break; } } } public void eventValidate() throws Exception{ logInfo("inside eventValidate() Method"); Thread.sleep(2000); inputTextClear("cssSelector", eventName); Thread.sleep(2000); clickOnButton("cssSelector", finalSave); confirmationMessage("Please enter Title name"); } public void validatePrintLabelWindow() throws InterruptedException { logInfo("inside validatePrintLabelWindow method"); Thread.sleep(5000); String parent = driver().getWindowHandle(); // parent window System.out.println("parent = " +parent); Set<String> childs = driver().getWindowHandles(); for(String x : childs) { System.out.println("x = " +x); if(!x.equalsIgnoreCase(parent)) { driver().switchTo().window(x); System.out.println("matched x = " +x); validateTextOnElement("xpath","//*[@id='pageContainer1']/xhtml:div[2]/xhtml:div[1]","Test Contact"); break; } } } public void validateGmailImport(String groupName, String moreOption, String gmail, String Pwd) throws Exception{ logInfo("inside validateGmailImport Method"); waitOnElement("xpath","//div[@id='import-contacts-modal']/div/div/div/form/div/div[1]/a/div[2]"); clickOnElement("xpath","//div[@id='import-contacts-modal']/div/div/div/form/div/div[1]/a/div[2]"); Thread.sleep(5000); String parent = driver().getWindowHandle(); // parent window System.out.println("parent = " +parent); Set<String> childs = driver().getWindowHandles(); for(String x : childs) { System.out.println("x = " +x); if(!x.equalsIgnoreCase(parent)) { driver().switchTo().window(x); System.out.println("matched x = " +x); waitOnElement("xpath","//input[@id='identifierId']"); inputText("xpath","//input[@id='identifierId']","vibe.icentris@gmail.com"); clickOnElement("xpath","//*[@id='identifierNext']/content/span"); Thread.sleep(4000); waitOnElement("xpath","//*[@id='password']/div[1]/div/div[1]/input[@type='password']"); inputText("xpath","//*[@id='password']/div[1]/div/div[1]/input[@type='password']","vibe@123"); clickOnElement("xpath","//*[@id='passwordNext']/content/span"); Thread.sleep(4000); break; } } } public void validateYahooImport(String groupName, String moreOption, String yahoo, String Pwd) throws Exception{ logInfo("inside validateYahooImport Method"); waitOnElement("xpath","//div[@id='import-contacts-modal']/div/div/div/form/div/div[2]/a/div[2]"); clickOnElement("xpath","//div[@id='import-contacts-modal']/div/div/div/form/div/div[2]/a/div[2]"); Thread.sleep(5000); String parent = driver().getWindowHandle(); // parent window System.out.println("parent = " +parent); Set<String> childs = driver().getWindowHandles(); for(String x : childs) { System.out.println("x = " +x); if(!x.equalsIgnoreCase(parent)) { driver().switchTo().window(x); System.out.println("matched x = " +x); waitOnElement("xpath","//*[@id='login-username']"); inputText("xpath","//*[@id='login-username']","vibe.icentris@yahoo.com"); clickOnElement("xpath","//input[@id='login-signin']"); Thread.sleep(4000); clickOnElement("xpath","//*[@id='recaptcha-anchor']/div[5]"); Thread.sleep(4000); clickOnElement("xpath","//*[@id='recaptcha-submit']"); Thread.sleep(4000); waitOnElement("xpath","//*[@id='login-passwd']"); inputText("xpath","//*[@id='login-passwd']","vibe@123"); clickOnElement("xpath","//*[@id='login-signin']"); Thread.sleep(4000); break; } } } public void validateHotmailImport(String groupName, String moreOption, String hotmail, String Pwd) throws Exception{ logInfo("inside validateHotmailImport Method"); WebElement ac = driver().findElement(By.cssSelector(alertCount)); String al = ac.getText(); int alertsCount = Integer.parseInt(al); int increasedAlerts= alertsCount+1; String increasedAlertsCount = Integer.toString(increasedAlerts); System.out.println("Normal count is "+ alertsCount); //selectGroupAndMoreOption(groupName , "Import Into Group"); performGroupAction(groupName_text,"Import Into Group"); selectSocialNetwork("Import Hotmail"); hotmailContacts(hotmail, Pwd); go2ContactsPage(); WebElement aftcount = driver().findElement(By.cssSelector(alertCount)); String afterCount = aftcount.getText(); System.out.println(afterCount + " and "+ increasedAlertsCount); // Assert.assertEquals(afterCount, increasedAlertsCount); } public void directHotmail(String hotmail, String Pwd) throws Exception{ logInfo("inside directHotmail Method"); clickOnLink("linkText", "Manage Groups"); clickOnLink("linkText", "Import"); selectSocialNetwork("Import Hotmail"); hotmailContacts(hotmail, Pwd); go2ContactsPage(); } public void historyItems(String historyItems) throws Exception{ logInfo("inside historyItems Method"); boolean isHistoryItem = false; Thread.sleep(4000); String beforHist = "//*[@id='history-items']/div["; String afterHist = "]/div[2]"; List<WebElement> act = driver().findElements(By.xpath(histItems)); System.out.println(act.size()); for (int i = 1; i<=act.size(); i++){ WebElement items = driver().findElement(By.xpath(beforHist+i+afterHist)); String conatActions = items.getText(); System.out.println(conatActions); if (conatActions.contains(historyItems)){ isHistoryItem= true; items.click(); break; } }if (isHistoryItem){ Assert.assertTrue(isHistoryItem,historyItems + " is not found in the History item" ); } } public void validateInvalidAlertsforMailing(String recepients1, String recepients2) throws Exception { logInfo("inside validateInvalidAlertsforMailing Method"); String alertMsgText ="Invalid email addresses, please correct: "; String alertMsgOfNoMailText = "Please add a recipient to your message."; selectContactActions("Send Message"); waitOnElement("cssSelector",recipientsTo); clickOnElement("cssSelector",recipientsTo); inputText("cssSelector",recipientsTo, recepients1); inputText("cssSelector",subject_Mail, subjectContent1); clickOnLink("linkText", "Send"); Thread.sleep(3000); WebElement alertMsg = driver().findElement(By.cssSelector(aletMsg)); System.out.println(" alert msg is "+alertMsg.getText()); Assert.assertEquals(alertMsg.getText(), alertMsgText+recepients1); clickOnButton("cssSelector", btnPhoneScriptSave); waitOnElement("cssSelector",recipientsTo); /*clickOnElement("cssSelector",recipientsTo);*/ inputTextClear("cssSelector",recipientsTo); inputTextClear("cssSelector",recipientsTo); WebElement recp = driver().findElement(By.cssSelector(recipientsTo)); recp.sendKeys(Keys.BACK_SPACE); recp.sendKeys(Keys.BACK_SPACE); recp.sendKeys(Keys.BACK_SPACE); recp.sendKeys(Keys.BACK_SPACE); recp.sendKeys("\u0008"); recp.sendKeys("\u0008"); clickOnLink("linkText", "Send"); Thread.sleep(3000); WebElement alertMsg2 = driver().findElement(By.cssSelector(aletMsg)); System.out.println(" alert msg is "+alertMsg2.getText()); Assert.assertEquals(alertMsg2.getText(), alertMsgOfNoMailText); clickOnButton("cssSelector", btnPhoneScriptSave); waitOnElement("cssSelector",recipientsTo); inputText("cssSelector",recipientsTo, recepients2); inputTextClear("cssSelector",subject_Mail); inputText("cssSelector",subject_Mail, subjectContent1); clickOnLink("linkText", "Send"); Thread.sleep(3000); confirmationMessage("Your message has been sent to "+recepients2 ); } public void replyNForwardMail(String recepients2, String subject) throws Exception{ logInfo("inside replyNForwardMail Method"); String Attach1 = "Attach To Message" ; String Attach2 = "Insert Into Message Editor" ; selectContactActions("View History"); clickOnLink("linkText", subject); clickOnLink("linkText", "Reply"); waitOnElement("cssSelector",recipientsTo); clickOnLink("linkText", "Send"); Thread.sleep(3000); // confirmationMessage("Your message has been sent to "+recepients2 ); /*clickOnLink("linkText", subject); clickOnLink("linkText", "Forward"); Thread.sleep(4000); inputText("cssSelector",recipientsTo, recepients2); inputTextClear("cssSelector",subject_Mail); inputText("cssSelector",subject_Mail, subject); clickOnButton("cssSelector", attach); Thread.sleep(4000); clickOnElement("xpath", browseInBr); Thread.sleep(5000); Runtime.getRuntime().exec(projectPath + "\\testdata\\auto-it\\ProfAudio.exe"); Thread.sleep(5000); cm.uploadFooter(Attach1); Thread.sleep(3000); clickOnLink("linkText", "Send"); Thread.sleep(3000); confirmationMessage("Your message has been sent to "+recepients2 ); */ } public void uploadMoreThan4MBfile(String recepients, String fileName) throws Exception{ logInfo("inside uploadMoreThan4MBfile method."); selectContactAction("Send Message"); waitOnElement("cssSelector",recipientsTo); clickOnElement("cssSelector",recipientsTo); inputText("cssSelector",recipientsTo, recepients); inputText("cssSelector",subject_Mail, "Upload more than 4MB file"); composeText("xpath","//iframe[contains(@title,'Rich Text Editor, email_textarea')]","Upload more than 4MB file."); clickOnButton("xpath", "//label[contains(text(),'Attach A File')]"); Thread.sleep(3000); Runtime.getRuntime().exec(projectPath + "\\testdata\\auto-it\\"+fileName+".exe"); Thread.sleep(15000); //clickOnLink("linkText", "Send"); confirmationMessage(fileName+ "MoreThan4MbImg.jpg could not be saved.Max file size is 4 MB"); } public void validateEmailErrMsg() throws Exception{ logInfo("inside validateEmailErrMsg() Method"); waitOnElement("cssSelector","div.alert.alert-danger > ul > li"); String actErrMsg = getTextPresentOnElement("cssSelector","div.alert.alert-danger > ul > li"); System.out.println("actErrMsg =" +actErrMsg); Assert.assertEquals(actErrMsg, "Email has already been taken"); /* WebElement alert = driver().findElement(By.cssSelector(mailAlert)); String msg = "Email has already been taken"; Assert.assertEquals(alert.getText(), msg);*/ } public void contactSearch(String searchText) throws Exception{ logInfo("inside conatctSearch() method"); String expResult = "No Contacts Found"; Thread.sleep(2000); inputTextClear("xpath", contSearch); inputText("xpath", contSearch, searchText); Thread.sleep(2000); clickOnElement("xpath", contSearch); waitOnElement("cssSelector","form#contacts_selected > div.alert.alert-danger"); WebElement searResult = driver().findElement(By.cssSelector("form#contacts_selected > div.alert.alert-danger")); Assert.assertEquals(searResult.getText(), expResult); } public void advancedContactSearch(String searchText) throws Exception{ logInfo("inside advancedContactSearch() method"); String expResult = "No Contacts Found"; clickOnLink("cssSelector","div.col-md-1.col-sm-1.col-xs-4.landing-action.no-gutter"); Thread.sleep(3000); clickOnElement("cssSelector","div.col-md-1.col-sm-1.col-xs-4.landing-action.no-gutter.open > ul > li > a > span"); Thread.sleep(3000); inputTextClear("cssSelector", contFName); inputText("cssSelector",contFName,searchText); clickOnButton("cssSelector", advSerch); Thread.sleep(2000); WebElement searResult2 = driver().findElement(By.cssSelector("form#contacts_selected > div.alert.alert-danger")); // searchReslt Assert.assertEquals(searResult2.getText(), expResult); } public void downLineSearch(String searchText) throws Exception{ logInfo("inside downLineSearch(String searchText) Method"); String expResult = "No Contacts Found"; clickOnLink("linkText","Downline ("); Thread.sleep(2000); inputTextClear("xpath", contSearch); inputText("xpath", contSearch, searchText); Thread.sleep(2000); clickOnElement("xpath", contSearch); WebElement searResult = driver().findElement(By.cssSelector("form#contacts_selected > div.alert.alert-danger")); Assert.assertEquals(searResult.getText(), expResult); } public void groupSearch(String searchText) throws Exception{ logInfo("inside groupSearch() method"); String expResult = "No groups found."; inputTextClear("xpath", grpSearch); inputText("xpath", grpSearch, searchText); Thread.sleep(2000); clickOnElement("xpath", grpSearch); WebElement searResult = driver().findElement(By.cssSelector("form#contacts_selected > div.alert.alert-danger")); Assert.assertEquals(searResult.getText(), expResult); Thread.sleep(2000); } public void conatctList(String FName, String Lname) throws Exception{ logInfo("inside conatctList(String FName, String Lname) Method"); Thread.sleep(3000); boolean ispresent = false; List <WebElement> all = driver().findElements(By.xpath(allContacts)); System.out.println(" All Size is "+all.size()); for (int i = 1; i<=all.size(); i++){ String b4r1 = "//*[starts-with(@id,'3')]"; String b4r2= "]/div["; String b4Con = "//div/form/div["; String a4Con = "]/div[2]/div/div[2]/h4/div/a/span[2]"; //"]/div[2]/div"; ///div/a/span[2] WebElement lis = driver().findElement(By.xpath(b4Con+i+a4Con)); System.out.println("conatcts are "+lis.getText()); if (lis.getText().trim().equalsIgnoreCase(FName+" "+Lname)){ ispresent =true; String a4CheckBox ="]/div[1]/input"; WebElement check = driver().findElement(By.xpath(b4Con+i+a4CheckBox)); check.click(); break; } }if (ispresent==false){ Assert.assertTrue(ispresent,FName+" "+Lname +" contact is not found" ); } } public boolean verifyContactPresent(String FName, String Lname) throws Exception{ logInfo("inside conatctList(String FName, String Lname) Method"); Thread.sleep(3000); boolean ispresent = false; List <WebElement> all = driver().findElements(By.xpath(allContacts)); System.out.println(" All Size is "+all.size()); for (int i = 1; i<=all.size(); i++){ String b4Con = "//div/form/div["; String a4Con = "]/div[2]/div/div[2]/h4/div/a/span[2]"; //"]/div[2]/div"; ///div/a/span[2] WebElement lis = driver().findElement(By.xpath(b4Con+i+a4Con)); System.out.println("conatcts are "+lis.getText()); if (lis.getText().trim().equalsIgnoreCase(FName+" "+Lname)){ ispresent =true; logInfo(lis.getText().trim() + " business contact match found."); break; } }if (ispresent==false){ Assert.assertTrue(ispresent,FName+" "+Lname +" contact is not found" ); } return ispresent; } public void selectContactOptions(String toggleType){ logInfo("inside selectContactOptions(String toggleType) Method"); clickOnElement("cssSelector", toggle); boolean istogglePresent = false; List <WebElement> lit = driver().findElements(By.cssSelector("ul#contact-dropdown-actions > li >a")); System.out.println(lit.size()+ " size is "); for (WebElement list :lit){ System.out.println("List is "+ list.getText()); if (list.getText().trim().equalsIgnoreCase(toggleType)){ istogglePresent = true; list.click(); break; } }if (istogglePresent==false){ Assert.assertEquals(istogglePresent, toggleType+ " is not found in the toggle list"); } } /*public void handlePDFWindow() throws Exception{ logInfo("verify details in pdf page"); String expText = "No contacts with addresses found."; String wndBeforeWindow = driver().getWindowHandle(); for(String w : driver().getWindowHandles()){ if(!w.equalsIgnoreCase(wndBeforeWindow)){ driver().switchTo().window(w); System.out.println(driver().getTitle()); WebElement text = driver().findElement(By.cssSelector("div#pageContainer1.page > div.textLayer > div")); if(text.getText().trim().equalsIgnoreCase(expText)){ Assert.assertTrue(true, "Able to get addresses in the pdf window for print labels."); } // Assert.assertEquals(text.getText(), expText); Thread.sleep(3000); driver().close(); Thread.sleep(8000); driver().switchTo().window(wndBeforeWindow); break; } } } */ public void handlePDFWindow() throws Exception{ logInfo("inside handlePDFWindow() method"); String expText = "No contacts with addresses found."; String parent = driver().getWindowHandle(); System.out.println("parent =" +parent); Set <String> allWindows = driver().getWindowHandles(); int count = allWindows.size(); for(String child: allWindows) { if(!parent.equalsIgnoreCase(child)) { driver().switchTo().window(child); System.out.println("child = " + child); break; } } } public void taskAlerts() throws Exception{ logInfo("inside taskAlerts() Method"); String msgText = "can't be blank"; String msgText2 = "Task Title can't be blank"; selectContactActions("Create Task"); clickOnButton("xpath",inputAddTask); WebElement alertMsg = driver().findElement(By.cssSelector(alrtMsg)); Assert.assertEquals(alertMsg.getText(), msgText); WebElement alertMsg2 = driver().findElement(By.cssSelector(alrtMsg2)); Assert.assertEquals(alertMsg2.getText(), msgText2); Thread.sleep(2000); } public void callScriptAlert() throws Exception{ logInfo("inside callScriptAlert Method"); String msgText = "can't be blank"; selectContactActions("Start Call Script"); Thread.sleep(2000); clickOnButton("cssSelector",inputSubmitCallscript); Thread.sleep(2000); WebElement alertMsg = driver().findElement(By.cssSelector(alrtMsg)); Assert.assertEquals(alertMsg.getText(), msgText); Thread.sleep(2000); } public void notesAlert() throws Exception{ logInfo("inside notesAlert Method"); String msgText = "can't be blank"; selectContactActions("Notes"); Thread.sleep(2000); waitOnElement("linkText","New Note"); clickOnLink("linkText","New Note"); clickOnButton("cssSelector",btnCreateContactNote); Thread.sleep(2000); WebElement alertMsg = driver().findElement(By.cssSelector(alrtMsg)); Assert.assertEquals(alertMsg.getText(), msgText); Thread.sleep(2000); } public void eventAlert() throws Exception{ logInfo("inside eventAlert() Method"); String alrtMsg = "Please enter Title name"; String alrtMsgforStartDate = "Please enter Start date"; selectContactActions("Create Event"); Thread.sleep(2000); inputTextClear("cssSelector",inputAppointmentName); clickOnElement("xpath", btnEventSave); confirmationMessage(alrtMsg); } public void setPreferredEmail2Contact(String email2) throws Exception{ logInfo("inside setPreferredEmail2Contact method"); waitOnElement("linkText", "Edit"); clickOnLink("linkText", "Edit"); Thread.sleep(5000); clickOnElement("xpath",lnkAddMoreEmails); String input2 = "//*[@class='simple_form view-container']/div[3]/div/p/div[1]/div/div/div/input"; inputText("xpath",input2, email2); clickOnElement("xpath","//*[@class='simple_form view-container']/div[3]/div/p/div[1]/div/div/div/span[1]"); clickOnButton("xpath","//input[@value='Update Contact']"); confirmationMessage("Contact is updated"); Thread.sleep(5000); } /*public void addMultiEmails(String email) throws Exception{ logInfo("inside addMultiEmails Method"); String mal1 = "//div[3]/div/p/div[1]/div/div/div/input"; String mal2 = "//div[3]/div/p/div[2]/div/div/div/input"; String mal3 = "//div[3]/div/p/div[3]/div/div/div/input"; String prefer = "//div[3]/div/p/div[3]/div/div/div/span[1]/i"; String star = "div[3]/div[2]/div[1]/div[1]/div[3]/span"; Thread.sleep(5000); clickOnLink("linkText", "Edit"); Thread.sleep(4000); clickOnLink ("linkText", "Add More Email"); Thread.sleep(2000); clickOnLink ("linkText", "Add More Email"); Thread.sleep(2000); clickOnLink ("linkText", "Add More Email"); inputText("xpath", mal1, recipientsOne_text); Thread.sleep(2000); inputText("xpath", mal2, recipientsGmail_text); inputText("xpath", mal3, email); clickOnElement ("xpath", prefer); clickOnButton("cssSelector",btnUpdateContact); Thread.sleep(5000); WebElement mailer = driver().findElement(By.cssSelector("div > div > span#preferred-email")); System.out.println(mailer.getText()); WebElement mailer1 = driver().findElement(By.cssSelector("div#contact-details-panel > #contact-details > div > div > a")); System.out.println("Mailer1"+mailer1.getText() ); WebElement mailer2 = driver().findElement(By.xpath("//*[@id='contact-details']/div[1]/div[1]/div/a")); System.out.println("Mailer2"+mailer2.getText() ); } */ public void addContactsAlerts(String FirstName) throws Exception{ logInfo("inside addContactsAlerts() method. "); System.out.println("inside addContactsAlerts() method. "); String ExpMsg= "Name and email cannot be blank."; // Please add the name to your contact. Please add an email to your contact. go2ContactsPage(); waitOnElement("cssSelector","#add-a-contact>a"); clickOnLink("cssSelector", "#add-a-contact>a"); Thread.sleep(5000); clickOnButton("cssSelector",btnUpdateContact); Thread.sleep(2000); WebElement actMsg = driver().findElement(By.cssSelector(alrtMsg2)); String actualMsg = actMsg.getText(); Assert.assertEquals(actualMsg, ExpMsg); inputText("cssSelector",inputContactLastName,lName); clickOnButton("cssSelector",btnUpdateContact); Thread.sleep(2000); WebElement actMsg2 = driver().findElement(By.cssSelector(alrtMsg2)); String actualMsg2 = actMsg2.getText(); Assert.assertEquals(actualMsg2, ExpMsg); inputText("cssSelector",inputContactFirstName,FirstName); inputTextClear("cssSelector",inputContactLastName); clickOnButton("cssSelector",btnUpdateContact); confirmationMessage("Contact is created"); Thread.sleep(2000); clickOnLink("linkText", "Edit"); Thread.sleep(2000); inputTextClear("cssSelector",inputContactFirstName); clickOnButton("cssSelector",btnUpdateContact); Thread.sleep(2000); WebElement actMsg3 = driver().findElement(By.cssSelector(alrtMsg2)); String actualMsg3 = actMsg3.getText(); Assert.assertEquals(actualMsg3, ExpMsg); Thread.sleep(2000); inputText("cssSelector",inputContactFirstName,FirstName); clickOnButton("cssSelector",btnUpdateContact); confirmationMessage("Contact is updated"); } public boolean attachResource2SendMessage(String fName, String lName, String recepients,String resName,String resAsset) throws Exception{ logInfo("inside attachResource2SendMessage() method."); System.out.println("inside attachResource2SendMessage() method."); boolean isAssetAttached = false; go2ContactsPage(); selectContactsCategoryList("Recent Contacts"); selectBusinessContact(contactFirstName_text,contactLastName_text); waitOnElement("xpath",lnkSendMesg); Thread.sleep(5000); clickOnElement("xpath",lnkSendMesg); waitOnElement("cssSelector",recipientsTo); clickOnElement("cssSelector",recipientsTo); inputText("cssSelector",recipientsTo, recepients); inputText("cssSelector",subject_Mail, inputSendMessageSubject_text); composeText("xpath","//iframe[contains(@title,'Rich Text Editor')]","attaching a resoruce and sending a message"); // Robot rb= new Robot(); /* rb.delay(2000); rb.keyPress(KeyEvent.VK_TAB); rb.keyRelease(KeyEvent.VK_TAB); */ // composeTextOnElement(); clickOnLink("linkText", "Attach Resource File"); Thread.sleep(5000); List<WebElement> el = driver().findElements(By.xpath(lstResources)); String before_plus = "//*[@id='resources-modal']/div/div[1]/div[2]/div/div[2]/div[3]/div["; String after_plus = "]/div/div[1]/a"; String before_check = "//*[@id='resources-modal']/div/div[1]/div[2]/div/div[2]/div[3]/div["; String after_check = "]/div/div[2]/div/div/div[2]/input"; String before_res = "//*[@id='resources-modal']/div/div[1]/div[2]/div/div[2]/div[3]/div["; String after_res = "]/div/div[1]"; for(int i=1;i<=el.size();i++){ WebElement res = driver().findElement(By.xpath(before_res+i+after_res)); if(res.getText().trim().contains(resName)){ waitOnElement("xpath",before_plus+i+after_plus); driver().findElement(By.xpath(before_plus+i+after_plus)).click(); Thread.sleep(3000); waitOnElement("xpath",before_check+i+after_check); clickOnElement("xpath",before_check+i+after_check); Thread.sleep(3000); clickOnElement("xpath",btnAttachAsset); break; } } Thread.sleep(5000); waitOnElement("xpath",lstAsset); List<WebElement> res = driver().findElements(By.xpath(lstAsset)); String before = "//*[@id='new_pyr_crm_message']/div[@class='attachment']["; String after = "]/div[1]"; for(int i=1;i<=res.size();i++){ WebElement assetType = driver().findElement(By.xpath(before+i+after)); if(assetType.getText().trim().contains(resAsset)){ isAssetAttached = true; Thread.sleep(3000); clickOnLink("linkText","Send"); Thread.sleep(5000); break; } } return isAssetAttached; } public void validateAppointment() throws Exception{ logInfo("inside validateAppointment() method."); System.out.println("inside validateAppointment() method"); waitOnElement("xpath",lnkCreateEvent); implicityWaits(5); clickOnElement("xpath",lnkCreateEvent); Thread.sleep(5000); waitOnElement("cssSelector",inputAppointmentName); inputTextClear("cssSelector", inputAppointmentName); clickOnLink("linkText", "More Options"); confirmationMessage("Please enter a title for your event."); } public void addBusinessContactsWithoutAddress(String fName, String lName, String email) throws Exception{ logInfo("inside addBusinessContactsWithoutAddress() method. "); System.out.println("inside addBusinessContactsWithoutAddress() method. "); go2ContactsPage(); waitOnElement("linkText","Add A Contact"); clickOnLink("linkText", "Add A Contact"); Thread.sleep(5000); waitOnElement("cssSelector",inputContactFirstName); inputText("cssSelector",inputContactFirstName,fName); // contactFirstName_text inputText("cssSelector",inputContactLastName,lName); // contactLastName_text inputText("cssSelector",inputContactEmail,email); inputText("cssSelector",inputContactPhone,contactPhone_text); WebElement element = driver().findElement(By.cssSelector(drpdnContactPhoneType)); Select select = new Select(element); List<WebElement> allItems =select.getOptions(); int size = allItems.size(); select.selectByIndex(size-1); logInfo("Entered all the fields in Business -> AddContact page."); clickOnButton("cssSelector",btnUpdateContact); Thread.sleep(5000); } public boolean validateContact() throws Exception{ logInfo("inside validateContact() method."); System.out.println("inside validateContact() method."); boolean isValidated = false; implicityWaits(3); waitOnElement("linkText","Edit"); clickOnElement("linkText", "Edit"); waitOnElement("cssSelector","#pyr_crm_contact_first_name"); inputTextClear("cssSelector","#pyr_crm_contact_first_name"); clickOnButton("cssSelector",btnUpdateContact); //validation msg should display here, bug has been logged for this. return isValidated; } public boolean validateCheckbox4Contact() throws Exception{ logInfo("inside validateCheckbox4Contact() method."); System.out.println("inside validateCheckbox4Contact() method."); boolean isValidated = false; String contactsPanel = "//*[@id='all-contacts-list']/div[1]/form"; waitOnElement("xpath",contactsPanel); WebElement econtactsPanel = driver().findElement(By.xpath(contactsPanel)); String expVal = contactFirstName_text + " " + contactLastName_text; List<WebElement> verifyContactsList = econtactsPanel.findElements(By.cssSelector(".contact-list-item")); // .media boolean isContactFound = false; int count= verifyContactsList.size(); System.out.println("contacts list count =" +count); String before_name = "//*[@id='all-contacts-list']/div[1]/form/div["; String after_name = "]/div[@class='media-body']/div/div[2]/h4/div/a/span[2]"; String before_check = "//*[@id='all-contacts-list']/div[1]/form/div["; String after_check = "]/div[@class='media-left']/input"; for(int i=1;i<=count;i++){ WebElement e = driver().findElement(By.xpath(before_name+i+after_name)); String name = e.getText().trim(); if(name.equalsIgnoreCase(expVal)){ isContactFound = true; logInfo(name + " business contact match found."); WebElement cb = driver().findElement(By.xpath(before_check+i+after_check)); cb.click(); System.out.println(name + " selected business contact"); break; } } clickOnElement("xpath","//*[@id='contacts-bulk-action-dropdown']/button"); clickOnElement("xpath", "//*[@id='group']"); waitOnElement("xpath","//*[@id='add_to_group']"); clickOnElement("xpath","//*[@id='add_to_group']"); confirmationMessage("Please select at least one group."); for(int i=1;i<=count;i++){ WebElement e = driver().findElement(By.xpath(before_name+i+after_name)); String name = e.getText().trim(); if(name.equalsIgnoreCase(expVal)){ isContactFound = true; logInfo(name + " business contact match found."); WebElement cb = driver().findElement(By.xpath(before_check+i+after_check)); if(cb.isSelected()){ isValidated = true; break; } } } return isValidated; } public void sendecard2Contacts() throws Exception{ logInfo("inside sendecard2Contacts() method."); System.out.println("inside sendecard2Contacts() method."); go2ContactsPage(); selectContactsCategoryList("Recent Contacts"); selectBusinessContact(contactFirstName_text,contactLastName_text); selectContactAction("Send Ecard"); } public void selectContactAction(String actionName) throws Exception { logInfo("inside selectContactAction() method"); boolean islinkAvailable = false; waitOnElement("xpath","//div[@id='contact-actions']"); WebElement actions = driver().findElement(By.xpath("//div[@id='contact-actions']")); List<WebElement> allActions = actions.findElements(By.xpath("//div[starts-with(@class,'contact-action')]")); int linksSize = allActions.size(); System.out.println("Total Actions = " +linksSize); String beforePath = "//*[@id='contact-actions']/div["; String afterPath = "]/a/span[2]"; for(int i=1;i<=linksSize; i++){ WebElement x = driver().findElement(org.openqa.selenium.By.xpath(beforePath+i+afterPath)); waitOnElement("xpath",beforePath+i+afterPath); scrollDown("xpath",beforePath+i+afterPath); String title = x.getText().trim(); System.out.println("title is " +title); if(title.equalsIgnoreCase(actionName)){ islinkAvailable= true; logInfo(actionName+ " action found in contact details list"); x.click(); Thread.sleep(5000); break; } }if (islinkAvailable==false){ logInfo(actionName+ "action not found in contact details list"); Assert.assertTrue(islinkAvailable,actionName + " is not found in contact details list"); } } public void selectAddContacts2Group(String groupName) throws Exception { logInfo("inside selectAddContacts2Group() method"); boolean isGroupFound2Add = false; waitOnElement("xpath","//div[@class='categories_list']/form[@id='addtoGroup']/table[@id='listContactGroups']/tbody"); WebElement groupTbl = driver().findElement(By.xpath("//div[@class='categories_list']/form[@id='addtoGroup']/table[@id='listContactGroups']/tbody")); List allRows = groupTbl.findElements(By.tagName("tr")); String before_grpName = "//div[@class='categories_list']/form[@id='addtoGroup']/table[@id='listContactGroups']/tbody/tr["; String after_grpName = "]/td[1]"; String before_inputSelectGroup = "//div[@class='categories_list']/form[@id='addtoGroup']/table[@id='listContactGroups']/tbody/tr["; String after_inputSelectGroup = "]/td[3]/input"; if(allRows.size()>0) { for(int i=1;i<=allRows.size();i++) { WebElement grpName = driver().findElement(By.xpath(before_grpName+i+after_grpName)); String actGroup = grpName.getText().trim(); if(actGroup.equalsIgnoreCase(groupName)) { WebElement input = driver().findElement(By.xpath(before_inputSelectGroup+i+after_inputSelectGroup)); input.click(); Thread.sleep(2000); clickOnElement("xpath","//input[@id='add_to_group']"); Thread.sleep(5000); logInfo(groupName + " found to add to contact."); isGroupFound2Add = true; break; } } } if(isGroupFound2Add==false) { logInfo(groupName + " not found to add to contact."); Assert.assertTrue(isGroupFound2Add, groupName + " not found to add to contact."); } } /*public void selectContactAction(String actionName) throws Exception { logInfo("inside selectContactAction() method"); boolean islinkAvailable = false; List<WebElement> links = driver().findElements(By.xpath("//*[@id='contact-actions']/div")); int linksSize = links.size(); System.out.println(linksSize); String beforePath = "//*[@id='contact-actions']/div["; String afterPath = "]/a/span[2]"; for(int i=1;i<=linksSize; i++){ WebElement x = driver().findElement(org.openqa.selenium.By.xpath(beforePath+i+afterPath)); waitOnElement("xpath",beforePath+i+afterPath); scrollDown("xpath",beforePath+i+afterPath); String title = x.getText().trim(); System.out.println("title is " +title); if(title.equalsIgnoreCase(actionName)){ islinkAvailable= true; logInfo(actionName+ " action found in contact details list"); x.click(); Thread.sleep(4000); break; } }if (islinkAvailable==false){ logInfo(actionName+ "action not found in contact details list"); Assert.assertTrue(islinkAvailable,actionName + " is not found in contact details list"); } }*/ public void go2UnassignedContactsPage() throws Exception{ logInfo("inside go2UnassignedContactsPage() method. "); driver().navigate().to(appUrl + "crm/v2/contacts/all"); clickOnLink("partialLinkText","Unassigned ("); } /* Avon Specific Methods */ //Ganga public void filterSearch(String searchText) throws Exception{ logInfo("inside filterSearch() method"); go2ContactsPage(); String expResult = "No Contacts Found"; clickOnLink("linkText","Filters"); inputTextClear("cssSelector", contFName); inputText("cssSelector",contFName,searchText); clickOnButton("cssSelector", advSerch); WebElement searResult2 = driver().findElement(By.cssSelector("form#contacts_selected > div.alert.alert-danger")); // searchReslt Assert.assertEquals(searResult2.getText(), expResult); } /*public void searchAndSelectContact(String fName, String lName) throws Exception { logInfo("inside searchAndSelectContact() method. "); System.out.println("inside searchContact() method. "); String expVal = fName + " " + lName; waitOnElement("cssSelector",inputContactSearch); inputText("cssSelector",inputContactSearch, expVal); String contactsPanel = "//*[@id='all-contacts-list']/div[1]/form"; WebElement econtactsPanel = driver().findElement(By.xpath(contactsPanel)); Thread.sleep(4000); WebElement link = driver().findElement(By.xpath(joyceAssocClk)); // waitOnElement("xPath", joyceAssocClk); link.click(); System.out.println(link.getText() + " selected business contact"); boolean isContactFound = false; List<WebElement> verifyContactsList = econtactsPanel.findElements(By.cssSelector(".contact-list-item")); int count= verifyContactsList.size(); System.out.println("contacts list count =" +count); String before_name = "//*[@id='all-contacts-list']/div[1]/form/div["; String after_name = "]/div[@class='media-body']/div/div[2]/h4/div/a/span[2]"; String before_link = "//*[@id='all-contacts-list']/div[1]/form/div["; String after_link = "]/div[@class='media-body']/div/div[2]/h4/div/a"; for(int i=2;i<=count;i++){ WebElement e = driver().findElement(By.xpath(before_name+i+after_name)); String name = e.getText().trim(); // System.out.println("Act Contact = " +name); // System.out.println("Exp Contact = " +expVal); if(name.equalsIgnoreCase(expVal)){ isContactFound = true; logInfo(name + " business contact match found."); WebElement link = driver().findElement(By.xpath(before_link+i+after_link)); link.click(); System.out.println(name + " selected business contact"); break; } } */ public String getAccountStatus() throws Exception { waitOnElement("cssSelector", ac); WebElement accst = driver().findElement(By.cssSelector(ac)); String acn = accst.getText(); return acn; } public String getContactTitle() throws Exception { waitOnElement("cssSelector", avtitle); WebElement acctit = driver().findElement(By.cssSelector(avtitle)); String actit = acctit.getText(); return actit; } public String getPcLevel() throws Exception { waitOnElement("cssSelector", avtitle); WebElement pclvl = driver().findElement(By.cssSelector(pclevel)); String pclevel = pclvl.getText(); return pclevel; } public String getRepID() throws Exception { waitOnElement("cssSelector", repid); WebElement repi = driver().findElement(By.cssSelector(repid)); String repd = repi.getText(); return repd; } public String getLOA() throws Exception { waitOnElement("cssSelector", loa); WebElement lo = driver().findElement(By.cssSelector(loa)); String looa = lo.getText(); return looa; } public String getLanguage() throws Exception { waitOnElement("cssSelector", lang); WebElement lan = driver().findElement(By.cssSelector(lang)); String language = lan.getText(); return language; } public String getRpsCode() throws Exception { waitOnElement("cssSelector", rps); WebElement rpsc = driver().findElement(By.cssSelector(rps)); String rpscode = rpsc.getText(); return rpscode; } public String filterActive() throws Exception{ logInfo("inside filterActive() method "); String expVal = fName + " " + lName; go2ContactsPage(); clickOnLink("linkText","Filters"); waitOnElement("cssSelector", filterBtn); selectFromDropdown("id",accntStatusDropdown,"byVisibleText","Active"); clickOnButton("cssSelector", filterBtn); String contactsPanel = "//*[@id='all-contacts-list']/div[1]/form"; WebElement econtactsPanel = driver().findElement(By.xpath(contactsPanel)); Thread.sleep(4000); WebElement link = driver().findElement(By.xpath(joyceAssocClk)); // waitOnElement("xPath", joyceAssocClk); link.click(); String expecteduser = link.getText().trim(); System.out.println(expecteduser + " selected business contact"); return expecteduser; } //This testcase is to do a filter search with valid data and verifying the results public void filtersSearchAndValidatingData() throws Exception { logInfo("inside getCotnactInfo() method "); String contactdata = filterActive(); String expectedAccntsts = getAccountStatus(); String expectedPCLevel = getPcLevel(); System.out.println(expectedPCLevel); String expectedTitle = getContactTitle(); System.out.println(expectedTitle); String expectedRepID = getRepID(); System.out.println(expectedRepID); String expectedLOA = getLOA(); System.out.println(expectedLOA); String expectedLanguage = getLanguage(); System.out.println(expectedLanguage); String expectedRPS = getRpsCode(); System.out.println(expectedRPS); clickOnLink("linkText","Filters"); waitOnElement("id", accntStatusDropdown); selectFromDropdown("id",accntStatusDropdown,"byVisibleText",expectedAccntsts); inputTextClear("id", representativeId); inputText("id", representativeId, expectedRepID); selectFromDropdown("id",titleRank,"byVisibleText",expectedTitle); selectFromDropdown("id",rankPClevel,"byVisibleText",expectedPCLevel); selectFromDropdown("id",languageDrpdn,"byVisibleText",expectedLanguage); clickOnButton("cssSelector", filterBtn); confirmationMessage("1 results found."); String contactsPanel = "//*[@id='all-contacts-list']/div[1]/form"; WebElement econtactsPanel = driver().findElement(By.xpath(contactsPanel)); Thread.sleep(4000); WebElement link = driver().findElement(By.xpath(joyceAssocClk)); // waitOnElement("xPath", joyceAssocClk); String expectedText = link.getText(); System.out.println(expectedText + "is the expected contact"); Assert.assertEquals(contactdata, expectedText); } /* public boolean verifyBusinessContact(String uName) throws Exception{ logInfo("inside verifyBusinessContact() method."); System.out.println("inside verifyBusinessContact() method."); go2ContactsPage(); selectContactsCategoryList("Recent Contacts"); String contactsPanel = prop.getLocatorForEnvironment(appUrl,"contactsPanel"); WebElement econtactsPanel = driver().findElement(By.xpath(contactsPanel)); waitOnElement("xpath",contactsPanel); String before_name = contactsPanel + "/div["; // "//*[@id='list-results']/div[3]/div/form/div["; // "//*[@id='all-contacts-list']/div[1]/form/div["; // String after_name = "]/div[@class='media-body']/div/div[2]/h4/div/a/span[2]"; String expVal = fName + " " + lName; List<WebElement> verifyContactsList = econtactsPanel.findElements(By.cssSelector(".contact-list-item.media")); boolean isContactFound = false; int count= verifyContactsList.size(); System.out.println("Total Business Contacts =" +count); logInfo("Total Business Contacts =" +count); for(int i=1;i<=count;i++){ WebElement e = driver().findElement(By.xpath(before_name+i+after_name)); String actText = e.getText().trim(); System.out.println("actText =" +actText); if(actText.equalsIgnoreCase(expVal)){ isContactFound = true; logInfo(expVal + " business contact match found."); break; } } return isContactFound; } */ /* public void sendecard2Contacts(String fName, String lName) throws Exception{ logInfo("inside sendecard2Contacts() method."); System.out.println("inside sendecard2Contacts() method."); go2ContactsPage(); selectContactsCategoryList("Recent Contacts"); selectBusinessContact(contactFirstName_text,contactLastName_text); waitOnElement("xpath",lnkSendEcard); clickOnElement("xpath",lnkSendEcard); } public void sendEcard() throws Exception{ logInfo("Inside sendEcard Method"); Thread.sleep(5000); String parentEcard = "Blank Letterhead"; String ecardtempName = "Embedded video"; em.selectcatNdEcard(parentEcard, ecardtempName); em.enterDetails(ecardCatSubText); waitOnElement("cssSelector", ecardMailSendBtn); clickOnButton("cssSelector", ecardMailSendBtn); confirmationMessage("Message sent to: "+mailId); }*/ public void selectEcard(String ecardCategory, String ecardTemplate) throws Exception{ logInfo("inside selectEcard() method"); waitOnElement("xpath","//ul[@class='panel-nav categories']"); WebElement ecat = driver().findElement(By.xpath("//ul[@class='panel-nav categories']")); List allCategories = ecat.findElements(By.tagName("li")); String before_li = "//ul[@class='panel-nav categories']/li[@id="; String after_li = "]/a"; if(allCategories.size()>0){ for(int i=1;i<=allCategories.size();i++){ WebElement ecatName = driver().findElement(By.xpath(before_li+i+after_li)); String actCategoryName = ecatName.getText().trim(); if(actCategoryName.equalsIgnoreCase(ecardCategory)){ ecatName.click(); // select category waitOnElement("xpath","//*[@id='ecard_query']"); inputTextClear("xpath","//*[@id='ecard_query']"); inputText("xpath","//*[@id='ecard_query']",ecardTemplate); waitOnElement("xpath","//div[@class='ecard-templates-grid']"); WebElement templateGrid = driver().findElement(By.xpath("//div[@class='ecard-templates-grid']")); List allGridRows = templateGrid.findElements(By.className("row")); String before_tempRow = "//div[@class='ecard-templates-grid']/div["; String after_tempRow = "]/div[@class='col-md-12']"; if(allGridRows.size()>0){ for(int j=1;j<=allGridRows.size();j++){ WebElement tempRow = driver().findElement(By.xpath(before_tempRow+j+after_tempRow)); List allTemplates = tempRow.findElements(By.cssSelector(".col-md-2.col-sm-4.col-xs-6")); if(allTemplates.size()>0){ String before_template1 = "//div[@class='ecard-templates-grid']/div["; String before_template2 = "]/div[@class='col-md-12']/div["; String before_template3 = "]/div[1]/div[3]/div[1]"; for(int k=1;k<=allTemplates.size();k++){ waitOnElement("xpath",before_template1+j+before_template2+k+before_template3); WebElement etempName = driver().findElement(By.xpath(before_template1+j+before_template2+k+before_template3)); String actualTemplate = etempName.getText().trim(); if(actualTemplate.equalsIgnoreCase(ecardTemplate)){ logInfo(ecardTemplate + " template match found"); etempName.click(); // click on Next button waitOnElement("cssSelector","form.simple_form.edit_pyr_crm_ecard > div.text-right > input.btn.btn-primary"); inputText("xpath","//*[@id='pyr_crm_ecard_subject']",ecardTemplate + " ecard template"); clickOnElement("cssSelector","form.simple_form.edit_pyr_crm_ecard > div.text-right > input.btn.btn-primary"); // click on Send Ecard button waitOnElement("cssSelector","div.text-right > button.btn.btn-primary.pull-right"); clickOnElement("linkText","Add Manually"); waitOnElement("xpath","//*[@id='ecard_manual_contacts_container']/div[@class='control-group']/div[2]/div[1]/input"); inputText("xpath","//*[@id='ecard_manual_contacts_container']/div[@class='control-group']/div[2]/div[1]/input",recipientsGmail_text); clickOnElement("xpath","//*[@id='ecard_manual_contacts']/div/div[1]/div[2]/div[4]/div/button"); clickOnElement("cssSelector","div.text-right > button.btn.btn-primary.pull-right"); break; } } } } } break; } } } } public void verifyStaticGroupsIsPresent(String groupName) throws Exception{ logInfo("Inside verifyStaticGroupsArePresent method()"); waitOnElement("xpath","//*[@id='list-results']"); WebElement grpPanel = driver().findElement(By.xpath("//*[@id='list-results']")); List allGrps = grpPanel.findElements(By.cssSelector(".list-result")); String before_grpName = "//*[@id='list-results']/div["; String after_grpName = "]/a"; boolean isGroupPresent = false; if(allGrps.size() >0){ for(int i=1;i<=allGrps.size();i++){ WebElement eGrpName = driver().findElement(By.xpath(before_grpName+i+after_grpName)); String actGrpName = eGrpName.getText().trim(); if(actGrpName.contains(groupName.trim())){ //equalsIgnoreCase System.out.println(actGrpName + " is present"); isGroupPresent = true; break; } } } if(isGroupPresent==false){ logInfo(isGroupPresent + " group is not present"); Assert.assertTrue(isGroupPresent, " group is not present"); } } // Method for Avon Coach User public void loginAsUserFromContactPanel(String fName, String lName) throws Exception{ logInfo("Inside loginAsUserFromContactPanel method()"); String contactsPanel = "//*[@id='all-contacts-list']/div[1]/form"; waitOnElement("xpath",contactsPanel); WebElement econtactsPanel = driver().findElement(By.xpath(contactsPanel)); String expVal = fName + " " + lName; List<WebElement> verifyContactsList = econtactsPanel.findElements(By.cssSelector(".contact-list-item")); // .media boolean isContactFound = false; int count= verifyContactsList.size(); System.out.println("contacts list count =" +count); /* String before_name = "//*[@id='all-contacts-list']/div[1]/form/div["; String after_name = "]/div[2]/div/div[2]/h4/a/span[2]";*/ String before_name = "//*[@id='all-contacts-list']/div[1]/form/div["; String after_name = "]/div[@class='media-body']/div/div[2]/h4/div/a/span[2]"; String before_link = "//*[@id='all-contacts-list']/div[1]/form/div["; String after_link = "]/div[@class='media-body']/div/div[2]/h4/div/a"; // "]/div[2]/div/div[2]/h4/a"; String before_loginAsUserlink = "//*[@id='all-contacts-list']/div[1]/form/div["; String after_loginAsUserlink = "]/div[@class='media-body']/div/div[2]/h4/a"; for(int i=1;i<=count;i++){ WebElement e = driver().findElement(By.xpath(before_name+i+after_name)); String name = e.getText().trim(); // System.out.println("Act Contact = " +name); // System.out.println("Exp Contact = " +expVal); if(name.equalsIgnoreCase(expVal)){ isContactFound = true; logInfo(name + " business contact match found."); WebElement link = driver().findElement(By.xpath(before_loginAsUserlink+i+after_loginAsUserlink)); link.click(); System.out.println(name + " selected business contact"); break; } } } public void verifyUserLoginMessage() throws Exception{ logInfo("Inside verifyLoginMessage method()"); waitOnElement("xpath","//*[@id='page']/div[1]"); String coachUserName = prop.getLocatorForEnvironment(appUrl,"coachFirstName_text") + " " + prop.getLocatorForEnvironment(appUrl,"coachLastName_text"); String expLoginMsg = "You are logged in as " + coachUserName + ". Click here to go back to your account."; WebElement eMsg = driver().findElement(By.xpath("//*[@id='page']/div[1]")); String actLoginMsg = eMsg.getText().trim(); System.out.println("actLoginMsg = " +actLoginMsg); System.out.println("expLoginMsg = " +expLoginMsg); Assert.assertEquals(actLoginMsg, expLoginMsg); } public void editBusinessContact() throws Exception { logInfo("Inside editBusinessContact method()"); clickOnElement("xpath","//*[@id='contact-summary']/div[1]/a[1]"); Thread.sleep(5000); clickOnElement("xpath", "//form[@class='simple_form view-container']/div[@class='form-group'][1]/div/p/a/span/i"); inputText("xpath","//form[@class='simple_form view-container']/div[@class='form-group'][1]/div/p/div[1]/div/div/div/input", prop.getLocatorForEnvironment(appUrl,"selfmailId1")); clickOnElement("xpath","//form[@class='simple_form view-container']/div[@class='form-group'][1]/div/p/div[1]/div/div/div/span[1]"); scrollDown("xpath","//input[@value='Update Contact']"); clickOnButton("xpath","//input[@value='Update Contact']"); Thread.sleep(6000); } }
true
a0044930018b4153dc29e7f77ad41cd39690fe69
Java
WBB1997/BookSystem
/src/model/Book_Subscribe.java
UTF-8
1,054
2.53125
3
[]
no_license
package model; public class Book_Subscribe { private Book book; private Reader reader; private String time; private String status; public Book getBook() { return book; } public void setBook(Book book) { this.book = book; } public Reader getReader() { return reader; } public void setReader(Reader reader) { this.reader = reader; } public String getTime() { return time; } public void setTime(String time) { this.time = time; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } @Override public String toString() { return "{" + "\"No\":\"" + reader.getNo() + '\"' + ", \"Name\":\"" + book.getName() + '\"' + ", \"ISBN\":\"" + book.getISBN() + '\"' + ", \"Time\":\"" + time + '\"' + ", \"Status\":\"" + status + '\"' + '}'; } }
true
abe1edfaa028578f55bbc5bec28235ba04a3d155
Java
nesserine0/Spring-15
/src/main/java/Class/Sphere.java
UTF-8
1,094
3.71875
4
[]
no_license
package Class; public class Sphere extends Cercle{ /** * Constructeur de la classe Sphere pour initialise un object Sphere * @param nom du Sphere : string * @param origine le point : Point * @param diametre : double */ public Sphere(String nom, Point origine, double diametre) { super(nom, origine, diametre); } /** * la superficie d'un Sphere */ @Override public double superficie() { return Math.pow(this.getDiametre(),2)*Math.PI*4; } //le mot final interdit la redifinition de la methode volume /** * une methode permetre de calculer le volume du Sphere , cette methode est finale : ne peut pas etre redifinie par les classes filles * @return double : volume de Sphere */ public final double Volume( ) { return Math.pow(this.getDiametre(),3)*Math.PI*4/3; } /** * Affichage des information du Shpere sous forme d'une chaine de caractere */ @Override public String toString() { //"]$ => replace last occ only return super.toString().replace("Cercle","Sphere").replaceAll("]$"," ,")+" Volume = "+this.Volume()+"]"; } }
true
99165b0f964b23a246f773f44e79b874c3e0bc7e
Java
DeepBlueRobotics/RobotCode2015
/SlideWinder/src/org/usfirst/frc100/SlideWinder/commands/AutoFollowLine.java
UTF-8
1,418
2.9375
3
[]
no_license
package org.usfirst.frc100.SlideWinder.commands; import org.usfirst.frc100.SlideWinder.SlideWinder; import edu.wpi.first.wpilibj.command.Command; /** * Uses line readers to follow the line autonomously. */ public class AutoFollowLine extends Command { private final double distance; /** * @param distance - The distance to travel in inches */ public AutoFollowLine(double distance) { this.distance = distance; requires(SlideWinder.drivetrain); } // Called just before this Command runs the first time protected void initialize() { SlideWinder.drivetrain.setDistanceTarget(distance); SlideWinder.drivetrain.setAngleTarget(0); } // Called repeatedly when this Command is scheduled to run protected void execute() { SlideWinder.drivetrain.drive(SlideWinder.drivetrain.updateDistance(), SlideWinder.drivetrain.followLine(), SlideWinder.drivetrain.updateAngle()); } // Make this return true when this Command no longer needs to run execute() protected boolean isFinished() { return SlideWinder.drivetrain.reachedDistance(); } // Called once after isFinished returns true protected void end() { SlideWinder.drivetrain.drive(0, 0, 0); } // Called when another command which requires one or more of the same // subsystems is scheduled to run protected void interrupted() { end(); } }
true
e99ebb0816729344099c685bbf7cd11a7a32d3ec
Java
whdals7337/coding-test-study
/src/sort/InjectionSort.java
UTF-8
733
3.90625
4
[]
no_license
package sort; public class InjectionSort { public static void main(String[] args) { // 배열 int[] arr = {5, 4, 3, 2, 1, 6, 7, 8, 9, 0}; int len = arr.length; for(int i = 1; i < len; i++){ for(int j = i; j > 0; j--){ // 왼쪽으로 이동하면서 값이 이전 값보다 작으면 서로 변경 if(arr[j] < arr[j-1]){ int temp = arr[j]; arr[j] = arr[j-1]; arr[j-1] = temp; } else { break; } } } //배열 출력 for (int i = 0; i <len; i++){ System.out.print(arr[i]+" "); } } }
true
be915f6f8e49aa432c10a839b3dfdc97fd3e6b71
Java
vladosby/Hibernate
/src/main/java/com/borisov/spring/components/framework/TransactionBPP.java
UTF-8
2,064
2.546875
3
[]
no_license
package com.borisov.spring.components.framework; import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.BeanPostProcessor; import org.springframework.stereotype.Component; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.HashMap; /** * Created by vladosby on 04.10.2015. */ @Component public class TransactionBPP implements BeanPostProcessor { private HashMap<String, Class> mapBeans = new HashMap<>(); @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { Class<?> clazz = bean.getClass(); Method[] methods = clazz.getMethods(); for (Method method : methods) { if (method.isAnnotationPresent(Transaction.class)) { mapBeans.put(beanName, clazz); } } return bean; } @Override public Object postProcessAfterInitialization(final Object bean, String beanName) throws BeansException { final Class clazz = mapBeans.get(beanName); if(clazz != null){ Object proxy = Proxy.newProxyInstance(clazz.getClassLoader(), clazz.getInterfaces(), new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Method originalMethod = clazz.getMethod(method.getName(), method.getParameterTypes()); if (originalMethod.isAnnotationPresent(Transaction.class)) { System.out.println("start transaction"); Object returnValue = method.invoke(bean, args); System.out.println("finish transaction"); return returnValue; } else { return method.invoke(bean, args); } } }); return proxy; } else { return bean; } } }
true
a9cb40bc4adf53b346ef6c43f3cb6bf6972f99be
Java
daniimara/app-spring-ciet
/src/test/java/br/com/treinamento/SerieTest.java
UTF-8
7,695
2.03125
2
[]
no_license
package br.com.treinamento; import static org.junit.Assert.*; import java.security.NoSuchAlgorithmException; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.fasterxml.jackson.core.Version; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.module.SimpleModule; import com.google.gson.Gson; import br.com.treinamento.config.TestConfig; import br.com.treinamento.dojo.model.CollectionURI; import br.com.treinamento.dojo.model.CollectionURIDeserializer; import br.com.treinamento.dojo.model.Serie; import br.com.treinamento.dojo.model.Result; import br.com.treinamento.dojo.model.Character; import br.com.treinamento.dojo.model.Comic; import br.com.treinamento.dojo.model.Creator; import br.com.treinamento.dojo.model.Story; import br.com.treinamento.dojo.model.URLFactory; import br.com.treinamento.dojo.parameter.SeriesParameters; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(TestConfig.class) public class SerieTest { private URLFactory urlFactory; private String publicKey = "4f8c462b9fdb1e043d0d907ce4164374"; private String privateKey = "52c4cd408bb0c1d27e4e98b741853f30f29d9115"; private WebTarget webTarget; private Client client; private ObjectMapper objectMapper; @Before public void setUp() throws NoSuchAlgorithmException { client = ClientBuilder.newClient(); urlFactory = new URLFactory(privateKey, publicKey); objectMapper = new ObjectMapper(); SimpleModule module = new SimpleModule("CollectionURIDeserializerModule", new Version(1, 0, 0, null, null, null)); module.addDeserializer(CollectionURI.class, new CollectionURIDeserializer()); objectMapper.registerModule(module); } @Test public void testGetSeriesApp() throws Exception { /*webTarget = client.target("http://localhost:8080/app-spring-ciet").path("v1").path("serie"); Response response = webTarget .request() .accept(MediaType.APPLICATION_JSON) .get(); String json = response.readEntity(String.class); //System.out.println("json\n" + json + "\n"); Gson gson = new Gson(); //ResponseProtocol resposta = gson.fromJson(json, ResponseProtocol.class); //Serie resposta = gson.fromJson(json, Serie.class); //System.out.println("resposta\n" + resposta.getTitle() + "\n"); Serie[] series = gson.fromJson(json, Serie[].class); //System.out.println("series\n" + series[1].getTitle() + "\n"); assertTrue(series.length > 0);*/ assertTrue(1 > 0); } @Test public void testGetSeries() throws Exception { webTarget = client.target(urlFactory.getSeriesURL()); Response response = webTarget .request() .accept(MediaType.APPLICATION_JSON) .get(); String json = response.readEntity(String.class); //System.out.println("json\n" + json + "\n"); Gson gson = new Gson(); Result<Serie> resposta = gson.fromJson(json, Result.class); //System.out.println("resposta\n" + resposta.toString() + "\n"); assertTrue(resposta.getData().getResults().size() > 0); } @Test public void testGetSeriesBySeriesId() throws Exception { webTarget = client.target(urlFactory.getSeriesURL(Constants.ID_SERIE)); Response response = webTarget .request() .accept(MediaType.APPLICATION_JSON) .get(); String json = response.readEntity(String.class); Gson gson = new Gson(); Result<Serie> resposta = gson.fromJson(json, Result.class); JavaType javaType = objectMapper.getTypeFactory().constructParametricType(Result.class, Serie.class); Result<Serie> mappedResult = objectMapper.readValue(json, javaType); Serie series = mappedResult.getData().getResults().get(0); assertTrue(resposta.getData().getResults().size() != 0); assertNotNull(series); assertNotNull(series.getTitle()); assertEquals(series.getTitle(), "4 (2004 - 2006)"); } @Test public void testGetSeriesCharacters() throws Exception { SeriesParameters seriesParameters = new SeriesParameters(Constants.ID_SERIE); webTarget = client.target(urlFactory.getSeriesCharactersURL(seriesParameters)); Response response = webTarget .request() .accept(MediaType.APPLICATION_JSON) .get(); String json = response.readEntity(String.class); Gson gson = new Gson(); Result<Serie> resposta = gson.fromJson(json, Result.class); JavaType javaType = objectMapper.getTypeFactory().constructParametricType(Result.class, Character.class); Result<Character> mappedResult = objectMapper.readValue(json, javaType); Character character = mappedResult.getData().getResults().get(0); assertTrue(resposta.getData().getResults().size() > 0); assertEquals(character.getName(), "Doctor Doom"); } @Test public void testGetSeriesComics() throws Exception { SeriesParameters seriesParameters = new SeriesParameters(Constants.ID_SERIE); webTarget = client.target(urlFactory.getSeriesComicsURL(seriesParameters)); Response response = webTarget .request() .accept(MediaType.APPLICATION_JSON) .get(); String json = response.readEntity(String.class); Gson gson = new Gson(); Result<Serie> resposta = gson.fromJson(json, Result.class); JavaType javaType = objectMapper.getTypeFactory().constructParametricType(Result.class, Comic.class); Result<Comic> mappedResult = objectMapper.readValue(json, javaType); Comic Comic = mappedResult.getData().getResults().get(0); assertTrue(resposta.getData().getResults().size() > 0); assertEquals(Comic.getTitle(), "4 (2004) #30"); } @Test public void testGetSeriesCreators() throws Exception { SeriesParameters seriesParameters = new SeriesParameters(Constants.ID_SERIE); webTarget = client.target(urlFactory.getSeriesCreatorsURL(seriesParameters)); Response response = webTarget .request() .accept(MediaType.APPLICATION_JSON) .get(); String json = response.readEntity(String.class); Gson gson = new Gson(); Result<Serie> resposta = gson.fromJson(json, Result.class); JavaType javaType = objectMapper.getTypeFactory().constructParametricType(Result.class, Creator.class); Result<Creator> mappedResult = objectMapper.readValue(json, javaType); Creator creator = mappedResult.getData().getResults().get(0); assertTrue(resposta.getData().getResults().size() > 0); assertEquals(creator.getFirstName(), "Roberto"); } @Test public void testGetSeriesStories() throws Exception { SeriesParameters seriesParameters = new SeriesParameters(Constants.ID_SERIE); webTarget = client.target(urlFactory.getSeriesStoriesURL(seriesParameters)); Response response = webTarget .request() .accept(MediaType.APPLICATION_JSON) .get(); String json = response.readEntity(String.class); Gson gson = new Gson(); Result<Serie> resposta = gson.fromJson(json, Result.class); JavaType javaType = objectMapper.getTypeFactory().constructParametricType(Result.class, Story.class); Result<Story> mappedResult = objectMapper.readValue(json, javaType); Story story = mappedResult.getData().getResults().get(0); assertTrue(resposta.getData().getResults().size() > 0); assertEquals(story.getTitle(), "3 of 3"); } }
true
8cf643d79734feb66dae361554bfc9ce004b8a49
Java
EverCedillo/moh-back
/src/main/java/mx/ohanahome/app/backend/entity/user/UserRole.java
UTF-8
2,551
2
2
[]
no_license
package mx.ohanahome.app.backend.entity.user; import com.google.appengine.repackaged.org.codehaus.jackson.annotate.JsonIgnore; import java.util.Date; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; /** * Created by brenda on 4/3/16. */ @NamedQueries( {@NamedQuery(name = "UserRole.getURByUserAndHome",query = "select ur from UserRole ur where ur.user.id_user = :user and ur.home.id_home = :home")} ) @Table(name = "TOH_USER_ROLE") @Entity public class UserRole { @GeneratedValue(generator = "increment") @Id private long id_user_role; @Temporal(TemporalType.TIMESTAMP) Date start_date; @Temporal(TemporalType.TIMESTAMP) Date modification_date; @Temporal(TemporalType.TIMESTAMP) Date end_date; @ManyToOne(cascade = CascadeType.PERSIST ) @JoinColumn(name = "id_role") private Role role; @ManyToOne(cascade = CascadeType.ALL) @JoinColumn(name = "id_user") private User user; @ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name = "id_home") private Home home; public Role getRole() { return role; } public void setRole(Role role) { this.role = role; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } @JsonIgnore public Home getHome() { return home; } public void setHome(Home home) { this.home = home; } public long getId_user_role() { return id_user_role; } public void setId_user_role(long id_user_role) { this.id_user_role = id_user_role; } public Date getStart_date() { return start_date; } public void setStart_date(Date start_date) { this.start_date = start_date; } public Date getEnd_date() { return end_date; } public void setEnd_date(Date end_date) { this.end_date = end_date; } public Date getModification_date() { return modification_date; } public void setModification_date(Date modification_date) { this.modification_date = modification_date; } public UserRole(){} }
true
9518f1296590447b5045a5a3137b2ec1b594be12
Java
bwolfee10/vending-machine
/java/src/main/java/com/techelevator/view/Beverages.java
UTF-8
365
2.453125
2
[]
no_license
package com.techelevator.view; import java.math.BigDecimal; public class Beverages extends Products{ private String message = "Glug Glug, Yum!"; @Override public String dispenseMsg(){ return this.message; } public Beverages(String slot, String name, BigDecimal price, String type) { super(slot, name, price, type); } }
true
fd96d05d99a2d49ccaac764f9b428097ca60b037
Java
maizhancheng/shop
/Taobao/app/src/main/java/com/mai/shop/taobao/pro/mine/view/MineFragment.java
UTF-8
740
1.945313
2
[]
no_license
package com.mai.shop.taobao.pro.mine.view; import android.view.View; import android.view.ViewGroup; import com.mai.shop.taobao.R; import com.mai.shop.taobao.pro.base.view.BaseFragment; import com.mai.shop.taobao.pro.base.view.navigation.impl.AppNavagion; /** * Created by admin on 2018/3/1. */ public class MineFragment extends BaseFragment{ @Override public int bindLayoutId() { return R.layout.fragment_mine; } @Override public void initContentView(View contentView) { AppNavagion.Builder builder = new AppNavagion.Builder(getActivity(), (ViewGroup) contentView); builder.setCenterImageRes(R.string.mine_tab) .setbackgroundColor(R.color.white).create().build(); } }
true
fa276065d8e0c1441db9a7f8cd45c7e329e1228a
Java
tuukkapa/Shakki-TIRALabra2015
/src/Chessboard/pieces/SuperPiece.java
UTF-8
9,510
3.40625
3
[]
no_license
/* * Copyright (C) 2015 * * Tuukka Paukkunen <tuukka.paukkunen@cs.helsinki.fi> */ package Chessboard.pieces; import Chessboard.Chessboard; import Chessboard.Move; import DataStructures.List; /** * This class is used to create protecting or attacking patterns from a chessboard * square. It is used at Evaluate-class to determine, whether own piece is protecting * player's another piece or whether enemy's piece is attacking player's piece. * * This should not be used in the game as an actual piece. * * @author Tuukka Paukkunen <tuukka.paukkunen@cs.helsinki.fi> */ public class SuperPiece extends Piece { public SuperPiece(boolean white, int position) { this.position = position; this.white = white; this.sign = white ? 'S' : 's'; this.hasMoved = false; } /** * Determines, if a piece positioned at superpiece's position is protected or attacked. * @param chessboard Chessboard-object, where the game is played. * @param own Boolean, whether the positions to be checked should be protecting or attacking. * @return boolean, true = protected/attacked, false otherwise. */ public boolean getProtectionStatus(Chessboard chessboard, boolean own) { boolean colour = own ? this.white : !this.white; boolean status = this.createStraightProtectingMoves(chessboard, colour); if (status) { return true; } status = this.createDiagonalProtectingMoves(chessboard, colour); if (status) { return true; } int row = position / 8; int col = position % 8; Pawn pawn = new Pawn(colour, 0); Knight knight = new Knight(colour, 0); // is pawn protecting or attacking int movement = white ? 1 : -1; if (row + movement >= 0 && row + movement < 8 && col - 1 >= 0 && this.endSquareContainsPiece(chessboard, pawn, (row + movement) * 8 + col - 1)) { return true; } if (row + movement >= 0 && row + movement < 8 && col + 1 < 8 && this.endSquareContainsPiece(chessboard, pawn, (row + movement) * 8 + col + 1)) { return true; } // is knight protecting or attacking if (row - 1 >= 0 && col - 2 >= 0 && this.endSquareContainsPiece(chessboard, knight, (row - 1) * 8 + (col - 2))) { return true; } if (row - 2 >= 0 && col - 1 >= 0 && this.endSquareContainsPiece(chessboard, knight, (row - 2) * 8 + (col - 1))) { return true; } if (row - 2 >= 0 && col + 1 < 8 && this.endSquareContainsPiece(chessboard, knight, (row - 2) * 8 + (col + 1))) { return true; } if (row - 1 >= 0 && col + 2 < 8 && this.endSquareContainsPiece(chessboard, knight, (row - 1) * 8 + (col + 2))) { return true; } if (row + 1 < 8 && col + 2 < 8 && this.endSquareContainsPiece(chessboard, knight, (row + 1) * 8 + (col + 2))) { return true; } if (row + 2 < 8 && col + 1 < 8 && this.endSquareContainsPiece(chessboard, knight, (row + 2) * 8 + (col + 1))) { return true; } if (row + 2 < 8 && col - 1 >= 0 && this.endSquareContainsPiece(chessboard, knight, (row + 2) * 8 + (col - 1))) { return true; } if (row + 1 < 8 && col - 2 >= 0 && this.endSquareContainsPiece(chessboard, knight, (row + 1) * 8 + (col - 2))) { return true; } return false; } /** * Determines, if a piece positioned at superpiece's position is protected or attacked * horizontally or vertically from the Piece-objects position (i.e. like Rook). * @param chessboard Chessboard-object, which pieces are to be moved. * @return boolean, true = protected/attacked, false otherwise. */ private boolean createStraightProtectingMoves(Chessboard chessboard, boolean colour) { int startRow = position / 8; int startCol = position % 8; boolean rightBlocked = false, downBlocked = false, leftBlocked = false, upBlocked = false; int maxMovement = Math.max(Math.max(startRow, startCol), Math.max(7-startRow, 7-startCol)); // check route for (int i = 1; i <= maxMovement; i++) { // check right if (!rightBlocked && startCol + i < 8) { int end = startRow * 8 + (startCol + i); Piece piece = chessboard.getSquareContents(end); if (chessboard.getSquareContents(end) == null) { // the route is clear, continue } else if ((piece instanceof Rook || piece instanceof Queen) && piece.amIWhite() == colour) { return true; } else { rightBlocked = true; } } // check down if (!downBlocked && startRow + i < 8) { int end = (startRow + i) * 8 + startCol; Piece piece = chessboard.getSquareContents(end); if (chessboard.getSquareContents(end) == null) { // the route is clear, continue } else if ((piece instanceof Rook || piece instanceof Queen) && piece.amIWhite() == colour) { return true; } else { downBlocked = true; } } // check left if (!leftBlocked && startCol - i >= 0) { int end = (startRow * 8) + startCol - i; Piece piece = chessboard.getSquareContents(end); if (chessboard.getSquareContents(end) == null) { // the route is clear, continue } else if ((piece instanceof Rook || piece instanceof Queen) && piece.amIWhite() == colour) { return true; } else { leftBlocked = true; } } // check up if (!upBlocked && startRow - i >= 0) { int end = (startRow - i) * 8 + startCol; Piece piece = chessboard.getSquareContents(end); if (chessboard.getSquareContents(end) == null) { // the route is clear, continue } else if ((piece instanceof Rook || piece instanceof Queen) && piece.amIWhite() == colour) { return true; } else { upBlocked = true; } } if (rightBlocked && downBlocked && leftBlocked && upBlocked) { break; } } return false; } /** * Determines, if a piece positioned at superpiece's position is protected or attacked * diagonally from the Piece-objects position (i.e. like Bishop). * @param chessboard Chessboard-object, which pieces are to be moved. * @return boolean, true = protected/attacked, false otherwise. */ private boolean createDiagonalProtectingMoves(Chessboard chessboard, boolean colour) { int row = position / 8; int col = position % 8; int maxMovement = 0; if (row < 4 && col < 4) { maxMovement = 7 - Math.max(row, col); } else if (row < 4 && col > 3) { maxMovement = Math.min(col, 7 - row); } else if (row > 3 && col < 4) { maxMovement = Math.min(row, 7 - col); } else { maxMovement = Math.min(row, col); } boolean neBlocked = false, seBlocked = false, swBlocked = false, nwBlocked = false; int nePosition, sePosition, swPosition, nwPosition; for (int i = 1; i <= maxMovement; i++) { // check north-east nePosition = (row - i) * 8 + col + i; sePosition = (row + i) * 8 + col + i; swPosition = (row + i) * 8 + col - i; nwPosition = (row - i) * 8 + col - i; if (!neBlocked && row - i >= 0 && col + i < 8) { Piece piece = chessboard.getSquareContents(nePosition); if (chessboard.getSquareContents(row-i, col+i) == null) { // the route is clear, continue } else if ((piece instanceof Bishop || piece instanceof Queen) && piece.amIWhite() == colour) { return true; } else { neBlocked = true; } } // check south-east if (!seBlocked && row + i < 8 && col + i < 8) { Piece piece = chessboard.getSquareContents(sePosition); if (chessboard.getSquareContents(row+i, col+i) == null) { // the route is clear, continue } else if ((piece instanceof Bishop || piece instanceof Queen) && piece.amIWhite() == colour) { return true; } else { seBlocked = true; } } // check south-west if (!swBlocked && row + i < 8 && col - i >= 0) { Piece piece = chessboard.getSquareContents(swPosition); if (chessboard.getSquareContents(row+i, col-i) == null) { // the route is clear, continue } else if ((piece instanceof Bishop || piece instanceof Queen) && piece.amIWhite() == colour) { return true; } else { swBlocked = true; } } // check nort-west if (!nwBlocked && row - i >= 0 && col - i >= 0) { Piece piece = chessboard.getSquareContents(nwPosition); if (chessboard.getSquareContents(row-i, col-i) == null) { // the route is clear, continue } else if ((piece instanceof Bishop || piece instanceof Queen) && piece.amIWhite() == colour) { return true; } else { nwBlocked = true; } } } return false; } /** * Returns true, if end square contains same kind of piece which is given as parameter. * @param chessboard Chessboard, where the game is played. * @param piece Piece-object to be compared with. * @param end Integer, chessboard square (0 = top left, 63 = bottom right). * @return Boolean, true if end square contains same kind of piece which is given as parameter. */ private boolean endSquareContainsPiece(Chessboard chessboard, Piece piece, int end) { if (!(0 <= end && end < 64)) { return false; } Piece endContents = chessboard.getSquareContents(end); if (endContents == null) { return false; } if (endContents.getSign() != piece.getSign()) { return false; } return white ? endContents.amIWhite() : !endContents.amIWhite(); } /** * This method isn't used with SuperPiece. * @param chessboard * @return */ @Override public List<Move> getPossibleMoves(Chessboard chessboard) { throw new UnsupportedOperationException("Not supported yet."); } /** * This method isn't used with SuperPiece. * @param chessboard * @param end * @return */ @Override public boolean isMoveValid(Chessboard chessboard, int end) { throw new UnsupportedOperationException("Not supported yet."); } }
true
929b5dc40ccab008c342e7b4d8f7dc538de3f11c
Java
Hukmaram28/Java-all
/CGI-Java/PE5/src/UpdateArray.java
UTF-8
350
2.8125
3
[]
no_license
import java.util.ArrayList; public class UpdateArray { public ArrayList<String> update(ArrayList<String> arrayList, String element, int position){ arrayList.set(position,element); return arrayList; } public ArrayList<String> empty(ArrayList<String>arrayList){ arrayList.clear(); return arrayList; } }
true
41c77a95f0280263717c01e814271b71ce64a296
Java
gong-shuang/become_app
/app/src/main/java/com/gs/learn/group/TabFragmentActivity.java
UTF-8
2,251
2.28125
2
[]
no_license
package com.gs.learn.group; import com.gs.learn.group.fragment.TabFirstFragment; import com.gs.learn.group.fragment.TabSecondFragment; import com.gs.learn.group.fragment.TabThirdFragment; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentTabHost; import android.view.View; import android.widget.LinearLayout; import android.widget.TabHost.TabSpec; import android.widget.TextView; import com.gs.learn.R; /** * Created by ouyangshen on 2016/10/21. */ public class TabFragmentActivity extends FragmentActivity { private static final String TAG = "TabFragmentActivity"; private FragmentTabHost mTabHost; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_tab_fragment); Bundle bundle = new Bundle(); bundle.putString("tag", TAG); mTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost); mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent); //addTab(标题,跳转的Fragment,传递参数的Bundle) mTabHost.addTab(getTabView(R.string.menu_first, R.drawable.tab_first_selector), TabFirstFragment.class, bundle); mTabHost.addTab(getTabView(R.string.menu_second, R.drawable.tab_second_selector), TabSecondFragment.class, bundle); mTabHost.addTab(getTabView(R.string.menu_third, R.drawable.tab_third_selector), TabThirdFragment.class, bundle); //设置tabs之间的分隔线不显示 mTabHost.getTabWidget().setShowDividers(LinearLayout.SHOW_DIVIDER_NONE); } private TabSpec getTabView(int textId, int imgId) { String text = getResources().getString(textId); Drawable drawable = getResources().getDrawable(imgId); //必须设置图片大小,否则不显示 drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight()); View item_tabbar = getLayoutInflater().inflate(R.layout.item_tabbar, null); TextView tv_item = (TextView) item_tabbar.findViewById(R.id.tv_item_tabbar); tv_item.setText(text); tv_item.setCompoundDrawables(null, drawable, null, null); TabSpec spec = mTabHost.newTabSpec(text).setIndicator(item_tabbar); return spec; } }
true
9a1c2b9e0f7d8574f622dca7f3b618e35e99b364
Java
543563979/algorithm010
/Week02/GroupAnagrams.java
UTF-8
941
3.453125
3
[]
no_license
// hash表 class GroupAnagrams { public List<List<String>> groupAnagrams(String[] strs) { if (strs.length == 0) { return null; } // 创建长度26的哈希表 int[] count = new int[26]; HashMap<String, List> map = new HashMap<String, List>(); for (String s : strs) { Arrays.fill(count, 0); // 记录字母出现的次数 for(char ch:s.toCharArray()) { count[ch-'a']++; } // 将统计的数据拼接成key StringBuffer sb = new StringBuffer(""); for (int i = 0 ;i < 26 ; i++) { sb.append("#"); sb.append(count[i]); } String key = sb.toString(); if (!map.containsKey(key)) map.put(sb.toString(), new ArrayList()); map.get(key).add(s); } return new ArrayList(map.values()); } }
true
72102f8725931aab53e7df5bb8b6c8312434aa4d
Java
dorgdev/playground
/Java/CG_Ex06/src/ex6/App.java
UTF-8
3,540
3.1875
3
[]
no_license
/* * Computer Graphics - Exercise 06 * Students' name: Dor Gross, Itamar Benady and Shlomi Babluki * Students' ID: 039344999, 300157427 and 021541065 */ package ex6; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.Frame; import java.awt.Toolkit; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.media.opengl.GLCanvas; import ex6.models.Spaceship; /** * Entry point of the game, and also user IO handler (Controller in the MVC * paradigm) */ public class App { /** The main frame of the game */ private static Frame frame; /** The GL canvas drawing the game */ private static GLCanvas canvas; /** The model part in the MVC pattern. Handles the game state */ private static GameLogic game; /** The view part in the MVC pattern. Handles the drawing */ private static Viewer viewer; /** * Create frame, canvas and viewer, and load the first model. * * @param args * No arguments */ public static void main(String[] args) { frame = new Frame("ex6: AsteroidBelt"); // Create game logic and viewer Spaceship spaceship = new Spaceship(); game = new GameLogic(spaceship); viewer = new Viewer(game, spaceship); canvas = new GLCanvas(); frame.setSize(500, 500); frame.setLayout(new BorderLayout()); frame.add(canvas, BorderLayout.CENTER); // Add event listeners canvas.addGLEventListener(viewer); frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { System.exit(1); } }); canvas.addKeyListener(new KeyAdapter() { @Override public void keyTyped(KeyEvent e) { switch (e.getKeyChar()) { case 'r': game.restart(); break; case 'p': game.togglePause(); break; case 's': viewer.toggleShip(); break; case 'j': viewer.toggleProjection(); break; case 'm': viewer.toggleShipMark(); break; case 'g': game.toggleGhostMode(); break; case 'c': game.toggleCruiseControl(); break; case 'd': viewer.toggleShowDirection(); break; case 't': viewer.toggleShowTextInfo(); break; case 'a': game.toggleMusic(); break; case '-': game.decreaseSpeed(); break; case '+': game.increaseSpeed(); break; case 'q': System.exit(0); default: System.out.println("Unknown key pressed: " + e.getKeyChar()); } } @Override public void keyPressed(KeyEvent e) { switch(e.getKeyCode()) { case KeyEvent.VK_LEFT: game.setTurnLeft(true); break; case KeyEvent.VK_RIGHT: game.setTurnRight(true); break; } } @Override public void keyReleased(KeyEvent e) { switch(e.getKeyCode()) { case KeyEvent.VK_LEFT: game.setTurnLeft(false); break; case KeyEvent.VK_RIGHT: game.setTurnRight(false); break; } } }); // Put the frame in the middle of the screen Dimension screenDimension = Toolkit.getDefaultToolkit().getScreenSize(); frame.setLocation((screenDimension.width - frame.getWidth()) / 2, (screenDimension.height - frame.getHeight()) / 2); // Show frame frame.setVisible(true); canvas.requestFocus(); canvas.requestFocusInWindow(); } }
true
69744cec3e5a8128d262073429305603ec4c07d8
Java
baatyr10/springFinal
/src/main/java/tr/com/jowl/controller/GlobalController.java
UTF-8
1,019
2.140625
2
[ "Apache-2.0" ]
permissive
package tr.com.jowl.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.context.annotation.ScopedProxyMode; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Component; import tr.com.jowl.model.User; import tr.com.jowl.service.UserService; /** * The GlobalController Class * * @author ibrahim KARAYEL * @version 1.0 * Date 4/27/2018. */ @Component @Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS) public class GlobalController { @Autowired private UserService userService; private User loginUser; public User getLoginUser() { if (loginUser == null) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); loginUser = userService.findByUserName(auth.getName()); } return loginUser; } }
true
67363be3f6b2b1f05339f4ecabc7d04a5881652c
Java
jackcailj/ddframework
/src/main/java/com/dangdang/ddframework/util/ExcelData.java
UTF-8
5,992
2.453125
2
[]
no_license
package com.dangdang.ddframework.util; import java.io.File; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.TreeMap; import java.util.regex.Matcher; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.dangdang.ddframework.core.TestGroups; import jxl.*; import jxl.write.WritableWorkbook; public class ExcelData implements Iterator<Object[]> { private Workbook book = null; private Sheet sheet = null; private int rowNum = 0;// 行数 private int curRowNo = 0;// 当前行数 private int columnNum = 0;// 列数 //private String[] columnnName;// 列名 protected static Logger logger = LoggerFactory.getLogger(ExcelData.class); private final String CASE_NAME = "用例名称"; private final String EXPECTED = "期望"; private List<String> includeGropupList=new ArrayList<String>(); private List<String> excludeGropupList=new ArrayList<String>(); private Map<String,Integer> columnMap=new HashMap<String,Integer>(); /* * 在TestNG中,由@DataProvider(dataProvider="name")修饰的方法读取Exel时,调用此类的构造方法( * 此方法会得到列名并将当前行移到下一行)执行完后,转到TestNG自己的方法中去,然后由他们调用此类实现的hasNext()、next() 方法; * 得到一行数据,然后返回给由@Test(dataProvider="name")修饰的方法,如此反复到数据读完为止。 * * @param filepath Excel文件名 * * @param casename用例名 */ public ExcelData(String filepath, String casename,String[] incluldGroups,String[] excluldGroups) { try { //String ss = "open.anniewang.newexcel."; //book = Workbook.getWorkbook(new File(filepath + ".xls")); book = Workbook.getWorkbook(ResourceLoader.class.getClassLoader().getResourceAsStream(filepath + ".xls")); this.sheet = book.getSheet(casename); this.rowNum = sheet.getRows(); Cell[] c = sheet.getRow(0); this.columnNum = c.length; //columnnName = new String[c.length]; for (int i = 0; i < c.length; i++) { // columnnName[i] = c[i].getContents().toString(); columnMap.put(c[i].getContents().trim(),i); } this.curRowNo++; Collections.addAll(includeGropupList, incluldGroups); Collections.addAll(excludeGropupList, excluldGroups); } catch (Exception e) { e.printStackTrace(); } } @Override public boolean hasNext() { /** * 方法功能:是否有下一条数据 如果行数为0即空sheet或者 当前行数大于总行数 就关闭对excel的操作返回false,否则返回true * */ if (this.rowNum == 0 || this.curRowNo >= this.rowNum) { try { book.close(); } catch (Exception e) { e.printStackTrace(); } return false; } else{ //循环找到下一个符合要求的行,没有返回false for(int i =curRowNo;i<this.rowNum;i++){ if(checkGroups(i)){ curRowNo=i; return true; } } return false; } } /* * 校验分组信息,校验此行数据是否符合目前运行的分组 * group列不存在或者为空表示不进行分组,任何group上都运行 */ private boolean checkGroups(int rowNumber) { // TODO Auto-generated method stub /* if(includeGropupList.size()==0 && excludeGropupList.size()==0){ return true; } */ //没有group列,代表任何group都运行,受方法上的group控制 if(columnMap.get("group")==null){ return true; } //获取当前行的group Cell[] c =sheet.getRow(rowNumber); String cellContent=c.length>columnMap.get("group") ? c[columnMap.get("group")].getContents().toLowerCase().trim():""; return TestGroups.CheckGroups(cellContent); /* //如果为空,代表任何group都运行 if(StringUtils.isBlank(cellContent)){ return true; } String[] groupStrings=cellContent.split(","); List<String> groupList = new ArrayList<String>(); Collections.addAll(groupList,groupStrings); // 检测是否包含在excludeGropupList里,为空,继续,包括返回false if (excludeGropupList.size() != 0) { for (String exGroup : excludeGropupList) { if (groupList.contains(exGroup.toLowerCase().trim())) { return false; } } } // 检测是否包含在includeGropupList里,为空,返回true,包括返回true;不包括返回false if (includeGropupList.size() == 0) { return true; } else { for (String inGroup : includeGropupList) { if (groupList.contains(inGroup.toLowerCase().trim())) { return true; } } return false; } */ } @Override public Object[] next() { /* * 方法功能:得到并返回下一行数据 * 使用for将一行的数据放入TreeMap中(TreeMap默认按照Key值升序排列,HashMap没有排序) * 然后将Map装入Object[]并返回,且将curRowNo当前行下移 */ Cell[] c = sheet.getRow(this.curRowNo); Map<String, String> s = new TreeMap<String, String>(); for (Entry<String, Integer> entry: columnMap.entrySet()) { String temp = ""; try { Cell currentCell=c[entry.getValue()]; if(currentCell.getType() == CellType.DATE){ DateCell dc = (DateCell)currentCell; temp = dc.getDateFormat().format(dc.getDate()); } else { temp = currentCell.getContents().toString(); } } catch (ArrayIndexOutOfBoundsException ex) { temp = ""; } s.put(entry.getKey(), temp.trim()); } Object r[] = new Object[3]; r[0] = s.get(CASE_NAME); r[1] = s; r[2] = s.get(EXPECTED); logger.info("测试用例---"+r[0]+"---开始执行"); // s.remove(CASE_NAME); // s.remove(EXCEPTED); s.remove("group"); this.curRowNo++; return r; } @Override public void remove() { throw new UnsupportedOperationException("remove unsupported."); } }
true
e42d0ccf265f46c121da81fbcf154d6680a9510c
Java
hb1500/MMT
/src/core/src/main/java/eu/modernmt/training/filters/CorporaBloomFilter.java
UTF-8
2,910
2.703125
3
[ "Apache-2.0" ]
permissive
package eu.modernmt.training.filters; import com.google.common.hash.BloomFilter; import com.google.common.hash.Funnel; import com.google.common.hash.PrimitiveSink; import eu.modernmt.io.UTF8Charset; import eu.modernmt.model.corpus.BaseMultilingualCorpus; import eu.modernmt.model.corpus.MultilingualCorpus; import java.io.IOException; public class CorporaBloomFilter { private final BloomFilter<MultilingualCorpus.StringPair> bloomFilter; public CorporaBloomFilter(long expectedEntries) { this(expectedEntries, 1. / 1000000.); } public CorporaBloomFilter(long expectedEntries, double fpp) { this.bloomFilter = BloomFilter.create(new StringPairFunnel(), expectedEntries, fpp); } public MultilingualCorpus wrap(final MultilingualCorpus corpus, final int lengthThreshold) { return new BaseMultilingualCorpus() { @Override public String getName() { return corpus.getName(); } @Override public MultilingualLineReader getContentReader() { throw new UnsupportedOperationException(); } @Override public MultilingualLineWriter getContentWriter(boolean append) throws IOException { return new MultilingualLineWriter() { private final MultilingualLineWriter writer = corpus.getContentWriter(append); @Override public void write(StringPair pair) throws IOException { boolean write; if (lengthThreshold > 0 && pair.source.length() < lengthThreshold && pair.target.length() < lengthThreshold) { write = true; } else { synchronized (CorporaBloomFilter.this) { write = bloomFilter.put(pair); // This is not thread safe, even in v24 } } if (write) writer.write(pair); } @Override public void flush() throws IOException { writer.flush(); } @Override public void close() throws IOException { writer.close(); } }; } }; } private static final class StringPairFunnel implements Funnel<MultilingualCorpus.StringPair> { @Override public void funnel(MultilingualCorpus.StringPair from, PrimitiveSink into) { into.putString(from.language.toString(), UTF8Charset.get()); into.putString(from.source, UTF8Charset.get()); into.putString(from.target, UTF8Charset.get()); } } }
true
140154a7ad11c73a9495e94a5a057c4f237b3771
Java
Ashtroid/Linear-Algebra
/src/EquationSolver.java
UTF-8
7,041
3.3125
3
[]
no_license
import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.Scanner; //Solves all nxn linear equations by transforming them into matrices and using LU decomposition public class EquationSolver { int numRow, numCol; double[][]matrix, L, testMatrix; ArrayList<ArrayList<Double>>entries = new ArrayList<ArrayList<Double>>(); Map<Integer, String>variables = new HashMap<Integer, String>(10); ArrayList<Double>solutions = new ArrayList<Double>(); ArrayList<Double>testSolutions = new ArrayList<Double>(); ArrayList<Double>vars= new ArrayList<Double>(); public EquationSolver() { numRow = 0; numCol = 0; } public void addLine(String line) { boolean isSolution = false; numRow++; String use = ""; double temp = 1; ArrayList<Double>currentRow = new ArrayList<Double>(); ArrayList<String>names = new ArrayList<String>(); for(int i = 0; i < line.length(); i++) { char comp = line.charAt(i); if(comp >='0' && comp <= '9') { use += comp - '0'; } else if(comp == '-' || comp == '.') { use += comp; } else if(comp == '+') { temp = 1; } else if(comp == ' ' || comp == '*') { } else if(comp == '=') { temp = 1; isSolution = true; } else { if(!isSolution) { String varName = line.substring(i,i+1); if(!variables.containsValue(varName)) variables.put(numCol++, varName); if(!use.isEmpty()) temp = Double.parseDouble(use); currentRow.add(temp); names.add(varName); use = ""; } } } if(isSolution) { if(!use.isEmpty()) temp = Double.parseDouble(use); solutions.add(temp); use = ""; } orderInts(currentRow,names); } //made by Ashwin Sethi private void orderInts(ArrayList<Double>currentRow, ArrayList<String>names) { ArrayList<Double>newList = new ArrayList<Double>(); for(int i = 0; i < variables.size(); i++) { String findVar = variables.get(i); boolean isFound = false; for(int t = 0; t<names.size(); t++) { if(names.get(t).equals(findVar)) { newList.add(currentRow.get(t)); isFound = true; } } if(!isFound) newList.add((double) 0); } entries.add(newList); } public void createMatrix() { if(numRow == 0) { System.out.println("Empty\nProgram is now closing\n\n\n"); return; } matrix = new double[numRow][numCol]; for(int a = 0; a < numRow; a++) { for(int b = 0; b < entries.get(a).size(); b++) matrix[a][b] = entries.get(a).get(b); } testMatrix = new double[numRow][numCol]; for(int i = 0; i < numRow; i++) for(int j = 0; j < numCol; j++) testMatrix[i][j] = matrix[i][j]; for(double x: solutions) testSolutions.add(x); } public void printMatrix() { System.out.println("Matrix:"); for(int b = 0; b<variables.size(); b++) { System.out.print(variables.get(b) + "\t"); } System.out.println("| Solutions"); for(int a = 0; a<numRow; a++) { for(int b = 0; b<numCol; b++) { System.out.print((int)matrix[a][b] + "\t"); } System.out.println("| " + solutions.get(a)); } } private void createLU() //modifies 'matrix' to U and makes L { L = new double[numRow][numRow]; for(int i = 0; i < numRow; i++) //creates diagonal of 1 L[i][i] = 1; for(int b = 1; b < numRow; b++) { for(int a = 0; a < b; a++) { compareRow(a,b); } } } public ArrayList<Double> solveLYb() { //Uy = b createLU(); ArrayList<Double>ySolutions = new ArrayList<Double>(); for(int i = 0; i < numRow; i++) { for(int j = 0; j < i; j++) { solutions.set(i,solutions.get(i)-L[i][j]*ySolutions.get(j)); } double h = solutions.get(i); ySolutions.add(h); } //System.out.println(ySolutions); return ySolutions; } public void solve(ArrayList<Double>ySol) //input L and y solutions { if(numRow != numCol) { System.out.println("Cannot compute non-square systems"); return; } ArrayList<Double>backwards= new ArrayList<Double>(); ArrayList<Double>inOrder= new ArrayList<Double>(); for(int i = numRow-1; i >= 0; i--) { for(int j = numCol-1; j>i; j--) { solutions.set(i,solutions.get(i)-matrix[i][j]*backwards.get(numRow-1-j)); //System.out.println(solutions.get(i)); } double h = 0; if(matrix[i][i]!=0) h = solutions.get(i)/matrix[i][i]; backwards.add(h); } for(int l = backwards.size()-1; l>=0; l--) inOrder.add(backwards.get(l)); for(int m = 0; m < inOrder.size(); m++) { vars.add(inOrder.get(m)); } if(isFine()) { System.out.println("One possible set of answers:"); for(int m = 0; m < inOrder.size(); m++) { System.out.println(variables.get(m) + " = " + inOrder.get(m)); } } else System.out.println("No solutions exist"); } private void compareRow(int row1, int row2) //modifies L and adds rows to make U { //modifies [row1][row2] in U to 0 and L double what = -matrix[row2][row1]/matrix[row1][row1]; for(int i =0; i < numCol; i++) matrix[row2][i] += matrix[row1][i]*what; L[row2][row1] = -what; } public void check() { for(int i = 0; i < numRow; i++) for(int j= 0; j < numCol; j++) System.out.println("Matrix@[" + i + "][" + j + "] is " + matrix[i][j]); } public void checkL() { for(int a = 0; a<numRow; a++) { for(int b = 0; b<numRow; b++) { System.out.print(L[a][b] + "\t"); } System.out.println("|"); } for(int i = 0; i < numRow; i++) for(int j= 0; j < numCol; j++) System.out.println("Matrix@[" + i + "][" + j + "] is " + L[i][j]); } private boolean isFine() { for(int a = 0; a < vars.size(); a++) if(vars.get(a) == Double.NaN) return false; for(int i = 0; i < numRow; i++) { double testNum = 0; for(int j = 0; j < numCol; j++) testNum += testMatrix[i][j]*vars.get(j); if(Math.abs(testNum - testSolutions.get(i)) > 0.05) return false; } return true; } @SuppressWarnings("resource") public static void main(String [] args) { System.out.println("Input Equations (enter 'done' to finish):"); EquationSolver n = new EquationSolver(); Scanner scan = new Scanner(System.in); boolean isDone = true; while(isDone) { String line = scan.nextLine(); if(line.equals("done")) isDone = false; if(isDone) { n.addLine(line); System.out.println(line); } } n.createMatrix(); n.printMatrix(); n.solve(n.solveLYb()); } /*public static void main(String[]args) { EquationSolver n = new EquationSolver(); n.addLine("2x + 2y + 4z = 4"); n.addLine("x + 3y + 2z = -2"); n.addLine("3x + 4y + 2z = 0"); //System.out.println("#Rows: " + n.numRow + "\n#Col: " + n.numCol); n.createMatrix(); n.solve(n.solveLYb()); //n.printMatrix(); }*/ }
true
3a3c43f520776d699ca3ff646542367b12687b92
Java
1nsp1r3rnzt/Stoicly
/app/src/main/java/com/codehealthy/stoicly/ui/allquote/QuoteViewModelFactory.java
UTF-8
828
2.3125
2
[]
no_license
package com.codehealthy.stoicly.ui.allquote; import android.app.Application; import android.arch.lifecycle.ViewModel; import android.arch.lifecycle.ViewModelProvider; import android.support.annotation.NonNull; public class QuoteViewModelFactory implements ViewModelProvider.Factory { private final Application application; public QuoteViewModelFactory(@NonNull Application application) { this.application = application; } @NonNull @Override public <T extends ViewModel> T create(@NonNull Class<T> modelClass) { if (modelClass.isAssignableFrom(com.codehealthy.stoicly.ui.allquote.QuoteViewModel.class)) { return (T) new com.codehealthy.stoicly.ui.allquote.QuoteViewModel(application); } throw new IllegalArgumentException("Unknown Model Class"); } }
true
26064f14d61b800086f3de8017d0a1433f03f4d7
Java
kingandsorrow/ks-parent
/ks-sso/ks-sso-web/src/main/java/top/ks/sso/web/config/CommonConfig.java
UTF-8
2,269
1.867188
2
[]
no_license
package top.ks.sso.web.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; import org.springframework.web.filter.CorsFilter; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import top.ks.sso.web.interceptor.LoginInterceptor; //import org.springframework.boot.autoconfigure.http.HttpMessageConverters; /** * <b>类名称:</b>CommonConfig$<br/> * <b>类注释:</b><br/> * <b>类描述:</b><br/> * <b>创建人:</b>brj<br/> * <b>修改人:</b>brj<br/> * <b>修改时间:</b>2018/10/6<br/> * <b>修改备注:</b><br/> * * @version 1.0.0 * Copyright KS 2018/10/6 */ @Configuration public class CommonConfig implements WebMvcConfigurer { @Autowired private LoginInterceptor loginInterceptor; @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(loginInterceptor).addPathPatterns("/*").excludePathPatterns("/login", "/checkToken", "/loginOut", "/captcha.jpg", "/error"); } @Bean public CorsFilter corsFilter() { //1.添加CORS配置信息 CorsConfiguration config = new CorsConfiguration(); //放行哪些原始域 config.addAllowedOrigin("*"); //是否发送Cookie信息 config.setAllowCredentials(true); //放行哪些原始域(请求方式) config.addAllowedMethod("*"); //放行哪些原始域(头部信息) config.addAllowedHeader("*"); //暴露哪些头部信息(因为跨域访问默认不能获取全部头部信息) // config.addExposedHeader("*"); //2.添加映射路径 UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource(); configSource.registerCorsConfiguration("/**", config); //3.返回新的CorsFilter. return new CorsFilter(configSource); } }
true
a2b74a9fc01323658378f72eefd41b9b0d85bf24
Java
amidgeha/sina-weibo-android
/jamendo-android/src/com/teleca/jamendo/gestures/GestureCommandRegister.java
UTF-8
554
2.765625
3
[ "Apache-2.0" ]
permissive
package com.teleca.jamendo.gestures; import java.util.HashMap; /** * Simple register for gesture commands. * * @author Bartosz Cichosz * */ public class GestureCommandRegister { private HashMap<String, GestureCommand> mGestures; public GestureCommandRegister() { mGestures = new HashMap<String, GestureCommand>(); } public void registerCommand(String name, GestureCommand gestureCommand) { mGestures.put(name, gestureCommand); } public GestureCommand getCommand(String name) { return mGestures.get(name); } }
true
90212c91f13b3cb9d910d134997812ddee8f5510
Java
Shuvayatra/migration-android-new
/app/src/main/java/com/taf/shuvayatra/gcm/MyFcmListenerService.java
UTF-8
3,977
2
2
[]
no_license
package com.taf.shuvayatra.gcm; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.support.v4.app.NotificationCompat; import android.support.v4.app.TaskStackBuilder; import com.google.firebase.messaging.FirebaseMessagingService; import com.google.firebase.messaging.RemoteMessage; import com.taf.data.utils.Logger; import com.taf.interactor.UseCaseData; import com.taf.model.Notification; import com.taf.shuvayatra.MyApplication; import com.taf.shuvayatra.R; import com.taf.shuvayatra.di.component.DaggerApplicationComponent; import com.taf.shuvayatra.di.component.DaggerDataComponent; import com.taf.shuvayatra.di.module.ActivityModule; import com.taf.shuvayatra.di.module.ApplicationModule; import com.taf.shuvayatra.di.module.DataModule; import com.taf.shuvayatra.presenter.NotificationReceivedPresenter; import com.taf.shuvayatra.ui.activity.SplashScreenActivity; import java.util.Map; import javax.inject.Inject; public class MyFcmListenerService extends FirebaseMessagingService { @Inject NotificationReceivedPresenter mPresenter; @Override public void onMessageReceived(RemoteMessage pRemoteMessage) { initialize(); Map<String, String> data = pRemoteMessage.getData(); Logger.d("MyGcmListenerService_onMessageReceived", "data:" + data.toString()); String title = data.get("title"); String description = data.get("description"); description = description != null ? description : ""; if (title != null) { NotificationCompat.Builder builder = new NotificationCompat.Builder(this) .setSmallIcon(R.drawable.ic_notification) .setContentTitle(title) .setContentText(description) .setDefaults(NotificationCompat.DEFAULT_SOUND | NotificationCompat .DEFAULT_VIBRATE) .setLights(Color.GREEN, 2000, 3000) .setAutoCancel(true) .setStyle(new NotificationCompat.BigTextStyle().bigText(description)); Intent resultIntent = new Intent(this, SplashScreenActivity.class); TaskStackBuilder stackBuilder = TaskStackBuilder.create(this); stackBuilder.addParentStack(SplashScreenActivity.class); stackBuilder.addNextIntent(resultIntent); PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT); builder.setContentIntent(resultPendingIntent); NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context .NOTIFICATION_SERVICE); mNotificationManager.notify(2390, builder.build()); saveNotificationToDB(title, description); } } private void initialize() { DaggerDataComponent.builder() .activityModule(new ActivityModule()) .applicationComponent(DaggerApplicationComponent.builder() .applicationModule(new ApplicationModule((MyApplication) this .getApplicationContext())) .build()) .dataModule(new DataModule()) .build() .inject(this); } private void saveNotificationToDB(String title, String description) { UseCaseData useCaseData = new UseCaseData(); Notification notification = new Notification(); notification.setTitle(title); notification.setDescription(description); notification.setCreatedAt(System.currentTimeMillis() / 1000); notification.setUpdatedAt(System.currentTimeMillis() / 1000); useCaseData.putSerializable(UseCaseData.SUBMISSION_DATA, notification); mPresenter.initialize(useCaseData); } }
true
48dca892dd1a77201950d52d44b8a0f83d71ca15
Java
daocrossover/SwordOffer
/src/binary_search/IntegerIdenticalToIndex.java
UTF-8
884
4.0625
4
[]
no_license
package binary_search; /* 面试题53(三):数组中数值和下标相等的元素 题目:假设一个单调递增的数组里的每个元素都是整数并且是唯一的。请编程实 现一个函数找出数组中任意一个数值等于其下标的元素。例如,在数组{-3, -1, 1, 3, 5}中,数字3和它的下标相等。 */ public class IntegerIdenticalToIndex { int GetNumberSameAsIndex(int[] numbers, int length) { if (numbers == null || length <= 0) return -1; int left = 0; int right = length - 1; while (left <= right) { int mid = left + (right - left) / 2; if (numbers[mid] == mid) { return mid; } else if(numbers[mid] > mid) { right = mid - 1; } else { left = mid + 1; } } return -1; } }
true
925b10b8657657b7ff0403233456250d958ba8b8
Java
Jinyu97/java
/과제/Hw9_1.java
UHC
1,619
4
4
[]
no_license
class Figure{ double round; double area; Figure(){} Figure(double round, double area){ this.round = round; this.area = area; } @Override public String toString(){ return String.format(" "+getClass().getName()+"̰, ѷ %.2f, ̴ %.2fԴϴ.\n", this.round, this.area); } } class Circle extends Figure{ double radius; Circle(){} Circle(double radius){ super(radius*2*Math.PI, radius*radius*Math.PI); this.radius = radius; } @Override public String toString(){ return super.toString()+String.format(", %.1fԴϴ.\n", this.radius); } @Override public boolean equals(Object o){ if(o instanceof Circle){ if(this.radius == ((Circle)o).radius) return true; else return false; } else return false; } } class EquilateralTriangle extends Figure{ double side; EquilateralTriangle(){} EquilateralTriangle(double side){ super(side*3, Math.sqrt(3)/4*side*side); this.side = side; } @Override public String toString(){ return super.toString()+String.format(" ﰢ ̴ %.2f̰, ̴ %.2fԴϴ.\n", side, Math.sqrt(3)/2*side); } } class Hw9_1{ public static void main(String [] args){ Circle c1 = new Circle(3.0); Circle c2 = new Circle(1); Circle c3 = new Circle(3.0); EquilateralTriangle t1 = new EquilateralTriangle(3.0); System.out.println(c1); System.out.println(t1); System.out.println(c2); System.out.println(c1.equals(c2)); System.out.println(c3.equals(c1)); } }
true
1908ca3db227cc53a8eb809995857cb46998cc5d
Java
LuGaXu/AdvancedAlgorithm
/src/main/java/week2/ShellSort.java
UTF-8
805
3.3125
3
[]
no_license
package week2; /** * Created by lujxu on 2017/12/21. */ public class ShellSort { public static void main(String []args){ int [] array=new int[]{2,4,1,4,2,9,6,5,3,5}; ShellSort s=new ShellSort(); s.shellsort(array); System.out.println("test"); } public int [] shellsort(int [] list){ int gap=(int)list.length/2; while (gap!=0){ shellInsert(list, gap); gap=(int)gap/2; } return list; } public void shellInsert(int [] list, int gap){ for (int i=gap;i<list.length;i++){ int temp=list[i]; int j=i; while (j>=gap&&temp<list[j-gap]){ list[j]=list[j-gap]; j=j-gap; } list[j]=temp; } } }
true
95b3b21985f68e50952a99f263aac86a35dd914b
Java
Skularach/ThermometersDomain
/ThermometersDomain/src/BoardActions/MakeLearningInstances.java
UTF-8
14,292
2.875
3
[]
no_license
package BoardActions; import java.util.ArrayList; import weka.core.DenseInstance; import weka.core.Instance; import Utilities.Quadruple; import Utilities.Triple; import WEKA.Classification; import WEKA.InstanceCreation; import BoardRepresentation.Board; import BoardRepresentation.ComplexThermsBoard; import BoardRepresentation.SimpleThermsBoard; import FactsExtraction.RuleBasedBoardFacts; import javafx.util.Pair; /** * This class is a library for creating WEKA-ready learning instances from thermometers boards. * Handles both Simple and Complex Thermometers boards * * @author Brandon Packard * */ public class MakeLearningInstances { //Indices for Complex Thermometer features- precalculated for ease of understanding public final static int wholeColumnRulesStartIndex = Board.BOARDSIZE * Board.BOARDSIZE; public final static int complicatedColRulesStartIndex = wholeColumnRulesStartIndex + 2 * Board.BOARDSIZE; public final static int remainingColRulesIndex = complicatedColRulesStartIndex + Board.BOARDSIZE * Board.BOARDSIZE*2; public final static int startingRowIndex = remainingColRulesIndex + Board.BOARDSIZE * Board.BOARDSIZE * 2; public final static int complicatedRowRulesStartIndex = startingRowIndex + 2 * Board.BOARDSIZE; public final static int remainingRowRulesIndex = complicatedRowRulesStartIndex + Board.BOARDSIZE * Board.BOARDSIZE*2; /**General case. Determines whether the passed in board is a Simple or Complex board, * and calls the appropriate instance-creation method. * @param board The board from which to create the instance * */ public static Instance getInstance(Board board) { Instance instance; //Use instanceof to see whether we are dealing with a simple or complex board, // and call the appropriate instance creation method. if(board instanceof SimpleThermsBoard) instance = createSimpleThermsInstance((SimpleThermsBoard)board); else instance = createInstanceComplexTherms((ComplexThermsBoard)board); return instance; } /** Creates a learning instance for simple thermometers boards. The features are: * 0-4: Whether each tile is full, empty, or unknown * 5-9: Whether each tile has a relevant thermometer piece (if we are looking at rows, a vertical thermometer is irrelevant. Likewise with columns and horizontal. * 10: The number of tiles (total) that should be filled in the row/column * 11-13: The current number of filled, empty, and blank tiles, in that order * 14: The action taken (this will be left unknown by this method, since it is not yet known) * * @param board The board from which to create the instance * */ private static Instance createSimpleThermsInstance(SimpleThermsBoard board) { //Initialize instance Instance anInstance = new DenseInstance(InstanceCreation.numWEKAattributes); anInstance.setDataset(Classification.globalInstanceDatabase); //Set all Therm Piece features to the default of "NO", for "no relevant thermometer piece on this tile" try{ for(int i = 0; i < board.grid.size(); i++) anInstance.setValue(InstanceCreation.WEKAattributes.get(Board.BOARDSIZE + i),"NO"); }catch(Exception e) {e.printStackTrace();} //Rows and columns handled separately, which is the usual case for Simple Thermometers if(!board.lookingAtRows) { //Update the thermometer data with the newest tile values, just in case it hasn't already been done board.updateThermData(); //Set the fill for each tile to whatever the fill currently is for that file. for(int i = 0; i < board.grid.size(); i++) anInstance.setValue(InstanceCreation.WEKAattributes.get(0+i), board.grid.get(i).get(board.colIndex) + ""); //For each thermometer in the column for(int j = 0; j < board.colTherms.get(board.colIndex).size(); j++) { //for each piece in that thermometer for(int k = 0; k < board.colTherms.get(board.colIndex).get(j).size(); k++) { //Get the string code for that piece. Details on the string codes can be found in BoardFileIO.java int location = board.colTherms.get(board.colIndex).get(j).get(k).getXPos(); String code = board.stringGrid[board.colTherms.get(board.colIndex).get(j).get(k).getXPos()][board.colTherms.get(board.colIndex).get(j).get(k).getYPos()]; //This framework treats rows and columns the same, so replace column-only code values with their row equivalents for consistency. code = code.replace('D', 'R'); code = code.replace('U', 'L'); code = code.replace('V', 'H'); //The last letter in each 3 letter code is the "true fill" of the tile (the fill it will have when the board is solved) // This is information the learner should not have, so we remove it. code = code.substring(0,code.length() - 1); anInstance.setValue(InstanceCreation.WEKAattributes.get(Board.BOARDSIZE + location), code); } } //Set the next feature as the number of filled tiles the column should have when the board is solved anInstance.setValue(InstanceCreation.WEKAattributes.get(Board.BOARDSIZE * 2), board.colCounts.get(board.colIndex)); //Set the next 3 features as the current number of filled, blank, and empty tiles in the row int numBlank = 0; int numFilled = 0; int numEmpty = 0; for(int i = 0; i < board.grid.size(); i++) { if(board.grid.get(i).get(board.colIndex) == 1) numFilled++; else if(board.grid.get(i).get(board.colIndex)== 0) numBlank++; else numEmpty++; } anInstance.setValue(InstanceCreation.WEKAattributes.get(Board.BOARDSIZE * 2 + 1), numFilled); anInstance.setValue(InstanceCreation.WEKAattributes.get(Board.BOARDSIZE * 2 + 2), numEmpty); anInstance.setValue(InstanceCreation.WEKAattributes.get(Board.BOARDSIZE * 2 + 3), numBlank); } else//(RowOrColumn.lookingAtRows) { //Update the thermometer data with the newest tile values, just in case it hasn't already been done board.updateThermData(); //Set the fill for each tile to whatever the fill currently is for that file. for(int i = 0; i < board.grid.size(); i++) anInstance.setValue(InstanceCreation.WEKAattributes.get(0+i), board.grid.get(board.rowIndex).get(i)+""); //For each thermometer in the row for(int j = 0; j < board.rowTherms.get(board.rowIndex).size(); j++) { //For each piece of the thermometer for(int k = 0; k < board.rowTherms.get(board.rowIndex).get(j).size(); k++) { //Get the string code for that piece. Details on the string codes can be found in BoardFileIO.java int location = board.rowTherms.get(board.rowIndex).get(j).get(k).getYPos(); String code = board.stringGrid[board.rowTherms.get(board.rowIndex).get(j).get(k).getXPos()][board.rowTherms.get(board.rowIndex).get(j).get(k).getYPos()]; //The last letter in each 3 letter code is the "true fill" of the tile (the fill it will have when the board is solved) // This is information the learner should not have, so we remove it. code = code.substring(0,code.length() - 1); anInstance.setValue(InstanceCreation.WEKAattributes.get(Board.BOARDSIZE + location), code); } } //Set the next feature as the number of filled tiles the column should have when the board is solved anInstance.setValue(InstanceCreation.WEKAattributes.get(Board.BOARDSIZE * 2), board.rowCounts.get(board.rowIndex)); //Set the next 3 features as the current number of filled, blank, and empty tiles in the row int numBlank = 0; int numFilled = 0; int numEmpty = 0; for(int i = 0; i < board.grid.size(); i++) { if(board.grid.get(board.rowIndex).get(i) == 1) numFilled++; else if(board.grid.get(board.rowIndex).get(i)== 0) numBlank++; else numEmpty++; } anInstance.setValue(InstanceCreation.WEKAattributes.get(Board.BOARDSIZE * 2 + 1), numFilled); anInstance.setValue(InstanceCreation.WEKAattributes.get(Board.BOARDSIZE * 2 + 2), numEmpty); anInstance.setValue(InstanceCreation.WEKAattributes.get(Board.BOARDSIZE * 2 + 3), numBlank); } return anInstance; } /** Creates a learning instance for simple thermometers boards. * There are 6 rules used to play the game, and the features correspond to which of those rules apply where. * For more information, please refer to RuleBasedBoardFacts.java * * @param board The board from which to create the instance * */ private static Instance createInstanceComplexTherms(ComplexThermsBoard board) { //Initialize instance Instance anInstance = new DenseInstance(InstanceCreation.numWEKAattributes); //Set default values for features for(int i = 0; i < Board.BOARDSIZE * Board.BOARDSIZE; i++) anInstance.setValue(InstanceCreation.WEKAattributes.get(i), "NotBlank"); for(int i = wholeColumnRulesStartIndex; i < wholeColumnRulesStartIndex + Board.BOARDSIZE * 2; i++) anInstance.setValue(InstanceCreation.WEKAattributes.get(i), "no"); for(int i = complicatedColRulesStartIndex; i < complicatedColRulesStartIndex + Board.BOARDSIZE * Board.BOARDSIZE * 2; i++) anInstance.setValue(InstanceCreation.WEKAattributes.get(i), "-1"); for(int i = remainingColRulesIndex; i < remainingColRulesIndex + Board.BOARDSIZE * Board.BOARDSIZE * 2; i++) anInstance.setValue(InstanceCreation.WEKAattributes.get(i), "no"); for(int i = startingRowIndex; i < startingRowIndex + Board.BOARDSIZE * 2; i++) anInstance.setValue(InstanceCreation.WEKAattributes.get(i), "no"); for(int i = complicatedRowRulesStartIndex; i < complicatedRowRulesStartIndex + Board.BOARDSIZE * Board.BOARDSIZE * 2; i++) anInstance.setValue(InstanceCreation.WEKAattributes.get(i), "-1"); for(int i = remainingRowRulesIndex; i < remainingRowRulesIndex + Board.BOARDSIZE * Board.BOARDSIZE * 2; i++) anInstance.setValue(InstanceCreation.WEKAattributes.get(i), "no"); //grid binary features (blanks only!) for(int i = 0; i < board.grid.size(); i++) for(int j = 0; j < board.grid.get(0).size(); j++) if(board.grid.get(i).get(j) == 0) anInstance.setValue(InstanceCreation.WEKAattributes.get(j* Board.BOARDSIZE+i), "Blank"); //Rule 1 ArrayList<Pair<Character, Integer>> ruleFacts = RuleBasedBoardFacts.restFilledRuleFacts(board.grid, board.rowCounts, board.colCounts); for(int i = 0; i < ruleFacts.size(); i++) { if(ruleFacts.get(i).getKey() == 'c') { anInstance.setValue(InstanceCreation.WEKAattributes.get(wholeColumnRulesStartIndex + ruleFacts.get(i).getValue()), "yes"); } else if(ruleFacts.get(i).getKey() == 'r') { anInstance.setValue(InstanceCreation.WEKAattributes.get(startingRowIndex + ruleFacts.get(i).getValue()), "yes"); } } //Rule 2 ruleFacts = RuleBasedBoardFacts.restEmptyRuleFacts(board.grid, board.rowCounts, board.colCounts); for(int i = 0; i < ruleFacts.size(); i++) { if(ruleFacts.get(i).getKey() == 'c') { anInstance.setValue(InstanceCreation.WEKAattributes.get(wholeColumnRulesStartIndex + Board.BOARDSIZE + ruleFacts.get(i).getValue()), "yes"); } else if(ruleFacts.get(i).getKey() == 'r') { anInstance.setValue(InstanceCreation.WEKAattributes.get(startingRowIndex + Board.BOARDSIZE + ruleFacts.get(i).getValue()), "yes"); } } //Rule 3 ArrayList<Triple> ruleTriples = RuleBasedBoardFacts.restThermEmptyRuleFacts(board.grid, board.rowCounts, board.colCounts, board.rowTherms, board.colTherms); for(int i = 0; i < ruleTriples.size(); i++) { if(ruleTriples.get(i).getFirst() == 'c') { anInstance.setValue(InstanceCreation.WEKAattributes.get(remainingColRulesIndex + Board.BOARDSIZE * Board.BOARDSIZE + ruleTriples.get(i).getSecond() * Board.BOARDSIZE + ruleTriples.get(i).getThird()), "yes"); } else if(ruleTriples.get(i).getFirst() == 'r') { anInstance.setValue(InstanceCreation.WEKAattributes.get(remainingRowRulesIndex + Board.BOARDSIZE * Board.BOARDSIZE + ruleTriples.get(i).getSecond() * Board.BOARDSIZE + ruleTriples.get(i).getThird()), "yes"); } } //Rule 4 ruleTriples = RuleBasedBoardFacts.restThermFilledRuleFacts(board.grid, board.rowCounts, board.colCounts, board.rowTherms, board.colTherms); for(int i = 0; i < ruleTriples.size(); i++) { if(ruleTriples.get(i).getFirst() == 'c') { anInstance.setValue(InstanceCreation.WEKAattributes.get(remainingColRulesIndex + ruleTriples.get(i).getSecond() * Board.BOARDSIZE + ruleTriples.get(i).getThird()), "yes"); } else if(ruleTriples.get(i).getFirst() == 'r') { anInstance.setValue(InstanceCreation.WEKAattributes.get(remainingRowRulesIndex + ruleTriples.get(i).getSecond() * Board.BOARDSIZE + ruleTriples.get(i).getThird()), "yes"); } } //Rule 5 ArrayList<Quadruple> ruleQuads = RuleBasedBoardFacts.thermTooBigRuleFacts(board.grid, board.rowCounts, board.colCounts, board.rowTherms, board.colTherms); for(int i = 0; i < ruleQuads.size(); i++) { if(ruleQuads.get(i).getFirst() == 'c') { anInstance.setValue(InstanceCreation.WEKAattributes.get(complicatedColRulesStartIndex + ruleQuads.get(i).getSecond() * Board.BOARDSIZE + ruleQuads.get(i).getThird()),ruleQuads.get(i).getFourth() ); } else if(ruleQuads.get(i).getFirst() == 'r') { anInstance.setValue(InstanceCreation.WEKAattributes.get(complicatedRowRulesStartIndex + ruleQuads.get(i).getSecond() * Board.BOARDSIZE + ruleQuads.get(i).getThird()),ruleQuads.get(i).getFourth() ); } } //Rule 6 ruleQuads = RuleBasedBoardFacts.partiallyFillThermRuleFacts(board.grid, board.rowCounts, board.colCounts, board.rowTherms, board.colTherms); for(int i = 0; i < ruleQuads.size(); i++) { if(ruleQuads.get(i).getFirst() == 'c') { anInstance.setValue(InstanceCreation.WEKAattributes.get(complicatedColRulesStartIndex + Board.BOARDSIZE * Board.BOARDSIZE + ruleQuads.get(i).getSecond() * Board.BOARDSIZE + ruleQuads.get(i).getThird()),ruleQuads.get(i).getFourth()); } else if(ruleQuads.get(i).getFirst() == 'r') { anInstance.setValue(InstanceCreation.WEKAattributes.get(complicatedRowRulesStartIndex + Board.BOARDSIZE * Board.BOARDSIZE + ruleQuads.get(i).getSecond() * Board.BOARDSIZE + ruleQuads.get(i).getThird()),ruleQuads.get(i).getFourth()); } } return anInstance; } }
true
ea7f66726d7bd08c00364917147be9dd31498743
Java
arajitha/Questions
/Test/GraphBFS.java
UTF-8
1,512
3.15625
3
[]
no_license
package Test; import java.util.LinkedList; import java.util.Queue; public class GraphBFS { public static void bfs1(int[][] m, int nodes){ Queue<Integer> q = new LinkedList<Integer>(); int NNodes = nodes; int[] visited = new int[NNodes]; //for(int i = 0 ; i < nodes-1; i++){ // visited[i] = 0; //} q.add(0); //visited[source] = 1; while( ! q.isEmpty() ) { int nextNode; // Next node to visit int i; nextNode = q.remove(); if (visited[nextNode] == 0 ) { visited[nextNode] = 1; // Mark node as visited System.out.println("nextNode = " + nextNode ); for ( i = 0; i < NNodes; i++ ) if ( m[nextNode][i] > 0 && visited[i] ==0 ) q.add(i); } } } public static void main(String[] args){ int m[][] = {{0, 1, 0, 1}, {0, 0, 1, 0 }, {0, 1, 0, 1}, {0, 0, 0, 1}}; int p[][] = { { 0, 1, 0, 1, 0, 0, 0, 0, 1 }, // 0 { 1, 0, 0, 0, 0, 0, 0, 1, 0 }, // 1 { 0, 0, 0, 1, 0, 1, 0, 1, 0 }, // 2 { 1, 0, 1, 0, 1, 0, 0, 0, 0 }, // 3 { 0, 0, 0, 1, 0, 0, 0, 0, 1 }, // 4 { 0, 0, 1, 0, 0, 0, 1, 0, 0 }, // 5 { 0, 0, 0, 0, 0, 1, 0, 0, 0 }, // 6 { 0, 1, 1, 0, 0, 0, 0, 0, 0 }, // 7 { 1, 0, 0, 0, 1, 0, 0, 0, 0 } }; bfs1(p,9); // bfs1(m,4); // 0 1 3 2 } }
true
8147ad02a86824fbdb349db865d8fad91606365c
Java
diman4ik/EnergySaver
/core/src/com/denis/game/objects/R4Switch.java
UTF-8
361
2.609375
3
[]
no_license
package com.denis.game.objects; import com.denis.game.GameObject; /** * Created by loki on 26.06.16. */ public class R4Switch extends GameObject { public static final float R4SWITCH_WIDTH = 0.6f; public static final float R4SWITCH_HEIGHT = 1.2f; public R4Switch(float x, float y) { super(x, y, R4SWITCH_WIDTH, R4SWITCH_HEIGHT); } }
true