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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
1a0922e36b92e8cda5424c9075359713e09a1228
|
Java
|
aaron0819/SalonAppV2
|
/src/main/java/com/hampson/salonapp/util/AppointmentUtils.java
|
UTF-8
| 891
| 2.421875
| 2
|
[] |
no_license
|
package com.hampson.salonapp.util;
import com.hampson.salonapp.model.AppointmentRequest;
public class AppointmentUtils {
public static AppointmentRequest buildAppointmentObject(String appointmentType, int customerId,
String appointmentDate, String alternateAppointmentDate, String appointmentStartTime,
String alternateAppointmentTime, String preferredStylist) {
AppointmentRequest apptRequest = new AppointmentRequest();
apptRequest.setAppointmentType(appointmentType);
apptRequest.setCustomerId(customerId);
apptRequest.setAppointmentDate(appointmentDate);
apptRequest.setAlternateAppointmentDate(alternateAppointmentDate);
apptRequest.setAppointmentStartTime(appointmentStartTime);
apptRequest.setAlternateAppointmentTime(alternateAppointmentTime);
apptRequest.setPreferredStylist(preferredStylist);
return apptRequest;
}
}
| true
|
77575bab351b269cb49d2ab089433737d5c258fa
|
Java
|
guoyu07/Latte-lang
|
/src/test/java/lt/compiler/library/TestLibraries.java
|
UTF-8
| 7,575
| 2.046875
| 2
|
[
"MIT"
] |
permissive
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2016 KuiGang Wang
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package lt.compiler.library;
import lt.repl.Compiler;
import org.junit.Test;
import java.lang.reflect.Method;
import java.util.*;
import static org.junit.Assert.*;
/**
* test libraries
*/
public class TestLibraries {
public static ClassLoader load(Map<String, Object> map) throws Exception {
Compiler compiler = new Compiler();
return compiler.compile(map);
}
@Test
public void testHtml() throws Exception {
ClassLoader loader = load(new HashMap<String, Object>() {{
try {
ClassLoader.getSystemClassLoader().loadClass("lt.html.HTMLElement");
} catch (ClassNotFoundException ignore) {
put("html.lt", TestLibraries.class.getResourceAsStream("/lt/html.lt"));
}
put("test_html.lt", TestLibraries.class.getResourceAsStream("/test_libraries/test_html.lt"));
}});
Class<?> TestHtml = loader.loadClass("lt.html.test.TestHtml");
Class<?> Html = loader.loadClass("lt.html.Html");
Object html = Html.newInstance(); // html=Html()
Method testConstructHtml = TestHtml.getMethod("testConstructHtml");
assertEquals(html, testConstructHtml.invoke(null));
Method testHtmlFormat = TestHtml.getMethod("testHtmlFormat");
assertEquals("" +
"<html>" +
"<head>" +
"</head>" +
"<body>" +
"<form>" +
"<input type='text' value='hello world'>" +
"</form>" +
"</body>" +
"</html>", testHtmlFormat.invoke(null).toString());
}
@Test
public void testSQL() throws Exception {
ClassLoader loader = load(new HashMap<String, Object>() {{
try {
ClassLoader.getSystemClassLoader().loadClass("lt.sql.DB");
} catch (ClassNotFoundException ignore) {
put("sql.lt", TestLibraries.class.getResourceAsStream("/lt/sql.lt"));
}
put("test_sql.lt", TestLibraries.class.getResourceAsStream("/test_libraries/test_sql.lt"));
}});
Class<?> TestSQL = loader.loadClass("lt.sql.test.TestSQL");
TestSQL.getMethod("init").invoke(null);
Method testSelectString = TestSQL.getMethod("testSelectString");
assertEquals("select `User`.`id`, `User`.`name` from `User` where `User`.`id` > ? order by `User`.`id` desc limit ?,?",
testSelectString.invoke(null));
Method testSelectAlias = TestSQL.getMethod("testSelectAlias");
assertEquals("select `User`.`id` as theId, `User`.`name` as theName from `User`",
testSelectAlias.invoke(null));
Method testSelectWithSubQuery = TestSQL.getMethod("testSelectWithSubQuery");
assertEquals("select `User`.`id`, `User`.`name` from `User` where `User`.`id` <= " +
"(select `User`.`id` from `User` limit ?) order by `User`.`id` desc",
testSelectWithSubQuery.invoke(null));
Method testInsertString = TestSQL.getMethod("testInsertString");
assertEquals("insert into `User` (`id`, `name`) values (?, ?)",
testInsertString.invoke(null));
Method testUpdateString = TestSQL.getMethod("testUpdateString");
assertEquals("update `User` set `User`.`id` = ? where `User`.`name` = ?",
testUpdateString.invoke(null));
Method testDeleteString = TestSQL.getMethod("testDeleteString");
assertEquals("delete from `User` where `User`.`id` = ?",
testDeleteString.invoke(null));
Method testDBUpdate = TestSQL.getMethod("testDBUpdate");
Object testDBUpdateResult = testDBUpdate.invoke(null);
List<Map<String, Object>> testDBUpdateResultExpected = new ArrayList<>();
Map<String, Object> testDBUpdateResultExpectedMap = new LinkedHashMap<>();
testDBUpdateResultExpectedMap.put("ID", 1);
testDBUpdateResultExpectedMap.put("NAME", "cass");
testDBUpdateResultExpected.add(testDBUpdateResultExpectedMap);
assertEquals(testDBUpdateResultExpected, testDBUpdateResult);
Method testQuery = TestSQL.getMethod("testQuery");
Object testQueryResult = testQuery.invoke(null);
List<List<Map<String, Object>>> expected = new ArrayList<>();
List<Map<String, Object>> testQueryRes1 = new ArrayList<>();
Map<String, Object> testQueryRes1Map1 = new LinkedHashMap<>();
testQueryRes1Map1.put("THENAME", "cass");
Map<String, Object> testQueryRes1Map2 = new LinkedHashMap<>();
testQueryRes1Map2.put("THENAME", "latte");
testQueryRes1.add(testQueryRes1Map1);
testQueryRes1.add(testQueryRes1Map2);
expected.add(testQueryRes1);
List<Map<String, Object>> testQueryRes2 = new ArrayList<>();
Map<String, Object> testQueryRes2Map1 = new LinkedHashMap<>();
testQueryRes2Map1.put("THENAME", "wkgcass");
Map<String, Object> testQueryRes2Map2 = new LinkedHashMap<>();
testQueryRes2Map2.put("THENAME", "latte");
testQueryRes2.add(testQueryRes2Map1);
testQueryRes2.add(testQueryRes2Map2);
expected.add(testQueryRes2);
List<Map<String, Object>> testQueryRes3 = new ArrayList<>();
testQueryRes3.add(testQueryRes2Map1);
expected.add(testQueryRes3);
assertEquals(expected, testQueryResult);
Method testAndOr = TestSQL.getMethod("testAndOr");
assertEquals("select User.name from User where (User.id > ? and User.name <> ?) or User.id < ?", testAndOr.invoke(null));
}
}
| true
|
d8892eb6f36256dbbd5b43fb8fe1dd29e94be1f2
|
Java
|
hippiesus/Analizador
|
/src/analizador/Nodo.java
|
UTF-8
| 852
| 2.53125
| 3
|
[] |
no_license
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package analizador;
import java.util.LinkedList;
import java.util.List;
/**
*
* @author juancarlos
*/
public class Nodo {
private String programa;
private List<Nodo> relaciones= new LinkedList<Nodo>();
/**
* @return the programa
*/
public String getPrograma() {
return programa;
}
/**
* @param programa the programa to set
*/
public void setPrograma(String programa) {
this.programa = programa;
}
/**
* @return the llamadas
*/
public List<Nodo> getLlamadas() {
return relaciones;
}
/**
* @param llamadas the llamadas to set
*/
public void setLlamadas(List<Nodo> llamadas) {
this.relaciones = llamadas;
}
}
| true
|
edbdff0bb0d424a21dddddfc316eb444467d7137
|
Java
|
jsnejcopbe/nanny
|
/src/com/zhuoan/shh/biz/SSHUtilBiz.java
|
UTF-8
| 2,206
| 2.40625
| 2
|
[] |
no_license
|
package com.zhuoan.shh.biz;
import java.io.Serializable;
import java.util.List;
import com.zhuoan.ssh.bean.PageUtil;
import com.zhuoan.ssh.bean.QueryParam;
public interface SSHUtilBiz {
/**
* 将实体对象持久化(保存到数据库)
* @param obj
* @return
*/
public Serializable saveObject(Object obj);
/**
* 根据实体对象ID获取实体对象
* @param clazz
* @param id
* @return
*/
public Object getObjectById(Class<?> clazz, Serializable id);
/**
* 更新实体对象信息
* @param obj
*/
public void updateObject(Object obj);
/**
* 将实体对象删除(慎用:物理删除)
* @param obj
*/
public void deleteObject(Object obj);
public void updateObjectBySQL(String sql, Object[] queryParam);
/**
* 根据条件获取列colName的总数
* @param clazz
* @param colName
* @param queryParam
* @return
*/
public Integer getObjectCount(Class<?> clazz, String colName, QueryParam queryParam);
/**
* 根据条件获取记录列表
* @param hql
* @param queryParam
* @param pageUtil
* @return
*/
public List<?> getObjectList(String hql, Object[] queryParam, PageUtil pageUtil);
/**
* 根据条件获取记录列表
* @param sql
* @param queryParam
* @param pageUtil
* @return
*/
public List<?> getObjectListBySQL(String sql, Object[] queryParam, PageUtil pageUtil);
/**
* 根据条件获取记录列表
* @param clazz
* @param queryParam
* @param pageUtil
* @return
*/
public List<?> getObjectList(Class<?> clazz, QueryParam queryParam, PageUtil pageUtil);
/**
* 根据条件获取总页数
* @param clazz
* @param queryParam
* @param pageUtil
* @return
*/
public PageUtil getPageCount(Class<?> clazz, QueryParam queryParam, PageUtil pageUtil);
/**
* 根据列名取数据列总和
* @param clazz
* @param colName
* @param queryParam
* @return
*/
public double getSum(Class<?> clazz, String colName, QueryParam queryParam);
/**
* 根据列名取该数据列平均值
* @param clazz
* @param colName
* @param queryParam
* @return
*/
public double getAvg(Class<?> clazz, String colName, QueryParam queryParam);
}
| true
|
a96cbaf2d44cc45b71cb1946afd04b161dfa5f03
|
Java
|
Great001/Intranet_Android
|
/app/src/main/java/com/xogrp/tkgz/fragment/PhotoWallFragment.java
|
UTF-8
| 6,270
| 1.96875
| 2
|
[] |
no_license
|
package com.xogrp.tkgz.fragment;
import android.app.Activity;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.Toast;
import com.xogrp.tkgz.R;
import com.xogrp.tkgz.TKGZApplication;
import com.xogrp.tkgz.View.AlphabetScrollBar;
import com.xogrp.tkgz.Widget.CirclePageIndicator;
import com.xogrp.tkgz.Widget.PhotoWallViewPagerAdapter;
import com.xogrp.tkgz.model.EmployeeProfile;
import com.xogrp.tkgz.provider.PhotoWallProvider;
import com.xogrp.tkgz.spi.PhotoWallApiCallBack;
import java.util.ArrayList;
import java.util.List;
/**
* Created by wlao on 12/23/2015.
*/
public class PhotoWallFragment extends AbstractTKGZFragment {
private static final int PHOTO_COUNT_PER_PAGE = 12;
private AlphabetScrollBar mVAlphabet;
private ViewPager mVpPhotoWall;
private CirclePageIndicator mVCirclePageIndicator;
private List<EmployeeProfile> mPhotoWallResponseList;
private PhotoWallViewPagerAdapter mPhotoAdapter;
private List<ArrayList<EmployeeProfile>> mPhotoWallProfileTotalList;
private int mPosition;
private ArrayList<AbstractTKGZFragment> mResultList;
@Override
protected int getLayoutResId() {
return R.layout.fragment_photo_wall_layout;
}
@Override
protected void onTKGZAttach(Activity activity) {
mResultList = new ArrayList<AbstractTKGZFragment>();
mPhotoAdapter = new PhotoWallViewPagerAdapter(getChildFragmentManager(), mResultList);
}
@Override
protected void onTKGZCreateView(View rootView) {
mVAlphabet = (AlphabetScrollBar) rootView.findViewById(R.id.v_alphabet);
mVpPhotoWall = (ViewPager) rootView.findViewById(R.id.vp_photo_wall);
mVpPhotoWall.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
@Override
public void onPageSelected(int position) {
mPosition = position;
refreshAlphabet(position);
}
});
mVAlphabet.setOnTouchBarListener(new AlphabetScrollBar.OnAlphabetScrollBarTouchListener() {
@Override
public void onTouch(String alphabet) {
refreshPhotoPage(alphabet);
refreshAlphabet(mPosition);
}
});
mVCirclePageIndicator = (CirclePageIndicator) rootView.findViewById(R.id.view_pager_photo_wall);
}
@Override
protected void onTKGZActivityCreated() {
mPhotoWallProfileTotalList = new ArrayList<>();
mVpPhotoWall.setAdapter(mPhotoAdapter);
showSpinner();
initLoader(PhotoWallProvider.getPhotoWallProvider(TKGZApplication.getInstance().getUserProfile(), this, new PhotoWallApiCallBack.OnPhotoWallApiCallBackListener() {
@Override
public void OnSuccess(List<EmployeeProfile> list) {
mPhotoWallResponseList = list;
int total = list.size();
int viewPageCount = total % PHOTO_COUNT_PER_PAGE == 0 ? total / PHOTO_COUNT_PER_PAGE : total / PHOTO_COUNT_PER_PAGE + 1;
for (int k = 0; k < viewPageCount; k++) {
mPhotoWallProfileTotalList.add(new ArrayList<EmployeeProfile>());
}
int pageNum = 0;
int size = total + 1;
for (int j = 1; j < size; j++) {
mPhotoWallProfileTotalList.get(pageNum).add(list.get(j - 1));
if (j % (PHOTO_COUNT_PER_PAGE) == 0 && pageNum < viewPageCount - 1) {
pageNum++;
}
}
for (int i = 0; i < viewPageCount; i++) {
mResultList.add(PhotoWallPageFragment.newInstance(mPhotoWallProfileTotalList.get(i)));
}
final Activity activity = getActivity();
if (activity != null) {
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
mPhotoAdapter.notifyDataSetChanged();
if (mPhotoAdapter.getIsAfterNotifyDataSetChanged()) {
mVCirclePageIndicator.setViewPager(mVpPhotoWall);
refreshAlphabet(0);
mPhotoAdapter.setAbleToDoNotifyDataSetChanged(false);
}
}
});
}
}
@Override
public void OnFailed() {
final Activity activity = getActivity();
if (activity != null) {
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(activity, getString(R.string.get_photowall_data_faild), Toast.LENGTH_LONG).show();
}
});
}
}
}));
}
@Override
public String getTransactionTag() {
return "photo_wall_fragment";
}
@Override
public boolean isHideActionBar() {
return false;
}
@Override
public String getActionBarTitle() {
return getString(R.string.actionbar_title_photo_wall_page);
}
public void refreshPhotoPage(String curPosIdx) {
if (mPhotoWallResponseList != null) {
int listSize = mPhotoWallResponseList.size();
for (int i = 0; i < listSize; i++) {
if (curPosIdx.equalsIgnoreCase(mPhotoWallResponseList.get(i).getMemberName().substring(0, 1))) {
mVpPhotoWall.setCurrentItem((i / PHOTO_COUNT_PER_PAGE));
break;
}
}
}
}
public void refreshAlphabet(int position) {
List<String> alphabetList = new ArrayList<>();
if (mPhotoWallProfileTotalList.size() > 0) {
int employeeSum = mPhotoWallProfileTotalList.get(position).size();
for (int i = 0; i < employeeSum; i++) {
alphabetList.add(mPhotoWallProfileTotalList.get(position).get(i).getMemberName().substring(0, 1));
}
mVAlphabet.setAlphabetFocus(alphabetList);
}
}
}
| true
|
caf546c486a4081acb6306ecc9482ab676d61582
|
Java
|
shimaomao/language
|
/java/disable/library/src/test/java/com/qunar/fresh/librarysystem/service/SystemServiceTest.java
|
UTF-8
| 4,683
| 1.992188
| 2
|
[] |
no_license
|
package com.qunar.fresh.librarysystem.service;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import com.qunar.fresh.librarysystem.dao.SystemServiceDao;
import com.qunar.fresh.librarysystem.model.SystemParam;
import com.qunar.fresh.librarysystem.service.impl.LogService;
import com.qunar.fresh.librarysystem.model.enums.OperationType;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.Date;
import java.util.Map;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* Created with IntelliJ IDEA.
* User: yingnan.zhang
* Date: 14-4-9
* Time: 下午12:51
* To change this template use File | Settings | File Templates.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:spring/*.xml", "classpath:extractor/*.xml"})
public class SystemServiceTest {
@Resource
private SystemService systemService;
private SystemServiceDao systemServiceDao;
private SystemParam systemParam, systemParamD;
private LogService logService;
@Before
public void beforeParameterParse() {
systemParam = new SystemParam();
systemParamD = new SystemParam();
systemParam.setBorrowPeriod(10);
systemParam.setBorrowTotalNum(5);
systemParam.setRedecorateNum(5);
systemParam.setRedecoratePeriod(10);
systemParam.setRemindDay(12);
systemParamD.setBorrowPeriod(10);
systemParamD.setBorrowTotalNum(2);
systemParamD.setRedecorateNum(6);
systemParamD.setRedecoratePeriod(10);
systemParamD.setRemindDay(12);
systemServiceDao = mock(SystemServiceDao.class);
}
@Test
@Ignore
public void test_ParameterParseNull() {
Map<String,Object> result = null;
when(systemServiceDao.fetchSystemCount(0)).thenReturn(1);
when(systemServiceDao.fetchSystemData(0)).thenReturn(systemParam);
systemService.setSystemParamDao(systemServiceDao);
result = systemService.parameterParse("10", "-5", "-6", "10", "12", 0, "yaya");
Assert.assertTrue(result.get("ret").equals(1) == false);
Assert.assertTrue(((Integer)result.get("browTotalNum")).equals(5));
Assert.assertTrue(((Integer)result.get("redecPeriod")).equals(10));
verify(systemServiceDao);
}
@Test
@Ignore
public void test_ParameterParseNotNull() {
Map<String,Object> result = null;
String differString;
Date date = new Date();
Timestamp NowDate = new Timestamp(date.getTime());
differString = systemService.differContext(systemParam, systemParamD);
when(systemServiceDao.fetchSystemCount(1)).thenReturn(1);
when(systemServiceDao.fetchSystemData(1)).thenReturn(systemParam);
when(systemServiceDao.updateSystemData(1, 2, 10, 10, 6, 12)).thenReturn(1);
systemService.setSystemParamDao(systemServiceDao);
result = systemService.parameterParse("10", "2", "10", "6", "12", 1, "yaya");
verify(systemServiceDao);
Assert.assertTrue(((Integer)result.get("browTotalNum")).equals(2));
Assert.assertTrue(((Integer)result.get("browPeriod")).equals(10));
Assert.assertTrue(((Integer)result.get("redecPeriod")).equals(10));
Assert.assertTrue(((Integer)result.get("redecCount")).equals(6));
Assert.assertTrue(((Integer)result.get("remindTime")).equals(12));
Assert.assertTrue((Boolean)result.get("ret") == true);
}
@Test
@Ignore
public void test_fetchAdminls() {
when(systemServiceDao.fetchAdminls("yaya")).thenReturn(null);
systemService.setSystemParamDao(systemServiceDao);
Assert.assertNull(systemService.fetchAdminls("yaya"));
verify(systemServiceDao);
}
@Test
@Ignore
public void test_getCheckOut() {
Assert.assertTrue(systemService.getCheckOut("", "", "", "", "") == false);
Assert.assertTrue(systemService.getCheckOut(null, null, null, null, null) == false);
Assert.assertTrue(systemService.getCheckOut("", "12", "", "", "") == true);
}
@Test
@Ignore
public void test_getBorrowPeriod() {
Integer libId = 12;
when(systemServiceDao.getBorrowPeriod(12)).thenReturn(null);
systemService.setSystemParamDao(systemServiceDao);
Assert.assertTrue(systemService.getBorrowPeriod(libId) == -1);
}
}
| true
|
90d815c234cb2468bdd3ce332e2ac90b286837e3
|
Java
|
simran191996/TSL756
|
/TSL756/src/testNg_Day4/TestSelenium.java
|
UTF-8
| 778
| 2.0625
| 2
|
[] |
no_license
|
package testNg_Day4;
import org.openqa.selenium.WebDriver;
import org.testng.annotations.Test;
import util.Base2;
public class TestSelenium extends Base2 {
@Test
public void LoginProcess() throws Exception {
Login login= new Login(driver);
driver.get("http://127.0.0.1:8080/htmldb");
login.LoginProcess("sys", "Newuser123");
System.out.println("login done");
}
@Test(dependsOnMethods="LoginProcess")
public void execute() throws Exception {
Sql_Command sql= new Sql_Command(driver);
SqlHome shome=new SqlHome(driver);
shome.startSql();
// sql.startSql();
Thread.sleep(1000);
sql.startsqlComm();
Thread.sleep(1000);
sql.executeCommand();
Thread.sleep(1000);
sql.logoutProcess();
Thread.sleep(1000);
}
}
| true
|
56f2925c731f6ed909c9d1629ad883a5c873d0b6
|
Java
|
hechuan73/train_ticket
|
/ts-travel-plan-service/src/main/java/travelplan/domain/GetRoutePlanInfo.java
|
UTF-8
| 1,200
| 2.453125
| 2
|
[] |
no_license
|
package travelplan.domain;
import java.util.Date;
public class GetRoutePlanInfo {
private String formStationName;
private String toStationName;
private Date travelDate;
private int num;
public GetRoutePlanInfo() {
//Empty Constructor
}
public GetRoutePlanInfo(String formStationName, String toStationName, Date travelDate, int num) {
this.formStationName = formStationName;
this.toStationName = toStationName;
this.travelDate = travelDate;
this.num = num;
}
public String getFormStationName() {
return formStationName;
}
public void setFormStationName(String formStationName) {
this.formStationName = formStationName;
}
public String getToStationName() {
return toStationName;
}
public void setToStationName(String toStationName) {
this.toStationName = toStationName;
}
public Date getTravelDate() {
return travelDate;
}
public void setTravelDate(Date travelDate) {
this.travelDate = travelDate;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
}
| true
|
b22b43f99601966e590bd5aa42a7b8a6383903c3
|
Java
|
huiyunfei/cultural
|
/src/main/java/com/yunfei/cultural/mapper/TCulturalSpecialistShMapper.java
|
UTF-8
| 485
| 1.726563
| 2
|
[] |
no_license
|
package com.yunfei.cultural.mapper;
import com.yunfei.cultural.entity.TCulturalSpecialistSh;
import com.yunfei.cultural.model.vo.CulturalSpecialistShResult;
import java.util.List;
import java.util.Map;
public interface TCulturalSpecialistShMapper {
void saveOrUpdateBitch(List<TCulturalSpecialistSh> culturalSpecialistShList);
List<CulturalSpecialistShResult> selectByParams(Map pramsMap);
CulturalSpecialistShResult selectById(Integer id);
Integer countAll();
}
| true
|
1cdd486b0af2dea675aee7ec47717f39b1e06891
|
Java
|
manogna5/JavaApplets
|
/SimpleRoll.java
|
UTF-8
| 3,516
| 2.921875
| 3
|
[] |
no_license
|
package sample;
import java.applet.*;
import java.awt.*;
import java.awt.image.*;
import java.io.*;
import SpinFilter;
public class SimpleRoll extends Applet
implements Runnable
{
private boolean init = false;
Image myImage = null;
Image allImages[] = null;
Thread animation = null;
MediaTracker tracker = null;
int roll_x = 0; // where to draw
boolean complete = false;
int current = 0;
/**
* Standard initialization method for an applet
*/
public void init()
{
if ( init == false )
{
init = true;
tracker = new MediaTracker(this);
allImages = new Image[4];
allImages[0] = getImage(getCodeBase(), "Samantha-Naga-Chaitanyas-Marriage-this-Year");
allImages[1] = getImage(getCodeBase(), "Samantha-Naga-Chaitanyas-Marriage-this-Year");
allImages[2] = getImage(getCodeBase(), "Samantha-Naga-Chaitanyas-Marriage-this-Year");
allImages[3] = getImage(getCodeBase(), "nagachaitanya-samantha-wedding2");
for ( int x = 0; x < 4; x++ )
tracker.addImage(allImages[x], x);
}
}
/**
* Standard paint routine for an applet.
* @param g contains the Graphics class to use for painting
*/
public void paint(Graphics g)
{
if ( complete )
{
g.drawImage(allImages[current], roll_x, 40, this);
}
else
{
g.drawString("Images not yet loaded", 0, 20);
}
}
public void start()
{
if ( animation == null )
{
animation = new Thread(this);
animation.start();
}
}
@SuppressWarnings("deprecation")
public void stop()
{
if ( animation != null )
{
animation.stop();
animation = null;
}
}
@SuppressWarnings("deprecation")
public void run()
{
while ( !checkRoll() ) sleep(250);
complete = true;
while (true)
{
roll(0, this.size().width-42); // roll left to right
roll(this.size().width-42, 0); // roll right to left
}
}
boolean checkRoll()
{
boolean finished = true;
for ( int i = 0; i < 4; i++ )
{
if ( (tracker.statusID(i, true) & MediaTracker.COMPLETE) == 0 )
finished = false;
}
return finished;
}
void roll(int begin, int end)
{
if ( begin < end )
{
for ( int x = begin; x <= end; x += 21 )
{
roll_x = x;
repaint();
current--;
if ( current == -1 ) current = 3;
sleep(150);
}
}
else
{
for ( int x = begin; x >= end; x -= 21 )
{
roll_x = x;
repaint();
current++;
if ( current == 4 ) current = 0;
sleep(150);
}
}
}
/**
* A simple sleep routine
* @param a the number of milliseconds to sleep
*/
private void sleep(int a)
{
try
{
Thread.currentThread().sleep(a);
}
catch (InterruptedException e)
{
}
}
}
| true
|
7ad73d9e7cd3b96a9eabbc3b9f4f3fe5ec8e30dc
|
Java
|
vuquangtin/designpattern
|
/java/src/designpatterns/apps/IT49-2015-DP/dialogs/DlgModifyingLine.java
|
UTF-8
| 8,494
| 2.8125
| 3
|
[
"MIT"
] |
permissive
|
package dialogs;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
public class DlgModifyingLine extends JDialog {
/**
*
*/
private static final long serialVersionUID = 1L;
private final JPanel contentPanel = new JPanel();
private JTextField txtMoveByX;
private JTextField txtMoveByY;
private boolean colorChanged = false;
public Color color = Color.BLACK;
public Color lineColor;
protected int x,y;
protected JButton btnColor;
protected boolean confirmed = false;
protected JTextField txtStartXY;
protected JTextField txtEndXY;
/**
* Launch the application.
*/
public static void main(String[] args) {
try {
DlgModifyingLine dialog = new DlgModifyingLine();
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Create the dialog.
*/
public DlgModifyingLine() {
setModal(true);
setTitle("Modify line");
setBounds(100, 100, 450, 300);
getContentPane().setLayout(new BorderLayout());
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
getContentPane().add(contentPanel, BorderLayout.CENTER);
contentPanel.setLayout(new BorderLayout(0, 0));
{
JPanel pnlCentar = new JPanel();
contentPanel.add(pnlCentar);
GridBagLayout gbl_pnlCentar = new GridBagLayout();
gbl_pnlCentar.columnWidths = new int[]{0, 0, 0, 0, 0};
gbl_pnlCentar.rowHeights = new int[]{0, 0, 0, 0, 0, 0, 0, 0};
gbl_pnlCentar.columnWeights = new double[]{0.0, 0.0, 0.0, 1.0, Double.MIN_VALUE};
gbl_pnlCentar.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
pnlCentar.setLayout(gbl_pnlCentar);
{
JLabel lblColorChooser = new JLabel("Pick a color:");
GridBagConstraints gbc_lblColorChooser = new GridBagConstraints();
gbc_lblColorChooser.insets = new Insets(0, 0, 5, 5);
gbc_lblColorChooser.gridx = 0;
gbc_lblColorChooser.gridy = 0;
pnlCentar.add(lblColorChooser, gbc_lblColorChooser);
}
{
btnColor = new JButton("Color");
btnColor.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
colorChanged = true;
btnColor.setBackground(colorChoosing(btnColor.getBackground()));
color = btnColor.getBackground();
}
});
GridBagConstraints gbc_btnColor = new GridBagConstraints();
gbc_btnColor.insets = new Insets(0, 0, 5, 0);
gbc_btnColor.gridx = 3;
gbc_btnColor.gridy = 0;
pnlCentar.add(btnColor, gbc_btnColor);
}
{
JLabel lblStartXY = new JLabel("Line's starting point's X,Y coordinates:");
GridBagConstraints gbc_lblStartXY = new GridBagConstraints();
gbc_lblStartXY.insets = new Insets(0, 0, 5, 5);
gbc_lblStartXY.gridx = 0;
gbc_lblStartXY.gridy = 1;
pnlCentar.add(lblStartXY, gbc_lblStartXY);
}
{
txtStartXY = new JTextField();
txtStartXY.setEditable(false);
GridBagConstraints gbc_txtStartXY = new GridBagConstraints();
gbc_txtStartXY.insets = new Insets(0, 0, 5, 0);
gbc_txtStartXY.fill = GridBagConstraints.HORIZONTAL;
gbc_txtStartXY.gridx = 3;
gbc_txtStartXY.gridy = 1;
pnlCentar.add(txtStartXY, gbc_txtStartXY);
txtStartXY.setColumns(10);
}
{
JLabel lblEndXY = new JLabel("Line's ending point's X,Y coordinates:");
GridBagConstraints gbc_lblEndXY = new GridBagConstraints();
gbc_lblEndXY.insets = new Insets(0, 0, 5, 5);
gbc_lblEndXY.gridx = 0;
gbc_lblEndXY.gridy = 2;
pnlCentar.add(lblEndXY, gbc_lblEndXY);
}
{
txtEndXY = new JTextField();
txtEndXY.setEditable(false);
GridBagConstraints gbc_txtEndXY = new GridBagConstraints();
gbc_txtEndXY.insets = new Insets(0, 0, 5, 0);
gbc_txtEndXY.fill = GridBagConstraints.HORIZONTAL;
gbc_txtEndXY.gridx = 3;
gbc_txtEndXY.gridy = 2;
pnlCentar.add(txtEndXY, gbc_txtEndXY);
txtEndXY.setColumns(10);
}
{
JLabel lblMoveByX = new JLabel("Move line's X coordinates by:");
GridBagConstraints gbc_lblMoveByX = new GridBagConstraints();
gbc_lblMoveByX.insets = new Insets(0, 0, 5, 5);
gbc_lblMoveByX.gridx = 0;
gbc_lblMoveByX.gridy = 5;
pnlCentar.add(lblMoveByX, gbc_lblMoveByX);
}
{
txtMoveByX = new JTextField();
GridBagConstraints gbc_txtMoveByX = new GridBagConstraints();
gbc_txtMoveByX.insets = new Insets(0, 0, 5, 0);
gbc_txtMoveByX.fill = GridBagConstraints.HORIZONTAL;
gbc_txtMoveByX.gridx = 3;
gbc_txtMoveByX.gridy = 5;
pnlCentar.add(txtMoveByX, gbc_txtMoveByX);
txtMoveByX.setColumns(10);
}
{
JLabel lblMoveByY = new JLabel("Move line's Y coordinates by:");
GridBagConstraints gbc_lblMoveByY = new GridBagConstraints();
gbc_lblMoveByY.insets = new Insets(0, 0, 0, 5);
gbc_lblMoveByY.gridx = 0;
gbc_lblMoveByY.gridy = 6;
pnlCentar.add(lblMoveByY, gbc_lblMoveByY);
}
{
txtMoveByY = new JTextField();
GridBagConstraints gbc_txtMoveByY = new GridBagConstraints();
gbc_txtMoveByY.fill = GridBagConstraints.HORIZONTAL;
gbc_txtMoveByY.gridx = 3;
gbc_txtMoveByY.gridy = 6;
pnlCentar.add(txtMoveByY, gbc_txtMoveByY);
txtMoveByY.setColumns(10);
}
}
{
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
getContentPane().add(buttonPane, BorderLayout.SOUTH);
{
JButton btnConfirm = new JButton("Confirm");
btnConfirm.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try{
confirmed = true;
if(colorChanged)
lineColor = color;
if(!txtMoveByX.getText().equals("") && !txtMoveByY.getText().equals(""))
{
x = Integer.parseInt(txtMoveByX.getText());
y = Integer.parseInt(txtMoveByY.getText());
setVisible(false);
} else throw new NumberFormatException();
}
catch(NumberFormatException c){
JOptionPane.showMessageDialog(null, "You have to enter numbers.", "Error", JOptionPane.ERROR_MESSAGE);
}
}
});
btnConfirm.setActionCommand("OK");
buttonPane.add(btnConfirm);
getRootPane().setDefaultButton(btnConfirm);
}
{
JButton btnCancel = new JButton("Cancel");
btnCancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
confirmed = false;
dispose();
}
});
btnCancel.setActionCommand("Cancel");
buttonPane.add(btnCancel);
}
}
}
public Color colorChoosing(Color Color)
{
Color newColor = JColorChooser.showDialog(null, "Pick a color:", Color);
if(newColor == null)
return Color;
else
return newColor;
}
public Color getLineColor() {
return lineColor;
}
public void setLineColor(Color lineColor) {
this.lineColor = lineColor;
}
public JTextField getTxtMoveByX() {
return txtMoveByX;
}
public void setTxtMoveByX(JTextField txtMoveByX) {
this.txtMoveByX = txtMoveByX;
}
public JTextField getTxtMoveByY() {
return txtMoveByY;
}
public void setTxtMoveByY(JTextField txtMoveByY) {
this.txtMoveByY = txtMoveByY;
}
public boolean isColorChanged() {
return colorChanged;
}
public void setColorChanged(boolean colorChanged) {
this.colorChanged = colorChanged;
}
public Color getColor() {
return color;
}
public void setColor(Color color) {
this.color = color;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public JButton getBtnColor() {
return btnColor;
}
public void setBtnColor(JButton btnColor) {
this.btnColor = btnColor;
}
public boolean isConfirmed() {
return confirmed;
}
public void setConfirmed(boolean confirmed) {
this.confirmed = confirmed;
}
public JTextField getTxtStartXY() {
return txtStartXY;
}
public void setTxtStartXY(JTextField txtStartXY) {
this.txtStartXY = txtStartXY;
}
public JTextField getTxtEndXY() {
return txtEndXY;
}
public void setTxtEndXY(JTextField txtEndXY) {
this.txtEndXY = txtEndXY;
}
}
| true
|
fe249694c81807e59898e4ea3e26ebef31c24e42
|
Java
|
xuyixuanwhut/Hadoop-Naive-Bayes
|
/src/main/java/org/xuchenlian/project/bank/NumClassifierReducer.java
|
UTF-8
| 1,110
| 2.65625
| 3
|
[] |
no_license
|
package org.xuchenlian.project.bank;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.hadoop.io.DoubleWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;
public class NumClassifierReducer extends Reducer<Text, DoubleWritable, Text, Text> {
StringBuilder doublePair = new StringBuilder();
List<Double> l = new ArrayList<Double>();
public void reduce(Text key, Iterable<DoubleWritable> values, Context context)
throws IOException, InterruptedException {
double total = 0;
int count = 0;
l.clear();
StringBuilder doublePair = new StringBuilder();
for (DoubleWritable value : values) {
l.add(value.get());
count += 1;
total += value.get();
}
double ave = total / count;
Iterator<Double> itr = l.iterator();
double sum = 0;
while (itr.hasNext()) {
double val = itr.next();
sum += Math.pow((val - ave), 2);
}
double var = Math.sqrt(sum /count);
doublePair.append(ave).append("\t").append(var);
context.write(key, new Text(doublePair.toString()));
}
}
| true
|
726921e82ffded7819ccdebd09995d76aebd4fcc
|
Java
|
myevas/myinterview
|
/src/test/java/helpers/GetProperties.java
|
UTF-8
| 1,153
| 3
| 3
|
[] |
no_license
|
package helpers;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.Set;
public class GetProperties {
private final Properties configProp = new Properties();
private GetProperties()
{
//Private constructor to restrict new instances
InputStream in = this.getClass().getClassLoader().getResourceAsStream("config.properties");
System.out.println("Read all properties from file");
try {
configProp.load(in);
} catch (IOException e) {
e.printStackTrace();
}
}
//Bill Pugh Solution for singleton pattern
private static class LazyHolder
{
private static final GetProperties INSTANCE = new GetProperties();
}
public static GetProperties getInstance()
{
return LazyHolder.INSTANCE;
}
public String getProperty(String key){
return configProp.getProperty(key);
}
public Set<String> getAllPropertyNames(){
return configProp.stringPropertyNames();
}
public boolean containsKey(String key){
return configProp.containsKey(key);
}
}
| true
|
33ce3076a94c069abe777c8c8f99250820649ae9
|
Java
|
amanmishra086/competitive-programming
|
/collection/src/collection/MyArrayList.java
|
UTF-8
| 2,018
| 3.21875
| 3
|
[] |
no_license
|
package collection;
import java.util.*;
public class MyArrayList {
public static void main(String[] args) {
// Pair< String , Integer> p1=new Pair("Aman",067);
// Pair< Boolean , Integer> p2=new Pair(true,067);
ArrayList<String> arraylist=new ArrayList<>();
LinkedList<String> linklist=new LinkedList<>();
arraylist.add("aman");
arraylist.add("ashu");
linklist.add("hello");
linklist.add("world");
arraylist.addAll(linklist);
//ArrayList<String>
arraylist.remove("world");// or we can remove using index also.
// System.out.println(arraylist.get(2));
arraylist.set(2, "hh");
arraylist.add(2, "mishra");
//arraylist.clear();
//Object x[]=arraylist.toArray();
String temp[]=new String[arraylist.size()];
arraylist.toArray(temp);
for(String s: temp) {
System.out.println(s);
}
int[] scores= {100,90,90,80,75,60};
int[] alice= {50,65,65,77,90,102};
System.out.println(Arrays.binarySearch(alice, 65));
int rank[]=new int[alice.length];
Set<Integer> set=new LinkedHashSet<>();
for(int i=0;i<scores.length;i++){
set.add(scores[i]);
}
ArrayList<Integer> alist=new ArrayList<>(set);
// System.out.println(alist);
Boolean get=false;
for(int i=0;i<alice.length;i++){
int marks=alice[i];
for(int j=0;j<alist.size();j++){
if(marks>=alist.get(j)){
rank[i]=j+1;
get = true;
break;
}
if(!get) {
rank[i]=alice.length+1;
}
}
}
for(int i=0;i<rank.length;i++) {
System.out.print(rank[i]+" ");
}
// System.out.println(set);
//System.out.println(arraylist.size());
// System.out.println(arraylist);
//System.out.println(x);
}
}
| true
|
48d97d1f5cee261db60d5d4af514083992cf7dcb
|
Java
|
eray-onur/kres-otomasyonu
|
/src/meltem/controllers/AdminClassroomInfoController.java
|
UTF-8
| 9,018
| 2.390625
| 2
|
[] |
no_license
|
package meltem.controllers;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.layout.StackPane;
import javafx.scene.text.Text;
import meltem.models.*;
import meltem.services.SceneBuilder;
import meltem.services.data_access.concrete.ClassroomAttendanceRepository;
import meltem.services.data_access.concrete.ClassroomCourseRepository;
import meltem.services.data_access.concrete.ClassroomRepository;
import meltem.services.data_access.concrete.StudentRepository;
import meltem.services.logging.Logger;
import meltem.view_models.ClassroomViewModel;
import meltem.view_models.CourseViewModel;
import meltem.view_models.StudentViewModel;
import meltem.view_models.UserViewModel;
import java.io.IOException;
import java.net.URL;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
public class AdminClassroomInfoController implements Initializable {
public static int CourseId = -1;
public static int ClassroomId = -1;
public static String ClassroomTeacherFullName = "";
public static Classroom classroom;
public Student selectedStudent;
@FXML
public Button btnShowStudents;
@FXML
public Button btnShowCourses;
@FXML
public Button btnUpdateStudent;
@FXML
public Button btnUpdateCourse;
@FXML
public StackPane showStack;
@FXML
public TableView<StudentViewModel> tableStudents;
@FXML
public TableView<CourseViewModel> tableCourses;
@FXML
public Text txtClassroomId;
@FXML
public Text txtClassroomName;
@FXML
public Text txtClassroomCapacity;
@FXML
public Text txtClassroomTeacherName;
@FXML
public TableColumn<CourseViewModel, SimpleIntegerProperty> colCourseId;
@FXML
public TableColumn<CourseViewModel, SimpleStringProperty> colCourseName;
@FXML
public TableColumn<CourseViewModel, SimpleStringProperty> colTeacherName;
@FXML
public TableColumn<CourseViewModel, SimpleStringProperty> colTeacherLastName;
@FXML
public TableColumn<CourseViewModel, SimpleStringProperty> colTeacherPhone;
public ObservableList<CourseViewModel> courseTable;
public ArrayList<CourseViewModel> courseList = new ArrayList<>();
private List<Course> courseModels = new ArrayList<>();
//
@FXML
public TableColumn<StudentViewModel, SimpleIntegerProperty> colStudentId;
@FXML
public TableColumn<StudentViewModel, SimpleStringProperty> colStudentName;
@FXML
public TableColumn<StudentViewModel, SimpleStringProperty> colStudentLastName;
@FXML
public TableColumn<StudentViewModel, SimpleStringProperty> colParentPhone;
public ObservableList<StudentViewModel> studentTable;
public ArrayList<StudentViewModel> studentList = new ArrayList<>();
private List<Student> studentModels = new ArrayList<>();
@Override
public void initialize(URL url, ResourceBundle resourceBundle) {
try {
//Classroom classroom = ClassroomRepository.Instance.fetchById(ClassroomId);
Logger.LogDebug(ClassroomId + " ID IN CLASSROOM INFO CONTROLLER!");
if(txtClassroomId != null) {
txtClassroomId.setText(String.valueOf(classroom.getClassroomId()));
}
txtClassroomName.setText(classroom.getClassroomName());
txtClassroomCapacity.setText(String.valueOf(classroom.getClassroomCapacity()));
txtClassroomTeacherName.setText(classroom.getClassroomTeacherName() + " " + classroom.getClassroomTeacherLastName());
tableCourses.setOnMouseClicked(v -> getCourseViewModel());
tableStudents.setOnMouseClicked(v -> getStudentViewModel());
colCourseId.setCellValueFactory(
course -> course.getValue().courseId
);
colCourseName.setCellValueFactory(
course -> course.getValue().courseName
);
colTeacherName.setCellValueFactory(
course -> course.getValue().teacherName
);
colTeacherLastName.setCellValueFactory(
course -> course.getValue().teacherLastName
);
colTeacherPhone.setCellValueFactory(
course -> course.getValue().teacherPhone
);
studentModels = ClassroomAttendanceRepository.Instance.fetchAll(ClassroomId);
studentTable = FXCollections.observableArrayList(
fetchAllModelsForStudents()
);
tableStudents.setItems(studentTable);
tableStudents.setFixedCellSize(50);
colStudentId.setCellValueFactory(
course -> course.getValue().studentId
);
colStudentName.setCellValueFactory(
course -> course.getValue().studentName
);
colStudentLastName.setCellValueFactory(
course -> course.getValue().studentLastName
);
colParentPhone.setCellValueFactory(
course -> course.getValue().parentNumber
);
courseModels = ClassroomCourseRepository.Instance.fetchAll();
courseTable = FXCollections.observableArrayList(
fetchAllModels()
);
tableCourses.setItems(courseTable);
tableCourses.setFixedCellSize(50);
} catch (SQLException e) {
e.printStackTrace();
}
}
private void getCourseViewModel() {
if(tableCourses.getSelectionModel().getSelectedItem() != null) {
btnUpdateCourse.setDisable(false);
AdminClassroomInfoController.ClassroomId = tableCourses.getSelectionModel().getSelectedItem().course.getClassroomCourseId();
ClassroomCourseEditController.courseToEdit = tableCourses.getSelectionModel().getSelectedItem().course;
Logger.LogDebug(String.valueOf(AdminClassroomInfoController.ClassroomId + " IS THE STATIC ID!"));
}
}
private void getStudentViewModel() {
if(tableStudents.getSelectionModel().getSelectedItem() != null) {
btnUpdateStudent.setDisable(false);
selectedStudent = tableStudents.getSelectionModel().getSelectedItem().student;
Logger.LogDebug(selectedStudent.getParentNumber());
}
}
public ArrayList<CourseViewModel> fetchAllModels() {
for (Course course: courseModels) {
courseList.add(new CourseViewModel(course));
}
return courseList;
}
public ArrayList<StudentViewModel> fetchAllModelsForStudents() {
for (Student student: studentModels) {
studentList.add(new StudentViewModel(student));
}
return studentList;
}
public void goBack() throws IOException {
SceneBuilder.Instance.BuildScene("classroom_list");
}
public void update() throws IOException {
SceneBuilder.Instance.BuildScene("classroom_edit", new RouteData(1, "user"));
}
public void delete() throws IOException {
Logger.LogDebug("DELETE!");
SceneBuilder.Instance.BuildScene("classroom_list");
}
public void goClassroomCourseEdit(ActionEvent event) {
StudentEditController.route = 1;
SceneBuilder.Instance.BuildScene("classroom_course_edit");
}
public void goClassroomCourseNew(ActionEvent event) {
SceneBuilder.Instance.BuildScene("classroom_course_new");
}
public void goBackToClassroomAdmin(ActionEvent event) {
SceneBuilder.Instance.BuildScene("attendance_classroom_admin");
}
public void showAttendanceModal(ActionEvent event) {
SceneBuilder.Instance.BuildWarningModal("modal_classroom_courses", "", event);
}
public void changeStackToStudents(ActionEvent event) {
tableCourses.setVisible(false);
tableStudents.setVisible(true);
}
public void changeStackToCourses(ActionEvent event) {
tableStudents.setVisible(false);
tableCourses.setVisible(true);
}
public void goClassroomStudentNew(ActionEvent event) {
StudentNewController.ClassroomId = Integer.parseInt(txtClassroomId.getText());
StudentNewController.route = 1;
SceneBuilder.Instance.BuildScene("student_new_classroom");
}
public void goClassroomStudentEdit(ActionEvent event) {
StudentEditController.StudentId = selectedStudent.getStudentId();
StudentEditController.route = 1;
SceneBuilder.Instance.BuildScene("student_edit_classroom");
}
}
| true
|
520f3ac57cf6780046243d9b7202fc413c927be3
|
Java
|
tux1224/BakingApp2
|
/app/src/main/java/com/example/salvadorelizarraras/bakingapp/FragmentsStepDetailView.java
|
UTF-8
| 10,955
| 1.773438
| 2
|
[] |
no_license
|
package com.example.salvadorelizarraras.bakingapp;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.media.session.MediaSessionCompat;
import android.support.v4.media.session.PlaybackStateCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.salvadorelizarraras.bakingapp.Recipe.Steps;
import com.google.android.exoplayer2.DefaultLoadControl;
import com.google.android.exoplayer2.ExoPlaybackException;
import com.google.android.exoplayer2.ExoPlayer;
import com.google.android.exoplayer2.ExoPlayerFactory;
import com.google.android.exoplayer2.LoadControl;
import com.google.android.exoplayer2.SimpleExoPlayer;
import com.google.android.exoplayer2.Timeline;
import com.google.android.exoplayer2.extractor.DefaultExtractorsFactory;
import com.google.android.exoplayer2.source.ExtractorMediaSource;
import com.google.android.exoplayer2.source.MediaSource;
import com.google.android.exoplayer2.source.TrackGroupArray;
import com.google.android.exoplayer2.trackselection.AdaptiveVideoTrackSelection;
import com.google.android.exoplayer2.trackselection.DefaultTrackSelector;
import com.google.android.exoplayer2.trackselection.TrackSelectionArray;
import com.google.android.exoplayer2.trackselection.TrackSelector;
import com.google.android.exoplayer2.ui.SimpleExoPlayerView;
import com.google.android.exoplayer2.upstream.BandwidthMeter;
import com.google.android.exoplayer2.upstream.DefaultBandwidthMeter;
import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory;
import com.google.android.exoplayer2.util.Util;
import java.util.ArrayList;
/**
* Created by Salvador Elizarraras on 11/03/2018.
*/
public class FragmentsStepDetailView extends Fragment implements ExoPlayer.EventListener, View.OnClickListener{
private SimpleExoPlayer mExoPlayer;
public final static String TAG = FragmentsStepDetailView.class.getSimpleName();
private PlaybackStateCompat.Builder mStateBuilder;
private long mPreviousPosition;
private final String SESION = "remaining_video";
Steps mStep;
private Bundle mArguments;
ArrayList<Steps> mSteps;
TextView tvDescription;
private int mPosition;
ImageView left;
ImageView right;
SimpleExoPlayerView mPlayerView;
FragmentManager fragmentManager;
private Uri uriView;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
Log.d(TAG, "onCreateView: ");
View view = inflater.inflate(R.layout.fragment_step_detail_view,container,false);
tvDescription = (TextView) view.findViewById(R.id.tv_description);
left = (ImageView) view.findViewById(R.id.left);
right = (ImageView) view.findViewById(R.id.right);
mPlayerView = (SimpleExoPlayerView) view.findViewById(R.id.player_view);
left.setOnClickListener(this);
right.setOnClickListener(this);
if(getArguments() != null && getArguments().containsKey("steps")) {
Log.d(TAG, "onCreateView: + Arguments" );
mArguments = getArguments();
mPosition = mArguments.getInt("position");
mSteps = mArguments.getParcelableArrayList("steps");
mStep = mSteps.get(mPosition);
uriView = Uri.parse(mStep.getVideoURL());
tvDescription.setText(mStep.getDescription());
Log.d(TAG, "onCreateView: "+uriView);
}
if (savedInstanceState!= null) {
Log.d(TAG, "onCreateView: ");
mPreviousPosition = (savedInstanceState.getLong(SESION, 0));
mPosition = savedInstanceState.getInt("position");
mSteps = savedInstanceState.getParcelableArrayList("steps");
mStep = mSteps.get(mPosition);
uriView = Uri.parse(mStep.getVideoURL());
tvDescription.setText(mStep.getDescription());
}
return view;
}
private void initializePlayer(Uri mediaUri) {
if (mExoPlayer == null) {
// Create an instance of the ExoPlayer.
BandwidthMeter bandwidthMeter = new DefaultBandwidthMeter();
TrackSelector trackSelector = new DefaultTrackSelector(new AdaptiveVideoTrackSelection.Factory(bandwidthMeter));
LoadControl loadControl = new DefaultLoadControl();
mExoPlayer = ExoPlayerFactory.newSimpleInstance(getActivity().getApplicationContext(), trackSelector, loadControl);
mPlayerView.setPlayer(mExoPlayer);
if(mediaUri.toString().isEmpty()) {
Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
R.drawable.novideo);
mPlayerView.setDefaultArtwork(bitmap);
mPlayerView.setUseController(false);
}else {
// Set the ExoPlayer.EventListener to this activity.
mExoPlayer.addListener(this);
// Prepare the MediaSource.
mExoPlayer.seekTo(mPreviousPosition);
String userAgent = Util.getUserAgent(getContext(), "BakingApp2");
MediaSource mediaSource = new ExtractorMediaSource(mediaUri, new DefaultDataSourceFactory(
getContext(), userAgent), new DefaultExtractorsFactory(), null, null);
mExoPlayer.prepare(mediaSource);
mExoPlayer.setPlayWhenReady(true);
}
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
Log.d(TAG, "onSaveInstanceState: "+ mExoPlayer.getCurrentPosition());
outState.putLong(SESION, mExoPlayer.getCurrentPosition());
outState.putParcelableArrayList("steps",mSteps);
outState.putInt("position",mPosition);
super.onSaveInstanceState(outState);
}
@Override
public void onViewStateRestored(@Nullable Bundle savedInstanceState) {
super.onViewStateRestored(savedInstanceState);
Log.d(TAG, "onViewStateRestored: ");
}
//#region lifeCycle
@Override
public void onStart() {
super.onStart();
initializePlayer(uriView);
if(getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT)
updateData();
Log.d(TAG, "onStart: " + uriView);
}
@Override
public void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
public void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
public void onStop() {
super.onStop();
saveMyPosition();
releasePlayer();
Log.d(TAG, "onStop: ");
}
@Override
public void onDestroyView() {
super.onDestroyView();
Log.d(TAG, "onDestroyView: ");
}
@Override
public void onDestroy() {
Log.d(TAG, "onDestroy: ");
super.onDestroy();
try {
if (!Utils.isTablet(getContext()) && getResources().getConfiguration().orientation != Configuration.ORIENTATION_PORTRAIT)
getFragmentManager().beginTransaction().remove(this).commit();
}catch (IllegalStateException e){
}
}
@Override
public void onDetach() {
super.onDetach();
Log.d(TAG, "onDetach: ");
}
//#endregion
private void updateData(){
Log.d(TAG, mPosition+"updateData: "+mSteps.size());
if (mPosition <= 0){
left.setVisibility(View.INVISIBLE);
right.setVisibility(View.VISIBLE);
}else if(mPosition >= mSteps.size()-1){
right.setVisibility(View.INVISIBLE);
left.setVisibility(View.VISIBLE);
}
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.left:
if(mPosition > 0) {
mPosition = mPosition - 1;
restartFragment( mPosition, mArguments);
}
break;
case R.id.right:
if (mPosition < mSteps.size()-1) {
mPosition = mPosition + 1;
restartFragment( mPosition, mArguments);
}
break;
}
}
public void restartFragment(int mPosition, Bundle arg) {
Fragment fragmentItself = new FragmentsStepDetailView();
Bundle bundle = new Bundle();
bundle.putInt("position",mPosition);
bundle.putParcelableArrayList("steps", mSteps);
fragmentItself.setArguments(bundle);
getFragmentManager().popBackStack();
getFragmentManager().beginTransaction().replace(R.id.main_container, fragmentItself).addToBackStack(FragmentsStepDetailView.TAG).commit();
}
private void releasePlayer() {
if (mExoPlayer != null) {
mExoPlayer.stop();
mExoPlayer.release();
}
mExoPlayer = null;
}
//#region callbacks
@Override
public void onTimelineChanged(Timeline timeline, Object manifest) {
}
@Override
public void onTracksChanged(TrackGroupArray trackGroups, TrackSelectionArray trackSelections) {
}
@Override
public void onLoadingChanged(boolean isLoading) {
}
@Override
public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
}
@Override
public void onPlayerError(ExoPlaybackException error) {
}
@Override
public void onPositionDiscontinuity() {
}
private class MySessionCallback extends MediaSessionCompat.Callback {
@Override
public void onPlay() {
mExoPlayer.setPlayWhenReady(true);
}
@Override
public void onPause() {
mExoPlayer.setPlayWhenReady(false);
}
@Override
public void onSkipToPrevious() {
mExoPlayer.seekTo(0);
}
}
//#endregion
private void saveMyPosition(){
if(mExoPlayer != null){
mPreviousPosition = mExoPlayer.getCurrentPosition();
}
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
Log.d(TAG, "onConfigurationChanged: ");
}
}
| true
|
08587550a5aff87cfa8327b20ba0f30399655024
|
Java
|
cybernhl/MvpCase
|
/app/src/main/java/com/tamic/mvp/sample/bisiness/api/LoginApi.java
|
UTF-8
| 1,080
| 2.34375
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.tamic.mvp.sample.bisiness.api;
import com.tamic.mvp.sample.base.api.Api;
import com.tamic.mvp.sample.bisiness.UserBean;
import java.util.Map;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Headers;
import retrofit2.http.QueryMap;
/**
* Created by Tamic on 2017-12-28.
*/
public class LoginApi<T> extends Api {
/**
* A dummy authentication store containing known user names and passwords.
* TODO: remove after connecting to a real authentication system.
*/
private static final String[] DUMMY_CREDENTIALS = new String[] {
"foo@example.com:hello", "bar@example.com:world"
};
@Override
public Call<UserBean> getData(Map maps) {
return create(LoginApiService.class).login(maps);
}
public interface LoginApiService {
/**
* http://ip.taobao.com/service/getIpInfo.php?ip=21.22.11.33
*/
@GET("service/getIpInfo.php")
@Headers( {"Accept: application/json"})
Call<UserBean> login(
@QueryMap Map<String, String> maps);
}
}
| true
|
9c4e76377654684d95c13e3b676345e7f8b0becd
|
Java
|
syte-ai/Android-SDK
|
/app/src/main/java/com/syte/ai/android_sdk/app/fragments/WildImageSearchFragment.java
|
UTF-8
| 3,320
| 1.882813
| 2
|
[] |
no_license
|
package com.syte.ai.android_sdk.app.fragments;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import com.syte.ai.android_sdk.app.R;
import com.syte.ai.android_sdk.app.common.BaseFragment;
import com.syte.ai.android_sdk.data.ImageSearch;
import org.jetbrains.annotations.NotNull;
import static android.app.Activity.RESULT_OK;
public class WildImageSearchFragment extends BaseFragment implements View.OnClickListener {
private static final int RESULT_LOAD_IMG = 20002;
private Button mGetBoundsSyncButton;
private Button mLoadImageButton;
private CheckBox mFetchOffersForTheFirstBoundCheckBox;
private Uri mSelectedImageUri = null;
@Override
public View onCreateView(@NotNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_wild_image_search, container, false);
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mGetBoundsSyncButton = view.findViewById(R.id.bounds_btn);
mLoadImageButton = view.findViewById(R.id.load_image_btn);
mFetchOffersForTheFirstBoundCheckBox = view.findViewById(R.id.fetch_offers_for_the_first_bound);
initViews();
}
private void initViews() {
mGetBoundsSyncButton.setOnClickListener(this);
mLoadImageButton.setOnClickListener(this);
mFetchOffersForTheFirstBoundCheckBox.setChecked(true);
}
@Override
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK) {
mSelectedImageUri = data.getData();
}
}
@Override
public void onClick(View v) {
ImageSearch requestData = new ImageSearch(mSelectedImageUri);
requestData.setRetrieveItemsForTheFirstBound(mFetchOffersForTheFirstBoundCheckBox.isChecked());
if (!mSyteManager.getViewedProducts().isEmpty()) {
requestData.setPersonalizedRanking(true);
}
switch (v.getId()) {
case R.id.load_image_btn:
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, RESULT_LOAD_IMG);
break;
case R.id.bounds_btn:
mSyteManager.wildImageSearch(
requestData,
syteResult -> {
if (syteResult.isSuccessful) {
mSyteManager.setLastRetrievedBoundsList(
syteResult.data.getBounds()
);
mNavigator.boundsFragment();
}
}
);
break;
}
}
}
| true
|
39213f79027b2ad09b717de6e77a82160727257e
|
Java
|
cdvcristiann/java-informatorio
|
/Actividades del informatorio/Ejercicios/ejercicio3.java
|
UTF-8
| 992
| 3.515625
| 4
|
[] |
no_license
|
package Ejercicios;
import java.util.Scanner;
public class ejercicio3{
public static void main(String[] args){
Scanner entradasdenotas = new Scanner(System.in);
System.out.println("Ingrese la nota del alumno: ");
int notas = entradasdenotas.nextInt();
if(notas>=93 && notas<=100){
System.out.println("Excelente");
}else{
if(notas>=85 && notas < 93){
System.out.println("Sobresaliente");
}else{
if(notas>=75 && notas < 85){
System.out.println("Distingido");
}else{
if(notas>=60 && notas < 75){
System.out.println("bueno");
}else{
if(notas>0 && notas< 60){
System.out.println("Desaprobado");
}else{
System.out.println("el dato ingresado no es valido");
}
}
}
}
}entradasdenotas.close();
}
}
| true
|
e711d68c26c12e6a408f623ff4c19b0552c06cb2
|
Java
|
Kevi0128/JavaDesignPatterns
|
/src/main/java/cn/kevi/study/design/create/FactoryMetohd/multi/impl/NSGame.java
|
UTF-8
| 266
| 2.125
| 2
|
[] |
no_license
|
package cn.kevi.study.design.create.FactoryMetohd.multi.impl;
import cn.kevi.study.design.create.FactoryMetohd.multi.interface_.Game;
public class NSGame implements Game {
@Override
public void play() {
System.out.println("play NS game");
}
}
| true
|
35c39bb308007e0972675b28a206705671d919d9
|
Java
|
zhongxingyu/Seer
|
/Diff-Raw-Data/32/32_4237682b42ccb16d41e22617403a089733eb1959/Goomba/32_4237682b42ccb16d41e22617403a089733eb1959_Goomba_t.java
|
UTF-8
| 2,665
| 2.734375
| 3
|
[] |
no_license
|
package characters;
import java.util.Random;
import map.DungeonCollision;
import core.Board;
import core.FileLink;
import core.GameManager;
public class Goomba extends AbstractEnemy implements Runnable, FileLink {
private static Player player;
private static DungeonCollision dungeonCollision;
public Goomba(){
initializeEnemy(FileLink.goomba, 400, 200, 65, 75, 1, 0, true, true, 0, 3);
//public AbstractEnemy(File sprite, int x, int y, int height, int width, int speed, int life, boolean hostile, boolean dungeon, int xMap, int yMap)
System.out.println("add goomba");
}
public Goomba(Player player, DungeonCollision dungeonCollision){
this.player = player;
this.dungeonCollision = dungeonCollision;
setPlayerObject(this.player);
setDungeonCollisionObject(this.dungeonCollision);
}
public void run(){
Random randomBoolean = new Random();
randomBoolean.nextBoolean();
if (GameManager.printMsg)
System.out.println("Enemy.run");
if(life > 0){
setBoundMain();
setBoundS();
followPlayer();
move();
paintEnemy();
if(oldLife < life){
oldLife = life;
}
}
if(life <= 0){
x = -100;
y = -100;
}
}
private void followPlayer(){
if(GameManager.printMsg)
System.out.println("goomba:"+x+" to "+ player.getX());
if(x > player.getX()){
moveRight = false;
moveLeft = true;
lastDirection = 2;
}
if(x < player.getX()){
moveLeft = false;
moveRight = true;
lastDirection = 6;
}
System.out.println("goomba:"+y+" to "+ player.getY());
if(y > player.getY()){
moveDown = false;
moveUp = true;
lastDirection = 4;
}
if(y < player.getY()){
moveUp = false;
moveDown = true;
lastDirection = 8;
}
}
public void loseLife(){
System.out.println("loseLife");
int fallBack = 3;
int playerLastPosition = player.getLastDirection();
for(int i = 0; i < 10; i++){
switch(playerLastPosition){
case 1: y -= fallBack;
break;
case 2: x += fallBack; y -= fallBack;
break;
case 3: x += fallBack;
break;
case 4: x += fallBack; y += fallBack;
break;
case 5: y += fallBack;
break;
case 6: x -= fallBack; y += fallBack;
break;
case 7: x -= fallBack;
break;
case 8: x -= fallBack;y -= fallBack;
break;
}
}
life -= 1;
}
public void setLife(int life){
this.life = life;
}
public void setSpeed(int speed){
this.speed = speed;
}
}
| true
|
413daf4dcd96a0d3eed2064032a048ab4c7cbe2d
|
Java
|
06112497liu/ssm
|
/common-dao/src/main/java/com/bbd/dao/OpinionExtDao.java
|
UTF-8
| 827
| 1.804688
| 2
|
[] |
no_license
|
package com.bbd.dao;
import com.bbd.param.ChannelTrend;
import com.bbd.param.NameValueInfo;
import com.bbd.param.OpinionVo;
import java.util.List;
import java.util.Map;
public interface OpinionExtDao {
/**
* 查询预警舆情top10
* @return
*/
List<OpinionVo> selectWarnOpinionTopTen();
/**
* 查询不同时间段舆情增量
* @return
*/
Map<String, Long> selectAddOpinionGroupByTime();
/**
* 查询舆情传播渠道分布
* @return
*/
List<ChannelTrend> selectOpinionChannelTrend();
/**
* 查询舆情事件类型分布
* @return
*/
List<NameValueInfo> selectEventTypeTrend();
/**
* 查询舆情事件地域分布
* @return
*/
List<NameValueInfo> selectEventMapTrend();
}
| true
|
1ed513cf0b6cf03f0d28c6d34884bf2b96f8cfcb
|
Java
|
ostapkoziy/PublicEnemies
|
/PublicEnemies/src/main/java/com/epam/publicenemies/web/fight/FightResultController.java
|
UTF-8
| 2,332
| 2.21875
| 2
|
[] |
no_license
|
package com.epam.publicenemies.web.fight;
import java.util.Random;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.epam.publicenemies.domain.Profile;
import com.epam.publicenemies.domain.fight.Fight;
import com.epam.publicenemies.service.IProfileManagerService;
import com.epam.publicenemies.utils.Utils;
/**
* @author Alexander Ivanov
*/
@Controller
public class FightResultController
{
@Autowired
private IProfileManagerService profileManagerService;
private int moneyAfterFight = 0;
@RequestMapping("/fightResult.html")
public ModelAndView fightResault(HttpServletRequest request, HttpServletResponse response)
{
Fight fight = (Fight) request.getSession().getAttribute("game");
String role = (String) request.getSession().getAttribute("gameRole");
ModelAndView mav = new ModelAndView("/fight/fightResult");
Profile profile = fight.getProfile(role);
profileManagerService.updateTotalFights(profile.getProfileId(), profile.getFightsTotal() + 1);
if (fight.getWhoWins() == null || (profile.getUserId() != fight.getWhoWins().getUserId()))
{
request.getSession().setAttribute("win", false);
}
else
{
if (moneyAfterFight == 0)
{
moneyAfterFight = new Random().nextInt(300) + 100 * profile.getLevel().getCurrentLevel();
}
/*
* Work with DB
*/
profileManagerService.updateExperience(profile.getUserId(), profile.getLevel().getAllExpirience());
profileManagerService.updateMoney(profile.getUserId(), profile.getMoney() + moneyAfterFight);
profileManagerService.updateWonFights(profile.getProfileId(), profile.getFightsWon() + 1);
/*
*
*/
int oldLvl = profile.getLevel().getCurrentLevel();
Utils.expAnalizer(profile.getLevel());
Utils.isNewLevel(profile.getLevel(), oldLvl, profile.getLevel().getCurrentLevel());
/*
* SESSION CONFIG
*/
request.getSession().setAttribute("win", true);
}
mav.addObject("money", moneyAfterFight);
mav.addObject("myProfile", profile);
return mav;
}
}
| true
|
ed9d7917124d22b2bd681ab71bb95e99e29bb864
|
Java
|
HosamZ/back-end
|
/reflection/encoder/src/main/java/at/nacs/encoder/EncoderEndpoint.java
|
UTF-8
| 892
| 2.125
| 2
|
[] |
no_license
|
package at.nacs.encoder;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@RestController
@RequestMapping("/encode")
@RequiredArgsConstructor
public class EncoderEndpoint {
private final MorseClient morseClient;
@PostMapping
String letter(@RequestBody String plainText){
return Stream.of(plainText)
.map(e -> plainText.replaceAll(" ",""))
.map(e -> e.split(""))
.flatMap(Stream::of)
.map(letter -> morseClient.send(letter))
.collect(Collectors.joining());
}
//ToDo post here
}
| true
|
4a8cdc0b0125c7d965b19434b7de2029e1ae810c
|
Java
|
ValenbergHar/G-JD1-2019-10-01_ValenbergHar
|
/src/android/CoolLessons/Saints/app/src/main/java/com/example/saints/Saint.java
|
UTF-8
| 855
| 2.921875
| 3
|
[] |
no_license
|
package com.example.saints;
public class Saint {
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDob() {
return dob;
}
public void setDob(String dob) {
this.dob = dob;
}
public String getDod() {
return dod;
}
public void setDod(String dod) {
this.dod = dod;
}
public float getRating() {
return rating;
}
public void setRating(float rating) {
this.rating = rating;
}
public Saint(String name, String dob, String dod, float rating) {
this.name = name;
this.dob = dob;
this.dod = dod;
this.rating = rating;
}
private String name;
private String dob;
private String dod;
private float rating = 0f;
}
| true
|
19f3faba42669ffd286b7f2c0c7ded1338e5b4b5
|
Java
|
cowbi/sparrow
|
/design-pattern/src/main/java/factory/abstractFactory/Vehicle.java
|
UTF-8
| 152
| 2.21875
| 2
|
[] |
no_license
|
package factory.abstractFactory;
/**
* @author zhaoyancheng
* @date 2021-05-19 08:29
**/
public abstract class Vehicle {
abstract void run();
}
| true
|
1d4dcd450031f0a1992b61fd2d1d3e3955ad83de
|
Java
|
bellmit/newHouses
|
/myssh/src/com/sc/tradmaster/service/visitRecords/VisitRecordsService.java
|
UTF-8
| 1,580
| 2.09375
| 2
|
[] |
no_license
|
package com.sc.tradmaster.service.visitRecords;
import java.text.ParseException;
import java.util.List;
import java.util.Map;
import com.sc.tradmaster.bean.ProjectCustomers;
import com.sc.tradmaster.bean.User;
import com.sc.tradmaster.bean.VisitRecords;
import com.sc.tradmaster.service.visitRecords.impl.visitRecordDTO.ProjectCustomersDTO;
import com.sc.tradmaster.service.visitRecords.impl.visitRecordDTO.VisitCustomerDTO;
import com.sc.tradmaster.utils.Page;
public interface VisitRecordsService {
/**
* 到访客户表
*/
List<VisitCustomerDTO> findVisitCustomer(User user, String projectId, String startTime, String endTime)throws ParseException;
/**
* 下载到访客户表
*/
void findVisit(String projectId,String arriveTime,Page p)throws ParseException;
/**
* 置业顾问到访客户表
*/
List<ProjectCustomersDTO> findSaleVisitList(User user);
/**
* 通过Id获取到访记录
* @param visitNo
* @return
*/
VisitRecords findVisitById(Integer visitNo);
/**
* 一个月中周一至周日每天接访人数
* @param month
* @return
*/
Map<String,Object> findOneDayVisitNum(String startTime, String endTime,String projectId)throws ParseException;
/**
* 一个月中周一至周日每天接访人数
* @param month
* @return
*/
Map<String,Object> findOneDayVisitNumTwo(String startTime, String endTime,String projectId)throws ParseException;
/**
* 更新到访记录中的案场客户信息
* @param visitNo
* @param old
*/
void addOrUpdateVisitByVisitNo(Integer visitNo, ProjectCustomers old);
}
| true
|
393b32ec85b67c7f73bface08f865aa8017ec1bc
|
Java
|
egoistor/Notepad
|
/app/src/main/java/com/example/android/notepadtext/DeleteActivity.java
|
UTF-8
| 1,534
| 2.015625
| 2
|
[] |
no_license
|
package com.example.android.notepadtext;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import java.util.ArrayList;
import java.util.List;
public class DeleteActivity extends AppCompatActivity {
private List<Note> deleteNoteList = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_delete);
final RecyclerView recyclerView = findViewById(R.id.recycle_view);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
final NoteAdapter adapter = new NoteAdapter(deleteNoteList);
recyclerView.setAdapter(adapter);
adapter.setOnItemClickListener(new NoteAdapter.OnItemClickListener() {
@Override
public void onItemClick(View view, int position) {
//TODO
}
});
adapter.setOnItemLongClickListener(new NoteAdapter.OnItemLongClickListener() {
@Override
public void onItemLongClick(View view, int position) {
//TODO
}
});
recyclerView.setAdapter(adapter);
}
}
| true
|
5b6b60042fcb0394238b96de771a68a50cc9a43d
|
Java
|
abdirahmanali1997/Calculus
|
/calculus/source/SequencesGraph.java
|
UTF-8
| 11,508
| 2.640625
| 3
|
[] |
no_license
|
import java.awt.*;
import java.awt.geom.*;
import java.awt.event.*;
import org.nfunk.jep.*;
class Series{
double val;
double sum;
double ratio;
double root;
long n;
Series next;
Series previous;
public Series( double val, Series previous){
this.val = val;
this.previous = previous;
this.sum = val;
this.n = 1;
if ( previous != null ){
previous.next = this;
this.sum = previous.sum + val;
this.n = previous.n + 1;
if ( previous.val != 0 ) ratio = Math.abs(this.val/previous.val);
if ( this.n != 0 ) root = Math.pow( Math.abs(this.val), 1/(double)this.n );
}
}
}
public class SequencesGraph extends Graph{
Series markerA;
Series markerB;
Series current;
int N;
public SequencesGraph( CalculusApplet applet, String f, String g, int m, int n ){
super();
this.applet = applet;
this.m = m;
this.n = n;
variable = "n";
pixels = 100.0;
F.parseExpression( f );
G.parseExpression( g );
init();
}
public void init(){
F.addVariable( "n", 1 );
markerA = new Series( F.getValue(), null );
markerB = markerA;
current = markerA;
}
public void paintComponent( Graphics graphics ){
w = getWidth();
h = getHeight();
Graphics2D g = (Graphics2D)graphics;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
if (backImage==null || backImage.getWidth(this) != w || backImage.getHeight(this) != h){
backImage = this.createImage( (int)w, (int)h );
backGraphics = (Graphics2D)(backImage.getGraphics());
backGraphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
newBackground = true;
}
scale = pixels/units[zoom];
// draw graph of function f
//if ( newBackground || shift ){
if ( newBackground ){
backGraphics.setColor( getBackground() );
backGraphics.fillRect( 0, 0, (int)w, (int)h );
if ( showGrid ) drawGridLines( backGraphics );
//if ( !shift ){
drawAxes( backGraphics );
drawFunction( backGraphics );
//}
draw( backGraphics );
newBackground = false;
}
g.drawImage( backImage, 0, 0, this );
if ( current != null && newA ){
Object s = applet.choice.getSelectedItem();
if ( s.equals( "Show Sequence Only" ) ){
//drawPoint( g, current.n, current.val, 1.5*r, Color.blue );
drawPoint( g, current.n, current.val, new Color(0,0,255,150), true );
} else if ( s.equals( "Sequence and Series" ) ){
drawPoint( g, current.n, current.sum, Color.red, true );
drawPoint( g, current.n, current.val, Color.blue, true );
} else if ( s.equals( "Sequence and Ratio Test" ) ){
drawPoint( g, current.n, current.ratio, Color.green, true );
drawPoint( g, current.n, current.val, Color.blue, true );
} else if ( s.equals( "Sequence and Root Test" ) ){
drawPoint( g, current.n, current.root, Color.yellow, true );
drawPoint( g, current.n, current.val, Color.blue, true );
} else if ( s.equals( "Comparison Test" ) ){
G.addVariable( "n", current.n );
drawPoint( g, current.n, G.getValue(), Color.magenta, true );
drawPoint( g, current.n, current.val, Color.blue, true );
} else if ( s.equals( "Limit Comparison Test" ) ){
G.addVariable( "n", current.n );
drawPoint( g, current.n, current.val/G.getValue(), Color.cyan, true );
drawPoint( g, current.n, current.val, Color.blue, true );
}
newA = false;
}
//if ( !shift ){
drawEndpoints( g );
drawCrosshair( g );
//}
}
double[] out = { originX + m*(a - w/2)/pixels, originY - n*(b-h/2)/pixels };
public void draw( Graphics2D g ){
int A = Math.max( 1, (int)(originX - m*w/pixels/2) );
int B = Math.max( 1, (int)(originX + m*w/pixels/2) );
if ( newStat ){
init();
newStat = false;
}
Series tmp;
int step = (int)( Math.max(1,10*m/pixels) );
if ( shift ) step = 1;
Object s = applet.choice.getSelectedItem();
if ( s.equals( "Show Sequence Only" ) ){
for ( int i=A; i<B+1; i+=step ){
F.addVariable( "n", i );
drawPoint( g, i, F.getValue(), new Color(0,0,255,150), false );
}
} else if ( s.equals( "Comparison Test" ) ){
for ( int i=A; i<B+1; i+=step ){
F.addVariable( "n", i );
drawPoint( g, i, F.getValue(), new Color(0,0,255,150), false );
G.addVariable( "n", i );
drawPoint( g, i, G.getValue(), new Color(255,0,255,150), false );
}
} else if ( s.equals( "Limit Comparison Test" ) ){
for ( int i=A; i<B+1; i+=step ){
F.addVariable( "n", i );
drawPoint( g, i, F.getValue(), new Color(0,0,255,150), false );
G.addVariable( "n", i );
drawPoint( g, i, F.getValue()/G.getValue(), new Color(0,255,255,150), false );
}
} else {
if ( markerB.n >= B ){
// move markerB up the list
while ( markerB.n > B ){
markerB = markerB.previous;
}
} else {
// move markerB down the list
while ( markerB.next != null && markerB.n < B ){
markerB = markerB.next;
}
// create new data if necessary
while ( markerB.n < B ){
F.addVariable( "n", (markerB.n + 1) );
tmp = new Series( F.getValue(), markerB );
markerB = tmp;
}
}
if ( markerA.n <= A ){
while ( markerA.n < A ){
markerA = markerA.next;
}
} else {
while ( markerA.n > A ){
markerA = markerA.previous;
}
}
int i;
if ( s.equals( "Sequence and Series" ) ){
tmp = markerA;
while ( tmp != null && tmp.n <= markerB.n ){
drawPoint( g, tmp.n, tmp.sum, new Color(255,0,0,150), false );
drawPoint( g, tmp.n, tmp.val, new Color(0,0,255,150), false );
//tmp = tmp.next;
i = 0;
while ( i++<step && tmp != null ) tmp = tmp.next;
}
} else if ( s.equals( "Sequence and Ratio Test" ) ){
tmp = markerA;
while ( tmp != null && tmp.n <= markerB.n ){
drawPoint( g, tmp.n, tmp.ratio, new Color(0,255,0,150), false );
drawPoint( g, tmp.n, tmp.val, new Color(0,0,255,150), false );
//tmp = tmp.next;
i = 0;
while ( i++<step && tmp != null ) tmp = tmp.next;
}
} else if ( s.equals( "Sequence and Root Test" ) ){
tmp = markerA;
while ( tmp != null && tmp.n <= markerB.n ){
drawPoint( g, tmp.n, tmp.root, new Color(255,255,0,150), false );
drawPoint( g, tmp.n, tmp.val, new Color(0,0,255,150), false );
//tmp = tmp.next;
i = 0;
while ( i++<step && tmp != null ) tmp = tmp.next;
}
}
}
setStat();
}
public void drawAxes( Graphics2D g ){
g.setColor( Color.black );
g.setStroke( axes );
double[] P = toScreenPoint( 0, 0 );
W = P[0];
if ( P[0] < 10 ) W = 10;
else if ( P[0] > w - 10 ) W = w - 10;
H = P[1];
if ( P[1] < 10 ) H = 10;
else if ( P[1] > h-20 ) H = h - 20;
// draw y-axis
g.draw( new Line2D.Double(W,0,W,h) );
// draw x-axis
g.draw( new Line2D.Double(0,H,w,H) );
// label y-axis
float ww = (float)(W+4);
String str;
for ( int A = (int)(originY/n-h/2/pixels)-1; A < (originY/n+h/2/pixels)+1; A++){
g.draw( new Line2D.Double( W-2, h/2 - pixels*(A-originY/n), W+2, h/2 - pixels*(A-originY/n) ) );
if ( A != 0 ){
str = "" + (int)(A*n);
if ( W != 1 ) ww = Math.max(14,(float)(W-3) - g.getFontMetrics().stringWidth(str));
g.drawString( str, ww, (float)(h/2 - pixels*(A-originY/n)) + g.getFontMetrics().getHeight()/3 );
}
}
// label x-axis
float hh = (float)(H+1)+g.getFontMetrics().getHeight();
if ( H == h - 1 ){
hh = (float)(H-4);
}
for ( int A = (int)(originX/m-w/2/pixels)-1; A < (originX/m+w/2/pixels)+1; A++){
g.draw( new Line2D.Double(w/2 + pixels*(A-originX/m),H-2,w/2 + pixels*(A-originX/m),H+2 ) );
if ( A != 0 ){
str = "" + (int)(A*m);
g.drawString( str, (float)(w/2 + pixels*(A-originX/m)) - g.getFontMetrics().stringWidth(str)/2, hh );
}
}
}
public void drawEndpoints( Graphics2D g ){
}
public void drawFunction( Graphics2D g ){
}
public void drawGridLines( Graphics2D g ){
g.setColor( Color.cyan );
g.setStroke( gridline );
for ( double A = (int)(originY/n-h/2/pixels)-1; A < (originY/n+h/2/pixels)+1; A=A+0.2){
g.draw( new Line2D.Double( 0,h/2 - pixels*(A-originY/n),w,h/2 - pixels*(A-originY/n) ) );
}
for ( double A = (int)(originX/m-w/2/pixels)-1; A < (originX/m+w/2/pixels)+1; A=A+0.2){
g.draw( new Line2D.Double( w/2 + pixels*(A-originX/m),0,w/2 + pixels*(A-originX/m),h ) );
}
}
public double[] toCartesianPoint( double a, double b ){
double[] out = { originX + m*(a - w/2)/pixels, originY - n*(b-h/2)/pixels };
return out;
}
public double[] toScreenPoint( double a, double b ){
double[] out = { w/2 + pixels*(a - originX)/m, h/2 - pixels*(b - originY)/n };
return out;
}
public void setStat(){
if ( current != null && N > 0 ){
applet.stat.setText( "" );
applet.stat2.setText( "" );
if ( current.n < N ){
while ( current.next != null && current.n < N ){
current = current.next;
}
} else if ( current.n > N ){
while ( current.previous != null && current.n > N ){
current = current.previous;
}
}
Object s = applet.choice.getSelectedItem();
if ( s.equals( "Show Sequence Only" ) ){
F.addVariable( "n", N );
applet.setStat(" a(" + N + ") \u2248 ", F.getValue(), Color.blue );
} else if ( s.equals( "Comparison Test" ) ){
F.addVariable( "n", N );
applet.setStat(" a(" + N + ") \u2248 ", F.getValue(), Color.blue );
G.addVariable( "n", N );
applet.setStat2(" b(" + N + ") \u2248 ", G.getValue(), Color.magenta );
} else if ( s.equals( "Limit Comparison Test" ) ){
F.addVariable( "n", N );
applet.setStat(" a(" + N + ") \u2248 ", F.getValue(), Color.blue );
G.addVariable( "n", N );
applet.setStat2(" a(" + N + ")/b(" + N + ") \u2248 ", F.getValue()/G.getValue(), Color.cyan );
} else if ( s.equals( "Sequence and Series" ) ){
applet.setStat(" a(" + N + ") \u2248 ", current.val, Color.blue );
applet.setStat2( " s(" + N + ") \u2248 ", current.sum, Color.red );
} else if ( s.equals( "Sequence and Ratio Test" ) ){
applet.setStat(" a(" + N + ") \u2248 ", current.val, Color.blue );
applet.setStat2( " s(" + N + ") \u2248 ", current.ratio, Color.green );
} else if ( s.equals( "Sequence and Root Test" ) ){
applet.setStat(" a(" + N + ") \u2248 ", current.val, Color.blue );
applet.setStat2( " s(" + N + ") \u2248 ", current.root, Color.yellow );
}
}
}
public void keyPressed( KeyEvent ke ){
int code = ke.getKeyCode();
if ( code == KeyEvent.VK_SHIFT ){// holding down shift key
shift = true;
newBackground = true;
repaint();
}
}
public void keyReleased( KeyEvent ke ){
shift = false;
newBackground = true;
repaint();
}
public void mouseMoved( MouseEvent me ){
N = (int)(originX + m*(me.getPoint().x - w/2)/pixels + 0.5 );
setStat();
newA = true;
repaint();
}
public void mouseClicked( MouseEvent me ){
POINT = me.getPoint();
//double[] P = toCartesianPoint( POINT.x, POINT.y );
if ( me.getClickCount() > 1 ){
// set center so that P stays in same place
int z = Math.max( 1, m/2 );
originX += (m - z)*(POINT.x-w/2)/pixels;
//originY = P[1] + n*(POINT.y-h/2)/pixels;
// zoom in on point P
applet.actionPerformed( new ActionEvent(applet.zoomin,ActionEvent.ACTION_PERFORMED,"zoom") );
}
}
public void mousePressed(MouseEvent me){
POINT = me.getPoint();
}
public void mouseDragged(MouseEvent me){
originX -= m*(me.getPoint().x - POINT.x)/pixels;
originY += n*(me.getPoint().y - POINT.y)/pixels;
POINT = me.getPoint();
newBackground = true;
repaint();
}
}
| true
|
e5f2e05629f4498e849dc0f691964994da60b45c
|
Java
|
FamilySearch/gedcomx-java
|
/gedcomx-model/src/main/java/org/gedcomx/common/EvidenceReference.java
|
UTF-8
| 5,169
| 1.890625
| 2
|
[
"Apache-2.0"
] |
permissive
|
/**
* Copyright Intellectual Reserve, Inc.
*
* 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.gedcomx.common;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.webcohesion.enunciate.metadata.Facet;
import org.gedcomx.links.HypermediaEnabledData;
import org.gedcomx.links.Link;
import org.gedcomx.rt.GedcomxConstants;
import org.gedcomx.rt.GedcomxModelVisitor;
import org.gedcomx.rt.json.JsonElementWrapper;
import javax.xml.XMLConstants;
import jakarta.xml.bind.annotation.XmlAttribute;
import jakarta.xml.bind.annotation.XmlRootElement;
import jakarta.xml.bind.annotation.XmlSchemaType;
import jakarta.xml.bind.annotation.XmlType;
/**
* A reference to a resource that is being used as evidence.
*
* @author Ryan Heaton
*/
@XmlRootElement
@XmlType ( name = "EvidenceReference" )
@JsonElementWrapper ( name = "evidence" )
@JsonInclude ( JsonInclude.Include.NON_NULL )
public final class EvidenceReference extends HypermediaEnabledData implements Attributable {
private URI resource;
private String resourceId;
private Attribution attribution;
public EvidenceReference() {
}
public EvidenceReference(URI resource) {
this.resource = resource;
}
public EvidenceReference(URI resource, String resourceId) {
this.resource = resource;
this.resourceId = resourceId;
}
@Override
public EvidenceReference link(Link link) {
return (EvidenceReference) super.link(link);
}
@Override
public EvidenceReference link(String rel, URI href) {
return (EvidenceReference) super.link(rel, href);
}
@Override
public EvidenceReference id(String id) {
return (EvidenceReference) super.id(id);
}
@Override
public EvidenceReference extensionElement(Object element) {
return (EvidenceReference) super.extensionElement(element);
}
/**
* The resource id of the resource being referenced. Used as an extension attribute when resolving the resource is inconvenient.
*
* @return The resource id of the resource being referenced.
*/
@XmlAttribute
@Facet ( GedcomxConstants.FACET_GEDCOMX_RS )
public String getResourceId() {
return resourceId;
}
/**
* The resource id of the resource being referenced. Used as an extension attribute when resolving the resource is inconvenient.
*
* @param resourceId The resource id of the resource being referenced.
*/
public void setResourceId(String resourceId) {
this.resourceId = resourceId;
}
/**
* Build up this reference with a resource id.
*
* @param resourceId The resource id.
* @return this.
*/
public EvidenceReference resourceId(String resourceId) {
this.resourceId = resourceId;
return this;
}
/**
* The URI to the resource being referenced as evidence.
*
* @see <a href="http://www.w3.org/TR/webarch/#identification">http://www.w3.org/TR/webarch/#identification</a>
* @return The URI to the resource.
*/
@XmlAttribute
@XmlSchemaType (name = "anyURI", namespace = XMLConstants.W3C_XML_SCHEMA_NS_URI)
public URI getResource() {
return resource;
}
/**
* The URI to the resource being referenced as evidence.
*
* @see <a href="http://www.w3.org/TR/webarch/#identification">http://www.w3.org/TR/webarch/#identification</a>
* @param resource The URI to the resource.
*/
public void setResource(URI resource) {
this.resource = resource;
}
/**
* Build up this reference with a resource URI.
*
* @param resource The resource.
* @return this
*/
public EvidenceReference resource(URI resource) {
this.resource = resource;
return this;
}
/**
* Attribution metadata for this evidence reference.
*
* @return Attribution metadata for evidence reference.
*/
@Override
public Attribution getAttribution() {
return attribution;
}
/**
* Attribution metadata for evidence reference.
*
* @param attribution Attribution metadata for evidence reference.
*/
@Override
public void setAttribution(Attribution attribution) {
this.attribution = attribution;
}
/**
* Build up this evidence reference with an attribution.
*
* @param attribution The attribution.
* @return this.
*/
public EvidenceReference attribution(Attribution attribution) {
this.attribution = attribution;
return this;
}
/**
* Accept a visitor.
*
* @param visitor The visitor.
*/
public void accept(GedcomxModelVisitor visitor) {
visitor.visitEvidenceReference(this);
}
/**
* Provide a simple toString() method.
*/
@Override
public String toString() {
return (resource == null) ? "" : resource.toString();
}
}
| true
|
8cf75dfdd97eb2575229f95836af5eafc1776a62
|
Java
|
ccrodrigues/curso-angular-mvc
|
/mvc/src/main/java/com/brq/mvc/resources/exception/ObjectNotFoundException.java
|
UTF-8
| 318
| 2.203125
| 2
|
[] |
no_license
|
package com.brq.mvc.resources.exception;
public class ObjectNotFoundException extends RuntimeException {
private static final long serialVersionUID = 1L;
public ObjectNotFoundException(int id, Object obj) {
super ("O " + obj.getClass().getSimpleName() +
" com id " + id + " não foi localizado");
}
}
| true
|
c28d77ca7e4d94e94cb0cff5070621eadae81cf8
|
Java
|
morreman/MahFoodInfoServer
|
/unicorn-spark/src/main/java/recensions/Storage.java
|
UTF-8
| 5,785
| 2.96875
| 3
|
[
"MIT"
] |
permissive
|
package recensions;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
/**
* @author "Anton & Mårten"
*/
public class Storage {
private Connection connection = null;
private String createStringRestaurant =
"create table RESTAURANT " +
"(RESTAURANT_NAME varchar(32)," +
"primary key(RESTAURANT_NAME))";
private String createStringComment =
"create table COMMENT " +
"(COMMENT_ID int AUTO INCREMENT, " +
"RESTAURANT_FK varchar(32)," +
"GRADE int," +
"REPORTED_BY varchar(32)," +
"DESCRIPTION varchar(140)," +
"primary key(COMMENT_ID)," +
"foreign key(RESTAURANT_FK) references RESTAURANT(RESTAURANT_NAME))";
/**
* Sets up the database connection.
*
* @throws ClassNotFoundException
*/
public Storage() throws ClassNotFoundException {
Class.forName("org.sqlite.JDBC");
try {
connection = DriverManager.getConnection("jdbc:sqlite:restaurants.db");
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* Closes the database connection.
*/
protected void finalize() throws Throwable {
try {
connection.close();
} catch (SQLException e) {
}
super.finalize();
}
/**
* Nollställer databasen när servern startar.
* Fyller på med de 5 restauranger som Tibblins API tillhandahåller.
*/
public void setup() {
System.out.println("In setup");
try {
Statement statement = connection.createStatement();
statement.executeUpdate("DROP TABLE IF EXISTS RESTAURANT");
statement.executeUpdate("DROP TABLE IF EXISTS COMMENT");
statement.executeUpdate(createStringComment);
statement.executeUpdate(createStringRestaurant);
statement.executeUpdate("INSERT INTO RESTAURANT VALUES ('Restaurang Niagara')");
statement.executeUpdate("INSERT INTO RESTAURANT VALUES ('Mia Maria')");
statement.executeUpdate("INSERT INTO RESTAURANT VALUES ('Välfärden')");
statement.executeUpdate("INSERT INTO RESTAURANT VALUES ('Lilla Köket')");
statement.executeUpdate("INSERT INTO RESTAURANT VALUES ('La Bonne Vie')");
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
public List<Visit> fetchRestaurants() {
List<Visit> recension = new ArrayList<>();
try {
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery("SELECT RESTAURANT.RESTAURANT_NAME, COMMENT.GRADE, COMMENT.DESCRIPTION, COMMENT.REPORTED_BY FROM RESTAURANT INNER " +
"JOIN COMMENT ON RESTAURANT.RESTAURANT_NAME=COMMENT.RESTAURANT_FK ");
while (rs.next()) {
Visit visit = new Visit();
visit.grade = rs.getInt("GRADE");
visit.description = rs.getString("DESCRIPTION");
visit.reportedBy = rs.getString("REPORTED_BY");
visit.restaurant = rs.getString("RESTAURANT_NAME");
recension.add(visit);
}
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
return recension;
}
/**
* Hämtar alla besök från en restaurang.
*
* @param id Id:t är restaurangens namn.
* @return returnernar alla besök för den givna restaurangen.
*/
public Visit fetchResturant(int id) {
Visit visit = null;
try {
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery("SELECT * FROM restaurants WHERE id = " + id);
if (rs.next()) {
visit = new Visit();
visit.grade = rs.getInt("grade");
visit.description = rs.getString("description");
visit.reportedBy = rs.getString("reportedBy");
visit.restaurant = rs.getString("restaurant_name");
}
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
return visit;
}
/**
* Skapar ett nytt besök.
*
* @param visit A new visit object.
*/
public void addRestaurant(Visit visit) {
System.out.println(visit.restaurant + " VIlken resturang");
try {
Statement statement = connection.createStatement();
String sql = "INSERT INTO COMMENT (GRADE, DESCRIPTION, REPORTED_BY, RESTAURANT_FK) "
+ "VALUES ('" + visit.grade + "', "
+ "'" + visit.description + "', "
+ "'" + visit.reportedBy + "', "
+ "'" + visit.restaurant + "');";
System.out.println(sql);
statement.executeUpdate(sql);
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* Uppdaterar ett besök.
* Används inte för tillfället (Kod inte fullständig).
* @param visit A visit object.
*/
// public void updateRestaurant(Visit visit) {
// try {
// Statement statement = connection.createStatement();
//
// String sql = "UPDATE restaurants SET id = " + visit.id + ", "
// + "restaurant_name = '" + visit.restaurant + "', "
// + "grade = '" + visit.grade + "', "
// + "description = '" + visit.description + "', "
// + "reportedBy = '" + visit.reportedBy + "', "
// + "WHERE id = " + visit.id + ";";
//
// statement.executeUpdate(sql);
//
// statement.close();
// } catch (SQLException e) {
// e.printStackTrace();
// }
// }
/**
* Tar bort ett besök tillhörande en restaurang.
* Används inte för tillfället (Kod inte fullständig).
* @param id Id:t för ett besök.
*/
public void deleteVisit(int id) {
try {
Statement statement = connection.createStatement();
statement.executeUpdate("DELETE FROM restaurants WHERE id = " + id);
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
| true
|
b4aeaf62d10524d3a4bfe60f122507e3f676c19c
|
Java
|
ShivrajMPujari/bridgeIt
|
/objectOriented/StockMain.java
|
UTF-8
| 3,869
| 3.015625
| 3
|
[] |
no_license
|
package com.bridgeIt.objectOriented;
import org.json.simple.JSONObject;
import com.bridgeIt.utility.Utility;
public class StockMain {
public static void main(String[] args) {
System.out.println("Stock processing-");
System.out.println("1.New user \n2.Existing user");
int user=Utility.inputInt();
if(user==1){
System.out.println("Enter the name of the Account");
String name=Utility.inputString();
StockAccount account= new StockAccount(name);
System.out.println("Enter the choice-\n 1. Buy the share 2.Sell the share 3.Save 4.Quit");
int num=Utility.inputInt();
int i=9;
while(i==9){
switch(num){
case 1:{
System.out.println("Enter the Company symbol");
String symbol=Utility.inputString();
System.out.println("Enter the share amount");
int amount=Utility.inputInt();
System.out.println("Enter the date");
String date=Utility.inputString();
account.buy(amount, symbol,date);
System.out.println("Enter the choice-\n 1. Buy the share 2.Sell the share 3.Save 4.Quit");
num=Utility.inputInt();
break;
}
case 2:{
System.out.println("Enter the Company symbol");
String symbol=Utility.inputString();
System.out.println("Enter the share amount");
int amount=Utility.inputInt();
System.out.println("enter the date");
String date=Utility.inputString();
account.sell(amount, symbol,date);
System.out.println("Enter the choice-\n 1. Buy the share 2.Sell the share 3.Save 4.Quit");
num=Utility.inputInt();
break;
}
case 3:{
account.save(name, account.list,account.totalSharePrice);
System.out.println("Your data is saved");
System.out.println("Enter the choice 1.display details 2.total share price");
int option=Utility.inputInt();;
if(option==1){
// account.list.display();
account.printReport();
}
else if(option==2){
System.out.println("total share price is "+account.totalSharePrice);
}
System.out.println("Enter the choice-\n 1. Buy the share 2.Sell the share 3.Save 4.Quit");
num=Utility.inputInt();
break;
}
case 4:{
System.exit(0);
break;
}
}
}
}
else if(user==2){
System.out.println("Enter the name of the Account");
String name=Utility.inputString();
StockAccount account= new StockAccount(name);
JSONObject jsonObject=account.editPerson(name);
System.out.println(jsonObject);
System.out.println("Enter the choice-\n 1. Buy the share 2.Sell the share 3.Save 4.Print Report");
int num=Utility.inputInt();
int j=9;
while(j==9){
switch(num){
case 1:{
System.out.println("Enter the Company symbol");
String symbol=Utility.inputString();
System.out.println("Enter the share amount");
int amount=Utility.inputInt();
account.editBuy(jsonObject, amount, symbol);
System.out.println("Enter the choice-\n 1. Buy the share 2.Sell the share 3.Save 4.Print Report");
num=Utility.inputInt();
break;
}
case 2:{
System.out.println("Enter the Company symbol");
String symbol=Utility.inputString();
System.out.println("Enter the share amount");
int amount=Utility.inputInt();
account.editSell(jsonObject, amount, symbol);
System.out.println("Enter the choice-\n 1. Buy the share 2.Sell the share 3.Save 4.Print Report");
num=Utility.inputInt();
break;
}
case 3:{
account.editPrint(jsonObject, name);
System.out.println("Enter the choice-\n 1. Buy the share 2.Sell the share 3.Save 4.Print Report");
num=Utility.inputInt();
break;
}
case 4:{
account.editDisplay(jsonObject);
System.exit(0);
break;
}
}
}
}
}
}
| true
|
9d8423e709a65752b0277b61ba471acffa706285
|
Java
|
joabeleonard/clubeserver
|
/src/main/java/com/example/polls/model/CategoriaEmpresa.java
|
UTF-8
| 1,248
| 2.6875
| 3
|
[] |
no_license
|
package com.example.polls.model;
import java.util.HashMap;
import java.util.Map;
/**
* Created by rajeevkumarsingh on 07/12/17.
*/
public enum CategoriaEmpresa {
ALIMENTACAO("ALIMENTACAO","Alimentacao"),
SERVICO_AUTOMATIVO("SERVICO_AUTOMATIVO","Serviço Automativo"),
EDUCACAO("EDUCACAO","Educação"),
TURISMO("TURISMO","Turismo"),
SERVICOS("SERVICOS","Serviços"),
SUPERMERCADO("SUPERMERCADO","Supermercado"),
ELETRODOMESTICOS("ELETRODOMESTICOS","Eletrodomesticos"),
OUTROS("OUTROS","Outros");
private static final Map<String, String> MAP = new HashMap<String, String>();
static {
for (CategoriaEmpresa s : CategoriaEmpresa.values()) {
MAP.put(s.code, s.descricao);
}
}
private final String code;
private String descricao;
CategoriaEmpresa(String code, String descricao){
this.code = code;
this.descricao = descricao;
}
public String getDescricao() {
return descricao;
}
public String getCode() {
return code;
}
}
| true
|
27e920f0ffe17045da64ccbf5c0f698dbd6ba9fe
|
Java
|
Liu-zhi-xiang/Kxian
|
/app/src/main/java/com/gjmetal/app/model/my/AdviceModel.java
|
UTF-8
| 1,622
| 2.125
| 2
|
[
"MIT"
] |
permissive
|
package com.gjmetal.app.model.my;
/**
* Description: 版本信息
* @author :liuzhixiang
* @Email 1910609992@qq.com
* @date 2019/4/27 13:22
*/
public class AdviceModel {
//app版本
private String appVersion;
//联系方式
private String contact;
//反馈内容
private String content;
//设备版本
private String deviceVersion;
//图片url
private String images;
//网络
private String network;
//系统版本
private String systemVersion;
public String getAppVersion() {
return appVersion;
}
public void setAppVersion(String appVersion) {
this.appVersion = appVersion;
}
public String getContact() {
return contact;
}
public void setContact(String contact) {
this.contact = contact;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getDeviceVersion() {
return deviceVersion;
}
public void setDeviceVersion(String deviceVersion) {
this.deviceVersion = deviceVersion;
}
public String getImages() {
return images;
}
public void setImages(String images) {
this.images = images;
}
public String getNetwork() {
return network;
}
public void setNetwork(String network) {
this.network = network;
}
public String getSystemVersion() {
return systemVersion;
}
public void setSystemVersion(String systemVersion) {
this.systemVersion = systemVersion;
}
}
| true
|
be613ce1d2a90567cbfbf5afa792f98d708fcd25
|
Java
|
tosim/Java-interview
|
/interview/src/main/java/com/tosim/interview/designpartten/creation/builder/Test.java
|
UTF-8
| 315
| 2.65625
| 3
|
[] |
no_license
|
package com.tosim.interview.designpartten.creation.builder;
public class Test {
public static void main(String[] args){
HouseDirector houseDirector = new HouseDirector();
House house = houseDirector.buildHouse(new ConcreteHouseBuilder());
System.out.println(house.toString());
}
}
| true
|
981f869c8ec7ccdd83be57a52ff15232bba721c6
|
Java
|
AugustoVasconellosUFC/qxd007-cofre
|
/src/test/java/TestCofre.java
|
UTF-8
| 4,895
| 3.140625
| 3
|
[] |
no_license
|
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
public class TestCofre {
@Test
public void testMoedas() {
assertTrue(Moeda.M10 instanceof Enum, "As moedas devem ser enumeracoes");
assertTrue(Moeda.M25 instanceof Enum, "As moedas devem ser enumeracoes");
assertTrue(Moeda.M50 instanceof Enum, "As moedas devem ser enumeracoes");
assertTrue(Moeda.M100 instanceof Enum, "As moedas devem ser enumeracoes");
}
@Test
public void testInicializacao() {
Cofre cofre = new Cofre(25);
assertEquals(25, cofre.getVolumeMaximo(),
"Ao inicializar o volumeMaximo do cofre deve ser igual ao informado no construtor");
assertEquals(0, cofre.getVolume(),
"Ao inicializar o volume do cofre deve ser igual ao zero");
assertTrue(cofre.taInteiro(), "Ao criar um cofre, ele deve estar inteiro");
}
@Test
public void testInserirMoedaCofreQuebrado() {
Cofre cofre = new Cofre(25);
cofre.quebrar();
assertFalse(cofre.add(Moeda.M50), "Nao deve ser possivel adicionar uma moeda em um cofre quebrado");
}
@Test
public void testInserirItemCofreQuebrado() {
Cofre cofre = new Cofre(25);
cofre.quebrar();
Item teste = new Item("Item teste", 10);
assertFalse(cofre.add(teste), "Nao deve ser possivel adicionar uma moeda em um cofre quebrado");
}
@Test
public void testInserirItemVolumoso() {
Cofre cofre = new Cofre(25);
Item arvore = new Item("Arvore", 1000);
assertFalse(cofre.add(arvore), "Nao deve ser possivel adicionar um item com volume maior que o do cofre");
}
@Test
public void testInserirItem() {
Cofre cofre = new Cofre(25);
Item passporte = new Item("Passaporte", 5);
assertTrue(cofre.add(passporte), "Tem espaco sobrando, entao deve ser possivel adicionar o item");
assertEquals(20, cofre.getVolumeRestante(), "Ao adicionar um item, o volume restante do cofre deve ser atualizado");
}
@Test
public void testInserirMoeda() {
Cofre cofre = new Cofre(10);
assertTrue(cofre.add(Moeda.M10), "Tem espaco sobrando, entao deve ser possivel adicionar o item");
assertEquals(9, cofre.getVolumeRestante(), "Ao adicionar uma moeda, o volume restante do cofre deve ser atualizado");
}
@Test
public void testInserirItemEmCofreCheio() {
Cofre cofre = new Cofre(4);
cofre.add(Moeda.M100);
Item passporte = new Item("Passaporte", 5);
assertFalse(cofre.add(Moeda.M10), "Nao deve ser possivel adicionar algo em um cofre cheio");
assertFalse(cofre.add(passporte), "Nao deve ser possivel adicionar algo em um cofre cheio");
}
@Test
public void testQuebrar() {
Cofre cofre = new Cofre(25);
assertTrue(cofre.quebrar(), "Deve ser possel quebrar um cofre inteiro");
}
@Test
public void testQuebrarQuebrado() {
Cofre cofre = new Cofre(25);
assertTrue(cofre.quebrar(), "Deve ser possel quebrar um cofre inteiro");
assertFalse(cofre.quebrar(), "Nao deve ser possivel quebrar um cofre quebrado");
}
@Test
public void testObterMoedaDeCofreInteiro() {
Cofre cofre = new Cofre(10);
cofre.add(Moeda.M10);
assertEquals(-1, cofre.obterMoedas(),
"Nao deve ser possivel obter moedas de um cofre inteiro (-1)");
}
@Test
public void testObterItemDeCofreInteiro() {
Cofre cofre = new Cofre(10);
cofre.add(Moeda.M10);
assertNull(cofre.obterItens(),
"Nao deve ser possivel obter itens de um cofre inteiro (null)");
}
@Test
public void testObterMoedas() {
Cofre cofre = new Cofre(10);
cofre.add(Moeda.M10);
cofre.add(Moeda.M100);
cofre.quebrar();
assertEquals(1.1, cofre.obterMoedas(),
"Ao obter as moedas, o cofre deve retornar a some de valores da moedas nele contidas");
}
@Test
public void testObterItems() {
Cofre cofre = new Cofre(10);
Item passporte = new Item("Passaporte", 5);
Item chave = new Item("Chave do carro", 3);
cofre.add(passporte);
cofre.add(chave);
cofre.quebrar();
assertEquals("Passaporte, Chave do carro", cofre.obterItens(),
"Ao obter as moedas, o cofre deve retornar a descricao dos itens nele contidos");
}
@Test
public void testObterCofreVazio() {
Cofre cofre = new Cofre(10);
cofre.quebrar();
assertEquals(0, cofre.obterMoedas(),
"Ao obter as moedas, se o cofre estiver vazio ele deve retornar zero");
assertEquals("vazio", cofre.obterItens(),
"Ao obter itens, se cofre estiver vazio ele deve retornar 'vazio'");
}
}
| true
|
b0f3f14f8a776e773ad2fb83b4b5afd84ca82b05
|
Java
|
virtudesp/gesmusic-server
|
/src/main/java/net/daw/bean/implementation/SociedadBean.java
|
UTF-8
| 8,150
| 2.234375
| 2
|
[
"MIT"
] |
permissive
|
/*
* 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 net.daw.bean.implementation;
import com.google.gson.annotations.Expose;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import net.daw.bean.publicinterface.GenericBean;
import net.daw.helper.statics.EncodingUtilHelper;
public class SociedadBean implements GenericBean {
@Expose
private Integer id = 0;
@Expose
private String nombre;
@Expose
private String razon_social;
@Expose
private String nif;
@Expose
private String direccion;
@Expose
private String poblacion;
@Expose
private String provincia;
@Expose
private String pais;
@Expose
private String codigopostal;
@Expose
private String telefono;
@Expose
private String email;
@Expose
private String web;
public SociedadBean() {
}
public SociedadBean(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getRazon_social() {
return razon_social;
}
public void setRazon_social(String razon_social) {
this.razon_social = razon_social;
}
public String getNif() {
return nif;
}
public void setNif(String nif) {
this.nif = nif;
}
public String getDireccion() {
return direccion;
}
public void setDireccion(String direccion) {
this.direccion = direccion;
}
public String getPoblacion() {
return poblacion;
}
public void setPoblacion(String poblacion) {
this.poblacion = poblacion;
}
public String getProvincia() {
return provincia;
}
public void setProvincia(String provincia) {
this.provincia = provincia;
}
public String getPais() {
return pais;
}
public void setPais(String pais) {
this.pais = pais;
}
public String getCodigopostal() {
return codigopostal;
}
public void setCodigopostal(String codigopostal) {
this.codigopostal = codigopostal;
}
public String getTelefono() {
return telefono;
}
public void setTelefono(String telefono) {
this.telefono = telefono;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getWeb() {
return web;
}
public void setWeb(String web) {
this.web = web;
}
@Override
public String getColumns() {
String strColumns = "";
strColumns += "id,";
strColumns += "nombre,";
strColumns += "razon_social,";
strColumns += "nif,";
strColumns += "direccion,";
strColumns += "poblacion,";
strColumns += "provincia,";
strColumns += "pais,";
strColumns += "codigopostal,";
strColumns += "telefono,";
strColumns += "email,";
strColumns += "web";
return strColumns;
}
@Override
public String getValues() {
String strColumns = "";
strColumns += id + ",";
strColumns += EncodingUtilHelper.quotate(getNombre()) + ",";
strColumns += EncodingUtilHelper.quotate(getRazon_social()) + ",";
strColumns += EncodingUtilHelper.quotate(getNif()) + ",";
strColumns += EncodingUtilHelper.quotate(getDireccion()) + ",";
strColumns += EncodingUtilHelper.quotate(getPoblacion()) + ",";
strColumns += EncodingUtilHelper.quotate(getProvincia()) + ",";
strColumns += EncodingUtilHelper.quotate(getPais()) + ",";
strColumns += EncodingUtilHelper.quotate(getCodigopostal()) + ",";
strColumns += EncodingUtilHelper.quotate(getTelefono()) + ",";
strColumns += EncodingUtilHelper.quotate(getEmail()) + ",";
strColumns += EncodingUtilHelper.quotate(getWeb());
return strColumns;
}
@Override
public String toPairs() {
String strPairs = "";
// strPairs += "nombre=" + EncodingUtilHelper.quotate(nombre) + ",";
// strPairs += "razon_social=" + EncodingUtilHelper.quotate(razon_social) + ",";
// strPairs += "nif=" + EncodingUtilHelper.quotate(nif) + ",";
// strPairs += "direccion=" + EncodingUtilHelper.quotate(direccion) + ",";
// strPairs += "poblacion=" + EncodingUtilHelper.quotate(poblacion) + ",";
// strPairs += "provincia=" + EncodingUtilHelper.quotate(provincia) + ",";
// strPairs += "provincia=" + EncodingUtilHelper.quotate(pais) + ",";
// strPairs += "codigopostal=" + EncodingUtilHelper.quotate(codigopostal) + ",";
// strPairs += "telefono=" + EncodingUtilHelper.quotate(telefono) + ",";
// strPairs += "email=" + EncodingUtilHelper.quotate(email) + ",";
// strPairs += "web=" + EncodingUtilHelper.quotate(web);
Boolean hay = false;
if (nombre != null) {
strPairs += "nombre=" + EncodingUtilHelper.quotate(nombre);
hay = true;
}
if (razon_social != null) {
strPairs += (hay) ? ",razon_social=" : "razon_social=";
strPairs += EncodingUtilHelper.quotate(razon_social);
hay = true;
}
if (nif != null) {
strPairs += (hay) ? ",nif=" : "nif=";
strPairs += EncodingUtilHelper.quotate(nif);
hay = true;
}
if (direccion != null) {
strPairs += (hay) ? ",direccion=" : "direccion=";
strPairs += EncodingUtilHelper.quotate(direccion);
hay = true;
}
if (poblacion != null) {
strPairs += (hay) ? ",poblacion=" : "poblacion=";
strPairs += EncodingUtilHelper.quotate(poblacion);
hay = true;
}
if (provincia != null) {
strPairs += (hay) ? ",provincia=" : "provincia=";
strPairs += EncodingUtilHelper.quotate(provincia);
hay = true;
}
if (pais != null) {
strPairs += (hay) ? ",pais=" : "pais=";
strPairs += EncodingUtilHelper.quotate(pais);
hay = true;
}
if (codigopostal != null) {
strPairs += (hay) ? ",codigopostal=" : "codigopostal=";
strPairs += EncodingUtilHelper.quotate(codigopostal);
hay = true;
}
if (telefono != null) {
strPairs += (hay) ? ",telefono=" : "telefono=";
strPairs += EncodingUtilHelper.quotate(telefono);
hay = true;
}
if (email != null) {
strPairs += (hay) ? ",email=" : "email=";
strPairs += EncodingUtilHelper.quotate(email);
hay = true;
}
if (web != null) {
strPairs += (hay) ? ",web=" : "web=";
strPairs += EncodingUtilHelper.quotate(web);
}
return strPairs;
}
@Override
public SociedadBean fill(ResultSet oResultSet, Connection pooledConnection, PusuarioBean oPuserBean_security, Integer expand) throws SQLException, Exception {
this.setId(oResultSet.getInt("id"));
this.setNombre(oResultSet.getString("nombre"));
this.setRazon_social(oResultSet.getString("razon_social"));
this.setNif(oResultSet.getString("nif"));
this.setDireccion(oResultSet.getString("direccion"));
this.setPoblacion(oResultSet.getString("poblacion"));
this.setProvincia(oResultSet.getString("provincia"));
this.setPais(oResultSet.getString("pais"));
this.setCodigopostal(oResultSet.getString("codigopostal"));
this.setTelefono(oResultSet.getString("telefono"));
this.setEmail(oResultSet.getString("email"));
this.setWeb(oResultSet.getString("web"));
return this;
}
}
| true
|
4a696508dd9ff114889064448443c371ccb8547c
|
Java
|
4lch4/Hermes_Android
|
/app/src/main/java/com/devinl/hermes/fragments/HomeFragment.java
|
UTF-8
| 3,838
| 2.515625
| 3
|
[] |
no_license
|
package com.devinl.hermes.fragments;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import com.devinl.hermes.R;
import com.devinl.hermes.services.HermesService;
/**
* A simple {@link Fragment} subclass for the Home fragment.
*/
public class HomeFragment extends Fragment {
private Button mPrimaryBtn;
public HomeFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.content_main, container, false);
mPrimaryBtn = (Button) rootView.findViewById(R.id.primaryBtn);
updateButton();
return rootView;
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
}
@Override
public void onDetach() {
super.onDetach();
}
/**
* Update the {@link Button} that starts/stops the {@link HermesService}. If the service is
* running, set the background to the pause icon and use the {@link #getPauseButtonListener()}.
* If the service isn't running, sets the background to the play icon and use the
* {@link #getStartButtonListener()}.
*/
private void updateButton() {
if (isHermesServiceOn(getContext())) {
mPrimaryBtn.setText(getText(R.string.pause_button_desc));
mPrimaryBtn.setOnClickListener(getPauseButtonListener());
} else {
mPrimaryBtn.setText(getText(R.string.start_button_desc));
mPrimaryBtn.setOnClickListener(getStartButtonListener());
}
}
/**
* Build and return the {@link android.view.View.OnClickListener} for the mStartButton that
* starts the service if it isn't currently running.
*
* @return {@link android.view.View.OnClickListener}
*/
public View.OnClickListener getStartButtonListener() {
return new View.OnClickListener() {
@Override
public void onClick(View view) {
if (!isHermesServiceOn(getContext()))
getActivity().startService(new Intent(getContext(), HermesService.class));
updateButton();
}
};
}
/**
* Build and return the {@link android.view.View.OnClickListener} for the mPauseButton that
* stops the service if it is running.
*
* @return {@link android.view.View.OnClickListener}
*/
public View.OnClickListener getPauseButtonListener() {
return new View.OnClickListener() {
@Override
public void onClick(View view) {
if (isHermesServiceOn(getContext()))
getActivity().stopService(new Intent(getContext(), HermesService.class));
updateButton();
}
};
}
/**
* Check to see if {@link HermesService} is currently running and return a boolean indicating the
* answer.
*
* @return {@link Boolean}
*/
public static boolean isHermesServiceOn(Context context) {
ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (HermesService.class.getName().equals(service.service.getClassName()))
return true;
}
return false;
}
}
| true
|
a8bbb74448718447e27da94ac2af2ffda0ec6029
|
Java
|
lukeharrison95/MyDevProjectBackend
|
/src/main/java/com/DM/demo/Util/PlayerNotFoundException.java
|
UTF-8
| 248
| 1.585938
| 2
|
[] |
no_license
|
package com.DM.demo.Util;
import javax.persistence.EntityNotFoundException;
public class PlayerNotFoundException extends EntityNotFoundException{
/**
*
*/
private static final long serialVersionUID = -7345397540802437683L;
}
| true
|
852f6ce6cc0077473219014f4e8dd1fb924d4e10
|
Java
|
DataScientists/OccIDEAS
|
/src/main/java/org/occideas/mapper/InterviewModuleMapperImpl.java
|
UTF-8
| 2,638
| 2.15625
| 2
|
[
"MIT"
] |
permissive
|
package org.occideas.mapper;
import org.occideas.entity.InterviewModule;
import org.occideas.vo.InterviewModuleVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
@Component
public class InterviewModuleMapperImpl implements InterviewModuleMapper {
@Autowired
private InterviewQuestionMapper iqMapper;
@Override
public InterviewModuleVO convertToInterviewModuleVO(InterviewModule entity) {
if (entity == null) {
return null;
}
InterviewModuleVO vo = new InterviewModuleVO();
vo.setCount(entity.getCount());
vo.setDeleted(entity.getDeleted());
vo.setIdInterview(entity.getIdInterview());
vo.setIdNode(entity.getIdNode());
vo.setName(entity.getName());
vo.setNumber(entity.getNumber());
vo.setParentAnswerId(entity.getParentAnswerId());
vo.setParentNode(entity.getParentNode());
vo.setAnswerNode(entity.getAnswerNode());
vo.setSequence(entity.getSequence());
vo.setTopNodeId(entity.getTopNodeId());
vo.setQuestionsAsked(iqMapper.convertToInterviewQuestionVOList(entity.getQuestionsAsked()));
return vo;
}
@Override
public List<InterviewModuleVO> convertToInterviewModuleVOList(List<InterviewModule> entity) {
if (entity == null) {
return null;
}
List<InterviewModuleVO> list = new ArrayList<>();
for (InterviewModule mod : entity) {
list.add(convertToInterviewModuleVO(mod));
}
return list;
}
@Override
public InterviewModule convertToInterviewModule(InterviewModuleVO vo) {
if (vo == null) {
return null;
}
InterviewModule entity = new InterviewModule();
entity.setCount(vo.getCount());
entity.setDeleted(vo.getDeleted());
entity.setIdInterview(vo.getIdInterview());
entity.setIdNode(vo.getIdNode());
entity.setName(vo.getName());
entity.setNumber(vo.getNumber());
entity.setParentAnswerId(vo.getParentAnswerId());
entity.setParentNode(vo.getParentNode());
entity.setAnswerNode(vo.getAnswerNode());
entity.setSequence(vo.getSequence());
entity.setTopNodeId(vo.getTopNodeId());
entity.setQuestionsAsked(iqMapper.convertToInterviewQuestionList(vo.getQuestionsAsked()));
return entity;
}
@Override
public List<InterviewModule> convertToInterviewModuleList(List<InterviewModuleVO> voList) {
if (voList == null) {
return null;
}
List<InterviewModule> list = new ArrayList<>();
for (InterviewModuleVO mod : voList) {
list.add(convertToInterviewModule(mod));
}
return list;
}
}
| true
|
679dc5cb45783edbbd74f5d273e1253729f42e9a
|
Java
|
elbarbero/TrabajosJavaClase
|
/NetBeansProjects/Ejercicio4.Colecciones.JFrame/src/modelo/Usuario.java
|
UTF-8
| 3,760
| 3.1875
| 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 modelo;
import java.util.ArrayList;
/**
*
* @author Mario
*/
public class Usuario {
private String nombre, login, password;
private int tipo;//Para saber si es admin o es un nempleado
private ArrayList<Agenda> bEntrada;
public Usuario(String nombre, String login, String password) {// es constructor lo creamos para dar de alta a los empleados
this.nombre = nombre;
this.login = login;
this.password = password;
this.bEntrada = new ArrayList<>(); // AL CREAR EL USUARIO NO TENDREMOS MAILS PERO CREAREMOS EL ESPACIO PARA GUARDARLOS
// PERO bENTRADA NO ESTARA EN EL METODO DEL CONSTRUCTOR
}
public Usuario(String nombre, String login, String password, int tipo) {// es constructor lo creamos el admin
this.nombre = nombre;
this.login = login;
this.password = password;
this.tipo = tipo;
this.bEntrada = new ArrayList<>(); // AL CREAR EL USUARIO NO TENDREMOS MAILS PERO CREAREMOS EL ESPACIO PARA GUARDARLOS
// PERO bENTRADA NO ESTARA EN EL METODO DEL CONSTRUCTOR
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getPassword() {
return password;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public void setPassword(String password) {
this.password = password;
}
public ArrayList<Agenda> getbEntrada() {
return bEntrada;//me devuelve una coleccion de correos
}
public void setbEntrada(ArrayList<Agenda> bEntrada) {
this.bEntrada = bEntrada;
}
public int getTipo() {
return tipo;
}
@Override
public String toString() {
/*Con el metodo toString nos muestra el nombre en vez de la direccion
de la memoria donde se guarda*/
return nombre;
}
/**
* Busca evento por evento si hay alguno con el mismo día y/o hora y lo
* compara con el que estamos introduciendo
*
* @param hora la hora introducida en el evento que estamos introduciendo
* @param fecha la fecha completa introducida en el evento que estamos
* introduciendo
* @return devuelve un boolean (verdadero o falso)
*/
public boolean buscarFechaEvento(String hora, String fecha) {
int i = 0;
boolean encontrado = false;
while (!encontrado && i < bEntrada.size()) {
if (fecha.compareToIgnoreCase(bEntrada.get(i).getFecha()) == 0) {
if (hora.compareToIgnoreCase(bEntrada.get(i).getHora()) == 0) {
encontrado = true;
} else {
i++;
}
} else {
i++;
}
}
return encontrado;
}
/**
* Busca evento por evento si hay alguno con el mismo nombre y lo compara
* con el que estamos introduciendo
*
* @param nombre el nombre introducida en el evento que estamos
* introduciendo
* @return devuelve un boolean (verdadero o falso)
*/
public boolean buscarNombreEvento(String nombre) {
int i = 0;
boolean encontrado = false;
while (!encontrado && i < bEntrada.size()) {
if (nombre.compareToIgnoreCase(bEntrada.get(i).getNombre()) == 0) {
encontrado = true;
} else {
i++;
}
}
return encontrado;
}
}
| true
|
b4ee767c8d709a91110fcc3d292db6bbefaa1e4d
|
Java
|
archwu/INFO-5100-SP-2020
|
/assignment4/src/IceCream.java
|
UTF-8
| 375
| 2.8125
| 3
|
[] |
no_license
|
public class IceCream extends DessertItem {
int cost;
public IceCream(String name, int cost){
super(name);
this.cost = cost;
}
@Override
public int getCost() {
return cost;
}
//TODO
public String getString() {
return String.format("%-30s%5s\n", name, DessertShoppe.cents2dollarsAndCents(getCost()));
}
}
| true
|
432efbacbe2ef58ee09f91febb1399ac605f31b1
|
Java
|
lucasjadami/bomberboys
|
/client/src/main/java/com/bomberboys/game/Bomb.java
|
UTF-8
| 2,272
| 2.84375
| 3
|
[] |
no_license
|
package com.bomberboys.game;
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import java.io.IOException;
import com.bomberboys.ui.Images;
public class Bomb extends MapObject {
private static final String[] sprites = {"bomb1", "bomb2", "bomb3", "bomb4"};
private int state;
private float accelerate_tax;
private int explosionRadius;
private int animationTimeout;
private int explosionStage;
public Bomb(int x, int y) {
super(x, y);
accelerate_tax = 1;
state = 0;
explosionStage = 0;
explosionRadius = 0;
animationTimeout = 100;
}
public void explode() {
explosionStage = 1;
}
@Override
public void draw(Graphics2D g) {
if (animationInProgress) {
switch (explosionStage) {
case 0: drawBomb(g); break;
case 1: drawExplosion(g); break;
}
}
}
private void drawBomb(Graphics2D g) {
state = (int)(state + accelerate_tax) % 40;
accelerate_tax += 0.03;
BufferedImage sprite = Images.get(sprites[state / 10]);
int size = sprite.getHeight();
g.drawImage(sprite, x - size / 2, MAP_HEIGHT - (y + size / 2), null);
}
private void drawExplosion(Graphics2D g) {
drawRuins(g);
drawBoom(g);
explosionRadius = explosionRadius < 250 ? explosionRadius + 10 : 255;
animationTimeout -= 1;
if (animationTimeout < 0) animationInProgress = false;
}
private void drawRuins(Graphics2D g) {
BufferedImage sprite = Images.get("crater1");
int size = sprite.getHeight();
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, animationTimeout * 0.01f));
g.drawImage(sprite, x - size / 2, MAP_HEIGHT - (y + size / 2), null);
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1));
}
private void drawBoom(Graphics2D g) {
g.setColor(new Color(255, 0, 0, 255 - explosionRadius));
g.fillArc(x - explosionRadius, MAP_HEIGHT - (y + explosionRadius),
explosionRadius * 2, explosionRadius * 2, 0, 360);
}
}
| true
|
267f67fed13ba5ad6940ea4f1b42d7c4015f9195
|
Java
|
jeffcanas13/mytest
|
/src/main/java/adec/tech/atms/validation/validator/VerticalValidator.java
|
UTF-8
| 975
| 2.421875
| 2
|
[] |
no_license
|
package adec.tech.atms.validation.validator;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import org.springframework.beans.factory.annotation.Autowired;
import adec.tech.atms.config.Constants;
import adec.tech.atms.repository.VerticalRepository;
import adec.tech.atms.validation.annotation.ValidVertical;
public class VerticalValidator implements ConstraintValidator<ValidVertical, String>{
@Autowired
private VerticalRepository verticalRepository;
@Override
public void initialize(ValidVertical constraintAnnotation) {
}
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
context.disableDefaultConstraintViolation();
int v = Integer.parseInt(value);
if(!verticalRepository.isVerticalExisting(v)) {
context.buildConstraintViolationWithTemplate(Constants.VERTICAL_DOES_NOT_EXIST).addConstraintViolation();
return false;
}
return true;
}
}
| true
|
8648f186d4d4f9472c66e2c4beade0670f268d10
|
Java
|
aartisoft/QuickRideAndroid
|
/quickRide/src/main/java/com/disha/quickride/androidapp/ecometer/RideSharingCommunityContributionGettingAsyncTask.java
|
UTF-8
| 2,920
| 2.078125
| 2
|
[] |
no_license
|
package com.disha.quickride.androidapp.ecometer;
import android.content.Context;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import com.disha.quickride.androidapp.usermgmt.cache.UserDataCache;
import com.disha.quickride.androidapp.usermgmt.cache.UserDataCacheReceiver;
import com.disha.quickride.androidapp.util.ProgressDialog;
import com.disha.quickride.domain.model.RideSharingCommunityContribution;
public class RideSharingCommunityContributionGettingAsyncTask extends AsyncTask<Void,Void,Throwable> {
private Context activity;
private long userId;
private RideSharingCommunityContribution rideSharingCommunityContribution;
//private RideSharingCommunityContributionReceiver rideSharingCommunityContributionReceiver;
private UserDataCacheReceiver userDataCacheReceiver;
private ProgressDialog progressDialog;
private boolean isReqProgress;
public RideSharingCommunityContributionGettingAsyncTask(Context activity, long userId,
UserDataCacheReceiver clientRef, boolean isReqProgress) {
this.activity = activity;
this.userId = userId;
this.userDataCacheReceiver = clientRef;
this.isReqProgress = isReqProgress;
}
@Override
protected void onPreExecute() {
if (!isReqProgress) return;
progressDialog = new ProgressDialog((AppCompatActivity) activity);
progressDialog.show();
}
@Override
protected Throwable doInBackground(Void... params) {
try {
rideSharingCommunityContribution = UserAnalyticsClient.getUserRideSharingCommunityContribution(activity, userId);
} catch (Throwable th) {
return th;
}
return null;
}
@Override
protected void onPostExecute(Throwable throwable) {
if (progressDialog != null) progressDialog.dismiss();
if (throwable != null) {
//ErrorProcessUtil.processException(activity,throwable,false,null);
if (userDataCacheReceiver != null)
userDataCacheReceiver.receiveDataFromCacheFailed(throwable);
//return;
} else {
UserDataCache userDataCache = UserDataCache.getCacheInstance();
if (userDataCache != null) {
// UserDataCache can be null if by the time this async task gets executed, some
// exception occurred which resulted in clearUserSession being called which in turn
// removes the user data cache instance
userDataCache.receiveUserInformationFromServer(rideSharingCommunityContribution, userDataCacheReceiver);
}
}
/* public interface RideSharingCommunityContributionReceiver
{
void receivedRideSharingCommunityContribution(RideSharingCommunityContribution rideSharingCommunityContribution);
}*/
}
}
| true
|
10f877ac52eb93acfae883b8a748cc01695acdf4
|
Java
|
sengeiou/workspace_xg
|
/jfAppService/src/main/java/com/jf/entity/MchtInfoCustom.java
|
UTF-8
| 2,930
| 1.960938
| 2
|
[] |
no_license
|
package com.jf.entity;
import java.math.BigDecimal;
import java.util.List;
public class MchtInfoCustom extends MchtInfo{
private Integer sourceNicheId;
private String storyIntroduction;
private String productIds;
private String oldProductIds;
private List<ProductCustom> productCustomList;
private String couponIds;
private List<Coupon> couponList;
private Integer totalSaleQuantity;
private Integer goodCommentCount;
private Integer totalCommentCount;
private String shopSalesAndCommentRate;
private Integer productSaleCount90Day;
private BigDecimal productApplauseRate;
public Integer getSourceNicheId() {
return sourceNicheId;
}
public void setSourceNicheId(Integer sourceNicheId) {
this.sourceNicheId = sourceNicheId;
}
public String getStoryIntroduction() {
return storyIntroduction;
}
public void setStoryIntroduction(String storyIntroduction) {
this.storyIntroduction = storyIntroduction;
}
public List<ProductCustom> getProductCustomList() {
return productCustomList;
}
public void setProductCustomList(List<ProductCustom> productCustomList) {
this.productCustomList = productCustomList;
}
public String getProductIds() {
return productIds;
}
public void setProductIds(String productIds) {
this.productIds = productIds;
}
public String getCouponIds() {
return couponIds;
}
public void setCouponIds(String couponIds) {
this.couponIds = couponIds;
}
public List<Coupon> getCouponList() {
return couponList;
}
public void setCouponList(List<Coupon> couponList) {
this.couponList = couponList;
}
public String getOldProductIds() {
return oldProductIds;
}
public void setOldProductIds(String oldProductIds) {
this.oldProductIds = oldProductIds;
}
public Integer getTotalSaleQuantity() {
return totalSaleQuantity;
}
public void setTotalSaleQuantity(Integer totalSaleQuantity) {
this.totalSaleQuantity = totalSaleQuantity;
}
public Integer getGoodCommentCount() {
return goodCommentCount;
}
public void setGoodCommentCount(Integer goodCommentCount) {
this.goodCommentCount = goodCommentCount;
}
public Integer getTotalCommentCount() {
return totalCommentCount;
}
public void setTotalCommentCount(Integer totalCommentCount) {
this.totalCommentCount = totalCommentCount;
}
public String getShopSalesAndCommentRate() {
return shopSalesAndCommentRate;
}
public void setShopSalesAndCommentRate(String shopSalesAndCommentRate) {
this.shopSalesAndCommentRate = shopSalesAndCommentRate;
}
public Integer getProductSaleCount90Day() {
return productSaleCount90Day;
}
public void setProductSaleCount90Day(Integer productSaleCount90Day) {
this.productSaleCount90Day = productSaleCount90Day;
}
public BigDecimal getProductApplauseRate() {
return productApplauseRate;
}
public void setProductApplauseRate(BigDecimal productApplauseRate) {
this.productApplauseRate = productApplauseRate;
}
}
| true
|
62a2855786ba2f8780f08355be3f5bbae2385d3e
|
Java
|
dudals4824/android-extract-gif-develop
|
/android-extract-gif/app/src/main/java/com/naver/hackday/android_extract_gif/database/GIFDao.java
|
UTF-8
| 457
| 2.25
| 2
|
[] |
no_license
|
package com.naver.hackday.android_extract_gif.database;
import android.arch.persistence.room.Dao;
import android.arch.persistence.room.Delete;
import android.arch.persistence.room.Insert;
import android.arch.persistence.room.Query;
import java.util.List;
@Dao
public interface GIFDao {
@Query("SELECT * FROM gif")
List<GifEntry> getAll();
@Insert
void insertGIF(GifEntry gifEntry);
@Delete
void deleteGIF(GifEntry gifEntry);
}
| true
|
0d82eb9fb2c1545d25b9f0b46bd174301b97180e
|
Java
|
TechGitRepo2020/AkashSatputePortfolio
|
/BookStoreApplication/src/main/java/com/nt/service/BookServiceImpl.java
|
UTF-8
| 662
| 2.546875
| 3
|
[] |
no_license
|
package com.nt.service;
import com.nt.bo.BookBO;
import com.nt.dao.BookDAOImpl;
import com.nt.dao.IBookDAO;
import com.nt.dto.BookDTO;
public class BookServiceImpl implements IBookService {
private IBookDAO dao;
public BookServiceImpl() {
dao=new BookDAOImpl();
}
@Override
public String Storebook(BookDTO dto) throws Exception {
BookBO bo=new BookBO();
//prepare bo obj
bo.setBname(dto.getBname());
bo.setBauthor(dto.getBauthor());
bo.setBprice(dto.getBprice());
bo.setBqty(dto.getBqty());
//call dao method
int count=dao.insertBook(bo);
return count==0?"Book is not stored":"Book is stored";
}
}
| true
|
b8a9638de11156aaa0942e29a31ed0e0a45b4eb1
|
Java
|
raulgarciadevop/SweetControl
|
/app/src/main/java/com/youngwaresoft/sweetcontrol/MyAdapter.java
|
UTF-8
| 1,170
| 2.46875
| 2
|
[
"MIT"
] |
permissive
|
package com.youngwaresoft.sweetcontrol;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
private String[] mDataset;
public static class MyViewHolder extends RecyclerView.ViewHolder{
public TextView textView;
public MyViewHolder(TextView v){
super(v);
textView=v;
}
}
public MyAdapter(String[] myDataset){
mDataset=myDataset;
}
@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
TextView v=(TextView) LayoutInflater.from(parent.getContext()).inflate(R.layout.my_text_view, parent,false);
MyViewHolder vh = new MyViewHolder(v);
return vh;
}
@Override
public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
holder.textView.setText(mDataset[position]);
}
@Override
public int getItemCount() {
return mDataset.length;
}
}
| true
|
a3be6eae8800ca3b21bf3608a76a90c063b55a8f
|
Java
|
christianmanzi/MTNECWAgentProd
|
/src/java/mtnecwagent/logic/AbstractMMHandler.java
|
UTF-8
| 516
| 1.8125
| 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 mtnecwagent.logic;
import java.io.InputStream;
/**
*
* @author aimable
*/
public abstract class AbstractMMHandler {
public AbstractMMHandler(){
}
public void sendMessage(String url,Object message){
}
public void receiveMessage(InputStream stream){
}
}
| true
|
3bb588dd369a26cd2cf3b47e8452d5ab74eaf9e5
|
Java
|
zshunxiang/database
|
/src/main/java/first/StudentDao.java
|
UTF-8
| 2,805
| 2.828125
| 3
|
[] |
no_license
|
package first;
import com.mysql.jdbc.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import common.*;
public class StudentDao {
private MyDB myDB=new MyDB();
public int insertStudent(Student student){
int i = 0;
String sql = "insert into student (department,stuNo,name,sex,school,dormitory,charge) values(?,?,?,?,?,?,?)";
try {
myDB.pstmt = (PreparedStatement) myDB.connection.prepareStatement(sql);
myDB.pstmt.setString(1, student.getDepartment());
myDB.pstmt.setString(2, student.getStuNo());
myDB.pstmt.setString(3, student.getName());
myDB.pstmt.setString(4, student.getSex());
myDB.pstmt.setString(5, student.getSchool());
myDB.pstmt.setString(6, student.getDormitory());
myDB.pstmt.setLong(7, student.getCharge());
i = myDB.pstmt.executeUpdate();
System.out.println("成功插入一条学生数据");
} catch (SQLException e) {
e.printStackTrace();
}
return i;
}
public List<String> getDepartment(String name){
String sql = "select distinct(a.department) from student a,student b where a.dormitory=b.dormitory and b.name='"+name+"'";
List<String> strings=new ArrayList<String>();
try{
myDB.pstmt=(PreparedStatement)myDB.connection.prepareStatement(sql);
myDB.rs=myDB.pstmt.executeQuery();
while (myDB.rs.next()){
strings.add(myDB.rs.getString(1));
}
}catch (SQLException e){
e.printStackTrace();
}
return strings;
}
public void update(String sql){
try {
myDB.pstmt = (PreparedStatement) myDB.connection.prepareStatement(sql);
myDB.pstmt.executeUpdate();
}catch (SQLException e){
e.printStackTrace();
}
}
public Student select(String name){
String sql="select * from student where name='"+name+"'";
Student student=new Student();
try{
myDB.pstmt=(PreparedStatement)myDB.connection.prepareStatement(sql);
myDB.rs=myDB.pstmt.executeQuery();
while (myDB.rs.next()) {
student.setDepartment(myDB.rs.getString(0));
student.setStuNo(myDB.rs.getString(1));
student.setName(myDB.rs.getString(2));
student.setSex(myDB.rs.getString(3));
student.setSchool(myDB.rs.getString(4));
student.setDormitory(myDB.rs.getString(5));
student.setCharge(myDB.rs.getLong(6));
}
}catch (SQLException e){
e.printStackTrace();
}
return student;
}
}
| true
|
74dc87f21fe79152b85afb141e10d633dbac372f
|
Java
|
TaylorHarvin/LegoSoccer
|
/LEGO_S_NEWEST/src/fullSoccer/SensorControl.java
|
UTF-8
| 6,511
| 2.4375
| 2
|
[] |
no_license
|
package fullSoccer;
import java.io.FileNotFoundException;
import java.io.FileReader;
import lejos.hardware.Button;
import lejos.hardware.port.Port;
import lejos.hardware.sensor.EV3UltrasonicSensor;
import lejos.hardware.sensor.HiTechnicCompass;
import lejos.hardware.sensor.HiTechnicIRSeekerV2;
import lejos.robotics.SampleProvider;
import lejos.robotics.localization.CompassPoseProvider;
import lejos.utility.Delay;
import lejos.hardware.DeviceException;
public class SensorControl {
private SampleProvider irSeekModeMod; // Gets value for modulated IR
private SampleProvider irSeekModeUnMod; // Gets value for unmodulated IR
private SampleProvider distMode; // Gets value for sonar
private float[] distanceSample; // The actual sonar value -- RAW
private float[] irSample; // The actual IR value -- RAW
//private HiTechnicCompass compassSensor; // The actual compass
//private SampleProvider compassSP; // compass sample provider
private float ballDirMod = 9999; // Last read IR Mod value
private float ballDirUnMod = 9999; // Last read IR Un-Mod value
private float sonarRead = 9999;
// Simulation parts
private FileReader simFileReader;
private boolean simMode;
EV3UltrasonicSensor sonarSensor = null; // Actual Sonar sensor
HiTechnicIRSeekerV2 irSensor = null; // Actual IR Seeker
/* Base Sensor Control constructor
* Preconditions:
* 1. Valid sonar port given
* 1.1. sonar connected
* 2. Valid ir port given
* 2.1. ir connected
* 3. Valid compass port given
* 3.1. compass connected
* 4. correct mode given
* Postconditions:
* 1. IR sampler setup
* 2. Sonar sampler setup
* 3. compass sampler setup
*/
public SensorControl(Port sonarPort, Port irPort, Port compassPort, boolean simulatorMode){
simMode = simulatorMode;
if(!simMode){
try{
if(sonarSensor == null && irSensor == null){
System.out.println("SEN SETUP");
sonarSensor = new EV3UltrasonicSensor(sonarPort);
irSensor = new HiTechnicIRSeekerV2(irPort);
}
else{
System.out.println("SensorPorts already in use!");
}
}
catch(DeviceException portError){
System.out.println("Sensor ports already setup!");
System.out.println("Closing SensorControl Setup");
//sonarSensor = new EV3UltrasonicSensor(sonarPort);
//irSensor = new HiTechnicIRSeekerV2(irPort);
return;
}
distMode = sonarSensor.getDistanceMode();
distanceSample = new float[distMode.sampleSize()];
irSeekModeMod = irSensor.getModulatedMode();
irSeekModeUnMod = irSensor.getUnmodulatedMode();
irSample = new float[irSeekModeMod.sampleSize()];
//compassPort = LocalEV3.get().getPort("S4");
//compassSensor = new HiTechnicCompass(compassPort);
//compassSP = compassSensor.getCompassMode();
//************Compass Calibration************************//
/*System.out.println("Calib Compass? -- UP");
if(Button.waitForAnyPress() == Button.ID_UP){
System.out.println("Start Calib");
//compassSensor.startCalibration();
Button.waitForAnyPress();
//compassSensor.stopCalibration();
System.out.println("End Calib");
}*/
}
else{
/*try {
simFileReader = new FileReader("simData/sensorData.txt");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
}
}
// Just returns the last read modulated IR
public float getLastModIR(){
return ballDirMod;
}
// Just returns the last read Unmodulated IR
public float getLastUnModIR(){
return ballDirUnMod;
}
// Just returns the last read sonar
public float getLastSonar(){
return sonarRead;
}
public float pingSonar(){
float tmpDist[] = new float[2];
distMode.fetchSample(tmpDist, 0);
Delay.msDelay(50);
return tmpDist[0];
}
public float pingIr(boolean modulated){
float tmpIr[] = new float[2];
if(modulated){
irSeekModeMod.fetchSample(tmpIr, 0);
}
else{
irSeekModeUnMod.fetchSample(tmpIr, 0);
}
Delay.msDelay(50);
return tmpIr[0];
}
/* Get the ball distance value relative to the robot
* Preconditions:
* 1. sonar is initialized to the correct port
* 2. sonar is working
* Postconditions:
* 1. Returns true
* 1.1. Some object is seen by sonar
* 2. Returns false
* 2.1. No object is seen
* 2.1.1. OR sonar read failed
* 2.1.1. AND/OR robot's batteries are low
*/
public boolean fetchSonarVal(){
if(!simMode){
distMode.fetchSample(distanceSample, 0);
//System.out.println(distanceSample[0]);
Delay.msDelay(50);
sonarRead = distanceSample[0];
}
else{
// Grab value from file or DB here if in sim
}
// Check for valid sonar value
if(!Float.isNaN(sonarRead)){
if(sonarRead <= 0)
sonarRead = 9999;
return true;
}
else
return false;
}
/* Get the ball angle relative to the robot
* Preconditions:
* 1. IR Seeker is initialized to the correct port
* 2. IR Seeker is functioning properly
* Postconditions:
* 1. Returns IR read : float
* 1.1. Valid Mod-IR read
* 1.1.1. OR valid Un-Mod IR read
* 1.2. Ball heading in relation to robot returned for requested mode
*/
public boolean fetchAngleVal(boolean modulated){
if(!simMode){
if(modulated){
irSeekModeMod.fetchSample(irSample, 0);
ballDirMod = irSample[0];
}
else{
irSeekModeUnMod.fetchSample(irSample, 0);
ballDirUnMod = irSample[0];
}
//System.out.println(irSample[0]);
Delay.msDelay(50);
}
else{
}
if(!Float.isNaN(irSample[0])){
return true;
}
else
return false;
//return irSample[0];
}
/* Tells the IR reads of the robot in relation to the ball signal
* Preconditions:
* 1. IR Seeker is initialized to the correct port
* 2. IR Seeker is functioning properly
* Postconditions:
* 1. Returns true
* 1.1. Valid Mod-IR read
* 1.1.1. and/or valid Un-Mod IR read
* 1.2. Ball heading in relation to robot stored
* in the class variables:
* - ballDirMod
* - ballDirUnMod
* 2. Returns false
* 2.1. The ball is at an unreadable angle to the robot
* 2.1.1. OR The ball is off or batteries are dead.
* 2.1.1. OR The robot's batteries are low.
*/
public boolean getAllIrSig(){
fetchAngleVal(true);
fetchAngleVal(false);
// Verify that an IR signal is read -- this should be at all times
if(!Float.isNaN(ballDirMod) || !Float.isNaN(ballDirUnMod))
return true;
else
return false;
}
}
| true
|
82956de186ea57104931e8d6a21a94f67577659b
|
Java
|
manishee/Sep2020JavaSession2
|
/src/JavaSessions/Ecomm.java
|
UTF-8
| 769
| 2.328125
| 2
|
[] |
no_license
|
//*************** Oct 21 -p2*******************
package JavaSessions;
public class Ecomm {
public static void main(String[] args) {
Ecomm e1=new Ecomm();
e1.search("samsung", 50);
}
public void search() {
}
public void search(String name) {
}
public void search(String name, int price) {
System.out.println(name+ " " + price);
}
public void search(String name, int price, String color) {
}
public void search(String name, String color) {
}
public void login() {
}
public void login(String email, String password) {
}
public void login(long number, String password) {
}
public void payment() {
}
public void payment(long cc, int cvv) {
}
public void payment(int UPI, int OTP)
{
}
}
| true
|
762977d6ee0c2dd007817fd1138b1a06f8ddd964
|
Java
|
deathrat/MineFactoryReloaded
|
/src/powercrystals/minefactoryreloaded/farmables/FertilizableGrass.java
|
UTF-8
| 1,669
| 2.28125
| 2
|
[] |
no_license
|
package powercrystals.minefactoryreloaded.farmables;
import java.util.Random;
import powercrystals.minefactoryreloaded.api.FertilizerType;
import powercrystals.minefactoryreloaded.api.IFactoryFertilizable;
import net.minecraft.block.Block;
import net.minecraft.world.World;
import net.minecraftforge.common.ForgeHooks;
public class FertilizableGrass implements IFactoryFertilizable
{
@Override
public boolean canFertilizeBlock(World world, int x, int y, int z, FertilizerType fertilizerType)
{
return fertilizerType == FertilizerType.GrowPlant;
}
@Override
public boolean fertilize(World world, Random rand, int x, int y, int z, FertilizerType fertilizerType)
{
if (!world.isRemote)
{
label133:
for (int var12 = 0; var12 < 128; ++var12)
{
int xTemp = x;
int yTemp = y + 1;
int zTemp = z;
for (int var16 = 0; var16 < var12 / 16; ++var16)
{
xTemp += rand.nextInt(3) - 1;
yTemp += (rand.nextInt(3) - 1) * rand.nextInt(3) / 2;
zTemp += rand.nextInt(3) - 1;
if (world.getBlockId(xTemp, yTemp - 1, zTemp) != Block.grass.blockID || world.isBlockNormalCube(xTemp, yTemp, zTemp))
{
continue label133;
}
}
if (world.getBlockId(xTemp, yTemp, zTemp) == 0)
{
if (rand.nextInt(10) != 0)
{
if (Block.tallGrass.canBlockStay(world, xTemp, yTemp, zTemp))
{
world.setBlockAndMetadataWithNotify(xTemp, yTemp, zTemp, Block.tallGrass.blockID, 1);
}
}
else
{
ForgeHooks.plantGrass(world, xTemp, yTemp, zTemp);
}
}
}
}
return true;
}
@Override
public int getFertilizableBlockId()
{
return Block.grass.blockID;
}
}
| true
|
d9bb8537e3d04b198d780413c5ca5ba13a5a2318
|
Java
|
lijian12388806/WSP
|
/src/com/liveneo/plat/web/form/mgr/MgrWoDefineForm.java
|
UTF-8
| 2,595
| 1.640625
| 2
|
[] |
no_license
|
package com.liveneo.plat.web.form.mgr;
import com.liveneo.plat.web.form.base.BaseForm;
public class MgrWoDefineForm extends BaseForm {
private static final long serialVersionUID = 1L;
private java.lang.String defType;
private java.lang.String defCol;
private java.lang.String defCanedit;
private java.lang.String defColTitle;
private java.lang.String defColType;
private java.lang.String defColFormat;
private java.lang.String defColLmin;
private java.lang.String defColLmax;
private java.lang.String defColClass;
private java.lang.String defColRequired;
private java.lang.String defColRegion;
private java.lang.String defColOrder;
public java.lang.String getDefType() {
return defType;
}
public void setDefType(java.lang.String defType) {
this.defType = defType;
}
public java.lang.String getDefCol() {
return defCol;
}
public void setDefCol(java.lang.String defCol) {
this.defCol = defCol;
}
public java.lang.String getDefColTitle() {
return defColTitle;
}
public void setDefColTitle(java.lang.String defColTitle) {
this.defColTitle = defColTitle;
}
public java.lang.String getDefColType() {
return defColType;
}
public void setDefColType(java.lang.String defColType) {
this.defColType = defColType;
}
public java.lang.String getDefColLmin() {
return defColLmin;
}
public void setDefColLmin(java.lang.String defColLmin) {
this.defColLmin = defColLmin;
}
public java.lang.String getDefColLmax() {
return defColLmax;
}
public void setDefColLmax(java.lang.String defColLmax) {
this.defColLmax = defColLmax;
}
public java.lang.String getDefColClass() {
return defColClass;
}
public void setDefColClass(java.lang.String defColClass) {
this.defColClass = defColClass;
}
public java.lang.String getDefColOrder() {
return defColOrder;
}
public void setDefColOrder(java.lang.String defColOrder) {
this.defColOrder = defColOrder;
}
public java.lang.String getDefColRequired() {
return defColRequired;
}
public void setDefColRequired(java.lang.String defColRequired) {
this.defColRequired = defColRequired;
}
public java.lang.String getDefColFormat() {
return defColFormat;
}
public void setDefColFormat(java.lang.String defColFormat) {
this.defColFormat = defColFormat;
}
public java.lang.String getDefCanedit() {
return defCanedit;
}
public void setDefCanedit(java.lang.String defCanedit) {
this.defCanedit = defCanedit;
}
public java.lang.String getDefColRegion() {
return defColRegion;
}
public void setDefColRegion(java.lang.String defColRegion) {
this.defColRegion = defColRegion;
}
}
| true
|
4e8b4b27a8d8a276570d315649b1ab9e3a3aac06
|
Java
|
c0deX1/BankSystem
|
/src/com/company/Interfaces/IBankController.java
|
UTF-8
| 330
| 1.710938
| 2
|
[] |
no_license
|
package com.company.Interfaces;
import com.company.dto.PaymentDocumentRq;
import com.company.dto.PaymentDocumentRs;
import java.io.IOException;
public interface IBankController {
PaymentDocumentRs paymentDocumentRqProcess(PaymentDocumentRq rq, boolean fromAnotherBank) throws IOException;
String showAccountsInfo();
}
| true
|
ef7dfa1d157fbf51045ba047b4fd0361090f2954
|
Java
|
IYash/test
|
/src/main/java/com/test/innerclass/OuterClass.java
|
UTF-8
| 1,232
| 3.484375
| 3
|
[] |
no_license
|
package com.test.innerclass;
/**
* @author huangchangling on 2017/8/14 0014
*
* 内部类可以访问外部类的范围
*/
public class OuterClass {
private String outer = "outer";
private static String souter = "souter_hello_world";
public String getOuter(){
return outer;
}
public static String getSouter(){
return souter;
}
public class InnerClass{
private String inner = "inner";
//非静态内部类不能有静态属性,字段
public void init(String newString){
inner = newString;
outer += newString;
}
}
public static class SInnerClass{
private static String sinner = "sinner";
private String nsinner = "nsinner";
public void init(String newString){
nsinner = newString;
}
public static void sinit(String newString){
sinner = newString;
}
}
public InnerClass buildInnerClass(){
new OuterClass.InnerClass();
new OuterClass.SInnerClass();
return new InnerClass();
}
public static void main(String[] args) {
new OuterClass.SInnerClass();
System.out.println("heel");
}
}
| true
|
e5acafd460c62176669af70c9ba9e498d6ca6ed1
|
Java
|
JessenPan/leetcode
|
/algorithms/java/src/test/java/org/jessenpan/leetcode/greedy/S874WalkingRobotSimulationTest.java
|
UTF-8
| 619
| 2.421875
| 2
|
[
"Apache-2.0"
] |
permissive
|
package org.jessenpan.leetcode.greedy;
import org.junit.Assert;
import org.junit.Test;
/**
* @author jessenpan
*/
public class S874WalkingRobotSimulationTest {
private S874WalkingRobotSimulation walkingRobotSimulation = new S874WalkingRobotSimulation();
@Test
public void test1() {
int t = walkingRobotSimulation.robotSim(new int[] { 4, -1, 3 }, new int[][] {});
Assert.assertEquals(25, t);
}
@Test
public void test2() {
int t = walkingRobotSimulation.robotSim(new int[] { 4, -1, 4, -2, 4 }, new int[][] { { 2, 4 } });
Assert.assertEquals(65, t);
}
}
| true
|
3937a1417b2207e4590297bb4a6b42e178b47752
|
Java
|
luvlysehgal/Address-Book
|
/AddressBook.java
|
UTF-8
| 999
| 2.828125
| 3
|
[] |
no_license
|
import java.util.ArrayList;
public class AddressBook {
public static void main(String[] args){
PersonInformation personInformation1 = new PersonInformation("Lovely", "Sehgal",
"Model Town", "Rohtak", "Haryana", 124001L, 8000004990L);
PersonInformation personInformation2 = new PersonInformation("Muskan", "Sharma",
"Bharat colony", "Gurgaon", "Haryana", 124001L, 8529010000L);
PersonInformation personInformation3 = new PersonInformation("Harshita", "Kapoor",
"Shivaji colony", "Panipat", "Haryana", 124001L, 8000002990L);
PersonInformation personInformation4 = new PersonInformation("Prithvi", "Malhotra",
"Power House", "Rewari", "Haryana", 124001L, 8000006440L);
ArrayList<PersonInformation> personalInfo = new ArrayList<PersonInformation>();
personalInfo.add(personInformation1);
personalInfo.add(personInformation2);
personalInfo.add(personInformation3);
personalInfo.add(personInformation4);
}
}
| true
|
d18d610a6510b671e4e5ff2f682b7c7c37a932b2
|
Java
|
tosrikant/interviews
|
/src/main/java/com/interview/company/airbnb/ValidParentheses.java
|
UTF-8
| 1,733
| 3.59375
| 4
|
[] |
no_license
|
package com.interview.company.airbnb;
import java.util.HashMap;
import java.util.Stack;
//https://www.programcreek.com/2012/12/leetcode-valid-parentheses-java/
public class ValidParentheses {
public static boolean isValid2(String s) {
HashMap<Character, Character> map = new HashMap<Character, Character>();
map.put('(', ')');
map.put('[', ']');
map.put('{', '}');
Stack<Character> stack = new Stack<Character>();
for (int i = 0; i < s.length(); i++) {
char curr = s.charAt(i);
if (map.keySet().contains(curr)) {
stack.push(curr);
} else if (map.values().contains(curr)) {
if (!stack.empty() && map.get(stack.peek()) == curr) {
stack.pop();
} else {
return false;
}
}
}
return stack.empty();
}
public boolean isValid1(String s) {
if (s.length() % 2 == 1) {
return false;
}
Stack<Character> stack = new Stack<Character>();
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '(' || s.charAt(i) == '[' || s.charAt(i) == '{') {
stack.push(s.charAt(i));
} else if (s.charAt(i) == ')' && !stack.isEmpty() && stack.peek() == '(') {
stack.pop();
} else if (s.charAt(i) == ']' && !stack.isEmpty() && stack.peek() == '[') {
stack.pop();
} else if (s.charAt(i) == '}' && !stack.isEmpty() && stack.peek() == '{') {
stack.pop();
} else {
return false;
}
}
return stack.isEmpty();
}
}
| true
|
66958bf2f98a00e2abb5fce4ff11a2eb03e78a7a
|
Java
|
Naua-stack/TCC-ControlBusiness
|
/app/src/main/java/com/example/tcc/SuportActivity.java
|
UTF-8
| 2,335
| 2.140625
| 2
|
[] |
no_license
|
package com.example.tcc;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
public class SuportActivity extends AppCompatActivity {
EditText assunto, mensagem;
Button enviar;
ImageButton voltar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.telasuporte);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
voltar = findViewById(R.id.voltarsuporte);
assunto = findViewById(R.id.assunto);
mensagem = findViewById(R.id.problema);
enviar = findViewById(R.id.btnenviarproblema);
voltar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(SuportActivity.this, informationsActivity.class);
startActivity(intent);
}
});
enviar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String stringassunto = assunto.getText().toString();
String stringmensagem = mensagem.getText().toString();
String email = "suportcontrolbusiness@gmail.com";
sendEmail(stringassunto, stringmensagem, email);
}
});
}
private void sendEmail(String stringassunto, String stringmensagem, String email) {
Intent emailIntent = new Intent(Intent.ACTION_SEND);
emailIntent.setData(Uri.parse("mailto:"));
emailIntent.setType("text/plain");
emailIntent.putExtra(Intent.EXTRA_EMAIL, new String[] {email});
emailIntent.putExtra(Intent.EXTRA_SUBJECT, stringassunto);
emailIntent.putExtra(Intent.EXTRA_TEXT, stringmensagem);
try {
startActivity(Intent.createChooser(emailIntent, "Choose an email client"));
}
catch (Exception e){
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}
| true
|
4af8d3b120f423bfc9c829757c7be8e0d1a9a731
|
Java
|
dione/credis-suisse
|
/src/main/java/com/test/EventsCorrelator.java
|
UTF-8
| 116
| 1.515625
| 2
|
[] |
no_license
|
package com.test;
import java.nio.file.Path;
public interface EventsCorrelator {
void checkFile(Path path);
}
| true
|
995487bfc191d0241f326c46d5f0a7473442c4ea
|
Java
|
Anubhav007-hue/Eclipse
|
/Damon/src/Josh/LeavesSum.java
|
UTF-8
| 1,094
| 3.265625
| 3
|
[] |
no_license
|
package Josh;
import Josh.PrintNodeWithOneChild.TreeNode;
public class LeavesSum {
class TreeNode
{
int data;
TreeNode left=null;
TreeNode right=null;
TreeNode (int data)
{
this.data=data;
}
}
public TreeNode insert(int data)
{
TreeNode node=new TreeNode(data);
return node;
}
public static void main(String[] args)
{
LeavesSum p=new LeavesSum();
TreeNode root=null;
root=p.insert(1);
root.left=p.insert(2);
root.right=p.insert(3);
root.left.left=p.insert(4);
root.left.right=p.insert(5);
root.left.left.left=p.insert(8);
root.left.right.right=p.insert(10);
root.right.right=p.insert(7);
root.right.left=p.insert(6);
root.right.left.right=p.insert(11);
int sum[]=new int[1];
getSum(root,sum);
System.out.println(sum[0]);
}
public static void getSum(TreeNode root,int[] sum)
{
if(root==null)
{
return ;
}
if(root.left==null && root.right==null)sum[0]=sum[0]+root.data;
getSum(root.left,sum);
getSum(root.right,sum);
}
}
| true
|
40d68fc311bdc5b9d80f8867adc45ba3a4bfe79b
|
Java
|
goldsenator/goldsenator
|
/account-service/src/main/java/kz/iitu/liquor/eshop/model/UserRoles.java
|
UTF-8
| 621
| 2.015625
| 2
|
[] |
no_license
|
package kz.iitu.liquor.eshop.model;
import lombok.Data;
import javax.persistence.*;
@Entity
@Table(name = "user_role")
@Data
public class UserRoles {
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
Long id;
@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.MERGE)
@JoinColumn(name = "user_id", foreignKey = @ForeignKey(name = "user_role_users_fk"))
private Users user;
@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.MERGE)
@JoinColumn(name = "role_id", foreignKey = @ForeignKey(name = "user_role_roles_fk"))
private Role role;
}
| true
|
780735f63a1438a5e08a7323ab369543b64b40e3
|
Java
|
tvdstorm/sea-of-saf
|
/martijnvdmaas/src/jsaf/game/FightEngine.java
|
UTF-8
| 11,253
| 2.640625
| 3
|
[] |
no_license
|
package jsaf.game;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Random;
import jsaf.astelements.Behaviour;
import jsaf.astelements.Bot;
import jsaf.astelements.Bots;
import jsaf.astelements.Characteristic;
import jsaf.astelements.ConditionChoices;
import jsaf.astelements.ConditionGroup;
import jsaf.constants.SAFConstants;
import jsaf.game.fighter.Fighter;
import jsaf.logger.ErrorLog;
import sun.audio.AudioPlayer;
import sun.audio.AudioStream;
public class FightEngine extends Observable implements SAFConstants
{
private Fighter leftFighter;
private Fighter rightFighter;
private Random randomInt;
private int distance;
private boolean isPlaying;
private String winner = "";
public FightEngine(Bots bots)
{
distance = START_HORIZONTAL_DISTANCE;
isPlaying = true;
randomInt = new Random();
leftFighter = initializeFighter(bots.getLeftBot());
rightFighter = initializeFighter(bots.getRightBot());
}
private Fighter initializeFighter(Bot bot)
{
Fighter fighter = new Fighter(bot.getBotName());
fighter.setCurrentAttack(ATTACK_TYPE_STAND);
fighter.setBehaviours(bot.getBehaviours());
initializeFighterCharacteristics(fighter, bot.getCharacteristics());
return fighter;
}
private void initializeFighterCharacteristics(Fighter safFighter, List<Characteristic> characteristics)
{
for (Characteristic characteristic : characteristics)
{
switch (characteristic.getName())
{
case CHARACTERISTIC_TYPE_PUNCH_REACH:
safFighter.setPunchReach(characteristic.getValue());
break;
case CHARACTERISTIC_TYPE_PUNCH_POWER:
safFighter.setPunchPower(characteristic.getValue());
break;
case CHARACTERISTIC_TYPE_KICK_REACH:
safFighter.setKickReach(characteristic.getValue());
break;
case CHARACTERISTIC_TYPE_KICK_POWER:
safFighter.setKickPower(characteristic.getValue());
break;
}
}
safFighter.setHealth(MAX_HEALTH);
safFighter.setWeight((safFighter.getPunchPower() + safFighter.getKickPower()) / 2);
safFighter.setHeight((safFighter.getPunchReach() + safFighter.getKickReach()) / 2);
safFighter.setSpeed((int) (0.5 * (safFighter.getHeight() - safFighter.getWeight())));
}
public void doStep()
{
if (isPlaying)
{
Behaviour nextLeftBehaviour = getNextRandomApplicableBehaviour(getLeftFighter(), getRightFighter().getHealth());
Behaviour nextRightBehaviour = getNextRandomApplicableBehaviour(getRightFighter(), getLeftFighter().getHealth());
setNextBehaviour(leftFighter, nextLeftBehaviour);
setNextBehaviour(rightFighter, nextRightBehaviour);
int leftInflictedDamage = calculateDamageBasedOnCurrentAttacks(leftFighter, rightFighter);
int rightInflictedDamage = calculateDamageBasedOnCurrentAttacks(rightFighter, leftFighter);
int currentLeftHealth = getLeftFighter().getHealth() - rightInflictedDamage;
int currentRightHealth = getRightFighter().getHealth() - leftInflictedDamage;
if (currentLeftHealth <= 0 || currentRightHealth <= 0)
{
setPlaying(false);
if (currentLeftHealth < currentRightHealth)
{
getRightFighter().setCurrentAttack(ATTACK_TYPE_WINNER);
getLeftFighter().setCurrentAttack(ATTACK_TYPE_DEAD);
setWinner(getRightFighter().getFighterName());
}
else
{
getRightFighter().setCurrentAttack(ATTACK_TYPE_DEAD);
getLeftFighter().setCurrentAttack(ATTACK_TYPE_WINNER);
setWinner(getLeftFighter().getFighterName());
}
}
calculatePlayerDistanceBasedOnMove(leftFighter);
calculatePlayerDistanceBasedOnMove(rightFighter);
getLeftFighter().setHealth(currentLeftHealth);
getRightFighter().setHealth(currentRightHealth);
setChanged();
notifyObservers();
}
}
public void playFightSound()
{
File soundDirectory = new File(jsaf.main.Main.getRelativeProjectPath() + "sounds");
File[] soundFiles = soundDirectory.listFiles();
int randomSoundIndex = (int) (Math.random() * soundFiles.length);
playSound(soundFiles[randomSoundIndex].getAbsolutePath());
}
private void setNextBehaviour(Fighter fighter, Behaviour inflictedBehaviour)
{
ArrayList<String> attackChoices = new ArrayList<>(inflictedBehaviour.getAttackChoices());
ArrayList<String> moveChoices = new ArrayList<>(inflictedBehaviour.getMoveChoices());
int randomAttackIndex = randomInt.nextInt(attackChoices.size());
int randomMoveIndex = randomInt.nextInt(moveChoices.size());
fighter.setCurrentAttack(attackChoices.get(randomAttackIndex));
fighter.setCurrentMove(moveChoices.get(randomMoveIndex));
}
private void calculatePlayerDistanceBasedOnMove(Fighter movingFighter)
{
switch (movingFighter.getCurrentMove())
{
case MOVE_TYPE_CROUCH:
distance = ((distance + CROUCH_STEP_DISTANCE) > MAX_HORIZONTAL_DISTANCE) ? MAX_HORIZONTAL_DISTANCE : distance + CROUCH_STEP_DISTANCE;
break;
case MOVE_TYPE_RUN_TOWARDS:
distance = ((distance + RUN_STEP_DISTANCE) > MAX_HORIZONTAL_DISTANCE) ? MAX_HORIZONTAL_DISTANCE : distance + RUN_STEP_DISTANCE;
break;
case MOVE_TYPE_WALK_TOWARDS:
distance = ((distance + WALK_STEP_DISTANCE) > MAX_HORIZONTAL_DISTANCE) ? MAX_HORIZONTAL_DISTANCE : distance + WALK_STEP_DISTANCE;
break;
case MOVE_TYPE_RUN_AWAY:
distance = ((distance - RUN_STEP_DISTANCE) < 0) ? 0 : distance - RUN_STEP_DISTANCE;
break;
case MOVE_TYPE_WALK_AWAY:
distance = ((distance - WALK_STEP_DISTANCE) < 0) ? 0 : distance - WALK_STEP_DISTANCE;
break;
}
}
public int calculateDamageBasedOnCurrentAttacks(Fighter attackingFighter, Fighter attackedFighter)
{
int damageAmount = 0;
String attack = attackingFighter.getCurrentAttack();
switch (attack)
{
case ATTACK_TYPE_BLOCK_LOW:
damageAmount = 0;
break;
case ATTACK_TYPE_BLOCK_HIGH:
damageAmount = 0;
break;
case ATTACK_TYPE_PUNCH_LOW:
if (!attackedFighter.getCurrentAttack().equals(ATTACK_TYPE_BLOCK_LOW))
{
damageAmount = attackingFighter.getPunchPower();
}
break;
case ATTACK_TYPE_PUNCH_HIGH:
if (!attackedFighter.getCurrentAttack().equals(ATTACK_TYPE_BLOCK_HIGH))
{
damageAmount = attackingFighter.getPunchPower();
}
break;
case ATTACK_TYPE_KICK_LOW:
if (!attackedFighter.getCurrentAttack().equals(ATTACK_TYPE_BLOCK_LOW))
{
damageAmount = attackingFighter.getKickPower();
}
break;
case ATTACK_TYPE_KICK_HIGH:
if (!attackedFighter.getCurrentAttack().equals(ATTACK_TYPE_BLOCK_HIGH))
{
damageAmount = attackingFighter.getKickPower();
}
break;
}
return damageAmount;
}
private Behaviour getNextRandomApplicableBehaviour(Fighter currentFighter, int opponentHealth)
{
ArrayList<Behaviour> possibleBehaviours = new ArrayList<Behaviour>();
for (Behaviour behaviour : currentFighter.getBehaviours())
{
if (conditionChoiceApplies(currentFighter, behaviour.getConditionChoices(), opponentHealth, distance))
{
possibleBehaviours.add(behaviour);
}
}
int randomIndex = randomInt.nextInt(possibleBehaviours.size());
return possibleBehaviours.get(randomIndex);
}
private boolean conditionChoiceApplies(Fighter currentFighter, ConditionChoices choices, int opponentHealth, int playerDistance)
{
boolean applicableConditionChoice = false;
for (ConditionGroup conditionGroup : choices.getConditionGroups())
{
boolean isApplicableCondition = true;
for (String condition : conditionGroup.getConditionTypes())
{
if (!conditionApplies(currentFighter, condition, opponentHealth, playerDistance))
{
isApplicableCondition = false;
}
}
if (isApplicableCondition) applicableConditionChoice = true;
}
return applicableConditionChoice;
}
private boolean conditionApplies(Fighter currentFighter, String condition, int opponentHealth, int playerDistance)
{
switch (condition)
{
case CONDITION_TYPE_STRONGER:
if (currentFighter.getHealth() > opponentHealth) return true;
break;
case CONDITION_TYPE_WEAKER:
if (opponentHealth < currentFighter.getHealth()) return true;
break;
case CONDITION_TYPE_MUCHSTRONGER:
if (currentFighter.getHealth() > (opponentHealth + MUCH_WEAKER_AMOUNT)) return true;
break;
case CONDITION_TYPE_MUCHWEAKER:
if (opponentHealth > (currentFighter.getHealth() + MUCH_WEAKER_AMOUNT)) return true;
break;
case CONDITION_TYPE_EVEN:
if (opponentHealth == currentFighter.getHealth()) return true;
break;
case CONDITION_TYPE_NEAR:
if (playerDistance > SHORT_DISTANCE) return true;
break;
case CONDITION_TYPE_FAR:
if (playerDistance >= LONG_DISTANCE) return true;
break;
case CONDITION_TYPE_ALWAYS:
return true;
}
return false;
}
/* Reinitializes the game: */
public void reStart()
{
setDistance(START_HORIZONTAL_DISTANCE);
setLeftHealth(MAX_HEALTH);
setRightHealth(MAX_HEALTH);
getLeftFighter().setCurrentAttack(ATTACK_TYPE_STAND);
getRightFighter().setCurrentAttack(ATTACK_TYPE_STAND);
setPlaying(true);
setChanged();
notifyObservers();
}
public static synchronized void playSound(final String url)
{
InputStream in;
try
{
in = new FileInputStream(url);
AudioStream as = new AudioStream(in);
AudioPlayer.player.start(as);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
new ErrorLog(e.getMessage());
}
}
/* Getters and Setters: */
public Fighter getLeftFighter()
{
return leftFighter;
}
public String getLeftCurrentAttack()
{
return leftFighter.getCurrentAttack();
}
public String getRightCurrentAttack()
{
return rightFighter.getCurrentAttack();
}
public void setFirstFighter(Fighter firstFighter)
{
this.leftFighter = firstFighter;
}
public Fighter getRightFighter()
{
return rightFighter;
}
public void setSecondFighter(Fighter secondFighter)
{
this.rightFighter = secondFighter;
}
public int getLeftHealth()
{
return getLeftFighter().getHealth();
}
public void setLeftHealth(int health)
{
getLeftFighter().setHealth(health);
}
public int getRightHealth()
{
return getRightFighter().getHealth();
}
public void setRightHealth(int health)
{
getRightFighter().setHealth(health);
}
public String getLeftPlayerName()
{
return getLeftFighter().getFighterName();
}
public String getRightPlayerName()
{
return getRightFighter().getFighterName();
}
public int getDistance()
{
return distance;
}
public void setDistance(int distance)
{
this.distance = distance;
}
public boolean isPlaying()
{
return isPlaying;
}
public void setPlaying(boolean isPlaying)
{
this.isPlaying = isPlaying;
}
public String getWinner()
{
return winner;
}
public void setWinner(String winner)
{
this.winner = winner;
}
}
| true
|
5bd2ce9c81074ee82bc3eee5d667bd98631f8856
|
Java
|
nasermasalma/Color-Models-Conversion
|
/src/p1/Activity.java
|
UTF-8
| 10,947
| 2.78125
| 3
|
[] |
no_license
|
package p1;
import javax.swing.*;
import javax.swing.border.TitledBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
//this is my project Naser Masalma
@SuppressWarnings("serial")
public class Activity extends JFrame {//name of class
JPanel p2 = new JPanel(new FlowLayout());//panel to fill the
JPanel p2cmy = new JPanel(new FlowLayout());//panel to fill the
JPanel p2hsv = new JPanel(new GridLayout(1,7,5,2));//panel to fill the
JPanel p1 = new JPanel(new GridLayout(3,2,10,5));//panel to fill the
JPanel p1cmy = new JPanel(new GridLayout(3,2,10,5));//panel to fill the
JPanel p3 = new JPanel(new GridLayout(1,2,10,5));//panel to fill the
JPanel p4 = new JPanel(new BorderLayout(20,15));//panel to fill the
JPanel totalPanel = new JPanel(new GridLayout(2,1,20,10));//panel to fill the
private JButton showIt =new JButton("Show It");
private JButton showIt2 =new JButton("Show It");
private JButton showIt3 =new JButton("Show It");
JPanel colorProject =new JPanel();
JSlider sliderRed = new JSlider(JSlider.HORIZONTAL,0,255,0);
JSlider sliderGreen = new JSlider(JSlider.HORIZONTAL,0,255,0);
JSlider sliderBlue = new JSlider(JSlider.HORIZONTAL,0,255,0);
static JLabel red = new JLabel("Red = 0",JLabel.CENTER);
static JLabel green = new JLabel("Green = 0",JLabel.CENTER);
static JLabel blue = new JLabel("Blue = 0",JLabel.CENTER);
JTextField textHue =new JTextField("0");
JTextField textSaturation =new JTextField("0.0");
JTextField textValue =new JTextField("0.0");
static JLabel Hue = new JLabel("Hue(0-360)",JLabel.CENTER);
static JLabel Saturation = new JLabel("Saturation(0-1)",JLabel.CENTER);
static JLabel Value = new JLabel("Value(0-1)",JLabel.CENTER);
JSlider sliderCyan = new JSlider(JSlider.HORIZONTAL,0,255,255);
JSlider sliderMagenta = new JSlider(JSlider.HORIZONTAL,0,255,255);
JSlider sliderYellow = new JSlider(JSlider.HORIZONTAL,0,255,255);
static JLabel cyan = new JLabel("Cyan = 0",JLabel.CENTER);
static JLabel magenta = new JLabel("Magenta = 0",JLabel.CENTER);
static JLabel yellow = new JLabel("Yellow = 0",JLabel.CENTER);
public Activity(){
TitledBorder t1 = new TitledBorder("Color Models");
TitledBorder t2 = new TitledBorder("RGB model");
TitledBorder t3 = new TitledBorder("CMY model");
TitledBorder t4 = new TitledBorder("HSV model");
red.setForeground(Color.RED);
green.setForeground(Color.green);
blue.setForeground(Color.blue);
sliderRed.setMajorTickSpacing(50);
sliderRed.setMinorTickSpacing(1);
sliderRed.setPaintTicks(true);
sliderRed.setPaintLabels(true);
sliderGreen.setMajorTickSpacing(50);
sliderGreen.setMinorTickSpacing(1);
sliderGreen.setPaintTicks(true);
sliderGreen.setPaintLabels(true);
sliderBlue.setMajorTickSpacing(50);
sliderBlue.setMinorTickSpacing(1);
sliderBlue.setPaintTicks(true);
sliderBlue.setPaintLabels(true);
cyan.setForeground(Color.CYAN);
magenta.setForeground(Color.MAGENTA);
yellow.setForeground(Color.black);
sliderCyan.setMajorTickSpacing(50);
sliderCyan.setMinorTickSpacing(1);
sliderCyan.setPaintTicks(true);
sliderCyan.setPaintLabels(true);
sliderMagenta.setMajorTickSpacing(50);
sliderMagenta.setMinorTickSpacing(1);
sliderMagenta.setPaintTicks(true);
sliderMagenta.setPaintLabels(true);
sliderYellow.setMajorTickSpacing(50);
sliderYellow.setMinorTickSpacing(1);
sliderYellow.setPaintTicks(true);
sliderYellow.setPaintLabels(true);
colorProject.setBackground(Color.black);
sliderRed.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
red.setText("Red = "+sliderRed.getValue());
}
});
sliderGreen.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
green.setText("Green = "+sliderGreen.getValue());
}
});
sliderBlue.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
blue.setText("Blue = "+sliderBlue.getValue());
}
});
sliderCyan.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
cyan.setText("Cyan = "+sliderCyan.getValue());
}
});
sliderMagenta.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
magenta.setText("Magenta = "+sliderMagenta.getValue());
}
});
sliderYellow.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
yellow.setText("Yellow = "+sliderYellow.getValue());
}
});
showIt.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int r = sliderRed.getValue();
int g = sliderGreen.getValue();
int b = sliderBlue.getValue();
colorProject.setBackground(new Color(r, g, b));
RGB toCon =new RGB(r, g, b);
CMY ret=ConvertRGBtoCMY(toCon);
sliderCyan.setValue(ret.getC());
sliderMagenta.setValue(ret.getM());
sliderYellow.setValue(ret.getY());
HSV n =ConvertRGBtoHSV(toCon);
textHue.setText(String.valueOf(n.getH()));
textSaturation.setText(String.valueOf(n.getS()));
textValue.setText(String.valueOf(n.getV()));
}
});
showIt2.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
int c = sliderCyan.getValue();
int m = sliderMagenta.getValue();
int y = sliderYellow.getValue();
CMY toCon =new CMY(c, m, y);
RGB ret=ConvertCMYtoRGB(toCon);
sliderRed.setValue(ret.getR());
sliderGreen.setValue(ret.getG());
sliderBlue.setValue(ret.getB());
colorProject.setBackground(new Color(ret.getR(),ret.getG(), ret.getB()));
HSV n =ConvertRGBtoHSV(ret);
textHue.setText(String.valueOf(n.getH()));
textSaturation.setText(String.valueOf(n.getS()));
textValue.setText(String.valueOf(n.getV()));
}
});
showIt3.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
float h = Float.parseFloat(textHue.getText());
float s = Float.parseFloat(textSaturation.getText());
float v = Float.parseFloat(textValue.getText());
if(s>1 ||v>1||s<0||v<0){
JOptionPane.showMessageDialog(null, "the is an error in the enter value with the value of v or s");
}
else{
RGB ret =ConvertHSVtoRGB(h,s,v);
sliderRed.setValue(ret.getR());
sliderGreen.setValue(ret.getG());
sliderBlue.setValue(ret.getB());
colorProject.setBackground(new Color(ret.getR(),ret.getG(), ret.getB()));
CMY ret1=ConvertRGBtoCMY(ret);
sliderCyan.setValue(ret1.getC());
sliderMagenta.setValue(ret1.getM());
sliderYellow.setValue(ret1.getY());
}}
});
p1.add(red);
p1.add(sliderRed);
p1.add(green);
p1.add(sliderGreen);
p1.add(blue);
p1.add(sliderBlue);
p2.add(p1,BorderLayout.CENTER);
p2.add(showIt,BorderLayout.EAST);
p2.setBorder(t2);
p1cmy.add(cyan);
p1cmy.add(sliderCyan);
p1cmy.add(magenta);
p1cmy.add(sliderMagenta);
p1cmy.add(yellow);
p1cmy.add(sliderYellow);
p2cmy.add(p1cmy,BorderLayout.CENTER);
p2cmy.add(showIt2,BorderLayout.EAST);
p2cmy.setBorder(t3);
p2hsv.add(Hue);
p2hsv.add(textHue);
p2hsv.add(Saturation);
p2hsv.add(textSaturation);
p2hsv.add(Value);
p2hsv.add(textValue);
p2hsv.add(showIt3);
p2hsv.setBorder(t4);
p3.add(p2);
p3.add(p2cmy);
p4.add(p3,BorderLayout.CENTER);
p4.add(p2hsv,BorderLayout.SOUTH);
p4.setBorder(t1);
totalPanel.add(p4);
totalPanel.add(colorProject);
add(totalPanel);
}
public HSV ConvertRGBtoHSV(RGB n){
float r=(float) (n.getR()/255.0);
float g=(float) ((n.getG())/255.0);
float b=(float) ((n.getB())/255.0);
float max =Max(r,Max(g,b));
float min =Min(r,Min(g,b));
float mid =Mid(r,g,b);
float delta =max-min;
float V =max;
float H,S;
int hue;
if(max==0){
S=0;
H=0;
}
else{
S =delta/max;
if(S==0){
H=0;
}
else{
float alpha=60*((mid-min)/delta);
if(r==max && b==min)
H=alpha;
else if(g==max && b==min)
H=120-alpha;
else if(g==max && r==min)
H=120+alpha;
else if(b==max && r==min)
H=240-alpha;
else if(b==max && g==min)
H=240+alpha;
else H=360-alpha;
}
}
hue=(int)H;
return new HSV(hue, S, V);
}
private float Mid(float a, float b, float c) {
float x = a-b;
float y = b-c;
float z = a-c;
if(x*y > 0) return b;
if(x*z > 0) return c;
return a;
}
private float Min(float a, float b) {
if(a>b)
return b;
else return a;
}
private float Max(float a, float b) {
if(a>b)
return a;
else return b;
}
public RGB ConvertHSVtoRGB(float h, float s, float v){
int i;
float low,mid1,mid2;
float r1=0,g1=0,b1=0;
int r,g,b;
while(h<0){
h=h+360;
}
while(h>=360){
h=h-360;
}
float hh = ((h/360)*6);
//System.out.println(hh);
if(s==0){
r=(int) (v*255);
g=(int) (v*255);
b=(int) (v*255);
}
else{
if(hh==6){
hh = 0;
}
i=(int) Math.floor(hh);
// System.out.println(i);
low= v*(1-s);
mid1=v*(1-s*(hh-i));
mid2=v*(1-s*(1-(hh-i)));
switch(i){
case 0:r1=v;g1=mid2;b1=low;break;
case 1:r1=mid1;g1=v;b1=low;break;
case 2:r1=low;g1=v;b1=mid2;break;
case 3:r1=low;g1=mid1;b1=v;break;
case 4:r1=mid2;g1=low;b1=v;break;
case 5:r1=v;g1=low;b1=mid1;break;
}
r=(int) (r1*255);
g=(int) (g1*255);
b=(int) (b1*255);
}
return new RGB(r, g, b);
}
public CMY ConvertRGBtoCMY(RGB n){
int c=255-n.getR();
int m=255-n.getG();
int y =255-n.getB();
CMY ret =new CMY(c,m,y);
return ret;
}
public RGB ConvertCMYtoRGB(CMY n){
int r=255-n.getC();
int g=255-n.getM();
int b =255-n.getY();
RGB ret =new RGB(r,g,b);
return ret;
}
public static void main(String[] args) {//Prepare frame
Activity panel = new Activity();//make object
panel.setTitle("PROJECT 1 GRAPHICS");//set title for the project
panel.setLocationRelativeTo(null);
panel.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//Close when X is clicked
panel.setVisible(true);//Make frame visible
panel.setSize(1000,600);//Set size to
panel.setResizable(false);//to keep the same size
}
}
| true
|
86d6f407a43b081e240b260238b702fa1d91e7c2
|
Java
|
EminAliev/Biology-study
|
/src/main/java/ru/itis/biology/dto/QuestionDto.java
|
UTF-8
| 208
| 1.742188
| 2
|
[] |
no_license
|
package ru.itis.biology.dto;
import lombok.Data;
import ru.itis.biology.models.Answer;
import java.util.Set;
@Data
public class QuestionDto {
private String content;
private Set<Answer> answers;
}
| true
|
cbddbf6f56f54ecb932fa42e10b02e91fe6ad734
|
Java
|
cbtian/strayboy
|
/app/src/main/java/com/tiancb/strayboy/logic/BaseLogic.java
|
UTF-8
| 277
| 1.804688
| 2
|
[] |
no_license
|
package com.tiancb.strayboy.logic;
import com.tiancb.strayboy.MainApplication;
/**
* Created by tiancb on 2018/4/11.
*/
public class BaseLogic {
public MainApplication app;
public BaseLogic(){
app = (MainApplication) MainApplication.getInstance();
}
}
| true
|
415c427a61d1381f92435458d37c75bc3867db05
|
Java
|
3035147105/HFQ-SpringBoot
|
/src/main/java/com/toy/server/config/dataBase/CtradeDataSourceConfig.java
|
UTF-8
| 2,384
| 2
| 2
|
[] |
no_license
|
package com.toy.server.config.dataBase;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateSettings;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.sql.DataSource;
import java.util.Map;
/**
* Created by ghq on 2018/4/24.
*/
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(entityManagerFactoryRef = "ctradeEntityManagerFactory",
transactionManagerRef = "ctradeTransactionManager", basePackages = {"com.toy.server.dao.ctrade"})
public class CtradeDataSourceConfig {
@Autowired
private JpaProperties jpaProperties;
@Autowired
@Qualifier("ctradeDataSource")
private DataSource ctradeDataSource;
@Primary
@Bean(name = "ctradeEntityManagerFactory")
public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean(EntityManagerFactoryBuilder builder) {
return builder.dataSource(ctradeDataSource)
.properties(getVendorProperties())
.packages("com.toy.server.entity.ctrade")
.build();
}
@Bean(name = "ctradeTransactionManager")
public PlatformTransactionManager ctradeTransactionManager(EntityManagerFactoryBuilder builder) {
return new JpaTransactionManager(entityManagerFactoryBean(builder).getObject());
}
// @Bean(name = "ctradeEntityManager")
// public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
// return entityManagerFactoryBean(builder).getObject().createEntityManager();
// }
private Map<String, Object> getVendorProperties() {
return jpaProperties.getHibernateProperties(new HibernateSettings());
}
}
| true
|
b6621d738828a4424b4b05938f75dc5cf9c8f47a
|
Java
|
evgenykuzin/crud-with-kafka
|
/src/test/java/ru/sberbank/kuzin19190813/crudwithkafka/controllers/CrudControllerTest.java
|
UTF-8
| 4,816
| 2.28125
| 2
|
[] |
no_license
|
package ru.sberbank.kuzin19190813.crudwithkafka.controllers;
import lombok.*;
import lombok.experimental.FieldDefaults;
import org.junit.jupiter.api.Test;
import ru.sberbank.kuzin19190813.crudwithkafka.body.response.NotFoundBody;
import ru.sberbank.kuzin19190813.crudwithkafka.body.response.RespBody;
import ru.sberbank.kuzin19190813.crudwithkafka.controllers.util.CrudRequestExecutor;
import ru.sberbank.kuzin19190813.crudwithkafka.util.test.TestMapper;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
public abstract class CrudControllerTest<D> extends BaseControllerTest {
protected String baseEndpoint;
protected String entityName;
protected Class<D> dtoClass;
protected CrudRequestExecutor crudRequestExecutor;
public CrudControllerTest(String baseEndpoint, String entityName, Class<D> dtoClass) {
this.baseEndpoint = baseEndpoint;
this.entityName = entityName;
this.dtoClass = dtoClass;
crudRequestExecutor = CrudRequestExecutor.getInstance(baseEndpoint);
crudRequestExecutor.clearAll();
}
public abstract D constructTestObject();
public abstract ModifiedResult<D> modifyTestObject(D d);
public abstract void testsForGet();
public abstract void testsForSave();
public abstract void testsForUpdate();
public abstract void testsForDelete();
public abstract void testsForFindAll();
@Test
protected void get() {
D constructed = constructTestObject();
Long id = saveObject(constructed);
D d = getObject(id);
assertEquals(constructed.toString(), d.toString());
Long illegalId = 123456L;
assertNotFound(illegalId);
testsForGet();
crudRequestExecutor.clearAll();
}
@Test
protected void save() {
D obj = constructTestObject();
Long id = saveObject(obj);
assertNotNull(id);
assertEquals(obj.toString(), getObject(id).toString());
testsForSave();
crudRequestExecutor.clearAll();
}
@Test
protected void update() {
Long savedId = saveObject(constructTestObject());
D d = getObject(savedId);
ModifiedResult<D> modifiedResult = modifyTestObject(d);
String mfn = modifiedResult.getModifiedFieldName();
Object mfv = modifiedResult.getModifiedFieldValue();
Object oldValue = modifiedResult.getOldFieldValue();
crudRequestExecutor.update(d);
D d2 = getObject(savedId);
Object d2Value = getFieldValue(d2, mfn);
assertEquals(mfv, d2Value);
assertNotEquals(mfv, oldValue);
testsForUpdate();
crudRequestExecutor.clearAll();
}
@Test
protected void delete() {
Long id = saveObject(constructTestObject());
crudRequestExecutor.delete(id);
assertNotFound(id);
testsForDelete();
crudRequestExecutor.clearAll();
}
@Test
protected void findAll() {
List<D> createdItems = new ArrayList<>();
for (int i = 0; i < 3; i++) {
createdItems.add(constructTestObject());
}
createdItems.forEach(crudRequestExecutor::save);
RespBody respBody = crudRequestExecutor.findAll();
System.out.println("respBody = " + respBody);
List<D> foundedItems = TestMapper.mapToDtoList(respBody.getResult(), dtoClass);
assertEquals(createdItems.toString(), foundedItems.toString());
testsForFindAll();
crudRequestExecutor.clearAll();
}
private Object getFieldValue(D object, String fieldName) {
Object fieldValue = null;
try {
Field field = dtoClass.getDeclaredField(fieldName);
field.setAccessible(true);
fieldValue = field.get(object);
} catch (IllegalAccessException | NoSuchFieldException e) {
fail(e);
}
return fieldValue;
}
protected D getObject(Long id) {
return TestMapper.map(crudRequestExecutor.get(id).getResult(), dtoClass);
}
protected Long saveObject(D d) {
return TestMapper.mapToLong(crudRequestExecutor.save(d).getResult());
}
protected void assertNotFound(Long id) {
RespBody errorResp = crudRequestExecutor.get(id, false);
assertNull(errorResp.getResult());
NotFoundBody notFoundBody = TestMapper.map(errorResp.getError(), NotFoundBody.class);
assertEquals(new NotFoundBody(entityName, id), notFoundBody);
}
@Getter
@FieldDefaults(level = AccessLevel.PRIVATE, makeFinal = true)
@AllArgsConstructor
public static class ModifiedResult<D> {
D obj;
String modifiedFieldName;
Object modifiedFieldValue;
Object oldFieldValue;
}
}
| true
|
54db9b59449ada0054b636f09b7eba8a5b26105d
|
Java
|
P79N6A/icse_20_user_study
|
/methods/Method_1003203.java
|
UTF-8
| 315
| 2.0625
| 2
|
[] |
no_license
|
@Override public boolean next(){
if (rowId < rowCount) {
rowId++;
remapIfOld();
if (rowId < rowCount) {
if (rowId - rowOffset >= result.size()) {
fetchRows(true);
}
currentRow=result.get(rowId - rowOffset);
return true;
}
currentRow=null;
}
return false;
}
| true
|
1890dfd3a968fc7424c430ee46a7ac5df55e2387
|
Java
|
Harshith7829/TY_CG_HTD_BangloreNovember_JFS_HarshithCR
|
/Module-2 test/retailer_db/src/main/java/com/capgemini/retailer_db/controller/UserController.java
|
UTF-8
| 4,128
| 2.359375
| 2
|
[] |
no_license
|
package com.capgemini.retailer_db.controller;
import java.util.Arrays;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.capgemini.retailer_db.dto.User;
import com.capgemini.retailer_db.dto.UserResponse;
import com.capgemini.retailer_db.service.ServiceUser;
@RestController
public class UserController {
@Autowired
private ServiceUser service;
@PostMapping(path="/auth-user", produces=MediaType.APPLICATION_JSON_VALUE,
consumes=MediaType.APPLICATION_JSON_VALUE)
public UserResponse auth(@RequestBody User bean) {
User userBean= service.auth(bean.getEmail(), bean.getPassword());
UserResponse response= new UserResponse();
if(userBean!=null) {
response.setStatusCode(201);
response.setMessesge("success");
response.setDiscription("Found");
response.setBean(userBean);
}else {
response.setStatusCode(401);
response.setMessesge("failure");
response.setDiscription("invalid credntials");
}
return response;
}
@PostMapping(path="/register-user",produces=MediaType.APPLICATION_JSON_VALUE,
consumes= MediaType.APPLICATION_JSON_VALUE)
public UserResponse register(@RequestBody User bean) {
UserResponse response= new UserResponse();
if(service.register(bean)) {
response.setStatusCode(201);
response.setMessesge("success");
response.setDiscription("Registerd");
}else {
response.setStatusCode(401);
response.setMessesge("failure");
response.setDiscription("Email already exists");
}
return response;
}
@GetMapping(path="/getall-users",produces=MediaType.APPLICATION_JSON_VALUE)
public UserResponse searchUser(@RequestParam(name="key")String key) {
UserResponse response= new UserResponse();
List<User> beans = service.getAllUsers();
if(beans.isEmpty()) {
response.setStatusCode(401);
response.setMessesge("failure");
response.setDiscription("User deatils Not Found");
}else {
response.setStatusCode(201);
response.setMessesge("success");
response.setDiscription("User Details Found");
response.setBeans(beans);
}
return response;
}
@PutMapping(path="/changeuser-pass",produces=MediaType.APPLICATION_JSON_VALUE,
consumes=MediaType.APPLICATION_JSON_VALUE)
public UserResponse changePassword(@RequestBody User bean) {
UserResponse response= new UserResponse();
if(service.changeUserPassword(bean.getUserid(),bean.getPassword())) {
response.setStatusCode(201);
response.setMessesge("success");
response.setDiscription("Password Changed");
}else {
response.setStatusCode(401);
response.setMessesge("failure");
response.setDiscription("Failed to change Password");
}
return response;
}
@DeleteMapping(path="/deleteuser/{id}",produces=MediaType.APPLICATION_JSON_VALUE)
public UserResponse deleteUser(@PathVariable("id")int id) {
UserResponse response= new UserResponse();
service.deleteUser(id);
response.setStatusCode(201);
response.setMessesge("success");
response.setDiscription("User Deleted");
return response;
}
@GetMapping(path="/get-user/{id}",produces=MediaType.APPLICATION_JSON_VALUE)
public UserResponse getCustomerDetails(@PathVariable("id")int key) {
UserResponse response= new UserResponse();
List<User> beans = service.getUser(key);
if(beans.isEmpty()) {
response.setStatusCode(401);
response.setMessesge("failure");
response.setDiscription("No such User found");
}else {
response.setStatusCode(201);
response.setMessesge("success");
response.setDiscription("Customer Details Found");
response.setBeans(beans);
}
return response;
}
}
| true
|
9abab9ce7ce5ef13d8215be8e16611156d78cf6c
|
Java
|
karenc-bq/aws-postgresql-jdbc
|
/pgjdbc/src/test/java/software/aws/rds/jdbc/postgresql/ca/ClusterAwareWriterFailoverHandlerTest.java
|
UTF-8
| 23,973
| 1.96875
| 2
|
[
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
/*
* AWS JDBC Driver for PostgreSQL
* Copyright Amazon.com Inc. or affiliates.
* See the LICENSE file in the project root for more information.
*/
package software.aws.rds.jdbc.postgresql.ca;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentMatchers;
import org.mockito.InOrder;
import org.mockito.Mockito;
import org.mockito.stubbing.Answer;
import org.postgresql.core.BaseConnection;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
/**
* ClusterAwareWriterFailoverHandlerTest class.
*/
public class ClusterAwareWriterFailoverHandlerTest {
/**
* Verify that writer failover handler can re-connect to a current writer node.
*
* <p>topology: no changes taskA: successfully re-connect to writer; return new connection taskB:
* fail to connect to any reader due to exception expected test result: new connection by taskA
*/
@Test
public void testReconnectToWriter_taskBReaderException() throws SQLException {
final AuroraTopologyService mockTopologyService = Mockito.mock(AuroraTopologyService.class);
final ConnectionProvider mockConnectionProvider = Mockito.mock(ConnectionProvider.class);
final BaseConnection mockConnection = Mockito.mock(BaseConnection.class);
final ReaderFailoverHandler mockReaderFailover = Mockito.mock(ReaderFailoverHandler.class);
final HostInfo writerHost = createBasicHostInfo("writer-host", true);
final HostInfo readerA_Host = createBasicHostInfo("reader-a-host", false);
final HostInfo readerB_Host = createBasicHostInfo("reader-b-host", false);
final List<HostInfo> currentTopology = new ArrayList<>();
currentTopology.add(writerHost);
currentTopology.add(readerA_Host);
currentTopology.add(readerB_Host);
when(mockConnectionProvider.connect(eq(writerHost.toHostSpec()), any(Properties.class), eq(writerHost.getUrl()))).thenReturn(mockConnection);
when(mockConnectionProvider.connect(eq(readerA_Host.toHostSpec()), any(Properties.class), eq(readerA_Host.getUrl()))).thenThrow(SQLException.class);
when(mockConnectionProvider.connect(eq(readerB_Host.toHostSpec()), any(Properties.class), eq(readerB_Host.getUrl()))).thenThrow(SQLException.class);
when(mockTopologyService.getTopology(any(BaseConnection.class), eq(true)))
.thenReturn(currentTopology);
when(mockReaderFailover.getReaderConnection(ArgumentMatchers.anyList()))
.thenThrow(SQLException.class);
final ClusterAwareWriterFailoverHandler target =
new ClusterAwareWriterFailoverHandler(
mockTopologyService,
mockConnectionProvider,
new Properties(),
mockReaderFailover,
5000,
2000,
2000);
final WriterFailoverResult result = target.failover(currentTopology);
assertTrue(result.isConnected());
assertFalse(result.isNewHost());
assertSame(result.getNewConnection(), mockConnection);
final InOrder inOrder = Mockito.inOrder(mockTopologyService);
inOrder.verify(mockTopologyService).addToDownHostList(eq(writerHost));
inOrder.verify(mockTopologyService).removeFromDownHostList(eq(writerHost));
}
private HostInfo createBasicHostInfo(String host, boolean isWriter) {
return new HostInfo(host, host,1234, isWriter);
}
/**
* Verify that writer failover handler can re-connect to a current writer node.
*
* <p>topology: no changes seen by task A, changes to [new-writer, reader-A, reader-B] for taskB
* taskA: successfully re-connect to initial writer; return new connection taskB: successfully
* connect to readerA and then new writer but it takes more time than taskA expected test result:
* new connection by taskA
*/
@Test
public void testReconnectToWriter_SlowReaderA() throws SQLException {
final AuroraTopologyService mockTopologyService = Mockito.mock(AuroraTopologyService.class);
final ConnectionProvider mockConnectionProvider = Mockito.mock(ConnectionProvider.class);
final BaseConnection mockWriterConnection = Mockito.mock(BaseConnection.class);
final BaseConnection mockReaderA_Connection = Mockito.mock(BaseConnection.class);
final ReaderFailoverHandler mockReaderFailover = Mockito.mock(ReaderFailoverHandler.class);
final HostInfo writerHost = createBasicHostInfo("writer-host", true);
final HostInfo readerA_Host = createBasicHostInfo("reader-a-host", false);
final HostInfo readerB_Host = createBasicHostInfo("reader-b-host", false);
final List<HostInfo> currentTopology = new ArrayList<>();
currentTopology.add(writerHost);
currentTopology.add(readerA_Host);
currentTopology.add(readerB_Host);
final HostInfo newWriterHost = createBasicHostInfo("new-writer-host", true);
final List<HostInfo> newTopology = new ArrayList<>();
newTopology.add(newWriterHost);
newTopology.add(readerA_Host);
newTopology.add(readerB_Host);
when(mockConnectionProvider.connect(eq(writerHost.toHostSpec()), any(Properties.class), eq(writerHost.getUrl()))).thenReturn(mockWriterConnection);
when(mockConnectionProvider.connect(eq(readerB_Host.toHostSpec()), any(Properties.class), eq(readerB_Host.getUrl()))).thenThrow(SQLException.class);
when(mockTopologyService.getTopology(eq(mockWriterConnection), eq(true)))
.thenReturn(currentTopology);
when(mockTopologyService.getTopology(eq(mockReaderA_Connection), eq(true)))
.thenReturn(newTopology);
when(mockReaderFailover.getReaderConnection(ArgumentMatchers.anyList()))
.thenAnswer(
(Answer<ReaderFailoverResult>)
invocation -> {
Thread.sleep(5000);
return new ReaderFailoverResult(mockReaderA_Connection, readerA_Host, true);
});
final ClusterAwareWriterFailoverHandler target =
new ClusterAwareWriterFailoverHandler(
mockTopologyService,
mockConnectionProvider,
new Properties(),
mockReaderFailover,
60000,
5000,
5000);
final WriterFailoverResult result = target.failover(currentTopology);
assertTrue(result.isConnected());
assertFalse(result.isNewHost());
assertSame(result.getNewConnection(), mockWriterConnection);
final InOrder inOrder = Mockito.inOrder(mockTopologyService);
inOrder.verify(mockTopologyService).addToDownHostList(eq(writerHost));
inOrder.verify(mockTopologyService).removeFromDownHostList(eq(writerHost));
}
/**
* Verify that writer failover handler can re-connect to a current writer node.
*
* <p>topology: no changes taskA: successfully re-connect to writer; return new connection taskB:
* successfully connect to readerA and retrieve topology, but latest writer is not new (defer to
* taskA) expected test result: new connection by taskA
*/
@Test
public void testReconnectToWriter_taskBDefers() throws SQLException {
final AuroraTopologyService mockTopologyService = Mockito.mock(AuroraTopologyService.class);
final ConnectionProvider mockConnectionProvider = Mockito.mock(ConnectionProvider.class);
final BaseConnection mockWriterConnection = Mockito.mock(BaseConnection.class);
final BaseConnection mockReaderA_Connection = Mockito.mock(BaseConnection.class);
final ReaderFailoverHandler mockReaderFailover = Mockito.mock(ReaderFailoverHandler.class);
final HostInfo writerHost = createBasicHostInfo("writer-host", true);
final HostInfo readerA_Host = createBasicHostInfo("reader-a-host", false);
final HostInfo readerB_Host = createBasicHostInfo("reader-b-host", false);
final List<HostInfo> currentTopology = new ArrayList<>();
currentTopology.add(writerHost);
currentTopology.add(readerA_Host);
currentTopology.add(readerB_Host);
when(mockConnectionProvider.connect(eq(writerHost.toHostSpec()), any(Properties.class), eq(writerHost.getUrl())))
.thenAnswer(
(Answer<Connection>)
invocation -> {
Thread.sleep(5000);
return mockWriterConnection;
});
when(mockConnectionProvider.connect(eq(readerB_Host.toHostSpec()), any(Properties.class), eq(readerB_Host.getUrl()))).thenThrow(SQLException.class);
when(mockTopologyService.getTopology(any(BaseConnection.class), eq(true)))
.thenReturn(currentTopology);
when(mockReaderFailover.getReaderConnection(ArgumentMatchers.anyList()))
.thenReturn(new ReaderFailoverResult(mockReaderA_Connection, readerA_Host, true));
final ClusterAwareWriterFailoverHandler target =
new ClusterAwareWriterFailoverHandler(
mockTopologyService,
mockConnectionProvider,
new Properties(),
mockReaderFailover,
60000,
2000,
2000);
final WriterFailoverResult result = target.failover(currentTopology);
assertTrue(result.isConnected());
assertFalse(result.isNewHost());
assertSame(result.getNewConnection(), mockWriterConnection);
final InOrder inOrder = Mockito.inOrder(mockTopologyService);
inOrder.verify(mockTopologyService).addToDownHostList(eq(writerHost));
inOrder.verify(mockTopologyService).removeFromDownHostList(eq(writerHost));
}
/**
* Verify that writer failover handler can re-connect to a new writer node.
*
* <p>topology: changes to [new-writer, reader-A, reader-B] for taskB, taskA sees no changes
* taskA: successfully re-connect to writer; return connection to initial writer but it takes more
* time than taskB taskB: successfully connect to readerA and then to new-writer expected test
* result: new connection to writer by taskB
*/
@Test
public void testConnectToReaderA_SlowWriter() throws SQLException {
final AuroraTopologyService mockTopologyService = Mockito.mock(AuroraTopologyService.class);
final ConnectionProvider mockConnectionProvider = Mockito.mock(ConnectionProvider.class);
final BaseConnection mockWriterConnection = Mockito.mock(BaseConnection.class);
final BaseConnection mockNewWriterConnection = Mockito.mock(BaseConnection.class);
final BaseConnection mockReaderA_Connection = Mockito.mock(BaseConnection.class);
final BaseConnection mockReaderB_Connection = Mockito.mock(BaseConnection.class);
final ReaderFailoverHandler mockReaderFailover = Mockito.mock(ReaderFailoverHandler.class);
final HostInfo writerHost = createBasicHostInfo("writer-host", true);
final HostInfo readerA_Host = createBasicHostInfo("reader-a-host", false);
final HostInfo readerB_Host = createBasicHostInfo("reader-b-host", false);
final List<HostInfo> currentTopology = new ArrayList<>();
currentTopology.add(writerHost);
currentTopology.add(readerA_Host);
currentTopology.add(readerB_Host);
final HostInfo newWriterHost = createBasicHostInfo("new-writer-host", true);
final List<HostInfo> newTopology = new ArrayList<>();
newTopology.add(newWriterHost);
newTopology.add(readerA_Host);
newTopology.add(readerB_Host);
when(mockConnectionProvider.connect(writerHost.toHostSpec(), new Properties(), writerHost.getUrl()))
.thenAnswer(
(Answer<Connection>)
invocation -> {
Thread.sleep(5000);
return mockWriterConnection;
});
when(mockConnectionProvider.connect(eq(readerA_Host.toHostSpec()), any(Properties.class),
eq(readerB_Host.getUrl()))).thenReturn(mockReaderA_Connection);
when(mockConnectionProvider.connect(eq(readerB_Host.toHostSpec()), any(Properties.class),
eq(readerB_Host.getUrl()))).thenReturn(mockReaderB_Connection);
when(mockConnectionProvider.connect(eq(newWriterHost.toHostSpec()), any(Properties.class),
eq(newWriterHost.getUrl()))).thenReturn(mockNewWriterConnection);
when(mockTopologyService.getTopology(eq(mockWriterConnection), eq(true)))
.thenReturn(currentTopology);
when(mockTopologyService.getTopology(eq(mockReaderA_Connection), eq(true)))
.thenReturn(newTopology);
when(mockReaderFailover.getReaderConnection(ArgumentMatchers.anyList()))
.thenReturn(new ReaderFailoverResult(mockReaderA_Connection, readerA_Host, true));
final ClusterAwareWriterFailoverHandler target =
new ClusterAwareWriterFailoverHandler(
mockTopologyService,
mockConnectionProvider,
new Properties(),
mockReaderFailover,
60000,
5000,
5000);
final WriterFailoverResult result = target.failover(currentTopology);
assertTrue(result.isConnected());
assertTrue(result.isNewHost());
assertSame(result.getNewConnection(), mockNewWriterConnection);
assertEquals(3, result.getTopology().size());
assertEquals("new-writer-host", result.getTopology().get(0).getHost());
verify(mockTopologyService, times(1)).addToDownHostList(eq(writerHost));
verify(mockTopologyService, times(1)).removeFromDownHostList(eq(newWriterHost));
}
/**
* Verify that writer failover handler can re-connect to a new writer node.
*
* <p>topology: changes to [new-writer, initial-writer, reader-A, reader-B] taskA: successfully
* reconnect, but initial-writer is now a reader (defer to taskB) taskB: successfully connect to
* readerA and then to new-writer expected test result: new connection to writer by taskB
*/
@Test
public void testConnectToReaderA_taskADefers() throws SQLException {
final AuroraTopologyService mockTopologyService = Mockito.mock(AuroraTopologyService.class);
final ConnectionProvider mockConnectionProvider = Mockito.mock(ConnectionProvider.class);
final BaseConnection mockNewWriterConnection = Mockito.mock(BaseConnection.class);
final BaseConnection mockReaderA_Connection = Mockito.mock(BaseConnection.class);
final BaseConnection mockReaderB_Connection = Mockito.mock(BaseConnection.class);
final ReaderFailoverHandler mockReaderFailover = Mockito.mock(ReaderFailoverHandler.class);
final HostInfo initialWriterHost = createBasicHostInfo("initial-writer-host", true);
final HostInfo readerA_Host = createBasicHostInfo("reader-a-host", false);
final HostInfo readerB_Host = createBasicHostInfo("reader-b-host", false);
final List<HostInfo> currentTopology = new ArrayList<>();
currentTopology.add(initialWriterHost);
currentTopology.add(readerA_Host);
currentTopology.add(readerB_Host);
final HostInfo newWriterHost = createBasicHostInfo("new-writer-host", true);
final List<HostInfo> newTopology = new ArrayList<>();
newTopology.add(newWriterHost);
newTopology.add(initialWriterHost);
newTopology.add(readerA_Host);
newTopology.add(readerB_Host);
when(mockConnectionProvider.connect(eq(initialWriterHost.toHostSpec()), any(Properties.class), eq(initialWriterHost.getUrl())))
.thenReturn(Mockito.mock(BaseConnection.class));
when(mockConnectionProvider.connect(eq(readerA_Host.toHostSpec()), any(Properties.class), eq(readerA_Host.getUrl()))).thenReturn(mockReaderA_Connection);
when(mockConnectionProvider.connect(eq(readerB_Host.toHostSpec()), any(Properties.class), eq(readerB_Host.getUrl()))).thenReturn(mockReaderB_Connection);
when(mockConnectionProvider.connect(eq(newWriterHost.toHostSpec()), any(Properties.class),
eq(newWriterHost.getUrl())))
.thenAnswer(
(Answer<Connection>)
invocation -> {
Thread.sleep(5000);
return mockNewWriterConnection;
});
when(mockTopologyService.getTopology(any(BaseConnection.class), eq(true)))
.thenReturn(newTopology);
when(mockReaderFailover.getReaderConnection(ArgumentMatchers.anyList()))
.thenReturn(new ReaderFailoverResult(mockReaderA_Connection, readerA_Host, true));
final ClusterAwareWriterFailoverHandler target =
new ClusterAwareWriterFailoverHandler(
mockTopologyService,
mockConnectionProvider,
new Properties(),
mockReaderFailover,
60000,
5000,
5000);
final WriterFailoverResult result = target.failover(currentTopology);
assertTrue(result.isConnected());
assertTrue(result.isNewHost());
assertSame(result.getNewConnection(), mockNewWriterConnection);
assertEquals(4, result.getTopology().size());
assertEquals("new-writer-host", result.getTopology().get(0).getHost());
verify(mockTopologyService, times(1)).addToDownHostList(eq(initialWriterHost));
verify(mockTopologyService, times(1)).removeFromDownHostList(eq(newWriterHost));
}
/**
* Verify that writer failover handler fails to re-connect to any writer node.
*
* <p>topology: no changes seen by task A, changes to [new-writer, reader-A, reader-B] for taskB
* taskA: fail to re-connect to writer due to failover timeout taskB: successfully connect to
* readerA and then fail to connect to writer due to failover timeout expected test result: no
* connection
*/
@Test
public void testFailedToConnect_failoverTimeout() throws SQLException {
final AuroraTopologyService mockTopologyService = Mockito.mock(AuroraTopologyService.class);
final ConnectionProvider mockConnectionProvider = Mockito.mock(ConnectionProvider.class);
final BaseConnection mockWriterConnection = Mockito.mock(BaseConnection.class);
final BaseConnection mockNewWriterConnection = Mockito.mock(BaseConnection.class);
final BaseConnection mockReaderA_Connection = Mockito.mock(BaseConnection.class);
final BaseConnection mockReaderB_Connection = Mockito.mock(BaseConnection.class);
final ReaderFailoverHandler mockReaderFailover = Mockito.mock(ReaderFailoverHandler.class);
final HostInfo writerHost = createBasicHostInfo("writer-host", true);
final HostInfo readerA_Host = createBasicHostInfo("reader-a-host", false);
final HostInfo readerB_Host = createBasicHostInfo("reader-b-host", false);
final List<HostInfo> currentTopology = new ArrayList<>();
currentTopology.add(writerHost);
currentTopology.add(readerA_Host);
currentTopology.add(readerB_Host);
final HostInfo newWriterHost = createBasicHostInfo("new-writer-host", true);
final List<HostInfo> newTopology = new ArrayList<>();
newTopology.add(newWriterHost);
newTopology.add(readerA_Host);
newTopology.add(readerB_Host);
when(mockConnectionProvider.connect(writerHost.toHostSpec(), new Properties(), writerHost.getUrl()))
.thenAnswer(
(Answer<Connection>)
invocation -> {
Thread.sleep(30000);
return mockWriterConnection;
});
when(mockConnectionProvider.connect(readerA_Host.toHostSpec(), new Properties(),
readerA_Host.getUrl())).thenReturn(mockReaderA_Connection);
when(mockConnectionProvider.connect(readerB_Host.toHostSpec(), new Properties(),
readerB_Host.getUrl())).thenReturn(mockReaderB_Connection);
when(mockConnectionProvider.connect(newWriterHost.toHostSpec(), new Properties(),
newWriterHost.getUrl()))
.thenAnswer(
(Answer<Connection>)
invocation -> {
Thread.sleep(30000);
return mockNewWriterConnection;
});
when(mockTopologyService.getTopology(eq(mockWriterConnection), any(Boolean.class)))
.thenReturn(currentTopology);
when(mockTopologyService.getTopology(eq(mockNewWriterConnection), any(Boolean.class)))
.thenReturn(newTopology);
when(mockReaderFailover.getReaderConnection(ArgumentMatchers.anyList()))
.thenReturn(new ReaderFailoverResult(mockReaderA_Connection, readerA_Host, true));
final ClusterAwareWriterFailoverHandler target =
new ClusterAwareWriterFailoverHandler(
mockTopologyService,
mockConnectionProvider,
new Properties(),
mockReaderFailover,
5000,
2000,
2000);
final WriterFailoverResult result = target.failover(currentTopology);
assertFalse(result.isConnected());
assertFalse(result.isNewHost());
verify(mockTopologyService, times(1)).addToDownHostList(eq(writerHost));
}
/**
* Verify that writer failover handler fails to re-connect to any writer node.
*
* <p>topology: changes to [new-writer, reader-A, reader-B] for taskB taskA: fail to re-connect
* to
* writer due to exception taskB: successfully connect to readerA and then fail to connect to
* writer due to exception expected test result: no connection
*/
@Test
public void testFailedToConnect_taskAException_taskBWriterException() throws SQLException {
final AuroraTopologyService mockTopologyService = Mockito.mock(AuroraTopologyService.class);
final ConnectionProvider mockConnectionProvider = Mockito.mock(ConnectionProvider.class);
final BaseConnection mockReaderA_Connection = Mockito.mock(BaseConnection.class);
final BaseConnection mockReaderB_Connection = Mockito.mock(BaseConnection.class);
final ReaderFailoverHandler mockReaderFailover = Mockito.mock(ReaderFailoverHandler.class);
final HostInfo writerHost = createBasicHostInfo("writer-host", true);
final HostInfo readerA_Host = createBasicHostInfo("reader-a-host", false);
final HostInfo readerB_Host = createBasicHostInfo("reader-b-host", false);
final List<HostInfo> currentTopology = new ArrayList<>();
currentTopology.add(writerHost);
currentTopology.add(readerA_Host);
currentTopology.add(readerB_Host);
final HostInfo newWriterHost = createBasicHostInfo("new-writer-host", true);
final List<HostInfo> newTopology = new ArrayList<>();
newTopology.add(newWriterHost);
newTopology.add(readerA_Host);
newTopology.add(readerB_Host);
when(mockConnectionProvider.connect(eq(writerHost.toHostSpec()), any(Properties.class), eq(writerHost.getUrl()))).thenThrow(SQLException.class);
when(mockConnectionProvider.connect(eq(readerA_Host.toHostSpec()), any(Properties.class),
eq(readerA_Host.getUrl()))).thenReturn(mockReaderA_Connection);
when(mockConnectionProvider.connect(eq(readerB_Host.toHostSpec()), any(Properties.class),
eq(readerB_Host.getUrl()))).thenReturn(mockReaderB_Connection);
when(mockConnectionProvider.connect(eq(newWriterHost.toHostSpec()), any(Properties.class),
eq(newWriterHost.getUrl()))).thenThrow(SQLException.class);
when(mockTopologyService.getTopology(any(BaseConnection.class), any(Boolean.class)))
.thenReturn(newTopology);
when(mockReaderFailover.getReaderConnection(ArgumentMatchers.anyList()))
.thenReturn(new ReaderFailoverResult(mockReaderA_Connection, readerA_Host, true));
final ClusterAwareWriterFailoverHandler target =
new ClusterAwareWriterFailoverHandler(
mockTopologyService,
mockConnectionProvider,
new Properties(),
mockReaderFailover,
5000,
2000,
2000);
final WriterFailoverResult result = target.failover(currentTopology);
assertFalse(result.isConnected());
assertFalse(result.isNewHost());
verify(mockTopologyService, times(1)).addToDownHostList(eq(writerHost));
verify(mockTopologyService, atLeastOnce()).addToDownHostList(eq(newWriterHost));
}
}
| true
|
f3ace8a75396e3b7c79ca1bcc2bc87076e78450d
|
Java
|
dorizorus/ATOS-fil-rouge-back
|
/src/main/java/atos/bdd/controller/CollaborateurController.java
|
UTF-8
| 6,268
| 2.390625
| 2
|
[] |
no_license
|
package atos.bdd.controller;
import atos.bdd.dao.ICollaborateurDao;
import atos.bdd.dao.IExperienceDao;
import atos.bdd.model.Collaborateur;
import atos.bdd.model.relation.Cle_collab_competence;
import atos.bdd.model.relation.Collaborateurs_Competences;
import atos.bdd.view.MyJsonView;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.fasterxml.jackson.annotation.JsonView;
@CrossOrigin
@RestController
public class CollaborateurController {
ICollaborateurDao iCollaborateurDao;
IExperienceDao iExperienceDao;
@Autowired
public CollaborateurController(ICollaborateurDao iCollaborateurDao, IExperienceDao iExperienceDao) {
this.iCollaborateurDao = iCollaborateurDao;
this.iExperienceDao = iExperienceDao;
}
@JsonView(MyJsonView.Collaborateur.class)
@GetMapping("/collaborateur/{id}") // Renvoie un collaborateur
public Collaborateur getCollaborateur(@PathVariable long id)
{
return iCollaborateurDao.findById(id);
}
@PostMapping("/collaborateur/ajoutercollaborateur") // Ajoute une compétence. Ne vérifie pas l'objet donc ne renvoie que du true.
public boolean ajouterCollaborateur(@RequestBody Collaborateur collaborateur)
{
iCollaborateurDao.save(collaborateur);
iCollaborateurDao.saveAndFlush(collaborateur); //flush car récup id du collab
for (Collaborateurs_Competences experience: collaborateur.getExperiences())
{
Cle_collab_competence cle = new Cle_collab_competence();
cle.setIdCollaborateur(collaborateur.getId());
cle.setIdCompetence(experience.getCompetence().getId());
experience.setId(cle);
experience.setCollaborateur(collaborateur);
iExperienceDao.save(experience);
}
// collaborateur.getExperiences().forEach(
// (experience) -> {
// Cle_collab_competence cle = new Cle_collab_competence();
// cle.setIdCollaborateur(collaborateur.getId());
// cle.setIdCompetence(experience.getCompetence().getId());
// experience.setId(cle);
// experience.setCollaborateur(collaborateur);
// iExperienceDao.save(experience);
// }
// );
return true;
}
@GetMapping("/collaborateur/supprimercollaborateur")
public boolean supprimerCollaborteur(@RequestBody Collaborateur collaborateur) // Supprimer collaborateur. Ne vérifie pas s'il est la ou non.
{
iCollaborateurDao.delete(collaborateur);
return true;
}
@PostMapping("/collaborateur/modifiercollaborateur/{id}") // Modifier collaborateur sans vraiment check d'autres trucs
public boolean modifierCollaborateur(@PathVariable long id, @RequestBody Collaborateur collaborateur)
{
if (iCollaborateurDao.findById(id) != null) {
iCollaborateurDao.save(collaborateur);
return true;
} else
return false;
}
@JsonView(MyJsonView.Collaborateur.class)
@GetMapping("/collaborateur/listepartitrecroissant")
public List<Collaborateur> ListeCollaborateurTitreCro() // Renvoie une liste complète de collabo trié par Titre (croissant)
{
return iCollaborateurDao.findAllByOrderByTitreAsc();
}
@JsonView(MyJsonView.Collaborateur.class)
@GetMapping("/collaborateur/listepartitredecroissant")
public List<Collaborateur> ListeCollaborateurTitreDec() // Renvoie une liste compléte de collabo trié par Titre (décroissant)
{
return iCollaborateurDao.findAllByOrderByTitreDesc();
}
@JsonView(MyJsonView.Collaborateur.class)
@GetMapping("/collaborateur/listeparnomcroissant")
public List<Collaborateur> ListeCollaborateurNomCro() // Renvoie une liste complète de collabo trié par Nom (croissant)
{
return iCollaborateurDao.findAllByOrderByNomAsc();
}
@JsonView(MyJsonView.Collaborateur.class)
@GetMapping("/collaborateur/listeparnomdecroissant")
public List<Collaborateur> ListeCollaborateurNomDec() // Renvoie une liste complète de collabo trié par Nom (décroissant)
{
return iCollaborateurDao.findAllByOrderByNomDesc();
}
@JsonView(MyJsonView.Collaborateur.class)
@GetMapping("/collaborateur/listeparprenomcroissant")
public List<Collaborateur> ListeCollaborateurPrenomCro() // Renvoie une liste complète de collabo trié par Prenom (croissant)
{
return iCollaborateurDao.findAllByOrderByPrenomAsc();
}
@JsonView(MyJsonView.Collaborateur.class)
@GetMapping("/collaborateur/listeparprenomdecroissant")
public List<Collaborateur> ListeCollaborateurPrenomDec() // Renvoie une liste complète de collabo trié par Prenom (décroissant)
{
return iCollaborateurDao.findAllByOrderByPrenomDesc();
}
@JsonView(MyJsonView.Collaborateur.class)
@GetMapping("/collaborateur/listeparidentifiantcroissant")
public List<Collaborateur> ListeCollaborateurIdentifiantCro() // Renvoie une liste complète de collabo trié par Identifiant (croissant)
{
return iCollaborateurDao.findAllByOrderByIdentifiantAsc();
}
@JsonView(MyJsonView.Collaborateur.class)
@GetMapping("/collaborateur/listeparidentifiantdecroissant")
public List<Collaborateur> ListeCollaborateurIdentifiantDec() // Renvoie une liste complète de collabo trié par Identifiant (décroissant)
{
return iCollaborateurDao.findAllByOrderByIdentifiantDesc();
}
@JsonView(MyJsonView.Collaborateur.class)
@GetMapping("/collaborateur/listeparbenchcroissant")
public List<Collaborateur> ListeCollaborateurBenchCro() // Renvoie une liste complète de collabo trié par Bench (croissant)
{
return iCollaborateurDao.findAllByOrderByBenchAsc();
}
@JsonView(MyJsonView.Collaborateur.class)
@GetMapping("/collaborateur/listeparbenchdecroissant")
public List<Collaborateur> ListeCollaborateurBenchDec() // Renvoie une liste complète de collabo trié par Bench (decroissant)
{
return iCollaborateurDao.findAllByOrderByBenchDesc();
}
}
| true
|
decb2995e97f357664dcbe75d76cc15b417f4400
|
Java
|
dipkothari/Assignments
|
/Day2/src/SelfReview/Example1.java
|
UTF-8
| 232
| 2.671875
| 3
|
[] |
no_license
|
package SelfReview;
public class Example1 {
public static void main(String[] args) {
int intValOne=5, intValTwo=7;
System.out.println(((intValTwo * 2)% intValOne));
System.out.println((intValTwo % intValOne));
}
}
| true
|
8869d279478f25b4593fdf8bb8512eaa0838f24e
|
Java
|
MitashGaurh/MusicLibrary
|
/src/main/java/com/mitashgaurh/musiclibrary/java/dao/SongDao.java
|
UTF-8
| 377
| 2.140625
| 2
|
[] |
no_license
|
package com.mitashgaurh.musiclibrary.java.dao;
import com.mitashgaurh.musiclibrary.java.entities.Song;
import java.util.List;
public interface SongDao {
Song addSong(Song song);
Song updateSong(Song song);
void deleteSong(Song song);
Song findSongById(Integer songId);
List<Song> getSongs();
List<Song> getSongsByCriteria(List<Integer> ids);
}
| true
|
aa3fbac75776a8b8661a68d3e75a5d90a1a759d9
|
Java
|
dabaoqiang/rabbitmq-demo
|
/src/main/java/com/xxq/rest/rabbitmq/demo1/demo6/ReceiveLogsToConsole.java
|
UTF-8
| 1,687
| 2.78125
| 3
|
[] |
no_license
|
package com.xxq.rest.rabbitmq.demo1.demo6;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.QueueingConsumer;
/**
* 控制器日志打印
*/
public class ReceiveLogsToConsole implements Runnable {
// 转发器
private static final String EXCHANGE_NAME = "ex_log";
public static void text() {
try {
System.out.println(Thread.currentThread().getName()+ " 当前线程 开始监听");
ConnectionFactory connectionFactory = new ConnectionFactory();
connectionFactory.setHost("localHost");
Connection connection = connectionFactory.newConnection();
Channel channel = connection.createChannel();
String queueName = channel.queueDeclare().getQueue();
// 第一个参数 队列名称,第二个参数转发器;
channel.queueBind(queueName, EXCHANGE_NAME, "");
System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
QueueingConsumer queueingConsumer = new QueueingConsumer(channel);
// 第一参数:队列名称,第二个参数 自动回答,第三个参数 消息队列
channel.basicConsume(queueName,true, queueingConsumer);
while (true) {
QueueingConsumer.Delivery delivery = queueingConsumer.nextDelivery();
String message = new String(delivery.getBody());
System.out.println(Thread.currentThread().getName() + ": 获取信息 :" + message);
}
}catch (Exception e){
e.getStackTrace();
}
}
@Override
public void run() {
text();
}
}
| true
|
d6163868f865bd0f68614d7eb015f01e8cc02004
|
Java
|
Grrui/ECollaborationMaven
|
/src/main/java/action/com/logIn/LogInAction.java
|
UTF-8
| 3,471
| 2.265625
| 2
|
[] |
no_license
|
package action.com.logIn;
import com.opensymphony.xwork2.ActionSupport;
import net.sf.json.JSONObject;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.interceptor.SessionAware;
import org.springframework.context.ApplicationContext;
import pojo.businessObject.UserBO;
import pojo.valueObject.domain.UserVO;
import tool.BeanFactory;
import tool.JSONHandler;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.util.Map;
import java.util.logging.Handler;
/**
* 登录
* Created by geyao on 2017/2/19.
*/
public class LogInAction extends ActionSupport implements ServletRequestAware, ServletResponseAware, SessionAware {
//jsp获取:
private String userName;
private String passWord;
private HttpServletRequest request;
private HttpServletResponse response;
private Map<String, Object> session;
private JSONObject jsonObject;
@Override
public String execute() throws Exception {
session.clear();
System.out.println("session已清空 ========= ");
UserBO userBO = BeanFactory.getBean("userBO",UserBO.class);
try {
System.out.println("request" + request);
jsonObject = userBO.logIn(userName, passWord, session);
System.out.println("jsonObject = " + jsonObject);
//43行调用的logIn已经对result赋值了?
// jsonObject.put("result", "success");
JSONHandler.sendJSON(jsonObject,response);
System.out.println("登录");
System.out.println(jsonObject);
return jsonObject.get("role").toString();
}catch(Exception e){
e.printStackTrace();
jsonObject.put("result","SQLException");
JSONHandler.sendJSON(jsonObject, response);
return "fail";
}
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassWord() {
return passWord;
}
public void setPassWord(String passWord) {
this.passWord = passWord;
}
@Override
public void setServletRequest(HttpServletRequest request) {
this.request = request;
try {
this.request.setCharacterEncoding("UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
@Override
public void setServletResponse(HttpServletResponse response) {
this.response = response;
this.response.setCharacterEncoding("UTF-8");
}
@Override
public void setSession(Map<String, Object> session) {
this.session = session;
}
public HttpServletRequest getRequest() {
return request;
}
public void setRequest(HttpServletRequest request) {
this.request = request;
}
public HttpServletResponse getResponse() {
return response;
}
public void setResponse(HttpServletResponse response) {
this.response = response;
}
public Map<String, Object> getSession() {
return session;
}
public JSONObject getJsonObject() {
return jsonObject;
}
public void setJsonObject(JSONObject jsonObject) {
this.jsonObject = jsonObject;
}
}
| true
|
c0da9fbb64e4359403607327b0defff3a2a8b849
|
Java
|
Gaurav-Gaikwad-1/Placement-Management-System
|
/src/campusrecruitmentsystem/Driver.java
|
UTF-8
| 207
| 1.5625
| 2
|
[] |
no_license
|
package campusrecruitmentsystem;
import Dashboard.MainScreen;
import LoginPages.Login;
public class Driver {
public static void main(String args[]){
new MainScreen().setVisible(true);
}
}
| true
|
b4e927ae09dc45ee9421e2ba5c94c4d93e1fa271
|
Java
|
pgithaiga/Pingball
|
/pingball-phase2/src/pingball/simulation/GridLocation.java
|
UTF-8
| 1,008
| 3.234375
| 3
|
[] |
no_license
|
package pingball.simulation;
import physics.Vect;
import pingball.util.Pair;
/**
* A grid location on the board.
*
* This is a lightweight wrapper around Pair.
*
* Rep-Invariant:
* None. The pair of integer can be anything within Integer range.
*/
public class GridLocation extends Pair<Integer, Integer> {
public GridLocation(Integer x, Integer y) {
super(x, y);
}
public static GridLocation of(Integer x, Integer y) {
return new GridLocation(x, y);
}
public Integer x() {
return getFirst();
}
public Integer y() {
return getSecond();
}
public GridLocation add (Integer dx, Integer dy){
return new GridLocation(this.getFirst()+dx,this.getSecond()+dy);
}
public GridLocation add (int[] displaceBy){
return new GridLocation(this.getFirst()+displaceBy[0],this.getSecond()+displaceBy[1]);
}
public Vect toVect(){
return new Vect(this.getFirst(),this.getSecond());
}
}
| true
|
e9df8bca33e751d57d60a7e934bfc247b7153c43
|
Java
|
fabiano1749/cepalab
|
/SistemaVendas/src/main/java/com/cepalab/sistemaVendas/operacao/controle/pesquisaRecebimentoInadimplenteBean.java
|
UTF-8
| 3,003
| 1.976563
| 2
|
[] |
no_license
|
package com.cepalab.sistemaVendas.operacao.controle;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.view.ViewScoped;
import javax.inject.Inject;
import javax.inject.Named;
import com.cepalab.sistemaVendas.cadastro.dominio.Funcionario;
import com.cepalab.sistemaVendas.cadastro.dominio.Grupo;
import com.cepalab.sistemaVendas.operacao.dominio.RecebimentoInadiplente;
import com.cepalab.sistemaVendas.repository.Funcionarios;
import com.cepalab.sistemaVendas.repository.RecebimentosInadiplentes;
import com.cepalab.sistemaVendas.repository.filter.RecebimentoInadimplenteFilter;
import com.cepalab.sistemaVendas.security.Seguranca;
import com.cepalab.sistemaVendas.util.jsf.FacesUtil;
@Named
@ViewScoped
public class pesquisaRecebimentoInadimplenteBean implements Serializable {
private static final long serialVersionUID = 1L;
private RecebimentoInadimplenteFilter filtro;
private List<RecebimentoInadiplente> recebimentosFiltrados = new ArrayList<>();
private List<Funcionario> listaFuncionarios = new ArrayList<>();
private RecebimentoInadiplente recebimento = new RecebimentoInadiplente();
@Inject
private RecebimentosInadiplentes recebimentos;
@Inject
private Funcionarios funcionarios;
@Inject
private Seguranca seg;
@PostConstruct
public void inicio() {
filtro = new RecebimentoInadimplenteFilter();
if (isVendedor()) {
filtro.setFuncionario(seg.UsuarioLogado());
} else {
listaFuncionarios = funcionarios.vendedorAtivo();
}
}
public void pesquisar() {
recebimentosFiltrados = recebimentos.recebimentosFiltrados(filtro);
}
public boolean isVendedor() {
for (Grupo g : seg.UsuarioLogado().getTipo().getGrupos()) {
if (g.getNome().equals("VENDEDORES")) {
return true;
}
}
return false;
}
public void troca(RecebimentoInadiplente recebimento) {
this.recebimento = recebimento;
}
public void excluir() {
try {
recebimentos.remover(recebimento);
FacesUtil.addInfoMessage("Recebimento inadimplente excluído com sucesso");
pesquisar();
} catch (Exception e) {
FacesUtil.addErrorMessage(e.getMessage());
}
}
public List<RecebimentoInadiplente> getRecebimentosFiltrados() {
return recebimentosFiltrados;
}
public void setRecebimentosFiltrados(List<RecebimentoInadiplente> recebimentosFiltrados) {
this.recebimentosFiltrados = recebimentosFiltrados;
}
public RecebimentoInadimplenteFilter getFiltro() {
return filtro;
}
public void setFiltro(RecebimentoInadimplenteFilter filtro) {
this.filtro = filtro;
}
public List<Funcionario> getListaFuncionarios() {
return listaFuncionarios;
}
public void setListaFuncionarios(List<Funcionario> listaFuncionarios) {
this.listaFuncionarios = listaFuncionarios;
}
public RecebimentoInadiplente getRecebimento() {
return recebimento;
}
public void setRecebimento(RecebimentoInadiplente recebimento) {
this.recebimento = recebimento;
}
}
| true
|
9490953120b15f59edc4a61861d7cb046cfeeb2c
|
Java
|
jingw/hanabi-bot
|
/src/main/java/hanabi/BitVectorUtil.java
|
UTF-8
| 786
| 3.4375
| 3
|
[] |
no_license
|
package hanabi;
public class BitVectorUtil {
/**
* Remove the ith bit by shifting down all higher order bits
*/
public static int deleteAndShift(int vector, int i) {
int lowerMask = (1 << i) - 1;
int upperMask = ~((1 << (i + 1)) - 1);
return ((vector & upperMask) >>> 1) | (vector & lowerMask);
}
/**
* Extract the lowest n set bits. Returns the original vector if there are less than n set bits.
*/
public static int lowestSetBits(int vector, int n) {
int result = 0;
int count = 0;
for (int i = 0; i < Integer.SIZE && count < n; i++) {
if ((vector & (1 << i)) != 0) {
result |= 1 << i;
count++;
}
}
return result;
}
}
| true
|
cb8aab6579a9f95167f2792c322ba86920d87eed
|
Java
|
DefNeoRoman/resumeStorage2
|
/src/test/java/abstractClasses/AbstractStorageTest.java
|
UTF-8
| 3,102
| 2.671875
| 3
|
[] |
no_license
|
package abstractClasses;
import TestData.*;
import com.exception.ExistStorageException;
import com.exception.NotExistStorageException;
import com.model.*;
import com.storage.interfaces.Storage;
import com.Config;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import static java.util.Objects.requireNonNull;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public abstract class AbstractStorageTest {
protected final Storage storage;
protected static final File STORAGE_DIR = Config.getInstance().getStorageDir();
public AbstractStorageTest(Storage storage) {
requireNonNull(storage, "Storage must not be null");
this.storage = storage;
}
@Before
public void setUp() throws Exception {
storage.clear();
storage.save(TestData.RESUME_1);
storage.save(TestData.RESUME_2);
storage.save(TestData.RESUME_3);
storage.save(TestData.FULL_RESUME);
}
@Test
public void clear()throws Exception{
storage.clear();
assertSize(0);
}
@Test
public void get() throws Exception{
assertGet(TestData.RESUME_1);
assertGet(TestData.RESUME_2);
assertGet(TestData.RESUME_3);
assertGet(TestData.FULL_RESUME);
}
@Test(expected = NotExistStorageException.class)
public void assertNotExist(){
storage.get("dfdfdf");
}
@Test(expected = ExistStorageException.class)
public void saveAlreadyExist() throws Exception{
// List <Resume> lr = storage.getAllSorted();
// Resume resume = lr.get(0);
storage.save(TestData.RESUME_X);
storage.save(TestData.RESUME_X);
}
@Test
public void save() throws Exception{
int sz = storage.size();
storage.save(new Resume(TestData.UUID_X, TestData.FULL_NAME_X));
assertSize(sz + 1);
Assert.assertEquals(TestData.RESUME_X, storage.get(TestData.UUID_X));
}
@Test
public void getAll(){
List<Resume> r = storage.getAllSorted();
Assert.assertEquals(4, r.size());
List<Resume> list= Arrays.asList(TestData.RESUME_1,TestData.RESUME_2, TestData.RESUME_3, TestData.FULL_RESUME);
Collections.sort(list);
Assert.assertEquals(r, list);
}
@Test
public void delete()throws Exception{
int sz = storage.size();
List<Resume> copyStorage = storage.getAllSorted();
storage.delete(copyStorage.get(sz - 1).getUuid());
// copyStorage.remove(sz - 1);
assertSize(sz - 1);
}
private void assertArrayWithSort(Resume... resumes){
List<Resume> arr = Arrays.asList(resumes);
assertTrue(arr.containsAll(storage.getAllSorted()));
}
private void assertGet(Resume resume){
assertEquals(resume, storage.get(resume.getUuid()));
}
private void assertSize(int size){
assertEquals(size, storage.size());
}
}
| true
|
cce3e7a1b974465e03bdc6b0e0a77152fe7263fa
|
Java
|
percussion/percussioncms
|
/projects/sitemanage/src/test/java/com/percussion/share/data/PSDataObjectTestCase.java
|
UTF-8
| 1,772
| 1.851563
| 2
|
[
"LicenseRef-scancode-dco-1.1",
"Apache-2.0",
"OFL-1.1",
"LGPL-2.0-or-later"
] |
permissive
|
/*
* Copyright 1999-2023 Percussion Software, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.percussion.share.data;
import static org.junit.Assert.*;
import static com.percussion.share.test.PSDataObjectTestUtils.*;
import org.junit.Before;
import org.junit.Test;
import com.percussion.share.test.PSDataObjectTestUtils;
public abstract class PSDataObjectTestCase<T>
{
public abstract T getObject() throws Exception;
protected T object;
@Before
public void setUp() throws Exception
{
object = getObject();
assertNotNull(object);
}
protected T getCopy() {
return PSDataObjectTestUtils.doXmlSerialization(object).actualSerialized;
}
@Test
public void testXmlSerialization() throws Exception
{
assertXmlSerialization(object);
}
@Test
public void testEquals() throws Exception
{
assertEqualsMethod(object);
}
@Test
public void testToString() throws Exception
{
assertNotNull(object.toString());
}
@Test
public void testHashCode() throws Exception
{
}
@Test
public void testClone() throws Exception
{
}
}
| true
|
7530af86247f1871f630c2de95b05f27aefd2099
|
Java
|
YongCheng97/Beautify
|
/Beautify-ws/src/java/ws/restful/StaffResource.java
|
UTF-8
| 3,022
| 2.265625
| 2
|
[] |
no_license
|
package ws.restful;
import ejb.session.stateless.ServiceProviderSessionBeanLocal;
import ejb.session.stateless.StaffSessionBeanLocal;
import entity.ServiceProvider;
import entity.Staff;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.Produces;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PUT;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import util.exception.InputDataValidationException;
import util.exception.InvalidLoginCredentialException;
import util.exception.ServiceProviderExistException;
import util.exception.StaffUsernameExistException;
import util.exception.UnknownPersistenceException;
import ws.datamodel.CreateServiceProviderReq;
import ws.datamodel.CreateServiceProviderRsp;
import ws.datamodel.CreateStaffReq;
import ws.datamodel.CreateStaffRsp;
import ws.datamodel.ErrorRsp;
import ws.datamodel.ServiceProviderLoginRsp;
import ws.datamodel.StaffLoginRsp;
import ws.datamodel.UpdateServiceProviderReq;
@Path("Staff")
public class StaffResource {
@Context
private UriInfo context;
private StaffSessionBeanLocal staffSessionBean = lookupStaffSessionBeanLocal();
public StaffResource() {
}
@Path("staffLogin")
@GET
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.APPLICATION_JSON)
public Response login(@QueryParam("username") String username,
@QueryParam("password") String password) {
try {
Staff staff = staffSessionBean.staffLogin(username, password);
System.out.println("********** StaffResource.staffLogin(): Staff " + staff.getEmail() + " login remotely via web service");
return Response.status(Status.OK).entity(new StaffLoginRsp(staff)).build();
} catch (InvalidLoginCredentialException ex) {
ErrorRsp errorRsp = new ErrorRsp(ex.getMessage());
System.out.println("test2");
return Response.status(Response.Status.UNAUTHORIZED).entity(errorRsp).build();
} catch (Exception ex) {
ErrorRsp errorRsp = new ErrorRsp(ex.getMessage());
System.out.println("test3");
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorRsp).build();
}
}
private StaffSessionBeanLocal lookupStaffSessionBeanLocal() {
try {
javax.naming.Context c = new InitialContext();
return (StaffSessionBeanLocal) c.lookup("java:global/Beautify/Beautify-ejb/StaffSessionBean!ejb.session.stateless.StaffSessionBeanLocal");
} catch (NamingException ne) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
throw new RuntimeException(ne);
}
}
}
| true
|
5c3e5f797d352155f543374b623ebf4d2bae09ce
|
Java
|
vradhan/Hackathon
|
/SpringBoot-master/src/main/java/com/primefaces/bean/MachineBean.java
|
UTF-8
| 5,468
| 2.359375
| 2
|
[] |
no_license
|
package com.primefaces.bean;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.inject.Named;
import org.primefaces.model.chart.Axis;
import org.primefaces.model.chart.AxisType;
import org.primefaces.model.chart.BarChartModel;
import org.primefaces.model.chart.ChartSeries;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.primefaces.serviceImpl.MachineServiceImpl;
@Named(value = "machine")
@Component
public class MachineBean {
@Autowired
private MachineServiceImpl machineService;
private Long machineID;
private String timePeriod;
private int output;
private Date date;
List<MachineBean> effectiveMachine = new ArrayList<MachineBean>();
List<MachineBean> pastEffectiveMachine = new ArrayList<MachineBean>();
public Long getMachineID() {
return machineID;
}
public void setMachineID(Long machineID) {
this.machineID = machineID;
}
public String getTimePeriod() {
return timePeriod;
}
public void setTimePeriod(String timePeriod) {
this.timePeriod = timePeriod;
}
public int getOutput() {
return output;
}
public void setOutput(int output) {
this.output = output;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public MachineServiceImpl getMachineService() {
return machineService;
}
public void setMachineService(MachineServiceImpl machineService) {
this.machineService = machineService;
}
public List<MachineBean> getEffectiveMachine() {
return effectiveMachine;
}
public void setEffectiveMachine(List<MachineBean> effectiveMachine) {
this.effectiveMachine = effectiveMachine;
}
public List<MachineBean> getPastEffectiveMachine() {
return pastEffectiveMachine;
}
public void setPastEffectiveMachine(List<MachineBean> pastEffectiveMachine) {
this.pastEffectiveMachine = pastEffectiveMachine;
}
@PostConstruct
public void init() {
effectiveMachine = machineService.todaysEfficiency();
pastEffectiveMachine = machineService.pastEfficiency();
createBarModels();
createBarModels2();
}
private BarChartModel barModel;
private BarChartModel barModel2;
public BarChartModel getBarModel2() {
return barModel2;
}
public BarChartModel getBarModel() {
return barModel;
}
private BarChartModel initBarModel() {
BarChartModel model = new BarChartModel();
ChartSeries boys = new ChartSeries();
boys.setLabel("Machine Capacity Output/Hour");
boys.set("9 - 10", 100);
boys.set("10 - 11", 100);
boys.set("11 - 12", 100);
boys.set("12 - 13", 100);
boys.set("13- 14", 100);
ChartSeries girls = new ChartSeries();
girls.setLabel("Machine Actual Output Today");
girls.set("9 - 10", 20);
girls.set("10 -11", 11);
girls.set("11 - 12", 18);
girls.set("12 - 13", 26);
girls.set("13 - 14", 45);
model.addSeries(boys);
model.addSeries(girls);
return model;
}
private BarChartModel initBarModel2() {
BarChartModel model = new BarChartModel();
ChartSeries boys = new ChartSeries();
boys.setLabel("Machine Actual Output Today");
boys.set("9 - 10", 20);
boys.set("10 - 11", 11);
boys.set("11 - 12", 18);
boys.set("12 - 13", 26);
boys.set("13- 14", 45);
ChartSeries girls = new ChartSeries();
girls.setLabel("Machine Actual Output past Date");
girls.set("9 - 10", 25);
girls.set("10 -11", 45);
girls.set("11 - 12", 18);
girls.set("12 - 13", 23);
girls.set("13 - 14", 50);
model.addSeries(boys);
model.addSeries(girls);
return model;
}
private void createBarModels() {
createBarModel();
createBarModel2();
}
private void createBarModels2() {
createBarModel2();
}
private void createBarModel() {
barModel = initBarModel();
barModel.setTitle("Bar Chart");
barModel.setLegendPosition("ne");
Axis xAxis = barModel.getAxis(AxisType.X);
xAxis.setLabel("OutPut/Hour");
Axis yAxis = barModel.getAxis(AxisType.Y);
yAxis.setLabel("Total OutPut");
yAxis.setMin(0);
yAxis.setMax(200);
}
private void createBarModel2() {
barModel2 = initBarModel2();
barModel2.setTitle("Bar Chart");
barModel2.setLegendPosition("ne");
Axis xAxis = barModel2.getAxis(AxisType.X);
xAxis.setLabel("OutPut/Hour");
Axis yAxis = barModel2.getAxis(AxisType.Y);
yAxis.setLabel("Total OutPut");
yAxis.setMin(0);
yAxis.setMax(100);
}
public void save(){
MachineBean mm = new MachineBean();
mm.setMachineID(1L);
mm.setDate(new Date());
mm.setTimePeriod("13 - 14");
mm.setOutput(80);
effectiveMachine.add(mm);
}
public LocalTime currentTime(){
return java.time.LocalTime.now();
}
}
| true
|
c709ab8d5223e4570563306852b80a302bd1d7a0
|
Java
|
zsl131/hlx
|
/src/main/java/com/zslin/multi/controller/AdminDiningTableController.java
|
UTF-8
| 4,601
| 2.078125
| 2
|
[] |
no_license
|
package com.zslin.multi.controller;
import com.zslin.basic.annotations.AdminAuth;
import com.zslin.basic.annotations.Token;
import com.zslin.basic.repository.SimplePageBuilder;
import com.zslin.basic.repository.SimpleSortBuilder;
import com.zslin.basic.tools.MyBeanUtils;
import com.zslin.basic.tools.TokenTools;
import com.zslin.basic.utils.ParamFilterUtil;
import com.zslin.client.tools.ClientFileTools;
import com.zslin.client.tools.ClientJsonTools;
import com.zslin.multi.dao.IDiningTableDao;
import com.zslin.multi.dao.IStoreDao;
import com.zslin.multi.model.DiningTable;
import com.zslin.multi.model.Store;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
@Controller
@RequestMapping(value="admin/diningTable")
@AdminAuth(name="餐桌管理", orderNum=10, psn="多店管理", pentity=0, porderNum=20)
public class AdminDiningTableController {
@Autowired
private IStoreDao storeDao;
@Autowired
private IDiningTableDao diningTableDao;
@Autowired
private ClientFileTools clientFileTools;
@GetMapping(value = "list")
@AdminAuth(name = "餐桌管理", orderNum = 1, type = "1", icon = "fa fa-desktop")
public String list(Model model, Integer page, HttpServletRequest request) {
Page<DiningTable> datas = diningTableDao.findAll(ParamFilterUtil.getInstance().buildSearch(model, request),
SimplePageBuilder.generate(page, SimpleSortBuilder.generateSort("orderNo_d")));
model.addAttribute("datas", datas);
List<Store> storeList = storeDao.findAll();
model.addAttribute("storeList", storeList);
return "admin/multi/diningTable/list";
}
@Token(flag= Token.READY)
@AdminAuth(name = "添加餐桌", orderNum = 2, icon="fa fa-plus")
@RequestMapping(value="add", method= RequestMethod.GET)
public String add(Model model, HttpServletRequest request) {
model.addAttribute("diningTable", new DiningTable());
List<Store> storeList = storeDao.findAll();
model.addAttribute("storeList", storeList);
return "admin/multi/diningTable/add";
}
@Token(flag= Token.CHECK)
@RequestMapping(value="add", method=RequestMethod.POST)
public String add(Model model, DiningTable table, HttpServletRequest request) {
if(TokenTools.isNoRepeat(request)) { //不是重复提交
diningTableDao.save(table);
send2Client(table, "save");
}
return "redirect:/admin/diningTable/list";
}
@Token(flag= Token.READY)
@AdminAuth(name="修改餐桌信息", orderNum=3, icon = "fa fa-pencil")
@RequestMapping(value="update/{id}", method=RequestMethod.GET)
public String update(Model model, @PathVariable Integer id, HttpServletRequest request) {
DiningTable s = diningTableDao.findOne(id);
model.addAttribute("diningTable", s);
List<Store> storeList = storeDao.findAll();
model.addAttribute("storeList", storeList);
return "admin/multi/diningTable/update";
}
@Token(flag= Token.CHECK)
@RequestMapping(value="update/{id}", method=RequestMethod.POST)
public String update(Model model, @PathVariable Integer id, DiningTable table, HttpServletRequest request) {
if(TokenTools.isNoRepeat(request)) {
DiningTable d = diningTableDao.findOne(id);
MyBeanUtils.copyProperties(table, d, "id");
diningTableDao.save(d);
send2Client(d, "save");
}
return "redirect:/admin/diningTable/list";
}
@AdminAuth(name="删除餐桌", orderNum=4, icon = "fa fa-remove")
@RequestMapping(value="delete/{id}", method=RequestMethod.POST)
public @ResponseBody
String delete(@PathVariable Integer id) {
try {
DiningTable table = diningTableDao.findOne(id);
send2Client(table, "delete");
diningTableDao.delete(table);
return "1";
} catch (Exception e) {
return "0";
}
}
private void send2Client(DiningTable table, String action) {
if(!"hlx".equals(table.getStoreSn())) { //如果不是hlx则需要传至客户端
String content = ClientJsonTools.buildDataJson(ClientJsonTools.buildDiningTable(table, action));
clientFileTools.setChangeContext(table.getStoreSn(), content, true);
}
}
}
| true
|
3669cf26d84cffb40a2ea63fa1a7109a301ea741
|
Java
|
MKanoune/Prog2-1
|
/src/de/hsa/games/fatsquirrel/Core/Entity/EntityContainer.java
|
UTF-8
| 3,131
| 3.0625
| 3
|
[] |
no_license
|
package de.hsa.games.fatsquirrel.Core.Entity;
import de.hsa.games.fatsquirrel.Core.Board.EntityContext;
import de.hsa.games.fatsquirrel.Core.Entity.Entities.Squirrel.MasterSquirrel;
import de.hsa.games.fatsquirrel.Core.Movement.XY;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import java.util.*;
import java.util.stream.Collectors;
/**
* Contains all Entities in an ArrayList
*/
public class EntityContainer {
private List<Entity> collection;
private List<Entity> toDelete;
private List<Entity> toAdd;
private Logger logger = Logger.getLogger(EntityContainer.class.getName());
/**
* Constructor for the Container.
* Initialize @collection and @toAdd
*/
public EntityContainer() {
collection = new ArrayList<>();
toAdd = new ArrayList<>();
}
/**
* Insert a new Entity in the Container
* There is no check if the Entity is already in the Container!
* @param entity The Entity which has to be inserted
*/
public void insert(Entity entity) {
toAdd.add(entity);
}
/**
* Deletes one Specific Entity of the Container, the others move up
* @param entity The Entity which has to be deleted
*/
public void delete(Entity entity) {
logger.log(Level.INFO, "delete:" + entity.toString());
toDelete.add(entity);
}
/**
* Start the NextStepand the nextStepRandom of all contained Entities
* @param context The Information about the Game in form of the FlattenedBoard
*/
public void startNextStep(EntityContext context) {
toDelete = new ArrayList<>();
collection.addAll(toAdd);
toAdd = new ArrayList<>();
for(Entity aCollection : collection) {
if(toDelete.contains(aCollection)) {
continue;
}
aCollection.nextStepRandomMove();
aCollection.nextStep(context);
}
collection.removeAll(toDelete);
}
/**
* Get the Entity at one specific Position
* @param pos The XY Object which contains the Coordinates of a possible Entity
* @return The Entity at this Position, if there is no it will return null
*/
public Entity getEntity(XY pos) {
for(Entity aCollection : collection) {
if(aCollection.getXY() == pos) {
return aCollection;
}
}
return null;
}
/**
* Get The Entity at the Position in the Array
* @param pos The Int Value of the Position as Int
* @return The Content at this Position as Entity
*/
public Entity getEntity(int pos) {
return collection.get(pos);
}
public Collection getCollection() {
return collection;
}
public void addToAdd() {
collection.addAll(toAdd);
toAdd.removeAll(toAdd);
}
public void deleteAll() {
toDelete = new ArrayList<>();
toDelete.addAll(collection.stream().filter(aCollection -> !(aCollection instanceof MasterSquirrel)).collect(Collectors.toList()));
collection.removeAll(toDelete);
}
}
| true
|
b9b984c3c5e65c9e55d5306100d61dedf47ad71d
|
Java
|
zhongxingyu/Seer
|
/Diff-Raw-Data/3/3_60599cdc959a1637534dd3a0004f67ab11a72046/AbstractJBTreeView/3_60599cdc959a1637534dd3a0004f67ab11a72046_AbstractJBTreeView_s.java
|
UTF-8
| 12,063
| 1.609375
| 2
|
[] |
no_license
|
/*******************************************************************************
* Copyright (c) 2004, 2010 BREDEX GmbH.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* BREDEX GmbH - initial API and implementation and/or initial documentation
*******************************************************************************/
package org.eclipse.jubula.client.ui.rcp.views;
import javax.persistence.EntityManager;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.GroupMarker;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jubula.client.core.events.DataEventDispatcher;
import org.eclipse.jubula.client.core.events.DataEventDispatcher.IDataChangedListener;
import org.eclipse.jubula.client.core.events.DataEventDispatcher.IProjectLoadedListener;
import org.eclipse.jubula.client.core.model.IPersistentObject;
import org.eclipse.jubula.client.core.persistence.GeneralStorage;
import org.eclipse.jubula.client.core.persistence.IEntityManagerProvider;
import org.eclipse.jubula.client.ui.constants.Constants;
import org.eclipse.jubula.client.ui.rcp.Plugin;
import org.eclipse.jubula.client.ui.rcp.businessprocess.UINodeBP;
import org.eclipse.jubula.client.ui.rcp.controllers.AbstractPartListener;
import org.eclipse.jubula.client.ui.rcp.editors.AbstractTestCaseEditor;
import org.eclipse.jubula.client.ui.rcp.filter.JBBrowserPatternFilter;
import org.eclipse.jubula.client.ui.rcp.filter.JBFilteredTree;
import org.eclipse.jubula.client.ui.rcp.i18n.Messages;
import org.eclipse.jubula.client.ui.rcp.sorter.NodeNameViewerSorter;
import org.eclipse.jubula.client.ui.rcp.utils.UIIdentitiyElementComparer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.dnd.Clipboard;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.dialogs.FilteredTree;
import org.eclipse.ui.part.ViewPart;
import org.eclipse.ui.views.properties.IPropertySheetPage;
/**
* @author BREDEX GmbH
* @created 21.10.2005
*/
public abstract class AbstractJBTreeView extends ViewPart implements
IProjectLoadedListener, IDataChangedListener, IEntityManagerProvider {
/** Default expansion for the tree */
public static final int DEFAULT_EXPANSION = 2;
/** number of columns = 1 */
protected static final int NUM_COLUMNS_1 = 1;
/** vertical spacing = 2 */
protected static final int VERTICAL_SPACING = 3;
/**ImageDescrptor for the Link with Editor-Button */
private static final ImageDescriptor LINK_IMAGE_DESC =
Plugin.getImageDescriptor("linkWithEditor.gif"); //$NON-NLS-1$
/**
* <code>m_treeViewer</code>tree Viewer
*/
private TreeViewer m_treeViewer;
/**
* <code>m_treeFilterText</code>tree Viewer
*/
private Text m_treeFilterText;
/**
* This part's reference to the clipboard.
* Note that the part shares this clipboard with the entire operating
* system, and this instance is only for easier access to the clipboard.
* The clipboard does not exclusively belong to the part.
*/
private Clipboard m_clipboard;
/** flag wether the view is linked with the editor or not */
private boolean m_isLinkedWithEditor = false;
/** The partListener of this view */
private PartListener m_partListener = new PartListener();
/**
* This listener updates the selection of the view based on the activated
* part.
*
* @author BREDEX GmbH
* @created 20.09.2006
*/
private final class PartListener extends AbstractPartListener {
/**
* {@inheritDoc}
*/
public void partActivated(IWorkbenchPart part) {
setSelectionToEditorNode(part);
super.partActivated(part);
}
}
/**
* Toggles "Link with Editor" functionality for this view. When linked,
* the selection of the view can be changed automatically based on the
* currently active editor.
*
* @author BREDEX GmbH
* @created Nov 8, 2006
*/
private final class ToggleLinkingAction extends Action {
/**
* Constructor
*/
public ToggleLinkingAction() {
super(Messages.TestCaseBrowserLinkWithEditor, IAction.AS_CHECK_BOX);
setImageDescriptor(LINK_IMAGE_DESC);
m_isLinkedWithEditor = Plugin.getDefault().getPreferenceStore()
.getBoolean(Constants.LINK_WITH_EDITOR_TCVIEW_KEY);
setChecked(m_isLinkedWithEditor);
}
/**
* {@inheritDoc}
*/
public void run() {
m_isLinkedWithEditor = isChecked();
Plugin.getDefault().getPreferenceStore().setValue(
Constants.LINK_WITH_EDITOR_TCVIEW_KEY,
m_isLinkedWithEditor);
if (Plugin.getActiveEditor() instanceof AbstractTestCaseEditor
&& m_isLinkedWithEditor) {
setSelectionToEditorNode(Plugin.getActiveEditor());
}
}
}
/**
* Sets the selection to the node of the current active editor if the
* linking is enabled
* @param part the current activated IWorkbenchPart
*/
private void setSelectionToEditorNode(IWorkbenchPart part) {
if (part != null) {
Object obj = part.getAdapter(AbstractTestCaseEditor.class);
AbstractTestCaseEditor tce = (AbstractTestCaseEditor)obj;
if (obj != null && m_isLinkedWithEditor && tce != null) {
final IPersistentObject editorWorkVersion =
tce.getEditorHelper().getEditSupport().getWorkVersion();
if (editorWorkVersion != null) {
UINodeBP.selectNodeInTree(editorWorkVersion.getId(),
getTreeViewer(), getEntityManager());
}
}
}
}
/**
*
*/
protected abstract void rebuildTree();
/**
* {@inheritDoc}
*/
public Object getAdapter(Class adapter) {
if (adapter.equals(AbstractJBTreeView.class)) {
return this;
} else if (adapter.equals(IPropertySheetPage.class)) {
return new JBPropertiesView(false, null);
}
return super.getAdapter(adapter);
}
/**
*
* {@inheritDoc}
*/
public final void handleProjectLoaded() {
if (GeneralStorage.getInstance().getProject() == null) {
// project-loaded fired for clearing the current project
// do not rebuild the tree
return;
}
Plugin.startLongRunning();
Plugin.getDisplay().syncExec(new Runnable() {
public void run() {
try {
rebuildTree();
} catch (OperationCanceledException oce) {
getTreeViewer().setInput(null);
}
}
});
Plugin.stopLongRunning();
}
/**
* @return tree Viewer
*/
public TreeViewer getTreeViewer() {
return m_treeViewer;
}
/**
* @return selection
*/
public ISelection getSelection() {
return m_treeViewer.getSelection();
}
/**
* @param selection selection to set
*/
public void setSelection(ISelection selection) {
m_treeViewer.setSelection(selection, true);
}
/**
* @param treeViewer The treeViewer to set.
*/
public void setTreeViewer(TreeViewer treeViewer) {
m_treeViewer = treeViewer;
}
/** {@inheritDoc} */
public void createPartControl(Composite parent) {
m_clipboard = new Clipboard(parent.getDisplay());
final FilteredTree ft = new JBFilteredTree(parent, SWT.MULTI
| SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER,
new JBBrowserPatternFilter(), true);
setTreeViewer(ft.getViewer());
setTreeFilterText(ft.getFilterControl());
addTreeListener();
getTreeViewer().setUseHashlookup(true);
getTreeViewer().setSorter(new NodeNameViewerSorter());
getTreeViewer().setComparer(new UIIdentitiyElementComparer());
getSite().setSelectionProvider(getTreeViewer());
getTreeViewer().setAutoExpandLevel(DEFAULT_EXPANSION);
final DataEventDispatcher dispatcher =
DataEventDispatcher.getInstance();
dispatcher.addProjectLoadedListener(this, false);
dispatcher.addDataChangedListener(this, true);
getViewSite().getActionBars().getToolBarManager().add(
new ToggleLinkingAction());
getViewSite().getWorkbenchWindow().getPartService().addPartListener(
m_partListener);
setFocus();
registerContextMenu();
}
/**
* Register the context menu for the receiver so that commands may be added
* to it.
*/
protected void registerContextMenu() {
MenuManager contextMenu = new MenuManager();
createContextMenu(contextMenu);
contextMenu.add(new GroupMarker(
IWorkbenchActionConstants.MB_ADDITIONS));
getSite().registerContextMenu(contextMenu, getTreeViewer());
Control control = getTreeViewer().getControl();
Menu menu = contextMenu.createContextMenu(control);
control.setMenu(menu);
}
/**
* @param contextMenu the MenuManager to create the context menu for
*/
protected abstract void createContextMenu(IMenuManager contextMenu);
/**
* Adds DoubleClickListener to Treeview.
*/
protected abstract void addTreeListener();
/**
* {@inheritDoc}
*/
public void dispose() {
try {
m_clipboard.dispose();
getViewSite().getWorkbenchWindow().getPartService()
.removePartListener(m_partListener);
final DataEventDispatcher dispatcher =
DataEventDispatcher.getInstance();
// clear corresponding views
dispatcher.firePartClosed(this);
dispatcher.removeProjectLoadedListener(this);
} finally {
getTreeViewer().getTree().dispose();
getSite().setSelectionProvider(null);
super.dispose();
}
}
/**
* @return a reference to the clipboard.
*/
public Clipboard getClipboard() {
return m_clipboard;
}
/**
* @param treeFilterText the treeFilterText to set
*/
public void setTreeFilterText(Text treeFilterText) {
m_treeFilterText = treeFilterText;
}
/**
* @return the treeFilterText
*/
public Text getTreeFilterText() {
return m_treeFilterText;
}
/**
* {@inheritDoc}
*/
public EntityManager getEntityManager() {
GeneralStorage gs = GeneralStorage.getInstance();
if (gs != null) {
return gs.getEntityManager();
}
return null;
}
}
| true
|
92c04ccb2771b51eca85c65ca891e3b9b566b460
|
Java
|
Julia9803/CuteProject
|
/CPClient/src/main/java/blservice/saleblservice/SaleUniBLService.java
|
UTF-8
| 750
| 1.867188
| 2
|
[] |
no_license
|
package blservice.saleblservice;
import java.util.List;
import VO.saleVO.SalesmanListVO;
import resultmessage.DataRM;
/**
* @author 李安迪
* @date 2017年12月24日
* @description 销售类单据统一的增删改查接口
*/
public interface SaleUniBLService {
public String getId();
public DataRM delete(String id);
// public DataRM approve(SalesmanListVO vo);
public DataRM reject(SalesmanListVO vo);
public DataRM save(SalesmanListVO vo);
public DataRM commit(SalesmanListVO vo);
public List<SalesmanListVO> openAllDraft();
public SalesmanListVO get(String id);
/**
* @param vo
* @param isWriteoff 是否为红冲单
* @return
*/
DataRM approve(SalesmanListVO vo, boolean isWriteoff);
}
| true
|
f126d1d4226a971425af748ceefdf28ab93b5ff7
|
Java
|
olbucaille/Andoid_Project_server
|
/Server_Mobility_Project/src/com/isep/mobility/project/server/Handler/RunnablerServer.java
|
ISO-8859-1
| 2,342
| 2.921875
| 3
|
[] |
no_license
|
package com.isep.mobility.project.server.Handler;
import java.net.*;
import java.io.*;
import com.isep.mobility.project.server.controller.StringProvider;
//** Classe associe chaque client **
class RunnableServer implements Runnable
{
private Thread _t; // contiendra le thread du client
private Socket _s; // recevra le socket liant au client
private PrintWriter _out; // pour gestion du flux de sortie
private BufferedReader _in; // pour gestion du flux d'entre
private server Serv; // pour utilisation des mthodes de la classe principale
private int _numClient=0; // contiendra le numro de client gr par ce thread
private BusinessServer bs;
//** Constructeur : cre les lments ncessaires au dialogue avec le client **
RunnableServer(Socket s, server server) // le param s est donne dans BlablaServ par ss.accept()
{
Serv=server; // passage de local en global (pour gestion dans les autres mthodes)
bs = new BusinessServer();
_s=s; // passage de local en global
try
{
_out =new PrintWriter(
new BufferedWriter(
new OutputStreamWriter(s.getOutputStream())),
true);
_in = new BufferedReader(new InputStreamReader(_s.getInputStream()));
}
catch (IOException e){ }
_t = new Thread(this); // instanciation du thread
_t.start(); // demarrage du thread, la fonction run() est ici lance
}
public void run()
{
try {
while (true) {
String str;
str = _in.readLine();
// lecture du message
System.out.println("ECHO = " + str); // trace locale*
//System.out.println(str.split("_")[0]);
switch (str.split("_")[0]) {
case StringProvider.REQ_GIVE_NAME:
bs.HandleGIVENAME(str, this);
break;
case StringProvider.REQ_GIVE_FULL_ACTIVITY:
bs.HandleActivity(str,this);
break;
case StringProvider.REQ_GIVE_HEARTBEAT:
bs.HandleHB(str,this);
break;
}
if (str.equals(StringProvider.END)) break;
}
_in.close();
_in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
_out.close();
}
public void BASIC_ANSWER()
{
_out.println(StringProvider.AQUITEMENT); // renvoi d'un cho
}
}
| true
|
485f66fc5136377ba1941476d3f62d05fcdef4b0
|
Java
|
lvniqi/Android_DSO
|
/multimeter/src/main/java/com/example/lvniqi/multimeter/LEDView.java
|
UTF-8
| 3,527
| 2.453125
| 2
|
[] |
no_license
|
package com.example.lvniqi.multimeter;
/**
* Created by lvniqi on 2015-05-17.
*/
import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Typeface;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.io.File;
public class LEDView extends LinearLayout {
private static final String DATE_FORMAT = "%02d:%02d:%02d";
private static final int REFRESH_DELAY = 500;
//服务程序
final private Handler mHandler = new Handler() {
};
private TextView fgView;
private TextView bgView;
public LEDView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context);
}
public LEDView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public LEDView(Context context) {
super(context);
init(context);
}
public Handler getmHandler() {
return mHandler;
}
private void init(Context context) {
LayoutInflater layoutInflater = LayoutInflater.from(context);
if (this.isInEditMode()) return;
View view = layoutInflater.inflate(R.layout.led_view, this);
fgView = (TextView) view.findViewById(R.id.ledview_fg);
bgView = (TextView) view.findViewById(R.id.ledview_bg);
AssetManager assets = context.getAssets();
final String FONT_DIGITAL_7 = "fonts" + File.separator
+ "digital-7.ttf";
final Typeface font = Typeface.createFromAsset(assets, FONT_DIGITAL_7);
fgView.setTypeface(font);// 设置字体
bgView.setTypeface(font);// 设置字体
}
public void setText(float x,int type){
String data = "";
switch (type){
case DefinedMessages.AC:
case DefinedMessages.DC:
if(x>=1000 || x<=-1000){
x /= 1000;
data = ""+x;
data += "kV";
}
else if(x<=1 && x>=-1){
x*=1000;
data = ""+(int)x;
data += "mV";
}
else{
float t = (float) (Math.round(x * 1000)) / 1000;
data = "" + t;
data += " V";
}
break;
case DefinedMessages.FREQ:
if(x>=1000 || x<=-1000){
x /= 1000;
data = ""+x;
data += "kHz";
}
else if(x<=1 && x>=-1){
x*=1000;
data = ""+(int)x;
data += "mHz";
}
else{
data = ""+(int)x;
data += " Hz";
}
break;
case DefinedMessages.UNKNOW:
data = "?????";
}
fgView.setText(data);
String back = createBgString(data);
bgView.setText(back);
}
private String createBgString(String data){
byte [] array = data.getBytes();
String back = "";
for(int i=0;i<array.length;i++){
if(array[i] <='9'&& array[i] >= '0') {
back += "8";
}
else{
back += " ";
}
}
return back;
}
}
| true
|
a73a25e2cc0ad111cdb79ce25e432542c994127d
|
Java
|
AxeemHaider/zeem-api
|
/src/main/java/org/octabyte/zeem/Queues/FollowerFeed.java
|
UTF-8
| 3,407
| 2.421875
| 2
|
[
"Apache-2.0"
] |
permissive
|
package org.octabyte.zeem.Queues;
import com.googlecode.objectify.Key;
import org.octabyte.zeem.API.Helper.UserHelper;
import org.octabyte.zeem.Datastore.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static org.octabyte.zeem.Helper.OfyService.ofy;
@SuppressWarnings("serial")
@WebServlet(name = "FollowerFeed", description = "Create Follower Feed when Post is Public",
urlPatterns = "/queue/follower_feed")
public class FollowerFeed extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// Getting value from URL
Long userId = Long.valueOf(req.getParameter("userId"));
Long postId = Long.valueOf(req.getParameter("postId"));
String postSafeKey = req.getParameter("postSafeKey");
Boolean startedByTag = Boolean.valueOf(req.getParameter("startedByTag"));
Long ownerId = null;
try {
ownerId = Long.valueOf(req.getParameter("ownerId"));
} catch (Exception e) {
e.printStackTrace();
}
// Create postKey from post safe string
Key postKey = Key.create(postSafeKey);
// Get list of followers
List<Follower> followerList = UserHelper.getFollowerList(userId);
// Get only followers ids from follower list
Long[] followerIds = followerList.stream().map(Follower::getFollowerId).toArray(Long[]::new);
// Check queue is started by tag or not if started by tag
// then remove users who are tagged with this post and also remove owner
if (startedByTag) {
// Get tagged user from this post
List<PostTag> postTags = ofy().load().type(PostTag.class).ancestor(Key.create(Post.class, postId)).list();
// Get only user ids from this object
Long[] taggedUserIds = postTags.stream().map(PostTag::getUserId).toArray(Long[]::new);
// Remove these users from follower ids
List<Long> l1 = new ArrayList<>(Arrays.asList(followerIds));
List<Long> l2 = new ArrayList<>(Arrays.asList(taggedUserIds));
l1.removeAll(l2);
// Now get the follower of owner
List<Follower> ownerFollowers = UserHelper.getFollowerList(ownerId);
// Get only follower ids from owner's follower list
Long[] ownerFollowerIds = ownerFollowers.stream().map(Follower::getFollowerId).toArray(Long[]::new);
// Convert owner follower ids into list
List<Long> ownerFollowerList = new ArrayList<>(Arrays.asList(ownerFollowerIds));
// remove also these followers from list
l1.removeAll(ownerFollowerList);
// Also remove owner from follower ids
l1.remove(ownerId);
followerIds = l1.toArray(new Long[0]);
} //
// Get list of follower and loop them
for ( Long followerId : followerIds ) {
// Save post into public feed for followers
CreateFeed.generatePublicFeed(followerId, postKey);
} // end for loop
}
}
| true
|
afb791279fadbe2e3c14e2b4bdd3f38638de9a14
|
Java
|
Runningsoftware/RunnerMeter
|
/SportsMeter/src/main/java/com/runner/sportsmeter/activities/AccountActivity.java
|
UTF-8
| 11,862
| 1.796875
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.runner.sportsmeter.activities;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.facebook.AccessToken;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.login.widget.ProfilePictureView;
import com.google.android.gms.ads.AdView;
import com.parse.ParseFacebookUtils;
import com.parse.ParseTwitterUtils;
import com.parse.ParseUser;
import com.runner.sportsmeter.R;
import com.runner.sportsmeter.common.Utility;
import com.runner.sportsmeter.models.Account;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
/**
* Created by angelr on 03-Sep-15.
*/
public class AccountActivity extends Activity {
private final HashMap accounts = new HashMap();
ProfilePictureView profilePic;
ProgressBar progressBar;
TextView name, userName, eMail, createdAt, isVerified;
Button closeBtn;
AdView mAdView;
String facebookId, twitterImageUrl, twitterImagePath;
ImageView twitterImageViewPicture;
Bitmap twitterBitmap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.l_account_layout);
// init views
progressBar = (ProgressBar) findViewById(R.id.progress_bar);
profilePic = (ProfilePictureView) findViewById(R.id.profile_picture);
name = (TextView) findViewById(R.id.edit_name);
userName = (TextView) findViewById(R.id.edit_username);
eMail = (TextView) findViewById(R.id.edit_mail);
isVerified = (TextView) findViewById(R.id.edit_is_verified);
createdAt = (TextView) findViewById(R.id.edit_date);
twitterImageViewPicture = (ImageView) findViewById(R.id.twitter_image_view);
closeBtn = (Button) findViewById(R.id.close_btn);
closeBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
// todo save account hashmap to local datastore
if (Utility.isNetworkConnected(AccountActivity.this) && ParseUser.getCurrentUser() != null) {
if (!accounts.containsKey(ParseUser.getCurrentUser().getUsername())) {
accounts.put(ParseUser.getCurrentUser().getUsername(), convertFromUserToAccount(ParseUser.getCurrentUser()));
}
Account current = (Account) accounts.get(ParseUser.getCurrentUser().getUsername());
if (ParseFacebookUtils.isLinked(ParseUser.getCurrentUser())) {
facebookId = AccessToken.getCurrentAccessToken().getUserId();
profilePic.setProfileId(facebookId);
} else if (ParseTwitterUtils.isLinked(ParseUser.getCurrentUser())) {
profilePic.setVisibility(View.INVISIBLE);
twitterImageViewPicture.setVisibility(View.VISIBLE);
}
name.setText(current.getName());
userName.setText(current.getName());
if (ParseFacebookUtils.isLinked(ParseUser.getCurrentUser())) {
facebookGraphMeRequestForUserInfo();
} else if (ParseTwitterUtils.isLinked(ParseUser.getCurrentUser())) {
eMail.setText(getString(R.string.twitter_email_not_present));
// new HttpGetTask().execute();
// try {
// twitterImagePath = getTwitterProfileImage();
// } catch (IOException e) {
// e.printStackTrace();
// } catch (JSONException e) {
// e.printStackTrace();
// }
} else {
eMail.setText(current.getEmail());
}
isVerified.setText(current.getIsVerified().toString());
createdAt.setText(current.getCreatedAt());
} else {
turnOnWiFiOrDataInternet();
}
// setup adds
mAdView = (AdView) findViewById(R.id.adViewAccount);
new Utility().setupAdds(mAdView, this);
}
private void turnOnWiFiOrDataInternet() {
if (!Utility.isNetworkConnected(AccountActivity.this)) {
new AlertDialog.Builder(AccountActivity.this)
.setTitle(getString(R.string.no_internet))
.setMessage(getString(R.string.no_net_message))
.setPositiveButton(getString(R.string.turn_on_wifi), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
WifiManager wifi = (WifiManager) AccountActivity.this.getSystemService(Context.WIFI_SERVICE);
wifi.setWifiEnabled(true);
}
})
.setNeutralButton(getString(R.string.turn_on_data), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// prompt user
// 1
// Intent dialogIntent = new Intent(android.provider.Settings.ACTION_SETTINGS);
// dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// startActivity(dialogIntent);
// 5
Intent intent = new Intent();
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction(Settings.ACTION_DATA_ROAMING_SETTINGS);
overridePendingTransition(android.R.anim.fade_in,
android.R.anim.fade_out);
startActivity(intent);
}
})
.setNegativeButton(getString(R.string.close), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).show();
}
}
private String getTwitterProfileImage() throws IOException, JSONException {
// 2
// String screenName = ParseTwitterUtils.getTwitter().getScreenName();
// String url = "https://api.twitter.com/1.1/users/show.json?screen_name="
// + screenName;
// ImageRequest request = new ImageRequest(url,
// new Response.Listener<Bitmap>() {
// @Override
// public void onResponse(Bitmap bitmap) {
// twitterImageViewPicture.setImageBitmap(bitmap);
// }
// }, 0, 0, null,
// new Response.ErrorListener() {
// public void onErrorResponse(VolleyError error) {
// }
// });
//// Access the RequestQueue through your singleton class.
// MySingleton.getInstance(this).addToRequestQueue(request);
// TwitterApiClient twitterApiClient = TwitterCore.getInstance().getApiClient();
// 1
// HttpClient client = new DefaultHttpClient();
// HttpGet verifyGetParse = new HttpGet(
// "https://api.twitter.com/1.1/users/show.json?screen_name="
// + screenName);
// ParseTwitterUtils.getTwitter().signRequest(verifyGetParse);
// HttpResponse response = (HttpResponse) client.execute(verifyGetParse);
// HttpEntity entity = new DefaultHttpClient().execute(verifyGet).getEntity();
// JSONObject responseJson = new JSONObject(IOUtils.toString(entity.getContent()));
// String url = responseJson.get("profile_image_url").toString();
return null;
}
private void facebookGraphMeRequestForUserInfo() {
GraphRequest request = GraphRequest.newMeRequest(
AccessToken.getCurrentAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
@Override
public void onCompleted(JSONObject object, GraphResponse graphResponse) {
// userName = object.getString("name");
// userId = object.getString("id");
// userGender = object.getString("gender");
// userProfileURL = object.getString("link");
// firstName = object.getString("first_name");
// lastName = object.getString("last_name");
try {
String mail = object.getString("email");
eMail.setText(mail);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "age_range,gender,name,id,link,email,picture.type(large),first_name,last_name");
request.setParameters(parameters);
request.executeAsync();
}
private Account convertFromUserToAccount(ParseUser currentUser) {
return new Account(currentUser.getUsername(),
currentUser.get("name").toString(),
currentUser.getEmail(),
(Boolean) currentUser.get("emailVerified"),
Utility.formatDate(currentUser.getCreatedAt()));
}
private class HttpGetTask extends AsyncTask<Void, Void, List<String>> {
// String screenName = ParseTwitterUtils.getTwitter().getScreenName();
// String URL = "https://api.twitter.com/1.1/users/show.json?screen_name="
// + screenName;
// AndroidHttpClient mClient = AndroidHttpClient.newInstance("");
@Override
protected void onPreExecute() {
progressBar.setVisibility(View.VISIBLE);
}
@Override
protected List<String> doInBackground(Void... params) {
// HttpGet request = new HttpGet(URL);
// ParseTwitterUtils.getTwitter().signRequest(request);
// JsonResponseHandler responseHandler = new JsonResponseHandler();
// try {
// return mClient.execute(request, responseHandler);
// } catch (ClientProtocolException e) {
// e.printStackTrace();
// } catch (IOException e) {
// e.printStackTrace();
// }
return null;
}
@Override
protected void onPostExecute(List<String> result) {
// if (null != mClient) {
// mClient.close();
// }
progressBar.setVisibility(View.GONE);
twitterImageUrl = result.get(0);
twitterImageUrl.replace("_normal", "_bigger");
// Thread netThread = new Thread(new Runnable() {
// @Override
// public void run() {
// twitterBitmap = new Utility().getBitmapFromURL(twitterImageUrl);
// twitterImagePath = Utility.saveToExternalStorage(twitterBitmap, AccountActivity.this);
// }
// });
// netThread.start();
// twitterImageViewPicture.setImageBitmap(twitterBitmap);
}
}
}
| true
|
15bba5457f9a359ee44e00508536ade0ac5135f6
|
Java
|
Shinku443/Tap1
|
/app/src/main/java/com/example/michael/tap/User.java
|
UTF-8
| 725
| 2.734375
| 3
|
[] |
no_license
|
package com.example.michael.tap;
/**
* Created by Nick Hauser on 2/9/2015.
*/
//TODO - this class is a stub used for testing; it likely needs improvement
public class User {
private String name;
private String id;
private String auth;
public User(String name) {
this.name = name;
}
public User(String name, String id){
this.name = name;
this.id = id;
}
public String getName() {
return name;
}
public String getID(){
return id;
}
public void setID(String newID){
id = newID;
}
public void setAuth(String authentication){
auth = authentication;
}
public String getAuth(){
return auth;
}
}
| true
|
327ab5ca9494d2623e25dd55b23d293e1c2ac082
|
Java
|
iljaosintsev/Apress-Calc
|
/calculator/src/main/java/com/turlir/calculator/member/Operator.java
|
UTF-8
| 657
| 2.71875
| 3
|
[
"Apache-2.0"
] |
permissive
|
package com.turlir.calculator.member;
import com.turlir.calculator.converter.Member;
import com.turlir.calculator.converter.Visual;
public abstract class Operator implements Member, Comparable<Operator> {
private final int mPriority;
private final Visual mVisual;
protected Operator(String token, int priority) {
mPriority = priority;
mVisual = new OperatorPrint(token);
}
@Override
public int compareTo(Operator o) {
return mPriority - o.mPriority;
}
@Override
public boolean operand() {
return false;
}
@Override
public Visual view() {
return mVisual;
}
}
| true
|
1fd83cc6cf3e59d4d2ac87dd150519c9c3ac05d9
|
Java
|
GekovIN/graduation
|
/src/main/java/ru/gekov/web/MenuDishController.java
|
UTF-8
| 2,993
| 2.28125
| 2
|
[] |
no_license
|
package ru.gekov.web;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.annotation.Secured;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import ru.gekov.model.MenuDish;
import ru.gekov.service.MenuDishService;
import ru.gekov.to.MenuDishTo;
import javax.validation.Valid;
import java.net.URI;
import java.time.LocalDate;
import java.util.List;
import static org.springframework.http.MediaType.*;
import static ru.gekov.util.ValidationUtil.*;
@RestController
@RequestMapping(MenuDishController.REST_URL)
public class MenuDishController {
static final String REST_URL = "/menus";
private final Logger log = LoggerFactory.getLogger(getClass());
private final MenuDishService menuService;
@Autowired
public MenuDishController(MenuDishService menuService) {
this.menuService = menuService;
}
@GetMapping(produces = APPLICATION_JSON_VALUE)
@Secured("ROLE_ADMIN")
public List<MenuDish> getAll() {
log.info("get all menuDishes");
return menuService.getAll();
}
@GetMapping(path = "/{id}", produces = APPLICATION_JSON_VALUE)
public MenuDish get(@PathVariable int id) {
log.info("get menuDish with id={}", id);
return menuService.getById(id);
}
@GetMapping(params = "date", produces = APPLICATION_JSON_VALUE)
public List<MenuDish> getByDate(@RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate date) {
log.info("get menuDishes by date {}", date);
return menuService.getAllByDate(date);
}
@DeleteMapping(path = "/{id}")
@ResponseStatus(HttpStatus.NO_CONTENT)
@Secured("ROLE_ADMIN")
public void delete(@PathVariable int id) {
log.info("delete menuDish {}", id);
menuService.delete(id);
}
@PostMapping
@Secured("ROLE_ADMIN")
public ResponseEntity<MenuDish> createWithNewUri(@Valid @RequestBody MenuDishTo menuTo) {
log.info("create {}", menuTo);
checkNew(menuTo);
MenuDish created = menuService.create(menuTo);
URI newResourceUri = ServletUriComponentsBuilder
.fromCurrentContextPath()
.path(REST_URL + "/{id}")
.buildAndExpand(created.getId())
.toUri();
return ResponseEntity.created(newResourceUri).body(created);
}
@PutMapping(value = "/{id}")
@ResponseStatus(HttpStatus.NO_CONTENT)
@Secured("ROLE_ADMIN")
public void update(@Valid @RequestBody MenuDishTo menuTo, @PathVariable Integer id) {
log.info("update {} with id={}", menuTo, id);
assureToIdConsistent(menuTo, id);
menuService.update(menuTo);
}
}
| true
|
81bcfabcad7dce345e0d4b6971234fdb12e73479
|
Java
|
Aset-U/distribution-service
|
/src/main/java/dao/mysql/MySqlCategoryDao.java
|
UTF-8
| 3,201
| 2.828125
| 3
|
[] |
no_license
|
package dao.mysql;
import dao.CategoryDao;
import dao.DaoFactory;
import dao.PersistException;
import entity.Category;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.LinkedList;
import java.util.List;
public class MySqlCategoryDao extends AbstractJDBCDao<Category, Integer> implements CategoryDao {
public MySqlCategoryDao(DaoFactory<Connection> parentFactory, Connection connection) {
super(parentFactory, connection);
}
@Override
public String getSelectQuery() {
return "SELECT id, name FROM category";
}
@Override
public String getCreateQuery() {
return "INSERT INTO category (name) \n" +
"VALUES (?);";
}
@Override
public String getUpdateQuery() {
return "UPDATE category \n" +
"SET name = ? \n" +
"WHERE id = ?;";
}
@Override
public String getDeleteQuery() {
return "DELETE FROM category WHERE id= ?;";
}
@Override
protected List<Category> parseResultSet(ResultSet rs) throws PersistException {
LinkedList<Category> result = new LinkedList<>();
try {
while (rs.next()) {
PersistCategory category = new PersistCategory();
category.setId(rs.getInt("id"));
category.setName(rs.getString("name"));
result.add(category);
}
} catch (Exception e) {
throw new PersistException(e);
}
return result;
}
@Override
protected void prepareStatementForInsert(PreparedStatement statement, Category object) throws PersistException {
try {
statement.setString(1, object.getName());
} catch (Exception e) {
throw new PersistException(e);
}
}
@Override
protected void prepareStatementForUpdate(PreparedStatement statement, Category object) throws PersistException {
try {
statement.setString(1, object.getName());
statement.setInt(2, object.getId());
} catch (Exception e) {
throw new PersistException(e);
}
}
@Override
public Category create() throws PersistException {
Category c = new Category();
return persist(c);
}
@Override
public Category getByName(String name) throws PersistException {
List<Category> list;
String sql = getSelectQuery();
sql += " WHERE name = ?";
try (PreparedStatement statement = connection.prepareStatement(sql)) {
statement.setString(1, name);
ResultSet rs = statement.executeQuery();
list = parseResultSet(rs);
} catch (Exception e) {
throw new PersistException(e);
}
if (list == null || list.size() == 0) {
return null;
}
if (list.size() > 1) {
throw new PersistException("Received more than one record.");
}
return list.iterator().next();
}
private class PersistCategory extends Category {
public void setId(int id) {
super.setId(id);
}
}
}
| true
|
64eef33ed028423892875f48b0cd985a5276d1e1
|
Java
|
sasanyi/JSlender
|
/JSlender2.0/JSlender/src/map/MapObjects.java
|
UTF-8
| 1,368
| 2.640625
| 3
|
[] |
no_license
|
package map;
import characters.Position;
import characters.Slenderman;
public class MapObjects {
public Position position = new Position(0, 0);
protected int width;
protected int height;
protected String mark;
protected boolean obstace;
protected boolean seeable;
protected boolean slenderman = false;
// public static int id = 0;
int getWidth() {
return this.width;
}
int getHeight() {
return this.height;
}
String getMark() {
return this.mark;
}
public Position getPosition() {
return this.position;
}
boolean isObstace() {
return this.obstace;
}
boolean isSeeable() {
return this.seeable;
}
public void setPosition(int x, int y) {
this.position.setX(x);
this.position.setY(y);
Map.updateMap(x, y, this);
}
public boolean updatePosition(Position oldpos, Position pos, MapObjects obj) {
if(Map.isRealPosition(pos)) {
if (obj instanceof Slenderman) {
MapObjects slendermanOn = ((Slenderman) obj).getSlendermanOn();
Map.updateMap(oldpos, slendermanOn);
((Slenderman) obj).setSlendermanOn(Map.getMapObject(pos));
} else {
Map.updateMap(oldpos, new Grass());
}
if (Map.updateMap(pos, obj)) {
return true;
} else {
Map.updateMap(oldpos, obj);
return false;
}
}else {
return false;
}
}
}
| true
|