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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
b2a9ceca031873dc923050188fb9028decd514a3
|
Java
|
roytuts/spring-in-memory-db
|
/spring-embedded-hsqldb/src/main/java/com/roytuts/spring/embedded/hsqldb/model/Customer.java
|
UTF-8
| 1,484
| 2.5625
| 3
|
[] |
no_license
|
package com.roytuts.spring.embedded.hsqldb.model;
public class Customer {
private Long customerId;
private String customerName;
private String customerAddress;
private String customerCity;
private String customerState;
private String customerZip;
public Long getCustomerId() {
return customerId;
}
public void setCustomerId(Long customerId) {
this.customerId = customerId;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public String getCustomerAddress() {
return customerAddress;
}
public void setCustomerAddress(String customerAddress) {
this.customerAddress = customerAddress;
}
public String getCustomerCity() {
return customerCity;
}
public void setCustomerCity(String customerCity) {
this.customerCity = customerCity;
}
public String getCustomerState() {
return customerState;
}
public void setCustomerState(String customerState) {
this.customerState = customerState;
}
public String getCustomerZip() {
return customerZip;
}
public void setCustomerZip(String customerZip) {
this.customerZip = customerZip;
}
@Override
public String toString() {
return "[ Customer Id : " + customerId + ", Customer Name : " + customerName + ", Customer Address : "
+ customerAddress + ", Customer City : " + customerCity + ", Customer State : " + customerState
+ ", Customer Zip Code : " + customerZip + "]";
}
}
| true
|
a4eb2931bc953fc6b1f258a1f306264ce4a27c96
|
Java
|
effy-r/NewJavaBootcamp
|
/src/main/java/lv/accenture/bootcamp/spring/SmsNotification.java
|
UTF-8
| 502
| 2.5625
| 3
|
[] |
no_license
|
package lv.accenture.bootcamp.spring;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component("sms")
public class SmsNotification implements NotificationChannel {
@Value("${notification.sms.operator}")
private String operator;
@Override
public void notifyUser(User user) {
String info = user.getFullName() + " is notified by sms on number " + user.getNumber() + " by operator "
+ operator;
System.out.println(info);
}
}
| true
|
535d8aca1d965758698d55f747b2eb84c92c92f2
|
Java
|
8emi95/elte-ik-java
|
/gy/java_16171_gy/java_gy06/verseny/Verseny.java
|
UTF-8
| 1,279
| 2.28125
| 2
|
[] |
no_license
|
package verseny;
import verseny.Versenyzo;
class Verseny {
String nev;
// A versenynek legyen egy nev adattagja (szöveg) és tartsuk számon, kik a versenyzok (Versenyzo?k tömbje).
Verseny(String fajlnev) {
//
}
// A konstruktora egy fájlnevet kap szövegesen paraméterként.
// Feltételezhető, hogy a fájl létezik, és helyesen van kitöltve:
// az első sorában tartalmazza a verseny nevét,
// a másodikban a benne található versenyzők számát,
// a fennmaradó sorokban pedig egy-egy versenyző adatait.
// A versenyzők adatai olyan alakúak, ahogyan azt a Versenyzo második konstruktora elvárja.
// A Verseny konstruktora olvassa be a fájl adatait, és töltse fel az adattagokat.
String toString() {
//
}
// A példaként adott verseny1.txt fájlban leírt verseny adja az alábbi kimenetet:
// "Verseny:(Verseny1, Versenyzo[Versenyzo1, [versenyA, versenyB, versenyC, versenyD]], Versenyzo[Versenyzo2, [versenyA, versenyE]], Versenyzo[Versenyzo3, [versenyB, versenyC, versenyF]])"
getVersenyVersenyzoi(String versenyNev) {
//
}
// Legyen egy getVersenyVersenyzoi művelete. Ez szövegesen megkapja egy verseny nevét, és azokat a versenyzőket adja vissza egy List listában, akik részt vettek ilyen nevű versenyen.
}
| true
|
3288eef4d82f06a1ad3bab56ba1c64ed2edb869c
|
Java
|
jlopez-code/ryanair
|
/src/main/java/com/ryanair/challenge/infrastructure/client/ryanair/schedule/RyanairScheduleClient.java
|
UTF-8
| 621
| 2.0625
| 2
|
[] |
no_license
|
package com.ryanair.challenge.infrastructure.client.ryanair.schedule;
import com.ryanair.challenge.infrastructure.client.dto.ScheduleDTO;
import feign.Param;
import feign.RequestLine;
import org.springframework.cloud.openfeign.FeignClient;
@FeignClient(
name = "ryanair-schedule",
url = "${provider.ryanair.schedule.url}"
)
public interface RyanairScheduleClient {
@RequestLine("GET schedules/{from}/{to}/years/{year}/months/{month}")
ScheduleDTO getSchedule(@Param("from") String from, @Param("to") String to,
@Param("year") Integer year, @Param("month") Integer month);
}
| true
|
e97e01aead3b50f2453183b7ffb7e57fd6f14f7a
|
Java
|
dknox2/ProjectPokedex
|
/ProjectPokedex/src/edu/westga/cs3212/projectpokedex/view/embed/PokemonEmbedHandler.java
|
UTF-8
| 6,244
| 2.671875
| 3
|
[
"Unlicense"
] |
permissive
|
package edu.westga.cs3212.projectpokedex.view.embed;
import java.util.ArrayList;
import java.util.List;
import edu.westga.cs3212.projectpokedex.model.Pokedex;
import edu.westga.cs3212.projectpokedex.model.pokedexitem.PokedexItem;
import edu.westga.cs3212.projectpokedex.model.pokemon.Pokemon;
import edu.westga.cs3212.projectpokedex.view.CaughtSeenSelection;
import javafx.beans.property.ListProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleListProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
/**
* Responsible for sorting PokemonEmbeds to be displayed in the MainPage
* according to the state of the Pokedex in the MainPage.
*
* @author Kyle Riggs, Cody Graham, Dylan Knox, Joseph Fuller
*/
public class PokemonEmbedHandler {
private final Pokedex pokedex;
private List<Integer> sortedPokemonInternalIds;
private ObjectProperty<CaughtSeenSelection> selectedCaughtSeenSelectionProperty;
private List<PokemonEmbed> allPokemonEmbeds;
private ObservableList<PokemonEmbed> displayedPokemonEmbeds;
private ListProperty<PokemonEmbed> displayedPokemonEmbedsProperty;
/**
* Instantiates a new pokedex embed manager.
*
* @param pokedex the pokedex to sort embeds for
*/
public PokemonEmbedHandler(Pokedex pokedex) {
this.pokedex = pokedex;
this.sortedPokemonInternalIds = new ArrayList<Integer>();
this.allPokemonEmbeds = new ArrayList<PokemonEmbed>();
this.displayedPokemonEmbeds = FXCollections.observableArrayList();
this.displayedPokemonEmbedsProperty = new SimpleListProperty<PokemonEmbed>();
this.selectedCaughtSeenSelectionProperty = new SimpleObjectProperty<CaughtSeenSelection>();
this.createAllDefaultEmbeds();
}
/**
* Sorts the Pokedex embeds according to the current status of the Pokedex and
* updates corresponding properties.
*/
public void updatePokemonEmbeds() {
this.updateSortedIndicies();
this.updateDisplayedPokemonEmbeds();
this.displayedPokemonEmbedsProperty.set(this.displayedPokemonEmbeds);
}
/**
* Flushes any data not created in the embeds currently
*/
public void flushInternalEmbeds() {
for (PokedexItem item : this.pokedex) {
this.sortedPokemonInternalIds.add(item.getInternalID());
if(item.getInternalID() >= this.allPokemonEmbeds.size()) {
this.addPokemonEmbed(item);
}
}
}
/**
* Gets the displayed Pokemon embeds for property binding
*
* @return the displayed Pokemon embeds
*/
public ObservableList<PokemonEmbed> getDisplayedPokemonEmbeds() {
return this.displayedPokemonEmbeds;
}
/**
* Gets the selected CaughtSeenSelection property for filtering the displayed
* Pokemon embeds via property binding.
*
* @return the selected CaughtSeenSelection property
*/
public ObjectProperty<CaughtSeenSelection> getSelectedCaughtSeenSelectionProperty() {
return this.selectedCaughtSeenSelectionProperty;
}
/**
* Gets the displayed Pokemon embeds list property for binding
*
* @return the displayed Pokemon embeds property
*/
public ListProperty<PokemonEmbed> getDisplayedPokemonEmbedsProperty() {
return this.displayedPokemonEmbedsProperty;
}
/**
* Adds a PokedexItem to the managed embeds and resorts.
*
* @param pokedexItem the pokedexItem to add to the embeds
*/
public void addPokemonEmbed(PokedexItem pokedexItem) {
this.allPokemonEmbeds.add(this.createPokemonEmbed(pokedexItem.getPokemon()));
}
private PokemonEmbed createPokemonEmbed(Pokemon pokemon) {
PokemonEmbed embed;
if (pokemon.getPostEvolutions() != null) {
if (pokemon.getPreviousEvolution() != null) {
embed = new PokemonEmbed(pokemon.getName(), String.valueOf(pokemon.getPokedexNumber()),
pokemon.getPrimaryType(), pokemon.getSecondaryType(), pokemon.getExclusivity(), pokemon.getLocation(),
String.valueOf(pokemon.getWeight()), String.valueOf(pokemon.getHeight()), pokemon.getDescription(),
pokemon.getLevelUpMoveset(), pokemon.getPreviousEvolution().toString(),
pokemon.getPostEvolutions().toString());
} else {
embed = new PokemonEmbed(pokemon.getName(), String.valueOf(pokemon.getPokedexNumber()),
pokemon.getPrimaryType(), pokemon.getSecondaryType(), pokemon.getExclusivity(), pokemon.getLocation(),
String.valueOf(pokemon.getWeight()), String.valueOf(pokemon.getHeight()), pokemon.getDescription(),
pokemon.getLevelUpMoveset(), "",
pokemon.getPostEvolutions().toString());
}
} else {
if (pokemon.getPreviousEvolution() != null) {
embed = new PokemonEmbed(pokemon.getName(), String.valueOf(pokemon.getPokedexNumber()),
pokemon.getPrimaryType(), pokemon.getSecondaryType(), pokemon.getExclusivity(), pokemon.getLocation(),
String.valueOf(pokemon.getWeight()), String.valueOf(pokemon.getHeight()), pokemon.getDescription(),
pokemon.getLevelUpMoveset(), pokemon.getPreviousEvolution().toString(),
"");
} else {
embed = new PokemonEmbed(pokemon.getName(), String.valueOf(pokemon.getPokedexNumber()),
pokemon.getPrimaryType(), pokemon.getSecondaryType(), pokemon.getExclusivity(), pokemon.getLocation(),
String.valueOf(pokemon.getWeight()), String.valueOf(pokemon.getHeight()), pokemon.getDescription(),
pokemon.getLevelUpMoveset(), "", "");
}
}
return embed;
}
private void createAllDefaultEmbeds() {
for (PokedexItem item : this.pokedex) {
PokemonEmbed embed = this.createPokemonEmbed(item.getPokemon());
this.allPokemonEmbeds.add(embed);
}
this.displayedPokemonEmbedsProperty.set(this.displayedPokemonEmbeds);
}
private void updateSortedIndicies() {
this.sortedPokemonInternalIds.clear();
this.flushInternalEmbeds();
}
private void updateDisplayedPokemonEmbeds() {
this.displayedPokemonEmbeds.clear();
for (int internalId : this.sortedPokemonInternalIds) {
PokemonEmbed embed = this.allPokemonEmbeds.get(internalId);
CaughtSeenSelection selectedCaughtSeenSelection = this.selectedCaughtSeenSelectionProperty.get();
if (embed.getCaughtSeenSelection() == selectedCaughtSeenSelection
|| selectedCaughtSeenSelection == CaughtSeenSelection.ALL) {
this.displayedPokemonEmbeds.add(embed);
}
}
}
}
| true
|
7b824774d6c29f92047175afa630dae4dc4788d4
|
Java
|
ClickerMonkey/ship
|
/Games/Battlecraft/src/axe/g2f/Bound2f.java
|
UTF-8
| 3,749
| 2.859375
| 3
|
[] |
no_license
|
package axe.g2f;
import axe.Scalarf;
public class Bound2f
{
public float l, r, t, b;
public Bound2f() {
}
public Bound2f(float x, float y) {
clear(x, y);
}
public Bound2f(float left, float top, float right, float bottom) {
set(left, top, right, bottom);
}
public Bound2f(Bound2f x) {
set(x);
}
public void include(float x, float y) {
if (x < l) l = x;
if (x > r) r = x;
if (y < t) t = y;
if (y > b) b = y;
}
public void clear(float x, float y) {
l = r = x;
t = b = y;
}
public void clear() {
l = r = t = b = 0f;
}
public void set(Bound2f x) {
set(x.l, x.t, x.r, x.b);
}
public void set(float left, float top, float right, float bottom) {
l = left;
r = right;
t = top;
b = bottom;
}
public void rect(float x, float y, float width, float height) {
set(x, y, x + width, y + height);
}
public void line(float x0, float y0, float x1, float y1) {
l = Math.min(x0, x1);
r = Math.max(x0, x1);
t = Math.min(y0, y1);
b = Math.min(y0, y1);
}
public void ellipse(float cx, float cy, float rw, float rh) {
rw = Math.abs(rw);
rh = Math.abs(rh);
l = cx - rw;
r = cx + rw;
t = cy - rh;
b = cy + rh;
}
public void quad(float cx, float cy, float w, float h, float angle) {
quad(cx, cy, w, h, Scalarf.cos(angle), Scalarf.sin(angle));
}
public void quad(float cx, float cy, float w, float h, float vx, float vy) {
vx = Math.abs(vx);
vy = Math.abs(vy);
float hw = (vx * w + vy * h) * 0.5f;
float hh = (vx * h + vy * w) * 0.5f;
ellipse(cx, cy, hw, hh);
}
public void center(float x, float y) {
float w = width() * 0.5f;
float h = height() * 0.5f;
l = x - w;
r = x + w;
t = y - h;
b = y + h;
}
public void move(float dx, float dy) {
l += dx; r += dx;
t += dy; b += dy;
}
public void zoom(float sx, float sy) {
float hw = width() * 0.5f * Math.abs(sx);
float hh = height() * 0.5f * Math.abs(sy);
ellipse(cx(), cy(), hw, hh);
}
public float width() {
return (r - l);
}
public float height() {
return (b - t);
}
public float cx() {
return (l + r) * 0.5f;
}
public float cy() {
return (t + b) * 0.5f;
}
public void intersection(Bound2f x, Bound2f y) {
l = Math.max(x.l, y.l);
r = Math.min(x.r, y.r);
t = Math.max(x.t, y.t);
b = Math.min(x.b, y.b);
}
public void union(Bound2f x, Bound2f y) {
l = Math.min(x.l, y.l);
r = Math.max(x.r, y.r);
t = Math.min(x.t, y.t);
b = Math.max(x.b, y.b);
}
public boolean intersects(Bound2f x) {
return !(x.l >= r || x.r <= l || x.t >= b || x.b <= t);
}
public boolean touches(Bound2f x) {
return !(x.l > r || x.r < l || x.t > b || x.b < t);
}
public boolean contains(Bound2f x) {
return !(x.l < l || x.r > r || x.t < t || x.b > b);
}
public boolean inside(Bound2f x) {
return !(x.l <= l || x.r >= r || x.t <= t || x.b >= b);
}
public String toString() {
return String.format("{%.2f, %.2f, %.2f, %.2f}", l, t, width(), height());
}
/**
glPushMatrix(); {
glColor3f(1, 0, 0);
glTranslatef(CENTER_X, CENTER_Y, 0);
glRotatef((float)Math.toDegrees(angle), 0, 0, 1);
glScalef(20f, 30f, 0f);
glBegin(GL_LINE_LOOP); {
glVertex2f(-0.5f, 0.5f);
glVertex2f(-0.5f,-0.5f);
glVertex2f( 0.5f,-0.5f);
glVertex2f( 0.5f, 0.5f);
} glEnd();
} glPopMatrix();
Bound2f b = new Bound2f();
b.quad(CENTER_X, CENTER_Y, 20, 30, angle);
glColor3f(0, 0, 1);
glBegin(GL_LINE_LOOP); {
glVertex2f(b.l, b.t);
glVertex2f(b.l, b.b);
glVertex2f(b.r, b.b);
glVertex2f(b.r, b.t);
} glEnd();
*/
}
| true
|
dad7a2a401fe9bf16e21fb28f1bb14d32f35dc8e
|
Java
|
koposoftware/2021_11_swyoon
|
/final-project/src/main/java/kr/ac/kopo/reservation/vo/ReservationVO.java
|
UTF-8
| 1,632
| 2.0625
| 2
|
[] |
no_license
|
package kr.ac.kopo.reservation.vo;
public class ReservationVO {
private String rsrvTime;
private String rsrvComment;
private String username;
private String pbName;
private String pbBranchName;
private String startDate;
public String getStartDate() {
return startDate;
}
public void setStartDate(String startDate) {
this.startDate = startDate;
}
public String getRsrvTime() {
return rsrvTime;
}
public void setRsrvTime(String rsrvTime) {
this.rsrvTime = rsrvTime;
}
public String getRsrvComment() {
return rsrvComment;
}
public void setRsrvComment(String rsrvComment) {
this.rsrvComment = rsrvComment;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPbName() {
return pbName;
}
public void setPbName(String pbName) {
this.pbName = pbName;
}
public String getPbBranchName() {
return pbBranchName;
}
public void setPbBranchName(String pbBranchName) {
this.pbBranchName = pbBranchName;
}
@Override
public String toString() {
return "ReservationVO{" +
"rsrvTime='" + rsrvTime + '\'' +
", rsrvComment='" + rsrvComment + '\'' +
", username='" + username + '\'' +
", pbName='" + pbName + '\'' +
", pbBranchName='" + pbBranchName + '\'' +
", startDate='" + startDate + '\'' +
'}';
}
}
| true
|
989754d4923b4444a8fe4caf18f2bc17baa841d3
|
Java
|
lionchi/InformationSystem
|
/information-system-api/src/main/java/ru/gavrilov/tasks/MemoryTask.java
|
UTF-8
| 1,398
| 2.71875
| 3
|
[] |
no_license
|
package ru.gavrilov.tasks;
import javafx.concurrent.Task;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ru.gavrilov.SystemInfo;
import ru.gavrilov.hardware.GlobalMemory;
import ru.gavrilov.hardware.HardwareAbstractionLayer;
import ru.gavrilov.software.OperatingSystem;
import ru.gavrilov.util.FormatUtil;
import java.util.ArrayList;
import java.util.List;
public class MemoryTask extends Task<List<String>> {
private static final HardwareAbstractionLayer hardwareAbstractionLayer = SystemInfo.INSTANCE.getHardware();
private static final OperatingSystem operatingSystem = SystemInfo.INSTANCE.getOperatingSystem();
private static final Logger LOG = LoggerFactory.getLogger(MemoryTask.class);
@Override
protected List<String> call() throws Exception {
LOG.info("Checking memory...");
GlobalMemory memory = hardwareAbstractionLayer.getMemory();
List<String> strings = new ArrayList<>();
strings.add(String.valueOf(operatingSystem.getProcessCount()));
strings.add(String.valueOf(operatingSystem.getThreadCount()));
strings.add(FormatUtil.formatBytes(memory.getAvailable()) + "/"
+ FormatUtil.formatBytes(memory.getTotal()));
strings.add(FormatUtil.formatBytes(memory.getSwapUsed()) + "/"
+ FormatUtil.formatBytes(memory.getSwapTotal()));
return strings;
}
}
| true
|
618344a923cebe1d7e3c528c7934e953d3c46ee1
|
Java
|
mvolkanaslan/JavaGameCenterDemo
|
/src/fakeIdentityMicroServise/FakeIdentityChacker.java
|
UTF-8
| 381
| 2.484375
| 2
|
[] |
no_license
|
package fakeIdentityMicroServise;
import JavaGameCenterDemo.entities.concretes.Customer;
public class FakeIdentityChacker {
public boolean checkCustomer(Customer customer) {
if(customer.getFirstName()=="Mehmet Volkan" && customer.getLastName() == "ASLAN" && customer.getYearOfBirth() == 1989 && customer.getIdentityNumber()=="123456") {
return true;
}
return false;
}
}
| true
|
a98325709decd1b5ca99ddc6af689fcc12a5c0a6
|
Java
|
s4ke/HibernateSearchQueryExtension
|
/src/test/java/de/hotware/hibernate/query/Place.java
|
UTF-8
| 2,027
| 2.203125
| 2
|
[] |
no_license
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.*
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* (C) Martin Braun 2014
*/
package de.hotware.hibernate.query;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import org.hibernate.search.annotations.DocumentId;
import org.hibernate.search.annotations.Field;
import org.hibernate.search.annotations.Index;
import org.hibernate.search.annotations.Indexed;
import org.hibernate.search.annotations.IndexedEmbedded;
import org.hibernate.search.annotations.Store;
@Indexed
@Entity
public class Place {
private Integer id;
private String name;
private Set<Sorcerer> sorcerers = new HashSet<>();
@Id
@DocumentId
@GeneratedValue(strategy=GenerationType.AUTO)
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@Field(store = Store.NO, index = Index.YES )
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@IndexedEmbedded
@OneToMany
public Set<Sorcerer> getSorcerers() {
return sorcerers;
}
public void setSorcerers(Set<Sorcerer> sorcerers) {
this.sorcerers = sorcerers;
}
@Override
public String toString() {
return "Place [id=" + id + ", name=" + name + ", sorcerers="
+ sorcerers + "]";
}
}
| true
|
b8c0b7252b090b111c756178543be1ae4be04c0a
|
Java
|
ekochnev/pla
|
/src/test/java/com/pla/underwriter/service/UnderWriterServiceUnitTest.java
|
UTF-8
| 9,033
| 2.21875
| 2
|
[] |
no_license
|
package com.pla.underwriter.service;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.pla.publishedlanguage.contract.IPlanAdapter;
import com.pla.underwriter.domain.model.UnderWriterInfluencingFactor;
import com.pla.underwriter.dto.UnderWriterDto;
import com.pla.underwriter.dto.UnderWriterLineItemDto;
import com.pla.underwriter.exception.UnderWriterTemplateParseException;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.*;
import static org.mockito.Mockito.when;
/**
* Created by Admin on 5/21/2015.
*/
@RunWith(MockitoJUnitRunner.class)
public class UnderWriterServiceUnitTest {
@Mock
private UnderWriterTemplateParser underWriterTemplateParser;
@Mock
private IPlanAdapter iPlanAdapter;
UnderWriterService underWriterService;
List<UnderWriterDto> underWriterDocumentItems;
@Before
public void setUp(){
underWriterDocumentItems = Lists.newArrayList();
UnderWriterDto underWriterDto = new UnderWriterDto();
List<UnderWriterLineItemDto> underWriterLineItem = Lists.newArrayList();
UnderWriterLineItemDto underWriterLineItemDto = new UnderWriterLineItemDto();
underWriterLineItemDto.setUnderWriterInfluencingFactor(UnderWriterInfluencingFactor.AGE);
underWriterLineItemDto.setInfluencingItemFrom("10");
underWriterLineItemDto.setInfluencingItemTo("30");
underWriterLineItem.add(underWriterLineItemDto);
underWriterDto.setUnderWriterLineItem(underWriterLineItem);
Set<String> documents = Sets.newHashSet("Document One", "Document Two", "Document Three", "Document Four");
underWriterDto.setDocuments(documents);
underWriterDocumentItems.add(underWriterDto);
underWriterService = new UnderWriterService(underWriterTemplateParser,iPlanAdapter);
}
/*
* Given
* the under writer document setup
* then
* it Should transform the setup to the expected form and return
* */
@Test
public void givenUnderWriterDocumentSetUp_thenItShouldTransformTheUnderWriterDocumentSetUpToRequiredFormat(){
List<Map<Object,Map<String,Object>>> underWriterDocumentMap = underWriterService.transformUnderWriterDocument(underWriterDocumentItems);
assertNotNull(underWriterDocumentMap);
}
/*
* Given
* the under writer document set up
* When
* the Under writer influencing factor from/to values are overlapping with other respective influencing factors from/to value
* then
* it should return isValidRow as false
* */
@Test
public void givenUnderWriterDocumentSetUp_whenTheInfluencingFactorsAreOverLapping_thenItShouldReturnIsValidRowAsFalse(){
UnderWriterDto underWriterDto = new UnderWriterDto();
List<UnderWriterLineItemDto> underWriterLineItem = Lists.newArrayList();
UnderWriterLineItemDto underWriterLineItemDto = new UnderWriterLineItemDto();
underWriterLineItemDto.setUnderWriterInfluencingFactor(UnderWriterInfluencingFactor.AGE);
underWriterLineItemDto.setInfluencingItemFrom("10");
underWriterLineItemDto.setInfluencingItemTo("50");
underWriterLineItem.add(underWriterLineItemDto);
underWriterDto.setUnderWriterLineItem(underWriterLineItem);
Set<String> documents = Sets.newHashSet("Document One", "Document Two", "Document Three", "Document Four");
underWriterDto.setDocuments(documents);
underWriterDocumentItems.add(underWriterDto);
boolean isValid = underWriterService.doesAnyRowOverLappingEachOther(underWriterDto, underWriterDocumentItems, true, Lists.newArrayList());
assertFalse(isValid);
}
/*
* Given
* the under writer document set up
* When
* the Under writer influencing factor from/to values are not overlapping with other respective influencing factors from/to value
* then
* it should return isValidRow as true
* */
@Test
public void givenUnderWriterDocumentSetUp_whenTheInfluencingFactorsAreNotOverLapping_thenItShouldReturnIsValidRowAsTrue(){
UnderWriterDto underWriterDto = new UnderWriterDto();
List<UnderWriterLineItemDto> underWriterLineItem = Lists.newArrayList();
UnderWriterLineItemDto underWriterLineItemDto = new UnderWriterLineItemDto();
underWriterLineItemDto.setUnderWriterInfluencingFactor(UnderWriterInfluencingFactor.AGE);
underWriterLineItemDto.setInfluencingItemFrom("40");
underWriterLineItemDto.setInfluencingItemTo("50");
underWriterLineItem.add(underWriterLineItemDto);
underWriterDto.setUnderWriterLineItem(underWriterLineItem);
Set<String> documents = Sets.newHashSet("Document One", "Document Two", "Document Three", "Document Four");
underWriterDto.setDocuments(documents);
underWriterDocumentItems.add(underWriterDto);
boolean isValid = underWriterService.doesAnyRowOverLappingEachOther(underWriterDto, underWriterDocumentItems, true, Lists.newArrayList());
assertTrue(isValid);
}
/*
* Given the Influencing factor from/to value in string type
* when the given value is a number
* then it should convert the string to double and return the value
* */
@Test
public void givenInfluencingFactorValue_whenTheValueIsValid_thenItShouldReturnTheInfluencingFactor(){
Double expectedValue = 1234.0;
Double influencingFactorValue = underWriterService.getInfluencingFactorValue("1234");
assertThat(expectedValue, is(influencingFactorValue));
}
/*
* Given the Influencing factor from/to value in string type
* when the given value is not a number
* then it should return 0l
* */
@Test
public void givenInfluencingFactorValue_whenTheValueIsNotValid_thenItShouldReturnTheInfluencingFactorAsZero(){
Double expectedValue = 0.0;
Double influencingFactorValue = underWriterService.getInfluencingFactorValue("12ABC");
assertThat(expectedValue, is(influencingFactorValue));
}
/*
*
* When the given plan code is valid,
* Then it should allow to create the Under Writer document
* */
@Test
public void givenAPlanCode_whenThePlanCodeIsValid_thenItShouldAllowToCreateTheUnderWriter(){
when(iPlanAdapter.isValidPlanCode("P001")).thenReturn(true);
underWriterService.checkValidPlanAndCoverageCode("P001");
}
/*
* When The plan code is not existed
* Then it should throw the exception with error message as Not a valid Plan.
*
* */
@Test(expected = UnderWriterTemplateParseException.class)
public void givenAPlanCode_whenThePlanCodeIsNotValid_thenItShouldThrowUnderWriterException(){
when(iPlanAdapter.isValidPlanCode("P001")).thenReturn(false);
underWriterService.checkValidPlanAndCoverageCode("P001");
}
@Test
public void itShouldReturnTheDefinedUnderWritingProcessTypes(){
List<Map<String,String>> expectedProcessList = Lists.newArrayList();
Map<String,String> processMap = Maps.newLinkedHashMap();
processMap.put("processType","ENROLLMENT");
processMap.put("description","Enrollment");
expectedProcessList.add(processMap);
processMap = Maps.newLinkedHashMap();
processMap.put("processType","CLAIM");
processMap.put("description","Claim");
expectedProcessList.add(processMap);
List<Map<String,String>> underWriterProcess = underWriterService.getUnderWriterProcess();
assertThat(expectedProcessList,is(underWriterProcess));
}
@Test
public void givenProcessTypeAsEnrollment_whenProcessTypeIsNotClaim_thenItShouldNotReturnTheClaimAmountInfluencingFactor(){
List<Map<String,String>> underWritingInfluencingFactor = underWriterService.getUnderWritingInfluencingFactor("ENROLLMENT");
assertNotNull(underWritingInfluencingFactor);
assertThat(underWritingInfluencingFactor.size(),is(5));
}
@Test
public void givenProcessTypeAsClaim_thenItShouldReturnTheClaimAmountInfluencingFactor(){
List<Map<String,String>> underWritingInfluencingFactor = underWriterService.getUnderWritingInfluencingFactor("CLAIM");
assertNotNull(underWritingInfluencingFactor);
assertThat(underWritingInfluencingFactor.size(),is(6));
}
@Test
public void given_when_then(){
List<UnderWriterInfluencingFactor> underWriterInfluencingFactors = Lists.newArrayList(UnderWriterInfluencingFactor.AGE,UnderWriterInfluencingFactor.SUM_ASSURED,UnderWriterInfluencingFactor.BMI,UnderWriterInfluencingFactor.HEIGHT);
underWriterService.getInfluencingFactorRange(underWriterInfluencingFactors);
}
}
| true
|
8a019c97fd4355924d4970a217f9cbff01824955
|
Java
|
hongchao1117/LeetCodeQuestion
|
/src/Mathmatics/reverse.java
|
UTF-8
| 417
| 3.28125
| 3
|
[] |
no_license
|
package Mathmatics;
public class reverse {
public static void main(String[] args) {
int sum = -123;
System.out.println(reverse(sum));
}
public static int reverse(int num) {
long res = 0L;
while (num != 0) {
res = res * 10 + num % 10;
num /= 10;
}
return res > Integer.MAX_VALUE || res < Integer.MIN_VALUE ? 0 : (int) res;
}
}
| true
|
d42aa48c4bd514c4d45fb67a1a7f93085c59211c
|
Java
|
guiguiangel/ddnsell_ace
|
/src/main/java/com/ddn/ddnsell/dao/UserRoleDao.java
|
UTF-8
| 622
| 1.96875
| 2
|
[] |
no_license
|
package com.ddn.ddnsell.dao;
import com.ddn.ddnsell.entity.Permission.UserRole;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
public interface UserRoleDao extends JpaRepository<UserRole,Long> {
@Modifying
@Query(value = "update user_role set status = 1 where user_id = :userId", nativeQuery = true)
public int deleteUserRoleBySetStatus(@Param("userId") Long userId);
public int deleteUserRolesByUserId(Long userId);
}
| true
|
aa6e0f7e86f6b9814bea24b905af16f5bf7d53f0
|
Java
|
benayadmohamed/code-testing
|
/src/main/java/com/services/VirementService.java
|
UTF-8
| 1,040
| 2.453125
| 2
|
[] |
no_license
|
package com.services;
import com.exceptions.AccountExistePasException;
import com.exceptions.MontantInfAZeroException;
import com.exceptions.SoldeInfAZeroException;
import com.models.VirementRequest;
import com.validators.VirementValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class VirementService {
@Autowired
AccountService accountService;
@Autowired
VirementValidator virementValidator;
public boolean performTransfer(VirementRequest virementRequest) {
try {
virementValidator.validateVirementRequest(virementRequest);
accountService.debiter(virementRequest.getEmetteur().getCode(), virementRequest.getAmount());
accountService.crediter(virementRequest.getRecepteur().getCode(), virementRequest.getAmount());
return true;
} catch (AccountExistePasException | SoldeInfAZeroException | MontantInfAZeroException e) {
return false;
}
}
}
| true
|
25f0dfcb05b321795b1081758eb1aab8c5ad85c6
|
Java
|
shangerdi/Android
|
/qr/src/main/java/com/malalaoshi/android/qr/QRCodeUtil.java
|
UTF-8
| 5,274
| 2.578125
| 3
|
[
"MIT"
] |
permissive
|
package com.malalaoshi.android.qr;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import java.util.EnumMap;
import java.util.Map;
/**
* Created by kang on 16/11/7.
*/
public class QRCodeUtil {
private static final int WHITE = 0xFFFFFFFF;
private static final int BLACK = 0xFF000000;
public static Bitmap createQRCode(String contentsToEncode, int dimension) throws WriterException {
if (contentsToEncode == null) {
return null;
}
Map<EncodeHintType, Object> hints = null;
String encoding = guessAppropriateEncoding(contentsToEncode);
if (encoding != null) {
hints = new EnumMap<>(EncodeHintType.class);
hints.put(EncodeHintType.CHARACTER_SET, encoding);
//容错级别
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
}
BitMatrix result;
try {
result = new MultiFormatWriter().encode(contentsToEncode,
BarcodeFormat.QR_CODE, dimension, dimension, hints);
} catch (IllegalArgumentException iae) {
// Unsupported format
return null;
}
// 下面这里按照二维码的算法,逐个生成二维码的图片,
int width = result.getWidth();
int height = result.getHeight();
int[] pixels = new int[width * height];
for (int y = 0; y < height; y++) {
int offset = y * width;
for (int x = 0; x < width; x++) {
pixels[offset + x] = result.get(x, y) ? BLACK : WHITE;
}
}
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
return bitmap;
}
public static Bitmap createQRCodeWithLogo(Context context, String contentsToEncode, int dimension, int drawableId) throws WriterException{
Bitmap bmp= BitmapFactory.decodeResource(context.getResources(), drawableId);
return QRCodeUtil.createQRCodeWithLogo(contentsToEncode,dimension,bmp);
}
/**
* 生成带logo的二维码,logo默认为二维码的1/5
*/
public static Bitmap createQRCodeWithLogo(String contentsToEncode, int dimension, Bitmap logo) throws WriterException {
int logoHeight = dimension / 14;
if (contentsToEncode == null) {
return null;
}
Map<EncodeHintType, Object> hints = null;
String encoding = guessAppropriateEncoding(contentsToEncode);
if (encoding != null) {
hints = new EnumMap<>(EncodeHintType.class);
hints.put(EncodeHintType.CHARACTER_SET, encoding);
//容错级别
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
}
BitMatrix result;
try {
result = new MultiFormatWriter().encode(contentsToEncode,
BarcodeFormat.QR_CODE, dimension, dimension, hints);
} catch (IllegalArgumentException iae) {
// Unsupported format
return null;
}
// 下面这里按照二维码的算法,逐个生成二维码的图片,
int width = result.getWidth();
int height = result.getHeight();
int halfW = width / 2;
int halfH = height / 2;
Matrix m = new Matrix();
float sx = (float) 2 * logoHeight / logo.getWidth();
float sy = (float) 2 * logoHeight / logo.getHeight();
m.setScale(sx, sy);
//设置缩放信息
//将logo图片按martix设置的信息缩放
logo = Bitmap.createBitmap(logo, 0, 0,
logo.getWidth(), logo.getHeight(), m, false);
int[] pixels = new int[width * height];
for (int y = 0; y < height; y++) {
int offset = y * width;
for (int x = 0; x < width; x++) {
if (x > halfW - logoHeight && x < halfW + logoHeight
&& y > halfH - logoHeight
&& y < halfH + logoHeight) {
//该位置用于存放图片信息
//记录图片每个像素信息
pixels[offset + x] = logo.getPixel(x - halfW
+ logoHeight, y - halfH + logoHeight);
} else {
pixels[offset + x] = result.get(x, y) ? BLACK : WHITE;
}
}
}
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
return bitmap;
}
private static String guessAppropriateEncoding(CharSequence contents) {
// Very crude at the moment
for (int i = 0; i < contents.length(); i++) {
if (contents.charAt(i) > 0xFF) {
return "UTF-8";
}
}
return null;
}
}
| true
|
328f1c1e3f845b922b46dab0296a75936b9ddf11
|
Java
|
brect/api-livinother
|
/src/main/java/com/manoloscorp/livinother/services/StateServiceImpl.java
|
UTF-8
| 1,239
| 2.421875
| 2
|
[] |
no_license
|
package com.manoloscorp.livinother.services;
import com.manoloscorp.livinother.entities.State;
import com.manoloscorp.livinother.repositories.StateRepository;
import com.manoloscorp.livinother.resources.exceptions.NotFoundException;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
@Service
public class StateServiceImpl implements StateService{
private final StateRepository stateRepository;
public StateServiceImpl(StateRepository stateRepository) {
this.stateRepository = stateRepository;
}
@Override
public List<State> getAllStates() {
return stateRepository.findAll();
}
@Override
public State getStateById(Long id) throws NotFoundException {
Optional<State> state = stateRepository.findById(id);
return state.orElseThrow(() -> new NotFoundException(id));
}
@Override
public State saveState(State state) {
return stateRepository.save(state);
}
@Override
public State updateState(Long id, State state) {
Optional<State> stateUpdate = stateRepository.findById(id);
if (stateUpdate != null) {
state.setId(stateUpdate.get().getId());
stateRepository.save(state);
return state;
}
return null;
}
}
| true
|
97622f653bf01b5e6b1b29ca67bab9f4eb7801b5
|
Java
|
montycheese/blackjack
|
/src/BlackJackDealer.java
|
UTF-8
| 176
| 2.078125
| 2
|
[] |
no_license
|
public class BlackJackDealer extends BlackJackPlayer {
private static final double BANK = (double) Double.MAX_VALUE/2;
public BlackJackDealer() {
super(BANK, 0);
}
}
| true
|
4e46966701d678837cdafb41eca0ea775575991d
|
Java
|
mamchayd/Demo-Design-pattern-Decorator-JavaFx-
|
/src/decorateur/Vani.java
|
UTF-8
| 386
| 2.6875
| 3
|
[] |
no_license
|
package decorateur;
import dec.Boisson;
public class Vani extends DecorateurBoisson{
public Vani(Boisson boisson) {
super(boisson);
// TODO Auto-generated constructor stub
}
@Override
public double cout() {
return 2+boisson.cout();
}
@Override
public String getDescription() {
// TODO Auto-generated method stub
return boisson.getDescription()+" avec vani";
}
}
| true
|
19823df42d1b8fb9edb9fdc32f822838dce76060
|
Java
|
adityapalavajjhala/NCFOA-user-application
|
/app/src/main/java/com/example/ncfoa_user_application/model/Restaurant.java
|
UTF-8
| 1,867
| 2.40625
| 2
|
[] |
no_license
|
package com.example.ncfoa_user_application.model;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
public class Restaurant {
private Integer id;
private String name,address,city,email,message;
private Boolean status,active;
private Map<String,Menu> menus;
public void setMenus(Map<String, Menu> menus) {
this.menus = menus;
}
public Map<String,Menu> getMenus() {
return menus;
}
public boolean addMenus(String name,Menu menu){
if(menus==null
||menus.isEmpty())
menus= new TreeMap<>();
if(menus.containsKey(name)
||menus.containsValue(menu))
return false;
menus.put(name,menu);
return true;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Boolean getStatus() {
return status;
}
public void setStatus(Boolean status) {
this.status = status;
}
public Boolean getActive() {
return active;
}
public void setActive(Boolean active) {
this.active = active;
}
}
| true
|
51f3317b2e4cc67b32206862bc006e0cb7a8de6b
|
Java
|
nirvana-info/old_bak
|
/cy/src/net/shopxx/dao/DictDao.java
|
UTF-8
| 272
| 1.726563
| 2
|
[] |
no_license
|
package net.shopxx.dao;
import java.util.List;
import net.shopxx.entity.Dict;
/**
* Dao - 数据字典
*
*
*
*/
public interface DictDao extends BaseDao<Dict, Long> {
List<Dict> findListByType(String type);
boolean valueExists(String type, String value);
}
| true
|
e0f29b3e728d901078c231f71722c06e15c3a538
|
Java
|
watanabetaka/R4A1
|
/harada/book/WEB-INF/src/dao/CouponDAO.java
|
UTF-8
| 2,023
| 2.609375
| 3
|
[] |
no_license
|
package dao;
import bean.Coupon;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.List;
import java.util.ArrayList;
public class CouponDAO extends DAO {
// 取得可能な値をデータベースから取得
public List<Coupon> search(int user_id) throws Exception {
List<Coupon> list=new ArrayList<>();
Connection con=getConnection();
PreparedStatement st=con.prepareStatement("SELECT g.get_coupon_id , c.coupon_id , s.picture_path , s.sightseeing_name , c.coupon_name , g.get_coupon_etime , c.coupon_eday FROM get_coupon as g JOIN coupon as c ON g.coupon_id = c.coupon_id JOIN sightseeing_place as s ON c.sightseeing_id = s.sightseeing_id where g.user_id = ? and c.coupon_eday >= getdate() and (g.get_coupon_etime is null or g.get_coupon_etime >= current_timestamp); delete from get_coupon as g where g.get_coupon_etime < current_timestamp ;");
st.setInt(1,user_id);
ResultSet rs=st.executeQuery(); //データベースから取得
while (rs.next()) {
Coupon p = new Coupon();
p.setGet_coupon_id(rs.getInt("get_coupon_id"));
p.setCoupon_id(rs.getInt("coupon_id"));
p.setPicture_path(rs.getString("picture_path"));
p.setSightseeing_name(rs.getString("sightseeing_name"));
p.setCoupon_name(rs.getString("coupon_name"));
p.setGet_coupon_etime(rs.getString("get_coupon_etime"));
p.setCoupon_eday(rs.getString("coupon_eday"));
list.add(p);
}
st.close();
con.close();
return list;
}
// sightseeing_id , user_id を favorite データベースへ挿入
public void update(int get_coupon_id) throws Exception {
Connection con=getConnection();
PreparedStatement st=con.prepareStatement("update get_coupon set get_coupon_stime = current_timestamp , get_coupon_etime = dateadd(minute, 30, current_timestamp) where get_coupon_id = ? ; delete from get_coupon as g where g.get_coupon_etime < current_timestamp ; ");
st.setInt(1,get_coupon_id);
st.executeUpdate();
st.close();
con.close();
}
}
| true
|
79f5d79257815d70fd5c82c1229d364a0d407d7b
|
Java
|
arubenruben/UDP-Distributed-Backup-Service
|
/src/peer/protocols/protocols/Protocol.java
|
UTF-8
| 18,599
| 2.546875
| 3
|
[] |
no_license
|
package peer.protocols.protocols;
import peer.Peer;
import peer.filesystem.ChunkInfo;
import peer.filesystem.FileInfo;
import peer.protocols.messages.Header;
import peer.protocols.messages.Message;
import peer.protocols.protocols.protocol1_0.RemoveCandidate;
import peer.utils.Constants;
import peer.utils.Logger;
import java.io.File;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
/**
* Abstract class that defines the basis of what a protocol should do
*/
public abstract class Protocol {
protected final String mcIp;
protected final int mcPort;
protected final String mdbIp;
protected final int mdbPort;
protected final Peer peer;
protected final String version;
protected final Logger log;
/**
* @param mcIp Control Channel IP
* @param mcPort Control Channel Port
* @param mdbIp DataBackup IP
* @param mdbPort DataBackup Port
* @param peer Peer reference
* @param version Protocol version
*/
public Protocol(String mcIp, int mcPort, String mdbIp, int mdbPort, Peer peer, String version) {
this.mcIp = mcIp;
this.mcPort = mcPort;
this.mdbIp = mdbIp;
this.mdbPort = mdbPort;
this.peer = peer;
this.version = version;
this.log = new Logger(peer.getId());
}
// Default implementations
//sendHeartbeat and recievedHeartbeat don't have implementation in Protocol 1.0,
//but are overriden and implemented in Protocol 1.1
public void sendHeartbeat() {
}
public void receivedHeartbeat(Message message) {
}
//Interface for Request
/**
* backups a file with a specific filename with a desired replication level. If he doesnt achieve that he simples deletes.
*
* @param filename
* @param replicationLevel
*/
public abstract void backup(String filename, int replicationLevel);
/**
* Restore the file with filename provided
*
* @param filename
*/
public abstract void restore(String filename);
/**
* Deletes the file with a fileId provided
*
* @param fileId
*/
public abstract void delete(String fileId);
/**
* Specify the maximum disk size to the value of the parameter
*
* @param availableDiskSpace
*/
public void reclaim(int availableDiskSpace) {
log.info("Request for reclaim with size " + availableDiskSpace);
peer.getFileSystem().setCapacity(availableDiskSpace);
log.info("Capacity set to " + peer.getFileSystem().getCapacity());
if (peer.getFileSystem().getExternalFiles().isEmpty()) {
log.info("No external files - nothing to delete");
return;
}
if (availableDiskSpace == 0) {
log.info("Notifying peers about the space reclaiming..");
for (String fileId : peer.getFileSystem().getExternalFiles().keySet()) {
for (Integer chunkNum : peer.getFileSystem().getExternalFiles().get(fileId).keySet()) {
sendRemovedMessage(fileId, chunkNum);
log.info("Sent msg REMOVED for file " + fileId + "--> " + chunkNum);
try {
peer.getFileSystem().deleteChunks(fileId);
} catch (IOException e) {
log.error("Error deleting chunks of file " + fileId);
}
}
}
}
log.info("Partial space reclaiming");
PriorityQueue<RemoveCandidate> candidates = createRemoveCandidates();
log.info("Currently have " + peer.getFileSystem().getOccupiedSpace() + " occupied space out of MAX " + peer.getFileSystem().getCapacity());
while (peer.getFileSystem().getOccupiedSpace() - peer.getFileSystem().getCapacity() > 0) {
log.info("Selecting the best chunk to remove..");
RemoveCandidate best = candidates.remove();
log.info("Notifying the peers about the chunk removal");
sendRemovedMessage(best.getFileId(), best.getChunkNumber());
log.info("Sent msg REMOVED for file " + best.getFileId() + "--> " + best.getChunkNumber());
try {
log.info("Removing the chunk " + best.getChunkNumber() + " from file " + best.getFileId());
peer.getFileSystem().deleteChunk(best.getFileId(), best.getChunkNumber());
peer.getFileSystem().deleteEmptyFolders();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* @return The Current State of the Peer
*/
public String state() {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("--------------------------------------------------------\n");
if (peer.getFileSystem().getFilenameFileInfo().isEmpty()) {
stringBuilder.append("No Files Stored\n");
} else {
stringBuilder.append("Files Stored:\n");
for (FileInfo fileInfo : peer.getFileSystem().getFilenameFileInfo().values()) {
stringBuilder.append("--------------------------------\n");
stringBuilder.append("Filename: ").append(fileInfo.getFileName()).append("\n");
stringBuilder.append("FileId: ").append(fileInfo.getFileId()).append("\n");
stringBuilder.append(" Desired replication Degree:").append(fileInfo.getDesiredReplicationLevel()).append("\n");
ConcurrentHashMap<Integer, ChunkInfo> chunkNumChunkInfo = peer.getFileSystem().getInternalFiles().get(fileInfo.getFileId());
stringBuilder.append(" Chunks of the file:\n");
for (Integer key : chunkNumChunkInfo.keySet()) {
stringBuilder.append(" ------------------------------\n");
Integer perceivedReplicationLevel = chunkNumChunkInfo.get(key).getPerceivedReplicationLevel();
stringBuilder.append(" Chunk Id: ").append(key).append("\n");
stringBuilder.append(" Perceived Replication Degree: ").append(perceivedReplicationLevel).append("\n");
stringBuilder.append(" ------------------------------\n");
}
}
}
if (peer.getFileSystem().getExternalFiles().isEmpty())
stringBuilder.append("\nNo Chunks Stored\n");
else {
stringBuilder.append("\nChunks Stored\n");
for (String key : peer.getFileSystem().getExternalFiles().keySet()) {
ConcurrentHashMap<Integer, ChunkInfo> chunkHashMap = peer.getFileSystem().getExternalFiles().get(key);
stringBuilder.append("--------------------------------\n");
stringBuilder.append("File Id: ").append(key).append("\n");
for (Integer chunkNo : chunkHashMap.keySet()) {
stringBuilder.append(" Id: ").append(chunkNo).append("\n");
stringBuilder.append(" Size: ").append(chunkHashMap.get(chunkNo).getSize()).append("\n");
stringBuilder.append(" Desired Replication Degree: ").append(chunkHashMap.get(chunkNo).getDesiredReplicationLevel()).append("\n");
stringBuilder.append(" Perceived Replication Degree: ").append(chunkHashMap.get(chunkNo).getPerceivedReplicationLevel()).append("\n\n");
}
}
}
stringBuilder.append("--------------------------------\n");
stringBuilder.append("\n").append("Free Space: ").append(peer.getFileSystem().getCapacity() - peer.getFileSystem().getOccupiedSpace()).append("\n");
stringBuilder.append("Storage Capacity: ").append(peer.getFileSystem().getCapacity());
return stringBuilder.toString();
}
private PriorityQueue<RemoveCandidate> createRemoveCandidates() {
PriorityQueue<RemoveCandidate> candidates = new PriorityQueue<>();
for (String fileId : peer.getFileSystem().getExternalFiles().keySet()) {
for (Integer chunkNum : peer.getFileSystem().getExternalFiles().get(fileId).keySet()) {
ChunkInfo chunkInfo = peer.getFileSystem().getExternalFiles().get(fileId).get(chunkNum);
int diff = chunkInfo.getPerceivedReplicationLevel() - chunkInfo.getDesiredReplicationLevel();
candidates.add(new RemoveCandidate(fileId, chunkNum, diff));
}
}
return candidates;
}
public Peer getPeer() {
return peer;
}
public String getVersion() {
return version;
}
/**
* Send the message for the specified IP and Port in a multicast UDP way.
*
* @param message
* @param ipAddress
* @param port
* @throws IOException
*/
public void sendDatagram(Message message, String ipAddress, int port) throws IOException {
byte[] byteArray = message.toByteArray();
MulticastSocket multicastSocket = new MulticastSocket(port);
DatagramPacket datagramPacket = new DatagramPacket(byteArray, byteArray.length, InetAddress.getByName(ipAddress), port);
multicastSocket.send(datagramPacket);
}
/**
* The following methods Process a RECEIVED/SEND the message type specified in their header
* @param request Request received.
*/
//Received
public abstract void receivedPutChunk(Message request);
public abstract void receivedGetChunk(Message request);
public abstract void receivedDelete(Message request);
public abstract void receivedStored(Message request);
public Optional<Message> receivedRemoved(Message notification) {
if (peer.getId() == notification.getHeader().getSenderId()) {
return Optional.empty();
}
String fileId = notification.getHeader().getFileId();
int chunkNum = notification.getHeader().getChunkNo();
// Update environment
if (peer.getFileSystem().getEnvironmentFilesRepLevel().containsKey(fileId)) {
if (peer.getFileSystem().getEnvironmentFilesRepLevel().get(fileId).containsKey(chunkNum)) {
peer.getFileSystem().getEnvironmentFilesRepLevel().get(fileId).get(chunkNum).decrementReplicationLevel();
try {
peer.getFileSystem().writeEnvironmentFilesRepLevelToDisk();
} catch (IOException e) {
e.printStackTrace();
}
}
}
ConcurrentHashMap<Integer, ChunkInfo> externalChunkNumChunkInfo = peer.getFileSystem().getExternalFiles().get(fileId);
// If I'm keeping track of that file and also keeping track of that chunk of that file, then update replication level
if (externalChunkNumChunkInfo != null && externalChunkNumChunkInfo.get(chunkNum) != null) {
log.info("Updating chunk of a file replication level..");
int updatedLevel = updateReplicationLevel(fileId, chunkNum);
int desiredReplicationLevel = externalChunkNumChunkInfo.get(chunkNum).getDesiredReplicationLevel();
log.info("Current: " + updatedLevel + ", Desired: " + desiredReplicationLevel);
if (updatedLevel < desiredReplicationLevel) {
log.info("Chunk " + chunkNum + "'s replication level dropped below desired..");
try {
byte[] buffer = peer.getFileSystem().readChunk(fileId, chunkNum);
Message message = new Message(
new Header(getVersion(), peer.getId(), fileId, chunkNum, desiredReplicationLevel, "PUTCHUNK"),
buffer
);
log.info("Sending PUTCHUNK for chunk " + chunkNum);
peer.getThreadPool().schedule(() -> sendPutChunkHelperReclaim(message, 1), 0, TimeUnit.SECONDS);
} catch (IOException e) {
e.printStackTrace();
log.error("Error Opening File");
}
}
try {
peer.getFileSystem().writeInternalFileMetadataToDisk();
} catch (IOException e) {
e.printStackTrace();
}
}
return Optional.empty();
}
public abstract void receivedChunk(Message message);
//Issued
public void sendStored(Message request) {
Message reply = new Message(new Header(request.getHeader().getProtocolVersion(), peer.getId(), request.getHeader().getFileId(), request.getHeader().getChunkNo(), "STORED"));
Random random = new Random();
peer.getThreadPool().schedule(() -> {
try {
sendDatagram(reply, mcIp, mcPort);
} catch (IOException e) {
log.error("Unable to reply STORED message");
}
}, random.nextInt(Constants.PUTCHUNK_MAX_TIMEOUT), TimeUnit.MILLISECONDS);
}
public abstract void sendChunk(Message request);
public void sendRemovedMessage(String fileId, Integer chunkNum) {
Message message = new Message(new Header(version, peer.getId(), fileId, chunkNum, "REMOVED"));
try {
byte[] byteArray = message.toByteArray();
MulticastSocket multicastSocket = new MulticastSocket(mcPort);
DatagramPacket datagramPacket = new DatagramPacket(byteArray, byteArray.length, InetAddress.getByName(mcIp), mcPort);
multicastSocket.send(datagramPacket);
} catch (IOException e) {
log.error("Unable to send the REMOVED message for reclaim");
}
}
/**
* This method sends a putchunk request until N times or until the replication level of all chunks is achieved. Runs concurrently in a Scheduled Thread for a random time
*
* @param request Request to send
* @param attempt Attempt Number of the request send
*/
//Helpers
protected void sendPutChunkHelper(Message request, int attempt) {
Integer perceivedReplicationDegree = peer.getFileSystem().getInternalFiles().get(request.getHeader().getFileId()).get(request.getHeader().getChunkNo()).getPerceivedReplicationLevel();
if (perceivedReplicationDegree >= request.getHeader().getDesiredReplicationLevel()) {
return;
}
if (attempt > Constants.MAX_PUTCHUNK_ATTEMPTS) {
log.error("Backup request timeout for chunk:" + request.getHeader().getChunkNo() + " - Got Replication:" + perceivedReplicationDegree);
// Delete chunks on the peers who managed to put them
log.info("Sending DELETE request to the peers for unsuccessful backed up file");
delete(request.getHeader().getFileId());
log.info("Cleanup metadata..");
for (Map.Entry<String, FileInfo> entry : peer.getFileSystem().getFilenameFileInfo().entrySet()) {
if (entry.getValue().getFileId().equals(request.getHeader().getFileId())) {
peer.getFileSystem().getFilenameFileInfo().remove(entry.getKey());
}
}
peer.getFileSystem().getInternalFiles().remove(request.getHeader().getFileId());
try {
peer.getFileSystem().writeInternalFileMetadataToDisk();
} catch (IOException e) {
e.printStackTrace();
}
return;
}
try {
sendDatagram(request, mdbIp, mdbPort);
} catch (IOException e) {
log.error("Opening socket but attempt of replication continues");
}
peer.getThreadPool().schedule(() -> sendPutChunkHelper(request, attempt + 1), (long) (Math.pow(2, attempt) * Constants.STORED_START_LISTENING_TIMEOUT), TimeUnit.SECONDS);
}
protected void sendPutChunkHelperReclaim(Message request, int attempt) {
Integer perceivedReplicationDegree = peer.getFileSystem().getExternalFiles().get(request.getHeader().getFileId()).get(request.getHeader().getChunkNo()).getPerceivedReplicationLevel();
if (perceivedReplicationDegree >= request.getHeader().getDesiredReplicationLevel()) {
return;
}
if (attempt > Constants.MAX_PUTCHUNK_ATTEMPTS) {
log.error("Backup request timeout for chunk:" + request.getHeader().getChunkNo() + " - Got Replication:" + perceivedReplicationDegree);
// Delete chunks on the peers who managed to put them
log.info("Sending DELETE request to the peers for unsuccessful backed up file");
delete(request.getHeader().getFileId());
log.info("Cleanup metadata..");
for (Map.Entry<String, FileInfo> entry : peer.getFileSystem().getFilenameFileInfo().entrySet()) {
if (entry.getValue().getFileId().equals(request.getHeader().getFileId())) {
peer.getFileSystem().getFilenameFileInfo().remove(entry.getKey());
}
}
peer.getFileSystem().getInternalFiles().remove(request.getHeader().getFileId());
try {
peer.getFileSystem().writeInternalFileMetadataToDisk();
} catch (IOException e) {
e.printStackTrace();
}
return;
}
try {
sendDatagram(request, mdbIp, mdbPort);
} catch (IOException e) {
log.error("Opening socket but attempt of replication continues");
}
peer.getThreadPool().schedule(() -> sendPutChunkHelperReclaim(request, attempt + 1), (long) (Math.pow(2, attempt) * Constants.STORED_START_LISTENING_TIMEOUT), TimeUnit.SECONDS);
}
public abstract void receivedDeleteAck(Message request);
private int updateReplicationLevel(String fileId, Integer chunkNum) {
ConcurrentHashMap<Integer, ChunkInfo> chunkNumChunkInfo = peer.getFileSystem().getExternalFiles().get(fileId);
ChunkInfo chunkInfo = chunkNumChunkInfo.get(chunkNum);
chunkInfo.decrementReplicationLevel();
chunkNumChunkInfo.put(chunkNum, chunkInfo);
return chunkInfo.getPerceivedReplicationLevel();
}
private File getFromInternal(String filename) {
for (File file : peer.getFileSystem().getInternalFilesDir().listFiles()) {
if (file.getName().equals(filename)) {
return file;
}
}
return null;
}
}
| true
|
a36dd7eb7a482cf42cd9fc30024518c205f7c632
|
Java
|
cha63506/CompSecurity
|
/JC-Penney/src/com/android/slyce/a/c/c/m.java
|
UTF-8
| 945
| 1.664063
| 2
|
[] |
no_license
|
// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.geocities.com/kpdus/jad.html
// Decompiler options: braces fieldsfirst space lnc
package com.android.slyce.a.c.c;
import com.android.slyce.a.bj;
import java.io.IOException;
import java.nio.ByteOrder;
import java.util.zip.CRC32;
// Referenced classes of package com.android.slyce.a.c.c:
// h, i
class m
implements bj
{
final i a;
m(i j)
{
a = j;
super();
}
public volatile void a(Object obj)
{
a((byte[])obj);
}
public void a(byte abyte0[])
{
short word0 = h.a(abyte0, 0, ByteOrder.LITTLE_ENDIAN);
if ((short)(int)a.e.e.getValue() != word0)
{
a.e.a(new IOException("CRC mismatch"));
return;
} else
{
a.e.e.reset();
a.e.d = false;
a.e.a(a.c);
return;
}
}
}
| true
|
e17bf950df3c82e0ae52c9499b0514dbf0937117
|
Java
|
eduardocezarinossp/trab-final-tsi
|
/bkp/src/crud/CRUD_pessoas.java
|
UTF-8
| 1,396
| 2.875
| 3
|
[] |
no_license
|
package crud;
import java.sql.ResultSet;
import java.util.ArrayList;
import conexao.Conexao;
import objetos.Pessoa;
public class CRUD_pessoas {
public String cadastra(Pessoa p) {
String sql = "INSERT INTO cad_pessoas( nome, cpf) VALUES( '"+p.getNome()+"', '"+p.getCpf()+"')";
Conexao c = new Conexao();
c.insere(sql);
return "ok";
}
public ArrayList<Pessoa> readAll(Pessoa p1){
ArrayList<Pessoa> lista = new ArrayList<Pessoa>();
String sql = "SELECT * from cad_pessoas";
Conexao c = new Conexao();
try {
ResultSet res = c.read(sql);
while(res.next()) {
Pessoa p = new Pessoa();
p.setNome(res.getString("nome"));
p.setCpf(res.getString("cpf"));
lista.add(p);
}
} catch (Exception e) {
e.printStackTrace();
}
return lista;
}
public String[] readAllString(){
String[] lista = null;
String sql = "SELECT * from cad_pessoas";
Conexao c = new Conexao();
try {
ResultSet res = c.read(sql);
int tamanho = 0;
if (res.last()) {
tamanho = res.getRow();
res.beforeFirst(); // not rs.first() because the rs.next() below will move on, missing the first element
}
lista = new String[tamanho];
int aux = 0;
while(res.next()) {
lista[aux] = res.getString("nome")+" - "+res.getInt("idcad_pessoas");
aux++;
}
} catch (Exception e) {
e.printStackTrace();
}
return lista;
}
}
| true
|
67f97db3a904d0347fba1af735629e27c9a945a0
|
Java
|
NimaSeyfi/JavaSocial
|
/src/SERVER/ServerUp.java
|
UTF-8
| 8,985
| 2.109375
| 2
|
[] |
no_license
|
package SERVER;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.LinkedList;
import javafx.application.Application;
import javafx.collections.ObservableList;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonType;
import javafx.scene.control.PasswordField;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.ButtonBar.ButtonData;
import javafx.scene.control.ScrollPane.ScrollBarPolicy;
import javafx.scene.effect.ColorInput;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.Background;
import javafx.scene.layout.BackgroundFill;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.CornerRadii;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Pane;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.paint.ImagePattern;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Line;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.stage.Stage;
public class ServerUp extends Application{
public static ArrayList<Profile> profiles=new ArrayList<Profile>();
public Scene serverScene;
Text usern=new Text();
ServerSocket serverSocket;
Socket socket;
ServerMainGUI smg;
public void start(Stage stage) throws Exception {
}
public Scene getScene(){
Thread th=new Thread(new Runnable() {
public void run() {
Font font1=new Font("Dolphian", 20);
Font font2=new Font("2 Arabic Style", 15);
Font font3=new Font("Dolphian", 45);
Font font4=new Font("Tw Cen MT", 18);
Font font5=new Font("Tw Cen MT", 14);
File file = new File("src/LOGO/icon.png");
final Image icon = new Image(file.toURI().toString());
int TX=0;
int TY=0;
// while(true){
Pane group=new Pane();
for(int i=0;i<profiles.size();i++){
if(i==0){
TX=160;
TY=70;
}
try {
Image onOff;
if(profiles.get(i).online){
onOff = new Image(new FileInputStream("src/icons/online.png"));
}else{
onOff = new Image(new FileInputStream("src/icons/offline.png"));
}
ImageView iv=new ImageView(onOff);
iv.setFitHeight(30);
iv.setFitWidth(30);
iv.setX(TX-140);
iv.setY(TY-20);
group.getChildren().add(iv);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Text t=new Text(profiles.get(i).getName());
t.setX(TX);
t.setY(TY);
t.setFont(font4);
Button scg=new Button("SCG");
scg.setLayoutX(TX+520);
scg.setLayoutY(TY-20);
scg.setFont(font5);
scg.setMaxSize(110, 10);
scg.wrapTextProperty();
final int index=i;
scg.setOnMouseClicked(new EventHandler<Event>() {
@Override
public void handle(Event arg0) {
// System.out.println(profiles.get(0).getGraph().source.followings.get(0).profile.
//getGraph().source.followings.get(0).profile.getName()
// );
Alert alert = new Alert(AlertType.INFORMATION);
alert.setResizable(false);
alert.setTitle("SCG");
alert.setHeaderText("Strongly Connected Graph");
alert.setContentText(" ");
VBox vbox=new VBox();
for(int k=0;k<profiles.get(index).getGraph().source.followings.size();k++){
System.out.println(profiles.get(index).getGraph().source.followings.size());
System.out.println(profiles.get(index).getGraph().source.followings.get(k).profile
.getGraph().source.followings.size());
for(int j=0;j<profiles.get(index).followers.size();j++){
if(profiles.get(index).followers.get(j).getName()
.equals(
profiles.get(index).getGraph().source.followings.get(k).profile.getName()
)){
System.out.println(profiles.get(index).getName()+"--->"
+profiles.get(index).getGraph().source.followings.get(k).profile
.getGraph().source.profile.getName());
// System.out.println("-"+profiles.get(index).getGraph().source.followings.get(k).profile.getName());
Pane p=new Pane();
p.setMinSize(500, 50);
p.setMaxSize(500, 50);
Text t=new Text();
t.setX(190);
t.setY(20);
t.setText(profiles.get(index).getName()+"<===>"
+profiles.get(index).getGraph().source.followings.get(k).profile
.getGraph().source.profile.getName());
p.getChildren().add(t);
vbox.getChildren().add(p);
}
}
}
ScrollPane scrollPane = new ScrollPane();
scrollPane.setContent(vbox);
scrollPane.setHbarPolicy(ScrollBarPolicy.NEVER);
alert.getDialogPane().setContent(scrollPane);
Stage stage2 = (Stage) alert.getDialogPane().getScene().getWindow();
stage2.getIcons().add(icon); // To add an icon
alert.showAndWait();
}
});
group.getChildren().add(scg);
Line line=new Line();
line.setStartX(0);
line.setStartY(TY+45);
line.setEndX(900);
line.setEndY(TY+45);
line.setStrokeWidth(1);
line.setStyle("-fx-stroke:#e0e0e0");
group.getChildren().add(line);
ImagePattern prof_pic;
try {
prof_pic = new ImagePattern(new Image(new FileInputStream(profiles.get(i).getIcon())));
Circle circle = new Circle(25);
circle.setCenterX(TX-60);
circle.setCenterY(TY-5);
circle.setFill(prof_pic);
group.getChildren().addAll(circle);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
TY=TY+100;
group.getChildren().add(t);
}
// bp.setCenter(vbox2);
ScrollPane scrollPane = new ScrollPane();
scrollPane.setContent(group);
scrollPane.setBackground(new Background(new BackgroundFill(null, CornerRadii.EMPTY, Insets.EMPTY)));
scrollPane.setHbarPolicy(ScrollBarPolicy.NEVER);
Scene scene=new Scene(scrollPane,800,800);
serverScene=scene;
}
//}
});
th.run();
return serverScene;
}
public void addCenter(final BorderPane bp){
new Thread(new Runnable() {
@Override
public void run() {
}
}).start();
}
public void serverOn() throws Exception{//run server method
connect();
//loadProfiles();
}
public void connect() throws Exception{
Thread connectThread=new Thread(new Runnable() {
public void run() {
try {
serverSocket=new ServerSocket(1234);
int count = 0;
while(true){
System.out.println("waiting for client. . .");
socket=serverSocket.accept();
ObjectOutputStream ObjectoutputStream=
ObjectoutputStream = new ObjectOutputStream(socket.getOutputStream());
ObjectInputStream ObjectinputStream=
ObjectinputStream = new ObjectInputStream(socket.getInputStream());
count++;
System.out.println(count);
ClientWorks cw=new ClientWorks(socket,ObjectoutputStream,ObjectinputStream,smg);
Thread t=new Thread(cw);
t.start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
});
connectThread.start();
}
public static void loadProfiles() throws IOException, ClassNotFoundException {
profiles.clear();
FileInputStream fi = new FileInputStream(new File("src/SERVER/_PROFILES.txt"));
ObjectInputStream oi = new ObjectInputStream(fi);
profiles= (ArrayList<Profile>) oi.readObject();
}
public static void saveProfiles() throws IOException{
FileOutputStream f = new FileOutputStream(new File("src/SERVER/_PROFILES.txt"));
ObjectOutputStream o = new ObjectOutputStream(f);
o.writeObject(profiles);
}
private static Profile findProfile(String name) {
for(int i=0;i<ServerUp.profiles.size();i++){
if(ServerUp.profiles.get(i).name.equals(name)){
return ServerUp.profiles.get(i);
}
}
return null;
}
private static Post findPost(long id) {
for(int i=0;i<ServerUp.profiles.size();i++){
for(int j=0;j<ServerUp.profiles.get(i).getPosts().size();j++){
if(ServerUp.profiles.get(i).getPosts().get(j).getId()==id){
return ServerUp.profiles.get(i).getPosts().get(j);
}
}
}
return null;
}
}
| true
|
c1a366b975112986f11766f6022c0db0122b3c10
|
Java
|
seaco-asia/SEACO_Neuropsych
|
/app/src/main/java/com/seaco/seaconeuropsych/prospective_initial.java
|
UTF-8
| 6,431
| 1.976563
| 2
|
[] |
no_license
|
package com.seaco.seaconeuropsych;
import android.content.Context;
import android.content.Intent;
import android.os.Environment;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.text.Html;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.TextView;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import java.io.File;
import java.io.IOException;
import java.util.Random;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import uk.co.chrisjenx.calligraphy.CalligraphyContextWrapper;
public class prospective_initial extends ActionBarActivity {
public static int shape; //store shape for this session
public static int fakeShape; //the decoy shape for this session
public static long start_time; //start timer
public final static String filename = String.valueOf(System.currentTimeMillis()) + ".xml";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Hide title bar
//supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.prospective_initial);
//initialise start timer
start_time = System.currentTimeMillis();
// Generate random shape from 1-4
Random r = new Random();
shape = r.nextInt(3) + 1;
String shapeName = null;
// get shape name from string.xml, and apply bold+underline
// also generates a decoy shape
switch (shape) {
case 1:
shapeName = "<b><u>" + getResources().getString(R.string.shape1) + "</u></b>";
fakeShape = 2;
break;
case 2:
shapeName = "<b><u>" + getResources().getString(R.string.shape2) + "</u></b>";
fakeShape = 3;
break;
case 3:
shapeName = "<b><u>" + getResources().getString(R.string.shape3) + "</u></b>";
fakeShape = 4;
break;
case 4:
shapeName = "<b><u>" + getResources().getString(R.string.shape4) + "</u></b>";
fakeShape = 1;
break;
}
// Initialise textview
TextView txtview = (TextView)findViewById(R.id.prospective_initial_text);
txtview.setText(Html.fromHtml(getString(R.string.prospective_initial_text, "<br>", shapeName)));
// setup Images
ImageView img1= (ImageView) findViewById(R.id.imageView_1);
img1.setImageResource(R.drawable.octagon_red);
ImageView img2= (ImageView) findViewById(R.id.imageView_2);
img2.setImageResource(R.drawable.circle_orange);
ImageView img3= (ImageView) findViewById(R.id.imageView_3);
img3.setImageResource(R.drawable.square_blue);
ImageView img4= (ImageView) findViewById(R.id.imageView_4);
img4.setImageResource(R.drawable.triangle_green);
}
@Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(new CalligraphyContextWrapper(newBase));
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_prospective_initial, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void nextActivity(View view) {
// when Next is clicked, start next activity
writeXML();
Intent intent = new Intent(this, pair_intro.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
//intent.putExtra("Answer", shape);
startActivity(intent);
finish();
overridePendingTransition(0, 0);
}
private void writeXML() {
try {
System.out.println("Start");
String filepath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + "SEACO" + "/" + filename;
File file = new File(filepath);
boolean fileCreated = file.createNewFile();
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.newDocument();
//Document doc = docBuilder.parse("file://" + filepath);
Element root = doc.createElement("seaco");
doc.appendChild(root);
Element shape_tag = doc.createElement("shape");
root.appendChild(shape_tag);
Element initialAnswer = doc.createElement("initialAnswer");
shape_tag.appendChild(initialAnswer);
initialAnswer.appendChild(doc.createTextNode(String.valueOf(shape)));
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File(filepath));
StreamResult resultx = new StreamResult(System.out);
transformer.transform(source, result);
transformer.transform(source, resultx);
System.out.println("Done");
} catch (ParserConfigurationException pce) {
pce.printStackTrace();
} catch (TransformerException tfe) {
tfe.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
@Override
public void onBackPressed() { // Disable hardware back button
}
}
| true
|
ec0515c743f39f07f0b19a9af9eee333f08630c3
|
Java
|
Tbichan/Android
|
/main/java/com/example/tbichan/syaroescape/OpenGL/GlRendererBase.java
|
UTF-8
| 652
| 1.835938
| 2
|
[] |
no_license
|
package com.example.tbichan.syaroescape.OpenGL;
import android.content.Context;
import android.opengl.GLSurfaceView;
import android.opengl.GLU;
import com.example.tbichan.syaroescape.R;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
public abstract class GlRendererBase implements GLSurfaceView.Renderer {
protected Context context;
//2次元スプライト
//SampleSprite face_img = new SampleSprite();
public GlRendererBase(Context _context) {
context = _context;
}
}
| true
|
de45dfeb1f713db29fc4288f0e3ce93d306f2607
|
Java
|
JinHong-H/insurance-back
|
/src/main/java/cn/wghtstudio/insurance/service/impl/GetOrderInfo.java
|
UTF-8
| 3,767
| 2.015625
| 2
|
[] |
no_license
|
package cn.wghtstudio.insurance.service.impl;
import cn.wghtstudio.insurance.dao.entity.Order;
import cn.wghtstudio.insurance.dao.entity.User;
import cn.wghtstudio.insurance.service.entity.GetInsuranceListItem;
import cn.wghtstudio.insurance.util.FormatDate;
import cn.wghtstudio.insurance.util.LicensePlateWhenNewFactory;
import cn.wghtstudio.insurance.util.excel.ExcelColumn;
import lombok.Builder;
import lombok.Data;
import org.apache.poi.ss.usermodel.Workbook;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;
@Data
@Builder
class BaseExportColumnItem {
@ExcelColumn(value = "序号", column = 1)
private String number;
@ExcelColumn(value = "车主", column = 2)
private String owner;
@ExcelColumn(value = "起保时间", column = 3)
private String startTime;
@ExcelColumn(value = "车辆类型", column = 4)
private String carType;
@ExcelColumn(value = "支付方式", column = 5)
private String payType;
@ExcelColumn(value = "车牌号", column = 6)
private String licensePlate;
@ExcelColumn(value = "车架号", column = 7)
private String frame;
@ExcelColumn(value = "发动机号", column = 8)
private String engine;
@ExcelColumn(value = "地址", column = 9)
private String address;
@ExcelColumn(value = "保单号", column = 10)
private String policy;
}
public abstract class GetOrderInfo {
static GetInsuranceListItem getGetInsuranceListItem(Order item, GetInsuranceListItem.GetInsuranceListItemBuilder itemBuilder) {
itemBuilder.id(item.getId()).
payType(item.getPayment().getName()).
carType(item.getCarType().getName()).
startTime(FormatDate.getFormatDate(item.getStartTime())).
createAt(FormatDate.getFormatDateTime(item.getCreateAt()));
if (item.getIdCard() != null) {
itemBuilder.owner(item.getIdCard().getName());
} else if (item.getBusinessLicense() != null) {
itemBuilder.owner(item.getBusinessLicense().getName());
}
if (item.getDrivingLicense() != null) {
itemBuilder.licensePlate(item.getDrivingLicense().getPlateNumber());
} else if (item.getCertificate() != null) {
itemBuilder.licensePlate(LicensePlateWhenNewFactory.getLicensePlateWhenNew(item.getCertificate().getEngine()));
}
if (item.getPolicy() != null) {
itemBuilder.policy(item.getPolicy().getNumber());
}
if (item.getOverInsurancePolicy() != null) {
itemBuilder.overPolicy(item.getOverInsurancePolicy().getUrl());
}
return itemBuilder.build();
}
static void writeToResponse(HttpServletResponse response, Workbook wb) throws IOException {
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setHeader("Content-disposition", "attachment;filename=export.xlsx");
response.flushBuffer();
OutputStream outputStream = response.getOutputStream();
wb.write(outputStream);
wb.close();
outputStream.flush();
outputStream.close();
}
public abstract List<Order> getALLOrderList(User user, Map<String, Object> params);
public abstract List<GetInsuranceListItem> processListItem(User user, Map<String, Object> params);
public abstract Order getOrderDetail(User user, Map<String, Object> params);
public abstract Integer getALLOrderListCount(User user, Map<String, Object> params);
public abstract void exportExcelItem(HttpServletResponse response, User user, Map<String, Object> params) throws IOException;
}
| true
|
4dea3fdab649f1018ee6815946aabfc60f3d4ed0
|
Java
|
HurmaH/JavaCore
|
/src/day7/Main.java
|
UTF-8
| 669
| 3.203125
| 3
|
[] |
no_license
|
package day7;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
//WRITE YOUR CODE HERE:
int num1, num2, num3, sum;
Scanner input = new Scanner (System.in);
System.out.println("Enter 3 numbers:");
num1= input.nextInt();
num2= input.nextInt();
num3= input.nextInt();
sum = num1+num2+num3;
System.out.println("Sum of numbers: "+sum);
int numberOfStudents = 300;
String batchName = "Spartans";
String fullName = numberOfStudents + batchName;
System.out.println(fullName);
input.close();
}
}
| true
|
20e3156dfae2221b2f9973d20666b251dd49efbc
|
Java
|
norbo112/Edzesnaplov3
|
/app/src/main/java/aa/droid/norbo/projects/edzesnaplo3/mvvm/data/api/GyakorlatRepository.java
|
UTF-8
| 571
| 1.820313
| 2
|
[] |
no_license
|
package aa.droid.norbo.projects.edzesnaplo3.mvvm.data.api;
import androidx.lifecycle.LiveData;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import aa.droid.norbo.projects.edzesnaplo3.mvvm.db.entities.Gyakorlat;
public interface GyakorlatRepository {
LiveData<List<Gyakorlat>> getAll();
LiveData<List<Gyakorlat>> getByCsoport(List<String> izomcsoportok);
void delete(Gyakorlat gyakorlat);
void insert(Gyakorlat gyakorlat);
void update(Gyakorlat gyakorlat);
CompletableFuture<List<Gyakorlat>> getGyakorlatList();
}
| true
|
bc04b783821a88273c59ab3217dcf56ed5df3e9b
|
Java
|
PengjuGao/java-framework-generation
|
/platform_core/src/main/java/com/platform/core/service/impl/TbCategoryServiceImpl.java
|
UTF-8
| 591
| 1.640625
| 2
|
[] |
no_license
|
/**
* @author gaopj
*
*/
package com.platform.core.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.platform.core.dao.TbCategoryMapper;
import com.platform.core.po.TbCategory;
import com.platform.core.vo.TbCategoryVo;
import com.platform.base.service.impl.BaseServiceImpl;
import com.platform.core.service.TbCategoryService;
@Service
public class TbCategoryServiceImpl extends BaseServiceImpl<TbCategory, TbCategoryVo> implements TbCategoryService {
@Autowired
private TbCategoryMapper mapper;
}
| true
|
f847cef998699307e0f6bce9ec7a7c861876f7df
|
Java
|
lxqgithub/learn-netty4
|
/src/main/java/com/flydean30/http2client/CustHttp2Client.java
|
UTF-8
| 5,556
| 2.203125
| 2
|
[] |
no_license
|
package com.flydean30.http2client;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.*;
import io.netty.handler.codec.http2.Http2SecurityUtil;
import io.netty.handler.codec.http2.HttpConversionUtil;
import io.netty.handler.ssl.*;
import io.netty.handler.ssl.ApplicationProtocolConfig.Protocol;
import io.netty.handler.ssl.ApplicationProtocolConfig.SelectedListenerFailureBehavior;
import io.netty.handler.ssl.ApplicationProtocolConfig.SelectorFailureBehavior;
import io.netty.handler.ssl.util.InsecureTrustManagerFactory;
import io.netty.util.AsciiString;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.TimeUnit;
import static io.netty.buffer.Unpooled.wrappedBuffer;
import static io.netty.handler.codec.http.HttpMethod.GET;
import static io.netty.handler.codec.http.HttpMethod.POST;
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;
/**
* 一个使用HTTP1-style InboundHttp2ToHttpAdapter方式发送HTTP2 frames的客户端
*/
@Slf4j
public final class CustHttp2Client {
static final boolean SSL = true;
static final String HOST = System.getProperty("host", "127.0.0.1");
static final int PORT = Integer.parseInt(System.getProperty("port", SSL? "8443" : "8000"));
static final String GETURL = "/";
static final String POSTURL = "/post";
static final String POSTDATA = "我是POST数据";
public static void main(String[] args) throws Exception {
// SSL配置
final SslContext sslCtx;
if (SSL) {
SslProvider provider =
SslProvider.isAlpnSupported(SslProvider.OPENSSL)? SslProvider.OPENSSL : SslProvider.JDK;
sslCtx = SslContextBuilder.forClient()
.sslProvider(provider)
.ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
// 因为我们的证书是自生成的,所以需要信任放行
.trustManager(InsecureTrustManagerFactory.INSTANCE)
.applicationProtocolConfig(new ApplicationProtocolConfig(
Protocol.ALPN,
SelectorFailureBehavior.NO_ADVERTISE,
SelectedListenerFailureBehavior.ACCEPT,
ApplicationProtocolNames.HTTP_2,
ApplicationProtocolNames.HTTP_1_1))
.build();
} else {
sslCtx = null;
}
EventLoopGroup workerGroup = new NioEventLoopGroup();
CustHttp2ClientInitializer initializer = new CustHttp2ClientInitializer(sslCtx, Integer.MAX_VALUE);
try {
// 配置client
Bootstrap b = new Bootstrap();
b.group(workerGroup);
b.channel(NioSocketChannel.class);
b.option(ChannelOption.SO_KEEPALIVE, true);
b.remoteAddress(HOST, PORT);
b.handler(initializer);
Channel channel = b.connect().syncUninterruptibly().channel();
log.info("连接到 [" + HOST + ':' + PORT + ']');
//等待 HTTP/2 升级
CustHttp2SettingsHandler http2SettingsHandler = initializer.settingsHandler();
http2SettingsHandler.awaitSettings(5, TimeUnit.SECONDS);
CustHttpResponseHandler responseHandler = initializer.responseHandler();
int streamId = 3;
HttpScheme scheme = SSL ? HttpScheme.HTTPS : HttpScheme.HTTP;
AsciiString hostName = new AsciiString(HOST + ':' + PORT);
log.info("发送请求...");
if (GETURL != null) {
// 创建一个get请求
FullHttpRequest request = new DefaultFullHttpRequest(HTTP_1_1, GET, GETURL, Unpooled.EMPTY_BUFFER);
request.headers().add(HttpHeaderNames.HOST, hostName);
request.headers().add(HttpConversionUtil.ExtensionHeaderNames.SCHEME.text(), scheme.name());
request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP);
request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.DEFLATE);
responseHandler.put(streamId, channel.write(request), channel.newPromise());
streamId += 2;
}
if (POSTURL != null) {
// 创建一个post请求
FullHttpRequest request = new DefaultFullHttpRequest(HTTP_1_1, POST, POSTURL,
wrappedBuffer(POSTDATA.getBytes(CharsetUtil.UTF_8)));
request.headers().add(HttpHeaderNames.HOST, hostName);
request.headers().add(HttpConversionUtil.ExtensionHeaderNames.SCHEME.text(), scheme.name());
request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP);
request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.DEFLATE);
responseHandler.put(streamId, channel.write(request), channel.newPromise());
}
channel.flush();
responseHandler.awaitResponses(5, TimeUnit.SECONDS);
log.info("HTTP/2 请求完毕");
channel.close().syncUninterruptibly();
} finally {
workerGroup.shutdownGracefully();
}
}
}
| true
|
cdcb40c040459de0e53ba3f6b4bf3dbfb7e19ddd
|
Java
|
via-He/moo_mall
|
/src/main/java/com/via/mall/controller/ProductController.java
|
UTF-8
| 1,360
| 1.84375
| 2
|
[] |
no_license
|
package com.via.mall.controller;
import com.github.pagehelper.PageInfo;
import com.via.mall.common.ApiRestResponse;
import com.via.mall.domain.ImoocMallProduct;
import com.via.mall.request.ProductListReq;
import com.via.mall.service.ImoocMallProductService;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
/**
* @author Qingqing.He
* @date 2021/1/11 16:30
* 前台商品
*/
@RestController
@RequestMapping("/product")
public class ProductController {
@Resource
ImoocMallProductService productService;
@ApiOperation("商品详情")
@GetMapping("/detail")
public ApiRestResponse detail(@RequestParam Integer id){
ImoocMallProduct productDetail = productService.selectByPrimaryKey(id);
return ApiRestResponse.success(productDetail);
}
@ApiOperation("商品列表")
@PostMapping("/list")
public ApiRestResponse list(ProductListReq productListReq){
PageInfo list = productService.list(productListReq);
return ApiRestResponse.success(list);
}
}
| true
|
521c133a4bf84f32d613f05d21ef6ea1e3fcab0b
|
Java
|
AgentForce/android
|
/app/src/main/java/manulife/manulifesop/fragment/FAGroup/clients/related/contactDetail/step2/ContactDetailStep2Contract.java
|
UTF-8
| 604
| 1.890625
| 2
|
[] |
no_license
|
package manulife.manulifesop.fragment.FAGroup.clients.related.contactDetail.step2;
import manulife.manulifesop.api.ObjectResponse.ContactActivity;
import manulife.manulifesop.base.BaseMVPView;
/**
* Created by Chick on 10/27/2017.
*/
public interface ContactDetailStep2Contract {
interface View extends BaseMVPView {
void showMenuCreateEvent();
void showMenuCreateEventUM();
void loadContactActivities(ContactActivity data);
void updateData();
}
interface Action {
void getEvents(int leadID);
void updateEventDone(int eventID);
}
}
| true
|
e748ba09b88a149ba1835b7f4673f60e55e9d4ec
|
Java
|
patryktokarski/SpringProject
|
/src/main/java/com/spring/test/dao/UserDao.java
|
UTF-8
| 347
| 2.109375
| 2
|
[] |
no_license
|
package com.spring.test.dao;
import com.spring.test.model.User;
import java.util.List;
public interface UserDao {
void create(User user);
void update(User user);
User findById(int id);
User findByEmail(String email);
List<User> getAll();
void deleteById(int id);
User userWithEmailExists(String email, User user);
}
| true
|
d654c75bee12ed6dfc862f43de0cdc03d1a805c6
|
Java
|
keepsl/keepsmis
|
/keeps-tools/src/main/java/com/keeps/tools/utils/RandomUtils.java
|
UTF-8
| 1,548
| 3.015625
| 3
|
[
"Apache-2.0"
] |
permissive
|
package com.keeps.tools.utils;
import java.util.Random;
import java.util.UUID;
public class RandomUtils {
public static long randomLong() {
return UUID.randomUUID().getMostSignificantBits();
}
public static String randomUUID() {
return UUID.randomUUID().toString().replace("-", "");
}
public static long randomABSLong() {
return Math.abs(randomLong());
}
public static String randomByYMDHMS(int n) {
String rs = DateUtils.formatNow("yyyyMMddHHmmss");
if (n > 0) {
rs = rs + randomNumByLength(n);
}
return rs;
}
public static String randomString4Int(int digit) {
Assert.isTrue(digit > 0);
Random random = new Random();
StringBuilder re = new StringBuilder(digit);
for (int i = 0; i < digit; i++) {
re.append(random.nextInt(10));
}
return re.toString();
}
public static String randomString4Letter(int digit) {
Assert.isTrue(digit > 0);
Random random = new Random();
StringBuilder re = new StringBuilder(digit);
for (int i = 0; i < digit; i++) {
boolean isBig = random.nextInt(2) == 1;
if (isBig) {
re.append((char) (random.nextInt(26) + 65));
} else {
re.append((char) (random.nextInt(26) + 97));
}
}
return re.toString();
}
public static String randomNumByLength(int length) {
StringBuffer sb = new StringBuffer();
Random random = new Random();
for (int i = 0; i < length; i++) {
sb.append(random.nextInt(10));
}
return sb.toString();
}
public static void main(String[] args) {
}
}
| true
|
e0406515e6e7e3589c836dcdbb2e377c0a6d8365
|
Java
|
paulywh/adminconfig
|
/src/com/computercenter/service/appinterface/bean/Course.java
|
UTF-8
| 2,500
| 2.09375
| 2
|
[] |
no_license
|
package com.computercenter.service.appinterface.bean;
import java.io.Serializable;
//课程
public class Course implements Serializable
{
private static final long serialVersionUID = -4280575248694307909L;
private int id;
private String name;
private String desc;
private float price;
private int flagtry;
private int settype;
private int setvalue;
private int flagcancle;
private int cancletype;
private int cancletime;
private int starttime;
private int endtime;
private int isview;//是否展示1是0否
public int getIsview()
{
return isview;
}
public void setIsview(int isview)
{
this.isview = isview;
}
public int getId()
{
return id;
}
public void setId(int id)
{
this.id = id;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public int getStarttime()
{
return starttime;
}
public void setStarttime(int starttime)
{
this.starttime = starttime;
}
public int getEndtime()
{
return endtime;
}
public void setEndtime(int endtime)
{
this.endtime = endtime;
}
public float getPrice()
{
return price;
}
public void setPrice(float price)
{
this.price = price;
}
public String getDesc()
{
return desc;
}
public void setDesc(String desc)
{
this.desc = desc;
}
public int getFlagtry()
{
return flagtry;
}
public void setFlagtry(int flagtry)
{
this.flagtry = flagtry;
}
public int getSettype()
{
return settype;
}
public void setSettype(int settype)
{
this.settype = settype;
}
public int getSetvalue()
{
return setvalue;
}
public void setSetvalue(int setvalue)
{
this.setvalue = setvalue;
}
public int getFlagcancle()
{
return flagcancle;
}
public void setFlagcancle(int flagcancle)
{
this.flagcancle = flagcancle;
}
public int getCancletype()
{
return cancletype;
}
public void setCancletype(int cancletype)
{
this.cancletype = cancletype;
}
public int getCancletime()
{
return cancletime;
}
public void setCancletime(int cancletime)
{
this.cancletime = cancletime;
}
}
| true
|
1b79cdabc1b76a9b028af1a74dcd458411d7e720
|
Java
|
giovannidefilippi/LidoOasi
|
/LidoOasi/EsameLidoOasi/src/it/unisalento/utility/PallinoVerdeOmbrellone.java
|
UTF-8
| 545
| 2.640625
| 3
|
[] |
no_license
|
package it.unisalento.utility;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Ellipse2D;
import javax.swing.JComponent;
public class PallinoVerdeOmbrellone extends JComponent
{
public void paintComponent(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
Color verde = new Color(0,255,0);
Ellipse2D cerchio = new Ellipse2D.Double(5, 5, 30, 30);
g2.setColor(verde);
g2.fill(cerchio);
g2.drawString("Libero", 40, 20);
}
}
| true
|
b0a4b2005d1f50dd8f3d42338b323fa17134f73e
|
Java
|
novas-meng/DataShow
|
/app/src/main/java/com/novas/controller/HomeController.java
|
UTF-8
| 6,496
| 2.015625
| 2
|
[] |
no_license
|
package com.novas.controller;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.AppCompatTextView;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.TextView;
import com.novas.datashow.R;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
/**
* Created by novas on 16/3/21.
*/
public class HomeController implements control
{
private static HomeController homeController;
private Activity context;
private FragmentTransaction ft;
private Hashtable<String, Fragment> fragmentHashtable=new Hashtable<>();
int[] ids=null;
View[] linearLayouts=null;
View[] textviews=null;
List<String> namelist=new ArrayList<>();
int currentindex=1;
private HomeController(Activity context)
{
this.context=context;
AppCompatActivity activity=(AppCompatActivity)context;
ft=activity.getSupportFragmentManager().beginTransaction();
}
public Context getContext()
{
return context;
}
//发出报警声
public void alarm()
{
NotificationManager nm=(NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notify2 = new Notification.Builder(context)
.setSmallIcon(R.drawable.bluetooth) // 设置状态栏中的小图片,尺寸一般建议在24×24,这个图片同样也是在下拉状态栏中所显示,如果在那里需要更换更大的图片,可以使用setLargeIcon(Bitmap
// icon)
.setTicker("TickerText:" + "您有新短消息,请注意查收!")// 设置在status
// bar上显示的提示文字
.setContentTitle("Notification Title")// 设置在下拉status
// bar后Activity,本例子中的NotififyMessage的TextView中显示的标题
.setContentText("This is the notification message")// TextView中显示的详细内容
.setNumber(1) // 在TextView的右方显示的数字,可放大图片看,在最右侧。这个number同时也起到一个序列号的左右,如果多个触发多个通知(同一ID),可以指定显示哪一个。
.getNotification(); // 需要注意build()是在API level
// 16及之后增加的,在API11中可以使用getNotificatin()来代替
notify2.flags |= Notification.FLAG_AUTO_CANCEL;
notify2.defaults = Notification.DEFAULT_ALL;
nm.notify(1, notify2);
}
public static HomeController getHomeControllerInstance(Activity context)
{
if(homeController==null)
{
homeController=new HomeController(context);
}
return homeController;
}
public void addFragment(int layoutid,String frname)
{
Fragment fr=null;
try {
Class c=Class.forName("com.novas.fragment."+frname);
fr=(Fragment)c.newInstance();
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
catch (InstantiationException e)
{
e.printStackTrace();
}
catch (IllegalAccessException e)
{
e.printStackTrace();
}
fragmentHashtable.put(frname,fr);
namelist.add(frname);
ft.add(layoutid,fr);
ft.hide(fr);
}
public void showFragment(String fragment)
{
linearLayouts=new View[fragmentHashtable.size()];
textviews=new View[linearLayouts.length];
ids=new int[fragmentHashtable.size()];
linearLayouts[0]=context.findViewById(R.id.tab1);
linearLayouts[1]=context.findViewById(R.id.tab2);
linearLayouts[2]=context.findViewById(R.id.tab3);
textviews[0]=context.findViewById(R.id.tab1text);
textviews[1]=context.findViewById(R.id.tab2text);
textviews[2]=context.findViewById(R.id.tab3text);
ids[0]=R.id.tab1;
ids[1]=R.id.tab2;
ids[2]=R.id.tab3;
tabClickListener tabClickListener=new tabClickListener();
// AppCompatActivity activity=(AppCompatActivity)context;
//ft=activity.getSupportFragmentManager().beginTransaction();
for(int i=0;i<linearLayouts.length;i++)
{
linearLayouts[i].setOnClickListener(tabClickListener);
}
ft.show(fragmentHashtable.get(fragment));
TextView textView=(TextView)context.findViewById(R.id.tab1text);
textView.setTextColor(Color.GREEN);
currentindex=namelist.indexOf(fragment);
// if(ft.)
ft.commit();
}
@Override
public void destroy() {
if(context!=null)
{
context=null;
ft=null;
homeController=null;
}
}
public void showtab(int id)
{
int index=0;
for(int i=0;i<ids.length;i++)
{
if(ids[i]==id)
{
index=i;
}
}
System.out.println("currentindex="+currentindex+"index="+index);
((TextView)textviews[index]).setTextColor(Color.GREEN);
if(index!=currentindex)
{
AppCompatActivity activity=(AppCompatActivity)context;
ft=activity.getSupportFragmentManager().beginTransaction();
((TextView)textviews[index]).setTextColor(Color.GREEN);
((TextView)textviews[currentindex]).setTextColor(Color.WHITE);
Fragment oldfragment=fragmentHashtable.get(namelist.get(currentindex));
Fragment newfragment=fragmentHashtable.get(namelist.get(index));
ft.hide(oldfragment);
ft.show(newfragment);
ft.commit();
currentindex=index;
}
}
class tabClickListener implements View.OnClickListener
{
@Override
public void onClick(View v) {
showtab(v.getId());
}
}
}
| true
|
23627db03053b6ecff7244f98cba005f7053535b
|
Java
|
NerdNu/EasyRider
|
/src/nu/nerd/easyrider/commands/HorseInfoExecutor.java
|
UTF-8
| 6,870
| 2.671875
| 3
|
[
"MIT"
] |
permissive
|
package nu.nerd.easyrider.commands;
import org.bukkit.ChatColor;
import org.bukkit.Sound;
import org.bukkit.SoundCategory;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.AbstractHorse;
import org.bukkit.entity.AnimalTamer;
import org.bukkit.entity.Llama;
import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerInteractEntityEvent;
import nu.nerd.easyrider.Ability;
import nu.nerd.easyrider.EasyRider;
import nu.nerd.easyrider.HorseEquipment;
import nu.nerd.easyrider.IPendingInteraction;
import nu.nerd.easyrider.Util;
import nu.nerd.easyrider.db.SavedHorse;
//-----------------------------------------------------------------------------
/**
* CommandExecutor implementation for the /horse-info command.
*/
public class HorseInfoExecutor extends ExecutorBase {
// ------------------------------------------------------------------------
/**
* Default constructor.
*/
public HorseInfoExecutor() {
super("horse-info", "help");
}
// ------------------------------------------------------------------------
/**
* @see org.bukkit.command.CommandExecutor#onCommand(org.bukkit.command.CommandSender,
* org.bukkit.command.Command, java.lang.String, java.lang.String[])
*/
@Override
public boolean onCommand(CommandSender sender, Command command, String alias, String[] args) {
if (!(sender instanceof Player)) {
sender.sendMessage(ChatColor.RED + "You must be in game to use this command.");
return true;
}
if (args.length == 0) {
Player player = (Player) sender;
if (player.getVehicle() instanceof AbstractHorse) {
showLevels(player, (AbstractHorse) player.getVehicle());
} else {
sender.sendMessage(ChatColor.GOLD + "Right click on an animal to show level information.");
EasyRider.PLUGIN.getState(player).setPendingInteraction(new IPendingInteraction() {
@Override
public void onPlayerInteractEntity(PlayerInteractEntityEvent event, SavedHorse savedHorse) {
showLevels(event.getPlayer(), (AbstractHorse) event.getRightClicked());
}
});
}
return true;
} else {
return false;
}
}
// ------------------------------------------------------------------------
/**
* Show the horse's hydration level to the player.
*
* @param player the player.
* @param savedHorse the horse.
*/
public static void showHydration(Player player, SavedHorse savedHorse) {
int hydration = (int) Math.round(100 * savedHorse.getHydration());
player.sendMessage(ChatColor.GOLD + "Hydration: " + (hydration < 5 ? ChatColor.RED : ChatColor.YELLOW) + hydration + "%");
}
// ------------------------------------------------------------------------
/**
* Send the player information about the current levels of the specified
* horse or the attributes of a llama.
*
* @param player the player.
* @param asbtractHorse the AbstractHorse.
*/
protected void showLevels(Player player, AbstractHorse abstractHorse) {
SavedHorse savedHorse = EasyRider.DB.findOrAddHorse(abstractHorse);
String type = Util.capitalise(Util.entityTypeName(abstractHorse));
player.sendMessage(ChatColor.GOLD + type + ": " + ChatColor.YELLOW + abstractHorse.getUniqueId());
AnimalTamer owner = abstractHorse.getOwner();
String ownerName = (owner != null) ? owner.getName() : "<no owner>";
player.sendMessage(ChatColor.GOLD + "Owner: " + ChatColor.YELLOW + ownerName);
player.sendMessage(ChatColor.GOLD + "Appearance: " +
ChatColor.WHITE + Util.getAppearance(abstractHorse) + " " +
ChatColor.YELLOW + HorseEquipment.description(HorseEquipment.bits(abstractHorse)));
if (Util.isTrainable(abstractHorse)) {
showLevel(player, EasyRider.CONFIG.SPEED, savedHorse);
showLevel(player, EasyRider.CONFIG.HEALTH, savedHorse);
showLevel(player, EasyRider.CONFIG.JUMP, savedHorse);
showHydration(player, savedHorse);
} else if (abstractHorse instanceof Llama) {
Llama llama = (Llama) abstractHorse;
showAttribute(player, EasyRider.CONFIG.SPEED, abstractHorse);
showAttribute(player, EasyRider.CONFIG.HEALTH, abstractHorse);
showAttribute(player, EasyRider.CONFIG.JUMP, abstractHorse);
player.sendMessage(ChatColor.GOLD + "Strength: " + ChatColor.GRAY + llama.getStrength());
}
player.playSound(player.getLocation(), Sound.UI_BUTTON_CLICK, SoundCategory.NEUTRAL, 1.0f, 1.0f);
}
// ------------------------------------------------------------------------
/**
* Show information about the current level of an ability, the corresponding
* attribute value, and the total effort expended for that ability on a
* specific horse.
*
* When the maximum possible level is exceeded by training, colour the level
* text red.
*
* @param player the player to be send messages.
* @param abililty the {@link Ability}.
* @param savedHorse the database state of the horse.
*/
protected void showLevel(Player player, Ability ability, SavedHorse savedHorse) {
double fractionalLevel = ability.getFractionalLevel(savedHorse);
ChatColor levelColour = (fractionalLevel >= ability.getMaxLevel()) ? ChatColor.RED : ChatColor.WHITE;
player.sendMessage(ChatColor.GOLD + ability.getDisplayName() + ": " +
levelColour + "Level " + String.format("%5.3f", fractionalLevel) +
ChatColor.GOLD + " - " +
ChatColor.YELLOW + ability.getFormattedValue(savedHorse) +
ChatColor.GRAY + " (" + ability.getFormattedEffort(savedHorse) + ")");
}
// ------------------------------------------------------------------------
/**
* Show the attribute value in a specified Ability of an AbstractHorse.
*
* @param player the player to message.
* @param ability the Ability.
* @param abstractHorse the horse-like entity.
*/
protected void showAttribute(Player player, Ability ability, AbstractHorse abstractHorse) {
double attributeValue = ability.getAttribute(abstractHorse);
double displayValue = ability.toDisplayValue(attributeValue);
String formattedValue = ability.formatValue(displayValue);
player.sendMessage(ChatColor.GOLD + ability.getDisplayName() + ": " + ChatColor.GRAY + formattedValue);
}
} // class HorseInfoExecutor
| true
|
8ef356dccc11305cecaaa63a23e92b184680f53f
|
Java
|
lucamarchi/sii_absa
|
/src/com/sii/crf/Main.java
|
UTF-8
| 2,677
| 2.265625
| 2
|
[] |
no_license
|
package com.sii.crf;
import java.io.File;
import java.io.IOException;
import java.util.List;
import com.sii.crf.controller.InsertController;
import com.sii.crf.controller.OutputController;
import com.sii.crf.controller.StatisticsController;
import com.sii.crf.mallet.EvaluateClassifier;
import com.sii.crf.mallet.ImportData;
import com.sii.crf.model.Sentence;
import com.sii.crf.mongodb.dao.SentenceDAO;
import com.sii.crf.mongodb.dao.SentenceDAOImplementation;
import com.sii.crf.writer.FileIO;
import cc.mallet.types.InstanceList;
public class Main {
final static String DATA_DIR = "/Users/luca/Desktop/data/";
final static int max_reviews = 25;
public static void main(String[] args) throws IOException {
/* InsertController.parseAndInsert() prende le singole sentences dall'xml
* e le salva nel db; il file xml si trova nel package parser, il db si chiama
* db_sii, la collezione trainSentencesT1.
*/
InsertController.parseAndInsert();
/* Mostra alcune informazioni sul dataset
*/
StatisticsController.showStatistics();
/* InsertController.NLPAndInsert() prende le singole sentences
* dal db del comando prima, e prende i risultati del NLP salvando
* il tutto nella collezione trainSentencesNLP; NB: bisogna eseguire
* questo comando con il server NLP in esecuzione.
*/
InsertController.NLPAndInsert();
/* FileIO.createDirectoriesByPolarityLabel(sentences) dato un'array di
* sentences crea le tre cartelle negative, neutral e positive
* ognuna delle quali contentente tanti file quante sentences
* (una per file) con quella class target; NB: cambiare la path
* in FileIO delle directory.
*/
SentenceDAO dao = new SentenceDAOImplementation();
List<Sentence> sentences = dao.findAll();
FileIO.createDirectoriesByPolarityLabel(sentences);
/* ImporterData prende come input le istanze nei file del passo precendente
* e le importa in Mallet.
*/
ImportData importer = new ImportData();
InstanceList instances = importer.readDirectory(new File("/Users/luca/Desktop/data"));
/* Esegue per 10 volte tre classificatori (MaxEntr,NaiveBayes,DecTree)
* e visualizza i valori medi di accuracy e f1.
*/
int num = 10;
EvaluateClassifier.evaluateDataClassify(instances,num);
/* Fa il retrieve delle review corrispondenti al modello indicato con il codice asin
* e mostra l'output; avviene creazione dell'evaluation model e classificazione.
*/
OutputController o = new OutputController("B01GFYP8II");
o.start();
}
}
| true
|
8b27afa3e2ba454096450c4161913d78131cd27d
|
Java
|
IBMStreams/streamsx.health
|
/ingest/fhir/com.ibm.streamsx.health.fhir/src/com/ibm/streamsx/health/fhir/model/ParseError.java
|
UTF-8
| 828
| 2.078125
| 2
|
[
"Apache-2.0"
] |
permissive
|
//*******************************************************************************
//* Copyright (C) 2017 International Business Machines Corporation
//* All Rights Reserved
//*******************************************************************************
package com.ibm.streamsx.health.fhir.model;
import java.io.Serializable;
public class ParseError implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private String exception;
private String rawMessage;
public ParseError setException(String exception) {
this.exception = exception;
return this;
}
public ParseError setRawMessage(String rawMessage) {
this.rawMessage = rawMessage;
return this;
}
public String getException() {
return exception;
}
public String getRawMessage() {
return rawMessage;
}
}
| true
|
a7d1e49ecd30fa3ca127a56918d00d663fc9e32d
|
Java
|
hcl0923/springboot
|
/mybank/src/main/java/com/yc/tx/bean/Accounts.java
|
UTF-8
| 247
| 1.578125
| 2
|
[] |
no_license
|
package com.yc.tx.bean;
import lombok.Data;
/**
* @program: reflectionAndAnnotation
* @description:
* @author: 作者
* @create: 2021-04-14 20:25
*/
@Data
public class Accounts {
private Integer accountId;
private Double balance;
}
| true
|
a5d1505779ee0f8ff5c328b27e5080233de642bc
|
Java
|
yugimaster/android-crawler_jav
|
/app/src/main/java/com/yugimaster/jav/view/MyVideoView.java
|
UTF-8
| 1,636
| 2.578125
| 3
|
[] |
no_license
|
package com.yugimaster.jav.view;
import android.content.Context;
import android.util.AttributeSet;
import android.view.ViewGroup;
import android.widget.VideoView;
/**
* Created by yugimaster on 2018/7/24.
*/
public class MyVideoView extends VideoView {
int defaultWidth = 1920;
int defaultHeight = 1080;
// Used in creating codes same as new
public MyVideoView(Context context) {
this(context, null);
}
// System will use this construction method automatically when use this class in layout
public MyVideoView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
/**
* Use this class when need style
* @param context
* @param attrs
* @param defStyleAttr
*/
public MyVideoView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
/**
* Measure
* @param widthMeasureSpec
* @param heightMeasureSpec
*/
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int width = getDefaultSize(defaultWidth, widthMeasureSpec);
int height = getDefaultSize(defaultHeight, heightMeasureSpec);
setMeasuredDimension(width, height);
}
/**
* set width/height of the screen
* @param width
* @param height
*/
public void setVideoSize(int width, int height) {
ViewGroup.LayoutParams params = getLayoutParams();
params.width = width;
params.height = height;
setLayoutParams(params);
}
}
| true
|
adb9ded85fd78d133c053f9d92648bae03d73744
|
Java
|
mamewotoko/podplayer
|
/app/src/androidTest/java/com/mamewo/podplayer0/tests/TestMainActivity.java
|
UTF-8
| 2,774
| 2.078125
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.mamewo.podplayer0.tests;
import com.mamewo.podplayer0.MainActivity;
import com.mamewo.podplayer0.PodplayerActivity;
import com.mamewo.podplayer0.PodplayerExpActivity;
import com.robotium.solo.Solo;
import com.robotium.solo.Solo.Config;
import android.app.Activity;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.test.ActivityInstrumentationTestCase2;
import android.util.Log;
public class TestMainActivity
extends ActivityInstrumentationTestCase2<MainActivity>
{
private Solo solo_;
static final
private String TAG = "podtest";
public TestMainActivity() {
super("com.mamewo.podplayer0", MainActivity.class);
}
@Override
public void setUp() {
Config config = new Config();
solo_ = new Solo(getInstrumentation(), config, getActivity());
}
@Override
public void tearDown() throws Exception {
try {
solo_.finalize();
}
catch(Throwable e) {
Log.i(TAG, "tearDown error", e);
}
if (! getActivity().isFinishing()) {
getActivity().finish();
}
super.tearDown();
}
//TODO: modify
public void testStart() {
Activity activity = getActivity();
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(activity);
boolean prevValue = pref.getBoolean("use_expandable_ui", false);
String activityClass;
if (prevValue) {
activityClass = PodplayerExpActivity.class.getName();
}
else {
activityClass = PodplayerActivity.class.getName();
}
// Activity last = solo_.getActivityMonitor().getLastActivity();
solo_.sleep(3000);
Log.d(TAG, "testStart: " + prevValue + " / " + activityClass);
//assertEquals(activityClass, last.getClass().getName());
pref.edit().putBoolean("use_expandable_ui", !prevValue).commit();
}
public void testStart2() {
Activity activity = getActivity();
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(activity);
boolean prevValue = pref.getBoolean("use_expandable_ui", false);
String activityClass;
if (prevValue) {
activityClass = PodplayerExpActivity.class.getName();
}
else {
activityClass = PodplayerActivity.class.getName();
}
// Activity last = solo_.getActivityMonitor().getLastActivity();
solo_.sleep(3000);
Log.d(TAG, "testStart: " + prevValue + " / " + activityClass);
//assertEquals(activityClass, last.getClass().getName());
pref.edit().putBoolean("use_expandable_ui", !prevValue).commit();
}
}
| true
|
ee9f7c97d8f34aabafec2f42319bf9d268c4b292
|
Java
|
kamiranoff/java-tutorials
|
/TileGame/src/dev/game/tilegame/gfx/ImageLoader.java
|
UTF-8
| 490
| 2.515625
| 3
|
[] |
no_license
|
package dev.game.tilegame.gfx;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
/**
* Created by kevin on 04/01/16.
*/
public class ImageLoader {
public static BufferedImage loadImage(String path){
try {
return ImageIO.read(ImageLoader.class.getResource(path));
} catch (IOException e) {
e.printStackTrace();
//doesnt run the game if the image does not load
System.exit(1);
}
return null;
}
}
| true
|
e40f48471fc5db58096bf56f18d05e2b3e94db43
|
Java
|
oggong/java_study
|
/JavaBasic/src/b_operator/Ex01_IncDec.java
|
UTF-8
| 1,218
| 3.984375
| 4
|
[] |
no_license
|
package b_operator;
public class Ex01_IncDec { // 증감 연산자
/*
* 증가 감소 연산자 : ++, --
*
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int a = 5, b = 7;
// System.out.println("A=" + a + 1 + ",B=" + b + 1); -- 값 A=51 B=71 나와 버림
// System.out.println("A=" + (a + 1) + ",B=" + (b + 1)); // A=6 B=8
/*
* a = a + 1; b = b - 1;
*
* System.out.println("A=" + a + ",B=" + b); // A=6 B=6
*
* // 위와 같은 코딩 a++; b--; System.out.println("A=" + a + ",B=" + b); // A=7 B=5 //
* 축약형으로 증가연산자 사용
*
* ++a; // a++ --b; // b++ System.out.println("A=" + a + ",B=" + b); // A=8 B=4
*/
// int result = ++a;
// System.out.println("Result:" + result + "A=" + a); // 6 6 a 먼저 증가시키고 result 값 입력
//
// int result2 = a++;
// System.out.println("Result:" + result2 + "A=" + a);// 6 7 result2 입력 후에 a를 증가시킴
System.out.println("A=" + ++a + "B=" + --b); // 6 6 --- 첫계산
System.out.println("A=" + a++ + "B=" + b--); // 6 6 --- 누적 후 두번째 계산
System.out.println("A=" + a + "B=" + b); // 7 5 --- 누적 후 세번째 계산
}
}
| true
|
be701289aba1c479c1f55dc230ba4b771f3211ba
|
Java
|
renx19960608/wechat-server
|
/src/main/java/com/renx/wechatserver/service/Impl/WXMenuServiceImpl.java
|
UTF-8
| 4,188
| 2.125
| 2
|
[] |
no_license
|
package com.renx.wechatserver.service.Impl;
import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.renx.wechatserver.dao.ConfigMapper;
import com.renx.wechatserver.dao.WxmenuMapper;
import com.renx.wechatserver.model.WechatConfig;
import com.renx.wechatserver.model.WechatMenu;
import com.renx.wechatserver.service.WXMenuService;
import com.renx.wechatserver.utils.ErrorCode;
import com.renx.wechatserver.weixin.WxMenUtil;
import com.renx.wechatserver.weixin.WxMenu;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
@Service
public class WXMenuServiceImpl implements WXMenuService {
@Value("${common.domain}")
private String domain;
@Value("${common.wechat_id}")
private String wechat_id;
@Autowired
private ConfigMapper configMapper;
@Autowired
private WxmenuMapper wxmenuMapper;
private WxMenu transferMenuInfo(WechatMenu menu){
WxMenu wxMenu = new WxMenu();
wxMenu.setName(menu.getName());
if(menu.getMenuType() == 1) {// 网页
wxMenu.setType("view");
}
if(menu.getLevel() == -1) {// 外部链接
wxMenu.setUrl(menu.getUri());
}else if(menu.getLevel() == 0) {// 内部链接
StringBuffer sb = new StringBuffer();
sb.append("http://").append(domain).append("/sysmgr-server/wechat/001/redirect/").append(menu.getMenuId());
// 内部链接指向地址
wxMenu.setUrl(sb.toString());
}
return wxMenu;
}
@Override
public ErrorCode createMenu(Map<String, Object> response) {
List<WechatMenu> wechatMenuList=wxmenuMapper.selectByGTLevel(wechat_id,0);
//一级菜单
List<WechatMenu> topMenus=new ArrayList<>();
//二级菜单
Map<Integer, List<WxMenu>> subMenusMap = new HashMap<Integer, List<WxMenu>>();
for(WechatMenu wechatMenu:wechatMenuList){
WxMenu wxMenu=transferMenuInfo(wechatMenu);
if(wechatMenu.getParentId()==0){
topMenus.add(wechatMenu);
}else{
List<WxMenu> list = subMenusMap.get(wechatMenu.getParentId());
if(list == null) {
list = new ArrayList<WxMenu>();
subMenusMap.put(wechatMenu.getParentId(), list);
}
list.add(wxMenu);
}
}
// 组装公众号菜单json数据
JSONArray jsonArray = new JSONArray();
for(WechatMenu wechatMenu:topMenus){
List<WxMenu> list = subMenusMap.get(wechatMenu.getMenuId());
JSONObject jsonObject=new JSONObject();
jsonObject.put("name",wechatMenu.getName());
if(list != null && list.size() > 0) {
jsonObject.put("sub_button", JSONArray.toJSON(list));
}else {
jsonObject.put("sub_button", new JSONArray());
// 可能一级菜单直接是个跳转链接,这里增加针对这种情况的处理
if(!StringUtils.isEmpty(wechatMenu.getUri())){
WxMenu wxMenu = transferMenuInfo(wechatMenu);
jsonObject.put("type", wxMenu.getType());
jsonObject.put("url", wxMenu.getUrl());
}
}
jsonArray.add(jsonObject);
}
if(jsonArray.size()>0){
JSONObject jsonObject=new JSONObject();
jsonObject.put("button",jsonArray);
WechatConfig config=configMapper.getConfigByWechatid(wechat_id);
System.out.println("菜单json"+jsonObject.toString());
if(WxMenUtil.createMenu(config.getAppid(),config.getSecret(),jsonObject.toString())){
return ErrorCode.SUCCEED;
}else {
return ErrorCode.ERR_CREATE_WXMENU;
}
}else{
return ErrorCode.ERR_EMPTY_WXMENU;
}
}
}
| true
|
1c214359bad7edd10457566b309372850a29929b
|
Java
|
lyqing0828/IdCardJCHL
|
/app/src/main/java/com/idcard/hnd/idcardjchl/bean/LoginInfo.java
|
UTF-8
| 2,717
| 2.3125
| 2
|
[] |
no_license
|
package com.idcard.hnd.idcardjchl.bean;
import android.util.Log;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Created by Administrator on 2019/6/13.
*/
public class LoginInfo {
private String code;
private String message;
private String bmdm;//部门代码
private String jybh;//警员编号
private String jwtmm;//警务通密码
private String xm;//姓名
public String getCode() {
return code;
}
public String getMessage() {
return message;
}
public void setCode(String code) {
this.code = code;
}
public void setMessage(String message) {
this.message = message;
}
public String getBmdm() {
return bmdm;
}
public String getJybh() {
return jybh;
}
public String getJwtmm() {
return jwtmm;
}
public void setBmdm(String bmdm) {
this.bmdm = bmdm;
}
public void setJybh(String jybh) {
this.jybh = jybh;
}
public void setJwtmm(String jwtmm) {
this.jwtmm = jwtmm;
}
public void setXm(String xm) {
this.xm = xm;
}
public String getXm() {
return xm;
}
@Override
public String toString() {
return "LoginInfo{" +
"bmdm='" + bmdm + '\'' +
", jybh='" + jybh + '\'' +
", jwtmm='" + jwtmm + '\'' +
", xm='" + xm + '\'' +
'}';
}
// public static LoginInfo parseLoginResult(String result) {
// LoginInfo login = new LoginInfo();
// try {
//// if (TextUtils.isEmpty(result)) {
//// return;
//// }
// JSONObject dataJson = new JSONObject(result);
// String code = dataJson.getString("code");
// String message = dataJson.getString("message");
// JSONObject dataJson2 = dataJson.getJSONObject("data");
// String bmdm = dataJson2.getString("bmdm");
// String jwtmm = dataJson2.getString("jwtmm");
// String jybh = dataJson2.getString("jybh");
// String xm = dataJson2.getString("xm");
// Log.d("数据", code + "--" + bmdm + "--" + jwtmm + "--" + jybh + "--" + xm + "--" + message);
// login.setCode(code);
// login.setMessage(message);
// login.setBmdm(bmdm);
// login.setJwtmm(jwtmm);
// login.setJybh(jybh);
// login.setXm(xm);
// } catch (JSONException e) {
// e.printStackTrace();
// }
// return login;
// }
}
| true
|
eb8a31013e750c2c20fdfdebece4a4b41362341a
|
Java
|
MinPyaeHein/Liblary-Management-System-TU-
|
/LmsTU/src/com/coder/dao/DepartmentDao.java
|
UTF-8
| 921
| 2.28125
| 2
|
[] |
no_license
|
package com.coder.dao;
import java.util.List;
import org.springframework.stereotype.Repository;
import com.coder.model.Book;
import com.coder.model.Department;
import com.coder.model.Position;
import com.coder.model.Student;
import com.coder.model.Teacher;
@Repository("departmentDao")
public class DepartmentDao extends AbstractDao<Integer,Department>{
public Integer saveDepartment(Department department)
{
return (Integer)super.persist(department);
}
public Department getDepartmentById(int id){
Department position=super.criteriaQuerryGetObjectById(id,"departmentId");
return position;}
public void updateDepartment(Department department)
{
super.update(department);
}
public void deleteDepartment(Department department)
{
super.delete(department);
}
public List<Department> getDepartments() {
List<Department> departments=(List<Department>)super.getAllEntity();
return departments;
}
}
| true
|
21317ceb3252e5a65c7e1dc9c7430075ebe63d8b
|
Java
|
RobertShippey/TravelAgency
|
/src/java/net/robertshippey/travelagency/testing/NullTesting.java
|
UTF-8
| 3,020
| 2.984375
| 3
|
[] |
no_license
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package net.robertshippey.travelagency.testing;
/**
*
* @author Robert
*/
public class NullTesting {
public static void main(String[] args) {
try {
System.out.println("getAllFlights");
System.out.println(getAllFlights(null));
System.out.println();
} catch (Exception e) {
System.err.println(e.getMessage());
}
try {
System.out.println("makeBooking");
System.out.println(makeBooking(null, null, null));
System.out.println();
} catch (Exception e) {
System.err.println(e.getMessage());
}
try {
System.out.println("searchFlights");
System.out.println(searchFlights(null, null, null, null, null));
System.out.println();
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
private static String getAllFlights(java.lang.String currency) {
net.robertshippey.travelagency.webservice.reference.TravelAgencyWebService_Service service = new net.robertshippey.travelagency.webservice.reference.TravelAgencyWebService_Service();
net.robertshippey.travelagency.webservice.reference.TravelAgencyWebService port = service.getTravelAgencyWebServicePort();
return port.getAllFlights(currency);
}
private static java.util.List<java.lang.String> getCurrencyCodes() {
net.robertshippey.travelagency.webservice.reference.TravelAgencyWebService_Service service = new net.robertshippey.travelagency.webservice.reference.TravelAgencyWebService_Service();
net.robertshippey.travelagency.webservice.reference.TravelAgencyWebService port = service.getTravelAgencyWebServicePort();
return port.getCurrencyCodes();
}
private static String makeBooking(java.lang.String flightCode, java.lang.String passengerName, java.lang.String noOfSeats) {
net.robertshippey.travelagency.webservice.reference.TravelAgencyWebService_Service service = new net.robertshippey.travelagency.webservice.reference.TravelAgencyWebService_Service();
net.robertshippey.travelagency.webservice.reference.TravelAgencyWebService port = service.getTravelAgencyWebServicePort();
return port.makeBooking(flightCode, passengerName, noOfSeats);
}
private static String searchFlights(java.lang.String origin, java.lang.String desdination, java.lang.String date, java.lang.String directFlight, java.lang.String currency) {
net.robertshippey.travelagency.webservice.reference.TravelAgencyWebService_Service service = new net.robertshippey.travelagency.webservice.reference.TravelAgencyWebService_Service();
net.robertshippey.travelagency.webservice.reference.TravelAgencyWebService port = service.getTravelAgencyWebServicePort();
return port.searchFlights(origin, desdination, date, directFlight, currency);
}
}
| true
|
7bd24873a588ad9c935d71f9dcfc9ce78ab9a718
|
Java
|
kingdas/lesson2
|
/pro27B/yc27001java001base/src/com/yc/java019jdbc/DbUtils.java
|
GB18030
| 2,754
| 2.90625
| 3
|
[] |
no_license
|
package com.yc.java019jdbc;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
public class DbUtils {
private static final String DRIVER;
private static final String URL;
private static final String USERNAME;
private static final String PASSWORD;
/**
* ע
*/
static {
Properties p = new Properties();
try {
p.load(Thread.currentThread().getContextClassLoader()
.getResourceAsStream("dbInfo.properties"));
} catch (IOException e) {
e.printStackTrace();
}
DRIVER = p.getProperty("driver");
URL = p.getProperty("url");
USERNAME = p.getProperty("username");
PASSWORD = p.getProperty("password");
try {
Class.forName(DRIVER);
} catch (ClassNotFoundException e) {
System.out.println("עʧ");
e.printStackTrace();
}
}
/**
* ȡݿӶ
*
* @return Ӷ
*/
public static Connection getConnection() {
Connection conn = null;
try {
conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
/**
* ִвѯ
*
* @param sql
* @return
*/
public static ResultSet executeR(String sql) {
ResultSet rs = null;
try {
Connection conn = getConnection();
Statement stat = conn.createStatement();
rs = stat.executeQuery(sql);
} catch (Exception e) {
e.printStackTrace();
}
return rs;
}
/**
* ִвѯ
*
* @param sql
* @return
*/
public static ResultSet executeR(Connection conn, String sql) {
ResultSet rs = null;
try {
Statement stat = conn.createStatement();
rs = stat.executeQuery(sql);
} catch (Exception e) {
e.printStackTrace();
}
return rs;
}
/**
* ִɾ
*
* @param sql
* @return Ӱ
*/
public static int executeCUD(String sql) {
int n = 0;
Connection conn = null;
Statement stat = null;
try {
conn = getConnection();
stat = conn.createStatement();
n = stat.executeUpdate(sql);
} catch (Exception e) {
e.printStackTrace();
} finally {
release(conn, stat, null);
}
return n;
}
public static void release(Connection conn, Statement stat, ResultSet rs) {
try {
if (conn != null && !conn.isClosed()) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (stat != null && !stat.isClosed()) {
stat.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (rs != null && !rs.isClosed()) {
rs.close();
}
} catch (SQLException e1) {
e1.printStackTrace();
}
}
}
| true
|
79869aeb4f69579989a6a66c83edeb122a016e43
|
Java
|
RajSingh-11/Design-Patterns
|
/DesignPatterns/src/com/design/patterns/creational/prototype/PrototypeMain.java
|
UTF-8
| 1,682
| 4.03125
| 4
|
[] |
no_license
|
package com.design.patterns.creational.prototype;
// when you create an object it takes more times for example if we create object
// from data base values
// it load from data base first and then we create an object, so next time when
// we want another object we do not hit the data base again
// we just copy or can say clone the object from first object.
// Example- if we have a book shop and we want to open another book shop so what
// we can do is we just clone the book shop where same books will be there.
/**
* The is achieved by Cloneable(marker) interface where we make the clone of
* Book Shop, by default java gives us shallow copy in which if we change in
* first object it changes it in the second object also, means two references
* pointing to same address in the memory. To avoid this we do deep cloning
* where we create new object of Book Shop and copy every value of book shop
* object to this new object, this will not affect the second object even if we
* delete something from the first object.
*/
public class PrototypeMain {
public static void main(String[] args) throws CloneNotSupportedException {
BookShop bShop = new BookShop();
bShop.setShopName("Novelity");
bShop.loadData();
// instead loading the second object form database we do deep cloning of
// object.
BookShop b1 = bShop.clone();
// this will remove from both objects if it is shallow copy but here we
// have done deep copy so it will not remove from second object.
bShop.getBooks().remove(2);
b1.setShopName("A1");
System.out.println(bShop);
System.out.println(b1);
}
}
| true
|
f468c8b3e76a0596843d4135f304f4d54584f324
|
Java
|
kasua/TestNGBasics
|
/src/com/class01/beforeAndAfterMethods.java
|
UTF-8
| 558
| 2.453125
| 2
|
[] |
no_license
|
package com.class01;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class beforeAndAfterMethods {
@BeforeMethod
public void testMethodsOne() {
System.out.println("beforeMethods");
}
@Test
public void testMethodOne() {
System.out.println("testMethod");
}
@Test
public void testMethodTwo() {
System.out.println("testMethodTwo");
}
@AfterMethod
public void afterMethod() {
System.out.println("afterMethods");
}
}
| true
|
60ab77a3e96e84bbcdfc8b8b1f321a6641bdd956
|
Java
|
Amstel90/Algos
|
/AlgoP4/src/main/java/Solver.java
|
UTF-8
| 5,508
| 3.34375
| 3
|
[] |
no_license
|
import java.util.Comparator;
import java.util.Iterator;
import java.util.TreeSet;
/**
* Created by Artem_Mikhalevitch on 3/18/15.
*/
public class Solver {
/*
* Board.
*/
private BoardState boardState;
/*
* Board.
*/
private int moves;
/*
* Board.
*/
private boolean solvable;
/*
* Board.
*/
private MinPQ<BoardState> open;
/*
* Board.
*/
private Stack<Board> solution;
/*
* Constructor. Find a solution to the initial board (using the A* algorithm)
*/
public Solver(Board initial) {
boardState = new BoardState(initial, null);
open = new MinPQ<BoardState>();
this.solve();
}
/*
* Solution.
*/
private void solve() {
open.insert(this.boardState);
TreeSet<BoardState> closedSet
= new TreeSet<BoardState>(new StateComparator());
while (open.size() != 0) {
BoardState min = open.delMin();
if (closedSet.contains(min)) {
min = null;
continue;
}
closedSet.add(min);
if (min.board.isGoal()) {
solvable = true;
this.restorePath(min);
break;
}
if (min.board.twin().isGoal()) {
break;
}
Iterator<Board> iterator = min.board.neighbors().iterator();
while (iterator.hasNext()) {
BoardState next = new BoardState(iterator.next(), min);
open.insert(next);
}
}
}
/*
* Returns true if the initial board solvable?
* @param another another state
*/
private void restorePath(final BoardState another) {
BoardState state = another;
solution = new Stack<Board>();
while (state.parent != null) {
solution.push(state.board);
state = state.parent;
moves++;
}
solution.push(state.board);
}
/*
* Returns true if the initial board solvable?
* @return true if solvable
*/
public boolean isSolvable() {
return solvable;
}
/*
* Returns min number of moves to solve initial board; -1 if unsolvable
* @return min number of moves to solve initial board; -1 if unsolvable
*/
public int moves() {
if (!solvable) {
return -1;
}
return moves;
}
/*
* Returns sequence of boards in a shortest solution; null if unsolvable
* @return sequence of boards in a shortest solution; null if unsolvable
*/
public Iterable<Board> solution() {
return solution;
}
/*
* Returns min number of moves to solve initial board; -1 if unsolvable
* @return min number of moves to solve initial board; -1 if unsolvable
*/
public static void main(String[] args) {
String fileName = args[0];
In in = new In(fileName);
int N = in.readInt();
int[][] blocks = new int[N][N];
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++)
blocks[i][j] = in.readInt();
Board initial = new Board(blocks);
// solve the puzzle
Solver solver = new Solver(initial);
// print solution to standard output
if (!solver.isSolvable())
StdOut.println("No solution possible");
else {
StdOut.println("Minimum number of moves = " + solver.moves());
for (Board board : solver.solution())
StdOut.println(board);
}
}
/*
* State Comparator.
*/
private class StateComparator implements Comparator<BoardState> {
@Override
public int compare(BoardState o1, BoardState o2) {
if (!o1.equals(o2)) {
return 1;
}
return 0;
}
}
/*
* State Comparator.
*/
private class BoardState implements Comparable {
/*
* Constructor.
*/
private Board board;
/*
* Constructor.
*/
private BoardState parent;
/*
* Constructor.
*/
private int level;
/*
* Constructor.
*/
private BoardState(Board board, BoardState parent) {
this.board = board;
this.parent = parent;
if (parent != null) {
this.level = parent.level + 1;
}
}
/*
* Board.
* @param o comparasion element
* @return value
*/
@Override
public int compareTo(Object o) {
BoardState that = (BoardState) o;
int result = this.board.manhattan() + this.level - that.board.manhattan() - that.level;
if (result == 0) {
result = this.board.hamming() + this.level - that.board.hamming() - that.level;
}
return result;
}
/**
* Returns does this board equal y?
* @param y param
* @return does this board equal y?
*/
@Override
public boolean equals(Object y) {
if (this == y) {
return true;
}
if (y instanceof BoardState) {
BoardState another = (BoardState) y;
return this.board.equals(another.board);
}
return false;
}
}
}
| true
|
47f3624c6a2eb08a6a5c4c407cf18ef50b221d92
|
Java
|
AllenAkhaumere/OpenCV_facedetection
|
/src/com/facedetection/vision/VideoTest.java
|
UTF-8
| 225
| 1.617188
| 2
|
[] |
no_license
|
package com.facedetection.vision;
public class VideoTest
{
public static void main(String[] args)
{
VideoProcessor proceesor = new VideoProcessor();
proceesor.run(Constants.CASCADE_CLASSIFIER_FRONT_FACE, 0, 20);
}
}
| true
|
8d968992b548ab18d512cd3f9f9381983f324746
|
Java
|
mzdz/aspectj-test
|
/src/test/java/CompileThirdJarTest.java
|
UTF-8
| 1,984
| 2.171875
| 2
|
[] |
no_license
|
import com.alibaba.fastjson.JSONObject;
import io.muzhi.Application;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
public class CompileThirdJarTest {
/**
* 切第三方库 注意要pom要添加运行时和第三方依赖
*1. 首先在pom.xml中引入
* <dependency>
* <groupId>org.aspectj</groupId>
* <artifactId>aspectjrt</artifactId>
* <version>1.9.7</version>
* </dependency>
*2. 引入第三方库的编织依赖weaveDependencies,然后安装依赖,编译即可;
* <plugin>
* <groupId>org.codehaus.mojo</groupId>
* <artifactId>aspectj-maven-plugin</artifactId>
* <version>1.14.0</version>
* <configuration>
* <complianceLevel>1.8</complianceLevel>
* <source>1.8</source>
* <target>1.8</target>
* <showWeaveInfo>true</showWeaveInfo>
* <Xlint>ignore</Xlint>
* <encoding>UTF-8</encoding>
* <forceAjcCompile>true</forceAjcCompile>
* <weaveDependencies>
* <weaveDependency>
* <groupId>com.alibaba</groupId>
* <artifactId>fastjson</artifactId>
* </weaveDependency>
* </weaveDependencies>
* </configuration>
* <executions>
* <execution>
* <goals>
* <goal>compile</goal>
* <goal>test-compile</goal>
* </goals>
* </execution>
* </executions>
* </plugin>
*/
@Test
public void thirdTest() {
System.out.println(JSONObject.toJSONString("Abc"));
}
}
| true
|
b53e04abda3fe4c1610ae74b2031a3eb8c6b7c55
|
Java
|
nicholaskhuong/ellipsesaasautomation
|
/EllipseSaaSAutomation/src/com/abb/ventyx/utilities/report/Error.java
|
UTF-8
| 119
| 1.578125
| 2
|
[] |
no_license
|
package com.abb.ventyx.utilities.report;
public class Error {
private String desc = "";
public Error() {
}
}
| true
|
4c9d39044a110773682895670c6fa470c6bf7741
|
Java
|
rajmahendra/forge-jrebirth-plugin
|
/src/main/java/org/jrebirth/forge/helper/MavenProfilePluginHelper.java
|
UTF-8
| 8,014
| 1.929688
| 2
|
[
"Apache-2.0"
] |
permissive
|
/**
* Get more info at : www.jrebirth.org .
* Copyright JRebirth.org © 2011-2013
* Contact : sebastien.bordes@jrebirth.org
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.jrebirth.forge.helper;
import static org.jrebirth.forge.utils.PluginUtils.messages;
import java.io.IOException;
import java.io.StringReader;
import org.apache.maven.model.Build;
import org.apache.maven.model.Model;
import org.apache.maven.model.Plugin;
import org.apache.maven.model.PluginExecution;
import org.codehaus.plexus.util.xml.Xpp3DomBuilder;
import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
import org.jboss.forge.maven.MavenCoreFacet;
import org.jboss.forge.project.Project;
import org.jrebirth.forge.utils.PluginUtils;
/**
* Class for handling Maven Profile Plugin settings.
*
* @author Rajmahendra Hegde <rajmahendra@gmail.com>
*
*/
public final class MavenProfilePluginHelper {
public static void setupMavenProjectProfiles(final Project project, final String topLevelPackageName, final String projectName) {
final MavenCoreFacet facet = project.getFacet(MavenCoreFacet.class);
final Model pom = facet.getPOM();
final String projName = PluginUtils.firstLetterCaps(projectName);
final Build build;
build = ((pom.getBuild() == null) ? new Build() : pom.getBuild());
addMavenDefaultProperties(pom, topLevelPackageName, projName);
build.addPlugin(addMavenJarPlugin());
build.addPlugin(addMavenCompilerPlugin());
build.addPlugin(addMavenWebstartPlugin());
pom.setBuild(build);
facet.setPOM(pom);
}
private static void addMavenDefaultProperties(final Model pom, final String topLevelPackageName,
final String projectName)
{
pom.addProperty("project.build.sourceEncoding", "UTF-8");
pom.addProperty("jrebirthVersion", messages.getKeyValue("jrebirthVersion"));
pom.addProperty("javaVersion", messages.getKeyValue("javaJdkVersion"));
pom.addProperty("appMainClass", topLevelPackageName + "." + projectName + "App");
pom.addProperty("jnlpFilename", projectName + ".jnlp");
pom.addProperty("appletWidth", messages.getKeyValue("appletWidth"));
pom.addProperty("appletHeight", messages.getKeyValue("appletHeight"));
pom.addProperty("deployUrl", "");
pom.addProperty("deployPath", "");
}
private static Plugin addMavenJarPlugin()
{
final Plugin mavenJarPlugin = new Plugin();
mavenJarPlugin.setGroupId("org.apache.maven.plugins");
mavenJarPlugin.setArtifactId("maven-jar-plugin");
mavenJarPlugin.setVersion(messages.getKeyValue("mavenJarVersion"));
mavenJarPlugin.setConfiguration(buildJarPluginConfiguration());
return mavenJarPlugin;
}
private static Plugin addMavenCompilerPlugin() {
final Plugin mavenCompilePlugin = new Plugin();
mavenCompilePlugin.setGroupId("org.apache.maven.plugins");
mavenCompilePlugin.setArtifactId("maven-compiler-plugin");
mavenCompilePlugin.setVersion(messages.getKeyValue("mavenCompilerVersion"));
mavenCompilePlugin.setConfiguration(buildCompilePluginConfiguration());
return mavenCompilePlugin;
}
private static Plugin addMavenWebstartPlugin()
{
final Plugin mavenWebstartPlugin = new Plugin();
PluginExecution pluginExecution = new PluginExecution();
mavenWebstartPlugin.setGroupId("org.codehaus.mojo");
mavenWebstartPlugin.setArtifactId("webstart-maven-plugin");
mavenWebstartPlugin.setVersion(messages.getKeyValue("mavenWebstartVersion"));
pluginExecution.addGoal("jnlp");
pluginExecution.setPhase("package");
mavenWebstartPlugin.addExecution(pluginExecution);
mavenWebstartPlugin.setConfiguration(buildWebstartPluginConfiguration());
return mavenWebstartPlugin;
}
private static Object buildCompilePluginConfiguration() {
final StringBuffer buffer = new StringBuffer();
buffer.append("<configuration>\n");
buffer.append("<source>${javaVersion}</source>\n");
buffer.append("<target>${javaVersion}</target>\n");
buffer.append(" <encoding>UTF-8</encoding>\n");
buffer.append(" <debug>false</debug>\n");
buffer.append("<showDeprecation>true</showDeprecation>\n");
buffer.append("</configuration>\n");
return convertFromStringToXpp3Dom(buffer.toString());
}
private static Object buildJarPluginConfiguration() {
final StringBuffer buffer = new StringBuffer();
buffer.append("<configuration>\n");
buffer.append("<archive>\n");
buffer.append("<manifestEntries>\n");
buffer.append("<JavaFX-Version>2.0</JavaFX-Version>\n");
buffer.append(" <Main-Class>${appMainClass}</Main-Class>\n");
buffer.append("<JavaFX-Application-Class>${appMainClass}</JavaFX-Application-Class>\n");
buffer.append("<implementation-version>1.0</implementation-version>\n");
buffer.append("<JavaFX-Class-Path></JavaFX-Class-Path>\n");
buffer.append("</manifestEntries>\n");
buffer.append("<manifest><addClasspath>true</addClasspath></manifest>\n");
buffer.append("</archive>\n");
buffer.append("</configuration>\n");
return convertFromStringToXpp3Dom(buffer.toString());
}
private static Object buildWebstartPluginConfiguration() {
final StringBuffer buffer = new StringBuffer();
buffer.append("<configuration>");
buffer.append("<jnlpFiles>${jrebirth.jnlp.filename}</jnlpFiles>");
buffer.append("<excludeTransitive>false</excludeTransitive>");
buffer.append("<libPath>lib</libPath>");
buffer.append("<resourcesDirectory>${project.basedir}/src/main/jnlp/resources</resourcesDirectory>");
buffer.append("<codebase>${deployUrl}/${deployPath}</codebase>");
buffer.append(" <jnlp>");
buffer.append("<outputFile>${jnlpFilename}</outputFile>");
buffer.append("<mainClass>${appMainClass}</mainClass>");
buffer.append("<offlineAllowed>true</offlineAllowed>");
buffer.append("</jnlp>");
buffer.append(" <sign>");
buffer.append(" <keystore></keystore>");
buffer.append("<keypass></keypass>");
buffer.append("<storepass></storepass>");
buffer.append("<alias></alias>");
buffer.append("<validity>360</validity>");
buffer.append("<dnameCn></dnameCn>");
buffer.append("<dnameOu></dnameOu><dnameO></dnameO><dnameL></dnameL><dnameSt></dnameSt>");
buffer.append("<dnameC></dnameC><verify>true</verify>");
buffer.append("<keystoreConfig><delete>true</delete><gen>true</gen></keystoreConfig></sign>");
buffer.append(" <pack200>true</pack200><gzip>true</gzip><outputJarVersions>false</outputJarVersions>");
buffer.append("<install>false</install><verbose>true</verbose>");
buffer.append("</configuration>");
return convertFromStringToXpp3Dom(buffer.toString());
}
private static Object convertFromStringToXpp3Dom(final String xml) {
try {
return Xpp3DomBuilder.build(new StringReader(xml));
} catch (final XmlPullParserException e) {
throw new IllegalStateException(e);
} catch (final IOException e) {
throw new java.lang.IllegalStateException(e);
}
}
}
| true
|
bd6d304e26c70993cb5115ac014eaa0f842a67f8
|
Java
|
mzuchnik/spring-praca-domowa-7b
|
/src/main/java/pl/mzuchnik/springpracadomowa7b/client/ArticleClientImpl.java
|
UTF-8
| 2,108
| 2.390625
| 2
|
[] |
no_license
|
package pl.mzuchnik.springpracadomowa7b.client;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;
import pl.mzuchnik.springpracadomowa7b.model.Article;
import pl.mzuchnik.springpracadomowa7b.model.api.ArticleApiFullResponse;
import java.util.ArrayList;
import java.util.List;
@Service
public class ArticleClientImpl implements ArticleClient {
private RestTemplate restTemplate;
@Value("${newsapi-url}")
private String apiUrl;
@Value("${newsapi-key}")
private String apiKey;
public ArticleClientImpl() {
restTemplate = new RestTemplate();
}
@Override
public List<Article> getTopLineArticles(String country) {
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.add("x-api-key", apiKey);
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(apiUrl)
.queryParam("country", country);
ArticleApiFullResponse body = restTemplate.exchange(
builder.toUriString(),
HttpMethod.GET,
new HttpEntity<>(null, httpHeaders),
ArticleApiFullResponse.class)
.getBody();
return getArticles(body);
}
private List<Article> getArticles(ArticleApiFullResponse body) {
List<Article> articles = new ArrayList<>();
body.getArticles().stream()
.forEach(a -> {
articles.add(new Article(0,
a.getSource().getName(),
a.getTitle(),
a.getDescription(),
a.getContent(),
a.getPublishedAt(),
a.getUrlToImage(),
a.getAuthor()));
});
return articles;
}
}
| true
|
b404bfca70024be7ecf090bde5ed46e4be2f741b
|
Java
|
rationalis/Tritonnections
|
/app/src/main/java/com/ucsdcse110/tritonnections/fragment/PostsRecyclerViewFragment.java
|
UTF-8
| 4,695
| 2.15625
| 2
|
[] |
no_license
|
package com.ucsdcse110.tritonnections.fragment;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
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.ucsdcse110.tritonnections.PostObj;
import com.ucsdcse110.tritonnections.PostObjRvAdapter;
import com.ucsdcse110.tritonnections.R;
import java.util.ArrayList;
import java.util.List;
public class PostsRecyclerViewFragment extends OptionsMenuFragment {
private List<PostObj> postList = new ArrayList<>();
private RecyclerView rv;
private PostObjRvAdapter adapter;
private DatabaseReference mDatabase;
@Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_forum_view, container, false);
rv = (RecyclerView) view.findViewById(R.id.rv);
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
rv.setLayoutManager(llm);
FloatingActionButton fab = (FloatingActionButton) view.findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
ForumFragment ff = new ForumFragment();
getFragmentManager().beginTransaction()
.replace(container.getId(), ff)
.addToBackStack(null)
.commit();
}
});
mDatabase = FirebaseDatabase.getInstance().getReference();
initializeAdapter();
initializeData();
isSearchable = true;
isSelectable = false;
setHasOptionsMenu(true);
return view;
}
public SearchView.OnQueryTextListener getSearchListener() {
return new SearchView.OnQueryTextListener() {
public boolean onQueryTextSubmit(String query) {
return true;
}
public boolean onQueryTextChange(String newText) {
if (newText.equals("")) {
adapter.setData(postList);
adapter.notifyDataSetChanged();
return true;
}
List<PostObj> list = new ArrayList<>();
for (PostObj o : postList) {
if (o.title.contains(newText)) {
list.add(o);
}
}
adapter.setData(list);
adapter.notifyDataSetChanged();
return true;
}
};
}
public void populateDropdown(Menu m, int[] ids) {
}
private void initializeData(){
System.out.println("Started initializing data for RV");
mDatabase.child("postobjs").orderByKey().limitToLast(1000).addChildEventListener(
new ChildEventListener() {
@Override
public void onCancelled(DatabaseError databaseError) {
System.out.println("Database error: " + databaseError.toString());
}
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String prevChildKey) {
PostObj post = dataSnapshot.getValue(PostObj.class);
postList.add(0, post);
adapter.notifyItemInserted(0);
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String prevChildKey) {}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String prevChildKey) {}
});
System.out.println("Finished initializing data for RV");
}
private void initializeAdapter(){
System.out.println("Started initializing adapter for RV");
adapter = new PostObjRvAdapter(postList);
rv.setAdapter(adapter);
System.out.println("Finished initializing adapter for RV");
}
public void setData(List<PostObj> data)
{
postList = data;
}
}
| true
|
66dd33a98875e6a4d4c44181b531851570369528
|
Java
|
starscream202/IntelliJ
|
/syntax/class31/IteratorDemo.java
|
UTF-8
| 558
| 3.390625
| 3
|
[] |
no_license
|
package class31;
import java.util.ArrayList;
import java.util.Iterator;
public class IteratorDemo {
public static void main(String[] args) {
ArrayList<Double> doubleArrayList=new ArrayList<>();
doubleArrayList.add(4.58);
doubleArrayList.add(7.9);
doubleArrayList.add(5.6);
Iterator<Double> iterator=doubleArrayList.iterator();
while (iterator.hasNext()){
if(iterator.next()<5){
iterator.remove();
}
}
System.out.println(doubleArrayList);
}
}
| true
|
a5c170c289b9e1bdf0a0a6006e426b042fda907d
|
Java
|
pratik822/RuralHealth
|
/app/src/main/java/com/hgs/ruralhealth/fragments/ActivityModel.java
|
UTF-8
| 641
| 2.203125
| 2
|
[] |
no_license
|
package com.hgs.ruralhealth.fragments;
import java.util.List;
/**
* Created by pratikb on 21-03-2018.
*/
public class ActivityModel {
String status,message;
List<ActivityData> data;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public List<ActivityData> getData() {
return data;
}
public void setData(List<ActivityData> data) {
this.data = data;
}
}
| true
|
4e96bdf591cb4326db873544aa27c6940dd563f1
|
Java
|
mistapostle/locklockword
|
/app/src/main/java/locklockwords/mistapostle/appspot/com/locklockworks/WordsFragment.java
|
UTF-8
| 8,243
| 2.09375
| 2
|
[] |
no_license
|
package locklockwords.mistapostle.appspot.com.locklockworks;
/**
* Created by mistapostle on 17/6/24.
*/
import android.app.Activity;
import android.content.Context;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.Loader;
import android.database.Cursor;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.widget.CursorAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.ToggleButton;
import java.util.logging.Logger;
import locklockwords.mistapostle.appspot.com.locklockworks.db.LockLockWorksContract;
import locklockwords.mistapostle.appspot.com.locklockworks.utils.LoggerUtils;
import locklockwords.mistapostle.appspot.com.locklockworks.utils.WordsLoader;
/**
* A placeholder fragment containing a simple view.
*/
public class WordsFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
private WordsLoader cl;
public WordsFragment() {
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static WordsFragment newInstance(int sectionNumber) {
WordsFragment fragment = new WordsFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
@Override
public void onResume() {
super.onResume();
LoggerUtils.getLogger().info("WordsFragment onResume");
createWordsLoader();
}
public void createWordsLoader() {
//TODO: why getView() will be null ??!?!?!? it happens when after android.os.Process.killProcess(android.os.Process.myPid()) and the mainActivity resumed automatically as it's the latest Activity at background
final ListView wordLv = (ListView) getView().findViewById(R.id.word_lv);
cl = LockLockWorksContract.Word.getAllWordsLoader(getContext());
cl.registerListener(1, new Loader.OnLoadCompleteListener<Cursor>() {
@Override
public void onLoadComplete(Loader<Cursor> loader, Cursor data) {
Logger.getLogger("LockLockWorks").info("data = " + data);
if (wordLv.getAdapter() == null) {
CursorAdapter adapter = new CursorAdapter(getContext(), data, true) {
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(context);
View v = inflater.inflate(R.layout.item_wordlist, parent, false);
// tv.setText(cursor.getString(0) + cursor.getString(1));
Logger.getLogger("LockLockWorks").info("newView:" + cursor.getString(0) + cursor.getString(1));
return v;
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
TextView wordTv = (TextView) view.findViewById(R.id.wordTv);
wordTv.setText(cursor.getString(1));
TextView rankTv = (TextView) view.findViewById(R.id.rankTv);
rankTv.setText(Integer.toString(cursor.getInt(4)));
Logger.getLogger("LockLockWorks").info("bindView:" + cursor.getString(0) + cursor.getString(1));
}
};
wordLv.setAdapter(adapter);
} else {
CursorAdapter adapter = (CursorAdapter) wordLv.getAdapter();
// adapter.changeCursor(data);
adapter.swapCursor(data);
// adapter.notifyDataSetChanged();
// wordLv.invalidate();
// wordLv.invalidateViews();
}
}
});
wordLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//showNewOrEditWordDialogFragment()
Cursor cursor = (Cursor) wordLv.getAdapter().getItem(position);
LockLockWorksContract.Word word = new LockLockWorksContract.Word(cursor);
showNewOrEditWordDialogFragment(word);
}
});
cl.order = getOrder();
cl.startLoading();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_wordlist, container, false);
//TextView textView = (TextView) rootView.findViewById(R.id.section_label);
//textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
// ToggleButton lockScreenTb = (ToggleButton) rootView.findViewById(R.id.lockScreenTb);
// lockScreenTb.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// Intent i = new Intent(getContext(), FullscreenActivity.class);
// startActivity(i);
// }
// });
initAddWordBtn(rootView);
Spinner sb = (Spinner) rootView.findViewById(R.id.orderByspinner);
sb.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
reloadWordLv();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
return rootView;
}
public MainActivity getMainActivity() {
return (MainActivity) getActivity();
}
private void initAddWordBtn(View rootView) {
FloatingActionButton fab = (FloatingActionButton) rootView.findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
showNewOrEditWordDialog();
// Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
// .setAction("Action", null).show();
}
});
}
void showNewOrEditWordDialog() {
showNewOrEditWordDialogFragment(null);
}
public void showNewOrEditWordDialogFragment(LockLockWorksContract.Word word) {
NewOrEditWordDialogFragment dialog = new NewOrEditWordDialogFragment();
dialog.existingWord = word;
dialog.show(getActivity().getSupportFragmentManager(), "NewOrEditWordDialogFragment");
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
}
public void reloadWordLv() {
if (cl == null) {
// //TODO: note: cl would be null
// as it seems when system resume a activity it may don't call fragment recall onCreateView/onResume ??? , but use the cached view directly
createWordsLoader();
} else {
cl.reset();
cl.order = getOrder();
cl.startLoading();
}
}
private String getOrder() {
Spinner sb = (Spinner) getView().findViewById(R.id.orderByspinner);
String v = (String) sb.getSelectedItem();
if ("create time".equals(v)) {
return LockLockWorksContract.Word.COLUMN_NAME_CREATE_TIME + ", " + LockLockWorksContract.Word.COLUMN_NAME_ID + " desc";
}
return LockLockWorksContract.Word.COLUMN_NAME_RANK + " asc";
}
}
| true
|
cbc29389cdeb5df9c51f3978d65bd37eb104ca03
|
Java
|
ikhsanaulia/future-phase-1
|
/restaurant/src/main/java/com/blibli/future/pos/restaurant/AuthenticationFitler.java
|
UTF-8
| 3,819
| 2.234375
| 2
|
[] |
no_license
|
package com.blibli.future.pos.restaurant;
import com.blibli.future.pos.restaurant.common.ApplicationContex;
import com.blibli.future.pos.restaurant.common.ErrorMessage;
import com.blibli.future.pos.restaurant.common.model.Config;
import com.blibli.future.pos.restaurant.common.model.User;
import com.blibli.future.pos.restaurant.service.BaseRESTService;
import com.blibli.future.pos.restaurant.service.UserService;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.*;
import org.apache.log4j.MDC;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.ws.rs.NotAuthorizedException;
import javax.ws.rs.NotFoundException;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Cookie;
import javax.ws.rs.ext.Provider;
import java.io.IOException;
import java.util.Map;
@Provider
public class AuthenticationFitler implements ContainerRequestFilter {
@Context
HttpServletRequest httpRequest;
private static final Config config = (Config) ApplicationContex.getServletContext().getAttribute("restaurantConfig");
private ContainerRequestContext requestContext;
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
this.requestContext = requestContext;
HttpSession session = httpRequest.getSession();
// get cookie
Cookie cookie = getCookie("POSRESTAURANT");
// get response from cookie
Map<String,Object> response = getTokenResponse(cookie);
// get payload
Map<String,Object> payload = (Map<String,Object>) response.get("payload");
String refreshToken = payload.get("refreshToken").toString();
Integer userId = Integer.valueOf(payload.get("id").toString());
if(session.getAttribute("userId") == null || session.getAttribute("userId") != userId){
System.out.println("init User : " + userId);
try {
User user = UserService.getUser(userId);
session.setAttribute("user",user);
} catch (Exception e) {
throw new IOException(e.toString());
}
}
session.setAttribute("refreshToken",refreshToken);
ApplicationContex.getServletContext().setAttribute("session", session);
}
private Cookie getCookie(String key) {
Cookie cookie = null;
Map<String,Cookie> cookies = requestContext.getCookies();
for (Map.Entry<String, Cookie> pair : cookies.entrySet()) {
if(pair.getKey().equals(key)){
cookie = pair.getValue();
}
}
if(cookie == null){
throw new NotFoundException("Cookie not found");
}
return cookie;
}
private Map<String,Object> getTokenResponse(Cookie cookie) throws IOException {
OkHttpClient client = new OkHttpClient();
FormBody requestBody = new FormBody.Builder().add("token",cookie.getValue()).build();
Request request = new Request.Builder()
.url(config.getAuthService() + "/parseToken")
.post(requestBody)
.build();
Response response = client.newCall(request).execute();
ResponseBody body = response.body();
String bodyStr = response.body().string();
body.close();
if(!response.isSuccessful()){
throw new NotAuthorizedException("Invalid token");
}
ObjectMapper mapper = new ObjectMapper();
Map<String,Object> result = mapper.readValue(bodyStr, Map.class);
if(!result.get("status").equals("ok")){
throw new NotAuthorizedException("Invalid token");
}
return result;
}
}
| true
|
d947434282f5324481ceb7be3df30f191bb1ad38
|
Java
|
GuoYL123/servicecomb-java-chassis
|
/handlers/handler-loadbalance/src/test/java/org/apache/servicecomb/loadbalance/TestDefaultRetryhandler.java
|
UTF-8
| 4,520
| 2.03125
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.servicecomb.loadbalance;
import java.io.IOException;
import java.net.ConnectException;
import java.net.NoRouteToHostException;
import java.net.SocketTimeoutException;
import org.apache.servicecomb.swagger.invocation.exception.InvocationException;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import com.netflix.client.RetryHandler;
import io.vertx.core.VertxException;
public class TestDefaultRetryhandler {
private static final String RETYR_NAME = "default";
private static final String MICROSERVICE_NAME = "servicename";
private RetryHandler retryHandler;
@Before
public void setup() {
DefaultRetryExtensionsFactory factory = new DefaultRetryExtensionsFactory();
retryHandler = factory.createRetryHandler(RETYR_NAME, MICROSERVICE_NAME, null);
}
@Test
public void testRetryWithConnectionException() {
Exception target = new ConnectException("connectin refused");
Exception root = new Exception(target);
boolean retriable = retryHandler.isRetriableException(root, false);
Assert.assertTrue(retriable);
}
@Test
public void testRetryWithSocketTimeout() {
Exception target = new SocketTimeoutException("Read timed out");
Exception root = new Exception(target);
boolean retriable = retryHandler.isRetriableException(root, false);
Assert.assertTrue(retriable);
}
@Test
public void testRetryWithIOException() {
Exception target = new IOException("Connection reset by peer");
Exception root = new Exception(target);
boolean retriable = retryHandler.isRetriableException(root, false);
Assert.assertTrue(retriable);
target = new IOException("Target not exist");
root = new Exception(target);
retriable = retryHandler.isRetriableException(root, false);
Assert.assertFalse(retriable);
}
@Test
public void testRetryVertxException() {
Exception target = new VertxException("Connection was closed");
Exception root = new Exception(target);
boolean retriable = retryHandler.isRetriableException(root, false);
Assert.assertTrue(retriable);
target = new IOException("");
root = new Exception(target);
retriable = retryHandler.isRetriableException(root, false);
Assert.assertFalse(retriable);
}
@Test
public void testRetryNoRouteToHostException() {
Exception target = new NoRouteToHostException("Host is unreachable");
Exception root = new Exception(target);
boolean retriable = retryHandler.isRetriableException(root, false);
Assert.assertTrue(retriable);
target = new NoRouteToHostException("No route to host");
root = new Exception(target);
retriable = retryHandler.isRetriableException(root, false);
Assert.assertTrue(retriable);
}
@Test
public void testRetryInvocation503() {
Exception root = new InvocationException(503, "Service Unavailable", "Error");
boolean retriable = retryHandler.isRetriableException(root, false);
Assert.assertTrue(retriable);
}
@Test
public void testRetryEqualTen() {
Exception target = new ConnectException("connectin refused");
for (int i = 0; i < 8; i++) {
target = new Exception("Level" + i, target);
}
Exception root = new Exception(target);
boolean retriable = retryHandler.isRetriableException(root, false);
Assert.assertTrue(retriable);
}
@Test
public void testRetryOverTen() {
Exception target = new ConnectException("connectin refused");
for (int i = 0; i < 9; i++) {
target = new Exception("Level" + i, target);
}
Exception root = new Exception(target);
boolean retriable = retryHandler.isRetriableException(root, false);
Assert.assertFalse(retriable);
}
}
| true
|
2d2b51dc1bff23b1e15ab42cddca65a328fc7783
|
Java
|
bikess/IOExampleForJAVA
|
/JAVAIO/src/test/Parent.java
|
UTF-8
| 148
| 2.25
| 2
|
[] |
no_license
|
package test;
public class Parent {
int x=10;
public Parent(){
add(2);
}
void add(int y){
x+=y;
}
}
| true
|
5f9d685ec004268ae38c70e24e0ee4937ebdc11a
|
Java
|
svn2github/RefactorIT
|
/refactorit-core/src/main/java/net/sf/refactorit/reports/NotUsedXMLExporter.java
|
UTF-8
| 5,269
| 1.78125
| 2
|
[] |
no_license
|
/*
* Copyright 2001-2008 Aqris Software AS. All rights reserved.
*
* This program is dual-licensed under both the Common Development
* and Distribution License ("CDDL") and the GNU General Public
* License ("GPL"). You may elect to use one or the other of these
* licenses.
*/
package net.sf.refactorit.reports;
import net.sf.refactorit.common.util.MultiValueMap;
import net.sf.refactorit.query.notused.ExcludeFilterRule;
import net.sf.refactorit.query.notused.NotUsedTreeTableModel;
import net.sf.refactorit.ui.treetable.BinTreeTableModel;
import net.sf.refactorit.ui.treetable.BinTreeTableNode;
import org.xml.sax.SAXException;
import javax.xml.transform.sax.TransformerHandler;
import java.util.Iterator;
import java.util.List;
public class NotUsedXMLExporter extends XMLExporter {
public NotUsedXMLExporter(String encoding, String dtd, boolean isIndentNeeded) {
super(encoding, dtd, isIndentNeeded, "not-used");
}
protected void processModelInfo(BinTreeTableModel mdl, TransformerHandler hd) throws SAXException {
NotUsedTreeTableModel model = (NotUsedTreeTableModel)mdl;
ExcludeFilterRule[] rules = model.getFilterRules();
if (rules.length > 0) {
atts.clear();
hd.startElement("", "info", "info", atts);
atts.clear();
hd.startElement("", "exclude-filter-rules", "exclude-filter-rules", atts);
for (int i = 0; i < rules.length; i++) {
processExcludeFilterRule(hd, rules[i], i);
}
hd.endElement("", "exclude-filter-rules", "exclude-filter-rules");
hd.endElement("", "info", "info");
}
}
/**
* @param hd
* @param rules
* @param i
* @throws SAXException
*/
private void processExcludeFilterRule(final TransformerHandler hd, final ExcludeFilterRule rule, final int i)
throws SAXException {
atts.clear();
atts.addAttribute("", "id", "id", "CDATA", rule.getKey());
atts.addAttribute("", "name", "name", "CDATA", rule.getName());
hd.startElement("", "rule", "rule", atts);
processExcludeFilterRuleOptions(hd, rule.getOptions());
hd.endElement("", "rule", "rule");
}
/**
* @param hd
* @param map
* @throws SAXException
*/
private void processExcludeFilterRuleOptions(final TransformerHandler hd, final MultiValueMap map)
throws SAXException {
if(map.size() > 0) {
for(Iterator it = map.keySet().iterator(); it.hasNext(); ) {
String optionName = (String)it.next();
List optionValueList = (List)map.get(optionName);
for(Iterator it2 = optionValueList.iterator(); it2.hasNext(); ) {
String optionValue = (String)it2.next();
atts.clear();
atts.addAttribute("", "name", "name", "CDATA", optionName);
atts.addAttribute("", "value", "value", "CDATA", optionValue);
hd.startElement("", "option", "option", atts);
hd.endElement("", "option", "option");
}
}
}
}
protected void processNode(BinTreeTableNode node, BinTreeTableModel model, TransformerHandler hd) throws SAXException {
String type = node.getNameType(node.getBin()).toLowerCase();
String name = node.getDisplayName();
atts.clear();
atts.addAttribute("", "name", "name", "CDATA", name);
hd.startElement("", type, type, atts);
processNodes(model, hd, node.getAllChildren());
hd.endElement("", type, type);
}
/**
* overriden version of document processing
* @param model
* @param hd
* @throws SAXException
*/
protected void processDocument(BinTreeTableModel model, TransformerHandler hd)
throws SAXException {
processModelInfo(model, hd);
if (model.getVisibleColumnsCount() > 0) {
BinTreeTableNode root = (BinTreeTableNode) model.getRoot();
List children = root.getChildren();
for (Iterator it = children.iterator(); it.hasNext();) {
BinTreeTableNode node = (BinTreeTableNode) it.next();
if (node.getBin().equals(NotUsedTreeTableModel.WHOLE_TYPES)) {
processWholeTypes(model, hd, node);
} else if (node.getBin().equals(NotUsedTreeTableModel.SINGLE_MEMBERS)) {
processSingleMembers(model, hd, node);
}
}
}
}
/**
* @param model
* @param hd
* @param node
* @throws SAXException
*/
private void processSingleMembers(final BinTreeTableModel model, final TransformerHandler hd, final BinTreeTableNode node)
throws SAXException {
atts.clear();
hd.startElement("", "single-members", "single-members", atts);
processNodes(model, hd, node.getAllChildren());
hd.endElement("", "single-members", "single-members");
}
/**
* @param model
* @param hd
* @param node
* @throws SAXException
*/
private void processWholeTypes(final BinTreeTableModel model, final TransformerHandler hd, final BinTreeTableNode node)
throws SAXException {
atts.clear();
hd.startElement("", "whole-types", "whole-types", atts);
processNodes(model, hd, node.getAllChildren());
hd.endElement("", "whole-types", "whole-types");
}
}
| true
|
000a1d46d259af347784f0fe0585530731d51760
|
Java
|
machadolucas/questionnaire
|
/src/main/java/me/machadolucas/questionnaire/entity/Devices.java
|
UTF-8
| 262
| 2.046875
| 2
|
[] |
no_license
|
package me.machadolucas.questionnaire.entity;
import lombok.AllArgsConstructor;
import lombok.Getter;
@AllArgsConstructor
public enum Devices {
MOUSE("Mouse"), GAMEPAD("Gamepad"), TOUCH("Toque"), KINECT("Kinect");
@Getter
private String name;
}
| true
|
97e0628b29890426a5c3f2dc8ecf7bd57641e774
|
Java
|
awagdii/Library-System-JavaFx
|
/src/mum/mpp/controller/SuperAdmin.java
|
UTF-8
| 489
| 2.140625
| 2
|
[] |
no_license
|
package mum.mpp.controller;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import mum.mpp.business.ServicesImp;
import mum.mpp.model.Author;
import java.util.ArrayList;
public class SuperAdmin {
@FXML
protected void clickSave(ActionEvent event) {
ArrayList<String> authorsList = new ArrayList<>();
for (Author a : ServicesImp.getServicesImp().getAuthors()) {
authorsList.add(a.getFirstName() + " " + a.getLastName());
}
}
}
| true
|
e5c6421a4911097251891bd3194820f388919192
|
Java
|
PioneerX1/whattopack
|
/app/src/main/java/compioneerx1/github/whattopack/ui/PurposeActivity.java
|
UTF-8
| 2,443
| 2.28125
| 2
|
[
"MIT"
] |
permissive
|
package compioneerx1.github.whattopack.ui;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import butterknife.Bind;
import butterknife.ButterKnife;
import compioneerx1.github.whattopack.R;
public class PurposeActivity extends AppCompatActivity {
@Bind(R.id.purposeListView) ListView mPurposeListView;
@Bind(R.id.purposeButton) Button mPurposeButton;
String purposeSelection = "";
private String[] purposeArray = new String[] {
"Business", "Casual Fun", "Active Outdoors"
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_purpose);
ButterKnife.bind(this);
Intent oldIntent = getIntent();
final String location = oldIntent.getStringExtra("location");
//final String dates = oldIntent.getStringExtra("dates");
ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, purposeArray);
mPurposeListView.setAdapter(adapter);
mPurposeListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
purposeSelection = ((TextView)view).getText().toString();
Toast.makeText(PurposeActivity.this, purposeSelection + " specified", Toast.LENGTH_SHORT).show();
}
});
mPurposeButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (purposeSelection.equals("")) {
Toast.makeText(PurposeActivity.this, "Please choose an option", Toast.LENGTH_SHORT).show();
} else {
Intent newIntent = new Intent(PurposeActivity.this, ResultsActivity.class);
//newIntent.putExtra("dates", dates);
newIntent.putExtra("location", location);
newIntent.putExtra("purpose", purposeSelection);
startActivity(newIntent);
}
}
});
}
}
| true
|
75f9eb0bce3c326e156e9a4e1d16118779fbeffe
|
Java
|
zsk13/network
|
/src/main/java/network/model/CourseStudentExample.java
|
UTF-8
| 14,636
| 2.359375
| 2
|
[] |
no_license
|
package network.model;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
public class CourseStudentExample {
protected String orderByClause;
protected boolean distinct;
protected List<Criteria> oredCriteria;
public CourseStudentExample() {
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));
}
protected void addCriterionForJDBCDate(String condition, Date value, String property) {
if (value == null) {
throw new RuntimeException("Value for " + property + " cannot be null");
}
addCriterion(condition, new java.sql.Date(value.getTime()), property);
}
protected void addCriterionForJDBCDate(String condition, List<Date> values, String property) {
if (values == null || values.size() == 0) {
throw new RuntimeException("Value list for " + property + " cannot be null or empty");
}
List<java.sql.Date> dateList = new ArrayList<java.sql.Date>();
Iterator<Date> iter = values.iterator();
while (iter.hasNext()) {
dateList.add(new java.sql.Date(iter.next().getTime()));
}
addCriterion(condition, dateList, property);
}
protected void addCriterionForJDBCDate(String condition, Date value1, Date value2, String property) {
if (value1 == null || value2 == null) {
throw new RuntimeException("Between values for " + property + " cannot be null");
}
addCriterion(condition, new java.sql.Date(value1.getTime()), new java.sql.Date(value2.getTime()), property);
}
public Criteria andCsIdIsNull() {
addCriterion("cs_id is null");
return (Criteria) this;
}
public Criteria andCsIdIsNotNull() {
addCriterion("cs_id is not null");
return (Criteria) this;
}
public Criteria andCsIdEqualTo(Long value) {
addCriterion("cs_id =", value, "csId");
return (Criteria) this;
}
public Criteria andCsIdNotEqualTo(Long value) {
addCriterion("cs_id <>", value, "csId");
return (Criteria) this;
}
public Criteria andCsIdGreaterThan(Long value) {
addCriterion("cs_id >", value, "csId");
return (Criteria) this;
}
public Criteria andCsIdGreaterThanOrEqualTo(Long value) {
addCriterion("cs_id >=", value, "csId");
return (Criteria) this;
}
public Criteria andCsIdLessThan(Long value) {
addCriterion("cs_id <", value, "csId");
return (Criteria) this;
}
public Criteria andCsIdLessThanOrEqualTo(Long value) {
addCriterion("cs_id <=", value, "csId");
return (Criteria) this;
}
public Criteria andCsIdIn(List<Long> values) {
addCriterion("cs_id in", values, "csId");
return (Criteria) this;
}
public Criteria andCsIdNotIn(List<Long> values) {
addCriterion("cs_id not in", values, "csId");
return (Criteria) this;
}
public Criteria andCsIdBetween(Long value1, Long value2) {
addCriterion("cs_id between", value1, value2, "csId");
return (Criteria) this;
}
public Criteria andCsIdNotBetween(Long value1, Long value2) {
addCriterion("cs_id not between", value1, value2, "csId");
return (Criteria) this;
}
public Criteria andCIdIsNull() {
addCriterion("c_id is null");
return (Criteria) this;
}
public Criteria andCIdIsNotNull() {
addCriterion("c_id is not null");
return (Criteria) this;
}
public Criteria andCIdEqualTo(Long value) {
addCriterion("c_id =", value, "cId");
return (Criteria) this;
}
public Criteria andCIdNotEqualTo(Long value) {
addCriterion("c_id <>", value, "cId");
return (Criteria) this;
}
public Criteria andCIdGreaterThan(Long value) {
addCriterion("c_id >", value, "cId");
return (Criteria) this;
}
public Criteria andCIdGreaterThanOrEqualTo(Long value) {
addCriterion("c_id >=", value, "cId");
return (Criteria) this;
}
public Criteria andCIdLessThan(Long value) {
addCriterion("c_id <", value, "cId");
return (Criteria) this;
}
public Criteria andCIdLessThanOrEqualTo(Long value) {
addCriterion("c_id <=", value, "cId");
return (Criteria) this;
}
public Criteria andCIdIn(List<Long> values) {
addCriterion("c_id in", values, "cId");
return (Criteria) this;
}
public Criteria andCIdNotIn(List<Long> values) {
addCriterion("c_id not in", values, "cId");
return (Criteria) this;
}
public Criteria andCIdBetween(Long value1, Long value2) {
addCriterion("c_id between", value1, value2, "cId");
return (Criteria) this;
}
public Criteria andCIdNotBetween(Long value1, Long value2) {
addCriterion("c_id not between", value1, value2, "cId");
return (Criteria) this;
}
public Criteria andSIdIsNull() {
addCriterion("s_id is null");
return (Criteria) this;
}
public Criteria andSIdIsNotNull() {
addCriterion("s_id is not null");
return (Criteria) this;
}
public Criteria andSIdEqualTo(Long value) {
addCriterion("s_id =", value, "sId");
return (Criteria) this;
}
public Criteria andSIdNotEqualTo(Long value) {
addCriterion("s_id <>", value, "sId");
return (Criteria) this;
}
public Criteria andSIdGreaterThan(Long value) {
addCriterion("s_id >", value, "sId");
return (Criteria) this;
}
public Criteria andSIdGreaterThanOrEqualTo(Long value) {
addCriterion("s_id >=", value, "sId");
return (Criteria) this;
}
public Criteria andSIdLessThan(Long value) {
addCriterion("s_id <", value, "sId");
return (Criteria) this;
}
public Criteria andSIdLessThanOrEqualTo(Long value) {
addCriterion("s_id <=", value, "sId");
return (Criteria) this;
}
public Criteria andSIdIn(List<Long> values) {
addCriterion("s_id in", values, "sId");
return (Criteria) this;
}
public Criteria andSIdNotIn(List<Long> values) {
addCriterion("s_id not in", values, "sId");
return (Criteria) this;
}
public Criteria andSIdBetween(Long value1, Long value2) {
addCriterion("s_id between", value1, value2, "sId");
return (Criteria) this;
}
public Criteria andSIdNotBetween(Long value1, Long value2) {
addCriterion("s_id not between", value1, value2, "sId");
return (Criteria) this;
}
public Criteria andSTimeIsNull() {
addCriterion("s_time is null");
return (Criteria) this;
}
public Criteria andSTimeIsNotNull() {
addCriterion("s_time is not null");
return (Criteria) this;
}
public Criteria andSTimeEqualTo(Date value) {
addCriterionForJDBCDate("s_time =", value, "sTime");
return (Criteria) this;
}
public Criteria andSTimeNotEqualTo(Date value) {
addCriterionForJDBCDate("s_time <>", value, "sTime");
return (Criteria) this;
}
public Criteria andSTimeGreaterThan(Date value) {
addCriterionForJDBCDate("s_time >", value, "sTime");
return (Criteria) this;
}
public Criteria andSTimeGreaterThanOrEqualTo(Date value) {
addCriterionForJDBCDate("s_time >=", value, "sTime");
return (Criteria) this;
}
public Criteria andSTimeLessThan(Date value) {
addCriterionForJDBCDate("s_time <", value, "sTime");
return (Criteria) this;
}
public Criteria andSTimeLessThanOrEqualTo(Date value) {
addCriterionForJDBCDate("s_time <=", value, "sTime");
return (Criteria) this;
}
public Criteria andSTimeIn(List<Date> values) {
addCriterionForJDBCDate("s_time in", values, "sTime");
return (Criteria) this;
}
public Criteria andSTimeNotIn(List<Date> values) {
addCriterionForJDBCDate("s_time not in", values, "sTime");
return (Criteria) this;
}
public Criteria andSTimeBetween(Date value1, Date value2) {
addCriterionForJDBCDate("s_time between", value1, value2, "sTime");
return (Criteria) this;
}
public Criteria andSTimeNotBetween(Date value1, Date value2) {
addCriterionForJDBCDate("s_time not between", value1, value2, "sTime");
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
|
26ce36e30516f1f5091a15572208d44345644d31
|
Java
|
Kristanen/MiniSims
|
/minisims/src/main/java/hadleys/hope/minisims/renderingsystem/HitButtonListener.java
|
UTF-8
| 2,583
| 2.9375
| 3
|
[] |
no_license
|
package hadleys.hope.minisims.renderingsystem;
import hadleys.hope.minisims.Ball;
import hadleys.hope.minisims.PoolGame;
import hadleys.hope.minisims.entitysystem.EntityManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JLabel;
import javax.swing.JTextField;
import org.dyn4j.geometry.Vector2;
/**
* Takes care of the hits.
* Calculates the force which is applied to the white ball and
* validates the power and angle fields.
* @author Krista Iltanen
*/
public class HitButtonListener implements ActionListener {
private static final double MAX_POWER = 500000.0;
private JTextField power;
private JTextField angle;
private JLabel currentStrokes;
/**
* Creates new HitBUtton listener
* @param power Power text field
* @param angle Angle text field
* @param currentStrokes Field which holds the current points
*/
public HitButtonListener(JTextField power, JTextField angle, JLabel currentStrokes) {
this.power = power;
this.angle = angle;
this.currentStrokes = currentStrokes;
}
@Override
public void actionPerformed(ActionEvent e) {
String whiteBallId = PoolGame.get().getPoolTable().getWhiteBall();
Ball whiteBall = (Ball) EntityManager.get().getEntity(whiteBallId);
Double power = null;
Double angle = null;
try {
power = Double.parseDouble(this.power.getText()) / 100.0;
if (power > 1.0 || power < 0.0) {
power = null;
throw new Exception();
}
} catch (Exception ex) {
this.power.setText("Invalid input!");
}
try {
angle = Double.parseDouble(this.angle.getText());
// Angle to radians from degrees
angle = angle * (Math.PI / 180);
} catch (Exception ex) {
this.angle.setText("Invalid input!");
}
if (power != null && angle != null) {
// Calculation for the force
double forceMagnitude = power * MAX_POWER;
double forceX = Math.cos(angle) * forceMagnitude;
double forceY = (-1.0) * Math.sin(angle) * forceMagnitude;
whiteBall.hit(new Vector2(forceX, forceY));
this.currentStrokes.setText(Integer.toString(PoolGame.get().getHits()));
}
}
}
| true
|
ce3e46557dd2d3025e8556af98d042c5d3b49d03
|
Java
|
deneth-weerasinghe/PracticeMod
|
/src/main/java/com/denethweerasinghe/practicemod/setup/ClientProxy.java
|
UTF-8
| 687
| 2.125
| 2
|
[] |
no_license
|
package com.denethweerasinghe.practicemod.setup;
import com.denethweerasinghe.practicemod.handlers.HudEventHandler;
import net.minecraft.client.Minecraft;
import net.minecraft.world.World;
import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent;
public class ClientProxy implements IProxy {
@Override // client side initialisation
public void init() {
}
@Override
public void setup(FMLCommonSetupEvent event) {
}
public static void eventInit() {
HudEventHandler.init();
}
@Override
public World getClientWorld(){
return Minecraft.getInstance().world; // overrides server side code with client side code
}
}
| true
|
fac5ff9683281827a8585d56075866f4f5285574
|
Java
|
JeyhunAli/all_about_java
|
/src/Encapsulation/User_1.java
|
UTF-8
| 2,508
| 3.359375
| 3
|
[] |
no_license
|
package Encapsulation;
/**
*
* @author jey
*
* // encapsulation is one of the oops consept
//there 3 oops consepts they are called PIE factor
//polymorphism, inheritence, encapsulation.
*
* encapsulation is data hiding
*
* encapsulation is creating with private key word once any method or instance variables declared with private key word
* it can be acccesibale only within the class
*
* to access the class variable encapsulation we have to create one public layer public method then we can access
* we dont have direct access to private property
*
* to access the class method encapsulation we have to create one public layer public method then we can access
* for that just call private method inside public method in same class then access
* in test class to the public class which is holding private method property
*
*
* note: constructor also used for set the value then we can access
* encapsulation also uses setters and getters what is the differences
*
* first of all cosntructor can be default can be with paramt if constructor is used to access class var
* so then no need to create object of that calss again again
*
* but encapsulation is data hiding getters and setters so felxiable for addind data addinf method
* even private method we can set and we can get
* lets say data or requirements are dynamic we have to keep increate and decrease the value and method with setters and getters is
* easy compare constuctor
* with the constructor need to crrate object again and again
*
*
* if in the method default constructor and cosnturoctor with the param
* in the test class once i created the object of it
* it will pick default constructor
*
*
*
*/
public class User_1 {
public String name;
public int age;
private int salary;
private String adress;
public void getuserinfo() {
System.out.println("user info 1234");
}
public User_1(String name, int age, int salary, String adress) {
super();
this.name = name;
this.age = age;
this.salary = salary;
this.adress = adress;
}
public void getUser_adress() {
System.out.println("user adress");
}
private void getBank_Account() {
System.out.println("bank account number is 567t7654we67686");
}
public void getUserBankData() {
getBank_Account();
}
public int getSalary() {
System.out.println("user1 salary " + salary);
return salary;
}
public String getUserAddress() {
return adress;
}
}
| true
|
0321c540d12804b06842631655a1cfbc6d16b825
|
Java
|
joss-io/io.joss.hillbilly
|
/core/src/main/java/com/jive/hillbilly/client/DispatchingClientTransactionListener.java
|
UTF-8
| 884
| 2.203125
| 2
|
[] |
no_license
|
package com.jive.hillbilly.client;
import java.util.concurrent.Executor;
import com.jive.sip.dummer.txn.ClientTransactionListener;
import com.jive.sip.dummer.txn.SipTransactionErrorInfo;
import com.jive.sip.dummer.txn.SipTransactionResponseInfo;
class DispatchingClientTransactionListener implements ClientTransactionListener
{
private final Executor executor;
private final ClientTransactionListener listener;
DispatchingClientTransactionListener(final Executor executor, final ClientTransactionListener listener)
{
this.executor = executor;
this.listener = listener;
}
@Override
public void onResponse(final SipTransactionResponseInfo res)
{
this.executor.execute(() -> this.listener.onResponse(res));
}
@Override
public void onError(final SipTransactionErrorInfo err)
{
this.executor.execute(() -> this.listener.onError(err));
}
}
| true
|
a1c33d6eade2b6265f59eaa41ad7c6ab4eda58a5
|
Java
|
vassik/bvr
|
/no.sintef.bvr.model/src/bvr/ChoiceVSpec.java
|
UTF-8
| 3,277
| 2.4375
| 2
|
[] |
no_license
|
/**
*/
package bvr;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Choice VSpec</b></em>'.
* <!-- end-user-doc -->
*
* <!-- begin-model-doc -->
* <p class="MsoNormal"><span style="font-size:8pt;font-family:Tahoma;">A ChoiceVSpec is a VSpec which either Choice or ChoiceOccurence.</span></p><p><span style="font-size:8pt;font-family:Tahoma;"></span>####CVLSemanticStart####</p><p>Invariant : If a choice is implied by parent, it must have a parent.</p><p>OCL :</p><p>-- Choice</p><p>-- If a choice is implied by parent, it must have a parent.</p><p>context Choice :</p><p>inv isImpliedByParentsImpliesAParent :</p><p>self.isImpliedByParent implies VSpec.allInstances()->exists(vSpec | vSpec.childVSpec->includes(self))</p><p>####CVLSemanticEnd####</p>
* <!-- end-model-doc -->
*
* <p>
* The following features are supported:
* <ul>
* <li>{@link bvr.ChoiceVSpec#isDefaultResolution <em>Default Resolution</em>}</li>
* <li>{@link bvr.ChoiceVSpec#isIsImpliedByParent <em>Is Implied By Parent</em>}</li>
* </ul>
* </p>
*
* @see bvr.BvrPackage#getChoiceVSpec()
* @model abstract="true"
* @generated
*/
public interface ChoiceVSpec extends VSpec {
/**
* Returns the value of the '<em><b>Default Resolution</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* <!-- begin-model-doc -->
* <p>The default resolution of this choice. (If True then the default is a PosResolution, if False then the default is a NegResolution)</p>
* <!-- end-model-doc -->
* @return the value of the '<em>Default Resolution</em>' attribute.
* @see #setDefaultResolution(boolean)
* @see bvr.BvrPackage#getChoiceVSpec_DefaultResolution()
* @model ordered="false"
* @generated
*/
boolean isDefaultResolution();
/**
* Sets the value of the '{@link bvr.ChoiceVSpec#isDefaultResolution <em>Default Resolution</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Default Resolution</em>' attribute.
* @see #isDefaultResolution()
* @generated
*/
void setDefaultResolution(boolean value);
/**
* Returns the value of the '<em><b>Is Implied By Parent</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* <!-- begin-model-doc -->
* <p>When True then resolving the parent VSpec positively implies deciding this choice positively. A VSpec resolution is positive if it is a choice decided positively, or any classifier instantiation, or any value assignment to a variable.<br><br>For a root choice, True implies it must be resolved positively.</p>
* <!-- end-model-doc -->
* @return the value of the '<em>Is Implied By Parent</em>' attribute.
* @see #setIsImpliedByParent(boolean)
* @see bvr.BvrPackage#getChoiceVSpec_IsImpliedByParent()
* @model required="true" ordered="false"
* @generated
*/
boolean isIsImpliedByParent();
/**
* Sets the value of the '{@link bvr.ChoiceVSpec#isIsImpliedByParent <em>Is Implied By Parent</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Is Implied By Parent</em>' attribute.
* @see #isIsImpliedByParent()
* @generated
*/
void setIsImpliedByParent(boolean value);
} // ChoiceVSpec
| true
|
728d0eb4ffdbc061dd0bf8d448df6e7f83922bf2
|
Java
|
szotaa/torrentr
|
/src/test/java/pl/szotaa/torrentr/service/SearchServiceTest.java
|
UTF-8
| 1,750
| 2.109375
| 2
|
[
"MIT"
] |
permissive
|
package pl.szotaa.torrentr.service;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.springframework.beans.factory.annotation.Autowired;
import pl.szotaa.UnitTest;
import pl.szotaa.torrentr.domain.Result;
import pl.szotaa.torrentr.worker.AbstractScrapWorker;
import pl.szotaa.torrentr.worker.ScrapWorkerSetFactory;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
@RunWith(PowerMockRunner.class)
@Category(UnitTest.class)
@PrepareForTest(ScrapWorkerSetFactory.class)
public class SearchServiceTest {
@Autowired
private SearchService searchService;
@Test
@Ignore //todo: fix
public void search_resultsAreFound() throws Exception {
//given
AbstractScrapWorker scrapWorker = PowerMockito.mock(AbstractScrapWorker.class);
Set<Result> results = new HashSet<>(Arrays.asList(
Result.builder().magnetLink("magnetLink1").build(),
Result.builder().magnetLink("magnetLink2").build(),
Result.builder().magnetLink("magnetLink3").build()
));
PowerMockito.when(scrapWorker.call()).thenReturn(results);
Set<AbstractScrapWorker> workers = new HashSet<>();
workers.add(scrapWorker);
PowerMockito.mockStatic(ScrapWorkerSetFactory.class);
PowerMockito.when(ScrapWorkerSetFactory.getSetOfScrapWorkers(Mockito.anyString())).thenReturn(workers);
System.out.println(searchService.search("").size());
}
}
| true
|
cba01d47700805472bd3bf2bf3f4a894b0c61b24
|
Java
|
UNAdopcion/Backend
|
/unadopcion/src/main/java/com/unadopcion/unadopcion/repositorio/ContactoRepositorio.java
|
UTF-8
| 304
| 1.570313
| 2
|
[] |
no_license
|
package com.unadopcion.unadopcion.repositorio;
import com.unadopcion.unadopcion.modelo.Contacto;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface ContactoRepositorio extends CrudRepository<Contacto, Integer> {
}
| true
|
50f261d37d0d3c486f090f210296e3243562f9dd
|
Java
|
Cxyour/thewishofthestarlanguage
|
/app/src/main/java/com/example/lenovo/thewishofthestarlanguage/view/personal/adapter/FollowListAdapter.java
|
UTF-8
| 5,569
| 1.835938
| 2
|
[] |
no_license
|
package com.example.lenovo.thewishofthestarlanguage.view.personal.adapter;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.support.v4.graphics.drawable.RoundedBitmapDrawable;
import android.support.v4.graphics.drawable.RoundedBitmapDrawableFactory;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.ImageViewTarget;
import com.example.lenovo.thewishofthestarlanguage.R;
import com.example.lenovo.thewishofthestarlanguage.model.biz.FollowService;
import com.example.lenovo.thewishofthestarlanguage.model.config.App;
import com.example.lenovo.thewishofthestarlanguage.model.config.Constant;
import com.example.lenovo.thewishofthestarlanguage.model.entity.FollowBean;
import com.example.lenovo.thewishofthestarlanguage.model.entity.SaveBean;
import com.example.lenovo.thewishofthestarlanguage.model.http.RetrofitUtils;
import java.util.List;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
/**
* Created by Lenovo on 2018/5/9.
*/
public class FollowListAdapter extends BaseAdapter {
private List<FollowBean.DataBean.ListBean> listBeans;
private final SharedPreferences user;
private final SharedPreferences.Editor edit;
private final FollowService followService;
public FollowListAdapter(List<FollowBean.DataBean.ListBean> listBeans) {
this.listBeans = listBeans;
user = App.context.getSharedPreferences(Constant.CookieSP, Context.MODE_PRIVATE);
edit = user.edit();
followService = RetrofitUtils.getInstance().getFollowService();
}
@Override
public int getCount() {
return listBeans.size();
}
@Override
public Object getItem(int position) {
return listBeans.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
holder = new ViewHolder();
convertView = App.context.getLayoutInflater().inflate(R.layout.follow_item, parent, false);
holder.follow_item_img = convertView.findViewById(R.id.follow_item_img);
holder.follow_item_btn = convertView.findViewById(R.id.follow_item_btn);
holder.follow_item_nickname = convertView.findViewById(R.id.follow_item_nickname);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
final ViewHolder finalHolder = holder;
holder.follow_item_btn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
finalHolder.follow_item_btn.setText("已关注");
followService.follow(listBeans.get(position).getAttentionId(), user.getInt("user_id", 0))
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<SaveBean>() {
@Override
public void accept(SaveBean saveBean) throws Exception {
Toast.makeText(App.context, saveBean.getMessage(), Toast.LENGTH_SHORT).show();
}
});
} else {
finalHolder.follow_item_btn.setText("关注");
followService.abolishConcern(listBeans.get(position).getAttentionId(), user.getInt("user_id", 0))
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<SaveBean>() {
@Override
public void accept(SaveBean saveBean) throws Exception {
Toast.makeText(App.context, saveBean.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
});
Glide.with(App.context).load(listBeans.get(position).getPhoto()).asBitmap().into(new ImageViewTarget<Bitmap>(finalHolder.follow_item_img) {
@Override
protected void setResource(Bitmap bitmap) {
RoundedBitmapDrawable drawable = RoundedBitmapDrawableFactory.create(App.context.getResources(), bitmap);
drawable.setCircular(true);
finalHolder.follow_item_img.setBackground(drawable);
}
});
holder.follow_item_nickname.setText(listBeans.get(position).getNickname());
return convertView;
}
class ViewHolder {
public ImageView follow_item_img;
public CheckBox follow_item_btn;
public TextView follow_item_nickname;
}
}
| true
|
d4bfa9fb399d556c6c23e52226d764fea8c44bb0
|
Java
|
jboss-fuse/narayana-spring-boot
|
/openshift/recovery-controller/src/main/java/me/snowdrop/boot/narayana/openshift/recovery/RecoveryErrorDetector.java
|
UTF-8
| 913
| 1.5625
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright 2020 Red Hat, Inc, and individual contributors.
*
* 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 me.snowdrop.boot.narayana.openshift.recovery;
/**
* Base interface of recovery error detectors.
*
* @author <a href="mailto:nferraro@redhat.com">Nicola Ferraro</a>
*/
public interface RecoveryErrorDetector {
void startDetection();
void stopDetection();
boolean errorsDetected();
}
| true
|
63fe8c8a77fa0fe7d24a13cb5173369ee061f424
|
Java
|
thelinh95/Open_Jdk8u_Test
|
/OpenJdk8uTest/src/test/java/io/File/SetLastModified.java
|
UTF-8
| 4,730
| 2.328125
| 2
|
[] |
no_license
|
package test.java.io.File;
/*
* Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
@bug 4091757 6652379
@summary Basic test for setLastModified method
*/
import java.io.File;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import test.java.io.*;
public class SetLastModified {
private static void ck(File f, long nt, long rt) throws Exception {
if (rt == nt) return;
if ((rt / 10 == nt / 10)
|| (rt / 100 == nt / 100)
|| (rt / 1000 == nt / 1000)
|| (rt / 10000 == (nt / 10000))) {
System.err.println(f + ": Time set to " + nt
+ ", rounded down by filesystem to " + rt);
return;
}
if ((rt / 10 == (nt + 5) / 10)
|| (rt / 100 == (nt + 50) / 100)
|| (rt / 1000 == (nt + 500) / 1000)
|| (rt / 10000 == ((nt + 5000) / 10000))) {
System.err.println(f + ": Time set to " + nt
+ ", rounded up by filesystem to " + rt);
return;
}
throw new Exception(f + ": Time set to " + nt
+ ", then read as " + rt);
}
public static void main(String[] args) throws Exception {
File d = new File(System.getProperty("test.dir", "."));
File d2 = new File(d, "x.SetLastModified.dir");
File f = new File(d2, "x.SetLastModified");
long ot, t;
/* New time: One week ago */
long nt = System.currentTimeMillis() - 1000 * 60 * 60 * 24 * 7;
if (f.exists()) f.delete();
if (d2.exists()) d2.delete();
if (!d2.mkdir()) {
throw new Exception("Can't create test directory " + d2);
}
boolean threw = false;
try {
d2.setLastModified(-nt);
} catch (IllegalArgumentException x) {
threw = true;
}
if (!threw)
throw new Exception("setLastModified succeeded with a negative time");
ot = d2.lastModified();
if (ot != 0) {
if (d2.setLastModified(nt)) {
ck(d2, nt, d2.lastModified());
d2.setLastModified(ot);
} else {
System.err.println("Warning: setLastModified on directories "
+ "not supported");
}
}
if (f.exists()) {
if (!f.delete())
throw new Exception("Can't delete test file " + f);
}
if (f.setLastModified(nt))
throw new Exception("Succeeded on non-existent file: " + f);
// set/check last modified on files of size 1, 1GB+1, 2GB+1, ..
// On Windows we only test with a tiny file as that platform doesn't
// support sparse files by default and so the test takes too long.
final long G = 1024L * 1024L * 1024L;
final long MAX_POSITION =
System.getProperty("os.name").startsWith("Windows") ? 0L : 3L*G;
long pos = 0L;
while (pos <= MAX_POSITION) {
try (FileChannel fc = new FileOutputStream(f).getChannel()) {
fc.position(pos).write(ByteBuffer.wrap("x".getBytes()));
}
ot = f.lastModified();
System.out.format("check with file size: %d\n", f.length());
if (!f.setLastModified(nt))
throw new Exception("setLastModified failed on file: " + f);
ck(f, nt, f.lastModified());
pos += G;
}
if (!f.delete()) throw new Exception("Can't delete test file " + f);
if (!d2.delete()) throw new Exception("Can't delete test directory " + d2);
}
}
| true
|
9ef0dac292133edd066d70b760980253200734e6
|
Java
|
gradle/performance-comparisons
|
/large-multiproject/project67/src/test/java/org/gradle/test/performance67_5/Test67_478.java
|
UTF-8
| 292
| 1.78125
| 2
|
[] |
no_license
|
package org.gradle.test.performance67_5;
import static org.junit.Assert.*;
public class Test67_478 {
private final Production67_478 production = new Production67_478("value");
@org.junit.Test
public void test() {
assertEquals(production.getProperty(), "value");
}
}
| true
|
18f657d2df2f95124c890dbcec0362a76509ec52
|
Java
|
balsampearshen/for
|
/WowYi/src/com/balsampearshz/wowyi/util/StringUtil.java
|
UTF-8
| 1,992
| 3.265625
| 3
|
[] |
no_license
|
package com.balsampearshz.wowyi.util;
/**
* 字符串操作类
*
* @author ylx
*
*/
public class StringUtil {
/**
* 不为空 返回真
*
* @param str
* 字符串
* @return 如果字符串不为空且长度大于1 返回真 ,其他返回假
*/
public static boolean isNotBlank(String str) {
return str != null && !(null==str||str.equals(""));
//str.isEmpty()
}
/**
* 如果为空 返回真
*
* @param str
* 字符串
* @return 如果为空或长度等于零,返回真,其他返回假
*/
public static boolean isBlank(String str) {
return str == null || str.length() == 0;
}
/**
* 去掉空格不为空 返回真
*
* @param str
* 字符串
* @return 如果字符串不为空且去掉空格长度大于1 返回真 ,其他返回假
*/
public static boolean isNotTrimBlank(String str) {
return str != null && !(null==str.trim() || str.trim().equals(""));
}
/**
* 去掉空格为空返回真
*
* @param str
* 字符串
* @return 如果字符串为空或去掉空格长度为0,返回真,其他返回假
*/
public static boolean isTrimBlank(String str) {
return str == null || (null==str.trim() || str.trim().equals(""));
}
/**
* 空串
*/
public final static String EMPTY = "";
/**
* 首字母大写
*
* @param str
* 要转换的字符串
* @return 首字母大写的字符串
*/
public static String capFirstUpperCase(String str) {
if (isBlank(str)) {
return str;
}
return str.substring(0, 1).toUpperCase() + str.substring(1);
}
/**
* 首字母小写
*
* @param str
* 要转换的字符串
* @return 首字母小写的字符串
*/
public static String capFirstLowerCase(String str) {
if (isBlank(str)) {
return str;
}
return str.substring(0, 1).toLowerCase() + str.substring(1);
}
}
| true
|
9ffb7a93a7b7d5936910b82b318a22884e55c47e
|
Java
|
satyam289/Data-structure-and-Algorithm
|
/src/Array/AntiDiagonal.java
|
UTF-8
| 3,026
| 4.15625
| 4
|
[
"MIT"
] |
permissive
|
package Array;
import java.util.ArrayList;
/*
(0, 0)
(0, 1), (1, 0)
(0,2), (1, 1), (2, 0)
(1, 2), (2, 1)
(2, 2)
*/
// https://www.geeksforgeeks.org/zigzag-or-diagonal-traversal-of-matrix/
class AntiDiagonal {
public static void diagonal(int[][] matrix, int row, int column) {
for (int line = 1; line <= (row + column - 1); line++) {
int start_col = Math.max(0, line - row);
int count = Math.min(line, column - start_col);
for (int k = 0; k < count; k++) {
int start_row = Math.min(line, row);
System.out.print(matrix[start_row - k - 1][start_col + k] + " ");
}
System.out.println("");
}
}
private static void diagonalOrder2(int[][] arr, int R, int C) {
for (int k = 0; k < R; k++) {
System.out.print(arr[k][0] + " "); // first element in diagonal already printed
// set row index for next point in diagonal
int i = k - 1;
// set column index for next point in diagonal
int j = 1;
/* Print Diagonally upward */
while (isValid(i, j, R, C)) {
System.out.print(arr[i][j] + " ");
i--;
j++;
}
System.out.println("");
}
for (int k = 1; k < C; k++) {
System.out.print(arr[R - 1][k] + " ");
// set row index for next point in diagonal
int i = R - 2;
// set column index for next point in diagonal
int j = k + 1;
/* Print Diagonally upward */
while (isValid(i, j, R, C)) {
System.out.print(arr[i][j] + " ");
i--;
j++;
}
System.out.println("");
}
}
static boolean isValid(int i, int j, int R, int C) {
if (i < 0 || i >= R || j >= C || j < 0)
return false;
return true;
}
public static void diagonalOrder3(int[][] arr, int n, int m) {
// the 2D vector will have (n+m-1) rows that is equal to the number of diagnols
ArrayList<ArrayList<Integer>> ans = new ArrayList<ArrayList<Integer>>(n + m - 1);
for (int i = 0; i < n + m - 1; i++) {
ans.add(new ArrayList<Integer>());
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
(ans.get(i + j)).add(arr[i][j]);
}
}
for (int i = 0; i < ans.size(); i++) {
for (int j = ans.get(i).size() - 1; j >= 0; j--) { // reading from opposite
System.out.print(ans.get(i).get(j) + " ");
}
System.out.println();
}
}
public static void main(String[] args) {
int M[][] = { { 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 },
{ 13, 14, 15, 16 },
{ 17, 18, 19, 20 }, };
diagonal(M, 5, 4);
System.out.println(" ---2nd Apporach--- ");
diagonalOrder2(M, 5, 4);
System.out.println(" ---3rd Apporach--- ");
diagonalOrder3(M, 5, 4);
}
}
| true
|
aa5bb64362e0ed101b53eee829c0b72da0d04dda
|
Java
|
AlexanderTolmachev/No-SQL-DataBase
|
/no-sql-database-server/src/java/ru/compscicenter/db/tolmachev/nosqldb/server/dbmanager/Balancer.java
|
UTF-8
| 9,407
| 2.875
| 3
|
[] |
no_license
|
package ru.compscicenter.db.tolmachev.nosqldb.server.dbmanager;
import ru.compscicenter.db.tolmachev.nosqldb.server.database.DataBase;
import ru.compscicenter.db.tolmachev.nosqldb.server.database.Row;
import ru.compscicenter.db.tolmachev.nosqldb.server.database.TableDescription;
import ru.compscicenter.db.tolmachev.nosqldb.server.exceptions.DBUnavailabilityException;
import ru.compscicenter.db.tolmachev.nosqldb.server.exceptions.DataBaseRequestException;
import ru.compscicenter.db.tolmachev.nosqldb.server.exceptions.DataBaseTableException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Balancer {
private Map<Pattern, DataBase> databases;
private static Balancer balancer;
public static Balancer getInstance() {
if (balancer == null) {
balancer = new Balancer();
}
return balancer;
}
private Balancer() {
DataBase db1 = new DataBase();
DataBase db2 = new DataBase();
DataBase db3 = new DataBase();
databases = new HashMap<Pattern, DataBase>();
databases.put(Pattern.compile("[a-mA-Mа-нА-Н]"), db1);
databases.put(Pattern.compile("[n-zN-Zо-яО-Я]"), db2);
databases.put(Pattern.compile("[^a-zA-ZA-Яа-я]"), db3);
}
/**
* get descriptions of all tables in the database
*
* @return set of descriptions, where each descriptions - is a list that contains name of the table at 0 index,
* and column names. Key name has 1 index in list.
*/
public Map<String, TableDescription> getTablesInDataBaseDescription() {
Map<String, TableDescription> result = new HashMap<String, TableDescription>();
for (DataBase db : databases.values()) {
for (TableDescription td : db.getTablesDescriptions()) {
String tableName = td.getName();
if (!result.containsKey(tableName)) {
result.put(tableName, td);
}
}
}
return result;
}
/**
* create table with given name and list of column names. Key name has 0 index in the list
*
* @param tableName - name of the table
* @param columnNames - name of columns as list of strings
* @return - if table created successfully. false - if there already exists table with such name
* @throws DataBaseTableException - if something wrong
*/
public boolean createTable(String tableName, List<String> columnNames) throws DataBaseTableException {
for (DataBase db : databases.values()) {
boolean result = db.createTable(tableName, columnNames);
if (!result) {
return false;
}
}
return true;
}
/**
* create table with given description
*
* @param tableDescription - given description
* @return true - if database modified
* @throws DataBaseTableException - if something wrong
*/
public boolean createTable(TableDescription tableDescription) throws DataBaseTableException {
String tableName = tableDescription.getName();
List<String> columnNames = tableDescription.getColumnNames();
return createTable(tableName, columnNames);
}
/**
* drop table with such name
*
* @param tableName - table name
* @return true - if deletion successful. false - if there is no table with such name
*/
public boolean dropTable(String tableName) {
for (DataBase db : databases.values()) {
boolean result = db.dropTable(tableName);
if (!result) {
return false;
}
}
return true;
}
/**
* add row to the table with given name
*
* @param tableName - name of the table
* @param args - row as list of args, key has 0 index
* @throws DBUnavailabilityException - database is not available
* @throws DataBaseRequestException - wrong request
* @throws DataBaseTableException - if something wrong with adding data to th table
*/
public void add(String tableName, List<String> args) throws DBUnavailabilityException,
DataBaseRequestException, DataBaseTableException {
if (args.isEmpty()) {
throw new DataBaseRequestException("zero args in request list");
}
String key = args.get(0);
if (key == null) {
throw new DataBaseRequestException("key shouldn't be null");
}
String firstCharAtName = key.substring(0, 1);
DataBase db = getDataBaseByKey(firstCharAtName);
db.add(tableName, args);
}
/**
* get row from table with given name by key
*
* @param tableName - table name
* @param key -
* @return row
* @throws DBUnavailabilityException - database is not available
* @throws DataBaseRequestException - wrong request
* @throws DataBaseTableException - if something wrong with adding data to th table
*/
public Row getByKey(String tableName, String key) throws DBUnavailabilityException,
DataBaseRequestException, DataBaseTableException {
if (key == null) {
throw new DataBaseRequestException("key shouldn't be null");
}
String firstCharAtName = key.substring(0, 1);
DataBase db = getDataBaseByKey(firstCharAtName);
return db.getByKey(tableName, key);
}
/**
* get all rows from the table with given name
*
* @param tableName table name
* @return all rows
* @throws DataBaseTableException - if something wrong with adding data to th table
*/
public Map<String, Row> getAll(String tableName) throws DataBaseTableException {
Map<String, Row> resultMap = new HashMap<String, Row>();
for (DataBase db : databases.values()) {
Map<String, Row> allInCurrentDB = db.getAll(tableName);
for (String key : allInCurrentDB.keySet()) {
Row row = allInCurrentDB.get(key);
resultMap.put(key, row);
}
}
return resultMap;
}
/**
* get description for the table with given name
*
* @param tableName - name of the table
* @return column names as string list
* @throws DataBaseTableException - if something wrong
*/
public List<String> getTableDescription(String tableName) throws DataBaseTableException {
TableDescription td = null;
for (DataBase db : databases.values()) {
td = db.getTableDescription(tableName);
if (td != null) {
return td.getColumnNames();
}
}
return null;
}
/**
* remove from table with given name by key
*
* @param tableName - table name
* @param key -
* @return true - if databse modified
* @throws DBUnavailabilityException - database is not available
* @throws DataBaseRequestException - wrong request
* @throws DataBaseTableException - if something wrong with adding data to th table
*/
public boolean removeByKey(String tableName, String key) throws DBUnavailabilityException,
DataBaseRequestException, DataBaseTableException {
if (key == null) {
throw new DataBaseRequestException("key shouldn't be null");
}
String firstCharAtName = key.substring(0, 1);
DataBase db = getDataBaseByKey(firstCharAtName);
return db.removeByKey(tableName, key);
}
/**
* update row in the table with given name
*
* @param tableName - table name
* @param args - row
* @return true - if database modified
* @throws DBUnavailabilityException - database is not available
* @throws DataBaseRequestException - wrong request
* @throws DataBaseTableException - if something wrong with adding data to th table
*/
public boolean updateByName(String tableName, List<String> args) throws DBUnavailabilityException,
DataBaseRequestException, DataBaseTableException {
if (args.isEmpty()) {
throw new DataBaseRequestException("zero args in request list");
}
String key = args.get(0);
if (key == null) {
throw new DataBaseRequestException("key shouldn't be null");
}
String firstCharAtName = key.substring(0, 1);
DataBase db = getDataBaseByKey(firstCharAtName);
return db.updateByKey(tableName, args);
}
/**
* get all available table names from database
*
* @return - set with table names
*/
public Set<String> getAllAvailableTableNames() {
Set<String> result = new HashSet<String>();
for (DataBase db : databases.values()) {
Set<String> namesOfAvailableTablesInCurrentDB = db.getTableNames();
result.addAll(namesOfAvailableTablesInCurrentDB);
}
return result;
}
private DataBase getDataBaseByKey(String key) throws DBUnavailabilityException {
for (Pattern regexp : databases.keySet()) {
Matcher matcher = regexp.matcher(key);
if (matcher.find()) {
return databases.get(regexp);
}
}
throw new DBUnavailabilityException("database is unavailable");
}
}
| true
|
a15339bcba319d91a96de3679e206e052aaef40e
|
Java
|
UnlimitedCodesWorks/husbandry
|
/src/main/java/xin/yiliya/service/ServiceEvaluateService.java
|
UTF-8
| 1,751
| 1.914063
| 2
|
[] |
no_license
|
package xin.yiliya.service;
import com.github.pagehelper.PageInfo;
import xin.yiliya.pojo.EvaluateService;
import xin.yiliya.pojo.ServiceEvalutePerMonth;
import java.util.Date;
public interface ServiceEvaluateService {
//添加一个评论
//返回:评论id,若返回0则添加评论失败
Integer addEvaluate(EvaluateService evaluateService);
//通过评论id删除一个评论
//返回:删除是否成功的布尔值
Boolean deleteEvaluateById(Integer evaluateId);
//列出服务下的所有评论(包括子回复)
//参数:pattern为true时代表默认模式按时间排序,为false时代表按热度排序
// sonPageSize代表子回复所显示的个数
//返回: 多个评论集合
PageInfo<EvaluateService> getAllEvaluateByServiceId(
Integer serviceId,Boolean pattern,int currentPage,int pageSize,int sonPageSize);
//为评论点赞
//返回:更新是否成功的布尔值
Boolean support(Integer evaluateId);
//为评论取消赞
//返回:更新是否成功的布尔值
Boolean unsupport(Integer evaluateId);
//获取服务评分
//返回:该服务的评分
Float getGradeByServiceId(Integer serviceId);
//获取服务评分人数
//返回:服务评分人数
Integer getGradeNumByServiceId(Integer serviceId);
//获得某月份的服务评分曲线信息
//参数:time为当前月份,如格式为2017-7
//返回:该月每天的评分记录
ServiceEvalutePerMonth getGradePerMonthBySeviceId(Integer serviceId,String serviceName,Date time);
//判断用户是否有评论资格
//返回:true为有,false为无
Boolean ReviewQualification(Integer serviceId,Integer userId);
}
| true
|
7cfe65ad8347bc01219e9fbfbe4784cb40705b3f
|
Java
|
mslowiak/Design-patterns
|
/src/ChainOfResponsibility/Cargo.java
|
UTF-8
| 519
| 2.921875
| 3
|
[] |
no_license
|
package ChainOfResponsibility;
public class Cargo {
private String country;
private double weight;
public Cargo(String country, double weight) {
this.country = country;
this.weight = weight;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
}
| true
|
c002a47709134b332150faaa99a23355d79bb561
|
Java
|
Kaifi7/data_structures
|
/Demo/src/linked_list/DetectAndRemoveLoopInLL.java
|
UTF-8
| 1,024
| 3.6875
| 4
|
[] |
no_license
|
package linked_list;
import java.util.HashMap;
public class DetectAndRemoveLoopInLL {
static class Node{
int data;
Node next;
Node(int d){
data = d;
next = null;
}
}
static Node head;
static void push(int new_data) {
Node new_node = new Node(new_data);
new_node.next= head;
head = new_node;
}
static HashMap<Integer, Integer>map = new HashMap<Integer, Integer>();
static int key=0;
static Node prev = null;
static boolean checkLoop(Node node) {
while(node!=null) {
if(map.containsValue(node.data)) {
prev.next = null;
return true;
}
map.put(++key, node.data);
prev =node;
node = node.next;
}
return false;
}
static void printList(Node node) {
while(node!=null) {
System.out.print(node.data + " ");
node = node.next;
}
}
public static void main(String[] args) {
push(20);
push(4);
push(15);
push(10);
head.next.next.next.next = head;
if(checkLoop(head))
System.out.println("Loop Found");
else
System.out.println("No Loop");
}
}
| true
|
f5c76b3e4dbcb5bdc4efc736acd8770da2c2fec6
|
Java
|
orlandoburli/personalerp-legacy
|
/src/br/com/orlandoburli/personalerp/facades/reports/financeiro/resumofinanceiro/RelatorioResumoFinanceiroExcelFacade.java
|
ISO-8859-1
| 9,714
| 1.75
| 2
|
[] |
no_license
|
package br.com.orlandoburli.personalerp.facades.reports.financeiro.resumofinanceiro;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.sql.Date;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletOutputStream;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import br.com.orlandoburli.core.dao.financeiro.contasapagar.ContaPagarDAO;
import br.com.orlandoburli.core.dao.sistema.LojaDAO;
import br.com.orlandoburli.core.vo.acesso.UsuarioVO;
import br.com.orlandoburli.core.vo.sistema.EmpresaVO;
import br.com.orlandoburli.core.vo.sistema.LojaVO;
import br.com.orlandoburli.core.web.framework.facades.BaseFacade;
import br.com.orlandoburli.core.web.framework.filters.IgnoreFacadeAuthentication;
@IgnoreFacadeAuthentication
public class RelatorioResumoFinanceiroExcelFacade extends BaseFacade {
private static final long serialVersionUID = 1L;
private Date DataInicialVencimento;
private Date DataFinalVencimento;
private String FlgTodasLojas;
private String FlgPesoDespesa;
private String FlgContasOcultas;
private String Lojas;
private EmpresaVO empresasessao;
private LojaVO lojasessao;
private UsuarioVO usuariosessao;
public void execute() {
try {
Integer CodigoEmpresa = null;
Integer CodigoLoja = null;
Integer CodigoEmpresaGlobal = null;
Integer CodigoLojaGlobal = null;
// if (getFlgTodasLojas() == null || getFlgTodasLojas().equals("N")) {
// CodigoEmpresa = getEmpresasessao().getCodigoEmpresa();
// CodigoLoja = getLojasessao().getCodigoLoja();
//
// if (getFlgPesoDespesa() == null || getFlgPesoDespesa().equals("1")) {
// CodigoEmpresaGlobal = getEmpresasessao().getCodigoEmpresa();
// CodigoLojaGlobal = getLojasessao().getCodigoLoja();
// }
// }
// Lojas Selecionadas
List<LojaVO> listLojas = new ArrayList<LojaVO>();
LojaDAO lojaDao = new LojaDAO();
String strLojaSelecionada = "";
for (String s : getLojas().split("\\;")) {
Integer codigoEmpresa = Integer.parseInt(s.split("\\.")[0]);
Integer codigoLoja = Integer.parseInt(s.split("\\.")[1]);
//parameters.put("CodigoEmpresa", codigoEmpresa);
//parameters.put("CodigoLoja", codigoLoja);
CodigoEmpresa = codigoEmpresa;
CodigoLoja = codigoLoja;
if (getFlgPesoDespesa() == null || getFlgPesoDespesa().equals("1")) {
CodigoEmpresaGlobal = getEmpresasessao().getCodigoEmpresa();
CodigoLojaGlobal = getLojasessao().getCodigoLoja();
} else {
CodigoEmpresaGlobal = null;
CodigoLojaGlobal = null;
}
LojaVO loja = new LojaVO();
loja.setCodigoEmpresa(codigoEmpresa);
loja.setCodigoLoja(codigoLoja);
try {
loja = lojaDao.get(loja);
listLojas.add(loja);
} catch (SQLException e) {
e.printStackTrace();
}
if (!strLojaSelecionada.equals("")) {
strLojaSelecionada += " UNION ALL ";
// Se tem mais de uma, vai nulo
CodigoEmpresa = null;
CodigoLoja = null;
CodigoEmpresaGlobal = null;
CodigoLojaGlobal = null;
}
strLojaSelecionada += "SELECT " + codigoEmpresa + ", " + codigoLoja;
// Lojas = strLojaSelecionada;
}
XSSFWorkbook wb = new XSSFWorkbook();
CreationHelper helper = wb.getCreationHelper();
XSSFSheet sheet = wb.createSheet();
ResultSet result = null;
try {
result = new ContaPagarDAO().getListContasResumo(CodigoEmpresa, CodigoLoja, CodigoEmpresaGlobal, CodigoLojaGlobal, getDataInicialVencimento(), getDataFinalVencimento(), getFlgContasOcultas(), strLojaSelecionada);
int linha = 0;
XSSFRow rowCabecalho = sheet.createRow(linha);
rowCabecalho.createCell(0);
rowCabecalho.getCell(0).setCellValue("Numero Plano de Contas");
rowCabecalho.createCell(1);
rowCabecalho.getCell(1).setCellValue("Nome Plano de Contas");
rowCabecalho.createCell(2);
rowCabecalho.getCell(2).setCellValue("Crdito");
rowCabecalho.createCell(3);
rowCabecalho.getCell(3).setCellValue("% Total Crdito");
rowCabecalho.createCell(4);
rowCabecalho.getCell(4).setCellValue("Dbito");
rowCabecalho.createCell(5);
rowCabecalho.getCell(5).setCellValue("% Total Dbito");
rowCabecalho.createCell(6);
rowCabecalho.getCell(6).setCellValue("% Sobre Receita");
while (result.next()) {
linha++;
XSSFRow rowDetalhe = sheet.createRow(linha);
// Cria todas as celulas
for (int i = 0; i < 7; i++) {
rowDetalhe.createCell(i);
}
CellStyle styleNumero = wb.createCellStyle();
styleNumero.setDataFormat(helper.createDataFormat().getFormat("0.00"));
CellStyle stylePercentual = wb.createCellStyle();
stylePercentual.setDataFormat(helper.createDataFormat().getFormat("0.00%"));
rowDetalhe.getCell(0).setCellType(Cell.CELL_TYPE_STRING);
rowDetalhe.getCell(1).setCellType(Cell.CELL_TYPE_STRING);
rowDetalhe.getCell(0).setCellValue(result.getString("numeroplanoconta"));
rowDetalhe.getCell(1).setCellValue(result.getString("nomeplanoconta"));
rowDetalhe.getCell(2).setCellType(Cell.CELL_TYPE_NUMERIC);
rowDetalhe.getCell(3).setCellType(Cell.CELL_TYPE_NUMERIC);
rowDetalhe.getCell(4).setCellType(Cell.CELL_TYPE_NUMERIC);
rowDetalhe.getCell(5).setCellType(Cell.CELL_TYPE_NUMERIC);
rowDetalhe.getCell(6).setCellType(Cell.CELL_TYPE_NUMERIC);
rowDetalhe.getCell(2).setCellStyle(styleNumero);
rowDetalhe.getCell(4).setCellStyle(styleNumero);
rowDetalhe.getCell(3).setCellStyle(stylePercentual);
rowDetalhe.getCell(5).setCellStyle(stylePercentual);
rowDetalhe.getCell(6).setCellStyle(stylePercentual);
if (result.getBigDecimal("valorcredito") != null) {
rowDetalhe.getCell(2).setCellValue(result.getBigDecimal("valorcredito").doubleValue());
} else {
rowDetalhe.getCell(2).setCellValue(0.0);
}
if (result.getBigDecimal("percentualcredito") != null) {
rowDetalhe.getCell(3).setCellValue(result.getBigDecimal("percentualcredito").doubleValue());
} else {
rowDetalhe.getCell(3).setCellValue(0.0);
}
if (result.getBigDecimal("valordebito") != null) {
rowDetalhe.getCell(4).setCellValue(result.getBigDecimal("valordebito").doubleValue());
} else {
rowDetalhe.getCell(4).setCellValue(0.0);
}
if (result.getBigDecimal("percentualdebito") != null) {
rowDetalhe.getCell(5).setCellValue(result.getBigDecimal("percentualdebito").doubleValue());
} else {
rowDetalhe.getCell(5).setCellValue(0.0);
}
if (result.getBigDecimal("percentualdebitosobrereceita") != null) {
rowDetalhe.getCell(6).setCellValue(result.getBigDecimal("percentualdebitosobrereceita").doubleValue());
} else {
rowDetalhe.getCell(6).setCellValue(0.0);
}
}
result.close();
} catch (SQLException e) {
e.printStackTrace();
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
wb.write(baos);
ServletOutputStream ouputStream = response.getOutputStream();
response.setContentLength(baos.toByteArray().length);
response.setHeader("Expires", "0");
response.setHeader("Cache-Control","must-revalidate, post-check=0, pre-check=0");
response.setHeader("Pragma", "public");
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition","attachment; filename=financeiro.xlsx;");
ouputStream.write(baos.toByteArray());
ouputStream.flush();
ouputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public Date getDataInicialVencimento() {
return DataInicialVencimento;
}
public void setDataInicialVencimento(Date dataInicialVencimento) {
DataInicialVencimento = dataInicialVencimento;
}
public Date getDataFinalVencimento() {
return DataFinalVencimento;
}
public void setDataFinalVencimento(Date dataFinalVencimento) {
DataFinalVencimento = dataFinalVencimento;
}
public String getFlgTodasLojas() {
return FlgTodasLojas;
}
public void setFlgTodasLojas(String flgTodasLojas) {
FlgTodasLojas = flgTodasLojas;
}
public String getFlgPesoDespesa() {
return FlgPesoDespesa;
}
public void setFlgPesoDespesa(String flgPesoDespesa) {
FlgPesoDespesa = flgPesoDespesa;
}
public String getFlgContasOcultas() {
return FlgContasOcultas;
}
public void setFlgContasOcultas(String flgContasOcultas) {
FlgContasOcultas = flgContasOcultas;
}
public void setEmpresasessao(EmpresaVO empresasessao) {
this.empresasessao = empresasessao;
}
public EmpresaVO getEmpresasessao() {
return empresasessao;
}
public void setLojasessao(LojaVO lojasessao) {
this.lojasessao = lojasessao;
}
public LojaVO getLojasessao() {
return lojasessao;
}
public void setUsuariosessao(UsuarioVO usuariosessao) {
this.usuariosessao = usuariosessao;
}
public UsuarioVO getUsuariosessao() {
return usuariosessao;
}
public String getLojas() {
return Lojas;
}
public void setLojas(String lojas) {
Lojas = lojas;
}
}
| true
|
ac7066d7ff37753396f61b14ebf40e62ff41faaa
|
Java
|
jackba/AppStore
|
/src/AppStoreV3.java
|
UTF-8
| 4,977
| 3.4375
| 3
|
[] |
no_license
|
/* App Store Coursework
* AppStore main class
* Instantiates container classes, stores and restores data.
*/
/* @author joshstringfellow */
package appstorev3;
import java.util.Scanner;
public class AppStoreV3 {
/** @param args the command line arguments */
public static void main(String[] args) {
//Instantiation of Storage object
Storage storeAppStore = new Storage();
//Instantiation of App Container object
AppManager appManager = new AppManager();
//Call method to deserialize and restore data from apps.ser into appManager HashMap
appManager.setList(storeAppStore.deSerializeData(appManager.getList(), "apps.ser"));
//Instantiation of User Container object
UserManager userManager = new UserManager();
//Call method to deserialize and restore data from users.ser into userManager HashMap
userManager.setList(storeAppStore.deSerializeData(userManager.getList(), "users.ser"));
//Instantiate Scanner object and String to get user input
Scanner userInput = new Scanner(System.in);
String userChoice;
//Start user input loop and interaction with CLI
do {
System.out.println("_________________________________________\n"
+ "Welcome to the App Store, what do you want to do?\n"
+ "(1) Do you want to login,\n"
+ "(2) register as a new customer,\n"
+ "(3) manage users,\n"
+ "(4) manage apps,\n"
+ "(0) or exit the program.\n"
+ "Please enter the corresponding number.\n"
+ "_________________________________________");
userChoice = userInput.nextLine();
switch(userChoice){
case "1":
/*User can login with their username, then edit their info,
list and search for apps, choose apps and pay for them*/
userManager.loginUser(userInput, appManager);
break;
case "2":
//User registers and is then immediately logged in
userManager.loginUser(userInput, appManager, userManager.addUser(userInput));
break;
case "3":
//Access the user manager to add, list, edit and delete users
userManager.manageUsers(userInput);
break;
case "4":
//Access the app manager to add, list, edit and delete apps
appManager.manageApps(userInput);
break;
case "5":
createDemoObjects(userManager, appManager);
break;
case "0":
//End loop and finish program
userChoice = "0";
break;
default:
//If invalid input is given the user is notified
System.out.println("Invalid input.");
}
} while(!userChoice.equals("0"));
//Call function/object method to serialize data/hashmap from hashmaps into files
storeAppStore.serializeData(appManager.getList(), "apps.ser");
storeAppStore.serializeData(userManager.getList(), "users.ser");
}
//Quickly add apps and users to flesh out demo instead of doing so manually
public static void createDemoObjects(UserManager userManager, AppManager appManager){
Customer testUser1 = new Customer("BloggerJoe", "Joe Bloggs", "12, Desmond Rd", "Raynes Park", "Surrey", "SW16 8PB", "Developer", 2, 1, 12.00);
Student testUser2 = new Student("TesterMike", "Mike Smith", "Nice House", "Decent Town", "Okay County", "WR15 6FB", "Tester", 8, 6, 58.00);
Academic testUser3 = new Academic("LecturerJan", "Jan Appleseed", "Nicer House", "Great Town", "Green County", "NW 9GK", "Lecturer", 4, 2, 7.00);
userManager.addToList(testUser1.getUserName(), testUser1);
userManager.addToList(testUser2.getUserName(), testUser2);
userManager.addToList(testUser3.getUserName(), testUser3);
App testApp1 = new App("Network News", "John Bee", "App for checking the news", "News", 15.00, false, 54);
App testApp2 = new App("Rain's a pain", "Michelle Stormzy", "Don't get caught in the rain with this weather app!", "Weather App", 5, true, 36);
App testApp3 = new App("Crazy Games", "Jess Hung", "These games are crazy", "Game", 10, true, 4);
App testApp4 = new App("Procrastintor", "Jeff Netflix", "You're not getting any work done with this app", "Time Waster", 0, false, 17);
appManager.addToList(testApp1.getAppName(), testApp1);
appManager.addToList(testApp2.getAppName(), testApp2);
appManager.addToList(testApp3.getAppName(), testApp3);
appManager.addToList(testApp4.getAppName(), testApp4);
}
}
| true
|
3e404907101475c6bce383f727822d4578377c0e
|
Java
|
chanhui27/Object-Oriented-Programming
|
/Question4/BagApp.java
|
UTF-8
| 596
| 3.4375
| 3
|
[
"Apache-2.0"
] |
permissive
|
package Question4;
import java.util.List;
public class BagApp {
public static double calcTotalVolume(List<Bag> bagList, double accum) {
if(bagList != null && bagList.size() > 0) {//check if the bagList got something
accum += bagList.get(0).getVolume(); //get first element's volume from bagList to the accum
List<Bag> subBagList = bagList.subList(1, bagList.size());//create sub list to get bagList's first index to the last index data
return calcTotalVolume(subBagList, accum); //return sub list and accum
}
else
return accum;
}
}//end of class BagApp
| true
|
2b3688b5060f3aa2d47a37368411066c22f7d505
|
Java
|
localghost8080/JaxWS
|
/SpringJAXWS/SpringJAXWS-0.0.1-SNAPSHOT/src/main/java/com/samrat/wsserver/webservices/SimpleWSImpl.java
|
UTF-8
| 422
| 2.265625
| 2
|
[] |
no_license
|
package com.samrat.wsserver.webservices;
import java.util.Date;
import javax.jws.WebService;
@WebService(endpointInterface="com.samrat.wsserver.webservices.SimpleWSInterface", serviceName="SimpleWS" )
public class SimpleWSImpl implements SimpleWSInterface {
public String getTimeAsString() {
return new Date().toString();
}
public long getTimeAsElapsed() {
return new Date().getTime();
}
}
| true
|
84cce83bbb990f7cc9933a78057310fff902c0d9
|
Java
|
banyucenter/KursusAndroid
|
/app/src/main/java/aplikasiku/com/aplikasiluas/DetailActivity.java
|
UTF-8
| 3,502
| 2.296875
| 2
|
[] |
no_license
|
package aplikasiku.com.aplikasiluas;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class DetailActivity extends AppCompatActivity {
Button jumlah, kali, bagi, kurang;
TextView angkapertama, angkakedua,hasilnya;
double a,b;
String angka1,angka2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
Intent intent = getIntent();
angka1 = intent.getStringExtra("angkasatu");
angka2 = intent.getStringExtra("angkadua");
hasilnya = (TextView)findViewById(R.id.txtHasil);
angkapertama = (TextView)findViewById(R.id.txtAngka1);
angkakedua = (TextView)findViewById(R.id.txtAngka2);
angkapertama.setText(angka1);
angkakedua.setText(angka2);
a = Double.parseDouble(angka1);
b = Double.parseDouble(angka2);
jumlah = (Button)findViewById(R.id.btnJumlah);
kali = (Button)findViewById(R.id.btnKali);
bagi = (Button)findViewById(R.id.btnBagi);
kurang = (Button)findViewById(R.id.btnKurang);
jumlah.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//masukan fungsi
double hs = hasiljumlah(a,b);
//parsing hasil menjadi string
String output = String.valueOf(hs);
//set txtHasil dengan output (string hasil parsing)
hasilnya.setText(output.toString());
}
});
kali.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//masukan fungsi
double hs = hasilkali(a,b);
//parsing hasil menjadi string
String output = String.valueOf(hs);
//set txtHasil dengan output (string hasil parsing)
hasilnya.setText(output.toString());
}
});
bagi.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//masukan fungsi
double hs = hasilbagi(a,b);
//parsing hasil menjadi string
String output = String.valueOf(hs);
//set txtHasil dengan output (string hasil parsing)
hasilnya.setText(output.toString());
}
});
kurang.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//masukan fungsi
double hs = hasilkurang(a,b);
//parsing hasil menjadi string
String output = String.valueOf(hs);
//set txtHasil dengan output (string hasil parsing)
hasilnya.setText(output.toString());
}
});
}
//fungsi jumlah
public double hasiljumlah(double a,double b){
return a+b;
}
//fungsi jumlah
public double hasilkali(double a,double b){
return a*b;
}
//fungsi jumlah
public double hasilbagi(double a,double b){
return a/b;
}
//fungsi jumlah
public double hasilkurang(double a,double b){
return a-b;
}
}
| true
|
0fa3a3c35f9a08d0a73e43b2c20ce05d73d6579b
|
Java
|
IronGatesXP/leetcode
|
/Leetcode/src/test/ContainsDuplicate.java
|
UTF-8
| 497
| 3.09375
| 3
|
[] |
no_license
|
package test;
import java.util.Arrays;
public class ContainsDuplicate {
public boolean containsDuplicate(int[] nums) {
Arrays.sort(nums);
for(int i=0;i<nums.length-1;i++){
if(nums[i]==nums[i+1])
return true;
}
return false;
}
public static void main(String[] args)
{
ContainsDuplicate t = new ContainsDuplicate();
int[] nums = {-1,2,0,2};
System.out.println(t.containsDuplicate(nums));
}
}
| true
|
7e94035402a1825da2c347700ec6f98a062a545a
|
Java
|
catiiche/graduation-project
|
/src/main/java/com/example/project/services/ClientService.java
|
UTF-8
| 6,579
| 2.828125
| 3
|
[] |
no_license
|
package com.example.project.services;
import com.example.project.entity.Client;
import com.example.project.exception.ClientException;
import com.example.project.repository.ClientRepository;
import com.example.project.validation.ClientCollections;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.*;
import java.util.stream.Collectors;
import static java.util.Objects.isNull;
/**
* class ClientService
* <p>
* makes a request to ClientRepository, execute method and send response to ClientsController.
* Also contains 2 methods of knn algorithm that help to assess the solvency of a bank's client
*
* @author Kate Shkuratova
* @version 1.0
* @see ClientRepository
*/
@Service // spring создаст объект этого сервиса и положит себе в контейнер
public class ClientService implements IClientService {
private final ClientRepository repository;
private ClientCollections clientsList = new ClientCollections();
private static final int K = 6;
@Autowired // инъекция зависимостей - spring установит в зависимости все, что установленно в данном конструкторе
public ClientService(ClientRepository repository) {
this.repository = repository;
clientsList.createClients();
}
// методами, перечисленными ниже будет пользоваться контроллер
private void validateClient(Client client) throws ClientException {
if (isNull(client)) {
throw new ClientException("Object client is null");
}
if (isNull(client.getSurname()) || client.getSurname().isEmpty()) {
throw new ClientException("Surname is empty");
}
}
@Override
public Client saveClient(Client client) throws ClientException {
validateClient(client);
Client savedClient = repository.save(client);
return savedClient;
}
@Override
public void deleteClient(Long passportID) {
repository.deleteById(passportID);
}
@Override
public List<Client> findBySurname(String surname) {
List<Client> clients = repository.findBySurname(surname);
if (clients == null || clients.isEmpty()) throw new ClientException("Запись не существует");
List<Client> additional = new ArrayList<>();
for (int i = 0; i < clients.size(); i++) {
Map<Integer, Double> mapD;
mapD = euclidianDistance(clients.get(i), clientsList.getApprovedClients(), K);
clients.get(i).setStatus(voting(mapD, clientsList.getApprovedClients()));
additional.add(clients.get(i));
}
return clients;
}
public Optional<Client> findById(Long passportId) {
Optional<Client> client = repository.findById(passportId);
if (client == null) throw new ClientException("Запись не существует");
Client additional;
additional = client.orElse(new Client());
Map<Integer, Double> mapD = new HashMap<>();
mapD = euclidianDistance(additional, clientsList.getApprovedClients(), K);
additional.setStatus(voting(mapD, clientsList.getApprovedClients()));
client = Optional.ofNullable(additional);
return client;
}
@Override
public List<Client> findByCity(String city) {
List<Client> clients = repository.findByCity(city);
if (clients == null || clients.isEmpty()) throw new ClientException("Запись не существует");
List<Client> additional = new ArrayList<>();
for (int i = 0; i < clients.size(); i++) {
Map<Integer, Double> mapD = new HashMap<>();
mapD = euclidianDistance(clients.get(i), clientsList.getApprovedClients(), K);
clients.get(i).setStatus(voting(mapD, clientsList.getApprovedClients()));
additional.add(clients.get(i));
}
return clients;
}
@Override
public List<Client> findAll() {
return repository.findAll().stream().collect(Collectors.toList());
}
// расстояние Чебышева или Евклидово
public Map<Integer, Double> euclidianDistance(Client client, List<Client> approvedClients, int k) {
Map<Integer, Double> mapD = new HashMap<>();
Map<Integer, Double> mapDk = new HashMap<>();
Double d;
int creditNonApproved = client.getCreditHistory() ? 20000 : 0;
int cityNonApproved = client.getCity().equals("Moscow") ? 5000 : 0;
for (int i = 0; i < approvedClients.size(); i++) {
int creditApproved = approvedClients.get(i).getCreditHistory() ? 20000 : 0;
int cityApproved = approvedClients.get(i).getCity().equals("Moscow") ? 5000 : 0;
d = Math.pow(client.getSalary() - approvedClients.get(i).getSalary(), 2)
+ Math.pow(2500 * (client.getAge() - approvedClients.get(i).getAge()), 2)
+ Math.pow(25000 * (client.getCountOfChildren() - approvedClients.get(i).getCountOfChildren()), 2)
+ Math.pow(creditNonApproved - creditApproved, 2)
+ Math.pow(cityNonApproved - cityApproved, 2);
mapD.put(i, Math.sqrt(d));
}
Map<Integer, Double> mapDSorted = mapD.entrySet().stream()
.sorted(Map.Entry.<Integer, Double>comparingByValue())
.collect(LinkedHashMap::new,
(m, c) -> m.put(c.getKey(), c.getValue()),
LinkedHashMap::putAll);
for (Map.Entry<Integer, Double> entry : mapDSorted.entrySet()) {
if (k == 0) break;
mapDk.put(entry.getKey(), entry.getValue());
k--;
}
for (Map.Entry<Integer, Double> entry : mapDk.entrySet()) {
System.out.println(entry.getValue() + " " + entry.getKey());
}
return mapDk;
}
//
public boolean voting(Map<Integer, Double> mapDk, List<Client> approvedClients) {
int cnt1 = 0;
int cnt2 = 0;
for (int i = 0; i < approvedClients.size(); i++) {
if (mapDk.containsKey(i)) {
if (approvedClients.get(i).getStatus() == true)
cnt1++;
else cnt2++;
}
}
//System.out.println("cnt1 " + cnt1 + " cnt2 " + cnt2);
return cnt1 > cnt2 ? true : false;
}
}
| true
|
32f642f0a9cf77ea88daad26c5445fd645ff4eb5
|
Java
|
green-fox-academy/grinder
|
/week-04/Apple/src/test/java/CountLettersTest.java
|
UTF-8
| 539
| 2.640625
| 3
|
[] |
no_license
|
import org.junit.Test;
import org.junit.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import static org.junit.Assert.*;
public class CountLettersTest {
@Test
public void countLetters_inputString_returnHashmap() {
CountLetters countLetters = new CountLetters();
String text = "greenfoxacademy";
HashMap<Character, Integer> hashMap = new HashMap<Character, Integer>();
hashMap.put('e', 3);
assertEquals(hashMap, countLetters.countLetters(text));
}
}
| true
|
8595b1b2e6a89e1db400c1742814ce7a0dafff9c
|
Java
|
matrixxun/FMTech
|
/GooglePlay6.0.5/app/src/main/java/com/google/android/finsky/layout/WishlistPlayActionButton.java
|
UTF-8
| 2,373
| 1.632813
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.google.android.finsky.layout;
import android.accounts.Account;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.View.OnClickListener;
import com.google.android.finsky.FinskyApp;
import com.google.android.finsky.analytics.FinskyEventLog;
import com.google.android.finsky.api.DfeApi;
import com.google.android.finsky.api.model.Document;
import com.google.android.finsky.fragments.PageFragment;
import com.google.android.finsky.navigationmanager.NavigationManager;
import com.google.android.finsky.protos.DocV2;
import com.google.android.finsky.utils.WishlistHelper;
import com.google.android.finsky.utils.WishlistHelper.WishlistStatusListener;
import com.google.android.play.layout.PlayActionButton;
public class WishlistPlayActionButton
extends PlayActionButton
implements WishlistHelper.WishlistStatusListener
{
public Document mDoc;
public boolean mIsConfigured;
public View.OnClickListener mOnWishlistClickListener;
public WishlistPlayActionButton(Context paramContext)
{
super(paramContext);
}
public WishlistPlayActionButton(Context paramContext, AttributeSet paramAttributeSet)
{
super(paramContext, paramAttributeSet);
}
public void onAttachedToWindow()
{
super.onAttachedToWindow();
WishlistHelper.addWishlistStatusListener(this);
}
public void onDetachedFromWindow()
{
WishlistHelper.removeWishlistStatusListener(this);
super.onDetachedFromWindow();
}
public final void onWishlistStatusChanged(String paramString, boolean paramBoolean1, boolean paramBoolean2)
{
if ((this.mIsConfigured) && (paramString.equals(this.mDoc.mDocument.docid))) {
syncVisuals(paramBoolean1, this.mDoc.mDocument.backendId);
}
}
public final void syncVisuals(boolean paramBoolean, int paramInt)
{
if (paramBoolean)
{
configure(paramInt, getContext().getString(2131362286), this.mOnWishlistClickListener);
return;
}
configure(paramInt, getContext().getString(2131362285), this.mOnWishlistClickListener);
}
}
/* Location: F:\apktool\apktool\Google_Play_Store6.0.5\classes-dex2jar.jar
* Qualified Name: com.google.android.finsky.layout.WishlistPlayActionButton
* JD-Core Version: 0.7.0.1
*/
| true
|
7fe8dde82a511cd185b144e38fe906e0379b745f
|
Java
|
tjwang/my_backup
|
/TS/計算成交明細/CulMoney.java
|
UTF-8
| 8,447
| 2.34375
| 2
|
[] |
no_license
|
import stock.db.*;
import java.io.*;
import java.net.*;
import java.util.*;
import java.util.concurrent.*;
import java.sql.*;
public class CulMoney {
static int currentCount = 0;
static int range = 0;
static Hashtable ht ;
static public void main(String[] arg)throws Exception{
PamountNew_Rec pmar = new PamountNew_Rec();
PamountNew_Rec pmar2 = null;
ht = new Hashtable();
Enumeration e = pmar.SelectBySQL("select * from Pamounttemp where date = '"+arg[0]+"' order by snum,date,time " );
Vector data = new Vector();
float openPrice = -1;
float closePrice = -1;
while(e.hasMoreElements()){
pmar = (PamountNew_Rec)e.nextElement();
if(openPrice == -1)
{
openPrice = Float.parseFloat(pmar.rp);
}
if((pmar2 !=null) &&(!pmar.snum.equals(pmar2.snum))){
// System.err.println(pmar.snum);
closePrice = Float.parseFloat(pmar2.rp);
Ds000_Rec ds000r = new Ds000_Rec();
ds000r.snum = pmar2.snum;
if(ds000r.SelectInto())
{
float capital = Float.parseFloat(ds000r.capital);
/*
System.out.println(pmar2.snum+"|"+openPrice+"|"+closePrice+"|"+(Float.parseFloat(pmar2.total)/capital)+"|"
+CulAvg(data)+"|"
+CulHigherPriceAvg(data,openPrice,(closePrice>=openPrice))+"|"+CulLowerPriceAvg(data,openPrice,(closePrice<openPrice))+"|"
+CulHigherPriceAvg(data,closePrice,(closePrice>openPrice))+"|"+CulLowerPriceAvg(data,closePrice,(closePrice<=openPrice))+"|"
+CulHigherPriceAmount(data,openPrice,(closePrice>=openPrice))+"|"+CulLowerPriceAmount(data,openPrice,(closePrice<openPrice))+"|"
+CulHigherPriceAmount(data,closePrice,(closePrice>openPrice))+"|"+CulLowerPriceAmount(data,closePrice,(closePrice<=openPrice))+"|"
);
*/
ht.put(pmar2.snum, pmar2.snum+"|"+arg[0]+"|"+openPrice+"|"+closePrice+"|"+(Float.parseFloat(pmar2.total)/capital)+"|"
+CulAvg(data)+"|"
+CulHigherPriceAvg(data,openPrice,(closePrice>=openPrice))+"|"+CulLowerPriceAvg(data,openPrice,(closePrice<openPrice))+"|"
+CulHigherPriceAvg(data,closePrice,(closePrice>openPrice))+"|"+CulLowerPriceAvg(data,closePrice,(closePrice<=openPrice))+"|"
+CulHigherPriceAmount(data,openPrice,(closePrice>=openPrice))+"|"+CulLowerPriceAmount(data,openPrice,(closePrice<openPrice))+"|"
+CulHigherPriceAmount(data,closePrice,(closePrice>openPrice))+"|"+CulLowerPriceAmount(data,closePrice,(closePrice<=openPrice))+"|"
);
}
openPrice = Float.parseFloat(pmar.rp);
data = new Vector();
}
data.add(pmar);
pmar2 = pmar;
}
{
closePrice = Float.parseFloat(pmar2.rp);
Ds000_Rec ds000r = new Ds000_Rec();
ds000r.snum = pmar2.snum;
ds000r.SelectInto();
float capital = Float.parseFloat(ds000r.capital);
ht.put(pmar2.snum, pmar2.snum+"|"+arg[0]+"|"+openPrice+"|"+closePrice+"|"+(Float.parseFloat(pmar2.total)/capital)+"|"
+CulAvg(data)+"|"
+CulHigherPriceAvg(data,openPrice,(closePrice>=openPrice))+"|"+CulLowerPriceAvg(data,openPrice,(closePrice<openPrice))+"|"
+CulHigherPriceAvg(data,closePrice,(closePrice>openPrice))+"|"+CulLowerPriceAvg(data,closePrice,(closePrice<=openPrice))+"|"
+CulHigherPriceAmount(data,openPrice,(closePrice>=openPrice))+"|"+CulLowerPriceAmount(data,openPrice,(closePrice<openPrice))+"|"
+CulHigherPriceAmount(data,closePrice,(closePrice>openPrice))+"|"+CulLowerPriceAmount(data,closePrice,(closePrice<=openPrice))+"|"
);
}
CulMData(arg[0]);
}
static float CulAvg(Vector data)
{
Enumeration e = data.elements();
double moneyAmount = 0;
PamountNew_Rec pmar = null;
while(e.hasMoreElements())
{
pmar = (PamountNew_Rec)e.nextElement();
// System.out.println(pmar.dump());
moneyAmount += Float.parseFloat(pmar.rp) * Integer.parseInt(pmar.ra);
}
if(Integer.parseInt(pmar.total) == 0)
return 0;
return (float)(moneyAmount / Integer.parseInt(pmar.total));
}
static float CulHigherPriceAvg(Vector data,float price, boolean eqFlag)
{
Enumeration e = data.elements();
double moneyAmount = 0;
PamountNew_Rec pmar = null;
int total = 0;
while(e.hasMoreElements())
{
pmar = (PamountNew_Rec)e.nextElement();
if ((Float.parseFloat(pmar.rp) > price) || ((eqFlag) &&
((Float.parseFloat(pmar.rp)-price)<0.01) && ((Float.parseFloat(pmar.rp)-price)>-0.01)))
{
moneyAmount += Float.parseFloat(pmar.rp) * Integer.parseInt(pmar.ra);
total += Integer.parseInt(pmar.ra);
}
}
if(total == 0)
return 0;
return (float)(moneyAmount / total);
}
static float CulLowerPriceAvg(Vector data,float price,boolean eqFlag)
{
Enumeration e = data.elements();
double moneyAmount = 0;
PamountNew_Rec pmar = null;
int total = 0;
while(e.hasMoreElements())
{
pmar = (PamountNew_Rec)e.nextElement();
if ((Float.parseFloat(pmar.rp) < price) || ((eqFlag) &&
((Float.parseFloat(pmar.rp)-price)<0.01) && ((Float.parseFloat(pmar.rp)-price)>-0.01)))
{
moneyAmount += Float.parseFloat(pmar.rp) * Integer.parseInt(pmar.ra);
total += Integer.parseInt(pmar.ra);
}
}
if(total == 0)
return 0;
return (float)(moneyAmount / total);
}
static int CulHigherPriceAmount(Vector data,float price,boolean eqFlag)
{
Enumeration e = data.elements();
double moneyAmount = 0;
PamountNew_Rec pmar = null;
int total = 0;
while(e.hasMoreElements())
{
pmar = (PamountNew_Rec)e.nextElement();
if ((Float.parseFloat(pmar.rp) > price) || ((eqFlag) &&
((Float.parseFloat(pmar.rp)-price)<0.01) && ((Float.parseFloat(pmar.rp)-price)>-0.01)))
{
total += Integer.parseInt(pmar.ra);
}
}
return total;
}
static int CulLowerPriceAmount(Vector data,float price,boolean eqFlag)
{
Enumeration e = data.elements();
double moneyAmount = 0;
PamountNew_Rec pmar = null;
int total = 0;
while(e.hasMoreElements())
{
pmar = (PamountNew_Rec)e.nextElement();
if ((Float.parseFloat(pmar.rp) < price) || ((eqFlag) &&
((Float.parseFloat(pmar.rp)-price)<0.01) && ((Float.parseFloat(pmar.rp)-price)>-0.01)))
{
total += Integer.parseInt(pmar.ra);
}
}
return total;
}
static void CulMData(String datestr)throws Exception {
PMAmount_Rec pcar = new PMAmount_Rec();
/// Enumeration e = pcar.SelectBySQL("select snum,date,'0' as mnum, sum(inAmount) as inAmount, sum(outAmount) as outAmount, sum(sum) as sum "+
// "from pMAmount where date = '"+datestr+"' and sum > 0 group by snum,date order by snum ");
Enumeration e = ht.elements();
while(e.hasMoreElements()){
String s = (String)e.nextElement();
System.out.println(s+"0|");
// pcar = (PMAmount_Rec)e.nextElement();
// PLast_Rec pr = new PLast_Rec();
// pr.snum = pcar.snum ;
// pr.date = datestr ;
// if(pr.SelectBySQL("select * from PLast where snum='"+pcar.snum+"' and date='"+datestr+"'").hasMoreElements()){
// try{
// String s = (String)ht.get(pr.snum);
// System.out.println(s+(Float.parseFloat(pcar.sum) / Float.parseFloat(pr.total))+"|");
// }catch(Exception ee){
//
// }
// }else {
// System.err.println("snum:"+pr.snum+" pr.ran:"+pr.total+" pcar.sum:" + pcar.sum);
// }
//
}
}
}
| true
|
e39c20f3f3c4d6cc08ff90caf90de415aaddca96
|
Java
|
wotjd4305/Algorithm
|
/java-project/src/TextBook/Z22_LinkedList.java
|
UTF-8
| 849
| 3.421875
| 3
|
[] |
no_license
|
package TextBook;
import java.util.LinkedList;
public class Z22_LinkedList {
public static void main(String args[]) {
Node n1 = new Node();
n1.pre = null;
n1.data = 1;
n1.next = null;
Node head = n1;
Node n2 = new Node();
n2.pre = n1;
n2.data = 2;
n2.next = null;
n1.next = n2;
LinkedList<Integer> list = new LinkedList<>(); //제너릭스표현법
list.add(3);
list.add(4);
list.add(5);
list.add(6);
//list = list.toString()이나 같음(오버라이딩)
//Object를 출력시에는 해시코드 값이 나오지만 여기는 toString()
System.out.println(list); //객체의 주소를 노출x
list.add(2,100);
System.out.println(list);
list.remove(1);//first, last, all, index(지우고싶은데이터)
System.out.println(list);
}
}// class
class Node {
Node pre;
int data;
Node next;
}
| true
|