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
1853702e98d1dcf87b765c5d38e89369b8c7ce07
Java
TrueBrain/xabrain
/mods/transport/ContainerConnector.java
UTF-8
1,007
2.375
2
[]
no_license
package xabrain.mods.transport; import net.minecraft.src.Container; import net.minecraft.src.EntityPlayer; import net.minecraft.src.InventoryPlayer; import net.minecraft.src.Slot; public class ContainerConnector extends Container { private Connector connector; public int selected; public ContainerConnector(InventoryPlayer inventoryPlayer, Connector connector) { this.connector = connector; this.selected = -1; /* Module slots */ int top = (18 * 4 - 18 * connector.slots) / 2; for (int i = 0; i < connector.slots; i++) { this.addSlot(new SlotModule(connector, i, 8, 7 + top + i * 18)); } /* Inventory slots */ for (int i = 0; i < 3; i++) { for (int j = 0; j < 9; j++) { this.addSlot(new Slot(inventoryPlayer, j + i * 9 + 9, 8 + j * 18, 84 + i * 18)); } } /* Equipped slots */ for (int i = 0; i < 9; i++) { this.addSlot(new Slot(inventoryPlayer, i, 8 + i * 18, 142)); } } @Override public boolean canInteractWith(EntityPlayer var1) { return true; } }
true
fa743eaac8036ce0a602c68a39a55d6d91a743fc
Java
dstmath/OppoR15
/app/src/main/java/java/beans/ChangeListenerMap.java
UTF-8
4,462
2.546875
3
[]
no_license
package java.beans; import java.util.ArrayList; import java.util.Collections; import java.util.EventListener; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; abstract class ChangeListenerMap<L extends EventListener> { private Map<String, L[]> map; public abstract L extract(L l); protected abstract L[] newArray(int i); protected abstract L newProxy(String str, L l); ChangeListenerMap() { } public final synchronized void add(String name, L listener) { int size; if (this.map == null) { this.map = new HashMap(); } Object array = (EventListener[]) this.map.get(name); if (array != null) { size = array.length; } else { size = 0; } Object clone = newArray(size + 1); clone[size] = listener; if (array != null) { System.arraycopy(array, 0, clone, 0, size); } this.map.put(name, clone); } public final synchronized void remove(String name, L listener) { if (this.map != null) { Object array = (EventListener[]) this.map.get(name); if (array != null) { int i = 0; while (i < array.length) { if (listener.equals(array[i])) { int size = array.length - 1; if (size > 0) { Object clone = newArray(size); System.arraycopy(array, 0, clone, 0, i); System.arraycopy(array, i + 1, clone, i, size - i); this.map.put(name, clone); } else { this.map.remove(name); if (this.map.isEmpty()) { this.map = null; } } } else { i++; } } } } } public final synchronized L[] get(String name) { L[] lArr = null; synchronized (this) { if (this.map != null) { lArr = (EventListener[]) this.map.get(name); } } return lArr; } public final void set(String name, L[] listeners) { if (listeners != null) { if (this.map == null) { this.map = new HashMap(); } this.map.put(name, listeners); } else if (this.map != null) { this.map.remove(name); if (this.map.isEmpty()) { this.map = null; } } } public final synchronized L[] getListeners() { if (this.map == null) { return newArray(0); } List<L> list = new ArrayList(); EventListener[] listeners = (EventListener[]) this.map.get(null); if (listeners != null) { for (L listener : listeners) { list.add(listener); } } for (Entry<String, L[]> entry : this.map.entrySet()) { String name = (String) entry.getKey(); if (name != null) { for (L listener2 : (EventListener[]) entry.getValue()) { list.add(newProxy(name, listener2)); } } } return (EventListener[]) list.toArray(newArray(list.size())); } public final L[] getListeners(String name) { if (name != null) { L[] listeners = get(name); if (listeners != null) { return (EventListener[]) listeners.clone(); } } return newArray(0); } /* JADX WARNING: inconsistent code. */ /* Code decompiled incorrectly, please refer to instructions dump. */ public final synchronized boolean hasListeners(String name) { boolean z = true; synchronized (this) { if (this.map == null) { return false; } else if (((EventListener[]) this.map.get(null)) == null && (name == null || this.map.get(name) == null)) { z = false; } } } public final Set<Entry<String, L[]>> getEntries() { if (this.map != null) { return this.map.entrySet(); } return Collections.emptySet(); } }
true
de31647a8dc78fa8505f5e8dcc942c318d3cc6da
Java
Annooo/xiong_mybatis_plugin
/src/main/java/com/shong/xiong_mybatis_plugin/core/impl/DeleteDynamicSql.java
UTF-8
2,870
2.109375
2
[]
no_license
package com.shong.xiong_mybatis_plugin.core.impl; import com.shong.xiong_mybatis_plugin.annotation.Ignore; import com.shong.xiong_mybatis_plugin.core.AbstractDynamicSql; import org.apache.ibatis.mapping.ResultMap; import org.apache.ibatis.mapping.SqlCommandType; import org.apache.ibatis.mapping.SqlSource; import org.apache.ibatis.scripting.xmltags.*; import org.apache.ibatis.session.SqlSessionFactory; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.List; /** * @auther 10349 XIONGSY * @create 2021/8/4 */ public class DeleteDynamicSql extends AbstractDynamicSql { @Override public String getId(Class intfClass) { return intfClass.getCanonicalName() + ".dynamicDelete"; } @Override public SqlCommandType getSqlCommandType() { return SqlCommandType.DELETE; } private String getIfContent(Field field) { String ifContent = " and " + getColumnName(field) + " = #{" + field.getName() + "}"; return ifContent; } public SqlNode handlerIfMixedSqlNode(Class clazz) { List<SqlNode> contents = new ArrayList<>(); for (Field field : clazz.getDeclaredFields()) { if (field.isAnnotationPresent(Ignore.class)) { continue; } List<SqlNode> ifChildContents = new ArrayList<>(); ifChildContents.add(new StaticTextSqlNode(getIfContent(field))); MixedSqlNode ifMixedSqlNode = new MixedSqlNode(ifChildContents); IfSqlNode ifSqlNode = new IfSqlNode(ifMixedSqlNode, field.getName() + " != null and " + field.getName() + " != ''"); contents.add(ifSqlNode); } return new MixedSqlNode(contents); } private SqlNode getTrimSqlNode(SqlSessionFactory sqlSessionFactory,Class clazz) { SqlNode sqlNode = handlerIfMixedSqlNode(clazz); return new TrimSqlNode(sqlSessionFactory.getConfiguration(), sqlNode, "WHERE", "AND|OR", null, null); } public StringBuffer handlerSql(Class clazz) { StringBuffer sql = new StringBuffer("delete from "); sql.append(getTableName(clazz)); return sql; } @Override public SqlSource sqlSource(SqlSessionFactory sqlSessionFactory, Class genericClazz) { StringBuffer sb = handlerSql(genericClazz); List<SqlNode> contents = new ArrayList<>(); contents.add(new StaticTextSqlNode(sb.toString())); contents.add(getTrimSqlNode(sqlSessionFactory,genericClazz)); MixedSqlNode mixedSqlNode = new MixedSqlNode(contents); SqlSource sqlSource = new DynamicSqlSource(sqlSessionFactory.getConfiguration(), mixedSqlNode); return sqlSource; } @Override public List<ResultMap> getResultMaps(SqlSessionFactory sqlSessionFactory, Class genericClazz, Class<?> intfClass) { return new ArrayList<>(); } }
true
dd38871ea08f01976e1214f54f34fc4111e83529
Java
T-Ford1/FinalProject
/src/frame/Window.java
UTF-8
3,428
2.796875
3
[]
no_license
package frame; import java.awt.Canvas; import java.awt.image.BufferedImage; import components.*; import input.*; import java.awt.Rectangle; import java.awt.image.DataBufferInt; import java.util.ArrayList; /** * * @author ford.terrell */ public class Window extends Canvas { private static final long serialVersionUID = 1L; private static ArrayList<GraphicsComponent> components; public static Keyboard keys; public static Mouse mouse; private static BufferedImage image; private static int[] pixels; public Window() { addKeyListener(keys = new Keyboard()); addMouseListener(mouse = new Mouse()); addMouseMotionListener(mouse); components = new ArrayList<>(); } public void init() { image = new BufferedImage(getSize().width, getSize().height, BufferedImage.TYPE_INT_RGB); pixels = new int[image.getWidth() * image.getHeight()]; pixels = ((DataBufferInt) (image.getRaster().getDataBuffer())).getData(); renderAll(); } public static void renderPixel(int x, int y, int rgb) { renderPixel(x + y * image.getWidth(), rgb); } public static void renderPixel(int index, int rgb) { if (rgb == 0xFF_FF_00_FF) { return; } pixels[index] = rgb; } public static void renderArray(Rectangle img, int[] p) { int xStart = img.x < 0 ? -img.x : 0; //int xStart = (img.x < 0 ? -img.x : 0) + (img.x < bounds.x ? bounds.x - img.x : 0); int yStart = img.y < 0 ? -img.y : 0; int xMax = img.x + img.width >= image.getWidth() ? image.getWidth() -img.x : img.width; int yMax = img.y + img.height >= image.getHeight() ? image.getHeight() -img.y : img.height; int xSkip = xStart + img.width - xMax; int wSkip = image.getWidth() - img.width + xSkip; int index1 = (yStart + img.y) * image.getWidth() + (xStart + img.x), index2 = yStart * img.width + xStart; for (int y = yStart; y < yMax; y++, index1 += wSkip, index2 += xSkip) { for (int x = xStart; x < xMax; x++, index1++, index2++) { renderPixel(index1, p[index2]); } } } public static int getPixel(int x, int y) { return pixels[x + y * image.getWidth()]; } public static void addComponent(GraphicsComponent g) { components.add(g); } public static void removeComponent(GraphicsComponent g) { components.remove(g); } public static void removeAll() { for (int i = 0; i < components.size(); i++) { components.remove(i--); } for (int i = 0; i < pixels.length; i++) { pixels[i] = 0xFF_00_00_00; } } protected static BufferedImage getImage() { return image; } public void update() { for (int i = 0; i < components.size(); i++) { components.get(i).update(); } keys.update(); mouse.update(); } public void render() { for (GraphicsComponent c : components) { if (c.isRender() | c.isAlwaysRender()) { c.render(); } } } public void renderAll() { for (GraphicsComponent c : components) { c.renderAll(); } } }
true
2219e8561719761d70dfd240226d84c228dc0733
Java
GEMLZC/mymafengwo
/trip-artcle-api/src/main/java/cn/wolfcode/luowowo/article/domain/ViewContent.java
UTF-8
299
1.570313
2
[]
no_license
package cn.wolfcode.luowowo.article.domain; import cn.wolfcode.luowowo.common.domain.BaseDomain; import lombok.*; /** * Created by Xhek on 2019/11/24. */ @Setter @Getter @AllArgsConstructor @NoArgsConstructor @ToString public class ViewContent extends BaseDomain { private String content; }
true
6dc16abd551439432ec475ccdae5830b5c4a9c7a
Java
MadMatt25/SWOPProject
/src/tests/UnregisterForNotificationUseCaseTest.java
UTF-8
2,423
2.25
2
[]
no_license
package tests; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import java.util.List; import org.junit.Before; import org.junit.Test; import controllers.exceptions.UnauthorizedAccessException; import model.notifications.IRegistration; import model.notifications.NotificationType; import model.notifications.forms.RegisterNotificationForm; import model.notifications.forms.UnregisterNotificationForm; public class UnregisterForNotificationUseCaseTest extends BugTrapTest { @Before public void setUp() throws UnauthorizedAccessException { super.setUp(); //Log in and register for notifications to be able to unregister userController.loginAs(issuer); RegisterNotificationForm form = notificationController.getRegisterNotificationForm(); form.setObservable(office); form.setNotificationType(NotificationType.CREATE_BUGREPORT); notificationController.registerNotification(form); userController.logOff(); } @Test public void unregisterForNotificationTest() throws UnauthorizedAccessException { //Log in as Administrator. userController.loginAs(issuer); //1. The issuer indicates that he wants to unregister from receiving specific notifications. UnregisterNotificationForm form = notificationController.getUnregisterNotificationForm(); //2. The system shows all active registrationTypes for notifications. List<IRegistration> registrations = null; registrations = notificationController.getRegistrations(); //3. The issuer selects a specific registration. form.setRegistration(registrations.get(0)); //User is registered for one thing. assertEquals(1, notificationController.getRegistrations().size()); //4. The system deactivates the specified registration for notifications. notificationController.unregisterNotification(form); //User is registered for nothing. assertEquals(0, notificationController.getRegistrations().size()); } @Test (expected = UnauthorizedAccessException.class) public void authorisationTest() throws UnauthorizedAccessException { //Can't unregister when not logged in. notificationController.getRegisterNotificationForm(); } @Test (expected = NullPointerException.class) public void varsNotFilledTest() throws UnauthorizedAccessException { //Log in as Administrator. userController.loginAs(admin); notificationController.getUnregisterNotificationForm().allVarsFilledIn(); } }
true
0e1854041a6f1c66802825eede5962d2031906ca
Java
jorge-luque/hb
/sources/com/tapjoy/internal/C5269u.java
UTF-8
835
1.71875
2
[]
no_license
package com.tapjoy.internal; import android.os.Handler; import android.os.Looper; /* renamed from: com.tapjoy.internal.u */ public final class C5269u { /* renamed from: a */ private static Handler f14461a; /* renamed from: a */ public static synchronized Handler m17670a() { Handler handler; synchronized (C5269u.class) { if (f14461a == null) { f14461a = new Handler(Looper.getMainLooper()); } handler = f14461a; } return handler; } /* renamed from: a */ public static C4904ba m17671a(final Handler handler) { return new C4904ba() { /* renamed from: a */ public final boolean mo30981a(Runnable runnable) { return handler.post(runnable); } }; } }
true
168cffefb0b1ec5b61d8af5dfdbdbe6d228ec3e8
Java
saha-arash/saha-backend
/src/test/java/ir/saha/domain/YeganTypeTest.java
UTF-8
705
2.171875
2
[]
no_license
package ir.saha.domain; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import ir.saha.web.rest.TestUtil; public class YeganTypeTest { @Test public void equalsVerifier() throws Exception { TestUtil.equalsVerifier(YeganType.class); YeganType yeganType1 = new YeganType(); yeganType1.setId(1L); YeganType yeganType2 = new YeganType(); yeganType2.setId(yeganType1.getId()); assertThat(yeganType1).isEqualTo(yeganType2); yeganType2.setId(2L); assertThat(yeganType1).isNotEqualTo(yeganType2); yeganType1.setId(null); assertThat(yeganType1).isNotEqualTo(yeganType2); } }
true
8b153d2edc8e9598d279efcde98753ed7b852d2f
Java
combats/ITA-java
/applicants-notification/src/main/java/com/softserveinc/ita/service/impl/MailServiceImpl.java
UTF-8
9,271
1.921875
2
[]
no_license
package com.softserveinc.ita.service.impl; import com.softserveinc.ita.entity.*; import com.softserveinc.ita.service.HttpRequestExecutor; import com.softserveinc.ita.service.MailService; import com.softserveinc.ita.service.exception.HttpRequestException; import com.softserveinc.ita.utils.JsonUtil; import org.apache.camel.Consume; import org.apache.velocity.app.VelocityEngine; import org.joda.time.DateTime; import org.joda.time.format.DateTimeFormatter; import org.joda.time.format.DateTimeFormatterBuilder; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.ClassPathResource; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.stereotype.Service; import org.springframework.ui.velocity.VelocityEngineUtils; import javax.mail.MessagingException; import javax.mail.internet.MimeMessage; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.HashMap; import java.util.Map; @Service public class MailServiceImpl implements MailService { public static final String ENCODING = "UTF-8"; public static final String NAME = "name"; public static final String SURNAME = "surname"; public static final String FROM = "ita@itsve.tk"; public static final String LOGO = "ItAcademyLogo"; public static final String LOGO_IMAGE_REF = "images/joinProfessionals.png"; public static final String TIME = "time"; public static final String COURSE = "course"; public static final String GROUP_START_TIME = "groupStartTime"; public static final String HR_NAME = "HRName"; public static final String HR_SURNAME = "HRSurname"; public static final String HR_PHONE = "HRPhone"; public static final String HR_EMAIL = "HRemail"; public static final String COURSE_ADDRESS = "courseAddress"; public static final String APPLICANT_EMAIL = "applicantEmail"; public static final String GROUP_NAME = "groupName"; @SuppressWarnings("SpringJavaAutowiringInspection") @Autowired private VelocityEngine velocityEngine; @Autowired private JavaMailSender mailSender; @Autowired private HttpRequestExecutor httpRequestExecutor; @Autowired private JsonUtil jsonUtil; private MimeMessageHelper helper; private MimeMessage mimeMessage; @Consume(uri = "activemq:notification.queue") public void notifyApplicant(String notificationJSONInfo) throws HttpRequestException { NotificationJSONInfo notificationInfo = jsonUtil.fromJson(notificationJSONInfo, NotificationJSONInfo.class); mimeMessage = mailSender.createMimeMessage(); try { helper = new MimeMessageHelper(mimeMessage, true); } catch (MessagingException e) { e.printStackTrace(); } String applicantId = notificationInfo.getApplicantId(); String groupId = notificationInfo.getGroupId(); String responsibleHrId = notificationInfo.getResponsibleHrId(); Applicant applicant = httpRequestExecutor.getObjectByID(applicantId, Applicant.class); Group group = httpRequestExecutor.getObjectByID(groupId, Group.class); User responsibleHr = httpRequestExecutor.getObjectByID(responsibleHrId, User.class); Applicant.Status status = group.getApplicants().get(applicantId).getStatus(); switch (status) { case NOT_SCHEDULED: sendNotScheduledLetterModel(applicant, group, responsibleHr); break; case SCHEDULED: sendScheduledLetter(applicant, group, responsibleHr); break; case NOT_PASSED: sendNotPassedLetter(applicant, group); break; case PASSED: sendPassedLetter(applicant, group, responsibleHr); break; case EMPLOYED: sendEmployedLetter(applicant, group, responsibleHr); } } private void sendEmployedLetter(Applicant applicant, Group group, User responsibleHr) { Map<String, Object> model = new HashMap<>(); model.put(NAME, applicant.getName()); model.put(SURNAME, applicant.getSurname()); model.put(HR_NAME, responsibleHr.getName()); model.put(HR_SURNAME, responsibleHr.getSurname()); model.put(HR_PHONE, responsibleHr.getPhone()); model.put(HR_EMAIL, responsibleHr.getEmail()); model.put(APPLICANT_EMAIL, applicant.getEmail()); sendLetter(group.getApplicants().get(applicant.getId()).getStatus(), model); } private void sendNotScheduledLetterModel(Applicant applicant, Group group, User responsibleHr) { Map<String, Object> model = new HashMap<>(); model.put(NAME, applicant.getName()); model.put(SURNAME, applicant.getSurname()); model.put(COURSE, group.getCourse().getName()); model.put(GROUP_NAME, group.getGroupName()); model.put(HR_NAME, responsibleHr.getName()); model.put(HR_SURNAME, responsibleHr.getSurname()); model.put(HR_PHONE, responsibleHr.getPhone()); model.put(HR_EMAIL, responsibleHr.getEmail()); model.put(APPLICANT_EMAIL, applicant.getEmail()); sendLetter(group.getApplicants().get(applicant.getId()).getStatus(), model); } private void sendPassedLetter(Applicant applicant, Group group, User responsibleHr) { Map<String, Object> model = new HashMap<>(); model.put(NAME, applicant.getName()); model.put(SURNAME, applicant.getSurname()); model.put(COURSE, group.getCourse().getName()); model.put(COURSE_ADDRESS, group.getAddress()); model.put(GROUP_START_TIME, convertTimeToDate(group.getStartTime())); model.put(HR_NAME, responsibleHr.getName()); model.put(HR_SURNAME, responsibleHr.getSurname()); model.put(HR_PHONE, responsibleHr.getPhone()); model.put(HR_EMAIL, responsibleHr.getEmail()); model.put(APPLICANT_EMAIL, applicant.getEmail()); sendLetter(group.getApplicants().get(applicant.getId()).getStatus(), model); } private void sendNotPassedLetter(Applicant applicant, Group group) { Map<String, Object> model = new HashMap<>(); model.put(NAME, applicant.getName()); model.put(SURNAME, applicant.getSurname()); model.put(APPLICANT_EMAIL, applicant.getEmail()); sendLetter(group.getApplicants().get(applicant.getId()).getStatus(), model); } private void sendScheduledLetter(Applicant applicant, Group group, User responsibleHr) throws HttpRequestException { Appointment appointment = null; String appointmentID; Map<Class, String> groupAndApplicantIDs = new HashMap<>(); groupAndApplicantIDs.put(Group.class, group.getGroupID()); groupAndApplicantIDs.put(Applicant.class, applicant.getId()); appointmentID = httpRequestExecutor.getListObjectsIdByPrams(Appointment.class, groupAndApplicantIDs); appointment = httpRequestExecutor.getObjectByID(appointmentID, Appointment.class); Map<String, Object> model = new HashMap<>(); model.put(NAME, applicant.getName()); model.put(SURNAME, applicant.getSurname()); model.put(COURSE_ADDRESS, group.getAddress()); model.put(TIME, convertTimeToDate(appointment.getStartTime())); model.put(HR_NAME, responsibleHr.getName()); model.put(HR_SURNAME, responsibleHr.getSurname()); model.put(HR_PHONE, responsibleHr.getPhone()); model.put(HR_EMAIL, responsibleHr.getEmail()); model.put(APPLICANT_EMAIL, applicant.getEmail()); sendLetter(group.getApplicants().get(applicant.getId()).getStatus(), model); } private void sendLetter(Applicant.Status applicantStatus, Map<String, Object> letterModel) { String emailText = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, applicantStatus.getTemplateRef(), ENCODING, letterModel); try { helper.setFrom(FROM); helper.setTo((String) letterModel.get(APPLICANT_EMAIL)); helper.setText(emailText, true); helper.setSubject(applicantStatus.getSubject()); ClassPathResource image = new ClassPathResource(LOGO_IMAGE_REF); helper.addInline(LOGO, image); mailSender.send(mimeMessage); } catch (MessagingException e) { e.printStackTrace(); } } public static String convertTimeToDate(long milliseconds) { DateTime dateTime = new DateTime(milliseconds); DateTimeFormatter fmt = new DateTimeFormatterBuilder() .appendDayOfWeekText() .appendLiteral(", ") .appendDayOfMonth(2) .appendLiteral("/") .appendMonthOfYear(2) .appendLiteral(" ") .appendHourOfDay(2) .appendLiteral(":") .appendMinuteOfHour(2) .toFormatter(); String stringTime = fmt.print(dateTime.getMillis()); return stringTime; } }
true
d7f49056b2d8d5152ff8cb79913656fe5241eac6
Java
Guilhermefcasagrande/api-java-web
/src/main/java/br/edu/unidavi/trabalhofinalapi/domain/repository/ClienteRepository.java
UTF-8
413
1.875
2
[]
no_license
package br.edu.unidavi.trabalhofinalapi.domain.repository; import br.edu.unidavi.trabalhofinalapi.domain.model.Cliente; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; public interface ClienteRepository extends JpaSpecificationExecutor<Cliente>, JpaRepository<Cliente, Long> { Cliente findByCpf(String cnpj); }
true
b276dfc2bf3356f818c89b8f277f60e5f5fdaccb
Java
jianmeichen123/starservice
/src/main/java/com/galaxy/im/business/rili/service/ScheduleDictServiceImpl.java
UTF-8
566
1.90625
2
[]
no_license
package com.galaxy.im.business.rili.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.galaxy.im.bean.schedule.ScheduleDict; import com.galaxy.im.business.rili.dao.IScheduleDictDao; import com.galaxy.im.common.db.service.BaseServiceImpl; @Service public class ScheduleDictServiceImpl extends BaseServiceImpl<ScheduleDict> implements IScheduleDictService{ @Autowired IScheduleDictDao dao; @Override protected IScheduleDictDao getBaseDao() { return dao; } }
true
ff684ca0c0af33bc3fd2848c372b3ada48979d2f
Java
themuks/jwd-final-testing-system
/src/main/java/com/kuntsevich/ts/controller/command/impl/ShowProfileCommand.java
UTF-8
1,560
2.21875
2
[]
no_license
package com.kuntsevich.ts.controller.command.impl; import com.kuntsevich.ts.controller.AttributeName; import com.kuntsevich.ts.controller.PagePath; import com.kuntsevich.ts.controller.ParameterName; import com.kuntsevich.ts.controller.command.Command; import com.kuntsevich.ts.controller.router.Router; import com.kuntsevich.ts.entity.User; import com.kuntsevich.ts.model.service.UserService; import com.kuntsevich.ts.model.service.exception.ServiceException; import com.kuntsevich.ts.model.service.factory.ServiceFactory; import org.apache.log4j.Logger; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; public class ShowProfileCommand implements Command { private static final Logger log = Logger.getLogger(ShowProfileCommand.class); @Override public Router execute(HttpServletRequest request, HttpServletResponse response) { HttpSession session = request.getSession(); Long userId = (Long) session.getAttribute(AttributeName.USER_ID); if (userId == null) { return new Router(PagePath.LOGIN).setRedirect(); } UserService userService = ServiceFactory.getInstance().getUserService(); try { User user = userService.findUserById(userId.toString()); request.setAttribute(ParameterName.USER, user); return new Router(PagePath.PROFILE); } catch (ServiceException e) { log.error(e); return new Router(PagePath.ERROR_500); } } }
true
641c45c3d64260e891caf58d29d0e89278a35570
Java
komamj/KomaWeather
/app/src/main/java/com/koma/weather/util/Utils.java
UTF-8
1,957
2.40625
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2017 Koma * * 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.koma.weather.util; import android.os.Build; /** * Created by koma on 7/22/17. */ public class Utils { /** * API 21 * * @see Build.VERSION_CODES#LOLLIPOP */ public static boolean hasLollipop() { return Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP; } /** * API 23 * * @see Build.VERSION_CODES#M */ public static boolean hasMarshmallow() { return Build.VERSION.SDK_INT >= Build.VERSION_CODES.M; } /** * API 24 * * @see Build.VERSION_CODES#N */ public static boolean hasNougat() { return Build.VERSION.SDK_INT >= Build.VERSION_CODES.N; } public static String getHourTime(String date) { return date.substring(date.length() - 5, date.length()); } public static String formatTemperature(String temperature) { return String.format("%s℃", temperature); } public static String formatHumidity(String humidity) { return String.format("%s%%", humidity); } public static String formatAqi(String aqi) { return String.format("%sμg/m³", aqi); } public static String formatPcpn(String pcpn) { return String.format("%smm", pcpn); } public static String formatVisibility(String visibily) { return String.format("%skm", visibily); } }
true
93159577b88420e6df9b30f0c2d056a83e4a235d
Java
JunHyeok96/algorithm
/2021/2/조이스틱-복습.java
UTF-8
1,132
3.328125
3
[]
no_license
class Solution { public int solution(String name) { int answer = 0; char[] arr = new char[name.length()]; for(int i=0; i < arr.length; i++){ arr[i] = 'A'; } int idx=0; while(!new String(arr).equals(name)){ answer += countControll(name.charAt(idx)); arr[idx] = name.charAt(idx); int right = 0; int left = 0; for(int i=1; i<arr.length; i++){ right = (idx + i)% arr.length; if(arr[right] != name.charAt(right)){ idx = right; answer+=i; break; } left = (idx - i + arr.length) % arr.length; if(arr[left] != name.charAt(left)){ idx = left; answer+=i; break; } } if(right==left){ break; } } return answer; } public int countControll(char dst){ return Math.min(dst - 'A', Math.abs('Z' - dst + 1)); } }
true
58ed55e9b60740dca33a99c02e4b903d4672c492
Java
imathrowback/riftools
/RiftTools/src/org/imathrowback/riftool/actions/ExtractVignettes.java
UTF-8
2,659
2.390625
2
[]
no_license
package org.imathrowback.riftool.actions; import java.io.File; import java.nio.file.Paths; import org.imathrowback.manifest.ReleaseType; import org.kohsuke.args4j.Option; import rift_extractor.Binky; import rift_extractor.assets.AssetDatabase; import rift_extractor.assets.AssetProcessor; import rift_extractor.assets.Manifest; public class ExtractVignettes extends RiftAction { @Option(name = "-convert", usage = "Automatically convert the OGG files to something usuable") boolean autoConvert = false; @Option(name = "-32") boolean is32 = false; @Option(name = "-riftDir", usage = "The RIFT directory (required)", metaVar = "RIFTDIR", required = true) File riftDir; @Option(name = "-outputDir", usage = "The directory to extract to (required)", metaVar = "OUTPUTDIR", required = true) File outputDir; @Option(name = "-release", usage = "Release to extract", required = true) ReleaseType releaseType; public ExtractVignettes() { } @Override public void go() { try { String manifestStr = "assets.manifest"; if (!is32) { manifestStr = "assets64.manifest"; System.out.println("==> Using 64bit manifest, if you have 32bit RIFT installed, use the -32 flag"); } else System.out.println("==> Using 32bit manifest"); File assetsManifest = Paths.get(riftDir.toString(), manifestStr).toFile(); File assetsDirectory = Paths.get(riftDir.toString(), "assets").toFile(); Manifest manifest = new Manifest(assetsManifest.toString()); AssetDatabase adb = AssetProcessor.buildDatabase(manifest, assetsDirectory.toString()); Binky.doVig(manifest, adb, releaseType, outputDir); if (autoConvert) { System.out.println("Doing autoconvert of OGG files to WAV (this may take a while)"); File[] files = outputDir.listFiles(); int totalCount = files.length; int index = 0; int lastP = -1; for (File file : files) { int per = (int) (((float) ++index / (float) totalCount) * 100.0f); if (lastP != per) { if ((per % 25) == 0) System.out.print(per + "%"); else if ((per % 5) == 0) System.out.print("."); lastP = per; } if (file.isFile() && file.getName().endsWith("ogg")) { // autoconvert Process process = Runtime.getRuntime() .exec(new String[] { "vgmstream\\test.exe", file.toString() }); int p = process.waitFor(); if (p == 0) { //System.out.println("Conversion Success!"); file.delete(); } else { System.out.println("Conversion failure: " + file); } } } } } catch (Exception ex) { throw new RuntimeException(ex); } } }
true
933c6cbb7ba3e836f74cc833f004b42d3d52745f
Java
nikanj/WebServicePracticalExercise
/GuestBook2/src/main/java/de/tum/in/dss/controller/GuestBookController.java
UTF-8
3,052
2.25
2
[]
no_license
package de.tum.in.dss.controller; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.springframework.validation.BindException; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.SimpleFormController; import de.tum.in.dss.additional.GuestBookAdd; import de.tum.in.dss.model.GuestBook; import de.tum.in.dss.model.GuestBookData; public class GuestBookController extends SimpleFormController { private boolean del = false; private boolean edit = false; private boolean add = false; public GuestBookController(){ setCommandClass(GuestBookData.class); setCommandName("guestbookhomeform"); } public boolean isDel() { return del; } public void setDel(boolean del) { this.del = del; } public boolean isEdit() { return edit; } public void setEdit(boolean edit) { this.edit = edit; } public boolean isAdd() { return add; } public void setAdd(boolean add) { this.add = add; } @Override protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command, BindException errors) throws Exception { GuestBookData req = (GuestBookData) command; GuestBookData Session = null; HttpSession session_1 = request.getSession(true); Object sessionObject = session_1.getAttribute( "guestBookListKey"); if(sessionObject!=null){ Session= (GuestBookData)sessionObject; } if(isAdd()){ Session = GuestBookAdd.createNewGuestBookEntry(Session, req.getdata()); session_1.setAttribute ("guestBookListKey", Session); Map<String,GuestBookData> modelMap = new HashMap<String,GuestBookData>(); modelMap.put("guestbookdata", Session); modelMap.put("homeform", Session); return new ModelAndView("guestbookhome",modelMap); } else if(isDel()){ } else if(isEdit()){ } else{ return new ModelAndView("home","guestbookentries",Session); } return super.onSubmit(request, response, command, errors); } @Override protected Object formBackingObject(HttpServletRequest request) throws Exception { String del = request.getParameter("delete"); String sort = request.getParameter("sort"); GuestBookData Session = null; HttpSession session_1 = request.getSession(); Object sessionObject = session_1.getAttribute("guestBookListKey"); if(sessionObject!=null){ Session= (GuestBookData)sessionObject; if(del!=null){ GuestBook bookPresent = null; try{ int id = Integer.parseInt(del); bookPresent = Session.searchdataById(id); } catch(Exception e){ e.printStackTrace(); } if(bookPresent!=null){ Session.removedata(bookPresent); } } if(sort!=null){ Session.sortGuestBookList(); session_1.setAttribute("homeform", Session); } } else{ Session = new GuestBookData(); } Session.setdata(new GuestBook()); return Session; } }
true
c31866d108dcece2f06f77a0c015a17430a8ea50
Java
svaithin/Life_Planner
/app/src/main/java/com/labs/svaithin/life_planner/MyBootReceiver.java
UTF-8
1,458
2.09375
2
[]
no_license
package com.labs.svaithin.life_planner; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.util.Log; import com.labs.svaithin.life_planner.db.TaskContract; import com.labs.svaithin.life_planner.db.TaskDbHelper; import java.util.List; import static android.content.ContentValues.TAG; /** * Created by Siddharth on 28/11/17. */ public class MyBootReceiver extends BroadcastReceiver { private TaskDbHelper mHelper; private String hour,minute; List<String> myList; SQLiteDatabase db; public void onReceive(Context context, Intent intent) { Log.d("SIDDDDDDD", "onReceive"); Cursor cursor = db.query(TaskContract.TaskEntry.NOTIFINAME, new String[]{TaskContract.TaskEntry._ID, TaskContract.TaskEntry.DAYOFWEEK, TaskContract.TaskEntry.HOUR, TaskContract.TaskEntry.MINUTE},null, null, null, null, null); while (cursor.moveToNext()) { int idx = cursor.getColumnIndex(TaskContract.TaskEntry._ID); int id = cursor.getInt(idx); int idy = cursor.getColumnIndex(TaskContract.TaskEntry.HOUR); String h = cursor.getString(idy); Log.d("SIDDDDDDD", "onReceive"+h); SetAlarm setalm = new SetAlarm(context); setalm.setNextAlarm(id); } } }
true
105b911f5ff5cbe62510c9b5380685c3e93573a7
Java
CalvinXCui/springboot-activiti-test
/src/main/java/com/example/demo/service/LeaveService.java
UTF-8
488
1.984375
2
[]
no_license
package com.example.demo.service; import java.util.List; import com.example.demo.entity.LeaveInfo; public interface LeaveService { /** * 新增一条请假单记录 * @param entity */ void addLeaveAInfo(String msg); /** * 查询待办流程 * @param userId * @return */ List<LeaveInfo> getByUserId(String userId); /** * 完成任务 * @param taskId * @param userId * @param audit */ void completeTaskByUser(String taskId,String userId,String audit); }
true
056ee30f02ef7362c254dec80c8d39d23afc3a0b
Java
Exzelsios/VCC_PoC
/vcc-admin/src/main/java/de/novatec/vccadmin/datapoolstatus/entity/LoadStatus.java
UTF-8
263
1.695313
2
[]
no_license
package de.novatec.vccadmin.datapoolstatus.entity; import com.fasterxml.jackson.annotation.JsonProperty; public enum LoadStatus { @JsonProperty("LOADED") LOADED, @JsonProperty("UNLOADED") UNLOADED, @JsonProperty("UNDEFINED") UNDEFINED }
true
fd4ff199f92491e18d673432cd4d92ced28e2436
Java
daviddl9/main
/src/test/java/seedu/address/model/request/UniqueRequestListTest.java
UTF-8
7,077
2.4375
2
[ "MIT" ]
permissive
package seedu.address.model.request; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static seedu.address.logic.commands.CommandTestUtil.VALID_PHONE_BOB; import static seedu.address.testutil.TypicalRequests.ALICE_REQUEST; import static seedu.address.testutil.TypicalRequests.BENSON_REQUEST; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.junit.Rule; import org.junit.jupiter.api.Test; import org.junit.rules.ExpectedException; import seedu.address.model.request.exceptions.DuplicateRequestException; import seedu.address.model.request.exceptions.RequestNotFoundException; import seedu.address.testutil.Assert; import seedu.address.testutil.RequestBuilder; class UniqueRequestListTest { @Rule public ExpectedException thrown = ExpectedException.none(); private final UniqueRequestList uniqueRequestList = new UniqueRequestList(); @Test public void contains_nullRequest_throwsNullPointerException() { Assert.assertThrows(NullPointerException.class, () -> uniqueRequestList.contains(null)); } @Test public void contains_requestNotInList_returnsFalse() { assertFalse(uniqueRequestList.contains(ALICE_REQUEST)); } @Test public void contains_personInList_returnsTrue() { uniqueRequestList.add(ALICE_REQUEST); assertTrue(uniqueRequestList.contains(ALICE_REQUEST)); } @Test public void contains_personWithSameRequestFieldsInList_returnsTrue() { uniqueRequestList.add(ALICE_REQUEST); Request editedAlice = new RequestBuilder(ALICE_REQUEST).build(); assertTrue(uniqueRequestList.contains(editedAlice)); } @Test public void add_nullRequest_throwsNullPointerException() { Assert.assertThrows(NullPointerException.class, () -> uniqueRequestList.add(null)); } @Test public void add_duplicateRequest_throwsDuplicateRequestxception() { uniqueRequestList.add(ALICE_REQUEST); assertThrows(DuplicateRequestException.class, () -> uniqueRequestList .add(ALICE_REQUEST)); } @Test public void setRequest_nullTargetRequest_throwsNullPointerException() { assertThrows(NullPointerException.class, () -> uniqueRequestList.setRequest(null, ALICE_REQUEST)); } @Test public void setRequest_nullEditedRequest_throwsNullPointerException() { assertThrows(NullPointerException.class, () -> uniqueRequestList.setRequest(ALICE_REQUEST, null)); } @Test public void setRequest_targetRequestNotInList_throwsRequestNotFoundException() { assertThrows(RequestNotFoundException.class, () -> uniqueRequestList.setRequest(ALICE_REQUEST, ALICE_REQUEST)); } @Test public void setRequest_editedRequestIsSameRequest_success() { uniqueRequestList.add(ALICE_REQUEST); uniqueRequestList.setRequest(ALICE_REQUEST, ALICE_REQUEST); UniqueRequestList expectedUniqueRequestList = new UniqueRequestList(); expectedUniqueRequestList.add(ALICE_REQUEST); assertEquals(expectedUniqueRequestList, uniqueRequestList); } @Test public void setRequest_editedRequestHasSameIdentity_success() { uniqueRequestList.add(ALICE_REQUEST); Request editedAlice = new RequestBuilder(ALICE_REQUEST).withPhone(VALID_PHONE_BOB).build(); uniqueRequestList.setRequest(ALICE_REQUEST, editedAlice); UniqueRequestList expectedUniqueReqList = new UniqueRequestList(); expectedUniqueReqList.add(editedAlice); assertEquals(expectedUniqueReqList, uniqueRequestList); } @Test public void setRequest_editedRequestHasDifferentIdentity_success() { uniqueRequestList.add(ALICE_REQUEST); uniqueRequestList.setRequest(ALICE_REQUEST, BENSON_REQUEST); UniqueRequestList expectedUniqueReqList = new UniqueRequestList(); expectedUniqueReqList.add(BENSON_REQUEST); assertEquals(expectedUniqueReqList, uniqueRequestList); } @Test public void setRequest_editedRequestHasNonUniqueIdentity_throwsDuplicateRequestException() { uniqueRequestList.add(ALICE_REQUEST); uniqueRequestList.add(BENSON_REQUEST); assertThrows(DuplicateRequestException.class, () -> uniqueRequestList .setRequest(ALICE_REQUEST, BENSON_REQUEST)); } @Test public void remove_nullRequest_throwsNullPointerException() { assertThrows(NullPointerException.class, () -> uniqueRequestList.remove(null)); } @Test public void remove_requestDoesNotExist_throwsRequestNotFoundException() { assertThrows(RequestNotFoundException.class, () -> uniqueRequestList.remove(ALICE_REQUEST)); } @Test public void remove_existingReq_removesReq() { uniqueRequestList.add(ALICE_REQUEST); uniqueRequestList.remove(ALICE_REQUEST); UniqueRequestList expectedUniqueReqList = new UniqueRequestList(); assertEquals(expectedUniqueReqList, uniqueRequestList); } @Test public void setReq_nullUniqueReqList_throwsNullPointerException() { assertThrows(NullPointerException.class, () -> uniqueRequestList.setRequests((UniqueRequestList) null)); } @Test public void setRequests_uniqueRequestList_replacesOwnListWithProvidedUniqueRequestList() { uniqueRequestList.add(ALICE_REQUEST); UniqueRequestList expectedUniqueReqList = new UniqueRequestList(); expectedUniqueReqList.add(BENSON_REQUEST); uniqueRequestList.setRequests(expectedUniqueReqList); assertEquals(expectedUniqueReqList, uniqueRequestList); } @Test public void setReq_nullList_throwsNullPointerException() { assertThrows(NullPointerException.class, () -> uniqueRequestList.setRequests((List<Request>) null)); } @Test public void setRequests_list_replacesOwnListWithProvidedList() { uniqueRequestList.add(ALICE_REQUEST); List<Request> requestList = Collections.singletonList(BENSON_REQUEST); uniqueRequestList.setRequests(requestList); UniqueRequestList expectedUniqueReqList = new UniqueRequestList(); expectedUniqueReqList.add(BENSON_REQUEST); assertEquals(expectedUniqueReqList, uniqueRequestList); } @Test public void setRequests_listWithDuplicateRequests_throwsDuplicateRequestException() { List<Request> listWithDuplicatePersons = Arrays.asList(ALICE_REQUEST, ALICE_REQUEST); assertThrows(DuplicateRequestException.class, () -> uniqueRequestList .setRequests(listWithDuplicatePersons)); } @Test public void asUnmodifiableObservableList_modifyList_throwsUnsupportedOperationException() { assertThrows(UnsupportedOperationException.class, () -> uniqueRequestList.asUnmodifiableObservableList().remove(0)); } }
true
aff959c370370c80809ef96df7bed86619397ff9
Java
strukov94/login
/app/src/main/java/com/strukov/login/login/login/LoginView.java
UTF-8
361
1.75
2
[]
no_license
package com.strukov.login.login.login; import android.content.Intent; import com.strukov.login.login.dialog.GuestDialogFragment; public interface LoginView extends GuestDialogFragment.GuestDialogListener { void startActivityForResult(Intent intent); void authSuccess(); void authFailure(); void syncError(); void showGuestDialog(); }
true
97f3f1a061ce1a17cd16fa80f52430046536a9fd
Java
samuelyo/Leetcode
/56MergeIntervals3.java
UTF-8
1,504
3.8125
4
[]
no_license
package com.leetcode.MergeIntervals; import java.util.ArrayList; import java.util.List; public class MergeIntervals3 { public static void main(String[] args) { Interval int1 = new Interval(1, 3); Interval int2 = new Interval(2, 6); Interval int3 = new Interval(8, 10); Interval int4 = new Interval(15, 18); // Interval int5 = new Interval(1,10); List<Interval> intervals = new ArrayList<Interval>(); intervals.add(int1); intervals.add(int2); intervals.add(int3); intervals.add(int4); // intervals.add(int5); List<Interval> ans = merge(intervals); for (int i = 0; i < ans.size(); i++) { System.out.println(ans.get(i).start + " " + ans.get(i).end); } } public static List<Interval> merge(List<Interval> intervals) { if (intervals.size() <= 1) return intervals; // Sort by ascending starting point using an anonymous Comparator intervals.sort((i1, i2) -> Integer.compare(i1.start, i2.start)); List<Interval> result = new ArrayList<Interval>(); int start = intervals.get(0).start; int end = intervals.get(0).end; for (Interval interval : intervals) { if (interval.start <= end) // Overlapping intervals, move the end if // needed end = Math.max(end, interval.end); else { // Disjoint intervals, add the previous one and reset bounds result.add(new Interval(start, end)); start = interval.start; end = interval.end; } } // Add the last interval result.add(new Interval(start, end)); return result; } }
true
5d0914941991389d741f84b589ff67a6233dbfab
Java
stateofzhao/RapidDevelopment
/core/src/main/java/com/diagrams/core/messagemgr/MessageID.java
UTF-8
487
2.140625
2
[]
no_license
package com.diagrams.core.messagemgr; public enum MessageID { OBSERVER_ID_RESERVE { public Class<? extends IObserverBase> getObserverClass() { return null; } }, SIMPLE { @Override Class<? extends IObserverBase> getObserverClass() { return SimpleObserver.class; } }; abstract Class<? extends IObserverBase> getObserverClass(); public static class SimpleObserver implements IObserverBase { } }
true
bdae0d69b808d0818d3b665296af0911ffd7c9e4
Java
ashwanikumar04/command-line-game
/src/main/java/in/ashwanik/clgame/models/Armoury.java
UTF-8
1,227
2.9375
3
[ "MIT" ]
permissive
package in.ashwanik.clgame.models; import java.util.ArrayList; import java.util.List; /** * Created by Ashwani Kumar on 13/04/18. */ public class Armoury { private static Armoury INSTANCE; private List<Weapon> weapons; private Armoury() { } public static Armoury get() { if (INSTANCE == null) { throw new IllegalStateException("Armoury is not ready"); } return INSTANCE; } public static void fill() { Armoury armoury = new Armoury(); INSTANCE = armoury; armoury.weapons = new ArrayList<>(); armoury.weapons.add(new Dagger("dagger", "Useful for short range attacks", 50, 5, 20)); armoury.weapons.add(new LongSword("long sword", "Useful for long range attacks", 150, 20, 40)); armoury.weapons.add(new Mace("mace", "Good for brutal attacks", 250, 25, 50)); armoury.weapons.add(new SpikeHammer("spike hammer", "Good for brutal attacks", 300, 30, 50)); armoury.weapons.add(new SpineSlasher("spine slasher", "Powerful attacks", 300, 40, 60)); } public List<Weapon> getWeapons() { return this.weapons; } public int numberOfWeapons() { return this.weapons.size(); } }
true
5431ad0febc453cb1ac8fec2c1c23a1607f9dd09
Java
camel-man-ims/coding-test-java
/src/inflearn_lecture/string_array/LicenseKeyFormatting.java
UTF-8
1,035
3.53125
4
[]
no_license
package inflearn_lecture.string_array; /* String str= "8F3Z-2e9-w" String str2 = "8-5g-3-j" 이런식으로 주어질 때 뒤에서 4자리를 끊고, 대문자로 합친 문자열을 만들어라 String str = "8F3Z-2E9W" String str2 = "8-5G3J" String,StringBuffer,StringBuilder */ public class LicenseKeyFormatting { public static void main(String[] args) { String str = "8F3Z-2e-9-wadwqdas"; String str2= "8-5g-3-j"; int k=4; String solution = solution(str, k); } private static String solution(String str, int k) { String replace = str.replace("-", ""); String s = replace.toUpperCase(); int length = replace.length(); StringBuilder sb = new StringBuilder(); for(int i=0;i<length;i++){ sb.append(s.charAt(i)); } for(int i=k;i<length;i=i+k){ System.out.println(length-i); sb.insert(length-i,"-"); } System.out.println(sb); return s; } }
true
5be31e0d6a1a92f214468a4b35b8b53a3d2e3b18
Java
meenuvijay/SeleniumAssignments
/assignments1/SortingUsingCollection.java
UTF-8
590
3.0625
3
[]
no_license
package week3day2.assignments1; import java.util.Arrays; //import java.util.Collections; public class SortingUsingCollection { public static void main(String[] args) { // TODO Auto-generated method stub String[] input = {"HCL","Wipro","Aspire Systems","CTS"}; Arrays.sort(input); System.out.println("The length of Array"+ " " + input.length); System.out.println("The Expected Reverse Array"); for( int i = input.length-1; i>=0 ; i--) { String j = input[i]; System.out.println(j); } } }
true
e58378e64c57a1c9ccba3d6a8801cda268a22575
Java
AKYChan/SetNetTool
/src/csc3095/project/setnet/components/Arc.java
UTF-8
1,797
2.4375
2
[]
no_license
package csc3095.project.setnet.components; import csc3095.project.setnet.components.core.SetnetObject; import javax.xml.bind.annotation.*; @XmlAccessorType(XmlAccessType.FIELD) public class Arc extends SetnetObject { @XmlAttribute @XmlIDREF private final Place place; @XmlAttribute @XmlIDREF private final Transition transition; @XmlElement private final Flow flow; @SuppressWarnings("unused") private Arc() { super(""); place = null; transition = null; flow = null; } public Arc(String name, Place place, Transition transition, Flow flow) { super(name); this.place = place; this.transition = transition; this.flow = flow; updateTransition(); } public final Place getPlace() { return place; } public final Transition getTransition() { return transition; } public final Flow getFlow() { return flow; } public final boolean canBeFired() { return flow.canBeFired(place); } public final void initiateFire() { if (canBeFired()) flow.performFire(place); } protected final void updateTransition() { if (flow == Flow.PLACE_TO_TRANSITION) { transition.addIncomingArc(this); place.addOutgoingTransition(transition); } else if (flow == Flow.TRANSITION_TO_PLACE) { transition.addOutgoingArc(this); place.addIncomingTransition(transition); } else throw new IllegalStateException(); } public boolean compareWith(Arc rhs) { return this.place == rhs.place && this.transition == rhs.transition && this.flow == rhs.flow; } }
true
5d3d643b302aaa6ee7bc8edf4db17a913c24dd99
Java
AgaPol/TicTacToeGame
/TicTacToe/src/Game.java
UTF-8
773
2.828125
3
[]
no_license
import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class Game extends JPanel { OXButton btn[] = new OXButton[9]; public Game(){ initGame(); } public void initGame(){ this.setLayout(new GridLayout(3, 3)); for (int i = 0; i < 9; i++) { btn[i] = new OXButton(); this.add(btn[i]); } } public void start(){ // if(btn[0].getIcon()==btn[1].getIcon() && btn[0].getIcon()==btn[2].getIcon() && btn[0].getIcon() != null){ // btn[0].setBackground(Color.red); // btn[1].setBackground(Color.red); // btn[2].setBackground(Color.red); } } }
true
dacb26b54c8e9e0214fa5d4cda16633358727b23
Java
renowx/angryBird
/src/Jalon2/Vue/ObstacleView.java
UTF-8
1,436
3.109375
3
[]
no_license
package Jalon2.Vue; import Jalon2.Modele.Modele; import java.awt.Color; import java.awt.Graphics; import java.awt.Point; import java.util.ArrayList; import java.util.Observable; import java.util.Observer; import javax.swing.JPanel; import Jalon2.Modele.MouvementObstacle; import Jalon2.Modele.Obstacle; public class ObstacleView extends JPanel implements Observer { Modele modele; public ObstacleView(Modele modele) { this.modele = modele; modele.addObserver(this); } @Override public void update(Observable arg0, Object arg1) { modele = (Modele) arg0; // car je n'ai pas réussie à passée l'array // liste directement // au paint component System.out.println("Uptdate obstacle view appelée"); repaint(); System.out.println("Position de l'oiseau: " + modele.getBird()); } public void paintComponent(Graphics g) { // System.out.println(ob1.getC().x+" "+ob1.getC().y+" "+ob1.getTaille()+" "+ob1.getTaille()); for (Obstacle o : modele.getObstacles()) { if (o.isActif()) { g.setColor(Color.GREEN); } else { g.setColor(Color.RED); } if (!o.isCarre()) { g.drawOval(o.getC().x, o.getC().y, o.getTaille(), o.getTaille()); } else { g.drawRect(o.getC().x, o.getC().y, o.getTaille(), o.getTaille()); } if (o instanceof MouvementObstacle) { MouvementObstacle mo = (MouvementObstacle) o; mo.moveX(); mo.moveY(); } } Scene.s.repaint(); } }
true
8fabbf5f741e035dc2c3f3b83c402af4d4815f74
Java
annajinneman/EsofA1
/src/Participation/Participation.java
UTF-8
984
2.984375
3
[]
no_license
package Participation; import java.io.Serializable; /** * An instance of this class represents a unit of participation to * a certain service. A customer can buy participations. * * See also the background provided in {@link Participation.ApplicationLogic}. */ public class Participation implements Serializable { /** * The customer owning the participation. */ Customer customer ; /** * The service to which the above customer participates. */ Service service ; /** * Make a new Participation instance with the given id. It represents * a participation of the given customer to the given service. */ public Participation(Customer c, Service s) { customer = c ; service = s ; } // Getters: /** * Return the customer to which this participation belongs to. */ public Customer getCustomer(){ return customer ; } /** * Return the service associated to this participation. */ public Service getService(){ return service ; } }
true
a44d772acac31950748c7ff373146bfe8214da3d
Java
bellmit/hxc
/earlyWarningMonintoring/src/main/java/com/cetccity/operationcenter/webframework/trigger/core/converter/AggregatesAlarmConverter.java
UTF-8
732
1.835938
2
[]
no_license
/** * Copyright (C), 2019, 中电科新型智慧城市研究院有限公司 * FileName: AggregatesAlarmConverter * Author: YHY * Date: 2019/5/16 17:18 * Description: * <author> <time> <version> <desc> * 作者姓名 修改时间 版本号 描述 */ package com.cetccity.operationcenter.webframework.trigger.core.converter; import com.cetccity.operationcenter.webframework.trigger.entity.AlarmInformation; import java.util.Collection; /** * 〈一句话功能简述〉<br> * 〈〉 * * @author yhy * @create 2019/5/16 * @since 1.0.0 */ public interface AggregatesAlarmConverter<T> extends Converter<Collection<T>, Collection<AlarmInformation>> { }
true
60372e133434394015964e278fd7a9371f6218da
Java
varunarya03/VaccNow
/src/main/java/com/xebia/vaccnow/repositories/VaccineRepository.java
UTF-8
222
1.679688
2
[]
no_license
package com.xebia.vaccnow.repositories; import com.xebia.vaccnow.models.Vaccine; import org.springframework.data.repository.CrudRepository; public interface VaccineRepository extends CrudRepository<Vaccine, Integer> { }
true
2b257a70c479f760ae73b0068d34da7f30076882
Java
OPTIMALSYSTEMS/yuuvis-momentum-java-tutorials
/upsert-validation-webhook-example/src/main/java/com/os/services/webhook/config/HookException.java
UTF-8
329
2.125
2
[]
no_license
package com.os.services.webhook.config; public class HookException extends Exception { private static final long serialVersionUID = 1L; public HookException(String message) { super(message); } public HookException(String string, Throwable exception) { super(string,exception); } }
true
dcaaa68e192792df25bb54bb3d60d2a7beb4870e
Java
shreyasJoshi30/Immigos
/app/src/main/java/com/example/welcomebot/HospitalListFragment.java
UTF-8
13,873
1.9375
2
[]
no_license
package com.example.welcomebot; import android.Manifest; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Build; import android.os.Bundle; import androidx.annotation.RequiresApi; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import androidx.core.content.ContextCompat; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import androidx.viewpager.widget.ViewPager; import okhttp3.Call; import okhttp3.Callback; import okhttp3.ConnectionPool; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import android.os.Handler; import android.os.Looper; 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.ProgressBar; import android.widget.Toast; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.math.RoundingMode; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.concurrent.TimeUnit; import static android.content.Context.MODE_PRIVATE; /** * the fragment used for displaying the nearby hospitals from google places api */ public class HospitalListFragment extends Fragment { private String mParam1; private String mParam2; RecyclerView recyclerView; View rootView; CardLayoutAdapter cardLayoutAdapter; LocationManager locationManager; Location currentLocation; List<PlacesListBean> placeList = new ArrayList<>(); String defaultLanguage = "NA"; ProgressBar progressBar; //------------------------------------------------------------------------------------------------------// @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment rootView = inflater.inflate(R.layout.fragment_hospital_list, container, false); recyclerView = rootView.findViewById(R.id.list_recycler_view); SharedPreferences pref = getActivity().getSharedPreferences("myPrefs",MODE_PRIVATE); defaultLanguage =pref.getString("isChinese","au"); setHasOptionsMenu(false); //capturing current location if(ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED){ locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE); locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10000, 50, mLocationListener); } progressBar = rootView.findViewById(R.id.loading_hospitals); progressBar.setVisibility(View.VISIBLE); //method call to fetch nearby hospitals Location loc = new Location("anc"); PlacesListBean placesListBean = new PlacesListBean("placeid","name","addr",loc,3.0,true,0.0f,"(0)"); placeList.add(placesListBean); recyclerView.setLayoutManager(new LinearLayoutManager(getActivity())); cardLayoutAdapter = new CardLayoutAdapter(getActivity(),placeList,defaultLanguage); // our adapter takes two string array recyclerView.setAdapter(cardLayoutAdapter); placeList.clear(); return rootView; } //------------------------------------------------------------------------------------------------------// /** * LocationListener is used to listent to location changes and sets the current location */ private final LocationListener mLocationListener = new LocationListener() { @Override public void onLocationChanged(final Location location) { //your code here currentLocation = location; getNearbyPlaces(); } @Override public void onStatusChanged(String provider, int status, Bundle extras) { } @Override public void onProviderEnabled(String provider) { } @Override public void onProviderDisabled(String provider) { } }; //------------------------------------------------------------------------------------------------------// @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.custom_toolbar, menu); super.onCreateOptionsMenu(menu, inflater); MenuItem item = menu.findItem(R.id.app_bar_search); item.setVisible(false); } /** * Overridden method to handle actionbar menu * @param item * @return */ @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if(id == R.id.app_bar_China){ SharedPreferences pref = getActivity().getSharedPreferences("myPrefs",MODE_PRIVATE); SharedPreferences.Editor editor = pref.edit(); editor.putString("isChinese","cn"); editor.commit(); defaultLanguage = "cn"; //translate(); ((AppCompatActivity)getActivity()).getSupportActionBar().setTitle("医疗服务"); placeList.clear(); getNearbyPlaces(); } if(id == R.id.app_bar_australia){ SharedPreferences pref = getActivity().getSharedPreferences("myPrefs",MODE_PRIVATE); SharedPreferences.Editor editor = pref.edit(); editor.putString("isChinese","au"); editor.commit(); defaultLanguage = "au"; ((AppCompatActivity)getActivity()).getSupportActionBar().setTitle("Medical Centers"); placeList.clear(); getNearbyPlaces(); } if(id == R.id.app_bar_about){ Intent intent = new Intent(getActivity(), AboutActivity.class); intent.putExtra("SCREEN", "about"); startActivity(intent); } if(id == android.R.id.home){ getActivity().getSupportFragmentManager() .beginTransaction() .replace(R.id.fragment_container, new LandingPageFragment()) .commit(); } return super.onOptionsItemSelected(item); } //------------------------------------------------------------------------------------------------------// /** * this method makes an API call to google places and displays the results for nearest hospital based on user's current location */ public void getNearbyPlaces(){ //-37.895078 //145.05485 ConnectionPool pool = new ConnectionPool(5, 10000, TimeUnit.MILLISECONDS); String placesAPI_key = getActivity().getResources().getString(R.string.placesAPI_key); OkHttpClient client = new OkHttpClient().newBuilder().connectionPool(pool) .build(); StringBuilder requestURL = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?"); requestURL.append("location="+currentLocation.getLatitude()+","+currentLocation.getLongitude()); //requestURL.append("&radius=10000"); requestURL.append("&rankby=distance"); requestURL.append("&type=hospital"); requestURL.append("&keyword=hospital"); requestURL.append("&key="+placesAPI_key); Request request = new Request.Builder() .url(requestURL.toString()) .method("GET", null) .build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { call.cancel(); Toast.makeText(getActivity(),"There was a problem in fetching results! Please try again later",Toast.LENGTH_SHORT).show(); } @Override public void onResponse(Call call, Response response) throws IOException { new Handler(Looper.getMainLooper()).post(new Runnable() { @RequiresApi(api = Build.VERSION_CODES.N) @Override public void run() { try { JSONObject newsObject = new JSONObject(response.body().string()); JSONArray Jarray = newsObject.getJSONArray("results"); recyclerView.setLayoutManager(new LinearLayoutManager(getActivity())); cardLayoutAdapter = new CardLayoutAdapter(getActivity(), placeList, defaultLanguage); // our adapter takes two string array recyclerView.setAdapter(cardLayoutAdapter); placeList.clear(); if (Jarray.length() > 0) { for (int i = 0; i < Jarray.length(); i++) { PlacesListBean placesListBean = new PlacesListBean(); JSONObject object = Jarray.getJSONObject(i); String placeId = object.getString("place_id"); String name = object.getString("name"); boolean openNow = true; if (object.has("opening_hours") && !object.isNull("opening_hours")) { openNow = object.getJSONObject("opening_hours").getBoolean("open_now"); } Location placeLoc = new Location(""); placeLoc.setLatitude(Double.parseDouble(object.getJSONObject("geometry").getJSONObject("location").getString("lat"))); placeLoc.setLongitude(Double.parseDouble(object.getJSONObject("geometry").getJSONObject("location").getString("lng"))); double rating = 0.0; if (object.has("rating") && !object.isNull("rating")) { rating = object.getDouble("rating"); } int total_user_rating = 0; if (object.has("user_ratings_total") && !object.isNull("user_ratings_total")) { total_user_rating = object.getInt("user_ratings_total"); } String address = object.getString("vicinity"); float distance = currentLocation.distanceTo(placeLoc) / 1000; placesListBean.setName(name); placesListBean.setAddress(address); placesListBean.setRating(rating); placesListBean.setPlaceId(placeId); placesListBean.setOpenNow(openNow); placesListBean.setLocation(placeLoc); placesListBean.setDistance(distance); placesListBean.setTotal_user_ratings(String.valueOf(total_user_rating)); placeList.add(placesListBean); } progressBar.setVisibility(View.GONE); recyclerView.setLayoutManager(new LinearLayoutManager(getActivity())); cardLayoutAdapter = new CardLayoutAdapter(getActivity(),placeList,defaultLanguage); // our adapter takes two string array recyclerView.setAdapter(cardLayoutAdapter); }else{ if (newsObject.has("error_message")) { Toast.makeText(getActivity(), "You have crossed the application's daily limit. Please try again after sometime.", Toast.LENGTH_LONG).show(); }else{ Toast.makeText(getActivity(), "Error loading data. Please try again after sometime.", Toast.LENGTH_LONG).show(); } progressBar.setVisibility(View.GONE); } //Collections.sort(placeList, (Comparator<PlacesListBean>) (o1, o2) -> o1.getDistance().compareTo(o2.getDistance())); /*Collections.sort(placeList, new Comparator<PlacesListBean>() { @Override public int compare(PlacesListBean o1, PlacesListBean o2) { return o1.getDistance().compareTo(o2.getDistance()); } });*/ } catch (JSONException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }); } }); } //------------------------------------------------------------------------------------------------------// }
true
3b5ac10888ba6920d5ff47bcd2e3872011a9d4b5
Java
yarorage/testGit
/src/main/java/ru/yaro/GuiceModule.java
UTF-8
1,920
1.960938
2
[]
no_license
package ru.yaro; import com.google.inject.AbstractModule; import com.google.inject.Provides; import org.apache.ibatis.mapping.Environment; import org.apache.ibatis.session.Configuration; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.apache.ibatis.transaction.TransactionFactory; import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory; import org.sqlite.SQLiteDataSource; import ru.yaro.Main; import ru.yaro.dao.UserDao; import ru.yaro.dao.UserDaoImpl; import ru.yaro.dao.UserMapper; import ru.yaro.service.Calculator; import ru.yaro.service.CalculatorImpl; import javax.inject.Singleton; import java.net.URISyntaxException; import java.net.URL; public class GuiceModule extends AbstractModule { @Override protected void configure() { bind(Calculator.class).to(CalculatorImpl.class); bind(UserDao.class).to(UserDaoImpl.class); } @Provides @Singleton public SqlSessionFactory createSQLSessionFactory() { URL resource = Main.class.getClassLoader().getResource("mydatabase.db"); String path = null; { try { path = resource.toURI().getPath(); } catch (URISyntaxException e) { e.printStackTrace(); } } String JDBCurl = ("jdbc:sqlite:" + path); SQLiteDataSource dataSource = new SQLiteDataSource(); dataSource.setUrl(JDBCurl); TransactionFactory transactionFactory = new JdbcTransactionFactory(); Environment environment = new Environment("development", transactionFactory, dataSource); Configuration configuration = new Configuration(environment); configuration.addMapper(UserMapper.class); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration); return sqlSessionFactory; } }
true
1c03ad02fe7611f8eca344bb676a4a07a70e101b
Java
flywind2/joeis
/src/irvine/oeis/a108/A108213.java
UTF-8
364
2.703125
3
[]
no_license
package irvine.oeis.a108; import irvine.oeis.LinearRecurrence; /** * A108213 <code>a(0)=44</code>; if n odd, <code>a(n) = a(n-1)/2</code>, otherwise <code>a(n) = 4*a(n-1)</code>. * @author Sean A. Irvine */ public class A108213 extends LinearRecurrence { /** Construct the sequence. */ public A108213() { super(new long[] {2, 0}, new long[] {44, 22}); } }
true
9dbb0b68707e7f256ef4e20db6922aef5933f533
Java
shiwen1006/Ajax_demo
/wen-web/src/main/java/com/sykean/config/DruidConfig.java
UTF-8
5,070
1.882813
2
[]
no_license
package com.sykean.config; import com.alibaba.druid.filter.Filter; import com.alibaba.druid.filter.stat.StatFilter; import com.alibaba.druid.pool.DruidDataSource; import com.alibaba.druid.support.http.StatViewServlet; import com.alibaba.druid.support.http.WebStatFilter; import com.baomidou.mybatisplus.MybatisConfiguration; import com.baomidou.mybatisplus.entity.GlobalConfiguration; import com.baomidou.mybatisplus.plugins.PerformanceInterceptor; import com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean; import com.github.pagehelper.PageHelper; import com.google.common.collect.Lists; import lombok.extern.slf4j.Slf4j; import org.apache.ibatis.plugin.Interceptor; import org.apache.ibatis.session.SqlSessionFactory; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.boot.web.servlet.ServletRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import org.springframework.core.io.support.ResourcePatternResolver; import java.util.Properties; /** * 数据库连接池 */ @Configuration @MapperScan(basePackages = "com.sykean.mapper") @Slf4j public class DruidConfig { /** * mybatis-plus SQL执行效率插件【生产环境可以关闭】 */ private PerformanceInterceptor performanceInterceptor() { return new PerformanceInterceptor(); } /** * 分页插件 */ private PageHelper pageHelper() { PageHelper pageHelper = new PageHelper(); Properties properties = new Properties(); properties.setProperty("dialect", "mysql"); pageHelper.setProperties(properties); return pageHelper; } @ConfigurationProperties(prefix = "spring.datasource.druid") @Bean public DruidDataSource dataSource() { DruidDataSource dataSource = new DruidDataSource(); dataSource.setProxyFilters(Lists.newArrayList(statFilter())); return dataSource; } @Bean public Filter statFilter() { StatFilter filter = new StatFilter(); filter.setSlowSqlMillis(5000); filter.setLogSlowSql(true); filter.setMergeSql(true); return filter; } /** * 置SQL监控用户名和密码 * * @return */ @Bean public ServletRegistrationBean druidServlet() { ServletRegistrationBean reg = new ServletRegistrationBean(); reg.setServlet(new StatViewServlet()); reg.addUrlMappings("/druid/*"); reg.addInitParameter("loginUsername", "lee"); reg.addInitParameter("loginPassword", "123456"); return reg; } /** * 设置SQL监控管理平台访问地址 * * @return */ @Bean public FilterRegistrationBean filterRegistrationBean() { FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(); filterRegistrationBean.setFilter(new WebStatFilter()); filterRegistrationBean.addUrlPatterns("/*"); filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*"); filterRegistrationBean.addInitParameter("profileEnable", "true"); return filterRegistrationBean; } private GlobalConfiguration globalConfiguration() { GlobalConfiguration globalConfiguration = new GlobalConfiguration(); //主键类型 0:"数据库ID自增", 1:"用户输入ID",2:"全局唯一ID (数字类型唯一ID)", 3:"全局唯一ID UUID"; globalConfiguration.setIdType(1); //字段策略 0:"忽略判断",1:"非 NULL 判断"),2:"非空判断" globalConfiguration.setFieldStrategy(1); //驼峰下划线转换 globalConfiguration.setDbColumnUnderline(true); //刷新mapper 调试神器 globalConfiguration.setRefresh(true); return globalConfiguration; } @Bean public SqlSessionFactory sqlSessionFactoryBean() throws Exception { MybatisSqlSessionFactoryBean sqlSessionFactory = new MybatisSqlSessionFactoryBean(); sqlSessionFactory.setDataSource(dataSource()); //设置分页插件 sqlSessionFactory.setPlugins(new Interceptor[]{ // performanceInterceptor(), pageHelper() }); MybatisConfiguration configuration = new MybatisConfiguration(); //转驼峰 configuration.setMapUnderscoreToCamelCase(true); //全局配置 //添加XML目录 ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); sqlSessionFactory.setConfiguration(configuration); sqlSessionFactory.setMapperLocations(resolver.getResources("classpath*:mappers/*Mapper.xml")); sqlSessionFactory.setGlobalConfig(globalConfiguration()); return sqlSessionFactory.getObject(); } }
true
4e789b4d97405d4837f8e521701e8c8527226caa
Java
ybkim1984/prj-yb
/dom2/namoo.board.dom2.da.hibernate/src/test/java/namoo/board/dom2/da/hibernate/BoardUserHibernateStoreTest.java
UTF-8
3,316
2.171875
2
[]
no_license
/* * COPYRIGHT (c) Nextree Consulting 2015 * This software is the proprietary of Nextree Consulting. * * @author <a href="mailto:demonpark@nextree.co.kr">SeokJae Park</a> * @since 2015. 2. 2. */ package namoo.board.dom2.da.hibernate; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.util.List; import namoo.board.dom2.da.hibernate.BoardUserHibernateStore; import namoo.board.dom2.entity.user.DCBoardUser; import namoo.board.dom2.util.exception.EmptyResultException; import namoo.board.dom2.util.exception.NamooBoardException; import org.dbunit.dataset.DataSetException; import org.junit.Test; public class BoardUserHibernateStoreTest extends BoardInitHibernateStoreTest { // private BoardUserHibernateStore userStore = new BoardUserHibernateStore(); @Override protected String getDatasetXml() { // return "./dataset/board_users.xml"; } @Test public void testCreate() throws EmptyResultException { // String email = "demonpark@nextree.co.kr"; DCBoardUser insertUser = new DCBoardUser(email,"박석재","010-0000-0000"); assertEquals(2,userStore.retrieveAll().size()); userStore.create(insertUser); assertEquals(3,userStore.retrieveAll().size()); DCBoardUser user = userStore.retrieveByEmail(email); assertEquals("박석재",user.getName()); } @Test public void testRetrieveByEmail() throws EmptyResultException { // DCBoardUser user = userStore.retrieveByEmail("hkkang@nextree.co.kr"); assertNotNull(user); assertEquals("강형구", user.getName()); assertEquals("010-1234-5678", user.getPhoneNumber()); } @Test public void testRetrieveAll() throws DataSetException { // List<DCBoardUser> users = userStore.retrieveAll(); assertEquals(2,users.size()); } @Test public void testRetrieveByName() { // List<DCBoardUser> users = userStore.retrieveByName("강형구"); assertEquals("hkkang@nextree.co.kr",users.get(0).getEmail()); } @Test public void testUpdate() throws Exception { DCBoardUser user = userStore.retrieveByEmail("hkkang@nextree.co.kr"); assertEquals("강형구",user.getName()); user.setName("수정 강형구"); userStore.update(user); DCBoardUser updateUser = userStore.retrieveByEmail("hkkang@nextree.co.kr"); assertEquals("수정 강형구",updateUser.getName()); } @Test public void testDeleteByEmail() throws Exception { DCBoardUser user = userStore.retrieveByEmail("hkkang@nextree.co.kr"); assertNotNull(user); userStore.deleteByEmail(user.getEmail()); DCBoardUser deleteUser = null; try { deleteUser = userStore.retrieveByEmail("hkkang@nextree.co.kr"); }catch(NamooBoardException e) { assertTrue(true); } assertNull(deleteUser); } @Test public void testIsExistByEmail() { assertTrue(userStore.isExistByEmail("hkkang@nextree.co.kr")); assertFalse(!userStore.isExistByEmail("demonpark@nextree.co.kr")); } }
true
cb1155a37aa25e2b64455e8d0a6722f37f5b928a
Java
Holenkov/EPAM-Training-Projects
/Task4XMLParsing/src/by/training/xmlparsing/bean/CPU.java
UTF-8
1,193
2.953125
3
[]
no_license
package by.training.xmlparsing.bean; /** * CPU bean, extends of Device. */ public class CPU extends Device { /** CPU frequency.*/ protected int frequency; /** public int getFrequency(). * Getter for CPU frequency. * @return CPU frequency. */ public int getFrequency() { return frequency; } /** public void setFrequency(int frequency). * Setter for CPU frequency. * @param frequency of CPU. */ public void setFrequency(int frequency) { this.frequency = frequency; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + frequency; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; CPU other = (CPU) obj; if (frequency != other.frequency) return false; return true; } @Override /** * To String. */ public String toString() { return "CPU [frequency=" + frequency + ", name=" + name + ", origin=" + origin + ", dateOfIssue=" + dateOfIssue + ", price=" + price + ", types=" + types + ", critical=" + critical + "]"; } }
true
b833107401edf2da020bb7578cfa4a24ba4d6a09
Java
Sinius15/MMV
/src/com/sinius15/MMV/components/ReferenceVariable.java
UTF-8
479
2.5625
3
[]
no_license
package com.sinius15.MMV.components; import com.sinius15.MMV.Application; public class ReferenceVariable extends Variable<Integer>{ public ReferenceVariable(String name, int referenceId) { super(name, referenceId); } public HeapFrame referencingTo(Application app) { return app.heap.getHeapFrame(getValue()); } @Override public String toString() { return getName() +(getValue() == -1 ? "" : (" referencing to " + getValue())); } }
true
bfb793ff858aaea71f8edc2654530f09a19c2f86
Java
annisafitrianin/Aplikasi-Ruang-Sedekah
/app/src/main/java/ap/annisafitriani/ruangsedekah/Model/Lokasi.java
UTF-8
1,323
2.046875
2
[]
no_license
package ap.annisafitriani.ruangsedekah.Model; import java.io.Serializable; /** * Created by Hp on 7/12/2018. */ public class Lokasi implements Serializable { private String namaTempat; private String lokasiId; private String kegiatanId; private Double lat, lang; public Lokasi(String namaTempat, String lokasiId, String kegiatanId, Double lat, Double lang) { this.namaTempat = namaTempat; this.lokasiId = lokasiId; this.kegiatanId = kegiatanId; this.lat = lat; this.lang = lang; } public Lokasi() { } public String getNamaTempat() { return namaTempat; } public void setNamaTempat(String namaTempat) { this.namaTempat = namaTempat; } public String getLokasiId() { return lokasiId; } public void setLokasiId(String lokasiId) { this.lokasiId = lokasiId; } public String getKegiatanId() { return kegiatanId; } public void setKegiatanId(String kegiatanId) { this.kegiatanId = kegiatanId; } public Double getLat() { return lat; } public void setLat(Double lat) { this.lat = lat; } public Double getLang() { return lang; } public void setLang(Double lang) { this.lang = lang; } }
true
3f889077df8f88ee24346c68bbeb4091a784c794
Java
iamfirdous/MIAMuslimIndustrialistAssociation
/app/src/main/java/com/nexusinfo/mia_muslimindustrialistassociation/ui/adapters/ProductAdapter.java
UTF-8
3,620
2.296875
2
[]
no_license
package com.nexusinfo.mia_muslimindustrialistassociation.ui.adapters; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.drawable.BitmapDrawable; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.nexusinfo.mia_muslimindustrialistassociation.R; import com.nexusinfo.mia_muslimindustrialistassociation.models.ProductModel; import com.nexusinfo.mia_muslimindustrialistassociation.ui.activities.ViewProductActivity; import java.util.List; /** * Created by firdous on 1/15/2018. */ public class ProductAdapter extends RecyclerView.Adapter<ProductAdapter.ProductViewHolder>{ private List<ProductModel> mProducts; private Context mContext; public ProductAdapter(Context mContext, List<ProductModel> mProducts) { this.mProducts = mProducts; this.mContext = mContext; } @Override public ProductViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { LayoutInflater inflater = LayoutInflater.from(mContext); View view = inflater.inflate(R.layout.listitem_product, null); return new ProductViewHolder(view); } @Override public void onBindViewHolder(ProductViewHolder holder, int position) { ProductModel product = mProducts.get(position); byte[] photoData = product.getPhoto(); String productName = product.getProductName(); String companyName = product.getCompanyName(); String productSpecification = product.getSpecification(); Bitmap bmp; if(photoData != null) bmp = BitmapFactory.decodeByteArray(photoData, 0, photoData.length); else bmp = ((BitmapDrawable)mContext.getResources().getDrawable(R.drawable.ic_product)).getBitmap(); holder.ivProductPhoto.setImageBitmap(bmp); if (productName != null && !productName.equals("")) holder.tvProductName.setText(productName); else holder.tvProductName.setText("-"); if (companyName != null && !companyName.equals("")) holder.tvCompanyName.setText(companyName); else holder.tvCompanyName.setText("-"); if (productSpecification != null && !productSpecification.equals("")) holder.tvProductSpecification.setText(productSpecification); else holder.tvProductSpecification.setText("-"); holder.itemView.setOnClickListener(view -> { Intent viewProduct = new Intent(mContext, ViewProductActivity.class); viewProduct.putExtra("product", product); mContext.startActivity(viewProduct); }); } @Override public int getItemCount() { return mProducts.size(); } class ProductViewHolder extends RecyclerView.ViewHolder{ ImageView ivProductPhoto; TextView tvProductName, tvCompanyName, tvProductSpecification; View itemView; public ProductViewHolder(View itemView) { super(itemView); this.itemView = itemView; ivProductPhoto = itemView.findViewById(R.id.imageView_productPhoto); tvProductName = itemView.findViewById(R.id.textView_productName); tvCompanyName = itemView.findViewById(R.id.textView_companyName_product); tvProductSpecification = itemView.findViewById(R.id.textView_productSpecification); } } }
true
bf6027274ed04b3acb66cc3a0dbb39dea85174d2
Java
TheRoddyWMS/Roddy
/RoddyCore/src/de/dkfz/roddy/knowledge/files/FileStageSettings.java
UTF-8
1,463
2.3125
2
[ "LicenseRef-scancode-proprietary-license", "LGPL-2.1-only", "EPL-2.0", "MPL-2.0-no-copyleft-exception", "MIT", "CC0-1.0", "AGPL-3.0-only", "LicenseRef-scancode-warranty-disclaimer", "MPL-2.0", "EPL-1.0", "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference", "GPL-2.0-only", "xpp"...
permissive
/* * Copyright (c) 2016 German Cancer Research Center (Deutsches Krebsforschungszentrum, DKFZ). * * Distributed under the MIT License (license terms are at https://www.github.com/TheRoddyWMS/Roddy/LICENSE.txt). */ package de.dkfz.roddy.knowledge.files; import de.dkfz.roddy.core.DataSet; import java.io.Serializable; /** * File stages contain information about the "detail" level / stage of a file. * i.e. Raw sequence files belong to the lowest stage and contain the highest level of detail (even the numeric index). * i.e. paired bam files are one level above raw sequences and do not have the index set but they still belong to a lane and a run * i.e. Merged bam files only contain information about the sample and the data set. * @author michael */ public abstract class FileStageSettings<T extends FileStageSettings> implements Serializable { protected final DataSet dataSet; protected final FileStage stage; protected FileStageSettings(DataSet dataSet, FileStage stage) { this.dataSet = dataSet; this.stage = stage; } public DataSet getDataSet() { return dataSet; } public FileStage getStage() { return stage; } public abstract T copy(); public abstract T decreaseLevel(); public abstract String getIDString(); public abstract String fillStringContent(String temp); public abstract String fillStringContentWithArrayValues(int index, String temp); }
true
83f7510820311b53e0bee8db0f7f20dd7801979d
Java
naemoo/Algorithm
/src/Kakao/Problem30.java
UTF-8
2,080
3.421875
3
[]
no_license
/* * 2020 KAKAO BLIND RECRUITMENT * https://programmers.co.kr/learn/courses/30/lessons/60059 * 자물쇠와 열쇠 */ package Kakao; import java.util.*; public class Problem30 { public static boolean solution(int[][] key, int[][] lock) { int[][][] keys = getRotatedKey(key); int n = lock.length; int m = key.length; lock = zeroPadding(m, lock); for (int[][] newKey : keys) { for (int i = 0; i < n + m - 1; i++) { for (int j = 0; j < m + n - 1; j++) { if (isMatchKey(newKey, lock, m, n, i, j)) return true; } } } return false; } private static boolean isMatchKey(int[][] newKey, int[][] lock, int m, int n, int row, int col) { lock = Arrays.stream(lock).map(int[]::clone).toArray(int[][]::new); for (int i = 0; i < m; i++) { for (int j = 0; j < m; j++) { lock[i + row][j + col] += newKey[i][j]; } } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (lock[m - 1 + i][m - 1 + j] != 1) return false; } } return true; } private static int[][] zeroPadding(int m, int[][] lock) { int n = lock.length; int[][] arr = new int[2 * m + n - 2][2 * m + n - 2]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { arr[m - 1 + i][m - 1 + j] = lock[i][j]; } } return arr; } private static int[][][] getRotatedKey(int[][] key) { int[][][] keys = new int[4][][]; keys[0] = rotateKey(key); keys[1] = rotateKey(keys[0]); keys[2] = rotateKey(keys[1]); keys[3] = rotateKey(keys[2]); return keys; } private static int[][] rotateKey(int[][] key) { int n = key.length; int[][] arr = new int[n][n]; for (int i = 0; i < key.length; i++) { for (int j = 0; j < key[i].length; j++) { arr[i][j] = key[n - 1 - j][i]; } } return arr; } public static void main(String[] args) { boolean ans = solution(new int[][] { { 0, 0, 0 }, { 1, 0, 0 }, { 0, 1, 1 } }, new int[][] { { 1, 1, 1 }, { 1, 1, 0 }, { 1, 0, 1 } }); System.out.println(ans); } }
true
4188cf810127941bd1f2bdb71eb1aeec0baf9d7f
Java
musol1985/fenix
/Fenix/src/main/java/com/sot/fenix/components/json/NuevoCentroJSON.java
UTF-8
233
1.664063
2
[]
no_license
package com.sot.fenix.components.json; import com.sot.fenix.components.models.Centro; import com.sot.fenix.components.models.Ubicacion; public class NuevoCentroJSON{ public Centro centro; public String nombreAdmin; }
true
3d473a6a7b53b63d3da2dda26057280a9b47d0e0
Java
MukeshAnandmax/JBDL-9
/REST-APIs_L6/src/main/java/org/geekforgeek/jbdl9/RESTAPIs/TestController.java
UTF-8
610
2.28125
2
[]
no_license
package org.geekforgeek.jbdl9.RESTAPIs; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.*; @RestController public class TestController { @RequestMapping(value = "/song/test-abc", method = RequestMethod.GET) public String greetUser(){ return "Hello User!!"; } @GetMapping("/song/test-abc2") public String greetUser2(){ return "Hello User!!"; } @PostMapping("/view/test-post") @ResponseStatus(value = HttpStatus.ACCEPTED) public Request getUser(@RequestBody Request request){ return request; } }
true
12d7ffcac1b15a067c917913f604bed298414d55
Java
ritchirp/School-Work
/COLLEGE/Junior/AI/maze-search/src/mazesearch/cse/miamioh/edu/AStarSearch.java
UTF-8
2,104
3.46875
3
[]
no_license
package mazesearch.cse.miamioh.edu; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.PriorityQueue; public class AStarSearch extends SearchStrategy { public AStarSearch(Maze maze) { super(maze); } @Override public void solve() { PriorityQueue<AStarNode> frontier = new PriorityQueue<AStarNode>(); frontier.add(new AStarNode(this.maze.getStart())); LinkedList<AStarNode> tempExplored = new LinkedList<AStarNode>(); // We will use a list for now so that we may access the entries while(!frontier.isEmpty()) { AStarNode n = frontier.poll(); Square[] children = n.getChildren(); for(Square s : children) { if (!this.maze.isBlocked(s)) { // Create a new node and assign its heuristic and path cost AStarNode child = new AStarNode(s); child.setVisitedFrom(n); child.setG(n.getG() + distance(child, n)); child.setF(child.getG() + h(child)); if(child.equals(this.maze.getGoal())) { LinkedList<Square> tempPath = new LinkedList<Square>(); while(child != null) { tempPath.addLast(child); child = child.getVisitedFrom(); } explored = new HashSet<Square>(tempExplored); path = tempPath; return; } if (frontier.contains(child) && hasLowerF(child, frontier.iterator())) continue; if (tempExplored.contains(child) && hasLowerF(child, tempExplored.iterator())) continue; frontier.add(child); } } tempExplored.add(n); } } private boolean hasLowerF(AStarNode n, Iterator<AStarNode> i){ AStarNode current; while(i.hasNext()) { current = i.next(); if(current.equals(n)) { if(current.getF() < n.getF()) return true; else return false; } } return false; } private float h(Square s){ // The Manhattan Distance Heuristic return distance(s, this.maze.getGoal()); } private float distance(Square s1, Square s2){ return Math.abs(s1.getColumn() - s2.getColumn()) + Math.abs(s1.getRow() - s2.getRow()); } }
true
acbe79d172ecaafe82bfc8ab39c36f41d987960a
Java
charro/subelo
/server/src/main/java/subelo/server/services/.svn/text-base/RestService.java.svn-base
UTF-8
2,962
2.09375
2
[]
no_license
/** Copyright 2011 UNED * * Miguel Rivero * Juan Manuel Cigarran * * Licensed under the EUPL, Version 1.1 or – as soon they will be approved by the European Commission – subsequent versions of the EUPL (the "Licence");* you may not use this work except in compliance with the Licence. * You may obtain a copy of the Licence at: * * http://www.osor.eu/eupl/european-union-public-licence-eupl-v.1.1 * * Unless required by applicable law or agreed to in writing, software distributed under the Licence is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the Licence for the specific language governing permissions and limitations under the Licence. */ package subelo.server.services; import java.util.HashMap; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import subelo.protocol.AvailableServiceProviders; import subelo.protocol.RequestMessage; import subelo.protocol.ResponseCodes; import subelo.protocol.ResponseMessage; import subelo.server.services.external.twitter.TwitterServiceProvider; @Path(value = "/subelo") public class RestService { @GET @Produces(MediaType.TEXT_PLAIN) @Path (value="/hello") public String getHello(){ return "Hello there. This is the Hello REST Web Service!!"; } @POST @Produces(MediaType.APPLICATION_JSON) @Path (value="/sendMap") @Consumes(MediaType.APPLICATION_JSON) public HashMap<String, String> sendMap(HashMap<String, String> map){ return map; } @GET @Produces(MediaType.APPLICATION_JSON) @Path (value="/testJSON") public ResponseMessage testJson(){ return new ResponseMessage(ResponseCodes.OK, "json test from subelo REST server"); } @POST @Produces(MediaType.APPLICATION_JSON) @Path (value="/testPostJSON") @Consumes(MediaType.APPLICATION_JSON) public ResponseMessage testPostJson(RequestMessage request){ return new ResponseMessage(ResponseCodes.OK, "Sucessfully received you request to the ServiceProvider: " + request); } @POST @Produces(MediaType.APPLICATION_JSON) @Path (value="/addItem") @Consumes(MediaType.APPLICATION_JSON) public ResponseMessage addNewItem(RequestMessage request){ return getServiceImpl(request.getServiceCode()).addItem(request); } @POST @Produces(MediaType.APPLICATION_JSON) @Path (value="/listMyItems") @Consumes(MediaType.APPLICATION_JSON) public ResponseMessage listMyItems(RequestMessage request){ return getServiceImpl(request.getServiceCode()).listMyItems(request); } private ServiceProvider getServiceImpl(AvailableServiceProviders provider){ ServiceProvider serviceProvider = null; switch(provider){ case TWITTER: serviceProvider = new TwitterServiceProvider(); break; } return serviceProvider; } }
true
a23937aabcb1e00b0ad8587bf4c9df4b8c38d89a
Java
clj911/solr
/src/test/java/a/solrTest.java
UTF-8
4,491
2.34375
2
[]
no_license
package a; import com.itheima.pojo.Items; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.impl.HttpSolrServer; import org.apache.solr.client.solrj.response.QueryResponse; import org.apache.solr.common.SolrDocument; import org.apache.solr.common.SolrDocumentList; import org.apache.solr.common.SolrInputDocument; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.util.List; import java.util.Map; import static org.apache.solr.client.solrj.SolrQuery.ORDER ; public class solrTest { HttpSolrServer solrServer ; @Before public void init() { //连接solr服务器 solrServer = new HttpSolrServer("http://localhost:8080/solr/core2"); } @Test public void solrTest1() throws IOException, SolrServerException { //创建文档 SolrInputDocument doc = new SolrInputDocument(); doc.addField("id",15l); doc.addField("title","8848手机,就是屌"); doc.addField("price",999900l); solrServer.add(doc); } @Test public void solrTest2() throws IOException, SolrServerException { //创建实体类对象 Items item = new Items(); item.setId(16l); item.setTitle("霸王手机,手机中的战斗机"); item.setPrice(1000000l); solrServer.addBean(item); } @Test public void deleteTest() throws IOException, SolrServerException { solrServer.deleteById("16"); } @Test public void queryTest1() throws SolrServerException { //创建查询对象 SolrQuery query = new SolrQuery("title:8848"); //执行查询 获取响应 QueryResponse response = solrServer.query(query); //解析响应 SolrDocumentList lists = response.getResults(); System.out.println("共有"+lists.getNumFound()+"条数据"); //遍历 for (SolrDocument doc : lists) { System.out.println("id:"+doc.getFieldValue("id")); System.out.println("title:"+doc.getFieldValue("title")); System.out.println("price:"+doc.getFieldValue("price")); } } @Test public void queryTest2() throws SolrServerException { //创建查询对象 SolrQuery query = new SolrQuery("title:8848 OR title:华为"); //执行查询 获取响应 QueryResponse response = solrServer.query(query); //解析响应 SolrDocumentList lists = response.getResults(); System.out.println("共有"+lists.getNumFound()+"条数据"); //遍历 lists.forEach(System.out::println); } @Test public void QueryByBean() throws SolrServerException { SolrQuery query = new SolrQuery("title:Apple"); QueryResponse response = solrServer.query(query); List<Items> list = response.getBeans(Items.class); list.forEach(System.out::println); } @Test public void queryByPage() throws SolrServerException { int num = 2 ; int size = 3 ; int start = (num-1)*size ; SolrQuery query = new SolrQuery("title:华为"); query.setSort("price", ORDER.desc); query.setStart(start); query.setRows(3); QueryResponse response = solrServer.query(query); List<Items> list = response.getBeans(Items.class); list.forEach(System.out::println); } @Test public void queryByHighLighlting() throws SolrServerException { SolrQuery query = new SolrQuery("title:华为"); query.setHighlightSimplePre("<em>"); query.setHighlightSimplePost("</em>"); //设置高亮字段 query.addHighlightField("title"); QueryResponse response = solrServer.query(query); //得到非高亮结果 List<Items> list = response.getBeans(Items.class); //得到高亮结果 Map<String, Map<String, List<String>>> map = response.getHighlighting(); //处理高亮 /*for (Items item : list) { item.setTitle(map.get(item.getId()+"").get("title").get(0)); }*/ //遍历 list.forEach(item -> { item.setTitle(map.get(item.getId()+"").get("title").get(0)); System.out.println(item); }); } @After public void after() throws IOException, SolrServerException { solrServer.commit(); } }
true
43b7b092caeb76ebe3f565e4b27745e79e0bc68d
Java
UweTrottmann/SeriesGuide
/app/src/main/java/com/battlelancer/seriesguide/util/SelectionBuilder.java
UTF-8
5,230
2.5
2
[ "Apache-2.0" ]
permissive
package com.battlelancer.seriesguide.util; import static android.database.sqlite.SQLiteDatabase.CONFLICT_NONE; import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteQueryBuilder; import android.text.TextUtils; import androidx.sqlite.db.SupportSQLiteDatabase; import com.battlelancer.seriesguide.provider.SeriesGuideProvider; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map; import timber.log.Timber; /** * Helper for building selection clauses for {@link SQLiteDatabase}. Each * appended clause is combined using {@code AND}. This class is <em>not</em> * thread safe. */ public class SelectionBuilder { private String table = null; private Map<String, String> projectionMap = new HashMap<>(); private StringBuilder selection = new StringBuilder(); private ArrayList<String> selectionArgs = new ArrayList<>(); /** * Reset any internal state, allowing this builder to be recycled. */ public SelectionBuilder reset() { table = null; selection.setLength(0); selectionArgs.clear(); return this; } /** * Append the given selection clause to the internal state. Each clause is * surrounded with parenthesis and combined using {@code AND}. */ public SelectionBuilder where(String selection, String... selectionArgs) { if (TextUtils.isEmpty(selection)) { if (selectionArgs != null && selectionArgs.length > 0) { throw new IllegalArgumentException( "Valid selection required when including arguments="); } // Shortcut when clause is empty return this; } if (this.selection.length() > 0) { this.selection.append(" AND "); } this.selection.append("(").append(selection).append(")"); if (selectionArgs != null) { Collections.addAll(this.selectionArgs, selectionArgs); } return this; } public SelectionBuilder table(String table) { this.table = table; return this; } private void assertTable() { if (table == null) { throw new IllegalStateException("Table not specified"); } } public SelectionBuilder mapToTable(String column, String table) { projectionMap.put(column, table + "." + column); return this; } public SelectionBuilder map(String fromColumn, String toClause) { projectionMap.put(fromColumn, toClause + " AS " + fromColumn); return this; } /** * Return selection string for current internal state. * * @see #getSelectionArgs() */ public String getSelection() { return selection.toString(); } /** * Return selection arguments for current internal state. * * @see #getSelection() */ public String[] getSelectionArgs() { return selectionArgs.toArray(new String[selectionArgs.size()]); } private void mapColumns(String[] columns) { for (int i = 0; i < columns.length; i++) { final String target = projectionMap.get(columns[i]); if (target != null) { columns[i] = target; } } } @Override public String toString() { return "SelectionBuilder[table=" + table + ", selection=" + getSelection() + ", selectionArgs=" + Arrays.toString(getSelectionArgs()) + "]"; } /** * Execute query using the current internal state as {@code WHERE} clause. */ public Cursor query(SupportSQLiteDatabase db, String[] columns, String orderBy) { return query(db, columns, null, null, orderBy, null); } /** * Execute query using the current internal state as {@code WHERE} clause. */ public Cursor query(SupportSQLiteDatabase db, String[] columns, String groupBy, String having, String orderBy, String limit) { assertTable(); if (columns != null) mapColumns(columns); if (SeriesGuideProvider.LOGV) Timber.v("query(columns=" + Arrays.toString(columns) + ") " + this); String query = SQLiteQueryBuilder.buildQueryString( false, table, columns, getSelection(), groupBy, having, orderBy, limit); return db.query(query, getSelectionArgs()); } /** * Execute update using the current internal state as {@code WHERE} clause. */ public int update(SupportSQLiteDatabase db, ContentValues values) { assertTable(); if (SeriesGuideProvider.LOGV) Timber.v("update() %s", this); return db.update(table, CONFLICT_NONE, values, getSelection(), getSelectionArgs()); } /** * Execute delete using the current internal state as {@code WHERE} clause. */ public int delete(SupportSQLiteDatabase db) { assertTable(); if (SeriesGuideProvider.LOGV) Timber.v("delete() %s", this); return db.delete(table, getSelection(), getSelectionArgs()); } }
true
2088db1153621fb56c2686508129adbc2584ea53
Java
nalet/bfh-bachelor-thesis
/src/main/java/ch/certe/optimization/maintenancesolver/product/domain/Interval.java
UTF-8
2,669
2.28125
2
[]
no_license
/* * Copyright 2017 JBoss by Red Hat. * * 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 ch.certe.optimization.maintenancesolver.product.domain; import ch.certe.optimization.maintenancesolver.common.domain.AbstractPersistable; import java.time.Period; import java.util.ArrayList; import javax.xml.bind.annotation.XmlRootElement; /** * * @author nalet */ @XmlRootElement public class Interval extends AbstractPersistable { public static final double MONTH_IN_DAYS = 30.4167; private Period period; private ArrayList<Requirement> requirements; private Task lastTask; private ArrayList<Task> tasks; private double accuracy; public Interval(Period period, ArrayList<Requirement> requirements, Task lastTask, ArrayList<Task> tasks, double accuracy, long id) { super(id); this.period = period; this.requirements = requirements; this.lastTask = lastTask; this.tasks = tasks; this.accuracy = accuracy; } public double getAccuracy() { return accuracy; } public void setAccuracy(double accuracy) { this.accuracy = accuracy; } public Task getLastTask() { return lastTask; } public void setLastTask(Task lastTask) { this.lastTask = lastTask; } public Period getPeriod() { return period; } public void setPeriod(Period duration) { this.period = duration; } public ArrayList<Requirement> getRequirements() { return requirements; } public void setRequirements(ArrayList<Requirement> requirements) { this.requirements = requirements; } public int intervalToDays() { int res = (int) (this.period.getYears() * 365 + this.period.getMonths() * MONTH_IN_DAYS + this.period.getDays()); return res; } @Override public String toString() { return "Interval{Period: " + this.period + ", intervalToDays():" + this.intervalToDays() + "}"; } public ArrayList<Task> getTasks() { return tasks; } public void setTasks(ArrayList<Task> tasks) { this.tasks = tasks; } }
true
f201e06bccfbe0dc83f414eaaf15fedfd23189fe
Java
HatemBay/donationJAVAFX
/src/javafxapplication1/DisplayAssociationAdminController.java
UTF-8
9,702
1.882813
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 javafxapplication1; import com.donation.Entite.Association; import com.donation.Service.ServiceAssociation; import java.io.IOException; import java.net.URL; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.ResourceBundle; import java.util.logging.Level; import java.util.logging.Logger; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.geometry.Insets; import javafx.scene.Node; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.PasswordField; import javafx.scene.control.RadioButton; import javafx.scene.control.TextArea; import javafx.scene.control.TextField; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.input.KeyEvent; import javafx.scene.input.MouseEvent; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.Background; import javafx.scene.layout.BackgroundFill; import javafx.scene.layout.CornerRadii; import javafx.scene.layout.Pane; import static javafx.scene.layout.Region.USE_COMPUTED_SIZE; import javafx.scene.layout.VBox; import javafx.scene.paint.Color; import javafx.stage.Stage; /** * FXML Controller class * * @author Tarek */ public class DisplayAssociationAdminController implements Initializable { @FXML private AnchorPane main; @FXML private VBox associationcontainer; @FXML private ImageView menu; com.donation.Service.ServiceAssociation SA = new ServiceAssociation(); @FXML private TextField name; @FXML private TextField objectif; @FXML private PasswordField password; @FXML private Button browse; @FXML private TextArea about; @FXML private TextField type; @FXML private TextArea address; @FXML private TextField email; @FXML private Button update; @FXML private Pane modifform; @FXML private Button fermeture; @FXML private TextField image; @FXML private TextField search; @FXML private RadioButton sortdate; @FXML private RadioButton sortname; @FXML private Button home; @FXML private Button events; @FXML private Button donations; @FXML private Button associations; @FXML private Button volunteering; @FXML private Button actions; @FXML private Button logout; /** * Initializes the controller class. */ @Override public void initialize(URL url, ResourceBundle rb) { fermeture.setBackground(Background.EMPTY); try { modifform.setVisible(false); List<Association> associations = SA.getAssociations(); Association connected = SA.getById(5); afficher(associations); Image men = new Image("pics/admin.jpg"); menu.setPreserveRatio(false); menu.setImage(men); } catch (SQLException ex) { Logger.getLogger(DisplayAssociationController.class.getName()).log(Level.SEVERE, null, ex); } } private void afficher(List<Association> associations) throws SQLException { Association connected = SA.getById(5); associationcontainer.getChildren().clear(); for (int i = 0; i < associations.size(); i++) { Association actuel = associations.get(i); Pane single = new Pane(); single.setPrefHeight(150); single.setPrefWidth(547); single.setBackground(new Background(new BackgroundFill(Color.WHITE, CornerRadii.EMPTY, Insets.EMPTY))); ImageView logo = new ImageView(); logo.setLayoutX(3); logo.setLayoutY(3); logo.setFitWidth(136); logo.setFitHeight(147); logo.setPreserveRatio(false); Image log = new Image(actuel.getLogo_Association()); logo.setImage(log); Label name = new Label(); name.setPrefHeight(27); name.setPrefWidth(USE_COMPUTED_SIZE); name.setLayoutX(166); name.setLayoutY(20); name.setStyle("-fx-font-size :18"); name.setText(actuel.getNom_Association()); Label type = new Label(); type.setPrefHeight(27); type.setPrefWidth(USE_COMPUTED_SIZE); type.setLayoutX(166); type.setLayoutY(47); type.setStyle("-fx-font-size :15"); type.setText(actuel.getType_Association()); Label location = new Label(); location.setPrefHeight(27); location.setPrefWidth(USE_COMPUTED_SIZE); location.setLayoutX(180); location.setLayoutY(72); location.setStyle("-fx-font-size :12"); location.setText(actuel.getAddress_Association()); ImageView marker = new ImageView(); marker.setLayoutX(163); marker.setLayoutY(78); marker.setFitWidth(15); marker.setFitHeight(15); marker.setPreserveRatio(false); Image mark = new Image("pics/pin.png"); marker.setImage(mark); Label description = new Label(); description.setPrefHeight(27); description.setPrefWidth(USE_COMPUTED_SIZE); description.setLayoutX(164); description.setLayoutY(100); description.setStyle("-fx-font-size :12"); description.setText(actuel.getDescription_Association()); Button supprimer = new Button("X"); supprimer.setPrefHeight(15); supprimer.setPrefWidth(15); supprimer.setLayoutX(519); supprimer.setLayoutY(3); supprimer.setVisible(true); supprimer.setOnMouseClicked((MouseEvent e) -> { try { SA.deleteAssociation(actuel); AnchorPane redirect; redirect = FXMLLoader.load(getClass().getResource("DisplayAssociationAdmin.fxml")); main.getChildren().setAll(redirect); } catch (SQLException ex) { Logger.getLogger(DisplayAssociationController.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(DisplayAssociationController.class.getName()).log(Level.SEVERE, null, ex); } }); single.getChildren().add(logo); single.getChildren().add(name); single.getChildren().add(type); single.getChildren().add(location); single.getChildren().add(marker); single.getChildren().add(description); single.getChildren().add(supprimer); associationcontainer.getChildren().add(single); } } @FXML private void searchAction(KeyEvent event) throws SQLException { String m = search.getText(); ArrayList<Association> a = (ArrayList<Association>) SA.SearchAssociations(m); ObservableList<Association> obs = FXCollections.observableArrayList(a); afficher(obs); } @FXML private void sortdate(ActionEvent event) throws SQLException { associationcontainer.getChildren().clear(); sortname.setSelected(false); afficher(SA.TrierAssociations(1)); } @FXML private void sortname(ActionEvent event) throws SQLException { sortdate.setSelected(false); associationcontainer.getChildren().clear(); afficher(SA.TrierAssociations(2)); } @FXML private void toHome(ActionEvent event) throws IOException { Parent tableViewParent = FXMLLoader.load(getClass().getResource("HomeAdmin.fxml")); Scene tableViewScene = new Scene(tableViewParent); //This line gets the Stage information Stage window = (Stage) ((Node) event.getSource()).getScene().getWindow(); window.setScene(tableViewScene); window.show(); } @FXML private void toProducts(ActionEvent event) { } @FXML private void toEvents(ActionEvent event) { } @FXML private void toDonations(ActionEvent event) { } @FXML private void toAssociations(ActionEvent event) throws IOException { Parent tableViewParent = FXMLLoader.load(getClass().getResource("DisplayAssociationAdmin.fxml")); Scene tableViewScene = new Scene(tableViewParent); //This line gets the Stage information Stage window = (Stage) ((Node) event.getSource()).getScene().getWindow(); window.setScene(tableViewScene); window.show(); } @FXML private void toVolunteering(ActionEvent event) { } @FXML private void toActions(ActionEvent event) throws IOException { Parent tableViewParent = FXMLLoader.load(getClass().getResource("DisplayActionAdmin.fxml")); Scene tableViewScene = new Scene(tableViewParent); //This line gets the Stage information Stage window = (Stage) ((Node) event.getSource()).getScene().getWindow(); window.setScene(tableViewScene); window.show(); } @FXML private void logout(ActionEvent event) { } }
true
4786fbb2feb52773a95eaa3bee3ee502c53e764e
Java
jeon9825/grade3_Algorithm
/03 -2 고급정렬/Exercise3_3/quickSort.java
UTF-8
796
3.765625
4
[]
no_license
import java.util.Arrays; public class quickSort { static void swap(String[] s, int index1, int index2) { String temp = s[index1]; s[index1] = s[index2]; s[index2] = temp; } static int partition(String[] s, int start, int end) { int i = start - 1; String value = s[end]; for (int j = start; j < end; j++) { if (s[j].compareTo(value) < 0) swap(s, ++i, j); } swap(s, ++i, end); return i; } static void quickSort(String[] s, int start, int end) { if (start >= end) return; int middle = partition(s, start, end); quickSort(s, start, middle - 1); quickSort(s, middle + 1, end); } public static void main(String[] args) { String[] s = { "AAA", "FFF", "CCC", "BBB", "TTT" }; quickSort(s, 0, s.length - 1); System.out.println(Arrays.toString(s)); } }
true
37ac393839dc3e6371cfd718a369b9fa4ca28805
Java
AgriCraft/AgriCraft
/src/main/java/com/infinityraider/agricraft/plugins/strawgolemreborn/StrawGolemRebornCompat.java
UTF-8
1,489
2.125
2
[ "MIT" ]
permissive
package com.infinityraider.agricraft.plugins.strawgolemreborn; import com.google.common.collect.Lists; import com.infinityraider.agricraft.content.AgriTileRegistry; import com.infinityraider.agricraft.content.core.TileEntityCrop; import com.t2pellet.strawgolem.crop.CropRegistry; import com.t2pellet.strawgolem.entity.EntityStrawGolem; import net.minecraft.core.BlockPos; import net.minecraft.server.level.ServerLevel; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; import java.util.List; class StrawGolemRebornCompat { static void init() { AgriCropLogic logic = new AgriCropLogic(); AgriTileRegistry.getInstance().crop.onRegistration(t -> CropRegistry.INSTANCE.register(t, logic, logic, logic)); } private static class AgriCropLogic implements CropRegistry.IHarvestChecker<TileEntityCrop>, CropRegistry.IHarvestLogic<TileEntityCrop>, CropRegistry.IReplantLogic<TileEntityCrop> { @Override public boolean isMature(TileEntityCrop crop) { return crop.isMature(); } @Override public List<ItemStack> doHarvest(ServerLevel level, EntityStrawGolem golem, BlockPos pos, TileEntityCrop crop) { List<ItemStack> drops = Lists.newArrayList(); crop.harvest(drops::add, golem); return drops; } @Override public void doReplant(Level level, BlockPos pos, TileEntityCrop crop) { // do nothing } } }
true
d1d17684232008f5dfef8b5eabe9c56007a6a7b2
Java
magefree/mage
/Mage.Sets/src/mage/cards/b/BayouGroff.java
UTF-8
1,343
2.421875
2
[ "MIT" ]
permissive
package mage.cards.b; import mage.MageInt; import mage.abilities.costs.OrCost; import mage.abilities.costs.common.SacrificeTargetCost; import mage.abilities.costs.mana.GenericManaCost; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.SubType; import mage.filter.StaticFilters; import mage.target.common.TargetControlledPermanent; import java.util.UUID; /** * @author TheElk801 */ public final class BayouGroff extends CardImpl { public BayouGroff(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{1}{G}"); this.subtype.add(SubType.PLANT); this.subtype.add(SubType.DOG); this.power = new MageInt(5); this.toughness = new MageInt(4); // As an additional cost to cast this spell, sacrifice a creature or pay {3}. this.getSpellAbility().addCost(new OrCost( "sacrifice a creature or pay {3}", new SacrificeTargetCost(new TargetControlledPermanent( StaticFilters.FILTER_CONTROLLED_CREATURE_SHORT_TEXT )), new GenericManaCost(3) )); } private BayouGroff(final BayouGroff card) { super(card); } @Override public BayouGroff copy() { return new BayouGroff(this); } }
true
2550addb4e31069ec87b39cd2fc857a78f408b66
Java
rentty/rent
/src/main/java/com/rent/controller/HouseShowController.java
UTF-8
2,666
2.25
2
[]
no_license
package com.rent.controller; import com.rent.bean.Housedl; import com.rent.bean.showHousedl; import com.rent.common.Result; import com.rent.service.House_managementService; import com.rent.service.impl.showHousedlM; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import java.util.ArrayList; import java.util.List; @Api("房屋展示") @RestController public class HouseShowController { @Autowired House_managementService house_managementService; @ApiOperation(value = "获取房屋信息") @GetMapping("/showSingle") @ResponseBody public Result getHouses() { return Result.ok().data("houses",house_managementService.showHousesByRent()); } @ApiOperation(value = "获取房屋详细信息") @GetMapping("/showDetail") @ResponseBody public Result getHouseDetail(Integer id) { return Result.ok().data("housedetail",house_managementService.showHouseDetail(id)); } @ApiOperation(value = "查询房屋") @GetMapping("/query") @ResponseBody public Result queryHouses(@RequestParam(value = "keyword", required = false) String keyword, @RequestParam(value = "a", required = false,defaultValue = "101") String district, @RequestParam(value = "b", required = false,defaultValue = "501") String type, @RequestParam(value = "c", required = false,defaultValue = "601") String rent) { List<String> list = new ArrayList<String>(); if(district != null && !StringUtils.isBlank(district)) { list.add(district); } if(type != null && !StringUtils.isBlank(type)) { list.add(type); } if(rent != null && !StringUtils.isBlank(rent)) { list.add(rent); } return Result.ok().data("houses", house_managementService.searchEntity(keyword,list)); } //获取条目栏------------------------------------------------------------------------ @ApiOperation(value = "获取筛选栏目和条件") @GetMapping("/showValue") @ResponseBody public Result getValues(@RequestParam(value="city", required = false, defaultValue = "广州") String city) { return Result.ok().data("dialogs",house_managementService.getSearchCondition()).data("entrydls",house_managementService.getSearchValue(city)); } }
true
52fc2e9cd0d5453caa9c2bc07eb2dc4e18236ca2
Java
hazemmasarani/fruit-ninja
/src/models/ObjThrow.java
UTF-8
1,294
2.1875
2
[]
no_license
package models; import javafx.animation.ParallelTransition; import javafx.scene.image.Image; import javafx.scene.image.ImageView; public interface ObjThrow { public void updateImageSize( int timeSizeMinimizer ); public void setThrowTransition(ParallelTransition parallelTransition); public void setCutTransitionLeft(ParallelTransition parallelTransition); public void setCutTransitionRight(ParallelTransition parallelTransition); public ParallelTransition getThrowTransition(); public ParallelTransition getCutTransitionLeft(); public ParallelTransition getCutTransitionRight(); public void cutTransition(); public Image getImage(); public ImageView getImageView(); public ImageView getImageView1(); public ImageView getImageView2(); public ImageView getImageView3(); public void updateImageView(); public void updateImageViewOrigin(); public boolean isBomb(); public boolean isDenamite(); public int getXposition(); public int getYposition(); public void updateXYposition(); public int getXOrigin(); public int getYOrigin(); public void setOrigin(int x,int y); public int getCurrentDirection(); public void setCurrentDirection(int direction); public Boolean isOffScreen(); public Boolean isSliced(); public void slice(); }
true
0a2f33d5321de63eec9a0b6aad82cf49943fead4
Java
ahmedifhaam/dhis2-android-sdk
/core-rules/src/main/java/org/hisp/dhis/rules/functions/RuleFunctionModulus.java
UTF-8
1,539
2.71875
3
[ "BSD-3-Clause" ]
permissive
package org.hisp.dhis.rules.functions; import org.hisp.dhis.rules.RuleVariableValue; import java.util.List; import java.util.Map; import javax.annotation.Nonnull; import javax.annotation.Nullable; /** * Produces the modulus when dividing the first with the second argument. */ final class RuleFunctionModulus extends RuleFunction { static final String D2_MODULUS = "d2:modulus"; @Nonnull static RuleFunctionModulus create() { return new RuleFunctionModulus(); } @Nonnull @Override public String evaluate(@Nonnull List<String> arguments, Map<String, RuleVariableValue> valueMap) { if (arguments == null) { throw new IllegalArgumentException( "Al most dividend and divisor arguments was expected"); } else if (arguments.size() != 2) { throw new IllegalArgumentException( "Al most dividend and divisor arguments was expected, " + arguments.size() + " were supplied"); } return String.valueOf(toInt(arguments.get(0)) % toInt(arguments.get(1))); } private static int toInt(@Nullable final String str) { try { return (int) Double.parseDouble(str); } catch (NumberFormatException exception) { throw new IllegalArgumentException(exception.getMessage(), exception); } catch (NullPointerException exception) { throw new IllegalArgumentException(exception.getMessage(), exception); } } }
true
d7bc04c7cd289c6897170be27d38ff1b6c4bf4c4
Java
Gustavokmp/facisa-map-308511
/Atividade 7/src/NumeroUm.java
UTF-8
103
2.09375
2
[]
no_license
public class NumeroUm extends Caractere{ public void imprimir() { System.out.print("1"); } }
true
4bb9a5ae8ebaf06253be4d9707447f015666067f
Java
HeavenlyBuns/SpringCaseBox
/spring-cloud-test/hystrixs/hystrix-dashboard/src/main/java/com/shehaoran/springcloud/hystrixdashboard/HystrixDashboardApplication.java
UTF-8
1,835
2.15625
2
[]
no_license
package com.shehaoran.springcloud.hystrixdashboard; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard; /** *启用 Hystrix Dashboard 功能。 */ @EnableHystrixDashboard @SpringBootApplication public class HystrixDashboardApplication { /** * 1.Hystrix-Dashboard 的主界面上输入要监控的服务例如: hystrix * 监控的服务需要: @EnableHystrix * 添加配置: * management: endpoints: web: exposure: include: hystrix.stream * * 2.该服务对应的地址 http://localhost:9004/actuator/hystrix.stream * 3.然后点击 Monitor Stream 按钮,进入页面。 * * 如果没有请求会一直显示 “Loading…”,这时访问 http://localhost:9004/actuator/hystrix.stream 也是不断的显示 “ping”。 */ public static void main(String[] args) { SpringApplication.run(HystrixDashboardApplication.class, args); } /** * 默认的集群监控:通过 URL:http://turbine-hostname:port/turbine.stream 开启,实现对默认集群的监控。 * 指定的集群监控:通过 URL:http://turbine-hostname:port/turbine.stream?cluster=[clusterName] 开启,实现对 clusterName 集群的监控。 * 单体应用的监控: 实现对具体某个服务实例的监控。 *( 现在这里的 URL 应该为 http://hystrix-app:port/actuator/hystrix.stream, * Actuator 2.x 以后  endpoints 全部在 /actuator 下,可以通过 * management.endpoints.web.base-path 修改) */ }
true
5d954a535d4fa5ff5bb2ac8c582df56444fca8ff
Java
klinker24/talon-for-twitter-android
/shared_assets/src/main/java/com/klinker/android/twitter_l/util/IoUtils.java
UTF-8
1,316
2.171875
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2014 Luke Klinker * * 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.klinker.android.twitter_l.util; import android.graphics.Bitmap; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; public class IoUtils { public void cacheBitmap(Bitmap bitmap, File file) throws Exception { file.getParentFile().mkdirs(); file.createNewFile(); FileOutputStream output = new FileOutputStream(file); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, output); output.close(); } public byte[] convertToByteArray(Bitmap bitmap) { ByteArrayOutputStream stream = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream); return stream.toByteArray(); } }
true
b755b8636dac9a01e074261b6e36405c8eb51c7c
Java
sudilshr/eTarkari
/src/com/etarkari/maps/Results.java
UTF-8
993
1.984375
2
[]
no_license
package com.etarkari.maps; import java.util.List; import com.google.gson.annotations.SerializedName; public class Results { public String getFormattedAddress() { return formatted_address; } public String getIcon() { return icon; } public String getId() { return id; } public String getName() { return name; } public Double getRating() { return rating; } public String getReference() { return reference; } public List<String> getTypes() { return types; } @SerializedName("formatted_address") private String formatted_address; @SerializedName("icon") private String icon; @SerializedName("id") private String id; @SerializedName("name") private String name; @SerializedName("rating") private Double rating; @SerializedName("reference") private String reference; @SerializedName("types") private List<String> types; }
true
4883e038f265a9402efd80eb255b61ce4cf2d2af
Java
sengeiou/chp-core
/.svn/pristine/48/4883e038f265a9402efd80eb255b61ce4cf2d2af.svn-base
UTF-8
1,640
2.125
2
[]
no_license
package com.creditharmony.core.common.entity.ex; import java.util.Date; /** * 已分配门店信息 * @author chenwd * */ public class StoreAssigned { private String memberId; //分配给的成员id private String memberName; //分配给的成员姓名 private String groupName; //分配成员所属的小组(机构)名称 private Integer storeAssignedCount; //该成员已分配的门店数量 private String storeName; //分配的门店名称 private Date assignTime; //分配时间 private String dataDomainId; //分配关系主键 public String getMemberId() { return memberId; } public void setMemberId(String memberId) { this.memberId = memberId; } public String getMemberName() { return memberName; } public void setMemberName(String memberName) { this.memberName = memberName; } public String getGroupName() { return groupName; } public void setGroupName(String groupName) { this.groupName = groupName; } public Integer getStoreAssignedCount() { return storeAssignedCount; } public void setStoreAssignedCount(Integer storeAssignedCount) { this.storeAssignedCount = storeAssignedCount; } public String getStoreName() { return storeName; } public void setStoreName(String storeName) { this.storeName = storeName; } public Date getAssignTime() { return assignTime; } public void setAssignTime(Date assignTime) { this.assignTime = assignTime; } public String getDataDomainId() { return dataDomainId; } public void setDataDomainId(String dataDomainId) { this.dataDomainId = dataDomainId; } }
true
00f8406736e12e31b8177fbb99b8321765933fa7
Java
vova-mark/javacore
/src/main/java/center/kit/app/classwork/lesson5/CircleArea.java
UTF-8
771
3.84375
4
[]
no_license
package center.kit.app.classwork.lesson5; import java.util.Scanner; public class CircleArea { public static float calculateCircleArea(float radius){ float circleArea = (float)Math.PI * (float)Math.pow(radius, 2); return circleArea; } public static String calculateBigger(float radius1, float radius2){ double area1 = CircleArea.calculateCircleArea(radius1); double area2 = CircleArea.calculateCircleArea(radius2); if ((radius1 > radius2)||(area1 > area2)){ return "Area of first circle is bigger"; } else if ((radius1 == radius2)||(area1 == area2)){ return "Areas are equal"; } else { return "Area of second circle is bigger"; } } }
true
5d78c70ca01d3757cd35658c5ba5f09597bc4c80
Java
wushunming/Java.UMC.Data
/src/UMC/Data/Sql/SqlUtils.java
UTF-8
564
2.09375
2
[]
no_license
package UMC.Data.Sql; import UMC.Data.Database; import UMC.Data.Utility; import java.util.Map; public class SqlUtils { public static ISqler sqler(Database.IProgress progress, DbProvider provider, boolean autoPfx) { return new Sqler(progress, provider, autoPfx); } public static <T> IObjectEntity objectEntity(ISqler sqler, DbProvider provider, Class<T> tClass) { return new ObjectEntity<T>(sqler, provider, tClass); } public static Map<String, Object> fieldMap(Object obj) { return Utility.fieldMap(obj); } }
true
275309d9ebdb40779ef37aa162c9233c37d8db16
Java
ldj8683/javaBasic
/java11/src/arrayApplication/InputIntoArrayQuiz01.java
UTF-8
1,016
4
4
[]
no_license
package arrayApplication; import javax.swing.JOptionPane; public class InputIntoArrayQuiz01 { public static void main(String[] args) { String[] s1 = new String[3]; String[] s2 = new String[3]; // 입력 // 작년에 가고 싶었던 곳 for (int i = 0; i < s1.length; i++) { s1[i] = JOptionPane.showInputDialog("작년에 가고 싶었던 곳을 입력하세요."); } // 올해 가고 싶었던 곳 for (int i = 0; i < s2.length; i++) { s2[i] = JOptionPane.showInputDialog("올해에 가고 싶었던 곳을 입력하세요."); } // 확인하기 위한 출력 for (int i = 0; i < s2.length; i++) { System.out.println(s1[i] + " " + s2[i]); } int count = 0; // 처리(if문), 출력(println) for (int i = 0; i < s1.length; i++) { for (int j = 0; j < s2.length; j++) { if (s2[j].equals(s1[i])) { count++; System.out.println("일치하는 장소는 " + s2[j] + "입니다."); } } } System.out.println("같은 위치의 개수는 " + count); } }
true
681cb77fb765e24fc0cc1508018cb33d501c00df
Java
43ndr1k/Digital-Text-Forensics
/src/main/java/de/uni_leipzig/digital_text_forensics/preprocessing/ConvertPdfXML.java
UTF-8
17,650
2.46875
2
[ "Apache-2.0" ]
permissive
package de.uni_leipzig.digital_text_forensics.preprocessing; import java.io.File; import java.io.IOException; import java.text.DateFormat; import java.text.SimpleDateFormat; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; // might not be needed later. import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.text.PDFTextStripper; import org.springframework.stereotype.Component; import org.w3c.dom.DOMException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.xml.sax.SAXException; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.Locale; import org.apache.commons.io.FilenameUtils; import org.apache.commons.lang3.StringUtils; /** * ConvertPdfXML * <p> Converts Pdf-Files to XML-Files and provides an Interface * to load XML-Files into Article-Objects (see Article.java). * * @author Tobias Wenzel * */ @Component public class ConvertPdfXML { private DocumentBuilderFactory docFactory; private DocumentBuilder docBuilder; private WordOperationClass wordOps; private DateFormat formatter, snd_formatter; static String NO_ENTRY = "No proper data found."; public String outputPath; private int titleLikeLength; public int docear_i,pdfbox_i,titleLike_i, dblpTitle_i; /** <b> Constructor </b> * * <p> It shouldn't be necessary to set the Output-Path since it's always the same. * Never the less it's possible for testing purposes. * */ public ConvertPdfXML() { setOutputPath("xmlFiles/"); this.wordOps = new WordOperationClass(); this.formatter = new SimpleDateFormat("E MMM dd HH:mm:ss 'CEST' yyyy",Locale.ENGLISH); this.snd_formatter = new SimpleDateFormat("E MMM dd HH:mm:ss 'CET' yyyy",Locale.ENGLISH); titleLikeLength = 10; } public void setOutputPath(String outputPath){ this.outputPath = outputPath; } /** <p> Extracts the first page of a Doc and runs a NE-recognition. * with <b>pdfbox</b> * * @param stripper to extract first page of doc * @param doc with actual data * @return String containing authors * @throws IOException */ private String extractAuthors(PDFTextStripper stripper, PDDocument doc) throws IOException{ stripper.setStartPage(0); stripper.setEndPage(1); String firstPage= stripper.getText(doc); String pdfbeginning = wordOps.getNWords(firstPage, 300); WordOperationClass nameFinder = new WordOperationClass(); try { List<String> myNames = nameFinder.findName(pdfbeginning); if (myNames.isEmpty()){ return NO_ENTRY; } else{ if (myNames.size() == 1){ return myNames.get(0); } else { return StringUtils.join(myNames, ", "); } } } catch (IOException e) { e.printStackTrace(); } catch (java.lang.NullPointerException e){ return NO_ENTRY; } return NO_ENTRY; } /** <p> Writes Article Object to XML-File. * * @param article with Data * @param outputFile */ public void writeToXML(Article article, String outputFile) { this.docFactory = DocumentBuilderFactory.newInstance(); try { this.docBuilder = docFactory.newDocumentBuilder(); } catch (ParserConfigurationException e) { e.printStackTrace(); } Document doc = this.docBuilder.newDocument(); Element rootElement = doc.createElement("article"); doc.appendChild(rootElement); Element metaDataElement = doc.createElement("metaData"); rootElement.appendChild(metaDataElement); metaDataElement.setAttribute("docId", article.getDoi()); Element parseTimeElement = doc.createElement("parseTime"); parseTimeElement.appendChild(doc.createTextNode(article.getParseDate())); metaDataElement.appendChild(parseTimeElement); Element fileNameElement = doc.createElement("fileName"); fileNameElement.appendChild(doc.createTextNode(article.getFileName())); metaDataElement.appendChild(fileNameElement); Element filePathElement = doc.createElement("filePath"); filePathElement.appendChild(doc.createTextNode(article.getFilePath())); metaDataElement.appendChild(filePathElement); Element titleElement = doc.createElement("title"); titleElement.appendChild(doc.createTextNode(article.getTitle())); metaDataElement.appendChild(titleElement); Element authorElement = doc.createElement("authors"); authorElement.appendChild(doc.createTextNode(article.getAuthorsAsString())); metaDataElement.appendChild(authorElement); Element refCountElement = doc.createElement("refCount"); refCountElement.appendChild(doc.createTextNode(article.getRefCount())); metaDataElement.appendChild(refCountElement); Element pubDate = doc.createElement("publicationDate"); pubDate.appendChild(doc.createTextNode(article.getPublicationDate())); metaDataElement.appendChild(pubDate); Element textElements = doc.createElement("textElements"); rootElement.appendChild(textElements); Element articleAbstract = doc.createElement("abstract"); articleAbstract.appendChild(doc.createCDATASection(article.getMyAbstract())); textElements.appendChild(articleAbstract); Element fullTextElement = doc.createElement("fullText"); fullTextElement.appendChild(doc.createCDATASection(article.getFullText())); textElements.appendChild(fullTextElement); try { // write the content into xml file TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(new File(outputFile)); try{ transformer.transform(source, result); System.out.println("Wrote to "+ outputFile); } catch (javax.xml.transform.TransformerException npr) { /** * Write empty template. */ //System.out.println("Could not read Data correctly. You have to insert it manually."); Article dummyArticle; dummyArticle = new Article(); dummyArticle.setMyAbstract("\n\n\n\n"); dummyArticle.setTitle(" "); dummyArticle.setAuthorsString(" "); dummyArticle.setPublicationDate("DD.MM.YYYY"); dummyArticle.setDoi("0"); dummyArticle.setFullText(" "); dummyArticle.setRefCount("0"); dummyArticle.setJournal(" "); LocalDateTime now = LocalDateTime.now(); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); String parseTime = now.format(formatter); dummyArticle.setParseDate(parseTime); String fileName = FilenameUtils.getName(outputFile); dummyArticle.setFileName(fileName.substring(0, fileName.length()-".xml".length())+".pdf"); dummyArticle.setFilePath(outputFile); this.writeToXML(dummyArticle, outputFile); //npr.printStackTrace(); } } catch (TransformerException tfe) { tfe.printStackTrace(); } catch (java.lang.NullPointerException npr) { npr.printStackTrace(); } } // end of function public void run_from_controller(String filename) { try { this.run(new File(filename), 0); } catch (IOException e) { e.printStackTrace(); } } /** <p>Converts PDF file to XML-data * <li> First try to extract meta-data with <b>pdfbox</b>. If this fails use name-entity-recognition * and similar methods. * <li> writing in writeToXML * * * @param file * @param id as dummy-data. Can also be real docid. */ public void run(File file, int id) throws IOException{ DBLPDataAccessor da = new DBLPDataAccessor(); Article article = null; LocalDateTime now = LocalDateTime.now(); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); String parseTime = now.format(formatter); String originalFilename = file.getName(); String outputFileName = originalFilename.substring(0, originalFilename.length()-".pdf".length())+".xml"; String outputFilePath = this.outputPath+ outputFileName; try { String title = null; String author = null; String pubDateString = null; String pdfbox_title = null; String pdfbox_author = null; String namedEntityRecAuthor = null; String fullText = null; Boolean success = false; PDDocument myDoc = null; PDFTextStripper stripper = null; try { /*-------------------------------------------------------- * get doc with pdfbox *--------------------------------------------------------*/ myDoc = PDDocument.load(file); stripper = new PDFTextStripper(); pdfbox_title = wordOps.clean_field(myDoc.getDocumentInformation().getTitle(), true); pdfbox_author = wordOps.clean_field(myDoc.getDocumentInformation() .getAuthor(),false); pubDateString = myDoc.getDocumentInformation() .getCreationDate().getTime().toString(); stripper.setStartPage(0); stripper.setEndPage(Integer.MAX_VALUE); fullText = stripper.getText(myDoc); fullText = stripNonValidXMLCharacters(fullText); namedEntityRecAuthor = wordOps.clean_field(extractAuthors(stripper, myDoc),false); } catch (IOException ioe) { ioe.printStackTrace(); } catch (java.lang.NullPointerException npe) { pubDateString = NO_ENTRY; } finally { if( myDoc != null ) myDoc.close(); } if ((pdfbox_title.length()==0)) { /*---------------------------------------------- * CHECK TITLE *----------------------------------------------*/ title = NO_ENTRY; // String docearTitle = wordOps.clean_field(getFieldDocearStyle(file).trim(), true); // if (!docearTitle.equals(NO_ENTRY)) { // title = docearTitle; // success = true; // docear_i++; // } } else { title = pdfbox_title; pdfbox_i++; success = true; } if (success) { /*---------------------------------------------- * only use dblp if we have an ok title *----------------------------------------------*/ try{ article = da.getArticleObj(title); } catch(java.net.UnknownHostException uhe){ article = null; } } else { title = wordOps.clean_field(wordOps.getNWords(fullText, titleLikeLength),true); } if (article != null) { List<String> authors = article.getAuthors(); StringBuilder sb = new StringBuilder(); for (int i=0;i<authors.size();i++){ sb.append(authors.get(i)); } author = sb.toString(); pubDateString = article.getPublicationDate(); } else { article = new Article(); /*---------------------------------------------- * CHECK AUTHORS *----------------------------------------------*/ if ((pdfbox_author.length()==0)) { if ((namedEntityRecAuthor.length()==0)) { author = NO_ENTRY; } else { author = namedEntityRecAuthor; } } else { author = pdfbox_author; } } if (!(title.length()==0)) { if (title.length() > 999) { // Only consider if title-length is unusual String shorterTitle = wordOps.getNWords(title,100); if (shorterTitle.length() > 1000) { // If title is still longer (~ 1 Word) cut after character. article.setTitle(title.substring(0,999)); } } else { article.setTitle(title); } } else { // take the first n words as title String titleLike = wordOps.clean_field(wordOps.getNWords(fullText, titleLikeLength),true); if (titleLike.length() > 999) { // Only consider if title-length is unusual String shorterTitle = wordOps.getNWords(title,100); if (shorterTitle.length() > 1000) { // If title is still longer (~ 1 Word) cut after character. article.setTitle(titleLike.substring(0,999)); } } else { article.setTitle(title); } } pubDateString = this.changeDataFormat(pubDateString); String firstLowerCaseWords = wordOps.getNWords(fullText,500).toLowerCase(); String result = null; try { result = firstLowerCaseWords.substring(firstLowerCaseWords.indexOf("abstract") + 8, firstLowerCaseWords.indexOf("introduction")); } catch(java.lang.StringIndexOutOfBoundsException e){ } if (result != null){ article.setMyAbstract(wordOps.getNWords(result,150)); } else { article.setMyAbstract(""); } article.setAuthorsString(author); article.setPublicationDate(pubDateString); article.setFileName(originalFilename); article.setFilePath(outputFilePath); article.setDoi(String.valueOf(id)); article.setParseDate(parseTime.replace(" ", "T")); article.setFullText(fullText); if (article != null) { // finally write the article to xml. writeToXML(article,outputFilePath); } } catch (DOMException e1) { e1.printStackTrace(); } catch (java.lang.NullPointerException npe){ //npe.printStackTrace(); //System.out.println(file.getName()); } } // end of function /** Simplify date string to year or month and year. * * @param dateString * @return */ public String changeDataFormat(String dateString){ Date date = null; try { date = (Date)formatter.parse(dateString); } catch (java.lang.NullPointerException npe){ } catch (java.text.ParseException e) { try { date = (Date)snd_formatter.parse(dateString); } catch (java.text.ParseException e1) { return dateString; } } if (date != null){ Calendar cal = Calendar.getInstance(); cal.setTime(date); String month = cal.getDisplayName(Calendar.MONTH, Calendar.LONG, Locale.ENGLISH); return month+ " " + cal.get(Calendar.YEAR); } else { return null; } } /** <p>There are some characters which should not occur in a cdata section * these are filtered out in this function. Probably there is a more efficient * solution. <br> * Copied from {@link http://blog.mark-mclaren.info/2007/02/invalid-xml-characters-when-valid-utf8_5873.html} * * @param in String with Text to be cleaned. * @return */ public String stripNonValidXMLCharacters(String in) { StringBuffer out = new StringBuffer(); // Used to hold the output. char current; // Used to reference the current character. if (in == null || ("".equals(in))) return ""; // vacancy test. for (int i = 0; i < in.length(); i++) { current = in.charAt(i); // NOTE: No IndexOutOfBoundsException caught here; it should not happen. if ((current == 0x9) || (current == 0xA) || (current == 0xD) || ((current >= 0x20) && (current <= 0xD7FF)) || ((current >= 0xE000) && (current <= 0xFFFD)) || ((current >= 0x10000) && (current <= 0x10FFFF))) out.append(current); } return out.toString(); } /** * <p> Gets the index created in the indexing process and corresponding file, * i.e. xmlFiles/document.xml. then * <li> read xml with sax-parser -> maybe i can do this without building a * new xml-file. * <li> alter doi * <li> write doc back. * * * @param docId * @param file */ public void insertIndexerDOCID(String docId, File file) { Article article = getArticleFromXML(file); article.setDoi(docId); writeToXML(article,file.toString()); } // end of insertIndexerDOCID /** Reads XML-Data with Sax-Parser. * * @param file * @return Article Object */ public Article getArticleFromXML (File file){ Article article = null; SAXParserFactory saxParserFactory = SAXParserFactory.newInstance(); try { SAXParser saxParser = saxParserFactory.newSAXParser(); ArticleHandler handler = new ArticleHandler(); saxParser.parse(file, handler); article = handler.getArticle(); } catch (ParserConfigurationException pce){ pce.printStackTrace(); } catch(SAXException sae) { sae.printStackTrace(); }catch ( IOException ioe) { ioe.printStackTrace(); } return article; } // end of getArticleFromXML /** * Comment: Could be called by "run"-method (see commented code). Because of the use of the * 'heuristic title search' we left this out since it's essentially trying to do the same without * a guarantee to receive a valid title. * * @param file * @return */ // private String getFieldDocearStyle(File file) { // boolean empty = true; // StringBuilder sb = new StringBuilder(); // PdfDataExtractor extractor = new PdfDataExtractor(file); // try { // if (!empty) { // sb.append("|"); // } // try { // // String title = extractor.extractTitle(); // if (title != null) { // sb.append(wordOps.clean_field(title,true)); // empty = false; // } // } // catch (IOException e) { // sb.append(NO_ENTRY); // } // catch (de.intarsys.pdf.cos.COSSwapException cose) { // System.out.println("cos ex"+ file.toString()); // } // } // finally { // // extractor.close(); // extractor = null; // } // return sb.toString(); // } } // end of class
true
40eb6c76cc1cb5f740b0789e69f1d7c30a36e8e7
Java
jneyrach/hr-salieri
/Tmp/asistencia-persistence/src/main/java/com/synapsis/rrhh/asistencia/persistence/service/EntityQueryParameter.java
UTF-8
1,043
2.0625
2
[]
no_license
package com.synapsis.rrhh.asistencia.persistence.service; public class EntityQueryParameter { private int parCode; private int parOrdinal; private String parName; private Class parType; public int getParCode() { return parCode; } public void setParCode(int parCode) { this.parCode = parCode; } public int getParOrdinal() { return parOrdinal; } public void setParOrdinal(int parOrdinal) { this.parOrdinal = parOrdinal; } public String getParName() { return parName; } public void setParName(String parName) { this.parName = parName; } public Class getParType() { return parType; } public void setParType(Class parType) { this.parType = parType; } public EntityQueryParameter(int parCode, int parOrdinal, String parName, Class parType) { this.parCode = parCode; this.parOrdinal = parOrdinal; this.parName = parName; this.parType = parType; } }
true
1a4527d4dbbced082b0a899e268efa0f79d1de23
Java
selenium3007/1_Jan_Project
/LiveProject_1_JAN_6PM/Selenium_Maven/src/test/java/com/durgasoft/selenium/testNG/excel/Excel_API.java
UTF-8
4,206
2.78125
3
[]
no_license
package com.durgasoft.selenium.testNG.excel; import java.io.FileInputStream; import java.io.FileOutputStream; import org.apache.poi.ss.usermodel.CellType; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class Excel_API { public FileInputStream fis = null; public FileOutputStream fos = null; public XSSFWorkbook w = null; public XSSFSheet s = null; public XSSFRow row = null; public XSSFCell cell = null; String filePath; public Excel_API(String file) throws Exception { this.filePath = file; fis = new FileInputStream(filePath); w = new XSSFWorkbook(fis); fis.close(); } // Reading cell data from excel file by using index public String getCellData(String sheetName, int colNum, int rowNum) { try { s = w.getSheet(sheetName); row = s.getRow(rowNum); cell = row.getCell(colNum); if (cell.getCellTypeEnum() == CellType.STRING) { return cell.getStringCellValue(); } else if (cell.getCellTypeEnum() == CellType.NUMERIC || cell.getCellTypeEnum() == CellType.FORMULA) { String cellValue = String.valueOf(cell.getNumericCellValue()); return cellValue; } else if (cell.getCellTypeEnum() == CellType.BLANK) { return " "; } else { return String.valueOf(cell.getBooleanCellValue()); } } catch (Exception e) { e.printStackTrace(); return "No matching value"; } } // Reading cell data from excel file by using column name public String getCellData(String sheetName, String colName, int rowNum) { try { int colNum = -1; s = w.getSheet(sheetName); row = s.getRow(0); for (int i = 0; i < row.getLastCellNum(); i++) { //System.out.println(row.getCell(i).getStringCellValue()); if (row.getCell(i).getStringCellValue().equalsIgnoreCase(colName)) { colNum = i; } } row = s.getRow(rowNum); cell = row.getCell(colNum); if (cell.getCellTypeEnum() == CellType.STRING) { return cell.getStringCellValue(); } else if (cell.getCellTypeEnum() == CellType.NUMERIC || cell.getCellTypeEnum() == CellType.FORMULA) { String cellValue = String.valueOf(cell.getNumericCellValue()); return cellValue; } else if (cell.getCellTypeEnum() == CellType.BLANK) { return " "; } else { return String.valueOf(cell.getBooleanCellValue()); } } catch (Exception e) { e.printStackTrace(); return "No matching value"; } } //Writing cell data top excel file by using column index public Boolean setCellData(String sheetName,int colNum,int rowNum,String value) throws Exception{ try { s=w.getSheet(sheetName); row=s.getRow(rowNum); if(row==null) row=s.createRow(rowNum); cell=row.getCell(colNum); if(cell==null) cell=row.createCell(colNum); cell.setCellValue(value); fos=new FileOutputStream (filePath); w.write(fos); fos.close(); } catch (Exception e) { e.printStackTrace(); return false; } return true; } //Writing cell data top excel file by using column Name public Boolean setCellData(String sheetName,String colName,int rowNum,String value) throws Exception{ try { int colNum=-1; s=w.getSheet(sheetName); row=s.getRow(0); for (int i = 0; i < row.getLastCellNum(); i++) { //System.out.println(row.getCell(i).getStringCellValue()); if (row.getCell(i).getStringCellValue().equalsIgnoreCase(colName)) { colNum = i; } } row=s.getRow(rowNum); if(row==null) row=s.createRow(rowNum); cell=row.getCell(colNum); if(cell==null) cell=row.createCell(colNum); cell.setCellValue(value); fos=new FileOutputStream (filePath); w.write(fos); fos.close(); } catch (Exception e) { e.printStackTrace(); return false; } return true; } //Identify no-of rows and columns in excel file public int getRows(String sheetName) { s=w.getSheet(sheetName); int rowCount=s.getLastRowNum()+1; return rowCount; } public int getColumns(String sheetName) { s=w.getSheet(sheetName); row=s.getRow(0); int colCount=row.getLastCellNum(); return colCount; } }
true
5ecce4abc7ce284dd4703319fdd970dce0886dee
Java
ulfricarchive/commons
/src/test/java/com/ulfric/commons/value/OptionalHelperTest.java
UTF-8
716
2.40625
2
[]
no_license
package com.ulfric.commons.value; import org.junit.jupiter.api.Test; import com.google.common.truth.Truth8; import com.ulfric.veracity.suite.HelperTestSuite; import java.util.Optional; import java.util.stream.Stream; class OptionalHelperTest extends HelperTestSuite { OptionalHelperTest() { super(OptionalHelper.class); } @Test void testStreamOfPresent() { Optional<Object> optional = Optional.of(new Object()); Stream<Object> stream = OptionalHelper.stream(optional); Truth8.assertThat(stream).hasSize(1); } @Test void testStreamOfEmpty() { Optional<Object> optional = Optional.empty(); Stream<Object> stream = OptionalHelper.stream(optional); Truth8.assertThat(stream).isEmpty(); } }
true
332af79c2ccc67d00cecb458b6b79876d4e4cdef
Java
lawlin00/Consultation-Hour-Booking-System-for-APU-Medical-Center
/MedicalCenter/OODJProject/src/OODJProj1/Controller/C_User.java
UTF-8
11,215
2.265625
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 OODJProj1.Controller; import OODJProj1.DataLayer.D_User; import OODJProj1.Model.Users; import OODJProj1.Others.Validation_User; import com.github.lgooddatepicker.components.TimePicker; import java.nio.file.StandardOpenOption; import java.util.ArrayList; import java.util.List; import javax.swing.JOptionPane; /** * * @author User */ public class C_User extends ControllerMessages implements CRUDReadable<Users>{ public static Users login = null; D_User userData = new D_User(); static TimePicker timePicker; public static Users getLogin() { return login; } public static void setLogin(Users login) { C_User.login = login; } public void create(Users newUser) { Boolean isExist = false; try { for (int i = 0; i < userData.getAll().size(); i++) { Users User = userData.getAll().get(i); if (newUser.getName().equals(User.getUsername())) { isExist = true; break; } } if (isExist) { displayErrorMessage("The Username is exist! Please try another username. "); } else { userData.create(newUser); displaySuccessMessage("Created Successfully!"); } } catch (Exception ex) { System.out.println(ex); } } // public void EditUser(Users EditedUser) { // Boolean isExist = false; // V_UserList UserAccCMS = new V_UserList(this); // try { // for (int i = 0; i < data.getUsers().size(); i++) { // Users User = data.getUsers().get(i); // if (EditedUser.getUsername().equals(User.getUsername()) && EditedUser.getUid() != User.getUid()) { // isExist = true; // break; // } // } // // if (isExist) { // UserAccCMS.displayErrorMessage("The Username is exist! Please try another username. "); // } else { // ArrayList<String> newList = new ArrayList<String>(); // for (int i = 0; i < data.getUsers().size(); i++) { // Users allUser = data.getUsers().get(i); // if (EditedUser.getUid() == allUser.getUid()) { // newList.add(EditedUser.newUser()); // } else { // newList.add(allUser.newUser()); // } // } // // if (newList.size() > 0) { // data.delete("Users.txt"); // for (int i = 0; i < newList.size(); i++) { // data.writeTo(newList.get(i), "Users.txt"); // } // } // UserAccCMS.displaySuccessMessage("Edited Successfully!"); // } // // } catch (Exception ex) { // System.out.println(ex); // } // } @Override public void update(Users EditedUser) { Boolean isExist = false; boolean edited = false; //V_UserList UserAccCMS = new V_UserList(this); try { for (int i = 0; i < userData.getAll().size(); i++) { Users User = userData.getAll().get(i); if (EditedUser.getUsername().equals(User.getUsername()) && EditedUser.getUid() != User.getUid()) { isExist = true; break; } } if (isExist) { //UserAccCMS.displayErrorMessage("The Username is exist! Please try another username. "); edited = false; displayErrorMessage("Username already exists"); } else { ArrayList<String> newList = new ArrayList<String>(); ArrayList<Users> newUsersData = new ArrayList<Users>(); for (int i = 0; i < userData.getAll().size(); i++) { Users allUser = userData.getAll().get(i); if (EditedUser.getUid() == allUser.getUid()) { // newList.add(EditedUser.getLine()); newUsersData.add(EditedUser); } else { newUsersData.add(allUser); } } if (newUsersData.size() > 0) { userData.update(newUsersData); // for (int i = 0; i < newList.size(); i++) { // userData.writeTo(newList.get(i)); // } } //UserAccCMS.displaySuccessMessage("Edited Successfully!"); edited = true; displaySuccessMessage("Updated "); } } catch (Exception ex) { System.out.println(ex); } } public boolean edit(Users EditedUser) { Boolean isExist = false; boolean edited = false; //V_UserList UserAccCMS = new V_UserList(this); try { for (int i = 0; i < userData.getAll().size(); i++) { Users User = userData.getAll().get(i); if (EditedUser.getUsername().equals(User.getUsername()) && EditedUser.getUid() != User.getUid()) { isExist = true; break; } } if (isExist) { //UserAccCMS.displayErrorMessage("The Username is exist! Please try another username. "); edited = false; } else { ArrayList<String> newList = new ArrayList<String>(); ArrayList<Users> newUsersData = new ArrayList<Users>(); for (int i = 0; i < userData.getAll().size(); i++) { Users allUser = userData.getAll().get(i); if (EditedUser.getUid() == allUser.getUid()) { // newList.add(EditedUser.getLine()); newUsersData.add(EditedUser); } else { newUsersData.add(allUser); } } if (newUsersData.size() > 0) { userData.update(newUsersData); // for (int i = 0; i < newList.size(); i++) { // userData.writeTo(newList.get(i)); // } } //UserAccCMS.displaySuccessMessage("Edited Successfully!"); edited = true; } } catch (Exception ex) { System.out.println(ex); } return edited; } public void delete(Users DeletedUser) { Boolean isExist = false; try { for (int i = 0; i < userData.getAll().size(); i++) { Users User = userData.getAll().get(i); if (DeletedUser.getUid() == User.getUid()) { isExist = true; break; } } if (isExist) { ArrayList<Users> newUserData = new ArrayList<Users>(); for (int i = 0; i < userData.getAll().size(); i++) { Users allUser = userData.getAll().get(i); if (DeletedUser.getUid() != allUser.getUid()) { newUserData.add(allUser); } else { newUserData.remove(allUser); } } if (newUserData.size() > 0) { userData.update(newUserData); // for (int i = 0; i < newList.size(); i++) { // userData.writeTo(newList.get(i)); // } } displaySuccessMessage("Deleted Successfully!"); } else { displayErrorMessage("Unexpected error occurs!"); } } catch (Exception ex) { System.out.println(ex); } } public Users getModel(String uid) { Users user = new Users(); for (int i = 0; i < userData.getAll().size(); i++) { Users allUser = userData.getAll().get(i); if (uid.equals(String.valueOf(allUser.getUid()))) { user = new Users(allUser.getUid(), allUser.getName(), allUser.getUsername(), allUser.getPassword(), allUser.getIsadmin(), allUser.getSelfdescription()); } } return user; } public ArrayList<Users> getModelList() { ArrayList<Users> userList = userData.getAll(); return userList; } public ArrayList<Users> FilterUser(String role){ boolean isAdmin = false; if(role.toLowerCase().equals("Admin")){ isAdmin = true; } ArrayList<Users> userList = userData.getAll(); ArrayList<Users> RoleList = new ArrayList<Users>(); for (Users user : userList) { if (user.getIsadmin() == isAdmin) { RoleList.add(user); } } return RoleList; } public ArrayList<Users> SearchUser(String searchkey) { ArrayList<Users> userList = userData.getAll(); ArrayList<Users> SearchUserResult = new ArrayList<Users>(); for (Users user : userList) { if (user.getName().contains(searchkey) | user.getUsername().contains(searchkey)) { SearchUserResult.add(user); } } return SearchUserResult; } public boolean Login(String username, String pwd) { boolean LoginSuccess = false; for (int i = 0; i < userData.getAll().size(); i++) { Users allUser = userData.getAll().get(i); if (username.trim().equals(allUser.getUsername().trim()) && pwd.equals(allUser.getPassword())) { login = allUser; LoginSuccess = true; break; } } return LoginSuccess; } public boolean Logout() { login = null; Boolean Logout = true; return Logout; } public String ChangePwd(String oldpwd, String newpwd, String retypepwd){ boolean success = false; Validation_User validation = new Validation_User(); boolean notEmpty = validation.required(oldpwd,newpwd,retypepwd); String errormsg = ""; if(notEmpty){ Users userInfo = getModel(String.valueOf(login.getUid())); if(!oldpwd.equals(userInfo.getPassword())){ System.out.println(userInfo.getPassword()); errormsg = "Old Password is incorrect! Please try again!"; }else{ if(!newpwd.equals(retypepwd)){ errormsg = "New password is not same with retype password! Please try again!"; } } }else{ errormsg = "Old Password, New Password, Retype Password fields is Required! "; } return errormsg; } }
true
e0ebccfce17847dcb73212073cacbf98a52844e7
Java
bellmit/algorithms
/leetcode/src/main/java/test/concurrent/ThreadPoolFactory.java
UTF-8
2,305
2.71875
3
[]
no_license
package test.concurrent; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.Executors; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import com.google.common.util.concurrent.ListeningExecutorService; import com.google.common.util.concurrent.MoreExecutors; public class ThreadPoolFactory { public static final int DEFAULT_POOL_SIZE = 20; public static final int DEFAULT_BLOCKING_SIZE = 500; private static final Map<Integer,ThreadPoolExecutor> poolMap = new HashMap<Integer,ThreadPoolExecutor>(); public static ListeningExecutorService getCacheService() { return MoreExecutors.listeningDecorator(Executors.newCachedThreadPool()); } public static ListeningExecutorService getFixedService(Integer size) { if (size <= 0) { return MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(DEFAULT_POOL_SIZE)); } return MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(size)); } public static ListeningExecutorService getCommomExecutorService() { return getCommomExecutorService(DEFAULT_POOL_SIZE, DEFAULT_POOL_SIZE); } public static ListeningExecutorService getCommomExecutorService(Integer coreSize, Integer maxSize) { return getCommomExecutorService(coreSize, maxSize, null); } public static ListeningExecutorService getCommomExecutorService(Integer coreSize, Integer maxSize, BlockingQueue<Runnable> workQueue) { coreSize = coreSize == null ? DEFAULT_POOL_SIZE : coreSize; maxSize = maxSize == null ? DEFAULT_POOL_SIZE : maxSize; workQueue = workQueue==null ? new ArrayBlockingQueue<Runnable>(DEFAULT_BLOCKING_SIZE) : workQueue; ThreadPoolExecutor executor = new ThreadPoolExecutor(coreSize, maxSize, 0L, TimeUnit.MILLISECONDS, workQueue, new ThreadPoolQueueFullHanlder()); ListeningExecutorService listeningDecorator = MoreExecutors.listeningDecorator(executor); if(!poolMap.containsKey(listeningDecorator.hashCode())){ poolMap.put(listeningDecorator.hashCode(), executor); } return listeningDecorator; } public static Map<Integer, ThreadPoolExecutor> getPoolmap() { return poolMap; } }
true
aac29e75fde342f87a999b02ace2dfacbab0aa46
Java
Gtm417/final-project
/src/main/java/ua/training/cruise/repository/CruiseRepository.java
UTF-8
225
1.617188
2
[]
no_license
package ua.training.cruise.repository; import org.springframework.data.jpa.repository.JpaRepository; import ua.training.cruise.entity.cruise.Cruise; public interface CruiseRepository extends JpaRepository<Cruise, Long> { }
true
8a6fe593d0265885b43491fde89fea8b09096bfc
Java
EncoderDevelopment/facilli
/src/br/com/facili/cenario/tela/CenarioTelaInicio.java
UTF-8
1,146
2.234375
2
[]
no_license
package br.com.facili.cenario.tela; import static br.com.facili.configuracao.dispositivo.ConfiguracaoDispositivo.alturaDaCena; import static br.com.facili.configuracao.dispositivo.ConfiguracaoDispositivo.larguraDaCena; import org.cocos2d.layers.CCLayer; import org.cocos2d.layers.CCScene; import org.cocos2d.nodes.CCSprite; import org.cocos2d.types.CGPoint; import br.com.facili.cenario.menu.CenarioMenuInicio; import br.com.facili.componente.ComponenteImagem; import br.com.facili.configuracao.dispositivo.ConfiguracaoImagemCaminho; public class CenarioTelaInicio extends CCLayer{ public CenarioTelaInicio() { ComponenteImagem imagemCenarioFundoTela = new ComponenteImagem(ConfiguracaoImagemCaminho.FUNDO_MENU); imagemCenarioFundoTela.setPosition(CGPoint.ccp(larguraDaCena() / 2.f, alturaDaCena() / 2.f)); addChild(imagemCenarioFundoTela); addChild(new CenarioMenuInicio()); } public CCScene criaCena(){ CCScene scene = CCScene.node(); scene.addChild(this); return scene; } public static CCScene criaCenario(){ CCScene cena = CCScene.node(); cena.addChild(new CenarioTelaInicio()); return cena; } }
true
273728e60c95c1413d54ece4d6c723ecc2a08545
Java
Ontotext-AD/graphdb-autocomplete-plugin
/src/test/java/com/ontotext/trree/plugin/autocomplete/AutocompletePluginTestBase.java
UTF-8
10,574
1.859375
2
[ "Apache-2.0" ]
permissive
package com.ontotext.trree.plugin.autocomplete; import com.ontotext.graphdb.Config; import com.ontotext.test.TemporaryLocalFolder; import com.ontotext.test.functional.base.SingleRepositoryFunctionalTest; import com.ontotext.test.utils.StandardUtils; import org.eclipse.rdf4j.common.io.IOUtil; import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Triple; import org.eclipse.rdf4j.model.Value; import org.eclipse.rdf4j.query.*; import org.eclipse.rdf4j.repository.RepositoryConnection; import org.eclipse.rdf4j.repository.RepositoryException; import org.eclipse.rdf4j.repository.config.RepositoryConfig; import org.eclipse.rdf4j.rio.RDFFormat; import org.eclipse.rdf4j.rio.RDFParseException; import org.eclipse.rdf4j.rio.helpers.NTriplesUtil; import org.junit.*; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.util.*; import static junit.framework.TestCase.assertEquals; import static org.junit.Assert.assertTrue; @RunWith(Parameterized.class) public abstract class AutocompletePluginTestBase extends SingleRepositoryFunctionalTest { private static final Logger LOG = LoggerFactory.getLogger(AutocompletePluginTestBase.class); private static final String AUTOCOMPLETE_QUERY_START = "SELECT ?s ?g WHERE { GRAPH ?g { ?s <http://www.ontotext.com/plugins/autocomplete#query> \""; private static final String GET_INDEX_STATUS = "SELECT ?s WHERE { ?o <http://www.ontotext.com/plugins/autocomplete#status> ?s . }"; private static final String IS_PLUGIN_ENABLED = "ASK WHERE { ?o <http://www.ontotext.com/plugins/autocomplete#enabled> ?s . }"; private static final String SHOULD_INDEX_IRIS = "ASK WHERE { ?o <http://www.ontotext.com/plugins/autocomplete#indexIRIs> ?s . }"; private static final String SET_SHOULD_INDEX_IRIS_INSERT = "INSERT DATA { _:s <http://www.ontotext.com/plugins/autocomplete#indexIRIs> \"%s\" . }"; private static final String SET_SHOULD_INDEX_IRIS_ASK = "ASK { GRAPH <http://www.ontotext.com/plugins/autocomplete#control> { _:s <http://www.ontotext.com/plugins/autocomplete#indexIRIs> \"%s\" . } }"; private static final String SET_ENABLE_INSERT = "INSERT DATA { _:s <http://www.ontotext.com/plugins/autocomplete#enabled> \"%s\" . }"; private static final String SET_ENABLE_ASK = "ASK { GRAPH <http://www.ontotext.com/plugins/autocomplete#control> { _:s <http://www.ontotext.com/plugins/autocomplete#enabled> \"%s\" . } }"; private static final String SET_REINDEX_INSERT = "INSERT DATA { _:s <http://www.ontotext.com/plugins/autocomplete#reIndex> true . }"; private static final String SET_REINDEX_ASK = "ASK { GRAPH <http://www.ontotext.com/plugins/autocomplete#control> { _:s <http://www.ontotext.com/plugins/autocomplete#reIndex> true . } }"; private static final String ADD_LABEL_CONFIG_INSERT = "INSERT DATA { <%s> <http://www.ontotext.com/plugins/autocomplete#addLabelConfig> \"%s\" }"; private static final String ADD_LABEL_CONFIG_ASK = "ASK { GRAPH <http://www.ontotext.com/plugins/autocomplete#control> { <%s> <http://www.ontotext.com/plugins/autocomplete#addLabelConfig> \"%s\" } }"; private static final String REMOVE_LABEL_CONFIG_INSERT = "INSERT DATA { <%s> <http://www.ontotext.com/plugins/autocomplete#removeLabelConfig> \"\" }"; private static final String REMOVE_LABEL_CONFIG_ASK = "ASK { GRAPH <http://www.ontotext.com/plugins/autocomplete#control> { <%s> <http://www.ontotext.com/plugins/autocomplete#removeLabelConfig> \"\" } }"; @Parameterized.Parameters static List<Object[]> getParams() { return Arrays.asList(new Object[][] { {false}, {true} }); } @ClassRule public static TemporaryLocalFolder tmpFolder = new TemporaryLocalFolder(); RepositoryConnection connection; private boolean useAskControl; AutocompletePluginTestBase(boolean useAskControl) { this.useAskControl = useAskControl; } @Override protected RepositoryConfig createRepositoryConfiguration() { // Test with the transactional entity pool as this is much likelier to discover potential issues System.setProperty("graphdb.engine.entity-pool-implementation", "transactional"); return StandardUtils.createOwlimSe("owl-horst-optimized"); } @BeforeClass public static void setWorkDir() { System.setProperty("graphdb.home.work", String.valueOf(tmpFolder.getRoot())); Config.reset(); } @AfterClass public static void resetWorkDir() { System.clearProperty("graphdb.home.work"); Config.reset(); } @Before public void setupConn() throws RepositoryException { connection = getRepository().getConnection(); } @After public void closeConn() throws RepositoryException { connection.close(); } private TupleQueryResult executeSparqlQuery(String query) throws Exception { return connection .prepareTupleQuery(QueryLanguage.SPARQL, query) .evaluate(); } protected TupleQueryResult executeSparqlQueryFromFile(String fileName) throws Exception { String query = IOUtil.readString( getClass().getResourceAsStream("/" + fileName + ".sparql")); return executeSparqlQuery(query); } void enablePlugin() throws Exception { setEnablePlugin(true); while (!getPluginStatus().startsWith(IndexStatus.READY.toString())) { Thread.sleep(1000L); } } void setEnablePlugin(boolean enablePlugin) throws Exception { connection.begin(); if (useAskControl) { connection.prepareBooleanQuery(String.format(SET_ENABLE_ASK, enablePlugin)).evaluate(); } else { connection.prepareUpdate(String.format(SET_ENABLE_INSERT, enablePlugin)).execute(); } connection.commit(); } void setShouldIndexIris(boolean shouldIndexIris) throws Exception { connection.begin(); if (useAskControl) { connection.prepareBooleanQuery(String.format(SET_SHOULD_INDEX_IRIS_ASK, shouldIndexIris)).evaluate(); } else { connection.prepareUpdate(String.format(SET_SHOULD_INDEX_IRIS_INSERT, shouldIndexIris)).execute(); } connection.commit(); } void disablePlugin() throws Exception { setEnablePlugin(false); } boolean isPluginEnabled() { return connection.prepareBooleanQuery(IS_PLUGIN_ENABLED).evaluate(); } boolean shouldIndexIRIs() { return connection.prepareBooleanQuery(SHOULD_INDEX_IRIS).evaluate(); } void reindex() throws Exception { connection.begin(); if (useAskControl) { connection.prepareBooleanQuery(SET_REINDEX_ASK).evaluate(); } else { connection.prepareUpdate(SET_REINDEX_INSERT).execute(); } connection.commit(); while (!getPluginStatus().startsWith(IndexStatus.READY.toString())) { Thread.sleep(1000L); } } String getPluginStatus() throws MalformedQueryException, RepositoryException, QueryEvaluationException { TupleQuery tq = connection.prepareTupleQuery(QueryLanguage.SPARQL, GET_INDEX_STATUS); return getFoundSubjects(tq.evaluate()).get(0); } private List<String> getFoundSubjects(TupleQueryResult result) throws QueryEvaluationException { List<String> foundSubjects = new LinkedList<>(); try { while (result.hasNext()) { BindingSet next = result.next(); Binding s = next.getBinding("s"); Binding g = next.getBinding("g"); if (g != null) { foundSubjects.add(asNTripleString(s.getValue()) + "; " + asNTripleString(g.getValue())); } else { foundSubjects.add(asNTripleString(s.getValue())); } } } finally { result.close(); } return foundSubjects; } private String asNTripleString(Value r) { if (r instanceof Triple) { return NTriplesUtil.toNTriplesString(r); } return r.stringValue(); } void executeQueryAndVerifyResults(String pluginQuery, int expected) throws RepositoryException, MalformedQueryException, QueryEvaluationException { String sparqlQuery = AUTOCOMPLETE_QUERY_START + pluginQuery + "\" . } }"; TupleQuery tq = connection.prepareTupleQuery(QueryLanguage.SPARQL, sparqlQuery); List<String> foundSubjects = getFoundSubjects(tq.evaluate()); assertEquals(expected, foundSubjects.size()); } List<String> executeQueryAndGetResults(String pluginQuery) throws RepositoryException, MalformedQueryException, QueryEvaluationException { String sparqlQuery = AUTOCOMPLETE_QUERY_START + pluginQuery + "\" . } }"; TupleQuery tq = connection.prepareTupleQuery(QueryLanguage.SPARQL, sparqlQuery); return getFoundSubjects(tq.evaluate()); } void importData(String fileName, RDFFormat format) throws RepositoryException, IOException, RDFParseException { connection.begin(); connection.add(new File(fileName), "urn:base", format); connection.commit(); } void addLanguageConfig(IRI labelPredicate, String languages) { connection.begin(); if (useAskControl) { connection.prepareBooleanQuery(String.format(ADD_LABEL_CONFIG_ASK, labelPredicate.stringValue(), languages)).evaluate(); } else { connection.prepareUpdate(String.format(ADD_LABEL_CONFIG_INSERT, labelPredicate.stringValue(), languages)).execute(); } connection.commit(); } void removeLanguageConfig(IRI labelPredicate) { connection.begin(); if (useAskControl) { connection.prepareBooleanQuery(String.format(REMOVE_LABEL_CONFIG_ASK, labelPredicate.stringValue())).evaluate(); } else { connection.prepareUpdate(String.format(REMOVE_LABEL_CONFIG_INSERT, labelPredicate.stringValue())).execute(); } connection.commit(); } Map<IRI, String> listLanguageConfigs() { Map<IRI, String> result = new HashMap<>(); TupleQuery tupleQuery = connection.prepareTupleQuery("select ?iri ?language { ?iri <http://www.ontotext.com/plugins/autocomplete#labelConfig> ?language }"); try (TupleQueryResult tqr = tupleQuery.evaluate()) { while (tqr.hasNext()) { BindingSet bs = tqr.next(); result.put((IRI) bs.getBinding("iri").getValue(), bs.getBinding("language").getValue().stringValue()); } } return result; } void restartRepository() { connection.close(); getRepository().shutDown(); getRepository().init(); connection = getRepository().getConnection(); } protected void waitForRankStatus(String status) { int counter = 20; String currentStatus = ""; while (counter-- > 0) { try (TupleQueryResult tqr = connection.prepareTupleQuery("SELECT ?o WHERE {_:b <http://www.ontotext.com/owlim/RDFRank#status> ?o}").evaluate()) { if (tqr.hasNext()) { currentStatus = tqr.next().getBinding("o").getValue().stringValue(); } } if (currentStatus.equals(status) || currentStatus.startsWith(status)) { break; } try { Thread.sleep(300); } catch (InterruptedException e) { e.printStackTrace(); } } assertTrue("Plugin status", currentStatus.startsWith(status)); } }
true
ff6f0a7354eaaa352bd72ad4e0126881fe3a817b
Java
anton0xf/checklist
/app/src/test/java/checklist/args/def/ArgsBlockDefTest.java
UTF-8
6,339
2.71875
3
[ "MIT" ]
permissive
package checklist.args.def; import org.junit.jupiter.api.Test; import checklist.args.ArgParseException; import checklist.args.val.ArgsBlockVal; import checklist.args.val.OptionArgVal; import checklist.args.val.PositionalArgVal; import io.vavr.Tuple; import io.vavr.Tuple2; import io.vavr.collection.List; import io.vavr.collection.Seq; import io.vavr.control.Option; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; class ArgsBlockDefTest { @Test public void parseLongOption() throws ArgParseException { ArgsBlockDef def = new ArgsBlockDef( List.of(new OptionArgDef("help")), List.empty()); Tuple2<ArgsBlockVal, Seq<String>> res = def.parse(List.of("--help", "rest")); assertThat(res._1.getOptions()).hasOnlyOneElementSatisfying( option -> assertThat(option.getName()).isEqualTo("help")); assertThat(res._2).isEqualTo(List.of("rest")); } @Test public void parseUnexpectedLongOption() { ArgsBlockDef def = new ArgsBlockDef( List.of(new OptionArgDef("help")), List.empty()); List<String> args = List.of("--other", "rest"); assertThatThrownBy(() -> def.parse(args)) .isInstanceOfSatisfying(ArgParseException.class, ex -> assertThat(ex).hasMessage("Unexpected option 'other': [--other, rest]")); } @Test public void parseShortOption() throws ArgParseException { ArgsBlockDef def = new ArgsBlockDef( List.of(new OptionArgDef("help").withShortName("h")), List.empty()); Tuple2<ArgsBlockVal, Seq<String>> res = def.parse(List.of("-h", "rest")); assertThat(res._1.getOptions()).hasOnlyOneElementSatisfying( option -> assertThat(option.getName()).isEqualTo("help")); assertThat(res._2).isEqualTo(List.of("rest")); } @Test public void parseShortOptions() throws ArgParseException { ArgsBlockDef def = new ArgsBlockDef( List.of(new OptionArgDef("verbose").withShortName("v"), new OptionArgDef("quiet").withShortName("q")), List.empty()); Tuple2<ArgsBlockVal, Seq<String>> res = def.parse(List.of("-vq", "rest")); assertThat(res._1.getOptions()).hasSize(2) .extracting(OptionArgVal::getName) .containsExactly("verbose", "quiet"); assertThat(res._2).isEqualTo(List.of("rest")); } @Test public void optionalPositionalShouldGoAtTheEnd() { assertThatThrownBy(() -> new ArgsBlockDef( List.empty(), List.of(new PositionalArgDef("o1").optional(), new PositionalArgDef("m1")))) .isInstanceOfSatisfying(IllegalArgumentException.class, ex -> assertThat(ex).hasMessage("Optional positional parameters should go at the end")); } @Test public void parsePositional() throws ArgParseException { ArgsBlockDef def = new ArgsBlockDef( List.empty(), List.of(new PositionalArgDef("name"))); Tuple2<ArgsBlockVal, Seq<String>> res = def.parse(List.of("test", "rest")); assertThat(res._1.getOptions()).isEmpty(); assertThat(res._1.getPositional()).hasOnlyOneElementSatisfying( arg -> assertThat(arg.getValue()).isEqualTo("test")); assertThat(res._2).isEqualTo(List.of("rest")); } @Test public void parseNotEnoughPositional() { ArgsBlockDef def = new ArgsBlockDef( List.of(new OptionArgDef("help").withShortName("h")), List.of(new PositionalArgDef("name"), new PositionalArgDef("other"))); assertThatThrownBy(() -> def.parse(List.of("test", "-h"))) .isInstanceOfSatisfying(ArgParseException.class, ex -> assertThat(ex).hasMessage("Expected positional parameters [other]: []")); } @Test public void parseComplex() throws ArgParseException { ArgsBlockDef def = new ArgsBlockDef( List.of(new OptionArgDef("verbose").withShortName("v"), new OptionArgDef("max-depth").withShortName("d").withParameter(), new OptionArgDef("long").withParameter(), new OptionArgDef("short").withShortName("s")), List.of(new PositionalArgDef("m1"), new PositionalArgDef("m2"), new PositionalArgDef("o1").optional(), new PositionalArgDef("o2").optional())); Tuple2<ArgsBlockVal, Seq<String>> res = def.parse(List.of("m1v", "-vd1", "m2v", "--long", "lp", "o1v", "-s")); assertThat(res._1.getOptions()).hasSize(4) .satisfies(opts -> assertThat(opts) .extracting(opt -> Tuple.of(opt.getName(), opt.getValue())) .containsExactlyElementsOf(List.of( Tuple.of("verbose", Option.none()), Tuple.of("max-depth", Option.some("1")), Tuple.of("long", Option.some("lp")), Tuple.of("short", Option.none())))); assertThat(res._1.getPositional()).hasSize(3) .extracting(PositionalArgVal::getValue) .containsExactly("m1v", "m2v", "o1v"); assertThat(res._2).isEmpty(); } @Test public void parseSeparatedPositional() throws ArgParseException { ArgsBlockDef def = new ArgsBlockDef( List.of(new OptionArgDef("verbose")), List.of(new PositionalArgDef("m1"), new PositionalArgDef("o1").optional())); Tuple2<ArgsBlockVal, Seq<String>> res = def.parse(List.of("--verbose", "m1v", "--", "--o1v", "rest")); assertThat(res._1.getOptions()).hasOnlyOneElementSatisfying( opt -> assertThat(opt.getName()).isEqualTo("verbose")); assertThat(res._1.getPositional()).hasSize(2) .extracting(PositionalArgVal::getValue) .containsExactly("m1v", "--o1v"); assertThat(res._2).isEqualTo(List.of("rest")); } }
true
0381accb0ba8e9cfea61b57a82ccfeaa6925c718
Java
caiyanzhi/easyfile
/easyfile/app/src/main/java/yanzhi/easyfile/easyfile/Network/FileUtil.java
UTF-8
3,932
2.75
3
[]
no_license
package yanzhi.easyfile.easyfile.Network; import android.annotation.TargetApi; import android.content.Context; import android.os.Build; import android.os.Environment; import android.util.Log; import java.io.File; import java.io.IOException; /** * @desc Created by yanzhi on 2016-03-06. */ public class FileUtil { /** * 判断SD卡是否存在 */ public static boolean hasSdcard() { String status = Environment.getExternalStorageState(); if (status.equals(Environment.MEDIA_MOUNTED)) { return true; } else { return false; } } @TargetApi(9) public static boolean isExternalStorageRemovable() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) { return Environment.isExternalStorageRemovable(); } return true; } @TargetApi(8) public static File getExternalCacheDir(Context context) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO && context.getExternalCacheDir() != null) { return context.getExternalCacheDir(); } // Before Froyo we need to construct the external cache dir ourselves String packagePath = Environment.getExternalStorageDirectory().getPath() + "/Android/data/" + context.getPackageName(); File packageDir = new File(packagePath); if (!tryMkdirs(packageDir)) { return null; } String cachePath = packagePath + "/cache/"; File cacheDir = new File(cachePath); if (!tryMkdirs(cacheDir)) { return null; } return cacheDir; } public static synchronized boolean tryMkdirs(File dir) { if (!(dir.exists() && dir.isDirectory())) { Log.v("mkdirs", dir.getAbsolutePath()); if (!dir.mkdirs()) { //创建不成功 return false; } } return true; } public static File getDiskFromPath(String dirPath) { File path = new File(dirPath); FileUtil.tryMkdirs(path); return path; } public static File getDiskCacheDir(Context context, String uniqueName) { // Check if media is mounted or storage is built-in, if so, try and use // external cache dir // otherwise use internal cache dir // if sdcard has no space, getExternalCacheDir(context) return null final String cachePath = ((Environment.MEDIA_MOUNTED.equals(Environment .getExternalStorageState()) || !isExternalStorageRemovable()) && getExternalCacheDir(context) != null) ? getExternalCacheDir(context).getPath() : context.getCacheDir().getPath(); File path = new File(cachePath + File.separator + uniqueName); FileUtil.tryMkdirs(path); return path; } public static void deleteDir(File dir) throws IOException { if (!dir.exists()) { return; } if (!dir.isDirectory()) { throw new IllegalArgumentException("not a directory: " + dir); } File[] files = dir.listFiles();// Returns null if this abstract pathname does not denote a directory, or if an I/O error occurs. if (files == null) { //not a dir return; } if (files!=null) { for (File file : files) { if (file.isDirectory()) { deleteDir(file); } if (!file.delete()) { throw new IOException("failed to delete file: " + file); } } } } public static File renameFile(File srcFile, File destFile) { if (srcFile == null || destFile == null) return null; try { srcFile.renameTo(destFile); } catch (Exception e) { e.printStackTrace(); } return destFile; } }
true
7bffe7aa60dbabae9cd4a7de1abcf3fafdbfcaf3
Java
muchafel/wojatzki
/interactiveStance/src/main/java/de/uni/due/ltl/interactiveStance/backend/ExperimentConfiguration.java
UTF-8
628
2.734375
3
[]
no_license
package de.uni.due.ltl.interactiveStance.backend; public class ExperimentConfiguration { private boolean simpleMode; private String scenario, mode; public ExperimentConfiguration(boolean simpleMode, String scenario, String mode) { this.simpleMode=simpleMode; this.scenario=scenario; this.mode=mode; } public boolean isSimpleMode() { return simpleMode; } public String getScenario() { return scenario; } public String getExperimentMode() { return mode; } public String valuesToString(){ return this.getScenario()+"\tMODE:\t"+this.getExperimentMode()+"\tSIMPLEMODE:\t"+this.isSimpleMode(); } }
true
a5f9b7931fbb2108bda6d05cce8163bf718d36a2
Java
calabacak/Repl.it
/src/day38_ArrayList/Triangle.java
UTF-8
198
2.109375
2
[]
no_license
package day38_ArrayList; import java.util.*; public class Triangle { static double area; int b=2; int h=3; public static void main(String[] args) { System.out.println(args.length); } }
true
7cad831d72613b81538938d76aea304587674433
Java
jay-donga/android-recyclerview-example
/app/src/main/java/com/recyclerview/Adapter_Movies.java
UTF-8
5,874
2.15625
2
[]
no_license
package com.recyclerview; import android.content.Context; import android.content.Intent; import android.support.v7.widget.CardView; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; import com.recyclerview.common.Constants; import com.recyclerview.modal.Movie_Data; import com.squareup.picasso.Picasso; import java.io.Serializable; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.List; public class Adapter_Movies extends RecyclerView.Adapter<Adapter_Movies.ViewHolder> { //private List<Movie_Data> moviesList; private List<Movie_Data> moviesList = Collections.emptyList(); private int mpage_no; private static final int TYPE_ARTICLE = 1; private static final int TYPE_LOADER = 0; Context context; public class ViewHolder extends RecyclerView.ViewHolder { public ImageView ivImage; public TextView tvTitle, tvOverview, tvDate; public ProgressBar progressBar; public CardView cardview; public ViewHolder(View view,int type) { super(view); if(type== TYPE_ARTICLE){ ivImage = view.findViewById(R.id.iv_image); tvTitle = view.findViewById(R.id.tv_title); tvOverview = view.findViewById(R.id.tv_overview); tvDate = view.findViewById(R.id.tv_date); cardview = view.findViewById(R.id.card_view); }else if(type == TYPE_LOADER){ progressBar = view.findViewById(R.id.progressBar); } } } private final LayoutInflater mInflater; public Adapter_Movies(Context context) { this.context = context; mInflater = LayoutInflater.from(context); moviesList = new ArrayList<>(); } public Adapter_Movies(List<Movie_Data> moviesList, Context context) { this.moviesList = moviesList; this.context = context; mInflater = LayoutInflater.from(context); } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View itemView; if(viewType==TYPE_ARTICLE){ // if (((MoviesList_Activity)context).is_gridview){ itemView = mInflater.inflate(R.layout.list_item_movie, parent, false); // }else{ // itemView = mInflater.inflate(R.layout.list_item_movie_list, parent, false); // } }else if(viewType==TYPE_LOADER){ itemView = mInflater.inflate(R.layout.list_item_progressbar, parent, false); }else{ itemView = mInflater.inflate(R.layout.list_item_none, parent, false); } ViewHolder viewHolder = new ViewHolder(itemView,viewType); return viewHolder; } @Override public void onBindViewHolder(ViewHolder holder, int position) { if(moviesList.get(position) == null){ holder.progressBar.setIndeterminate(true); return; }else { Movie_Data movie = moviesList.get(position); if(movie!=null) { holder.tvTitle .setText(movie.getTitle()); holder.tvOverview.setText(movie.getOverview()); DateFormat dateFormatAPI = new SimpleDateFormat("yyyy-mm-dd"); DateFormat dateFormatPrint = new SimpleDateFormat("dd-MMM-yyyy"); Date dateAPI = new Date(); String printdate = ""; try { dateAPI = dateFormatAPI.parse(movie.getReleaseDate()); printdate = dateFormatPrint.format(dateAPI); } catch (ParseException e) { e.printStackTrace(); printdate = "N/A"; } holder.tvDate.setText(printdate); String url=Constants.IMAGE_URL_PATH+moviesList.get(position).getPosterPath(); Log.e("my log","picture path : "+url); Picasso.get().load(url).placeholder(R.color.placeholder).fit().into(((ViewHolder) holder).ivImage); } } } @Override public int getItemCount() { return moviesList.size(); } public void SetPageNo(int page_no){ mpage_no=page_no; } public int GetPageNo(){ return mpage_no; } @Override public int getItemViewType(int position) { if(moviesList.get(position)!=null){ return TYPE_ARTICLE; } else{ return TYPE_LOADER; } } public void RefreshData(){ this.moviesList.clear(); } public void addNewData(List<Movie_Data> mMoviesList){ RemoveLoadmoreProgress(); for(Movie_Data data:mMoviesList){ if(!moviesList.contains(data)){ moviesList.add(data); } } notifyDataSetChanged(); } public void SetLoadmoreProgress(){ if(moviesList.get(moviesList.size() - 1) != null) { this.moviesList.add(null); } } void setMovies(List<Movie_Data> movies) { moviesList = movies; notifyDataSetChanged(); } public void RemoveLoadmoreProgress(){ try { if (moviesList != null && moviesList.size() > 0) { if (moviesList.get(moviesList.size() - 1) == null) { this.moviesList.remove(moviesList.size() - 1); } } }catch (Exception e){ e.printStackTrace(); } } }
true
2dfa97b9b17a583fb23a88e625dc2d78ad911bdf
Java
Romanasa91/backend_project
/src/main/java/twins/logic/UserLogic.java
UTF-8
7,154
2.15625
2
[]
no_license
package twins.logic; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Sort; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import twins.boundaries.UserBoundary; import twins.boundaries.id.UserId; import twins.data.UserEntity; import twins.data.UserHandler; import twins.data.UserRole; import javax.annotation.PostConstruct; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; @Service public class UserLogic implements UsersServiceExtended{ private final UserHandler userHandler; private String space; private final LogicType logicType; private final DataAccessControl dac; @Autowired public UserLogic(UserHandler userHandler, DataAccessControl dac) { super(); this.userHandler = userHandler; this.logicType = LogicType.USER; this.dac = dac; } @Value("${spring.application.name:2021b.Roman}") public void setSpace(String space){ this.space = space; } @PostConstruct public void createAdmin() { UserId id = new UserId(this.space,"admin@admin.com"); UserBoundary adminBoundary = new UserBoundary(); adminBoundary.setUserId(id); adminBoundary.setRole("ADMIN"); adminBoundary.setUsername("admin"); adminBoundary.setAvatar("ADMIN"); userHandler.save(convertToEntity(adminBoundary)); } @PostConstruct public void createManager() { UserId id = new UserId(this.space,"manager@manager.com"); UserBoundary adminBoundary = new UserBoundary(); adminBoundary.setUserId(id); adminBoundary.setRole("MANAGER"); adminBoundary.setUsername("manager"); adminBoundary.setAvatar("MANAGER"); userHandler.save(convertToEntity(adminBoundary)); } @Override @Transactional public UserBoundary createUser(UserBoundary user) { if(!isValidUser(user)) return null; user.setRole(user.getRole().toUpperCase()); user.setUserId( new UserId(this.space, user.getUserId().getEmail())); return convertToBoundary(userHandler.save(convertToEntity(user))); } @Override @Transactional(readOnly = true) public UserBoundary login(String userSpace, String userEmail) { String id = new UserId(userSpace, userEmail).convertToString(); UserEntity userEntity = userHandler.findById(id) .orElseThrow(RuntimeException::new); convertToBoundary(userEntity); return convertToBoundary(userEntity); } @Override @Transactional public UserBoundary updateUser(String userSpace, String userEmail, UserBoundary update) { String id = new UserId(userSpace, userEmail).convertToString(); UserEntity entity = userHandler.findById(id) .orElseThrow(RuntimeException::new); // user ID cannot be changed update.setUserId(convertToBoundary(entity).getUserId()); userHandler.save(convertToEntity(update)); return update; } @Override @Transactional(readOnly = true) @Deprecated public List<UserBoundary> getAllUsers(String adminSpace, String adminEmail) { throw new RuntimeException("deprecated operation"); } public List<UserBoundary> getAllUsers(String adminSpace, String adminEmail, int page, int size) throws Exception { UserRole role = findRole(adminSpace, adminEmail); boolean allowed = dac.isAllowed(role, logicType, ActionType.GET_ALL); if(!allowed){ throw new Exception("Access Denied!"); } Page<UserEntity> usersPage = userHandler .findAll(PageRequest.of(page,size, Sort.Direction.ASC,"role","username")); List<UserEntity> content = usersPage.getContent(); List<UserBoundary> rv = new ArrayList<>(); for (UserEntity entity : content) { UserBoundary boundary = this.convertToBoundary(entity); rv.add(boundary); } return rv; } @Override @Transactional public void deleteAllUsers(String adminSpace, String adminEmail) throws Exception { UserRole role = findRole(adminSpace, adminEmail); boolean allowed = dac.isAllowed(role, logicType, ActionType.DELETE_ALL); if(!allowed){ throw new Exception("Access Denied!"); } userHandler.deleteAll(); } public UserRole findRole(String userSpace, String userEmail) throws Exception { String id = new UserId(userSpace, userEmail).convertToString(); if(!userHandler.findById(id).isPresent()) { throw new Exception("No such user!"); } return userHandler.findById(id).get().getRole(); } private UserEntity convertToEntity(UserBoundary boundary) { UserEntity rv = new UserEntity(); rv.setUserId(boundary.getUserId().convertToString()); rv.setRole(UserRole.valueOf(boundary.getRole().toUpperCase())); rv.setUsername(boundary.getUsername()); rv.setAvatar(boundary.getAvatar()); return rv; } private UserBoundary convertToBoundary(UserEntity entity) { UserBoundary rv = new UserBoundary(); rv.setUserId(covertToUserId(entity.getUserId())); rv.setRole(entity.getRole().toString()); rv.setUsername(entity.getUsername()); rv.setAvatar(entity.getAvatar()); return rv; } private UserId covertToUserId(String id){ String[] s = id.split(UserId.ID_SEPARATOR); if (s.length == 2) { String space = s[0]; String email = s[1]; return new UserId(space,email); } return null; } private boolean isValidEmail(String email) { Pattern p = Pattern.compile( "^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,6}$", Pattern.CASE_INSENSITIVE); Matcher matcher = p.matcher(email); return matcher.find(); } private boolean isValidRole(String role) { for (UserRole r: UserRole.values()) { if(r.toString().equals(role.toUpperCase())) return true; } return false; } private boolean isValidUser(UserBoundary user) { boolean rv = true; if(!isValidEmail(user.getUserId().getEmail())) { System.err.println("Email is not valid"); rv = false; } if(!isValidRole(user.getRole())){ System.err.println("Role is not valid"); rv = false; } if(user.getUsername() == null) { System.err.println("Name is not valid"); rv = false; } if(user.getAvatar() == null || user.getAvatar().equals("")) { System.err.println("Avatar is not valid"); rv = false; } return rv; } }
true
88e261c5dc610dfaee07693c5d04486f56140416
Java
coder-hx/AlgorithmTraining
/src/com/hxcoder/complete/medium/fiveHundredEighteen/Solution.java
UTF-8
579
3.25
3
[]
no_license
package com.hxcoder.complete.medium.fiveHundredEighteen; /** * 518. 零钱兑换 II * 要求: * 给定不同面额的硬币和一个总金额,计算可以凑成总金额的硬币组合数 * 假设每一种面额的硬币有无限个 * <p> * 提示: * 0 <= amount (总金额) <= 5000 * 1 <= coin (硬币面额)<= 5000 * 硬币种类不超过 500 种 * 结果符合 32 位符号整数 * * @author hxcoder */ public class Solution { public static void main(String[] args) { } public int change(int amount, int[] coins) { return 0; } }
true
c6181ab5f91f27a12cf4518308078614dcfe6c90
Java
Jan111111/RE2011
/src/main/java/raf/Note.java
UTF-8
1,159
3.46875
3
[]
no_license
package raf; import java.io.FileNotFoundException; import java.io.IOException; import java.io.RandomAccessFile; import java.io.UnsupportedEncodingException; import java.util.Scanner; /* 完成简易记事本工具 程序启动后要求用户输入一个文件夹,然后对该文件进行写操作 之后用户在控制台输入的每一行为内容都要写入到文件中. 当用户单独输入“exit”时程序退出. 注:写入文件中的数据不需要考虑换行问题 */ public class Note { public static void main(String[] args) throws IOException { Scanner scan=new Scanner(System.in); System.out.println("请输入一个文件夹"); String str=scan.nextLine(); RandomAccessFile raf=new RandomAccessFile(str,"rw"); System.out.println("请输入内容"); for(;;){ String str1=scan.nextLine(); if (str1.equals("exit")) { System.out.println("已退出"); break; } byte[] date = str1.getBytes("UTF-8"); raf.write(date); } System.out.println("写出完毕"); raf.close(); } }
true
2517ad422173a0416468bf47e604686ccd4bac17
Java
Vyrm/chat
/src/main/java/com/devcolibri/handler/MessageHandler.java
UTF-8
381
2.234375
2
[]
no_license
package com.devcolibri.handler; import java.util.concurrent.ConcurrentLinkedDeque; public class MessageHandler { private ConcurrentLinkedDeque<String> concurrentLinkedDeque; public MessageHandler() { concurrentLinkedDeque = new ConcurrentLinkedDeque<>(); } public ConcurrentLinkedDeque<String> getQueue() { return concurrentLinkedDeque; } }
true
98948783b557d9310dd2a852bec158e2763ee27a
Java
duythu3606/lab3
/src/oop/bai9/CNList.java
UTF-8
1,397
3
3
[]
no_license
package oop; public class CNList { private int n=3; private Congnhan cnlist[]; private int count =0; public CNList(){cnlist = new Congnhan[n];} public void add(Congnhan cn){ if (check_full()) { cnlist[count] = cn; count++; } } private boolean check_full(){ if( count>n) return false; return true; } public void getall(){ for (int i = 0 ; i< n;i++) { System.out.println(cnlist[i]); } } public void SoCN(){ int dem =0; for (int i =0 ; i< cnlist.length;i++) { if (cnlist[i]==null) { dem=dem; } else dem++; } System.out.println("Số công nhân là : " + count); } public void CN200(){ for (int i =0 ; i<cnlist.length ; i++){ if (cnlist[i].getmSP() > 200){ System.out.println(cnlist[i]); } } } public void giamdan(){ Congnhan temp =null; for (int i =0; i < cnlist.length-1;i++){ for (int j =i+1;j < cnlist.length;j++){ if (cnlist[i].getmSP() < cnlist[j].getmSP()) { temp = cnlist[i]; cnlist[i] = cnlist[j]; cnlist[j] = temp; } } } } }
true
badc1348287165a1aaa1e68112b678cefc2d1cef
Java
GuDongyeong/Server_Basic
/ServletEx/src/hello/HelloServlet.java
UTF-8
860
2.71875
3
[]
no_license
package hello; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/Hello") public class HelloServlet extends HttpServlet { private static final long serialVersionUID = 1L; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("/Hello 접속 완료"); // 응답 데이터 형식 지정 resp.setContentType("text/html;charset=utf-8"); // 응답 출력 스트림 PrintWriter out = resp.getWriter(); //응답 내용 출력(HTML 형식) out.append("<h1>하이하이<h1>") .append("<h3>헤헤<h3>"); } }
true
5bb533e6f1527a3d4eec0537fe242f68878308e8
Java
akaiserg/tdd_calc_spring_boot
/src/main/java/com/project/calc/rest/Response.java
UTF-8
333
2.265625
2
[]
no_license
package com.project.calc.rest; public class Response { private final long id; private final double result; public Response(long id, double result){ this.id=id; this.result=result; } public long getId() { return id; } public double getResult() { return result; } }
true
56ab84cf419eee2bc4ff5c7ddf2ad31361672b6a
Java
EsfingeFramework/gamification
/Gamification/src/test/java/net/sf/esfinge/gamification/auth/GuardedTrophyImpl.java
UTF-8
630
2.5
2
[ "MIT" ]
permissive
package net.sf.esfinge.gamification.auth; import net.sf.esfinge.gamification.annotation.auth.trophy.AllowTrophy; import net.sf.esfinge.gamification.annotation.auth.trophy.DenyTrophy; public class GuardedTrophyImpl implements Guarded { @AllowTrophy(achievementName = "silver") public void changeProfilePhoto() { System.out.println("profile photo changed"); } @DenyTrophy(achievementName = "gold") public void takePhoto() { System.out.println("photo taked"); } public void recordVideo() { System.out.println("video recorded"); } public void receivePhoto() { System.out.println("photo received"); } }
true
baf3f0eda993883c4701d81dc53bc4e8adf33cfd
Java
P79N6A/icse_20_user_study
/methods/Method_17826.java
UTF-8
178
2
2
[]
no_license
protected void bindDynamicProp(int dynamicPropIndex,Object value,Object content){ throw new RuntimeException("Components that have dynamic Props must override this method"); }
true
f29d298f8a0ba82715df8b43570dda43ee0d0868
Java
boox30/www
/android/kreader/libraries/onyxsdk-scribble/src/main/java/com/onyx/android/sdk/scribble/data/ShapeDataProvider.java
UTF-8
5,269
2.140625
2
[]
no_license
package com.onyx.android.sdk.scribble.data; import android.content.Context; import com.onyx.android.sdk.scribble.shape.Shape; import com.onyx.android.sdk.utils.StringUtils; import com.raizlabs.android.dbflow.annotation.Database; import com.raizlabs.android.dbflow.config.DatabaseConfig; import com.raizlabs.android.dbflow.config.DatabaseDefinition; import com.raizlabs.android.dbflow.config.FlowManager; import com.raizlabs.android.dbflow.sql.language.Delete; import com.raizlabs.android.dbflow.sql.language.Select; import com.raizlabs.android.dbflow.sql.language.Where; import com.raizlabs.android.dbflow.structure.database.DatabaseWrapper; import com.raizlabs.android.dbflow.structure.database.transaction.*; import java.util.*; /** * Created by zhuzeng on 9/16/15. * CRUD for shape data. */ public class ShapeDataProvider { public static abstract class DataProviderCallback { public abstract void finished(); } public static List<ShapeModel> loadShapeList(final Context context, final String documentUniqueId, final String pageUniqueId, final String subPageName) { Select select = new Select(); Where where = select.from(ShapeModel.class).where(ShapeModel_Table.documentUniqueId.eq(documentUniqueId)).and(ShapeModel_Table.pageUniqueId.eq(pageUniqueId)); if (StringUtils.isNotBlank(subPageName)) { where = where.and(ShapeModel_Table.subPageName.eq(subPageName)); } List<ShapeModel> list = where.queryList(); return list; } public static void saveShapeList(final Context context, final Collection<ShapeModel> list) { final DatabaseWrapper database= FlowManager.getDatabase(ShapeDatabase.NAME).getWritableDatabase(); database.beginTransaction(); for(ShapeModel shapeModel : list) { shapeModel.save(); } database.setTransactionSuccessful(); database.endTransaction(); } public static void svaeShapeListInBackground(final Context context, final Collection<ShapeModel> list, final DataProviderCallback callback) { final DatabaseDefinition database= FlowManager.getDatabase(ShapeDatabase.NAME); ProcessModelTransaction<ShapeModel> processModelTransaction = new ProcessModelTransaction.Builder<>(new ProcessModelTransaction.ProcessModel<ShapeModel>() { @Override public void processModel(ShapeModel model) { model.save(); } }).processListener(new ProcessModelTransaction.OnModelProcessListener<ShapeModel>() { @Override public void onModelProcessed(long current, long total, ShapeModel modifiedModel) { if (callback != null && current >= total - 1) { callback.finished(); } } }).addAll(list).build(); Transaction transaction = database.beginTransactionAsync(processModelTransaction).build(); transaction.execute(); } public static void removeAllShapeOfDocument(final Context context, final String documentUniqueId) { Delete delete = new Delete(); delete.from(ShapeModel.class).where(ShapeModel_Table.documentUniqueId.eq(documentUniqueId)).query(); } public static boolean removeShape(final Context context, final String uniqueId) { Delete delete = new Delete(); delete.from(ShapeModel.class).where(ShapeModel_Table.shapeUniqueId.eq(uniqueId)).query(); return true; } public static boolean removeShapesByIdList(final Context context, final List<String> list) { Delete delete = new Delete(); delete.from(ShapeModel.class).where(ShapeModel_Table.shapeUniqueId.in(list)).query(); return true; } public static void removeShapesByIdListInBackground(final Context context, final List<String> list, final DataProviderCallback callback) { final DatabaseDefinition database= FlowManager.getDatabase(ShapeDatabase.NAME); Transaction transaction = database.beginTransactionAsync(new ITransaction() { @Override public void execute(DatabaseWrapper databaseWrapper) { Delete delete = new Delete(); delete.from(ShapeModel.class).where(ShapeModel_Table.shapeUniqueId.in(list)).query(); if (callback != null) { callback.finished(); } } }).build(); transaction.execute(); } public static boolean removePage(final Context context, final String pageUniqueId) { Delete delete = new Delete(); delete.from(ShapeModel.class).where(ShapeModel_Table.pageUniqueId.eq(pageUniqueId)).query(); return true; } }
true
a86346efe51f97264b9222113b011ce8b5d13d39
Java
Blueazchevelle/Java-Web-Application
/src/main/java/org/kekelidos/weather/application/WeatherApplication/model/StationPath.java
UTF-8
1,830
2.515625
3
[]
no_license
package org.kekelidos.weather.application.WeatherApplication.model; /** * * @author kekeli D Akouete * * Description: * A station is a any weather observing platform where data is recorded. */ public class StationPath extends PathModel{ protected String datacategoryid; protected String datatypeid; protected String locationid; protected String extent; public StationPath() { super(); } public String getDatacategoryid() { return datacategoryid; } public void setDatacategoryid(String datacategoryid) { this.datacategoryid = datacategoryid.toUpperCase(); } public String getDatatypeid() { return datatypeid; } public void setDatatypeid(String datatypeid) { this.datatypeid = datatypeid.toUpperCase(); } public String getLocationid() { return locationid; } public void setLocationid(String locationid) { this.locationid = locationid.toUpperCase(); } public String getExtent() { return extent; } public void setExtent(String extent) { this.extent = extent; } @Override public String toString() { return "Stations = {datasetid: " + datasetid + ", " + "locationid: " + locationid + ", " + "datacategoryid: " + datacategoryid + ", " + "datatypeid: " + datatypeid + ", " + "extent: " + extent + ", " + "startdate: " + startdate + ", " + "enddate: " + enddate + ", " + "sortfield: " + sortfield + ", " + "sortorder: " + sortorder + ", " + "limit: " + limit + ", " + "offset: " + offset +"}"; } @Override public String toQueryString() { return "?datasetid=" + datasetid + "&locationid=" + locationid + "&datacategoryid=" + datacategoryid + "&datatypeid=" + datatypeid + "&extent=" + extent + "&startdate=" + startdate + "&enddate=" + enddate + "&sortfield=" + sortfield + "&sortorder=" + sortorder + "&limit=" + limit + "&offset=" + offset; } }
true
4792d4dffd4203208e1730a1fb80e471a1eabb81
Java
PaulieKlein/Module_javaEE
/BankonetWeb/src/com/bankonet/servlet/DateServlet.java
UTF-8
1,921
2.296875
2
[]
no_license
package com.bankonet.servlet; import java.io.IOException; import java.util.Date; import java.text.SimpleDateFormat; import javax.servlet.RequestDispatcher; import javax.servlet.ServletConfig; import javax.servlet.ServletException; //import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class DateServlet */ public class DateServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public DateServlet() { super(); // TODO Auto-generated constructor stub } public void init(ServletConfig servconfig) throws ServletException { System.out.println("initialisation de DateServlet"); super.init(servconfig); } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub System.out.println("Bienvenue sur Bankonet") ; SimpleDateFormat sdf = new SimpleDateFormat("dd MMMM yyyy"); System.out.println(sdf.format(new Date())) ; RequestDispatcher disp = this.getServletContext().getRequestDispatcher("/login.jsp"); disp.forward(request, response); //response.sendRedirect(request.getContextPath()+"/login.jsp"); } @Override public void destroy() { // TODO Auto-generated method stub super.destroy(); System.out.println("suppression de DateServlet"); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub } }
true
6996707283c0cd21a3367cbaa00414b23dce1f41
Java
Elena-Bruyako/BrunyatkoFriends
/data/src/main/java/com/bruyako/repository/MessageRepository.java
UTF-8
1,440
2.578125
3
[]
no_license
package com.bruyako.repository; import com.bruyako.entity.Message; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import java.util.*; /** * Created by brunyatko on 21.09.15. */ @Repository public class MessageRepository implements BaseRepository <Message, Long> { @Autowired public SessionFactory sessionFactory; @Override public void create(Message message) { getSession().save(message); } @Override public void delete(Long id) { Query query = getSession().createQuery("delete from Message m where m.Message_id = :id"); query.setParameter("id", id); query.executeUpdate(); } @Override public void update(Message message) { getSession().saveOrUpdate(message); } @Override public Message getById(Long id) { Message message = (Message) getSession() .createQuery("select m.Message_id from Message m where m.Message_id = :id") .setParameter("id", id); return message; } @Override public List<Message> getAll() { List<Message> messages = getSession().createQuery("from Message").list(); return messages; } private Session getSession() { return sessionFactory.getCurrentSession(); } }
true
68e115a4e40945ef489e05f5f6ef03f1a25d1ad1
Java
kashish17/MineSweeper
/app/src/main/java/com/example/kashish/minesweeper/MButton.java
UTF-8
461
2.1875
2
[]
no_license
package com.example.kashish.minesweeper; import android.content.Context; import android.support.v7.widget.AppCompatButton; import android.widget.Button; public class MButton extends AppCompatButton { MButton(Context context){ super(context); } int i,j; boolean lc=false; boolean shown = false; private int value; public void set(int i){ value=i; } public int getVal(){ return value; } }
true
22fb1997ac8016e7b9ff800cd86376780a308b4d
Java
aman-rastogi/70-Days-Coding-Challenge
/Day 2/CONFLIP.java
UTF-8
2,373
3.25
3
[]
no_license
package codechef.easy; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; public class CONFLIP { public static void main(String[] args) { FastReader fr = new FastReader(); int T = fr.nextInt(); for(int k=0;k<T;k++) { int G = fr.nextInt(); for(int g=0;g<G;g++) { String[] s = fr.nextLine().split(" "); int[] numbers = Arrays.stream(s).mapToInt(Integer::parseInt).toArray(); int [] a = new int[numbers[1]]; if(numbers[0]==1)// All Head Arrays.fill(a, 1); else if(numbers[0]==2)// All tail Arrays.fill(a, 0); System.out.println("Input\t"+Arrays.toString(a)); for(int i=0;i<a.length;i++) { for(int j=0;j<=i;j++) { if(a[j]==0) a[j]=1; else if(a[j]==1) a[j]=0; } } System.out.println("Output\t"+Arrays.toString(a)); } } } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { String s1 = br.readLine(); if(null==s1){ System.exit(0); } st = new StringTokenizer(s1); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
true
3ab8ad08c0e392ea5e20d1ec1f94a629892f7412
Java
subhasis-sys/subhasiscentralizedrepository
/x/src/test/java/test/x/Thissuperconstructorprogram.java
UTF-8
721
3.265625
3
[]
no_license
package test.x; public class Thissuperconstructorprogram { public Thissuperconstructorprogram() { this(1,2); System.out.println("default parent constructor"); } public Thissuperconstructorprogram(int a) { this(1,2,3); System.out.println("1 parametrized parent constructor"); } public Thissuperconstructorprogram(int a, int b) { System.out.println("2 parameterized parent construcor"); } public Thissuperconstructorprogram(int a, int b, int c) { this(1,2,3,4); System.out.println("3 parameterized parent constuctor"); } public Thissuperconstructorprogram(int a, int b, int c, int d) { this(); System.out.println("4 parameterized constructor"); } }
true
084b5995e1499818a30669153d7388d7a9e00800
Java
eric-lanita/BigRoadTruckingLogbookApp_v21.0.12_source_from_JADX
/android/support/constraint/solver/C0033a.java
UTF-8
16,595
1.804688
2
[]
no_license
package android.support.constraint.solver; import android.support.constraint.solver.SolverVariable.Type; import com.google.android.gms.maps.model.GroundOverlayOptions; import java.util.Arrays; public class C0033a { int f244a = 0; private final C0035b f245b; private final C0036c f246c; private int f247d = 8; private SolverVariable f248e = null; private int[] f249f = new int[this.f247d]; private int[] f250g = new int[this.f247d]; private float[] f251h = new float[this.f247d]; private int f252i = -1; private int f253j = -1; private boolean f254k = false; C0033a(C0035b c0035b, C0036c c0036c) { this.f245b = c0035b; this.f246c = c0036c; } public final void m133a(SolverVariable solverVariable, float f) { if (f == 0.0f) { m127a(solverVariable); } else if (this.f252i == -1) { this.f252i = 0; this.f251h[this.f252i] = f; this.f249f[this.f252i] = solverVariable.f234a; this.f250g[this.f252i] = -1; solverVariable.f242i++; this.f244a++; if (!this.f254k) { this.f253j++; if (this.f253j >= this.f249f.length) { this.f254k = true; this.f253j = this.f249f.length - 1; } } } else { int i = this.f252i; int i2 = 0; int i3 = -1; while (i != -1 && i2 < this.f244a) { if (this.f249f[i] == solverVariable.f234a) { this.f251h[i] = f; return; } if (this.f249f[i] < solverVariable.f234a) { i3 = i; } i2++; i = this.f250g[i]; } i = this.f253j + 1; if (this.f254k) { if (this.f249f[this.f253j] == -1) { i = this.f253j; } else { i = this.f249f.length; } } if (i >= this.f249f.length && this.f244a < this.f249f.length) { for (i2 = 0; i2 < this.f249f.length; i2++) { if (this.f249f[i2] == -1) { i = i2; break; } } } if (i >= this.f249f.length) { i = this.f249f.length; this.f247d *= 2; this.f254k = false; this.f253j = i - 1; this.f251h = Arrays.copyOf(this.f251h, this.f247d); this.f249f = Arrays.copyOf(this.f249f, this.f247d); this.f250g = Arrays.copyOf(this.f250g, this.f247d); } this.f249f[i] = solverVariable.f234a; this.f251h[i] = f; if (i3 != -1) { this.f250g[i] = this.f250g[i3]; this.f250g[i3] = i; } else { this.f250g[i] = this.f252i; this.f252i = i; } solverVariable.f242i++; this.f244a++; if (!this.f254k) { this.f253j++; } if (this.f244a >= this.f249f.length) { this.f254k = true; } if (this.f253j >= this.f249f.length) { this.f254k = true; this.f253j = this.f249f.length - 1; } } } public final void m139b(SolverVariable solverVariable, float f) { if (f != 0.0f) { if (this.f252i == -1) { this.f252i = 0; this.f251h[this.f252i] = f; this.f249f[this.f252i] = solverVariable.f234a; this.f250g[this.f252i] = -1; solverVariable.f242i++; this.f244a++; if (!this.f254k) { this.f253j++; if (this.f253j >= this.f249f.length) { this.f254k = true; this.f253j = this.f249f.length - 1; return; } return; } return; } int i = this.f252i; int i2 = 0; int i3 = -1; while (i != -1 && i2 < this.f244a) { int i4 = this.f249f[i]; if (i4 == solverVariable.f234a) { float[] fArr = this.f251h; fArr[i] = fArr[i] + f; if (this.f251h[i] == 0.0f) { if (i == this.f252i) { this.f252i = this.f250g[i]; } else { this.f250g[i3] = this.f250g[i]; } this.f246c.f262c[i4].m125b(this.f245b); if (this.f254k) { this.f253j = i; } solverVariable.f242i--; this.f244a--; return; } return; } if (this.f249f[i] < solverVariable.f234a) { i3 = i; } i2++; i = this.f250g[i]; } i = this.f253j + 1; if (this.f254k) { if (this.f249f[this.f253j] == -1) { i = this.f253j; } else { i = this.f249f.length; } } if (i >= this.f249f.length && this.f244a < this.f249f.length) { for (i2 = 0; i2 < this.f249f.length; i2++) { if (this.f249f[i2] == -1) { i = i2; break; } } } if (i >= this.f249f.length) { i = this.f249f.length; this.f247d *= 2; this.f254k = false; this.f253j = i - 1; this.f251h = Arrays.copyOf(this.f251h, this.f247d); this.f249f = Arrays.copyOf(this.f249f, this.f247d); this.f250g = Arrays.copyOf(this.f250g, this.f247d); } this.f249f[i] = solverVariable.f234a; this.f251h[i] = f; if (i3 != -1) { this.f250g[i] = this.f250g[i3]; this.f250g[i3] = i; } else { this.f250g[i] = this.f252i; this.f252i = i; } solverVariable.f242i++; this.f244a++; if (!this.f254k) { this.f253j++; } if (this.f253j >= this.f249f.length) { this.f254k = true; this.f253j = this.f249f.length - 1; } } } public final float m127a(SolverVariable solverVariable) { if (this.f248e == solverVariable) { this.f248e = null; } if (this.f252i == -1) { return 0.0f; } int i = this.f252i; int i2 = 0; int i3 = -1; while (i != -1 && i2 < this.f244a) { int i4 = this.f249f[i]; if (i4 == solverVariable.f234a) { if (i == this.f252i) { this.f252i = this.f250g[i]; } else { this.f250g[i3] = this.f250g[i]; } this.f246c.f262c[i4].m125b(this.f245b); solverVariable.f242i--; this.f244a--; this.f249f[i] = -1; if (this.f254k) { this.f253j = i; } return this.f251h[i]; } i2++; int i5 = i; i = this.f250g[i]; i3 = i5; } return 0.0f; } public final void m131a() { this.f252i = -1; this.f253j = -1; this.f254k = false; this.f244a = 0; } final boolean m140b(SolverVariable solverVariable) { if (this.f252i == -1) { return false; } int i = this.f252i; int i2 = 0; while (i != -1 && i2 < this.f244a) { if (this.f249f[i] == solverVariable.f234a) { return true; } i = this.f250g[i]; i2++; } return false; } void m138b() { int i = this.f252i; int i2 = 0; while (i != -1 && i2 < this.f244a) { float[] fArr = this.f251h; fArr[i] = fArr[i] * GroundOverlayOptions.NO_DIMENSION; i = this.f250g[i]; i2++; } } void m132a(float f) { int i = this.f252i; int i2 = 0; while (i != -1 && i2 < this.f244a) { float[] fArr = this.f251h; fArr[i] = fArr[i] / f; i = this.f250g[i]; i2++; } } void m134a(C0035b c0035b) { int i = this.f252i; int i2 = 0; while (i != -1 && i2 < this.f244a) { this.f246c.f262c[this.f249f[i]].m123a(c0035b); i = this.f250g[i]; i2++; } } private boolean m126a(SolverVariable solverVariable, C0038e c0038e) { return solverVariable.f242i <= 1; } SolverVariable m129a(C0038e c0038e) { SolverVariable solverVariable = null; boolean z = false; int i = 0; int i2 = this.f252i; float f = 0.0f; float f2 = 0.0f; SolverVariable solverVariable2 = null; boolean z2 = false; while (i2 != -1 && i < this.f244a) { SolverVariable solverVariable3; float f3 = this.f251h[i2]; if (f3 < 0.0f) { if (f3 > (-981668463)) { this.f251h[i2] = 0.0f; f3 = 0.0f; } } else if (f3 < 0.001f) { this.f251h[i2] = 0.0f; f3 = 0.0f; } SolverVariable solverVariable4 = this.f246c.f262c[this.f249f[i2]]; if (solverVariable4.f239f != Type.UNRESTRICTED) { if (solverVariable == null && f3 < 0.0f) { if (solverVariable2 == null) { z = m126a(solverVariable4, c0038e); f = f3; f3 = f2; solverVariable3 = solverVariable; } else if (f > f3) { z = m126a(solverVariable4, c0038e); f = f3; f3 = f2; solverVariable3 = solverVariable; } else if (!z && m126a(solverVariable4, c0038e)) { z = true; f = f3; f3 = f2; solverVariable3 = solverVariable; } } f3 = f2; solverVariable4 = solverVariable2; solverVariable3 = solverVariable; } else if (solverVariable == null) { z2 = m126a(solverVariable4, c0038e); solverVariable3 = solverVariable4; solverVariable4 = solverVariable2; } else if (f2 > f3) { z2 = m126a(solverVariable4, c0038e); solverVariable3 = solverVariable4; solverVariable4 = solverVariable2; } else { if (!z2 && m126a(solverVariable4, c0038e)) { z2 = true; solverVariable3 = solverVariable4; solverVariable4 = solverVariable2; } f3 = f2; solverVariable4 = solverVariable2; solverVariable3 = solverVariable; } i++; i2 = this.f250g[i2]; solverVariable = solverVariable3; solverVariable2 = solverVariable4; f2 = f3; } return solverVariable != null ? solverVariable : solverVariable2; } void m135a(C0035b c0035b, C0035b c0035b2) { int i = this.f252i; int i2 = 0; while (i != -1 && i2 < this.f244a) { if (this.f249f[i] == c0035b2.f255a.f234a) { float f = this.f251h[i]; m127a(c0035b2.f255a); C0033a c0033a = c0035b2.f258d; i = c0033a.f252i; i2 = 0; while (i != -1 && i2 < c0033a.f244a) { m139b(this.f246c.f262c[c0033a.f249f[i]], c0033a.f251h[i] * f); i = c0033a.f250g[i]; i2++; } c0035b.f256b += c0035b2.f256b * f; c0035b2.f255a.m125b(c0035b); i = this.f252i; i2 = 0; } else { i = this.f250g[i]; i2++; } } } void m136a(C0035b c0035b, C0035b[] c0035bArr) { int i = this.f252i; int i2 = 0; while (i != -1 && i2 < this.f244a) { SolverVariable solverVariable = this.f246c.f262c[this.f249f[i]]; if (solverVariable.f235b != -1) { float f = this.f251h[i]; m127a(solverVariable); C0035b c0035b2 = c0035bArr[solverVariable.f235b]; if (!c0035b2.f259e) { C0033a c0033a = c0035b2.f258d; i = c0033a.f252i; i2 = 0; while (i != -1 && i2 < c0033a.f244a) { m139b(this.f246c.f262c[c0033a.f249f[i]], c0033a.f251h[i] * f); i = c0033a.f250g[i]; i2++; } } c0035b.f256b += c0035b2.f256b * f; c0035b2.f255a.m125b(c0035b); i = this.f252i; i2 = 0; } else { i = this.f250g[i]; i2++; } } } SolverVariable m130a(boolean[] zArr, SolverVariable solverVariable) { SolverVariable solverVariable2 = null; int i = 0; int i2 = this.f252i; float f = 0.0f; while (i2 != -1 && i < this.f244a) { SolverVariable solverVariable3; if (this.f251h[i2] < 0.0f) { SolverVariable solverVariable4 = this.f246c.f262c[this.f249f[i2]]; if ((zArr == null || !zArr[solverVariable4.f234a]) && solverVariable4 != solverVariable && (solverVariable4.f239f == Type.SLACK || solverVariable4.f239f == Type.ERROR)) { float f2 = this.f251h[i2]; if (f2 < f) { f = f2; solverVariable3 = solverVariable4; i++; i2 = this.f250g[i2]; solverVariable2 = solverVariable3; } } } solverVariable3 = solverVariable2; i++; i2 = this.f250g[i2]; solverVariable2 = solverVariable3; } return solverVariable2; } final SolverVariable m128a(int i) { int i2 = this.f252i; int i3 = 0; while (i2 != -1 && i3 < this.f244a) { if (i3 == i) { return this.f246c.f262c[this.f249f[i2]]; } i2 = this.f250g[i2]; i3++; } return null; } final float m137b(int i) { int i2 = this.f252i; int i3 = 0; while (i2 != -1 && i3 < this.f244a) { if (i3 == i) { return this.f251h[i2]; } i2 = this.f250g[i2]; i3++; } return 0.0f; } public final float m141c(SolverVariable solverVariable) { int i = this.f252i; int i2 = 0; while (i != -1 && i2 < this.f244a) { if (this.f249f[i] == solverVariable.f234a) { return this.f251h[i]; } i = this.f250g[i]; i2++; } return 0.0f; } public String toString() { String str = ""; int i = this.f252i; int i2 = 0; while (i != -1 && i2 < this.f244a) { str = ((str + " -> ") + this.f251h[i] + " : ") + this.f246c.f262c[this.f249f[i]]; i = this.f250g[i]; i2++; } return str; } }
true
23d697619610ac905b1aee7ccd3dfef00fd78425
Java
minfaatong/RaspberryPI
/bundles/org.eclipse.ecf.raspberrypi.gpio.pi4j/src/org/eclipse/ecf/raspberrypi/gpio/pi4j/InputListenerTrackerCustomizer.java
UTF-8
4,590
1.804688
2
[]
no_license
/******************************************************************************* * Copyright (c) 2014 Composent, Inc. All rights reserved. This * program and the accompanying materials are made available under the terms of * the Eclipse Public License v1.0 which accompanies this distribution, and is * available at http://www.eclipse.org/legal/epl-v10.html * * Contributors: Scott Lewis - initial API and implementation ******************************************************************************/ package org.eclipse.ecf.raspberrypi.gpio.pi4j; import java.util.HashMap; import java.util.Map; import org.eclipse.ecf.internal.raspberrypi.gpio.pi4j.Activator; import org.eclipse.ecf.raspberrypi.gpio.IGPIOPin; import org.eclipse.ecf.raspberrypi.gpio.IGPIOPinInputListener; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceReference; import org.osgi.util.tracker.ServiceTrackerCustomizer; import com.pi4j.io.gpio.GpioPinDigitalInput; import com.pi4j.io.gpio.Pin; import com.pi4j.io.gpio.PinPullResistance; public class InputListenerTrackerCustomizer implements ServiceTrackerCustomizer<IGPIOPinInputListener, IGPIOPinInputListener> { private BundleContext context; private Map<ServiceReference<IGPIOPinInputListener>, ListenerHolder> refToListenerMap = new HashMap<ServiceReference<IGPIOPinInputListener>, ListenerHolder>(); public InputListenerTrackerCustomizer(BundleContext context) { this.context = context; } class ListenerHolder { final GpioPinDigitalInput inputListener; Pi4jGPIOPinInputListener listener; public ListenerHolder(GpioPinDigitalInput inputListener) { this.inputListener = inputListener; setListener(listener); } public void setListener(Pi4jGPIOPinInputListener listener) { this.listener = listener; } } @Override public IGPIOPinInputListener addingService( ServiceReference<IGPIOPinInputListener> reference) { // get service IGPIOPinInputListener gPIOInputListener = context.getService(reference); if (gPIOInputListener == null) return null; // Get pinId Integer pinId = IGPIOPin.Util.getPinId(reference); if (pinId == null) pinId = new Integer(IGPIOPin.DEFAULT_INPUT_PIN); Pin pin = Pi4jGPIOPin.getPinForId(pinId.intValue()); if (pin != null) { // Get pinName String pinName = IGPIOPin.Util.getPinName(reference); if (pinName == null) pinName = String.valueOf(pinId); // Get pullresistance Integer pullResistance = IGPIOPin.Util .getInputPullResistance(reference); // If it's not set, set to PUL if (pullResistance == null) pullResistance = new Integer( IGPIOPin.PIN_DEFAULTINPUTPULLRESISTANCE); PinPullResistance pr = Pi4jGPIOPin .getPinPullResistance(pullResistance.intValue()); if (pr == null) pr = PinPullResistance.PULL_DOWN; // Get controller GPIO synchronized (refToListenerMap) { // Find reference ListenerHolder listenerHolder = refToListenerMap.get(reference); GpioPinDigitalInput inputListener = null; // We've not seen this request before if (listenerHolder == null) { inputListener = Activator.getGPIOController() .provisionDigitalInputPin(pin, pinName, pr); listenerHolder = new ListenerHolder(inputListener); } else // We've seen it before so we use the old inputListener inputListener = listenerHolder.inputListener; // create new Pi4jGPIOPinInputListener Pi4jGPIOPinInputListener listener = new Pi4jGPIOPinInputListener( inputListener, gPIOInputListener); // set on the listener holder listenerHolder.setListener(listener); // put into map refToListenerMap.put(reference, listenerHolder); } } else { System.err .println("adding IGPIOPinInputListener service...pinId is not available for pinId=" + pinId); } return gPIOInputListener; } @Override public void modifiedService( ServiceReference<IGPIOPinInputListener> reference, IGPIOPinInputListener service) { } @Override public void removedService( ServiceReference<IGPIOPinInputListener> reference, IGPIOPinInputListener service) { synchronized (refToListenerMap) { ListenerHolder listenerHolder = refToListenerMap.remove(reference); if (listenerHolder != null) { // Close our listener first if (listenerHolder.listener != null) listenerHolder.listener.close(); // Then unprovision the pin if (listenerHolder.inputListener != null) Activator.getGPIOController().unprovisionPin( listenerHolder.inputListener); } } } public void close() { refToListenerMap.clear(); } }
true
30d29a80e163b9ed06db7291813a83d1d09e7fae
Java
SoniCoder/Victum
/src/victum/Notification.java
UTF-8
447
1.8125
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package victum; import java.time.LocalTime; import java.util.ArrayList; /** * * @author Addict */ public class Notification { static ArrayList<Notification> notList; LocalTime t; String notMessage; Notification(){ } }
true
10f69c3ab95bfab1998c5b56252e62b8f03e8577
Java
NF1198/WiFiMapper
/WifiMapperGUI/src/main/java/org/tauterra/wifimapper/wifimappergui/app/NetworkWiFiAnalyzerJSHelper.java
UTF-8
2,439
2.203125
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 org.tauterra.wifimapper.wifimappergui.app; import com.tauterra.geo.LatLonBounds; import com.tauterra.geo.LatLonCoord; import java.text.MessageFormat; /** * * @author nickfolse */ public class NetworkWiFiAnalyzerJSHelper { private final NetworkWiFiAnalyzer analy; public NetworkWiFiAnalyzerJSHelper(NetworkWiFiAnalyzer analy) { this.analy = analy; } public String formatBounds(LatLonBounds b) { return MessageFormat.format("" + "'{'" + "east: {0,number,0.00000000}, " + "north: {1,number,0.00000000}, " + "south: {2,number,0.00000000}, " + "west: {3,number,0.00000000}" + "'}'", b.getMax().getLon(), b.getMax().getLat(), b.getMin().getLat(), b.getMin().getLon() ); } /** * Generate javascript code to set the bounds of the specified map variable. * * @param mapVar * @param padding * @return */ public String setBounds(String mapVar, double padding) { return MessageFormat.format("{0}.fitBounds({1}, {2,number,0.000000});", mapVar, formatBounds(analy.bounds()), padding ); } public String setDataGeoJSON(String mapVar, String geoJson) { return MessageFormat.format("" + "(function() '{'\n" + "var geoJson = {1};\n" + "{0}.data.forEach((f)=>{0}.data.remove(f));\n" + "{0}.data.addGeoJson(geoJson);\n" + "{0}.data.setStyle((f) => '{'\n" + "return '{'\n" + " fillColor: f.getProperty(\"fill\"),\n" + " fillOpacity: f.getProperty(\"fill-opacity\"),\n" + " strokeWeight: f.getProperty(\"stroke-width\"),\n" + " strokeColor: f.getProperty(\"stroke\"),\n" + " strokeOpacity: f.getProperty(\"stroke-opacity\"),\n" + " title: f.getProperty(\"level\"),\n" + " cursor: \"pointer\"\n" + "'}'\n" + "'}');\n" + "'}')();", mapVar, geoJson); } }
true