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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
b2376a92cb4d162a5b02eaf1ea32a2df6186fccf | Java | rPraml/org.openntf.domino | /domino/rest/src/main/java/org/openntf/domino/rest/servlet/ODARootResource.java | UTF-8 | 1,465 | 1.9375 | 2 | [
"BSD-3-Clause",
"MIT",
"Apache-2.0",
"BSD-2-Clause",
"ICU",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | package org.openntf.domino.rest.servlet;
import java.io.IOException;
import java.net.URI;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;
import javax.ws.rs.core.UriInfo;
import com.ibm.commons.util.io.json.JsonException;
import com.ibm.domino.commons.util.UriHelper;
import com.ibm.domino.das.service.RestService;
import com.ibm.domino.das.servlet.DasServlet;
import com.ibm.domino.das.utils.ErrorHelper;
@Path("")
public class ODARootResource {
public ODARootResource() {
// TODO Auto-generated constructor stub
}
@GET
public Response getInfo(@Context final UriInfo uriInfo) {
String entity = null;
RestService.verifyNoDatabaseContext();
URI baseURI;
try {
baseURI = UriHelper.copy(uriInfo.getAbsolutePath(), true);
entity = DasServlet.getServicesResponse(baseURI.toString());
} catch (IOException e) {
throw new WebApplicationException(ErrorHelper.createErrorResponse(e, Response.Status.INTERNAL_SERVER_ERROR));
} catch (JsonException e) {
throw new WebApplicationException(ErrorHelper.createErrorResponse(e, Response.Status.INTERNAL_SERVER_ERROR));
}
ResponseBuilder builder = Response.ok();
builder.type(MediaType.APPLICATION_JSON_TYPE).entity(entity);
Response response = builder.build();
return response;
}
}
| true |
5fd216b56a09319b2cbe8a25ee83db7edd9d49b7 | Java | achyutpoudel365/javaPrograms | /EmployeeExample/src/com/company/SalaryEmployee.java | UTF-8 | 647 | 3.46875 | 3 | [] | no_license | package com.company;
import java.util.Scanner;
public class SalaryEmployee extends Employee {
private double monthlySalary;
public double getMonthlySalary() {
return monthlySalary;
}
public void setMonthlySalary(double monthlySalary) {
this.monthlySalary = monthlySalary;
}
@Override
public double totalSalary() {
if (monthlySalary <= 0) {
throw new IllegalArgumentException("Salary can't be zero");
}
return monthlySalary;
}
@Override
public String toString() {
return super.toString() + "\nMonthly Salary::" + getMonthlySalary();
}
}
| true |
2e2427cf08ff457d33effa42f3752f047bf53193 | Java | Mojo774/RecipeMaster | /src/sample/WindowClass.java | UTF-8 | 521 | 2.5 | 2 | [] | no_license | package sample;
import javafx.stage.Stage;
import sample.controller.Controllers;
// Класс окна
// Содержит stage и controller
public class WindowClass {
private Stage stage = new Stage();
private Controllers controller;
public WindowClass(Stage stage, Controllers controller) {
this.stage = stage;
this.controller = controller;
}
public Stage getStage() {
return stage;
}
public Controllers getController() {
return controller;
}
}
| true |
e8ae2af96579934b787f2db57ba2896296a6e435 | Java | JCRN/Sprint-Challenge--RDBMS-and-API-Intros-java-todos | /javatodos/src/main/java/local/jcrn/javatodos/service/UserService.java | UTF-8 | 373 | 1.953125 | 2 | [
"MIT"
] | permissive | package local.jcrn.javatodos.service;
import local.jcrn.javatodos.model.User;
import java.util.List;
public interface UserService {
void delete(long id);
List<User> findAll();
User findUserById(long id);
org.springframework.security.core.userdetails.User findUserByName(String name);
User save(User user);
User update(User user, long id);
} | true |
7ed1b56841adfde717f16552dc6e945a043835ca | Java | therealbop/Android-Driver | /HeRide_partner/app/src/main/java/com/karry/side_screens/profile/profile_model/ProfileDriverDetail.java | UTF-8 | 2,075 | 2.046875 | 2 | [] | no_license | package com.karry.side_screens.profile.profile_model;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import com.karry.pojo.Signup.PreferencesList;
import java.util.ArrayList;
public class ProfileDriverDetail
{
@SerializedName("lastName")
@Expose
private String lastName;
@SerializedName("phone")
@Expose
private String phone;
@SerializedName("email")
@Expose
private String email;
@SerializedName("profilePic")
@Expose
private String profilePic;
@SerializedName("countryCode")
@Expose
private String countryCode;
@SerializedName("firstName")
@Expose
private String firstName;
@SerializedName("driverPreferencesArr")
@Expose
private ArrayList<PreferencesList> driverPreferencesArr;
public String getLastName ()
{
return lastName;
}
public void setLastName (String lastName)
{
this.lastName = lastName;
}
public String getPhone ()
{
return phone;
}
public void setPhone (String phone)
{
this.phone = phone;
}
public String getEmail ()
{
return email;
}
public void setEmail (String email)
{
this.email = email;
}
public String getProfilePic ()
{
return profilePic;
}
public void setProfilePic (String profilePic)
{
this.profilePic = profilePic;
}
public String getCountryCode ()
{
return countryCode;
}
public void setCountryCode (String countryCode)
{
this.countryCode = countryCode;
}
public String getFirstName ()
{
return firstName;
}
public void setFirstName (String firstName)
{
this.firstName = firstName;
}
public ArrayList<PreferencesList> getDriverPreferencesArr() {
return driverPreferencesArr;
}
public void setDriverPreferencesArr(ArrayList<PreferencesList> driverPreferencesArr) {
this.driverPreferencesArr = driverPreferencesArr;
}
}
| true |
e37bb8e78b36548b7eccebb2fe06d86a81f82c75 | Java | ankitkatiyar91/java-framework-examples | /Struts/StrutsForm/src/com/ask/action/HtmlTest.java | UTF-8 | 457 | 1.921875 | 2 | [] | no_license | package com.ask.action;
import com.opensymphony.xwork2.ActionSupport;
public class HtmlTest extends ActionSupport {
private String ank;
public String getAnk() {
return ank;
}
public void setAnk(String ank) {
this.ank = ank;
}
public void validate()
{
System.out.println("HtmlTest.validate()");
addFieldError("ank", "error hehehhe");
}
public String execute()
{
System.out.println("HtmlTest.execute()");
return "success";
}
}
| true |
b1604d38def304048c1196dc7ce799f28e243dbf | Java | aldehir/TS3ServerQuery | /src/test/java/net/visualcoding/ts3serverquery/TS3ServerDummy.java | UTF-8 | 10,070 | 2.640625 | 3 | [] | no_license | package net.visualcoding.ts3serverquery;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.lang.reflect.Method;
import java.math.BigInteger;
import java.net.ServerSocket;
import java.net.Socket;
import java.security.SecureRandom;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Random;
import java.util.Map;
import java.util.Set;
import java.util.Collections;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.io.IOException;
public class TS3ServerDummy extends Thread {
protected int port;
protected ServerSocket serverSocket;
protected TS3Writer writer;
protected TS3Reader reader;
protected Map<Integer, TS3Map> clients;
protected Set<String> notifications;
protected Random random;
protected SecureRandom secureRandom;
/* Binary semaphores */
protected Semaphore semEventReceived = new Semaphore(0);
protected Semaphore semEvents = new Semaphore(0);
protected Semaphore semFirstClientList = new Semaphore(0);
protected boolean firstClientList = true;
protected Map<String, Semaphore> semMsgMap = new HashMap<String, Semaphore>();
protected Semaphore semMessages = new Semaphore(0);
protected Semaphore semMsgReceived = new Semaphore(0);
public TS3ServerDummy(int port) {
this.port = port;
random = new Random();
secureRandom = new SecureRandom();
// Instantiate client map and create some fake clients
clients = Collections.synchronizedMap(new HashMap<Integer, TS3Map>());
for(int i = 1; i <= 25; i++) {
TS3Map client = createRandomClient(i);
clients.put(i, client);
}
// Instantiate the notifications set, which will contain all the
// notifications that were registered
notifications = new HashSet<String>();
semMsgMap.put("textserver", new Semaphore(0));
semMsgMap.put("textprivate", new Semaphore(0));
semMsgMap.put("textchannel", new Semaphore(0));
}
protected TS3Map createRandomClient(int id) {
TS3Map client = new TS3Map();
client.add("clid", id);
client.add("client_nickname", "client" + Integer.toString(id));
client.add("client_unique_identifier", (new BigInteger(130,
secureRandom)).toString(32));
client.add("cid", random.nextInt(10) + 1);
return client;
}
public void run() {
try {
runServer();
} catch(Exception e) {
e.printStackTrace();
assert false;
}
}
private void runServer() throws Exception {
// Start listening on our port
serverSocket = new ServerSocket(port);
// Get the first client, no need for multiple client support
Socket socket = serverSocket.accept();
// Instantiate writer/reader objects
writer = new TS3Writer(new OutputStreamWriter(socket.getOutputStream()));
reader = new TS3Reader(new InputStreamReader(socket.getInputStream()));
// Send in the first two lines, the welcome messages
write("TS3");
write("Hello world!");
// Spawn thread that makes changes to the client map to test the polling
// thread functionality
Thread t = new Thread(new ClientMapChanger(this));
t.start();
// Spawn the messenger thread
Thread tMsg = new Thread(new Messenger(this));
tMsg.start();
// Listen for input
String input;
while((input = reader.readLine()) != null) {
// Split by whitespace
String[] split = input.split("\\s+", 2);
// We're going to do something nasty here, but just for convenience
Class<?> c = getClass();
try {
// Try to obtain a method in the form of command_COMMAND.
// For example, clientlist will call command_clientlist
Method method = c.getDeclaredMethod("command_" + split[0], String.class);
// Invoke method
method.invoke(this, split[1]);
} catch(NoSuchMethodException e) {
// Command not found error
writeError(256, "command not found");
}
}
}
protected void command_login(String cmd) throws Exception {
writeError();
}
protected void command_clientlist(String cmd) throws Exception {
StringBuilder sb = new StringBuilder();
Iterator<TS3Map> it = clients.values().iterator();
while(it.hasNext()) {
TS3Map client = it.next();
sb.append(client.toString());
if(it.hasNext()) sb.append("|");
}
write(sb.toString());
writeError();
// If this was the first client list query, then signal our semaphore
if(firstClientList) {
semFirstClientList.release();
firstClientList = false;
}
}
protected void command_servernotifyregister(String cmd) throws Exception {
TS3Map map = new TS3Map(cmd);
// Get the event name
String event = map.get("event");
// Don't do anything if the event is channel and a channel id is not
// passed
if(event.equalsIgnoreCase("channel")) {
if(map.contains("id")) return;
}
// Add event to our notifications set
notifications.add(event);
// Release the message semaphore
if(semMsgMap.containsKey(event)) {
semMsgMap.get(event).release();
}
writeError();
}
protected void write(String line) throws Exception {
getWriter().writeLine(line);
}
protected void writeError() throws Exception {
writeError(0, "ok");
}
protected void writeError(int id, String msg) throws Exception {
write(String.format("error id=%d msg=%s", id, TS3Map.escape(msg)));
}
protected TS3Writer getWriter() {
return writer;
}
protected TS3Reader getReader() {
return reader;
}
public boolean hasClient(int id) {
return clients.containsKey(new Integer(id));
}
public boolean isClientInChannel(int id, int channel) {
TS3Map client = clients.get(new Integer(id));
if(client == null) return false;
return client.getInteger("cid").intValue() == channel;
}
public boolean isEventRegistered(String event) {
return notifications.contains(event);
}
private class ClientMapChanger implements Runnable {
TS3ServerDummy server;
public ClientMapChanger(TS3ServerDummy server) {
this.server = server;
}
public void run() {
try {
runChanger();
} catch(InterruptedException e) {
// blah
}
}
protected void runChanger() throws InterruptedException {
// Wait until the first client list was called before making any
// changes. This way we don't deadlock
assert semFirstClientList.tryAcquire(1000, TimeUnit.MILLISECONDS);
// Remove a client from the map
server.clients.remove(1);
waitForResponse();
// Add in a new client
TS3Map client = server.createRandomClient(30);
server.clients.put(client.getInteger("clid"), client);
waitForResponse();
// Change the channel of a client
client = server.clients.get(2);
int channel = client.getInteger("cid").intValue();
client.remove("cid");
client.add("cid", channel + 1);
waitForResponse();
// Release semaphore for all events
semEvents.release();
}
protected void waitForResponse() throws InterruptedException {
// Wait until the event was received
assert semEventReceived.tryAcquire(5000, TimeUnit.MILLISECONDS);
}
}
private class Messenger implements Runnable {
TS3ServerDummy server;
public Messenger(TS3ServerDummy server) {
this.server = server;
}
public void run() {
try {
runMessenger();
} catch(InterruptedException e) {
} catch(IOException e) {
} catch(Exception e) {
}
}
protected void runMessenger() throws InterruptedException, IOException,
Exception {
// Wait until the client registers the notifications
for(Semaphore sem : semMsgMap.values()) {
assert sem.tryAcquire(5, TimeUnit.SECONDS);
}
String prefix = "notifytextmessage ";
TS3Map map = new TS3Map();
map.add("invokerid", 521);
map.add("invokername", "server");
map.add("invokeruid", "uid of invoker");
// Send a private text message
map.add("targetmode", 1);
map.add("msg", "Private text message!");
server.write(prefix + map.toString());
waitForResponse();
// Send a channel message
map.remove("targetmode");
map.remove("msg");
map.add("targetmode", 2);
map.add("msg", "Channel text message!");
server.write(prefix + map.toString());
waitForResponse();
// Send a server message
map.remove("targetmode");
map.remove("msg");
map.add("targetmode", 3);
map.add("msg", "Server text message!");
server.write(prefix + map.toString());
waitForResponse();
// Signal that we're done sending messages
semMessages.release();
}
protected void waitForResponse() throws InterruptedException {
assert semMsgReceived.tryAcquire(5, TimeUnit.SECONDS);
}
}
}
| true |
52cf2e5a21d693130236c69034b9f664a9dbcb63 | Java | EBojilova/Java | /ExamPreparation/src/regex/EnigmaEB.java | UTF-8 | 931 | 3.375 | 3 | [] | no_license | package regex;
import java.util.Scanner;
public class EnigmaEB {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = Integer.parseInt(scanner.nextLine());
for (int i = 0; i < n; i++) {
String input = scanner.nextLine();
String withoutWhitespacesAndNumbers = input.trim()
.replaceAll("[\\s\\d]+", "");
int halfLength = withoutWhitespacesAndNumbers.length() / 2;
for (int j = 0; j < input.length(); j++) {
char currentChar = input.charAt(j);
if (!Character.isDigit(currentChar) && !Character.isWhitespace(currentChar)) {
currentChar = (char) ((int) currentChar + halfLength);
}
System.out.print(currentChar);
}
System.out.println();
}
}
}
| true |
c6cfe1b5c166796ccba71523742d667426a74ab0 | Java | Seitenbau/stu | /stu-common/src/test/java/com/seitenbau/stu/rules/CompositeRuleTest.java | UTF-8 | 2,231 | 2.671875 | 3 | [] | no_license | package com.seitenbau.stu.rules;
import static org.fest.assertions.Assertions.*;
import java.util.Stack;
import org.fest.assertions.Fail;
import org.junit.Test;
import org.junit.rules.MethodRule;
import org.junit.runners.model.FrameworkMethod;
import org.junit.runners.model.Statement;
public class CompositeRuleTest
{
boolean _base;
Stack<Integer> _stack = new Stack<Integer>();
Statement base = new Statement()
{
@Override
public void evaluate() throws Throwable
{
_base = true;
}
};
@Test
public void testEmpty() throws Throwable
{
CompositeRule sut = new CompositeRule();
sut.apply(base, null, this).evaluate();
assertThat(_base).isTrue();
}
@Test
public void testOrderOfExecution() throws Throwable
{
// prepare
CompositeRule sut = new CompositeRule();
sut.add(createRule(1));
sut.add(createRule(2));
sut.add(createRule(3));
// exeucte
sut.apply(base, null, this).evaluate();
// verify
assertThat(_base).isTrue();
assertThat(_stack).containsExactly(1, 2, 3);
}
@Test
public void testStopExecutionOnError() throws Throwable
{
// prepare
CompositeRule sut = new CompositeRule();
sut.add(createRule(1));
sut.add(createRule(2, new IllegalArgumentException()));
sut.add(createRule(3));
// exeucte
try
{
sut.apply(base, null, this).evaluate();
Fail.fail();
}
catch (IllegalArgumentException e)
{
}
// verify
assertThat(_base).isFalse();
assertThat(_stack).containsExactly(1, 2);
}
private MethodRule createRule(int id)
{
return createRule(id, null);
}
private MethodRule createRule(final int id, final Throwable error)
{
return new MethodRule()
{
public Statement apply(final Statement base, FrameworkMethod method,
Object target)
{
return new Statement()
{
@Override
public void evaluate() throws Throwable
{
_stack.push(id);
if (error == null)
{
base.evaluate();
}
else
{
throw error;
}
}
};
}
};
}
}
| true |
d4d9c4f7784badc1b37f056f97917d675a1bc537 | Java | suao123/mavendemo | /src/main/java/com/demo/model/StudioExample.java | UTF-8 | 20,822 | 2.328125 | 2 | [] | no_license | package com.demo.model;
import java.util.ArrayList;
import java.util.List;
public class StudioExample {
protected String orderByClause;
protected boolean distinct;
protected List<Criteria> oredCriteria;
public StudioExample() {
oredCriteria = new ArrayList<Criteria>();
}
public void setOrderByClause(String orderByClause) {
this.orderByClause = orderByClause;
}
public String getOrderByClause() {
return orderByClause;
}
public void setDistinct(boolean distinct) {
this.distinct = distinct;
}
public boolean isDistinct() {
return distinct;
}
public List<Criteria> getOredCriteria() {
return oredCriteria;
}
public void or(Criteria criteria) {
oredCriteria.add(criteria);
}
public Criteria or() {
Criteria criteria = createCriteriaInternal();
oredCriteria.add(criteria);
return criteria;
}
public Criteria createCriteria() {
Criteria criteria = createCriteriaInternal();
if (oredCriteria.size() == 0) {
oredCriteria.add(criteria);
}
return criteria;
}
protected Criteria createCriteriaInternal() {
Criteria criteria = new Criteria();
return criteria;
}
public void clear() {
oredCriteria.clear();
orderByClause = null;
distinct = false;
}
protected abstract static class GeneratedCriteria {
protected List<Criterion> criteria;
protected GeneratedCriteria() {
super();
criteria = new ArrayList<Criterion>();
}
public boolean isValid() {
return criteria.size() > 0;
}
public List<Criterion> getAllCriteria() {
return criteria;
}
public List<Criterion> getCriteria() {
return criteria;
}
protected void addCriterion(String condition) {
if (condition == null) {
throw new RuntimeException("Value for condition cannot be null");
}
criteria.add(new Criterion(condition));
}
protected void addCriterion(String condition, Object value, String property) {
if (value == null) {
throw new RuntimeException("Value for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value));
}
protected void addCriterion(String condition, Object value1, Object value2, String property) {
if (value1 == null || value2 == null) {
throw new RuntimeException("Between values for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value1, value2));
}
public Criteria andSPhoneIsNull() {
addCriterion("s_phone is null");
return (Criteria) this;
}
public Criteria andSPhoneIsNotNull() {
addCriterion("s_phone is not null");
return (Criteria) this;
}
public Criteria andSPhoneEqualTo(String value) {
addCriterion("s_phone =", value, "sPhone");
return (Criteria) this;
}
public Criteria andSPhoneNotEqualTo(String value) {
addCriterion("s_phone <>", value, "sPhone");
return (Criteria) this;
}
public Criteria andSPhoneGreaterThan(String value) {
addCriterion("s_phone >", value, "sPhone");
return (Criteria) this;
}
public Criteria andSPhoneGreaterThanOrEqualTo(String value) {
addCriterion("s_phone >=", value, "sPhone");
return (Criteria) this;
}
public Criteria andSPhoneLessThan(String value) {
addCriterion("s_phone <", value, "sPhone");
return (Criteria) this;
}
public Criteria andSPhoneLessThanOrEqualTo(String value) {
addCriterion("s_phone <=", value, "sPhone");
return (Criteria) this;
}
public Criteria andSPhoneLike(String value) {
addCriterion("s_phone like", value, "sPhone");
return (Criteria) this;
}
public Criteria andSPhoneNotLike(String value) {
addCriterion("s_phone not like", value, "sPhone");
return (Criteria) this;
}
public Criteria andSPhoneIn(List<String> values) {
addCriterion("s_phone in", values, "sPhone");
return (Criteria) this;
}
public Criteria andSPhoneNotIn(List<String> values) {
addCriterion("s_phone not in", values, "sPhone");
return (Criteria) this;
}
public Criteria andSPhoneBetween(String value1, String value2) {
addCriterion("s_phone between", value1, value2, "sPhone");
return (Criteria) this;
}
public Criteria andSPhoneNotBetween(String value1, String value2) {
addCriterion("s_phone not between", value1, value2, "sPhone");
return (Criteria) this;
}
public Criteria andSSnameIsNull() {
addCriterion("s_sname is null");
return (Criteria) this;
}
public Criteria andSSnameIsNotNull() {
addCriterion("s_sname is not null");
return (Criteria) this;
}
public Criteria andSSnameEqualTo(String value) {
addCriterion("s_sname =", value, "sSname");
return (Criteria) this;
}
public Criteria andSSnameNotEqualTo(String value) {
addCriterion("s_sname <>", value, "sSname");
return (Criteria) this;
}
public Criteria andSSnameGreaterThan(String value) {
addCriterion("s_sname >", value, "sSname");
return (Criteria) this;
}
public Criteria andSSnameGreaterThanOrEqualTo(String value) {
addCriterion("s_sname >=", value, "sSname");
return (Criteria) this;
}
public Criteria andSSnameLessThan(String value) {
addCriterion("s_sname <", value, "sSname");
return (Criteria) this;
}
public Criteria andSSnameLessThanOrEqualTo(String value) {
addCriterion("s_sname <=", value, "sSname");
return (Criteria) this;
}
public Criteria andSSnameLike(String value) {
addCriterion("s_sname like", value, "sSname");
return (Criteria) this;
}
public Criteria andSSnameNotLike(String value) {
addCriterion("s_sname not like", value, "sSname");
return (Criteria) this;
}
public Criteria andSSnameIn(List<String> values) {
addCriterion("s_sname in", values, "sSname");
return (Criteria) this;
}
public Criteria andSSnameNotIn(List<String> values) {
addCriterion("s_sname not in", values, "sSname");
return (Criteria) this;
}
public Criteria andSSnameBetween(String value1, String value2) {
addCriterion("s_sname between", value1, value2, "sSname");
return (Criteria) this;
}
public Criteria andSSnameNotBetween(String value1, String value2) {
addCriterion("s_sname not between", value1, value2, "sSname");
return (Criteria) this;
}
public Criteria andSNameIsNull() {
addCriterion("s_name is null");
return (Criteria) this;
}
public Criteria andSNameIsNotNull() {
addCriterion("s_name is not null");
return (Criteria) this;
}
public Criteria andSNameEqualTo(String value) {
addCriterion("s_name =", value, "sName");
return (Criteria) this;
}
public Criteria andSNameNotEqualTo(String value) {
addCriterion("s_name <>", value, "sName");
return (Criteria) this;
}
public Criteria andSNameGreaterThan(String value) {
addCriterion("s_name >", value, "sName");
return (Criteria) this;
}
public Criteria andSNameGreaterThanOrEqualTo(String value) {
addCriterion("s_name >=", value, "sName");
return (Criteria) this;
}
public Criteria andSNameLessThan(String value) {
addCriterion("s_name <", value, "sName");
return (Criteria) this;
}
public Criteria andSNameLessThanOrEqualTo(String value) {
addCriterion("s_name <=", value, "sName");
return (Criteria) this;
}
public Criteria andSNameLike(String value) {
addCriterion("s_name like", value, "sName");
return (Criteria) this;
}
public Criteria andSNameNotLike(String value) {
addCriterion("s_name not like", value, "sName");
return (Criteria) this;
}
public Criteria andSNameIn(List<String> values) {
addCriterion("s_name in", values, "sName");
return (Criteria) this;
}
public Criteria andSNameNotIn(List<String> values) {
addCriterion("s_name not in", values, "sName");
return (Criteria) this;
}
public Criteria andSNameBetween(String value1, String value2) {
addCriterion("s_name between", value1, value2, "sName");
return (Criteria) this;
}
public Criteria andSNameNotBetween(String value1, String value2) {
addCriterion("s_name not between", value1, value2, "sName");
return (Criteria) this;
}
public Criteria andSEmailIsNull() {
addCriterion("s_email is null");
return (Criteria) this;
}
public Criteria andSEmailIsNotNull() {
addCriterion("s_email is not null");
return (Criteria) this;
}
public Criteria andSEmailEqualTo(String value) {
addCriterion("s_email =", value, "sEmail");
return (Criteria) this;
}
public Criteria andSEmailNotEqualTo(String value) {
addCriterion("s_email <>", value, "sEmail");
return (Criteria) this;
}
public Criteria andSEmailGreaterThan(String value) {
addCriterion("s_email >", value, "sEmail");
return (Criteria) this;
}
public Criteria andSEmailGreaterThanOrEqualTo(String value) {
addCriterion("s_email >=", value, "sEmail");
return (Criteria) this;
}
public Criteria andSEmailLessThan(String value) {
addCriterion("s_email <", value, "sEmail");
return (Criteria) this;
}
public Criteria andSEmailLessThanOrEqualTo(String value) {
addCriterion("s_email <=", value, "sEmail");
return (Criteria) this;
}
public Criteria andSEmailLike(String value) {
addCriterion("s_email like", value, "sEmail");
return (Criteria) this;
}
public Criteria andSEmailNotLike(String value) {
addCriterion("s_email not like", value, "sEmail");
return (Criteria) this;
}
public Criteria andSEmailIn(List<String> values) {
addCriterion("s_email in", values, "sEmail");
return (Criteria) this;
}
public Criteria andSEmailNotIn(List<String> values) {
addCriterion("s_email not in", values, "sEmail");
return (Criteria) this;
}
public Criteria andSEmailBetween(String value1, String value2) {
addCriterion("s_email between", value1, value2, "sEmail");
return (Criteria) this;
}
public Criteria andSEmailNotBetween(String value1, String value2) {
addCriterion("s_email not between", value1, value2, "sEmail");
return (Criteria) this;
}
public Criteria andSInfoIsNull() {
addCriterion("s_info is null");
return (Criteria) this;
}
public Criteria andSInfoIsNotNull() {
addCriterion("s_info is not null");
return (Criteria) this;
}
public Criteria andSInfoEqualTo(String value) {
addCriterion("s_info =", value, "sInfo");
return (Criteria) this;
}
public Criteria andSInfoNotEqualTo(String value) {
addCriterion("s_info <>", value, "sInfo");
return (Criteria) this;
}
public Criteria andSInfoGreaterThan(String value) {
addCriterion("s_info >", value, "sInfo");
return (Criteria) this;
}
public Criteria andSInfoGreaterThanOrEqualTo(String value) {
addCriterion("s_info >=", value, "sInfo");
return (Criteria) this;
}
public Criteria andSInfoLessThan(String value) {
addCriterion("s_info <", value, "sInfo");
return (Criteria) this;
}
public Criteria andSInfoLessThanOrEqualTo(String value) {
addCriterion("s_info <=", value, "sInfo");
return (Criteria) this;
}
public Criteria andSInfoLike(String value) {
addCriterion("s_info like", value, "sInfo");
return (Criteria) this;
}
public Criteria andSInfoNotLike(String value) {
addCriterion("s_info not like", value, "sInfo");
return (Criteria) this;
}
public Criteria andSInfoIn(List<String> values) {
addCriterion("s_info in", values, "sInfo");
return (Criteria) this;
}
public Criteria andSInfoNotIn(List<String> values) {
addCriterion("s_info not in", values, "sInfo");
return (Criteria) this;
}
public Criteria andSInfoBetween(String value1, String value2) {
addCriterion("s_info between", value1, value2, "sInfo");
return (Criteria) this;
}
public Criteria andSInfoNotBetween(String value1, String value2) {
addCriterion("s_info not between", value1, value2, "sInfo");
return (Criteria) this;
}
public Criteria andPwdIsNull() {
addCriterion("pwd is null");
return (Criteria) this;
}
public Criteria andPwdIsNotNull() {
addCriterion("pwd is not null");
return (Criteria) this;
}
public Criteria andPwdEqualTo(String value) {
addCriterion("pwd =", value, "pwd");
return (Criteria) this;
}
public Criteria andPwdNotEqualTo(String value) {
addCriterion("pwd <>", value, "pwd");
return (Criteria) this;
}
public Criteria andPwdGreaterThan(String value) {
addCriterion("pwd >", value, "pwd");
return (Criteria) this;
}
public Criteria andPwdGreaterThanOrEqualTo(String value) {
addCriterion("pwd >=", value, "pwd");
return (Criteria) this;
}
public Criteria andPwdLessThan(String value) {
addCriterion("pwd <", value, "pwd");
return (Criteria) this;
}
public Criteria andPwdLessThanOrEqualTo(String value) {
addCriterion("pwd <=", value, "pwd");
return (Criteria) this;
}
public Criteria andPwdLike(String value) {
addCriterion("pwd like", value, "pwd");
return (Criteria) this;
}
public Criteria andPwdNotLike(String value) {
addCriterion("pwd not like", value, "pwd");
return (Criteria) this;
}
public Criteria andPwdIn(List<String> values) {
addCriterion("pwd in", values, "pwd");
return (Criteria) this;
}
public Criteria andPwdNotIn(List<String> values) {
addCriterion("pwd not in", values, "pwd");
return (Criteria) this;
}
public Criteria andPwdBetween(String value1, String value2) {
addCriterion("pwd between", value1, value2, "pwd");
return (Criteria) this;
}
public Criteria andPwdNotBetween(String value1, String value2) {
addCriterion("pwd not between", value1, value2, "pwd");
return (Criteria) this;
}
public Criteria andSStateIsNull() {
addCriterion("s_state is null");
return (Criteria) this;
}
public Criteria andSStateIsNotNull() {
addCriterion("s_state is not null");
return (Criteria) this;
}
public Criteria andSStateEqualTo(Integer value) {
addCriterion("s_state =", value, "sState");
return (Criteria) this;
}
public Criteria andSStateNotEqualTo(Integer value) {
addCriterion("s_state <>", value, "sState");
return (Criteria) this;
}
public Criteria andSStateGreaterThan(Integer value) {
addCriterion("s_state >", value, "sState");
return (Criteria) this;
}
public Criteria andSStateGreaterThanOrEqualTo(Integer value) {
addCriterion("s_state >=", value, "sState");
return (Criteria) this;
}
public Criteria andSStateLessThan(Integer value) {
addCriterion("s_state <", value, "sState");
return (Criteria) this;
}
public Criteria andSStateLessThanOrEqualTo(Integer value) {
addCriterion("s_state <=", value, "sState");
return (Criteria) this;
}
public Criteria andSStateIn(List<Integer> values) {
addCriterion("s_state in", values, "sState");
return (Criteria) this;
}
public Criteria andSStateNotIn(List<Integer> values) {
addCriterion("s_state not in", values, "sState");
return (Criteria) this;
}
public Criteria andSStateBetween(Integer value1, Integer value2) {
addCriterion("s_state between", value1, value2, "sState");
return (Criteria) this;
}
public Criteria andSStateNotBetween(Integer value1, Integer value2) {
addCriterion("s_state not between", value1, value2, "sState");
return (Criteria) this;
}
}
public static class Criteria extends GeneratedCriteria {
protected Criteria() {
super();
}
}
public static class Criterion {
private String condition;
private Object value;
private Object secondValue;
private boolean noValue;
private boolean singleValue;
private boolean betweenValue;
private boolean listValue;
private String typeHandler;
public String getCondition() {
return condition;
}
public Object getValue() {
return value;
}
public Object getSecondValue() {
return secondValue;
}
public boolean isNoValue() {
return noValue;
}
public boolean isSingleValue() {
return singleValue;
}
public boolean isBetweenValue() {
return betweenValue;
}
public boolean isListValue() {
return listValue;
}
public String getTypeHandler() {
return typeHandler;
}
protected Criterion(String condition) {
super();
this.condition = condition;
this.typeHandler = null;
this.noValue = true;
}
protected Criterion(String condition, Object value, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.typeHandler = typeHandler;
if (value instanceof List<?>) {
this.listValue = true;
} else {
this.singleValue = true;
}
}
protected Criterion(String condition, Object value) {
this(condition, value, null);
}
protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.secondValue = secondValue;
this.typeHandler = typeHandler;
this.betweenValue = true;
}
protected Criterion(String condition, Object value, Object secondValue) {
this(condition, value, secondValue, null);
}
}
} | true |
79dffcd1568b9f4e61e3aeae41150fcc2d42814a | Java | Garfield-Qiang/Jarvis | /leetcode/src/algorithms/easy/LongestCommonPrefix.java | UTF-8 | 1,448 | 4.3125 | 4 | [] | no_license | package algorithms.easy;
/**
* 给定一个字符串数组,求出这个数组里,最长的公共前缀
* @author Jarvis
*
*/
public class LongestCommonPrefix {
/**
* 先提取出前两个的公共前缀,再拿去和后面的字符串依次提取,
* 如果公共前缀为空了,则停止比较,直接返回空
* @param strs
* @return
*/
public String longestCommonPrefix(String[] strs) {
if(strs.length == 0) {
return "";
}
if(strs.length == 1) {
return strs[0];
}
String prefix = getPrefix(strs[0], strs[1]);
if(strs.length == 2) {
return prefix;
}
for(int i = 2;i<strs.length;i++) {
prefix = getPrefix(prefix, strs[i]);
if(prefix == "") {
return "";
}
}
return prefix;
}
/**
* 获取两个字符串的相同前缀
* @param s1
* @param s2
* @return
*/
public String getPrefix(String s1,String s2) {
StringBuilder sb = new StringBuilder();
int length = s1.length()>s2.length() ? s2.length() : s1.length();
for(int i = 0 ;i<length; i++) {
if(s1.charAt(i) == s2.charAt(i)) {
sb.append(s1.charAt(i));
} else {
break;
}
}
return sb.toString();
}
public static void main(String[] args) {
LongestCommonPrefix clazz = new LongestCommonPrefix();
String[] strs = {"flower","flow","flight"};
System.out.println(clazz.longestCommonPrefix(strs));
}
}
| true |
3836cf79afeb3f2bb4e2c951ff5154a51b19cd7f | Java | EBISPOT/goci | /goci-tools/goci-datapublisher/src/main/java/uk/ac/ebi/spot/goci/service/DefaultGWASOWLConverter.java | UTF-8 | 29,851 | 1.617188 | 2 | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | package uk.ac.ebi.spot.goci.service;
import org.semanticweb.owlapi.model.AddAxiom;
import org.semanticweb.owlapi.model.AddImport;
import org.semanticweb.owlapi.model.IRI;
import org.semanticweb.owlapi.model.ImportChange;
import org.semanticweb.owlapi.model.OWLAnnotationAssertionAxiom;
import org.semanticweb.owlapi.model.OWLAnnotationProperty;
import org.semanticweb.owlapi.model.OWLClass;
import org.semanticweb.owlapi.model.OWLClassAssertionAxiom;
import org.semanticweb.owlapi.model.OWLDataFactory;
import org.semanticweb.owlapi.model.OWLDataProperty;
import org.semanticweb.owlapi.model.OWLDataPropertyAssertionAxiom;
import org.semanticweb.owlapi.model.OWLImportsDeclaration;
import org.semanticweb.owlapi.model.OWLLiteral;
import org.semanticweb.owlapi.model.OWLNamedIndividual;
import org.semanticweb.owlapi.model.OWLObjectProperty;
import org.semanticweb.owlapi.model.OWLObjectPropertyAssertionAxiom;
import org.semanticweb.owlapi.model.OWLOntology;
import org.semanticweb.owlapi.model.OWLOntologyCreationException;
import org.semanticweb.owlapi.model.OWLOntologyManager;
import org.semanticweb.owlapi.vocab.OWL2Datatype;
import org.semanticweb.owlapi.vocab.OWLRDFVocabulary;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import uk.ac.ebi.spot.goci.exception.OWLConversionException;
import uk.ac.ebi.spot.goci.model.Association;
import uk.ac.ebi.spot.goci.model.EfoTrait;
import uk.ac.ebi.spot.goci.model.Location;
import uk.ac.ebi.spot.goci.model.Locus;
import uk.ac.ebi.spot.goci.model.Region;
import uk.ac.ebi.spot.goci.model.RiskAllele;
import uk.ac.ebi.spot.goci.model.SingleNucleotidePolymorphism;
import uk.ac.ebi.spot.goci.model.Study;
import uk.ac.ebi.spot.goci.ontology.OntologyConstants;
import uk.ac.ebi.spot.goci.ontology.ReflexiveIRIMinter;
import uk.ac.ebi.spot.goci.ontology.owl.OntologyLoader;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
/**
* A default implementation of {@link GWASOWLConverter} that fetches data from the GWAS catalog using a {@link
* uk.ac.ebi.spot.goci.ontology.owl.OntologyLoader} and converts all obtained {@link Study} objects to OWL.
*
* @author Tony Burdett Date 26/01/12
*/
@Service
public class DefaultGWASOWLConverter implements GWASOWLConverter {
// private OntologyConfiguration configuration;
private OntologyLoader ontologyLoader;
private ReflexiveIRIMinter minter;
private Logger log = LoggerFactory.getLogger(getClass());
protected Logger getLog() {
return log;
}
@Autowired
public DefaultGWASOWLConverter(OntologyLoader ontologyLoader) {
this.ontologyLoader = ontologyLoader;
this.minter = new ReflexiveIRIMinter();
}
public OWLOntologyManager getManager() {
return this.ontologyLoader.getOntology().getOWLOntologyManager();
}
public OWLDataFactory getDataFactory() {
return getManager().getOWLDataFactory();
}
public ReflexiveIRIMinter getMinter() {
return minter;
}
public OWLOntology createConversionOntology() throws OWLConversionException {
try {
// create a new graph to represent our data dump
OWLOntology conversion =
getManager().createOntology(IRI.create(OntologyConstants.GWAS_ONTOLOGY_BASE_IRI + "/" +
new SimpleDateFormat("yyyy/MM/dd").format(new Date())));
// import the gwas ontology schema and efo
OWLImportsDeclaration gwasImportDecl = getDataFactory().getOWLImportsDeclaration(
IRI.create(OntologyConstants.GWAS_ONTOLOGY_SCHEMA_IRI));
ImportChange gwasImport = new AddImport(conversion, gwasImportDecl);
getManager().applyChange(gwasImport);
OWLImportsDeclaration efoImportDecl = getDataFactory().getOWLImportsDeclaration(
IRI.create(OntologyConstants.EFO_ONTOLOGY_SCHEMA_IRI));
ImportChange efoImport = new AddImport(conversion, efoImportDecl);
getManager().applyChange(efoImport);
return conversion;
}
catch (OWLOntologyCreationException e) {
throw new OWLConversionException("Failed to create new ontology", e);
}
}
public void addStudiesToOntology(Collection<Study> studies, OWLOntology ontology) {
for (Study study : studies) {
convertStudy(study, ontology);
}
}
public void addSNPsToOntology(Collection<SingleNucleotidePolymorphism> snps, OWLOntology ontology) {
for (SingleNucleotidePolymorphism snp : snps) {
convertSNP(snp, ontology);
}
}
public void addAssociationsToOntology(Collection<Association> associations, OWLOntology ontology) {
// the set of warnings that were issued during mappings
Set<String> issuedWarnings = new HashSet<String>();
for (Association association : associations) {
convertAssociation(association, ontology, issuedWarnings);
}
}
protected void convertStudy(Study study, OWLOntology ontology) {
// get the study class
OWLClass studyCls = getDataFactory().getOWLClass(IRI.create(OntologyConstants.STUDY_CLASS_IRI));
// create a new study instance
OWLNamedIndividual studyIndiv = getDataFactory().getOWLNamedIndividual(
getMinter().mint(OntologyConstants.GWAS_ONTOLOGY_BASE_IRI, study));
// assert class membership
OWLClassAssertionAxiom classAssertion = getDataFactory().getOWLClassAssertionAxiom(studyCls, studyIndiv);
getManager().addAxiom(ontology, classAssertion);
// add datatype properties...
// get datatype relations
OWLDataProperty has_author = getDataFactory().getOWLDataProperty(
IRI.create(OntologyConstants.HAS_AUTHOR_PROPERTY_IRI));
OWLDataProperty has_publication_date = getDataFactory().getOWLDataProperty(
IRI.create(OntologyConstants.HAS_PUBLICATION_DATE_PROPERTY_IRI));
OWLDataProperty has_pubmed_id = getDataFactory().getOWLDataProperty(
IRI.create(OntologyConstants.HAS_PUBMED_ID_PROPERTY_IRI));
// get annotation relations
OWLAnnotationProperty rdfsLabel =
getDataFactory().getOWLAnnotationProperty(OWLRDFVocabulary.RDFS_LABEL.getIRI());
// assert author relation
// THOR
OWLLiteral author = getDataFactory().getOWLLiteral(study.getPublicationId().getFirstAuthor().getFullname());
OWLDataPropertyAssertionAxiom author_relation =
getDataFactory().getOWLDataPropertyAssertionAxiom(has_author, studyIndiv, author);
AddAxiom add_author = new AddAxiom(ontology, author_relation);
getManager().applyChange(add_author);
// assert publication_date relation
if (study.getPublicationId().getPublicationDate() != null) {
String rfcTimezone =
new SimpleDateFormat("Z").format(study.getPublicationId().getPublicationDate());
String xsdTimezone =
rfcTimezone.substring(0, 3).concat(":").concat(rfcTimezone.substring(3, rfcTimezone.length()));
String xmlDatetimeStr =
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").format(study.getPublicationId().getPublicationDate()) + xsdTimezone;
OWLLiteral publication_date = getDataFactory().getOWLLiteral(xmlDatetimeStr, OWL2Datatype.XSD_DATE_TIME);
OWLDataPropertyAssertionAxiom publication_date_relation =
getDataFactory().getOWLDataPropertyAssertionAxiom(has_publication_date,
studyIndiv,
publication_date);
AddAxiom add_publication_date = new AddAxiom(ontology, publication_date_relation);
getManager().applyChange(add_publication_date);
}
// assert pubmed_id relation
OWLLiteral pubmed_id = getDataFactory().getOWLLiteral(study.getPublicationId().getPubmedId());
OWLDataPropertyAssertionAxiom pubmed_id_relation =
getDataFactory().getOWLDataPropertyAssertionAxiom(has_pubmed_id, studyIndiv, pubmed_id);
AddAxiom add_pubmed_id = new AddAxiom(ontology, pubmed_id_relation);
getManager().applyChange(add_pubmed_id);
// assert label
OWLLiteral study_label = getDataFactory().getOWLLiteral(pubmed_id.toString());
OWLAnnotationAssertionAxiom label_annotation =
getDataFactory().getOWLAnnotationAssertionAxiom(rdfsLabel, studyIndiv.getIRI(), study_label);
AddAxiom add_label = new AddAxiom(ontology, label_annotation);
getManager().applyChange(add_label);
// add object properties...
// get the has_part relation
OWLObjectProperty has_part = getDataFactory().getOWLObjectProperty(
IRI.create(OntologyConstants.HAS_PART_PROPERTY_IRI));
OWLObjectProperty part_of = getDataFactory().getOWLObjectProperty(
IRI.create(OntologyConstants.PART_OF_PROPERTY_IRI));
// for this study, get all trait associations
Collection<Association> associations = study.getAssociations();
// and create an study has_part association assertion for each one
for (Association association : associations) {
// get the trait association instance for this association
IRI traitIRI = getMinter().mint(OntologyConstants.GWAS_ONTOLOGY_BASE_IRI, association);
OWLNamedIndividual taIndiv = getDataFactory().getOWLNamedIndividual(traitIRI);
// assert relation
OWLObjectPropertyAssertionAxiom has_part_relation =
getDataFactory().getOWLObjectPropertyAssertionAxiom(has_part, studyIndiv, taIndiv);
AddAxiom addAxiomChange = new AddAxiom(ontology, has_part_relation);
getManager().applyChange(addAxiomChange);
OWLObjectPropertyAssertionAxiom is_part_of_relation =
getDataFactory().getOWLObjectPropertyAssertionAxiom(part_of, taIndiv, studyIndiv);
AddAxiom addAxiomChangeRev = new AddAxiom(ontology, is_part_of_relation);
getManager().applyChange(addAxiomChangeRev);
}
}
protected void convertSNP(SingleNucleotidePolymorphism snp, OWLOntology ontology) {
log.debug("converting snp: " + snp.getId() + ", rsid: " + snp.getRsId());
// get the snp class
OWLClass snpClass = getDataFactory().getOWLClass(IRI.create(OntologyConstants.SNP_CLASS_IRI));
// create a new snp instance
OWLNamedIndividual snpIndiv = getDataFactory().getOWLNamedIndividual(
getMinter().mint(OntologyConstants.GWAS_ONTOLOGY_BASE_IRI, snp));
// assert class membership
OWLClassAssertionAxiom classAssertion = getDataFactory().getOWLClassAssertionAxiom(snpClass, snpIndiv);
getManager().addAxiom(ontology, classAssertion);
// add datatype properties...
// get datatype relations
OWLDataProperty has_snp_rsid = getDataFactory().getOWLDataProperty(
IRI.create(OntologyConstants.HAS_SNP_REFERENCE_ID_PROPERTY_IRI));
OWLDataProperty has_bp_pos = getDataFactory().getOWLDataProperty(
IRI.create(OntologyConstants.HAS_BP_POSITION_PROPERTY_IRI));
// get annotation relations
OWLAnnotationProperty rdfsLabel =
getDataFactory().getOWLAnnotationProperty(OWLRDFVocabulary.RDFS_LABEL.getIRI());
// assert rsid relation
OWLLiteral rsid = getDataFactory().getOWLLiteral(snp.getRsId());
OWLDataPropertyAssertionAxiom rsid_relation =
getDataFactory().getOWLDataPropertyAssertionAxiom(has_snp_rsid, snpIndiv, rsid);
AddAxiom add_rsid = new AddAxiom(ontology, rsid_relation);
getManager().applyChange(add_rsid);
// assert bp_pos relation
if (snp.getLocations() != null) {
for (Location snpLocation : snp.getLocations()) {
if (snpLocation.getChromosomePosition() != null) {
OWLLiteral bp_pos =
// getDataFactory().getOWLLiteral(snpLocation.getChromosomePosition(), OWL2Datatype.XSD_INT);
getDataFactory().getOWLLiteral(snpLocation.getChromosomePosition());
OWLDataPropertyAssertionAxiom bp_pos_relation =
getDataFactory().getOWLDataPropertyAssertionAxiom(has_bp_pos, snpIndiv, bp_pos);
AddAxiom add_bp_pos = new AddAxiom(ontology, bp_pos_relation);
getManager().applyChange(add_bp_pos);
}
}
}
else {
getLog().debug("No SNP location available for SNP " + rsid);
}
// assert label
OWLAnnotationAssertionAxiom snp_label_annotation =
getDataFactory().getOWLAnnotationAssertionAxiom(rdfsLabel, snpIndiv.getIRI(), rsid);
AddAxiom add_snp_label = new AddAxiom(ontology, snp_label_annotation);
getManager().applyChange(add_snp_label);
// get the band class
OWLClass bandClass = getDataFactory().getOWLClass(IRI.create(OntologyConstants.CYTOGENIC_REGION_CLASS_IRI));
// get datatype relations
OWLDataProperty has_name = getDataFactory().getOWLDataProperty(
IRI.create(OntologyConstants.HAS_NAME_PROPERTY_IRI));
// get object relations
OWLObjectProperty located_in = getDataFactory().getOWLObjectProperty(
IRI.create(OntologyConstants.LOCATED_IN_PROPERTY_IRI));
OWLObjectProperty location_of = getDataFactory().getOWLObjectProperty(
IRI.create(OntologyConstants.LOCATION_OF_PROPERTY_IRI));
// get datatype relations
OWLDataProperty has_chr_name = getDataFactory().getOWLDataProperty(
IRI.create(OntologyConstants.HAS_NAME_PROPERTY_IRI));
// get object properties
OWLObjectProperty has_part = getDataFactory().getOWLObjectProperty(
IRI.create(OntologyConstants.HAS_PART_PROPERTY_IRI));
OWLObjectProperty part_of = getDataFactory().getOWLObjectProperty(
IRI.create(OntologyConstants.PART_OF_PROPERTY_IRI));
for (Location location : snp.getLocations()) {
Region region = location.getRegion();
if (region.getName() != null){
// create a new band individual
OWLNamedIndividual bandIndiv = getDataFactory().getOWLNamedIndividual(
getMinter().mint(OntologyConstants.GWAS_ONTOLOGY_BASE_IRI,
"CytogeneticRegion",
region.getName())
);
// assert class membership
OWLClassAssertionAxiom bandClassAssertion =
getDataFactory().getOWLClassAssertionAxiom(bandClass, bandIndiv);
getManager().addAxiom(ontology, bandClassAssertion);
// assert name relation
OWLLiteral name = getDataFactory().getOWLLiteral(region.getName());
OWLDataPropertyAssertionAxiom name_relation =
getDataFactory().getOWLDataPropertyAssertionAxiom(has_name, bandIndiv, name);
AddAxiom add_name = new AddAxiom(ontology, name_relation);
getManager().applyChange(add_name);
// assert label
OWLAnnotationAssertionAxiom band_label_annotation =
getDataFactory().getOWLAnnotationAssertionAxiom(rdfsLabel, bandIndiv.getIRI(), name);
AddAxiom add_band_label = new AddAxiom(ontology, band_label_annotation);
getManager().applyChange(add_band_label);
// assert located_in relation
OWLObjectPropertyAssertionAxiom located_in_relation =
getDataFactory().getOWLObjectPropertyAssertionAxiom(located_in, snpIndiv, bandIndiv);
AddAxiom add_located_in = new AddAxiom(ontology, located_in_relation);
getManager().applyChange(add_located_in);
// assert location_of relation
OWLObjectPropertyAssertionAxiom location_of_relation =
getDataFactory().getOWLObjectPropertyAssertionAxiom(location_of, bandIndiv, snpIndiv);
AddAxiom add_location_of = new AddAxiom(ontology, location_of_relation);
getManager().applyChange(add_location_of);
// get the appropriate chromosome class given the chromosome name
OWLClass chrClass = getDataFactory().getOWLClass(IRI.create(OntologyConstants.CHROMOSOME_CLASS_IRI));
// create a new chromosome individual
//If a snp has a chromosome name, create the chromosome individual if it doesn't have one (ex : the snp is
// no mapped any more) then just don't create it.
String chromName = location.getChromosomeName();
if (chromName != null) {
OWLNamedIndividual chrIndiv = getDataFactory().getOWLNamedIndividual(
getMinter().mint(OntologyConstants.GWAS_ONTOLOGY_BASE_IRI,
"Chromosome",
chromName));
OWLClassAssertionAxiom chrClassAssertion =
getDataFactory().getOWLClassAssertionAxiom(chrClass, chrIndiv);
getManager().addAxiom(ontology, chrClassAssertion);
// assert chr_name relation
OWLLiteral chr_name = getDataFactory().getOWLLiteral(chromName);
OWLDataPropertyAssertionAxiom chr_name_relation =
getDataFactory().getOWLDataPropertyAssertionAxiom(has_chr_name, chrIndiv, chr_name);
AddAxiom add_chr_name = new AddAxiom(ontology, chr_name_relation);
getManager().applyChange(add_chr_name);
// assert label
OWLLiteral chr_label = getDataFactory().getOWLLiteral("Chromosome " + chromName);
OWLAnnotationAssertionAxiom chr_label_annotation =
getDataFactory().getOWLAnnotationAssertionAxiom(rdfsLabel,
chrIndiv.getIRI(),
chr_label);
AddAxiom add_chr_label = new AddAxiom(ontology, chr_label_annotation);
getManager().applyChange(add_chr_label);
// assert has_part relation
OWLObjectPropertyAssertionAxiom has_part_relation =
getDataFactory().getOWLObjectPropertyAssertionAxiom(has_part, chrIndiv, bandIndiv);
AddAxiom add_has_part = new AddAxiom(ontology, has_part_relation);
getManager().applyChange(add_has_part);
// assert part_of relation
OWLObjectPropertyAssertionAxiom part_of_relation =
getDataFactory().getOWLObjectPropertyAssertionAxiom(part_of, bandIndiv, chrIndiv);
AddAxiom add_part_of = new AddAxiom(ontology, part_of_relation);
getManager().applyChange(add_part_of);
}
}
else {
getLog().trace("No known region for location on chromosomse " + location.getChromosomeName());
}
}
}
protected void convertAssociation(Association association, OWLOntology ontology, Set<String> issuedWarnings) {
// get the trait association class
OWLClass taClass = getDataFactory().getOWLClass(IRI.create(OntologyConstants.TRAIT_ASSOCIATION_CLASS_IRI));
IRI taIndIRI = getMinter().mint(OntologyConstants.GWAS_ONTOLOGY_BASE_IRI, association);
// create a new trait association instance
OWLNamedIndividual taIndiv = getDataFactory().getOWLNamedIndividual(taIndIRI);
// assert class membership
OWLClassAssertionAxiom classAssertion = getDataFactory().getOWLClassAssertionAxiom(taClass, taIndiv);
getManager().addAxiom(ontology, classAssertion);
// get datatype relations
OWLDataProperty has_p_value = getDataFactory().getOWLDataProperty(
IRI.create(OntologyConstants.HAS_P_VALUE_PROPERTY_IRI));
// get annotation relations
OWLAnnotationProperty rdfsLabel =
getDataFactory().getOWLAnnotationProperty(OWLRDFVocabulary.RDFS_LABEL.getIRI());
// assert pValue relation
//Sometimes there won't be any pvalue associated with an association. For example if the author doesn't give the
//pvalue but says it was less then 10-6. So if we have no pvalue we just don't add it.
if (association.getPvalueMantissa() != null && association.getPvalueExponent() != null) {
double pval = association.getPvalueMantissa() * Math.pow(10, association.getPvalueExponent());
OWLLiteral pValue = getDataFactory().getOWLLiteral(pval);
// OWLLiteral pValue = getDataFactory().getOWLLiteral(association.getPvalueMantissa()+"e"+association.getPvalueExponent());
OWLDataPropertyAssertionAxiom p_value_relation =
getDataFactory().getOWLDataPropertyAssertionAxiom(has_p_value, taIndiv, pValue);
AddAxiom add_p_value = new AddAxiom(ontology, p_value_relation);
getManager().applyChange(add_p_value);
}
// get the snp instance for this association
OWLNamedIndividual snpIndiv;
String rsId = null;
for (Locus locus : association.getLoci()) {
for (RiskAllele riskAllele : locus.getStrongestRiskAlleles()) {
SingleNucleotidePolymorphism snp = riskAllele.getSnp();
rsId = snp.getRsId();
snpIndiv = getDataFactory().getOWLNamedIndividual(
getMinter().mint(OntologyConstants.GWAS_ONTOLOGY_BASE_IRI, snp));
if (snpIndiv == null) {
String warning = "A new SNP with the given RSID only will be created";
if (!issuedWarnings.contains(warning)) {
getLog().warn(warning);
issuedWarnings.add(warning);
}
snpIndiv = getDataFactory().getOWLNamedIndividual(
getMinter().mint(OntologyConstants.GWAS_ONTOLOGY_BASE_IRI,
"SingleNucleotidePolymorphism",
snp.getRsId(),
true));
// assert class membership
OWLClass snpClass = getDataFactory().getOWLClass(IRI.create(OntologyConstants.SNP_CLASS_IRI));
OWLClassAssertionAxiom snpClassAssertion =
getDataFactory().getOWLClassAssertionAxiom(snpClass, snpIndiv);
getManager().addAxiom(ontology, snpClassAssertion);
// assert rsid relation
OWLDataProperty has_snp_rsid = getDataFactory().getOWLDataProperty(
IRI.create(OntologyConstants.HAS_SNP_REFERENCE_ID_PROPERTY_IRI));
OWLLiteral rsid = getDataFactory().getOWLLiteral(snp.getRsId());
OWLDataPropertyAssertionAxiom rsid_relation =
getDataFactory().getOWLDataPropertyAssertionAxiom(has_snp_rsid, snpIndiv, rsid);
AddAxiom add_rsid = new AddAxiom(ontology, rsid_relation);
getManager().applyChange(add_rsid);
// assert label
OWLAnnotationAssertionAxiom snp_label_annotation =
getDataFactory().getOWLAnnotationAssertionAxiom(rdfsLabel, snpIndiv.getIRI(), rsid);
AddAxiom add_snp_label = new AddAxiom(ontology, snp_label_annotation);
getManager().applyChange(add_snp_label);
}
// get object properties
OWLObjectProperty has_subject =
getDataFactory().getOWLObjectProperty(IRI.create(OntologyConstants.HAS_SUBJECT_IRI));
OWLObjectProperty is_subject_of =
getDataFactory().getOWLObjectProperty(IRI.create(OntologyConstants.IS_SUBJECT_OF_IRI));
// assert relations
OWLObjectPropertyAssertionAxiom has_subject_snp_relation =
getDataFactory().getOWLObjectPropertyAssertionAxiom(has_subject, taIndiv, snpIndiv);
AddAxiom add_has_subject_snp = new AddAxiom(ontology, has_subject_snp_relation);
getManager().applyChange(add_has_subject_snp);
OWLObjectPropertyAssertionAxiom is_subject_of_snp_relation =
getDataFactory().getOWLObjectPropertyAssertionAxiom(is_subject_of, snpIndiv, taIndiv);
AddAxiom add_is_subject_of_snp = new AddAxiom(ontology, is_subject_of_snp_relation);
getManager().applyChange(add_is_subject_of_snp);
}
// get the EFO class for the trait
for (EfoTrait efoTrait : association.getEfoTraits()) {
OWLClass traitClass;
traitClass = getDataFactory().getOWLClass(IRI.create(efoTrait.getUri()));
if (traitClass == null) {
String warning = "This trait will be mapped to Experimental Factor";
if (!issuedWarnings.contains(warning)) {
getLog().warn(warning);
issuedWarnings.add(warning);
}
traitClass =
getDataFactory().getOWLClass(IRI.create(OntologyConstants.EXPERIMENTAL_FACTOR_CLASS_IRI));
}
// create a new trait instance (puns the class)
IRI traitIRI = traitClass.getIRI();
OWLNamedIndividual traitIndiv = getDataFactory().getOWLNamedIndividual(traitIRI);
if (ontology.containsIndividualInSignature(traitIRI)) {
getLog().trace(
"Trait individual '" + traitIRI.toString() + "' (type: " + traitClass + ") already exists");
}
else {
getLog().trace(
"Creating trait individual '" + traitIRI.toString() + "' (type: " + traitClass + ")");
}
// and also add the gwas label to the individual so we don't lose curated data
OWLDataProperty has_gwas_trait_name = getDataFactory().getOWLDataProperty(
IRI.create(OntologyConstants.HAS_GWAS_TRAIT_NAME_PROPERTY_IRI));
OWLLiteral gwasTrait =
getDataFactory().getOWLLiteral(association.getStudy().getDiseaseTrait().getTrait());
OWLDataPropertyAssertionAxiom gwas_trait_relation =
getDataFactory().getOWLDataPropertyAssertionAxiom(has_gwas_trait_name, taIndiv, gwasTrait);
AddAxiom add_gwas_trait_name = new AddAxiom(ontology, gwas_trait_relation);
getManager().applyChange(add_gwas_trait_name);
// assert class membership
OWLClassAssertionAxiom traitClassAssertion =
getDataFactory().getOWLClassAssertionAxiom(traitClass, traitIndiv);
getManager().addAxiom(ontology, traitClassAssertion);
// get object properties
OWLObjectProperty has_object =
getDataFactory().getOWLObjectProperty(IRI.create(OntologyConstants.HAS_OBJECT_IRI));
OWLObjectProperty is_object_of =
getDataFactory().getOWLObjectProperty(IRI.create(OntologyConstants.IS_OBJECT_OF_IRI));
// assert relations
OWLObjectPropertyAssertionAxiom has_object_trait_relation =
getDataFactory().getOWLObjectPropertyAssertionAxiom(has_object, taIndiv, traitIndiv);
AddAxiom add_has_object_trait = new AddAxiom(ontology, has_object_trait_relation);
getManager().applyChange(add_has_object_trait);
OWLObjectPropertyAssertionAxiom is_object_of_trait_relation =
getDataFactory().getOWLObjectPropertyAssertionAxiom(is_object_of, traitIndiv, taIndiv);
AddAxiom add_is_object_of_trait = new AddAxiom(ontology, is_object_of_trait_relation);
getManager().applyChange(add_is_object_of_trait);
}
// finally, assert label for this association
OWLLiteral label = getDataFactory().getOWLLiteral(
"Association between " + rsId + " and " +
association.getStudy().getDiseaseTrait().getTrait());
OWLAnnotationAssertionAxiom label_annotation =
getDataFactory().getOWLAnnotationAssertionAxiom(rdfsLabel, taIndiv.getIRI(), label);
AddAxiom add_band_label = new AddAxiom(ontology, label_annotation);
getManager().applyChange(add_band_label);
}
}
}
| true |
1d8ee637503e4549dcd4fffaeccd5ee2064b0dca | Java | ecemkrpyk/BTM-SGW | /SpringBootWebLogic-BTM/src/main/java/com/argelastaj/springbootweblogicbtm/kafka/service/Producer.java | UTF-8 | 1,766 | 2.375 | 2 | [] | no_license | package com.argelastaj.springbootweblogicbtm.kafka.service;
import com.argelastaj.springbootweblogicbtm.model.Incoming_Message;
import com.argelastaj.springbootweblogicbtm.model.User;
import com.argelastaj.springbootweblogicbtm.utilities.ContentPartnerCounter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
@Service
public class Producer extends ContentPartnerCounter {
@Autowired
private KafkaTemplate<String,Object> kafkaTemplate;
public void sendUser(User user, String topic){
System.out.println("Producer runs");
this.kafkaTemplate.send(topic,user);
}
public void sendMessage(Incoming_Message incoming_message,Integer ContentPartnerId, String topic){
System.out.println("Producer runs");
if(!topic.contains("ssgw")) {
this.kafkaTemplate.send(topic,0,topic.toString()+"-0",incoming_message);
}
else
{
incrementRequestCount(ContentPartnerId,1);
if(getPreviousTimeCount(ContentPartnerId) <= 5) {
System.out.println("0. partition");
this.kafkaTemplate.send(topic,0,"ssgw-0",incoming_message);
}
else if(getPreviousTimeCount(ContentPartnerId) > 5 && getPreviousTimeCount(ContentPartnerId) <= 10){
System.out.println("1. partition");
this.kafkaTemplate.send(topic,1,"ssgw-1",incoming_message);
}
else if (getPreviousTimeCount(ContentPartnerId) > 10) {
System.out.println("2. partition");
this.kafkaTemplate.send(topic,2,"ssgw-2",incoming_message);
}
}
}
}
| true |
e428415f226491111a80c8b0f3930f09ac9498a3 | Java | alexdmiller/spacefiller | /src/spacefiller/spaceplants/plants/PlantSystem.java | UTF-8 | 4,238 | 2.5625 | 3 | [] | no_license | package spacefiller.spaceplants.plants;
import processing.core.PGraphics;
import spacefiller.math.Vector;
import spacefiller.spaceplants.System;
import spacefiller.particles.Particle;
import spacefiller.particles.ParticleSystem;
import spacefiller.particles.ParticleTag;
import spacefiller.particles.Spring;
import spacefiller.particles.behaviors.ParticleFriction;
import spacefiller.particles.behaviors.RepelParticles;
import spacefiller.particles.behaviors.SymmetricRepel;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class PlantSystem implements System {
// the maximum nodes allowed in the system; otherwise it gets too slow.
private static final int MAX_PLANT_NODES = 10000;
private final SymmetricRepel symmetricRepel;
// underlying particle system for basic particle physics
private ParticleSystem particleSystem;
private List<PlantNode> plantNodes;
private List<PlantNode> creationQueue;
private List<PlantNode> deleteQueue;
private PlantColor plantColor;
private float lightLevel;
public SymmetricRepel getSymmetricRepel() {
return symmetricRepel;
}
public PlantSystem(ParticleSystem particleSystem) {
this.particleSystem = particleSystem;
symmetricRepel = new SymmetricRepel(15, 1f);
particleSystem.addBehavior(symmetricRepel, ParticleTag.PLANT);
particleSystem.addBehavior(new ParticleFriction(0.5f), ParticleTag.PLANT);
particleSystem.addBehavior(new RepelParticles(15, 1f), ParticleTag.FLOWER);
particleSystem.addBehavior(new RepelParticles(20, 2), ParticleTag.EXCITED, ParticleTag.PLANT);
particleSystem.addBehavior(new RepelParticles(20, 1), ParticleTag.SEED);
particleSystem.addBehavior(new RepelParticles(20, 2f), ParticleTag.PLANT, ParticleTag.HIVE);
particleSystem.addBehavior(new RepelParticles(20, 0.5f), ParticleTag.PLANT, ParticleTag.FLYTRAP);
particleSystem.addBehavior(new ParticleFriction(0.95f), ParticleTag.SEED);
plantNodes = Collections.synchronizedList(new ArrayList<>());
creationQueue = new ArrayList<>();
deleteQueue = new ArrayList<>();
plantColor = new PlantColor();
}
@Override
public void update() {
for (PlantNode node : plantNodes) {
node.update();
// grow the plants (if they can be grown)
if (!node.condemned && plantNodes.size() < MAX_PLANT_NODES) {
node.grow();
}
// particles move towards the average position of the particles they're
// connected to. this flattens out chains of particles.
if (node.particle.getConnections().size() > 0) {
Vector avg = new Vector();
for (Spring spring : node.particle.getConnections()) {
Particle other = spring.other(node.particle);
avg.add(other.getPosition());
}
avg.div(node.particle.getConnections().size());
Vector delta = Vector.sub(avg, node.particle.getPosition());
delta.mult(0.1f);
node.particle.applyForce(delta);
}
}
// add nodes from creation queue; remove nodes from deletion queue.
plantNodes.addAll(creationQueue);
plantNodes.removeAll(deleteQueue);
deleteQueue.clear();
creationQueue.clear();
}
@Override
public void draw(PGraphics graphics) {
plantNodes.forEach(node -> node.draw(graphics, plantColor));
}
public ParticleSystem getParticleSystem() {
return particleSystem;
}
public void addPlantNode(PlantNode trunkNode) {
creationQueue.add(trunkNode);
}
public void removePlantNode(PlantNode node) {
deleteQueue.add(node);
}
public SeedNode createSeed(Vector position) {
Particle particle = particleSystem.createParticle(position);
SeedNode node = new SeedNode(particle, PlantDNA.createNewDNA(), this, 0);
addPlantNode(node);
return node;
}
public SeedNode createSeed(Vector position, PlantDNA dna) {
Particle particle = particleSystem.createParticle(position);
SeedNode node = new SeedNode(particle, dna, this, 0);
addPlantNode(node);
return node;
}
public void setLightLevel(float lightLevel) {
this.lightLevel = lightLevel;
plantColor.setLightLevel(lightLevel);
}
public float getLightLevel() {
return lightLevel;
}
}
| true |
f731c1a623e7b4b3e0f2ae90a0fa1ea826c44c46 | Java | xiongqisong/authen | /authen_middleware_server/src/main/java/com/xqs/interceptor/CORSInterceptor.java | UTF-8 | 1,726 | 2.25 | 2 | [] | no_license | package com.xqs.interceptor;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import com.xqs.entity.App;
import com.xqs.service.base.intf.AppService;
/**
* 处理跨域请求拦截器
*
* @author ycr
*
*/
public class CORSInterceptor extends HandlerInterceptorAdapter {
private AppService sysAppService;
private static List<String> LEGAL_ORIGINS;// 合法的源集合
@Autowired
public CORSInterceptor(AppService sysAppService) {
this.sysAppService = sysAppService;
}
/**
* 初始化合法的源
*/
@PostConstruct
private void initAllLegalOrigin() {
List<App> sysAppList = sysAppService.findAll();
if (sysAppList != null && !sysAppList.isEmpty()) {
LEGAL_ORIGINS = new CopyOnWriteArrayList<String>();
for (App sysApp : sysAppList) {
LEGAL_ORIGINS.add(sysApp.getContextPath());
}
}
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
String origin = request.getHeader("Origin");
if (LEGAL_ORIGINS.contains(origin)) {
response.setHeader("Access-Control-Allow-Origin", origin);
}
response.setHeader("Access-Control-Allow-Method", "GET,POST,OPTIONS");
response.setHeader("Access-Control-Allow-Headers", "content-type,x-client-ip,x-forwarded-for");
response.setHeader("Access-control-Allow-Credentials", "true");
return true;
}
}
| true |
4f8c879cd24e3626dc3197195dfad02e105b9bf1 | Java | leeyouseung/Fiba | /app/src/main/java/com/example/fiba/database/db_api/FindChildDao.java | UTF-8 | 671 | 2.15625 | 2 | [] | no_license | package com.example.fiba.database.db_api;
import androidx.lifecycle.LiveData;
import androidx.room.Dao;
import androidx.room.Delete;
import androidx.room.Insert;
import androidx.room.Query;
import androidx.room.Update;
import com.example.fiba.model.FindChild;
import java.util.List;
@Dao
public interface FindChildDao {
@Insert
void insert(FindChild findChild);
@Update
void update(FindChild findChild);
@Delete
void delete(FindChild findChild);
@Query("DELETE FROM find_child_table")
void deleteAllFindChild();
@Query("SELECT * FROM find_child_table ORDER BY childId DESC")
LiveData<List<FindChild>> getAllFindChild();
}
| true |
f95242d43c5ed8513b08a60677ab98d76928a317 | Java | OsiacAlexandru/MedCom | /app/src/main/java/osiac/ase/ro/medcom/Activities/PatientPageActivity.java | UTF-8 | 15,600 | 1.890625 | 2 | [] | no_license | package osiac.ase.ro.medcom.Activities;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import java.text.SimpleDateFormat;
import java.util.Date;
import osiac.ase.ro.medcom.Classes.Appointment;
import osiac.ase.ro.medcom.Classes.Document;
import osiac.ase.ro.medcom.Classes.Message;
import osiac.ase.ro.medcom.Classes.MessageAdapter;
import osiac.ase.ro.medcom.R;
public class PatientPageActivity extends AppCompatActivity {
private FirebaseAuth mAuth;
private DatabaseReference databaseReference;
private Button manageAccount;
private Button bttnBack;
private Button bttnViewDocuments;
private Button bttnCalendar;
private Button bttnChat;
private FirebaseDatabase mDatabase;
private DatabaseReference mReferenceMessages;
private DatabaseReference mReferenceDocuments;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
overridePendingTransition(R.anim.fadein, R.anim.fadeout);
setContentView(R.layout.activity_patient_page);
mAuth=FirebaseAuth.getInstance();
databaseReference=FirebaseDatabase.getInstance().getReference();
manageAccount=findViewById(R.id.bttnManageAccount);
bttnBack = findViewById(R.id.bttnBack12);
bttnViewDocuments = findViewById(R.id.bttnViewDocuments);
bttnCalendar = findViewById(R.id.bttnPatientCalendar);
bttnChat = findViewById(R.id.bttnPatientChat);
SharedPreferences sp = getSharedPreferences("ok_notification", MODE_PRIVATE);
SharedPreferences.Editor ed = sp.edit();
ed.putBoolean("active",false);
ed.commit();
mDatabase = FirebaseDatabase.getInstance();
// Message Notification
mReferenceMessages = FirebaseDatabase.getInstance().getReference("Messages");
mReferenceMessages.addValueEventListener(new ValueEventListener() {
boolean showNotif = false;
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if(showNotif){
for(DataSnapshot snapshot: dataSnapshot.getChildren()) {
String recv = snapshot.child("receiver").getValue(String.class);
boolean seen = snapshot.child("isSeen").getValue(Boolean.class);
String send = snapshot.child("sender").getValue(String.class);
String txt = snapshot.child("text").getValue(String.class);
Message mess = new Message(seen, send, recv, txt);
SharedPreferences sp = getSharedPreferences("ok_notification", MODE_PRIVATE);
boolean check = sp.getBoolean("active", true);
if (mess.getReceiver().equals(mAuth.getCurrentUser().getEmail()) && check == false) {
addNotification(send);
}
}
}
showNotif = true;
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
// -----------------------------------------------------------------------------------------------
// CALENDAR NOTIFICATION
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
Date date = new Date();
final String currentDate = sdf.format(date);
final Query check = databaseReference.child("Appointments").orderByChild("calendarDate").equalTo(currentDate);
check.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
// TAKE THE DATA OUT OF THE DATABASE
for (DataSnapshot datasnapshot : dataSnapshot.getChildren()) {
Appointment appointment = datasnapshot.getValue(Appointment.class);
if(appointment.getCalendarDate().equals(currentDate)
&& appointment.getPatientEmail().equals(mAuth.getCurrentUser().getEmail()))
addNotificationAppointment();
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
// --------------------------------------------------------------------------------
// DOCUMENTS NOTIFICATION
mReferenceDocuments = FirebaseDatabase.getInstance().getReference("documents");
mReferenceDocuments.addValueEventListener(new ValueEventListener() {
boolean showNotif = false;
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(showNotif) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
Document doc = postSnapshot.getValue(Document.class);
if (doc.getmPatientEmail().equals(mAuth.getCurrentUser().getEmail()))
addNotificationDocuments();
}
}
showNotif = true;
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
manageAccount.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(),ManageAccountActivity.class);
startActivity(intent);
}
});
bttnBack.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(),MainActivity.class);
startActivity(intent);
Toast.makeText(getApplicationContext(),getString(R.string.successfullySignedOut),Toast.LENGTH_LONG).show();
mAuth.signOut();
}
});
bttnViewDocuments.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String email = mAuth.getCurrentUser().getEmail();
Intent intent = new Intent(getApplicationContext(),ViewDocumentsActivity.class);
intent.putExtra("email",email);
startActivity(intent);
}
});
bttnCalendar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(),PatientCalendar.class);
startActivity(intent);
}
});
bttnChat.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final String id = mAuth.getCurrentUser().getUid();
DatabaseReference ref1 = mDatabase.getReference().child("Patients").child(id).child("doctor");
ref1.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
final Integer docI = dataSnapshot.getValue(Integer.class);
Query ref2 = mDatabase.getReference().child("Doctors").orderByChild("accessCode");
ref2.addValueEventListener(new ValueEventListener() {
@RequiresApi(api = Build.VERSION_CODES.N)
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
Long acc = ds.child("accessCode").getValue(Long.class);
Integer accI = Math.toIntExact(acc);
if (accI.equals(docI)) {
String docEmail = ds.child("email").getValue(String.class);
Intent intent = new Intent(getApplicationContext(),PatientMessageActivity.class);
intent.putExtra("email",docEmail);
startActivity(intent);
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.user_menu,menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
case R.id.mSignOut:
mAuth.signOut();
Intent intent = new Intent(getApplicationContext(),MainActivity.class);
startActivity(intent);
Toast.makeText(getApplicationContext(),getString(R.string.successfullySignedOut),Toast.LENGTH_LONG).show();
finish();
break;
}
return true;
}
private void addNotification(String senderName) {
String CHANNEL_ID = "my_channel_message_notification";
CharSequence name = "my_channel";
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
int importance = NotificationManager.IMPORTANCE_LOW;
NotificationChannel notificationChannel = new NotificationChannel(CHANNEL_ID,name, importance);
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.enableVibration(true);
notificationChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
manager.createNotificationChannel(notificationChannel);
}
NotificationCompat.Builder builder = new NotificationCompat.Builder(this,CHANNEL_ID)
.setSmallIcon(R.drawable.caduceus4)
.setContentTitle("You have a new message!")
.setContentText("Message from " + senderName);
Intent notificationIntent = new Intent();
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent,PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(contentIntent);
manager.notify((int)(System.currentTimeMillis()/1000), builder.build());
}
private void addNotificationAppointment() {
String CHANNEL_ID = "my_channel_message_appointment";
CharSequence name = "my_channel_02";
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
int importance = NotificationManager.IMPORTANCE_LOW;
NotificationChannel notificationChannel = new NotificationChannel(CHANNEL_ID,name, importance);
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.enableVibration(true);
notificationChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
manager.createNotificationChannel(notificationChannel);
}
NotificationCompat.Builder builder = new NotificationCompat.Builder(this,CHANNEL_ID)
.setSmallIcon(R.drawable.caduceus4)
.setContentTitle("You have appointments today!")
.setContentText("Please check your appointments list");
Intent notificationIntent = new Intent();
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(contentIntent);
manager.notify((int) ((new Date().getTime() / 1000L) % Integer.MAX_VALUE), builder.build());
}
private void addNotificationDocuments() {
String CHANNEL_ID = "my_channel_message_document";
CharSequence name = "my_channel_02";
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
int importance = NotificationManager.IMPORTANCE_LOW;
NotificationChannel notificationChannel = new NotificationChannel(CHANNEL_ID,name, importance);
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.enableVibration(true);
notificationChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
manager.createNotificationChannel(notificationChannel);
}
NotificationCompat.Builder builder = new NotificationCompat.Builder(this,CHANNEL_ID)
.setSmallIcon(R.drawable.caduceus4)
.setContentTitle("You received a new document")
.setContentText("Please check your documents list");
Intent notificationIntent = new Intent();
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(contentIntent);
manager.notify((int) ((new Date().getTime() / 1000L) % Integer.MAX_VALUE), builder.build());
}
@Override
public void onBackPressed()
{
mAuth.signOut();
Toast.makeText(getApplicationContext(),getString(R.string.successfullySignedOut),Toast.LENGTH_LONG).show();
finish();
}
@Override
protected void onStart() {
super.onStart();
SharedPreferences sp = getSharedPreferences("ok_notification", MODE_PRIVATE);
SharedPreferences.Editor ed = sp.edit();
ed.putBoolean("active",false);
ed.commit();
}
}
| true |
4af789caa10375c541410440a56e548a4e23bcdf | Java | sophialee8568/8-Connected-Component | /boundingBox.java | UTF-8 | 554 | 2.953125 | 3 | [] | no_license | import java.io.PrintWriter;
public class boundingBox {
int minrow;
int mincol;
int maxrow;
int maxcol;
boundingBox(){
minrow = 0;
mincol = 0;
maxrow = 0;
maxcol = 0;
}
boundingBox(int count){
minrow = count;
mincol = count;
maxrow = 0;
maxcol = 0;
}
boundingBox(int minr, int minc, int maxr, int maxc){
minrow = minr;
mincol = minc;
maxrow = maxr;
maxcol = maxc;
}
public void printBoundingBox(PrintWriter writer){
writer.println("min " + minrow +"," + mincol + " max " + maxrow + "," + maxcol);
}
}
| true |
473c8c6ca9a86c8c35d264f76faab88c58ff5a7e | Java | maxim-zhvdv/Search-Engine | /src/sample/ReadFile.java | UTF-8 | 2,471 | 3 | 3 | [] | no_license | package sample;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.TextNode;
import org.jsoup.select.Elements;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
public class ReadFile
{
private LinkedList<Doc> documentsList;
private String Path;
protected static int docsRead=0;
public ReadFile(String path) {
Path = path;
documentsList=new LinkedList<>();
}
/**
* The method reads 12 files from the corpus and adds them to the "documentsList"
*/
public void Read()
{
File corpus=new File(Path);
File[] foldersArray=corpus.listFiles();
boolean finishedTwelve=false;
while(!finishedTwelve){
for(int i=0;i<12&&docsRead<foldersArray.length;docsRead++){
if(!foldersArray[docsRead].isDirectory()) continue;
for(File fileInCorpus:foldersArray[docsRead].listFiles()){
try {
Document htmlDoc=Jsoup.parse(fileInCorpus,"UTF-8");
Elements elements=htmlDoc.getElementsByTag("DOC");
for(Element el:elements){
addNewDocToDocumentList(el);
}
} catch (IOException e) {
e.printStackTrace();
}
}
i++;
}
finishedTwelve=true;
}
}
/**
* The method adds a single document to the "documentsList"
* @param el
*/
private void addNewDocToDocumentList(Element el){
// String docID=((Element)el.childNode(1)).select("docno").text();
// String docDate=((Element)el.childNode(5)).select("date1").text();
// String docTi=el.select("ti").text();
// String docText=(((Element)el.childNode(el.childNodeSize()-2)).select("text")).text();
String docID=el.getElementsByTag("DOCNO").text();
String docDate=el.getElementsByTag("DATE1").text();
String docTi=el.getElementsByTag("TI").text();
String docText=el.getElementsByTag("TEXT").text();
documentsList.add(new Doc(docID,docDate,docTi,docText));
}
public LinkedList<Doc> getDocumentsList() {
return documentsList;
}
public void clearDocumentsList(){
documentsList=new LinkedList<>();
}
} | true |
e350a62b0aca8ce0eb83dbd5d3a595ae17be99f9 | Java | jiney518/MapTest | /MAP_PC_RegressionTest/src/test/java/example/TC02_search_menu.java | UHC | 8,997 | 2.109375 | 2 | [] | no_license | package example;
import org.testng.annotations.Test;
import junit.framework.Assert;
import org.testng.annotations.BeforeTest;
import java.io.File;
import java.util.concurrent.TimeUnit;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.support.ui.Select;
import org.testng.annotations.AfterTest;
public class TC02_search_menu {
private static WebDriver driver;
@Test
public void tc007() throws Exception{
//˻
driver.findElement(By.xpath("//div[@id='nav']/ul/li[1]/a")).click();
//
driver.findElement(By.id("search-input")).clear();
driver.findElement(By.id("search-input")).sendKeys("ڵ");
driver.findElement(By.xpath("/html/body/div[3]/div[1]/div[1]/fieldset/button")).click();
driver.findElement(By.xpath("//div[@id='panel']/div[2]/div[1]/div[2]/div[1]/div/p[2]/a")).click();
driver.findElement(By.id("search-input")).clear();
driver.findElement(By.id("search-input")).sendKeys("߾ӵ");
driver.findElement(By.xpath("/html/body/div[3]/div[1]/div[1]/fieldset/button")).click();
Thread.sleep(2000);
// ˻
driver.findElement(By.xpath("//div[@id='panel']/div[2]/div[1]/div[2]/div[1]/div[1]/a[1]")).click();
driver.findElement(By.xpath("//div[@id='panel']/div[2]/div[1]/div[2]/div[1]/div[1]/a[2]")).click();
//ּ
driver.findElement(By.xpath("//div[@id='panel']/div[2]/div[1]/div[2]/div[1]/div[2]/ul/li[1]/a")).click();
driver.findElement(By.xpath("//div[@id='panel']/div[2]/div[1]/div[2]/div[2]/ul/li[2]/div[1]/div[2]/a")).click();
Thread.sleep(2000);
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(org.openqa.selenium.OutputType.FILE);
FileUtils.copyFile(scrFile, new File("C:\\Users\\Administrator\\Desktop\\jiney\\map_scrShot\\addressTab.png"));
Thread.sleep(2000);
//ֿ Ŭ
driver.findElement(By.xpath("//div[@id='panel']/div[2]/div[1]/div[2]/div[2]/ul/li[5]/div[1]/dl/dd[2]/a[3]")).click();
//System.out.println( driver.findElement(By.id("search-input")).getAttribute("value"));
Assert.assertEquals("δб ڹ",driver.findElement(By.id("search-input")).getAttribute("value"));
driver.findElement(By.id("search-input")).clear();
driver.findElement(By.id("search-input")).sendKeys("걸 굿2 1-3");
driver.findElement(By.xpath("/html/body/div[3]/div[1]/div[1]/fieldset/button")).click();
//θ+ ư Ŭ
driver.findElement(By.xpath("//div[@id='panel']/div[2]/div[1]/div[2]/div[2]/ul/li/div[1]/div[3]/div/a[1]")).click();
driver.findElement(By.xpath("//div[@id='panel']/div[2]/div[1]/div[2]/div[2]/ul/li/div[1]/div[3]/div/a[2]")).click();
//̾ >
driver.findElement(By.xpath("//div[@id='naver_map']/div[1]/div[10]/div[3]/div/div/div[2]/div[1]/ul/li[1]")).click();
driver.findElement(By.id("search-input")).clear();
driver.findElement(By.id("search-input")).sendKeys("ڵ");
driver.findElement(By.xpath("/html/body/div[3]/div[1]/div[1]/fieldset/button")).click();
//
driver.findElement(By.xpath("//div[@id='panel']/div[2]/div[1]/div[2]/div[1]/div[2]/ul/li[2]/a")).click();
//ߺ
WebElement duplicationBox =driver.findElement(By.xpath("//div[@id='panel']/div[2]/div[1]/div[2]/div[1]/div[3]/h2/select"));
Select dropDown1 = new Select(duplicationBox);
dropDown1.selectByIndex(2);
System.out.println("ߺ Ȯ");
// ɼ
driver.findElement(By.xpath("//div[@id='panel']/div[2]/div[1]/div[2]/div[1]/div[3]/div[1]/a[1]/span")).click();
//Ÿ ɼ
driver.findElement(By.xpath("//div[@id='panel']/div[2]/div[1]/div[2]/div[1]/div[3]/div[2]/ul/li[2]/a")).click();
Thread.sleep(2000);
//ٴٹٶ Ŭ
driver.findElement(By.xpath("//div[@id='panel']/div[2]/div[1]/div[2]/div[2]/ul/li[1]/div[1]/dl/dt/a")).click();
//̾ ݱ
//driver.findElement(By.xpath("//div[@id='naver_map']/div[1]/div[10]/div[3]/div/div/div[3]")).click();
// ̼
driver.findElement(By.xpath("//div[@id='panel']/div[2]/div[1]/div[2]/div[2]/div/div/a[5]")).click();
driver.navigate().refresh();
driver.findElement(By.id("search-input")).clear();
driver.findElement(By.id("search-input")).sendKeys("λ絿");
driver.findElement(By.xpath("/html/body/div[3]/div[1]/div[1]/fieldset/button")).click();
Thread.sleep(2000);
//
driver.findElement(By.xpath("//div[@id='panel']/div[2]/div[1]/div[2]/div[1]/div[2]/ul/li[3]/a")).click();
driver.findElement(By.xpath("//div[@id='panel']/div[2]/div[1]/div[2]/div[1]/div[3]/ul/li[1]/a")).click();
//ȣ
driver.findElement(By.xpath("//div[@id='panel']/div[2]/div[1]/div[2]/div[1]/div[4]/div[2]/div[2]")).click();
driver.findElement(By.xpath("//div[@id='panel']/div[2]/div[1]/div[2]/div[1]/div[4]/div[2]/div[2]/div/ul/li[8]/a")).click();
driver.findElement(By.xpath("//div[@id='panel']/div[2]/div[1]/div[2]/div[2]/ul/li[1]/div/div[1]/a")).click();
driver.findElement(By.xpath("//div[@id='aside']/div[3]/a")).click();
//
driver.findElement(By.xpath("//div[@id='panel']/div[2]/div[1]/div[2]/div[1]/div[3]/ul/li[2]/a")).click();
Thread.sleep(2000);
driver.findElement(By.xpath("//*[@id='panel']/div[2]/div[1]/div[2]/div[1]/div[4]/div[2]/div/a")).click();
driver.findElement(By.xpath("//div[@id='panel']/div[2]/div[1]/div[2]/div[1]/div[4]/div[2]/div/div/ul/li[2]/a")).click();
driver.findElement(By.xpath("//div[@id='panel']/div[2]/div[1]/div[2]/div[2]/ul/li[2]/div[1]/div[2]/a[1]")).click();
// ȣ ˻
driver.findElement(By.id("search-input")).clear();
driver.findElement(By.id("search-input")).sendKeys("8106");
driver.findElement(By.xpath("/html/body/div[3]/div[1]/div[1]/fieldset/button")).click();
driver.findElement(By.xpath("//div[@id='panel']/div[2]/div[1]/div[2]/div[2]/ul/li/div/div[1]/a")).click();
System.out.println(" ˻ Ȯ");
}
@Test
public void tc008() throws Exception{
//tab ̽
driver.findElement(By.id("search-input")).clear();
driver.findElement(By.id("search-input")).sendKeys(" ");
driver.findElement(By.xpath("/html/body/div[3]/div[1]/div[1]/fieldset/button")).click();
Assert.assertEquals("", driver.findElement(By.xpath("//div[@id='panel']/div[2]/div[1]/div[2]/div[1]/div[1]/ul/li/a")).getText());
driver.findElement(By.id("search-input")).clear();
driver.findElement(By.id("search-input")).sendKeys("굿");
driver.findElement(By.xpath("/html/body/div[3]/div[1]/div[1]/fieldset/button")).click();
Assert.assertEquals("ּ", driver.findElement(By.xpath("//div[@id='panel']/div[2]/div[1]/div[2]/div[1]/div[2]/ul/li[1]/a")).getText());
Assert.assertEquals("", driver.findElement(By.xpath("//div[@id='panel']/div[2]/div[1]/div[2]/div[1]/div[2]/ul/li[2]/a")).getText());
Assert.assertEquals("", driver.findElement(By.xpath("//div[@id='panel']/div[2]/div[1]/div[2]/div[1]/div[2]/ul/li[3]/a")).getText());
driver.findElement(By.id("search-input")).clear();
driver.findElement(By.id("search-input")).sendKeys("dfesafsfdsd");
driver.findElement(By.xpath("/html/body/div[3]/div[1]/div[1]/fieldset/button")).click();
System.out.println(driver.findElement(By.xpath("//div[@id='panel']/div[2]/div[1]/div[2]/div[2]/div/p")).getText());
/*//19 ˻ Ұ
driver.findElement(By.id("search-input")).clear();
driver.findElement(By.id("search-input")).sendKeys("η");
driver.findElement(
By.xpath("/html/body/div[3]/div[1]/div[1]/fieldset/button")).click();
Thread.sleep(5000);
driver.switchTo().defaultContent();
driver.findElement(By.id("id")).click();
driver.findElement(By.id("id")).sendKeys("nvqa_2tc028");
driver.findElement(By.id("pw")).click();
driver.findElement(By.id("pw")).sendKeys("qalab123");
driver.findElement(By.className("btn_login")).click();*/
}
@BeforeTest
public void beforeTest() {
System.setProperty("webdriver.ie.driver", "C:\\Users\\Administrator\\Desktop\\jiney\\IEDriverServer.exe");
DesiredCapabilities dc = DesiredCapabilities.internetExplorer();
dc.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);
driver = new InternetExplorerDriver(dc);
driver.get("http://stg.map.naver.com");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
System.out.println("IE ");
}
@AfterTest
public void afterTest() {
System.out.println("tearDown");
//driver.close();
//driver.quit();
}
}
| true |
242bad83488ae0290305b73cb15a1d3e629e504e | Java | JosephCasal/MACTraining | /projects/Weekend1/app/src/main/java/com/example/joseph/weekend1/PictureActivity.java | UTF-8 | 1,689 | 2.21875 | 2 | [] | no_license | package com.example.joseph.weekend1;
import android.content.Intent;
import android.graphics.Bitmap;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class PictureActivity extends AppCompatActivity {
private ImageView iv;
private Bitmap imageBitmap;
private Button b;
static final int REQUEST_IMAGE_CAPTURE = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_picture);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
iv = (ImageView) findViewById(R.id.ivPhoto);
b = (Button) findViewById(R.id.btnTakePicture);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
imageBitmap = (Bitmap) extras.get("data");
iv.setImageBitmap(imageBitmap);
}
}
}
| true |
2281f740ffa77c6c1fe1f5af643a81443f76c3b7 | Java | alexolirib/BEA_WebLogic_Integration_quote- | /Tutorial_Process_Application_Web/src/requestquote/services/TaxCalcProcessTransformation.java | UTF-8 | 706 | 1.570313 | 2 | [] | no_license | package requestquote.services;
import com.bea.wli.common.XQuery;
import com.bea.wli.transform.DataTransformation;
import com.bea.wli.transform.XQueryTransform;
@DataTransformation()
@XQuery(version = XQuery.Version.v2004)
public abstract class TaxCalcProcessTransformation implements java.io.Serializable
{
static final long serialVersionUID = 1L;
@XQueryTransform(transformType = XQueryTransform.TransformMethodType.XQUERY_REF,
value = "stateToString.xq",
schemaValidate = @XQueryTransform.SchemaValidate(returnValue = false,
parameters = false))
public abstract java.lang.String stateToString(org.example.request.QuoteRequestDocument _quoteRequestDoc);
}
| true |
ad9345e8eee43c8f0bca2266a2557136b918a547 | Java | dramyaa88/PersonalLoanJDBC | /PersonalLoan/src/com/peronal/loan/dbconnection/MySQLclass.java | UTF-8 | 7,644 | 2.609375 | 3 | [] | no_license | package com.peronal.loan.dbconnection;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;
import com.peronal.loan.javabean.JavaBean;
import com.personal.loan.interfaces.InterMethods;
public class MySQLclass extends JavaBean implements InterMethods{
Scanner sc = new Scanner(System.in);
MySQLConnection myconn=new MySQLConnection();
Connection conn;
JavaBean obj2 = new JavaBean();
public int validate(String uid1,String pwd1)
{
int t=0;
conn=myconn.mySqlDBConnection();
ResultSet rsp;
try {
String sql = "select count(uid) from login where uid=? and pwd like ?";
PreparedStatement p=conn.prepareStatement(sql);
p.setString(1,uid1);
p.setString(2, pwd1);
rsp=p.executeQuery();
while(rsp.next()) {
t = rsp.getInt(1);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return t;
}
public void updateInfo()
{
System.out.println("Updating phone number");
conn=myconn.mySqlDBConnection();
System.out.println("Enter your Mobile number");
String phNumber = sc.nextLine();
obj2.setPhonenumber(phNumber);
String updateQuery = "update personalDetails set phoneNo = ? where uid = ?";
try {
PreparedStatement pp = conn.prepareStatement(updateQuery);
pp.setString(1, phNumber);
pp.setString(2, getUid());
pp.execute();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void deleteInfo()
{
System.out.println("Deleting your information");
conn=myconn.mySqlDBConnection();
String deleteQuery = "delete from login where uid=?";
String deleteQuery1 = "delete from personalDetails where uid=?";
String deleteQuery2 = "delete from loanDetails where uid=?";
try {
PreparedStatement psm = conn.prepareStatement(deleteQuery);
psm.setString(1, getUid());
PreparedStatement ps = conn.prepareStatement(deleteQuery1);
ps.setString(1, getUid());
PreparedStatement pst = conn.prepareStatement(deleteQuery2);
pst.setString(1, getUid());
psm.execute();
ps.execute();
pst.execute();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void insertDisplay()
{
conn=myconn.mySqlDBConnection();
//String sqlQuery = "select deptId,deptName from department where deptId > ?";
String addQuery = "insert into login values(?,?)";
String addQuery1 = "insert into personalDetails values(?,?,?,?,?)";
String addQuery2 = "insert into loanDetails values(?,?,?,?,?)";
try
{
PreparedStatement psmt1 = conn.prepareStatement(addQuery);
psmt1.setString(1,getUid());
psmt1.setString(2, getPwd());
psmt1.executeUpdate();
}catch(SQLException e)
{
e.printStackTrace();
}catch(Exception ee)
{
ee.printStackTrace();
}
try
{
PreparedStatement psmt2 = conn.prepareStatement(addQuery1);
psmt2.setString(1,getUid());
psmt2.setString(2, getPhonenumber());
psmt2.setString(3,getName());
//psmt2.setInt(4, getAge());
psmt2.setString(4, getCity());
psmt2.setString(5,getPan());
psmt2.executeUpdate();
}catch(SQLException e)
{
e.printStackTrace();
}catch(Exception ee)
{
ee.printStackTrace();
}
try
{
PreparedStatement psmt4 = conn.prepareStatement(addQuery2);
psmt4.setString(1,getUid());
psmt4.setInt(2,getSal());
psmt4.setInt(3,getExpense());
psmt4.setInt(4,getLoanAmount());
psmt4.setInt(5,getTenure());
psmt4.executeUpdate();
}catch(SQLException e)
{
e.printStackTrace();
}catch(Exception ee)
{
ee.printStackTrace();
}
}
public void insertUpdate()
{
String update = "update loanDetails set loanAmount = ? and tenure = ? where uid = ?";
try {
PreparedStatement ppt = conn.prepareStatement(update);
ppt.setInt(1, getLoanAmount());
ppt.setInt(2, getTenure());
ppt.setString(3, getUid());
ppt.execute();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void display()
{
System.out.println("Displaying your information");
String displayQuery = "select * from login where uid=?";
String displayQuery1 = "select * from personalDetails where uid=?";
String displayQuery2 = "select * from loanDetails where uid=?";
try
{
PreparedStatement psmt3 = conn.prepareStatement(displayQuery);
psmt3.setString(1, getUid());
psmt3.execute();
ResultSet rs = psmt3.executeQuery();
while(rs.next())
{
System.out.print("UID :"+rs.getString(1)+" , ");
System.out.print("Password :"+rs.getString(2));
System.out.println();
}
while(rs.next())
{
System.out.println();
}
}catch(SQLException e)
{
e.printStackTrace();
}catch(Exception ee)
{
ee.printStackTrace();
}
try
{
PreparedStatement psmt5 = conn.prepareStatement(displayQuery1);
psmt5.setString(1, getUid());
psmt5.execute();
ResultSet rs1 = psmt5.executeQuery();
while(rs1.next())
{
System.out.print("UId :"+rs1.getString(1)+" , ");
System.out.print("PhoneNumber :"+rs1.getString(2)+" , ");
System.out.print("Name :"+rs1.getString(3)+" , ");
// System.out.print("Age :"+rs1.getInt(4)+" , ");
System.out.print("City :"+rs1.getString(4)+" , ");
System.out.print("Pan :"+rs1.getString(5));
System.out.println();
}
while(rs1.next())
{
System.out.println();
}
}catch(SQLException e)
{
e.printStackTrace();
}catch(Exception ee)
{
ee.printStackTrace();
}
try
{
PreparedStatement psmt6 = conn.prepareStatement(displayQuery2);
psmt6.setString(1, getUid());
psmt6.execute();
ResultSet rs2 = psmt6.executeQuery();
while(rs2.next())
{
System.out.print("UID :"+rs2.getString(1)+" , ");
System.out.print("Income :"+rs2.getInt(2)+" , ");
System.out.print("Expense :"+rs2.getInt(3)+" , ");
System.out.print("LoanAmount :"+rs2.getInt(4)+" , ");
System.out.print("Tenure in months :"+rs2.getInt(5));
System.out.println();
}
while(rs2.next())
{
System.out.println();
}
}catch(SQLException e)
{
e.printStackTrace();
}catch(Exception ee)
{
ee.printStackTrace();
}finally
{
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
@Override
public void welcomePage() {
// TODO Auto-generated method stub
}
@Override
public void loanDetails(int loanAmount, int tenure) {
// TODO Auto-generated method stub
}
@Override
public void endMessage() {
// TODO Auto-generated method stub
}
@Override
public void newUserDetails() {
// TODO Auto-generated method stub
}
@Override
public void existingUserDetails() {
// TODO Auto-generated method stub
}
@Override
public void loanChange() {
// TODO Auto-generated method stub
}
@Override
public void validate() {
// TODO Auto-generated method stub
}
@Override
public void eligibility(String name, String city, String phNumber, String pan, int sal, int expense) {
// TODO Auto-generated method stub
}
} | true |
793b4c20cf19b37257283fd68844cc596d865519 | Java | haranprithvii/JavaPrograms | /com/ds/collections/NonRepeatingCharacter.java | UTF-8 | 1,056 | 3.90625 | 4 | [] | no_license | package com.ds.collections;
import java.util.*;
public class NonRepeatingCharacter {
public static void main(String[] args) {
// NOTE: The following input values will be used for testing your solution.
//System.out.println(nonRepeating("abcab"));
// should return 'c'
//System.out.println(nonRepeating("abab")); // should return null
//System.out.println(nonRepeating("aabbbc")); // should return 'c'
System.out.println(nonRepeating("aabbdbc")); // should return 'd'
}
// Implement your solution below.
public static Character nonRepeating(String s) {
char[] c = s.toCharArray();
Map<Character, Integer> map = new HashMap<Character, Integer>();
//List<Character> list = new ArrayList<Character>();
for (int i = 0; i < c.length; i++) {
if (map.containsKey(c[i])) {
Integer count = map.get(c[i]);
map.put(c[i], count + 1);
} else {
map.put(c[i], 1);
}
}
for (Character ch: s.toCharArray()) {
if (map.get(ch) == 1) {
return ch;
}
}
return null;
}
}
| true |
9d30c5ef0bc1d45237b129e85841c66b2863fb8a | Java | FanWenTao-Felix/hello-spring-cloud-alibaba | /commons/commons-cache/src/main/java/com/funtl/spring/cloud/alibaba/commons/redisson/enums/RedissonLockModel.java | UTF-8 | 2,060 | 2.78125 | 3 | [
"Apache-2.0"
] | permissive | package com.funtl.spring.cloud.alibaba.commons.redisson.enums;
public enum RedissonLockModel {
/**
* 可重入锁:某个线程已经获得某个锁,可以再次获取锁而不会出现死锁
*/
REENTRANT,
/**
* 公平锁:加锁前先查看是否有排队等待的线程,有的话优先处理排在前面的线程
*/
FAIR,
/**
* 联锁:可以把一组锁当作一个锁来加锁和释放
* 基于 Redis 的分布式 RedissonMultiLock 对象将多个 RLock 对象分组,并将它们作为一个锁处理。
* 每个 RLock 对象可能属于不同的 Redisson 实例
*/
MULTIPLE,
/**
* 红锁:用于解决异步数据丢失和脑裂问题
* 假设有多个 Redis 节点,这些节点之间既没有主从,也没有集群关系。
* 客户端用相同的 key 和随机值在多个节点上请求锁,请求锁的超时时间应小于锁自动释放时间。
* 当超过半数 Redis 上请求到锁的时候,才算是真正获取到了锁。
* 如果没有获取到锁,则把部分已锁的 Redis 释放掉
*/
REDLOCK,
/**
* 读锁(共享锁):共享用于不更改或不更新数据的操作(只读操作),如 SELECT 语句
* 如果事务 T 对数据 A 加上共享锁后,则其他事务只能对 A 再加共享锁,不能加排他锁。
* 获准共享锁的事务只能读数据,不能修改数据
*/
READ,
/**
* 写锁(排他锁):用于数据修改操作,例如 INSERT、UPDATE 或 DELETE。确保不会同时同一资源进行多重更新
* 如果事务 T 对数据 A 加上排他锁后,则其他事务不能再对 A 加任何类型的锁。
* 获准排他锁的事务既能读数据,又能修改数据。
* 我们在操作数据库的时候,可能会由于并发问题而引起的数据的不一致性(数据冲突)
*/
WRITE,
/**
* 自动模式,当参数只有一个使用 REENTRANT 参数多个 REDLOCK
*/
AUTO
}
| true |
b641a408e02d2e17d58579c980eab0ceb0c138e1 | Java | MrHiepdh/Java-MrDan- | /Week7/Cricle.java | UTF-8 | 682 | 3.6875 | 4 | [] | no_license | package Week7;
import java.util.*;
public class Cricle {
private double radius;
private double pi = 3.14;
public void Cricle(double radius) {
this.radius = radius;
}
public double getAre() {
return radius * radius * pi;
}
public double getPre() {
return 2 * pi * radius;
}
}
class run1 {
public static void main(String[] args) {
Cricle cr1 = new Cricle();
Scanner sc = new Scanner(System.in);
double radius = sc.nextDouble();
cr1.Cricle(radius);
System.out.printf("Area : %.2f" ,cr1.getAre());
System.out.println("Area : " + cr1.getPre());
sc.close();
}
}
| true |
b436ffe3f1679dd462af8344a63765e8786a683b | Java | vinitmk/CodingPatterns | /src/main/java/com/mkv/codingpatterns/inplacereversallinkedlist/ReverseAlternatingKElements.java | UTF-8 | 1,977 | 4.1875 | 4 | [] | no_license | package com.mkv.codingpatterns.inplacereversallinkedlist;
/*
Given the head of a LinkedList and a number ‘k’, reverse every alternating ‘k’ sized sub-list starting from the head.
If, in the end, you are left with a sub-list with less than ‘k’ elements, reverse it too.
Time complexity #
The time complexity of our algorithm will be O(N) where ‘N’ is the total number of nodes in the LinkedList.
Space complexity #
We only used constant space, therefore, the space complexity of our algorithm is O(1).
*/
public class ReverseAlternatingKElements {
private Node reverse(Node head, int k) {
Node lastNodeOfSubList, lastNodeOfPreviousPart, next, current = head, previous = null;
do {
lastNodeOfSubList = current;
lastNodeOfPreviousPart = previous;
for (int i = 0; current != null && i < k; i++) {
next = current.next;
current.next = previous;
previous = current;
current = next;
}
if (lastNodeOfPreviousPart != null) lastNodeOfPreviousPart.next = previous;
else head = previous;
lastNodeOfSubList.next = current;
for (int i = 0; current != null && i < k; ++i) {
previous = current;
current = current.next;
}
}
while (current != null);
return head;
}
public static void main(String[] args) {
ReverseAlternatingKElements main = new ReverseAlternatingKElements();
Node head = new Node(1);
head.next = new Node(2);
head.next.next = new Node(3);
head.next.next.next = new Node(4);
head.next.next.next.next = new Node(5);
head.next.next.next.next.next = new Node(6);
head.next.next.next.next.next.next = new Node(7);
head.next.next.next.next.next.next.next = new Node(8);
Node result = main.reverse(head, 2);
System.out.print("Nodes of the reversed LinkedList are: ");
while (result != null) {
System.out.print(result.value + " ");
result = result.next;
}
}
}
| true |
34a6df422764cfda45ed01f24cd42c57a5c3bfe1 | Java | charu11/sum | /School.java | UTF-8 | 320 | 3 | 3 | [] | no_license | import java.util.*;
class School{
public static void main(String args[]){
Scanner input=new Scanner(System.in);
System.out.println("Enter num1:");
int num1=input.nextInt();
System.out.println("Enter num2");
int num2=input.nextInt();
int total=num1+num2;
System.out.println("Tolal is:"+total);
}
}
| true |
d5193bedc73b567d8c2ba563c94fa18cb26cbbac | Java | Stanislav77753/Module_1_6_Patterns | /src/com/stanislav/patterns/behavioral/state/StateRunner.java | UTF-8 | 317 | 3.125 | 3 | [] | no_license | package com.stanislav.patterns.behavioral.state;
public class StateRunner {
public static void main(String[] args) {
Radio radio = new Radio();
radio.setStation(new RadioOne());
for(int i = 0; i < 5; i++){
radio.playRadio();
radio.nextStation();
}
}
}
| true |
8d7e420d2e866d4b5914d88ee247402b66aa474c | Java | FruitWave/FritzLevelONE | /src/Mediempire.java | UTF-8 | 2,708 | 2.59375 | 3 | [] | no_license | import java.applet.AudioClip;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JApplet;
import javax.swing.JLabel;
public class Mediempire {
public JLabel loadImageFromTheInternet(String imageURL) throws MalformedURLException {
URL url = new URL(imageURL);
Icon icon = new ImageIcon(url);
return new JLabel(icon);
}
/*
* To use this method, the image must be placed in your Eclipse project in the same package as this class.
*/
public JLabel loadImageFromWithinProject(String fileName) {
URL imageURL = getClass().getResource(fileName);
Icon icon = new ImageIcon(imageURL);
return new JLabel(icon);
}
/*
* To use this method, pass in the full path of the image.
*/
public JLabel loadImageFromHardDrive(String filePath) {
Icon icon = new ImageIcon(filePath);
return new JLabel(icon);
}
/*
* To use this method, you must first download JLayer: http://www.javazoom.net/javalayer/javalayer.html, and add the
* jar to project. Then uncomment this method.
*/
// private void playMp3FromComputer(String fileName) throws JavaLayerException {
// FileInputStream songStream = new FileInputStream(fileName);
//
// final Player playMp3 = new Player(songStream);
//
// Thread t = new Thread() {
// public void run() {
// try {
// playMp3.play();
// } catch (JavaLayerException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// }
// };
// t.start();
// }
/* This method will use your default mp3 player to play the song */
public void playMusicOnComputer(String fileName) {
File fileToPlay = new File(fileName);
try {
java.awt.Desktop.getDesktop().open(fileToPlay);
} catch (IOException e1) {
e1.printStackTrace();
}
}
/* If you want to use an mp3, you must first convert it to a .wav file on http://media.io */
public AudioClip loadSound(String fileName) {
return JApplet.newAudioClip(getClass().getResource(fileName));
}
public void playSoundFromInternet(String soundURL) {
try {
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new URL(soundURL));
Clip clip = AudioSystem.getClip();
clip.open(audioInputStream);
clip.start();
Thread.sleep(500);
} catch (Exception ex) {
System.out.println("Problem playing sound: " + soundURL);
ex.printStackTrace();
}
}
void speak(String words) {
try {
Runtime.getRuntime().exec("say " + words).waitFor();
} catch (Exception e) {
e.printStackTrace();
}
}
}
| true |
904c2a2501ba0e3c5121397871c56642eb3544c7 | Java | AjayKumar465/SpringBootMultiTenancy | /SpringBootMultiTenancy/src/main/java/com/poc/multitenancy/SampleJerseyApplication.java | UTF-8 | 3,201 | 2.15625 | 2 | [
"MIT"
] | permissive | package com.poc.multitenancy;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import javax.sql.DataSource;
import org.apache.commons.dbcp2.BasicDataSource;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import com.poc.multitenancy.core.ThreadLocalStorage;
import com.poc.multitenancy.routing.TenantAwareRoutingSource;
@SpringBootApplication
@EnableTransactionManagement
public class SampleJerseyApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
new SampleJerseyApplication()
.configure(new SpringApplicationBuilder(SampleJerseyApplication.class))
.properties(getDefaultProperties())
.run(args);
}
@Bean
public DataSource dataSource() {
AbstractRoutingDataSource dataSource = new TenantAwareRoutingSource();
Map<Object,Object> targetDataSources = new HashMap<>();
targetDataSources.put("TenantOne", tenantOne());
targetDataSources.put("TenantTwo", tenantTwo());
dataSource.setTargetDataSources(targetDataSources);
dataSource.afterPropertiesSet();
ThreadLocalStorage.setTenantName("TenantTwo");
return dataSource;
}
public DataSource tenantOne() {
BasicDataSource basicDataSource = new BasicDataSource();
basicDataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
basicDataSource.setUrl("jdbc:mysql://pushlive-dev-env.crrslh60fv0r.us-west-1.rds.amazonaws.com:3306/TenantOne");
basicDataSource.setUsername("pushlivedev");
basicDataSource.setPassword("pushlivedev");
// Below field required for jtds in MS SQL database
return basicDataSource;
}
public DataSource tenantTwo() {
BasicDataSource basicDataSource = new BasicDataSource();
basicDataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
basicDataSource.setUrl("jdbc:mysql://pushlive-dev-env.crrslh60fv0r.us-west-1.rds.amazonaws.com:3306/TenantTwo");
basicDataSource.setUsername("pushlivedev");
basicDataSource.setPassword("pushlivedev");
// Below field required for jtds in MS SQL database
return basicDataSource;
}
private static Properties getDefaultProperties() {
Properties defaultProperties = new Properties();
// Set sane Spring Hibernate properties:
defaultProperties.put("spring.jpa.show-sql", "true");
defaultProperties.put("spring.jpa.hibernate.naming.physical-strategy", "org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl");
defaultProperties.put("spring.datasource.initialize", "false");
// Prevent JPA from trying to Auto Detect the Database:
// defaultProperties.put("spring.jpa.database", "postgresql");
// Prevent Hibernate from Automatic Changes to the DDL Schema:
defaultProperties.put("hibernate.dialect", "org.hibernate.dialect.MySQL5InnoDBDialect");
defaultProperties.put("spring.jpa.hibernate.ddl-auto", "none");
return defaultProperties;
}
} | true |
b3d08a7f9b18d995dd4bede8ab1fecff390a736f | Java | tsmacdonald/Discretion | /src/main/java/com/discretion/SolveHomework.java | UTF-8 | 2,725 | 3.015625 | 3 | [] | no_license | package com.discretion;
import com.discretion.problem.Homework;
import com.discretion.problem.ProblemSet;
import com.discretion.proof.Proof;
import com.discretion.proof.printer.IndentedProofPrinter;
import com.discretion.proof.printer.ParagraphProofPrinter;
import com.discretion.proof.printer.ProofPrettyPrinter;
import com.discretion.solver.BestEffortSolver;
import com.discretion.problem.Problem;
import com.discretion.solver.Solver;
import com.discretion.solver.StructureOnlySolver;
import java.io.*;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
public class SolveHomework {
public static void main(String[] args) {
List<Solver> solvers = Arrays.asList(
new BestEffortSolver(),
new StructureOnlySolver()
);
List<ProofPrettyPrinter> printers = Arrays.asList(
new IndentedProofPrinter("indented"),
new ParagraphProofPrinter("english")
);
try {
File outputDirectory = new File("output/solutions");
System.out.println("Output directory: " + outputDirectory);
outputDirectory.mkdirs();
for (ProblemSet problemSet : Homework.ALL_PROBLEM_SETS) {
System.out.println(String.format("Solving problem set: %s (%s problems)",
problemSet.getTitle(),
problemSet.getProblems().size()));
for (Solver solver : solvers) {
String solverName = solver.getClass().getSimpleName();
System.out.println(" solver: " + solverName);
// Solve each problem and track the total time
long solverStartTime = System.currentTimeMillis();
List<Proof> solutions = new LinkedList<>();
for (Problem problem : problemSet.getProblems()) {
long proofStartTime = System.currentTimeMillis();
Proof proof = solver.solve(problem);
long proofSolveTime = System.currentTimeMillis() - proofStartTime;
System.out.println(String.format(" %s - %sms",
problem.getTitle(),
proofSolveTime));
solutions.add(proof);
}
long solveTime = System.currentTimeMillis() - solverStartTime;
// Output the time taken to solve the problems
System.out.println(String.format(" finished in %dms", solveTime));
// Pretty print the solutions with each printer
for (ProofPrettyPrinter printer : printers) {
String fileName = String.format("%s-%s-%s.txt", problemSet.getTitle(), solverName, printer.getName());
File solutionFile = new File(outputDirectory, fileName);
PrintStream outputStream = new PrintStream(solutionFile);
for (Proof proof : solutions) {
printer.prettyPrint(proof, outputStream);
outputStream.println();
}
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
| true |
6ce199fcf8f0cdbc7ce7d34ac1872b11122f105b | Java | lowkey42/java-jumpandrun-dev | /core/src/main/java/de/secondsystem/game01/impl/gui/ElementContainer.java | UTF-8 | 5,738 | 2.375 | 2 | [
"Unlicense"
] | permissive | package de.secondsystem.game01.impl.gui;
import java.util.ArrayList;
import java.util.List;
import org.jsfml.graphics.RenderTarget;
import org.jsfml.system.Vector2f;
import de.secondsystem.game01.impl.gui.AttributesDataTable.AttributesSource;
import de.secondsystem.game01.impl.gui.DataTable.ColumnDef;
import de.secondsystem.game01.impl.gui.LayoutElementContainer.Layout;
import de.secondsystem.game01.impl.gui.listeners.IOnClickListener;
public class ElementContainer extends Element {
protected final List<Element> children = new ArrayList<>();
private Element mouseOver;
private Element focus;
private final Style style;
public ElementContainer(float x, float y, float width, float height) {
super(x, y, width, height, null);
this.style = null;
}
public ElementContainer(float x, float y, float width, float height, Style style) {
super(x, y, width, height, null);
this.style = style;
}
public ElementContainer(float x, float y, float width, float height, ElementContainer owner) {
super(x, y, width, height, owner);
this.style = null;
}
@Override
public void onDestroy() {
super.onDestroy();
for( Element c : children )
c.onDestroy();
}
@Override
protected Style getStyle() {
return style!=null ? style : super.getStyle();
}
void addElement( Element element ) {
children.add(element);
}
public void removeElement( Element element ) {
children.remove(element);
}
public void clear() {
children.clear();
}
protected Element getByPos(Vector2f mp) {
for( Element c : children ) {
if( c.inside(mp) ) {
return c;
}
}
return getStyle().autoFocus && !children.isEmpty() ? children.get(0) : null;
}
@Override
public void onMouseOver(Vector2f mp) {
Element e = getByPos(mp);
if( mouseOver!=null && e!=mouseOver )
mouseOver.onMouseOut();
mouseOver = e;
if( mouseOver!=null )
mouseOver.onMouseOver(mp);
}
@Override
protected void onMouseOut() {
if( mouseOver!=null )
mouseOver.onMouseOut();
}
@Override
protected void onScroll(int offset) {
if( mouseOver!=null )
mouseOver.onScroll(offset);
}
@Override
public void onFocus(Vector2f mp) {
if( overlays!=null )
for( Overlay o : overlays )
if( o.inside(mp) ) {
o.onFocus(mp);
return;
}
Element e = getByPos(mp);
if( focus!=null && e!=focus )
focus.onUnFocus();
focus = e;
if( focus!=null )
focus.onFocus(mp);
}
@Override
protected void onUnFocus() {
if( focus!=null )
focus.onUnFocus();
}
@Override
public void onKeyPressed(KeyType type) {
if( focus!=null )
focus.onKeyPressed(type);
}
@Override
public void onKeyReleased(KeyType type) {
if( focus!=null )
focus.onKeyReleased(type);
}
@Override
protected void onTextInput(int character) {
if( focus!=null )
focus.onTextInput(character);
}
@Override
protected void drawImpl(RenderTarget renderTarget) {
for( Element c : children )
c.draw(renderTarget);
}
@Override
public void update(long frameTimeMs) {
for( Element c : children )
c.update(frameTimeMs);
}
public final <T> DataTable<T> createDataTable(float x, float y, float width, Iterable<T> rowData,
List<ColumnDef<T>> columns) {
return new DataTable<>(x, y, width, this, rowData, columns);
}
public final AttributesDataTable createAttributesDataTable(float x, float y, float width, AttributesSource attributesSource) {
return new AttributesDataTable(x, y, width, attributesSource, this);
}
public final Panel createPanel(float x, float y, float width, float height) {
return new Panel(x, y, width, height, this);
}
public final Panel createPanel(float x, float y, float width, float height, Layout layout) {
return new Panel(x, y, width, height, layout, this);
}
public final Slider createSlider(float x, float y) {
return new Slider(x, y, this);
}
public final Label createLabel(float x, float y, String text, Element forElem) {
return new Label(x, y, text, this, forElem);
}
public final Label createLabel(float x, float y, String text) {
return new Label(x, y, text, this);
}
public final Label createLabel(float x, float y, String text, float width, float height, Element forElem) {
return new Label(x, y, text, width, height, this, forElem);
}
public final Label createLabel(float x, float y, String text, float width, float height) {
return new Label(x, y, text, width, height, this);
}
public final Button createButton(float x, float y, String caption, IOnClickListener clickListener) {
return new Button(x, y, caption, this, clickListener);
}
public final Edit createInputField(float x, float y, float width, String text) {
return new Edit(x, y, width, text, this);
}
public final Edit createInputField(float x, float y, float width, RwValueRef<String> text) {
return new Edit(x, y, width, text, this);
}
public final StringGrid createStringGrid(float x, float y, int rowCount, int colCount, float cellWidth, float cellHeight) {
return new StringGrid(x, y, rowCount, colCount, cellWidth, cellHeight, this);
}
public final CheckBox createCheckbox(float x, float y, RwValueRef<Boolean> state) {
return new CheckBox(x, y, state, this);
}
public final <T> RadioBox<T> createRadiobox(float x, float y, RwValueRef<T> groupState, T val) {
return new RadioBox<T>(x, y, groupState, val, this);
}
public final <T extends Enum<T>> DropDownField<T> createDropDown(float x, float y, float width, Class<T> valueEnum, RwValueRef<T> value) {
return new DropDownField<>(x, y, width, valueEnum, value, this);
}
public final VScrollPanel createScrollPanel(float x, float y, float width, float height, Layout layout) {
return new VScrollPanel(x, y, width, height, layout, this);
}
}
| true |
236eeb177c5cc28cd4885ecfdf5dd31d0796030b | Java | 12urenloop/Telraam | /src/main/java/telraam/logic/external/ExternalLapper.java | UTF-8 | 3,545 | 2.359375 | 2 | [
"MIT"
] | permissive | package telraam.logic.external;
import io.dropwizard.jersey.setup.JerseyEnvironment;
import org.jdbi.v3.core.Jdbi;
import telraam.database.daos.LapDAO;
import telraam.database.daos.LapSourceDAO;
import telraam.database.models.Detection;
import telraam.database.models.Lap;
import telraam.database.models.LapSource;
import telraam.logic.Lapper;
import java.sql.Timestamp;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
public class ExternalLapper implements Lapper {
static final String SOURCE_NAME = "external-lapper";
private final LapDAO lapDAO;
private int lapSourceId;
public ExternalLapper(Jdbi jdbi) {
this.lapDAO = jdbi.onDemand(LapDAO.class);
// Get the lapSourceId, create the source if needed
LapSourceDAO lapSourceDAO = jdbi.onDemand(LapSourceDAO.class);
lapSourceDAO.getByName(SOURCE_NAME).ifPresentOrElse(
lapSource -> this.lapSourceId = lapSource.getId(),
() -> this.lapSourceId = lapSourceDAO.insert(new LapSource(SOURCE_NAME))
);
}
@Override
public void handle(Detection msg) {
// Do nothing here. The external lappers polls periodically using the general api.
}
public void saveLaps(List<ExternalLapperTeamLaps> teamLaps) {
List<Lap> laps = lapDAO.getAllBySource(lapSourceId).stream().filter(l -> ! l.getManual()).toList();
// Remember laps we have to take actions on
List<Lap> lapsToDelete = new LinkedList<>();
List<Lap> lapsToAdd = new LinkedList<>();
// Find which laps are no longer needed or have to be added
for (ExternalLapperTeamLaps teamLap : teamLaps) {
List<Lap> lapsForTeam = laps.stream().filter(l -> l.getTeamId() == teamLap.teamId).sorted(Comparator.comparing(Lap::getTimestamp)).toList();
List<Lap> newLapsForTeam = teamLap.laps.stream().map(nl -> new Lap(teamLap.teamId, lapSourceId, new Timestamp((long) (nl.timestamp)))).sorted(Comparator.comparing(Lap::getTimestamp)).toList();
int lapsIndex = 0;
int newLapsIndex = 0;
while (lapsIndex != lapsForTeam.size() || newLapsIndex != newLapsForTeam.size()) {
if (lapsIndex != lapsForTeam.size() && newLapsIndex != newLapsForTeam.size()) {
Lap lap = lapsForTeam.get(lapsIndex);
Lap newLap = newLapsForTeam.get(newLapsIndex);
if (lap.getTimestamp().before(newLap.getTimestamp())) {
lapsToDelete.add(lap);
lapsIndex++;
} else if (lap.getTimestamp().after(newLap.getTimestamp())) {
lapsToAdd.add(newLap);
newLapsIndex++;
} else { // Lap is present in both lists. Keep it.
lapsIndex++;
newLapsIndex++;
}
} else if (lapsIndex != lapsForTeam.size()) {
lapsToDelete.add(lapsForTeam.get(lapsIndex));
lapsIndex++;
} else {
lapsToAdd.add(newLapsForTeam.get(newLapsIndex));
newLapsIndex++;
}
}
}
// Do the required actions
lapDAO.deleteAllById(lapsToDelete.iterator());
lapDAO.insertAll(lapsToAdd.iterator());
}
@Override
public void registerAPI(JerseyEnvironment jersey) {
jersey.register(new ExternalLapperResource(this));
}
}
| true |
8b8728a3d90999a4af6b602bb2740985317b0496 | Java | manikantat/YelpNew | /src/com/mani/yelp/attributeType.java | UTF-8 | 264 | 2.140625 | 2 | [] | no_license | package com.mani.yelp;
public class attributeType {
String userID;
double starRating;
int usefulCount =0;
int funnyCount=0;
int coolCount=0;
int totalNumberofVotes;
public void setRatingClass()
{
this.starRating = Math.ceil(this.starRating);
}
}
| true |
78a2e4b3612a3ee3d150ce27d0ad6a4f5001a303 | Java | xiaodaozuihou/ServletStudyDemo | /javaStudy/src/main/sorm/core/TableContext.java | UTF-8 | 3,707 | 2.828125 | 3 | [] | no_license | package core;
import bean.ColumnInfo;
import bean.Configuration;
import bean.TableInfo;
import utils.JavaFileUtils;
import utils.StringUtils;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
/**
*负责获取管理数据库所有表结构和类结构的关系,并可以根据表结构生成类结构
*/
public class TableContext {
//表名为key,表信息对象为value
public static Map<String, TableInfo> tables = new HashMap<String, TableInfo>();
//将po的class对象和表信息对象关联起来,便于使用
public static Map<Class, TableInfo> poClassTableMap = new HashMap<Class, TableInfo>();
public TableContext() {
}
static {
Connection con = DBManager.getCon();
try {
DatabaseMetaData dbmd = con.getMetaData();
ResultSet tablesRet = dbmd.getTables(null, "%", "%", new String[]{"TABLE"});
while (tablesRet.next()){
String tableName = (String) tablesRet.getObject("TABLE_NAME");
TableInfo ti = new TableInfo(tableName, new ArrayList<ColumnInfo>(), new HashMap<String, ColumnInfo>());
tables.put(tableName,ti);
//查询表中所有的字段
ResultSet set = dbmd.getColumns(null, "%", tableName, "%");
while (set.next()){
ColumnInfo ci = new ColumnInfo(set.getString("COLUMN_NAME"),set.getString("TYPE_NAME"),0);
ti.getColumns().put(set.getString("COLUMN_NAME"),ci);
}
//查询表中的主键
ResultSet set1 = dbmd.getPrimaryKeys(null, "%", tableName);
while (set1.next()){
ColumnInfo ci1 = ti.getColumns().get(set1.getObject("COLUMN_NAME"));
ci1.setKeyType(1);
ti.getPriKey().add(ci1);
}
//取唯一主键使用,如果是联合主键,则为空
if (ti.getPriKey().size() > 0){
ti.setOnlyPriKey(ti.getPriKey().get(0));
}
}
//更新类结构
updateJavaPoFile();
//加载po下面所有的类,便于重用,提高效率
loadPOTables();
} catch (SQLException e) {
e.printStackTrace();
}
}
public static Map<String, TableInfo> getTables() {
return tables;
}
public static void setTables(Map<String, TableInfo> tables) {
TableContext.tables = tables;
}
public static Map<Class, TableInfo> getPoClassTableMap() {
return poClassTableMap;
}
public static void setPoClassTableMap(Map<Class, TableInfo> poClassTableMap) {
TableContext.poClassTableMap = poClassTableMap;
}
/**
* 根据表结构,更新配置的po包下面的java类
*/
public static void updateJavaPoFile(){
Map<String, TableInfo> map = TableContext.tables;
for (TableInfo t:map.values()) {
JavaFileUtils.createJavaPOFile(t,new MysqlTypeConvertor());
}
}
/**
* 加载po类
*/
public static void loadPOTables(){
for (TableInfo tableInfo:tables.values()) {
try {
Class c = Class.forName(DBManager.getConf().getPoPackage()
+ "." + StringUtils.firstCharToUpperCase(tableInfo.getTname()));
poClassTableMap.put(c,tableInfo);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
}
| true |
deacd6c2e86dde04acbe622a6b002585b0e6e1d4 | Java | ThinkmanWang/ThinkSpringbootV2 | /src/main/java/com/thinkman/thinkspringboot/project/netty/tcpclient/ClientHandler.java | UTF-8 | 1,013 | 2.265625 | 2 | [] | no_license | package com.thinkman.thinkspringboot.project.netty.tcpclient;
import com.thinkman.thinkspringboot.project.netty.tcpserver.TCPServerHandler;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.apache.log4j.Logger;
public class ClientHandler extends SimpleChannelInboundHandler<Object> {
private static final Logger logger = Logger.getLogger(TCPServerHandler.class);
@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
logger.info("FXXK");
}
@Override
public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
logger.info("FXXK");
}
@Override
public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
logger.info("client接收到服务器返回的消息:"+msg);
}
}
| true |
c02cbca4f046865d567f83a4a5a4a468a7e916e1 | Java | CommercialWebDevelopment/pyramid | /src/main/java/com/financial/pyramid/web/ContactsController.java | UTF-8 | 3,034 | 1.929688 | 2 | [] | no_license | package com.financial.pyramid.web;
import com.financial.pyramid.domain.Contact;
import com.financial.pyramid.service.ContactService;
import com.financial.pyramid.service.EmailService;
import com.financial.pyramid.service.SettingsService;
import com.financial.pyramid.service.UserService;
import com.financial.pyramid.settings.Setting;
import com.financial.pyramid.utils.Session;
import com.financial.pyramid.web.form.FeedbackForm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import java.util.HashMap;
import java.util.Map;
/**
* User: dbudunov
* Date: 22.08.13
* Time: 14:03
*/
@Controller
@RequestMapping("/contacts")
public class ContactsController extends AbstractController {
@Autowired
ContactService contactService;
@Autowired
EmailService emailService;
@Autowired
SettingsService settingsService;
@Autowired
UserService userService;
@RequestMapping(value = "/save", method = RequestMethod.POST)
public String save(ModelMap model, @ModelAttribute("contact") Contact contact) {
contactService.save(contact);
return "redirect:/app/admin/contact_settings";
}
@RequestMapping(value = "/remove/{id}", method = RequestMethod.GET)
public String remove(ModelMap model, @PathVariable Long id) {
contactService.remove(id);
return "redirect:/app/admin/contact_settings";
}
@RequestMapping(value = "/feedback", method = RequestMethod.POST)
public String sendFeedback(ModelMap model, @ModelAttribute("feedbackForm") FeedbackForm feedbackForm) {
String adminEmail = settingsService.getProperty(Setting.FEEDBACK_RECEIVER_EMAIL);
com.financial.pyramid.domain.User adminUser = userService.findByEmail(adminEmail);
Object principal = Session.getAuthentication().getPrincipal();
String currentUserName = feedbackForm.getName();
String currentUserEmail = feedbackForm.getEmail();
String feedback = feedbackForm.getFeedback();
if (!principal.equals("anonymousUser")) {
com.financial.pyramid.domain.User user = Session.getCurrentUser();
currentUserName = user.getName();
currentUserEmail = user.getEmail();
}
Map map = new HashMap();
map.put("name", adminUser.getName());
map.put("username", currentUserName);
map.put("usermail", currentUserEmail);
map.put("feedback", feedback);
map.put("subject", localizationService.translate("feedbackFromUser"));
emailService.setTemplate("feedback-template");
boolean result = emailService.sendEmail(adminUser, map);
return "redirect:/app/contacts?sent=" + result;
}
} | true |
2e17f0fc3f7a652cb36e6ea804f26c4746453619 | Java | 88543024/open | /lunwen/app/models/X86SynchDto.java | UTF-8 | 7,593 | 2.015625 | 2 | [] | no_license | package models;
public class X86SynchDto{
//TSAM信息同步
private String tsamInfoDay_hour;//每天几点
private String tsamInfoDay_minute;//几分
private String tsamInfoWeek_day;//每周几
private String tsamInfoWeek_hour;//几点
private String tsamInfoWeek_minute;//几分
private String tsamInfoMonth_day;//每月最后一天
private String tsamInfoMonth_hour;//几点
private String tsamInfoMonth_minute;//几分
//AD用户信息同步
private String userInfoDay_hour;//每天几点
private String userInfoDay_minute;//几分
private String userInfoWeek_day;//每周几
private String userInfoWeek_hour;//几点
private String userInfoWeek_minute;//几分
private String userInfoMonth_day;//每月最后一天
private String userInfoMonth_hour;//几点
private String userInfoMonth_minute;//几分
//X86资产信息同步
private String resourceDay_hour;//每天几点
private String resourceDay_minute;//几分
private String resourceWeek_day;//每周几
private String resourceWeek_hour;//几点
private String resourceWeek_minute;//几分
private String resourceMonth_day;//每月最后一天
private String resourceMonth_hour;//几点
private String resourceMonth_minute;//几分
//X86性能信息同步
private String performanceDay_hour;//每天几点
private String performanceDay_minute;//几分
private String performanceWeek_day;//每周几
private String performanceWeek_hour;//几点
private String performanceWeek_minute;//几分
private String performanceMonth_day;//每月最后一天
private String performanceMonth_hour;//几点
private String performanceMonth_minute;//几分
public String getTsamInfoDay_hour() {
return tsamInfoDay_hour;
}
public void setTsamInfoDay_hour(String tsamInfoDay_hour) {
this.tsamInfoDay_hour = tsamInfoDay_hour;
}
public String getTsamInfoDay_minute() {
return tsamInfoDay_minute;
}
public void setTsamInfoDay_minute(String tsamInfoDay_minute) {
this.tsamInfoDay_minute = tsamInfoDay_minute;
}
public String getTsamInfoWeek_day() {
return tsamInfoWeek_day;
}
public void setTsamInfoWeek_day(String tsamInfoWeek_day) {
this.tsamInfoWeek_day = tsamInfoWeek_day;
}
public String getTsamInfoWeek_hour() {
return tsamInfoWeek_hour;
}
public void setTsamInfoWeek_hour(String tsamInfoWeek_hour) {
this.tsamInfoWeek_hour = tsamInfoWeek_hour;
}
public String getTsamInfoWeek_minute() {
return tsamInfoWeek_minute;
}
public void setTsamInfoWeek_minute(String tsamInfoWeek_minute) {
this.tsamInfoWeek_minute = tsamInfoWeek_minute;
}
public String getTsamInfoMonth_day() {
return tsamInfoMonth_day;
}
public void setTsamInfoMonth_day(String tsamInfoMonth_day) {
this.tsamInfoMonth_day = tsamInfoMonth_day;
}
public String getTsamInfoMonth_hour() {
return tsamInfoMonth_hour;
}
public void setTsamInfoMonth_hour(String tsamInfoMonth_hour) {
this.tsamInfoMonth_hour = tsamInfoMonth_hour;
}
public String getTsamInfoMonth_minute() {
return tsamInfoMonth_minute;
}
public void setTsamInfoMonth_minute(String tsamInfoMonth_minute) {
this.tsamInfoMonth_minute = tsamInfoMonth_minute;
}
public String getUserInfoDay_hour() {
return userInfoDay_hour;
}
public void setUserInfoDay_hour(String userInfoDayHour) {
userInfoDay_hour = userInfoDayHour;
}
public String getUserInfoDay_minute() {
return userInfoDay_minute;
}
public void setUserInfoDay_minute(String userInfoDayMinute) {
userInfoDay_minute = userInfoDayMinute;
}
public String getUserInfoWeek_day() {
return userInfoWeek_day;
}
public void setUserInfoWeek_day(String userInfoWeekDay) {
userInfoWeek_day = userInfoWeekDay;
}
public String getUserInfoWeek_hour() {
return userInfoWeek_hour;
}
public void setUserInfoWeek_hour(String userInfoWeekHour) {
userInfoWeek_hour = userInfoWeekHour;
}
public String getUserInfoWeek_minute() {
return userInfoWeek_minute;
}
public void setUserInfoWeek_minute(String userInfoWeekMinute) {
userInfoWeek_minute = userInfoWeekMinute;
}
public String getUserInfoMonth_day() {
return userInfoMonth_day;
}
public void setUserInfoMonth_day(String userInfoMonthDay) {
userInfoMonth_day = userInfoMonthDay;
}
public String getUserInfoMonth_hour() {
return userInfoMonth_hour;
}
public void setUserInfoMonth_hour(String userInfoMonthHour) {
userInfoMonth_hour = userInfoMonthHour;
}
public String getUserInfoMonth_minute() {
return userInfoMonth_minute;
}
public void setUserInfoMonth_minute(String userInfoMonthMinute) {
userInfoMonth_minute = userInfoMonthMinute;
}
public String getResourceDay_hour() {
return resourceDay_hour;
}
public void setResourceDay_hour(String resourceDayHour) {
resourceDay_hour = resourceDayHour;
}
public String getResourceDay_minute() {
return resourceDay_minute;
}
public void setResourceDay_minute(String resourceDayMinute) {
resourceDay_minute = resourceDayMinute;
}
public String getResourceWeek_day() {
return resourceWeek_day;
}
public void setResourceWeek_day(String resourceWeekDay) {
resourceWeek_day = resourceWeekDay;
}
public String getResourceWeek_hour() {
return resourceWeek_hour;
}
public void setResourceWeek_hour(String resourceWeekHour) {
resourceWeek_hour = resourceWeekHour;
}
public String getResourceWeek_minute() {
return resourceWeek_minute;
}
public void setResourceWeek_minute(String resourceWeekMinute) {
resourceWeek_minute = resourceWeekMinute;
}
public String getResourceMonth_day() {
return resourceMonth_day;
}
public void setResourceMonth_day(String resourceMonthDay) {
resourceMonth_day = resourceMonthDay;
}
public String getResourceMonth_hour() {
return resourceMonth_hour;
}
public void setResourceMonth_hour(String resourceMonthHour) {
resourceMonth_hour = resourceMonthHour;
}
public String getResourceMonth_minute() {
return resourceMonth_minute;
}
public void setResourceMonth_minute(String resourceMonthMinute) {
resourceMonth_minute = resourceMonthMinute;
}
public String getPerformanceDay_hour() {
return performanceDay_hour;
}
public void setPerformanceDay_hour(String performanceDayHour) {
performanceDay_hour = performanceDayHour;
}
public String getPerformanceDay_minute() {
return performanceDay_minute;
}
public void setPerformanceDay_minute(String performanceDayMinute) {
performanceDay_minute = performanceDayMinute;
}
public String getPerformanceWeek_day() {
return performanceWeek_day;
}
public void setPerformanceWeek_day(String performanceWeekDay) {
performanceWeek_day = performanceWeekDay;
}
public String getPerformanceWeek_hour() {
return performanceWeek_hour;
}
public void setPerformanceWeek_hour(String performanceWeekHour) {
performanceWeek_hour = performanceWeekHour;
}
public String getPerformanceWeek_minute() {
return performanceWeek_minute;
}
public void setPerformanceWeek_minute(String performanceWeekMinute) {
performanceWeek_minute = performanceWeekMinute;
}
public String getPerformanceMonth_day() {
return performanceMonth_day;
}
public void setPerformanceMonth_day(String performanceMonthDay) {
performanceMonth_day = performanceMonthDay;
}
public String getPerformanceMonth_hour() {
return performanceMonth_hour;
}
public void setPerformanceMonth_hour(String performanceMonthHour) {
performanceMonth_hour = performanceMonthHour;
}
public String getPerformanceMonth_minute() {
return performanceMonth_minute;
}
public void setPerformanceMonth_minute(String performanceMonthMinute) {
performanceMonth_minute = performanceMonthMinute;
}
}
| true |
c37ad2c9aa48841a8f2d4c488705756cd7ee422a | Java | Zhuinden/flowless | /flowless-sample-master-detail/src/main/java/com/zhuinden/flow_alpha_master_detail/paths/FourthMasterKey.java | UTF-8 | 620 | 1.960938 | 2 | [
"Apache-2.0"
] | permissive | package com.zhuinden.flow_alpha_master_detail.paths;
import com.google.auto.value.AutoValue;
import com.zhuinden.flow_alpha_master_detail.IsMaster;
import com.zhuinden.flow_alpha_master_detail.R;
import com.zhuinden.flow_alpha_master_detail.extracted.FlowAnimation;
import com.zhuinden.flow_alpha_master_detail.extracted.LayoutKey;
/**
* Created by Zhuinden on 2016.04.16..
*/
@AutoValue
public abstract class FourthMasterKey
implements LayoutKey, IsMaster {
public static FourthMasterKey create() {
return new AutoValue_FourthMasterKey(R.layout.path_fourth_master, FlowAnimation.SEGUE);
}
}
| true |
2baaebd494cae013f75d036af80bc4326a4a42cf | Java | bo91678/itheima_health | /health_parent/health_web/src/main/java/com/itheima/health/controller/CheckGroupController.java | UTF-8 | 3,483 | 2.125 | 2 | [] | no_license | package com.itheima.health.controller;
import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.health.constant.MessageConstant;
import com.itheima.health.entity.PageResult;
import com.itheima.health.entity.QueryPageBean;
import com.itheima.health.entity.Result;
import com.itheima.health.pojo.CheckGroup;
import com.itheima.health.service.CheckGroupService;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/checkgroup")
public class CheckGroupController {
@Reference
private CheckGroupService checkGroupService;
/**
* 查询所有检查组的信息
* @return
*/
@RequestMapping("/findAll")
public Result findAll(){
//调用服务查询所有检查组数据
List<CheckGroup> checkGroupList = checkGroupService.findAll();
//返回响应
return new Result(true, MessageConstant.QUERY_CHECKGROUP_SUCCESS, checkGroupList);
}
/**
* 添加检查组数据
* @param checkitemIds
* @param checkGroup
* @return
*/
@PostMapping("/add")
public Result add(Integer[] checkitemIds, @RequestBody CheckGroup checkGroup){
//调用服务添加检查组数据
checkGroupService.add(checkGroup, checkitemIds);
//返回响应
return new Result(true, MessageConstant.ADD_CHECKGROUP_SUCCESS);
}
/**
* 分页查询检查组信息
* @param queryPageBean
* @return
*/
@PostMapping("/findPage")
public Result findPage(@RequestBody QueryPageBean queryPageBean){
//调用服务分页查询数据
PageResult<CheckGroup> pageResult = checkGroupService.findPage(queryPageBean);
//返回响应
return new Result(true, MessageConstant.QUERY_CHECKGROUP_SUCCESS, pageResult);
}
/**
* 根据id查询检查组信息
* @param checkGroupId
* @return
*/
@GetMapping("/findById")
public Result findById(int checkGroupId){
//调用服务查询检查组数据
CheckGroup checkGroup = checkGroupService.findById(checkGroupId);
//返回响应
return new Result(true, MessageConstant.QUERY_CHECKGROUP_SUCCESS, checkGroup);
}
/**
* 通过检查组id查询选中的检查项id
* @param checkGroupId
* @return
*/
@GetMapping("/findCheckItemIdsByCheckGroupId")
public Result findCheckItemIdsByCheckGroupId(int checkGroupId){
//调用服务查询数据
List<Integer> checkItemIds = checkGroupService.findCheckItemIdsByCheckGroupId(checkGroupId);
//返回响应
return new Result(true, MessageConstant.QUERY_CHECKITEM_SUCCESS, checkItemIds);
}
/**
* 根据id修改检查组数据
* @param checkitemIds
* @return
*/
@PostMapping("/update")
public Result update(Integer[] checkitemIds, @RequestBody CheckGroup checkGroup){
//调用服务根据id修改检查组数据
checkGroupService.update(checkGroup, checkitemIds);
//返回响应
return new Result(true, MessageConstant.EDIT_CHECKGROUP_SUCCESS);
}
/**
* 根据id删除检查组信息
* @param id
* @return
*/
@PostMapping("/deleteById")
public Result deleteById(int id){
//调用服务根据id删除检查组信息
checkGroupService.deleteById(id);
return new Result(true, MessageConstant.DELETE_CHECKGROUP_SUCCESS);
}
}
| true |
07c5de88768d5c3fd14e89a67c7ce8c897c2e806 | Java | LongYeh/OCPJP | /src/main/java/com/test/exception/Question98.java | UTF-8 | 511 | 3.140625 | 3 | [] | no_license | package com.test.exception;
import java.io.IOException;
public class Question98 {
public static void main(String[] args) {
X obj=new X();
try{
obj.printFileContent();
}
// catch (Exception K){ }Exception 是IOException的superclass因此若例外發生Exception已經抓到.
catch (IOException c){
System.out.println(c);
}
}
}
class X{
public void printFileContent() throws IOException {
throw new IOException();
}
}
| true |
3ab527bbdb53af83773ed81a9ba2242881474d00 | Java | charroch/chrogeo | /chrogeo/src/com/novoda/chrogeo/server/Chrogeo.java | UTF-8 | 2,141 | 2.5625 | 3 | [] | no_license | package com.novoda.chrogeo.server;
import java.io.IOException;
import java.net.URI;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.beoui.geocell.GeocellManager;
import com.beoui.geocell.model.Point;
import com.novoda.chrogeo.server.jdo.JdoDataPointDao;
import com.novoda.chrogeo.shared.DataPoint;
public class Chrogeo extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String lat = req.getParameter("lat");
String lon = req.getParameter("lon");
double latd = Double.valueOf(lat);
double lond = Double.valueOf(lon);
Point point = new Point(latd, lond);
URI uri = URI.create(req.getRequestURI());
String tag = uri.getPath().replace("/", "");
returnColor(resp, lat, lon, proximitySearch(point, tag), tag);
}
public String proximitySearch(Point center, String tag) {
List<String> cells = GeocellManager.generateGeoCell(center);
String cell = cells.get(11);
JdoDataPointDao dao = new JdoDataPointDao();
List<DataPoint> points = dao.proximitySearch(cell, tag);
if("crime".equals(tag)) {
int size = 0;
if(points != null) {
size = points.size();
}
if(size == 0) {
return "FF00FF00";
} else if (0 < size && size < 3) {
return "FFFFFF00";
} else {
return "FFFF0000";
}
} else { //politics
if(points != null && points.size() > 0) {
String content = points.get(0).getContent();
if("conservative".equals(content)) {
return "FFFF0000";
} else {
return "FF0000FF";
}
} else {
return "FF000000";
}
}
}
private void returnColor(HttpServletResponse resp, String lat, String lon, String color, String tag) throws IOException {
resp.getContentType();
resp.getWriter().append("{\"colour\":" + "\"" + color + "\"" + ",\"lon\":" + lon +
",\"lat\":" + lat + ",\"tag\":\"" + tag + "\" }");
resp.flushBuffer();
}
}
| true |
cefe8fb7b74a89ad29e349c4c43f80a3e6774bb5 | Java | for-l00p/data-structures-and-algorithms | /java/ds/BinaryHeap.java | UTF-8 | 3,906 | 3.5 | 4 | [] | no_license | package ds;
import java.util.List;
import java.util.ArrayList;
import java.util.*;
interface MinPQ<E> {
public void insert (E element);
public E min();
public E deleteMin();
}
class Job implements Comparable<Job>{
int duration;
String name;
int priority;
public Job(int duration, String name, int priority){
this.duration = duration;
this.name = name;
this.priority = priority;
}
public int compareTo(Job job2){
return this.priority - job2.priority;
}
@Override
public String toString(){
return name;
}
}
public class BinaryHeap<E extends Comparable<E>> implements MinPQ<E>{
private final List<E> heap;
private int size;
private Comparator<E> comparator;
public BinaryHeap(){
heap = new ArrayList<>();
size = 0;
heap.add(null);
}
public BinaryHeap(E[] elements){
this();
int n = elements.length;
for (int i = 1; i <= n; i++){
heap.add(elements[i-1]);
size++;
}
int limit = size/2;
for (int i = limit; i > 0; i--){
bubbleDown(i);
}
}
public BinaryHeap(Comparator<E> comparator){
this();
this.comparator = comparator;
}
public BinaryHeap(E[] elements, Comparator<E> comparator){
this(elements);
this.comparator = comparator;
}
@Override
public void insert (E element){
heap.add(element);
size++;
bubbleUp(size);
}
@Override
public E min(){
if (isEmpty()) return null;
return heap.get(1);
}
@Override
public E deleteMin(){
if (isEmpty()) return null;
E temp = heap.get(1);
heap.set(1, heap.get(size));
size--;
bubbleDown(1);
return temp;
}
private boolean isEmpty(){
return this.size == 0;
}
private void bubbleDown(int i){
validateIndex(i);
while(2*i <= size){
int childToSwap = 2*i;
if((2*i+1 <= size) && greater(2*i, 2*i+1)){
childToSwap++;
}
if (greater(childToSwap, i)) break;
swap(i, childToSwap);
i = childToSwap;
}
}
private void bubbleUp(int i){
validateIndex(i);
while(i > 1 && greater(i/2, i)){
swap(i, i/2);
i = i/2;
}
}
private boolean greater(int i, int j){
validateIndex(i);
validateIndex(j);
E first = heap.get(i);
E second = heap.get(j);
if (this.comparator == null){
return first.compareTo(second) > 0;
}
return comparator.compare(first, second) > 0;
}
private void swap(int i, int j){
validateIndex(i);
validateIndex(j);
E temp = heap.get(i);
heap.set(i, heap.get(j));
heap.set(j, temp);
}
private boolean validateIndex(int i){
if (i <= 0 || i > size) throw new NoSuchElementException("Index: " + i);
return true;
}
public String toString(){
StringBuilder s = new StringBuilder();
for (int i = 1; i <= size; i++){
s.append(i);
s.append(": ");
s.append(heap.get(i));
}
return s.toString();
}
static class DurationComparator implements Comparator<Job>{
@Override
public int compare(Job job1,Job job2){
return job1.duration*job1.priority - job2.duration*job2.priority;
}
}
public static void main(String[] args){
Job dishes = new Job (10, "dishes", 1);
Job shower = new Job (20, "shower", 2);
Job cleaning = new Job (5, "cleannig", 3);
Job email = new Job (12, "email", 2);
Job call = new Job (5, "call", 4);
Job[] jobs = new Job[]{dishes, shower};
DurationComparator cmp = new DurationComparator();
System.out.println("Comparing" + cmp.compare(dishes, shower));
BinaryHeap<Job> test = new BinaryHeap<>(jobs, new DurationComparator());
System.out.println("After 1: " + test);
test.insert(cleaning);
System.out.println("After 2: " + test);
test.insert(email);
test.insert(null);
System.out.println("After inserting all except call: " + test);
System.out.println("Minimum: " + test.min());
System.out.println("Deleteting:: " + test.deleteMin());
System.out.println("Minimum now: " + test.min());
test.insert(call);
System.out.println("After inserting call: " + test.min());
}
} | true |
c2c8977eb92d260410bb047d92ebbc4634732cab | Java | Arquitectura-Proyecto/bodysoft-mobileapp | /app/src/main/java/com/example/myapplication/Model/Repositories/ProfileTrainerRepository.java | UTF-8 | 8,758 | 2.015625 | 2 | [] | no_license | package com.example.myapplication.Model.Repositories;
import android.widget.Toast;
import com.apollographql.apollo.ApolloCall;
import com.apollographql.apollo.ApolloClient;
import com.apollographql.apollo.api.Response;
import com.apollographql.apollo.exception.ApolloException;
import com.example.apollographqlandroid.ProfileUsersQuery;
import com.example.apollographqlandroid.ProfileUserQuery;
import com.example.apollographqlandroid.ProfileTrainerQuery;
import com.example.apollographqlandroid.EditProfileUserMutation;
import com.example.apollographqlandroid.EditProfileTrainerMutation;
import com.example.apollographqlandroid.CreateProfileMutation;
import com.example.apollographqlandroid.ProfileSpecialitiesToAddQuery;
import com.example.apollographqlandroid.CreateProfileTrainerSpecialityMutation;
import com.example.apollographqlandroid.ProfileDegreesQuery;
import com.example.apollographqlandroid.CreateDegreeMutation;
import com.example.myapplication.Model.Models.ModelListener;
import com.example.myapplication.Model.Repositories.Data.Client;
import com.example.myapplication.ui.GlobalState;
import org.jetbrains.annotations.NotNull;
import java.util.List;
import java.util.concurrent.CompletableFuture;
public class ProfileTrainerRepository {
public static ApolloClient apolloClient= Client.getApolloClient();
public ProfileTrainerRepository(){
}
public static void getProfileUsers(ApolloCall.Callback<ProfileUsersQuery.Data>listener){
apolloClient.query(ProfileUsersQuery.builder().build()).enqueue(new ApolloCall.Callback<ProfileUsersQuery.Data>() {
@Override
public void onResponse(@NotNull Response<ProfileUsersQuery.Data> response) {
System.out.println("los datos son "+response.data().toString());
List<ProfileUsersQuery.ProfileUser> array= response.data().profileUsers();
listener.onResponse(response);
}
@Override
public void onFailure(@NotNull ApolloException e) {
System.out.println("el error es "+e.getMessage());
}
});
}
public static void getProfileTrainer(ApolloCall.Callback<ProfileTrainerQuery.Data>listener, String token){
apolloClient.query(ProfileTrainerQuery.builder().token(token).build()).enqueue(new ApolloCall.Callback<ProfileTrainerQuery.Data>() {
@Override
public void onResponse(@NotNull Response<ProfileTrainerQuery.Data> response) {
ProfileTrainerQuery.ProfileTrainer user= response.data().profileTrainer();
System.out.println("repo" + user);
listener.onResponse(response);
}
@Override
public void onFailure(@NotNull ApolloException e) {
System.out.println("el error es "+e.getMessage());
}
});
}
public static void editProfileTrainer(ApolloCall.Callback<EditProfileTrainerMutation.Data>listener, String trainer_name, int age, String photo, String telephone, String city, int sum_ratings, int num_ratings, String description, String resources, String work_experience, String token){
apolloClient.mutate(EditProfileTrainerMutation.builder().trainer_name(trainer_name).age(age).photo(photo).telephone(telephone).city(city).sum_ratings(sum_ratings).num_ratings(num_ratings).description(description).resources(resources).work_experience(work_experience).token(token).build()).enqueue(new ApolloCall.Callback<EditProfileTrainerMutation.Data>() {
@Override
public void onResponse(@NotNull Response<EditProfileTrainerMutation.Data> response) {
EditProfileTrainerMutation.UpdateProfileTrainer trainer= response.data().updateProfileTrainer();
System.out.println("repo" + trainer);
listener.onResponse(response);
}
@Override
public void onFailure(@NotNull ApolloException e) {
System.out.println("el error es "+e.getMessage());
}
});
}
public static void createProfileTrainer(ApolloCall.Callback<CreateProfileMutation.Data>listener, String trainer_name, int age, String photo, String telephone, String city, String description, String resources, String work_experience, String token){
apolloClient.mutate(CreateProfileMutation.builder().name(trainer_name).age(age).photo(photo).telephone(telephone).city(city).sum_ratings(0).num_ratings(0).description(description).resources(resources).work_experience(work_experience).token(token).build()).enqueue(new ApolloCall.Callback<CreateProfileMutation.Data>() {
@Override
public void onResponse(@NotNull Response<CreateProfileMutation.Data> response) {
String trainer= response.data().createProfile();
System.out.println("repo" + trainer);
listener.onResponse(response);
}
@Override
public void onFailure(@NotNull ApolloException e) {
System.out.println("el error es "+e.getMessage());
}
});
}
public static void getSpecialitiesToAdd(ApolloCall.Callback<ProfileSpecialitiesToAddQuery.Data>listener, String token){
apolloClient.query(ProfileSpecialitiesToAddQuery.builder().token(token).build()).enqueue(new ApolloCall.Callback<ProfileSpecialitiesToAddQuery.Data>() {
@Override
public void onResponse(@NotNull Response<ProfileSpecialitiesToAddQuery.Data> response) {
System.out.println("los datos son "+response.data().toString());
List<ProfileSpecialitiesToAddQuery.ProfileToAddSpecialitity> array= response.data().profileToAddSpecialitities();
listener.onResponse(response);
}
@Override
public void onFailure(@NotNull ApolloException e) {
System.out.println("el error es "+e.getMessage());
}
});
}
public static void createProfileTrainerSpeciality(ApolloCall.Callback<CreateProfileTrainerSpecialityMutation.Data>listener, String speciality, String token){
System.out.println("in repo: " + speciality + " token: " + token);
apolloClient.mutate(CreateProfileTrainerSpecialityMutation.builder().speciality(speciality).token(token).build()).enqueue(new ApolloCall.Callback<CreateProfileTrainerSpecialityMutation.Data>() {
@Override
public void onResponse(@NotNull Response<CreateProfileTrainerSpecialityMutation.Data> response) {
CreateProfileTrainerSpecialityMutation.CreateProfileTrainerSpeciality relation= response.data().createProfileTrainerSpeciality();
System.out.println("repo" + relation);
listener.onResponse(response);
}
@Override
public void onFailure(@NotNull ApolloException e) {
System.out.println("el error es "+e.getMessage() + " " + e.getLocalizedMessage() + " " + e.toString() + " " + e.getCause());
}
});
}
public static void getProfileDegrees(ApolloCall.Callback<ProfileDegreesQuery.Data>listener, String token){
apolloClient.query(ProfileDegreesQuery.builder().token(token).build()).enqueue(new ApolloCall.Callback<ProfileDegreesQuery.Data>() {
@Override
public void onResponse(@NotNull Response<ProfileDegreesQuery.Data> response) {
System.out.println("los datos son "+response.data().toString());
List<ProfileDegreesQuery.ProfileDegreesByTrainer> array= response.data().profileDegreesByTrainers();
listener.onResponse(response);
}
@Override
public void onFailure(@NotNull ApolloException e) {
listener.onFailure(e);
}
});
}
public static void createProfileTrainerDegree(ApolloCall.Callback<CreateDegreeMutation.Data>listener, String degree_name, int year, String institution, String token){
apolloClient.mutate(CreateDegreeMutation.builder().degree_name(degree_name).institution(institution).year(year).token(token).build()).enqueue(new ApolloCall.Callback<CreateDegreeMutation.Data>() {
@Override
public void onResponse(@NotNull Response<CreateDegreeMutation.Data> response) {
CreateDegreeMutation.CreateProfileDegree degree= response.data().createProfileDegree();
System.out.println("repo" + degree);
listener.onResponse(response);
}
@Override
public void onFailure(@NotNull ApolloException e) {
listener.onFailure(e);
}
});
}
} | true |
2b77ca0d690c9c895b5f62100ab13c8f906ac08e | Java | ahmedtanjim/Dora_TV | /app/src/main/java/com/crazybotstudio/doratv/ui/subChannelActivity.java | UTF-8 | 5,416 | 1.75 | 2 | [] | no_license | package com.crazybotstudio.doratv.ui;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.crazybotstudio.doratv.R;
import com.crazybotstudio.doratv.models.subChannel;
import com.crazybotstudio.doratv.player.PlayerActivity;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.startapp.sdk.adsbase.Ad;
import com.startapp.sdk.adsbase.StartAppAd;
import com.startapp.sdk.adsbase.StartAppSDK;
import com.startapp.sdk.adsbase.adlisteners.AdDisplayListener;
import java.util.Objects;
public class subChannelActivity extends AppCompatActivity {
private String channelName;
private DatabaseReference db_reference;
private RecyclerView recyclerView;
@Override
protected void onCreate(Bundle savedInstanceState) {
vpnControl.stopVpn(this);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sub_channel);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Objects.requireNonNull(getSupportActionBar()).setDisplayShowTitleEnabled(false);
if (getIntent().hasExtra("channelName")) {
channelName = getIntent().getExtras().get("channelName").toString();
}
TextView toolBarTextView = findViewById(R.id.toolbar_title);
toolBarTextView.setText(channelName);
FirebaseDatabase database = FirebaseDatabase.getInstance();
db_reference = FirebaseDatabase.getInstance().getReference("multi/" + channelName);
StorageReference storageReference = FirebaseStorage.getInstance().getReference();
recyclerView = this.findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new GridLayoutManager(this, 3));
StartAppSDK.init(this, getString(R.string.start_app_id), false);
StartAppAd.disableSplash();
StartAppSDK.setUserConsent (this,
"pas",
System.currentTimeMillis(),
false);
}
@Override
protected void onStart() {
super.onStart();
FirebaseRecyclerOptions<subChannel> options =
new FirebaseRecyclerOptions.Builder<subChannel>()
.setQuery(db_reference, subChannel.class)
.build();
FirebaseRecyclerAdapter<subChannel, subChannelActivity.channelNameViewHolder> adapter =
new FirebaseRecyclerAdapter<subChannel, channelNameViewHolder>(options) {
@Override
protected void onBindViewHolder(@NonNull subChannelActivity.channelNameViewHolder holder, final int position, @NonNull subChannel model) {
String cLink = model.getLink();
Glide
.with(subChannelActivity.this)
.load(cLink)
.into(holder.channelLogo);
holder.channelName.setText(model.getChannelname());
holder.itemView.setOnClickListener(view -> {
String link = model.getChannellink();
Intent profileIntent = new Intent(subChannelActivity.this, PlayerActivity.class);
profileIntent.putExtra("url_media_item", link);
// profileIntent.putExtra("type", model.getType());
profileIntent.putExtra("channelName", model.getChannelname());
startActivity(profileIntent);
});
}
@NonNull
@Override
public subChannelActivity.channelNameViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.tvchannel, viewGroup, false);
return new subChannelActivity.channelNameViewHolder(view);
}
};
recyclerView.setAdapter(adapter);
adapter.startListening();
vpnControl.stopVpn(this);
}
public static class channelNameViewHolder extends RecyclerView.ViewHolder {
TextView channelName;
ImageView channelLogo;
public channelNameViewHolder(@NonNull View itemView) {
super(itemView);
channelName = itemView.findViewById(R.id.channelName);
channelLogo = itemView.findViewById(R.id.channel_logo);
}
}
@Override
protected void onDestroy() {
super.onDestroy();
finish();
}
@Override
protected void onStop() {
super.onStop();
}
} | true |
d434bb02bfea4e59ffd516e9da17d083bbd752fc | Java | IsaiasSantana/entrevista-android | /app/src/main/java/com/isaias_santana/desafioandroid/mvp/model/mainActivity/MainActivityModel.java | UTF-8 | 6,423 | 2.453125 | 2 | [
"MIT"
] | permissive | package com.isaias_santana.desafioandroid.mvp.model.mainActivity;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.util.Log;
import com.isaias_santana.desafioandroid.domain.People;
import com.isaias_santana.desafioandroid.domain.PeopleResult;
import com.isaias_santana.desafioandroid.domain.Planet;
import com.isaias_santana.desafioandroid.domain.Specie;
import com.isaias_santana.desafioandroid.domain.interfaces.PeopleAPI;
import com.isaias_santana.desafioandroid.mvp.presenter.mainActivity.MainActivityPresenterI;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
/**
* @author Isaías Santana on 29/05/17.
* email: isds.santana@gmail.com
*/
public class MainActivityModel implements MainActivityModelI
{
private static final String BASE_URL = "http://swapi.co/api/";
private final MainActivityPresenterI.PresenterToModel presenter;
private final PeopleAPI peopleAPI;
private final Handler handler;
public MainActivityModel(MainActivityPresenterI.PresenterToModel presenter)
{
this.presenter = presenter;
peopleAPI = buildRetrofit().create(PeopleAPI.class);
handler = new Handler();
}
@Override
public void getPeoples(final int page)
{
handler.post(new Runnable() { //Para evitar erros durante a paginação.
@Override
public void run()
{
Call<PeopleResult> call = peopleAPI.getPeoples(page);
call.enqueue(new Callback<PeopleResult>() {
@Override
public void onResponse(@NonNull Call<PeopleResult> call,
@NonNull Response<PeopleResult> response) {
if (response.isSuccessful())
{
PeopleResult peopleResult = response.body();
assert peopleResult != null;
List<People> peoples = peopleResult.getPeoples();
if(peoples != null && peoples.get(0)!= null) //recuperou os dados
{
Log.d("model","Sucesso!");
getHomeWorld(peoples);
getSpecie(peoples);
presenter.setPeople(peoples,peopleResult.getNext());
}
else presenter.setPeople(null,null);
}
}
@Override
public void onFailure(@NonNull Call<PeopleResult> call, @NonNull Throwable t)
{
t.printStackTrace();
}
}); // Fim do Callback<PeopleResult>().
}
}); //fim Handler e Runnable;
}
private Retrofit buildRetrofit()
{
return new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
/*Procura pelo planeta natal*/
private void getHomeWorld(final List<People> peoples)
{
handler.post(new Runnable() {
@Override
public void run()
{
for(final People p : peoples)
{
if(p.getHomeWorld() == null || p.getHomeWorld().isEmpty())
{
p.setHomeWorld("Desconhecido");
}
else
{
Call<Planet> call = peopleAPI
.getPlanetName(getIdPlanetOrSpecie(p.getHomeWorld(),"planets"));
call.enqueue(new Callback<Planet>() {
@Override
public void onResponse(Call<Planet> call, Response<Planet> response)
{
if(response.isSuccessful())
{
p.setHomeWorld(response.body().getName());
Log.d("sp",response.body().getName());
}
}
@Override
public void onFailure(Call<Planet> call, Throwable t) {
}
});
}
}
}
});
}
private void getSpecie(final List<People> peoples)
{
handler.post(new Runnable() {
@Override
public void run() {
for(final People p : peoples)
{
if(p.getSpecies().isEmpty())
{
ArrayList<String> species = new ArrayList<String>();
species.add("Não especificado.");
p.setSpecies(species);
}
else
{
Call<Specie> call = peopleAPI
.getEspecieName(getIdPlanetOrSpecie(p.getSpecies().get(0),"species"));
call.enqueue(new Callback<Specie>() {
@Override
public void onResponse(Call<Specie> call, Response<Specie> response)
{
if(response.isSuccessful())
{
ArrayList<String> species = new ArrayList<String>();
species.add(response.body().getName());
p.setSpecies(species);
Log.d("sp",response.body().getName());
}
}
@Override
public void onFailure(Call<Specie> call, Throwable t) {
}
});
}
}
}
});
}
private String getIdPlanetOrSpecie(String url,String tag)
{
return url.substring(url.lastIndexOf(tag),url.length()).split("/")[1];
}
}
| true |
2be10b40c405e6cfd28867ffc684355b57e520da | Java | zzyyppqq/AndroidAudioVideoStudy | /app/src/main/java/com/zyp/androidaudiovideostudy/LiblameActivity.java | UTF-8 | 4,406 | 2.171875 | 2 | [] | no_license | package com.zyp.androidaudiovideostudy;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.zyp.androidaudiovideostudy.util.RecMicToMp3;
public class LiblameActivity extends AppCompatActivity {
private RecMicToMp3 mRecMicToMp3 = new RecMicToMp3(
Environment.getExternalStorageDirectory() + "/bbb.mp3", 8000);
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_liblame);
final TextView statusTextView = (TextView) findViewById(R.id.StatusTextView);
mRecMicToMp3.setHandle(new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case RecMicToMp3.MSG_REC_STARTED:
statusTextView.setText("˜^‰¹’†");
break;
case RecMicToMp3.MSG_REC_STOPPED:
statusTextView.setText("");
break;
case RecMicToMp3.MSG_ERROR_GET_MIN_BUFFERSIZE:
statusTextView.setText("");
Toast.makeText(LiblameActivity.this,
"˜^‰¹‚ªŠJŽn‚Å‚«‚Ü‚¹‚ñ‚Å‚µ‚½B‚±‚Ì’[––‚ª˜^‰¹‚ðƒTƒ|[ƒg‚",
Toast.LENGTH_LONG).show();
break;
case RecMicToMp3.MSG_ERROR_CREATE_FILE:
statusTextView.setText("");
Toast.makeText(LiblameActivity.this, "ƒtƒ@ƒCƒ‹‚ª¶¬‚Å‚«‚Ü‚¹‚ñ‚Å‚µ‚½",
Toast.LENGTH_LONG).show();
break;
case RecMicToMp3.MSG_ERROR_REC_START:
statusTextView.setText("");
Toast.makeText(LiblameActivity.this, "˜^‰¹‚ªŠJŽn‚Å‚«‚Ü‚¹‚ñ‚Å‚µ‚½",
Toast.LENGTH_LONG).show();
break;
case RecMicToMp3.MSG_ERROR_AUDIO_RECORD:
statusTextView.setText("");
Toast.makeText(LiblameActivity.this, "˜^‰¹‚ª‚Å‚«‚Ü‚¹‚ñ‚Å‚µ‚½",
Toast.LENGTH_LONG).show();
break;
case RecMicToMp3.MSG_ERROR_AUDIO_ENCODE:
statusTextView.setText("");
Toast.makeText(LiblameActivity.this, "ƒGƒ“ƒR[ƒh‚ÉŽ¸”s‚µ‚Ü‚µ‚½",
Toast.LENGTH_LONG).show();
break;
case RecMicToMp3.MSG_ERROR_WRITE_FILE:
statusTextView.setText("");
Toast.makeText(LiblameActivity.this, "ƒtƒ@ƒCƒ‹‚Ì‘‚«ž‚݂Ɏ¸”s‚µ‚Ü‚µ‚½",
Toast.LENGTH_LONG).show();
break;
case RecMicToMp3.MSG_ERROR_CLOSE_FILE:
statusTextView.setText("");
Toast.makeText(LiblameActivity.this, "ƒtƒ@ƒCƒ‹‚Ì‘‚«ž‚݂Ɏ¸”s‚µ‚Ü‚µ‚½",
Toast.LENGTH_LONG).show();
break;
default:
break;
}
}
});
Button startButton = (Button) findViewById(R.id.StartButton);
startButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mRecMicToMp3.start();
}
});
Button stopButton = (Button) findViewById(R.id.StopButton);
stopButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mRecMicToMp3.stop();
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
mRecMicToMp3.stop();
}
}
| true |
1f6f666cbf78981cff7b2212750e1b2653f88f82 | Java | ranjithaselvam/maven | /AutomateAtmecs/src/main/java/com/atmecs/project/report/LogReport.java | UTF-8 | 522 | 2.21875 | 2 | [] | no_license | package com.atmecs.project.report;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import com.atmecs.project.constants.Constants;
/**
* Which keeps track of the record when any event happens or any software run.
* @author ranjitha.selvam
*
*/
public class LogReport {
static Logger logger = null;
public static void info(String message) {
PropertyConfigurator.configure(Constants.log_file);
logger = Logger.getLogger(LogReport.class.getName());
logger.info(message);
}
}
| true |
9ecf6aea69a775e6553b2a65d2046586bd594c7a | Java | dongryoung/Class_Examples | /1. 수업 예제/20. JDBC/Ex04_update.java | UHC | 1,075 | 3.3125 | 3 | [] | no_license | import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class Ex04_update {
public static void main(String[] args) {
// ȣ(num) 1 ȸ(ȫ浿) (age) 31 ,
// ȭ ȣ(tel) 010-9876-1234
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
String url = "jdbc:oracle:thin:@127.0.0.1:1521:XE";
String user = "hanul";
String password = "0000";
Connection conn = DriverManager.getConnection(url, user, password);
System.out.println(" ");
Statement st = conn.createStatement();
String sql = "update tblMember set age = 31, tel = '010-9876-1234' "; // ο ⸦ ݵ Ѵ.
sql += "where num = 1";
int succ = st.executeUpdate(sql);
if (succ > 0) {
System.out.println(" ");
} else {
System.out.println(" ");
}
} catch (Exception e) {
e.printStackTrace();
}
} // main()
} // class | true |
a2614af78c6084687a4003c132b6e65da55cc4b8 | Java | AOCAMPH/automation_petcenter | /src/main/java/pe/com/web/petcenter/core/ElementNotPresentException.java | UTF-8 | 318 | 1.921875 | 2 | [] | no_license | package pe.com.web.petcenter.core;
import org.openqa.selenium.NoSuchElementException;
public class ElementNotPresentException extends NoSuchElementException{
/**
*
*/
private static final long serialVersionUID = 7866845021122785932L;
public ElementNotPresentException(String reason) {
super(reason);
}
} | true |
99ff5e6e88255d817360f60acc351483f19f949f | Java | Angkna/CinemaFinalBackEnd | /src/test/java/cinema/persistence/entity/test/TestMovie.java | UTF-8 | 21,848 | 2.65625 | 3 | [] | no_license | package cinema.persistence.entity.test;
import static org.junit.jupiter.api.Assertions.*;
import java.time.LocalDate;
import java.util.Collections;
import java.util.List;
import javax.persistence.EntityManager;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase.Replace;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import cinema.persistence.entity.Audiance;
import cinema.persistence.entity.Movie;
import cinema.persistence.entity.Person;
import cinema.persistence.repository.MovieRepository;
import cinema.persistence.repository.PersonRepository;
@DataJpaTest
@AutoConfigureTestDatabase(replace=Replace.NONE)
class TestMovie {
@Autowired
MovieRepository repoMovie;
@Autowired
PersonRepository repoPerson;
@Autowired
EntityManager entityManager;
@Test
void testNewMovie() {
Movie movie = new Movie("Joker", 2019);
repoMovie.save(movie);
var id = movie.getIdMovie();
System.out.println("id new movies: " + movie.getIdMovie());
assertNotNull(id);
}
@Test
void testFindAll() {
//given
List<Movie> data = List.of(
new Movie("Joker", 2019),
new Movie("Parasite",2019, 132), //1
new Movie("Interstellar",2014, 169), //2
new Movie("Gran Torino", 2008, 116));
data.forEach(entityManager::persist);
// when
var dataRead = repoMovie.findAll();
//then
dataRead.forEach(System.out::println);
assertEquals(data.size(), dataRead.size());
assertTrue(dataRead.stream()
.map(Movie::getTitle)
.allMatch(tr -> data.stream() //tous vrai
.map(Movie::getTitle)
.anyMatch(th -> th.equals(tr)) //au moins un vrai
));
}
@Test
void testFindById () {
Movie movie = new Movie("Joker", 2019);
entityManager.persist(movie);
var id = movie.getIdMovie();
//when
var movieReadOpt = repoMovie.findById(id);
System.out.println(movieReadOpt);
assertAll(
() -> assertTrue(movieReadOpt.isPresent()),
() -> assertEquals(movie.getTitle(), movieReadOpt.get().getTitle())
);
}
@Test
void testFindByTitle() {
String title = "Le Roi Lion";
List<Movie> data = List.of(
new Movie("Parasite",2019, 132),
new Movie(title,2019),
new Movie(title, 1994));
data.forEach(entityManager::persist);
//when
var dataRead = repoMovie.findByTitle(title);
assertTrue(dataRead.stream().allMatch(m -> title.equals(m.getTitle())));
}
@Test
void testFindByTitleContainingIgnoreCase() {
String title = "Le Roi Lion";
List<Movie> data = List.of(
new Movie("Parasite",2019, 132),
new Movie(title,2019),
new Movie(title, 1994));
data.forEach(entityManager::persist);
String partTitle = "lion";
var dataRead = repoMovie.findByTitleContainingIgnoreCase(partTitle);
assertTrue(dataRead.stream().allMatch(m -> title.equals(m.getTitle())));
}
@Test
void testFindByTitleAndYear() {
String title = "Le Roi Lion";
List<Movie> data = List.of(
new Movie("Parasite",2019, 132),
new Movie(title, 2019),
new Movie(title, 1994));
data.forEach(entityManager::persist);
var dataRead = repoMovie.findByTitleAndYear("Le Roi Lion", 2019);
assertTrue(dataRead.stream().allMatch(m -> (title.equals(m.getTitle())) && (m.getYear() == 2019)));
}
@Test
void testFindByYear() {
//given
List<Movie> data = List.of(
new Movie("Joker", 2019),
new Movie("Parasite",2019, 132),
new Movie("Interstellar",2014, 169),
new Movie("Gran Torino", 2008, 116));
data.forEach(entityManager::persist);
//when
var year = 2019;
var dataRead = repoMovie.findByYear(year);
assertTrue(dataRead.stream().allMatch(m -> m.getYear() == year));
}
@Test
void testFindByYearLessThan() {
//given
List<Movie> data = List.of(
new Movie("Joker", 2019),
new Movie("Parasite",2019, 132),
new Movie("Interstellar",2014, 169),
new Movie("Gran Torino", 2008, 116));
data.forEach(entityManager::persist);
//when
var year = 2010;
var dataRead = repoMovie.findByYearLessThan(year);
assertTrue(dataRead.stream().allMatch(m -> m.getYear() < year));
}
@Test
void testFindByYearGreaterThan() {
//given
List<Movie> data = List.of(
new Movie("Joker", 2019),
new Movie("Parasite", 2019, 132),
new Movie("Interstellar", 2014, 169),
new Movie("Gran Torino", 2008, 116));
data.forEach(entityManager::persist);
//when
Integer year = 2010;
var dataRead = repoMovie.findByYearGreaterThan(year);
assertTrue(dataRead.stream().allMatch(m -> m.getYear() > year));
}
@Test
void testFindByYearBetween() {
//given
var year1 = 1990;
var year2 = 2019;
List<Movie> data = List.of(
new Movie("Joker", year2),
new Movie("Parasite",2019, 132),
new Movie("Interstellar",2014, 169),
new Movie("Gran Torino", 2008, 116) ,
new Movie("Very old", 1960, 116),
new Movie("Old", year1, 118),
new Movie("Young", 2020, 118));
data.forEach(entityManager::persist);
var dataRead = repoMovie.findByYearBetween(year1, year2);
//then
System.out.println(dataRead);
assertAll(
() -> assertEquals(5, dataRead.size() ), //assert true permet de valider le test seulement si le bolean réponse est true
() -> assertTrue(dataRead.stream() // les parenthèse permettent de mettre une chronologie aux 2 tests
.mapToInt(Movie::getYear)
.allMatch(y -> (y >= year1) && (y <= year2) )));
}
//assertAll(
// () -> assertTrue(movieReadOpt.isPresent()),
// () -> assertEquals(movie.getTitle(), movieReadOpt.get().getTitle())
// );
@Test
void testFindByYearAndTitle() {
//given
List<Movie> data = List.of(
new Movie("Joker", 2019),
new Movie("Parasite",2019, 132),
new Movie("Interstellar",2014, 169),
new Movie("Gran Torino", 2008, 116) ,
new Movie("Very old", 1960, 138),
new Movie("Le Roi Lion", 1994),
new Movie("Le Roi Lion", 2019));
data.forEach(entityManager::persist);
var year = 1994;
String title = "Le Roi Lion";
var dataRead = repoMovie.findByYearAndTitle(year, title);
//then
assertTrue(dataRead.stream()
.allMatch(m-> (m.getYear() == year) && (m.getTitle() == title)));
}
@Test
void testFindByTitleAndYearAndDuration() {
//given
List<Movie> data = List.of(
new Movie("Joker", 2019),
new Movie("Parasite",2019, 132),
new Movie("Interstellar",2014, 169),
new Movie("Gran Torino", 2008, 116) ,
new Movie("Very old", 1960, 138),
new Movie ("Le Roi Lion", 1994, 166),
new Movie ("Le Roi Lion", 2019));
data.forEach(entityManager::persist);
var year = 1994;
String title = "Le Roi Lion";
var duration = 166;
var dataRead = repoMovie.findByYearAndTitleAndDuration(year, title, duration);
assertTrue(dataRead.stream()
.allMatch(m-> (m.getYear() == year) && (m.getTitle() == title) && (m.getDuration() == duration)));
}
@Test
void testFindByDurationGreaterThan() {
List<Movie> data = List.of(
new Movie("Joker", 2019),
new Movie("Parasite",2019, 132),
new Movie("Interstellar",2014, 169),
new Movie("Gran Torino", 2008, 116) ,
new Movie("Very old", 1960, 138),
new Movie ("Le Roi Lion", 1994, 166),
new Movie ("Le Roi Lion", 2019));
data.forEach(entityManager::persist);
var duration = 130;
var dataRead = repoMovie.findByDurationGreaterThan(duration);
assertTrue(dataRead.stream().allMatch(m -> m.getDuration() > duration));
}
@Test
void testFindByDurationBetween() {
List<Movie> data = List.of(
new Movie("Joker", 2019),
new Movie("Parasite",2019, 132),
new Movie("Interstellar",2014, 169),
new Movie("Gran Torino", 2008, 116) ,
new Movie("Very old", 1960, 138),
new Movie ("Le Roi Lion", 1994, 166),
new Movie ("Le Roi Lion", 2019));
data.forEach(entityManager::persist);
var durationMin = 120;
var durationMax = 150;
var dataRead = repoMovie.findByDurationBetween(durationMin, durationMax);
assertTrue(dataRead.stream().allMatch(m -> (m.getDuration() > durationMin) && (m.getDuration() < durationMax)));
}
@Test
void testFindByDurationLessThanEqual() {
List<Movie> data = List.of(
new Movie("Joker", 2019),
new Movie("Parasite",2019, 132),
new Movie("Interstellar",2014, 169),
new Movie("Gran Torino", 2008, 116) ,
new Movie("Very old", 1960, 138),
new Movie ("Le Roi Lion", 1994, 166),
new Movie ("Le Roi Lion", 2019));
data.forEach(entityManager::persist);
var duration = 140;
var dataRead = repoMovie.findByDurationLessThanEqual(duration);
assertTrue(dataRead.stream().allMatch(m -> m.getDuration() <= duration));
}
@Test
void testFindByGenres() {
var horror = "horror";
var action = "action";
var fantasy = "fantasy";
var adventure = "adventure";
var animation = "animation";
// var genres = List.of(horror, action, fantasy, adventure, animation);
// genres.forEach(entityManager::persist);
var joker = new Movie("Joker", 2019, 165);
var parasite = new Movie("Parasite",2019, 132);
var interstellar = new Movie("Interstellar",2014, 169);
var granTorino= new Movie("Gran Torino", 2008, 116);
var impitoyable = new Movie("Impitoyable", 1992, 130);
var infwar = new Movie("Avengers: Infinity War", 2018, 149);
var end = new Movie("Avengers: Endgame", 2019, 181);
var genres1 = List.of(horror);
var genres2 = List.of(action, adventure);
var genres3 = List.of(animation, adventure, fantasy);
joker.setGenres(genres1);
interstellar.setGenres(genres2);
infwar.setGenres(genres3);
var movies = List.of(joker, parasite, interstellar, granTorino, impitoyable, infwar, end);
movies.forEach(entityManager::persist);
String genreRead = "adventure";
var dataRead = repoMovie.findByGenresIgnoreCase(genreRead);
System.out.println(dataRead);
assertTrue(dataRead.stream()
.allMatch(m -> m.getGenres().stream()
.anyMatch(g -> g.equals(genreRead))
));
}
@Test
void testFindByRatingGreaterThanEqual() {
List<Movie> data = List.of(
new Movie("Joker", 2019, 155, 9.9, null),
new Movie("Parasite",2019, 132, 8.2, null),
new Movie("Interstellar",2014, 169, 3.7, null),
new Movie("Gran Torino", 2008, 116, 4.9, null),
new Movie("Very old", 1960, 138, 1.3, null),
new Movie ("Le Roi Lion", 1994, 166, 7.1, null),
new Movie ("Le Roi Lion", 2019, 178, 8.5, null));
data.forEach(entityManager::persist);
var rating = 6.0;
var dataRead = repoMovie.findByRatingGreaterThanEqual(rating);
assertTrue(dataRead.stream().allMatch(m -> (m.getRating() > rating)));
}
@Test
void testFindBySynopsisContaining() {
Movie m1 = new Movie("Joker", 2019);
Movie m2 = new Movie("Parasite",2019, 132);
Movie m3 = new Movie("Interstellar",2014, 169);
Movie m4 = new Movie("Gran Torino", 2008, 116);
List<Movie> data = List.of(m1, m2, m3, m4);
String synoM2 = "L'histoire passionate des vers de terre irlandais en australie";
String synoM3 = "Une découverte des planets dans leur intimité la plus secrete";
m2.setSynopsis(synoM2);
m3.setSynopsis(synoM3);
data.forEach(entityManager::persist);
String extrait = "vers";
var dataRead = repoMovie.findBySynopsisContaining(extrait);
assertTrue(dataRead.stream().allMatch(m -> m.getSynopsis().contains(extrait)));
}
@Test
void testFindByAudiance() {
Movie m1 = new Movie("Joker", 2019);
Movie m2 = new Movie("Parasite",2019, 132);
Movie m3 = new Movie("Interstellar",2014, 169);
Movie m4 = new Movie("Gran Torino", 2008, 116);
Movie m5 = new Movie("Very old", 1960, 138);
List<Movie> data = List.of(m1, m2, m3, m4, m5);
m1.setAudiance(Audiance.PG13);
m2.setAudiance(Audiance.NC17);
m3.setAudiance(Audiance.G);
m4.setAudiance(Audiance.PG13);
data.forEach(entityManager::persist);
var dataRead = repoMovie.findByAudiance(Audiance.PG13);
assertTrue(dataRead.stream().allMatch(m -> m.getAudiance() == Audiance.PG13));
}
@Test
void testSaveMovieWithDirector() {
//Given
Person person = new Person ("Todd Phillips", LocalDate.of(1970,12,20));
Movie movie = new Movie("Joker", 2019, 165, person);
entityManager.persist(person); //already in cache
repoMovie.save(movie);
//var id = movie.getIdMovie();
System.out.println(movie);
System.out.println(person);
}
@Test
void testFindByDirector() {
var todd = new Person("Todd Phillips", LocalDate.of(1970, 12, 20));
var clint = new Person("Clint Eastwood", LocalDate.of(1930, 5, 31));
var brad = new Person("Bradley Cooper", LocalDate.of(1975, 1, 5));
var persons = List.of(todd, clint, brad);
persons.forEach(entityManager::persist);
var joker = new Movie("Joker", 2019, 165, todd);
var parasite = new Movie("Parasite",2019, 132);
var interstellar = new Movie("Interstellar",2014, 169);
var granTorino= new Movie("Gran Torino", 2008, 116, clint);
var impitoyable = new Movie("Impitoyable", 1992, 130, clint);
var snip = new Movie("American Sniper", 2014, 133, clint);
var bad = new Movie("Very Bad Trip", 2009, 100, todd);
var infwar = new Movie("Avengers: Infinity War", 2018, 149);
var movies = List.of(joker, parasite, interstellar, granTorino, impitoyable, snip,bad, infwar);
movies.forEach(entityManager::persist);
var dataRead = repoMovie.findByDirector(clint);
assertTrue(dataRead.stream().allMatch(m -> clint.equals(m.getDirector())));
}
@Test
void testFindByDirectorName() {
var todd = new Person("Todd Phillips", LocalDate.of(1970, 12, 20));
var clint = new Person("Clint Eastwood", LocalDate.of(1930, 5, 31));
var brad = new Person("Bradley Cooper", LocalDate.of(1975, 1, 5));
var persons = List.of(todd, clint, brad);
persons.forEach(entityManager::persist);
var joker = new Movie("Joker", 2019, 165, todd);
var parasite = new Movie("Parasite",2019, 132);
var interstellar = new Movie("Interstellar",2014, 169);
var granTorino= new Movie("Gran Torino", 2008, 116, clint);
var impitoyable = new Movie("Impitoyable", 1992, 130, clint);
var snip = new Movie("American Sniper", 2014, 133, clint);
var bad = new Movie("Very Bad Trip", 2009, 100, todd);
var infwar = new Movie("Avengers: Infinity War", 2018, 149);
var movies = List.of(joker, parasite, interstellar, granTorino, impitoyable, snip,bad, infwar);
movies.forEach(entityManager::persist);
String Name = "Todd Phillips";
var dataRead = repoMovie.findByDirectorName(Name);
assertTrue(dataRead.stream().allMatch(m -> todd.equals(m.getDirector())));
}
@Test
void testFindByDirectorNameEndingWith() {
var todd = new Person("Todd Phillips", LocalDate.of(1970, 12, 20));
var clint = new Person("Clint Eastwood", LocalDate.of(1930, 5, 31));
var brad = new Person("Bradley Cooper", LocalDate.of(1975, 1, 5));
var persons = List.of(todd, clint, brad);
persons.forEach(entityManager::persist);
var joker = new Movie("Joker", 2019, 165, todd);
var parasite = new Movie("Parasite",2019, 132);
var interstellar = new Movie("Interstellar",2014, 169);
var granTorino= new Movie("Gran Torino", 2008, 116, clint);
var impitoyable = new Movie("Impitoyable", 1992, 130, clint);
var snip = new Movie("American Sniper", 2014, 133, clint);
var bad = new Movie("Very Bad Trip", 2009, 100, todd);
var infwar = new Movie("Avengers: Infinity War", 2018, 149);
var movies = List.of(joker, parasite, interstellar, granTorino, impitoyable, snip,bad, infwar);
movies.forEach(entityManager::persist);
String partName = "lips";
var dataRead = repoMovie.findByDirectorNameEndingWith(partName);
assertTrue(dataRead.stream().allMatch(m -> todd.equals(m.getDirector())));
}
@Test
void testFindByDirectorIdPerson() {
var todd = new Person("Todd Phillips", LocalDate.of(1970, 12, 20));
var clint = new Person("Clint Eastwood", LocalDate.of(1930, 5, 31));
var brad = new Person("Bradley Cooper", LocalDate.of(1975, 1, 5));
var persons = List.of(todd, clint, brad);
persons.forEach(entityManager::persist);
var joker = new Movie("Joker", 2019, 165, todd);
var parasite = new Movie("Parasite",2019, 132);
var interstellar = new Movie("Interstellar",2014, 169);
var granTorino= new Movie("Gran Torino", 2008, 116, clint);
var impitoyable = new Movie("Impitoyable", 1992, 130, clint);
var snip = new Movie("American Sniper", 2014, 133, clint);
var bad = new Movie("Very Bad Trip", 2009, 100, todd);
var infwar = new Movie("Avengers: Infinity War", 2018, 149);
var movies = List.of(joker, parasite, interstellar, granTorino, impitoyable, snip,bad, infwar);
movies.forEach(entityManager::persist);
var idDirector = clint.getIdPerson();
//when
var dataRead = repoMovie.findByDirectorIdPerson(idDirector);
assertTrue(dataRead.stream().allMatch(m -> clint.equals(m.getDirector())));
}
// @Test
// void testFindByActorsName() {
// var todd = new Person("Todd Phillips", LocalDate.of(1970, 12, 20));
// var clint = new Person("Clint Eastwood", LocalDate.of(1930, 5, 31));
// var brad = new Person("Bradley Cooper", LocalDate.of(1975, 1, 5));
// var gene = new Person("Gene Hackman", LocalDate.of(1930, 1, 30));
// var morgan = new Person("Morgan Freeman", LocalDate.of(1937, 6, 1));
// var persons = List.of(todd, clint, brad, gene, morgan);
// persons.forEach(entityManager::persist);
//
// var joker = new Movie("Joker", 2019, 165, todd);
// var parasite = new Movie("Parasite",2019, 132);
// var interstellar = new Movie("Interstellar",2014, 169);
// var granTorino= new Movie("Gran Torino", 2008, 116, clint);
// var impitoyable = new Movie("Impitoyable", 1992, 130, clint);
// var infwar = new Movie("Avengers: Infinity War", 2018, 149);
// var end = new Movie("Avengers: Endgame", 2019, 181);
// var actors1 = List.of(morgan);
// var actors2 = List.of(gene, clint);
// var actors3 = List.of(gene, morgan, brad);
// joker.setActors(actors1);
// interstellar.setActors(actors2);
// infwar.setActors(actors3);
// var movies = List.of(joker, parasite, interstellar, granTorino, impitoyable, infwar, end);
// movies.forEach(entityManager::persist);
//
// String actorName = "Gene Hackman";
// var dataRead = repoMovie.findByActorsName(actorName);
// assertTrue(dataRead.stream()
// .allMatch(m -> m.getActors().stream()
// .map(Person::getName)
// .anyMatch(n -> n.equals(actorName))
// ));
// }
//
// @Test
// void testFindByActorsIdPerson() {
// var todd = new Person("Todd Phillips", LocalDate.of(1970, 12, 20));
// var clint = new Person("Clint Eastwood", LocalDate.of(1930, 5, 31));
// var brad = new Person("Bradley Cooper", LocalDate.of(1975, 1, 5));
// var gene = new Person("Gene Hackman", LocalDate.of(1930, 1, 30));
// var morgan = new Person("Morgan Freeman", LocalDate.of(1937, 6, 1));
// var persons = List.of(todd, clint, brad, gene, morgan);
// persons.forEach(entityManager::persist);
//
// var joker = new Movie("Joker", 2019, 165, todd);
// var parasite = new Movie("Parasite",2019, 132);
// var interstellar = new Movie("Interstellar",2014, 169);
// var granTorino= new Movie("Gran Torino", 2008, 116, clint);
// var impitoyable = new Movie("Impitoyable", 1992, 130, clint);
// var infwar = new Movie("Avengers: Infinity War", 2018, 149);
// var end = new Movie("Avengers: Endgame", 2019, 181);
// var actors1 = List.of(morgan);
// var actors2 = List.of(gene, clint);
// var actors3 = List.of(gene, morgan, brad);
// joker.setActors(actors1);
// interstellar.setActors(actors2);
// infwar.setActors(actors3);
// var movies = List.of(joker, parasite, interstellar, granTorino, impitoyable, infwar, end);
// movies.forEach(entityManager::persist);
//
// var idActor = clint.getIdPerson();
// var dataRead = repoMovie.findByActorsIdPerson(idActor);
// assertTrue(dataRead.stream()
// .allMatch(m -> m.getActors().stream()
// .map(Person::getIdPerson)
// .anyMatch(n -> n.equals(idActor))
// ));
// }
//
// @Test
// void testfindByActorsNameEndingWith (){
// //given
// var joker = new Movie("Joker", 2019, 165);
// var roi = new Movie ("Le Roi Lion", 1994, 166);
// var parasite = new Movie("Parasite", 2019, 132);
// var mad = new Movie("Mad Max", 1987);
// var arme = new Movie ("L'arme Fatale", 1978);
// List<Movie> movies = List.of(joker, roi, parasite, mad, arme);
// movies.forEach(entityManager::persist);
//
// var mel = new Person("Mel Gibson");
// var whoopi = new Person("Whoopi Golberg");
// var danny = new Person("Danny Glover")
// ; entityManager.persist(mel);
// entityManager.persist(whoopi);
// entityManager.persist(danny);
//
// roi.getActors().add(whoopi);
// mad.getActors().add(mel);
// Collections.addAll(arme.getActors(), mel, danny);
// entityManager.flush();
// //when
// var moviesWithMel = repoMovie.findByActorsNameEndingWith("Gibson");
//
// //then
// assertAll(
// () -> assertTrue(moviesWithMel.contains(mad)),
// () -> assertTrue(moviesWithMel.contains(arme)),
// () -> assertFalse(moviesWithMel.contains(roi))
// );
// }
//
@Test
void testAct() {
//Given
Person person = new Person ("Todd Phillips", LocalDate.of(1970,12,20));
entityManager.persist(person); //already in cache
Movie movie = new Movie("Joker", 2019, 165);
movie.getActors().add(person);
entityManager.persist(movie);
entityManager.flush();
String role = "JeanJoker";
}
@Test
void testMovieLike() {
var listMovieLikedByOne = repoMovie.findByUsersWhoLike(3);
System.out.println("Liste de movie liked by user 3 : " + listMovieLikedByOne);
}
@Test
void testMovieActor() {
var movietest = repoMovie.findById(15);
movietest.ifPresent(m -> {
System.out.println(m);
System.out.println(m.getActors());
});
}
}
| true |
7a803b85f85a9b4f4ec0faeb6cd26b7fbb5cd9f2 | Java | evertonschuster/SistemaPOO2 | /SistemaPOO2/src/br/edu/udc/sistemas/poo2/main/Main.java | UTF-8 | 481 | 2.03125 | 2 | [] | no_license | package br.edu.udc.sistemas.poo2.main;
import br.edu.udc.sistemas.poo2.gui.FormMain;
import br.edu.udc.sistemas.poo2.infra.IOTools;
public class Main {
public static void main(String[] args) throws Exception {
// br.edu.udc.sistemas.poo2.tui.FormMain frm = new br.edu.udc.sistemas.poo2.tui.FormMain();
// frm.execute();
//str = IOTools.geradorDeToString( new String[]{"01","ever","luan"} , new Integer[]{3,7,7} );
FormMain form = new FormMain();
}
}
| true |
57278ef0701d6ad3f837abf5c4b1e5eed4adf925 | Java | gache/exercicesProgrammationJava | /src/lesConditions/Date.java | UTF-8 | 1,141 | 3.578125 | 4 | [] | no_license | package lesConditions;
import java.util.Scanner;
public class Date {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Déclarion des variables
int jour, mois, annee;
System.out.println("Saisir un jour: ");
jour = scanner.nextInt();
System.out.println("Saisir le mois: ");
mois = scanner.nextInt();
System.out.println("Saisir l'anneé: ");
annee = scanner.nextInt();
if ((jour >= 1) && (jour <= 30)) { // si le jour est correcte
if ((mois >= 1) && (mois <= 12)) { // si le mois est correcte
if (annee != 0) { // si l'année est correcte
System.out.println("La date est correcte");
} else {
System.out.println("La date n'est pas correcte, l'année est incorrect");
}
} else {
System.out.println("La date n'est pas correcte, Le mois est incorrect");
}
} else {
System.out.println("La date n'est pas correcte, Le jour est incorrect ");
}
}
}
| true |
9b88e8453b4cf0bfabed615a1836cfa65d0df028 | Java | ThangaArchi/ODC | /JavaSource/oem/edge/ed/odc/dropbox/service/helper/ServiceMulticaster.java | UTF-8 | 4,299 | 2.359375 | 2 | [] | no_license | package oem.edge.ed.odc.dropbox.service.helper;
import java.util.*;
/* ------------------------------------------------------------------ */
/* Copyright Header Check */
/* ------------------------------------------------------------------ */
/* */
/* OCO Source Materials */
/* */
/* Product(s): PROFIT */
/* */
/* (C)Copyright IBM Corp. 2006 */
/* */
/* All Rights Reserved */
/* US Government Users Restricted Rights */
/* */
/* The source code for this program is not published or otherwise */
/* divested of its trade secrets, irrespective of what has been */
/* deposited with the US Copyright Office. */
/* ------------------------------------------------------------------ */
/* Please do not remove any of these commented lines 21 lines */
/* ------------------------------------------------------------------ */
/* Copyright Footer Check */
/* ------------------------------------------------------------------ */
// Listener linking/management
class ServiceMulticaster implements OperationListener, SessionListener {
// Static Worker routine
public static EventListener removeInternal(EventListener l,
EventListener oldl) {
if (l == oldl || l == null) {
return null;
} else if (l instanceof ServiceMulticaster) {
return ((ServiceMulticaster)l).remove(oldl);
} else {
return l; // it's not here
}
}
// Static Worker routine
public static EventListener addInternal(EventListener a,
EventListener b) {
if (a == null) return b;
if (b == null) return a;
return new ServiceMulticaster(a, b);
}
public EventListener remove(EventListener oldl) {
if (oldl == a) return b;
if (oldl == b) return a;
EventListener a2 = removeInternal(a, oldl);
EventListener b2 = removeInternal(b, oldl);
if (a2 == a && b2 == b) {
return this; // it's not here
}
return addInternal(a2, b2);
}
private final EventListener a, b;
public ServiceMulticaster(EventListener a, EventListener b) {
this.a = a;
this.b = b;
}
// ------------- Operation Event processing --------------
public static OperationListener addOperationListener(OperationListener a,
OperationListener b) {
return (OperationListener)addInternal(a, b);
}
public static OperationListener removeOperationListener(OperationListener l,
OperationListener oldl) {
return (OperationListener)removeInternal(l, oldl);
}
public void operationUpdate(OperationEvent e) {
// we are ALWAYS full
((OperationListener)a).operationUpdate(e);
((OperationListener)b).operationUpdate(e);
}
// -------------- Session Event processing ---------------
public static SessionListener addSessionListener(SessionListener a,
SessionListener b) {
return (SessionListener)addInternal(a, b);
}
public static SessionListener removeSessionListener(SessionListener l,
SessionListener oldl) {
return (SessionListener)removeInternal(l, oldl);
}
public void sessionUpdate(SessionEvent e) {
// we are ALWAYS full
((SessionListener)a).sessionUpdate(e);
((SessionListener)b).sessionUpdate(e);
}
}
| true |
f23462ef0ff0443526f76612ffb25c34f8807062 | Java | yinyifan1991/SimpleDht | /app/src/main/java/edu/buffalo/cse/cse486586/simpledht/Message.java | UTF-8 | 792 | 2.28125 | 2 | [] | no_license | package edu.buffalo.cse.cse486586.simpledht;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
/**
* Created by yifan on 4/9/17.
*/
public class Message implements Serializable {
String nodeId;
String predId;
String succId;
int type;
String port;
String predPort;
String succPort;
Map<String, String> map = new HashMap<String, String>();
public Message(String port, String nodeId, String predPort, String succPort, String predId, String succId, int type, Map<String, String> map) {
this.nodeId = nodeId;
this.predId = predId;
this.succId = succId;
this.type = type;
this.port = port;
this.predPort = predPort;
this.succPort = succPort;
this.map = map;
}
}
| true |
104be46bddbd7c686abb0a9f243943cb300d1401 | Java | juanmav/SiuWeb | /src/com/diphot/siuweb/client/services/InspeccionService.java | UTF-8 | 569 | 1.5625 | 2 | [] | no_license | package com.diphot.siuweb.client.services;
import java.util.ArrayList;
import com.diphot.siuweb.shared.dtos.EncodedImageDTO;
import com.diphot.siuweb.shared.dtos.InspeccionDTO;
import com.google.gwt.user.client.rpc.RemoteService;
import com.google.gwt.user.client.rpc.RemoteServiceRelativePath;
@RemoteServiceRelativePath("inspeccionservice")
public interface InspeccionService extends RemoteService {
ArrayList<InspeccionDTO> getList();
Long create(InspeccionDTO dto);
void createImage(EncodedImageDTO dto, int numero);
void examplesCreate();
}
| true |
9e37fae7d4c512b6947f31737834689f49a049ee | Java | juancsosap/javatraining | /JavaApps/src/WebDownloader/Downloader.java | UTF-8 | 1,755 | 3.125 | 3 | [] | no_license | package WebDownloader;
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.io.Writer;
import java.net.URL;
public class Downloader {
public static void download(String url, String target, boolean binary) {
try {
System.err.println("Downloading file from " + url);
URL website = new URL(url);
try(InputStream in = website.openStream()) {
if(binary) {
try(OutputStream out = new FileOutputStream(target)) {
int bytes;
byte[] buffer = new byte[1024];
while((bytes = in.read(buffer)) != -1) {
out.write(buffer, 0, bytes);
}
}
} else {
try(Reader inRead = new InputStreamReader(in);
BufferedReader inBuffer = new BufferedReader(inRead);
Writer outWrite = new FileWriter(target)){
String line;
while((line = inBuffer.readLine()) != null) {
outWrite.write(line + "\n");
}
}
}
}
} catch (IOException e) {
System.err.println("Error : " + e.getMessage());
}
}
public static void download(String url, String target) { download(url, target, false); }
}
| true |
4a57d283222f8748ba89eaeb5d01c76fb8ddddfd | Java | ppareit/pebble-locker | /pebble-locker-android/pebblelocker/src/main/java/com/lukekorth/pebblelocker/receivers/ConnectionReceiver.java | UTF-8 | 3,905 | 2.21875 | 2 | [
"MIT"
] | permissive | package com.lukekorth.pebblelocker.receivers;
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import com.lukekorth.pebblelocker.LockState;
import com.lukekorth.pebblelocker.Locker;
import com.lukekorth.pebblelocker.helpers.BaseBroadcastReceiver;
import com.lukekorth.pebblelocker.helpers.BluetoothHelper;
import com.lukekorth.pebblelocker.helpers.DeviceHelper;
import com.lukekorth.pebblelocker.helpers.WifiHelper;
public class ConnectionReceiver extends BaseBroadcastReceiver {
private static final String PEBBLE_CONNECTED = "com.getpebble.action.pebble_connected";
private static final String PEBBLE_DISCONNECTED = "com.getpebble.action.pebble_disconnected";
private static final String BLUETOOTH_CONNECTED = "android.bluetooth.device.action.acl_connected";
private static final String BLUETOOTH_DISCONNECTED = "android.bluetooth.device.action.acl_disconnected";
private static final String CONNECTIVITY_CHANGE = "android.net.conn.connectivity_change";
private static final String USER_PRESENT = "android.intent.action.user_present";
public static final String STATUS_CHANGED_INTENT = "com.lukekorth.pebblelocker.STATUS_CHANGED";
public static final String LOCKED = "locked";
private SharedPreferences mPrefs;
private String mAction;
@SuppressLint("DefaultLocale")
@Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
acquireWakeLock();
mPrefs = PreferenceManager.getDefaultSharedPreferences(context);
mAction = intent.getAction().toLowerCase();
mLogger.log("ConnectionReceiver: " + mAction);
DeviceHelper deviceHelper = new DeviceHelper(context, mLogger);
deviceHelper.sendLockStatusChangedBroadcast();
LockState lockState = LockState.getCurrentState(context);
if (lockState == LockState.AUTO) {
checkForBluetoothDevice(((BluetoothDevice) intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)));
boolean isWifiConnected = new WifiHelper(context, mLogger).isTrustedWifiConnected();
if (mAction.equals(USER_PRESENT) && deviceHelper.isUnlockNeeded()) {
mLogger.log("User present and need to unlock...attempting to unlock");
new Locker(context, mTag).handleLocking();
} else if ((mAction.equals(PEBBLE_CONNECTED) || mAction.equals(BLUETOOTH_CONNECTED) ||
(mAction.equals(CONNECTIVITY_CHANGE) && isWifiConnected)) && deviceHelper.isLocked(true)) {
mLogger.log("Attempting unlock");
new Locker(context, mTag).handleLocking();
} else if ((mAction.equals(PEBBLE_DISCONNECTED) || mAction.equals(BLUETOOTH_DISCONNECTED) ||
(mAction.equals(CONNECTIVITY_CHANGE) && !isWifiConnected)) && !deviceHelper.isLocked(false)) {
mLogger.log("Attempting lock");
lockWithDelay();
}
} else {
mLogger.log("Lock state was manually set to " + lockState.getDisplayName());
}
releaseWakeLock();
}
private void lockWithDelay() {
int delay = Integer.parseInt(mPrefs.getString("key_grace_period", "2"));
if (delay != 0) {
mLogger.log("Sleeping for " + delay + " seconds");
SystemClock.sleep(delay * 1000);
}
mLogger.log("Locking...");
new Locker(mContext, mTag).handleLocking();
}
private void checkForBluetoothDevice(BluetoothDevice device) {
if (mAction.equals(BLUETOOTH_CONNECTED)) {
new BluetoothHelper(mContext, mLogger).setDeviceStatus(device.getName(), device.getAddress(), true);
} else if (mAction.equals(BLUETOOTH_DISCONNECTED)) {
new BluetoothHelper(mContext, mLogger).setDeviceStatus(device.getName(), device.getAddress(), false);
}
}
}
| true |
e03449440220c95d26d675838abc441243daa7aa | Java | charles-lo/TaipeiZooDemo | /app/src/main/java/com/example/charleslo/taipeizoodemo/model/ZooSection.java | UTF-8 | 1,135 | 1.859375 | 2 | [] | no_license | package com.example.charleslo.taipeizoodemo.model;
import com.google.gson.annotations.SerializedName;
import java.io.Serializable;
/**
*/
public class ZooSection implements Serializable {
@SerializedName("E_Pic_URL")
public String m_PicUrl;
@SerializedName("E_Geo")
private String m_Geo;
@SerializedName("E_Info")
public String m_Info;
@SerializedName("E_no")
private String m_no;
@SerializedName("E_Category")
public String m_Category;
@SerializedName("E_Name")
public String m_Name;
@SerializedName("E_Memo")
public String m_Memo;
@SerializedName("_id")
private String m_Id;
@SerializedName("E_URL")
public String m_URL;
public ZooSection(String picUrl, String geo, String info, String no, String gategory, String name, String memo, String id, String url) {
this.m_PicUrl = picUrl;
this.m_Geo = geo;
this.m_Info = info;
this.m_no = no;
this.m_Category = gategory;
this.m_Name = name;
this.m_Memo = memo;
this.m_Id = id;
this.m_URL = url;
}
public ZooSection() {
}
} | true |
bba75574d04ff9e59d691330a1959034dd795c9b | Java | Searge-DP/Practical-Logistics | /src/main/java/sonar/logistics/info/providers/tile/AE2GridProvider.java | UTF-8 | 6,697 | 1.851563 | 2 | [] | no_license | package sonar.logistics.info.providers.tile;
import java.util.Iterator;
import java.util.List;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.World;
import net.minecraftforge.common.util.ForgeDirection;
import sonar.logistics.api.Info;
import sonar.logistics.api.StandardInfo;
import sonar.logistics.api.providers.TileProvider;
import sonar.logistics.integration.AE2Helper;
import appeng.api.AEApi;
import appeng.api.implementations.IPowerChannelState;
import appeng.api.implementations.tiles.IChestOrDrive;
import appeng.api.networking.IGrid;
import appeng.api.networking.IGridBlock;
import appeng.api.networking.IGridConnection;
import appeng.api.networking.IGridHost;
import appeng.api.networking.IGridNode;
import appeng.api.networking.IMachineSet;
import appeng.api.networking.storage.IStorageGrid;
import appeng.api.storage.ICellInventory;
import appeng.api.storage.ICellInventoryHandler;
import appeng.api.storage.IMEInventory;
import appeng.api.storage.IMEInventoryHandler;
import appeng.api.storage.StorageChannel;
import appeng.api.storage.data.IAEFluidStack;
import appeng.api.storage.data.IAEItemStack;
import appeng.api.storage.data.IItemList;
import appeng.core.Api;
import appeng.me.GridAccessException;
import appeng.me.helpers.IGridProxyable;
import appeng.me.storage.DriveWatcher;
import appeng.tile.storage.TileChest;
import appeng.tile.storage.TileDrive;
import cpw.mods.fml.common.Loader;
public class AE2GridProvider extends TileProvider {
public static String name = "AE2-Grid-Provider";
public String[] categories = new String[] { "AE2 Energy", "AE2 Channels", "AE2 Storage" };
public String[] subcategories = new String[] { "Idle Power Usage", "Used Channels", "Is Active", "Is Powered", "Item Types", "Fluid Types", "Cell Count", "Total Cells", "Used Bytes", "Total Bytes", "Stored Item Types", "Total Item Types", "Stored Fluid Types", "Total Fluid Types" };
@Override
public String getName() {
return name;
}
@Override
public boolean canProvideInfo(World world, int x, int y, int z, ForgeDirection dir) {
TileEntity target = world.getTileEntity(x, y, z);
return target != null && (target instanceof IGridBlock || target instanceof IGridConnection || target instanceof IPowerChannelState || target instanceof IGridProxyable);
}
@Override
public void getHelperInfo(List<Info> infoList, World world, int x, int y, int z, ForgeDirection dir) {
int id = this.getID();
TileEntity target = world.getTileEntity(x, y, z);
if (target instanceof IGridBlock) {
IGridBlock grid = (IGridBlock) target;
infoList.add(new StandardInfo(id, 0, 0, (int) grid.getIdlePowerUsage()).addSuffix("ae/t"));
}
if (target instanceof IGridConnection) {
IGridConnection grid = (IGridConnection) target;
infoList.add(new StandardInfo(id, 1, 1, grid.getUsedChannels()));
}
if (target instanceof IPowerChannelState) {
IPowerChannelState grid = (IPowerChannelState) target;
infoList.add(new StandardInfo(id, 1, 2, grid.isActive()));
infoList.add(new StandardInfo(id, 1, 3, grid.isPowered()));
}
if (target instanceof IGridProxyable) {
IGridProxyable proxy = (IGridProxyable) target;
IGrid grid;
try {
grid = proxy.getProxy().getGrid();
/*
* IStorageGrid storage = grid.getCache(IStorageGrid.class); if
* (storage != null) { IItemList<IAEItemStack> itemInventory =
* storage.getItemInventory().getStorageList(); infoList.add(new
* StandardInfo(id, 2, 4, itemInventory.size()));
*
* IItemList<IAEFluidStack> fluidInventory =
* storage.getFluidInventory().getStorageList();
* infoList.add(new StandardInfo(id, 2, 5,
* fluidInventory.size())); }
*/
long usedCells = 0;
long totalCells = 0;
long usedBytes = 0;
long totalBytes = 0;
long usedTypes = 0;
long totalTypes = 0;
long usedTypesF = 0;
long totalTypesF = 0;
IMachineSet set = grid.getMachines(TileDrive.class);
// IMachineSet chest = grid.getMachines(TileChest.class);
Iterator<IGridNode> drives = set.iterator();
while (drives.hasNext()) {
IGridHost node = drives.next().getMachine();
if (node instanceof TileDrive) {
TileDrive drive = (TileDrive) node;
totalCells += drive.getCellCount();
for (int i = 0; i < drive.getInternalInventory().getSizeInventory(); i++) {
ItemStack is = drive.getInternalInventory().getStackInSlot(i);
if (is != null) {
IMEInventoryHandler itemInventory = AEApi.instance().registries().cell().getCellInventory(is, null, StorageChannel.ITEMS);
if (itemInventory instanceof ICellInventoryHandler) {
ICellInventoryHandler handler = (ICellInventoryHandler) itemInventory;
ICellInventory cellInventory = handler.getCellInv();
if (cellInventory != null) {
totalBytes += cellInventory.getTotalBytes();
usedBytes += cellInventory.getUsedBytes();
totalTypes += cellInventory.getTotalItemTypes();
usedTypes += cellInventory.getStoredItemTypes();
}
}
IMEInventoryHandler fluidInventory = AEApi.instance().registries().cell().getCellInventory(is, null, StorageChannel.FLUIDS);
if (fluidInventory instanceof ICellInventoryHandler) {
ICellInventoryHandler handler = (ICellInventoryHandler) fluidInventory;
ICellInventory cellInventory = handler.getCellInv();
if (cellInventory != null) {
totalBytes += cellInventory.getTotalBytes();
usedBytes += cellInventory.getUsedBytes();
totalTypesF += cellInventory.getTotalItemTypes();
usedTypesF += cellInventory.getStoredItemTypes();
}
}
}
}
}
}
infoList.add(new AE2Helper.StorageInfo(id, 2, 6, usedCells).addSuffix("cells"));
infoList.add(new AE2Helper.StorageInfo(id, 2, 7, totalCells).addSuffix("cells"));
infoList.add(new AE2Helper.StorageInfo(id, 2, 8, usedBytes).addSuffix("bytes"));
infoList.add(new AE2Helper.StorageInfo(id, 2, 9, totalBytes).addSuffix("bytes"));
infoList.add(new AE2Helper.StorageInfo(id, 2, 10, usedTypes));
infoList.add(new AE2Helper.StorageInfo(id, 2, 11, totalTypes));
infoList.add(new AE2Helper.StorageInfo(id, 2, 12, usedTypesF));
infoList.add(new AE2Helper.StorageInfo(id, 2, 13, totalTypesF));
} catch (GridAccessException e) {
e.printStackTrace();
}
}
}
@Override
public String getCategory(int id) {
return categories[id];
}
@Override
public String getSubCategory(int id) {
return subcategories[id];
}
public boolean isLoadable() {
return Loader.isModLoaded("appliedenergistics2");
}
}
| true |
dc3566f2e9c4a1c931129e867532c16dea9be118 | Java | alexasp/tdt4100-exercise-lectures | /src/programs/CellStructure.java | UTF-8 | 338 | 2.34375 | 2 | [] | no_license | package programs;
public class CellStructure {
public CellStructure(int rows, int columns) {
// TODO Auto-generated constructor stub
}
public Cell get(int row, int column) {
// TODO Auto-generated method stub
return null;
}
public void set(int row, int column, Cell cell) {
// TODO Auto-generated method stub
}
}
| true |
c6b8964c3fa40795dd1b9d5de4e5b43bab6abec5 | Java | y62wang/vegapunk | /src/main/java/com/y62wang/chess/engine/magic/MagicCache.java | UTF-8 | 3,836 | 2.984375 | 3 | [] | no_license | package com.y62wang.chess.engine.magic;
import com.y62wang.chess.engine.Bishop;
import com.y62wang.chess.engine.BoardUtil;
import com.y62wang.chess.engine.Rook;
import java.util.List;
import java.util.function.BiFunction;
import java.util.function.Function;
import static com.y62wang.chess.engine.BoardConstants.BOARD_SIZE;
import static com.y62wang.chess.engine.magic.MagicConstants.BISHOP_MAGIC;
import static com.y62wang.chess.engine.magic.MagicConstants.BISHOP_MAGIC_BITS;
import static com.y62wang.chess.engine.magic.MagicConstants.ROOK_MAGIC;
import static com.y62wang.chess.engine.magic.MagicConstants.ROOK_MAGIC_BITS;
public class MagicCache
{
private static MagicCache INSTANCE;
private Magic[] bishopMagic;
private Magic[] rookMagic;
static
{
INSTANCE = new MagicCache();
}
public static synchronized MagicCache getInstance()
{
if (INSTANCE == null)
{
INSTANCE = new MagicCache();
}
return INSTANCE;
}
private MagicCache()
{
rookMagic = prepareMagic(ROOK_MAGIC, ROOK_MAGIC_BITS, Rook::rookMask, Rook::rookAttacks);
bishopMagic = prepareMagic(BISHOP_MAGIC, BISHOP_MAGIC_BITS, Bishop::bishopMask, Bishop::bishopAttacks);
}
private Magic[] prepareMagic(long[] magicNumbers, int[] magicBits, Function<Integer, Long> maskFunction, BiFunction<Integer, Long, Long> attackFunction)
{
Magic[] magicCache = new Magic[BOARD_SIZE];
for (int square = 0; square < BOARD_SIZE; square++)
{
int bitShifts = BOARD_SIZE - magicBits[square];
long magicNumber = magicNumbers[square];
long mask = maskFunction.apply(square);
long[] attacks = indexAttacksCache(square, magicBits[square], magicNumber, mask, attackFunction);
Magic magic = new Magic(bitShifts, magicNumber, mask, attacks);
magicCache[square] = magic;
}
return magicCache;
}
private long[] indexAttacksCache(int square, int magicBits, long magicNumber, long mask, BiFunction<Integer, Long, Long> attackFunction)
{
List<Integer> squares = BoardUtil.squaresOfBB(mask);
long[] attacks = new long[( int ) Math.pow(2, magicBits)];
for (int encodedCombination = 0; encodedCombination < ( int ) Math.pow(2, squares.size()); encodedCombination++)
{
long occupancy = getOccupiedSquares(squares, encodedCombination);
long attackSet = attackFunction.apply(square, occupancy);
int key = ( int ) ((occupancy * magicNumber) >>> (64 - magicBits));
attacks[key] = attackSet;
}
return attacks;
}
/**
* Create a BB with specific occupancy squares.
* The occupancyBits indicates which of the square should be set.
*
* @param occupiedSquares squares that could be set
* @param occupancyBits bit at position N indicates the square occupied.get(N) should bet set
* @return BB with set occupancies
*/
private static long getOccupiedSquares(List<Integer> occupiedSquares, long occupancyBits)
{
long result = 0;
for (int i = 0; i < 32; i++)
{
if (((1L << i) & occupancyBits) != 0)
{
result |= (1L << occupiedSquares.get(i));
}
}
return result;
}
public long rookAttacks(int square, long occupied)
{
Magic magic = rookMagic[square];
return magic.getAttacks(occupied);
}
public long bishopAttacks(int square, long occupied)
{
Magic magic = bishopMagic[square];
return magic.getAttacks(occupied);
}
public long queenAttacks(int square, long occupied)
{
return bishopAttacks(square, occupied) | rookAttacks(square, occupied);
}
}
| true |
993fe8ec4fb90ae2d49e020783bf1b50a8615e87 | Java | yokotary/basic | /src/objectSample/StaticSample.java | UTF-8 | 803 | 3.671875 | 4 | [] | no_license | package objectSample;
//staticのまとめ
class StaticTest {
//staticField
static String staticField = "school";
//staticMethod
static String staticMethod() {
return "wars";
}
static int max(int x,int y){
if (x>y) {
return x;
} else {
return y;
}
//書きかけ
//return Math.max(x,y);
}
}
public class StaticSample {
public static void main(String[] args) {
//クラス名.フィールド名で利用できる
System.out.println(StaticTest.staticField);
//クラス名.メソッド名で利用できる
System.out.println(StaticTest.staticMethod());
System.out.println(StaticTest.max(10,20));
//System.out.println(StaticTest.min(10,20));
}
}
| true |
40247cb32ebdb3d5727b1cb623a65ac8bfd34c4b | Java | babbaj/pepsimod | /src/main/java/net/daporkchop/pepsimod/module/ModuleManager.java | UTF-8 | 8,059 | 2.21875 | 2 | [] | no_license | /*
* Adapted from the Wizardry License
*
* Copyright (c) 2017 Team Pepsi
*
* Permission is hereby granted to any persons and/or organizations using this software to copy, modify, merge, publish, and distribute it.
* Said persons and/or organizations are not allowed to use the software or any derivatives of the work for commercial use or any other means to generate income, nor are they allowed to claim this software as their own.
*
* The persons and/or organizations are also disallowed from sub-licensing and/or trademarking this software without explicit permission from Team Pepsi.
*
* Any persons and/or organizations using this software must disclose their source code and have it publicly available, include this license, provide sufficient credit to the original authors of the project (IE: Team Pepsi), as well as provide a link to the original project.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package net.daporkchop.pepsimod.module;
import net.daporkchop.pepsimod.module.api.Module;
import net.daporkchop.pepsimod.module.api.ModuleSortType;
import net.daporkchop.pepsimod.util.PepsiUtils;
import net.daporkchop.pepsimod.util.config.impl.GeneralTranslator;
import net.minecraft.network.Packet;
import java.util.ArrayList;
public class ModuleManager {
/**
* All modules that are registered
*/
public static ArrayList<Module> AVALIBLE_MODULES = new ArrayList<>();
/**
* All modules that are currently enabled
*/
public static ArrayList<Module> ENABLED_MODULES = new ArrayList<>();
/**
* Adds a module to the registry
*
* @param toRegister the Module to register
* @return the Module passed to the function
*/
public static final Module registerModule(Module toRegister) {
if (toRegister.shouldRegister()) {
AVALIBLE_MODULES.add(toRegister);
if (toRegister.state.enabled) {
enableModule(toRegister);
} else {
disableModule(toRegister);
}
}
return toRegister;
}
public static void unRegister(Module module) {
if (AVALIBLE_MODULES.contains(module)) {
AVALIBLE_MODULES.remove(module);
ENABLED_MODULES.remove(module);
}
}
/**
* Enables a module
*
* @param toEnable the module to enable
* @return the enabled module
*/
public static final Module enableModule(Module toEnable) {
if (!ENABLED_MODULES.contains(toEnable)) {
if (AVALIBLE_MODULES.contains(toEnable)) {
ENABLED_MODULES.add(toEnable);
toEnable.setEnabled(true);
} else {
throw new IllegalStateException("Attempted to enable an unregistered Module!");
}
}
return toEnable;
}
/**
* Disables a module
*
* @param toDisable the module to disable
* @return the disabled module
*/
public static final Module disableModule(Module toDisable) {
if (toDisable.state.enabled && ENABLED_MODULES.contains(toDisable)) {
if (AVALIBLE_MODULES.contains(toDisable)) {
ENABLED_MODULES.remove(toDisable);
toDisable.setEnabled(false);
} else {
throw new IllegalStateException("Attempted to disable an unregistered Module!");
}
}
return toDisable;
}
/**
* Toggles a module
*
* @param toToggle the module to toggle
* @return the toggled module
*/
public static final Module toggleModule(Module toToggle) {
if (toToggle.state.enabled) {
disableModule(toToggle);
} else {
enableModule(toToggle);
}
return toToggle;
}
/**
* Gets a module by it's name
*
* @param name the module's name
* @return a module, or null if nothing was found
*/
public static final Module getModuleByName(String name) {
for (Module module : AVALIBLE_MODULES) {
if (module.name.equals(name)) {
return module;
}
}
return null;
}
public static final void sortModules(ModuleSortType type) {
GeneralTranslator.INSTANCE.sortType = type;
switch (type) {
case ALPHABETICAL:
ArrayList<Module> tempArrayList = (ArrayList<Module>) ENABLED_MODULES.clone();
ArrayList<Module> newArrayList = new ArrayList<>();
ESCAPE:
for (Module module : tempArrayList) {
for (int i = 0; i < newArrayList.size(); i++) {
if (module.name.compareTo(newArrayList.get(i).name) < 0) {
newArrayList.add(i, module);
continue ESCAPE;
}
}
newArrayList.add(module);
}
ENABLED_MODULES = newArrayList;
break;
case DEFAULT: //hehe do nothing lol
break;
case SIZE:
ArrayList<Module> tempArrayList1 = (ArrayList<Module>) ENABLED_MODULES.clone();
ArrayList<Module> newArrayList1 = new ArrayList<>();
ESCAPE:
for (Module module : tempArrayList1) {
if (module.text == null) {
return;
}
for (int i = 0; i < newArrayList1.size(); i++) {
Module existingModule = newArrayList1.get(i);
if (module.text.width() > existingModule.text.width()) {
newArrayList1.add(i, module);
continue ESCAPE;
} else if (module.text.width() == existingModule.text.width()) {
if (module.name.compareTo(existingModule.name) < 0) {
newArrayList1.add(i, module);
continue ESCAPE;
}
}
}
newArrayList1.add(module);
}
ENABLED_MODULES = newArrayList1;
break;
case RANDOM:
ArrayList<Module> tempArrayList2 = (ArrayList<Module>) ENABLED_MODULES.clone();
ArrayList<Module> newArrayList2 = new ArrayList<>();
ESCAPE:
for (Module module : tempArrayList2) {
newArrayList2.add(PepsiUtils.rand(0, newArrayList2.size()), module);
}
ENABLED_MODULES = newArrayList2;
}
}
public static boolean preRecievePacket(Packet<?> packetIn) {
boolean cancel = false;
for (Module module : ENABLED_MODULES) {
if (module.preRecievePacket(packetIn)) {
cancel = true;
}
}
return cancel;
}
public static void postRecievePacket(Packet<?> packetIn) {
for (Module module : ENABLED_MODULES) {
module.postRecievePacket(packetIn);
}
}
public static boolean preSendPacket(Packet<?> packetIn) {
boolean cancel = false;
for (Module module : ENABLED_MODULES) {
if (module.preSendPacket(packetIn)) {
cancel = true;
}
}
return cancel;
}
public static void postSendPacket(Packet<?> packetIn) {
for (Module module : ENABLED_MODULES) {
module.postSendPacket(packetIn);
}
}
}
| true |
6556aca3e1821c4ec1f20b9ca834b3415e855f4b | Java | db117/example | /leetcode/src/main/java/com/db117/example/leetcode/solution1/Solution130.java | UTF-8 | 4,075 | 3.53125 | 4 | [
"Apache-2.0"
] | permissive | package com.db117.example.leetcode.solution1;
import java.util.Arrays;
/**
* 130. 被围绕的区域
* 给定一个二维的矩阵,包含 'X' 和 'O'(字母 O)。
* <p>
* 找到所有被 'X' 围绕的区域,并将这些区域里所有的 'O' 用 'X' 填充。
* <p>
* 示例:
* <p>
* X X X X
* X O O X
* X X O X
* X O X X
* 运行你的函数后,矩阵变为:
* <p>
* X X X X
* X X X X
* X X X X
* X O X X
* 解释:
* <p>
* 被围绕的区间不会存在于边界上,换句话说,任何边界上的 'O' 都不会被填充为 'X'。 任何不在边界上,或不与边界上的 'O' 相连的 'O' 最终都会被填充为 'X'。如果两个元素在水平或垂直方向相邻,则称它们是“相连”的。
* <p>
* 来源:力扣(LeetCode)
* 链接:https://leetcode-cn.com/problems/surrounded-regions
* 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*
* @author db117
* @date 2019/9/23/023 16:46
*/
public class Solution130 {
public static void main(String[] args) {
char[][] board = new char[][]{
{'X', 'O', 'X', 'X'},
{'O', 'X', 'O', 'X'},
{'X', 'O', 'X', 'O'},
{'O', 'X', 'O', 'X'},
{'X', 'O', 'X', 'O'},
{'O', 'X', 'O', 'X'}
};
new Solution130().solve(board);
System.out.println(Arrays.deepToString(board));
}
int row, col;
// 并查集
public void solve(char[][] board) {
if (board == null || board.length == 0 || board[0].length == 0) {
return;
}
row = board.length;
col = board[0].length;
UnionFind find = new UnionFind(row * col + 1);
// 边界位置
int temp = row * col;
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
int node = node(i, j);
if (board[i][j] == 'O') {
if (i == 0 || j == 0 || i == row - 1 || j == col - 1) {
// 合并边界
find.union(temp, node);
} else {
// 合并上下左右
if (board[i - 1][j] == 'O') {
find.union(node, node(i - 1, j));
}
if (board[i + 1][j] == 'O') {
find.union(node, node(i + 1, j));
}
if (board[i][j - 1] == 'O') {
find.union(node, node(i, j - 1));
}
if (board[i][j + 1] == 'O') {
find.union(node, node(i, j + 1));
}
}
}
}
}
// 充填
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
if (find.find(temp) != find.find(node(i, j))) {
// 不是边界
board[i][j] = 'X';
}
}
}
}
int node(int i, int j) {
return i * col + j;
}
class UnionFind {
int[] parents;
public UnionFind(int n) {
parents = new int[n];
for (int i = 0; i < n; i++) {
parents[i] = i;
}
}
public int find(int node) {
while (node != parents[node]) {
// 当当前的上级不是自己是,把当前的上级指向上级的上级
parents[node] = parents[parents[node]];
node = parents[node];
}
// 找到最上面的一级
return node;
}
public void union(int left, int right) {
int x = find(left);
int y = find(right);
if (x != y) {
// 当这两个的上级不是同一个是,指定为同一个
parents[x] = y;
}
}
}
}
| true |
d8fb7e29a08819bd162080eedeabaa4914454806 | Java | kristinagerdt/CheatSheet | /src/time/DiffParseFormat.java | UTF-8 | 3,347 | 3.015625 | 3 | [] | no_license | package time;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
import java.util.Locale;
import java.util.stream.Collectors;
import static java.time.temporal.ChronoUnit.DAYS;
public class DiffParseFormat {
private static DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
public static void main(String[] args) {
List<LocalDateTime> dateTimeList = new LinkedList<>();
Collections.addAll(dateTimeList,
LocalDateTime.parse("2020-01-15T00:00:00"),
LocalDateTime.parse("2020-01-16T00:00:00"),
LocalDateTime.parse("2020-01-17T00:00:00"));
long between = diffMaxMin(dateTimeList);
System.out.println(between);
String source = "src/time/dates.txt";
System.out.println(diffMaxMin(source));
List<String> stringDates = new LinkedList<>();
Collections.addAll(stringDates,
"03 Jun 2018",
"05 Jul 2018",
"13 Sep 2018",
"04 Oct 2018");
List<String> newStringDates = changeFormat(stringDates);
newStringDates.forEach(System.out::println);
}
private static long diffMaxMin(List<LocalDateTime> dateTimeList) {
Collections.sort(dateTimeList);
LocalDateTime min = dateTimeList.get(0);
LocalDateTime max = dateTimeList.get(dateTimeList.size() - 1);
return Duration.between(min, max).toDays();
}
private static long diffMaxMin(String source) {
try (BufferedReader in = new BufferedReader(new FileReader(source))) {
List<LocalDate> dates = in
.lines()
.map(d -> parseDate(d).orElse(LocalDate.now()))
.sorted()
.collect(Collectors.toList());
LocalDate min = dates.get(0);
LocalDate max = dates.get(dates.size() - 1);
System.out.println(dates);
return DAYS.between(min, max);
} catch (IOException e) {
e.getStackTrace();
}
return 0L;
}
public static Optional<LocalDate> parseDate(String dateString) {
try {
return Optional.of(LocalDate.parse(dateString, formatter));
} catch (DateTimeParseException e) {
return Optional.empty();
}
}
private static List<String> changeFormat(List<String> stringDates) {
// https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEE, dd MMM yyyy", new Locale("ru"));
//formatter.format(TemporalAccessor temporal)
return stringDates
.stream()
.map(d -> LocalDate.parse(d, DateTimeFormatter.ofPattern("dd MMM yyyy", Locale.ENGLISH)))
.sorted()
.map(formatter::format)
.collect(Collectors.toList());
}
} | true |
5005ee923eda301d404d92dad473148f9638a3e9 | Java | micrometer-metrics/micrometer | /micrometer-core/src/main/java/io/micrometer/core/instrument/binder/jms/JmsInstrumentation.java | UTF-8 | 3,084 | 2.484375 | 2 | [
"Apache-2.0"
] | permissive | /*
* Copyright 2023 VMware, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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 io.micrometer.core.instrument.binder.jms;
import io.micrometer.observation.ObservationRegistry;
import jakarta.jms.Session;
import java.lang.reflect.Proxy;
/**
* Instrument Jakarta JMS {@link Session sessions} for observability.
* <p>
* This instrumentation {@link Proxy proxies} JMS sessions to intercept various calls and
* create dedicated observations:
* <ul>
* <li>{@code send*} method calls on {@link jakarta.jms.MessageProducer} will create
* {@link JmsObservationDocumentation#JMS_MESSAGE_PUBLISH "jms.message.publish"}
* observations.
* <li>When configuring a {@link jakarta.jms.MessageListener} on
* {@link jakarta.jms.MessageConsumer} instances returned by the session,
* {@link JmsObservationDocumentation#JMS_MESSAGE_PROCESS "jms.message.process"}
* observations are created when messages are received by the callback.
* </ul>
* <p>
* Here is how an existing JMS Session instance can be instrumented for observability:
* <pre>
* Session original = ...
* ObservationRegistry registry = ...
* Session session = JmsInstrumentation.instrumentSession(original, registry);
*
* Topic topic = session.createTopic("micrometer.test.topic");
* MessageProducer producer = session.createProducer(topic);
* // this operation will create a "jms.message.publish" observation
* producer.send(session.createMessage("test message content"));
*
* MessageConsumer consumer = session.createConsumer(topic);
* // when a message is processed by the listener,
* // a "jms.message.process" observation is created
* consumer.setMessageListener(message -> consumeMessage(message));
* </pre>
*
* @author Brian Clozel
* @since 1.12.0
* @see JmsObservationDocumentation
*/
public abstract class JmsInstrumentation {
private JmsInstrumentation() {
}
/**
* Instrument the {@link Session} given as argument for observability and records
* observations using the provided Observation registry.
* @param session the target session to proxy for instrumentation.
* @param registry the Observation registry to use
* @return the instrumented session that should be used to record observations.
*/
public static Session instrumentSession(Session session, ObservationRegistry registry) {
SessionInvocationHandler handler = new SessionInvocationHandler(session, registry);
return (Session) Proxy.newProxyInstance(session.getClass().getClassLoader(), new Class[] { Session.class },
handler);
}
}
| true |
ed4ea44dd29df5dd9f49f667d302c76bc94088b3 | Java | jamestweeddale/weather | /station/src/main/java/station/io/GpioServiceImpl.java | UTF-8 | 1,939 | 2.40625 | 2 | [] | no_license | package station.io;
import com.pi4j.gpio.extension.base.AdcGpioProvider;
import com.pi4j.gpio.extension.mcp.MCP3008GpioProvider;
import com.pi4j.io.gpio.*;
import com.pi4j.io.spi.SpiChannel;
import com.pi4j.io.spi.SpiDevice;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.IOException;
@Service
public class GpioServiceImpl implements GpioService {
private static final Logger logger = LoggerFactory.getLogger(GpioServiceImpl.class);
private GpioController gpio;
private AdcGpioProvider analogToDigitalProvider;
@Autowired
public GpioServiceImpl() throws IOException {
gpio = GpioFactory.getInstance();
gpio.setShutdownOptions(true, PinState.LOW);
analogToDigitalProvider = new MCP3008GpioProvider(SpiChannel.CS0,
SpiDevice.DEFAULT_SPI_SPEED,
SpiDevice.DEFAULT_SPI_MODE,
false);
logger.info("Started PI GPIO service...");
}
@Override
public void writePinState(Pin pin, PinState pinState) {
GpioPinDigitalOutput pinObj = gpio.provisionDigitalOutputPin(pin, PinState.HIGH);
pinObj.setState(pinState);
}
@Override
public PinState readPinState(Pin pin) {
return null;
}
@Override
public double readAnalogValue(Pin pin) {
double returnVal;
GpioPinAnalogInput gpioPinAnalogInput = null;
try {
gpioPinAnalogInput = gpio.provisionAnalogInputPin(analogToDigitalProvider, pin);
returnVal = gpioPinAnalogInput.getValue();
} finally {
try {
gpio.unprovisionPin(gpioPinAnalogInput);
} catch (Exception e) {
logger.error("Exception occurred unprovisioning analog pin", e);
}
}
return returnVal;
}
}
| true |
3dd7a473daf9fe5d4d65e9a87d6e17e7e3466d21 | Java | HubertYoung/AcFun | /acfun5_7/src/main/java/com/xiaomi/mipush/sdk/FCMPushHelper.java | UTF-8 | 1,592 | 1.742188 | 2 | [] | no_license | package com.xiaomi.mipush.sdk;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import com.huawei.hms.support.api.push.PushReceiver.BOUND_KEY;
import java.util.Map;
public class FCMPushHelper {
public static void clearToken(Context context) {
i.a(context, f.ASSEMBLE_PUSH_FCM);
}
public static void convertMessage(Intent intent) {
i.a(intent);
}
public static boolean isFCMSwitchOpen(Context context) {
return i.b(context, f.ASSEMBLE_PUSH_FCM) && MiPushClient.getOpenFCMPush();
}
public static void notifyFCMNotificationCome(Context context, Map<String, String> map) {
String str = (String) map.get(BOUND_KEY.pushMsgKey);
if (!TextUtils.isEmpty(str)) {
PushMessageReceiver b = i.b(context);
if (b != null) {
b.onReceiveMessage(context, i.a(str));
}
}
}
public static void notifyFCMPassThoughMessageCome(Context context, Map<String, String> map) {
String str = (String) map.get(BOUND_KEY.pushMsgKey);
if (!TextUtils.isEmpty(str)) {
PushMessageReceiver b = i.b(context);
if (b != null) {
b.onReceivePassThroughMessage(context, i.a(str));
}
}
}
public static void reportFCMMessageDelete() {
MiTinyDataClient.upload(i.b(f.ASSEMBLE_PUSH_FCM), "fcm", 1, "some fcm messages was deleted ");
}
public static void uploadToken(Context context, String str) {
i.a(context, f.ASSEMBLE_PUSH_FCM, str);
}
}
| true |
65bc1aa21e85fbbd502036eac530a6550d3818f4 | Java | fabiano-cortez-souza/testeDeConceitoJC | /teste-conceito-agenda-cliente/src/main/java/br/com/fcs/agendacliente/business/AgendaClienteBusiness.java | UTF-8 | 12,931 | 1.976563 | 2 | [] | no_license |
package br.com.fcs.agendacliente.business;
import java.time.LocalTime;
import java.time.format.DateTimeParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import br.com.fcs.agendacliente.constants.Constants;
import br.com.fcs.agendacliente.dto.AgendaClienteSolicitationDTO;
import br.com.fcs.agendacliente.enums.ErrorType;
import br.com.fcs.agendacliente.enums.SuccessMessage;
import br.com.fcs.agendacliente.model.AgendaClienteModel;
import br.com.fcs.agendacliente.response.AgendaClienteApiResponse;
import br.com.fcs.agendacliente.service.AgendaClienteService;
import br.com.fcs.agendacliente.utils.DateUtils;
import br.com.fcs.agendacliente.utils.Utils;
import br.com.fcs.agendacliente.vo.AgendaClienteVO;
@Service
public class AgendaClienteBusiness {
@Autowired
AgendaClienteService agendaClienteService;
private List<AgendaClienteModel> agendaClienteModels;
private boolean jUnitTest = false;
@Value("${apigee.credentials.bffkey}")
private String apigeeCredentialsBffkey;
//private OneAgentSDK oneAgentSdk = OneAgentSDKFactory.createInstance();
@SuppressWarnings("unused")
private static final Logger LOGGER = LoggerFactory.getLogger(AgendaClienteBusiness.class);
public AgendaClienteApiResponse saveAgendaCliente(AgendaClienteModel agendaClienteModel, String bffKey) {
if(StringUtils.isBlank(bffKey) ) {
return new AgendaClienteApiResponse(ErrorType.FIELD_VALIDATION_BFFKEY_INVALID, HttpStatus.ACCEPTED.value());
}
if(!bffKey.equals(apigeeCredentialsBffkey)) {
return new AgendaClienteApiResponse(ErrorType.FIELD_VALIDATION_BFFKEY_INVALID, HttpStatus.ACCEPTED.value());
}
//getDynatraceApigeeCredentialsBffkey();
AgendaClienteApiResponse api = fieldValidationSave(agendaClienteModel);
if (api == null) {
if (agendaClienteService.save(agendaClienteModel)){
api = new AgendaClienteApiResponse(SuccessMessage.TRANSACTION_SUCCESS, HttpStatus.OK.value());
}else {
api = new AgendaClienteApiResponse(ErrorType.HTTP_RESPONSE_TRANSACTION_HISTORY_DENIED, HttpStatus.ACCEPTED.value());
}
}
return api;
}
public AgendaClienteApiResponse fieldValidationSave(AgendaClienteModel agendaCliente) {
if( StringUtils.isBlank(agendaCliente.getAgendaDataHora())
|| StringUtils.isBlank(agendaCliente.getCriacaoaAgendaDataHora())
|| StringUtils.isBlank(agendaCliente.getDescricaoFalha())
|| StringUtils.isBlank(agendaCliente.getModeloCelular())
|| StringUtils.isBlank(agendaCliente.getIdAgenda().toString())
|| StringUtils.isBlank(agendaCliente.getCpf())
|| StringUtils.isBlank(agendaCliente.getEndereco())
|| StringUtils.isBlank(agendaCliente.getNome())) {
return new AgendaClienteApiResponse(ErrorType.FIELD_VALIDATION_REQUIRED_FIELD_NOT_FOUND, HttpStatus.ACCEPTED.value());
}
if(Utils.invalidTimestampFormat(agendaCliente.getAgendaDataHora())) {
return new AgendaClienteApiResponse(ErrorType.FIELD_VALIDATION_TIMESTAMP_INVALID, HttpStatus.ACCEPTED.value());
}
/*
if (!Utils.hasOnlyNumbers(agendaCliente.getMsisdn()) ||
agendaCliente.getMsisdn().length() != Constants.MSISDN_LENGTH) {
return new AgendaClienteApiResponse(ErrorType.FIELD_VALIDATION_MSISDN_INVALID, HttpStatus.ACCEPTED.value());
}
if(!Utils.hasOnlyNumbers(agendaCliente.getAmount()) ||
Utils.fieldOutOfRange(agendaCliente.getAmount())) {
return new AgendaClienteApiResponse(ErrorType.FIELD_VALIDATION_AMOUNT_INVALID, HttpStatus.ACCEPTED.value());
}
if(agendaCliente.getType().length() > 20) {
return new AgendaClienteApiResponse(ErrorType.FIELD_VALIDATION_TYPE_INVALID, HttpStatus.ACCEPTED.value());
}
if(agendaCliente.getTransactionID().length() > Constants.DEFAULT_TRANSACTION_ID_LENGTH) {
return new AgendaClienteApiResponse(ErrorType.FIELD_VALIDATION_TRANSACTIONID_INVALID, HttpStatus.ACCEPTED.value());
}
if (!Utils.hasOnlyNumbers(agendaCliente.getTransactionID())) {
return new AgendaClienteApiResponse(ErrorType.FIELD_VALIDATION_TRANSACTIONID_INVALID, HttpStatus.ACCEPTED.value());
}
if(StringUtils.isBlank(agendaCliente.getDescription())) {
return new AgendaClienteApiResponse(ErrorType.FIELD_VALIDATION_DESCRIPTION_INVALID, HttpStatus.ACCEPTED.value());
}
if(agendaCliente.getDescription().length() > 50) {
return new AgendaClienteApiResponse(ErrorType.FIELD_VALIDATION_DESCRIPTION_INVALID, HttpStatus.ACCEPTED.value());
}
/**/
agendaCliente.setIdAgenda(agendaCliente.getIdAgenda());
String eventExist = agendaClienteService.eventExists(agendaCliente.getIdAgenda());
if(eventExist.equals("S")) {
return new AgendaClienteApiResponse(ErrorType.DOCUMENT_ALREADY_EXISTS, HttpStatus.ACCEPTED.value());
}
if(eventExist.equals("ERRO")) {
return new AgendaClienteApiResponse(ErrorType.HTTP_RESPONSE_TRANSACTION_HISTORY_DENIED, HttpStatus.ACCEPTED.value());
}
return null;
}
public AgendaClienteApiResponse findAgendaClienteDocuments(AgendaClienteSolicitationDTO agendaClienteSolicitation, String bffKey) {
if(!jUnitTest) {
agendaClienteModels = new ArrayList<>();
}
List<AgendaClienteModel> listaByAgendaCliente = new ArrayList<>();
if(StringUtils.isBlank(bffKey) ) {
return new AgendaClienteApiResponse(ErrorType.FIELD_VALIDATION_BFFKEY_INVALID, HttpStatus.ACCEPTED.value());
}
if(!bffKey.equals(apigeeCredentialsBffkey)) {
return new AgendaClienteApiResponse(ErrorType.FIELD_VALIDATION_BFFKEY_INVALID, HttpStatus.ACCEPTED.value());
}
//getDynatraceApigeeCredentialsBffkey();
AgendaClienteApiResponse apiResponse = fieldValidationFind(agendaClienteSolicitation);
List<AgendaClienteVO> listTransactionHistoryVO = new ArrayList<>();
int numPage = 0;
if(agendaClienteSolicitation.getNumPage() != null && !agendaClienteSolicitation.getNumPage().equals("")) {
numPage = Integer.parseInt(agendaClienteSolicitation.getNumPage());
}
if(apiResponse == null) {
if(!jUnitTest) {
listaByAgendaCliente = agendaClienteService.findAgendaByidAgenda(agendaClienteSolicitation.getIdAgenda());
}
adicionaAgendaClienteModels(agendaClienteSolicitation, listaByAgendaCliente);
long totalOfDocuments = agendaClienteModels.size();
int totalPages = Utils.calculateTotalOfPages(totalOfDocuments, Integer.parseInt(agendaClienteSolicitation.getNumRecord()));
if(totalPages == 0) {
totalPages = 1;
}
inserirListaAgendaClienteVO(listTransactionHistoryVO);
apiResponse = new AgendaClienteApiResponse(SuccessMessage.TRANSACTION_SEARCH_SUCCESS,
agendaClienteSolicitation.getCpf(),
numPage,
totalPages,
totalOfDocuments,
HttpStatus.OK.value(),
listTransactionHistoryVO);
}
return apiResponse;
}
private void adicionaAgendaClienteModels(AgendaClienteSolicitationDTO transactionHistorySolicitation,
List<AgendaClienteModel> listaByMsisdn) {
for (AgendaClienteModel transactionHistoryModel : listaByMsisdn) {
DateTime timestampDate = DateTime.parse(transactionHistoryModel.getAgendaDataHora());
DateTime strDate = DateTime.parse(transactionHistorySolicitation.getStartDate()+ "T" + LocalTime.of(0, 0, 0));
DateTime endDate = DateTime.parse(transactionHistorySolicitation.getEndDate()+ "T" + LocalTime.of(23, 59, 59));
if (agendaClienteModels.size() <= Integer.parseInt(transactionHistorySolicitation.getNumRecord()) &&
((timestampDate.isAfter(strDate) && timestampDate.isBefore(endDate)) ||
timestampDate.isEqual(strDate) || timestampDate.isEqual(endDate))) {
agendaClienteModels.add(transactionHistoryModel);
}
}
}
private void inserirListaAgendaClienteVO(List<AgendaClienteVO> listAgendaClienteVO) {
if(!agendaClienteModels.isEmpty()) {
for (AgendaClienteModel agendaClienteModel : agendaClienteModels) {
AgendaClienteVO agendaClienteVO = new AgendaClienteVO();
agendaClienteVO.setCpf(agendaClienteModel.getCpf());
agendaClienteVO.setEndereco(agendaClienteModel.getEndereco());
agendaClienteVO.setIdCliente(agendaClienteModel.getIdCliente());
agendaClienteVO.setNome(agendaClienteModel.getNome());
listAgendaClienteVO.add(agendaClienteVO);
}
}
}
public AgendaClienteApiResponse fieldValidationFind(AgendaClienteSolicitationDTO agendaClienteSolicitation) {
if(StringUtils.isBlank(agendaClienteSolicitation.getStartDate()) ||
StringUtils.isBlank(agendaClienteSolicitation.getCpf()) ||
StringUtils.isBlank(agendaClienteSolicitation.getEndDate()) ||
StringUtils.isBlank(agendaClienteSolicitation.getNumRecord())) {
return new AgendaClienteApiResponse (ErrorType.FIELD_VALIDATION_REQUIRED_FIELD_NOT_FOUND, HttpStatus.ACCEPTED.value());
}
if(invalidDateFormat(agendaClienteSolicitation.getStartDate()) ||
invalidDateFormat(agendaClienteSolicitation.getEndDate())) {
return new AgendaClienteApiResponse(ErrorType.FIELD_VALIDATION_DATE_INVALID, HttpStatus.ACCEPTED.value());
}
/*
if (!Utils.hasOnlyNumbers(agendaClienteSolicitation.getMsisdn()) ||
agendaClienteSolicitation.getMsisdn().length() != Constants.MSISDN_LENGTH) {
return new AgendaClienteApiResponse(ErrorType.FIELD_VALIDATION_MSISDN_INVALID, HttpStatus.ACCEPTED.value());
}
/**/
if(!Utils.hasOnlyNumbers(agendaClienteSolicitation.getNumRecord()) ||
Integer.parseInt(agendaClienteSolicitation.getNumRecord()) < 1 ||
Integer.parseInt(agendaClienteSolicitation.getNumRecord()) > 100) {
return new AgendaClienteApiResponse(ErrorType.FIELD_VALIDATION_NUMRECORDS_INVALID, HttpStatus.ACCEPTED.value());
}
if(!StringUtils.isBlank(agendaClienteSolicitation.getNumPage()) &&
!Utils.hasOnlyNumbers(agendaClienteSolicitation.getNumPage())) {
return new AgendaClienteApiResponse(ErrorType.FIELD_VALIDATION_NUMPAGE_INVALID, HttpStatus.ACCEPTED.value());
}
return null;
}
private boolean invalidDateFormat(String startDate) {
try {
DateUtils.dateValidation(startDate);
return false;
} catch (DateTimeParseException dateTimeParseException) {
return true;
}
}
//private void getDynatraceApigeeCredentialsBffkey() {
//oneAgentSdk.addCustomRequestAttribute("agenda-cliente-apigeeCredentialsBffkey", apigeeCredentialsBffkey);
//}
public void setTransactionHistoryService(AgendaClienteService agendaClienteService) {
this.agendaClienteService = agendaClienteService;
}
public void setTransactionHistoryModels(List<AgendaClienteModel> transactionHistoryModels) {
this.agendaClienteModels = transactionHistoryModels;
}
public void setjUnitTest(boolean jUnitTest) {
this.jUnitTest = jUnitTest;
}
public String getApigeeCredentialsBffkey() {
return apigeeCredentialsBffkey;
}
public void setApigeeCredentialsBffkey(String apigeeCredentialsBffkey) {
this.apigeeCredentialsBffkey = apigeeCredentialsBffkey;
}
}
| true |
b0f8fdb025ad6e9ff580470f76d1afb6b980edb0 | Java | ArpNetworking/metrics-aggregator-daemon | /src/main/java/com/arpnetworking/metrics/proxy/models/protocol/v1/HeartbeatMessagesProcessor.java | UTF-8 | 2,604 | 1.921875 | 2 | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | /*
* Copyright 2014 Groupon.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.arpnetworking.metrics.proxy.models.protocol.v1;
import com.arpnetworking.commons.jackson.databind.ObjectMapperFactory;
import com.arpnetworking.metrics.incubator.PeriodicMetrics;
import com.arpnetworking.metrics.proxy.actors.Connection;
import com.arpnetworking.metrics.proxy.models.messages.Command;
import com.arpnetworking.metrics.proxy.models.protocol.MessagesProcessor;
import com.fasterxml.jackson.databind.node.ObjectNode;
/**
* Processes heartbeat messages.
*
* @author Brandon Arp (brandon dot arp at inscopemetrics dot io)
*/
public class HeartbeatMessagesProcessor implements MessagesProcessor {
/**
* Public constructor.
*
* @param connection ConnectionContext where processing takes place
* @param metrics {@link PeriodicMetrics} instance to record metrics to
*/
public HeartbeatMessagesProcessor(final Connection connection, final PeriodicMetrics metrics) {
_connection = connection;
_metrics = metrics;
}
@Override
public boolean handleMessage(final Object message) {
if (message instanceof Command) {
//TODO(barp): Map with a POJO mapper [MAI-184]
final Command command = (Command) message;
final ObjectNode commandNode = (ObjectNode) command.getCommand();
final String commandString = commandNode.get("command").asText();
if (COMMAND_HEARTBEAT.equals(commandString)) {
_metrics.recordCounter(HEARTBEAT_COUNTER, 1);
_connection.send(OK_RESPONSE);
return true;
}
}
return false;
}
private PeriodicMetrics _metrics;
private final Connection _connection;
private static final String COMMAND_HEARTBEAT = "heartbeat";
private static final ObjectNode OK_RESPONSE =
ObjectMapperFactory.getInstance().getNodeFactory().objectNode().put("response", "ok");
private static final String HEARTBEAT_COUNTER = "actors/connection/command/heartbeat";
}
| true |
6091843d09b7ab6b7de385c9f78d22776f514d00 | Java | JetBrains/intellij-community | /java/java-impl-inspections/src/com/intellij/codeInspection/MeaninglessRecordAnnotationInspection.java | UTF-8 | 3,839 | 1.914063 | 2 | [
"Apache-2.0"
] | permissive | // Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.codeInspection;
import com.intellij.codeInsight.AnnotationTargetUtil;
import com.intellij.codeInsight.daemon.impl.analysis.HighlightingFeature;
import com.intellij.codeInsight.daemon.impl.quickfix.DeleteElementFix;
import com.intellij.java.JavaBundle;
import com.intellij.psi.*;
import com.intellij.psi.PsiAnnotation.TargetType;
import com.intellij.psi.util.JavaPsiRecordUtil;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
import java.util.EnumSet;
import java.util.Set;
public class MeaninglessRecordAnnotationInspection extends AbstractBaseJavaLocalInspectionTool {
private static final Set<TargetType> RECORD_TARGETS =
EnumSet.of(TargetType.RECORD_COMPONENT, TargetType.FIELD, TargetType.METHOD,
TargetType.PARAMETER, TargetType.TYPE_USE);
private static final Set<TargetType> ALWAYS_USEFUL_RECORD_TARGETS =
EnumSet.of(TargetType.RECORD_COMPONENT, TargetType.FIELD, TargetType.TYPE_USE);
@Override
public @NotNull PsiElementVisitor buildVisitor(@NotNull ProblemsHolder holder, boolean isOnTheFly) {
if (!HighlightingFeature.RECORDS.isAvailable(holder.getFile())) {
return PsiElementVisitor.EMPTY_VISITOR;
}
return new JavaElementVisitor() {
@Override
public void visitRecordComponent(@NotNull PsiRecordComponent recordComponent) {
PsiClass recordClass = recordComponent.getContainingClass();
if (recordClass == null) return;
String name = recordComponent.getName();
for (PsiAnnotation annotation : recordComponent.getAnnotations()) {
processAnnotation(recordClass, name, annotation);
}
}
private void processAnnotation(PsiClass recordClass, String name, PsiAnnotation annotation) {
PsiClass annotationType = annotation.resolveAnnotationType();
if (annotationType == null) return;
Set<TargetType> targets = AnnotationTargetUtil.getAnnotationTargets(annotationType);
if (targets == null || targets.isEmpty()) return;
targets = EnumSet.copyOf(targets);
targets.retainAll(RECORD_TARGETS);
if (targets.isEmpty() || ContainerUtil.exists(ALWAYS_USEFUL_RECORD_TARGETS, targets::contains)) return;
boolean hasAccessor = false;
boolean hasCanonicalConstructor = false;
if (targets.contains(TargetType.METHOD)) {
for (PsiMethod method : recordClass.findMethodsByName(name, false)) {
if (method.getParameterList().isEmpty() && method.isPhysical()) {
hasAccessor = true;
targets.remove(TargetType.METHOD);
break;
}
}
}
if (targets.contains(TargetType.PARAMETER)) {
PsiMethod constructor = JavaPsiRecordUtil.findCanonicalConstructor(recordClass);
if (constructor != null && JavaPsiRecordUtil.isExplicitCanonicalConstructor(constructor)) {
hasCanonicalConstructor = true;
targets.remove(TargetType.PARAMETER);
}
}
if (!targets.isEmpty()) return;
String message;
if (hasAccessor && hasCanonicalConstructor) {
message = JavaBundle.message("inspection.meaningless.record.annotation.message.method.and.parameter");
}
else if (hasAccessor) {
message = JavaBundle.message("inspection.meaningless.record.annotation.message.method");
}
else if (hasCanonicalConstructor) {
message = JavaBundle.message("inspection.meaningless.record.annotation.message.parameter");
}
else return;
holder.problem(annotation, message).fix(new DeleteElementFix(annotation)).register();
}
};
}
}
| true |
0ed3d3040a84bdb806d48cdffc4b9f0c4fbfc03f | Java | rafaelhdr/tccsauron | /Barra/fusao_framework/sources/src/br/com/r4j/research/image/sequence/sfm/VLineMatcherWrapperImageGrabber.java | ISO-8859-1 | 3,100 | 2.34375 | 2 | [] | no_license | package br.com.r4j.research.image.sequence.sfm;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import JSci.maths.AbstractDoubleSquareMatrix;
import br.com.r4j.research.RigidBodyTranformation2D;
import br.com.r4j.research.image.sequence.ImageGrabber;
import br.com.r4j.research.image.sequence.featurematch.vline.Matcher;
import br.com.r4j.research.pose2destimation.Pose2DGrabber;
import br.com.r4j.research.vline.VLineMap;
import br.com.r4j.robosim.Pose2D;
/**
* Classe centralizadora dos dados, reponsvel por gerar as estimativas.
*
* Tambm a classe que coleta os dados. Para os dados assncronos,
* ela chamada por algum. Para os dados disponveis sempre, ela
* chama sincronamente.
*/
public class VLineMatcherWrapperImageGrabber implements ImageGrabber
{
private static Log log = LogFactory.getLog(VLineMatcherWrapperImageGrabber.class.getName());
private Matcher matchTest = null;
private Pose2DGrabber poseGrabber = null;
private long timeStampLastMeasures = 0;
private int [] arraCopyOut = null;
public VLineMatcherWrapperImageGrabber()
{
}
public void setMatcher(Matcher matcher)
{
this.matchTest = matcher;
}
public void setPose2DGrabber(Pose2DGrabber poseGrabber)
{
this.poseGrabber = poseGrabber;
}
public long getMeasuresTimestamp()
{
return timeStampLastMeasures;
}
public VLineMap getStateMap()
{
return matchTest.getStateMap();
}
public void imageReceived(int [] inData, int [] outData, int width, int height, long imageTimestamp)
{
if (arraCopyOut == null || arraCopyOut.length < inData.length)
{
arraCopyOut = new int[inData.length];
}
long start_t = System.currentTimeMillis();
RigidBodyTranformation2D cameraTrafo = new RigidBodyTranformation2D(poseGrabber.getPose(imageTimestamp));
Pose2D cameraMoveEstimate = poseGrabber.getMovement(imageTimestamp);
AbstractDoubleSquareMatrix cameraMoveCovar = poseGrabber.getMovementCovar(imageTimestamp);
AbstractDoubleSquareMatrix cameraPoseCovar = poseGrabber.getPoseCovar(imageTimestamp);
log.debug("robot pose: " + poseGrabber.getPose(imageTimestamp));
log.debug("robot move: " + poseGrabber.getMovement(imageTimestamp));
this.timeStampLastMeasures = imageTimestamp;
// Calcula as estimativas das linhas conhecidas para o movimento atual.
// Usa o erro total at agora para tentar repuperar linhas j processadas.
// matchTest.getMeasures().calculateEstimatedProjections(structurePoseEstimate);
// Calcula as novas medidas e extrai possveis novas linhas.
matchTest.update(inData, width, height, cameraTrafo, cameraPoseCovar, cameraMoveEstimate, cameraMoveCovar);//, outData);
log.debug("timeTaken: " + (System.currentTimeMillis() - start_t));
/*
{
boolean bSaved = ImageUtil.saveImageJPEG(ImageUtil.createBufferedImage(outData, width, height, BufferedImage.TYPE_INT_RGB), "out_" + imageTimestamp + ".jpg");
log.debug("bSaved out_" + imageTimestamp + ".jpg = " + bSaved);
}
log.debug("timeTaken after img saving ...: " + (System.currentTimeMillis() - start_t));
//*/
}
}
| true |
9b707cc2bcb62520b139ef8ba9372f45fd85caa0 | Java | Bilalesque/HogwartsExpress | /app/src/main/java/com/example/bilalsalman/hogwartsexpress/RouteObjForFireBase.java | UTF-8 | 1,917 | 2.171875 | 2 | [] | no_license | package com.example.bilalsalman.hogwartsexpress;
public class RouteObjForFireBase {
String start, stop1, stop2, stop3, stop4, stop5, trackId, dest, id;
public RouteObjForFireBase() {
}
public RouteObjForFireBase(String start, String stop1, String stop2, String stop3, String stop4, String stop5, String trackId, String dest, String id) {
this.start = start;
this.stop1 = stop1;
this.stop2 = stop2;
this.stop3 = stop3;
this.stop4 = stop4;
this.stop5 = stop5;
this.trackId = trackId;
this.dest = dest;
this.id = id;
}
public String getStart() {
return start;
}
public void setStart(String start) {
this.start = start;
}
public String getStop1() {
return stop1;
}
public void setStop1(String stop1) {
this.stop1 = stop1;
}
public String getStop2() {
return stop2;
}
public void setStop2(String stop2) {
this.stop2 = stop2;
}
public String getStop3() {
return stop3;
}
public void setStop3(String stop3) {
this.stop3 = stop3;
}
public String getStop4() {
return stop4;
}
public void setStop4(String stop4) {
this.stop4 = stop4;
}
public String getStop5() {
return stop5;
}
public void setStop5(String stop5) {
this.stop5 = stop5;
}
public String getTrackId() {
return trackId;
}
public void setTrackId(String trackId) {
this.trackId = trackId;
}
public String getDest() {
return dest;
}
public void setDest(String dest) {
this.dest = dest;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
} | true |
1ee868fdd8f131cf74d2728b355ab774a46b1aef | Java | RobbieAvans/ivh11a1b | /src/main/java/edu/avans/hartigehap/service/ManagerService.java | UTF-8 | 248 | 1.882813 | 2 | [] | no_license | package edu.avans.hartigehap.service;
import edu.avans.hartigehap.domain.Manager;
public interface ManagerService {
Manager findByEmail(String email);
Manager findBySessionID(String sessionID);
Manager save(Manager manager);
}
| true |
16a82e60ce9bf4198b038806e13d6e52c69a010e | Java | Rein4ldoAlv3s/ProjetoIntegrador3PeriodoCompleto | /src/java/dao/dao_tipoAcessorio.java | UTF-8 | 5,627 | 2.46875 | 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 dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import model.tipo_acessorio;
import util.Conexao;
/**
*
* @author joaov
*/
public class dao_tipoAcessorio {
private Connection conexao;
public dao_tipoAcessorio(){
conexao = Conexao.getConexao();
}
public void addTipoAcessorio(tipo_acessorio tipoAcessorio){
String sql2 = "SELECT id_tipo FROM tipo_acessorio ORDER BY id_tipo DESC LIMIT 1";
try {
PreparedStatement preparedStatement = conexao.prepareStatement(sql2);
ResultSet rs = preparedStatement.executeQuery();
if (rs.next()) {
int aux = rs.getInt("id_tipo");
aux++;
tipoAcessorio.setId_tipoacessorio(aux);
}
} catch (SQLException e) {
e.printStackTrace();
}
String sql = "insert into tipo_acessorio (id_tipo,descricao) values(?,?)";
try {
PreparedStatement preparedStatement = conexao.prepareStatement(sql);
preparedStatement.setInt(1,tipoAcessorio.getId_tipoacessorio());
preparedStatement.setString(2, tipoAcessorio.getDescricao());
preparedStatement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void deleteTipoAcessorio(int id){
String sql = "delete from tipo_acessorio where id_tipo=?";
try {
PreparedStatement preparedStatement = conexao.prepareStatement(sql);
preparedStatement.setInt(1, id);
preparedStatement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void deleteTipoAcessorioDescricao(String descricao){
String sql = "delete from tipo_acessorio where descricao=?";
try {
PreparedStatement preparedStatement = conexao.prepareStatement(sql);
preparedStatement.setString(1, descricao);
preparedStatement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void updateTipoAcessorio(tipo_acessorio tipo_acessorio){
String sql = "update tipo_acessorio set descricao=? where id_tipo=?";
try {
PreparedStatement preparedStatement = conexao.prepareStatement(sql);
preparedStatement.setString(1, tipo_acessorio.getDescricao());
preparedStatement.setInt(2, tipo_acessorio.getId_tipoacessorio());
preparedStatement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
public tipo_acessorio getAcessorioDescricao(String descricao){
tipo_acessorio tipo = new tipo_acessorio();
try {
String sql = "select * from tipo_acessorio where descricao=?";
PreparedStatement preparedStatement = conexao.prepareStatement(sql);
preparedStatement.setString(1, descricao);
ResultSet rs = preparedStatement.executeQuery();
if (rs.next()) {
tipo.setId_tipoacessorio(rs.getInt("id_tipo"));
tipo.setDescricao(rs.getString("descricao"));
}
} catch (SQLException e) {
e.printStackTrace();
}
return tipo;
}
public tipo_acessorio getTipoAcessorio(int id){
tipo_acessorio tipo = new tipo_acessorio();
try {
String sql = "select * from tipo_acessorio where id_tipo=?";
PreparedStatement preparedStatement = conexao.prepareStatement(sql);
preparedStatement.setInt(1, id);
ResultSet rs = preparedStatement.executeQuery();
if (rs.next()) {
tipo.setId_tipoacessorio(rs.getInt("id_tipo"));
tipo.setDescricao(rs.getString("descricao"));
}
} catch (SQLException e) {
e.printStackTrace();
}
return tipo;
}
public List<tipo_acessorio> getAllTipoAcessorio(){
List<tipo_acessorio> tipos = new ArrayList<tipo_acessorio>();
String sql = "select * from tipo_acessorio";
try {
Statement statement = conexao.createStatement();
ResultSet rs = statement.executeQuery(sql);
while (rs.next()) {
tipo_acessorio tipo = new tipo_acessorio();
tipo.setId_tipoacessorio(rs.getInt("id_tipo"));
tipo.setDescricao(rs.getString("descricao"));
tipos.add(tipo);
}
} catch (SQLException e) {
e.printStackTrace();
}
return tipos;
}
}
| true |
fa64e598a762c82c2aac323991f782135c80196e | Java | NychyporenkoM/DietGen | /app/src/main/java/antarit/dietgen/activities/BaseActivity.java | UTF-8 | 6,879 | 1.945313 | 2 | [] | no_license | package antarit.dietgen.activities;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.FrameLayout;
import antarit.dietgen.R;
public abstract class BaseActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
public enum SelectedItem {
Diets,
Users,
Products,
NotSelected
}
private static SelectedItem selectedItem;
public static void setSelectedItem(SelectedItem item) {
selectedItem = item;
}
public static void initializeSelectedItem() {
if(selectedItem == null)
selectedItem = SelectedItem.NotSelected;
}
private View mActivityContent;
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mDrawerToggle;
private FrameLayout mContainerView;
private NavigationView mNavigationView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initializeSelectedItem();
setContentView(R.layout.base_activity);
Toolbar toolbar = (Toolbar) findViewById(R.id.base_act_toolbar);
setSupportActionBar(toolbar);
if(getSupportActionBar()!=null)
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
setDrawerLayout((DrawerLayout) findViewById(R.id.base_act_drawer));
setDrawerToggle(new ActionBarDrawerToggle(this, getDrawerLayout(), R.string.drawer_open, R.string.drawer_close));
getDrawerLayout().addDrawerListener(getDrawerToggle());
setContainerView((FrameLayout) findViewById(R.id.base_act_view_container));
setNavigationView((NavigationView) findViewById(R.id.base_act_navigation));
customizeNavigationView();
getNavigationView().setNavigationItemSelectedListener(this);
}
@Override
public boolean onNavigationItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.nav_diets:
navigate(item, SelectedItem.Diets, new DietsActivity());
break;
case R.id.nav_products:
navigate(item, SelectedItem.Products, new FoodProductsActivity());
break;
case R.id.nav_users:
navigate(item, SelectedItem.Users, new UsersActivity());
break;
default:
getDrawerLayout().closeDrawers();
break;
}
return true;
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
getDrawerToggle().syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
getDrawerToggle().onConfigurationChanged(newConfig);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
return getDrawerToggle().onOptionsItemSelected(item) || super.onOptionsItemSelected(item);
}
public void setActivityContent(int resId) {
LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
mActivityContent = inflater.inflate(resId, getDrawerLayout(), false);
getContainerView().addView(mActivityContent);
}
public void setDrawerLayout(DrawerLayout mDrawerLayout) {
this.mDrawerLayout = mDrawerLayout;
}
public void setDrawerToggle(ActionBarDrawerToggle mDrawerToggle) {
this.mDrawerToggle = mDrawerToggle;
}
public void setContainerView(FrameLayout mContainerView) {
this.mContainerView = mContainerView;
}
public void setNavigationView(NavigationView mNavigationView) {
this.mNavigationView = mNavigationView;
}
public View getActivityContent() {
return mActivityContent;
}
public DrawerLayout getDrawerLayout() {
return mDrawerLayout;
}
public ActionBarDrawerToggle getDrawerToggle() {
return mDrawerToggle;
}
public FrameLayout getContainerView() {
return mContainerView;
}
public NavigationView getNavigationView() {
return mNavigationView;
}
public void navigate(MenuItem item, SelectedItem selectedItem, Activity activity) {
setSelectedItem(selectedItem);
item.setChecked(true);
getDrawerLayout().closeDrawers();
startActivity(new Intent(this, activity.getClass()));
}
public void processException (String exceptionMessage) {
Snackbar snackbar = Snackbar.make(getActivityContent(), exceptionMessage, Snackbar.LENGTH_LONG);
View snackBarView = snackbar.getView();
snackBarView.setBackgroundColor(ContextCompat.getColor(this, R.color.red));
snackbar.show();
}
public void customizeNavigationView() {
switch (selectedItem) {
case Diets:
getNavigationView().getMenu().findItem(R.id.nav_diets).setChecked(true);
break;
case Users:
getNavigationView().getMenu().findItem(R.id.nav_users).setChecked(true);
break;
case Products:
getNavigationView().getMenu().findItem(R.id.nav_products).setChecked(true);
break;
default:
break;
}
}
public void setIndicatorBounds(ExpandableListView expandableListView) {
DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
int widthPixels = displayMetrics.widthPixels;
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN_MR2)
expandableListView.setIndicatorBounds(widthPixels - GetPixelFromDensityIndependentPixels(50), widthPixels - GetPixelFromDensityIndependentPixels(10));
else
expandableListView.setIndicatorBoundsRelative(widthPixels - GetPixelFromDensityIndependentPixels(50), widthPixels - GetPixelFromDensityIndependentPixels(10));
}
public int GetPixelFromDensityIndependentPixels(float densityIndependentPixels) {
final float scale = getResources().getDisplayMetrics().density;
return (int) (densityIndependentPixels * scale + 0.5f);
}
} | true |
06db6b031265323db8f0960932940cda5ff0b4ef | Java | onap/archive-sdc-dcae-d-dt-be-main | /dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/translators/LogEventTranslator.java | UTF-8 | 1,681 | 1.835938 | 2 | [
"Apache-2.0"
] | permissive | /*-
* ============LICENSE_START=======================================================
* SDC
* ================================================================================
* Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* 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.
* ============LICENSE_END=========================================================
*/
package org.onap.sdc.dcae.rule.editor.translators;
import org.onap.sdc.dcae.composition.restmodels.ruleeditor.LogEventAction;
public class LogEventTranslator extends ActionTranslator<LogEventAction> {
private static LogEventTranslator logEventTranslator = new LogEventTranslator();
public static LogEventTranslator getInstance() {
return logEventTranslator;
}
private LogEventTranslator(){}
public Object translateToHpJson(LogEventAction action) {
return new LogEventTranslation(action);
}
private class LogEventTranslation extends ProcessorTranslation {
String title;
LogEventTranslation(LogEventAction action) {
clazz = "LogEvent";
title = action.logTitle();
}
}
}
| true |
a84010f58b853542eaf52ce646d97cbdc27519e8 | Java | is-alpha/CalorieM8 | /app/src/main/java/com/dingo/caloriem8/ExerciseSubmenuFragment.java | UTF-8 | 2,091 | 2.21875 | 2 | [] | no_license | package com.dingo.caloriem8;
import android.os.Bundle;
import androidx.cardview.widget.CardView;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
public class ExerciseSubmenuFragment extends Fragment implements View.OnClickListener{
private DatabaseReference dbRef;
private FirebaseAuth fAuth;
private CardView card_AddActivity;
private CardView card_ExerciseTracker;
private View exercisefragContainer;
public ExerciseSubmenuFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_exercise_submenu, container, false);
//base de datos
fAuth = FirebaseAuth.getInstance();
dbRef = FirebaseDatabase.getInstance().getReference();
card_AddActivity = (CardView) view.findViewById(R.id.card_AddActivity);
card_ExerciseTracker = (CardView) view.findViewById(R.id.card_ExerciseTracker);
exercisefragContainer = view.findViewById(R.id.main_fragment_container);
card_AddActivity.setOnClickListener(this);
card_ExerciseTracker.setOnClickListener(this);
return view;
}
@Override
public void onClick(View v) {
FragmentTransaction ft = getFragmentManager().beginTransaction();
if(v == card_AddActivity)
ft.replace(R.id.main_fragment_container, new ExerciseFragment());
else if(v == card_ExerciseTracker)
ft.replace(R.id.main_fragment_container, new ExerciseTrackerFragment());
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.addToBackStack(null);
ft.commit();
}
@Override
public void onStart() {
super.onStart();
}
} | true |
3eb8072b15b6e7d988e55e947568432ea996a473 | Java | davidarcila93/maratones | /Codeforces/src/GukizHatesBoxes.java | UTF-8 | 882 | 2.859375 | 3 | [] | no_license | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class GukizHatesBoxes {
static ArrayList<Integer> list, acum, remainder;
static int n,m;
public static boolean can(long k){
return true;
}
public static void main(String[] args)throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
n = Integer.parseInt(st.nextToken());
m = Integer.parseInt(st.nextToken());
st = new StringTokenizer(br.readLine());
list = new ArrayList<Integer>(n);
acum = new ArrayList<Integer>(n);
remainder = new ArrayList<Integer>(n);
long min, max, mid;
min=0; max=1000000000000000000L;
while(min<max){
mid=(min+max)/2L;
if(can(mid)){
min=mid;
}else{
max=mid-1;
}
}
}
}
| true |
52f978a3ebaefd50793d7576a8fc80a4605ddcbe | Java | zhouxu-z/data-structure | /src/com/xysfxy/collection/Queue.java | UTF-8 | 2,252 | 3.9375 | 4 | [] | no_license | package com.xysfxy.collection;
import java.util.Iterator;
/**
* @Auther: 周宝辉
* @Date: 2020/7/15 15:16
* @Description:队列的实现
*/
public class Queue<T> implements Iterable<T> {
private Node head;
private Node last;
private int N;
public Queue() {
this.head = new Node(null, null);
this.last = null;
this.N = 0;
}
public boolean isEampty() {
return N == 0;
}
public int size() {
return N;
}
/**
* 取出元素
*
* @return
*/
public T dequeue() {
if (!isEampty()) {
Node node = head.getNext();
head.setNext(node.getNext());
N--;
if(isEampty()){
last = null;
}
return (T) node.getItem();
}
return null;
}
/**
* 插入元素
*
* @param t
*/
public void enqueue(T t) {
if (last == null) {
last = new Node(t, null);
head.setNext(last);
} else {
Node node = new Node(t, null);
last.setNext(node);
last = node;
}
N++;
}
@Override
public Iterator<T> iterator() {
return new MyIterator();
}
private class MyIterator implements Iterator<T> {
private Node n;
public MyIterator() {
this.n = head;
}
@Override
public boolean hasNext() {
return n.getNext() != null;
}
@Override
public T next() {
n = n.getNext();
return (T) n.getItem();
}
}
public static void main(String[] args) {
Queue<Integer> queue = new Queue<>();
queue.enqueue(1);
queue.enqueue(2);
queue.enqueue(3);
queue.enqueue(4);
System.out.println("插入元素");
for (int i : queue) {
System.out.println(i);
}
queue.dequeue();
queue.dequeue();
queue.dequeue();
System.out.println("删除元素");
for (int i : queue) {
System.out.println(i);
}
System.out.println(queue.isEampty());
System.out.println(queue.size());
}
} | true |
5a53e668d7f314404e4b230355f2e737f9798d6a | Java | abstractionLevel/ReporektBackend | /src/main/java/com/example/ReportPlayer/repository/report/type/ReportTypeBrazilRepository.java | UTF-8 | 389 | 1.90625 | 2 | [] | no_license | package com.example.ReportPlayer.repository.report.type;
import com.example.ReportPlayer.enumerated.Server;
import com.example.ReportPlayer.models.report.type.ReportTypeBrazil;
import org.springframework.stereotype.Repository;
@Repository("report_type_repository_"+ Server.Region.BRAZIL)
public interface ReportTypeBrazilRepository extends ReportTypeBaseRepository<ReportTypeBrazil> {
}
| true |
34ed35b8df50febfdaef27e7ef589fbc2d8ca152 | Java | POO-UNALMED/taller-7-Maik1104 | /src/main/java/comunicacion/Alfabeto.java | UTF-8 | 873 | 3.15625 | 3 | [] | no_license | package comunicacion;
public class Alfabeto extends Pictograma{
public Alfabeto(String origen, String[] letras, String interpretacion) {
super(origen);
this.letras = letras;
this.interpretacion = interpretacion;
}
private String[] letras;
private String interpretacion;
public int cantidadLetras() {
return letras.length;
}
public String interpretacion() {
return interpretacion;
}
public String toString() {
String a = letras[0]+", ";
for (int i = 1; i<letras.length-1; i++) {
a = a + letras[i] + ", ";
}
return a+letras[letras.length-1];
}
public String[] getLetras() {
return letras;
}
public void setLetras(String[] letras) {
this.letras = letras;
}
public String getInterpretacion() {
return interpretacion;
}
public void setInterpretacion(String interpretacion) {
this.interpretacion = interpretacion;
}
}
| true |
73ca5745b60a60cc2f9997e72ea946f00c66d956 | Java | aksalj/PocketHub | /app/src/main/java/com/github/pockethub/accounts/AuthenticatedUserLoader.java | UTF-8 | 2,637 | 2.265625 | 2 | [
"Apache-2.0"
] | permissive | /*
* Copyright (c) 2015 PocketHub
*
* 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.github.pockethub.accounts;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AccountsException;
import android.app.Activity;
import android.content.Context;
import com.github.kevinsawicki.wishlist.AsyncLoader;
import com.google.inject.Inject;
import java.io.IOException;
import roboguice.RoboGuice;
import roboguice.inject.ContextScope;
/**
* Base loader class that ensures an authenticated account exists before
* {@link #load(Account)} is called
*
* @param <D>
*/
public abstract class AuthenticatedUserLoader<D> extends AsyncLoader<D> {
@Inject
private ContextScope contextScope;
@Inject
private AccountScope accountScope;
/**
* Activity using this loader
*/
@Inject
protected Activity activity;
/**
* Create loader for context
*
* @param context
*/
public AuthenticatedUserLoader(final Context context) {
super(context);
RoboGuice.injectMembers(context, this);
}
/**
* Get data to display when obtaining an account fails
*
* @return data
*/
protected abstract D getAccountFailureData();
@Override
public final D loadInBackground() {
final AccountManager manager = AccountManager.get(activity);
final Account account;
try {
account = AccountUtils.getAccount(manager, activity);
} catch (IOException e) {
return getAccountFailureData();
} catch (AccountsException e) {
return getAccountFailureData();
}
accountScope.enterWith(account, manager);
try {
contextScope.enter(getContext());
try {
return load(account);
} finally {
contextScope.exit(getContext());
}
} finally {
accountScope.exit();
}
}
/**
* Load data
*
* @param account
* @return data
*/
public abstract D load(Account account);
}
| true |
d219554c5af0dd28863f23b8d1e6848b2bdb6f97 | Java | wyw9611/LoanBook | /src/model/Member.java | GB18030 | 3,530 | 2.671875 | 3 | [] | no_license | package model;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class Member {
private String Id;
private String Name;
private ArrayList<Loan> Loans = new ArrayList<Loan>();
private List < ISpecification < Member > > specifications = new ArrayList <> ( );
public String getId() {
return Id;
}
public void setId(String id) {
Id = id;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public ArrayList<Loan> getLoans() {
return Loans;
}
public void setLoans(ArrayList<Loan> loans) {
Loans = loans;
}
public final void Return(Book book){
model.Loan loan = findCurrentLoanFor(book);
if(loan!=null){
loan.MarkAsReturned();
book.setLoanTo(null);
System.out.println("ɹ");
}
}
public final boolean CanLoan(Book book){
if(book.getLoanTo()!=null){
System.out.println("ѽʧܣ");
return false;
}else{
HasNotReachMaxSpecification hasReachMaxSpecification=new HasNotReachMaxSpecification();
if( !hasReachMaxSpecification.IsSatisfiedBy(this)){
return false;
}
LoanOnlyOneSpecification loanOnlyOneSpecification=new LoanOnlyOneSpecification(book);
return loanOnlyOneSpecification.IsSatisfiedBy(this);
}
// ISpecification<Member> hasNotReachMax=new model.HasNotReachMaxSpecification();
// ISpecification<Member> loanOnlyOne=new model.LoanOnlyOneSpecification(book);
// return hasNotReachMax.IsSatisfiedBy(this)&&loanOnlyOne.IsSatisfiedBy(this)&&book.getLoanTo()==null;
// return book.getLoanTo()==null&&validate();
}
public final Loan Loan(Book book){
Loan loan = new Loan();
if(CanLoan(book)){
loan.setBook(book);
loan.setMember(this);
this.getLoans().add(loan);
System.out.println("ɹ");
return loan;
}
System.out.println("ʧ");
return loan;
}
public Loan findCurrentLoanFor ( Book book ) {
System.out.println("id:"+book.getId()+"-ISBN:"+book.getISBN()+"-Titil:"+book.getTitle());
return getLoans ( ).stream ( )
.filter ( loan -> book.getId ( ).equals ( loan.getBook ( ).getId ( ) ) && loan.HasNotBeenReturned ( ) )
.collect ( Collectors.toList ( ) )
.get ( 0 );
// List < Loan > collect = getLoans ( ).stream ( )
//
// .filter ( loan -> book.getId ( ).equals ( loan.getBook ( ).getId ( ) ) && loan.HasNotBeenReturned ( ) )
//
// .collect ( Collectors.toList ( ) );
//
// if ( collect.size ( ) > 0 ) {
//
// return collect.get ( 0 );
//
// }
//
// return null;
}
// private boolean validate(){
// System.out.println("-----");
// boolean result = false;
// for(ISpecification<Member> spec:specifications){
// result = spec.IsSatisfiedBy(this);
// System.out.println("");
// if(!result)
// System.out.println("");
// return false;
// }
// return result;
//
// }
// public List < ISpecification < Member > > getSpecifications ( ) {
//
//
//
// return specifications;
//
// }
//
//
//
// public void setSpecifications ( List < ISpecification < Member > > specifications ) {
//
//
//
// this.specifications = specifications;
//
// }
}
| true |
2d250757733b8321e3b8b0a2733f8979986f044f | Java | egorshulga/HireThem | /src/main/java/com/github/hirethem/model/dao/exception/DaoException.java | UTF-8 | 379 | 1.992188 | 2 | [] | no_license | package com.github.hirethem.model.dao.exception;
import com.github.hirethem.exception.ProjectException;
/**
* Created by egors.
*/
public class DaoException extends ProjectException {
public DaoException(String message) {
super(message);
}
public DaoException(String message, Exception maskedException) {
super(message, maskedException);
}
}
| true |
7cd0bdb1f13b096376f9a0a50ddf1bf459e6281f | Java | r-c-s/Auth | /src/test/java/rcs/auth/testutils/InMemoryDataSourceTestBase.java | UTF-8 | 709 | 2.1875 | 2 | [] | no_license | package rcs.auth.testutils;
import org.junit.Before;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.jdbc.core.JdbcTemplate;
import javax.sql.DataSource;
public class InMemoryDataSourceTestBase {
protected JdbcTemplate template;
@Before
public final void setupTemplate() {
template = new JdbcTemplate(dataSource());
}
private DataSource dataSource() {
return DataSourceBuilder.create()
.username("username")
.password("password")
.driverClassName("org.h2.Driver")
.url("jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE")
.build();
}
}
| true |
5756e5b69d8958f3cab9ffe454f3bb57572c24b4 | Java | dpdaidai/litespting | /src/test/java/top/dpdaidai/mn/test/v4/ClassPathBeanDefinitionScannerTest.java | UTF-8 | 2,639 | 2.34375 | 2 | [] | no_license | package top.dpdaidai.mn.test.v4;
import org.junit.Assert;
import org.junit.Test;
import top.dpdaidai.mn.beans.factory.BeanDefinition;
import top.dpdaidai.mn.beans.factory.support.DefaultBeanFactory;
import top.dpdaidai.mn.context.annotation.ClassPathBeanDefinitionScanner;
import top.dpdaidai.mn.context.annotation.ScannedGenericBeanDefinition;
import top.dpdaidai.mn.core.annotation.AnnotationAttributes;
import top.dpdaidai.mn.core.type.AnnotationMetadata;
import top.dpdaidai.mn.stereotype.Component;
/**
*
* 测试类ClassPathBeanDefinitionScanner
* 该类用于根据包名 , 扫描包下含有Component注解的类 , 根据class文件 , 解析得到的 beanDefinition 相关信息并进行注册
*
* @Author chenpantao
* @Date 9/17/21 3:46 PM
* @Version 1.0
*/
public class ClassPathBeanDefinitionScannerTest {
@Test
public void testBeanDefinitionScanner() {
DefaultBeanFactory defaultBeanFactory = new DefaultBeanFactory();
String basePackage = "top.dpdaidai.mn.service.v4,top.dpdaidai.mn.service.daoV4";
ClassPathBeanDefinitionScanner classPathBeanDefinitionScanner = new ClassPathBeanDefinitionScanner(defaultBeanFactory);
classPathBeanDefinitionScanner.doScan(basePackage);
String componentAnnotation = Component.class.getName();
{
BeanDefinition bd = defaultBeanFactory.getBeanDefinition("petStore");
Assert.assertTrue(bd instanceof ScannedGenericBeanDefinition);
ScannedGenericBeanDefinition sbd = (ScannedGenericBeanDefinition)bd;
AnnotationMetadata amd = sbd.getMetadata();
Assert.assertTrue(amd.hasAnnotation(componentAnnotation));
AnnotationAttributes attributes = amd.getAnnotationAttributes(componentAnnotation);
Assert.assertEquals("petStore", attributes.get("value"));
}
{
BeanDefinition bd = defaultBeanFactory.getBeanDefinition("accountDao");
Assert.assertTrue(bd instanceof ScannedGenericBeanDefinition);
ScannedGenericBeanDefinition sbd = (ScannedGenericBeanDefinition)bd;
AnnotationMetadata amd = sbd.getMetadata();
Assert.assertTrue(amd.hasAnnotation(componentAnnotation));
}
{
BeanDefinition bd = defaultBeanFactory.getBeanDefinition("itemDao");
Assert.assertTrue(bd instanceof ScannedGenericBeanDefinition);
ScannedGenericBeanDefinition sbd = (ScannedGenericBeanDefinition)bd;
AnnotationMetadata amd = sbd.getMetadata();
Assert.assertTrue(amd.hasAnnotation(componentAnnotation));
}
}
}
| true |
d7c70d9ec9b6dd6626263a0672c99d90b8ecaf61 | Java | gunungloli666/web-analitik | /src/com/parsing/bilangan/CutLongString.java | UTF-8 | 582 | 3.09375 | 3 | [] | no_license | package com.parsing.bilangan;
public class CutLongString {
public static String CutString( String input , int maxlength , String newline){
String result = "";
StringBuilder builder = new StringBuilder();
String[] temp = input.split("\\s+");
int i = 0 , n = 0;
while( i < temp.length ){
int panjang = temp[i].length();
if( n + panjang < maxlength ){
n += panjang;
builder.append(temp[i]);
builder.append(" ");
i++;
}else{
builder.append( newline );
n = 0;
}
}
result= builder.toString();
return result;
}
}
| true |
539496d3d54b9af205cc949bad4db03520890c90 | Java | stiffme/LearnOpenGL | /src/main/java/org/esipeng/opengl/rumen/HelloWindow.java | UTF-8 | 1,148 | 2.5625 | 3 | [] | no_license | package org.esipeng.opengl.rumen;
import org.esipeng.opengl.base.OGLApplicationAbstract;
import org.esipeng.opengl.base.OGLApplicationGL33;
import static org.lwjgl.opengl.GL33.*;
import static org.lwjgl.glfw.GLFW.*;
import static org.lwjgl.system.MemoryUtil.NULL;
public class HelloWindow extends OGLApplicationGL33 {
int m_width = 800, m_height = 600;
@Override
protected boolean applicationCreateContext() {
long window = glfwCreateWindow(m_width,m_height, "LearnOpenGL", NULL, NULL);
if(window == NULL)
return false;
glfwMakeContextCurrent(window);
return true;
}
@Override
protected boolean applicationInitAfterContext() {
glViewport(0,0,m_width,m_height);
glClearColor(0.2f,0.3f,0.3f,1.0f);
return true;
}
@Override
protected void update(float elapsed) {
glClear(GL_COLOR_BUFFER_BIT);
}
@Override
protected void draw() {
}
public static void main(String[] args) {
OGLApplicationAbstract application = new HelloWindow();
application.enableFps(true);
application.run();
}
}
| true |
2c28662fea6a13a34b0db3a9ceb2f9fc107b36ba | Java | ryaninhust/FindHust | /src/java/com/stip/find/service/HusterService.java | UTF-8 | 1,712 | 2.25 | 2 | [] | no_license | /*
* To change this template, choose Tools | Templates and open the template in
* the editor.
*/
package com.stip.find.service;
import com.stip.find.da.FindDao;
import com.stip.find.entity.UserHub;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.EJB;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
/**
*
* @author BlueBerry
*/
@Stateless
@LocalBean
@Path("home")
public class HusterService {
// Add business logic below. (Right-click in editor and choose
// "Insert Code > Add Business Method")
@EJB
FindDao findDao;
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/husters")
public List<UserHub> findHusters(@QueryParam("name")String name){
if (name!=null) {
List<UserHub> userHubs=findDao.findHusterByName2(name);
if (!userHubs.isEmpty()) {
System.out.println(name);
return userHubs;
}
else{
throw new WebApplicationException(404);
}
}
throw new WebApplicationException(404);
}
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/huster/{uid}")
public List<UserHub> findHuster(@PathParam("uid") String uid){
List<UserHub> userHubs=new ArrayList<UserHub>();
if (uid!=null) {
UserHub userHub=findDao.findHusterByUID(uid);
if (userHub!=null) {
userHubs.add(userHub);
System.out.println(uid);
return userHubs;
}
throw new WebApplicationException(404);
}
throw new WebApplicationException(404);
}
}
| true |
d82e682edb881c09f5beaca3895be66497a5f4bb | Java | jayyei/Repositorio | /Java/Java-pildoras-youtube/src/vector_4.java | UTF-8 | 816 | 3.84375 | 4 | [] | no_license | import java.util.Scanner;
public class vector_4 {
public int[] vector;
Scanner entrada = new Scanner(System.in);
public void cargar() {
vector = new int[10];
for (int i = 0; i < vector.length; i++) {
vector[i] = entrada.nextInt();
}
}
public void ordenamiento(){
int dato = 0;
for (int j = 0 ; j < vector.length -1; j++){
if(vector[j]>vector[j+1]){
dato++;
}
}
if(dato!=0){
System.out.println("El arreglo no esta ordenado");
} else {
System.out.println("El arreglo esta ordenado correctamente");
}
}
public static void main (String args[]){
vector_4 vet = new vector_4();
vet.cargar();
vet.ordenamiento();
}
} | true |
932002508237ad880564d14c974b6f4d97cd313a | Java | Choonster-Minecraft-Mods/TestMod2 | /src/main/java/com/choonster/testmod2/creativetab/ItemSorter.java | UTF-8 | 1,869 | 2.9375 | 3 | [
"MIT",
"CC-BY-3.0"
] | permissive | package com.choonster.testmod2.creativetab;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraftforge.oredict.OreDictionary;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
public class ItemSorter implements Comparator<ItemStack> {
private final Map<ItemStack, OreDictionaryPriority> oreDictPriorityCache = new HashMap<>();
private OreDictionaryPriority getOreDictionaryPriority(ItemStack itemStack) {
OreDictionaryPriority priority = oreDictPriorityCache.get(itemStack);
if (priority != null) {
return priority;
}
priority = OreDictionaryPriority.NONE;
for (int oreID : OreDictionary.getOreIDs(itemStack)) {
String oreName = OreDictionary.getOreName(oreID);
if (oreName.startsWith("ore")) {
priority = OreDictionaryPriority.ORE;
break;
} else if (oreName.startsWith("ingot")) {
priority = OreDictionaryPriority.INGOT;
break;
} else if (oreName.startsWith("dust")) {
priority = OreDictionaryPriority.DUST;
break;
}
}
oreDictPriorityCache.put(itemStack, priority);
return priority;
}
@Override
public int compare(ItemStack stack1, ItemStack stack2) {
OreDictionaryPriority priority1 = getOreDictionaryPriority(stack1), priority2 = getOreDictionaryPriority(stack2);
if (priority1 == priority2) { // Both stacks have the same priority, order them by their ID/metadata
Item item1 = stack1.getItem();
Item item2 = stack2.getItem();
if (item1 == item2) { // If the stacks have the same item, order them by their metadata
return stack1.getMetadata() - stack2.getMetadata();
} else { // Else order them by their ID
return Item.getIdFromItem(item1) - Item.getIdFromItem(item2);
}
} else { // Stacks have different priorities, order them by priority instead
return priority1.compareTo(priority2);
}
}
}
| true |
5cbdaf7b99c116d29801197cf1609e6d79ce8ebc | Java | wasabiwithbun/KB | /MyKbs/plugin/org/javacoo/cowswing/plugin/core/service/dispose/CoreDisposeService.java | UTF-8 | 698 | 2.296875 | 2 | [] | no_license | /**
* 如石子一粒,仰高山之巍峨,但不自惭形秽.
* 若小草一棵,慕白杨之伟岸,却不妄自菲薄.
*/
package org.javacoo.cowswing.plugin.core.service.dispose;
import org.javacoo.cowswing.core.dispose.DisposeService;
import org.springframework.stereotype.Component;
/**
*
* <p>说明:</p>
* <li></li>
* @author DuanYong
* @since 2014-7-9 下午4:29:12
* @version 1.0
*/
@Component("coreDisposeService")
public class CoreDisposeService implements DisposeService{
/* (non-Javadoc)
* @see org.javacoo.cowswing.core.dispose.DisposeService#dispose()
*/
@Override
public void dispose() {
// TODO Auto-generated method stub
}
}
| true |
27ac7597745d478ecb94a79bb0b5df99ee916afb | Java | RenzhiJ/JDEletericity | /src/main/java/com/example/bwie/mydemo/callback/YueBinglistCallback.java | UTF-8 | 202 | 1.773438 | 2 | [] | no_license | package com.example.bwie.mydemo.callback;
import com.example.bwie.mydemo.bean.YueBingBean;
public interface YueBinglistCallback {
void success(YueBingBean body);
void failed(Exception e);
}
| true |
a81994ff0b4c188bfef716266a7f49be30b0ce31 | Java | hariKing12/Elibrary | /src/com/sample/project/elibrary/AddquantityDao.java | UTF-8 | 600 | 2.390625 | 2 | [] | no_license | package com.sample.project.elibrary;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class AddquantityDao {
public static int quantity(int number,String callno){
int status=0;
try{
Connection connection=jdbcUtil.getConnection();
PreparedStatement ps=connection.prepareStatement("update E_BOOK set quantity=? where callno=?");
ps.setInt(1, number);
ps.setString(2, callno);
status=ps.executeUpdate();
System.out.println(status);
}catch(SQLException e){
System.out.println(e.getMessage());
}
return status;
}
}
| true |
b1ff6f37b7035b8a33ebe5111310c29f84a24257 | Java | jakop52/Zadanie | /src/main/java/tests/AbstractTest.java | UTF-8 | 760 | 2.234375 | 2 | [] | no_license | package tests;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeSuite;
import java.util.concurrent.TimeUnit;
public class AbstractTest {
protected static WebDriver driver;
@BeforeSuite
public void setUpSuite() {
System.setProperty("webdriver.chrome.driver", "src/main/resources/drivers/chromedriver.exe");
driver = new ChromeDriver();
driver.manage().timeouts().pageLoadTimeout(40, TimeUnit.SECONDS);
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.get("https://google.com");
}
@AfterSuite
public void tearDownSuite() {
driver.quit();
}
}
| true |
7aa7462c5ce3960bac0650fe081a4c8518a49d9f | Java | MakerYan/Fragment_Framework | /app/src/main/java/com/makeryan/lib/widget/ImageHorizontalContainer.java | UTF-8 | 2,232 | 2.390625 | 2 | [] | no_license | package com.makeryan.lib.widget;
import android.content.Context;
import android.support.v7.widget.OrientationHelper;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.widget.ImageView;
import android.widget.LinearLayout;
import com.makeryan.lib.util.ImageUtil;
import com.zhy.autolayout.utils.AutoUtils;
import java.util.List;
/**
* Created by MakerYan on 16/9/21 18:47.
* Email : light.yan@qq.com
* Personal e-mail : light.yan@qq.com
* project name : ChengGua2
* package name : com.chenggua.cg.app.lib.view.widget
*/
public class ImageHorizontalContainer
extends LinearLayout {
protected LayoutInflater mInflater;
public ImageHorizontalContainer(Context context) {
super(context);
init(context);
}
public ImageHorizontalContainer(Context context, AttributeSet attrs) {
super(
context,
attrs
);
init(context);
}
public ImageHorizontalContainer(Context context, AttributeSet attrs, int defStyleAttr) {
super(
context,
attrs,
defStyleAttr
);
init(context);
}
/**
* 初始化
*
* @param context
*/
protected void init(Context context) {
setOrientation(OrientationHelper.HORIZONTAL);
mInflater = LayoutInflater.from(context);
}
/**
* 添加图片
*/
public void addImages(List<String> imgs) {
addImages(
imgs,
0
);
}
/**
* 添加图片
*
* @param imgs
* Url list
* @param imgSize
* 图片大小 比如 R.dimen.y38
*/
public void addImages(List<String> imgs, int imgSize) {
int size = imgSize == 0 ?
AutoUtils.getPercentWidthSize(38) :
imgSize;
removeAllViews();
Context context = getContext();
LayoutParams layoutParams = new LayoutParams(
getResources().getDimensionPixelSize(size),
getResources().getDimensionPixelSize(size)
);
layoutParams.rightMargin = AutoUtils.getPercentWidthSize(15);
layoutParams.weight = 1;
for (String url : imgs) {
CircleImageView circleImageView = new CircleImageView(context);
circleImageView.setLayoutParams(layoutParams);
circleImageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
ImageUtil.loadAsBitmap(
url,
circleImageView
);
addView(circleImageView);
}
requestLayout();
}
}
| true |
b8b7c601e4bf0b0b5e800483e06f132324641908 | Java | guoxuliang/yunshangzhihui_android | /app/src/main/java/yszhh/wlgj/com/yunshangzhihui_android/ui/fragment/Fragment3.java | UTF-8 | 1,074 | 1.859375 | 2 | [] | no_license | package yszhh.wlgj.com.yunshangzhihui_android.ui.fragment;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import yszhh.wlgj.com.yunshangzhihui_android.R;
public class Fragment3 extends Fragment implements OnItemClickListener {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View view = inflater.inflate(R.layout.fragment_line, null);
initViews(view);
return view;
}
private void initViews(View view) {
}
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// Info s = mInfo.get(arg2);
// TextView tvmessage = (TextView) arg1.findViewById(R.id.list_message_item);
}
}
| true |