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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
285b394da4d40aeaeab0ac5b924bad52c85e4c13 | Java | sdatallinngokhan/summary | /src/main/java/week11/advanced/oop/inheritance/Mercedes.java | UTF-8 | 475 | 3.6875 | 4 | [] | no_license | package week11.advanced.oop.inheritance;
public class Mercedes extends Car {
public Mercedes() {
System.out.println("I am in sub class default const.");
}
public Mercedes(String name) {
super(name);
System.out.println("I am in sub class parameterized const.");
System.out.println(name);
}
public static void main(String[] args) {
String name = "Gokhan";
Mercedes mercedes = new Mercedes(name);
}
}
| true |
684624709802d0679f5282ccc9f7798de404eb28 | Java | Xxxx-Xxx/xxx | /src/main/epamlab/tddtask/enums/Direction.java | UTF-8 | 222 | 2.25 | 2 | [] | no_license | package main.epamlab.tddtask.enums;
/**
* Created by al on 7/7/16.
*/
public enum Direction {
/**
* Used as marker for direction "up"
*/
UP,
/**
* Used for direction "down"
*/
DOWN
}
| true |
1b8755b14d111821910bce746bf4914f8f5586fd | Java | zaproxy/zaproxy | /zap/src/main/java/org/zaproxy/zap/extension/api/ZapApiIgnore.java | UTF-8 | 1,446 | 1.578125 | 2 | [
"Apache-2.0"
] | permissive | /*
* Zed Attack Proxy (ZAP) and its related class files.
*
* ZAP is an HTTP/HTTPS proxy for assessing web application security.
*
* Copyright 2014 The ZAP Development Team
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.zaproxy.zap.extension.api;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Indicates that the method must be ignored by the ZAP API.
*
* <p><strong>Note:</strong> Currently honoured only for API options (the only ones that are
* dynamically generated from {@code AbstractParam}s set to {@code ApiImplementor}s).
*
* @see org.parosproxy.paros.common.AbstractParam
* @see ApiImplementor
* @see ApiImplementor#addApiOptions(org.parosproxy.paros.common.AbstractParam)
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface ZapApiIgnore {}
| true |
a72194c34e3ce5e7b36c5a73b7f3cf4b992fecb5 | Java | Saidewade/Java-Programs-In-Training | /CaluculationOfGrossOfEggs.java | UTF-8 | 636 | 3.515625 | 4 | [] | no_license | public class CaluculationOfGrossOfEggs
{
public static void main(String[] args)
{
Scanner scn = new Scanner(System.in);
System.out.println("enter the mnumber of eggs you want");
int eggs = scn.nextInt();
if(eggs>0)
{
if(eggs>=144)
{
int gross = eggs/144;
System.out.println("there are "+gross+" gross of eggs");
eggs = eggs-(gross*144);
}
else if(eggs>=12)
{
int dozen = eggs/12;
System.out.println("there are "+dozen+" dozen of eggs");
eggs = eggs-(dozen*12);
}
else
{
remaining = eggs;
System.out.println("there are "+remaining+" remaining of eggs");
}
}
}
}
| true |
8e1551f90096356e428b66a9f23076727a24381d | Java | xillio/xill-platform | /xill-ide/src/main/java/nl/xillio/migrationtool/dialogs/UploadToServerDialog.java | UTF-8 | 18,426 | 2.09375 | 2 | [
"Apache-2.0"
] | permissive | /**
* Copyright (C) 2014 Xillio (support@xillio.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.xillio.migrationtool.dialogs;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.scene.layout.GridPane;
import javafx.util.Pair;
import me.biesaart.utils.FileUtils;
import me.biesaart.utils.Log;
import me.biesaart.utils.StringUtils;
import nl.xillio.migrationtool.RobotValidationException;
import nl.xillio.migrationtool.XillServerUploader;
import nl.xillio.migrationtool.gui.FXController;
import nl.xillio.migrationtool.gui.ProjectPane;
import nl.xillio.xill.util.settings.Settings;
import org.slf4j.Logger;
import java.io.File;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
/**
* A dialog to upload an item to the server.
*/
public class UploadToServerDialog extends FXMLDialog {
private static final Logger LOGGER = Log.get();
@FXML
private TextField tfserver;
@FXML
private TextField tfusername;
@FXML
private TextField tfpassword;
@FXML
private CheckBox cbvalidate;
private final ObservableList<TreeItem<Pair<File, String>>> treeItems;
private final ProjectPane projectPane;
private final XillServerUploader xillServerUploader = new XillServerUploader();
private List<String> uploadedRobots = new LinkedList<>();
private String uploadedProjectId = "";
private boolean overwriteAll = false;
private static final String MAX_FILE_SIZE_SETTINGS_KEY = "spring.http.multipart.max-file-size";
private long maxFileSize; // Maximum file size that Xill server accepts
/**
* Default constructor.
*
* @param projectPane the projectPane to which this dialog is attached to.
* @param treeItems the tree item on which the item will be deleted
*/
public UploadToServerDialog(final ProjectPane projectPane, final ObservableList<TreeItem<Pair<File, String>>> treeItems) {
super("/fxml/dialogs/UploadToServer.fxml");
this.treeItems = treeItems;
this.projectPane = projectPane;
setTitle("Upload to server");
tfserver.setText(FXController.settings.simple().get(Settings.SERVER, Settings.XILL_SERVER_HOST));
tfusername.setText(FXController.settings.simple().get(Settings.SERVER, Settings.XILL_SERVER_USERNAME));
tfpassword.setText(FXController.settings.simple().get(Settings.SERVER, Settings.XILL_SERVER_PASSWORD));
}
@FXML
private void cancelBtnPressed(final ActionEvent event) {
close();
}
@FXML
private void okayBtnPressed(final ActionEvent event) {
try {
// Do connect and authenticate to server
xillServerUploader.authenticate(tfserver.getText(), tfusername.getText(), tfpassword.getText());
} catch (IOException e) {
LOGGER.error("Could not login to server", e);
AlertDialog dialog = new AlertDialog(Alert.AlertType.ERROR, "Upload to server",
"Could not login to server.", e.getMessage(),
ButtonType.OK);
dialog.showAndWait();
return;
}
try {
// Save current credentials
FXController.settings.simple().save(Settings.SERVER, Settings.XILL_SERVER_HOST, tfserver.getText());
FXController.settings.simple().save(Settings.SERVER, Settings.XILL_SERVER_USERNAME, tfusername.getText());
FXController.settings.simple().save(Settings.SERVER, Settings.XILL_SERVER_PASSWORD, tfpassword.getText());
// Clean up
uploadedRobots.clear();
overwriteAll = false;
// Get current server settings
queryServerSettings();
// Assign projectId
String projectId = null;
if(treeItems.size() > 0) {
final TreeItem<Pair<File, String>> item = treeItems.get(0);
final File projectFolder = projectPane.getProject(item).getValue().getKey();
final String projectName = xillServerUploader.getProjectName(projectFolder);
boolean projectAlreadyExists = xillServerUploader.findProject(projectName) != null;
projectId = ensureProjectExists(item);
// Process items (do selected robots and resources upload)
if (!processItems(treeItems, projectId, projectAlreadyExists)) {
return; // Process has been user interrupted - so no success dialog is shown
}
}
// Validate uploaded robots (in a one bulk server request - because of every Xill environment start is very time consuming)
if (cbvalidate.isSelected() && !uploadedRobots.isEmpty()) {
xillServerUploader.validateRobots(uploadedProjectId, uploadedRobots);
}
// Show success message
AlertDialog dialog = new AlertDialog(Alert.AlertType.INFORMATION, "Upload to server",
"Uploading process has been successfully finished.", "",
ButtonType.OK);
dialog.showAndWait();
// Close the dialog
close();
} catch (IOException e) {
LOGGER.error("Uploading process has failed", e);
AlertDialog dialog = new AlertDialog(Alert.AlertType.ERROR, "Upload to server",
"Uploading process has failed.", e.getMessage() + (e.getCause() == null ? "" : "\n" + e.getCause().getMessage()),
ButtonType.OK);
dialog.showAndWait();
} catch (RobotValidationException e) {
LOGGER.error("At least one uploaded robot is not valid", e);
AlertDialog dialog = new AlertDialog(Alert.AlertType.WARNING, "Upload to server",
"At least one uploaded robot is not valid.", e.getMessage(),
ButtonType.OK);
dialog.showAndWait();
}
}
private boolean isProject(final TreeItem<Pair<File, String>> item) {
return item.getParent() == projectPane.getRoot();
}
private boolean isFolder(final TreeItem<Pair<File, String>> item) {
return item.getValue().getKey().isDirectory();
}
private enum ExistsResult {
NO,
YES_OVERWRITE,
YES_CANCEL
}
private ExistsResult resourceExists(final File resourceFile, String projectId, final File projectFolder) throws IOException {
final String resourceName = xillServerUploader.getResourceName(resourceFile, projectFolder);
if (xillServerUploader.existResource(projectId, resourceName)) {
if(overwriteAll){
return ExistsResult.YES_OVERWRITE;
}
// Set up dialog content
CheckBox checkBox = new CheckBox("Overwrite all");
GridPane gridPane = new GridPane();
GridPane.setMargin(checkBox, new javafx.geometry.Insets(20, 0, 0, 0));
gridPane.add(checkBox, 0, 1);
ContentAlertDialog dialog = new ContentAlertDialog(Alert.AlertType.WARNING, "Uploading resource",
String.format("The resource %1$s already exists on the server", resourceName),
"Do you want to overwrite it?",
gridPane,
ButtonType.YES, ButtonType.NO);
dialog.showAndWait();
final Optional<ButtonType> result = dialog.getResult();
if (result.get().getButtonData() != ButtonBar.ButtonData.YES) {
return ExistsResult.YES_CANCEL;
}
overwriteAll = checkBox.isSelected();
return ExistsResult.YES_OVERWRITE;
}
return ExistsResult.NO;
}
private ExistsResult projectExists(final TreeItem<Pair<File, String>> item, boolean projectAlreadyExists) throws IOException {
final File projectFolder = projectPane.getProject(item).getValue().getKey();
final String projectName = xillServerUploader.getProjectName(projectFolder);
if (projectAlreadyExists) {
// Set up dialog content
CheckBox checkBox = new CheckBox("Overwrite all");
GridPane gridPane = new GridPane();
GridPane.setMargin(checkBox, new javafx.geometry.Insets(20, 0, 0, 0));
gridPane.add(checkBox, 0, 1);
ContentAlertDialog dialog = new ContentAlertDialog(Alert.AlertType.WARNING, "Uploading project",
String.format("The project %1$s already exists on the server", projectName),
"Do you want to overwrite entire project?",
gridPane,
ButtonType.YES, ButtonType.NO);
dialog.showAndWait();
final Optional<ButtonType> result = dialog.getResult();
if (result.get().getButtonData() != ButtonBar.ButtonData.YES) {
return ExistsResult.YES_CANCEL;
}
overwriteAll = checkBox.isSelected();
return ExistsResult.YES_OVERWRITE;
}
return ExistsResult.NO;
}
private ExistsResult robotExists(final File robotFile, String projectId, final File projectFolder) throws IOException {
final String robotFqn = xillServerUploader.getFqn(robotFile, projectFolder);
if (projectId == null) {
projectId = xillServerUploader.ensureProjectExist(xillServerUploader.getProjectName(projectFolder));
}
if(xillServerUploader.existRobot(projectId, robotFqn)) {
if(overwriteAll){
return ExistsResult.YES_OVERWRITE;
}
// Set up dialog content
CheckBox checkBox = new CheckBox("Overwrite all");
GridPane gridPane = new GridPane();
GridPane.setMargin(checkBox, new javafx.geometry.Insets(20, 0, 0, 0));
gridPane.add(checkBox, 0, 1);
// Set up dialog
ContentAlertDialog dialog = new ContentAlertDialog(Alert.AlertType.WARNING, "Uploading robot",
String.format("The robot %1$s already exists on the server", robotFile.getName()),
"Do you want to overwrite it?",
gridPane,
ButtonType.YES, ButtonType.NO);
dialog.showAndWait();
final Optional<ButtonType> result = dialog.getResult();
if (result.get().getButtonData() != ButtonBar.ButtonData.YES) {
return ExistsResult.YES_CANCEL;
}
overwriteAll = checkBox.isSelected();
return ExistsResult.YES_OVERWRITE;
}
xillServerUploader.existRobot(projectId, robotFqn);
return ExistsResult.NO;
}
private String ensureProjectExists(final TreeItem<Pair<File, String>> item) throws IOException {
final File projectFolder = projectPane.getProject(item).getValue().getKey();
return xillServerUploader.ensureProjectExist(xillServerUploader.getProjectName(projectFolder));
}
private void uploadChildren(final TreeItem<Pair<File, String>> item, String projectId) throws IOException {
for (TreeItem<Pair<File, String>> subItem : item.getChildren()) {
if (isFolder(subItem)) {
uploadFolder(subItem, projectId);
continue;
}
handleFileUploading(subItem, projectId);
}
}
private void uploadFolder(final TreeItem<Pair<File, String>> item, String projectId) throws IOException {
uploadChildren(item, projectId);
}
private void uploadProject(final TreeItem<Pair<File, String>> item, String projectId) throws IOException {
uploadChildren(item, projectId);
}
private void uploadRobot(final File robotFile, final File projectFolder, String projectId) throws IOException {
// Check if robot does not exceed the multipart file size limit
if (robotFile.length() > maxFileSize) {
final String robotFqn = xillServerUploader.getFqn(robotFile, projectFolder);
AlertDialog dialog = new AlertDialog(Alert.AlertType.ERROR, "Uploading robot",
"The robot cannot be uploaded to the Xill server.",
String.format("The size of robot %1$s exceeds the server file size limit.", robotFqn),
ButtonType.CLOSE);
dialog.showAndWait();
return;
}
final String code = FileUtils.readFileToString(robotFile);
final String robotFqn = xillServerUploader.getFqn(robotFile, projectFolder);
// Upload the robot
xillServerUploader.uploadRobot(projectId, robotFqn, code);
// Store robot's FQN to list for bulk validation process after entire uploading is done
uploadedRobots.add(robotFqn);
uploadedProjectId = projectId;
}
private void uploadResource(final File resourceFile, final File projectFolder, String projectId) throws IOException {
final String resourceName = xillServerUploader.getResourceName(resourceFile, projectFolder);
// Check if resource does not exceed the multipart file size limit
if (resourceFile.length() > maxFileSize) {
AlertDialog dialog = new AlertDialog(Alert.AlertType.ERROR, "Uploading resource",
"The resource cannot be uploaded to the Xill server.",
String.format("The size of resource %1$s exceeds the server file size limit.", resourceName),
ButtonType.CLOSE);
dialog.showAndWait();
return;
}
// Upload the resource
xillServerUploader.uploadResource(projectId, resourceName, resourceFile);
}
private boolean handleProjectUploading(TreeItem<Pair<File, String>> item, String projectId, boolean projectAlreadyExists) throws IOException {
ExistsResult existsResult = projectExists(item, projectAlreadyExists);
if (existsResult == ExistsResult.YES_CANCEL) {
return false;
} else if (existsResult == ExistsResult.YES_OVERWRITE) {
xillServerUploader.deleteProject(projectId);
}
projectId = ensureProjectExists(item);
uploadProject(item, projectId);
return true;
}
private boolean handleFileUploading(TreeItem<Pair<File, String>> item, String projectId) throws IOException {
ExistsResult existsResult;
final File projectFolder = projectPane.getProject(item).getValue().getKey();
final File itemFile = item.getValue().getKey();
if(isRobot(itemFile, projectFolder)) {
existsResult = robotExists(item.getValue().getKey(), projectId, projectFolder);
if(existsResult == ExistsResult.YES_CANCEL) {
return false;
}
uploadRobot(itemFile, projectFolder, projectId);
} else { //is resource
existsResult = resourceExists(item.getValue().getKey(), projectId, projectFolder);
if(existsResult == ExistsResult.YES_CANCEL) {
return false;
}
uploadResource(itemFile, projectFolder, projectId);
}
return true;
}
private boolean handleFolderUploading(TreeItem<Pair<File, String>> item, String projectId) throws IOException {
uploadFolder(item, projectId);
return true;
}
private boolean processItems(final List<TreeItem<Pair<File, String>>> items, String projectId, boolean projectAlreadyExists) throws IOException {
for (TreeItem<Pair<File, String>> item : items) {
if (isProject(item)) {
if(!handleProjectUploading(item, projectId, projectAlreadyExists)) {
return false;
}
} else if (isFolder(item)) {// Directory
if(!handleFolderUploading(item, projectId)) {
return false;
}
} else {
if(!handleFileUploading(item, projectId)) {
return false;
}
}
}
return true;
}
private void queryServerSettings() throws IOException {
Map<String, String> settings = xillServerUploader.querySettings();
if (!settings.containsKey(MAX_FILE_SIZE_SETTINGS_KEY)) {
throw new IOException("Invalid response from the server.");
}
maxFileSize = Long.valueOf(settings.get(MAX_FILE_SIZE_SETTINGS_KEY));
}
/**
* Determine if item is robot or resource.
*
* A robot has a fully qualified name if:
* - All folder names above it (up to and excluding the project folder) are valid package names. Regex: ([a-zA-Z][a-zA-Z0-9_]*)
* - The robot itself is a valid robot name ([a-zA-Z][a-zA-Z0-9_]*) and ends with the .xill extension
* All other files (including Xill scripts that do not match the rules above) are considered resources.
*
* @param itemFile the file to be determined
* @return true if it's robot, otherwise it's a resource
*/
private boolean isRobot(final File itemFile, final File projectFolder) {
// Get inner path
final String innerPath = projectFolder.toURI().relativize(itemFile.getParentFile().toURI()).getPath();
// Validate inner path if it's compliant for being part of robot's FQN
if (!innerPath.isEmpty()) {
for (String part : innerPath.split("/")) {
if (!part.matches("[a-zA-Z][a-zA-Z0-9_]*")) { // Check each folder name in inner path if it is a valid package name
return false; // No, it's a resource
}
}
}
// Validate robot name
return itemFile.getName().matches("^[_a-zA-Z][a-zA-Z0-9_]*\\.xill$");
}
}
| true |
2965612deef592e99f2281d1b280fe777a8e8aa8 | Java | jabrahamocampo/KnowingJava | /src/com/cap07/Networking/DemoServerMT.java | UTF-8 | 1,593 | 3.453125 | 3 | [] | no_license | package com.cap07.Networking;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class DemoServerMT {
public static void main(String[] args) throws Exception{
Socket s = null;
ServerSocket ss = new ServerSocket(5432);
while(true){
try{
//Server socket me da el socket
s = ss.accept();
//instancio un thread
(new Tarea(s)).start();
}catch(Exception ex){
ex.printStackTrace();
}
}
}
static class Tarea extends Thread{
private Socket s = null;
private ObjectOutputStream oos = null;
private ObjectInputStream ois = null;
public Tarea(Socket socket){
this.s = socket;
}
public void run(){
try{
//informacion en la consola
System.out.println("Se conectaron desde la IP: "+s.getInetAddress());
//enmascaro la entrada y salida de los bytes
ois = new ObjectInputStream(s.getInputStream());
oos = new ObjectOutputStream(s.getOutputStream());
//leo el nombre que envia el cliente
String nom = (String)ois.readObject();
//armo el saludo personalizado que le quiero enviar
String saludo = "Hola Mundo ("+nom+")"+System.currentTimeMillis();
//envio el saludo al cliente
oos.writeObject(saludo);
System.out.println("Saludo enviado...");
}catch(Exception ex){
ex.printStackTrace();
}finally{
try{
if(oos != null) oos.close();
if(ois != null) ois.close();
if(s != null) s.close();
}catch(Exception ex){
ex.printStackTrace();
}
}
}
}
}
| true |
3b62527796a5b90b1e0a4c7399f401c1ca12a310 | Java | warning5/credit | /framework/com/bluecloud/mvc/core/FragmentActionHandlerImpl.java | UTF-8 | 3,434 | 2.15625 | 2 | [] | no_license | /**
*
*/
package com.bluecloud.mvc.core;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.bluecloud.mvc.api.FragmentActionHandler;
import com.bluecloud.mvc.exception.HtmlFragmentDispatcherException;
import com.bluecloud.mvc.external.Action;
import com.bluecloud.mvc.external.FragmentEvent;
import com.bluecloud.mvc.external.widgets.MessageWidget;
import com.bluecloud.mvc.external.widgets.impl.DefaultMessageWidget;
import com.bluecloud.mvc.web.data.RequestData;
import com.bluecloud.mvc.web.data.ResponseData;
import com.bluecloud.mvc.web.http.HtmlFragmentDispatcher;
import com.bluecloud.mvc.web.http.HtmlFragmentRequest;
import com.bluecloud.mvc.web.http.HtmlFragmentResponse;
/**
* @author Hanlu
*
*/
public class FragmentActionHandlerImpl implements FragmentActionHandler {
private Log log = LogFactory.getLog(FragmentActionHandlerImpl.class);
protected HtmlFragmentRequest request;
protected HtmlFragmentResponse response;
public FragmentActionHandlerImpl(HtmlFragmentRequest request, HtmlFragmentResponse response, RequestData reqData) {
request.setData(reqData);
this.request = request;
this.response = response;
}
/*
* (non-Javadoc)
*
* @see com.bluecloud.mvc.api.FragmentActionHandler#getRequestActionName()
*/
@Override
public final String getRequestActionName() {
return request.getActionName();
}
@Override
public final void service(Action action) throws Exception {
try {
if (action == null) {
this.processError(response, "html/404.html", "请求地址不正确:"
+ request.getHttpServletRequest().getRequestURI());
return;
}
action.setResponse(response);
request.setBeans(action.getBeans());
String eventName = request.getEventName();
if (eventName == null) {
action.execute(request);
} else {
FragmentEvent event = action.getEvent(eventName);
if (null == event) {
this.processError(response, "html/404.html", "请求地址不正确:"
+ request.getHttpServletRequest().getRequestURI());
return;
} else {
event.execute(request, action);
}
}
ResponseData resData = response.getData();
HtmlFragmentDispatcher dispatch = resData.getDispatcher();
if (null != dispatch) {
dispatch.exce(this);
} else {
PrintWriter pw = new PrintWriter(new OutputStreamWriter(response.getHttpServletResponse()
.getOutputStream(), response.getHttpServletResponse().getCharacterEncoding()));
String s = response.getData().toString();
pw.println(s);
pw.flush();
pw.close();
}
} catch (Exception e) {
log.error(e.getMessage(), e);
this.processError(response, "html/error.html", e.getMessage());
}
}
/**
* @param res
* @param path
* @param info
* @throws HtmlFragmentDispatcherException
*
*/
private void processError(HtmlFragmentResponse res, String path, String info)
throws HtmlFragmentDispatcherException {
log.debug("请求出错,转向:" + path);
MessageWidget message = new DefaultMessageWidget(info);
message.fail();
res.addMessage(message);
res.forward(path);
res.getData().getDispatcher().exce(this);
}
/**
*
* @return
*/
public final HtmlFragmentRequest getRrequest() {
return request;
}
/**
*
* @return
*/
public final HtmlFragmentResponse getResponse() {
return response;
}
}
| true |
176d90e0abf27c914fb19b287f22ffcf8186a281 | Java | tsreenath198/ccpttool | /ccpt-parent/ccpt-server/src/main/java/com/ccpt/model/SmsTemplate.java | UTF-8 | 488 | 1.984375 | 2 | [] | no_license | package com.ccpt.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@Entity
@Table
@Getter
@Setter
@ToString
public class SmsTemplate extends IDEntity {
/**
*
*/
private static final long serialVersionUID = 1L;
@Column(name = "type", unique = true)
@NotNull
private String type;
}
| true |
a284dce4992bb88babfa6d5ab3efe6f6c121b83c | Java | Khalid-Altoum/eBanking | /src/main/java/com/example/ebanking/run/UpdateTesting.java | UTF-8 | 546 | 2.046875 | 2 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.example.ebanking.run;
import com.example.ebanking.model.*;
public class UpdateTesting {
public static void main(String[] args) {
SavingAccount sa = SavingAccount.getSavingAccountById(1);
ChequingAccount ca = ChequingAccount.getChequingAccountById(2);
Account.transfer(ca, sa, 100, "Paying my load");
}
}
| true |
e2cbd5c9e36008927483975159facdef9bb1361c | Java | anndyd/iot | /src/main/java/com/ljy/iot/util/DataUtil1.java | UTF-8 | 2,470 | 2.8125 | 3 | [] | no_license | package com.ljy.iot.util;
import java.math.BigInteger;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* @author : 夕
* @date : 2019/8/30
*/
public class DataUtil1 {
public static String getTimeStamp(String s){
String a = s.substring(0,2);
String b = s.substring(2,4);
String c = s.substring(4,6);
String d = s.substring(6,8);
String e = s.substring(8,10);
String f = s.substring(10,12);
String res = "20" + a + "-" + b + "-" + c + " " + d + ":" + e + ":" + f ;
return res;
}
public static String compareAndSwap(int data_flag, String data){
if(data_flag == 3 || data_flag == 4 || data_flag == 5 || data_flag == 6 ||
data_flag == 7 || data_flag == 8 || data_flag == 9 || data_flag == 32
|| data_flag == 35 || data_flag == 39 || data_flag == 42
|| data_flag == 46 || data_flag == 49){
if(Integer.parseInt(data ,16) > Integer.parseInt("8000",16) ){
data = String.valueOf(Integer.parseInt("8000" ,16) - Integer.parseInt(data,16));
data = getFloatData(data_flag,data);
}else {
data = new BigInteger(data,16).toString(10);
data = getFloatData(data_flag,data);
}
}else {
data = new BigInteger(data,16).toString(10);
data = getFloatData(data_flag,data);
}
return data;
}
public static String getFloatData(int flag ,String data){
if( (flag >= 3 && flag <= 8) || (flag >= 10 && flag <= 13) || (flag >= 17 && flag <= 20 ) || (flag >= 22 && flag <= 26) || flag == 51 ){
data = String.valueOf(Integer.parseInt(data) * 0.1);
java.text.DecimalFormat dF = new java.text.DecimalFormat("0.0");
data = dF.format(Float.parseFloat(data));
}
if(flag == 9 || flag == 15 || flag == 16){
data = String.valueOf(Integer.parseInt(data) * 0.01);
java.text.DecimalFormat dF = new java.text.DecimalFormat("0.00");
data = dF.format(Float.parseFloat(data));
}
if(flag >= 36 && flag <= 49){
data = String.valueOf(Integer.parseInt(data) * 0.001);
java.text.DecimalFormat dF = new java.text.DecimalFormat("0.000");
data = dF.format(Float.parseFloat(data));
}
return data;
}
}
| true |
462cc259cfb3cf466b9b9a063a043d81a2c5da1e | Java | zeynepUcar/new_jersey | /src/TubaDeneme.java | UTF-8 | 128 | 1.75 | 2 | [] | no_license | public class TubaDeneme {
public static void main(String[] args) {
System.out.println("Zeynep bi baksana");
}
}
| true |
97daa6d7bdfd40849c26caeb9ff96414d10ea8a9 | Java | SlimeKnights/TinkersConstruct | /src/main/java/slimeknights/tconstruct/gadgets/item/slimesling/EarthSlimeSlingItem.java | UTF-8 | 1,765 | 2.21875 | 2 | [
"MIT"
] | permissive | package slimeknights.tconstruct.gadgets.item.slimesling;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.phys.BlockHitResult;
import net.minecraft.world.level.ClipContext;
import net.minecraft.world.phys.HitResult;
import net.minecraft.world.phys.Vec3;
import net.minecraft.world.level.Level;
import slimeknights.tconstruct.library.utils.SlimeBounceHandler;
import slimeknights.tconstruct.shared.block.SlimeType;
import net.minecraft.world.item.Item.Properties;
public class EarthSlimeSlingItem extends BaseSlimeSlingItem {
public EarthSlimeSlingItem(Properties props) {
super(props, SlimeType.EARTH);
}
/** Called when the player stops using an Item (stops holding the right mouse button). */
@Override
public void releaseUsing(ItemStack stack, Level worldIn, LivingEntity entityLiving, int timeLeft) {
if (!entityLiving.isOnGround() || !(entityLiving instanceof Player)) {
return;
}
// check if player was targeting a block
Player player = (Player) entityLiving;
BlockHitResult mop = getPlayerPOVHitResult(worldIn, player, ClipContext.Fluid.NONE);
if (mop.getType() == HitResult.Type.BLOCK) {
// we fling the inverted player look vector
float f = getForce(stack, timeLeft);
Vec3 vec = player.getLookAngle().normalize();
player.push(vec.x * -f,
vec.y * -f / 3f,
vec.z * -f);
SlimeBounceHandler.addBounceHandler(player);
if (!worldIn.isClientSide) {
player.getCooldowns().addCooldown(stack.getItem(), 3);
onSuccess(player, stack);
}
} else {
playMissSound(player);
}
}
}
| true |
9f94bec0d60839ad23045b656f4804c5fb9b1637 | Java | RiceanVlad/Hospital-Management | /src/Test.java | UTF-8 | 14,413 | 2.828125 | 3 | [
"MIT"
] | permissive | import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
/**
* Clasa Test contine 3 liste(clinici, sectii, pacienti) si functii care extrag data din baza de date si care adauga pacienti/sectii/clinici
* si care afiseaza informatii despre spital
* @author Vlad
* @version 1.01
*
*/
public class Test {
/**
* @param pacienti, contine o lista de obiecte de tip Pacient
* @param sectii, contine o lista de obiecte de tip Sectie
* @param clinici, contine o lista de obiecte de tip Clinica
*/
protected static List<Pacient> pacienti = new ArrayList<Pacient>();
protected static List<Sectie> sectii = new ArrayList<Sectie>();
protected static List<Clinica> clinici = new ArrayList<Clinica>();
public static void main(String[] args) {
extragePacienti();
extrageSectii();
extrageClinici();
Meniu nw = new Meniu();
nw.fereastraMeniu();
}
/**
* functia addDiscount() adauga discount tuturor pacientilor care au cel putin 2 vizite in anul curent la spital
*/
public static void addDiscount() {
try {
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/bd","vlad","vlad4567");
Statement comanda = myConn.createStatement();
comanda.executeUpdate("UPDATE bd.pacient SET discount=0");
}
catch (Exception exc) {
exc.printStackTrace();
System.exit(1);
}
for(Pacient pacient : pacienti) {
try {
int cnt=0;
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/bd","vlad","vlad4567");
Statement comanda = myConn.createStatement();
ResultSet rs = comanda.executeQuery("SELECT COUNT(*) as count "
+ "FROM bd.dataie dataie "
+ "inner join bd.pacient pacient ON pacient.cnp=dataie.cnp "
+ "where dataie.datai>='2020-01-01' and dataie.cnp='"+pacient.getCnp()+"'");
if(rs.next()) {
cnt=rs.getInt("count");
}
if(cnt>=2) {
comanda.executeUpdate("UPDATE bd.pacient SET discount=1 where bd.pacient.cnp='"+pacient.getCnp()+"'");
}
}
catch (Exception exc) {
exc.printStackTrace();
System.exit(1);
}
}
}
/**
* functia internariExternari() returneaza informatiile despre un spital (clinicile pe care le contine, si pentru fiecare clinica afiseaza cate femei
* si barbati sunt internati in sectii, in ziua curenta)
* @return
*/
public static String internariExternari() {
StringBuilder sb = new StringBuilder();
for(Clinica clinica : clinici) {
sb.append("Clinica "+clinica.getNume()+"\n");
for(Sectie sectie : sectii) {
if(sectie.getClno()==clinica.getClno()) {
sb.append(" Sectia "+sectie.getSectno()+"\n");
int cnt=0;
try {
//barbati internati
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/bd","vlad","vlad4567");
Statement comanda = myConn.createStatement();
ResultSet rs = comanda.executeQuery("SELECT COUNT(*) as count "
+ "FROM bd.dataie dataie "
+ "inner join bd.pacient pacient ON pacient.cnp=dataie.cnp "
+ "inner join bd.sectie sectie ON sectie.sectno=pacient.sectno "
+ "inner join bd.clinica clinica ON clinica.clno=sectie.clno "
+ "where sectie.sectno="+ sectie.getSectno() +" and clinica.clno="+ clinica.getClno() +" and str_to_date(curdate(),'%Y-%m-%d')=dataie.datai and pacient.cnp like '1%'");
if(rs.next()) {
cnt = rs.getInt("count");
}
//barbati externati
ResultSet rs1 = comanda.executeQuery("SELECT COUNT(*) as count "
+ "FROM bd.dataie dataie "
+ "inner join bd.pacient pacient ON pacient.cnp=dataie.cnp "
+ "inner join bd.sectie sectie ON sectie.sectno=pacient.sectno "
+ "inner join bd.clinica clinica ON clinica.clno=sectie.clno "
+ "where sectie.sectno="+ sectie.getSectno() +" and clinica.clno="+ clinica.getClno() +" and str_to_date(curdate(),'%Y-%m-%d')=dataie.datae and pacient.cnp like '1%'");
if(rs1.next()) {
cnt += rs1.getInt("count");
sb.append(" Barbati internati/externati: "+cnt+"\n");
}
//
//femei internate
cnt=0;
ResultSet rs0 = comanda.executeQuery("SELECT COUNT(*) as count "
+ "FROM bd.dataie dataie "
+ "inner join bd.pacient pacient ON pacient.cnp=dataie.cnp "
+ "inner join bd.sectie sectie ON sectie.sectno=pacient.sectno "
+ "inner join bd.clinica clinica ON clinica.clno=sectie.clno "
+ "where sectie.sectno="+ sectie.getSectno() + " and clinica.clno="+ clinica.getClno() +" and str_to_date(curdate(),'%Y-%m-%d')=dataie.datai and pacient.cnp like '2%'");
if(rs0.next()) {
cnt = rs0.getInt("count");
}
//femei externate
ResultSet rs2 = comanda.executeQuery("SELECT COUNT(*) as count "
+ "FROM bd.dataie dataie "
+ "inner join bd.pacient pacient ON pacient.cnp=dataie.cnp "
+ "inner join bd.sectie sectie ON sectie.sectno=pacient.sectno "
+ "inner join bd.clinica clinica ON clinica.clno=sectie.clno "
+ "where sectie.sectno="+ sectie.getSectno() + " and clinica.clno="+ clinica.getClno() +" and str_to_date(curdate(),'%Y-%m-%d')=dataie.datae and pacient.cnp like '2%'");
if(rs2.next()) {
cnt += rs2.getInt("count");
sb.append(" Femei internate/externate: "+cnt+"\n");
}
//
}
catch (Exception exc) {
exc.printStackTrace();
System.exit(1);
}
}//if sectie.clno=clinica.clno
}
sb.append("----------------------------------------"+"\n");
}
return sb.toString();
}
/**
* functia addPacientiInSectii returneaza pentru o clinica data, gradul de ocupare al fiecarei sectii
* @param c clinica
* @return
*/
public static String addPacientiInSectii(Clinica c) {
try {
StringBuilder sb = new StringBuilder();
sb.append("UPDATE bd.sectie SET locuriOcupate=0");
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/bd","vlad","vlad4567");
Statement comanda = myConn.createStatement();
comanda.executeUpdate(sb.toString());
StringBuilder sbAdd = new StringBuilder();
ResultSet rs0 = comanda.executeQuery("SELECT COUNT(*) as count "
+ "FROM bd.sectie "
+ "WHERE bd.sectie.clno="+c.getClno());
if(rs0.next()) {
sbAdd.append("Clinica " + c.getNume()+" are "+rs0.getInt("count") + " sectii"+"\n");
}
for(Sectie sectie : sectii) {
if(c.getClno()==sectie.getClno()) {
sbAdd.append(" Sectia " + sectie.getSectno()+"\n");
StringBuilder sbQ = new StringBuilder();
sbQ.append("SELECT COUNT(*) as count "
+ "from bd.dataie dataie "
+ "inner join bd.pacient pacient ON dataie.cnp=pacient.cnp "
+ "inner join bd.sectie sectie ON sectie.sectno=pacient.sectno "
+ "inner join bd.clinica clinica ON clinica.clno=sectie.clno "
+ "where str_to_date(curdate(),'%Y-%m-%d')=dataie.datai and sectie.sectno="+ sectie.getSectno() +" and sectie.clno="+c.getClno());
ResultSet rs = comanda.executeQuery(sbQ.toString());
int cnt=0;
if(rs.next()) {
cnt=rs.getInt("count");
sbAdd.append(" "+cnt+"/"+sectie.getLocuri()+" locuri ocupate"+"\n");
}
comanda.executeUpdate("UPDATE bd.sectie SET locuriOcupate="+cnt);
}
}
return sbAdd.toString();
}
catch (Exception exc) {
exc.printStackTrace();
System.exit(1);
}
return null;
}
/**
* functia addPacient adaugau un pacient in sectie
* @param p pacientul ce urmeaza sa fie adaugat
*/
public static void addPacient(Pacient p) {
try {
StringBuilder sb = new StringBuilder();
sb.append("INSERT INTO bd.pacient(cnp,nume,prenume,abonament,discount,sectno) "
+ "values('"+p.getCnp()+"','"+ p.getNume() +"','"+ p.getPrenume() +"','"+ p.getAbonament() +"',"+ "0" +",'"+ p.getSectno() + "')");
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/bd","vlad","vlad4567");
Statement comanda = myConn.createStatement();
comanda.executeUpdate(sb.toString());
pacienti.add(p);
}
catch (Exception exc) {
exc.printStackTrace();
System.exit(1);
}
}
/**
* functia adauga pentru un CNP dat, intarea si externarea din spital
* @param cnp CNP pacient
* @param datai data de internare in spital
* @param datae data de externare din spital
*/
public static void addDataIE(String cnp, String datai, String datae) {
try {
StringBuilder sb = new StringBuilder();
sb.append("INSERT INTO bd.dataie(cnp,datai,datae) "
+ "values('"+cnp+"','"+ datai +"','"+ datae + "')");
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/bd","vlad","vlad4567");
Statement comanda = myConn.createStatement();
comanda.executeUpdate(sb.toString());
}
catch (Exception exc) {
exc.printStackTrace();
System.exit(1);
}
}
/**
* fucntia addSectie adauga o sectie in clinica
* @param s sectia ce urmeaza sa fie adaugata
*/
public static void addSectie(Sectie s) {
try {
StringBuilder sb = new StringBuilder();
sb.append("INSERT INTO bd.sectie(sectno,locuri,locuriOcupate,tip,clno) "
+ "values('"+ s.getSectno() +"','"+ s.getLocuri()+ "',0" +",'"+ s.getTip() + "','"+ s.getClno() + "')");
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/bd","vlad","vlad4567");
Statement comanda = myConn.createStatement();
comanda.executeUpdate(sb.toString());
sectii.add(s);
}
catch (Exception exc) {
exc.printStackTrace();
System.exit(1);
}
}
/**
* functia addClinica adauga o noua clinica in spital
* @param c clinica ce urmeaza sa fie adaugata
*/
public static void addClinica(Clinica c) {
try {
StringBuilder sb = new StringBuilder();
sb.append("INSERT INTO bd.clinica(clno,nume,spno) "
+ "values('"+ c.getClno() +"','"+ c.getNume() +"','"+ c.getSpno() + "')");
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/bd","vlad","vlad4567");
Statement comanda = myConn.createStatement();
comanda.executeUpdate(sb.toString());
clinici.add(c);
}
catch (Exception exc) {
exc.printStackTrace();
System.exit(1);
}
}
/**
* functia extragePacienti() extrage pacientii din baza de date, si ii adauga in lista de pacienti
*/
public static void extragePacienti() {
StringBuilder sbPacient=new StringBuilder();
sbPacient.append("SELECT * FROM bd.pacient");
try {
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/bd","vlad","vlad4567");
Statement comanda = myConn.createStatement();
ResultSet rez=comanda.executeQuery(sbPacient.toString());
int ok=0;
while(rez.next()) {
Pacient p=new Pacient(rez.getString("cnp"),rez.getString("nume"),rez.getString("prenume"),rez.getInt("abonament"),rez.getInt("sectno"));
pacienti.add(p);
}
}
catch (Exception exc) {
exc.printStackTrace();
System.exit(1);
}
}
/**
* functia extrageSectii() extrage sectiile din baza de date, si le adauga in lista de sectii
*/
public static void extrageSectii() {
try {
StringBuilder sb = new StringBuilder();
sb.append("SELECT * from bd.sectie");
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/bd","vlad","vlad4567");
Statement comanda = myConn.createStatement();
ResultSet rs = comanda.executeQuery(sb.toString());
while(rs.next()) {
Sectie s = new Sectie(rs.getInt("sectno"),rs.getInt("locuri"),rs.getString("tip"),rs.getInt("clno"));
sectii.add(s);
}
}
catch (Exception exc) {
exc.printStackTrace();
System.exit(1);
}
}
/**
* functia extrageClinici() extrage clinicile din baza de date, si le adauga in lista de clinici
*/
public static void extrageClinici() {
StringBuilder sb=new StringBuilder();
sb.append("SELECT * FROM bd.clinica");
try {
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/bd","vlad","vlad4567");
Statement comanda = myConn.createStatement();
ResultSet rez=comanda.executeQuery(sb.toString());
int ok=0;
while(rez.next()) {
Clinica c=new Clinica(rez.getInt("clno"),rez.getString("nume"),rez.getInt("spno"));
clinici.add(c);
}
}
catch (Exception exc) {
exc.printStackTrace();
System.exit(1);
}
}
}//test
| true |
8d95bd16243120fbeea7c0aa36939e3a2f4686d2 | Java | cnipr/backup | /pss-jp/src/main/java/com/cr/pss/search/impl/PatAutoTipSearcher.java | UTF-8 | 833 | 2.171875 | 2 | [] | no_license | package com.cnipr.pss.search.impl;
import com.cnipr.pss.search.AbstractSearcher;
import com.cnipr.pss.util.ReadresourceUtil;
import com.eprobiti.trs.TRSException;
/**
* 自动提示
* @author lq
*
*/
public class PatAutoTipSearcher extends AbstractSearcher {
private String strWhere;
public PatAutoTipSearcher(String strWhere){
this.searchType = 2;
this.strWhere = strWhere;
}
@Override
public String doSearch() {
String r = "";
String[] wordTips = null;
int tipsNum = Integer.parseInt(ReadresourceUtil.getNum("wordtipsnum"));
try {
wordTips = semanticInstance.GetWordTips(strWhere, tipsNum, "");
if (wordTips != null && wordTips.length > 0) {
for (String s : wordTips) {
r += s + "###";
}
}
} catch (TRSException e) {
e.printStackTrace();
return null;
}
return r;
}
}
| true |
bbf1aa0922187aece8494963dd5e859fc2c47683 | Java | Fluxengin/fdsl-test | /fluxengine-local-test/src/test/java/jp/co/fluxengine/example/Variant.java | UTF-8 | 1,438 | 2.28125 | 2 | [] | no_license | package jp.co.fluxengine.example;
import jp.co.fluxengine.apptest.DslPath;
import jp.co.fluxengine.apptest.DslPathResolver;
import jp.co.fluxengine.apptest.TestResult;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import static jp.co.fluxengine.apptest.TestUtils.testDslAndGetResults;
import static org.assertj.core.api.Assertions.assertThat;
@ExtendWith(DslPathResolver.class)
@DslPath("dsl/junit/02_エンジン/06_Variant")
public class Variant {
@Test
@DslPath("複雑な構造")
void complexStructure(String dslPath) {
assertThat(testDslAndGetResults(dslPath)).hasSize(1).allMatch(TestResult::isSucceeded);
}
@Test
@DslPath("mapの中にenum")
void enumInMap(String dslPath) {
assertThat(testDslAndGetResults(dslPath)).hasSize(1).allMatch(TestResult::isSucceeded);
}
@Test
@DslPath("テストからの値の設定")
void setValueFromTest(String dslPath) {
assertThat(testDslAndGetResults(dslPath)).hasSize(2).allMatch(TestResult::isSucceeded);
}
@Test
@DslPath("キャッシュ")
void cache(String dslPath) {
assertThat(testDslAndGetResults(dslPath)).hasSize(2).allMatch(TestResult::isSucceeded);
}
@Test
@DslPath("条件分岐")
void conditionalBranches(String dslPath) {
assertThat(testDslAndGetResults(dslPath)).hasSize(3).allMatch(TestResult::isSucceeded);
}
}
| true |
f41dceaf7f4fe84f887cb5713b9dfbdb7675e65f | Java | whol/redisClusterDemo | /src/main/java/com/example/demo/beans/common/JsonFormatException.java | UTF-8 | 684 | 2.390625 | 2 | [
"Apache-2.0"
] | permissive | package com.example.demo.beans.common;
import com.example.demo.common.exception.GeneralException;
/**
* JSON格式化异常
* @see GeneralException
* Created by alen on 17-9-21.
*/
public class JsonFormatException extends GeneralException {
public JsonFormatException(String errorCode) {
super(errorCode);
}
public JsonFormatException(String errorCode, String message) {
super(errorCode, message);
}
public JsonFormatException(String errorCode, String message, Throwable cause) {
super(errorCode, message, cause);
}
public JsonFormatException(String errorCode, Throwable cause) {
super(errorCode, cause);
}
}
| true |
833e778c977795c389e7039f9039206030c58546 | Java | FWJacky/personalAccountant | /sms_system_demo/src/main/java/com/liu/sms/po/CourseCustom.java | UTF-8 | 753 | 2.21875 | 2 | [] | no_license | package com.liu.sms.po;
/**
* Course扩展类 课程
*/
public class CourseCustom extends Course {
//所属院系名
private String collegeName;
// 所属老师
private String teacherName;
private Integer teacherID;
public Integer getTeacherID() {
return teacherID;
}
public void setTeacherID(Integer teacherID) {
this.teacherID = teacherID;
}
public String getTeacherName() {
return teacherName;
}
public void setTeacherName(String teacherName) {
this.teacherName = teacherName;
}
public String getCollegeName() {
return collegeName;
}
public void setCollegeName(String collegeName) {
this.collegeName = collegeName;
}
}
| true |
70b642ec62fa86a46ea94f36fc963ef5852640df | Java | rizzkim/JavaEdu | /JavaEdu/src/javaapp1030/HTMLDownload.java | UTF-8 | 1,274 | 3.296875 | 3 | [] | no_license | package javaapp1030;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HTMLDownload {
public static void main(String[] args) {
try {
// URL 생성
URL url = new URL("http://chunchu.yonsei.ac.kr/rss/allArticle.xml");
// 연결 객체 생성
HttpURLConnection con = (HttpURLConnection)url.openConnection();
// 옵션 설정
// 접속 시도 시간을 설정
// 캐시 사용 여부를 설정
con.setConnectTimeout(30000);
con.setUseCaches(false);
// 전송방식이 POST 라면 setRequestMethod 호출
// 문자열 다운로드이면 BufferedReader를 만들고,
// 파일 다운로드이면 BufferedInputStream을 생성
BufferedReader br = new BufferedReader(
new InputStreamReader(con.getInputStream()));
StringBuilder sb = new StringBuilder();
while(true) {
String line = br.readLine();
if(line == null) {
break;
}
sb.append(line+"\n");
}
String content = sb.toString();
System.out.printf("%s", content);
// 정리작업
br.close();
con.disconnect();
} catch(Exception e) {
System.out.printf("예외: %s\n", e.getMessage());
e.printStackTrace();
}
}
}
| true |
1cde60fe087ccc057dae2534f52f4a9dd181a0a8 | Java | xuxingyin/fescar | /core/src/main/java/com/alibaba/fescar/core/protocol/RegisterRMRequest.java | UTF-8 | 4,388 | 1.992188 | 2 | [
"Apache-2.0"
] | permissive | /*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* 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.alibaba.fescar.core.protocol;
import java.io.Serializable;
import io.netty.buffer.ByteBuf;
/**
* The type Register rm request.
*
* @Author: jimin.jm @alibaba-inc.com
* @Project: fescar -all
* @DateTime: 2018 /10/10 14:43
* @FileName: RegisterRMRequest
* @Description:
*/
public class RegisterRMRequest extends AbstractIdentifyRequest implements Serializable {
private static final long serialVersionUID = 7539732523682335742L;
private String resourceIds;
/**
* Instantiates a new Register rm request.
*/
public RegisterRMRequest() {
this(null, null);
}
/**
* Instantiates a new Register rm request.
*
* @param applicationId the application id
* @param transactionServiceGroup the transaction service group
*/
public RegisterRMRequest(String applicationId, String transactionServiceGroup) {
super(applicationId, transactionServiceGroup);
}
/**
* Gets resource ids.
*
* @return the resource ids
*/
public String getResourceIds() {
return resourceIds;
}
/**
* Sets resource ids.
*
* @param resourceIds the resource ids
*/
public void setResourceIds(String resourceIds) {
this.resourceIds = resourceIds;
}
@Override
public short getTypeCode() {
return TYPE_REG_RM;
}
@Override
protected void doEncode() {
super.doEncode();
if (this.resourceIds != null) {
byte[] bs = resourceIds.getBytes(UTF8);
byteBuffer.putInt(bs.length);
if (bs.length > 0) {
byteBuffer.put(bs);
}
} else {
byteBuffer.putInt(0);
}
}
@Override
public boolean decode(ByteBuf in) {
int i = in.readableBytes();
if (i < 1) {
return false;
}
short len = in.readShort();
if (len > 0) {
if (i < len) {
return false;
} else {
i -= len;
}
byte[] bs = new byte[len];
in.readBytes(bs);
this.setVersion(new String(bs, UTF8));
}
len = in.readShort();
if (len > 0) {
if (i < len) {
return false;
} else {
i -= len;
}
byte[] bs = new byte[len];
in.readBytes(bs);
this.setApplicationId(new String(bs, UTF8));
}
len = in.readShort();
if (len > 0) {
if (i < len) {
return false;
} else {
i -= len;
}
byte[] bs = new byte[len];
in.readBytes(bs);
this.setTransactionServiceGroup(new String(bs, UTF8));
}
len = in.readShort();
if (len > 0) {
if (i < len) {
return false;
} else {
i -= len;
}
byte[] bs = new byte[len];
in.readBytes(bs);
this.setExtraData(new String(bs, UTF8));
}
int iLen = in.readInt();
if (iLen > 0) {
if (i < iLen) {
return false;
} else {
i -= iLen;
}
byte[] bs = new byte[iLen];
in.readBytes(bs);
this.setResourceIds(new String(bs, UTF8));
}
return true;
}
@Override
public String toString() {
return "RegisterRMRequest{" +
"resourceIds='" + resourceIds + '\'' +
", applicationId='" + applicationId + '\'' +
", transactionServiceGroup='" + transactionServiceGroup + '\'' +
'}';
}
}
| true |
342aa59aae6951bec71ea1af23021c68f0b49ca2 | Java | yuyuliuyu/LAOBAO | /src/com/lingnet/hcm/service/impl/check/StandardServiceImpl.java | UTF-8 | 5,098 | 2.265625 | 2 | [] | no_license | package com.lingnet.hcm.service.impl.check;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Service;
import com.lingnet.common.service.impl.BaseServiceImpl;
import com.lingnet.hcm.dao.check.StandardDao;
import com.lingnet.hcm.entity.check.CkStandard;
import com.lingnet.hcm.service.check.StandardService;
import com.lingnet.util.Pager;
/**
*
* @ClassName: StandardServiceImpl
* @Description: 考勤标准service实现类
* @author wangqiang
* @date 2017年3月22日 下午2:13:12
*
*/
@Service("standardService")
public class StandardServiceImpl extends BaseServiceImpl<CkStandard, String> implements StandardService{
@Resource(name = "standardDao")
private StandardDao standardDao;
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public Map<String, Object> getDataByCond(Pager pager) {
List<Map<String, Object>> datas = standardDao.getInfoByCond(pager);
HashMap result = new HashMap();
result.put("data", datas);
result.put("total", pager.getTotalCount());
return result;
}
@Override
public void saveOrUpdateInfo(Map<String,String> dataMap) throws Exception {
if (!dataMap.isEmpty()){
if (!"".equals(dataMap.get("id"))){//修改
CkStandard standard = standardDao.get(dataMap.get("id"));
standard.setYearCalendar(dataMap.get("yearCalendar"));
standard.setMonthDays(dataMap.get("monthDays"));
standard.setWorkDays(dataMap.get("workDays"));
standard.setRestDays(dataMap.get("restDays"));
standard.setHolidayDays(dataMap.get("holidayDays"));
standard.setFestival1(dataMap.get("festival1"));
standard.setFestival2(dataMap.get("festival2"));
standard.setFestival3(dataMap.get("festival3"));
standard.setFestival4(dataMap.get("festival4"));
standardDao.update(standard);
} else {//保存
CkStandard standard = new CkStandard();
standard.setYearCalendar(dataMap.get("yearCalendar"));
standard.setMonthDays(dataMap.get("monthDays"));
standard.setWorkDays(dataMap.get("workDays"));
standard.setRestDays(dataMap.get("restDays"));
standard.setHolidayDays(dataMap.get("holidayDays"));
standard.setFestival1(dataMap.get("festival1"));
standard.setFestival2(dataMap.get("festival2"));
standard.setFestival3(dataMap.get("festival3"));
standard.setFestival4(dataMap.get("festival4"));
standard.setIsDelete(0);
standardDao.save(standard);
}
}
}
@Override
public HSSFWorkbook exportInfos() {
String[] cellname={
"序号","年月份","月历天数","工作日","公休日","节假日","节一","节二","节三","节四"
};
HSSFWorkbook hwb = new HSSFWorkbook();
HSSFSheet sheet = hwb.createSheet("考勤标准信息");
HSSFRow row = sheet.createRow(0);
HSSFCell cell;
HSSFCellStyle stycle = hwb.createCellStyle();
stycle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
for (int i = 0; i < cellname.length; i++) {
cell = row.createCell(i);
cell.setCellValue(cellname[i]);
cell.setCellStyle(stycle);
sheet.setColumnWidth((short) i, cellname[i].getBytes().length * 600);
}
//查询班制名称信息
List<Map<String, String>> list = standardDao.getAllInfoList();
if (list != null) {
for (int i = 0; i < list.size(); i++) {
Map<String, String> info = list.get(i);
row = sheet.createRow(i + 1);
row.createCell(0).setCellValue(i+1+"");
row.createCell(1).setCellValue(info.get("yearCalendar"));
row.createCell(2).setCellValue(info.get("monthDays"));
row.createCell(3).setCellValue(info.get("workDays"));
row.createCell(4).setCellValue(info.get("restDays"));
if(info.get("holidayDays") != null && !"null".equals(info.get("holidayDays"))){
row.createCell(5).setCellValue(info.get("holidayDays"));
}
if(info.get("festival1") != null && !"null".equals(info.get("festival1"))){
row.createCell(6).setCellValue(info.get("festival1"));
}
if(info.get("festival2") != null && !"null".equals(info.get("festival2"))){
row.createCell(7).setCellValue(info.get("festival2"));
}
if(info.get("festival3") != null && !"null".equals(info.get("festival3"))){
row.createCell(8).setCellValue(info.get("festival3"));
}
if(info.get("festival4") != null && !"null".equals(info.get("festival4"))){
row.createCell(9).setCellValue(info.get("festival4"));
}
}
}
return hwb;
}
}
| true |
81cfbb044c48c6896bab4ccb98cd6b0243a7ed8b | Java | xiajunt/projectPariSport | /src/projetPariSport/saxHandler/TeamHandler.java | UTF-8 | 1,355 | 2.421875 | 2 | [] | no_license | package projetPariSport.saxHandler;
import java.util.LinkedList;
import java.util.List;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import projetPariSport.structObject.Team;
/**
* TeamHandler - Determines the logic to parse the data Team
*
* @version 1.0
*
* @author Rodier Madiande
* @date 25/12/2013
*
*/
public class TeamHandler extends DefaultHandler {
private List<Team> teams;
private Team team;
public TeamHandler() {
teams = new LinkedList<Team>();
}
public void startElement(String uri, String localName,
String qName, Attributes attributes) throws SAXException{
if(qName.equals("team")){
team = new Team();
team.setAttributesValues(attributes, qName);
}else if(qName.equals("venue")){
team.setAttributesValues(attributes, qName);
}else if(qName.equals("league")){
team.setLeagueId(attributes.getValue("id"));
}else if(qName.equals("conference")){
team.setConferenceId(attributes.getValue("id"));
}else if(qName.equals("division")){
team.setDivisionId(attributes.getValue("id"));
}else{
/**/
}
}
public void endElement(String uri, String localName, String qName){
if(qName.equals("team")){
teams.add(team);
team = null;
}
else{
/*DO NOTHIN*/
}
}
public List<Team> getTeams()
{
return teams;
}
}
| true |
9adb10583ad517838c6c8d16ff21b4ef901a155e | Java | marcelofag/Aula-08-Angular-backend | /java/server/src-gen/main/java/br/com/senior/examples/helloworld/RetrieveItem.java | UTF-8 | 590 | 2.21875 | 2 | [] | no_license | /**
* This is a generated file. DO NOT EDIT ANY CODE HERE, YOUR CHANGES WILL BE LOST.
*/
package br.com.senior.examples.helloworld;
import br.com.senior.messaging.model.*;
import br.com.senior.examples.helloworld.Item;
import br.com.senior.examples.helloworld.Item.Id;
/**
* The 'retrieve' request primitive for the Item entity.
*/
@CommandDescription(name="retrieveItem", kind=CommandKind.Retrieve, requestPrimitive="retrieveItem", responsePrimitive="retrieveItemResponse")
public interface RetrieveItem extends MessageHandler {
public Item retrieveItem(Item.Id id);
}
| true |
b33cbd1f7023d767ccac19d7b356a19a8fef7584 | Java | jinshunjing/btcsegwit | /src/test/java/org/jim/bitcoin/segwit/transaction/SegwitTransactionHashTest.java | UTF-8 | 3,901 | 1.953125 | 2 | [
"Apache-2.0"
] | permissive | package org.jim.bitcoin.segwit.transaction;
import org.bitcoinj.core.Utils;
import org.bitcoinj.params.MainNetParams;
import org.bitcoinj.script.Script;
import org.bitcoinj.script.ScriptBuilder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
public class SegwitTransactionHashTest {
@Test
public void testValue() {
long v = 3800000L;
byte[] bytes = new byte[8];
Utils.uint32ToByteArrayLE(v, bytes, 0);
System.out.println(Utils.HEX.encode(bytes));
}
@Test
public void testTxid() {
String txid = "7b2c850111f011349d766c115f9b998ab62f3b74b5bf8c958c762814e8cce8e1";
txid = Utils.HEX.encode(Utils.reverseBytes(Utils.HEX.decode(txid)));
System.out.println(txid);
}
@Test
public void testNewTx() {
String txid = "7b2c850111f011349d766c115f9b998ab62f3b74b5bf8c958c762814e8cce8e1";
long vout = 0L;
String addr = "mrwFaerzWhX4W8g5gL2LrjHJzZYdxkw85D";
long value = 3800000L;
String rawTx = SegwitTransactionHash.newTx(txid, vout, addr, value);
System.out.println(rawTx);
// 0100000001e1e8cce81428768c958cbfb5743b2fb68a999b5f116c769d3411f01101852c7b0000000000ffffffff01c0fb3900000000001976a9147d41cbe740db118228932b9d6f4799b4803a4f5a88ac00000000
}
@Test
public void testInputSignature() {
String outpint = "e1e8cce81428768c958cbfb5743b2fb68a999b5f116c769d3411f01101852c7b00000000";
String amount = "404b4c0000000000";
String prevSequence = "ffffffff";
String outputs = "c0fb3900000000001976a9147d41cbe740db118228932b9d6f4799b4803a4f5a88ac";
String lockTime = "00000000";
String redeemScript = "001450507ef7413040b843344d32f74927fcb2fc74a8";
String prvKey = "L1e26WVtSgYxxXrSBKTZqeJN7d9Tna8r3LUhki6csStu5zCagE1R";
String txHash = SegwitTransactionHash.hashForP2SHP2WPKH(outpint, amount, prevSequence, redeemScript, outputs, lockTime);
String signature = SignTransactionService.signInputByWIF(txHash, prvKey);
System.out.println(signature);
// 30450221009d0ddf00d710d10f6a4992686ba95e12811f773927a556fad8910cbaa7e08c090220764ae31aac6f94d074f9f758857fbceb70eba4499e5a48684f263065dca59c9a01
}
@Test
public void testSignTx() {
String rawTx = "0100000001e1e8cce81428768c958cbfb5743b2fb68a999b5f116c769d3411f01101852c7b0000000000ffffffff01c0fb3900000000001976a9147d41cbe740db118228932b9d6f4799b4803a4f5a88ac00000000";
String pubKey = "0274f7bcdf9b6e2d3aa0cded33871f4e4a1956b1c3214b5c65dc7da61306d35d4e";
String redeemScript = "001450507ef7413040b843344d32f74927fcb2fc74a8";
String signature = "30450221009d0ddf00d710d10f6a4992686ba95e12811f773927a556fad8910cbaa7e08c090220764ae31aac6f94d074f9f758857fbceb70eba4499e5a48684f263065dca59c9a01";
// parse unsigned tx
SegwitTransaction transaction = new SegwitTransaction(MainNetParams.get(), Utils.HEX.decode(rawTx));
// add redeem script
Script inputScript = (new ScriptBuilder()).data(Utils.HEX.decode(redeemScript)).build();
transaction.getInput(0).setScriptSig(inputScript);
// add witness script
TransactionWitness txWitness = new TransactionWitness();
txWitness.addPush(Utils.HEX.decode(signature));
txWitness.addPush(Utils.HEX.decode(pubKey));
transaction.setWitness(0, txWitness);
// generate the signed tx
String signedRawTx = Utils.HEX.encode(transaction.bitcoinSerialize());
System.out.println(signedRawTx);
// 01000000000101e1e8cce81428768c958cbfb5743b2fb68a999b5f116c769d3411f01101852c7b000000001716001450507ef7413040b843344d32f74927fcb2fc74a8ffffffff01c0fb3900000000001976a9147d41cbe740db118228932b9d6f4799b4803a4f5a88ac024830450221009d0ddf00d710d10f6a4992686ba95e12811f773927a556fad8910cbaa7e08c090220764ae31aac6f94d074f9f758857fbceb70eba4499e5a48684f263065dca59c9a01210274f7bcdf9b6e2d3aa0cded33871f4e4a1956b1c3214b5c65dc7da61306d35d4e00000000
}
}
| true |
8ba0eb0e2bed46224f82d64e3113bbb1f2782a52 | Java | thiagolimacg/exemplos | /java/src/progjava/misc/Derivada1.java | UTF-8 | 139 | 2.171875 | 2 | [] | no_license | package progjava.misc;
class Derivada1 extends Base1 {
public void print() {
System.out.println("print called");
}
}
| true |
e4f4013a593077ec15a6b2c4c809c7560299ff3d | Java | vapporwashmade/apcs-2020 | /src/main/java/org/apoorv/ap/cs2020practice/Digits.java | UTF-8 | 594 | 3.515625 | 4 | [
"MIT"
] | permissive | package org.apoorv.ap.cs2020practice;
import java.util.ArrayList;
public class Digits {
private ArrayList<Integer> digitList;
public Digits(int num) {
// check precondition: num >= 0
this.digitList = new ArrayList<>();
while (num > 0) {
this.digitList.add(num % 10);
num /= 10;
}
}
public boolean isStrictlyIncreasing() {
for (int i = 1; i < digitList.size(); i++) {
if (digitList.get(i) > digitList.get(i - 1)) {
return false;
}
}
return true;
}
}
| true |
785b4eebf3cdb2d19a1a9b9d7691a847fd0db6d8 | Java | wujianwei121/framework | /framwork/src/main/java/com/example/framwork/utils/LoadDataLayoutUtils.java | UTF-8 | 2,948 | 2.03125 | 2 | [] | no_license | package com.example.framwork.utils;
import android.content.Context;
import android.support.v4.content.ContextCompat;
import android.view.View;
import com.example.framwork.R;
import com.example.framwork.widget.LoadDataLayout;
/**
* Created by ${wjw} on 2016/4/15.
*/
public class LoadDataLayoutUtils {
private LoadDataLayout loadDataLayout;
private LoadDataLayout.OnReloadListener onReloadListener;
public LoadDataLayoutUtils(LoadDataLayout loadDataLayout, LoadDataLayout.OnReloadListener onReloadListener) {
this.loadDataLayout = loadDataLayout;
this.onReloadListener = onReloadListener;
if (onReloadListener != null) {
loadDataLayout.setOnReloadListener(onReloadListener);
}
}
/**
* 显示内容
*/
public void showContent() {
if (loadDataLayout != null) {
loadDataLayout.setStatus(LoadDataLayout.SUCCESS);
}
}
public void showLoading(String s) {
if (loadDataLayout != null) {
loadDataLayout.setLoadingText(s);
loadDataLayout.setStatus(LoadDataLayout.LOADING);
}
}
public void showNoWifiError(String error) {
if (loadDataLayout != null) {
loadDataLayout.setNoNetWorkText(error);
loadDataLayout.setReloadBtnText("");
loadDataLayout.setStatus(LoadDataLayout.NO_NETWORK);
}
}
public LoadDataLayout showEmpty(String error) {
if (loadDataLayout != null) {
loadDataLayout.setEmptyText(error);
loadDataLayout.setReloadBtnText("");
loadDataLayout.setStatus(LoadDataLayout.EMPTY);
}
return loadDataLayout;
}
public LoadDataLayout showEmpty(String error, int emptyRes) {
if (loadDataLayout != null) {
loadDataLayout.setEmptyText(error);
loadDataLayout.setReloadBtnText("");
loadDataLayout.setEmptyImage(emptyRes);
loadDataLayout.setStatus(LoadDataLayout.EMPTY);
}
return loadDataLayout;
}
public void showError(String error) {
if (loadDataLayout != null) {
loadDataLayout.setErrorBtnTextColor(R.color.gray_98);
loadDataLayout.setErrorBtnBg(R.color.transparent);
loadDataLayout.setErrorText(error);
loadDataLayout.setReloadBtnText("点击重试");
loadDataLayout.setStatus(LoadDataLayout.ERROR);
}
}
public void showNoLogin(String error, int btnTxtColor, int btnBg) {
if (loadDataLayout != null) {
loadDataLayout.setErrorText(error);
loadDataLayout.setErrorBtnTextColor(btnTxtColor);
loadDataLayout.setReloadBtnText("登录");
loadDataLayout.setErrorBtnBg(btnBg);
loadDataLayout.setStatus(LoadDataLayout.NO_Login);
}
}
public LoadDataLayout getLoadDataLayout() {
return loadDataLayout;
}
}
| true |
9d80bbda00a1f60ec931c90afaff9611519d61e9 | Java | AnthonyLaye/TileO | /src/ca/mcgill/ecse223/tileo/controller/TileOController.java | UTF-8 | 35,928 | 2.109375 | 2 | [] | no_license | /*PLEASE DO NOT EDIT THIS CODE*/
/*This code was generated using the UMPLE 1.25.0-9e8af9e modeling language!*/
package ca.mcgill.ecse223.tileo.controller;
import ca.mcgill.ecse223.tileo.application.TileOApplication;
import ca.mcgill.ecse223.tileo.exception.InvalidInputException;
import ca.mcgill.ecse223.tileo.model.TileO;
import ca.mcgill.ecse223.tileo.model.Game;
import ca.mcgill.ecse223.tileo.model.Deck;
import ca.mcgill.ecse223.tileo.model.Tile;
import ca.mcgill.ecse223.tileo.model.WinTile;
import ca.mcgill.ecse223.tileo.model.ActionTile;
import ca.mcgill.ecse223.tileo.model.NormalTile;
import ca.mcgill.ecse223.tileo.model.Player;
import ca.mcgill.ecse223.tileo.model.Connection;
import ca.mcgill.ecse223.tileo.model.ActionCard;
import ca.mcgill.ecse223.tileo.model.ConnectTilesActionCard;
import ca.mcgill.ecse223.tileo.model.LoseTurnActionCard;
import ca.mcgill.ecse223.tileo.model.RemoveConnectionActionCard;
import ca.mcgill.ecse223.tileo.model.RollDieActionCard;
import ca.mcgill.ecse223.tileo.model.TeleportActionCard;
import ca.mcgill.ecse223.tileo.model.RemoveRandomTileActionCard;
import ca.mcgill.ecse223.tileo.model.RevealTileActionCard;
import ca.mcgill.ecse223.tileo.model.SendBackToStartActionCard;
import ca.mcgill.ecse223.tileo.model.SwapPositionActionCard;
import ca.mcgill.ecse223.tileo.model.WinTileHintActionCard;
import java.util.ArrayList;
import java.util.List;
// line 3 "../../../../../TileOControllerStates.ump"
public class TileOController
{
//------------------------
// MEMBER VARIABLES
//------------------------
//TileOController Attributes
private Tile currentTile;
private ArrayList<Tile> possibleTiles;
//TileOController State Machines
public enum ControllerState { Design, Game }
public enum ControllerStateGame { Null, StartOfTurn, WaitForTile, WaitForLanding, GameWon, LandedAction }
private ControllerState controllerState;
private ControllerStateGame controllerStateGame;
//------------------------
// CONSTRUCTOR
//------------------------
public TileOController()
{
setControllerStateGame(ControllerStateGame.Null);
setControllerState(ControllerState.Design);
}
//------------------------
// INTERFACE
//------------------------
public boolean setCurrentTile(Tile aCurrentTile)
{
boolean wasSet = false;
currentTile = aCurrentTile;
wasSet = true;
return wasSet;
}
public boolean setPossibleTiles(ArrayList<Tile> aPossibleTiles)
{
boolean wasSet = false;
possibleTiles = aPossibleTiles;
wasSet = true;
return wasSet;
}
public Tile getCurrentTile()
{
return currentTile;
}
public ArrayList<Tile> getPossibleTiles()
{
return possibleTiles;
}
public String getControllerStateFullName()
{
String answer = controllerState.toString();
if (controllerStateGame != ControllerStateGame.Null) { answer += "." + controllerStateGame.toString(); }
return answer;
}
public ControllerState getControllerState()
{
return controllerState;
}
public ControllerStateGame getControllerStateGame()
{
return controllerStateGame;
}
public boolean startGame(Game game) throws InvalidInputException
{
boolean wasEventProcessed = false;
ControllerState aControllerState = controllerState;
switch (aControllerState)
{
case Design:
// line 37 "../../../../../TileOControllerStates.ump"
doStartGame(game);
setControllerState(ControllerState.Game);
wasEventProcessed = true;
break;
default:
// Other states do respond to this event
}
return wasEventProcessed;
}
private boolean enterGame()
{
boolean wasEventProcessed = false;
ControllerStateGame aControllerStateGame = controllerStateGame;
switch (aControllerStateGame)
{
case Null:
setControllerStateGame(ControllerStateGame.StartOfTurn);
wasEventProcessed = true;
break;
default:
// Other states do respond to this event
}
return wasEventProcessed;
}
private boolean exitGame()
{
boolean wasEventProcessed = false;
ControllerStateGame aControllerStateGame = controllerStateGame;
switch (aControllerStateGame)
{
case StartOfTurn:
setControllerStateGame(ControllerStateGame.Null);
wasEventProcessed = true;
break;
case WaitForTile:
setControllerStateGame(ControllerStateGame.Null);
wasEventProcessed = true;
break;
case WaitForLanding:
setControllerStateGame(ControllerStateGame.Null);
wasEventProcessed = true;
break;
case GameWon:
setControllerStateGame(ControllerStateGame.Null);
wasEventProcessed = true;
break;
case LandedAction:
setControllerStateGame(ControllerStateGame.Null);
wasEventProcessed = true;
break;
default:
// Other states do respond to this event
}
return wasEventProcessed;
}
public boolean rollDie()
{
boolean wasEventProcessed = false;
ControllerStateGame aControllerStateGame = controllerStateGame;
switch (aControllerStateGame)
{
case StartOfTurn:
// line 44 "../../../../../TileOControllerStates.ump"
doRollDie();
setControllerStateGame(ControllerStateGame.WaitForTile);
wasEventProcessed = true;
break;
default:
// Other states do respond to this event
}
return wasEventProcessed;
}
public boolean selectNewTile(Tile aTile) throws InvalidInputException
{
boolean wasEventProcessed = false;
ControllerStateGame aControllerStateGame = controllerStateGame;
switch (aControllerStateGame)
{
case WaitForTile:
// line 50 "../../../../../TileOControllerStates.ump"
doSelectNewTile(aTile);
setControllerStateGame(ControllerStateGame.WaitForLanding);
wasEventProcessed = true;
break;
default:
// Other states do respond to this event
}
return wasEventProcessed;
}
public boolean playChooseAdditionalMoveActionCard(int n)
{
boolean wasEventProcessed = false;
ControllerStateGame aControllerStateGame = controllerStateGame;
switch (aControllerStateGame)
{
case WaitForTile:
if (verifyGameMode(Game.Mode.GAME_CHOOSEADDITIONALMOVEACTIONCARD))
{
// line 53 "../../../../../TileOControllerStates.ump"
doPlayChooseAdditionalMoveActionCard(n);
setControllerStateGame(ControllerStateGame.WaitForTile);
wasEventProcessed = true;
break;
}
break;
case LandedAction:
if (verifyGameMode(Game.Mode.GAME_CHOOSEADDITIONALMOVEACTIONCARD))
{
// line 89 "../../../../../TileOControllerStates.ump"
doPlayChooseAdditionalMoveActionCard(n);
TileOApplication.getTileO().getCurrentGame().setNextCard();
setControllerStateGame(ControllerStateGame.WaitForTile);
wasEventProcessed = true;
break;
}
break;
default:
// Other states do respond to this event
}
return wasEventProcessed;
}
public boolean land() throws InvalidInputException
{
boolean wasEventProcessed = false;
ControllerStateGame aControllerStateGame = controllerStateGame;
switch (aControllerStateGame)
{
case WaitForLanding:
if (tileIsNormal())
{
// line 59 "../../../../../TileOControllerStates.ump"
doLand(currentTile);
setControllerStateGame(ControllerStateGame.StartOfTurn);
wasEventProcessed = true;
break;
}
if (tileIsWin())
{
// line 60 "../../../../../TileOControllerStates.ump"
doLand(currentTile);
setControllerStateGame(ControllerStateGame.GameWon);
wasEventProcessed = true;
break;
}
if (tileIsAction())
{
// line 61 "../../../../../TileOControllerStates.ump"
doLand(currentTile);
setControllerStateGame(ControllerStateGame.LandedAction);
wasEventProcessed = true;
break;
}
break;
default:
// Other states do respond to this event
}
return wasEventProcessed;
}
public boolean playRollDieActionCard() throws InvalidInputException
{
boolean wasEventProcessed = false;
ControllerStateGame aControllerStateGame = controllerStateGame;
switch (aControllerStateGame)
{
case LandedAction:
if (verifyGameMode(Game.Mode.GAME_ROLLDIEACTIONCARD))
{
// line 68 "../../../../../TileOControllerStates.ump"
doPlayRollDieActionCard();
setControllerStateGame(ControllerStateGame.WaitForTile);
wasEventProcessed = true;
break;
}
break;
default:
// Other states do respond to this event
}
return wasEventProcessed;
}
public boolean playConnectTilesActionCard(Tile t1,Tile t2) throws InvalidInputException
{
boolean wasEventProcessed = false;
ControllerStateGame aControllerStateGame = controllerStateGame;
switch (aControllerStateGame)
{
case LandedAction:
if (verifyGameMode(Game.Mode.GAME_CONNECTTILESACTIONCARD))
{
// line 71 "../../../../../TileOControllerStates.ump"
doPlayConnectTilesActionCard(t1, t2);
setControllerStateGame(ControllerStateGame.StartOfTurn);
wasEventProcessed = true;
break;
}
break;
default:
// Other states do respond to this event
}
return wasEventProcessed;
}
public boolean playRemoveConnectionActionCard(Tile t1,Tile t2) throws InvalidInputException
{
boolean wasEventProcessed = false;
ControllerStateGame aControllerStateGame = controllerStateGame;
switch (aControllerStateGame)
{
case LandedAction:
if (verifyGameMode(Game.Mode.GAME_REMOVECONNECTIONACTIONCARD))
{
// line 74 "../../../../../TileOControllerStates.ump"
doPlayRemoveConnectionActionCard(t1, t2);
setControllerStateGame(ControllerStateGame.StartOfTurn);
wasEventProcessed = true;
break;
}
break;
default:
// Other states do respond to this event
}
return wasEventProcessed;
}
public boolean playTeleportActionCard(Tile t) throws InvalidInputException
{
boolean wasEventProcessed = false;
ControllerStateGame aControllerStateGame = controllerStateGame;
switch (aControllerStateGame)
{
case LandedAction:
if (verifyGameMode(Game.Mode.GAME_TELEPORTACTIONCARD))
{
// line 77 "../../../../../TileOControllerStates.ump"
doPlayTeleportActionCard(t);
setControllerStateGame(ControllerStateGame.WaitForLanding);
wasEventProcessed = true;
break;
}
break;
default:
// Other states do respond to this event
}
return wasEventProcessed;
}
public boolean playLoseTurnActionCard() throws InvalidInputException
{
boolean wasEventProcessed = false;
ControllerStateGame aControllerStateGame = controllerStateGame;
switch (aControllerStateGame)
{
case LandedAction:
if (verifyGameMode(Game.Mode.GAME_LOSETURNACTIONCARD))
{
// line 80 "../../../../../TileOControllerStates.ump"
doPlayLoseTurnActionCard();
setControllerStateGame(ControllerStateGame.StartOfTurn);
wasEventProcessed = true;
break;
}
break;
default:
// Other states do respond to this event
}
return wasEventProcessed;
}
public boolean playRemoveRandomTileActionCard(Game game)
{
boolean wasEventProcessed = false;
ControllerStateGame aControllerStateGame = controllerStateGame;
switch (aControllerStateGame)
{
case LandedAction:
if (verifyGameMode(Game.Mode.GAME_REMOVERANDOMTILEACTIONCARD))
{
// line 83 "../../../../../TileOControllerStates.ump"
doPlayRemoveRandomTileActionCard(game);
setControllerStateGame(ControllerStateGame.StartOfTurn);
wasEventProcessed = true;
break;
}
break;
default:
// Other states do respond to this event
}
return wasEventProcessed;
}
public boolean playTurnInactiveActionCard(Game currentGame)
{
boolean wasEventProcessed = false;
ControllerStateGame aControllerStateGame = controllerStateGame;
switch (aControllerStateGame)
{
case LandedAction:
if (verifyGameMode(Game.Mode.GAME_TURNINACTIVEACTIONCARD))
{
// line 86 "../../../../../TileOControllerStates.ump"
doPlayTurnInactiveActionCard(currentGame);
setControllerStateGame(ControllerStateGame.StartOfTurn);
wasEventProcessed = true;
break;
}
break;
default:
// Other states do respond to this event
}
return wasEventProcessed;
}
public boolean playRevealTileActionCard()
{
boolean wasEventProcessed = false;
ControllerStateGame aControllerStateGame = controllerStateGame;
switch (aControllerStateGame)
{
case LandedAction:
if (verifyGameMode(Game.Mode.GAME_REVEALTILEACTIONCARD))
{
// line 93 "../../../../../TileOControllerStates.ump"
doPlayRevealTileActionCard();
setControllerStateGame(ControllerStateGame.StartOfTurn);
wasEventProcessed = true;
break;
}
break;
default:
// Other states do respond to this event
}
return wasEventProcessed;
}
public boolean playSendBackToStartActionCard(Tile t) throws InvalidInputException
{
boolean wasEventProcessed = false;
ControllerStateGame aControllerStateGame = controllerStateGame;
switch (aControllerStateGame)
{
case LandedAction:
if (verifyGameMode(Game.Mode.GAME_SENDBACKTOSTARTACTIONCARD))
{
// line 97 "../../../../../TileOControllerStates.ump"
doPlaySendBackToStartActionCard(t);
setControllerStateGame(ControllerStateGame.StartOfTurn);
wasEventProcessed = true;
break;
}
break;
default:
// Other states do respond to this event
}
return wasEventProcessed;
}
public boolean playSwapPositionActionCard(Tile t) throws InvalidInputException
{
boolean wasEventProcessed = false;
ControllerStateGame aControllerStateGame = controllerStateGame;
switch (aControllerStateGame)
{
case LandedAction:
if (verifyGameMode(Game.Mode.GAME_SWAPPOSITIONACTIONCARD))
{
// line 101 "../../../../../TileOControllerStates.ump"
doPlaySwapPositionActionCard(t);
setControllerStateGame(ControllerStateGame.StartOfTurn);
wasEventProcessed = true;
break;
}
break;
default:
// Other states do respond to this event
}
return wasEventProcessed;
}
public boolean playWinTileHintActionCard()
{
boolean wasEventProcessed = false;
ControllerStateGame aControllerStateGame = controllerStateGame;
switch (aControllerStateGame)
{
case LandedAction:
if (verifyGameMode(Game.Mode.GAME_WINTILEHINTACTIONCARD))
{
// line 105 "../../../../../TileOControllerStates.ump"
doPlayWinTileHintActionCard();
setControllerStateGame(ControllerStateGame.StartOfTurn);
wasEventProcessed = true;
break;
}
break;
default:
// Other states do respond to this event
}
return wasEventProcessed;
}
private void exitControllerState()
{
switch(controllerState)
{
case Game:
exitGame();
break;
}
}
private void setControllerState(ControllerState aControllerState)
{
controllerState = aControllerState;
// entry actions and do activities
switch(controllerState)
{
case Game:
if (controllerStateGame == ControllerStateGame.Null) { setControllerStateGame(ControllerStateGame.StartOfTurn); }
break;
}
}
private void setControllerStateGame(ControllerStateGame aControllerStateGame)
{
controllerStateGame = aControllerStateGame;
if (controllerState != ControllerState.Game && aControllerStateGame != ControllerStateGame.Null) { setControllerState(ControllerState.Game); }
}
public void delete()
{}
/**
* guard
*/
// line 115 "../../../../../TileOControllerStates.ump"
private boolean verifyGameMode(Game.Mode aMode){
return TileOApplication.getTileO().getCurrentGame().getMode()==aMode;
}
// line 118 "../../../../../TileOControllerStates.ump"
private boolean tileIsNormal(){
return currentTile instanceof NormalTile || (currentTile instanceof ActionTile && ((ActionTile)currentTile).getInactivityStatus()==ActionTile.InactivityStatus.Inactive);
}
// line 121 "../../../../../TileOControllerStates.ump"
private boolean tileIsWin(){
return currentTile instanceof WinTile;
}
// line 124 "../../../../../TileOControllerStates.ump"
private boolean tileIsAction(){
return currentTile instanceof ActionTile && ((ActionTile)currentTile).getInactivityStatus() == ActionTile.InactivityStatus.Active;
}
/**
* Design
*/
// line 130 "../../../../../TileOControllerStates.ump"
public Game newGame(int nPlayer) throws InvalidInputException{
if (nPlayer < Game.minimumNumberOfPlayers())
throw new InvalidInputException("Not enough players");
if (nPlayer > Game.maximumNumberOfPlayers())
throw new InvalidInputException("Too many players");
TileO tileo = TileOApplication.getTileO();
Game game = new Game(0);
tileo.addGame(game);
int n = 0;
while (n < nPlayer){
Player p = new Player(n, game);
p.setColorByNumber();
n++;
}
game.setMode(Game.Mode.DESIGN);
setControllerState(ControllerState.Design);
setControllerStateGame(ControllerStateGame.Null);
tileo.setCurrentGame(game);
return game;
}
// line 154 "../../../../../TileOControllerStates.ump"
public void addRegularTile(int x, int y, Game game){
TileO tileO = TileOApplication.getTileO();
try{
tileO.addNormalTile(x, y, game);
}catch (RuntimeException e){
System.out.print("Error");
}
}
// line 166 "../../../../../TileOControllerStates.ump"
public void addActionTile(int x, int y, Game game, int inactivityPeriod){
TileO tileO = TileOApplication.getTileO();
try{
tileO.addActionTile(x, y, game, inactivityPeriod);
}catch (RuntimeException e){
System.out.print("Error");
}
}
// line 178 "../../../../../TileOControllerStates.ump"
public void addHiddenTile(int x, int y, Game game){
try{
WinTile wt = new WinTile(x, y, game);
game.setWinTile(wt);
}catch (RuntimeException e){
System.out.print("Error");
}
}
// line 190 "../../../../../TileOControllerStates.ump"
public void removeTile(Tile tile, Game game){
TileO tileO = TileOApplication.getTileO();
if (tile instanceof WinTile)
tileO.getCurrentGame().setWinTile(null);
tileO.removeTile(tile);
}
// line 197 "../../../../../TileOControllerStates.ump"
public void addConnection(Tile t1, Tile t2, Game game) throws InvalidInputException{
if (t1.isConnectedWith(t2))
throw new InvalidInputException("Tiles are already connected");
if (!game.connectTiles(t1, t2))
throw new InvalidInputException("Selected tiles are not adjacent");
}
// line 204 "../../../../../TileOControllerStates.ump"
public void removeConnection(Tile t1, Tile t2, Game game) throws InvalidInputException{
if (!game.disconnectTiles(t1, t2))
throw new InvalidInputException("These tiles are not connected");
}
// line 209 "../../../../../TileOControllerStates.ump"
public void setStartingTile(int nPlayer, Tile t, Game game) throws InvalidInputException{
if (t!=null && t!=game.getWinTile()) {
Player p = game.getPlayer(nPlayer);
p.setStartingTile(t);
}
else
throw new InvalidInputException("Invalid tile");
}
// line 218 "../../../../../TileOControllerStates.ump"
public void updateCards(int numberOfCards, int cardType) throws InvalidInputException{
Game game = TileOApplication.getTileO().getCurrentGame();
Deck deck = game.getDeck();
int toAdd = numberOfCards - deck.numberOfCardsForType(cardType);
if (toAdd>0) deck.addCards (toAdd, cardType);
else if (toAdd<0) deck.rmCards(toAdd*-1, cardType);
}
/**
* Game
*/
// line 230 "../../../../../TileOControllerStates.ump"
private void cloneGame(Game game){
TileO tileo = TileOApplication.getTileO();
if (game.getMode() == Game.Mode.DESIGN) { // when you start a game
if (game.getFilename() == null || game.getFilename() == "") return; // if you never saved this design dont clone it
Game cloned = game.clone();
tileo.addGame(cloned);
tileo.setCurrentGame(cloned);
saveGame(""); // will use the current name for the design
game.setFilename(null); // make sure it's saved under a new name
tileo.setCurrentGame(game);
}
}
// line 243 "../../../../../TileOControllerStates.ump"
private void doStartGame(Game selectedGame) throws InvalidInputException{
/* Starts the selected game if it respects the rules */
String error = "";
Deck deck = selectedGame.getDeck();
if (deck.numberOfCards() != Game.NumberOfActionCards)
error+= "The deck needs to have "+Game.NumberOfActionCards+" cards ";
if (selectedGame.getWinTile() == null)
error+="There is no WinTile selected ";
if (selectedGame.numberOfPlayers() < selectedGame.minimumNumberOfPlayers())
error+="Needs minimum two players ";
if (selectedGame.numberOfPlayers() > selectedGame.maximumNumberOfPlayers())
error+="Too many players ";
for (Player aPlayer : selectedGame.getPlayers())
if (aPlayer.getStartingTile()==null)
error+="Missing starting tile for player "+aPlayer.getNumber()+" ";
if (!error.equals(""))
throw new InvalidInputException(error.trim());
cloneGame(selectedGame);
deck.shuffle();
deck.setCurrentCard(deck.getCard(0));
for (Tile aTile : selectedGame.getTiles()) aTile.setHasBeenVisited(false);
for (Player aPlayer : selectedGame.getPlayers()) {
aPlayer.setCurrentTile(aPlayer.getStartingTile());
aPlayer.getCurrentTile().setHasBeenVisited(true);
}
selectedGame.setCurrentPlayer(selectedGame.getPlayers().get(0));
selectedGame.setCurrentConnectionPieces(Game.SpareConnectionPieces);
selectedGame.setMode(Game.Mode.GAME);
}
// line 277 "../../../../../TileOControllerStates.ump"
private void doRollDie(){
Game game = TileOApplication.getTileO().getCurrentGame();
setPossibleTiles(game.rollDie());
}
// line 282 "../../../../../TileOControllerStates.ump"
private void doSelectNewTile(Tile aTile) throws InvalidInputException{
if (getPossibleTiles().contains(aTile) || getPossibleTiles().size()==0)
setCurrentTile(aTile);
else
throw new InvalidInputException("Invalid tile");
}
// line 289 "../../../../../TileOControllerStates.ump"
private void doLand(Tile tile) throws InvalidInputException{
/* Initiates when a player lands on a tile */
tile.land();
setPossibleTiles(null);
setCurrentTile(null);
}
// line 297 "../../../../../TileOControllerStates.ump"
private void doPlayRollDieActionCard() throws InvalidInputException{
Game currentGame= TileOApplication.getTileO().getCurrentGame();
ArrayList<Tile> availableTiles=null;
currentGame.setMode(Game.Mode.GAME_ROLLDIEACTIONCARD);
Deck currentDeck= currentGame.getDeck();
Player currentPlayer= currentGame.getCurrentPlayer();
ActionCard currentCard = currentDeck.getCurrentCard();
if(currentCard instanceof RollDieActionCard){
RollDieActionCard playCard = (RollDieActionCard) currentCard;
availableTiles= playCard.play();
}
currentGame.setNextCard();
currentGame.setMode(Game.Mode.GAME);
setPossibleTiles(availableTiles);
}
// line 315 "../../../../../TileOControllerStates.ump"
private void doPlayConnectTilesActionCard(Tile t1, Tile t2) throws InvalidInputException{
Game currentGame = TileOApplication.getTileO().getCurrentGame();
currentGame.setMode(Game.Mode.GAME_CONNECTTILESACTIONCARD);
Player currentPlayer= currentGame.getCurrentPlayer();
Deck currentDeck = currentGame.getDeck();
ActionCard currentCard= currentDeck.getCurrentCard();
if (t1.isConnectedWith(t2))
throw new InvalidInputException("Tiles are already connected");
boolean wasConnected = false;
if(currentGame.getCurrentConnectionPieces() <= 0)
wasConnected = true;
else if(currentCard instanceof ConnectTilesActionCard){
ConnectTilesActionCard playCard = (ConnectTilesActionCard) currentCard;
wasConnected =playCard.play(t1, t2);
}
if(wasConnected){
currentGame.setNextPlayer();
currentGame.setNextCard();
currentGame.setMode(Game.Mode.GAME);
if(!(currentGame.getCurrentConnectionPieces() == 0))
currentGame.setCurrentConnectionPieces(currentGame.getCurrentConnectionPieces() - 1);
else
currentGame.setCurrentConnectionPieces(0);
}
else{
throw new InvalidInputException("Tiles not adjacent, choose another tile");
}
}
// line 346 "../../../../../TileOControllerStates.ump"
private void doPlayRemoveConnectionActionCard(Tile t1, Tile t2) throws InvalidInputException{
Game currentGame = TileOApplication.getTileO().getCurrentGame();
currentGame.setMode(Game.Mode.GAME_REMOVECONNECTIONACTIONCARD);
Player currentPlayer=currentGame.getCurrentPlayer();
Deck currentDeck = currentGame.getDeck();
ActionCard currentCard= currentDeck.getCurrentCard();
boolean wasRemoved = false;
if(currentCard instanceof RemoveConnectionActionCard){
RemoveConnectionActionCard playCard = (RemoveConnectionActionCard) currentCard;
wasRemoved= playCard.play(t1, t2);
}
if(wasRemoved){
currentGame.setNextPlayer();
currentGame.setNextCard();
currentGame.setMode(Game.Mode.GAME);
}
else{
throw new InvalidInputException("No connection between tiles");
}
}
// line 369 "../../../../../TileOControllerStates.ump"
private void doPlayTeleportActionCard(Tile t) throws InvalidInputException{
Game currentGame = TileOApplication.getTileO().getCurrentGame();
currentGame.setMode(Game.Mode.GAME_TELEPORTACTIONCARD);
Deck currentDeck = currentGame.getDeck();
ActionCard currentCard= currentDeck.getCurrentCard();
if (currentCard instanceof TeleportActionCard){
TeleportActionCard playCard = (TeleportActionCard) currentCard;
setCurrentTile(t);
}
currentGame.setNextCard();
currentGame.setMode(Game.Mode.GAME);
}
// line 384 "../../../../../TileOControllerStates.ump"
private void doPlayLoseTurnActionCard() throws InvalidInputException{
Game currentGame = TileOApplication.getTileO().getCurrentGame();
Deck d = currentGame.getDeck();
ActionCard c = d.getCurrentCard();
if (!(c instanceof LoseTurnActionCard))
throw new InvalidInputException("Invalid card");
((LoseTurnActionCard) c).play();
currentGame.setNextCard();
currentGame.setNextPlayer();
currentGame.setMode(Game.Mode.GAME);
}
// line 397 "../../../../../TileOControllerStates.ump"
private void doPlayRemoveRandomTileActionCard(Game game){
Deck deck = game.getDeck();
ActionCard currentCard = deck.getCurrentCard();
if (currentCard instanceof RemoveRandomTileActionCard) {
((RemoveRandomTileActionCard) currentCard).play();
}
game.setNextPlayer();
game.setNextCard();
game.setMode(Game.Mode.GAME);
}
// line 410 "../../../../../TileOControllerStates.ump"
private boolean doPlayTurnInactiveActionCard(Game currentGame){
List<Tile> allTiles = currentGame.getTiles();
boolean success = false;
for(int i = 0; i< allTiles.size(); i++){
Tile aTile = allTiles.get(i);
if (aTile instanceof ActionTile){
ActionTile aActionTile = (ActionTile) aTile;
success = aActionTile.deactivate();
}
}
currentGame.setNextPlayer();
currentGame.setNextCard();
currentGame.setMode(Game.Mode.GAME);
return success;
}
// line 428 "../../../../../TileOControllerStates.ump"
private void doPlayChooseAdditionalMoveActionCard(int n){
Game game = TileOApplication.getTileO().getCurrentGame();
setPossibleTiles(game.getCurrentPlayer().getPossibleMoves(n));
}
// line 433 "../../../../../TileOControllerStates.ump"
private void doPlayRevealTileActionCard(){
Game game = TileOApplication.getTileO().getCurrentGame();
game.setNextPlayer();
game.setNextCard();
game.setMode(Game.Mode.GAME);
}
// line 440 "../../../../../TileOControllerStates.ump"
public String revealTile(Tile t){
Game game = TileOApplication.getTileO().getCurrentGame();
ActionCard c = game.getDeck().getCurrentCard();
if (c instanceof RevealTileActionCard) {
return ((RevealTileActionCard)c).play(t);
}
return "";
}
// line 449 "../../../../../TileOControllerStates.ump"
private void doPlaySendBackToStartActionCard(Tile t) throws InvalidInputException{
Game currentGame = TileOApplication.getTileO().getCurrentGame();
Player currentPlayer = currentGame.getCurrentPlayer();
if(currentPlayer.getCurrentTile()==t) throw new InvalidInputException ("Can't choose self");
ArrayList<Player> otherPlayers= new ArrayList<Player>();
for(Player p:currentGame.getPlayers()){
if(p!=currentPlayer) otherPlayers.add(p);
}
currentGame.setMode(Game.Mode.GAME_SENDBACKTOSTARTACTIONCARD);
Deck gameDeck = currentGame.getDeck();
ActionCard currentCard= gameDeck.getCurrentCard();
boolean wasSentBack= false;
if(currentCard instanceof SendBackToStartActionCard){
SendBackToStartActionCard playCard = (SendBackToStartActionCard)currentCard;
wasSentBack = playCard.play(t,otherPlayers);
}
if(wasSentBack){
currentGame.setNextPlayer();
currentGame.setNextCard();
currentGame.setMode(Game.Mode.GAME);
}
else{
throw new InvalidInputException("Choose a player");
}
}
// line 475 "../../../../../TileOControllerStates.ump"
private void doPlaySwapPositionActionCard(Tile t) throws InvalidInputException{
Game currentGame = TileOApplication.getTileO().getCurrentGame();
Player currentPlayer = currentGame.getCurrentPlayer();
if(currentPlayer.getCurrentTile()==t) throw new InvalidInputException("Can't choose self");
ArrayList<Player> otherPlayers= new ArrayList<Player>();
for(Player p:currentGame.getPlayers()){
if(p!=currentPlayer) otherPlayers.add(p);
}
currentGame.setMode(Game.Mode.GAME_SWAPPOSITIONACTIONCARD);
Deck gameDeck = currentGame.getDeck();
ActionCard currentCard= gameDeck.getCurrentCard();
boolean wasSwapped= false;
if(currentCard instanceof SwapPositionActionCard){
SwapPositionActionCard playCard = (SwapPositionActionCard) currentCard;
wasSwapped = playCard.play(t,otherPlayers, currentPlayer);
}
if(wasSwapped){
currentGame.setNextPlayer();
currentGame.setNextCard();
currentGame.setMode(Game.Mode.GAME);
}
else{
throw new InvalidInputException("Choose a player");
}
}
// line 501 "../../../../../TileOControllerStates.ump"
public boolean winTileHint(Tile t) throws InvalidInputException{
Game game = t.getGame();
Deck deck = game.getDeck();
ActionCard card = deck.getCurrentCard();
if (!(card instanceof WinTileHintActionCard))
throw new InvalidInputException("Card does not match");
return ((WinTileHintActionCard)card).play(t);
}
// line 511 "../../../../../TileOControllerStates.ump"
private void doPlayWinTileHintActionCard(){
Game game = TileOApplication.getTileO().getCurrentGame();
game.setNextPlayer();
game.setNextCard();
game.setMode(Game.Mode.GAME);
}
// line 518 "../../../../../TileOControllerStates.ump"
public String saveGame(String filename){
TileOApplication.save(filename, false);
return TileOApplication.getTileO().getCurrentGame().getFilename();
}
// line 523 "../../../../../TileOControllerStates.ump"
public Game loadGame(String filename) throws InvalidInputException{
TileO tileo = TileOApplication.getTileO();
Game loadedGame = TileOApplication.load(filename);
if (loadedGame == null)
throw new InvalidInputException("The game you selected does not exists");
// removes the game if it exists
for (int i=0; i<tileo.getGames().size(); ++i){
if (loadedGame == tileo.getGame(i)){
tileo.removeGame(tileo.getGame(i));
break;
}
}
tileo.addGame(loadedGame);
tileo.setCurrentGame(loadedGame);
loadedGame.changeDie();
switch (loadedGame.getMode()) {
case DESIGN:
setControllerState(ControllerState.Design);
setControllerStateGame(ControllerStateGame.Null);
break;
case GAME_WON:
setControllerState(ControllerState.Game);
setControllerStateGame(ControllerStateGame.GameWon);
break;
case GAME:
setControllerState(ControllerState.Game);
setControllerStateGame(ControllerStateGame.StartOfTurn);
break;
case GAME_ROLLDIEACTIONCARD:
case GAME_CONNECTTILESACTIONCARD:
case GAME_REMOVECONNECTIONACTIONCARD:
case GAME_TELEPORTACTIONCARD:
case GAME_LOSETURNACTIONCARD:
case GAME_REMOVERANDOMTILEACTIONCARD:
case GAME_TURNINACTIVEACTIONCARD:
case GAME_REVEALTILEACTIONCARD:
case GAME_SENDBACKTOSTARTACTIONCARD:
case GAME_CHOOSEADDITIONALMOVEACTIONCARD:
case GAME_SWAPPOSITIONACTIONCARD:
case GAME_WINTILEHINTACTIONCARD:
setControllerState(ControllerState.Game);
setControllerStateGame(ControllerStateGame.LandedAction);
break;
}
return loadedGame;
}
public String toString()
{
String outputString = "";
return super.toString() + "["+ "]" + System.getProperties().getProperty("line.separator") +
" " + "currentTile" + "=" + (getCurrentTile() != null ? !getCurrentTile().equals(this) ? getCurrentTile().toString().replaceAll(" "," ") : "this" : "null") + System.getProperties().getProperty("line.separator") +
" " + "possibleTiles" + "=" + (getPossibleTiles() != null ? !getPossibleTiles().equals(this) ? getPossibleTiles().toString().replaceAll(" "," ") : "this" : "null")
+ outputString;
}
} | true |
86ad42fc4a316257e59795b644389eedca17d0ba | Java | kevingeorgex/MultiDimensionalSearch | /IO.java | UTF-8 | 641 | 3.546875 | 4 | [] | no_license | /** CS 4V95.001, 5V81.001. Java I/O example
@author rbk
*/
import java.util.*;
import java.io.*;
public class IO {
// If command line arg is found, it is assumed to be a file name.
// Otherwise read from stdin (console)
public static void main(String[] args) throws FileNotFoundException
{
Scanner in;
if (args.length > 0) {
File inputFile = new File(args[0]);
in = new Scanner(inputFile);
} else {
in = new Scanner(System.in);
}
int s = in.nextInt();
float t = in.nextFloat();
System.out.println("s: " + s + " t: " + t);
}
}
| true |
7eb3992870fface6dadb65de9563653616a04afc | Java | FoxsTail/qr_client | /app/src/main/java/com/lis/qr_client/activity/MainMenuActivity.java | UTF-8 | 8,748 | 1.859375 | 2 | [] | no_license | package com.lis.qr_client.activity;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.*;
import com.badoo.mobile.util.WeakHandler;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.lis.qr_client.R;
import com.lis.qr_client.application.QrApplication;
import com.lis.qr_client.constants.DbTables;
import com.lis.qr_client.constants.MyPreferences;
import com.lis.qr_client.extra.async_helpers.AsyncMultiDbManager;
import com.lis.qr_client.extra.dialog_fragment.ScanDialogFragment;
import com.lis.qr_client.extra.utility.ObjectUtility;
import com.lis.qr_client.extra.utility.PreferenceUtility;
import com.lis.qr_client.extra.utility.Utility;
import lombok.extern.java.Log;
import java.util.HashMap;
@Log
public class MainMenuActivity extends AppCompatActivity {
protected Toolbar toolbar;
private Button btnFormulyar, btnInventory, btnProfile, btnScanQR;
private ProgressBar pbInventory;
private final int REQUEST_SCAN_QR = 1;
protected HashMap<String, Object> scannedMap;
private WeakHandler dialogHandler;
private String url;
private Activity activity;
@Override
protected void onCreate(Bundle savedInstanceState) {
//----Full screen
Utility.fullScreen(this);
super.onCreate(savedInstanceState);
log.info("Main menu --- onCreate()");
setContentView(R.layout.activity_main_menu);
int id_user = PreferenceUtility.getIntegerDataFromPreferences(this, MyPreferences.PREFERENCE_ID_USER);
log.info(String.valueOf(id_user));
/*set toolbar icons and actions*/
ImageView img_info = findViewById(R.id.img_btn_info);
img_info.setOnClickListener(onClickListener);
ImageView img_log_out = findViewById(R.id.img_btn_log_out);
img_log_out.setOnClickListener(onClickListener);
//--------
url = "http://" + getString(R.string.emu_ip) + ":"
+ getString(R.string.port) + getString(R.string.api_addresses_load);
btnFormulyar = findViewById(R.id.btnFormulyar);
btnFormulyar.setOnClickListener(onClickListener);
btnInventory = findViewById(R.id.btnInventory);
btnInventory.setOnClickListener(onClickListener);
btnProfile = findViewById(R.id.btnProfile);
btnProfile.setOnClickListener(onClickListener);
btnScanQR = findViewById(R.id.btnScanQR);
btnScanQR.setOnClickListener(onClickListener);
pbInventory = findViewById(R.id.pbInventory);
dialogHandler = new WeakHandler(showDialogHandler);
}
Handler.Callback showDialogHandler = new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
ScanDialogFragment dialogFragment = new ScanDialogFragment();
Bundle bundle = new Bundle();
String scanned_msg = ObjectUtility.scannedMapToMsg(scannedMap);
log.info("Scanned msg: " + scanned_msg);
dialogFragment.callDialog(getSupportFragmentManager(), bundle, scanned_msg,
getString(R.string.result_title), R.drawable.ic_check_circle,"qr_scan");
return false;
}
};
//---------------------------//
View.OnClickListener onClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnFormulyar: {
Intent intent = new Intent(QrApplication.getInstance(), TestActivity.class);
startActivity(intent);
break;
}
case R.id.btnInventory: {
log.info("---Remove old saved data---");
/*clear old saved data*/
PreferenceUtility.removeOldPreferences(QrApplication.getInstance(), MyPreferences.PREFERENCE_FILE_NAME,
MyPreferences.ADDRESS_ID_PREFERENCES,
MyPreferences.ROOM_ID_PREFERENCES);
/*load all available strings from ext db, starts new Db*/
if (url != null) {
String table_name = DbTables.TABLE_ADDRESS;
log.info("url is " + url);
new AsyncMultiDbManager(QrApplication.getInstance(), table_name, null, url,
true, InventoryParamSelectActivity.class,
new int[]{Intent.FLAG_ACTIVITY_NEW_TASK}, null,
btnInventory, pbInventory, true).runAsyncLoader();
} else {
log.warning("---URL IS NULL!---");
}
break;
}
case R.id.btnProfile: {
Intent intent = new Intent(QrApplication.getInstance(), ProfileActivity.class);
startActivity(intent);
break;
}
/*call CameraActivity for scanning*/
case R.id.btnScanQR: {
Intent intent = new Intent(QrApplication.getInstance(), CameraActivity.class);
startActivityForResult(intent, REQUEST_SCAN_QR);
break;
}
case R.id.img_btn_info: {
log.info("Getting the information...");
ScanDialogFragment dialogFragment = new ScanDialogFragment();
dialogFragment.callDialog(getSupportFragmentManager(), new Bundle(),
getString(R.string.plain_info), getString(R.string.info), R.drawable.ic_info,
"info");
break;
}
case R.id.img_btn_log_out: {
log.info("Logging out...");
logout();
break;
}
}
}
};
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data == null) {
return;
}
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_SCAN_QR) {
final String scan_result = data.getStringExtra("scan_result");
/*
show alertDialog with scanned data
*/
new Thread(new Runnable() {
@Override
public void run() {
/*
converts gotten data from json to map
*/
scannedMap = ObjectUtility.scannedJsonToMap(scan_result);
dialogHandler.sendEmptyMessage(1);
}
}).start();
}
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(this, getString(R.string.mission_was_canceled), Toast.LENGTH_LONG).show();
}
}
//----------------------------------------//
@Override
public void onBackPressed() {
super.onBackPressed();
log.info("---MainMenu onBackPressed()---");
/*
finish();
*/
}
@Override
protected void onStop() {
log.info("---MainMenu -- onStop()---");
super.onStop();
dialogHandler.removeCallbacksAndMessages(null);
/*set null buttons and pb*/
btnScanQR = null;
btnProfile = null;
btnInventory = null;
btnFormulyar = null;
pbInventory = null;
/*other ref's*/
onClickListener = null;
showDialogHandler = null;
toolbar = null;
}
@Override
protected void onDestroy() {
super.onDestroy();
log.info("---MainMenu -- onDestroy()---");
activity = null;
}
//---Methods----
public void logout() {
/*remove saved user's data*/
PreferenceUtility.removeLoginPreferences(QrApplication.getInstance(), MyPreferences.PREFERENCE_SAVE_USER,
MyPreferences.PREFERENCE_IS_USER_SAVED);
/*clear app's task and run login page*/
Intent intent = new Intent(QrApplication.getInstance(), LogInActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
}
}
| true |
58a06d91a09e815044eb82a6d42128219f914381 | Java | saktanorovich/coding | /gcj/src/kickstart2017/rounde/CopyPaste.java | UTF-8 | 2,152 | 2.859375 | 3 | [] | no_license | package kickstart2017.rounde;
import utils.io.*;
import java.io.*;
import java.util.*;
// Problem A
public class CopyPaste {
public void process(int testCase, InputReader in, PrintWriter out) {
this.s = in.next();
this.n = s.length();
this.e = new boolean[n][n][n];
for (int i = 0; i < n; ++i) {
for (int j = i + 1; j < n; ++j) {
e[i][j][1] = s.charAt(i) == s.charAt(j);
}
}
for (int k = 2; k < n; ++k) {
for (int i = 0; i + k <= n; ++i) {
for (int j = i + k; j + k <= n; ++j) {
if (e[i][j][k - 1]) {
e[i][j][k] = e[i + k - 1][j + k - 1][1];
}
}
}
}
this.f = new int[n][n][n + 1];
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
Arrays.fill(f[i][j], Integer.MAX_VALUE);
}
}
f[0][0][0] = 1;
for (int i = 0; i < n; ++i) {
int best = Integer.MAX_VALUE;
for (int j = 0; j <= i; ++j) {
for (int k = 0; j + k - 1 <= i; ++k) {
best = Math.min(best, f[i][j][k]);
}
}
if (i + 1 == n) {
out.format("Case #%d: %d\n", testCase, best);
return;
}
for (int j = 0; j <= i; ++j) {
for (int k = 1; j + k - 1 <= i; ++k) {
f[i][j][k] = Math.min(f[i][j][k], best + 1);
}
}
for (int j = 0; j <= i; ++j) {
for (int c = 0; j + c - 1 <= i; ++c) {
if (f[i][j][c] < Integer.MAX_VALUE) {
if (e[j][i + 1][c]) {
f[i + c][j][c] = Math.min(f[i + c][j][c], f[i][j][c] + 1);
}
f[i + 1][j][c] = Math.min(f[i + 1][j][c], f[i][j][c] + 1);
}
}
}
}
}
private String s;
private boolean e[][][];
private int f[][][];
private int n;
}
| true |
e317cb99dec8507069824ff9d293a99d67abbe48 | Java | shark-dynamics/shark-camera | /app/src/main/java/com/shark/dynamics/sharkcamera/EffectAdapter.java | UTF-8 | 854 | 2.171875 | 2 | [] | no_license | package com.shark.dynamics.sharkcamera;
import android.content.Context;
import android.graphics.Color;
import com.shark.dynamics.basic.rv.RViewAdapter;
import com.shark.dynamics.basic.rv.RViewHolder;
import java.util.List;
public class EffectAdapter extends RViewAdapter<EffectItem> {
public EffectAdapter(Context context, List<EffectItem> data) {
super(context, data);
}
@Override
public int getLayoutId() {
return R.layout.item_effect;
}
@Override
public void bindDataToView(RViewHolder holder, int position) {
EffectItem item = mData.get(position);
holder.setText(R.id.id_effect_name, item.name);
if (item.selected) {
holder.itemView.setBackgroundColor(Color.GRAY);
} else {
holder.itemView.setBackgroundColor(Color.LTGRAY);
}
}
}
| true |
dcbf27b190ee6dbd17030f60a9f21ae964915fa4 | Java | druizcayuela/java-ddd | /src/rrss/test/social/app/rrss/shared/infrastructure/bus/event/rabbitmq/TestCreatedDomainEvent.java | UTF-8 | 1,809 | 2.34375 | 2 | [] | no_license | package social.app.rrss.shared.infrastructure.bus.event.rabbitmq;
import social.app.shared.domain.bus.event.DomainEvent;
import java.io.Serializable;
import java.util.HashMap;
public final class TestCreatedDomainEvent extends DomainEvent {
private final String name;
public TestCreatedDomainEvent() {
super(null);
this.name = null;
}
public TestCreatedDomainEvent(String aggregateId, String name) {
super(aggregateId);
this.name = name;
}
public TestCreatedDomainEvent(
String aggregateId,
String eventId,
String occurredOn,
String name
) {
super(aggregateId, eventId, occurredOn);
this.name = name;
}
@Override
public String eventName() {
return "test.created";
}
@Override
public HashMap<String, Serializable> toPrimitives() {
return new HashMap<String, Serializable>() {{
put("name", name);
}};
}
@Override
public TestCreatedDomainEvent fromPrimitives(
String aggregateId,
HashMap<String, Serializable> body,
String eventId,
String occurredOn
) {
return new TestCreatedDomainEvent(
aggregateId,
eventId,
occurredOn,
(String) body.get("name")
);
}
public String name() {
return name;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
TestCreatedDomainEvent that = (TestCreatedDomainEvent) o;
return name != null ? name.equals(that.name) : that.name == null;
}
@Override
public int hashCode() {
return name != null ? name.hashCode() : 0;
}
}
| true |
dde43aff8c20322a5007af714908ed0d6db0aae6 | Java | SpongeBob90/updownload | /src/main/java/com/wyw/updownload/controller/UpDownLoadController.java | UTF-8 | 2,953 | 2.5625 | 3 | [] | no_license | package com.wyw.updownload.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
/**
* @author wyw
* @date 2018\2\5 0005 14:01
*/
@Controller
public class UpDownLoadController {
@GetMapping(value = "/index")
public String upDownLoad() {
return "html/upDownLoad.html";
}
@PostMapping(value = "/upLoadFile")
@ResponseBody
public String upLoadFile(MultipartFile file) {
if (null == file) {
return "fail to upload";
} else {
String fileName = file.getOriginalFilename();
try {
///File tempFile = File.createTempFile(fileName);
File nFile = new File("/" + fileName);
file.transferTo(nFile);
} catch (IOException e) {
e.printStackTrace();
}
return "upload success";
}
}
@GetMapping(value = "/downLoadFile")
@ResponseBody
public void downLoad(HttpServletResponse res) {
String fileName;
try{
//浏览器会以iso8859-1的编码格式去解析header(包括filename),所以需要转换为iso8859-1格式
fileName = new String("森林公园.jpg".getBytes("utf-8"),"iso8859-1");
String path = this.getClass().getResource("/static/download/20170108181458.jpg").getPath();
res.setHeader("content-type", "application/octet-stream");
res.setHeader("Content-Disposition", "attachment;filename=" + fileName);
res.setContentType("application/octet-stream;charset=utf-8");
res.setCharacterEncoding("UTF-8");
byte[] buff = new byte[1024];
BufferedInputStream bis = null;
OutputStream os;
try {
os = res.getOutputStream();
bis = new BufferedInputStream(new FileInputStream(new File(path)));
int i = bis.read(buff);
while (i != -1) {
os.write(buff, 0, buff.length);
os.flush();
i = bis.read(buff);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//关闭bis或者os中的任意一个socket就会被关闭,因此不用同时手动关闭os和bis
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}catch (UnsupportedEncodingException e){
e.printStackTrace();
}
}
}
| true |
f306e318b9c531d6b3e90aa60d9c8347e7f1f3be | Java | Taraszhygal/SpringScooterRent | /src/main/java/com/test/exeption/ServiceException.java | UTF-8 | 925 | 2.703125 | 3 | [] | no_license | package com.test.exeption;
public class ServiceException extends RuntimeException{
private int code;
String message;
String detail;
public ServiceException(int code, String message, String detail) {
this.code = code;
this.message = message;
this.detail = detail;
}
public ServiceException(String message, Throwable cause, int code, String detail) {
super(message, cause);
this.code = code;
this.detail = detail;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
@Override
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getDetails() {
return detail;
}
public void setDetails(String detail) {
this.detail = detail;
}
}
| true |
8977b1eb8043feb2fa18f7b6af20001b22679210 | Java | jimarasim/SeleniumStandalone | /src/test/java/com/jaemzware/pinterest/tests/PinterestScrollTest.java | UTF-8 | 1,742 | 2.375 | 2 | [] | no_license | package com.jaemzware.pinterest.tests;
import com.jaemzware.BaseSeleniumTest;
import com.jaemzware.pinterest.pageobjects.PinterestHomePage;
import com.jaemzware.pinterest.pageobjects.PinterestLoginPage;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Assert;
import org.testng.annotations.Test;
public class PinterestScrollTest extends BaseSeleniumTest{
//THIS TEST SCROLLS DOWN THE PIN FEED, VERIFYING INTEGRITY OF ALL ELEMENTS ALONG THE WAY
@Test(groups={"pinteresttest","pinterestscrolltest"})
public void scrollTest() throws Exception{
PinterestLoginPage login = new PinterestLoginPage(driver);
PinterestHomePage home = new PinterestHomePage(driver);
//go to main site url and login if not already (default)
driver.get(home.URL);
login.LoginIfNot();
//scroll the page slowly, and ensure the static elements remain on the page
Object innerHeight = ((JavascriptExecutor) driver).executeScript("return window.innerHeight");
for(int i=0;i<10;i++) {
((JavascriptExecutor) driver).executeScript("window.scrollBy(0," + innerHeight.toString() + ")");
Thread.sleep(3000);
Assert.assertTrue(home.resultsListCount() > 2);
Assert.assertTrue(home.IsHomeButtonEnabled());
Assert.assertTrue(home.IsPButtonEnabled());
Assert.assertTrue(home.IsExploreButtonEnabled());
Assert.assertTrue(home.IsProfileButtonEnabled());
Assert.assertTrue(home.IsAddPinButtonEnabled());
Assert.assertTrue(home.IsMoreButtonEnabled());
}
}
}
| true |
7ab5713b0a093f50863d4177dc7840987c9b54a1 | Java | notaro1997/ChatCommands | /src/notaro/chatcommands/commands/Block.java | UTF-8 | 2,777 | 2.765625 | 3 | [] | no_license | package notaro.chatcommands.commands;
import notaro.chatcommands.ChatCommands;
import notaro.chatcommands.files.BlockFile;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
public class Block implements CommandExecutor{
private ChatCommands plugin;
public Block(ChatCommands plugin){
this.plugin = plugin;
}
@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
BlockFile blockFile = plugin.BlockedItems;
if(cmd.getName().equalsIgnoreCase("block") && args.length == 1){
if(sender.hasPermission("notaro.block") || sender.hasPermission("notaro.*")){
plugin.log.info(sender.getName() + ": ChatCommands: BLOCK");
if(args[0].equalsIgnoreCase("mob") || args[0].equalsIgnoreCase("mobs")){
blockFile.add("mobs");
blockFile.saveData();
sender.sendMessage(ChatColor.YELLOW + "Mobs blocked.");
}else{
Material material = null;
try {
material = Material.getMaterial(Integer.parseInt(args[0]));
} catch (NumberFormatException e) {
material = Material.getMaterial(args[0].toUpperCase());
}
if (material == null){
if(!args[0].equalsIgnoreCase("mob") || !args[0].equalsIgnoreCase("mobs")){
sender.sendMessage(ChatColor.RED + "Unknown item.");
}
}
else if(args[0].equalsIgnoreCase(material.toString())){
blockFile.add(material.toString().toLowerCase());
blockFile.saveData();
sender.sendMessage(ChatColor.YELLOW + material.toString().toLowerCase() + " blocked.");
}
}
}else{
sender.sendMessage(ChatColor.RED + "You need the permission: " + ChatColor.DARK_GREEN + "notaro.block " + ChatColor.RED + "to perform this command.");
}
}else if(cmd.getName().equalsIgnoreCase("unblock") && args.length == 1){
if(sender.hasPermission("notaro.unblock") || sender.hasPermission("notaro.*")){
plugin.log.info(sender.getName() + ": ChatCommands: UNBLOCK");
if(blockFile.contains(args[0])){
blockFile.remove(args[0]);
sender.sendMessage(ChatColor.YELLOW + args[0] + " unblocked.");
blockFile.saveData();
}else if(args[0].equalsIgnoreCase("mob")){
blockFile.remove("mobs");
blockFile.saveData();
sender.sendMessage(ChatColor.YELLOW + "Mobs unblocked.");
}else{
sender.sendMessage(ChatColor.RED + args[0] + " wasn't blocked.");
}
}else{
sender.sendMessage(ChatColor.RED + "You need the permission: " + ChatColor.DARK_GREEN + "notaro.unblock " + ChatColor.RED + "to perform this command.");
}
}else{
sender.sendMessage(ChatColor.RED + "Type /block then something to block. Or /unblock ");
}
return false;
}
} | true |
6b8f8626dbc6047713302e56012e45c2199e8bc0 | Java | PeterJohnson/allwpilib | /hal/src/main/java/edu/wpi/first/hal/HALUtil.java | UTF-8 | 1,481 | 1.523438 | 2 | [
"BSD-3-Clause"
] | permissive | // Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
package edu.wpi.first.hal;
public final class HALUtil extends JNIWrapper {
public static final int NULL_PARAMETER = -1005;
public static final int SAMPLE_RATE_TOO_HIGH = 1001;
public static final int VOLTAGE_OUT_OF_RANGE = 1002;
public static final int LOOP_TIMING_ERROR = 1004;
public static final int INCOMPATIBLE_STATE = 1015;
public static final int ANALOG_TRIGGER_PULSE_OUTPUT_ERROR = -1011;
public static final int NO_AVAILABLE_RESOURCES = -104;
public static final int PARAMETER_OUT_OF_RANGE = -1028;
public static final int RUNTIME_ROBORIO = 0;
public static final int RUNTIME_ROBORIO2 = 1;
public static final int RUNTIME_SIMULATION = 2;
public static native short getFPGAVersion();
public static native int getFPGARevision();
public static native String getSerialNumber();
public static native String getComments();
public static native long getFPGATime();
public static native int getHALRuntimeType();
public static native boolean getFPGAButton();
public static native String getHALErrorMessage(int code);
public static native int getHALErrno();
public static native String getHALstrerror(int errno);
public static String getHALstrerror() {
return getHALstrerror(getHALErrno());
}
private HALUtil() {}
}
| true |
fbb3f31cceb1ed019ea78e87c67ebbee0e5c4f31 | Java | umireon/collaboration-project | /src/JabberClient.java | UTF-8 | 1,764 | 2.8125 | 3 | [] | no_license | /*
* Copyright (C) 2014 umireon
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import java.io.*;
import java.net.*;
/**
*
* @author umireon
*/
public class JabberClient {
public static void main(String[] args) throws IOException {
InetAddress addr = InetAddress.getByName("localhost"); // IPアドレスへの変換
System.out.println("addr = " + addr);
Socket socket = new Socket(addr, JabberServer.PORT); // ソケットの生成
try {
System.out.println("socket = " + socket);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); // データ受信用バッファの設定
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true); // 送信バッファ設定
for (int i = 0; i < 10; i++) {
out.println("howdy" + i);
String str = in.readLine();
System.out.println(str);
}
out.println("END");
} finally {
System.out.println("closing...");
socket.close();
}
}
}
| true |
d68e947499e39d6900e96675b73373411c8f3abc | Java | intrahealth/msakhi_uk | /app/src/main/java/com/microware/intrahealth/ReportIndicator_ashaList.java | UTF-8 | 18,749 | 1.625 | 2 | [] | no_license | package com.microware.intrahealth;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.TextView;
import com.google.gson.internal.bind.ArrayTypeAdapter;
import com.microware.intrahealth.R;
import com.microware.intrahealth.Report_Module;
import com.microware.intrahealth.dataprovider.DataProvider;
import com.microware.intrahealth.object.MstVillage;
public class ReportIndicator_ashaList extends Activity {
TextView tvCurrentlypregnant, tvinfirsttrimester, tvinsecondtrimester, tvinthirdtrimester, tv1stAnc, tv2ndAnc, tv3rdAnc, tv4rthAnc, tvTT2Boster, tvHRP, tv_9month;
DataProvider dataprovider;
Global global;
int ashaid = 0, VillageID = 0, flag = 0;
Spinner spinVillageName;
ArrayList<MstVillage> Village = new ArrayList<MstVillage>();
ArrayAdapter<String> adapter;
Validate validate;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.reportindicator_asha_list);
dataprovider = new DataProvider(this);
validate = new Validate(this);
global = (Global) getApplication();
setTitle(global.getVersionName());
tvCurrentlypregnant = (TextView) findViewById(R.id.tvCurrentlypregnant);
spinVillageName = (Spinner) findViewById(R.id.spinVillageName);
tvinfirsttrimester = (TextView) findViewById(R.id.tvinfirsttrimester);
tvinsecondtrimester = (TextView) findViewById(R.id.tvinsecondtrimester);
tvinthirdtrimester = (TextView) findViewById(R.id.tvinthirdtrimester);
tv1stAnc = (TextView) findViewById(R.id.tv1stAnc);
tv2ndAnc = (TextView) findViewById(R.id.tv2ndAnc);
tv3rdAnc = (TextView) findViewById(R.id.tv3rdAnc);
tv4rthAnc = (TextView) findViewById(R.id.tv4rthAnc);
tvTT2Boster = (TextView) findViewById(R.id.tvTT2Boster);
tvHRP = (TextView) findViewById(R.id.tvHRP);
tv_9month = (TextView) findViewById(R.id.tv_9month);
if (global.getsGlobalAshaCode() != null
&& global.getsGlobalAshaCode().length() > 0) {
ashaid = Integer.valueOf(global.getsGlobalAshaCode());
}
Bundle extras = getIntent().getExtras();
if (extras != null)
flag = extras.getInt("flag");
fillVillageName(global.getLanguage());
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.Spinnerfilter, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinVillageName.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
if (pos > 0) {
VillageID = Village.get(
spinVillageName.getSelectedItemPosition() - 1)
.getVillageID();
showdata(VillageID);
} else {
VillageID = 0;
showAlldata();
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, 0, 1, validate.RetriveSharepreferenceString("name")).setShowAsAction(
MenuItem.SHOW_AS_ACTION_IF_ROOM);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getOrder()) {
case 1:
if (item.getTitle().equals(validate.RetriveSharepreferenceString("Username"))) {
item.setTitle(validate.RetriveSharepreferenceString("name"));
} else {
item.setTitle(validate.RetriveSharepreferenceString("Username"));
}
break;
default:
break;
}
return true;
}
public void showdata(int VillageId) {
String sql1 = "";
sql1 = "select count(*) from tblPregnant_woman inner join Tbl_HHSurvey on tblPregnant_woman.HHGUID=Tbl_HHSurvey.HHSurveyGUID where IsPregnant=1 and Tbl_HHSurvey.VillageID=" + VillageId + " and tblPregnant_woman.AshaID ="
+ ashaid
+ "";
int ivalue1 = 0;
ivalue1 = dataprovider.getMaxRecord(sql1);
tvCurrentlypregnant.setText(String.valueOf(ivalue1));
String sql2 = "";
sql2 = "select count(*) from tblPregnant_woman inner join Tbl_HHSurvey on tblPregnant_woman.HHGUID=Tbl_HHSurvey.HHSurveyGUID where cast(round(julianday('Now')-julianday(tblPregnant_woman.LMPDate) ) as int) between 0 and 90 and IsPregnant=1 and Tbl_HHSurvey.VillageID=" + VillageId + " and tblPregnant_woman.AshaID ="
+ ashaid
+ "";
int ivalue2 = 0;
ivalue2 = dataprovider.getMaxRecord(sql2);
tvinfirsttrimester.setText(String.valueOf(ivalue2));
String sql3 = "";
sql3 = "select count(*) from tblPregnant_woman inner join Tbl_HHSurvey on tblPregnant_woman.HHGUID=Tbl_HHSurvey.HHSurveyGUID where cast(round(julianday('Now')-julianday(tblPregnant_woman.LMPDate) ) as int) between 91 and 180 and IsPregnant=1 and Tbl_HHSurvey.VillageID=" + VillageId + " and tblPregnant_woman.AshaID ="
+ ashaid
+ "";
int ivalue3 = 0;
ivalue3 = dataprovider.getMaxRecord(sql3);
tvinsecondtrimester.setText(String.valueOf(ivalue3));
String sql4 = "";
sql4 = "select count(*) from tblPregnant_woman inner join Tbl_HHSurvey on tblPregnant_woman.HHGUID=Tbl_HHSurvey.HHSurveyGUID where cast(round(julianday('Now')-julianday(tblPregnant_woman.LMPDate) ) as int) between 181 and 270 and IsPregnant=1 and Tbl_HHSurvey.VillageID=" + VillageId + " and tblPregnant_woman.AshaID ="
+ ashaid
+ "";
int ivalue4 = 0;
ivalue4 = dataprovider.getMaxRecord(sql4);
tvinthirdtrimester.setText(String.valueOf(ivalue4));
String sql49month = "";
sql49month = "select count(*) from tblPregnant_woman inner join Tbl_HHSurvey on tblPregnant_woman.HHGUID=Tbl_HHSurvey.HHSurveyGUID where cast(round(julianday('Now')-julianday(tblPregnant_woman.LMPDate) ) as int) > 270 and IsPregnant=1 and Tbl_HHSurvey.VillageID=" + VillageId + " and tblPregnant_woman.AshaID ="
+ ashaid
+ "";
int ivalue49month = 0;
ivalue49month = dataprovider.getMaxRecord(sql49month);
tv_9month.setText(String.valueOf(ivalue49month));
String sql5 = "";
sql5 = "select count(*) from tblPregnant_woman inner join Tbl_HHSurvey on tblPregnant_woman.HHGUID=Tbl_HHSurvey.HHSurveyGUID inner join tblancvisit on tblancvisit.PWGUID =tblPregnant_woman.PWGUID where tblancvisit.Visit_No=1 and tblancvisit.CheckupVisitDate is not null and tblancvisit.CheckupVisitDate!='' and IsPregnant=1 and Tbl_HHSurvey.VillageID=" + VillageId + " and tblPregnant_woman.AshaID ="
+ ashaid
+ "";
int ivalue5 = 0;
ivalue5 = dataprovider.getMaxRecord(sql5);
tv1stAnc.setText(String.valueOf(ivalue5));
String sql6 = "";
sql6 = "select count(*) from tblPregnant_woman inner join Tbl_HHSurvey on tblPregnant_woman.HHGUID=Tbl_HHSurvey.HHSurveyGUID inner join tblancvisit on tblancvisit.PWGUID =tblPregnant_woman.PWGUID where tblancvisit.Visit_No=2 and tblancvisit.CheckupVisitDate is not null and tblancvisit.CheckupVisitDate!='' and IsPregnant=1 and Tbl_HHSurvey.VillageID=" + VillageId + " and tblPregnant_woman.AshaID ="
+ ashaid
+ "";
int ivalue6 = 0;
ivalue6 = dataprovider.getMaxRecord(sql6);
tv2ndAnc.setText(String.valueOf(ivalue6));
String sql7 = "";
sql7 = "select count(*) from tblPregnant_woman inner join Tbl_HHSurvey on tblPregnant_woman.HHGUID=Tbl_HHSurvey.HHSurveyGUID inner join tblancvisit on tblancvisit.PWGUID =tblPregnant_woman.PWGUID where tblancvisit.Visit_No=3 and tblancvisit.CheckupVisitDate is not null and tblancvisit.CheckupVisitDate!='' and IsPregnant=1 and Tbl_HHSurvey.VillageID=" + VillageId + " and tblPregnant_woman.AshaID ="
+ ashaid
+ "";
int ivalue7 = 0;
ivalue7 = dataprovider.getMaxRecord(sql7);
tv3rdAnc.setText(String.valueOf(ivalue7));
String sql8 = "";
sql8 = "select count(*) from tblPregnant_woman inner join Tbl_HHSurvey on tblPregnant_woman.HHGUID=Tbl_HHSurvey.HHSurveyGUID inner join tblancvisit on tblancvisit.PWGUID =tblPregnant_woman.PWGUID where tblancvisit.Visit_No=4 and tblancvisit.CheckupVisitDate is not null and tblancvisit.CheckupVisitDate!='' and IsPregnant=1 and Tbl_HHSurvey.VillageID=" + VillageId + " and tblPregnant_woman.AshaID ="
+ ashaid
+ "";
int ivalue8 = 0;
ivalue8 = dataprovider.getMaxRecord(sql8);
tv4rthAnc.setText(String.valueOf(ivalue8));
String sql9 = "";
sql9 = "select count(Distinct(tblPregnant_woman.PWGUID )) from tblPregnant_woman inner join Tbl_HHSurvey on tblPregnant_woman.HHGUID=Tbl_HHSurvey.HHSurveyGUID inner join tblancvisit on tblancvisit.PWGUID =tblPregnant_woman.PWGUID where ((tblancvisit.TTfirstDoseDate is not null and tblancvisit.TTfirstDoseDate !='') or (tblancvisit.TTsecondDoseDate is not null and tblancvisit.TTsecondDoseDate!='') or(tblancvisit.TTBoosterDate is not null and tblancvisit.TTBoosterDate!='')) and IsPregnant=1 and Tbl_HHSurvey.VillageID=" + VillageId + " and tblPregnant_woman.AshaID ="
+ ashaid
+ " ";
int ivalue9 = 0;
ivalue9 = dataprovider.getMaxRecord(sql9);
tvTT2Boster.setText(String.valueOf(ivalue9));
String sql10 = "";
sql10 = "select count(DISTINCT(tblPregnant_woman.PWGUID)) from tblPregnant_woman inner join Tbl_HHSurvey on tblPregnant_woman.HHGUID=Tbl_HHSurvey.HHSurveyGUID inner join tblancvisit on tblancvisit.PWGUID =tblPregnant_woman.PWGUID where (tblPregnant_woman.HighRisk=1 or tblancvisit.HighRisk=1) and IsPregnant=1 and Tbl_HHSurvey.VillageID=" + VillageId + " and tblPregnant_woman.AshaID ="
+ ashaid
+ " ";
int ivalue10 = 0;
ivalue10 = dataprovider.getMaxRecord(sql10);
tvHRP.setText(String.valueOf(ivalue10));
}
private void fillVillageName(int Language) {
Village = dataprovider.getMstVillageName(global.getsGlobalAshaCode(), Language, 0);
String sValue[] = new String[Village.size() + 1];
sValue[0] = getResources().getString(R.string.select);
for (int i = 0; i < Village.size(); i++) {
sValue[i + 1] = Village.get(i).getVillageName();
}
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_dropdown_item, sValue);
spinVillageName.setAdapter(adapter);
}
public void showAlldata() {
String sql1 = "";
sql1 = "select count(*) from tblPregnant_woman inner join Tbl_HHSurvey on tblPregnant_woman.HHGUID=Tbl_HHSurvey.HHSurveyGUID where IsPregnant=1 and tblPregnant_woman.AshaID ="
+ ashaid
+ "";
int ivalue1 = 0;
ivalue1 = dataprovider.getMaxRecord(sql1);
tvCurrentlypregnant.setText(String.valueOf(ivalue1));
String sql2 = "";
sql2 = "select count(*) from tblPregnant_woman inner join Tbl_HHSurvey on tblPregnant_woman.HHGUID=Tbl_HHSurvey.HHSurveyGUID where cast(round(julianday('Now')-julianday(tblPregnant_woman.LMPDate) ) as int) between 0 and 90 and IsPregnant=1 and tblPregnant_woman.AshaID ="
+ ashaid
+ "";
int ivalue2 = 0;
ivalue2 = dataprovider.getMaxRecord(sql2);
tvinfirsttrimester.setText(String.valueOf(ivalue2));
String sql3 = "";
sql3 = "select count(*) from tblPregnant_woman inner join Tbl_HHSurvey on tblPregnant_woman.HHGUID=Tbl_HHSurvey.HHSurveyGUID where cast(round(julianday('Now')-julianday(tblPregnant_woman.LMPDate) ) as int) between 91 and 180 and IsPregnant=1 and tblPregnant_woman.AshaID ="
+ ashaid
+ "";
int ivalue3 = 0;
ivalue3 = dataprovider.getMaxRecord(sql3);
tvinsecondtrimester.setText(String.valueOf(ivalue3));
String sql4 = "";
sql4 = "select count(*) from tblPregnant_woman inner join Tbl_HHSurvey on tblPregnant_woman.HHGUID=Tbl_HHSurvey.HHSurveyGUID where cast(round(julianday('Now')-julianday(tblPregnant_woman.LMPDate) ) as int) between 181 and 270 and IsPregnant=1 and tblPregnant_woman.AshaID ="
+ ashaid
+ "";
int ivalue4 = 0;
ivalue4 = dataprovider.getMaxRecord(sql4);
tvinthirdtrimester.setText(String.valueOf(ivalue4));
String sql49month = "";
sql49month = "select count(*) from tblPregnant_woman inner join Tbl_HHSurvey on tblPregnant_woman.HHGUID=Tbl_HHSurvey.HHSurveyGUID where cast(round(julianday('Now')-julianday(tblPregnant_woman.LMPDate) ) as int) > 270 and IsPregnant=1 and tblPregnant_woman.AshaID ="
+ ashaid
+ "";
int ivalue49month = 0;
ivalue49month = dataprovider.getMaxRecord(sql49month);
tv_9month.setText(String.valueOf(ivalue49month));
String sql5 = "";
sql5 = "select count(*) from tblPregnant_woman inner join Tbl_HHSurvey on tblPregnant_woman.HHGUID=Tbl_HHSurvey.HHSurveyGUID inner join tblancvisit on tblancvisit.PWGUID =tblPregnant_woman.PWGUID where tblancvisit.Visit_No=1 and tblancvisit.CheckupVisitDate is not null and tblancvisit.CheckupVisitDate!='' and IsPregnant=1 and tblPregnant_woman.AshaID ="
+ ashaid
+ "";
int ivalue5 = 0;
ivalue5 = dataprovider.getMaxRecord(sql5);
tv1stAnc.setText(String.valueOf(ivalue5));
String sql6 = "";
sql6 = "select count(*) from tblPregnant_woman inner join Tbl_HHSurvey on tblPregnant_woman.HHGUID=Tbl_HHSurvey.HHSurveyGUID inner join tblancvisit on tblancvisit.PWGUID =tblPregnant_woman.PWGUID where tblancvisit.Visit_No=2 and tblancvisit.CheckupVisitDate is not null and tblancvisit.CheckupVisitDate!='' and IsPregnant=1 and tblPregnant_woman.AshaID ="
+ ashaid
+ "";
int ivalue6 = 0;
ivalue6 = dataprovider.getMaxRecord(sql6);
tv2ndAnc.setText(String.valueOf(ivalue6));
String sql7 = "";
sql7 = "select count(*) from tblPregnant_woman inner join Tbl_HHSurvey on tblPregnant_woman.HHGUID=Tbl_HHSurvey.HHSurveyGUID inner join tblancvisit on tblancvisit.PWGUID =tblPregnant_woman.PWGUID where tblancvisit.Visit_No=3 and tblancvisit.CheckupVisitDate is not null and tblancvisit.CheckupVisitDate!='' and IsPregnant=1 and tblPregnant_woman.AshaID ="
+ ashaid
+ "";
int ivalue7 = 0;
ivalue7 = dataprovider.getMaxRecord(sql7);
tv3rdAnc.setText(String.valueOf(ivalue7));
String sql8 = "";
sql8 = "select count(*) from tblPregnant_woman inner join Tbl_HHSurvey on tblPregnant_woman.HHGUID=Tbl_HHSurvey.HHSurveyGUID inner join tblancvisit on tblancvisit.PWGUID =tblPregnant_woman.PWGUID where tblancvisit.Visit_No=4 and tblancvisit.CheckupVisitDate is not null and tblancvisit.CheckupVisitDate!='' and IsPregnant=1 and tblPregnant_woman.AshaID ="
+ ashaid
+ "";
int ivalue8 = 0;
ivalue8 = dataprovider.getMaxRecord(sql8);
tv4rthAnc.setText(String.valueOf(ivalue8));
String sql9 = "";
sql9 = "select count(Distinct(tblPregnant_woman.PWGUID )) from tblPregnant_woman inner join Tbl_HHSurvey on tblPregnant_woman.HHGUID=Tbl_HHSurvey.HHSurveyGUID inner join tblancvisit on tblancvisit.PWGUID =tblPregnant_woman.PWGUID where ((tblancvisit.TTfirstDoseDate is not null and tblancvisit.TTfirstDoseDate !='') or (tblancvisit.TTsecondDoseDate is not null and tblancvisit.TTsecondDoseDate!='') or(tblancvisit.TTBoosterDate is not null and tblancvisit.TTBoosterDate!='')) and IsPregnant=1 and tblPregnant_woman.AshaID ="
+ ashaid
+ " ";
int ivalue9 = 0;
ivalue9 = dataprovider.getMaxRecord(sql9);
tvTT2Boster.setText(String.valueOf(ivalue9));
String sql10 = "";
sql10 = "select count(DISTINCT(tblPregnant_woman.PWGUID)) from tblPregnant_woman inner join Tbl_HHSurvey on tblPregnant_woman.HHGUID=Tbl_HHSurvey.HHSurveyGUID inner join tblancvisit on tblancvisit.PWGUID =tblPregnant_woman.PWGUID where (tblPregnant_woman.HighRisk=1 or tblancvisit.HighRisk=1) and IsPregnant=1 and tblPregnant_woman.AshaID ="
+ ashaid
+ " ";
int ivalue10 = 0;
ivalue10 = dataprovider.getMaxRecord(sql10);
tvHRP.setText(String.valueOf(ivalue10));
}
@Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
if (global.getiGlobalRoleID() == 3 && flag == 0) {
Intent i = new Intent(ReportIndicator_ashaList.this,
AshaDashboardList.class);
finish();
startActivity(i);
} else if (flag == 1) {
Intent i = new Intent(ReportIndicator_ashaList.this,
AncActivity.class);
finish();
startActivity(i);
} else {
Intent i = new Intent(ReportIndicator_ashaList.this,
Report_Module.class);
finish();
startActivity(i);
}
}
}
| true |
6872f83f1cc0655aab0147705ed548b934603a6f | Java | kendix/asteroids | /src/Bullet.java | UTF-8 | 1,406 | 3.296875 | 3 | [] | no_license | import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
public class Bullet {
double [] position;
double direction;
double speed;
double size;
double[] maxPosition;
double maxDistance;
double distanceTraveled;
boolean maxDistanceReached = false;
public Bullet(double[] position, double direction, double speed, double size, double[] maxPosition,
double maxDistance) {
super();
this.position = position;
this.direction = direction;
this.speed = speed;
this.size = size;
this.maxPosition = maxPosition;
this.maxDistance = maxDistance;
this.distanceTraveled = 0;
}
public void step(double dt) {
position[0] += speed * Math.cos(direction) * dt;
position[1] += speed * Math.sin(direction) * dt;
distanceTraveled += speed * dt;
if(position[0] > maxPosition[0]) {
position[0] -= maxPosition[0];
} else if(position[0] < 0) {
position[0] += maxPosition[0];
}
if(position[1] > maxPosition[1]) {
position[1] -= maxPosition[1];
} else if(position[1] < 0) {
position[1] += maxPosition[1];
}
if(distanceTraveled > maxDistance) {
speed = 0;
maxDistanceReached = true;
}
}
public void draw(Graphics2D g) {
AffineTransform oldTransform=g.getTransform();
g.translate(position[0], position[1]);
g.rotate(direction);
g.setColor(Color.WHITE);
g.drawLine(-3, 0, 0, 0);
g.setTransform(oldTransform);
}
}
| true |
b342ce24bee9984c038825b28abd9eb8fd5a821c | Java | ingef/conquery | /backend/src/main/java/com/bakdata/conquery/models/preproc/TableInputDescriptor.java | UTF-8 | 4,952 | 2.046875 | 2 | [
"MIT"
] | permissive | package com.bakdata.conquery.models.preproc;
import java.time.LocalDate;
import java.util.Arrays;
import java.util.stream.Stream;
import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import com.bakdata.conquery.models.common.Range;
import com.bakdata.conquery.models.config.ConqueryConfig;
import com.bakdata.conquery.models.events.MajorTypeId;
import com.bakdata.conquery.models.preproc.outputs.CopyOutput;
import com.bakdata.conquery.models.preproc.outputs.OutputDescription;
import com.bakdata.conquery.models.preproc.parser.Parser;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import groovy.lang.GroovyShell;
import io.dropwizard.validation.ValidationMethod;
import it.unimi.dsi.fastutil.objects.Object2IntArrayMap;
import it.unimi.dsi.fastutil.objects.Object2IntMap;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.codehaus.groovy.control.CompilerConfiguration;
import org.codehaus.groovy.control.customizers.ImportCustomizer;
/**
* An input describes transformations on a single CSV file to be loaded into the table described in {@link TableImportDescriptor}.
* <p>
* It requires a primary Output and at least one normal output.
* <p>
* Input data can be filtered using the field filter, which is evaluated as a groovy script on every row.
*/
@Data
@Slf4j
public class TableInputDescriptor {
private static final long serialVersionUID = 1L;
private static final String[] AUTO_IMPORTS = Stream.of(
LocalDate.class,
Range.class
).map(Class::getName).toArray(String[]::new);
@NotNull
private String sourceFile;
private String filter;
/**
* Output producing the primary column. This should be the primary key across all tables.
* Default is `COPY("pid", STRING)`
*/
@NotNull
@Valid
private OutputDescription primary = new CopyOutput("pid", "id", MajorTypeId.STRING);
@Valid
@NotEmpty
@JsonManagedReference
private OutputDescription[] output;
/**
* Empty array to be used only for validation of groovy script.
*/
public static final String[] FAKE_HEADERS = new String[50];
@JsonIgnore
@ValidationMethod(message = "One or more columns are duplicated")
public boolean allColumnsDistinct() {
return Arrays.stream(getOutput()).map(OutputDescription::getName)
.distinct()
.count() == getOutput().length;
}
@JsonIgnore
@ValidationMethod(message = "Groovy script is not valid.")
public boolean isValidGroovyScript() {
try {
createFilter(FAKE_HEADERS);
}
catch (Exception ex) {
log.error("Groovy script is not valid", ex);
return false;
}
return true;
}
@JsonIgnore
@ValidationMethod(message = "Each column requires a unique name")
public boolean isEachNameUnique() {
Object2IntMap<String> names = new Object2IntArrayMap<>(getWidth());
names.defaultReturnValue(-1);
for (int index = 0; index < output.length; index++) {
int prev = names.put(output[index].getName(), index);
if (prev != -1) {
log.error("Duplicate Output to Column[{}] at indices {} and {}", output[index].getName(), prev, index);
return false;
}
}
return true;
}
@JsonIgnore
@ValidationMethod(message = "The primary column must be of type STRING")
public boolean isPrimaryString() {
return primary.getResultType() == MajorTypeId.STRING;
}
public GroovyPredicate createFilter(String[] headers) {
if (filter == null) {
return null;
}
try {
CompilerConfiguration config = new CompilerConfiguration();
config.addCompilationCustomizers(new ImportCustomizer().addImports(AUTO_IMPORTS));
config.setScriptBaseClass(GroovyPredicate.class.getName());
GroovyShell groovy = new GroovyShell(config);
for (int col = 0; col < headers.length; col++) {
groovy.setVariable(headers[col], col);
}
return (GroovyPredicate) groovy.parse(filter);
}
catch (Exception e) {
throw new RuntimeException("Failed to compile filter `" + filter + "`", e);
}
}
@JsonIgnore
public int getWidth() {
return getOutput().length;
}
public ColumnDescription getColumnDescription(int i) {
return output[i].getColumnDescription();
}
/**
* Create a mapping from a header to it's column position.
*/
public static Object2IntArrayMap<String> buildHeaderMap(String[] headers) {
final int[] indices = new int[headers.length];
Arrays.setAll(indices, i -> i);
return new Object2IntArrayMap<>(headers, indices);
}
/**
* Hashcode is used to in validity-hash of Preprocessed files.
*/
public int hashCode() {
final HashCodeBuilder builder = new HashCodeBuilder();
builder.append(getSourceFile());
builder.append(getFilter());
builder.append(getPrimary());
for (OutputDescription outputDescription : getOutput()) {
builder.append(outputDescription.hashCode());
}
return builder.toHashCode();
}
}
| true |
6caf6988efab51214753802f5df3b6024abc7c5f | Java | big-guy/largeJavaMultiProject | /project253/src/test/java/org/gradle/test/performance/largejavamultiproject/project253/p1266/Test25338.java | UTF-8 | 2,525 | 2.21875 | 2 | [] | no_license | package org.gradle.test.performance.largejavamultiproject.project253.p1266;
import org.gradle.test.performance.largejavamultiproject.project250.p1251.Production25038;
import org.gradle.test.performance.largejavamultiproject.project251.p1256.Production25138;
import org.gradle.test.performance.largejavamultiproject.project252.p1261.Production25238;
import org.junit.Test;
import static org.junit.Assert.*;
public class Test25338 {
Production25338 objectUnderTest = new Production25338();
@Test
public void testProperty0() {
Production25329 value = new Production25329();
objectUnderTest.setProperty0(value);
assertEquals(value, objectUnderTest.getProperty0());
}
@Test
public void testProperty1() {
Production25333 value = new Production25333();
objectUnderTest.setProperty1(value);
assertEquals(value, objectUnderTest.getProperty1());
}
@Test
public void testProperty2() {
Production25337 value = new Production25337();
objectUnderTest.setProperty2(value);
assertEquals(value, objectUnderTest.getProperty2());
}
@Test
public void testProperty3() {
Production25038 value = new Production25038();
objectUnderTest.setProperty3(value);
assertEquals(value, objectUnderTest.getProperty3());
}
@Test
public void testProperty4() {
Production25138 value = new Production25138();
objectUnderTest.setProperty4(value);
assertEquals(value, objectUnderTest.getProperty4());
}
@Test
public void testProperty5() {
Production25238 value = new Production25238();
objectUnderTest.setProperty5(value);
assertEquals(value, objectUnderTest.getProperty5());
}
@Test
public void testProperty6() {
String value = "value";
objectUnderTest.setProperty6(value);
assertEquals(value, objectUnderTest.getProperty6());
}
@Test
public void testProperty7() {
String value = "value";
objectUnderTest.setProperty7(value);
assertEquals(value, objectUnderTest.getProperty7());
}
@Test
public void testProperty8() {
String value = "value";
objectUnderTest.setProperty8(value);
assertEquals(value, objectUnderTest.getProperty8());
}
@Test
public void testProperty9() {
String value = "value";
objectUnderTest.setProperty9(value);
assertEquals(value, objectUnderTest.getProperty9());
}
} | true |
8c5d4548f34a48a35b245058c0008e18a0f68724 | Java | lyndemberg/sd-oficina | /shared/src/main/java/sd/oficina/shared/model/person/Cidade.java | UTF-8 | 381 | 2.015625 | 2 | [] | no_license | package sd.oficina.shared.model.person;
import lombok.Data;
import javax.persistence.*;
import java.io.Serializable;
@Entity
@Data
public class Cidade implements Serializable {
@Id
@GeneratedValue
private long id;
@Column(nullable = false)
private String nome;
@ManyToOne(cascade = {CascadeType.MERGE, CascadeType.DETACH})
private Estado estado;
}
| true |
ad95251a555249b9e0735f2ccdd6b8cb34e97bad | Java | haowuhoss/hossdemo | /src/main/java/dynamicProxy/RealStar.java | UTF-8 | 319 | 3.015625 | 3 | [] | no_license | package dynamicProxy;
public class RealStar implements Star{
@Override
public void talk() {
System.out.println("明星本人谈话");
}
@Override
public void sing() {
System.out.println("明星本人唱歌");
}
@Override
public void charge() {
System.out.println("明星本人收钱");
}
}
| true |
d5bcb4ebf4a1a4d0d319a243160fe0ead8f58af9 | Java | alenantonova/smart-home-2019 | /src/main/java/ru/sbt/mipt/oop/action/TurnOffLight.java | UTF-8 | 1,066 | 2.90625 | 3 | [] | no_license | package ru.sbt.mipt.oop.action;
import ru.sbt.mipt.oop.object.Light;
import ru.sbt.mipt.oop.object.Room;
public class TurnOffLight implements Action {
String light_id;
String room_name;
public TurnOffLight(String object_id) {
light_id = object_id;
room_name = "none";
}
public String GetRoom() {return room_name;}
public void InspectRoom (Room room) {
if (light_id.equals("all")) {
room_name = room.getName();
} else {
for (Light light : room.getLights()) {
if (light.getId().equals(light_id)) {
room_name = room.getName();
}
}
}
}
public void run(Object object) {
if(object instanceof Light) {
String cur_id = ((Light) object).getId();
if (light_id.equals(cur_id) || light_id.equals("all")) {
((Light) object).setOn(false);
System.out
.println("Light " + cur_id + " in room " + room_name + " was turned off.");
}
} else if (object instanceof Room && room_name.equals("none")) {
InspectRoom((Room) object);
}
}
}
| true |
21e5c2eb9248e5d85c92c49adb63e71f917421a8 | Java | varunbhatbm/ANZAssessment | /src/com/assessment/conversionchain/MultiHopConverter.java | UTF-8 | 3,093 | 2.9375 | 3 | [] | no_license | package com.assessment.conversionchain;
import com.assessment.config.Currencies;
import com.assessment.config.CurrencyConversionConfiguration;
import com.assessment.core.CurrencyConversionMatrix;
import com.assessment.utils.CurrencyConverterLogger;
public class MultiHopConverter extends AbstractConverter {
@Override
public Float doConversion(String fromCurrency, String toCurrency, Float currencyValue) {
Float returnValue = null;
Integer fromCurrencyIndex = Currencies.getCurrencyIndex(fromCurrency);
Integer toCurrencyIndex = Currencies.getCurrencyIndex(toCurrency);
//Check using the from and to currency if direct conversion is possible
// If direct conversion is not possible then use the intermediate currency for conversion
String conversionVia = CurrencyConversionMatrix
.getInstance().getCurrencyConversionMatrix()[fromCurrencyIndex][toCurrencyIndex];
Integer conversionViaIndex = Currencies.getCurrencyIndex(conversionVia);
String singleHopCurrency = CurrencyConversionMatrix
.getInstance().getCurrencyConversionMatrix()[conversionViaIndex][toCurrencyIndex];
Integer singleHopCurrencyIndex = Currencies.getCurrencyIndex(singleHopCurrency);
String lastHopCurrency = CurrencyConversionMatrix
.getInstance().getCurrencyConversionMatrix()[singleHopCurrencyIndex][toCurrencyIndex];
if ((lastHopCurrency == CurrencyConversionMatrix.DIRECT_CHECK)
|| (lastHopCurrency == CurrencyConversionMatrix.INVERSE)
) {
// Since direct conversion is possible use the input file for conversion rates..
Float intermediatConversionRate = CurrencyConversionConfiguration.getInstance().convertValue(fromCurrency, conversionVia);
Float intermediateValue = intermediatConversionRate * currencyValue;
CurrencyConverterLogger.debug("Intermediate ConversionRate is "+intermediatConversionRate);
Float intermediatConversionRate1 = CurrencyConversionConfiguration.getInstance().convertValue(conversionVia, singleHopCurrency);
Float intermediateValue1 = intermediatConversionRate1 * intermediateValue;
CurrencyConverterLogger.debug("Intermediate 1 ConversionRate is "+intermediatConversionRate1);
Float finalConversionRate = CurrencyConversionConfiguration.getInstance().convertValue(singleHopCurrency, toCurrency);
CurrencyConverterLogger.debug("Final ConversionRate is "+finalConversionRate);
returnValue = finalConversionRate * intermediateValue1;
}
else if(lastHopCurrency == CurrencyConversionMatrix.SAME_CURRENCY)
{
Float intermediatConversionRate = CurrencyConversionConfiguration.getInstance().convertValue(fromCurrency, conversionVia);
Float intermediateValue = intermediatConversionRate * currencyValue;
CurrencyConverterLogger.debug("Intermediate ConversionRate is "+intermediatConversionRate);
Float finalConversionRate = CurrencyConversionConfiguration.getInstance().convertValue(conversionVia, toCurrency);
CurrencyConverterLogger.debug("Final ConversionRate is "+finalConversionRate);
returnValue = finalConversionRate * currencyValue;
}
return returnValue;
}
}
| true |
da816d3b656de8d30d88610f3086e43ea1b4c264 | Java | MovecarePolimi/MobileUse | /app/src/main/java/com/polimi/mobileuse/logic/http/HttpAbstract.java | UTF-8 | 6,769 | 2.03125 | 2 | [] | no_license | package com.polimi.mobileuse.logic.http;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import com.polimi.mobileuse.dao.preferences.LoginPreferences;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URLEncoder;
import static android.content.Context.CONNECTIVITY_SERVICE;
public abstract class HttpAbstract {
private static final String TAG = "HttpAbstract";
protected Context context;
protected String broadcastEventName;
protected enum ConnectionType{
WIFI,
MOBILE_DATA,
OTHER
};
protected final static int TIMEOUT_VALUE = 1000;
protected final static String POST_STRING = "POST";
protected final static String GET_STRING = "GET";
private final static String USERNAME_STRING = "username";
private final static String PASSWORD_STRING = "password";
private final static String APPLICATION_STRING = "application";
private final static String GRANT_TYPE_STRING = "grant_type";
private final static String TENANT_STRING = "tenant";
protected final static String ACCESS_TOKEN_STRING = "access_token";
protected final static String TOKEN_TYPE_STRING = "token_type";
protected final static String REFRESH_TOKEN_STRING = "refresh_token";
protected final static String EXPIRES_IN_STRING = "expires_in";
protected final static String JTI_STRING = "jti";
protected final static String[] refreshTokenParamsName = {
GRANT_TYPE_STRING,
REFRESH_TOKEN_STRING,
APPLICATION_STRING,
TENANT_STRING
};
protected final static String[] loginParamsName = {
GRANT_TYPE_STRING,
USERNAME_STRING,
PASSWORD_STRING,
APPLICATION_STRING,
TENANT_STRING
};
protected boolean isConnected(Context context){
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
}
// return 1 if Wi-Fi, 2 if mobile data, otherwise 0
protected ConnectionType getConnectionType(Context context){
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isWiFi = isConnected(context) && activeNetwork.getType() == ConnectivityManager.TYPE_WIFI;
if(isWiFi){
return ConnectionType.WIFI;
}
boolean isMobileData = isConnected(context) && activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE;
if(isMobileData){
return ConnectionType.MOBILE_DATA;
}
return ConnectionType.OTHER;
}
protected void enableMobileData(Context context, boolean enabled) throws Exception{
final ConnectivityManager conman = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
Class conmanClass = null;
try {
conmanClass = Class.forName(conman.getClass().getName());
} catch (ClassNotFoundException e) {
e.printStackTrace();
return;
}
final Field iConnectivityManagerField = conmanClass.getDeclaredField("mService");
iConnectivityManagerField.setAccessible(true);
final Object iConnectivityManager = iConnectivityManagerField.get(conman);
final Class iConnectivityManagerClass = Class.forName(iConnectivityManager.getClass().getName());
final Method setMobileDataEnabledMethod = iConnectivityManagerClass.getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE);
setMobileDataEnabledMethod.setAccessible(true);
setMobileDataEnabledMethod.invoke(iConnectivityManager, enabled);
}
protected void storeNewToken(Context context,
String accessToken,
String tokenType,
String refreshToken,
String expiresIn,
String jti ){
LoginPreferences logPref = new LoginPreferences();
logPref.storeVariable(context, LoginPreferences.Variable.ACCESS_TOKEN, accessToken);
logPref.storeVariable(context, LoginPreferences.Variable.TOKEN_TYPE, tokenType);
logPref.storeVariable(context, LoginPreferences.Variable.REFRESH_TOKEN, refreshToken);
logPref.storeVariable(context, LoginPreferences.Variable.EXPIRES_IN, expiresIn);
logPref.storeVariable(context, LoginPreferences.Variable.JTI, jti);
}
protected String getParams(String[] paramsName, String[] paramsValue) throws UnsupportedEncodingException
{
if(paramsName == null || paramsValue == null || (paramsName.length != paramsValue.length)){
Log.e(TAG, "Parameters error: error on name or value");
return null;
}
StringBuilder result = new StringBuilder();
boolean first = true;
for(int i = 0; i< paramsName.length; i++){
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(paramsName[i], "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(paramsValue[i], "UTF-8"));
}
return result.toString();
}
protected String getResponseText(InputStream stream) throws IOException {
if(stream == null){
Log.e(TAG, "Method GetResponseString: received NULL stream object");
throw new IOException();
}
StringBuilder result = new StringBuilder();
Reader reader = new InputStreamReader(stream, "UTF-8");
BufferedReader bufferedReader = new BufferedReader(reader);
String line;
while ((line = bufferedReader.readLine()) != null) {
result.append(line);
}
return result.toString();
}
protected void sendMessage(String broadcasterName, HttpLogin.MessageType msg) {
Log.v(TAG, "Send broadcasting message");
//Intent intent = new Intent("custom-event-name");
Intent intent = new Intent(broadcasterName);
intent.putExtra("message", msg);
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
}
}
| true |
913a47a9b83e379de8eb445cf406c4d64d75ea9b | Java | moutainhigh/welink | /welink-commons/src/main/java/com/welink/commons/persistence/BannerDOMapper.java | UTF-8 | 3,333 | 1.859375 | 2 | [] | no_license | package com.welink.commons.persistence;
import com.welink.commons.domain.BannerDO;
import com.welink.commons.domain.BannerDOExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.session.RowBounds;
import org.springframework.stereotype.Repository;
@Repository
public interface BannerDOMapper {
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table banner
*
* @mbggenerated Tue Nov 24 17:34:03 CST 2015
*/
int countByExample(BannerDOExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table banner
*
* @mbggenerated Tue Nov 24 17:34:03 CST 2015
*/
int deleteByExample(BannerDOExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table banner
*
* @mbggenerated Tue Nov 24 17:34:03 CST 2015
*/
int deleteByPrimaryKey(Long id);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table banner
*
* @mbggenerated Tue Nov 24 17:34:03 CST 2015
*/
int insert(BannerDO record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table banner
*
* @mbggenerated Tue Nov 24 17:34:03 CST 2015
*/
int insertSelective(BannerDO record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table banner
*
* @mbggenerated Tue Nov 24 17:34:03 CST 2015
*/
List<BannerDO> selectByExampleWithRowbounds(BannerDOExample example, RowBounds rowBounds);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table banner
*
* @mbggenerated Tue Nov 24 17:34:03 CST 2015
*/
List<BannerDO> selectByExample(BannerDOExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table banner
*
* @mbggenerated Tue Nov 24 17:34:03 CST 2015
*/
BannerDO selectByPrimaryKey(Long id);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table banner
*
* @mbggenerated Tue Nov 24 17:34:03 CST 2015
*/
int updateByExampleSelective(@Param("record") BannerDO record, @Param("example") BannerDOExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table banner
*
* @mbggenerated Tue Nov 24 17:34:03 CST 2015
*/
int updateByExample(@Param("record") BannerDO record, @Param("example") BannerDOExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table banner
*
* @mbggenerated Tue Nov 24 17:34:03 CST 2015
*/
int updateByPrimaryKeySelective(BannerDO record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table banner
*
* @mbggenerated Tue Nov 24 17:34:03 CST 2015
*/
int updateByPrimaryKey(BannerDO record);
} | true |
5837a7623c886545c7448e31ef0304d7bbef145a | Java | lucassoller2000/modulo-java | /tcc/back-end/tcc/src/main/java/br/com/cwi/crescer/tcc/service/post/EditarPrivacidadePostService.java | UTF-8 | 1,054 | 2.109375 | 2 | [] | no_license | package br.com.cwi.crescer.tcc.service.post;
import br.com.cwi.crescer.tcc.dominio.Post;
import br.com.cwi.crescer.tcc.dominio.dto.PrivacidadeDto;
import br.com.cwi.crescer.tcc.repository.IPostRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Objects;
@Service
public class EditarPrivacidadePostService {
@Autowired
BuscarPostPorIdService buscarPostPorIdService;
@Autowired
IPostRepository postRepository;
public Post editar(Long id, PrivacidadeDto privacidadeDto){
if(Objects.isNull(id)){
throw new IllegalArgumentException("O id não pode estar em branco");
}
if(Objects.isNull(privacidadeDto.getPrivacidadePost())){
throw new IllegalArgumentException("A privacidade não pode estar em branco");
}
Post post = buscarPostPorIdService.buscar(id);
post.setPrivacidadePost(privacidadeDto.getPrivacidadePost());
return postRepository.save(post).get();
}
}
| true |
51e73efc1a992b2493abbce9125479d91b8dfa16 | Java | jameszgw/account-kernel | /OLink-kernel/OLink-bpm/src/main/java/OLink/bpm/core/validate/repository/ejb/ValidateRepositoryProcess.java | UTF-8 | 774 | 2.234375 | 2 | [] | no_license | package OLink.bpm.core.validate.repository.ejb;
import java.util.Collection;
import OLink.bpm.base.ejb.IDesignTimeProcess;
public interface ValidateRepositoryProcess extends IDesignTimeProcess<ValidateRepositoryVO> {
/**
* 根据(模块)module对象主键标识,获取验证对象集合.
*
* @param moduleid
* Module对象标识
* @return 验证对象集合
* @throws Exception
*/
Collection<ValidateRepositoryVO> get_validate(String applicationid) throws Exception;
/**
* 根据检验库名,判断名称是否唯一
* @param id
* @param name
* @param application
* @return 存在返回true,否则返回false
* @throws Exception
*/
boolean isValidateNameExist(String id, String name, String application)throws Exception;
}
| true |
d8b5709da3663027450afbbf632886af16ac8a61 | Java | Rhuax/FOOL | /src/ast/IdTypeNode.java | UTF-8 | 845 | 2.46875 | 2 | [] | no_license | package ast;
import util.Environment;
import util.SemanticError;
import java.util.ArrayList;
/**
* Created by crow on 26/06/17.
*/
public class IdTypeNode implements Node {
public String getTypeName() {
return typeName;
}
private String typeName;
public IdTypeNode(String typeName) {
this.typeName = typeName;
}
@Override
public String toPrint(String indent) {
return indent + "typeName:" + typeName + "\n";
}
@Override
public String toString() {
return getTypeName();
}
@Override
public Node typeCheck() {
return null;
}
@Override
public String codeGeneration() {
return "";
}
@Override
public ArrayList<SemanticError> checkSemantics(Environment env) {
return new ArrayList<SemanticError>();
}
}
| true |
870b476ac11bdf0a92a25c566297c2ccea7541db | Java | onkar5891/ok-data-structure | /ok-algorithms/src/main/java/dp/subsetsum/SubsetSum.java | UTF-8 | 1,091 | 3.578125 | 4 | [] | no_license | package dp.subsetsum;
public class SubsetSum {
public boolean sumExists(int[] nos, int sum) {
int n = nos.length;
Boolean[][] dp = new Boolean[n][sum + 1];
// populate 0th column which indicates 0 sum is possible without any element
for (int i = 0; i < nos.length; i++) {
dp[0][i] = true;
}
// for single number, populate 0th row and the value is true only if sum is equal to the number
for (int s = 1; s <= sum; s++) {
dp[0][s] = nos[0] == s;
}
// process all subsets for all sums
for (int i = 1; i < n; i++) {
for (int s = 1; s <= sum; s++) {
// if we get sum 's' without number at index 'i'
if (dp[i - 1][s]) {
dp[i][s] = dp[i - 1][s];
} else if (nos[i] <= s) {
// else include the number and see if we can find a subset with remaining sum
dp[i][s] = dp[i - 1][s - nos[i]];
}
}
}
return dp[n - 1][sum];
}
}
| true |
7df835db2e5129887aba42eb69b1fde769556c15 | Java | IosifGabriel/vanir-backend | /src/test/java/com/jimaio/vanir/test/unit/UtilsUnitTests.java | UTF-8 | 1,287 | 2.203125 | 2 | [] | no_license | package com.jimaio.vanir.test.unit;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import com.jimaio.vanir.VanirApplication;
import com.jimaio.vanir.utils.AvatarUtils;
import com.jimaio.vanir.utils.Utils;
@RunWith(JUnit4.class)
@SpringBootTest(classes = VanirApplication.class,
webEnvironment = WebEnvironment.RANDOM_PORT)
public class UtilsUnitTests {
@Autowired
private AvatarUtils avatarUtils;
@Test
public void avatarGeneration() {
String avatarBasePath = "https://avataaars.io/png/";
String generatedAvatar = avatarUtils.generateAvatarUrl();
assertTrue(generatedAvatar.substring(avatarBasePath.length()).length() > 0);
}
@Test
public void randomCardNumberGenerator() {
int length = 16;
String randomCode = Utils.generateRandomNumber(length);
int codeLengthWithSpacing = length + length / 4 - 1;
assertEquals(randomCode.length(), codeLengthWithSpacing);
}
}
| true |
088cdd2a9d7e215012836d00b03741bf78a54d51 | Java | garfield19/KYMApp | /app/src/main/java/ng/com/babbangona/kymapp/Data/POJO/Members.java | UTF-8 | 4,776 | 2.046875 | 2 | [] | no_license | package ng.com.babbangona.kymapp.Data.POJO;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Members {
@SerializedName("member_name")
@Expose
private String memberName;
@SerializedName("ik_number")
@Expose
private String ikNumber;
@SerializedName("unique_member_id")
@Expose
private String uniqueMemberId;
@SerializedName("member_role")
@Expose
private String memberRole;
@SerializedName("picker")
@Expose
private String picker;
@SerializedName("template")
@Expose
private String template;
@SerializedName("done")
@Expose
private String done;
@SerializedName("card")
@Expose
private String card;
@SerializedName("m_date")
@Expose
private String m_date;
@SerializedName("pass_done")
@Expose
private String pass_done;
@SerializedName("fail_picture_done")
@Expose
private String fail_picture_done;
@SerializedName("approved")
@Expose
private String approved;
@SerializedName("member_id")
@Expose
private String member_id;
public static final String TABLE_NAME = "members_records_db";
public static final String COLUMN_ID = "id";
public static final String MEMBER_NAME = "member_name";
public static final String COLUMN_MEMBER_ID = "member_id";
public static final String PICKER = "picker";
public static final String IK_NUMBER = "ik_number";
public static final String COLUMN_TEMPLATE = "template";
public static final String DONE= "done";
public static final String ROLE= "role";
public static final String CARD= "card";
public static final String PASS_DONE= "pass_done";
public static final String PC_APPROVED= "approved";
public static final String FAIL_PICTURE_DONE= "fail_picture_done";
public static final String MEMBER_ID= "old_member_id";
//START DATABASE CREATION
public static final String CREATE_TABLE =
"CREATE TABLE " + TABLE_NAME + "("
+ COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ MEMBER_NAME + " TEXT,"
+ COLUMN_MEMBER_ID + " TEXT,"
+ IK_NUMBER + " TEXT,"
+ ROLE + " TEXT,"
+ PICKER + " TEXT,"
+ DONE + " TEXT,"
+ COLUMN_TEMPLATE + " TEXT,"
+ PC_APPROVED + " TEXT,"
+ CARD + " TEXT,"
+ PASS_DONE + " TEXT,"
+ FAIL_PICTURE_DONE + " TEXT,"
+ MEMBER_ID + " TEXT"
+ ")";
//END DATABASE CREATION
//START GETTER & SETTER
public String getMemberName() {
return memberName;
}
public void setMemberName(String memberName) {
this.memberName = memberName;
}
public String getIkNumber() {
return ikNumber;
}
public void setIkNumber(String ikNumber) {
this.ikNumber = ikNumber;
}
public String getUniqueMemberId() {
return uniqueMemberId;
}
public void setUniqueMemberId(String uniqueMemberId) {
this.uniqueMemberId = uniqueMemberId;
}
public String getMemberRole() {
return memberRole;
}
public void setMemberRole(String memberRole) {
this.memberRole = memberRole;
}
public String getPicker() {
return picker;
}
public void setPicker(String picker) {
this.picker = picker;
}
public String getTemplate() {
return template;
}
public void setTemplate(String template) {
this.template = template;
}
public String getDone() {
return done;
}
public void setDone(String done) {
this.done = done;
}
public String getCard() {
return card;
}
public void setCard(String card) {
this.card = card;
}
public String getM_date() {
return m_date;
}
public void setM_date(String m_date) {
this.m_date = m_date;
}
public String getPass_done() {
return pass_done;
}
public void setPass_done(String pass_done) {
this.pass_done = pass_done;
}
public String getFail_picture_done() {
return fail_picture_done;
}
public void setFail_picture_done(String fail_picture_done) {
this.fail_picture_done = fail_picture_done;
}
public String getApproved() {
return approved;
}
public void setApproved(String approved) {
this.approved = approved;
}
public String getMember_id() {
return member_id;
}
public void setMember_id(String member_id) {
this.member_id = member_id;
}
}
| true |
825381c3302082f97531e8b8804072bae9193b53 | Java | ptrvck/Breeer | /app/src/main/java/com/genius/petr/breeer/map/FragmentMap.java | UTF-8 | 49,158 | 1.554688 | 2 | [] | no_license | package com.genius.petr.breeer.map;
import android.Manifest;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Point;
import android.graphics.PorterDuff;
import android.location.Location;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.GridLayout;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TableLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.genius.petr.breeer.R;
import com.genius.petr.breeer.activity.MainActivity;
import com.genius.petr.breeer.circuits.CircuitMapPagerAdapter;
import com.genius.petr.breeer.circuits.CircuitMapViewModel;
import com.genius.petr.breeer.database.AppDatabase;
import com.genius.petr.breeer.database.Place;
import com.genius.petr.breeer.database.PlaceConstants;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.BitmapDescriptor;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.MapStyleOptions;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;
import com.google.android.gms.tasks.OnCanceledListener;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.maps.android.clustering.ClusterManager;
import org.w3c.dom.Document;
import java.lang.ref.WeakReference;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import static android.support.v4.view.ViewPager.SCROLL_STATE_IDLE;
import static android.support.v4.view.ViewPager.SCROLL_STATE_SETTLING;
/**
* Created by Petr on 24. 2. 2018.
*/
public class FragmentMap
extends Fragment
implements OnMapReadyCallback, GoogleMap.OnMarkerClickListener,
GoogleMap.OnMapClickListener, GoogleMap.OnMapLoadedCallback {
private static final String TAG = "mapFragmentLog";
private static final String PLACE_ESSENTIALS_TAG = "placeEssentialsFragment";
private MapView mMapView;
private GoogleMap map;
private ClusterManager<PlaceCluster> clusterManager;
private LinearLayout filtersLayout;
private GridLayout filtersGrid;
private CheckBox filtersCheckbox;
private List<Marker> circuitMarkers;
private CircuitMapViewModel activeCircuit;
private Place activePlace;
private Marker activeMarker = null;
private long activePlaceId = -1;
private boolean showingCategory = false;
private static final int STATE_PLACES = 0;
private static final int STATE_CIRCUIT = 1;
private static final int STATE_SINGLE = 2;
private static final int STATE_NAVIGATION = 3;
private static final int STATE_NAVIGATION_DETAIL = 4;
private int currentState = STATE_PLACES;
private static final String SAVE_STATE_STATE = "state";
private static final String SAVE_STATE_CIRCUIT = "active_circuit";
private static final String SAVE_STATE_PLACE = "active_place";
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, final Bundle savedInstanceState) {
Log.i("Breeer", "OnCreateView called");
View rootView = inflater.inflate(R.layout.fragment_map, container, false);
rootView.findViewById(R.id.loadingOverlay).setVisibility(View.VISIBLE);
ProgressBar progressBar = rootView.findViewById(R.id.progressBar);
progressBar.getIndeterminateDrawable().setColorFilter(ContextCompat.getColor(getContext(), R.color.colorLightGray), PorterDuff.Mode.SRC_IN );
mMapView = rootView.findViewById(R.id.mapView);
mMapView.onCreate(savedInstanceState);
try {
MapsInitializer.initialize(getActivity().getApplicationContext());
} catch (Exception e) {
e.printStackTrace();
}
if (savedInstanceState != null) {
if (savedInstanceState.containsKey(SAVE_STATE_STATE)) {
currentState = savedInstanceState.getInt(SAVE_STATE_STATE);
}
if(currentState == STATE_CIRCUIT) {
long id = savedInstanceState.getLong(SAVE_STATE_CIRCUIT);
Log.i("circuitTest", "restored id: " + id);
activeCircuit = new CircuitMapViewModel(id);
}
if(currentState == STATE_SINGLE || currentState == STATE_NAVIGATION || currentState == STATE_NAVIGATION_DETAIL) {
long id = savedInstanceState.getLong(SAVE_STATE_PLACE);
Log.i("placeTest", "restored id: " + id);
activePlaceId = id;
}
}
setupFilters(rootView);
mMapView.getMapAsync(this);
return rootView;
}
private void setupFilters(View rootView) {
filtersLayout = rootView.findViewById(R.id.filtersLayout);
filtersGrid = filtersLayout.findViewById(R.id.filtersGrid);
filtersCheckbox = filtersLayout.findViewById(R.id.checkBoxFilters);
final ViewTreeObserver viewTreeObserver = filtersGrid.getViewTreeObserver();
if (viewTreeObserver.isAlive()) {
viewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
filtersGrid.getViewTreeObserver().removeOnGlobalLayoutListener(this);
final int width = filtersGrid.getWidth();
filtersCheckbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
filtersLayout.setTranslationX(width);
filtersLayout.animate()
.translationXBy(-width)
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationStart(Animator animation) {
super.onAnimationEnd(animation);
filtersGrid.setVisibility(View.VISIBLE);
}
});
} else {
//filtersLayout.setTranslationX();
filtersLayout.animate()
.translationXBy(width)
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
filtersGrid.setVisibility(View.INVISIBLE);
}
});
}
}
});
if (!filtersCheckbox.isChecked()) {
filtersLayout.setTranslationX(width);
}
}
});
if (currentState != STATE_PLACES) {
filtersLayout.setVisibility(View.GONE);
}
}
for(int i=0; i < filtersGrid.getChildCount(); i++) {
View child = filtersGrid.getChildAt(i);
if (child instanceof CheckBox) {
final CheckBox filter = (CheckBox) child;
filter.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (!filter.isPressed())
{
// Not from user!
return;
}
refreshMarkers();
}
});
}
}
}
private void refreshMarkers(){
List<Integer> categories = new ArrayList<>();
int category = 0;
for(int i=0; i < filtersGrid.getChildCount(); i++) {
View child = filtersGrid.getChildAt(i);
if (child instanceof CheckBox) {
CheckBox filter = (CheckBox)child;
if (filter.isChecked()) {
categories.add(category);
}
}
category++;
}
for (int cat : categories) {
Log.i(TAG, "cat displayed: " + cat);
}
AddMarkersAsyncTask task = new AddMarkersAsyncTask(FragmentMap.this, AppDatabase.getDatabase(getContext().getApplicationContext()), categories);
task.execute();
}
@Override
public void onMapReady(GoogleMap googleMap){
this.map = googleMap;
map.setOnMapLoadedCallback(this);
try {
// Customise the styling of the base map using a JSON object defined
// in a raw resource file.
boolean success = googleMap.setMapStyle(
MapStyleOptions.loadRawResourceStyle(
getContext(), R.raw.style_json));
if (!success) {
Log.e(TAG, "Style parsing failed.");
}
} catch (Resources.NotFoundException e) {
Log.e(TAG, "Can't find style. Error: ", e);
}
map.moveCamera( CameraUpdateFactory.newLatLngZoom(new LatLng(49.19522, 16.60796) , 14.0f) );
clusterManager = new ClusterManager<>(getContext(), googleMap);
clusterManager.setRenderer(new CustomMapClusterRenderer<>(getContext(),map, clusterManager));
clusterManager.setAlgorithm(new ClusteringAlgorithm<PlaceCluster>());
map.setOnCameraIdleListener(clusterManager);
map.setOnMapClickListener(this);
map.setOnMarkerClickListener(this);
if (currentState == STATE_SINGLE) {
final RelativeLayout placeDetail = getView().findViewById(R.id.placeLayout);
placeDetail.setVisibility(View.GONE);
}
map.setOnMyLocationButtonClickListener(new GoogleMap.OnMyLocationButtonClickListener() {
@Override
public boolean onMyLocationButtonClick() {
if (!isLocationAvailable()) {
Toast.makeText(getContext(), "Your phone has no idea where you are. Are you sure it has enabled location?", Toast.LENGTH_LONG).show();
}
return false;
}
});
}
private boolean isLocationAvailable(){
boolean gps_enabled = false;
boolean network_enabled = false;
LocationManager lm = (LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);
try {
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
}catch (Exception ex){}
try{
network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}catch (Exception ex){}
return (gps_enabled || network_enabled);
}
@Override
public void onMapLoaded() {
MainActivity activity = (MainActivity)getActivity();
activity.tryToEnableLocation();
View overlay = getView().findViewById(R.id.loadingOverlay);
overlay.setVisibility(View.GONE);
if (currentState == STATE_PLACES) {
refreshMarkers();
}
if (currentState == STATE_CIRCUIT) {
Log.i("circuitTest", "showing circuit: " + activeCircuit.getId());
showCircuit(activeCircuit.getId());
}
if (currentState == STATE_SINGLE || currentState == STATE_NAVIGATION || currentState == STATE_NAVIGATION_DETAIL) {
selectPlace(activePlaceId);
}
}
public boolean onMarkerClick(Marker marker) {
if (currentState == STATE_SINGLE) {
return true;
}
if (currentState == STATE_PLACES || currentState == STATE_NAVIGATION) {
Log.i(TAG, "onMarkerClick");
//cluster
if (marker.getTitle() == null) {
map.animateCamera(CameraUpdateFactory.newLatLngZoom(
marker.getPosition(), (float) Math.floor(map
.getCameraPosition().zoom + 1)), 300,
null);
return true;
} else {
long id = Long.parseLong(marker.getTitle());
selectPlace(id);
return true;
}
}
if (currentState == STATE_CIRCUIT) {
updateCircuitActiveMarker(marker);
selectCircuitNode(marker);
return true;
}
return true;
}
private void updateCircuitActiveMarker(Marker active){
int color = getResources().getColor(PlaceConstants.CATEGORY_COLORS.get(activeCircuit.getType()));
BitmapDescriptor markerIcon = MapUtils.bitmapDescriptorFromVector(FragmentMap.this.getContext(), R.drawable.marker_circuit, color);
//old active
if (activeMarker != null) {
activeMarker.setIcon(markerIcon);
}
activeMarker = active;
activeMarker.setIcon(MapUtils.bitmapDescriptorFromVector(FragmentMap.this.getContext(), R.drawable.marker_circuit));
}
private void selectCircuitNode(Marker marker){
RelativeLayout circuitLayout = getView().findViewById(R.id.circuitLayout);
ViewPager viewPager = circuitLayout.findViewById(R.id.viewpager_circuitStops);
viewPager.setVisibility(View.VISIBLE);
int position = 0;
for (Marker m : circuitMarkers) {
if (m.equals(marker)) {
viewPager.setCurrentItem(position+1);
break;
}
position++;
}
}
private void animateLatLngZoom(LatLng latlng, int reqZoom, int offsetX, int offsetY) {
if (map == null) {
return;
}
// Save current zoom
float originalZoom = map.getCameraPosition().zoom;
// Move temporarily camera zoom
map.moveCamera(CameraUpdateFactory.zoomTo(reqZoom));
Point pointInScreen = map.getProjection().toScreenLocation(latlng);
Point newPoint = new Point();
newPoint.x = pointInScreen.x + offsetX;
newPoint.y = pointInScreen.y + offsetY;
LatLng newCenterLatLng = map.getProjection().fromScreenLocation(newPoint);
// Restore original zoom
map.moveCamera(CameraUpdateFactory.zoomTo(originalZoom));
// Animate a camera with new latlng center and required zoom.
map.animateCamera(CameraUpdateFactory.newLatLngZoom(newCenterLatLng, reqZoom));
}
@Override
public void onMapClick(LatLng latLng) {
if (currentState == STATE_SINGLE) {
hideCurrentState();
activateStatePlaces();
return;
}
if (currentState == STATE_NAVIGATION_DETAIL) {
hidePlaceDetail();
return;
}
if (currentState == STATE_CIRCUIT) {
deactivateCircuitNode();
return;
}
}
private void deactivateCircuitNode(){
int color = getResources().getColor(PlaceConstants.CATEGORY_COLORS.get(activeCircuit.getType()));
BitmapDescriptor markerIcon = MapUtils.bitmapDescriptorFromVector(FragmentMap.this.getContext(), R.drawable.marker_circuit, color);
//old active
if (activeMarker != null) {
activeMarker.setIcon(markerIcon);
activeMarker = null;
}
ViewPager viewPager = getView().findViewById(R.id.viewpager_circuitStops);
viewPager.setVisibility(View.GONE);
}
public void navigationFail(){
RelativeLayout placeDetail = getView().findViewById(R.id.placeLayout);
Button navigateButton = placeDetail.findViewById(R.id.button_startNavigation);
navigateButton.setEnabled(true);
Toast.makeText(getContext(), "Your phone has no idea where you are.", Toast.LENGTH_LONG).show();
}
public void navigationDenied(){
RelativeLayout placeDetail = getView().findViewById(R.id.placeLayout);
Button navigateButton = placeDetail.findViewById(R.id.button_startNavigation);
navigateButton.setEnabled(true);
Toast.makeText(getContext(), "Can't navigate because we don't know where you are.", Toast.LENGTH_LONG).show();
}
private void navigateToActivePlace() {
MainActivity activity = (MainActivity)getActivity();
activity.tryToNavigateToActivePlace();
}
private void activateStateNavigation(NavResponse response) {
currentState = STATE_NAVIGATION;
activePlace = response.getPlace();
activePlaceId = activePlace.getId();
MarkerOptions markerOptions = new MarkerOptions().position(activePlace.getPosition()).title(Long.toString(activePlace.getId()))
.icon(MapUtils.bitmapDescriptorFromVector(getContext(), PlaceConstants.CATEGORY_MARKERS.get(activePlace.getCategory())));
if(map!=null) {
activeMarker = map.addMarker(markerOptions);
final TableLayout navigationLayout = getView().findViewById(R.id.navigationLayout);
int colorId = PlaceConstants.CATEGORY_COLORS.get(activePlace.getCategory());
navigationLayout.setBackgroundColor(getActivity().getResources().getColor(colorId));
Button stopButton = navigationLayout.findViewById(R.id.button_stopNavigation);
stopButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
hideCurrentState();
activateStatePlaces();
}
});
TextView nameTextView = navigationLayout.findViewById(R.id.placeName);
nameTextView.setText(activePlace.getName());
navigationLayout.setVisibility(View.VISIBLE);
navigationLayout.getViewTreeObserver().addOnGlobalLayoutListener(
new ViewTreeObserver.OnGlobalLayoutListener(){
@Override
public void onGlobalLayout() {
Log.i(TAG, "on global layout");
// gets called after layout has been done but before display
navigationLayout.getViewTreeObserver().removeOnGlobalLayoutListener( this );
int height = navigationLayout.getHeight();
map.setPadding(0, height, 0, 0);
int viewHeight = getView().getHeight();
navigationLayout.setTranslationY(-height);
navigationLayout.animate().translationY(0).setDuration(700).setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
navigationLayout.clearAnimation();
navigationLayout.animate().setListener(null);
}
@Override
public void onAnimationCancel(Animator animation) {
animation.removeAllListeners();
}
});
}
});
}
}
private void startNavigation(NavResponse navResponse) {
if (map == null) {
return;
}
if (navResponse == null) {
Toast.makeText(getContext(), "Unable to find directions. Check your internet connection and try again please.", Toast.LENGTH_LONG).show();
RelativeLayout placeDetail = getView().findViewById(R.id.placeLayout);
if (placeDetail.getVisibility() == View.VISIBLE) {
Button navigateButton = placeDetail.findViewById(R.id.button_startNavigation);
navigateButton.setEnabled(true);
return;
}
}
hideCurrentState();
activateStateNavigation(navResponse);
Place place = navResponse.getPlace();
ArrayList<LatLng> navPoints = navResponse.getNavPoints();
int colorId = PlaceConstants.CATEGORY_COLORS.get(place.getCategory());
PolylineOptions rectLine = new PolylineOptions().width(8).color(getActivity().getResources().getColor(colorId));
Log.d("route", "navPoints: " + navPoints.size());
for (LatLng navPoint : navPoints) {
rectLine.add(navPoint);
}
Polyline route = map.addPolyline(rectLine);
}
public void startNavigationToActivePlace(LatLng userLocation){
Log.i("route", "starting task");
new GMapV2DirectionAsyncTask(FragmentMap.this, AppDatabase.getDatabase(getContext().getApplicationContext()), activePlace.id, userLocation).execute();
}
public void selectPlace(final Place place) {
Log.i(TAG, "showing place: " + place.getName());
if ((currentState == STATE_NAVIGATION || currentState == STATE_NAVIGATION_DETAIL) && (place.getId() == activePlace.getId())) {
currentState = STATE_NAVIGATION_DETAIL;
} else {
hideCurrentState();
currentState = STATE_SINGLE;
int category = place.getCategory();
View f = filtersGrid.getChildAt(category);
if (f instanceof CheckBox) {
final CheckBox filter = (CheckBox) f;
filter.setChecked(true);
}
}
activePlace = place;
activePlaceId = place.getId();
MarkerOptions markerOptions = new MarkerOptions().position(place.getPosition()).title(Long.toString(place.getId()))
.icon(MapUtils.bitmapDescriptorFromVector(getContext(), PlaceConstants.CATEGORY_MARKERS_ACTIVE.get(place.getCategory())));
if(map!=null) {
Log.i(TAG, "map ok");
if(activeMarker != null) {
activeMarker.remove();
}
activeMarker = map.addMarker(markerOptions);
final RelativeLayout placeDetail = getView().findViewById(R.id.placeLayout);
TextView tvName = placeDetail.findViewById(R.id.placeName);
TextView tvCategory = placeDetail.findViewById(R.id.placeCategory);
TextView tvDescription = placeDetail.findViewById(R.id.placeDescription);
final Button navigateButton = placeDetail.findViewById(R.id.button_startNavigation);
Button detailButton = placeDetail.findViewById(R.id.button_detail);
navigateButton.setEnabled(true);
navigateButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
navigateToActivePlace();
navigateButton.setEnabled(false);
}
});
final long id = place.getId();
detailButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
((MainActivity) getActivity()).showPlaceDetail(id);
}
});
tvName.setText(place.getName());
tvCategory.setText(PlaceConstants.CATEGORY_NAMES.get(place.getCategory()));
tvDescription.setText(place.getDescription());
int color = ContextCompat.getColor(getContext(), PlaceConstants.CATEGORY_COLORS.get(place.getCategory()));
tvCategory.setTextColor(color);
detailButton.getBackground().setColorFilter(color, PorterDuff.Mode.SRC_ATOP);
final LatLng position = place.getPosition();
placeDetail.setVisibility(View.VISIBLE);
placeDetail.getViewTreeObserver().addOnGlobalLayoutListener(
new ViewTreeObserver.OnGlobalLayoutListener(){
@Override
public void onGlobalLayout() {
Log.i(TAG, "on global layout");
// gets called after layout has been done but before display
placeDetail.getViewTreeObserver().removeOnGlobalLayoutListener( this );
int height = placeDetail.getHeight();
int viewHeight = getView().getHeight();
int newCenter = (viewHeight + height) / 2;
int offsetY = newCenter - (viewHeight/2);
if (map!=null) {
float zoom = map.getCameraPosition().zoom;
if (zoom < 16) {
zoom = 16;
}
animateLatLngZoom(position, (int)zoom, 0, offsetY);
}
placeDetail.setTranslationY(height);
placeDetail.animate().translationY(0).setDuration(1000).setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
Log.i(TAG, "on show anim end");
Log.i(TAG, "visibility: " + placeDetail.getVisibility());
placeDetail.clearAnimation();
placeDetail.animate().setListener(null);
}
@Override
public void onAnimationCancel(Animator animation) {
animation.removeAllListeners();
}
});
final View content = placeDetail.findViewById(R.id.content);
content.setAlpha(0f);
content.animate().alpha(1f).setDuration(800).setStartDelay(250).setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
content.clearAnimation();
content.animate().setListener(null);
}
@Override
public void onAnimationCancel(Animator animation) {
animation.removeAllListeners();
}
});
/*
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
view.setVisibility(View.GONE);
}
});
*/
}
});
}
}
public void selectPlace(long placeId) {
Log.i(TAG, "selectPlace called: " + placeId);
ShowPlaceAsyncTask task = new ShowPlaceAsyncTask(FragmentMap.this, AppDatabase.getDatabase(getContext().getApplicationContext()), placeId);
task.execute();
}
public void showCategory(int category) {
hideCurrentState();
for(int i=0; i < filtersGrid.getChildCount(); i++) {
View child = filtersGrid.getChildAt(i);
if (child instanceof CheckBox) {
final CheckBox filter = (CheckBox) child;
if (i==category) {
filter.setChecked(true);
} else {
filter.setChecked(false);
}
}
}
showingCategory = true;
activateStatePlaces();
}
public void closePlace(){
hideCurrentState();
activateStatePlaces();
}
private void hidePlaceDetail(){
if (map != null) {
if (currentState == STATE_NAVIGATION_DETAIL) {
activeMarker.remove();
MarkerOptions markerOptions = new MarkerOptions().position(activePlace.getPosition()).title(Long.toString(activePlace.getId()))
.icon(MapUtils.bitmapDescriptorFromVector(getContext(), PlaceConstants.CATEGORY_MARKERS.get(activePlace.getCategory())));
activeMarker = map.addMarker(markerOptions);
currentState = STATE_NAVIGATION;
} else {
map.clear();
activePlace = null;
}
}
final RelativeLayout placeDetail = getView().findViewById(R.id.placeLayout);
int height = placeDetail.getHeight();
placeDetail.animate().translationY(height).setDuration(1000).setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
placeDetail.setVisibility(View.GONE);
placeDetail.clearAnimation();
placeDetail.animate().setListener(null);
}
@Override
public void onAnimationCancel(Animator animation) {
animation.removeAllListeners();
}
});
View content = placeDetail.findViewById(R.id.content);
content.animate().alpha(0f).setDuration(700);
}
@Override
public void onResume() {
super.onResume();
//activeMarker = null;
mMapView.onResume();
}
@Override
public void onPause() {
super.onPause();
/*
//todo: this is now called to prevent crash when app was suspended to background and restored (it crashed when you unselect marker)
if (currentState == STATE_NAVIGATION_DETAIL) {
hidePlaceDetail();
}
*/
mMapView.onPause();
}
@Override
public void onDestroy() {
super.onDestroy();
mMapView.onDestroy();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mMapView.onLowMemory();
}
@Override
public void onSaveInstanceState (Bundle outState) {
Log.i(TAG, "onSaveCalled");
super.onSaveInstanceState(outState);
mMapView.onSaveInstanceState(outState);
if (currentState == STATE_NAVIGATION || currentState == STATE_NAVIGATION_DETAIL) {
outState.putInt(SAVE_STATE_STATE, STATE_SINGLE);
} else {
outState.putInt(SAVE_STATE_STATE, currentState);
}
Log.i("circuitTest", "current state: " + currentState);
if (currentState == STATE_CIRCUIT) {
outState.putLong(SAVE_STATE_CIRCUIT, activeCircuit.getId());
Log.i("circuitTest", "saving id: " + activeCircuit.getId());
}
if (currentState == STATE_SINGLE) {
outState.putLong(SAVE_STATE_PLACE, activePlace.getId());
}
if (currentState == STATE_NAVIGATION) {
outState.putLong(SAVE_STATE_PLACE, activePlace.getId());
}
if (currentState == STATE_NAVIGATION_DETAIL) {
outState.putLong(SAVE_STATE_PLACE, activePlace.getId());
}
}
private void addClusters(List<PlaceCluster> clusters){
LatLngBounds.Builder boundsBuilder = new LatLngBounds.Builder();
clusterManager.clearItems();
for (PlaceCluster cluster : clusters) {
clusterManager.addItem(cluster);
boundsBuilder.include(cluster.getPosition());
}
clusterManager.cluster();
//todo: find a more elegant way to handle this?
if (showingCategory) {
showingCategory = false;
LatLngBounds bounds = boundsBuilder.build();
int width = getResources().getDisplayMetrics().widthPixels;
int padding = (int)(width*0.2); // offset from edges of the map in pixels
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngBounds(bounds, padding);
map.animateCamera(cameraUpdate);
}
}
public void showCircuit(Long id){
hideCurrentState();
Log.i("circuitTest", "id: " + id);
ShowCircuitAsyncTask task = new ShowCircuitAsyncTask(FragmentMap.this, AppDatabase.getDatabase(getContext().getApplicationContext()), id);
task.execute();
}
private void hideCurrentState() {
if (map != null) {
map.setPadding(0, 0, 0, 0);
}
if (currentState == STATE_PLACES) {
if (clusterManager != null) {
clusterManager.clearItems();
clusterManager.cluster();
}
if (map != null) {
map.clear();
}
filtersLayout.setVisibility(View.GONE);
}
if (currentState == STATE_CIRCUIT) {
if (map != null) {
map.clear();
}
activeCircuit = null;
if (circuitMarkers != null) {
circuitMarkers.clear();
circuitMarkers = null;
}
RelativeLayout circuitLayout = getView().findViewById(R.id.circuitLayout);
circuitLayout.setVisibility(View.GONE);
}
if (currentState == STATE_SINGLE) {
hidePlaceDetail();
}
if (currentState == STATE_NAVIGATION) {
TableLayout navigationLayout = getView().findViewById(R.id.navigationLayout);
navigationLayout.setVisibility(View.GONE);
if (map != null) {
map.clear();
}
}
if (currentState == STATE_NAVIGATION_DETAIL) {
TableLayout navigationLayout = getView().findViewById(R.id.navigationLayout);
navigationLayout.setVisibility(View.GONE);
if (map != null) {
map.clear();
}
if (activePlace != null) {
hidePlaceDetail();
}
}
}
private void showCircuit(CircuitMapViewModel viewModel) {
activeCircuit = viewModel;
circuitMarkers = new ArrayList<>();
int color = getResources().getColor(PlaceConstants.CATEGORY_COLORS.get(activeCircuit.getType()));
BitmapDescriptor markerIcon = MapUtils.bitmapDescriptorFromVector(FragmentMap.this.getContext(), R.drawable.marker_circuit, color);
for (Place place : activeCircuit.getStops()) {
MarkerOptions markerOptions = new MarkerOptions().position(place.getPosition()).title(Long.toString(place.getId())).icon(markerIcon).anchor(0.5f, 0.5f);
Marker marker = map.addMarker(markerOptions);
circuitMarkers.add(marker);
}
activeMarker = circuitMarkers.get(0);
List<LatLng> path = activeCircuit.getPath();
if (path.size() < 2) {
return;
}
RelativeLayout circuitLayout = getView().findViewById(R.id.circuitLayout);
RelativeLayout circuitLabelLayout = getView().findViewById(R.id.circuitLabelLayout);
circuitLabelLayout.setBackgroundColor(color);
circuitLayout.setVisibility(View.VISIBLE);
TextView tvCircuitName = getView().findViewById(R.id.circuitName);
tvCircuitName.setText(activeCircuit.getName());
Button button_close = getView().findViewById(R.id.button_closeCircuit);
button_close.setTextColor(color);
button_close.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
closeCircuit();
}
});
final ViewPager viewPager = getView().findViewById(R.id.viewpager_circuitStops);
//this is to add 2 dummy items to make viewpager "linked"
List<Place> places = viewModel.getStops();
places.add(places.get(0));
places.add(0, places.get(places.size()-2));
final CircuitMapPagerAdapter adapter = new CircuitMapPagerAdapter(getContext(), viewModel) {
@Override
public void callback(long placeId){
Log.i("callbackTest", "from fragment");
Log.i("callbackTest", "id: " +placeId);
MainActivity activity = (MainActivity)getActivity();
activity.showPlaceDetail(placeId, false);
}
@Override
public void leftButton(){
viewPager.arrowScroll(View.FOCUS_LEFT);
}
@Override
public void rightButton(){
viewPager.arrowScroll(View.FOCUS_RIGHT);
}
};
viewPager.setAdapter(adapter);
viewPager.setCurrentItem(1, false);
viewPager.setVisibility(View.VISIBLE);
circuitLabelLayout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
RelativeLayout circuitLabelLayout = getView().findViewById(R.id.circuitLabelLayout);
circuitLabelLayout.getViewTreeObserver().removeOnGlobalLayoutListener(this);
int topPadding = circuitLabelLayout.getHeight();
int bottomPadding = viewPager.getHeight();
map.setPadding(0, topPadding, 0 , bottomPadding);
}
});
//todo: remove this and rework panel so that viewpager is hidden until user selects a node
int selectedPosition = viewPager.getCurrentItem();
circuitMarkers.get(selectedPosition-1).setIcon(MapUtils.bitmapDescriptorFromVector(FragmentMap.this.getContext(), R.drawable.marker_circuit));
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
if (position == circuitMarkers.size()+1) {
viewPager.setCurrentItem(1, false);
return;
}
if (position == 0) {
viewPager.setCurrentItem(circuitMarkers.size(), false); // false will prevent sliding animation of view pager
return;
}
LatLng location = circuitMarkers.get(position-1).getPosition();
map.animateCamera(CameraUpdateFactory.newLatLng(location));
updateCircuitActiveMarker(circuitMarkers.get(position-1));
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
LatLngBounds.Builder boundsBuilder = new LatLngBounds.Builder();
final PolylineOptions polylineOptions = new PolylineOptions();
for (LatLng node : path) {
polylineOptions.add(node);
boundsBuilder.include(node);
}
map.addPolyline(polylineOptions);
LatLngBounds bounds = boundsBuilder.build();
int width = getResources().getDisplayMetrics().widthPixels;
int padding = (int)(width*0.2); // offset from edges of the map in pixels
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngBounds(bounds, padding);
map.animateCamera(cameraUpdate);
currentState = STATE_CIRCUIT;
}
public void closeCircuit(){
hideCurrentState();
activateStatePlaces();
}
public void activateStatePlaces(){
refreshMarkers();
//filtersLayout.setVisibility(View.VISIBLE);
setupFilters(getView());
filtersLayout.setVisibility(View.VISIBLE);
currentState = STATE_PLACES;
}
private static class AddMarkersAsyncTask extends AsyncTask<Void, Void, List<PlaceCluster>> {
private WeakReference<FragmentMap> fragment;
private final AppDatabase mDb;
private List<Integer> categories;
public AddMarkersAsyncTask(FragmentMap fragment, AppDatabase db, List<Integer> categories) {
this.fragment = new WeakReference<>(fragment);
this.mDb = db;
this.categories = categories;
}
@Override
protected List<PlaceCluster> doInBackground(final Void... params) {
List<PlaceCluster> clusters = new ArrayList<>();
for (int category : categories) {
List<Place> placesOfCategory = mDb.place().getListByCategory(category);
for (Place place : placesOfCategory) {
PlaceCluster cluster = new PlaceCluster(new LatLng(place.getLat(), place.getLng()), place.getId(), category);
clusters.add(cluster);
}
}
return clusters;
}
@Override
protected void onPostExecute(List<PlaceCluster> clusters) {
final FragmentMap fragment = this.fragment.get();
if (fragment != null) {
fragment.addClusters(clusters);
}
}
}
private static class ShowCircuitAsyncTask extends AsyncTask<Void, Void, CircuitMapViewModel> {
private WeakReference<FragmentMap> fragment;
private final AppDatabase mDb;
private long circuitId;
public ShowCircuitAsyncTask(FragmentMap fragment, AppDatabase db, long id) {
this.fragment = new WeakReference<>(fragment);
this.mDb = db;
this.circuitId = id;
}
@Override
protected CircuitMapViewModel doInBackground(final Void... params) {
CircuitMapViewModel viewModel = new CircuitMapViewModel(mDb, circuitId);
return viewModel;
}
@Override
protected void onPostExecute(CircuitMapViewModel viewModel) {
final FragmentMap fragment = this.fragment.get();
if (fragment != null) {
fragment.showCircuit(viewModel);
}
}
}
private static class ShowPlaceAsyncTask extends AsyncTask<Void, Void, Place> {
private WeakReference<FragmentMap> fragment;
private final AppDatabase mDb;
private long placeId;
public ShowPlaceAsyncTask(FragmentMap fragment, AppDatabase db, long id) {
this.fragment = new WeakReference<>(fragment);
this.mDb = db;
this.placeId = id;
}
@Override
protected Place doInBackground(final Void... params) {
Place place = mDb.place().selectByIdSynchronous(placeId);
Log.i(TAG, "selecting place by id: " + placeId);
Log.i(TAG, "place: " + place.getName());
return place;
}
@Override
protected void onPostExecute(Place place) {
final FragmentMap fragment = this.fragment.get();
if (fragment != null) {
fragment.selectPlace(place);
}
}
}
private static class GMapV2DirectionAsyncTask extends AsyncTask<String, Void, NavResponse> {
private LatLng start, end;
private String mode;
private WeakReference<FragmentMap> fragment;
private final AppDatabase mDb;
private long placeId;
private String apiKey;
public GMapV2DirectionAsyncTask(FragmentMap fragment, AppDatabase db, long id, LatLng start) {
this.fragment = new WeakReference<>(fragment);
this.mDb = db;
this.placeId = id;
this.apiKey = fragment.getContext().getResources().getString(R.string.google_maps_key);
this.start = start;
this.mode = GMapV2DirectionParser.MODE_WALKING;
}
@Override
protected NavResponse doInBackground(String... params) {
Place place = mDb.place().selectByIdSynchronous(placeId);
this.end = place.getPosition();
String url = "https://maps.googleapis.com/maps/api/directions/xml?"
+ "origin=" + start.latitude + "," + start.longitude
+ "&destination=" + end.latitude + "," + end.longitude
+ "&sensor=false&units=metric&mode=" + mode
+"&key=" + apiKey;
Log.d("url", url);
try {
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
con.setDoOutput(true);
int responseCode = con.getResponseCode();
Log.d("route", "Sending 'Get' request to URL : " + url+"--"+responseCode);
DocumentBuilder builder = DocumentBuilderFactory.newInstance()
.newDocumentBuilder();
Document doc = builder.parse(con.getInputStream());
GMapV2DirectionParser md = new GMapV2DirectionParser();
ArrayList<LatLng> directionPoint = md.getDirection(doc);
return new NavResponse(place, directionPoint);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(NavResponse navResponse) {
try {
Log.d("route", "doc != null");
final FragmentMap fragment = this.fragment.get();
if (fragment != null) {
fragment.startNavigation(navResponse);
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected void onPreExecute() {
}
@Override
protected void onProgressUpdate(Void... values) {
}
}
//returns true if back was handled
public boolean backPressed(){
if (currentState == STATE_CIRCUIT) {
Log.i(TAG, "circuit state");
if (activeMarker != null) {
Log.i(TAG, "marker !null");
deactivateCircuitNode();
return true;
}
}
if (currentState == STATE_NAVIGATION_DETAIL) {
hidePlaceDetail();
return true;
}
//todo: if there is circuit displayed, show dialog to make sure they want to close it
if (currentState != STATE_PLACES) {
hideCurrentState();
activateStatePlaces();
return true;
}
return false;
}
public void enableMyLocation() {
try {
map.setMyLocationEnabled(true);
} catch (SecurityException e) {
}
}
} | true |
b089034bcd2a9326bff026edbbb31d94f4da200e | Java | NikhilaGaddam/TechMahindraDay1 | /Vehicle.java | UTF-8 | 130 | 1.9375 | 2 | [] | no_license | /* Abstract class */
package org.TechMDay1.app;
public abstract class Vehicle
{
abstract public void Bike();
}
| true |
6be081f41d677cee42bf1c3e012a4c435cb9c650 | Java | ducquy2200/Tic-Tac-Toe | /Raw Code/TicTacWindow.java | UTF-8 | 6,893 | 3.53125 | 4 | [] | no_license | /**
* Name: Quy Do
* Date: 14/12/2017
*
* Purpose: Java program will initiate and run the game Tic Tac Toe.
* The program has JFrame, JLabel and Font to support and help run
* the graphic of the game. The game will let the users play and
* determine whether there is a winner or the game is a tie.
*
*
* Constructors(in class TicTacWindow:
* TicTacToeWindow()
*
* Functions(in class TicTacWindow):
* actionPerformed - void
* mousePressed - void
* mouseReleased - void
* mouseEntered - void
* mouseExited - void
* mouseClicked - void
* main - void
*
* Constructors(in class TicTacRules):
* TicTacRules()
*
* Functions(in class TicTacRules):
* win - void
* gameOver - void
*/
package tictactoe;
import java.awt.*;
import java.awt.event.*;
import javax.swing.AbstractButton;
import javax.swing.JButton;
import javax.swing.JFrame; //needed to use swing components e.g. JFrame
import javax.swing.JLabel;
public class TicTacWindow extends JFrame implements ActionListener,MouseListener{
// Set up constants for width and height of frame
static final int WIDTH = 400;
static final int HEIGHT = 400;
// Set up constants for the interval between the position of the JBuottons of the board
private static int bWidth = 100;
private static int bHeight = 50;
//all the necessary JButtons, JLabel and Font
protected static JButton[][] button;
protected static JButton exitButton, resetButton;
protected static JLabel statusLabel;
protected static Font fancyFont;
//click counter and the game over check
protected static int click=0;
protected static boolean gameOver = false;
// default constructor
public TicTacWindow(String title) {
// Set the title of the frame, must be before variable declarations
super(title);
//set up the general frame
getContentPane().setLayout(null);
getContentPane().setBackground(Color.getHSBColor(120, 200, 150));
//create buttons for the board of the game
button = new JButton[3][3];
for (int column=0; column<3; column++){
for (int row=0; row<3; row++){
button[column][row] = new JButton("");
button[column][row].setBackground(SystemColor.control);
button[column][row].setLocation((50+(column*bWidth)), (100+(row*bHeight)));
button[column][row].setSize(bWidth,bHeight);
getContentPane().add(button[column][row]);
//Set all buttons to work with the event handlers
button[column][row].addActionListener(this);
button[column][row].addMouseListener(this);
}
}
// Create and add a status label JLabel
statusLabel = new JLabel("Start Playing!");
fancyFont = new Font("Times New Roman", Font.BOLD, 28);
statusLabel.setFont(fancyFont);
statusLabel.setBounds(110,30,250, 45);
getContentPane().add(statusLabel);
//create and add an exit button JButton
exitButton = new JButton("Exit");
exitButton.setBackground(SystemColor.control);
exitButton.setLocation(250, 300);
exitButton.setSize(100,40);
getContentPane().add(exitButton);
//create and add a restart button JButton
resetButton = new JButton("New Game");
resetButton.setBackground(SystemColor.control);
resetButton.setLocation(50, 300);
resetButton.setSize(100,40);
getContentPane().add(resetButton);
//Set the exit and restart buttons to work with the event handlers
resetButton.addMouseListener(this);
exitButton.addMouseListener(this);
resetButton.addActionListener(this);
exitButton.addActionListener(this);
}
//This is the event handler for the button
public void actionPerformed(ActionEvent e) {
//Ask the event which button it represents
//exit the game if the user chooses the exit button
if (e.getActionCommand().equals("Exit")){
System.exit(0);
}
//restart the game if the user chooses the exit button
if (e.getActionCommand().equals("New Game")){
for (int column=0; column<3; column++){
for (int row=0; row<3; row++){
button[column][row].setEnabled(true);
button[column][row].setText("");
}
}
statusLabel.setText("Start Playing!");
gameOver=false;
click=0;
}
//change the text of the buttons in the board if the user chooses them
if (e.getActionCommand().equals("")){
click++;
if((click%2)==1){
((AbstractButton) e.getSource()).setText("X");
statusLabel.setText("Player 2's Turn!");
}else if(click==0){
statusLabel.setText("Start Playing!");
}else{
((AbstractButton) e.getSource()).setText("O");
statusLabel.setText("Player 1's Turn!");
}
}
//run the methods to check the winner and to check if the game is over
TicTacRules.win();
TicTacRules.gameOver();
}
//method which initiates when the mouse is pressed
public void mousePressed(MouseEvent event) {
System.out.println("MousePressed");
}
//method which initiates when the mouse is released
public void mouseReleased(MouseEvent event) {
System.out.println("MouseReleased");
}
//method which initiates when the mouse enters a button
public void mouseEntered(MouseEvent event) {
System.out.println("MouseEntered");
}
//method which initiates when the mouse exits a button
public void mouseExited(MouseEvent event) {
System.out.println("MouseExited");
}
//method which initiates when the mouse clicks on a button
public void mouseClicked(MouseEvent event) {
String s;
if (event.getButton() == 1)
s = "Right";
else s = "Left"; // Ignores the middle button case
System.out.printf("Mouse" + s + "-Clicked " + event.getClickCount() +
" times successively ", event);
}
public static JButton getButton(int columnNum,int rowNum){
return(button[columnNum][rowNum]);
}
//the main method of the class which will initiate the game
public static void main(String args[]) {
// Instantiate a FirstApplication object so you can display it
TicTacWindow frame = new TicTacWindow("TicTacToe Game");
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
// Set the size of the application window (frame)
frame.setSize(WIDTH, HEIGHT);
frame.setVisible(true); // Show the application (frame)
frame.setResizable(false); // Make the size of the window fixed
}
}
| true |
1a69c9297f7a6408b8665dc524a5ee6dd83796b3 | Java | hrishikeshpujari1902/Note4You | /app/src/main/java/com/HrishikeshPujari/Note4youFirebase/NoteClass.java | UTF-8 | 1,123 | 2.25 | 2 | [] | no_license | package com.HrishikeshPujari.Note4youFirebase;
import java.text.DateFormat;
import java.util.Calendar;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.util.Base64;
import java.io.ByteArrayOutputStream;
import java.util.Date;
public class NoteClass {
private String currentDate;
private String currentTime;
private String title;
private String description;
private String imageUrl;
public NoteClass(String title1, String description1, String imageUrl1,String currentDate1,String currentTime1) {
title = title1;
currentDate= currentDate1;
description = description1;
imageUrl= imageUrl1;
currentTime= currentTime1;
}
public NoteClass(){
}
public String getCurrentDate() {
return currentDate;
}
public String getCurrentTime() {
return currentTime;
}
public String getTitle() {
return title;
}
public String getDescription() {
return description;
}
public String getImageUrl(){return imageUrl;}
}
| true |
c300c416e7d3c52f130c6e1ff82d383ee3a6aaf2 | Java | djm-im/jLocalCoin | /src/main/java/im/djm/p2p/node/BlockChainNode.java | UTF-8 | 4,361 | 2.453125 | 2 | [
"MIT"
] | permissive | package im.djm.p2p.node;
import java.util.ArrayList;
import java.util.List;
import im.djm.blockchain.BlockChain;
import im.djm.blockchain.BlockChainStatus;
import im.djm.blockchain.block.Block;
import im.djm.blockchain.block.Miner;
import im.djm.coin.NullTxData;
import im.djm.coin.tx.Tx;
import im.djm.coin.tx.TxData;
import im.djm.coin.txhash.TxHash;
import im.djm.coin.utxo.Utxo;
import im.djm.wallet.WalletAddress;
/**
* @author djm.im
*/
public class BlockChainNode {
static final int REWARD = 100;
private BlockChain blockChain;
private TxUtxoPoolsNode txUtxoPool;
private WalletAddress minerAddress;
private List<BlockChainNode> network = new ArrayList<>();
public BlockChainNode() {
this.initBlockChainAndPools();
}
public BlockChainNode(WalletAddress minerAddress) {
this.initMinerAddress(minerAddress);
this.initBlockChainAndPools();
this.initNullTxBlock();
}
private void initMinerAddress(WalletAddress minerAddress) {
if (minerAddress == null) {
throw new NullWalletAddressException("Wallet address cannot be null.");
}
this.minerAddress = minerAddress;
}
private void initBlockChainAndPools() {
this.txUtxoPool = new TxUtxoPoolsNode();
this.blockChain = new BlockChain();
}
private void initNullTxBlock() {
Block nullTxBlock = this.createNullTxBlock();
this.blockChain.add(nullTxBlock);
}
private Block createNullTxBlock() {
NullTxData nullTxData = new NullTxData();
Block txBlock = this.generateNewTxBlock(nullTxData);
return txBlock;
}
public BlockChainStatus status() {
return this.blockChain.status();
}
public List<Utxo> getAllUtxo() {
return this.txUtxoPool.getAllUtxo();
}
public Tx getTxFromPool(TxHash txId) {
return this.txUtxoPool.getTxFromPool(txId);
}
public String printBlockChain() {
return this.blockChain.toString();
}
public long getBalance(WalletAddress walletAddress) {
return this.txUtxoPool.getBalance(walletAddress);
}
public List<Utxo> getUtxoFor(WalletAddress walletAddress) {
return this.txUtxoPool.getUtxoFor(walletAddress);
}
public void sendCoin(Tx newTx) {
Block block = this.createTxDataBlock(newTx);
this.blockChain.add(block);
this.announceNewBlockToNetwork(block);
}
private void announceNewBlockToNetwork(Block block) {
this.network.forEach(node -> node.annonceNewBlockCreated(block));
}
private void annonceNewBlockCreated(Block block) {
this.update(block);
}
private Block createTxDataBlock(Tx tx) {
TxData txData = new TxData();
txData.add(tx);
Block block = this.generateNewTxBlock(txData);
return block;
}
private Block generateNewTxBlock(final TxData txData) {
TxData txDataLocal = this.addCoinbaseTx(txData, BlockChainNode.REWARD);
Block prevBlock = blockChain.getTopBlock();
Block newBlock = Miner.createNewBlock(prevBlock, txDataLocal);
this.updatePools(newBlock);
return newBlock;
}
private TxData addCoinbaseTx(TxData txData, long reward) {
if (this.minerAddress == null) {
throw new NullBlockChainNodeException("Miner wallet is not set.");
}
Tx coinbaseTx = new Tx(this.minerAddress, reward);
txData.addCoinbaseTx(coinbaseTx);
return txData;
}
public void sync() {
if (this.network == null || this.network.isEmpty()) {
throw new NullNetworkException("No netwrok: The node didn't discover network.");
}
// TODO
// Improve algorithm for sync
// for now just sync with the first node
BlockChainNode bcn = this.network.get(0);
if (!this.status().equals(bcn.status())) {
long start = this.status().getLength();
List<Block> blocksFrom = bcn.getBlocksFrom(start);
this.updateBlockChain(blocksFrom);
}
}
private void updateBlockChain(List<Block> newBlocks) {
newBlocks.forEach(block -> this.update(block));
}
private void update(Block block) {
this.blockChain.add(block);
this.updatePools(block);
}
private void updatePools(Block block) {
TxData txData = (TxData) block.getData();
this.txUtxoPool.updateTxPoolAndUtxoPool(txData);
}
private List<Block> getBlocksFrom(long start) {
return this.blockChain.getBlocksFrom(start);
}
public void addNode(BlockChainNode bcn) {
this.network.add(bcn);
}
public void setMinerAddress(WalletAddress minerAddress) {
this.minerAddress = minerAddress;
}
@Override
public String toString() {
return this.blockChain.toString();
}
}
| true |
f16ba556ed5e5607159f0e73deaad91800541b98 | Java | XealRedan/cos-sim | /modules/visualizer/src/main/java/ru/cos/sim/visualizer/scene/ComplexDisplayList.java | UTF-8 | 1,254 | 2.53125 | 3 | [] | no_license | package ru.cos.sim.visualizer.scene;
import java.util.ArrayList;
import ru.cos.sim.visualizer.exception.OglException;
import ru.cos.sim.visualizer.renderer.impl.IRenderable;
public class ComplexDisplayList extends BasicRenderable{
protected ArrayList<IRenderable> objects;
// public ComplexDisplayList()
// {
// super(RenderMode.DisplayList);
//
// objects = new ArrayList<IRenderable>();
// }
//
// public void construct()
// {
// super.begin();
// for (IRenderable r : objects) {
// r.render();
// }
// super.end();
// }
public void addObject(IRenderable r)
{
if (isConstructed()) throw new OglException("LayerDisplayList is already constructed");
objects.add(r);
}
public ComplexDisplayList(int uid, RenderMode mode) {
super(uid, mode);
// TODO Auto-generated constructor stub
}
public ComplexDisplayList(int uid) {
super(uid);
// TODO Auto-generated constructor stub
}
public void render()
{
// if (!isConstructed()) {
// construct();
// }
// super.render();
}
public void disposeTempResources()
{
objects = null;
}
@Override
protected void postdraw() {
// TODO Auto-generated method stub
}
@Override
protected void predraw() {
// TODO Auto-generated method stub
}
}
| true |
a9fce65dd754d3cb65af8b571545a9bc394df306 | Java | AnuSindhura/Penguin-Care-Website | /src/main/java/se/kth/sda7/wdgroupproject/movies/MovieService.java | UTF-8 | 857 | 2.375 | 2 | [] | no_license | package se.kth.sda7.wdgroupproject.movies;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import se.kth.sda7.wdgroupproject.movies.Movie;
import se.kth.sda7.wdgroupproject.movies.MovieRepository;
import java.util.List;
@Service
public class MovieService {
@Autowired
public MovieRepository repository;
public List<Movie> getAll() {
return repository.findAll();
}
public Movie save(Movie newMovie) {
return repository.save(newMovie);
}
public void deleteById(Long id) {
repository.deleteById(id);
}
public Movie update(Movie movie) throws Exception {
return repository.findById(movie.getId()).map(r -> {
return repository.save(movie);
}).orElseThrow(() -> new Exception("Movie not found"));
}
}
| true |
de634e5d237471a908cf4cb12a041ac33fb22374 | Java | jcdourado/Financeiro | /src/teste/TesteRecebimentoDao.java | UTF-8 | 1,424 | 2.3125 | 2 | [] | no_license | package teste;
import static org.junit.Assert.*;
import java.sql.SQLException;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import dao.RecebimentoDao;
import model.Recebimento;
import model.Usuario;
public class TesteRecebimentoDao {
private static RecebimentoDao dao;
private static Usuario usuario;
private static Recebimento recebimento;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
dao = new RecebimentoDao();
usuario = new Usuario();
usuario.setNome("julio");
usuario.setUsuario("julio43");
usuario.setEmail("jcd17071997");
usuario.setSenha("43432");
recebimento = new Recebimento();
recebimento.setDescricao("teste recebimento");
recebimento.setFrequencia(12);
recebimento.setNome("recebimento da r443ua3");
recebimento.setValor(423555);
recebimento.setUsuario(usuario);
recebimento.setId(1);
}
// @Test
// public void adicionar() throws ClassNotFoundException, SQLException {
// assertTrue(dao.adicionar(recebimento));
// }
// @Test
// public void alterar() throws ClassNotFoundException, SQLException {
// assertTrue(dao.alterar(recebimento));
// }
@Test
public void excluir() throws ClassNotFoundException, SQLException {
assertTrue(dao.remover(recebimento.getId()));
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
}
}
| true |
54d280b9c90a7b42846739e466d3728d22ade99e | Java | KoraNetwork/kora_android | /app/src/main/java/com/kora/android/presentation/model/builder/BorrowEntityBuilder.java | UTF-8 | 4,157 | 2.328125 | 2 | [] | no_license | package com.kora.android.presentation.model.builder;
import com.kora.android.presentation.enums.BorrowState;
import com.kora.android.presentation.enums.BorrowType;
import com.kora.android.presentation.enums.Direction;
import com.kora.android.presentation.model.BorrowEntity;
import com.kora.android.presentation.model.UserEntity;
import java.util.Date;
import java.util.List;
public class BorrowEntityBuilder {
private String mId;
private Direction mDirection;
private BorrowState mState;
private double mFromAmount;
private double mToAmount;
private int mRate;
private String mAdditionalNote;
private Date mStartDate;
private Date mMaturityDate;
private Date mCreatedAt;
private UserEntity mSender;
private UserEntity mReceiver;
private List<UserEntity> mGuarantors;
private String mLoanId;
private BorrowType mType;
private double mFromTotalAmount;
private double mToTotalAmount;
private double mFromBalance;
private double mToBalance;
private double mFromReturnedMoney;
private double mToReturnedMoney;
public BorrowEntityBuilder setId(String id) {
mId = id;
return this;
}
public BorrowEntityBuilder setDirection(Direction direction) {
mDirection = direction;
return this;
}
public BorrowEntityBuilder setState(BorrowState state) {
mState = state;
return this;
}
public BorrowEntityBuilder setFromAmount(double fromAmount) {
mFromAmount = fromAmount;
return this;
}
public BorrowEntityBuilder setToAmount(double toAmount) {
mToAmount = toAmount;
return this;
}
public BorrowEntityBuilder setRate(int rate) {
mRate = rate;
return this;
}
public BorrowEntityBuilder setAdditionalNote(String additionalNote) {
mAdditionalNote = additionalNote;
return this;
}
public BorrowEntityBuilder setStartDate(Date startDate) {
mStartDate = startDate;
return this;
}
public BorrowEntityBuilder setMaturityDate(Date maturityDate) {
mMaturityDate = maturityDate;
return this;
}
public BorrowEntityBuilder setCreatedAt(Date createdAt) {
mCreatedAt = createdAt;
return this;
}
public BorrowEntityBuilder setSender(UserEntity sender) {
mSender = sender;
return this;
}
public BorrowEntityBuilder setReceiver(UserEntity receiver) {
mReceiver = receiver;
return this;
}
public BorrowEntityBuilder setGuarantors(List<UserEntity> guarantors) {
mGuarantors = guarantors;
return this;
}
public BorrowEntityBuilder setLoanId(String loanId) {
mLoanId = loanId;
return this;
}
public BorrowEntityBuilder setType(BorrowType type) {
mType = type;
return this;
}
public BorrowEntityBuilder setFromTotalAmount(double fromTotalAmount) {
mFromTotalAmount = fromTotalAmount;
return this;
}
public BorrowEntityBuilder setToTotalAmount(double toTotalAmount) {
mToTotalAmount = toTotalAmount;
return this;
}
public BorrowEntityBuilder setFromBalance(double fromBalance) {
mFromBalance = fromBalance;
return this;
}
public BorrowEntityBuilder setToBalance(double toBalance) {
mToBalance = toBalance;
return this;
}
public BorrowEntityBuilder setFromReturnedMoney(double fromReturnedMoney) {
mFromReturnedMoney = fromReturnedMoney;
return this;
}
public BorrowEntityBuilder setToReturnedMoney(double toReturnedMoney) {
mToReturnedMoney = toReturnedMoney;
return this;
}
public BorrowEntity createBorrowEntity() {
return new BorrowEntity(mId, mDirection, mState, mFromAmount, mToAmount,
mRate, mAdditionalNote, mStartDate, mMaturityDate, mCreatedAt,
mSender, mReceiver, mGuarantors, mLoanId, mType,
mFromTotalAmount, mToTotalAmount, mFromBalance, mToBalance,
mFromReturnedMoney, mToReturnedMoney);
}
} | true |
f476c9997fabc28663703159be6c730fa7d5d270 | Java | 2491-NoMythic/2018-Tempest-Gradle | /src/main/java/com/_2491nomythic/tempest/commands/LocateCube.java | UTF-8 | 2,224 | 3.4375 | 3 | [] | no_license | package com._2491nomythic.tempest.commands;
/**
* Rotates the drivetrain until it has centered on a cube as according to the limelight
*/
public class LocateCube extends CommandBase {
private double leftSpeed, rightSpeed, tolerance;
private boolean direction, tune;
/**
* Rotates the drivetrain until it has centered on a cube as according to the limelight
* @param direction Pass true to rotate left, false to rotate right
*/
public LocateCube(boolean direction) {
// Use requires() here to declare subsystem dependencies
// eg. requires(chassis);
requires(drivetrain);
this.direction = direction;
leftSpeed = .25;
rightSpeed = .25;
tolerance = .5;
}
// Called just before this Command runs the first time
protected void initialize() {
if (direction) {
leftSpeed *= -1;
}
else {
rightSpeed *= -1;
}
drivetrain.setVisionMode();
tune = false;
System.out.println("Target Status: " + drivetrain.hasTarget());
}
// Called repeatedly when this Command is scheduled to run
protected void execute() {
if (!drivetrain.hasTarget() && !tune) {
drivetrain.drivePercentOutput(leftSpeed, rightSpeed);
}
else if (Math.abs(drivetrain.getX()) > 0 + tolerance && drivetrain.hasTarget() && !tune) {
drivetrain.drivePercentOutput(leftSpeed, rightSpeed);
if (Math.abs(drivetrain.getX()) > 0 + (tolerance * 2)) {
tune = true;
}
}
if (tune && drivetrain.getX() < 0 - tolerance) {
drivetrain.drivePercentOutput(Math.abs(-leftSpeed),
Math.abs(rightSpeed));
}
else if (tune && drivetrain.getX() > 0 + tolerance) {
drivetrain.drivePercentOutput(Math.abs(leftSpeed), -Math.abs(rightSpeed));
}
}
// Make this return true when this Command no longer needs to run execute()
protected boolean isFinished() {
return false;
}
// Called once after isFinished returns true
protected void end() {
drivetrain.setCameraMode();
}
// Called when another command which requires one or more of the same
// subsystems is scheduled to run
protected void interrupted() {
end();
}
}
| true |
37aab24c60f7434e34e731eeab5d6935975ff7ca | Java | hexanome4if/SMART_H4234 | /SMART_back-master/src/main/java/fr/insa_lyon/smart_back/model/ProfileDTO.java | UTF-8 | 1,834 | 2.03125 | 2 | [] | no_license | package fr.insa_lyon.smart_back.model;
import lombok.Data;
import javax.persistence.*;
import java.util.Date;
import java.util.List;
@Data
public class ProfileDTO {
private long userId;
private String userName;
private String displayName;
private String mail;
private String password;
private Date birth;
private String tel;
private boolean counselor;
private boolean verify;
private String status;
private String photo;
private String identityDocument;
private String device;
private long levelId;
private Level level;
private long avatarId;
private Avatar avatar;
private List<Tag> userAbilityTags;
private List<Tag> userInterestTags;
public List<Experience> experiences;
public List<Education> educations;
public Iterable<QuestionAnswer> faqs;
public ProfileDTO() {}
public ProfileDTO(User user) {
this.userId = user.getUserId();
this.userName = user.getUserName();
this.displayName = user.getDisplayName();
this.mail = user.getMail();
this.password = user.getPassword();
this.birth = user.getBirth();
this.tel = user.getTel();
this.counselor = user.isCounselor();
this.verify = user.isVerify();
this.status = user.getStatus();
this.photo = user.getPhoto();
this.identityDocument = user.getIdentityDocument();
this.device = user.getDevice();
this.level = user.getLevel();
this.levelId = user.getLevelId();
this.avatar = user.getAvatar();
this.avatarId = user.getAvatarId();
this.userAbilityTags = user.getUserAbilityTags();
this.userInterestTags = user.getUserInterestTags();
this.educations = user.getEducations();
this.experiences = user.getExperiences();
}
}
| true |
30e6b556e944a0cfbd922dfecab3587c56fdf524 | Java | ashwinnishad/ChatBot | /bot.java | UTF-8 | 3,591 | 2.90625 | 3 | [] | no_license | import org.jibble.pircbot.PircBot;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import com.google.gson.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.text.DecimalFormat;
public class bot extends PircBot
{
static final String defaultLocation = "75080"; // Provide any default zip-code.
final Pattern regex = Pattern.compile("(\\d{5})"); // to extract zip code
String temperature;
public bot()
{
this.setName("WeatherBot"); //this is the name the bot will use to join the IRC server
} // end of constructor
public void onMessage(String channel, String sender, String login, String hostname, String message)
{
message = message.toLowerCase();
if (message.contains("weather"))
{
String location = defaultLocation;
String[] words = message.split(" ");
if (words.length == 2)
{
if (words[0].equals("weather"))
{
location = words[1];
}
else
{
location = words[0];
}
}
else
{
Matcher matcher = regex.matcher(message);
if (matcher.find())
{
location = matcher.group(1);
}
else
{
sendMessage(channel, "Unable to determine location. Assuming Richardson."); // Change city name here based on provided default zip-code.
}
}
temperature = startWebRequest(location);
sendMessage(channel, "Hey " + sender + "! "+ temperature);
}// end of outer if
} // end of class onMessage
static String startWebRequest(String zipcode)
{
String weatherURL = "http://api.openweathermap.org/data/2.5/weather?zip="+zipcode+"&appid=""; // Get Application ID from OpenWeather API
StringBuilder result = new StringBuilder();
try
{
URL url = new URL(weatherURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null)
{
result.append(line);
}
rd.close();
return parseJson(result.toString());
}
catch(Exception e)
{return "Error! Exception: " + e;}
} // end of startWebRequest
static String parseJson(String json)
{
JsonObject object = new JsonParser().parse(json).getAsJsonObject();
String cityName = object.get("name").getAsString();
JsonObject main = object.getAsJsonObject("main");
double temp = main.get("temp").getAsDouble();
temp = (temp-273.15) * 1.8 + 32;
double tempMin = main.get("temp_min").getAsDouble();
tempMin = (tempMin-273.15) * 1.8 + 32;
double tempMax = main.get("temp_max").getAsDouble();
tempMax = (tempMax-273.15) * 1.8 + 32;
DecimalFormat df = new DecimalFormat("####0.0");
// Bot output
return "The current temperature in " + cityName + " is " + df.format(temp) + "˚F with a high of " + df.format(tempMax) +
"˚F and a low of " + df.format(tempMin) + "˚F." ;
}// end of parseJson
} // end of class
| true |
c0d47f4c8a41af2196d501b622c2300d9bbd3e5c | Java | wudafang/SHIYAN | /java基础/java基础第四章/src/R7.java | GB18030 | 526 | 3.046875 | 3 | [] | no_license | import java.util.Scanner;
public class R7 {
public static void main(String[] args){
Scanner s=new Scanner(System.in);
int m=0;
do{
System.out.println("0:˳ 1 2 3̵");
m=s.nextInt();
switch(m){
case 1:
System.out.println("ִн");
break;
case 2:
System.out.println("ִ");
break;
case 3:
System.out.println("̵ִ");
break;
}
}while(m!=0);
System.out.println("ӭ´ʹ");
}
}
| true |
9a0a6e88056b4f9808024f7f6bbcdd0535bd9d48 | Java | Weiran-Lin/MyEventPlanner | /app/src/main/java/com/example/linweiran/myeventplanner/view/EventListActivity.java | UTF-8 | 3,202 | 1.945313 | 2 | [] | no_license | package com.example.linweiran.myeventplanner.view;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import com.example.linweiran.myeventplanner.R;
import com.example.linweiran.myeventplanner.model.DatabaseOperations;
import com.example.linweiran.myeventplanner.view.model.ViewPagerAdapter;
public class EventListActivity extends AppCompatActivity {
private static final String DEBUG_TAG = EventListActivity.class.getName();
Toolbar tabBar;
TabLayout tabLayout;
ViewPager viewPager;
ViewPagerAdapter viewPagerAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_event_list);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent i = new Intent(EventListActivity.this, AddEventActivity.class);
i.putExtra("callFrom",EventListActivity.class.getName());
startActivity(i);
}
});
tabBar = (Toolbar) findViewById(R.id.tabBar);
setSupportActionBar(tabBar);
tabLayout = (TabLayout) findViewById(R.id.tabLayout);
viewPager = (ViewPager) findViewById(R.id.viewPager);
viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
viewPagerAdapter.addFragments(new ListFragment(), "List View");
viewPagerAdapter.addFragments(new CalendarFragment(), "Calendar View");
viewPager.setAdapter(viewPagerAdapter);
tabLayout.setupWithViewPager(viewPager);
Intent intent = new Intent(this, CheckTimeService.class);
startService(intent);
//create database
DatabaseOperations db = new DatabaseOperations(this);
SQLiteDatabase sqLiteDatabase = db.getWritableDatabase();
db.onUpgrade(sqLiteDatabase, 1, 2);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_event_list, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
Intent i = new Intent(this, MySettingsActivity.class);
startActivity(i);
return true;
}
return super.onOptionsItemSelected(item);
}
}
| true |
942b8d09819d91954a971fc63f63cdd3e049ca13 | Java | mhmtk/AutoTextMate | /src/com/mhmt/autoreplymate/broadcastreceivers/SMSReceiver.java | UTF-8 | 3,857 | 2.5 | 2 | [] | no_license | package com.mhmt.autoreplymate.broadcastreceivers;
import com.mhmt.autoreplymate.database.DatabaseManager;
import com.mhmt.autoreplymate.dataobjects.Rule;
import com.mhmt.autoreplymate.dataobjects.SMS;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.BaseColumns;
import android.provider.ContactsContract;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.util.Log;
import android.widget.Toast;
/**
*
* @author Mehmet Kologlu
* @version November May 29, 2015
*
*/
public class SMSReceiver extends BroadcastReceiver{
private static long delay = 2000; // 2 secs delay before responding
private String logTag = "SMSReceiver";
private SmsManager smsManager;
private Context context;
private DatabaseManager dbManager;
@Override
public void onReceive(final Context c, Intent intent) {
context = c;
String phoneNo = "";
Bundle bundle = intent.getExtras();
SmsMessage[] msg = null;
if (bundle != null) {
Log.i(logTag, "Non-null intent received");
dbManager = new DatabaseManager(c);
Object[] pdus = (Object[]) bundle.get("pdus");
msg = new SmsMessage[pdus.length];
for (int i=0; i<msg.length; i++) {
msg[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
//get the phoneNo of the sender
phoneNo = msg[i].getOriginatingAddress();
}
//REPLY
final String pn = phoneNo;//re-create phone no string, to make it final
new Handler().postDelayed(new Runnable() { //Handler/Runnable usage in order to delay the reply
public void run() {
smsManager = SmsManager.getDefault();
for (Rule r : dbManager.getEnabledSMSRules()) { //Reply for each rule
if (r.getOnlyContacts() == 1) { // Reply only if the sender no is in the contacts
if (inContacts(pn)) { // Check if the sender is in the contacts
sendSMS(r, pn);
}
}
else {
sendSMS(r, pn);
}
}
}
}, delay );
}
}
/**
* Sends out an SMS to phoneNo using Rule r, also logs this action to SMS table for outbox usage.
* @param r
* @param phoneNo
*/
private void sendSMS(Rule r, String phoneNo) {
// Reply
String replyText = r.getText();
smsManager.sendTextMessage(phoneNo, null, replyText, null, null);
// Add the reply to the Outbox DB
dbManager.addSMS(new SMS(System.currentTimeMillis(), replyText, String.valueOf(phoneNo), r.getName()));
//documentation & feedback
Toast.makeText(context, "Replied to " + phoneNo + ": " + replyText, Toast.LENGTH_SHORT).show();
Log.i(logTag, "Sent out an SMS to " + String.valueOf(phoneNo));
}
/**
* Checks if the given no is in the contacts
*
* @param no The phone no to check for
* @return True if the passed no is saved in the contacts, false otherwise
*/
private boolean inContacts(String no) {
Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(no));
// String name = "?";
ContentResolver contentResolver = context.getContentResolver();
Cursor contactLookup = contentResolver.query(uri,
new String[] {BaseColumns._ID }, //ContactsContract.PhoneLookup.DISPLAY_NAME }
null, null, null);
if (contactLookup != null)
{
try {
if (contactLookup.getCount() > 0) {
Log.i(logTag, contactLookup.getCount() + " contact(s) found with the senders no");
return true;
//name = contactLookup.getString(contactLookup.getColumnIndex(ContactsContract.Data.DISPLAY_NAME));
//String contactId = contactLookup.getString(contactLookup.getColumnIndex(BaseColumns._ID));
}
} finally {
contactLookup.close();
}
}
return false;
}
} | true |
5e4a5b017eb4f96270f8138112e2431e102eebc9 | Java | chaodewen/leetcode | /src/com/leetcode/no6/Solution.java | UTF-8 | 1,109 | 3.328125 | 3 | [] | no_license | package com.leetcode.no6;
public class Solution {
public String convert(String s, int numRows) {
if(numRows <= 1) return s;
int len = s.length(), step = 2 * numRows - 2;
StringBuilder sb = new StringBuilder();
for(int i = 0; i < numRows; i ++)
for(int j = i; j < len; j += step) {
sb.append(s.charAt(j));
if(i != 0 && i != numRows - 1 && j + step - 2 * i < len)
sb.append(s.charAt(j + step - 2 * i));
}
return sb.toString();
}
}
//public class Solution {
// public String convert(String s, int numRows) {
// if(numRows <= 1) return s;
// int div = 2 * numRows - 2, len = s.length();
// int divNum = s.length() < div ? (s.length() == 0 ? 0 : 1) : (s.length() / div + 1);
// StringBuilder sb = new StringBuilder();
// for(int i = 0; i < numRows; i ++)
// for(int j = 0; j < divNum; j ++) {
// int index = j * div + i;
// if(index < len)
// sb.append(s.charAt(index));
// int adjacent = j * div + 2 * numRows - 2 - i;
// if(i != 0 && i != numRows - 1 && adjacent < s.length())
// sb.append(s.charAt(adjacent));
// }
// return sb.toString();
// }
//} | true |
dd7acc1017ebb0d521a14923765558628b543254 | Java | githugme/Online-Cinema-Ticket-booking | /src/main/java/com/PickMyShow/controller/UserController.java | UTF-8 | 2,693 | 2.0625 | 2 | [] | no_license | package com.PickMyShow.controller;
import java.util.List;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException;
import com.PickMyShow.repository.*;
import com.PickMyShow.model.*;
import com.PickMyShow.service.*;
@RestController
@RequestMapping("/user")
@CrossOrigin(origins = "http://localhost:4200")
public class UserController {
@Autowired
UserRepository repo1;
@Autowired
BookRepository repo2;
@Autowired
UserService service;
@PostMapping("/Registration")
public User saveUser(@RequestBody User user) throws Exception
{
String email=user.getEmail();
if(email!=null && !email.equals(""))
{
User obj=service.fetchUserByEmailId(email);
if(obj!=null)
{
throw new Exception("user with " + email + " is already exist");
}
}
User obj=null;
obj=service.saveUser(user);
return obj;
}
// @PostMapping("/Registration")
// public User saveUser1(@RequestBody User user) {
// User userDto = new User();
// UserService.saveUser("user", userDto);
// return "Registration";
// }
@PostMapping("/Login")
public User fetchUserByEmailAndPassword(@RequestBody User user) throws Exception
{
String email=user.getEmail();
String password=user.getPassword();
User obj=null;
if(email!=null && password!=null)
{
obj=service.fetchUserByEmailAndPassword(email, password);
}
if(obj==null)
{
throw new Exception("Please enter valid credentials");
}
return obj;
}
@PostMapping("/Contact")
public Contact saveContactInfo(@RequestBody Contact contact) throws Exception
{
Contact Cobj=service.saveContactInfo(contact);
return Cobj;
}
@PostMapping("/Book-ticket")
public Book saveStudent(@RequestBody Book book) throws Exception
{
Book Bobj=service.saveBooking(book);
return Bobj;
}
}
| true |
e910069a58422354480cb77e6497acdf538ad335 | Java | geniusninedev/EngineeringConverter | /app/src/main/java/com/nineinfosys/engineeringconverter/ConverterActivitiesList/ConversionTorqueListActivity.java | UTF-8 | 14,541 | 1.570313 | 2 | [] | no_license | package com.nineinfosys.engineeringconverter.ConverterActivitiesList;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.print.PrintHelper;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.MobileAds;
import com.nineinfosys.engineeringconverter.Engines.TorqueConverter;
import com.nineinfosys.engineeringconverter.R;
import com.nineinfosys.engineeringconverter.Supporter.ItemList;
import com.nineinfosys.engineeringconverter.Supporter.Settings;
import com.nineinfosys.engineeringconverter.adapter.RecyclerViewConversionListAdapter;
import java.io.File;
import java.io.FileOutputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class ConversionTorqueListActivity extends AppCompatActivity implements TextWatcher {
List<ItemList> list = new ArrayList<ItemList>();
private String stringSpinnerFrom;
private double doubleEdittextvalue;
private EditText edittextConversionListvalue;
private TextView textconversionFrom,textViewConversionShortform;
View ChildView ;
DecimalFormat formatter = null;
private static final int REQUEST_CODE = 100;
private File imageFile;
private Bitmap bitmap;
private PrintHelper printhelper;
private RecyclerView rView;
RecyclerViewConversionListAdapter rcAdapter;
List<ItemList> rowListItem,rowListItem1;
private String strnewtonmeter=null,strnewtoncentimeter=null,strnewtonmillimeter=null,strkilonewtonmeter=null,strdynemeter=null,strdynecentimeter=null,strdynemillimeter=null,strkilogramforcemeter=null,
strkilogramforcecentimeter=null,strkilogramforcemillimeter=null,strgramforcemeter=null,strgramforcecentimeter=null,strgramforcemillimeter=null,strounceforcefoot=null,
strounceforceinch=null,strpoundforcefoot=null,strpoundforceinch=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_conversion_list);
//keyboard hidden first time
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
//customize toolbar
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#59db59")));
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setTitle("Conversion Report");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(Color.parseColor("#0aa828"));
}
MobileAds.initialize(ConversionTorqueListActivity.this, getString(R.string.ads_app_id));
AdView mAdView = (AdView) findViewById(R.id.adViewUnitConverterList);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
//format of decimal pint
formatsetting();
edittextConversionListvalue=(EditText)findViewById(R.id.edittextConversionListvalue) ;
textconversionFrom=(TextView) findViewById(R.id.textViewConversionFrom) ;
textViewConversionShortform=(TextView) findViewById(R.id.textViewConversionShortform) ;
//get the value from temperture activity
stringSpinnerFrom = getIntent().getExtras().getString("stringSpinnerFrom");
doubleEdittextvalue= getIntent().getExtras().getDouble("doubleEdittextvalue");
edittextConversionListvalue.setText(String.valueOf(doubleEdittextvalue));
NamesAndShortform(stringSpinnerFrom);
// Toast.makeText(this,"string1 "+stringSpinnerFrom,Toast.LENGTH_LONG).show();
rowListItem = getAllunitValue(stringSpinnerFrom,doubleEdittextvalue);
//Initializing Views
rView = (RecyclerView) findViewById(R.id.recyclerViewConverterList);
rView.setHasFixedSize(true);
rView.setLayoutManager(new GridLayoutManager(this, 1));
//Initializing our superheroes list
rcAdapter = new RecyclerViewConversionListAdapter(this,rowListItem);
rView.setAdapter(rcAdapter);
edittextConversionListvalue.addTextChangedListener(this);
}
private void NamesAndShortform(String stringSpinnerFrom) {
switch (stringSpinnerFrom) {
case "Newton meter -N*m":
textconversionFrom.setText("Newton meter "); textViewConversionShortform.setText("N*m");
break;
case "Newton centimeter -N*cm":
textconversionFrom.setText("Newton centimeter "); textViewConversionShortform.setText("N*cm");
break;
case "Newton millimeter -N*mm":
textconversionFrom.setText("Newton millimeter "); textViewConversionShortform.setText("N*mm");
break;
case "Kilonewton meter -kN*m":
textconversionFrom.setText("Kilonewton meter "); textViewConversionShortform.setText("kN*m");
break;
case "Dyne meter -dyn*m":
textconversionFrom.setText("Dyne meter "); textViewConversionShortform.setText("dyn*m");
break;
case "Dyne centimeter -dyn*cm":
textconversionFrom.setText("Dyne centimeter "); textViewConversionShortform.setText("dyn*cm");
break;
case "Dyne millimeter -dyn*mm":
textconversionFrom.setText("Dyne millimeter "); textViewConversionShortform.setText("dyn*mm");
break;
case "Kilogram-force meter -kgf*m":
textconversionFrom.setText("Kilogram-force meter "); textViewConversionShortform.setText("kgf*m");
break;
case "Kilogram-force centimeter -kgf*cm":
textconversionFrom.setText("Kilogram-force centimeter "); textViewConversionShortform.setText("kgf*cm");
break;
case "Kilogram-force millimeter -kgf*mm":
textconversionFrom.setText("Kilogram-force millimeter "); textViewConversionShortform.setText("kgf*mm");
break;
case "Gram-force meter -gf*m":
textconversionFrom.setText("Gram-force meter "); textViewConversionShortform.setText("gf*m");
break;
case "Gram-force centimeter -gf*cm":
textconversionFrom.setText("Gram-force centimeter "); textViewConversionShortform.setText("gf*cm");
break;
case "Gram-force millimeter -gf*mm":
textconversionFrom.setText("Gram-force millimeter "); textViewConversionShortform.setText("gf*mm");
break;
case "Ounce-force foot -ozf*ft":
textconversionFrom.setText("Ounce-force foot "); textViewConversionShortform.setText("ozf*ft");
break;
case "Ounce-force inch -ozf*in":
textconversionFrom.setText("Ounce-force inch "); textViewConversionShortform.setText("ozf*in");
break;
case "Pound-force foot -lbf*ft":
textconversionFrom.setText("Pound-force foot "); textViewConversionShortform.setText("lbf*ft");
break;
case "Pound-force inch -lbf*in":
textconversionFrom.setText("Pound-force inch "); textViewConversionShortform.setText("lbf*in");
break;
}
}
private void formatsetting() {
//fetching value from sharedpreference
SharedPreferences sharedPreferences =this.getSharedPreferences(Settings.SHARED_PREF_NAME, Context.MODE_PRIVATE);
//Fetching thepatient_mobile_Number value form sharedpreferences
String FormattedString = sharedPreferences.getString(Settings.Format_Selected_SHARED_PREF,"Thousands separator");
String DecimalplaceString= sharedPreferences.getString(Settings.Decimal_Place_Selected_SHARED_PREF,"2");
Settings settings=new Settings(FormattedString,DecimalplaceString);
formatter= settings.setting();
}
private List<ItemList> getAllunitValue(String strSpinnerFrom,double doubleEdittextvalue1) {
TorqueConverter c = new TorqueConverter(strSpinnerFrom,doubleEdittextvalue1);
ArrayList<TorqueConverter.ConversionResults> results = c.calculateTorqueConversion();
int length = results.size();
for (int i = 0; i < length; i++) {
TorqueConverter.ConversionResults item = results.get(i);
strnewtonmeter=String.valueOf(formatter.format(item.getNewtonmeter()));
strnewtoncentimeter=String.valueOf(formatter.format(item.getNewtoncentimeter()));
strnewtonmillimeter=String.valueOf(formatter.format(item.getNewtonmillimeter()));
strkilonewtonmeter=String.valueOf(formatter.format(item.getKilonewtonmeter()));
strdynemeter=String.valueOf(formatter.format(item.getDynemeter()));
strdynecentimeter=String.valueOf(formatter.format(item.getDynecentimeter()));
strdynemillimeter=String.valueOf(formatter.format(item.getDynemillimeter()));
strkilogramforcemeter=String.valueOf(formatter.format(item.getKilogramforcemeter()));
strkilogramforcecentimeter=String.valueOf(formatter.format(item.getKilogramforcecentimeter()));
strkilogramforcemillimeter=String.valueOf(formatter.format(item.getKilogramforcemillimeter()));
strgramforcemeter=String.valueOf(formatter.format(item.getGramforcemeter()));
strgramforcecentimeter=String.valueOf(formatter.format(item.getGramforcecentimeter()));
strgramforcemillimeter=String.valueOf(formatter.format(item.getGramforcemillimeter()));
strounceforcefoot=String.valueOf(formatter.format(item.getOunceforcefoot()));
strounceforceinch=String.valueOf(formatter.format(item.getOunceforceinch()));
strpoundforcefoot=String.valueOf(formatter.format(item.getPoundforcefoot()));
strpoundforceinch=String.valueOf(formatter.format(item.getPoundforceinch()));
list.add(new ItemList("N*m","Newton meter ",strnewtonmeter,"N*m"));
list.add(new ItemList("N*cm","Newton centimeter ",strnewtoncentimeter,"N*cm"));
list.add(new ItemList("N*mm","Newton millimeter ",strnewtonmillimeter,"N*mm"));
list.add(new ItemList("kN*m","Kilonewton meter ",strkilonewtonmeter,"kN*m"));
list.add(new ItemList("dyn*m","Dyne meter ",strdynemeter,"dyn*m"));
list.add(new ItemList("dyn*cm","Dyne centimeter ",strdynecentimeter,"dyn*cm"));
list.add(new ItemList("dyn*mm","Dyne millimeter ",strdynemillimeter,"dyn*mm"));
list.add(new ItemList("kgf*m","Kilogram-force meter ",strkilogramforcemeter,"kgf*m"));
list.add(new ItemList("kgf*cm","Kilogram-force centimeter ",strkilogramforcecentimeter,"kgf*cm"));
list.add(new ItemList("kgf*mm","Kilogram-force millimeter ",strkilogramforcemillimeter,"kgf*mm"));
list.add(new ItemList("gf*m","Gram-force meter ",strgramforcemeter,"gf*m"));
list.add(new ItemList("gf*cm","Gram-force centimeter ",strgramforcecentimeter,"gf*cm"));
list.add(new ItemList("gf*mm","Gram-force millimeter ",strgramforcemillimeter,"gf*mm"));
list.add(new ItemList("ozf*ft","Ounce-force foot ",strounceforcefoot,"ozf*ft"));
list.add(new ItemList("ozf*in","Ounce-force inch ",strounceforceinch,"ozf*in"));
list.add(new ItemList("lbf*ft","Pound-force foot ",strpoundforcefoot,"lbf*ft"));
list.add(new ItemList("lbf*in","Pound-force inch ",strpoundforceinch,"lbf*in"));
}
return list;
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
rowListItem.clear();
try {
double value = Double.parseDouble(edittextConversionListvalue.getText().toString().trim());
rowListItem1 = getAllunitValue(stringSpinnerFrom,value);
rcAdapter = new RecyclerViewConversionListAdapter(this,rowListItem1);
rView.setAdapter(rcAdapter);
}
catch (NumberFormatException e) {
doubleEdittextvalue = 0;
}
}
@Override
public void afterTextChanged(Editable s) {
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
return super.onCreateOptionsMenu(menu);
}
public boolean onOptionsItemSelected(MenuItem item) {
// Take appropriate action for each action item click
switch (item.getItemId()) {
case android.R.id.home:
this.finish();
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
this.finish();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
| true |
115998e9c0a2785e728eabb933ab60e773845b9d | Java | radharamana/tangent | /src/main/java/co/za/tangent/service/PositionService.java | UTF-8 | 752 | 2.421875 | 2 | [] | no_license | package co.za.tangent.service;
import java.util.List;
import java.util.SortedMap;
import java.util.TreeMap;
import org.springframework.stereotype.Service;
import co.za.tangent.domain.Employee;
import co.za.tangent.domain.Position;
@Service
public class PositionService {
private SortedMap<Long, Position> positions = new TreeMap<Long, Position>();
public void doPopulatePosition(List<Employee> employees){
employees.stream().forEach(e->positions.put(e.getPosition().getId(), e.getPosition()));
}
public SortedMap<Long, Position> getPositions() {
return positions;
}
public void setPositions(SortedMap<Long, Position> positions) {
this.positions = positions;
}
public boolean isPopulated(){
return positions.size() > 0;
}
}
| true |
994c4aea5f2db3e86982c711e9cc723298bd75b8 | Java | lkstc112233/CSCI-6461-Simulator | /src/increment/simulator/chips/Memory.java | UTF-8 | 4,136 | 2.921875 | 3 | [] | no_license | package increment.simulator.chips;
import increment.simulator.Cable;
import increment.simulator.SingleCable;
import increment.simulator.tools.AssemblyCompiler.CompiledProgram;
/**
* The memory. It's abstracted as a black box that supports read/load by byte, a.k.a. a memory interface.<br>
* There is a build in cache inside this interface. It's a magical cache! implemented by MAGIC!<br>
* A memory will have three inputs:<br>
* * load[1]<br>
* * address[12]<br>
* * input[16] <br>
* A memory will have two outputs:<br>
* * output[16]
* * fault[1]
*
* @author Xu Ke
*
*/
public class Memory extends Chip {
/**
* Memory data stored in a big array. Using cable allow me to handle bits more conveniently.
*/
protected Cable[] data;
protected static class CacheEntry {
public int tag;
public boolean valid = false;
}
protected CacheEntry[] cache;
protected int cachePointer = 0;
/**
* Constructor. Creating a 12-bit addressed memory (4096 words, addressing from 0 to 4095).
*/
public Memory(){
this(12);
}
/**
* Constructor. Creating a width-bit addressed memory.
* @param width
*/
public Memory(int width) {
data = new Cable[1 << width];
changed = new boolean[1 << width];
for (int i = 0; i < data.length; ++i)
data[i] = new SingleCable(16);
addPort("load", 1);
addPort("address", 1 << width);
addPort("input", 16);
addPort("output", 16);
addPort("fault", 1);
cache = new CacheEntry[16];
for (int i = 0; i < 16; ++i)
cache[i] = new CacheEntry();
}
/**
* When timer ticks, if input[0] is true, we move data of input to data[address].
*/
@Override
public void tick(){
int address = (int) getPort("address").toInteger();
if (getPort("load").getBit(0)) {
if (outofRange(address))
return;
data[address].assign(getPort("input"));
changed[address] = true;
}
if (!outofRange(address)) {
loadCache(address >> 2);
} else {
System.err.println("Trying to access " + address);
}
}
/**
* Checks if target address is out of range.
* @param address
* @return
*/
private boolean outofRange(int address) {
if (address < 0)
return true;
return address >= data.length;
}
/**
* When evaluates, we move specified data to output.
* @return true if value changed.
*/
@Override
public boolean evaluate(){
int address = (int) getPort("address").toInteger();
if (outofRange(address))
return assignPort("fault", 1);
return getPort("output").assign(data[address]);
}
/**
* Only those data assigned will be output during toString.
* This array is used to store if those bits are assigned.
*/
protected boolean[] changed;
/**
* Turns chip value into a readable way.
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("Cache Status:\n");
for (int i = 0; i < 16; ++i) {
if (!cache[i].valid)
continue;
int tag = cache[i].tag;
sb.append("Tag ");
sb.append(tag);
sb.append(": \n\t");
for (int j = tag << 2; j < (cache[i].tag << 2) + 4; ++j) {
sb.append(String.format("%04X", data[j].toInteger()));
sb.append(" ");
}
sb.append("\n");
}
sb.append("Memory chip data:\n");
for (int i = 0; i < data.length; ++i) {
if (!changed[i]) continue;
sb.append(i);
sb.append(": ");
sb.append(data[i].toInteger());
sb.append("\n");
}
return sb.toString();
}
/**
* Put value to desired address.
* @param address
* @param value
*/
public void putValue(int address, int value) {
data[address].putValue(value);
changed[address] = true;
}
/**
* Load a program into memory.
* @param address The starting address in memory.
* @param code The compiled program. {@link increment.simulator.tools.AssemblyCompiler}
*/
public void loadProgram(int address, CompiledProgram code) {
for (Short ins : code) {
putValue(address++, ins);
}
}
private void loadCache(int tag) {
for (int i = 0; i < 16; ++i)
if (cache[i].valid)
if (cache[i].tag == tag)
return;
cache[cachePointer].valid = true;
cache[cachePointer].tag = tag;
cachePointer++;
cachePointer %= 16;
}
}
| true |
7d1885b7d387e0a939ec5cd76fdd04e1cd54b958 | Java | HJohnson-/Kingtaker | /src/graphics/ChessFrame.java | UTF-8 | 1,889 | 3.265625 | 3 | [] | no_license | package graphics;
import javax.swing.*;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
/**
* A basic JFrame implementation, which handles displaying the window on the screen.
*/
public abstract class ChessFrame extends JFrame {
protected String title;
protected int width = 750, height = 600;
protected JPanel panel;
public boolean fullscreen = false;
/**
* Sets up all the parameters of the ChessFrame.
* @param title What to display in the title bar.
* @param width The width of the window.
* @param height The height of the window.
* @param panel The panel of the chess variant, which is drawn into the window.
*/
public ChessFrame(String title, int width, int height, final ChessPanel panel) {
this.title = title;
this.width = width;
this.height = height;
this.panel = panel;
this.setResizable(true);
this.setLocationRelativeTo(null);
initUI();
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
StopWatch.isRunning = false;
panel.stopWatch.interrupt();
panel.panelStopwatch.setVisible(false);
}
});
}
/**
* Part of initialising a JPanel, this function sets UP the window.
*/
protected void initUI() {
setTitle(title);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
this.getContentPane().add(panel);
if (fullscreen) {
setExtendedState(Frame.MAXIMIZED_BOTH);
setUndecorated(true);
} else {
Dimension minimumDimensions = new Dimension(width, height);
setSize(minimumDimensions);
setMinimumSize(minimumDimensions);
}
setLocationRelativeTo(null);
}
}
| true |
80450531753c18bff623d0ede5f1b5f72a6443b0 | Java | hamzabinamin/arduino-yoyo | /app/src/main/java/com/hamzabinamin/yoyo/MainActivity.java | UTF-8 | 19,378 | 2 | 2 | [] | no_license | package com.hamzabinamin.yoyo;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.GlideDrawableImageViewTarget;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import static android.widget.AbsListView.OnScrollListener.SCROLL_STATE_IDLE;
public class MainActivity extends Activity implements View.OnClickListener {
Button clearTableButton;
TextView txtString;
ListView listView;
CustomAdapter customAdapter;
Handler bluetoothIn;
PlayGifView yoyo;
final int handlerState = 0; //used to identify handler message
private BluetoothAdapter btAdapter = null;
private BluetoothSocket btSocket = null;
private StringBuilder recDataString = new StringBuilder();
private static final String USER_AGENT = "Mozilla/5.0";
String yoyoID = "";
String yoyoValue = "";
List<Player> playerList = new ArrayList<Player>();
private ConnectedThread mConnectedThread;
// SPP UUID service - this should work for most devices
private static final UUID BTMODULEUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
// String for MAC address
private static String address;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
clearTableButton = (Button) findViewById(R.id.clearTableButton);
txtString = (TextView) findViewById(R.id.myResultsTextView);
listView = (ListView) findViewById(R.id.listview);
customAdapter = new CustomAdapter(getBaseContext(), playerList);
listView.setAdapter(customAdapter);
clearTableButton.setOnClickListener(this);
ImageView imageView = (ImageView) findViewById(R.id.yoyo);
if (imageView != null)
Glide.with(this).load("http://www.animated-gifs.eu/kids-yoyo/0010.gif").asGif().into(imageView);
//Declare the timer
Timer t = new Timer();
//Set the schedule function and rate
t.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
String url = String.format("http://www.sg-yoyo.com/retrieveTest.php\n");
try {
sendGETforRetrieve(url);
} catch (IOException e) {
e.printStackTrace();
}
}
}, 0, 5000);
bluetoothIn = new Handler() {
public void handleMessage(android.os.Message msg) {
if (msg.what == handlerState) { //if message is what we want
String readMessage = (String) msg.obj; // msg.arg1 = bytes from connect thread
recDataString.append(readMessage); //keep appending to string until ~
// int endOfLineIndex = recDataString.indexOf("END"); // determine the end-of-line
// if (endOfLineIndex > 0) { // make sure there data before ~
// String dataInPrint = recDataString.substring(0, endOfLineIndex);
// extract string
if(recDataString.toString().contains("P0C01") || recDataString.toString().contains("C01") || recDataString.toString().contains("P0C02") || recDataString.toString().contains("C02")) {
String[] store = recDataString.toString().split("!");
String deviceName = store[0];
//deviceName = deviceName.substring(deviceName.indexOf("POC"));
deviceName = deviceName.replaceAll(".*P","");
String number = store[1];
txtString.setText(number);
if(recDataString.toString().contains("C01")) {
yoyoID = "POC01";
}
else if(recDataString.toString().contains("C02")) {
yoyoID = "POC02";
}
yoyoID = deviceName;
yoyoValue = number;
String url = String.format("http://www.sg-yoyo.com/insertTest.php?yoyoID=%s&yoyoValue=%s\n", yoyoID, yoyoValue);
try {
sendGET(yoyoID, yoyoValue, url);
} catch (IOException e) {
e.printStackTrace();
}
recDataString.delete(0, recDataString.length()); //clear all string data
}
}
}
};
btAdapter = BluetoothAdapter.getDefaultAdapter(); // get Bluetooth adapter
checkBTState();
}
private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
return device.createRfcommSocketToServiceRecord(BTMODULEUUID);
//creates secure outgoing connecetion with BT device using UUID
}
@Override
public void onResume() {
super.onResume();
//Get MAC address from DeviceListActivity via intent
Intent intent = getIntent();
//Get the MAC address from the DeviceListActivty via EXTRA
address = intent.getStringExtra(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
//create device and set the MAC address
BluetoothDevice device = btAdapter.getRemoteDevice(address);
try {
btSocket = createBluetoothSocket(device);
} catch (IOException e) {
Toast.makeText(getBaseContext(), "Socket creation failed", Toast.LENGTH_LONG).show();
}
// Establish the Bluetooth socket connection.
try
{
btSocket.connect();
} catch (IOException e) {
try
{
btSocket.close();
} catch (IOException e2)
{
//insert code to deal with this
}
}
mConnectedThread = new ConnectedThread(btSocket);
mConnectedThread.start();
//I send a character when resuming.beginning transmission to check device is connected
//If it is not an exception will be thrown in the write method and finish() will be called
mConnectedThread.write("x");
}
public void sendGET(final String paramUsername, final String paramPassword, String paramURL) throws IOException {
class HttpGetAsyncTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... strings) {
String loginStatus = "";
try {
String paramUsername = strings[0];
String paramPassword = strings[1];
String paramURL = strings[2];
System.out.println("paramUsername: " + paramUsername + " paramPassword is: " + paramPassword + "paramURL: " +paramURL );
URL url = new URL(paramURL);
System.out.println("URL: "+ url.toString());
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setRequestProperty("User-Agent", USER_AGENT);
InputStream stream = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream));
StringBuilder builder = new StringBuilder();
String inputString;
while ((inputString = bufferedReader.readLine()) != null) {
builder.append(inputString);
}
Log.e("Response 1: ",builder.toString());
loginStatus = builder.toString();
urlConnection.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
return loginStatus;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if(result.contains("New record created successfully")){
Log.e("Response", "Record Got Saved");
Toast.makeText(getApplicationContext(), "YoYo Values got Saved", Toast.LENGTH_SHORT).show();
}
else if(result.contains("Error")) {
Log.e("Response", "Record Didn't Get Saved");
Toast.makeText(getApplicationContext(), "YoYo Values didn't get Saved", Toast.LENGTH_SHORT).show();
}
}
}
HttpGetAsyncTask httpGetAsyncTask = new HttpGetAsyncTask();
// Parameter we pass in the execute() method is relate to the first generic type of the AsyncTask
// We are passing the connectWithHttpGet() method arguments to that
httpGetAsyncTask.execute(paramUsername, paramPassword, paramURL);
}
public void sendGETforRetrieve(String paramURL) throws IOException {
class HttpGetAsyncTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... strings) {
String loginStatus = "";
try {
String paramURL = strings[0];
URL url = new URL(paramURL);
System.out.println("URL: "+ url.toString());
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setRequestProperty("User-Agent", USER_AGENT);
InputStream stream = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream));
StringBuilder builder = new StringBuilder();
String inputString;
while ((inputString = bufferedReader.readLine()) != null) {
builder.append(inputString);
}
Log.e("Response 1: ",builder.toString());
loginStatus = builder.toString();
urlConnection.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
return loginStatus;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
playerList.clear();
String[] storeResult = result.split(",");
String[] storeResult2 = new String[storeResult.length * 2];
List<String> yoyoScore = new ArrayList<String>();
List<String> yoyoDevice = new ArrayList<String>();
List<String> yoyoTimeStamp = new ArrayList<String>();
Log.e("JSON Result: ", result.toString());
if (!result.contains("0 results")) {
try {
JSONArray arr = new JSONArray(result);
for (int i = 0; i < arr.length(); i++) {
yoyoScore.add(arr.getJSONObject(i).getString("YoYoValue"));
yoyoDevice.add(arr.getJSONObject(i).getString("YoYoID"));
yoyoTimeStamp.add(arr.getJSONObject(i).getString("YoYoLatUpdate"));
playerList.add(new Player(i + 1, yoyoDevice.get(i), yoyoTimeStamp.get(i), Integer.parseInt(yoyoScore.get(i))));
int position = listView.getSelectedItemPosition();
customAdapter.notifyDataSetChanged();
listView.setSelection(position);
}
} catch (JSONException e) {
e.printStackTrace();
}
Log.e("YoYo Score: ", yoyoScore.toString());
Log.e("YoYo Time Stamp: ", yoyoTimeStamp.toString());
}
}
}
HttpGetAsyncTask httpGetAsyncTask = new HttpGetAsyncTask();
// Parameter we pass in the execute() method is relate to the first generic type of the AsyncTask
// We are passing the connectWithHttpGet() method arguments to that
httpGetAsyncTask.execute(paramURL);
}
public void sendGETforClearTable(String paramURL) throws IOException {
class HttpGetAsyncTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... strings) {
String loginStatus = "";
try {
String paramURL = strings[0];
URL url = new URL(paramURL);
System.out.println("URL: "+ url.toString());
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setRequestProperty("User-Agent", USER_AGENT);
InputStream stream = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream));
StringBuilder builder = new StringBuilder();
String inputString;
while ((inputString = bufferedReader.readLine()) != null) {
builder.append(inputString);
}
Log.e("Response 1: ",builder.toString());
loginStatus = builder.toString();
urlConnection.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
return loginStatus;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.e("JSON Result: ", result.toString());
if(result.contains("Table cleared successfully")) {
Toast.makeText(getBaseContext(), "Table Cleared", Toast.LENGTH_SHORT).show();
}
}
}
HttpGetAsyncTask httpGetAsyncTask = new HttpGetAsyncTask();
// Parameter we pass in the execute() method is relate to the first generic type of the AsyncTask
// We are passing the connectWithHttpGet() method arguments to that
httpGetAsyncTask.execute(paramURL);
}
@Override
public void onPause()
{
super.onPause();
try
{
//Don't leave Bluetooth sockets open when leaving activity
btSocket.close();
} catch (IOException e2) {
//insert code to deal with this
}
}
//Checks that the Android device Bluetooth is available and prompts to be turned on if off
private void checkBTState() {
if(btAdapter==null) {
Toast.makeText(getBaseContext(), "Device does not support bluetooth", Toast.LENGTH_LONG).show();
} else {
if (btAdapter.isEnabled()) {
} else {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
}
}
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.clearTableButton:
String url = String.format("http://sg-yoyo.com/clearTable.php\n");
try {
sendGETforClearTable(url);
} catch (IOException e) {
e.printStackTrace();
}
break;
}
}
//create new class for connect thread
private class ConnectedThread extends Thread {
private final InputStream mmInStream;
private final OutputStream mmOutStream;
//creation of the connect thread
public ConnectedThread(BluetoothSocket socket) {
InputStream tmpIn = null;
OutputStream tmpOut = null;
try {
//Create I/O streams for connection
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) { }
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer = new byte[256];
int bytes;
// Keep looping to listen for received messages
while (true) {
try {
bytes = mmInStream.read(buffer); //read bytes from input buffer
String readMessage = new String(buffer, 0, bytes);
// Send the obtained bytes to the UI Activity via handler
bluetoothIn.obtainMessage(handlerState, bytes, -1, readMessage).sendToTarget();
} catch (IOException e) {
break;
}
}
}
//write method
public void write(String input) {
byte[] msgBuffer = input.getBytes(); //converts entered String into bytes
try {
mmOutStream.write(msgBuffer); //write bytes over BT connection via outstream
} catch (IOException e) {
//if you cannot write, close the application
Toast.makeText(getBaseContext(), "Connection Failure", Toast.LENGTH_LONG).show();
finish();
}
}
}
public void showList() {
List<Player> playerList = new ArrayList<Player>();
customAdapter = new CustomAdapter(this, playerList);
listView.setAdapter(customAdapter);
}
} | true |
e0590fdfca8264dd0ddd69995c8ba79209ff3401 | Java | DohYou/WX | /app/src/main/java/com/ylr/hyy/mvp/model/AiNewsModel.java | UTF-8 | 3,341 | 2.40625 | 2 | [] | no_license | package com.ylr.hyy.mvp.model;
import com.ylr.hyy.base.Base;
import java.util.List;
public class AiNewsModel extends Base {
/**
* data : {"customer":{"current":1,"orders":[],"pages":0,"records":[],"searchCount":true,"size":10,"total":0},"isshow":0,"keyword":["在玩游戏","在玩游好","关键字","关键字1","关键字2","关键字3","关键字4"]}
*/
private DataBean data;
public DataBean getData() {
return data;
}
public void setData(DataBean data) {
this.data = data;
}
public static class DataBean {
/**
* customer : {"current":1,"orders":[],"pages":0,"records":[],"searchCount":true,"size":10,"total":0}
* isshow : 0
* keyword : ["在玩游戏","在玩游好","关键字","关键字1","关键字2","关键字3","关键字4"]
*/
private CustomerBean customer;
private int isshow;
private List<String> keyword;
public CustomerBean getCustomer() {
return customer;
}
public void setCustomer(CustomerBean customer) {
this.customer = customer;
}
public int getIsshow() {
return isshow;
}
public void setIsshow(int isshow) {
this.isshow = isshow;
}
public List<String> getKeyword() {
return keyword;
}
public void setKeyword(List<String> keyword) {
this.keyword = keyword;
}
public static class CustomerBean {
/**
* current : 1
* orders : []
* pages : 0
* records : []
* searchCount : true
* size : 10
* total : 0
*/
private int current;
private int pages;
private boolean searchCount;
private int size;
private int total;
private List<?> orders;
private List<?> records;
public int getCurrent() {
return current;
}
public void setCurrent(int current) {
this.current = current;
}
public int getPages() {
return pages;
}
public void setPages(int pages) {
this.pages = pages;
}
public boolean isSearchCount() {
return searchCount;
}
public void setSearchCount(boolean searchCount) {
this.searchCount = searchCount;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public List<?> getOrders() {
return orders;
}
public void setOrders(List<?> orders) {
this.orders = orders;
}
public List<?> getRecords() {
return records;
}
public void setRecords(List<?> records) {
this.records = records;
}
}
}
}
| true |
e6c6a4f62c99cdd1f5996db3c685a91cc1ae0187 | Java | warnercibertec/tienda-jsf | /tienda-modelo/src/main/java/pe/edu/cibertec/spring/base/repository/config/ConfiguracionGestorTransaccion.java | UTF-8 | 565 | 1.929688 | 2 | [] | no_license | package pe.edu.cibertec.spring.base.repository.config;
import javax.persistence.EntityManagerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.orm.jpa.JpaTransactionManager;
@Configuration
public class ConfiguracionGestorTransaccion {
@Bean
public JpaTransactionManager jpaTransactionManager(EntityManagerFactory emf) {
JpaTransactionManager jtm = new JpaTransactionManager();
jtm.setEntityManagerFactory(emf);
return jtm;
}
}
| true |
ff9b4617c0347d4ccafa965905e7bb63fde6d248 | Java | RiditaNizam/PracticingStaticConcept | /src/com/company/Person.java | UTF-8 | 218 | 2.296875 | 2 | [] | no_license | package com.company;
/**
* Created by ridita on 9/25/17.
*/
public class Person {
public static int count; //Variable belongs to the class rather than the object
public Person(){
count++;
}
} | true |
3bb7ebc44cb01f9ad6f8a61504103b7c74f6c0df | Java | RzTutul/Daily-Book---Income-Expense-Manager | /app/src/main/java/com/rztechtunes/dailyexpensemanager/MainActivity.java | UTF-8 | 9,049 | 1.539063 | 2 | [] | no_license | package com.rztechtunes.dailyexpensemanager;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.navigation.NavController;
import androidx.navigation.NavDestination;
import androidx.navigation.NavHostController;
import androidx.navigation.Navigation;
import androidx.work.Constraints;
import androidx.work.NetworkType;
import androidx.work.OneTimeWorkRequest;
import androidx.work.PeriodicWorkRequest;
import androidx.work.WorkManager;
import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import com.etebarian.meowbottomnavigation.MeowBottomNavigation;
import com.google.android.material.bottomappbar.BottomAppBar;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.navigation.NavigationView;
import com.rztechtunes.dailyexpensemanager.db.ExpenseIncomeDatabase;
import com.rztechtunes.dailyexpensemanager.entites.DairyPojo;
import com.rztechtunes.dailyexpensemanager.helper.NotificationWorker;
import com.rztechtunes.dailyexpensemanager.pref.UserActivityStorePref;
import java.util.concurrent.TimeUnit;
import cn.pedant.SweetAlert.SweetAlertDialog;
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
BottomNavigationView bottomNav;
BottomAppBar bottomBar;
FloatingActionButton addExpenseBtn;
NavController navController;
boolean isExit = false, isBack = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//For Bottom Nevigation
bottomNav = findViewById(R.id.bottom_navigation);
bottomBar = findViewById(R.id.bottomBar);
addExpenseBtn = findViewById(R.id.addexpenseBtn);
bottomNav.setOnNavigationItemSelectedListener(navListener);
navController = Navigation.findNavController(this, R.id.nav_host_fragment);
addExpenseBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AddTransactionFrag.positionupdate = -1;
Navigation.findNavController(MainActivity.this,R.id.nav_host_fragment).navigate(R.id.addTransactionFrag);
}
});
navController.addOnDestinationChangedListener(new NavController.OnDestinationChangedListener() {
@Override
public void onDestinationChanged(@NonNull NavController controller, @NonNull NavDestination destination, @Nullable Bundle arguments) {
switch (destination.getId()) {
case R.id.splashScreenFragment:
bottomBar.setVisibility(View.GONE);
addExpenseBtn.setVisibility(View.GONE);
break;
case R.id.expenseManagerFrag:
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
bottomBar.setVisibility(View.VISIBLE);
addExpenseBtn.setVisibility(View.VISIBLE);
bottomNav.getMenu().findItem(R.id.home_menu).setChecked(true);
}
});
isExit = true;
break;
case R.id.dailyNoteFragment:
bottomBar.setVisibility(View.VISIBLE);
addExpenseBtn.setVisibility(View.VISIBLE);
bottomNav.getMenu().findItem(R.id.dairy_menu).setChecked(true);
isBack = true;
isExit = false;
break;
case R.id.allCalculationFragment:
bottomNav.getMenu().findItem(R.id.calculate_menu).setChecked(true);
isBack = true;
isExit = false;
break;
case R.id.addTransactionFrag :
bottomBar.setVisibility(View.GONE);
addExpenseBtn.setVisibility(View.GONE);
isBack = true;
isExit = false;
break;
case R.id.addDairyFragment:
bottomBar.setVisibility(View.GONE);
addExpenseBtn.setVisibility(View.GONE);
isExit = false;
case R.id.diaryDetailsFrag:
bottomBar.setVisibility(View.GONE);
addExpenseBtn.setVisibility(View.GONE);
isExit = false;
default:
isExit = false;
isBack = false;
break;
}
}
});
}
@Override
public void onBackPressed() {
if (isExit) {
new SweetAlertDialog(this, SweetAlertDialog.CUSTOM_IMAGE_TYPE)
.setTitleText("Rate this app?")
.setCustomImage(R.drawable.ratingimage)
.setContentText("if you enjoy this app,would you mind taking a moment to rate it? it won't take more than a minute.Thank you!")
.setConfirmText("Rate Now")
.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
@Override
public void onClick(SweetAlertDialog sDialog) {
final String appPackageName = getPackageName(); // getPackageName() from Context or Activity object
try {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + appPackageName)));
} catch (android.content.ActivityNotFoundException anfe) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + appPackageName)));
}
sDialog.dismissWithAnimation();
}
})
.setCancelButton("Later", new SweetAlertDialog.OnSweetClickListener() {
@Override
public void onClick(SweetAlertDialog sDialog) {
MainActivity.this.finish();
sDialog.dismissWithAnimation();
}
})
.show();
} else if (isBack) {
Navigation.findNavController(MainActivity.this, R.id.nav_host_fragment).navigate(R.id.expenseManagerFrag);
}
/* else if (isDairyFrg) {
final Bundle bundle = new Bundle();
bundle.putString("id", eventID);
Navigation.findNavController(MainActivity.this, R.id.nav_host_fragmnet).navigate(R.id.eventDairyListFragment,bundle);
}
*/
else {
super.onBackPressed();
}
}
private BottomNavigationView.OnNavigationItemSelectedListener navListener =
new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.home_menu:
Navigation.findNavController(MainActivity.this, R.id.nav_host_fragment).navigate(R.id.expenseManagerFrag);
break;
case R.id.calculate_menu:
Navigation.findNavController(MainActivity.this, R.id.nav_host_fragment).navigate(R.id.allCalculationFragment);
break;
case R.id.dairy_menu:
Navigation.findNavController(MainActivity.this, R.id.nav_host_fragment).navigate(R.id.dailyNoteFragment);
break;
case R.id.setting_menu:
Navigation.findNavController(MainActivity.this, R.id.nav_host_fragment).navigate(R.id.settingFragment);
break;
default:
break;
}
return true;
}
};
} | true |
629a8dec412217e5377cdefa519bb1754539fd66 | Java | pxson001/facebook-app | /classes5.dex_source_from_JADX/com/facebook/graphql/enums/GraphQLNotifHighlightState.java | UTF-8 | 723 | 2.046875 | 2 | [] | no_license | package com.facebook.graphql.enums;
/* compiled from: mLightweightPlacePickerPlaces */
public enum GraphQLNotifHighlightState {
UNSET_OR_UNRECOGNIZED_ENUM_VALUE,
HIGHLIGHTED,
NONE,
NOT_HIGHLIGHTED;
public static GraphQLNotifHighlightState fromString(String str) {
if (str == null || str.isEmpty()) {
return UNSET_OR_UNRECOGNIZED_ENUM_VALUE;
}
if (str.equalsIgnoreCase("HIGHLIGHTED")) {
return HIGHLIGHTED;
}
if (str.equalsIgnoreCase("NONE")) {
return NONE;
}
if (str.equalsIgnoreCase("NOT_HIGHLIGHTED")) {
return NOT_HIGHLIGHTED;
}
return UNSET_OR_UNRECOGNIZED_ENUM_VALUE;
}
}
| true |
3b7edf10d7ea346dec17f53fe82f16a6ccad80e3 | Java | luisitocaiza17/JavaProcesoBatch | /Cotizador/src/com/qbe/cotizador/servlets/mantenimiento/MantenimientoController.java | UTF-8 | 40,588 | 1.65625 | 2 | [] | no_license | package com.qbe.cotizador.servlets.mantenimiento;
import java.io.IOException;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import com.qbe.cotizador.dao.cotizacion.AutorizacionSriDAO;
import com.qbe.cotizador.dao.cotizacion.CoberturaDAO;
import com.qbe.cotizador.dao.cotizacion.CoberturasConjuntoDAO;
import com.qbe.cotizador.dao.cotizacion.ConjuntoCoberturaDAO;
import com.qbe.cotizador.dao.cotizacion.DeducibleDAO;
import com.qbe.cotizador.dao.cotizacion.GrupoCoberturaDAO;
import com.qbe.cotizador.dao.cotizacion.PlanDAO;
import com.qbe.cotizador.dao.cotizacion.ProductoDAO;
import com.qbe.cotizador.dao.cotizacion.TipoCoberturaDAO;
import com.qbe.cotizador.dao.cotizacion.TipoTasaDAO;
import com.qbe.cotizador.dao.entidad.ConfiguracionProductoDAO;
import com.qbe.cotizador.dao.entidad.DetalleProductoDAO;
import com.qbe.cotizador.dao.entidad.EntidadDAO;
import com.qbe.cotizador.dao.entidad.EntidadJrDAO;
import com.qbe.cotizador.dao.entidad.FirmasDigitalesDAO;
import com.qbe.cotizador.dao.entidad.RamoDAO;
import com.qbe.cotizador.dao.entidad.SucursalDAO;
import com.qbe.cotizador.dao.producto.vehiculo.ClaseVehiculoDAO;
import com.qbe.cotizador.dao.producto.vehiculo.ColorDAO;
import com.qbe.cotizador.dao.producto.vehiculo.MarcaDAO;
import com.qbe.cotizador.dao.producto.vehiculo.ModeloDAO;
import com.qbe.cotizador.dao.producto.vehiculo.TipoExtraDAO;
import com.qbe.cotizador.model.AutorizacionSri;
import com.qbe.cotizador.model.ClaseVehiculo;
import com.qbe.cotizador.model.Cobertura;
import com.qbe.cotizador.model.CoberturasConjunto;
import com.qbe.cotizador.model.Color;
import com.qbe.cotizador.model.ConfiguracionProducto;
import com.qbe.cotizador.model.ConjuntoCobertura;
import com.qbe.cotizador.model.Deducible;
import com.qbe.cotizador.model.DetalleProducto;
import com.qbe.cotizador.model.Entidad;
import com.qbe.cotizador.model.EntidadJr;
import com.qbe.cotizador.model.FirmasDigitales;
import com.qbe.cotizador.model.GrupoCobertura;
import com.qbe.cotizador.model.Marca;
import com.qbe.cotizador.model.Modelo;
import com.qbe.cotizador.model.Plan;
import com.qbe.cotizador.model.Producto;
import com.qbe.cotizador.model.Ramo;
import com.qbe.cotizador.model.Sucursal;
import com.qbe.cotizador.model.TipoCobertura;
import com.qbe.cotizador.model.TipoExtra;
import com.qbe.cotizador.model.TipoTasa;
import com.qbe.cotizador.servicios.QBE.cliente.WebServiceCotizadorImplService;
import com.qbe.cotizador.transaction.cotizacion.AutorizacionSriTransaction;
import com.qbe.cotizador.transaction.cotizacion.CoberturaTransaction;
import com.qbe.cotizador.transaction.cotizacion.CoberturasConjuntoTransaction;
import com.qbe.cotizador.transaction.cotizacion.ConfiguracionProductoTransaction;
import com.qbe.cotizador.transaction.cotizacion.ConjuntoCoberturaTransaction;
import com.qbe.cotizador.transaction.cotizacion.DeducibleTransaction;
import com.qbe.cotizador.transaction.producto.DetalleProductoTransaction;
import com.qbe.cotizador.transaction.producto.vehiculo.ClaseVehiculoTransaction;
import com.qbe.cotizador.transaction.producto.vehiculo.ColorTransaction;
import com.qbe.cotizador.transaction.producto.vehiculo.MarcaTransaction;
import com.qbe.cotizador.transaction.producto.vehiculo.ModeloTransaction;
import com.qbe.cotizador.transaction.producto.vehiculo.TipoExtraTransaction;
import com.qbe.cotizador.transaction.cotizacion.GrupoCoberturaTransaction;
import com.qbe.cotizador.transaction.cotizacion.PlanTransaction;
import com.qbe.cotizador.transaction.cotizacion.ProductoTransaction;
import com.qbe.cotizador.transaction.entidad.EntidadJrTransaction;
import com.qbe.cotizador.transaction.entidad.FirmasDigitalesTransaction;
/**
* Servlet implementation class MantenimientoController
*/
@WebServlet("/MantenimientoController")
public class MantenimientoController extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public MantenimientoController() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
JSONObject result = new JSONObject();
HttpSession session = request.getSession();
session.setMaxInactiveInterval(3*60*60);//(3 horas por 60 minutos por 60 segundos)
PlanTransaction planTransaction = new PlanTransaction();
ProductoTransaction productoTransaction = new ProductoTransaction();
GrupoCoberturaTransaction grupoCoberturaTransaction = new GrupoCoberturaTransaction();
ConfiguracionProductoTransaction configuracionProductoTransaction= new ConfiguracionProductoTransaction();
ConjuntoCoberturaTransaction conjuntoCoberturaTransaction = new ConjuntoCoberturaTransaction();
CoberturasConjuntoTransaction coberturasConjuntoTransaction = new CoberturasConjuntoTransaction();
CoberturaTransaction coberturaTransaction = new CoberturaTransaction();
DetalleProductoTransaction detalleProductoTransaction = new DetalleProductoTransaction();
DeducibleTransaction deducibleTransaction = new DeducibleTransaction();
EntidadJrTransaction entidadJrTransaction = new EntidadJrTransaction();
FirmasDigitalesTransaction firmasDigitalesTransaction = new FirmasDigitalesTransaction();
AutorizacionSriTransaction autorizacionSriTransaction = new AutorizacionSriTransaction();
MarcaTransaction marcaTransaction = new MarcaTransaction();
ClaseVehiculoTransaction claseVehiculoTransaction = new ClaseVehiculoTransaction();
ModeloTransaction modeloTransaction = new ModeloTransaction();
ColorTransaction colorTransaction = new ColorTransaction();
TipoExtraTransaction tipoExtraTransaction = new TipoExtraTransaction();
try{
String tipoConsulta = request.getParameter("tipoConsulta") == null ? "" : request.getParameter("tipoConsulta");
Cobertura cobertura = new Cobertura();
Plan plan = new Plan();
Producto producto = new Producto();
GrupoCobertura grupoCobertura = new GrupoCobertura();
Ramo ramo = new Ramo();
CoberturaDAO coberturaDAO = new CoberturaDAO();
PlanDAO planDAO = new PlanDAO();
ProductoDAO productoDAO = new ProductoDAO();
GrupoCoberturaDAO grupoCoberturaDAO = new GrupoCoberturaDAO();
RamoDAO ramoDAO = new RamoDAO();
// Metodo para actualizar Tablas de vehiculos desde ensurance
if(tipoConsulta.equals("actualizarCatalogosVH")){
System.out.println("HORA INICIO: "+new Date());
WebServiceCotizadorImplService webService = new WebServiceCotizadorImplService();
// Actualizacion Plan VH
String listadoPlanes = webService.getWebServiceCotizadorImplPort().obtenerPlanes();
String [] listadoPlanesArr=listadoPlanes.split("\\><");
String resultadoActualizacion = "";
int planesNuevos =0;
int planesActualizados =0;
for(String planFila:listadoPlanesArr){
String [] planValores = planFila.split("\\|");
String planEstado = "";
plan = planDAO.buscarPorId(planValores[0]);
if(plan == null || plan.getId()==null){
plan = new Plan();
planEstado = "NUEVO";
}
plan.setId(planValores[0].toString());
plan.setNombre(planValores[1].toString());
plan.setDescripcion(planValores[2].toString());
plan.setSigla(planValores[3].toString());
if(planEstado.equalsIgnoreCase("NUEVO")){
plan = planTransaction.crear(plan);
planesNuevos++;
}
else{
plan = planTransaction.editar(plan);
planesActualizados++;
}
}
resultadoActualizacion = "HORA INICIO: "+new Date()+" ---- ";
resultadoActualizacion +="Planes: "+planesNuevos+" Nuevos "+planesActualizados+" Actualizados";
// Actualizacion GrupoCobertura VH
String listadoGrupoCoberturas = webService.getWebServiceCotizadorImplPort().obtenerGruposCoberturaVH();
String [] listadoGrupoCoberturasArr=listadoGrupoCoberturas.split("\\><");
int grupoCoberturaNuevos=0;
int grupoCoberturaActualizados=0;
for(String grupoCoberturaFila:listadoGrupoCoberturasArr){
String [] grupoCoberturaValores = grupoCoberturaFila.split("\\|");
String grupoCoberturaEstado = "";
grupoCobertura = grupoCoberturaDAO.buscarPorId(grupoCoberturaValores[0]);
if(grupoCobertura == null || grupoCobertura.getId()==null){
grupoCobertura = new GrupoCobertura();
grupoCoberturaEstado = "NUEVO";
}
grupoCobertura.setId(grupoCoberturaValores[0].toString());
grupoCobertura.setNombre(grupoCoberturaValores[1].toString());
ramo = ramoDAO.buscarPorId(grupoCoberturaValores[2].toString());
grupoCobertura.setRamo(ramo);
grupoCobertura.setNombreNemotecnico(grupoCoberturaValores[3].toString());
grupoCobertura.setCodcontable(grupoCoberturaValores[4].toString());
grupoCobertura.setOrden(grupoCoberturaValores[5].toString());
grupoCobertura.setSumaaltotal(Double.parseDouble(grupoCoberturaValores[6].toString()));
grupoCobertura.setCuentapolizatotal(grupoCoberturaValores[7].toString());
if(grupoCoberturaEstado.equalsIgnoreCase("NUEVO")){
grupoCobertura = grupoCoberturaTransaction.crear(grupoCobertura);
grupoCoberturaNuevos++;
}
else{
grupoCobertura = grupoCoberturaTransaction.editar(grupoCobertura);
grupoCoberturaActualizados++;
}
}
resultadoActualizacion +="GrupoCobertura: "+planesNuevos+" Nuevos "+planesActualizados+" Actualizados";
// Actualizacion Productos VH
String listadoProducto = webService.getWebServiceCotizadorImplPort().obteneProductosVH();
String [] listadoProductoArr =listadoProducto.split("\\><");
int productosNuevos=0;
int productosActualizados=0;
for(String productoFila:listadoProductoArr){
String [] productoValores = productoFila.split("\\|");
String productoEstado = "";
producto = productoDAO.buscarPorId(productoValores[0]);
if(producto == null){
producto = new Producto();
productoEstado = "NUEVO";
}
producto.setId(productoValores[0].toString());
producto.setNombre(productoValores[1].toString());
producto.setRamoId(new BigInteger(productoValores[2].toString()));
producto.setDefecto(productoValores[3].toString());
producto.setVigencia(Integer.parseInt(productoValores[4].toString()));
producto.setDinamico(productoValores[5].toString());
if(productoEstado.equalsIgnoreCase("NUEVO")){
producto = productoTransaction.crear(producto);
productosNuevos++;
}
else{
producto = productoTransaction.editar(producto);
productosActualizados++;
}
}
resultadoActualizacion +="Productos: "+productosNuevos+" Nuevos "+productosActualizados+" Actualizados";
// Actualizacion ConfiguracionProducto
String listadoConfiguracionProducto = webService.getWebServiceCotizadorImplPort().obtenerConfiguracionProducto();
String [] listadoConfiguracionProductoArr=listadoConfiguracionProducto.split("\\><");
int configuracionProductosNuevos=0;
int configuracionProductosActualizados=0;
ConfiguracionProducto configuracionProducto = new ConfiguracionProducto();
ConfiguracionProductoDAO configuracionProductoDAO = new ConfiguracionProductoDAO();
for(String configuracionProductoFila:listadoConfiguracionProductoArr){
String [] configuracionProductoValores = configuracionProductoFila.split("\\|");
String configuracionProductoEstado="";
productoDAO = new ProductoDAO();
producto=productoDAO.buscarPorId(configuracionProductoValores[1].toString());
if (producto != null && producto.getId() != null) {
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
configuracionProducto=configuracionProductoDAO.buscarPorId(configuracionProductoValores[0].toString());
if (configuracionProducto == null || configuracionProducto.getId() == null) {
configuracionProducto = new ConfiguracionProducto();
configuracionProductoEstado = "NUEVO";
}
configuracionProducto.setId(configuracionProductoValores[0].toString());
Date fecha=null;
Date vigenciaDesde=null;
Date vigenciaHasta=null;
if(!configuracionProductoValores[2].toString().trim().equals(""))
fecha=sdf.parse(configuracionProductoValores[2].toString());
if(!configuracionProductoValores[4].toString().trim().equals(""))
vigenciaDesde=sdf.parse(configuracionProductoValores[4].toString());
if(!configuracionProductoValores[5].toString().trim().equals(""))
vigenciaHasta=sdf.parse(configuracionProductoValores[5].toString());
configuracionProducto.setProducto(producto);
if(fecha!=null)
configuracionProducto.setFecha(fecha);
if(vigenciaDesde!=null)
configuracionProducto.setVigenciadesde(vigenciaDesde);
if(vigenciaHasta!=null)
configuracionProducto.setVigenciahasta(vigenciaHasta);
configuracionProducto.setVigente(configuracionProductoValores[3].toString());
configuracionProducto.setModificable(configuracionProductoValores[6].toString());
if(configuracionProductoEstado.equalsIgnoreCase("NUEVO")){
configuracionProducto = configuracionProductoTransaction.crear(configuracionProducto);
configuracionProductosNuevos++;
}
else{
configuracionProducto = configuracionProductoTransaction.editar(configuracionProducto);
configuracionProductosActualizados++;
}
}
}
resultadoActualizacion +="Configuracion Productos: "+configuracionProductosNuevos+" Nuevos "+configuracionProductosActualizados+" Actualizados";
// Actualizacion Conjunto Coberturas
String listadoConjuntoCoberturas = webService.getWebServiceCotizadorImplPort().obteneConjuntoCoberturasVH();
String [] listadoConjuntoCoberturasArr =listadoConjuntoCoberturas.split("\\><");
int conjuntoCoberturasNuevos=0;
int conjuntoCoberturasActualizados=0;
for(String conjuntoCoberturasFila:listadoConjuntoCoberturasArr){
String [] conjuntoCoberturasValores = conjuntoCoberturasFila.split("\\|");
String conjuntoCoberturaEstado = "";
ConjuntoCobertura conjuntoCobertura = new ConjuntoCobertura();
ConjuntoCoberturaDAO conjuntoCoberturaDAO = new ConjuntoCoberturaDAO();
conjuntoCobertura = conjuntoCoberturaDAO.buscarPorId(conjuntoCoberturasValores[0]);
if(conjuntoCobertura == null||conjuntoCobertura.getId()==null){
conjuntoCobertura = new ConjuntoCobertura();
conjuntoCoberturaEstado = "NUEVO";
}
ConfiguracionProductoDAO cfDAO=new ConfiguracionProductoDAO();
configuracionProducto=cfDAO.buscarPorId(conjuntoCoberturasValores[2]);
if(configuracionProducto!=null&&configuracionProducto.getId()!=null){
conjuntoCobertura.setConfiguracionProducto(configuracionProducto);
conjuntoCobertura.setOrden(conjuntoCoberturasValores[3]);
conjuntoCobertura.setId(conjuntoCoberturasValores[0]);
conjuntoCobertura.setNombre(conjuntoCoberturasValores[1]);
if(conjuntoCoberturaEstado.equalsIgnoreCase("NUEVO")){
conjuntoCobertura = conjuntoCoberturaTransaction.crear(conjuntoCobertura);
conjuntoCoberturasNuevos++;
}
else{
conjuntoCobertura = conjuntoCoberturaTransaction.editar(conjuntoCobertura);
conjuntoCoberturasActualizados++;
}
}
}
resultadoActualizacion +="Conjunto Coberturas: "+conjuntoCoberturasNuevos+" Nuevos "+conjuntoCoberturasActualizados+" Actualizados";
// Actualizacion CoberturasConjunto
String listadoCoberturaConjunto = webService.getWebServiceCotizadorImplPort().obtenerCoberturasConjunto();
String [] listadoCoberturaConjuntoArr=listadoCoberturaConjunto.split("\\><");
int coberturasConjuntoNuevos=0;
int coberturasConjuntoActualizados=0;
for(String coberturaConjuntoFila:listadoCoberturaConjuntoArr){
String [] coberturaConjuntoValores = coberturaConjuntoFila.split("\\|");
ConjuntoCoberturaDAO conjuntoCoberturaDAO = new ConjuntoCoberturaDAO();
ConjuntoCobertura conjuntoCobertura=conjuntoCoberturaDAO.buscarPorId(coberturaConjuntoValores[1].toString());
cobertura = coberturaDAO.buscarPorId(coberturaConjuntoValores[2].toString());
CoberturasConjuntoDAO coberturasConjuntoDAO = new CoberturasConjuntoDAO();
String coberturasConjuntoEstado="";
if (conjuntoCobertura != null && conjuntoCobertura.getId() != null && cobertura!=null && cobertura.getId()!=null) {
CoberturasConjunto coberturasConjunto=coberturasConjuntoDAO.buscarPorId(coberturaConjuntoValores[0].toString());
if (coberturasConjunto == null || coberturasConjunto.getId() == null) {
coberturasConjunto = new CoberturasConjunto();
coberturasConjuntoEstado = "NUEVO";
}
coberturasConjunto.setConjuntoCobertura(conjuntoCobertura);
coberturasConjunto.setCobertura(cobertura);
coberturasConjunto.setId(coberturaConjuntoValores[0].toString());
if(coberturasConjuntoEstado.equalsIgnoreCase("NUEVO")){
coberturasConjunto = coberturasConjuntoTransaction.crear(coberturasConjunto);
coberturasConjuntoNuevos++;
}
else{
coberturasConjunto = coberturasConjuntoTransaction.editar(coberturasConjunto);
coberturasConjuntoActualizados++;
}
}
}
resultadoActualizacion +="Coberturas Conjunto: "+coberturasConjuntoNuevos+" Nuevos "+coberturasConjuntoActualizados+" Actualizados";
// Actualizacion Coberturas VH
String listadoCoberturas = webService.getWebServiceCotizadorImplPort().obtenerCoberturaDetalleProducto();
String [] listadoCoberturasDetalleArr=listadoCoberturas.split("\\><");
DetalleProductoDAO detalleProductoDAO= new DetalleProductoDAO();
List<Cobertura> coberturasGrabar=new ArrayList<Cobertura>();
List<DetalleProducto> detallesGrabar=new ArrayList<DetalleProducto>();
for(String coberturaDetalleFila:listadoCoberturasDetalleArr){
String [] coberturaValores = coberturaDetalleFila.split("\\|");
cobertura = coberturaDAO.buscarPorId(coberturaValores[0]);
if(cobertura == null||cobertura.getId()==null){
cobertura = new Cobertura();
}
cobertura.setId(coberturaValores[0].toString());
cobertura.setNombre(coberturaValores[1].toString());
cobertura.setTexto(coberturaValores[2].getBytes("UTF-8"));
TipoCoberturaDAO tipoCoberturaDAO = new TipoCoberturaDAO();
TipoCobertura tipoCobertura = tipoCoberturaDAO.buscarPorId(coberturaValores[3].toString());
cobertura.setTipoCobertura(tipoCobertura);
cobertura.setTipoCobertura(tipoCobertura);
grupoCobertura = grupoCoberturaDAO.buscarPorId(coberturaValores[4].toString());
cobertura.setGrupoCobertura(grupoCobertura);
TipoTasaDAO ttDAO=new TipoTasaDAO();
TipoTasa tipoTasa=ttDAO.buscarPorId(coberturaValores[11].toString());
cobertura.setTipoTasa(tipoTasa);
cobertura.setAfectaGrupo(coberturaValores[5].toString());
cobertura.setAfectaValorAsegurado(coberturaValores[6].toString());
cobertura.setSeccion(coberturaValores[7].toString());
cobertura.setOrden(Integer.parseInt(coberturaValores[8].toString()));
cobertura.setLimite(coberturaValores[9].toString());
cobertura.setEsPredeterminada(coberturaValores[10].toString());
cobertura.setEsPrimaFija(coberturaValores[11].toString().equals("1")?"1":"0");
cobertura.setEsTodoRiesgo(coberturaValores[12].toString());
cobertura.setEsMasivo(coberturaValores[13].toString());
cobertura.setEsPrincipal(coberturaValores[14].toString());
cobertura.setRebajaValorAsegurado(coberturaValores[15].toString());
cobertura.setGeneraEndosoRasa(coberturaValores[16].toString());
cobertura.setEsIndemnizable(coberturaValores[17].toString());
cobertura.setEsLimiteSuma(coberturaValores[18].toString());
cobertura.setPrincipalCobertura(coberturaValores[19].toString());
coberturasGrabar.add(cobertura);
DetalleProducto detalleProducto=detalleProductoDAO.buscarPorId(coberturaValores[20].toString());
detalleProducto.setAfectaPrima(coberturaValores[26].toString());
detalleProducto.setAfectaValorAsegurado(coberturaValores[27].toString());
CoberturasConjuntoDAO coberturasConjuntoDAO=new CoberturasConjuntoDAO();
CoberturasConjunto coberturasConjunto=coberturasConjuntoDAO.buscarPorId(coberturaValores[22].toString());
if(coberturasConjunto!=null&&coberturasConjunto.getId()!=null)
detalleProducto.setCoberturasConjunto(coberturasConjunto);
configuracionProductoDAO=new ConfiguracionProductoDAO();
configuracionProducto=configuracionProductoDAO.buscarPorId(coberturaValores[36].toString());
if(configuracionProducto!=null&&configuracionProducto.getId()!=null)
detalleProducto.setConfiguracionProducto(configuracionProducto);
detalleProducto.setDefecto(coberturaValores[31].toString());
detalleProducto.setId(coberturaValores[20].toString());
detalleProducto.setMonto(Double.parseDouble(coberturaValores[24].toString()));
detalleProducto.setPeriodicidad(Integer.parseInt(coberturaValores[30].toString()));
planDAO=new PlanDAO();
plan=planDAO.buscarPorId(coberturaValores[21].toString());
if(plan!=null&&plan.getId()!=null)
detalleProducto.setPlan(plan);
detalleProducto.setPorccomisionvendedor(Double.parseDouble(coberturaValores[34].toString()));
detalleProducto.setPorcentajeComision(Double.parseDouble(coberturaValores[32].toString()));
detalleProducto.setPorcotros(Double.parseDouble(coberturaValores[37].toString()));
detalleProducto.setPorcutilidad(Double.parseDouble(coberturaValores[35].toString()));
detalleProducto.setPrima(Double.parseDouble(coberturaValores[25].toString()));
detalleProducto.setPrimaBasica(Double.parseDouble(coberturaValores[33].toString()));
detalleProducto.setTasa(Double.parseDouble(coberturaValores[23].toString()));
detalleProducto.setTexto(coberturaValores[28].toString().getBytes("UTF-8") );
detalleProducto.setValorPeriodo(Double.parseDouble(coberturaValores[29].toString()));
detallesGrabar.add(detalleProducto);
}
int detallesBorrados=detalleProductoDAO.eliminarTodos();
int coberturasCreados=0;
int coberturasActualizados=0;
int detalleProductoCreados=0;
int detalleProductoActualizados=0;
int cont=0;
for(Cobertura coberturaGrabar:coberturasGrabar){
if(coberturaGrabar.getId()==null){
coberturaGrabar = coberturaTransaction.crear(coberturaGrabar);
coberturasCreados++;
}
else{
coberturaGrabar = coberturaTransaction.editar(coberturaGrabar);
coberturasActualizados++;
}
DetalleProducto detalleGrabar=detallesGrabar.get(cont);
if(detalleGrabar.getId()==null){
detalleGrabar = detalleProductoTransaction.crear(detalleGrabar);
detalleProductoCreados++;
}
else{
detalleGrabar = detalleProductoTransaction.editar(detalleGrabar);
detalleProductoActualizados++;
}
cont++;
}
resultadoActualizacion +="Coberturas: "+coberturasCreados+" Nuevos "+coberturasActualizados+" Actualizados";
resultadoActualizacion +="Detalle Productos: "+detalleProductoCreados+" Nuevos "+detalleProductoActualizados+" Actualizados";
coberturasGrabar=null;
detallesGrabar=null;
// Actualizacion deducibles
String listadoDeducibles = webService.getWebServiceCotizadorImplPort().obtenerDeducibles();
String [] listadoDeduciblesArr=listadoDeducibles.split("\\><");
int deduciblesCreados=0;
int deduciblesActualizados=0;
DeducibleDAO deducibleDAO=new DeducibleDAO();
List<Deducible> deduciblesGrabar=new ArrayList<Deducible>();
for(String deducibleFila:listadoDeduciblesArr){
String [] deducibleValores = deducibleFila.split("\\|");
Deducible deducible=deducibleDAO.buscarPorProductoDeducible(deducibleValores[0],deducibleValores[1]);
if(deducible==null||deducible.getId()==null){
deducible=deducibleDAO.buscarPorCoberturaPlanDeducible(deducibleValores[0],deducibleValores[5],deducibleValores[6]);
}
if (deducible == null || deducible.getId() == null) {
deducible = new Deducible();
}
if(!deducibleValores[6].equals("0"))
deducible.setPlanId(deducibleValores[6]);
if(!deducibleValores[5].equals("0"))
deducible.setCoberturaId(deducibleValores[5]);
deducible.setTipoDeducibleId(BigInteger.valueOf(Long.parseLong(deducibleValores[3])));
deducible.setTexto(deducibleValores[2]);
deducible.setProductoId(deducibleValores[1]);
deducible.setValor(Double.parseDouble(deducibleValores[4]));
deducible.setDeducibleId(deducibleValores[0]);
deduciblesGrabar.add(deducible);
}
int deduciblesBorrados=deducibleDAO.eliminarTodos();
for(Deducible deducibleGrabar:deduciblesGrabar){
if(deducibleGrabar.getId()==null){
deducibleGrabar = deducibleTransaction.crear(deducibleGrabar);
deduciblesCreados++;
}
else{
deducibleGrabar = deducibleTransaction.editar(deducibleGrabar);
deduciblesActualizados++;
}
}
resultadoActualizacion +="Deducibles: "+deduciblesCreados+" Nuevos "+deduciblesActualizados+" Actualizados";
resultadoActualizacion += " ---- HORA FIN: "+new Date();
result.put("success", Boolean.TRUE);
result.put("resultadoActualizacion",resultadoActualizacion);
}
if(tipoConsulta.equals("actualizarEntidadJr")){
WebServiceCotizadorImplService webService = new WebServiceCotizadorImplService();
// Actualizacion EntidadesJr
String listadoEntidadesJr = webService.getWebServiceCotizadorImplPort().obtenerEntidadesJr();
String [] listadoEntidadesJrArr=listadoEntidadesJr.split("\\><");
EntidadJrDAO entidadJrDAO = new EntidadJrDAO();
System.out.println("ELIMINADOS "+entidadJrDAO.eliminarTodos()+" REGISTROS DE ENTIDADJR");
for(String entidadesJrFila:listadoEntidadesJrArr){
String [] entidadesJrValores = entidadesJrFila.split("\\|");
EntidadJr entidadJr=new EntidadJr();
entidadJr.setId(Integer.parseInt(entidadesJrValores[0]));
entidadJr.setNombre(entidadesJrValores[1]);
entidadJr.setApellido(entidadesJrValores[2]);
entidadJr.setNombreCompleto(entidadesJrValores[3]);
entidadJr.setIdentificacion(entidadesJrValores[4]);
System.out.print("EntidadJr: "+entidadJr.getId());
entidadJr = entidadJrTransaction.crear(entidadJr);
System.out.println(" CREADO");
}
}
if(tipoConsulta.equals("actualizarFirmasDigitales")){
WebServiceCotizadorImplService webService = new WebServiceCotizadorImplService();
String listadoFirmasDigitales = webService.getWebServiceCotizadorImplPort().obtenerFirmasDigitales();
String [] listadoFirmasDigitalesArr=listadoFirmasDigitales.split("\\><");
FirmasDigitalesDAO firmasDigitalesDAO = new FirmasDigitalesDAO();
for(String firmasDigitalesFila:listadoFirmasDigitalesArr){
String [] firmasDigitalesValores = firmasDigitalesFila.split("\\|");
SucursalDAO sucursalDAO=new SucursalDAO();
ramoDAO=new RamoDAO();
EntidadDAO entidadDAO=new EntidadDAO();
Entidad entidad=entidadDAO.buscarEntidadPorIdEnsurance(firmasDigitalesValores[1]);
Sucursal sucursal=sucursalDAO.buscarPorIdEnsurance(firmasDigitalesValores[2]);
ramo=ramoDAO.buscarPorId(firmasDigitalesValores[3]);
FirmasDigitales firmasDigitales=new FirmasDigitales();
String idEnsurance=firmasDigitalesValores[0];
String firmasDigitalesEstado = "";
if(sucursal!=null&&ramo!=null&&entidad!=null&&sucursal.getId()!=null&&ramo.getId()!=null&&entidad.getId()!=null){
firmasDigitales=firmasDigitalesDAO.buscarPorRamoSucursalEntidad(ramo, sucursal, entidad);
if(firmasDigitales == null||firmasDigitales.getId()==null){
firmasDigitales = new FirmasDigitales();
firmasDigitalesEstado = "NUEVO";
}
byte[] bytes = webService.getWebServiceCotizadorImplPort().obtenerFirmasDigitalesParametros(sucursal.getSucEnsurance(), entidad.getEntEnsurance(), ramo.getId());
if (bytes.length > 1) {
firmasDigitales.setFirma(bytes);
firmasDigitales.setIdEnsurance(idEnsurance);
firmasDigitales.setRamo(ramo);
firmasDigitales.setEntidad(entidad);
firmasDigitales.setSucursal(sucursal);
if (firmasDigitalesEstado.equals("NUEVO")) {
firmasDigitales = firmasDigitalesTransaction.crear(firmasDigitales);
System.out.print("FirmasDigitales: "+ firmasDigitales.getId());
System.out.println(" CREADO");
}
else {
System.out.print("FirmasDigitales: "+ firmasDigitales.getId());
firmasDigitales = firmasDigitalesTransaction.editar(firmasDigitales);
System.out.println(" ACTUALIZADO");
}
}
}
}
}
if(tipoConsulta.equals("actualizarAutorizacionSri")){
WebServiceCotizadorImplService webService = new WebServiceCotizadorImplService();
String listadoAutorizacionSRI = webService.getWebServiceCotizadorImplPort().obtenerAurotizacionesSRI();
String [] listadoAutorizacionSRIArr=listadoAutorizacionSRI.split("\\><");
AutorizacionSriDAO autorizacionSRIDAO = new AutorizacionSriDAO();
for(String autorizacionSRIFila:listadoAutorizacionSRIArr){
String [] autorizacionSRIValores = autorizacionSRIFila.split("\\|");
AutorizacionSri aSRI=new AutorizacionSri();
String autorizacionSriEstado ="";
aSRI = autorizacionSRIDAO.buscarPorIdEnsurance(autorizacionSRIValores[4]);
if(aSRI == null || aSRI.getId()==null){
aSRI = new AutorizacionSri();
autorizacionSriEstado = "NUEVO";
}
aSRI.setIdEnsurance(autorizacionSRIValores[4].toString());
aSRI.setNumero(autorizacionSRIValores[0].toString());
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
Date vigenciaDesde=sdf.parse(autorizacionSRIValores[1].toString().split(" ")[0]);
Date vigenciaHasta=sdf.parse(autorizacionSRIValores[2].toString().split(" ")[0]);
aSRI.setVigenciaDesde(vigenciaDesde);
aSRI.setVigenciaHasta(vigenciaHasta);
if(autorizacionSRIValores[3].toString().equals("0"))
aSRI.setActivo(false);
else
aSRI.setActivo(true);
if(autorizacionSriEstado.equalsIgnoreCase("NUEVO")){
aSRI = autorizacionSriTransaction.crear(aSRI);
System.out.print("AutorizacionSRI: "+aSRI.getId());
System.out.println(" CREADO");
}
else{
aSRI = autorizacionSriTransaction.editar(aSRI);
System.out.print("AutorizacionSRI: "+aSRI.getId());
System.out.println(" ACTUALIZADO");
}
}
}
if(tipoConsulta.equals("actualizarMarcasModelos")){
WebServiceCotizadorImplService webService = new WebServiceCotizadorImplService();
// Actualizacion Marcas, Modelos, Clase Vehiculo
String listadoMarcasModelos = webService.getWebServiceCotizadorImplPort().obtenerMarcasVehiculo();
JSONObject marcasJSONObject = new JSONObject();
JSONArray marcasJSONArray = new JSONArray();
if(listadoMarcasModelos.length() > 0){
String [] listadoMarcasModelosArr=listadoMarcasModelos.split("\\><");
if(listadoMarcasModelosArr.length>1){
for(String fila:listadoMarcasModelosArr){
String [] marcasModelosValores = fila.split("\\|");
Marca marca = new Marca();
MarcaDAO mDao= new MarcaDAO();
ModeloDAO moDao = new ModeloDAO();
Modelo modelo = new Modelo();
marca = mDao.buscarPorCodigoEnsurance(marcasModelosValores[0]);
if(marca.getId()== null){
marca.setMarEnsurance(marcasModelosValores[0]);
marca.setNombre(marcasModelosValores[1]);
marca.setActivo(true);
marcaTransaction.crear(marca);
ClaseVehiculo claseVehiculo = new ClaseVehiculo();
ClaseVehiculoDAO clDao = new ClaseVehiculoDAO();
claseVehiculo.setNombre(marcasModelosValores[5]);
claseVehiculo.setActivo(true);
claseVehiculoTransaction.crear(claseVehiculo);
modelo = new Modelo();
moDao = new ModeloDAO();
modelo.setMarca(marca);
modelo.setClaseVehiculo(claseVehiculo);
modelo.setModEnsurance(marcasModelosValores[2]);
modelo.setNombre(marcasModelosValores[3]);
modeloTransaction.crear(modelo);
marcasJSONObject.put("marca", marcasModelosValores[1]);
marcasJSONObject.put("modelo", marcasModelosValores[5]);
marcasJSONObject.put("clase", marcasModelosValores[3]);
}
else{
modelo = new Modelo();
modelo = moDao.buscarPorCodigoEnsurance(marcasModelosValores[2]);
if(modelo.getId()== null){
modelo.setMarca(marca);
//modelo.setClaseVehiculo(claseVehiculo);
modelo.setModEnsurance(marcasModelosValores[2]);
modelo.setNombre(marcasModelosValores[3]);
modeloTransaction.crear(modelo);
marcasJSONObject.put("marca", marcasModelosValores[1]);
marcasJSONObject.put("modelo", marcasModelosValores[5]);
marcasJSONObject.put("clase", marcasModelosValores[3]);
}
}
marcasJSONArray.add(marcasJSONObject);
}
}
}
result.put("success", Boolean.TRUE);
result.put("listadoMarcas", marcasJSONArray);
}
if(tipoConsulta.equals("actualizarColores")){
WebServiceCotizadorImplService webService = new WebServiceCotizadorImplService();
// Actualizacion Colores
String listadoColores = webService.getWebServiceCotizadorImplPort().obtenerColoresVehiculo();
JSONObject coloresJSONObject = new JSONObject();
JSONArray coloresJSONArray = new JSONArray();
if(listadoColores.length() > 0){
String [] listadoColoresArr=listadoColores.split("\\><");
if(listadoColoresArr.length>0){
for(String fila:listadoColoresArr){
String [] coloresValores = fila.split("\\|");
Color color = new Color();
ColorDAO coDao= new ColorDAO();
color = coDao.buscarPorCodigoEnsurance(coloresValores[0]);
if(color.getId()== null){
color.setColEnsurance(coloresValores[0]);
color.setNombre(coloresValores[1]);
color.setActivo(false);
colorTransaction.crear(color);
System.out.println("CREADO");
coloresJSONObject.put("color", coloresValores[1]);
}
coloresJSONArray.add(coloresJSONObject);
}
}
}
result.put("success", Boolean.TRUE);
result.put("listadoColor", coloresJSONArray);
}
if(tipoConsulta.equals("actualizarTipoExtras")){
WebServiceCotizadorImplService webService = new WebServiceCotizadorImplService();
// Actualizacion TipoExtras
String listadoTipoExtras = webService.getWebServiceCotizadorImplPort().obtenerTipoExtra();
JSONObject extrasJSONObject = new JSONObject();
JSONArray extrasJSONArray = new JSONArray();
if(listadoTipoExtras.length() > 0){
String [] listadoTipoExtrasArr=listadoTipoExtras.split("\\><");
if(listadoTipoExtrasArr.length>0){
for(String fila:listadoTipoExtrasArr){
String [] marcasTipoExtrasValores = fila.split("\\|");
TipoExtra tipoExtra = new TipoExtra();
TipoExtraDAO tipoExtraDAO = new TipoExtraDAO();
tipoExtra = tipoExtraDAO.buscarPorIdEnsurance(marcasTipoExtrasValores[0]);
if(tipoExtra.getId()== null){
tipoExtra.setTipExtEnsurance(marcasTipoExtrasValores[0]);
tipoExtra.setNombre(marcasTipoExtrasValores[1]);
tipoExtra.setActivo(true);
tipoExtraTransaction.crear(tipoExtra);
extrasJSONObject.put("extra", marcasTipoExtrasValores[1]);
System.out.println("CREADO");
extrasJSONArray.add(extrasJSONObject);
}
}
}
}
result.put("success", Boolean.TRUE);
result.put("listadoExtras", extrasJSONArray);
}
if(tipoConsulta.equals("actualizarProductosGanadero")){
WebServiceCotizadorImplService webService = new WebServiceCotizadorImplService();
// Actualizacion Productos ganadero
String listadoProducto = webService.getWebServiceCotizadorImplPort().obtenerProductosGanadero();
String [] listadoProductoArr =listadoProducto.split("\\><");
for(String productoFila:listadoProductoArr){
String [] productoValores = productoFila.split("\\|");
String productoEstado = "";
producto = productoDAO.buscarPorId(productoValores[0]);
if(producto == null){
producto = new Producto();
productoEstado = "NUEVO";
}
producto.setId(productoValores[0].toString());
producto.setNombre(productoValores[1].toString());
producto.setRamoId(new BigInteger(productoValores[2].toString()));
producto.setDefecto(productoValores[3].toString());
producto.setVigencia(Integer.parseInt(productoValores[4].toString()));
producto.setDinamico(productoValores[5].toString());
if(productoEstado.equalsIgnoreCase("NUEVO")){
System.out.print("Producto: "+producto.getId());
producto = productoTransaction.crear(producto);
System.out.println(" CREADO");
}
else{
System.out.print("Producto: "+producto.getId());
producto = productoTransaction.editar(producto);
System.out.println(" ACTUALIZADO");
}
}
}
session.setMaxInactiveInterval(1*60*60);
result.put("success", Boolean.TRUE);
response.setContentType("application/json; charset=ISO-8859-1");
result.write(response.getWriter());
}catch(Exception e){
session.setMaxInactiveInterval(1*60*60);
result.put("success", Boolean.FALSE);
result.put("error", e.getLocalizedMessage());
response.setContentType("application/json; charset=ISO-8859-1");
result.write(response.getWriter());
e.printStackTrace();
}
}
}
| true |
c4a8724b3544ea46c1634bd4f3cff0ea87f27c43 | Java | cervm/WesternStyle | /src/test/java/modelCollections/DBCustomersTest.java | UTF-8 | 4,203 | 2.828125 | 3 | [] | no_license | package modelCollections;
import model.CustomerGroup;
import model.entity.Customer;
import model.exception.ModelSyncException;
import org.junit.BeforeClass;
import org.junit.Test;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
/**
* Tests for Customers DAO
*/
public class DBCustomersTest {
private static DBCustomers customers;
@BeforeClass
public static void setUp() throws Exception {
customers = new DBCustomers();
}
@Test
public void load() throws Exception {
customers.load();
Field array = customers.getClass().getDeclaredField("customers");
array.setAccessible(true);
ArrayList<Customer> list = (ArrayList<Customer>) array.get(customers);
assertNotEquals("Empty table or fetching error", 0, list.size());
}
@Test
public void getAll() throws Exception {
List<Customer> c = customers.getAll();
assertNotEquals("Empty table or fetching error", 0, c.size());
}
@Test
public void getById() throws Exception {
Customer c = customers.getById(22);
assertEquals(1, c.getGroupID());
}
@Test
public void createDelete() throws Exception {
// Initial list size
List<Customer> c = customers.getAll();
int initialSize = c.size();
// Create new object
Customer temp = new Customer("test", "tefgst", "test1", "test", "test", "test", "PL", 1);
temp = customers.create(temp);
int tempId = temp.getId();
// Check the list size after creation
c = customers.getAll();
int creationSize = c.size();
// Delete the object
customers.delete(temp);
// Check the list size after deletion
c = customers.getAll();
int deletionSize = c.size();
assertNotEquals("The customer not created", creationSize, initialSize);
assertEquals("The customer not deleted. The id is " + tempId, deletionSize, initialSize);
}
@Test
public void update() throws Exception {
String street = "308 Negro Arroyo Lane";
customers.load();
Customer c = customers.getById(24);
c.setAddress(street);
customers.update(c);
customers.load();
assertEquals(street, customers.getById(24).getAddress());
}
@Test
public void updateMultiple() throws Exception {
String phone = "721312709";
String city = "Zbonszynek";
customers.load();
Customer c = customers.getById(21);
c.setPhone(phone);
c.setCity(city);
customers.update(c);
DBCustomers c2 = new DBCustomers();
assertEquals(phone, c2.getById(21).getPhone());
assertEquals(city, c2.getById(21).getCity());
}
@Test
public void getCustomerGroupsTest() throws Exception {
List<CustomerGroup> groups = customers.getCustomerGroups();
assertNotEquals(0, groups.size());
}
@Test
public void assignToGroupTest() throws Exception {
int newGroupID = 2;
customers.load();
Customer c = customers.getById(24);
customers.assignToGroup(c, customers.getCustomerGroups().get(1));
assertEquals(newGroupID, c.getGroupID());
}
@Test(expected = NoSuchElementException.class)
public void getByIDNoSuchElementExceptionTest() throws Exception {
customers.getById(-1);
}
@Test(expected = NullPointerException.class)
public void updateExceptionTest() throws Exception {
customers.update(null);
}
@Test(expected = ModelSyncException.class)
public void updateInvalidObjectTest() throws Exception {
Customer c = new Customer("Richard Cheese", "dfgsdgsdfgsdfgsdfgsdfg", "1", null, null, null, "DA", 1);
customers.update(c);
}
@Test(expected = ModelSyncException.class)
public void createInvalidObjectTest() throws Exception {
Customer c = new Customer("Richard Cheese", "dfgsdgsdfgsdfgsdfgsdfg", "1", null, null, null, "DA", 1);
customers.create(c);
}
} | true |
94c797558a482439c8aedfab96c2df8d7578d0dc | Java | CodePredator01/JAVA-CODES | /JAVA_CODES/src/labTasks/LabTask2A.java | UTF-8 | 2,008 | 3.5 | 4 | [] | no_license | /*
* Created by IntelliJ IDEA.
* User: Priyanshu (CodePredator01)
* Date: 11-08-2020
* Time: 08:52 PM
* File: LabTask3.java
* */
// Task2A : Create a program in java that prints the range table.
package labTasks;
public class LabTask2A {
public static void main(String[] args) {
System.out.println("-------------------------------------------------------------------------------------------------");
System.out.printf("|\t%-13s|\t%-14s|\t%-14s|\t\t\t\t\t%-28s|\n", "data type", "size in bits", "size in bytes", "range");
System.out.println("-------------------------------------------------------------------------------------------------");
System.out.printf("|\t%-13s|\t%-14d|\t%-14s| %-43s |\n", "byte", Byte.SIZE, Byte.SIZE / 8, Byte.MIN_VALUE + " to " + Byte.MAX_VALUE);
System.out.printf("|\t%-13s|\t%-14d|\t%-14s| %-43s |\n", "int", Integer.SIZE, Integer.SIZE / 8, Integer.MIN_VALUE + " to " + Integer.MAX_VALUE);
System.out.printf("|\t%-13s|\t%-14d|\t%-14s| %-43s |\n", "short", Short.SIZE, Short.SIZE / 8, Short.MIN_VALUE + " to " + Short.MAX_VALUE);
System.out.printf("|\t%-13s|\t%-14d|\t%-14s| %-43s |\n", "long", Long.SIZE, Long.SIZE / 8, Long.MIN_VALUE + " to " + Long.MAX_VALUE);
System.out.printf("|\t%-13s|\t%-14d|\t%-14s| %-43s |\n", "float", Float.SIZE, Float.SIZE / 8, Float.MIN_VALUE + " to " + Float.MAX_VALUE);
System.out.printf("|\t%-13s|\t%-14d|\t%-14s| %-43s |\n", "double", Double.SIZE, Double.SIZE / 8, Double.MIN_VALUE + " to " + Double.MAX_VALUE);
System.out.printf("|\t%-13s|\t%-14d|\t%-14s| %-43s |\n", "char", Character.SIZE, Character.SIZE / 8, (int) Character.MIN_VALUE + " to " + (int) Character.MAX_VALUE);
System.out.printf("|\t%-13s|\t%-14d|\t%-14s| %-43s |\n", "boolean", 1, (double) 1 / 8, Boolean.TRUE + " to " + Boolean.FALSE);
System.out.println("-------------------------------------------------------------------------------------------------");
}
}
| true |
9e6ea23487671aeea5dbd6fb72b27cc75db01ca6 | Java | ArbustaIT/CapacitacionAutomation | /src/main/java/co/com/arbusta/capacitacion/autoScreenplayCucumber/userinterfaces/UIMicuenta.java | UTF-8 | 958 | 1.640625 | 2 | [] | no_license | package co.com.arbusta.capacitacion.autoScreenplayCucumber.userinterfaces;
import org.openqa.selenium.By;
import net.serenitybdd.screenplay.targets.Target;
public class UIMicuenta {
public static final Target BTN_CUENTA = Target.the("Botón Mi cuentas").located(By.xpath("//header/div[2]/div[1]/div[1]/nav[1]/div[1]/a[1]"));
public static final Target BTN_HISTORIALCOMPRA = Target.the("Botón de historial de compra").located(By.xpath("//*[@id=\"center_column\"]/div/div[1]/ul/li[1]/a"));
public static final Target BTN_FACTURA = Target.the("Botón de factura de compra").located(By.xpath("//*[@id=\"order-list\"]/tbody/tr[1]/td[6]/a"));
public static final Target BTN_DETALLES = Target.the("Botón detalles de compra").located(By.xpath("//*[@id=\"order-list\"]/tbody/tr[1]/td[7]/a[1]"));
public static final Target BTN_REORDENAR = Target.the("Botón de reordenar compra").located(By.xpath("//*[@id=\"order-list\"]/tbody/tr[1]/td[7]/a[2]"));
}
| true |
712785e06ce94773494708ce5c0d34d76b277db1 | Java | cderian/Curso-AppsAndroid | /Curso 1 Java/Semana 2/Netflix/src/com/cderian/netflix/Pelicula.java | ISO-8859-1 | 1,065 | 2.96875 | 3 | [] | no_license | package com.cderian.netflix;
public class Pelicula extends Proyeccion implements Visualizable {
private int anio;
public Pelicula() {
super();
}
public Pelicula(String titulo, String creador) {
super(titulo, creador);
this.anio = 0;
}
public Pelicula(String titulo, String creador, String genero, int duracion, int anio) {
super (titulo, creador, genero, duracion);
this.anio = anio;
}
public int getAnio() {
return anio;
}
public void setAnio(int anio) {
this.anio = anio;
}
public String toString() {
String info = super.toString("Pelcula");
info+= "Ao: " + anio + "\n";
return info;
}
@Override
public void marcarVisto() {
super.visto = true;
}
@Override
public boolean esVisto() {
return super.visto;
}
@Override
public double tiempoVisto() {
double tiempo = super.getDuracion();
if (tiempo > 110 && tiempo < 130) {
tiempo = tiempo*1.3;
} else if (tiempo > 130 && tiempo < 180) {
tiempo = tiempo*1.5;
} else if (tiempo > 180) {
tiempo = tiempo*1.8;
}
return tiempo;
}
} | true |
78398bfc57495ffa476bfd157c74fa84683f1f29 | Java | BioinformaticsArchive/GenPlay | /trunk/GenPlay/src/edu/yu/einstein/genplay/core/IO/extractor/GFFExtractor.java | UTF-8 | 6,405 | 2.28125 | 2 | [] | no_license | /*******************************************************************************
* GenPlay, Einstein Genome Analyzer
* Copyright (C) 2009, 2014 Albert Einstein College of Medicine
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* Authors: Julien Lajugie <julien.lajugie@einstein.yu.edu>
* Nicolas Fourel <nicolas.fourel@einstein.yu.edu>
* Eric Bouhassira <eric.bouhassira@einstein.yu.edu>
*
* Website: <http://genplay.einstein.yu.edu>
******************************************************************************/
package edu.yu.einstein.genplay.core.IO.extractor;
import java.io.File;
import java.io.FileNotFoundException;
import edu.yu.einstein.genplay.core.IO.dataReader.RepeatReader;
import edu.yu.einstein.genplay.core.IO.dataReader.SCWReader;
import edu.yu.einstein.genplay.core.IO.dataReader.StrandReader;
import edu.yu.einstein.genplay.core.IO.utils.DataLineValidator;
import edu.yu.einstein.genplay.core.IO.utils.Extractors;
import edu.yu.einstein.genplay.core.IO.utils.StrandedExtractorOptions;
import edu.yu.einstein.genplay.dataStructure.chromosome.Chromosome;
import edu.yu.einstein.genplay.dataStructure.chromosomeWindow.SimpleChromosomeWindow;
import edu.yu.einstein.genplay.dataStructure.enums.Strand;
import edu.yu.einstein.genplay.exception.exceptions.DataLineException;
import edu.yu.einstein.genplay.exception.exceptions.InvalidChromosomeException;
/**
* A GFF file extractor
* @author Julien Lajugie
*/
public final class GFFExtractor extends TextFileExtractor implements SCWReader, RepeatReader, StrandReader, StrandedExtractor {
/** Default first base position of bed files. GFF files are 1-based */
public static final int DEFAULT_FIRST_BASE_POSITION = 1;
private int firstBasePosition = DEFAULT_FIRST_BASE_POSITION;// position of the first base
private StrandedExtractorOptions strandOptions; // options on the strand and read length / shift
private Chromosome chromosome; // chromosome of the last item read
private Integer start; // start position of the last item read
private Integer stop; // stop position of the last item read
private String name; // name of the last item read
private Float score; // score of the last item read
private Strand strand; // strand of the last item read
/**
* Creates an instance of {@link GFFExtractor}
* @param dataFile file containing the data
* @throws FileNotFoundException if the specified file is not found
*/
public GFFExtractor(File dataFile) throws FileNotFoundException {
super(dataFile);
}
@Override
protected int extractDataLine(String line) throws DataLineException {
chromosome = null;
start = null;
stop = null;
name = null;
score = null;
strand = null;
String[] splitedLine = Extractors.parseLineTabOnly(line);
if (splitedLine.length < 7) {
throw new DataLineException(DataLineException.INVALID_PARAMETER_NUMBER);
}
// chromosome
String chromosomeName = splitedLine[0];
if (getChromosomeSelector() != null) {
// case where last chromosome already extracted, no more data to extract
if (getChromosomeSelector().isExtractionDone(chromosomeName)) {
return EXTRACTION_DONE;
}
// chromosome was not selected for extraction
if (!getChromosomeSelector().isSelected(chromosomeName)) {
return LINE_SKIPPED;
}
}
try {
chromosome = getProjectChromosome().get(chromosomeName) ;
} catch (InvalidChromosomeException e) {
// unknown chromosome
return LINE_SKIPPED;
}
// strand
strand = Strand.get(splitedLine[6].trim().charAt(0));
if ((strand != null) && (strandOptions != null) && (!strandOptions.isSelected(strand))) {
chromosome = null;
return LINE_SKIPPED;
}
// start and stop
start = Extractors.getInt(splitedLine[3]);
stop = Extractors.getInt(splitedLine[4]);
String errors = DataLineValidator.getErrors(chromosome, start, stop);
if (!errors.isEmpty()) {
throw new DataLineException(errors);
}
// Stop position checking, must not be greater than the chromosome length
String stopEndErrorMessage = DataLineValidator.getErrors(chromosome, stop);
if (!stopEndErrorMessage.isEmpty()) {
DataLineException stopEndException = new DataLineException(stopEndErrorMessage, DataLineException.SHRINK_STOP_PROCESS);
// notify the listeners that the stop position needed to be shrunk
notifyDataEventListeners(stopEndException, getCurrentLineNumber(), line);
stop = chromosome.getLength();
}
// compute the read position with specified strand shift and read length
if (strandOptions != null) {
SimpleChromosomeWindow resultStartStop = strandOptions.computeStartStop(chromosome, start, stop, strand);
start = resultStartStop.getStart();
stop = resultStartStop.getStop();
}
// if we are in a multi-genome project, we compute the position on the meta genome
start = getRealGenomePosition(chromosome, start);
stop = getRealGenomePosition(chromosome, stop);
// name and score
name = splitedLine[2];
score = Extractors.getFloat(splitedLine[5]);
return ITEM_EXTRACTED;
}
@Override
public Chromosome getChromosome() {
return chromosome;
}
@Override
public int getFirstBasePosition() {
return firstBasePosition;
}
@Override
public String getName() {
return name;
}
@Override
public Float getScore() {
return score;
}
@Override
public Integer getStart() {
return start;
}
@Override
public Integer getStop() {
return stop;
}
@Override
public Strand getStrand() {
return strand;
}
@Override
public StrandedExtractorOptions getStrandedExtractorOptions() {
return strandOptions;
}
@Override
public void setFirstBasePosition(int firstBasePosition) {
this.firstBasePosition = firstBasePosition;
}
@Override
public void setStrandedExtractorOptions(StrandedExtractorOptions options) {
strandOptions = options;
}
}
| true |
af9bdc5f028c37d22e62d5291a02d0faa928278b | Java | Travis40508/MusicApp | /app/src/main/java/com/elkcreek/rodneytressler/musicapp/di/modules/MusicDatabaseModule.java | UTF-8 | 1,461 | 2.140625 | 2 | [] | no_license | package com.elkcreek.rodneytressler.musicapp.di.modules;
import android.arch.persistence.room.Room;
import android.arch.persistence.room.RoomDatabase;
import android.content.Context;
import android.content.SharedPreferences;
import com.elkcreek.rodneytressler.musicapp.repo.database.MusicDatabase;
import com.elkcreek.rodneytressler.musicapp.services.MusicDatabaseService;
import com.elkcreek.rodneytressler.musicapp.services.MusicDatabaseServiceImpl;
import com.elkcreek.rodneytressler.musicapp.utils.Constants;
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
@Module
public class MusicDatabaseModule {
@Provides
@Singleton
MusicDatabase providesMusicDatabase(Context context) {
MusicDatabase musicDatabase = Room.databaseBuilder
(context.getApplicationContext(),
MusicDatabase.class,
Constants.DATABASE_KEY)
.build();
return musicDatabase;
}
@Provides
MusicDatabaseService providesMusicDatabaseService(MusicDatabase musicDatabase, SharedPreferences sharedPreferences) {
return new MusicDatabaseServiceImpl(musicDatabase, sharedPreferences);
}
@Provides
SharedPreferences providesSharedPreferences(Context context) {
SharedPreferences sharedPreferences = context.getSharedPreferences(Constants.SHAREDPREFKEY, Context.MODE_PRIVATE);
return sharedPreferences;
}
}
| true |
693056917b11d6a59317b8b77cd444f131153c7e | Java | jjcard/TextAdventurePackage | /src/main/java/jjcard/text/game/impl/Player.java | UTF-8 | 4,281 | 2.734375 | 3 | [
"Apache-2.0",
"MIT"
] | permissive | package jjcard.text.game.impl;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import jjcard.text.game.IArmour;
import jjcard.text.game.IItem;
import jjcard.text.game.IStatus;
import jjcard.text.game.IWeapon;
import jjcard.text.game.leveling.HasLeveling;
import jjcard.text.game.util.ObjectsUtil;
@JsonDeserialize(builder = Player.Builder.class)
public class Player extends Mob implements HasLeveling{
@JsonProperty("lvl")
private int level;
@JsonProperty("xp")
private int xp;
public static class Builder extends Mob.Builder{
private int level;
private int xp;
public Builder(){
super();
}
public Builder(Player p){
super(p);
this.xp = p.xp;
this.level = p.level;
}
public Builder(AbstractGameElement g){
super(g);
}
@Override
public Builder name(String name){
super.name(name);
return this;
}
@JsonProperty("lvl")
public Builder level(int level){
this.level = level;
return this;
}
@JsonProperty("xp")
public Builder xp(int xp){
this.xp = xp;
return this;
}
@Override
public Builder checkHealth(boolean checkHealth){
super.checkHealth(checkHealth);
return this;
}
@Override
public Builder roomDescription(String roomDescrip){
super.roomDescription(roomDescrip);
return this;
}
@Override
public Builder maxHealth(int maxHealth){
super.maxHealth(maxHealth);
return this;
}
@Override
public Builder health(int curHealth){
super.health(curHealth);
return this;
}
@Override
public Builder viewDescription(String description){
super.viewDescription(description);
return this;
}
@Override
public Builder money(int money){
super.money(money);
return this;
}
@Override
public Builder inventory(Map<String, IItem> inventory){
super.inventory(inventory);
return this;
}
@Override
public Builder addItem(IItem item){
super.addItem(item);
return this;
}
@Override
public Builder defense(int defense){
super.defense(defense);
return this;
}
@Override
public Builder attack(int attack){
super.attack(attack);
return this;
}
@Override
public Builder hostile(boolean hostile){
super.hostile(hostile);
return this;
}
@Override
public Builder statusList(List<IStatus> statusList){
super.statusList(statusList);
return this;
}
@Override
public Builder armour(IArmour armour){
super.armour(armour);
return this;
}
@Override
public Builder weapon(IWeapon weapon){
super.weapon(weapon);
return this;
}
@Override
public Builder addStatus(IStatus status){
super.addStatus(status);
return this;
}
@Override
public Builder validateFields(boolean validateFields){
super.validateFields(validateFields);
return this;
}
@Override
public Builder hidden(boolean hidden){
super.hidden(hidden);
return this;
}
@Override
public Player build(){
return new Player(this);
}
}
protected Player(Builder b){
super(b);
setXp(b.xp);
setLevel(b.level);
}
public Player(String name){
super(name);
}
/**
* Returns level
*/
@Override
public int getLevel(){
return level;
}
/**
* Returns xp
*/
@Override
public int getXp() {
return xp;
}
public void changeLevel(int change){
setLevel(level + change);
}
@Override
public void setLevel(int levelN){
level = levelN;
if (doValidateFields() && level < 0){
level = 0;
}
}
public void changeXp(int change){
setXp(this.xp + change);
}
public void setXp(int xpN){
xp = xpN;
if (doValidateFields() && xp < 0){
xp = 0;
}
}
@Override
public boolean equals(Object o){
if (o == this){
return true;
}
if (o instanceof Player){
if (!super.equals(o)){
return false;
}
Player p = (Player) o;
if (p.xp != xp){
return false;
}
if (level != p.level){
return false;
}
return true;
} else {
return false;
}
}
@Override
public int hashCode(){
return ObjectsUtil.getHashWithStart(super.hashCode(),
xp, level);
}
}
| true |
9a2dda7b439daea723d9296c2e40d844964dd1bf | Java | rkamath3/chocosolver | /src/main/java/org/clafer/choco/constraint/propagator/PropReifyEqualXC.java | UTF-8 | 2,930 | 2.421875 | 2 | [
"MIT"
] | permissive | package org.clafer.choco.constraint.propagator;
import org.chocosolver.solver.constraints.Propagator;
import org.chocosolver.solver.constraints.PropagatorPriority;
import org.chocosolver.solver.exception.ContradictionException;
import org.chocosolver.solver.variables.BoolVar;
import org.chocosolver.solver.variables.IntVar;
import org.chocosolver.solver.variables.events.IntEventType;
import org.chocosolver.util.ESat;
/**
* (reify = reifyC) <=> (x = c)
*
* @author jimmy
*/
public class PropReifyEqualXC extends Propagator<IntVar> {
private final IntVar reify;
private final int reifyC;
private final IntVar x;
private final int c;
public PropReifyEqualXC(BoolVar reify, boolean reifyC, IntVar x, int c) {
this(reify, reifyC ? 1 : 0, x, c);
}
public PropReifyEqualXC(IntVar reify, int reifyC, IntVar x, int c) {
super(new IntVar[]{reify, x}, PropagatorPriority.UNARY, true);
this.reify = reify;
this.reifyC = reifyC;
this.x = x;
this.c = c;
}
private boolean isReifyVar(int idx) {
return idx == 0;
}
private boolean isXVar(int idx) {
return idx == 1;
}
@Override
public int getPropagationConditions(int vIdx) {
return IntEventType.all();
}
private void propagateReifyVar() throws ContradictionException {
assert reify.isInstantiated();
if (reify.getValue() == reifyC) {
x.instantiateTo(c, aCause);
} else {
x.removeValue(c, aCause);
}
setPassive();
}
private void propagateXVar() throws ContradictionException {
if (x.contains(c)) {
if (x.isInstantiated()) {
reify.instantiateTo(reifyC, aCause);
setPassive();
}
} else {
reify.instantiateTo(1 - reifyC, aCause);
setPassive();
}
}
@Override
public void propagate(int evtmask) throws ContradictionException {
if (reify.isInstantiated()) {
propagateReifyVar();
} else {
propagateXVar();
}
}
@Override
public void propagate(int idxVarInProp, int mask) throws ContradictionException {
if (isReifyVar(idxVarInProp)) {
propagateReifyVar();
} else {
assert isXVar(idxVarInProp);
propagateXVar();
}
}
@Override
public ESat isEntailed() {
if (reify.isInstantiated()) {
if (!x.contains(c)) {
return reify.getValue() == reifyC ? ESat.FALSE : ESat.TRUE;
}
if (x.isInstantiated()) {
return reify.getValue() == reifyC ? ESat.TRUE : ESat.FALSE;
}
}
return ESat.UNDEFINED;
}
@Override
public String toString() {
return (reifyC == 1 ? reify : "!" + reify) + " <=> (" + x + " = " + c + ")";
}
}
| true |
db1d7961f72cbfbd4e981acf626628c5387f1966 | Java | hanuz06/chemcool | /security-package/authorization/auth-service/src/main/java/com/chemcool/school/auth/service/service/UserRegistrationService.java | UTF-8 | 200 | 1.75 | 2 | [] | no_license | package com.chemcool.school.auth.service.service;
import com.chemcool.school.auth.service.domain.RegisterUser;
public interface UserRegistrationService {
void save(RegisterUser registerUser);
}
| true |
70148c5b5bcb7277197510e59bd5db68a657b0e8 | Java | AlberGDeveloper/FirebaseAgenda | /app/src/main/java/com/appalber/firebaseagenda/MainActivity.java | UTF-8 | 1,156 | 2 | 2 | [] | no_license |
package com.appalber.firebaseagenda;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button alta = findViewById(R.id.btn_alta);
Button muestra = findViewById(R.id.btn_mostrar);
alta.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(com.appalber.firebaseagenda.MainActivity.this, AltaContactos.class);
startActivity(intent);
}
});
muestra.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(com.appalber.firebaseagenda.MainActivity.this, ActivityVistaContactos.class);
startActivity(intent);
}
});
}
} | true |
ab4dcfe900d07bd8264f94ae4a2740b994f34756 | Java | yiting1122/sort | /suanfa/src/com/suanfa/paixu/QuickSort.java | UTF-8 | 777 | 3.296875 | 3 | [] | no_license | package com.suanfa.paixu;
public class QuickSort {
/**
* @param args
*/
public static void main(String[] args) {
int a[] = { 1,54,6,3,78,34,12,45,56,100};
quickSort(a,0,a.length-1);
for (int i : a) {
System.out.println(i);
}
}
private static int getMiddle(int[] a,int start,int end) {
int temp=a[start];
while(start<end){
while(end>start&&a[end]>=temp){
end--;
}
a[start]=a[end];
while(start<end&&a[start]<=temp){
start++;
}
a[end]=a[start];
}
a[start]=temp;
return start;
}
public static void quickSort(int[] a,int start,int end){
if(start<end){
int middle=getMiddle(a, start, end);
quickSort(a, start, middle-1);
quickSort(a, middle+1, end);
}
}
}
| true |
165f0980eadf4945369603a5cfecad47f27f8b93 | Java | Litier/laboratorio-java | /src/test/java/es/ingantosan/labjava/mybatis/bitácora/dominio/Autor.java | UTF-8 | 1,945 | 2.375 | 2 | [] | no_license | package es.ingantosan.labjava.mybatis.bitácora.dominio;
import java.util.List;
public class Autor {
private int id;
private String nombre;
private String usuario;
private String contraseña;
private String correo;
private String bio;
private List<Bitácora> bitácoras;
private List<Artículo> artículos;
public Autor() {
}
public Autor(int id) {
this.id = id;
}
public Autor(int id, String nombre, String usuario, String contraseña, String correo, String bio) {
this.id = id;
this.nombre = nombre;
this.usuario = usuario;
this.contraseña = contraseña;
this.correo = correo;
this.bio = bio;
}
public List<Bitácora> getBitácoras() {
return bitácoras;
}
public void setBitácoras(List<Bitácora> bitácoras) {
this.bitácoras = bitácoras;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getUsuario() {
return usuario;
}
public void setUsuario(String usuario) {
this.usuario = usuario;
}
public String getContraseña() {
return contraseña;
}
public void setContraseña(String contraseña) {
this.contraseña = contraseña;
}
public String getCorreo() {
return correo;
}
public void setCorreo(String correo) {
this.correo = correo;
}
public String getBio() {
return bio;
}
public void setBio(String bio) {
this.bio = bio;
}
public List<Artículo> getArtículos() {
return artículos;
}
public void setArtículos(List<Artículo> artículos) {
this.artículos = artículos;
}
}
| true |
ca010ce445e97805d73c43dcb41f10180b0ffbad | Java | caiweihao/KotlinSyntacticDemo | /src/Test.java | UTF-8 | 511 | 3.296875 | 3 | [] | no_license | import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(String[] args) {
List<String> strings = new ArrayList<>();
instanceOf(123);
instanceOf("1234");
strings.stream();
}
public static void instanceOf(Object object) {
if (object instanceof String) {
System.out.println("string length is " + ((String )object).length());
} else {
System.out.println("is not String");
}
}
}
| true |
f329faf5abaf1efc431113f2840ecb23cfe7316a | Java | RochelleTaylor/4-ALL | /src/main/java/com/fourall/fourall/PhotoMetaData.java | UTF-8 | 430 | 2.21875 | 2 | [] | no_license | package com.fourall.fourall;
import java.io.File;
import java.io.IOException;
import com.drew.imaging.ImageMetadataReader;
import com.drew.imaging.ImageProcessingException;
import com.drew.metadata.Metadata;
public class PhotoMetaData {
public Metadata getPhotoData(String imgPath) throws ImageProcessingException, IOException {
File jpegFile = new File(imgPath);
return ImageMetadataReader.readMetadata(jpegFile);
}
}
| true |
c396f0264a265b4548198fc5cabf6239622308e2 | Java | choishin/DataAnalysis | /openCSV-project - 코로나,버스,지하철 이용객 수의 상관관계/src/Transportation/Subway.java | UHC | 5,941 | 2.84375 | 3 | [
"Apache-2.0"
] | permissive | package Transportation;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import com.opencsv.CSVReader;
import com.opencsv.CSVWriter;
public class Subway {
public static void main(String[] args) throws IOException {
getSubway();
}
public static void getSubway() throws IOException {
// TODO Auto-generated method stub
String readFileName = "C:\\Users\\ֽ\\Desktop\\Data\\01\\ﱳ 2020 Ϻ ð뺰 ο(1_8ȣ).csv";
String writeFileName = "C:\\Users\\ֽ\\Desktop\\subway.csv";
CSVReader csvReader;
CSVWriter cw = null;
try {
cw = new CSVWriter(new FileWriter((writeFileName), true));
csvReader = new CSVReader(new InputStreamReader(new FileInputStream(readFileName), "CP949"));
String[] nextLine;
// پ dataȿ ֱ
List<String> data = new ArrayList<String>();
while ((nextLine = csvReader.readNext()) != null) {
data.add(String.join("\t", nextLine));
}
// ߹迭 ܾ ֱ(Hashset->ArrayList)
String[][] words = new String[data.size()][];
HashSet<String> dateSet = new HashSet<String>();
for (int i = 1; i < data.size(); i++) {
words[i] = data.get(i).split("\t");
// ¥ ְ
dateSet.add(words[i][0]);
}
List<String> dateArr = new ArrayList<String>(dateSet);
Collections.sort(dateArr);
// ¥ ջϱ
int[] getOn = new int[dateArr.size()];
int[] getOff = new int[dateArr.size()];
for (int i = 0; i < dateArr.size(); i++) {
getOn[i] = 0;
getOff[i] = 0;
}
for (int i = 1; i < data.size(); i=i+2) {
for (int j = 0; j < dateArr.size(); j++) {
words[i] = data.get(i).split("\t");
if (words[i][0].contains(dateArr.get(j))) {
try {
int temp_getOn5 = Integer.parseInt(words[i][5]);
int temp_getOn6 = Integer.parseInt(words[i][6]);
int temp_getOn7 = Integer.parseInt(words[i][7]);
int temp_getOn8 = Integer.parseInt(words[i][8]);
int temp_getOn9 = Integer.parseInt(words[i][9]);
int temp_getOn10 = Integer.parseInt(words[i][10]);
int temp_getOn11 = Integer.parseInt(words[i][11]);
int temp_getOn12 = Integer.parseInt(words[i][12]);
int temp_getOn13 = Integer.parseInt(words[i][13]);
int temp_getOn14 = Integer.parseInt(words[i][14]);
int temp_getOn15 = Integer.parseInt(words[i][15]);
int temp_getOn16 = Integer.parseInt(words[i][16]);
int temp_getOn17 = Integer.parseInt(words[i][17]);
int temp_getOn18 = Integer.parseInt(words[i][18]);
int temp_getOn19 = Integer.parseInt(words[i][19]);
int temp_getOn20 = Integer.parseInt(words[i][20]);
int temp_getOn21 = Integer.parseInt(words[i][21]);
int temp_getOn22 = Integer.parseInt(words[i][22]);
int temp_getOn23 = Integer.parseInt(words[i][23]);
int temp_getOn24 = Integer.parseInt(words[i][24]);
int temp_getOff5 = Integer.parseInt(words[i+1][5]);
int temp_getOff6 = Integer.parseInt(words[i+1][6]);
int temp_getOff7 = Integer.parseInt(words[i+1][7]);
int temp_getOff8 = Integer.parseInt(words[i+1][8]);
int temp_getOff9 = Integer.parseInt(words[i+1][9]);
int temp_getOff10 = Integer.parseInt(words[i+1][10]);
int temp_getOff11 = Integer.parseInt(words[i+1][11]);
int temp_getOff12 = Integer.parseInt(words[i+1][12]);
int temp_getOff13 = Integer.parseInt(words[i+1][13]);
int temp_getOff14 = Integer.parseInt(words[i+1][14]);
int temp_getOff15 = Integer.parseInt(words[i+1][15]);
int temp_getOff16 = Integer.parseInt(words[i+1][16]);
int temp_getOff17 = Integer.parseInt(words[i+1][17]);
int temp_getOff18 = Integer.parseInt(words[i+1][18]);
int temp_getOff19 = Integer.parseInt(words[i+1][19]);
int temp_getOff20 = Integer.parseInt(words[i+1][20]);
int temp_getOff21 = Integer.parseInt(words[i+1][21]);
int temp_getOff22 = Integer.parseInt(words[i+1][22]);
int temp_getOff23 = Integer.parseInt(words[i+1][23]);
int temp_getOff24 = Integer.parseInt(words[i+1][24]);
getOn[j] = getOn[j] + temp_getOn5+temp_getOn6+temp_getOn7+temp_getOn8+temp_getOn9+temp_getOn10+
temp_getOn11+temp_getOn11+temp_getOn12+temp_getOn13+temp_getOn14+temp_getOn15+
temp_getOn16+temp_getOn17+temp_getOn18+temp_getOn19+temp_getOn20+temp_getOn21+temp_getOn22+temp_getOn23+temp_getOn24;
getOff[j] = getOff[j] + temp_getOff5+temp_getOff6+temp_getOff7+temp_getOff8+temp_getOff9+temp_getOff10+
temp_getOff11+temp_getOff12+temp_getOff13+temp_getOff14+temp_getOff15+temp_getOff16+temp_getOff17+
temp_getOff18+temp_getOff19+temp_getOff20+temp_getOff21+temp_getOff22+temp_getOff23+temp_getOff24;
} catch (Exception e) {
System.out.println(e);
System.out.println(words[i][0] + ". " + words[i][1] + ". " + words[i][2] + ". "
+ words[i][3] + ". " + words[i][4] + ". " + words[i][5] + ". " + words[i][6]
+ ". " + words[i][7]);
}
} // if
} // for
} // for
//
String[] result = new String[3];
for (int i = 0; i < dateArr.size(); i++) {
result[0] = dateArr.get(i);
result[1] = Integer.toString(getOn[i]);
result[2] = Integer.toString(getOff[i]);
System.out.println(result[0]);
System.out.println(result[1]);
System.out.println(result[2]);
cw.writeNext(result);
}
}
catch (IOException e) {
System.out.println(e);
} catch (Exception e) {
e.printStackTrace();
} finally {
System.out.println("done!");
cw.close();
}
}
}
| true |
5dd83b25a74f4d503a3b93047e3239d07e0ca928 | Java | hsreekanth/Spring-boot-projects | /phonebook_app/src/main/java/com/ashokit/controllers/ViewController.java | UTF-8 | 1,014 | 2.21875 | 2 | [] | no_license | package com.ashokit.controllers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.ashokit.models.Contact;
import com.ashokit.service.ContactService;
@Controller
public class ViewController {
@Autowired
private ContactService contactService;
@GetMapping("/editContact")
public String editContact(@RequestParam("cid")Integer contactId, Model model) {
Contact c = contactService.getContactById(contactId);
model.addAttribute("contact",c);
return "contactInfo";
}
@GetMapping("/deleteContact")
public String deleteContact(@RequestParam("cid")Integer contactId,Model model) {
boolean isDeleted = contactService.deleteContact(contactId);
if(isDeleted) {
model.addAttribute("msg", "message deleted succesfully");
}
return "redirect:viewContacts1";
}
}
| true |
396370fa4501af9880c2c32ec33c74b33c12c3f5 | Java | PugachevAA/repo_lessons | /src/main/java/ru/geekbrains/qr_1/level_2/lesson_5/arrays/Arrays.java | UTF-8 | 2,856 | 3.625 | 4 | [] | no_license | package ru.geekbrains.qr_1.level_2.lesson_5.arrays;
public class Arrays {
static final int size = 10000000;
static final int h = size/2;
static int endCount = 0;
public static void array1Thrd() {
float[] arr = new float[size];
fillArr(arr);
long a = System.currentTimeMillis();
for (int i = 0; i < arr.length; i++) {
arr[i] = calc(arr[i], i);
}
System.out.println("Время работы первого метода: " + (System.currentTimeMillis() - a) + "мс");
}
public static void array2Thrds() {
float[] arr = new float[size];
float[] arr1 = new float[h];
float[] arr2 = new float[h];
fillArr(arr);
long allTime = System.currentTimeMillis();
long a1 = System.currentTimeMillis();
System.arraycopy(arr, 0, arr1, 0, h);
System.arraycopy(arr, h, arr2, 0, h);
System.out.println("Время разбивки массива: " + (System.currentTimeMillis() - a1) + "мс");
Thread thread1 = newThread(arr1);
Thread thread2 = newThread(arr2);
thread1.start();
thread2.start();
while (true) {
if (getEndCount() >=2 ) {
long a2 = System.currentTimeMillis();
System.arraycopy(arr1, 0, arr, 0, h);
System.arraycopy(arr2, 0, arr, h, h);
System.out.println("Время склейки массива: " + (System.currentTimeMillis() - a2) + "мс");
System.out.println("Время работы второго метода: " + (System.currentTimeMillis() - allTime) + "мс");
break;
}
}
}
public static Thread newThread(float[] arr) {
return new Thread(new Runnable() {
@Override
public void run() {
try {
long time = System.currentTimeMillis();
for (int i = 0; i < arr.length; i++) {
arr[i] = calc(arr[i], i);
}
System.out.println("Время работы потока: " + (System.currentTimeMillis() - time) + "мс");
setEndCount(getEndCount() + 1);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public static void fillArr(float[] arr){
for (float f : arr) {
f = 1;
}
}
public static float calc(float arr, int i) {
return (float)(arr * Math.sin(0.2f + i / 5) * Math.cos(0.2f + i / 5) * Math.cos(0.4f + i / 2));
}
public synchronized static int getEndCount() {
return endCount;
}
public synchronized static void setEndCount(int endCount) {
Arrays.endCount = endCount;
}
}
| true |
e16b5bed56541a17d7d888eae7789e476914cffa | Java | SecureCameraCapture/AndroidClient | /app/src/main/java/com/sc3/securecameracaptureclient/imageHolder.java | UTF-8 | 409 | 2.3125 | 2 | [] | no_license | package com.sc3.securecameracaptureclient;
/**
* Created by Nathan on 3/29/2016.
*/
public class imageHolder {
String name;
String age;
int photoId;
String photoTitle;
imageHolder(String name, String age, int photoId, String photoTitle) {
this.name = name;
this.age = age;
this.photoId = photoId;
this.photoTitle = photoTitle;
}
}
| true |