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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
64fd5445c787974437157f6024b2fd9b41a4f9b4
|
Java
|
complitex/flexpay
|
/ab/src/org/flexpay/ab/service/impl/TownTypeServiceImpl.java
|
UTF-8
| 10,261
| 1.9375
| 2
|
[] |
no_license
|
package org.flexpay.ab.service.impl;
import org.apache.commons.lang.StringUtils;
import org.flexpay.ab.dao.TownTypeDao;
import org.flexpay.ab.persistence.TownType;
import org.flexpay.ab.persistence.TownTypeTranslation;
import org.flexpay.ab.persistence.filters.TownTypeFilter;
import org.flexpay.ab.service.TownTypeService;
import org.flexpay.common.esb.EsbSyncRequestExecutor;
import org.flexpay.common.exception.FlexPayException;
import org.flexpay.common.exception.FlexPayExceptionContainer;
import org.flexpay.common.persistence.EsbXmlSyncObject;
import org.flexpay.common.persistence.Language;
import org.flexpay.common.persistence.Stub;
import org.flexpay.common.persistence.history.ModificationListener;
import org.flexpay.common.service.internal.SessionUtils;
import org.flexpay.common.util.TranslationUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.orm.jpa.JpaTemplate;
import org.springframework.transaction.annotation.Transactional;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
import java.util.Locale;
import static org.flexpay.common.persistence.Stub.stub;
import static org.flexpay.common.util.CollectionUtils.list;
@Transactional (readOnly = true)
public class TownTypeServiceImpl implements TownTypeService {
private final Logger log = LoggerFactory.getLogger(getClass());
private TownTypeDao townTypeDao;
private EsbSyncRequestExecutor<TownType> esbSyncRequestExecutor;
private SessionUtils sessionUtils;
private ModificationListener<TownType> modificationListener;
/**
* Read TownType object by its unique id
*
* @param stub Town type stub
* @return TownType object, or <code>null</code> if object not found
*/
@Nullable
@Override
public TownType readFull(@NotNull Stub<TownType> stub) {
return townTypeDao.readFull(stub.getId());
}
/**
* Get a list of available town types
*
* @return List of TownTypes
*/
@NotNull
@Override
public List<TownType> getEntities() {
return townTypeDao.listTownTypes(TownType.STATUS_ACTIVE);
}
/**
* Disable town types
*
* @param townTypeIds IDs of town types to disable
*/
@Transactional (readOnly = false)
@Override
public void disable(@NotNull Collection<Long> townTypeIds) {
for (Long id : townTypeIds) {
if (id == null) {
log.warn("Null id in collection of town type ids for disable");
continue;
}
TownType townType = townTypeDao.read(id);
if (townType == null) {
log.warn("Can't get town type with id {} from DB", id);
continue;
}
townType.disable();
townTypeDao.update(townType);
modificationListener.onDelete(townType);
log.debug("Town type disabled: {}", townType);
}
TownType townType = new TownType();
townType.setAction(EsbXmlSyncObject.ACTION_DELETE);
townType.setIds(townTypeIds);
try {
if (esbSyncRequestExecutor != null) {
log.debug("Sending synchronizing request...");
esbSyncRequestExecutor.executeRequest(townType);
}
} catch (IOException e) {
log.error("Error with synchronizing request");
}
}
/**
* Create town type
*
* @param townType Town type to save
* @return Saved instance of town type
* @throws FlexPayExceptionContainer if validation fails
*/
@Transactional (readOnly = false)
@NotNull
@Override
public TownType create(@NotNull TownType townType) throws FlexPayExceptionContainer {
validate(townType);
townType.setId(null);
townTypeDao.create(townType);
modificationListener.onCreate(townType);
townType.setAction(EsbXmlSyncObject.ACTION_INSERT);
try {
if (esbSyncRequestExecutor != null) {
log.debug("Sending synchronizing request...");
esbSyncRequestExecutor.executeRequest(townType);
}
} catch (IOException e) {
log.error("Error with synchronizing request");
throw new FlexPayExceptionContainer(new FlexPayException("Error with synchronizing request"));
}
return townType;
}
/**
* Update or create town type
*
* @param townType Town type to save
* @return Saved instance of town type
* @throws FlexPayExceptionContainer if validation fails
*/
@SuppressWarnings ({"ThrowableInstanceNeverThrown"})
@Transactional (readOnly = false)
@NotNull
@Override
public TownType update(@NotNull TownType townType) throws FlexPayExceptionContainer {
validate(townType);
TownType oldType = readFull(stub(townType));
if (oldType == null) {
throw new FlexPayExceptionContainer(
new FlexPayException("No town type found to update " + townType));
}
sessionUtils.evict(oldType);
modificationListener.onUpdate(oldType, townType);
townTypeDao.update(townType);
townType.setAction(EsbXmlSyncObject.ACTION_UPDATE);
try {
if (esbSyncRequestExecutor != null) {
log.debug("Sending synchronizing request...");
esbSyncRequestExecutor.executeRequest(townType);
}
} catch (IOException e) {
log.error("Error with synchronizing request");
throw new FlexPayExceptionContainer(new FlexPayException("Error with synchronizing request"));
}
return townType;
}
/**
* Validate town type before save
*
* @param type TownType object to validate
* @throws FlexPayExceptionContainer if validation fails
*/
@SuppressWarnings ({"ThrowableInstanceNeverThrown"})
private void validate(@NotNull TownType type) throws FlexPayExceptionContainer {
FlexPayExceptionContainer container = new FlexPayExceptionContainer();
boolean defaultLangNameFound = false;
boolean defaultLangShortNameFound = false;
for (TownTypeTranslation translation : type.getTranslations()) {
Language lang = translation.getLang();
String name = translation.getName();
String shortName = translation.getShortName();
boolean nameNotEmpty = StringUtils.isNotEmpty(name);
boolean shortNameNotEmpty = StringUtils.isNotEmpty(shortName);
if (lang.isDefault()) {
defaultLangNameFound = nameNotEmpty;
defaultLangShortNameFound = shortNameNotEmpty;
}
if (nameNotEmpty) {
List<TownType> types = townTypeDao.findByNameAndLanguage(name, lang.getId());
if (!types.isEmpty() && !types.get(0).getId().equals(type.getId())) {
container.addException(new FlexPayException(
"Name \"" + name + "\" is already use", "ab.error.name_is_already_use", name));
}
}
if (shortNameNotEmpty) {
List<TownType> types = townTypeDao.findByShortNameAndLanguage(shortName, lang.getId());
if (!types.isEmpty() && !types.get(0).getId().equals(type.getId())) {
container.addException(new FlexPayException(
"Short name \"" + shortName + "\" is already use", "ab.error.short_name_is_already_use", shortName));
}
}
}
if (!defaultLangNameFound) {
container.addException(new FlexPayException(
"No default language translation", "ab.error.town_type.full_name_is_required"));
}
if (!defaultLangShortNameFound) {
container.addException(new FlexPayException(
"No default language translation", "ab.error.town_type.short_name_is_required"));
}
if (container.isNotEmpty()) {
throw container;
}
}
/**
* Initialize filter
*
* @param townTypeFilter filter to init
* @param locale Locale to get names in
* @return initialized filter
* @throws FlexPayException if failure occurs
*/
@NotNull
@Override
public TownTypeFilter initFilter(@Nullable TownTypeFilter townTypeFilter, @NotNull Locale locale) throws FlexPayException {
List<TownTypeTranslation> translations = getTranslations(locale);
if (translations.isEmpty()) {
throw new FlexPayException("No town types", "ab.error.town_type.no_town_types");
}
if (townTypeFilter == null) {
townTypeFilter = new TownTypeFilter();
}
townTypeFilter.setNames(translations);
if (townTypeFilter.getSelectedId() == null) {
townTypeFilter.setSelectedId(translations.get(0).getId());
}
return townTypeFilter;
}
/**
* Get TownType translations for specified locale,
* if translation is not found check for translation in default locale
*
* @param locale Locale to get translations for
* @return List of name translations for all town types
*/
@NotNull
private List<TownTypeTranslation> getTranslations(@NotNull Locale locale) {
List<TownType> townTypes = getEntities();
List<TownTypeTranslation> translations = list();
for (TownType townType : townTypes) {
TownTypeTranslation translation = TranslationUtil.getTranslation(townType.getTranslations(), locale);
if (translation == null) {
log.warn("No name for town type: {}", townType);
continue;
}
translations.add(translation);
}
return translations;
}
/**
* Get all objects
*
* @return List of all objects
*/
@Override
public List<TownType> getAll() {
return getEntities();
}
@Override
public void setJpaTemplate(JpaTemplate jpaTemplate) {
townTypeDao.setJpaTemplate(jpaTemplate);
sessionUtils.setJpaTemplate(jpaTemplate);
modificationListener.setJpaTemplate(jpaTemplate);
}
public void setEsbSyncRequestExecutor(EsbSyncRequestExecutor<TownType> esbSyncRequestExecutor) {
this.esbSyncRequestExecutor = esbSyncRequestExecutor;
}
@Required
public void setTownTypeDao(TownTypeDao townTypeDao) {
this.townTypeDao = townTypeDao;
}
@Required
public void setModificationListener(ModificationListener<TownType> modificationListener) {
this.modificationListener = modificationListener;
}
@Required
public void setSessionUtils(SessionUtils sessionUtils) {
this.sessionUtils = sessionUtils;
}
}
| true
|
3afd65d5ed9bb4ed69d4892fd4bb0399562bf82b
|
Java
|
claudemirramosferreira/ECM
|
/codigo/src/ecm-interactive/ecm-core/src/main/java/br/interactive/ecm/util/DatabaseUtil.java
|
UTF-8
| 2,801
| 2.40625
| 2
|
[] |
no_license
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2015, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package br.interactive.ecm.util;
import java.util.Map;
import javax.persistence.EntityManager;
/**
* @author josimar.alencar
*
*/
public class DatabaseUtil {
/**
* Enum dos tipos de dados
*/
public static enum DatabaseType {
TYPE_ORACLE("Oracle"), TYPE_SQL_SERVER("Microsoft SQL Server"), TYPE_POSTGRESQL("PostgreSQL");
/** Pattern. */
private final String pattern;
private DatabaseType(String pattern) {
this.pattern = pattern;
}
public String getPattern() {
return pattern;
}
}
/**
* Construtor
*/
public DatabaseUtil() {
}
/**
* Metodo que obtem as propriedades do persistence
*
* @param entityManager
* @return Map<String, Object>
*/
private static Map<String, Object> getDataBase(EntityManager entityManager) {
return entityManager.getEntityManagerFactory().getProperties();
}
/**
* Metodo para retornar o base de dados
*
* @return DatabaseType
*/
public static DatabaseType getDatabaseType(EntityManager entityManager) {
String dialect = getDataBase(entityManager).get("hibernate.dialect").toString().toLowerCase();
if (dialect.contains("sqlserver")) {
return DatabaseType.TYPE_SQL_SERVER;
} else if (dialect.contains("postgres")) {
return DatabaseType.TYPE_POSTGRESQL;
} else
return DatabaseType.TYPE_ORACLE;
}
/**
* Metodo que retorna o schema que esta sendo usado
*
* @return String
*/
public static String getDefaultSchema(EntityManager entityManager) {
return getDataBase(entityManager).get("hibernate.default_schema").toString();
}
}
| true
|
00e6d80f7e126801eca703748cd2955b2740040d
|
Java
|
MohamadHojabr/EconomyClient
|
/app/src/main/java/com/economyportal/economyportalclient/utility/ClickListener.java
|
UTF-8
| 255
| 1.898438
| 2
|
[] |
no_license
|
package com.economyportal.economyportalclient.utility;
import android.view.View;
/**
* Created by mohamad on 10/30/2016.
*/
public interface ClickListener {
void onClick(View view, int position);
void onLongClick(View view, int position);
}
| true
|
97f9efed6d0fddbcc0d27b9e038e4d472e8b25f6
|
Java
|
cdi1001/QBGTimesheet
|
/timesheet/src/main/java/timesheet/model/Employee.java
|
UTF-8
| 1,625
| 2.3125
| 2
|
[] |
no_license
|
package timesheet.model;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.OneToOne;
import javax.persistence.Table;
@Entity
@Table(name = "EMPLOYEE")
public class Employee implements Serializable {
private static final long serialVersionUID = 598803739896116673L;
@Id
@GeneratedValue
@Column(name = "EMPLOYEE_ID", unique = true, nullable = false)
private long employeeId;
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name="USER_ID")
private User user;
@ManyToOne
@JoinColumn(name="MANAGER_ID")
private Manager manager;
@ManyToMany(mappedBy="employees")
private List<Project> projects = new ArrayList<Project>();
public long getEmployeeId() {
return employeeId;
}
public void setEmployeeId(long employeeId) {
this.employeeId = employeeId;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Manager getManager() {
return manager;
}
public void setManager(Manager manager) {
this.manager = manager;
}
public List<Project> getProjects() {
return projects;
}
public void setProjects(List<Project> projects) {
this.projects = projects;
}
}
| true
|
a29f380c1cab190a99f73ea983c0092773328434
|
Java
|
SHAVIKA-GROUP/taxis
|
/taxis/src/main/java/com/shavika/taxis/service/TripService.java
|
UTF-8
| 336
| 1.882813
| 2
|
[] |
no_license
|
package com.shavika.taxis.service;
import com.shavika.taxis.api.dto.Trip;
import com.shavika.taxis.api.exception.ShavikaAppException;
public abstract interface TripService {
public abstract int insertTrip(Trip trip) throws ShavikaAppException;
public abstract int genrateMail(Trip trip) throws ShavikaAppException;
}
| true
|
8a3d61769d5c66ce4de02b6930c3b5712c3eb5fc
|
Java
|
grzegul/JavaPlayground
|
/Testing/src/test/java/io/github/grzegul/junit/helper/StringHelperTest.java
|
UTF-8
| 1,480
| 2.5
| 2
|
[] |
no_license
|
package io.github.grzegul.junit.helper;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Before;
import org.junit.Test;
public class StringHelperTest {
StringHelper s;
@Before
public void before(){
s = new StringHelper();
}
@Test
public void testTruncateAInFirst2Positions_AinFirstTwoPositions() {
assertEquals("CD", s.truncateAInFirst2Positions("AACD"));
}
@Test
public void testTruncateAInFirst2Positions_AinFirstPosition() {
assertEquals("CD", s.truncateAInFirst2Positions("ACD"));
}
@Test
public void testTruncateAInFirst2Positions_CDEF() {
assertEquals("CDEF", s.truncateAInFirst2Positions("CDEF"));
}
@Test
public void testTruncateAInFirst2Positions_CDAA() {
assertEquals("CDAA", s.truncateAInFirst2Positions("CDAA"));
}
@Test
public void testAreFirstAndLastTwoCharactersTheSame_basicNegativeScenario(){
assertFalse(s.areFirstAndLastTwoCharactersTheSame("ABCD"));
}
@Test
public void testAreFirstAndLastTwoCharactersTheSame_basicPositiveScenario(){
assertTrue(s.areFirstAndLastTwoCharactersTheSame("ABAB"));
}
@Test
public void testAreFirstAndLastTwoCharactersTheSame_AB(){
assertTrue(s.areFirstAndLastTwoCharactersTheSame("AB"));
}
@Test
public void testAreFirstAndLastTwoCharactersTheSame_A(){
assertEquals(false, s.areFirstAndLastTwoCharactersTheSame("A"));
}
}
| true
|
e0db4448e943b5c588d8a4657694119674a3796d
|
Java
|
Oaks907/bookspace
|
/LeetCode/src/S101_200/S108_ConvertSortedArraytoBinarySearchTree.java
|
UTF-8
| 629
| 3.234375
| 3
|
[] |
no_license
|
package S101_200;
import model.TreeNode;
/**
* Create by haifei on 26/3/2019 5:46 PM.
* <p>
* https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/
*/
public class S108_ConvertSortedArraytoBinarySearchTree {
public TreeNode sortedArrayToBST(int[] nums) {
return helper(nums, 0, nums.length - 1);
}
public TreeNode helper(int[] nums, int low, int high) {
if (low > high) {
return null;
}
int mid = (low + high) >> 1;
TreeNode tmp = new TreeNode(nums[mid]);
tmp.left = helper(nums, low, mid - 1);
tmp.right = helper(nums, mid + 1, high);
return tmp;
}
}
| true
|
149c3382ebceecd3622e9797f8a16731786efa4f
|
Java
|
xujianhai/mycat-netty
|
/src/main/java/io/mycat/netty/mysql/auth/PrivilegeFactory.java
|
UTF-8
| 1,346
| 2.28125
| 2
|
[
"Apache-2.0"
] |
permissive
|
package io.mycat.netty.mysql.auth;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
/**
* Created by snow_young on 16/8/7.
*/
public class PrivilegeFactory {
private static final Logger logger = LoggerFactory.getLogger(PrivilegeFactory.class);
// todo: refactor privilege, prop privilege is diffrent
private static volatile Privilege privilege;
public static final Privilege TRUE_PRIVILEGE = new Privilege(){
public boolean userExists(String user) {
return true;
}
public boolean schemaExists(String user, String schema) {
return true;
}
public String password(String user) {
return null;
}
public boolean checkPassword(String user, byte[] password, String salt) {
return true;
}
public List<String> getSchemas(String user) { return null; }
};
public static void loadPrivilege(String file){
// seek config file
XmlPrivilege xmlPrivilege = new XmlPrivilege();
try {
xmlPrivilege.load();
} catch (Exception e) {
logger.info("load file[{}] with xml occurs error", file, e);
}
privilege = xmlPrivilege;
}
public static Privilege getPrivilege(){
return privilege;
}
}
| true
|
951fbcdb614ac58f80d2c55d5bb0124ff286a758
|
Java
|
vostreshtw/krankenhaus
|
/Vostres_s0566769_Aufgabe8/src/de/htw/krankenhaus/modell/Aufenthalt.java
|
UTF-8
| 3,009
| 2.890625
| 3
|
[] |
no_license
|
package de.htw.krankenhaus.modell;
/**
* Klasse fuer Aufenthalte
*
* @author Yevheniia Vostres (566769)
* @since 16.04.2019
*
*/
import java.util.Date;
import java.util.LinkedList;
public class Aufenthalt {
private String patientenName;
private int patientenNummer;
private long dauer;
private Date aufnahmeDatum;
private Date entlassungsDatum;
/**
* @return the aufnahmeDatum
*/
public Date getAufnahmeDatum() {
return aufnahmeDatum;
}
/**
* @param aufnahmeDatum
* the aufnahmeDatum to set
*/
public void setAufnahmeDatum(Date aufnahmeDatum) {
this.aufnahmeDatum = aufnahmeDatum;
}
/**
* @return the entlassungsDatum
*/
public Date getEntlassungsDatum() {
return entlassungsDatum;
}
/**
* @param entlassungsDatum
* the entlassungsDatum to set
*/
public void setEntlassungsDatum(Date entlassungsDatum) {
this.entlassungsDatum = entlassungsDatum;
}
/**
* @return the patientenName
*/
public String getPatientenName() {
return patientenName;
}
/**
* @param patientenName
* the patientenName to set
*/
public void setPatientenName(String patientenName) {
this.patientenName = patientenName;
}
/**
* @return the patientenNummer
*/
public int getPatientenNummer() {
return patientenNummer;
}
/**
* @param patientenNummer
* the patientenNummer to set
*/
public void setPatientenNummer(int patientenNummer) {
this.patientenNummer = patientenNummer;
}
/**
* @return the dauer
*/
public long getDauer() {
return dauer;
}
/**
* @param dauer
* the dauer to set
*/
public void setDauer(long dauer) {
this.dauer = dauer;
}
/**
* @param patientenName
* @param patientenNummer
* @param dauer
* @param aufnahmeDatum
* @param entlassungsDatum
*/
public Aufenthalt(String patientenName, int patientenNummer, long dauer, Date aufnahmeDatum,
Date entlassungsDatum) {
super();
this.patientenName = patientenName;
this.patientenNummer = patientenNummer;
this.dauer = dauer;
this.aufnahmeDatum = aufnahmeDatum;
this.entlassungsDatum = entlassungsDatum;
}
// 2. Konstruktor fuer aktuelle Aufenthalte
/**
* @param patientenName
* @param patientenNummer
* @param dauer
* @param aufnahmeDatum
*/
public Aufenthalt(String patientenName, int patientenNummer, Date aufnahmeDatum) {
super();
this.patientenName = patientenName;
this.patientenNummer = patientenNummer;
this.aufnahmeDatum = aufnahmeDatum;
this.entlassungsDatum = entlassungsDatum;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "Aufenthalt [patientenName=" + patientenName + ", patientenNummer=" + patientenNummer + ", dauer="
+ dauer + ", aufnahmeDatum=" + aufnahmeDatum + ", entlassungsDatum=" + entlassungsDatum + "]";
}
}
| true
|
0784d678dd73aa3af8b0c7e62b2a96a7140013f5
|
Java
|
moutainhigh/easysaas-project
|
/easysaas-portal/src/main/java/org/easymis/easysaas/portal/service/DictionaryService.java
|
UTF-8
| 497
| 1.546875
| 2
|
[] |
no_license
|
package org.easymis.easysaas.portal.service;
import java.util.List;
public interface DictionaryService {
List getEstiblishYearType();
List getRegisteredCapitalType();
//企业状态列表
public List getCompanyStatusList();
//资本币种列表
public List getMoneyList();
//企业类型列表
public List getCompanyTypeList();
//参保人数范围列表
public List getSocialSecurityList();
public List getSortList();
public String getSortDepict(String key);
}
| true
|
94b92f63372e244278020373775c05979b07cc73
|
Java
|
ninjaframework/ninja-appengine
|
/ninja-appengine-module/src/main/java/ninja/appengine/AppEngineEnvironmentInterceptor.java
|
UTF-8
| 1,515
| 1.835938
| 2
|
[
"Apache-2.0"
] |
permissive
|
/**
* Copyright (C) 2012-2018-2014 the original author or authors.
*
* 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 ninja.appengine;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.persist.PersistService;
import com.google.inject.persist.UnitOfWork;
import javax.persistence.EntityManager;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
public class AppEngineEnvironmentInterceptor implements MethodInterceptor {
final Provider<NinjaAppengineEnvironment> ninjaAppengineEnvironment;
@Inject
public AppEngineEnvironmentInterceptor(
Provider<NinjaAppengineEnvironment> ninjaAppengineEnvironment) {
this.ninjaAppengineEnvironment = ninjaAppengineEnvironment;
}
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
ninjaAppengineEnvironment.get().initOrSkip();
return invocation.proceed();
}
}
| true
|
47cb9f99c1b2db4a470af834536ade24a7ac503f
|
Java
|
flyingonion93/SDI_ws
|
/PR02_prj-rmi_Clients/src/client/ComputeTestClient.java
|
UTF-8
| 1,743
| 2.78125
| 3
|
[] |
no_license
|
package client;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.Serializable;
import java.rmi.Naming;
import java.rmi.RemoteException;
import interfaces.compute.ComputeServerInt;
import interfaces.compute.TaskInt;
import interfaces.echo.EchoInt;
public class ComputeTestClient implements Serializable
{
/**
*
*/
private static final long serialVersionUID = 1L;
public TaskInt echoTask = new TaskEcho();
public static void vmain( String[] args )
{
String server_name = new String();
if( args.length == 1 )
server_name = "//" + args[0] + "/miComputeServer";
else
server_name = "//localhost/miComputeServer";
ComputeTestClient computeClient = new ComputeTestClient();
if( System.getSecurityManager() == null )
System.setSecurityManager( new SecurityManager() );
BufferedReader stdIn = new BufferedReader( new InputStreamReader( System.in ) );
PrintWriter stdOut = new PrintWriter( System.out );
String input, output;
try
{
//EJERCICIO: "lookup" the Compute server RMI object
ComputeServerInt cs = (ComputeServerInt) Naming.lookup( server_name );
//EJERCICIO: load the task (computeClient.echoTask) to the computeServer
int taskid = cs.loadTask( computeClient.echoTask );
stdOut.println("> ");
stdOut.flush();
while( ( input = stdIn.readLine() ) != null )
{
//EJERCICIO: execute the loaded task. Get the response in "output"
output = (String) cs.executeTask( taskid, input );
stdOut.println( output );
stdOut.print( "> " );
stdOut.flush();
}
}catch( Exception e )
{
System.err.println( "Error en el cliente de echo RMI: " + e.getMessage() );
e.printStackTrace();
}
}
}
| true
|
8b37b61ecbaca8bb3c9a2dc007705a956bcc8edd
|
Java
|
GmwEnterprise/Learn
|
/VueCrudDemo/vue-demo-crud/src/main/java/com/example/vuedemocrud/po/People.java
|
UTF-8
| 993
| 2.640625
| 3
|
[] |
no_license
|
package com.example.vuedemocrud.po;
public class People {
public static final byte SEX_MAN = 1;
public static final byte SEX_WOMAN = 2;
private Integer id;
private String name;
private Byte sex;
private String role;
@Override
public String toString() {
return "People {" +
"id=" + id +
", name='" + name + '\'' +
", sex=" + sex +
", role='" + role + '\'' +
'}';
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Byte getSex() {
return sex;
}
public void setSex(Byte sex) {
this.sex = sex;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
}
| true
|
42ae31317548153f3e783c36cca267c0ba9c6911
|
Java
|
lw-bthub/api-demo
|
/demo/java/src/main/java/com/bthub/apidemo/dto/WsMessage.java
|
UTF-8
| 422
| 2.390625
| 2
|
[] |
no_license
|
package com.bthub.apidemo.dto;
public class WsMessage<T> {
private String event;
private T data;
@Override
public String toString() {
return String.format("Message [event=%s, data=%s]", event, data);
}
public String getEvent() {
return event;
}
public void setEvent(String event) {
this.event = event;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
}
| true
|
0fe9961266041a9725f4828713276ffa1837309d
|
Java
|
colorshifter/caaers
|
/caAERS/software/core/src/main/java/gov/nih/nci/cabig/caaers/domain/LabLoad.java
|
UTF-8
| 4,498
| 2.140625
| 2
|
[
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
/*******************************************************************************
* Copyright SemanticBits, Northwestern University and Akaza Research
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/caaers/LICENSE.txt for details.
******************************************************************************/
package gov.nih.nci.cabig.caaers.domain;
import gov.nih.nci.cabig.ctms.domain.AbstractMutableDomainObject;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.Transient;
import org.apache.commons.lang.StringUtils;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;
/**
* This class represents the LabLoad domain object associated with the Adverse event report.
*
* @author Srini Akkala
*/
@Entity
@Table(name = "labs")
@GenericGenerator(name = "id-generator", strategy = "native", parameters = { @Parameter(name = "sequence", value = "seq_labs_id") })
public class LabLoad extends AbstractMutableDomainObject {
/** The name. */
private String name;
/** The units. */
private String units;
/** The result. */
private String result;
/** The dismissed. */
private boolean dismissed;
/** The lab date. */
private Date labDate;
/** The assignment. */
private StudyParticipantAssignment assignment;
// //// BEAN PROPERTIES
/**
* Gets the units.
*
* @return the units
*/
public String getUnits() {
return units;
}
/**
* Sets the units.
*
* @param units the new units
*/
public void setUnits(String units) {
this.units = units;
}
/**
* Gets the lab date.
*
* @return the lab date
*/
public Date getLabDate() {
return labDate;
}
/**
* Sets the lab date.
*
* @param labDate the new lab date
*/
public void setLabDate(Date labDate) {
this.labDate = labDate;
}
/**
* Checks if is dismissed.
*
* @return true, if is dismissed
*/
public boolean isDismissed() {
return dismissed;
}
/**
* Sets the dismissed.
*
* @param dismissed the new dismissed
*/
public void setDismissed(boolean dismissed) {
this.dismissed = dismissed;
}
/**
* Gets the result.
*
* @return the result
*/
public String getResult() {
return result;
}
/**
* Sets the result.
*
* @param result the new result
*/
public void setResult(String result) {
this.result = result;
}
/**
* Sets the name.
*
* @param name the new name
*/
public void setName(String name) {
this.name = name;
}
/**
* Gets the name.
*
* @return the name
*/
public String getName() {
return name;
}
/**
* Gets the participant.
*
* @return the participant
*/
@Transient
public Participant getParticipant() {
return getAssignment() == null ? null : getAssignment().getParticipant();
}
/**
* Gets the study.
*
* @return the study
*/
@Transient
public Study getStudy() {
StudySite ss = getAssignment() == null ? null : getAssignment().getStudySite();
return ss == null ? null : ss.getStudy();
}
/**
* Gets the assignment.
*
* @return the assignment
*/
@ManyToOne(fetch = FetchType.LAZY)
public StudyParticipantAssignment getAssignment() {
return assignment;
}
/**
* Sets the assignment.
*
* @param assignment the new assignment
*/
public void setAssignment(StudyParticipantAssignment assignment) {
this.assignment = assignment;
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return ("" + getName() ).hashCode();
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (obj == this) return true;
if (obj == null) return false;
if (!(obj instanceof Lab)) return false;
LabLoad l = (LabLoad) obj;
if (!StringUtils.equals(name, l.name)) return false;
if (l.units != null && !units.equals(l.units)) return false;
if (l.result != null && !result.equals(l.result)) return false;
return true;
}
}
| true
|
7d4742cf35599602e6c6366caef3d3da1c54c1b7
|
Java
|
yogabraman/Simacol
|
/app/src/main/java/com/smart/simacol/Adapters/BookingAllAdapter.java
|
UTF-8
| 2,070
| 2.203125
| 2
|
[] |
no_license
|
package com.smart.simacol.Adapters;
import android.support.annotation.NonNull;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.smart.simacol.R;
import com.smart.simacol.models.BookingAll;
public class BookingAllAdapter extends FirebaseRecyclerAdapter<BookingAll, BookingAllAdapter.BookingAllHolder> {
public BookingAllAdapter(@NonNull FirebaseRecyclerOptions<BookingAll> options) {
super(options);
}
@Override
protected void onBindViewHolder(@NonNull final BookingAllHolder holder, int position, @NonNull final BookingAll model) {
holder.text_subjek.setText(model.getSubjek());
holder.text_tgl.setText(model.getTanggal());
holder.text_start.setText(model.getStart());
holder.text_end.setText(model.getEnd());
holder.text_user.setText(model.getUser());
}
@NonNull
@Override
public BookingAllHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_booking_all, parent, false);
return new BookingAllAdapter.BookingAllHolder(view);
}
class BookingAllHolder extends RecyclerView.ViewHolder{
TextView text_subjek, text_tgl, text_start, text_end, text_user;
CardView cardBookingAll;
public BookingAllHolder(View itemView) {
super(itemView);
text_subjek = itemView.findViewById(R.id.text_subjek);
text_tgl = itemView.findViewById(R.id.text_tgl);
text_start = itemView.findViewById(R.id.text_start);
text_end = itemView.findViewById(R.id.text_end);
text_user = itemView.findViewById(R.id.text_user);
cardBookingAll = itemView.findViewById(R.id.cardBookingAll);
}
}
}
| true
|
aa368749a4b289a12b42b13f30ff3800f6719924
|
Java
|
Akankshaanshu/CalculatorMaven
|
/src/main/java/com/devops/traing/jenkins/JenkinsCalculator.java
|
UTF-8
| 234
| 2.453125
| 2
|
[] |
no_license
|
package com.devops.traing.jenkins;
public class JenkinsCalculator {
public int addnumbers(int number1, int number2) {
return number1+number2;
}
public int subnumbers(int number1, int number2) {
return number1-number2;
}
}
| true
|
0fed8cc1d3c7c9048671d4938fb4df52fde9ac97
|
Java
|
sunweifengfeng/community
|
/src/main/java/life/kobefengfeng/community/community/exception/ICustomizeErrorCode.java
|
UTF-8
| 246
| 1.8125
| 2
|
[] |
no_license
|
package life.kobefengfeng.community.community.exception;
/**
* @Author KobeFL
* @Description TODO
* @Date 2021/6/14 17:41
* @Version 1.0
*/
public interface ICustomizeErrorCode {
String getMessage() ;
Integer getCode();
}
| true
|
38a0c0442efc154ecb2e71e3711072e4fa72e239
|
Java
|
VonGriff/ADK
|
/Labb1/Konkordans.java
|
UTF-8
| 1,665
| 2.96875
| 3
|
[] |
no_license
|
import java.util.LinkedList;
import java.io.RandomAccessFile;
import java.io.IOException;
import java.io.FileNotFoundException;
public class Konkordans {
private static RandomAccessFile file;
private static Path
public Konkordans() {
int i;
}
public static void main(String[] args) throws IOException, FileNotFoundException {
file = new RandomAccessFile("korpus","r");
// word.getBytes("ISO-8859-1")
file.seek(50);
byte[] b = new byte[10];
String s;
for (long i = 0; i < 10; i++) {
b[i] = file.readByte();
}
s = new String(b, "ISO-8859-1");
System.out.println(s);
}
// Fetc the index of where the word with starting chars "xxx" exist
private static int getWordIndex(String s) {
char[] c = s.toCharArray();
int size = c.length;
int index = 0; // Will never exist anything on index 0
if (size < 3) {
int multiplier = 900;
for (int i = 0; i < size; i++) {
index += c[i]*multiplier;
multiplier = multiplier/30;
}
}
else {
index = c[0]*900 + c[1]*30 + c[2];
}
return index;
}
// Fetch all indeces of where in the text word X exist
private static LinkedList<Long> getWordLocation(int index, String word) {
return null;
}
// Will print all words on every position where occurring along with
// 30 chars before and after
// Paramaters pos are the positions of every word, len is the length of the word
private static void printWord(LinkedList<Long> pos,int len) throws IOException {
// new String(b, "ISO-8859-1")
int i;
byte[] sentence = new byte[60+len];
for (long l: pos) {
if (l < 30) {
file.seek(0);
//file.read(
}
}
}
}
| true
|
81ed4645be9e5e0268a2ae0c853bbbae74a8af94
|
Java
|
wirdakurnia/Deteksi-Hangeul
|
/app/src/main/java/com/wirnin/hanguldetection/Fragment/FragmentKalimat.java
|
UTF-8
| 6,086
| 1.890625
| 2
|
[] |
no_license
|
package com.wirnin.hanguldetection.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import com.wirnin.hanguldetection.Activity.MenuUtama;
import com.wirnin.hanguldetection.Kalimat;
import com.wirnin.hanguldetection.ViewHolder.KalimatViewHolder;
import com.wirnin.hanguldetection.R;
import androidx.annotation.NonNull;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
/**
* A simple {@link Fragment} subclass.
*/
public class FragmentKalimat extends Fragment {
public static String TAG = "FragmentKalimat";
public static String KEY_FRG = "msg_fragment";
// [START define_database_reference]
private DatabaseReference mDatabase;
// [END define_database_reference]
private FirebaseRecyclerAdapter<Kalimat, KalimatViewHolder> mAdapter;
private RecyclerView mRecycler;
private LinearLayoutManager mManager;
String vokalkey, jenisLatihan;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootview = inflater.inflate(R.layout.fragment_kalimat, container, false);
final Toolbar toolbar = rootview.findViewById(R.id.toolbar);
toolbar.setTitle("Percakapan Dasar");
toolbar.setNavigationIcon(R.drawable.homekecil);
toolbar.setNavigationOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent backhome = new Intent(getActivity(), MenuUtama.class);
startActivity(backhome);
}
}
);
mDatabase = FirebaseDatabase.getInstance().getReference();
mRecycler = rootview.findViewById(R.id.list_kalimat);
mRecycler.setHasFixedSize(true);
mManager = new LinearLayoutManager(getContext());
mManager.setReverseLayout(true);
mManager.setStackFromEnd(true);
mRecycler.setLayoutManager(new GridLayoutManager(getContext(), 1));
// Set up FirebaseRecyclerAdapter with the Query
Query query = getQuery(mDatabase);
FirebaseRecyclerOptions options = new FirebaseRecyclerOptions.Builder<Kalimat>()
.setQuery(query, Kalimat.class)
.build();
mAdapter = new FirebaseRecyclerAdapter<Kalimat, KalimatViewHolder>(options) {
@Override
public KalimatViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
return new KalimatViewHolder(inflater.inflate(R.layout.item_kalimat, parent, false));
}
@Override
protected void onBindViewHolder(@NonNull KalimatViewHolder holder, final int i, @NonNull final Kalimat kalimat) {
holder.bindToKalimat(kalimat, new View.OnClickListener() {
@Override
public void onClick(View view) {
mDatabase.child("kalimat")
.orderByChild("arti")
.equalTo(kalimat.arti)
.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
vokalkey = childSnapshot.getKey();
}
assert vokalkey != null;
Log.i(TAG, kalimat.id);
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
Bundle data = new Bundle();
String msg = kalimat.id;
data.putString(FragmentKalimat.KEY_FRG, msg);
FragmentSoundKalimat soundKalimat = new FragmentSoundKalimat();
FragmentManager FM = getActivity().getSupportFragmentManager();
soundKalimat.setArguments(data);
FragmentTransaction FT = FM.beginTransaction();
FT.replace(R.id.isi_kalimat, soundKalimat);
FT.commit();
}
});
}
};
mAdapter.notifyDataSetChanged();
mRecycler.setAdapter(mAdapter);
return rootview;
}
@Override
public void onStart() {
super.onStart();
if (mAdapter != null) {
mAdapter.startListening();
}
}
@Override
public void onStop() {
super.onStop();
if (mAdapter != null) {
mAdapter.stopListening();
}
}
private Query getQuery(DatabaseReference mDatabase){
Query query = mDatabase.child("kalimat");
return query;
}
}
| true
|
1847f9f485b4039fafb17e40d06430f8f558b771
|
Java
|
xabe/EJB_REMOTE_JBOSS
|
/ejb/src/main/java/es/xabe/arquitectura/ejb/RegistroEJBImpl.java
|
UTF-8
| 830
| 2.109375
| 2
|
[] |
no_license
|
package es.xabe.arquitectura.ejb;
import java.util.List;
import javax.ejb.Remote;
import javax.ejb.Stateless;
import javax.interceptor.Interceptors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ejb.interceptor.SpringBeanAutowiringInterceptor;
import es.xabe.arquitectura.model.Acta;
import es.xabe.arquitectura.service.RegistroService;
@Stateless(mappedName = "registroEJB")
@Remote(RegistroEJB.class)
@Interceptors(SpringBeanAutowiringInterceptor.class)
public class RegistroEJBImpl implements RegistroEJB {
@Autowired
private RegistroService registroService;
@Override
public Acta getestado(String value) {
Acta acta = new Acta();
acta.setNombre(value);
return acta;
}
@Override
public List<Acta> getestados() {
return registroService.getActas();
}
}
| true
|
f71ecaeef0ca2eb7cdc2a55c49205134aeaae62e
|
Java
|
newtutorials/Jackson-Examples
|
/src/main/java/org/newtutorials/jackson/standard/JacksonSimpleExample.java
|
UTF-8
| 2,271
| 3.09375
| 3
|
[] |
no_license
|
package org.newtutorials.jackson.standard;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.newtutorials.jackson.standard.model.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* Created by dani on 5/20/2017.
*/
public class JacksonSimpleExample {
public static void main(String[] args) {
final ObjectMapper objectMapper = new ObjectMapper();
Order order = createOrder();
try {
String orderAsString = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(order);
System.out.println(orderAsString);
Order orderFromJson = objectMapper.readValue(orderAsString, Order.class);
System.out.println(orderFromJson);
} catch (JsonProcessingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private static Order createOrder() {
Customer customer = new CustomerBuilder()
.setId(1l)
.setName("First Customer")
.createCustomer();
Product product = new ProductBuilder()
.setId(1l)
.setName("Product One")
.setPrice(1.5d)
.createProduct();
Product productTwo = new ProductBuilder()
.setId(1l)
.setName("Product Two")
.setPrice(5d)
.createProduct();
List<OrderedProduct> orderedProducts = new ArrayList<>();
orderedProducts.add(
new OrderedProductBuilder()
.setId(1l)
.setProduct(product)
.setQuantity(1)
.createOrderedProduct());
orderedProducts.add(
new OrderedProductBuilder()
.setId(2l)
.setProduct(productTwo)
.setQuantity(5)
.createOrderedProduct());
return new OrderBuilder()
.setId(1l)
.setCustomer(customer)
.setOrderedProducts(orderedProducts)
.createOrder();
}
}
| true
|
cb6159de20d4f994797d76e74f1b1c43cb2cbfc7
|
Java
|
tracyly/WYCDemo
|
/app/src/main/java/com/weishop/test/mvp/MvpTestActivity.java
|
UTF-8
| 2,354
| 2.03125
| 2
|
[] |
no_license
|
package com.weishop.test.mvp;
import android.os.Bundle;
import android.view.View;
import android.widget.AbsListView;
import android.widget.ListView;
import com.weishop.test.R;
import com.weishop.test.list.ListData;
import com.weishop.test.list.draglistview.ListViewAdapter;
import com.weishop.test.mvp.base.BaseMvpActivity;
import java.util.List;
public class MvpTestActivity extends BaseMvpActivity<TestContract.Presenter> implements View.OnClickListener,
AbsListView.OnScrollListener, TestContract.View {
private ListView mListView;
private ListViewAdapter mAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_listview);
mListView = (ListView) findViewById(R.id.listview);
mAdapter = new ListViewAdapter(this);
mListView.setAdapter(mAdapter);
mListView.setOnScrollListener(new AbsListView.OnScrollListener() {
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
System.out.println("onScrollStateChanged scrollState=" + scrollState);
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
int totalItemCount) {
System.out.println("onScroll firstVisibleItem=" + firstVisibleItem +
",visibleItemCount=" + visibleItemCount + ",totalItemCount=" + totalItemCount);
}
});
findViewById(R.id.start).setOnClickListener(this);
mPresenter.initData();
}
@Override
protected TestContract.Presenter createPresenter() {
return new TestPresenter();
}
@Override
public void onClick(View v) {
}
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
int totalItemCount) {
}
@Override
public void showLoading() {
}
@Override
public void hideLoading() {
}
@Override
public void showData(List<ListData> data) {
mAdapter.setData(data);
mAdapter.notifyDataSetChanged();
}
}
| true
|
a033c61891babbfea32d5e6937524ee935305502
|
Java
|
format686/L2jOrg
|
/Gameserver/src/main/org.l2j.gameserver/org/l2j/gameserver/network/clientpackets/RequestRecipeShopManageList.java
|
UTF-8
| 1,198
| 2.265625
| 2
|
[] |
no_license
|
package org.l2j.gameserver.network.clientpackets;
import org.l2j.gameserver.enums.PrivateStoreType;
import org.l2j.gameserver.model.actor.instance.L2PcInstance;
import org.l2j.gameserver.network.serverpackets.ActionFailed;
import org.l2j.gameserver.network.serverpackets.RecipeShopManageList;
import java.nio.ByteBuffer;
public final class RequestRecipeShopManageList extends IClientIncomingPacket {
@Override
public void readImpl(ByteBuffer packet) {
}
@Override
public void runImpl() {
final L2PcInstance player = client.getActiveChar();
if (player == null) {
return;
}
// Player shouldn't be able to set stores if he/she is alike dead (dead or fake death)
if (player.isAlikeDead()) {
client.sendPacket(ActionFailed.STATIC_PACKET);
return;
}
if (player.getPrivateStoreType() != PrivateStoreType.NONE) {
player.setPrivateStoreType(PrivateStoreType.NONE);
player.broadcastUserInfo();
if (player.isSitting()) {
player.standUp();
}
}
client.sendPacket(new RecipeShopManageList(player, true));
}
}
| true
|
4f34bd7df9309982e4237e334312efc36ee8fa5e
|
Java
|
Ravibhushan222/Java
|
/Week4/src/Exception_handl/finally_.java
|
UTF-8
| 492
| 3.03125
| 3
|
[] |
no_license
|
package Exception_handl;
public class finally_ {
public static void main(String [] args){
int i = 5;
int j = 0;
// int k =i/j;
try {
int m=i/j;
}
catch(ArithmeticException e) {
System.out.println("can't divide zero");
System.out.println(e);
}
finally {
System.out.println("always get excecuted no matter exception or not");
}
}
}
| true
|
71cab37bb2fa7989c79c11fedace26487b289f4d
|
Java
|
shubham9415/ProgramsJava
|
/DoubleCheck.java
|
UTF-8
| 365
| 3.015625
| 3
|
[] |
no_license
|
package com.practice;
public class DoubleCheck {
public static void main(String[] args) {
/* Object d = new Double(123);
String s = (String)d;
System.out.println(s);*/
DoubleCheck check = new DoubleCheck();
check.printThis();
}
public void printThis(){
System.out.println(this);
}
}
| true
|
e504c0a7df1b1dd980ddcc41d7adccdbfb162769
|
Java
|
vaarcilal/ST0245-032
|
/laboratorios/lab03/codigo/MainSearchBySubject.java
|
UTF-8
| 2,277
| 4.03125
| 4
|
[] |
no_license
|
import java.util.*;
import java.io.*;
/**
* This class contains the methods necessary to read doto from a .txt document, transform it into Student objects, add tem to an ArrayList data structure and search said
* data tructure by semester and subject.
*
* @author Isabel Piedrahita
* @version 24/03/2019
*/
public class MainSearchBySubject
{
public String file;
public String semester;
public ArrayList<Student> records = new ArrayList<Student> ();
public MainSearchBySubject(String subjectCode, String semester) {//Complexity O(1)
this.file = "./" + subjectCode.toUpperCase() + ".txt";
this.semester = semester;
}
public void readFile(String fileName, String skipLine) throws IOException {//Complexity O(n)
FileReader reader = new FileReader(fileName);
BufferedReader b = new BufferedReader(reader);
String line = "";
while((line = b.readLine()) != null){
if(! line.equals(skipLine)){
Student s = parseLine(line, ",");
records.add(s);
}
}
b.close();
}
public Student parseLine(String line, String separator) {//Complexity O(1)
String[] info = line.split(separator);
Student s = new Student(info[1], info[3], info[12]);
return s;
}
public void searchBySemester(String semester) {//Complexity O(n)
for(Student student: records) {
if(student.getSemester().equals(semester)){
student.print();
}
}
}
public static void main() throws IOException {//Complexity O(n) + O(n) + O(1) + O(n)
Scanner s = new Scanner(System.in);
System.out.print("Ingrese el código de la materia en formato {ST} + {Codigo}: ");
String subjectCode = s.nextLine();
System.out.print("Ingrese el semestre en formato {Año} + {Semestre}: ");
String semester = s.nextLine();
MainSearchBySubject m = new MainSearchBySubject(subjectCode, semester);
m.readFile(m.file, "");
System.out.println("Los registros que coinciden con la busqueda son:");
m.searchBySemester(m.semester);
}
}
| true
|
9b34ffe6ca8faf269c6fada8ec067c1af086965f
|
Java
|
hassanlatif/sqm-api
|
/src/com/stc/sqm/hajj/DatabaseAccess.java
|
UTF-8
| 10,974
| 2.625
| 3
|
[] |
no_license
|
package com.stc.sqm.hajj;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.HashMap;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
public class DatabaseAccess {
public ArrayList<ToDo> getToDoListByCreator(String creatorUid) {
ArrayList<ToDo> toDoList = null;
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
System.out.println("getToDoListByCreator(...) --> Creator ID = " + creatorUid);
try {
conn = getDBConnection();
stmt = conn.createStatement();
rs = stmt.executeQuery(
"SELECT TASK_ID, CREATOR_UID, CREATOR_EMAIL, CREATOR_MOBILE, " + "ASSIGNED_UID, ASSIGNED_SHIFT, TASK_DESC,"
+ " STATUS, NOTIFY_ID, CREATE_DATE, TARGET_DATE, PRIORITY, "
+ "ASSIGNED_EMAIL, ASSIGNED_MOBILE FROM HAJJ_TODO_LIST "
+ "WHERE CREATOR_UID LIKE '" + creatorUid + "'");
toDoList = new ArrayList<ToDo>();
while (rs.next()) {
ToDo toDo = new ToDo();
toDo.setTaskId(rs.getInt("TASK_ID"));
toDo.setCreatorUid(rs.getString("CREATOR_UID"));
toDo.setCreatorEmail(rs.getString("CREATOR_EMAIL"));
toDo.setCreatorMobile(rs.getString("CREATOR_MOBILE"));
toDo.setAssignedUid(rs.getString("ASSIGNED_UID"));
toDo.setAssignedShift(rs.getString("ASSIGNED_SHIFT"));
toDo.setAssignedEmail(rs.getString("ASSIGNED_EMAIL"));
toDo.setAssignedMobile(rs.getString("ASSIGNED_MOBILE"));
toDo.setTaskDesc(rs.getString("TASK_DESC"));
toDo.setStatus(rs.getString("STATUS"));
toDo.setCreateDate(rs.getString("CREATE_DATE"));
toDo.setTargetDate(rs.getString("TARGET_DATE"));
toDo.setPriority(rs.getInt("PRIORITY"));
toDoList.add(toDo);
}
rs.close();
rs = null;
stmt.close();
stmt = null;
conn.close(); // Return to connection pool
conn = null; // Make sure we don't close it twice
} catch (SQLException e) {
e.printStackTrace();
} finally {
// Always make sure result sets and statements are closed,
// and the connection is returned to the pool
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
rs = null;
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
stmt = null;
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
conn = null;
}
}
return toDoList;
}
public ArrayList<ToDo> getToDoListAll() {
ArrayList<ToDo> toDoList = null;
toDoList = getToDoListByCreator("%");
return toDoList;
}
public int setToDoTaskAsCleared(int taskId) {
Connection conn = null;
Statement stmt = null;
int rs = 0;
System.out.println("Task ID to be CLEARED is " + taskId);
try {
conn = getDBConnection();
stmt = conn.createStatement();
rs = stmt.executeUpdate("UPDATE HAJJ_TODO_LIST SET STATUS = 'CLEARED' WHERE TASK_ID = " + taskId);
stmt.close();
stmt = null;
conn.close(); // Return to connection pool
conn = null; // Make sure we don't close it twice
} catch (SQLException e) {
e.printStackTrace();
} finally {
// Always make sure result sets and statements are closed,
// and the connection is returned to the pool
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();;
}
stmt = null;
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();;
}
conn = null;
}
}
return rs;
}
public int setToDoStatus(int taskId, String status) {
Connection conn = null;
Statement stmt = null;
int rs = 0;
System.out.println("Set Status (Task ID: " + taskId + ", New Status: " + status);
try {
conn = getDBConnection();
stmt = conn.createStatement();
rs = stmt.executeUpdate("UPDATE HAJJ_TODO_LIST SET STATUS = '" + status + "' WHERE TASK_ID = " + taskId);
stmt.close();
stmt = null;
conn.close(); // Return to connection pool
conn = null; // Make sure we don't close it twice
} catch (SQLException e) {
e.printStackTrace();
} finally {
// Always make sure result sets and statements are closed,
// and the connection is returned to the pool
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
stmt = null;
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
conn = null;
}
}
return rs;
}
public int addNewToDo(ToDo toDo) {
Connection conn = null;
Statement stmt = null;
int rs = 0;
// System.out.println("Add ToDo (Task ID: " + toDo.getTaskId() + ", Create UID: " + toDo.getCreatorUid());
try {
conn = getDBConnection();
stmt = conn.createStatement();
String sql = "INSERT INTO HAJJ_TODO_LIST "
+ "(CREATOR_UID, ASSIGNED_UID, ASSIGNED_SHIFT, ASSIGNED_EMAIL, ASSIGNED_MOBILE, TASK_DESC, STATUS, PRIORITY) "
+ "VALUES "
+ "('" + toDo.getCreatorUid() + "', '" + toDo.getAssignedUid() + "', '" + toDo.getAssignedShift() +
"', '" + toDo.getAssignedEmail() + "', '" + toDo.getAssignedMobile() + "', '" + toDo.getTaskDesc() + "', 'PENDING', " + toDo.getPriority() + ")";
System.out.println("Add ToDo --> SQL: " + sql);
rs = stmt.executeUpdate(sql);
stmt.close();
stmt = null;
conn.close(); // Return to connection pool
conn = null; // Make sure we don't close it twice
} catch (SQLException e) {
e.printStackTrace();
} finally {
// Always make sure result sets and statements are closed,
// and the connection is returned to the pool
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
stmt = null;
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
conn = null;
}
}
return rs;
}
public HashMap<String, Utilization> getUtilAll() {
HashMap<String, Utilization> utilHash = null;
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
System.out.println("getUtilAll(...) --> BEGIN");
try {
conn = getDBConnection();
stmt = conn.createStatement();
String sql = "SELECT KPI_DATE, CUSTOMER, CIRCUIT, AVAILABILITY, "
+ "CONFIGURED_BANDWIDTH, AVG_UTIL_IN, AVG_UTIL_OUT, "
+ "MAX_UTIL_IN, MAX_UTIL_IN_DATE, MAX_UTIL_OUT, MAX_UTIL_OUT_DATE, "
+ "AVG_ERROR_IN, AVG_ERROR_OUT, HAJJ, VIP, IS_HAJJ_VIP FROM "
+ "MV_DSH_HAJJ_VIP_IV_UTIL_2017";
rs = stmt.executeQuery(sql);
utilHash = new HashMap<String, Utilization>();
while (rs.next()) {
Utilization util = new Utilization();
util.setKpiDate(rs.getString("KPI_DATE"));
util.setCustomer(rs.getString("CUSTOMER"));
util.setCircuit(rs.getString("CIRCUIT"));
util.setAvailability(rs.getString("AVAILABILITY"));
util.setConfiguredBandwidth(rs.getString("CONFIGURED_BANDWIDTH"));
util.setAvgUtilIn(rs.getString("AVG_UTIL_IN"));
util.setAvgUtilOut(rs.getString("AVG_UTIL_OUT"));
util.setMaxUtilIn(rs.getString("MAX_UTIL_IN"));
util.setMaxUtilInDate(rs.getString("MAX_UTIL_IN_DATE"));
util.setMaxUtilOut(rs.getString("MAX_UTIL_OUT"));
util.setMaxUtilOutDate(rs.getString("MAX_UTIL_OUT_DATE"));
util.setAvgErrorIn(rs.getString("AVG_ERROR_IN"));
util.setAvgErrorOut(rs.getString("AVG_ERROR_OUT"));
util.setHajj(rs.getString("HAJJ"));
util.setVip(rs.getString("VIP"));
util.setIsHajjVip(rs.getString("IS_HAJJ_VIP"));
utilHash.put(util.getCircuit(), util);
}
rs.close();
rs = null;
stmt.close();
stmt = null;
conn.close(); // Return to connection pool
conn = null; // Make sure we don't close it twice
} catch (SQLException e) {
e.printStackTrace();
} finally {
// Always make sure result sets and statements are closed,
// and the connection is returned to the pool
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
rs = null;
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
stmt = null;
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
conn = null;
}
}
return utilHash;
}
public ArrayList<UtilReadings> getUtilReadingsAll() {
ArrayList<UtilReadings> utilReadingsList = null;
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
//System.out.println("getUtilReadingsAll(...) --> BEGIN");
try {
conn = getDBConnection();
stmt = conn.createStatement();
String sql = "SELECT CIRCUIT, SUBSTR(UTIL_DATE, -8, 5) UTIL_DATE, UTIL_IN, UTIL_OUT "
+ "FROM MV_DSH_HAJJ_VIP_LATEST_5_2017 WHERE (UTIL_IN IS NOT NULL AND UTIL_OUT IS NOT NULL) "
+ "ORDER BY CIRCUIT, UTIL_DATE";
rs = stmt.executeQuery(sql);
utilReadingsList = new ArrayList<UtilReadings>();
while (rs.next()) {
UtilReadings utilR = new UtilReadings();
utilR.setUtilDate(rs.getString("UTIL_DATE"));
utilR.setCircuit(rs.getString("CIRCUIT"));
utilR.setUtilIn(rs.getString("UTIL_IN"));
utilR.setUtilOut(rs.getString("UTIL_OUT"));
utilReadingsList.add(utilR);
}
rs.close();
rs = null;
stmt.close();
stmt = null;
conn.close(); // Return to connection pool
conn = null; // Make sure we don't close it twice
} catch (SQLException e) {
e.printStackTrace();
} finally {
// Always make sure result sets and statements are closed,
// and the connection is returned to the pool
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
rs = null;
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
stmt = null;
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
conn = null;
}
}
return utilReadingsList;
}
public Connection getDBConnection() throws SQLException {
Context initContext = null;
Context envContext = null;
DataSource dataSource = null;
Connection connection = null;
try {
initContext = new InitialContext();
envContext = (Context) initContext.lookup("java:/comp/env");
dataSource = (DataSource) envContext.lookup("jdbc/sadb");
connection = dataSource.getConnection();
if (connection != null) {
System.out.println("Connected to database!");
}
} catch (NamingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return connection;
}
}
| true
|
ab55d1994a3a3a48377401c0ac27b6708ca76fec
|
Java
|
ManojReddyPothuganti/HackerRanker
|
/Algorithms/ChiefHooper.java
|
UTF-8
| 589
| 3.203125
| 3
|
[] |
no_license
|
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
int[] a = new int[N];
int minE = 0;
for(int i =0 ;i <N;i++)
{
a[i] = sc.nextInt();
}
for(int j=N-1;j>=0;j--)
{
minE = (minE+a[j] + 1)/2;
}
System.out.println(minE);
}
}
| true
|
bd33e513329da6afea6165e8f900f88a18b8c2bd
|
Java
|
AlexanderUkhta/subscribegenerator
|
/src/main/java/com/a1s/subscribegeneratorapp/excel/WriteToExcel.java
|
UTF-8
| 8,815
| 2.421875
| 2
|
[] |
no_license
|
package com.a1s.subscribegeneratorapp.excel;
import com.a1s.subscribegeneratorapp.config.MsisdnAndExcelProperties;
import com.a1s.subscribegeneratorapp.model.ReportData;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.xssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import static com.a1s.ConfigurationConstantsAndMethods.*;
/**
* Represents methods for writing and saving excel workbook.
*/
@Component
public class WriteToExcel {
private static final Log logger = LogFactory.getLog(WriteToExcel.class);
private XSSFWorkbook book;
private XSSFSheet sheet;
private String sheetName;
@Autowired
private MsisdnAndExcelProperties msisdnAndExcelProperties;
@Autowired
private CellStyle cellStyle;
public WriteToExcel() {
sheetName = getDateWithHourAccuracy();
book = new XSSFWorkbook();
sheet = book.createSheet(sheetName);
}
/**
* Returns current date, which is then set as sheetName.
* @return string like "2019-03-18 18-49"
*/
private String getDateWithHourAccuracy() {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm");
return dateFormat.format(new Date());
}
/**
* Generates first row, that contains column headers.
*/
public void createFirstRow() {
List<String> columnName = msisdnAndExcelProperties.getExcelColumns();
XSSFRow row = sheet.createRow(0);
for (int i = 0; i < columnName.size() - 1; i++) { //No last 'welcome notification' column
XSSFCell cell = row.createCell(i);
cell.setCellValue(columnName.get(i));
cell.setCellStyle(cellStyle.greyBorderAndItalicFont(book));
}
}
/**
* Creates a row in the report sheet and fills it with data from the ReportData.
* @param reportDataMap final map, that is formed after all subscribe responses had arrived
*/
public int writeMap(final Map<Integer, ReportData> reportDataMap) {
AtomicInteger rowsProcessed = new AtomicInteger();
List<String> columnName = new ArrayList<>(msisdnAndExcelProperties.getExcelColumns());
logger.info("Started putting report into new excel.");
reportDataMap.forEach((transactionId, reportData) -> {
logger.info("Processing report data: " + rowsProcessed.incrementAndGet());
XSSFRow row = sheet.createRow(transactionId);
if (reportData.getSubscribeRequestData() != null) {
for (int cellId = 0; cellId < columnName.size() - 1; cellId++) {
int result = createCell(row, cellId, reportData);
if (result == 1) {
if (reportData.getActualResponse() != null) {
reportData.setErrorMessage(RESPONSES_DONT_MATCH);
createCell(row, ERROR_COLUMN, reportData);
break;
} else {
createCell(row, ERROR_COLUMN, reportData);
break;
}
}
}
} else {
for (int cellId = 0; cellId < columnName.size() - 1; cellId++) {
XSSFCell cell = row.createCell(cellId, CellType.STRING);
cell.setCellValue(EMPTY_CELL);
}
createCell(row, ERROR_COLUMN, reportData);
}
});
logger.info("Finished putting report into new excel, going to save document.");
saveReport();
return rowsProcessed.get();
}
/**
* Creates cell in current sheet and fills it with information, according to the column id.
* @param row current raw, correlates with transactionId
* @param cellId number of current cell in current raw
* @param reportData contains the information to be set in all report columns
* @return ONE if actual and expected responses do not correspond, otherwise ZERO
*/
private int createCell(final XSSFRow row, final int cellId, final ReportData reportData) {
XSSFCell cell = row.createCell(cellId, CellType.STRING);
List<String> columnName = msisdnAndExcelProperties.getExcelColumns();
switch (columnName.get(cellId)) {
case ("PS_ID_NAME"):
if (reportData.getSubscribeRequestData().getPsIdName() != null)
cell.setCellValue(reportData.getSubscribeRequestData().getPsIdName());
else cell.setCellValue(EMPTY_CELL);
break;
case ("PS_ID"):
if (reportData.getSubscribeRequestData().getPsId() != 0)
cell.setCellValue(String.valueOf(reportData.getSubscribeRequestData().getPsId()));
else cell.setCellValue(EMPTY_CELL);
break;
case ("SHORT_NUM"):
if (reportData.getSubscribeRequestData().getShortNum() != null)
cell.setCellValue(reportData.getSubscribeRequestData().getShortNum());
else cell.setCellValue(EMPTY_CELL);
break;
case ("REQUEST"):
if (reportData.getSubscribeRequestData().getRequestText() != null)
cell.setCellValue(reportData.getSubscribeRequestData().getRequestText());
else cell.setCellValue(EMPTY_CELL);
break;
case ("EXPECTED_RESPONSE"):
if (reportData.getSubscribeRequestData().getResponseText() != null)
cell.setCellValue(reportData.getSubscribeRequestData().getResponseText());
else cell.setCellValue(EMPTY_CELL);
break;
case ("ACTUAL_RESPONSE"):
if (reportData.getActualResponse() != null) {
String actualResponse = reportData.getActualResponse();
String expectedResult = reportData.getSubscribeRequestData().getResponseText();
cell.setCellValue(reportData.getActualResponse());
XSSFCell expectedCell = row.getCell(cellId - 1);
if (actualResponse.equals(expectedResult)) {
cell.setCellStyle(cellStyle.greenBorderCell(book));
expectedCell.setCellStyle(cellStyle.greenBorderCell(book));
logger.info("Results MATCH!");
} else {
cell.setCellStyle(cellStyle.redBorderCell(book));
// expectedCell.setCellStyle(cellStyle.redBorderCell(book)); see row in ERROR_DATA case
logger.info("Results DO NOT MATCH!");
return 1;
}
} else {
cell.setCellValue(EMPTY_CELL);
return 1;
}
break;
case ("ERROR_DATA"):
String errorMessage = reportData.getErrorMessage();
if (errorMessage != null) {
cell.setCellValue(reportData.getErrorMessage());
cell.setCellStyle(cellStyle.redBorderCell(book));
XSSFCell expectedCell = row.getCell(cellId - 2);
expectedCell.setCellStyle(cellStyle.redBorderCell(book));
}
break;
default:
break;
}
return 0;
}
/**
* Saves Excel report in directory src/main/resources/.
*/
private void saveReport() {
try {
autosizeColumns();
FileOutputStream out = new FileOutputStream(REPORT_PATH);
book.write(out);
out.close();
book.close();
logger.info("Report document is saved.");
} catch (FileNotFoundException e) {
logger.error("Can't find excel on the given path.", e);
e.printStackTrace();
} catch (IOException e) {
logger.error(e);
e.printStackTrace();
}
}
/**
* Autosizes columns by text length.
*/
private void autosizeColumns() {
for (int i = 0; i < sheet.getRow(0).getPhysicalNumberOfCells(); i++) {
sheet.autoSizeColumn(i);
}
logger.info("All columns in report have been autosized.");
}
}
| true
|
7088a471a67d7d032adcb0657d1eb9f2450e5de1
|
Java
|
asifu9/myproject
|
/fullApp/server/src/main/java/com/share/master/data/service/UserCredentialService.java
|
UTF-8
| 580
| 1.90625
| 2
|
[] |
no_license
|
package com.share.master.data.service;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import com.base.domain.UserCredential;
/**
* Created by jt on 1/10/17.
*/
import com.share.exception.AppException;
public interface UserCredentialService {
UserCredential login(String name)throws AppException;
UserCredential createUpdate(UserCredential cre)throws AppException;
UserCredential getById(String id)throws AppException;
}
| true
|
55b37b7093853f5eb5ebffc8b16442525d8e4f13
|
Java
|
Ilya28/mFAL-IDE
|
/src/test/java/asmparser/LangParserTest.java
|
UTF-8
| 2,087
| 2.765625
| 3
|
[] |
no_license
|
package asmparser;
import bingenerator.commandinfo.MFALCommand;
import bingenerator.commandinfo.MFALCommandParam;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.*;
public class LangParserTest {
@Test
public void parseLine() {
//MFALCommand testCmd = LangParser.parseLine("mul reg 5 num 23");
assertEquals(new MFALCommand(MFALCommand.MUL, 5, MFALCommandParam.REG, 23, MFALCommandParam.NUM),
LangParser.parseLine("mul reg 5 num 23"));
assertEquals(new MFALCommand(MFALCommand.DIV, 0, MFALCommandParam.STACK, -457, MFALCommandParam.NUM),
LangParser.parseLine("div stack num -457"));
assertEquals(new MFALCommand(MFALCommand.SUB, 0, MFALCommandParam.STACK, 0, MFALCommandParam.STACK),
LangParser.parseLine("sub STACK STACK"));
assertEquals(new MFALCommand(MFALCommand.RET, new MFALCommandParam(0, MFALCommandParam.STACK), null),
LangParser.parseLine("RET STACK"));
assertEquals(new MFALCommand(MFALCommand.CAL, new MFALCommandParam(9, MFALCommandParam.REG), null),
LangParser.parseLine("cal reg 9"));
assertEquals(new MFALCommand(MFALCommand.MOV, 40324, MFALCommandParam.ARR, 123456789, MFALCommandParam.NUM),
LangParser.parseLine("MOV ARR 40324 NUM 123456789"));
}
@Test
public void asCommandList() {
List<MFALCommand> commands = new ArrayList<>(100);
commands.add(LangParser.parseLine("LFM STACK NUM 0"));
commands.add(LangParser.parseLine("MOV STACK REG 10"));
commands.add(LangParser.parseLine("ADD STACK STACK"));
commands.add(LangParser.parseLine("cal stack"));
String code =
"LFM STACK NUM 0\n" +
"MOV STACK REG 10\n" +
" ADD STACK STACK // hello\n" +
"// omg\n" +
" \n" +
"\n" +
"cal stack\n";
assertEquals(commands, LangParser.asCommandList(code));
}
}
| true
|
2377ec6e9bcdc16bff48101ae78e17bd96e6a0a8
|
Java
|
tangjizhou/algorithm
|
/src/main/java/net/mshome/twisted/algorithm/leecode/GenerateParentheses.java
|
UTF-8
| 461
| 2.390625
| 2
|
[] |
no_license
|
package net.mshome.twisted.algorithm.leecode;
import java.util.Collections;
import java.util.List;
/**
* https://leetcode-cn.com/problems/generate-parentheses/
* 生成所有有效的括号组合
*
* @author tangjizhouchn@foxmail.com
* @since 2020/8/9
*/
public class GenerateParentheses {
public List<String> generateParenthesis(int n) {
if (n <= 0) {
return Collections.emptyList();
}
return Collections.emptyList();
}
}
| true
|
0bbbfb9b6cadf856f566fee0e35520f375ac26cf
|
Java
|
xgzsChris/questionnaire
|
/src/Model2/checkcode.java
|
UTF-8
| 2,101
| 2.34375
| 2
|
[] |
no_license
|
package Model2;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.servlet.*;
public class checkcode extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("image/jpeg");
HttpSession session=request.getSession();
int width=60;
int height=20;
response.setHeader("Pragma","No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
BufferedImage image=new BufferedImage(width,height,BufferedImage.TYPE_INT_BGR);
Graphics g=image.getGraphics();
String chars="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char[] rands=new char[4];
for(int i=0;i<4;i++) {
int rand=(int)(Math.random()*36);
rands[i]=chars.charAt(rand);
}
g.setColor(new Color(0xDCDCDC));
g.fillRect(0, 0, width, height);
for(int i=0;i<120;i++) {
int x=(int)(Math.random()*width);
int y=(int)(Math.random()*height);
int red=(int)(Math.random()*255);
int green=(int)(Math.random()*255);
int blue=(int)(Math.random()*255);
g.setColor(new Color(red,green,blue));
g.drawOval(x, y, 1, 0);
}
g.setColor(Color.BLACK);
g.setFont(new Font(null,Font.ITALIC|Font.BOLD,18));
g.drawString(""+rands[0],1,17);
g.drawString(""+rands[1],16,15);
g.drawString(""+rands[2],31,18);
g.drawString(""+rands[3],46,16);
g.dispose();
ServletOutputStream sos=response.getOutputStream();
ByteArrayOutputStream baos=new ByteArrayOutputStream();
ImageIO.write(image,"JPEG",baos);
byte[] buffer=baos.toByteArray();
response.setContentLength(buffer.length);
sos.write(buffer);
baos.close();
sos.close();
session.setAttribute("checkCode", new String(rands));
}
}
| true
|
38843f176ed3b4dd7a73eb0a99d12029d1b5076f
|
Java
|
tskulbru/TodoApp
|
/src/no/evry/todo/data/TodoItem.java
|
UTF-8
| 430
| 2.28125
| 2
|
[] |
no_license
|
package no.evry.todo.data;
public class TodoItem {
public String id;
public String title;
public String desc;
public boolean finished;
public TodoItem(String id, String title, String desc, boolean finished) {
this.id = id;
this.title = title;
this.desc = desc;
this.finished = finished;
}
public TodoItem(String title, String desc) {
this.title = title;
this.desc = desc;
this.finished = false;
}
}
| true
|
9e3103b04bedc3b683027acb85816c669789cd54
|
Java
|
iamslash/learntocode
|
/leetcode3/SplitStringsbySeparator/MainApp.java
|
UTF-8
| 571
| 3.03125
| 3
|
[] |
no_license
|
// Copyright (C) 2023 by iamslash
import java.util.*;
// 30ms 20.00% 45.1MB 40.00%
// brute force
// O(N) O(N)
class Solution {
public List<String> splitWordsBySeparator(List<String> words, char separator) {
List<String> ans = new ArrayList<>();
for (String word : words) {
String[] strs = word.split(String.format("[%c]", separator));
for (String str : strs) {
if (!str.isEmpty()) {
ans.add(str);
}
}
}
return ans;
}
}
| true
|
3dcbd8a72e553855ccbedac6ee075e8301108d0c
|
Java
|
khushboobajaj25/LeetCode-Problems
|
/src/LeetcodeProblems/LinkedList_Cycle.java
|
UTF-8
| 489
| 2.734375
| 3
|
[] |
no_license
|
package LeetcodeProblems;
public class LinkedList_Cycle {
}
class Solution141 {
public boolean hasCycle(ListNode head) {
ListNode slow,fast;
slow=fast=head;
while(fast!=null &&fast.next!=null && fast.next.next!=null)
{
slow=slow.next;
fast=fast.next.next;
if(fast==slow)
return true;
}
return false;
}
class ListNode{
ListNode next = null;
int val =0;
}
}
| true
|
909e445e4d171b25f449ac381c3c075bd5b99249
|
Java
|
dhananjay762/Test-Automation-Framework
|
/src/test/java/com/store/pages/ShoppingPage.java
|
UTF-8
| 1,225
| 2.203125
| 2
|
[] |
no_license
|
package com.store.pages;
import org.openqa.selenium.By;
import com.store.utility.Keywords;
public class ShoppingPage extends Keywords{
private By casualDressSideMenu = By.xpath("//ul[@class='tree dynamized']/li/a[normalize-space()='Casual Dresses']");
private By firstProduct = By.xpath("//ul[contains(@class, 'product_list')]/li[1]//img");
private By more = By.xpath("//span[text()='More']");
private By addQuantity = By.className("icon-plus");
private By selectSize = By.id("group_1");
private By addToCart = By.xpath("//span[text()='Add to cart']");
private By proceedToCheckout = By.xpath("//a[@title='Proceed to checkout']");
public void clickOnCasualDressMenu() {
ClickOb(casualDressSideMenu);
}
public void chooseFirstProduct() {
ClickOb(firstProduct);
}
public void clickOnMoreForProduct() {
HoverOverElement(firstProduct);
ClickOb(more);
}
public void chooseQuantity(int quantity) {
if(quantity>=2) {
for(int i=0;i<quantity-1;i++) {
ClickOb(addQuantity);
}
}
}
public void selectSize(String size) {
SelectByVisibleText(selectSize, size);
}
public void addToCart() {
ClickOb(addToCart);
}
public void doCheckout() {
ClickOb(proceedToCheckout);
}
}
| true
|
3f20c1d483053299632c0d272e5a52b5993ffc7d
|
Java
|
sitimaeturoh/netbeans
|
/CollectionImpl/src/List/TestList.java
|
UTF-8
| 11,647
| 2.328125
| 2
|
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package List;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.util.List;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
/**
*
* @author MaySM
*/
public class TestList extends javax.swing.JFrame {
List<Object> List = new ArrayList<>();
/**
* Creates new form TestList
*/
public TestList() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
btnTambah = new javax.swing.JButton();
BtnTampil = new javax.swing.JButton();
BtnHapus = new javax.swing.JButton();
BtnUbah = new javax.swing.JButton();
BtnKosongkan = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
MessageArea = new javax.swing.JTextArea();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
btnTambah.setText("Tambahkan Objek");
btnTambah.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnTambahActionPerformed(evt);
}
});
BtnTampil.setText("Tampilkan Isi List");
BtnTampil.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
BtnTampilActionPerformed(evt);
}
});
BtnHapus.setText("Hapus Objek");
BtnHapus.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
BtnHapusActionPerformed(evt);
}
});
BtnUbah.setText("Ubah Objek");
BtnUbah.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
BtnUbahActionPerformed(evt);
}
});
BtnKosongkan.setText("Kosongkan List");
BtnKosongkan.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
BtnKosongkanActionPerformed(evt);
}
});
MessageArea.setColumns(20);
MessageArea.setRows(5);
jScrollPane1.setViewportView(MessageArea);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(20, 20, 20)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(BtnKosongkan)
.addComponent(BtnUbah)
.addComponent(BtnHapus)
.addComponent(BtnTampil)
.addComponent(btnTambah))
.addGap(18, 18, 18)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 394, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(23, 23, 23)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1)
.addGroup(layout.createSequentialGroup()
.addComponent(btnTambah)
.addGap(18, 18, 18)
.addComponent(BtnTampil)
.addGap(18, 18, 18)
.addComponent(BtnHapus)
.addGap(18, 18, 18)
.addComponent(BtnUbah)
.addGap(18, 18, 18)
.addComponent(BtnKosongkan)
.addGap(0, 79, Short.MAX_VALUE)))
.addContainerGap())
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void btnTambahActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnTambahActionPerformed
// TODO add your handling code here
Object input = JOptionPane.showInputDialog(this, "Ketikkan apapun",
"Tambah elemnt", JOptionPane.INFORMATION_MESSAGE);
if(input == null || "".equals(input)){
JOptionPane.showMessageDialog(this, "Anda belum mengetikan"
+ "elemen yang akan ditambahkan");
}else{
List.add(input);
MessageArea.append("Menambahkan objek '"+input+"' ke dalam List\n");
}
}//GEN-LAST:event_btnTambahActionPerformed
private void BtnTampilActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtnTampilActionPerformed
// TODO add your handling code here:
if(List.size() > 0){
MessageArea.setText("");
List.forEach((object) -> {
MessageArea.append("" + object + "\n");
});
}else{
JOptionPane.showMessageDialog(this, "List Kosong");
}
}//GEN-LAST:event_BtnTampilActionPerformed
private void BtnHapusActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtnHapusActionPerformed
// TODO add your handling code here:
JDialog dialog = new JDialog(this, "Hapus isi List",true);
JPanel panel = new JPanel(new BorderLayout());
JComboBox combo = new JComboBox();
List.forEach((Object) -> {
combo.addItem(Object);
});
JButton hapus = new JButton("Hapus");
hapus.addActionListener((ActionEvent e) -> {
if(List.size() > 0){
Object obj = combo.getSelectedItem();
List.remove(obj);
combo.removeAllItems();
List.forEach((Object) -> {
});
JOptionPane.showMessageDialog(TestList.this, "Berhasil"
+ " mnghapus element list");
}else{
JOptionPane.showMessageDialog(TestList.this, "Tidak ada elemen"
+ " dalam list");
}
});
panel.add(combo, BorderLayout.CENTER);
panel.add(hapus, BorderLayout.SOUTH);
dialog.add(panel);
dialog.setLocationRelativeTo(null);
dialog.pack();
dialog.setVisible(true);
}//GEN-LAST:event_BtnHapusActionPerformed
private void BtnUbahActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtnUbahActionPerformed
// TODO add your handling code here:
JDialog dialog = new JDialog(this, "Ubah isi List", true);
JPanel panel = new JPanel (new BorderLayout());
JComboBox combo = new JComboBox();
List.forEach((object) -> {
combo.addItem(object);
});
JTextField txtEdit = new JTextField();
JButton hapus = new JButton("Ubah");
hapus.addActionListener((ActionEvent e) -> {
if(List.size() > 0) {
Object newObject = txtEdit.getText();
if(!txtEdit.getText().isEmpty()) {
Object obj = combo.getSelectedItem();
int index = combo.getSelectedIndex();
List.set(index, newObject);
combo.removeAllItems();
List.forEach((object) -> {
combo.addItem(object);
});
combo.setSelectedIndex(index);
txtEdit.setText("");
JOptionPane.showMessageDialog(TestList.this,"Berhasil"
+ "mengubah elemen List");
}else{
JOptionPane.showMessageDialog(TestList.this, "Masukan"
+ "elemen/objek");
txtEdit.requestFocus();
}
}else{
JOptionPane.showMessageDialog(TestList.this, "Tidak ada elemen"
+ "dalam liat");
}
});
panel.add(combo, BorderLayout.NORTH);
panel.add(txtEdit, BorderLayout.CENTER);
panel.add(hapus, BorderLayout.SOUTH);
dialog.add(panel);
dialog.setLocation(null);
dialog.pack();
dialog.setVisible(true);
}//GEN-LAST:event_BtnUbahActionPerformed
private void BtnKosongkanActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtnKosongkanActionPerformed
// TODO add your handling code her
List.clear();
JOptionPane.showMessageDialog(TestList.this,"semua elemen dalam list"
+ "telah di hapus");
}//GEN-LAST:event_BtnKosongkanActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(TestList.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(TestList.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(TestList.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(TestList.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new TestList().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton BtnHapus;
private javax.swing.JButton BtnKosongkan;
private javax.swing.JButton BtnTampil;
private javax.swing.JButton BtnUbah;
private javax.swing.JTextArea MessageArea;
private javax.swing.JButton btnTambah;
private javax.swing.JScrollPane jScrollPane1;
// End of variables declaration//GEN-END:variables
}
| true
|
985161e2f8a02a5920b7158f19b30d75a6dcd3b1
|
Java
|
ilefotiv/progetto-ing-soft
|
/SimpleTwitterServer/src/server/hibernate___foundation/ENota.java
|
UTF-8
| 12,075
| 2.234375
| 2
|
[] |
no_license
|
/**
* "Visual Paradigm: DO NOT MODIFY THIS FILE!"
*
* This is an automatic generated file. It will be regenerated every time
* you generate persistence class.
*
* Modifying its content may cause the program not work, or your work may lost.
*/
/**
* Licensee: DuKe TeAm
* License Type: Purchased
*/
package server.hibernate___foundation;
import org.orm.*;
import org.hibernate.Query;
import java.util.List;
public class ENota extends EntityServer {
public ENota() {
}
public static ENota loadENotaByORMID(int id) throws PersistentException {
try {
PersistentSession session = server.hibernate___foundation.Android2javaPersistentManager.instance().getSession();
return loadENotaByORMID(session, id);
}
catch (Exception e) {
e.printStackTrace();
throw new PersistentException(e);
}
}
public static ENota getENotaByORMID(int id) throws PersistentException {
try {
PersistentSession session = server.hibernate___foundation.Android2javaPersistentManager.instance().getSession();
return getENotaByORMID(session, id);
}
catch (Exception e) {
e.printStackTrace();
throw new PersistentException(e);
}
}
public static ENota loadENotaByORMID(int id, org.hibernate.LockMode lockMode) throws PersistentException {
try {
PersistentSession session = server.hibernate___foundation.Android2javaPersistentManager.instance().getSession();
return loadENotaByORMID(session, id, lockMode);
}
catch (Exception e) {
e.printStackTrace();
throw new PersistentException(e);
}
}
public static ENota getENotaByORMID(int id, org.hibernate.LockMode lockMode) throws PersistentException {
try {
PersistentSession session = server.hibernate___foundation.Android2javaPersistentManager.instance().getSession();
return getENotaByORMID(session, id, lockMode);
}
catch (Exception e) {
e.printStackTrace();
throw new PersistentException(e);
}
}
public static ENota loadENotaByORMID(PersistentSession session, int id) throws PersistentException {
try {
return (ENota) session.load(server.hibernate___foundation.ENota.class, new Integer(id));
}
catch (Exception e) {
e.printStackTrace();
throw new PersistentException(e);
}
}
public static ENota getENotaByORMID(PersistentSession session, int id) throws PersistentException {
try {
return (ENota) session.get(server.hibernate___foundation.ENota.class, new Integer(id));
}
catch (Exception e) {
e.printStackTrace();
throw new PersistentException(e);
}
}
public static ENota loadENotaByORMID(PersistentSession session, int id, org.hibernate.LockMode lockMode) throws PersistentException {
try {
return (ENota) session.load(server.hibernate___foundation.ENota.class, new Integer(id), lockMode);
}
catch (Exception e) {
e.printStackTrace();
throw new PersistentException(e);
}
}
public static ENota getENotaByORMID(PersistentSession session, int id, org.hibernate.LockMode lockMode) throws PersistentException {
try {
return (ENota) session.get(server.hibernate___foundation.ENota.class, new Integer(id), lockMode);
}
catch (Exception e) {
e.printStackTrace();
throw new PersistentException(e);
}
}
public static ENota[] listENotaByQuery(String condition, String orderBy) throws PersistentException {
try {
PersistentSession session = server.hibernate___foundation.Android2javaPersistentManager.instance().getSession();
return listENotaByQuery(session, condition, orderBy);
}
catch (Exception e) {
e.printStackTrace();
throw new PersistentException(e);
}
}
public static ENota[] listENotaByQuery(String condition, String orderBy, org.hibernate.LockMode lockMode) throws PersistentException {
try {
PersistentSession session = server.hibernate___foundation.Android2javaPersistentManager.instance().getSession();
return listENotaByQuery(session, condition, orderBy, lockMode);
}
catch (Exception e) {
e.printStackTrace();
throw new PersistentException(e);
}
}
public static ENota[] listENotaByQuery(PersistentSession session, String condition, String orderBy) throws PersistentException {
StringBuffer sb = new StringBuffer("From server.hibernate___foundation.ENota as ENota");
if (condition != null)
sb.append(" Where ").append(condition);
if (orderBy != null)
sb.append(" Order By ").append(orderBy);
try {
Query query = session.createQuery(sb.toString());
List list = query.list();
return (ENota[]) list.toArray(new ENota[list.size()]);
}
catch (Exception e) {
e.printStackTrace();
throw new PersistentException(e);
}
}
public static ENota[] listENotaByQuery(PersistentSession session, String condition, String orderBy, org.hibernate.LockMode lockMode) throws PersistentException {
StringBuffer sb = new StringBuffer("From server.hibernate___foundation.ENota as ENota");
if (condition != null)
sb.append(" Where ").append(condition);
if (orderBy != null)
sb.append(" Order By ").append(orderBy);
try {
Query query = session.createQuery(sb.toString());
query.setLockMode("this", lockMode);
List list = query.list();
return (ENota[]) list.toArray(new ENota[list.size()]);
}
catch (Exception e) {
e.printStackTrace();
throw new PersistentException(e);
}
}
public static ENota loadENotaByQuery(String condition, String orderBy) throws PersistentException {
try {
PersistentSession session = server.hibernate___foundation.Android2javaPersistentManager.instance().getSession();
return loadENotaByQuery(session, condition, orderBy);
}
catch (Exception e) {
e.printStackTrace();
throw new PersistentException(e);
}
}
public static ENota loadENotaByQuery(String condition, String orderBy, org.hibernate.LockMode lockMode) throws PersistentException {
try {
PersistentSession session = server.hibernate___foundation.Android2javaPersistentManager.instance().getSession();
return loadENotaByQuery(session, condition, orderBy, lockMode);
}
catch (Exception e) {
e.printStackTrace();
throw new PersistentException(e);
}
}
public static ENota loadENotaByQuery(PersistentSession session, String condition, String orderBy) throws PersistentException {
ENota[] eNotas = listENotaByQuery(session, condition, orderBy);
if (eNotas != null && eNotas.length > 0)
return eNotas[0];
else
return null;
}
public static ENota loadENotaByQuery(PersistentSession session, String condition, String orderBy, org.hibernate.LockMode lockMode) throws PersistentException {
ENota[] eNotas = listENotaByQuery(session, condition, orderBy, lockMode);
if (eNotas != null && eNotas.length > 0)
return eNotas[0];
else
return null;
}
public static java.util.Iterator iterateENotaByQuery(String condition, String orderBy) throws PersistentException {
try {
PersistentSession session = server.hibernate___foundation.Android2javaPersistentManager.instance().getSession();
return iterateENotaByQuery(session, condition, orderBy);
}
catch (Exception e) {
e.printStackTrace();
throw new PersistentException(e);
}
}
public static java.util.Iterator iterateENotaByQuery(String condition, String orderBy, org.hibernate.LockMode lockMode) throws PersistentException {
try {
PersistentSession session = server.hibernate___foundation.Android2javaPersistentManager.instance().getSession();
return iterateENotaByQuery(session, condition, orderBy, lockMode);
}
catch (Exception e) {
e.printStackTrace();
throw new PersistentException(e);
}
}
public static java.util.Iterator iterateENotaByQuery(PersistentSession session, String condition, String orderBy) throws PersistentException {
StringBuffer sb = new StringBuffer("From server.hibernate___foundation.ENota as ENota");
if (condition != null)
sb.append(" Where ").append(condition);
if (orderBy != null)
sb.append(" Order By ").append(orderBy);
try {
Query query = session.createQuery(sb.toString());
return query.iterate();
}
catch (Exception e) {
e.printStackTrace();
throw new PersistentException(e);
}
}
public static java.util.Iterator iterateENotaByQuery(PersistentSession session, String condition, String orderBy, org.hibernate.LockMode lockMode) throws PersistentException {
StringBuffer sb = new StringBuffer("From server.hibernate___foundation.ENota as ENota");
if (condition != null)
sb.append(" Where ").append(condition);
if (orderBy != null)
sb.append(" Order By ").append(orderBy);
try {
Query query = session.createQuery(sb.toString());
query.setLockMode("this", lockMode);
return query.iterate();
}
catch (Exception e) {
e.printStackTrace();
throw new PersistentException(e);
}
}
public static ENota loadENotaByCriteria(ENotaCriteria eNotaCriteria) {
ENota[] eNotas = listENotaByCriteria(eNotaCriteria);
if(eNotas == null || eNotas.length == 0) {
return null;
}
return eNotas[0];
}
public static ENota[] listENotaByCriteria(ENotaCriteria eNotaCriteria) {
return eNotaCriteria.listENota();
}
public static ENota createENota() {
return new server.hibernate___foundation.ENota();
}
public boolean save() throws PersistentException {
try {
server.hibernate___foundation.Android2javaPersistentManager.instance().saveObject(this);
return true;
}
catch (Exception e) {
e.printStackTrace();
throw new PersistentException(e);
}
}
public boolean delete() throws PersistentException {
try {
server.hibernate___foundation.Android2javaPersistentManager.instance().deleteObject(this);
return true;
}
catch (Exception e) {
e.printStackTrace();
throw new PersistentException(e);
}
}
public boolean refresh() throws PersistentException {
try {
server.hibernate___foundation.Android2javaPersistentManager.instance().getSession().refresh(this);
return true;
}
catch (Exception e) {
e.printStackTrace();
throw new PersistentException(e);
}
}
public boolean evict() throws PersistentException {
try {
server.hibernate___foundation.Android2javaPersistentManager.instance().getSession().evict(this);
return true;
}
catch (Exception e) {
e.printStackTrace();
throw new PersistentException(e);
}
}
public boolean deleteAndDissociate()throws PersistentException {
try {
if(getScrittaDa() != null) {
getScrittaDa().getAutoreDi().remove(this);
}
return delete();
}
catch(Exception e) {
e.printStackTrace();
throw new PersistentException(e);
}
}
public boolean deleteAndDissociate(org.orm.PersistentSession session)throws PersistentException {
try {
if(getScrittaDa() != null) {
getScrittaDa().getAutoreDi().remove(this);
}
try {
session.delete(this);
return true;
} catch (Exception e) {
return false;
}
}
catch(Exception e) {
e.printStackTrace();
throw new PersistentException(e);
}
}
public int id;
private server.hibernate___foundation.EUtente scrittaDa;
public String content;
public long data;
public void setContent(String value) {
this.content = value;
}
public String getContent() {
return content;
}
public void setData(long value) {
this.data = value;
}
public long getData() {
return data;
}
private void setId(int value) {
this.id = value;
}
public int getId() {
return id;
}
public int getORMID() {
return getId();
}
public void setScrittaDa(server.hibernate___foundation.EUtente value) {
this.scrittaDa = value;
}
public server.hibernate___foundation.EUtente getScrittaDa() {
return scrittaDa;
}
public String toString() {
return String.valueOf(getId());
}
}
| true
|
c3cf7b21b853a4a539f5f58b599c43a796b2c171
|
Java
|
xumingyi/WanAndroid
|
/common/src/main/java/com/sgitg/common/common/OnStepperNavigationBarListener.java
|
UTF-8
| 311
| 1.695313
| 2
|
[] |
no_license
|
package com.sgitg.common.common;
/**
* 描述:
*
* @author 周麟
* @created 2018/3/12 14:09
*/
public interface OnStepperNavigationBarListener {
/**
* STEP组件下一步按钮状态回调
*
* @param enabled 是否可用
*/
void onChangeEndButtonEnabled(boolean enabled);
}
| true
|
001a5da6aae3764d6c540638cfd4dbff75835ee5
|
Java
|
sunlight3d/Aptech
|
/C2009i/Android/21-09-2022/app/src/main/java/nguyenvana/aprotrain/com/database/TblNotes.java
|
UTF-8
| 381
| 1.859375
| 2
|
[] |
no_license
|
package nguyenvana.aprotrain.com.database;
public class TblNotes {
public static final String TABLE_NAME = "tblNotes";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_CONTENT = "content";
public static final String COLUMN_IMPORTANT = "isImportant";
public static final String COLUMN_CREATED_DATE = "createdDate";
}
| true
|
03a43549cfd70c4a6a72457b133f35de24884950
|
Java
|
zongyangqu/DevelopTools
|
/app/src/main/java/com/quzy/coding/ui/activity/StaggeredGridActivity.java
|
UTF-8
| 5,038
| 2.109375
| 2
|
[] |
no_license
|
package com.quzy.coding.ui.activity;
import android.view.View;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;
import com.coding.qzy.baselibrary.utils.AbToastUtil;
import com.coding.qzy.baselibrary.widget.refreshview.SpringView;
import com.coding.qzy.baselibrary.widget.refreshview.container.MeituanFooter;
import com.coding.qzy.baselibrary.widget.refreshview.container.MeituanHeader;
import com.quzy.coding.R;
import com.quzy.coding.base.BaseActivity;
import com.quzy.coding.bean.Anim;
import com.quzy.coding.ui.adapter.StaggeredAdapter;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
/**
* author : quzongyang
* e-mail : quzongyang@xiaohe.com
* time : 2018/11/16
* desc :
* version: 1.0
*/
public class StaggeredGridActivity extends BaseActivity {
@BindView(R.id.recyclerView)
RecyclerView recyclerView;
@BindView(R.id.springview)
SpringView springView;
int total_page = 3;
int currentPage = 1;
private List<Anim> data;
private StaggeredAdapter adapter;
@Override
protected void onViewCreated() {
//线性布局Manager
// LinearLayoutManager recyclerViewLayoutManager = new LinearLayoutManager(this);
//recyclerViewLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
//网络布局Manager
//GridLayoutManager recyclerViewLayoutManager = new GridLayoutManager(this, 3);
//使用瀑布流布局
// 第一个参数 spanCount 列数,第二个参数 orentation 排列方向
//给recyclerView设置LayoutManager
StaggeredGridLayoutManager recyclerViewLayoutManager =
new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
recyclerView.setLayoutManager(recyclerViewLayoutManager);
initData();
adapter = new StaggeredAdapter(data, this);
recyclerView.setAdapter(adapter);
setListener();
}
public void setListener() {
springView.setType(SpringView.Type.FOLLOW);
springView.setListener(new SpringView.OnFreshListener() {
@Override
public void onRefresh() {
initData();
adapter.refresh(data);
springView.onFinishFreshAndLoad();
}
@Override
public void onLoadmore() {
if (total_page > currentPage) {
currentPage = currentPage + 1;
adapter.addDatas(addData());
springView.onFinishFreshAndLoad();
} else {
springView.onFinishFreshAndLoad();
AbToastUtil.showToast(getActivity(), "没有更多了,亲!");
}
}
});
springView.setHeader(new MeituanHeader(getActivity()));
springView.setFooter(new MeituanFooter(getActivity()));
// springView.setHeader(new RotationHeader(getActivity()));
// springView.setFooter(new RotationFooter(getActivity()));
}
/**
* 生成一些数据添加到集合中
*/
private void initData() {
Anim anim;
currentPage = 1;
data = new ArrayList<Anim>();
for (int i = 0; i < 5; i++) {
anim = new Anim("狮子" + i, R.mipmap.shizi);
data.add(anim);
anim = new Anim("老虎" + i, R.mipmap.artboard);
data.add(anim);
anim = new Anim("daxiang" + i, R.mipmap.daxiang);
data.add(anim);
anim = new Anim("狗" + i, R.mipmap.gougou);
data.add(anim);
anim = new Anim("狗" + i, R.mipmap.gougou1);
data.add(anim);
anim = new Anim("猫" + i, R.mipmap.mao);
data.add(anim);
anim = new Anim("哈士奇" + i, R.mipmap.hashiqi);
data.add(anim);
anim = new Anim("哈士奇" + i, R.mipmap.hashiqi1);
data.add(anim);
anim = new Anim("老虎" + i, R.mipmap.artboard);
data.add(anim);
anim = new Anim("猫" + i, R.mipmap.mao);
data.add(anim);
}
}
private List<Anim> addData() {
List<Anim> data = new ArrayList<Anim>();
data.add(new Anim("哈士奇" , R.mipmap.hashiqi));
data.add(new Anim("哈士奇" , R.mipmap.hashiqi1));
data.add(new Anim("老虎" , R.mipmap.artboard));
data.add(new Anim("猫" , R.mipmap.mao));
data.add(new Anim("狮子" , R.mipmap.shizi));
data.add(new Anim("老虎" , R.mipmap.artboard));
data.add(new Anim("daxiang" , R.mipmap.daxiang));
data.add(new Anim("狗" , R.mipmap.gougou));
data.add(new Anim("狗" , R.mipmap.gougou1));
data.add(new Anim("猫" , R.mipmap.mao));
return data;
}
@Override
protected View getLayoutView() {
return null;
}
@Override
protected int getLayoutId() {
return R.layout.activity_staggered_activity;
}
}
| true
|
44db0454c471d6bd0ee4df9924995d3add1e87f4
|
Java
|
techgeeker/java
|
/java-test/src/com/reflection/VipUser.java
|
UTF-8
| 896
| 2.609375
| 3
|
[] |
no_license
|
package com.reflection;
public class VipUser extends User implements Comparable<VipUser> {
private Integer score;
private String vipNo;
public Integer getScore() {
return score;
}
public void setScore(Integer score) {
this.score = score;
}
public String getVipNo() {
return vipNo;
}
public void setVipNo(String vipNo) {
this.vipNo = vipNo;
}
@Override
public String toString() {
final StringBuffer sb = new StringBuffer("VipUser{");
sb.append("id=").append(getId());
sb.append(", name='").append(getName()).append('\'');
sb.append(", score=").append(score);
sb.append(", vipNo='").append(vipNo).append('\'');
sb.append('}');
return sb.toString();
}
@Override
public int compareTo(VipUser user) {
return score - user.score;
}
}
| true
|
f97402f9f088688320bdbcc6a1ba6fbbacaa1254
|
Java
|
AirYoukai/an-ze-xian
|
/anZeXian/src/main/java/com/anzexian/demo/entity/extend/InsuranceServiceExtend.java
|
UTF-8
| 1,467
| 2.015625
| 2
|
[] |
no_license
|
package com.anzexian.demo.entity.extend;
import com.anzexian.demo.entity.InsuranceCompany;
public class InsuranceServiceExtend {
private InsuranceCompany insuranceCompany;
private String createTimeFrom;
private String createTimeTo;
private String orderByOne;
private String orderByTwo;
private String orderByThree;
public InsuranceCompany getInsuranceCompany() {
return insuranceCompany;
}
public void setInsuranceCompany(InsuranceCompany insuranceCompany) {
this.insuranceCompany = insuranceCompany;
}
public String getOrderByOne() {
return orderByOne;
}
public void setOrderByOne(String orderByOne) {
this.orderByOne = orderByOne;
}
public String getOrderByTwo() {
return orderByTwo;
}
public void setOrderByTwo(String orderByTwo) {
this.orderByTwo = orderByTwo;
}
public String getOrderByThree() {
return orderByThree;
}
public void setOrderByThree(String orderByThree) {
this.orderByThree = orderByThree;
}
public String getCreateTimeFrom() {
return createTimeFrom;
}
public void setCreateTimeFrom(String createCreateTimeFrom) {
this.createTimeFrom = createCreateTimeFrom;
}
public String getCreateTimeTo() {
return createTimeTo;
}
public void setCreateTimeTo(String createCreateTimeTo) {
this.createTimeTo = createCreateTimeTo;
}
}
| true
|
dd48c3c773110acd58d2c13c10f4f91adc238d1b
|
Java
|
lfbermeo/fp-utpl-18-clases
|
/semana_6/src/Ejercicio_2.java
|
UTF-8
| 697
| 3.34375
| 3
|
[] |
no_license
|
import java.util.Scanner;
public class Ejercicio_2 {
public static void main(String[] args) {
Scanner entrada = new Scanner (System.in);
String cadena_final;
int suma=0;
int edad;
int contador = 1;
cadena_final = String.format("%s\t%s\n","Edad", "Suma");
while ( contador <=5){
System.out.println("Ingrese el valor de edad");
edad = entrada.nextInt();
suma = suma+ edad ;
cadena_final = String.format("%s%d\t%d\n",cadena_final, edad,suma);
contador = contador +1;
}
System.out.printf("%s",cadena_final);
}
}
| true
|
620144bf7ad0cb8aaf1603e610b97b4340ea505e
|
Java
|
bellmit/origin
|
/family_order/src/soa/com/asiainfo/veris/crm/order/soa/group/groupTrans/action/qry/TransSnB2SnAction.java
|
UTF-8
| 669
| 1.773438
| 2
|
[] |
no_license
|
package com.asiainfo.veris.crm.order.soa.group.groupTrans.action.qry;
import com.ailk.common.data.IData;
import com.asiainfo.veris.crm.order.pub.frame.bcf.util.IDataUtil;
import com.asiainfo.veris.crm.order.soa.frame.bcf.group.common.base.trans.ITrans;
public class TransSnB2SnAction implements ITrans
{
@Override
public final void transRequestData(IData idata) throws Exception
{
addSubDataBefore(idata);
}
// 子类重载
protected void addSubDataBefore(IData idata) throws Exception
{
IDataUtil.chkParam(idata, "SERIAL_NUMBER_B");
idata.put("SERIAL_NUMBER", idata.getString("SERIAL_NUMBER_B", ""));
}
}
| true
|
7b3facb7146486915505d1246b0a970bfff4ae6c
|
Java
|
masler77/json_jackson
|
/src/main/java/json/bindingWriter.java
|
UTF-8
| 2,254
| 2.84375
| 3
|
[] |
no_license
|
package json;
import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.Map;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class bindingWriter {
public static void main(String[] args){
ObjectMapper mapper = new ObjectMapper();
stu stu = new stu();
stu.setId(1234);
stu.setName("Magnus");
stu.setLastName("leray");
stu stu2 = new stu();
stu2.setId(1);
stu2.setName("Magnus2");
stu2.setLastName("leray2");
try {
System.out.println(mapper.writeValueAsString(stu));
System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(stu));
} catch (JsonProcessingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Map<String, Object> mapJson = new LinkedHashMap<String, Object>();
mapJson.put("key1", 1);
mapJson.put("key2", 22);
mapJson.put("key3", 333);
mapJson.put("booleanTrue", true);
mapJson.put("booleanFalse", false);
mapJson.put("array", new String[]{"1","2","3"});
mapJson.put("arratOfObjects", new stu[]{stu, stu2});
mapJson.put("nestedObjekt", stu);
mapJson.put("integer", 1);
mapJson.put("valueNull", null);
mapJson.put("list", Arrays.asList(1,2,3,4,5));
mapJson.put("date", LocalDateTime.now().toString());
try {
System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(mapJson));
} catch (JsonProcessingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
mapper.writerWithDefaultPrettyPrinter().writeValue(new File("src\\main\\resources\\jsonMap.json"), mapJson);
} catch (JsonGenerationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JsonMappingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| true
|
b28964f971eb5c7359e9c416512ea66f75d887a6
|
Java
|
denghui1010/realtime-store
|
/src/main/java/com/goodow/realtime/store/CollaborativeString.java
|
UTF-8
| 9,362
| 2.15625
| 2
|
[] |
no_license
|
/*
* Copyright 2012 Goodow.com
*
* 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.goodow.realtime.store;
import com.goodow.realtime.core.Diff;
import com.goodow.realtime.core.Handler;
import com.goodow.realtime.core.Platform;
import com.goodow.realtime.core.Registration;
import com.goodow.realtime.operation.Operation;
import com.goodow.realtime.operation.OperationComponent;
import com.goodow.realtime.operation.create.CreateComponent;
import com.goodow.realtime.operation.list.ListTarget;
import com.goodow.realtime.operation.list.string.StringDeleteComponent;
import com.goodow.realtime.operation.list.string.StringInsertComponent;
import com.goodow.realtime.store.util.ModelFactory;
import com.google.common.annotations.GwtIncompatible;
import org.timepedia.exporter.client.Export;
import org.timepedia.exporter.client.ExportAfterCreateMethod;
import org.timepedia.exporter.client.ExportPackage;
/**
* Creates a new collaborative string. Unlike regular strings, collaborative strings are mutable.
* <p>
* Changes to the string will automatically be synced with the server and other collaborators. To
* listen for changes, add EventListeners for the following event types:
* <ul>
* <li>{@link com.goodow.realtime.store.EventType#TEXT_INSERTED}
* <li>{@link com.goodow.realtime.store.EventType#TEXT_DELETED}
* </ul>
* <p>
* This class should not be instantiated directly. To create a new collaborative string, use
* {@link com.goodow.realtime.store.Model#createString(String)}
*/
@ExportPackage(ModelFactory.PACKAGE_PREFIX_REALTIME)
@Export(all = true)
public class CollaborativeString extends CollaborativeObject {
@GwtIncompatible(ModelFactory.JS_REGISTER_PROPERTIES)
@ExportAfterCreateMethod
// @formatter:off
public native static void __jsniRunAfter__() /*-{
// var _ = $wnd.good.realtime.CollaborativeString.prototype;
// Object.defineProperties(_, {
// id : {
// get : function() {
// return this.g.@com.goodow.realtime.store.CollaborativeObject::id;
// }
// },
// length : {
// get : function() {
// return this.g.@com.goodow.realtime.store.CollaborativeString::length()();
// }
// }
// });
}-*/;
// @formatter:on
private final StringBuilder snapshot;
CollaborativeString(Model model) {
super(model);
snapshot = new StringBuilder();
}
public Registration addTextDeletedListener(Handler<TextDeletedEvent> handler) {
return addEventListener(EventType.TEXT_DELETED, handler, false);
}
public Registration addTextInsertedListener(Handler<TextInsertedEvent> handler) {
return addEventListener(EventType.TEXT_INSERTED, handler, false);
}
/**
* Appends a string to the end of this one.
*
* @param text The new text to append.
* @exception java.lang.IllegalArgumentException
*/
public void append(String text) {
insertString(length(), text);
}
/**
* Gets a string representation of the collaborative string.
*
* @return A string representation of the collaborative string.
*/
public String getText() {
return snapshot.toString();
}
/**
* Inserts a string into the collaborative string at a specific index.
*
* @param index The index to insert at.
* @param text The new text to insert.
* @exception java.lang.IllegalArgumentException
* @exception java.lang.StringIndexOutOfBoundsException
*/
public void insertString(int index, String text) {
if (text == null || text.isEmpty()) {
throw new IllegalArgumentException(
"At least one value must be specified for an insert mutation. text: " + text);
}
checkIndex(index);
StringInsertComponent op = new StringInsertComponent(id, index, text);
consumeAndSubmit(op);
}
/**
* @return The length of the string. Read only.
*/
public int length() {
return snapshot.length();
}
/**
* Creates an IndexReference at the given {@code index}. If {@code canBeDeleted} is set, then a
* delete over the index will delete the reference. Otherwise the reference will shift to the
* beginning of the deleted range.
*
* @param index The index of the reference.
* @param canBeDeleted Whether this index is deleted when there is a delete of a range covering
* this index.
* @return The newly registered reference.
*/
public IndexReference registerReference(int index, boolean canBeDeleted) {
checkIndex(index);
return model.createIndexReference(id, index, canBeDeleted);
}
/**
* Deletes the text between startIndex (inclusive) and endIndex (exclusive).
*
* @param startIndex The start index of the range to delete (inclusive).
* @param endIndex The end index of the range to delete (exclusive).
* @exception java.lang.StringIndexOutOfBoundsException
*/
public void removeRange(int startIndex, int endIndex) {
int length = length();
if (startIndex < 0 || startIndex >= length || endIndex <= startIndex || endIndex > length) {
throw new StringIndexOutOfBoundsException("StartIndex: " + startIndex + ", EndIndex: "
+ endIndex + ", Size: " + length);
}
StringDeleteComponent op =
new StringDeleteComponent(id, startIndex, snapshot.substring(startIndex, endIndex));
consumeAndSubmit(op);
}
/**
* Sets the contents of this collaborative string. Note that this method performs a text diff
* between the current string contents and the new contents so that the string will be modified
* using the minimum number of text inserts and deletes possible to change the current contents to
* the newly-specified contents.
*
* @param text The new value of the string.
*/
public void setText(String text) {
if (text == null) {
throw new IllegalArgumentException("Expected string for text, but was: null");
}
model.beginCompoundOperation("replaceText");
Platform.diff().diff(getText(), text, new Diff.ListTarget<String>() {
@Override
public void insert(int startIndex, String values) {
insertString(startIndex, values);
}
@Override
public void remove(int startIndex, int length) {
removeRange(startIndex, startIndex + length);
}
@Override
public void replace(int startIndex, String values) {
throw new UnsupportedOperationException();
}
@Override
public void move(int fromIndex, int toIndex, int length) {
throw new UnsupportedOperationException();
}
});
model.endCompoundOperation();
}
@Override
public Object toJson() {
return getText();
}
@SuppressWarnings("unchecked")
@Override
protected void consume(final String userId, final String sessionId,
OperationComponent<?> component) {
((Operation<ListTarget<String>>) component).apply(new ListTarget<String>() {
@Override
public void delete(int startIndex, int length) {
deleteAndFireEvent(startIndex, length, sessionId, userId);
}
@Override
public void insert(int startIndex, String values) {
insertAndFireEvent(startIndex, values, sessionId, userId);
}
@Override
public void replace(int startIndex, String values) {
throw new UnsupportedOperationException();
}
});
}
@Override
OperationComponent<?>[] toInitialization() {
OperationComponent<?>[] toRtn = new OperationComponent[1 + (length() == 0 ? 0 : 1)];
toRtn[0] = new CreateComponent(id, CreateComponent.STRING);
if (length() != 0) {
toRtn[1] = new StringInsertComponent(id, 0, getText());
}
return toRtn;
}
private void checkIndex(int index) {
int length = length();
if (index < 0 || index > length) {
throw new StringIndexOutOfBoundsException("Index: " + index + ", Size: " + length);
}
}
private void deleteAndFireEvent(int startIndex, int length, String sessionId, String userId) {
int endIndex = startIndex + length;
assert length > 0 && endIndex <= length();
String toDelete = snapshot.substring(startIndex, endIndex);
TextDeletedEvent event =
new TextDeletedEvent(event(sessionId, userId).set("index", startIndex)
.set("text", toDelete));
snapshot.delete(startIndex, endIndex);
fireEvent(event);
model.setIndexReferenceIndex(id, false, startIndex, length, sessionId, userId);
model.bytesUsed -= length;
}
private void insertAndFireEvent(int index, String text, String sessionId, String userId) {
assert index <= length();
TextInsertedEvent event =
new TextInsertedEvent(event(sessionId, userId).set("index", index).set("text", text));
snapshot.insert(index, text);
fireEvent(event);
model.setIndexReferenceIndex(id, true, index, text.length(), sessionId, userId);
model.bytesUsed += text.length();
}
}
| true
|
34fdddef173c28db5b9ee9a77a3dfcf91e909360
|
Java
|
TuyenHuynhCong/hocjava
|
/JavaCore/src/Mang_TimKiem/TimKiemPhanTu.java
|
UTF-8
| 1,666
| 3.421875
| 3
|
[] |
no_license
|
package Mang_TimKiem;
import java.util.Scanner;
public class TimKiemPhanTu {
public static void NhapMang(int M[])
{
Scanner sc=new Scanner(System.in);
for(int i=0;i<M.length;i++)
{
System.out.println("M["+i+"]=");
M[i]=sc.nextInt();
}
}
public static void XuatMang(int M[])
{
for(int i=0; i<M.length;i++)
{
System.out.print(M[i]+ " ");
}
}
public static void TimSuXuatHien(int M[], int k)
{
Boolean TimThay=false;
for(int i=0; i<M.length;i++)
{
if(M[i]==k)
{
TimThay=true;
break;
}
}
if(TimThay==true)
{
System.out.println("phan tu "+k+"co trong mang");
}
else
{
System.out.println("phan tu "+k+" khong co trong mang");
}
}
public static void TimSoLanXuatHien(int M[], int k)
{
String s="";
int Solan=0;
for(int i=0;i<M.length;i++)
{
if(M[i]==k)
{
s+=i+";";
Solan++;
}
}
if(Solan>0)
{
System.out.println("so lan xuat hien cua "+k+"la:"+Solan);
System.out.println("vi tri cua tung phan tu la: "+s);
}
else
{
System.out.println("khong co phan tu "+k+" trong mang");
}
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("Nhap so luong phan tu cua mang: ");
int n=sc.nextInt();
int M[]= new int [n];
System.out.println("Moi ban nhap tung phan tu cho mang: ");
NhapMang(M);
System.out.println("Mang sau khi nhap la: ");
XuatMang(M);
System.out.println("Moi ban nhap phan tu k de tim kiem: ");
int k=sc.nextInt();
TimSuXuatHien(M, k);
System.out.println("moi ban nhap phan tu k de tim so lan xuat hien: ");
int x=sc.nextInt();
TimSoLanXuatHien(M, x);
}
}
| true
|
2f019fddd6bd656291f31f991733b2ca6b82dea4
|
Java
|
anshulBharath/CISC230-classwork
|
/Lab10/src/Misc.java
|
UTF-8
| 953
| 3.6875
| 4
|
[] |
no_license
|
import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.ListIterator;
import java.util.Scanner;
public class Misc {
public void method1() {
System.out.println("How now brown cow");
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int in = 0;
ArrayList<Integer> list = new ArrayList<Integer>();
while(in >= 0) {
System.out.print("Please enter your number: ");
try {
in = input.nextInt();
if(in >= 0) {
list.add(in);
}
}
catch(InputMismatchException exp) {
System.out.println("You entered the wrong type of information.");
input.nextLine();
in = 0;
}
}
ListIterator<Integer> it = list.listIterator();
while(it.hasNext()) {
int i = it.next();
System.out.println(i);
}
/*for(int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}*/
/*Misc m = new Misc();
m.method1();*/
}
}
| true
|
ff91aa185d472183bc996166112cd8045b72a7f3
|
Java
|
bellmit/java-zk-pipeline-spo
|
/spo/spoJdbcDal/src/com/vtb/domain/TaskStatusReturn.java
|
UTF-8
| 1,496
| 2.09375
| 2
|
[] |
no_license
|
package com.vtb.domain;
import java.util.Date;
import ru.masterdm.compendium.domain.crm.StatusReturn;
public class TaskStatusReturn extends VtbObject {
private static final long serialVersionUID = 1L;
private StatusReturn statusReturn;
private String statusReturnText;
private Date dateReturn;
private Long idUser;
public TaskStatusReturn() {
super();
}
public TaskStatusReturn(StatusReturn statusReturn, String statusReturnText) {
super();
this.statusReturn = statusReturn;
this.statusReturnText = statusReturnText;
}
/**
* @return the statusReturn
*/
public StatusReturn getStatusReturn() {
return statusReturn;
}
/**
* @param statusReturn the statusReturn to set
*/
public void setStatusReturn(StatusReturn statusReturn) {
this.statusReturn = statusReturn;
}
/**
* @return the statusReturnText
*/
public String getStatusReturnText() {
return statusReturnText==null?"":statusReturnText;
}
/**
* @param statusReturnText the statusReturnText to set
*/
public void setStatusReturnText(String statusReturnText) {
this.statusReturnText = statusReturnText;
}
/**
* @return the dateReturn
*/
public Date getDateReturn() {
return dateReturn;
}
/**
* @param dateReturn the dateReturn to set
*/
public void setDateReturn(Date dateReturn) {
this.dateReturn = dateReturn;
}
public Long getIdUser() {
return idUser;
}
public void setIdUser(Long idUser) {
this.idUser = idUser;
}
}
| true
|
59a32dc6f816bd01a3b9e7ea7a61f8b4c3e0efbc
|
Java
|
tmntduke/Pattern
|
/src/Proxy/StaticProxy.java
|
UTF-8
| 447
| 2.796875
| 3
|
[] |
no_license
|
package Proxy;
/**
* Created by tmnt on 2017/4/5.
*/
public class StaticProxy implements Star {
private Real real;
public StaticProxy(Real real) {
this.real = real;
}
@Override
public void prepare() {
System.out.println("proxy prepare");
}
@Override
public void sing() {
real.sing();
}
@Override
public void handle() {
System.out.println("proxy handle");
}
}
| true
|
db3855dd7e76e2fd86fc7c15644f7c465ef767d5
|
Java
|
MIMteamQuizMaster/Quizmaster
|
/src/main/java/controller/fx/GradeFX2.java
|
UTF-8
| 3,735
| 2.671875
| 3
|
[] |
no_license
|
package controller.fx;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.scene.control.Label;
import model.Grade;
import java.time.LocalDate;
public class GradeFX2 {
private SimpleIntegerProperty quizId;
private SimpleDoubleProperty grade;
private SimpleIntegerProperty studentId;
private SimpleStringProperty quizName;
private SimpleObjectProperty<LocalDate> date;
private SimpleDoubleProperty succesDefinition;
private SimpleObjectProperty<Label> failesPassedLabel;
private boolean failedPassed;
private Grade gradeObject;
public GradeFX2(Grade gradeObject) {
this.gradeObject = gradeObject;
this.quizId = new SimpleIntegerProperty(this.gradeObject.getQuizId());
this.grade = new SimpleDoubleProperty(this.gradeObject.getGrade());
this.studentId = new SimpleIntegerProperty(this.gradeObject.getStudentId());
this.quizName = new SimpleStringProperty(this.gradeObject.getQuizName());
this.date = new SimpleObjectProperty<LocalDate>(this.gradeObject.getDate());
this.succesDefinition = new SimpleDoubleProperty(this.gradeObject.getSuccesDefinition());
this.failesPassedLabel = new SimpleObjectProperty<Label>(new Label());
this.failedPassed = this.gradeObject.checkIfStudentFailed();
setTextToLabel();
}
public int getQuizId() {
return quizId.get();
}
public SimpleIntegerProperty quizIdProperty() {
return quizId;
}
public void setQuizId(int quizId) {
this.quizId.set(quizId);
}
public double getGrade() {
return grade.get();
}
public SimpleDoubleProperty gradeProperty() {
return grade;
}
public void setGrade(double grade) {
this.grade.set(grade);
}
public int getStudentId() {
return studentId.get();
}
public SimpleIntegerProperty studentIdProperty() {
return studentId;
}
public void setStudentId(int studentId) {
this.studentId.set(studentId);
}
public String getQuizName() {
return quizName.get();
}
public SimpleStringProperty quizNameProperty() {
return quizName;
}
public void setQuizName(String quizName) {
this.quizName.set(quizName);
}
public LocalDate getDate() {
return date.get();
}
public SimpleObjectProperty<LocalDate> dateProperty() {
return date;
}
public void setDate(LocalDate date) {
this.date.set(date);
}
public Grade getGradeObject() {
return gradeObject;
}
public void setGradeObject(Grade gradeObject) {
this.gradeObject = gradeObject;
}
public double getSuccesDefinition() {
return succesDefinition.get();
}
public SimpleDoubleProperty succesDefinitionProperty() {
return succesDefinition;
}
public void setSuccesDefinition(double succesDefinition) {
this.succesDefinition.set(succesDefinition);
}
public Label getFailesPassedLabel() {
return failesPassedLabel.get();
}
public SimpleObjectProperty<Label> failesPassedLabelProperty() {
return failesPassedLabel;
}
public void setFailesPassedLabel(Label failesPassedLabel) {
this.failesPassedLabel.set(failesPassedLabel);
}
public void setTextToLabel()
{
if (failedPassed)
{
getFailesPassedLabel().setText("Niet gehaald");
}
else
{
getFailesPassedLabel().setText("Geslaagd");
}
}
}
| true
|
70881536464f8a102d8302571fa8fc3d43d9fe67
|
Java
|
tianxincc/ecommerce
|
/src/main/java/com/ecommerce/service/PromoService.java
|
UTF-8
| 228
| 1.703125
| 2
|
[] |
no_license
|
package com.ecommerce.service;
import com.ecommerce.service.model.PromoModel;
public interface PromoService {
//根据itemid获取即将进行的和正在进行的活动
PromoModel getPromoByItemId(Integer itemId);
}
| true
|
50863a0eb316748f8c6fb7b3467e3ad4f951f6af
|
Java
|
EAGzzyCSL/Smartable2
|
/app/src/main/java/adapter/Adapter_main_viewPager_kind.java
|
UTF-8
| 3,924
| 2.421875
| 2
|
[] |
no_license
|
package adapter;
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
import bit.eagzzycsl.smartable2.EnumEntry;
import bit.eagzzycsl.smartable2.R;
import decorator.DividerItemDecoration;
import entry.Entry;
import my.MyUtil;
public class Adapter_main_viewPager_kind extends PagerAdapter {
private View[] views;
private String[] pageTitle;
private int[] titleSort;
private Adapter_recyclerView_entry[] adapters = new Adapter_recyclerView_entry[4];
private ArrayList<ArrayList<? extends Entry>> entries;
@Override
public int getCount() {
return views.length;
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
public Adapter_main_viewPager_kind(ArrayList<ArrayList<? extends Entry>> entries, Context context, String[] pageTitle, int titleSort[]) {
//在构造方法里完成recycler的创建
this.entries = entries;
RecyclerView[] pages = new RecyclerView[]{
(RecyclerView) View.inflate(context, R.layout.adapter_main_smart_pager, null),
(RecyclerView) View.inflate(context, R.layout.adapter_main_smart_pager, null),
(RecyclerView) View.inflate(context, R.layout.adapter_main_smart_pager, null),
(RecyclerView) View.inflate(context, R.layout.adapter_main_smart_pager, null),
};
int i = 0;
for (RecyclerView r : pages) {
r.setLayoutManager(new StaggeredGridLayoutManager(1, LinearLayoutManager.VERTICAL));
r.setItemAnimator(new DefaultItemAnimator());
r.addItemDecoration(new DividerItemDecoration(context));
adapters[i] = new Adapter_recyclerView_entry(entries.get(titleSort[i]), context);
r.setAdapter(adapters[i++]);
}
this.views = pages;
this.pageTitle = pageTitle;
this.titleSort = titleSort;
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
View v = views[position];
container.addView(v);
return v;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
View v = views[position];
container.removeView(v);
}
@Override
public CharSequence getPageTitle(int position) {
return pageTitle[titleSort[position]];
}
private int getTypeId(Entry entry) {
return MyUtil.indexOf(EnumEntry.fourEnumEntries, entry.getType());
}
@SuppressWarnings("unchecked")
public void insertEntry(Entry entry) {
//首先要找到对应的适配器和数据组
int typeId = getTypeId(entry);
((ArrayList<Entry>) entries.get(typeId)).add(entry);
adapters[typeId].notifyItemInserted(entries.get(typeId).size());
}
@SuppressWarnings("unchecked")
public void updateEntry(Entry entry) {
int typeId = getTypeId(entry);
int i = getIndexInEntries(typeId, entry);
((ArrayList<Entry>) entries.get(typeId)).set(i, entry);
adapters[typeId].notifyItemChanged(i);
}
public void deleteEntry(Entry entry) {
int typeId = getTypeId(entry);
int i = getIndexInEntries(typeId, entry);
entries.get(typeId).remove(i);
adapters[typeId].notifyItemRemoved(i);
}
private int getIndexInEntries(int typeId, Entry entry) {
for (int i = 0; i < entries.size(); i++) {
if (entries.get(typeId).get(i).getId() == entry.getId()) {
return i;
}
}
return -1;
}
}
| true
|
0a8c8fc00766086704be8bbf4118bac7a7295ace
|
Java
|
mlwmlw/jetris
|
/place.java
|
UTF-8
| 2,365
| 2.921875
| 3
|
[] |
no_license
|
public class place
{
boolean place[][]=new boolean[12][19];//場地
Player player;//方塊消掉時呼叫小朋友
place()
{
for(int i=0;i<12;i++)
{
for(int j=0;j<19;j++)
{
if(i==0 ||i==11)
place[i][j]=true;
else
{
if(j==18)
place[i][j]=true;
}
}
}
}
public void setPlayer(Player p)
{
player=p;
}
public void show()
{
int i,j;
for(i=0;i<19;i++)
{
for(j=0;j<12;j++)
{
if(place[j][i])
System.out.print("■");
else
System.out.print("□");
}
System.out.println("");
}
}
public boolean getPlace(int x,int y)//多載get point
{
return place[x][y];
}
public boolean[][] getPlace()//多載get全部
{
return place;
}
public void setPlace(int x,int y)
{
place[x][y]=true;
}
public void setYGround(int y)
{
for(int i=1;i<11;i++)
{
place[i][y]=true;
}
}
public void clearYGround(int y)
{
for(int i=1;i<11;i++)
{
place[i][y]=false;
}
}
public int addCube(cube c)
{
for(int i=0;i<4;i++)
{
//System.out.println("新放置場地"+(c.getCubeSpace()[i][0]+c.getCenter()[0])+" "+(c.getCubeSpace()[i][1]+c.getCenter()[1]));
setPlace(c.getCubeSpace()[i][0]+c.getCenter()[0],c.getCubeSpace()[i][1]+c.getCenter()[1]);
}
return checkPlace();
}
public int checkPlace()//確認場地是否有該消除之行數
{
int i,j,k;
int line=0;
for(i=0,k=0;i<18;i++)
{
k=0;
for(j=1;j<11;j++)
{
if(place[j][i])
k++;
}
if(k==10)
{
line++;
// show();
drop(i);
if(!player.isjump&&!player.ifIsfloor(getPlace(),0,1))//沒有在跳 而且往下移不是地板
player.haveGravity(getPlace());
//show();
}
}
return line;
}
public void drop(int x)//消除方塊與將之上方塊下降
{
int level=-1;
clearYGround(x);
for(int i=0;i<18;i++)
{
for(int j=1;j<11;j++)
{
if(place[j][i])//算出最高層
{
level=i;
break;
}
}
if(level!=-1)
{
break;
}
}
for(int i=x-1;i>=level-1;i--)
{
for(int j=1;j<11;j++)
{
place[j][i+1]=false;
if(i!=level-1)
{
place[j][i+1]=place[j][i];
}
else
place[j][i]=false;
}
}
}
}
| true
|
dbcc158f9aead89f371d6dbe5688c751e9e653d6
|
Java
|
anPerez4120/MetalCrawler
|
/app/src/main/java/csc472/depaul/edu/metalcrawler/GameComponents/CellularAutomata/Room.java
|
UTF-8
| 2,310
| 2.953125
| 3
|
[] |
no_license
|
package csc472.depaul.edu.metalcrawler.GameComponents.CellularAutomata;
import android.support.annotation.NonNull;
import java.util.ArrayList;
import java.util.List;
public class Room implements Comparable<Room>
{
public List<Coord> tiles; // get pr set
public List<Coord> edgeTiles;
public List<Room> connectedRooms;
public int roomSize;
public boolean isConnectedToMainRoom ;
public boolean isMainRoom ;
public Room() { }
public Room(List<Coord> roomTiles, Tile[][] map)
{
tiles = roomTiles;
roomSize = tiles.size();
connectedRooms = new ArrayList<Room>();
edgeTiles = new ArrayList<Coord>();
for (Coord tile : tiles)
{
for (int x = tile.x - 1; x <= tile.x + 1; x++)
{
for (int y = tile.y - 1; y <= tile.y + 1; y++)
{
if (x == tile.x || y == tile.y)
{
if (map[x][y].GetBlockType() != TileBlockType.EMPTY)
{
edgeTiles.add(tile);
}
}
}
}
}
}
public static void ConnectRooms(Room roomA, Room roomB)
{
if (roomA.isConnectedToMainRoom)
{
roomB.MakeConnectedToMainRoom();
}
else if (roomB.isConnectedToMainRoom)
{
roomA.MakeConnectedToMainRoom();
}
roomA.connectedRooms.add(roomB);
roomB.connectedRooms.add(roomA);
}
public boolean IsConnected(Room otherRoom)
{
return connectedRooms.contains(otherRoom);
}
public int CompareTo(Room otherRoom)
{
return Integer.compare(otherRoom.roomSize,roomSize);
}
public void MakeMainRoom()
{
isMainRoom = true;
isConnectedToMainRoom = true;
}
public void MakeConnectedToMainRoom()
{
if (!isConnectedToMainRoom)
{
isConnectedToMainRoom = true;
for (Room connectedRoom : connectedRooms)
{
connectedRoom.MakeConnectedToMainRoom();
}
}
}
@Override
public int compareTo(@NonNull Room o) {
return Integer.compare(o.roomSize,roomSize);
}
}
| true
|
6190d33552726a2a7beda275e6f138dfa30d6ccf
|
Java
|
jcarreracpp/CS245Program1
|
/BSet.java
|
UTF-8
| 1,543
| 2.546875
| 3
|
[] |
no_license
|
package cs245guiproject1;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import javax.swing.*;
public class BSet extends JButton{
public BSet(){}
public JButton back(){
JButton temp = new JButton();
temp.setText("Back");
temp.setActionCommand("MM");
temp.setFont(new Font("Papyrus", Font.BOLD, 12));
temp.setBackground(Color.WHITE);
return temp;
}
public JButton Score(){
JButton temp = new JButton();
temp.setText("Highscores");
temp.setActionCommand("Scores");
temp.setFont(new Font("Comic Sans", Font.BOLD, 12));
temp.setForeground(Color.WHITE);
temp.setBackground(Color.BLUE);
temp.setPreferredSize(new Dimension(100,50));
return temp;
}
public JButton Cred(){
JButton temp = new JButton();
temp.setText("Credits");
temp.setActionCommand("Cred");
temp.setFont(new Font("Comic Sans", Font.BOLD, 12));
temp.setForeground(Color.WHITE);
temp.setBackground(Color.BLUE);
temp.setPreferredSize(new Dimension(100,50));
return temp;
}
public JButton Play(){
JButton temp = new JButton();
temp.setText("Play");
temp.setActionCommand("Play");
temp.setFont(new Font("Comic Sans", Font.BOLD, 12));
temp.setForeground(Color.WHITE);
temp.setBackground(Color.BLUE);
temp.setPreferredSize(new Dimension(100,50));
return temp;
}
}
| true
|
12156b657917dbbe7eaa24af422c72127253e51d
|
Java
|
wajda/web-harvest
|
/webharvest-core/src/main/java/org/webharvest/runtime/processors/XsltProcessor.java
|
UTF-8
| 4,366
| 1.710938
| 2
|
[
"BSD-2-Clause"
] |
permissive
|
/* Copyright (c) 2006-2007, Vladimir Nikic
All rights reserved.
Redistribution and use of this software in source and binary forms,
with or without modification, are permitted provided that the following
conditions are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other
materials provided with the distribution.
* The name of Web-Harvest may not be used to endorse or promote
products derived from this software without specific prior
written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
You can contact Vladimir Nikic by sending e-mail to
nikic_vladimir@yahoo.com. Please include the word "Web-Harvest" in the
subject line.
*/
package org.webharvest.runtime.processors;
import static org.webharvest.WHConstants.XMLNS_CORE;
import static org.webharvest.WHConstants.XMLNS_CORE_10;
import java.io.StringReader;
import java.io.StringWriter;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.webharvest.annotation.Definition;
import org.webharvest.definition.IElementDef;
import org.webharvest.definition.XsltDef;
import org.webharvest.exception.XsltException;
import org.webharvest.runtime.DynamicScopeContext;
import org.webharvest.runtime.processors.plugins.Autoscanned;
import org.webharvest.runtime.processors.plugins.TargetNamespace;
import org.webharvest.runtime.variables.NodeVariable;
import org.webharvest.runtime.variables.Variable;
/**
* XSLT processor.
*/
//TODO Add unit test
//TODO Add javadoc
@Autoscanned
@TargetNamespace({ XMLNS_CORE, XMLNS_CORE_10 })
@Definition(value = "xslt", validAttributes = "id",
validSubprocessors = {"xml", "stylesheet"},
requiredSubprocessors = { "xml", "stylesheet" },
definitionClass = XsltDef.class)
public class XsltProcessor extends AbstractProcessor<XsltDef> {
public Variable execute(DynamicScopeContext context) throws InterruptedException {
final IElementDef xsltElementDef = elementDef.getXmlDef();
Variable xmlStr = getBodyTextContent(xsltElementDef, context, true);
debug(xsltElementDef, context, xmlStr);
IElementDef stylesheetElementDef = elementDef.getStylesheetDef();
Variable stylesheetStr = getBodyTextContent(stylesheetElementDef, context, true);
debug(stylesheetElementDef, context, stylesheetStr);
try {
TransformerFactory xformFactory = TransformerFactory.newInstance();
Source xsl = new StreamSource(new StringReader(stylesheetStr.toString()));
Transformer stylesheet = xformFactory.newTransformer(xsl);
Source request = new StreamSource(new StringReader(xmlStr.toString()));
StringWriter writer = new StringWriter();
Result response = new StreamResult(writer);
stylesheet.transform(request, response);
return new NodeVariable(writer.toString());
} catch (TransformerException e) {
throw new XsltException("Error during XSLT transforming!", e);
}
}
}
| true
|
8f0bc0de029dbffd289c6db1d5baa709c2f095bf
|
Java
|
Bleink/hgsm
|
/hotelguestmanagementsystem/src/main/java/edu/miu/cs/cs425/seniorproject/hotelguestmanagementsystem/config/WebSecurityConfig.java
|
UTF-8
| 3,491
| 2.140625
| 2
|
[] |
no_license
|
package edu.miu.cs.cs425.seniorproject.hotelguestmanagementsystem.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true, proxyTargetClass = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userService;
@Autowired
private LoggingAccessDeniedHandler accessDeniedHandler;
@Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public DaoAuthenticationProvider authenticationProvider(){
DaoAuthenticationProvider auth = new DaoAuthenticationProvider();
auth.setUserDetailsService(userService);
auth.setPasswordEncoder(passwordEncoder());
return auth;
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.
authenticationProvider(authenticationProvider());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.headers()
.frameOptions().sameOrigin()
.and()
.authorizeRequests()
.antMatchers("/resources/static/**", "/img/**", "/css/**","/Other/**","/login","/signup","/home").permitAll()
.antMatchers("/init").permitAll()
.antMatchers("/admin/**","/roomType","/roomType/**").hasAuthority("ADMIN")
.antMatchers("/reception/**").hasAuthority("RECEPTION")
.antMatchers("/guest/**").hasAuthority("GUEST")
.antMatchers("/**/reservation/**","/checkRooms").hasAnyAuthority("GUEST","RECEPTION")
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.successHandler(myAuthenticationSuccessHandler())
.failureUrl("/login?error")
.permitAll()
.and()
.logout()
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/login?logout")
.permitAll()
.and()
.exceptionHandling().accessDeniedHandler(accessDeniedHandler);
}
@Bean
public AuthenticationSuccessHandler myAuthenticationSuccessHandler(){
return new MySimpleUrlAuthenticationSuccessHandler();
}
}
| true
|
41d83872e03c7adc7f144a0bcafbf74fe68b25c8
|
Java
|
MeesterVers/GroepProject4-SIE-V1D
|
/src/model/presentie/Presentie.java
|
UTF-8
| 580
| 2.890625
| 3
|
[] |
no_license
|
package model.presentie;
import model.persoon.Student;
public class Presentie {
private Student student;
private String status;
public Presentie(Student student, String status) {
this.student = student;
this.status = status;
}
public Student getStudent() {
return student;
}
public String getStatus() {
return status;
}
@Override
public String toString() {
return "Presentie{" +
"student=" + student +
", status='" + status + '\'' +
'}';
}
}
| true
|
f07270a0df0a8473d286122f7cb558044c8c80e1
|
Java
|
suyash-capiot/bookingEngine
|
/src/main/java/com/coxandkings/travel/bookingengine/orchestrator/holidays/HolidaysSearchAsyncProcessor.java
|
UTF-8
| 8,358
| 1.976563
| 2
|
[] |
no_license
|
package com.coxandkings.travel.bookingengine.orchestrator.holidays;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONObject;
import org.w3c.dom.Element;
import com.coxandkings.travel.bookingengine.config.ServiceConfig;
import com.coxandkings.travel.bookingengine.config.ThreadPoolConfig;
import com.coxandkings.travel.bookingengine.config.air.AirConfig;
import com.coxandkings.travel.bookingengine.config.holidays.HolidaysConfig;
import com.coxandkings.travel.bookingengine.enums.ToDoTaskName;
import com.coxandkings.travel.bookingengine.enums.ToDoTaskPriority;
import com.coxandkings.travel.bookingengine.enums.ToDoTaskSubType;
import com.coxandkings.travel.bookingengine.exception.InternalProcessingException;
import com.coxandkings.travel.bookingengine.exception.RequestProcessingException;
import com.coxandkings.travel.bookingengine.exception.ValidationException;
import com.coxandkings.travel.bookingengine.userctx.ProductSupplier;
import com.coxandkings.travel.bookingengine.userctx.UserContext;
import com.coxandkings.travel.bookingengine.utils.TrackingContext;
import com.coxandkings.travel.bookingengine.utils.Utils;
import com.coxandkings.travel.bookingengine.orchestrator.holidays.SupplierSearchProcessor;
import com.coxandkings.travel.bookingengine.orchestrator.operations.OperationsToDoProcessor;
public class HolidaysSearchAsyncProcessor implements HolidayConstants{
private static final Logger logger = LogManager.getLogger(HolidaysSearchAsyncProcessor.class);
private JSONObject mReqJson;
private static JSONObject EMPTY_RESJSON = new JSONObject(String.format("{\"%s\": {\"%s\": []}}", JSON_PROP_RESBODY, JSON_PROP_DYNAMICPACKAGE));
public HolidaysSearchAsyncProcessor(JSONObject reqJson) {
mReqJson = reqJson;
}
public static String process(JSONObject requestJSON) throws InternalProcessingException, RequestProcessingException, ValidationException {
Element requestElement = null;
JSONObject requestHeaderJSON = null, requestBodyJSON = null;
//OperationConfig opConfig = null;
ServiceConfig opConfig = null;
UserContext usrCtx = null;
try {
TrackingContext.setTrackingContext(requestJSON);
// have to check why this statement is failing for holidays
//opConfig = HolidaysConfig.getOperationConfig(TrackingContext.getTrackingContext().getTrackingParameter(ServletContext.RESTPROP_OPERATION));
opConfig = HolidaysConfig.getOperationConfig("search");
requestHeaderJSON = requestJSON.getJSONObject(JSON_PROP_REQHEADER);
requestBodyJSON = requestJSON.getJSONObject(JSON_PROP_REQBODY);
//X----------------------------------------DELETE--------------------------------------------------X
//TEMP FIX FOR HOLIDAYS OFFERS
//HOLIDAY OFFERS NEEDS GIVING ERROR WITHOUT BRANDNAME
JSONArray dynamicPackageArraytest = requestBodyJSON.getJSONArray(JSON_PROP_DYNAMICPACKAGE);
for(int i=0;i<dynamicPackageArraytest.length();i++)
{
JSONObject dynamicPackageObj = dynamicPackageArraytest.getJSONObject(i);
dynamicPackageObj.put("brandName", "");
}
//X----------------------------------------DELETE--------------------------------------------------X
HolidaysSearchProcessor.validateRequestParameters(requestJSON);
//usrCtx = UserContext.getUserContextForSession(requestHeaderJSON);
// requestElement = HolidaysSearchProcessor.createSIRequest(opConfig, usrCtx, requestHeaderJSON, requestBodyJSON);
}
catch (ValidationException valx) {
throw valx;
}
catch (Exception x) {
logger.error("Exception during request processing", x);
throw new RequestProcessingException(x);
}
try {
usrCtx = UserContext.getUserContextForSession(requestHeaderJSON);
JSONArray dynamicPackageArray = requestBodyJSON.getJSONArray(JSON_PROP_DYNAMICPACKAGE);
//Get List of all the Product Suppliers supported for that client
List<ProductSupplier> productSuppliersList = new ArrayList<ProductSupplier>();
List<JSONObject> NewRequestDynamicPkgList = new ArrayList<JSONObject>();
List<ProductSupplier> prodSuppliers = usrCtx.getSuppliersForProduct(PROD_CATEG_HOLIDAYS,PROD_CATEG_HOLIDAYS);
if(prodSuppliers==null || prodSuppliers.size()==0)
OperationsToDoProcessor.callOperationTodo(ToDoTaskName.SEARCH, ToDoTaskPriority.HIGH, ToDoTaskSubType.ORDER, "", "", requestHeaderJSON,"Product supplier not found for Holidays");
if (prodSuppliers == null) {
logger.warn("Product supplier not found for user/client for subtype ".concat(PROD_CATEG_HOLIDAYS));
}
//----------------INITIALIZE LISTENER WITH DEFAULT REQUEST-------------------
if(prodSuppliers!=null) {
//removing redundent suppliers for that client
for(int i=0;i<dynamicPackageArray.length();i++)
{
JSONObject dynamicPackageObj = dynamicPackageArray.getJSONObject(i);
String supplierID = dynamicPackageObj.getString(JSON_PROP_SUPPID);
for(ProductSupplier productSupplier : prodSuppliers) {
if(productSupplier.getSupplierID().equals(supplierID))
{
productSuppliersList.add(productSupplier);
NewRequestDynamicPkgList.add(getSingleRequest(requestJSON, dynamicPackageObj));
}
}
}
int check =0;
HolidaysSearchListnerResponder searchListener = new HolidaysSearchListnerResponder(productSuppliersList, requestJSON);
//---------------CALL SI PER SUPPLIER PER DYNAMIC PACKAGE OBJECT-------------
for(int i=0;i<productSuppliersList.size();i++)
{
requestElement = HolidaysSearchProcessor.createSIRequest(opConfig, usrCtx, requestHeaderJSON, NewRequestDynamicPkgList.get(i).getJSONObject(JSON_PROP_REQBODY));
SupplierSearchProcessor supplierSearchProcessor = new SupplierSearchProcessor(searchListener, productSuppliersList.get(i) , NewRequestDynamicPkgList.get(i), requestElement);
ThreadPoolConfig.execute(supplierSearchProcessor);
check = 1;
}
if(check==0) {
throw new Exception("Product suppliers not found for user/client ");
}
if (Utils.isSynchronousSearchRequest(requestJSON)) {
// This is a synchronous search request
// Wait for all supplier threads to finish or till configured timeout
synchronized(searchListener) {
searchListener.wait(AirConfig.getAsyncSearchWaitMillis());
}
JSONObject resJson = searchListener.getSearchResponse();
return resJson.toString();
}
}
else {
JSONObject resJson=new JSONObject();
resJson.put(JSON_PROP_RESHEADER, requestHeaderJSON);
resJson.put(JSON_PROP_RESBODY, EMPTY_RESJSON.getJSONObject(JSON_PROP_RESBODY));
return resJson.toString();
}
}
catch (Exception x) {
logger.error("Exception received while processing", x);
throw new InternalProcessingException(x);
}
// Code will reach here only in case of asynchronous search.
// It does not matter what is returned here for asynchronous search.
return null;
}
private static JSONObject getSingleRequest(JSONObject requestJSON,JSONObject dynamicPackageObj) {
JSONObject newRequestJSON = new JSONObject();
JSONObject newRequestBody = new JSONObject();
newRequestBody.put(JSON_PROP_TOURCODE, dynamicPackageObj.getString(JSON_PROP_TOURCODE));
newRequestBody.put(JSON_PROP_SUBTOURCODE, dynamicPackageObj.optString(JSON_PROP_SUBTOURCODE));
newRequestBody.put(JSON_PROP_SUPPID, dynamicPackageObj.getString(JSON_PROP_SUPPID));
newRequestBody.put(JSON_PROP_BRANDNAME, "");
newRequestJSON.put(JSON_PROP_REQBODY, newRequestBody);
newRequestJSON.put(JSON_PROP_REQHEADER, requestJSON.getJSONObject(JSON_PROP_REQHEADER));
return newRequestJSON;
}
}
| true
|
ea157b4f61b64bbbba8744e5a6e97e31e3ac616f
|
Java
|
MetallFoX/Evolution
|
/src/main/java/ru/cardgame/GameDiscardPile.java
|
ISO-8859-6
| 1,001
| 3.03125
| 3
|
[] |
no_license
|
package ru.cardgame;
import java.util.ArrayList;
import java.util.Collection;
/**
* .
* <p/>
* Created by MetallFoX on 21.11.2015.
*/
public class GameDiscardPile implements DiscardPile {
private int size;
private Collection<Card> cards;
public GameDiscardPile() {
cards = new ArrayList<>();
}
public Collection<Card> getCards() {
return cards;
}
public void discard(Card card) {
cards.add(card);
size++;
}
public void discard(Collection<Card> cards) {
if (cards.isEmpty()) {
throw new AttemptDiscardZeroCardsException();
}
this.cards.addAll(cards);
size += cards.size();
}
public boolean contains(Card card) {
return cards.contains(card);
}
public int getSize() {
return size;
}
public boolean isEmpty() {
return size == 0;
}
public class AttemptDiscardZeroCardsException extends RuntimeException {
}
}
| true
|
293008ed061f5863338f19e0cf29209e54f47dc9
|
Java
|
yishuai10/JavaDesignPatterns
|
/Chapter09_Abstract Factory/after/EmployeeDAO.java
|
UTF-8
| 968
| 2.625
| 3
|
[] |
no_license
|
package AbstractFactory.after;
import AbstractFactory.after.IDBCommand;
import AbstractFactory.after.IDBConnection;
import AbstractFactory.after.IDataReader;
import AbstractFactory.after.*;
import AbstractFactory.others.EmployeeDO;
import java.util.ArrayList;
import java.util.List;
/**
* 下面是最终的设计方案,把同类型的数据库处理操作绑定在同一个工厂对象下面
*/
public class EmployeeDAO {
IDBFactory idbFactory; //具体类型由上层传入
public EmployeeDAO(IDBFactory idbFactory) {
this.idbFactory = idbFactory;
}
public List<EmployeeDO> getEmployees(){
List<EmployeeDO> list = new ArrayList<>();
//数据库连接操作
IDBConnection connection = idbFactory.createDBConnection();
IDBCommand command = idbFactory.createDBCommand();
IDataReader reader = idbFactory.createDBDataReader();
// 数据操作
// ...
return list;
}
}
| true
|
69590bc7a5976c4e722150a1bfee19228b5f8697
|
Java
|
mgijax/fedatamodel
|
/src/mgi/frontend/datamodel/ProbeCloneCollection.java
|
UTF-8
| 1,004
| 2.546875
| 3
|
[] |
no_license
|
package mgi.frontend.datamodel;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* ProbeCloneCollection
* @author mhall
* Returns a collection of probes and clones.
*/
@Entity
@Table (name="probe_clone_collection")
public class ProbeCloneCollection {
private String collection;
private int probeKey;
private int uniqueKey;
// ================= Getters and Setters ===================== //
public String getCollection() {
return collection;
}
@Column(name="probe_key")
public int getProbeKey() {
return probeKey;
}
@Id
@Column(name="unique_key")
public int getUniqueKey() {
return uniqueKey;
}
public void setCollection(String collection) {
this.collection = collection;
}
public void setProbeKey(int probeKey) {
this.probeKey = probeKey;
}
public void setUniqueKey(int uniqueKey) {
this.uniqueKey = uniqueKey;
}
}
| true
|
dc16bc5c4d3fdd47ded55e81ac76cbdd81c41b30
|
Java
|
crom52/all4pet
|
/src/main/java/com/springboot/ServiceController/ViewController.java
|
UTF-8
| 1,632
| 2.375
| 2
|
[] |
no_license
|
package com.springboot.ServiceController;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import com.springboot.Entity.Person;
import com.springboot.mapper.PersonMapper;
@Controller
public class ViewController {
@Autowired PersonMapper personMapper;
@RequestMapping(value = { "/index" , ""})
public String welcomeView(Model model) {
Person person = new Person();
model.addAttribute("loginUser", person);
return "index";
}
@RequestMapping(value = { "/personList" })
public String personListView() {
return "personList";
}
@RequestMapping(value = { "/home" })
public String homePage() {
return "home";
}
@RequestMapping(value = { "/registrationForm" })
public String registerView() {
return "registrationForm";
}
// @PostMapping("/loginSubmit")
// public String login(@ModelAttribute("loginUser") Person person ) {
// String userName = person.getuserName();
// String password = person.getPassword();
// List<Person> personList = personMapper.selectAllPerson();
// for (int i = 0; i<personList.size() ; i++)
// if (personList.get(i).getuserName().equals(userName)
// && personList.get(i).getPassword().equals(password)) {
// return "redirect:personList";
// }
// return "redirect:index";
// }
}
| true
|
721ea177cb976e500201782df7e5aecfc8c5d2aa
|
Java
|
buitoan89/codegym_Buivantoan
|
/chuyendoitiente/src/controllers/ChuyenDoiTien.java
|
UTF-8
| 306
| 1.8125
| 2
|
[] |
no_license
|
package controllers;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class ChuyenDoiTien {
@GetMapping("/chuyentien")
public String showform(){
System.out.println("AAA");
return "chuyentien";
}
}
| true
|
83c56f9dffd0d4b74025fdfcfae93d6f9c473b4a
|
Java
|
rcoolboy/guilvN
|
/app/src/main/java/com/p118pd/sdk/O0O0O00.java
|
UTF-8
| 765
| 1.835938
| 2
|
[] |
no_license
|
package com.p118pd.sdk;
import org.jetbrains.annotations.NotNull;
/* renamed from: com.pd.sdk.O0O0O00 */
public final class O0O0O00 extends O0OO0<double[]> {
public final double[] OooO00o;
public O0O0O00(int i) {
super(i);
this.OooO00o = new double[i];
}
public int OooO00o(@NotNull double[] dArr) {
o0O0OO00.OooO0o(dArr, "receiver$0");
return dArr.length;
}
public final void OooO00o(double d) {
double[] dArr = this.OooO00o;
int OooO00o2 = OooO00o();
OooO00o(OooO00o2 + 1);
dArr[OooO00o2] = d;
}
@Override // com.p118pd.sdk.O0OO0
@NotNull
public final double[] OooO00o() {
return (double[]) OooO00o(this.OooO00o, new double[OooO0O0()]);
}
}
| true
|
13ed8191db2ae44e1648849ba5095224f37b98be
|
Java
|
Chicachu/Word-Frequency
|
/src/HashTable.java
|
UTF-8
| 4,236
| 3.328125
| 3
|
[] |
no_license
|
public class HashTable {
private Cell[] my_table;
private int TABLE_SIZE = 9973;
private int[] polyIndex;
private int cells_used = 0;
public HashTable() {
my_table = new Cell[TABLE_SIZE];
initializePolynomialIndex();
}
/**
* Uses hashing function 1.
* @param the_word The word to be added.
* @param hashNum Hash function to use (1-5).
*/
public void addWord1(final String the_word) {
Cell list;
int index = hash1(the_word);
Word word = new Word(the_word);
// create a new cell of words if array at index is null
if (my_table[index] == null) {
list = new Cell(word);
my_table[index] = list;
cells_used++;
} else {
// otherwise, add to cell
list = my_table[index];
list.addWord(word);
my_table[index] = list;
}
}
public void addWord2(final String the_word) {
Cell list;
int index = hash2(the_word);
Word word = new Word(the_word);
// create a new cell of words if array at index is null
if (my_table[index] == null) {
list = new Cell(word);
my_table[index] = list;
cells_used++;
} else {
// otherwise, add to cell
list = my_table[index];
list.addWord(word);
my_table[index] = list;
}
}
public void addWord3(final String the_word) {
Cell list;
int index = hash3(the_word);
Word word = new Word(the_word);
// create a new cell of words if array at index is null
if (my_table[index] == null) {
list = new Cell(word);
my_table[index] = list;
cells_used++;
} else {
// otherwise, add to cell
list = my_table[index];
list.addWord(word);
my_table[index] = list;
}
}
public void addWord4(final String the_word) {
Cell list;
int index = hash4(the_word);
Word word = new Word(the_word);
// create a new cell of words if array at index is null
if (my_table[index] == null) {
list = new Cell(word);
my_table[index] = list;
cells_used++;
} else {
// otherwise, add to cell
list = my_table[index];
list.addWord(word);
my_table[index] = list;
}
}
public void addWord5(final String the_word) {
Cell list;
int index = hash5(the_word);
Word word = new Word(the_word);
// create a new cell of words if array at index is null
if (my_table[index] == null) {
list = new Cell(word);
my_table[index] = list;
cells_used++;
} else {
// otherwise, add to cell
list = my_table[index];
list.addWord(word);
my_table[index] = list;
}
}
public int getCellCount() {
return cells_used;
}
public int getTableSize() {
return TABLE_SIZE;
}
/**
* 5 hashing functions in a switch statement, choose one by enter 1-5 as second param.
* @param key The key.
* @param hashNumber The hashing function to use (1-5).
* @return The hashcode.
*/
public int hash1(final String key) {
int indexOfKey = 1;
double hashInd = 0.0, sum = 0.0;
for (int j = 0; j < key.length(); j++) {
sum += (int)key.charAt(j);
hashInd += (double)((int)key.charAt(j)) * polyIndex[j];
}
indexOfKey = ((int) ((int)hashInd % sum) * key.length()) % TABLE_SIZE;
return indexOfKey;
}
public int hash2(final String key) {
int index = 1;
int sum = key.hashCode();
if (sum < 0) {
sum = 0 - sum;
}
for (int i = 0; i < 5; i++) {
sum += sum;
index += sum * polyIndex[i] + sum;
}
if (index < 0) {
index = 0 - index;
}
return index % TABLE_SIZE;
}
public int hash3(final String key) {
int index2 = key.hashCode() * key.hashCode();
for (int i = 0; i < key.length(); i++) {
index2 *= polyIndex[i];
}
if (index2 < 0) {
index2 = 0 - index2;
}
return index2 % TABLE_SIZE;
}
public int hash4(final String key) {
int ind = key.hashCode() * key.hashCode();
for (int i = 0; i < key.length(); i++) {
// subtle difference between this one and the one above.
ind += polyIndex[i];
}
if (ind < 0) {
ind = 0 - ind;
}
return ind % TABLE_SIZE;
}
public int hash5(final String key) {
int keyCode = key.hashCode();
keyCode *= keyCode + keyCode;
if (keyCode < 0) {
keyCode = 0 - keyCode;
}
return keyCode % TABLE_SIZE;
}
private void initializePolynomialIndex() {
polyIndex = new int[40];
for (int i = 0; i < 40; i++) {
polyIndex[i] = (int)Math.pow(11, i);
}
}
}
| true
|
0d7fdff74079fd741527ee86a510d604c566608d
|
Java
|
kzubrinic/futura-radionice-java
|
/FuturaRadioniceJava/src/r05/rjesenja_zadataka/Zadatak3.java
|
WINDOWS-1250
| 2,623
| 3.46875
| 3
|
[] |
no_license
|
package r05.rjesenja_zadataka;
import java.io.BufferedReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.Scanner;
/**
* @author Krunoslav ubrini
* 21. tra 2015.
*/
public class Zadatak3 {
private BufferedReader in;
private PrintWriter pw;
public void obrada() throws IOException {
String stranica = "http://www.zaba.hr/home/ZabaUtilsWeb/utils/tecaj/prn/danas";
String nazivDat = "srednji.txt";
Scanner s1 = new Scanner(System.in);
System.out.print("Unesite oznaku valute: ");
String v = s1.nextLine();
// Podaci potrebni za povezivanje s URL adresom
URL o = new URL(stranica);
// Povezujemo se sa stranicom
URLConnection yc = o.openConnection();
// Stvara se bufferirani tok podataka s web adrese na koju smo spojeni
in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
// objekt za spremanje teksta na disk
pw = new PrintWriter(new FileWriter(nazivDat));
String inputLine, oznaka="";
float sr=0f;
while ((inputLine = in.readLine()) != null){
// ita redak po redak
Scanner s2 = new Scanner(inputLine);
while (s2.hasNext()) {
// prvi token je ifra - ona nas ne zanima pa ju preskaemo
preskoci(s2);
// sljedei je oznaka - ona nas zanima pa ju itamo u varijablu
if (s2.hasNext())
oznaka = s2.next();
// trei je jedinica - preskaemo, isto kao i etvrti i peti
for (int i = 0; i<3; i++)
preskoci(s2);
// esti je srednji teaj i njega itamo
// Moramo pretvarati posredno: String->Float->float jer je u
// datoteci decimalna toka, alokalne postavke su kod nas hrvatske (zarez)
if (s2.hasNext())
sr = Float.parseFloat(s2.next().toString());
// sedmi i osmi preskaemo
for (int i = 0; i < 2; i++)
preskoci(s2);
}
s2.close();
if (oznaka.equals(v)){
// ispii na ekran
String st = String.format("%s:%.6f", oznaka,sr);
System.out.println("Pronaeno: " + st);
// i zapii u datoteku
pw.println(st);
break;
}
}
s1.close();
}
private void preskoci(Scanner s){
if (s.hasNext())
s.next();
}
public static void main(String[] args){
Zadatak3 z = new Zadatak3();
try {
z.obrada();
} catch(IOException e){
System.out.println(e.getMessage());
e.printStackTrace();
}
finally{
try {
if (z.in != null)
z.in.close();
if (z.pw != null)
z.pw.close();
} catch (IOException e1){
System.out.println(e1.getMessage());
e1.printStackTrace();
}
}
}
}
| true
|
503ebfa574ea3511d66c2a02a9c7e05213ee604b
|
Java
|
treenewbi/groot
|
/groot/src/main/java/com/huangwu/designmode/behavior/AttackA.java
|
UTF-8
| 317
| 2.484375
| 2
|
[] |
no_license
|
package com.huangwu.designmode.behavior;
/**
* @Package: com.huangwu.designmode.behavior
* @Author: huangwu
* @Date: 2018/7/11 22:03
* @Description:
* @LastModify:
*/
public class AttackA implements IAttackBehavior {
@Override
public void attack() {
System.out.println("远程攻击");
}
}
| true
|
698080e36a15f42e2fff8dca5213334d78d9997b
|
Java
|
erickrocha/com.rochatec.athena
|
/core/business/src/main/java/com/rochatec/athena/facade/impl/SupplyFacadeImpl.java
|
UTF-8
| 2,964
| 2.15625
| 2
|
[] |
no_license
|
package com.rochatec.athena.facade.impl;
import java.util.Calendar;
import java.util.List;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import com.rochatec.athena.eao.local.ShipperEaoLocal;
import com.rochatec.athena.eao.local.SupplierEaoLocal;
import com.rochatec.athena.facade.local.SupplyFacadeLocal;
import com.rochatec.athena.facade.remote.SupplyFacadeRemote;
import com.rochatec.athena.model.Shipper;
import com.rochatec.athena.model.Status;
import com.rochatec.athena.model.Supplier;
@Stateless
public class SupplyFacadeImpl implements SupplyFacadeLocal,SupplyFacadeRemote {
@EJB
private SupplierEaoLocal supplierEaoLocal;
@EJB
private ShipperEaoLocal shipperEaoLocal;
public Supplier persist(Supplier supplier) {
supplier = supplierEaoLocal.persist(supplier);
return supplier;
}
public void remove(Supplier supplier) {
supplierEaoLocal.remove(supplier);
}
public Supplier findSupplierById(Long id) {
Supplier supplier = supplierEaoLocal.findById(id);
return supplier;
}
public Supplier findSupplierBySocialSecurity(String socialSecurity) {
Supplier supplier = supplierEaoLocal.findBySocialSecurity(socialSecurity);
return supplier;
}
public Supplier findSupplierByIndex(Long id, String socialSecurity) {
Supplier supplier = supplierEaoLocal.findByIndex(id,socialSecurity);
return supplier;
}
public Shipper persist(Shipper shipper) {
shipper = shipperEaoLocal.persist(shipper);
return shipper;
}
public void remove(Shipper shipper) {
shipperEaoLocal.remove(shipper);
}
public Shipper findShipperById(Long id) {
Shipper shipper = shipperEaoLocal.findById(id);
return shipper;
}
public List<Shipper> findShippersByName(String name,Calendar begin,Calendar end,Status status) {
List<Shipper> shippers = shipperEaoLocal.findByName(name,begin,end,status);
return shippers;
}
public Shipper findShipperBySocialSecurity(String socialSecurity) {
Shipper carrier = shipperEaoLocal.findBySocialSecurity(socialSecurity);
return carrier;
}
@Override
public List<Supplier> findSuppliersByName(String name, Calendar begin,Calendar end, Status status) {
List<Supplier> suppliers = supplierEaoLocal.findByName(name,begin, end, status);
return suppliers;
}
@Override
public List<Supplier> findBySuppliersDateRegister(Calendar begin,Calendar end, Status status) {
List<Supplier> suppliers = supplierEaoLocal.findByDateRegister(begin, end, status);
return suppliers;
}
@Override
public Shipper findShipperByIdOrSocialSecurity(Long id,String socialSecurity) {
Shipper shipper = shipperEaoLocal.findByIndex(id,socialSecurity);
return shipper;
}
@Override
public List<Shipper> findByShippersDateRegister(Calendar begin,
Calendar end, Status status) {
List<Shipper> shippers = shipperEaoLocal.findbyDateRegister(begin, end, status);
return shippers;
}
}
| true
|
d634c76dd5c9aa1fddf5d98c4b456399e75d3fef
|
Java
|
tenebrius1/tp
|
/src/main/java/seedu/address/model/person/Student.java
|
UTF-8
| 612
| 2.828125
| 3
|
[
"MIT"
] |
permissive
|
package seedu.address.model.person;
import static seedu.address.commons.util.CollectionUtil.requireAllNonNull;
import java.util.Set;
import seedu.address.model.tag.Tag;
/**
* Represents a Student in CLITutors.
* Guarantees: details are present and not null, field values are validated, immutable.
*/
public class Student extends Person {
/**
* Every field must be present and not null.
*/
public Student(Name name, Phone phone, Gender gender, Remark remark, Set<Tag> tags) {
super(name, phone, gender, remark, tags);
requireAllNonNull(name, phone, gender, tags);
}
}
| true
|
d6d2c5ad6057de2eccdaf6fb815d852985191161
|
Java
|
FeehAvelar/POOJavaCursoVideo
|
/POO/CursoEmVideo/src/Aula13/Aula13.java
|
UTF-8
| 266
| 2.1875
| 2
|
[] |
no_license
|
package Aula13;
public class Aula13 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Cachorro c = new Cachorro();
c.reagir("Ola");
c.reagir(11, 45);
c.reagir(19, 00);
c.reagir(true);
c.reagir(false);
}
}
| true
|
ecd388f75203d52a067ca4dd603286a1406e6646
|
Java
|
Newbiepeople/Newbie
|
/struts2/src/com/helloweenvsfei/struts2/bean/Person.java
|
UTF-8
| 1,265
| 2.46875
| 2
|
[] |
no_license
|
package com.helloweenvsfei.struts2.bean;
import java.sql.Date;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
public class Person {
private Integer id;
private String account;
private String name;
private Date birthday;
private Timestamp createDate = new Timestamp(System.currentTimeMillis());
private boolean secret;
private List<String> hobby = new ArrayList<String>();
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public Timestamp getCreateDate() {
return createDate;
}
public void setCreateDate(Timestamp createDate) {
this.createDate = createDate;
}
public List<String> getHobby() {
return hobby;
}
public void setHobby(List<String> hobby) {
this.hobby = hobby;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isSecret() {
return secret;
}
public void setSecret(boolean secret) {
this.secret = secret;
}
}
| true
|
d0ceba2e5223d467da174f58dd8ec0b64557ed23
|
Java
|
oysteinhaune/TicTackToe
|
/src/com/company/TicTacToeProgram.java
|
UTF-8
| 4,761
| 3.3125
| 3
|
[] |
no_license
|
package com.company;
import java.util.Scanner;
public class TicTacToeProgram {
private TicTacToe ticTacToe;
private String activeplayer;
private String playersymbol;
private Scanner scanner;
public TicTacToeProgram() {
this.ticTacToe = new TicTacToe();
this.activeplayer = "Player 1";
this.playersymbol = "X";
this.scanner = new Scanner(System.in);
}
public void run() {
System.out.println(this.activeplayer + ", choose your place on the board: ");
String place = this.scanner.nextLine();
if (this.isRightInput(place)) {
if (this.input(this.playersymbol, place)) {
System.out.println(ticTacToe);
if (!this.winnerCheck("X", this.ticTacToe) && !this.winnerCheck("O", this.ticTacToe)) {
this.switchPlayerSymbol(this.activeplayer);
this.switchActiveplayer(this.activeplayer);
this.run();
}
else {
System.out.println(this.activeplayer + " won the game! Congratulations!! :D :D");
}
}
else {
this.run();
}
}
else {
this.run();
}
}
public boolean input(String symbol, String place) {
if (place.equals("00") && this.ticTacToe.oppvenstre == " ") {
this.ticTacToe.oppvenstre = symbol;
return true;
} else if (place.equals("10") && this.ticTacToe.oppmidt == " ") {
this.ticTacToe.oppmidt = symbol;
return true;
} else if (place.equals("20") && this.ticTacToe.opphoyre == " ") {
this.ticTacToe.opphoyre = symbol;
return true;
} else if (place.equals("01") && this.ticTacToe.midtvenstre == " ") {
this.ticTacToe.midtvenstre = symbol;
return true;
} else if (place.equals("11") && this.ticTacToe.midtmidt == " ") {
this.ticTacToe.midtmidt = symbol;
return true;
} else if (place.equals("21") && this.ticTacToe.midthoyre == " ") {
this.ticTacToe.midthoyre = symbol;
return true;
} else if (place.equals("02") && this.ticTacToe.nedvenstre == " ") {
this.ticTacToe.nedvenstre = symbol;
return true;
} else if (place.equals("12") && this.ticTacToe.nedmidt == " ") {
this.ticTacToe.nedmidt = symbol;
return true;
} else if (place.equals("22") && this.ticTacToe.nedhoyre == " "){
this.ticTacToe.nedhoyre = symbol;
return true;
}
else {
return false;
}
}
public boolean isRightInput(String input) {
if (input.equals("00") || input.equals("10") || input.equals("20") || input.equals("01")
|| input.equals("11") || input.equals("21") || input.equals("02") || input.equals("12") ||
input.equals("22")) {
return true;
}
return false;
}
public boolean winnerCheck(String symbol ,TicTacToe ticTacToe) {
if (ticTacToe.oppvenstre == symbol && ticTacToe.oppmidt == symbol && ticTacToe.opphoyre == symbol) {
return true;
} else if (ticTacToe.midtvenstre == symbol && ticTacToe.midtmidt == symbol && ticTacToe.midthoyre == symbol) {
return true;
} else if (ticTacToe.nedvenstre == symbol && ticTacToe.nedmidt == symbol && ticTacToe.nedhoyre == symbol) {
return true;
} else if (ticTacToe.oppvenstre == symbol && ticTacToe.midtvenstre == symbol && ticTacToe.nedvenstre == symbol) {
return true;
} else if (ticTacToe.oppmidt == symbol && ticTacToe.midtmidt == symbol && ticTacToe.nedmidt == symbol) {
return true;
} else if (ticTacToe.opphoyre == symbol && ticTacToe.midthoyre == symbol && ticTacToe.nedhoyre == symbol) {
return true;
} else if (ticTacToe.nedvenstre == symbol && ticTacToe.midtmidt == symbol && ticTacToe.opphoyre == symbol) {
return true;
} else if (ticTacToe.oppvenstre == symbol && ticTacToe.midtmidt == symbol && ticTacToe.nedhoyre == symbol) {
return true;
} else {
return false;
}
}
public void switchActiveplayer(String player) {
if (player == "Player 1") {
this.activeplayer = "Player 2";
}
else {
this.activeplayer = "Player 1";
}
}
public void switchPlayerSymbol(String player) {
if (player == "Player 1") {
this.playersymbol = "O";
}
else {
this.playersymbol = "X";
}
}
}
| true
|
04e88d10a1d19fe80e4c4d192c2e0c6ff0024c95
|
Java
|
douglasapolinario/smart-school-rest
|
/src/main/java/br/com/smartschool/business/ResponsavelBusinessImpl.java
|
UTF-8
| 4,208
| 2.390625
| 2
|
[] |
no_license
|
package br.com.smartschool.business;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import javax.inject.Inject;
import static br.com.smartschool.business.BusinessResponse.BusinessResponseStatus.*;
import br.com.smartschool.dao.ResponsavelDaoImpl;
import br.com.smartschool.model.Responsavel;
public class ResponsavelBusinessImpl implements ResponsavelBusiness {
@Inject
private ResponsavelDaoImpl responsavelDao;
@Override
public BusinessResponse<Responsavel> save(Responsavel responsavel) {
if (!Optional.ofNullable(responsavel).isPresent()) {
return BusinessResponse.<Responsavel>builder()
.messages(Collections.singletonMap("resp", "Responsavel não pode ser nulo"))
.status(ERROR)
.build();
}
Optional<Map<String,String>> validations = responsavel.applyValidations();
if (validations.isPresent()) {
return BusinessResponse.<Responsavel>builder()
.messages(validations.get())
.status(ERROR)
.build();
}
Responsavel respFromDB = responsavelDao.findByCPF(responsavel.getCpf());
if (Optional.ofNullable(respFromDB).isPresent()) {
return BusinessResponse.<Responsavel>builder()
.messages(Collections.singletonMap("cpf", "CPF já está em uso por outro responsável"))
.status(ERROR)
.build();
}
respFromDB = responsavelDao.findByEmail(responsavel.getEmail());
if (Optional.ofNullable(respFromDB).isPresent()) {
return BusinessResponse.<Responsavel>builder()
.messages(Collections.singletonMap("email", "Email já está em uso por outro responsável"))
.status(ERROR)
.build();
}
Responsavel resp = responsavelDao.createOrUpdate(responsavel);
return BusinessResponse.<Responsavel>builder()
.content(resp)
.status(OK)
.build();
}
@Override
public BusinessResponse<Responsavel> update(Responsavel responsavel) {
Responsavel respFromDB = responsavelDao.findByCPF(responsavel.getCpf());
if (!Optional.ofNullable(respFromDB).isPresent()) {
return BusinessResponse.<Responsavel>builder()
.messages(Collections.singletonMap("resp", "Nenhum responsável encontrado"))
.status(ERROR)
.build();
}
respFromDB.setCelular(responsavel.getCelular());
respFromDB.setTelefone(responsavel.getTelefone());
respFromDB.setRg(responsavel.getRg());
respFromDB.setNome(responsavel.getNome());
respFromDB.setSobrenome(responsavel.getSobrenome());
respFromDB.setSenha(responsavel.getSenha());
responsavelDao.createOrUpdate(respFromDB);
return BusinessResponse.<Responsavel>builder()
.content(respFromDB)
.status(OK)
.build();
}
@Override
public BusinessResponse<Responsavel> delete(Responsavel responsavel) {
responsavelDao.delete(responsavel.getId());
return BusinessResponse.<Responsavel>builder()
.status(OK)
.build();
}
@Override
public BusinessResponse<Responsavel> findById(Long id) {
Responsavel respFromDB = responsavelDao.find(id);
if (!Optional.ofNullable(respFromDB).isPresent()) {
return BusinessResponse.<Responsavel>builder()
.messages(Collections.singletonMap("resp", "Nenhum responsável encontrado"))
.status(ERROR)
.build();
}
return BusinessResponse.<Responsavel>builder()
.content(respFromDB)
.status(OK)
.build();
}
@Override
public BusinessResponse<Responsavel> findByCPF(String cpf) {
Responsavel respFromDB = responsavelDao.findByCPF(cpf);
return BusinessResponse.<Responsavel>builder()
.content(respFromDB)
.status(OK)
.build();
}
@Override
public BusinessResponse<Responsavel> findByEmail(String email) {
Responsavel respFromDB = responsavelDao.findByEmail(email);
return BusinessResponse.<Responsavel>builder()
.content(respFromDB)
.status(OK)
.build();
}
@Override
public BusinessResponse<List<Responsavel>> findAll() {
Iterable<Responsavel> findAll = responsavelDao.findAll();
List<Responsavel> responsaveis = new ArrayList<>();
findAll.forEach(responsaveis::add);
return BusinessResponse.<List<Responsavel>>builder()
.content(responsaveis)
.status(OK)
.build();
}
}
| true
|
ffc752fb8208ab495ca3a880cc721f6292d7da49
|
Java
|
AlekseiNovoselov/zerkalosteklo
|
/src/main/java/database/ImageDataSet.java
|
UTF-8
| 952
| 2.703125
| 3
|
[] |
no_license
|
package database;
public class ImageDataSet {
private Long id;
private String name;
private String date_of_create;
private String album;
public ImageDataSet(long id, String name, String date_of_create, String album) {
this.id = id;
this.name = name;
this.date_of_create = date_of_create;
this.album = album;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String email) {
this.name = name;
}
public String getDateOfCreate() {
return date_of_create;
}
public void setDateOfCreate(String date_of_create) {
this.date_of_create = date_of_create;
}
public String getAlbum() {
return album;
}
public void setAlbum(Integer quantity_of_images) {
this.album = album;
}
}
| true
|
30375ae8fc3ee32767f84084d8d67bda8ce35f79
|
Java
|
zyot249/Java
|
/JavaWebTopica/Exercises/week1/ConvertColor/src/Test.java
|
UTF-8
| 258
| 2.4375
| 2
|
[] |
no_license
|
public class Test {
public static void main(String[] args) {
Convert convert = new Convert();
try {
convert.readBitmapImage("inputimage.bmp");
} catch (Exception e) {
e.printStackTrace();
}
}
}
| true
|
c1f1fd3ba73344fa63ea26ed90811d1cb7892bf8
|
Java
|
Dhanam22/07-09-2021-Assignment
|
/Book Management/BookImplement.java
|
UTF-8
| 533
| 2.09375
| 2
|
[] |
no_license
|
package Book;
import java.sql.Connection;
import java.util.List;
import Book.Book;
public interface BookImplement {
public static final String jdbcurl="jdbc:mysql://localhost:3306/Book";
public static final String driverclass="com.mysql.cj.jdbc.Driver";
public static final String username="Devi";
public static final String password="Dhanam";
Connection getConnection();
void insertBook(Book e);
Book selectBook(int id);
List<Book> selectAllBook();
boolean deleteBook(int Bookid);
boolean updateBook(Book e);
}
| true
|
b3048df0ba76109ff11aa920fded3a095b46664d
|
Java
|
astaputhra/SeqAnalysis
|
/com/project/seqAnalysis/algorithms/clustering/optics/DoubleArrayOPTICS.java
|
UTF-8
| 2,732
| 2.875
| 3
|
[] |
no_license
|
package com.project.seqAnalysis.algorithms.clustering.optics;
import java.util.Collections;
import java.util.List;
import com.project.seqAnalysis.datastructures.kdtree.KNNPoint;
import com.project.seqAnalysis.patterns.cluster.DoubleArray;
/* This file is copyright (c) 2008-2015 Philippe Fournier-Viger
*
* This file is part of the SPMF DATA MINING SOFTWARE
* (http://www.philippe-fournier-viger.com/spmf).
*
* SPMF is free software: you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later
* version.
* SPMF is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU General Public License for more details.
* You should have received a copy of the GNU General Public License along with
* SPMF. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* This class represents a vector of double values used by the DBScan algorithm.
* It has a "visited" flag to remember the node that have been already visited.
*
* @author Philippe Fournier-Viger
*/
public class DoubleArrayOPTICS extends DoubleArray implements Comparable<DoubleArrayOPTICS>{
boolean visited = false;
public double reachabilityDistance = Double.POSITIVE_INFINITY; // undefined
double core_distance = Double.POSITIVE_INFINITY; // undefined
/**
* Constructor
* @param data an array of double values
*/
public DoubleArrayOPTICS(double[] data) {
super(data);
}
/**
* Set the core distance of this point
* @param neighbors the neighbors of this point
* @param epsilon the epsilon distance
* @param minPts the minPts parameter
*/
public void setCoreDistance(List<KNNPoint> neighboors, double epsilon,
int minPts) {
// if not enough neighbors, then undefined
if(neighboors.size() < minPts - 1) {
core_distance = Double.POSITIVE_INFINITY;
}else {
// sort neighbors by increasing distance
Collections.sort(neighboors);
// the core distance is the distance of the minPts-1-th neighbor
core_distance = (neighboors.get(minPts-2)).distance;
}
}
/**
* Compare this point to another point
* @param point2 the given point.
* @return an integer <0 if the distance of this point is smaller than the distance of point2
* an integer >0 if the distance of this point is larger than the one of point2
* 0 if the distance is the same.
*/
public int compareTo(DoubleArrayOPTICS point2) {
return Double.compare(this.reachabilityDistance, point2.reachabilityDistance);
}
}
| true
|
c7dfb1967313cf3ece4a8f0488fbc748f325de3f
|
Java
|
jorge-luque/hb
|
/sources/com/criteo/publisher/model/C2452m.java
|
UTF-8
| 1,936
| 1.828125
| 2
|
[] |
no_license
|
package com.criteo.publisher.model;
import com.criteo.publisher.p054a0.C2330h;
import com.criteo.publisher.p054a0.C2338m;
import com.criteo.publisher.p054a0.C2345t;
import com.criteo.publisher.p058q.C2506d;
import com.criteo.publisher.p066y.C2580a;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Future;
/* renamed from: com.criteo.publisher.model.m */
public class C2452m {
/* renamed from: a */
private final C2460s f7900a;
/* renamed from: b */
private final C2456q f7901b;
/* renamed from: c */
private final C2338m f7902c;
/* renamed from: d */
private final C2580a f7903d;
/* renamed from: e */
private final C2506d f7904e;
/* renamed from: f */
private final C2330h f7905f;
public C2452m(C2460s sVar, C2456q qVar, C2338m mVar, C2580a aVar, C2506d dVar, C2330h hVar) {
this.f7900a = sVar;
this.f7901b = qVar;
this.f7902c = mVar;
this.f7903d = aVar;
this.f7904e = dVar;
this.f7905f = hVar;
}
/* renamed from: b */
private List<C2453n> m9261b(List<C2450k> list) {
ArrayList arrayList = new ArrayList();
for (C2450k a : list) {
arrayList.add(m9260a(a));
}
return arrayList;
}
/* renamed from: a */
public C2451l mo10374a(List<C2450k> list) {
return new C2451l(this.f7900a, C2466x.m9331a(this.f7902c.mo10156b(), C2345t.m9005a(this.f7903d.mo10632c()), C2345t.m9005a(this.f7903d.mo10631b()), C2345t.m9005a(this.f7903d.mo10633d())), this.f7905f.mo10140m(), this.f7905f.mo10139l(), this.f7903d.mo10628a(), m9261b(list));
}
/* renamed from: a */
private C2453n m9260a(C2450k kVar) {
return C2453n.m9264a(this.f7904e.mo10515a(), kVar.mo10366b(), kVar.mo10365a(), kVar.mo10367c());
}
/* renamed from: a */
public Future<String> mo10375a() {
return this.f7901b.mo10295a();
}
}
| true
|
21355800401213d7582edd4d262298b166083966
|
Java
|
supermanxkq/projects
|
/SSI2/src/com/ssi/stu/util/CellStyle.java
|
UTF-8
| 2,125
| 2.546875
| 3
|
[] |
no_license
|
package com.ssi.stu.util;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
public class CellStyle {
/**
*@MethodName:createCellStyle
*@Description:设置Excel样式
*@param wb
*@author:半仙儿
*@return HSSFCellStyle
*@date:2015-10-29下午02:54:49
*/
public static HSSFCellStyle createCellStyle(HSSFWorkbook wb) {
HSSFCellStyle style = wb.createCellStyle();
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
style.setFillForegroundColor(HSSFColor.LIGHT_YELLOW.index);
return style;
}
/**
*@MethodName:createCellStyle1
*@Description:设置Excel样式1
*@param wb
*@author:半仙儿
*@return HSSFCellStyle
*@date:2015-10-29下午02:54:49
*/
public static HSSFCellStyle createCellStyle1(HSSFWorkbook wb) {
HSSFCellStyle style = wb.createCellStyle();
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
style.setFillForegroundColor(HSSFColor.LIGHT_YELLOW.index);
style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
return style;
}
/**
*@MethodName:createCell
*@Description:创建单元格
*@param style
*@param row
*@param cellCount
*@author:半仙儿
*@return HSSFCell
*@date:2015-10-29下午04:40:21
*/
public static HSSFCell createCell(HSSFCellStyle style, HSSFRow row,
int cellCount) {
HSSFCell cell = row.createCell(cellCount);
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
cell.setCellStyle(style);
return cell;
}
}
| true
|
bed2dd82b1710a5e3d51a2390a989272169bbf8b
|
Java
|
poorneshv15/BMSHostel
|
/app/src/main/java/com/psps/projects/bmshostel/MyProfileFragment.java
|
UTF-8
| 6,170
| 2.3125
| 2
|
[] |
no_license
|
package com.psps.projects.bmshostel;
import android.content.Context;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import java.util.Arrays;
import firebaseclasses.Hostelite;
import firebaseclasses.Student;
import firebaseclasses.Warden;
import io.realm.Realm;
/**
* A simple {@link Fragment} subclass.
*/
public class MyProfileFragment extends Fragment {
OnMenuClickProfileIF outListener;
public MyProfileFragment() {
// Required empty public constructor
}
interface OnMenuClickProfileIF {
void onMenuClickOfProfileFragment(int id);
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
try {
outListener = (OnMenuClickProfileIF) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString()
+ " must implement OnHeadlineSelectedListener");
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView=inflater.inflate(R.layout.fragment_my_profile, container, false);
LinearLayout linearLayout= (LinearLayout) rootView.findViewById(R.id.fragment_profile_root);
TextView nameTv= (TextView) rootView.findViewById(R.id.userNameTv);
nameTv.setText(HomeActivity.user.getDisplayName());
Uri url=HomeActivity.user.getPhotoUrl();
Log.d("PROFILE FRAGMENT","DP Uri "+url);
switch (HomeActivity.userType){
case "WARDEN":
Warden warden= Realm.getDefaultInstance().where(Warden.class).contains("email",HomeActivity.user.getEmail()).findFirst();
addWardenLayout(warden,linearLayout);
break;
case "HOSTELITE":
Hostelite hostelite=Realm.getDefaultInstance().where(Hostelite.class).contains("email",HomeActivity.user.getEmail()).findFirst();
addHosteliteLayout(hostelite,linearLayout);
break;
default:
Student student=Realm.getDefaultInstance().where(Student.class).contains("email",HomeActivity.user.getEmail()).findFirst();
addStudentLayout(student,linearLayout);
}
ImageView profilePic= (ImageView) rootView.findViewById(R.id.userProfileIv);
Glide.with(this).load(HomeActivity.user.getPhotoUrl()).into(profilePic);
new AsyncTask<ImageView,String,String>() {
@Override
protected String doInBackground(ImageView... params) {
return null;
}
}.execute(profilePic);
setHasOptionsMenu(true);
return rootView;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
outListener.onMenuClickOfProfileFragment(item.getItemId());
return super.onOptionsItemSelected(item);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.profile_menu,menu);
}
private void addWardenLayout(Warden warden, LinearLayout linearLayout) {
LayoutInflater inflater=LayoutInflater.from(linearLayout.getContext());
View detailsView=inflater.inflate(R.layout.warden_content,null);
linearLayout.addView(detailsView,2);
TextView dump= (TextView) detailsView.findViewById(R.id.roomNoTv);
dump.setText(warden.email);
dump=(TextView)detailsView.findViewById(R.id.mobileTv);
dump.setText(warden.mobile);
dump=(TextView)detailsView.findViewById(R.id.roomsTv);
Hostel hostel=Realm.getDefaultInstance().where(Hostel.class).findFirst();
dump.setText(hostel.getHostelName().toUpperCase()+"\n"+ Arrays.toString(hostel.getRoomsUnderCotrol()));
}
private void addStudentLayout(Student student,LinearLayout linearLayout) {
View detailsView=getLayoutInflater(null).inflate(R.layout.student_content,null);
linearLayout.addView(detailsView,2);
TextView dump= (TextView) detailsView.findViewById(R.id.roomNoTv);
dump.setText(HomeActivity.user.getEmail());
dump=(TextView)detailsView.findViewById(R.id.sUsn);
dump.setText(student.usn);
}
private void addHosteliteLayout(Hostelite hostelite,LinearLayout linearLayout) {
View detailsView=getLayoutInflater(null).inflate(R.layout.hostelite_content,null);
linearLayout.addView(detailsView,2);
TextView dump= (TextView) detailsView.findViewById(R.id.roomNoTv);
dump.setText(hostelite.getEmail());
dump=(TextView)detailsView.findViewById(R.id.sRoomNoTv);
dump.setText(hostelite.getHostelName()+" "+hostelite.getRoomNo());
dump=(TextView)detailsView.findViewById(R.id.sUsn);
dump.setText(hostelite.getUsn());
dump=(TextView)detailsView.findViewById(R.id.sMobileTv);
dump.setText(hostelite.getMobile());
dump=(TextView)detailsView.findViewById(R.id.fNameTv);
dump.setText(hostelite.getFatherName());
dump=(TextView)detailsView.findViewById(R.id.fMobileTv);
dump.setText(hostelite.getFatherMobile());
dump=(TextView)detailsView.findViewById(R.id.fAddressTv);
dump.setText(hostelite.getFatherAddress());
dump=(TextView)detailsView.findViewById(R.id.gNameTv);
dump.setText(hostelite.getGuardianName());
dump=(TextView)detailsView.findViewById(R.id.gMobileTv);
dump.setText(hostelite.getGuardianMobile());
dump=(TextView)detailsView.findViewById(R.id.gAddressTv);
dump.setText(hostelite.getGuardianAddress());
}
}
| true
|
1386512c84236a7304e742efd64c8d1dc6eaae57
|
Java
|
toandrew/FactoryTool
|
/app/src/main/java/com/xiaoyezi/midicore/factorytool/stability/StabilityPresenter.java
|
UTF-8
| 8,021
| 2.15625
| 2
|
[] |
no_license
|
package com.xiaoyezi.midicore.factorytool.stability;
import android.content.Context;
import android.support.annotation.NonNull;
import android.util.Log;
import com.xiaoyezi.midicore.factorytool.data.MiDiDataRepository;
import com.xiaoyezi.midicore.factorytool.data.MiDiDataRepository.TestData;
import com.xiaoyezi.midicore.factorytool.data.MiDiDataSource;
import com.xiaoyezi.midicore.factorytool.data.TestConfig;
import com.xiaoyezi.midicore.factorytool.utils.Tlog;
import com.xiaoyezi.midicore.factorytool.utils.Utils;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
import rx.Observable;
import rx.Subscriber;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;
import rx.schedulers.Schedulers;
/**
* Created by jim on 2017/4/10.
*/
public class StabilityPresenter implements StabilityContract.Presenter {
private static final String TAG = "StabilityPresenter";
private StabilityFragment mStabilityFragment;
private MiDiDataRepository mMiDiDataRepository;
StabilityPresenter.TestMidiEventListener mMidiListener = new StabilityPresenter.TestMidiEventListener();
Subscription mSubscription;
// badly
private int mCurrentTestIndex = 0;
public StabilityPresenter(StabilityFragment fragment, MiDiDataRepository dataRepository) {
mStabilityFragment = fragment;
mMiDiDataRepository = dataRepository;
}
@Override
public void start(@NonNull final Context context) {
Tlog.e("startDevice!");
mMiDiDataRepository.setMidiDevEventListener(mMidiListener);
mMiDiDataRepository.startDevice();
}
@Override
public void stop() {
Tlog.e("stopDevice!");
// stop test
if (mSubscription != null) {
mStabilityFragment.onTestFinished();
stopTest();
}
mMiDiDataRepository.stopDevice();
}
@Override
public void resume() {
Tlog.e("resumeDevice!");
mMiDiDataRepository.resumeDevice();
}
@Override
public void pause() {
Tlog.e("pauseDevice!");
mMiDiDataRepository.pauseDevice();
}
@Override
public void sendMidiEvent(int type, int data1, int data2) {
mMiDiDataRepository.sendMidiEvent(type, data1, data2);
}
/**
* Midi event listener
*/
private final class TestMidiEventListener implements MiDiDataSource.EventListener {
@Override
public void onAttached() {
mStabilityFragment.setDeviceConnectionState(true);
}
@Override
public void onDetached() {
mStabilityFragment.setDeviceConnectionState(false);
}
@Override
public void onMidiData(final byte[] data) {
mStabilityFragment.onMidiData(data);
}
}
/**
* Start/Stop test
*
* @param config
*/
@Override
public void startStopText(final TestConfig config) {
if (mSubscription == null) {
final ArrayList<TestData> testSet = (ArrayList) buildTests(config);
Tlog.e("BEGIN");
mCurrentTestIndex = 0;
mSubscription = Observable.interval(config.getTestTimeGap() == 0 ? 1 : config.getTestTimeGap(), TimeUnit.MILLISECONDS)
.limit(config.getTestTimes() == -1 ? Integer.MAX_VALUE : testSet.size() * config.getTestTimes())
.subscribeOn(Schedulers.computation())
.observeOn(AndroidSchedulers.mainThread())
.doOnSubscribe(new Action0() {
@Override
public void call() {
}
})
.doOnUnsubscribe(new Action0() {
@Override
public void call() {
}
})
.subscribe(new Subscriber<Long>() {
@Override
public void onCompleted() {
Tlog.e("END");
if (!mSubscription.isUnsubscribed()) {
mSubscription.unsubscribe();
mSubscription = null;
}
Log.w(TAG, "onCompleted!");
mStabilityFragment.onTestFinished();
}
@Override
public void onError(Throwable e) {
Tlog.e("onError");
if (!mSubscription.isUnsubscribed()) {
mSubscription.unsubscribe();
mSubscription = null;
}
mStabilityFragment.onTestFinished();
}
@Override
public void onNext(Long aLong) {
if (mCurrentTestIndex < testSet.size()) {
TestData t = testSet.get(mCurrentTestIndex);
Log.w(TAG, "onNext!" + t.type);
if (t.type == MiDiDataSource.MIDI_COMMAND_TURN_ON || t.type == MiDiDataSource.MIDI_COMMAND_TURN_OFF) {
t.data1 = (int) Utils.getRandom(22, 110);
t.data2 = (int) Utils.getRandom(1, 3);
}
mStabilityFragment.onSendMidiData(mMiDiDataRepository.getMidiData(t.type, t.data1, t.data2));
sendMidiEvent(t.type, t.data1, t.data2);
mCurrentTestIndex++;
} else {
mCurrentTestIndex = 0;
}
}
});
} else {
Tlog.e("END");
stopTest();
}
}
/**
* Create all tests
*
* @param config
* @return
*/
private ArrayList<TestData> buildTests(final TestConfig config) {
ArrayList<TestData> tests = new ArrayList<>();
if (config.getConnectTest()) {
tests.add(new TestData(MiDiDataSource.MIDI_COMMAND_CONNECT, 0, 0));
tests.add(new TestData(MiDiDataSource.MIDI_COMMAND_DISCONNECT, 0, 0));
}
if (config.getDevInfoTest()) {
tests.add(new TestData(MiDiDataSource.MIDI_COMMAND_CONNECT, 0, 0));
tests.add(new TestData(MiDiDataSource.MIDI_COMMAND_QUERY_INFO, 0, 0));
}
if (config.getLightAllTest()) {
tests.add(new TestData(MiDiDataSource.MIDI_COMMAND_CONNECT, 0, 0));
int color = (int) Utils.getRandom(1, 3);
tests.add(new TestData(MiDiDataSource.MIDI_COMMAND_TURN_ON_ALL, color, 0));
tests.add(new TestData(MiDiDataSource.MIDI_COMMAND_TURN_OFF_ALL, color, 0));
}
if (config.getLightTest()) {
tests.add(new TestData(MiDiDataSource.MIDI_COMMAND_CONNECT, 0, 0));
int lightNum = config.getTestLightNum();
for (int i = 0; i < lightNum; i++) {
int light = (int) Utils.getRandom(22, 110);
int color = (int) Utils.getRandom(1, 3);
tests.add(new TestData(MiDiDataSource.MIDI_COMMAND_TURN_ON, light, color));
tests.add(new TestData(MiDiDataSource.MIDI_COMMAND_TURN_OFF, light, color));
}
}
tests.add(new TestData(MiDiDataSource.MIDI_COMMAND_CONNECT, 0, 0));
tests.add(new TestData(MiDiDataSource.MIDI_COMMAND_TURN_OFF_ALL, 0, 0));
return tests;
}
/**
* Stop test
*/
private void stopTest() {
mSubscription.unsubscribe();
mSubscription = null;
mCurrentTestIndex = 0;
}
/**
* Test config data
*/
public static class StabilityTestConfig extends TestConfig {
}
}
| true
|
a233e7d9a2d7ba197f82257fbd301573852e561b
|
Java
|
odiszapc/stem
|
/components/shared/src/main/java/org/stem/api/request/ApproveNodeRequest.java
|
UTF-8
| 1,327
| 1.726563
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright 2014 Alexey Plotnik
*
* 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.stem.api.request;
import java.util.UUID;
public class ApproveNodeRequest extends ClusterManagerRequest {
UUID nodeId;
String datacenter;
String rack;
public UUID getNodeId() {
return nodeId;
}
public void setNodeId(UUID nodeId) {
this.nodeId = nodeId;
}
public String getDatacenter() {
return datacenter;
}
public void setDatacenter(String datacenter) {
this.datacenter = datacenter;
}
public String getRack() {
return rack;
}
public void setRack(String rack) {
this.rack = rack;
}
public ApproveNodeRequest() {
}
public ApproveNodeRequest(UUID nodeId) {
this.nodeId = nodeId;
}
}
| true
|
5e9c2421be29d8c416602e742de9dd070add060c
|
Java
|
dgrigory/Java2DB
|
/src/main/java/com/github/collinalpert/java2db/services/BaseService.java
|
UTF-8
| 28,344
| 2.3125
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.github.collinalpert.java2db.services;
import com.github.collinalpert.java2db.annotations.DefaultIfNull;
import com.github.collinalpert.java2db.database.DBConnection;
import com.github.collinalpert.java2db.entities.BaseEntity;
import com.github.collinalpert.java2db.exceptions.IllegalEntityFieldAccessException;
import com.github.collinalpert.java2db.mappers.BaseMapper;
import com.github.collinalpert.java2db.mappers.Mappable;
import com.github.collinalpert.java2db.modules.AnnotationModule;
import com.github.collinalpert.java2db.modules.FieldModule;
import com.github.collinalpert.java2db.modules.LoggingModule;
import com.github.collinalpert.java2db.modules.TableModule;
import com.github.collinalpert.java2db.pagination.CacheablePaginationResult;
import com.github.collinalpert.java2db.pagination.PaginationResult;
import com.github.collinalpert.java2db.queries.EntityQuery;
import com.github.collinalpert.java2db.queries.OrderTypes;
import com.github.collinalpert.java2db.utilities.IoC;
import com.github.collinalpert.lambda2sql.Lambda2Sql;
import com.github.collinalpert.lambda2sql.functions.SqlFunction;
import com.github.collinalpert.lambda2sql.functions.SqlPredicate;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.sql.SQLException;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.StringJoiner;
import java.util.stream.Collectors;
/**
* Class that provides base functionality for all service classes. Every service class must extend this class.
*
* @author Collin Alpert
*/
public class BaseService<T extends BaseEntity> {
private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
private static final DateTimeFormatter TIME_FORMATTER = DateTimeFormatter.ofPattern("HH:mm:ss");
private static final AnnotationModule annotationModule;
private static final FieldModule fieldModule;
private static final TableModule tableModule;
/**
* The logger used to log queries and messages to the console.
*/
private static final LoggingModule loggingModule;
static {
annotationModule = new AnnotationModule();
fieldModule = new FieldModule();
tableModule = new TableModule();
loggingModule = new LoggingModule();
}
/**
* The generic type of this service.
*/
protected final Class<T> type;
/**
* Represents the table name of the entity this services corresponds to.
* It contains the table name with escaping backticks.
*/
protected final String tableName;
/**
* The mapper used for mapping database objects to Java entities in this service.
*/
protected final Mappable<T> mapper;
/**
* Represents the id column being accessed.
*/
private final String idAccess;
/**
* Constructor for the base class of all services. It is not possible to create instances of it.
*/
protected BaseService() {
this.type = getGenericType();
this.mapper = IoC.resolveMapper(this.type, new BaseMapper<>(this.type));
this.tableName = tableModule.getTableName(this.type);
final SqlFunction<T, Long> idFunc = BaseEntity::getId;
this.idAccess = Lambda2Sql.toSql(idFunc, this.tableName);
}
//region Create
/**
* Creates this Java entity on the database.
*
* @param instance The instance to create on the database.
* @return The id of the newly created record.
* @throws SQLException if the query cannot be executed due to database constraints
* i.e. non-existing default value for field or an incorrect data type or a foreign key constraint.
*/
public long create(T instance) throws SQLException {
var insertQuery = createInsertHeader();
var joiner = new StringJoiner(", ", "(", ");");
fieldModule.getEntityFields(instance.getClass(), BaseEntity.class).forEach(field -> {
field.setAccessible(true);
if (getFieldValue(field, instance) == null && annotationModule.hasAnnotation(field, DefaultIfNull.class, DefaultIfNull::onCreate)) {
joiner.add("default");
return;
}
joiner.add(getSqlValue(field, instance));
});
//For using the default database setting for the id.
joiner.add("default");
insertQuery.append(joiner.toString());
try (var connection = new DBConnection()) {
var id = connection.update(insertQuery.toString());
loggingModule.logf("%s successfully created!", this.type.getSimpleName());
return id;
}
}
/**
* Creates a variable amount of entities on the database.
*
* @param instances The instances to create.
* @throws SQLException if the query cannot be executed due to database constraints
* i.e. non-existing default value for field or an incorrect data type or a foreign key constraint.
* @see #create(List)
*/
@SuppressWarnings("unchecked")
public void create(T... instances) throws SQLException {
create(Arrays.asList(instances));
}
/**
* Creates multiple entities on the database.
* It is recommended to use this method instead of iterating over the list and
* calling a normal {@link #create(BaseEntity)} on each entity separately.
*
* @param instances The list of entities to create on the database.
* @throws SQLException if the query cannot be executed due to database constraints
* i.e. non-existing default value for field or an incorrect data type or a foreign key constraint.
*/
public void create(List<T> instances) throws SQLException {
if (instances.isEmpty()) {
return;
}
var insertQuery = createInsertHeader();
var rows = new String[instances.size()];
StringJoiner joiner;
for (int i = 0, instancesSize = instances.size(); i < instancesSize; i++) {
var entityFields = fieldModule.getEntityFields(instances.get(i).getClass(), BaseEntity.class);
joiner = new StringJoiner(", ", "(", ")");
for (var entityField : entityFields) {
entityField.setAccessible(true);
var instance = instances.get(i);
if (getFieldValue(entityField, instance) == null && annotationModule.hasAnnotation(entityField, DefaultIfNull.class, DefaultIfNull::onCreate)) {
joiner.add("default");
return;
}
joiner.add(getSqlValue(entityField, instance));
}
//For using the default database setting for the id.
joiner.add("default");
rows[i] = joiner.toString();
}
insertQuery.append(String.join(", ", rows));
try (var connection = new DBConnection()) {
connection.update(insertQuery.toString());
loggingModule.logf("%s entities were successfully created.", this.type.getSimpleName());
}
}
//endregion
//region Read
//region Count
/**
* An overload of the {@link #count(SqlPredicate)} method. It will count all the rows that have an id, since this should be a reasonable criteria.
* Use with caution, as this call can take quite a while.
*
* @return The amount of rows in this table.
*/
public long count() {
return count(x -> true);
}
/**
* Counts the rows that have an id (which should usually be every row) and match a certain condition. Note that COUNT operations usually are very slow.
*
* @param predicate The condition to test for.
* @return The number of rows matching the condition.
*/
public long count(SqlPredicate<T> predicate) {
try (var connection = new DBConnection()) {
try (var result = connection.execute(String.format("select count(%s) from `%s` where %s;", this.idAccess, this.tableName, Lambda2Sql.toSql(predicate, this.tableName)))) {
if (result.next()) {
return result.getLong(String.format("count(%s)", this.idAccess));
}
return 0;
}
} catch (SQLException e) {
e.printStackTrace();
throw new IllegalArgumentException(String.format("Could not get amount of rows in table %s for this predicate.", this.tableName));
}
}
//endregion
//region Any
/**
* Checks if a table has at least one row.
*
* @return {@code True} if at least one row exists in the table, {@code false} if not.
*/
public boolean any() {
return any(x -> true);
}
/**
* Checks if a value matching the condition exists in the table.
*
* @param predicate The condition to check for.
* @return {@code True} if the predicate matches one or more records, {@code false} if not.
*/
public boolean any(SqlPredicate<T> predicate) {
try (var connection = new DBConnection()) {
try (var result = connection.execute(String.format("select exists(select %s from `%s` where %s limit 1) as result;", this.idAccess, this.tableName, Lambda2Sql.toSql(predicate, this.tableName)))) {
if (result.next()) {
return result.getInt("result") == 1;
}
return false;
}
} catch (SQLException e) {
e.printStackTrace();
throw new IllegalArgumentException(String.format("Could not check if a row matches this condition on table %s.", this.tableName));
}
}
//endregion
//region HasDuplicates
/**
* Checks if duplicate values exist for a specific column in a table.
*
* @param column The column to check for duplicate values for.
* @return {@code True} if there is at least one duplicate value in the specified column, {@code false} otherwise.
*/
public boolean hasDuplicates(SqlFunction<T, ?> column) {
var sqlColumn = Lambda2Sql.toSql(column, this.tableName);
try (var connection = new DBConnection()) {
try (var result = connection.execute(String.format("select %s from `%s` group by %s having count(%s) > 1", sqlColumn, this.tableName, sqlColumn, sqlColumn))) {
return result.next();
}
} catch (SQLException e) {
e.printStackTrace();
throw new IllegalArgumentException(String.format("Could not check if duplicate values exist in column %s on table %s.", sqlColumn, this.tableName));
}
}
//endregion
//region Query
/**
* @return a {@link EntityQuery} object with which a DQL statement can be built, using operations like order by, limit etc.
* If you do not require a plain {@link EntityQuery}, please consider using the
* {@link #getSingle(SqlPredicate)}, {@link #getMultiple(SqlPredicate)} or {@link #getAll()} methods.
*/
protected EntityQuery<T> createQuery() {
return new EntityQuery<>(this.type, this.mapper);
}
/**
* Retrieves a single entity which matches the predicate.
*
* @param predicate The {@link SqlPredicate} to add constraints to a DQL query.
* @return An entity matching the result of the query.
*/
public Optional<T> getSingle(SqlPredicate<T> predicate) {
return createQuery().where(predicate).getFirst();
}
/**
* Retrieves list of entities which match the predicate.
*
* @param predicate The {@link SqlPredicate} to add constraints to a DQL statement.
* @return A list of entities matching the result of the query.
*/
public EntityQuery<T> getMultiple(SqlPredicate<T> predicate) {
return createQuery().where(predicate);
}
/**
* @param id The id of the desired entity.
* @return Gets an entity by its id.
*/
public Optional<T> getById(long id) {
return getSingle(x -> x.getId() == id);
}
/**
* @return All entities in this table.
*/
public List<T> getAll() {
return createQuery().toList();
}
/**
* Gets all values from the table and orders them in an ascending order.
*
* @param orderBy The property to order by.
* @return A list of all records ordered by a specific property in an ascending order.
*/
public List<T> getAll(SqlFunction<T, ?> orderBy) {
return createQuery().orderBy(orderBy).toList();
}
/**
* Gets all values from the table and orders them in an ascending order by multiple columns in a coalescing manner.
*
* @param orderBy The properties to order by.
* @return A list of all records ordered by a specific property in an ascending order.
*/
@SuppressWarnings("unchecked")
public List<T> getAll(SqlFunction<T, ?>... orderBy) {
return createQuery().orderBy(orderBy).toList();
}
/**
* Gets all values from the table and orders them in the specified order by multiple columns in a coalescing manner.
*
* @param orderBy The property to order by.
* @param sortingType The order direction. Can be either ascending or descending.
* @return A list of all records ordered by a specific property in the specified order.
*/
public List<T> getAll(OrderTypes sortingType, SqlFunction<T, ?> orderBy) {
return createQuery().orderBy(sortingType, orderBy).toList();
}
/**
* Gets all values from the table and orders them in the specified order by multiple columns in a coalescing manner.
*
* @param orderBy The properties to order by.
* @param sortingType The order direction. Can be either ascending or descending.
* @return A list of all records ordered by a specific property in the specified order.
*/
@SuppressWarnings("unchecked")
public List<T> getAll(OrderTypes sortingType, SqlFunction<T, ?>... orderBy) {
return createQuery().orderBy(sortingType, orderBy).toList();
}
//endregion EntityQuery
//region Pagination
/**
* Creates a pagination structure that splits the entire table into multiple pages.
* Note that the query to the database for each page is only executed when that specific page is requested and
* <em>not</em> when this method is called.
*
* @param entriesPerPage The number of entries to be displayed on each page.
* @return A pagination which splits up an entire table into multiple pages.
*/
public PaginationResult<T> createPagination(int entriesPerPage) {
return new PaginationResult<>(createPaginationQueries(entriesPerPage));
}
/**
* Creates a pagination structure that splits the result of a query into multiple pages.
* Note that the query to the database for each page is only executed when that specific page is requested and
* <em>not</em> when this method is called.
* The predicate to filter by.
*
* @param predicate The predicate to filter by.
* @param entriesPerPage The number of entries to be displayed on each page.
* @return A pagination which splits the result of a condition into multiple pages.
*/
public PaginationResult<T> createPagination(SqlPredicate<T> predicate, int entriesPerPage) {
return new PaginationResult<>(createPaginationQueries(predicate, entriesPerPage));
}
/**
* Creates a pagination structure that splits the entire table into multiple pages.
* Note that the query to the database for each page is only executed when that specific page is requested and
* <em>not</em> when this method is called.
* When pages are retrieved, they are stored in a cache, so they can be
* retrieved from there the next time they are requested. Note that this will work, until the specified {@code cacheExpiration}
* is up. After that, the next time a page is requested, it will be reloaded from the database.
*
* @param entriesPerPage The number of entries to be displayed on each page.
* @param cacheExpiration The time a page is valid in the cache. If a page is requested and in the cache, but expired,
* it will be retrieved from the database again and re-stored in the cache.
* @return A pagination which displays a entire table
*/
public CacheablePaginationResult<T> createPagination(int entriesPerPage, Duration cacheExpiration) {
return new CacheablePaginationResult<>(createPaginationQueries(entriesPerPage), cacheExpiration);
}
/**
* Creates a cached pagination structure that splits the result of a query into multiple pages.
* Note that the query to the database for each page is only executed when that specific page is requested and
* <em>not</em> when this method is called.
* When pages are retrieved, they are stored in a cache, so they can be
* retrieved from there the next time they are requested. Note that this will work, until the specified {@code cacheExpiration}
* is up. After that, the next time a page is requested, it will be reloaded from the database.
*
* @param predicate The predicate to filter by.
* @param entriesPerPage The number of entries to be displayed on each page.
* @param cacheExpiration The time a page is valid in the cache. If a page is requested and in the cache, but expired,
* it will be retrieved from the database again and re-stored in the cache.
* @return A pagination which allows the developer to retrieve specific pages from the result.
*/
public CacheablePaginationResult<T> createPagination(SqlPredicate<T> predicate, int entriesPerPage, Duration cacheExpiration) {
return new CacheablePaginationResult<>(createPaginationQueries(predicate, entriesPerPage), cacheExpiration);
}
//endregion
//endregion
//region Update
/**
* Updates this entity's row on the database.
*
* @param instance The instance to update on the database.
* @throws SQLException if the query cannot be executed due to database constraints
* i.e. non-existing default value for field or an incorrect data type.
*/
public void update(T instance) throws SQLException {
try (var connection = new DBConnection()) {
connection.update(updateQuery(instance));
loggingModule.logf("%s with id %d was successfully updated.", this.type.getSimpleName(), instance.getId());
}
}
/**
* Variable argument version which behaves the same as the {@link #update(List)} method.
*
* @param instances The instances to update on the database.
* @throws SQLException if the query cannot be executed due to database constraints
* i.e. non-existing default value for field or an incorrect data type.
* @see #update(List)
*/
@SuppressWarnings("unchecked")
public void update(T... instances) throws SQLException {
update(Arrays.asList(instances));
}
/**
* Updates multiple entity's rows on the database. This method only opens one connection to the database as oppose
* to when calling the {@link #update(BaseEntity)} method in a for loop, which opens a new connection for every entity.
*
* @param instances The instances to update on the database.
* @throws SQLException if the query cannot be executed due to database constraints
* i.e. non-existing default value for field or an incorrect data type.
*/
public void update(List<T> instances) throws SQLException {
try (var connection = new DBConnection()) {
for (T instance : instances) {
connection.update(updateQuery(instance));
}
loggingModule.logf("%s were successfully updated.", this.type.getSimpleName());
}
}
private String updateQuery(T instance) {
var updateQuery = new StringBuilder("update `").append(this.tableName).append("` set ");
var fieldJoiner = new StringJoiner(", ");
fieldModule.getEntityFields(instance.getClass(), BaseEntity.class).forEach(field -> {
field.setAccessible(true);
var sqlValue = getFieldValue(field, instance) == null && annotationModule.hasAnnotation(field, DefaultIfNull.class, DefaultIfNull::onUpdate) ? "default" : getSqlValue(field, instance);
fieldJoiner.add(String.format("`%s` = %s", tableModule.getColumnName(field), sqlValue));
});
return updateQuery.append(fieldJoiner.toString()).append(String.format(" where %s = ", this.idAccess)).append(instance.getId()).toString();
}
/**
* Updates a specific column for a single record in a table.
* This method is not affected by the {@link DefaultIfNull} annotation.
*
* @param entityId The id of the record.
* @param column The column to update.
* @param newValue The new value of the column.
* @param <R> The data type of the column to update. It must be the same as the data type of the new value.
* @throws SQLException if the query cannot be executed due to database constraints
* i.e. non-existing default value for field or an incorrect data type.
*/
public <R> void update(long entityId, SqlFunction<T, R> column, R newValue) throws SQLException {
update(x -> x.getId() == entityId, column, newValue);
}
/**
* Updates a specific column for records matching a condition in a table.
* This method is not affected by the {@link DefaultIfNull} annotation.
*
* @param condition The condition to update the column by.
* @param column The column to update.
* @param newValue The new value of the column.
* @param <R> The data type of the column to update. It must be the same as the data type of the new value.
* @throws SQLException if the query cannot be executed due to database constraints
* i.e. non-existing default value for field or an incorrect data type.
*/
public <R> void update(SqlPredicate<T> condition, SqlFunction<T, R> column, R newValue) throws SQLException {
var query = String.format("update `%s` set %s = %s where %s;", this.tableName, Lambda2Sql.toSql(column, this.tableName), convertToSql(newValue), Lambda2Sql.toSql(condition, this.tableName));
try (var connection = new DBConnection()) {
connection.update(query);
loggingModule.logf("Column-specific update for table '%s' was successful.", tableModule.getTableName(this.type));
}
}
//endregion
//region Delete
/**
* Deletes the corresponding row on the database.
*
* @param instance The instance to delete on the database.
* @throws SQLException for example because of a foreign key constraint.
*/
public void delete(T instance) throws SQLException {
var id = instance.getId();
delete(x -> x.getId() == id);
}
/**
* Deletes a row by an id.
*
* @param id The row with this id to delete.
* @throws SQLException for example because of a foreign key constraint.
*/
public void delete(long id) throws SQLException {
delete(x -> x.getId() == id);
}
/**
* Deletes a list of entities at once.
*
* @param entities The list of entities to delete.
* @throws SQLException for example because of a foreign key constraint.
*/
public void delete(List<T> entities) throws SQLException {
var joiner = new StringJoiner(", ", "(", ")");
for (T entity : entities) {
joiner.add(Long.toString(entity.getId()));
}
var joinedIds = joiner.toString();
try (var connection = new DBConnection()) {
connection.update(String.format("delete from `%s` where %s in %s", this.tableName, this.idAccess, joinedIds));
loggingModule.logf("%s with ids %s successfully deleted!", this.type.getSimpleName(), joinedIds);
}
}
/**
* Deletes multiple entities at once.
*
* @param entities A variable amount of entities.
* @throws SQLException for example because of a foreign key constraint.
* @see #delete(List)
*/
@SuppressWarnings("unchecked")
public void delete(T... entities) throws SQLException {
delete(Arrays.asList(entities));
}
/**
* Deletes multiple rows with the corresponding ids.
*
* @param ids The ids to delete the rows by.
* @throws SQLException for example because of a foreign key constraint.
*/
public void delete(long... ids) throws SQLException {
var list = new ArrayList<Long>(ids.length);
for (long id : ids) {
list.add(id);
}
delete(x -> list.contains(x.getId()));
}
/**
* Deletes rows based on a condition.
*
* @param predicate The condition to delete by.
* @throws SQLException in case the condition cannot be applied or if a foreign key constraint fails.
*/
public void delete(SqlPredicate<T> predicate) throws SQLException {
try (var connection = new DBConnection()) {
connection.update(String.format("delete from `%s` where %s;", this.tableName, Lambda2Sql.toSql(predicate, this.tableName)));
loggingModule.logf("%s successfully deleted!", this.type.getSimpleName());
}
}
/**
* Truncates the corresponding table on the database.
*
* @throws SQLException for example because a foreign key references this table. Note that you will not be able to
* truncate a table, even if no foreign key references a row in this table. TRUNCATE is a DDL
* command and cannot check if rows are being referenced or not.
*/
public void truncateTable() throws SQLException {
try (var connection = new DBConnection()) {
connection.update(String.format("truncate table `%s`;", this.tableName));
loggingModule.logf("Table %s was successfully truncated.", this.tableName);
}
}
//endregion
/**
* Gets the generic type of this class.
*
* @return The entity class used as a generic type for this BaseService.
*/
@SuppressWarnings("unchecked")
private Class<T> getGenericType() {
return ((Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0]);
}
/**
* Will create a {@link StringBuilder} containing the beginning of a DML INSERT statement.
*
* @return An INSERT statement up to the VALUES keyword.
*/
private StringBuilder createInsertHeader() {
return new StringBuilder("insert into `").append(this.tableName).append("` ").append(fieldModule.getEntityFields(this.type)
.stream().map(field -> String.format("`%s`", tableModule.getColumnName(field)))
.collect(Collectors.joining(", ", "(", ")"))).append(" values ");
}
/**
* Gets a field value from an entity and handles the checked exception.
*
* @param entityField The field to get the value for.
* @param entityInstance The entity to get the value from.
* @return The value of the field in the entity.
*/
private Object getFieldValue(Field entityField, T entityInstance) {
try {
return entityField.get(entityInstance);
} catch (IllegalAccessException e) {
throw new IllegalEntityFieldAccessException(entityField.getName(), this.type.getSimpleName(), e.getMessage());
}
}
/**
* Returns a field value from an entity in its SQL equivalent.
*
* @param entityField The value's field.
* @param entityInstance The entity containing the value
* @return A {@code String} representing the SQL value of the entity field.
*/
private String getSqlValue(Field entityField, T entityInstance) {
return convertToSql(getFieldValue(entityField, entityInstance));
}
/**
* Converts a Java object to its SQL representation.
*
* @param value The value to convert.
* @return The SQL version of a Java value.
*/
private String convertToSql(Object value) {
if (value == null) {
return "null";
}
if (value instanceof String) {
return "'" + value + "'";
}
if (value instanceof Boolean) {
var bool = (boolean) value;
return bool ? "1" : "0";
}
if (value instanceof LocalDateTime) {
var dateTime = (LocalDateTime) value;
return "'" + DATE_TIME_FORMATTER.format(dateTime) + "'";
}
if (value instanceof LocalDate) {
var date = (LocalDate) value;
return "'" + DATE_FORMATTER.format(date) + "'";
}
if (value instanceof LocalTime) {
var time = (LocalTime) value;
return "'" + TIME_FORMATTER.format(time) + "'";
}
return value.toString();
}
/**
* An overload of the {@link #createPaginationQueries(SqlPredicate, int)} method.
* It creates queries for getting all the values from a table.
*
* @param entriesPerPage The number of entries to be displayed on each page.
* @return A list of queries containing the definitions for getting specific pages.
*/
private List<EntityQuery<T>> createPaginationQueries(int entriesPerPage) {
return createPaginationQueries(x -> true, entriesPerPage);
}
/**
* Creates queries that define the queries for specific pages. Note that this does not execute the queries yet.
*
* @param predicate A filter to narrow down the queries.
* @param entriesPerPage The number of entries to be displayed on each page.
* @return A list of queries containing the definitions for getting specific pages.
*/
private List<EntityQuery<T>> createPaginationQueries(SqlPredicate<T> predicate, int entriesPerPage) {
var count = this.count(predicate);
var numberOfPages = Math.ceil(count / (double) entriesPerPage);
var queries = new ArrayList<EntityQuery<T>>((int) numberOfPages);
for (int i = 0; i < numberOfPages; i++) {
var offset = i * entriesPerPage;
//TODO Refactor the limit-offset-combo for performance in bigger data sets.
queries.add(getMultiple(predicate).limit(entriesPerPage, offset));
}
return queries;
}
}
| true
|
e4ff01fb3ee28ca190154aac976b6b2ca3e2eca0
|
Java
|
wumin123150/wumin
|
/wumin-common/src/main/java/com/wumin/common/security/shiro/WeixinToken.java
|
UTF-8
| 1,029
| 2.328125
| 2
|
[] |
no_license
|
package com.wumin.common.security.shiro;
import org.apache.shiro.authc.HostAuthenticationToken;
public class WeixinToken implements HostAuthenticationToken {
private String openId;
private String host;
public WeixinToken() {
}
public WeixinToken(String openId) {
this(openId, null);
}
public WeixinToken(String openId, String host) {
this.openId = openId;
this.host = host;
}
public String getOpenId() {
return openId;
}
public void setOpenId(String openId) {
this.openId = openId;
}
public Object getPrincipal() {
return getOpenId();
}
public Object getCredentials() {
return getOpenId();
}
public String getHost() {
return this.host;
}
public void setHost(String host) {
this.host = host;
}
public void clear() {
this.host = null;
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getName());
sb.append(" - ");
if (this.host != null) {
sb.append(" (").append(this.host).append(")");
}
return sb.toString();
}
}
| true
|
4ea1e1b9a6b4f4c25d191154349e7db93b01ab62
|
Java
|
svennjegac/FER-java-opjj
|
/hw09-0036479615/src/hr/fer/zemris/java/raytracer/RayCaster.java
|
UTF-8
| 2,798
| 2.9375
| 3
|
[] |
no_license
|
package hr.fer.zemris.java.raytracer;
import hr.fer.zemris.java.raytracer.model.IRayTracerProducer;
import hr.fer.zemris.java.raytracer.model.IRayTracerResultObserver;
import hr.fer.zemris.java.raytracer.model.Point3D;
import hr.fer.zemris.java.raytracer.model.Ray;
import hr.fer.zemris.java.raytracer.model.Scene;
import hr.fer.zemris.java.raytracer.viewer.RayTracerViewer;
/**
* Program draws 3D scene by method of ray-tracing.
* Program is one threaded and pretty slow.
*
* @author Sven Njegač
* @version 1.0
*/
public class RayCaster {
/**
* Method which is run when program starts.
*
* @param args command line arguments
*/
public static void main(String[] args) {
RayTracerViewer.show(getIRayTracerProducer(),
new Point3D(10, 0, 0),
new Point3D(0, 0, 0),
new Point3D(0, 0, 10),
20, 20);
}
/**
* Getter for {@link IRayTracerProducer}.
* It returns an object which is able to populate data which can be then
* used for drawing a scene.
*
* @return new {@link IRayTracerProducer}
*/
private static IRayTracerProducer getIRayTracerProducer() {
return new IRayTracerProducer() {
@Override
public void produce(Point3D eye, Point3D view, Point3D viewUp, double horizontal, double vertical, int width,
int height, long requestNo, IRayTracerResultObserver observer) {
System.out.println("Započinjem izračune...");
short[] red = new short[width * height];
short[] green = new short[width * height];
short[] blue = new short[width * height];
Point3D OGNormalized = eye.difference(view, eye).normalize();
Point3D VUVNormalized = viewUp.normalize();
Point3D j_ = VUVNormalized.sub(OGNormalized.scalarMultiply(OGNormalized.scalarProduct(VUVNormalized)));
Point3D j = j_.normalize();
Point3D i_ = OGNormalized.vectorProduct(j);
Point3D i = i_.normalize();
Point3D screenCorner = view.sub(i.scalarMultiply(horizontal / 2)).add(j.scalarMultiply(vertical / 2));
Scene scene = RayTracerViewer.createPredefinedScene();
short[] rgb = new short[3];
int offset = 0;
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
Point3D screenPoint = screenCorner.add(i.scalarMultiply(((double) x) / (width - 1) * horizontal)).sub(j.scalarMultiply((((double) y) / (height - 1) * vertical)));
Ray ray = Ray.fromPoints(eye.copy(), screenPoint.copy());
Util.tracer(scene, ray, rgb);
red[offset] = rgb[0] > 255 ? 255 : rgb[0];
green[offset] = rgb[1] > 255 ? 255 : rgb[1];
blue[offset] = rgb[2] > 255 ? 255 : rgb[2];
offset++;
}
}
System.out.println("Izračuni gotovi...");
observer.acceptResult(red, green, blue, requestNo);
}
};
}
}
| true
|
f0d4f43246f03037dbef6df916a2423a9f9ac12a
|
Java
|
Jiangyi/StoryTime
|
/core/src/com/jxz/notcontra/entity/Alien.java
|
UTF-8
| 2,235
| 2.5
| 2
|
[] |
no_license
|
package com.jxz.notcontra.entity;
import com.badlogic.gdx.math.MathUtils;
import com.jxz.notcontra.animation.AnimationEx;
import com.jxz.notcontra.animation.SpriteEx;
import com.jxz.notcontra.handlers.AudioHelper;
/**
* Created by Samuel on 01/06/2015.
* First ranged AI monster.
*/
public class Alien extends RangedMonster {
// Animation frame name values
private final String TEXTURE_ATLAS_NAME = "alien";
private final String ANIM_WALK = "move";
private final String ANIM_IDLE = "stand";
private final String ANIM_JUMP = "jump";
private final String ANIM_HURT = "hit1";
private final String ANIM_ATTACK = "attack1";
private final String ANIM_DEATH = "die1";
public Alien() {
super("alien", 1);
// Set up score
deathScore = 10;
// Set up animations
animIdle = new AnimationEx(1 / 6f, ANIM_IDLE, TEXTURE_ATLAS_NAME);
animWalk = new AnimationEx(1 / 6f, ANIM_WALK, TEXTURE_ATLAS_NAME);
animHurt = new AnimationEx(1 / 6f, ANIM_HURT, TEXTURE_ATLAS_NAME);
animJump = new AnimationEx(1 / 6f, ANIM_JUMP, TEXTURE_ATLAS_NAME);
animDeath = new AnimationEx(1 / 10f, ANIM_DEATH, TEXTURE_ATLAS_NAME);
animCast = new AnimationEx[1];
animCast[0] = new AnimationEx(1 / 10f, ANIM_ATTACK, TEXTURE_ATLAS_NAME);
hitboxOffset.set(-aabb.getWidth() / 2f, 0);
renderOffset = 0;
// Initialize sprite stuff
this.sprite = new SpriteEx(animIdle.getKeyFrame(animStateTime, true));
// Knock back values
kbDuration = 0.4f;
kbDistance = 25f;
kbThreshold = 15;
// Combat stats
baseDamage = 10;
baseHealth = 75;
speed = 2 + MathUtils.random(-0.5f, 0.5f);
damageMultiplier = 1;
aimRadius = 95;
attackRange = 500;
// Jump parameters
maxJumps = 1;
jumpCounter = 0;
jumpState = 0;
jumpMultiplier = 1.2f;
jumpTime = 3f;
// Speed parameters
patrolSpeed = 2.0f;
chaseSpeed = 3.0f;
// Sound
dieSnd = "alien_die";
hitSnd = "alien_hit";
// Magic skills and stuff
skills.setInventory(0, "iceball");
}
}
| true
|
272291f8fcfb9819ae514a0ca21ef8768478aa98
|
Java
|
nanter1986/chaniagameB
|
/app/src/main/java/chaniagame/nanter1986/com/chaniagame/akrotiri/AkrotiriTen.java
|
UTF-8
| 2,104
| 1.992188
| 2
|
[] |
no_license
|
package chaniagame.nanter1986.com.chaniagame.akrotiri;
import android.view.View;
import chaniagame.nanter1986.com.chaniagame.JukeBox;
import chaniagame.nanter1986.com.chaniagame.R;
import chaniagame.nanter1986.com.chaniagame.RoomMaker;
import chaniagame.nanter1986.com.chaniagame.stories.RingStory;
import chaniagame.nanter1986.com.chaniagame.xaniacity.Ktel;
/**
* Created by nanter1986 on 18/8/2016.
*/
public class AkrotiriTen extends RoomMaker {
@Override
public void north(View north) {
intentCreator(this,AkrotiriNine.class);
}
@Override
public void south(View south) {
}
@Override
public void west(View west) {
}
@Override
public void east(View east) {
}
@Override
public void investigate(View investigate) {
}
@Override
public void setBack() {
b.setImageResource(R.drawable.akrotiriten);
}
@Override
public void setStartingTextOptions() {
if(esH.readEvent("talisman").equals("yes")){
esH.updateEvent("talisman","used");
dialogCreator("That's impossible...\nIt's not over yet...\nYou will hear from me sooooon....", R.drawable.blackcoat, "green");
bForward.setText(">>");
bForward.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
talisman();
}
});
}else {
esH.updateEvent("akrotiriairportfirst","yes");
dialogCreator("I will not allow you to succeed.\nYou have no power over me in this mind.", R.drawable.blackcoat, "green");
exitForward();
}
}
private void talisman() {
intentCreator(this,RingStory.class);
}
@Override
public void onNavOn() {
navigationAssigner(true,false,false,false);
}
@Override
public void setAreaSong() {
areasong= JukeBox.HELPINGHAND;
esH.updateEvent("song",areasong.getName());
}
}
| true
|
44e652ade44bb70a0df46e5f0006e149d1f00857
|
Java
|
zhangliangnbu/android-develop-art_study
|
/app/src/main/java/com/tech/heathcilff/androiddevelopart/Intents.java
|
UTF-8
| 1,348
| 2.09375
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.tech.heathcilff.androiddevelopart;
import android.content.Context;
import android.content.Intent;
import com.tech.heathcilff.androiddevelopart.aidl.BookManagerActivity;
import com.tech.heathcilff.androiddevelopart.messenger.MessengerActivity;
import com.tech.heathcilff.androiddevelopart.provider.BookProviderActivity;
/**
*
* Created by zhangliang on 24/08/2017.
*/
public class Intents {
public static Intent toSecondActivity(Context context) {
return new Intent(context, SecondActivity.class);
}
public static Intent toThirdActivity(Context context) {
return new Intent(context, ThirdActivity.class);
}
public static Intent toFourthActivity(Context context) {
return new Intent(context, FourthActivity.class);
}
public static Intent toFifthActivity(Context context) {
return new Intent(context, FifthIPCActivity.class);
}
public static Intent toSixthhActivity(Context context) {
return new Intent(context, SixthIPCActivity.class);
}
public static Intent toBookManagerActivity(Context context) {
return new Intent(context, BookManagerActivity.class);
}
public static Intent toMessengerActivity(Context context) {
return new Intent(context, MessengerActivity.class);
}
public static Intent toBookProviderPage(Context context) {
return new Intent(context, BookProviderActivity.class);
}
}
| true
|
a88637a05f67bbdbe479ae98cdb95c3d6a0b7f0e
|
Java
|
boomya/practice
|
/test-case/src/main/java/net/shan/practice/usage/App.java
|
UTF-8
| 390
| 2.078125
| 2
|
[] |
no_license
|
package net.shan.practice.usage;
/**
* Created by sam.js on 14-1-13.
*/
public class App {
public static void main(String[] args){
System.out.println("a=====================");
UsageStatic us = new UsageStatic();
UsageStatic us2 = new UsageStatic();
UsageStatic us3 = new UsageStatic();
System.out.println("b=====================");
}
}
| true
|
fa6beb996cea86646f7a40f0de8f40de74801d5b
|
Java
|
gg15137/s2-easy-buy
|
/src/com/buy/web/HomeServlet.java
|
UTF-8
| 1,296
| 2.1875
| 2
|
[] |
no_license
|
package com.buy.web;
import com.buy.entity.EasybuyProductCategory;
import com.buy.service.product.IProductCategoryService;
import com.buy.service.product.ProductCatrgoryServiceImpl;
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.List;
@WebServlet(name = "HomeServlet",urlPatterns = {"/home"})
public class HomeServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//从service层获取数据
IProductCategoryService productCategoryService = new ProductCatrgoryServiceImpl();
List<EasybuyProductCategory> categories = productCategoryService.queryAllproductCategory("0");
//存储数据
request.setAttribute("categories",categories);
//携带数据跳转到home.jsp,传递数据
request.getRequestDispatcher("/frot/Index.jsp").forward(request,response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
}
| true
|
8590b3530f2d1b3af3ddacf3749f48574be6efa7
|
Java
|
osivia/toutatice-cms
|
/toutatice-portail-cms-nuxeo-web/src/main/java/fr/toutatice/portail/cms/nuxeo/portlets/customizer/CMSCustomizer.java
|
UTF-8
| 1,425
| 1.898438
| 2
|
[] |
no_license
|
/*
* (C) Copyright 2014 Académie de Rennes (http://www.ac-rennes.fr/), OSIVIA (http://www.osivia.com) and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser General Public License
* (LGPL) version 2.1 which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl-2.1.html
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
*
*
*/
package fr.toutatice.portail.cms.nuxeo.portlets.customizer;
import javax.portlet.PortletContext;
import fr.toutatice.portail.cms.nuxeo.portlets.service.CMSService;
/**
* Ce customizer permet de définir :
*
* de nouveaux templates de listes
* le schéma du moteur de recherche
* les templates de contenu
*
* Le template d'affichage par défaut est WEB-INF/jsp/liste/view-[nom-du-template].jsp
*
* @author jeanseb
* @see DefaultCMSCustomizer
*/
public class CMSCustomizer extends DefaultCMSCustomizer {
/**
* Constructor.
*
* @param portletContext portlet context
* @param cmsService CMS service
*/
public CMSCustomizer(PortletContext portletContext, CMSService cmsService) {
super(portletContext, cmsService);
}
}
| true
|
88fda714504f05f7e75a8b18f0e30b49da3a5ffb
|
Java
|
kakaxicm/SignSdk
|
/qicode-sign/src/main/java/com/qicode/mylibrary/model/ChargeResponse.java
|
UTF-8
| 16,895
| 1.976563
| 2
|
[] |
no_license
|
package com.qicode.mylibrary.model;
import java.util.List;
/**
* Created by star on 15/10/24.
*/
public class ChargeResponse extends BaseResponse {
private ResultEntity result;
public void setResult(ResultEntity result) {
this.result = result;
}
public ResultEntity getResult() {
return result;
}
public static class ResultEntity {
private ChargeEntity charge;
public void setCharge(ChargeEntity charge) {
this.charge = charge;
}
public ChargeEntity getCharge() {
return charge;
}
public static class ChargeEntity {
private String order_no;
private ExtraEntity extra;
private String app;
private boolean livemode;
private String currency;
private Object time_settle;
private int time_expire;
private String id;
private String subject;
private Object failure_msg;
private String channel;
private MetadataEntity metadata;
private String body;
private CredentialEntity credential;
private String client_ip;
private Object description;
private int amount_refunded;
private boolean refunded;
private String object;
private boolean paid;
private int amount_settle;
private Object time_paid;
private Object failure_code;
private RefundsEntity refunds;
private int created;
private Object transaction_no;
private int amount;
public void setOrder_no(String order_no) {
this.order_no = order_no;
}
public void setExtra(ExtraEntity extra) {
this.extra = extra;
}
public void setApp(String app) {
this.app = app;
}
public void setLivemode(boolean livemode) {
this.livemode = livemode;
}
public void setCurrency(String currency) {
this.currency = currency;
}
public void setTime_settle(Object time_settle) {
this.time_settle = time_settle;
}
public void setTime_expire(int time_expire) {
this.time_expire = time_expire;
}
public void setId(String id) {
this.id = id;
}
public void setSubject(String subject) {
this.subject = subject;
}
public void setFailure_msg(Object failure_msg) {
this.failure_msg = failure_msg;
}
public void setChannel(String channel) {
this.channel = channel;
}
public void setMetadata(MetadataEntity metadata) {
this.metadata = metadata;
}
public void setBody(String body) {
this.body = body;
}
public void setCredential(CredentialEntity credential) {
this.credential = credential;
}
public void setClient_ip(String client_ip) {
this.client_ip = client_ip;
}
public void setDescription(Object description) {
this.description = description;
}
public void setAmount_refunded(int amount_refunded) {
this.amount_refunded = amount_refunded;
}
public void setRefunded(boolean refunded) {
this.refunded = refunded;
}
public void setObject(String object) {
this.object = object;
}
public void setPaid(boolean paid) {
this.paid = paid;
}
public void setAmount_settle(int amount_settle) {
this.amount_settle = amount_settle;
}
public void setTime_paid(Object time_paid) {
this.time_paid = time_paid;
}
public void setFailure_code(Object failure_code) {
this.failure_code = failure_code;
}
public void setRefunds(RefundsEntity refunds) {
this.refunds = refunds;
}
public void setCreated(int created) {
this.created = created;
}
public void setTransaction_no(Object transaction_no) {
this.transaction_no = transaction_no;
}
public void setAmount(int amount) {
this.amount = amount;
}
public String getOrder_no() {
return order_no;
}
public ExtraEntity getExtra() {
return extra;
}
public String getApp() {
return app;
}
public boolean isLivemode() {
return livemode;
}
public String getCurrency() {
return currency;
}
public Object getTime_settle() {
return time_settle;
}
public int getTime_expire() {
return time_expire;
}
public String getId() {
return id;
}
public String getSubject() {
return subject;
}
public Object getFailure_msg() {
return failure_msg;
}
public String getChannel() {
return channel;
}
public MetadataEntity getMetadata() {
return metadata;
}
public String getBody() {
return body;
}
public CredentialEntity getCredential() {
return credential;
}
public String getClient_ip() {
return client_ip;
}
public Object getDescription() {
return description;
}
public int getAmount_refunded() {
return amount_refunded;
}
public boolean isRefunded() {
return refunded;
}
public String getObject() {
return object;
}
public boolean isPaid() {
return paid;
}
public int getAmount_settle() {
return amount_settle;
}
public Object getTime_paid() {
return time_paid;
}
public Object getFailure_code() {
return failure_code;
}
public RefundsEntity getRefunds() {
return refunds;
}
public int getCreated() {
return created;
}
public Object getTransaction_no() {
return transaction_no;
}
public int getAmount() {
return amount;
}
public static class ExtraEntity {
}
public static class MetadataEntity {
}
public static class CredentialEntity {
private String object;
private AlipayEntity alipay;
private BfbEntity bfb;
private WxEntity wx;
public void setObject(String object) {
this.object = object;
}
public void setAlipay(AlipayEntity alipay) {
this.alipay = alipay;
}
public void setBfb(BfbEntity bfb) {
this.bfb = bfb;
}
public void setWx(WxEntity wx) {
this.wx = wx;
}
public String getObject() {
return object;
}
public AlipayEntity getAlipay() {
return alipay;
}
public BfbEntity getBfb() {
return bfb;
}
public WxEntity getWx() {
return wx;
}
public static class AlipayEntity {
private String orderInfo;
public void setOrderInfo(String orderInfo) {
this.orderInfo = orderInfo;
}
public String getOrderInfo() {
return orderInfo;
}
}
public static class BfbEntity {
private String pay_type;
private String goods_name;
private String order_create_time;
private int total_amount;
private String order_no;
private String extra;
private String input_charset;
private String sp_no;
private String service_code;
private String goods_desc;
private String sign;
private String currency;
private String version;
private String sign_method;
private String expire_time;
private String return_url;
public void setPay_type(String pay_type) {
this.pay_type = pay_type;
}
public void setGoods_name(String goods_name) {
this.goods_name = goods_name;
}
public void setOrder_create_time(String order_create_time) {
this.order_create_time = order_create_time;
}
public void setTotal_amount(int total_amount) {
this.total_amount = total_amount;
}
public void setOrder_no(String order_no) {
this.order_no = order_no;
}
public void setExtra(String extra) {
this.extra = extra;
}
public void setInput_charset(String input_charset) {
this.input_charset = input_charset;
}
public void setSp_no(String sp_no) {
this.sp_no = sp_no;
}
public void setService_code(String service_code) {
this.service_code = service_code;
}
public void setGoods_desc(String goods_desc) {
this.goods_desc = goods_desc;
}
public void setSign(String sign) {
this.sign = sign;
}
public void setCurrency(String currency) {
this.currency = currency;
}
public void setVersion(String version) {
this.version = version;
}
public void setSign_method(String sign_method) {
this.sign_method = sign_method;
}
public void setExpire_time(String expire_time) {
this.expire_time = expire_time;
}
public void setReturn_url(String return_url) {
this.return_url = return_url;
}
public String getPay_type() {
return pay_type;
}
public String getGoods_name() {
return goods_name;
}
public String getOrder_create_time() {
return order_create_time;
}
public int getTotal_amount() {
return total_amount;
}
public String getOrder_no() {
return order_no;
}
public String getExtra() {
return extra;
}
public String getInput_charset() {
return input_charset;
}
public String getSp_no() {
return sp_no;
}
public String getService_code() {
return service_code;
}
public String getGoods_desc() {
return goods_desc;
}
public String getSign() {
return sign;
}
public String getCurrency() {
return currency;
}
public String getVersion() {
return version;
}
public String getSign_method() {
return sign_method;
}
public String getExpire_time() {
return expire_time;
}
public String getReturn_url() {
return return_url;
}
}
public static class WxEntity {
private String packageValue;
private int timeStamp;
private String sign;
private String partnerId;
private String appId;
private String prepayId;
private String nonceStr;
public void setPackageValue(String packageValue) {
this.packageValue = packageValue;
}
public void setTimeStamp(int timeStamp) {
this.timeStamp = timeStamp;
}
public void setSign(String sign) {
this.sign = sign;
}
public void setPartnerId(String partnerId) {
this.partnerId = partnerId;
}
public void setAppId(String appId) {
this.appId = appId;
}
public void setPrepayId(String prepayId) {
this.prepayId = prepayId;
}
public void setNonceStr(String nonceStr) {
this.nonceStr = nonceStr;
}
public String getPackageValue() {
return packageValue;
}
public int getTimeStamp() {
return timeStamp;
}
public String getSign() {
return sign;
}
public String getPartnerId() {
return partnerId;
}
public String getAppId() {
return appId;
}
public String getPrepayId() {
return prepayId;
}
public String getNonceStr() {
return nonceStr;
}
}
}
public static class RefundsEntity {
private String url;
private boolean has_more;
private String object;
private List<?> data;
public void setUrl(String url) {
this.url = url;
}
public void setHas_more(boolean has_more) {
this.has_more = has_more;
}
public void setObject(String object) {
this.object = object;
}
public void setData(List<?> data) {
this.data = data;
}
public String getUrl() {
return url;
}
public boolean isHas_more() {
return has_more;
}
public String getObject() {
return object;
}
public List<?> getData() {
return data;
}
}
}
}
}
| true
|
fc961bde12934f305401aba32d8724e8ecbdc4ba
|
Java
|
ruhimbazabertin/springWeb
|
/src/main/java/com/spring/spring5webapp/repository/BookRepository.java
|
UTF-8
| 224
| 1.734375
| 2
|
[] |
no_license
|
package com.spring.spring5webapp.repository;
import com.spring.spring5webapp.model.Book;
import org.springframework.data.repository.CrudRepository;
public interface BookRepository extends CrudRepository<Book, Integer>{
}
| true
|
c3e829c819f87f09649c10b2b891b9145fac22c9
|
Java
|
StefanoRUsai/Progetto_Ium
|
/app/src/main/java/com/example/st3/coinquiapp/activity/Turni.java
|
UTF-8
| 7,967
| 2.28125
| 2
|
[] |
no_license
|
package com.example.st3.coinquiapp.activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.Toolbar;
import com.example.st3.coinquiapp.R;
import com.github.sundeepk.compactcalendarview.CompactCalendarView;
import com.github.sundeepk.compactcalendarview.domain.Event;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class Turni extends AppCompatActivity {
CompactCalendarView compactCalendar;
private SimpleDateFormat dateFormatMonth = new SimpleDateFormat("MMMM- yyyy", Locale.getDefault());
TextView mese;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_turni);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mese = (TextView) findViewById(R.id.textView3);
String meseAttuale = dateFormatMonth.format(new Date());
mese.setText(meseAttuale);
FloatingActionButton mShowDialog = (FloatingActionButton) findViewById(R.id.floatingActionButton2);
mShowDialog.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
AlertDialog.Builder mBuilder = new AlertDialog.Builder(Turni.this);
View mView = getLayoutInflater().inflate(R.layout.turni_dialog, null);
final EditText mTurno = (EditText) mView.findViewById(R.id.turno);
final EditText mData = (EditText) mView.findViewById(R.id.data_turno);
Button mButton = (Button) mView.findViewById(R.id.aggiungi_turno);
mButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(!mTurno.getText().toString().isEmpty() && !mData.getText().toString().isEmpty()){
Toast.makeText(Turni.this, R.string.check_aggiunto, Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(Turni.this, R.string.error_campi, Toast.LENGTH_SHORT).show();
}
Intent intent = new Intent(view.getContext(), Turni.class);
startActivity(intent);
}
});
mBuilder.setView(mView);
AlertDialog dialog = mBuilder.create();
dialog.show();
}
});
// add back arrow to toolbar
if (getSupportActionBar() != null){
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
compactCalendar = (CompactCalendarView) findViewById(R.id.compactcalendar_view);
compactCalendar.setUseThreeLetterAbbreviation(true);
Event ev1 = new Event(Color.BLUE, 1517788800000L, "Turno piatti Alessandro");
Event ev2 = new Event(Color.YELLOW, 1518048000000L, "Turno bagno Stefano");
Event ev3 = new Event(Color.GREEN, 1518134400000L, "Turno pulizie corridoio Marta");
Event ev4 = new Event(Color.BLUE, 1518220800000L, "Turno cucina Giorgia");
compactCalendar.addEvent(ev1);
compactCalendar.addEvent(ev2);
compactCalendar.addEvent(ev3);
compactCalendar.addEvent(ev4);
compactCalendar.setListener(new CompactCalendarView.CompactCalendarViewListener() {
@Override
public void onDayClick(Date dateClicked) {
Context context = getApplicationContext();
if (dateClicked.toString().compareTo("Mon Feb 05 00:00:00 GMT+00:00 2018") == 0) {
Toast.makeText(context, "Turno piatti Alessandro", Toast.LENGTH_SHORT).show();
} else {
if (dateClicked.toString().compareTo("Fri Feb 09 00:00:00 GMT+00:00 2018") == 0) {
Toast.makeText(context, "Turno bagno Stefano", Toast.LENGTH_SHORT).show();
} else {
if (dateClicked.toString().compareTo("Sat Feb 10 00:00:00 GMT+00:00 2018") == 0) {
Toast.makeText(context, "Turno pulizie corridoio Marta", Toast.LENGTH_SHORT).show();
} else {
if (dateClicked.toString().compareTo("Thu Feb 08 00:00:00 GMT+00:00 2018") == 0) {
Toast.makeText(context, "Turno cucina Giorgia", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "Non ci sono turni in questo momento", Toast.LENGTH_SHORT).show();
AlertDialog.Builder mBuilder = new AlertDialog.Builder(Turni.this);
View mView = getLayoutInflater().inflate(R.layout.turni_dialog, null);
final EditText mTurno = (EditText) mView.findViewById(R.id.turno);
final EditText mData = (EditText) mView.findViewById(R.id.data_turno);
Button mButton = (Button) mView.findViewById(R.id.aggiungi_turno);
mButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(!mTurno.getText().toString().isEmpty() && !mData.getText().toString().isEmpty()){
Toast.makeText(Turni.this, R.string.check_aggiunto, Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(Turni.this, R.string.error_campi, Toast.LENGTH_SHORT).show();
}
Intent intent = new Intent(view.getContext(), Turni.class);
startActivity(intent);
}
});
mBuilder.setView(mView);
AlertDialog dialog = mBuilder.create();
dialog.show();
}
}
}
}
}
@Override
public void onMonthScroll (Date firstDayOfNewMonth){
mese.setText(dateFormatMonth.format(firstDayOfNewMonth));
}
});
}
private void setSupportActionBar(Toolbar toolbar) {
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
if (item.getItemId() == android.R.id.home) {
finish(); // close this activity and return to preview activity (if there is any)
}
return super.onOptionsItemSelected(item);
}
}
| true
|
2c0508bcfb7cf9e2ff07b63bf8306e7f66a58cf6
|
Java
|
KNOLSKAPE/kaltura-video-player-ui-android
|
/kalturavideoplayer/src/main/java/com/knolskape/kalturavideoplayer/kaltura/KalturaVideoPlayer.java
|
UTF-8
| 24,600
| 1.65625
| 2
|
[] |
no_license
|
package com.knolskape.kalturavideoplayer.kaltura;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.PorterDuff;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import androidx.constraintlayout.widget.ConstraintLayout;
import com.kaltura.playkit.PKMediaConfig;
import com.kaltura.playkit.PKMediaEntry;
import com.kaltura.playkit.PKMediaFormat;
import com.kaltura.playkit.PKMediaSource;
import com.kaltura.playkit.PKPluginConfigs;
import com.kaltura.playkit.PlayKitManager;
import com.kaltura.playkit.Player;
import com.kaltura.playkit.PlayerEvent;
import com.kaltura.playkit.player.AudioTrack;
import com.kaltura.playkit.player.SubtitleStyleSettings;
import com.kaltura.playkit.player.TextTrack;
import com.kaltura.playkit.player.VideoTrack;
import com.knolskape.kalturavideoplayer.R;
import com.squareup.picasso.Callback;
import com.squareup.picasso.NetworkPolicy;
import com.squareup.picasso.OkHttp3Downloader;
import com.squareup.picasso.Picasso;
import org.joda.time.Duration;
import org.joda.time.format.PeriodFormatter;
import org.joda.time.format.PeriodFormatterBuilder;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;
public class KalturaVideoPlayer extends ConstraintLayout {
private ImageView playPauseBtn;
private TextView timeLapsed;
private TextView timeLeft;
private FrameLayout videoView;
private String entryId;
private SeekBar seekBar;
private ImageView thumbnailImage;
private ImageView thumbnailPlayBtn;
private ConstraintLayout videoOverlayControls;
private boolean isTimerTaskActive = false;
private Timer timer;
private TimerTask timerTask;
private Handler handler = new Handler();
private long currentPosition = -1;
private long currentBufferedPosition = -1;
private Player player;
private PKMediaConfig mediaConfig;
private boolean isThumbnailDismissed = false;
private float playbackRate = 1.0f;
private ImageView forwardBtn;
private ConstraintLayout controls;
private boolean isControlsVisible = true;
private long controlsVisibiltyTimestamp = -1;
private ImageView backward10Btn;
private ImageView forward10Btn;
private boolean restorePreviousState = false;
private boolean restoreIsPlaying = false;
private long restoreSeekPos = -1;
private OnPlayerStateChangeListener stateChangeListener;
private List<VideoTrack> videoTracks;
private List<TextTrack> textTracks;
private List<AudioTrack> audioTracks;
private int videoTrackBitrate = 0;
private ArrayList<String> previousSelections;
private Float previousSpeed = null;
private Long startPosition = 0L; // position tp start playback in seconds.
private String sourceURLFormat = "https://cdnapisec.kaltura.com/p/%s/sp/%s/playManifest/entryId/%s/protocol/https/format/mpegdash/a.mp4";
private String thumbnailUrlFormat = "https://cdnapisec.kaltura.com/p/%s/thumbnail/entry_id/%s/width/%d/height/%d";
private String mediaSourceId = "1234";
private String partnerId = null;
private String subPartnerId = null;
public String getSourceUrl() {
return sourceUrl;
}
public void setSourceUrl(String sourceUrl) {
this.sourceUrl = sourceUrl;
}
private String sourceUrl;
private int thumbnailHeight = 768;
private int thumbnailWidth = 1024;
// Time format for time left and time lapsed
PeriodFormatter hhmm = new PeriodFormatterBuilder()
.printZeroAlways()
.minimumPrintedDigits(2)
.appendMinutes()
.appendSeparator(":")
.appendSeconds()
.toFormatter();
final Runnable myRunnable = new Runnable() {
public void run() {
seekBar.setProgress((int) currentPosition);
seekBar.setSecondaryProgress((int) currentBufferedPosition);
long currentPosDuration = player.getCurrentPosition();
// update time lapsed and time left
if(currentPosDuration > 0){
Duration durTimeLapsed = new Duration(currentPosDuration);
timeLapsed.setText(hhmm.print(durTimeLapsed.toPeriod()));
Duration durTimeLeft = new Duration(player.getDuration()
- player.getCurrentPosition());
long timeLeftInSeconds = durTimeLeft.getStandardSeconds();
if(-2147483648L <= timeLeftInSeconds && timeLeftInSeconds <= 2147483647L){
timeLeft.setText(String.format(Locale.getDefault(),
getResources().getString(R.string.time_left_format),
hhmm.print(durTimeLeft.toPeriod())));
}
}
// put the player in replay mode if the video has reached the end
if(currentPosition == 100){
stopTimer();
playPauseBtn
.setImageDrawable(
getContext()
.getDrawable(R.drawable.video_replay));
showControls();
player.setPlaybackRate(1.0f);
backward10Btn.setVisibility(View.GONE);
forward10Btn.setVisibility(View.GONE);
player.pause();
if(stateChangeListener != null){
stateChangeListener.onPause();
}
}
// automatically close the video controls after 3s
// unless it is paused (or in replay mode)
if(currentPosition != 100){
if(isControlsVisible){
if(controlsVisibiltyTimestamp == -1 ||
(System.currentTimeMillis() - controlsVisibiltyTimestamp >= 5000)){
hideControls();
isControlsVisible = false;
}
}
}
}
};
public void setStartPosition(Long startPosition) {
this.startPosition = startPosition;
}
public void setMediaSourceId(String mediaSourceId) {
this.mediaSourceId = mediaSourceId;
}
public void setSubPartnerId(String subPartnerId) {
this.subPartnerId = subPartnerId;
}
public void setPartnerId(String clientId) {
this.partnerId = clientId;
}
public void setThumbnailHeight(int thumbnailHeight) {
this.thumbnailHeight = thumbnailHeight;
}
public void setThumbnailWidth(int thumbnailWidth) {
this.thumbnailWidth = thumbnailWidth;
}
public KalturaVideoPlayer(Context context) {
super(context);
init(context);
}
public KalturaVideoPlayer(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
private void init(Context context){
View.inflate(context, R.layout.kaltura_video_player, this);
playPauseBtn = findViewById(R.id.play_pause_btn);
timeLapsed = findViewById(R.id.time_lapsed);
timeLeft = findViewById(R.id.time_left);
videoView = findViewById(R.id.video_view);
seekBar = findViewById(R.id.seekbar);
thumbnailImage = findViewById(R.id.thmubnail_view);
thumbnailPlayBtn = findViewById(R.id.thumbnail_play_btn);
forwardBtn = findViewById(R.id.forward_btn);
forward10Btn = findViewById(R.id.forward_10);
backward10Btn = findViewById(R.id.rewind_10);
controls = findViewById(R.id.controls);
videoOverlayControls = findViewById(R.id.video_overlay_controls);
}
public void configurePlayer(String entryId,
String partnerId,
String subPartnerId,
String sourceUrl,
int thumbnailHeight,
int thumbnailWidth){
setPartnerId(partnerId);
setSubPartnerId(subPartnerId);
setThumbnailHeight(thumbnailHeight);
setThumbnailWidth(thumbnailWidth);
setSourceUrl(sourceUrl);
player = PlayKitManager.loadPlayer(getContext(), new PKPluginConfigs());
this.entryId = entryId;
OkHttp3Downloader downloader = new OkHttp3Downloader(getContext());
Picasso picasso = new Picasso.Builder(getContext()).downloader(downloader).build();
picasso.setLoggingEnabled(true);
DisplayMetrics metrics = Resources.getSystem().getDisplayMetrics();
String thumbailUrl = getThumbnailUrl(entryId, metrics.widthPixels, metrics.heightPixels);
picasso.load(thumbailUrl).networkPolicy(NetworkPolicy.OFFLINE).into(thumbnailImage, new Callback() {
@Override
public void onSuccess() {
//Offline Cache hit
}
@Override
public void onError(Exception e) {
picasso.load(thumbailUrl).into(thumbnailImage);
}
});
createMediaConfig();
player = PlayKitManager.loadPlayer(getContext(), null);
videoView.addView(player.getView());
addPlayPauseButton();
player.prepare(mediaConfig);
seekBar.getProgressDrawable().setColorFilter(Colors.primaryColor,
PorterDuff.Mode.SRC_ATOP);
seekBar.getThumb().setColorFilter(Colors.primaryColor,
PorterDuff.Mode.SRC_ATOP);
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
long playerSeekTo = (long) (player.getDuration()*((double)progress/100));
if(stateChangeListener != null){
stateChangeListener.onSeek(playerSeekTo, progress, fromUser);
}
if(fromUser){
if(player.isPlaying()){
player.seekTo(playerSeekTo);
}
}
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
thumbnailPlayBtn.setOnClickListener(v -> dismissThumbnailAndStartPlaying());
forwardBtn.setOnClickListener(v -> {
playbackRate += 0.5f;
if(playbackRate >= 2.5f){
playbackRate = 1.0f;
}
player.setPlaybackRate(playbackRate);
Toast.makeText(getContext(), player.getPlaybackRate() +"x", Toast.LENGTH_SHORT).show();
});
videoView.setOnClickListener(v -> toggleControlsVisibility());
controls.setOnClickListener(v -> controlsVisibiltyTimestamp = System.currentTimeMillis());
backward10Btn.setOnClickListener(v -> player.seekTo(player.getCurrentPosition() - 10000));
forward10Btn.setOnClickListener(v -> player.seekTo(player.getCurrentPosition()+10000));
player.addEventListener(event -> {
//Cast event to PlayerEvent.TracksAvailable
PlayerEvent.TracksAvailable tracksAvailable = (PlayerEvent.TracksAvailable) event;
//Get the tracks data object.
videoTracks = tracksAvailable.tracksInfo.getVideoTracks();
textTracks = tracksAvailable.tracksInfo.getTextTracks();
audioTracks = tracksAvailable.tracksInfo.getAudioTracks();
if(previousSelections != null){
for(String uniqueId: previousSelections){
player.changeTrack(uniqueId);
}
previousSelections = null;
}
if(previousSpeed != null){
player.setPlaybackRate(previousSpeed);
previousSpeed = null;
}
}, PlayerEvent.Type.TRACKS_AVAILABLE);
player.getSettings().setSubtitleStyle(new SubtitleStyleSettings("AD")
.setTextColor(Colors.white)
.setBackgroundColor(Colors.black)
.setTextSizeFraction(SubtitleStyleSettings.SubtitleTextSizeFraction.SUBTITLE_FRACTION_100));
player.getSettings().setCea608CaptionsEnabled(true);
player.getView().showVideoSurface();
player.getView().showVideoSubtitles();
if(restorePreviousState){
restoreStateInternal();
}
}
public void dismissThumbnailAndStartPlaying(){
if(!isThumbnailDismissed){
dismissThumbnail();
handlePlayPause();
}
}
private void dismissThumbnail(){
isThumbnailDismissed = true;
thumbnailPlayBtn.setVisibility(GONE);
thumbnailImage.setVisibility(GONE);
}
private void toggleControlsVisibility(){
if(isControlsVisible){
hideControls();
}else{
showControls();
controlsVisibiltyTimestamp = System.currentTimeMillis();
}
isControlsVisible = !isControlsVisible;
}
public void restoreState(long pos, boolean isPlaying,
ArrayList<String> previousSelections,
float previousSpeed){
if(pos != -1) {
restorePreviousState = true;
restoreIsPlaying = isPlaying;
restoreSeekPos = pos;
}
this.previousSelections = previousSelections;
this.previousSpeed = previousSpeed;
}
public void restoreStateInternal(){
if(restoreSeekPos != -1) {
dismissThumbnail();
if(restoreIsPlaying){
handlePlayPause();
}
player.seekTo(restoreSeekPos);
restoreSeekPos = -1;
restoreIsPlaying = false;
restorePreviousState = false;
}
}
public float getPlaybackRate(){
return player != null ? player.getPlaybackRate(): 0f;
}
public void setPlaybackRate(float rate){
player.setPlaybackRate(rate);
}
public List<VideoTrack> getVideoTracks(){
return videoTracks;
}
public List<TextTrack> getTextTracks(){
return textTracks;
}
public List<AudioTrack> getAudioTracks(){
return audioTracks;
}
public void changeTrack(VideoTrack track){
player.changeTrack(track.getUniqueId());
}
public void changeTrack(AudioTrack track){
player.changeTrack(track.getUniqueId());
}
public void changeTrack(TextTrack track){
player.changeTrack(track.getUniqueId());
}
private void createMediaConfig() {
//First. Create PKMediaConfig object.
mediaConfig = new PKMediaConfig();
//Set start position of the media. This will
//automatically start playback from specified position.
mediaConfig.setStartPosition(startPosition);
//Second. Create PKMediaEntry object.
PKMediaEntry mediaEntry = createMediaEntry();
//Add it to the mediaConfig.
mediaConfig.setMediaEntry(mediaEntry);
}
private void addPlayPauseButton() {
//Get reference to the play/pause button.
//Add clickListener.
playPauseBtn.setOnClickListener(v -> handlePlayPause());
player.addEventListener(event -> {
});
player.addStateChangeListener(event -> {
});
}
private void handlePlayPause(){
backward10Btn.setVisibility(View.VISIBLE);
forward10Btn.setVisibility(View.VISIBLE );
if (player.isPlaying()) {
playPauseBtn
.setImageDrawable(
getContext()
.getDrawable(R.drawable.video_play));
player.pause();
if(stateChangeListener != null){
stateChangeListener.onPause();
}
stopTimer();
showControls();
} else {
playPauseBtn
.setImageDrawable(
getContext()
.getDrawable(R.drawable.video_pause));
if(currentPosition == 100){
player.replay();
if(stateChangeListener != null){
stateChangeListener.onReplay();
}
}else{
player.play();
if(stateChangeListener != null){
stateChangeListener.onPlay();
}
}
startTimer();
}
}
private PKMediaEntry createMediaEntry() {
//Create media entry.
PKMediaEntry mediaEntry = new PKMediaEntry();
//Set id for the entry.
mediaEntry.setId(entryId);
//Set media entry type. It could be Live,Vod or Unknown.
//In this sample we use Vod.
mediaEntry.setMediaType(PKMediaEntry.MediaEntryType.Vod);
//Create list that contains at least 1 media source.
//Each media entry can contain a couple of different media sources.
//All of them represent the same content, the difference is in it format.
//For example same entry can contain PKMediaSource with dash and another
// PKMediaSource can be with hls. The player will decide by itself which source is
// preferred for playback.
List<PKMediaSource> mediaSources = createMediaSources();
//Set media sources to the entry.
mediaEntry.setSources(mediaSources);
return mediaEntry;
}
private List<PKMediaSource> createMediaSources() {
//Init list which will hold the PKMediaSources.
List<PKMediaSource> mediaSources = new ArrayList<>();
//Create new PKMediaSource instance.
PKMediaSource mediaSource = new PKMediaSource();
//Set the id.
mediaSource.setId(mediaSourceId);
//Set the content url. In our case it will be link to hls source(.m3u8).
mediaSource.setUrl(getUrl(entryId));
//Set the format of the source. In our case it will be hls in case of mpd/wvm formats you have to to call mediaSource.setDrmData method as well
mediaSource.setMediaFormat(PKMediaFormat.dash);
//Add media source to the list.
mediaSources.add(mediaSource);
return mediaSources;
}
private String getUrl(String id){
if(sourceUrl != null){
return sourceUrl;
}else{
return String.format(Locale.getDefault(), sourceURLFormat, partnerId, subPartnerId, id);
}
}
public String getThumbnailUrl(String id, int width, int height){
if(width <= 0){
width = 400;
}
if(height <= 0){
height = 200;
}
return String.format(Locale.getDefault(), thumbnailUrlFormat, partnerId, id, width, height);
}
private void startTimer(){
isTimerTaskActive = true;
timer = new Timer();
timerTask = new TimerTask() {
@Override
public void run() {
updateUI();
}
};
timer.schedule(timerTask, 0, 50);
}
private void updateUI(){
double durationPercentage = ((double)player.getCurrentPosition()/player.getDuration())*100.0;
double durationBufferedPercentage = ((double)player.getBufferedPosition()/player.getDuration())*100.0;
if(durationPercentage < 0 || durationBufferedPercentage < 0){
return;
}
currentPosition = (int) durationPercentage;
// mark video completed if the duration left is less than 30s or 90% video is over
long diff = player.getDuration() - player.getCurrentPosition();
if(diff < 30000 || durationPercentage > 90){
stateChangeListener.onEnd();
}
currentBufferedPosition = (int) durationBufferedPercentage;
handler.post(myRunnable);
}
private void hideControls(){
controls.animate().alpha(0.0f).setDuration(500);
videoOverlayControls.animate().alpha(0.0f).setDuration(500);
if(stateChangeListener != null){
stateChangeListener.onControlsHide();
}
}
private void showControls(){
controls.animate().alpha(1.0f).setDuration(500);
videoOverlayControls.animate().alpha(1.0f).setDuration(500);
if(stateChangeListener != null){
stateChangeListener.onControlsShow();
}
}
private void stopTimer(){
isTimerTaskActive = false;
if(timer != null){
timer.cancel();
timer.purge();
}
}
public void destroy(){
if(player != null){
player.destroy();
}
}
public void stop(){
if(player != null){
player.stop();
}
}
public long getCurrentPosition(){
return player != null ? player.getCurrentPosition():-1;
}
public boolean getIsPlaying(){
return player.isPlaying();
}
public boolean isTimerTaskActive() {
return isTimerTaskActive;
}
public void addStateChangeListener(OnPlayerStateChangeListener listener){
stateChangeListener = listener;
}
public void destroyPlayer(){
if(player != null){
player.destroy();
}
stopTimer();
}
public interface OnPlayerStateChangeListener{
void onPause();
void onPlay();
void onReplay();
void onSeek(long seekPos, int completionPercentage, boolean fromUser);
void onControlsShow();
void onControlsHide();
void onEnd();
}
public static enum KalturaOptions{
SPEED("Speed"),
SUBTITLES("Subtitles"),
QUALITY("Quality"),
AUDIO("Audio");
private String displayName;
public String getDisplayName()
{
return this.displayName;
}
private KalturaOptions(String displayName) {
this.displayName = displayName;
}
}
public static enum KalturaVideoSpeed{
SLOWEST(0.5f, "0.5x"),
SLOW(0.75f, "0.75x"),
NORMAL(1f, "1.0x"),
FAST(1.25f,"1.25x"),
FASTER(1.5f, "1.5x"),
FASTEST(2.0f, "2.0x");
private float speed;
public float getSpeed() {
return speed;
}
public String getDisplayName() {
return displayName;
}
private String displayName;
private KalturaVideoSpeed(float speed, String displayName){
this.speed = speed;
this.displayName = displayName;
}
}
public static class KalturaPlayerConfig{
String partnerId;
String subPartnerId;
boolean autoplay;
String mediaSourceId;
long startPosition;
String entryId;
String sourceUrl;
int thumbnailHeight;
int thumbnailWidth;
public KalturaPlayerConfig(String partnerId, String subPartnerId, boolean autoplay, String mediaSourceId, long startPosition, String entryId, String sourceUrl, int thumbnailHeight, int thumbnailWidth) {
this.partnerId = partnerId;
this.subPartnerId = subPartnerId;
this.autoplay = autoplay;
this.mediaSourceId = mediaSourceId;
this.startPosition = startPosition;
this.entryId = entryId;
this.sourceUrl = sourceUrl;
this.thumbnailHeight = thumbnailHeight;
this.thumbnailWidth = thumbnailWidth;
}
public String getPartnerId() {
return partnerId;
}
public String getSubPartnerId() {
return subPartnerId;
}
public boolean isAutoplay() {
return autoplay;
}
public String getMediaSourceId() {
return mediaSourceId;
}
public long getStartPosition() {
return startPosition;
}
public String getEntryId() {
return entryId;
}
public String getSourceUrl() {
return sourceUrl;
}
public int getThumbnailHeight() {
return thumbnailHeight;
}
public int getThumbnailWidth() {
return thumbnailWidth;
}
}
}
| true
|