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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
1624f1b014829d6aa25024d47d077238f8283601 | Java | bobthemagicman/of-a-feather | /src/main/java/com/flockspring/domain/types/Affiliation.java | UTF-8 | 3,341 | 2.15625 | 2 | [] | no_license | /*
* Copyright 2013 flockspring Inc. All rights reserved
*/
package com.flockspring.domain.types;
import com.flockspring.ui.model.LocalizedEnum;
public enum Affiliation implements LocalizedEnum
{
APISTOLIC("affiliation.apistolic"),
ASSEMBLIES_OF_GOD("affiliation.assemblies.of.god"),
// AFRICAN_INITIATED("affiliation.african.initiated"),
ANGLICAN("affiliation.angelicanism"),
// ANABAPTISTS("affiliation.anabaptists"),
BAPTIST("affiliation.baptists"),
// BRETHREN("affiliation.brethren"),
// BIBLE_STUDENT_GROUPS("affiliation.bible.student.groups"),
CHRISTIAN_SCIENCE("affiliation.christian.science"),
CHRISTIAN_AND_MISSIONARY_ALLIANCE("affiliation.christian.and.missionary.alliance"),
// CONGREGATIONALIST("affiliation.congregationalist"),
CATHOLIC("affiliation.catholicism"),
// CALVIN("affiliation.calvinism"),
CHURCH_OF_GOD("affiliation.church.of.god"),
// CHARISMATICS("affiliation.charismatics"),
DISCIPLES_OF_CHRIST("affiliation.disciples.of.christ"),
// ESOTERIC("affiliation.esotericism"),
// EASTERN_ORTHODOX("affiliation.eastern.orthodox"),
EVANGELICAL_COVENANT("affiliation.evangelical.covenant"),
FOURSQUARE("affiliation.foursquare"),
JEHOVAS_WITNESS("affiliation.jehovas.witness"),
LUTHERAN("affiliation.lutheranism"),
LATTER_DAY_SAINTS("affiliation.latter.day.saints"),
METHODISTS("affiliation.methodists"),
// MILLERITES("affiliation.millerites"),
MESSIANIC_JUDAISM("affiliation.messianic.judiasm"),
NONDENOMINATIONAL("affiliation.nondenominational"),
MENNONITE("affiliation.mennonite"),
NAZARENE("affiliation.nazarene"),
// NEW_THOUGHT("affiliation.new.thought"),
NONE("affiliation.none"),
// ONENESS_PENTACOSTAL("affiliation.oneness.pentacostalism"),
// ORIENTAL_ORTHODOX("affiliation.oriental.orthodox"),
OPEN_BIBLE("affiliation.open.bible"),
ORTHODOX("affiliation.orthodox"),
PRESBYTERIAN("affiliation.presbyterianism"),
PROTESTANT("affiliation.protestantism"),
PENTECOSTAL("affiliation.pentecostalism"),
// PRIESTS_AND_HOLINESS("affiliation.priests.and.holiness"),
QUAKER("affiliation.quaker"),
REFORMED_CHURCHES("affiliation.reformed.churches"),
// STONE_CAMPBELL_RESTORATION("affiliation.stone.campbell.restoration"),
// SOUTHCOTTITES("affiliation.southcottites"),
SEVENTH_DAY_ADVENTIST("affiliation.seventh.day.adventist"),
// UNITED_AND_UNITING("affiliation.united.and.uniting"),
UNITARIAN("affiliation.unitarian"),
UNITED_CHURCH_OF_CHRIST("affiliation.united.church.of.christ"),
SOUTHERN_BAPTIST("affiliation.southern.baptist", BAPTIST),
AMERICAN_BAPTIST("affiliation.american.baptist", BAPTIST);
private String localizationCode;
private Affiliation[] affiliations;
Affiliation(String localizationCode, Affiliation... affiliations)
{
this.localizationCode = localizationCode;
this.affiliations = affiliations;
}
@Override
public String getLocalizedStringCode()
{
return localizationCode;
}
public Affiliation[] getChildAffiliations()
{
return affiliations;
}
@Override
public String getName()
{
return this.name();
}
@Override
public int getOrdinal()
{
return ordinal();
}
}
| true |
c447923040262ac128daa85fad99156bc9a054f6 | Java | as130232/comm-utils | /src/main/java/com/example/commutils/constant/LOAD_TYPE.java | UTF-8 | 971 | 2.484375 | 2 | [] | no_license | package com.example.commutils.constant;
import com.example.commutils.utils.StringUtil;
/**
* 方式
* @author charles.chen
* @date 2019年5月16日 下午2:06:16
*/
public enum LOAD_TYPE {
/*** 主軸(1) */
MAC_OS(1, "MAC_OS"),
/*** 內部ATC(2) */
WINDOWS(2, "WINDOWS");
public final Integer intValue;
public final String i18n;
private LOAD_TYPE(Integer intValue, String i18n){
this.i18n = i18n;
this.intValue = intValue;
}
public static String getI18n(String columnName, String status){
String result = MSG.UNKNOW.i18n;
LOAD_TYPE[] array = LOAD_TYPE.values();
for(LOAD_TYPE enumObj : array){
String enumName = enumObj.toString();
String camelName = StringUtil.toCamelCase(enumName);
camelName = StringUtil.toHeadLowerCase(camelName);
if(camelName.indexOf(columnName) != -1){
String enumValue = enumObj.intValue.toString();
if(enumValue.equals(status)){
return enumObj.i18n;
}
}
}
return result;
}
}
| true |
d1056cba69eff338921230c605b49962c5a11c81 | Java | adelapena/cassandra-lucene-index | /plugin/src/main/java/com/stratio/cassandra/lucene/schema/column/Columns.java | UTF-8 | 5,226 | 2.453125 | 2 | [
"Apache-2.0"
] | permissive | /*
* Licensed to STRATIO (C) under one or more contributor license agreements.
* See the NOTICE file distributed with this work for additional information
* regarding copyright ownership. The STRATIO (C) 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 com.stratio.cassandra.lucene.schema.column;
import com.google.common.base.Objects;
import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
/**
* A sorted list of CQL3 logic {@link Column}s.
*
* @author Andres de la Pena {@literal <adelapena@stratio.com>}
*/
public class Columns implements Iterable<Column<?>> {
/** The wrapped columns. */
private final List<Column<?>> columns;
/** Returns an empty {@link Column} list. */
public Columns() {
this.columns = new LinkedList<>();
}
/**
* Returns a new {@link Columns} composed by the specified {@link Column}s.
*
* @param columns A list of {@link Column}s.
*/
public Columns(Column<?>... columns) {
this.columns = Arrays.asList(columns);
}
/**
* Adds the specified {@link Column} to the existing ones.
*
* @param column the {@link Column} to be added.
* @return this
*/
public Columns add(Column<?> column) {
columns.add(column);
return this;
}
/**
* Adds the specified {@link Column}s to the existing ones.
*
* @param columns The {@link Column}s to be added.
* @return this {@link Columns} with the specified {@link Column}s.
*/
public Columns add(Columns columns) {
for (Column<?> column : columns) {
this.columns.add(column);
}
return this;
}
/**
* Returns an iterator over the {@link Column}s in insert order.
*
* @return An iterator over the {@link Column}s in insert order.
*/
public Iterator<Column<?>> iterator() {
return columns.iterator();
}
/**
* Returns the number of {@link Column}s in this list. If this list contains more than <tt>Integer.MAX_VALUE</tt>
* elements, returns <tt>Integer.MAX_VALUE</tt>.
*
* @return The number of {@link Column}s in this list
*/
public int size() {
return columns.size();
}
public boolean isEmpty() {
return columns.isEmpty();
}
/**
* Returns the {@link Column} identified by the specified full name, or {@code null} if not found.
*
* @param name The full name of the {@link Column} to be returned.
* @return The {@link Column} identified by the specified full name, or {@code null} if not found.
*/
public Columns getColumnsByFullName(String name) {
Column.check(name);
Columns result = new Columns();
for (Column<?> column : columns) {
if (column.getFullName().equals(name)) {
result.add(column);
}
}
return result;
}
/**
* Returns the {@link Column} identified by the specified CQL cell name, or {@code null} if not found.
*
* @param name The CQL cell name of the{@link Column} to be returned.
* @return The {@link Column} identified by the specified CQL cell name, or {@code null} if not found.
*/
public Columns getColumnsByCellName(String name) {
Column.check(name);
String cellName = Column.getCellName(name);
Columns result = new Columns();
for (Column<?> column : columns) {
if (column.getCellName().equals(cellName)) {
result.add(column);
}
}
return result;
}
/**
* Returns the {@link Column} identified by the specified mapper name, or {@code null} if not found.
*
* @param name The mapper name of the {@link Column} to be returned.
* @return The {@link Column} identified by the specified mapper name, or {@code null} if not found.
*/
public Columns getColumnsByMapperName(String name) {
Column.check(name);
String mapperName = Column.getMapperName(name);
Columns result = new Columns();
for (Column<?> column : columns) {
if (column.getMapperName().equals(mapperName)) {
result.add(column);
}
}
return result;
}
public Column<?> getFirst() {
return columns.isEmpty() ? null : columns.get(0);
}
/** {@inheritDoc} */
@Override
public String toString() {
Objects.ToStringHelper helper = Objects.toStringHelper(this);
for (Column<?> column : columns) {
helper.add(column.getFullName(), column.getComposedValue());
}
return helper.toString();
}
}
| true |
55637e0d862c015970ac77e947266998e070bafd | Java | SamirTalwar/Rekord | /core/src/test/java/com/noodlesandwich/rekord/functions/InvertibleFunctionTest.java | UTF-8 | 1,996 | 3.171875 | 3 | [] | no_license | package com.noodlesandwich.rekord.functions;
import org.junit.Test;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
public final class InvertibleFunctionTest {
@Test public void
has_an_identity_function() {
InvertibleFunction<Double, Double> identity = Functions.invertibleIdentity();
assertThat(identity.applyForward(7.5), is(7.5));
assertThat(identity.applyBackward(12.34), is(12.34));
}
@Test public void
can_be_constructed_from_a_pair_of_functions() {
InvertibleFunction<Integer, Integer> incrementor = Functions.invertibleFrom(increment, decrement);
assertThat(incrementor.applyForward(3), is(4));
assertThat(incrementor.applyBackward(9), is(8));
}
@Test public void
can_be_composed() {
InvertibleFunction<Integer, String> stringIncrementor =
Functions.compose(stringify, Functions.invertibleFrom(increment, decrement));
Functions.compose(stringify, Functions.invertibleFrom(increment, decrement));
assertThat(stringIncrementor.applyForward(12), is("13"));
assertThat(stringIncrementor.applyBackward("1"), is(0));
}
private static final Function<Integer, Integer> increment = new Function<Integer, Integer>() {
@Override
public Integer apply(Integer input) {
return input + 1;
}
};
private static final Function<Integer, Integer> decrement = new Function<Integer, Integer>() {
@Override
public Integer apply(Integer input) {
return input - 1;
}
};
private static final InvertibleFunction<Integer, String> stringify = new InvertibleFunction<Integer, String>() {
@Override
public String applyForward(Integer input) {
return input.toString();
}
@Override
public Integer applyBackward(String input) {
return Integer.parseInt(input);
}
};
}
| true |
1956c06fa14b1728b69b7625743303af7448fbe2 | Java | MaciejBienia/Maciej-Bienia-kodilla-java | /kodilla-good-patterns/src/main/java/com/kodilla/good/patterns/challenges/allegro/ProductInformationService.java | UTF-8 | 260 | 2.46875 | 2 | [] | no_license | package com.kodilla.good.patterns.challenges.allegro;
public class ProductInformationService implements InformationService {
public void inform(User user) {
System.out.println(user.getNickname() + ": Your order is now being processed..");
}
}
| true |
6cb8e19d7be73a14424d55b8faeaa376d84eda63 | Java | Zoly90/EMZOtours | /src/main/java/ro/emzo/turismapp/offer/endpoint/PersonalizedOfferController.java | UTF-8 | 3,360 | 2.0625 | 2 | [] | no_license | package ro.emzo.turismapp.offer.endpoint;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import ro.emzo.turismapp.core.model.PagedList;
import ro.emzo.turismapp.core.model.SearchCriteria;
import ro.emzo.turismapp.offer.to.ApplyOfferToUserTO;
import ro.emzo.turismapp.offer.model.PersonalizedOffer;
import ro.emzo.turismapp.offer.service.PersonalizedOfferService;
import ro.emzo.turismapp.offer.to.PersonalizedOfferTableDataTO;
import ro.emzo.turismapp.user.exceptions.InsufficientPermissionException;
import ro.emzo.turismapp.user.exceptions.UserDoesNotExistInTheDatabase;
@RestController
@RequestMapping("/api/turism-app/personalized-offer")
public class PersonalizedOfferController {
@Autowired
PersonalizedOfferService personalizedOfferService;
@PostMapping(value = "/search", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public ResponseEntity<PagedList<PersonalizedOfferTableDataTO>> getPersonalizedOffersBySearchCriteria(
@RequestBody SearchCriteria searchCriteria
) {
PagedList<PersonalizedOfferTableDataTO> offersTableData = personalizedOfferService.getPersonalizedOffersBySearchCriteria(searchCriteria);
return new ResponseEntity<>(offersTableData, HttpStatus.OK);
}
@GetMapping("/{personalizedOfferId}")
public ResponseEntity<PersonalizedOffer> getOnePersonalizedOffer(@PathVariable(name = "personalizedOfferId") Long personalizedOfferId) {
return new ResponseEntity<>(personalizedOfferService.getPersonalizedOfferById(personalizedOfferId), HttpStatus.OK);
}
@PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public ResponseEntity<PersonalizedOffer> savePersonalizedOffer(@RequestBody PersonalizedOffer personalizedOffer) {
return new ResponseEntity<>(personalizedOfferService.saveNewPersonalizedOffer(personalizedOffer), HttpStatus.OK);
}
@PostMapping(value = "/apply", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public ResponseEntity<PersonalizedOffer> applyToUser(@RequestBody ApplyOfferToUserTO applyOfferToUserTO) throws UserDoesNotExistInTheDatabase {
return new ResponseEntity<>(personalizedOfferService.applyToUser(applyOfferToUserTO), HttpStatus.OK);
}
@PostMapping(value = "/finalize", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public ResponseEntity<PersonalizedOffer> applyToUser(@RequestBody PersonalizedOffer personalizedOffer) throws InsufficientPermissionException {
return new ResponseEntity<>(personalizedOfferService.finalizeOffer(personalizedOffer), HttpStatus.OK);
}
@DeleteMapping("/{personalizedOfferId}")
public ResponseEntity<Void> deletePersonalizedOffer(@PathVariable("personalizedOfferId") Long personalizedOfferId) throws InsufficientPermissionException {
personalizedOfferService.deleteOffer(personalizedOfferId);
return new ResponseEntity<>(HttpStatus.OK);
}
}
| true |
e32e87a0acfef599e4ee045519dc2efcf5116638 | Java | SKuznet/java-ir | /src/main/java/com/education/l2/Main.java | UTF-8 | 340 | 2.5 | 2 | [] | no_license | package com.education.l2;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] array = new int[10];
Cat[] array2 = new Cat[10];
Object[] arrayName = array2;
System.out.println(Arrays.toString(array));
System.out.println(Arrays.toString(array2));
}
}
| true |
15856875dc9a466603618d2d9a579d1449fb19b5 | Java | DDTH/DASP | /servlet/src/ddth/dasp/common/redis/impl/AbstractRedisClient.java | UTF-8 | 1,449 | 2.4375 | 2 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | package ddth.dasp.common.redis.impl;
import ddth.dasp.common.redis.IRedisClient;
import ddth.dasp.common.redis.IRedisClientPool;
public abstract class AbstractRedisClient implements IRedisClient {
private String redisHost = "localhost", redisUsername, redisPassword;
private int redisPort = 6379;
private IRedisClientPool redisClientPool;
protected IRedisClientPool getRedisClientPool() {
return redisClientPool;
}
public AbstractRedisClient setRedisClientPool(IRedisClientPool redisClientPool) {
this.redisClientPool = redisClientPool;
return this;
}
protected String getRedisHost() {
return redisHost;
}
public AbstractRedisClient setRedisHost(String redisHost) {
this.redisHost = redisHost;
return this;
}
protected int getRedisPort() {
return redisPort;
}
public AbstractRedisClient setRedisPort(int redisPort) {
this.redisPort = redisPort;
return this;
}
protected String getRedisUsername() {
return redisUsername;
}
public AbstractRedisClient setRedisUsername(String redisUsername) {
this.redisUsername = redisUsername;
return this;
}
protected String getRedisPassword() {
return redisPassword;
}
public AbstractRedisClient setRedisPassword(String redisPassword) {
this.redisPassword = redisPassword;
return this;
}
}
| true |
a16cb316c0975fd74d0a055e3cd2c656703c3c77 | Java | jack1cheng/kafkaSpout4 | /src/main/java/com/kafka/kafkaSpout4/KafkaBrokerInfoFetcher.java | UTF-8 | 1,638 | 2.375 | 2 | [] | no_license | package com.kafka.kafkaSpout4;
import java.util.List;
import java.util.Map;
import org.apache.zookeeper.ZooKeeper;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
public class KafkaBrokerInfoFetcher {
public static void main(String[] args){
try{
ZooKeeper zk = new ZooKeeper("localhost:2181", 10000, null);
List<String> topics = zk.getChildren("/brokers/topics", false);
List<String> ids = zk.getChildren("/brokers/ids", false);
for (String topic : topics) {
System.out.println("topic " + topic);
}
for (String id : ids) {
if( zk.getData("/brokers/ids/" + id, false, null) != null){
String brokerInfo = new String(zk.getData("/brokers/ids/" + id, false, null));
System.out.println(id + ": " + brokerInfo);
}
}
/*
ZooKeeper zk = new ZooKeeper("localhost:2181", 10000, null);
List<String> topics = zk.getChildren("/brokers/topics", false);
List<String> ids = zk.getChildren("/brokers/ids", false);
JSONObject fieldsJson = null;
JSONParser parser = new JSONParser();
for (String id : ids) {
String brokerInfo = new String(zk.getData("/brokers/ids/" + id, false, null));
fieldsJson = (JSONObject) parser.parse(brokerInfo);
System.out.println(id + ": " + brokerInfo);
System.out.println(fieldsJson.get("host"));
}
for (String topic : topics) {
System.out.println("topic " + topic);
}
*/
}catch(Exception e){
System.out.println(e);
}
}
}
| true |
df23e40c53bcdbc20139e1a015218a62bca57e5d | Java | aymenfarhani123/mycode | /JunitDemo/src/com/string/StringHelper.java | UTF-8 | 620 | 3.203125 | 3 | [] | no_license | package com.string;
public class StringHelper {
public String truncateAInFirst2Positions(String str){
if(str.length()<=2)
str.replace("A", "");
String first2Chars=str.substring(0,2);
String stringMinusFirst2Chars=str.substring(2);
return first2Chars.replace("A", "")+stringMinusFirst2Chars;
}
public boolean areFirstAndLastTwoCharactersAreTheSame(String str){
if(str.length()<=1)
return false;
if(str.length()<=1)
return true;
String first2Chars=str.substring(0,2);
String last2Chars=str.substring(str.length()-2);
return first2Chars.equals(last2Chars);
}
}
| true |
a58225bec3078a83ac97ad691e5760b8aba9ab7b | Java | jiani3005/MVVM | /exercise/src/main/java/com/mykotlinapplication/exercise/MainActivity.java | UTF-8 | 2,860 | 2.21875 | 2 | [] | no_license | package com.mykotlinapplication.exercise;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.ButterKnife;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.mykotlinapplication.exercise.adapters.RecyclerViewAdapter;
import com.mykotlinapplication.exercise.models.Place;
import com.mykotlinapplication.exercise.viewmodels.MainActivityViewModel;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
@BindView(R.id.recyclerView)
RecyclerView recyclerView;
@BindView(R.id.floatingActionButton)
FloatingActionButton floatingActionButton;
@BindView(R.id.progressBar)
ProgressBar progressBar;
private RecyclerViewAdapter recyclerViewAdapter;
private MainActivityViewModel mainActivityViewModel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
mainActivityViewModel = ViewModelProviders.of(this).get(MainActivityViewModel.class);
mainActivityViewModel.init();
mainActivityViewModel.getPlaces().observe(this, new Observer<ArrayList<Place>>() {
@Override
public void onChanged(ArrayList<Place> places) {
recyclerViewAdapter.setData(places);
// recyclerViewAdapter.notifyDataSetChanged();
}
});
mainActivityViewModel.getIsUpdating().observe(this, new Observer<Boolean>() {
@Override
public void onChanged(Boolean aBoolean) {
if (aBoolean) {
progressBar.setVisibility(View.VISIBLE);
} else {
progressBar.setVisibility(View.GONE);
}
}
});
floatingActionButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mainActivityViewModel.addNewValue(new Place("Maui", "https://travel.usnews.com/dims4/USNEWS/b0d4c9e/2147483647/resize/445x280%5E%3E/crop/445x280/quality/85/?url=travel.usnews.com/static-travel/images/destinations/61/2016-main-getty-cropped_445x280.jpg"));
}
});
recyclerViewAdapter = new RecyclerViewAdapter(mainActivityViewModel.getPlaces().getValue());
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(recyclerViewAdapter);
}
}
| true |
2843037bf6ca0c5b37181657224192df928b4d6c | Java | idavehuwei/qtxln-call-center | /qtxln-esl-spring-boot-starter-demo/src/main/java/com/qtxln/model/vo/SysDictionaryVO.java | UTF-8 | 1,482 | 2.03125 | 2 | [] | no_license | package com.qtxln.model.vo;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
/**
* 字典数据BO
*
* @author 秦腾
* @version 1.0
* @date 2020/7/14 11:21 上午
* @since 1.0
*/
@Data
public class SysDictionaryVO {
@ApiModelProperty("主键")
@NotNull(message = "更新id不能为空", groups = {GroupUpdate.class})
private Long id;
@ApiModelProperty("字典名称")
@NotBlank(message = "字典名称不能为空", groups = {GroupInsert.class})
private String dicName;
@ApiModelProperty("字典代码")
@NotBlank(message = "字典代码不能为空", groups = {GroupInsert.class})
private String dicCode;
@ApiModelProperty("描述")
private String dicDescribe;
@ApiModelProperty("父id")
private Long parentId;
@ApiModelProperty("排序值")
@NotNull(message = "排序值不能为空", groups = {GroupInsert.class})
private Integer sortValue;
@ApiModelProperty("页码")
@NotNull(message = "页码不能为空", groups = {GroupQuery.class})
private Integer pageNum;
@ApiModelProperty("查询长度")
@NotNull(message = "查询长度不能为空", groups = {GroupQuery.class})
private Integer pageSize;
/**
* 查询分组
*/
public interface GroupQuery {
}
/**
* 添加分组
*/
public interface GroupInsert {
}
/**
* 更新分组
*/
public interface GroupUpdate {
}
}
| true |
ebe9d2b9574f976834d5de4ee1b41e6940b2b76a | Java | MarcoRevolledo/PB-Reto5 | /src/main/Reto5.java | UTF-8 | 437 | 2.046875 | 2 | [] | no_license |
package main;
import modelo.Persona;
import Controladores.Controlador;
import vistas.VentanaPrincipal;
public class Reto5 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Persona mod = new Persona();
VentanaPrincipal vista = new VentanaPrincipal();
Controlador ctrl = new Controlador(mod,vista);
ctrl.iniciar(); }
}
| true |
d5ee9af62e3c74b8917340d00eac4dc6157f894e | Java | ming4J/GeekJava000 | /week05/src/main/java/beans/SpringBeanXmlLoading.java | UTF-8 | 793 | 2.734375 | 3 | [
"Apache-2.0"
] | permissive | package beans;
import beans.domain.Student;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.Map;
/**
* Spring Bean装配方式一: 使用xml方式
*/
@Slf4j
public class SpringBeanXmlLoading {
public static void main(String[] args) {
final ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:beans.xml");
final Object student = context.getBean("student");
log.info("student {}", student);
final Student student1 = context.getBean("student1", Student.class);
log.info("student {}", student1);
final Map<String, Student> students = context.getBeansOfType(Student.class);
log.info("student {}", students);
}
}
| true |
f68def86856e32976aad6af5447d0069cb22a4ec | Java | abychko/StackCalc | /src/my/calc/cmd/Resource.java | UTF-8 | 234 | 1.773438 | 2 | [] | no_license | package my.calc.cmd;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/**
* Created by nerff on 13.09.13.
*/
@Retention(RetentionPolicy.RUNTIME)
public @interface Resource {
String type();
}
| true |
928778eba75df33f12a5bfd91a1a2ef90a79eb06 | Java | Chae224/heyu | /src/main/java/com/example/demo/service/HeyUSecurityService.java | UTF-8 | 180 | 1.71875 | 2 | [] | no_license | //package com.example.demo.service;
//
//public interface HeyUSecurityService {
// String findLoggedInUsername();
//
// void autoLogin(String username, String password);
//}
| true |
5a67e71881605e698e2c6e7969e0e6adf7fea5bc | Java | alogfans/rpc | /src/com/alogfans/rpc/control/RpcServer.java | UTF-8 | 8,033 | 2.390625 | 2 | [] | no_license | package com.alogfans.rpc.control;
import com.alogfans.rpc.marshal.MarshalHelper;
import com.alogfans.rpc.marshal.RequestPacket;
import com.alogfans.rpc.marshal.ResponsePacket;
import com.alogfans.rpc.stub.Provider;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.HashMap;
import java.util.Iterator;
import java.util.concurrent.ConcurrentHashMap;
/**
* The server that provides calling services. Several provided objected can be
* published for invoking remotely. The callings are async and use by NIO mechanism.
* (Non-blocking socket I/O)
*
* Created by Alogfans on 2015/8/5.
*/
public class RpcServer {
private final int BUFFER_SIZE = 4096;
private int port;
private int timeout;
// all provider we will listening to, for others will just ignore them.
private ConcurrentHashMap<Class<?>, Provider> rpcProviderHashMap;
// NIO implementation related elements
private ServerSocketChannel serverSocketChannel;
private Selector selector;
public RpcServer() {
timeout = Integer.MAX_VALUE;
rpcProviderHashMap = new ConcurrentHashMap<>();
}
public RpcServer setPort(int port) {
this.port = port;
return this;
}
public RpcServer setTimeout(int timeout) {
this.timeout = timeout;
return this;
}
/**
* Register the given rpc service, and the server will keep track of the request
* of such invocations.
* @param provider new instance of a structure of server-end object for invocation
* @return the caller RpcServer itself.
*/
public RpcServer register(Provider provider) throws IllegalArgumentException {
if (rpcProviderHashMap.containsKey(provider.getInterfaceClass()))
throw new IllegalArgumentException("Provider object registered.");
rpcProviderHashMap.put(provider.getInterfaceClass(), provider);
provider.setRpcServer(this);
return this;
}
/**
* Unregister the given rpc service, and the provider will be collected because it's
* useless unless registers again.
* @param provider instance of a structure of server-end object for invocation currently
* @return the caller RpcServer itself.
*/
public RpcServer unregister(Provider provider) throws IllegalArgumentException {
if (!rpcProviderHashMap.containsKey(provider.getInterfaceClass()))
throw new IllegalArgumentException("Provider object not registered.");
rpcProviderHashMap.remove(provider.getInterfaceClass());
provider.setRpcServer(null);
return this;
}
// ----- Now comes to the implementation dependent part -----
/**
* Prepare NIO objects and start processing looping in current thread. Never exit unless
* abortion because of exception.
*/
public void startService() {
try {
prepareNioObjects();
while (selector.select() > 0) {
frameProcess();
}
} catch (IOException e) {
e.printStackTrace();
}
}
private void prepareNioObjects() throws IOException {
serverSocketChannel = ServerSocketChannel.open();
selector = Selector.open();
serverSocketChannel.configureBlocking(false);
serverSocketChannel.socket().setReuseAddress(true);
serverSocketChannel.bind(new InetSocketAddress(port));
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
}
public void frameProcess() throws IOException {
Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
while (iterator.hasNext()) {
SelectionKey selectionKey = iterator.next();
iterator.remove();
if (selectionKey.isAcceptable()) {
SocketChannel socketChannel = serverSocketChannel.accept();
socketChannel.configureBlocking(false);
socketChannel.register(selector, SelectionKey.OP_READ);
}
if (selectionKey.isReadable()) {
SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
onReadRequests(socketChannel);
}
}
}
public void writeResponsePacket(SocketChannel socketChannel, ResponsePacket responsePacket) {
try {
ByteBuffer byteBuffer;
byteBuffer = ByteBuffer.allocate(BUFFER_SIZE);
byte[] marshalObject = MarshalHelper.objectToBytes(responsePacket);
byte[] marshalHeader = MarshalHelper.int32ToBytes(marshalObject.length);
byteBuffer.clear();
byteBuffer.put(marshalHeader);
byteBuffer.put(marshalObject);
byteBuffer.flip();
// If no connection now, please ignore it (usually in async calling)
try {
if (socketChannel.isConnected()) {
socketChannel.write(byteBuffer);
}
} catch (IOException e) {
socketChannel.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
private void onReadRequests(SocketChannel socketChannel) throws IOException {
ByteBuffer byteBuffer;
byteBuffer = ByteBuffer.allocate(BUFFER_SIZE);
byteBuffer.clear();
socketChannel.read(byteBuffer);
byteBuffer.flip();
int countBytes = byteBuffer.limit();
if (countBytes == 0) {
socketChannel.close();
}
int cursor = 0;
// System.out.println(countBytes);
while (cursor < countBytes) {
// TODO: Not considered with slitted packet!
byte[] marshallBytes = readBytes(socketChannel, byteBuffer, 4);
int packetLength = MarshalHelper.bytesToInt32(marshallBytes);
byte[] marshallObject = readBytes(socketChannel, byteBuffer, packetLength);
cursor += Integer.BYTES + packetLength;
RequestPacket requestPacket = null;
try {
requestPacket = (RequestPacket) MarshalHelper.byteToObject(marshallObject);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
dispatchRequestPacket(socketChannel, requestPacket);
}
}
private byte[] readBytes(SocketChannel socketChannel, ByteBuffer byteBuffer, int countBytes) throws IOException {
byte[] result = new byte[countBytes];
int firstBytes = byteBuffer.limit() - byteBuffer.position();
if (firstBytes < countBytes) {
// need more content, first read it fully
byteBuffer.get(result, 0, firstBytes);
// read again
ByteBuffer tinyByteBuffer;
tinyByteBuffer = ByteBuffer.allocate(countBytes - firstBytes);
tinyByteBuffer.clear();
socketChannel.read(tinyByteBuffer);
tinyByteBuffer.flip();
tinyByteBuffer.get(result, firstBytes, countBytes - firstBytes);
} else {
byteBuffer.get(result);
}
return result;
}
private void dispatchRequestPacket(SocketChannel socketChannel, RequestPacket requestPacket) {
if (requestPacket == null)
return;
Provider provider = rpcProviderHashMap.get(requestPacket.interfaceClass);
if (provider == null) {
writeResponsePacket(socketChannel,
new ResponsePacket()
.copyFromRequest(requestPacket)
.setException(new ClassNotFoundException("Such class not provided")));
return;
}
new Thread(new Runnable() {
@Override
public void run() {
ResponsePacket responsePacket = provider.invoke(requestPacket);
writeResponsePacket(socketChannel, responsePacket);
}
}).start();
}
}
| true |
483e8fb839d99f441d6295f944a16ecf79b511ce | Java | Jackjet/uw-mydb | /src/main/java/uw/mydb/stats/vo/SqlStatsPair.java | UTF-8 | 6,530 | 2.421875 | 2 | [] | no_license | package uw.mydb.stats.vo;
import com.fasterxml.jackson.annotation.JsonIgnore;
/**
* sql统计数据对。
* 里面包含两个sql统计对象,一个是全局对象,一个是临时对象。
*
* @author axeon
*/
public class SqlStatsPair {
public SqlStats sqlStats;
@JsonIgnore
public SqlStats sqlStatsMetrics;
public SqlStatsPair(boolean enableStats, boolean enableMetrics) {
if (enableStats) {
sqlStats = new SqlStats();
if (enableMetrics) {
sqlStatsMetrics = new SqlStats();
}
}
}
public void addSqlReadCount(long sqlCount) {
if (sqlStats != null) {
sqlStats.addSqlReadCount(sqlCount);
if (sqlStatsMetrics != null) {
sqlStatsMetrics.addSqlReadCount(sqlCount);
}
}
}
public void addSqlWriteCount(long sqlCount) {
if (sqlStats != null) {
sqlStats.addSqlWriteCount(sqlCount);
if (sqlStatsMetrics != null) {
sqlStatsMetrics.addSqlWriteCount(sqlCount);
}
}
}
public void addExeSuccessCount(long exeSuccessCount) {
if (sqlStats != null) {
sqlStats.addExeSuccessCount(exeSuccessCount);
if (sqlStatsMetrics != null) {
sqlStatsMetrics.addExeSuccessCount(exeSuccessCount);
}
}
}
public void addExeFailureCount(long exeFailureCount) {
if (sqlStats != null) {
sqlStats.addExeFailureCount(exeFailureCount);
if (sqlStatsMetrics != null) {
sqlStatsMetrics.addExeFailureCount(exeFailureCount);
}
}
}
public void addDataRowsCount(long dataRowsCount) {
if (sqlStats != null) {
sqlStats.addDataRowsCount(dataRowsCount);
if (sqlStatsMetrics != null) {
sqlStatsMetrics.addDataRowsCount(dataRowsCount);
}
}
}
public void addAffectRowsCount(long affectRowsCount) {
if (sqlStats != null) {
sqlStats.addAffectRowsCount(affectRowsCount);
if (sqlStatsMetrics != null) {
sqlStatsMetrics.addAffectRowsCount(affectRowsCount);
}
}
}
public void addExeTime(long exeTime) {
if (sqlStats != null) {
sqlStats.addExeTime(exeTime);
if (sqlStatsMetrics != null) {
sqlStatsMetrics.addExeTime(exeTime);
}
}
}
public void addSendBytes(long sendBytes) {
if (sqlStats != null) {
sqlStats.addSendBytes(sendBytes);
if (sqlStatsMetrics != null) {
sqlStatsMetrics.addSendBytes(sendBytes);
}
}
}
public void addRecvBytes(long recvBytes) {
if (sqlStats != null) {
sqlStats.addRecvBytes(recvBytes);
if (sqlStatsMetrics != null) {
sqlStats.addRecvBytes(recvBytes);
}
}
}
public long getSqlReadCount() {
if (sqlStats != null) {
return sqlStats.getSqlReadCount();
} else {
return -1;
}
}
@JsonIgnore
public long getAndClearSqlReadCount() {
if (sqlStatsMetrics != null) {
return sqlStatsMetrics.getAndClearSqlReadCount();
} else {
return -1;
}
}
public long getSqlWriteCount() {
if (sqlStats != null) {
return sqlStats.getSqlWriteCount();
} else {
return -1;
}
}
@JsonIgnore
public long getAndClearSqlWriteCount() {
if (sqlStatsMetrics != null) {
return sqlStatsMetrics.getAndClearSqlWriteCount();
} else {
return -1;
}
}
public long getDataRowsCount() {
if (sqlStats != null) {
return sqlStats.getDataRowsCount();
} else {
return -1;
}
}
@JsonIgnore
public long getAndClearDataRowsCount() {
if (sqlStatsMetrics != null) {
return sqlStatsMetrics.getAndClearDataRowsCount();
} else {
return -1;
}
}
public long getAffectRowsCount() {
if (sqlStats != null) {
return sqlStats.getAffectRowsCount();
} else {
return -1;
}
}
@JsonIgnore
public long getAndClearAffectRowsCount() {
if (sqlStatsMetrics != null) {
return sqlStatsMetrics.getAndClearAffectRowsCount();
} else {
return -1;
}
}
public long getExeSuccessCount() {
if (sqlStats != null) {
return sqlStats.getExeSuccessCount();
} else {
return -1;
}
}
@JsonIgnore
public long getAndClearExeSuccessCount() {
if (sqlStatsMetrics != null) {
return sqlStatsMetrics.getAndClearExeSuccessCount();
} else {
return -1;
}
}
@JsonIgnore
public long getAndClearExeFailureCount() {
if (sqlStatsMetrics != null) {
return sqlStatsMetrics.getAndClearExeFailureCount();
} else {
return -1;
}
}
public long getExeFailureCount() {
if (sqlStats != null) {
return sqlStats.getExeFailureCount();
} else {
return -1;
}
}
public long getExeTime() {
if (sqlStats != null) {
return sqlStats.getExeTime();
} else {
return -1;
}
}
@JsonIgnore
public long getAndClearExeTime() {
if (sqlStatsMetrics != null) {
return sqlStatsMetrics.getAndClearExeTime();
} else {
return -1;
}
}
public long getSendBytes() {
if (sqlStats != null) {
return sqlStats.getSendBytes();
} else {
return -1;
}
}
@JsonIgnore
public long getAndClearSendBytes() {
if (sqlStatsMetrics != null) {
return sqlStatsMetrics.getAndClearSendBytes();
} else {
return -1;
}
}
public long getRecvBytes() {
if (sqlStats != null) {
return sqlStats.getRecvBytes();
} else {
return -1;
}
}
@JsonIgnore
public long getAndClearRecvBytes() {
if (sqlStatsMetrics != null) {
return sqlStatsMetrics.getAndClearRecvBytes();
} else {
return -1;
}
}
}
| true |
a18e47a10d074098597d527b135ceda0b661b62e | Java | DiovaniMotta/caminhamento-grafo | /src/main/java/br/com/furb/grafos/dijkstra/Vertice.java | UTF-8 | 2,531 | 2.9375 | 3 | [] | no_license | package br.com.furb.grafos.dijkstra;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import br.com.furb.grafos.entidades.Ponto;
public class Vertice implements Comparable<Vertice> {
private String descricao;
private double distancia;
private boolean visitado = false;
private Ponto ponto;
private Vertice pai;
private List<Aresta> arestas = new ArrayList<Aresta>();
private List<Vertice> vizinhos = new ArrayList<Vertice>();
public void posicao(Ponto ponto){
this.ponto = ponto;
}
public Ponto getPonto(){
return ponto;
}
public void setDescricao(String nome) {
this.descricao = nome;
}
public String getDescricao() {
return descricao;
}
public void visitar() {
this.visitado = true;
}
public boolean verificarVisita() {
return visitado;
}
public void setDistancia(double distancia) {
this.distancia = distancia;
}
public double getDistancia() {
return this.distancia;
}
public double formatDistancia() {
return new BigDecimal(this.distancia).setScale(2, BigDecimal.ROUND_HALF_DOWN).doubleValue();
}
public void setPai(Vertice pai) {
this.pai = pai;
}
public Vertice getPai() {
return this.pai;
}
public void setVizinhos(List<Vertice> vizinhos) {
this.vizinhos.addAll(vizinhos);
}
public List<Vertice> getVizinhos() {
return this.vizinhos;
}
public void setArestas(List<Aresta> arestas) {
this.arestas.addAll(arestas);
}
public List<Aresta> getArestas() {
return arestas;
}
public int compareTo(Vertice vertice) {
if (this.getDistancia() < vertice.getDistancia())
return -1;
else if (this.getDistancia() == vertice.getDistancia())
return 0;
return 1;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((descricao == null) ? 0 : descricao.hashCode());
result = prime * result + ((ponto == null) ? 0 : ponto.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Vertice other = (Vertice) obj;
if (descricao == null) {
if (other.descricao != null)
return false;
} else if (!descricao.equals(other.descricao))
return false;
if (ponto == null) {
if (other.ponto != null)
return false;
} else if (!ponto.equals(other.ponto))
return false;
return true;
}
@Override
public String toString() {
String s = " ";
s += this.getDescricao();
return s;
}
}
| true |
eab55122f89346ba032d7ef24246135b3ae020ce | Java | mordanov/JavaElevatorLab | /classes/Passenger.java | UTF-8 | 2,077 | 3.09375 | 3 | [] | no_license | package classes;
public final class Passenger {
private final Floor source;
private final Floor destination;
private final long id;
private final long createTime;
private long inTime;
private long outTime;
private final String firstname;
private final String secondname;
public Passenger(Floor source, Floor destination, long id, long createTime, String firstname, String secondname) {
this.source = source;
this.destination = destination;
this.id = id;
this.createTime = createTime;
this.firstname = firstname;
this.secondname = secondname;
}
@Override
public boolean equals(Object o) {
if(!(o instanceof Passenger)) {
return false;
}
Passenger p = (Passenger)o;
return (p.id==this.id);
}
@Override
public String toString() {
return "{id: " + String.valueOf(this.id) + ", source=" + this.getSource().getNumber() + ", destination=" +
this.getDestination().getNumber() + "}";
}
@Override
public Passenger clone() {
Passenger p = new Passenger(this.source, this.destination, this.id, this.createTime, this.firstname, this.secondname);
p.setInTime(this.inTime);
p.setOutTime(this.outTime);
return p;
}
public void setInTime(long inTime) {
this.inTime = inTime;
}
public void setOutTime(long outTime) {
this.outTime = outTime;
}
public long getCreateTime() {
return createTime;
}
public long getInTime() {
return inTime;
}
public long getOutTime() {
return outTime;
}
public long getInOutTime() {
return outTime - inTime;
}
public String getFirstname() {
return firstname;
}
public String getSecondname() {
return secondname;
}
public Floor getSource() {
return source;
}
public Floor getDestination() {
return destination;
}
public long getId() {
return id;
}
}
| true |
0224e7cdaf566a9615e83489ed06e121b05e32bf | Java | moul/cattle | /code/iaas/simple-allocator/src/main/java/io/cattle/platform/simple/allocator/AllocationCandidateCallback.java | UTF-8 | 263 | 1.546875 | 2 | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | package io.cattle.platform.simple.allocator;
import io.cattle.platform.allocator.service.AllocationCandidate;
import java.util.List;
public interface AllocationCandidateCallback {
List<AllocationCandidate> withCandidate(AllocationCandidate candidate);
}
| true |
4767cc2d55ea1a51ccde6d09f7a7be5a41dbfa78 | Java | verygroup0001/trep | /Main.java | UTF-8 | 162 | 1.703125 | 2 | [
"MIT"
] | permissive | package org.trep;
public class Main {
public static void main(String... args) {
if (args.length == 0) {
System.out.println("Main.java");
}
}
}
| true |
6a799dce9b15a37dd4d9c9367f10ff00e0759081 | Java | tototo121212/project003 | /0517_Web_AOP/src/ex03/MyAspect.java | UTF-8 | 829 | 3.40625 | 3 | [] | no_license | package ex03;
public class MyAspect {
// advice
// Before advice : joinpoint 전에 수행되는 advice
// After returning advice : 성공적으로 리턴 된 후에 동작
// After throwing advice : 예외처리가 발생하면 동작
// After advice (finally) : 성공적이거나 예외적이어도 반드시 실행
// Around advice : 전, 후에 수행되는 advice
public void before(){
System.out.println("문을 열고 집에 들어간다.");
}
public void after(){
System.out.println("문 열고 집에 나온다.");
}
public void after_returning(){
System.out.println("잠을 잔다.");
}
public void after_throwing(){
System.out.println("119에 신고한다.");
}
public void around(){
System.out.println("뭐야 이건?");
}
}
| true |
57aed94e1072e2cdaa9d751ace652be5dae29f28 | Java | RaphaelVRossi/meli-proxy | /core/src/main/java/br/com/rrossi/proxy/ProxyResource.java | UTF-8 | 1,537 | 2.171875 | 2 | [] | no_license | package br.com.rrossi.proxy;
import br.com.rrossi.proxy.api.MercadoLibreApi;
import javax.inject.Inject;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
@Path("/{apiUri:.*}")
public class ProxyResource {
private final MercadoLibreApi mercadoLibreApiClient;
@Inject
public ProxyResource(MercadoLibreApi mercadoLibreApiClient) {
this.mercadoLibreApiClient = mercadoLibreApiClient;
}
@GET
@Produces
public Response get(@Context UriInfo info, @Context HttpHeaders headers) {
return mercadoLibreApiClient.callApiGet(info, headers);
}
@POST
@Consumes
@Produces
public Response post(String body, @Context UriInfo info, @Context HttpHeaders headers) {
return mercadoLibreApiClient.callApiPost(body, info, headers);
}
@PUT
@Consumes
@Produces
public Response put(String body, @Context UriInfo info, @Context HttpHeaders headers) {
return mercadoLibreApiClient.callApiPut(body, info, headers);
}
@PATCH
@Consumes
@Produces
public Response patch(String body, @Context UriInfo info, @Context HttpHeaders headers) {
return mercadoLibreApiClient.callApiPatch(body, info, headers);
}
@DELETE
@Consumes
@Produces
public Response delete(String body, @Context UriInfo info, @Context HttpHeaders headers) {
return mercadoLibreApiClient.callApiDelete(body, info, headers);
}
} | true |
cf731cac9013d374fe4135d3e18783f96d127912 | Java | Bilal912/Demo_Agora | /EDU_HUNT/app/src/main/java/com/edu_touch/edu_hunt/Teacher_detail.java | UTF-8 | 11,412 | 1.710938 | 2 | [] | no_license | package com.edu_touch.edu_hunt;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.LinearSmoothScroller;
import androidx.recyclerview.widget.RecyclerView;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.Html;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.Window;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.RetryPolicy;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.Volley;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.edu_touch.edu_hunt.Adapter.Book_Now_Adapter;
import com.edu_touch.edu_hunt.Adapter.Subject_Adapter;
import com.edu_touch.edu_hunt.Model.select_model;
import com.edu_touch.edu_hunt.Model.subject_model;
import com.edu_touch.edu_hunt.volley.CustomRequest;
import com.google.firebase.iid.FirebaseInstanceId;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Hashtable;
import java.util.Map;
import java.util.Random;
import de.hdodenhof.circleimageview.CircleImageView;
import es.dmoral.toasty.Toasty;
import static com.edu_touch.edu_hunt.MainActivity.MY_PREFS_NAME;
public class Teacher_detail extends AppCompatActivity implements clicky {
RecyclerView recyclerView;
SharedPreferences sharedPreferences;
Book_Now_Adapter adapter;
TextView Name,City,Address,Experience,Qualification;
String name,city,address,exp,quali,fees,board,subject,classes,code,id,image,subject_id,class_id,board_id;
ArrayList<select_model> arrayList;
CircleImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_teacher_detail);
arrayList = new ArrayList<>();
recyclerView = findViewById(R.id.recycler_id);
Name=findViewById(R.id.t_name);
City = findViewById(R.id.t_city);
Address = findViewById(R.id.t_address);
Experience = findViewById(R.id.t_exp);
Qualification = findViewById(R.id.t_quali);
imageView = findViewById(R.id.image_id);
image = getIntent().getStringExtra("image");
name = getIntent().getStringExtra("name");
city = getIntent().getStringExtra("city");
address = getIntent().getStringExtra("address");
exp = getIntent().getStringExtra("experience");
quali = getIntent().getStringExtra("qualification");
fees = getIntent().getStringExtra("fee");
board = getIntent().getStringExtra("board");
subject = getIntent().getStringExtra("subject");
id = getIntent().getStringExtra("id");
code = getIntent().getStringExtra("code");
classes = getIntent().getStringExtra("class");
subject_id = getIntent().getStringExtra("subject_id");
class_id = getIntent().getStringExtra("class_id");
board_id = getIntent().getStringExtra("board_id");
Glide.with(Teacher_detail.this)
.load(image)
.centerCrop()
.placeholder(R.drawable.user2)
.diskCacheStrategy(DiskCacheStrategy.ALL)
.dontAnimate()
.into(imageView);
imageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(Teacher_detail.this,Show_image.class);
i.putExtra("image",image);
startActivity(i);
}
});
Name.setText(name);
City.setText("City : "+city);
Address.setText("Address : "+ Html.fromHtml(address).toString());
Qualification.setText("Qualification : "+quali);
Experience.setText("Experience : "+exp);
LinearLayoutManager layoutManager = new LinearLayoutManager(Teacher_detail.this) {
@Override
public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state, int position) {
LinearSmoothScroller smoothScroller = new LinearSmoothScroller(Teacher_detail.this) {
private static final float SPEED = 2000f;// Change this value (default=25f)
@Override
protected float calculateSpeedPerPixel(DisplayMetrics displayMetrics) {
return SPEED / displayMetrics.densityDpi;
}
};
smoothScroller.setTargetPosition(position);
startSmoothScroll(smoothScroller);
}
};
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
getData();
}
private void getData() {
if (subject.contains("|")){
String[] subjecty = subject.split("\\|");
String[] boardy = board.split("\\|");
String[] feey = fees.split("\\|");
String[] classy = classes.split("\\|");
String[] subjecty_id = subject_id.split("\\|");
String[] boardy_id = board_id.split("\\|");
String[] classy_id = class_id.split("\\|");
for (int i=0;i<feey.length;i++){
select_model s = new select_model();
s.setId(id);
s.setBoards(boardy[i]);
s.setClass_name(classy[i]);
s.setFees(feey[i]);
s.setSubjects(subjecty[i]);
s.setBoards_id(boardy_id[i]);
s.setClass_id(classy_id[i]);
s.setSubjects_id(subjecty_id[i]);
arrayList.add(s);
}
}
else {
select_model s = new select_model();
s.setId(id);
s.setBoards(board);
s.setClass_name(classes);
s.setFees(fees);
s.setSubjects(subject);
s.setBoards_id(board_id);
s.setClass_id(class_id);
s.setSubjects_id(subject_id);
arrayList.add(s);
}
adapter = new Book_Now_Adapter(Teacher_detail.this, arrayList,Teacher_detail.this);
recyclerView.setAdapter(adapter);
}
@Override
public void onclicky(String s, String c, String b,String fee,String transc) {
sharedPreferences = getSharedPreferences(MY_PREFS_NAME,MODE_PRIVATE);
String code = "";
for (int z=0;z<4;z++) {
final int min = 0;
final int max = 9;
final int random = new Random().nextInt((max - min) + 1) + min;
code = code.concat(String.valueOf(random));
}
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
Date dateobj = new Date();
String newDateStr = df.format(dateobj);
//Toast.makeText(this, newDateStr+""+code+"- "+sharedPreferences.getString("id","null"), Toast.LENGTH_SHORT).show();
Context context = Teacher_detail.this;
final AlertDialog loading = new ProgressDialog(context);
loading.setMessage("Booking....");
loading.setCancelable(false);
loading.show();
Map<String, String> params = new Hashtable<String, String>();
params.put("std_id",sharedPreferences.getString("id","null"));
params.put("teacher_id",id);
params.put("subject_id",s);
params.put("class_group_id",c);
params.put("booking_date",newDateStr);
params.put("billdesk_id",transc);
params.put("teacher_otp",code);
params.put("amount",fee);
params.put("starting_date","000000");
params.put("user_subscription_status",sharedPreferences.getString("status","null"));
CustomRequest jsonRequest = new CustomRequest(Request.Method.POST, Constant.Base_url_booking_teacher, params, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
String message = response.getString("message");
String code = response.getString("error_code");
if (code.equals("200")){
//Toasty.success(context, message, Toast.LENGTH_SHORT, true).show();
loading.dismiss();
Teacher_detail.ViewDialog1 alert = new Teacher_detail.ViewDialog1();
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("status", "1");
editor.apply();
alert.showDialog(Teacher_detail.this);
}
else {
loading.dismiss();
Toasty.error(context, message, Toast.LENGTH_SHORT, true).show();
}
} catch (JSONException e) {
loading.dismiss();
e.printStackTrace();
//Toasty.error(context, "Error", Toast.LENGTH_SHORT, true).show();
}
}
}
, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
loading.dismiss();
Toasty.error(context, "Connection Timed Out", Toast.LENGTH_SHORT, true).show();
}
});
jsonRequest.setRetryPolicy(new RetryPolicy() {
@Override
public int getCurrentTimeout() {
return 50000;
}
@Override
public int getCurrentRetryCount() {
return 50000;
}
@Override
public void retry(VolleyError error) throws VolleyError {
}
});
RequestQueue queue = Volley.newRequestQueue(context);
queue.add(jsonRequest);
}
public class ViewDialog1 {
public void showDialog(Activity activity) {
final Dialog dialog = new Dialog(activity);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setCancelable(true);
dialog.setContentView(R.layout.dialogbox);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
dialog.show();
dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
@Override
public void onDismiss(final DialogInterface arg0) {
Intent intent = new Intent(Teacher_detail.this,Home.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
});
}
}
} | true |
c5710083d7b00ad848433eaac188c6314338ee99 | Java | moonjuhyeon/paper | /src/com/paper/dto/Paper_infoDTO.java | UTF-8 | 2,215 | 1.734375 | 2 | [] | no_license | package com.paper.dto;
public class Paper_infoDTO {
private String paper_no;
private String paper_kor;
private String paper_eng;
private String user_no;
private String file_name1;
private String file_name2;
private String file_path;
private String notice_no;
private String paper_ad;
private String reg_dt;
private String reg_user_no;
private String chg_dt;
private String cht_user_no;
public String getPaper_no() {
return paper_no;
}
public void setPaper_no(String paper_no) {
this.paper_no = paper_no;
}
public String getPaper_kor() {
return paper_kor;
}
public void setPaper_kor(String paper_kor) {
this.paper_kor = paper_kor;
}
public String getPaper_eng() {
return paper_eng;
}
public void setPaper_eng(String paper_eng) {
this.paper_eng = paper_eng;
}
public String getUser_no() {
return user_no;
}
public void setUser_no(String user_no) {
this.user_no = user_no;
}
public String getFile_name1() {
return file_name1;
}
public void setFile_name1(String file_name1) {
this.file_name1 = file_name1;
}
public String getFile_name2() {
return file_name2;
}
public void setFile_name2(String file_name2) {
this.file_name2 = file_name2;
}
public String getFile_path() {
return file_path;
}
public void setFile_path(String file_path) {
this.file_path = file_path;
}
public String getNotice_no() {
return notice_no;
}
public void setNotice_no(String notice_no) {
this.notice_no = notice_no;
}
public String getPaper_ad() {
return paper_ad;
}
public void setPaper_ad(String paper_ad) {
this.paper_ad = paper_ad;
}
public String getReg_dt() {
return reg_dt;
}
public void setReg_dt(String reg_dt) {
this.reg_dt = reg_dt;
}
public String getReg_user_no() {
return reg_user_no;
}
public void setReg_user_no(String reg_user_no) {
this.reg_user_no = reg_user_no;
}
public String getChg_dt() {
return chg_dt;
}
public void setChg_dt(String chg_dt) {
this.chg_dt = chg_dt;
}
public String getCht_user_no() {
return cht_user_no;
}
public void setCht_user_no(String cht_user_no) {
this.cht_user_no = cht_user_no;
}
}
| true |
b8d145a9073074dd89940ae09ea04933301ec71a | Java | SurfGitHub/BLIZZARD-Replication-Package-ESEC-FSE2018 | /Corpus/ecf/600.java | UTF-8 | 3,049 | 1.929688 | 2 | [
"MIT"
] | permissive | /*******************************************************************************
* Copyright (c) 2010 Angelo Zerr and others. All rights reserved. This
* program and the accompanying materials are made available under the terms of
* the Eclipse Public License v1.0 which accompanies this distribution, and is
* available at http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Angelo ZERR <angelo.zerr@gmail.com>. - initial API and implementation
******************************************************************************/
package org.eclipse.ecf.springframework;
import org.eclipse.ecf.core.ContainerCreateException;
import org.eclipse.ecf.core.ContainerFactory;
import org.eclipse.ecf.core.IContainer;
import org.eclipse.ecf.core.IContainerFactory;
import org.eclipse.ecf.core.IContainerManager;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
/**
* Abstract {@link org.springframework.beans.factory.FactoryBean} that creates
* ECF container {@link IContainer}.
*
*/
public abstract class AbstractContainerFactoryBean implements FactoryBean, InitializingBean, DisposableBean {
private IContainer container = null;
private String containerType = null;
private IContainerFactory containerFactory = null;
public void setContainerManager(IContainerManager containerManager) {
setContainerFactory(containerManager.getContainerFactory());
}
public void setContainerFactory(IContainerFactory containerFactory) {
this.containerFactory = containerFactory;
}
protected IContainerFactory getContainerFactory() {
return containerFactory;
}
public void setContainerType(String containerType) {
this.containerType = containerType;
}
protected String getContainerType() {
return containerType;
}
// public void setConnectContext(IConnectContext connectContext) {
// this.connectContext = connectContext;
// }
public Object getObject() throws Exception {
return this.container;
}
public Class getObjectType() {
return (this.container != null ? this.container.getClass() : IContainer.class);
}
public boolean isSingleton() {
return true;
}
public void afterPropertiesSet() throws Exception {
if (containerFactory == null) {
containerFactory = ContainerFactory.getDefault();
}
this.container = createContainer();
}
public void destroy() throws Exception {
if (this.container != null) {
this.container.disconnect();
this.container.dispose();
}
this.container = null;
this.containerType = null;
this.containerFactory = null;
}
protected IContainer createBasicContainer() throws ContainerCreateException {
return containerFactory.createContainer(this.containerType);
}
protected abstract IContainer createContainer() throws Exception;
}
| true |
f3b5e237c82331ddac60dcc7829cec54f1ad0708 | Java | AuBGa/aubga | /aubga-redis/src/main/java/com/aubga/redis/redisweb/JedisReplication.java | UTF-8 | 658 | 2.703125 | 3 | [] | no_license | package com.aubga.redis.redisweb;
import com.aubga.redis.IP_AND_PORT;
import redis.clients.jedis.Jedis;
// 主从复制类
public class JedisReplication
{
public static void main(String[] args)
{
// 主机
Jedis jedis_m = new Jedis(IP_AND_PORT.IP,IP_AND_PORT.PORT);
// 从机
Jedis jedis_s = new Jedis(IP_AND_PORT.SLAVE_IP,IP_AND_PORT.SLAVE_PORT);
// 创建二者关系
jedis_s.slaveof(IP_AND_PORT.IP,IP_AND_PORT.PORT);
// 主机写
jedis_m.set("class","6379");
// 从机读
String aClass = jedis_s.get("class");
System.out.println(aClass);
}
}
| true |
50ff48c2505fc400626ef2ff4af61dd3affe1153 | Java | nairakash96/CDAC | /Project/Backend/src/main/java/com/ehospital/dto/DoctorDTO.java | UTF-8 | 319 | 1.75 | 2 | [] | no_license | package com.ehospital.dto;
import java.time.LocalDateTime;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@NoArgsConstructor
@AllArgsConstructor
@Setter
@Getter
public class DoctorDTO {
private Integer id;
private String name;
}
| true |
2326e4c6ce5d1e84c9f64931bc171911d7344221 | Java | PrzemyslawDudek/FormHandleDemo | /src/main/java/pl/dudecode/FormHandleDemo/modelAttributeWithValues/Email.java | UTF-8 | 213 | 1.859375 | 2 | [] | no_license | package pl.dudecode.FormHandleDemo.modelAttributeWithValues;
import lombok.Data;
@Data
public class Email {
private long id;
private String label;
private String email;
private boolean active;
}
| true |
b907f0bbe8dd8c622cc34fbc85087635921dd664 | Java | sunape/jinrong | /app/src/main/java/com/honglu/future/ui/live/LiveFragment.java | UTF-8 | 4,820 | 1.976563 | 2 | [] | no_license | package com.honglu.future.ui.live;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import com.honglu.future.R;
import com.honglu.future.app.App;
import com.honglu.future.base.BaseActivity;
import com.honglu.future.base.BaseFragment;
import com.honglu.future.config.Constant;
import com.honglu.future.http.HttpManager;
import com.honglu.future.http.HttpSubscriber;
import com.honglu.future.http.RxHelper;
import com.honglu.future.ui.live.bean.LiveListBean;
import com.honglu.future.ui.usercenter.fragment.UserCenterFragment;
import com.honglu.future.util.AndroidUtil;
import com.honglu.future.util.SpUtil;
import com.honglu.future.widget.DrawableCenterTextView;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import java.util.List;
import butterknife.BindView;
import static com.honglu.future.R.id.tv_back;
/**
* deprecation:直播
* author:zq
* time:2018/1/6
*/
public class LiveFragment extends BaseFragment {
@BindView(R.id.srl_refreshView)
SmartRefreshLayout srl_refreshView;
@BindView(R.id.lv_listView)
ListView lv_listView;
@BindView(R.id.tv_back)
View mIvBack;
private LiveAdapter liveAdapter;
private View empty_view;
private boolean isLoading;
public static LiveFragment liveFragment;
public static LiveFragment getInstance() {
if (liveFragment == null) {
liveFragment = new LiveFragment();
}
return liveFragment;
}
@Override
public int getLayoutId() {
return R.layout.activity_live;
}
@Override
public void initPresenter() {
}
@Override
public void loadData() {
initViews();
}
private void initViews() {
mTitle.setTitle(false, R.color.white, "视频直播");
mIvBack.setVisibility(View.GONE);
srl_refreshView.setOnRefreshListener(new OnRefreshListener() {
@Override
public void onRefresh(RefreshLayout refreshlayout) {
refresh();
}
});
empty_view = LayoutInflater.from(mContext).inflate(R.layout.live_empty, null);
liveAdapter = new LiveAdapter(lv_listView);
lv_listView.setAdapter(liveAdapter);
lv_listView.setDividerHeight(AndroidUtil.dip2px(mContext,10));
}
@Override
public void onHiddenChanged(boolean hidden) {
super.onHiddenChanged(hidden);
if(!hidden){
refresh();
}
}
@Override
public void onResume() {
super.onResume();
refresh();
}
private void refresh(){
if (isLoading){
return;
}
App.loadingContent(mActivity, "正在加载");
isLoading = true;
HttpManager.getApi().getLiveData(SpUtil.getString(Constant.CACHE_TAG_UID)).compose(RxHelper.<List<LiveListBean>>handleSimplyResult()).subscribe(new HttpSubscriber<List<LiveListBean>>() {
@Override
protected void _onNext(List<LiveListBean> liveListBean) {
super._onNext(liveListBean);
isLoading = false;
if (srl_refreshView ==null){
return;
}
App.hideLoading();
srl_refreshView.finishRefresh();
liveAdapter.setDatas(liveListBean);
if (liveListBean != null && liveListBean.size() > 0) {
if (lv_listView.getFooterViewsCount() != 0){
lv_listView.removeFooterView(empty_view);
}
} else {
//空布局
if (lv_listView.getFooterViewsCount() == 0 && liveAdapter.getCount() == 0) {
lv_listView.addFooterView(empty_view, null, false);
}
}
}
@Override
protected void _onError(String message) {
super._onError(message);
isLoading = false;
if (srl_refreshView ==null){
return;
}
App.hideLoading();
srl_refreshView.finishRefresh();
if (liveAdapter.getCount() > 0) {
if (lv_listView.getFooterViewsCount() != 0){
lv_listView.removeFooterView(empty_view);
}
} else {
//空布局
if (lv_listView.getFooterViewsCount() == 0 && liveAdapter.getCount() == 0) {
lv_listView.addFooterView(empty_view, null, false);
}
}
}
});
}
}
| true |
c1409687332620885ae4c72b81d1ffcd98ff8088 | Java | App24/Racing-Game | /src/org/appproductions/guis/components/SoundComponent.java | UTF-8 | 665 | 2.5 | 2 | [] | no_license | package org.appproductions.guis.components;
import org.appproductions.audio.AudioManager;
import org.appproductions.audio.AudioMaster;
import org.appproductions.audio.Source;
import org.appproductions.guis.GUI;
public class SoundComponent extends GUIComponent {
int buffer;
Source source=new Source();
public SoundComponent(GUI gui, String audioFile) {
super(SOUND, gui);
buffer=AudioMaster.loadSound(audioFile);
AudioManager.addSource(source);
}
@Override
protected void onUpdate() {
}
public void playSound() {
source.play(buffer);
}
@Override
protected void onStatusUpdate() {
}
@Override
protected void onLoad() {
}
}
| true |
8da21a3319cbde8c342facb0a8a46a3235054ba0 | Java | ismat18/BasicJava | /Session1/src/corejava/ClassActivity2.java | UTF-8 | 300 | 2.640625 | 3 | [] | no_license | package corejava;
public class ClassActivity2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
String s="My name is Ismat Jahan";
String[] arr=s.split(" ");
for(int i=0; i<=(arr.length-1); i++) {
System.out.println(arr[i]);
}
}
}
| true |
b6bed0945656273a1e280e6f9819f2de1f828149 | Java | fatcookies/jamwish | /src/org/adamp/jam/menu/About.java | UTF-8 | 1,819 | 2.6875 | 3 | [] | no_license | package org.adamp.jam.menu;
import org.adamp.jam.Main;
import org.adamp.jam.Resources;
import org.newdawn.slick.*;
import org.newdawn.slick.state.BasicGameState;
import org.newdawn.slick.state.StateBasedGame;
import org.newdawn.slick.state.transition.FadeInTransition;
import org.newdawn.slick.state.transition.FadeOutTransition;
/**
* Created by adam on 11/04/14.
*/
public class About extends BasicGameState {
public static final int ID = 3;
private StateBasedGame game;
private Font font;
@Override
public int getID() {
return ID;
}
@Override
public void init(GameContainer gameContainer, StateBasedGame stateBasedGame) throws SlickException {
game = stateBasedGame;
font = Resources.loadMenuFont(50);
}
@Override
public void render(GameContainer gameContainer, StateBasedGame stateBasedGame, Graphics graphics) throws SlickException {
graphics.setBackground(Color.black);
graphics.setFont(font);
graphics.setColor(Color.white);
drawCentre(graphics, "Created by fc", (int) (Main.HEIGHT * 0.1));
drawCentre(graphics, "copyright 2014", (int) (Main.HEIGHT * 0.3));
drawCentre(graphics, "Press any key to return", (int) (Main.HEIGHT * 0.5));
drawCentre(graphics, "wololo", (int) (Main.HEIGHT * 0.85));
}
private void drawCentre(Graphics g, String text, int y) {
int width = font.getWidth(text);
g.drawString(text,(Main.WIDTH/2) - (width/2),y);
}
@Override
public void keyPressed(int key, char c) {
game.enterState(MainMenu.ID, new FadeOutTransition(Color.black),new FadeInTransition(Color.black));
}
@Override
public void update(GameContainer gameContainer, StateBasedGame stateBasedGame, int i) throws SlickException {
}
}
| true |
74f6ee13da7f65f3ddc6f3552d5ac3d4ff26bc0f | Java | jasp0894/ICOM4035_Lab6 | /src/positionListLLDirect/PositionListElementsBackwardIterator.java | UTF-8 | 1,094 | 2.890625 | 3 | [] | no_license | package positionListLLDirect;
import java.util.Iterator;
import java.util.NoSuchElementException;
import positionInterfaces.Position;
import positionInterfaces.PositionList;
public class PositionListElementsBackwardIterator<T> implements Iterator<T>{
protected Position<T> current;
protected PositionList<T> theList;
public PositionListElementsBackwardIterator() {
//for inheritance purposes
}
public PositionListElementsBackwardIterator(PositionList<T> list) {
// TODO Auto-generated constructor stub
theList = list;
if(theList.isEmpty())
current = null;
else
current = theList.last();
}
@Override
public boolean hasNext() {
// TODO Auto-generated method stub
return current!=null;
}
@Override
public T next() throws NoSuchElementException {
// TODO Auto-generated method stub
if(!hasNext()) throw new NoSuchElementException();
Position<T> ptr = current;
try{
current = theList.prev(current);
}catch(Exception e){
current = null;
}
return ptr.element();
}
}
| true |
cc893e4a527498c351b1e62ab777e916a98aa6ed | Java | cristian64/criludage | /Criludage/AplicacionDesguace/src/aplicaciondesguace/Propuesta.java | UTF-8 | 6,975 | 2.25 | 2 | [] | no_license | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package aplicaciondesguace;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.GregorianCalendar;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
import org.tempuri.ENEstadosPieza;
import org.tempuri.ENPropuesta;
/**
*
* @author DAMIAN-MACBOOK
*/
public class Propuesta extends ENPropuesta{
private GregorianCalendar miFechaEntrega;
private int idSolicitud;
private int idEmpleado;
private int idDesguace;
private String informacionAdicional;
private Connection conexion=null;
public Propuesta(){
setId(0);
setDescripcion("");
setPrecio(0.0f);
setEstado(ENEstadosPieza.USADA);
setMiFechaEntrega(new GregorianCalendar());
setIdDesguace(0);
setIdSolicitud(0);
informacionAdicional = "";
idEmpleado = 0;
miFechaEntrega.add(GregorianCalendar.DAY_OF_YEAR, 7);
}
public Propuesta(ResultSet rs){
try{
setId(rs.getInt("id"));
setDescripcion(rs.getString("descripcion"));
setPrecio(rs.getFloat("precioMax"));
if(rs.getString("estado").equals("USADA")){
setEstado(ENEstadosPieza.USADA);
}
if(rs.getString("estado").equals("NO_FUNCIONA")){
setEstado(ENEstadosPieza.NO_FUNCIONA);
}
if(rs.getString("estado").equals("NUEVA")){
setEstado(ENEstadosPieza.NUEVA);
}
setMiFechaEntrega(getGregorianCalendar(rs.getString("fechaEntrega")," "));
informacionAdicional = rs.getString("informacionAdicional");
}
catch(SQLException e){
System.err.println(e);
}
}
private GregorianCalendar getGregorianCalendar(String s,String sep){
//System.out.println(s);
String fecha = s.split(sep)[0];
String hora = s.split(sep)[1];
int ano = new Integer(fecha.split("\\.")[2]);
int mes = new Integer(fecha.split("\\.")[1]);
int dia = new Integer(fecha.split("\\.")[0]);
int hor = new Integer(hora.split(":")[0]);
int min = new Integer(hora.split(":")[1]);
int seg = new Integer(hora.split(":")[2]);
//System.out.println(dia + "." + mes + "." + ano + " " + hor + ":" + min + ":" + seg);
GregorianCalendar g = new GregorianCalendar(ano, mes, dia);
g.set(GregorianCalendar.DAY_OF_MONTH, dia);
g.set(GregorianCalendar.MONTH, mes-1);
g.set(GregorianCalendar.YEAR,ano);
g.set(GregorianCalendar.HOUR_OF_DAY, hor);
g.set(GregorianCalendar.MINUTE, min);
g.set(GregorianCalendar.SECOND, seg);
//System.out.println(ImprimirFecha(g));
return g;
}
public ENPropuesta getENPropuesta(){
ENPropuesta p = new ENPropuesta();
p.setId(getId());
p.setDescripcion(getDescripcion());
p.setPrecio(getPrecio());
p.setEstado(getEstado());
p.setFechaEntrega(GCToXMLGC(miFechaEntrega));
p.setIdDesguace(getIdDesguace());
p.setIdSolicitud(getIdSolicitud());
return p;
}
public XMLGregorianCalendar GCToXMLGC(GregorianCalendar g) {
XMLGregorianCalendar f=null;
try {
f = DatatypeFactory.newInstance().newXMLGregorianCalendar(getMiFechaEntrega());
} catch (DatatypeConfigurationException e) {
}
return f;
}
public GregorianCalendar getMiFechaEntrega() {
return miFechaEntrega;
}
public void setMiFechaEntrega(GregorianCalendar f) {
this.miFechaEntrega = f;
}
public int getIdEmpleado() {
return idEmpleado;
}
public void setIdEmpleado(int idEmpleado) {
this.idEmpleado = idEmpleado;
}
public String getInformacionAdicional() {
return informacionAdicional;
}
public void setInformacionAdicional(String informacionAdicional) {
this.informacionAdicional = informacionAdicional;
}
public String ImprimirFecha(GregorianCalendar f) {
DecimalFormat format = new DecimalFormat("00");
return format.format(f.get(GregorianCalendar.DAY_OF_MONTH)) + "." +
format.format(f.get(GregorianCalendar.MONTH)+1) + "." +
format.format(f.get(GregorianCalendar.YEAR)) + " " +
format.format(f.get(GregorianCalendar.HOUR_OF_DAY)) + ":" +
format.format(f.get(GregorianCalendar.MINUTE)) + ":" +
format.format(f.get(GregorianCalendar.SECOND));
}
public boolean guardar(String con){
crearConexion(con);
return ejecutarSQL("INSERT INTO propuestas (id, idSolicitud,idDesguace,descripcion,fechaEntrega,precioMax,estado,informacionAdicional) VALUES (" + getId() + "," + getIdSolicitud() + "," + getIdDesguace() + ",'" + getDescripcion() + "','" + ImprimirFecha(getMiFechaEntrega()) + "'," + getPrecio() + ",'" + getEstado().toString() + "','" + getInformacionAdicional() + "');");
}
public ArrayList<Propuesta> obtenerPropuestasPorSolicitud(String con,int sol){
crearConexion(con);
ArrayList<Propuesta> propuestas = new ArrayList<Propuesta>();
try{
ResultSet rs = consultaSQL("select * from propuestas where idSolicitud=" + sol);
while(rs.next()){
propuestas.add(new Propuesta(rs));
}
}
catch(SQLException e){
}
return propuestas;
}
public boolean crearConexion(String con) {
try {
Class.forName("org.sqlite.JDBC");
conexion = DriverManager.getConnection(con);
//Class.forName("com.mysql.jdbc.Driver");
//conexion = DriverManager.getConnection("jdbc:mysql://localhost:3306/desguace", "root", "");
} catch (SQLException ex) {
ex.printStackTrace();
return false;
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
return false;
}
return true;
}
public boolean ejecutarSQL(String sql) {
try {
Statement sentencia = conexion.createStatement();
sentencia.executeUpdate(sql);
} catch (SQLException ex) {
ex.printStackTrace();
return false;
}
return true;
}
public ResultSet consultaSQL(String sql){
try {
Statement s = conexion.createStatement();
return s.executeQuery (sql);
} catch (SQLException ex) {
ex.printStackTrace();
}
return null;
}
}
| true |
27b0a99d4ee0a1230877c79dd8bcbd63a8c4716d | Java | HYVincent/MyViewExample | /app/src/main/java/com/vincent/myviewexample/MyCircleView.java | UTF-8 | 4,238 | 2.5 | 2 | [] | no_license | package com.vincent.myviewexample;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
/**
* @author Vincent Vincent
* @version v1.0
* @name MyViewExample
* @page com.vincent.myviewexample
* @class describe
* @date 2018/11/21 15:40
*/
public class MyCircleView extends View {
public MyCircleView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
this.mContext = context;
init(mContext);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
mViewWidth = w;
mViewHeight = h;
mCircleX = w/2;
mCircleY = h/2;
if(mViewWidth > mViewHeight){
mCircleRadius = mViewHeight / 2;
}else {
mCircleRadius = mViewWidth / 2;
}
super.onSizeChanged(w, h, oldw, oldh);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
drawCircle(canvas);
}
private void drawCircle(Canvas canvas) {
canvas.drawCircle(mCircleX,mCircleY,mCurrentCircleRadius,mPaint);
}
public void startDrawable(){
animator = ObjectAnimator.ofFloat(mContext, "progress", 0, mCircleRadius);
animator.setDuration(800);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
mCurrentCircleRadius = (float) animation.getAnimatedValue();
Log.d(TAG, "onAnimationUpdate: "+mCurrentCircleRadius);
invalidate();
}
});
animator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
animation.start();
}
});
animator.start();
}
private void init(Context mContext) {
mCircleRadius = DpUtil.dp2px(mContext,mCircleRadius);
mCircleColor = ContextCompat.getColor(mContext,R.color.color_green_a8edc5);
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setColor(mCircleColor);
mPaint.setStrokeWidth(DpUtil.dp2px(mContext,2));
mPaint.setStyle(Paint.Style.STROKE);
}
private Context mContext;
private Paint mPaint;
private float mViewWidth;
private float mViewHeight;
private float mCircleRadius = 10;//半径
private float mCurrentCircleRadius;//正在绘制的圆的半径
private int mCircleColor;
private float mCircleX;
private float mCircleY;
private ObjectAnimator animator;
private static final String TAG = "绘制圆";
/**
* view的大小控制
*/
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(measureWidth(widthMeasureSpec),
measureHeight(heightMeasureSpec));
}
private int measureHeight(int measureSpec) {
int result = 0;
int mode = MeasureSpec.getMode(measureSpec);
int size = MeasureSpec.getSize(measureSpec);
if (mode == MeasureSpec.EXACTLY) {
result = size;
} else {
result = (int) mViewHeight;
if (mode == MeasureSpec.AT_MOST) {
result = Math.min(result, size);
}
}
return result;
}
private int measureWidth(int measureSpec) {
int result = 0;
int mode = MeasureSpec.getMode(measureSpec);
int size = MeasureSpec.getSize(measureSpec);
if (mode == MeasureSpec.EXACTLY) {
result = size;
} else {
result = (int) mViewWidth;//根据自己的需要更改
if (mode == MeasureSpec.AT_MOST) {
result = Math.min(result, size);
}
}
return result;
}
}
| true |
f96183e7a023aae6714b7c208149fa7b1d7ebc06 | Java | TuonglLe/ELMusicPlayer | /app/src/main/java/example/com/elmusicplayer/UI/SongDetailFragment.java | UTF-8 | 379 | 1.859375 | 2 | [
"Apache-2.0"
] | permissive | package example.com.elmusicplayer.UI;
import android.support.v4.app.Fragment;
import example.com.elmusicplayer.R;
import example.com.elmusicplayer.UI.Fragment.AdvancedMediaControllerFragment;
public class SongDetailFragment extends AdvancedMediaControllerFragment {
@Override
protected int rootViewLayout() {
return R.layout.fragment_song_detail;
}
}
| true |
bbdc40aa61a5a450727275a777b9117cd4b96b26 | Java | LiaoCheng123456/fundbug | /CommonUtils.java | UTF-8 | 11,988 | 2.359375 | 2 | [] | no_license | package com.rh.cwcd;
import com.alibaba.fastjson.JSON;
import com.rh.cwcd.dto.notice.EduNotice;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.xml.sax.InputSource;
import javax.servlet.http.HttpServletRequest;
import java.io.PrintWriter;
import java.io.StringReader;
import java.io.StringWriter;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* @author liaocheng
* @date: 2020-02-17 11:39
*/
public class CommonUtils {
/**
* 时间格式化 年-月-日 时:分:秒
*/
private static final String YMDHMS = "yyyy-MM-dd HH:mm:ss";
/**
* 一亿
*/
private static final long MAX = 100000000;
private static int id = 10000;
/**
* 年月日
*/
private static final String YMD = "yyMMdd";
/**
* 当前时间戳
*/
private static final Long NOWTIME = System.currentTimeMillis();
/**
* 获取格式化过后的当前时间
*
* @return 2020-02-17 11:44:31
*/
public static String getNowFormatTime() {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(YMDHMS);
return simpleDateFormat.format(System.currentTimeMillis());
}
/**
* 获取当前时间戳
*
* @return 1581911390
*/
public static Long getTimeStamp() {
return NOWTIME / 1000;
}
/**
* 获取id
*
* @return
*/
// public static Long getId() {
// String ipAddress = "";
//
// try {
// //获取服务器IP地址
// ipAddress = InetAddress.getLocalHost().getHostAddress();
// } catch (Exception e) {
// e.printStackTrace();
// }
//
// String uuid = ipAddress + "$" + UUID.randomUUID().toString().replaceAll("-", "").toUpperCase();
//
// long suffix = Math.abs(uuid.hashCode() % MAX);
//
// SimpleDateFormat sdf = new SimpleDateFormat(YMD);
//
// String time = sdf.format(new Date(System.currentTimeMillis()));
//
// long prefix = Long.parseLong(time) * MAX;
//
// return Long.parseLong(String.valueOf(prefix + suffix));
// }
/**
* md5 工具
*
* @param str
* @return
*/
public static String md5(String str) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(str.getBytes());
byte[] b = md.digest();
StringBuilder buf = new StringBuilder("");
for (int b1 : b) {
int i = b1;
if (i < 0) {
i += 256;
}
if (i < 16) {
buf.append("0");
}
buf.append(Integer.toHexString(i));
}
str = buf.toString();
} catch (Exception var6) {
var6.printStackTrace();
}
return str;
}
public static int generatorSixSmsCode() {
for (; ; ) {
int i1 = new Random().nextInt(999999);
if (i1 > 100000) {
return i1;
}
}
}
/**
* 获取格式化时间,由于微信支付设置过期时间
*
* @return
*/
public static String getStringDate(int minute) {
Date now = new Date();
Date afterDate = new Date(now.getTime() + minute * 60 * 1000);
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
return formatter.format(afterDate);
}
/**
* 获取用户真实IP地址,不使用request.getRemoteAddr();的原因是有可能用户使用了代理软件方式避免真实IP地址。
* 可是,如果通过了多级反向代理的话,X-Forwarded-For的值并不止一个,而是一串IP值,究竟哪个才是真正的用户端的真实IP呢?
* 答案是取X-Forwarded-For中第一个非unknown的有效IP字符串
*
* @param request
* @return
*/
public static String getIpAddress(HttpServletRequest request) {
String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_CLIENT_IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
if ("127.0.0.1".equals(ip) || "0:0:0:0:0:0:0:1".equals(ip)) {
//根据网卡取本机配置的IP
InetAddress inet = null;
try {
inet = InetAddress.getLocalHost();
} catch (UnknownHostException e) {
e.printStackTrace();
}
ip = inet.getHostAddress();
}
}
return ip;
}
/**
* 二次签名H5
*
* @param prepay_id
* @param appid
* @param nonce_str
* @return
*/
public static String createSecondSignH5(String prepay_id, String appid, String nonce_str, String timestape) {
String secondSign = "";
SortedMap<Object, Object> parameters = new TreeMap<Object, Object>();
parameters.put("appId", appid);
parameters.put("nonceStr", nonce_str);
parameters.put("package", "prepay_id=" + prepay_id);
parameters.put("signType", "MD5");
parameters.put("timeStamp", timestape);
secondSign = createSign("UTF-8", parameters, "H5");
return secondSign;
}
/**
* 二次签名APP
*
* @param prepay_id
* @param appid
* @param nonce_str
* @return
*/
public static String createSecondSignAPP(String prepay_id, String appid, String mchid, String nonce_str,
String timestape, String packageName) {
String secondSign = "";
SortedMap<Object, Object> parameters = new TreeMap<Object, Object>();
parameters.put("appid", appid);
parameters.put("noncestr", nonce_str);
parameters.put("package", packageName);
parameters.put("partnerid", mchid);
parameters.put("prepayid", prepay_id);
parameters.put("timestamp", timestape);
secondSign = createSign("UTF-8", parameters, "APP");
return secondSign;
}
/**
* 微信支付签名算法sign
*
* @param characterEncoding
* @param parameters
* @return
*/
@SuppressWarnings("rawtypes")
public static String createSign(String characterEncoding, SortedMap<Object, Object> parameters, String type) {
StringBuffer sb = new StringBuffer();
Set es = parameters.entrySet();// 所有参与传参的参数按照accsii排序(升序)
Iterator it = es.iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
String k = (String) entry.getKey();
Object v = entry.getValue();
if (null != v && !"".equals(v) && !"sign".equals(k) && !"key".equals(k)) {
sb.append(k + "=" + v + "&");
}
}
if (type.equals("APP")) {
sb.append("key=" + Const.APP);
} else if (type.equals("H5")) {
sb.append("key=" + Const.WECHAT);
}
System.out.println("字符串拼接后是:" + sb.toString());
String sign = MD5Encode(sb.toString(), characterEncoding).toUpperCase();
return sign;
}
public static String MD5Encode(String origin, String charsetname) {
String resultString = null;
try {
resultString = new String(origin);
MessageDigest md = MessageDigest.getInstance("MD5");
if (charsetname == null || "".equals(charsetname))
resultString = byteArrayToHexString(md.digest(resultString
.getBytes()));
else
resultString = byteArrayToHexString(md.digest(resultString
.getBytes(charsetname)));
} catch (Exception exception) {
}
return resultString;
}
private static String byteArrayToHexString(byte b[]) {
StringBuffer resultSb = new StringBuffer();
for (int i = 0; i < b.length; i++)
resultSb.append(byteToHexString(b[i]));
return resultSb.toString();
}
private static String byteToHexString(byte b) {
int n = b;
if (n < 0)
n += 256;
int d1 = n / 16;
int d2 = n % 16;
return hexDigits[d1] + hexDigits[d2];
}
private static final String hexDigits[] = {"0", "1", "2", "3", "4", "5",
"6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};
public static String getRandomString(int length) { //length表示生成字符串的长度
String base = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
Random random = new Random();
StringBuffer sb = new StringBuffer();
int number = 0;
for (int i = 0; i < length; i++) {
number = random.nextInt(base.length());
sb.append(base.charAt(number));
}
return sb.toString();
}
public static String toStackTrace(Throwable e) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
try {
e.printStackTrace(pw);
return sw.toString();
} catch (Exception e1) {
return "";
}
}
/**
* 解析微信回调后参数解析 解析的时候自动去掉CDMA
*
* @param xml
*/
public static HashMap getWXPayResultV2(String xml) {
HashMap weChatModel = new HashMap();
try {
StringReader read = new StringReader(xml);
// 创建新的输入源SAX 解析器将使用 InputSource 对象来确定如何读取 XML 输入
InputSource source = new InputSource(read);
// 创建一个新的SAXBuilder
SAXBuilder sb = new SAXBuilder();
// 通过输入源构造一个Document
Document doc;
doc = (Document) sb.build(source);
Element root = doc.getRootElement();// 指向根节点
List<Element> list = root.getChildren();
if (list != null && list.size() > 0) {
for (Element element : list) {
weChatModel.put(element.getName(), element.getText());
}
}
} catch (Exception e) {
e.printStackTrace();
}
return weChatModel;
}
public static Object parsePageSize(Object object, Class tClass) {
HashMap map = JSON.parseObject(JSON.toJSONString(object), HashMap.class);
if (map.get("page") != null && map.get("size") != null) {
map.put("page", Integer.parseInt(map.get("page").toString()) <= 0 ? 0 : (Integer.parseInt(map.get("page").toString()) - 1) * Integer.parseInt(map.get("size").toString()));
return JSON.parseObject(JSON.toJSONString(map), tClass);
}
return object;
}
public synchronized static int getAutoIncId() {
return id++;
}
public static void main(String[] args) {
EduNotice eduNotice = new EduNotice();
eduNotice.setPage(3);
eduNotice.setSize(10);
eduNotice = (EduNotice) parsePageSize(eduNotice, EduNotice.class);
System.out.println(JSON.toJSONString(eduNotice));
}
}
| true |
7e1d5f09fd49a4c536f5cc0da2d5af580eb68f49 | Java | ErinLouiseClark/Inheritance2 | /src/Mind.java | UTF-8 | 322 | 2.765625 | 3 | [] | no_license |
public class Mind extends Powers {
protected boolean telekensis;
public void readMinds(){
System.out.println(name + " read " + archnemesis + "'s mind and was able to defend themselves and attack better!");
}
public void beLeaders(){
System.out.println(name + " took the lead and helped others train!");
}
}
| true |
7d77f13500c33675577b44e8525be9d3813de8b9 | Java | yutuer/javaFx | /src/main/java/fasterLogger/process/IService.java | UTF-8 | 241 | 2.234375 | 2 | [] | no_license | package fasterLogger.process;
/**
* @Description 服务器 调度单位
* @Author zhangfan
* @Date 2020/9/7 17:16
* @Version 1.0
*/
public interface IService
{
/**
* 单位时间的调用
*/
void tick(int ticker);
}
| true |
d2e8e5e04d994eae093139f897bea25495a5d1ba | Java | srosenberg/datakernel | /eventloop/src/main/java/io/datakernel/async/AsyncCallables.java | UTF-8 | 4,146 | 2.859375 | 3 | [
"Apache-2.0"
] | permissive | package io.datakernel.async;
import io.datakernel.eventloop.Eventloop;
import java.util.List;
import java.util.concurrent.TimeoutException;
import static java.util.Arrays.asList;
public class AsyncCallables {
public static final TimeoutException TIMEOUT_EXCEPTION = new TimeoutException();
private AsyncCallables() {
}
private static final class DoneState {
boolean done;
}
public static <T> AsyncCallable<T> timeout(final Eventloop eventloop, final long timestamp, final AsyncCallable<T> callable) {
return new AsyncCallable<T>() {
@Override
public void call(final ResultCallback<T> callback) {
final DoneState state = new DoneState();
callable.call(new ResultCallback<T>() {
@Override
protected void onResult(T result) {
if (!state.done) {
state.done = true;
callback.setResult(result);
}
}
@Override
protected void onException(Exception e) {
if (!state.done) {
state.done = true;
callback.setException(e);
}
}
});
if (!state.done) {
eventloop.schedule(timestamp, new Runnable() {
@Override
public void run() {
if (!state.done) {
state.done = true;
callback.setException(TIMEOUT_EXCEPTION);
}
}
});
}
}
};
}
public static <T> AsyncCallable<T[]> callAll(final Eventloop eventloop, final AsyncCallable<?>... callables) {
return callAll(eventloop, asList(callables));
}
private static final class CallState {
int pending;
public CallState(int pending) {
this.pending = pending;
}
}
@SuppressWarnings("unchecked")
public static <T> AsyncCallable<T[]> callAll(final Eventloop eventloop, final List<AsyncCallable<?>> callables) {
return new AsyncCallable<T[]>() {
@Override
public void call(final ResultCallback<T[]> callback) {
final CallState state = new CallState(callables.size());
final T[] results = (T[]) new Object[callables.size()];
if (state.pending == 0) {
callback.setResult(results);
return;
}
for (int i = 0; i < callables.size(); i++) {
AsyncCallable<T> callable = (AsyncCallable<T>) callables.get(i);
final int finalI = i;
callable.call(new ResultCallback<T>() {
@Override
protected void onResult(T result) {
results[finalI] = result;
if (--state.pending == 0) {
callback.setResult(results);
}
}
@Override
protected void onException(Exception e) {
if (state.pending > 0) {
state.pending = 0;
callback.setException(e);
}
}
});
}
}
};
}
public static <T> AsyncCallable<T[]> callWithTimeout(final Eventloop eventloop, final long timestamp, final AsyncCallable<? extends T>... callables) {
return callWithTimeout(eventloop, timestamp, asList(callables));
}
public static <T> AsyncCallable<T[]> callWithTimeout(final Eventloop eventloop, final long timestamp, final List<AsyncCallable<? extends T>> callables) {
return new AsyncCallable<T[]>() {
@Override
public void call(final ResultCallback<T[]> callback) {
final CallState state = new CallState(callables.size());
final T[] results = (T[]) new Object[callables.size()];
if (state.pending == 0) {
callback.setResult(results);
return;
}
for (int i = 0; i < callables.size(); i++) {
final AsyncCallable<T> callable = (AsyncCallable<T>) callables.get(i);
final int finalI = i;
callable.call(new ResultCallback<T>() {
@Override
protected void onResult(T result) {
results[finalI] = result;
if (--state.pending == 0) {
callback.setResult(results);
}
}
@Override
protected void onException(Exception e) {
if (state.pending > 0) {
state.pending = 0;
callback.setException(e);
}
}
});
}
if (state.pending != 0) {
eventloop.schedule(timestamp, new Runnable() {
@Override
public void run() {
if (state.pending > 0) {
state.pending = 0;
callback.setResult(results);
}
}
});
}
}
};
}
}
| true |
d810d7ac7edfc5934e157f49b5f61e4dda37087d | Java | Mmati1996/paw-back | /back/src/main/java/com/example/back/services/LabelServiceImpl.java | UTF-8 | 620 | 2.546875 | 3 | [] | no_license | package com.example.back.services;
import com.example.back.models.Label;
import com.example.back.repositories.LabelRepository;
public class LabelServiceImpl implements LabelService {
private LabelRepository labelRepository;
public LabelServiceImpl() {
}
public LabelServiceImpl(LabelRepository labelRepository) {
this.labelRepository = labelRepository;
}
@Override
public Label getLabelById(int id) {
return labelRepository.findById(id).get();
}
@Override
public String getName(int id) {
return labelRepository.findById(id).get().getName();
}
}
| true |
553e8b94b1e42e16ba04b35440e03feafe104f15 | Java | gengyuntuo/CollegeStudentsEvaluation | /src/main/java/cn/xuemengzihe/sylu/ces/util/JSONUtil.java | UTF-8 | 3,732 | 2.65625 | 3 | [] | no_license | package cn.xuemengzihe.sylu.ces.util;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;
import com.github.pagehelper.PageInfo;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
/**
* <h1>JSON 工具类</h1>
* <p>
* </p>
*
* @author 李春
* @time 2017年3月20日 下午3:44:38
*/
public class JSONUtil {
/**
* 将List<Map<String, String>>类型的集合转化成JSON数据
*
* @param list
* 集合
* @return JSON
*/
public static String parseListToJSON(List<Map<String, String>> list) {
StringBuilder builder = new StringBuilder();
builder.append("[");
Gson gson = new Gson();
Type type = new TypeToken<Map<String, String>>() {
}.getType();
if (list == null || list.size() == 0) {
return builder.append("]").toString();
}
for (Map<String, String> var : list) {
builder.append(gson.toJson(var, type));
builder.append(",");
}
builder.deleteCharAt(builder.length() - 1); // 删除最后一行的“,”号
return builder.append("]").toString();
}
/**
* 将PageInfo对象转化成带分页信息的JSON数据
*
* @param pageInfo
* PageInfo 对象
* @return JSON
*/
public static String parsePageInfoToJSON(
PageInfo<Map<String, String>> pageInfo) {
StringBuilder builder = new StringBuilder();
builder.append("{\"total\":");
builder.append(pageInfo.getTotal());
builder.append(",\"rows\": [");
if (pageInfo.getList() == null || pageInfo.getList().size() <= 0) {
return builder.append("]}").toString();
}
Gson gson = new Gson();
Type type = new TypeToken<Map<String, String>>() {
}.getType();
for (Map<String, String> var : pageInfo.getList()) {
builder.append(gson.toJson(var, type));
builder.append(",");
}
builder.deleteCharAt(builder.length() - 1); // 删除最后一行的“,”号
return builder.append("]}").toString();
}
/**
* 将PageInfo对象转化成带分页信息的JSON数据,带有当前页的页码
*
* @param pageInfo
* PageInfo 对象
* @return JSON
*/
public static String parsePageInfoToJSONWithPageNumber(
PageInfo<Map<String, String>> pageInfo) {
StringBuilder builder = new StringBuilder();
builder.append("{\"total\":");
builder.append(pageInfo.getTotal());
builder.append(",\"page\": ");
builder.append(pageInfo.getPageNum());
builder.append(",\"rows\": [");
if (pageInfo.getList() == null || pageInfo.getList().size() <= 0) {
return builder.append("]}").toString();
}
Gson gson = new Gson();
Type type = new TypeToken<Map<String, String>>() {
}.getType();
for (Map<String, String> var : pageInfo.getList()) {
builder.append(gson.toJson(var, type));
builder.append(",");
}
builder.deleteCharAt(builder.length() - 1); // 删除最后一行的“,”号
return builder.append("]}").toString();
}
public static String parsePageInfoToJSONUseForMessageDetect(
PageInfo<Map<String, String>> pageInfo) {
StringBuilder builder = new StringBuilder();
builder.append("{\"total\":");
builder.append(pageInfo.getTotal());
builder.append(",\"msg\": [");
if (pageInfo.getList() == null || pageInfo.getList().size() <= 0) {
return builder.append("]}").toString();
}
Gson gson = new Gson();
Type type = new TypeToken<Map<String, String>>() {
}.getType();
for (Map<String, String> var : pageInfo.getList()) {
builder.append(gson.toJson(var, type));
builder.append(",");
}
builder.deleteCharAt(builder.length() - 1); // 删除最后一行的“,”号
return builder.append("]}").toString();
}
}
| true |
d2d673ad039597d2041433b8c23bcba41bbd0997 | Java | cesarlatorre2021/Construccion | /src/main/java/com/construccion/repository/ParametrosRepository.java | UTF-8 | 220 | 1.804688 | 2 | [] | no_license | package com.construccion.repository;
import com.construccion.entity.ParametrosConstruccion;
public interface ParametrosRepository {
ParametrosConstruccion consultarParametrosPorConstruccion(Integer idConstruccion);
}
| true |
421153960d083e6f9de3debc7158db18371a82e6 | Java | saidlachhab/TDD_example_Point | /src/point/PointTest.java | UTF-8 | 1,029 | 3.125 | 3 | [] | no_license | package point;
import org.junit.Assert;
import org.junit.Test;
public class PointTest {
@Test
public void distanceBetweenTwoPointsMustbePositive(){
Point p = new Point(1, 4);
Point p2 = new Point(5,6);
Assert.assertTrue(p.getDistance(p2) >= 0);
}
@Test
public void distanceBetweenPointAndItselfShouldBe0(){
Point p = new Point(1, 4);
Double result = p.getDistance(p);
Assert.assertEquals(Double.valueOf(0), result);
}
@Test
public void distanceBetweenTwoPointsWhoHaveTheSameXandYshouldBe0(){
Point p1 = new Point(1, 9);
Point p2 = new Point(1, 9);
Double result = p1.getDistance(p2);
Assert.assertEquals(Double.valueOf(0), result);
}
@Test
public void distanceBetweenTwoDifferentsPoints(){
Point p1 = new Point(1, 9);
Point p2 = new Point(4, 7);
Double result = p1.getDistance(p2);
Assert.assertEquals(Double.valueOf(3.605551275463989), result);
}
}
| true |
12ac53203c227906a4f1bcbb9772914a85c339b0 | Java | DevsDi/springboot-rabbitmq | /springboot-rabbitmq-fanout/src/main/java/com/rabbit/fanout/FanoutSender.java | UTF-8 | 580 | 1.921875 | 2 | [] | no_license | package com.rabbit.fanout;
import java.util.Date;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class FanoutSender {
@Autowired
private RabbitTemplate rabbitTemplate;
public void send() {
String msgString="fanoutSender========";
System.out.println(msgString);
this.rabbitTemplate.convertAndSend("fanout.exchange","abcd.ee", msgString);
}
} | true |
2c3b1c074448711ddfe391971fb4e128eb32f768 | Java | 123qweqwe123/scm | /scm-data-sync/src/main/java/com/jet/datasync/samples/repository/CustomerRepository.java | UTF-8 | 284 | 1.773438 | 2 | [] | no_license | package com.jet.datasync.samples.repository;
import com.jet.datasync.samples.proto.CustomerProtos;
/**
* Description:
* <pre>
* </pre>
* Author: huangrupeng
* Create: 17/7/10 下午7:55
*/
public interface CustomerRepository {
CustomerProtos.Customer findById(int id);
}
| true |
c048a12cb1b0fd82069643c3cfe6c14e3d22306d | Java | jibijose/httpbin | /src/main/java/com/jibi/controller/MemoryController.java | UTF-8 | 2,114 | 2.484375 | 2 | [
"Apache-2.0"
] | permissive | package com.jibi.controller;
import com.jibi.common.StringUtil;
import com.jibi.common.Util;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.ArraySchema;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
/** The type Memory controller. */
@Tag(name = "Memory Api", description = "Memory Api")
@RestController(value = "Memory Api")
@RequestMapping("/memory")
@Slf4j
public class MemoryController {
/**
* Memory hold.
*
* @param bytes the bytes
* @param time the time
*/
@Operation(
summary = "Memory api",
description = "Memory hold operation",
tags = {"memory"})
@ApiResponses(
value = {
@ApiResponse(
responseCode = "200",
description = "Successful operation",
content =
@Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))),
@ApiResponse(responseCode = "500", description = "Internal server error")
})
@Parameter(name = "bytes", schema = @Schema(description = "Bytes", type = "integer"))
@Parameter(name = "time", schema = @Schema(description = "Time in seconds", type = "integer"))
@RequestMapping(value = "/{bytes}/{time}", method = RequestMethod.GET)
public void memoryHold(@PathVariable("bytes") Integer bytes, @PathVariable("time") Integer time) {
String storeString = StringUtil.getRandomString(bytes / 2);
Util.sleepMillisSilent(time * 1000);
log.trace("Kept string of length {} in memory for {} seconds", storeString.length(), time);
}
}
| true |
3022aac8378aa1191ddb700c4aee6a7a33ea8495 | Java | Black-Jack-web/By.belhardj19 | /src/By/belhardj19/homework/homework_lesson6/ex2/Main.java | UTF-8 | 701 | 2.765625 | 3 | [] | no_license | package By.belhardj19.homework.homework_lesson6.ex2;
@SuppressWarnings("Duplicates")
public class Main {
public static void main(String[] args) {
List personListHandler = new List();
personListHandler.addPerson(new Person("Vasily"));
personListHandler.addPerson(new Person("Ivan"));
personListHandler.addPerson(new Person("Marina"));
personListHandler.addPerson(new Person("Olga"));
personListHandler.addPerson(new Person("Ignat"));
personListHandler.addPerson(new Person("Marina"));
personListHandler.getListInfo();
System.out.println();
System.out.println(personListHandler.getPersonByName("Marina"));
}
} | true |
c7ced93b4b75ce6453142dae49c910bf2efbf6ab | Java | c12yp71Cc0d312/notes-android | /Mentorship Project/app/src/main/java/com/example/onsitetask3/TextNoteInfoDialog.java | UTF-8 | 1,504 | 2.25 | 2 | [] | no_license | package com.example.onsitetask3;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatDialogFragment;
import com.google.firebase.Timestamp;
import java.sql.Date;
import java.text.SimpleDateFormat;
public class TextNoteInfoDialog extends AppCompatDialogFragment {
private static final String TAG = "TextNoteInfoDialog";
Timestamp timestamp;
String createdDate;
public TextNoteInfoDialog(Timestamp timestamp) {
this.timestamp = timestamp;
long seconds = timestamp.getSeconds()*1000;
Date date = new Date(seconds);
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy hh:mm:ss a");
createdDate = sdf.format(date);
Log.d(TAG, "TextNoteInfoDialog: date: " + date);
}
@NonNull
@Override
public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Info")
.setMessage("Created on: " + createdDate)
.setPositiveButton("ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
return builder.create();
}
}
| true |
658a18ec602eaafe32cd35099d176a55f1987ec0 | Java | ogneyar79/junior | /chapter_001/src/main/java/ru/job4j/combainforsaleofbuns/CoinsFive.java | UTF-8 | 3,165 | 3.328125 | 3 | [] | no_license | package ru.job4j.combainforsaleofbuns;
/**
* класс coins5 for and realisation geting and keeping coins.
*
* @author Sirotkin.
*/
public class CoinsFive implements ICoins {
/**
* @ param field for name string.
*/
private final String name = "Coin_5";
public int getNominal() {
return nominal;
}
@Override
public int getCashBalance() {
return cashBalance;
}
private final int nominal = 5;
String yourChange;
/**
* @ param field int for pay maney back.
*/
private int change;
private int quantity;
/**
* @ param int for max sum coins.
*/
private final int maxCash = 1500;
/**
* @ param int field for max monets.
*/
private final int maxQuantity = 300;
/**
* @ param int for quantity monets.
*/
private int balanceMonets;
/**
* @ param int for cout cash 10 coins.
*/
private int cashBalance = balanceMonets * 5;
/**
* @ param int that show remaining place for monets.
*/
private int difference = maxQuantity - balanceMonets;
private int differenceCashBalance = maxCash - cashBalance;
/**
* method for creaction Coinx_10 object.
*
* @param balanceMonets int
*/
public CoinsFive(int balanceMonets, int change) {
this.balanceMonets = balanceMonets;
this.cashBalance = balanceMonets * 5;
this.change = change;
}
public String getName() {
return name;
}
public int getQuantity() {
return quantity;
}
public int getMaxQuantity() {
return maxQuantity;
}
public int getBalanceMonets() {
return balanceMonets;
}
public int getDifference() {
return difference;
}
@Override
public int getMaxCash() {
return maxCash;
}
@Override
public int getDifferenceCashBalance() {
return differenceCashBalance;
}
@Override
public int getChange() {
return change;
}
public void giveChange() {
System.out.println(" Your change =" + " " + change);
}
/**
* method for download coins to stock.
*
* @return balanceMonets
*/
public int putMoney(int quantity) {
int temporraryBank = quantity;
if (quantity > difference) {
change = quantity - differenceCashBalance;
giveChange(change);
temporraryBank = differenceCashBalance;
cashBalance = temporraryBank + cashBalance;
temporraryBank = 0;
} else {
cashBalance = quantity + cashBalance;
temporraryBank = 0;
}
info();
return cashBalance;
}
public void giveChange(int quantity) {
change = quantity;
giveChange();
}
public void info() {
System.out.print("Your balanceMonets is" + balanceMonets + "5 coins" + ", cashBalance" + cashBalance);
}
public void setChange(int change) {
this.change = change;
}
public void setCashBalance(int cashBalance) {
this.cashBalance = cashBalance;
}
}
| true |
6b016ce09d41e85b0bdb93f201c483e2b70039c8 | Java | glee1228/Java_Web_Security_Navigation | /Security_Navigation_Web/src/model/domain/AccidentDTO.java | UTF-8 | 3,272 | 2.671875 | 3 | [] | no_license | package model.domain;
public class AccidentDTO {
private String Name;
private float RiskRatio;
private float RiskGrade;
private String Gu;
private float Length;
private float Lane;
private float AccidentNum;
private float DeadNum;
private float CriticalNum;
private float StableNum;
private float ClaimantNum;
public AccidentDTO() {}
public AccidentDTO(float riskRatio, float riskGrade, float accidentNum, float deadNum, float criticalNum, float stableNum, float claimantNum) {
super();
RiskRatio = riskRatio;
RiskGrade = riskGrade;
AccidentNum = accidentNum;
DeadNum = deadNum;
CriticalNum = criticalNum;
StableNum = stableNum;
ClaimantNum = claimantNum;
}
public AccidentDTO(String name, float riskRatio, float riskGrade, String gu, float length, float lane,
float accidentNum, float deadNum, float criticalNum, float stableNum, float claimantNum) {
super();
Name = name;
RiskRatio = riskRatio;
RiskGrade = riskGrade;
Gu = gu;
Length = length;
Lane = lane;
AccidentNum = accidentNum;
DeadNum = deadNum;
CriticalNum = criticalNum;
StableNum = stableNum;
ClaimantNum = claimantNum;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public float getRiskRatio() {
return RiskRatio;
}
public void setRiskRatio(float riskRatio) {
RiskRatio = riskRatio;
}
public float getRiskGrade() {
return RiskGrade;
}
public void setRiskGrade(float riskGrade) {
RiskGrade = riskGrade;
}
public String getGu() {
return Gu;
}
public void setGu(String gu) {
Gu = gu;
}
public float getLength() {
return Length;
}
public void setLength(float length) {
Length = length;
}
public float getLane() {
return Lane;
}
public void setLane(float lane) {
Lane = lane;
}
public float getAccidentNum() {
return AccidentNum;
}
public void setAccidentNum(float accidentNum) {
AccidentNum = accidentNum;
}
public float getDeadNum() {
return DeadNum;
}
public void setDeadNum(float deadNum) {
DeadNum = deadNum;
}
public float getCriticalNum() {
return CriticalNum;
}
public void setCriticalNum(float criticalNum) {
CriticalNum = criticalNum;
}
public float getStableNum() {
return StableNum;
}
public void setStableNum(float stableNum) {
StableNum = stableNum;
}
public float getClaimantNum() {
return ClaimantNum;
}
public void setClaimantNum(float claimantNum) {
ClaimantNum = claimantNum;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("AccidentDTO [Name=");
builder.append(Name);
builder.append(", RiskRatio=");
builder.append(RiskRatio);
builder.append(", RiskGrade=");
builder.append(RiskGrade);
builder.append(", Gu=");
builder.append(Gu);
builder.append(", Length=");
builder.append(Length);
builder.append(", Lane=");
builder.append(Lane);
builder.append(", AccidentNum=");
builder.append(AccidentNum);
builder.append(", DeadNum=");
builder.append(DeadNum);
builder.append(", CriticalNum=");
builder.append(CriticalNum);
builder.append(", StableNum=");
builder.append(StableNum);
builder.append(", ClaimantNum=");
builder.append(ClaimantNum);
builder.append("]");
return builder.toString();
}
}
| true |
80132d7fd562bd6ba8a05050240fe391ced88d44 | Java | tolweb/tolweb-app | /TreeGrow/src/org/tolweb/treegrow/tree/PriorityPopupMenu.java | UTF-8 | 869 | 2.296875 | 2 | [] | no_license | /*
* Created on Dec 8, 2005
*
* To change the template for this generated file go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
package org.tolweb.treegrow.tree;
import java.util.ArrayList;
import javax.swing.undo.AbstractUndoableEdit;
import org.tolweb.treegrow.tree.undo.PriorityUndoableEdit;
public class PriorityPopupMenu extends AbstractPopupMenu {
/**
*
*/
private static final long serialVersionUID = -7960501283651343536L;
public ArrayList getStrings() {
return Node.getPriorityStrings();
}
/**
* Returns undoable edit, which will specify the property changes to be
* made for the node of interest
*/
public AbstractUndoableEdit getEdit(int newVal) {
return new PriorityUndoableEdit(node, newVal);
}
public int getProperty() {
return node.getPriority();
}
}
| true |
b18ef983702e3439f019e09930399efec5859486 | Java | Hilal-Anwar/ConsoleCalculator | /src/com/Calculator.java | UTF-8 | 1,488 | 3.4375 | 3 | [] | no_license | package com;
public class Calculator extends CalculatorOperation {
Calculator(String ConsoleValue) {
int start = 0, end = 0;
while (ConsoleValue.contains("(") || ConsoleValue.contains(")")) {
for (int i = 0; i < ConsoleValue.length(); i++) {
if (ConsoleValue.charAt(i) == '(')
start = i;
if (ConsoleValue.charAt(i) == ')') {
end = i;
break;
}
}
String x = ConsoleValue.substring(start, end + 1);
Operation(ConsoleValue.substring(start + 1, end));
if (start != 0 && Character.isDigit(ConsoleValue.charAt(start - 1)))
ConsoleValue = ConsoleValue.replace(x, "*" + findAnswers());
else if (start != 0 && ConsoleValue.charAt(start - 1) == '-') {
String y = ConsoleValue.substring(start - 1, end + 1);
ConsoleValue = ConsoleValue.replace(y, -1 + "*" + findAnswers());
} else if (start != 0 && ConsoleValue.charAt(start - 1) == '*')
ConsoleValue = ConsoleValue.replace(x, String.valueOf(findAnswers()));
else
ConsoleValue = ConsoleValue.replace(x, String.valueOf(findAnswers()));
}
Operation(ConsoleValue);
}
Double findAnswers() {
power();
division();
multiplication();
AdditionAndSubtraction();
return FinalValue;
}
}
| true |
1ed6417fa45d2a419f1e84fe6583861964819b1d | Java | Killfill0o/Delfin | /Delfin/Money.java | UTF-8 | 10,728 | 2.890625 | 3 | [] | no_license | // Imports
import java.io.PrintStream;
import java.io.InputStream;
import java.io.FileNotFoundException;
import java.util.Locale;
import java.time.LocalDate;
import java.io.File;
import java.util.Scanner;
import java.util.ArrayList;
import java.math.BigDecimal;
import java.math.RoundingMode;
public class Money {
private String string;
public Money() {
this.string = string;
}
public static void runMenu() {
Display ds = new Display();
Scanner s = new Scanner(System.in);
s.useLocale(Locale.US);
boolean run_money = true;
while(run_money){
ds.clear();
ds.print(" Welcome to money menu \r\n");
ds.print(" 1. Members in restance"+"\r\n"+" 2. Recharge balance"+"\r\n"+" 3. Calculate funds"+"\r\n"+" 4. Exit money menu"+"\r\n");
ds.center(4);
Scanner inninput = new Scanner(System.in);
int innswi = inninput.nextInt();
switch (innswi) {
case 1:
restanceMember();
break;
case 2:
rechargeBalance();
break;
case 3:
calculate();
break;
case 4:
run_money = false;
break;
default:
ds.print("Please choose one of the given options!");
break;
}
}
}
public static void rechargeBalance() {
Display ds = new Display();
ArrayList<Elite> elites = new ArrayList<Elite>();
ArrayList<Members> members = new ArrayList<Members>();
Scanner s = new Scanner(System.in);
s.useLocale(Locale.US);
try{
Scanner scan = new Scanner(new File("_members.log"));
scan.useLocale(Locale.US);
ds.print(" Select ID to recharge: ");
int inp_id = s.nextInt();
ds.print(" Select amount to insert: ");
double ref = s.nextDouble();
double newBalance = 0.0;
if(ref > 0.0){newBalance = ref;;}
while(scan.hasNext())
{
String plan = scan.next();
int id = scan.nextInt();
String fname = scan.next();
String lname = scan.next();
int age = scan.nextInt();
String cpr = scan.next();
String type = scan.next();
String status = scan.next();
double balance = scan.nextDouble();
String disiplin = scan.next();
String trainer = scan.next();
int result = scan.nextInt();
if(id == inp_id){ balance = balance + newBalance;}
elites.add(new Elite(disiplin, trainer, result));
members.add(new Members(plan, id, fname, lname, age, cpr, type, status, balance));
}
PrintStream file = new PrintStream(new File("_members.log"));
for(int i = 0; i < members.size();){
file.print("\r\n"+members.get(i).getPlan()+" "+ members.get(i).getId()+" "+ members.get(i).getFname()+" "+ members.get(i).getLname()+" "+ members.get(i).getAge()+" "+ members.get(i).getCpr()+"\r\n"+ members.get(i).getType()+" "+ members.get(i).getStatus()+" "+ members.get(i).getBalance()+"\r\n"+elites.get(i).getDisiplin()+" "+elites.get(i).getTrainer()+" "+elites.get(i).getResult()+"\r\n");
i++;
}
} catch(FileNotFoundException e){System.out.println(e);}
catch(Exception e){System.out.println(e);}
}
public static void oneYear() {
Display ds = new Display();
ArrayList<Elite> elites = new ArrayList<Elite>();
ArrayList<Members> members = new ArrayList<Members>();
Scanner s = new Scanner(System.in);
try{
Scanner scan = new Scanner(new File("_members.log"));
scan.useLocale(Locale.US);
while(scan.hasNext())
{
String plan = scan.next();
int id = scan.nextInt();
String fname = scan.next();
String lname = scan.next();
int age = scan.nextInt();
String cpr = scan.next();
String type = scan.next();
String status = scan.next();
double balance = scan.nextDouble();
String disiplin = scan.next();
String trainer = scan.next();
int result = scan.nextInt();
double price = 0;
if(age < 18){price = 1000.00;}
if(age > 18){price = 1600.00;}
if(age > 60){price = 1600.00*0.75;}
if(status.equalsIgnoreCase("pasive")){price = 500.00;}
balance = balance - price;
elites.add(new Elite(disiplin, trainer, result));
members.add(new Members(plan, id, fname, lname, age, cpr, type, status, balance));
}
PrintStream file = new PrintStream(new File("_members.log"));
for(int i = 0; i < members.size();){
file.print("\r\n"+members.get(i).getPlan()+" "+ members.get(i).getId()+" "+ members.get(i).getFname()+" "+ members.get(i).getLname()+" "+ members.get(i).getAge()+" "+ members.get(i).getCpr()+"\r\n"+ members.get(i).getType()+" "+ members.get(i).getStatus()+" "+ members.get(i).getBalance()+"\r\n"+elites.get(i).getDisiplin()+" "+elites.get(i).getTrainer()+" "+elites.get(i).getResult()+"\r\n");
i++;
}
} catch(FileNotFoundException e){System.out.println(e);}
catch(Exception e){System.out.println(e);}
}
public static void restanceMember() {
Display ds = new Display();
ArrayList<Elite> elites = new ArrayList<Elite>();
ArrayList<Members> restance = new ArrayList<Members>();
ArrayList<Members> members = new ArrayList<Members>();
Scanner s = new Scanner(System.in);
try{
Scanner scan = new Scanner(new File("_members.log"));
scan.useLocale(Locale.US);
while(scan.hasNext())
{
String plan = scan.next();
int id = scan.nextInt();
String fname = scan.next();
String lname = scan.next();
int age = scan.nextInt();
String cpr = scan.next();
String type = scan.next();
String status = scan.next();
double balance = scan.nextDouble();
String disiplin = scan.next();
String trainer = scan.next();
int result = scan.nextInt();
if(balance < 0){
restance.add(new Members(plan,id,fname,lname,age,cpr,type,status,balance));
}
}
} catch(FileNotFoundException e){System.out.println(e);}
catch(Exception e){System.out.println(e);}
ds.clear();
for(int j = 0; j<restance.size();){
int j1 = j+1;
ds.clear();
ds.print(" Displaying member: "+j1+" / "+restance.size());
ds.center(1);
ds.print(ds.fixlen("Plan",restance.get(j).getPlan(),12)+ds.fixlen("ID",String.valueOf(restance.get(j).getId()),12)+ds.fixlen("Firstname",restance.get(j).getFname(),12)+ds.fixlen("Lastname",restance.get(j).getLname(),12)+ds.fixlen("Age",String.valueOf(restance.get(j).getAge()),12)+ds.fixlen("Cpr",restance.get(j).getCpr(),12)+ds.fixlen("Type",restance.get(j).getType(),12)+ds.fixlen("Status",restance.get(j).getStatus(),12)+ds.fixlen("Balance",String.valueOf(restance.get(j).getBalance()),12));
ds.center(2);
ds.print(" < Last | exit | next > ");
String in = s.next().toString();
if(in.equalsIgnoreCase("last")){
j--;
}
if(in.equalsIgnoreCase("next")){
j++;
}
if(in.equalsIgnoreCase("exit")){
j = 100000;
}
if(j == -1){j = 0;}
}
}
public static void calculate() {
Display ds = new Display();
ArrayList<Elite> elites = new ArrayList<Elite>();
ArrayList<Members> members = new ArrayList<Members>();
Scanner s = new Scanner(System.in);
double totalBalance = 0;
double negBalance = 0;
double posBalance = 0;
try{
Scanner scan = new Scanner(new File("_members.log"));
scan.useLocale(Locale.US);
while(scan.hasNext())
{
String plan = scan.next();
int id = scan.nextInt();
String fname = scan.next();
String lname = scan.next();
int age = scan.nextInt();
String cpr = scan.next();
String type = scan.next();
String status = scan.next();
double balance = scan.nextDouble();
String disiplin = scan.next();
String trainer = scan.next();
int result = scan.nextInt();
totalBalance = totalBalance + balance;
if(balance < 0){
negBalance = negBalance + balance;
}
if(balance > 0){
posBalance = posBalance + balance;
}
}
ds.clear();
ds.print(" Svoemmeklub Delfinen");
ds.center(1);
ds.print(ds.fixlen("Total",String.valueOf(new BigDecimal(totalBalance).setScale(2, RoundingMode.HALF_UP).doubleValue()),8)+
ds.fixlen("Negative",String.valueOf(new BigDecimal(negBalance).setScale(2, RoundingMode.HALF_UP).doubleValue()),8)+
ds.fixlen("Positive",String.valueOf(new BigDecimal(posBalance).setScale(2, RoundingMode.HALF_UP).doubleValue()),8));
ds.center(2);
ds.print(" Hit enter to continue");
ds.center(3);
String pause = System.console().readLine();
} catch(FileNotFoundException e){System.out.println(e);}
catch(Exception e){System.out.println(e);}
} // end calculate
} // end Money | true |
dce08c5f555fccb6e2e4d4f081eea5aa929bf739 | Java | Clark-caipeiyuan/sampleSDK | /XiXiSdk/src/main/java/com/xixi/sdk/model/LLPushContent.java | UTF-8 | 1,392 | 2.0625 | 2 | [
"Apache-2.0"
] | permissive |
package com.xixi.sdk.model;
public class LLPushContent {
public String getService_title() {
return service_title;
}
public LLPushContent() {
}
public LLPushContent(String service_title, String service_body_des, String service_url, String service_image,
String service_time) {
super();
this.service_title = service_title;
this.service_body_des = service_body_des;
this.service_url = service_url;
this.service_image = service_image;
this.service_time = service_time;
}
public void setService_title(String service_title) {
this.service_title = service_title;
}
public String getService_body_des() {
return service_body_des;
}
public void setService_body_des(String service_body_des) {
this.service_body_des = service_body_des;
}
public String getService_url() {
return service_url;
}
public void setService_url(String service_url) {
this.service_url = service_url;
}
public String getService_image() {
return service_image;
}
public void setService_image(String service_image) {
this.service_image = service_image;
}
public String getService_time() {
return service_time;
}
public void setService_time(String service_time) {
this.service_time = service_time;
}
private String service_title;
private String service_body_des;
private String service_url;
private String service_image;
private String service_time;
}
| true |
3c0eba0c2168ed64e2faf3c1ad01c791740be3cd | Java | pjok1122/JSP-Model2-Board-Project | /src/com/dev/dto/UserDTO.java | UTF-8 | 680 | 2.546875 | 3 | [] | no_license | package com.dev.dto;
public class UserDTO {
private int seq;
private String id;
private String password;
private String name;
private int gender;
private String salt;
public UserDTO(int seq, String id, String password, String name, int gender, String salt) {
this.seq = seq;
this.id = id;
this.password = password;
this.name = name;
this.gender = gender;
this.salt = salt;
}
public int getSeq() {
return seq;
}
public String getSalt() {
return salt;
}
public String getId() {
return id;
}
public String getPassword() {
return password;
}
public String getName() {
return name;
}
public int getGender() {
return gender;
}
}
| true |
999d1002af0e67b331e720cc4f58d4050a86ec0e | Java | Diffblue-benchmarks/Classfan-test | /src/main/java/com/baison/e3plus/basebiz/order/service/dao/mapper/rds/AdvancedStrategyPlatformGoodsDetailMapper.java | UTF-8 | 1,292 | 1.90625 | 2 | [] | no_license | package com.baison.e3plus.basebiz.order.service.dao.mapper.rds;
import com.baison.e3plus.basebiz.order.api.model.adapter.AdvancedStrategyPlatformGoodsDetail;
import com.baison.e3plus.basebiz.order.service.dao.model.example.AdvancedStrategyPlatformGoodsDetailExample;
import java.util.List;
public interface AdvancedStrategyPlatformGoodsDetailMapper {
int deleteByPrimaryKey(Long id);
int insert(AdvancedStrategyPlatformGoodsDetail record);
int insertSelective(AdvancedStrategyPlatformGoodsDetail record);
List<AdvancedStrategyPlatformGoodsDetail> selectByExample(AdvancedStrategyPlatformGoodsDetailExample example);
AdvancedStrategyPlatformGoodsDetail selectByPrimaryKey(Long id);
int updateByPrimaryKeySelective(AdvancedStrategyPlatformGoodsDetail record);
int updateByPrimaryKey(AdvancedStrategyPlatformGoodsDetail record);
int insertBatch(AdvancedStrategyPlatformGoodsDetail[] beans);
int updateByPrimaryKeySelectiveBatch(AdvancedStrategyPlatformGoodsDetail[] sortedBeans);
int deleteByPrimaryKeyBatch(Long[] idArr);
List<AdvancedStrategyPlatformGoodsDetail> selectByPrimaryKeyBatch(Object[] ids);
long countByExample(AdvancedStrategyPlatformGoodsDetailExample example);
int deleteByExpressStrategyIdBatch(Long[] idArr);
} | true |
826645012a38182c1c3be758150e866588bb9841 | Java | VoraciousSoftworks/Here-There-Be-Dragons | /src/com/voracious/dragons/client/utils/InputHandler.java | UTF-8 | 6,770 | 2.71875 | 3 | [] | no_license | package com.voracious.dragons.client.utils;
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import com.voracious.dragons.client.graphics.Screen;
import com.voracious.dragons.common.Vec2D;
public class InputHandler implements KeyListener, MouseListener, MouseMotionListener {
public static final int VK_MOUSE_1 = 7894561;
public static final int VK_MOUSE_2 = 7894562;
public static final int VK_MOUSE_WHEEL = 7894563;
public static Map<Integer, Boolean> keymap;
public static List<Screen> screens;
private static int mousex = 0;
private static int mousey = 0;
private static int dx = 0;
private static int dy = 0;
private static int sx = 0;
private static int sy = 0;
private static boolean letMouseMove = true;
private static Robot robot;
private static Logger logger = Logger.getLogger(InputHandler.class);
public InputHandler() {
keymap = new HashMap<Integer, Boolean>(307);
screens = new ArrayList<Screen>();
try {
robot = new Robot();
} catch (AWTException e) {
logger.error("Could not capture mouse", e);
}
registerButton(VK_MOUSE_1);
registerButton(VK_MOUSE_2);
registerButton(VK_MOUSE_WHEEL);
}
public static void registerButton(int keyCode) {
if (keymap.containsKey(keyCode)) {
logger.warn("Key already registered");
} else {
keymap.put(keyCode, false);
}
}
public static void deregisterButton(int keyCode) {
keymap.remove(keyCode);
}
public static void registerScreen(Screen screen) {
synchronized(screens){
screens.add(screen);
}
}
public static void deregisterScreen(Screen screen) {
synchronized(screens){
screens.remove(screen);
}
}
public static boolean isDown(int keyCode) {
Boolean result = keymap.get(keyCode);
if (result == null) {
logger.error("Key not registered; returned false");
return false;
} else {
return result.booleanValue();
}
}
public static void setMouseMoveable(boolean letMouseMove) {
InputHandler.letMouseMove = letMouseMove;
}
public static Vec2D getChangeInMouse() {
return new Vec2D.Double(dx, dy);
}
public static Vec2D getMousePos() {
return new Vec2D.Double(mousex, mousey);
}
private void handleMouseMotion(MouseEvent arg0) {
dx = arg0.getX() - mousex;
dy = arg0.getY() - mousey;
if (letMouseMove) {
mousex = arg0.getX();
mousey = arg0.getY();
sx = arg0.getXOnScreen();
sy = arg0.getYOnScreen();
} else {
if (robot != null) {
robot.mouseMove(sx, sy);
} else {
logger.warn("Robot is not available");
letMouseMove = true;
}
}
synchronized(screens){
Iterator<Screen> it = screens.iterator();
while (it.hasNext()) {
it.next().mouseMoved(arg0);
}
}
}
@Override
public void mouseMoved(MouseEvent arg0) {
handleMouseMotion(arg0);
}
@Override
public void mouseDragged(MouseEvent arg0) {
handleMouseMotion(arg0);
}
@Override
public void mousePressed(MouseEvent arg0) {
switch (arg0.getButton()) {
case MouseEvent.BUTTON1:
keymap.put(VK_MOUSE_1, true);
break;
case MouseEvent.BUTTON3:
keymap.put(VK_MOUSE_2, true);
break;
case MouseEvent.BUTTON2:
keymap.put(VK_MOUSE_WHEEL, true);
break;
default:
if (arg0.getButton() != MouseEvent.NOBUTTON) {
if (keymap.containsKey(arg0.getButton())) {
keymap.put(arg0.getButton(), true);
}
}
}
synchronized(screens){
Iterator<Screen> it = screens.iterator();
while (it.hasNext()) {
it.next().mousePressed(arg0);
}
}
}
@Override
public void mouseReleased(MouseEvent arg0) {
switch (arg0.getButton()) {
case MouseEvent.BUTTON1:
keymap.put(VK_MOUSE_1, false);
break;
case MouseEvent.BUTTON3:
keymap.put(VK_MOUSE_2, false);
break;
case MouseEvent.BUTTON2:
keymap.put(VK_MOUSE_WHEEL, false);
break;
default:
if (arg0.getButton() != MouseEvent.NOBUTTON) {
if (keymap.containsKey(arg0.getButton())) {
keymap.put(arg0.getButton(), false);
}
}
}
synchronized(screens){
Iterator<Screen> it = screens.iterator();
while (it.hasNext()) {
it.next().mouseReleased(arg0);
}
}
}
@Override
public void keyPressed(KeyEvent arg0) {
if (keymap.containsKey(arg0.getKeyCode())) {
keymap.put(arg0.getKeyCode(), true);
}
synchronized(screens){
Iterator<Screen> it = screens.iterator();
while (it.hasNext()) {
it.next().keyPressed(arg0);
}
}
}
@Override
public void keyReleased(KeyEvent arg0) {
if (keymap.containsKey(arg0.getKeyCode())) {
keymap.put(arg0.getKeyCode(), false);
}
synchronized(screens){
Iterator<Screen> it = screens.iterator();
while (it.hasNext()) {
it.next().keyReleased(arg0);
}
}
}
@Override
public void keyTyped(KeyEvent arg0) {
synchronized(screens){
Iterator<Screen> it = screens.iterator();
while (it.hasNext()) {
it.next().keyTyped(arg0);
}
}
}
@Override
public void mouseClicked(MouseEvent arg0) {
synchronized(screens){
Iterator<Screen> it = screens.iterator();
while (it.hasNext()) {
it.next().mouseClicked(arg0);
}
}
}
@Override
public void mouseEntered(MouseEvent arg0) {
}
@Override
public void mouseExited(MouseEvent arg0) {
}
}
| true |
c6f2aa32ddb90a45bf3304fd95e6cf29205c9b0c | Java | changchen96/ClinicManagementSystem | /src/clinicsystem/EditStaffMemberMenu.java | UTF-8 | 18,433 | 2.296875 | 2 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package clinicsystem;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import javax.swing.JOptionPane;
/**
*
* @author c7-ong
*/
public class EditStaffMemberMenu extends javax.swing.JFrame {
/**
* Creates new form AddPatientMenu
*/
String role;
final static String DATE_FORMAT = "dd/MM/yyyy";
public EditStaffMemberMenu() {
initComponents();
}
public void setRole(String setRole)
{
this.role = setRole;
System.out.println(role);
}
public String getRole()
{
return role;
}
public javax.swing.JComboBox<String> getComboBox()
{
return staffCombo;
}
public boolean isDateValid(String date)
{
try
{
DateFormat format = new SimpleDateFormat(DATE_FORMAT);
format.setLenient(false);
format.parse(date);
return true;
}
catch (ParseException e)
{
System.out.println(e.getMessage());
return false;
}
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
usernameText = new javax.swing.JTextField();
jLabel5 = new javax.swing.JLabel();
staffRoleText = new javax.swing.JTextField();
addressText = new javax.swing.JTextField();
jLabel6 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
telNoText = new javax.swing.JTextField();
updateStaffDetailsBtn = new javax.swing.JButton();
backBtn = new javax.swing.JButton();
jLabel8 = new javax.swing.JLabel();
staffNameText = new javax.swing.JTextField();
jLabel9 = new javax.swing.JLabel();
DOBText = new javax.swing.JTextField();
passwordText = new javax.swing.JPasswordField();
jLabel4 = new javax.swing.JLabel();
staffCombo = new javax.swing.JComboBox<>();
selectStaffBtn = new javax.swing.JButton();
jLabel10 = new javax.swing.JLabel();
staffIDText = new javax.swing.JTextField();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setText("Edit staff details");
jLabel2.setText("Username:");
jLabel3.setText("Password:");
usernameText.setEnabled(false);
usernameText.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
usernameTextActionPerformed(evt);
}
});
jLabel5.setText("Staff Role:");
staffRoleText.setEnabled(false);
addressText.setEnabled(false);
jLabel6.setText("Address:");
jLabel7.setText("Tel. no:");
telNoText.setEnabled(false);
updateStaffDetailsBtn.setText("Update staff member details");
updateStaffDetailsBtn.setEnabled(false);
updateStaffDetailsBtn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
updateStaffDetailsBtnActionPerformed(evt);
}
});
backBtn.setText("Back");
backBtn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
backBtnActionPerformed(evt);
}
});
jLabel8.setText("Staff Name:");
staffNameText.setEnabled(false);
jLabel9.setText("Date of birth (dd/mm/yyyy):");
DOBText.setEnabled(false);
passwordText.setEnabled(false);
jLabel4.setText("Staff ID:");
selectStaffBtn.setText("Select staff member");
selectStaffBtn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
selectStaffBtnActionPerformed(evt);
}
});
jLabel10.setText("Staff ID:");
staffIDText.setEnabled(false);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(32, 32, 32)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel4)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(staffCombo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(selectStaffBtn))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel1)
.addComponent(updateStaffDetailsBtn)
.addGroup(layout.createSequentialGroup()
.addGap(84, 84, 84)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel10)
.addComponent(jLabel2))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(staffIDText)
.addComponent(usernameText)))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel9)
.addComponent(jLabel7, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel6, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel5, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel8, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel3, javax.swing.GroupLayout.Alignment.TRAILING))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(telNoText)
.addComponent(addressText)
.addComponent(staffRoleText)
.addComponent(staffNameText)
.addGroup(layout.createSequentialGroup()
.addComponent(passwordText, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
.addComponent(DOBText)))))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(backBtn)
.addGap(42, 42, 42))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(26, 26, 26)
.addComponent(jLabel1)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4)
.addComponent(staffCombo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(selectStaffBtn))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel10)
.addComponent(staffIDText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(2, 2, 2)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(usernameText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(passwordText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(9, 9, 9)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel8)
.addComponent(staffNameText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel5)
.addComponent(staffRoleText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(addressText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel6))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel7)
.addComponent(telNoText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel9)
.addComponent(DOBText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(updateStaffDetailsBtn)
.addComponent(backBtn))
.addContainerGap())
);
pack();
setLocationRelativeTo(null);
}// </editor-fold>//GEN-END:initComponents
private void usernameTextActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_usernameTextActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_usernameTextActionPerformed
private void updateStaffDetailsBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_updateStaffDetailsBtnActionPerformed
// TODO add your handling code here:
if (usernameText.getText().isEmpty() ||
String.valueOf(passwordText.getPassword()).isEmpty() ||
staffNameText.getText().isEmpty() ||
staffRoleText.getText().isEmpty() ||
addressText.getText().isEmpty() ||
telNoText.getText().isEmpty() ||
DOBText.getText().isEmpty() ||
staffIDText.getText().isEmpty())
{
JOptionPane.showMessageDialog(null, "One or more empty fields detected! Please fill in the empty fields!");
}
else if (isDateValid(DOBText.getText()) == false)
{
JOptionPane.showMessageDialog(null, "Please re-enter date again!");
}
else
{
String username = usernameText.getText();
String password = String.valueOf(passwordText.getPassword());
String staffName = staffNameText.getText();
String staffRole = staffRoleText.getText();
String address = addressText.getText();
String telNo = telNoText.getText();
String dob = DOBText.getText();
String id = staffIDText.getText();
databaseConn.updateStaffDetails(username, password, staffName, staffRole, address, telNo, dob, id);
}
}//GEN-LAST:event_updateStaffDetailsBtnActionPerformed
private void backBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_backBtnActionPerformed
// TODO add your handling code here:
ManageStaffMembersMenu manageStaff = new ManageStaffMembersMenu();
manageStaff.setVisible(true);
manageStaff.setRole(this.getRole());
dispose();
}//GEN-LAST:event_backBtnActionPerformed
private void selectStaffBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_selectStaffBtnActionPerformed
// TODO add your handling code here:
String id = staffCombo.getSelectedItem().toString();
if (id.isEmpty())
{
JOptionPane.showMessageDialog(null, "Select a patient first!");
}
else
{
databaseConn.findStaffDetailsForEdit(id, staffIDText, usernameText, passwordText, staffNameText, staffRoleText, addressText, telNoText, DOBText);
usernameText.setEnabled(true);
passwordText.setEnabled(true);
staffNameText.setEnabled(true);
staffRoleText.setEnabled(true);
addressText.setEnabled(true);
telNoText.setEnabled(true);
DOBText.setEnabled(true);
updateStaffDetailsBtn.setEnabled(true);
}
}//GEN-LAST:event_selectStaffBtnActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(EditStaffMemberMenu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(EditStaffMemberMenu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(EditStaffMemberMenu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(EditStaffMemberMenu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new EditStaffMemberMenu().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JTextField DOBText;
private javax.swing.JTextField addressText;
private javax.swing.JButton backBtn;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JPasswordField passwordText;
private javax.swing.JButton selectStaffBtn;
private javax.swing.JComboBox<String> staffCombo;
private javax.swing.JTextField staffIDText;
private javax.swing.JTextField staffNameText;
private javax.swing.JTextField staffRoleText;
private javax.swing.JTextField telNoText;
private javax.swing.JButton updateStaffDetailsBtn;
private javax.swing.JTextField usernameText;
// End of variables declaration//GEN-END:variables
}
| true |
9ebe8af6f92e932ac2234bd5a915365812f78f74 | Java | swarup1986/SeleniumProject | /Internship/src/main/java/ConnectWithUsFlow.java | UTF-8 | 781 | 2.109375 | 2 | [] | no_license |
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class ConnectWithUsFlow {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:\\Swarup\\Selenium\\chromedriver_win32\\chromedriver.exe");
WebDriver driver=new ChromeDriver();
driver.get("https://www.validlog.com/contact-us/");
driver.findElement(By.id("form-field-name")).sendKeys("a");
driver.findElement(By.id("form-field-phone")).sendKeys("3");
driver.findElement(By.id("form-field-email")).sendKeys("ee");
driver.findElement(By.id("form-field-message")).sendKeys("ddd");
driver.findElement(By.xpath("//span[contains(text(),'Send')]")).click();
driver.quit();
}
}
| true |
8a79ceef6bc9f5e6b69e07828e61f32ac7231997 | Java | eakulova/Multithreading | /src/main/java/MinValueSearcherThread.java | UTF-8 | 843 | 3.125 | 3 | [] | no_license | public class MinValueSearcherThread extends Thread {
private InputStorage inputStorage;
public MinValueSearcherThread(InputStorage inputStorage) {
this.inputStorage = inputStorage;
}
private static final int SLEEP_TIME_MILLIS = 5_000;
@Override
public void run() {
while (true) {
try {
Thread.sleep(SLEEP_TIME_MILLIS);
deleteMinValue();
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}
private void deleteMinValue() {
try {
int deletedNumber = inputStorage.findMinValueAndDelete();
System.out.println("min value is: " + deletedNumber);
} catch (IllegalStateException ex) {
System.out.println(ex.getMessage());
}
}
}
| true |
a0ff82f7bc7bdecf27540958c57a7b90b6b92dc1 | Java | maneesh-javadev/creative-mind | /src/com/cmc/lgd/localbody/entities/LBTypeDetails.java | UTF-8 | 2,334 | 2.265625 | 2 | [] | no_license | package com.cmc.lgd.localbody.entities;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedNativeQueries;
import javax.persistence.NamedNativeQuery;
@Entity
@NamedNativeQueries({
@NamedNativeQuery(query = "SELECT * from get_dynamic_lb_hierarchy_dtl_with_type(:setupCode, :setupVersion);", name ="Dynamic_Local_body_Type_Details", resultClass = LBTypeDetails.class),
@NamedNativeQuery(query = "Select * from get_statewise_lb_type_details(:stateCode, :panchayatType);", name ="Urban_Local_body_Type_Details", resultClass = LBTypeDetails.class),
@NamedNativeQuery(query = "SELECT tier_setup_code, local_body_type_code, local_body_type_name as name, parent_tier_setup_code, level as lblevel, category as lbType FROM get_local_gov_setup_fn(:stateCode, :panchayatType) where local_body_type_code <> :selectedLBType", name ="Excluded_Selection_Urban_LB_Type", resultClass = LBTypeDetails.class),
})
public class LBTypeDetails {
@Id
@Column(name = "tier_setup_code", nullable = false)
private Integer tierSetupCode;
@Column(name = "local_body_type_code", nullable = false)
private Integer localBodyTypeCode;
@Column(name = "lbtype")
private Character lbType;
@Column(name = "name")
private String name;
@Column(name = "parent_tier_setup_code")
private Integer parentTierSetupCode;
@Column(name = "lblevel")
private Character lbLevel;
public Integer getTierSetupCode() {
return tierSetupCode;
}
public void setTierSetupCode(Integer tierSetupCode) {
this.tierSetupCode = tierSetupCode;
}
public Integer getLocalBodyTypeCode() {
return localBodyTypeCode;
}
public void setLocalBodyTypeCode(Integer localBodyTypeCode) {
this.localBodyTypeCode = localBodyTypeCode;
}
public Character getLbType() {
return lbType;
}
public void setLbType(Character lbType) {
this.lbType = lbType;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getParentTierSetupCode() {
return parentTierSetupCode;
}
public void setParentTierSetupCode(Integer parentTierSetupCode) {
this.parentTierSetupCode = parentTierSetupCode;
}
public Character getLbLevel() {
return lbLevel;
}
public void setLbLevel(Character lbLevel) {
this.lbLevel = lbLevel;
}
}
| true |
ce81f8f6c71bbce86617aabf1ab0f5f4059d8ee4 | Java | ZM9316/dangjian | /FangjiazhuangApp/app/src/main/java/a9chou/com/fangjiazhuangApp/module/activity/MyReadActivity.java | UTF-8 | 4,396 | 1.921875 | 2 | [] | no_license | package a9chou.com.fangjiazhuangApp.module.activity;
import android.util.Log;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.android.tu.loadingdialog.LoadingDailog;
import org.litepal.crud.DataSupport;
import java.util.List;
import a9chou.com.fangjiazhuangApp.R;
import a9chou.com.fangjiazhuangApp.base.BaseActivity;
import a9chou.com.fangjiazhuangApp.db.BookList;
import a9chou.com.fangjiazhuangApp.utils.UrlUtil;
import a9chou.com.fangjiazhuangApp.utils.WebViewUtils;
import butterknife.BindView;
import butterknife.OnClick;
import static a9chou.com.fangjiazhuangApp.utils.Config.IP;
public class MyReadActivity extends BaseActivity {
private static final String TAG = "MyReadActivity";
@BindView(R.id.big_events_left_back)
TextView mBigEventsLeftBack;
@BindView(R.id.big_events_title_title)
TextView mBigEventsTitleTitle;
@BindView(R.id.big_events_search_iv)
ImageView mBigEventsSearchIv;
@BindView(R.id.big_events_title_relative)
RelativeLayout mBigEventsTitleRelative;
@BindView(R.id.big_events_search_edit)
EditText mBigEventsSearchEdit;
@BindView(R.id.search_abolish)
TextView mSearchAbolish;
@BindView(R.id.search_linear)
LinearLayout mSearchLinear;
@BindView(R.id.web)
WebView mWeb;
@BindView(R.id.activity_big_events)
LinearLayout mActivityBigEvents;
private LoadingDailog mDialog;
private List<BookList> mBookLists;
private String mUrl;
private String mId;
private BookList mBookList;
private String mRecordId;
@Override
protected int attachLayoutRes() {
return R.layout.activity_my_read;
}
@Override
protected void initViews() {
mBigEventsTitleTitle.setText("我阅读的书籍");
mBigEventsSearchIv.setVisibility(View.GONE);
LoadingDailog.Builder loadBuilder = new LoadingDailog.Builder(MyReadActivity.this)
.setMessage("加载中...")
.setCancelable(true);
mDialog = loadBuilder.create();
mDialog.show();
// 查。
mBookLists = DataSupport.findAll(BookList.class);
String url = UrlUtil.FATHER_HTML + UrlUtil.READ + UrlUtil.getWithNo(this);
// 设置支持js
WebViewUtils.setWebView(mDialog, mWeb, url, MyReadActivity.this, "android");
// 获取webview中的标题,然后传到我的title中
WebChromeClient wvcc = new WebChromeClient() {
@Override
public void onReceivedTitle(WebView view, String title) {
super.onReceivedTitle(view, title);
mBigEventsTitleTitle.setText(title);
}
};
mWeb.setWebChromeClient(wvcc);
}
@OnClick(R.id.big_events_left_back)
public void onViewClicked() {
finish();
}
//在线学习 跳转 阅读角界面
@JavascriptInterface
public void readingCorner(final String str) {
runOnUiThread(new Runnable() {
@Override
public void run() {
String[] a = str.split(",");
mUrl = a[0];
mId = a[2];
mRecordId = a[1];
Log.d(TAG, "run: id ==>" + mUrl + " " + mId);
mBookList = new BookList();
mBookList.setBookpath(IP+"/treps" + mUrl);
if (mBookLists.size() == 0) {
mBookList.save();
} else {
boolean isSave = false;
for (int i = 0; i < mBookLists.size(); i++) {
if (mBookLists.get(i).getBookpath().equals(mBookList.getBookpath())) {
isSave = true;
mBookList = mBookLists.get(i);
}
}
if (!isSave) {
mBookList.save();
}
}
ReadActivity.openBook(mBookList, MyReadActivity.this, mId, mRecordId);
}
});
}
@Override
protected void onStart() {
super.onStart();
mWeb.reload();
}
} | true |
8de94b939501a26653dc3bab759861314b934fee | Java | mklemarczyk/test-1516 | /java/Proj2/src/test/java/ug/lab/project2/MockitoTest.java | UTF-8 | 4,048 | 2.5 | 2 | [] | no_license | package ug.lab.project2;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import ug.lab.project2.ConnectionStatus;
import ug.lab.project2.MalformedRecipientException;
import ug.lab.project2.MessageService;
import ug.lab.project2.SendingStatus;
public class MockitoTest {
@Mock
private MessageService mockService;
private Messenger msg;
private final String VALID_SERVER = "inf.ug.edu.pl";
private final String INVALID_SERVER = "inf.ug.edu.eu";
private final String INVALID_SERVER2 = "xxx";
private final String VALID_MESSAGE = "some message";
private final String INVALID_MESSAGE = "ab";
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
msg = new Messenger(mockService);
}
@After
public void tearDown() throws Exception {
mockService = null;
msg = null;
}
@Test
public void checkConnectionValidServer() {
when(mockService.checkConnection(VALID_SERVER)).thenReturn(ConnectionStatus.SUCCESS);
int result = msg.testConnection(VALID_SERVER);
assertEquals(0, result);
verify(mockService).checkConnection(VALID_SERVER);
}
@Test
public void checkFailureConnectionValidServer() {
when(mockService.checkConnection(VALID_SERVER)).thenReturn(ConnectionStatus.FAILURE);
int result = msg.testConnection(VALID_SERVER);
assertEquals(1, result);
verify(mockService).checkConnection(VALID_SERVER);
}
@Test
public void checkConnectionInvalidServer() {
when(mockService.checkConnection(INVALID_SERVER)).thenReturn(ConnectionStatus.FAILURE);
int result = msg.testConnection(INVALID_SERVER);
assertEquals(1, result);
verify(mockService).checkConnection(INVALID_SERVER);
}
@Test
public void checkConnectionNoServer() {
when(mockService.checkConnection(null)).thenReturn(ConnectionStatus.FAILURE);
int result = msg.testConnection(null);
assertEquals(1, result);
verify(mockService).checkConnection(null);
}
@Test
public void sendValidServerAndValidMessage() throws MalformedRecipientException {
when(mockService.send(VALID_SERVER, VALID_MESSAGE)).thenReturn(SendingStatus.SENT);
int result = msg.sendMessage(VALID_SERVER, VALID_MESSAGE);
assertEquals(0, result);
verify(mockService).send(VALID_SERVER, VALID_MESSAGE);
}
@Test
public void sendErrorValidServerAndValidMessage() throws MalformedRecipientException {
when(mockService.send(VALID_SERVER, VALID_MESSAGE)).thenReturn(SendingStatus.SENDING_ERROR);
int result = msg.sendMessage(VALID_SERVER, VALID_MESSAGE);
assertEquals(1, result);
verify(mockService).send(VALID_SERVER, VALID_MESSAGE);
}
@Test
public void sendInvalidServerAndValidMessage() throws MalformedRecipientException {
when(mockService.send(INVALID_SERVER2, VALID_MESSAGE)).thenThrow(new MalformedRecipientException());
int result = msg.sendMessage(INVALID_SERVER2, VALID_MESSAGE);
assertEquals(2, result);
verify(mockService).send(INVALID_SERVER2, VALID_MESSAGE);
}
@Test
public void sendValidServerAndInvalidMessage() throws MalformedRecipientException {
when(mockService.send(VALID_SERVER, INVALID_MESSAGE)).thenThrow(new MalformedRecipientException());
int result = msg.sendMessage(VALID_SERVER, INVALID_MESSAGE);
assertEquals(2, result);
verify(mockService).send(VALID_SERVER, INVALID_MESSAGE);
}
@Test
public void sendNoServerAndValidMessage() throws MalformedRecipientException {
when(mockService.send(null, VALID_MESSAGE)).thenThrow(new MalformedRecipientException());
int result = msg.sendMessage(null, VALID_MESSAGE);
assertEquals(2, result);
verify(mockService).send(null, VALID_MESSAGE);
}
@Test
public void sendValidServerAndNoMessage() throws MalformedRecipientException {
when(mockService.send(VALID_SERVER, null)).thenThrow(new MalformedRecipientException());
int result = msg.sendMessage(VALID_SERVER, null);
assertEquals(2, result);
verify(mockService).send(VALID_SERVER, null);
}
}
| true |
07876822c0091373b3138e22b1fa1134724ad0ee | Java | Chethan-Bidare/c2info_OrderBuk | /src/main/java/c2info_OrderBuk_UIPages/ReadyForOrder.java | UTF-8 | 8,344 | 2.21875 | 2 | [] | no_license | package c2info_OrderBuk_UIPages;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.log4j.Logger;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;
import c2info_OrderBuk_TestBase.TestBase;
public class ReadyForOrder extends TestBase{
public static final Logger log = Logger.getLogger(ReadyForOrder.class.getName());
WebDriverWait wait = new WebDriverWait(driver, 45);
@FindBy(xpath=".//*[@id='wrapper']/div/div[1]/div/div/div/label")
WebElement OrderIDInRFO ;
@FindBy(xpath=".//*[@id='wrapper']/div/div[1]/div/div/div/div/div[1]/form/div[1]")
WebElement CustomerNameInRFO ;
@FindBy(xpath=".//*[@id='wrapper']/div/div[1]/div/div/div/div/div[1]/form/div[3]")
WebElement CustomerNumberInRFO ;
@FindBy(id="subtotal")
WebElement SubTotal ;
@FindBy(id="discount")
WebElement discount ;
@FindBy(id="del")
WebElement deliverycharge ;
@FindBy(id="total")
WebElement GrandTotal ;
@FindBy(id="btnconfirm")
WebElement ConfirmBtn ;
@FindBy(id="reverify")
WebElement reverifyBtn ;
@FindBy(id="textbr")
WebElement Remark ;
@FindBy(xpath=".//*[@id='bootstrap-table_filter']/label/input")
WebElement Searchbox ;
@FindBy(id="cancel")
WebElement cancelBtn ;
@FindBy(id="btncancel")
WebElement ordercancelbtn ;
@FindBy(id="ll")
WebElement itemSearch ;
@FindBy(id="delivery")
WebElement deliveryDropdown ;
@FindBy(id="payment")
WebElement paymentDropdown ;
public ReadyForOrder(){
PageFactory.initElements(driver, this);
}
public void selectOrder(String OrderID) throws InterruptedException{
List<WebElement> orderIDs = driver.findElements(By.xpath(".//*[@id='bootstrap-table']/tbody/tr/td[1]"));
for(WebElement we : orderIDs){
if(we.getText().equals(OrderID)){
we.click();
break ;
}
}
Thread.sleep(5000);
}
public String getOrderIDFromRFOPage(){
String OrderID = OrderIDInRFO.getText();
OrderID = OrderID.substring(OrderID.length()-6,OrderID.length());
OrderID = OrderID.trim();
System.out.println(OrderID);
return OrderID ;
}
public ArrayList<String> getItemNames(){
ArrayList<String> ItemNames = new ArrayList<String>();
List<WebElement> itemlist = driver.findElements(By.xpath(".//*[@id='printTable']/tbody/tr"));
for(int i=1; i<=itemlist.size(); i++){
String temp = driver.findElement(By.xpath(".//*[@id='printTable']/tbody/tr["+i+"]/td[2]")).getText();
ItemNames.add(temp);
}
return ItemNames ;
}
public String getCustomerNameInRFOpage(){
String custName = CustomerNameInRFO.getText();
custName.trim();
custName = custName.substring(16);
return custName ;
}
public String getCustomerNumberInRFOpage(){
String custNum = CustomerNumberInRFO.getText();
custNum.trim();
custNum = custNum.substring(16);
return custNum ;
}
public ArrayList<Double> getItemwiseAmt() throws InterruptedException{
Thread.sleep(2000);
ArrayList<Double> ItemAmtlist = new ArrayList<Double>();
List<WebElement> itemlist = driver.findElements(By.xpath(".//*[@id='printTable']/tbody/tr"));
for(int i=0; i<itemlist.size(); i++){
String temp = driver.findElement(By.xpath(".//*[@id='total_value"+i+"']")).getAttribute("value");
System.out.println(temp);
temp = temp.trim();
double temp1 = Double.parseDouble(temp);
ItemAmtlist.add(temp1);
}
return ItemAmtlist ;
}
public double getItemWiseTotalAmt() throws InterruptedException{
double total = 0;
ArrayList<Double> ItemAmttot = getItemwiseAmt();
for(double sum : ItemAmttot ){
total +=sum ;
}
return total ;
}
public double getSubTotal() throws InterruptedException{
Thread.sleep(2000);
String subtotal = SubTotal.getText();
double subTotalAmt = Double.parseDouble(subtotal);
return subTotalAmt ;
}
public double getDiscount() throws InterruptedException{
Thread.sleep(2000);
String disc = discount.getText();
double discount = Double.parseDouble(disc);
return discount ;
}
public double getDeliverycharge() throws InterruptedException{
Thread.sleep(2000);
String del = deliverycharge.getText();
double delivery = Double.parseDouble(del);
return delivery ;
}
public double getGrandTotal() throws InterruptedException{
Thread.sleep(2000);
String total = GrandTotal.getText();
double GrandTot = Double.parseDouble(total);
return GrandTot ;
}
public void clickOnConfirmBtnInRFOpage() throws InterruptedException{
ConfirmBtn.click();
Thread.sleep(5000);
}
public void clickOnCancelBtnInRFOpage(){
cancelBtn.click();
}
public void enterCancelDetails(){
Remark.sendKeys("order cancel");
ordercancelbtn.click();
}
public void clickOnReverifyBtnInRFOpage(){
reverifyBtn.click();
}
public void SearchOrder(String OrderID){
Searchbox.clear();
Searchbox.sendKeys(OrderID);
}
public void enterItemNameInSearch(String ItemName) throws InterruptedException{
itemSearch.clear();
itemSearch.sendKeys(ItemName);
Thread.sleep(10000);
SelectItemNameFromAutoSuggestionSearch(ItemName);
}
public void UncheckAllItems() throws InterruptedException{
Thread.sleep(3000);
List<WebElement> itemlist = driver.findElements(By.xpath(".//*[@id='printTable']/tbody/tr"));
for(int i=0; i<itemlist.size(); i++){
driver.findElement(By.id("itemchk"+i+"")).click();
}
}
public String select1Item() {
List<WebElement> itemlist = driver.findElements(By.xpath(".//*[@id='printTable']/tbody/tr"));
for(int i=0; i<itemlist.size(); i++){
driver.findElement(By.id("itemchk"+i+"")).click();
}
String itemName = driver.findElement(By.id("01")).getText();
System.out.println();
driver.findElement(By.id("itemchk0")).click();
return itemName ;
}
public HashMap<String,Integer> getItemNamesAndQtyInRFO(){
List<WebElement> itemlist = driver.findElements(By.xpath(".//*[@id='printTable']/tbody/tr"));
HashMap<String, Integer> itemNameAndQty = new HashMap<String, Integer>();
for(int i=0;i<itemlist.size(); i++){
String val;
String key = driver.findElement(By.xpath(".//*[@id='"+i+"1']")).getText();
val = driver.findElement(By.xpath(".//*[@id='qty"+i+"']")).getAttribute("value");
int value = Integer.parseInt(val);
itemNameAndQty.put(key, value);
}
for(String check : itemNameAndQty.keySet()){
String key = check.toString();
int val = itemNameAndQty.get(check);
System.out.println("Key ="+key);
System.out.println("Value ="+val);
}
return itemNameAndQty ;
}
public int getNoOfItems(){
List<WebElement> itemlist = driver.findElements(By.xpath(".//*[@id='printTable']/tbody/tr"));
int noOfItems = itemlist.size();
return noOfItems ;
}
public void increaseQtyForAddedItem() throws InterruptedException{
int noOfItems = getNoOfItems() - 1 ;
driver.findElement(By.xpath(".//*[@id='"+noOfItems+"3']/a[2]")).click();
Thread.sleep(1000);
driver.findElement(By.xpath(".//*[@id='"+noOfItems+"3']/a[2]")).click();
Thread.sleep(1000);
driver.findElement(By.xpath(".//*[@id='"+noOfItems+"3']/a[2]")).click();
Thread.sleep(1000);
}
public int getItemQty(String itemName){
HashMap<String,Integer> itemlist = getItemNamesAndQtyInRFO();
int qty = itemlist.get(itemName);
return qty;
}
/* public HashMap<String, Integer> getItemListAfterAddingItems(){
HashMap<String, Integer> itemList = getItemNamesAndQtyInRFO();
int noOfItems = getNoOfItems();
String tempKey = driver.findElement(By.xpath(".//*[@id='"+noOfItems+"']/td[2]")).getText();
String tempval = driver.findElement(By.xpath(".//*[@id='qty"+noOfItems+"']")).getAttribute("value");
int tempvalue = Integer.parseInt(tempval);
itemList.put(tempKey, tempvalue);
return itemList ;
}
*/
public void selectDeliveryTypeDropdown(String deliveryType){
Select select = new Select(deliveryDropdown);
select.selectByVisibleText(deliveryType);
}
public void selectPaymentTypeDropdown(String paymentType){
Select select = new Select(paymentDropdown);
select.selectByVisibleText(paymentType);
}
}
| true |
9ef51aac45fd662dfda706e750f398b5694572d4 | Java | BulkSecurityGeneratorProject/straps | /src/main/java/com/neowave/promaly/service/dto/ContactDTO.java | UTF-8 | 2,915 | 2.484375 | 2 | [] | no_license | package com.neowave.promaly.service.dto;
import java.io.Serializable;
import java.util.Objects;
/**
* A DTO for the Contact entity.
*/
public class ContactDTO implements Serializable {
private Long id;
private String firstName;
private String lastName;
private String email;
private String phonePrimary;
private String phoneSecondary;
private Long contactType;
private String version;
private Long companyId;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhonePrimary() {
return phonePrimary;
}
public void setPhonePrimary(String phonePrimary) {
this.phonePrimary = phonePrimary;
}
public String getPhoneSecondary() {
return phoneSecondary;
}
public void setPhoneSecondary(String phoneSecondary) {
this.phoneSecondary = phoneSecondary;
}
public Long getContactType() {
return contactType;
}
public void setContactType(Long contactType) {
this.contactType = contactType;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public Long getCompanyId() {
return companyId;
}
public void setCompanyId(Long companyId) {
this.companyId = companyId;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ContactDTO contactDTO = (ContactDTO) o;
if (contactDTO.getId() == null || getId() == null) {
return false;
}
return Objects.equals(getId(), contactDTO.getId());
}
@Override
public int hashCode() {
return Objects.hashCode(getId());
}
@Override
public String toString() {
return "ContactDTO{" +
"id=" + getId() +
", firstName='" + getFirstName() + "'" +
", lastName='" + getLastName() + "'" +
", email='" + getEmail() + "'" +
", phonePrimary='" + getPhonePrimary() + "'" +
", phoneSecondary='" + getPhoneSecondary() + "'" +
", contactType=" + getContactType() +
", version='" + getVersion() + "'" +
", company=" + getCompanyId() +
"}";
}
}
| true |
604b2f9cd402d613d6eba572ea49a0a967b936a4 | Java | prakhar4/learner | /java_learner_trash/class/point_line/line.java | UTF-8 | 572 | 3.328125 | 3 | [] | no_license | //package point_line;
public class line
{
public point start, end;
public line(point p1, point p2)
{
start=new point(p1);
end= new point(p2);
}
public line (int x1, int y1, int x2, int y2)
{
start= new point(x1,y1);
end= new point(x2,y2);
}
public double linelength()
{
return start.dist(end);
}
public void disp()
{
System.out.println("the line has "+start+" and "+ end);
}
}
| true |
9a80a93e565a44f6fd12418b27a715c07fd81b79 | Java | dstravis86/BankApp | /src/MySQLSource.java | UTF-8 | 3,031 | 2.9375 | 3 | [] | no_license | import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Date;
public class MySQLSource {
private Connection connect = null;
private Statement statement = null;
private final PreparedStatement preparedStatement = null;
private ResultSet resultSet = null;
public boolean isUserValid(String user, String password) throws Exception {
try {
// This will load the MySQL driver, each DB has its own driver
Class.forName("com.mysql.jdbc.Driver");
// Setup the connection with the DB
connect = DriverManager
.getConnection("jdbc:mysql://localhost:3306/mysql?zeroDate"
+ "TimeBehavior=convertToNull"
+ " [root on Default schema]");
// Statements allow to issue SQL queries to the database
statement = connect.createStatement();
// Result set get the result of the SQL query
resultSet = statement
.executeQuery("select count(*) as numberofrecords from table "
+ "where user = '" + user +"' "
+ "and password = '" + password + "'");
String records = resultSet.getString("numberofrecords");
writeResultSet(resultSet);
return false;
} catch (ClassNotFoundException | SQLException e) {
throw e;
} finally {
close();
}
}
private void writeResultSet(ResultSet resultSet) throws SQLException {
// ResultSet is initially before the first data set
while (resultSet.next()) {
// It is possible to get the columns via name
// also possible to get the columns via the column number
// which starts at 1
// e.g. resultSet.getSTring(2);
String user = resultSet.getString("myuser");
String website = resultSet.getString("webpage");
String summary = resultSet.getString("summary");
Date date = resultSet.getDate("datum");
String comment = resultSet.getString("comments");
System.out.println("User: " + user);
System.out.println("Website: " + website);
System.out.println("summary: " + summary);
System.out.println("Date: " + date);
System.out.println("Comment: " + comment);
}
}
// You need to close the resultSet
private void close() {
try {
if (resultSet != null) {
resultSet.close();
}
if (statement != null) {
statement.close();
}
if (connect != null) {
connect.close();
}
} catch (Exception e) {
}
}
}
| true |
e856fa3b4b781a54e4a8e9acdd61d5c85b8425c6 | Java | wagnerinacio16/rp4-fourzeta | /Coding/Desktop_and_Web/src/main/java/fourzeta/FourZetaApplication.java | UTF-8 | 483 | 1.6875 | 2 | [] | no_license | package fourzeta;
import java.io.IOException;
import java.text.ParseException;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
@SpringBootApplication()
public class FourZetaApplication {
public static void main(String[] args) throws ParseException, IOException {
SpringApplication.run(FourZetaApplication.class, args);
}
}
| true |
a1c660c7c8d845ffb876be79ad3d1f90af5a2839 | Java | Jonius7/Brewcraft | /src/main/java/redgear/brewcraft/effects/EffectImmunity.java | UTF-8 | 573 | 2.09375 | 2 | [] | no_license | package redgear.brewcraft.effects;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import redgear.brewcraft.plugins.core.AchievementPlugin;
public class EffectImmunity extends PotionExtension {
public EffectImmunity(int id) {
super("immunity", id, false, 0x9933CC);
setIconIndex(3, 0);
}
@Override
public void performEffect(EntityLivingBase living, int strength) {
if (living instanceof EntityPlayer && AchievementPlugin.immunity != null)
((EntityPlayer) living).addStat(AchievementPlugin.immunity, 1);
}
}
| true |
b88151647369440e4614a2591a8f0f00cae9b28c | Java | dudehs6726/mysite | /src/com/douzon/mysite/action/board/ListFormAction.java | UTF-8 | 1,394 | 2.1875 | 2 | [] | no_license | package com.douzon.mysite.action.board;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.douzon.mvc.action.Action;
import com.douzon.mvc.util.WebUtils;
import com.douzon.mysite.repository.BoardDao;
import com.douzon.mysite.vo.BoardVo;
public class ListFormAction implements Action {
@Override
public void excute(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
String page = request.getParameter("page");
String kwd = request.getParameter("kwd");
BoardVo vo = new BoardVo();
if(page != null)
{
vo.setPage(Integer.parseInt(page));
}else {
vo.setPage(1);
}
BoardDao dao = new BoardDao();
List<BoardVo> list = dao.getList(vo, kwd);
//데이터를 request 범위에 저장
request.setAttribute("list", list);
//page
dao.getPageList(vo, kwd); //총 글수
dao.makeBlock(vo, vo.getPage()); //선택한 페이지의 해당 리스트 1~5
dao.makeLastPageNum(vo); //마지막 페이지 계산
request.setAttribute("vo", vo);
request.setAttribute("kwd", kwd);
//forwarding
WebUtils.forward(request, response, "WEB-INF/views/board/list.jsp");
}
}
| true |
bbce82948ec6e17a68825a083f85897c1ef7608b | Java | Jino2/AssignmentOldBookSell | /src/BookSell/Admin.java | UTF-8 | 167 | 2.03125 | 2 | [] | no_license | package BookSell;
public class Admin extends User {
UserSystem userSystem;
public Admin(UserSystem us)
{
super("admin","nayana");
this.userSystem = us;
}
}
| true |
9b939632840cfd2bee37156414e239e5f65b91fc | Java | devkrzyzanowski/Butler.old | /NetBeans/jfxtras-8.0/jfxtras-common/src/main/java/jfxtras/scene/layout/responsivepane/Layout.java | UTF-8 | 2,295 | 2.59375 | 3 | [
"BSD-3-Clause"
] | permissive | package jfxtras.scene.layout.responsivepane;
import javafx.beans.DefaultProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.scene.Node;
/**
*
*/
@DefaultProperty("root")
public class Layout {
/**
* For FXML
*/
public Layout() {
}
/**
*
*/
public Layout(Size sizeAtLeast, Node root) {
setSizeAtLeast(sizeAtLeast);
setRoot(root);
}
/**
*
*/
public Layout(Size sizeAtLeast, Orientation orientation, Node root) {
setSizeAtLeast(sizeAtLeast);
setOrientation(orientation);
setRoot(root);
}
/** Root */
public ObjectProperty<Node> rootProperty() { return rootProperty; }
final private SimpleObjectProperty<Node> rootProperty = new SimpleObjectProperty<>(this, "root", null);
public Node getRoot() { return rootProperty.getValue(); }
public void setRoot(Node value) { rootProperty.setValue(value); }
public Layout withRoot(Node value) { setRoot(value); return this; }
/** sizeAtLeast */
public ObjectProperty<Size> sizeAtLeastProperty() { return sizeAtLeastProperty; }
final private SimpleObjectProperty<Size> sizeAtLeastProperty = new SimpleObjectProperty<>(this, "sizeAtLeast", Size.ZERO);
public Size getSizeAtLeast() { return sizeAtLeastProperty.getValue(); }
public void setSizeAtLeast(Size value) { sizeAtLeastProperty.setValue(value); }
public Layout withSizeAtLeast(Size value) { setSizeAtLeast(value); return this; }
/** Orientation */
public ObjectProperty<Orientation> orientationProperty() { return orientationProperty; }
final private SimpleObjectProperty<Orientation> orientationProperty = new SimpleObjectProperty<>(this, "orientation", null);
public Orientation getOrientation() { return orientationProperty.getValue(); }
public void setOrientation(Orientation value) { orientationProperty.setValue(value); }
public Layout withOrientation(Orientation value) { setOrientation(value); return this; }
public String describeSizeConstraints() {
return getSizeAtLeast() + (getOrientation() == null ? "" : "-" + getOrientation());
}
public String toString() {
return super.toString()
+ (getRoot() == null || getRoot().getId() == null ? "" : ", root-id=" + getRoot().getId())
+ (getRoot() == null? "" : ", root=" + getRoot())
;
}
} | true |
ddcb42d51bddec57f95d5f8566d9ff511be2e8c5 | Java | SteffenHeu/mzmine3 | /src/main/java/io/github/mzmine/modules/visualization/spectra/spectra_stack/pseudospectra/PseudoSpectrum.java | UTF-8 | 5,985 | 1.890625 | 2 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | /*
* Copyright (c) 2004-2022 The MZmine Development Team
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
package io.github.mzmine.modules.visualization.spectra.spectra_stack.pseudospectra;
import io.github.mzmine.datamodel.DataPoint;
import io.github.mzmine.datamodel.IsotopePattern;
import io.github.mzmine.datamodel.RawDataFile;
import io.github.mzmine.datamodel.features.Feature;
import io.github.mzmine.datamodel.features.FeatureListRow;
import io.github.mzmine.gui.chartbasics.gui.javafx.EChartViewer;
import io.github.mzmine.main.MZmineCore;
import io.github.mzmine.util.scans.ScanUtils;
import java.awt.Color;
import java.text.NumberFormat;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.plot.DatasetRenderingOrder;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.XYItemRenderer;
import org.jfree.chart.ui.RectangleInsets;
import org.jfree.data.xy.XYSeries;
public class PseudoSpectrum {
public static PseudoSpectrumDataSet createDataSet(FeatureListRow[] group, RawDataFile raw,
boolean sum) {
// data
PseudoSpectrumDataSet series = new PseudoSpectrumDataSet(true, "pseudo");
// add all isotopes as a second series:
XYSeries isoSeries = new XYSeries("Isotopes", true);
// raw isotopes in a different color
XYSeries rawIsoSeries = new XYSeries("Raw isotope pattern", true);
// for each row
for (FeatureListRow row : group) {
String annotation = null;
// sum -> heighest peak
if (sum) {
series.addDP(row.getAverageMZ(), row.getBestFeature().getHeight(), annotation);
} else {
Feature f = raw == null ? row.getBestFeature() : row.getFeature(raw);
if (f != null) {
series.addDP(f.getMZ(), f.getHeight(), null);
}
}
// add isotopes
IsotopePattern pattern = row.getBestIsotopePattern();
if (pattern != null) {
for (DataPoint dp : ScanUtils.extractDataPoints(pattern)) {
isoSeries.add(dp.getMZ(), dp.getIntensity());
}
}
}
series.addSeries(isoSeries);
series.addSeries(rawIsoSeries);
return series;
}
public static EChartViewer createChartViewer(FeatureListRow[] group, RawDataFile raw, boolean sum,
String title) {
PseudoSpectrumDataSet data = createDataSet(group, raw, sum);
if (data == null) {
return null;
}
JFreeChart chart = createChart(data, raw, sum, title);
if (chart != null) {
EChartViewer pn = new EChartViewer(chart);
XYItemRenderer renderer = chart.getXYPlot().getRenderer();
PseudoSpectraItemLabelGenerator labelGenerator = new PseudoSpectraItemLabelGenerator(pn);
renderer.setDefaultItemLabelsVisible(true);
renderer.setDefaultItemLabelPaint(Color.BLACK);
renderer.setSeriesItemLabelGenerator(0, labelGenerator);
return pn;
}
return null;
}
public static JFreeChart createChart(PseudoSpectrumDataSet dataset, RawDataFile raw, boolean sum,
String title) {
//
JFreeChart chart = ChartFactory.createXYLineChart(title, // title
"m/z", // x-axis label
"Intensity", // y-axis label
dataset, // data set
PlotOrientation.VERTICAL, // orientation
true, // isotopeFlag, // create legend?
true, // generate tooltips?
false // generate URLs?
);
chart.setBackgroundPaint(Color.white);
chart.getTitle().setVisible(false);
// set the plot properties
XYPlot plot = chart.getXYPlot();
plot.setBackgroundPaint(Color.white);
plot.setAxisOffset(RectangleInsets.ZERO_INSETS);
// set rendering order
plot.setDatasetRenderingOrder(DatasetRenderingOrder.FORWARD);
// set crosshair (selection) properties
plot.setDomainCrosshairVisible(false);
plot.setRangeCrosshairVisible(false);
NumberFormat mzFormat = MZmineCore.getConfiguration().getMZFormat();
NumberFormat intensityFormat = MZmineCore.getConfiguration().getIntensityFormat();
// set the X axis (retention time) properties
NumberAxis xAxis = (NumberAxis) plot.getDomainAxis();
xAxis.setNumberFormatOverride(mzFormat);
xAxis.setUpperMargin(0.08);
xAxis.setLowerMargin(0.00);
xAxis.setTickLabelInsets(new RectangleInsets(0, 0, 20, 20));
xAxis.setAutoRangeIncludesZero(true);
xAxis.setMinorTickCount(5);
// set the Y axis (intensity) properties
NumberAxis yAxis = (NumberAxis) plot.getRangeAxis();
yAxis.setNumberFormatOverride(intensityFormat);
yAxis.setUpperMargin(0.20);
PseudoSpectraRenderer renderer = new PseudoSpectraRenderer(Color.BLACK, false);
plot.setRenderer(0, renderer);
plot.setRenderer(1, renderer);
plot.setRenderer(2, renderer);
renderer.setSeriesVisibleInLegend(1, false);
renderer.setSeriesPaint(2, Color.ORANGE);
//
return chart;
}
}
| true |
c28a4c06682d197208a8641582c09ca95b916cb0 | Java | MariyaBystrova/Bystrova_Totalizator | /Totalizator/src/main/java/by/tr/totalizator/command/impl/user/GoToMakeBetCommand.java | UTF-8 | 4,008 | 2.171875 | 2 | [] | no_license | package by.tr.totalizator.command.impl.user;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import by.tr.totalizator.command.Command;
import by.tr.totalizator.controller.PageName;
import by.tr.totalizator.entity.bean.Match;
import by.tr.totalizator.entity.bean.User;
import by.tr.totalizator.service.MatchService;
import by.tr.totalizator.service.exception.ServiceException;
import by.tr.totalizator.service.factory.ServiceFactory;
import by.tr.totalizator.tag.bean.JSPListBean;
import by.tr.totalizator.tag.bean.JspMapBean;
/**
* Implements {@link by.tr.totalizator.command.Command} for a command to go to
* the page for making a bet. Available for "user".
*
* @author Mariya Bystrova
*/
public class GoToMakeBetCommand implements Command {
private final static Logger logger = LogManager.getLogger(GoToMakeBetCommand.class.getName());
private final static String CURRENT_URL_ATTR = "currentUrl";
private final static String CURRENT_URL = "Controller?command=go-to-make-bet";
private final static String USER = "user";
private final static String RESULT = "result";
private final static String AMOUNT = "amount";
private final static String MAP = "map";
private final static String LIST = "list";
private final static String COUPON = "coupon";
private final static String AMP = "&";
private final static String EQ = "=";
/**
* Provides the service of forming the page to go to. Checks the session and
* user's privileges to go to this page.
* <p>
* Forms the request object with the list of matches for the current coupon,
* the Map of chosen results and entered money amount.
* </p>
*
* @return {@link by.tr.totalizator.controller.PageName#USER_PAGE_MAKE_BET},
* if the role of authorized person is "user" or
* {@link by.tr.totalizator.controller.PageName#INDEX_PAGE}, if
* either the session time has expired or an authorized user's role
* is not "user".
* <p>
* Might return
* {@link by.tr.totalizator.controller.PageName#ERROR_PAGE} in case
* of {@link by.tr.totalizator.service.exception.ServiceException}.
* </p>
*
* @see by.tr.totalizator.command.Command
*/
@Override
public String execute(HttpServletRequest request, HttpServletResponse response) {
if (request.getSession(false) == null) {
return PageName.INDEX_PAGE;
}
String url = CURRENT_URL;
for (int i = 1; i <= 15; i++) {
url = url.concat(AMP + RESULT + new Integer(i).toString() + EQ
+ request.getParameter(RESULT + new Integer(i).toString()));
}
url = url.concat(AMP + AMOUNT + EQ + request.getParameter(AMOUNT));
request.getSession(false).setAttribute(CURRENT_URL_ATTR, url);
String page;
User user = (User) request.getSession(false).getAttribute(USER);
if (user != null && user.getRole().equals(USER)) {
Map<String, String> map = new HashMap<String, String>();
for (int i = 1; i <= 15; i++) {
map.put(RESULT + new Integer(i).toString(), request.getParameter(RESULT + new Integer(i).toString()));
}
JspMapBean mapBean = new JspMapBean();
mapBean.setMap(map);
request.setAttribute(MAP, mapBean);
request.setAttribute(AMOUNT, Integer.parseInt(request.getParameter(AMOUNT)));
ServiceFactory factory = ServiceFactory.getInstance();
MatchService matchService = factory.getMatchService();
try {
List<Match> list = matchService.getCurrentCupon();
if (list != null && !list.isEmpty()) {
JSPListBean jsp = new JSPListBean(list);
request.setAttribute(LIST, jsp);
request.setAttribute(COUPON, list.get(0).getCouponId());
}
} catch (ServiceException e) {
logger.error(e);
page = PageName.ERROR_PAGE;
}
page = PageName.USER_PAGE_MAKE_BET;
} else {
page = PageName.INDEX_PAGE;
}
return page;
}
}
| true |
37df56a430eda8abaf01481b9ea833da2180f9fb | Java | Jeppehel/designEksamen | /3.SemesterDesignProjekt/src/main/java/com/example/demo/controller/AdminController.java | UTF-8 | 326 | 1.726563 | 2 | [] | no_license | package com.example.demo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class AdminController {
@RequestMapping(value = "/admin/control")
public String siteControl() {
return "admin/SiteControlAdmin";
}
}
| true |
941491f2f2ab2432ec23a14ac116e106e5132a12 | Java | lehrig/m2m-quality | /de.upb.m2m.quality.model/src/de/upb/m2m/quality/model/QualityMetrics/impl/MetricsImpl.java | UTF-8 | 9,103 | 1.570313 | 2 | [] | no_license | /**
* <copyright>
* </copyright>
*
* $Id$
*/
package de.upb.m2m.quality.model.QualityMetrics.impl;
import de.upb.m2m.quality.model.QualityMetrics.AggregatedIntegerMetric;
import de.upb.m2m.quality.model.QualityMetrics.AggregatedRealMetric;
import de.upb.m2m.quality.model.QualityMetrics.Metrics;
import de.upb.m2m.quality.model.QualityMetrics.QualityMetricsPackage;
import de.upb.m2m.quality.model.QualityMetrics.SimpleMetric;
import java.util.Collection;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.NotificationChain;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.eclipse.emf.ecore.impl.EObjectImpl;
import org.eclipse.emf.ecore.util.EObjectContainmentEList;
import org.eclipse.emf.ecore.util.InternalEList;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Metrics</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* <ul>
* <li>{@link de.upb.m2m.quality.model.QualityMetrics.impl.MetricsImpl#getSimpleMetrics <em>Simple Metrics</em>}</li>
* <li>{@link de.upb.m2m.quality.model.QualityMetrics.impl.MetricsImpl#getAggregatedIntegerMetrics <em>Aggregated Integer Metrics</em>}</li>
* <li>{@link de.upb.m2m.quality.model.QualityMetrics.impl.MetricsImpl#getAggregatedRealMetrics <em>Aggregated Real Metrics</em>}</li>
* <li>{@link de.upb.m2m.quality.model.QualityMetrics.impl.MetricsImpl#getTrafoName <em>Trafo Name</em>}</li>
* </ul>
* </p>
*
* @generated
*/
public class MetricsImpl extends EObjectImpl implements Metrics {
/**
* The cached value of the '{@link #getSimpleMetrics() <em>Simple Metrics</em>}' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getSimpleMetrics()
* @generated
* @ordered
*/
protected EList<SimpleMetric> simpleMetrics;
/**
* The cached value of the '{@link #getAggregatedIntegerMetrics() <em>Aggregated Integer Metrics</em>}' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getAggregatedIntegerMetrics()
* @generated
* @ordered
*/
protected EList<AggregatedIntegerMetric> aggregatedIntegerMetrics;
/**
* The cached value of the '{@link #getAggregatedRealMetrics() <em>Aggregated Real Metrics</em>}' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getAggregatedRealMetrics()
* @generated
* @ordered
*/
protected EList<AggregatedRealMetric> aggregatedRealMetrics;
/**
* The default value of the '{@link #getTrafoName() <em>Trafo Name</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getTrafoName()
* @generated
* @ordered
*/
protected static final String TRAFO_NAME_EDEFAULT = null;
/**
* The cached value of the '{@link #getTrafoName() <em>Trafo Name</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getTrafoName()
* @generated
* @ordered
*/
protected String trafoName = TRAFO_NAME_EDEFAULT;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected MetricsImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return QualityMetricsPackage.Literals.METRICS;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<SimpleMetric> getSimpleMetrics() {
if (simpleMetrics == null) {
simpleMetrics = new EObjectContainmentEList<SimpleMetric>(SimpleMetric.class, this, QualityMetricsPackage.METRICS__SIMPLE_METRICS);
}
return simpleMetrics;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<AggregatedIntegerMetric> getAggregatedIntegerMetrics() {
if (aggregatedIntegerMetrics == null) {
aggregatedIntegerMetrics = new EObjectContainmentEList<AggregatedIntegerMetric>(AggregatedIntegerMetric.class, this, QualityMetricsPackage.METRICS__AGGREGATED_INTEGER_METRICS);
}
return aggregatedIntegerMetrics;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<AggregatedRealMetric> getAggregatedRealMetrics() {
if (aggregatedRealMetrics == null) {
aggregatedRealMetrics = new EObjectContainmentEList<AggregatedRealMetric>(AggregatedRealMetric.class, this, QualityMetricsPackage.METRICS__AGGREGATED_REAL_METRICS);
}
return aggregatedRealMetrics;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getTrafoName() {
return trafoName;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setTrafoName(String newTrafoName) {
String oldTrafoName = trafoName;
trafoName = newTrafoName;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, QualityMetricsPackage.METRICS__TRAFO_NAME, oldTrafoName, trafoName));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
switch (featureID) {
case QualityMetricsPackage.METRICS__SIMPLE_METRICS:
return ((InternalEList<?>)getSimpleMetrics()).basicRemove(otherEnd, msgs);
case QualityMetricsPackage.METRICS__AGGREGATED_INTEGER_METRICS:
return ((InternalEList<?>)getAggregatedIntegerMetrics()).basicRemove(otherEnd, msgs);
case QualityMetricsPackage.METRICS__AGGREGATED_REAL_METRICS:
return ((InternalEList<?>)getAggregatedRealMetrics()).basicRemove(otherEnd, msgs);
}
return super.eInverseRemove(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case QualityMetricsPackage.METRICS__SIMPLE_METRICS:
return getSimpleMetrics();
case QualityMetricsPackage.METRICS__AGGREGATED_INTEGER_METRICS:
return getAggregatedIntegerMetrics();
case QualityMetricsPackage.METRICS__AGGREGATED_REAL_METRICS:
return getAggregatedRealMetrics();
case QualityMetricsPackage.METRICS__TRAFO_NAME:
return getTrafoName();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@SuppressWarnings("unchecked")
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case QualityMetricsPackage.METRICS__SIMPLE_METRICS:
getSimpleMetrics().clear();
getSimpleMetrics().addAll((Collection<? extends SimpleMetric>)newValue);
return;
case QualityMetricsPackage.METRICS__AGGREGATED_INTEGER_METRICS:
getAggregatedIntegerMetrics().clear();
getAggregatedIntegerMetrics().addAll((Collection<? extends AggregatedIntegerMetric>)newValue);
return;
case QualityMetricsPackage.METRICS__AGGREGATED_REAL_METRICS:
getAggregatedRealMetrics().clear();
getAggregatedRealMetrics().addAll((Collection<? extends AggregatedRealMetric>)newValue);
return;
case QualityMetricsPackage.METRICS__TRAFO_NAME:
setTrafoName((String)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case QualityMetricsPackage.METRICS__SIMPLE_METRICS:
getSimpleMetrics().clear();
return;
case QualityMetricsPackage.METRICS__AGGREGATED_INTEGER_METRICS:
getAggregatedIntegerMetrics().clear();
return;
case QualityMetricsPackage.METRICS__AGGREGATED_REAL_METRICS:
getAggregatedRealMetrics().clear();
return;
case QualityMetricsPackage.METRICS__TRAFO_NAME:
setTrafoName(TRAFO_NAME_EDEFAULT);
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case QualityMetricsPackage.METRICS__SIMPLE_METRICS:
return simpleMetrics != null && !simpleMetrics.isEmpty();
case QualityMetricsPackage.METRICS__AGGREGATED_INTEGER_METRICS:
return aggregatedIntegerMetrics != null && !aggregatedIntegerMetrics.isEmpty();
case QualityMetricsPackage.METRICS__AGGREGATED_REAL_METRICS:
return aggregatedRealMetrics != null && !aggregatedRealMetrics.isEmpty();
case QualityMetricsPackage.METRICS__TRAFO_NAME:
return TRAFO_NAME_EDEFAULT == null ? trafoName != null : !TRAFO_NAME_EDEFAULT.equals(trafoName);
}
return super.eIsSet(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String toString() {
if (eIsProxy()) return super.toString();
StringBuffer result = new StringBuffer(super.toString());
result.append(" (TrafoName: ");
result.append(trafoName);
result.append(')');
return result.toString();
}
} //MetricsImpl
| true |
bff0a57cbfe6a3747ff9a98f17bba3f547cd0958 | Java | raycraft/MyBigApp_Discuz_Android | /libs/ClanBase/src/com/youzu/taobao/base/json/mobclickagent/MobclickAgentConfig.java | UTF-8 | 736 | 1.976563 | 2 | [
"Apache-2.0"
] | permissive | package com.youzu.taobao.base.json.mobclickagent;
import com.youzu.android.framework.json.annotation.JSONField;
/**
* Created by Zhao on 15/6/2.
*/
public class MobclickAgentConfig {
private int policy;
private int duration;
private String apiPath;
public int getPolicy() {
return policy;
}
public void setPolicy(int policy) {
this.policy = policy;
}
public int getDuration() {
return duration;
}
public void setDuration(int duration) {
this.duration = duration;
}
public String getApiPath() {
return apiPath;
}
@JSONField(name = "api_path")
public void setApiPath(String apiPath) {
this.apiPath = apiPath;
}
}
| true |
d2bdb37fcd23b32f74ea52775b805001e52a8fd3 | Java | johnsonmoon/MediaFormatter | /src/main/java/xuyihao/formatter/ui/executor/GIFExecutor.java | UTF-8 | 4,135 | 2.59375 | 3 | [] | no_license | package xuyihao.formatter.ui.executor;
import java.io.File;
import javafx.scene.control.TextField;
import xuyihao.formatter.invoker.executer.Executor;
import xuyihao.formatter.invoker.progress.Progress;
import xuyihao.formatter.ui.window.information.InformationWindow;
import xuyihao.formatter.ui.window.warning.WarningWindow;
/**
* GIF制作
*
* @Author Xuyh created at 2016年11月14日 上午11:09:09
*
*/
public class GIFExecutor {
private TextField main_text_field_inputFile;
private TextField main_text_field_outputFilePath;
private TextField main_tab_makeGIF_text_field_beginTime;
private TextField main_tab_makeGIF_text_field_lastTime;
private TextField main_tab_makeGIF_text_field_sizeX;
private TextField main_tab_makeGIF_text_field_sizeY;
private TextField main_tab_makeGIF_text_field_outputFileName;
public GIFExecutor(TextField main_text_field_inputFile, TextField main_text_field_outputFilePath,
TextField main_tab_makeGIF_text_field_beginTime, TextField main_tab_makeGIF_text_field_lastTime,
TextField main_tab_makeGIF_text_field_sizeX, TextField main_tab_makeGIF_text_field_sizeY,
TextField main_tab_makeGIF_text_field_outputFileName) {
this.main_text_field_inputFile = main_text_field_inputFile;
this.main_text_field_outputFilePath = main_text_field_outputFilePath;
this.main_tab_makeGIF_text_field_beginTime = main_tab_makeGIF_text_field_beginTime;
this.main_tab_makeGIF_text_field_lastTime = main_tab_makeGIF_text_field_lastTime;
this.main_tab_makeGIF_text_field_sizeX = main_tab_makeGIF_text_field_sizeX;
this.main_tab_makeGIF_text_field_sizeY = main_tab_makeGIF_text_field_sizeY;
this.main_tab_makeGIF_text_field_outputFileName = main_tab_makeGIF_text_field_outputFileName;
}
private String inputFile = "";
private String outputPath = "";
private String beginTime = "";
private String lastTime = "";
private String sizeX = "";
private String sizeY = "";
private String outputFileName = "";
private void refresh() {
inputFile = main_text_field_inputFile.getText().trim();
outputPath = main_text_field_outputFilePath.getText().trim();
beginTime = main_tab_makeGIF_text_field_beginTime.getText().trim();
lastTime = main_tab_makeGIF_text_field_lastTime.getText().trim();
sizeX = main_tab_makeGIF_text_field_sizeX.getText().trim();
sizeY = main_tab_makeGIF_text_field_sizeY.getText().trim();
outputFileName = main_tab_makeGIF_text_field_outputFileName.getText().trim();
}
/**
* 制作GIF
*/
public void makeGIF() {
refresh();
if (inputFile == null || inputFile.equals("")) {
new WarningWindow("inputFile is null !").show();
} else {
if (outputPath == null || outputPath.equals("")) {
new WarningWindow("outputPath is null !").show();
} else {
if (beginTime == null || beginTime.equals("")) {
new WarningWindow("beginTime is null !").show();
} else {
if (lastTime == null || lastTime.equals("")) {
new WarningWindow("lastTime is null !").show();
} else {
if (sizeX == null || sizeX.equals("")) {
new WarningWindow("sizeX is null !").show();
} else {
if (sizeY == null || sizeY.equals("")) {
new WarningWindow("sizeY is null !").show();
} else {
if (outputFileName == null || outputFileName.equals("")) {
new WarningWindow("outputFileName is null !").show();
} else {
final Progress progress = Executor.generateGIFImage(inputFile, Integer.parseInt(beginTime),
Integer.parseInt(lastTime), Integer.parseInt(sizeX), Integer.parseInt(sizeY),
outputPath + File.separator + outputFileName + ".gif");
final InformationWindow informationWindow = new InformationWindow("生成GIF中...", 18.0, progress);
informationWindow.show();
informationWindow.appendInformationMessage("\r\nCommand--> \r\n#" + progress.getCommand());
new Thread(new Runnable() {
public void run() {
progress.waitFor();
informationWindow.appendInformationMessage("\r\n执行完成!");
}
}).start();
}
}
}
}
}
}
}
}
}
| true |
44d23c2168566adb22dcef8cf3558025d6d364d1 | Java | ZhaoChaoqun/LeetCode | /src/leetcode/_200_3.java | UTF-8 | 888 | 3.109375 | 3 | [] | no_license | package leetcode;
public class _200_3 {
int m, n;
public int numIslands(char[][] grid) {
m = grid.length;
if(m == 0) return 0;
n = grid[0].length;
int result = 0;
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
if(grid[i][j] == '1') {
recursive(grid, i, j);
result++;
}
}
}
return result;
}
private void recursive(char[][] board, int i, int j) {
board[i][j] = '0';
if(i > 0 && board[i-1][j] == '1')
recursive(board, i-1, j);
if(j > 0 && board[i][j-1] == '1')
recursive(board, i, j-1);
if(i + 1 < m && board[i+1][j] == '1')
recursive(board, i+1, j);
if(j + 1 < n && board[i][j+1] == '1')
recursive(board, i, j+1);
}
}
| true |
5b35b5a910305672d9a73d9c4b8ed5b40c21a51c | Java | gustavo-aguiar01/PO2021 | /woo-core/src/woo/exceptions/UnknownTransactionException.java | UTF-8 | 507 | 2.609375 | 3 | [] | no_license | package woo.exceptions;
/** Exception for unknown transaction keys. */
public class UnknownTransactionException extends Exception {
/** Serial number for serialization. */
private static final long serialVersionUID = 202009192008L;
/** Unknown key. */
private int _key;
/** @param key Unknown key to report. */
public UnknownTransactionException(int key) {
_key = key;
}
/**
* @return the invalid transaction key.
*/
public int getTransactionKey() {
return _key;
}
}
| true |
ae5d2478f7bd1a7ef98d1e5259f1105d8d44f452 | Java | adrfrank/ProyectoTSOA | /sistemaDistribuido/src/sistemaDistribuido/sistema/rpc/modoUsuario/ProcesoServidor.java | UTF-8 | 4,582 | 2.5625 | 3 | [] | no_license | /*
* Laura Teresa García López 212354614
* Sección: D05
* Practica Java #3
*/
package sistemaDistribuido.sistema.rpc.modoUsuario;
import sistemaDistribuido.sistema.rpc.modoMonitor.RPC; //para pr�ctica 4
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.logging.Level;
import java.util.logging.Logger;
import sistemaDistribuido.sistema.clienteServidor.modoMonitor.Nucleo;
import sistemaDistribuido.sistema.clienteServidor.modoUsuario.Proceso;
import sistemaDistribuido.util.Escribano;
/**
*
*/
public class ProcesoServidor extends Proceso{
private LibreriaServidor ls; //para pr�ctica 3
/**
*
*/
private byte[] solServidor=new byte[1024];
private byte[] respServidor = new byte[1024];
public ProcesoServidor(Escribano esc){
super(esc);
ls=new LibreriaServidor(esc); //para pr�ctica 3
start();
}
/**
* Resguardo del servidor
*/
public void run(){
imprimeln("Proceso servidor en ejecucion.");
CrearAsa asa = null;
try {
asa = new CrearAsa(InetAddress.getLocalHost().getHostAddress(),dameID());
} catch (UnknownHostException ex) {
Logger.getLogger(ProcesoServidor.class.getName()).log(Level.SEVERE, null, ex);
}
int idUnico=RPC.exportarInterfaz("FileServer", "3.1", asa); //para pr�ctica 4
while(continuar()){
imprimeln("Invocando a receive.");
Nucleo.receive(dameID(),solServidor);
imprimeln("Procesando petición recibida del cliente");
Desempaquetar();
Nucleo.send(solServidor[0],respServidor);
}
RPC.deregistrarInterfaz("FileServer", "3.1", idUnico); //para pr�ctica 4
}
private void Desempaquetar() {
int codop,param,resul;
int [] parametros, resultado;
codop= solServidor[8];
switch(codop){
case 0:
param= ObtenerI(solServidor);
resul=ls.cuadrado(param);
Empaqueta(resul,10);
break;
case 1:
parametros = ObtenerP(solServidor);
resultado = ls.ordena(parametros);
Empaqueta(resultado);
break;
case 2:
parametros = ObtenerP(solServidor);
resul = ls.promedio(parametros);
Empaqueta(resul,10);
break;
case 3:
param= ObtenerI(solServidor);
resul=ls.raiz(param);
Empaqueta(resul,10);
break;
}
}
private int ObtenerI(byte[] a){
int numero= a[13];
numero= (numero<<24);
numero =(numero|(a[12]&0x00FF)<<16);
numero =(numero|(a[11]&0x00FF)<<8);
numero =(numero|(a[10]&0x00FF));
// System.out.println("el numeroooo: " +numero);
return numero;
}
private void Empaqueta(int resul, int i) {
respServidor[i] = (byte)resul;
respServidor[i+1] = (byte)(resul>>>8);
respServidor[i+2] = (byte)(resul>>>16);
respServidor[i+3] = (byte)(resul>>>24);
//System.out.println(Arrays.toString(respServidor));
}
private int[] ObtenerP(byte[] solServidor) {
int cuantos=solServidor[9];
int num=(cuantos*4)+9;
//System.out.println("CUANTOS: "+ cuantos+" num: "+num);
int [] parametros= new int [cuantos];
for(int i =0; i<cuantos;i++){
int numero= solServidor[num];
numero= (numero<<24);
num--;
numero =(numero|(solServidor[num]&0x00FF)<<16);
num--;
numero =(numero|(solServidor[num]&0x00FF)<<8);
num--;
numero =(numero|(solServidor[num]&0x00FF));
num--;
parametros[i]= numero;
}
//System.out.println("DEL SERVIDOR"+Arrays.toString(parametros));
return parametros;
}
private void Empaqueta(int[] resultado) {
int inicio = 10;
int cuantos=solServidor[9];
for(int i =0; i<cuantos;i++){
respServidor[inicio] = (byte)resultado[i];
inicio++;
respServidor[inicio] = (byte)(resultado[i]>>>8);
inicio++;
respServidor[inicio] = (byte)(resultado[i]>>>16);
inicio++;
respServidor[inicio] = (byte)(resultado[i]>>>24);
inicio++;
}
}
}
| true |
6f22106b4b3503018e698e850d490c877daba5ba | Java | clover34/ssm3 | /delightstouring/src/test/java/com/etc/delightstouring/utils/VerifyUtilTest.java | UTF-8 | 471 | 2.25 | 2 | [] | no_license | package com.etc.delightstouring.utils;
import org.junit.Test;
/**
* @ClassName VerifyUtilTest
* @Description TODO
* @Author Administrator
* @Date 20/10/28 21:57
* @Version 1.0
**/
public class VerifyUtilTest {
@Test
public void test(){
System.out.println("VerifyUtil.verifyPhone(\"1760899285\") = " + VerifyUtil.verifyPhone("17608994857"));
System.out.println("VerifyUtil.verifyPhone(\"123\") = " + VerifyUtil.verifyPhone("123"));
}
}
| true |
1be678f5c6ba3df641d2634d18fe1d08d324661a | Java | xiayifan888/PropertyApp | /PropertyApp/app/src/main/java/com/glory/bianyitong/bean/BannerInfo.java | UTF-8 | 2,513 | 2.296875 | 2 | [] | no_license | package com.glory.bianyitong.bean;
import java.util.List;
/**
* Created by lucy on 2016/11/10.
*/
public class BannerInfo {
/**
* Success : true
* ApiName : ImgList
* Msg : 成功
* ResultData : [{"Img_ID":1,"Img_Type":1,"Img_URL":"Update/Banner/1.jpg","Img_Link":"http://www.123.com"},{"Img_ID":1,"Img_Type":1,"Img_URL":"Update/Banner/1.jpg","Img_Link":"http://www.123.com"}]
* RowCount : 10
* ErrNum : 0
*/
private boolean Success;
private String ApiName;
private String Msg;
private int RowCount;
private int ErrNum;
/**
* Img_ID : 1
* Img_Type : 1
* Img_URL : Update/Banner/1.jpg
* Img_Link : http://www.123.com
*/
private List<ResultDataBean> ResultData;
public boolean isSuccess() {
return Success;
}
public void setSuccess(boolean Success) {
this.Success = Success;
}
public String getApiName() {
return ApiName;
}
public void setApiName(String ApiName) {
this.ApiName = ApiName;
}
public String getMsg() {
return Msg;
}
public void setMsg(String Msg) {
this.Msg = Msg;
}
public int getRowCount() {
return RowCount;
}
public void setRowCount(int RowCount) {
this.RowCount = RowCount;
}
public int getErrNum() {
return ErrNum;
}
public void setErrNum(int ErrNum) {
this.ErrNum = ErrNum;
}
public List<ResultDataBean> getResultData() {
return ResultData;
}
public void setResultData(List<ResultDataBean> ResultData) {
this.ResultData = ResultData;
}
public static class ResultDataBean {
private int Img_ID;
private int Img_Type;
private String Img_URL;
private String Img_Link;
public int getImg_ID() {
return Img_ID;
}
public void setImg_ID(int Img_ID) {
this.Img_ID = Img_ID;
}
public int getImg_Type() {
return Img_Type;
}
public void setImg_Type(int Img_Type) {
this.Img_Type = Img_Type;
}
public String getImg_URL() {
return Img_URL;
}
public void setImg_URL(String Img_URL) {
this.Img_URL = Img_URL;
}
public String getImg_Link() {
return Img_Link;
}
public void setImg_Link(String Img_Link) {
this.Img_Link = Img_Link;
}
}
}
| true |
9931d9ab9267b9da7ce16de686aee910622f5d27 | Java | Veziik/URLScanner | /src/searchTool/SearchTool.java | UTF-8 | 30,823 | 2.34375 | 2 | [] | no_license | package searchTool;
import java.util.*;
import java.util.regex.*;
import java.io.*;
import java.lang.StringBuilder;
import java.lang.management.*;
import java.net.*;
import javax.management.*;
import searchTool.Webpage;
public class SearchTool {
private static Date lastTimePaused = null;
private int rootDepth = 0;
private ArrayList<Webpage> next = new ArrayList<Webpage>();
private ArrayList<Webpage> visited = new ArrayList<Webpage>();
private HashSet<Webpage> container = new HashSet<Webpage>();
public HashMap<Integer,HashSet<Webpage>> mapPagesByStatus = new HashMap<Integer,HashSet<Webpage>>();
public HashMap<Webpage,HashSet<Webpage>> map404ParentToChildren = new HashMap<Webpage,HashSet<Webpage>>();
public HashMap<Webpage,HashSet<Webpage>> map404ChildToParents = new HashMap<Webpage,HashSet<Webpage>>();
public HashMap<String,HashSet<Webpage>> mapFileTypeToURL = new HashMap<String,HashSet<Webpage>>();
public HashMap<Webpage,HashSet<ArrayList<Webpage>>> mapParentTo404Trace = new HashMap<Webpage,HashSet<ArrayList<Webpage>>>();
private HashSet<String> setOfUniqueDomainNames = new HashSet<String>();
private HashMap<Webpage ,String> problemsByPatterns = new HashMap<Webpage , String>();
//Problems by patterns divides the 404 problems by the first folder in their path, note that the page that gives the 404 is given a folder, not the parent that links to it
/**
* Initiates a SearchTool object with only one starting website
* @param root
* @param url
* @throws IOException
*/
public SearchTool( String root, String url ) throws IOException {
if(!root.equals("DEBUG")){
testPath();
}
next.add(new Webpage(url));
container.add(next.get(next.size()-1));
next.get(next.size()-1).depth = (++rootDepth)+"";
MyDesignTimePatterns.AllowedDomainNames += " , " + next.get(next.size()-1).url.getHost();
}
/**
* Tests root path given by user to assure validity and sets up folders for
* printed data
* @throws IOException
*/
public void testPath() throws IOException{
File dir = new File(MyRunTimeConstants.RootPath),
dir200 = new File(MyDesignTimePatterns.dir200s),
dir404 = new File(MyDesignTimePatterns.dir404s),
dir400 = new File(MyDesignTimePatterns.dir4xxNot404s),
dir300 = new File(MyDesignTimePatterns.dir300s),
dirNot200 = new File(MyDesignTimePatterns.dirNot200s),
masterDir = new File(MyDesignTimePatterns.dirMaster),
dumpDirectory = new File(MyDesignTimePatterns.dirDump),
dirDotDot = new File(MyDesignTimePatterns.dirDotDot),
dirProblemsByPatterns = new File(MyDesignTimePatterns.dirProblemsByPatterns),
dirProblems = new File(MyDesignTimePatterns.dirProblems),
testFile;
PrintWriter writer;
FileReader reader;
BufferedReader bReader;
if(dir.exists()){
if(!masterDir.exists())
masterDir.mkdir();
if(!dumpDirectory.exists())
dumpDirectory.mkdir();
if(!dirProblems.exists())
dirProblems.mkdir();
if(!dirProblemsByPatterns.exists())
dirProblemsByPatterns.mkdir();
if(!dir404.exists())
dir404.mkdir();
if(!dir400.exists())
dir400.mkdir();
if(!dir300.exists())
dir300.mkdir();
if(!dir200.exists())
dir200.mkdir();
if(!dirNot200.exists())
dirNot200.mkdir();
if(!dirDotDot.exists())
dirDotDot.mkdir();
} else{
dir.mkdirs();
dirProblems.mkdir();
dirProblemsByPatterns.mkdir();
masterDir.mkdir();
dumpDirectory.mkdir();
dir404.mkdir();
dir400.mkdir();
dir300.mkdir();
dir200.mkdir();
dirNot200.mkdir();
dirDotDot.mkdir();
}
testFile = new File(dumpDirectory+"\\test.txt");
writer = new PrintWriter(dumpDirectory+"\\test.txt", "UTF-8");
writer.println("testing");
writer.close();
reader = new FileReader(dumpDirectory+"\\test.txt");
bReader = new BufferedReader(reader);
bReader.readLine();
bReader.close();
reader.close();
testFile.delete();
}
public HashMap<Webpage ,String> getPatternMap(){
return problemsByPatterns;
}
/**
* @return the ArrayList<Webpage> next
*/
public ArrayList<Webpage> getNext(){
return next;
}
/**
* @return the ArrayList<Webpage> visited
*/
public ArrayList<Webpage> getVisited(){
return visited;
}
/**
* Takes the page at next.get(0) and checks properties like content type, response code
* If the webpage being accessed returns any code 300+, the method sets the groundwork for
* immediately accessing the redirected page, or handles reallocation of data if the redirected page
* was already checked
* @return the webpage that was accessed
* @throws IOException
*/
public Webpage gatherPreliminaryInformationAboutNextWebpageInQueue(){
HttpURLConnection connection;
Webpage newWebpage = null, redirectedPage;
InetAddress address;
boolean excludeThisURL = false;
newWebpage = next.get(0);
next.remove(0);
MyDesignTimePatterns.appendToTextFile(newWebpage.url.toString(), MyDesignTimePatterns.processFile);
if(MyRunTimeConstants.shouldWeExcludeCertainPatterns){
checkForAnyExcludedPatterns(newWebpage);
}
if(excludeThisURL){
MyDesignTimePatterns.appendToTextFile("Previous Link Excluded", MyDesignTimePatterns.processFile);
}
try {
if(!visited.contains(newWebpage) && !excludeThisURL){
address = InetAddress.getByName(newWebpage.url.getHost());
connection = (HttpURLConnection)newWebpage.url.openConnection();
connection.setConnectTimeout(MyDesignTimePatterns.webpageAccessTimeoutPeriod);
connection.setRequestMethod("GET");
connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.1.2) Gecko/20090729 Firefox/3.5.2 (.NET CLR 3.5.30729)");
connection.connect();
newWebpage.status = connection.getResponseCode();
newWebpage.IPAddress = address.getHostAddress();
if(newWebpage.status == 404 && newWebpage.isRelative && newWebpage.relativeURL.contains("//"))
newWebpage.relativeURL += "---Possible mispelling of URL on parent page---";
newWebpage.contentType = connection.getContentType();
if(newWebpage.contentType != null ){
if(newWebpage.contentType.contains(";")){
newWebpage.contentType = newWebpage.contentType.substring(0, newWebpage.contentType.indexOf(";"));
}
newWebpage.contentType = newWebpage.contentType.toLowerCase();
}
visited.add(newWebpage);
if(newWebpage.status >= 300 && newWebpage.status < 400 && MyRunTimeConstants.shouldWeFollowRedirections){
newWebpage.redirect = new Webpage(connection.getHeaderField("Location"));
if(visited.contains(newWebpage.redirect)){
newWebpage.redirect = visited.get(visited.indexOf(newWebpage.redirect));
redirectedPage = newWebpage.redirect;
while(!newWebpage.parent.children.contains(redirectedPage)){
newWebpage.parent.children.add(newWebpage.parent.children.indexOf(newWebpage)+1, redirectedPage);
if(redirectedPage.redirect != null)
redirectedPage = visited.get(visited.indexOf(redirectedPage.redirect));
}
}else if(container.contains(newWebpage.redirect)){
newWebpage.redirect = next.get(next.indexOf(newWebpage.redirect));
if(!newWebpage.parent.children.contains(newWebpage.redirect))
newWebpage.parent.children.add(newWebpage.redirect);
next.remove(next.indexOf(newWebpage.redirect));
next.add(0, newWebpage.redirect);
} else{
next.add(0, newWebpage.redirect);
container.add(newWebpage.redirect);
newWebpage.redirect.parent = newWebpage.parent;
if(newWebpage.redirect.parent == null){
newWebpage.redirect.depth = ++rootDepth+"";
}
newWebpage.redirect.parent.children.add(newWebpage.redirect.parent.children.indexOf(newWebpage)+1, newWebpage.redirect);
}
} else if(MyRunTimeConstants.shouldWeFollowRedirections){
MyDesignTimePatterns.appendToTextFile("3xx found, but not followed", MyDesignTimePatterns.progressTextFile);
}
connection.disconnect();
} else if(visited.contains(newWebpage) && newWebpage.isRelative && (newWebpage.isRelative != visited.get(visited.indexOf(newWebpage)).isRelative)){
visited.get(visited.indexOf(newWebpage)).isRelative = true;
visited.get(visited.indexOf(newWebpage)).relativeURL = newWebpage.relativeURL;
newWebpage = null;
} else
newWebpage = null;
} catch (IOException e) {
newWebpage.status = 0;
newWebpage.contentType = e.toString();
visited.add(newWebpage);
} catch(IllegalArgumentException e){
newWebpage.status = 0;
newWebpage.contentType = e.toString();
visited.add(newWebpage);
}
return newWebpage;
}
private boolean checkForAnyExcludedPatterns(Webpage page){
if(!MyDesignTimePatterns.ignoreContainsPattern.isEmpty()){
for(String pattern : MyDesignTimePatterns.ignoreContainsPattern){
if(page.url.toString().contains(pattern)){
page.status = 998;
page.IPAddress = "Excluded from Processing";
visited.add(page);
return true;
}
}
}
if(!MyDesignTimePatterns.ignoreStartsWithPattern.isEmpty()){
for(String pattern : MyDesignTimePatterns.ignoreStartsWithPattern){
if(page.url.toString().startsWith(pattern)){
page.status = 998;
page.IPAddress = "Excluded from Processing";
visited.add(page);
return true;
}
}
}
if(!MyDesignTimePatterns.ignoreEndsWithPattern.isEmpty()){
for(String pattern : MyDesignTimePatterns.ignoreEndsWithPattern){
if(page.url.toString().endsWith(pattern)){
page.status = 998;
page.IPAddress = "Excluded from Processing";
visited.add(page);
return true;
}
}
}
if(!MyDesignTimePatterns.ignoreEqualsPattern.isEmpty()){
for(String pattern : MyDesignTimePatterns.ignoreEqualsPattern){
if(page.url.toString().equals(pattern)){
page.status = 998;
page.IPAddress = "Excluded from Processing";
visited.add(page);
return true;
}
}
}
if( !MyRunTimeConstants.shouldWeUseHTTPSURLS && page.url.toString().startsWith("https://")){
page.status = 998;
page.IPAddress = "Excluded from Processing";
visited.add(page);
MyDesignTimePatterns.appendToTextFile( new Date().toString() + " , " + page.url.toString() + page.parent.url.toString(), MyDesignTimePatterns.httpsLinksFile);
return true;
}
return false;
}
/**
* returns the a stringbuilder containing the given wepage's complete html code
* this one allows the user to select directly from the array
* @param index
* @throws IOException
* **/
public StringBuilder loadPage (int index) throws IOException{
return loadPage(visited.get(index));
}
/**
* Returns the a stringbuilder containing the given wepage's complete html code
* this one allows the user to denote which webpage object to load.
* WARNING: the webpage to be loaded does not need to be in ArrayLsit visited
* @param check
* @throws IOException
* **/
public StringBuilder loadPage( Webpage check ){
InputStream stream = null;
BufferedInputStream buffStream = null;
StringBuilder page = new StringBuilder();
if(check.status == 200 && check.contentType != null && check.contentType.contains("text")){
try {
URL url = check.url;
stream = url.openStream();
buffStream = new BufferedInputStream(stream);
int data;
do{
data = buffStream.read();
if(data != -1)
page.append((char)data);
}while(data != -1);
stream.close();
buffStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return page;
}
/**
* Gives the datminer object all the data that the searchtool has collected including
* allowed paths, visited pages, and allowed domains
* @param miner
*/
public void giveData(Dataminer miner){
for( Webpage page : visited){
miner.pages.add(page);
miner.container.add(page);
}
miner.problemsByPatterns = problemsByPatterns;
miner.mapFileTypeToURL = mapFileTypeToURL;
}
/**
* Removes the commented sections of the html page to avoid picking up commented out urls
* @param page
* @return the cleaned page
*/
public static StringBuilder cleanComments(StringBuilder page){
String commentRegex = "<!--(?:.*?)-->";
Pattern commentReg = Pattern.compile(commentRegex, Pattern.DOTALL);
Matcher commentMatcher = commentReg.matcher(page);
page = new StringBuilder(commentMatcher.replaceAll("<!-- replaced -->"));
return page;
}
/**
* Collects all valid url links from the current loaded page
* and places them into ArrayList next.
* @param page
* @throws IOException
*/
public static ArrayList<String> matchURLs( StringBuilder page, Webpage parent) throws IOException{
String matched;
Pattern reg ;
Matcher matcher;
ArrayList<String> matches = new ArrayList<String>();
if(page.length() != 0){
page = cleanComments(page);
reg = Pattern.compile(MyDesignTimePatterns.REGEX_TO_PICK_UP_HTTP_URLS, Pattern.DOTALL);
matcher = reg.matcher(page);
while(matcher.find()){
matched = matcher.group();
matched = matched.contains("\"") ? matched.substring(matched.indexOf("\"") + 1, matched.lastIndexOf("\"")): matched.substring(matched.indexOf("'") + 1, matched.lastIndexOf("'"));
matches.add(matched.toLowerCase());
}
if(MyRunTimeConstants.shouldWeUseHTTPSURLS){
reg = Pattern.compile(MyDesignTimePatterns.REGEX_TO_PICK_UP_HTTPS_URLS, Pattern.DOTALL);
matcher = reg.matcher(page);
while(matcher.find()){
matched = matcher.group();
matched = matched.contains("\"") ? matched.substring(matched.indexOf("\"") + 1, matched.lastIndexOf("\"")): matched.substring(matched.indexOf("'") + 1, matched.lastIndexOf("'"));
matches.add(matched.toLowerCase());
}
}
}
if(MyRunTimeConstants.shouldWeUseRelativeURLS){
matches.addAll(matchRelativeURLs(page, parent));
}
return matches;
}
public static ArrayList<String> matchRelativeURLs( StringBuilder page, Webpage parent) throws IOException{
String matched;
Pattern reg;
Matcher matcher;
ArrayList<String> matches = new ArrayList<String>();
if(page.length() != 0){
page = cleanComments(page);
if(MyRunTimeConstants.shouldWeUseRelativeSlashURLS){
reg = Pattern.compile(MyDesignTimePatterns.REGEX_TO_PICK_UP_RELATIVE_SLASH_URLS, Pattern.DOTALL);
matcher = reg.matcher(page);
while(matcher.find()){
matched = matcher.group();
matched = matched.contains("\"") ? matched.substring(matched.indexOf("\"") + 1, matched.lastIndexOf("\"")): matched.substring(matched.indexOf("'") + 1, matched.lastIndexOf("'"));
matches.add(matched.toLowerCase());
}
}
if(MyRunTimeConstants.shouldWeUseRelativeNoSlashURLS){
reg = Pattern.compile(MyDesignTimePatterns.REGEX_TO_PICK_UP_RELATIVE_NO_SLASH_URLS, Pattern.DOTALL);
matcher = reg.matcher(page);
while(matcher.find()){
matched = matcher.group();
matched = matched.contains("\"") ? matched.substring(matched.indexOf("\"") + 1, matched.lastIndexOf("\"")): matched.substring(matched.indexOf("'") + 1, matched.lastIndexOf("'"));
matched = matched.toLowerCase();
if(!matched.startsWith("http") && !matched.startsWith("/") && !matched.startsWith("../") && !matched.startsWith("mailto:") && !matched.startsWith("#") && !matched.endsWith(";") && !matched.contains("javascript"))
matches.add(matched);
}
}
if(MyRunTimeConstants.shouldWeUseDotDotURLS){
reg = Pattern.compile(MyDesignTimePatterns.REGEX_TO_PICK_UP_DOT_DOT_URLS, Pattern.DOTALL);
matcher = reg.matcher(page);
while(matcher.find()){
matched = matcher.group();
matched = matched.contains("\"") ? matched.substring(matched.indexOf("\"") + 1, matched.lastIndexOf("\"")): matched.substring(matched.indexOf("'") + 1, matched.lastIndexOf("'"));
matches.add(matched.toLowerCase());
}
}
}
return matches;
}
/**
* @param page
* @return The breadth at which page is located
*/
public int breadth(Webpage page){
String depth, check = "-";
int count = 0;
if(page != null){
depth = page.depth;
while(depth.contains(check)){
count++;
depth = depth.substring(depth.indexOf(check)+1);
}
}
return count;
}
/**
* Cross references the given page's domain name with all allowed domain names
* @param page
* @return True if page's domain is also an allowed domain, false otherwise
*/
public boolean domainCheck(Webpage page){
String domainName = page.url.getHost().toLowerCase();
if( !setOfUniqueDomainNames.contains(domainName) ){
setOfUniqueDomainNames.add(domainName);
MyDesignTimePatterns.appendToTextFile(page.IPAddress + " , " + domainName, MyDesignTimePatterns.domainNameFile);
if(page.IPAddress != null)
MyDesignTimePatterns.appendToTextFile(page.IPAddress, MyDesignTimePatterns.ipFile);
}
return MyDesignTimePatterns.AllowedDomainNames.contains(domainName);
}
public void sortSite(Webpage page){
addToHashMap(mapPagesByStatus, page.status, page);
addToHashMap(mapFileTypeToURL, page.contentType, page);
if(page.parent != null && page.status == 404){
addToHashMap(map404ParentToChildren, page.parent, page);
addToHashMap(map404ChildToParents, page, page.parent);
addToTraceMap( page.parent, page);
}
for(Webpage child : page.children){
if(child.status == 404){
addToHashMap(map404ChildToParents, child, page);
}
}
}
public void writeSite(Webpage page){
String progressText = page.IPAddress + " , " + page.url;
if (page.isRelative){
progressText += " , " + page.relativeURL;
}
if(page.parent != null){
progressText += " , " + page.parent.url;
}
MyDesignTimePatterns.appendToTextFile(progressText, MyDesignTimePatterns.masterFile);
if(page.isRelative){
if(page.relativeURL.startsWith("/")) {
MyDesignTimePatterns.appendToTextFile( page.status + " , " + progressText , MyDesignTimePatterns.forwardSlashRelativeLinkFile);
} else if(page.relativeURL.startsWith("../")){
MyDesignTimePatterns.appendToTextFile( page.status + " , " + progressText , MyDesignTimePatterns.dotDotRelativeLinkFile);
} else{
MyDesignTimePatterns.appendToTextFile( page.status + " , " + progressText , MyDesignTimePatterns.noSlashRelativeLinkFile);
}
}
if(page.status == 200){
MyDesignTimePatterns.appendToTextFile(progressText, MyDesignTimePatterns.fileProgressive200s);
}else{
MyDesignTimePatterns.appendToTextFile(progressText + page.status, MyDesignTimePatterns.fileNot200s);
if(page.status > 299 && page.status < 400){
MyDesignTimePatterns.appendToTextFile(progressText + page.status, MyDesignTimePatterns.fileProgressive300s);
}else if(page.status > 399 && page.status < 500 && page.status != 404){
MyDesignTimePatterns.appendToTextFile(progressText + page.status, MyDesignTimePatterns.fileProgressive300s);
}else if(page.status == 404){
MyDesignTimePatterns.appendToTextFile(progressText, MyDesignTimePatterns.fileProgressive404s);
}
}
//TODO create a txt file not200snot404s
MyDesignTimePatterns.appendToTextFile( visited.size()+ " , " + page.depth + " , "+ MyDesignTimePatterns.getCurrentDateTimeInMyFormat() + "," + progressText, MyDesignTimePatterns.progressTextFile);
}
/**
* @return Current cpu usage by the program
* @throws Exception
*/
public static double getProcessCpuLoad() throws Exception {
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
ObjectName name = ObjectName.getInstance("java.lang:type=OperatingSystem");
AttributeList list = mbs.getAttributes(name, new String[]{ "ProcessCpuLoad" });
if (list.isEmpty()) return Double.NaN;
Attribute att = (Attribute)list.get(0);
Double value = (Double)att.getValue();
// usually takes a couple of seconds before we get real values
if (value == -1.0) return Double.NaN;
// returns a percentage value with 1 decimal point precision
return ((int)(value * 1000) / 10.0);
}
/**
* @return current memory and cpu usage by the program
*/
public static String getProcessResourceLoad(){
String returnValue = null;
try {
returnValue =
"CPU load:" + getProcessCpuLoad() + "%" +
"\nMemory usage:" + ((Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory())/1048576.0);
} catch (Exception e) {
e.printStackTrace();
}
return returnValue;
}
/**
* Allows the program to retrieve pages directly from the hashSet container
* @param page
* @return the Webpage to be found, null if operation fails or if page does not exist
*/
public Webpage getPageFromContainer( Webpage page){
if(container.contains(page))
for(Webpage containerPage: container)
if(page.equals(containerPage))
return containerPage;
return null;
}
public Webpage buildRelativeURL(String URL, Webpage parent) throws IOException{
Webpage checkWebpage= null;
if(URL.startsWith("/")){
checkWebpage = buildRelativeSlashURL(URL, parent);
}else if(URL.startsWith("../")){
checkWebpage = buildRelativeDotDotURL(URL, parent);
} else{
checkWebpage = buildRelativeNoSlashURL(URL, parent);
}
return checkWebpage;
}
public Webpage buildRelativeSlashURL(String URL, Webpage parent)throws IOException{
Webpage checkWebpage= null;
String host = parent.url.getHost();
checkWebpage = new Webpage("http://" + host + URL);
checkWebpage.isRelative = true;
checkWebpage.relativeURL = URL;
return checkWebpage;
}
public Webpage buildRelativeNoSlashURL(String URL, Webpage parent)throws IOException{
Webpage checkWebpage= null;
String host = parent.url.getHost(), path = parent.url.getPath();
if(path.endsWith("/")){
path = path.substring(0, path.lastIndexOf("/"));
}
checkWebpage = new Webpage("http://" + host + path.substring(0, path.lastIndexOf("/")) + "/" + URL);
checkWebpage.isRelative = true;
checkWebpage.relativeURL = URL;
return checkWebpage;
}
public Webpage buildRelativeDotDotURL(String URL, Webpage parent) throws IOException{
Webpage checkWebpage= null;
String host = parent.url.getHost();
String temp = URL;
while(temp.contains("../")){
temp = temp.substring(temp.indexOf("/")+1);
}
checkWebpage = new Webpage("http://" + host + temp);
checkWebpage.isRelative = true;
checkWebpage.relativeURL = URL;
return checkWebpage;
}
/**
* builds the URLs that will be used in limitedBreadthSearch
* @param URL
* @param parent
* @return
*/
public Webpage buildURL(String URL, Webpage parent) throws IOException{
Webpage checkWebpage = null;
String host = parent.url.getHost();
if(MyRunTimeConstants.shouldWeUseRelativeURLS && !URL.startsWith("http")){
return buildRelativeURL(URL, parent);
}else
checkWebpage= new Webpage(URL);
if(checkWebpage.url.toString().startsWith("https://") && MyRunTimeConstants.shouldWeUseHTTPSURLS){
processHttps(URL, parent , checkWebpage);
}
MyDesignTimePatterns.appendToTextFile(checkWebpage.url + "," + URL + "," + host, MyDesignTimePatterns.absoluteLinkFile);
return checkWebpage;
}
public void processHttps(String URL, Webpage parent, Webpage child) throws IOException{
MyDesignTimePatterns.appendToTextFile( new Date().toString() + " , " + child.url.toString() + " , " + child.parent.url.toString(), MyDesignTimePatterns.httpsLinksFile);
/*
* the function does little more than print the newly formed url, as http and https urls are bot built the same way
* but at the very least, this gives room for https urls to be treated seperately after being built
*/
}
/**
* Extracts the first part of a URL's path
* I.E. http://www.domain.com/[this one]/[not]/[any]/[of]/[these]
* @param page
* @return the first part of the path
*/
public static String extractPathPattern(Webpage page){
String pagePath = page.url.getPath(), returnValue = MyRunTimeConstants.FOLDER_NAME_FOR_NO_PATTERN;
if(!pagePath.isEmpty()){
pagePath = pagePath.substring(1);
}
if(pagePath.contains("/") && pagePath.length() > 1){
returnValue = pagePath.substring(0, pagePath.indexOf("/"));
}
return returnValue;
}
public void addPatternToHashmap( String pattern, Webpage page){
problemsByPatterns.put(page, pattern);
}
public void processPatternMap( Webpage page){
String pattern = extractPathPattern(page);
if(!problemsByPatterns.containsKey(page.url.toString()))
addPatternToHashmap( pattern, page);
if(!MyDesignTimePatterns.dirPatterns.contains(MyDesignTimePatterns.dirProblemsByPatterns + "\\" + pattern + "\\404s")){
new File(MyDesignTimePatterns.dirProblemsByPatterns + "\\" + pattern ).mkdir();
MyDesignTimePatterns.dirPatterns.add( MyDesignTimePatterns.dirProblemsByPatterns + "\\" + pattern + "\\404s");
}
}
/**
* The bulk of the program's
*
* @param iterations
*/
public void limitedBreadthSearch(int iterations){
Webpage newWebpage = null, checkWebpage = null;
ArrayList<String> matches = new ArrayList<String>();
StringBuilder report = new StringBuilder();
iterations--;
lastTimePaused = new Date();
try {
MyDesignTimePatterns.appendToTextFile("Resource Usage:", MyDesignTimePatterns.dumpFile);
while(!next.isEmpty()){
newWebpage = gatherPreliminaryInformationAboutNextWebpageInQueue();
lastTimePaused = new Date();
report =new StringBuilder("\nat "+ lastTimePaused + "\n"+ getProcessResourceLoad() + "\n");
MyDesignTimePatterns.appendToTextFile(report.toString(), MyDesignTimePatterns.dumpFile);
if(newWebpage != null){
if(newWebpage.parent!=null){
newWebpage.depth = newWebpage.parent.depth + "-" + String.format("%d", newWebpage.parent.children.indexOf(newWebpage) + 1);
}
if(newWebpage.status == 404){
processPatternMap(newWebpage);
}
writeSite(newWebpage);
if(breadth(newWebpage) < iterations){
if(domainCheck(newWebpage)){
matches = matchURLs(loadPage(newWebpage), newWebpage);
report = new StringBuilder("On page: " + newWebpage);
for( String match : matches){
report.append("\n\t\t" + match);
}
MyDesignTimePatterns.appendToTextFile(report.toString(), MyDesignTimePatterns.matchFile);
printToConsole(newWebpage.depth);
}
while(!matches.isEmpty()){
checkWebpage = buildURL(matches.get(0), newWebpage);
if(checkWebpage != null){
if(container.contains(checkWebpage))
newWebpage.children.add(getPageFromContainer(checkWebpage));
else{
next.add(checkWebpage);
container.add(checkWebpage);
checkWebpage.parent = newWebpage;
newWebpage.children.add(checkWebpage);
}
}
matches.remove(0);
}
}
sortSite(newWebpage);
}
}
MyDesignTimePatterns.appendToTextFile("Search Over. Printing within searchtool.", MyDesignTimePatterns.progressTextFile);
printFromHashMap(MyDesignTimePatterns.SearchToolChildFirst404file, map404ChildToParents);
printFromHashMap(MyDesignTimePatterns.SearchToolParentFirst404file, map404ParentToChildren);
MyDesignTimePatterns.appendToTextFile("SearchTool Print Over", MyDesignTimePatterns.progressTextFile);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void printToConsole( Object o){
//System.out.println(o.toString());
}
public static void addToHashMap( HashMap<Webpage,HashSet<Webpage>> map , Webpage key , Webpage value){
if(!map.containsKey(key)){
map.put(key, new HashSet<Webpage>());
map.get(key).add(value);
} else {
map.get(key).add(value);
}
}
public static void addToHashMap( HashMap<String,HashSet<Webpage>> map , String key , Webpage value){
if(!map.containsKey(key)){
map.put(key, new HashSet<Webpage>());
map.get(key).add(value);
} else {
map.get(key).add(value);
}
}
public void addToTraceMap(Webpage parent , Webpage child){
if(!mapParentTo404Trace.containsKey(parent)){
mapParentTo404Trace.put(parent, new HashSet<ArrayList<Webpage>>());
mapParentTo404Trace.get(parent).add(traceRedirectionsToWebpageInSearchTool( parent, child));
} else {
mapParentTo404Trace.get(parent).add(traceRedirectionsToWebpageInSearchTool( parent, child));
}
}
public static void addToHashMap( HashMap<Integer,HashSet<Webpage>> map , Integer key , Webpage value){
if(!map.containsKey(key)){
map.put(key, new HashSet<Webpage>());
map.get(key).add(value);
} else {
map.get(key).add(value);
}
}
/**
* A similar function like this already exists in the dataminer class and works, i was just leaving the framework
* here in case the searchtool would like to feature redirection tracing
* @param parent
* @param child
* @return
*/
public ArrayList<Webpage> traceRedirectionsToWebpageInSearchTool( Webpage parent, Webpage child){
ArrayList<Webpage> tracePath = new ArrayList<Webpage>();
// HashSet<Webpage> all301sAnd302s = new HashSet<Webpage>();
// Webpage checkPage = child;
//
//
// if(mapPagesByStatus.containsKey(301)){
// all301sAnd302s.addAll(mapPagesByStatus.get(301));
// }
//
// if(mapPagesByStatus.containsKey(302)){
// all301sAnd302s.addAll(mapPagesByStatus.get(302));
// }
//
// while( !tracePath.contains(checkPage.url.toString())){
// tracePath.add(checkPage);
//
// for(Webpage page : all301sAnd302s){
// if(parent != null && parent.children.contains(page) && page.redirect.equals(checkPage)){
// checkPage = page;
// break;
// }
// }
// }
tracePath.add(child);
return tracePath;
}
public void printFromHashMap( File file , HashMap< Webpage , HashSet<Webpage>> map){
int outerCount = 0, innerCount;
if(!map.isEmpty()){
for(Webpage page : map.keySet()){
MyDesignTimePatterns.appendToTextFile( ++outerCount + " , " + page, file);
innerCount = 1;
for(Webpage subpage : map.get(page)){
MyDesignTimePatterns.appendToTextFile( outerCount + "." +innerCount++ + " , " + subpage, file);
}
}
}
}
public void reset(){
next.clear();
next.add(visited.get(0));
visited.clear();
}
}
| true |
f4d73886736c71c203c181318b2debfdab61fac2 | Java | RyanTech/TakePicBuy | /app/src/main/java/com/unionbigdata/takepicbuy/adapter/SearchResultAdapter.java | UTF-8 | 9,697 | 1.84375 | 2 | [] | no_license | package com.unionbigdata.takepicbuy.adapter;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.facebook.drawee.view.SimpleDraweeView;
import com.google.gson.Gson;
import com.unionbigdata.takepicbuy.R;
import com.unionbigdata.takepicbuy.activity.GoodsCompare;
import com.unionbigdata.takepicbuy.activity.WebViewActivity;
import com.unionbigdata.takepicbuy.baseclass.SuperAdapter;
import com.unionbigdata.takepicbuy.http.AsyncHttpTask;
import com.unionbigdata.takepicbuy.http.ResponseHandler;
import com.unionbigdata.takepicbuy.model.SearchResultListModel;
import com.unionbigdata.takepicbuy.model.SearchResultModel;
import com.unionbigdata.takepicbuy.params.SearchResultParam;
import com.unionbigdata.takepicbuy.utils.ClickUtil;
import org.apache.http.Header;
import java.util.ArrayList;
import butterknife.ButterKnife;
import butterknife.InjectView;
/**
* 搜索结果
* Created by Christain on 2015/4/20.
*/
public class SearchResultAdapter extends SuperAdapter {
private int page = 0, isOver = 0, maxPage;
public int limit = 20;
private String imgUrl = "", filterString = "all";
private ResponseHandler responseHandler;
private Context mContext;
public SearchResultAdapter(Context context) {
super(context);
this.mContext = context;
this.initListener();
}
private void initListener() {
responseHandler = new ResponseHandler() {
@Override
public void onResponseSuccess(int returnCode, Header[] headers, String result) {
Gson gson = new Gson();
SearchResultListModel list = gson.fromJson(result, SearchResultListModel.class);
if (page == 0) {
limit = list.getPage_listsize();
imgUrl = list.getSrcimageurl();
maxPage = list.getPage_sum();
}
if (list != null && list.getSearchresult() != null) {
switch (loadType) {
case REFRESH:
refreshItems(list.getSearchresult());
if (list.getSearchresult().size() == 0) {
refreshOver(returnCode, ISNULL);
} else if (page == maxPage - 1) {
isOver = 1;
refreshOver(returnCode, ISOVER);
} else {
page++;
refreshOver(returnCode, CLICK_MORE);
}
break;
case LOADMORE:
if (page != maxPage - 1) {
page++;
loadMoreOver(returnCode, CLICK_MORE);
} else {
isOver = 1;
loadMoreOver(returnCode, ISOVER);
}
addItems(list.getSearchresult());
break;
}
} else {
switch (loadType) {
case REFRESH:
refreshOver(returnCode, ISNULL);
break;
case LOADMORE:
loadMoreOver(returnCode, ISOVER);
break;
}
}
isRequest = false;
}
@Override
public void onResponseFailed(int returnCode, String errorMsg) {
switch (loadType) {
case REFRESH:
refreshOver(-1, errorMsg);
break;
case LOADMORE:
loadMoreOver(-1, errorMsg);
break;
}
isRequest = false;
}
};
}
@SuppressLint("InflateParams")
@Override
public View getView(int position, View convertView, ViewGroup arg2) {
ViewHolder holder = null;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.item_search_result, null);
holder = new ViewHolder(convertView);
DisplayMetrics metrics = context.getResources().getDisplayMetrics();
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) holder.ivPic.getLayoutParams();
params.width = (metrics.widthPixels - context.getResources().getDimensionPixelOffset(R.dimen.search_result_padding) * 3) / 2;
params.height = params.width;
holder.ivPic.setLayoutParams(params);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
ArrayList<SearchResultModel> list = (ArrayList<SearchResultModel>) getItem(position);
if (position == 0 || position == 1) {
holder.view.setVisibility(View.VISIBLE);
} else {
holder.view.setVisibility(View.GONE);
}
holder.ivPic.setImageURI(Uri.parse(list.get(0).getImg_url()));
holder.tvTitle.setText(list.get(0).getTitle());
holder.tvPrice.setText("¥" + list.get(0).getPrice());
switch (list.get(0).getOrig_id()) {
case 1:
holder.ivType.setImageResource(R.mipmap.icon_type_taobao);
break;
case 2:
holder.ivType.setImageResource(R.mipmap.icon_type_tmall);
break;
case 3:
holder.ivType.setImageResource(R.mipmap.icon_type_jd);
break;
default:
holder.ivType.setImageResource(R.mipmap.icon_type_taobao);
break;
}
if (list.get(0).getSalesnum() > 999) {
holder.tvSaleNum.setText("销量:" + "999+");
if (list.get(0).getSalesnum() > 2000) {
holder.tvSaleNum.setText("销量:" + "2000+");
} else if (list.get(0).getSalesnum() > 5000) {
holder.tvSaleNum.setText("销量:" + "5000+");
} else if (list.get(0).getSalesnum() > 10000) {
holder.tvSaleNum.setText("销量:" + "10000+");
}
} else {
holder.tvSaleNum.setText("销量:" + list.get(0).getSalesnum());
}
if (list.size() > 1) {
holder.tvSameNum.setVisibility(View.VISIBLE);
holder.tvSameNum.setText((list.size()) + "件同款");
} else {
holder.tvSameNum.setVisibility(View.GONE);
}
holder.llItemAll.setOnClickListener(new OnItemAllClickListener(list));
return convertView;
}
static class ViewHolder {
@InjectView(R.id.llItemAll)
LinearLayout llItemAll;
@InjectView(R.id.view)
View view;
@InjectView(R.id.ivPic)
SimpleDraweeView ivPic;
@InjectView(R.id.tvTitle)
TextView tvTitle;
@InjectView(R.id.tvPrice)
TextView tvPrice;
@InjectView(R.id.ivType)
ImageView ivType;
@InjectView(R.id.tvSaleNum)
TextView tvSaleNum;
@InjectView(R.id.tvSameNum)
TextView tvSameNum;
public ViewHolder(View convertView) {
ButterKnife.inject(this, convertView);
}
}
private class OnItemAllClickListener implements View.OnClickListener {
private ArrayList<SearchResultModel> list;
public OnItemAllClickListener(ArrayList<SearchResultModel> list) {
this.list = list;
}
@Override
public void onClick(View view) {
if (!ClickUtil.isFastClick()) {
if (list.size() > 1) {
Intent intent = new Intent(context, GoodsCompare.class);
intent.putExtra("LIST", list);
context.startActivity(intent);
} else {
Intent intent = new Intent(context, WebViewActivity.class);
intent.putExtra("URL", list.get(0).getUrl());
intent.putExtra("TITLE", "商品详情");
context.startActivity(intent);
}
}
}
}
@Override
public void refresh() {
}
@Override
public void loadMore() {
if (isOver == 1) {
loadMoreOver(0, ISOVER);
} else {
if (!isRequest) {
this.isRequest = true;
this.loadType = LOADMORE;
SearchResultParam param = new SearchResultParam(imgUrl, filterString, page, limit);
AsyncHttpTask.post(param.getUrl(), param, responseHandler);
}
}
}
public boolean getIsOver() {
return (isOver == 1) ? true : false;
}
/**
* 搜索第一次加载分类
*/
public void searchResultList(String imgUrl, String filterString) {
if (!isRequest) {
this.isRequest = true;
this.loadType = REFRESH;
this.page = 0;
isOver = 0;
this.imgUrl = imgUrl;
this.filterString = filterString;
SearchResultParam param = new SearchResultParam(imgUrl, filterString, page, limit);
AsyncHttpTask.post(param.getUrl(), param, responseHandler);
}
}
} | true |
fd3add5c98d6968698f57849bb8fad89f48f926c | Java | JaeJinBae/uhan | /src/main/java/com/antweb/persistence/ReplyDaoImpl.java | UTF-8 | 892 | 2.046875 | 2 | [] | no_license | package com.antweb.persistence;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.antweb.domain.ReplyVO;
@Repository
public class ReplyDaoImpl implements ReplyDao {
private static final String namespace="com.antweb.mappers.ReplyMapper";
@Autowired
private SqlSession session;
@Override
public ReplyVO select(int bno) throws Exception {
return session.selectOne(namespace+".select",bno);
}
@Override
public void insert(ReplyVO vo) throws Exception {
session.insert(namespace+".insert", vo);
}
@Override
public void update(ReplyVO vo) throws Exception {
session.update(namespace+".update", vo);
}
@Override
public void delete(int rno) throws Exception {
session.delete(namespace+".delete", rno);
}
}
| true |
63155970f1754de4d19a012bb7c67c61da15f5cb | Java | huntercap/erp | /src/com/cx/erp/action/EmployeeAction.java | UTF-8 | 990 | 2.03125 | 2 | [] | no_license | package com.cx.erp.action;
import com.cx.erp.service.EmployeeService;
import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts2.interceptor.RequestAware;
import java.util.Map;
/**
* Created by Administrator on 2017/3/7.
*/
public class EmployeeAction extends ActionSupport implements RequestAware
{
private static final long serialVersionUID = 1L;
private Map<String,Object> request;
@Override
public void setRequest(Map<String, Object> request) {
System.out.println("set request!");
this.request = request;
}
private EmployeeService employeeService;
public void setEmployeeService(EmployeeService e) {
System.out.println("3:setEmployeeService");
this.employeeService = e;
}
public String list(){
System.out.println(request.toString());
//System.out.println(employeeService.toString());
this.request.put("employees",employeeService.getAll());
return "list";
}
}
| true |
daa48d2714f48483de1ef2c1377cd8476cc99cca | Java | cckmit/PaypalPaymentGateway | /STBI/src/begindashboardservlets/GetBasicDetailsServlet.java | UTF-8 | 3,724 | 2.109375 | 2 | [] | no_license | package begindashboardservlets;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.omg.CORBA.RepositoryIdHelper;
import com.dao.Dao;
import com.dao.WebResponse;
import com.google.gson.Gson;
import beginmystartup_pojo.BasicDetails;
import beginmystartup_pojo.EducationDetails;
/**
* Servlet implementation class GetBasicDetailsServlet
*/
//@WebServlet("/GetBasicDetailsServlet")
public class GetBasicDetailsServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private Connection connection;
private PreparedStatement pst;
private ResultSet rst;
private String ismobile=null;
private ArrayList<EducationDetails>arrayedudetails=null;
/**
* @see HttpServlet#HttpServlet()
*/
public GetBasicDetailsServlet() {
super();
// TODO Auto-generated constructor stub
}
@Override
public void init() throws ServletException {
// TODO Auto-generated method stub
super.init();
try {
connection=Dao.getConnection();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter pw=response.getWriter();
WebResponse wb=new WebResponse();
String ismobile=request.getParameter("is_Mobile");
if(ismobile == null)
{
ismobile="0";
}
String userid=request.getParameter("userid");
String selectquery="select firstname,middlename,lastname,dob,gender,mobilenumber,emailid,adharcardno,tempararyaddress,permenentaddress,city,pincode from user where userId=?";
try {
pst=connection.prepareStatement(selectquery);
pst.setString(1, userid);
rst=pst.executeQuery();
BasicDetails basincdetails=null;
while(rst.next())
{
String firstname=rst.getString(1);
String middlename=rst.getString(2);
String lastname=rst.getString(3);
String dob=rst.getString(4);
String gender=rst.getString(5);
String contact=rst.getString(6);
String emailid=rst.getString(7);
String adharcardno=rst.getString(8);
String ta=rst.getString(9);
String pa=rst.getString(10);
String city=rst.getString(11);
String pincode=rst.getString(12);
basincdetails=new BasicDetails(firstname, middlename, lastname, dob, gender, contact, emailid, adharcardno,ta, pa, city, pincode);
}
wb.data=basincdetails;
wb.result=true;
if(ismobile.equals("1"))
{
Gson gson=new Gson();
String tojson=gson.toJson(wb);
pw.write(tojson);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
| true |
329dbc16bd76aad5cc628b4f9428113dc1aa9c48 | Java | javeteam/calendar | /src/main/java/com/aspect/calendar/entity/calendar/Job.java | UTF-8 | 1,195 | 2.828125 | 3 | [] | no_license | package com.aspect.calendar.entity.calendar;
import com.aspect.calendar.entity.user.Person;
import java.util.ArrayList;
import java.util.List;
public class Job {
private Person provider;
// value in hours
private float xtrfDuration;
// value in seconds
private int calendarDuration;
List<CalendarItem> calendarItems = new ArrayList<>();
public Person getProvider() {
return provider;
}
public void setProvider(Person provider) {
this.provider = provider;
}
public float getXtrfDuration() {
return Math.round(xtrfDuration * 100) / 100f;
}
public void addXtrfDuration(float xtrfDuration) {
this.xtrfDuration += xtrfDuration;
}
public float getCalendarDuration() {
return Math.round(calendarDuration / 36f) / 100f;
}
public List<CalendarItem> getCalendarItems() {
return calendarItems;
}
public void addCalendarItem(CalendarItem calendarItem) {
this.calendarItems.add(calendarItem);
this.calendarDuration += calendarItem.getDuration();
}
public boolean valuesDifferent(){
return getXtrfDuration() != getCalendarDuration();
}
}
| true |
19db426b31d0193c94a44b8421e58a7e2c0f6e76 | Java | neorus616/OOP | /OOPNew/src/main/java/filters/LocationFilter.java | UTF-8 | 4,378 | 2.65625 | 3 | [] | no_license | package main.java.filters;
import main.java.wifi.Networks;
/**
*
* @author Kostia Kazakov & Yogev Rahamim <br>
* @version 2.0
* Description:
* Location filter.
*/
public class LocationFilter implements Filter {
private static final long serialVersionUID = 456L;
private double _maxAlt, _minAlt, _maxLon, _minLon, _maxLat, _minLat;
private double _Lat, _Lon, _radius;
private boolean _not = true;
/**
* Constructor
* @param startLat - Start Latitude
* @param startLong - Start Longitude
* @param endLat - End Latitude
* @param endLong - End Longitude
*/
public LocationFilter(String Lat, String Lon,String radius) {
_Lat = Double.parseDouble(Lat);
_Lon = Double.parseDouble(Lon);
_radius = Double.parseDouble(radius);
}
/**
* Constructor
* @param minLat - Minimum Latitude
* @param maxLat - Maximum Latitude
* @param minLon - Minimum Longitude
* @param maxLon - Maximum Longitude
* @param minAlt - Minimum Altitude
* @param maxAlt - Maximum Altitude
*/
public LocationFilter(String minLat, String maxLat, String minLon, String maxLon, String minAlt, String maxAlt) {
_maxAlt = Double.parseDouble(maxAlt);
_minAlt = Double.parseDouble(minAlt);
_maxLon = Double.parseDouble(maxLon);
_minLon = Double.parseDouble(minLon);
_maxLat = Double.parseDouble(maxLat);
_minLat = Double.parseDouble(minLat);
}
/**
* Constructor
* @param loc - Array of location
*/
public LocationFilter(String [] loc) {
_minLat = Double.parseDouble(loc[0]);
_maxLat = Double.parseDouble(loc[1]);
_minLon = Double.parseDouble(loc[2]);
_maxLon = Double.parseDouble(loc[3]);
_minAlt = Double.parseDouble(loc[4]);
_maxAlt = Double.parseDouble(loc[5]);
}
/**
* Constructor for not operator
* @param loc - Array of location
* @param not - not operator
*/
public LocationFilter(String [] loc, boolean not) {
_minLat = Double.parseDouble(loc[0]);
_maxLat = Double.parseDouble(loc[1]);
_minLon = Double.parseDouble(loc[2]);
_maxLon = Double.parseDouble(loc[3]);
_minAlt = Double.parseDouble(loc[4]);
_maxAlt = Double.parseDouble(loc[5]);
_not = not;
}
@Override
public boolean test(Networks p) {
// TODO Auto-generated method stub
if(_radius == 0) {
if(_not)
return _maxAlt >= p.getAlt() && _minAlt <= p.getAlt() &&
_maxLon >= p.getLon() && _minLon <= p.getLon() &&
_maxLat >= p.getLat() && _minLat <= p.getLat();
else return !(_maxAlt >= p.getAlt() && _minAlt <= p.getAlt() &&
_maxLon >= p.getLon() && _minLon <= p.getLon() &&
_maxLat >= p.getLat() && _minLat <= p.getLat());
} else {
return (distance(p.getLat(), p.getLon(), _Lat, _Lon) <= _radius);
}
}
@Override
public String toString() {
if(_radius == 0) {
if(_not)
return "LocationFilter [_maxAlt=" + _maxAlt + ", _minAlt=" + _minAlt + ", _maxLon=" + _maxLon + ", _minLon="
+ _minLon + ", _maxLat=" + _maxLat + ", _minLat=" + _minLat + "]";
else return "Not(LocationFilter [_maxAlt=" + _maxAlt + ", _minAlt=" + _minAlt + ", _maxLon=" + _maxLon + ", _minLon="
+ _minLon + ", _maxLat=" + _maxLat + ", _minLat=" + _minLat + "])";
} else {
return "LocationFilter [_Lat=" + _Lat + ", _Lon=" + _Lon + ", _radius=" + _radius + "]";
}
}
/**
* @author Jason Winn <br>
* * @version 1.0
* <b>Description:</b> <br>
* Calculate distance between two locations on earth
* using the Haversine formula.
* Source: https://github.com/jasonwinn/haversine/blob/master/Haversine.java
* @param startLat - Start Latitude
* @param startLong - Start Longitude
* @param endLat - End Latitude
* @param endLong - End Longitude
* @return distance between 2 points.
*/
public static double distance(double startLat, double startLong,
double endLat, double endLong) {
double dLat = Math.toRadians((endLat - startLat));
double dLong = Math.toRadians((endLong - startLong));
startLat = Math.toRadians(startLat);
endLat = Math.toRadians(endLat);
double a = Math.pow(Math.sin(dLat / 2), 2) + Math.cos(startLat) * Math.cos(endLat) * Math.pow(Math.sin(dLong / 2), 2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
int EARTH_RADIUS = 6371; // Approximate Earth radius in KM
return EARTH_RADIUS * c*1000; // <-- distance
}
}
| true |
003f86de8b1d0326d174b0657ed85d1c146f85cd | Java | ActiveZ/java-cnam2 | /src/Validation/Joueur.java | UTF-8 | 274 | 2.796875 | 3 | [] | no_license | package Validation;
public class Joueur {
public String nom = "";
private De de = new De(6);
public Joueur(String nom) {
this.nom = nom;
} //constructeur
public int lanceDe () {
return de.lancer();
} // methode de tirage de dé
}
| true |
6a7f760d4400dee6594f00ffb713a04736a07760 | Java | liyanippon/working | /data/work/androidstudio/AndroidStudioProjects/CoinMachine/app/src/main/java/com/example/admin/coinmachine/ui/activity/MainActivity.java | UTF-8 | 3,163 | 2.21875 | 2 | [
"Apache-2.0"
] | permissive | package com.example.admin.coinmachine.ui.activity;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.example.admin.coinmachine.common.BaseActivity;
import com.example.admin.coinmachine.database.UserDao;
import com.example.admin.coinmachine.http.StatisticUrl;
import com.example.admin.coinmachine.model.User;
import com.example.admin.coinmachine.paymentcode.CodeUtils;
import java.util.List;
public class MainActivity extends BaseActivity {
private TextView iop;
private ImageView imageView,twocode;
public static Activity activity;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
activity = MainActivity.this;
initView();
database();//数据库测试
imageView();//图片缓存加载测试
twoCode();//二维码测试
}
private void twoCode() {
twocode.setBackgroundColor(Color.WHITE);
Log.d("MainActivity", twocode.getWidth() + ",," + twocode.getHeight());
Bitmap bitmap = CodeUtils.CreateTwoDCode("testtwocode", 300, 300);
twocode.setImageBitmap(bitmap);
}
private void imageView() {
Glide.with(getApplicationContext())
.load(StatisticUrl.viewUrl)
.diskCacheStrategy(DiskCacheStrategy.ALL)//既缓存全尺寸又缓存其他尺寸,加载显示非常快
.placeholder(R.drawable.ic_launcher_round)//加载占位图
.error(R.drawable.ic_launcher_round)//错误加载
.into(imageView);
}
private void database() {
//testAddUser();//添加后查询
testUpdateUser();//更新
}
@Override
public void initView() {
super.initView();
imageView = (ImageView) findViewById(R.id.image);
twocode = (ImageView) findViewById(R.id.twocode);
}
public void testAddUser(){
User ul = new User("zhy", "2B青年");
UserDao userDao = new UserDao(getApplicationContext());
//userDao.add(ul);//添加
/*UserDao userDao = new UserDao(getApplicationContext());
userDao.deleteUserId(1);*/
userDao.deleteUser(ul);
List<User> list = userDao.getAllUser();//查询所有姓名
for (User userList:list){
Log.d("MainActivity", "输出所有信息:" + userList.getName() + ";;" + userList.getDesc() + ";;" + userList.getId());
}
}
public void testUpdateUser(){
User ul = new User("天一", "中国人");
UserDao userDao = new UserDao(getApplicationContext());
userDao.updateUser(ul);
List<User> list = userDao.getAllUser();//查询所有姓名
for (User userList:list){
Log.d("MainActivity", "输出所有信息:" + userList.getName() + ";;" + userList.getDesc() + ";;" + userList.getId());
}
}
}
| true |
6bb3445f1c978ec08743869a8ba6eb015a781bea | Java | michaelSaid/Data-Structure | /data-structure/src/eg/edu/alexu/csd/datastructure/mailServer/cs38/MyPriorityQueue.java | UTF-8 | 4,754 | 3 | 3 | [] | no_license | package eg.edu.alexu.csd.datastructure.mailServer.cs38;
import eg.edu.alexu.csd.datastructure.mailServer.IPriorityQueue;
/**
*
* @author DELL
*
*/
public class MyPriorityQueue implements IPriorityQueue {
/**
*
*/
PNode head;
/**
*
*/
PNode tail;
/**
*
*/
int size;
/**
*
* @author DELL
*
*/
public class PNode {
/**
*
*/
Object item;
/**
*
*/
PNode next;
/**
*
*/
PNode prev;
/**
*
*/
int key;
/**
*
* @return prev
*/
public PNode getPrev() {
return prev;
}
/**
*
* @param newPrev
* ...
*/
public void setPrev(final PNode newPrev) {
this.prev = newPrev;
}
/**
*
* @return item.
*/
public Object getItem() {
return item;
}
/**
*
* @param newItem
* ...
*/
public void setItem(final Object newItem) {
this.item = newItem;
}
/**
*
* @return next.
*/
public PNode getNext() {
return next;
}
/**
*
* @param newNext
* ....
*/
public void setNext(final PNode newNext) {
this.next = newNext;
}
/**
*
* @return key
*/
public int getKey() {
return key;
}
/**
*
* @param newkey
* ....
*/
public void setKey(final int newkey) {
this.key = newkey;
}
/**
*
* @param newItem
* ...
* @param newNext
* ..
* @param newPrev
* ....
* @param newkey
* ...
*/
public PNode(final Object newItem, final PNode newNext, final PNode newPrev,
final int newkey) {
// TODO Auto-generated constructor stub
this.item = newItem;
this.next = newNext;
this.prev = newPrev;
this.key = newkey;
}
}
/**
*
*/
public MyPriorityQueue() {
// TODO Auto-generated constructor stub
size = 0;
head = new PNode(null, tail, null, 0);
tail = new PNode(null, null, head, 0);
}
@Override
public final void insert(final Object item, final int key) {
// TODO Auto-generated method stub
if (key < 1) {
throw new RuntimeException();
}
PNode newNode = new PNode(item, null, null, key);
if (size == 0) {
head.setNext(newNode);
newNode.setPrev(head);
newNode.setNext(tail);
tail.setPrev(newNode);
size++;
return;
}
if (size == 1) {
if (head.getNext().getKey() > key) {
newNode.setPrev(head);
newNode.setNext(head.getNext());
head.getNext().setPrev(newNode);
head.setNext(newNode);
} else {
newNode.setNext(tail);
newNode.setPrev(tail.getPrev());
tail.getPrev().setNext(newNode);
tail.setPrev(newNode);
}
size++;
return;
}
PNode first = head.getNext();
PNode last = tail.getPrev();
for (int i = 0; i < size; i++) {
if (key >= last.getKey()) {
newNode.setNext(last.getNext());
newNode.setPrev(last);
last.getNext().setPrev(newNode);
last.setNext(newNode);
break;
} else if (key < first.getKey()) {
newNode.setPrev(first.getPrev());
newNode.setNext(first);
first.getPrev().setNext(newNode);
first.setPrev(newNode);
break;
} else {
first = first.getNext();
last = last.getPrev();
}
}
size++;
}
@Override
public final Object removeMin() {
// TODO Auto-generated method stub
if (size == 0) {
throw new RuntimeException();
}
Object ret = head.getNext().getItem();
if (size == 1) {
size = 0;
head = new PNode(null, tail, null, 0);
tail = new PNode(null, null, head, 0);
return ret;
}
PNode deleted = head.getNext();
head.setNext(deleted.getNext());
deleted.getNext().setPrev(head);
deleted.setNext(null);
deleted.setPrev(null);
size--;
return ret;
}
@Override
public final Object min() {
// TODO Auto-generated method stub
if (size == 0) {
throw new RuntimeException();
}
return head.getNext().getItem();
}
@Override
public final boolean isEmpty() {
// TODO Auto-generated method stub
return size == 0;
}
@Override
public final int size() {
// TODO Auto-generated method stub
return size;
}
}
| true |
c227db561033fe23651c6a1759b9f3cdf4f3441a | Java | fatmind/TestIdea | /src/main/java/com/keepalive/mina/ClientKeepAliveMessageFactoryImpl.java | UTF-8 | 955 | 2.578125 | 3 | [] | no_license | package com.keepalive.mina;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.keepalive.KeepAliveMessageFactory;
public class ClientKeepAliveMessageFactoryImpl implements KeepAliveMessageFactory {
private static final String serverMsg = "#";
private static final String clientMsg = "*";
@Override
public boolean isRequest(IoSession session, Object message) {
if(clientMsg.equals(message)) {
System.out.println("client : client -> server, keepalive reques");
return true;
}
return false;
}
@Override
public boolean isResponse(IoSession session, Object message) {
if(serverMsg.equals(message)) {
System.out.println("client : server -> client, keepalive reponse");
return true;
}
return false;
}
@Override
public Object getRequest(IoSession session) {
return clientMsg;
}
@Override
public Object getResponse(IoSession session, Object request) {
return serverMsg;
}
}
| true |
038345abfba835ecbfcb7c98a5ac93285a2b1c33 | Java | wtu403/PluginAPK | /plugin/src/main/java/me/yuqirong/plugin/PluginManager.java | UTF-8 | 7,315 | 1.875 | 2 | [
"Apache-2.0"
] | permissive | package me.yuqirong.plugin;
import android.app.Application;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageParser;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.text.TextUtils;
import java.io.File;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import me.yuqirong.plugin.constant.PluginConstant;
import me.yuqirong.plugin.constant.PluginConstant.*;
import me.yuqirong.plugin.entity.Plugin;
import me.yuqirong.plugin.entity.PluginDataStorage;
import me.yuqirong.plugin.hook.PluginClassLoader;
import me.yuqirong.plugin.hook.PluginContext;
import me.yuqirong.plugin.hook.PluginEnvironment;
import me.yuqirong.plugin.hook.PluginShellActivity;
import me.yuqirong.plugin.util.ReflectUtil;
/**
* @author Zhouyu
* @date 2018/8/13
*/
public class PluginManager {
private static PluginManager instance;
private Context context;
// key = plugin package name
private Map<String, Plugin> pluginMap = new HashMap<>();
private PluginManager(Context context) {
//no instance
this.context = context;
}
public static PluginManager getInstance(Context context) {
if (instance == null) {
instance = new PluginManager(context);
}
return instance;
}
public Plugin getPlugin(String packageName) {
return pluginMap.get(packageName);
}
/**
* 加载插件apk
*
* @param pluginApkPath
* @return
*/
public Plugin loadPluginApk(String pluginApkPath) {
if (TextUtils.isEmpty(pluginApkPath)) {
return null;
}
File pluginApk = new File(pluginApkPath);
if (!pluginApk.exists() || !pluginApk.isFile()) {
return null;
}
Plugin plugin = new Plugin();
plugin.mFilePath = pluginApkPath;
// init plugin environment
PluginEnvironment.initPluginEnvironmentIfNeed();
// load apk
parsePluginPackage(plugin);
loadPluginResource(plugin);
createPluginClassLoader(plugin);
createPluginApplication(plugin);
// register broadcast receiver
registerBroadCastReceiver(plugin);
// cache plugin
pluginMap.put(plugin.mPackage.packageName, plugin);
return plugin;
}
private void registerBroadCastReceiver(Plugin plugin) {
try {
ArrayList<PackageParser.Activity> receivers = plugin.mPackage.receivers;
for (PackageParser.Activity receiver : receivers) {
Object obj = Class.forName(receiver.getComponentName().getClassName(), false, plugin.mClassLoader).newInstance();
BroadcastReceiver broadcastReceiver = BroadcastReceiver.class.cast(obj);
// 注册广播
for (PackageParser.ActivityIntentInfo intentInfo : receiver.intents) {
context.registerReceiver(broadcastReceiver, intentInfo);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void startActivity(Context context, Plugin plugin, Intent intent) throws Exception {
if (plugin == null || intent == null) {
throw new Exception("plugin or intent cannot be null");
}
ComponentName component = intent.getComponent();
if (component == null) {
throw new Exception("component cannot be null");
}
PluginDataStorage pluginDataStorage = new PluginDataStorage();
pluginDataStorage.packageName = component.getPackageName();
pluginDataStorage.className = component.getClassName();
// replace activity
intent.putExtra(PluginConstant.PLUGIN_DATA, pluginDataStorage);
intent.setClass(context, PluginShellActivity.class);
intent.setExtrasClassLoader(PluginDataStorage.class.getClassLoader());
context.startActivity(intent);
}
private void createPluginApplication(Plugin plugin) {
try {
ApplicationInfo applicationInfo = plugin.mPackage.applicationInfo;
String appClassName = applicationInfo.className;
if (appClassName == null) {
appClassName = Application.class.getName();
}
Application application = (Application) plugin.mClassLoader.loadClass(appClassName).newInstance();
plugin.mApplication = application;
// attach base context TODO why ?
Field mBase = ReflectUtil.getField(ContextWrapper.class, FieldName.mBase);
if (mBase != null) {
mBase.set(application, new PluginContext(context.getApplicationContext(), plugin));
}
} catch (Throwable e) {
e.printStackTrace();
}
}
private void createPluginClassLoader(Plugin plugin) {
try {
String dexPath = context.getCacheDir().getAbsolutePath() + "/plugin-dir/dex";
File dexDir = new File(dexPath);
if (!dexDir.exists()) {
dexDir.mkdirs();
}
String libPath = context.getCacheDir().getAbsolutePath() + "/plugin-dir/lib";
File libDir = new File(libPath);
if (!libDir.exists()) {
libDir.mkdirs();
}
PluginClassLoader pluginClassLoader = new PluginClassLoader(plugin.mFilePath,
dexDir.getAbsolutePath(), libDir.getAbsolutePath(),
ClassLoader.getSystemClassLoader().getParent());
plugin.mClassLoader = pluginClassLoader;
} catch (Exception e) {
e.printStackTrace();
}
}
private void loadPluginResource(Plugin plugin) {
try {
AssetManager am = AssetManager.class.newInstance();
ReflectUtil.invokeMethod(ClassName.AssetManager, am, MethodName.addAssetPath,
new Class[]{String.class}, new Object[]{plugin.mFilePath});
plugin.mAssetManager = am;
Resources hostRes = context.getResources();
Resources res = new Resources(am, hostRes.getDisplayMetrics(),
hostRes.getConfiguration());
plugin.mResources = res;
} catch (Exception e) {
e.printStackTrace();
}
}
private void parsePluginPackage(Plugin plugin) {
// 这里直接copy VirtualAPK 解析插件的方法
try {
File pluginApk = new File(plugin.mFilePath);
PackageParser packageParser = new PackageParser();
PackageParser.Package pluginPackage = packageParser.parsePackage(pluginApk, PackageParser.PARSE_MUST_BE_APK);
ReflectUtil.invokeMethod(PluginConstant.ClassName.PackageParser, null, PluginConstant.MethodName.collectCertificates,
new Class[]{PackageParser.Package.class, int.class}, new Object[]{pluginPackage, PackageParser.PARSE_MUST_BE_APK});
plugin.mPackage = pluginPackage;
} catch (Exception e) {
e.printStackTrace();
}
}
}
| true |
967f0be7f5576ac040f08f5e99ebc13363d5f447 | Java | erizoo/ram_base | /src/main/java/by/boiko/crm/service/impl/SalesServiceImpl.java | UTF-8 | 789 | 2.0625 | 2 | [] | no_license | package by.boiko.crm.service.impl;
import by.boiko.crm.dao.GoodsDao;
import by.boiko.crm.model.Goods;
import by.boiko.crm.service.SalesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Service
@Transactional
public class SalesServiceImpl implements SalesService {
private final GoodsDao goodsDao;
@Autowired
public SalesServiceImpl(GoodsDao goodsDao) {
this.goodsDao = goodsDao;
}
@Override
public List<Goods> getGoods(int category) {
return goodsDao.loadGoods(category);
}
@Override
public int getCount(int category) {
return goodsDao.getCount(category);
}
}
| true |
5c3883602fe5835a6f9cd03a423c0adfc35c98ff | Java | ayumilong/Algorithm | /yz/google/codejam/Round1B2016C.java | UTF-8 | 1,954 | 3.640625 | 4 | [] | no_license | /**
* File Name: Round1B2016C.java
* Package Name: yz.google.codejam
* Project Name: Algorithm
* Purpose:
* Created Time: 12:32:18 PM Apr 30, 2016
* Author: Yaolin Zhang
*/
package yz.google.codejam;
import java.util.Scanner;
import java.util.*;
/**
* @author Yaolin Zhang
* @time 12:32:18 PM Apr 30, 2016
*/
public class Round1B2016C {
public static void main(String args[]){
Scanner scan = new Scanner(System.in);
int T = scan.nextInt();
for(int t = 1; t <= T; ++t){
int N = scan.nextInt();
scan.nextLine();
String[][] topics = new String[N][2];
for(int i = 0; i < N; ++i){
topics[i] = scan.nextLine().split(" ");
}
int count = fakeNumber(topics);
System.out.printf("Case #%d: %d\n", t, count);
}
scan.close();
}
private static int fakeNumber(String[][] topics){
HashMap<String, Integer> first = new HashMap<>();
HashMap<String, Integer> second = new HashMap<>();
for(String[] sa : topics){
if(first.containsKey(sa[0])){
first.put(sa[0], first.get(sa[0]) + 1);
}else{
first.put(sa[0], 1);
}
if(second.containsKey(sa[1])){
second.put(sa[1], second.get(sa[1]) + 1);
}else{
second.put(sa[1], 1);
}
}
for(Map.Entry<String, Integer> e : first.entrySet()){
System.out.println(e.getKey() + " " + e.getValue());
}
System.out.println();
for(Map.Entry<String, Integer> e : second.entrySet()){
System.out.println(e.getKey() + " " + e.getValue());
}
int count = 0;
for(String[] sa : topics){
if(first.get(sa[0]) >= 2 && second.get(sa[1]) >= 2){
first.put(sa[0], first.get(sa[0]) - 1);
second.put(sa[1], second.get(sa[1]) - 1);
++count;
}
}
System.out.println();
for(Map.Entry<String, Integer> e : first.entrySet()){
System.out.println(e.getKey() + " " + e.getValue());
}
System.out.println();
for(Map.Entry<String, Integer> e : second.entrySet()){
System.out.println(e.getKey() + " " + e.getValue());
}
return count;
}
}
| true |