blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
7
332
content_id
stringlengths
40
40
detected_licenses
listlengths
0
50
license_type
stringclasses
2 values
repo_name
stringlengths
7
115
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
557 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.85k
684M
star_events_count
int64
0
77.7k
fork_events_count
int64
0
48k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
82 values
src_encoding
stringclasses
28 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
7
5.41M
extension
stringclasses
11 values
content
stringlengths
7
5.41M
authors
listlengths
1
1
author
stringlengths
0
161
4b16e7bfd9437723e6b497ba1bcf52fb91bee554
6050a000fffec25e4e801af4dbc57c95e25e9ee3
/src/adventDays/DayThirteen.java
f9bfcb9b36819dc14ddfaf33d8186e3f129c66f5
[]
no_license
DBreitigan/AdventOfCode17
b8af7434622f88bf027a830a519cc5e144cfee0d
8bf33d88e1523c0cf7b6ae47a586a4868f6eb556
refs/heads/master
2021-08-29T11:48:30.013942
2017-12-13T21:42:42
2017-12-13T21:42:42
112,998,826
0
0
null
null
null
null
UTF-8
Java
false
false
4,142
java
package adventDays; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.StringTokenizer; //Day thirteen of Advert of Coding //http://adventofcode.com/2017/day/13 public class DayThirteen { private static String inputLocation = "src/inputs/DayThirteenInput"; private class FireWall { private Map<Integer, Integer> scannerLocations; private Integer scannerDepth; FireWall(Map<Integer, Integer> scannerLocations, Integer scannerDepth) { this.scannerLocations = scannerLocations; this.scannerDepth = scannerDepth; } Map<Integer, Integer> getScannerLocations() { return scannerLocations; } Integer getScannerDepth() { return scannerDepth; } } private FireWall mapStringtoIntegerMap(String inputLocation, String delimiter) { Map<Integer, Integer> map = new HashMap<>(); int maxDepth = Integer.MIN_VALUE; BufferedReader bufRdr = null; try { bufRdr = new BufferedReader(new FileReader(inputLocation)); } catch (FileNotFoundException e) { e.printStackTrace(); } String line; try { while ((line = bufRdr.readLine()) != null) { StringTokenizer st = new StringTokenizer(line, delimiter); int counter = 0; int mainInt = 0; while (st.hasMoreTokens()) { switch (counter) { case 0: mainInt = Integer.parseInt(st.nextToken().replace(":", "")); if (mainInt > maxDepth) maxDepth = mainInt; break; case 1: map.put(mainInt, Integer.parseInt(st.nextToken()) - 1); break; } counter++; } } } catch (IOException e) { e.printStackTrace(); } return new FireWall(map, maxDepth); } private int adventChallengeOne(FireWall input) { Map<Integer, Integer> fireWallLocations = input.getScannerLocations(); int severity = 0; for (int i = 0; i <= input.getScannerDepth(); i++) { int currentDepthsRange = fireWallLocations.getOrDefault(i, -1); int currentLocation; if (currentDepthsRange == -1) continue; else if (i / currentDepthsRange % 2 == 0) currentLocation = i % currentDepthsRange; else currentLocation = currentDepthsRange - (i % currentDepthsRange); if (currentLocation == 0) severity += (currentDepthsRange + 1) * i; } return severity; } private int adventChallengeTwo(FireWall input) { Map<Integer, Integer> fireWallLocations = input.getScannerLocations(); int offset = 0; while (true) { boolean found = false; for (int i = 0; i <= input.getScannerDepth(); i++) { int currentDepthsRange = fireWallLocations.getOrDefault(i, -1); int currentLocation; if (currentDepthsRange == -1) continue; else if ((i + offset) / currentDepthsRange % 2 == 0) currentLocation = (i + offset) % currentDepthsRange; else currentLocation = currentDepthsRange - ((i + offset) % currentDepthsRange); if (currentLocation == 0) { found = true; break; } } if (!found) break; offset++; } return offset; } public static void main(String[] args) { DayThirteen dayThirteen = new DayThirteen(); FireWall input = dayThirteen.mapStringtoIntegerMap(inputLocation, " "); System.out.println("Day thirteen Challenge 1: " + dayThirteen.adventChallengeOne(input)); System.out.println("Day thirteen Challenge 2: " + dayThirteen.adventChallengeTwo(input)); } }
[ "danthemanb3@gmail.com" ]
danthemanb3@gmail.com
f3296f39f2ef6d6193e3eb22cf294bbdd9dd85f6
bf7c8767ff43c5414fb25a0a26542e2305c7d6b1
/src/main/java/com/local/shortener/UrlEventService.java
56bc071bea29bb5bef8ae315626a0a290b37c2a8
[]
no_license
raymondchua98/URLShortener
4c75aa70384fc55bd2c0c6c2c469e40bfa63cff8
ee800cd6f50c118db78ff49ade32835c5dbd06cb
refs/heads/main
2023-08-21T15:16:07.479239
2021-10-13T16:29:23
2021-10-13T16:29:23
null
0
0
null
null
null
null
UTF-8
Java
false
false
427
java
package com.local.shortener; import java.util.List; public interface UrlEventService { /** * Request to create new URL event by Url and client IP * @param url * @param clientIp * @throws Exception */ void createNewUrlEvent(Url url, String clientIp) throws Exception; /** * Request to find all events by Short Code * @param shortCode * @return */ List<UrlEvent> findAllByShortCode(String shortCode); }
[ "kahhowchua.dev@gmail.com" ]
kahhowchua.dev@gmail.com
37ee681280aaa1641ace332a6276482da391a8d5
b67950ec57d6d89fc21f2a2af6e324dc752b8204
/src/server/Route.java
57040fd524ebac8bc934c3e936e114479ed46e4c
[]
no_license
AlexChung1995/IndieRecordsServer
b9010515cbe0e1c7ea32b9326407d24b7ee012b2
94a9dc830f84114314432392dc3c1c93f1bd3661
refs/heads/master
2020-04-10T21:11:02.576901
2018-03-17T00:15:12
2018-03-17T00:15:12
124,289,778
0
0
null
null
null
null
UTF-8
Java
false
false
3,098
java
package server; import java.util.Arrays; import java.util.HashMap; import java.util.Map.Entry; import java.util.function.Function; import Communications.Request; import Communications.Response; import utils.ByteUtils; public class Route { /** * Defines common RESTful function definitions * @author Anonymous * */ public static enum REST{ GET,POST,PUT } private HashMap<String,Route> router; private HashMap<String,Function<Request,Response>> functions; private Function<Request, Response> defaultFunc; /** * Class constructor * Routes are defined following classic file system tree structure in this server * @param routes a hashmap of String to Route, each String defines a child route of this route object * so if you pass a hashmap of [(one,Route);(two,Route);(three,Route)] and your current route is title "base" * you will have defined behaviour on your server at base/one, base/two, base/three * @param get the get request at this route * @param put the post request at this route * @param post the put request at this route * @param defaultFunc the default function at this route, if any of "get", "post", or "put" is null * the default func is used when you receive a request to this route */ public Route(HashMap<String,Route> routes, Function<Request, Response> get, Function <Request, Response> put, Function <Request, Response> post, Function<Request,Response> defaultFunc){ this.router = routes; this.defaultFunc = defaultFunc; this.router.put("", this);//loopback this.functions = new HashMap<String,Function<Request,Response>>(); this.functions.put("GET", get); this.functions.put("PUT", put); this.functions.put("POST", post); } /** * The function to find the route that the request has specified * @param path the path given by the request * @param pathPlace the iteration number along this path * @param request the RESTful request type ("GET", "POST, "PUT") * @return Lambda Function taking type Request and returning a type Response defined by developer */ public Function<Request,Response> route(String [] path, int pathPlace, String request) { System.out.println("path: " + Arrays.toString(path) + " pathPlace: " + pathPlace + " path.length: " + path.length + " " + request + ";"); if (pathPlace == path.length) { Function<Request,Response> func = this.functions.get(request); if (func == null) { System.out.println("no route, sending defaultFunc"); func = this.defaultFunc; } return func; }else { try { return this.router.get(path[pathPlace]).route(path, pathPlace + 1, request); } catch(NullPointerException e) { System.out.println("No such route: " + Arrays.toString(path)); return this.defaultFunc; } } } /** * toString function for Route */ public String toString() { String routeAsString = "route: {\r\n"; for (Entry<String, Function<Request,Response>> route: functions.entrySet()) { routeAsString += "\r" + route.getKey() + ": " + route.getValue() + "\r\n"; } routeAsString += "}"; return routeAsString; } }
[ "alex.chung@mail.mcgill.ca" ]
alex.chung@mail.mcgill.ca
820e947b9cdc37f4db974003399ff4e6cd977a59
73f78c49abeb38722b49e8f025b47176f91b56fa
/cine/src/main/java/cine/domain/Ocupacion.java
ed60517b8938729d582f6a2f6f55a283978b6022
[]
no_license
luciano10/Programacion-2
21f0b85f73360f49cf07e74d25d344512a1721ac
f840b6da7494fd0f9db30035c07a16385348ac21
refs/heads/master
2020-03-06T19:59:19.610575
2018-12-02T22:40:16
2018-12-02T22:40:16
127,042,445
0
0
null
null
null
null
UTF-8
Java
false
false
4,239
java
package cine.domain; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; import javax.persistence.*; import javax.validation.constraints.*; import java.io.Serializable; import java.math.BigDecimal; import java.time.ZonedDateTime; import java.util.Objects; /** * A Ocupacion. */ @Entity @Table(name = "ocupacion") @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) public class Ocupacion implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @NotNull @DecimalMin(value = "0") @Column(name = "valor", precision = 10, scale = 2, nullable = false) private BigDecimal valor; @NotNull @Column(name = "created", nullable = false) private ZonedDateTime created; @NotNull @Column(name = "updated", nullable = false) private ZonedDateTime updated; @ManyToOne @JsonIgnoreProperties("ocupacions") private Ticket ticket; @ManyToOne @JsonIgnoreProperties("ocupacions") private Entrada entrada; @ManyToOne @JsonIgnoreProperties("ocupacions") private Butaca butaca; @ManyToOne @JsonIgnoreProperties("ocupacions") private Funcion funcion; // jhipster-needle-entity-add-field - JHipster will add fields here, do not remove public Long getId() { return id; } public void setId(Long id) { this.id = id; } public BigDecimal getValor() { return valor; } public Ocupacion valor(BigDecimal valor) { this.valor = valor; return this; } public void setValor(BigDecimal valor) { this.valor = valor; } public ZonedDateTime getCreated() { return created; } public Ocupacion created(ZonedDateTime created) { this.created = created; return this; } public void setCreated(ZonedDateTime created) { this.created = created; } public ZonedDateTime getUpdated() { return updated; } public Ocupacion updated(ZonedDateTime updated) { this.updated = updated; return this; } public void setUpdated(ZonedDateTime updated) { this.updated = updated; } public Ticket getTicket() { return ticket; } public Ocupacion ticket(Ticket ticket) { this.ticket = ticket; return this; } public void setTicket(Ticket ticket) { this.ticket = ticket; } public Entrada getEntrada() { return entrada; } public Ocupacion entrada(Entrada entrada) { this.entrada = entrada; return this; } public void setEntrada(Entrada entrada) { this.entrada = entrada; } public Butaca getButaca() { return butaca; } public Ocupacion butaca(Butaca butaca) { this.butaca = butaca; return this; } public void setButaca(Butaca butaca) { this.butaca = butaca; } public Funcion getFuncion() { return funcion; } public Ocupacion funcion(Funcion funcion) { this.funcion = funcion; return this; } public void setFuncion(Funcion funcion) { this.funcion = funcion; } // jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here, do not remove @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Ocupacion ocupacion = (Ocupacion) o; if (ocupacion.getId() == null || getId() == null) { return false; } return Objects.equals(getId(), ocupacion.getId()); } @Override public int hashCode() { return Objects.hashCode(getId()); } @Override public String toString() { return "Ocupacion{" + "id=" + getId() + ", valor=" + getValor() + ", created='" + getCreated() + "'" + ", updated='" + getUpdated() + "'" + "}"; } }
[ "lucho_94_1994@hotmail.com" ]
lucho_94_1994@hotmail.com
19354e21e531fd1becfed4d17d3fcf4892707611
84e178232f16d4ffbc05b8b3c7bc9d9985f11729
/src/test/java/ph/hatch/ddd/oe/test/domain/repository/EmployeeMemRepository.java
92f87b65098ffb9af739a5406e6046d736924cab
[]
no_license
jett/d3
d6241003be16115cddef7d1c41ee2c3f347efa7f
105af7a21538e983ce27520b459c804942e05565
refs/heads/master
2021-01-01T18:29:02.394977
2019-04-24T02:31:02
2019-04-24T02:31:02
11,690,442
2
0
null
null
null
null
UTF-8
Java
false
false
614
java
package ph.hatch.ddd.oe.test.domain.repository; import ph.hatch.ddd.oe.test.domain.Employee; import ph.hatch.ddd.oe.test.domain.PersonId; import java.util.HashMap; import java.util.Map; public class EmployeeMemRepository { Map dataStore = new HashMap(); public void save(Employee employee) { dataStore.put(employee.getPersonId().toString(), employee); } public Employee load(PersonId personId) { if(dataStore.containsKey(personId.toString())) { return (Employee) dataStore.get(personId.toString()); } else { return null; } } }
[ "jettgamboa@gmail.com" ]
jettgamboa@gmail.com
2ab7f9bf2c9edd9d8badbcede1b16d700bbff655
487e1d530ef6276d43579f3c7165ae6bd58e8feb
/src/logica/Sistema.java
1497282330024116f505b9edf89268d3e35eeadf
[]
no_license
nikodius/TallerPaint
c9d2f12202002db041080e0afd3cc6f876babfca
791ba783096d3a8543e49c7c305495fc21439f61
refs/heads/master
2022-12-19T13:16:44.244915
2020-09-20T20:02:50
2020-09-20T20:02:50
295,875,065
0
0
null
null
null
null
UTF-8
Java
false
false
1,300
java
package logica; import java.awt.geom.Path2D; import java.io.File; import persistencia.DatosDTO; /** * Clase principal logica para creacion de dibujos, guardar y abrir archivos */ public class Sistema { private Dibujo dibujo; private DatosDTO datos; private Path2D lienzo; public Sistema() { this.dibujo = new Dibujo(); this.lienzo = new Path2D.Float(); } /** * Metodo para abrir dibujo de un archivo guardado * @param nombreArchivo * @throws Exception */ public void abrirArchivo(File nombreArchivo) throws Exception { //pendiente de implementar } /** * Metodo para guardar dibujo en un archivo * @param nombreArchivo * @throws Exception */ public void guardarArchivo(File nombreArchivo) throws Exception { //pendiente de implementar } public Dibujo getDibujo() { return dibujo; } public void setDibujo(Dibujo dibujo) { this.dibujo = dibujo; } public DatosDTO getDatos() { return datos; } public void setDatos(DatosDTO datos) { this.datos = datos; } public Path2D getLienzo() { return lienzo; } public void setLienzo(Path2D lienzo) { this.lienzo = lienzo; } }
[ "nicolasrg2502@gmail.com" ]
nicolasrg2502@gmail.com
3ba00db6150c4638b885940b9c1e8c8254cb44b1
21d5937efc38468712533ce42da383179d1a3310
/src/main/java/com/example/model/Doadores.java
e22f4965504af9febe74eca6dea6ca9ac19a8dd5
[]
no_license
caiohman/bd-project
90ee80df9ac2bc767ae0a422194c76408c9c1bed
459f3e312fe81de3080cb770886238fb75fd2ac0
refs/heads/main
2023-09-02T07:10:56.175418
2021-11-24T15:51:24
2021-11-24T15:51:24
430,786,741
0
1
null
null
null
null
UTF-8
Java
false
false
402
java
package com.example.model; import lombok.Data; import javax.persistence.*; import javax.validation.constraints.NotBlank; import javax.validation.constraints.Size; @Data @Entity @Table(name = "doadores") public class Doadores { @Id @JoinColumn(name = "individuos") private long cpf; @Column(name = "fonteDeRenda") @Size(max = 30) @NotBlank private String fonteDeRenda; }
[ "tc.cohman@padtec.com.br" ]
tc.cohman@padtec.com.br
e2839da216ba9f17f90ec8d36ab658729165f7e2
bb55b5dd83d4de9003752f079fd08d8d3b88e908
/src/main/java/com/berg/fastsearch/core/car/entity/Car.java
77561389d785037e56bc0a5c74028f04c5b443a9
[]
no_license
bergturing/fastsearch
d576f23fdbf1ea9ef566b8228f6bd8dbe5accf9e
54c3ff9a1666b3e79ba7676ce7164355130e4488
refs/heads/master
2021-10-10T22:03:33.184284
2019-01-18T01:57:36
2019-01-18T01:57:48
125,644,647
1
0
null
null
null
null
UTF-8
Java
false
false
6,460
java
package com.berg.fastsearch.core.car.entity; import com.berg.fastsearch.core.system.base.entity.BaseEntity; import javax.persistence.*; import java.math.BigDecimal; import java.util.Date; /** * <p>车辆对象实体</p> * * @author bergturing@qq.com * @version v1.0 * @apiNote Created on 18-5-5 */ @Table( name = "fs_cars" ) @Entity public class Car extends BaseEntity { /** * 车辆的主键 */ @Id @GeneratedValue( strategy = GenerationType.IDENTITY ) private Long id; /** * 车辆的品牌主键 */ private Long brandId; /** * 车辆的系列主键 */ private Long seriesId; /** * 发布者的id,用户表(sys_users)的主键 */ @Column private Long deployeeId; /** * 汽车的标题 */ @Column private String title; /** * 汽车的价格 */ @Column private BigDecimal price; /** * 汽车的座位数 */ @Column private Integer seats; /** * 汽车的排量 */ @Column private BigDecimal displacement; /** * 汽车的里程 */ @Column private BigDecimal mileage; /** * 车龄 */ @Column private Integer age; /** * 汽车变速箱类型,代码维护code:FS.CAR_GEAR_BOXS */ @Column private String gearBox; /** * 汽车的颜色,代码维护code:FS.CAR_COLORS */ @Column private String color; /** * 汽车的驱动类型,代码维护code:FS_CAR_DRIVE_TYPES */ @Column private String driveType; /** * 汽车的排放标准,代码维护code:FS_CAR_DMISSION_STANDARDS */ @Column private String emissionStandard; /** * 车型,代码维护code:FS_CAR_STYLES */ @Column private String style; /** * 燃油类型,代码维护code:FS_CAR_FUEL_TYPES */ @Column private String fuelType; /** * 被看次数 */ @Column private Long watchTimes; /** * 城市Id */ @Column private Long cityId; /** * 地区Id */ @Column private Long regionId; /** * 详细地址 */ @Column private String address; /** * 封面 */ @Column private String cover; /** * 汽车的状态 */ @Column private String status; /** * 描述 */ @Column private String description; /** * 汽车创建时间 */ @Column private Date createTime; /** * 上次更新记录时间 */ @Column private Date lastUpdateTime; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getBrandId() { return brandId; } public void setBrandId(Long brandId) { this.brandId = brandId; } public Long getSeriesId() { return seriesId; } public void setSeriesId(Long seriesId) { this.seriesId = seriesId; } public Long getDeployeeId() { return deployeeId; } public void setDeployeeId(Long deployeeId) { this.deployeeId = deployeeId; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public BigDecimal getPrice() { return price; } public void setPrice(BigDecimal price) { this.price = price; } public Integer getSeats() { return seats; } public void setSeats(Integer seats) { this.seats = seats; } public BigDecimal getDisplacement() { return displacement; } public void setDisplacement(BigDecimal displacement) { this.displacement = displacement; } public BigDecimal getMileage() { return mileage; } public void setMileage(BigDecimal mileage) { this.mileage = mileage; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public String getGearBox() { return gearBox; } public void setGearBox(String gearBox) { this.gearBox = gearBox; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } public String getDriveType() { return driveType; } public void setDriveType(String driveType) { this.driveType = driveType; } public String getEmissionStandard() { return emissionStandard; } public void setEmissionStandard(String emissionStandard) { this.emissionStandard = emissionStandard; } public String getStyle() { return style; } public void setStyle(String style) { this.style = style; } public String getFuelType() { return fuelType; } public void setFuelType(String fuelType) { this.fuelType = fuelType; } public Long getWatchTimes() { return watchTimes; } public void setWatchTimes(Long watchTimes) { this.watchTimes = watchTimes; } public Long getCityId() { return cityId; } public void setCityId(Long cityId) { this.cityId = cityId; } public Long getRegionId() { return regionId; } public void setRegionId(Long regionId) { this.regionId = regionId; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getCover() { return cover; } public void setCover(String cover) { this.cover = cover; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Date getLastUpdateTime() { return lastUpdateTime; } public void setLastUpdateTime(Date lastUpdateTime) { this.lastUpdateTime = lastUpdateTime; } }
[ "993450432@qq.com" ]
993450432@qq.com
68f9f4da6fc77f2614bf2a5c585e63cc628f5559
22d4d740455d1be67b1fa773f69fb0f7bad60d0b
/src/main/java/org/apache/activemq/schema/core/DtoMemoryPersistenceAdapter.java
01ffd2eb481f690d061e20b96b2e050307694866
[]
no_license
brentos/activemq-editor-plugin
727c7cc22ea82bcb2fe11bcd4e025c5132e42c10
b5fef51454dbbecebf35b472b5b55bb05268e5ba
refs/heads/master
2021-01-10T14:21:49.627745
2016-04-08T23:31:15
2016-04-08T23:31:15
54,238,215
0
0
null
null
null
null
UTF-8
Java
false
false
23,456
java
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.10-b140310.1920 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2016.04.08 at 03:50:50 PM PDT // package org.apache.activemq.schema.core; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.xml.bind.JAXBElement; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAnyAttribute; import javax.xml.bind.annotation.XmlAnyElement; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElementRef; import javax.xml.bind.annotation.XmlID; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import javax.xml.namespace.QName; import org.jvnet.jaxb2_commons.lang.Equals; import org.jvnet.jaxb2_commons.lang.EqualsStrategy; import org.jvnet.jaxb2_commons.lang.HashCode; import org.jvnet.jaxb2_commons.lang.HashCodeStrategy; import org.jvnet.jaxb2_commons.lang.JAXBHashCodeStrategy; import org.jvnet.jaxb2_commons.lang.JAXBToStringStrategy; import org.jvnet.jaxb2_commons.lang.ToString; import org.jvnet.jaxb2_commons.lang.ToStringStrategy; import org.jvnet.jaxb2_commons.locator.ObjectLocator; import org.jvnet.jaxb2_commons.locator.util.LocatorUtils; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;choice maxOccurs="unbounded" minOccurs="0"> * &lt;choice> * &lt;element name="usageManager" minOccurs="0"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;choice minOccurs="0"> * &lt;element ref="{http://activemq.apache.org/schema/core}systemUsage"/> * &lt;any namespace='##other'/> * &lt;/choice> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;any namespace='##other' maxOccurs="unbounded" minOccurs="0"/> * &lt;/choice> * &lt;/choice> * &lt;attribute name="brokerName" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;attribute name="createTransactionStore" type="{http://www.w3.org/2001/XMLSchema}boolean" /> * &lt;attribute name="directory" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;attribute name="usageManager" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;attribute name="useExternalMessageReferences" type="{http://www.w3.org/2001/XMLSchema}boolean" /> * &lt;attribute name="id" type="{http://www.w3.org/2001/XMLSchema}ID" /> * &lt;anyAttribute processContents='lax' namespace='##other'/> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "usageManagerOrAny" }) @XmlRootElement(name = "memoryPersistenceAdapter") public class DtoMemoryPersistenceAdapter implements Equals, HashCode, ToString { @XmlElementRef(name = "usageManager", namespace = "http://activemq.apache.org/schema/core", type = JAXBElement.class, required = false) @XmlAnyElement(lax = true) protected List<Object> usageManagerOrAny; @XmlAttribute(name = "brokerName") protected String brokerName; @XmlAttribute(name = "createTransactionStore") protected Boolean createTransactionStore; @XmlAttribute(name = "directory") protected String directory; @XmlAttribute(name = "usageManager") protected String usageManager; @XmlAttribute(name = "useExternalMessageReferences") protected Boolean useExternalMessageReferences; @XmlAttribute(name = "id") @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlID @XmlSchemaType(name = "ID") protected String id; @XmlAnyAttribute private Map<QName, String> otherAttributes = new HashMap<QName, String>(); /** * Gets the value of the usageManagerOrAny property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the usageManagerOrAny property. * * <p> * For example, to add a new item, do as follows: * <pre> * getUsageManagerOrAny().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link JAXBElement }{@code <}{@link DtoMemoryPersistenceAdapter.UsageManager }{@code >} * {@link Object } * * */ public List<Object> getUsageManagerOrAny() { if (usageManagerOrAny == null) { usageManagerOrAny = new ArrayList<Object>(); } return this.usageManagerOrAny; } /** * Gets the value of the brokerName property. * * @return * possible object is * {@link String } * */ public String getBrokerName() { return brokerName; } /** * Sets the value of the brokerName property. * * @param value * allowed object is * {@link String } * */ public void setBrokerName(String value) { this.brokerName = value; } /** * Gets the value of the createTransactionStore property. * * @return * possible object is * {@link Boolean } * */ public Boolean isCreateTransactionStore() { return createTransactionStore; } /** * Sets the value of the createTransactionStore property. * * @param value * allowed object is * {@link Boolean } * */ public void setCreateTransactionStore(Boolean value) { this.createTransactionStore = value; } /** * Gets the value of the directory property. * * @return * possible object is * {@link String } * */ public String getDirectory() { return directory; } /** * Sets the value of the directory property. * * @param value * allowed object is * {@link String } * */ public void setDirectory(String value) { this.directory = value; } /** * Gets the value of the usageManager property. * * @return * possible object is * {@link String } * */ public String getUsageManager() { return usageManager; } /** * Sets the value of the usageManager property. * * @param value * allowed object is * {@link String } * */ public void setUsageManager(String value) { this.usageManager = value; } /** * Gets the value of the useExternalMessageReferences property. * * @return * possible object is * {@link Boolean } * */ public Boolean isUseExternalMessageReferences() { return useExternalMessageReferences; } /** * Sets the value of the useExternalMessageReferences property. * * @param value * allowed object is * {@link Boolean } * */ public void setUseExternalMessageReferences(Boolean value) { this.useExternalMessageReferences = value; } /** * Gets the value of the id property. * * @return * possible object is * {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } /** * Gets a map that contains attributes that aren't bound to any typed property on this class. * * <p> * the map is keyed by the name of the attribute and * the value is the string value of the attribute. * * the map returned by this method is live, and you can add new attribute * by updating the map directly. Because of this design, there's no setter. * * * @return * always non-null */ public Map<QName, String> getOtherAttributes() { return otherAttributes; } public String toString() { final ToStringStrategy strategy = JAXBToStringStrategy.INSTANCE; final StringBuilder buffer = new StringBuilder(); append(null, buffer, strategy); return buffer.toString(); } public StringBuilder append(ObjectLocator locator, StringBuilder buffer, ToStringStrategy strategy) { strategy.appendStart(locator, this, buffer); appendFields(locator, buffer, strategy); strategy.appendEnd(locator, this, buffer); return buffer; } public StringBuilder appendFields(ObjectLocator locator, StringBuilder buffer, ToStringStrategy strategy) { { List<Object> theUsageManagerOrAny; theUsageManagerOrAny = (((this.usageManagerOrAny!= null)&&(!this.usageManagerOrAny.isEmpty()))?this.getUsageManagerOrAny():null); strategy.appendField(locator, this, "usageManagerOrAny", buffer, theUsageManagerOrAny); } { String theBrokerName; theBrokerName = this.getBrokerName(); strategy.appendField(locator, this, "brokerName", buffer, theBrokerName); } { Boolean theCreateTransactionStore; theCreateTransactionStore = this.isCreateTransactionStore(); strategy.appendField(locator, this, "createTransactionStore", buffer, theCreateTransactionStore); } { String theDirectory; theDirectory = this.getDirectory(); strategy.appendField(locator, this, "directory", buffer, theDirectory); } { String theUsageManager; theUsageManager = this.getUsageManager(); strategy.appendField(locator, this, "usageManager", buffer, theUsageManager); } { Boolean theUseExternalMessageReferences; theUseExternalMessageReferences = this.isUseExternalMessageReferences(); strategy.appendField(locator, this, "useExternalMessageReferences", buffer, theUseExternalMessageReferences); } { String theId; theId = this.getId(); strategy.appendField(locator, this, "id", buffer, theId); } return buffer; } public int hashCode(ObjectLocator locator, HashCodeStrategy strategy) { int currentHashCode = 1; { List<Object> theUsageManagerOrAny; theUsageManagerOrAny = (((this.usageManagerOrAny!= null)&&(!this.usageManagerOrAny.isEmpty()))?this.getUsageManagerOrAny():null); currentHashCode = strategy.hashCode(LocatorUtils.property(locator, "usageManagerOrAny", theUsageManagerOrAny), currentHashCode, theUsageManagerOrAny); } { String theBrokerName; theBrokerName = this.getBrokerName(); currentHashCode = strategy.hashCode(LocatorUtils.property(locator, "brokerName", theBrokerName), currentHashCode, theBrokerName); } { Boolean theCreateTransactionStore; theCreateTransactionStore = this.isCreateTransactionStore(); currentHashCode = strategy.hashCode(LocatorUtils.property(locator, "createTransactionStore", theCreateTransactionStore), currentHashCode, theCreateTransactionStore); } { String theDirectory; theDirectory = this.getDirectory(); currentHashCode = strategy.hashCode(LocatorUtils.property(locator, "directory", theDirectory), currentHashCode, theDirectory); } { String theUsageManager; theUsageManager = this.getUsageManager(); currentHashCode = strategy.hashCode(LocatorUtils.property(locator, "usageManager", theUsageManager), currentHashCode, theUsageManager); } { Boolean theUseExternalMessageReferences; theUseExternalMessageReferences = this.isUseExternalMessageReferences(); currentHashCode = strategy.hashCode(LocatorUtils.property(locator, "useExternalMessageReferences", theUseExternalMessageReferences), currentHashCode, theUseExternalMessageReferences); } { String theId; theId = this.getId(); currentHashCode = strategy.hashCode(LocatorUtils.property(locator, "id", theId), currentHashCode, theId); } return currentHashCode; } public int hashCode() { final HashCodeStrategy strategy = JAXBHashCodeStrategy.INSTANCE; return this.hashCode(null, strategy); } public boolean equals(ObjectLocator thisLocator, ObjectLocator thatLocator, Object object, EqualsStrategy strategy) { if (!(object instanceof DtoMemoryPersistenceAdapter)) { return false; } if (this == object) { return true; } final DtoMemoryPersistenceAdapter that = ((DtoMemoryPersistenceAdapter) object); { List<Object> lhsUsageManagerOrAny; lhsUsageManagerOrAny = (((this.usageManagerOrAny!= null)&&(!this.usageManagerOrAny.isEmpty()))?this.getUsageManagerOrAny():null); List<Object> rhsUsageManagerOrAny; rhsUsageManagerOrAny = (((that.usageManagerOrAny!= null)&&(!that.usageManagerOrAny.isEmpty()))?that.getUsageManagerOrAny():null); if (!strategy.equals(LocatorUtils.property(thisLocator, "usageManagerOrAny", lhsUsageManagerOrAny), LocatorUtils.property(thatLocator, "usageManagerOrAny", rhsUsageManagerOrAny), lhsUsageManagerOrAny, rhsUsageManagerOrAny)) { return false; } } { String lhsBrokerName; lhsBrokerName = this.getBrokerName(); String rhsBrokerName; rhsBrokerName = that.getBrokerName(); if (!strategy.equals(LocatorUtils.property(thisLocator, "brokerName", lhsBrokerName), LocatorUtils.property(thatLocator, "brokerName", rhsBrokerName), lhsBrokerName, rhsBrokerName)) { return false; } } { Boolean lhsCreateTransactionStore; lhsCreateTransactionStore = this.isCreateTransactionStore(); Boolean rhsCreateTransactionStore; rhsCreateTransactionStore = that.isCreateTransactionStore(); if (!strategy.equals(LocatorUtils.property(thisLocator, "createTransactionStore", lhsCreateTransactionStore), LocatorUtils.property(thatLocator, "createTransactionStore", rhsCreateTransactionStore), lhsCreateTransactionStore, rhsCreateTransactionStore)) { return false; } } { String lhsDirectory; lhsDirectory = this.getDirectory(); String rhsDirectory; rhsDirectory = that.getDirectory(); if (!strategy.equals(LocatorUtils.property(thisLocator, "directory", lhsDirectory), LocatorUtils.property(thatLocator, "directory", rhsDirectory), lhsDirectory, rhsDirectory)) { return false; } } { String lhsUsageManager; lhsUsageManager = this.getUsageManager(); String rhsUsageManager; rhsUsageManager = that.getUsageManager(); if (!strategy.equals(LocatorUtils.property(thisLocator, "usageManager", lhsUsageManager), LocatorUtils.property(thatLocator, "usageManager", rhsUsageManager), lhsUsageManager, rhsUsageManager)) { return false; } } { Boolean lhsUseExternalMessageReferences; lhsUseExternalMessageReferences = this.isUseExternalMessageReferences(); Boolean rhsUseExternalMessageReferences; rhsUseExternalMessageReferences = that.isUseExternalMessageReferences(); if (!strategy.equals(LocatorUtils.property(thisLocator, "useExternalMessageReferences", lhsUseExternalMessageReferences), LocatorUtils.property(thatLocator, "useExternalMessageReferences", rhsUseExternalMessageReferences), lhsUseExternalMessageReferences, rhsUseExternalMessageReferences)) { return false; } } { String lhsId; lhsId = this.getId(); String rhsId; rhsId = that.getId(); if (!strategy.equals(LocatorUtils.property(thisLocator, "id", lhsId), LocatorUtils.property(thatLocator, "id", rhsId), lhsId, rhsId)) { return false; } } return true; } public boolean equals(Object object) { final EqualsStrategy strategy = new org.apache.activemq.plugin.jaxb2_commons.ElementAwareEqualsStrategy(); return equals(null, null, object, strategy); } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;choice minOccurs="0"> * &lt;element ref="{http://activemq.apache.org/schema/core}systemUsage"/> * &lt;any namespace='##other'/> * &lt;/choice> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "systemUsage", "any" }) public static class UsageManager implements Equals, HashCode, ToString { protected DtoSystemUsage systemUsage; @XmlAnyElement(lax = true) protected Object any; /** * Gets the value of the systemUsage property. * * @return * possible object is * {@link DtoSystemUsage } * */ public DtoSystemUsage getSystemUsage() { return systemUsage; } /** * Sets the value of the systemUsage property. * * @param value * allowed object is * {@link DtoSystemUsage } * */ public void setSystemUsage(DtoSystemUsage value) { this.systemUsage = value; } /** * Gets the value of the any property. * * @return * possible object is * {@link Object } * */ public Object getAny() { return any; } /** * Sets the value of the any property. * * @param value * allowed object is * {@link Object } * */ public void setAny(Object value) { this.any = value; } public String toString() { final ToStringStrategy strategy = JAXBToStringStrategy.INSTANCE; final StringBuilder buffer = new StringBuilder(); append(null, buffer, strategy); return buffer.toString(); } public StringBuilder append(ObjectLocator locator, StringBuilder buffer, ToStringStrategy strategy) { strategy.appendStart(locator, this, buffer); appendFields(locator, buffer, strategy); strategy.appendEnd(locator, this, buffer); return buffer; } public StringBuilder appendFields(ObjectLocator locator, StringBuilder buffer, ToStringStrategy strategy) { { DtoSystemUsage theSystemUsage; theSystemUsage = this.getSystemUsage(); strategy.appendField(locator, this, "systemUsage", buffer, theSystemUsage); } { Object theAny; theAny = this.getAny(); strategy.appendField(locator, this, "any", buffer, theAny); } return buffer; } public int hashCode(ObjectLocator locator, HashCodeStrategy strategy) { int currentHashCode = 1; { DtoSystemUsage theSystemUsage; theSystemUsage = this.getSystemUsage(); currentHashCode = strategy.hashCode(LocatorUtils.property(locator, "systemUsage", theSystemUsage), currentHashCode, theSystemUsage); } { Object theAny; theAny = this.getAny(); currentHashCode = strategy.hashCode(LocatorUtils.property(locator, "any", theAny), currentHashCode, theAny); } return currentHashCode; } public int hashCode() { final HashCodeStrategy strategy = JAXBHashCodeStrategy.INSTANCE; return this.hashCode(null, strategy); } public boolean equals(ObjectLocator thisLocator, ObjectLocator thatLocator, Object object, EqualsStrategy strategy) { if (!(object instanceof DtoMemoryPersistenceAdapter.UsageManager)) { return false; } if (this == object) { return true; } final DtoMemoryPersistenceAdapter.UsageManager that = ((DtoMemoryPersistenceAdapter.UsageManager) object); { DtoSystemUsage lhsSystemUsage; lhsSystemUsage = this.getSystemUsage(); DtoSystemUsage rhsSystemUsage; rhsSystemUsage = that.getSystemUsage(); if (!strategy.equals(LocatorUtils.property(thisLocator, "systemUsage", lhsSystemUsage), LocatorUtils.property(thatLocator, "systemUsage", rhsSystemUsage), lhsSystemUsage, rhsSystemUsage)) { return false; } } { Object lhsAny; lhsAny = this.getAny(); Object rhsAny; rhsAny = that.getAny(); if (!strategy.equals(LocatorUtils.property(thisLocator, "any", lhsAny), LocatorUtils.property(thatLocator, "any", rhsAny), lhsAny, rhsAny)) { return false; } } return true; } public boolean equals(Object object) { final EqualsStrategy strategy = new org.apache.activemq.plugin.jaxb2_commons.ElementAwareEqualsStrategy(); return equals(null, null, object, strategy); } } }
[ "domenicbove@gmail.com" ]
domenicbove@gmail.com
c0268af660d47504ac2e8904542f062a27bcb825
c6a2a401e2c5f2ce44bad054d30c9b722edd9810
/src/main/java/com/buyalskaya/appliance/creator/impl/SpeakerFactory.java
cf270c7a461d3e820098616cd30c51490707ca48
[]
no_license
Julie717/Task2_1
9b9628d0327ee1fc569375018fd79340ce3c0382
870e0807a756b875819f4ef43182d5335b96451d
refs/heads/master
2022-11-28T01:43:26.271400
2020-08-09T09:57:51
2020-08-09T09:57:51
285,922,968
0
0
null
null
null
null
UTF-8
Java
false
false
1,821
java
package com.buyalskaya.appliance.creator.impl; import com.buyalskaya.appliance.creator.AbstractFactory; import com.buyalskaya.appliance.model.entity.Appliance; import com.buyalskaya.appliance.model.entity.ApplianceParameter; import com.buyalskaya.appliance.model.entity.impl.Speaker; import java.util.Map; public class SpeakerFactory implements AbstractFactory { private final static String REGEX_DASH = "-"; @Override public Appliance createAppliance(Map<ApplianceParameter, String> parameters) { Speaker speaker = new Speaker(); for (ApplianceParameter parameter : parameters.keySet()) { switch (parameter) { case POWER_CONSUMPTION: double powerConsumption = Double.parseDouble(parameters.get(parameter)); speaker.setPowerConsumption(powerConsumption); break; case NUMBER_OF_SPEAKERS: int numberOfSpeakers = Integer.parseInt(parameters.get(parameter)); speaker.setNumberOfSpeakers(numberOfSpeakers); break; case FREQUENCY_RANGE: String[] frequencies = parameters.get(parameter).split(REGEX_DASH); double startFrequencyRange = Double.parseDouble(frequencies[0]); double endFrequencyRange = Double.parseDouble(frequencies[1]); speaker.setStartFrequencyRange(startFrequencyRange); speaker.setEndFrequencyRange(endFrequencyRange); break; case CORD_LENGTH: int cordLength = Integer.parseInt(parameters.get(parameter)); speaker.setCordLength(cordLength); break; } } return speaker; } }
[ "buyalskaya.yv@gmail.com" ]
buyalskaya.yv@gmail.com
6cc536ae7274c18be7be40b014e568d02452dfbd
c43d00049fdc7ec3bc7086535aa29499b230ad3a
/app/src/main/java/com/ldl/tagview/tag2/TagGroupModel.java
9ea9f12d28ef3c29e03ad3df9cffa4085a146618
[]
no_license
LDLGH/TagView
d69067268d26ae363b9416dafad505d35e53b7d0
766d4d869f94e7e1f21396c4a9f61dc2aea06bc9
refs/heads/master
2020-04-01T17:09:33.816007
2018-10-18T06:38:18
2018-10-18T06:38:18
153,415,960
0
0
null
null
null
null
UTF-8
Java
false
false
1,324
java
package com.ldl.tagview.tag2; import java.util.ArrayList; import java.util.List; /** * author: shell * date 2016/12/30 下午3:37 **/ public class TagGroupModel { private List<Tag> tags = new ArrayList<>(); private float percentX; private float percentY; public List<Tag> getTags() { return tags; } public void setTags(List<Tag> tags) { this.tags = tags; } public float getPercentX() { return percentX; } public void setPercentX(float percentX) { this.percentX = percentX; } public float getPercentY() { return percentY; } public void setPercentY(float percentY) { this.percentY = percentY; } public static class Tag { public String name; public String link; public int direction; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getLink() { return link; } public void setLink(String link) { this.link = link; } public int getDirection() { return direction; } public void setDirection(int direction) { this.direction = direction; } } }
[ "lidelu@eyee.com" ]
lidelu@eyee.com
0a2cc95b3d0268fac6801e9958f458e42ccdc53f
383c2435aa05bcbc75f2bd7cb0bb2cb6cfaa95a7
/Logs/15_07_15/code_gen/CG_JAVA_5/java5-StaticImport2/StaticImport.java
45f0076fb75673a548cf7983049ee5be2deba19e
[]
no_license
caspar/Altova
bdfa5c74ce3e9a3dd13a761b4dd51b672a55309d
9a33bd054da513124113ebece1120761ff7e38ff
refs/heads/master
2016-08-02T22:25:20.006120
2015-07-31T09:27:15
2015-07-31T09:27:15
38,431,719
2
0
null
null
null
null
UTF-8
Java
false
false
53
java
public class StaticImport{ double r = cos(PI); }
[ "casparlant@gmail.com" ]
casparlant@gmail.com
a13857f4a91eb2d94e17b37d19756fed58812862
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/15/15_9074be33c79bc141f41e4859f5a0331e8b9ebc98/StaffController/15_9074be33c79bc141f41e4859f5a0331e8b9ebc98_StaffController_s.java
57cfe09fbcd3ce5a6a8fdaa49e774f18881863e5
[]
no_license
zhongxingyu/Seer
48e7e5197624d7afa94d23f849f8ea2075bcaec0
c11a3109fdfca9be337e509ecb2c085b60076213
refs/heads/master
2023-07-06T12:48:55.516692
2023-06-22T07:55:56
2023-06-22T07:55:56
259,613,157
6
2
null
2023-06-22T07:55:57
2020-04-28T11:07:49
null
UTF-8
Java
false
false
6,948
java
package org.motechproject.ghana.national.web; import org.motechproject.ghana.national.domain.StaffType; import org.motechproject.ghana.national.service.StaffService; import org.motechproject.ghana.national.web.form.StaffForm; import org.motechproject.ghana.national.web.helper.StaffHelper; import org.motechproject.mrs.exception.UserAlreadyExistsException; import org.motechproject.mrs.model.MRSPerson; import org.motechproject.mrs.model.MRSUser; import org.motechproject.openmrs.advice.ApiSession; import org.motechproject.openmrs.services.OpenMRSUserAdapter; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.MessageSource; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.validation.BindingResult; import org.springframework.validation.FieldError; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import javax.servlet.http.HttpServletRequest; import javax.validation.Valid; import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.Map; @Controller @RequestMapping(value = "/admin/staffs") public class StaffController { public static final String REQUESTED_STAFFS = "requestedStaffs"; private StaffService staffService; private MessageSource messageSource; private StaffHelper staffHelper; public static final String STAFF_ID = "userId"; public static final String STAFF_SEQUENTIAL_ID = "Id"; public static final String STAFF_NAME = "userName"; public static final String EMAIL = "newEmail"; public static final String STAFF_FORM = "staffForm"; public static final String STAFF_ALREADY_EXISTS = "user_email_already_exists"; public static final String NEW_STAFF_URL = "staffs/new"; public static final String SEARCH_STAFF = "staffs/search"; public static final String EDIT_STAFF_URL = "staffs/edit"; public StaffController() { } @Autowired public StaffController(StaffService staffService, MessageSource messageSource, StaffHelper staffHelper) { this.staffService = staffService; this.messageSource = messageSource; this.staffHelper = staffHelper; } @ApiSession @RequestMapping(value = "new", method = RequestMethod.GET) public String newStaff(ModelMap modelMap) { modelMap.addAttribute(STAFF_FORM, new StaffForm()); staffHelper.populateRoles(modelMap, staffService.fetchAllRoles()); return NEW_STAFF_URL; } @ApiSession @RequestMapping(value = "create", method = RequestMethod.POST) public String create(@Valid StaffForm staffForm, BindingResult bindingResult, ModelMap modelMap) { try { MRSUser openMRSUser = staffService.saveUser(staffForm.createUser()); modelMap.put(STAFF_ID, openMRSUser.getSystemId()); modelMap.put(STAFF_NAME, openMRSUser.getPerson().getFullName()); modelMap.put("successMessage", "Staff created successfully.Email with login credentials sent (to admin users only)."); staffHelper.populateRoles(modelMap, staffService.fetchAllRoles()); return staffHelper.getStaffForId(modelMap, openMRSUser); } catch (UserAlreadyExistsException e) { handleUserAlreadyExistsError(modelMap, bindingResult); return NEW_STAFF_URL; } } @ApiSession @RequestMapping(value = "edit", method = RequestMethod.GET) public String edit(ModelMap modelMap, HttpServletRequest httpServletRequest) { String staffId = httpServletRequest.getParameter(STAFF_SEQUENTIAL_ID); staffHelper.populateRoles(modelMap, staffService.fetchAllRoles()); return staffHelper.getStaffForId(modelMap, staffService.getUserByEmailIdOrMotechId(staffId)); } @ApiSession @RequestMapping(value = "update", method = RequestMethod.POST) public String update(@Valid StaffForm staffForm, BindingResult bindingResult, ModelMap modelMap) { MRSUser mrsUser = staffForm.createUser(); if (!staffForm.getCurrentEmail().equals(staffForm.getNewEmail()) && staffService.getUserByEmailIdOrMotechId(staffForm.getNewEmail()) != null) { handleUserAlreadyExistsError(modelMap, bindingResult); return NEW_STAFF_URL; } Map userData = staffService.updateUser(mrsUser); final MRSUser openMRSUser = (MRSUser) userData.get(OpenMRSUserAdapter.USER_KEY); if (StaffType.Role.isAdmin(staffForm.getNewRole()) && !staffForm.getNewRole().equals(staffForm.getCurrentRole())) { staffService.changePasswordByEmailId(staffForm.getNewEmail()); } staffHelper.populateRoles(modelMap, staffService.fetchAllRoles()); staffHelper.getStaffForId(modelMap, openMRSUser); modelMap.put("successMessage", "Staff edited successfully.Email with login credentials sent (to admin users only)."); return EDIT_STAFF_URL; } @ApiSession @RequestMapping(value = "search", method = RequestMethod.GET) public String search(ModelMap modelMap) { modelMap.put(STAFF_FORM, new StaffForm()); staffHelper.populateRoles(modelMap, staffService.fetchAllRoles()); return SEARCH_STAFF; } @ApiSession @RequestMapping(value = "searchStaffs", method = RequestMethod.POST) public String search(@Valid final StaffForm staffForm, ModelMap modelMap) { final List<MRSUser> mrsUsers = staffService.searchStaff(staffForm.getStaffId(), staffForm.getFirstName(), staffForm.getMiddleName(), staffForm.getLastName(), staffForm.getPhoneNumber(), staffForm.getNewRole()); final ArrayList<StaffForm> staffForms = new ArrayList<StaffForm>(); for (MRSUser mrsUser : mrsUsers) { MRSPerson mrsPerson = mrsUser.getPerson(); staffForms.add(new StaffForm(mrsUser.getId(), mrsUser.getSystemId(), mrsPerson.getFirstName(), mrsPerson.getMiddleName(), mrsPerson.getLastName(), staffHelper.getEmail(mrsUser), staffHelper.getPhoneNumber(mrsUser), staffHelper.getRole(mrsUser), null, null)); } modelMap.put(STAFF_FORM, new StaffForm()); modelMap.put(REQUESTED_STAFFS, staffForms); staffHelper.populateRoles(modelMap, staffService.fetchAllRoles()); return SEARCH_STAFF; } private void handleUserAlreadyExistsError(ModelMap modelMap, BindingResult bindingResult) { bindingResult.addError(new FieldError(STAFF_FORM, EMAIL, messageSource.getMessage(STAFF_ALREADY_EXISTS, null, Locale.getDefault()))); staffHelper.populateRoles(modelMap, staffService.fetchAllRoles()); modelMap.mergeAttributes(bindingResult.getModel()); } }
[ "yuzhongxing88@gmail.com" ]
yuzhongxing88@gmail.com
5dc417cbe59fd42fbd0d2e750ee1d02da2d61740
ffe0ea2a467e12ce661497150692faa9758225f7
/JiJianYunFa/Communication_yw_z39v_01/app/src/main/java/com/lzkj/aidlservice/push/HandlerPushCommand.java
532ae4c60a17ff13d5139b122782e695139eb364
[]
no_license
changjigang52084/Mark-s-Project
cc1be3e3e4d2b5d0d7d48b8decbdb0c054b742b7
8e82a8c3b1d75d00a70cf54838f3a91411ff1d16
refs/heads/master
2022-12-31T01:21:42.822825
2020-10-13T10:24:58
2020-10-13T10:24:58
303,652,140
1
1
null
null
null
null
UTF-8
Java
false
false
1,308
java
package com.lzkj.aidlservice.push; import android.content.Intent; import com.lzkj.aidlservice.push.handler.PushHandler; /** * @author kchang Email:changkai@lz-mr.com * @version 1.0 * @date 创建时间:2015年6月3日 上午11:06:13 * @parameter 处理推送命令的类 */ public class HandlerPushCommand { private HandlerPushCommand() { } public static HandlerPushCommand getInstance() { return HandlerPushCommandInstand.handlerPushCommand; } private static class HandlerPushCommandInstand { private static final HandlerPushCommand handlerPushCommand = new HandlerPushCommand(); } /** * 处理穿透消息 * * @param intent 包含的穿透数据的intent对象 * @param cls 处理消息的类 GeTuiPusherHandler.class */ public void handlerPayLoadMes(Intent intent, Class<? extends PushHandler> cls) { try { PushHandler pushHandler = (PushHandler) Class.forName(cls.getName()).newInstance(); pushHandler.handlerPerspective(intent); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } }
[ "451861975@qq.com" ]
451861975@qq.com
861d00b96a23ee1bfe19b19e0a479cfa54f2a73a
ac987c871d69e86bbd5c87ad106c2413feecd578
/asistenciaweb/src/main/java/pe/edu/uni/fiis/cuarta/asistenciaweb/dao/AsistenciaDatasource.java
8148aca18a7972e03fde90c902e4b73c5c470058
[]
no_license
miguel199826/Telsur1.0
983ad370b07de244db8761d7e6b9f9c098e14077
a13f4429dd790f320e873fccd5b187b33bd5080e
refs/heads/master
2020-04-17T16:01:20.431253
2019-02-15T01:02:04
2019-02-15T01:02:04
166,723,161
0
0
null
null
null
null
UTF-8
Java
false
false
751
java
package pe.edu.uni.fiis.cuarta.asistenciaweb.dao; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.sql.DataSource; import java.sql.Connection; import java.sql.SQLException; abstract class AsistenciaDatasource { public static Connection getConection(){ InitialContext context = null; Connection connection = null; try { context = new InitialContext(); DataSource ds = (DataSource) context.lookup("java:/comp/env/jdbc/asistencia"); connection = ds.getConnection(); } catch (NamingException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } return connection; } }
[ "miguel199826@gmail.com" ]
miguel199826@gmail.com
890b99376c186c4db494aac2dde2627d6aac3338
e40274a2ab72849b80a4d695c5907ff2713a6a32
/src/main/java/com/stoop/api/entities/User.java
e9c81393e7c70919fb5bca76e822ab842d9c7b7a
[]
no_license
maxwellknoxx/StoopCar
31fe2fa487e3fb90d918dab22c525e7aebc0942f
b167f405c3e42714f7a0924b5d970df870156635
refs/heads/master
2020-03-27T09:22:25.028237
2019-03-12T15:27:21
2019-03-12T15:27:21
146,335,189
0
0
null
null
null
null
UTF-8
Java
false
false
1,113
java
package com.stoop.api.entities; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import com.stoop.api.enums.Role; @Entity @Table(name = "user") public class User { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @Column(nullable = false) private String user; @Column(nullable = false) private String password; @Enumerated(EnumType.STRING) @Column(nullable = false) private Role roleEnum; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getUser() { return user; } public void setUser(String user) { this.user = user; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Role getRoleEnum() { return roleEnum; } public void setRoleEnum(Role roleEnum) { this.roleEnum = roleEnum; } }
[ "maxwell.knoxx@live.com" ]
maxwell.knoxx@live.com
2d2d909ca3bdbee673bc54e2eded259f7856ca46
debd4f3559ab31a2c52f3df5d16db6c52812e961
/airlinerecovery_lastfight/src/sghku/tianchi/IntelligentAviation/algorithm/NetworkConstructor.java
8ac5c4aa43df419899be90942ad6ffd0159293eb
[]
no_license
zdpony/airline_lastfight
dfb23969e414404c3250b8061caec57194a189c4
2fa695745a89021e65a4d41c4b63fd37040c1cf5
refs/heads/master
2021-01-22T07:42:29.604454
2017-09-04T11:16:18
2017-09-04T11:16:18
102,310,994
0
0
null
null
null
null
UTF-8
Java
false
false
42,277
java
package sghku.tianchi.IntelligentAviation.algorithm; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Scanner; import java.util.Set; import java.util.concurrent.SynchronousQueue; import sghku.tianchi.IntelligentAviation.common.Parameter; import sghku.tianchi.IntelligentAviation.comparator.NodeComparator; import sghku.tianchi.IntelligentAviation.entity.Aircraft; import sghku.tianchi.IntelligentAviation.entity.Airport; import sghku.tianchi.IntelligentAviation.entity.ConnectingArc; import sghku.tianchi.IntelligentAviation.entity.Failure; import sghku.tianchi.IntelligentAviation.entity.FailureType; import sghku.tianchi.IntelligentAviation.entity.Flight; import sghku.tianchi.IntelligentAviation.entity.FlightArc; import sghku.tianchi.IntelligentAviation.entity.FlightSection; import sghku.tianchi.IntelligentAviation.entity.GroundArc; import sghku.tianchi.IntelligentAviation.entity.Leg; import sghku.tianchi.IntelligentAviation.entity.ConnectingFlightpair; import sghku.tianchi.IntelligentAviation.entity.Node; import sghku.tianchi.IntelligentAviation.entity.ParkingInfo; import sghku.tianchi.IntelligentAviation.entity.Scenario; import sghku.tianchi.IntelligentAviation.entity.TransferPassenger; /** * @author ych * Construct a feasible route (a sequence of flights) for all aircraft * */ public class NetworkConstructor { //第一种生成方法,根据原始schedule大范围生成arc public List<FlightArc> generateArcForFlight(Aircraft aircraft, Flight f, int givenGap, Scenario scenario){ List<FlightArc> generatedFlightArcList = new ArrayList<>(); int presetGap = 5; FlightArc arc = null; if(!f.isIncludedInTimeWindow) { //因为在调整窗口外,不存在单独的联程航班 //if(!f.isIncludedInConnecting){ //如果该航班在调整时间窗口外 if(f.initialAircraft.id == aircraft.id) { arc = new FlightArc(); arc.flight = f; arc.aircraft = aircraft; arc.delay = f.fixedTakeoffTime - f.initialTakeoffT; /*arc.takeoffTime = f.initialTakeoffT+arc.delay; arc.landingTime = arc.takeoffTime+flyTime;*/ arc.takeoffTime = f.fixedTakeoffTime; arc.landingTime = f.fixedLandingTime; arc.readyTime = arc.landingTime + (f.isShortConnection?f.shortConnectionTime:Parameter.MIN_BUFFER_TIME); f.flightarcList.add(arc); aircraft.flightArcList.add(arc); arc.calculateCost(scenario); generatedFlightArcList.add(arc); if(f.leg.destinationAirport.id == 25 && arc.landingTime <= Parameter.airport25_67ParkingLimitStart && arc.readyTime >= Parameter.airport25_67ParkingLimitEnd){ scenario.airport25ParkingFlightArcList.add(arc); } if(f.leg.destinationAirport.id == 67 && arc.landingTime <= Parameter.airport25_67ParkingLimitStart && arc.readyTime >= Parameter.airport25_67ParkingLimitEnd){ scenario.airport67ParkingFlightArcList.add(arc); } } //} }else { //2.1 check whether f can be brought forward and generate earliness arcs int nnn = 0; int startIndex = 0; int endIndex = 0; if(f.isDeadhead) { //如果是调机航班,则只能小范围延误 endIndex = Parameter.NORMAL_DELAY_TIME/presetGap; }else { if(f.isAffected){ //在scenario里根据input预判断,缩小了solution space if(f.isDomestic){ endIndex = Parameter.MAX_DELAY_DOMESTIC_TIME/presetGap; }else{ endIndex = Parameter.MAX_DELAY_INTERNATIONAL_TIME/presetGap; } }else{ endIndex = Parameter.NORMAL_DELAY_TIME/presetGap; } } if(f.isAllowtoBringForward){ startIndex = Parameter.MAX_LEAD_TIME/presetGap; } int flyTime = f.flyTime; if(f.isDeadhead) { flyTime = f.leg.flytimeArray[aircraft.type-1]; }else if(f.isStraightened) { flyTime = f.leg.flytimeArray[aircraft.type-1]; if(flyTime <= 0) { flyTime = f.connectingFlightpair.firstFlight.initialLandingT-f.connectingFlightpair.firstFlight.initialTakeoffT + f.connectingFlightpair.secondFlight.initialLandingT-f.connectingFlightpair.secondFlight.initialTakeoffT; } } for(int i=-startIndex;i<=endIndex;i++){ boolean isOriginInAffectedLdnTkfLimitPeriod = false; boolean isDestinationInAffectedLdnTkfLimitPeriod = false; if(scenario.affectedAirportSet.contains(f.leg.originAirport.id)) { int tkfTime = f.initialTakeoffT + i*presetGap; if((tkfTime >= Parameter.airportBeforeTyphoonTimeWindowStart && tkfTime <= Parameter.airportBeforeTyphoonTimeWindowEnd) || (tkfTime >= Parameter.airportAfterTyphoonTimeWindowStart && tkfTime <= Parameter.airportAfterTyphoonTimeWindowEnd)) { isOriginInAffectedLdnTkfLimitPeriod = true; } }else if(scenario.affectedAirportSet.contains(f.leg.destinationAirport.id)) { int ldnTime = f.initialLandingT + i*presetGap; if((ldnTime >= Parameter.airportBeforeTyphoonTimeWindowStart && ldnTime <= Parameter.airportBeforeTyphoonTimeWindowEnd) || (ldnTime >= Parameter.airportAfterTyphoonTimeWindowStart && ldnTime <= Parameter.airportAfterTyphoonTimeWindowEnd)) { isDestinationInAffectedLdnTkfLimitPeriod = true; } } if((i*presetGap)%givenGap != 0){ //小gap,只有当其受影响时才继续生成相应arc if(!isOriginInAffectedLdnTkfLimitPeriod && !isDestinationInAffectedLdnTkfLimitPeriod){ continue; } } arc = new FlightArc(); arc.flight = f; arc.aircraft = aircraft; if(i < 0) { arc.earliness = -i*presetGap; }else { arc.delay = i*presetGap; } arc.takeoffTime = f.initialTakeoffT+i*presetGap; arc.landingTime = arc.takeoffTime+flyTime; //arc.readyTime = arc.landingTime + Parameter.MIN_BUFFER_TIME; arc.readyTime = arc.landingTime + (f.isShortConnection?f.shortConnectionTime:Parameter.MIN_BUFFER_TIME); if(!arc.checkViolation()){ //如果是调剂航班,不需要做任何处理 if(f.isDeadhead) { }else if(f.isStraightened) { //如果是联程拉直,将该arc加到对应的两段航班中 f.connectingFlightpair.firstFlight.flightarcList.add(arc); f.connectingFlightpair.secondFlight.flightarcList.add(arc); //联程拉直航班则没有对应的flight section //联程拉直乘客容量 arc.passengerCapacity = aircraft.passengerCapacity; //要减去对应的联程乘客 arc.passengerCapacity = arc.passengerCapacity - f.connectedPassengerNumber; //其他乘客全部被取消,所以不需要考虑 arc.passengerCapacity = Math.max(0, arc.passengerCapacity); }else { f.flightarcList.add(arc); //将该arc加入到对应的flight section中 boolean isFound = false; for(FlightSection currentFlightSection:f.flightSectionList) { if(arc.takeoffTime >= currentFlightSection.startTime && arc.takeoffTime < currentFlightSection.endTime) { isFound = true; currentFlightSection.flightArcList.add(arc); if(currentFlightSection.startTime == 10930 && currentFlightSection.endTime == 11090){ nnn++; } break; } } if(!isFound) { //check 是否每个arc都放进了一个section if(f.flightSectionList.get(f.flightSectionList.size()-1).endTime != arc.takeoffTime) { System.out.println("no flight section found 3!"+f.flightSectionList.get(f.flightSectionList.size()-1).endTime+" "+arc.takeoffTime); System.exit(1); } f.flightSectionList.get(f.flightSectionList.size()-1).flightArcList.add(arc); } //乘客容量 arc.passengerCapacity = aircraft.passengerCapacity; //减去转乘乘客 arc.passengerCapacity = arc.passengerCapacity - f.occupiedSeatsByTransferPassenger; //如果该航班是联程航班,则代表联程航班已经被取消,所以不需要在考虑对应的联程乘客 //剩下的则为有效座位 arc.passengerCapacity = Math.max(0, arc.passengerCapacity); if(Parameter.onlySignChangeDisruptedPassenger){ //减去普通乘客 arc.passengerCapacity = arc.passengerCapacity - f.normalPassengerNumber; }else{ // 减去普通乘客 arc.fulfilledNormalPassenger = Math.min(arc.passengerCapacity, f.normalPassengerNumber); arc.passengerCapacity = arc.passengerCapacity - arc.fulfilledNormalPassenger; arc.flight.itinerary.flightArcList.add(arc); } //剩下的则为有效座位 arc.passengerCapacity = Math.max(0, arc.passengerCapacity); } arc.calculateCost(scenario); aircraft.flightArcList.add(arc); generatedFlightArcList.add(arc); //加入对应的起降时间点 if(isOriginInAffectedLdnTkfLimitPeriod) { int tkfTime = f.initialTakeoffT + i*presetGap; List<FlightArc> faList = scenario.airportTimeFlightArcMap.get(f.leg.originAirport.id+"_"+tkfTime); faList.add(arc); }else if(isDestinationInAffectedLdnTkfLimitPeriod){ int ldnTime = f.initialLandingT + i*presetGap; List<FlightArc> faList = scenario.airportTimeFlightArcMap.get(f.leg.destinationAirport.id+"_"+ldnTime); faList.add(arc); } //加入停机约束 if(f.leg.destinationAirport.id == 25 && arc.landingTime <= Parameter.airport25_67ParkingLimitStart && arc.readyTime >= Parameter.airport25_67ParkingLimitEnd){ scenario.airport25ParkingFlightArcList.add(arc); } if(f.leg.destinationAirport.id == 67 && arc.landingTime <= Parameter.airport25_67ParkingLimitStart && arc.readyTime >= Parameter.airport25_67ParkingLimitEnd){ scenario.airport67ParkingFlightArcList.add(arc); } } } if(f.id == 1333){ System.out.println("nnn:"+nnn); } } return generatedFlightArcList; } //根据fix的schedule来 public List<FlightArc> generateArcForFlightBasedOnFixedSchedule(Aircraft aircraft, Flight f, Scenario scenario){ List<FlightArc> generatedFlightArcList = new ArrayList<>(); int presetGap = 5; FlightArc arc = null; arc = new FlightArc(); arc.flight = f; arc.aircraft = aircraft; if(f.actualTakeoffT - f.initialTakeoffT < 0){ arc.earliness = f.initialTakeoffT - f.actualTakeoffT; }else{ arc.delay = f.actualTakeoffT - f.initialTakeoffT; } /*arc.takeoffTime = f.initialTakeoffT+arc.delay; arc.landingTime = arc.takeoffTime+flyTime;*/ arc.takeoffTime = f.actualTakeoffT; arc.landingTime = f.actualLandingT; arc.readyTime = arc.landingTime + (f.isShortConnection?f.shortConnectionTime:Parameter.MIN_BUFFER_TIME); f.flightarcList.add(arc); aircraft.flightArcList.add(arc); arc.calculateCost(scenario); generatedFlightArcList.add(arc); //加入对应的起降时间点 boolean isOriginInAffectedLdnTkfLimitPeriod = false; boolean isDestinationInAffectedLdnTkfLimitPeriod = false; if(scenario.affectedAirportSet.contains(f.leg.originAirport.id)) { int tkfTime = arc.takeoffTime; if((tkfTime >= Parameter.airportBeforeTyphoonTimeWindowStart && tkfTime <= Parameter.airportBeforeTyphoonTimeWindowEnd) || (tkfTime >= Parameter.airportAfterTyphoonTimeWindowStart && tkfTime <= Parameter.airportAfterTyphoonTimeWindowEnd)) { isOriginInAffectedLdnTkfLimitPeriod = true; } }else if(scenario.affectedAirportSet.contains(f.leg.destinationAirport.id)) { int ldnTime = arc.landingTime; if((ldnTime >= Parameter.airportBeforeTyphoonTimeWindowStart && ldnTime <= Parameter.airportBeforeTyphoonTimeWindowEnd) || (ldnTime >= Parameter.airportAfterTyphoonTimeWindowStart && ldnTime <= Parameter.airportAfterTyphoonTimeWindowEnd)) { isDestinationInAffectedLdnTkfLimitPeriod = true; } } if(isOriginInAffectedLdnTkfLimitPeriod) { int tkfTime = arc.takeoffTime; List<FlightArc> faList = scenario.airportTimeFlightArcMap.get(f.leg.originAirport.id+"_"+tkfTime); faList.add(arc); }else if(isDestinationInAffectedLdnTkfLimitPeriod){ int ldnTime = arc.landingTime; List<FlightArc> faList = scenario.airportTimeFlightArcMap.get(f.leg.destinationAirport.id+"_"+ldnTime); faList.add(arc); } //加入停机约束 if(f.leg.destinationAirport.id == 25 && arc.landingTime <= Parameter.airport25_67ParkingLimitStart && arc.readyTime >= Parameter.airport25_67ParkingLimitEnd){ scenario.airport25ParkingFlightArcList.add(arc); } if(f.leg.destinationAirport.id == 67 && arc.landingTime <= Parameter.airport25_67ParkingLimitStart && arc.readyTime >= Parameter.airport25_67ParkingLimitEnd){ scenario.airport67ParkingFlightArcList.add(arc); } return generatedFlightArcList; } public List<ConnectingArc> generateArcForConnectingFlightPair(Aircraft aircraft, ConnectingFlightpair cf, int givenGap, boolean isGenerateArcForEachFlight, Scenario scenario){ List<ConnectingArc> generatedConnectingArcList = new ArrayList<>(); int presetGap = 5; int connectionTime = Math.min(cf.secondFlight.initialTakeoffT-cf.firstFlight.initialLandingT, Parameter.MIN_BUFFER_TIME); List<FlightArc> firstFlightArcList = new ArrayList<>(); List<ConnectingArc> connectingArcList = new ArrayList<>(); //如果该联程航班在调整窗口之外 if(!cf.firstFlight.isIncludedInTimeWindow) { if(cf.firstFlight.initialAircraft.id == aircraft.id) { //构建第一个flight arc FlightArc firstArc = new FlightArc(); firstArc.flight = cf.firstFlight; firstArc.aircraft = aircraft; firstArc.delay = cf.firstFlight.fixedTakeoffTime - cf.firstFlight.initialTakeoffT; firstArc.takeoffTime = cf.firstFlight.initialTakeoffT+firstArc.delay; firstArc.landingTime = firstArc.takeoffTime+cf.firstFlight.flyTime; firstArc.readyTime = firstArc.landingTime + connectionTime; //构建第二个flight arc FlightArc secondArc = new FlightArc(); secondArc.flight = cf.secondFlight; secondArc.aircraft = aircraft; secondArc.delay = cf.secondFlight.fixedTakeoffTime - cf.secondFlight.initialTakeoffT; secondArc.takeoffTime = cf.secondFlight.initialTakeoffT+secondArc.delay; secondArc.landingTime = secondArc.takeoffTime+cf.secondFlight.flyTime; secondArc.readyTime = secondArc.landingTime + (cf.secondFlight.isShortConnection?cf.secondFlight.shortConnectionTime:Parameter.MIN_BUFFER_TIME); ConnectingArc ca = new ConnectingArc(); ca.firstArc = firstArc; ca.secondArc = secondArc; ca.aircraft = aircraft; aircraft.connectingArcList.add(ca); cf.firstFlight.connectingarcList.add(ca); cf.secondFlight.connectingarcList.add(ca); ca.connectingFlightPair = cf; ca.calculateCost(scenario); generatedConnectingArcList.add(ca); //加入25和67停机约束 if(cf.firstFlight.leg.destinationAirport.id == 25 && ca.firstArc.landingTime <= Parameter.airport25_67ParkingLimitStart && ca.secondArc.takeoffTime >= Parameter.airport25_67ParkingLimitEnd){ scenario.airport25ClosureConnectingArcList.add(ca); } if(cf.firstFlight.leg.destinationAirport.id == 67 && ca.firstArc.landingTime <= Parameter.airport25_67ParkingLimitStart && ca.secondArc.takeoffTime >= Parameter.airport25_67ParkingLimitEnd){ scenario.airport25ClosureConnectingArcList.add(ca); } } }else { //otherwise, create a set of connecting arcs for this connecting flight if(!aircraft.tabuLegs.contains(cf.firstFlight.leg) && !aircraft.tabuLegs.contains(cf.secondFlight.leg)){ //only if this leg is not in the tabu list of the corresponding aircraft FlightArc arc = null; //2.1 check whether f can be brought forward and generate earliness arcs int startIndex = 0; if(cf.firstFlight.isAllowtoBringForward){ startIndex = Parameter.MAX_LEAD_TIME/presetGap; } //2.3 generate delay arcs int endIndex = 0; if(cf.isAffected){ if(cf.firstFlight.isDomestic){ endIndex = Parameter.MAX_DELAY_DOMESTIC_TIME/presetGap; }else{ endIndex = Parameter.MAX_DELAY_INTERNATIONAL_TIME/presetGap; } }else{ endIndex = Parameter.NORMAL_DELAY_TIME/presetGap; } for(int i=-startIndex;i<=endIndex;i++){ boolean isOriginInAffectedLdnTkfPeriod = false; boolean isDestinationInAffectedLdnTkfPeriod = false; if(scenario.affectedAirportSet.contains(cf.firstFlight.leg.originAirport.id)) { int tkfTime = cf.firstFlight.initialTakeoffT + i*presetGap; if((tkfTime >= Parameter.airportBeforeTyphoonTimeWindowStart && tkfTime <= Parameter.airportBeforeTyphoonTimeWindowEnd) || (tkfTime >= Parameter.airportAfterTyphoonTimeWindowStart && tkfTime <= Parameter.airportAfterTyphoonTimeWindowEnd)) { isOriginInAffectedLdnTkfPeriod = true; } }else if(scenario.affectedAirportSet.contains(cf.firstFlight.leg.destinationAirport.id)) { int ldnTime = cf.firstFlight.initialLandingT + i*presetGap; if((ldnTime >= Parameter.airportBeforeTyphoonTimeWindowStart && ldnTime <= Parameter.airportBeforeTyphoonTimeWindowEnd) || (ldnTime >= Parameter.airportAfterTyphoonTimeWindowStart && ldnTime <= Parameter.airportAfterTyphoonTimeWindowEnd)) { isDestinationInAffectedLdnTkfPeriod = true; } } if((i*presetGap)%givenGap != 0){ if(!isOriginInAffectedLdnTkfPeriod && !isDestinationInAffectedLdnTkfPeriod){ continue; } } arc = new FlightArc(); arc.flight = cf.firstFlight; arc.aircraft = aircraft; if(i < 0) { arc.earliness = -i*presetGap; }else { arc.delay = i*presetGap; } arc.takeoffTime = cf.firstFlight.initialTakeoffT+i*presetGap; arc.landingTime = arc.takeoffTime+cf.firstFlight.flyTime; arc.readyTime = arc.landingTime + connectionTime; if(!arc.checkViolation()){ firstFlightArcList.add(arc); arc.isWithinAffectedRegionOrigin = isOriginInAffectedLdnTkfPeriod; arc.isWithinAffectedRegionDestination = isDestinationInAffectedLdnTkfPeriod; } } } for(FlightArc firstArc:firstFlightArcList){ if(cf.secondFlight.isAllowtoBringForward){ int startIndex = Parameter.MAX_LEAD_TIME/presetGap; for(int i=startIndex;i>0;i--){ boolean isWithinAffectedRegionOrigin2 = false; boolean isWithinAffectedRegionDestination2 = false; if(scenario.affectedAirportSet.contains(cf.secondFlight.leg.originAirport.id)) { int t = cf.secondFlight.initialTakeoffT + i*presetGap; if((t >= Parameter.airportBeforeTyphoonTimeWindowStart && t <= Parameter.airportBeforeTyphoonTimeWindowEnd) || (t >= Parameter.airportAfterTyphoonTimeWindowStart && t <= Parameter.airportAfterTyphoonTimeWindowEnd)) { isWithinAffectedRegionOrigin2 = true; } }else if(scenario.affectedAirportSet.contains(cf.secondFlight.leg.destinationAirport.id)) { int t = cf.secondFlight.initialLandingT + i*presetGap; if((t >= Parameter.airportBeforeTyphoonTimeWindowStart && t <= Parameter.airportBeforeTyphoonTimeWindowEnd) || (t >= Parameter.airportAfterTyphoonTimeWindowStart && t <= Parameter.airportAfterTyphoonTimeWindowEnd)) { isWithinAffectedRegionDestination2 = true; } } if((i*presetGap)%givenGap != 0){ if(!isWithinAffectedRegionOrigin2 && !isWithinAffectedRegionDestination2){ continue; } } if(cf.secondFlight.initialTakeoffT-presetGap*i >= firstArc.readyTime){ FlightArc secondArc = new FlightArc(); secondArc.flight = cf.secondFlight; secondArc.aircraft = aircraft; secondArc.earliness = i*presetGap; secondArc.takeoffTime = cf.secondFlight.initialTakeoffT-secondArc.earliness; secondArc.landingTime = secondArc.takeoffTime+cf.secondFlight.flyTime; secondArc.readyTime = secondArc.landingTime + (cf.secondFlight.isShortConnection?cf.secondFlight.shortConnectionTime:Parameter.MIN_BUFFER_TIME); secondArc.isWithinAffectedRegionOrigin = isWithinAffectedRegionOrigin2; secondArc.isWithinAffectedRegionDestination = isWithinAffectedRegionDestination2; if(!secondArc.checkViolation()){ ConnectingArc ca = new ConnectingArc(); ca.firstArc = firstArc; ca.secondArc = secondArc; ca.aircraft = aircraft; aircraft.connectingArcList.add(ca); cf.firstFlight.connectingarcList.add(ca); cf.secondFlight.connectingarcList.add(ca); ca.connectingFlightPair = cf; connectingArcList.add(ca); ca.calculateCost(scenario); generatedConnectingArcList.add(ca); } } } } int endIndex = 0; if(cf.isAffected){ if(cf.secondFlight.isDomestic){ endIndex = Parameter.MAX_DELAY_DOMESTIC_TIME/presetGap; }else{ endIndex = Parameter.MAX_DELAY_INTERNATIONAL_TIME/presetGap; } }else{ endIndex = Parameter.NORMAL_DELAY_TIME/presetGap; } for(int i=0;i<=endIndex;i++){ boolean isWithinAffectedRegionOrigin2 = false; boolean isWithinAffectedRegionDestination2 = false; if(scenario.affectedAirportSet.contains(cf.secondFlight.leg.originAirport.id)) { int t = cf.secondFlight.initialTakeoffT + i*presetGap; if((t >= Parameter.airportBeforeTyphoonTimeWindowStart && t <= Parameter.airportBeforeTyphoonTimeWindowEnd) || (t >= Parameter.airportAfterTyphoonTimeWindowStart && t <= Parameter.airportAfterTyphoonTimeWindowEnd)) { isWithinAffectedRegionOrigin2 = true; } }else if(scenario.affectedAirportSet.contains(cf.secondFlight.leg.destinationAirport.id)) { int t = cf.secondFlight.initialLandingT + i*presetGap; if((t >= Parameter.airportBeforeTyphoonTimeWindowStart && t <= Parameter.airportBeforeTyphoonTimeWindowEnd) || (t >= Parameter.airportAfterTyphoonTimeWindowStart && t <= Parameter.airportAfterTyphoonTimeWindowEnd)) { isWithinAffectedRegionDestination2 = true; } } if((i*presetGap)%givenGap != 0){ if(!isWithinAffectedRegionOrigin2 && !isWithinAffectedRegionDestination2){ continue; } } if(cf.secondFlight.initialTakeoffT+presetGap*i >= firstArc.readyTime){ FlightArc secondArc = new FlightArc(); secondArc.flight = cf.secondFlight; secondArc.aircraft = aircraft; secondArc.delay = i*presetGap; secondArc.takeoffTime = cf.secondFlight.initialTakeoffT+secondArc.delay; secondArc.landingTime = secondArc.takeoffTime+cf.secondFlight.flyTime; secondArc.readyTime = secondArc.landingTime + + (cf.secondFlight.isShortConnection?cf.secondFlight.shortConnectionTime:Parameter.MIN_BUFFER_TIME); secondArc.isWithinAffectedRegionOrigin = isWithinAffectedRegionOrigin2; secondArc.isWithinAffectedRegionDestination = isWithinAffectedRegionDestination2; if(!secondArc.checkViolation()){ ConnectingArc ca = new ConnectingArc(); ca.firstArc = firstArc; ca.secondArc = secondArc; aircraft.connectingArcList.add(ca); cf.firstFlight.connectingarcList.add(ca); cf.secondFlight.connectingarcList.add(ca); ca.connectingFlightPair = cf; ca.aircraft = aircraft; connectingArcList.add(ca); ca.calculateCost(scenario); generatedConnectingArcList.add(ca); if(!isWithinAffectedRegionOrigin2 && !isWithinAffectedRegionDestination2 ) { break; } } } } } int nnn = 0; for(ConnectingArc arc:connectingArcList) { //加入到对应的机场 if(arc.firstArc.isWithinAffectedRegionOrigin) { List<ConnectingArc> caList = scenario.airportTimeConnectingArcMap.get(arc.firstArc.flight.leg.originAirport.id+"_"+arc.firstArc.takeoffTime); caList.add(arc); } if(arc.firstArc.isWithinAffectedRegionDestination) { List<ConnectingArc> caList = scenario.airportTimeConnectingArcMap.get(arc.firstArc.flight.leg.destinationAirport.id+"_"+arc.firstArc.landingTime); caList.add(arc); } if(arc.secondArc.isWithinAffectedRegionOrigin) { List<ConnectingArc> caList = scenario.airportTimeConnectingArcMap.get(arc.secondArc.flight.leg.originAirport.id+"_"+arc.secondArc.takeoffTime); caList.add(arc); } if(arc.secondArc.isWithinAffectedRegionDestination) { List<ConnectingArc> caList = scenario.airportTimeConnectingArcMap.get(arc.secondArc.flight.leg.destinationAirport.id+"_"+arc.secondArc.landingTime); caList.add(arc); } //加入25和67停机约束 if(cf.firstFlight.leg.destinationAirport.id == 25 && arc.firstArc.landingTime <= Parameter.airport25_67ParkingLimitStart && arc.secondArc.takeoffTime >= Parameter.airport25_67ParkingLimitEnd){ scenario.airport25ClosureConnectingArcList.add(arc); } if(cf.firstFlight.leg.destinationAirport.id == 67 && arc.firstArc.landingTime <= Parameter.airport25_67ParkingLimitStart && arc.secondArc.takeoffTime >= Parameter.airport25_67ParkingLimitEnd){ scenario.airport25ClosureConnectingArcList.add(arc); } //设置第一个arc //arc.firstArc.isIncludedInConnecting = true; //arc.firstArc.connectingArcList.add(arc); //乘客容量 arc.firstArc.passengerCapacity = aircraft.passengerCapacity; //减去联程乘客 arc.firstArc.passengerCapacity = arc.firstArc.passengerCapacity - cf.firstFlight.connectedPassengerNumber; //减去转乘乘客 arc.firstArc.passengerCapacity = arc.firstArc.passengerCapacity - cf.firstFlight.occupiedSeatsByTransferPassenger; if(Parameter.onlySignChangeDisruptedPassenger){ //减去普通乘客 arc.firstArc.passengerCapacity = arc.firstArc.passengerCapacity - cf.firstFlight.normalPassengerNumber; }else{ // 减去普通乘客 arc.firstArc.fulfilledNormalPassenger = Math.min(arc.firstArc.passengerCapacity, cf.firstFlight.normalPassengerNumber); arc.firstArc.passengerCapacity = arc.firstArc.passengerCapacity - arc.firstArc.fulfilledNormalPassenger; arc.firstArc.flight.itinerary.firstConnectionArcList.add(arc); } /*if(arc.firstArc.flight.id == 1333){ System.out.println("flight 1333:"+arc.firstArc.passengerCapacity+" "); }*/ //剩下的则为有效座位 arc.firstArc.passengerCapacity = Math.max(0, arc.firstArc.passengerCapacity); boolean isFound = false; for(FlightSection currentFlightSection:cf.firstFlight.flightSectionList) { if(arc.firstArc.takeoffTime >= currentFlightSection.startTime && arc.firstArc.takeoffTime < currentFlightSection.endTime) { //currentFlightSection.flightArcList.add(arc.firstArc); currentFlightSection.connectingFirstArcList.add(arc); isFound = true; /*if(currentFlightSection.flight.id == 1333 && currentFlightSection.startTime == 10930 && currentFlightSection.endTime == 11090){ System.out.println("we find this flight section 1: "+arc.firstArc.takeoffTime+" "+arc.secondArc.takeoffTime); nnn++; }*/ break; } } if(!isFound) { if(arc.firstArc.takeoffTime != cf.firstFlight.flightSectionList.get(cf.firstFlight.flightSectionList.size()-1).endTime) { System.out.println("no flight section found! "+arc.firstArc.takeoffTime+" "+cf.firstFlight.flightSectionList.get(cf.firstFlight.flightSectionList.size()-1).endTime); System.exit(1); } cf.firstFlight.flightSectionList.get(cf.firstFlight.flightSectionList.size()-1).connectingFirstArcList.add(arc); /*FlightSection currentFlightSection = cf.firstFlight.flightSectionList.get(cf.firstFlight.flightSectionList.size()-1); if(currentFlightSection.flight.id == 1333 && currentFlightSection.startTime == 10930 && currentFlightSection.endTime == 11090){ System.out.println("we find this flight section 2: "+arc.firstArc.takeoffTime+" "+arc.secondArc.takeoffTime); }*/ } //设置第二个arc //arc.secondArc.isIncludedInConnecting = true; //arc.secondArc.connectingArcList.add(arc); //乘客容量 arc.secondArc.passengerCapacity = aircraft.passengerCapacity; //减去联程乘客 arc.secondArc.passengerCapacity = arc.secondArc.passengerCapacity - cf.secondFlight.connectedPassengerNumber; //减去转乘乘客 arc.secondArc.passengerCapacity = arc.secondArc.passengerCapacity - cf.secondFlight.occupiedSeatsByTransferPassenger; if(Parameter.onlySignChangeDisruptedPassenger){ //减去普通乘客 arc.secondArc.passengerCapacity = arc.secondArc.passengerCapacity - cf.secondFlight.normalPassengerNumber; }else{ // 减去普通乘客 arc.secondArc.fulfilledNormalPassenger = Math.min(arc.secondArc.passengerCapacity, cf.secondFlight.normalPassengerNumber); arc.secondArc.passengerCapacity = arc.secondArc.passengerCapacity - arc.secondArc.fulfilledNormalPassenger; arc.secondArc.flight.itinerary.secondConnectingArcList.add(arc); } //剩下的则为有效座位 arc.secondArc.passengerCapacity = Math.max(0, arc.secondArc.passengerCapacity); isFound = false; for(FlightSection currentFlightSection:cf.secondFlight.flightSectionList) { if(arc.secondArc.takeoffTime >= currentFlightSection.startTime && arc.secondArc.takeoffTime < currentFlightSection.endTime) { currentFlightSection.connectingSecondArcList.add(arc); isFound = true; /*if(currentFlightSection.flight.id == 1333 && currentFlightSection.startTime == 10930 && currentFlightSection.endTime == 11090){ System.out.println("we find this flight section 3: "+arc.firstArc.takeoffTime+" "+arc.secondArc.takeoffTime); }*/ break; } } if(!isFound) { if(arc.secondArc.takeoffTime != cf.secondFlight.flightSectionList.get(cf.secondFlight.flightSectionList.size()-1).endTime) { System.out.println("no flight section found 2! "+arc.secondArc.takeoffTime+" "+cf.secondFlight.flightSectionList.get(cf.secondFlight.flightSectionList.size()-1).endTime); System.exit(1); } cf.secondFlight.flightSectionList.get(cf.secondFlight.flightSectionList.size()-1).connectingSecondArcList.add(arc); /*FlightSection currentFlightSection = cf.firstFlight.flightSectionList.get(cf.firstFlight.flightSectionList.size()-1); if(currentFlightSection.flight.id == 1333 && currentFlightSection.startTime == 10930 && currentFlightSection.endTime == 11090){ System.out.println("we find this flight section 4: "+arc.firstArc.takeoffTime+" "+arc.secondArc.takeoffTime); }*/ } } /*//3. 为每一个flight生成arc,可以单独取消联程航班中的一段 if(isGenerateArcForEachFlight) { if(!aircraft.tabuLegs.contains(cf.firstFlight.leg)){ generateArcForFlight(aircraft, cf.firstFlight, givenGap, scenario); } if(!aircraft.tabuLegs.contains(cf.secondFlight.leg)){ generateArcForFlight(aircraft, cf.secondFlight, givenGap, scenario); } }*/ if(cf.firstFlight.id == 1333){ System.out.println("nnn:"+nnn); } } return generatedConnectingArcList; } //生成点和地面arc public void generateNodes(List<Aircraft> aircraftList, List<Airport> airportList, Scenario scenario){ //2. generate nodes for each arc for(Aircraft aircraft:aircraftList){ //1. clear node map for each airport for(int i=0;i<airportList.size();i++){ Airport a = airportList.get(i); aircraft.nodeMapArray[i] = new HashMap<>(); aircraft.nodeListArray[i] = new ArrayList<>(); } for(FlightArc flightArc:aircraft.flightArcList){ Airport departureAirport = flightArc.flight.leg.originAirport; Airport arrivalAirport = flightArc.flight.leg.destinationAirport; Node node = aircraft.nodeMapArray[departureAirport.id-1].get(flightArc.takeoffTime); if(node == null){ node = new Node(); node.airport = departureAirport; node.time = flightArc.takeoffTime; aircraft.nodeMapArray[departureAirport.id-1].put(flightArc.takeoffTime, node); } node.flowoutFlightArcList.add(flightArc); flightArc.fromNode = node; node = aircraft.nodeMapArray[arrivalAirport.id-1].get(flightArc.readyTime); if(node == null){ node = new Node(); node.airport = arrivalAirport; node.time = flightArc.readyTime; aircraft.nodeMapArray[arrivalAirport.id-1].put(flightArc.readyTime, node); } node.flowinFlightArcList.add(flightArc); flightArc.toNode = node; } for(ConnectingArc flightArc:aircraft.connectingArcList){ Airport departureAirport = flightArc.firstArc.flight.leg.originAirport; Airport arrivalAirport = flightArc.secondArc.flight.leg.destinationAirport; int takeoffTime = flightArc.firstArc.takeoffTime; int readyTime = flightArc.secondArc.readyTime; Node node = aircraft.nodeMapArray[departureAirport.id-1].get(takeoffTime); if(node == null){ node = new Node(); node.airport = departureAirport; node.time = takeoffTime; aircraft.nodeMapArray[departureAirport.id-1].put(takeoffTime, node); } node.flowoutConnectingArcList.add(flightArc); flightArc.fromNode = node; node = aircraft.nodeMapArray[arrivalAirport.id-1].get(readyTime); if(node == null){ node = new Node(); node.airport = arrivalAirport; node.time = readyTime; aircraft.nodeMapArray[arrivalAirport.id-1].put(readyTime, node); } node.flowinConnectingArcList.add(flightArc); flightArc.toNode = node; } //生成source和sink点 Node sourceNode = new Node(); sourceNode.isSource = true; aircraft.sourceNode = sourceNode; Node sinkNode = new Node(); sinkNode.isSink = true; aircraft.sinkNode = sinkNode; //3. sort nodes of each airport for(int i=0;i<airportList.size();i++){ for(Integer key:aircraft.nodeMapArray[i].keySet()){ aircraft.nodeListArray[i].add(aircraft.nodeMapArray[i].get(key)); } Airport airport = airportList.get(i); boolean isFound = false; Collections.sort(aircraft.nodeListArray[i], new NodeComparator()); for(int j=0;j<aircraft.nodeListArray[i].size()-1;j++){ Node n1 = aircraft.nodeListArray[i].get(j); Node n2 = aircraft.nodeListArray[i].get(j+1); GroundArc groundArc = new GroundArc(); groundArc.fromNode = n1; groundArc.toNode = n2; groundArc.aircraft = aircraft; n1.flowoutGroundArcList.add(groundArc); n2.flowinGroundArcList.add(groundArc); aircraft.groundArcList.add(groundArc); if(!isFound) { if(scenario.affectedAirportSet.contains(airport.id)) { if(n1.time <= Parameter.airport49_50_61ParkingLimitStart && n2.time >= Parameter.airport49_50_61ParkingLimitEnd) { List<GroundArc> gaList = scenario.affectedAirportCoverParkLimitGroundArcMap.get(airport.id); gaList.add(groundArc); isFound = true; } } } if(n1.airport.id == 25 && n1.time <= Parameter.airport25_67ParkingLimitStart && n2.time >=Parameter.airport25_67ParkingLimitEnd){ scenario.airport25ClosureGroundArcList.add(groundArc); } if(n1.airport.id == 67 && n1.time <= Parameter.airport25_67ParkingLimitStart && n2.time >=Parameter.airport25_67ParkingLimitEnd){ scenario.airport67ClosureGroundArcList.add(groundArc); } /*if(!groundArc.checkViolation()){ n1.flowoutGroundArcList.add(groundArc); n2.flowinGroundArcList.add(groundArc); aircraft.groundArcList.add(groundArc); }*/ } } //4. construct source and sink arcs //连接source和每个飞机初始机场的第一个点 if(aircraft.nodeListArray[aircraft.initialLocation.id-1].size() > 0) { Node firstNode = aircraft.nodeListArray[aircraft.initialLocation.id-1].get(0); GroundArc arc = new GroundArc(); arc.fromNode = sourceNode; arc.toNode = firstNode; arc.isSource = true; arc.aircraft = aircraft; sourceNode.flowoutGroundArcList.add(arc); firstNode.flowinGroundArcList.add(arc); aircraft.groundArcList.add(arc); } //对停机限制的机场飞机可以刚开停靠 /*if(Parameter.restrictedAirportSet.contains(aircraft.initialLocation)){ if(aircraft.nodeListArray[aircraft.initialLocation.id-1].size() > 0){ for(int j=1;j<aircraft.nodeListArray[aircraft.initialLocation.id-1].size();j++){ Node n = aircraft.nodeListArray[aircraft.initialLocation.id-1].get(j); GroundArc arc = new GroundArc(); arc.fromNode = sourceNode; arc.toNode = n; arc.isSource = true; sourceNode.flowoutGroundArcList.add(arc); n.flowinGroundArcList.add(arc); aircraft.groundArcList.add(arc); } } }*/ //对停机限制的机场飞机可以刚开始停靠 if(scenario.affectedAirportSet.contains(aircraft.initialLocation.id)){ if(aircraft.nodeListArray[aircraft.initialLocation.id-1].size() > 0){ for(int j=1;j<aircraft.nodeListArray[aircraft.initialLocation.id-1].size();j++){ Node n = aircraft.nodeListArray[aircraft.initialLocation.id-1].get(j); if(n.time >= Parameter.airportAfterTyphoonTimeWindowStart) { GroundArc arc = new GroundArc(); arc.fromNode = sourceNode; arc.toNode = n; arc.isSource = true; arc.aircraft = aircraft; sourceNode.flowoutGroundArcList.add(arc); n.flowinGroundArcList.add(arc); aircraft.groundArcList.add(arc); break; } } } } /*for(Airport airport:airportList){ if(aircraft.nodeListArray[airport.id-1].size() > 0){ if(Parameter.restrictedAirportSet.contains(airport)){ for(Node lastNode:aircraft.nodeListArray[airport.id-1]){ GroundArc arc = new GroundArc(); arc.fromNode = lastNode; arc.toNode = sinkNode; arc.isSink = true; lastNode.flowoutGroundArcList.add(arc); sinkNode.flowinGroundArcList.add(arc); aircraft.groundArcList.add(arc); lastNode.airport.sinkArcList[aircraft.type-1].add(arc); } }else{ Node lastNode = aircraft.nodeListArray[airport.id-1].get(aircraft.nodeListArray[airport.id-1].size()-1); GroundArc arc = new GroundArc(); arc.fromNode = lastNode; arc.toNode = sinkNode; arc.isSink = true; lastNode.flowoutGroundArcList.add(arc); sinkNode.flowinGroundArcList.add(arc); aircraft.groundArcList.add(arc); lastNode.airport.sinkArcList[aircraft.type-1].add(arc); } } }*/ for(Airport airport:airportList){ if(aircraft.nodeListArray[airport.id-1].size() > 0){ if(scenario.affectedAirportSet.contains(airport.id)){ for(int j=aircraft.nodeListArray[airport.id-1].size()-2;j>=0;j--) { Node lastNode = aircraft.nodeListArray[airport.id-1].get(j); if(lastNode.time <= Parameter.airportBeforeTyphoonTimeWindowEnd) { GroundArc arc = new GroundArc(); arc.fromNode = lastNode; arc.toNode = sinkNode; arc.isSink = true; arc.aircraft = aircraft; lastNode.flowoutGroundArcList.add(arc); sinkNode.flowinGroundArcList.add(arc); aircraft.groundArcList.add(arc); lastNode.airport.sinkArcList[aircraft.type-1].add(arc); break; } } } Node lastNode = aircraft.nodeListArray[airport.id-1].get(aircraft.nodeListArray[airport.id-1].size()-1); GroundArc arc = new GroundArc(); arc.fromNode = lastNode; arc.toNode = sinkNode; arc.isSink = true; arc.aircraft = aircraft; lastNode.flowoutGroundArcList.add(arc); sinkNode.flowinGroundArcList.add(arc); aircraft.groundArcList.add(arc); lastNode.airport.sinkArcList[aircraft.type-1].add(arc); } } /*//4.2 生成直接从source node连接到sink node的arc GroundArc arc = new GroundArc(); arc.fromNode = sourceNode; arc.toNode = sinkNode; arc.isSink = true; arc.aircraft = aircraft; sourceNode.flowoutGroundArcList.add(arc); sinkNode.flowinGroundArcList.add(arc); aircraft.groundArcList.add(arc); aircraft.initialLocation.sinkArcList[aircraft.type-1].add(arc);*/ //5. construct turn-around arc GroundArc arc = new GroundArc(); arc.fromNode = sinkNode; arc.toNode = sourceNode; arc.aircraft = aircraft; sinkNode.flowoutGroundArcList.add(arc); sourceNode.flowinGroundArcList.add(arc); aircraft.groundArcList.add(arc); aircraft.turnaroundArc = arc; } } }
[ "zd.pony@gmail.com" ]
zd.pony@gmail.com
0755ae37a7a1680e386491b9da88b16061dce3ac
3c65f2eac11632a035e6fc9702fe0a71b5f2d3ad
/mykit-test/mykit-test-service/mykit-test-service-xml/src/main/java/io/mykit/serial/test/SerialNumberServiceFactoryBeanTest.java
b293e2f7f3306cf3299b9e067d0b726ee18012b5
[ "LicenseRef-scancode-unknown-license-reference", "GPL-2.0-only", "Apache-2.0", "GPL-1.0-or-later" ]
permissive
alinshen/mykit-serial
5752db76a26cb5d4e3ab5bc4f7aa8775e740828e
a70847123f9a6df428d955e4476861c4c391652e
refs/heads/master
2023-01-24T18:02:08.797456
2020-12-06T02:30:29
2020-12-06T02:30:29
318,975,892
1
0
Apache-2.0
2020-12-06T07:24:48
2020-12-06T07:24:47
null
UTF-8
Java
false
false
3,817
java
/** * Copyright 2020-9999 the original author or authors. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.mykit.serial.test; import io.mykit.serial.bean.SerialNumber; import io.mykit.serial.service.SerialNumberService; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.testng.AssertJUnit; import org.testng.annotations.Test; /** * @author binghe * @version 1.0.0 * @description 测试使用FactoryBean生成序列号 */ public class SerialNumberServiceFactoryBeanTest { @Test(groups = {"serialNumberService"}) public void testSimple() { ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring/mykit-serial-service-factory-bean-property-test.xml"); SerialNumberService serialNumberService = (SerialNumberService) applicationContext.getBean("serialNumberService"); long serialNumber = serialNumberService.genSerialNumber(); SerialNumber serialNumberdo = serialNumberService.expSerialNumber(serialNumber); long serialNumber1 = serialNumberService.makeSerialNumber(serialNumberdo.getVersion(), serialNumberdo.getType(), serialNumberdo.getGenMethod(), serialNumberdo.getTime(), serialNumberdo.getSeq(), serialNumberdo.getMachine()); System.err.println(serialNumber + ":" + serialNumberdo); AssertJUnit.assertEquals(serialNumber, serialNumber1); } @Test(groups = {"serialNumberService"}) public void testIpConfigurable() { ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring/mykit-serial-service-factory-bean-ip-configurable-test.xml"); SerialNumberService serialNumberService = (SerialNumberService) applicationContext.getBean("serialNumberServiceIpConfigurable"); long serialNumber = serialNumberService.genSerialNumber(); SerialNumber serialNumbero = serialNumberService.expSerialNumber(serialNumber); long serialNumber1 = serialNumberService.makeSerialNumber(serialNumbero.getVersion(), serialNumbero.getType(), serialNumbero.getGenMethod(), serialNumbero.getTime(), serialNumbero.getSeq(), serialNumbero.getMachine()); System.err.println(serialNumber + ":" + serialNumbero); AssertJUnit.assertEquals(serialNumber, serialNumber1); } @Test(groups = {"serialNumberService"}) public void testDb() { ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring/mykit-serial-service-factory-bean-db-test.xml"); SerialNumberService serialNumberService = (SerialNumberService) applicationContext.getBean("serialNumberServiceDb"); long serialNumber = serialNumberService.genSerialNumber(); SerialNumber serialNumbero = serialNumberService.expSerialNumber(serialNumber); long serialNumbero1 = serialNumberService.makeSerialNumber(serialNumbero.getVersion(), serialNumbero.getType(), serialNumbero.getGenMethod(), serialNumbero.getTime(), serialNumbero.getSeq(), serialNumbero.getMachine()); System.err.println(serialNumber + ":" + serialNumbero); AssertJUnit.assertEquals(serialNumber, serialNumbero1); } }
[ "1028386804@qq.com" ]
1028386804@qq.com
a5320df0581bab3838fb30e3196c2fab49ba98ad
af7c917922b60b30016df8503ef5843d714d335c
/src/main/java/com/fabulouslab/collection/BlackoutLongList.java
a553bfb02e4e79fa0e7059332388bb8276c1b2c0
[]
no_license
oraclewalid/Blackout
9c56fba555c7fda6fc19f8b382a5e567ce3ff1fd
dc75794a26189a5a7dc484bf9f4eda7268539053
refs/heads/master
2020-05-30T10:59:22.062096
2016-09-18T09:42:34
2016-09-18T09:42:34
55,913,701
0
0
null
2016-09-09T09:58:34
2016-04-10T17:47:31
Java
UTF-8
Java
false
false
3,764
java
package com.fabulouslab.collection; import com.fabulouslab.exception.BlackoutException; import com.fabulouslab.util.Memory; import java.util.Collection; import java.util.Objects; public class BlackoutLongList extends BlackoutAbstractList<Long>{ private static final int SHORT_LENGTH = 8; public BlackoutLongList(int capacity) { if(size < 0 ) throw new IllegalArgumentException("Size must be higher than 0"); this.size = 0; this.capacity = capacity; address = Memory.allocate(this.capacity * getLength()); } public BlackoutLongList(long... values) { Objects.requireNonNull(values); createOffHeapArray(values, values.length); } private void createOffHeapArray(long[] values, int length) { this.size = length; this.capacity = length; address = Memory.allocate(this.capacity * getLength()); for (int i = 0; i < length; i++) { long addr = address + i * getLength(); Memory.putLong(addr, values[i]); } } @Override public Long get(int index) { checkSizeBounds(index); long addr = address + index * getLength(); return Memory.getLong(addr); } @Override public Long set(int index, Long element) { Long oldValue = get(index); long addr = Memory.computeAddr(address, index, getLength()); Memory.putLong(addr,element); return oldValue; } @Override public Object[] toArray() { Long[] integers = new Long[size]; for (int i = 0; i < size ; i++) { integers[i] = get(i); } return integers; } @Override public boolean removeAll(Collection<?> c) { long[] elementData = new long[size]; int newIndex = 0; for (int i = 0; i < size ; i++) { if (!c.contains(get(i))) { elementData[newIndex++] = get(i); } } if (newIndex != size) { long oldAddress = address; createOffHeapArray(elementData, newIndex); Memory.free(oldAddress); return true; } return false; } @Override public boolean addAll(int index, Collection<? extends Long> c) { try { checkLimits(index); if(!checkCapacity(c.size())){ address = reallocate(c.size(), index); } int i = 0; for (Long element : c) { long addr = Memory.computeAddr(address, index + i, getLength()); Memory.putLong(addr,element); i++; } size = size + c.size(); return true; } catch (BlackoutException ex){ return false; } } @Override public boolean addAll(Collection<? extends Long> c) { try { if(!checkCapacity(c.size())){ address = reallocate(c.size()); } int i = 0; for (long element : c) { long addr = Memory.computeAddr(address, size + i, getLength()); Memory.putLong(addr,element); i++; } size = size + c.size(); return true; } catch (BlackoutException ex){ return false; } } @Override public void add(int index, Long element) { checkLimits(index); if(!checkCapacity(1)){ address = reallocate(1, index); } long addr = Memory.computeAddr(address, index, getLength()); Memory.putLong(addr,element); size = size + 1; } @Override public int getLength() { return SHORT_LENGTH; } }
[ "walid.chergui@gmail.com" ]
walid.chergui@gmail.com
4d9eb1c9db21d3f43df79f1eb7c8a0639fa8b661
abb240447253b2e1ab4bf9ce12c556c89f5bd052
/src/main/java/dto/PostDTO.java
dd6d47461b51a78f240ca50b8789567527b3a7c7
[]
no_license
hillelqateam/serenity_qa_framework
8148ac2e6d7211fbf8a883cf42f46c26ad563ac0
4c77efe3f4880156bc96e7010739567f298dfa9d
refs/heads/master
2020-04-16T15:40:04.467671
2019-01-17T17:54:13
2019-01-17T17:55:04
165,710,807
0
0
null
null
null
null
UTF-8
Java
false
false
120
java
package dto; import lombok.Data; @Data public class PostDTO { private String title; private String author; }
[ "Deniss22605@gmail.com" ]
Deniss22605@gmail.com
1827887c039f2d7d653537681debdc1a73ef182c
f5a488d534c73d7b65e759e805342a26f68978a6
/app/src/main/java/com/example/andr3lesson3/ui/MainActivity.java
e8c236c10ff29ff32c9a603a19f6dc35cbfe123a
[]
no_license
Turdukulov07/android3HomeWork3
dae3deb5330a5df5952a1fec7d939942e11c27aa
8cc64f28ddab44fe4e28ffcc0c3edfb89bfcdbdf
refs/heads/master
2023-04-05T17:21:52.878519
2021-04-22T13:56:21
2021-04-22T13:56:21
360,537,403
0
0
null
null
null
null
UTF-8
Java
false
false
376
java
package com.example.andr3lesson3.ui; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import com.example.andr3lesson3.R; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } }
[ "66789345+Turdukulov07@users.noreply.github.com" ]
66789345+Turdukulov07@users.noreply.github.com
c2930736d4bba1fd1df0a4a75fb9a79cf2acace0
6e7e5bf2c24cba9fffa665b9db20a3cf6862910a
/ch09/src/ch09/GraphicCard.java
4ef4e5c8fb8e38ff91d441fc06c860369833f325
[]
no_license
stellayk/JAVA
cc9093787db4e6a4822865ecb389fcac6903f943
49f65021802142abd52a152de00b1e5040239d62
refs/heads/master
2023-04-25T10:25:03.357665
2021-05-14T18:09:43
2021-05-14T18:09:43
350,936,751
0
0
null
null
null
null
UTF-8
Java
false
false
97
java
package ch09; public interface GraphicCard { String MEMORY = "26"; public void process(); }
[ "yeeunkk@gmail.com" ]
yeeunkk@gmail.com
7d7ee4a6164d378bd85f79f0552eb5d0d05cd0d4
11dda7fe53e39ba60e2e140b3d14ef8fea1d0951
/src/com/bjsxt/controller/AdminController.java
fd18ff0d545cad7221579f16b27053d1d1d38214
[]
no_license
chenbin5/ting
bd73732257e8b2616c8b8379d106bd0dfae8e723
067dd033ec3331823ddb15004eb95ed5dcdb1e95
refs/heads/master
2022-11-10T22:59:40.572858
2020-06-30T08:59:46
2020-06-30T08:59:46
273,114,011
0
0
null
null
null
null
UTF-8
Java
false
false
1,335
java
package com.bjsxt.controller; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.bjsxt.entity.Admin; import com.bjsxt.service.IAdminService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMethod; import javax.servlet.http.HttpSession; /** * <p> * 前端控制器 * </p> * * @author ${author} * @since 2020-06-11 */ @Controller @RequestMapping("/admin") public class AdminController { @Autowired private IAdminService adminService; @RequestMapping(value = "/login",method = {RequestMethod.POST}) public String adminLogin(String aname,String apwd,HttpSession httpSession){ QueryWrapper<Admin> query = new QueryWrapper<>(); query.eq("aname",aname); query.eq("apwd",apwd); Admin admin = adminService.getOne(query); //判断用户是否登录成功 if (null == admin){ //如果登录失败 httpSession.setAttribute("flag","1"); return "redirect:/index.jsp"; }else{ //登陆成功 httpSession.setAttribute("admin",admin); return "redirect:/main.jsp"; } } }
[ "18143798073@163.com" ]
18143798073@163.com
0649bc0f35e4ba092a2bb42ab77d28469be6a436
f7dd51eb274442f607a532106ecf251cd010a13d
/guns-admin/src/main/java/com/stylefeng/guns/modular/api/controller/JifenAddApiController.java
7d66a86174158f27d8ad3160b118e7926d4a4bf1
[ "Apache-2.0" ]
permissive
vicenteam/changsha-hyxt
8f2e83b05bfcd15192b959556c51e81290750c06
8aa82bf27e01fd28124867372f3e1a3925367725
refs/heads/master
2020-04-11T10:50:32.313273
2019-04-16T01:02:31
2019-04-16T01:02:31
161,728,071
1
1
null
null
null
null
UTF-8
Java
false
false
8,975
java
package com.stylefeng.guns.modular.api.controller; import com.baomidou.mybatisplus.mapper.EntityWrapper; import com.stylefeng.guns.core.common.BaseEntityWrapper.BaseEntityWrapper; import com.stylefeng.guns.modular.api.apiparam.RequstData; import com.stylefeng.guns.modular.api.apiparam.ResponseData; import com.stylefeng.guns.modular.api.base.BaseController; import com.stylefeng.guns.modular.api.model.jifen.JifenAddModel; import com.stylefeng.guns.modular.api.model.jifen.JifenPageDataMode; import com.stylefeng.guns.modular.api.model.jifen.ZengSongJifenModel; import com.stylefeng.guns.modular.api.util.ReflectionObject; import com.stylefeng.guns.modular.main.controller.IntegralrecordController; import com.stylefeng.guns.modular.main.controller.MembermanagementController; import com.stylefeng.guns.modular.main.service.IIntegralrecordService; import com.stylefeng.guns.modular.main.service.IIntegralrecordtypeService; import com.stylefeng.guns.modular.main.service.IMembermanagementService; import com.stylefeng.guns.modular.main.service.IMembershipcardtypeService; import com.stylefeng.guns.modular.system.model.Integralrecordtype; import com.stylefeng.guns.modular.system.model.MemberCard; import com.stylefeng.guns.modular.system.model.Membermanagement; import com.stylefeng.guns.modular.system.model.Membershipcardtype; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiOperation; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import java.util.ArrayList; import java.util.List; import java.util.Map; @RestController @Scope("prototype") @RequestMapping("/api/jifenaddapi") @Api(description = "新增积分") public class JifenAddApiController extends BaseController { private final Logger log = LoggerFactory.getLogger(JifenAddApiController.class); @Autowired private MembermanagementController membermanagementController; @Autowired private IMembermanagementService membermanagementService; @Autowired private IntegralrecordController integralrecordController; @Autowired private IIntegralrecordtypeService integralrecordtypeService; @Autowired private IMembershipcardtypeService membershipcardtypeService; @RequestMapping(value = "/findUserInfo", method = RequestMethod.POST) @ApiOperation("读卡查询用户信息") @ApiImplicitParams({ @ApiImplicitParam(required = true, name = "userId", value = "操作人id", paramType = "query"), @ApiImplicitParam(required = true, name = "deptId", value = "操作人部门id", paramType = "query"), @ApiImplicitParam(required = true, name = "cardCode", value = "卡片信息", paramType = "query"), }) public ResponseData<JifenAddModel> findUserInfo(RequstData requstData, String cardCode) throws Exception { ResponseData<JifenAddModel> responseData = new ResponseData(); try { MemberCard userInfo = (MemberCard)membermanagementController.getUserInfo(cardCode); Integer memberid = userInfo.getMemberid(); Membermanagement membermanagement = membermanagementService.selectById(memberid); JifenAddModel change = new ReflectionObject<JifenAddModel>().change(membermanagement, new JifenAddModel()); change.setJifenAddUserId(memberid); //获取积分类型 String deptId = membermanagement.getDeptId(); EntityWrapper<Integralrecordtype> integralrecordtypeEntityWrapper = new EntityWrapper<>(); List<Map<String, Object>> mapList = integralrecordtypeService.selectMaps(integralrecordtypeEntityWrapper); if(mapList==null)throw new NoSuchMethodException("无积分类型"); change.setJifenType(mapList); //设置卡等级 Membershipcardtype membershipcardtype = membershipcardtypeService.selectById(change.getLevelID()); if(membershipcardtype!=null)change.setLevelID(membershipcardtype.getCardname()); responseData.setDataCollection(change); }catch (Exception e){ throw new Exception("系统异常!"+e.getMessage()); } return responseData; } @RequestMapping(value = "/addJifen", method = RequestMethod.POST) @ApiOperation("新增积分") @ApiImplicitParams({ @ApiImplicitParam(required = true, name = "userId", value = "操作人id", paramType = "query"), @ApiImplicitParam(required = true, name = "deptId", value = "操作人部门id", paramType = "query"), @ApiImplicitParam(required = true, name = "jifenAddUserId", value = "卡片用户id", paramType = "query"), @ApiImplicitParam(required = true, name = "nowPice", value = "新增积分", paramType = "query"), @ApiImplicitParam(required = true, name = "jifenType", value = "积分类型", paramType = "query"), @ApiImplicitParam(required = true, name = "consumptionNum", value = "购买数量", paramType = "query"), }) public ResponseData addJifen(RequstData requstData,Integer jifenAddUserId,Double nowPice,Integer jifenType,Integer consumptionNum) throws Exception { ResponseData responseData = new ResponseData(); try { integralrecordController.add(nowPice,jifenType,jifenAddUserId,consumptionNum); }catch (Exception e){ throw new Exception("新增失败 请联系管理员!"); } return responseData; } @RequestMapping(value = "/getLeaveInfo", method = RequestMethod.POST) @ApiOperation("获取卡等级") @ApiImplicitParams({ @ApiImplicitParam(required = true, name = "userId", value = "操作人id", paramType = "query"), @ApiImplicitParam(required = true, name = "deptId", value = "操作人部门id", paramType = "query"), // @ApiImplicitParam(required = true, name = "leaveId", value = "卡等级", paramType = "query"), // @ApiImplicitParam(required = true, name = "nowPice", value = "积分值", paramType = "query"), }) public ResponseData<List<ZengSongJifenModel>> getLeaveInfo(RequstData requstData) throws Exception { ResponseData<List<ZengSongJifenModel>> responseData = new ResponseData(); try { BaseEntityWrapper<Membershipcardtype> zengSongJifenModelBaseEntityWrapper=new BaseEntityWrapper(); List<Membershipcardtype> list=membershipcardtypeService.selectList(zengSongJifenModelBaseEntityWrapper); List<ZengSongJifenModel> list1=new ArrayList<>(); list.forEach(a->{ ZengSongJifenModel zengSongJifenModel=new ZengSongJifenModel(); zengSongJifenModel.setLeaveId(a.getId()); zengSongJifenModel.setLeaveName(a.getCardname()); list1.add(zengSongJifenModel); }); responseData.setDataCollection(list1); }catch (Exception e){ throw new Exception("获取会员卡等级失败 请联系管理员!"); } return responseData; } @RequestMapping(value = "/zengsongjifen", method = RequestMethod.POST) @ApiOperation("赠送积分") @ApiImplicitParams({ @ApiImplicitParam(required = true, name = "userId", value = "操作人id", paramType = "query"), @ApiImplicitParam(required = true, name = "deptId", value = "操作人部门id", paramType = "query"), @ApiImplicitParam(required = true, name = "leaveIds", value = "卡等级id组合(例 43,55,66)", paramType = "query"), @ApiImplicitParam(required = true, name = "nowPice", value = "积分值", paramType = "query"), }) @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW) public ResponseData zengsongjifen(RequstData requstData,String leaveIds,Double nowPice) throws Exception { ResponseData responseData = new ResponseData(); try { BaseEntityWrapper<Membermanagement> wrapper = new BaseEntityWrapper<>(); if(leaveIds!=null&&leaveIds.length()>0){ wrapper.in("levelID",leaveIds); } List<Membermanagement> ms = membermanagementService.selectList(wrapper); //积分添加操作 integralrecordController.insertIntegral(nowPice,2,10,ms); }catch (Exception e){ throw new Exception("赠送积分失败 请联系管理员!"); } return responseData; } }
[ "1418806370@qq.com" ]
1418806370@qq.com
b4429ca33b0fb3c1ed82867aa98b4300fcc0b779
2d8d6bc8c0a3b165d2b98c6b0a7f4aaa8f01db26
/src/main/java/com/spring/SpringLookupMethodExample.java
c03546ee7139b095fa63caa220277a7a222296ab
[]
no_license
venkys1259/project
97c66b3afd93a8376c2f913203cd0feb5b0cb17a
696f641fe90b162de427103622b411d720154d54
refs/heads/master
2021-01-24T13:40:24.020260
2018-04-09T21:17:11
2018-04-09T21:17:11
83,075,575
0
0
null
null
null
null
UTF-8
Java
false
false
1,284
java
package com.spring; import org.springframework.context.support.ClassPathXmlApplicationContext; public class SpringLookupMethodExample { public static void main(String[] args) { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext( "applicationContext.xml"); try { /* PizzaShop pizzaShop = (PizzaShop) context.getBean("pizzaShop"); Pizza firstPizza = pizzaShop.makePizza(); System.out.println("First Pizza: " + firstPizza); Pizza secondPizza = pizzaShop.makePizza(); System.out.println("Second Pizza: " + secondPizza); Pizza veggiePizza = pizzaShop.makeVeggiePizza(); System.out.println("Veggie Pizza: " + veggiePizza);*/ RequestProcessor processor = (RequestProcessor)context.getBean("processor"); for (int i=0;i<3;i++){ ResourceA resource = processor.getResourceA(); System.out.println("resource A:" +resource ); } for (int i=0;i<3;i++){ ResourceB resource = processor.getResourceB(); System.out.println("resource B:" +resource ); } } finally { context.close(); } } }
[ "venkys1259@gmail.com" ]
venkys1259@gmail.com
e077ec6898892f4a05bd8ae40ef4236e06f7e3fb
512de81089acda25addd3cabbf70e8a36e094c97
/src/test/java/org/blue/webframework/junit/account/AccountServiceTest.java
81ee8a2ac8a7707cce8102060253aff69e6b83fd
[]
no_license
simon2007/WebFramework
ce85a1427b9579e92c2ef48b6a9c5431d7713509
ea0bbd1f137fe37a962c3e7fd1f9a44c039ec1fe
refs/heads/master
2022-06-29T21:36:27.565862
2019-08-22T01:02:46
2019-08-22T01:02:46
164,195,802
0
0
null
2022-06-17T02:03:33
2019-01-05T08:17:53
Java
UTF-8
Java
false
false
4,940
java
package org.blue.webframework.junit.account; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import java.util.Date; import org.blue.webframework.junit.SpringTestBase; import org.blue.webframework.sys.account.service.AccountService; import org.blue.webframework.sys.account.vo.AccountLoginVo; import org.blue.webframework.sys.account.vo.AccountVo; import org.junit.Assert; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.annotation.Rollback; import com.github.pagehelper.Page; @Rollback(true) public class AccountServiceTest extends SpringTestBase { @Autowired AccountService accountService; @Test public void userGetByIdTest() { AccountVo admin = new AccountVo(); admin.setGroupId(1); admin.setName("hello_1"); admin.setOpenId("WeiXin12"); admin.setEnable(true); admin.setRoleId(1); accountService.add(admin, "hello123"); System.out.println("id=" + admin.getId()); AccountVo dbUserVo = accountService.getAccountById(admin.getId()); assertNotNull(dbUserVo); assertEquals(dbUserVo.getName(), admin.getName()); assertEquals(dbUserVo.getGroupId(), admin.getGroupId()); assertEquals(dbUserVo.getOpenId(), admin.getOpenId()); assertEquals(dbUserVo.getEnable(), admin.getEnable()); assertEquals(dbUserVo.getRoleId(), admin.getRoleId()); } @Test public void userInsertTest() { AccountVo user = new AccountVo(); user.setGroupId(1); user.setName("future"); user.setOpenId("WeiXin11"); user.setEnable(true); user.setRoleId(1); Integer row = accountService.add(user, "future123"); System.err.println("userId=" + user.getId()+" row="+row); user.setName("user1"); user.setGroupId(2); user.setOpenId("email1"); user.setRoleId(3); accountService.update(user); System.err.println("user.getId()=" + user.getId()); AccountVo dbUserVo = accountService.getAccountById(user.getId()); System.err.println("dbUserVo.getName()=" + dbUserVo.getName()); System.err.println("user.getName()=" + user.getName()); assertEquals(dbUserVo.getName(), user.getName()); assertEquals(dbUserVo.getGroupId(), user.getGroupId()); assertEquals(dbUserVo.getOpenId(), user.getOpenId()); assertEquals(dbUserVo.getEnable(), user.getEnable()); assertEquals(dbUserVo.getRoleId(), user.getRoleId()); } @Test public void userLoginTest() { AccountVo admin = new AccountVo(); admin.setGroupId(1); admin.setName("hello_2"); admin.setOpenId("WeiXin12"); admin.setEnable(true); admin.setRoleId(1); accountService.add(admin, "hello123"); AccountLoginVo accoutLoginVo=new AccountLoginVo(); accoutLoginVo.setName(admin.getName()); accoutLoginVo.setPassword("hello123"); AccountVo dbUserVo = accountService.login(accoutLoginVo); assertNotNull(dbUserVo); assertEquals(dbUserVo.getName(), admin.getName()); assertEquals(dbUserVo.getGroupId(), admin.getGroupId()); assertEquals(dbUserVo.getOpenId(), admin.getOpenId()); assertEquals(dbUserVo.getEnable(), admin.getEnable()); assertEquals(dbUserVo.getRoleId(), admin.getRoleId()); } @Test public void resetPasswordTest() { AccountVo admin = new AccountVo(); admin.setGroupId(1); admin.setName("hello_3"); admin.setOpenId("WeiXin12"); admin.setEnable(true); admin.setRoleId(1); accountService.add(admin, "hello123"); //int ret = accountService.resetPassword(admin.getName(), "hello123", "hello123"); //assertEquals(ret, 1); } @Test public void getByNameAndPassword() { AccountVo admin = new AccountVo(); admin.setGroupId(1); admin.setName("hello_4"); admin.setOpenId("WeiXin12"); admin.setEnable(true); admin.setRoleId(1); accountService.add(admin, "hello123"); AccountLoginVo accoutLoginVo=new AccountLoginVo(); accoutLoginVo.setName(admin.getName()); accoutLoginVo.setPassword("hello123"); AccountVo result = accountService.login(accoutLoginVo); System.err.println("result=" + result); } @Test public void add() { AccountVo admin = new AccountVo(); admin.setGroupId(1); admin.setName("hello_5"); admin.setOpenId("WeiXin12"); admin.setEnable(true); admin.setRoleId(1); admin.setAvatar("hello.png"); admin.setCreatedTime(new Date()); int rows = accountService.add(admin, "hello123"); Assert.assertTrue(rows > 0); } @Test public void getList() { Page<AccountVo> list = accountService.getList(0, 10); System.out.println(list.get(0)); } @Test public void getTokenTest() { AccountVo account=new AccountVo(); account.setId(123); String token=accountService.getUserToken(account); Assert.assertNotNull(token); System.out.print(token); Assert.assertEquals(account.getId(), accountService.getAccountIdFromToken(token)); } }
[ "simon2007@163.com" ]
simon2007@163.com
b0e2263746a187210ea8a4652fb77bce6d9d25e6
0546107948230e72d8f4dffb0d63c204bc5819ab
/src/main/java/com/lv/model/Person.java
471bdeeeb2e859a391e20a93f16465b198f20bbb
[]
no_license
simperLv/springboot2.0
cbcac6ada6faf80b39576ae3be958d9cc3f76f8e
1e5be4dfcc51c9ba1bb8d04168f3821007bc1ebf
refs/heads/master
2020-03-24T00:06:45.370778
2018-11-22T02:20:41
2018-11-22T02:20:41
142,273,922
0
0
null
null
null
null
UTF-8
Java
false
false
463
java
package com.lv.model; /** * Created by simperLv * on 2018/07/30 16:32 */ public class Person { private String name; private int age; public Person() { } public Person(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public int getAge() { return age; } public String getInfo() { return name + "(" + age + ")"; } }
[ "593324988@qq.com" ]
593324988@qq.com
8eaaa428a133a9238d7b3d0607a5d27b56fb0903
ffb5acde331464fab0786ef60866bdb1344849b9
/src/main/java/com/credit/ACCFinance/service/HistoriCicilanRepository.java
4f869d34cd0feeab8443f4ab6aa37090b8416842
[]
no_license
devoav1997/CrudApplicationSpringboot
5bd31d25c9d0ec0a774cf31556567629eb0895f1
0f6e9c648101b2acbe69ca1a0e23205e48b16a84
refs/heads/main
2023-05-12T20:15:54.790181
2021-05-31T01:30:30
2021-05-31T01:30:30
372,350,227
0
0
null
null
null
null
UTF-8
Java
false
false
254
java
package com.credit.ACCFinance.service; import org.springframework.data.repository.CrudRepository; import com.credit.ACCFinance.model.HistoriCicilan; public interface HistoriCicilanRepository extends CrudRepository<HistoriCicilan, String>{ }
[ "Devoav2012@gmail.com" ]
Devoav2012@gmail.com
3d3ca9030e04d753b0172a92d0dec639cb2ff09f
38641ef8ac481d21a9cacf32c721e84cf31bde82
/Schleifen/Schleifexymultiallforms.java
5cf8ecea82410503c27b82458f3fe0674aaa76c1
[]
no_license
Johny2610/Schulprojekte
a74223beeed9f8738e7cf05cfcd4723649532672
761dff98e5c4d8355192eed03e148b7f3846a814
refs/heads/master
2016-09-06T18:03:14.305954
2016-02-25T15:58:11
2016-02-25T15:58:11
42,719,259
2
0
null
null
null
null
ISO-8859-1
Java
false
false
1,174
java
// Autor: Johannes Julius Weiss // Datum: 05.11.2015 // Version: 1.0 public class Schleifexymultiallforms { public static void main(String[] args) { System.out.println("// Title: Schleifexy //"); System.out.println("// Autor: Johannes Weiss //"); System.out.println("// Datum: 05.11.2015 //"); System.out.println("// Version: 1.0 //\n"); System.out.print("Geben Sie x ein: "); double x = Tastatur.leseKommazahl(); System.out.print("Geben Sie y ein: "); double y = Tastatur.leseKommazahl(); double summe = 1; if (x <= y) { double a; double c; for (a = x; a <= y ; a++ ) { summe = summe * a; } System.out.println("Summe1 = "+summe); summe = 1; double b = x; while ( b <= y ) { summe = summe * b; b++; } System.out.println("Summe2 = "+summe); summe = 1; c = x; do { summe = summe * c; c++; } while ( c <= y ); System.out.println("Summe3 = "+summe); } else { System.err.println("ERROR: x ist größer als y"); } } }
[ "Johny2610@users.noreply.github.com" ]
Johny2610@users.noreply.github.com
daad78112fb8644abff069725fff2f94b5037b19
7f0656763cb27c8973028061c81eec1731d54ce3
/src/main/java/com/example/demo/src/netflixContents/model/GetContentsTvKeepRes.java
88556fa8d610c9276f7ad052f2f61f4eda7850a6
[]
no_license
luoran852/Softsquared_Spring_Netflix
3883eca2abe90693b3438d824bd2aaa1eed2780d
3067d0a6718858707897485adcae2aa17885f483
refs/heads/main
2023-07-12T04:07:28.071213
2021-08-17T13:52:25
2021-08-17T13:52:25
null
0
0
null
null
null
null
UTF-8
Java
false
false
293
java
package com.example.demo.src.netflixContents.model; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.Setter; @Getter @Setter @AllArgsConstructor public class GetContentsTvKeepRes { private String typeTxt; private int keepIdx; private String keepPosterUrl; }
[ "hannn0414@naver.com" ]
hannn0414@naver.com
de5e08db30dae29710c518e2458e7af8a8c6904f
3fda6fc717fbe755a53a04e8d776bbaa7cab83b1
/src/net/aerith/misao/toolkit/ImageConversion/ImageConversionFrame.java
e5b007f9d6db5505679d5d6d2d52896b56fc7946
[]
no_license
jankotek/Pixy2
ef8fe9c8f2c76b63a636286f641cfb07c159454b
7e2480f5eb58eeaee22f6cad9f6784b954b84df9
refs/heads/master
2023-05-29T22:39:28.248329
2011-10-15T14:30:27
2011-10-15T14:30:27
2,581,830
2
0
null
null
null
null
UTF-8
Java
false
false
4,619
java
/* * @(#)ImageConversionFrame.java * * Copyright (C) 1997-2007 Seiichi Yoshida * All rights reserved. */ package net.aerith.misao.toolkit.ImageConversion; import java.awt.*; import java.awt.event.*; import javax.swing.*; import net.aerith.misao.gui.*; import net.aerith.misao.io.filechooser.*; /** * The <code>ImageConversionFrame</code> represents a frame to convert * the format of and transform the selected images. * * @author Seiichi Yoshida (comet@aerith.net) * @version 2003 August 17 */ public class ImageConversionFrame extends BaseFrame { /* * The table. */ protected ImageConversionTable table; /* * The operation. */ protected ImageConversionOperation operation; /* * The control panel. */ protected ImageConversionControlPanel control_panel; /** * The content pane of this frame. */ protected Container pane; /** * Constructs an <code>ImageConversionFrame</code>. */ public ImageConversionFrame ( ) { pane = getContentPane(); table = new ImageConversionTable(); operation = new ImageConversionOperation(table); control_panel = new ImageConversionControlPanel(operation, table); pane.setLayout(new BorderLayout()); JPanel panel = new JPanel(); panel.setLayout(new GridLayout(2, 1)); panel.add(control_panel); panel.add(new JLabel("Drag image files and drop on the table.")); pane.add(panel, BorderLayout.NORTH); pane.add(new JScrollPane(table), BorderLayout.CENTER); initMenu(); } /** * Initializes this window. This is invoked at construction. */ public void initialize ( ) { // Never invoke initMenu() here. It must be invoked after the // control panel is created in the constructor of this class. // initMenu(); } /** * Initializes menu bar. A <code>JMenuBar</code> must be set to * this <code>JFrame</code> previously. */ public void initMenu ( ) { addFileMenu(); addOperationMenu(); super.initMenu(); } /** * Adds the <tt></tt> menus to the menu bar. */ public void addFileMenu ( ) { JMenu menu = addMenu("File"); JMenuItem menu_config = new JMenuItem("Configuration"); menu_config.addActionListener(new ConfigurationListener()); menu.add(menu_config); menu.addSeparator(); JMenuItem item = new JMenuItem("Close"); item.addActionListener(new CloseListener()); menu.add(item); } /** * Adds the <tt>Operaton</tt> menus to the menu bar. */ public void addOperationMenu ( ) { JMenu menu = addMenu("Operation"); JMenuItem[] menu_items = control_panel.getMenuItems(); for (int i = 0 ; i < menu_items.length ; i++) menu.add(menu_items[i]); } /** * Sets the operation. * @param operation the operation. */ protected void setOperation ( ImageConversionOperation operation ) { this.operation = operation; control_panel.setOperation(operation); } /** * Starts the operation. */ public void startOperation ( ) { control_panel.start(); } /** * The <code>ConfigurationListener</code> is a listener class of * menu selection to configure. */ protected class ConfigurationListener implements ActionListener { /** * Invoked when one of the menus is selected. * @param e contains the selected menu item. */ public void actionPerformed ( ActionEvent e ) { if (control_panel.getCurrentMode() == ControlPanel.MODE_SETTING) { ConversionDialog dialog = new ConversionDialog(); int answer = dialog.show(pane); if (answer == 0) { if (dialog.specifiesInputFormat()) { table.setInputImageFileFilter(dialog.getInputFileFilter()); } if (dialog.specifiesOutputFormat()) { table.setOutputImageFileFilter(dialog.getOutputFileFilter(), dialog.changesFilenames()); } if (dialog.transformsAll()) { if (dialog.isSize()) { table.setOutputImageSize(dialog.getImageSize(), dialog.rescalesSbig()); } else { table.setOutputImageScale(dialog.getScale(), dialog.rescalesSbig()); } } if (dialog.appliesImageProcessingFilters()) { table.setImageProcessingFilter(dialog.getFilterSet()); } } } } } /** * The <code>CloseListener</code> is a listener class of menu * selection to close. */ protected class CloseListener implements ActionListener { /** * Invoked when one of the menus is selected. * @param e contains the selected menu item. */ public void actionPerformed ( ActionEvent e ) { dispose(); } } }
[ "jan@kotek" ]
jan@kotek
2a93c190eb6887dd501dbd5153cc0217d014e2fd
ffff630f2e307cc3e0ab118611461a333ddb4f2b
/app/src/main/java/eu/mobiletouch/fotoland/collage/OldCollageView.java
5422b135b731df64ede3f7d66ad24a490fbfe186
[]
no_license
gongadev/Fotoland
159ec1bec49999687e9bf21f8d840ae34cce3efd
d2aac624cc33ce2ac8aa2908489c01e78e4b1ba1
refs/heads/master
2020-03-17T20:03:17.084702
2017-06-27T15:29:26
2017-06-27T15:29:27
null
0
0
null
null
null
null
UTF-8
Java
false
false
14,496
java
package eu.mobiletouch.fotoland.collage; import android.app.Activity; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.util.AttributeSet; import android.view.DragEvent; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.widget.FrameLayout; import android.widget.LinearLayout; import com.lge.gallery.common.Utils; import com.lge.gallery.data.MediaItem; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import eu.mobiletouch.fotoland.collage.OldCollageImageView; public class OldCollageView extends FrameLayout implements OldCollageImageView.CollageChangeImageListener { public static final String CHANGE_COLLAGE = "change_collage"; private static final int[] COLLAGE_DEFAULT_LAYOUT_IDS = { 2130968583, 2130968589, 2130968601, 2130968610, 2130968620, 2130968632, 2130968644, 2130968653 }; private static final boolean DEBUG = false; private static final int[] IMAGE_FRAME_IDS = { 2131623970, 2131623971, 2131623972, 2131623973, 2131623974, 2131623975, 2131623976, 2131623977, 2131623978 }; private static final String TAG = "CollageView"; private static final HashMap<Integer, Integer> mLayoutIds; private ArrayList<Bitmap> mBitmapList = new ArrayList(); private LinearLayout mCollageLayout = null; private ArrayList<MediaItem> mCollageList = new ArrayList(); private int mCurrentViewId; private OldCollageImageView mFocusedView; private ArrayList<OldCollageImageView> mImageViewList; private final LayoutInflater mInflater; private int mReplaceImageViewId; private View mTouchedView; static { int[][] arrayOfInt = new int[79][]; arrayOfInt[0] = { 2131623969, 2130968583 }; arrayOfInt[1] = { 2131623983, 2130968584 }; arrayOfInt[2] = { 2131623984, 2130968585 }; arrayOfInt[3] = { 2131623985, 2130968586 }; arrayOfInt[4] = { 2131623986, 2130968587 }; arrayOfInt[5] = { 2131623987, 2130968588 }; arrayOfInt[6] = { 2131623989, 2130968589 }; arrayOfInt[7] = { 2131623990, 2130968593 }; arrayOfInt[8] = { 2131623991, 2130968594 }; arrayOfInt[9] = { 2131623992, 2130968595 }; arrayOfInt[10] = { 2131623993, 2130968596 }; arrayOfInt[11] = { 2131623994, 2130968597 }; arrayOfInt[12] = { 2131623995, 2130968598 }; arrayOfInt[13] = { 2131623996, 2130968599 }; arrayOfInt[14] = { 2131623997, 2130968600 }; arrayOfInt[15] = { 2131623998, 2130968590 }; arrayOfInt[16] = { 2131623999, 2130968591 }; arrayOfInt[17] = { 2131624000, 2130968592 }; arrayOfInt[18] = { 2131624002, 2130968601 }; arrayOfInt[19] = { 2131624003, 2130968602 }; arrayOfInt[20] = { 2131624004, 2130968603 }; arrayOfInt[21] = { 2131624005, 2130968604 }; arrayOfInt[22] = { 2131624006, 2130968605 }; arrayOfInt[23] = { 2131624007, 2130968606 }; arrayOfInt[24] = { 2131624008, 2130968607 }; arrayOfInt[25] = { 2131624009, 2130968608 }; arrayOfInt[26] = { 2131624010, 2130968609 }; arrayOfInt[27] = { 2131624012, 2130968610 }; arrayOfInt[28] = { 2131624013, 2130968612 }; arrayOfInt[29] = { 2131624014, 2130968613 }; arrayOfInt[30] = { 2131624015, 2130968614 }; arrayOfInt[31] = { 2131624016, 2130968615 }; arrayOfInt[32] = { 2131624017, 2130968616 }; arrayOfInt[33] = { 2131624018, 2130968617 }; arrayOfInt[34] = { 2131624019, 2130968618 }; arrayOfInt[35] = { 2131624020, 2130968619 }; arrayOfInt[36] = { 2131624021, 2130968611 }; arrayOfInt[37] = { 2131624023, 2130968620 }; arrayOfInt[38] = { 2131624024, 2130968624 }; arrayOfInt[39] = { 2131624025, 2130968625 }; arrayOfInt[40] = { 2131624026, 2130968626 }; arrayOfInt[41] = { 2131624027, 2130968627 }; arrayOfInt[42] = { 2131624028, 2130968628 }; arrayOfInt[43] = { 2131624029, 2130968629 }; arrayOfInt[44] = { 2131624030, 2130968630 }; arrayOfInt[45] = { 2131624031, 2130968631 }; arrayOfInt[46] = { 2131624032, 2130968621 }; arrayOfInt[47] = { 2131624033, 2130968622 }; arrayOfInt[48] = { 2131624034, 2130968623 }; arrayOfInt[49] = { 2131624036, 2130968632 }; arrayOfInt[50] = { 2131624037, 2130968636 }; arrayOfInt[51] = { 2131624038, 2130968637 }; arrayOfInt[52] = { 2131624039, 2130968638 }; arrayOfInt[53] = { 2131624040, 2130968639 }; arrayOfInt[54] = { 2131624041, 2130968640 }; arrayOfInt[55] = { 2131624042, 2130968641 }; arrayOfInt[56] = { 2131624043, 2130968642 }; arrayOfInt[57] = { 2131624044, 2130968643 }; arrayOfInt[58] = { 2131624045, 2130968633 }; arrayOfInt[59] = { 2131624046, 2130968634 }; arrayOfInt[60] = { 2131624047, 2130968635 }; arrayOfInt[61] = { 2131624049, 2130968644 }; arrayOfInt[62] = { 2131624050, 2130968645 }; arrayOfInt[63] = { 2131624051, 2130968646 }; arrayOfInt[64] = { 2131624052, 2130968647 }; arrayOfInt[65] = { 2131624053, 2130968648 }; arrayOfInt[66] = { 2131624054, 2130968649 }; arrayOfInt[67] = { 2131624055, 2130968650 }; arrayOfInt[68] = { 2131624056, 2130968651 }; arrayOfInt[69] = { 2131624057, 2130968652 }; arrayOfInt[70] = { 2131624059, 2130968653 }; arrayOfInt[71] = { 2131624060, 2130968654 }; arrayOfInt[72] = { 2131624061, 2130968655 }; arrayOfInt[73] = { 2131624062, 2130968656 }; arrayOfInt[74] = { 2131624063, 2130968657 }; arrayOfInt[75] = { 2131624064, 2130968658 }; arrayOfInt[76] = { 2131624065, 2130968659 }; arrayOfInt[77] = { 2131624066, 2130968660 }; arrayOfInt[78] = { 2131624067, 2130968661 }; HashMap localHashMap = new HashMap(); int i = 0; while (i < arrayOfInt.length) { localHashMap.put(Integer.valueOf(arrayOfInt[i][0]), Integer.valueOf(arrayOfInt[i][1])); i += 1; } mLayoutIds = localHashMap; } public OldCollageView(Context paramContext, AttributeSet paramAttributeSet) { super(paramContext, paramAttributeSet); this.mInflater = ((LayoutInflater)paramContext.getSystemService("layout_inflater")); this.mImageViewList = new ArrayList(); } private int findImageViewIndex(int paramInt) { int k = 0; int i = 0; for (;;) { int j = k; if (i < IMAGE_FRAME_IDS.length) { if (IMAGE_FRAME_IDS[i] == paramInt) { j = i; } } else { return j; } i += 1; } } private void onCollageImageChanged(int paramInt1, int paramInt2) { paramInt1 = findImageViewIndex(paramInt1); paramInt2 = findImageViewIndex(paramInt2); MediaItem localMediaItem1 = (MediaItem)this.mCollageList.get(paramInt2); Bitmap localBitmap1 = (Bitmap)this.mBitmapList.get(paramInt2); MediaItem localMediaItem2 = (MediaItem)this.mCollageList.get(paramInt1); Bitmap localBitmap2 = (Bitmap)this.mBitmapList.get(paramInt1); this.mCollageList.set(paramInt1, localMediaItem1); this.mBitmapList.set(paramInt1, localBitmap1); this.mCollageList.set(paramInt2, localMediaItem2); this.mBitmapList.set(paramInt2, localBitmap2); ((OldCollageImageView)this.mImageViewList.get(paramInt1)).setImageItem((MediaItem)this.mCollageList.get(paramInt1), (Bitmap)this.mBitmapList.get(paramInt1)); ((OldCollageImageView)this.mImageViewList.get(paramInt1)).updateImageBitmap(); ((OldCollageImageView)this.mImageViewList.get(paramInt2)).setImageItem((MediaItem)this.mCollageList.get(paramInt2), (Bitmap)this.mBitmapList.get(paramInt2)); ((OldCollageImageView)this.mImageViewList.get(paramInt2)).updateImageBitmap(); } private void updateLayout(View paramView) { if (paramView != null) { removeView(paramView); } this.mImageViewList.clear(); int i = 0; while (i < this.mBitmapList.size()) { paramView = (OldCollageImageView)this.mCollageLayout.findViewById(IMAGE_FRAME_IDS[i]); paramView.setImageChangeListner(this); paramView.setImageItem((MediaItem)this.mCollageList.get(i), (Bitmap)this.mBitmapList.get(i)); this.mImageViewList.add(paramView); i += 1; } } public void clearData() { this.mCollageList.clear(); Iterator localIterator = this.mBitmapList.iterator(); while (localIterator.hasNext()) { Bitmap localBitmap = (Bitmap)localIterator.next(); if (localBitmap != null) { localBitmap.recycle(); } } this.mBitmapList.clear(); localIterator = this.mImageViewList.iterator(); while (localIterator.hasNext()) { ((OldCollageImageView)localIterator.next()).clearData(); } } public int getCurrentLayoutId() { return this.mCurrentViewId; } public MediaItem getDefaultImageItem() { return (MediaItem)this.mCollageList.get(0); } public int getImageCount() { return this.mBitmapList.size(); } public int getItemCount() { return this.mCollageList.size(); } public ArrayList<MediaItem> getItemList() { return this.mCollageList; } public int getReplaceViewId() { return this.mReplaceImageViewId; } public Bitmap getSaveCollageImage() { this.mCollageLayout.destroyDrawingCache(); this.mCollageLayout.setDrawingCacheEnabled(true); return this.mCollageLayout.getDrawingCache(); } public void onCollageImageReplaced(int paramInt) { this.mReplaceImageViewId = paramInt; Intent localIntent = new Intent("android.intent.action.GET_CONTENT"); localIntent.setType("image/*"); localIntent.putExtra("android.intent.extra.LOCAL_ONLY", true); localIntent.putExtra("change_collage", true); localIntent.setComponent(new ComponentName("com.android.gallery3d", "com.android.gallery3d.app.Gallery")); ((Activity)getContext()).startActivityForResult(localIntent, 1); } public void onDrag(View paramView, DragEvent paramDragEvent) { switch (paramDragEvent.getAction()) { default: case 5: case 6: do { do { return; } while (!(paramView instanceof OldCollageImageView)); this.mFocusedView = ((OldCollageImageView)paramView); this.mFocusedView.setImageFrameFocusd(true); return; } while (this.mFocusedView == null); this.mFocusedView.setImageFrameFocusd(false); this.mFocusedView = null; return; case 3: onCollageImageChanged(((View)paramDragEvent.getLocalState()).getId(), paramView.getId()); return; } if (this.mFocusedView != null) { this.mFocusedView.setImageFrameFocusd(false); this.mFocusedView = null; } int i = findImageViewIndex(((View)paramDragEvent.getLocalState()).getId()); ((OldCollageImageView)this.mImageViewList.get(i)).setVisibility(0); } public boolean onTouchEvent(View paramView, MotionEvent paramMotionEvent) { if ((paramMotionEvent.getAction() == 1) || (paramMotionEvent.getAction() == 3)) { this.mTouchedView = null; } do { return true; if (this.mTouchedView == null) { this.mTouchedView = paramView; return true; } } while (paramView.equals(this.mTouchedView)); return false; } public void pause() { int i = 0; while (i < this.mImageViewList.size()) { ((OldCollageImageView)this.mImageViewList.get(i)).pause(); i += 1; } } public void replaceImageBitmap(Bitmap paramBitmap) { if (paramBitmap == null) { return; } int i = findImageViewIndex(this.mReplaceImageViewId); this.mBitmapList.set(i, paramBitmap); ((OldCollageImageView)this.mImageViewList.get(i)).setImageItem((MediaItem)this.mCollageList.get(i), (Bitmap)this.mBitmapList.get(i)); ((OldCollageImageView)this.mImageViewList.get(i)).updateImageBitmap(); } public void resume() { int i = 0; while (i < this.mImageViewList.size()) { ((OldCollageImageView)this.mImageViewList.get(i)).resume(); i += 1; } } public void setImageBitmap(MediaItem paramMediaItem, Bitmap paramBitmap) { if ((paramMediaItem == null) || (paramBitmap == null)) { return; } this.mCollageList.add(paramMediaItem); this.mBitmapList.add(paramBitmap); } public void setLayoutById(int paramInt) { LinearLayout localLinearLayout = this.mCollageLayout; this.mCurrentViewId = paramInt; if (paramInt == 0) { paramInt = Utils.clamp(this.mBitmapList.size() - 2, 0, COLLAGE_DEFAULT_LAYOUT_IDS.length - 1); } for (this.mCollageLayout = ((LinearLayout)this.mInflater.inflate(COLLAGE_DEFAULT_LAYOUT_IDS[paramInt], null, false));; this.mCollageLayout = ((LinearLayout)this.mInflater.inflate(((Integer)mLayoutIds.get(Integer.valueOf(paramInt))).intValue(), null, false))) { addView(this.mCollageLayout); updateLayout(localLinearLayout); return; } } public void setMediaItemList(MediaItem paramMediaItem) { int i = findImageViewIndex(this.mReplaceImageViewId); this.mCollageList.set(i, paramMediaItem); } public void setReplaceViewId(int paramInt) { this.mReplaceImageViewId = paramInt; } }
[ "r.zaharia@gamahealthcare.com" ]
r.zaharia@gamahealthcare.com
9863ecbeca49d2a9d682fbf428291d86923d9891
32f5a60e971dd6db3bf6494f8ddc5de6053d6f66
/src/main/java/ohtu/ohtuvarasto/Varasto.java
6f6f0cf6812a8a349648d50412eb41af602ed883
[]
no_license
ssuihko/ohtu-2019-viikko1
0cc1a0f41b892342ab9557ceaf0f4cd3202fc92a
8c4a203b215e5c465697f3171a9daac5bd2052a2
refs/heads/master
2020-08-31T05:02:54.316722
2019-11-10T18:03:14
2019-11-10T18:03:14
218,598,252
0
0
null
null
null
null
UTF-8
Java
false
false
2,539
java
package ohtu.ohtuvarasto; public class Varasto { // --- piilotettu tietorakenteen toteutus: --- private double tilavuus; // paljonko varastoon mahtuu, > 0 private double saldo; // paljonko varastossa on nyt, >= 0 // --- konstruktorit: --- public Varasto(double tilavuus) { // tilavuus on annettava if (tilavuus > 0.0) { this.tilavuus = tilavuus; } else {// virheellinen, nollataan this.tilavuus = 0.0; // => käyttökelvoton varasto } saldo = 0; // oletus: varasto on tyhjä } public Varasto(double tilavuus, double alkuSaldo) { // kuormitetaan this(tilavuus); if (alkuSaldo < 0.0) { this.saldo = 0.0; } else if (alkuSaldo <= tilavuus) {// mahtuu this.saldo = alkuSaldo; } else { this.saldo = tilavuus; // täyteen ja ylimäärä hukkaan! } } // --- ottavat aksessorit eli getterit: --- public double getSaldo() { return saldo; } public double getTilavuus() { return tilavuus; } public double paljonkoMahtuu() { // huom: ominaisuus voidaan myös laskea return tilavuus - saldo; // ei tarvita erillistä kenttää vielaTilaa tms. } // --- asettavat aksessorit eli setterit: --- public void lisaaVarastoon(double maara) { if (maara < 0) {// virhetilanteessa voidaan tehdä return; // tällainen pikapoistuminenkin! } if (maara <= paljonkoMahtuu()) {// omia aksessoreita voi kutsua saldo = saldo + maara; // ihan suoraan sellaisinaan } else { saldo = tilavuus; // täyteen ja ylimäärä hukkaan! } } public double otaVarastosta(double maara) { if (maara < 0) { // virhetilanteessa voidaan tehdä return 0.0; // tällainen pikapoistuminenkin! } if (maara > saldo) { // annetaan mitä voidaan double kaikkiMitaVoidaan = saldo; saldo = 0.0; // ja tyhjäksi menee return kaikkiMitaVoidaan; // poistutaan saman tien } // jos tänne päästään, kaikki pyydetty voidaan antaa saldo = saldo - maara; // vähennetään annettava saldosta return maara; } // --- Merkkijonoesitys Varasto-oliolle: ---- public String toString() { return ("saldo = " + saldo + ", vielä tilaa " + paljonkoMahtuu()); } }
[ "sahsuihkonen@gmail.com" ]
sahsuihkonen@gmail.com
8dbc333326a4a55da3b83fb0f906d290fd655eeb
b94e5c99dd5454e903511b0ca31b4b4e21c92ce3
/FinalProject/JavaApplication21/src/drawingPackage/paint.java
ef9ba74745945e86d27982f3cd222e23b7718a76
[]
no_license
kent7777777/CS203
183629ee3fd86250bf52da4800e244f26b30b722
e549ab04137992c95a0bb8026be062dc08b692d0
refs/heads/master
2016-09-09T22:18:37.994250
2015-03-19T15:01:47
2015-03-19T15:01:47
31,226,437
0
0
null
null
null
null
UTF-8
Java
false
false
3,755
java
/* * 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 drawingPackage; /** * * @author Kevin */ import java.awt.*; import java.awt.event.*; import javax.swing.*; public class paint { private Icon iconB; private Icon iconM; private Icon iconB1; private Icon iconG; private Icon iconR; private JFrame frame; private Container content; private JPanel panel; private JButton clearButton; private JButton blueButton; private JButton magentaButton; private JButton blackButton; private JButton greenButton; private JButton redButton; public static void main(String[] args){ paint start = new paint(); start.go(); } public void go(){ iconB = new ImageIcon("blue.gif"); iconM = new ImageIcon("magenta.gif"); iconB1 = new ImageIcon("black.gif"); iconG = new ImageIcon("green.gif"); iconR = new ImageIcon("red.gif"); frame = new JFrame("Paint"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); content = frame.getContentPane(); content.setLayout(new BorderLayout()); final PadDraw drawPad = new PadDraw(); content.add(drawPad, BorderLayout.CENTER); panel = new JPanel(); panel.setPreferredSize(new Dimension(32, 64)); panel.setMinimumSize(new Dimension(32, 68)); panel.setMaximumSize(new Dimension(32, 68)); clearButton = new JButton("Clear"); clearButton.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent e) { drawPad.clear(); } }); redButton = new JButton(iconR); redButton.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent e){ drawPad.red(); } }); greenButton = new JButton(iconG); greenButton.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent e) { drawPad.green(); } }); blackButton = new JButton(iconB1); blackButton.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent e) { drawPad.black(); } }); magentaButton = new JButton(iconM); magentaButton.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent e) { drawPad.magenta(); } }); blueButton = new JButton(iconB); blueButton.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent e) { drawPad.blue(); } }); blackButton.setPreferredSize(new Dimension(16, 16)); magentaButton.setPreferredSize(new Dimension(16, 16)); redButton.setPreferredSize(new Dimension(16, 16)); blueButton.setPreferredSize(new Dimension(16, 16)); greenButton.setPreferredSize(new Dimension(16,16)); panel.add(redButton); panel.add(greenButton); panel.add(blackButton); panel.add(magentaButton); panel.add(blueButton); panel.add(clearButton); content.add(panel, BorderLayout.NORTH); frame.setSize(600, 600); frame.setVisible(true); } }
[ "coolkent7777777@gmail.com" ]
coolkent7777777@gmail.com
b84dd53fd994659fb9fd35070f013bc05f6db72b
006b72974754b8a69875b1464e34f85a7e928766
/src/main/java/com/hackcumple/eventsapp/data/Event.java
7d46e2b094757e2ec1983df035e277c4ef64403c
[]
no_license
hackcumple/events-app
437fa32705927005c05d2fbf05606c3d5bd862f2
0c129ce69363f03b5c1ae5d6ff6d8e387f41942a
refs/heads/master
2020-04-30T18:16:50.005384
2019-03-24T11:48:35
2019-03-24T11:48:35
177,005,724
0
0
null
null
null
null
UTF-8
Java
false
false
504
java
package com.hackcumple.eventsapp.data; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import javax.persistence.*; import java.time.Instant; @Entity @NoArgsConstructor @Setter @Getter public class Event { @Id @GeneratedValue(strategy = GenerationType.AUTO) Long id; String name; String description; Instant date; String city; @Column(name = "STREETNAME") String streetName; @Column(name = "STREETNUMBER") String streetNumber; }
[ "rafal.jankowski@comarch.com" ]
rafal.jankowski@comarch.com
87dd1cb9068556824922bec880ceb1f56c7e79ad
75b06e3820f60812c1b2297638e10ed6f9e1e4d1
/src/main/java/cz/jkoudelka/tictactoe/cpu/package-info.java
4872621352bd86dec7de4990779cc6272cc5a63e
[]
no_license
jlochman/TicTacToe
1a86e8b621de004436c9f760216165d80ea8a799
9a15244b0281a2afc8fc78b18709785c0f1d5785
refs/heads/master
2021-01-25T08:07:28.075775
2017-07-06T12:30:20
2017-07-06T12:30:20
93,718,772
0
0
null
null
null
null
UTF-8
Java
false
false
136
java
/** * nutne tridy k vytvoreni logiku, jak CPU bude hrat tic-tac-toe. * * @author jlochman * */ package cz.jkoudelka.tictactoe.cpu;
[ "jan.lochman@icloud.com" ]
jan.lochman@icloud.com
5e4c344050ef06dfcc15658f7512edda40e7edce
b731f4a775a653b1cad9582e25cc802ba02e0ae1
/easymis-workflow-elasticsearch/src/main/java/org/easymis/workflow/elasticsearch/upload/UploadController.java
95a91c8af3cded49d7876b66e532c1900794f291
[]
no_license
tanyujie/easymis-workflow
1f1af7b6e4746893a27aff7f6bb90d981049b268
5a0ae50e5139c3a5eff8b5494b8b38e70008f4cd
refs/heads/master
2022-07-18T03:33:21.296478
2019-09-01T11:47:31
2019-09-01T11:47:31
199,408,179
3
1
null
2022-06-21T01:33:43
2019-07-29T08:09:44
JavaScript
UTF-8
Java
false
false
2,150
java
package org.easymis.workflow.elasticsearch.upload; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestPart; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; /** * @Description: * @author: ztd * @date 2019/6/17 下午2:56 */ @RequestMapping("/api") @RestController @Api(value = "语料信息controller", tags = { "语料信息操作接口" }) public class UploadController { @Autowired private UploadClient client; /** * 单个文件上传 * @param type * @param file * @return */ @PostMapping(value ="/upload",produces = {MediaType.APPLICATION_JSON_UTF8_VALUE}, consumes = MediaType.MULTIPART_FORM_DATA_VALUE) public String upload(@RequestParam(value = "type", required = false) String type, @RequestPart(value="file", required = false)MultipartFile file) { System.out.println(file.getOriginalFilename()); return "成功!"; } /** * 多个文件上传 * @param type * @param files * @return */ @ApiOperation(value = "多条件查询项目列表", notes = "多条件查询项目列表") @PostMapping(value ="/multiUpload",produces = {MediaType.APPLICATION_JSON_UTF8_VALUE}, consumes = MediaType.MULTIPART_FORM_DATA_VALUE) public String multiUpload(@RequestParam(value = "type", required = false) String type, @RequestPart(value="files", required = false)MultipartFile[] files) { for (MultipartFile file : files) { //System.out.println(file.getOriginalFilename()); } System.out.println(client.multiUpload(type, files)); return "成功!"; } }
[ "13551259347@139.com" ]
13551259347@139.com
3ecadce5e2f4850e526a17389acfcb42b0d38f21
67cab5e5c9cb1f3921f5bdb58a95d947047abf61
/src/FourSum_18.java
88e9f74ff746332109c1622854031e84876fe6cd
[]
no_license
wssgyyg/Leetcode
7576f860195f0ab4f9ef638212c4fa3952290e76
679cfc4aa01ad3e9a226ae44969142d5a7d3388c
refs/heads/master
2021-05-14T01:31:06.275203
2018-03-13T03:38:54
2018-03-13T03:38:54
116,569,245
0
0
null
2018-01-08T15:38:56
2018-01-07T13:51:05
null
UTF-8
Java
false
false
1,465
java
import java.util.Arrays; import java.util.Collections; import java.util.LinkedList; import java.util.List; public class FourSum_18 { public List<List<Integer>> fourSum(int[] nums, int target) { Arrays.sort(nums); List<List<Integer>> resultList = new LinkedList<>(); for (int i = 0; i < nums.length - 3; i++) { if (i == 0 || nums[i] != nums[i - 1]) { for (int j = i + 1; j < nums.length - 2; j++) { if (j == i + 1 || nums[j] != nums[j - 1]) { int remain = target - nums[i] - nums[j]; int left = j + 1; int right = nums.length - 1; while (left < right) { int twoSum = nums[left] + nums[right]; if (twoSum == remain) { resultList.add(Arrays.asList(nums[i], nums[j], nums[left], nums[right])); while (left < right && nums[++left] == nums[left - 1]); while (left < right && nums[--right] == nums[right + 1]); } else if (twoSum < remain) { left++; } else { right--; } } } } } } return resultList; } }
[ "827580591@qq.com" ]
827580591@qq.com
df6dd9409a933614e0f8b192747ce5796e2207d1
eab8f724c5fcec2f0d2d490ac362a67e0bf00c4d
/shoppingbackend/src/test/java/com/sujan/shoppingbackend/test/CartLineTestCase.java
8348a9a33c3a28264a4e52cb99253b3f0f11459f
[]
no_license
Shoojan/sajilo-shopping
37a185467d93e994fa8a3faaee6fff200a529804
28b1ce4672aec4a4a407aaaa05687519a4692d60
refs/heads/master
2021-09-03T06:19:56.755572
2018-01-06T10:17:00
2018-01-06T10:17:00
112,017,443
1
0
null
null
null
null
UTF-8
Java
false
false
2,192
java
package com.sujan.shoppingbackend.test; import static org.junit.Assert.assertEquals; import org.junit.BeforeClass; import org.junit.Test; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import com.sujan.shoppingbackend.DAO.CartLineDAO; import com.sujan.shoppingbackend.DAO.ProductDAO; import com.sujan.shoppingbackend.DAO.UserDAO; import com.sujan.shoppingbackend.DTO.Cart; import com.sujan.shoppingbackend.DTO.CartLine; import com.sujan.shoppingbackend.DTO.Product; import com.sujan.shoppingbackend.DTO.User; public class CartLineTestCase { private static AnnotationConfigApplicationContext context; private static CartLineDAO cartLineDAO = null; private static ProductDAO productDAO = null; private static UserDAO userDAO = null; private Product product = null; private Cart cart = null; private User user = null; private CartLine cartLine = null; @BeforeClass public static void init() { context = new AnnotationConfigApplicationContext(); context.scan("com.sujan.shoppingbackend"); context.refresh(); productDAO = (ProductDAO) context.getBean("productDAO"); cartLineDAO = (CartLineDAO) context.getBean("cartLineDAO"); userDAO = (UserDAO) context.getBean("userDAO"); } @Test public void testAddNewCartLine() { //1. Get the user user = userDAO.getByEmail("ravi@gmail.com"); //2. Fetch the cart cart = user.getCart(); //3. Get the product product = productDAO.get(1); //4. Create a new cart line cartLine = new CartLine(); cartLine.setBuyingPrice(product.getUnitPrice()); cartLine.setProductCount(cartLine.getProductCount() + 1); cartLine.setTotal(cartLine.getProductCount()*product.getUnitPrice()); cartLine.setAvailable(true); cartLine.setCartId(cart.getId()); cartLine.setProduct(product); assertEquals("Failed to add a cartline.",true,cartLineDAO.add(cartLine)); //Update the cart cart.setGrandTotal(cart.getGrandTotal() + cartLine.getTotal()); cart.setCartLines(cart.getCartLines() + 1); assertEquals("Failed to update the cart.",true,cartLineDAO.updateCart(cart)); } }
[ "sujan.mhrzn2@gmail.com" ]
sujan.mhrzn2@gmail.com
8feeb56866ef4e7329efaaa778bafa2f5f07b49d
18d65d6b710f3d1dc1ad2a1d78c74ef480a8ef56
/src/core/introducaoMetodos/teste/TestNumeros.java
278745810d6f15de49a8182ad6aba12e4a01402f
[]
no_license
leandro19br/Java
95d882c738a99691aeebce80906dd0654a566941
8831e7d4b65e38b59e9764a75d4f4c8ae0b73ca4
refs/heads/master
2021-08-23T06:41:13.492986
2017-12-03T23:38:43
2017-12-03T23:38:43
112,972,277
0
0
null
null
null
null
UTF-8
Java
false
false
444
java
package core.introducaoMetodos.teste; import core.introducaoMetodos.classes.Calculadora; public class TestNumeros { public static void main(String[] args) { Calculadora cal = new Calculadora(); int num1 = 1; int num2 = 2; cal.alterarDoisNumeros(num1,num2); System.out.println("dentro do teste"); System.out.println("numero1 " + num1); System.out.println("numero2 " + num2); } }
[ "leandro19br@gmail.com" ]
leandro19br@gmail.com
2fbee40c9bd4dfedbd458b125e7d950fbd34c9e6
e77abeae4169e48f8564145316fb8fa8a9510008
/skiWorld-ejb/src/main/java/skiworld/services/HandelUser.java
dc2508a1cfb1ed4b8e21db2bd8d12f8d5725fe09
[]
no_license
HoudaFer/Skiworld_JEE
4e7269e22edb77ed56175f595d2a59b12c2b7521
9958daab21426fd0e6cf25ba5a6571ed4856b682
refs/heads/master
2021-07-16T11:09:54.055127
2017-10-20T12:52:56
2017-10-20T12:52:56
107,608,705
0
0
null
null
null
null
UTF-8
Java
false
false
2,508
java
package skiworld.services; import java.util.Iterator; import java.util.List; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query; import javax.persistence.TypedQuery; import skiworld.persistence.Client; import skiworld.persistence.EventHolder; import skiworld.persistence.Instructor; import skiworld.persistence.Player; import skiworld.persistence.RestaurantManager; import skiworld.persistence.SkiMan; import skiworld.persistence.User; import skiworld.persistence.Worker; @Stateless public class HandelUser implements IHandelUser { @PersistenceContext EntityManager em; @Override public void addSkiMan(SkiMan skiman) { em.persist(skiman); } @Override public void addInstructor(Instructor instructor) { em.persist(instructor); } @Override public void addEventHolder(EventHolder eventHolder) { em.persist(eventHolder); } @Override public void addPlayer(Player player) { em.persist(player); } @Override public void addWorker(Worker worker) { em.persist(worker); } @Override public void addRestaurantManager(RestaurantManager restaurantManager) { em.persist(restaurantManager); } @Override public List<User> getUser() { TypedQuery<User> querry = em.createQuery("select u from User u", User.class); return querry.getResultList(); } @Override public List<Instructor> getInstructor() { TypedQuery<Instructor> querry = em.createQuery("select i from Instructor i", Instructor.class); return querry.getResultList(); } @Override public void removeUser(User user) { em.remove(em.merge(user)); } @Override public void updateUser(User user) { em.merge(user); } @Override public void addClient(Client client) { em.persist(client); } @Override public List<Worker> FindAllWorker() { TypedQuery<Worker> query=em.createQuery("Select w from Worker w", Worker.class); return query.getResultList(); } @Override public void deleteWorker(Worker worker) { em.remove(em.merge(worker)); } @Override public void updateWorker(Worker worker) { em.merge(worker); } @Override public boolean removeUserById(int id) { Iterator<User> iterator=getUser().iterator(); while(iterator.hasNext()){ User r=iterator.next(); if(r.getIdUser()==id){ em.remove(r); return true; } } return false; } }
[ "noreply@github.com" ]
noreply@github.com
784ae9848769a4a29aea2ee31b94391935ca1a80
81ed2d12440bfbf1443ad2b4baa166a616eb80ad
/src/game/states/mainGameState/level/entity/mobs/contollers/WonderingController.java
3d93f1aaef8e6de4f5aa4b5119e35b11f600d132
[]
no_license
alycarter/graphicsv2
794f9b00ad254d91fb6409c15c1314f36df29157
c7b74476be039dfd6ce4e75fc3fa65eb325a0ce1
refs/heads/master
2020-05-29T13:33:41.487259
2013-04-02T09:19:46
2013-04-02T09:19:46
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,319
java
package game.states.mainGameState.level.entity.mobs.contollers; import game.Game; import game.states.mainGameState.level.entity.mobs.Mob; public class WonderingController extends MobController{ private Mob mob; private Game game; private int teatherX; private int teatherY; private int range; private double walkDelay=5; private double walkTimer; public WonderingController(Mob mob, int range, Game game) { this.mob=mob; this.game=game; this.teatherX=(int)mob.getX(); this.teatherY=(int)mob.getY(); this.range = range; this.walkTimer=Math.random()*this.walkDelay; } @Override public void update() { if(walkTimer <= 0){ walkTimer = walkDelay+((Math.random()*2)-1); if(Math.random()<0.5){ if(Math.abs(mob.getX()-this.teatherX)>=this.range){ if(mob.getX()>this.teatherX){ mob.moveLeft(); }else{ mob.moveRight(); } }else{ if(Math.random()<0.5){ mob.moveLeft(); }else{ mob.moveRight(); } } }else{ if(Math.abs(mob.getY()-this.teatherY)>=this.range){ if(mob.getY()>this.teatherY){ mob.moveUp(); }else{ mob.moveDown(); } }else{ if(Math.random()<0.5){ mob.moveUp(); }else{ mob.moveDown(); } } } }else{ walkTimer -= game.deltaTime; } } }
[ "alycarter@hotmail.co.uk" ]
alycarter@hotmail.co.uk
587274dbf2b361aca6ad084bc7fb4d168a64b796
deb400b102a2489c9a0cf3fd545358151b78eb66
/proj_studio/app/src/main/java/com/work/teacher/bean/HistoryType.java
c15c639a255edab5ae117867a27a6b9a9a65e642
[]
no_license
DavidMGT/Testdemo2
8891e905926d4aea373524e8e0bf1d4cdcfce2aa
a9bce5dc64162694b5b7402fa2440f989a9a0d08
refs/heads/master
2021-05-01T21:37:28.031204
2016-09-23T14:41:42
2016-09-23T14:41:42
69,034,326
0
0
null
null
null
null
UTF-8
Java
false
false
1,044
java
package com.work.teacher.bean; import java.io.Serializable; import java.util.List; /** * 历史列表分类 * * @author 左丽姬 */ public class HistoryType implements Serializable { private String name; private List<HistoryClass> list; private int status;// 0.当前自定义班级,1.当前加入班级,2.用户历史创建班级,3.用户历史加入班级 public HistoryType() { super(); } public HistoryType(String name, List<HistoryClass> list, int status) { super(); this.name = name; this.list = list; this.status = status; } public String getName() { return name; } public void setName(String name) { this.name = name; } public List<HistoryClass> getList() { return list; } public void setList(List<HistoryClass> list) { this.list = list; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } @Override public String toString() { return "HistoryType [name=" + name + ", list=" + list + ", status=" + status + "]"; } }
[ "马贵涛" ]
马贵涛
ee405136269a953a8e3f7f9e5c9506b1f7abf712
c53e70ba016a9ba6396a2c4f994bc84911e5f6a8
/ed2.tinkerscript/src/br/edu/ifsp/cmp/asw_ed2/tinkerscript/sintatico/arvore/nos/NóExprAtomo.java
fa91bc5d20f90be02af20ad5d8c91536bb2504c8
[ "MIT" ]
permissive
OliverPimentel/arquiteturadesoftware
ef60ae6c57c03b477036b742e0891a972a2ecdec
6def4067f190dd51d5c59c2a2007a407d036896f
refs/heads/master
2021-01-23T21:43:45.827145
2015-06-24T12:08:06
2015-06-24T12:08:06
31,989,220
0
0
null
2015-03-11T00:19:41
2015-03-11T00:19:41
null
UTF-8
Java
false
false
118
java
package br.edu.ifsp.cmp.asw_ed2.tinkerscript.sintatico.arvore.nos; public class NóExprAtomo extends NóAbstrato { }
[ "daniel.t.dt@gmail.com" ]
daniel.t.dt@gmail.com
02dc224f57dbd1b1647bbafe786dd5c39c2c041d
39e880dacc9a01d03399b3ff1fb5e96b98802039
/tern-core/src/main/java/org/ternlang/core/resume/Promise.java
577702928de95362c3307f91d96d89b7ab72dbe7
[]
no_license
tern-lang/tern
581aa79bebcfe079fe7648f764e921ecb7a12390
7cf10f325f25b379717985673af4c0bae308a712
refs/heads/master
2023-07-18T12:27:05.425643
2023-07-09T13:54:21
2023-07-09T13:54:21
169,908,813
24
2
null
2023-02-10T16:44:12
2019-02-09T20:11:12
Java
UTF-8
Java
false
false
512
java
package org.ternlang.core.resume; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; public interface Promise<T> { T value(); T value(long wait); T value(long wait, TimeUnit unit); Promise<T> join(); Promise<T> join(long wait); Promise<T> join(long wait, TimeUnit unit); Promise<T> success(Task<T> task); Promise<T> success(Runnable task); Promise<T> failure(Task<Object> task); Promise<T> failure(Runnable task); Future<T> future(); }
[ "theternlang@gmail.com" ]
theternlang@gmail.com
af30b7833e83d0354c4b69c4adaae8fb82baeb7b
c205ea4c0d8b4c361bf518d91fdbc901fc966ae0
/SetterEgetters/src/aplication/Program.java
19670d333448a71d0bbc59ab7e44fec080e86a2d
[]
no_license
wilianfidelis/CursoJava
0df187fd69c9a7169fa08e8c2bd7609a8c59ddd9
0e45d33d3c1c6b891837f8198b853767e84419fe
refs/heads/master
2020-08-24T18:57:34.528143
2020-03-20T19:43:38
2020-03-20T19:43:38
216,886,063
0
0
null
null
null
null
ISO-8859-1
Java
false
false
1,436
java
package aplication; import java.util.Locale; import java.util.Scanner; import entites.Product; public class Program { public static void main(String[] args) { Scanner sc = new Scanner(System.in); Locale.setDefault(Locale.US); Product acount; /* ---- Criação da variavel para não ficar no if ---*/ System.out.print(" Digite o número da conta: "); int number = sc.nextInt(); System.out.print(" Digite o nome do titular: "); sc.nextLine(); String holder = sc.nextLine(); System.out.print("Ira com um deposito inicial (y/n):"); char response = sc.next().charAt(0); if (response == 'y') { System.out.print(" Entre com deposito inicial: "); double initialDeposit = sc.nextDouble(); acount = new Product(number, holder, initialDeposit); } else { acount = new Product(number, holder); } System.out.println(); System.out.println("Valor da conta atualizado: "); System.out.println(acount); System.out.println(); System.out.print("Entre com o valor do deposito: "); double depositValue = sc.nextDouble(); acount.deposit(depositValue); System.out.println("Valor da conta atualizado: "); System.out.println(acount); System.out.println(); System.out.print("Entre com o valor do saque: "); double saque = sc.nextDouble(); acount.withdraw(saque); System.out.println("Valor da conta atualizado: "); System.out.println(acount); sc.close(); } }
[ "wilian.fidelis.adler@gmail.com" ]
wilian.fidelis.adler@gmail.com
86d22b016b95a43a1035f36a28780b06d2846ad6
0f18f506a3b6bdbba61ae4116ab2039ba5bcd8e1
/JavaServlets/out/artifacts/JavaServlets_war_exploded/message.java
d837a9e18c9dd31ebf62380ba34a8d62550f1bb4
[]
no_license
BilalAli181999/Javascript
a730c505b09d6acc736c81db55c91757e3c465ea
99266c1c4d68084f54d512101b97503dc3f61787
refs/heads/master
2022-12-22T01:09:48.813996
2019-09-01T20:08:02
2019-09-01T20:08:02
205,726,574
0
0
null
2022-12-16T10:19:21
2019-09-01T20:05:47
JavaScript
UTF-8
Java
false
false
401
java
import java.io.*; import java.servlet.*; import java.servlet.http.*; public class message extends HttpServlet { private String message; public void doGet(HttpServletRequest request,HttpServletResponse response) { message="hello friends"; response.setContentType("text/html"); PrintWriter out=request.getWriter(); out.print("<h1>"+message+"</h1>"); } }
[ "m.bilalali181999@gmail.com" ]
m.bilalali181999@gmail.com
986ab04cbd6767035603986636b24015b86c83d4
93e45c897af7b91169bdd3b3240b6c37f8cc7395
/days14/Extends04.java
9e57c5ecd9dbdaed1303bf281b417bfe0a5b68bf
[]
no_license
YataNox/Java_WebDeveloper_ClassB
e3d6b8115846cdc9e5593fff79aaa7e4fb0a896b
db03afe2af4e775aa9b45cc57f11c3918bcc1098
refs/heads/main
2023-07-24T16:30:27.908350
2021-08-18T07:50:33
2021-08-18T07:50:33
386,215,316
0
0
null
null
null
null
UTF-8
Java
false
false
3,203
java
package days14; // 일반 객체의 생성 과정 // 1. 멤버 필드 메모리 로딩 // 2. 생성자 호출 // 상속 관계에서의 객체 생성 과정 // 1. 멤버 필드의 메모리 로딩 - 부모/자식 클래스의 모든 멤버 필드가 메모리 로딩 // 2. 생성자 호출(먼저 자식 클래스의 생성자 호출) // 3. 자식 클래스 생성자의 첫 번째 실행 코드인 super()에 의해 부모클래스의 // 생성자 호출. super()라는 명령은 따로 쓰지 않아도 이미 존재하며 부모 클래스가 있다면 // 자동 호출되는 명령. // 4. 자식클래스의 생성자의 나머지 코드들 실행 // - 부모 클래스의 private멤버와 같은 경우 자식 클래스에서 초기화를 할 수 없기 // 때문에 부모 클래스의 생성자를 통해 초기화를 실행 class SuperB { int superNum; public SuperB() { System.out.println("부모 클래스의 생성자 실행"); } // 부모 클래스 생성자 } class SubB extends SuperB // SuperB 클래스 상속 { int subNum; // 생성자를 별도로 꺼내서 정의하지 않았다면.. // 보이지 않는 곳에 디폴트 생성자가 존재할 것이며, 그의 첫 번째 명령은 // super();가 되어있습니다. // SubB(){super();} // 생성자를 별로도 꺼내서 정의한 경우.. // 매개변수가 있는 생성자가 오버로딩 된 경우... this()로 형제 생성자를 호출한 경우 public SubB() { super(); // 자식 클래스에서 부모 클래스 생성자 호출은 super();라고 명령하며, // 반드시 첫 번째 실행코드로 씁니다. // 다만 부모 클래스의 생성자가 오버로딩 되거나 하지 않았다면 쓰지 않아도 // super();명령은 실행됩니다. // 부모클래스 생성자가 디폴트 생성자만 있을 경우 super(); 명령 생략 - 자동호출 System.out.println("자식 클래스의 생성자 호출"); } // 매개변수가 있는 생성자가 오버로딩 된 경우... this()로 형제 생성자를 호출한 경우 public SubB(int subNum) // 오버로딩된 자식 클래스 생성자 { // 자식 클래스의 오버로딩된 생성자의 첫 번째 실행코드는 super() 또는 // this()를 코딩하는데 그 둘을 같이 실행할 수는 없습니다. // 현재 클래스의 매개 변수가 없는 생성자를 this()로 호출하고 그 안에서 // super()가 실행되도록 합니다. this(); System.out.println("자식 클래스의 오버로딩된 생성자 실행(this()o)"); // 부모나 형제 생성자에 매개 변수가 있는 경우 반드시 // 호출하려는 super() 또는 this()의 매개 변수에 맞춰 전달인수를 전달합니다. } // 매개 변수가 있는 생성자가 오버로딩 된 경우 // this()로 형제 생성자를 호출 하지 않는 경우 public SubB(int subNum, int num) { super(); System.out.println("자식 클래스의 오버로딩된 생성자 실행(this()x)"); } } public class Extends04 { public static void main(String[] args) { SubB b = new SubB(); System.out.println(); SubB b1 = new SubB(10); System.out.println(); SubB b2 = new SubB(10, 20); } }
[ "noreply@github.com" ]
noreply@github.com
18ba8b0a5205b89229b25a33ef4d22aeb8a870a7
56e8c4a51a46f3cec421dbdc0e243d313f50c512
/org/boris/pecoff4j/SectionData.java
7e59b192061a5d85d5700e95324b4d28351b3d5b
[]
no_license
karanbabu2110/pecoff4j
3d76494346b5eff372469e39a8f79a5bcc969412
c40de82bf1516b9a8b993d2ae7540d361ede18be
refs/heads/master
2020-08-30T21:43:41.047576
2019-10-30T10:14:23
2019-10-30T10:14:23
218,496,953
0
0
null
null
null
null
UTF-8
Java
false
false
818
java
/******************************************************************************* * This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Peter Smith *******************************************************************************/ package org.boris.pecoff4j; public class SectionData { private byte[] data; private byte[] preamble; public byte[] getPreamble() { return preamble; } public void setPreamble(byte[] preamble) { this.preamble = preamble; } public byte[] getData() { return data; } public void setData(byte[] data) { this.data = data; } }
[ "noreply@github.com" ]
noreply@github.com
3c99a311e6be8a5fccda6eee7b0069c8e3b280db
32b6ca50e4d191a75f7c6b58377f248a0f8df963
/src/main/java/com/awsmu/service/DashboardServiceImpl.java
aab60b81478ecd9aedeba434577361c85e8caa2f
[]
no_license
rajnishsipl/awsmuAdmin
f65e542eb6451d5763bb07ea38266b59ff90bbe5
6bb7e8348cb30884cdaf263f81e23015bb18795d
refs/heads/master
2021-01-10T05:39:46.744723
2016-04-01T10:17:22
2016-04-01T10:17:22
55,222,392
0
0
null
null
null
null
UTF-8
Java
false
false
8,066
java
package com.awsmu.service; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.log4j.Logger; import org.ocpsoft.prettytime.PrettyTime; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.beans.factory.annotation.Qualifier; import com.awsmu.builder.ExpertRequestBuilder; import com.awsmu.builder.PlannerBuilder; import com.awsmu.builder.UserBuilder; import com.awsmu.builder.UserPlannerBuilder; import com.awsmu.config.Properties; import com.awsmu.dao.DashboardDao; import com.awsmu.model.AjaxResponse; import com.awsmu.model.ExpertRequestModel; import com.awsmu.model.PlannersModel; import com.awsmu.model.UserMessageAggregation; import com.awsmu.model.UserModel; import com.awsmu.model.UserPlannersModel; import com.awsmu.entity.ExpertRequest; import com.awsmu.entity.Planners; import com.awsmu.entity.User; import com.awsmu.entity.UserPlanners; import com.awsmu.exception.AwsmuException; import com.google.gson.Gson; /** * Dashboard service implementation */ @Service(value = "DashboardService") public class DashboardServiceImpl implements DashboardService { private static Logger logger = Logger.getLogger(DashboardServiceImpl.class); /** * Injecting DashboardDao */ @Autowired(required = true) @Qualifier(value = "DashboardDao") private DashboardDao dashboardDao; /** * get dashboard detail */ @Override public AjaxResponse getDashboardData(){ AjaxResponse ajaxResponse = new AjaxResponse(); try{ //date time format PrettyTime preetyObj = new PrettyTime(); // get total user count int totalUsersCount = dashboardDao.getAllUsersCount(); // get latest user List<User> usersList = dashboardDao.getLatestUsers(); UserBuilder userBuilder = new UserBuilder(); List<UserModel> userModelList = new ArrayList<UserModel>(); if( ! usersList.isEmpty()){ // iterating user to convert User Entity to UserModel and add into list for (User userRow : usersList) { userModelList.add(userBuilder.fromEntityToModel(userRow)); } } //get user messages List<UserMessageAggregation> unreadMessages = dashboardDao.getUnreadMessages(); List<UserMessageAggregation> messages = dashboardDao.getRecentMessages(); //create message list List<Object> messagesList = new ArrayList<Object>(); if (! messages.isEmpty()) { for (UserMessageAggregation messagesRow : messages) { Map<String, String> messageRow = new HashMap<String, String>(); if (messagesRow.getToUserId().equalsIgnoreCase(Properties.ADMIN_ID)) { String profilePic = messagesRow.getFromUserImage() == "" ? "profile_no_pic.png": messagesRow.getFromUserImage(); int intIndex = profilePic.indexOf("http"); if (intIndex == -1) { profilePic = Properties.AMAZON_PROFILE_PIC_URL+ profilePic; } messageRow.put("image", profilePic); messageRow.put("displayName", messagesRow.getFromUserDisplayName()); messageRow.put("isRead", String.valueOf(messagesRow.getIsRead())); messageRow.put("userName", messagesRow.getFromUserUserName()); messageRow.put("userRole", messagesRow.getFromUserRole()); } else { String profilePic = messagesRow.getToUserImage() == "" ? "profile_no_pic.png" : messagesRow.getToUserImage(); int intIndex = profilePic.indexOf("http"); if (intIndex == -1) { profilePic = Properties.AMAZON_PROFILE_PIC_URL+ profilePic; } messageRow.put("image", profilePic); messageRow.put("displayName", messagesRow.getToUserDisplayName()); messageRow.put("isRead", "1"); messageRow.put("userName", messagesRow.getToUserUserName()); } messageRow.put("message", messagesRow.getMessage()); messageRow.put("chainId", messagesRow.getChainId()); messageRow.put("dateTime", preetyObj.format(messagesRow.getCreatedDate()).toString()); messagesList.add(messageRow); } // get total planners count int totalPlannersCount = dashboardDao.getAllPlannersCount(); // get latest planners List<Planners> plannersList = dashboardDao.getLatestPlanners(); PlannerBuilder plannerBuilder = new PlannerBuilder(); List<PlannersModel> plannersModelList = new ArrayList<PlannersModel>(); if( ! plannersList.isEmpty()){ // iterating user to convert Planners Entity to PlannersModel and add into list for (Planners plannerRow : plannersList) { plannersModelList.add(plannerBuilder.fromEntityToModel(plannerRow)); } } // get total user's planners count int totalUserPlannersCount = dashboardDao.getAllUserPlannersCount(); // get latest user's planners List<UserPlanners> userPlannersList = dashboardDao.getLatestUserPlanners(); UserPlannerBuilder userPlannerBuilder = new UserPlannerBuilder(); List<UserPlannersModel> userPlannersModelList = new ArrayList<UserPlannersModel>(); if( ! userPlannersList.isEmpty()){ // iterating user to convert UserPlanners Entity to UserPlannersModel and add into list for (UserPlanners userPlannerRow : userPlannersList) { userPlannersModelList.add(userPlannerBuilder.fromEntityToModel(userPlannerRow)); } } // get total experts count int totalExpertRequestsCount = dashboardDao.getAllExpertRequestCount(); // get latest user's planners List<ExpertRequest> expertRequestsList = dashboardDao.getLatestExpertRequest(); ExpertRequestBuilder expertRequestBuilder = new ExpertRequestBuilder(); List<ExpertRequestModel> expertRequestsModelList = new ArrayList<ExpertRequestModel>(); if( ! userPlannersList.isEmpty()){ // iterating user to convert UserPlanners Entity to UserPlannersModel and add into list for (ExpertRequest userPlannerRow : expertRequestsList) { expertRequestsModelList.add(expertRequestBuilder.fromEntityToModel(userPlannerRow)); } } //set ajax response String jsonTotalUsersCount = new Gson().toJson(totalUsersCount); String jsonLatestUserList = new Gson().toJson(userModelList); String jsonUnreadMessagesCount = new Gson().toJson(unreadMessages.size()); String jsonMessagesList = new Gson().toJson(messagesList); String jsonTotalPlannersCount = new Gson().toJson(totalPlannersCount); String jsonPlannersList = new Gson().toJson(plannersModelList); String jsonTotalUserPlannersCount = new Gson().toJson(totalUserPlannersCount); String jsonUserPlannersList = new Gson().toJson(userPlannersModelList); String jsonTotalExpertRequestsCount = new Gson().toJson(totalExpertRequestsCount); String jsonExpertRequestsList = new Gson().toJson(expertRequestsModelList); String jsonContent = "{\"totalUsersCount\":"+jsonTotalUsersCount+", " + "\"latestUserList\":"+jsonLatestUserList+", " + "\"unreadMessagesCount\":"+jsonUnreadMessagesCount+", " + "\"messagesList\":"+jsonMessagesList+", " + "\"totalPlannersCount\":"+jsonTotalPlannersCount+", " + "\"plannersList\":"+jsonPlannersList+", " + "\"totalUserPlannersCount\":"+jsonTotalUserPlannersCount+", " + "\"userPlannersList\":"+jsonUserPlannersList+", " + "\"totalExpertRequestsCount\":"+jsonTotalExpertRequestsCount+", " + "\"expertRequestsList\":"+jsonExpertRequestsList+"}"; ajaxResponse.setStatus(true); ajaxResponse.setContent(jsonContent); } } catch(AwsmuException e){ logger.debug(Properties.EXCEPTION_DAO_ERROR +":"+ e.getStackTrace().toString()); ajaxResponse.setMessage(e.getDisplayMsg()); ajaxResponse.setCode(e.getCode()); } catch(Exception e){ logger.debug(Properties.EXCEPTION_SERVICE_ERROR+":"+e); ajaxResponse.setMessage(e.getMessage()); ajaxResponse.setCode(Properties.INTERNAL_SERVER_ERROR); } return ajaxResponse; } }
[ "rajnish.katiyar@systematixindia.com" ]
rajnish.katiyar@systematixindia.com
9250e1786b4637c991fc392d6008d8e3a7fcd5aa
770f60260e50bc9b4b8449b02f5967ec6bf38540
/src/test/java/io/netty/buffer/api/BufferLongOffsettedAccessorsTest.java
702795e24b31c96229d90bedb2e4aeca8eadfe85
[]
no_license
NiteshKant/netty-incubator-buffer-api
778c15693e85f09c1ab6097e6177e1af505f33b1
fc7ba4522f791d065027a1df9a4bb061a736ef42
refs/heads/main
2023-04-24T18:20:18.799321
2021-05-11T11:13:29
2021-05-11T11:13:29
359,622,085
0
0
null
2021-04-19T23:07:41
2021-04-19T23:07:40
null
UTF-8
Java
false
false
7,044
java
/* * Copyright 2021 The Netty Project * * The Netty Project 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: * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package io.netty.buffer.api; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import static java.nio.ByteOrder.BIG_ENDIAN; import static org.junit.jupiter.api.Assertions.assertThrows; public class BufferLongOffsettedAccessorsTest extends BufferTestSupport { @ParameterizedTest @MethodSource("allocators") void offsettedGetOfLongMustBoundsCheckOnNegativeOffset(Fixture fixture) { try (BufferAllocator allocator = fixture.createAllocator(); Buffer buf = allocator.allocate(8)) { assertThrows(IndexOutOfBoundsException.class, () -> buf.getLong(-1)); } } @ParameterizedTest @MethodSource("allocators") void offsettedGetOfLongReadOnlyMustBoundsCheckOnNegativeOffset(Fixture fixture) { try (BufferAllocator allocator = fixture.createAllocator(); Buffer buf = allocator.allocate(8)) { assertThrows(IndexOutOfBoundsException.class, () -> buf.makeReadOnly().getLong(-1)); } } @ParameterizedTest @MethodSource("allocators") void offsettedGetOfLongMustNotBoundsCheckWhenReadOffsetAndSizeIsEqualToWriteOffset(Fixture fixture) { try (BufferAllocator allocator = fixture.createAllocator(); Buffer buf = allocator.allocate(8)) { long value = 0x0102030405060708L; buf.writeLong(value); assertEquals(value, buf.getLong(0)); } } @ParameterizedTest @MethodSource("allocators") void offsettedGetOfLongMustReadWithDefaultEndianByteOrder(Fixture fixture) { try (BufferAllocator allocator = fixture.createAllocator(); Buffer buf = allocator.allocate(8)) { buf.order(BIG_ENDIAN); long value = 0x0102030405060708L; buf.writeLong(value); buf.setByte(0, (byte) 0x10); assertEquals(0x1002030405060708L, buf.getLong(0)); } } @ParameterizedTest @MethodSource("allocators") void offsettedGetOfLongMustBoundsCheckWhenReadOffsetAndSizeIsGreaterThanWriteOffset(Fixture fixture) { try (BufferAllocator allocator = fixture.createAllocator(); Buffer buf = allocator.allocate(8)) { long value = 0x0102030405060708L; buf.writeLong(value); assertThrows(IndexOutOfBoundsException.class, () -> buf.getLong(1)); } } @ParameterizedTest @MethodSource("allocators") void offsettedGetOfLongReadOnlyMustBoundsCheckWhenReadOffsetAndSizeIsGreaterThanWriteOffset(Fixture fixture) { try (BufferAllocator allocator = fixture.createAllocator(); Buffer buf = allocator.allocate(8)) { long value = 0x0102030405060708L; buf.writeLong(value); assertThrows(IndexOutOfBoundsException.class, () -> buf.makeReadOnly().getLong(1)); } } @ParameterizedTest @MethodSource("allocators") void offsettedGetOfLongMustNotBoundsCheckWhenReadOffsetIsGreaterThanWriteOffset(Fixture fixture) { try (BufferAllocator allocator = fixture.createAllocator(); Buffer buf = allocator.allocate(8)) { buf.getLong(0); } } @ParameterizedTest @MethodSource("allocators") void offsettedGetOfLongMustBoundsCheckWhenReadOffsetIsGreaterThanCapacity(Fixture fixture) { try (BufferAllocator allocator = fixture.createAllocator(); Buffer buf = allocator.allocate(8)) { assertThrows(IndexOutOfBoundsException.class, () -> buf.getLong(8)); } } @ParameterizedTest @MethodSource("allocators") void offsettedGetOfLongReadOnlyMustNotBoundsCheckWhenReadOffsetIsGreaterThanWriteOffset(Fixture fixture) { try (BufferAllocator allocator = fixture.createAllocator(); Buffer buf = allocator.allocate(8)) { buf.makeReadOnly().getLong(0); } } @ParameterizedTest @MethodSource("allocators") void offsettedGetOfLongReadOnlyMustBoundsCheckWhenReadOffsetIsGreaterThanCapacity(Fixture fixture) { try (BufferAllocator allocator = fixture.createAllocator(); Buffer buf = allocator.allocate(8)) { assertThrows(IndexOutOfBoundsException.class, () -> buf.makeReadOnly().getLong(8)); } } @ParameterizedTest @MethodSource("allocators") void offsettedSetOfLongMustBoundsCheckWhenWriteOffsetIsNegative(Fixture fixture) { try (BufferAllocator allocator = fixture.createAllocator(); Buffer buf = allocator.allocate(8)) { assertEquals(Long.BYTES, buf.capacity()); long value = 0x0102030405060708L; assertThrows(IndexOutOfBoundsException.class, () -> buf.setLong(-1, value)); buf.writerOffset(Long.BYTES); // Verify contents are unchanged. assertEquals(0, buf.readLong()); } } @ParameterizedTest @MethodSource("allocators") void offsettedSetOfLongMustBoundsCheckWhenWriteOffsetAndSizeIsBeyondCapacity(Fixture fixture) { try (BufferAllocator allocator = fixture.createAllocator(); Buffer buf = allocator.allocate(8)) { assertEquals(Long.BYTES, buf.capacity()); long value = 0x0102030405060708L; assertThrows(IndexOutOfBoundsException.class, () -> buf.setLong(1, value)); buf.writerOffset(Long.BYTES); // Verify contents are unchanged. assertEquals(0, buf.readLong()); } } @ParameterizedTest @MethodSource("allocators") void offsettedSetOfLongMustHaveDefaultEndianByteOrder(Fixture fixture) { try (BufferAllocator allocator = fixture.createAllocator(); Buffer buf = allocator.allocate(8)) { buf.order(BIG_ENDIAN); long value = 0x0102030405060708L; buf.setLong(0, value); buf.writerOffset(Long.BYTES); assertEquals((byte) 0x01, buf.readByte()); assertEquals((byte) 0x02, buf.readByte()); assertEquals((byte) 0x03, buf.readByte()); assertEquals((byte) 0x04, buf.readByte()); assertEquals((byte) 0x05, buf.readByte()); assertEquals((byte) 0x06, buf.readByte()); assertEquals((byte) 0x07, buf.readByte()); assertEquals((byte) 0x08, buf.readByte()); } } }
[ "christianvest_hansen@apple.com" ]
christianvest_hansen@apple.com
f0ff450bb8dc1ad575ebf7c532e0d7fd20f4cf33
2a86eaaf0b58555d2eb06c4e1e94f5112d29681b
/src/main/java/com/dev/cinema/controllers/MovieController.java
519f513236ce5fd4e2a52cc4fe2fec416301c6a6
[]
no_license
graveman13/cinema-hibernate
35e857979e25b1c06d020d25942aeee10bcf67e7
879807a205c38040894b654a5412f4c4ec6b8931
refs/heads/master
2022-12-25T15:14:14.163150
2020-02-24T11:16:12
2020-02-24T11:16:12
238,207,443
0
0
null
2022-12-15T23:36:16
2020-02-04T13:02:20
Java
UTF-8
Java
false
false
1,764
java
package com.dev.cinema.controllers; import com.dev.cinema.dto.MovieRequestDto; import com.dev.cinema.dto.MovieResponseDto; import com.dev.cinema.model.Movie; import com.dev.cinema.service.MovieService; import java.util.List; import java.util.stream.Collectors; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/movies") public class MovieController { @Autowired private MovieService movieService; @PostMapping public MovieResponseDto add(@RequestBody MovieRequestDto movieRequestDto) { return convertMovieToMovieDtoResponse( movieService.add(convertMovieRequestDtoToMovie(movieRequestDto))); } @GetMapping public List<MovieResponseDto> getAll() { return movieService.getAll().stream() .map(this::convertMovieToMovieDtoResponse).collect(Collectors.toList()); } private MovieResponseDto convertMovieToMovieDtoResponse(Movie movie) { MovieResponseDto movieResponseDto = new MovieResponseDto(); movieResponseDto.setTitle(movie.getTitle()); movieResponseDto.setDescription(movie.getDescription()); return movieResponseDto; } private Movie convertMovieRequestDtoToMovie(MovieRequestDto movieRequestDto) { Movie movie = new Movie(); movie.setTitle(movieRequestDto.getTitle()); movie.setDescription(movieRequestDto.getDescription()); return movie; } }
[ "graveman13@gmail.com" ]
graveman13@gmail.com
eb071987fb12284b99f637d3123ed80714d46f41
7adad41359305f48e8bf4aa075416f0c3bb25e0d
/ord/src/main/java/com/tuniu/ord/vo/StockOccupyInfoOutput.java
ab760c1085316028127e061c615cc2f1156ab357
[]
no_license
tanbinh123/order-system
19663e5a47df48d991b3fcb2f4d1ee21f224dae9
952d794d924065e48d8dd0e908df28fc71d0ec30
refs/heads/master
2023-03-16T09:53:03.931159
2019-12-11T02:40:25
2019-12-11T02:40:25
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,366
java
/******************************************************************************* * * COPYRIGHT (C) 2016 Tuniu Limited - ALL RIGHTS RESERVED. * * Creation Date: 2016年10月12日 * *******************************************************************************/ package com.tuniu.ord.vo; /** * @author zhairongping * */ public class StockOccupyInfoOutput { /** * 占位单号 */ private Integer id; /** * 占位总数 */ private Integer inNumber; /** * 占位余位 */ private Integer leftNumber; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getInNumber() { return inNumber; } public void setInNumber(Integer inNumber) { this.inNumber = inNumber; } public Integer getLeftNumber() { return leftNumber; } public void setLeftNumber(Integer leftNumber) { this.leftNumber = leftNumber; } }
[ "zhairp@zhairpdeMacBook-Pro.local" ]
zhairp@zhairpdeMacBook-Pro.local
679a61e93638c4563b3cabdd65d92b808542f464
8ced17b9694537fa50fe510a878704413b17472c
/honeystore/src/main/java/com/honeystore/domain/ProductToCartItem.java
29ab9f820b662716a0bdc439a3f45d80321a5af1
[]
no_license
DanielAbrashev/HoneyStore
e6dfc7e5f2adfd7b11b257c5515c4e94c96d6e44
86012c54782b004ee633f75ab09cd1dc2adbbc7d
refs/heads/master
2023-09-05T15:55:15.243973
2021-11-09T15:34:39
2021-11-09T15:34:39
258,817,321
0
0
null
null
null
null
UTF-8
Java
false
false
776
java
package com.honeystore.domain; import javax.persistence.*; @Entity public class ProductToCartItem { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @ManyToOne @JoinColumn(name = "product_id") private Product product; @ManyToOne @JoinColumn(name = "cart_item_id") private CartItem cartItem; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Product getProduct() { return product; } public void setProduct(Product product) { this.product = product; } public CartItem getCartItem() { return cartItem; } public void setCartItem(CartItem cartItem) { this.cartItem = cartItem; } }
[ "danielabrashev93@gmail.com" ]
danielabrashev93@gmail.com
808ff541377524b987e5bbcac6952592994314f4
d475561939aeb5240f16cb105d0076071c81ac33
/app/src/main/java/com/zerofeetaway/ui/DividerItemDecoration.java
1294838f15bd73fb28a953f366056703dd256c6d
[]
no_license
cfor-grindr/zerofeetaway
57670ec4a8c22573659b1d8437fd9b76f05b4440
2382b18d64c9c3c28cb2a87c2d1d7b22844177cd
refs/heads/master
2021-01-01T05:21:31.567352
2016-05-10T01:06:08
2016-05-10T01:06:08
58,270,741
0
0
null
null
null
null
UTF-8
Java
false
false
3,304
java
package com.zerofeetaway.ui; import android.content.Context; import android.content.res.TypedArray; import android.util.AttributeSet; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.LinearLayoutManager; import android.view.View; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.graphics.Canvas; public class DividerItemDecoration extends RecyclerView.ItemDecoration { private Drawable mDivider; public DividerItemDecoration(Context context, AttributeSet attrs) { final TypedArray a = context.obtainStyledAttributes(attrs, new int [] { android.R.attr.listDivider }); mDivider = a.getDrawable(0); a.recycle(); } public DividerItemDecoration(Drawable divider) { mDivider = divider; } @Override public void getItemOffsets (Rect outRect, View view, RecyclerView parent, RecyclerView.State state) { super.getItemOffsets(outRect, view, parent, state); if (mDivider == null) return; if (parent.getChildPosition(view) < 1) return; if (getOrientation(parent) == LinearLayoutManager.VERTICAL) outRect.top = mDivider.getIntrinsicHeight(); else outRect.left = mDivider.getIntrinsicWidth(); } @Override public void onDrawOver(Canvas c, RecyclerView parent) { if (mDivider == null) { super.onDrawOver(c, parent); return; } if (getOrientation(parent) == LinearLayoutManager.VERTICAL) { final int left = parent.getPaddingLeft(); final int right = parent.getWidth() - parent.getPaddingRight(); final int childCount = parent.getChildCount(); for (int i=1; i < childCount; i++) { final View child = parent.getChildAt(i); final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams(); final int size = mDivider.getIntrinsicHeight(); final int top = child.getTop() - params.topMargin; final int bottom = top + size; mDivider.setBounds(left, top, right, bottom); mDivider.draw(c); } } else { //horizontal final int top = parent.getPaddingTop(); final int bottom = parent.getHeight() - parent.getPaddingBottom(); final int childCount = parent.getChildCount(); for (int i=1; i < childCount; i++) { final View child = parent.getChildAt(i); final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams(); final int size = mDivider.getIntrinsicWidth(); final int left = child.getLeft() - params.leftMargin; final int right = left + size; mDivider.setBounds(left, top, right, bottom); mDivider.draw(c); } } } private int getOrientation(RecyclerView parent) { if (parent.getLayoutManager() instanceof LinearLayoutManager) { LinearLayoutManager layoutManager = (LinearLayoutManager) parent.getLayoutManager(); return layoutManager.getOrientation(); } else throw new IllegalStateException("DividerItemDecoration can only be used with a LinearLayoutManager."); } }
[ "curlyfriesonionrings@gmail.com" ]
curlyfriesonionrings@gmail.com
9af8174363b3dc84da036e6b6cc1f8e3df13f6bb
2bd5499e7a707aa0d4f2e43ba8402c85efa1ad2c
/src/test/java/ua/test/taf/stepDefs/MainPageDefinitionSteps.java
a8161ed2582835374139b354118a082a7033c055
[]
no_license
vpriyma/test.taf
5c68191782457b90290fddadecd7916744366cd1
2d0c3acd148dd498f0ce49bf4c79cdc8bf099318
refs/heads/master
2020-12-21T16:20:14.643622
2020-01-27T12:52:51
2020-01-27T12:52:51
236,488,160
0
1
null
2020-10-13T19:05:47
2020-01-27T12:42:22
Java
UTF-8
Java
false
false
871
java
package ua.test.taf.stepDefs; import org.aeonbits.owner.ConfigFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import io.cucumber.java.bs.Ali; import io.cucumber.java.en.Given; import io.cucumber.java.en.When; import lombok.extern.slf4j.Slf4j; import ua.test.taf.core.config.MainConfig; import ua.test.taf.pageObject.GooglePage; import static com.codeborne.selenide.Selenide.open; import static com.codeborne.selenide.Selenide.page; @Slf4j public class MainPageDefinitionSteps { protected static MainConfig config = ConfigFactory.create(MainConfig.class); @Given("User opens Google page") public void user_opens_Google_page() { open(config.base_url(), GooglePage.class); } @When("User searches per {string}") public void user_searches_per(String string) { page(GooglePage.class).searchPer(string); } }
[ "vitalii_priyma@epam.com" ]
vitalii_priyma@epam.com
2cd2245aa195624e3e608b5196d77697eb5e9ed3
fdd421f9a9f9b9d8760516a05f96b524d007650f
/server/src/main/java/WAT/I8E2S4/TaskManager/Services/EmailService.java
3f5bf6d558c7c183cb271305c460c547652bf1ae
[]
no_license
jdabrowski11926/taskManager
36d284e8cd75a9fd0e5282c81bfe99225ab91546
a881d48c11d7a48987690c22efd98bf64db81566
refs/heads/master
2022-10-29T17:11:05.121161
2020-06-17T19:54:57
2020-06-17T19:54:57
269,048,008
0
0
null
null
null
null
UTF-8
Java
false
false
2,766
java
package WAT.I8E2S4.TaskManager.Services; import WAT.I8E2S4.TaskManager.Model.Category; import WAT.I8E2S4.TaskManager.Model.Task; import WAT.I8E2S4.TaskManager.Model.User; import WAT.I8E2S4.TaskManager.Repositories.CategoryRepository; import WAT.I8E2S4.TaskManager.Repositories.TaskRepository; import WAT.I8E2S4.TaskManager.Repositories.UserRepository; import lombok.AllArgsConstructor; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSenderImpl; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.List; import static WAT.I8E2S4.TaskManager.Security.SecurityConstants.*; @Service @AllArgsConstructor public class EmailService { private JavaMailSenderImpl javaMailSender; private UserRepository userRepository; private CategoryRepository categoryRepository; private TaskRepository taskRepository; @Scheduled(fixedRate = 60000) public void searchForActiveTasks() { javaMailSender.setHost(MAIL_HOST); javaMailSender.setPort(MAIL_PORT); javaMailSender.setUsername(MAIL_USERNAME); javaMailSender.setPassword(MAIL_PASSWORD); String currentTime = new SimpleDateFormat("yyyy-MM-dd HH:mm").format(Calendar.getInstance().getTime()); currentTime = currentTime.replaceAll(" ","T"); System.out.println("OBECNY CZAS : "+currentTime); List<User> users = userRepository.findAll(); for(int i=0; i<users.size(); i++){ List<Category> categories = categoryRepository.findAllByUserUsername(users.get(i).getUsername()); for(int j=0; j<categories.size();j++){ List<Task> tasks = taskRepository.findAllByCategory_NameAndCategory_User_username(categories.get(j).getName(),users.get(i).getUsername()); for(int k=0; k<tasks.size(); k++){ if(tasks.get(k).getStartDateTime().toString().equals(currentTime) && tasks.get(k).isActive() && tasks.get(k).isNotification()){ sendEmail(users.get(i), tasks.get(k)); } } } } } public void sendEmail(User user, Task task) { SimpleMailMessage mailMessage = new SimpleMailMessage(); mailMessage.setFrom("taskControllerTIM@gmail.com"); mailMessage.setTo(user.getUsername()); mailMessage.setSubject("Przypomnienie o zadaniu"); mailMessage.setText("Na "+ task.getStartDateTime()+" - " + task.getEndDateTime() + " zostało zaplanowane zadanie: "+ task.getName() + "(opis : "+task.getDescription()+")"); javaMailSender.send(mailMessage); } }
[ "fyb11926@gmail.com" ]
fyb11926@gmail.com
609b7fc3ad18d60f0b44817c09efa02e33e16aaf
399d419f7772561973b8b2bc5135e9d6704c9ede
/core/src/de/swagner/paxbritannica/frigate/MissileAI.java
5c50e99d0eb3586474b69383d50671ae6ff60ca5
[ "MIT" ]
permissive
libgdx/libgdx-demo-pax-britannica
1de86c946da4fbf76ec7b5c2da1f0b34a8b6097a
2e5e958eb10b4cc9b4fef9639fe48df8b521fe39
refs/heads/master
2023-06-03T01:42:45.522206
2021-07-30T20:43:03
2021-07-30T20:43:03
18,311,697
109
78
MIT
2021-07-30T20:43:09
2014-03-31T23:40:42
Java
UTF-8
Java
false
false
1,785
java
package de.swagner.paxbritannica.frigate; import com.badlogic.gdx.math.Vector2; import de.swagner.paxbritannica.GameInstance; import de.swagner.paxbritannica.Ship; import de.swagner.paxbritannica.Targeting; public class MissileAI { private float MAX_LIFETIME = 5; // 5 seconds to auto-destruct private Ship target; private Missile missile; Vector2 relativeVel = new Vector2(); Vector2 toTarget = new Vector2(); public MissileAI(Missile missile) { this.missile = missile; retarget(); } public void retarget() { target = Targeting.getTypeInRange(missile, 0, 500); if (target == null) { target = Targeting.getTypeInRange(missile, 1, 500); } else return; if (target == null) { target = Targeting.getTypeInRange(missile, 2, 500); } else return; if (target == null) { target = Targeting.getNearestOfType(missile, 1); } else return; if (target == null) { target = Targeting.getNearestOfType(missile, 3); } else target = null; } public void selfDestruct() { // EXPLODE! missile.alive = false; GameInstance.getInstance().explosionParticles.addTinyExplosion(missile.collisionCenter); } public Vector2 predict() { relativeVel.set(missile.velocity).sub(target.velocity); toTarget.set(target.collisionCenter).sub(missile.collisionCenter); if (missile.velocity.dot(toTarget) != 0) { float time_to_target = toTarget.dot(toTarget) / relativeVel.dot(toTarget); return new Vector2(target.collisionCenter).sub(relativeVel.scl(Math.max(0, time_to_target))); } else { return target.collisionCenter; } } public void update() { if (target == null || missile.aliveTime > MAX_LIFETIME) { selfDestruct(); } else if (!target.alive) { retarget(); } else { missile.goTowards(predict(), true); } } }
[ "tomaszwojciechowski@hotmail.co.uk" ]
tomaszwojciechowski@hotmail.co.uk
de32d16ca4a36bea9e9e2b8eae5adb5d5ca80029
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/20/20_736baa60f1ed2527ed03e5046c369bc1f5522ff8/PImage/20_736baa60f1ed2527ed03e5046c369bc1f5522ff8_PImage_t.java
4bf9d42efb8a813f9e2b22dba1d812587525aaef
[]
no_license
zhongxingyu/Seer
48e7e5197624d7afa94d23f849f8ea2075bcaec0
c11a3109fdfca9be337e509ecb2c085b60076213
refs/heads/master
2023-07-06T12:48:55.516692
2023-06-22T07:55:56
2023-06-22T07:55:56
259,613,157
6
2
null
2023-06-22T07:55:57
2020-04-28T11:07:49
null
UTF-8
Java
false
false
62,434
java
/* -*- mode: jde; c-basic-offset: 2; indent-tabs-mode: nil -*- */ /* Part of the Processing project - http://processing.org Copyright (c) 2004-06 Ben Fry and Casey Reas Copyright (c) 2001-04 Massachusetts Institute of Technology This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package processing.core; import java.awt.image.*; import java.io.*; import java.lang.reflect.*; /** * Storage class for pixel data. This is the base class for most image and * pixel information, such as PGraphics and the video library classes. * <P> * Code for copying, resizing, scaling, and blending contributed * by <A HREF="http://www.toxi.co.uk">toxi</A> * <P> */ public class PImage implements PConstants, Cloneable { /** * Format for this image, one of RGB, ARGB or ALPHA. * note that RGB images still require 0xff in the high byte * because of how they'll be manipulated by other functions */ public int format; public int pixels[]; public int width, height; // would scan line be useful? maybe for pow of 2 gl textures /** * Path to parent object that will be used with save(). * This prevents users from needing savePath() to use PImage.save(). */ public PApplet parent; // note! inherited by PGraphics public int imageMode = CORNER; public boolean smooth = false; /** native storage for java 1.3 image object */ //public Object image; /** for subclasses that need to store info about the image */ public Object cache; /** modified portion of the image */ public boolean modified; public int mx1, my1, mx2, my2; // private fields private int fracU, ifU, fracV, ifV, u1, u2, v1, v2, sX, sY, iw, iw1, ih1; private int ul, ll, ur, lr, cUL, cLL, cUR, cLR; private int srcXOffset, srcYOffset; private int r, g, b, a; private int[] srcBuffer; // fixed point precision is limited to 15 bits!! static final int PRECISIONB = 15; static final int PRECISIONF = 1 << PRECISIONB; static final int PREC_MAXVAL = PRECISIONF-1; static final int PREC_ALPHA_SHIFT = 24-PRECISIONB; static final int PREC_RED_SHIFT = 16-PRECISIONB; // internal kernel stuff for the gaussian blur filter int blurRadius; int blurKernelSize; int[] blurKernel; int[][] blurMult; ////////////////////////////////////////////////////////////// /** * Create an empty image object, set its format to RGB. * The pixel array is not allocated. */ public PImage() { //format = RGB; // makes sure that this guy is useful format = ARGB; // default to ARGB images for release 0116 cache = null; } /** * Create a new RGB (alpha ignored) image of a specific size. * All pixels are set to zero, meaning black, but since the * alpha is zero, it will be transparent. */ public PImage(int width, int height) { init(width, height, RGB); //init(width, height, RGB); //this(new int[width * height], width, height, ARGB); // toxi: is it maybe better to init the image with max alpha enabled? //for(int i=0; i<pixels.length; i++) pixels[i]=0xffffffff; // fry: i'm opting for the full transparent image, which is how // photoshop works, and our audience oughta be familiar with. // also, i want to avoid having to set all those pixels since // in java it's super slow, and most using this fxn will be // setting all the pixels anyway. // toxi: agreed and same reasons why i left it out ;) } public PImage(int width, int height, int format) { init(width, height, format); } /** * Function to be used by subclasses to setup their own bidness. * Used by Capture and Movie classes (and perhaps others), * because the width/height will not be known when super() is called. */ public void init(int width, int height, int format) { // ignore this.width = width; this.height = height; this.pixels = new int[width*height]; this.format = format; this.cache = null; } /** * Check the alpha on an image, using a really primitive loop. */ protected void checkAlpha() { if (pixels == null) return; for (int i = 0; i < pixels.length; i++) { // since transparency is often at corners, hopefully this // will find a non-transparent pixel quickly and exit if ((pixels[i] & 0xff000000) != 0xff000000) { format = ARGB; break; } } } /** * Construct a new PImage from a java.awt.Image. This constructor assumes * that you've done the work of making sure a MediaTracker has been used * to fully download the data and that the img is valid. */ public PImage(java.awt.Image img) { width = img.getWidth(null); height = img.getHeight(null); pixels = new int[width*height]; PixelGrabber pg = new PixelGrabber(img, 0, 0, width, height, pixels, 0, width); try { pg.grabPixels(); } catch (InterruptedException e) { } format = RGB; cache = null; } ////////////////////////////////////////////////////////////// /** * The mode can only be set to CORNERS or CORNER, because the others are * just too weird for the other functions. Do you really want to use * get() or copy() with imageMode(CENTER)? */ public void imageMode(int mode) { if ((mode == CORNER) || (mode == CORNERS)) { imageMode = mode; } else { String msg = "imageMode() only works with CORNER or CORNERS"; throw new RuntimeException(msg); } } /** * If true in PImage, use bilinear interpolation for copy() * operations. When inherited by PGraphics, also controls shapes. */ public void smooth() { smooth = true; } /** * Disable smoothing. See smooth(). */ public void noSmooth() { smooth = false; } ////////////////////////////////////////////////////////////// // MARKING IMAGE AS MODIFIED / FOR USE w/ GET/SET /** * Call this when you want to mess with the pixels[] array. * <p/> * For subclasses where the pixels[] buffer isn't set by default, * this should copy all data into the pixels[] array */ public void loadPixels() { // ignore } /** * Call this when finished messing with the pixels[] array. * <p/> * Mark all pixels as needing update. */ public void updatePixels() { updatePixels(0, 0, width, height); } /** * Mark the pixels in this region as needing an update. * <P> * This is not currently used by any of the renderers, however the api * is structured this way in the hope of being able to use this to * speed things up in the future. * <P> * Note that when using imageMode(CORNERS), * the x2 and y2 positions are non-inclusive. */ public void updatePixels(int x1, int y1, int x2, int y2) { if (imageMode == CORNER) { // x2, y2 are w/h x2 += x1; y2 += y1; } if (!modified) { mx1 = x1; mx2 = x2; my1 = y1; my2 = y2; modified = true; } else { if (x1 < mx1) mx1 = x1; if (x1 > mx2) mx2 = x1; if (y1 < my1) my1 = y1; if (y1 > my2) my2 = y1; if (x2 < mx1) mx1 = x2; if (x2 > mx2) mx2 = x2; if (y2 < my1) my1 = y2; if (y2 > my2) my2 = y2; } } ////////////////////////////////////////////////////////////// // GET/SET PIXELS /** * Returns an ARGB "color" type (a packed 32 bit int with the color. * If the coordinate is outside the image, zero is returned * (black, but completely transparent). * <P> * If the image is in RGB format (i.e. on a PVideo object), * the value will get its high bits set, just to avoid cases where * they haven't been set already. * <P> * If the image is in ALPHA format, this returns a white with its * alpha value set. * <P> * This function is included primarily for beginners. It is quite * slow because it has to check to see if the x, y that was provided * is inside the bounds, and then has to check to see what image * type it is. If you want things to be more efficient, access the * pixels[] array directly. */ public int get(int x, int y) { if ((x < 0) || (y < 0) || (x >= width) || (y >= height)) return 0; switch (format) { case RGB: return pixels[y*width + x] | 0xff000000; case ARGB: return pixels[y*width + x]; case ALPHA: return (pixels[y*width + x] << 24) | 0xffffff; } return 0; } /** * Grab a subsection of a PImage, and copy it into a fresh PImage. * This honors imageMode() for the coordinates. */ public PImage get(int x, int y, int w, int h) { if (imageMode == CORNERS) { // if CORNER, do nothing //x2 += x1; y2 += y1; // w/h are x2/y2 in this case, bring em down to size w = (w - x); h = (h - x); } if (x < 0) { w += x; // clip off the left edge x = 0; } if (y < 0) { h += y; // clip off some of the height y = 0; } if (x + w > width) w = width - x; if (y + h > height) h = height - y; PImage newbie = new PImage(w, h, format); int index = y*width + x; int index2 = 0; for (int row = y; row < y+h; row++) { System.arraycopy(pixels, index, newbie.pixels, index2, w); index+=width; index2+=w; } return newbie; } /** * Returns a copy of this PImage. Equivalent to get(0, 0, width, height). */ public PImage get() { try { return (PImage) clone(); } catch (CloneNotSupportedException e) { return null; } } /** * Silently ignores if the coordinate is outside the image. */ public void set(int x, int y, int c) { if ((x < 0) || (y < 0) || (x >= width) || (y >= height)) return; pixels[y*width + x] = c; } public void set(int dx, int dy, PImage src) { int sx = 0; int sy = 0; int sw = src.width; int sh = src.height; if (dx < 0) { // off left edge sx -= dx; sw += dx; dx = 0; } if (dy < 0) { // off top edge sy -= dy; sh += dy; dy = 0; } if (dx + sw > width) { // off right edge sw = width - dx; } if (dy + sh > height) { // off bottom edge sh = height - dy; } // this could be nonexistant if ((sw <= 0) || (sh <= 0)) return; setImpl(dx, dy, sx, sy, sw, sh, src); } /** * Internal function to actually handle setting a block of pixels that * has already been properly cropped from the image to a valid region. */ protected void setImpl(int dx, int dy, int sx, int sy, int sw, int sh, PImage src) { int srcOffset = sy * src.width + sx; int dstOffset = dy * width + dx; for (int y = sy; y < sy + sh; y++) { System.arraycopy(src.pixels, srcOffset, pixels, dstOffset, sw); srcOffset += src.width; dstOffset += width; } } ////////////////////////////////////////////////////////////// // ALPHA CHANNEL /** * Set alpha channel for an image. Black colors in the source * image will make the destination image completely transparent, * and white will make things fully opaque. Gray values will * be in-between steps. * <P> * Strictly speaking the "blue" value from the source image is * used as the alpha color. For a fully grayscale image, this * is correct, but for a color image it's not 100% accurate. * For a more accurate conversion, first use filter(GRAY) * which will make the image into a "correct" grayscake by * performing a proper luminance-based conversion. */ public void mask(int alpha[]) { // don't execute if mask image is different size if (alpha.length != pixels.length) { throw new RuntimeException("The PImage used with mask() must be " + "the same size as the applet."); } for (int i = 0; i < pixels.length; i++) { pixels[i] = ((alpha[i] & 0xff) << 24) | (pixels[i] & 0xffffff); } format = ARGB; } /** * Set alpha channel for an image using another image as the source. */ public void mask(PImage alpha) { mask(alpha.pixels); } /** * Method to apply a variety of basic filters to this image. * <P> * <UL> * <LI>filter(BLUR) provides a basic blur. * <LI>filter(GRAY) converts the image to grayscale based on luminance. * <LI>filter(INVERT) will invert the color components in the image. * <LI>filter(OPAQUE) set all the high bits in the image to opaque * <LI>filter(THRESHOLD) converts the image to black and white. * <LI>filter(DILATE) grow white/light areas * <LI>filter(ERODE) shrink white/light areas * </UL> * Luminance conversion code contributed by * <A HREF="http://www.toxi.co.uk">toxi</A> * <P/> * Gaussian blur code contributed by * <A HREF="http://incubator.quasimondo.com">Mario Klingemann</A> */ public void filter(int kind) { loadPixels(); switch (kind) { case BLUR: // TODO write basic low-pass filter blur here // what does photoshop do on the edges with this guy? // better yet.. why bother? just use gaussian with radius 1 filter(BLUR, 1); break; case GRAY: // Converts RGB image data into grayscale using // weighted RGB components, and keeps alpha channel intact. // [toxi 040115] for (int i = 0; i < pixels.length; i++) { int col = pixels[i]; // luminance = 0.3*red + 0.59*green + 0.11*blue // 0.30 * 256 = 77 // 0.59 * 256 = 151 // 0.11 * 256 = 28 int lum = (77*(col>>16&0xff) + 151*(col>>8&0xff) + 28*(col&0xff))>>8; pixels[i] = (col & ALPHA_MASK) | lum<<16 | lum<<8 | lum; } break; case INVERT: for (int i = 0; i < pixels.length; i++) { //pixels[i] = 0xff000000 | pixels[i] ^= 0xffffff; } break; case POSTERIZE: throw new RuntimeException("Use filter(POSTERIZE, int levels) " + "instead of filter(POSTERIZE)"); case RGB: for (int i = 0; i < pixels.length; i++) { pixels[i] |= 0xff000000; } format = RGB; break; case THRESHOLD: filter(THRESHOLD, 0.5f); break; // [toxi20050728] added new filters case ERODE: dilate(true); break; case DILATE: dilate(false); break; } updatePixels(); // mark as modified } /** * Method to apply a variety of basic filters to this image. * These filters all take a parameter. * <P> * <UL> * <LI>filter(BLUR, int radius) performs a gaussian blur of the * specified radius. * <LI>filter(POSTERIZE, int levels) will posterize the image to * between 2 and 255 levels. * <LI>filter(THRESHOLD, float center) allows you to set the * center point for the threshold. It takes a value from 0 to 1.0. * </UL> * Gaussian blur code contributed by * <A HREF="http://incubator.quasimondo.com">Mario Klingemann</A> * and later updated by toxi for better speed. */ public void filter(int kind, float param) { loadPixels(); switch (kind) { case BLUR: if (format == ALPHA) blurAlpha(param); else if (format == ARGB) blurARGB(param); else blurRGB(param); break; case GRAY: throw new RuntimeException("Use filter(GRAY) instead of " + "filter(GRAY, param)"); case INVERT: throw new RuntimeException("Use filter(INVERT) instead of " + "filter(INVERT, param)"); case OPAQUE: throw new RuntimeException("Use filter(OPAQUE) instead of " + "filter(OPAQUE, param)"); case POSTERIZE: int levels = (int)param; if ((levels < 2) || (levels > 255)) { throw new RuntimeException("Levels must be between 2 and 255 for " + "filter(POSTERIZE, levels)"); } int levels1 = levels - 1; for (int i = 0; i < pixels.length; i++) { int rlevel = (pixels[i] >> 16) & 0xff; int glevel = (pixels[i] >> 8) & 0xff; int blevel = pixels[i] & 0xff; rlevel = (((rlevel * levels) >> 8) * 255) / levels1; glevel = (((glevel * levels) >> 8) * 255) / levels1; blevel = (((blevel * levels) >> 8) * 255) / levels1; pixels[i] = ((0xff000000 & pixels[i]) | (rlevel << 16) | (glevel << 8) | blevel); } break; case THRESHOLD: // greater than or equal to the threshold int thresh = (int) (param * 255); for (int i = 0; i < pixels.length; i++) { int max = Math.max((pixels[i] & RED_MASK) >> 16, Math.max((pixels[i] & GREEN_MASK) >> 8, (pixels[i] & BLUE_MASK))); pixels[i] = (pixels[i] & ALPHA_MASK) | ((max < thresh) ? 0x000000 : 0xffffff); } break; // [toxi20050728] added new filters case ERODE: throw new RuntimeException("Use filter(ERODE) instead of " + "filter(ERODE, param)"); case DILATE: throw new RuntimeException("Use filter(DILATE) instead of " + "filter(DILATE, param)"); } updatePixels(); // mark as modified } /** * Optimized code for building the blur kernel. * further optimized blur code (approx. 15% for radius=20) * bigger speed gains for larger radii (~30%) * added support for various image types (ALPHA, RGB, ARGB) * [toxi 050728] */ protected void buildBlurKernel(float r) { int radius = (int) (r * 3.5f); radius = (radius < 1) ? 1 : ((radius < 248) ? radius : 248); if (blurRadius != radius) { blurRadius = radius; blurKernelSize = 1 + blurRadius<<1; blurKernel = new int[blurKernelSize]; blurMult = new int[blurKernelSize][256]; int bk,bki; int[] bm,bmi; for (int i = 1, radiusi = radius - 1; i < radius; i++) { blurKernel[radius+i] = blurKernel[radiusi] = bki = radiusi * radiusi; bm=blurMult[radius+i]; bmi=blurMult[radiusi--]; for (int j = 0; j < 256; j++) bm[j] = bmi[j] = bki*j; } bk = blurKernel[radius] = radius * radius; bm = blurMult[radius]; for (int j = 0; j < 256; j++) bm[j] = bk*j; } } protected void blurAlpha(float r) { int sum, /*cr, cg,*/ cb; //, k; int /*pixel,*/ read, ri, /*roff,*/ ym, ymi, /*riw,*/ bk0; int b2[] = new int[pixels.length]; int yi = 0; buildBlurKernel(r); for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { //cb = cg = cr = sum = 0; cb = sum = 0; read = x - blurRadius; if (read<0) { bk0=-read; read=0; } else { if (read >= width) break; bk0=0; } for (int i = bk0; i < blurKernelSize; i++) { if (read >= width) break; int c = pixels[read + yi]; int[] bm=blurMult[i]; cb += bm[c & BLUE_MASK]; sum += blurKernel[i]; read++; } ri = yi + x; b2[ri] = cb / sum; } yi += width; } yi = 0; ym=-blurRadius; ymi=ym*width; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { //cb = cg = cr = sum = 0; cb = sum = 0; if (ym<0) { bk0 = ri = -ym; read = x; } else { if (ym >= height) break; bk0 = 0; ri = ym; read = x + ymi; } for (int i = bk0; i < blurKernelSize; i++) { if (ri >= height) break; int[] bm=blurMult[i]; cb += bm[b2[read]]; sum += blurKernel[i]; ri++; read += width; } pixels[x+yi] = (cb/sum); } yi += width; ymi += width; ym++; } } protected void blurRGB(float r) { int sum, cr, cg, cb; //, k; int /*pixel,*/ read, ri, /*roff,*/ ym, ymi, /*riw,*/ bk0; int r2[] = new int[pixels.length]; int g2[] = new int[pixels.length]; int b2[] = new int[pixels.length]; int yi = 0; buildBlurKernel(r); for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { cb = cg = cr = sum = 0; read = x - blurRadius; if (read<0) { bk0=-read; read=0; } else { if (read >= width) break; bk0=0; } for (int i = bk0; i < blurKernelSize; i++) { if (read >= width) break; int c = pixels[read + yi]; int[] bm=blurMult[i]; cr += bm[(c & RED_MASK) >> 16]; cg += bm[(c & GREEN_MASK) >> 8]; cb += bm[c & BLUE_MASK]; sum += blurKernel[i]; read++; } ri = yi + x; r2[ri] = cr / sum; g2[ri] = cg / sum; b2[ri] = cb / sum; } yi += width; } yi = 0; ym=-blurRadius; ymi=ym*width; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { cb = cg = cr = sum = 0; if (ym<0) { bk0 = ri = -ym; read = x; } else { if (ym >= height) break; bk0 = 0; ri = ym; read = x + ymi; } for (int i = bk0; i < blurKernelSize; i++) { if (ri >= height) break; int[] bm=blurMult[i]; cr += bm[r2[read]]; cg += bm[g2[read]]; cb += bm[b2[read]]; sum += blurKernel[i]; ri++; read += width; } pixels[x+yi] = 0xff000000 | (cr/sum)<<16 | (cg/sum)<<8 | (cb/sum); } yi += width; ymi += width; ym++; } } protected void blurARGB(float r) { int sum, cr, cg, cb, ca; int /*pixel,*/ read, ri, /*roff,*/ ym, ymi, /*riw,*/ bk0; int wh = pixels.length; int r2[] = new int[wh]; int g2[] = new int[wh]; int b2[] = new int[wh]; int a2[] = new int[wh]; int yi = 0; buildBlurKernel(r); for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { cb = cg = cr = ca = sum = 0; read = x - blurRadius; if (read<0) { bk0=-read; read=0; } else { if (read >= width) break; bk0=0; } for (int i = bk0; i < blurKernelSize; i++) { if (read >= width) break; int c = pixels[read + yi]; int[] bm=blurMult[i]; ca += bm[(c & ALPHA_MASK) >>> 24]; cr += bm[(c & RED_MASK) >> 16]; cg += bm[(c & GREEN_MASK) >> 8]; cb += bm[c & BLUE_MASK]; sum += blurKernel[i]; read++; } ri = yi + x; a2[ri] = ca / sum; r2[ri] = cr / sum; g2[ri] = cg / sum; b2[ri] = cb / sum; } yi += width; } yi = 0; ym=-blurRadius; ymi=ym*width; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { cb = cg = cr = ca = sum = 0; if (ym<0) { bk0 = ri = -ym; read = x; } else { if (ym >= height) break; bk0 = 0; ri = ym; read = x + ymi; } for (int i = bk0; i < blurKernelSize; i++) { if (ri >= height) break; int[] bm=blurMult[i]; ca += bm[a2[read]]; cr += bm[r2[read]]; cg += bm[g2[read]]; cb += bm[b2[read]]; sum += blurKernel[i]; ri++; read += width; } pixels[x+yi] = (ca/sum)<<24 | (cr/sum)<<16 | (cg/sum)<<8 | (cb/sum); } yi += width; ymi += width; ym++; } } /** * Generic dilate/erode filter using luminance values * as decision factor. [toxi 050728] */ protected void dilate(boolean isInverted) { int currIdx=0; int maxIdx=pixels.length; int[] out=new int[maxIdx]; if (!isInverted) { // erosion (grow light areas) while (currIdx<maxIdx) { int currRowIdx=currIdx; int maxRowIdx=currIdx+width; while (currIdx<maxRowIdx) { int colOrig,colOut; colOrig=colOut=pixels[currIdx]; int idxLeft=currIdx-1; int idxRight=currIdx+1; int idxUp=currIdx-width; int idxDown=currIdx+width; if (idxLeft<currRowIdx) idxLeft=currIdx; if (idxRight>=maxRowIdx) idxRight=currIdx; if (idxUp<0) idxUp=0; if (idxDown>=maxIdx) idxDown=currIdx; int colUp=pixels[idxUp]; int colLeft=pixels[idxLeft]; int colDown=pixels[idxDown]; int colRight=pixels[idxRight]; // compute luminance int currLum = 77*(colOrig>>16&0xff) + 151*(colOrig>>8&0xff) + 28*(colOrig&0xff); int lumLeft = 77*(colLeft>>16&0xff) + 151*(colLeft>>8&0xff) + 28*(colLeft&0xff); int lumRight = 77*(colRight>>16&0xff) + 151*(colRight>>8&0xff) + 28*(colRight&0xff); int lumUp = 77*(colUp>>16&0xff) + 151*(colUp>>8&0xff) + 28*(colUp&0xff); int lumDown = 77*(colDown>>16&0xff) + 151*(colDown>>8&0xff) + 28*(colDown&0xff); if (lumLeft>currLum) { colOut=colLeft; currLum=lumLeft; } if (lumRight>currLum) { colOut=colRight; currLum=lumRight; } if (lumUp>currLum) { colOut=colUp; currLum=lumUp; } if (lumDown>currLum) { colOut=colDown; currLum=lumDown; } out[currIdx++]=colOut; } } } else { // dilate (grow dark areas) while (currIdx<maxIdx) { int currRowIdx=currIdx; int maxRowIdx=currIdx+width; while (currIdx<maxRowIdx) { int colOrig,colOut; colOrig=colOut=pixels[currIdx]; int idxLeft=currIdx-1; int idxRight=currIdx+1; int idxUp=currIdx-width; int idxDown=currIdx+width; if (idxLeft<currRowIdx) idxLeft=currIdx; if (idxRight>=maxRowIdx) idxRight=currIdx; if (idxUp<0) idxUp=0; if (idxDown>=maxIdx) idxDown=currIdx; int colUp=pixels[idxUp]; int colLeft=pixels[idxLeft]; int colDown=pixels[idxDown]; int colRight=pixels[idxRight]; // compute luminance int currLum = 77*(colOrig>>16&0xff) + 151*(colOrig>>8&0xff) + 28*(colOrig&0xff); int lumLeft = 77*(colLeft>>16&0xff) + 151*(colLeft>>8&0xff) + 28*(colLeft&0xff); int lumRight = 77*(colRight>>16&0xff) + 151*(colRight>>8&0xff) + 28*(colRight&0xff); int lumUp = 77*(colUp>>16&0xff) + 151*(colUp>>8&0xff) + 28*(colUp&0xff); int lumDown = 77*(colDown>>16&0xff) + 151*(colDown>>8&0xff) + 28*(colDown&0xff); if (lumLeft<currLum) { colOut=colLeft; currLum=lumLeft; } if (lumRight<currLum) { colOut=colRight; currLum=lumRight; } if (lumUp<currLum) { colOut=colUp; currLum=lumUp; } if (lumDown<currLum) { colOut=colDown; currLum=lumDown; } out[currIdx++]=colOut; } } } System.arraycopy(out,0,pixels,0,maxIdx); } ////////////////////////////////////////////////////////////// // REPLICATING & BLENDING (AREAS) OF PIXELS /** * Copy things from one area of this image * to another area in the same image. */ public void copy(int sx1, int sy1, int sx2, int sy2, int dx1, int dy1, int dx2, int dy2) { copy(this, sx1, sy1, sx2, sy2, dx1, dy1, dx2, dy2); } /** * Copies area of one image into another PImage object. */ public void copy(PImage src, int sx1, int sy1, int sx2, int sy2, int dx1, int dy1, int dx2, int dy2) { if (imageMode == CORNER) { // if CORNERS, do nothing sx2 += sx1; sy2 += sy1; dx2 += dx1; dy2 += dy1; //} else if (imageMode == CENTER) { //sx2 /= 2f; sy2 /= 2f; //dx2 /= 2f; dy2 /= 2f; } if ((src == this) && intersect(sx1, sy1, sx2, sy2, dx1, dy1, dx2, dy2)) { // if src is me, and things intersect, make a copy of the data blit_resize(get(sx1, sy1, sx2 - sx1, sy2 - sy1), 0, 0, sx2 - sx1 - 1, sy2 - sy1 - 1, pixels, width, height, dx1, dy1, dx2, dy2, REPLACE); } else { blit_resize(src, sx1, sy1, sx2, sy2, pixels, width, height, dx1, dy1, dx2, dy2, REPLACE); } } /** * Blend two colors based on a particular mode. * <PRE> * BLEND - linear interpolation of colours: C = A*factor + B * ADD - additive blending with white clip: C = min(A*factor + B, 255) * SUBTRACT - substractive blend with black clip: C = max(B - A*factor, 0) * DARKEST - only the darkest colour succeeds: C = min(A*factor, B) * LIGHTEST - only the lightest colour succeeds: C = max(A*factor, B) * REPLACE - destination colour equals colour of source pixel: C = A * </PRE> */ static public int blendColor(int c1, int c2, int mode) { switch (mode) { case BLEND: return blend_multiply(c1, c2); case ADD: return blend_add_pin(c1, c2); case SUBTRACT: return blend_sub_pin(c1, c2); case LIGHTEST: return blend_lightest(c1, c2); case DARKEST: return blend_darkest(c1, c2); case REPLACE: return c2; } return 0; } /** * Copies and blends 1 pixel with MODE to pixel in this image. * Removing this function, the blend() command above can be used instead. */ /* public void blend(int sx, int sy, int dx, int dy, int mode) { if ((dx >= 0) && (dx < width) && (sx >= 0) && (sx < width) && (dy >= 0) && (dy < height) && (sy >= 0) && (sy < height)) { pixels[dy * width + dx] = blend(pixels[dy * width + dx], pixels[sy * width + sx], mode); } } */ /** * Copies and blends 1 pixel with MODE to pixel in another image */ /* public void blend(PImage src, int sx, int sy, int dx, int dy, int mode) { if ((dx >= 0) && (dx < width) && (sx >= 0) && (sx < src.width) && (dy >= 0) && (dy < height) && (sy >= 0) && (sy < src.height)) { pixels[dy * width + dx] = blend(pixels[dy * width + dx], src.pixels[sy * src.width + sx], mode); } } */ /** * Blends one area of this image to another area */ public void blend(int sx1, int sy1, int sx2, int sy2, int dx1, int dy1, int dx2, int dy2, int mode) { blend(this, sx1, sy1, sx2, sy2, dx1, dy1, dx2, dy2, mode); } /** * Copies area of one image into another PImage object */ public void blend(PImage src, int sx1, int sy1, int sx2, int sy2, int dx1, int dy1, int dx2, int dy2, int mode) { if (imageMode == CORNER) { // if CORNERS, do nothing sx2 += sx1; sy2 += sy1; dx2 += dx1; dy2 += dy1; //} else if (imageMode == CENTER) { //sx2 /= 2f; sy2 /= 2f; //dx2 /= 2f; dy2 /= 2f; } if ((src == this) && intersect(sx1, sy1, sx2, sy2, dx1, dy1, dx2, dy2)) { blit_resize(get(sx1, sy1, sx2 - sx1, sy2 - sy1), 0, 0, sx2 - sx1 - 1, sy2 - sy1 - 1, pixels, width, height, dx1, dy1, dx2, dy2, mode); } else { blit_resize(src, sx1, sy1, sx2, sy2, pixels, width, height, dx1, dy1, dx2, dy2, mode); } } /** * Check to see if two rectangles intersect one another */ protected boolean intersect(int sx1, int sy1, int sx2, int sy2, int dx1, int dy1, int dx2, int dy2) { int sw = sx2 - sx1 + 1; int sh = sy2 - sy1 + 1; int dw = dx2 - dx1 + 1; int dh = dy2 - dy1 + 1; if (dx1 < sx1) { dw += dx1 - sx1; if (dw > sw) { dw = sw; } } else { int w = sw + sx1 - dx1; if (dw > w) { dw = w; } } if (dy1 < sy1) { dh += dy1 - sy1; if (dh > sh) { dh = sh; } } else { int h = sh + sy1 - dy1; if (dh > h) { dh = h; } } return !(dw <= 0 || dh <= 0); } ////////////////////////////////////////////////////////////// // COPYING IMAGE DATA /** * Duplicate an image, returns new PImage object. * The pixels[] array for the new object will be unique * and recopied from the source image. This is implemented as an * override of Object.clone(). We recommend using get() instead, * because it prevents you from needing to catch the * CloneNotSupportedException, and from doing a cast from the result. */ public Object clone() throws CloneNotSupportedException { // ignore PImage c = (PImage) super.clone(); // super.clone() will only copy the reference to the pixels // array, so this will do a proper duplication of it instead. c.pixels = new int[width * height]; System.arraycopy(pixels, 0, c.pixels, 0, pixels.length); // return the goods return c; } ////////////////////////////////////////////////////////////// /** * Internal blitter/resizer/copier from toxi. * Uses bilinear filtering if smooth() has been enabled * 'mode' determines the blending mode used in the process. */ private void blit_resize(PImage img, int srcX1, int srcY1, int srcX2, int srcY2, int[] destPixels, int screenW, int screenH, int destX1, int destY1, int destX2, int destY2, int mode) { if (srcX1 < 0) srcX1 = 0; if (srcY1 < 0) srcY1 = 0; if (srcX2 >= img.width) srcX2 = img.width - 1; if (srcY2 >= img.height) srcY2 = img.height - 1; int srcW = srcX2 - srcX1; int srcH = srcY2 - srcY1; int destW = destX2 - destX1; int destH = destY2 - destY1; if (!smooth) { srcW++; srcH++; } if (destW <= 0 || destH <= 0 || srcW <= 0 || srcH <= 0 || destX1 >= screenW || destY1 >= screenH || srcX1 >= img.width || srcY1 >= img.height) { return; } int dx = (int) (srcW / (float) destW * PRECISIONF); int dy = (int) (srcH / (float) destH * PRECISIONF); srcXOffset = (int) (destX1 < 0 ? -destX1 * dx : srcX1 * PRECISIONF); srcYOffset = (int) (destY1 < 0 ? -destY1 * dy : srcY1 * PRECISIONF); if (destX1 < 0) { destW += destX1; destX1 = 0; } if (destY1 < 0) { destH += destY1; destY1 = 0; } destW = low(destW, screenW - destX1); destH = low(destH, screenH - destY1); int destOffset = destY1 * screenW + destX1; srcBuffer = img.pixels; if (smooth) { // use bilinear filtering iw = img.width; iw1 = img.width - 1; ih1 = img.height - 1; switch (mode) { case BLEND: for (int y = 0; y < destH; y++) { filter_new_scanline(); for (int x = 0; x < destW; x++) { destPixels[destOffset + x] = blend_multiply(destPixels[destOffset + x], filter_bilinear()); sX += dx; } destOffset += screenW; srcYOffset += dy; } break; case ADD: for (int y = 0; y < destH; y++) { filter_new_scanline(); for (int x = 0; x < destW; x++) { destPixels[destOffset + x] = blend_add_pin(destPixels[destOffset + x], filter_bilinear()); sX += dx; } destOffset += screenW; srcYOffset += dy; } break; case SUBTRACT: for (int y = 0; y < destH; y++) { filter_new_scanline(); for (int x = 0; x < destW; x++) { destPixels[destOffset + x] = blend_sub_pin(destPixels[destOffset + x], filter_bilinear()); sX += dx; } destOffset += screenW; srcYOffset += dy; } break; case LIGHTEST: for (int y = 0; y < destH; y++) { filter_new_scanline(); for (int x = 0; x < destW; x++) { destPixels[destOffset + x] = blend_lightest(destPixels[destOffset + x], filter_bilinear()); sX += dx; } destOffset += screenW; srcYOffset += dy; } break; case DARKEST: for (int y = 0; y < destH; y++) { filter_new_scanline(); for (int x = 0; x < destW; x++) { destPixels[destOffset + x] = blend_darkest(destPixels[destOffset + x], filter_bilinear()); sX += dx; } destOffset += screenW; srcYOffset += dy; } break; case REPLACE: for (int y = 0; y < destH; y++) { filter_new_scanline(); for (int x = 0; x < destW; x++) { destPixels[destOffset + x] = filter_bilinear(); sX += dx; } destOffset += screenW; srcYOffset += dy; } break; } } else { // nearest neighbour scaling (++fast!) switch (mode) { case BLEND: for (int y = 0; y < destH; y++) { sX = srcXOffset; sY = (srcYOffset >> PRECISIONB) * img.width; for (int x = 0; x < destW; x++) { destPixels[destOffset + x] = blend_multiply(destPixels[destOffset + x], srcBuffer[sY + (sX >> PRECISIONB)]); sX += dx; } destOffset += screenW; srcYOffset += dy; } break; case ADD: for (int y = 0; y < destH; y++) { sX = srcXOffset; sY = (srcYOffset >> PRECISIONB) * img.width; for (int x = 0; x < destW; x++) { destPixels[destOffset + x] = blend_add_pin(destPixels[destOffset + x], srcBuffer[sY + (sX >> PRECISIONB)]); sX += dx; } destOffset += screenW; srcYOffset += dy; } break; case SUBTRACT: for (int y = 0; y < destH; y++) { sX = srcXOffset; sY = (srcYOffset >> PRECISIONB) * img.width; for (int x = 0; x < destW; x++) { destPixels[destOffset + x] = blend_sub_pin(destPixels[destOffset + x], srcBuffer[sY + (sX >> PRECISIONB)]); sX += dx; } destOffset += screenW; srcYOffset += dy; } break; case LIGHTEST: for (int y = 0; y < destH; y++) { sX = srcXOffset; sY = (srcYOffset >> PRECISIONB) * img.width; for (int x = 0; x < destW; x++) { destPixels[destOffset + x] = blend_lightest(destPixels[destOffset + x], srcBuffer[sY + (sX >> PRECISIONB)]); sX += dx; } destOffset += screenW; srcYOffset += dy; } break; case DARKEST: for (int y = 0; y < destH; y++) { sX = srcXOffset; sY = (srcYOffset >> PRECISIONB) * img.width; for (int x = 0; x < destW; x++) { destPixels[destOffset + x] = blend_darkest(destPixels[destOffset + x], srcBuffer[sY + (sX >> PRECISIONB)]); sX += dx; } destOffset += screenW; srcYOffset += dy; } break; case REPLACE: for (int y = 0; y < destH; y++) { sX = srcXOffset; sY = (srcYOffset >> PRECISIONB) * img.width; for (int x = 0; x < destW; x++) { destPixels[destOffset + x] = srcBuffer[sY + (sX >> PRECISIONB)]; sX += dx; } destOffset += screenW; srcYOffset += dy; } break; } } } private void filter_new_scanline() { sX = srcXOffset; fracV = srcYOffset & PREC_MAXVAL; ifV = PREC_MAXVAL - fracV; v1 = (srcYOffset >> PRECISIONB) * iw; v2 = low((srcYOffset >> PRECISIONB) + 1, ih1) * iw; } private int filter_bilinear() { fracU = sX & PREC_MAXVAL; ifU = PREC_MAXVAL - fracU; ul = (ifU * ifV) >> PRECISIONB; ll = (ifU * fracV) >> PRECISIONB; ur = (fracU * ifV) >> PRECISIONB; lr = (fracU * fracV) >> PRECISIONB; u1 = (sX >> PRECISIONB); u2 = low(u1 + 1, iw1); // get color values of the 4 neighbouring texels cUL = srcBuffer[v1 + u1]; cUR = srcBuffer[v1 + u2]; cLL = srcBuffer[v2 + u1]; cLR = srcBuffer[v2 + u2]; r = ((ul*((cUL&RED_MASK)>>16) + ll*((cLL&RED_MASK)>>16) + ur*((cUR&RED_MASK)>>16) + lr*((cLR&RED_MASK)>>16)) << PREC_RED_SHIFT) & RED_MASK; g = ((ul*(cUL&GREEN_MASK) + ll*(cLL&GREEN_MASK) + ur*(cUR&GREEN_MASK) + lr*(cLR&GREEN_MASK)) >>> PRECISIONB) & GREEN_MASK; b = (ul*(cUL&BLUE_MASK) + ll*(cLL&BLUE_MASK) + ur*(cUR&BLUE_MASK) + lr*(cLR&BLUE_MASK)) >>> PRECISIONB; a = ((ul*((cUL&ALPHA_MASK)>>>24) + ll*((cLL&ALPHA_MASK)>>>24) + ur*((cUR&ALPHA_MASK)>>>24) + lr*((cLR&ALPHA_MASK)>>>24)) << PREC_ALPHA_SHIFT) & ALPHA_MASK; return a | r | g | b; } ////////////////////////////////////////////////////////////// // internal blending methods private static int low(int a, int b) { return (a < b) ? a : b; } private static int high(int a, int b) { return (a > b) ? a : b; } private static int mix(int a, int b, int f) { return a + (((b - a) * f) >> 8); } ///////////////////////////////////////////////////////////// // BLEND MODE IMPLEMENTIONS private static int blend_multiply(int a, int b) { int f = (b & ALPHA_MASK) >>> 24; return (low(((a & ALPHA_MASK) >>> 24) + f, 0xff) << 24 | mix(a & RED_MASK, b & RED_MASK, f) & RED_MASK | mix(a & GREEN_MASK, b & GREEN_MASK, f) & GREEN_MASK | mix(a & BLUE_MASK, b & BLUE_MASK, f)); } /** * additive blend with clipping */ private static int blend_add_pin(int a, int b) { int f = (b & ALPHA_MASK) >>> 24; return (low(((a & ALPHA_MASK) >>> 24) + f, 0xff) << 24 | low(((a & RED_MASK) + ((b & RED_MASK) >> 8) * f), RED_MASK) & RED_MASK | low(((a & GREEN_MASK) + ((b & GREEN_MASK) >> 8) * f), GREEN_MASK) & GREEN_MASK | low((a & BLUE_MASK) + (((b & BLUE_MASK) * f) >> 8), BLUE_MASK)); } /** * subtractive blend with clipping */ private static int blend_sub_pin(int a, int b) { int f = (b & ALPHA_MASK) >>> 24; return (low(((a & ALPHA_MASK) >>> 24) + f, 0xff) << 24 | high(((a & RED_MASK) - ((b & RED_MASK) >> 8) * f), GREEN_MASK) & RED_MASK | high(((a & GREEN_MASK) - ((b & GREEN_MASK) >> 8) * f), BLUE_MASK) & GREEN_MASK | high((a & BLUE_MASK) - (((b & BLUE_MASK) * f) >> 8), 0)); } /** * only returns the blended lightest colour */ private static int blend_lightest(int a, int b) { int f = (b & ALPHA_MASK) >>> 24; return (low(((a & ALPHA_MASK) >>> 24) + f, 0xff) << 24 | high(a & RED_MASK, ((b & RED_MASK) >> 8) * f) & RED_MASK | high(a & GREEN_MASK, ((b & GREEN_MASK) >> 8) * f) & GREEN_MASK | high(a & BLUE_MASK, ((b & BLUE_MASK) * f) >> 8)); } /** * only returns the blended darkest colour */ private static int blend_darkest(int a, int b) { int f = (b & ALPHA_MASK) >>> 24; return (low(((a & ALPHA_MASK) >>> 24) + f, 0xff) << 24 | mix(a & RED_MASK, low(a & RED_MASK, ((b & RED_MASK) >> 8) * f), f) & RED_MASK | mix(a & GREEN_MASK, low(a & GREEN_MASK, ((b & GREEN_MASK) >> 8) * f), f) & GREEN_MASK | mix(a & BLUE_MASK, low(a & BLUE_MASK, ((b & BLUE_MASK) * f) >> 8), f)); } ////////////////////////////////////////////////////////////// // FILE I/O static byte TIFF_HEADER[] = { 77, 77, 0, 42, 0, 0, 0, 8, 0, 9, 0, -2, 0, 4, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 3, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 3, 0, 0, 0, 1, 0, 0, 0, 0, 1, 2, 0, 3, 0, 0, 0, 3, 0, 0, 0, 122, 1, 6, 0, 3, 0, 0, 0, 1, 0, 2, 0, 0, 1, 17, 0, 4, 0, 0, 0, 1, 0, 0, 3, 0, 1, 21, 0, 3, 0, 0, 0, 1, 0, 3, 0, 0, 1, 22, 0, 3, 0, 0, 0, 1, 0, 0, 0, 0, 1, 23, 0, 4, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 0, 8, 0, 8 }; /* protected boolean saveHeaderTIFF(OutputStream output) { try { byte tiff[] = new byte[768]; System.arraycopy(tiff_header, 0, tiff, 0, tiff_header.length); tiff[30] = (byte) ((width >> 8) & 0xff); tiff[31] = (byte) ((width) & 0xff); tiff[42] = tiff[102] = (byte) ((height >> 8) & 0xff); tiff[43] = tiff[103] = (byte) ((height) & 0xff); int count = width*height*3; tiff[114] = (byte) ((count >> 24) & 0xff); tiff[115] = (byte) ((count >> 16) & 0xff); tiff[116] = (byte) ((count >> 8) & 0xff); tiff[117] = (byte) ((count) & 0xff); output.write(tiff); return true; } catch (IOException e) { e.printStackTrace(); } return false; } */ static final String TIFF_ERROR = "Error: Processing can only read its own TIFF files."; static protected PImage loadTIFF(byte tiff[]) { if ((tiff[42] != tiff[102]) || // width/height in both places (tiff[43] != tiff[103])) { System.err.println(TIFF_ERROR); return null; } int width = ((tiff[30] & 0xff) << 8) | (tiff[31] & 0xff); int height = ((tiff[42] & 0xff) << 8) | (tiff[43] & 0xff); int count = ((tiff[114] & 0xff) << 24) | ((tiff[115] & 0xff) << 16) | ((tiff[116] & 0xff) << 8) | (tiff[117] & 0xff); if (count != width * height * 3) { System.err.println(TIFF_ERROR + " (" + width + ", " + height +")"); return null; } // check the rest of the header for (int i = 0; i < TIFF_HEADER.length; i++) { if ((i == 30) || (i == 31) || (i == 42) || (i == 43) || (i == 102) || (i == 103) || (i == 114) || (i == 115) || (i == 116) || (i == 117)) continue; if (tiff[i] != TIFF_HEADER[i]) { System.err.println(TIFF_ERROR + " (" + i + ")"); return null; } } PImage outgoing = new PImage(width, height, RGB); int index = 768; count /= 3; for (int i = 0; i < count; i++) { outgoing.pixels[i] = 0xFF000000 | (tiff[index++] & 0xff) << 16 | (tiff[index++] & 0xff) << 8 | (tiff[index++] & 0xff); } return outgoing; } protected boolean saveTIFF(OutputStream output) { // shutting off the warning, people can figure this out themselves /* if (format != RGB) { System.err.println("Warning: only RGB information is saved with " + ".tif files. Use .tga or .png for ARGB images and others."); } */ try { byte tiff[] = new byte[768]; System.arraycopy(TIFF_HEADER, 0, tiff, 0, TIFF_HEADER.length); tiff[30] = (byte) ((width >> 8) & 0xff); tiff[31] = (byte) ((width) & 0xff); tiff[42] = tiff[102] = (byte) ((height >> 8) & 0xff); tiff[43] = tiff[103] = (byte) ((height) & 0xff); int count = width*height*3; tiff[114] = (byte) ((count >> 24) & 0xff); tiff[115] = (byte) ((count >> 16) & 0xff); tiff[116] = (byte) ((count >> 8) & 0xff); tiff[117] = (byte) ((count) & 0xff); // spew the header to the disk output.write(tiff); for (int i = 0; i < pixels.length; i++) { output.write((pixels[i] >> 16) & 0xff); output.write((pixels[i] >> 8) & 0xff); output.write(pixels[i] & 0xff); } output.flush(); return true; } catch (IOException e) { e.printStackTrace(); } return false; } /** * Creates a Targa32 formatted byte sequence of specified * pixel buffer using RLE compression. * </p> * Also figured out how to avoid parsing the image upside-down * (there's a header flag to set the image origin to top-left) * </p> * Starting with revision 0092, the format setting is taken into account: * <UL> * <LI><TT>ALPHA</TT> images written as 8bit grayscale (uses lowest byte) * <LI><TT>RGB</TT> &rarr; 24 bits * <LI><TT>ARGB</TT> &rarr; 32 bits * </UL> * All versions are RLE compressed. * </p> * Contributed by toxi 8-10 May 2005, based on this RLE * <A HREF="http://www.wotsit.org/download.asp?f=tga">specification</A> */ protected boolean saveTGA(OutputStream output) { byte header[] = new byte[18]; if (format == ALPHA) { // save ALPHA images as 8bit grayscale header[2] = 0x0B; header[16] = 0x08; header[17] = 0x28; } else if (format == RGB) { header[2] = 0x0A; header[16] = 24; header[17] = 0x20; } else if (format == ARGB) { header[2] = 0x0A; header[16] = 32; header[17] = 0x28; } else { throw new RuntimeException("Image format not recognized inside save()"); } // set image dimensions lo-hi byte order header[12] = (byte) (width & 0xff); header[13] = (byte) (width >> 8); header[14] = (byte) (height & 0xff); header[15] = (byte) (height >> 8); try { output.write(header); int maxLen = height * width; int index = 0; int col; //, prevCol; int[] currChunk = new int[128]; // 8bit image exporter is in separate loop // to avoid excessive conditionals... if (format == ALPHA) { while (index < maxLen) { boolean isRLE = false; int rle = 1; currChunk[0] = col = pixels[index] & 0xff; while (index + rle < maxLen) { if (col != (pixels[index + rle]&0xff) || rle == 128) { isRLE = (rle > 1); break; } rle++; } if (isRLE) { output.write(0x80 | (rle - 1)); output.write(col); } else { rle = 1; while (index + rle < maxLen) { int cscan = pixels[index + rle] & 0xff; if ((col != cscan && rle < 128) || rle < 3) { currChunk[rle] = col = cscan; } else { if (col == cscan) rle -= 2; break; } rle++; } output.write(rle - 1); for (int i = 0; i < rle; i++) output.write(currChunk[i]); } index += rle; } } else { // export 24/32 bit TARGA while (index < maxLen) { boolean isRLE = false; currChunk[0] = col = pixels[index]; int rle = 1; // try to find repeating bytes (min. len = 2 pixels) // maximum chunk size is 128 pixels while (index + rle < maxLen) { if (col != pixels[index + rle] || rle == 128) { isRLE = (rle > 1); // set flag for RLE chunk break; } rle++; } if (isRLE) { output.write(128 | (rle - 1)); output.write(col & 0xff); output.write(col >> 8 & 0xff); output.write(col >> 16 & 0xff); if (format == ARGB) output.write(col >>> 24 & 0xff); } else { // not RLE rle = 1; while (index + rle < maxLen) { if ((col != pixels[index + rle] && rle < 128) || rle < 3) { currChunk[rle] = col = pixels[index + rle]; } else { // check if the exit condition was the start of // a repeating colour if (col == pixels[index + rle]) rle -= 2; break; } rle++; } // write uncompressed chunk output.write(rle - 1); if (format == ARGB) { for (int i = 0; i < rle; i++) { col = currChunk[i]; output.write(col & 0xff); output.write(col >> 8 & 0xff); output.write(col >> 16 & 0xff); output.write(col >>> 24 & 0xff); } } else { for (int i = 0; i < rle; i++) { col = currChunk[i]; output.write(col & 0xff); output.write(col >> 8 & 0xff); output.write(col >> 16 & 0xff); } } } index += rle; } } output.flush(); return true; } catch (IOException e) { e.printStackTrace(); return false; } } /** * Use ImageIO functions from Java 1.4 and later to handle image save. * Various formats are supported, typically jpeg, png, bmp, and wbmp. * To get a list of the supported formats for writing, use: <BR> * <TT>println(javax.imageio.ImageIO.getReaderFormatNames())</TT> */ protected void saveImageIO(String path) throws IOException { try { //BufferedImage bimage = // new BufferedImage(width, height, (format == ARGB) ? // BufferedImage.TYPE_INT_ARGB : // BufferedImage.TYPE_INT_RGB); Class bufferedImageClass = Class.forName("java.awt.image.BufferedImage"); Constructor bufferedImageConstructor = bufferedImageClass.getConstructor(new Class[] { Integer.TYPE, Integer.TYPE, Integer.TYPE }); Field typeIntRgbField = bufferedImageClass.getField("TYPE_INT_RGB"); int typeIntRgb = typeIntRgbField.getInt(typeIntRgbField); Field typeIntArgbField = bufferedImageClass.getField("TYPE_INT_ARGB"); int typeIntArgb = typeIntArgbField.getInt(typeIntArgbField); Object bimage = bufferedImageConstructor.newInstance(new Object[] { new Integer(width), new Integer(height), new Integer((format == ARGB) ? typeIntArgb : typeIntRgb) }); //bimage.setRGB(0, 0, width, height, pixels, 0, width); Method setRgbMethod = bufferedImageClass.getMethod("setRGB", new Class[] { Integer.TYPE, Integer.TYPE, Integer.TYPE, Integer.TYPE, pixels.getClass(), Integer.TYPE, Integer.TYPE }); setRgbMethod.invoke(bimage, new Object[] { new Integer(0), new Integer(0), new Integer(width), new Integer(height), pixels, new Integer(0), new Integer(width) }); File file = new File(path); String extension = path.substring(path.lastIndexOf('.') + 1); //ImageIO.write(bimage, extension, file); Class renderedImageClass = Class.forName("java.awt.image.RenderedImage"); Class ioClass = Class.forName("javax.imageio.ImageIO"); Method writeMethod = ioClass.getMethod("write", new Class[] { renderedImageClass, String.class, File.class }); writeMethod.invoke(null, new Object[] { bimage, extension, file }); } catch (Exception e) { e.printStackTrace(); throw new IOException("image save failed."); } } protected String[] saveImageFormats; /** * Save this image to disk. * <p> * As of revision 0100, this function requires an absolute path, * in order to avoid confusion. To save inside the sketch folder, * use the function savePath() from PApplet, or use saveFrame() instead. * <p> * As of revision 0115, when using Java 1.4 and later, you can write * to several formats besides tga and tiff. If Java 1.4 is installed * and the extension used is supported (usually png, jpg, jpeg, bmp, * and tiff), then those methods will be used to write the image. * To get a list of the supported formats for writing, use: <BR> * <TT>println(javax.imageio.ImageIO.getReaderFormatNames())</TT> * <p> * To use the original built-in image writers, use .tga as the extension, * or don't include an extension, in which case .tif will be added. * <p> * The ImageIO API claims to support wbmp files, however they probably * require a black and white image. Basic testing produced a zero-length * file with no error. * <p> * As of revision 0116, savePath() is not needed if this object has been * created (as recommended) via createImage() or createGraphics() or * one of its neighbors. */ public void save(String path) { // ignore boolean success = false; File file = new File(path); if (!file.isAbsolute()) { if (parent != null) { //file = new File(parent.savePath(filename)); path = parent.savePath(path); } else { throw new RuntimeException("PImage.save() requires an absolute path. Or you can " + "use createImage() instead or pass savePath() to save()."); } } try { OutputStream os = null; if (PApplet.javaVersion >= 1.4f) { if (saveImageFormats == null) { //saveImageFormats = javax.imageio.ImageIO.getWriterFormatNames(); try { Class ioClass = Class.forName("javax.imageio.ImageIO"); Method getFormatNamesMethod = ioClass.getMethod("getWriterFormatNames", (Class[]) null); saveImageFormats = (String[]) getFormatNamesMethod.invoke((Class[]) null, (Object[]) null); } catch (Exception e) { e.printStackTrace(); } } if (saveImageFormats != null) { for (int i = 0; i < saveImageFormats.length; i++) { if (path.endsWith("." + saveImageFormats[i])) { saveImageIO(path); return; } } } } if (path.toLowerCase().endsWith(".tga")) { os = new BufferedOutputStream(new FileOutputStream(path), 32768); success = saveTGA(os); //, pixels, width, height, format); } else { if (!path.toLowerCase().endsWith(".tif") && !path.toLowerCase().endsWith(".tiff")) { // if no .tif extension, add it.. path += ".tif"; } os = new BufferedOutputStream(new FileOutputStream(path), 32768); success = saveTIFF(os); //, pixels, width, height); } os.flush(); os.close(); } catch (IOException e) { //System.err.println("Error while saving image."); e.printStackTrace(); success = false; } if (!success) { throw new RuntimeException("Error while saving image."); } } }
[ "yuzhongxing88@gmail.com" ]
yuzhongxing88@gmail.com
b2f6584dc1dd28216d08189149c5542752b9430a
a7f9a18aa0a75ddaf3422d03f4a258c01b3ed0b4
/Project/src/main/java/tn/esprit/Project/Controller/StockControl.java
eb6d6fc30b3b24236bd99d06c6b87afecfea6869
[]
no_license
zbidi48/ahmed-pi-dev
6501b416fa0f14b09ddf1e01f8aa1caac4c13f4c
4263e21bdb9cce879491d4ac69ee8e76503e04c0
refs/heads/master
2023-04-21T22:55:20.337989
2021-05-11T08:25:46
2021-05-11T08:25:46
356,905,725
0
0
null
null
null
null
UTF-8
Java
false
false
1,394
java
package tn.esprit.Project.Controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import tn.esprit.Project.Service.StockService; import tn.esprit.Project.entites.Stock; @RestController public class StockControl { @Autowired private StockService ss ; @GetMapping("/Stock") public List<Stock> showStock(){ return ss.showS(); } @PostMapping("/Stock/Add") public Stock AddStock (@RequestBody Stock l) { return ss.SaveStock(l); } @DeleteMapping("/Stock/Delete/{id}") public void Delete (@PathVariable("id") Long id) { ss.DeletStockById(id); } @GetMapping("/Stock/{id}") public Stock GetById (@PathVariable("id") Long id) { return ss.getStock(id); } @PutMapping("/Stock/Update/{id}") public Stock updateStock (@RequestBody Stock newstock, @PathVariable Long id) { return ss.UpadateStock(newstock); } }
[ "rami.benmessaoud@esprit.tn" ]
rami.benmessaoud@esprit.tn
533f77f61f96e6beb793c24f75ec44fb2eef97d7
cb5f168154e958afe009c4138d35522116672c9e
/workspaces/default/AWT/src/MyCanvas1.java
e86ac0dea636956220fe0db2da292c3bdc3301fc
[]
no_license
vipin182sahu/java-application
a4efdcab83555617a8729d2f014b1449472ffb53
059015a8ac23afe9141fc02cce865e37284c2d81
refs/heads/master
2020-12-03T18:33:57.716405
2016-08-29T14:00:11
2016-08-29T14:00:11
66,348,315
86
1
null
null
null
null
UTF-8
Java
false
false
200
java
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class MyCanvas1 extends Canvas { public void paint(Graphics g){ g.setColor(Color.red); g.drawLine(70,70,200,200); } }
[ "vipin182sahu@gmail.com" ]
vipin182sahu@gmail.com
65367f087173c2058402da769b9ebd5c78d5e120
d14638a5db18ad30d3039e73c8b3a7937b1dc827
/ruoyi-resume/src/main/java/com/ruoyi/statistic/ds.java
32ddef2acc123754437e0c2c12ec320a9c65517b
[ "MIT" ]
permissive
yanchenghu/oa
5deb91a8f374f6493d7175a3d87a0286983bb48f
2eaeac8d556eef531916b20e957584d9c053e655
refs/heads/master
2023-06-19T23:37:41.151760
2021-04-22T07:16:23
2021-04-22T07:16:23
302,515,053
0
0
null
null
null
null
UTF-8
Java
false
false
50
java
package com.ruoyi.statistic; public class ds { }
[ "931410396@qq.com" ]
931410396@qq.com
206ed493b9487374e4efcfa61ef77a16b1370715
e124c06aa37b93502a84f8931e1e792539883b9d
/jshooter-master/contrib/ms3d/MS3DModel.java
b7e5f75b043157c48f794f5721bf0136ef478417
[ "Unlicense" ]
permissive
m-shayanshafi/FactRepositoryProjects
12d7b65505c1e0a8e0ec3577cf937a1e3d17c417
1d45d667b454064107d78213e8cd3ec795827b41
refs/heads/master
2020-06-13T12:04:53.891793
2016-12-02T11:30:49
2016-12-02T11:30:49
75,389,381
1
0
null
null
null
null
UTF-8
Java
false
false
3,869
java
package ms3d; import java.io.*; import utils.LittleEndianDataInputStream; /** * A Milkshape 3D Model. * * @author Nikolaj Ougaard */ public class MS3DModel { public MS3DHeader header; public MS3DVertex[] vertices; public MS3DTriangle[] triangles; public MS3DGroup[] groups; public MS3DMaterial[] materials; public MS3DJoint[] joints; public MS3DModel(MS3DHeader header, MS3DVertex[] vertices, MS3DTriangle[] triangles, MS3DGroup[] groups, MS3DMaterial[] materials, MS3DJoint[] joints) { this.header = header; this.vertices = vertices; this.triangles = triangles; this.groups = groups; this.materials = materials; this.joints = joints; } public static MS3DModel decodeMS3DModel(InputStream is) throws IOException { LittleEndianDataInputStream dataInputStream = new LittleEndianDataInputStream(is); MS3DHeader header = decodeMS3DHeader(dataInputStream); MS3DVertex[] vertices = decodeMS3DVertices(dataInputStream); MS3DTriangle[] triangles = decodeMS3DTriangles(dataInputStream); MS3DGroup[] groups = decodeMS3DGroups(dataInputStream); MS3DMaterial[] materials = decodeMaterials(dataInputStream); MS3DJoint[] joints = decodeJoints(dataInputStream); return new MS3DModel(header, vertices, triangles, groups, materials, joints); } private static MS3DJoint[] decodeJoints(DataInput input) throws IOException { int numJoints = input.readUnsignedShort(); MS3DJoint[] joints = new MS3DJoint[numJoints]; for (int jc = 0; jc < numJoints; jc++) { joints[jc] = MS3DJoint.decodeMS3DJoint(input); } return joints; } private static MS3DMaterial[] decodeMaterials(DataInput input) throws IOException { int numMaterials = input.readUnsignedShort(); MS3DMaterial[] materials = new MS3DMaterial[numMaterials]; for (int mc = 0; mc < numMaterials; mc++) { materials[mc] = MS3DMaterial.decodeMS3DMaterial(input); } return materials; } private static MS3DGroup[] decodeMS3DGroups(DataInput input) throws IOException { int numGroups = input.readUnsignedShort(); MS3DGroup[] groups = new MS3DGroup[numGroups]; for (int gc = 0; gc < numGroups; gc++) { groups[gc] = MS3DGroup.decodeMS3DGroup(input); } return groups; } private static MS3DTriangle[] decodeMS3DTriangles(DataInput input) throws IOException { int numTriangles = input.readUnsignedShort(); MS3DTriangle[] triangles = new MS3DTriangle[numTriangles]; for (int tc = 0; tc < numTriangles; tc++) { triangles[tc] = MS3DTriangle.decodeMS3DTriangle(input); } return triangles; } private static MS3DVertex[] decodeMS3DVertices(DataInput input) throws IOException { int numVertices = input.readUnsignedShort(); MS3DVertex[] vertices = new MS3DVertex[numVertices]; for (int vc = 0; vc < numVertices; vc++) { vertices[vc] = MS3DVertex.decodeMS3DVertex(input); } return vertices; } private static MS3DHeader decodeMS3DHeader(DataInput input) throws IOException { return MS3DHeader.decodeMS3DHeader(input); } static String decodeZeroTerminatedString(DataInput input, int maximumLength) throws IOException { boolean zeroEncountered = false; StringBuffer stringBuffer = new StringBuffer(); for (int c = 0; c < maximumLength; c++) { int readByte = input.readUnsignedByte(); if (!zeroEncountered && readByte != 0) { stringBuffer.append((char)readByte); } else { zeroEncountered = true; } } return stringBuffer.toString(); } }
[ "mshayanshafi@gmail.com" ]
mshayanshafi@gmail.com
4d4cc846e5df32908006fb6e61274a50822b5ab6
abaee31383bbb6dd467d6678b0dd3522cd6a220b
/src/test/java/rc/demo/app/util/TestNumberFormatterUtil.java
224638f0949c8db073c3664f1276b8c99d8b2ded
[]
no_license
ravaneswaran/paytm-web-integration-demo
39710ff14824d45b2f8536693162e7799e77273f
1d00461144669c6b8f5c7a6cbaa8c43a9b817b91
refs/heads/master
2021-06-14T22:33:08.272850
2019-11-06T01:36:49
2019-11-06T01:36:49
204,686,545
0
0
null
2021-06-04T02:14:47
2019-08-27T11:15:07
Java
UTF-8
Java
false
false
870
java
package rc.demo.app.util; import junit.framework.TestCase; import rc.demo.app.util.NumberFormatterUtil; public class TestNumberFormatterUtil extends TestCase { public void testGetFormattedString_1() { long value = 1234l; String returnVal = NumberFormatterUtil.getFormattedString(value); assertEquals("123.40", returnVal); } public void testGetFormattedString_2() { long value = 12345l; String returnVal = NumberFormatterUtil.getFormattedString(value); assertEquals("123.45", returnVal); } public void testGetFormattedString_3() { long value = 123456l; String returnVal = NumberFormatterUtil.getFormattedString(value); assertEquals("1234.56", returnVal); } public void testGetFormattedString_4() { long value = 1234567l; String returnVal = NumberFormatterUtil.getFormattedString(value); assertEquals("12345.67", returnVal); } }
[ "ravaneswaran.chinnasamy@niivsoftware.com" ]
ravaneswaran.chinnasamy@niivsoftware.com
3eb5aaa5131b81f4c55b0ee0a69100a6d90ea5ac
9c15c0ed0e7a5a520c3b4e6e7b55d34783387f78
/src/main/java/com/apiapp/service/ResponseAssembler.java
5eab829f4563944194019e4b2c1699c12ba1b3f2
[]
no_license
arundhati-adiga/spring-boot-rest
c12ff099d0ce268adb935d62563b9661a456ee8d
94774fd940a3f9f4833ad7f0ab9ca69e274bb7de
refs/heads/master
2020-12-02T09:20:22.074698
2020-01-02T13:38:42
2020-01-02T13:38:42
230,959,901
0
0
null
null
null
null
UTF-8
Java
false
false
1,511
java
package com.apiapp.service; import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.linkTo; import java.util.Arrays; import org.springframework.hateoas.Link; import com.apiapp.controller.CategoryController; import com.apiapp.model.CategorisedTransaction; import com.apiapp.model.CategorizedTransactionsList; /** * Add the links * @author Arundhati Adiga *ResponseAssembler.java */ public class ResponseAssembler { /** * Add link page info for get service * @param categorizedTransaction * @param page * @param size * @param categoryIds * @return */ public CategorizedTransactionsList addLinks(CategorizedTransactionsList categorizedTransaction,int page,int size, String[] categoryIds) { Link self=linkTo(CategoryController.class).slash(Arrays.toString(categoryIds)).withSelfRel(); Link next=linkTo(CategoryController.class).slash(Arrays.toString(categoryIds)).slash(page+1).slash(size).withRel("Next"); Link first=linkTo(CategoryController.class).slash(Arrays.toString(categoryIds)).slash(1).slash(size).withRel("First"); categorizedTransaction.add(self); categorizedTransaction.add(next); categorizedTransaction.add(first); return categorizedTransaction; } public CategorisedTransaction addLinks(CategorisedTransaction newCategorizedtransaction) { Link self=linkTo(CategoryController.class).slash(newCategorizedtransaction.getCategoryId()).withSelfRel(); newCategorizedtransaction.add(self); return newCategorizedtransaction; } }
[ "arundhati.adiga@gmail.com" ]
arundhati.adiga@gmail.com
459dbc56b92f7ff2577c9cb5f334355ae336a4cb
c66ebc7ce29aced70d088729f10c54d547553d36
/ReflectiveObjectInspector/src/a2/InterfaceA.java
ac209faa72a0e461e955e0ad30cb70f5bd3db8d5
[]
no_license
CarolineZhou/ReflectiveObjectInspector
3f1f2fc1f88d06fa984c5115f39fd69a1b8efef4
259320c2147bd71f5a46e9a5f8041c7b0360a588
refs/heads/master
2020-04-26T21:09:35.897053
2019-03-07T23:15:33
2019-03-07T23:15:33
173,833,987
0
0
null
null
null
null
UTF-8
Java
false
false
245
java
package a2; public interface InterfaceA extends InterfaceB { public void func1(int a,double b,boolean c, String s) throws Exception; public int func2(String s)throws Exception, ArithmeticException , IllegalMonitorStateException ; }
[ "c_z.y@live.cn" ]
c_z.y@live.cn
2bd6198f5daf54e193116f0005292a891917820d
413f2a757238872cf091458b5e136afb8c14bce1
/src/ar/edu/ort/tp1/tp3Ejercicio03/Heladera.java
1eaa38822f21f5da5112355497ec08af435bd824
[]
no_license
LDibiase/TP1-TrabajoPractico3
f5812bf826172799a8d1476295351352a15774b1
feffd0f88a9f6468f9765ba5b316042073edb417
refs/heads/master
2022-12-27T00:35:02.778727
2020-10-12T05:23:24
2020-10-12T05:23:24
303,283,392
0
0
null
null
null
null
UTF-8
Java
false
false
1,018
java
package ar.edu.ort.tp1.tp3Ejercicio03; public class Heladera extends Electrodomestico { private float capacidad; private boolean esNoFrost; public Heladera(String marca, String modelo, int numeroDeSerie, int voltaje, boolean estado, float precio, float capacidad, boolean esNoFrost) { super(marca, modelo, numeroDeSerie, voltaje, estado, precio); this.capacidad = capacidad; this.esNoFrost = esNoFrost; } public float getCapacidad() { return capacidad; } public void setCapacidad(float capacidad) { this.capacidad = capacidad; } public boolean isEsNoFrost() { return esNoFrost; } public void setEsNoFrost(boolean esNoFrost) { this.esNoFrost = esNoFrost; } @Override public String mostrarProducto() { return "Heladera " + super.mostrarProducto() + " ]"; } @Override public String mostrarInfoYPrecio() { return "Heladera " + getMarca() + ", modelo " + getModelo() + (this.esNoFrost ? "no frost" : "") + ", capacidad " + this.capacidad + " litros: $" + this.getPrecio(); } }
[ "lucas.dibiase@mercadolibre.com" ]
lucas.dibiase@mercadolibre.com
22e6f3a3fac4a2dad0eda5564769133b35fb0868
74c1a633d9053d31845fd56f2d7478af85964a9f
/src/main/java/com/company/solution/Solution5352.java
aa965f8fc7e0f77118f0f7d99d988e5e06207e17
[]
no_license
ZengJinRong/learn
bb1d679a337000189b8e2a4ab59dd2c62c0bc88d
4cdb92d5082bcdcc3c4b460d80607cca39ab55ab
refs/heads/master
2023-02-05T03:53:27.196321
2020-12-30T02:19:21
2020-12-30T02:19:21
323,321,987
0
0
null
null
null
null
UTF-8
Java
false
false
570
java
package com.company.solution; /** * 5352. 生成每种字符都是奇数个的字符串 */ public class Solution5352 { public String generateTheString(int n) { StringBuilder stringBuilder = new StringBuilder(); if (n % 2 == 1) { for (int i = 0; i < n; i++) { stringBuilder.append('a'); } } else { for (int i = 0; i < n - 1; i++) { stringBuilder.append('a'); } stringBuilder.append('b'); } return stringBuilder.toString(); } }
[ "jinrong.zeng@outlook.com" ]
jinrong.zeng@outlook.com
0c1a2b4bdf29a4fcfafd3c796e72c5cd48ba6c51
61e76981aa12421a6cfd067e5526e8802ae92f1f
/app/src/main/java/com/cognet/ItemsListActivity.java
760e9de03a5d292fa5e6f85e4701332350546b0b
[]
no_license
namhoan/MIT-Cognet_MobileApplication_Android
68502f29f03919859988c9d6cdc4a4c1ae6351e0
f821ea3e52011793bb991f94dfba161bdd84a927
refs/heads/master
2021-01-10T06:56:02.590808
2016-01-08T18:06:20
2016-01-08T18:06:20
49,288,022
0
0
null
null
null
null
UTF-8
Java
false
false
13,015
java
package com.cognet; import android.app.ListActivity; import android.content.Context; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import android.view.View; import android.widget.AbsListView; import android.widget.AdapterView; import android.widget.ListView; import android.text.TextWatcher; import android.text.Editable; import android.widget.EditText; import android.view.LayoutInflater; import android.widget.SimpleAdapter; import android.widget.TextView; import android.util.Log; import com.cognet.httprequests.HttpRequests; public class ItemsListActivity extends ListActivity implements AbsListView.OnScrollListener { private SimpleAdapter adapter; private static final String JOURNALS_LIST_URL = "http://cognet-staging2.mit.edu/journal-list.xml"; private static final String BOOKS_LIST_URL = "http://cognet-staging2.mit.edu/books-clone-list.xml"; private static final String REFWORKS_LIST_URL = "http://cognet-staging2.mit.edu/eref-list.xml"; private MyTask task; private TextView footer; private int TOTAL_ITEMS; private int number = 1; private int currentlistItemIndex = 0; private final int MAX_ITEMS_PER_PAGE = 20; private boolean isloading = false; private TextView header; EditText searchtext; ListView listView; int textlength = 0; protected String cookie; protected String token; ArrayList<String> text_sort = new ArrayList<String>(); ArrayList<Integer> image_sort = new ArrayList<Integer>(); List<HashMap<String, String>> items = null; List<HashMap<String, String>> loadedItems = null; List<HashMap<String, String>> loadedItemsBackground = null; List<HashMap<String, String>> resultItems = null; // Keys used in Hashmap final String[] from = {"tlt", "aut", "pud"}; // Ids of views in listview_layout final int[] to = {R.id.text_tlt, R.id.text_aut, R.id.text_pud}; //System.out.println("text tlt id: "+ R.id); public void initializeItemsList(final ItemsListActivity listActivity) { // read local .xml //InputStream is = getResources().openRawResource(R.raw.books_list); // retrieve books list from server InputStream is = null; try { if (listActivity instanceof BooksListActivity) { is = HttpRequests.getInpuStream(BOOKS_LIST_URL); } else if (listActivity instanceof JournalsListActivity){ is = HttpRequests.getInpuStream(JOURNALS_LIST_URL); } else if (listActivity instanceof RefworksListActivity){ is = HttpRequests.getInpuStream(REFWORKS_LIST_URL); } System.out.println(is); } catch (IOException e) { e.printStackTrace(); } if (is != null) { XMLListDataExtractor extractor = null; if (listActivity instanceof BooksListActivity){ extractor = new BooksXMLListDataExtractor(is); } else if(listActivity instanceof JournalsListActivity){ extractor = new JournalsXMLListDataExtractor(is); } else if (listActivity instanceof RefworksListActivity){ extractor = new RefworksXMLListDataExtractor(is); } try { items = extractor.extract(); TOTAL_ITEMS = items.size(); is.close(); } catch (Exception e) { System.err.println("Exception while reading .xml file"); } } loadedItems = new ArrayList<HashMap<String, String>>(); resultItems = new ArrayList<HashMap<String, String>>(items); // Getting a reference to listview of list_listview.xml layout file header = (TextView) listActivity.findViewById(R.id.text_items_list_header); // Instantiating an adapter to store each items // R.layout.listview_layout defines the layout of each item runOnUiThread(new Runnable() { @Override public void run() { LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); footer = (TextView) inflater.inflate(R.layout.footer, null); listView = (ListView) listActivity.findViewById(android.R.id.list); listView.addFooterView(footer); adapter = new SimpleAdapter(getBaseContext(), loadedItems, R.layout.listview_layout, from, to); // Setting the adapter to the listView listView.setAdapter(adapter); listView.setOnScrollListener(listActivity); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { System.out.println("List position clicked: "+ position); HashMap<String, String> item = loadedItems.get(position); System.out.println("Starting description activity for " + item.get("id") + " (pos "+position+")"); Intent intent = new Intent("android.intent.action.BOOK_DESCR"); Bundle extras = new Bundle(); extras.putString("title", item.get("tlt")); extras.putString("author", item.get("aut")); extras.putString("pubDate", item.get("pud")); extras.putString("description", item.get("descr")); extras.putString("cookie", ItemsListActivity.this.cookie); extras.putString("token", ItemsListActivity.this.token); extras.putString("image", item.get("image")); intent.putExtras(extras); startActivity(intent); } }); } }); Log.d("initializeItemsList", "initializeItemsList is calling background task"); task = new MyTask(); task.execute(); searchtext = (EditText) listActivity.findViewById(R.id.edit_text_item_search); runOnUiThread(new Runnable() { public void run() { searchtext.clearFocus(); } }); searchtext.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void afterTextChanged(Editable s) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { /*if (s.length() < 3) { return; }*/ boolean inserted; textlength = searchtext.getText().length(); text_sort.clear(); image_sort.clear(); ArrayList<String> titles = new ArrayList<String>(); ArrayList<String> authors = new ArrayList<String>(); loadedItems = new ArrayList<HashMap<String, String>>(); resultItems = new ArrayList<HashMap<String, String>>(); currentlistItemIndex = 0; for (HashMap<String, String> item : items) { inserted = false; String title = item.get("tlt"); String author = item.get("aut"); String searchText = searchtext.getText() .toString(); // search for title if (textlength <= title.length()) { if (title.toLowerCase().indexOf (searchText.toLowerCase()) != -1) { resultItems.add(item); inserted = true; } } // for now Journals don't have author if (author != null) { // search for author if (textlength <= title.length() && !inserted) { if (author.toLowerCase().indexOf (searchText.toLowerCase()) != -1) { resultItems.add(item); } } } } TOTAL_ITEMS = resultItems.size(); System.out.println("New text: "+ s + ", Total items: " + TOTAL_ITEMS); runOnUiThread(new Runnable() { @Override public void run() { //listView.addFooterView(footer); listView.setOnScrollListener(listActivity); adapter = new SimpleAdapter(getBaseContext(), loadedItems, R.layout.listview_layout, from, to); listView.setAdapter(adapter); //adapter.notifyDataSetChanged(); //listView.requestLayout(); } }); if(task != null && (task.getStatus() == AsyncTask.Status.FINISHED)) { Log.d("onTextChanged", "onTextChanged is calling background task"); task = new MyTask(); task.execute(); } } }); } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { int loadedItems = firstVisibleItem + visibleItemCount; Log.d("onScroll", "loaded items: " + loadedItems + ", total item count: " + totalItemCount + ", visible item count: " + visibleItemCount); if((loadedItems == totalItemCount) && /*loadedItems < resultBooks.size() &&*/ !isloading ){ if(task != null && (task.getStatus() == AsyncTask.Status.FINISHED)){ Log.d("onScroll", "onScroll starts a background task, task status: "+task.getStatus()); task = new MyTask(); task.execute(); } } } @Override public void onScrollStateChanged(AbsListView view, int scrollState) { } class MyTask extends AsyncTask<Void, Void, Void> { @Override protected Void doInBackground(Void... params) { isloading = true; loadedItemsBackground = new ArrayList<HashMap<String, String>>(loadedItems); Log.d("doInBackground", "loaded books background: " + loadedItemsBackground.size() + " current Book Index: " + currentlistItemIndex); if (TOTAL_ITEMS > currentlistItemIndex) { for (int i = 1; i <= MAX_ITEMS_PER_PAGE && currentlistItemIndex< resultItems.size(); i++) { Log.d("doInBackground", "adding book from index " + currentlistItemIndex); loadedItemsBackground.add(resultItems.get(currentlistItemIndex)); currentlistItemIndex += 1; } Log.d("doInBackground", "DONE! loaded books background: " + loadedItemsBackground.size() + " current Book Index: " + currentlistItemIndex); } return null; } @Override protected void onPostExecute(Void result) { isloading = false; Log.d("onPostExecute", "loaded books background: " + loadedItemsBackground.size() + ", total books: " + TOTAL_ITEMS + ", adapter count: " + adapter.getCount()); runOnUiThread(new Runnable() { @Override public void run() { loadedItems.clear(); loadedItems.addAll(loadedItemsBackground); adapter.notifyDataSetChanged(); Log.d("onPostExecute", "loaded books background: " + loadedItemsBackground.size() + ", total books: " + TOTAL_ITEMS + ", adapter count: " + adapter.getCount()); if (adapter.getCount() == TOTAL_ITEMS) { header.setText("All " + adapter.getCount() + " Items are loaded."); listView.setOnScrollListener(null); listView.removeFooterView(footer); } else { header.setText("Loaded items - " + adapter.getCount() + " out of " + TOTAL_ITEMS); } } }); } } }
[ "namho8211@gmail.com" ]
namho8211@gmail.com
d78803a3a3c90a05bebfcbce3c1720da9dd5e6ea
5f63a60fd029b8a74d2b1b4bf6992f5e4c7b429b
/com/planet_ink/coffee_mud/Abilities/Spells/Spell_AcidSpray.java
432168dae5e7c9e1052c697e53f4fe2a1d7080c5
[ "Apache-2.0" ]
permissive
bozimmerman/CoffeeMud
5da8b5b98c25b70554ec9a2a8c0ef97f177dc041
647864922e07572b1f6c863de8f936982f553288
refs/heads/master
2023-09-04T09:17:12.656291
2023-09-02T00:30:19
2023-09-02T00:30:19
5,267,832
179
122
Apache-2.0
2023-04-30T11:09:14
2012-08-02T03:22:12
Java
UTF-8
Java
false
false
4,623
java
package com.planet_ink.coffee_mud.Abilities.Spells; import com.planet_ink.coffee_mud.core.interfaces.*; import com.planet_ink.coffee_mud.core.*; import com.planet_ink.coffee_mud.core.collections.*; import com.planet_ink.coffee_mud.Abilities.interfaces.*; import com.planet_ink.coffee_mud.Areas.interfaces.*; import com.planet_ink.coffee_mud.Behaviors.interfaces.*; import com.planet_ink.coffee_mud.CharClasses.interfaces.*; import com.planet_ink.coffee_mud.Commands.interfaces.*; import com.planet_ink.coffee_mud.Common.interfaces.*; import com.planet_ink.coffee_mud.Exits.interfaces.*; import com.planet_ink.coffee_mud.Items.interfaces.*; import com.planet_ink.coffee_mud.Libraries.interfaces.*; import com.planet_ink.coffee_mud.Locales.interfaces.*; import com.planet_ink.coffee_mud.MOBS.interfaces.*; import com.planet_ink.coffee_mud.Races.interfaces.*; import java.util.*; /* Copyright 2012-2023 Bo Zimmerman Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ public class Spell_AcidSpray extends Spell { @Override public String ID() { return "Spell_AcidSpray"; } private final static String localizedName = CMLib.lang().L("Acid Spray"); @Override public String name() { return localizedName; } private final static String localizedStaticDisplay = CMLib.lang().L("(Acid Spray)"); @Override public String displayText() { return localizedStaticDisplay; } @Override public int abstractQuality() { return Ability.QUALITY_MALICIOUS; } @Override protected int canAffectCode() { return CAN_MOBS; } @Override protected int canTargetCode() { return 0; } @Override public int maxRange() { return adjustedMaxInvokerRange(1); } @Override public int classificationCode() { return Ability.ACODE_SPELL|Ability.DOMAIN_CONJURATION; } @Override public long flags() { return Ability.FLAG_EARTHBASED; } @Override public boolean tick(final Tickable ticking, final int tickID) { if((tickID==Tickable.TICKID_MOB) &&(affected instanceof MOB)) { final MOB vic=(MOB)affected; if((!vic.amDead()) &&(vic.location()!=null)) { final MOB invoker=(invoker()!=null) ? invoker() : vic; CMLib.combat().postDamage(invoker,vic,this,CMLib.dice().roll(1,10+super.getXLEVELLevel(invoker())+(2*super.getX1Level(invoker())),0),CMMsg.MASK_ALWAYS|CMMsg.TYP_ACID,-1,L("<T-NAME> sizzle(s) from the acid!")); } } return super.tick(ticking,tickID); } @Override public boolean invoke(final MOB mob, final List<String> commands, final Physical givenTarget, final boolean auto, final int asLevel) { final MOB target=this.getTarget(mob,commands,givenTarget); if(target==null) return false; Room R=CMLib.map().roomLocation(target); if(R==null) R=mob.location(); if(!super.invoke(mob,commands,givenTarget,auto,asLevel)) return false; final boolean success=proficiencyCheck(mob,0,auto); if(success) { final CMMsg msg=CMClass.getMsg(mob,target,this,somanticCastCode(mob,target,auto),L(auto?"<T-NAME> <T-IS-ARE> sprayed with acid.":"^S<S-NAME> reach(es) for <T-NAMESELF>, spraying acid all over <T-HIM-HER>!^?")+CMLib.protocol().msp("spelldam1.wav",40)); final CMMsg msg2=CMClass.getMsg(mob,target,this,CMMsg.MSK_CAST_MALICIOUS_SOMANTIC|CMMsg.TYP_ACID|(auto?CMMsg.MASK_ALWAYS:0),null); if((R.okMessage(mob,msg))&&((R.okMessage(mob,msg2)))) { R.send(mob,msg); R.send(mob,msg2); invoker=mob; final int numDice = (adjustedLevel(mob,asLevel)+(2*super.getX1Level(invoker())))/2; int damage = CMLib.dice().roll(2, numDice, 1); if((msg2.value()>0)||(msg.value()>0)) damage = (int)Math.round(CMath.div(damage,2.0)); CMLib.combat().postDamage(mob,target,this,damage,CMMsg.MASK_ALWAYS|CMMsg.TYP_ACID,Weapon.TYPE_MELTING,L("The acid <DAMAGE> <T-NAME>!")); maliciousAffect(mob,target,asLevel,3,-1); } } else return maliciousFizzle(mob,target,L("<S-NAME> reach(es) for <T-NAMESELF>, but nothing more happens.")); return success; } }
[ "bo@zimmers.net" ]
bo@zimmers.net
01c8a4b318688d3e9369da6672a185fda0876fae
27aff37c36df4b70c958c16d18fe13ce43f25b0f
/src/main/java/glint/mvp/cache/VoteQueue.java
fb01c3d2eb437342ceedecc507fc51358ff9dee8
[]
no_license
ifwonderland/giants-mvp
894343766df4c0241d5912def2df88603e0e717e
036172aadbcc91c15167514cf3f83453c9f2148a
refs/heads/master
2021-01-01T17:43:37.762163
2014-11-25T18:35:38
2014-11-25T18:35:38
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,173
java
package glint.mvp.cache; import glint.mvp.model.Vote; import glint.mvp.util.Constants; import org.apache.log4j.Logger; import java.util.Iterator; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; /** * Singleton shared blocking queue where vote client puts vote in and server takes vote out and process it. * Created by ifwonderland on 11/16/14. */ public final class VoteQueue implements Cache<Vote, Vote> { private static BlockingQueue<Vote> voteQueue = null; private static Logger log = Logger.getLogger(VoteQueue.class); protected VoteQueue() { voteQueue = new ArrayBlockingQueue<Vote>(Constants.numVotes); } @Override public Vote get(Vote key) { Iterator<Vote> it = voteQueue.iterator(); while (it.hasNext()) { Vote vote = it.next(); if (vote.equals(key)) return vote; } return null; } @Override public void put(Vote key, Vote value) { try { enqueue(key); } catch (InterruptedException e) { log.error("Exception happened when trying to put vote into queue: "+key); } } @Override public Vote remove(Vote key) { boolean result = voteQueue.remove(key); return result?key:null; } @Override public Vote remove(){ try { return dequeue(); } catch (InterruptedException e) { log.error("dequeue throws exception. ",e); return null; } } @Override public void clear() { voteQueue = new ArrayBlockingQueue<Vote>(Constants.numVotes); } public static VoteQueue getInstance() { return (VoteQueue) CacheRepository.getInstance(VoteQueue.class.getName()); } private void enqueue(Vote vote) throws InterruptedException { log.debug("Vote " + vote + " enqueued into vote queue. "); voteQueue.put(vote); } private Vote dequeue() throws InterruptedException { Vote vote = voteQueue.take(); log.debug("Vote " + vote + " dequeued and to be processed. "); return vote; } }
[ "ifwonderland@gmail.com" ]
ifwonderland@gmail.com
f676d4b9dd8abaf9947ffac08008e04af138baaa
3dde2a8be3532651902232e185bdc086df301cef
/src/com/algorithms/trees/SecondMinimum.java
ca72bf04714a10d6d6f0b988d3bae6498fc4aada
[]
no_license
rahultaing/algorithms
e08e7dc7a36a33f7fc0b6258909f993a17da268c
6a98df95c0708ac277d3ff1014d35c362996b4e5
refs/heads/master
2021-06-02T19:13:08.158679
2021-03-13T21:16:59
2021-03-13T21:16:59
136,843,009
0
0
null
2018-07-13T16:35:43
2018-06-10T20:35:51
Java
UTF-8
Java
false
false
598
java
//https://leetcode.com/articles/second-minimum-node-in-a-binary-tree/ public class SecondMinimum{ private int min; private long ans = Long.MAX_VALUE; public int compute(TreeNode node){ min = node.val; dfs(node); return ans != Long.MAX_VALUE ? (int) ans : -1; } public void dfs(TreeNode node){ if (node!=null){ if (ans > node.val && min<node.val){ ans = node.val; } else if (min == node.val){ dfs(node.left); dfs(node.right); } } } }
[ "rahult@zillowgroup.com" ]
rahult@zillowgroup.com
5da14f50334f48e22b7e60f113c51e47c3c118b1
bcd75f379dd88361b5db85439d579c0d21d8b682
/server/src/main/java/service/ClearService.java
900105e7ed14c984246a1733dc6c785682c233f9
[]
no_license
jacobthewest/FamilyMapClient
ecbb88bb5cf2f43be89ce515f8aa3e327c797513
f068c7a0f45d3d464e028bf4cfe9f320ecd5013e
refs/heads/master
2021-03-27T22:40:51.742949
2020-04-09T08:02:35
2020-04-09T08:02:35
247,814,278
0
0
null
null
null
null
UTF-8
Java
false
false
989
java
package service; import dataAccess.Database; import dataAccess.DatabaseException; import result.ApiResult; import result.ClearResult; /** * Implements all methods needed to serve the API route <code>/clear</code> */ public class ClearService { /** * Deletes ALL data from the database, including user accounts, auth tokens, and * generated person, and event data. * @return the result of clearing the request */ public ClearResult clear() { try { Database db = new Database(); db.loadDriver(); db.openConnection(); // db.initializeTables(); db.emptyTables(); db.commitConnection(true); // Close db connection and return db.closeConnection(); return new ClearResult(); } catch(DatabaseException e) { return new ClearResult(ApiResult.INTERNAL_SERVER_ERROR,e.getMessage() + " Failure to clear database."); } } }
[ "jacobthewest@gmail.com" ]
jacobthewest@gmail.com
4041d077697d397c5992196a424954c6abe75793
4f2b0b0a6b1440c436fd6ef6bb49fcd8e1854905
/src/main/java/dao/sellerDao.java
b13b920f5d86eed482ebe85960d58b13eeddae0f
[]
no_license
dmc123456789/gm
ca7875d096de66a93410602bd730bcccaa811be8
384384862eca70d2e51a999b89c188ac0d89f7da
refs/heads/master
2020-04-14T16:07:57.129572
2019-01-04T06:40:25
2019-01-04T06:40:25
163,944,132
0
0
null
null
null
null
UTF-8
Java
false
false
375
java
package dao; import pojo.Announcement; import pojo.Page; import pojo.Seller; import java.util.List; public interface sellerDao { //查询全部及分页查询 List<Seller> goodsquery(String sql); Page<Seller> pageQuery(int pageSize, int pageNumber); //修改 //删除 Boolean goodsdel(int id); //添加 int goodsadd(String sql,Seller s); }
[ "2766927210@qq.com" ]
2766927210@qq.com
12cead7ee124c675d7b631bcaa713d0fea964a24
4dcdc6d31ba54e24ad88c64139fd31b4064a2a47
/src/main/java/com/cg/FileIOService.java
d06b6da693281bc2e87a42b931cf76ac0f826440
[]
no_license
krovel/EmployeePayroll
09f58a8ae7be516236eb36f9a8a199b418c28f63
ce240e408421fd204e3fef002e683706ebaae20d
refs/heads/main
2023-01-07T11:56:17.521428
2020-11-05T20:35:56
2020-11-05T20:35:56
310,027,201
0
0
null
2020-11-04T14:52:03
2020-11-04T14:30:52
Java
UTF-8
Java
false
false
1,666
java
package com.cg; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; public class FileIOService { public static final String PAYROLL_FILE_NAME = "employee-payroll-file.txt"; public void writeData(List<EmployeePayrollData> employeeList) { StringBuffer employeeBufferString = new StringBuffer(); employeeList.forEach(employee -> { String employeeDataString = employee.toString().concat("\n"); employeeBufferString.append(employeeDataString); }); try { Files.write(Paths.get(PAYROLL_FILE_NAME), employeeBufferString.toString().getBytes()); } catch (IOException e) { e.printStackTrace(); } } public long countEntries() { long countOfEntries = 0; try { countOfEntries = Files.lines(Paths.get(PAYROLL_FILE_NAME)).count(); } catch (IOException e) { } return countOfEntries; } public void printEmployeePayrolls() { try { Files.lines(Paths.get(PAYROLL_FILE_NAME)).forEach(System.out::println); } catch (IOException e) { } } public List<EmployeePayrollData> readData() { List<EmployeePayrollData> employeeReadList = new ArrayList<EmployeePayrollData>(); try { Files.lines(Paths.get(PAYROLL_FILE_NAME)).map(line -> line.trim()).forEach(line -> { String[] data = line.split("[ a-zA-Z]+ : "); int id = Character.getNumericValue(data[1].charAt(0)); String name = data[2]; double salary = Double.parseDouble(data[4]); EmployeePayrollData employeeobject = new EmployeePayrollData(id, name, salary); employeeReadList.add(employeeobject); }); } catch (IOException e) { } return employeeReadList; } }
[ "krove@DESKTOP-Q5SED1R" ]
krove@DESKTOP-Q5SED1R
78c5a58fe8fc33dca758bc639ba85a3e4b2fb358
4f61d0b70c7a9a997fc0fa024993e2f13babfc4b
/src/serv/BD/servBDInstanceFightIns.java
e072e76ee5fbfd2663c9c038f256eee4c8d0939b
[]
no_license
lechuandafo/yys
1c9f43f6f9369e33eb0f50ded5d2d93f2978216f
0a56cc56c5dfa76ad10627283ee534fc188a3524
refs/heads/master
2022-07-30T21:35:45.013384
2020-05-20T07:56:50
2020-05-20T07:56:50
265,457,659
0
0
null
null
null
null
UTF-8
Java
false
false
3,255
java
package serv.BD; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import vo.BD.voBDInstanceFight; import dao.BD.daoBDInstanceFight; public class servBDInstanceFightIns extends HttpServlet { /** * Constructor of the object. */ public servBDInstanceFightIns() { super(); } /** * Destruction of the servlet. <br> */ public void destroy() { super.destroy(); // Just puts "destroy" string in log // Put your code here } /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">"); out.println("<HTML>"); out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>"); out.println(" <BODY>"); out.print(" This is "); out.print(this.getClass()); out.println(", using the GET method"); out.println(" </BODY>"); out.println("</HTML>"); out.flush(); out.close(); } /** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); String InstanceNo = request.getParameter("instanceNo").trim(); int RoundTime = Integer.valueOf(request.getParameter("roundTime").trim()); String SGroupNo = request.getParameter("sGroupNo").trim(); String MapNo = request.getParameter("mapNo").trim(); voBDInstanceFight voInstanceFight = new voBDInstanceFight(); daoBDInstanceFight daoInstanceFight = new daoBDInstanceFight(); voInstanceFight.setInstanceNo(InstanceNo); voInstanceFight.setRoundTime(RoundTime); voInstanceFight.setSGroupNo(SGroupNo); voInstanceFight.setMapNo(MapNo); boolean flag = daoInstanceFight.insInstanceFight(voInstanceFight); if (flag==false){ out.print("<script>location.href='../../Manage/instanceFight.jsp';" + "alert('insert fail!');</script>"); }else{ out.print("<script>location.href='../../Manage/instanceFight.jsp';</script>"); } } /** * Initialization of the servlet. <br> * * @throws ServletException if an error occurs */ public void init() throws ServletException { // Put your code here } }
[ "1216132190@qq.com" ]
1216132190@qq.com
09c38984dce8aabf2ccab5bf3e288f2289aab950
707d2e73d8e9adbc177b72aa2897c825a86f2ee2
/org.correttouml.uml/src/org/correttouml/uml/diagrams/statediagram/Guard.java
54f55e01c277b666047c2f1f8946ff5df0248a02
[]
no_license
deib-polimi/Corretto
e8ff90f7ee6f9b8b465deb1d4d42108a0249641e
62b75a10e0128956cd2fecdff6d74055a507fad5
refs/heads/master
2021-01-18T22:52:19.176149
2017-01-16T14:22:37
2017-01-16T14:22:37
30,644,630
2
2
null
null
null
null
UTF-8
Java
false
false
850
java
package org.correttouml.uml.diagrams.statediagram; import org.correttouml.uml.helpers.BooleanExpressionsParser; public class Guard { private String uml_guard; private org.eclipse.uml2.uml.Transition uml_transition; public Guard(String guard, org.eclipse.uml2.uml.Transition t) { this.uml_guard=guard; this.uml_transition=t; } public org.correttouml.grammars.booleanExpressions.Model getBooleanExpression() { return BooleanExpressionsParser.parse(this.uml_guard); } public String getUMLGuard(){ return uml_guard; } public Transition getTransition() { return new Transition(this.uml_transition); } @Override public boolean equals(java.lang.Object o){ Guard other_guard=(Guard) o; return this.uml_guard.equals(other_guard.uml_guard); } @Override public int hashCode(){ return this.uml_guard.hashCode(); } }
[ "mmpourhashem@gmail.com" ]
mmpourhashem@gmail.com
1781ce04777ffa67b439c2a88e01a90b4897cc64
c911a6a1dc56d30f870a9b8e1fdcedd9b4329ecc
/app/src/main/java/xj/property/activity/repair/ValueSheetActivity.java
48469252002764987d3ff52e82bdcdef243d4597
[ "Apache-2.0" ]
permissive
samuelhehe/Property
a87022ef5d082cb6d87ef8f4043ce4222f4035a9
67b8214cd86bab963908fd066d163c783ddb9e18
refs/heads/master
2021-01-13T07:40:46.269767
2016-12-12T09:10:10
2016-12-12T09:10:10
76,239,989
1
0
null
null
null
null
UTF-8
Java
false
false
4,625
java
package xj.property.activity.repair; import android.os.Bundle; import android.view.View; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; import java.util.HashMap; import java.util.List; import java.util.Map; import retrofit.Callback; import retrofit.RetrofitError; import retrofit.http.GET; import retrofit.http.Path; import retrofit.http.QueryMap; import xj.property.R; import xj.property.activity.HXBaseActivity.HXBaseActivity; import xj.property.adapter.XJBaseAdapter; import xj.property.beans.ValueSheetBean; import xj.property.beans.ValueSheetV3Bean; import xj.property.netbase.CommonRespBean; import xj.property.netbase.RetrofitFactory; import xj.property.utils.other.PreferencesUtil; /** * Created by Administrator on 2015/3/20. */ public class ValueSheetActivity extends HXBaseActivity { ListView lv_tools; LinearLayout ll_item; XJBaseAdapter adapter; List<ValueSheetV3Bean> bean; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_valuesheet); ll_item= (LinearLayout) findViewById(R.id.ll_item); lv_tools=(ListView)findViewById(R.id.lv_tools); getValueSheetList(); initTitle(null,"报价表",""); } interface ValueSheetService { ///api/v1/communities/{communityId}/shops/quotation @GET("/api/v1/communities/{communityId}/shops/quotation") void getValueSheet(@Path("communityId") long communityId, Callback<ValueSheetBean> cb); @GET("/api/v3/repairs/items") void getValueSheetV3(@QueryMap Map<String, String> map, Callback<CommonRespBean<List<ValueSheetV3Bean>>> cb); } private void initItem(){ for(int i=0;i<bean.size();i++) { View view=(LinearLayout)View.inflate(this,R.layout.item_sheet,null); TextView tv_left=(TextView)view.findViewById(R.id.tv_left); ll_item.addView(view); final int position=i; tv_left.setText(bean.get(i).getCatName()); tv_left.setTextColor(getResources().getColor(R.color.sheet_text_normal)); tv_left.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { adapter.changeData(bean.get(position).getItems()); for(int i=0;i<ll_item.getChildCount();i++){ // ll_item.getChildAt(i).setBackgroundColor(getResources().getColor(R.color.sheet_normal)); // ((TextView)ll_item.getChildAt(i)).setTextColor(getResources().getColor(R.color.sheet_text_normal)); ((LinearLayout)ll_item.getChildAt(i)).getChildAt(0).setBackgroundColor(getResources().getColor(R.color.sheet_normal)); ((TextView)v).setTextColor(getResources().getColor(R.color.sheet_text_normal)); } v.setBackgroundColor(getResources().getColor(R.color.white)); ((TextView)v).setTextColor(getResources().getColor(R.color.sheet_text_pressed)); } }); if(i==0)tv_left.setBackgroundColor(getResources().getColor(R.color.white)); } } private void getValueSheetList() { HashMap<String,String> map = new HashMap<String,String>(); map.put("communityId",PreferencesUtil.getCommityId(this)+""); ValueSheetService service = RetrofitFactory.getInstance().create(getmContext(), map, ValueSheetService.class); Callback<CommonRespBean<List<ValueSheetV3Bean>>> callback = new Callback<CommonRespBean<List<ValueSheetV3Bean>>>() { @Override public void success(CommonRespBean<List<ValueSheetV3Bean>> commonRespBean, retrofit.client.Response response) { if(commonRespBean!=null&&commonRespBean.getData()!=null) { bean = commonRespBean.getData(); initItem(); adapter = new XJBaseAdapter(ValueSheetActivity.this, R.layout.item_tools, bean.get(0).getItems(), new String[]{"serviceName", "price"}); lv_tools.setAdapter(adapter); } } @Override public void failure(RetrofitError error) { error.printStackTrace(); showNetErrorToast(); } }; service.getValueSheetV3(map, callback); } }
[ "wangshengxi@greencheng.com" ]
wangshengxi@greencheng.com
64744f6fc1cc837bd25a4b3324ed31c02959e50d
2b8cdd96826a4d5fa252c54b4ad6f9a021a6e6d7
/src/main/java/com/homk/project/tool/gen/util/VelocityInitializer.java
ecb8f60085a6fafa3120b136d09a13f9b66c1d72
[]
no_license
mengyangxu/Homk
dc4a7990a185f45b37846b2f03269baee7b1ebaf
370ea65010c8a48a2777f282af73645ad25170fb
refs/heads/master
2020-04-05T07:44:02.120406
2018-11-12T02:13:13
2018-11-12T02:13:13
156,686,600
0
0
null
null
null
null
UTF-8
Java
false
false
944
java
package com.homk.project.tool.gen.util; import com.homk.common.constant.Constants; import org.apache.velocity.app.Velocity; import java.util.Properties; /** * VelocityEngine工厂 * * @author RuoYi */ public class VelocityInitializer { /** * 初始化vm方法 */ public static void initVelocity() { Properties p = new Properties(); try { // 加载classpath目录下的vm文件 p.setProperty("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); // 定义字符集 p.setProperty(Velocity.ENCODING_DEFAULT, Constants.UTF8); p.setProperty(Velocity.OUTPUT_ENCODING, Constants.UTF8); // 初始化Velocity引擎,指定配置Properties Velocity.init(p); } catch (Exception e) { throw new RuntimeException(e); } } }
[ "xumengyang@datatang.com" ]
xumengyang@datatang.com
9f21ff71cfd69d0f913afc84f09f4ed0179e8623
71d9c30d132929551c87ebcb454d67d43e398783
/src/main/java/com/crawler/Crawler.java
41dde35d135cfa37250428739a1008aa401dabed
[]
no_license
icccool/java-demo
081526bbcd3f15ed85065a90b0ed904b527cf6e7
ababd56d98b45d1a51fe609c20b2fc2d1e2adc52
refs/heads/master
2022-12-22T11:36:42.412094
2019-09-25T00:58:07
2019-09-25T00:58:07
130,784,495
0
0
null
2022-12-16T03:56:38
2018-04-24T02:26:46
Java
UTF-8
Java
false
false
902
java
package com.crawler; import org.jsoup.Connection; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import java.io.IOException; import java.net.InetSocketAddress; import java.net.Proxy; public class Crawler { public static void main(String[] args) { String urlStr = "http://www.tumblr.com"; Document document = getDocByUrl(urlStr); System.out.println(document.toString()); } /** * 获取链接,并且处理异常 * * @param url 待获取的链接 * @return */ public static Document getDocByUrl(String url) { Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 1087)); Connection connection = Jsoup.connect(url).proxy(proxy); try { return connection.get(); } catch (IOException e) { e.printStackTrace(); } return null; } }
[ "wlish.ml@gmail.com" ]
wlish.ml@gmail.com
d2dfc830fc9806a4556cb6eb4282044794905080
e3e29bf28e0a04c5823c2b84418d1cabf3256789
/target/m2e-wtp/overlays/vaadin-6.8.2.jar/com/vaadin/terminal/gwt/client/ui/dd/VAnd.java
9905f04872316d2c3b0b53bc70d54e6542715d55
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
manishgaurav08/webportal
3beafc6efee03844c8d87e4679ac599fda0a8a88
0227910598b6fb2ee31083204beb9063db3bcc0d
refs/heads/master
2020-06-06T23:08:07.666238
2015-09-15T08:51:12
2015-09-15T08:51:12
42,067,797
0
0
null
null
null
null
UTF-8
Java
false
false
1,564
java
/* * Copyright 2011 Vaadin Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ /** * */ package com.vaadin.terminal.gwt.client.ui.dd; import com.vaadin.terminal.gwt.client.UIDL; final public class VAnd extends VAcceptCriterion implements VAcceptCallback { private boolean b1; static VAcceptCriterion getCriteria(VDragEvent drag, UIDL configuration, int i) { UIDL childUIDL = configuration.getChildUIDL(i); return VAcceptCriteria.get(childUIDL.getStringAttribute("name")); } @Override protected boolean accept(VDragEvent drag, UIDL configuration) { int childCount = configuration.getChildCount(); for (int i = 0; i < childCount; i++) { VAcceptCriterion crit = getCriteria(drag, configuration, i); b1 = false; crit.accept(drag, configuration.getChildUIDL(i), this); if (!b1) { return false; } } return true; } public void accepted(VDragEvent event) { b1 = true; } }
[ "manishgaurav08@gmail.com" ]
manishgaurav08@gmail.com
3314ed255487b17e621a8ff9b5195072ff719365
739d085abd9f285c44aeb360a044cac94c543241
/src/main/java/me/activated/core/commands/essentials/staff/MassayCommand.java
a7754d8aa0c34d906d883837529e7c04b81a5170
[]
no_license
RenCas3258/AquaCore
0c1591c9827fb2a4bb7869cbd712e527140db7d0
576596b5b1f9b854b72cab7a4d2ec9a87e4b97cb
refs/heads/master
2023-04-15T21:45:37.229415
2021-04-30T01:46:55
2021-04-30T01:46:55
362,994,798
3
0
null
null
null
null
UTF-8
Java
false
false
1,120
java
package me.activated.core.commands.essentials.staff; import me.activated.core.enums.Language; import me.activated.core.utilities.Utilities; import me.activated.core.utilities.chat.Color; import me.activated.core.utilities.command.BaseCommand; import me.activated.core.utilities.command.Command; import me.activated.core.utilities.command.CommandArgs; import me.activated.core.utilities.general.StringUtils; import org.bukkit.entity.Player; public class MassayCommand extends BaseCommand { @Command(name = "massay", permission = "aqua.command.massay") public void onCommand(CommandArgs command) { Player player = command.getPlayer(); String[] args = command.getArgs(); if (args.length == 0) { player.sendMessage(Color.translate("&cCorrect usage: /massay <message>")); return; } Utilities.getOnlinePlayers().forEach(online -> { online.chat(StringUtils.buildMessage(args, 0)); }); player.sendMessage(Language.MASSAY_SUCCESS.toString() .replace("<message>", StringUtils.buildMessage(args, 0))); } }
[ "renas321@gmail.com" ]
renas321@gmail.com
045fe734db0fcc863be07c0897e6eddee69cde27
9cf029213d31147e3550d3b7053ec3abbdc7151d
/IACNAWebServer/src/main/java/com/cplsys/iacna/domain/Producto.java
f4b81ede6f951a9b163146e23e7046df5641cf09
[]
no_license
ca4los-palalia/14CN4
81b9ca434d79bf6311e91308aa0b3b463d519984
dec1b4d0748628dfcd6725c1bfd35aa6afd0cdb6
refs/heads/master
2016-08-11T19:02:18.858750
2016-03-22T14:45:51
2016-03-22T14:45:51
54,481,838
0
0
null
null
null
null
UTF-8
Java
false
false
1,645
java
package com.cplsys.iacna.domain; import java.io.Serializable; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.persistence.Version; @Entity @Table public class Producto implements Serializable { private static final long serialVersionUID = 4416294258351232746L; private String nombre; private Integer idProducto; private List<Formula> formulas = new ArrayList<Formula>(); private Calendar fechaModificacion; public Producto() { } @Column(name = "nombre") public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "idProducto") public Integer getIdProducto() { return idProducto; } public void setIdProducto(Integer idProducto) { this.idProducto = idProducto; } /* @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "producto") public Set<Formula> getFormulas() { return formulas; } public void setFormulas(Set<Formula> formulas) { this.formulas = formulas; }*/ @Column(name = "fechaModificacion") @Temporal(TemporalType.TIMESTAMP) @Version public Calendar getFechaModificacion() { return fechaModificacion; } public void setFechaModificacion(Calendar fechaModificacion) { this.fechaModificacion = fechaModificacion; } }
[ "carlos.palalia@gmail.com" ]
carlos.palalia@gmail.com
787a28f142846c27f7f6ba412eb4d7cea0797450
eb9a97ec5ebc444985b89a532794fabc8812930b
/app/src/main/java/cn/ommiao/autotask/entity/ExecuteResultData.java
eceb6d19c101c687c9695f2814eec51fc4a3cf85
[]
no_license
ommiao/AutoTask
539cd1c26765f79c6d3dcb8d0fcf2b4f1e56661b
9dbe0a5c5ece5ad5c783d4c000cd7b8de56f1b6a
refs/heads/master
2020-07-06T22:01:56.774120
2019-11-13T03:31:33
2019-11-13T03:31:33
203,150,384
0
0
null
null
null
null
UTF-8
Java
false
false
1,440
java
package cn.ommiao.autotask.entity; import androidx.annotation.NonNull; import androidx.room.Entity; import cn.ommiao.base.entity.JavaBean; @Entity(primaryKeys = {"taskId", "startTime"}) public class ExecuteResultData extends JavaBean { @NonNull private String taskId = "ommiao"; private String taskName; private boolean success; @NonNull private String startTime = "no time"; private String endTime; private String errorReason; @NonNull public String getTaskId() { return taskId; } public void setTaskId(@NonNull String taskId) { this.taskId = taskId; } public String getTaskName() { return taskName; } public void setTaskName(String taskName) { this.taskName = taskName; } public boolean isSuccess() { return success; } public void setSuccess(boolean success) { this.success = success; } @NonNull public String getStartTime() { return startTime; } public void setStartTime(@NonNull String startTime) { this.startTime = startTime; } public String getEndTime() { return endTime; } public void setEndTime(String endTime) { this.endTime = endTime; } public String getErrorReason() { return errorReason; } public void setErrorReason(String errorReason) { this.errorReason = errorReason; } }
[ "ommiao@foxmail.com" ]
ommiao@foxmail.com
adbbf228c198d19fcd2a1940c5013f6789bb5e02
6ddcefecb11b729c137277977d1392f713023ccf
/src/com/example/filetest1/MainActivity.java
acbd7a97c3b73ca8a7ee7b82961a9f74e61ce033
[]
no_license
luwang66/FileTest1
17a9f842ade4f7237b610549d52148413c192a53
678615494b2520e856d3ebee30b4ed931b2c0924
refs/heads/master
2021-01-12T11:44:32.594154
2016-10-29T13:22:39
2016-10-29T13:22:39
72,286,093
0
0
null
null
null
null
GB18030
Java
false
false
2,423
java
package com.example.filetest1; import java.io.File; import java.io.FileInputStream; import java.io.RandomAccessFile; import android.os.Bundle; import android.os.Environment; import android.app.Activity; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; public class MainActivity extends Activity { private Button read, write; private EditText readText, writeText; private String fileName = "content.txt"; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); read = (Button) findViewById(R.id.read); write = (Button) findViewById(R.id.write); readText = (EditText) findViewById(R.id.readText); writeText = (EditText) findViewById(R.id.writeText); read.setOnClickListener(new OnClickListener() { public void onClick(View v) { readText.setText(read()); } }); write.setOnClickListener(new OnClickListener() { public void onClick(View v) { write(writeText.getText().toString()); } }); } public void write(String content) { try { if (Environment.getExternalStorageState().equals( Environment.MEDIA_MOUNTED)) { File sdCardDir = Environment.getExternalStorageDirectory(); File destFile = new File(sdCardDir.getCanonicalPath() + File.separator + fileName); System.out.println("*********"+destFile.getAbsolutePath()); RandomAccessFile raf = new RandomAccessFile(destFile, "rw"); raf.seek(destFile.length()); raf.write(content.getBytes()); raf.close(); } } catch (Exception e) { e.printStackTrace(); } } public String read() { StringBuilder sbBuilder = new StringBuilder(""); try { //判断手机中是否存在可用的SD卡 if(Environment.getExternalStorageState(). equals(Environment.MEDIA_MOUNTED)){ File sdCard=Environment.getExternalStorageDirectory(); File destFile = new File(sdCard.getCanonicalPath() + File.separator + fileName); FileInputStream fis=new FileInputStream(destFile); byte[] buffer = new byte[64]; int hasRead; while ((hasRead = fis.read(buffer)) != -1) { sbBuilder.append(new String(buffer, 0, hasRead)); } return sbBuilder.toString(); } } catch (Exception e) { e.printStackTrace(); } return null; } }
[ "635819835@qq.com" ]
635819835@qq.com
2d03d5dea300314b77fbec1688f57e1aed75000e
34b8ae5562e3d51857f2d4d78ecb178e44cc463a
/app/src/main/java/com/example/vishnubk/sharjahcharity/ui/DetailPageActivity.java
1135b25e15d86a0825e0bd02cd44c20b5d7e0862
[]
no_license
vbk6/SharjahCharity
97a945a39caff77a9ef42edcbf86ae9db38c102e
4607f2f067d109ed87f8fb9ac2eed96abc0aaafc
refs/heads/master
2021-01-12T07:16:25.848129
2017-03-13T11:14:15
2017-03-13T11:14:15
76,929,654
0
0
null
null
null
null
UTF-8
Java
false
false
1,933
java
package com.example.vishnubk.sharjahcharity.ui; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.example.vishnubk.sharjahcharity.R; public class DetailPageActivity extends AppCompatActivity { TextView title; ImageView imageView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_detail_page); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); toolbar.setNavigationIcon(R.drawable.ic_arrow_back); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { DetailPageActivity.super.onBackPressed(); } }); imageView=(ImageView)findViewById(R.id.imageThumbnail); String content=getIntent().getStringExtra("title"); // Uri imageUri = (Uri) getIntent().getParcelableExtra("image"); byte[] byteArray = getIntent().getByteArrayExtra("image"); Bitmap bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length); this.setTitle(content); imageView.setImageBitmap(bmp); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fabDonate); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(DetailPageActivity.this, DonatorDetailActivity.class); startActivity(intent); } }); } }
[ "vishnubk693@gmail.com" ]
vishnubk693@gmail.com
4bbfa029c83c1ee50f2521b4de6cd72d16a0f542
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/4/4_383bfa0f5ffe40d39820927c63a0685fc5c697fb/BasicLogger/4_383bfa0f5ffe40d39820927c63a0685fc5c697fb_BasicLogger_s.java
e60190a4ead65f9cf7c4d0f6bedae6656ff08cbc
[]
no_license
zhongxingyu/Seer
48e7e5197624d7afa94d23f849f8ea2075bcaec0
c11a3109fdfca9be337e509ecb2c085b60076213
refs/heads/master
2023-07-06T12:48:55.516692
2023-06-22T07:55:56
2023-06-22T07:55:56
259,613,157
6
2
null
2023-06-22T07:55:57
2020-04-28T11:07:49
null
UTF-8
Java
false
false
3,837
java
package com.rimproject.andsensor; import java.util.Calendar; import java.util.Timer; import java.util.TimerTask; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; /* Example of how this class and its timer's will work: * * Timer 1 -> 10 seconds has passed * Timer 2 created -> let me know when 3 seconds has passed * Sensor recording start * 10:55:10 v:11 * 10:55:10 v:12 * 10:55:11 v:11 * 10:55:11 v:10 * 10:55:12 v:15 * 10:55:12 v:16 * 10:55:13 v:11 * Timer 2 -> 3 seconds has passed * sensor recording stop * * Timer 1 -> 10 seconds has passed * Timer 2 created -> let me know when 3 seconds has passed * Sensor recording start * 10:55:20 v:11 * 10:55:20 v:12 * 10:55:21 v:11 * 10:55:21 v:10 * 10:55:22 v:15 * 10:55:22 v:16 * 10:55:23 v:11 * Timer 2 -> 3 seconds has passed * sensor recording stop * etc. */ public abstract class BasicLogger extends TimerTask implements LoggerInterface, SensorEventListener { private Timer delayBetweenLoggingTimer; // Timer 1 private long delayBetweenLogging; private long loggingDuration; private DataLogger dataLogger; protected SensorManager sensorManager; protected Sensor sensor; public BasicLogger() { super(); this.delayBetweenLogging = 60 * 1000; this.loggingDuration = 10 * 1000; } public void initiateRepeatedLogging() { System.out.println(this+" : "+Calendar.getInstance().getTime()+" @ Logging Initiated"); this.delayBetweenLoggingTimer = new Timer(); this.delayBetweenLoggingTimer.scheduleAtFixedRate(this, 0, this.delayBetweenLogging); //0 == triggers immediately } public void terminateRepeatedLogging(boolean immidiate) { this.delayBetweenLoggingTimer.cancel(); if (immidiate) { this.dataLogger.run(); } System.out.println(this+" : "+Calendar.getInstance().getTime()+" @ Logging Terminated"); } protected void startLogging() { System.out.println(this+" : "+Calendar.getInstance().getTime()+" @ Logging Started"); } protected void stopLogging() { System.out.println(this+" : "+Calendar.getInstance().getTime()+" @ Logging Stopped"); } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { System.out.println(this+" : "+"onAccuracyChanged: " + sensor + ", accuracy: " + accuracy); } @Override public void onSensorChanged(SensorEvent event) { System.out.println(this+" : "+"onSensorChanged: " + event); } class DataLogger extends TimerTask { private BasicLogger logger; private Timer loggingDurationTimer; // Timer 2 public DataLogger(BasicLogger logger) { this.logger = logger; this.loggingDurationTimer = new Timer(); this.loggingDurationTimer.scheduleAtFixedRate(this, loggingDuration, loggingDuration); this.logger.startLogging(); } public void run() { this.logger.stopLogging(); //stop the timer as we don't want timer 2 to repeat this.loggingDurationTimer.cancel(); } } public long getDelayBetweenLogging() { return delayBetweenLogging; } public void setDelayBetweenLogging(long delayBetweenLogging) { this.delayBetweenLogging = delayBetweenLogging; } public long getLoggingDuration() { return loggingDuration; } public void setLoggingDuration(long loggingDuration) { this.loggingDuration = loggingDuration; } @Override public void run() { //timer 1 System.out.println(this+" : "+Calendar.getInstance().getTime()+" @ Trigger Logging"); this.dataLogger = new DataLogger(this); } public String toString() { return this.getClass().getSimpleName(); } }
[ "yuzhongxing88@gmail.com" ]
yuzhongxing88@gmail.com
687a4933a6fab05df5bc503c6a519b320d4d4b2d
6e8e213290ead44719713752e05eb62c6f696bd9
/src/main/java/p455w0rd/morphtweaks/blocks/tiles/TileVoidifier.java
9ba4fb068dcaffe39abc9add8e3e153c92d13181
[ "MIT" ]
permissive
p455w0rd/MorphTweaks
0b69499c4d174ec8eab44fc7d814985573f4d3bb
465cf0ac435fdbe437e1866dc5d8b8c82143ef4c
refs/heads/master
2018-11-23T21:19:31.114952
2018-09-04T15:43:24
2018-09-04T15:43:24
116,668,183
0
1
null
null
null
null
UTF-8
Java
false
false
4,214
java
package p455w0rd.morphtweaks.blocks.tiles; import javax.annotation.Nullable; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.network.NetworkManager; import net.minecraft.network.play.server.SPacketUpdateTileEntity; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.EnumFacing; import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.energy.CapabilityEnergy; import net.minecraftforge.energy.EnergyStorage; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.capability.CapabilityFluidHandler; import net.minecraftforge.fluids.capability.FluidTankProperties; import net.minecraftforge.fluids.capability.IFluidHandler; import net.minecraftforge.fluids.capability.IFluidTankProperties; import net.minecraftforge.items.CapabilityItemHandler; import net.minecraftforge.items.ItemStackHandler; /** * @author p455w0rd * */ public class TileVoidifier extends TileEntity { public IFluidHandler invFluid = new IFluidHandler() { @Override public IFluidTankProperties[] getTankProperties() { return new IFluidTankProperties[] { new FluidTankProperties(null, Integer.MAX_VALUE, true, false), new FluidTankProperties(null, Integer.MAX_VALUE, true, false), new FluidTankProperties(null, Integer.MAX_VALUE, true, false), new FluidTankProperties(null, Integer.MAX_VALUE, true, false), new FluidTankProperties(null, Integer.MAX_VALUE, true, false), new FluidTankProperties(null, Integer.MAX_VALUE, true, false), new FluidTankProperties(null, Integer.MAX_VALUE, true, false) }; } @Override public int fill(FluidStack fluid, boolean doFill) { return fluid != null ? fluid.amount : 0; } @Override @Nullable public FluidStack drain(FluidStack fluid, boolean doDrain) { return null; } @Override @Nullable public FluidStack drain(int maxDrain, boolean doDrain) { return null; } }; public ItemStackHandler invItem = new ItemStackHandler(27) { @Override public void setStackInSlot(int slot, ItemStack stack) { } @Override public ItemStack getStackInSlot(int slot) { return ItemStack.EMPTY; } @Override public ItemStack insertItem(int slot, ItemStack stack, boolean simulate) { return ItemStack.EMPTY; } @Override public ItemStack extractItem(int slot, int amount, boolean simulate) { return ItemStack.EMPTY; } }; public EnergyStorage storageFE = new EnergyStorage(Integer.MAX_VALUE) { @Override public int receiveEnergy(int maxReceive, boolean simulate) { return maxReceive; } @Override public int extractEnergy(int maxExtract, boolean simulate) { return 0; } @Override public int getEnergyStored() { return 0; } @Override public int getMaxEnergyStored() { return capacity; } @Override public boolean canExtract() { return false; } @Override public boolean canReceive() { return true; } }; @Override public boolean hasCapability(Capability<?> capability, EnumFacing facing) { return capability == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY || capability == CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY || capability == CapabilityEnergy.ENERGY || super.hasCapability(capability, facing); } @Override public <T> T getCapability(Capability<T> capability, EnumFacing facing) { if (capability == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY) { return CapabilityItemHandler.ITEM_HANDLER_CAPABILITY.cast(invItem); } else if (capability == CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY) { return CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY.cast(invFluid); } else if (capability == CapabilityEnergy.ENERGY) { return CapabilityEnergy.ENERGY.cast(storageFE); } return super.getCapability(capability, facing); } @Override public NBTTagCompound getUpdateTag() { return writeToNBT(new NBTTagCompound()); } @Override @Nullable public SPacketUpdateTileEntity getUpdatePacket() { return new SPacketUpdateTileEntity(getPos(), 0, getUpdateTag()); } @Override public void onDataPacket(NetworkManager net, SPacketUpdateTileEntity pkt) { readFromNBT(pkt.getNbtCompound()); } }
[ "p455w0rd@gmail.com" ]
p455w0rd@gmail.com
bd2ac8a3c1e6b98bd076fce74607bc825ff8d554
b19674396d9a96c7fd7abdcfa423fe9fea4bb5be
/ratis-proto-shaded/src/main/java/org/apache/ratis/shaded/io/netty/buffer/WrappedUnpooledUnsafeDirectByteBuf.java
2c8488931365d12ce4c987f0da3b6b5b8f1962d2
[]
no_license
snemuri/ratis.github.io
0529ceed6f86ad916fbc559576b39ae123c465a0
85e1dd1890477d4069052358ed0b163c3e23db76
refs/heads/master
2020-03-24T07:18:03.130700
2018-07-27T13:29:06
2018-07-27T13:29:06
142,558,496
0
0
null
null
null
null
UTF-8
Java
false
false
1,207
java
/* * Copyright 2016 The Netty Project * * The Netty Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.apache.ratis.shaded.io.netty.buffer; import org.apache.ratis.shaded.io.netty.util.internal.PlatformDependent; import java.nio.ByteBuffer; final class WrappedUnpooledUnsafeDirectByteBuf extends UnpooledUnsafeDirectByteBuf { WrappedUnpooledUnsafeDirectByteBuf(ByteBufAllocator alloc, long memoryAddress, int size, boolean doFree) { super(alloc, PlatformDependent.directBuffer(memoryAddress, size), size, doFree); } @Override protected void freeDirect(ByteBuffer buffer) { PlatformDependent.freeMemory(memoryAddress); } }
[ "snemuri@hortonworks.com" ]
snemuri@hortonworks.com
6d64a3eb3cd401466ed801d264990e3c5e300373
a9829ea77376836b2cab9c430f43e4feceb3dbf3
/src/devhire/linkedlists/FloydAlgorithm.java
1dcf200bb10a173da15edd8cfd6d21af809cc9da
[]
no_license
devhire-2021-2/LinkedLists
791202c651d0ed89288da799170470fee80a7d1a
69a580c7dd855018f063e2b08128d1fc66112171
refs/heads/master
2023-08-08T01:03:33.107428
2021-09-13T20:23:00
2021-09-13T20:23:00
406,115,252
0
0
null
null
null
null
UTF-8
Java
false
false
1,676
java
package devhire.linkedlists; import java.util.Scanner; public class FloydAlgorithm { public static Node<?> detect(LinkedList<?> l){ var fast = l.head; var slow = l.head; while(fast !=null && fast.next != null) { fast = fast.next.next; slow = slow.next; if(fast == slow) { break; } } if (fast == null || fast.next == null) { return null; } slow = l.head; while(fast != slow) { fast = fast.next; slow = slow.next; } return fast; } public static void main (String[] args) { int len = 0; int loop_i = 0; var l = new LinkedList<Integer>(); try (Scanner scn = new Scanner(System.in)){ len = scn.nextInt(); loop_i = scn.nextInt(); var last = new Node<Integer>(len); l.head = last; for (int i = len-1; i > 0; i--) { var n = new Node<Integer>(i, l.head); l.head = n; if (i == loop_i) { //last.next = n; } } } System.out.print(l.head); var n = l.head.next; int charsUntilLoop = 1; int charsUntilEnd = 0; for (int i = 2; i <= len; i++) { System.out.print("->"); System.out.print(n); if (i <= loop_i) { charsUntilLoop += 2 + ((int)Math.floor(Math.log10(i)) + 1); } if (i > loop_i) { charsUntilEnd += 2 + ((int)(Math.log10(i)) + 1); } n = n.next; } int loopdig = ((int)Math.floor(Math.log10(loop_i)) + 1); int lenddig = ((int)Math.floor(Math.log10(len)) + 1); System.out.println("\n"+" ".repeat(charsUntilLoop - loopdig) + "^" + " ".repeat(charsUntilEnd - lenddig) + "|"); System.out.println(" ".repeat(charsUntilLoop - loopdig) + "⌎" + "-".repeat(charsUntilEnd - lenddig) + "⌏"); System.out.println(detect(l)); } }
[ "joao.gabrielaaj@gmail.com" ]
joao.gabrielaaj@gmail.com
e5ca155ae0e7bb6a7eafd5e56f0277166dd6817f
c35e45631d24498a4c83434d9ca03e864137225e
/src/test/java/Decrypt.java
40b4a37e7902fc05c083804277fbecaa0d9a84de
[]
no_license
jordanh97/cryptography
1e2598d8f3c5fe51497dcf1a757173434cece5c4
176637dedb27702db40ea8d271bb1a2e84bf6a55
refs/heads/master
2020-04-22T16:19:46.982804
2019-02-15T22:46:51
2019-02-15T22:46:51
170,504,282
0
1
null
2019-02-14T08:47:41
2019-02-13T12:27:47
Java
UTF-8
Java
false
false
978
java
public class Decrypt { private String input; public String basicDecrypt(String i) { input = i; String output = ""; int k = input.length(); int h = 0; do { char charValue = input.charAt(h); int newIntValue = (int) charValue - 3; char newCharValue = (char)newIntValue; output = new StringBuffer(output).insert(h, newCharValue).toString(); h++; }while (h < k); return output; } public String moderateDecrypt(String i) { input = i; String output = ""; int k = input.length(); int h = 0; do { char charValue = input.charAt(h); int newIntValue = (int) charValue - 72; int lastInt = newIntValue - h; char newCharValue = (char)lastInt; output = output + newCharValue; h++; }while (h < k); return output; } }
[ "47331061+jordanh97@users.noreply.github.com" ]
47331061+jordanh97@users.noreply.github.com
08645aa76f1e0c3d972340d6d2aeaf19ac802c30
be702c1cc5bf00b322daddb23476c500e973a193
/android/src/com/box/androidlib/DAO/SearchResult.java
8c6a6d9db3f615d4c31e691552882d37bf46fba1
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
appcelerator-archive/ti.box
1ce33ee6c44f96101454d5d4e8d74ca773f1cec2
39346bf7250ba445c6236c52795412441aa2bd62
refs/heads/master
2020-04-10T00:52:29.518780
2017-03-28T20:28:16
2017-03-28T20:28:16
22,700,963
1
1
null
2017-03-28T20:28:17
2014-08-06T22:55:54
Java
UTF-8
Java
false
false
1,579
java
/******************************************************************************* * Copyright 2011 Box.net. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.box.androidlib.DAO; import java.util.ArrayList; /** * Represents a the result of a search on Box. Contains the files and folders * returned. * * @author developers@box.net */ public class SearchResult extends DAO { /** * List of folders found in search. */ protected ArrayList<BoxFolder> mFolders = new ArrayList<BoxFolder>(); /** * List of files found in search. */ protected ArrayList<BoxFile> mFiles = new ArrayList<BoxFile>(); /** * Get list of folders found in search. * * @return list of folders */ public ArrayList<BoxFolder> getFolders() { return mFolders; } /** * Get list of files found in search. * * @return list of files */ public ArrayList<BoxFile> getFiles() { return mFiles; } }
[ "jon@local" ]
jon@local
4e2fc2824ba826f09ccb0680c8d35035f2452c8b
a78cbb3413a46c8b75ed2d313b46fdd76fff091f
/src/mobius.esc/escjava/tags/escjava-2-0a0/ESCTools/Javafe/java/javafe/util/LocationManagerCorrelatedReader.java
a73b1a9a0ee6d6865b4c63a6e0233eb7fd17cb1f
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
wellitongb/Mobius
806258d483bd9b893312d7565661dadbf3f92cda
4b16bae446ef5b91b65fd248a1d22ffd7db94771
refs/heads/master
2021-01-16T22:25:14.294886
2013-02-18T20:25:24
2013-02-18T20:25:24
null
0
0
null
null
null
null
UTF-8
Java
false
false
14,677
java
/* Copyright 2000, 2001, Compaq Computer Corporation */ package javafe.util; import javafe.genericfile.GenericFile; import java.util.Vector; import java.io.StringBufferInputStream; import java.io.IOException; /** * This <code>CorrelatedReader</code> class manages the allocation of * location numbers. */ public abstract class LocationManagerCorrelatedReader extends BufferedCorrelatedReader { /* ************************************************ * * * Class variables & constants: * * * * ************************************************/ /** * The next location to be allocated to a LocationManagerCorrelatedReader * instance. (The next instance's stream will have locations in a prefix of * [freeLoc, freeLoc+MAXFILESIZE).) <p> * * We do not use ints below STARTFREELOC to denote locations. If * freeLoc+MAXFILESIZE results in an overflow, then too many * LocationManagerCorrelatedReader instances have been created and an * assertion failure occurs. */ //@ invariant STARTFREELOC <= freeLoc; private static int freeLoc = STARTFREELOC; /** * A location is an integer that encodes file/line/column/offset * information. When a LocationManagerCorrelatedReader is created, * we allocate MAXFILESIZE locations for its stream. An assertion * failure will occur if a location is requested for a character * located at an offset greater than or equal to MAXFILESIZE. */ static final int MAXFILESIZE = 30000000; /** * Each LocationManagerCorrelatedReader has a "new line offset * array", or NLOA, that contains the offset of the beginning of * each line. This array allows us to map an offset to line or * column information. <p> * * NLOA is defined for indexes in [0..curLineNo). <p> * * If NLOA[i], i in [0..curLineNo), = j, then the characters at * offset j and j-1 were on different lines. Furthermore, either * (a) i=j=0, or * (b) i>0, j>0, and the character at offset j-1 is a newline. <p> * * Note: this means a line ends just *after* a newline, not before. <p> */ //@ invariant curLineNo <= NLOA.length; /*@ invariant (\forall int i; 0 <= i && i < curLineNo ==> 0 <= NLOA[i]); */ /*@ spec_public */ private /*@ non_null */ int[] NLOA; /** The default initial size to allocate an NLOA array */ //@ invariant NLOA_DEFAULT_SIZE <= NLOA.length; private static final int NLOA_DEFAULT_SIZE = 200; /** * This constructor allocates a range of location for use by the * CorrelatedReader. */ //@ ensures curNdx == 0; //@ ensures !marked; //@ ensures !isWholeFile; //@ ensures buf == null; LocationManagerCorrelatedReader() { // Allocate locations for us: super(/*minLoc*/ freeLoc, /*beforeBufLoc*/ freeLoc-1, /*maxLoc*/ freeLoc+MAXFILESIZE); freeLoc += MAXFILESIZE; if (freeLoc<0) { long limit = (1L<<32 - STARTFREELOC) / MAXFILESIZE; ErrorSet.fatal("javafe.util.LocationManagerCorrelatedReader " + "maximum # of files limit (~"+limit+") exceeded"); } this.NLOA = new int[NLOA_DEFAULT_SIZE]; this.NLOA[0] = 0; allCorrStreams.addElement(this); } /** * Closes us. No other I/O operations may be called on us after * we have been closed. */ public void close() { if (maxLoc == freeLoc) { maxLoc = beforeBufLoc + curNdx + 1; freeLoc = maxLoc; } super.close(); } /** Records a newline at the current location. */ //@ modifies NLOA; //@ ensures curLineNo < NLOA.length; //@ ensures 0 <= NLOA[curLineNo]; protected void recordNewLineLocation() { if (curLineNo == NLOA.length) { int[] new_NLOA = new int[ 2*NLOA.length ]; System.arraycopy( NLOA, 0, new_NLOA, 0, NLOA.length ); NLOA = new_NLOA; } //@ assert curLineNo < NLOA.length; NLOA[ curLineNo ] = beforeBufLoc + curNdx + 1 - minLoc; } /** * A static Vector containing all LocationManagerCorrelatedReader * instances, in the order they were allocated, which is used to * map a given location to a corresponding LocationManagerCorrelatedReader * instance. <p> * * A location's streamId is its index in allCorrStreams. See * locToStreamId(int) for the algorithm mapping locations to * streamId's. */ //@ invariant !allCorrStreams.containsNull; //@ invariant allCorrStreams.elementType == \type(LocationManagerCorrelatedReader); /*@spec_public*/ private static /*@non_null*/ Vector allCorrStreams = new Vector(); /** * Creates and returns a vector that associates file numbers * to file names. */ //@ ensures \result != null; //@ ensures \result.elementType == \type(String); //@ ensures !\result.containsNull; public static Vector fileNumbersToNames() { Vector v = new Vector(); //@ set v.elementType = \type(String); //@ set v.containsNull = false; for(int i = 0; i < allCorrStreams.size(); i++) { LocationManagerCorrelatedReader s = getCorrStreamAt(i); v.addElement(s.getFile().getHumanName()); } return v; } /* ************************************************ * * * Inspecting Locations: * * * * * * These methods are mostly package-protected. * * The Location class provides access to these * * methods. * * * * ************************************************/ /** * Return the LocationManagerCorrelatedReader associated with * streamId i. <p> * * If i is not a valid streamId (aka, i not in * [0, allCorrStreams.size()) ), an assertion failure occurs. <p> */ //@ requires 0 <= i && i < allCorrStreams.elementCount; //@ ensures \result != null; protected static LocationManagerCorrelatedReader getCorrStreamAt(int i) { try { LocationManagerCorrelatedReader c = (LocationManagerCorrelatedReader)allCorrStreams.elementAt(i); return c; } catch (ArrayIndexOutOfBoundsException e) { Assert.precondition("invalid streamId " + i); return null; // dummy return } } /** * Attempt to return the valid regular location associated with a * given streamId, line #, and col #. <p> * * If there is no such location currently in existence, an * assertion failure will occur. <p> * * This method is intended mainly for debugging purposes. <p> */ //@ requires 0 <= streamId && streamId < allCorrStreams.elementCount; //@ requires 0 < line; //@ requires 0 <= col; //@ ensures \result != Location.NULL; static int makeLocation(int streamId, int line, int col) { LocationManagerCorrelatedReader s = getCorrStreamAt(streamId); if (s.isWholeFile) { Assert.fail("streamId denotes a whole file location"); } if (line>s.curLineNo) { Assert.fail("line number too large"); } if ((line==s.curLineNo && col+1>s.curNdx) || (line!=s.curLineNo && col+1>(s.NLOA[line]-s.NLOA[line-1]))) { Assert.fail("column number too large"); } int loc; if (line == 0) { loc = s.minLoc + col; } else { loc = s.minLoc + s.NLOA[line-1] + col; } // Verify we got the right location: if (locToStreamId(loc)!=streamId || locToColumn(loc) != col || locToLineNumber(loc) != line) { Assert.fail("bug found in makeLocation"); } return loc; } /** * Return the LocationManager CorrelatedReader instance associated * with location loc. <p> * * Requires that loc be a valid location. <p> */ //@ requires loc != Location.NULL; //@ ensures \result != null; //@ ensures \result.minLoc <= loc && loc <= \result.beforeBufLoc + \result.curNdx; protected static LocationManagerCorrelatedReader locToStream(int loc) { int i = locToStreamId(loc); LocationManagerCorrelatedReader s = getCorrStreamAt(i); Assert.notFalse(s.minLoc <= loc && loc <= s.beforeBufLoc + s.curNdx); //@ nowarn Pre return s; } /** * Returns the internal stream ID used for the stream associated * with location <code>loc</code>. * * Requires that loc be a valid location. <p> */ //@ requires loc != Location.NULL; //@ ensures 0 <= \result && \result < allCorrStreams.elementCount; static int locToStreamId(int loc) { // This is somewhat inefficient: for(int i = 0; i < allCorrStreams.size(); i++) { LocationManagerCorrelatedReader s = getCorrStreamAt(i); if (s.minLoc <= loc && loc <= s.beforeBufLoc + s.curNdx) { return i; } } // Bad location: Assert.precondition("Bad location "+loc); return -1; // dummy return } /** * Is a location a whole file location? * * Requires that loc be a valid location or NULL. <p> */ static boolean isWholeFileLoc(int loc) { if (loc == Location.NULL) { return false; } return locToStream(loc).isWholeFile; } /** * Returns the offset associated with location * <code>loc</code>. <p> * * Requires that loc be a valid regular location (regular ==> not * a whole-file location). <p> * * Note: offsets start with 1 (a la emacs). <p> */ //@ requires loc != Location.NULL; static int locToOffset(int loc) { if (isWholeFileLoc(loc)) { Assert.precondition("locToOffset passed a whole-file location"); } LocationManagerCorrelatedReader s = locToStream(loc); return loc - s.minLoc + 1; } /** * Returns the line number associated with location * <code>loc</code>. <p> * * Requires that loc be a valid regular location (regular ==> not * a whole-file location). <p> * * Note: line numbers start with 1 (a la emacs). <p> */ //@ requires loc != Location.NULL; //@ ensures 1 <= \result; static int locToLineNumber(int loc) { return locToColOrLine(loc, false); } /** * Returns the column number associated with location * <code>loc</code>. <p> * * Requires that loc be a valid regular location (regular ==> not * a whole-file location). <p> * * Note: column numbers start with 0. <p> */ //@ requires loc != Location.NULL; //@ ensures 0 <= \result; static int locToColumn(int loc) { return locToColOrLine(loc, true); } /** * Returns the column number (if wantColumn) or line number (if * !wantColumn) associated with location <code>loc</code>. <p> * * Requires that loc be a valid regular location (regular ==> not * a whole-file location). <p> * * Note: line numbers start with 1 (a la emacs), while column * numbers start with 0. <p> */ //@ requires loc != Location.NULL; //@ ensures 0 <= \result; //@ ensures !wantColumn ==> 1 <= \result; private static int locToColOrLine(int loc, boolean wantColumn) { LocationManagerCorrelatedReader s = locToStream(loc); int offset = loc - s.minLoc; for (int i = s.curLineNo-1; /* Have sentinel s.NLOA[0]==0 */; i--) { if( s.NLOA[i] <= offset ) { // Line i+1 begins before offset return wantColumn ? offset-s.NLOA[i] : i+1; } } } /** * Returns the GenericFile associated with stream id * <code>id</code>, where <code>id</code> has previously been * returned by <code>locToStreamId</code>. * * Requires that id be a valid streamId. */ //@ requires 0 <= id && id < allCorrStreams.elementCount; static GenericFile streamIdToFile(int id) { return getCorrStreamAt(id).getFile(); } /** * Returns the GenericFile associated with location * <code>loc</code>. <p> * * Requires that id be a valid streamId of a FileCorrelatedReader. <p> */ //@ requires loc != Location.NULL; //@ ensures \result != null; static GenericFile locToFile(int loc) { return locToStream(loc).getFile(); } /* ************************************************ * * * Whole-file correlated readers: * * * * ************************************************/ /** * Are all of our locations whole-file locations? */ /*@spec_public*/ protected boolean isWholeFile = false; //@ invariant isWholeFile ==> buf==null; /* ************************************************ * * * Stuff related to counting lines: * * * * ************************************************/ /** * The total # of lines that have been read so far by all * FileCorrelatedReaders. <p> * * This is not used internally, and is kept only for interested * clients. */ public static int totalLinesRead = 0; /** * The current line number; that is, the number of <newlines> * we've read from our stream so far + 1. <p> * * (Line numbers are counted from 1 not 0.) <p> */ //@ invariant 1 <= curLineNo; protected int curLineNo = 1; /** * The value of curLineNo at the mark point (if marked is true). <p> * * The justification for why it's okay to place the following invariant * in this class, even though <code>marked</code> is declared in the * superclass, is that this class overrides the methods that set * <code>marked</code> to <code>true</code>. (But there's no mechanical * check that this justification is upheld, so it needs to be upheld * manually.) */ //@ invariant marked ==> 0 < markLineNo && markLineNo <= curLineNo; private int markLineNo /*@ readable_if marked */; public void mark() { markLineNo = curLineNo; super.mark(); } public void reset() throws IOException { curLineNo = markLineNo; super.reset(); } /* ************************************************ * * * Misc: * * * * ************************************************/ public String toString() { StringBuffer r = new StringBuffer("LocationManagerCorrelatedReader: \""); r.append(getFile().getHumanName()); r.append("\" "); if (buf == null) { r.append("closed"); } else { r.append("buf["); for(int i=curNdx; i<endBufNdx; i++ ) r.append( ""+(char)buf[i] ); r.append("] "+marked); } return r.toString(); } }
[ "nobody@c6399e9c-662f-4285-9817-23cccad57800" ]
nobody@c6399e9c-662f-4285-9817-23cccad57800
726dfd010cd809f469c67e64780eb96b9ac8586b
b2f07f3e27b2162b5ee6896814f96c59c2c17405
/com/sun/org/apache/bcel/internal/generic/LDC_W.java
83189d1e33b0a95ece772d2aa7f29e92bceadbbd
[]
no_license
weiju-xi/RT-JAR-CODE
e33d4ccd9306d9e63029ddb0c145e620921d2dbd
d5b2590518ffb83596a3aa3849249cf871ab6d4e
refs/heads/master
2021-09-08T02:36:06.675911
2018-03-06T05:27:49
2018-03-06T05:27:49
null
0
0
null
null
null
null
UTF-8
Java
false
false
796
java
/* */ package com.sun.org.apache.bcel.internal.generic; /* */ /* */ import com.sun.org.apache.bcel.internal.util.ByteSequence; /* */ import java.io.IOException; /* */ /* */ public class LDC_W extends LDC /* */ { /* */ LDC_W() /* */ { /* */ } /* */ /* */ public LDC_W(int index) /* */ { /* 78 */ super(index); /* */ } /* */ /* */ protected void initFromFile(ByteSequence bytes, boolean wide) /* */ throws IOException /* */ { /* 87 */ setIndex(bytes.readUnsignedShort()); /* */ /* 89 */ this.opcode = 19; /* */ } /* */ } /* Location: C:\Program Files\Java\jdk1.7.0_79\jre\lib\rt.jar * Qualified Name: com.sun.org.apache.bcel.internal.generic.LDC_W * JD-Core Version: 0.6.2 */
[ "yuexiahandao@gmail.com" ]
yuexiahandao@gmail.com
e627dd18b38e1e4017e86f2f133d8c92c5afa93d
4b15f864ccd6e946902a7eb88540c4bf6e7705ca
/src/main/java/org/javaboy/vhr/model/Employee.java
e50ac81978d97335fa9e685cd0a59c9738a083c6
[]
no_license
shiguangming2/vhr-server
ac3645f64acb717d72770305b2c46b4e6681cf23
5f6bb0000e1bdfbb823c02e1214d9329e42a833e
refs/heads/master
2022-07-18T00:52:47.216183
2020-01-05T14:48:05
2020-01-05T14:48:05
231,927,259
1
0
null
2022-06-21T02:34:51
2020-01-05T14:11:24
Java
UTF-8
Java
false
false
6,024
java
package org.javaboy.vhr.model; import java.util.Date; public class Employee { private Integer id; private String name; private String gender; private Date birthday; private String idcard; private String wedlock; private Integer nationid; private String nativeplace; private Integer politicid; private String email; private String phone; private String address; private Integer departmentid; private Integer joblevelid; private Integer posid; private String engageform; private String tiptopdegree; private String specialty; private String school; private Date begindate; private String workstate; private String workid; private Double contractterm; private Date conversiontime; private Date notworkdate; private Date begincontract; private Date endcontract; private Integer workage; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name == null ? null : name.trim(); } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender == null ? null : gender.trim(); } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public String getIdcard() { return idcard; } public void setIdcard(String idcard) { this.idcard = idcard == null ? null : idcard.trim(); } public String getWedlock() { return wedlock; } public void setWedlock(String wedlock) { this.wedlock = wedlock == null ? null : wedlock.trim(); } public Integer getNationid() { return nationid; } public void setNationid(Integer nationid) { this.nationid = nationid; } public String getNativeplace() { return nativeplace; } public void setNativeplace(String nativeplace) { this.nativeplace = nativeplace == null ? null : nativeplace.trim(); } public Integer getPoliticid() { return politicid; } public void setPoliticid(Integer politicid) { this.politicid = politicid; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email == null ? null : email.trim(); } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone == null ? null : phone.trim(); } public String getAddress() { return address; } public void setAddress(String address) { this.address = address == null ? null : address.trim(); } public Integer getDepartmentid() { return departmentid; } public void setDepartmentid(Integer departmentid) { this.departmentid = departmentid; } public Integer getJoblevelid() { return joblevelid; } public void setJoblevelid(Integer joblevelid) { this.joblevelid = joblevelid; } public Integer getPosid() { return posid; } public void setPosid(Integer posid) { this.posid = posid; } public String getEngageform() { return engageform; } public void setEngageform(String engageform) { this.engageform = engageform == null ? null : engageform.trim(); } public String getTiptopdegree() { return tiptopdegree; } public void setTiptopdegree(String tiptopdegree) { this.tiptopdegree = tiptopdegree == null ? null : tiptopdegree.trim(); } public String getSpecialty() { return specialty; } public void setSpecialty(String specialty) { this.specialty = specialty == null ? null : specialty.trim(); } public String getSchool() { return school; } public void setSchool(String school) { this.school = school == null ? null : school.trim(); } public Date getBegindate() { return begindate; } public void setBegindate(Date begindate) { this.begindate = begindate; } public String getWorkstate() { return workstate; } public void setWorkstate(String workstate) { this.workstate = workstate == null ? null : workstate.trim(); } public String getWorkid() { return workid; } public void setWorkid(String workid) { this.workid = workid == null ? null : workid.trim(); } public Double getContractterm() { return contractterm; } public void setContractterm(Double contractterm) { this.contractterm = contractterm; } public Date getConversiontime() { return conversiontime; } public void setConversiontime(Date conversiontime) { this.conversiontime = conversiontime; } public Date getNotworkdate() { return notworkdate; } public void setNotworkdate(Date notworkdate) { this.notworkdate = notworkdate; } public Date getBegincontract() { return begincontract; } public void setBegincontract(Date begincontract) { this.begincontract = begincontract; } public Date getEndcontract() { return endcontract; } public void setEndcontract(Date endcontract) { this.endcontract = endcontract; } public Integer getWorkage() { return workage; } public void setWorkage(Integer workage) { this.workage = workage; } }
[ "2357484843@qq.com" ]
2357484843@qq.com
ffa4f995b88019f907b677f98ab45215b6a15f34
48a82e5cb4629e2d074d3aaf4a28e4791895f7a0
/app/src/main/java/com/example/jandroid/tourguide/Place.java
764a802dac4f8c7f9bb7e4d87e5be26aaeceba6f
[]
no_license
IoannisK97/Tourguide
a1652c6443156f17847043cf973621f16e9d16b2
3ceb5721c8f67da91b56bba1916be38327af1f48
refs/heads/main
2023-06-16T05:55:24.638659
2021-07-15T09:51:40
2021-07-15T09:51:40
386,240,465
0
0
null
null
null
null
UTF-8
Java
false
false
1,248
java
package com.example.jandroid.tourguide; import android.graphics.drawable.Drawable; public class Place { private String name; private int image; private String telNumber=NOT_PROVIDED; private String openHours=NOT_PROVIDED; private static final String NOT_PROVIDED="not provided"; public Place (String pName,int pImage){ name=pName; image=pImage; } public Place (String pName,int pImage,String pTelNumber,String pOpenHours){ name=pName; image=pImage; telNumber=pTelNumber; openHours=pOpenHours; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getImage() { return image; } public void setImage(int image) { this.image = image; } public String getTelNumber() { return telNumber; } public void setTelNumber(String telNumber) { this.telNumber = telNumber; } public String getOpenHours() { return openHours; } public void setOpenHours(String openHours) { this.openHours = openHours; } public Boolean hasTelAndHours(){ return telNumber!=NOT_PROVIDED; } }
[ "ioannis@windowslive.com" ]
ioannis@windowslive.com
e090ebfc45d61be32fe0228de8e67e5a3ffc8f17
ab4fd2cdce015e0b443b66f949c6dfb741bf61c9
/src/main/java/com/sun/org/apache/xerces/internal/xs/XSAttributeGroupDefinition.java
93d786a1425f6a8cee0e6e7582636fcba5ff9fa3
[]
no_license
lihome/jre
5964771e9e3ae7375fa697b8dfcd19656e008160
4fc2a1928f1de6af00ab6f7b0679db073fe0d054
refs/heads/master
2023-05-28T12:13:23.010031
2023-05-10T07:30:15
2023-05-10T07:30:15
116,901,440
0
0
null
2018-11-15T09:49:34
2018-01-10T03:13:15
Java
UTF-8
Java
false
false
1,781
java
/* * Copyright (c) 2007, 2023, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */ /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.sun.org.apache.xerces.internal.xs; /** * This interface represents the Attribute Group Definition schema component. */ public interface XSAttributeGroupDefinition extends XSObject { /** * A set of [attribute uses] if it exists, otherwise an empty * <code>XSObjectList</code>. */ public XSObjectList getAttributeUses(); /** * A [wildcard] if it exists, otherwise <code>null</code>. */ public XSWildcard getAttributeWildcard(); /** * An annotation if it exists, otherwise <code>null</code>. If not null * then the first [annotation] from the sequence of annotations. */ public XSAnnotation getAnnotation(); /** * A sequence of [annotations] or an empty <code>XSObjectList</code>. */ public XSObjectList getAnnotations(); }
[ "lihome.jia@gmail.com" ]
lihome.jia@gmail.com
8c5dc15346d5ef049efe4c9a5ba443f16bc8aa06
fa73d9ec5adfd4776ae5c582a1b1d3784cb66f60
/src/com/company/Main.java
490b7cbded0f482b2c7429a2685dc057e81edb44
[]
no_license
Deadpurecrock/Work5
c0afed638972890522b01cc770d01b7045a849de
7e5d8496720e99a21207fe7bb7befa122fa95b6b
refs/heads/master
2023-08-22T09:53:11.388013
2021-10-07T20:03:51
2021-10-07T20:03:51
414,741,590
0
0
null
null
null
null
UTF-8
Java
false
false
295
java
package com.company; import java.util.Scanner; public class Main { public static void main(String[] args) { Task16 task16 = new Task16(); task16.Count(); Task2 task2 = new Task2(); task2.Go(); Task1 task1 = new Task1(); task1.Execute(); } }
[ "milovanov.1243@gmail.com" ]
milovanov.1243@gmail.com
fcb60a1b1c4ebbac7ebc9eef20133028335d71d7
b0c7501f1fd6f29ae2420e1898d011d06b9ce86a
/app/src/main/java/com/wust/newsmartschool/ui/SchoolActivity.java
94f00184d4325851d20fe23d4199ce42541a186f
[]
no_license
lwz0208/NewSmartSchool
d4d3b9a81d958cd12c75df0c36816412e5e1d9ac
4e237b2878a028c4cd51d4a855332293de98f49b
refs/heads/master
2021-09-22T22:36:11.479861
2017-04-17T09:14:35
2017-04-17T09:14:42
124,881,243
0
0
null
null
null
null
UTF-8
Java
false
false
2,746
java
package com.wust.newsmartschool.ui; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.Window; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.wust.newsmartschool.R; import com.wust.newsmartschool.utils.URL_UNIVERSAL; import com.zhy.http.okhttp.OkHttpUtils; import com.zhy.http.okhttp.callback.StringCallback; import okhttp3.Call; import okhttp3.MediaType; public class SchoolActivity extends Activity { private TextView schoolTxt1; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.activity_school); ImageView backImageView = (ImageView) findViewById(R.id.back); backImageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); schoolTxt1 = (TextView) findViewById(R.id.shooltxt1); initContent(); } private void initContent() { JSONObject jsonObject = new JSONObject(); OkHttpUtils.postString().url(URL_UNIVERSAL.URL_SCHOOL_INTRODUCTION).content(jsonObject.toJSONString()) .mediaType(MediaType.parse("application/json")).build() .execute(new StringCallback() { @Override public void onError(Call call, Exception e) { Log.i("NewsResult", "校园简介接口访问失败:" + call + "---" + e); Toast.makeText(SchoolActivity.this, "网络开小差了哦", Toast.LENGTH_SHORT).show(); } @Override public void onResponse(String response) { Log.i("NewsResult", "校园简介接口访问成功:" + response); JSONObject jsonObject = JSON.parseObject(response); if(jsonObject.getIntValue("code") == 1) { schoolTxt1.setText(jsonObject.getString("data")); } else if(jsonObject.getIntValue("code") == 0) { Toast.makeText(SchoolActivity.this, "暂时没有数据哦", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(SchoolActivity.this, "服务器异常...", Toast.LENGTH_SHORT).show(); } } }); } }
[ "158956573@qq.com" ]
158956573@qq.com
c91e8ca94ff75f49db31b1613400e76fc1694d68
c4117591b2e53d07406355e23f45d955f8feaa4d
/cm-service/src/main/java/cn/eatammy/cm/service/business/IBackIndentService.java
a68f5786476d41e5a2a21103fa591bfcf7f0c02d
[]
no_license
eatammy/cm-platform
ad9b49460e3a60d2a8f2b4d034f6b9b6e8a67a11
c3465bf19f31f70c43a2d915f5d98a4c2cbcb2f6
refs/heads/master
2021-01-17T21:19:48.173749
2017-03-18T15:54:12
2017-03-18T15:54:12
53,736,157
1
1
null
2016-03-12T14:38:10
2016-03-12T14:38:09
null
UTF-8
Java
false
false
1,368
java
/* {***************************************************************************** { 吃咩主平台 v1.0 { 版权信息 (c) 2005-2016 广东全通教育股份有限公司. 保留所有权利. { 创建人: 郭旭辉 { 审查人: { 模块:退单 { 功能描述: { { --------------------------------------------------------------------------- { 维护历史: { 日期 维护人 维护类型 { --------------------------------------------------------------------------- { 2016-03-23 郭旭辉 新建 { { --------------------------------------------------------------------------- { 注:本模块代码由codgen代码生成工具辅助生成 http://www.oschina.net/p/codgen {***************************************************************************** */ package cn.eatammy.cm.service.business; import cn.eatammy.common.domain.BaseDomain; import cn.eatammy.cm.dao.ICMBaseDAO; import cn.eatammy.cm.service.ICMBaseService; import cn.eatammy.common.service.IPageService; /** * 《退单》 业务逻辑服务接口 * @author 郭旭辉 * */ public interface IBackIndentService<D extends ICMBaseDAO<T>, T extends BaseDomain> extends ICMBaseService<D, T>,IPageService<D, T>{ }
[ "simagle@163.com" ]
simagle@163.com